From df8ffb2a631f9f312f270cad620b6f49237cfeda Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:00:08 +0000 Subject: [PATCH 001/259] test: scan source directories recursively The source scanners in xtask (i18n coverage, scorecard) and engine/tests/it/prefs_usage.rs already walk src/ recursively. The i18n coverage scan also skips directories named tests, as the other two do, so test files moved to foo/tests/*.rs stay out of the key list. The report is unchanged on current main. --- xtask/src/i18n_coverage.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/xtask/src/i18n_coverage.rs b/xtask/src/i18n_coverage.rs index cd8fbbce63..2f340371ea 100644 --- a/xtask/src/i18n_coverage.rs +++ b/xtask/src/i18n_coverage.rs @@ -156,7 +156,9 @@ fn source_files(root: &Path) -> Result, String> { let entry = entry.map_err(|e| format!("{}: {e}", path.display()))?; let path = entry.path(); if path.is_dir() { - stack.push(path); + if path.file_name().is_some_and(|name| name != "tests") { + stack.push(path); + } } else if path.extension().and_then(|ext| ext.to_str()) == Some("rs") { let stem = path.file_stem().and_then(|name| name.to_str()).unwrap_or_default(); if stem == "tests" || stem.ends_with("_tests") { From 6d0692ce53d4a3ce7057863686f78916dbfdc5e0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:15:07 +0000 Subject: [PATCH 002/259] refactor(algo): move src/segment/mod.rs to src/segment.rs --- crates/algo/src/{segment/mod.rs => segment.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename crates/algo/src/{segment/mod.rs => segment.rs} (100%) diff --git a/crates/algo/src/segment/mod.rs b/crates/algo/src/segment.rs similarity index 100% rename from crates/algo/src/segment/mod.rs rename to crates/algo/src/segment.rs From 24a11846e6f8fc3ded8301b38c121e65f93bda3a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:15:07 +0000 Subject: [PATCH 003/259] refactor(codecs): move src/codecs/vp8/mod.rs to src/codecs/vp8.rs --- crates/codecs/src/codecs/{vp8/mod.rs => vp8.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename crates/codecs/src/codecs/{vp8/mod.rs => vp8.rs} (100%) diff --git a/crates/codecs/src/codecs/vp8/mod.rs b/crates/codecs/src/codecs/vp8.rs similarity index 100% rename from crates/codecs/src/codecs/vp8/mod.rs rename to crates/codecs/src/codecs/vp8.rs From ea6268d736cb87b978b4fa7504cb23c99502b554 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:15:07 +0000 Subject: [PATCH 004/259] refactor(codecs): move src/codecs/mod.rs to src/codecs.rs --- crates/codecs/src/{codecs/mod.rs => codecs.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename crates/codecs/src/{codecs/mod.rs => codecs.rs} (100%) diff --git a/crates/codecs/src/codecs/mod.rs b/crates/codecs/src/codecs.rs similarity index 100% rename from crates/codecs/src/codecs/mod.rs rename to crates/codecs/src/codecs.rs From 640d35c19ab5ac44f0824e5952cf1cfd52efc4b2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:15:08 +0000 Subject: [PATCH 005/259] refactor(engine): move src/presets/mod.rs to src/presets.rs --- crates/engine/src/{presets/mod.rs => presets.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename crates/engine/src/{presets/mod.rs => presets.rs} (100%) diff --git a/crates/engine/src/presets/mod.rs b/crates/engine/src/presets.rs similarity index 100% rename from crates/engine/src/presets/mod.rs rename to crates/engine/src/presets.rs From b7b113352ecb8dc69ab70286b5e4b44b4db9ff49 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:15:08 +0000 Subject: [PATCH 006/259] refactor(ui-egui): move src/i18n/mod.rs to src/i18n.rs --- crates/ui-egui/src/{i18n/mod.rs => i18n.rs} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename crates/ui-egui/src/{i18n/mod.rs => i18n.rs} (100%) diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n.rs similarity index 100% rename from crates/ui-egui/src/i18n/mod.rs rename to crates/ui-egui/src/i18n.rs From 25e8edb784341337681f018514fc3d5b5226df12 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:15:28 +0000 Subject: [PATCH 007/259] refactor(xtask): read the i18n registry from i18n.rs --- docs/development.md | 2 +- docs/localization-zh-hans.md | 2 +- xtask/src/i18n_coverage.rs | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/development.md b/docs/development.md index 1a39c103e7..337dcbaaf0 100644 --- a/docs/development.md +++ b/docs/development.md @@ -344,7 +344,7 @@ the live command registry (`menus::is_live`) and rewrites [`docs/parity-checklis `parity::tests::parity_does_not_regress` fails if the live count drops below `parity::FLOOR`. `cargo xtask i18n-coverage` prints the UI translation coverage for each language in the -`crates/ui-egui/src/i18n/mod.rs` registry, in stable language-code order. Its English-key set is +`crates/ui-egui/src/i18n.rs` registry, in stable language-code order. Its English-key set is derived from UI `tl!` literals, the menu catalog and UI command table, and menu command labels in the engine source. Catalog rows are validated for malformed and duplicate keys; unused legacy translations do not affect the denominator. Unregistered locale TSV files are ignored. After the diff --git a/docs/localization-zh-hans.md b/docs/localization-zh-hans.md index 9a84589589..fec786ab92 100644 --- a/docs/localization-zh-hans.md +++ b/docs/localization-zh-hans.md @@ -27,7 +27,7 @@ language manually there. - `crates/ui-egui/src/i18n/zh-hans.tsv` contains the translations, independent of the lookup implementation. Its UTF-8 columns are `contextsourcetranslation`. -- `crates/ui-egui/src/i18n/mod.rs` registers `zh-hans` with one plural form and +- `crates/ui-egui/src/i18n.rs` registers `zh-hans` with one plural form and `complete_menus: true`. `cargo xtask i18n-coverage` lists any menu string, `tl!` literal or other source key the catalog lacks; those show in English. - Shortcut templates retain `{key}` so the shell supplies the correct key for diff --git a/xtask/src/i18n_coverage.rs b/xtask/src/i18n_coverage.rs index 2f340371ea..e8c221905f 100644 --- a/xtask/src/i18n_coverage.rs +++ b/xtask/src/i18n_coverage.rs @@ -16,7 +16,7 @@ struct Language { pub fn run(root: &Path) -> Result<(), String> { let i18n_dir = root.join("crates/ui-egui/src/i18n"); - let registry_path = i18n_dir.join("mod.rs"); + let registry_path = root.join("crates/ui-egui/src/i18n.rs"); let registry = fs::read_to_string(®istry_path).map_err(|e| format!("{}: {e}", registry_path.display()))?; let languages = registered_languages(®istry)?; @@ -176,7 +176,7 @@ fn source_files(root: &Path) -> Result, String> { fn tl_keys(sources: &[(PathBuf, String)]) -> BTreeSet { let mut keys = BTreeSet::new(); for (path, source) in sources { - if path.ends_with("i18n/mod.rs") { + if path.ends_with("ui-egui/src/i18n.rs") { continue; } let code = before_test_module(source); @@ -202,7 +202,7 @@ fn tl_keys(sources: &[(PathBuf, String)]) -> BTreeSet { fn plural_keys(sources: &[(PathBuf, String)]) -> BTreeSet { let mut keys = BTreeSet::new(); for (path, source) in sources { - if path.ends_with("i18n/mod.rs") { + if path.ends_with("ui-egui/src/i18n.rs") { continue; } let code = before_test_module(source); From 893acab66b89b2b3844750e7a404452fd1f4e2c8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:15:45 +0000 Subject: [PATCH 008/259] refactor(io): move smart_map tests to src/smart_map/tests.rs --- crates/io/src/smart_map.rs | 2321 +----------------------------- crates/io/src/smart_map/tests.rs | 2318 +++++++++++++++++++++++++++++ 2 files changed, 2319 insertions(+), 2320 deletions(-) create mode 100644 crates/io/src/smart_map/tests.rs diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs index fcc9eec3f9..5d56c55ae8 100644 --- a/crates/io/src/smart_map.rs +++ b/crates/io/src/smart_map.rs @@ -1748,2323 +1748,4 @@ pub fn uuid_from(seed: &[u8]) -> String { } #[cfg(test)] -mod tests { - use super::*; - - fn count(hay: &[u8], needle: &[u8]) -> usize { - hay.windows(needle.len()).filter(|w| *w == needle).count() - } - - /// A freshly built placed layer writes `warp` (key and class) as a length-4 string, as - /// Photoshop does; the code form is a different key to Photoshop. - #[test] - fn fresh_placed_warp_is_a_string_id() { - let spec = - PlacedSpec { idnt: "id", placed: "id", transform: Affine::IDENTITY, perspective: None, size: (10.0, 10.0), dpi: 72.0, warp: None, filter_fx: None }; - let mut warnings = Vec::new(); - let sold = sold_bytes(None, &spec, &mut warnings); - let plld = plld_bytes(&spec, &mut warnings); - // `SoLd`: the `warp` key and the warp descriptor's class; `PlLd`: the descriptor's class. - for (bytes, n) in [(&sold, 2), (&plld, 1)] { - assert_eq!(count(bytes, b"\0\0\0\x04warp"), n); - assert_eq!(count(bytes, b"\0\0\0\0warp"), 0); - } - let d = sold_descriptor(&sold).unwrap(); - assert!(matches!(d.get("warp"), Some(Value::Descriptor(w)) if w.class_id == Id::Str(b"warp".to_vec()))); - } - - fn sf(command: &str, params: J) -> SmartFilter { - SmartFilter { command: command.into(), params, blend: BlendMode::Normal, opacity: 1.0, visible: true } - } - - #[test] - fn modelled_filters_round_trip() { - let filters = vec![ - sf("filter.blur.gaussianBlur", json!({"radius": 4.0})), - sf("filter.blur.boxBlur", json!({"radius": 5.0})), - sf("filter.blur.motionBlur", json!({"angle": -20, "distance": 10.0})), - sf("filter.blur.surfaceBlur", json!({"radius": 12.0, "threshold": 40})), - sf("filter.blur.smartBlur", json!({"radius": 5.0, "threshold": 25.0, "quality": "high", "mode": "normal"})), - sf("filter.blur.smartBlur", json!({"radius": 3.0, "threshold": 30.0, "quality": "medium", "mode": "overlayEdge"})), - sf("filter.blur.smartBlur", json!({"radius": 0.5, "threshold": 0.1, "quality": "low", "mode": "edgeOnly"})), - sf("filter.blur.radialBlur", json!({"amount": 10, "method": "spin", "quality": "draft"})), - sf("filter.blur.radialBlur", json!({"amount": 20, "method": "zoom", "quality": "good"})), - sf("filter.blur.radialBlur", json!({"amount": 100, "method": "spin", "quality": "best"})), - sf("filter.sharpen.unsharpMask", json!({"amount": 150.0, "radius": 2.0, "threshold": 0})), - sf("filter.noise.addNoise", json!({"amount": 12.0, "distribution": "uniform", "monochromatic": false, "seed": 1234})), - sf("filter.noise.median", json!({"radius": 3.0})), - sf("filter.other.highPass", json!({"radius": 3.0})), - sf("filter.other.maximum", json!({"radius": 2.0})), - sf("filter.other.minimum", json!({"radius": 2.0})), - sf("filter.pixelate.mosaic", json!({"cellSize": 8.0})), - sf("filter.pixelate.mezzotint", json!({"type": "mediumStrokes"})), - sf("filter.pixelate.colorHalftone", json!({"maxRadius": 6, "channel1": 10, "channel2": 20, "channel3": 30, "channel4": 40})), - sf("filter.stylize.emboss", json!({"angle": 135, "height": 3, "amount": 100})), - sf("filter.sharpen.smartSharpen", json!({"amount": 120.0, "radius": 2.5, "reduceNoise": 5.0})), - sf("filter.noise.dustAndScratches", json!({"radius": 4, "threshold": 20})), - sf("filter.stylize.diffuse", json!({"mode": "normal"})), - sf("filter.stylize.diffuse", json!({"mode": "darkenOnly"})), - sf("filter.stylize.diffuse", json!({"mode": "lightenOnly"})), - sf("filter.stylize.diffuse", json!({"mode": "anisotropic"})), - sf("filter.stylize.traceContour", json!({"level": 60, "edge": "lower"})), - sf("filter.stylize.traceContour", json!({"level": 128, "edge": "upper"})), - sf("filter.stylize.traceContour", json!({"level": 0, "edge": "upper"})), - sf("filter.stylize.traceContour", json!({"level": 255, "edge": "lower"})), - sf("filter.pixelate.crystallize", json!({"cellSize": 10})), - sf("filter.pixelate.crystallize", json!({"cellSize": 3})), - sf("filter.pixelate.crystallize", json!({"cellSize": 300})), - sf("filter.pixelate.pointillize", json!({"cellSize": 7, "background": [1.0, 1.0, 1.0, 1.0]})), - sf("filter.pixelate.pointillize", json!({"cellSize": 300, "background": [0.0, 0.5, 1.0, 1.0]})), - sf("filter.other.offset", json!({"horizontal": 12, "vertical": -7, "undefinedAreas": "transparent"})), - sf("filter.other.custom", json!({"kernel": SHARPEN, "scale": 1, "offset": 0})), - sf("image.adjustments.levels", json!({"inBlack": 20, "inWhite": 220, "gamma": 1.4, "red": {"inBlack": 0, "inWhite": 255, "gamma": 0.8}})), - sf("image.adjustments.curves", json!({"points": [[0.0, 0.0], [64.0, 40.0], [255.0, 255.0]], "blue": [[0.0, 20.0], [255.0, 235.0]]})), - sf("image.adjustments.shadowsHighlights", json!({})), - sf("filter.sharpen.sharpen", json!({})), - // Photoshop stores Dust & Scratches' radius in whole pixels (a `long`). - sf("filter.noise.dustAndScratches", json!({"radius": 4, "threshold": 12})), - sf( - "image.adjustments.hueSaturation", - json!({"colorize": false, "hue": 10, "saturation": -20, "lightness": 5, "reds": {"hue": 5, "saturation": 0, "lightness": -3, "range": [315, 345, 15, 45]}}), - ), - // A pencil-drawn curve: 256 output levels (`Mpng`). - sf("image.adjustments.curves", json!({"pencil": true, "points": (0..256).rev().collect::>()})), - sf("filter.distort.pinch", json!({"amount": -28})), - sf("filter.distort.polarCoordinates", json!({"mode": "rectangularToPolar"})), - sf("filter.distort.ripple", json!({"amount": 250, "size": "small"})), - sf("filter.distort.spherize", json!({"amount": 60, "mode": "verticalOnly"})), - sf("filter.distort.twirl", json!({"angle": -355})), - sf( - "filter.distort.wave", - json!({"type": "square", "generators": 3, "wavelengthMin": 20, "wavelengthMax": 90, "amplitudeMin": 4, "amplitudeMax": 30, - "undefinedAreas": "repeat", "seed": 4_000_000_000u32}), - ), - sf("filter.distort.zigZag", json!({"amount": 30, "ridges": 7, "style": "aroundCenter"})), - sf("image.adjustments.invert", json!({})), - ]; - for mut f in filters.into_iter().chain(wind_extrude_tiles_settings()) { - f.blend = BlendMode::Overlay; - f.opacity = 0.75; - f.visible = false; - let d = item_for_filter(&f).unwrap(); - let bytes = d.to_bytes(); - let back = filter_from_item(&Descriptor::from_bytes(&bytes).unwrap()); - assert_eq!(back, f, "{}", f.command); - } - } - - /// The filters without options, their measured `filterID`s (as Photoshop wrote them). - const MEASURED_NO_OPTIONS: [(&str, i32); 11] = [ - ("filter.blur.blur", 1114403360), - ("filter.blur.blurMore", 1114403405), - ("filter.blur.average", 1098281575), - ("filter.noise.despeckle", 1148416099), - ("filter.stylize.findEdges", 1181639749), - ("filter.pixelate.facet", 1180922912), - ("filter.pixelate.fragment", 1181902701), - ("filter.sharpen.sharpen", 1399353968), - ("filter.sharpen.sharpenMore", 1399353933), - ("filter.sharpen.sharpenEdges", 1399353925), - ("filter.stylize.solarize", 1399616122), - ]; - - /// A filter without options as Photoshop saves it: `hasoptions` false, no `Fltr`, a localized - /// name and the current colours. - fn photoshop_no_options_item(name: &str, filter_id: Value) -> Descriptor { - let rgb = |r: f64, g: f64, b: f64| { - Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(r)).with("Grn ", Value::Double(g)).with("Bl ", Value::Double(b))) - }; - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul(name))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 60.0)).with("Md ", enumv("BlnM", "Mltp")))) - .with("enab", Value::Boolean(false)) - .with("hasoptions", Value::Boolean(false)) - .with("FrgC", rgb(167.0, 157.0, 147.0)) - .with("BckC", rgb(255.0, 255.0, 255.0)) - .with("filterID", filter_id) - } - - #[test] - fn filters_without_options_round_trip_in_the_measured_shape() { - let keys = ["Nm ", "blendOptions", "enab", "hasoptions", "FrgC", "BckC", "filterID"]; - for (command, id) in MEASURED_NO_OPTIONS { - let mut f = sf(command, json!({})); - f.blend = BlendMode::Overlay; - f.opacity = 0.75; - f.visible = false; - let d = item_for_filter(&f).unwrap(); - let got: Vec = d.items.iter().map(|(k, _)| String::from_utf8_lossy(k.as_bytes()).into_owned()).collect(); - assert_eq!(got, keys, "{command}"); - assert_eq!(d.get("hasoptions"), Some(&Value::Boolean(false)), "{command}"); - assert_eq!(d.get("filterID"), Some(&Value::Integer(id)), "{command}"); - let back = filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()); - assert_eq!(back, f, "{command}"); - // Keys an old record may carry have no effect on these filters: still written. - let extra = item_for_filter(&sf(command, json!({"radius": 3.0, "layer": "L"}))).unwrap(); - assert_eq!(extra.get("filterID"), Some(&Value::Integer(id)), "{command}"); - for p in [json!(null), json!("x"), json!([1, 2])] { - assert!(item_for_filter(&sf(command, p)).is_ok(), "{command}"); - } - } - } - - #[test] - fn photoshop_filters_without_options_open_editable() { - for (command, id) in MEASURED_NO_OPTIONS { - let item = photoshop_no_options_item("Weichzeichnen", Value::Integer(id)); - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!(f.command, command); - assert_eq!(f.params, json!({})); - assert_eq!((f.visible, f.blend), (false, BlendMode::Multiply)); - assert!((f.opacity - 0.6).abs() < 1e-6); - } - } - - #[test] - fn malformed_filters_without_options_are_kept_verbatim() { - let blur = code(b"Blr "); - let cases = [ - // An id no filter has, a missing id, ids of the wrong type. - photoshop_no_options_item("X", Value::Integer(code(b"Zzzz"))), - Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)), - photoshop_no_options_item("X", Value::Double(f64::from(blur))), - photoshop_no_options_item("X", Value::Double(f64::NAN)), - photoshop_no_options_item("X", Value::Text(UnicodeString::new_nul("Blr "))), - photoshop_no_options_item("X", Value::Integer(-1)), - // Settings we don't know of on a filter that has none. - photoshop_no_options_item("X", Value::Integer(blur)).with("Fltr", Value::Descriptor(Descriptor::new("Blr ").with("Amnt", Value::Integer(5)))), - // Settings that aren't a descriptor, on a filter that has none. - photoshop_no_options_item("X", Value::Integer(blur)).with("Fltr", Value::Integer(5)), - photoshop_no_options_item("X", Value::Integer(blur)).with("Fltr", Value::Text(UnicodeString::new_nul("Blr "))), - photoshop_no_options_item("X", Value::Integer(781)).with("Fltr", Value::Integer(5)), - ]; - for item in cases { - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); - // Written back (a bare item gains blending and visibility) and still not editable. - let written = item_for_filter(&f).unwrap(); - assert_eq!(written.get("Fltr"), item.get("Fltr"), "{item:?}"); - let back = filter_from_item(&written); - assert_eq!((back.command.as_str(), &back.params["filterID"]), (UNSUPPORTED_FILTER, &f.params["filterID"])); - } - } - - /// Smart Sharpen's `Fltr` in the measured shape (no `presetKind`, no `Angl`). - fn smart_sharpen(amount: f64, radius: f64, noise: f64, blur: &str) -> Descriptor { - Descriptor::new("smartSharpen") - .with("useLegacy", Value::Boolean(false)) - .with("Amnt", unit(b"#Prc", amount)) - .with("Rds ", unit(b"#Pxl", radius)) - .with("noiseReduction", unit(b"#Prc", noise)) - .with("blur", enumv("blurType", blur)) - } - - fn dust(radius: i32, threshold: i32) -> Descriptor { - Descriptor::new("DstS").with("Rds ", Value::Integer(radius)).with("Thsh", Value::Integer(threshold)) - } - - /// The `Fltr` descriptor PhotoCraft writes for `f`, after a byte round trip. - fn written_fltr(f: &SmartFilter) -> Descriptor { - let d = Descriptor::from_bytes(&item_for_filter(f).unwrap().to_bytes()).unwrap(); - get_desc(&d, "Fltr").unwrap().clone() - } - - /// Measured in Photoshop: Smart Sharpen 120 %, 2.5 px, noise 5 %, Gaussian Blur - /// (filterID 1131); the default entry adds `presetKind` first, which is not kept. - #[test] - fn smart_sharpen_photoshop_entry_opens_and_writes_back() { - let fltr = smart_sharpen(120.0, 2.5, 5.0, "GsnB"); - let item = ps_item("Smart Sharpen...", fltr.clone(), 1131); - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!(f.command, "filter.sharpen.smartSharpen"); - assert_eq!(f.params, json!({"amount": 120.0, "radius": 2.5, "reduceNoise": 5.0})); - assert_eq!(written_fltr(&f), fltr); - let d = item_for_filter(&f).unwrap(); - assert_eq!(int(&d, "filterID"), Some(1131)); - assert_eq!(get_desc(&d, "Fltr").unwrap().class_id, Id::Str(b"smartSharpen".to_vec())); - // The four-character keys and enum values are codes, as Photoshop writes them. - let bytes = d.to_bytes(); - assert_eq!(count(&bytes, b"\0\0\0\0blurenum\0\0\0\x08blurType\0\0\0\0GsnB"), 1); - assert_eq!(count(&bytes, b"\0\0\0\0Rds UntF#Pxl"), 1); - - // With `presetKind` (any value): opens, but the params hold only the engine's own keys - // (it rejects unknown ones), and a re-save leaves it out as Photoshop does for explicit - // values. - for kind in ["presetKindDefault", "presetKindCustom", "Xxxx"] { - let mut with_preset = Descriptor::new("smartSharpen").with("presetKind", enumv("presetKindType", kind)); - with_preset.items.extend(smart_sharpen(200.0, 1.0, 10.0, "GsnB").items); - let f = filter_from_item(&Descriptor::from_bytes(&ps_item("Smart Sharpen...", with_preset, 1131).to_bytes()).unwrap()); - assert_eq!(f.command, "filter.sharpen.smartSharpen"); - let keys: Vec<&str> = f.params.as_object().unwrap().keys().map(String::as_str).collect(); - assert_eq!(keys.len(), 3, "{keys:?}"); - assert!(keys.iter().all(|k| ["amount", "radius", "reduceNoise"].contains(k)), "{keys:?}"); - assert_eq!(f.params, json!({"amount": 200.0, "radius": 1.0, "reduceNoise": 10.0})); - assert_eq!(written_fltr(&f), smart_sharpen(200.0, 1.0, 10.0, "GsnB")); - } - - // Without options PhotoCraft writes the engine's defaults, Gaussian Blur. - assert_eq!(written_fltr(&sf("filter.sharpen.smartSharpen", json!({}))), smart_sharpen(100.0, 1.0, 10.0, "GsnB")); - } - - /// Lens Blur (Photoshop's default), Motion Blur and legacy mode render differently from - /// PhotoCraft's Smart Sharpen, so those entries stay verbatim. - #[test] - fn smart_sharpen_settings_we_dont_render_stay_verbatim() { - let mut default_entry = Descriptor::new("smartSharpen").with("presetKind", enumv("presetKindType", "presetKindDefault")); - default_entry.items.extend(smart_sharpen(200.0, 1.0, 10.0, "lensBlur").items); - let motion = smart_sharpen(80.0, 1.5, 0.0, "MtnB").with("Angl", Value::Integer(30)); - let mut legacy = smart_sharpen(100.0, 1.0, 10.0, "GsnB"); - set(&mut legacy, "useLegacy", Value::Boolean(true)); - for fltr in [default_entry, motion, legacy] { - let item = ps_item("Smart Sharpen...", fltr, 1131); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER); - assert_eq!(f.params["filterID"], 1131); - assert_eq!(item_for_filter(&f).unwrap(), item); - } - } - - #[test] - fn malformed_smart_sharpen_is_kept_verbatim() { - let g = || smart_sharpen(100.0, 1.0, 10.0, "GsnB"); - let without = |key: &str| { - let mut d = g(); - d.items.retain(|(k, _)| !k.is(key)); - d - }; - let with = |key: &str, v: Value| { - let mut d = g(); - set(&mut d, key, v); - d - }; - let cases = vec![ - without("useLegacy"), - without("Amnt"), - without("Rds "), - without("noiseReduction"), - without("blur"), - with("Amnt", Value::Double(100.0)), - with("Amnt", unit(b"#Pxl", 100.0)), - with("Rds ", Value::Integer(1)), - with("useLegacy", Value::Integer(0)), - with("Amnt", unit(b"#Prc", 0.0)), - with("Amnt", unit(b"#Prc", 501.0)), - with("Rds ", unit(b"#Pxl", 0.05)), - with("Rds ", unit(b"#Pxl", 65.0)), - with("Rds ", unit(b"#Pxl", f64::NAN)), - with("noiseReduction", unit(b"#Prc", -1.0)), - with("noiseReduction", unit(b"#Prc", f64::INFINITY)), - with("blur", enumv("blurType", "Xxxx")), - with("blur", enumv("BlrM", "GsnB")), - with("blur", Value::Integer(0)), - with("presetKind", Value::Integer(1)), - g().with("Angl", Value::Integer(30)), - g().with("shadowMode", Value::Descriptor(Descriptor::new("adaptCorrectTones"))), - ]; - for fltr in cases { - let item = ps_item("Smart Sharpen...", fltr, 1131); - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr")); - assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes()); - } - // No `Fltr` at all (hasoptions false). - let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(1131)); - assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); - } - - /// Measured in Photoshop: Dust & Scratches at its defaults (1, 0) and at 4, 20 (filterID - /// `DstS`, 1148417107; both settings `long`). - #[test] - fn dust_and_scratches_photoshop_entry_opens_and_writes_back() { - for (radius, threshold) in [(1, 0), (4, 20), (500, 255)] { - let fltr = dust(radius, threshold); - let item = ps_item("Dust & Scratches...", fltr.clone(), 1_148_417_107); - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!(f.command, "filter.noise.dustAndScratches"); - assert_eq!(f.params, json!({"radius": radius, "threshold": threshold})); - assert_eq!(written_fltr(&f), fltr); - assert_eq!(int(&item_for_filter(&f).unwrap(), "filterID"), Some(1_148_417_107)); - } - // No `Fltr` (hasoptions false): kept verbatim. - let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"DstS"))); - assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); - } - - #[test] - fn malformed_dust_and_scratches_is_kept_verbatim() { - let cases = vec![ - Descriptor::new("DstS").with("Thsh", Value::Integer(0)), - Descriptor::new("DstS").with("Rds ", Value::Integer(1)), - Descriptor::new("DstS").with("Rds ", Value::Double(1.0)).with("Thsh", Value::Integer(0)), - Descriptor::new("DstS").with("Rds ", unit(b"#Pxl", 1.0)).with("Thsh", Value::Integer(0)), - Descriptor::new("DstS").with("Rds ", Value::Integer(1)).with("Thsh", Value::Boolean(false)), - dust(0, 0), - dust(501, 0), - dust(1, -1), - dust(1, 256), - dust(i32::MIN, i32::MAX), - dust(1, 0).with("Xtra", Value::Integer(1)), - ]; - for fltr in cases { - let item = ps_item("Dust & Scratches...", fltr, code(b"DstS")); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr")); - assert_eq!(item_for_filter(&f).unwrap(), item); - } - } - - /// Every option's range ends round trip; hostile params are written in range (the engine - /// clamps the same way), never a panic. - #[test] - fn smart_sharpen_and_dust_option_values_round_trip() { - let mut cases = Vec::new(); - for amount in [1.0, 100.0, 500.0] { - for radius in [0.1, 1.0, 64.0] { - for noise in [0.0, 10.0, 100.0] { - cases.push(sf("filter.sharpen.smartSharpen", json!({"amount": amount, "radius": radius, "reduceNoise": noise}))); - } - } - } - for radius in [1, 2, 100, 500] { - for threshold in [0, 1, 128, 255] { - cases.push(sf("filter.noise.dustAndScratches", json!({"radius": radius, "threshold": threshold}))); - } - } - for f in cases { - let back = filter_from_item(&Descriptor::from_bytes(&item_for_filter(&f).unwrap().to_bytes()).unwrap()); - assert_eq!(back, f); - } - let defaults = json!({"amount": 100.0, "radius": 1.0, "reduceNoise": 10.0}); - for (command, p, want) in [ - ( - "filter.sharpen.smartSharpen", - json!({"amount": 1e9, "radius": -5.0, "reduceNoise": "x"}), - json!({"amount": 500.0, "radius": 0.1, "reduceNoise": 10.0}), - ), - ("filter.sharpen.smartSharpen", json!({"presetKind": "presetKindDefault", "amount": null}), defaults.clone()), - ("filter.sharpen.smartSharpen", json!(null), defaults.clone()), - ("filter.noise.dustAndScratches", json!({"radius": 2.4, "threshold": 1e12}), json!({"radius": 2, "threshold": 255})), - ("filter.noise.dustAndScratches", json!({"radius": -3, "threshold": -3}), json!({"radius": 1, "threshold": 0})), - ("filter.noise.dustAndScratches", json!([]), json!({"radius": 1, "threshold": 0})), - ] { - let back = filter_from_item(&item_for_filter(&sf(command, p.clone())).unwrap()); - assert_eq!((back.command.as_str(), &back.params), (command, &want), "{p}"); - } - } - - /// Every option value of Wind, Extrude and Tiles (and the ends of their ranges). - fn wind_extrude_tiles_settings() -> Vec { - let mut v = Vec::new(); - for method in ["wind", "blast", "stagger"] { - for direction in ["fromRight", "fromLeft"] { - v.push(sf("filter.stylize.wind", json!({"method": method, "direction": direction}))); - } - } - for t in ["blocks", "pyramids"] { - for mode in ["random", "levelBased"] { - for (solid, mask) in [(false, false), (true, false), (false, true), (true, true)] { - v.push(sf( - "filter.stylize.extrude", - json!({"type": t, "size": 7, "depth": 9, "depthMode": mode, "solidFrontFaces": solid, "maskIncompleteBlocks": mask}), - )); - } - } - } - v.push(sf( - "filter.stylize.extrude", - json!({"type": "blocks", "size": 2, "depth": 1, "depthMode": "random", "solidFrontFaces": false, "maskIncompleteBlocks": false}), - )); - v.push(sf( - "filter.stylize.extrude", - json!({"type": "pyramids", "size": 255, "depth": 255, "depthMode": "levelBased", "solidFrontFaces": true, "maskIncompleteBlocks": true}), - )); - for fill in ["background", "foreground", "inverse", "unaltered"] { - v.push(sf( - "filter.stylize.tiles", - json!({"count": 6, "maxOffset": 20, "fill": fill, "foreground": [1.0, 0.0, 0.5, 1.0], "background": [0.0, 0.5, 1.0, 1.0]}), - )); - } - for (count, offset) in [(1, 1), (99, 99)] { - v.push(sf( - "filter.stylize.tiles", - json!({"count": count, "maxOffset": offset, "fill": "background", "foreground": [0.0, 0.0, 0.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), - )); - } - v - } - - /// A `filterFX` entry shaped as Photoshop saves Wind, Extrude and Tiles (measured in Photoshop: - /// applied through Action Manager to a smart object, saved, `filterFX` read back): the item's - /// `FrgC`/`BckC` are the document colours, `Fltr` holds the settings, `filterID` the class code. - fn measured_item(fltr: Descriptor, fg: f64, bg: f64) -> Descriptor { - let id = code(fltr.class_id.as_bytes().try_into().unwrap()); - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Filter..."))) - .with("blendOptions", blend_options(&sf("", J::Null))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgbc(fg)) - .with("BckC", rgbc(bg)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(id)) - } - - /// The `Fltr` descriptors Photoshop 27 wrote for these filters (one smart object each, saved as - /// PSD and read back), with the settings PhotoCraft reads from them. - const PHOTOSHOP_FLTR: [(&str, &str, &str); 6] = [ - ("filter.distort.pinch", r#"{"amount":-28}"#, "0000000600500069006e00630068000000000000506e63680000000100000000416d6e746c6f6e67ffffffe4"), - ("filter.distort.twirl", r#"{"angle":-355}"#, "000000060054007700690072006c0000000000005477726c0000000100000000416e676c6c6f6e67fffffe9d"), - ( - "filter.distort.ripple", - r#"{"amount":-273,"size":"large"}"#, - "000000070052006900700070006c006500000000000052706c650000000200000000416d6e746c6f6e67fffffeef0000000052706c53656e756d0000000052706c53000000004c726720", - ), - ( - "filter.distort.spherize", - r#"{"amount":-1,"mode":"horizontalOnly"}"#, - "00000009005300700068006500720069007a0065000000000000537068720000000200000000416d6e746c6f6e67ffffffff000000005370684d656e756d000000005370684d0000000048727a4f", - ), - ( - "filter.distort.polarCoordinates", - r#"{"mode":"polarToRectangular"}"#, - "000000120050006f006c0061007200200043006f006f007200640069006e0061007400650073000000000000506c72200000000100000000436e7672656e756d00000000436e767200000000506c7252", - ), - ( - "filter.distort.zigZag", - r#"{"amount":-42,"ridges":11,"style":"pondRipples"}"#, - "00000007005a00690067005a006100670000000000005a675a670000000300000000416d6e746c6f6e67ffffffd6000000004e6d62526c6f6e670000000b000000005a5a5479656e756d000000005a5a547900000000506e6452", - ), - ]; - - /// Photoshop's Wave with Scale 100% / 28%: PhotoCraft's Wave has no Scale. - const PHOTOSHOP_WAVE: &str = "000000050057006100760065000000000000576176650000000a0000000057767470656e756d00000000577674700000000057765472000000004e6d62476c6f6e670000014c00000000574c4d6e6c6f6e67000000d500000000574c4d786c6f6e67000000d600000000416d4d6e6c6f6e67000000f000000000416d4d786c6f6e67000000f10000000053636c486c6f6e67000000640000000053636c566c6f6e670000001c00000000556e6441656e756d00000000556e6441000000005772704100000000526e64536c6f6e670013624a"; - - /// A `filterFX` list item as Photoshop writes it (enabled, Normal at 100%, with options), wrapping the `Fltr` descriptor `fltr`. - fn photoshop_fltr_item(fltr: Descriptor) -> Descriptor { - let id = code(fltr.class_id.as_bytes().try_into().unwrap()); - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("from Photoshop"))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(id)) - } - - fn wind(method: &str, direction: &str) -> Descriptor { - Descriptor::new("Wnd ").with("WndM", enumv("WndM", method)).with("Drct", enumv("Drct", direction)) - } - - fn extrude(t: &str, size: Value, depth: Value, mode: &str, solid: Value, mask: Value) -> Descriptor { - Descriptor::new("Extr") - .with("ExtT", enumv("ExtT", t)) - .with("ExtS", size) - .with("ExtD", depth) - .with("ExtR", enumv("ExtR", mode)) - .with("ExtF", solid) - .with("ExtM", mask) - } - - fn tiles(count: Value, offset: Value, fill: &str) -> Descriptor { - Descriptor::new("Tls ").with("TlNm", count).with("TlOf", offset).with("FlCl", enumv("FlCl", fill)) - } - - #[test] - fn wind_extrude_tiles_open_from_photoshop_shapes() { - let (long, yes, no) = (Value::Integer, Value::Boolean(true), Value::Boolean(false)); - let cases = [ - // The measured files. - (wind("Blst", "Left"), "filter.stylize.wind", json!({"method": "blast", "direction": "fromRight"})), - (wind("Stgr", "Rght"), "filter.stylize.wind", json!({"method": "stagger", "direction": "fromLeft"})), - (wind("Wnd ", "Rght"), "filter.stylize.wind", json!({"method": "wind", "direction": "fromLeft"})), - ( - extrude("Blks", long(7), long(9), "Rndm", yes.clone(), no.clone()), - "filter.stylize.extrude", - json!({"type": "blocks", "size": 7, "depth": 9, "depthMode": "random", "solidFrontFaces": true, "maskIncompleteBlocks": false}), - ), - ( - extrude("Pyrm", long(12), long(20), "LvlB", no, yes), - "filter.stylize.extrude", - json!({"type": "pyramids", "size": 12, "depth": 20, "depthMode": "levelBased", "solidFrontFaces": false, "maskIncompleteBlocks": true}), - ), - ( - tiles(long(6), long(20), "FlFr"), - "filter.stylize.tiles", - json!({"count": 6, "maxOffset": 20, "fill": "foreground", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), - ), - ( - tiles(long(4), long(5), "FlIn"), - "filter.stylize.tiles", - json!({"count": 4, "maxOffset": 5, "fill": "inverse", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), - ), - ( - tiles(long(10), long(10), "FlBc"), - "filter.stylize.tiles", - json!({"count": 10, "maxOffset": 10, "fill": "background", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), - ), - ( - tiles(long(99), long(1), "FlSm"), - "filter.stylize.tiles", - json!({"count": 99, "maxOffset": 1, "fill": "unaltered", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), - ), - ]; - for (fltr, command, params) in cases { - let item = measured_item(fltr, 51.0, 255.0); - // Through bytes, as read from a file. - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!((f.command.as_str(), &f.params), (command, ¶ms)); - // Written back in the measured shape: same class, keys and their order, value types - // (long, bool, enum with its type), filterID; Tiles also its colours. - let back = item_for_filter(&f).unwrap(); - assert_eq!(get_desc(&back, "Fltr").map(Descriptor::to_bytes), get_desc(&item, "Fltr").map(Descriptor::to_bytes), "{command}"); - assert_eq!(back.get("filterID"), item.get("filterID"), "{command}"); - if command == "filter.stylize.tiles" { - assert_eq!((back.get("FrgC"), back.get("BckC")), (item.get("FrgC"), item.get("BckC"))); - } - } - // The class codes: numeric filterIDs of the four-char classes. - for (c, id) in [("filter.stylize.wind", 1466852384), ("filter.stylize.extrude", 1165522034), ("filter.stylize.tiles", 1416393504)] { - assert_eq!(item_for_filter(&sf(c, json!({}))).unwrap().get("filterID"), Some(&Value::Integer(id))); - } - // A filter found by its filterID alone (no `Fltr` class to go by) still needs its settings. - let bare = Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)).with("filterID", Value::Integer(1466852384)); - assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); - // Only Tiles reads the entry's colours; Wind and Extrude write the defaults. - let f = filter_from_item(&measured_item(wind("Wnd ", "Left"), 51.0, 0.0)); - assert_eq!(f.params, json!({"method": "wind", "direction": "fromRight"})); - let back = item_for_filter(&f).unwrap(); - assert_eq!((back.get("FrgC"), back.get("BckC")), (Some(&rgbc(0.0)), Some(&rgbc(255.0)))); - // Tiles without colours in its params (or the entry) writes the engine's black and white. - let f = filter_from_item(&Descriptor::new("filterFX").with("Fltr", Value::Descriptor(tiles(long(4), long(5), "FlBc")))); - assert_eq!(f.params, json!({"count": 4, "maxOffset": 5, "fill": "background"})); - let back = item_for_filter(&f).unwrap(); - assert_eq!((back.get("FrgC"), back.get("BckC")), (Some(&rgbc(0.0)), Some(&rgbc(255.0)))); - } - - #[test] - fn wind_extrude_tiles_write_defaults_and_photoshop_ranges() { - let fltr = |c: &str, p: J| match item_for_filter(&sf(c, p)).unwrap().get("Fltr") { - Some(Value::Descriptor(d)) => d.clone(), - other => panic!("no Fltr: {other:?}"), - }; - let long = Value::Integer; - let (yes, no) = (Value::Boolean(true), Value::Boolean(false)); - // Defaults are the engine's; our random seed has no PSD key and is not written. - assert_eq!(fltr("filter.stylize.wind", json!({"seed": 9})), wind("Wnd ", "Left")); - assert_eq!(fltr("filter.stylize.extrude", json!({"seed": 9})), extrude("Blks", long(30), long(30), "Rndm", no.clone(), no.clone())); - assert_eq!(fltr("filter.stylize.tiles", json!({"seed": 9})), tiles(long(10), long(10), "FlBc")); - // Out of range, fractional, non-numeric and non-bool values as the engine reads them. - assert_eq!( - fltr("filter.stylize.extrude", json!({"size": 1e12, "depth": -5, "solidFrontFaces": "yes", "maskIncompleteBlocks": true})), - extrude("Blks", long(255), long(1), "Rndm", no.clone(), yes) - ); - assert_eq!(fltr("filter.stylize.tiles", json!({"count": 0, "maxOffset": 12.6})), tiles(long(1), long(13), "FlBc")); - assert_eq!(fltr("filter.stylize.tiles", json!({"count": "many", "maxOffset": 1000})), tiles(long(10), long(99), "FlBc")); - assert_eq!(fltr("filter.stylize.extrude", json!({"size": f64::NAN})), extrude("Blks", long(30), long(30), "Rndm", no.clone(), no)); - } - - #[test] - fn malformed_wind_extrude_tiles_are_kept_verbatim() { - let long = Value::Integer; - let (yes, no) = (Value::Boolean(true), Value::Boolean(false)); - let cases = [ - // Missing keys. - Descriptor::new("Wnd "), - Descriptor::new("Wnd ").with("WndM", enumv("WndM", "Blst")), - Descriptor::new("Wnd ").with("Drct", enumv("Drct", "Left")), - Descriptor::new("Extr").with("ExtT", enumv("ExtT", "Blks")).with("ExtS", long(7)).with("ExtD", long(9)).with("ExtR", enumv("ExtR", "Rndm")), - Descriptor::new("Tls ").with("TlNm", long(6)).with("TlOf", long(20)), - Descriptor::new("Tls ").with("TlNm", long(6)).with("FlCl", enumv("FlCl", "FlFr")), - // Unknown enum values and enum types (Photoshop falls back to a default for these; - // we keep them as they are rather than guess). - wind("Wild", "Left"), - wind("Blst", "Up "), - Descriptor::new("Wnd ").with("WndM", enumv("Drct", "Blst")).with("Drct", enumv("Drct", "Left")), - extrude("Cube", long(7), long(9), "Rndm", yes.clone(), no.clone()), - extrude("Blks", long(7), long(9), "Sine", yes.clone(), no.clone()), - tiles(long(6), long(20), "FlXx"), - Descriptor::new("Tls ").with("TlNm", long(6)).with("TlOf", long(20)).with("FlCl", enumv("BlnM", "FlFr")), - // Wrong types (also NaN). - Descriptor::new("Wnd ").with("WndM", long(1)).with("Drct", enumv("Drct", "Left")), - extrude("Blks", Value::Double(7.0), long(9), "Rndm", yes.clone(), no.clone()), - extrude("Blks", long(7), unit(b"#Pxl", 9.0), "Rndm", yes.clone(), no.clone()), - extrude("Blks", long(7), long(9), "Rndm", long(1), no.clone()), - extrude("Blks", long(7), long(9), "Rndm", yes.clone(), Value::Double(f64::NAN)), - tiles(Value::Double(f64::NAN), long(20), "FlFr"), - tiles(long(6), Value::Text(UnicodeString::new_nul("20")), "FlFr"), - // Out of range. - extrude("Blks", long(1), long(9), "Rndm", yes.clone(), no.clone()), - extrude("Blks", long(256), long(9), "Rndm", yes.clone(), no.clone()), - extrude("Blks", long(7), long(0), "Rndm", yes.clone(), no.clone()), - extrude("Blks", long(7), long(i32::MAX), "Rndm", yes, no), - tiles(long(0), long(20), "FlFr"), - tiles(long(100), long(20), "FlFr"), - tiles(long(6), long(0), "FlFr"), - tiles(long(6), long(i32::MIN), "FlFr"), - ]; - for fltr in cases { - let item = measured_item(fltr, 0.0, 255.0); - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); - assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes()); - } - // A Tiles entry whose colour is unreadable is kept verbatim too. - for (key, bad) in [ - ("FrgC", Value::Integer(3)), - ("BckC", Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)))), - ( - "BckC", - Value::Descriptor( - Descriptor::new("RGBC").with("Rd ", Value::Double(f64::NAN)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0)), - ), - ), - ] { - let mut item = measured_item(tiles(long(6), long(20), "FlFr"), 0.0, 255.0); - set(&mut item, key, bad); - assert_eq!(filter_from_item(&item).command, UNSUPPORTED_FILTER); - } - // Values with no PSD equivalent are reported, not guessed. - for (c, p) in [ - ("filter.stylize.wind", json!({"method": "gale"})), - ("filter.stylize.wind", json!({"direction": "fromTop"})), - ("filter.stylize.wind", json!({"direction": 1})), - ("filter.stylize.extrude", json!({"type": "cubes"})), - ("filter.stylize.extrude", json!({"depthMode": null})), - ("filter.stylize.tiles", json!({"fill": "transparent"})), - ("filter.stylize.tiles", json!({"foreground": "teal"})), - ("filter.stylize.tiles", json!({"background": [1.0]})), - ("filter.stylize.tiles", json!({"background": [f64::NAN, 0.0, 0.0]})), - ] { - assert!(item_for_filter(&sf(c, p.clone())).is_err(), "{c} {p}"); - } - } - - /// Photoshop's default Custom kernel: a 3 × 3 sharpen centred in the 5 × 5. - const SHARPEN: [i32; 25] = [0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 5, -1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0]; - - /// A `filterFXList` item as measured in Photoshop (applied through Action Manager to a smart - /// object, saved, `filterFX` read back). - fn measured_named_item(id: &[u8; 4], name: &str, fltr: Descriptor) -> Descriptor { - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul(name))) - .with("blendOptions", blend_options(&sf("", J::Null))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgbc(0.0)) - .with("BckC", rgbc(255.0)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(code(id))) - } - - fn offset_fltr(h: Value, v: Value, fill: Value) -> Descriptor { - Descriptor::new("Ofst").with("Hrzn", h).with("Vrtc", v).with("Fl ", fill) - } - - fn custom_fltr(scale: Value, offset: Value, m: Vec) -> Descriptor { - Descriptor::new("Cstm").with("Scl ", scale).with("Ofst", offset).with("Mtrx", Value::List(m)) - } - - fn longs(m: &[i32]) -> Vec { - m.iter().map(|v| Value::Integer(*v)).collect() - } - - #[test] - fn offset_round_trips_every_fill_mode() { - for (fill, ours) in [("Wrp ", "wrap"), ("Rpt ", "repeat"), ("Bckg", "transparent")] { - for (h, v) in [(0, 0), (12, -7), (5, 3), (i32::MIN, i32::MAX)] { - let f = sf("filter.other.offset", json!({"horizontal": h, "vertical": v, "undefinedAreas": ours})); - let d = item_for_filter(&f).unwrap(); - let fltr = get_desc(&d, "Fltr").unwrap(); - assert_eq!(*fltr, offset_fltr(Value::Integer(h), Value::Integer(v), enumv("FlMd", fill))); - assert_eq!(int(&d, "filterID"), Some(1_332_114_292)); - assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); - } - } - } - - /// The measured descriptors (Wrap 0/0, Set to Background 12/−7, Repeat 5/3) open as Offset. - #[test] - fn offset_measured_descriptors_open_as_offset() { - for (h, v, fill, ours) in [(0, 0, "Wrp ", "wrap"), (12, -7, "Bckg", "transparent"), (5, 3, "Rpt ", "repeat")] { - let item = measured_named_item(b"Ofst", "Offset...", offset_fltr(Value::Integer(h), Value::Integer(v), enumv("FlMd", fill))); - let f = filter_from_item(&item); - assert_eq!(f.command, "filter.other.offset"); - assert_eq!(f.params, json!({"horizontal": h, "vertical": v, "undefinedAreas": ours})); - // Written back exactly as measured. - assert_eq!(item_for_filter(&f).unwrap(), item); - } - } - - #[test] - fn offset_written_with_engine_defaults() { - // No params: 0, 0, Wrap Around (the engine's defaults); fractional pixels round. - let d = item_for_filter(&sf("filter.other.offset", json!({}))).unwrap(); - assert_eq!(*get_desc(&d, "Fltr").unwrap(), offset_fltr(Value::Integer(0), Value::Integer(0), enumv("FlMd", "Wrp "))); - let d = item_for_filter(&sf("filter.other.offset", json!({"horizontal": 2.6, "vertical": 3e12, "undefinedAreas": "bogus"}))).unwrap(); - assert_eq!(*get_desc(&d, "Fltr").unwrap(), offset_fltr(Value::Integer(3), Value::Integer(i32::MAX), enumv("FlMd", "Wrp "))); - } - - #[test] - fn malformed_offset_is_kept_verbatim() { - let i = Value::Integer; - for fltr in [ - offset_fltr(i(1), i(2), enumv("FlMd", "Xxxx")), - offset_fltr(i(1), i(2), Value::Integer(1)), - offset_fltr(Value::Double(1.5), i(2), enumv("FlMd", "Wrp ")), - offset_fltr(i(1), unit(b"#Pxl", f64::NAN), enumv("FlMd", "Wrp ")), - Descriptor::new("Ofst").with("Hrzn", i(1)).with("Fl ", enumv("FlMd", "Wrp ")), - Descriptor::new("Ofst"), - // A mistyped enum, a setting we don't write back and a repeated one. - offset_fltr(i(1), i(2), enumv("Xxxx", "Wrp ")), - offset_fltr(i(1), i(2), enumv("FlMd", "Wrp ")).with("Xtra", i(1)), - offset_fltr(i(1), i(2), enumv("FlMd", "Wrp ")).with("Hrzn", i(3)), - ] { - let item = measured_named_item(b"Ofst", "Offset...", fltr); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); - assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "kept byte for byte"); - } - let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"Ofst"))); - assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); - } - - #[test] - fn custom_round_trips() { - let edge: Vec = (0..25) - .map(|i| { - if i == 12 { - 8 - } else if (6..=18).contains(&i) && i % 5 != 0 && i % 5 != 4 { - -1 - } else { - 0 - } - }) - .collect(); - let full: Vec = (0..25).map(|i| i * 83 - 999).collect(); - for (kernel, scale, offset) in [(SHARPEN.to_vec(), 1, 0), (edge, 2, 10), (full, 9999, -9999), (vec![999; 25], 1, 9999)] { - let f = sf("filter.other.custom", json!({"kernel": kernel, "scale": scale, "offset": offset})); - let d = item_for_filter(&f).unwrap(); - assert_eq!(*get_desc(&d, "Fltr").unwrap(), custom_fltr(Value::Integer(scale), Value::Integer(offset), longs(&kernel))); - assert_eq!(int(&d, "filterID"), Some(1_131_639_917)); - assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); - } - } - - /// The measured descriptors (the default sharpen; a blur at Scale 2, Offset 10) open as Custom. - #[test] - fn custom_measured_descriptors_open_as_custom() { - let blur = [0, 0, 0, 0, 0, 0, 1, 2, 1, 0, 0, 2, 4, 2, 0, 0, 1, 2, 1, 0, 0, 0, 0, 0, 0]; - for (kernel, scale, offset) in [(SHARPEN, 1, 0), (blur, 2, 10)] { - let item = measured_named_item(b"Cstm", "Custom...", custom_fltr(Value::Integer(scale), Value::Integer(offset), longs(&kernel))); - let f = filter_from_item(&item); - assert_eq!(f.command, "filter.other.custom"); - assert_eq!(f.params, json!({"kernel": kernel, "scale": scale, "offset": offset})); - assert_eq!(item_for_filter(&f).unwrap(), item); - } - } - - #[test] - fn custom_written_like_the_engine_reads_it() { - let fltr = |p: J| get_desc(&item_for_filter(&sf("filter.other.custom", p)).unwrap(), "Fltr").cloned().unwrap(); - // No kernel: the engine's identity; short kernels pad with 0; out-of-range values clamp. - let mut id = [0; 25]; - id[12] = 1; - assert_eq!(fltr(json!({})), custom_fltr(Value::Integer(1), Value::Integer(0), longs(&id))); - let mut short = [0; 25]; - short[0] = 3; - short[1] = -999; - assert_eq!(fltr(json!({"kernel": [3, -5000], "scale": 0, "offset": 20000})), custom_fltr(Value::Integer(1), Value::Integer(9999), longs(&short))); - // Fractions have no PSD equivalent. - for p in [json!({"kernel": [0.5]}), json!({"scale": 1.5}), json!({"offset": -0.25})] { - assert!(item_for_filter(&sf("filter.other.custom", p.clone())).is_err(), "{p}"); - } - } - - #[test] - fn malformed_custom_is_kept_verbatim() { - let i = Value::Integer; - let mut wrong_type = longs(&SHARPEN); - wrong_type[3] = Value::Double(1.0); - for fltr in [ - custom_fltr(i(1), i(0), longs(&SHARPEN[..24])), - custom_fltr(i(1), i(0), longs(&[0; 26])), - custom_fltr(i(1), i(0), wrong_type), - custom_fltr(i(1), i(0), longs(&[1000; 25])), - custom_fltr(i(0), i(0), longs(&SHARPEN)), - custom_fltr(i(10_000), i(0), longs(&SHARPEN)), - custom_fltr(i(1), i(-10_000), longs(&SHARPEN)), - custom_fltr(Value::Double(f64::NAN), i(0), longs(&SHARPEN)), - custom_fltr(i(1), unit(b"#Pxl", 1.0), longs(&SHARPEN)), - Descriptor::new("Cstm").with("Scl ", i(1)).with("Ofst", i(0)).with("Mtrx", i(5)), - Descriptor::new("Cstm").with("Scl ", i(1)).with("Mtrx", Value::List(longs(&SHARPEN))), - Descriptor::new("Cstm"), - // A setting we don't write back. - custom_fltr(i(1), i(0), longs(&SHARPEN)).with("Xtra", i(1)), - ] { - let item = measured_named_item(b"Cstm", "Custom...", fltr); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); - assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "kept byte for byte"); - } - } - - /// A `filterFX` item holding `fltr`, as Photoshop writes a filter with options. - fn pixelate_item(name: &str, fltr: Descriptor, filter_id: i32) -> Descriptor { - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul(name))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "Nrml")))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgbc(0.0)) - .with("BckC", rgbc(255.0)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(filter_id)) - } - - #[test] - fn mezzotint_round_trips_every_type_and_reads_photoshops_shape() { - for (code, ty) in MEZZOTINT_TYPES { - let f = sf("filter.pixelate.mezzotint", json!({"type": ty})); - let d = item_for_filter(&f).unwrap(); - assert_eq!(int(&d, "filterID"), Some(1_299_870_830)); - let fltr = get_desc(&d, "Fltr").unwrap(); - assert!(fltr.class_id.is("Mztn")); - assert_eq!(enum_of(fltr, "MztT"), Some(&code[..])); - assert!(matches!(fltr.get("MztT"), Some(Value::Enumerated { type_id, .. }) if type_id.is("MztT"))); - assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f, "{ty}"); - } - // Measured in Photoshop: `{'_class': 'Mztn', 'MztT': 'MztT.CrsD'}` and `LngS`, filterID 1299870830. - for (code, ty) in [("CrsD", "coarseDots"), ("LngS", "longStrokes")] { - let item = pixelate_item("Mezzotint...", Descriptor::new("Mztn").with("MztT", enumv("MztT", code)), 1_299_870_830); - let f = filter_from_item(&item); - assert_eq!((f.command.as_str(), &f.params), ("filter.pixelate.mezzotint", &json!({"type": ty}))); - } - // No type or an unknown type is Fine Dots, like the engine; the seed - // (PhotoCraft only) is not saved. - for p in [json!({}), json!({"type": "sparkles"}), json!({"type": "fineDots", "seed": 77})] { - let d = item_for_filter(&sf("filter.pixelate.mezzotint", p)).unwrap(); - let fltr = get_desc(&d, "Fltr").unwrap(); - assert_eq!(enum_of(fltr, "MztT"), Some(&b"FnDt"[..])); - assert_eq!(fltr.items.len(), 1); - } - } - - #[test] - fn color_halftone_round_trips_and_reads_photoshops_shape() { - for p in [ - json!({"maxRadius": 8, "channel1": 108, "channel2": 162, "channel3": 90, "channel4": 45}), - json!({"maxRadius": 4, "channel1": -360, "channel2": 0, "channel3": 360, "channel4": -45}), - json!({"maxRadius": 127, "channel1": 1, "channel2": 2, "channel3": 3, "channel4": 4}), - ] { - let f = sf("filter.pixelate.colorHalftone", p); - let d = item_for_filter(&f).unwrap(); - assert_eq!(int(&d, "filterID"), Some(1_131_180_616)); - let fltr = get_desc(&d, "Fltr").unwrap(); - assert!(fltr.class_id.is("ClrH")); - for k in ["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"] { - assert!(matches!(fltr.get(k), Some(Value::Integer(_))), "{k} is a long"); - } - assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); - } - // Measured in Photoshop: `{'_class': 'ClrH', 'Rds ': 6, 'Ang1': 10, 'Ang2': 20, 'Ang3': 30, 'Ang4': 40}`. - let measured = Descriptor::new("ClrH") - .with("Rds ", Value::Integer(6)) - .with("Ang1", Value::Integer(10)) - .with("Ang2", Value::Integer(20)) - .with("Ang3", Value::Integer(30)) - .with("Ang4", Value::Integer(40)); - let item = pixelate_item("Color Halftone...", measured.clone(), 1_131_180_616); - let f = filter_from_item(&item); - assert_eq!(f.command, "filter.pixelate.colorHalftone"); - assert_eq!(f.params, json!({"maxRadius": 6, "channel1": 10, "channel2": 20, "channel3": 30, "channel4": 40})); - assert_eq!(get_desc(&item_for_filter(&f).unwrap(), "Fltr"), Some(&measured)); - // Defaults and hostile values write longs within the dialog's ranges. - let d = item_for_filter(&sf("filter.pixelate.colorHalftone", json!({"maxRadius": f64::NAN, "channel1": 1e12, "channel2": -1e12, "channel3": "x"}))) - .unwrap(); - let fltr = get_desc(&d, "Fltr").unwrap(); - let got: Vec<_> = ["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"].iter().map(|k| int(fltr, k)).collect(); - assert_eq!(got, [Some(8), Some(360), Some(-360), Some(90), Some(45)]); - } - - #[test] - fn malformed_pixelate_filters_stay_verbatim() { - let mz = |v: Value| Descriptor::new("Mztn").with("MztT", v); - let ch = |rds: Value, ang1: Value| { - Descriptor::new("ClrH") - .with("Rds ", rds) - .with("Ang1", ang1) - .with("Ang2", Value::Integer(20)) - .with("Ang3", Value::Integer(30)) - .with("Ang4", Value::Integer(40)) - }; - let cases = [ - pixelate_item("Mezzotint...", Descriptor::new("Mztn"), code(b"Mztn")), - pixelate_item("Mezzotint...", mz(enumv("MztT", "Sprk")), code(b"Mztn")), - pixelate_item("Mezzotint...", mz(Value::Integer(1)), code(b"Mztn")), - pixelate_item("Color Halftone...", Descriptor::new("ClrH"), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(Value::Double(6.0), Value::Integer(10)), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(unit(b"#Pxl", 6.0), Value::Integer(10)), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(Value::Integer(3), Value::Integer(10)), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(Value::Integer(128), Value::Integer(10)), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(361)), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(i32::MIN)), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Double(f64::NAN)), code(b"ClrH")), - // A mistyped enum and settings we don't write back. - pixelate_item("Mezzotint...", mz(enumv("Xxxx", "FnDt")), code(b"Mztn")), - pixelate_item("Mezzotint...", mz(enumv("MztT", "FnDt")).with("Xtra", Value::Integer(1)), code(b"Mztn")), - pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(10)).with("Xtra", Value::Integer(1)), code(b"ClrH")), - pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(10)).with("Ang1", Value::Integer(11)), code(b"ClrH")), - ]; - for item in cases { - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr")); - // Written back with its own settings (blending is rewritten from the model). - let back = item_for_filter(&f).unwrap(); - // Compared as bytes: a NaN setting is not equal to itself. - let fltr = |d: &Descriptor| get_desc(d, "Fltr").map(Descriptor::to_bytes); - assert_eq!((fltr(&back), int(&back, "filterID")), (fltr(&item), int(&item, "filterID"))); - } - // Without a `Fltr` the filter has no settings to read: kept verbatim too. - let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"ClrH"))); - assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); - } - - /// Distort smart filters from a Photoshop file open as their PhotoCraft filters, and the ones - /// PhotoCraft writes carry the same settings, keys and order as Photoshop's. - #[test] - fn photoshop_distort_filters_read_and_write_like_photoshop() { - for (command, params, hex) in PHOTOSHOP_FLTR { - let ps = Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap(); - let f = filter_from_item(&photoshop_fltr_item(ps.clone())); - let want: J = serde_json::from_str(params).unwrap(); - assert_eq!((f.command.as_str(), &f.params), (command, &want), "{command}"); - let ours = match item_for_filter(&f).unwrap().get("Fltr") { - Some(Value::Descriptor(d)) => d.clone(), - other => panic!("{command}: no Fltr ({other:?})"), - }; - assert_eq!((&ours.class_id, &ours.items), (&ps.class_id, &ps.items), "{command}: same keys, values and order"); - } - // A scaled wave can't be modelled, so it stays Photoshop's, unchanged. - let wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap(); - let item = photoshop_fltr_item(wave); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER); - assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr")); - // Unscaled, but with 332 generators (the renderer draws 64 at most), it stays Photoshop's too. - let mut unscaled = match item.get("Fltr") { - Some(Value::Descriptor(d)) => d.clone(), - other => panic!("wave: no Fltr ({other:?})"), - }; - set(&mut unscaled, "SclV", Value::Integer(100)); - let item = photoshop_fltr_item(unscaled); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER); - assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr")); - - // An extra or repeated setting PhotoCraft doesn't model keeps the filter Photoshop's, unchanged. - let mut fltrs: Vec = PHOTOSHOP_FLTR.iter().map(|(_, _, hex)| Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap()).collect(); - let mut wave = unscaled_wave(); - set(&mut wave, "NmbG", Value::Integer(5)); - assert_eq!(filter_from_item(&photoshop_fltr_item(wave.clone())).command, "filter.distort.wave", "the plain wave maps"); - fltrs.push(wave); - for ps in fltrs { - let name = String::from_utf8_lossy(ps.class_id.as_bytes()).into_owned(); - let mut repeated = ps.clone(); - repeated.items.push(ps.items[0].clone()); - for odd in [ps.clone().with("Xtra", Value::Integer(7)), repeated] { - let item = photoshop_fltr_item(odd); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{name}"); - assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"), "{name}: written back unchanged"); - } - } - } - - /// Photoshop's Wave ([`PHOTOSHOP_WAVE`]) at 100% scale both ways. - fn unscaled_wave() -> Descriptor { - let mut wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap(); - set(&mut wave, "SclV", Value::Integer(100)); - wave - } - - /// An unscaled Wave opens as PhotoCraft's Wave (Triangle, the other settings as stored) up to - /// the generators the renderer models; one more and it stays Photoshop's, unchanged. - #[test] - fn wave_maps_up_to_the_generators_the_renderer_models() { - let max = i32::try_from(photocraft_algo::MAX_WAVE_GENERATORS).unwrap(); - assert_eq!(max, 64); - let mut wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap(); - set(&mut wave, "SclV", Value::Integer(100)); - for (generators, mapped) in [(1, true), (max, true), (max + 1, false), (999, false), (0, false), (-1, false)] { - set(&mut wave, "NmbG", Value::Integer(generators)); - let item = photoshop_fltr_item(wave.clone()); - let f = filter_from_item(&item); - if mapped { - assert_eq!( - (f.command.as_str(), &f.params), - ( - "filter.distort.wave", - &json!({"type": "triangle", "generators": generators, "wavelengthMin": 213, "wavelengthMax": 214, "amplitudeMin": 240, - "amplitudeMax": 241, "undefinedAreas": "wrap", "seed": 1270346}) - ), - "{generators} generators" - ); - match item_for_filter(&f).unwrap().get("Fltr") { - Some(Value::Descriptor(ours)) => assert_eq!((&ours.class_id, &ours.items), (&wave.class_id, &wave.items), "{generators} generators"), - other => panic!("wave: no Fltr ({other:?})"), - } - } else { - assert_eq!(f.command, UNSUPPORTED_FILTER, "{generators} generators"); - assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"), "{generators} generators"); - } - } - } - - /// PhotoCraft draws at most `MAX_WAVE_GENERATORS` generators, so a Wave edited past that exports - /// the 64 it rendered, and a count below 1 exports 1, instead of Photoshop drawing more. - #[test] - fn wave_export_writes_only_the_generators_the_renderer_draws() { - let max = i32::try_from(photocraft_algo::MAX_WAVE_GENERATORS).unwrap(); - for (stored, written) in [(100, max), (999, max), (max + 1, max), (max, max), (5, 5), (1, 1), (0, 1), (-3, 1)] { - let wave = sf( - "filter.distort.wave", - json!({"type": "sine", "generators": stored, "wavelengthMin": 20, "wavelengthMax": 90, "amplitudeMin": 4, "amplitudeMax": 30}), - ); - let fltr = match item_for_filter(&wave).unwrap().get("Fltr") { - Some(Value::Descriptor(d)) => d.clone(), - other => panic!("wave: no Fltr ({other:?})"), - }; - assert_eq!(int(&fltr, "NmbG"), Some(written), "{stored} generators"); - } - } - - /// `RndS` is the seed the renderer draws with, also for a legacy signed or fractional seed - /// (stored as is by `layer.smartFilter.setParams`), not 0. - #[test] - fn wave_export_writes_the_seed_the_renderer_draws() { - for (stored, written) in [ - (json!(77), 77), - (json!(4_000_000_000u32), -294_967_296), - (json!(-1), -1), - (json!(7.4), 7), - (json!(-2.6), -3), - (json!(1e12), i32::MAX), - (json!("x"), 0), - ] { - let wave = sf("filter.distort.wave", json!({"generators": 3, "seed": stored})); - let fltr = match item_for_filter(&wave).unwrap().get("Fltr") { - Some(Value::Descriptor(d)) => d.clone(), - other => panic!("wave: no Fltr ({other:?})"), - }; - assert_eq!(int(&fltr, "RndS"), Some(written), "seed {stored}"); - // And it reads back as that bit pattern. - assert_eq!(known_params("Wave", Some(&fltr), &Descriptor::new("filterFX")).unwrap().1["seed"], json!(written as u32), "seed {stored}"); - } - } - - /// Invert on a smart object: Photoshop stores no `Fltr`, `hasoptions` false and its filter id. - #[test] - fn invert_smart_filter_reads_and_writes_like_photoshop() { - let item = Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Invert"))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(false)) - .with("FrgC", rgbc(255.0)) - .with("BckC", rgbc(0.0)) - .with("filterID", Value::Integer(code(b"Invr"))); - let f = filter_from_item(&item); - assert_eq!((f.command.as_str(), &f.params), ("image.adjustments.invert", &json!({}))); - let back = item_for_filter(&f).unwrap(); - assert_eq!(back.get("Fltr"), None); - assert_eq!(back.get("hasoptions"), Some(&Value::Boolean(false))); - assert_eq!(back.get("filterID"), Some(&Value::Integer(code(b"Invr")))); - assert_eq!(back.get("Nm "), Some(&Value::Text(UnicodeString::new_nul("Invert")))); - } - - /// A filter PhotoCraft doesn't model, or a known one with settings it doesn't, is kept verbatim; only its visibility and blend change. - #[test] - fn photoshop_sharpen_without_fltr_imports_as_sharpen() { - // #6267: Photoshop's Sharpen item holds only its name, blending and `filterID`. - let item = Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Sharpen"))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(false)) - .with("filterID", Value::Integer(1_399_353_968)); - let f = filter_from_item(&item); - assert_eq!((f.command.as_str(), &f.params), ("filter.sharpen.sharpen", &json!({}))); - // Hue/Saturation with an unnumbered range and Dust & Scratches with a missing setting fail - // cleanly instead of panicking. - let bad = SmartFilter { - command: "image.adjustments.hueSaturation".into(), - params: json!({"reds": {"range": [1, "x", 3, 4]}}), - blend: BlendMode::Normal, - opacity: 1.0, - visible: true, - }; - assert!(item_for_filter(&bad).is_err()); - let dust = Descriptor::new("filterFX") - .with("Fltr", Value::Descriptor(Descriptor::new("DstS").with("Rds ", Value::Integer(3)))) - .with("filterID", Value::Integer(code(b"DstS"))); - assert_eq!(filter_from_item(&dust).command, UNSUPPORTED_FILTER); - } - - #[test] - fn hue_saturation_ranges_are_not_lost() { - let hue_sat = |params: J| item_for_filter(&sf("image.adjustments.hueSaturation", params)); - // A range that is not an object is an error, not a silently dropped setting. - assert!(hue_sat(json!({"reds": 5})).is_err()); - assert!(hue_sat(json!({"reds": null})).is_ok()); - // Colorize's 25% default is the master saturation's only: a range's stays 0. - let d = hue_sat(json!({"colorize": true, "reds": {"hue": 5}})).unwrap(); - let adjs = adjustment_list(get_desc(&d, "Fltr").unwrap()).unwrap(); - let saturations: Vec<_> = adjs.iter().map(|a| int(a, "Strt")).collect(); - assert_eq!(saturations, [Some(25), Some(0)]); - // A repeated range (or master) would overwrite the first: the filter is kept verbatim. - let entry = |range: Option| { - let e = Descriptor::new("Hst2").with("H ", Value::Integer(0)).with("Strt", Value::Integer(0)).with("Lght", Value::Integer(0)); - let Some(r) = range else { return Value::Descriptor(e) }; - let e = ["BgnR", "BgnS", "EndS", "EndR"].iter().fold(e.with("LclR", Value::Integer(r)), |e, k| e.with(k, Value::Integer(10))); - Value::Descriptor(e) - }; - for adjs in [vec![entry(None), entry(Some(1)), entry(Some(1))], vec![entry(None), entry(None)]] { - let fltr = Descriptor::new("HStr").with("Clrz", Value::Boolean(false)).with("Adjs", Value::List(adjs)); - let item = Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Hue/Saturation..."))) - .with( - "blendOptions", - Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal"))), - ) - .with("enab", Value::Boolean(true)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(code(b"HStr"))); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER); - assert_eq!(item_for_filter(&f).unwrap(), item); - } - } - - #[test] - fn unknown_filters_keep_their_descriptor() { - let item = Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Shear..."))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) - .with("enab", Value::Boolean(true)) - .with("Fltr", Value::Descriptor(Descriptor::new("Shr ").with("UndA", enumv("UndA", "WrpA")))) - .with("filterID", Value::Integer(code(b"Shr "))); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER); - assert_eq!(f.params["name"], "Shear..."); - assert_eq!(item_for_filter(&f).unwrap(), item); - // Hidden and re-blended: only those keys change. - let mut g = f.clone(); - g.visible = false; - g.blend = BlendMode::Screen; - let back = filter_from_item(&item_for_filter(&g).unwrap()); - assert_eq!((back.visible, back.blend, &back.params), (false, BlendMode::Screen, &f.params)); - // A known filter with a setting we don't model is kept verbatim too. - let odd = Descriptor::new("filterFX").with("Fltr", Value::Descriptor(Descriptor::new("GsnB"))).with("filterID", Value::Integer(code(b"GsnB"))); - assert_eq!(filter_from_item(&odd).command, UNSUPPORTED_FILTER); - } - - /// A `filterFXList` item with filter `fltr` and `filterID`, as Photoshop saves it. - fn ps_item(name: &str, fltr: Descriptor, filter_id: i32) -> Descriptor { - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul(name))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgbc(0.0)) - .with("BckC", rgbc(255.0)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(filter_id)) - } - - fn surface_blur(rds: f64, thsh: i32) -> Descriptor { - Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Pxl", rds)).with("Thsh", Value::Integer(thsh)) - } - - fn smart_blur(rds: f64, thsh: f64, q: &str, m: &str) -> Descriptor { - Descriptor::new("SmrB").with("Rds ", Value::Double(rds)).with("Thsh", Value::Double(thsh)).with("SmBQ", enumv("SmBQ", q)).with("SmBM", enumv("SmBM", m)) - } - - fn radial_blur(amnt: i32, m: &str, q: &str) -> Descriptor { - Descriptor::new("RdlB").with("Amnt", Value::Integer(amnt)).with("BlrM", enumv("BlrM", m)).with("BlrQ", enumv("BlrQ", q)) - } - - /// The `Fltr` shapes measured in Photoshop (each filter applied to a smart object through - /// Action Manager, saved, and `filterFX` read back) open as our filters and are written back - /// with the same keys, value types, units, enums and filter ids. - #[test] - fn blur_family_matches_photoshop_shapes() { - let smart = code(b"SmrB"); - let radial = code(b"RdlB"); - assert_eq!((smart, radial), (1_399_681_602, 1_382_313_026)); - let cases = [ - (surface_blur(5.0, 15), 1135, "filter.blur.surfaceBlur", json!({"radius": 5.0, "threshold": 15})), - (surface_blur(12.0, 40), 1135, "filter.blur.surfaceBlur", json!({"radius": 12.0, "threshold": 40})), - ( - smart_blur(5.0, 25.0, "SBQH", "SBMN"), - smart, - "filter.blur.smartBlur", - json!({"radius": 5.0, "threshold": 25.0, "quality": "high", "mode": "normal"}), - ), - ( - smart_blur(3.0, 30.0, "SBQL", "SBME"), - smart, - "filter.blur.smartBlur", - json!({"radius": 3.0, "threshold": 30.0, "quality": "low", "mode": "edgeOnly"}), - ), - ( - smart_blur(3.0, 30.0, "SBQM", "SBMO"), - smart, - "filter.blur.smartBlur", - json!({"radius": 3.0, "threshold": 30.0, "quality": "medium", "mode": "overlayEdge"}), - ), - (radial_blur(10, "Spn ", "Drft"), radial, "filter.blur.radialBlur", json!({"amount": 10, "method": "spin", "quality": "draft"})), - (radial_blur(20, "Spn ", "Bst "), radial, "filter.blur.radialBlur", json!({"amount": 20, "method": "spin", "quality": "best"})), - (radial_blur(20, "Zm ", "Gd "), radial, "filter.blur.radialBlur", json!({"amount": 20, "method": "zoom", "quality": "good"})), - ]; - for (fltr, id, command, params) in cases { - let item = ps_item("x", fltr.clone(), id); - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!((f.command.as_str(), &f.params), (command, ¶ms), "{fltr:?}"); - let out = item_for_filter(&f).unwrap(); - assert_eq!(out.get("filterID"), Some(&Value::Integer(id))); - assert_eq!(out.get("hasoptions"), Some(&Value::Boolean(true))); - // Byte-identical filter descriptor: class id, four-char keys, types, units and enums. - let Some(Value::Descriptor(w)) = out.get("Fltr") else { panic!("no Fltr for {command}") }; - assert_eq!(w.to_bytes(), fltr.to_bytes(), "{command}"); - } - // Surface Blur's class is a string id; Smart Blur's and Radial Blur's are four-char codes. - assert_eq!(surface_blur(1.0, 2).class_id, Id::Str(b"surfaceBlur".to_vec())); - assert_eq!(radial_blur(1, "Spn ", "Gd ").class_id, Id::Code(*b"RdlB")); - // Unset options are written with the dialog defaults. - let fltr = |c: &str, p: J| item_for_filter(&sf(c, p)).unwrap().get("Fltr").cloned(); - assert_eq!(fltr("filter.blur.surfaceBlur", json!({})), Some(Value::Descriptor(surface_blur(5.0, 15)))); - assert_eq!(fltr("filter.blur.smartBlur", json!({})), Some(Value::Descriptor(smart_blur(3.0, 25.0, "SBQH", "SBMN")))); - assert_eq!(fltr("filter.blur.radialBlur", json!({"centerX": 0.5, "centerY": 0.5})), Some(Value::Descriptor(radial_blur(10, "Spn ", "Gd ")))); - } - - /// `d` with `key` set to `v` (replacing the measured value). - fn replaced(mut d: Descriptor, key: &str, v: Value) -> Descriptor { - set(&mut d, key, v); - d - } - - /// Malformed or unmodelled blur descriptors stay verbatim (and are written back unchanged); - /// settings PSD can't hold are reported, never a panic. - #[test] - fn blur_family_malformed_is_kept_verbatim() { - let smart = code(b"SmrB"); - let radial = code(b"RdlB"); - let text = |s: &str| Value::Text(UnicodeString::new_nul(s)); - let bad = [ - // Missing keys. - (Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Pxl", 5.0)), 1135), - (Descriptor::new("SmrB").with("Rds ", Value::Double(3.0)).with("Thsh", Value::Double(25.0)), smart), - (Descriptor::new("RdlB").with("Amnt", Value::Integer(10)).with("BlrM", enumv("BlrM", "Spn ")), radial), - // Wrong types. - (Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Pxl", 5.0)).with("Thsh", Value::Double(15.0)), 1135), - ( - Descriptor::new("SmrB") - .with("Rds ", text("3")) - .with("Thsh", Value::Double(25.0)) - .with("SmBQ", enumv("SmBQ", "SBQH")) - .with("SmBM", enumv("SmBM", "SBMN")), - smart, - ), - (Descriptor::new("RdlB").with("Amnt", text("10")).with("BlrM", enumv("BlrM", "Spn ")).with("BlrQ", enumv("BlrQ", "Gd ")), radial), - (Descriptor::new("RdlB").with("Amnt", Value::Integer(10)).with("BlrM", Value::Integer(1)).with("BlrQ", enumv("BlrQ", "Gd ")), radial), - // Out of range, NaN and infinity. - (surface_blur(0.5, 15), 1135), - (surface_blur(5.0, 300), 1135), - (surface_blur(f64::NAN, 15), 1135), - (smart_blur(f64::INFINITY, 25.0, "SBQH", "SBMN"), smart), - (smart_blur(3.0, 0.0, "SBQH", "SBMN"), smart), - (radial_blur(0, "Spn ", "Gd "), radial), - (radial_blur(101, "Zm ", "Gd "), radial), - // Unknown enum values. - (smart_blur(3.0, 25.0, "SBQX", "SBMN"), smart), - (smart_blur(3.0, 25.0, "Hgh ", "SBMN"), smart), - (radial_blur(10, "Twrl", "Gd "), radial), - (radial_blur(10, "Spn ", "Hgh "), radial), - // A key we don't model (an off-centre Radial Blur would carry one). - (radial_blur(10, "Zm ", "Gd ").with("Cntr", Value::Descriptor(Descriptor::new("Pnt ").with("Hrzn", Value::Double(10.0)))), radial), - (surface_blur(5.0, 15).with("Edg ", Value::Integer(1)), 1135), - // Enums of another type, units and value types we would not write back. - (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "SmBQ", enumv("Othr", "SBQH")), smart), - (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "SmBM", enumv("SmBQ", "SBMN")), smart), - (replaced(radial_blur(10, "Spn ", "Gd "), "BlrM", enumv("Othr", "Spn ")), radial), - (replaced(radial_blur(10, "Spn ", "Gd "), "BlrQ", enumv("BlrM", "Gd ")), radial), - (Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Prc", 5.0)).with("Thsh", Value::Integer(15)), 1135), - (Descriptor::new("surfaceBlur").with("Rds ", Value::Double(5.0)).with("Thsh", Value::Integer(15)), 1135), - (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "Rds ", unit(b"#Pxl", 3.0)), smart), - (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "Thsh", unit(b"#Prc", 25.0)), smart), - (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "Thsh", Value::Integer(25)), smart), - ]; - for (fltr, id) in bad { - let item = ps_item("x", fltr.clone(), id); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{fltr:?}"); - // Compared as bytes: a NaN setting is not equal to itself. - assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "{fltr:?}"); - } - // Radial Blur at its defaults has no `Fltr` (measured): its values are not stored, so the - // entry stays verbatim instead of guessing them. - let no_opts = Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)).with("filterID", Value::Integer(radial)); - assert_eq!(filter_from_item(&no_opts).command, UNSUPPORTED_FILTER); - // Settings with no PSD equivalent are errors when writing. - for (command, p) in [ - ("filter.blur.smartBlur", json!({"quality": "ultra"})), - ("filter.blur.smartBlur", json!({"mode": 3})), - ("filter.blur.radialBlur", json!({"method": "twirl"})), - ("filter.blur.radialBlur", json!({"quality": ["best"]})), - ("filter.blur.radialBlur", json!({"centerX": 0.25})), - ("filter.blur.radialBlur", json!({"centerY": 1.0})), - // A centre, or a value, that is there but can't be written as Photoshop would open it. - ("filter.blur.radialBlur", json!({"centerX": "middle"})), - ("filter.blur.radialBlur", json!({"centerY": true})), - ("filter.blur.radialBlur", json!({"amount": 0})), - ("filter.blur.radialBlur", json!({"amount": 101})), - ("filter.blur.radialBlur", json!({"amount": "10"})), - ("filter.blur.surfaceBlur", json!({"radius": 0.5})), - ("filter.blur.surfaceBlur", json!({"radius": 100.5})), - ("filter.blur.surfaceBlur", json!({"threshold": 1})), - ("filter.blur.surfaceBlur", json!({"threshold": 256})), - ("filter.blur.surfaceBlur", json!({"radius": "5"})), - ("filter.blur.smartBlur", json!({"radius": 0.05})), - ("filter.blur.smartBlur", json!({"threshold": 100.5})), - ("filter.blur.smartBlur", json!({"threshold": [25]})), - ] { - assert!(item_for_filter(&sf(command, p.clone())).is_err(), "{command} {p}"); - } - // Every value that is written opens again as the same editable filter (range ends included). - for (command, p) in [ - ("filter.blur.surfaceBlur", json!({"radius": 1.0, "threshold": 2})), - ("filter.blur.surfaceBlur", json!({"radius": 100.0, "threshold": 255})), - ("filter.blur.smartBlur", json!({"radius": 0.1, "threshold": 100.0, "quality": "low", "mode": "edgeOnly"})), - ("filter.blur.radialBlur", json!({"amount": 1, "method": "zoom", "quality": "best", "centerX": 0.5, "centerY": null})), - ("filter.blur.radialBlur", json!({"amount": 100, "method": "spin", "quality": "draft"})), - ] { - let back = filter_from_item(&item_for_filter(&sf(command, p.clone())).unwrap()); - assert_eq!(back.command, command, "{p}"); - } - // Hostile numbers write without panicking. - for p in [json!({"radius": f64::MAX, "threshold": -1e300, "amount": 1e300}), json!({"radius": "x", "threshold": null}), json!(null), json!([1, 2])] { - for command in ["filter.blur.surfaceBlur", "filter.blur.smartBlur", "filter.blur.radialBlur"] { - let _ = item_for_filter(&sf(command, p.clone())); - } - } - } - - /// A `filterFX` entry shaped as Photoshop saves it (measured in Photoshop: the filter applied - /// through Action Manager to a smart object, the PSD saved, `filterFX` read back). - fn photoshop_item(filter_id: &[u8; 4], fltr: Descriptor) -> Descriptor { - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Filter..."))) - .with("blendOptions", blend_options(&sf("", J::Null))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgbc(0.0)) - .with("BckC", rgbc(255.0)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(code(filter_id))) - } - - #[test] - fn stylize_and_pixelate_filters_open_from_photoshop_shapes() { - let cases = [ - (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "Nrml")), "filter.stylize.diffuse", json!({"mode": "normal"})), - (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "DrkO")), "filter.stylize.diffuse", json!({"mode": "darkenOnly"})), - (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "LghO")), "filter.stylize.diffuse", json!({"mode": "lightenOnly"})), - (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "anisotropic")), "filter.stylize.diffuse", json!({"mode": "anisotropic"})), - ( - b"TrcC", - Descriptor::new("TrcC").with("Lvl ", Value::Integer(128)).with("Edg ", enumv("CntE", "Upr ")), - "filter.stylize.traceContour", - json!({"level": 128, "edge": "upper"}), - ), - ( - b"TrcC", - Descriptor::new("TrcC").with("Lvl ", Value::Integer(60)).with("Edg ", enumv("CntE", "Lwr ")), - "filter.stylize.traceContour", - json!({"level": 60, "edge": "lower"}), - ), - (b"Crst", Descriptor::new("Crst").with("ClSz", Value::Integer(10)), "filter.pixelate.crystallize", json!({"cellSize": 10})), - ( - b"Pntl", - Descriptor::new("Pntl").with("ClSz", Value::Integer(7)), - "filter.pixelate.pointillize", - json!({"cellSize": 7, "background": [1.0, 1.0, 1.0, 1.0]}), - ), - ]; - for (id, fltr, command, params) in cases { - let item = photoshop_item(id, fltr); - // Through bytes, as read from a file. - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!((f.command.as_str(), &f.params), (command, ¶ms)); - // Written back in the measured shape: same class, keys, value types and filterID. - let back = item_for_filter(&f).unwrap(); - for key in ["Fltr", "filterID", "BckC"] { - assert_eq!(back.get(key), item.get(key), "{command} {key}"); - } - } - // The `anisotropic` mode is a long id, as Photoshop writes it. - let d = item_for_filter(&sf("filter.stylize.diffuse", json!({"mode": "anisotropic"}))).unwrap(); - let Some(Value::Descriptor(fltr)) = d.get("Fltr") else { panic!("no Fltr") }; - assert!(matches!(fltr.get("Md "), Some(Value::Enumerated { value: Id::Str(v), .. }) if v == b"anisotropic")); - // Pointillize takes the entry's background colour; the others ignore it. - let mut item = photoshop_item(b"Pntl", Descriptor::new("Pntl").with("ClSz", Value::Integer(7))); - set(&mut item, "BckC", rgbc(51.0)); - let f = filter_from_item(&item); - assert_eq!(f.params["background"], json!([0.2, 0.2, 0.2, 1.0])); - assert_eq!(item_for_filter(&f).unwrap().get("BckC"), Some(&rgbc(51.0))); - let mut item = photoshop_item(b"Crst", Descriptor::new("Crst").with("ClSz", Value::Integer(7))); - set(&mut item, "BckC", rgbc(51.0)); - assert_eq!(filter_from_item(&item).params, json!({"cellSize": 7})); - // Our random seed has no PSD key: it is not written. - let fltr = |c: &str, p: J| item_for_filter(&sf(c, p)).unwrap().get("Fltr").cloned(); - assert_eq!( - fltr("filter.stylize.diffuse", json!({"mode": "normal", "seed": 7})), - Some(Value::Descriptor(Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "Nrml")))) - ); - // Defaults and out-of-range values are written in Photoshop's ranges. - assert_eq!( - fltr("filter.stylize.traceContour", json!({})), - Some(Value::Descriptor(Descriptor::new("TrcC").with("Lvl ", Value::Integer(128)).with("Edg ", enumv("CntE", "Lwr ")))) - ); - assert_eq!(fltr("filter.pixelate.crystallize", json!({})), Some(Value::Descriptor(Descriptor::new("Crst").with("ClSz", Value::Integer(10))))); - assert_eq!(fltr("filter.pixelate.pointillize", json!({})), Some(Value::Descriptor(Descriptor::new("Pntl").with("ClSz", Value::Integer(5))))); - assert_eq!( - fltr("filter.pixelate.crystallize", json!({"cellSize": 1e9})), - Some(Value::Descriptor(Descriptor::new("Crst").with("ClSz", Value::Integer(300)))) - ); - assert_eq!( - fltr("filter.pixelate.pointillize", json!({"cellSize": "big"})), - Some(Value::Descriptor(Descriptor::new("Pntl").with("ClSz", Value::Integer(5)))) - ); - assert_eq!( - fltr("filter.stylize.traceContour", json!({"level": -40, "edge": "upper"})), - Some(Value::Descriptor(Descriptor::new("TrcC").with("Lvl ", Value::Integer(0)).with("Edg ", enumv("CntE", "Upr ")))) - ); - } - - #[test] - fn malformed_stylize_and_pixelate_filters_are_kept_verbatim() { - let long = Value::Integer; - let cases = [ - // Missing keys. - (b"Dfs ", Descriptor::new("Dfs ")), - (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(60))), - (b"TrcC", Descriptor::new("TrcC").with("Edg ", enumv("CntE", "Upr "))), - (b"Crst", Descriptor::new("Crst")), - (b"Pntl", Descriptor::new("Pntl")), - // Unknown enum values or enum types. - (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "Wild"))), - (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("BlnM", "Nrml"))), - (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(60)).with("Edg ", enumv("CntE", "Mddl"))), - // Wrong types (also NaN). - (b"Dfs ", Descriptor::new("Dfs ").with("Md ", long(1))), - (b"TrcC", Descriptor::new("TrcC").with("Lvl ", Value::Double(60.0)).with("Edg ", enumv("CntE", "Upr "))), - (b"Crst", Descriptor::new("Crst").with("ClSz", unit(b"#Pxl", 10.0))), - (b"Pntl", Descriptor::new("Pntl").with("ClSz", Value::Double(f64::NAN))), - // Out of range. - (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(256)).with("Edg ", enumv("CntE", "Upr "))), - (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(-1)).with("Edg ", enumv("CntE", "Upr "))), - (b"Crst", Descriptor::new("Crst").with("ClSz", long(2))), - (b"Pntl", Descriptor::new("Pntl").with("ClSz", long(i32::MAX))), - ]; - for (id, fltr) in cases { - let item = photoshop_item(id, fltr); - let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); - assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes()); - } - // Saved without options (`hasoptions` false, no `Fltr`): kept verbatim. - let bare = Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)).with("filterID", Value::Integer(code(b"Crst"))); - assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); - // A Pointillize entry whose background colour is unreadable is kept verbatim too. - for bad in [Value::Integer(3), Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)))] { - let mut item = photoshop_item(b"Pntl", Descriptor::new("Pntl").with("ClSz", Value::Integer(7))); - set(&mut item, "BckC", bad); - assert_eq!(filter_from_item(&item).command, UNSUPPORTED_FILTER); - } - // Values with no PSD equivalent are reported, not guessed. - for (c, p) in [ - ("filter.stylize.diffuse", json!({"mode": "sideways"})), - ("filter.stylize.diffuse", json!({"mode": 3})), - ("filter.stylize.traceContour", json!({"edge": "middle"})), - ("filter.pixelate.pointillize", json!({"background": "teal"})), - ("filter.pixelate.pointillize", json!({"background": [1.0]})), - ] { - assert!(item_for_filter(&sf(c, p.clone())).is_err(), "{c} {p}"); - } - } - - /// A Filter Gallery item as Photopea writes it (Chrome, Detail 12, Smoothness 4). - fn gallery_item_with(effects: Vec) -> Descriptor { - let rgb = - |v: f64| Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))); - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Filtergalerie"))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgb(0.0)) - .with("BckC", rgb(255.0)) - .with("Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfs", Value::List(effects.into_iter().map(Value::Descriptor).collect())))) - .with("filterID", Value::Integer(code(b"GEfc"))) - } - - fn chrome(detail: i32, smoothness: i32, visible: bool) -> Descriptor { - Descriptor::new("GEfc") - .with("Dtl ", Value::Integer(detail)) - .with("Smth", Value::Integer(smoothness)) - .with("GEfk", enumv("GEft", "Chrm")) - .with("GELv", Value::Boolean(visible)) - } - - #[test] - fn filter_gallery_chrome_imports_as_editable_gallery() { - let f = filter_from_item(&gallery_item_with(vec![chrome(12, 4, true), chrome(3, 9, false)])); - assert_eq!(f.command, "filter.filterGallery"); - assert_eq!( - f.params, - json!({ - "effects": [ - {"filter": "chrome", "params": {"detail": 12, "smoothness": 4}, "visible": true}, - {"filter": "chrome", "params": {"detail": 3, "smoothness": 9}, "visible": false}, - ], - "foreground": [0.0, 0.0, 0.0, 1.0], - "background": [1.0, 1.0, 1.0, 1.0], - }) - ); - // Written back and read again: unchanged, also when re-blended and hidden. - let mut g = f.clone(); - g.blend = BlendMode::Multiply; - g.opacity = 0.5; - g.visible = false; - let d = item_for_filter(&g).unwrap(); - assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), g); - let fltr = get_desc(&d, "Fltr").unwrap(); - assert!(fltr.class_id.is("GEfc")); - assert_eq!(int(&d, "filterID"), Some(code(b"GEfc"))); - } - - /// A single effect as Photoshop 27 writes it: inline in `Fltr`, no `GEfs` list or `GELv`. - fn photoshop_chrome(detail: i32, smoothness: i32) -> Descriptor { - let rgb = - |v: f64| Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))); - let mut fltr = - Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Chrm")).with("Dtl ", Value::Integer(detail)).with("Smth", Value::Integer(smoothness)); - fltr.name = UnicodeString::new_nul("Filter Gallery"); - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Filter Gallery..."))) - .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "Nrml")))) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgb(255.0)) - .with("BckC", rgb(0.0)) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(code(b"GEfc"))) - } - - #[test] - fn filter_gallery_photoshop_inline_effect_imports_and_writes_back_inline() { - let item = photoshop_chrome(10, 4); - let f = filter_from_item(&item); - assert_eq!(f.command, "filter.filterGallery"); - assert_eq!( - f.params, - json!({ - "effects": [{"filter": "chrome", "params": {"detail": 10, "smoothness": 4}, "visible": true}], - "foreground": [1.0, 1.0, 1.0, 1.0], - "background": [0.0, 0.0, 0.0, 1.0], - }) - ); - // Written back in Photoshop's own layout. - let d = item_for_filter(&f).unwrap(); - assert_eq!(get_desc(&d, "Fltr"), get_desc(&item, "Fltr")); - assert_eq!((get_desc(&d, "FrgC"), get_desc(&d, "BckC")), (get_desc(&item, "FrgC"), get_desc(&item, "BckC"))); - assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); - // A hidden single effect needs the list (only it has a visibility flag). - let mut hidden = f.clone(); - hidden.params["effects"][0]["visible"] = json!(false); - let d = item_for_filter(&hidden).unwrap(); - assert!(get_desc(&d, "Fltr").unwrap().get("GEfs").is_some()); - assert_eq!(filter_from_item(&d), hidden); - // Inline effects we don't model stay verbatim. - let mut odd = photoshop_chrome(10, 4); - set(&mut odd, "Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Ctot")).with("Dtl ", Value::Integer(1)))); - assert_eq!(filter_from_item(&odd).command, UNSUPPORTED_FILTER); - let mut extra = photoshop_chrome(10, 4); - set(&mut extra, "Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Chrm")).with("Xtra", Value::Integer(1)))); - assert_eq!(filter_from_item(&extra).command, UNSUPPORTED_FILTER); - } - - #[test] - fn gallery_table_matches_the_gallery_filters() { - for g in &GALLERY_EFFECTS { - let f = photocraft_algo::GalleryFilter::from_key(g.key).unwrap(); - let keys: Vec<&str> = f.params().iter().map(|p| p.key).collect(); - for (_, ours) in g.settings { - assert!(keys.contains(ours), "{}.{ours}", g.key); - } - } - } - - #[test] - fn filter_gallery_written_with_defaults_and_colours() { - let f = sf("filter.filterGallery", json!({"effects": [{"filter": "chrome"}], "foreground": "#ff0000", "background": [0.0, 0.0, 1.0, 1.0]})); - let back = filter_from_item(&item_for_filter(&f).unwrap()); - assert_eq!(back.params["effects"][0]["params"], json!({"detail": 4, "smoothness": 7})); - assert_eq!(back.params["foreground"], json!([1.0, 0.0, 0.0, 1.0])); - assert_eq!(back.params["background"], json!([0.0, 0.0, 1.0, 1.0])); - } - - #[test] - fn filter_gallery_we_dont_model_is_kept_verbatim() { - // Another effect, an extra setting, a wrong-typed setting, no effects, a non-list. - let other = Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Ctot")).with("GELv", Value::Boolean(true)); - let extra = chrome(4, 7, true).with("Xtra", Value::Integer(1)); - let typed = Descriptor::new("GEfc").with("Dtl ", Value::Double(4.0)).with("GEfk", enumv("GEft", "Chrm")); - for effects in [vec![chrome(4, 7, true), other], vec![extra], vec![typed], vec![]] { - let item = gallery_item_with(effects); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER); - assert_eq!(item_for_filter(&f).unwrap(), item); - } - let odd = Descriptor::new("filterFX").with("Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfs", Value::Integer(3)))); - assert_eq!(filter_from_item(&odd).command, UNSUPPORTED_FILTER); - let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"GEfc"))); - assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); - } - - #[test] - fn filter_gallery_without_psd_equivalent_is_reported() { - for p in [ - json!({"effects": [{"filter": "cutout"}]}), - json!({"effects": [{"filter": "chrome", "params": {"sparkle": 1}}]}), - json!({"effects": [{"params": {}}]}), - json!({"effects": []}), - json!({}), - json!({"effects": [{"filter": "chrome"}], "list": true}), - json!({"effects": [{"filter": "chrome"}], "foreground": "red"}), - json!(null), - ] { - assert!(item_for_filter(&sf("filter.filterGallery", p.clone())).is_err(), "{p}"); - } - } - - /// Filters with no PSD equivalent are skipped with a warning each, and the writable ones around them still export. - #[test] - fn unwritable_filters_are_reported_not_fatal() { - let stack = FilterStack { - filters: vec![ - // Shear's curve isn't mapped to Photoshop's grid yet. - sf("filter.distort.shear", json!({"amount": 40})), - sf("filter.blur.gaussianBlur", json!({"radius": 2.0})), - sf(UNSUPPORTED_FILTER, json!({"psd": "zz"})), - sf("image.adjustments.levels", json!({"cyan": {"gamma": 2.0}})), - sf("image.adjustments.shadowsHighlights", json!({"shadowAmount": 50})), - ], - ..Default::default() - }; - let mut w = Vec::new(); - let d = filter_fx(&stack, "L", &mut w); - assert_eq!(w.len(), 4, "{w:?}"); - let back = filter_stack(&d); - assert_eq!(back.filters, vec![stack.filters[1].clone()]); - } - - #[test] - fn placed_blocks_parse_back() { - let t = Affine { m: [0.5, 0.1, -0.1, 0.5, 10.0, 20.0] }; - let stack = - FilterStack { enabled: false, filters: vec![sf("filter.blur.gaussianBlur", json!({"radius": 3.0}))], mask_enabled: false, mask_linked: true }; - let mut w = Vec::new(); - let spec = PlacedSpec { - idnt: "id-1", - placed: "pl-2", - transform: t, - perspective: None, - size: (64.0, 32.0), - dpi: 72.0, - warp: None, - filter_fx: Some(filter_fx(&stack, "L", &mut w)), - }; - let sold = sold_bytes(None, &spec, &mut w); - assert!(w.is_empty()); - assert_eq!(sold.len() % 4, 0); - let p = parse_sold(&sold).unwrap(); - assert_eq!((p.idnt.as_str(), p.placed.as_str()), ("id-1", "pl-2")); - for (a, b) in p.transform.m.iter().zip(t.m) { - assert!((a - b).abs() < 1e-9); - } - assert_eq!(p.stack, Some(stack)); - let tb = photocraft_psd::TaggedBlock::new(*b"SoLd", sold.clone()); - tb.check_structure().unwrap(); - let pl = photocraft_psd::TaggedBlock::new(*b"PlLd", plld_bytes(&spec, &mut w)); - pl.check_structure().unwrap(); - // A template keeps its other keys; an unmoved transform keeps its exact quad. - let mut tmpl = sold_descriptor(&sold).unwrap(); - tmpl.items.push((Id::new("extraKey"), Value::Integer(7))); - let again = sold_bytes(Some(&tmpl), &PlacedSpec { filter_fx: None, ..spec }, &mut w); - let d = sold_descriptor(&again).unwrap(); - assert_eq!(d.get("extraKey"), Some(&Value::Integer(7))); - assert!(d.get("filterFX").is_none()); - assert_eq!(d.get("Trnf"), tmpl.get("Trnf")); - } - - /// A Distort / Perspective placement goes out as its four corners (`Trnf`, `nonAffineTransform`) - /// and comes back as the same projective map; an affine one reads back as no perspective. - #[test] - fn perspective_placement_round_trips_through_sold() { - let h = photocraft_algo::transform::Homography::rect_to_quad([0.0, 0.0, 64.0, 32.0], [[10.0, 5.0], [80.0, 8.0], [70.0, 50.0], [12.0, 40.0]]).unwrap(); - let mut w = Vec::new(); - let mut spec = PlacedSpec { - idnt: "id", - placed: "pl", - transform: Affine::IDENTITY, - perspective: Some(h.0), - size: (64.0, 32.0), - dpi: 72.0, - warp: None, - filter_fx: None, - }; - let sold = sold_bytes(None, &spec, &mut w); - let back = crate::blocks::parse_smart_perspective(b"SoLd", &sold).expect("a projective placement"); - let n = |m: [f64; 9]| m.map(|v| v / m[8]); - for (a, b) in n(back).iter().zip(n(h.0)) { - assert!((a - b).abs() < 1e-9 * (1.0 + b.abs()), "{back:?} vs {:?}", h.0); - } - // Affine placements carry no perspective. - spec.perspective = None; - spec.transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 5.0, 7.0] }; - let sold = sold_bytes(None, &spec, &mut w); - assert_eq!(crate::blocks::parse_smart_perspective(b"SoLd", &sold), None); - assert_eq!(crate::blocks::parse_smart_perspective(b"PlLd", &sold), None); - } - - /// `quad_moved` compares the corners a template stores with the placement's: unchanged keeps - /// the template's quad, a moved corner (affine or projective) or a missing quad rewrites it. - #[test] - fn quad_moved_detects_corner_changes() { - let t = Affine { m: [1.0, 0.0, 0.0, 1.0, 3.0, 4.0] }; - let mut w = Vec::new(); - let mut spec = PlacedSpec { idnt: "id", placed: "pl", transform: t, perspective: None, size: (20.0, 10.0), dpi: 72.0, warp: None, filter_fx: None }; - let template = parse_sold(&sold_bytes(None, &spec, &mut w)).expect("parses").descriptor; - assert!(!quad_moved(&template, &spec, spec.warp), "same placement"); - spec.transform = Affine { m: [1.0, 0.0, 0.0, 1.0, 3.5, 4.0] }; - assert!(quad_moved(&template, &spec, spec.warp), "moved half a pixel"); - spec.transform = t; - spec.perspective = - photocraft_algo::transform::Homography::rect_to_quad([0.0, 0.0, 20.0, 10.0], [[3.0, 4.0], [23.0, 4.0], [20.0, 12.0], [3.0, 14.0]]).map(|h| h.0); - assert!(quad_moved(&template, &spec, spec.warp), "one corner moved (Distort)"); - assert!(quad_moved(&Descriptor::new("null"), &spec, spec.warp), "no stored quad"); - } - - /// Corrupted placed-layer data and filter descriptors never panic: they parse to something - /// (unknown filters stay verbatim) or to nothing. - #[test] - fn mutated_placed_data_never_panics() { - let stack = FilterStack { - filters: vec![ - sf("filter.blur.gaussianBlur", json!({"radius": 3.0})), - sf("image.adjustments.curves", json!({"points": [[0.0, 0.0], [255.0, 255.0]]})), - sf("image.adjustments.levels", json!({"inBlack": 3, "inWhite": 250, "gamma": 1.1})), - ], - ..Default::default() - }; - let mut w = Vec::new(); - let spec = PlacedSpec { - idnt: "id", - placed: "pl", - transform: Affine::IDENTITY, - perspective: None, - size: (8.0, 8.0), - dpi: 72.0, - warp: None, - filter_fx: Some(filter_fx(&stack, "L", &mut w)), - }; - let sold = sold_bytes(None, &spec, &mut w); - let mut state = 0x2545_F491_4F6C_DD1Du64; - let mut next = || { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - state - }; - for _ in 0..3000 { - let mut b = sold.clone(); - for _ in 0..1 + next() % 3 { - let i = (next() as usize) % b.len(); - b[i] = next() as u8; - } - if let Some(p) = parse_sold(&b) { - for f in p.stack.iter().flat_map(|s| &s.filters) { - let _ = item_for_filter(f); - } - let _ = sold_bytes(Some(&p.descriptor), &spec, &mut w); - } - } - } - - #[test] - fn warps_are_written_and_read_back() { - use photocraft_geom::warp::BezierMesh; - let bounds = [0.0, 0.0, 60.0, 30.0]; - let mut custom = BezierMesh::identity(bounds, 1, 1); - custom.points[15] = [67.0, 30.0]; - let mut multi = Warp::preset(WarpStyle::Custom, 0.0, bounds); - let mut split = BezierMesh::identity(bounds, 2, 2); - split.points[8][1] += 4.0; - multi.mesh = Some(split); - let mut arc = Warp::preset(WarpStyle::Arc, 40.0, bounds); - arc.vertical = true; - arc.h_distort = 10.0; - let mut c = Warp::preset(WarpStyle::Custom, 0.0, bounds); - c.mesh = Some(custom); - for (w, back) in [(Some(arc.clone()), Some(arc)), (Some(c.clone()), Some(c)), (Some(multi.clone()), Some(multi)), (None, None)] { - let mut warnings = Vec::new(); - let spec = PlacedSpec { - idnt: "i", - placed: "p", - transform: Affine::IDENTITY, - perspective: None, - size: (60.0, 30.0), - dpi: 72.0, - warp: w.as_ref(), - filter_fx: None, - }; - let sold = sold_bytes(None, &spec, &mut warnings); - assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), back); - assert!(warnings.is_empty(), "{warnings:?}"); - } - } - - /// A placed layer over a 50 × 25 source, at `transform`, with `warp`. - fn placed<'a>(transform: Affine, warp: Option<&'a Warp>) -> PlacedSpec<'a> { - PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (50.0, 25.0), dpi: 72.0, warp, filter_fx: None } - } - - /// A 3 × 2 patch split warp over the 50 × 25 source with one interior control point pulled. - fn split_warp() -> Warp { - use photocraft_geom::warp::BezierMesh; - let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 3, 2); - mesh.points[10 * 3 + 4][1] += 3.0; - Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]) - } - - /// An imported `soLD` descriptor holding `warp` as Photoshop writes a split warp: a - /// `quiltWarp` whose outer slices sit 0.6 px past the source, before a `warpNone` `warp`. - fn photoshop_template(warp: &Warp) -> Descriptor { - let mesh = warp.mesh.as_ref().expect("a mesh"); - let slices = |k: &str, knots: &[f64], len: f64| { - let n = knots.len() - 1; - let values = knots - .iter() - .enumerate() - .map(|(i, u)| { - if i == 0 { - -0.6 - } else if i == n { - len + 0.6 - } else { - u * len - } - }) - .collect::>(); - let prefix = values.len() as u32; - Value::ObjectArray(ObjectArray { prefix, body: Descriptor::new("UntF").with(k, Value::UnitFloats { unit: *b"#Pxl", values }) }) - }; - let Value::Descriptor(plain) = warp_desc(None, (50.0, 25.0), &mut Vec::new()) else { panic!("a descriptor") }; - let mut quilt = plain.clone(); - quilt.class_id = Id::new("quiltWarp"); - set(&mut quilt, "warpStyle", enumv("warpStyle", "warpCustom")); - let points = Descriptor::new("rationalPoint") - .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: mesh.points.iter().map(|p| p[0]).collect() }) - .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: mesh.points.iter().map(|p| p[1]).collect() }); - let envelope = Descriptor::new("customEnvelopeWarp") - .with("quiltSliceX", slices("quiltSliceX", &mesh.us, 50.0)) - .with("quiltSliceY", slices("quiltSliceY", &mesh.vs, 25.0)) - .with("meshPoints", Value::ObjectArray(ObjectArray { prefix: mesh.points.len() as u32, body: points })); - quilt = quilt - .with("deformNumRows", Value::Integer(mesh.ny() as i32)) - .with("deformNumCols", Value::Integer(mesh.nx() as i32)) - .with("customEnvelopeWarp", Value::Descriptor(envelope)); - let mut d = sold_descriptor(&sold_bytes(None, &placed(Affine::IDENTITY, None), &mut Vec::new())).expect("a descriptor"); - let at = d.items.iter().position(|(k, _)| k.is("warp")).expect("a warp key"); - d.items.insert(at, (Id::new("quiltWarp"), Value::Descriptor(quilt))); - d - } - - fn sold_of(d: Descriptor) -> Vec { - let mut out = b"soLD".to_vec(); - out.extend_from_slice(&4u32.to_be_bytes()); - out.extend(VersionedDescriptor::new(d).to_bytes()); - out - } - - fn quilt_of(d: &Descriptor) -> Option<&Descriptor> { - get_desc(d, "quiltWarp") - } - - /// A split warp of more patches along a side than a `quiltWarp` is read with (Warp Grid 64, - /// then one more split) is written as no warp, with a message, framed by the source rect, so - /// the layer reopens where it was. Before, its `quiltWarp` was refused on reopen while `Trnf` - /// still framed its control box: the layer came back stretched and shifted. - #[test] - fn a_split_warp_past_the_quilt_limit_keeps_its_placement() { - use photocraft_geom::warp::BezierMesh; - let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], crate::blocks::QUILT_MAX_PATCHES, 1); - assert!(mesh.split_u(0.005)); - mesh.points[0] = [-10.0, -5.0]; - let warp = Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]); - let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; - let mut warnings = Vec::new(); - let sold = sold_bytes(None, &placed(transform, Some(&warp)), &mut warnings); - assert_eq!(warnings.len(), 1, "{warnings:?}"); - assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); - assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), None); - assert!(quilt_of(&sold_descriptor(&sold).expect("a descriptor")).is_none()); - // Over an imported split warp, the stale `quiltWarp` goes and the placement holds. - let template = photoshop_template(&split_warp()); - let mut warnings = Vec::new(); - let sold = sold_bytes(Some(&template), &placed(transform, Some(&warp)), &mut warnings); - assert_eq!(warnings.len(), 1, "{warnings:?}"); - assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); - assert!(quilt_of(&sold_descriptor(&sold).expect("a descriptor")).is_none()); - // So does one this reader can't read, which Photoshop would still apply. - let mut template = photoshop_template(&split_warp()); - let Some((_, Value::Descriptor(q))) = template.items.iter_mut().find(|(k, _)| k.is("quiltWarp")) else { panic!("a quiltWarp") }; - set(q, "deformNumRows", Value::Integer(0)); - let sold = sold_bytes(Some(&template), &placed(transform, Some(&warp)), &mut Vec::new()); - assert!(quilt_of(&sold_descriptor(&sold).expect("a descriptor")).is_none()); - // At the limit the split warp is still written. - let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], crate::blocks::QUILT_MAX_PATCHES, 1); - mesh.points[0] = [-10.0, -5.0]; - let warp = Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]); - let mut warnings = Vec::new(); - let sold = sold_bytes(None, &placed(transform, Some(&warp)), &mut warnings); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); - assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(warp)); - } - - /// A split (multi-patch) custom warp is written as Photoshop writes it, a `quiltWarp` before a - /// `warpNone` `warp`, and reads back with its mesh and its transform. Before, the warp was - /// written as none while `Trnf` was still the image of its control-point box, so the layer - /// came back stretched and shifted. - #[test] - fn split_warp_round_trips_through_sold() { - use photocraft_geom::warp::BezierMesh; - let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 2, 1); - mesh.points[0] = [-10.0, -5.0]; - let warp = Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]); - let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; - let mut warnings = Vec::new(); - let sold = sold_bytes(None, &placed(transform, Some(&warp)), &mut warnings); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); - assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(warp)); - let d = sold_descriptor(&sold).expect("a descriptor"); - let at = |key: &str| d.items.iter().position(|(k, _)| k.is(key)); - assert!(at("quiltWarp").expect("a quiltWarp") < at("warp").expect("a warp")); - let plain = get_desc(&d, "warp").expect("a warp"); - assert_eq!(enum_of(plain, "warpStyle"), Some(&b"warpNone"[..])); - assert!(plain.get("customEnvelopeWarp").is_none()); - let quilt = quilt_of(&d).expect("a quiltWarp"); - assert!(quilt.class_id.is("quiltWarp")); - assert_eq!((quilt.get("deformNumCols"), quilt.get("deformNumRows")), (Some(&Value::Integer(7)), Some(&Value::Integer(4)))); - let env = get_desc(quilt, "customEnvelopeWarp").expect("an envelope"); - let prefix = |k: &str| match env.get(k) { - Some(Value::ObjectArray(a)) => Some(a.prefix), - _ => None, - }; - assert_eq!((prefix("quiltSliceX"), prefix("quiltSliceY"), prefix("meshPoints")), (Some(3), Some(2), Some(28))); - } - - /// A template's split warp is replaced along with its `warp`: a warp changed to Arc, to none, - /// to one patch or to another mesh reads back as changed, not as the imported split warp. - #[test] - fn a_replaced_split_warp_does_not_come_back() { - use photocraft_geom::warp::BezierMesh; - let bounds = [0.0, 0.0, 50.0, 25.0]; - let split = split_warp(); - let template = photoshop_template(&split); - let arc = Warp::preset(WarpStyle::Arc, 30.0, bounds); - let mut one = BezierMesh::identity(bounds, 1, 1); - one.points[5][0] += 2.0; - let one = Warp::custom(one, bounds); - let mut resplit = BezierMesh::identity(bounds, 2, 2); - resplit.points[8][1] += 4.0; - let resplit = Warp::custom(resplit, bounds); - for w in [Some(arc), None, Some(one), Some(resplit)] { - let mut warnings = Vec::new(); - let sold = sold_bytes(Some(&template), &placed(Affine::IDENTITY, w.as_ref()), &mut warnings); - assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), w); - let d = sold_descriptor(&sold).expect("a descriptor"); - assert_eq!(quilt_of(&d).is_some(), w.as_ref().is_some_and(|w| w.mesh.as_ref().is_some_and(|m| m.points.len() > 16)), "{w:?}"); - assert!(warnings.is_empty(), "{warnings:?}"); - } - } - - /// An imported split warp that nothing changed keeps Photoshop's `quiltWarp` as stored when - /// the layer is rewritten for something else (here a move); a mesh edited on the same grid - /// keeps Photoshop's slices. - #[test] - fn an_imported_split_warp_keeps_photoshop_s_quilt() { - let template = photoshop_template(&split_warp()); - let read = crate::blocks::parse_placed_warp(b"SoLd", &sold_of(template.clone())).expect("the split warp"); - let moved = Affine { m: [1.0, 0.0, 0.0, 1.0, 4.0, 0.0] }; - let sold = sold_bytes(Some(&template), &placed(moved, Some(&read)), &mut Vec::new()); - let d = sold_descriptor(&sold).expect("a descriptor"); - assert_eq!(d.get("quiltWarp"), template.get("quiltWarp")); - assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, moved); - let mut edited = read.clone(); - if let Some(m) = edited.mesh.as_mut() { - m.points[12][0] += 1.5; - } - let sold = sold_bytes(Some(&template), &placed(Affine::IDENTITY, Some(&edited)), &mut Vec::new()); - assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(edited)); - let slices = |d: &Descriptor| { - let env = get_desc(quilt_of(d)?, "customEnvelopeWarp")?; - Some((env.get("quiltSliceX").cloned(), env.get("quiltSliceY").cloned())) - }; - assert_eq!(slices(&sold_descriptor(&sold).expect("a descriptor")), slices(&template)); - } - - /// The legacy `PlLd` record has no split warp: it stores none, with its corners framed by the - /// source rect, so a reader of `PlLd` alone places the layer where its transform puts it. - #[test] - fn plld_of_a_split_warp_is_framed_by_the_source() { - let warp = split_warp(); - let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; - let mut warnings = Vec::new(); - let plld = plld_bytes(&placed(transform, Some(&warp)), &mut warnings); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(crate::blocks::parse_plld_warp(&plld), crate::blocks::PlldWarp::None); - let (_, corners) = crate::blocks::parse_plld(&plld).expect("a record"); - assert_eq!(crate::blocks::plld_transform(&corners, Some((50.0, 25.0)), None).0, transform); - } - - /// Export writes `Trnf` as the image of the custom warp's control-point box, the inverse of - /// import: a spilled mesh comes back with the same transform and the quad Photoshop expects. - #[test] - fn warp_control_box_quad_round_trips() { - use photocraft_geom::warp::BezierMesh; - let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 1, 1); - mesh.points[0] = [-10.0, -5.0]; - mesh.points[15] = [60.0, 25.0]; - let mut warp = Warp::preset(WarpStyle::Custom, 0.0, [0.0, 0.0, 50.0, 25.0]); - warp.mesh = Some(mesh); - let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; - let spec = PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (50.0, 25.0), dpi: 72.0, warp: Some(&warp), filter_fx: None }; - let sold = sold_bytes(None, &spec, &mut Vec::new()); - let p = parse_sold(&sold).expect("parses"); - let Some(Value::List(q)) = p.descriptor.get("Trnf") else { panic!("no Trnf") }; - let q: Vec = q.iter().filter_map(|v| num(Some(v))).collect(); - assert_eq!(q, [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]); - assert_eq!(p.transform, transform); - // The imported quad reads as unmoved, so the template's `Trnf` is kept as stored. - assert!(!quad_moved(&p.descriptor, &spec, spec.warp)); - } - - /// #4112: a regenerated `SoLd` (after Replace Contents, a move…) writes a cylinder back as - /// `warpCylinder` and its seven values, not as no warp, and frames its control-point box with - /// the quad, affine or projective, so import places it where it was. - #[test] - fn cylinder_warp_round_trips_through_sold() { - let v = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5]; - let warp = Warp::cylinder(&v, [0.0, 0.0, 1000.0, 1000.0]).unwrap(); - let transform = Affine { m: [0.5, 0.0, 0.0, 0.5, 40.0, 30.0] }; - let mut spec = - PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (1000.0, 1000.0), dpi: 72.0, warp: Some(&warp), filter_fx: None }; - let mut warnings = Vec::new(); - let sold = sold_bytes(None, &spec, &mut warnings); - assert!(warnings.is_empty(), "{warnings:?}"); - let p = parse_sold(&sold).expect("parses"); - let Some(Value::Descriptor(w)) = p.descriptor.get("warp") else { panic!("no warp") }; - assert_eq!(crate::blocks::enum_of(w, "warpStyle"), Some(b"warpCylinder".as_slice())); - let Some(Value::List(values)) = w.get("warpValues") else { panic!("no warpValues") }; - assert_eq!(values.iter().filter_map(|x| num(Some(x))).collect::>(), v); - assert!(w.get("customEnvelopeWarp").is_none()); - assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(warp.clone())); - for (a, b) in p.transform.m.iter().zip(transform.m) { - assert!((a - b).abs() < 1e-9, "{:?}", p.transform); - } - // The quad is the image of the control-point box, not of the source rect. - let cb = warp.mesh.as_ref().unwrap().control_bounds(); - let Some(Value::List(q)) = p.descriptor.get("Trnf") else { panic!("no Trnf") }; - let q: Vec = q.iter().filter_map(|x| num(Some(x))).collect(); - let want = [cb[0], cb[1], cb[2], cb[1], cb[2], cb[3], cb[0], cb[3]].map(|c| 0.5 * c); - for (i, (a, b)) in q.iter().zip(want).enumerate() { - let shift = if i % 2 == 0 { 40.0 } else { 30.0 }; - assert!((a - (b + shift)).abs() < 1e-9, "corner {i}: {q:?}"); - } - assert!(!quad_moved(&p.descriptor, &spec, spec.warp)); - // A projective placement comes back as the same map. - let h = photocraft_algo::transform::Homography::rect_to_quad(cb, [[10.0, 20.0], [410.0, 60.0], [400.0, 480.0], [30.0, 520.0]]).unwrap(); - spec.perspective = Some(h.0); - let sold = sold_bytes(None, &spec, &mut warnings); - let back = crate::blocks::parse_smart_perspective(b"SoLd", &sold).expect("projective"); - let n = |m: [f64; 9]| m.map(|x| x / m[8]); - for (a, b) in n(back).iter().zip(n(h.0)) { - assert!((a - b).abs() < 1e-9 * (1.0 + b.abs()), "{back:?} vs {:?}", h.0); - } - let plld = plld_bytes(&spec, &mut warnings); - assert_eq!(crate::blocks::parse_plld_warp(&plld), crate::blocks::PlldWarp::Warp(warp)); - assert!(warnings.is_empty(), "{warnings:?}"); - } - - #[test] - fn hex_and_uuid() { - assert_eq!(from_hex(&to_hex(&[0, 1, 0xab, 0xff])), Some(vec![0, 1, 0xab, 0xff])); - assert_eq!(from_hex("abc"), None); - assert_eq!(from_hex("zz"), None); - let u = uuid_from(b"x"); - assert_eq!(u.len(), 36); - assert_eq!(u, uuid_from(b"x")); - assert_ne!(u, uuid_from(b"y")); - } - - // Render filters as Photoshop 27 saves them on a smart object (`filterFXList` items, with - // neutral blending): Clouds and Difference Clouds in white on black, Fibers in black on white, - // Lens Flare with the 50-300mm Zoom at 159%. - const PHOTOSHOP_CLOUDS: &str = "0000000100000000000866696c746572465800000008000000004e6d202054455854000000070043006c006f00750064007300000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f7562000000000000000000000000466c74724f626a63000000070043006c006f007500640073000000000000436c64730000000100000000466c52736c6f6e67000049e40000000866696c74657249446c6f6e67436c6473"; - const PHOTOSHOP_DIFFERENCE_CLOUDS: &str = "0000000100000000000866696c746572465800000008000000004e6d202054455854000000120044006900660066006500720065006e0063006500200043006c006f00750064007300000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f7562000000000000000000000000466c74724f626a63000000120044006900660066006500720065006e0063006500200043006c006f007500640073000000000000446672430000000100000000466c52736c6f6e67000057d20000000866696c74657249446c6f6e6744667243"; - const PHOTOSHOP_FIBERS: &str = "0000000100000000000866696c746572465800000008000000004e6d2020544558540000000a004600690062006500720073002e002e002e00000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f756200000000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe0000000000000000000466c74724f626a630000000700460069006200650072007300000000000046627273000000030000000056726e636c6f6e670000001000000000537472676c6f6e670000000400000000526e64536c6f6e67000062f10000000866696c74657249446c6f6e6746627273"; - const PHOTOSHOP_LENS_FLARE: &str = "0000000100000000000866696c746572465800000008000000004e6d2020544558540000000e004c0065006e007300200046006c006100720065002e002e002e00000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f756200000000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe0000000000000000000466c74724f626a630000000b004c0065006e007300200046006c0061007200650000000000004c6e73460000000300000000427267686c6f6e670000009f00000000466c72434f626a6300000001000000000000506e7420000000020000000048727a6e646f75623fe86666600000000000000056727463646f75623fe60b60c0000000000000004c6e7320656e756d000000004c6e7320000000005a6d20200000000866696c74657249446c6f6e674c6e7346"; - - fn photoshop(hex: &str) -> Descriptor { - Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap() - } - - fn set_lens(item: &mut Descriptor, code: [u8; 4]) { - let Some(Value::Descriptor(fltr)) = item.items.iter_mut().find(|(k, _)| k.is("Fltr")).map(|(_, v)| v) else { panic!("no Fltr") }; - set(fltr, "Lns ", Value::Enumerated { type_id: Id::new("Lns "), value: Id::Code(code) }); - } - - #[test] - fn photoshop_render_filters_read_and_write_like_photoshop() { - let colours = |fg: f64, bg: f64| (json!([fg, fg, fg, 1.0]), json!([bg, bg, bg, 1.0])); - let (white, black) = colours(1.0, 0.0); - let cases = [ - (PHOTOSHOP_CLOUDS, "filter.render.clouds", json!({"seed": 18916, "foreground": white, "background": black})), - (PHOTOSHOP_DIFFERENCE_CLOUDS, "filter.render.differenceClouds", json!({"seed": 22482, "foreground": white, "background": black})), - (PHOTOSHOP_FIBERS, "filter.render.fibers", json!({"variance": 16, "strength": 4, "seed": 25329, "foreground": black, "background": white})), - ( - PHOTOSHOP_LENS_FLARE, - "filter.render.lensFlare", - json!({"brightness": 159, "centerX": 0.762499988079071, "centerY": 0.6888889074325562, "lens": "zoom"}), - ), - ]; - for (hex, command, params) in cases { - let item = photoshop(hex); - let f = filter_from_item(&item); - assert_eq!((f.command.as_str(), &f.params), (command, ¶ms)); - // Written back, it is Photoshop's item again: name, colours, settings and key order. - assert_eq!(item_for_filter(&f).unwrap().items, item.items, "{command}"); - } - } - - #[test] - fn every_lens_flare_lens_round_trips_with_photoshops_code() { - for (code, lens) in LENSES { - let mut item = photoshop(PHOTOSHOP_LENS_FLARE); - set_lens(&mut item, *code); - let f = filter_from_item(&item); - assert_eq!(f.params["lens"], lens); - assert_eq!(item_for_filter(&f).unwrap().items, item.items, "{lens}"); - } - // A lens we don't know keeps the filter verbatim. - let mut item = photoshop(PHOTOSHOP_LENS_FLARE); - set_lens(&mut item, *b"Xxxx"); - assert_eq!(filter_from_item(&item).command, UNSUPPORTED_FILTER); - } - - /// The descriptor at `path` (nested keys) inside `item`, for editing. - fn desc_at<'a>(item: &'a mut Descriptor, path: &[&str]) -> &'a mut Descriptor { - path.iter().fold(item, |d, key| { - let Some(Value::Descriptor(x)) = d.items.iter_mut().find(|(k, _)| k.is(key)).map(|(_, v)| v) else { panic!("no {key}") }; - x - }) - } - - #[test] - fn render_filters_with_settings_we_dont_model_stay_verbatim() { - // Each case changes one thing in a Photoshop item: an extra setting, a repeated one, or a - // value of another type than Photoshop writes. Opened as editable, a re-save would drop the - // extra setting or rewrite the value; kept verbatim, the item is written back byte for byte. - type Edit = Box; - /// A descriptor path in the item (nested keys) and the edit made there. - type Change = (&'static [&'static str], Edit); - let extra: fn(&mut Descriptor) = |d| d.items.push((Id::new("Xtra"), Value::Integer(1))); - let as_double = |key: &'static str| -> Edit { Box::new(move |d| set(d, key, Value::Double(1.0))) }; - let as_long = |key: &'static str| -> Edit { Box::new(move |d| set(d, key, Value::Integer(1))) }; - let repeat = |key: &'static str| -> Edit { - Box::new(move |d| { - let v = d.get(key).cloned().unwrap(); - d.items.push((Id::new(key), v)); - }) - }; - let colour_edits = || -> Vec { - vec![ - (&["FrgC"], Box::new(|d: &mut Descriptor| d.items.push((Id::new("redFloat"), Value::Double(0.5))))), - (&["BckC"], as_long("Grn ")), - (&["FrgC"], Box::new(|d: &mut Descriptor| set(d, "Rd ", Value::Double(300.0)))), - (&["BckC"], Box::new(|d: &mut Descriptor| d.class_id = Id::new("HSBC"))), - ] - }; - let mut cases: Vec<(&str, &'static [&'static str], Edit)> = Vec::new(); - for hex in [PHOTOSHOP_CLOUDS, PHOTOSHOP_DIFFERENCE_CLOUDS] { - cases.push((hex, &["Fltr"], Box::new(extra))); - cases.push((hex, &["Fltr"], repeat("FlRs"))); - cases.push((hex, &["Fltr"], as_double("FlRs"))); - cases.extend(colour_edits().into_iter().map(|(p, e)| (hex, p, e))); - } - cases.push((PHOTOSHOP_FIBERS, &["Fltr"], Box::new(extra))); - cases.push((PHOTOSHOP_FIBERS, &["Fltr"], repeat("Strg"))); - for key in ["Vrnc", "Strg", "RndS"] { - cases.push((PHOTOSHOP_FIBERS, &["Fltr"], as_double(key))); - } - cases.extend(colour_edits().into_iter().map(|(p, e)| (PHOTOSHOP_FIBERS, p, e))); - cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], Box::new(extra))); - cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], repeat("Brgh"))); - cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], as_double("Brgh"))); - cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], Box::new(|d| set(d, "Lns ", Value::Enumerated { type_id: Id::new("Xxxx"), value: Id::Code(*b"Zm ") })))); - cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr", "FlrC"], Box::new(extra))); - cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr", "FlrC"], as_long("Hrzn"))); - cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr", "FlrC"], Box::new(|d| set(d, "Vrtc", Value::UnitFloat { unit: *b"#Pxl", value: 0.5 })))); - for (i, (hex, path, edit)) in cases.iter().enumerate() { - let mut item = photoshop(hex); - edit(desc_at(&mut item, path)); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "case {i} ({path:?}): {:?}", f.params); - assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "case {i} ({path:?})"); - } - } - - #[test] - fn render_filters_made_in_photocraft_are_written() { - // Without colours (an older document or a script), Photoshop's default black and white. - let back = filter_from_item(&item_for_filter(&sf("filter.render.clouds", json!({"seed": 7}))).unwrap()); - assert_eq!(back.params, json!({"seed": 7, "foreground": [0.0, 0.0, 0.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]})); - // A seed above i32::MAX keeps its bit pattern, and colours may be hex. - let p = json!({"variance": 30, "strength": 10, "seed": 4_000_000_000u32, "foreground": "#ff0000", "background": [0.0, 0.0, 1.0, 1.0]}); - let back = filter_from_item(&item_for_filter(&sf("filter.render.fibers", p)).unwrap()); - assert_eq!( - back.params, - json!({"variance": 30, "strength": 10, "seed": 4_000_000_000u32, "foreground": [1.0, 0.0, 0.0, 1.0], "background": [0.0, 0.0, 1.0, 1.0]}) - ); - let flare = sf("filter.render.lensFlare", json!({"brightness": 120, "centerX": 0.25, "centerY": 0.75, "lens": "moviePrime"})); - assert_eq!(filter_from_item(&item_for_filter(&flare).unwrap()).params, flare.params); - // Lenses and colours we can't write are reported, not guessed. - assert!(item_for_filter(&sf("filter.render.lensFlare", json!({"lens": "fisheye"}))).unwrap_err().contains("fisheye")); - assert!(item_for_filter(&sf("filter.render.clouds", json!({"foreground": "red"}))).is_err()); - } -} +mod tests; diff --git a/crates/io/src/smart_map/tests.rs b/crates/io/src/smart_map/tests.rs new file mode 100644 index 0000000000..eea8c0538e --- /dev/null +++ b/crates/io/src/smart_map/tests.rs @@ -0,0 +1,2318 @@ +use super::*; + +fn count(hay: &[u8], needle: &[u8]) -> usize { + hay.windows(needle.len()).filter(|w| *w == needle).count() +} + +/// A freshly built placed layer writes `warp` (key and class) as a length-4 string, as +/// Photoshop does; the code form is a different key to Photoshop. +#[test] +fn fresh_placed_warp_is_a_string_id() { + let spec = + PlacedSpec { idnt: "id", placed: "id", transform: Affine::IDENTITY, perspective: None, size: (10.0, 10.0), dpi: 72.0, warp: None, filter_fx: None }; + let mut warnings = Vec::new(); + let sold = sold_bytes(None, &spec, &mut warnings); + let plld = plld_bytes(&spec, &mut warnings); + // `SoLd`: the `warp` key and the warp descriptor's class; `PlLd`: the descriptor's class. + for (bytes, n) in [(&sold, 2), (&plld, 1)] { + assert_eq!(count(bytes, b"\0\0\0\x04warp"), n); + assert_eq!(count(bytes, b"\0\0\0\0warp"), 0); + } + let d = sold_descriptor(&sold).unwrap(); + assert!(matches!(d.get("warp"), Some(Value::Descriptor(w)) if w.class_id == Id::Str(b"warp".to_vec()))); +} + +fn sf(command: &str, params: J) -> SmartFilter { + SmartFilter { command: command.into(), params, blend: BlendMode::Normal, opacity: 1.0, visible: true } +} + +#[test] +fn modelled_filters_round_trip() { + let filters = vec![ + sf("filter.blur.gaussianBlur", json!({"radius": 4.0})), + sf("filter.blur.boxBlur", json!({"radius": 5.0})), + sf("filter.blur.motionBlur", json!({"angle": -20, "distance": 10.0})), + sf("filter.blur.surfaceBlur", json!({"radius": 12.0, "threshold": 40})), + sf("filter.blur.smartBlur", json!({"radius": 5.0, "threshold": 25.0, "quality": "high", "mode": "normal"})), + sf("filter.blur.smartBlur", json!({"radius": 3.0, "threshold": 30.0, "quality": "medium", "mode": "overlayEdge"})), + sf("filter.blur.smartBlur", json!({"radius": 0.5, "threshold": 0.1, "quality": "low", "mode": "edgeOnly"})), + sf("filter.blur.radialBlur", json!({"amount": 10, "method": "spin", "quality": "draft"})), + sf("filter.blur.radialBlur", json!({"amount": 20, "method": "zoom", "quality": "good"})), + sf("filter.blur.radialBlur", json!({"amount": 100, "method": "spin", "quality": "best"})), + sf("filter.sharpen.unsharpMask", json!({"amount": 150.0, "radius": 2.0, "threshold": 0})), + sf("filter.noise.addNoise", json!({"amount": 12.0, "distribution": "uniform", "monochromatic": false, "seed": 1234})), + sf("filter.noise.median", json!({"radius": 3.0})), + sf("filter.other.highPass", json!({"radius": 3.0})), + sf("filter.other.maximum", json!({"radius": 2.0})), + sf("filter.other.minimum", json!({"radius": 2.0})), + sf("filter.pixelate.mosaic", json!({"cellSize": 8.0})), + sf("filter.pixelate.mezzotint", json!({"type": "mediumStrokes"})), + sf("filter.pixelate.colorHalftone", json!({"maxRadius": 6, "channel1": 10, "channel2": 20, "channel3": 30, "channel4": 40})), + sf("filter.stylize.emboss", json!({"angle": 135, "height": 3, "amount": 100})), + sf("filter.sharpen.smartSharpen", json!({"amount": 120.0, "radius": 2.5, "reduceNoise": 5.0})), + sf("filter.noise.dustAndScratches", json!({"radius": 4, "threshold": 20})), + sf("filter.stylize.diffuse", json!({"mode": "normal"})), + sf("filter.stylize.diffuse", json!({"mode": "darkenOnly"})), + sf("filter.stylize.diffuse", json!({"mode": "lightenOnly"})), + sf("filter.stylize.diffuse", json!({"mode": "anisotropic"})), + sf("filter.stylize.traceContour", json!({"level": 60, "edge": "lower"})), + sf("filter.stylize.traceContour", json!({"level": 128, "edge": "upper"})), + sf("filter.stylize.traceContour", json!({"level": 0, "edge": "upper"})), + sf("filter.stylize.traceContour", json!({"level": 255, "edge": "lower"})), + sf("filter.pixelate.crystallize", json!({"cellSize": 10})), + sf("filter.pixelate.crystallize", json!({"cellSize": 3})), + sf("filter.pixelate.crystallize", json!({"cellSize": 300})), + sf("filter.pixelate.pointillize", json!({"cellSize": 7, "background": [1.0, 1.0, 1.0, 1.0]})), + sf("filter.pixelate.pointillize", json!({"cellSize": 300, "background": [0.0, 0.5, 1.0, 1.0]})), + sf("filter.other.offset", json!({"horizontal": 12, "vertical": -7, "undefinedAreas": "transparent"})), + sf("filter.other.custom", json!({"kernel": SHARPEN, "scale": 1, "offset": 0})), + sf("image.adjustments.levels", json!({"inBlack": 20, "inWhite": 220, "gamma": 1.4, "red": {"inBlack": 0, "inWhite": 255, "gamma": 0.8}})), + sf("image.adjustments.curves", json!({"points": [[0.0, 0.0], [64.0, 40.0], [255.0, 255.0]], "blue": [[0.0, 20.0], [255.0, 235.0]]})), + sf("image.adjustments.shadowsHighlights", json!({})), + sf("filter.sharpen.sharpen", json!({})), + // Photoshop stores Dust & Scratches' radius in whole pixels (a `long`). + sf("filter.noise.dustAndScratches", json!({"radius": 4, "threshold": 12})), + sf( + "image.adjustments.hueSaturation", + json!({"colorize": false, "hue": 10, "saturation": -20, "lightness": 5, "reds": {"hue": 5, "saturation": 0, "lightness": -3, "range": [315, 345, 15, 45]}}), + ), + // A pencil-drawn curve: 256 output levels (`Mpng`). + sf("image.adjustments.curves", json!({"pencil": true, "points": (0..256).rev().collect::>()})), + sf("filter.distort.pinch", json!({"amount": -28})), + sf("filter.distort.polarCoordinates", json!({"mode": "rectangularToPolar"})), + sf("filter.distort.ripple", json!({"amount": 250, "size": "small"})), + sf("filter.distort.spherize", json!({"amount": 60, "mode": "verticalOnly"})), + sf("filter.distort.twirl", json!({"angle": -355})), + sf( + "filter.distort.wave", + json!({"type": "square", "generators": 3, "wavelengthMin": 20, "wavelengthMax": 90, "amplitudeMin": 4, "amplitudeMax": 30, + "undefinedAreas": "repeat", "seed": 4_000_000_000u32}), + ), + sf("filter.distort.zigZag", json!({"amount": 30, "ridges": 7, "style": "aroundCenter"})), + sf("image.adjustments.invert", json!({})), + ]; + for mut f in filters.into_iter().chain(wind_extrude_tiles_settings()) { + f.blend = BlendMode::Overlay; + f.opacity = 0.75; + f.visible = false; + let d = item_for_filter(&f).unwrap(); + let bytes = d.to_bytes(); + let back = filter_from_item(&Descriptor::from_bytes(&bytes).unwrap()); + assert_eq!(back, f, "{}", f.command); + } +} + +/// The filters without options, their measured `filterID`s (as Photoshop wrote them). +const MEASURED_NO_OPTIONS: [(&str, i32); 11] = [ + ("filter.blur.blur", 1114403360), + ("filter.blur.blurMore", 1114403405), + ("filter.blur.average", 1098281575), + ("filter.noise.despeckle", 1148416099), + ("filter.stylize.findEdges", 1181639749), + ("filter.pixelate.facet", 1180922912), + ("filter.pixelate.fragment", 1181902701), + ("filter.sharpen.sharpen", 1399353968), + ("filter.sharpen.sharpenMore", 1399353933), + ("filter.sharpen.sharpenEdges", 1399353925), + ("filter.stylize.solarize", 1399616122), +]; + +/// A filter without options as Photoshop saves it: `hasoptions` false, no `Fltr`, a localized +/// name and the current colours. +fn photoshop_no_options_item(name: &str, filter_id: Value) -> Descriptor { + let rgb = |r: f64, g: f64, b: f64| { + Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(r)).with("Grn ", Value::Double(g)).with("Bl ", Value::Double(b))) + }; + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul(name))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 60.0)).with("Md ", enumv("BlnM", "Mltp")))) + .with("enab", Value::Boolean(false)) + .with("hasoptions", Value::Boolean(false)) + .with("FrgC", rgb(167.0, 157.0, 147.0)) + .with("BckC", rgb(255.0, 255.0, 255.0)) + .with("filterID", filter_id) +} + +#[test] +fn filters_without_options_round_trip_in_the_measured_shape() { + let keys = ["Nm ", "blendOptions", "enab", "hasoptions", "FrgC", "BckC", "filterID"]; + for (command, id) in MEASURED_NO_OPTIONS { + let mut f = sf(command, json!({})); + f.blend = BlendMode::Overlay; + f.opacity = 0.75; + f.visible = false; + let d = item_for_filter(&f).unwrap(); + let got: Vec = d.items.iter().map(|(k, _)| String::from_utf8_lossy(k.as_bytes()).into_owned()).collect(); + assert_eq!(got, keys, "{command}"); + assert_eq!(d.get("hasoptions"), Some(&Value::Boolean(false)), "{command}"); + assert_eq!(d.get("filterID"), Some(&Value::Integer(id)), "{command}"); + let back = filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()); + assert_eq!(back, f, "{command}"); + // Keys an old record may carry have no effect on these filters: still written. + let extra = item_for_filter(&sf(command, json!({"radius": 3.0, "layer": "L"}))).unwrap(); + assert_eq!(extra.get("filterID"), Some(&Value::Integer(id)), "{command}"); + for p in [json!(null), json!("x"), json!([1, 2])] { + assert!(item_for_filter(&sf(command, p)).is_ok(), "{command}"); + } + } +} + +#[test] +fn photoshop_filters_without_options_open_editable() { + for (command, id) in MEASURED_NO_OPTIONS { + let item = photoshop_no_options_item("Weichzeichnen", Value::Integer(id)); + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!(f.command, command); + assert_eq!(f.params, json!({})); + assert_eq!((f.visible, f.blend), (false, BlendMode::Multiply)); + assert!((f.opacity - 0.6).abs() < 1e-6); + } +} + +#[test] +fn malformed_filters_without_options_are_kept_verbatim() { + let blur = code(b"Blr "); + let cases = [ + // An id no filter has, a missing id, ids of the wrong type. + photoshop_no_options_item("X", Value::Integer(code(b"Zzzz"))), + Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)), + photoshop_no_options_item("X", Value::Double(f64::from(blur))), + photoshop_no_options_item("X", Value::Double(f64::NAN)), + photoshop_no_options_item("X", Value::Text(UnicodeString::new_nul("Blr "))), + photoshop_no_options_item("X", Value::Integer(-1)), + // Settings we don't know of on a filter that has none. + photoshop_no_options_item("X", Value::Integer(blur)).with("Fltr", Value::Descriptor(Descriptor::new("Blr ").with("Amnt", Value::Integer(5)))), + // Settings that aren't a descriptor, on a filter that has none. + photoshop_no_options_item("X", Value::Integer(blur)).with("Fltr", Value::Integer(5)), + photoshop_no_options_item("X", Value::Integer(blur)).with("Fltr", Value::Text(UnicodeString::new_nul("Blr "))), + photoshop_no_options_item("X", Value::Integer(781)).with("Fltr", Value::Integer(5)), + ]; + for item in cases { + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); + // Written back (a bare item gains blending and visibility) and still not editable. + let written = item_for_filter(&f).unwrap(); + assert_eq!(written.get("Fltr"), item.get("Fltr"), "{item:?}"); + let back = filter_from_item(&written); + assert_eq!((back.command.as_str(), &back.params["filterID"]), (UNSUPPORTED_FILTER, &f.params["filterID"])); + } +} + +/// Smart Sharpen's `Fltr` in the measured shape (no `presetKind`, no `Angl`). +fn smart_sharpen(amount: f64, radius: f64, noise: f64, blur: &str) -> Descriptor { + Descriptor::new("smartSharpen") + .with("useLegacy", Value::Boolean(false)) + .with("Amnt", unit(b"#Prc", amount)) + .with("Rds ", unit(b"#Pxl", radius)) + .with("noiseReduction", unit(b"#Prc", noise)) + .with("blur", enumv("blurType", blur)) +} + +fn dust(radius: i32, threshold: i32) -> Descriptor { + Descriptor::new("DstS").with("Rds ", Value::Integer(radius)).with("Thsh", Value::Integer(threshold)) +} + +/// The `Fltr` descriptor PhotoCraft writes for `f`, after a byte round trip. +fn written_fltr(f: &SmartFilter) -> Descriptor { + let d = Descriptor::from_bytes(&item_for_filter(f).unwrap().to_bytes()).unwrap(); + get_desc(&d, "Fltr").unwrap().clone() +} + +/// Measured in Photoshop: Smart Sharpen 120 %, 2.5 px, noise 5 %, Gaussian Blur +/// (filterID 1131); the default entry adds `presetKind` first, which is not kept. +#[test] +fn smart_sharpen_photoshop_entry_opens_and_writes_back() { + let fltr = smart_sharpen(120.0, 2.5, 5.0, "GsnB"); + let item = ps_item("Smart Sharpen...", fltr.clone(), 1131); + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!(f.command, "filter.sharpen.smartSharpen"); + assert_eq!(f.params, json!({"amount": 120.0, "radius": 2.5, "reduceNoise": 5.0})); + assert_eq!(written_fltr(&f), fltr); + let d = item_for_filter(&f).unwrap(); + assert_eq!(int(&d, "filterID"), Some(1131)); + assert_eq!(get_desc(&d, "Fltr").unwrap().class_id, Id::Str(b"smartSharpen".to_vec())); + // The four-character keys and enum values are codes, as Photoshop writes them. + let bytes = d.to_bytes(); + assert_eq!(count(&bytes, b"\0\0\0\0blurenum\0\0\0\x08blurType\0\0\0\0GsnB"), 1); + assert_eq!(count(&bytes, b"\0\0\0\0Rds UntF#Pxl"), 1); + + // With `presetKind` (any value): opens, but the params hold only the engine's own keys + // (it rejects unknown ones), and a re-save leaves it out as Photoshop does for explicit + // values. + for kind in ["presetKindDefault", "presetKindCustom", "Xxxx"] { + let mut with_preset = Descriptor::new("smartSharpen").with("presetKind", enumv("presetKindType", kind)); + with_preset.items.extend(smart_sharpen(200.0, 1.0, 10.0, "GsnB").items); + let f = filter_from_item(&Descriptor::from_bytes(&ps_item("Smart Sharpen...", with_preset, 1131).to_bytes()).unwrap()); + assert_eq!(f.command, "filter.sharpen.smartSharpen"); + let keys: Vec<&str> = f.params.as_object().unwrap().keys().map(String::as_str).collect(); + assert_eq!(keys.len(), 3, "{keys:?}"); + assert!(keys.iter().all(|k| ["amount", "radius", "reduceNoise"].contains(k)), "{keys:?}"); + assert_eq!(f.params, json!({"amount": 200.0, "radius": 1.0, "reduceNoise": 10.0})); + assert_eq!(written_fltr(&f), smart_sharpen(200.0, 1.0, 10.0, "GsnB")); + } + + // Without options PhotoCraft writes the engine's defaults, Gaussian Blur. + assert_eq!(written_fltr(&sf("filter.sharpen.smartSharpen", json!({}))), smart_sharpen(100.0, 1.0, 10.0, "GsnB")); +} + +/// Lens Blur (Photoshop's default), Motion Blur and legacy mode render differently from +/// PhotoCraft's Smart Sharpen, so those entries stay verbatim. +#[test] +fn smart_sharpen_settings_we_dont_render_stay_verbatim() { + let mut default_entry = Descriptor::new("smartSharpen").with("presetKind", enumv("presetKindType", "presetKindDefault")); + default_entry.items.extend(smart_sharpen(200.0, 1.0, 10.0, "lensBlur").items); + let motion = smart_sharpen(80.0, 1.5, 0.0, "MtnB").with("Angl", Value::Integer(30)); + let mut legacy = smart_sharpen(100.0, 1.0, 10.0, "GsnB"); + set(&mut legacy, "useLegacy", Value::Boolean(true)); + for fltr in [default_entry, motion, legacy] { + let item = ps_item("Smart Sharpen...", fltr, 1131); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(f.params["filterID"], 1131); + assert_eq!(item_for_filter(&f).unwrap(), item); + } +} + +#[test] +fn malformed_smart_sharpen_is_kept_verbatim() { + let g = || smart_sharpen(100.0, 1.0, 10.0, "GsnB"); + let without = |key: &str| { + let mut d = g(); + d.items.retain(|(k, _)| !k.is(key)); + d + }; + let with = |key: &str, v: Value| { + let mut d = g(); + set(&mut d, key, v); + d + }; + let cases = vec![ + without("useLegacy"), + without("Amnt"), + without("Rds "), + without("noiseReduction"), + without("blur"), + with("Amnt", Value::Double(100.0)), + with("Amnt", unit(b"#Pxl", 100.0)), + with("Rds ", Value::Integer(1)), + with("useLegacy", Value::Integer(0)), + with("Amnt", unit(b"#Prc", 0.0)), + with("Amnt", unit(b"#Prc", 501.0)), + with("Rds ", unit(b"#Pxl", 0.05)), + with("Rds ", unit(b"#Pxl", 65.0)), + with("Rds ", unit(b"#Pxl", f64::NAN)), + with("noiseReduction", unit(b"#Prc", -1.0)), + with("noiseReduction", unit(b"#Prc", f64::INFINITY)), + with("blur", enumv("blurType", "Xxxx")), + with("blur", enumv("BlrM", "GsnB")), + with("blur", Value::Integer(0)), + with("presetKind", Value::Integer(1)), + g().with("Angl", Value::Integer(30)), + g().with("shadowMode", Value::Descriptor(Descriptor::new("adaptCorrectTones"))), + ]; + for fltr in cases { + let item = ps_item("Smart Sharpen...", fltr, 1131); + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr")); + assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes()); + } + // No `Fltr` at all (hasoptions false). + let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(1131)); + assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); +} + +/// Measured in Photoshop: Dust & Scratches at its defaults (1, 0) and at 4, 20 (filterID +/// `DstS`, 1148417107; both settings `long`). +#[test] +fn dust_and_scratches_photoshop_entry_opens_and_writes_back() { + for (radius, threshold) in [(1, 0), (4, 20), (500, 255)] { + let fltr = dust(radius, threshold); + let item = ps_item("Dust & Scratches...", fltr.clone(), 1_148_417_107); + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!(f.command, "filter.noise.dustAndScratches"); + assert_eq!(f.params, json!({"radius": radius, "threshold": threshold})); + assert_eq!(written_fltr(&f), fltr); + assert_eq!(int(&item_for_filter(&f).unwrap(), "filterID"), Some(1_148_417_107)); + } + // No `Fltr` (hasoptions false): kept verbatim. + let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"DstS"))); + assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); +} + +#[test] +fn malformed_dust_and_scratches_is_kept_verbatim() { + let cases = vec![ + Descriptor::new("DstS").with("Thsh", Value::Integer(0)), + Descriptor::new("DstS").with("Rds ", Value::Integer(1)), + Descriptor::new("DstS").with("Rds ", Value::Double(1.0)).with("Thsh", Value::Integer(0)), + Descriptor::new("DstS").with("Rds ", unit(b"#Pxl", 1.0)).with("Thsh", Value::Integer(0)), + Descriptor::new("DstS").with("Rds ", Value::Integer(1)).with("Thsh", Value::Boolean(false)), + dust(0, 0), + dust(501, 0), + dust(1, -1), + dust(1, 256), + dust(i32::MIN, i32::MAX), + dust(1, 0).with("Xtra", Value::Integer(1)), + ]; + for fltr in cases { + let item = ps_item("Dust & Scratches...", fltr, code(b"DstS")); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr")); + assert_eq!(item_for_filter(&f).unwrap(), item); + } +} + +/// Every option's range ends round trip; hostile params are written in range (the engine +/// clamps the same way), never a panic. +#[test] +fn smart_sharpen_and_dust_option_values_round_trip() { + let mut cases = Vec::new(); + for amount in [1.0, 100.0, 500.0] { + for radius in [0.1, 1.0, 64.0] { + for noise in [0.0, 10.0, 100.0] { + cases.push(sf("filter.sharpen.smartSharpen", json!({"amount": amount, "radius": radius, "reduceNoise": noise}))); + } + } + } + for radius in [1, 2, 100, 500] { + for threshold in [0, 1, 128, 255] { + cases.push(sf("filter.noise.dustAndScratches", json!({"radius": radius, "threshold": threshold}))); + } + } + for f in cases { + let back = filter_from_item(&Descriptor::from_bytes(&item_for_filter(&f).unwrap().to_bytes()).unwrap()); + assert_eq!(back, f); + } + let defaults = json!({"amount": 100.0, "radius": 1.0, "reduceNoise": 10.0}); + for (command, p, want) in [ + ( + "filter.sharpen.smartSharpen", + json!({"amount": 1e9, "radius": -5.0, "reduceNoise": "x"}), + json!({"amount": 500.0, "radius": 0.1, "reduceNoise": 10.0}), + ), + ("filter.sharpen.smartSharpen", json!({"presetKind": "presetKindDefault", "amount": null}), defaults.clone()), + ("filter.sharpen.smartSharpen", json!(null), defaults.clone()), + ("filter.noise.dustAndScratches", json!({"radius": 2.4, "threshold": 1e12}), json!({"radius": 2, "threshold": 255})), + ("filter.noise.dustAndScratches", json!({"radius": -3, "threshold": -3}), json!({"radius": 1, "threshold": 0})), + ("filter.noise.dustAndScratches", json!([]), json!({"radius": 1, "threshold": 0})), + ] { + let back = filter_from_item(&item_for_filter(&sf(command, p.clone())).unwrap()); + assert_eq!((back.command.as_str(), &back.params), (command, &want), "{p}"); + } +} + +/// Every option value of Wind, Extrude and Tiles (and the ends of their ranges). +fn wind_extrude_tiles_settings() -> Vec { + let mut v = Vec::new(); + for method in ["wind", "blast", "stagger"] { + for direction in ["fromRight", "fromLeft"] { + v.push(sf("filter.stylize.wind", json!({"method": method, "direction": direction}))); + } + } + for t in ["blocks", "pyramids"] { + for mode in ["random", "levelBased"] { + for (solid, mask) in [(false, false), (true, false), (false, true), (true, true)] { + v.push(sf( + "filter.stylize.extrude", + json!({"type": t, "size": 7, "depth": 9, "depthMode": mode, "solidFrontFaces": solid, "maskIncompleteBlocks": mask}), + )); + } + } + } + v.push(sf( + "filter.stylize.extrude", + json!({"type": "blocks", "size": 2, "depth": 1, "depthMode": "random", "solidFrontFaces": false, "maskIncompleteBlocks": false}), + )); + v.push(sf( + "filter.stylize.extrude", + json!({"type": "pyramids", "size": 255, "depth": 255, "depthMode": "levelBased", "solidFrontFaces": true, "maskIncompleteBlocks": true}), + )); + for fill in ["background", "foreground", "inverse", "unaltered"] { + v.push(sf( + "filter.stylize.tiles", + json!({"count": 6, "maxOffset": 20, "fill": fill, "foreground": [1.0, 0.0, 0.5, 1.0], "background": [0.0, 0.5, 1.0, 1.0]}), + )); + } + for (count, offset) in [(1, 1), (99, 99)] { + v.push(sf( + "filter.stylize.tiles", + json!({"count": count, "maxOffset": offset, "fill": "background", "foreground": [0.0, 0.0, 0.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), + )); + } + v +} + +/// A `filterFX` entry shaped as Photoshop saves Wind, Extrude and Tiles (measured in Photoshop: +/// applied through Action Manager to a smart object, saved, `filterFX` read back): the item's +/// `FrgC`/`BckC` are the document colours, `Fltr` holds the settings, `filterID` the class code. +fn measured_item(fltr: Descriptor, fg: f64, bg: f64) -> Descriptor { + let id = code(fltr.class_id.as_bytes().try_into().unwrap()); + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Filter..."))) + .with("blendOptions", blend_options(&sf("", J::Null))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgbc(fg)) + .with("BckC", rgbc(bg)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(id)) +} + +/// The `Fltr` descriptors Photoshop 27 wrote for these filters (one smart object each, saved as +/// PSD and read back), with the settings PhotoCraft reads from them. +const PHOTOSHOP_FLTR: [(&str, &str, &str); 6] = [ + ("filter.distort.pinch", r#"{"amount":-28}"#, "0000000600500069006e00630068000000000000506e63680000000100000000416d6e746c6f6e67ffffffe4"), + ("filter.distort.twirl", r#"{"angle":-355}"#, "000000060054007700690072006c0000000000005477726c0000000100000000416e676c6c6f6e67fffffe9d"), + ( + "filter.distort.ripple", + r#"{"amount":-273,"size":"large"}"#, + "000000070052006900700070006c006500000000000052706c650000000200000000416d6e746c6f6e67fffffeef0000000052706c53656e756d0000000052706c53000000004c726720", + ), + ( + "filter.distort.spherize", + r#"{"amount":-1,"mode":"horizontalOnly"}"#, + "00000009005300700068006500720069007a0065000000000000537068720000000200000000416d6e746c6f6e67ffffffff000000005370684d656e756d000000005370684d0000000048727a4f", + ), + ( + "filter.distort.polarCoordinates", + r#"{"mode":"polarToRectangular"}"#, + "000000120050006f006c0061007200200043006f006f007200640069006e0061007400650073000000000000506c72200000000100000000436e7672656e756d00000000436e767200000000506c7252", + ), + ( + "filter.distort.zigZag", + r#"{"amount":-42,"ridges":11,"style":"pondRipples"}"#, + "00000007005a00690067005a006100670000000000005a675a670000000300000000416d6e746c6f6e67ffffffd6000000004e6d62526c6f6e670000000b000000005a5a5479656e756d000000005a5a547900000000506e6452", + ), +]; + +/// Photoshop's Wave with Scale 100% / 28%: PhotoCraft's Wave has no Scale. +const PHOTOSHOP_WAVE: &str = "000000050057006100760065000000000000576176650000000a0000000057767470656e756d00000000577674700000000057765472000000004e6d62476c6f6e670000014c00000000574c4d6e6c6f6e67000000d500000000574c4d786c6f6e67000000d600000000416d4d6e6c6f6e67000000f000000000416d4d786c6f6e67000000f10000000053636c486c6f6e67000000640000000053636c566c6f6e670000001c00000000556e6441656e756d00000000556e6441000000005772704100000000526e64536c6f6e670013624a"; + +/// A `filterFX` list item as Photoshop writes it (enabled, Normal at 100%, with options), wrapping the `Fltr` descriptor `fltr`. +fn photoshop_fltr_item(fltr: Descriptor) -> Descriptor { + let id = code(fltr.class_id.as_bytes().try_into().unwrap()); + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("from Photoshop"))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(id)) +} + +fn wind(method: &str, direction: &str) -> Descriptor { + Descriptor::new("Wnd ").with("WndM", enumv("WndM", method)).with("Drct", enumv("Drct", direction)) +} + +fn extrude(t: &str, size: Value, depth: Value, mode: &str, solid: Value, mask: Value) -> Descriptor { + Descriptor::new("Extr") + .with("ExtT", enumv("ExtT", t)) + .with("ExtS", size) + .with("ExtD", depth) + .with("ExtR", enumv("ExtR", mode)) + .with("ExtF", solid) + .with("ExtM", mask) +} + +fn tiles(count: Value, offset: Value, fill: &str) -> Descriptor { + Descriptor::new("Tls ").with("TlNm", count).with("TlOf", offset).with("FlCl", enumv("FlCl", fill)) +} + +#[test] +fn wind_extrude_tiles_open_from_photoshop_shapes() { + let (long, yes, no) = (Value::Integer, Value::Boolean(true), Value::Boolean(false)); + let cases = [ + // The measured files. + (wind("Blst", "Left"), "filter.stylize.wind", json!({"method": "blast", "direction": "fromRight"})), + (wind("Stgr", "Rght"), "filter.stylize.wind", json!({"method": "stagger", "direction": "fromLeft"})), + (wind("Wnd ", "Rght"), "filter.stylize.wind", json!({"method": "wind", "direction": "fromLeft"})), + ( + extrude("Blks", long(7), long(9), "Rndm", yes.clone(), no.clone()), + "filter.stylize.extrude", + json!({"type": "blocks", "size": 7, "depth": 9, "depthMode": "random", "solidFrontFaces": true, "maskIncompleteBlocks": false}), + ), + ( + extrude("Pyrm", long(12), long(20), "LvlB", no, yes), + "filter.stylize.extrude", + json!({"type": "pyramids", "size": 12, "depth": 20, "depthMode": "levelBased", "solidFrontFaces": false, "maskIncompleteBlocks": true}), + ), + ( + tiles(long(6), long(20), "FlFr"), + "filter.stylize.tiles", + json!({"count": 6, "maxOffset": 20, "fill": "foreground", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), + ), + ( + tiles(long(4), long(5), "FlIn"), + "filter.stylize.tiles", + json!({"count": 4, "maxOffset": 5, "fill": "inverse", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), + ), + ( + tiles(long(10), long(10), "FlBc"), + "filter.stylize.tiles", + json!({"count": 10, "maxOffset": 10, "fill": "background", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), + ), + ( + tiles(long(99), long(1), "FlSm"), + "filter.stylize.tiles", + json!({"count": 99, "maxOffset": 1, "fill": "unaltered", "foreground": [0.2, 0.2, 0.2, 1.0], "background": [1.0, 1.0, 1.0, 1.0]}), + ), + ]; + for (fltr, command, params) in cases { + let item = measured_item(fltr, 51.0, 255.0); + // Through bytes, as read from a file. + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!((f.command.as_str(), &f.params), (command, ¶ms)); + // Written back in the measured shape: same class, keys and their order, value types + // (long, bool, enum with its type), filterID; Tiles also its colours. + let back = item_for_filter(&f).unwrap(); + assert_eq!(get_desc(&back, "Fltr").map(Descriptor::to_bytes), get_desc(&item, "Fltr").map(Descriptor::to_bytes), "{command}"); + assert_eq!(back.get("filterID"), item.get("filterID"), "{command}"); + if command == "filter.stylize.tiles" { + assert_eq!((back.get("FrgC"), back.get("BckC")), (item.get("FrgC"), item.get("BckC"))); + } + } + // The class codes: numeric filterIDs of the four-char classes. + for (c, id) in [("filter.stylize.wind", 1466852384), ("filter.stylize.extrude", 1165522034), ("filter.stylize.tiles", 1416393504)] { + assert_eq!(item_for_filter(&sf(c, json!({}))).unwrap().get("filterID"), Some(&Value::Integer(id))); + } + // A filter found by its filterID alone (no `Fltr` class to go by) still needs its settings. + let bare = Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)).with("filterID", Value::Integer(1466852384)); + assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); + // Only Tiles reads the entry's colours; Wind and Extrude write the defaults. + let f = filter_from_item(&measured_item(wind("Wnd ", "Left"), 51.0, 0.0)); + assert_eq!(f.params, json!({"method": "wind", "direction": "fromRight"})); + let back = item_for_filter(&f).unwrap(); + assert_eq!((back.get("FrgC"), back.get("BckC")), (Some(&rgbc(0.0)), Some(&rgbc(255.0)))); + // Tiles without colours in its params (or the entry) writes the engine's black and white. + let f = filter_from_item(&Descriptor::new("filterFX").with("Fltr", Value::Descriptor(tiles(long(4), long(5), "FlBc")))); + assert_eq!(f.params, json!({"count": 4, "maxOffset": 5, "fill": "background"})); + let back = item_for_filter(&f).unwrap(); + assert_eq!((back.get("FrgC"), back.get("BckC")), (Some(&rgbc(0.0)), Some(&rgbc(255.0)))); +} + +#[test] +fn wind_extrude_tiles_write_defaults_and_photoshop_ranges() { + let fltr = |c: &str, p: J| match item_for_filter(&sf(c, p)).unwrap().get("Fltr") { + Some(Value::Descriptor(d)) => d.clone(), + other => panic!("no Fltr: {other:?}"), + }; + let long = Value::Integer; + let (yes, no) = (Value::Boolean(true), Value::Boolean(false)); + // Defaults are the engine's; our random seed has no PSD key and is not written. + assert_eq!(fltr("filter.stylize.wind", json!({"seed": 9})), wind("Wnd ", "Left")); + assert_eq!(fltr("filter.stylize.extrude", json!({"seed": 9})), extrude("Blks", long(30), long(30), "Rndm", no.clone(), no.clone())); + assert_eq!(fltr("filter.stylize.tiles", json!({"seed": 9})), tiles(long(10), long(10), "FlBc")); + // Out of range, fractional, non-numeric and non-bool values as the engine reads them. + assert_eq!( + fltr("filter.stylize.extrude", json!({"size": 1e12, "depth": -5, "solidFrontFaces": "yes", "maskIncompleteBlocks": true})), + extrude("Blks", long(255), long(1), "Rndm", no.clone(), yes) + ); + assert_eq!(fltr("filter.stylize.tiles", json!({"count": 0, "maxOffset": 12.6})), tiles(long(1), long(13), "FlBc")); + assert_eq!(fltr("filter.stylize.tiles", json!({"count": "many", "maxOffset": 1000})), tiles(long(10), long(99), "FlBc")); + assert_eq!(fltr("filter.stylize.extrude", json!({"size": f64::NAN})), extrude("Blks", long(30), long(30), "Rndm", no.clone(), no)); +} + +#[test] +fn malformed_wind_extrude_tiles_are_kept_verbatim() { + let long = Value::Integer; + let (yes, no) = (Value::Boolean(true), Value::Boolean(false)); + let cases = [ + // Missing keys. + Descriptor::new("Wnd "), + Descriptor::new("Wnd ").with("WndM", enumv("WndM", "Blst")), + Descriptor::new("Wnd ").with("Drct", enumv("Drct", "Left")), + Descriptor::new("Extr").with("ExtT", enumv("ExtT", "Blks")).with("ExtS", long(7)).with("ExtD", long(9)).with("ExtR", enumv("ExtR", "Rndm")), + Descriptor::new("Tls ").with("TlNm", long(6)).with("TlOf", long(20)), + Descriptor::new("Tls ").with("TlNm", long(6)).with("FlCl", enumv("FlCl", "FlFr")), + // Unknown enum values and enum types (Photoshop falls back to a default for these; + // we keep them as they are rather than guess). + wind("Wild", "Left"), + wind("Blst", "Up "), + Descriptor::new("Wnd ").with("WndM", enumv("Drct", "Blst")).with("Drct", enumv("Drct", "Left")), + extrude("Cube", long(7), long(9), "Rndm", yes.clone(), no.clone()), + extrude("Blks", long(7), long(9), "Sine", yes.clone(), no.clone()), + tiles(long(6), long(20), "FlXx"), + Descriptor::new("Tls ").with("TlNm", long(6)).with("TlOf", long(20)).with("FlCl", enumv("BlnM", "FlFr")), + // Wrong types (also NaN). + Descriptor::new("Wnd ").with("WndM", long(1)).with("Drct", enumv("Drct", "Left")), + extrude("Blks", Value::Double(7.0), long(9), "Rndm", yes.clone(), no.clone()), + extrude("Blks", long(7), unit(b"#Pxl", 9.0), "Rndm", yes.clone(), no.clone()), + extrude("Blks", long(7), long(9), "Rndm", long(1), no.clone()), + extrude("Blks", long(7), long(9), "Rndm", yes.clone(), Value::Double(f64::NAN)), + tiles(Value::Double(f64::NAN), long(20), "FlFr"), + tiles(long(6), Value::Text(UnicodeString::new_nul("20")), "FlFr"), + // Out of range. + extrude("Blks", long(1), long(9), "Rndm", yes.clone(), no.clone()), + extrude("Blks", long(256), long(9), "Rndm", yes.clone(), no.clone()), + extrude("Blks", long(7), long(0), "Rndm", yes.clone(), no.clone()), + extrude("Blks", long(7), long(i32::MAX), "Rndm", yes, no), + tiles(long(0), long(20), "FlFr"), + tiles(long(100), long(20), "FlFr"), + tiles(long(6), long(0), "FlFr"), + tiles(long(6), long(i32::MIN), "FlFr"), + ]; + for fltr in cases { + let item = measured_item(fltr, 0.0, 255.0); + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); + assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes()); + } + // A Tiles entry whose colour is unreadable is kept verbatim too. + for (key, bad) in [ + ("FrgC", Value::Integer(3)), + ("BckC", Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)))), + ( + "BckC", + Value::Descriptor( + Descriptor::new("RGBC").with("Rd ", Value::Double(f64::NAN)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0)), + ), + ), + ] { + let mut item = measured_item(tiles(long(6), long(20), "FlFr"), 0.0, 255.0); + set(&mut item, key, bad); + assert_eq!(filter_from_item(&item).command, UNSUPPORTED_FILTER); + } + // Values with no PSD equivalent are reported, not guessed. + for (c, p) in [ + ("filter.stylize.wind", json!({"method": "gale"})), + ("filter.stylize.wind", json!({"direction": "fromTop"})), + ("filter.stylize.wind", json!({"direction": 1})), + ("filter.stylize.extrude", json!({"type": "cubes"})), + ("filter.stylize.extrude", json!({"depthMode": null})), + ("filter.stylize.tiles", json!({"fill": "transparent"})), + ("filter.stylize.tiles", json!({"foreground": "teal"})), + ("filter.stylize.tiles", json!({"background": [1.0]})), + ("filter.stylize.tiles", json!({"background": [f64::NAN, 0.0, 0.0]})), + ] { + assert!(item_for_filter(&sf(c, p.clone())).is_err(), "{c} {p}"); + } +} + +/// Photoshop's default Custom kernel: a 3 × 3 sharpen centred in the 5 × 5. +const SHARPEN: [i32; 25] = [0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 5, -1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0]; + +/// A `filterFXList` item as measured in Photoshop (applied through Action Manager to a smart +/// object, saved, `filterFX` read back). +fn measured_named_item(id: &[u8; 4], name: &str, fltr: Descriptor) -> Descriptor { + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul(name))) + .with("blendOptions", blend_options(&sf("", J::Null))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgbc(0.0)) + .with("BckC", rgbc(255.0)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(code(id))) +} + +fn offset_fltr(h: Value, v: Value, fill: Value) -> Descriptor { + Descriptor::new("Ofst").with("Hrzn", h).with("Vrtc", v).with("Fl ", fill) +} + +fn custom_fltr(scale: Value, offset: Value, m: Vec) -> Descriptor { + Descriptor::new("Cstm").with("Scl ", scale).with("Ofst", offset).with("Mtrx", Value::List(m)) +} + +fn longs(m: &[i32]) -> Vec { + m.iter().map(|v| Value::Integer(*v)).collect() +} + +#[test] +fn offset_round_trips_every_fill_mode() { + for (fill, ours) in [("Wrp ", "wrap"), ("Rpt ", "repeat"), ("Bckg", "transparent")] { + for (h, v) in [(0, 0), (12, -7), (5, 3), (i32::MIN, i32::MAX)] { + let f = sf("filter.other.offset", json!({"horizontal": h, "vertical": v, "undefinedAreas": ours})); + let d = item_for_filter(&f).unwrap(); + let fltr = get_desc(&d, "Fltr").unwrap(); + assert_eq!(*fltr, offset_fltr(Value::Integer(h), Value::Integer(v), enumv("FlMd", fill))); + assert_eq!(int(&d, "filterID"), Some(1_332_114_292)); + assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); + } + } +} + +/// The measured descriptors (Wrap 0/0, Set to Background 12/−7, Repeat 5/3) open as Offset. +#[test] +fn offset_measured_descriptors_open_as_offset() { + for (h, v, fill, ours) in [(0, 0, "Wrp ", "wrap"), (12, -7, "Bckg", "transparent"), (5, 3, "Rpt ", "repeat")] { + let item = measured_named_item(b"Ofst", "Offset...", offset_fltr(Value::Integer(h), Value::Integer(v), enumv("FlMd", fill))); + let f = filter_from_item(&item); + assert_eq!(f.command, "filter.other.offset"); + assert_eq!(f.params, json!({"horizontal": h, "vertical": v, "undefinedAreas": ours})); + // Written back exactly as measured. + assert_eq!(item_for_filter(&f).unwrap(), item); + } +} + +#[test] +fn offset_written_with_engine_defaults() { + // No params: 0, 0, Wrap Around (the engine's defaults); fractional pixels round. + let d = item_for_filter(&sf("filter.other.offset", json!({}))).unwrap(); + assert_eq!(*get_desc(&d, "Fltr").unwrap(), offset_fltr(Value::Integer(0), Value::Integer(0), enumv("FlMd", "Wrp "))); + let d = item_for_filter(&sf("filter.other.offset", json!({"horizontal": 2.6, "vertical": 3e12, "undefinedAreas": "bogus"}))).unwrap(); + assert_eq!(*get_desc(&d, "Fltr").unwrap(), offset_fltr(Value::Integer(3), Value::Integer(i32::MAX), enumv("FlMd", "Wrp "))); +} + +#[test] +fn malformed_offset_is_kept_verbatim() { + let i = Value::Integer; + for fltr in [ + offset_fltr(i(1), i(2), enumv("FlMd", "Xxxx")), + offset_fltr(i(1), i(2), Value::Integer(1)), + offset_fltr(Value::Double(1.5), i(2), enumv("FlMd", "Wrp ")), + offset_fltr(i(1), unit(b"#Pxl", f64::NAN), enumv("FlMd", "Wrp ")), + Descriptor::new("Ofst").with("Hrzn", i(1)).with("Fl ", enumv("FlMd", "Wrp ")), + Descriptor::new("Ofst"), + // A mistyped enum, a setting we don't write back and a repeated one. + offset_fltr(i(1), i(2), enumv("Xxxx", "Wrp ")), + offset_fltr(i(1), i(2), enumv("FlMd", "Wrp ")).with("Xtra", i(1)), + offset_fltr(i(1), i(2), enumv("FlMd", "Wrp ")).with("Hrzn", i(3)), + ] { + let item = measured_named_item(b"Ofst", "Offset...", fltr); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); + assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "kept byte for byte"); + } + let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"Ofst"))); + assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); +} + +#[test] +fn custom_round_trips() { + let edge: Vec = (0..25) + .map(|i| { + if i == 12 { + 8 + } else if (6..=18).contains(&i) && i % 5 != 0 && i % 5 != 4 { + -1 + } else { + 0 + } + }) + .collect(); + let full: Vec = (0..25).map(|i| i * 83 - 999).collect(); + for (kernel, scale, offset) in [(SHARPEN.to_vec(), 1, 0), (edge, 2, 10), (full, 9999, -9999), (vec![999; 25], 1, 9999)] { + let f = sf("filter.other.custom", json!({"kernel": kernel, "scale": scale, "offset": offset})); + let d = item_for_filter(&f).unwrap(); + assert_eq!(*get_desc(&d, "Fltr").unwrap(), custom_fltr(Value::Integer(scale), Value::Integer(offset), longs(&kernel))); + assert_eq!(int(&d, "filterID"), Some(1_131_639_917)); + assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); + } +} + +/// The measured descriptors (the default sharpen; a blur at Scale 2, Offset 10) open as Custom. +#[test] +fn custom_measured_descriptors_open_as_custom() { + let blur = [0, 0, 0, 0, 0, 0, 1, 2, 1, 0, 0, 2, 4, 2, 0, 0, 1, 2, 1, 0, 0, 0, 0, 0, 0]; + for (kernel, scale, offset) in [(SHARPEN, 1, 0), (blur, 2, 10)] { + let item = measured_named_item(b"Cstm", "Custom...", custom_fltr(Value::Integer(scale), Value::Integer(offset), longs(&kernel))); + let f = filter_from_item(&item); + assert_eq!(f.command, "filter.other.custom"); + assert_eq!(f.params, json!({"kernel": kernel, "scale": scale, "offset": offset})); + assert_eq!(item_for_filter(&f).unwrap(), item); + } +} + +#[test] +fn custom_written_like_the_engine_reads_it() { + let fltr = |p: J| get_desc(&item_for_filter(&sf("filter.other.custom", p)).unwrap(), "Fltr").cloned().unwrap(); + // No kernel: the engine's identity; short kernels pad with 0; out-of-range values clamp. + let mut id = [0; 25]; + id[12] = 1; + assert_eq!(fltr(json!({})), custom_fltr(Value::Integer(1), Value::Integer(0), longs(&id))); + let mut short = [0; 25]; + short[0] = 3; + short[1] = -999; + assert_eq!(fltr(json!({"kernel": [3, -5000], "scale": 0, "offset": 20000})), custom_fltr(Value::Integer(1), Value::Integer(9999), longs(&short))); + // Fractions have no PSD equivalent. + for p in [json!({"kernel": [0.5]}), json!({"scale": 1.5}), json!({"offset": -0.25})] { + assert!(item_for_filter(&sf("filter.other.custom", p.clone())).is_err(), "{p}"); + } +} + +#[test] +fn malformed_custom_is_kept_verbatim() { + let i = Value::Integer; + let mut wrong_type = longs(&SHARPEN); + wrong_type[3] = Value::Double(1.0); + for fltr in [ + custom_fltr(i(1), i(0), longs(&SHARPEN[..24])), + custom_fltr(i(1), i(0), longs(&[0; 26])), + custom_fltr(i(1), i(0), wrong_type), + custom_fltr(i(1), i(0), longs(&[1000; 25])), + custom_fltr(i(0), i(0), longs(&SHARPEN)), + custom_fltr(i(10_000), i(0), longs(&SHARPEN)), + custom_fltr(i(1), i(-10_000), longs(&SHARPEN)), + custom_fltr(Value::Double(f64::NAN), i(0), longs(&SHARPEN)), + custom_fltr(i(1), unit(b"#Pxl", 1.0), longs(&SHARPEN)), + Descriptor::new("Cstm").with("Scl ", i(1)).with("Ofst", i(0)).with("Mtrx", i(5)), + Descriptor::new("Cstm").with("Scl ", i(1)).with("Mtrx", Value::List(longs(&SHARPEN))), + Descriptor::new("Cstm"), + // A setting we don't write back. + custom_fltr(i(1), i(0), longs(&SHARPEN)).with("Xtra", i(1)), + ] { + let item = measured_named_item(b"Cstm", "Custom...", fltr); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); + assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "kept byte for byte"); + } +} + +/// A `filterFX` item holding `fltr`, as Photoshop writes a filter with options. +fn pixelate_item(name: &str, fltr: Descriptor, filter_id: i32) -> Descriptor { + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul(name))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "Nrml")))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgbc(0.0)) + .with("BckC", rgbc(255.0)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(filter_id)) +} + +#[test] +fn mezzotint_round_trips_every_type_and_reads_photoshops_shape() { + for (code, ty) in MEZZOTINT_TYPES { + let f = sf("filter.pixelate.mezzotint", json!({"type": ty})); + let d = item_for_filter(&f).unwrap(); + assert_eq!(int(&d, "filterID"), Some(1_299_870_830)); + let fltr = get_desc(&d, "Fltr").unwrap(); + assert!(fltr.class_id.is("Mztn")); + assert_eq!(enum_of(fltr, "MztT"), Some(&code[..])); + assert!(matches!(fltr.get("MztT"), Some(Value::Enumerated { type_id, .. }) if type_id.is("MztT"))); + assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f, "{ty}"); + } + // Measured in Photoshop: `{'_class': 'Mztn', 'MztT': 'MztT.CrsD'}` and `LngS`, filterID 1299870830. + for (code, ty) in [("CrsD", "coarseDots"), ("LngS", "longStrokes")] { + let item = pixelate_item("Mezzotint...", Descriptor::new("Mztn").with("MztT", enumv("MztT", code)), 1_299_870_830); + let f = filter_from_item(&item); + assert_eq!((f.command.as_str(), &f.params), ("filter.pixelate.mezzotint", &json!({"type": ty}))); + } + // No type or an unknown type is Fine Dots, like the engine; the seed + // (PhotoCraft only) is not saved. + for p in [json!({}), json!({"type": "sparkles"}), json!({"type": "fineDots", "seed": 77})] { + let d = item_for_filter(&sf("filter.pixelate.mezzotint", p)).unwrap(); + let fltr = get_desc(&d, "Fltr").unwrap(); + assert_eq!(enum_of(fltr, "MztT"), Some(&b"FnDt"[..])); + assert_eq!(fltr.items.len(), 1); + } +} + +#[test] +fn color_halftone_round_trips_and_reads_photoshops_shape() { + for p in [ + json!({"maxRadius": 8, "channel1": 108, "channel2": 162, "channel3": 90, "channel4": 45}), + json!({"maxRadius": 4, "channel1": -360, "channel2": 0, "channel3": 360, "channel4": -45}), + json!({"maxRadius": 127, "channel1": 1, "channel2": 2, "channel3": 3, "channel4": 4}), + ] { + let f = sf("filter.pixelate.colorHalftone", p); + let d = item_for_filter(&f).unwrap(); + assert_eq!(int(&d, "filterID"), Some(1_131_180_616)); + let fltr = get_desc(&d, "Fltr").unwrap(); + assert!(fltr.class_id.is("ClrH")); + for k in ["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"] { + assert!(matches!(fltr.get(k), Some(Value::Integer(_))), "{k} is a long"); + } + assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); + } + // Measured in Photoshop: `{'_class': 'ClrH', 'Rds ': 6, 'Ang1': 10, 'Ang2': 20, 'Ang3': 30, 'Ang4': 40}`. + let measured = Descriptor::new("ClrH") + .with("Rds ", Value::Integer(6)) + .with("Ang1", Value::Integer(10)) + .with("Ang2", Value::Integer(20)) + .with("Ang3", Value::Integer(30)) + .with("Ang4", Value::Integer(40)); + let item = pixelate_item("Color Halftone...", measured.clone(), 1_131_180_616); + let f = filter_from_item(&item); + assert_eq!(f.command, "filter.pixelate.colorHalftone"); + assert_eq!(f.params, json!({"maxRadius": 6, "channel1": 10, "channel2": 20, "channel3": 30, "channel4": 40})); + assert_eq!(get_desc(&item_for_filter(&f).unwrap(), "Fltr"), Some(&measured)); + // Defaults and hostile values write longs within the dialog's ranges. + let d = item_for_filter(&sf("filter.pixelate.colorHalftone", json!({"maxRadius": f64::NAN, "channel1": 1e12, "channel2": -1e12, "channel3": "x"}))) + .unwrap(); + let fltr = get_desc(&d, "Fltr").unwrap(); + let got: Vec<_> = ["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"].iter().map(|k| int(fltr, k)).collect(); + assert_eq!(got, [Some(8), Some(360), Some(-360), Some(90), Some(45)]); +} + +#[test] +fn malformed_pixelate_filters_stay_verbatim() { + let mz = |v: Value| Descriptor::new("Mztn").with("MztT", v); + let ch = |rds: Value, ang1: Value| { + Descriptor::new("ClrH") + .with("Rds ", rds) + .with("Ang1", ang1) + .with("Ang2", Value::Integer(20)) + .with("Ang3", Value::Integer(30)) + .with("Ang4", Value::Integer(40)) + }; + let cases = [ + pixelate_item("Mezzotint...", Descriptor::new("Mztn"), code(b"Mztn")), + pixelate_item("Mezzotint...", mz(enumv("MztT", "Sprk")), code(b"Mztn")), + pixelate_item("Mezzotint...", mz(Value::Integer(1)), code(b"Mztn")), + pixelate_item("Color Halftone...", Descriptor::new("ClrH"), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(Value::Double(6.0), Value::Integer(10)), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(unit(b"#Pxl", 6.0), Value::Integer(10)), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(Value::Integer(3), Value::Integer(10)), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(Value::Integer(128), Value::Integer(10)), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(361)), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(i32::MIN)), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Double(f64::NAN)), code(b"ClrH")), + // A mistyped enum and settings we don't write back. + pixelate_item("Mezzotint...", mz(enumv("Xxxx", "FnDt")), code(b"Mztn")), + pixelate_item("Mezzotint...", mz(enumv("MztT", "FnDt")).with("Xtra", Value::Integer(1)), code(b"Mztn")), + pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(10)).with("Xtra", Value::Integer(1)), code(b"ClrH")), + pixelate_item("Color Halftone...", ch(Value::Integer(6), Value::Integer(10)).with("Ang1", Value::Integer(11)), code(b"ClrH")), + ]; + for item in cases { + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{:?}", get_desc(&item, "Fltr")); + // Written back with its own settings (blending is rewritten from the model). + let back = item_for_filter(&f).unwrap(); + // Compared as bytes: a NaN setting is not equal to itself. + let fltr = |d: &Descriptor| get_desc(d, "Fltr").map(Descriptor::to_bytes); + assert_eq!((fltr(&back), int(&back, "filterID")), (fltr(&item), int(&item, "filterID"))); + } + // Without a `Fltr` the filter has no settings to read: kept verbatim too. + let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"ClrH"))); + assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); +} + +/// Distort smart filters from a Photoshop file open as their PhotoCraft filters, and the ones +/// PhotoCraft writes carry the same settings, keys and order as Photoshop's. +#[test] +fn photoshop_distort_filters_read_and_write_like_photoshop() { + for (command, params, hex) in PHOTOSHOP_FLTR { + let ps = Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap(); + let f = filter_from_item(&photoshop_fltr_item(ps.clone())); + let want: J = serde_json::from_str(params).unwrap(); + assert_eq!((f.command.as_str(), &f.params), (command, &want), "{command}"); + let ours = match item_for_filter(&f).unwrap().get("Fltr") { + Some(Value::Descriptor(d)) => d.clone(), + other => panic!("{command}: no Fltr ({other:?})"), + }; + assert_eq!((&ours.class_id, &ours.items), (&ps.class_id, &ps.items), "{command}: same keys, values and order"); + } + // A scaled wave can't be modelled, so it stays Photoshop's, unchanged. + let wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap(); + let item = photoshop_fltr_item(wave); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr")); + // Unscaled, but with 332 generators (the renderer draws 64 at most), it stays Photoshop's too. + let mut unscaled = match item.get("Fltr") { + Some(Value::Descriptor(d)) => d.clone(), + other => panic!("wave: no Fltr ({other:?})"), + }; + set(&mut unscaled, "SclV", Value::Integer(100)); + let item = photoshop_fltr_item(unscaled); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr")); + + // An extra or repeated setting PhotoCraft doesn't model keeps the filter Photoshop's, unchanged. + let mut fltrs: Vec = PHOTOSHOP_FLTR.iter().map(|(_, _, hex)| Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap()).collect(); + let mut wave = unscaled_wave(); + set(&mut wave, "NmbG", Value::Integer(5)); + assert_eq!(filter_from_item(&photoshop_fltr_item(wave.clone())).command, "filter.distort.wave", "the plain wave maps"); + fltrs.push(wave); + for ps in fltrs { + let name = String::from_utf8_lossy(ps.class_id.as_bytes()).into_owned(); + let mut repeated = ps.clone(); + repeated.items.push(ps.items[0].clone()); + for odd in [ps.clone().with("Xtra", Value::Integer(7)), repeated] { + let item = photoshop_fltr_item(odd); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{name}"); + assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"), "{name}: written back unchanged"); + } + } +} + +/// Photoshop's Wave ([`PHOTOSHOP_WAVE`]) at 100% scale both ways. +fn unscaled_wave() -> Descriptor { + let mut wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap(); + set(&mut wave, "SclV", Value::Integer(100)); + wave +} + +/// An unscaled Wave opens as PhotoCraft's Wave (Triangle, the other settings as stored) up to +/// the generators the renderer models; one more and it stays Photoshop's, unchanged. +#[test] +fn wave_maps_up_to_the_generators_the_renderer_models() { + let max = i32::try_from(photocraft_algo::MAX_WAVE_GENERATORS).unwrap(); + assert_eq!(max, 64); + let mut wave = Descriptor::from_bytes(&from_hex(PHOTOSHOP_WAVE).unwrap()).unwrap(); + set(&mut wave, "SclV", Value::Integer(100)); + for (generators, mapped) in [(1, true), (max, true), (max + 1, false), (999, false), (0, false), (-1, false)] { + set(&mut wave, "NmbG", Value::Integer(generators)); + let item = photoshop_fltr_item(wave.clone()); + let f = filter_from_item(&item); + if mapped { + assert_eq!( + (f.command.as_str(), &f.params), + ( + "filter.distort.wave", + &json!({"type": "triangle", "generators": generators, "wavelengthMin": 213, "wavelengthMax": 214, "amplitudeMin": 240, + "amplitudeMax": 241, "undefinedAreas": "wrap", "seed": 1270346}) + ), + "{generators} generators" + ); + match item_for_filter(&f).unwrap().get("Fltr") { + Some(Value::Descriptor(ours)) => assert_eq!((&ours.class_id, &ours.items), (&wave.class_id, &wave.items), "{generators} generators"), + other => panic!("wave: no Fltr ({other:?})"), + } + } else { + assert_eq!(f.command, UNSUPPORTED_FILTER, "{generators} generators"); + assert_eq!(item_for_filter(&f).unwrap().get("Fltr"), item.get("Fltr"), "{generators} generators"); + } + } +} + +/// PhotoCraft draws at most `MAX_WAVE_GENERATORS` generators, so a Wave edited past that exports +/// the 64 it rendered, and a count below 1 exports 1, instead of Photoshop drawing more. +#[test] +fn wave_export_writes_only_the_generators_the_renderer_draws() { + let max = i32::try_from(photocraft_algo::MAX_WAVE_GENERATORS).unwrap(); + for (stored, written) in [(100, max), (999, max), (max + 1, max), (max, max), (5, 5), (1, 1), (0, 1), (-3, 1)] { + let wave = sf( + "filter.distort.wave", + json!({"type": "sine", "generators": stored, "wavelengthMin": 20, "wavelengthMax": 90, "amplitudeMin": 4, "amplitudeMax": 30}), + ); + let fltr = match item_for_filter(&wave).unwrap().get("Fltr") { + Some(Value::Descriptor(d)) => d.clone(), + other => panic!("wave: no Fltr ({other:?})"), + }; + assert_eq!(int(&fltr, "NmbG"), Some(written), "{stored} generators"); + } +} + +/// `RndS` is the seed the renderer draws with, also for a legacy signed or fractional seed +/// (stored as is by `layer.smartFilter.setParams`), not 0. +#[test] +fn wave_export_writes_the_seed_the_renderer_draws() { + for (stored, written) in [ + (json!(77), 77), + (json!(4_000_000_000u32), -294_967_296), + (json!(-1), -1), + (json!(7.4), 7), + (json!(-2.6), -3), + (json!(1e12), i32::MAX), + (json!("x"), 0), + ] { + let wave = sf("filter.distort.wave", json!({"generators": 3, "seed": stored})); + let fltr = match item_for_filter(&wave).unwrap().get("Fltr") { + Some(Value::Descriptor(d)) => d.clone(), + other => panic!("wave: no Fltr ({other:?})"), + }; + assert_eq!(int(&fltr, "RndS"), Some(written), "seed {stored}"); + // And it reads back as that bit pattern. + assert_eq!(known_params("Wave", Some(&fltr), &Descriptor::new("filterFX")).unwrap().1["seed"], json!(written as u32), "seed {stored}"); + } +} + +/// Invert on a smart object: Photoshop stores no `Fltr`, `hasoptions` false and its filter id. +#[test] +fn invert_smart_filter_reads_and_writes_like_photoshop() { + let item = Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Invert"))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(false)) + .with("FrgC", rgbc(255.0)) + .with("BckC", rgbc(0.0)) + .with("filterID", Value::Integer(code(b"Invr"))); + let f = filter_from_item(&item); + assert_eq!((f.command.as_str(), &f.params), ("image.adjustments.invert", &json!({}))); + let back = item_for_filter(&f).unwrap(); + assert_eq!(back.get("Fltr"), None); + assert_eq!(back.get("hasoptions"), Some(&Value::Boolean(false))); + assert_eq!(back.get("filterID"), Some(&Value::Integer(code(b"Invr")))); + assert_eq!(back.get("Nm "), Some(&Value::Text(UnicodeString::new_nul("Invert")))); +} + +/// A filter PhotoCraft doesn't model, or a known one with settings it doesn't, is kept verbatim; only its visibility and blend change. +#[test] +fn photoshop_sharpen_without_fltr_imports_as_sharpen() { + // #6267: Photoshop's Sharpen item holds only its name, blending and `filterID`. + let item = Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Sharpen"))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(false)) + .with("filterID", Value::Integer(1_399_353_968)); + let f = filter_from_item(&item); + assert_eq!((f.command.as_str(), &f.params), ("filter.sharpen.sharpen", &json!({}))); + // Hue/Saturation with an unnumbered range and Dust & Scratches with a missing setting fail + // cleanly instead of panicking. + let bad = SmartFilter { + command: "image.adjustments.hueSaturation".into(), + params: json!({"reds": {"range": [1, "x", 3, 4]}}), + blend: BlendMode::Normal, + opacity: 1.0, + visible: true, + }; + assert!(item_for_filter(&bad).is_err()); + let dust = Descriptor::new("filterFX") + .with("Fltr", Value::Descriptor(Descriptor::new("DstS").with("Rds ", Value::Integer(3)))) + .with("filterID", Value::Integer(code(b"DstS"))); + assert_eq!(filter_from_item(&dust).command, UNSUPPORTED_FILTER); +} + +#[test] +fn hue_saturation_ranges_are_not_lost() { + let hue_sat = |params: J| item_for_filter(&sf("image.adjustments.hueSaturation", params)); + // A range that is not an object is an error, not a silently dropped setting. + assert!(hue_sat(json!({"reds": 5})).is_err()); + assert!(hue_sat(json!({"reds": null})).is_ok()); + // Colorize's 25% default is the master saturation's only: a range's stays 0. + let d = hue_sat(json!({"colorize": true, "reds": {"hue": 5}})).unwrap(); + let adjs = adjustment_list(get_desc(&d, "Fltr").unwrap()).unwrap(); + let saturations: Vec<_> = adjs.iter().map(|a| int(a, "Strt")).collect(); + assert_eq!(saturations, [Some(25), Some(0)]); + // A repeated range (or master) would overwrite the first: the filter is kept verbatim. + let entry = |range: Option| { + let e = Descriptor::new("Hst2").with("H ", Value::Integer(0)).with("Strt", Value::Integer(0)).with("Lght", Value::Integer(0)); + let Some(r) = range else { return Value::Descriptor(e) }; + let e = ["BgnR", "BgnS", "EndS", "EndR"].iter().fold(e.with("LclR", Value::Integer(r)), |e, k| e.with(k, Value::Integer(10))); + Value::Descriptor(e) + }; + for adjs in [vec![entry(None), entry(Some(1)), entry(Some(1))], vec![entry(None), entry(None)]] { + let fltr = Descriptor::new("HStr").with("Clrz", Value::Boolean(false)).with("Adjs", Value::List(adjs)); + let item = Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Hue/Saturation..."))) + .with( + "blendOptions", + Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal"))), + ) + .with("enab", Value::Boolean(true)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(code(b"HStr"))); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(item_for_filter(&f).unwrap(), item); + } +} + +#[test] +fn unknown_filters_keep_their_descriptor() { + let item = Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Shear..."))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) + .with("enab", Value::Boolean(true)) + .with("Fltr", Value::Descriptor(Descriptor::new("Shr ").with("UndA", enumv("UndA", "WrpA")))) + .with("filterID", Value::Integer(code(b"Shr "))); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(f.params["name"], "Shear..."); + assert_eq!(item_for_filter(&f).unwrap(), item); + // Hidden and re-blended: only those keys change. + let mut g = f.clone(); + g.visible = false; + g.blend = BlendMode::Screen; + let back = filter_from_item(&item_for_filter(&g).unwrap()); + assert_eq!((back.visible, back.blend, &back.params), (false, BlendMode::Screen, &f.params)); + // A known filter with a setting we don't model is kept verbatim too. + let odd = Descriptor::new("filterFX").with("Fltr", Value::Descriptor(Descriptor::new("GsnB"))).with("filterID", Value::Integer(code(b"GsnB"))); + assert_eq!(filter_from_item(&odd).command, UNSUPPORTED_FILTER); +} + +/// A `filterFXList` item with filter `fltr` and `filterID`, as Photoshop saves it. +fn ps_item(name: &str, fltr: Descriptor, filter_id: i32) -> Descriptor { + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul(name))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgbc(0.0)) + .with("BckC", rgbc(255.0)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(filter_id)) +} + +fn surface_blur(rds: f64, thsh: i32) -> Descriptor { + Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Pxl", rds)).with("Thsh", Value::Integer(thsh)) +} + +fn smart_blur(rds: f64, thsh: f64, q: &str, m: &str) -> Descriptor { + Descriptor::new("SmrB").with("Rds ", Value::Double(rds)).with("Thsh", Value::Double(thsh)).with("SmBQ", enumv("SmBQ", q)).with("SmBM", enumv("SmBM", m)) +} + +fn radial_blur(amnt: i32, m: &str, q: &str) -> Descriptor { + Descriptor::new("RdlB").with("Amnt", Value::Integer(amnt)).with("BlrM", enumv("BlrM", m)).with("BlrQ", enumv("BlrQ", q)) +} + +/// The `Fltr` shapes measured in Photoshop (each filter applied to a smart object through +/// Action Manager, saved, and `filterFX` read back) open as our filters and are written back +/// with the same keys, value types, units, enums and filter ids. +#[test] +fn blur_family_matches_photoshop_shapes() { + let smart = code(b"SmrB"); + let radial = code(b"RdlB"); + assert_eq!((smart, radial), (1_399_681_602, 1_382_313_026)); + let cases = [ + (surface_blur(5.0, 15), 1135, "filter.blur.surfaceBlur", json!({"radius": 5.0, "threshold": 15})), + (surface_blur(12.0, 40), 1135, "filter.blur.surfaceBlur", json!({"radius": 12.0, "threshold": 40})), + ( + smart_blur(5.0, 25.0, "SBQH", "SBMN"), + smart, + "filter.blur.smartBlur", + json!({"radius": 5.0, "threshold": 25.0, "quality": "high", "mode": "normal"}), + ), + ( + smart_blur(3.0, 30.0, "SBQL", "SBME"), + smart, + "filter.blur.smartBlur", + json!({"radius": 3.0, "threshold": 30.0, "quality": "low", "mode": "edgeOnly"}), + ), + ( + smart_blur(3.0, 30.0, "SBQM", "SBMO"), + smart, + "filter.blur.smartBlur", + json!({"radius": 3.0, "threshold": 30.0, "quality": "medium", "mode": "overlayEdge"}), + ), + (radial_blur(10, "Spn ", "Drft"), radial, "filter.blur.radialBlur", json!({"amount": 10, "method": "spin", "quality": "draft"})), + (radial_blur(20, "Spn ", "Bst "), radial, "filter.blur.radialBlur", json!({"amount": 20, "method": "spin", "quality": "best"})), + (radial_blur(20, "Zm ", "Gd "), radial, "filter.blur.radialBlur", json!({"amount": 20, "method": "zoom", "quality": "good"})), + ]; + for (fltr, id, command, params) in cases { + let item = ps_item("x", fltr.clone(), id); + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!((f.command.as_str(), &f.params), (command, ¶ms), "{fltr:?}"); + let out = item_for_filter(&f).unwrap(); + assert_eq!(out.get("filterID"), Some(&Value::Integer(id))); + assert_eq!(out.get("hasoptions"), Some(&Value::Boolean(true))); + // Byte-identical filter descriptor: class id, four-char keys, types, units and enums. + let Some(Value::Descriptor(w)) = out.get("Fltr") else { panic!("no Fltr for {command}") }; + assert_eq!(w.to_bytes(), fltr.to_bytes(), "{command}"); + } + // Surface Blur's class is a string id; Smart Blur's and Radial Blur's are four-char codes. + assert_eq!(surface_blur(1.0, 2).class_id, Id::Str(b"surfaceBlur".to_vec())); + assert_eq!(radial_blur(1, "Spn ", "Gd ").class_id, Id::Code(*b"RdlB")); + // Unset options are written with the dialog defaults. + let fltr = |c: &str, p: J| item_for_filter(&sf(c, p)).unwrap().get("Fltr").cloned(); + assert_eq!(fltr("filter.blur.surfaceBlur", json!({})), Some(Value::Descriptor(surface_blur(5.0, 15)))); + assert_eq!(fltr("filter.blur.smartBlur", json!({})), Some(Value::Descriptor(smart_blur(3.0, 25.0, "SBQH", "SBMN")))); + assert_eq!(fltr("filter.blur.radialBlur", json!({"centerX": 0.5, "centerY": 0.5})), Some(Value::Descriptor(radial_blur(10, "Spn ", "Gd ")))); +} + +/// `d` with `key` set to `v` (replacing the measured value). +fn replaced(mut d: Descriptor, key: &str, v: Value) -> Descriptor { + set(&mut d, key, v); + d +} + +/// Malformed or unmodelled blur descriptors stay verbatim (and are written back unchanged); +/// settings PSD can't hold are reported, never a panic. +#[test] +fn blur_family_malformed_is_kept_verbatim() { + let smart = code(b"SmrB"); + let radial = code(b"RdlB"); + let text = |s: &str| Value::Text(UnicodeString::new_nul(s)); + let bad = [ + // Missing keys. + (Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Pxl", 5.0)), 1135), + (Descriptor::new("SmrB").with("Rds ", Value::Double(3.0)).with("Thsh", Value::Double(25.0)), smart), + (Descriptor::new("RdlB").with("Amnt", Value::Integer(10)).with("BlrM", enumv("BlrM", "Spn ")), radial), + // Wrong types. + (Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Pxl", 5.0)).with("Thsh", Value::Double(15.0)), 1135), + ( + Descriptor::new("SmrB") + .with("Rds ", text("3")) + .with("Thsh", Value::Double(25.0)) + .with("SmBQ", enumv("SmBQ", "SBQH")) + .with("SmBM", enumv("SmBM", "SBMN")), + smart, + ), + (Descriptor::new("RdlB").with("Amnt", text("10")).with("BlrM", enumv("BlrM", "Spn ")).with("BlrQ", enumv("BlrQ", "Gd ")), radial), + (Descriptor::new("RdlB").with("Amnt", Value::Integer(10)).with("BlrM", Value::Integer(1)).with("BlrQ", enumv("BlrQ", "Gd ")), radial), + // Out of range, NaN and infinity. + (surface_blur(0.5, 15), 1135), + (surface_blur(5.0, 300), 1135), + (surface_blur(f64::NAN, 15), 1135), + (smart_blur(f64::INFINITY, 25.0, "SBQH", "SBMN"), smart), + (smart_blur(3.0, 0.0, "SBQH", "SBMN"), smart), + (radial_blur(0, "Spn ", "Gd "), radial), + (radial_blur(101, "Zm ", "Gd "), radial), + // Unknown enum values. + (smart_blur(3.0, 25.0, "SBQX", "SBMN"), smart), + (smart_blur(3.0, 25.0, "Hgh ", "SBMN"), smart), + (radial_blur(10, "Twrl", "Gd "), radial), + (radial_blur(10, "Spn ", "Hgh "), radial), + // A key we don't model (an off-centre Radial Blur would carry one). + (radial_blur(10, "Zm ", "Gd ").with("Cntr", Value::Descriptor(Descriptor::new("Pnt ").with("Hrzn", Value::Double(10.0)))), radial), + (surface_blur(5.0, 15).with("Edg ", Value::Integer(1)), 1135), + // Enums of another type, units and value types we would not write back. + (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "SmBQ", enumv("Othr", "SBQH")), smart), + (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "SmBM", enumv("SmBQ", "SBMN")), smart), + (replaced(radial_blur(10, "Spn ", "Gd "), "BlrM", enumv("Othr", "Spn ")), radial), + (replaced(radial_blur(10, "Spn ", "Gd "), "BlrQ", enumv("BlrM", "Gd ")), radial), + (Descriptor::new("surfaceBlur").with("Rds ", unit(b"#Prc", 5.0)).with("Thsh", Value::Integer(15)), 1135), + (Descriptor::new("surfaceBlur").with("Rds ", Value::Double(5.0)).with("Thsh", Value::Integer(15)), 1135), + (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "Rds ", unit(b"#Pxl", 3.0)), smart), + (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "Thsh", unit(b"#Prc", 25.0)), smart), + (replaced(smart_blur(3.0, 25.0, "SBQH", "SBMN"), "Thsh", Value::Integer(25)), smart), + ]; + for (fltr, id) in bad { + let item = ps_item("x", fltr.clone(), id); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{fltr:?}"); + // Compared as bytes: a NaN setting is not equal to itself. + assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "{fltr:?}"); + } + // Radial Blur at its defaults has no `Fltr` (measured): its values are not stored, so the + // entry stays verbatim instead of guessing them. + let no_opts = Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)).with("filterID", Value::Integer(radial)); + assert_eq!(filter_from_item(&no_opts).command, UNSUPPORTED_FILTER); + // Settings with no PSD equivalent are errors when writing. + for (command, p) in [ + ("filter.blur.smartBlur", json!({"quality": "ultra"})), + ("filter.blur.smartBlur", json!({"mode": 3})), + ("filter.blur.radialBlur", json!({"method": "twirl"})), + ("filter.blur.radialBlur", json!({"quality": ["best"]})), + ("filter.blur.radialBlur", json!({"centerX": 0.25})), + ("filter.blur.radialBlur", json!({"centerY": 1.0})), + // A centre, or a value, that is there but can't be written as Photoshop would open it. + ("filter.blur.radialBlur", json!({"centerX": "middle"})), + ("filter.blur.radialBlur", json!({"centerY": true})), + ("filter.blur.radialBlur", json!({"amount": 0})), + ("filter.blur.radialBlur", json!({"amount": 101})), + ("filter.blur.radialBlur", json!({"amount": "10"})), + ("filter.blur.surfaceBlur", json!({"radius": 0.5})), + ("filter.blur.surfaceBlur", json!({"radius": 100.5})), + ("filter.blur.surfaceBlur", json!({"threshold": 1})), + ("filter.blur.surfaceBlur", json!({"threshold": 256})), + ("filter.blur.surfaceBlur", json!({"radius": "5"})), + ("filter.blur.smartBlur", json!({"radius": 0.05})), + ("filter.blur.smartBlur", json!({"threshold": 100.5})), + ("filter.blur.smartBlur", json!({"threshold": [25]})), + ] { + assert!(item_for_filter(&sf(command, p.clone())).is_err(), "{command} {p}"); + } + // Every value that is written opens again as the same editable filter (range ends included). + for (command, p) in [ + ("filter.blur.surfaceBlur", json!({"radius": 1.0, "threshold": 2})), + ("filter.blur.surfaceBlur", json!({"radius": 100.0, "threshold": 255})), + ("filter.blur.smartBlur", json!({"radius": 0.1, "threshold": 100.0, "quality": "low", "mode": "edgeOnly"})), + ("filter.blur.radialBlur", json!({"amount": 1, "method": "zoom", "quality": "best", "centerX": 0.5, "centerY": null})), + ("filter.blur.radialBlur", json!({"amount": 100, "method": "spin", "quality": "draft"})), + ] { + let back = filter_from_item(&item_for_filter(&sf(command, p.clone())).unwrap()); + assert_eq!(back.command, command, "{p}"); + } + // Hostile numbers write without panicking. + for p in [json!({"radius": f64::MAX, "threshold": -1e300, "amount": 1e300}), json!({"radius": "x", "threshold": null}), json!(null), json!([1, 2])] { + for command in ["filter.blur.surfaceBlur", "filter.blur.smartBlur", "filter.blur.radialBlur"] { + let _ = item_for_filter(&sf(command, p.clone())); + } + } +} + +/// A `filterFX` entry shaped as Photoshop saves it (measured in Photoshop: the filter applied +/// through Action Manager to a smart object, the PSD saved, `filterFX` read back). +fn photoshop_item(filter_id: &[u8; 4], fltr: Descriptor) -> Descriptor { + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Filter..."))) + .with("blendOptions", blend_options(&sf("", J::Null))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgbc(0.0)) + .with("BckC", rgbc(255.0)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(code(filter_id))) +} + +#[test] +fn stylize_and_pixelate_filters_open_from_photoshop_shapes() { + let cases = [ + (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "Nrml")), "filter.stylize.diffuse", json!({"mode": "normal"})), + (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "DrkO")), "filter.stylize.diffuse", json!({"mode": "darkenOnly"})), + (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "LghO")), "filter.stylize.diffuse", json!({"mode": "lightenOnly"})), + (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "anisotropic")), "filter.stylize.diffuse", json!({"mode": "anisotropic"})), + ( + b"TrcC", + Descriptor::new("TrcC").with("Lvl ", Value::Integer(128)).with("Edg ", enumv("CntE", "Upr ")), + "filter.stylize.traceContour", + json!({"level": 128, "edge": "upper"}), + ), + ( + b"TrcC", + Descriptor::new("TrcC").with("Lvl ", Value::Integer(60)).with("Edg ", enumv("CntE", "Lwr ")), + "filter.stylize.traceContour", + json!({"level": 60, "edge": "lower"}), + ), + (b"Crst", Descriptor::new("Crst").with("ClSz", Value::Integer(10)), "filter.pixelate.crystallize", json!({"cellSize": 10})), + ( + b"Pntl", + Descriptor::new("Pntl").with("ClSz", Value::Integer(7)), + "filter.pixelate.pointillize", + json!({"cellSize": 7, "background": [1.0, 1.0, 1.0, 1.0]}), + ), + ]; + for (id, fltr, command, params) in cases { + let item = photoshop_item(id, fltr); + // Through bytes, as read from a file. + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!((f.command.as_str(), &f.params), (command, ¶ms)); + // Written back in the measured shape: same class, keys, value types and filterID. + let back = item_for_filter(&f).unwrap(); + for key in ["Fltr", "filterID", "BckC"] { + assert_eq!(back.get(key), item.get(key), "{command} {key}"); + } + } + // The `anisotropic` mode is a long id, as Photoshop writes it. + let d = item_for_filter(&sf("filter.stylize.diffuse", json!({"mode": "anisotropic"}))).unwrap(); + let Some(Value::Descriptor(fltr)) = d.get("Fltr") else { panic!("no Fltr") }; + assert!(matches!(fltr.get("Md "), Some(Value::Enumerated { value: Id::Str(v), .. }) if v == b"anisotropic")); + // Pointillize takes the entry's background colour; the others ignore it. + let mut item = photoshop_item(b"Pntl", Descriptor::new("Pntl").with("ClSz", Value::Integer(7))); + set(&mut item, "BckC", rgbc(51.0)); + let f = filter_from_item(&item); + assert_eq!(f.params["background"], json!([0.2, 0.2, 0.2, 1.0])); + assert_eq!(item_for_filter(&f).unwrap().get("BckC"), Some(&rgbc(51.0))); + let mut item = photoshop_item(b"Crst", Descriptor::new("Crst").with("ClSz", Value::Integer(7))); + set(&mut item, "BckC", rgbc(51.0)); + assert_eq!(filter_from_item(&item).params, json!({"cellSize": 7})); + // Our random seed has no PSD key: it is not written. + let fltr = |c: &str, p: J| item_for_filter(&sf(c, p)).unwrap().get("Fltr").cloned(); + assert_eq!( + fltr("filter.stylize.diffuse", json!({"mode": "normal", "seed": 7})), + Some(Value::Descriptor(Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "Nrml")))) + ); + // Defaults and out-of-range values are written in Photoshop's ranges. + assert_eq!( + fltr("filter.stylize.traceContour", json!({})), + Some(Value::Descriptor(Descriptor::new("TrcC").with("Lvl ", Value::Integer(128)).with("Edg ", enumv("CntE", "Lwr ")))) + ); + assert_eq!(fltr("filter.pixelate.crystallize", json!({})), Some(Value::Descriptor(Descriptor::new("Crst").with("ClSz", Value::Integer(10))))); + assert_eq!(fltr("filter.pixelate.pointillize", json!({})), Some(Value::Descriptor(Descriptor::new("Pntl").with("ClSz", Value::Integer(5))))); + assert_eq!( + fltr("filter.pixelate.crystallize", json!({"cellSize": 1e9})), + Some(Value::Descriptor(Descriptor::new("Crst").with("ClSz", Value::Integer(300)))) + ); + assert_eq!( + fltr("filter.pixelate.pointillize", json!({"cellSize": "big"})), + Some(Value::Descriptor(Descriptor::new("Pntl").with("ClSz", Value::Integer(5)))) + ); + assert_eq!( + fltr("filter.stylize.traceContour", json!({"level": -40, "edge": "upper"})), + Some(Value::Descriptor(Descriptor::new("TrcC").with("Lvl ", Value::Integer(0)).with("Edg ", enumv("CntE", "Upr ")))) + ); +} + +#[test] +fn malformed_stylize_and_pixelate_filters_are_kept_verbatim() { + let long = Value::Integer; + let cases = [ + // Missing keys. + (b"Dfs ", Descriptor::new("Dfs ")), + (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(60))), + (b"TrcC", Descriptor::new("TrcC").with("Edg ", enumv("CntE", "Upr "))), + (b"Crst", Descriptor::new("Crst")), + (b"Pntl", Descriptor::new("Pntl")), + // Unknown enum values or enum types. + (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("DfsM", "Wild"))), + (b"Dfs ", Descriptor::new("Dfs ").with("Md ", enumv("BlnM", "Nrml"))), + (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(60)).with("Edg ", enumv("CntE", "Mddl"))), + // Wrong types (also NaN). + (b"Dfs ", Descriptor::new("Dfs ").with("Md ", long(1))), + (b"TrcC", Descriptor::new("TrcC").with("Lvl ", Value::Double(60.0)).with("Edg ", enumv("CntE", "Upr "))), + (b"Crst", Descriptor::new("Crst").with("ClSz", unit(b"#Pxl", 10.0))), + (b"Pntl", Descriptor::new("Pntl").with("ClSz", Value::Double(f64::NAN))), + // Out of range. + (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(256)).with("Edg ", enumv("CntE", "Upr "))), + (b"TrcC", Descriptor::new("TrcC").with("Lvl ", long(-1)).with("Edg ", enumv("CntE", "Upr "))), + (b"Crst", Descriptor::new("Crst").with("ClSz", long(2))), + (b"Pntl", Descriptor::new("Pntl").with("ClSz", long(i32::MAX))), + ]; + for (id, fltr) in cases { + let item = photoshop_item(id, fltr); + let f = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{item:?}"); + assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes()); + } + // Saved without options (`hasoptions` false, no `Fltr`): kept verbatim. + let bare = Descriptor::new("filterFX").with("hasoptions", Value::Boolean(false)).with("filterID", Value::Integer(code(b"Crst"))); + assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); + // A Pointillize entry whose background colour is unreadable is kept verbatim too. + for bad in [Value::Integer(3), Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)))] { + let mut item = photoshop_item(b"Pntl", Descriptor::new("Pntl").with("ClSz", Value::Integer(7))); + set(&mut item, "BckC", bad); + assert_eq!(filter_from_item(&item).command, UNSUPPORTED_FILTER); + } + // Values with no PSD equivalent are reported, not guessed. + for (c, p) in [ + ("filter.stylize.diffuse", json!({"mode": "sideways"})), + ("filter.stylize.diffuse", json!({"mode": 3})), + ("filter.stylize.traceContour", json!({"edge": "middle"})), + ("filter.pixelate.pointillize", json!({"background": "teal"})), + ("filter.pixelate.pointillize", json!({"background": [1.0]})), + ] { + assert!(item_for_filter(&sf(c, p.clone())).is_err(), "{c} {p}"); + } +} + +/// A Filter Gallery item as Photopea writes it (Chrome, Detail 12, Smoothness 4). +fn gallery_item_with(effects: Vec) -> Descriptor { + let rgb = + |v: f64| Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))); + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Filtergalerie"))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgb(0.0)) + .with("BckC", rgb(255.0)) + .with("Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfs", Value::List(effects.into_iter().map(Value::Descriptor).collect())))) + .with("filterID", Value::Integer(code(b"GEfc"))) +} + +fn chrome(detail: i32, smoothness: i32, visible: bool) -> Descriptor { + Descriptor::new("GEfc") + .with("Dtl ", Value::Integer(detail)) + .with("Smth", Value::Integer(smoothness)) + .with("GEfk", enumv("GEft", "Chrm")) + .with("GELv", Value::Boolean(visible)) +} + +#[test] +fn filter_gallery_chrome_imports_as_editable_gallery() { + let f = filter_from_item(&gallery_item_with(vec![chrome(12, 4, true), chrome(3, 9, false)])); + assert_eq!(f.command, "filter.filterGallery"); + assert_eq!( + f.params, + json!({ + "effects": [ + {"filter": "chrome", "params": {"detail": 12, "smoothness": 4}, "visible": true}, + {"filter": "chrome", "params": {"detail": 3, "smoothness": 9}, "visible": false}, + ], + "foreground": [0.0, 0.0, 0.0, 1.0], + "background": [1.0, 1.0, 1.0, 1.0], + }) + ); + // Written back and read again: unchanged, also when re-blended and hidden. + let mut g = f.clone(); + g.blend = BlendMode::Multiply; + g.opacity = 0.5; + g.visible = false; + let d = item_for_filter(&g).unwrap(); + assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), g); + let fltr = get_desc(&d, "Fltr").unwrap(); + assert!(fltr.class_id.is("GEfc")); + assert_eq!(int(&d, "filterID"), Some(code(b"GEfc"))); +} + +/// A single effect as Photoshop 27 writes it: inline in `Fltr`, no `GEfs` list or `GELv`. +fn photoshop_chrome(detail: i32, smoothness: i32) -> Descriptor { + let rgb = + |v: f64| Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))); + let mut fltr = + Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Chrm")).with("Dtl ", Value::Integer(detail)).with("Smth", Value::Integer(smoothness)); + fltr.name = UnicodeString::new_nul("Filter Gallery"); + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Filter Gallery..."))) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "Nrml")))) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgb(255.0)) + .with("BckC", rgb(0.0)) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(code(b"GEfc"))) +} + +#[test] +fn filter_gallery_photoshop_inline_effect_imports_and_writes_back_inline() { + let item = photoshop_chrome(10, 4); + let f = filter_from_item(&item); + assert_eq!(f.command, "filter.filterGallery"); + assert_eq!( + f.params, + json!({ + "effects": [{"filter": "chrome", "params": {"detail": 10, "smoothness": 4}, "visible": true}], + "foreground": [1.0, 1.0, 1.0, 1.0], + "background": [0.0, 0.0, 0.0, 1.0], + }) + ); + // Written back in Photoshop's own layout. + let d = item_for_filter(&f).unwrap(); + assert_eq!(get_desc(&d, "Fltr"), get_desc(&item, "Fltr")); + assert_eq!((get_desc(&d, "FrgC"), get_desc(&d, "BckC")), (get_desc(&item, "FrgC"), get_desc(&item, "BckC"))); + assert_eq!(filter_from_item(&Descriptor::from_bytes(&d.to_bytes()).unwrap()), f); + // A hidden single effect needs the list (only it has a visibility flag). + let mut hidden = f.clone(); + hidden.params["effects"][0]["visible"] = json!(false); + let d = item_for_filter(&hidden).unwrap(); + assert!(get_desc(&d, "Fltr").unwrap().get("GEfs").is_some()); + assert_eq!(filter_from_item(&d), hidden); + // Inline effects we don't model stay verbatim. + let mut odd = photoshop_chrome(10, 4); + set(&mut odd, "Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Ctot")).with("Dtl ", Value::Integer(1)))); + assert_eq!(filter_from_item(&odd).command, UNSUPPORTED_FILTER); + let mut extra = photoshop_chrome(10, 4); + set(&mut extra, "Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Chrm")).with("Xtra", Value::Integer(1)))); + assert_eq!(filter_from_item(&extra).command, UNSUPPORTED_FILTER); +} + +#[test] +fn gallery_table_matches_the_gallery_filters() { + for g in &GALLERY_EFFECTS { + let f = photocraft_algo::GalleryFilter::from_key(g.key).unwrap(); + let keys: Vec<&str> = f.params().iter().map(|p| p.key).collect(); + for (_, ours) in g.settings { + assert!(keys.contains(ours), "{}.{ours}", g.key); + } + } +} + +#[test] +fn filter_gallery_written_with_defaults_and_colours() { + let f = sf("filter.filterGallery", json!({"effects": [{"filter": "chrome"}], "foreground": "#ff0000", "background": [0.0, 0.0, 1.0, 1.0]})); + let back = filter_from_item(&item_for_filter(&f).unwrap()); + assert_eq!(back.params["effects"][0]["params"], json!({"detail": 4, "smoothness": 7})); + assert_eq!(back.params["foreground"], json!([1.0, 0.0, 0.0, 1.0])); + assert_eq!(back.params["background"], json!([0.0, 0.0, 1.0, 1.0])); +} + +#[test] +fn filter_gallery_we_dont_model_is_kept_verbatim() { + // Another effect, an extra setting, a wrong-typed setting, no effects, a non-list. + let other = Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Ctot")).with("GELv", Value::Boolean(true)); + let extra = chrome(4, 7, true).with("Xtra", Value::Integer(1)); + let typed = Descriptor::new("GEfc").with("Dtl ", Value::Double(4.0)).with("GEfk", enumv("GEft", "Chrm")); + for effects in [vec![chrome(4, 7, true), other], vec![extra], vec![typed], vec![]] { + let item = gallery_item_with(effects); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(item_for_filter(&f).unwrap(), item); + } + let odd = Descriptor::new("filterFX").with("Fltr", Value::Descriptor(Descriptor::new("GEfc").with("GEfs", Value::Integer(3)))); + assert_eq!(filter_from_item(&odd).command, UNSUPPORTED_FILTER); + let bare = Descriptor::new("filterFX").with("filterID", Value::Integer(code(b"GEfc"))); + assert_eq!(filter_from_item(&bare).command, UNSUPPORTED_FILTER); +} + +#[test] +fn filter_gallery_without_psd_equivalent_is_reported() { + for p in [ + json!({"effects": [{"filter": "cutout"}]}), + json!({"effects": [{"filter": "chrome", "params": {"sparkle": 1}}]}), + json!({"effects": [{"params": {}}]}), + json!({"effects": []}), + json!({}), + json!({"effects": [{"filter": "chrome"}], "list": true}), + json!({"effects": [{"filter": "chrome"}], "foreground": "red"}), + json!(null), + ] { + assert!(item_for_filter(&sf("filter.filterGallery", p.clone())).is_err(), "{p}"); + } +} + +/// Filters with no PSD equivalent are skipped with a warning each, and the writable ones around them still export. +#[test] +fn unwritable_filters_are_reported_not_fatal() { + let stack = FilterStack { + filters: vec![ + // Shear's curve isn't mapped to Photoshop's grid yet. + sf("filter.distort.shear", json!({"amount": 40})), + sf("filter.blur.gaussianBlur", json!({"radius": 2.0})), + sf(UNSUPPORTED_FILTER, json!({"psd": "zz"})), + sf("image.adjustments.levels", json!({"cyan": {"gamma": 2.0}})), + sf("image.adjustments.shadowsHighlights", json!({"shadowAmount": 50})), + ], + ..Default::default() + }; + let mut w = Vec::new(); + let d = filter_fx(&stack, "L", &mut w); + assert_eq!(w.len(), 4, "{w:?}"); + let back = filter_stack(&d); + assert_eq!(back.filters, vec![stack.filters[1].clone()]); +} + +#[test] +fn placed_blocks_parse_back() { + let t = Affine { m: [0.5, 0.1, -0.1, 0.5, 10.0, 20.0] }; + let stack = + FilterStack { enabled: false, filters: vec![sf("filter.blur.gaussianBlur", json!({"radius": 3.0}))], mask_enabled: false, mask_linked: true }; + let mut w = Vec::new(); + let spec = PlacedSpec { + idnt: "id-1", + placed: "pl-2", + transform: t, + perspective: None, + size: (64.0, 32.0), + dpi: 72.0, + warp: None, + filter_fx: Some(filter_fx(&stack, "L", &mut w)), + }; + let sold = sold_bytes(None, &spec, &mut w); + assert!(w.is_empty()); + assert_eq!(sold.len() % 4, 0); + let p = parse_sold(&sold).unwrap(); + assert_eq!((p.idnt.as_str(), p.placed.as_str()), ("id-1", "pl-2")); + for (a, b) in p.transform.m.iter().zip(t.m) { + assert!((a - b).abs() < 1e-9); + } + assert_eq!(p.stack, Some(stack)); + let tb = photocraft_psd::TaggedBlock::new(*b"SoLd", sold.clone()); + tb.check_structure().unwrap(); + let pl = photocraft_psd::TaggedBlock::new(*b"PlLd", plld_bytes(&spec, &mut w)); + pl.check_structure().unwrap(); + // A template keeps its other keys; an unmoved transform keeps its exact quad. + let mut tmpl = sold_descriptor(&sold).unwrap(); + tmpl.items.push((Id::new("extraKey"), Value::Integer(7))); + let again = sold_bytes(Some(&tmpl), &PlacedSpec { filter_fx: None, ..spec }, &mut w); + let d = sold_descriptor(&again).unwrap(); + assert_eq!(d.get("extraKey"), Some(&Value::Integer(7))); + assert!(d.get("filterFX").is_none()); + assert_eq!(d.get("Trnf"), tmpl.get("Trnf")); +} + +/// A Distort / Perspective placement goes out as its four corners (`Trnf`, `nonAffineTransform`) +/// and comes back as the same projective map; an affine one reads back as no perspective. +#[test] +fn perspective_placement_round_trips_through_sold() { + let h = photocraft_algo::transform::Homography::rect_to_quad([0.0, 0.0, 64.0, 32.0], [[10.0, 5.0], [80.0, 8.0], [70.0, 50.0], [12.0, 40.0]]).unwrap(); + let mut w = Vec::new(); + let mut spec = PlacedSpec { + idnt: "id", + placed: "pl", + transform: Affine::IDENTITY, + perspective: Some(h.0), + size: (64.0, 32.0), + dpi: 72.0, + warp: None, + filter_fx: None, + }; + let sold = sold_bytes(None, &spec, &mut w); + let back = crate::blocks::parse_smart_perspective(b"SoLd", &sold).expect("a projective placement"); + let n = |m: [f64; 9]| m.map(|v| v / m[8]); + for (a, b) in n(back).iter().zip(n(h.0)) { + assert!((a - b).abs() < 1e-9 * (1.0 + b.abs()), "{back:?} vs {:?}", h.0); + } + // Affine placements carry no perspective. + spec.perspective = None; + spec.transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 5.0, 7.0] }; + let sold = sold_bytes(None, &spec, &mut w); + assert_eq!(crate::blocks::parse_smart_perspective(b"SoLd", &sold), None); + assert_eq!(crate::blocks::parse_smart_perspective(b"PlLd", &sold), None); +} + +/// `quad_moved` compares the corners a template stores with the placement's: unchanged keeps +/// the template's quad, a moved corner (affine or projective) or a missing quad rewrites it. +#[test] +fn quad_moved_detects_corner_changes() { + let t = Affine { m: [1.0, 0.0, 0.0, 1.0, 3.0, 4.0] }; + let mut w = Vec::new(); + let mut spec = PlacedSpec { idnt: "id", placed: "pl", transform: t, perspective: None, size: (20.0, 10.0), dpi: 72.0, warp: None, filter_fx: None }; + let template = parse_sold(&sold_bytes(None, &spec, &mut w)).expect("parses").descriptor; + assert!(!quad_moved(&template, &spec, spec.warp), "same placement"); + spec.transform = Affine { m: [1.0, 0.0, 0.0, 1.0, 3.5, 4.0] }; + assert!(quad_moved(&template, &spec, spec.warp), "moved half a pixel"); + spec.transform = t; + spec.perspective = + photocraft_algo::transform::Homography::rect_to_quad([0.0, 0.0, 20.0, 10.0], [[3.0, 4.0], [23.0, 4.0], [20.0, 12.0], [3.0, 14.0]]).map(|h| h.0); + assert!(quad_moved(&template, &spec, spec.warp), "one corner moved (Distort)"); + assert!(quad_moved(&Descriptor::new("null"), &spec, spec.warp), "no stored quad"); +} + +/// Corrupted placed-layer data and filter descriptors never panic: they parse to something +/// (unknown filters stay verbatim) or to nothing. +#[test] +fn mutated_placed_data_never_panics() { + let stack = FilterStack { + filters: vec![ + sf("filter.blur.gaussianBlur", json!({"radius": 3.0})), + sf("image.adjustments.curves", json!({"points": [[0.0, 0.0], [255.0, 255.0]]})), + sf("image.adjustments.levels", json!({"inBlack": 3, "inWhite": 250, "gamma": 1.1})), + ], + ..Default::default() + }; + let mut w = Vec::new(); + let spec = PlacedSpec { + idnt: "id", + placed: "pl", + transform: Affine::IDENTITY, + perspective: None, + size: (8.0, 8.0), + dpi: 72.0, + warp: None, + filter_fx: Some(filter_fx(&stack, "L", &mut w)), + }; + let sold = sold_bytes(None, &spec, &mut w); + let mut state = 0x2545_F491_4F6C_DD1Du64; + let mut next = || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + for _ in 0..3000 { + let mut b = sold.clone(); + for _ in 0..1 + next() % 3 { + let i = (next() as usize) % b.len(); + b[i] = next() as u8; + } + if let Some(p) = parse_sold(&b) { + for f in p.stack.iter().flat_map(|s| &s.filters) { + let _ = item_for_filter(f); + } + let _ = sold_bytes(Some(&p.descriptor), &spec, &mut w); + } + } +} + +#[test] +fn warps_are_written_and_read_back() { + use photocraft_geom::warp::BezierMesh; + let bounds = [0.0, 0.0, 60.0, 30.0]; + let mut custom = BezierMesh::identity(bounds, 1, 1); + custom.points[15] = [67.0, 30.0]; + let mut multi = Warp::preset(WarpStyle::Custom, 0.0, bounds); + let mut split = BezierMesh::identity(bounds, 2, 2); + split.points[8][1] += 4.0; + multi.mesh = Some(split); + let mut arc = Warp::preset(WarpStyle::Arc, 40.0, bounds); + arc.vertical = true; + arc.h_distort = 10.0; + let mut c = Warp::preset(WarpStyle::Custom, 0.0, bounds); + c.mesh = Some(custom); + for (w, back) in [(Some(arc.clone()), Some(arc)), (Some(c.clone()), Some(c)), (Some(multi.clone()), Some(multi)), (None, None)] { + let mut warnings = Vec::new(); + let spec = PlacedSpec { + idnt: "i", + placed: "p", + transform: Affine::IDENTITY, + perspective: None, + size: (60.0, 30.0), + dpi: 72.0, + warp: w.as_ref(), + filter_fx: None, + }; + let sold = sold_bytes(None, &spec, &mut warnings); + assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), back); + assert!(warnings.is_empty(), "{warnings:?}"); + } +} + +/// A placed layer over a 50 × 25 source, at `transform`, with `warp`. +fn placed<'a>(transform: Affine, warp: Option<&'a Warp>) -> PlacedSpec<'a> { + PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (50.0, 25.0), dpi: 72.0, warp, filter_fx: None } +} + +/// A 3 × 2 patch split warp over the 50 × 25 source with one interior control point pulled. +fn split_warp() -> Warp { + use photocraft_geom::warp::BezierMesh; + let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 3, 2); + mesh.points[10 * 3 + 4][1] += 3.0; + Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]) +} + +/// An imported `soLD` descriptor holding `warp` as Photoshop writes a split warp: a +/// `quiltWarp` whose outer slices sit 0.6 px past the source, before a `warpNone` `warp`. +fn photoshop_template(warp: &Warp) -> Descriptor { + let mesh = warp.mesh.as_ref().expect("a mesh"); + let slices = |k: &str, knots: &[f64], len: f64| { + let n = knots.len() - 1; + let values = knots + .iter() + .enumerate() + .map(|(i, u)| { + if i == 0 { + -0.6 + } else if i == n { + len + 0.6 + } else { + u * len + } + }) + .collect::>(); + let prefix = values.len() as u32; + Value::ObjectArray(ObjectArray { prefix, body: Descriptor::new("UntF").with(k, Value::UnitFloats { unit: *b"#Pxl", values }) }) + }; + let Value::Descriptor(plain) = warp_desc(None, (50.0, 25.0), &mut Vec::new()) else { panic!("a descriptor") }; + let mut quilt = plain.clone(); + quilt.class_id = Id::new("quiltWarp"); + set(&mut quilt, "warpStyle", enumv("warpStyle", "warpCustom")); + let points = Descriptor::new("rationalPoint") + .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: mesh.points.iter().map(|p| p[0]).collect() }) + .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: mesh.points.iter().map(|p| p[1]).collect() }); + let envelope = Descriptor::new("customEnvelopeWarp") + .with("quiltSliceX", slices("quiltSliceX", &mesh.us, 50.0)) + .with("quiltSliceY", slices("quiltSliceY", &mesh.vs, 25.0)) + .with("meshPoints", Value::ObjectArray(ObjectArray { prefix: mesh.points.len() as u32, body: points })); + quilt = quilt + .with("deformNumRows", Value::Integer(mesh.ny() as i32)) + .with("deformNumCols", Value::Integer(mesh.nx() as i32)) + .with("customEnvelopeWarp", Value::Descriptor(envelope)); + let mut d = sold_descriptor(&sold_bytes(None, &placed(Affine::IDENTITY, None), &mut Vec::new())).expect("a descriptor"); + let at = d.items.iter().position(|(k, _)| k.is("warp")).expect("a warp key"); + d.items.insert(at, (Id::new("quiltWarp"), Value::Descriptor(quilt))); + d +} + +fn sold_of(d: Descriptor) -> Vec { + let mut out = b"soLD".to_vec(); + out.extend_from_slice(&4u32.to_be_bytes()); + out.extend(VersionedDescriptor::new(d).to_bytes()); + out +} + +fn quilt_of(d: &Descriptor) -> Option<&Descriptor> { + get_desc(d, "quiltWarp") +} + +/// A split warp of more patches along a side than a `quiltWarp` is read with (Warp Grid 64, +/// then one more split) is written as no warp, with a message, framed by the source rect, so +/// the layer reopens where it was. Before, its `quiltWarp` was refused on reopen while `Trnf` +/// still framed its control box: the layer came back stretched and shifted. +#[test] +fn a_split_warp_past_the_quilt_limit_keeps_its_placement() { + use photocraft_geom::warp::BezierMesh; + let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], crate::blocks::QUILT_MAX_PATCHES, 1); + assert!(mesh.split_u(0.005)); + mesh.points[0] = [-10.0, -5.0]; + let warp = Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]); + let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; + let mut warnings = Vec::new(); + let sold = sold_bytes(None, &placed(transform, Some(&warp)), &mut warnings); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); + assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), None); + assert!(quilt_of(&sold_descriptor(&sold).expect("a descriptor")).is_none()); + // Over an imported split warp, the stale `quiltWarp` goes and the placement holds. + let template = photoshop_template(&split_warp()); + let mut warnings = Vec::new(); + let sold = sold_bytes(Some(&template), &placed(transform, Some(&warp)), &mut warnings); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); + assert!(quilt_of(&sold_descriptor(&sold).expect("a descriptor")).is_none()); + // So does one this reader can't read, which Photoshop would still apply. + let mut template = photoshop_template(&split_warp()); + let Some((_, Value::Descriptor(q))) = template.items.iter_mut().find(|(k, _)| k.is("quiltWarp")) else { panic!("a quiltWarp") }; + set(q, "deformNumRows", Value::Integer(0)); + let sold = sold_bytes(Some(&template), &placed(transform, Some(&warp)), &mut Vec::new()); + assert!(quilt_of(&sold_descriptor(&sold).expect("a descriptor")).is_none()); + // At the limit the split warp is still written. + let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], crate::blocks::QUILT_MAX_PATCHES, 1); + mesh.points[0] = [-10.0, -5.0]; + let warp = Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]); + let mut warnings = Vec::new(); + let sold = sold_bytes(None, &placed(transform, Some(&warp)), &mut warnings); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); + assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(warp)); +} + +/// A split (multi-patch) custom warp is written as Photoshop writes it, a `quiltWarp` before a +/// `warpNone` `warp`, and reads back with its mesh and its transform. Before, the warp was +/// written as none while `Trnf` was still the image of its control-point box, so the layer +/// came back stretched and shifted. +#[test] +fn split_warp_round_trips_through_sold() { + use photocraft_geom::warp::BezierMesh; + let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 2, 1); + mesh.points[0] = [-10.0, -5.0]; + let warp = Warp::custom(mesh, [0.0, 0.0, 50.0, 25.0]); + let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; + let mut warnings = Vec::new(); + let sold = sold_bytes(None, &placed(transform, Some(&warp)), &mut warnings); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, transform); + assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(warp)); + let d = sold_descriptor(&sold).expect("a descriptor"); + let at = |key: &str| d.items.iter().position(|(k, _)| k.is(key)); + assert!(at("quiltWarp").expect("a quiltWarp") < at("warp").expect("a warp")); + let plain = get_desc(&d, "warp").expect("a warp"); + assert_eq!(enum_of(plain, "warpStyle"), Some(&b"warpNone"[..])); + assert!(plain.get("customEnvelopeWarp").is_none()); + let quilt = quilt_of(&d).expect("a quiltWarp"); + assert!(quilt.class_id.is("quiltWarp")); + assert_eq!((quilt.get("deformNumCols"), quilt.get("deformNumRows")), (Some(&Value::Integer(7)), Some(&Value::Integer(4)))); + let env = get_desc(quilt, "customEnvelopeWarp").expect("an envelope"); + let prefix = |k: &str| match env.get(k) { + Some(Value::ObjectArray(a)) => Some(a.prefix), + _ => None, + }; + assert_eq!((prefix("quiltSliceX"), prefix("quiltSliceY"), prefix("meshPoints")), (Some(3), Some(2), Some(28))); +} + +/// A template's split warp is replaced along with its `warp`: a warp changed to Arc, to none, +/// to one patch or to another mesh reads back as changed, not as the imported split warp. +#[test] +fn a_replaced_split_warp_does_not_come_back() { + use photocraft_geom::warp::BezierMesh; + let bounds = [0.0, 0.0, 50.0, 25.0]; + let split = split_warp(); + let template = photoshop_template(&split); + let arc = Warp::preset(WarpStyle::Arc, 30.0, bounds); + let mut one = BezierMesh::identity(bounds, 1, 1); + one.points[5][0] += 2.0; + let one = Warp::custom(one, bounds); + let mut resplit = BezierMesh::identity(bounds, 2, 2); + resplit.points[8][1] += 4.0; + let resplit = Warp::custom(resplit, bounds); + for w in [Some(arc), None, Some(one), Some(resplit)] { + let mut warnings = Vec::new(); + let sold = sold_bytes(Some(&template), &placed(Affine::IDENTITY, w.as_ref()), &mut warnings); + assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), w); + let d = sold_descriptor(&sold).expect("a descriptor"); + assert_eq!(quilt_of(&d).is_some(), w.as_ref().is_some_and(|w| w.mesh.as_ref().is_some_and(|m| m.points.len() > 16)), "{w:?}"); + assert!(warnings.is_empty(), "{warnings:?}"); + } +} + +/// An imported split warp that nothing changed keeps Photoshop's `quiltWarp` as stored when +/// the layer is rewritten for something else (here a move); a mesh edited on the same grid +/// keeps Photoshop's slices. +#[test] +fn an_imported_split_warp_keeps_photoshop_s_quilt() { + let template = photoshop_template(&split_warp()); + let read = crate::blocks::parse_placed_warp(b"SoLd", &sold_of(template.clone())).expect("the split warp"); + let moved = Affine { m: [1.0, 0.0, 0.0, 1.0, 4.0, 0.0] }; + let sold = sold_bytes(Some(&template), &placed(moved, Some(&read)), &mut Vec::new()); + let d = sold_descriptor(&sold).expect("a descriptor"); + assert_eq!(d.get("quiltWarp"), template.get("quiltWarp")); + assert_eq!(crate::blocks::parse_smart(b"SoLd", &sold).1, moved); + let mut edited = read.clone(); + if let Some(m) = edited.mesh.as_mut() { + m.points[12][0] += 1.5; + } + let sold = sold_bytes(Some(&template), &placed(Affine::IDENTITY, Some(&edited)), &mut Vec::new()); + assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(edited)); + let slices = |d: &Descriptor| { + let env = get_desc(quilt_of(d)?, "customEnvelopeWarp")?; + Some((env.get("quiltSliceX").cloned(), env.get("quiltSliceY").cloned())) + }; + assert_eq!(slices(&sold_descriptor(&sold).expect("a descriptor")), slices(&template)); +} + +/// The legacy `PlLd` record has no split warp: it stores none, with its corners framed by the +/// source rect, so a reader of `PlLd` alone places the layer where its transform puts it. +#[test] +fn plld_of_a_split_warp_is_framed_by_the_source() { + let warp = split_warp(); + let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; + let mut warnings = Vec::new(); + let plld = plld_bytes(&placed(transform, Some(&warp)), &mut warnings); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(crate::blocks::parse_plld_warp(&plld), crate::blocks::PlldWarp::None); + let (_, corners) = crate::blocks::parse_plld(&plld).expect("a record"); + assert_eq!(crate::blocks::plld_transform(&corners, Some((50.0, 25.0)), None).0, transform); +} + +/// Export writes `Trnf` as the image of the custom warp's control-point box, the inverse of +/// import: a spilled mesh comes back with the same transform and the quad Photoshop expects. +#[test] +fn warp_control_box_quad_round_trips() { + use photocraft_geom::warp::BezierMesh; + let mut mesh = BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 1, 1); + mesh.points[0] = [-10.0, -5.0]; + mesh.points[15] = [60.0, 25.0]; + let mut warp = Warp::preset(WarpStyle::Custom, 0.0, [0.0, 0.0, 50.0, 25.0]); + warp.mesh = Some(mesh); + let transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 120.0, 210.0] }; + let spec = PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (50.0, 25.0), dpi: 72.0, warp: Some(&warp), filter_fx: None }; + let sold = sold_bytes(None, &spec, &mut Vec::new()); + let p = parse_sold(&sold).expect("parses"); + let Some(Value::List(q)) = p.descriptor.get("Trnf") else { panic!("no Trnf") }; + let q: Vec = q.iter().filter_map(|v| num(Some(v))).collect(); + assert_eq!(q, [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]); + assert_eq!(p.transform, transform); + // The imported quad reads as unmoved, so the template's `Trnf` is kept as stored. + assert!(!quad_moved(&p.descriptor, &spec, spec.warp)); +} + +/// #4112: a regenerated `SoLd` (after Replace Contents, a move…) writes a cylinder back as +/// `warpCylinder` and its seven values, not as no warp, and frames its control-point box with +/// the quad, affine or projective, so import places it where it was. +#[test] +fn cylinder_warp_round_trips_through_sold() { + let v = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5]; + let warp = Warp::cylinder(&v, [0.0, 0.0, 1000.0, 1000.0]).unwrap(); + let transform = Affine { m: [0.5, 0.0, 0.0, 0.5, 40.0, 30.0] }; + let mut spec = + PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (1000.0, 1000.0), dpi: 72.0, warp: Some(&warp), filter_fx: None }; + let mut warnings = Vec::new(); + let sold = sold_bytes(None, &spec, &mut warnings); + assert!(warnings.is_empty(), "{warnings:?}"); + let p = parse_sold(&sold).expect("parses"); + let Some(Value::Descriptor(w)) = p.descriptor.get("warp") else { panic!("no warp") }; + assert_eq!(crate::blocks::enum_of(w, "warpStyle"), Some(b"warpCylinder".as_slice())); + let Some(Value::List(values)) = w.get("warpValues") else { panic!("no warpValues") }; + assert_eq!(values.iter().filter_map(|x| num(Some(x))).collect::>(), v); + assert!(w.get("customEnvelopeWarp").is_none()); + assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(warp.clone())); + for (a, b) in p.transform.m.iter().zip(transform.m) { + assert!((a - b).abs() < 1e-9, "{:?}", p.transform); + } + // The quad is the image of the control-point box, not of the source rect. + let cb = warp.mesh.as_ref().unwrap().control_bounds(); + let Some(Value::List(q)) = p.descriptor.get("Trnf") else { panic!("no Trnf") }; + let q: Vec = q.iter().filter_map(|x| num(Some(x))).collect(); + let want = [cb[0], cb[1], cb[2], cb[1], cb[2], cb[3], cb[0], cb[3]].map(|c| 0.5 * c); + for (i, (a, b)) in q.iter().zip(want).enumerate() { + let shift = if i % 2 == 0 { 40.0 } else { 30.0 }; + assert!((a - (b + shift)).abs() < 1e-9, "corner {i}: {q:?}"); + } + assert!(!quad_moved(&p.descriptor, &spec, spec.warp)); + // A projective placement comes back as the same map. + let h = photocraft_algo::transform::Homography::rect_to_quad(cb, [[10.0, 20.0], [410.0, 60.0], [400.0, 480.0], [30.0, 520.0]]).unwrap(); + spec.perspective = Some(h.0); + let sold = sold_bytes(None, &spec, &mut warnings); + let back = crate::blocks::parse_smart_perspective(b"SoLd", &sold).expect("projective"); + let n = |m: [f64; 9]| m.map(|x| x / m[8]); + for (a, b) in n(back).iter().zip(n(h.0)) { + assert!((a - b).abs() < 1e-9 * (1.0 + b.abs()), "{back:?} vs {:?}", h.0); + } + let plld = plld_bytes(&spec, &mut warnings); + assert_eq!(crate::blocks::parse_plld_warp(&plld), crate::blocks::PlldWarp::Warp(warp)); + assert!(warnings.is_empty(), "{warnings:?}"); +} + +#[test] +fn hex_and_uuid() { + assert_eq!(from_hex(&to_hex(&[0, 1, 0xab, 0xff])), Some(vec![0, 1, 0xab, 0xff])); + assert_eq!(from_hex("abc"), None); + assert_eq!(from_hex("zz"), None); + let u = uuid_from(b"x"); + assert_eq!(u.len(), 36); + assert_eq!(u, uuid_from(b"x")); + assert_ne!(u, uuid_from(b"y")); +} + +// Render filters as Photoshop 27 saves them on a smart object (`filterFXList` items, with +// neutral blending): Clouds and Difference Clouds in white on black, Fibers in black on white, +// Lens Flare with the 50-300mm Zoom at 159%. +const PHOTOSHOP_CLOUDS: &str = "0000000100000000000866696c746572465800000008000000004e6d202054455854000000070043006c006f00750064007300000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f7562000000000000000000000000466c74724f626a63000000070043006c006f007500640073000000000000436c64730000000100000000466c52736c6f6e67000049e40000000866696c74657249446c6f6e67436c6473"; +const PHOTOSHOP_DIFFERENCE_CLOUDS: &str = "0000000100000000000866696c746572465800000008000000004e6d202054455854000000120044006900660066006500720065006e0063006500200043006c006f00750064007300000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f7562000000000000000000000000466c74724f626a63000000120044006900660066006500720065006e0063006500200043006c006f007500640073000000000000446672430000000100000000466c52736c6f6e67000057d20000000866696c74657249446c6f6e6744667243"; +const PHOTOSHOP_FIBERS: &str = "0000000100000000000866696c746572465800000008000000004e6d2020544558540000000a004600690062006500720073002e002e002e00000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f756200000000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe0000000000000000000466c74724f626a630000000700460069006200650072007300000000000046627273000000030000000056726e636c6f6e670000001000000000537472676c6f6e670000000400000000526e64536c6f6e67000062f10000000866696c74657249446c6f6e6746627273"; +const PHOTOSHOP_LENS_FLARE: &str = "0000000100000000000866696c746572465800000008000000004e6d2020544558540000000e004c0065006e007300200046006c006100720065002e002e002e00000000000c626c656e644f7074696f6e734f626a63000000000000000c626c656e644f7074696f6e7300000002000000004f706374556e7446235072634059000000000000000000004d642020656e756d00000000426c6e4d000000066e6f726d616c00000000656e6162626f6f6c010000000a6861736f7074696f6e73626f6f6c0100000000467267434f626a630000000100000000000052474243000000030000000052642020646f756200000000000000000000000047726e20646f7562000000000000000000000000426c2020646f756200000000000000000000000042636b434f626a630000000100000000000052474243000000030000000052642020646f7562406fe000000000000000000047726e20646f7562406fe0000000000000000000426c2020646f7562406fe0000000000000000000466c74724f626a630000000b004c0065006e007300200046006c0061007200650000000000004c6e73460000000300000000427267686c6f6e670000009f00000000466c72434f626a6300000001000000000000506e7420000000020000000048727a6e646f75623fe86666600000000000000056727463646f75623fe60b60c0000000000000004c6e7320656e756d000000004c6e7320000000005a6d20200000000866696c74657249446c6f6e674c6e7346"; + +fn photoshop(hex: &str) -> Descriptor { + Descriptor::from_bytes(&from_hex(hex).unwrap()).unwrap() +} + +fn set_lens(item: &mut Descriptor, code: [u8; 4]) { + let Some(Value::Descriptor(fltr)) = item.items.iter_mut().find(|(k, _)| k.is("Fltr")).map(|(_, v)| v) else { panic!("no Fltr") }; + set(fltr, "Lns ", Value::Enumerated { type_id: Id::new("Lns "), value: Id::Code(code) }); +} + +#[test] +fn photoshop_render_filters_read_and_write_like_photoshop() { + let colours = |fg: f64, bg: f64| (json!([fg, fg, fg, 1.0]), json!([bg, bg, bg, 1.0])); + let (white, black) = colours(1.0, 0.0); + let cases = [ + (PHOTOSHOP_CLOUDS, "filter.render.clouds", json!({"seed": 18916, "foreground": white, "background": black})), + (PHOTOSHOP_DIFFERENCE_CLOUDS, "filter.render.differenceClouds", json!({"seed": 22482, "foreground": white, "background": black})), + (PHOTOSHOP_FIBERS, "filter.render.fibers", json!({"variance": 16, "strength": 4, "seed": 25329, "foreground": black, "background": white})), + ( + PHOTOSHOP_LENS_FLARE, + "filter.render.lensFlare", + json!({"brightness": 159, "centerX": 0.762499988079071, "centerY": 0.6888889074325562, "lens": "zoom"}), + ), + ]; + for (hex, command, params) in cases { + let item = photoshop(hex); + let f = filter_from_item(&item); + assert_eq!((f.command.as_str(), &f.params), (command, ¶ms)); + // Written back, it is Photoshop's item again: name, colours, settings and key order. + assert_eq!(item_for_filter(&f).unwrap().items, item.items, "{command}"); + } +} + +#[test] +fn every_lens_flare_lens_round_trips_with_photoshops_code() { + for (code, lens) in LENSES { + let mut item = photoshop(PHOTOSHOP_LENS_FLARE); + set_lens(&mut item, *code); + let f = filter_from_item(&item); + assert_eq!(f.params["lens"], lens); + assert_eq!(item_for_filter(&f).unwrap().items, item.items, "{lens}"); + } + // A lens we don't know keeps the filter verbatim. + let mut item = photoshop(PHOTOSHOP_LENS_FLARE); + set_lens(&mut item, *b"Xxxx"); + assert_eq!(filter_from_item(&item).command, UNSUPPORTED_FILTER); +} + +/// The descriptor at `path` (nested keys) inside `item`, for editing. +fn desc_at<'a>(item: &'a mut Descriptor, path: &[&str]) -> &'a mut Descriptor { + path.iter().fold(item, |d, key| { + let Some(Value::Descriptor(x)) = d.items.iter_mut().find(|(k, _)| k.is(key)).map(|(_, v)| v) else { panic!("no {key}") }; + x + }) +} + +#[test] +fn render_filters_with_settings_we_dont_model_stay_verbatim() { + // Each case changes one thing in a Photoshop item: an extra setting, a repeated one, or a + // value of another type than Photoshop writes. Opened as editable, a re-save would drop the + // extra setting or rewrite the value; kept verbatim, the item is written back byte for byte. + type Edit = Box; + /// A descriptor path in the item (nested keys) and the edit made there. + type Change = (&'static [&'static str], Edit); + let extra: fn(&mut Descriptor) = |d| d.items.push((Id::new("Xtra"), Value::Integer(1))); + let as_double = |key: &'static str| -> Edit { Box::new(move |d| set(d, key, Value::Double(1.0))) }; + let as_long = |key: &'static str| -> Edit { Box::new(move |d| set(d, key, Value::Integer(1))) }; + let repeat = |key: &'static str| -> Edit { + Box::new(move |d| { + let v = d.get(key).cloned().unwrap(); + d.items.push((Id::new(key), v)); + }) + }; + let colour_edits = || -> Vec { + vec![ + (&["FrgC"], Box::new(|d: &mut Descriptor| d.items.push((Id::new("redFloat"), Value::Double(0.5))))), + (&["BckC"], as_long("Grn ")), + (&["FrgC"], Box::new(|d: &mut Descriptor| set(d, "Rd ", Value::Double(300.0)))), + (&["BckC"], Box::new(|d: &mut Descriptor| d.class_id = Id::new("HSBC"))), + ] + }; + let mut cases: Vec<(&str, &'static [&'static str], Edit)> = Vec::new(); + for hex in [PHOTOSHOP_CLOUDS, PHOTOSHOP_DIFFERENCE_CLOUDS] { + cases.push((hex, &["Fltr"], Box::new(extra))); + cases.push((hex, &["Fltr"], repeat("FlRs"))); + cases.push((hex, &["Fltr"], as_double("FlRs"))); + cases.extend(colour_edits().into_iter().map(|(p, e)| (hex, p, e))); + } + cases.push((PHOTOSHOP_FIBERS, &["Fltr"], Box::new(extra))); + cases.push((PHOTOSHOP_FIBERS, &["Fltr"], repeat("Strg"))); + for key in ["Vrnc", "Strg", "RndS"] { + cases.push((PHOTOSHOP_FIBERS, &["Fltr"], as_double(key))); + } + cases.extend(colour_edits().into_iter().map(|(p, e)| (PHOTOSHOP_FIBERS, p, e))); + cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], Box::new(extra))); + cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], repeat("Brgh"))); + cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], as_double("Brgh"))); + cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr"], Box::new(|d| set(d, "Lns ", Value::Enumerated { type_id: Id::new("Xxxx"), value: Id::Code(*b"Zm ") })))); + cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr", "FlrC"], Box::new(extra))); + cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr", "FlrC"], as_long("Hrzn"))); + cases.push((PHOTOSHOP_LENS_FLARE, &["Fltr", "FlrC"], Box::new(|d| set(d, "Vrtc", Value::UnitFloat { unit: *b"#Pxl", value: 0.5 })))); + for (i, (hex, path, edit)) in cases.iter().enumerate() { + let mut item = photoshop(hex); + edit(desc_at(&mut item, path)); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "case {i} ({path:?}): {:?}", f.params); + assert_eq!(item_for_filter(&f).unwrap().to_bytes(), item.to_bytes(), "case {i} ({path:?})"); + } +} + +#[test] +fn render_filters_made_in_photocraft_are_written() { + // Without colours (an older document or a script), Photoshop's default black and white. + let back = filter_from_item(&item_for_filter(&sf("filter.render.clouds", json!({"seed": 7}))).unwrap()); + assert_eq!(back.params, json!({"seed": 7, "foreground": [0.0, 0.0, 0.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]})); + // A seed above i32::MAX keeps its bit pattern, and colours may be hex. + let p = json!({"variance": 30, "strength": 10, "seed": 4_000_000_000u32, "foreground": "#ff0000", "background": [0.0, 0.0, 1.0, 1.0]}); + let back = filter_from_item(&item_for_filter(&sf("filter.render.fibers", p)).unwrap()); + assert_eq!( + back.params, + json!({"variance": 30, "strength": 10, "seed": 4_000_000_000u32, "foreground": [1.0, 0.0, 0.0, 1.0], "background": [0.0, 0.0, 1.0, 1.0]}) + ); + let flare = sf("filter.render.lensFlare", json!({"brightness": 120, "centerX": 0.25, "centerY": 0.75, "lens": "moviePrime"})); + assert_eq!(filter_from_item(&item_for_filter(&flare).unwrap()).params, flare.params); + // Lenses and colours we can't write are reported, not guessed. + assert!(item_for_filter(&sf("filter.render.lensFlare", json!({"lens": "fisheye"}))).unwrap_err().contains("fisheye")); + assert!(item_for_filter(&sf("filter.render.clouds", json!({"foreground": "red"}))).is_err()); +} From 5286968033bf204a181eca1b620d68a50648a1fa Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:00 +0000 Subject: [PATCH 009/259] refactor(psd): move abr.rs tests to abr/tests.rs --- crates/psd/src/abr.rs | 301 +----------------------------------- crates/psd/src/abr/tests.rs | 298 +++++++++++++++++++++++++++++++++++ 2 files changed, 299 insertions(+), 300 deletions(-) create mode 100644 crates/psd/src/abr/tests.rs diff --git a/crates/psd/src/abr.rs b/crates/psd/src/abr.rs index 6a9f0806c5..35f4135a53 100644 --- a/crates/psd/src/abr.rs +++ b/crates/psd/src/abr.rs @@ -673,303 +673,4 @@ pub fn write_v6_folders( } #[cfg(test)] -mod tests { - use super::*; - use crate::descriptor::UnicodeString; - - fn sample(id: &str, w: u32, h: u32, depth: u16) -> AbrSample { - let bpp = usize::from(depth / 8); - let data = (0..w as usize * h as usize * bpp).map(|i| if (i / bpp) % 3 == 0 { 255 } else { (i % 7) as u8 * 30 }).collect(); - AbrSample { id: id.into(), width: w, height: h, depth, data } - } - - #[test] - fn embedded_patterns_spend_the_samples_budget() { - let p = PsdPattern { - mode: 3, - width: 5, - height: 3, - name: "p".into(), - id: "id".into(), - palette: None, - depth: 8, - channels: vec![vec![1; 15], vec![2; 15], vec![3; 15]], - alpha: None, - }; - let abr = write_v6(2, &[sample("s", 10, 10, 8)], &[p.clone(), p], &[], true).unwrap(); - let parse_within = |left: usize| { - let mut out = AbrFile::default(); - let mut budget = Budget(left); - parse_v6_within(&mut Rd::new(&abr[2..]), &mut out, &mut budget).unwrap(); - (out, budget.0) - }; - // 100 sample bytes plus two 45-byte patterns. - let (out, left) = parse_within(190); - assert_eq!((out.samples.len(), out.patterns.len(), left), (1, 2, 0)); - // One byte short: the patterns no longer fit after the sample (they used not to count). - let (out, left) = parse_within(189); - assert_eq!((out.samples.len(), out.patterns.len(), left), (1, 0, 14)); - assert!(out.warnings.iter().any(|w| w.contains("embedded patterns unreadable")), "{:?}", out.warnings); - } - - #[test] - fn failed_pattern_section_does_not_refund_budget_to_later_sections() { - let p = PsdPattern { - mode: 3, - width: 5, - height: 3, - name: "p".into(), - id: "id".into(), - palette: None, - depth: 8, - channels: vec![vec![1; 15], vec![2; 15], vec![3; 15]], - alpha: None, - }; - let valid = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let mut malformed = valid.clone(); - malformed.extend_from_slice(&100u32.to_be_bytes()); - - let mut body = 2u16.to_be_bytes().to_vec(); - section(&mut body, b"patt", &malformed); - section(&mut body, b"patt", &valid); - let mut out = AbrFile::default(); - let mut budget = Budget(60); - parse_v6_within(&mut Rd::new(&body), &mut out, &mut budget).unwrap(); - - assert!(out.patterns.is_empty(), "a failed block is discarded atomically"); - assert_eq!(budget.0, 0, "the failed block's first 45 bytes and later partial 15-byte charge are retained"); - assert_eq!(out.warnings.iter().filter(|w| w.contains("embedded patterns unreadable")).count(), 2); - } - - #[test] - fn v1_v2_round_trip_raw_and_rle() { - for version in [1u16, 2] { - for rle in [false, true] { - let brushes = vec![ - LegacyBrush { - name: String::new(), - spacing: 25, - anti_alias: true, - tip: LegacyTip::Computed { diameter: 19, hardness: 80, angle: -30, roundness: 50 }, - }, - LegacyBrush { - name: if version == 2 { "Leaf ✓".into() } else { String::new() }, - spacing: 40, - anti_alias: false, - tip: LegacyTip::Sampled(sample("", 13, 9, 8)), - }, - LegacyBrush { name: String::new(), spacing: 10, anti_alias: true, tip: LegacyTip::Sampled(sample("", 4, 6, 16)) }, - ]; - let bytes = write_v12(version, &brushes, rle).unwrap(); - let f = parse(&bytes).unwrap(); - assert_eq!(f.version, version); - assert_eq!(f.legacy, brushes, "v{version} rle={rle}"); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - } - } - } - - #[test] - fn v6_round_trip_both_subversions() { - let samples = vec![sample("$abc", 20, 11, 8), sample("$def", 5, 5, 16)]; - let preset = Descriptor::new("brushPreset") - .with("Nm ", Value::Text(UnicodeString::new_nul("Grass"))) - .with("Brsh", Value::Descriptor(Descriptor::new("sampledBrush").with("sampledData", Value::Text(UnicodeString::new_nul("$abc"))))); - for sub in [1u16, 2] { - for rle in [false, true] { - let bytes = write_v6(sub, &samples, &[], std::slice::from_ref(&preset), rle).unwrap(); - let f = parse(&bytes).unwrap(); - assert_eq!((f.version, f.subversion), (6, sub)); - assert_eq!(f.samples, samples); - assert_eq!(f.presets, vec![preset.clone()]); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - } - } - assert_eq!(samples[1].to_unit().len(), 25); - } - - #[test] - fn hostile_input_errors_without_panicking() { - assert!(parse(&[]).is_err()); - assert!(parse(&[0, 3, 0, 0]).is_err()); - assert!(parse(&[0, 6, 0, 9]).is_err()); - // Absurd sample bounds. - let mut s = sample("", 2, 2, 8); - s.width = MAX_EDGE + 1; - assert!(write_v12(1, &[LegacyBrush { name: String::new(), spacing: 1, anti_alias: true, tip: LegacyTip::Sampled(s) }], false).is_err()); - let good = write_v6(2, &[sample("$a", 30, 30, 8)], &[], &[Descriptor::new("brushPreset")], true).unwrap(); - for cut in 0..good.len() { - let _ = parse(&good[..cut]); - } - let v2 = write_v12(2, &[LegacyBrush { name: "x".into(), spacing: 1, anti_alias: true, tip: LegacyTip::Sampled(sample("", 9, 9, 16)) }], true).unwrap(); - for cut in 0..v2.len() { - let _ = parse(&v2[..cut]); - } - // Flip every byte once: never panics. - for i in 0..good.len() { - let mut b = good.clone(); - b[i] ^= 0xa5; - let _ = parse(&b); - } - // A huge declared count with no data is an error, not an allocation. - assert!(parse(&[0, 2, 0xff, 0xff]).is_err()); - } - - fn named(n: &str) -> Descriptor { - Descriptor::new("brushPreset").with("Nm ", Value::Text(UnicodeString::new_nul(n))) - } - - /// Hierarchy tokens: `G(name)` opens, `P` is a preset, `E` closes. - enum Tok<'a> { - G(&'a str), - P, - E, - } - - /// A v6 file with `n` presets and a hand-made `phry` token stream. - fn with_phry(n: usize, toks: &[Tok]) -> Vec { - let presets: Vec = (0..n).map(|i| named(&format!("B{i}"))).collect(); - let mut bytes = write_v6(2, &[], &[], &presets, false).unwrap(); - section(&mut bytes, b"phry", &phry_bytes(toks)); - bytes - } - - /// A `phry` section body holding `toks`. - fn phry_bytes(toks: &[Tok]) -> Vec { - let items = toks - .iter() - .map(|t| { - Value::Descriptor(match t { - Tok::G(name) => Descriptor::new("Grup") - .with("Nm ", Value::Text(UnicodeString::new_nul(name))) - .with("zuid", Value::Text(UnicodeString::new_nul("c9ee8fd5-eb7d-924c-9e95-ddc98e40bb6c"))), - Tok::P => Descriptor::new("preset"), - Tok::E => Descriptor::new("groupEnd"), - }) - }) - .collect(); - VersionedDescriptor::new(Descriptor::new("null").with("hierarchy", Value::List(items))).to_bytes() - } - - fn path(p: &[&str]) -> Vec { - p.iter().map(|s| s.to_string()).collect() - } - - #[test] - fn phry_flat_folders_like_photoshop_25() { - // The layout of Photoshop 25.1's default brushes: four folders, every preset in one. - use Tok::*; - let f = parse(&with_phry(5, &[G("General"), P, P, E, G("Dry Media"), P, E, G("Wet Media"), P, E, G("Special Effects"), P, E])).unwrap(); - assert_eq!(f.folders, vec![path(&["General"]), path(&["General"]), path(&["Dry Media"]), path(&["Wet Media"]), path(&["Special Effects"])]); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - } - - #[test] - fn phry_nested_folders_and_top_level_presets() { - use Tok::*; - let f = parse(&with_phry(5, &[P, G("Animals"), G("Birds"), P, E, P, G("Fish"), P, E, E, P])).unwrap(); - assert_eq!(f.folders, vec![path(&[]), path(&["Animals", "Birds"]), path(&["Animals"]), path(&["Animals", "Fish"]), path(&[])]); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - // No folder at all: no hierarchy. - let f = parse(&with_phry(2, &[P, P])).unwrap(); - assert!(f.folders.is_empty()); - } - - #[test] - fn phry_mismatches_become_warnings() { - use Tok::*; - // A stray groupEnd is ignored; an unclosed folder still holds its presets. - let f = parse(&with_phry(2, &[E, G("A"), P, E, E, G("B"), P])).unwrap(); - assert_eq!(f.folders, vec![path(&["A"]), path(&["B"])]); - assert!(f.warnings.iter().any(|w| w.contains("folder end")), "{:?}", f.warnings); - // Fewer preset tokens than presets: the rest are at the top level. - let f = parse(&with_phry(3, &[G("A"), P, E])).unwrap(); - assert_eq!(f.folders, vec![path(&["A"]), path(&[]), path(&[])]); - assert!(f.warnings.iter().any(|w| w.contains("list 1 brushes but the file holds 3")), "{:?}", f.warnings); - // More preset tokens than presets: extras ignored. - let f = parse(&with_phry(1, &[G("A"), P, P, P, E])).unwrap(); - assert_eq!(f.folders, vec![path(&["A"])]); - assert_eq!(f.presets.len(), 1); - assert!(!f.warnings.is_empty()); - // A depth bomb: folders deeper than the limit merge into their ancestor at the limit. - let mut toks: Vec = (0..10_000).map(|_| G("deep")).collect(); - toks.push(P); - toks.extend((0..10_000).map(|_| E)); - toks.extend([G("next"), P, E]); - let f = parse(&with_phry(2, &toks)).unwrap(); - assert_eq!(f.folders[0].len(), MAX_FOLDER_DEPTH); - assert_eq!(f.folders[1], path(&["next"])); - assert!(f.warnings.iter().any(|w| w.contains("deeper")), "{:?}", f.warnings); - // An unreadable hierarchy: imported flat, with a warning. - let mut bytes = write_v6(2, &[], &[], &[named("x")], false).unwrap(); - section(&mut bytes, b"phry", &[0, 0, 0, 16, 0xff, 0xff]); - let f = parse(&bytes).unwrap(); - assert!(f.folders.is_empty() && f.presets.len() == 1); - assert!(f.warnings.iter().any(|w| w.contains("phry")), "{:?}", f.warnings); - // Truncations and bit flips of a file with a hierarchy never panic. - let good = with_phry(3, &[G("A"), P, G("B"), P, E, E, P]); - for cut in 0..good.len() { - let _ = parse(&good[..cut]); - } - for i in 0..good.len() { - let mut b = good.clone(); - b[i] ^= 0x5a; - let _ = parse(&b); - } - } - - #[test] - fn phry_builds_paths_only_for_the_files_presets() { - use Tok::*; - // A few-KB section listing 100,000 deep presets for a file with 2: two paths are built. - let mut toks: Vec = (0..MAX_FOLDER_DEPTH).map(|_| G("folder")).collect(); - toks.extend((0..100_000).map(|_| P)); - let mut warnings = Vec::new(); - let folders = read_phry(&phry_bytes(&toks), 2, &mut warnings).unwrap(); - assert_eq!(folders.len(), 2); - assert_eq!(folders.capacity(), 2); - assert_eq!(folders[1].len(), MAX_FOLDER_DEPTH); - assert!(warnings.iter().any(|w| w.contains("list 100000 brushes but the file holds 2")), "{warnings:?}"); - // `phry` before `desc` still pairs with the file's presets. - let mut bytes = write_v6(2, &[], &[], &[named("a"), named("b")], false).unwrap(); - let at = bytes.windows(8).position(|w| w == b"8BIMdesc").unwrap(); - let mut phry = Vec::new(); - section(&mut phry, b"phry", &phry_bytes(&[G("A"), P, E, P])); - bytes.splice(at..at, phry); - let f = parse(&bytes).unwrap(); - assert_eq!(f.folders, vec![path(&["A"]), path(&[])]); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - } - - #[test] - fn phry_folder_paths_stay_within_their_byte_budget() { - use Tok::*; - // Thousands of presets under 32 folders of 255-character names would need ~27 MB of paths. - let long = "x".repeat(MAX_FOLDER_NAME); - let mut toks: Vec = (0..MAX_FOLDER_DEPTH).map(|_| G(&long)).collect(); - toks.extend((0..3_000).map(|_| P)); - let mut warnings = Vec::new(); - let folders = read_phry(&phry_bytes(&toks), 3_000, &mut warnings).unwrap(); - assert_eq!(folders.len(), 3_000); - let held: usize = folders.iter().flatten().map(|n| n.len() + size_of::()).sum(); - assert!(held <= MAX_FOLDER_BYTES, "{held}"); - assert_eq!(folders[0].len(), MAX_FOLDER_DEPTH); - assert!(folders[2_999].is_empty(), "past the budget: top level"); - assert!(warnings.iter().any(|w| w.contains("too large")), "{warnings:?}"); - } - - #[test] - fn phry_round_trips_through_the_writer() { - let presets: Vec = (0..6).map(|i| named(&format!("B{i}"))).collect(); - let folders = vec![path(&[]), path(&["Set", "Ink"]), path(&["Set", "Ink"]), path(&["Set"]), path(&["Other"]), path(&["Set", "Ink"])]; - let bytes = write_v6_folders(2, &[], &[], &presets, &folders, true).unwrap(); - let f = parse(&bytes).unwrap(); - assert_eq!(f.presets, presets); - assert_eq!(f.folders, folders); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - // No folders: no phry section, same bytes as write_v6. - assert_eq!(write_v6_folders(2, &[], &[], &presets, &vec![Vec::new(); 6], true).unwrap(), write_v6(2, &[], &[], &presets, true).unwrap()); - // Mismatched lengths are an error. - assert!(write_v6_folders(2, &[], &[], &presets, &folders[..2], true).is_err()); - } -} +mod tests; diff --git a/crates/psd/src/abr/tests.rs b/crates/psd/src/abr/tests.rs new file mode 100644 index 0000000000..29ed91ec6e --- /dev/null +++ b/crates/psd/src/abr/tests.rs @@ -0,0 +1,298 @@ +use super::*; +use crate::descriptor::UnicodeString; + +fn sample(id: &str, w: u32, h: u32, depth: u16) -> AbrSample { + let bpp = usize::from(depth / 8); + let data = (0..w as usize * h as usize * bpp).map(|i| if (i / bpp) % 3 == 0 { 255 } else { (i % 7) as u8 * 30 }).collect(); + AbrSample { id: id.into(), width: w, height: h, depth, data } +} + +#[test] +fn embedded_patterns_spend_the_samples_budget() { + let p = PsdPattern { + mode: 3, + width: 5, + height: 3, + name: "p".into(), + id: "id".into(), + palette: None, + depth: 8, + channels: vec![vec![1; 15], vec![2; 15], vec![3; 15]], + alpha: None, + }; + let abr = write_v6(2, &[sample("s", 10, 10, 8)], &[p.clone(), p], &[], true).unwrap(); + let parse_within = |left: usize| { + let mut out = AbrFile::default(); + let mut budget = Budget(left); + parse_v6_within(&mut Rd::new(&abr[2..]), &mut out, &mut budget).unwrap(); + (out, budget.0) + }; + // 100 sample bytes plus two 45-byte patterns. + let (out, left) = parse_within(190); + assert_eq!((out.samples.len(), out.patterns.len(), left), (1, 2, 0)); + // One byte short: the patterns no longer fit after the sample (they used not to count). + let (out, left) = parse_within(189); + assert_eq!((out.samples.len(), out.patterns.len(), left), (1, 0, 14)); + assert!(out.warnings.iter().any(|w| w.contains("embedded patterns unreadable")), "{:?}", out.warnings); +} + +#[test] +fn failed_pattern_section_does_not_refund_budget_to_later_sections() { + let p = PsdPattern { + mode: 3, + width: 5, + height: 3, + name: "p".into(), + id: "id".into(), + palette: None, + depth: 8, + channels: vec![vec![1; 15], vec![2; 15], vec![3; 15]], + alpha: None, + }; + let valid = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let mut malformed = valid.clone(); + malformed.extend_from_slice(&100u32.to_be_bytes()); + + let mut body = 2u16.to_be_bytes().to_vec(); + section(&mut body, b"patt", &malformed); + section(&mut body, b"patt", &valid); + let mut out = AbrFile::default(); + let mut budget = Budget(60); + parse_v6_within(&mut Rd::new(&body), &mut out, &mut budget).unwrap(); + + assert!(out.patterns.is_empty(), "a failed block is discarded atomically"); + assert_eq!(budget.0, 0, "the failed block's first 45 bytes and later partial 15-byte charge are retained"); + assert_eq!(out.warnings.iter().filter(|w| w.contains("embedded patterns unreadable")).count(), 2); +} + +#[test] +fn v1_v2_round_trip_raw_and_rle() { + for version in [1u16, 2] { + for rle in [false, true] { + let brushes = vec![ + LegacyBrush { + name: String::new(), + spacing: 25, + anti_alias: true, + tip: LegacyTip::Computed { diameter: 19, hardness: 80, angle: -30, roundness: 50 }, + }, + LegacyBrush { + name: if version == 2 { "Leaf ✓".into() } else { String::new() }, + spacing: 40, + anti_alias: false, + tip: LegacyTip::Sampled(sample("", 13, 9, 8)), + }, + LegacyBrush { name: String::new(), spacing: 10, anti_alias: true, tip: LegacyTip::Sampled(sample("", 4, 6, 16)) }, + ]; + let bytes = write_v12(version, &brushes, rle).unwrap(); + let f = parse(&bytes).unwrap(); + assert_eq!(f.version, version); + assert_eq!(f.legacy, brushes, "v{version} rle={rle}"); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + } + } +} + +#[test] +fn v6_round_trip_both_subversions() { + let samples = vec![sample("$abc", 20, 11, 8), sample("$def", 5, 5, 16)]; + let preset = Descriptor::new("brushPreset") + .with("Nm ", Value::Text(UnicodeString::new_nul("Grass"))) + .with("Brsh", Value::Descriptor(Descriptor::new("sampledBrush").with("sampledData", Value::Text(UnicodeString::new_nul("$abc"))))); + for sub in [1u16, 2] { + for rle in [false, true] { + let bytes = write_v6(sub, &samples, &[], std::slice::from_ref(&preset), rle).unwrap(); + let f = parse(&bytes).unwrap(); + assert_eq!((f.version, f.subversion), (6, sub)); + assert_eq!(f.samples, samples); + assert_eq!(f.presets, vec![preset.clone()]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + } + } + assert_eq!(samples[1].to_unit().len(), 25); +} + +#[test] +fn hostile_input_errors_without_panicking() { + assert!(parse(&[]).is_err()); + assert!(parse(&[0, 3, 0, 0]).is_err()); + assert!(parse(&[0, 6, 0, 9]).is_err()); + // Absurd sample bounds. + let mut s = sample("", 2, 2, 8); + s.width = MAX_EDGE + 1; + assert!(write_v12(1, &[LegacyBrush { name: String::new(), spacing: 1, anti_alias: true, tip: LegacyTip::Sampled(s) }], false).is_err()); + let good = write_v6(2, &[sample("$a", 30, 30, 8)], &[], &[Descriptor::new("brushPreset")], true).unwrap(); + for cut in 0..good.len() { + let _ = parse(&good[..cut]); + } + let v2 = write_v12(2, &[LegacyBrush { name: "x".into(), spacing: 1, anti_alias: true, tip: LegacyTip::Sampled(sample("", 9, 9, 16)) }], true).unwrap(); + for cut in 0..v2.len() { + let _ = parse(&v2[..cut]); + } + // Flip every byte once: never panics. + for i in 0..good.len() { + let mut b = good.clone(); + b[i] ^= 0xa5; + let _ = parse(&b); + } + // A huge declared count with no data is an error, not an allocation. + assert!(parse(&[0, 2, 0xff, 0xff]).is_err()); +} + +fn named(n: &str) -> Descriptor { + Descriptor::new("brushPreset").with("Nm ", Value::Text(UnicodeString::new_nul(n))) +} + +/// Hierarchy tokens: `G(name)` opens, `P` is a preset, `E` closes. +enum Tok<'a> { + G(&'a str), + P, + E, +} + +/// A v6 file with `n` presets and a hand-made `phry` token stream. +fn with_phry(n: usize, toks: &[Tok]) -> Vec { + let presets: Vec = (0..n).map(|i| named(&format!("B{i}"))).collect(); + let mut bytes = write_v6(2, &[], &[], &presets, false).unwrap(); + section(&mut bytes, b"phry", &phry_bytes(toks)); + bytes +} + +/// A `phry` section body holding `toks`. +fn phry_bytes(toks: &[Tok]) -> Vec { + let items = toks + .iter() + .map(|t| { + Value::Descriptor(match t { + Tok::G(name) => Descriptor::new("Grup") + .with("Nm ", Value::Text(UnicodeString::new_nul(name))) + .with("zuid", Value::Text(UnicodeString::new_nul("c9ee8fd5-eb7d-924c-9e95-ddc98e40bb6c"))), + Tok::P => Descriptor::new("preset"), + Tok::E => Descriptor::new("groupEnd"), + }) + }) + .collect(); + VersionedDescriptor::new(Descriptor::new("null").with("hierarchy", Value::List(items))).to_bytes() +} + +fn path(p: &[&str]) -> Vec { + p.iter().map(|s| s.to_string()).collect() +} + +#[test] +fn phry_flat_folders_like_photoshop_25() { + // The layout of Photoshop 25.1's default brushes: four folders, every preset in one. + use Tok::*; + let f = parse(&with_phry(5, &[G("General"), P, P, E, G("Dry Media"), P, E, G("Wet Media"), P, E, G("Special Effects"), P, E])).unwrap(); + assert_eq!(f.folders, vec![path(&["General"]), path(&["General"]), path(&["Dry Media"]), path(&["Wet Media"]), path(&["Special Effects"])]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); +} + +#[test] +fn phry_nested_folders_and_top_level_presets() { + use Tok::*; + let f = parse(&with_phry(5, &[P, G("Animals"), G("Birds"), P, E, P, G("Fish"), P, E, E, P])).unwrap(); + assert_eq!(f.folders, vec![path(&[]), path(&["Animals", "Birds"]), path(&["Animals"]), path(&["Animals", "Fish"]), path(&[])]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + // No folder at all: no hierarchy. + let f = parse(&with_phry(2, &[P, P])).unwrap(); + assert!(f.folders.is_empty()); +} + +#[test] +fn phry_mismatches_become_warnings() { + use Tok::*; + // A stray groupEnd is ignored; an unclosed folder still holds its presets. + let f = parse(&with_phry(2, &[E, G("A"), P, E, E, G("B"), P])).unwrap(); + assert_eq!(f.folders, vec![path(&["A"]), path(&["B"])]); + assert!(f.warnings.iter().any(|w| w.contains("folder end")), "{:?}", f.warnings); + // Fewer preset tokens than presets: the rest are at the top level. + let f = parse(&with_phry(3, &[G("A"), P, E])).unwrap(); + assert_eq!(f.folders, vec![path(&["A"]), path(&[]), path(&[])]); + assert!(f.warnings.iter().any(|w| w.contains("list 1 brushes but the file holds 3")), "{:?}", f.warnings); + // More preset tokens than presets: extras ignored. + let f = parse(&with_phry(1, &[G("A"), P, P, P, E])).unwrap(); + assert_eq!(f.folders, vec![path(&["A"])]); + assert_eq!(f.presets.len(), 1); + assert!(!f.warnings.is_empty()); + // A depth bomb: folders deeper than the limit merge into their ancestor at the limit. + let mut toks: Vec = (0..10_000).map(|_| G("deep")).collect(); + toks.push(P); + toks.extend((0..10_000).map(|_| E)); + toks.extend([G("next"), P, E]); + let f = parse(&with_phry(2, &toks)).unwrap(); + assert_eq!(f.folders[0].len(), MAX_FOLDER_DEPTH); + assert_eq!(f.folders[1], path(&["next"])); + assert!(f.warnings.iter().any(|w| w.contains("deeper")), "{:?}", f.warnings); + // An unreadable hierarchy: imported flat, with a warning. + let mut bytes = write_v6(2, &[], &[], &[named("x")], false).unwrap(); + section(&mut bytes, b"phry", &[0, 0, 0, 16, 0xff, 0xff]); + let f = parse(&bytes).unwrap(); + assert!(f.folders.is_empty() && f.presets.len() == 1); + assert!(f.warnings.iter().any(|w| w.contains("phry")), "{:?}", f.warnings); + // Truncations and bit flips of a file with a hierarchy never panic. + let good = with_phry(3, &[G("A"), P, G("B"), P, E, E, P]); + for cut in 0..good.len() { + let _ = parse(&good[..cut]); + } + for i in 0..good.len() { + let mut b = good.clone(); + b[i] ^= 0x5a; + let _ = parse(&b); + } +} + +#[test] +fn phry_builds_paths_only_for_the_files_presets() { + use Tok::*; + // A few-KB section listing 100,000 deep presets for a file with 2: two paths are built. + let mut toks: Vec = (0..MAX_FOLDER_DEPTH).map(|_| G("folder")).collect(); + toks.extend((0..100_000).map(|_| P)); + let mut warnings = Vec::new(); + let folders = read_phry(&phry_bytes(&toks), 2, &mut warnings).unwrap(); + assert_eq!(folders.len(), 2); + assert_eq!(folders.capacity(), 2); + assert_eq!(folders[1].len(), MAX_FOLDER_DEPTH); + assert!(warnings.iter().any(|w| w.contains("list 100000 brushes but the file holds 2")), "{warnings:?}"); + // `phry` before `desc` still pairs with the file's presets. + let mut bytes = write_v6(2, &[], &[], &[named("a"), named("b")], false).unwrap(); + let at = bytes.windows(8).position(|w| w == b"8BIMdesc").unwrap(); + let mut phry = Vec::new(); + section(&mut phry, b"phry", &phry_bytes(&[G("A"), P, E, P])); + bytes.splice(at..at, phry); + let f = parse(&bytes).unwrap(); + assert_eq!(f.folders, vec![path(&["A"]), path(&[])]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); +} + +#[test] +fn phry_folder_paths_stay_within_their_byte_budget() { + use Tok::*; + // Thousands of presets under 32 folders of 255-character names would need ~27 MB of paths. + let long = "x".repeat(MAX_FOLDER_NAME); + let mut toks: Vec = (0..MAX_FOLDER_DEPTH).map(|_| G(&long)).collect(); + toks.extend((0..3_000).map(|_| P)); + let mut warnings = Vec::new(); + let folders = read_phry(&phry_bytes(&toks), 3_000, &mut warnings).unwrap(); + assert_eq!(folders.len(), 3_000); + let held: usize = folders.iter().flatten().map(|n| n.len() + size_of::()).sum(); + assert!(held <= MAX_FOLDER_BYTES, "{held}"); + assert_eq!(folders[0].len(), MAX_FOLDER_DEPTH); + assert!(folders[2_999].is_empty(), "past the budget: top level"); + assert!(warnings.iter().any(|w| w.contains("too large")), "{warnings:?}"); +} + +#[test] +fn phry_round_trips_through_the_writer() { + let presets: Vec = (0..6).map(|i| named(&format!("B{i}"))).collect(); + let folders = vec![path(&[]), path(&["Set", "Ink"]), path(&["Set", "Ink"]), path(&["Set"]), path(&["Other"]), path(&["Set", "Ink"])]; + let bytes = write_v6_folders(2, &[], &[], &presets, &folders, true).unwrap(); + let f = parse(&bytes).unwrap(); + assert_eq!(f.presets, presets); + assert_eq!(f.folders, folders); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + // No folders: no phry section, same bytes as write_v6. + assert_eq!(write_v6_folders(2, &[], &[], &presets, &vec![Vec::new(); 6], true).unwrap(), write_v6(2, &[], &[], &presets, true).unwrap()); + // Mismatched lengths are an error. + assert!(write_v6_folders(2, &[], &[], &presets, &folders[..2], true).is_err()); +} From 35107dccae71a16f1e3dce5c5d48dfc75f278625 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:00 +0000 Subject: [PATCH 010/259] refactor(psd): move tiff.rs tests to tiff/tests.rs --- crates/psd/src/tiff.rs | 1015 +--------------------------------- crates/psd/src/tiff/tests.rs | 1012 +++++++++++++++++++++++++++++++++ 2 files changed, 1013 insertions(+), 1014 deletions(-) create mode 100644 crates/psd/src/tiff/tests.rs diff --git a/crates/psd/src/tiff.rs b/crates/psd/src/tiff.rs index 8b11a6b61e..450c81a7df 100644 --- a/crates/psd/src/tiff.rs +++ b/crates/psd/src/tiff.rs @@ -1656,1017 +1656,4 @@ pub mod transcode { } #[cfg(test)] -mod tests { - use super::transcode::*; - use super::*; - use crate::compression::Compression; - use crate::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; - use crate::header::ColorMode; - use crate::testgen; - - /// Keys the generator plants that the transcoder (rightly) does not know. - const UNKNOWN: [&[u8; 4]; 3] = [b"zOdd", b"zNop", b"Txt2"]; - - /// `d` without the blocks a little-endian round trip drops, and without the layer-info - /// padding (which follows the body length, so it changes when blocks are dropped). - fn known(d: &ImageSourceData) -> ImageSourceData { - let mut d = d.clone(); - d.byte_order = ByteOrder::Big; - d.global_blocks.retain(|b| !UNKNOWN.contains(&&b.key)); - if d.layer_info.is_none() { - d.layer_info_key = *b"Layr"; - } - if let Some(info) = &mut d.layer_info { - info.padding = None; - for l in &mut info.layers { - l.blocks.retain(|b| !UNKNOWN.contains(&&b.key)); - } - } - d - } - - fn roundtrip(d: &ImageSourceData) -> ImageSourceData { - let (big, w) = d.to_bytes(ByteOrder::Big).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.iter().all(|w| UNKNOWN.iter().any(|k| w.starts_with(std::str::from_utf8(*k).unwrap()))), "{w:?}"); - if w.is_empty() { - assert_eq!(big.len(), little.len()); - } - if big.len() > 36 { - assert_ne!(big, little); - assert!(little[36..].starts_with(b"MIB8")); - } - let (back_big, w) = ImageSourceData::from_bytes(&big).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let (back_little, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - if little.len() > 36 { - assert_eq!(back_little.byte_order, ByteOrder::Little); - } - assert_eq!(known(&back_little), known(&back_big)); - // The little-endian bytes are a fixed point (from the second generation on when blocks - // were dropped, since the layer-info padding then follows the shorter body). - let (little2, _) = back_little.to_bytes(ByteOrder::Little).unwrap(); - let little3 = ImageSourceData::from_bytes(&little2).unwrap().0.to_bytes(ByteOrder::Little).unwrap().0; - assert_eq!(little3, little2); - back_big - } - - #[test] - fn generated_files_survive_both_orders() { - for case in testgen::all_cases() { - let d = ImageSourceData::from_psd(&case.file); - let back = roundtrip(&d); - assert_eq!(back.version, d.version, "{}", case.name); - assert_eq!(known(&back), known(&d), "{}", case.name); - // Nothing but the planted unknown blocks is lost on the little-endian path. - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(known(&back), known(&d), "{}", case.name); - } - } - - #[test] - fn same_order_transcoding_is_the_identity() { - for case in testgen::all_cases() { - let d = ImageSourceData::from_psd(&case.file); - let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); - let (same, w) = transcode_blocks(&big[36..], d.version, ByteOrder::Big, ByteOrder::Big).unwrap(); - assert!(w.is_empty()); - assert_eq!(same, big[36..].to_vec(), "{}", case.name); - } - } - - fn sample_layers() -> ImageSourceData { - let file = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); - ImageSourceData::from_psd(&file) - } - - #[test] - fn signature_selects_the_version() { - let mut d = sample_layers(); - let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); - assert!(b.starts_with(SIGNATURE)); - d.version = Version::Psb; - let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); - assert!(b.starts_with(SIGNATURE_PSB)); - assert_eq!(ImageSourceData::from_bytes(&b).unwrap().0.version, Version::Psb); - roundtrip(&d); - } - - #[test] - fn layer_key_follows_depth() { - assert_eq!(layer_info_key(8), *b"Layr"); - assert_eq!(layer_info_key(16), *b"Lr16"); - assert_eq!(layer_info_key(32), *b"Lr32"); - for (depth, comp) in [(16, Compression::ZipPrediction), (32, Compression::ZipPrediction), (16, Compression::Rle)] { - let file = testgen::layered(Version::Psd, ColorMode::Rgb, depth, comp); - let d = ImageSourceData::from_psd(&file); - assert_eq!(d.layer_info_key, layer_info_key(depth)); - let back = roundtrip(&d); - assert_eq!(back.layer_info_key, d.layer_info_key); - // The 16/32-bit model goes back into a PSD as a global block, like Photoshop's. - let psd = back.into_psd(file.header.clone(), file.resources.clone(), file.image_data.clone()); - assert!(matches!(psd.layer_info_placement, LayerInfoPlacement::GlobalBlock { .. })); - let again = PsdFile::from_bytes(&psd.to_bytes().unwrap()).unwrap(); - assert_eq!(known(&ImageSourceData::from_psd(&again)).layer_info, known(&d).layer_info); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(known(&back).layer_info, known(&d).layer_info, "depth {depth}"); - } - } - - #[test] - fn blocks_are_padded_to_four() { - let d = sample_layers(); - let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); - let mut at = 36; - while at < b.len() { - assert_eq!(&b[at..at + 4], b"8BIM"); - let len = u32::from_be_bytes(b[at + 8..at + 12].try_into().unwrap()) as usize; - at += 12 + len; - at += (4 - at % 4) % 4; - } - assert_eq!(at, b.len()); - } - - fn block_rt(key: [u8; 4], data: Vec) -> (Vec, Vec) { - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(key, data.clone())], ..Default::default() }; - let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - assert_eq!(back.global_blocks[0].data, data); - assert_eq!(back.to_bytes(ByteOrder::Big).unwrap().0, big); - (big, little) - } - - #[test] - fn descriptor_blocks_swap_keys_and_numbers() { - let mut desc = Descriptor::new("null"); - desc.items.push((Id::new("Opct"), Value::UnitFloat { unit: *b"#Prc", value: 75.5 })); - desc.items.push((Id::new("Nm "), Value::Text(UnicodeString::new_nul("Drop Shadow")))); - desc.items.push((Id::new("enab"), Value::Boolean(true))); - desc.items.push((Id::new("Md "), Value::Enumerated { type_id: Id::new("BlnM"), value: Id::new("Mltp") })); - desc.items.push((Id::new("list"), Value::List(vec![Value::Integer(-3), Value::Double(1.5), Value::LargeInteger(7)]))); - desc.items.push((Id::new("longKeyName"), Value::Descriptor(Descriptor::new("innr")))); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor::new(desc).to_bytes()); - let (big, little) = block_rt(*b"lfx2", data); - // Keys are reversed and the version field swapped in the little-endian bytes. - assert!(little[36..].starts_with(b"MIB82xfl")); - let body_at = 48; - assert_eq!(&little[body_at..body_at + 4], &[0, 0, 0, 0]); - assert_eq!(&little[body_at + 4..body_at + 8], &[16, 0, 0, 0]); - assert_eq!(&big[body_at + 4..body_at + 8], &[0, 0, 0, 16]); - assert!(little.windows(4).any(|w| w == b"crP#"), "unit key reversed"); - assert!(little.windows(11).any(|w| w == b"longKeyName"), "string ids are not reversed"); - } - - #[test] - fn descriptor_references_by_identifier_and_index_keep_their_class() { - use crate::descriptor::{Class, ReferenceItem}; - let class = || Class { name: UnicodeString::new(""), class_id: Id::new("Lyr ") }; - let desc = Descriptor::new("null") - .with("null", Value::Reference(vec![ReferenceItem::Identifier { class: class(), id: 7 }, ReferenceItem::Index { class: class(), index: 2 }])); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor::new(desc).to_bytes()); - block_rt(*b"lfx2", data); - } - - fn type_layer_data() -> Vec { - let mut data = Vec::new(); - data.put_u16(1); - for value in [1.5, 0.0, -0.25, 1.75, 12.5, -3.25] { - data.put_f64(value); - } - data.put_u16(50); - let text = Descriptor::new("TxLr").with("Txt ", Value::Text(UnicodeString::new_nul("Synthetic Ω 🦀"))); - data.extend(VersionedDescriptor::new(text).to_bytes()); - data.put_u16(1); - data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); - for value in [11, -22, 333, 4_444] { - data.put_i32(value); - } - data - } - - fn tagged_payload<'a>(bytes: &'a [u8], signature_and_key: &[u8; 8], little: bool) -> &'a [u8] { - let block_at = bytes.windows(8).position(|window| window == signature_and_key).expect("tagged block"); - let length_at = block_at + 8; - let length_bytes: [u8; 4] = bytes.get(length_at..length_at + 4).expect("tagged block length").try_into().expect("four-byte length"); - let length = if little { u32::from_le_bytes(length_bytes) } else { u32::from_be_bytes(length_bytes) }; - let data_at = length_at + 4; - let data_end = data_at + usize::try_from(length).expect("test block length fits usize"); - bytes.get(data_at..data_end).expect("tagged block payload") - } - - fn legacy_little_endian_type_block() -> Vec { - let mut tysh = Vec::new(); - tysh.extend_from_slice(&1u16.to_le_bytes()); - for value in [1.5f64, 0.0, -0.25, 1.75, 12.5, -3.25] { - tysh.extend_from_slice(&value.to_le_bytes()); - } - tysh.extend_from_slice(&50u16.to_le_bytes()); - // Independently encode a little-endian `VersionedDescriptor` with a single TEXT value. - tysh.extend_from_slice(&16u32.to_le_bytes()); - tysh.extend_from_slice(&0u32.to_le_bytes()); // empty descriptor name - tysh.extend_from_slice(&0u32.to_le_bytes()); // four-character class id - tysh.extend_from_slice(b"rLxT"); // little-endian four-character class id - tysh.extend_from_slice(&1u32.to_le_bytes()); // one item - tysh.extend_from_slice(&0u32.to_le_bytes()); // four-character key - tysh.extend_from_slice(b" txT"); // little-endian four-character key - tysh.extend_from_slice(b"TXET"); // little-endian OSType - let mut units: Vec = "Synthetic Ω 🦀".encode_utf16().collect(); - units.push(0); // `new_nul`, matching the canonical fixture - tysh.extend_from_slice(&u32::try_from(units.len()).expect("short test string").to_le_bytes()); - for unit in units { - tysh.extend_from_slice(&unit.to_le_bytes()); - } - tysh.extend_from_slice(&1u16.to_le_bytes()); - // Empty warp descriptor, also encoded independently in little-endian order. - tysh.extend_from_slice(&16u32.to_le_bytes()); - tysh.extend_from_slice(&0u32.to_le_bytes()); // empty descriptor name - tysh.extend_from_slice(&4u32.to_le_bytes()); // `warp` is a four-byte string id - tysh.extend_from_slice(b"warp"); - tysh.extend_from_slice(&0u32.to_le_bytes()); // no items - for value in [11i32, -22, 333, 4_444] { - tysh.extend_from_slice(&value.to_le_bytes()); - } - - let mut image_source = super::SIGNATURE.to_vec(); - image_source.extend_from_slice(b"MIB8hSyT"); - image_source.extend_from_slice(&u32::try_from(tysh.len()).expect("short test block").to_le_bytes()); - image_source.extend_from_slice(&tysh); - let padding = (4 - tysh.len() % 4) % 4; - image_source.resize(image_source.len() + padding, 0); - image_source - } - - #[test] - fn type_block_write_keeps_text_descriptor_in_psd_order() { - let canonical = type_layer_data(); - let source = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"TySh", canonical.clone())], ..Default::default() }; - - let (little, warnings) = source.to_bytes(ByteOrder::Little).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - let payload = tagged_payload(&little, b"MIB8hSyT", true); - assert_eq!(payload.get(..2), Some(&[1, 0][..]), "TySh header stays in TIFF order"); - for (index, expected) in [1.5f64, 0.0, -0.25, 1.75, 12.5, -3.25].into_iter().enumerate() { - let start = 2 + index * 8; - let bytes: [u8; 8] = payload.get(start..start + 8).unwrap().try_into().unwrap(); - assert_eq!(f64::from_le_bytes(bytes), expected, "matrix element {index}"); - } - - let (text_descriptor, descriptor_len) = VersionedDescriptor::parse_prefix(canonical.get(52..).unwrap()).unwrap(); - let text_section_len = 2 + descriptor_len; - assert_eq!(payload.get(50..52), Some(&50u16.to_be_bytes()[..])); - assert_eq!(payload.get(52..56), Some(&16u32.to_be_bytes()[..])); - assert_eq!(payload.get(50..50 + text_section_len), canonical.get(50..50 + text_section_len)); - assert!(matches!(text_descriptor.descriptor.get("Txt "), Some(Value::Text(value)) if value.to_string_lossy() == "Synthetic Ω 🦀")); - let text_descriptor_from_output = VersionedDescriptor::parse_prefix(payload.get(52..).unwrap()).unwrap().0; - assert!(matches!(text_descriptor_from_output.descriptor.get("Txt "), Some(Value::Text(value)) if value.to_string_lossy() == "Synthetic Ω 🦀")); - - let warp_at = 50 + text_section_len; - assert_eq!(payload.get(warp_at..warp_at + 2), Some(&1u16.to_le_bytes()[..])); - let (_, warp_len) = VersionedDescriptor::parse_prefix(canonical.get(warp_at + 2..).unwrap()).unwrap(); - let warp_descriptor_at = warp_at + 2; - assert_eq!(payload.get(warp_descriptor_at..warp_descriptor_at + 4), Some(&16u32.to_le_bytes()[..])); - assert_eq!(payload.get(warp_descriptor_at + 4..warp_descriptor_at + 8), Some(&0u32.to_le_bytes()[..])); - assert_eq!(payload.get(warp_descriptor_at + 8..warp_descriptor_at + 12), Some(&4u32.to_le_bytes()[..])); - assert_eq!(payload.get(warp_descriptor_at + 12..warp_descriptor_at + 16), Some(b"warp".as_slice())); - assert_eq!(payload.get(warp_descriptor_at + 16..warp_descriptor_at + 20), Some(&0u32.to_le_bytes()[..])); - let bounds_at = warp_descriptor_at + warp_len; - for (index, expected) in [11i32, -22, 333, 4_444].into_iter().enumerate() { - let start = bounds_at + index * 4; - assert_eq!(payload.get(start..start + 4), Some(&expected.to_le_bytes()[..]), "bound {index}"); - } - - let (big, warnings) = source.to_bytes(ByteOrder::Big).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(tagged_payload(&big, b"8BIMTySh", false), canonical); - - let (reopened, warnings) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(reopened.global_blocks[0].data, canonical); - assert_eq!(reopened.to_bytes(ByteOrder::Big).unwrap().0, big); - } - - #[test] - fn legacy_little_endian_type_descriptor_still_imports() { - let input = legacy_little_endian_type_block(); - let (reopened, warnings) = ImageSourceData::from_bytes(&input).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(reopened.global_blocks[0].data, type_layer_data()); - } - - #[test] - fn type_block_layout() { - let mut data = Vec::new(); - data.put_u16(1); - for v in [1.0, 0.0, 0.0, 1.0, 12.5, -3.0] { - data.put_f64(v); - } - data.put_u16(50); - data.extend(VersionedDescriptor::new(Descriptor::new("TxLr")).to_bytes()); - data.put_u16(1); - data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); - for v in [0.0, 0.0, 100.0, 20.0] { - data.put_f64(v); - } - let (_, little) = block_rt(*b"TySh", data); - assert!(little[48..].starts_with(&[1, 0])); - assert_eq!(&little[50..58], &1.0f64.to_le_bytes()); - } - - #[test] - fn photoshop_type_block_switches_to_big_endian_after_its_matrix() { - let mut data = Vec::new(); - data.put_u16(1); - for v in [1.8054202887117468, 0.0, -0.143, 1.8063853899082987, 247.25, 2864.5] { - data.put_f64(v); - } - data.put_u16(50); - let text = Descriptor::new("TxLr").with("Txt ", Value::Text(UnicodeString::new_nul("Synthetic headline"))); - data.extend(VersionedDescriptor::new(text).to_bytes()); - data.put_u16(1); - data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); - for v in [0, 0, 120, 30] { - data.put_i32(v); - } - let (_, mut little) = block_rt(*b"TySh", data.clone()); - // Photoshop uses big-endian text but returns to little-endian for warp/bounds. - let (_, used) = VersionedDescriptor::parse_prefix(&data[52..]).unwrap(); - little[98..100 + used].copy_from_slice(&data[50..52 + used]); - let (back, warnings) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - assert!(!back.global_blocks[0].is_foreign_order()); - assert_eq!(back.global_blocks[0].data, data); - // The normalized model remains writable in either order. - for order in [ByteOrder::Big, ByteOrder::Little] { - let (bytes, warnings) = back.to_bytes(order).unwrap(); - assert!(warnings.is_empty()); - let (again, warnings) = ImageSourceData::from_bytes(&bytes).unwrap(); - assert!(warnings.is_empty()); - assert_eq!(again.global_blocks[0].data, data); - } - } - - #[test] - fn legacy_effects_and_adjustments() { - // lrFX with a drop shadow and a solid fill. - let mut fx = Vec::new(); - fx.put_u16(0); - fx.put_u16(3); - fx.put(b"8BIMcmnS"); - fx.put_u32(7); - fx.put_u32(0); - fx.put_u8(1); - fx.put_u16(0); - fx.put(b"8BIMdsdw"); - let mut sh = Vec::new(); - sh.put_u32(2); - for v in [5 << 16, 75 << 16, 120 << 16, 7 << 16] { - sh.put_i32(v); - } - for _ in 0..5 { - sh.put_u16(0); - } - sh.put(b"8BIMmul "); - sh.put_u8(1); - sh.put_u8(1); - sh.put_u8(191); - sh.put_u16(0); - sh.put_u16(0x1234); - sh.put_u16(0); - sh.put_u16(0); - sh.put_u16(0); - fx.put_u32(sh.len() as u32); - fx.put(&sh); - fx.put(b"8BIMsofi"); - let mut so = Vec::new(); - so.put_u32(2); - so.put(b"8BIMnorm"); - so.put_u16(0); - so.put_u16(0xffff); - so.put_u16(0); - so.put_u16(0); - so.put_u16(0); - so.put_u8(255); - so.put_u8(1); - so.put_u16(0); - so.put_u16(0xffff); - so.put_u16(0); - so.put_u16(0); - so.put_u16(0); - fx.put_u32(so.len() as u32); - fx.put(&so); - let (_, little) = block_rt(*b"lrFX", fx); - assert!(little.windows(8).any(|w| w == b"MIB8wdsd"), "effect keys reversed"); - assert!(little.windows(2).any(|w| w == [0x34, 0x12]), "colour component swapped"); - - // levl: version + 29 records + the Lvls extension. - let mut lv = Vec::new(); - lv.put_u16(2); - for i in 0..29 * 5 { - lv.put_u16(i as u16); - } - lv.put(b"Lvls"); - lv.put_u16(3); - lv.put_u16(33); - for i in 0..4 * 5 { - lv.put_u16(1000 + i as u16); - } - let (_, little) = block_rt(*b"levl", lv); - assert!(little.windows(4).any(|w| w == b"slvL")); - - // curv with the Crv extension. - let mut cv = vec![0u8]; - cv.put_u16(1); - cv.put_u32(0b101); - cv.put_u16(2); - cv.put_u16(0); - cv.put_u16(0); - cv.put_u16(255); - cv.put_u16(255); - cv.put_u16(1); - cv.put_u16(128); - cv.put_u16(100); - cv.put(b"Crv "); - cv.put_u16(4); - cv.put_u32(1); - cv.put_u16(2); - cv.put_u16(1); - cv.put_u16(7); - cv.put_u16(9); - block_rt(*b"curv", cv); - - for (key, data) in [ - (*b"hue2", vec![0, 2, 0, 0, 0, 10, 0, 20, 0, 30, 0, 40, 0, 50, 0, 60]), - (*b"brit", vec![0, 10, 0, 20, 0, 30, 1, 0]), - (*b"thrs", vec![0, 128, 0, 0]), - (*b"post", vec![0, 4, 0, 0]), - (*b"nvrt", vec![]), - (*b"expA", [1u16.to_be_bytes().to_vec(), 0.5f32.to_be_bytes().to_vec(), 0.0f32.to_be_bytes().to_vec(), 1.0f32.to_be_bytes().to_vec()].concat()), - (*b"blnc", vec![0; 20]), - (*b"mixr", vec![0, 1, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0]), - (*b"selc", vec![0, 1, 0, 0, 0, 5, 0, 6, 0, 7, 0, 8]), - (*b"phfl", vec![0, 3, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 25, 1, 0]), - (*b"phfl", vec![0, 2, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 0, 0, 25, 1, 0]), - (*b"lclr", vec![0, 1, 0, 0, 0, 0, 0, 0]), - (*b"fxrp", [1.5f64.to_be_bytes().to_vec(), 2.5f64.to_be_bytes().to_vec()].concat()), - (*b"brst", vec![0, 0, 0, 1, 0, 0, 0, 2]), - (*b"FMsk", vec![0, 0, 255, 255, 0, 0, 0, 0, 0, 0, 0, 50]), - (*b"lsct", [3u32.to_be_bytes().to_vec(), b"8BIMpass".to_vec()].concat()), - (*b"lspf", vec![0, 0, 0, 5]), - (*b"lnsr", b"layr".to_vec()), - (*b"knko", vec![1, 0, 0, 0]), - (*b"knko", vec![2, 0, 0, 0]), - (*b"infx", vec![1, 0, 0, 0]), - (*b"clbl", vec![0, 0, 0, 0]), - (*b"tsly", vec![0, 0, 0, 0]), - (*b"lmgm", vec![1, 0, 0, 0]), - (*b"vmgm", vec![1, 0, 0, 0]), - (*b"iOpa", vec![128, 0, 0, 0]), - ] { - let (big, little) = block_rt(key, data.clone()); - if data.len() >= 2 && key != *b"nvrt" { - assert_ne!(big, little, "{}", String::from_utf8_lossy(&key)); - } - } - } - - #[test] - fn global_layer_mask_block() { - let d = ImageSourceData { global_layer_mask: Some(GlobalLayerMask { data: vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 128, 0] }), ..Default::default() }; - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.is_empty()); - assert!(little[36..].starts_with(b"MIB8ksML")); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(back.global_layer_mask, d.global_layer_mask); - assert_eq!(back.global_layer_mask.unwrap().opacity(), Some(50)); - } - - #[test] - fn gradient_map_layout() { - let mut g = Vec::new(); - g.put_u16(3); - g.put_u8(0); - g.put_u8(1); - g.put(b"Lnr "); - g.put_u32(2); - g.put_u16(u16::from(b'a')); - g.put_u16(0); - g.put_u16(2); - for (loc, mid) in [(0u32, 50u32), (4096, 50)] { - g.put_u32(loc); - g.put_u32(mid); - g.put_u16(0); - g.put_u16(0x1111); - g.put_u16(0x2222); - g.put_u16(0x3333); - g.put_u16(0); - g.put_u16(0); - } - g.put_u16(2); - for loc in [0u32, 4096] { - g.put_u32(loc); - g.put_u32(50); - g.put_u16(100); - } - g.put_u16(2); - g.put_u16(1); - g.put_u16(32); - g.put_u16(0); - g.put_u32(0xdead_beef); - for _ in 0..12 { - g.put_u16(0); - } - let (_, little) = block_rt(*b"grdm", g); - assert!(little.windows(4).any(|w| w == 0xdead_beefu32.to_le_bytes())); - assert!(little.windows(4).any(|w| w == b" rnL")); - } - - #[test] - fn vector_mask_records() { - let mut v = Vec::new(); - v.put_u32(3); - v.put_u32(0); - // Closed length record, then two linked knots. - v.put_u16(0); - v.put_u16(2); - v.put_i16(1); - v.put(&[0; 20]); - for sel in [1u16, 1] { - v.put_u16(sel); - for i in 0..6 { - v.put_i32((i + 1) * 0x0010_0000); - } - } - let (_, little) = block_rt(*b"vmsk", v); - assert!(little.windows(4).any(|w| w == [0, 0, 0x10, 0]), "fixed-point coordinate swapped"); - } - - #[test] - fn pattern_block() { - let plane: Vec = (0..16u8).collect(); - let p = crate::patterns::PsdPattern { - mode: 3, - width: 4, - height: 4, - name: "dots".into(), - id: "abc".into(), - palette: None, - depth: 8, - channels: vec![plane.clone(), plane.clone(), plane.clone()], - alpha: Some(plane), - }; - let data = crate::patterns::write_pattern_block(std::slice::from_ref(&p)).unwrap(); - block_rt(*b"Patt", data.clone()); - // Little-endian pattern data parses back into the same pattern. - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"Patt", data)], ..Default::default() }; - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(crate::patterns::parse_pattern_block(&back.global_blocks[0].data).unwrap(), vec![p]); - } - - #[test] - fn filter_effects_block() { - use crate::filter_effects::{EffectsPlane, FilterEffects, FilterEffectsItem}; - let plane = EffectsPlane::encode(Compression::Rle, &[1, 2, 3, 4, 5, 6], 3, 2, 8).unwrap(); - let mask = EffectsPlane::encode(Compression::Raw, &[9; 6], 3, 2, 8).unwrap(); - let rect = crate::layer::Rect { top: 0, left: 0, bottom: 2, right: 3 }; - let fx = FilterEffects { - version: 1, - items: vec![FilterEffectsItem { - id: "x".into(), - version: 1, - rect, - depth: 8, - max_channels: 1, - slots: vec![Some(plane.clone()), None, Some(plane)], - mask: Some((rect, mask)), - }], - }; - let data = fx.to_bytes(); - block_rt(*b"FEid", data.clone()); - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"FEid", data)], ..Default::default() }; - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(FilterEffects::parse(&back.global_blocks[0].data).unwrap(), fx); - } - - /// Photoshop writes one `FEid` section per smart object: every section's lengths and - /// numbers are swapped, not only the first one's. - #[test] - fn filter_effects_block_swaps_every_section() { - use crate::filter_effects::{EffectsPlane, FilterEffects, FilterEffectsItem}; - let rect = crate::layer::Rect { top: 0, left: 0, bottom: 2, right: 3 }; - let item = |id: &str, v: u8| FilterEffectsItem { - id: id.into(), - version: 1, - rect, - depth: 8, - max_channels: 1, - slots: vec![Some(EffectsPlane::encode(Compression::Raw, &[v; 6], 3, 2, 8).unwrap()), None, None], - mask: None, - }; - let fx = FilterEffects { version: 1, items: vec![item("first", 1), item("second-object", 2)] }; - let data = fx.to_bytes(); - let len1 = u64::from_be_bytes(data[4..12].try_into().unwrap()) as usize; - let second = 12 + len1 + (4 - len1 % 4) % 4; - let len2 = &data[second..second + 8]; - block_rt(*b"FEid", data.clone()); - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"FEid", data.clone())], ..Default::default() }; - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - // 36-byte signature, then `MIB8`, the reversed key and a u32 length: the block data. - let body = &little[36 + 12..]; - let mut swapped = len2.to_vec(); - swapped.reverse(); - assert_eq!(&body[second..second + 8], &swapped[..], "second section's length is little-endian"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - assert_eq!(FilterEffects::parse(&back.global_blocks[0].data).unwrap(), fx); - } - - #[test] - fn metadata_setting_items() { - let desc = VersionedDescriptor::new(Descriptor::new("null")).to_bytes(); - let items = vec![crate::metadata::MetadataItem::new(*b"cmls", desc)]; - block_rt(*b"shmd", crate::metadata::write_shmd(&items)); - // An unknown item cannot be converted: it is dropped on its own, the rest stays. - let items = vec![ - crate::metadata::MetadataItem::new(*b"zzzz", vec![1, 2, 3, 4, 5, 6, 7, 8]), - crate::metadata::MetadataItem::new(*b"mdyn", vec![0, 0, 0, 1]), - crate::metadata::MetadataItem::new(*b"cmls", VersionedDescriptor::new(Descriptor::new("null")).to_bytes()), - ]; - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"shmd", crate::metadata::write_shmd(&items))], ..Default::default() }; - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert_eq!(w.len(), 1, "{w:?}"); - assert!(w[0].starts_with("shmd item zzzz dropped"), "{}", w[0]); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty()); - let back_items = crate::metadata::parse_shmd(&back.global_blocks[0].data).unwrap(); - assert_eq!(back_items, items[1..].to_vec()); - } - - #[test] - fn unknown_descriptor_shaped_blocks_are_converted() { - // A key the transcoder has never heard of, holding a versioned descriptor (as every - // block Photoshop added since CS6 does): converted, not dropped. - let mut desc = Descriptor::new("null"); - desc.items.push((Id::new("Nm "), Value::Text(UnicodeString::new_nul("x")))); - let data = VersionedDescriptor::new(desc.clone()).to_bytes(); - block_rt(*b"Qqqq", data); - let mut with_version = 3u32.to_be_bytes().to_vec(); - with_version.extend(VersionedDescriptor::new(desc).to_bytes()); - block_rt(*b"Qqqq", with_version); - // Empty data needs no conversion either. - block_rt(*b"Mt32", Vec::new()); - } - - #[test] - fn linked_layer_items() { - // One embedded file (liFD, version 7) as photocraft-io writes it. - let mut item = Vec::new(); - item.put(b"liFD"); - item.put_u32(7); - item.put_u8(4); - item.put(b"uuid"); - let units: Vec = "a.png\0".encode_utf16().collect(); - item.put_u32(units.len() as u32); - for u in units { - item.put_u16(u); - } - item.put(b"png "); - item.put(b"8BIM"); - let bytes = [0x89, b'P', b'N', b'G', 1, 2, 3]; - item.put_u64(bytes.len() as u64); - item.put_u8(0); - item.put(&bytes); - item.put_u32(0); - item.put_f64(0.0); - item.put_u8(0); - let mut data = (item.len() as u64).to_be_bytes().to_vec(); - data.put(&item); - while !data.len().is_multiple_of(4) { - data.push(0); - } - let (_, little) = block_rt(*b"lnk2", data); - assert!(little.windows(4).any(|w| w == b"DFil"), "item type key reversed"); - assert!(little.windows(7).any(|w| w == bytes), "file bytes untouched"); - } - - #[test] - fn annotation_block() { - let mut a = Vec::new(); - a.put_u16(2); - a.put_u16(1); - a.put_u32(1); - let mut item = Vec::new(); - item.put(b"txtA"); - item.put_u8(0); - item.put_u8(1); - item.put_u16(0); - for v in [10, 20, 30, 40, 50, 60, 70, 80] { - item.put_i32(v); - } - item.put_u16(0); - for v in [0xffff, 0, 0, 0] { - item.put_u16(v); - } - for s in [&b"me"[..], b"note", b"2026"] { - item.put_u8(s.len() as u8); - item.put(s); - if (1 + s.len()) % 2 == 1 { - item.put_u8(0); - } - } - let text = [0xfe, 0xff, 0, b'h', 0, b'i']; - let mut d = Vec::new(); - d.put(b"txtC"); - d.put_u32(text.len() as u32); - d.put(&text); - item.put_u32(d.len() as u32 + 4); - item.put(&d); - a.put_u32(item.len() as u32 + 4); - a.put(&item); - let (_, little) = block_rt(*b"Anno", a); - assert!(little.windows(4).any(|w| w == b"Atxt")); - assert!(little.windows(6).any(|w| w == text), "text kept as stored"); - } - - #[test] - fn unknown_blocks_kept_in_big_dropped_in_little() { - let mut d = sample_layers(); - d.global_blocks.push(TaggedBlock::new(*b"Zzzz", vec![1, 2, 3, 4, 5])); - let (big, w) = d.to_bytes(ByteOrder::Big).unwrap(); - assert!(w.is_empty()); - let (back, w) = ImageSourceData::from_bytes(&big).unwrap(); - assert!(w.is_empty()); - assert_eq!(back.global_blocks, d.global_blocks); - // Big-endian data of unknown layout cannot go into a little-endian file. - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert_eq!(w.iter().filter(|w| w.starts_with("Zzzz block (5 bytes) dropped")).count(), 1, "{w:?}"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty()); - assert_eq!(back.global_blocks.iter().map(|b| b.key).collect::>(), vec![*b"Patt", *b"FMsk"]); - assert_eq!(known(&back).layer_info, known(&d).layer_info); - } - - #[test] - fn unknown_blocks_from_a_little_endian_file_are_kept_with_their_byte_order() { - let d = sample_layers(); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - // A little-endian file with a block of unknown layout, among known ones. - let mut raw = little.clone(); - raw.extend_from_slice(b"MIB8zzzZ"); - raw.extend_from_slice(&6u32.to_le_bytes()); - raw.extend_from_slice(&[9, 8, 7, 6, 5, 4, 0, 0]); - raw.extend_from_slice(b"MIB8diyl"); - raw.extend_from_slice(&4u32.to_le_bytes()); - raw.extend_from_slice(&7u32.to_le_bytes()); - let (back, w) = ImageSourceData::from_bytes(&raw).unwrap(); - assert!(w.is_empty(), "{w:?}"); - assert_eq!(known(&back).layer_info, known(&d).layer_info); - let kept = back.global_blocks.iter().find(|b| &b.key == b"Zzzz").expect("kept"); - assert!(kept.is_foreign_order()); - assert_eq!(kept.signature, *b"MIB8"); - assert_eq!(kept.data, [9, 8, 7, 6, 5, 4]); - // The known block after it was still converted. - assert_eq!(back.global_blocks.iter().find(|b| &b.key == b"lyid").unwrap().data, 7u32.to_be_bytes()); - // Written back to a little-endian TIFF, the bytes are exactly what was read. - let (again, w) = back.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let tail = &raw[raw.len() - 18 - 16..]; - assert!(again.windows(tail.len()).any(|x| x == tail), "foreign-order block restored verbatim"); - assert_eq!(ImageSourceData::from_bytes(&again).unwrap().0.global_blocks, back.global_blocks); - // The big-endian (PSD) model keeps the marker, so a PSD writer can tell it apart. - let (big, _) = back.to_bytes(ByteOrder::Big).unwrap(); - assert!(big.windows(8).any(|x| x == b"MIB8Zzzz")); - assert_eq!(ImageSourceData::from_bytes(&big).unwrap().0.global_blocks, back.global_blocks); - } - - /// A PSB keeps `Mt16`/`Mt32`/`Mtrn`/`Alph` blocks of unknown layout verbatim, and their - /// length field is 8 bytes (a PSB long key). Writing them into a little-endian TIFF must - /// read that width; the old code looked the key up after reversing it for the target - /// order, which never matches `PSB_LONG_KEYS`. - #[test] - fn psb_foreign_order_long_key_roundtrips() { - let d = ImageSourceData { - version: Version::Psb, - byte_order: ByteOrder::Little, - global_blocks: vec![TaggedBlock { signature: *b"MIB8", key: *b"Mt16", data: vec![9, 8, 7, 6, 5, 4], padding: None }], - ..Default::default() - }; - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - assert_eq!(back.global_blocks, d.global_blocks, "the 8-byte length and the bytes survive"); - } - - #[test] - fn rle_counts_follow_the_container_and_samples_do_not() { - let file = testgen::layered(Version::Psd, ColorMode::Rgb, 16, Compression::Rle); - let d = ImageSourceData::from_psd(&file); - let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - let d = known(&d); - let (a, b) = (d.layer_info.as_ref().unwrap(), back.layer_info.as_ref().unwrap()); - for (la, lb) in a.layers.iter().zip(&b.layers) { - for (ca, cb) in la.channels.iter().zip(&lb.channels) { - assert_eq!(ca, cb); - let (w, h) = la.channel_rect(ca.id).size().unwrap(); - assert_eq!(ca.decode(w, h, 16, Version::Psd).unwrap(), cb.decode(w, h, 16, Version::Psd).unwrap()); - } - } - // The encoded samples (after the count table) are identical bytes in both files, while - // the count table itself is swapped. - let (rec, ch) = a - .layers - .iter() - .flat_map(|l| l.channels.iter().filter(|c| c.id >= -1 && c.compression == Some(Compression::Rle)).map(move |c| (l, c))) - .find(|(l, c)| l.rect.height() > 1 && c.data.len() > l.rect.height() as usize * 2 + 8) - .unwrap(); - let table = rec.rect.height() as usize * 2; - let samples = &ch.data[table..]; - assert!(big.windows(samples.len()).any(|w| w == samples)); - assert!(little.windows(samples.len()).any(|w| w == samples)); - let counts = &ch.data[..table]; - let swapped: Vec = counts.chunks(2).flat_map(|c| [c[1], c[0]]).collect(); - assert!(little.windows(table + samples.len()).any(|w| w[..table] == swapped[..] && w[table..] == *samples)); - } - - #[test] - fn blending_ranges_are_bytes_in_either_order() { - let mut file = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); - let ranges: Vec = [0u8, 0, 255, 255].repeat(10); - let marked: Vec = (1u8..=40).collect(); - for (i, l) in file.layer_info.as_mut().unwrap().layers.iter_mut().enumerate() { - l.blending_ranges.data = if i == 0 { marked.clone() } else { ranges.clone() }; - } - let d = ImageSourceData::from_psd(&file); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - // Written verbatim (what Photoshop writes in an `II` TIFF), not swapped per u32. - assert!(little.windows(marked.len()).any(|w| w == marked)); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - for (a, b) in d.layer_info.as_ref().unwrap().layers.iter().zip(&back.layer_info.as_ref().unwrap().layers) { - assert_eq!(a.blending_ranges, b.blending_ranges); - } - } - - #[test] - fn psb_sized_data_uses_long_lengths_and_counts() { - let file = testgen::layered(Version::Psb, ColorMode::Cmyk, 8, Compression::Rle); - let d = ImageSourceData::from_psd(&file); - assert_eq!(d.version, Version::Psb); - let back = roundtrip(&d); - assert_eq!(back.layer_info, d.layer_info); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(little[36..].starts_with(b"MIB8")); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(known(&back).layer_info, known(&d).layer_info); - } - - #[test] - fn resources_both_orders() { - let res = vec![ - ImageResource::new(1005, vec![0, 72, 0, 0, 0, 1, 0, 1, 0, 72, 0, 0, 0, 1, 0, 1]), - ImageResource::new(1037, vec![0, 0, 0, 120]), - ImageResource::new(1039, vec![1, 2, 3]), - ImageResource { signature: *b"8BIM", id: 1026, name: b"grp".to_vec(), data: vec![0, 1, 0, 1, 0, 0] }, - ]; - let big = resources_to_bytes(&res).unwrap(); - let (back, w) = resources_from_bytes(&big).unwrap(); - assert!(w.is_empty()); - assert_eq!(back, res); - let (little, w) = transcode_resources(&big, ByteOrder::Big, ByteOrder::Little).unwrap(); - assert!(w.is_empty()); - assert!(little.starts_with(b"MIB8")); - assert_eq!(little.len(), big.len()); - assert_eq!(&little[4..6], &[0xed, 3]); - let (back, w) = resources_from_bytes(&little).unwrap(); - assert!(w.is_empty()); - assert_eq!(back, res); - // The ICC blob is untouched by the swap. - assert!(little.windows(3).any(|w| w == [1, 2, 3])); - // An odd trailing pad byte is tolerated. - let mut padded = big.clone(); - padded.push(0); - assert_eq!(resources_from_bytes(&padded).unwrap().0, res); - } - - #[test] - fn malformed_input_errors_without_panicking() { - assert!(ImageSourceData::from_bytes(b"").is_err()); - assert!(ImageSourceData::from_bytes(b"Adobe Photoshop Document Data Block").is_err()); - let mut bad = SIGNATURE.to_vec(); - bad.extend_from_slice(b"XXXXLayr"); - assert!(ImageSourceData::from_bytes(&bad).is_err()); - let d = sample_layers(); - for order in [ByteOrder::Big, ByteOrder::Little] { - let (bytes, _) = d.to_bytes(order).unwrap(); - for cut in (0..bytes.len()).step_by(7).chain(bytes.len().saturating_sub(8)..bytes.len()) { - let _ = ImageSourceData::from_bytes(&bytes[..cut]); - } - // Bit flips in the structure (not the signature). - for i in (36..bytes.len()).step_by(13) { - let mut b = bytes.clone(); - b[i] ^= 0x5a; - let _ = ImageSourceData::from_bytes(&b); - } - } - // A block that claims more data than exists. - let mut huge = SIGNATURE.to_vec(); - huge.extend_from_slice(b"8BIMluni"); - huge.extend_from_slice(&u32::MAX.to_be_bytes()); - assert!(ImageSourceData::from_bytes(&huge).is_err()); - assert!(resources_from_bytes(b"8BIM\x03\xed\x00").is_err()); - } - - #[test] - fn into_psd_roundtrips_through_the_psd_writer() { - let file = testgen::layered(Version::Psd, ColorMode::Grayscale, 8, Compression::Zip); - let d = ImageSourceData::from_psd(&file); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - let psd = back.into_psd(file.header.clone(), file.resources.clone(), file.image_data.clone()); - let bytes = psd.to_bytes().unwrap(); - let again = PsdFile::from_bytes(&bytes).unwrap(); - let expected = known(&ImageSourceData::from_psd(&file)); - assert_eq!(known(&ImageSourceData::from_psd(&again)).layer_info, expected.layer_info); - assert_eq!(again.global_blocks, expected.global_blocks); - assert_eq!(again.layer_tree().len(), file.layer_tree().len()); - } - - /// Global blocks are padded as they are written, not on a copy: the bytes are those of the - /// former path (each block cloned with explicit padding to 4, written with `write_blocks`). - #[test] - fn global_blocks_written_without_copies_keep_their_bytes() { - for version in [Version::Psd, Version::Psb] { - let mut d = ImageSourceData { version, global_layer_mask: Some(GlobalLayerMask { data: vec![0, 1, 0, 2, 0, 3, 0, 4, 9] }), ..Default::default() }; - for n in 0..8u8 { - d.global_blocks.push(TaggedBlock::new(*b"FMsk", (0..n).collect())); - } - let mut explicit = TaggedBlock::new(*b"FMsk", vec![1, 2, 3]); - explicit.padding = Some(vec![]); - d.global_blocks.push(explicit); - let mut odd = TaggedBlock::new(*b"FMsk", vec![1, 2]); - odd.padding = Some(vec![0, 0, 0, 0, 0]); - d.global_blocks.push(odd); - let mut copies = vec![padded_block(*b"LMsk", d.global_layer_mask.as_ref().unwrap().data.clone())]; - for b in &d.global_blocks { - let mut b = b.clone(); - if b.padding.is_none() { - b.padding = Some(vec![0; (4 - b.data.len() % 4) % 4]); - } - copies.push(b); - } - let mut body = Vec::new(); - crate::tagged::write_blocks(&mut body, &copies, version, 2).unwrap(); - let signature = if version.is_psb() { SIGNATURE_PSB } else { SIGNATURE }; - assert_eq!(d.to_bytes(ByteOrder::Big).unwrap().0, [signature, &body[..]].concat()); - let (little, _) = transcode_blocks(&body, version, ByteOrder::Big, ByteOrder::Little).unwrap(); - assert_eq!(d.to_bytes(ByteOrder::Little).unwrap().0, [signature, &little[..]].concat()); - } - } - - /// Nested structures are transcoded into one shared buffer. A block whose body fails - /// part-way leaves no partial bytes: dropped on the way out (with the enclosing lengths - /// patched as if it had never been there), or kept exactly as stored on the way in. - #[test] - fn a_nested_block_that_fails_part_way_leaves_nothing_behind() { - let clean = sample_layers(); - let mut fx = Vec::new(); - fx.put_u32(0); - fx.extend_from_slice(&VersionedDescriptor::new(Descriptor::new("null").with("Opct", Value::Double(1.0))).to_bytes()); - // A whole number of 4-byte units, so dropping it cannot change any padding. - fx.resize(fx.len().next_multiple_of(4), 0); - let mut d = clean.clone(); - d.layer_info.as_mut().unwrap().layers[0].blocks.insert(0, TaggedBlock::new(*b"lfx2", fx.clone())); - let (mut little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(!w.iter().any(|w| w.starts_with("lfx2")), "{w:?}"); - // An unknown value type after the descriptor's header: parsing fails part-way. - let at = little.windows(4).position(|w| w == b"buod").unwrap(); - little[at..at + 4].copy_from_slice(b"????"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(w.iter().filter(|w| w.starts_with("lfx2 block")).count(), 1, "{w:?}"); - let kept = &back.layer_info.as_ref().unwrap().layers[0].blocks[0]; - assert!(kept.is_foreign_order()); - let stored = little.windows(4).position(|w| w == b"2xfl").unwrap() + 8; - assert_eq!(kept.data, little[stored..stored + fx.len()]); - // Big-endian data that fails part-way cannot go into a little-endian file: dropped. - let mut big_bad = d.clone(); - let mut broken = fx.clone(); - let at = broken.windows(4).position(|w| w == b"doub").unwrap(); - broken[at..at + 4].copy_from_slice(b"????"); - big_bad.layer_info.as_mut().unwrap().layers[0].blocks[0].data = broken; - let (little, w) = big_bad.to_bytes(ByteOrder::Little).unwrap(); - assert_eq!(w.iter().filter(|w| w.starts_with("lfx2 block")).count(), 1, "{w:?}"); - assert_eq!(little, clean.to_bytes(ByteOrder::Little).unwrap().0); - } -} +mod tests; diff --git a/crates/psd/src/tiff/tests.rs b/crates/psd/src/tiff/tests.rs new file mode 100644 index 0000000000..3836822bf4 --- /dev/null +++ b/crates/psd/src/tiff/tests.rs @@ -0,0 +1,1012 @@ +use super::transcode::*; +use super::*; +use crate::compression::Compression; +use crate::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; +use crate::header::ColorMode; +use crate::testgen; + +/// Keys the generator plants that the transcoder (rightly) does not know. +const UNKNOWN: [&[u8; 4]; 3] = [b"zOdd", b"zNop", b"Txt2"]; + +/// `d` without the blocks a little-endian round trip drops, and without the layer-info +/// padding (which follows the body length, so it changes when blocks are dropped). +fn known(d: &ImageSourceData) -> ImageSourceData { + let mut d = d.clone(); + d.byte_order = ByteOrder::Big; + d.global_blocks.retain(|b| !UNKNOWN.contains(&&b.key)); + if d.layer_info.is_none() { + d.layer_info_key = *b"Layr"; + } + if let Some(info) = &mut d.layer_info { + info.padding = None; + for l in &mut info.layers { + l.blocks.retain(|b| !UNKNOWN.contains(&&b.key)); + } + } + d +} + +fn roundtrip(d: &ImageSourceData) -> ImageSourceData { + let (big, w) = d.to_bytes(ByteOrder::Big).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); + assert!(w.iter().all(|w| UNKNOWN.iter().any(|k| w.starts_with(std::str::from_utf8(*k).unwrap()))), "{w:?}"); + if w.is_empty() { + assert_eq!(big.len(), little.len()); + } + if big.len() > 36 { + assert_ne!(big, little); + assert!(little[36..].starts_with(b"MIB8")); + } + let (back_big, w) = ImageSourceData::from_bytes(&big).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let (back_little, w) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(w.is_empty(), "{w:?}"); + if little.len() > 36 { + assert_eq!(back_little.byte_order, ByteOrder::Little); + } + assert_eq!(known(&back_little), known(&back_big)); + // The little-endian bytes are a fixed point (from the second generation on when blocks + // were dropped, since the layer-info padding then follows the shorter body). + let (little2, _) = back_little.to_bytes(ByteOrder::Little).unwrap(); + let little3 = ImageSourceData::from_bytes(&little2).unwrap().0.to_bytes(ByteOrder::Little).unwrap().0; + assert_eq!(little3, little2); + back_big +} + +#[test] +fn generated_files_survive_both_orders() { + for case in testgen::all_cases() { + let d = ImageSourceData::from_psd(&case.file); + let back = roundtrip(&d); + assert_eq!(back.version, d.version, "{}", case.name); + assert_eq!(known(&back), known(&d), "{}", case.name); + // Nothing but the planted unknown blocks is lost on the little-endian path. + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + assert_eq!(known(&back), known(&d), "{}", case.name); + } +} + +#[test] +fn same_order_transcoding_is_the_identity() { + for case in testgen::all_cases() { + let d = ImageSourceData::from_psd(&case.file); + let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); + let (same, w) = transcode_blocks(&big[36..], d.version, ByteOrder::Big, ByteOrder::Big).unwrap(); + assert!(w.is_empty()); + assert_eq!(same, big[36..].to_vec(), "{}", case.name); + } +} + +fn sample_layers() -> ImageSourceData { + let file = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); + ImageSourceData::from_psd(&file) +} + +#[test] +fn signature_selects_the_version() { + let mut d = sample_layers(); + let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); + assert!(b.starts_with(SIGNATURE)); + d.version = Version::Psb; + let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); + assert!(b.starts_with(SIGNATURE_PSB)); + assert_eq!(ImageSourceData::from_bytes(&b).unwrap().0.version, Version::Psb); + roundtrip(&d); +} + +#[test] +fn layer_key_follows_depth() { + assert_eq!(layer_info_key(8), *b"Layr"); + assert_eq!(layer_info_key(16), *b"Lr16"); + assert_eq!(layer_info_key(32), *b"Lr32"); + for (depth, comp) in [(16, Compression::ZipPrediction), (32, Compression::ZipPrediction), (16, Compression::Rle)] { + let file = testgen::layered(Version::Psd, ColorMode::Rgb, depth, comp); + let d = ImageSourceData::from_psd(&file); + assert_eq!(d.layer_info_key, layer_info_key(depth)); + let back = roundtrip(&d); + assert_eq!(back.layer_info_key, d.layer_info_key); + // The 16/32-bit model goes back into a PSD as a global block, like Photoshop's. + let psd = back.into_psd(file.header.clone(), file.resources.clone(), file.image_data.clone()); + assert!(matches!(psd.layer_info_placement, LayerInfoPlacement::GlobalBlock { .. })); + let again = PsdFile::from_bytes(&psd.to_bytes().unwrap()).unwrap(); + assert_eq!(known(&ImageSourceData::from_psd(&again)).layer_info, known(&d).layer_info); + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + assert_eq!(known(&back).layer_info, known(&d).layer_info, "depth {depth}"); + } +} + +#[test] +fn blocks_are_padded_to_four() { + let d = sample_layers(); + let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); + let mut at = 36; + while at < b.len() { + assert_eq!(&b[at..at + 4], b"8BIM"); + let len = u32::from_be_bytes(b[at + 8..at + 12].try_into().unwrap()) as usize; + at += 12 + len; + at += (4 - at % 4) % 4; + } + assert_eq!(at, b.len()); +} + +fn block_rt(key: [u8; 4], data: Vec) -> (Vec, Vec) { + let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(key, data.clone())], ..Default::default() }; + let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); + let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(back.global_blocks[0].data, data); + assert_eq!(back.to_bytes(ByteOrder::Big).unwrap().0, big); + (big, little) +} + +#[test] +fn descriptor_blocks_swap_keys_and_numbers() { + let mut desc = Descriptor::new("null"); + desc.items.push((Id::new("Opct"), Value::UnitFloat { unit: *b"#Prc", value: 75.5 })); + desc.items.push((Id::new("Nm "), Value::Text(UnicodeString::new_nul("Drop Shadow")))); + desc.items.push((Id::new("enab"), Value::Boolean(true))); + desc.items.push((Id::new("Md "), Value::Enumerated { type_id: Id::new("BlnM"), value: Id::new("Mltp") })); + desc.items.push((Id::new("list"), Value::List(vec![Value::Integer(-3), Value::Double(1.5), Value::LargeInteger(7)]))); + desc.items.push((Id::new("longKeyName"), Value::Descriptor(Descriptor::new("innr")))); + let mut data = 0u32.to_be_bytes().to_vec(); + data.extend(VersionedDescriptor::new(desc).to_bytes()); + let (big, little) = block_rt(*b"lfx2", data); + // Keys are reversed and the version field swapped in the little-endian bytes. + assert!(little[36..].starts_with(b"MIB82xfl")); + let body_at = 48; + assert_eq!(&little[body_at..body_at + 4], &[0, 0, 0, 0]); + assert_eq!(&little[body_at + 4..body_at + 8], &[16, 0, 0, 0]); + assert_eq!(&big[body_at + 4..body_at + 8], &[0, 0, 0, 16]); + assert!(little.windows(4).any(|w| w == b"crP#"), "unit key reversed"); + assert!(little.windows(11).any(|w| w == b"longKeyName"), "string ids are not reversed"); +} + +#[test] +fn descriptor_references_by_identifier_and_index_keep_their_class() { + use crate::descriptor::{Class, ReferenceItem}; + let class = || Class { name: UnicodeString::new(""), class_id: Id::new("Lyr ") }; + let desc = Descriptor::new("null") + .with("null", Value::Reference(vec![ReferenceItem::Identifier { class: class(), id: 7 }, ReferenceItem::Index { class: class(), index: 2 }])); + let mut data = 0u32.to_be_bytes().to_vec(); + data.extend(VersionedDescriptor::new(desc).to_bytes()); + block_rt(*b"lfx2", data); +} + +fn type_layer_data() -> Vec { + let mut data = Vec::new(); + data.put_u16(1); + for value in [1.5, 0.0, -0.25, 1.75, 12.5, -3.25] { + data.put_f64(value); + } + data.put_u16(50); + let text = Descriptor::new("TxLr").with("Txt ", Value::Text(UnicodeString::new_nul("Synthetic Ω 🦀"))); + data.extend(VersionedDescriptor::new(text).to_bytes()); + data.put_u16(1); + data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); + for value in [11, -22, 333, 4_444] { + data.put_i32(value); + } + data +} + +fn tagged_payload<'a>(bytes: &'a [u8], signature_and_key: &[u8; 8], little: bool) -> &'a [u8] { + let block_at = bytes.windows(8).position(|window| window == signature_and_key).expect("tagged block"); + let length_at = block_at + 8; + let length_bytes: [u8; 4] = bytes.get(length_at..length_at + 4).expect("tagged block length").try_into().expect("four-byte length"); + let length = if little { u32::from_le_bytes(length_bytes) } else { u32::from_be_bytes(length_bytes) }; + let data_at = length_at + 4; + let data_end = data_at + usize::try_from(length).expect("test block length fits usize"); + bytes.get(data_at..data_end).expect("tagged block payload") +} + +fn legacy_little_endian_type_block() -> Vec { + let mut tysh = Vec::new(); + tysh.extend_from_slice(&1u16.to_le_bytes()); + for value in [1.5f64, 0.0, -0.25, 1.75, 12.5, -3.25] { + tysh.extend_from_slice(&value.to_le_bytes()); + } + tysh.extend_from_slice(&50u16.to_le_bytes()); + // Independently encode a little-endian `VersionedDescriptor` with a single TEXT value. + tysh.extend_from_slice(&16u32.to_le_bytes()); + tysh.extend_from_slice(&0u32.to_le_bytes()); // empty descriptor name + tysh.extend_from_slice(&0u32.to_le_bytes()); // four-character class id + tysh.extend_from_slice(b"rLxT"); // little-endian four-character class id + tysh.extend_from_slice(&1u32.to_le_bytes()); // one item + tysh.extend_from_slice(&0u32.to_le_bytes()); // four-character key + tysh.extend_from_slice(b" txT"); // little-endian four-character key + tysh.extend_from_slice(b"TXET"); // little-endian OSType + let mut units: Vec = "Synthetic Ω 🦀".encode_utf16().collect(); + units.push(0); // `new_nul`, matching the canonical fixture + tysh.extend_from_slice(&u32::try_from(units.len()).expect("short test string").to_le_bytes()); + for unit in units { + tysh.extend_from_slice(&unit.to_le_bytes()); + } + tysh.extend_from_slice(&1u16.to_le_bytes()); + // Empty warp descriptor, also encoded independently in little-endian order. + tysh.extend_from_slice(&16u32.to_le_bytes()); + tysh.extend_from_slice(&0u32.to_le_bytes()); // empty descriptor name + tysh.extend_from_slice(&4u32.to_le_bytes()); // `warp` is a four-byte string id + tysh.extend_from_slice(b"warp"); + tysh.extend_from_slice(&0u32.to_le_bytes()); // no items + for value in [11i32, -22, 333, 4_444] { + tysh.extend_from_slice(&value.to_le_bytes()); + } + + let mut image_source = super::SIGNATURE.to_vec(); + image_source.extend_from_slice(b"MIB8hSyT"); + image_source.extend_from_slice(&u32::try_from(tysh.len()).expect("short test block").to_le_bytes()); + image_source.extend_from_slice(&tysh); + let padding = (4 - tysh.len() % 4) % 4; + image_source.resize(image_source.len() + padding, 0); + image_source +} + +#[test] +fn type_block_write_keeps_text_descriptor_in_psd_order() { + let canonical = type_layer_data(); + let source = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"TySh", canonical.clone())], ..Default::default() }; + + let (little, warnings) = source.to_bytes(ByteOrder::Little).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let payload = tagged_payload(&little, b"MIB8hSyT", true); + assert_eq!(payload.get(..2), Some(&[1, 0][..]), "TySh header stays in TIFF order"); + for (index, expected) in [1.5f64, 0.0, -0.25, 1.75, 12.5, -3.25].into_iter().enumerate() { + let start = 2 + index * 8; + let bytes: [u8; 8] = payload.get(start..start + 8).unwrap().try_into().unwrap(); + assert_eq!(f64::from_le_bytes(bytes), expected, "matrix element {index}"); + } + + let (text_descriptor, descriptor_len) = VersionedDescriptor::parse_prefix(canonical.get(52..).unwrap()).unwrap(); + let text_section_len = 2 + descriptor_len; + assert_eq!(payload.get(50..52), Some(&50u16.to_be_bytes()[..])); + assert_eq!(payload.get(52..56), Some(&16u32.to_be_bytes()[..])); + assert_eq!(payload.get(50..50 + text_section_len), canonical.get(50..50 + text_section_len)); + assert!(matches!(text_descriptor.descriptor.get("Txt "), Some(Value::Text(value)) if value.to_string_lossy() == "Synthetic Ω 🦀")); + let text_descriptor_from_output = VersionedDescriptor::parse_prefix(payload.get(52..).unwrap()).unwrap().0; + assert!(matches!(text_descriptor_from_output.descriptor.get("Txt "), Some(Value::Text(value)) if value.to_string_lossy() == "Synthetic Ω 🦀")); + + let warp_at = 50 + text_section_len; + assert_eq!(payload.get(warp_at..warp_at + 2), Some(&1u16.to_le_bytes()[..])); + let (_, warp_len) = VersionedDescriptor::parse_prefix(canonical.get(warp_at + 2..).unwrap()).unwrap(); + let warp_descriptor_at = warp_at + 2; + assert_eq!(payload.get(warp_descriptor_at..warp_descriptor_at + 4), Some(&16u32.to_le_bytes()[..])); + assert_eq!(payload.get(warp_descriptor_at + 4..warp_descriptor_at + 8), Some(&0u32.to_le_bytes()[..])); + assert_eq!(payload.get(warp_descriptor_at + 8..warp_descriptor_at + 12), Some(&4u32.to_le_bytes()[..])); + assert_eq!(payload.get(warp_descriptor_at + 12..warp_descriptor_at + 16), Some(b"warp".as_slice())); + assert_eq!(payload.get(warp_descriptor_at + 16..warp_descriptor_at + 20), Some(&0u32.to_le_bytes()[..])); + let bounds_at = warp_descriptor_at + warp_len; + for (index, expected) in [11i32, -22, 333, 4_444].into_iter().enumerate() { + let start = bounds_at + index * 4; + assert_eq!(payload.get(start..start + 4), Some(&expected.to_le_bytes()[..]), "bound {index}"); + } + + let (big, warnings) = source.to_bytes(ByteOrder::Big).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(tagged_payload(&big, b"8BIMTySh", false), canonical); + + let (reopened, warnings) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(reopened.global_blocks[0].data, canonical); + assert_eq!(reopened.to_bytes(ByteOrder::Big).unwrap().0, big); +} + +#[test] +fn legacy_little_endian_type_descriptor_still_imports() { + let input = legacy_little_endian_type_block(); + let (reopened, warnings) = ImageSourceData::from_bytes(&input).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(reopened.global_blocks[0].data, type_layer_data()); +} + +#[test] +fn type_block_layout() { + let mut data = Vec::new(); + data.put_u16(1); + for v in [1.0, 0.0, 0.0, 1.0, 12.5, -3.0] { + data.put_f64(v); + } + data.put_u16(50); + data.extend(VersionedDescriptor::new(Descriptor::new("TxLr")).to_bytes()); + data.put_u16(1); + data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); + for v in [0.0, 0.0, 100.0, 20.0] { + data.put_f64(v); + } + let (_, little) = block_rt(*b"TySh", data); + assert!(little[48..].starts_with(&[1, 0])); + assert_eq!(&little[50..58], &1.0f64.to_le_bytes()); +} + +#[test] +fn photoshop_type_block_switches_to_big_endian_after_its_matrix() { + let mut data = Vec::new(); + data.put_u16(1); + for v in [1.8054202887117468, 0.0, -0.143, 1.8063853899082987, 247.25, 2864.5] { + data.put_f64(v); + } + data.put_u16(50); + let text = Descriptor::new("TxLr").with("Txt ", Value::Text(UnicodeString::new_nul("Synthetic headline"))); + data.extend(VersionedDescriptor::new(text).to_bytes()); + data.put_u16(1); + data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); + for v in [0, 0, 120, 30] { + data.put_i32(v); + } + let (_, mut little) = block_rt(*b"TySh", data.clone()); + // Photoshop uses big-endian text but returns to little-endian for warp/bounds. + let (_, used) = VersionedDescriptor::parse_prefix(&data[52..]).unwrap(); + little[98..100 + used].copy_from_slice(&data[50..52 + used]); + let (back, warnings) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(!back.global_blocks[0].is_foreign_order()); + assert_eq!(back.global_blocks[0].data, data); + // The normalized model remains writable in either order. + for order in [ByteOrder::Big, ByteOrder::Little] { + let (bytes, warnings) = back.to_bytes(order).unwrap(); + assert!(warnings.is_empty()); + let (again, warnings) = ImageSourceData::from_bytes(&bytes).unwrap(); + assert!(warnings.is_empty()); + assert_eq!(again.global_blocks[0].data, data); + } +} + +#[test] +fn legacy_effects_and_adjustments() { + // lrFX with a drop shadow and a solid fill. + let mut fx = Vec::new(); + fx.put_u16(0); + fx.put_u16(3); + fx.put(b"8BIMcmnS"); + fx.put_u32(7); + fx.put_u32(0); + fx.put_u8(1); + fx.put_u16(0); + fx.put(b"8BIMdsdw"); + let mut sh = Vec::new(); + sh.put_u32(2); + for v in [5 << 16, 75 << 16, 120 << 16, 7 << 16] { + sh.put_i32(v); + } + for _ in 0..5 { + sh.put_u16(0); + } + sh.put(b"8BIMmul "); + sh.put_u8(1); + sh.put_u8(1); + sh.put_u8(191); + sh.put_u16(0); + sh.put_u16(0x1234); + sh.put_u16(0); + sh.put_u16(0); + sh.put_u16(0); + fx.put_u32(sh.len() as u32); + fx.put(&sh); + fx.put(b"8BIMsofi"); + let mut so = Vec::new(); + so.put_u32(2); + so.put(b"8BIMnorm"); + so.put_u16(0); + so.put_u16(0xffff); + so.put_u16(0); + so.put_u16(0); + so.put_u16(0); + so.put_u8(255); + so.put_u8(1); + so.put_u16(0); + so.put_u16(0xffff); + so.put_u16(0); + so.put_u16(0); + so.put_u16(0); + fx.put_u32(so.len() as u32); + fx.put(&so); + let (_, little) = block_rt(*b"lrFX", fx); + assert!(little.windows(8).any(|w| w == b"MIB8wdsd"), "effect keys reversed"); + assert!(little.windows(2).any(|w| w == [0x34, 0x12]), "colour component swapped"); + + // levl: version + 29 records + the Lvls extension. + let mut lv = Vec::new(); + lv.put_u16(2); + for i in 0..29 * 5 { + lv.put_u16(i as u16); + } + lv.put(b"Lvls"); + lv.put_u16(3); + lv.put_u16(33); + for i in 0..4 * 5 { + lv.put_u16(1000 + i as u16); + } + let (_, little) = block_rt(*b"levl", lv); + assert!(little.windows(4).any(|w| w == b"slvL")); + + // curv with the Crv extension. + let mut cv = vec![0u8]; + cv.put_u16(1); + cv.put_u32(0b101); + cv.put_u16(2); + cv.put_u16(0); + cv.put_u16(0); + cv.put_u16(255); + cv.put_u16(255); + cv.put_u16(1); + cv.put_u16(128); + cv.put_u16(100); + cv.put(b"Crv "); + cv.put_u16(4); + cv.put_u32(1); + cv.put_u16(2); + cv.put_u16(1); + cv.put_u16(7); + cv.put_u16(9); + block_rt(*b"curv", cv); + + for (key, data) in [ + (*b"hue2", vec![0, 2, 0, 0, 0, 10, 0, 20, 0, 30, 0, 40, 0, 50, 0, 60]), + (*b"brit", vec![0, 10, 0, 20, 0, 30, 1, 0]), + (*b"thrs", vec![0, 128, 0, 0]), + (*b"post", vec![0, 4, 0, 0]), + (*b"nvrt", vec![]), + (*b"expA", [1u16.to_be_bytes().to_vec(), 0.5f32.to_be_bytes().to_vec(), 0.0f32.to_be_bytes().to_vec(), 1.0f32.to_be_bytes().to_vec()].concat()), + (*b"blnc", vec![0; 20]), + (*b"mixr", vec![0, 1, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0]), + (*b"selc", vec![0, 1, 0, 0, 0, 5, 0, 6, 0, 7, 0, 8]), + (*b"phfl", vec![0, 3, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 25, 1, 0]), + (*b"phfl", vec![0, 2, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 0, 0, 25, 1, 0]), + (*b"lclr", vec![0, 1, 0, 0, 0, 0, 0, 0]), + (*b"fxrp", [1.5f64.to_be_bytes().to_vec(), 2.5f64.to_be_bytes().to_vec()].concat()), + (*b"brst", vec![0, 0, 0, 1, 0, 0, 0, 2]), + (*b"FMsk", vec![0, 0, 255, 255, 0, 0, 0, 0, 0, 0, 0, 50]), + (*b"lsct", [3u32.to_be_bytes().to_vec(), b"8BIMpass".to_vec()].concat()), + (*b"lspf", vec![0, 0, 0, 5]), + (*b"lnsr", b"layr".to_vec()), + (*b"knko", vec![1, 0, 0, 0]), + (*b"knko", vec![2, 0, 0, 0]), + (*b"infx", vec![1, 0, 0, 0]), + (*b"clbl", vec![0, 0, 0, 0]), + (*b"tsly", vec![0, 0, 0, 0]), + (*b"lmgm", vec![1, 0, 0, 0]), + (*b"vmgm", vec![1, 0, 0, 0]), + (*b"iOpa", vec![128, 0, 0, 0]), + ] { + let (big, little) = block_rt(key, data.clone()); + if data.len() >= 2 && key != *b"nvrt" { + assert_ne!(big, little, "{}", String::from_utf8_lossy(&key)); + } + } +} + +#[test] +fn global_layer_mask_block() { + let d = ImageSourceData { global_layer_mask: Some(GlobalLayerMask { data: vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 128, 0] }), ..Default::default() }; + let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); + assert!(w.is_empty()); + assert!(little[36..].starts_with(b"MIB8ksML")); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + assert_eq!(back.global_layer_mask, d.global_layer_mask); + assert_eq!(back.global_layer_mask.unwrap().opacity(), Some(50)); +} + +#[test] +fn gradient_map_layout() { + let mut g = Vec::new(); + g.put_u16(3); + g.put_u8(0); + g.put_u8(1); + g.put(b"Lnr "); + g.put_u32(2); + g.put_u16(u16::from(b'a')); + g.put_u16(0); + g.put_u16(2); + for (loc, mid) in [(0u32, 50u32), (4096, 50)] { + g.put_u32(loc); + g.put_u32(mid); + g.put_u16(0); + g.put_u16(0x1111); + g.put_u16(0x2222); + g.put_u16(0x3333); + g.put_u16(0); + g.put_u16(0); + } + g.put_u16(2); + for loc in [0u32, 4096] { + g.put_u32(loc); + g.put_u32(50); + g.put_u16(100); + } + g.put_u16(2); + g.put_u16(1); + g.put_u16(32); + g.put_u16(0); + g.put_u32(0xdead_beef); + for _ in 0..12 { + g.put_u16(0); + } + let (_, little) = block_rt(*b"grdm", g); + assert!(little.windows(4).any(|w| w == 0xdead_beefu32.to_le_bytes())); + assert!(little.windows(4).any(|w| w == b" rnL")); +} + +#[test] +fn vector_mask_records() { + let mut v = Vec::new(); + v.put_u32(3); + v.put_u32(0); + // Closed length record, then two linked knots. + v.put_u16(0); + v.put_u16(2); + v.put_i16(1); + v.put(&[0; 20]); + for sel in [1u16, 1] { + v.put_u16(sel); + for i in 0..6 { + v.put_i32((i + 1) * 0x0010_0000); + } + } + let (_, little) = block_rt(*b"vmsk", v); + assert!(little.windows(4).any(|w| w == [0, 0, 0x10, 0]), "fixed-point coordinate swapped"); +} + +#[test] +fn pattern_block() { + let plane: Vec = (0..16u8).collect(); + let p = crate::patterns::PsdPattern { + mode: 3, + width: 4, + height: 4, + name: "dots".into(), + id: "abc".into(), + palette: None, + depth: 8, + channels: vec![plane.clone(), plane.clone(), plane.clone()], + alpha: Some(plane), + }; + let data = crate::patterns::write_pattern_block(std::slice::from_ref(&p)).unwrap(); + block_rt(*b"Patt", data.clone()); + // Little-endian pattern data parses back into the same pattern. + let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"Patt", data)], ..Default::default() }; + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + assert_eq!(crate::patterns::parse_pattern_block(&back.global_blocks[0].data).unwrap(), vec![p]); +} + +#[test] +fn filter_effects_block() { + use crate::filter_effects::{EffectsPlane, FilterEffects, FilterEffectsItem}; + let plane = EffectsPlane::encode(Compression::Rle, &[1, 2, 3, 4, 5, 6], 3, 2, 8).unwrap(); + let mask = EffectsPlane::encode(Compression::Raw, &[9; 6], 3, 2, 8).unwrap(); + let rect = crate::layer::Rect { top: 0, left: 0, bottom: 2, right: 3 }; + let fx = FilterEffects { + version: 1, + items: vec![FilterEffectsItem { + id: "x".into(), + version: 1, + rect, + depth: 8, + max_channels: 1, + slots: vec![Some(plane.clone()), None, Some(plane)], + mask: Some((rect, mask)), + }], + }; + let data = fx.to_bytes(); + block_rt(*b"FEid", data.clone()); + let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"FEid", data)], ..Default::default() }; + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + assert_eq!(FilterEffects::parse(&back.global_blocks[0].data).unwrap(), fx); +} + +/// Photoshop writes one `FEid` section per smart object: every section's lengths and +/// numbers are swapped, not only the first one's. +#[test] +fn filter_effects_block_swaps_every_section() { + use crate::filter_effects::{EffectsPlane, FilterEffects, FilterEffectsItem}; + let rect = crate::layer::Rect { top: 0, left: 0, bottom: 2, right: 3 }; + let item = |id: &str, v: u8| FilterEffectsItem { + id: id.into(), + version: 1, + rect, + depth: 8, + max_channels: 1, + slots: vec![Some(EffectsPlane::encode(Compression::Raw, &[v; 6], 3, 2, 8).unwrap()), None, None], + mask: None, + }; + let fx = FilterEffects { version: 1, items: vec![item("first", 1), item("second-object", 2)] }; + let data = fx.to_bytes(); + let len1 = u64::from_be_bytes(data[4..12].try_into().unwrap()) as usize; + let second = 12 + len1 + (4 - len1 % 4) % 4; + let len2 = &data[second..second + 8]; + block_rt(*b"FEid", data.clone()); + let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"FEid", data.clone())], ..Default::default() }; + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + // 36-byte signature, then `MIB8`, the reversed key and a u32 length: the block data. + let body = &little[36 + 12..]; + let mut swapped = len2.to_vec(); + swapped.reverse(); + assert_eq!(&body[second..second + 8], &swapped[..], "second section's length is little-endian"); + let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(FilterEffects::parse(&back.global_blocks[0].data).unwrap(), fx); +} + +#[test] +fn metadata_setting_items() { + let desc = VersionedDescriptor::new(Descriptor::new("null")).to_bytes(); + let items = vec![crate::metadata::MetadataItem::new(*b"cmls", desc)]; + block_rt(*b"shmd", crate::metadata::write_shmd(&items)); + // An unknown item cannot be converted: it is dropped on its own, the rest stays. + let items = vec![ + crate::metadata::MetadataItem::new(*b"zzzz", vec![1, 2, 3, 4, 5, 6, 7, 8]), + crate::metadata::MetadataItem::new(*b"mdyn", vec![0, 0, 0, 1]), + crate::metadata::MetadataItem::new(*b"cmls", VersionedDescriptor::new(Descriptor::new("null")).to_bytes()), + ]; + let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"shmd", crate::metadata::write_shmd(&items))], ..Default::default() }; + let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); + assert_eq!(w.len(), 1, "{w:?}"); + assert!(w[0].starts_with("shmd item zzzz dropped"), "{}", w[0]); + let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(w.is_empty()); + let back_items = crate::metadata::parse_shmd(&back.global_blocks[0].data).unwrap(); + assert_eq!(back_items, items[1..].to_vec()); +} + +#[test] +fn unknown_descriptor_shaped_blocks_are_converted() { + // A key the transcoder has never heard of, holding a versioned descriptor (as every + // block Photoshop added since CS6 does): converted, not dropped. + let mut desc = Descriptor::new("null"); + desc.items.push((Id::new("Nm "), Value::Text(UnicodeString::new_nul("x")))); + let data = VersionedDescriptor::new(desc.clone()).to_bytes(); + block_rt(*b"Qqqq", data); + let mut with_version = 3u32.to_be_bytes().to_vec(); + with_version.extend(VersionedDescriptor::new(desc).to_bytes()); + block_rt(*b"Qqqq", with_version); + // Empty data needs no conversion either. + block_rt(*b"Mt32", Vec::new()); +} + +#[test] +fn linked_layer_items() { + // One embedded file (liFD, version 7) as photocraft-io writes it. + let mut item = Vec::new(); + item.put(b"liFD"); + item.put_u32(7); + item.put_u8(4); + item.put(b"uuid"); + let units: Vec = "a.png\0".encode_utf16().collect(); + item.put_u32(units.len() as u32); + for u in units { + item.put_u16(u); + } + item.put(b"png "); + item.put(b"8BIM"); + let bytes = [0x89, b'P', b'N', b'G', 1, 2, 3]; + item.put_u64(bytes.len() as u64); + item.put_u8(0); + item.put(&bytes); + item.put_u32(0); + item.put_f64(0.0); + item.put_u8(0); + let mut data = (item.len() as u64).to_be_bytes().to_vec(); + data.put(&item); + while !data.len().is_multiple_of(4) { + data.push(0); + } + let (_, little) = block_rt(*b"lnk2", data); + assert!(little.windows(4).any(|w| w == b"DFil"), "item type key reversed"); + assert!(little.windows(7).any(|w| w == bytes), "file bytes untouched"); +} + +#[test] +fn annotation_block() { + let mut a = Vec::new(); + a.put_u16(2); + a.put_u16(1); + a.put_u32(1); + let mut item = Vec::new(); + item.put(b"txtA"); + item.put_u8(0); + item.put_u8(1); + item.put_u16(0); + for v in [10, 20, 30, 40, 50, 60, 70, 80] { + item.put_i32(v); + } + item.put_u16(0); + for v in [0xffff, 0, 0, 0] { + item.put_u16(v); + } + for s in [&b"me"[..], b"note", b"2026"] { + item.put_u8(s.len() as u8); + item.put(s); + if (1 + s.len()) % 2 == 1 { + item.put_u8(0); + } + } + let text = [0xfe, 0xff, 0, b'h', 0, b'i']; + let mut d = Vec::new(); + d.put(b"txtC"); + d.put_u32(text.len() as u32); + d.put(&text); + item.put_u32(d.len() as u32 + 4); + item.put(&d); + a.put_u32(item.len() as u32 + 4); + a.put(&item); + let (_, little) = block_rt(*b"Anno", a); + assert!(little.windows(4).any(|w| w == b"Atxt")); + assert!(little.windows(6).any(|w| w == text), "text kept as stored"); +} + +#[test] +fn unknown_blocks_kept_in_big_dropped_in_little() { + let mut d = sample_layers(); + d.global_blocks.push(TaggedBlock::new(*b"Zzzz", vec![1, 2, 3, 4, 5])); + let (big, w) = d.to_bytes(ByteOrder::Big).unwrap(); + assert!(w.is_empty()); + let (back, w) = ImageSourceData::from_bytes(&big).unwrap(); + assert!(w.is_empty()); + assert_eq!(back.global_blocks, d.global_blocks); + // Big-endian data of unknown layout cannot go into a little-endian file. + let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); + assert_eq!(w.iter().filter(|w| w.starts_with("Zzzz block (5 bytes) dropped")).count(), 1, "{w:?}"); + let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(w.is_empty()); + assert_eq!(back.global_blocks.iter().map(|b| b.key).collect::>(), vec![*b"Patt", *b"FMsk"]); + assert_eq!(known(&back).layer_info, known(&d).layer_info); +} + +#[test] +fn unknown_blocks_from_a_little_endian_file_are_kept_with_their_byte_order() { + let d = sample_layers(); + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + // A little-endian file with a block of unknown layout, among known ones. + let mut raw = little.clone(); + raw.extend_from_slice(b"MIB8zzzZ"); + raw.extend_from_slice(&6u32.to_le_bytes()); + raw.extend_from_slice(&[9, 8, 7, 6, 5, 4, 0, 0]); + raw.extend_from_slice(b"MIB8diyl"); + raw.extend_from_slice(&4u32.to_le_bytes()); + raw.extend_from_slice(&7u32.to_le_bytes()); + let (back, w) = ImageSourceData::from_bytes(&raw).unwrap(); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(known(&back).layer_info, known(&d).layer_info); + let kept = back.global_blocks.iter().find(|b| &b.key == b"Zzzz").expect("kept"); + assert!(kept.is_foreign_order()); + assert_eq!(kept.signature, *b"MIB8"); + assert_eq!(kept.data, [9, 8, 7, 6, 5, 4]); + // The known block after it was still converted. + assert_eq!(back.global_blocks.iter().find(|b| &b.key == b"lyid").unwrap().data, 7u32.to_be_bytes()); + // Written back to a little-endian TIFF, the bytes are exactly what was read. + let (again, w) = back.to_bytes(ByteOrder::Little).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let tail = &raw[raw.len() - 18 - 16..]; + assert!(again.windows(tail.len()).any(|x| x == tail), "foreign-order block restored verbatim"); + assert_eq!(ImageSourceData::from_bytes(&again).unwrap().0.global_blocks, back.global_blocks); + // The big-endian (PSD) model keeps the marker, so a PSD writer can tell it apart. + let (big, _) = back.to_bytes(ByteOrder::Big).unwrap(); + assert!(big.windows(8).any(|x| x == b"MIB8Zzzz")); + assert_eq!(ImageSourceData::from_bytes(&big).unwrap().0.global_blocks, back.global_blocks); +} + +/// A PSB keeps `Mt16`/`Mt32`/`Mtrn`/`Alph` blocks of unknown layout verbatim, and their +/// length field is 8 bytes (a PSB long key). Writing them into a little-endian TIFF must +/// read that width; the old code looked the key up after reversing it for the target +/// order, which never matches `PSB_LONG_KEYS`. +#[test] +fn psb_foreign_order_long_key_roundtrips() { + let d = ImageSourceData { + version: Version::Psb, + byte_order: ByteOrder::Little, + global_blocks: vec![TaggedBlock { signature: *b"MIB8", key: *b"Mt16", data: vec![9, 8, 7, 6, 5, 4], padding: None }], + ..Default::default() + }; + let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); + assert!(w.is_empty(), "{w:?}"); + let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(back.global_blocks, d.global_blocks, "the 8-byte length and the bytes survive"); +} + +#[test] +fn rle_counts_follow_the_container_and_samples_do_not() { + let file = testgen::layered(Version::Psd, ColorMode::Rgb, 16, Compression::Rle); + let d = ImageSourceData::from_psd(&file); + let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + let d = known(&d); + let (a, b) = (d.layer_info.as_ref().unwrap(), back.layer_info.as_ref().unwrap()); + for (la, lb) in a.layers.iter().zip(&b.layers) { + for (ca, cb) in la.channels.iter().zip(&lb.channels) { + assert_eq!(ca, cb); + let (w, h) = la.channel_rect(ca.id).size().unwrap(); + assert_eq!(ca.decode(w, h, 16, Version::Psd).unwrap(), cb.decode(w, h, 16, Version::Psd).unwrap()); + } + } + // The encoded samples (after the count table) are identical bytes in both files, while + // the count table itself is swapped. + let (rec, ch) = a + .layers + .iter() + .flat_map(|l| l.channels.iter().filter(|c| c.id >= -1 && c.compression == Some(Compression::Rle)).map(move |c| (l, c))) + .find(|(l, c)| l.rect.height() > 1 && c.data.len() > l.rect.height() as usize * 2 + 8) + .unwrap(); + let table = rec.rect.height() as usize * 2; + let samples = &ch.data[table..]; + assert!(big.windows(samples.len()).any(|w| w == samples)); + assert!(little.windows(samples.len()).any(|w| w == samples)); + let counts = &ch.data[..table]; + let swapped: Vec = counts.chunks(2).flat_map(|c| [c[1], c[0]]).collect(); + assert!(little.windows(table + samples.len()).any(|w| w[..table] == swapped[..] && w[table..] == *samples)); +} + +#[test] +fn blending_ranges_are_bytes_in_either_order() { + let mut file = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); + let ranges: Vec = [0u8, 0, 255, 255].repeat(10); + let marked: Vec = (1u8..=40).collect(); + for (i, l) in file.layer_info.as_mut().unwrap().layers.iter_mut().enumerate() { + l.blending_ranges.data = if i == 0 { marked.clone() } else { ranges.clone() }; + } + let d = ImageSourceData::from_psd(&file); + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + // Written verbatim (what Photoshop writes in an `II` TIFF), not swapped per u32. + assert!(little.windows(marked.len()).any(|w| w == marked)); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + for (a, b) in d.layer_info.as_ref().unwrap().layers.iter().zip(&back.layer_info.as_ref().unwrap().layers) { + assert_eq!(a.blending_ranges, b.blending_ranges); + } +} + +#[test] +fn psb_sized_data_uses_long_lengths_and_counts() { + let file = testgen::layered(Version::Psb, ColorMode::Cmyk, 8, Compression::Rle); + let d = ImageSourceData::from_psd(&file); + assert_eq!(d.version, Version::Psb); + let back = roundtrip(&d); + assert_eq!(back.layer_info, d.layer_info); + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + assert!(little[36..].starts_with(b"MIB8")); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + assert_eq!(known(&back).layer_info, known(&d).layer_info); +} + +#[test] +fn resources_both_orders() { + let res = vec![ + ImageResource::new(1005, vec![0, 72, 0, 0, 0, 1, 0, 1, 0, 72, 0, 0, 0, 1, 0, 1]), + ImageResource::new(1037, vec![0, 0, 0, 120]), + ImageResource::new(1039, vec![1, 2, 3]), + ImageResource { signature: *b"8BIM", id: 1026, name: b"grp".to_vec(), data: vec![0, 1, 0, 1, 0, 0] }, + ]; + let big = resources_to_bytes(&res).unwrap(); + let (back, w) = resources_from_bytes(&big).unwrap(); + assert!(w.is_empty()); + assert_eq!(back, res); + let (little, w) = transcode_resources(&big, ByteOrder::Big, ByteOrder::Little).unwrap(); + assert!(w.is_empty()); + assert!(little.starts_with(b"MIB8")); + assert_eq!(little.len(), big.len()); + assert_eq!(&little[4..6], &[0xed, 3]); + let (back, w) = resources_from_bytes(&little).unwrap(); + assert!(w.is_empty()); + assert_eq!(back, res); + // The ICC blob is untouched by the swap. + assert!(little.windows(3).any(|w| w == [1, 2, 3])); + // An odd trailing pad byte is tolerated. + let mut padded = big.clone(); + padded.push(0); + assert_eq!(resources_from_bytes(&padded).unwrap().0, res); +} + +#[test] +fn malformed_input_errors_without_panicking() { + assert!(ImageSourceData::from_bytes(b"").is_err()); + assert!(ImageSourceData::from_bytes(b"Adobe Photoshop Document Data Block").is_err()); + let mut bad = SIGNATURE.to_vec(); + bad.extend_from_slice(b"XXXXLayr"); + assert!(ImageSourceData::from_bytes(&bad).is_err()); + let d = sample_layers(); + for order in [ByteOrder::Big, ByteOrder::Little] { + let (bytes, _) = d.to_bytes(order).unwrap(); + for cut in (0..bytes.len()).step_by(7).chain(bytes.len().saturating_sub(8)..bytes.len()) { + let _ = ImageSourceData::from_bytes(&bytes[..cut]); + } + // Bit flips in the structure (not the signature). + for i in (36..bytes.len()).step_by(13) { + let mut b = bytes.clone(); + b[i] ^= 0x5a; + let _ = ImageSourceData::from_bytes(&b); + } + } + // A block that claims more data than exists. + let mut huge = SIGNATURE.to_vec(); + huge.extend_from_slice(b"8BIMluni"); + huge.extend_from_slice(&u32::MAX.to_be_bytes()); + assert!(ImageSourceData::from_bytes(&huge).is_err()); + assert!(resources_from_bytes(b"8BIM\x03\xed\x00").is_err()); +} + +#[test] +fn into_psd_roundtrips_through_the_psd_writer() { + let file = testgen::layered(Version::Psd, ColorMode::Grayscale, 8, Compression::Zip); + let d = ImageSourceData::from_psd(&file); + let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); + let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); + let psd = back.into_psd(file.header.clone(), file.resources.clone(), file.image_data.clone()); + let bytes = psd.to_bytes().unwrap(); + let again = PsdFile::from_bytes(&bytes).unwrap(); + let expected = known(&ImageSourceData::from_psd(&file)); + assert_eq!(known(&ImageSourceData::from_psd(&again)).layer_info, expected.layer_info); + assert_eq!(again.global_blocks, expected.global_blocks); + assert_eq!(again.layer_tree().len(), file.layer_tree().len()); +} + +/// Global blocks are padded as they are written, not on a copy: the bytes are those of the +/// former path (each block cloned with explicit padding to 4, written with `write_blocks`). +#[test] +fn global_blocks_written_without_copies_keep_their_bytes() { + for version in [Version::Psd, Version::Psb] { + let mut d = ImageSourceData { version, global_layer_mask: Some(GlobalLayerMask { data: vec![0, 1, 0, 2, 0, 3, 0, 4, 9] }), ..Default::default() }; + for n in 0..8u8 { + d.global_blocks.push(TaggedBlock::new(*b"FMsk", (0..n).collect())); + } + let mut explicit = TaggedBlock::new(*b"FMsk", vec![1, 2, 3]); + explicit.padding = Some(vec![]); + d.global_blocks.push(explicit); + let mut odd = TaggedBlock::new(*b"FMsk", vec![1, 2]); + odd.padding = Some(vec![0, 0, 0, 0, 0]); + d.global_blocks.push(odd); + let mut copies = vec![padded_block(*b"LMsk", d.global_layer_mask.as_ref().unwrap().data.clone())]; + for b in &d.global_blocks { + let mut b = b.clone(); + if b.padding.is_none() { + b.padding = Some(vec![0; (4 - b.data.len() % 4) % 4]); + } + copies.push(b); + } + let mut body = Vec::new(); + crate::tagged::write_blocks(&mut body, &copies, version, 2).unwrap(); + let signature = if version.is_psb() { SIGNATURE_PSB } else { SIGNATURE }; + assert_eq!(d.to_bytes(ByteOrder::Big).unwrap().0, [signature, &body[..]].concat()); + let (little, _) = transcode_blocks(&body, version, ByteOrder::Big, ByteOrder::Little).unwrap(); + assert_eq!(d.to_bytes(ByteOrder::Little).unwrap().0, [signature, &little[..]].concat()); + } +} + +/// Nested structures are transcoded into one shared buffer. A block whose body fails +/// part-way leaves no partial bytes: dropped on the way out (with the enclosing lengths +/// patched as if it had never been there), or kept exactly as stored on the way in. +#[test] +fn a_nested_block_that_fails_part_way_leaves_nothing_behind() { + let clean = sample_layers(); + let mut fx = Vec::new(); + fx.put_u32(0); + fx.extend_from_slice(&VersionedDescriptor::new(Descriptor::new("null").with("Opct", Value::Double(1.0))).to_bytes()); + // A whole number of 4-byte units, so dropping it cannot change any padding. + fx.resize(fx.len().next_multiple_of(4), 0); + let mut d = clean.clone(); + d.layer_info.as_mut().unwrap().layers[0].blocks.insert(0, TaggedBlock::new(*b"lfx2", fx.clone())); + let (mut little, w) = d.to_bytes(ByteOrder::Little).unwrap(); + assert!(!w.iter().any(|w| w.starts_with("lfx2")), "{w:?}"); + // An unknown value type after the descriptor's header: parsing fails part-way. + let at = little.windows(4).position(|w| w == b"buod").unwrap(); + little[at..at + 4].copy_from_slice(b"????"); + let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); + assert_eq!(w.iter().filter(|w| w.starts_with("lfx2 block")).count(), 1, "{w:?}"); + let kept = &back.layer_info.as_ref().unwrap().layers[0].blocks[0]; + assert!(kept.is_foreign_order()); + let stored = little.windows(4).position(|w| w == b"2xfl").unwrap() + 8; + assert_eq!(kept.data, little[stored..stored + fx.len()]); + // Big-endian data that fails part-way cannot go into a little-endian file: dropped. + let mut big_bad = d.clone(); + let mut broken = fx.clone(); + let at = broken.windows(4).position(|w| w == b"doub").unwrap(); + broken[at..at + 4].copy_from_slice(b"????"); + big_bad.layer_info.as_mut().unwrap().layers[0].blocks[0].data = broken; + let (little, w) = big_bad.to_bytes(ByteOrder::Little).unwrap(); + assert_eq!(w.iter().filter(|w| w.starts_with("lfx2 block")).count(), 1, "{w:?}"); + assert_eq!(little, clean.to_bytes(ByteOrder::Little).unwrap().0); +} From d314299d5bff57598e0cf7658eedb2ae4949668d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:01 +0000 Subject: [PATCH 011/259] refactor(psd): move layer.rs tests to layer/tests.rs --- crates/psd/src/layer.rs | 382 +--------------------------------- crates/psd/src/layer/tests.rs | 374 +++++++++++++++++++++++++++++++++ 2 files changed, 375 insertions(+), 381 deletions(-) create mode 100644 crates/psd/src/layer/tests.rs diff --git a/crates/psd/src/layer.rs b/crates/psd/src/layer.rs index 5b11411dfb..1b5c241191 100644 --- a/crates/psd/src/layer.rs +++ b/crates/psd/src/layer.rs @@ -778,384 +778,4 @@ impl LayerInfo { } #[cfg(test)] -mod tests { - use super::*; - - fn sample_record(version: Version) -> LayerRecord { - let rect = Rect::from_xywh(-3, 2, 5, 4); - let px: Vec = (0..20).collect(); - let mut channels = Vec::new(); - for (id, comp) in [(-1, Compression::Rle), (0, Compression::Raw), (1, Compression::Zip), (2, Compression::ZipPrediction)] { - channels.push(ChannelData::encode(id, comp, &px, 5, 4, 8, version).unwrap()); - } - let mask = LayerMask::new(Rect::from_xywh(0, 0, 2, 2), 255, LayerMask::FLAG_RELATIVE); - channels.push(ChannelData::encode(-2, Compression::Rle, &[1, 2, 3, 4], 2, 2, 8, version).unwrap()); - LayerRecord { - rect, - channels, - blend_mode: BlendMode::Screen, - opacity: 200, - clipping: 1, - flags: LayerFlags(LayerFlags::HIDDEN), - mask: MaskData::Mask(mask), - blending_ranges: BlendingRanges::full(3), - name: b"abc".to_vec(), - blocks: vec![TaggedBlock::unicode_name("\u{e4}bc"), TaggedBlock::layer_id(5)], - ..Default::default() - } - } - - fn rt(info: &LayerInfo, version: Version) -> Vec { - let mut out = Vec::new(); - info.write_body(&mut out, version).unwrap(); - let back = LayerInfo::read_body(&out, version).unwrap(); - assert_eq!(&back, info); - let mut again = Vec::new(); - back.write_body(&mut again, version).unwrap(); - assert_eq!(again, out); - out - } - - #[test] - fn empty_layer_info() { - let out = rt(&LayerInfo::default(), Version::Psd); - assert_eq!(out, vec![0, 0]); - } - - #[test] - fn record_roundtrip_psd_psb() { - for v in [Version::Psd, Version::Psb] { - let info = LayerInfo { merged_alpha: true, layers: vec![sample_record(v), LayerRecord::default()], padding: None }; - let out = rt(&info, v); - assert_eq!(out.len() % 2, 0); - assert_eq!(&out[..2], &(-2i16).to_be_bytes()); - } - } - - #[test] - fn psb_channel_lengths_are_8_bytes() { - let mut rec = LayerRecord::default(); - rec.channels.push(ChannelData { id: 0, compression: Some(Compression::Raw), data: vec![] }); - let info = LayerInfo { layers: vec![rec], ..Default::default() }; - let psd = rt(&info, Version::Psd); - let psb = rt(&info, Version::Psb); - assert_eq!(psb.len(), psd.len() + 4); - } - - #[test] - fn channel_decode_via_record() { - let rec = sample_record(Version::Psd); - let px: Vec = (0..20).collect(); - for id in [-1, 0, 1, 2] { - assert_eq!(rec.decode_channel(id, 8, Version::Psd).unwrap(), px); - } - assert_eq!(rec.decode_channel(-2, 8, Version::Psd).unwrap(), vec![1, 2, 3, 4]); - assert!(rec.decode_channel(7, 8, Version::Psd).is_err()); - } - - #[test] - fn record_accessors() { - let rec = sample_record(Version::Psd); - assert_eq!(rec.name(), "\u{e4}bc"); - assert!(!rec.is_visible()); - assert_eq!(rec.layer_id(), Some(5)); - assert_eq!(rec.fill_opacity(), 255); - assert_eq!(rec.section_type(), SectionType::Other); - assert!(rec.layer_mask().is_some()); - assert_eq!(rec.channel_rect(-2), Rect::from_xywh(0, 0, 2, 2)); - assert_eq!(rec.channel_rect(0), rec.rect); - let mut plain = LayerRecord { name: b"legacy".to_vec(), ..Default::default() }; - assert_eq!(plain.name(), "legacy"); - plain.blocks.push(TaggedBlock::fill_opacity(10)); - assert_eq!(plain.fill_opacity(), 10); - plain.block_mut(b"iOpa").unwrap().data[0] = 11; - assert_eq!(plain.fill_opacity(), 11); - } - - #[test] - fn mask_variants_roundtrip() { - let base = LayerMask::new(Rect::from_xywh(1, 2, 3, 4), 0, 0); - let with_real = LayerMask { real: Some(RealMask { flags: 1, background: 255, rect: Rect::from_xywh(0, 0, 9, 9) }), trailing: vec![], ..base.clone() }; - let with_params = LayerMask { - flags: LayerMask::FLAG_PARAMETERS, - parameters: Some(MaskParameters { - flags: 0b1111, - user_density: Some(128), - user_feather: Some(2.5), - vector_density: Some(64), - vector_feather: Some(0.5), - }), - real: Some(RealMask::default()), - trailing: vec![0, 0], - ..base.clone() - }; - let partial_params = LayerMask { - flags: LayerMask::FLAG_PARAMETERS, - parameters: Some(MaskParameters { flags: 0b0010, user_feather: Some(1.0), ..Default::default() }), - trailing: vec![], - ..base.clone() - }; - for m in [base, with_real, with_params, partial_params] { - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(LayerMask::parse(&out).unwrap(), m); - } - } - - /// Photoshop stores the real-mask fields before the mask parameters (psd-tools - /// mask-density-layervectormask.psd): user + vector mask with both densities set. - #[test] - fn real_mask_before_parameters_photoshop_layout() { - let mut d = Vec::new(); - Rect::from_xywh(15, -1, 18, 10).write(&mut d); - d.extend([0, LayerMask::FLAG_PARAMETERS | 8]); - d.extend([0, 255]); - Rect::from_xywh(0, 0, 32, 8).write(&mut d); - d.extend([0b0101, 64, 64, 0]); - let m = LayerMask::parse(&d).unwrap(); - assert_eq!(m.real.map(|r| r.rect), Some(Rect::from_xywh(0, 0, 32, 8))); - assert_eq!(m.real.map(|r| r.background), Some(255)); - let p = m.parameters.unwrap(); - assert_eq!((p.user_density, p.vector_density), (Some(64), Some(64))); - assert_eq!(m.trailing, vec![0]); - assert!(m.real_first); - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out, d); - } - - /// A density-only record in the spec's order (#949): the parameter flags byte at 18 says one - /// value byte, so the spec's reading excludes the 38-byte length only if the real mask is - /// ignored, while byte 36 (inside the real rectangle's `right`) is 0 and makes Photoshop's - /// reading fit too. Photoshop's reading puts the density (64) where a 0-or-255 background - /// belongs, so the spec's order wins and the density survives. - #[test] - fn density_only_spec_layout_is_not_read_as_photoshop_order() { - for (density, right) in [(64u8, 1u32), (200, 1), (64, 300), (1, 7)] { - let mut d = Vec::new(); - Rect::from_xywh(0, 0, 1, 1).write(&mut d); - d.extend([255, LayerMask::FLAG_PARAMETERS]); - d.extend([0b0001, density]); - d.extend([0, 0]); - Rect::from_xywh(0, 0, right, 1).write(&mut d); - let m = LayerMask::parse(&d).unwrap(); - assert!(!m.real_first, "density {density}, right {right}: {m:?}"); - assert_eq!(m.parameters.unwrap().user_density, Some(density)); - assert_eq!(m.real, Some(RealMask { flags: 0, background: 0, rect: Rect::from_xywh(0, 0, right, 1) })); - assert!(m.trailing.is_empty()); - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out, d); - } - // Photoshop's order with the same lengths still reads as Photoshop's order. - let mut d = Vec::new(); - Rect::from_xywh(0, 0, 1, 1).write(&mut d); - d.extend([255, LayerMask::FLAG_PARAMETERS]); - d.extend([0, 255]); - Rect::from_xywh(0, 0, 1, 1).write(&mut d); - d.extend([0b0001, 64]); - let m = LayerMask::parse(&d).unwrap(); - assert!(m.real_first, "{m:?}"); - assert_eq!(m.parameters.unwrap().user_density, Some(64)); - assert_eq!(m.real.map(|r| r.background), Some(255)); - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out, d); - } - - /// The spec's order (parameters, then real fields) still parses and stays byte-stable. - #[test] - fn real_mask_after_parameters_spec_layout() { - let mut d = Vec::new(); - Rect::from_xywh(1, 2, 3, 4).write(&mut d); - d.extend([255, LayerMask::FLAG_PARAMETERS]); - d.extend([0b0011, 200]); - d.extend(1.5f64.to_be_bytes()); - d.extend([0, 255]); - Rect::from_xywh(0, 0, 3, 3).write(&mut d); - let m = LayerMask::parse(&d).unwrap(); - assert!(!m.real_first); - assert_eq!(m.real.map(|r| r.rect), Some(Rect::from_xywh(0, 0, 3, 3))); - assert_eq!(m.parameters.unwrap().user_feather, Some(1.5)); - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out, d); - // Parameters alone (no real mask) keep reading in the spec's order. - let mut d = Vec::new(); - Rect::from_xywh(1, 2, 3, 4).write(&mut d); - d.extend([255, LayerMask::FLAG_PARAMETERS, 0b1010]); - d.extend(1.0f64.to_be_bytes()); - d.extend(2.0f64.to_be_bytes()); - d.extend([0, 0]); - let m = LayerMask::parse(&d).unwrap(); - assert_eq!(m.real, None); - assert_eq!(m.parameters.map(|p| (p.user_feather, p.vector_feather)), Some((Some(1.0), Some(2.0)))); - } - - #[test] - fn mask_sizes() { - let mut out = Vec::new(); - LayerMask::new(Rect::default(), 0, 0).write(&mut out); - assert_eq!(out.len(), 20); - let m = LayerMask { real: Some(RealMask::default()), trailing: vec![], ..LayerMask::new(Rect::default(), 0, 0) }; - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out.len(), 36); - } - - #[test] - fn short_mask_kept_raw() { - let mut rec = LayerRecord { mask: MaskData::Raw(vec![1, 2, 3]), ..Default::default() }; - rec.channels.clear(); - let info = LayerInfo { layers: vec![rec], ..Default::default() }; - rt(&info, Version::Psd); - } - - #[test] - fn flags_helpers() { - let mut f = LayerFlags::default(); - f.set_hidden(true); - f.set_transparency_protected(true); - assert!(f.hidden() && f.transparency_protected()); - f.set_pixel_data_irrelevant(true); - assert!(f.bit4_useful() && f.pixel_data_irrelevant()); - f.set_hidden(false); - assert!(!f.hidden()); - } - - #[test] - fn blending_ranges_parse() { - let br = BlendingRanges::full(3); - assert_eq!(br.data.len(), 32); - let r = br.ranges(); - assert_eq!(r.len(), 4); - assert_eq!(r[0].source, [0, 0, 255, 255]); - } - - #[test] - fn rect_helpers() { - let r = Rect::from_xywh(-5, -6, 10, 3); - assert_eq!((r.width(), r.height()), (10, 3)); - assert_eq!(r.size().unwrap(), (10, 3)); - assert!(!r.is_empty()); - let bad = Rect { top: 5, left: 0, bottom: 0, right: 1 }; - assert!(bad.size().is_err()); - assert!(bad.is_empty()); - let huge = Rect { top: 0, left: i32::MIN, bottom: 1, right: i32::MAX }; - assert!(huge.size().is_err()); - } - - #[test] - fn truncation_errors() { - let info = LayerInfo { layers: vec![sample_record(Version::Psd)], ..Default::default() }; - let mut out = Vec::new(); - info.write_body(&mut out, Version::Psd).unwrap(); - // The final byte may be the (optional) even padding; stop before it. - for cut in 0..out.len() - 1 { - assert!(LayerInfo::read_body(&out[..cut], Version::Psd).is_err(), "cut {cut}"); - } - } - - #[test] - fn bad_blend_signature() { - let info = LayerInfo { layers: vec![LayerRecord::default()], ..Default::default() }; - let mut out = Vec::new(); - info.write_body(&mut out, Version::Psd).unwrap(); - // count(2) + rect(16) + nch(2) = 20 → signature - out[20] = b'X'; - assert!(matches!(LayerInfo::read_body(&out, Version::Psd), Err(PsdError::InvalidSignature { .. }))); - } - - #[test] - fn too_many_layers_rejected() { - let out = 1000i16.to_be_bytes(); - assert!(LayerInfo::read_body(&out, Version::Psd).is_err()); - } - - #[test] - fn zero_length_channel() { - let mut rec = LayerRecord::default(); - rec.channels.push(ChannelData { id: 0, compression: None, data: vec![] }); - let info = LayerInfo { layers: vec![rec], ..Default::default() }; - rt(&info, Version::Psd); - assert_eq!(info.layers[0].decode_channel(0, 8, Version::Psd).unwrap(), Vec::::new()); - } - - /// The computed length matches the bytes written for every mask form, long names, custom block - /// padding, long-length blocks and trailing bytes. - #[test] - fn unpadded_len_matches_the_written_body() { - for version in [Version::Psd, Version::Psb] { - let mut layers = vec![sample_record(version), LayerRecord::default()]; - for (params, real, real_first) in [(true, true, true), (true, true, false), (true, false, true), (false, true, true)] { - let mut mask = LayerMask::new(Rect::from_xywh(1, 2, 3, 4), 0, LayerMask::FLAG_PARAMETERS); - mask.parameters = params.then_some(MaskParameters { - flags: 0x0f, - user_density: Some(1), - user_feather: Some(2.5), - vector_density: Some(3), - vector_feather: None, - }); - mask.real = real.then_some(RealMask { flags: 0, background: 255, rect: Rect::from_xywh(0, 0, 1, 1) }); - mask.real_first = real_first; - mask.trailing = vec![0; 3]; - let mut rec = sample_record(version); - rec.mask = MaskData::Mask(mask); - rec.name = vec![b'n'; 300]; - rec.blocks.push(TaggedBlock { signature: *b"8BIM", key: *b"lsct", data: vec![1; 5], padding: Some(vec![0; 3]) }); - rec.blocks.push(TaggedBlock { signature: *b"8BIM", key: *b"Lr16", data: vec![2; 7], padding: None }); - rec.extra_trailing = vec![9; 2]; - layers.push(rec); - } - layers.push(LayerRecord { mask: MaskData::Raw(vec![5; 11]), name: b"ab".to_vec(), ..Default::default() }); - let info = LayerInfo { layers, ..Default::default() }; - let mut out = Vec::new(); - info.write_unpadded(&mut out, version).unwrap(); - assert_eq!(info.unpadded_len(version).unwrap(), out.len() as u64, "{version:?}"); - } - } - - /// Padding without cloning the layers writes the same bytes as `pad_to` on a clone, and the - /// channel data length hint is exact. - #[test] - fn unpadded_write_matches_pad_to_on_a_clone() { - use crate::{ColorMode, Compression, testgen}; - for version in [Version::Psd, Version::Psb] { - for depth in [8u16, 16, 32] { - for compression in [Compression::Raw, Compression::Rle] { - let file = testgen::layered(version, ColorMode::Rgb, depth, compression); - let mut info = file.layer_info.clone().unwrap(); - for align in [1u64, 2, 4, 8] { - let mut cloned = info.clone(); - cloned.pad_to(version, align).unwrap(); - let mut want = Vec::new(); - cloned.write_body(&mut want, version).unwrap(); - let pad = info.pad_len(version, align).unwrap(); - let mut got = Vec::new(); - info.write_unpadded(&mut got, version).unwrap(); - assert!(got.len() >= info.channel_data_len()); - got.resize(got.len() + pad, 0); - assert_eq!(got, want, "{version:?} {depth} {compression:?} align {align}"); - } - info.padding = Some(vec![7, 7]); - let mut with_padding = Vec::new(); - info.write_body(&mut with_padding, version).unwrap(); - assert!(with_padding.ends_with(&[7, 7])); - } - } - } - } - - #[test] - fn nondefault_padding_kept() { - let info = LayerInfo { padding: Some(vec![0, 0]), ..Default::default() }; - let out = rt(&info, Version::Psd); - assert_eq!(out.len(), 4); - } - - #[test] - fn unknown_blend_and_blocks_passthrough() { - let rec = LayerRecord { blend_mode: BlendMode::Unknown(*b"wxyz"), blocks: vec![TaggedBlock::new(*b"Zzzz", vec![1, 2, 3, 4, 5])], ..Default::default() }; - rt(&LayerInfo { layers: vec![rec], ..Default::default() }, Version::Psd); - } -} +mod tests; diff --git a/crates/psd/src/layer/tests.rs b/crates/psd/src/layer/tests.rs new file mode 100644 index 0000000000..a5ad06efbb --- /dev/null +++ b/crates/psd/src/layer/tests.rs @@ -0,0 +1,374 @@ +use super::*; + +fn sample_record(version: Version) -> LayerRecord { + let rect = Rect::from_xywh(-3, 2, 5, 4); + let px: Vec = (0..20).collect(); + let mut channels = Vec::new(); + for (id, comp) in [(-1, Compression::Rle), (0, Compression::Raw), (1, Compression::Zip), (2, Compression::ZipPrediction)] { + channels.push(ChannelData::encode(id, comp, &px, 5, 4, 8, version).unwrap()); + } + let mask = LayerMask::new(Rect::from_xywh(0, 0, 2, 2), 255, LayerMask::FLAG_RELATIVE); + channels.push(ChannelData::encode(-2, Compression::Rle, &[1, 2, 3, 4], 2, 2, 8, version).unwrap()); + LayerRecord { + rect, + channels, + blend_mode: BlendMode::Screen, + opacity: 200, + clipping: 1, + flags: LayerFlags(LayerFlags::HIDDEN), + mask: MaskData::Mask(mask), + blending_ranges: BlendingRanges::full(3), + name: b"abc".to_vec(), + blocks: vec![TaggedBlock::unicode_name("\u{e4}bc"), TaggedBlock::layer_id(5)], + ..Default::default() + } +} + +fn rt(info: &LayerInfo, version: Version) -> Vec { + let mut out = Vec::new(); + info.write_body(&mut out, version).unwrap(); + let back = LayerInfo::read_body(&out, version).unwrap(); + assert_eq!(&back, info); + let mut again = Vec::new(); + back.write_body(&mut again, version).unwrap(); + assert_eq!(again, out); + out +} + +#[test] +fn empty_layer_info() { + let out = rt(&LayerInfo::default(), Version::Psd); + assert_eq!(out, vec![0, 0]); +} + +#[test] +fn record_roundtrip_psd_psb() { + for v in [Version::Psd, Version::Psb] { + let info = LayerInfo { merged_alpha: true, layers: vec![sample_record(v), LayerRecord::default()], padding: None }; + let out = rt(&info, v); + assert_eq!(out.len() % 2, 0); + assert_eq!(&out[..2], &(-2i16).to_be_bytes()); + } +} + +#[test] +fn psb_channel_lengths_are_8_bytes() { + let mut rec = LayerRecord::default(); + rec.channels.push(ChannelData { id: 0, compression: Some(Compression::Raw), data: vec![] }); + let info = LayerInfo { layers: vec![rec], ..Default::default() }; + let psd = rt(&info, Version::Psd); + let psb = rt(&info, Version::Psb); + assert_eq!(psb.len(), psd.len() + 4); +} + +#[test] +fn channel_decode_via_record() { + let rec = sample_record(Version::Psd); + let px: Vec = (0..20).collect(); + for id in [-1, 0, 1, 2] { + assert_eq!(rec.decode_channel(id, 8, Version::Psd).unwrap(), px); + } + assert_eq!(rec.decode_channel(-2, 8, Version::Psd).unwrap(), vec![1, 2, 3, 4]); + assert!(rec.decode_channel(7, 8, Version::Psd).is_err()); +} + +#[test] +fn record_accessors() { + let rec = sample_record(Version::Psd); + assert_eq!(rec.name(), "\u{e4}bc"); + assert!(!rec.is_visible()); + assert_eq!(rec.layer_id(), Some(5)); + assert_eq!(rec.fill_opacity(), 255); + assert_eq!(rec.section_type(), SectionType::Other); + assert!(rec.layer_mask().is_some()); + assert_eq!(rec.channel_rect(-2), Rect::from_xywh(0, 0, 2, 2)); + assert_eq!(rec.channel_rect(0), rec.rect); + let mut plain = LayerRecord { name: b"legacy".to_vec(), ..Default::default() }; + assert_eq!(plain.name(), "legacy"); + plain.blocks.push(TaggedBlock::fill_opacity(10)); + assert_eq!(plain.fill_opacity(), 10); + plain.block_mut(b"iOpa").unwrap().data[0] = 11; + assert_eq!(plain.fill_opacity(), 11); +} + +#[test] +fn mask_variants_roundtrip() { + let base = LayerMask::new(Rect::from_xywh(1, 2, 3, 4), 0, 0); + let with_real = LayerMask { real: Some(RealMask { flags: 1, background: 255, rect: Rect::from_xywh(0, 0, 9, 9) }), trailing: vec![], ..base.clone() }; + let with_params = LayerMask { + flags: LayerMask::FLAG_PARAMETERS, + parameters: Some(MaskParameters { + flags: 0b1111, + user_density: Some(128), + user_feather: Some(2.5), + vector_density: Some(64), + vector_feather: Some(0.5), + }), + real: Some(RealMask::default()), + trailing: vec![0, 0], + ..base.clone() + }; + let partial_params = LayerMask { + flags: LayerMask::FLAG_PARAMETERS, + parameters: Some(MaskParameters { flags: 0b0010, user_feather: Some(1.0), ..Default::default() }), + trailing: vec![], + ..base.clone() + }; + for m in [base, with_real, with_params, partial_params] { + let mut out = Vec::new(); + m.write(&mut out); + assert_eq!(LayerMask::parse(&out).unwrap(), m); + } +} + +/// Photoshop stores the real-mask fields before the mask parameters (psd-tools +/// mask-density-layervectormask.psd): user + vector mask with both densities set. +#[test] +fn real_mask_before_parameters_photoshop_layout() { + let mut d = Vec::new(); + Rect::from_xywh(15, -1, 18, 10).write(&mut d); + d.extend([0, LayerMask::FLAG_PARAMETERS | 8]); + d.extend([0, 255]); + Rect::from_xywh(0, 0, 32, 8).write(&mut d); + d.extend([0b0101, 64, 64, 0]); + let m = LayerMask::parse(&d).unwrap(); + assert_eq!(m.real.map(|r| r.rect), Some(Rect::from_xywh(0, 0, 32, 8))); + assert_eq!(m.real.map(|r| r.background), Some(255)); + let p = m.parameters.unwrap(); + assert_eq!((p.user_density, p.vector_density), (Some(64), Some(64))); + assert_eq!(m.trailing, vec![0]); + assert!(m.real_first); + let mut out = Vec::new(); + m.write(&mut out); + assert_eq!(out, d); +} + +/// A density-only record in the spec's order (#949): the parameter flags byte at 18 says one +/// value byte, so the spec's reading excludes the 38-byte length only if the real mask is +/// ignored, while byte 36 (inside the real rectangle's `right`) is 0 and makes Photoshop's +/// reading fit too. Photoshop's reading puts the density (64) where a 0-or-255 background +/// belongs, so the spec's order wins and the density survives. +#[test] +fn density_only_spec_layout_is_not_read_as_photoshop_order() { + for (density, right) in [(64u8, 1u32), (200, 1), (64, 300), (1, 7)] { + let mut d = Vec::new(); + Rect::from_xywh(0, 0, 1, 1).write(&mut d); + d.extend([255, LayerMask::FLAG_PARAMETERS]); + d.extend([0b0001, density]); + d.extend([0, 0]); + Rect::from_xywh(0, 0, right, 1).write(&mut d); + let m = LayerMask::parse(&d).unwrap(); + assert!(!m.real_first, "density {density}, right {right}: {m:?}"); + assert_eq!(m.parameters.unwrap().user_density, Some(density)); + assert_eq!(m.real, Some(RealMask { flags: 0, background: 0, rect: Rect::from_xywh(0, 0, right, 1) })); + assert!(m.trailing.is_empty()); + let mut out = Vec::new(); + m.write(&mut out); + assert_eq!(out, d); + } + // Photoshop's order with the same lengths still reads as Photoshop's order. + let mut d = Vec::new(); + Rect::from_xywh(0, 0, 1, 1).write(&mut d); + d.extend([255, LayerMask::FLAG_PARAMETERS]); + d.extend([0, 255]); + Rect::from_xywh(0, 0, 1, 1).write(&mut d); + d.extend([0b0001, 64]); + let m = LayerMask::parse(&d).unwrap(); + assert!(m.real_first, "{m:?}"); + assert_eq!(m.parameters.unwrap().user_density, Some(64)); + assert_eq!(m.real.map(|r| r.background), Some(255)); + let mut out = Vec::new(); + m.write(&mut out); + assert_eq!(out, d); +} + +/// The spec's order (parameters, then real fields) still parses and stays byte-stable. +#[test] +fn real_mask_after_parameters_spec_layout() { + let mut d = Vec::new(); + Rect::from_xywh(1, 2, 3, 4).write(&mut d); + d.extend([255, LayerMask::FLAG_PARAMETERS]); + d.extend([0b0011, 200]); + d.extend(1.5f64.to_be_bytes()); + d.extend([0, 255]); + Rect::from_xywh(0, 0, 3, 3).write(&mut d); + let m = LayerMask::parse(&d).unwrap(); + assert!(!m.real_first); + assert_eq!(m.real.map(|r| r.rect), Some(Rect::from_xywh(0, 0, 3, 3))); + assert_eq!(m.parameters.unwrap().user_feather, Some(1.5)); + let mut out = Vec::new(); + m.write(&mut out); + assert_eq!(out, d); + // Parameters alone (no real mask) keep reading in the spec's order. + let mut d = Vec::new(); + Rect::from_xywh(1, 2, 3, 4).write(&mut d); + d.extend([255, LayerMask::FLAG_PARAMETERS, 0b1010]); + d.extend(1.0f64.to_be_bytes()); + d.extend(2.0f64.to_be_bytes()); + d.extend([0, 0]); + let m = LayerMask::parse(&d).unwrap(); + assert_eq!(m.real, None); + assert_eq!(m.parameters.map(|p| (p.user_feather, p.vector_feather)), Some((Some(1.0), Some(2.0)))); +} + +#[test] +fn mask_sizes() { + let mut out = Vec::new(); + LayerMask::new(Rect::default(), 0, 0).write(&mut out); + assert_eq!(out.len(), 20); + let m = LayerMask { real: Some(RealMask::default()), trailing: vec![], ..LayerMask::new(Rect::default(), 0, 0) }; + let mut out = Vec::new(); + m.write(&mut out); + assert_eq!(out.len(), 36); +} + +#[test] +fn short_mask_kept_raw() { + let mut rec = LayerRecord { mask: MaskData::Raw(vec![1, 2, 3]), ..Default::default() }; + rec.channels.clear(); + let info = LayerInfo { layers: vec![rec], ..Default::default() }; + rt(&info, Version::Psd); +} + +#[test] +fn flags_helpers() { + let mut f = LayerFlags::default(); + f.set_hidden(true); + f.set_transparency_protected(true); + assert!(f.hidden() && f.transparency_protected()); + f.set_pixel_data_irrelevant(true); + assert!(f.bit4_useful() && f.pixel_data_irrelevant()); + f.set_hidden(false); + assert!(!f.hidden()); +} + +#[test] +fn blending_ranges_parse() { + let br = BlendingRanges::full(3); + assert_eq!(br.data.len(), 32); + let r = br.ranges(); + assert_eq!(r.len(), 4); + assert_eq!(r[0].source, [0, 0, 255, 255]); +} + +#[test] +fn rect_helpers() { + let r = Rect::from_xywh(-5, -6, 10, 3); + assert_eq!((r.width(), r.height()), (10, 3)); + assert_eq!(r.size().unwrap(), (10, 3)); + assert!(!r.is_empty()); + let bad = Rect { top: 5, left: 0, bottom: 0, right: 1 }; + assert!(bad.size().is_err()); + assert!(bad.is_empty()); + let huge = Rect { top: 0, left: i32::MIN, bottom: 1, right: i32::MAX }; + assert!(huge.size().is_err()); +} + +#[test] +fn truncation_errors() { + let info = LayerInfo { layers: vec![sample_record(Version::Psd)], ..Default::default() }; + let mut out = Vec::new(); + info.write_body(&mut out, Version::Psd).unwrap(); + // The final byte may be the (optional) even padding; stop before it. + for cut in 0..out.len() - 1 { + assert!(LayerInfo::read_body(&out[..cut], Version::Psd).is_err(), "cut {cut}"); + } +} + +#[test] +fn bad_blend_signature() { + let info = LayerInfo { layers: vec![LayerRecord::default()], ..Default::default() }; + let mut out = Vec::new(); + info.write_body(&mut out, Version::Psd).unwrap(); + // count(2) + rect(16) + nch(2) = 20 → signature + out[20] = b'X'; + assert!(matches!(LayerInfo::read_body(&out, Version::Psd), Err(PsdError::InvalidSignature { .. }))); +} + +#[test] +fn too_many_layers_rejected() { + let out = 1000i16.to_be_bytes(); + assert!(LayerInfo::read_body(&out, Version::Psd).is_err()); +} + +#[test] +fn zero_length_channel() { + let mut rec = LayerRecord::default(); + rec.channels.push(ChannelData { id: 0, compression: None, data: vec![] }); + let info = LayerInfo { layers: vec![rec], ..Default::default() }; + rt(&info, Version::Psd); + assert_eq!(info.layers[0].decode_channel(0, 8, Version::Psd).unwrap(), Vec::::new()); +} + +/// The computed length matches the bytes written for every mask form, long names, custom block +/// padding, long-length blocks and trailing bytes. +#[test] +fn unpadded_len_matches_the_written_body() { + for version in [Version::Psd, Version::Psb] { + let mut layers = vec![sample_record(version), LayerRecord::default()]; + for (params, real, real_first) in [(true, true, true), (true, true, false), (true, false, true), (false, true, true)] { + let mut mask = LayerMask::new(Rect::from_xywh(1, 2, 3, 4), 0, LayerMask::FLAG_PARAMETERS); + mask.parameters = + params.then_some(MaskParameters { flags: 0x0f, user_density: Some(1), user_feather: Some(2.5), vector_density: Some(3), vector_feather: None }); + mask.real = real.then_some(RealMask { flags: 0, background: 255, rect: Rect::from_xywh(0, 0, 1, 1) }); + mask.real_first = real_first; + mask.trailing = vec![0; 3]; + let mut rec = sample_record(version); + rec.mask = MaskData::Mask(mask); + rec.name = vec![b'n'; 300]; + rec.blocks.push(TaggedBlock { signature: *b"8BIM", key: *b"lsct", data: vec![1; 5], padding: Some(vec![0; 3]) }); + rec.blocks.push(TaggedBlock { signature: *b"8BIM", key: *b"Lr16", data: vec![2; 7], padding: None }); + rec.extra_trailing = vec![9; 2]; + layers.push(rec); + } + layers.push(LayerRecord { mask: MaskData::Raw(vec![5; 11]), name: b"ab".to_vec(), ..Default::default() }); + let info = LayerInfo { layers, ..Default::default() }; + let mut out = Vec::new(); + info.write_unpadded(&mut out, version).unwrap(); + assert_eq!(info.unpadded_len(version).unwrap(), out.len() as u64, "{version:?}"); + } +} + +/// Padding without cloning the layers writes the same bytes as `pad_to` on a clone, and the +/// channel data length hint is exact. +#[test] +fn unpadded_write_matches_pad_to_on_a_clone() { + use crate::{ColorMode, Compression, testgen}; + for version in [Version::Psd, Version::Psb] { + for depth in [8u16, 16, 32] { + for compression in [Compression::Raw, Compression::Rle] { + let file = testgen::layered(version, ColorMode::Rgb, depth, compression); + let mut info = file.layer_info.clone().unwrap(); + for align in [1u64, 2, 4, 8] { + let mut cloned = info.clone(); + cloned.pad_to(version, align).unwrap(); + let mut want = Vec::new(); + cloned.write_body(&mut want, version).unwrap(); + let pad = info.pad_len(version, align).unwrap(); + let mut got = Vec::new(); + info.write_unpadded(&mut got, version).unwrap(); + assert!(got.len() >= info.channel_data_len()); + got.resize(got.len() + pad, 0); + assert_eq!(got, want, "{version:?} {depth} {compression:?} align {align}"); + } + info.padding = Some(vec![7, 7]); + let mut with_padding = Vec::new(); + info.write_body(&mut with_padding, version).unwrap(); + assert!(with_padding.ends_with(&[7, 7])); + } + } + } +} + +#[test] +fn nondefault_padding_kept() { + let info = LayerInfo { padding: Some(vec![0, 0]), ..Default::default() }; + let out = rt(&info, Version::Psd); + assert_eq!(out.len(), 4); +} + +#[test] +fn unknown_blend_and_blocks_passthrough() { + let rec = LayerRecord { blend_mode: BlendMode::Unknown(*b"wxyz"), blocks: vec![TaggedBlock::new(*b"Zzzz", vec![1, 2, 3, 4, 5])], ..Default::default() }; + rt(&LayerInfo { layers: vec![rec], ..Default::default() }, Version::Psd); +} From 363a5797f88cf1d6496c99aef0a33761baf4ac25 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:01 +0000 Subject: [PATCH 012/259] refactor(psd): move compression.rs tests to compression/tests.rs --- crates/psd/src/compression.rs | 356 +--------------------------- crates/psd/src/compression/tests.rs | 353 +++++++++++++++++++++++++++ 2 files changed, 354 insertions(+), 355 deletions(-) create mode 100644 crates/psd/src/compression/tests.rs diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs index 68782464ad..3ec7d64bb8 100644 --- a/crates/psd/src/compression.rs +++ b/crates/psd/src/compression.rs @@ -539,361 +539,7 @@ pub fn unpredict(buf: &mut [u8], layout: &PlaneLayout) -> Result<()> { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn checked_zip_validates_trailer_size_and_padding_budget() { - let layout = PlaneLayout { planes: 1, width: 3, height: 1, depth: 8, version: Version::Psd }; - for compression in [Compression::Zip, Compression::ZipPrediction] { - let data = encode_planes(compression, &[1, 2, 3], &layout).unwrap(); - for cut in 0..data.len() { - assert!(decode_planes(compression, &data[..cut], &layout).is_err(), "cut {cut}"); - assert!(validate_planes(compression, &data[..cut], &layout).is_err()); - } - let mut corrupt = data; - *corrupt.last_mut().unwrap() ^= 1; - assert!(decode_planes(compression, &corrupt, &layout).is_err()); - assert!(validate_planes(compression, &corrupt, &layout).is_err()); - } - let padded = zip_compress(&[1, 2, 3, 0]); - assert_eq!(decode_planes(Compression::Zip, &padded, &layout).unwrap(), [1, 2, 3]); - let bomb = zip_compress(&vec![0; (1 << 20) + 4]); - assert!(decode_planes(Compression::Zip, &bomb, &layout).is_err()); - assert!(validate_planes(Compression::Zip, &bomb, &layout).is_err()); - } - - fn layout(planes: usize, width: usize, height: usize, depth: u16, version: Version) -> PlaneLayout { - PlaneLayout { planes, width, height, depth, version } - } - - fn pb_roundtrip(src: &[u8]) -> Vec { - let enc = packbits::encode_vec(src); - let dec = packbits::decode(&enc, src.len()).unwrap(); - assert_eq!(dec, src, "encoded: {enc:?}"); - enc - } - - #[test] - fn zip_absurd_declared_size_is_an_error() { - let z = zip_compress(&[7u8; 64]); - for expected in [1usize << 40, usize::MAX / 2, usize::MAX] { - assert!(zip_decompress(&z, expected).is_err(), "expected {expected}"); - } - // Through decode_planes: a tiny ZIP channel claiming a huge (but capped) plane. - let l = layout(1, 1 << 16, 1 << 15, 8, Version::Psb); - assert!(decode_planes(Compression::Zip, &z, &l).is_err()); - assert!(decode_planes(Compression::ZipPrediction, &z, &l).is_err()); - // Past MAX_DECODED_BYTES. - let l = layout(4, 1 << 20, 1 << 20, 32, Version::Psb); - assert!(decode_planes(Compression::Zip, &z, &l).is_err()); - // Garbage that is not zlib at all. - assert!(zip_decompress(&[0xff; 16], 1 << 30).is_err()); - } - - #[test] - fn zip_decompress_exact_and_truncated() { - let src: Vec = (0..3_000_000u32).map(|i| (i % 251) as u8).collect(); - let z = zip_compress(&src); - assert_eq!(zip_decompress(&z, src.len()).unwrap(), src); - // Asking for fewer bytes returns exactly that many. - assert_eq!(zip_decompress(&z, 1000).unwrap(), &src[..1000]); - assert!(zip_decompress(&z, src.len() + 1).is_err()); - assert!(zip_decompress(&z, 0).unwrap().is_empty()); - } - - #[test] - fn packbits_empty() { - assert!(pb_roundtrip(&[]).is_empty()); - } - - #[test] - fn packbits_single() { - assert_eq!(pb_roundtrip(&[7]), vec![0, 7]); - } - - #[test] - fn packbits_run_of_two() { - assert_eq!(pb_roundtrip(&[5, 5]), vec![0xff, 5]); - } - - #[test] - fn packbits_run_128() { - let src = vec![9u8; 128]; - assert_eq!(pb_roundtrip(&src), vec![0x81, 9]); - } - - #[test] - fn packbits_run_129() { - let src = vec![9u8; 129]; - assert_eq!(pb_roundtrip(&src), vec![0x81, 9, 0, 9]); - } - - #[test] - fn packbits_run_130_and_256() { - pb_roundtrip(&[1u8; 130]); - let enc = pb_roundtrip(&[1u8; 256]); - assert_eq!(enc, vec![0x81, 1, 0x81, 1]); - } - - #[test] - fn packbits_literal_128_and_129() { - let src: Vec = (0..128u32).map(|i| i as u8).collect(); - let enc = pb_roundtrip(&src); - assert_eq!(enc[0], 127); - assert_eq!(enc.len(), 129); - let src: Vec = (0..129u32).map(|i| i as u8).collect(); - let enc = pb_roundtrip(&src); - assert_eq!(enc[0], 127); - assert_eq!(enc[129], 0); - assert_eq!(enc.len(), 131); - } - - #[test] - fn packbits_literal_run_boundary() { - pb_roundtrip(&[1, 2, 3, 3, 3, 3, 4, 5]); - pb_roundtrip(&[1, 1, 2, 2, 3, 3]); - pb_roundtrip(&[1, 2, 2, 3]); - pb_roundtrip(&[0, 0, 0, 1, 0, 0, 0]); - let enc = pb_roundtrip(&[1, 2, 3, 3, 3]); - assert_eq!(enc, vec![1, 1, 2, 0xfe, 3]); - } - - #[test] - fn packbits_never_emits_noop() { - for n in 0..300usize { - let src: Vec = (0..n).map(|i| ((i / 3) % 5) as u8).collect(); - let enc = pb_roundtrip(&src); - // Walk the packets to find headers. - let mut i = 0; - while i < enc.len() { - let h = enc[i] as i8; - assert_ne!(h, -128); - i += if h >= 0 { h as usize + 2 } else { 2 }; - } - } - } - - #[test] - fn packbits_decode_noop_skipped() { - assert_eq!(packbits::decode(&[0x80, 0, 42], 1).unwrap(), vec![42]); - } - - #[test] - fn packbits_decode_errors() { - assert!(packbits::decode(&[], 1).is_err()); - assert!(packbits::decode(&[2, 1, 2], 3).is_err()); // literal truncated - assert!(packbits::decode(&[0xfe], 3).is_err()); // run truncated - assert!(packbits::decode(&[0xfd, 1], 3).is_err()); // run overflows (4 > 3) - assert!(packbits::decode(&[3, 1, 2, 3, 4], 3).is_err()); // literal overflows - } - - /// `out.len() + expected` past `usize::MAX` used to panic in debug builds and, in release, - /// wrap and return `Ok` having decoded nothing. - #[test] - fn packbits_decode_into_output_length_overflow_is_an_error() { - let mut out = vec![7u8]; - let r = packbits::decode_into(&[0x00, 0xaa], usize::MAX, &mut out); - assert!(matches!(r, Err(PsdError::LimitExceeded(_))), "{r:?}"); - assert_eq!(out, [7]); - // The largest `expected` that fits still decodes up to the input, then reports it short. - let r = packbits::decode_into(&[0x00, 0xaa], usize::MAX - 1, &mut out); - assert!(matches!(r, Err(PsdError::Decompress(_))), "{r:?}"); - assert_eq!(out, [7, 0xaa]); - } - - #[test] - fn packbits_zero_expected_ignores_input() { - assert_eq!(packbits::decode(&[0xff, 1], 0).unwrap(), Vec::::new()); - } - - #[test] - fn compression_values() { - for v in 0..6 { - assert_eq!(Compression::from_u16(v).as_u16(), v); - } - assert_eq!(Compression::from_u16(9), Compression::Unknown(9)); - } - - fn sample_data(l: &PlaneLayout) -> Vec { - let n = l.decoded_len().unwrap(); - (0..n).map(|i| ((i * 7 + i / 5) % 251) as u8).collect() - } - - #[test] - fn all_codecs_roundtrip_all_depths() { - for version in [Version::Psd, Version::Psb] { - for depth in [1u16, 8, 16, 32] { - for (w, h) in [(0, 0), (1, 1), (3, 2), (17, 5), (0, 3), (4, 0)] { - for planes in [1, 3] { - let l = layout(planes, w, h, depth, version); - let data = sample_data(&l); - for c in Compression::ALL { - let enc = encode_planes(c, &data, &l).unwrap(); - validate_planes(c, &enc, &l).unwrap(); - let dec = decode_planes(c, &enc, &l).unwrap(); - assert_eq!(dec, data, "{c:?} {depth} {w}x{h} {version:?}"); - } - } - } - } - } - } - - #[test] - fn rle_count_width_psd_vs_psb() { - let data = vec![0u8; 4]; - let psd = encode_planes(Compression::Rle, &data, &layout(1, 2, 2, 8, Version::Psd)).unwrap(); - let psb = encode_planes(Compression::Rle, &data, &layout(1, 2, 2, 8, Version::Psb)).unwrap(); - assert_eq!(psd, vec![0, 2, 0, 2, 0xff, 0, 0xff, 0]); - assert_eq!(psb, vec![0, 0, 0, 2, 0, 0, 0, 2, 0xff, 0, 0xff, 0]); - assert!(decode_planes(Compression::Rle, &psd, &layout(1, 2, 2, 8, Version::Psb)).is_err()); - } - - #[test] - fn rle_odd_width() { - let l = layout(1, 7, 3, 16, Version::Psd); - let data = sample_data(&l); - let enc = encode_planes(Compression::Rle, &data, &l).unwrap(); - assert_eq!(decode_planes(Compression::Rle, &enc, &l).unwrap(), data); - } - - #[test] - fn rle_truncated_fails() { - let l = layout(1, 10, 10, 8, Version::Psd); - let data = sample_data(&l); - let enc = encode_planes(Compression::Rle, &data, &l).unwrap(); - for cut in 0..enc.len() { - assert!(decode_planes(Compression::Rle, &enc[..cut], &l).is_err(), "cut {cut}"); - assert!(validate_planes(Compression::Rle, &enc[..cut], &l).is_err(), "cut {cut}"); - } - } - - #[test] - fn zip_truncated_fails() { - let l = layout(1, 10, 10, 8, Version::Psd); - let data = sample_data(&l); - let enc = encode_planes(Compression::Zip, &data, &l).unwrap(); - for cut in 0..enc.len() - 4 { - assert!(decode_planes(Compression::Zip, &enc[..cut], &l).is_err(), "cut {cut}"); - assert!(validate_planes(Compression::Zip, &enc[..cut], &l).is_err(), "cut {cut}"); - } - } - - /// #2926: a ZIP stream declaring more than `MAX_DECODED_BYTES` is not inflated at parse - /// time. Garbage zlib data proves it: decompressing it would fail, skipping it passes, and - /// decoding the layout still reports the size limit. - #[test] - fn zip_over_budget_is_not_decompressed_at_parse() { - let l = layout(4, 300_000, 300_000, 8, Version::Psb); - assert!(l.total_bytes().unwrap() > MAX_DECODED_BYTES); - let garbage = [0xde, 0xad, 0xbe, 0xef, 0x01, 0x02, 0x03]; - for c in [Compression::Zip, Compression::ZipPrediction] { - validate_planes(c, &garbage, &l).unwrap(); - assert!(matches!(decode_planes(c, &garbage, &l), Err(PsdError::LimitExceeded(_))), "{c:?}"); - } - // Within the budget the stream is still checked. - let small = layout(1, 4, 4, 8, Version::Psd); - assert!(validate_planes(Compression::Zip, &garbage, &small).is_err()); - } - - #[test] - fn raw_short_fails() { - let l = layout(2, 3, 3, 8, Version::Psd); - assert!(decode_planes(Compression::Raw, &[0; 17], &l).is_err()); - assert!(decode_planes(Compression::Raw, &[0; 18], &l).is_ok()); - } - - #[test] - fn unknown_compression_errors() { - let l = layout(1, 1, 1, 8, Version::Psd); - assert!(decode_planes(Compression::Unknown(7), &[0], &l).is_err()); - assert!(encode_planes(Compression::Unknown(7), &[0], &l).is_err()); - } - - #[test] - fn encode_rejects_wrong_size() { - let l = layout(1, 2, 2, 8, Version::Psd); - assert!(encode_planes(Compression::Raw, &[0; 3], &l).is_err()); - } - - #[test] - fn decoded_len_limits() { - let l = layout(56, 300_000, 300_000, 32, Version::Psb); - assert!(matches!(l.decoded_len(), Err(PsdError::LimitExceeded(_)))); - assert!(decode_planes(Compression::Rle, &[0; 16], &l).is_err()); - } - - /// Real PSBs go past 2 GiB in one decode (#375): a 30000² RGB merged image and a 33000² - /// 16-bit layer channel. Only checks the limit, so nothing is allocated. - #[test] - #[cfg(target_pointer_width = "64")] - fn decoded_len_allows_large_psb_planes() { - assert_eq!(layout(3, 30_000, 30_000, 8, Version::Psb).decoded_len().unwrap(), 2_700_000_000); - assert_eq!(layout(1, 33_000, 33_000, 16, Version::Psb).decoded_len().unwrap(), 2_178_000_000); - assert!(layout(4, 40_000, 40_000, 16, Version::Psb).decoded_len().is_err()); - } - - #[test] - fn prediction_8bit_known_vector() { - let l = layout(1, 4, 1, 8, Version::Psd); - let mut v = vec![10, 12, 11, 255]; - predict(&mut v, &l).unwrap(); - assert_eq!(v, vec![10, 2, 255, 244]); - unpredict(&mut v, &l).unwrap(); - assert_eq!(v, vec![10, 12, 11, 255]); - } - - #[test] - fn prediction_16bit_known_vector() { - let l = layout(1, 3, 1, 16, Version::Psd); - let mut v = vec![0x01, 0x00, 0x01, 0x05, 0x00, 0x00]; - predict(&mut v, &l).unwrap(); - assert_eq!(v, vec![0x01, 0x00, 0x00, 0x05, 0xfe, 0xfb]); - unpredict(&mut v, &l).unwrap(); - assert_eq!(v, vec![0x01, 0x00, 0x01, 0x05, 0x00, 0x00]); - } - - #[test] - fn prediction_32bit_plane_shuffle() { - // Two samples: AABBCCDD and 11223344 → planes [AA,11][BB,22][CC,33][DD,44] - let l = layout(1, 2, 1, 32, Version::Psd); - let orig = vec![0xAA, 0xBB, 0xCC, 0xDD, 0x11, 0x22, 0x33, 0x44]; - let mut v = orig.clone(); - predict(&mut v, &l).unwrap(); - let planes = [0xAAu8, 0x11, 0xBB, 0x22, 0xCC, 0x33, 0xDD, 0x44]; - let mut expect = planes; - for i in (1..8).rev() { - expect[i] = expect[i].wrapping_sub(expect[i - 1]); - } - assert_eq!(v, expect); - unpredict(&mut v, &l).unwrap(); - assert_eq!(v, orig); - } - - #[test] - fn prediction_32bit_floats_roundtrip() { - let l = layout(1, 5, 2, 32, Version::Psd); - let mut v = Vec::new(); - for i in 0..10 { - v.extend_from_slice(&(i as f32 * 0.37 - 1.0).to_be_bytes()); - } - let enc = encode_planes(Compression::ZipPrediction, &v, &l).unwrap(); - assert_eq!(decode_planes(Compression::ZipPrediction, &enc, &l).unwrap(), v); - } - - #[test] - fn zip_bomb_is_bounded() { - let big = zip_compress(&vec![0u8; 1 << 20]); - let out = zip_decompress(&big, 10).unwrap(); - assert_eq!(out.len(), 10); - } - - #[test] - fn zip_garbage_errors() { - assert!(zip_decompress(&[1, 2, 3, 4], 4).is_err()); - } -} +mod tests; #[cfg(test)] mod parallel_rle_equivalence { diff --git a/crates/psd/src/compression/tests.rs b/crates/psd/src/compression/tests.rs new file mode 100644 index 0000000000..a9700ded31 --- /dev/null +++ b/crates/psd/src/compression/tests.rs @@ -0,0 +1,353 @@ +use super::*; + +#[test] +fn checked_zip_validates_trailer_size_and_padding_budget() { + let layout = PlaneLayout { planes: 1, width: 3, height: 1, depth: 8, version: Version::Psd }; + for compression in [Compression::Zip, Compression::ZipPrediction] { + let data = encode_planes(compression, &[1, 2, 3], &layout).unwrap(); + for cut in 0..data.len() { + assert!(decode_planes(compression, &data[..cut], &layout).is_err(), "cut {cut}"); + assert!(validate_planes(compression, &data[..cut], &layout).is_err()); + } + let mut corrupt = data; + *corrupt.last_mut().unwrap() ^= 1; + assert!(decode_planes(compression, &corrupt, &layout).is_err()); + assert!(validate_planes(compression, &corrupt, &layout).is_err()); + } + let padded = zip_compress(&[1, 2, 3, 0]); + assert_eq!(decode_planes(Compression::Zip, &padded, &layout).unwrap(), [1, 2, 3]); + let bomb = zip_compress(&vec![0; (1 << 20) + 4]); + assert!(decode_planes(Compression::Zip, &bomb, &layout).is_err()); + assert!(validate_planes(Compression::Zip, &bomb, &layout).is_err()); +} + +fn layout(planes: usize, width: usize, height: usize, depth: u16, version: Version) -> PlaneLayout { + PlaneLayout { planes, width, height, depth, version } +} + +fn pb_roundtrip(src: &[u8]) -> Vec { + let enc = packbits::encode_vec(src); + let dec = packbits::decode(&enc, src.len()).unwrap(); + assert_eq!(dec, src, "encoded: {enc:?}"); + enc +} + +#[test] +fn zip_absurd_declared_size_is_an_error() { + let z = zip_compress(&[7u8; 64]); + for expected in [1usize << 40, usize::MAX / 2, usize::MAX] { + assert!(zip_decompress(&z, expected).is_err(), "expected {expected}"); + } + // Through decode_planes: a tiny ZIP channel claiming a huge (but capped) plane. + let l = layout(1, 1 << 16, 1 << 15, 8, Version::Psb); + assert!(decode_planes(Compression::Zip, &z, &l).is_err()); + assert!(decode_planes(Compression::ZipPrediction, &z, &l).is_err()); + // Past MAX_DECODED_BYTES. + let l = layout(4, 1 << 20, 1 << 20, 32, Version::Psb); + assert!(decode_planes(Compression::Zip, &z, &l).is_err()); + // Garbage that is not zlib at all. + assert!(zip_decompress(&[0xff; 16], 1 << 30).is_err()); +} + +#[test] +fn zip_decompress_exact_and_truncated() { + let src: Vec = (0..3_000_000u32).map(|i| (i % 251) as u8).collect(); + let z = zip_compress(&src); + assert_eq!(zip_decompress(&z, src.len()).unwrap(), src); + // Asking for fewer bytes returns exactly that many. + assert_eq!(zip_decompress(&z, 1000).unwrap(), &src[..1000]); + assert!(zip_decompress(&z, src.len() + 1).is_err()); + assert!(zip_decompress(&z, 0).unwrap().is_empty()); +} + +#[test] +fn packbits_empty() { + assert!(pb_roundtrip(&[]).is_empty()); +} + +#[test] +fn packbits_single() { + assert_eq!(pb_roundtrip(&[7]), vec![0, 7]); +} + +#[test] +fn packbits_run_of_two() { + assert_eq!(pb_roundtrip(&[5, 5]), vec![0xff, 5]); +} + +#[test] +fn packbits_run_128() { + let src = vec![9u8; 128]; + assert_eq!(pb_roundtrip(&src), vec![0x81, 9]); +} + +#[test] +fn packbits_run_129() { + let src = vec![9u8; 129]; + assert_eq!(pb_roundtrip(&src), vec![0x81, 9, 0, 9]); +} + +#[test] +fn packbits_run_130_and_256() { + pb_roundtrip(&[1u8; 130]); + let enc = pb_roundtrip(&[1u8; 256]); + assert_eq!(enc, vec![0x81, 1, 0x81, 1]); +} + +#[test] +fn packbits_literal_128_and_129() { + let src: Vec = (0..128u32).map(|i| i as u8).collect(); + let enc = pb_roundtrip(&src); + assert_eq!(enc[0], 127); + assert_eq!(enc.len(), 129); + let src: Vec = (0..129u32).map(|i| i as u8).collect(); + let enc = pb_roundtrip(&src); + assert_eq!(enc[0], 127); + assert_eq!(enc[129], 0); + assert_eq!(enc.len(), 131); +} + +#[test] +fn packbits_literal_run_boundary() { + pb_roundtrip(&[1, 2, 3, 3, 3, 3, 4, 5]); + pb_roundtrip(&[1, 1, 2, 2, 3, 3]); + pb_roundtrip(&[1, 2, 2, 3]); + pb_roundtrip(&[0, 0, 0, 1, 0, 0, 0]); + let enc = pb_roundtrip(&[1, 2, 3, 3, 3]); + assert_eq!(enc, vec![1, 1, 2, 0xfe, 3]); +} + +#[test] +fn packbits_never_emits_noop() { + for n in 0..300usize { + let src: Vec = (0..n).map(|i| ((i / 3) % 5) as u8).collect(); + let enc = pb_roundtrip(&src); + // Walk the packets to find headers. + let mut i = 0; + while i < enc.len() { + let h = enc[i] as i8; + assert_ne!(h, -128); + i += if h >= 0 { h as usize + 2 } else { 2 }; + } + } +} + +#[test] +fn packbits_decode_noop_skipped() { + assert_eq!(packbits::decode(&[0x80, 0, 42], 1).unwrap(), vec![42]); +} + +#[test] +fn packbits_decode_errors() { + assert!(packbits::decode(&[], 1).is_err()); + assert!(packbits::decode(&[2, 1, 2], 3).is_err()); // literal truncated + assert!(packbits::decode(&[0xfe], 3).is_err()); // run truncated + assert!(packbits::decode(&[0xfd, 1], 3).is_err()); // run overflows (4 > 3) + assert!(packbits::decode(&[3, 1, 2, 3, 4], 3).is_err()); // literal overflows +} + +/// `out.len() + expected` past `usize::MAX` used to panic in debug builds and, in release, +/// wrap and return `Ok` having decoded nothing. +#[test] +fn packbits_decode_into_output_length_overflow_is_an_error() { + let mut out = vec![7u8]; + let r = packbits::decode_into(&[0x00, 0xaa], usize::MAX, &mut out); + assert!(matches!(r, Err(PsdError::LimitExceeded(_))), "{r:?}"); + assert_eq!(out, [7]); + // The largest `expected` that fits still decodes up to the input, then reports it short. + let r = packbits::decode_into(&[0x00, 0xaa], usize::MAX - 1, &mut out); + assert!(matches!(r, Err(PsdError::Decompress(_))), "{r:?}"); + assert_eq!(out, [7, 0xaa]); +} + +#[test] +fn packbits_zero_expected_ignores_input() { + assert_eq!(packbits::decode(&[0xff, 1], 0).unwrap(), Vec::::new()); +} + +#[test] +fn compression_values() { + for v in 0..6 { + assert_eq!(Compression::from_u16(v).as_u16(), v); + } + assert_eq!(Compression::from_u16(9), Compression::Unknown(9)); +} + +fn sample_data(l: &PlaneLayout) -> Vec { + let n = l.decoded_len().unwrap(); + (0..n).map(|i| ((i * 7 + i / 5) % 251) as u8).collect() +} + +#[test] +fn all_codecs_roundtrip_all_depths() { + for version in [Version::Psd, Version::Psb] { + for depth in [1u16, 8, 16, 32] { + for (w, h) in [(0, 0), (1, 1), (3, 2), (17, 5), (0, 3), (4, 0)] { + for planes in [1, 3] { + let l = layout(planes, w, h, depth, version); + let data = sample_data(&l); + for c in Compression::ALL { + let enc = encode_planes(c, &data, &l).unwrap(); + validate_planes(c, &enc, &l).unwrap(); + let dec = decode_planes(c, &enc, &l).unwrap(); + assert_eq!(dec, data, "{c:?} {depth} {w}x{h} {version:?}"); + } + } + } + } + } +} + +#[test] +fn rle_count_width_psd_vs_psb() { + let data = vec![0u8; 4]; + let psd = encode_planes(Compression::Rle, &data, &layout(1, 2, 2, 8, Version::Psd)).unwrap(); + let psb = encode_planes(Compression::Rle, &data, &layout(1, 2, 2, 8, Version::Psb)).unwrap(); + assert_eq!(psd, vec![0, 2, 0, 2, 0xff, 0, 0xff, 0]); + assert_eq!(psb, vec![0, 0, 0, 2, 0, 0, 0, 2, 0xff, 0, 0xff, 0]); + assert!(decode_planes(Compression::Rle, &psd, &layout(1, 2, 2, 8, Version::Psb)).is_err()); +} + +#[test] +fn rle_odd_width() { + let l = layout(1, 7, 3, 16, Version::Psd); + let data = sample_data(&l); + let enc = encode_planes(Compression::Rle, &data, &l).unwrap(); + assert_eq!(decode_planes(Compression::Rle, &enc, &l).unwrap(), data); +} + +#[test] +fn rle_truncated_fails() { + let l = layout(1, 10, 10, 8, Version::Psd); + let data = sample_data(&l); + let enc = encode_planes(Compression::Rle, &data, &l).unwrap(); + for cut in 0..enc.len() { + assert!(decode_planes(Compression::Rle, &enc[..cut], &l).is_err(), "cut {cut}"); + assert!(validate_planes(Compression::Rle, &enc[..cut], &l).is_err(), "cut {cut}"); + } +} + +#[test] +fn zip_truncated_fails() { + let l = layout(1, 10, 10, 8, Version::Psd); + let data = sample_data(&l); + let enc = encode_planes(Compression::Zip, &data, &l).unwrap(); + for cut in 0..enc.len() - 4 { + assert!(decode_planes(Compression::Zip, &enc[..cut], &l).is_err(), "cut {cut}"); + assert!(validate_planes(Compression::Zip, &enc[..cut], &l).is_err(), "cut {cut}"); + } +} + +/// #2926: a ZIP stream declaring more than `MAX_DECODED_BYTES` is not inflated at parse +/// time. Garbage zlib data proves it: decompressing it would fail, skipping it passes, and +/// decoding the layout still reports the size limit. +#[test] +fn zip_over_budget_is_not_decompressed_at_parse() { + let l = layout(4, 300_000, 300_000, 8, Version::Psb); + assert!(l.total_bytes().unwrap() > MAX_DECODED_BYTES); + let garbage = [0xde, 0xad, 0xbe, 0xef, 0x01, 0x02, 0x03]; + for c in [Compression::Zip, Compression::ZipPrediction] { + validate_planes(c, &garbage, &l).unwrap(); + assert!(matches!(decode_planes(c, &garbage, &l), Err(PsdError::LimitExceeded(_))), "{c:?}"); + } + // Within the budget the stream is still checked. + let small = layout(1, 4, 4, 8, Version::Psd); + assert!(validate_planes(Compression::Zip, &garbage, &small).is_err()); +} + +#[test] +fn raw_short_fails() { + let l = layout(2, 3, 3, 8, Version::Psd); + assert!(decode_planes(Compression::Raw, &[0; 17], &l).is_err()); + assert!(decode_planes(Compression::Raw, &[0; 18], &l).is_ok()); +} + +#[test] +fn unknown_compression_errors() { + let l = layout(1, 1, 1, 8, Version::Psd); + assert!(decode_planes(Compression::Unknown(7), &[0], &l).is_err()); + assert!(encode_planes(Compression::Unknown(7), &[0], &l).is_err()); +} + +#[test] +fn encode_rejects_wrong_size() { + let l = layout(1, 2, 2, 8, Version::Psd); + assert!(encode_planes(Compression::Raw, &[0; 3], &l).is_err()); +} + +#[test] +fn decoded_len_limits() { + let l = layout(56, 300_000, 300_000, 32, Version::Psb); + assert!(matches!(l.decoded_len(), Err(PsdError::LimitExceeded(_)))); + assert!(decode_planes(Compression::Rle, &[0; 16], &l).is_err()); +} + +/// Real PSBs go past 2 GiB in one decode (#375): a 30000² RGB merged image and a 33000² +/// 16-bit layer channel. Only checks the limit, so nothing is allocated. +#[test] +#[cfg(target_pointer_width = "64")] +fn decoded_len_allows_large_psb_planes() { + assert_eq!(layout(3, 30_000, 30_000, 8, Version::Psb).decoded_len().unwrap(), 2_700_000_000); + assert_eq!(layout(1, 33_000, 33_000, 16, Version::Psb).decoded_len().unwrap(), 2_178_000_000); + assert!(layout(4, 40_000, 40_000, 16, Version::Psb).decoded_len().is_err()); +} + +#[test] +fn prediction_8bit_known_vector() { + let l = layout(1, 4, 1, 8, Version::Psd); + let mut v = vec![10, 12, 11, 255]; + predict(&mut v, &l).unwrap(); + assert_eq!(v, vec![10, 2, 255, 244]); + unpredict(&mut v, &l).unwrap(); + assert_eq!(v, vec![10, 12, 11, 255]); +} + +#[test] +fn prediction_16bit_known_vector() { + let l = layout(1, 3, 1, 16, Version::Psd); + let mut v = vec![0x01, 0x00, 0x01, 0x05, 0x00, 0x00]; + predict(&mut v, &l).unwrap(); + assert_eq!(v, vec![0x01, 0x00, 0x00, 0x05, 0xfe, 0xfb]); + unpredict(&mut v, &l).unwrap(); + assert_eq!(v, vec![0x01, 0x00, 0x01, 0x05, 0x00, 0x00]); +} + +#[test] +fn prediction_32bit_plane_shuffle() { + // Two samples: AABBCCDD and 11223344 → planes [AA,11][BB,22][CC,33][DD,44] + let l = layout(1, 2, 1, 32, Version::Psd); + let orig = vec![0xAA, 0xBB, 0xCC, 0xDD, 0x11, 0x22, 0x33, 0x44]; + let mut v = orig.clone(); + predict(&mut v, &l).unwrap(); + let planes = [0xAAu8, 0x11, 0xBB, 0x22, 0xCC, 0x33, 0xDD, 0x44]; + let mut expect = planes; + for i in (1..8).rev() { + expect[i] = expect[i].wrapping_sub(expect[i - 1]); + } + assert_eq!(v, expect); + unpredict(&mut v, &l).unwrap(); + assert_eq!(v, orig); +} + +#[test] +fn prediction_32bit_floats_roundtrip() { + let l = layout(1, 5, 2, 32, Version::Psd); + let mut v = Vec::new(); + for i in 0..10 { + v.extend_from_slice(&(i as f32 * 0.37 - 1.0).to_be_bytes()); + } + let enc = encode_planes(Compression::ZipPrediction, &v, &l).unwrap(); + assert_eq!(decode_planes(Compression::ZipPrediction, &enc, &l).unwrap(), v); +} + +#[test] +fn zip_bomb_is_bounded() { + let big = zip_compress(&vec![0u8; 1 << 20]); + let out = zip_decompress(&big, 10).unwrap(); + assert_eq!(out.len(), 10); +} + +#[test] +fn zip_garbage_errors() { + assert!(zip_decompress(&[1, 2, 3, 4], 4).is_err()); +} From 02d2de4b9955c02ffd639a7486316901f76e8911 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:01 +0000 Subject: [PATCH 013/259] refactor(psd): move patterns.rs tests to patterns/tests.rs --- crates/psd/src/patterns.rs | 355 +------------------------------ crates/psd/src/patterns/tests.rs | 352 ++++++++++++++++++++++++++++++ 2 files changed, 353 insertions(+), 354 deletions(-) create mode 100644 crates/psd/src/patterns/tests.rs diff --git a/crates/psd/src/patterns.rs b/crates/psd/src/patterns.rs index 85bf285db9..af4afea0a2 100644 --- a/crates/psd/src/patterns.rs +++ b/crates/psd/src/patterns.rs @@ -575,357 +575,4 @@ pub fn write_pat_file(patterns: &[PsdPattern]) -> Result> { } #[cfg(test)] -mod tests { - use super::*; - - fn pat(depth: u16, alpha: bool) -> PsdPattern { - let (w, h) = (5u32, 3u32); - let bpp = usize::from(depth / 8); - let plane = |s: u8| (0..w as usize * h as usize * bpp).map(|i| (i as u8).wrapping_mul(7).wrapping_add(s)).collect::>(); - PsdPattern { - mode: 3, - width: w, - height: h, - name: "Test ✓".into(), - id: "0bd2d3ba-1234-11d4-8f8f-aabbccddeeff".into(), - palette: None, - depth, - channels: vec![plane(1), plane(2), plane(3)], - alpha: alpha.then(|| plane(9)), - } - } - - /// #9318 review: a name the reader refuses (more than 65,536 UTF-16 units with its NUL) is - /// refused on write, so a saved library can't become a file that loads nothing. - #[test] - fn a_name_the_reader_refuses_is_refused_on_write() { - let long = PsdPattern { name: "a".repeat(65_536), ..pat(8, false) }; - assert!(matches!(write_pat_file(&[long]), Err(PsdError::LimitExceeded(_)))); - let longest = PsdPattern { name: "a".repeat(65_535), ..pat(8, false) }; - assert_eq!(parse_pat_file(&write_pat_file(std::slice::from_ref(&longest)).unwrap()).unwrap(), [longest]); - } - - /// #9318 review: more patterns than a `.pat` holds are refused on write, and a file claiming - /// more is refused on read rather than silently cut to the first 100,000. - #[test] - fn more_patterns_than_a_pat_file_holds_are_refused() { - let many = vec![pat(8, false); MAX_PAT_PATTERNS + 1]; - assert!(matches!(write_pat_file(&many), Err(PsdError::LimitExceeded(_)))); - let mut header = b"8BPT".to_vec(); - header.extend_from_slice(&1u16.to_be_bytes()); - header.extend_from_slice(&(MAX_PAT_PATTERNS as u32 + 1).to_be_bytes()); - assert!(matches!(parse_pat_file(&header), Err(PsdError::LimitExceeded(_)))); - } - - #[test] - fn block_and_pat_file_round_trip_at_every_depth() { - for depth in [8, 16, 32] { - for alpha in [false, true] { - let ps = vec![pat(depth, alpha), PsdPattern { name: "Second".into(), ..pat(depth, false) }]; - let blk = write_pattern_block(&ps).unwrap(); - assert_eq!(blk.len() % 4, 0); - assert_eq!(parse_pattern_block(&blk).unwrap(), ps); - let f = write_pat_file(&ps).unwrap(); - assert_eq!(parse_pat_file(&f).unwrap(), ps); - // Re-serialising is byte-stable. - assert_eq!(write_pattern_block(&parse_pattern_block(&blk).unwrap()).unwrap(), blk); - } - } - } - - /// Offsets of the virtual memory arrays of a one-pattern block (each at its "written" flag), - /// with whether each is written, and the end of the array list. - fn vma_slots(block: &[u8], p: &PsdPattern) -> (Vec<(usize, bool)>, usize) { - let rect = pattern_vma_rect_offset(4, p); - let end = rect + u32::from_be_bytes(block[rect - 4..rect].try_into().unwrap()) as usize; - let (mut at, mut slots) = (rect + 20, Vec::new()); - while at < end { - let written = u32::from_be_bytes(block[at..at + 4].try_into().unwrap()) != 0; - slots.push((at, written)); - at += 4; - if written { - at += 4 + u32::from_be_bytes(block[at..at + 4].try_into().unwrap()) as usize; - } - } - (slots, end) - } - - #[test] - fn transparency_goes_in_the_sheet_mask_array_like_photoshop() { - // #8054: transparency in the user mask array (slot 24) made Photoshop refuse the file; - // Photoshop keeps it in the sheet mask array (slot 25). - for depth in [8, 16, 32] { - let p = pat(depth, true); - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let (slots, end) = vma_slots(&block, &p); - let written: Vec = slots.iter().enumerate().filter(|(_, s)| s.1).map(|(i, _)| i).collect(); - assert_eq!((slots.len(), written), (26, vec![0, 1, 2, 25]), "{depth}-bit"); - assert!(!block_has_user_mask(&block)); - // The layout older PhotoCraft builds wrote still opens, and is detected. - block[slots[24].0..end].rotate_left(4); - let (slots, _) = vma_slots(&block, &p); - assert!(slots[24].1 && !slots[25].1); - assert!(block_has_user_mask(&block)); - assert_eq!(parse_pattern_block(&block).unwrap(), vec![p]); - } - assert!(!block_has_user_mask(&write_pattern_block(&[pat(8, false)]).unwrap())); - for junk in [&[][..], &[0, 0, 0, 9, 1], &[0xff; 64]] { - assert!(!block_has_user_mask(junk)); - } - } - - #[test] - fn malformed_input_errors_without_panicking() { - let blk = write_pattern_block(&[pat(8, true)]).unwrap(); - for cut in [3, 10, 40, blk.len() - 5] { - let _ = parse_pattern_block(&blk[..cut]); - } - assert!(parse_pat_file(b"8BPS\0\x01").is_err()); - assert!(parse_pattern_block(&[]).unwrap().is_empty()); - } - - fn pattern_vma_rect_offset(pattern_start: usize, p: &PsdPattern) -> usize { - let name_units = p.name.encode_utf16().count() + 1; - pattern_start + 16 + name_units * 2 + 1 + p.id.len() + if p.mode == 2 { 768 } else { 0 } + 8 - } - - fn set_i32(bytes: &mut [u8], offset: usize, value: i32) { - bytes[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); - } - - #[test] - fn hostile_pattern_rectangles_are_rejected_through_all_import_routes() { - let p = pat(8, false); - - // A subtraction of the hostile endpoints overflowed before rectangle validation. - let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut global, vma + 4, i32::MIN); - set_i32(&mut global, vma + 12, i32::MAX); - assert!(parse_pattern_block(&global).is_err()); - - let mut standalone = write_pat_file(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(10, &p); - set_i32(&mut standalone, vma + 4, i32::MIN); - set_i32(&mut standalone, vma + 12, i32::MAX); - assert!(parse_pat_file(&standalone).is_err()); - - let mut abr = crate::abr::write_v6( - 1, - &[crate::abr::AbrSample { id: String::new(), width: 1, height: 1, depth: 8, data: vec![0] }], - std::slice::from_ref(&p), - &[], - true, - ) - .unwrap(); - let section = abr.windows(4).position(|w| w == b"patt").unwrap(); - let vma = pattern_vma_rect_offset(section + 8, &p) + 4; - set_i32(&mut abr, vma + 4, i32::MIN); - set_i32(&mut abr, vma + 12, i32::MAX); - let parsed = crate::abr::parse(&abr).unwrap(); - assert!(parsed.patterns.is_empty()); - assert!(parsed.warnings.iter().any(|warning| warning.contains("embedded patterns unreadable"))); - } - - #[test] - fn huge_pattern_rect_with_tiny_channel_payload_is_rejected() { - // RGB32 needs 10.8 GB; CMYK16 plus alpha needs 9 GB. Both exceed the - // existing pattern budget, but their first plane fits on 64-bit targets. - // The complete metadata must be checked before allocating that first plane. - huge_pattern_rect_is_rejected(pat(32, false)); - let mut cmyk = pat(16, true); - cmyk.mode = 4; - cmyk.channels.push(vec![0; 5 * 3 * 2]); - huge_pattern_rect_is_rejected(cmyk); - } - - fn huge_pattern_rect_is_rejected(p: PsdPattern) { - let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut global, vma + 8, 30_000); - set_i32(&mut global, vma + 12, 30_000); - assert!(matches!(parse_pattern_block(&global), Err(PsdError::LimitExceeded(_)))); - - let mut standalone = write_pat_file(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(10, &p); - set_i32(&mut standalone, vma + 8, 30_000); - set_i32(&mut standalone, vma + 12, 30_000); - assert!(matches!(parse_pat_file(&standalone), Err(PsdError::LimitExceeded(_)))); - - let mut abr = crate::abr::write_v6( - 1, - &[crate::abr::AbrSample { id: String::new(), width: 1, height: 1, depth: 8, data: vec![0] }], - std::slice::from_ref(&p), - &[], - true, - ) - .unwrap(); - let section = abr.windows(4).position(|w| w == b"patt").unwrap(); - let vma = pattern_vma_rect_offset(section + 8, &p) + 4; - set_i32(&mut abr, vma + 8, 30_000); - set_i32(&mut abr, vma + 12, 30_000); - let parsed = crate::abr::parse(&abr).unwrap(); - assert!(parsed.patterns.is_empty()); - assert!(parsed.warnings.iter().any(|warning| warning.contains("embedded patterns unreadable"))); - } - - #[test] - fn offset_channel_rectangles_are_placed_inside_the_pattern() { - for depth in [8, 16, 32] { - let original = pat(depth, true); - let mut block = write_pattern_block(std::slice::from_ref(&original)).unwrap(); - let vma = pattern_vma_rect_offset(4, &original); - set_i32(&mut block, vma, -2); - set_i32(&mut block, vma + 4, -3); - set_i32(&mut block, vma + 8, 4); - set_i32(&mut block, vma + 12, 5); - - let parsed = parse_pattern_block(&block).unwrap(); - let parsed = parsed.first().unwrap(); - assert_eq!((parsed.width, parsed.height), (8, 6)); - let bytes_per_sample = usize::from(depth / 8); - for (actual, expected) in parsed.channels.iter().zip(&original.channels).chain(parsed.alpha.iter().zip(original.alpha.iter())) { - for y in 0..6usize { - for x in 0..8usize { - let at = (y * 8 + x) * bytes_per_sample; - let actual_sample = actual.get(at..at + bytes_per_sample).unwrap(); - if (2..5).contains(&y) && (3..8).contains(&x) { - let source_at = ((y - 2) * 5 + (x - 3)) * bytes_per_sample; - assert_eq!(actual_sample, expected.get(source_at..source_at + bytes_per_sample).unwrap()); - } else { - assert!(actual_sample.iter().all(|&sample| sample == 0)); - } - } - } - } - } - } - - #[test] - fn one_bit_offset_channel_placement_preserves_msb_first_pixels() { - let source = PlaneLayout { planes: 1, width: 5, height: 2, depth: 1, version: Version::Psd }; - let destination = PlaneLayout { planes: 1, width: 8, height: 4, depth: 1, version: Version::Psd }; - let placed = place_channel_plane(vec![0b1010_1000, 0b0101_0000], &source, 2, 1, &destination).unwrap(); - assert_eq!(placed, [0, 0b0010_1010, 0b0001_0100, 0]); - } - - #[test] - fn full_size_channels_reuse_the_decoded_allocation() { - for depth in [1, 8, 16, 32] { - let layout = PlaneLayout { planes: 1, width: 5, height: 3, depth, version: Version::Psd }; - let plane = vec![0x55; layout.decoded_len().unwrap()]; - let original = plane.as_ptr(); - let placed = place_channel_plane(plane, &layout, 0, 0, &layout).unwrap(); - assert_eq!(placed.as_ptr(), original); - let expected = if depth == 1 { 0x50 } else { 0x55 }; - assert!(placed.iter().all(|&byte| byte == expected)); - } - } - - #[test] - fn large_channel_padding_within_the_existing_budget_is_allowed() { - let mut p = pat(8, false); - p.mode = 1; - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - // More than 64 MiB of implicit padding is valid: the fix must not introduce - // a smaller, padding-specific format limit to avoid the oversized RGB case. - set_i32(&mut block, vma + 8, 8193); - set_i32(&mut block, vma + 12, 8193); - let parsed = parse_pattern_block(&block).unwrap(); - let plane = &parsed[0].channels[0]; - assert_eq!(plane.len(), 8193 * 8193); - for y in 0..3 { - assert_eq!(&plane[y * 8193..y * 8193 + 5], &p.channels[0][y * 5..y * 5 + 5]); - } - assert_eq!(plane[5], 0); - assert_eq!(plane[plane.len() - 1], 0); - } - - #[test] - fn padded_plane_allocation_failure_is_an_error() { - // Capacity overflow is deterministic and never asks the OS for huge memory. - assert!(matches!(zeroed_pattern_plane(usize::MAX), Err(PsdError::LimitExceeded("not enough memory for the padded pattern channel")))); - } - - #[test] - fn tiny_channels_in_a_huge_pattern_rect_are_not_zero_padded_without_bound() { - // 3 channels of 5x3 padded to 30000x30000 would allocate 2.7 GB of zeros. - let p = pat(8, false); - let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut global, vma + 8, 30_000); - set_i32(&mut global, vma + 12, 30_000); - assert!(matches!(parse_pattern_block(&global), Err(PsdError::LimitExceeded("padded pattern channels exceed MAX_PADDED_PATTERN_BYTES")))); - } - - /// A one-channel gray pattern whose 5x3 channel is padded into a `size`x`size` rectangle. - fn padded_gray_block(size: i32) -> Vec { - let mut p = pat(8, false); - p.mode = 1; - p.channels.truncate(1); - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut block, vma + 8, size); - set_i32(&mut block, vma + 12, size); - block - } - - #[test] - fn failed_pattern_block_keeps_partial_charge_for_the_next_block() { - let one = padded_gray_block(100); - let mut malformed = one.clone(); - malformed.extend_from_slice(&100u32.to_be_bytes()); - let mut budget = PatternBudget::with_decoded_limit(15_000); - assert!(parse_pattern_block_with(&malformed, &mut budget).is_err()); - assert_eq!(budget.decoded_left(), 5_000); - assert!(parse_pattern_block_with(&one, &mut budget).is_err()); - assert_eq!(budget.decoded_left(), 5_000); - } - - #[test] - fn padding_budget_is_shared_by_every_pattern_of_a_parse() { - // Each pattern pads 100x100 = 10000 bytes; a 15000-byte budget fits one, not two. Before - // the fix each pattern got a fresh allowance, so N tiny patterns committed N times the cap. - let one = padded_gray_block(100); - let mut budget = PatternBudget::with_decoded_limit(15_000); - assert_eq!(parse_pattern_block_with(&one, &mut budget).unwrap().len(), 1); - assert_eq!(budget.decoded_left(), 5_000); - - let two = [one.clone(), one.clone()].concat(); - let mut budget = PatternBudget::with_decoded_limit(15_000); - assert!(matches!(parse_pattern_block_with(&two, &mut budget), Err(PsdError::LimitExceeded(_)))); - // Charges are monotonic: the first pattern's 10000 bytes stay charged even when the second - // record fails. - assert_eq!(budget.decoded_left(), 5_000); - - // Two blocks of one document share a budget too. - let mut budget = PatternBudget::with_decoded_limit(15_000); - assert!(parse_pattern_block_with(&one, &mut budget).is_ok()); - assert!(parse_pattern_block_with(&one, &mut budget).is_err()); - } - - #[test] - fn channels_at_different_depths_are_rejected() { - // The second colour channel claims 8 bits in a 16-bit pattern. It used to be accepted with - // the pattern's depth taken from the last channel, so the result couldn't be written back. - let p = pat(16, false); - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let first = pattern_vma_rect_offset(4, &p) + 20; - let first_len = u32::from_be_bytes(block[first + 4..first + 8].try_into().unwrap()) as usize; - let second = first + 8 + first_len; - block[second + 8..second + 12].copy_from_slice(&8u32.to_be_bytes()); - block[second + 28..second + 30].copy_from_slice(&8u16.to_be_bytes()); - let err = parse_pattern_block(&block).unwrap_err().to_string(); - assert!(err.contains("different depths"), "{err}"); - } - - #[test] - fn zero_size_pattern_rectangles_are_rejected() { - let p = pat(8, false); - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut block, vma + 8, 0); - assert!(parse_pattern_block(&block).is_err()); - } -} +mod tests; diff --git a/crates/psd/src/patterns/tests.rs b/crates/psd/src/patterns/tests.rs new file mode 100644 index 0000000000..c66c8189d4 --- /dev/null +++ b/crates/psd/src/patterns/tests.rs @@ -0,0 +1,352 @@ +use super::*; + +fn pat(depth: u16, alpha: bool) -> PsdPattern { + let (w, h) = (5u32, 3u32); + let bpp = usize::from(depth / 8); + let plane = |s: u8| (0..w as usize * h as usize * bpp).map(|i| (i as u8).wrapping_mul(7).wrapping_add(s)).collect::>(); + PsdPattern { + mode: 3, + width: w, + height: h, + name: "Test ✓".into(), + id: "0bd2d3ba-1234-11d4-8f8f-aabbccddeeff".into(), + palette: None, + depth, + channels: vec![plane(1), plane(2), plane(3)], + alpha: alpha.then(|| plane(9)), + } +} + +/// #9318 review: a name the reader refuses (more than 65,536 UTF-16 units with its NUL) is +/// refused on write, so a saved library can't become a file that loads nothing. +#[test] +fn a_name_the_reader_refuses_is_refused_on_write() { + let long = PsdPattern { name: "a".repeat(65_536), ..pat(8, false) }; + assert!(matches!(write_pat_file(&[long]), Err(PsdError::LimitExceeded(_)))); + let longest = PsdPattern { name: "a".repeat(65_535), ..pat(8, false) }; + assert_eq!(parse_pat_file(&write_pat_file(std::slice::from_ref(&longest)).unwrap()).unwrap(), [longest]); +} + +/// #9318 review: more patterns than a `.pat` holds are refused on write, and a file claiming +/// more is refused on read rather than silently cut to the first 100,000. +#[test] +fn more_patterns_than_a_pat_file_holds_are_refused() { + let many = vec![pat(8, false); MAX_PAT_PATTERNS + 1]; + assert!(matches!(write_pat_file(&many), Err(PsdError::LimitExceeded(_)))); + let mut header = b"8BPT".to_vec(); + header.extend_from_slice(&1u16.to_be_bytes()); + header.extend_from_slice(&(MAX_PAT_PATTERNS as u32 + 1).to_be_bytes()); + assert!(matches!(parse_pat_file(&header), Err(PsdError::LimitExceeded(_)))); +} + +#[test] +fn block_and_pat_file_round_trip_at_every_depth() { + for depth in [8, 16, 32] { + for alpha in [false, true] { + let ps = vec![pat(depth, alpha), PsdPattern { name: "Second".into(), ..pat(depth, false) }]; + let blk = write_pattern_block(&ps).unwrap(); + assert_eq!(blk.len() % 4, 0); + assert_eq!(parse_pattern_block(&blk).unwrap(), ps); + let f = write_pat_file(&ps).unwrap(); + assert_eq!(parse_pat_file(&f).unwrap(), ps); + // Re-serialising is byte-stable. + assert_eq!(write_pattern_block(&parse_pattern_block(&blk).unwrap()).unwrap(), blk); + } + } +} + +/// Offsets of the virtual memory arrays of a one-pattern block (each at its "written" flag), +/// with whether each is written, and the end of the array list. +fn vma_slots(block: &[u8], p: &PsdPattern) -> (Vec<(usize, bool)>, usize) { + let rect = pattern_vma_rect_offset(4, p); + let end = rect + u32::from_be_bytes(block[rect - 4..rect].try_into().unwrap()) as usize; + let (mut at, mut slots) = (rect + 20, Vec::new()); + while at < end { + let written = u32::from_be_bytes(block[at..at + 4].try_into().unwrap()) != 0; + slots.push((at, written)); + at += 4; + if written { + at += 4 + u32::from_be_bytes(block[at..at + 4].try_into().unwrap()) as usize; + } + } + (slots, end) +} + +#[test] +fn transparency_goes_in_the_sheet_mask_array_like_photoshop() { + // #8054: transparency in the user mask array (slot 24) made Photoshop refuse the file; + // Photoshop keeps it in the sheet mask array (slot 25). + for depth in [8, 16, 32] { + let p = pat(depth, true); + let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let (slots, end) = vma_slots(&block, &p); + let written: Vec = slots.iter().enumerate().filter(|(_, s)| s.1).map(|(i, _)| i).collect(); + assert_eq!((slots.len(), written), (26, vec![0, 1, 2, 25]), "{depth}-bit"); + assert!(!block_has_user_mask(&block)); + // The layout older PhotoCraft builds wrote still opens, and is detected. + block[slots[24].0..end].rotate_left(4); + let (slots, _) = vma_slots(&block, &p); + assert!(slots[24].1 && !slots[25].1); + assert!(block_has_user_mask(&block)); + assert_eq!(parse_pattern_block(&block).unwrap(), vec![p]); + } + assert!(!block_has_user_mask(&write_pattern_block(&[pat(8, false)]).unwrap())); + for junk in [&[][..], &[0, 0, 0, 9, 1], &[0xff; 64]] { + assert!(!block_has_user_mask(junk)); + } +} + +#[test] +fn malformed_input_errors_without_panicking() { + let blk = write_pattern_block(&[pat(8, true)]).unwrap(); + for cut in [3, 10, 40, blk.len() - 5] { + let _ = parse_pattern_block(&blk[..cut]); + } + assert!(parse_pat_file(b"8BPS\0\x01").is_err()); + assert!(parse_pattern_block(&[]).unwrap().is_empty()); +} + +fn pattern_vma_rect_offset(pattern_start: usize, p: &PsdPattern) -> usize { + let name_units = p.name.encode_utf16().count() + 1; + pattern_start + 16 + name_units * 2 + 1 + p.id.len() + if p.mode == 2 { 768 } else { 0 } + 8 +} + +fn set_i32(bytes: &mut [u8], offset: usize, value: i32) { + bytes[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); +} + +#[test] +fn hostile_pattern_rectangles_are_rejected_through_all_import_routes() { + let p = pat(8, false); + + // A subtraction of the hostile endpoints overflowed before rectangle validation. + let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(4, &p); + set_i32(&mut global, vma + 4, i32::MIN); + set_i32(&mut global, vma + 12, i32::MAX); + assert!(parse_pattern_block(&global).is_err()); + + let mut standalone = write_pat_file(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(10, &p); + set_i32(&mut standalone, vma + 4, i32::MIN); + set_i32(&mut standalone, vma + 12, i32::MAX); + assert!(parse_pat_file(&standalone).is_err()); + + let mut abr = crate::abr::write_v6( + 1, + &[crate::abr::AbrSample { id: String::new(), width: 1, height: 1, depth: 8, data: vec![0] }], + std::slice::from_ref(&p), + &[], + true, + ) + .unwrap(); + let section = abr.windows(4).position(|w| w == b"patt").unwrap(); + let vma = pattern_vma_rect_offset(section + 8, &p) + 4; + set_i32(&mut abr, vma + 4, i32::MIN); + set_i32(&mut abr, vma + 12, i32::MAX); + let parsed = crate::abr::parse(&abr).unwrap(); + assert!(parsed.patterns.is_empty()); + assert!(parsed.warnings.iter().any(|warning| warning.contains("embedded patterns unreadable"))); +} + +#[test] +fn huge_pattern_rect_with_tiny_channel_payload_is_rejected() { + // RGB32 needs 10.8 GB; CMYK16 plus alpha needs 9 GB. Both exceed the + // existing pattern budget, but their first plane fits on 64-bit targets. + // The complete metadata must be checked before allocating that first plane. + huge_pattern_rect_is_rejected(pat(32, false)); + let mut cmyk = pat(16, true); + cmyk.mode = 4; + cmyk.channels.push(vec![0; 5 * 3 * 2]); + huge_pattern_rect_is_rejected(cmyk); +} + +fn huge_pattern_rect_is_rejected(p: PsdPattern) { + let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(4, &p); + set_i32(&mut global, vma + 8, 30_000); + set_i32(&mut global, vma + 12, 30_000); + assert!(matches!(parse_pattern_block(&global), Err(PsdError::LimitExceeded(_)))); + + let mut standalone = write_pat_file(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(10, &p); + set_i32(&mut standalone, vma + 8, 30_000); + set_i32(&mut standalone, vma + 12, 30_000); + assert!(matches!(parse_pat_file(&standalone), Err(PsdError::LimitExceeded(_)))); + + let mut abr = crate::abr::write_v6( + 1, + &[crate::abr::AbrSample { id: String::new(), width: 1, height: 1, depth: 8, data: vec![0] }], + std::slice::from_ref(&p), + &[], + true, + ) + .unwrap(); + let section = abr.windows(4).position(|w| w == b"patt").unwrap(); + let vma = pattern_vma_rect_offset(section + 8, &p) + 4; + set_i32(&mut abr, vma + 8, 30_000); + set_i32(&mut abr, vma + 12, 30_000); + let parsed = crate::abr::parse(&abr).unwrap(); + assert!(parsed.patterns.is_empty()); + assert!(parsed.warnings.iter().any(|warning| warning.contains("embedded patterns unreadable"))); +} + +#[test] +fn offset_channel_rectangles_are_placed_inside_the_pattern() { + for depth in [8, 16, 32] { + let original = pat(depth, true); + let mut block = write_pattern_block(std::slice::from_ref(&original)).unwrap(); + let vma = pattern_vma_rect_offset(4, &original); + set_i32(&mut block, vma, -2); + set_i32(&mut block, vma + 4, -3); + set_i32(&mut block, vma + 8, 4); + set_i32(&mut block, vma + 12, 5); + + let parsed = parse_pattern_block(&block).unwrap(); + let parsed = parsed.first().unwrap(); + assert_eq!((parsed.width, parsed.height), (8, 6)); + let bytes_per_sample = usize::from(depth / 8); + for (actual, expected) in parsed.channels.iter().zip(&original.channels).chain(parsed.alpha.iter().zip(original.alpha.iter())) { + for y in 0..6usize { + for x in 0..8usize { + let at = (y * 8 + x) * bytes_per_sample; + let actual_sample = actual.get(at..at + bytes_per_sample).unwrap(); + if (2..5).contains(&y) && (3..8).contains(&x) { + let source_at = ((y - 2) * 5 + (x - 3)) * bytes_per_sample; + assert_eq!(actual_sample, expected.get(source_at..source_at + bytes_per_sample).unwrap()); + } else { + assert!(actual_sample.iter().all(|&sample| sample == 0)); + } + } + } + } + } +} + +#[test] +fn one_bit_offset_channel_placement_preserves_msb_first_pixels() { + let source = PlaneLayout { planes: 1, width: 5, height: 2, depth: 1, version: Version::Psd }; + let destination = PlaneLayout { planes: 1, width: 8, height: 4, depth: 1, version: Version::Psd }; + let placed = place_channel_plane(vec![0b1010_1000, 0b0101_0000], &source, 2, 1, &destination).unwrap(); + assert_eq!(placed, [0, 0b0010_1010, 0b0001_0100, 0]); +} + +#[test] +fn full_size_channels_reuse_the_decoded_allocation() { + for depth in [1, 8, 16, 32] { + let layout = PlaneLayout { planes: 1, width: 5, height: 3, depth, version: Version::Psd }; + let plane = vec![0x55; layout.decoded_len().unwrap()]; + let original = plane.as_ptr(); + let placed = place_channel_plane(plane, &layout, 0, 0, &layout).unwrap(); + assert_eq!(placed.as_ptr(), original); + let expected = if depth == 1 { 0x50 } else { 0x55 }; + assert!(placed.iter().all(|&byte| byte == expected)); + } +} + +#[test] +fn large_channel_padding_within_the_existing_budget_is_allowed() { + let mut p = pat(8, false); + p.mode = 1; + let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(4, &p); + // More than 64 MiB of implicit padding is valid: the fix must not introduce + // a smaller, padding-specific format limit to avoid the oversized RGB case. + set_i32(&mut block, vma + 8, 8193); + set_i32(&mut block, vma + 12, 8193); + let parsed = parse_pattern_block(&block).unwrap(); + let plane = &parsed[0].channels[0]; + assert_eq!(plane.len(), 8193 * 8193); + for y in 0..3 { + assert_eq!(&plane[y * 8193..y * 8193 + 5], &p.channels[0][y * 5..y * 5 + 5]); + } + assert_eq!(plane[5], 0); + assert_eq!(plane[plane.len() - 1], 0); +} + +#[test] +fn padded_plane_allocation_failure_is_an_error() { + // Capacity overflow is deterministic and never asks the OS for huge memory. + assert!(matches!(zeroed_pattern_plane(usize::MAX), Err(PsdError::LimitExceeded("not enough memory for the padded pattern channel")))); +} + +#[test] +fn tiny_channels_in_a_huge_pattern_rect_are_not_zero_padded_without_bound() { + // 3 channels of 5x3 padded to 30000x30000 would allocate 2.7 GB of zeros. + let p = pat(8, false); + let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(4, &p); + set_i32(&mut global, vma + 8, 30_000); + set_i32(&mut global, vma + 12, 30_000); + assert!(matches!(parse_pattern_block(&global), Err(PsdError::LimitExceeded("padded pattern channels exceed MAX_PADDED_PATTERN_BYTES")))); +} + +/// A one-channel gray pattern whose 5x3 channel is padded into a `size`x`size` rectangle. +fn padded_gray_block(size: i32) -> Vec { + let mut p = pat(8, false); + p.mode = 1; + p.channels.truncate(1); + let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(4, &p); + set_i32(&mut block, vma + 8, size); + set_i32(&mut block, vma + 12, size); + block +} + +#[test] +fn failed_pattern_block_keeps_partial_charge_for_the_next_block() { + let one = padded_gray_block(100); + let mut malformed = one.clone(); + malformed.extend_from_slice(&100u32.to_be_bytes()); + let mut budget = PatternBudget::with_decoded_limit(15_000); + assert!(parse_pattern_block_with(&malformed, &mut budget).is_err()); + assert_eq!(budget.decoded_left(), 5_000); + assert!(parse_pattern_block_with(&one, &mut budget).is_err()); + assert_eq!(budget.decoded_left(), 5_000); +} + +#[test] +fn padding_budget_is_shared_by_every_pattern_of_a_parse() { + // Each pattern pads 100x100 = 10000 bytes; a 15000-byte budget fits one, not two. Before + // the fix each pattern got a fresh allowance, so N tiny patterns committed N times the cap. + let one = padded_gray_block(100); + let mut budget = PatternBudget::with_decoded_limit(15_000); + assert_eq!(parse_pattern_block_with(&one, &mut budget).unwrap().len(), 1); + assert_eq!(budget.decoded_left(), 5_000); + + let two = [one.clone(), one.clone()].concat(); + let mut budget = PatternBudget::with_decoded_limit(15_000); + assert!(matches!(parse_pattern_block_with(&two, &mut budget), Err(PsdError::LimitExceeded(_)))); + // Charges are monotonic: the first pattern's 10000 bytes stay charged even when the second + // record fails. + assert_eq!(budget.decoded_left(), 5_000); + + // Two blocks of one document share a budget too. + let mut budget = PatternBudget::with_decoded_limit(15_000); + assert!(parse_pattern_block_with(&one, &mut budget).is_ok()); + assert!(parse_pattern_block_with(&one, &mut budget).is_err()); +} + +#[test] +fn channels_at_different_depths_are_rejected() { + // The second colour channel claims 8 bits in a 16-bit pattern. It used to be accepted with + // the pattern's depth taken from the last channel, so the result couldn't be written back. + let p = pat(16, false); + let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let first = pattern_vma_rect_offset(4, &p) + 20; + let first_len = u32::from_be_bytes(block[first + 4..first + 8].try_into().unwrap()) as usize; + let second = first + 8 + first_len; + block[second + 8..second + 12].copy_from_slice(&8u32.to_be_bytes()); + block[second + 28..second + 30].copy_from_slice(&8u16.to_be_bytes()); + let err = parse_pattern_block(&block).unwrap_err().to_string(); + assert!(err.contains("different depths"), "{err}"); +} + +#[test] +fn zero_size_pattern_rectangles_are_rejected() { + let p = pat(8, false); + let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); + let vma = pattern_vma_rect_offset(4, &p); + set_i32(&mut block, vma + 8, 0); + assert!(parse_pattern_block(&block).is_err()); +} From a83bd683c2eda3b390663f1eca586c0f2704ae56 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:02 +0000 Subject: [PATCH 014/259] refactor(algo): move transform.rs tests to transform/tests.rs --- crates/algo/src/transform.rs | 351 +---------------------------- crates/algo/src/transform/tests.rs | 344 ++++++++++++++++++++++++++++ 2 files changed, 345 insertions(+), 350 deletions(-) create mode 100644 crates/algo/src/transform/tests.rs diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs index 3edd0a1879..1ed0ec7c04 100644 --- a/crates/algo/src/transform.rs +++ b/crates/algo/src/transform.rs @@ -551,353 +551,4 @@ fn warp( } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn output_size_prices_the_unclipped_extent_independently_of_position() { - let src = Rect::new(0, 0, 24, 16); - for dx in [0.0, 900_000.0, 10_000_000.0] { - let h = Homography([1.0, 0.0, dx, 0.0, 1.0, -dx, 0.0, 0.0, 1.0]); - assert_eq!(warp_output_size(src, &h), Some((26, 18))); - } - for sx in [1e7, -1e7] { - let h = Homography([sx, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); - assert_eq!(warp_output_size(src, &h), Some((240_000_002, 18))); - } - } - - /// The unclipped size matches the clipped bounds where nothing is clipped, saturates when it - /// can't be represented, and is `None` for empty or singular inputs. - #[test] - fn output_size_saturates_overflows_and_preserves_filter_support() { - let src = Rect::new(0, 0, 24, 16); - let fractional = Homography([0.5, 0.0, 0.25, 0.0, 1.0, 0.75, 0.0, 0.0, 1.0]); - let bounds = warp_output_bounds(src, &fractional).unwrap(); - assert_eq!(warp_output_size(src, &fractional), Some((u64::from(bounds.width()), u64::from(bounds.height())))); - let huge = Homography([1e308, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); - assert_eq!(warp_output_size(src, &huge), Some((u64::MAX, u64::MAX))); - assert_eq!(warp_output_size(Rect::EMPTY, &Homography::IDENTITY), None); - assert_eq!(warp_output_size(src, &Homography([0.0; 9])), None); - } - - /// [`warp_output_clipped`] says yes exactly when [`warp_output_bounds`] clamps a side (#7807). - #[test] - fn output_clipped_matches_the_clamped_bounds() { - let src = Rect::new(0, 0, 24, 16); - let at = |dx: f64| Homography([1.0, 0.0, dx, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); - let edge = f64::from(WARP_REACH) - 24.0; - assert!(!warp_output_clipped(src, &at(edge)), "the right edge lands on the reach"); - assert_eq!(warp_output_bounds(src, &at(edge)).map(|b| b.x1), Some(WARP_REACH + 1)); - assert!(warp_output_clipped(src, &at(edge + 1.0)), "one pixel past it"); - assert_eq!(warp_output_bounds(src, &at(edge + 1.0)).map(|b| b.x1), Some(WARP_REACH + 1), "clamped"); - assert!(warp_output_clipped(src, &at(-f64::from(WARP_REACH) - 1.0))); - assert!(!warp_output_clipped(Rect::EMPTY, &at(1e12)), "nothing to clip"); - } - - #[test] - fn the_interruptible_warp_reports_progress_and_stops_when_cancelled() { - let mut s = Surface::new(PixelFormat::RGBA8); - s.fill_rect(Rect::new(0, 0, 600, 400), &[0.2, 0.4, 0.6, 1.0]); - let r = s.content_bounds(); - let h = Homography::rect_to_quad([0.0, 0.0, 600.0, 400.0], [[10.0, 0.0], [590.0, 20.0], [600.0, 400.0], [0.0, 380.0]]).unwrap(); - let reported = std::sync::Mutex::new(0.0f32); - let progress = |p: f32| { - let mut m = reported.lock().unwrap(); - *m = m.max(p); - }; - let never = || false; - let out = warp_surface_with(&s, r, &h, Interp::Bicubic, &Interrupt::new(&never, &progress)).unwrap().expect("not cancelled"); - assert_eq!(out.read_region(r), warp_surface(&s, r, &h, Interp::Bicubic).unwrap().read_region(r)); - assert!(*reported.lock().unwrap() > 0.9); - let always = || true; - assert!(warp_surface_with(&s, r, &h, Interp::Bicubic, &Interrupt::cancel_only(&always)).unwrap().is_none()); - } - - /// Perspective Crop's map lands each quad corner exactly on its rectangle corner; degenerate, - /// self-crossing, counter-clockwise and non-finite quads have none. - #[test] - fn quad_to_rect_maps_corners_and_refuses_bad_quads() { - let q = [[30.0, 12.0], [140.0, 25.0], [128.0, 110.0], [14.0, 95.0]]; - let h = quad_to_rect(&q, 100.0, 80.0).unwrap(); - for (c, want) in q.iter().zip([[0.0, 0.0], [100.0, 0.0], [100.0, 80.0], [0.0, 80.0]]) { - let (x, y) = h.apply(c[0], c[1]); - assert!((x - want[0]).abs() < 1e-9 && (y - want[1]).abs() < 1e-9, "{c:?} -> ({x}, {y})"); - } - let (w, ht) = quad_size(&q); - assert!((w - 112.874).abs() < 1e-3 && (ht - 85.185).abs() < 1e-3, "{w} x {ht}"); - for bad in [ - [[0.0, 0.0], [50.0, 0.0], [100.0, 0.0], [0.0, 50.0]], - [[0.0, 0.0], [50.0, 50.0], [50.0, 0.0], [0.0, 50.0]], - [[0.0, 0.0], [0.0, 50.0], [50.0, 50.0], [50.0, 0.0]], - [[0.0, 0.0], [f64::NAN, 0.0], [50.0, 50.0], [0.0, 50.0]], - [[0.0, 0.0]; 4], - ] { - assert!(quad_to_rect(&bad, 10.0, 10.0).is_none(), "{bad:?}"); - } - assert!(quad_to_rect(&q, 0.0, 10.0).is_none()); - } - - fn rgba() -> Surface { - Surface::new(PixelFormat::RGBA8) - } - - /// The "pixel stretch" (#3773): a 1 px column scaled 100x stays solid across the stretch, as in - /// Photoshop. Samples past the source edge repeat the edge, and only the outline is antialiased. - #[test] - fn stretched_single_column_stays_opaque() { - let mut s = rgba(); - s.fill_rect(Rect::new(0, 0, 1, 4), &[0.0, 1.0, 0.0, 1.0]); - for interp in [Interp::Bicubic, Interp::Bilinear] { - let h = Homography::rect_to_quad([0.0, 0.0, 1.0, 4.0], [[0.0, 0.0], [100.0, 0.0], [100.0, 4.0], [0.0, 4.0]]).unwrap(); - let w = warp_surface(&s, Rect::new(0, 0, 1, 4), &h, interp).unwrap(); - assert_eq!(w.content_bounds(), Rect::new(0, 0, 100, 4), "{interp:?}"); - for x in [0, 1, 25, 50, 75, 99] { - for y in 0..4 { - assert!((w.sample_channel(x, y, 3) - 1.0).abs() < 1e-6, "{interp:?} alpha at ({x}, {y}) = {}", w.sample_channel(x, y, 3)); - } - } - } - } - - /// Photoshop 27.11's Free Transform, Bicubic, 200 % about the centre of a 64 px image whose left - /// half is grey 64 and right half grey 192: the row across the edge, columns 26..36. - #[test] - fn bicubic_upscale_matches_photoshop() { - let mut src = rgba(); - let g = |v: f32| v / 255.0; - src.fill_rect(Rect::new(0, 0, 32, 64), &[g(64.0), g(64.0), g(64.0), 1.0]); - src.fill_rect(Rect::new(32, 0, 64, 64), &[g(192.0), g(192.0), g(192.0), 1.0]); - let q = [[-32.0, -32.0], [96.0, -32.0], [96.0, 96.0], [-32.0, 96.0]]; - let h = Homography::rect_to_quad([0.0, 0.0, 64.0, 64.0], q).unwrap(); - let out = warp_surface(&src, Rect::new(0, 0, 64, 64), &h, Interp::Bicubic).unwrap(); - let photoshop = [64.0, 64.0, 64.0, 60.0, 51.0, 93.0, 163.0, 206.0, 197.0, 192.0]; - for (i, want) in photoshop.iter().enumerate() { - let got = out.pixel(26 + i as i32, 50)[0] * 255.0; - assert!((got - want).abs() <= 1.5, "column {}: {got} vs {want}", 26 + i); - } - } - - #[test] - fn homography_maps_rect_corners_and_inverts() { - let r = [10.0, 20.0, 110.0, 70.0]; - let q = [[0.0, 0.0], [200.0, 10.0], [180.0, 150.0], [-20.0, 120.0]]; - let h = Homography::rect_to_quad(r, q).unwrap(); - for (p, e) in [(10.0, 20.0), (110.0, 20.0), (110.0, 70.0), (10.0, 70.0)].iter().zip(q) { - let (x, y) = h.apply(p.0, p.1); - assert!((x - e[0]).abs() < 1e-9 && (y - e[1]).abs() < 1e-9, "{p:?} → {x},{y} vs {e:?}"); - } - let inv = h.inverse().unwrap(); - let (x, y) = inv.apply(90.0, 60.0); - let (bx, by) = h.apply(x, y); - assert!((bx - 90.0).abs() < 1e-9 && (by - 60.0).abs() < 1e-9); - assert!(Homography::rect_to_quad(r, [[0.0, 0.0]; 4]).is_none() || Homography::rect_to_quad(r, [[0.0, 0.0]; 4]).unwrap().inverse().is_none()); - } - - #[test] - fn steep_distort_keeps_every_pixel_inside_the_quad() { - // Corner C is almost flat, so the horizon of the inverse map crosses the 256-px tiles that - // also hold quad pixels; those tiles must still read every source pixel that lands in them. - let mut s = rgba(); - s.fill_rect(Rect::new(0, 0, 100, 100), &[1.0, 0.0, 0.0, 1.0]); - let r = s.content_bounds(); - let h = Homography::rect_to_quad([0.0, 0.0, 100.0, 100.0], [[0.0, 0.0], [300.0, 0.0], [155.0, 155.0], [0.0, 300.0]]).unwrap(); - let w = warp_surface(&s, r, &h, Interp::Nearest).unwrap(); - for (x, y) in [(20, 20), (252, 14), (252, 42), (14, 252), (42, 252)] { - let a = w.read_region(Rect::new(x, y, x + 1, y + 1))[3]; - assert!(a > 0.99, "({x},{y}) inside the quad is transparent: {a}"); - } - for (x, y) in [(200, 200), (280, 100), (100, 280)] { - assert_eq!(w.read_region(Rect::new(x, y, x + 1, y + 1))[3], 0.0, "({x},{y}) outside the quad is painted"); - } - } - - /// #4863: a Distort with the bottom corners pulled in and one dragged past the horizon (a - /// concave quad) leaves part of the source behind the horizon. That part maps to the far side, - /// where it showed as a mirrored copy wrapped round infinity; only the front side is drawn. - #[test] - fn a_distort_past_the_horizon_draws_only_its_front_side() { - let mut s = rgba(); - s.fill_rect(Rect::new(0, 0, 100, 100), &[0.0, 0.5, 1.0, 1.0]); - let r = s.content_bounds(); - let h = Homography::rect_to_quad([0.0, 0.0, 100.0, 100.0], [[0.0, 0.0], [300.0, 0.0], [60.0, 60.0], [0.0, 300.0]]).unwrap(); - let corners = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| h.w(x, y)); - assert!(corners.iter().any(|w| *w > 0.0) && corners.iter().any(|w| *w < 0.0), "the source straddles the horizon: {corners:?}"); - let front = h.front_side([0.0, 0.0, 100.0, 100.0]); - let inv = h.inverse().unwrap(); - let clip = Rect::new(-400, -400, 700, 700); - for interp in [Interp::Nearest, Interp::Bilinear] { - let w = warp_surface_clipped(&s, r, &h, interp, clip).unwrap(); - let px = w.read_region(clip); - let (mut drawn, mut behind) = (0, 0); - for y in clip.y0..clip.y1 { - for x in clip.x0..clip.x1 { - let i = ((y - clip.y0) * clip.width() as i32 + (x - clip.x0)) as usize * 4; - if px[i + 3] > 0.0 { - drawn += 1; - // The source point this pixel samples is on the far side of the horizon. - if front * inv.w(x as f64 + 0.5, y as f64 + 0.5) <= 0.0 { - behind += 1; - } - } - } - } - assert!(drawn > 1000, "{interp:?}: the front side is drawn ({drawn} px)"); - assert_eq!(behind, 0, "{interp:?}: {behind} pixels come from behind the horizon"); - } - // A quad wholly in front of the horizon is drawn exactly as before. - let ok = Homography::rect_to_quad([0.0, 0.0, 100.0, 100.0], [[0.0, 0.0], [300.0, 0.0], [155.0, 155.0], [0.0, 300.0]]).unwrap(); - assert_eq!(ok.front_side([0.0, 0.0, 100.0, 100.0]), ok.w(50.0, 50.0).signum()); - } - - /// #7557: a Perspective Crop quad low on a strongly converging photo puts the horizon across - /// the layer with most of it (and its centre) on the far side. The clip maps wholly into the - /// quad, so its side is the one drawn, not the source's majority. - #[test] - fn a_clip_wholly_on_one_side_draws_that_side() { - let mut s = rgba(); - s.fill_rect(Rect::new(0, 0, 100, 100), &[1.0, 0.0, 0.0, 1.0]); - let q = [[40.0, 70.0], [60.0, 70.0], [90.0, 95.0], [10.0, 95.0]]; - let h = quad_to_rect(&q, 50.0, 39.0).unwrap(); - assert!(h.front_side([0.0, 0.0, 100.0, 100.0]) * h.w(50.0, 80.0) < 0.0, "the source's majority is behind the quad's side"); - for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] { - let w = warp_surface_clipped(&s, s.content_bounds(), &h, interp, Rect::new(0, 0, 50, 39)).unwrap(); - assert_eq!(w.rgba(25, 20), [1.0, 0.0, 0.0, 1.0], "{interp:?}"); - } - } - - #[test] - fn identity_and_translation_are_exact() { - let mut s = rgba(); - s.fill_rect(Rect::new(4, 4, 20, 12), &[1.0, 0.5, 0.0, 1.0]); - let r = s.content_bounds(); - for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] { - let h = Homography([1.0, 0.0, 7.0, 0.0, 1.0, -3.0, 0.0, 0.0, 1.0]); - let o = warp_surface(&s, r, &h, interp).unwrap(); - assert_eq!(o.content_bounds(), Rect::new(11, 1, 27, 9), "{interp:?}"); - assert_eq!(o.pixel(15, 5), vec![1.0, 128.0 / 255.0, 0.0, 1.0], "{interp:?}"); - } - } - - #[test] - fn translation_preserves_colour_range_at_every_depth() { - use photocraft_color::{ColorMode, SampleType}; - - let h = Homography([1.0, 0.0, 7.0, 0.0, 1.0, -3.0, 0.0, 0.0, 1.0]); - for sample in SampleType::ALL { - for mode in [ColorMode::Rgb, ColorMode::Grayscale] { - for alpha in [false, true] { - let mut s = Surface::new(PixelFormat::new(mode, sample, alpha)); - let mut pixel = if mode == ColorMode::Rgb { vec![2.0, -0.25, 0.5] } else { vec![2.0] }; - if alpha { - pixel.push(0.5); - } - s.fill_rect(Rect::new(4, 4, 8, 8), &pixel); - let mut expected = s.pixel(5, 5); - if !alpha { - expected.push(1.0); - } - for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] { - let out = warp_surface(&s, s.content_bounds(), &h, interp).unwrap(); - assert_eq!(out.pixel(12, 2), expected, "{sample:?}/{mode:?}/alpha={alpha}/{interp:?}"); - assert_eq!(out.pixel(0, 0).last(), Some(&0.0)); - } - } - } - } - } - - #[test] - fn bilinear_translation_interpolates_signed_hdr_colours() { - let mut s = Surface::new(PixelFormat::RGBA32F); - s.write_pixel(0, 0, &[2.0, -0.5, 0.25, 0.5]); - s.write_pixel(1, 0, &[4.0, -0.25, 0.75, 0.5]); - let h = Homography([1.0, 0.0, 0.5, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); - let out = warp_surface(&s, s.content_bounds(), &h, Interp::Bilinear).unwrap(); - assert_eq!(out.pixel(1, 0), vec![3.0, -0.375, 0.5, 0.5]); - } - - #[test] - fn scale_doubles_size_and_rotation_keeps_area() { - let mut s = rgba(); - s.fill_rect(Rect::new(0, 0, 40, 20), &[0.2, 0.4, 0.6, 1.0]); - let r = s.content_bounds(); - let up = warp_surface( - &s, - r, - &Homography::rect_to_quad([0.0, 0.0, 40.0, 20.0], [[0.0, 0.0], [80.0, 0.0], [80.0, 40.0], [0.0, 40.0]]).unwrap(), - Interp::Bicubic, - ) - .unwrap(); - let b = up.content_bounds(); - assert!(b.width() >= 80 && b.width() <= 82 && b.height() >= 40 && b.height() <= 42, "{b:?}"); - // 90° rotation about (20, 10): a 40×20 box becomes 20×40. - let q = [[30.0, -10.0], [30.0, 30.0], [10.0, 30.0], [10.0, -10.0]]; - let rot = warp_surface(&s, r, &Homography::rect_to_quad([0.0, 0.0, 40.0, 20.0], q).unwrap(), Interp::Bilinear).unwrap(); - let b = rot.content_bounds(); - assert!(b.width().abs_diff(20) <= 2 && b.height().abs_diff(40) <= 2, "{b:?}"); - let p = rot.pixel(20, 10); - assert!((p[0] - 0.2).abs() < 0.01 && p[3] > 0.99, "{p:?}"); - } - - /// #6203: a bicubic rotation of a sprite whose edge pixels are partly transparent overshoots - /// its alpha past 1. The colour must stay the sprite's, not grow with the overshoot into a - /// light border. - #[test] - fn rotation_keeps_the_colour_of_a_soft_edged_sprite() { - let mut s = rgba(); - s.fill_rect(Rect::new(10, 10, 30, 30), &[0.8, 0.6, 0.4, 0.5]); - s.fill_rect(Rect::new(11, 11, 29, 29), &[0.8, 0.6, 0.4, 1.0]); - let (c, k) = (20.0, std::f64::consts::FRAC_1_SQRT_2 * 10.0); - let q = [[c, c - 2.0 * k], [c + 2.0 * k, c], [c, c + 2.0 * k], [c - 2.0 * k, c]]; - let h = Homography::rect_to_quad([10.0, 10.0, 30.0, 30.0], q).unwrap(); - for interp in [Interp::Bicubic, Interp::Bilinear] { - let out = warp_surface(&s, s.content_bounds(), &h, interp).unwrap(); - let b = out.content_bounds(); - for y in b.y0..b.y1 { - for x in b.x0..b.x1 { - let p = out.pixel(x, y); - if p[3] > 0.0 { - let off = (0..3).map(|i| (p[i] - [0.8, 0.6, 0.4][i]).abs()).fold(0.0f32, f32::max); - assert!(off <= 1.0 / 255.0, "{interp:?} ({x}, {y}): {p:?}"); - } - } - } - } - } - - #[test] - fn large_downscale_is_prefiltered() { - // A 1px checkerboard shrunk 8× must come out ~50% grey, not aliased black/white. - let mut s = rgba(); - for y in 0..64 { - for x in 0..64 { - let v = ((x + y) % 2) as f32; - s.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, v, v, 1.0]); - } - } - let h = Homography::rect_to_quad([0.0, 0.0, 64.0, 64.0], [[0.0, 0.0], [8.0, 0.0], [8.0, 8.0], [0.0, 8.0]]).unwrap(); - let o = warp_surface(&s, s.content_bounds(), &h, Interp::Bicubic).unwrap(); - let p = o.pixel(4, 4); - assert!((p[0] - 0.5).abs() < 0.1, "{p:?}"); - } - - #[test] - fn surfaces_without_alpha_gain_it() { - let mut s = Surface::new(PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, false)); - s.fill_rect(Rect::new(0, 0, 10, 10), &[1.0, 0.0, 0.0]); - let h = Homography([1.0, 0.0, 5.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); - let o = warp_surface(&s, Rect::new(0, 0, 10, 10), &h, Interp::Nearest).unwrap(); - assert!(o.format().alpha); - assert_eq!(o.pixel(2, 2)[3], 0.0); - assert_eq!(o.pixel(7, 2), vec![1.0, 0.0, 0.0, 1.0]); - } - - #[test] - fn homography_is_identity() { - assert!(Homography::IDENTITY.is_identity()); - assert!(Homography([2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 2.0]).is_identity()); - assert!(!Homography([1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).is_identity()); - assert!(!Homography([1.0, 0.1, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).is_identity()); - } -} +mod tests; diff --git a/crates/algo/src/transform/tests.rs b/crates/algo/src/transform/tests.rs new file mode 100644 index 0000000000..b70bc74c3d --- /dev/null +++ b/crates/algo/src/transform/tests.rs @@ -0,0 +1,344 @@ +use super::*; + +#[test] +fn output_size_prices_the_unclipped_extent_independently_of_position() { + let src = Rect::new(0, 0, 24, 16); + for dx in [0.0, 900_000.0, 10_000_000.0] { + let h = Homography([1.0, 0.0, dx, 0.0, 1.0, -dx, 0.0, 0.0, 1.0]); + assert_eq!(warp_output_size(src, &h), Some((26, 18))); + } + for sx in [1e7, -1e7] { + let h = Homography([sx, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + assert_eq!(warp_output_size(src, &h), Some((240_000_002, 18))); + } +} + +/// The unclipped size matches the clipped bounds where nothing is clipped, saturates when it +/// can't be represented, and is `None` for empty or singular inputs. +#[test] +fn output_size_saturates_overflows_and_preserves_filter_support() { + let src = Rect::new(0, 0, 24, 16); + let fractional = Homography([0.5, 0.0, 0.25, 0.0, 1.0, 0.75, 0.0, 0.0, 1.0]); + let bounds = warp_output_bounds(src, &fractional).unwrap(); + assert_eq!(warp_output_size(src, &fractional), Some((u64::from(bounds.width()), u64::from(bounds.height())))); + let huge = Homography([1e308, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + assert_eq!(warp_output_size(src, &huge), Some((u64::MAX, u64::MAX))); + assert_eq!(warp_output_size(Rect::EMPTY, &Homography::IDENTITY), None); + assert_eq!(warp_output_size(src, &Homography([0.0; 9])), None); +} + +/// [`warp_output_clipped`] says yes exactly when [`warp_output_bounds`] clamps a side (#7807). +#[test] +fn output_clipped_matches_the_clamped_bounds() { + let src = Rect::new(0, 0, 24, 16); + let at = |dx: f64| Homography([1.0, 0.0, dx, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + let edge = f64::from(WARP_REACH) - 24.0; + assert!(!warp_output_clipped(src, &at(edge)), "the right edge lands on the reach"); + assert_eq!(warp_output_bounds(src, &at(edge)).map(|b| b.x1), Some(WARP_REACH + 1)); + assert!(warp_output_clipped(src, &at(edge + 1.0)), "one pixel past it"); + assert_eq!(warp_output_bounds(src, &at(edge + 1.0)).map(|b| b.x1), Some(WARP_REACH + 1), "clamped"); + assert!(warp_output_clipped(src, &at(-f64::from(WARP_REACH) - 1.0))); + assert!(!warp_output_clipped(Rect::EMPTY, &at(1e12)), "nothing to clip"); +} + +#[test] +fn the_interruptible_warp_reports_progress_and_stops_when_cancelled() { + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(0, 0, 600, 400), &[0.2, 0.4, 0.6, 1.0]); + let r = s.content_bounds(); + let h = Homography::rect_to_quad([0.0, 0.0, 600.0, 400.0], [[10.0, 0.0], [590.0, 20.0], [600.0, 400.0], [0.0, 380.0]]).unwrap(); + let reported = std::sync::Mutex::new(0.0f32); + let progress = |p: f32| { + let mut m = reported.lock().unwrap(); + *m = m.max(p); + }; + let never = || false; + let out = warp_surface_with(&s, r, &h, Interp::Bicubic, &Interrupt::new(&never, &progress)).unwrap().expect("not cancelled"); + assert_eq!(out.read_region(r), warp_surface(&s, r, &h, Interp::Bicubic).unwrap().read_region(r)); + assert!(*reported.lock().unwrap() > 0.9); + let always = || true; + assert!(warp_surface_with(&s, r, &h, Interp::Bicubic, &Interrupt::cancel_only(&always)).unwrap().is_none()); +} + +/// Perspective Crop's map lands each quad corner exactly on its rectangle corner; degenerate, +/// self-crossing, counter-clockwise and non-finite quads have none. +#[test] +fn quad_to_rect_maps_corners_and_refuses_bad_quads() { + let q = [[30.0, 12.0], [140.0, 25.0], [128.0, 110.0], [14.0, 95.0]]; + let h = quad_to_rect(&q, 100.0, 80.0).unwrap(); + for (c, want) in q.iter().zip([[0.0, 0.0], [100.0, 0.0], [100.0, 80.0], [0.0, 80.0]]) { + let (x, y) = h.apply(c[0], c[1]); + assert!((x - want[0]).abs() < 1e-9 && (y - want[1]).abs() < 1e-9, "{c:?} -> ({x}, {y})"); + } + let (w, ht) = quad_size(&q); + assert!((w - 112.874).abs() < 1e-3 && (ht - 85.185).abs() < 1e-3, "{w} x {ht}"); + for bad in [ + [[0.0, 0.0], [50.0, 0.0], [100.0, 0.0], [0.0, 50.0]], + [[0.0, 0.0], [50.0, 50.0], [50.0, 0.0], [0.0, 50.0]], + [[0.0, 0.0], [0.0, 50.0], [50.0, 50.0], [50.0, 0.0]], + [[0.0, 0.0], [f64::NAN, 0.0], [50.0, 50.0], [0.0, 50.0]], + [[0.0, 0.0]; 4], + ] { + assert!(quad_to_rect(&bad, 10.0, 10.0).is_none(), "{bad:?}"); + } + assert!(quad_to_rect(&q, 0.0, 10.0).is_none()); +} + +fn rgba() -> Surface { + Surface::new(PixelFormat::RGBA8) +} + +/// The "pixel stretch" (#3773): a 1 px column scaled 100x stays solid across the stretch, as in +/// Photoshop. Samples past the source edge repeat the edge, and only the outline is antialiased. +#[test] +fn stretched_single_column_stays_opaque() { + let mut s = rgba(); + s.fill_rect(Rect::new(0, 0, 1, 4), &[0.0, 1.0, 0.0, 1.0]); + for interp in [Interp::Bicubic, Interp::Bilinear] { + let h = Homography::rect_to_quad([0.0, 0.0, 1.0, 4.0], [[0.0, 0.0], [100.0, 0.0], [100.0, 4.0], [0.0, 4.0]]).unwrap(); + let w = warp_surface(&s, Rect::new(0, 0, 1, 4), &h, interp).unwrap(); + assert_eq!(w.content_bounds(), Rect::new(0, 0, 100, 4), "{interp:?}"); + for x in [0, 1, 25, 50, 75, 99] { + for y in 0..4 { + assert!((w.sample_channel(x, y, 3) - 1.0).abs() < 1e-6, "{interp:?} alpha at ({x}, {y}) = {}", w.sample_channel(x, y, 3)); + } + } + } +} + +/// Photoshop 27.11's Free Transform, Bicubic, 200 % about the centre of a 64 px image whose left +/// half is grey 64 and right half grey 192: the row across the edge, columns 26..36. +#[test] +fn bicubic_upscale_matches_photoshop() { + let mut src = rgba(); + let g = |v: f32| v / 255.0; + src.fill_rect(Rect::new(0, 0, 32, 64), &[g(64.0), g(64.0), g(64.0), 1.0]); + src.fill_rect(Rect::new(32, 0, 64, 64), &[g(192.0), g(192.0), g(192.0), 1.0]); + let q = [[-32.0, -32.0], [96.0, -32.0], [96.0, 96.0], [-32.0, 96.0]]; + let h = Homography::rect_to_quad([0.0, 0.0, 64.0, 64.0], q).unwrap(); + let out = warp_surface(&src, Rect::new(0, 0, 64, 64), &h, Interp::Bicubic).unwrap(); + let photoshop = [64.0, 64.0, 64.0, 60.0, 51.0, 93.0, 163.0, 206.0, 197.0, 192.0]; + for (i, want) in photoshop.iter().enumerate() { + let got = out.pixel(26 + i as i32, 50)[0] * 255.0; + assert!((got - want).abs() <= 1.5, "column {}: {got} vs {want}", 26 + i); + } +} + +#[test] +fn homography_maps_rect_corners_and_inverts() { + let r = [10.0, 20.0, 110.0, 70.0]; + let q = [[0.0, 0.0], [200.0, 10.0], [180.0, 150.0], [-20.0, 120.0]]; + let h = Homography::rect_to_quad(r, q).unwrap(); + for (p, e) in [(10.0, 20.0), (110.0, 20.0), (110.0, 70.0), (10.0, 70.0)].iter().zip(q) { + let (x, y) = h.apply(p.0, p.1); + assert!((x - e[0]).abs() < 1e-9 && (y - e[1]).abs() < 1e-9, "{p:?} → {x},{y} vs {e:?}"); + } + let inv = h.inverse().unwrap(); + let (x, y) = inv.apply(90.0, 60.0); + let (bx, by) = h.apply(x, y); + assert!((bx - 90.0).abs() < 1e-9 && (by - 60.0).abs() < 1e-9); + assert!(Homography::rect_to_quad(r, [[0.0, 0.0]; 4]).is_none() || Homography::rect_to_quad(r, [[0.0, 0.0]; 4]).unwrap().inverse().is_none()); +} + +#[test] +fn steep_distort_keeps_every_pixel_inside_the_quad() { + // Corner C is almost flat, so the horizon of the inverse map crosses the 256-px tiles that + // also hold quad pixels; those tiles must still read every source pixel that lands in them. + let mut s = rgba(); + s.fill_rect(Rect::new(0, 0, 100, 100), &[1.0, 0.0, 0.0, 1.0]); + let r = s.content_bounds(); + let h = Homography::rect_to_quad([0.0, 0.0, 100.0, 100.0], [[0.0, 0.0], [300.0, 0.0], [155.0, 155.0], [0.0, 300.0]]).unwrap(); + let w = warp_surface(&s, r, &h, Interp::Nearest).unwrap(); + for (x, y) in [(20, 20), (252, 14), (252, 42), (14, 252), (42, 252)] { + let a = w.read_region(Rect::new(x, y, x + 1, y + 1))[3]; + assert!(a > 0.99, "({x},{y}) inside the quad is transparent: {a}"); + } + for (x, y) in [(200, 200), (280, 100), (100, 280)] { + assert_eq!(w.read_region(Rect::new(x, y, x + 1, y + 1))[3], 0.0, "({x},{y}) outside the quad is painted"); + } +} + +/// #4863: a Distort with the bottom corners pulled in and one dragged past the horizon (a +/// concave quad) leaves part of the source behind the horizon. That part maps to the far side, +/// where it showed as a mirrored copy wrapped round infinity; only the front side is drawn. +#[test] +fn a_distort_past_the_horizon_draws_only_its_front_side() { + let mut s = rgba(); + s.fill_rect(Rect::new(0, 0, 100, 100), &[0.0, 0.5, 1.0, 1.0]); + let r = s.content_bounds(); + let h = Homography::rect_to_quad([0.0, 0.0, 100.0, 100.0], [[0.0, 0.0], [300.0, 0.0], [60.0, 60.0], [0.0, 300.0]]).unwrap(); + let corners = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| h.w(x, y)); + assert!(corners.iter().any(|w| *w > 0.0) && corners.iter().any(|w| *w < 0.0), "the source straddles the horizon: {corners:?}"); + let front = h.front_side([0.0, 0.0, 100.0, 100.0]); + let inv = h.inverse().unwrap(); + let clip = Rect::new(-400, -400, 700, 700); + for interp in [Interp::Nearest, Interp::Bilinear] { + let w = warp_surface_clipped(&s, r, &h, interp, clip).unwrap(); + let px = w.read_region(clip); + let (mut drawn, mut behind) = (0, 0); + for y in clip.y0..clip.y1 { + for x in clip.x0..clip.x1 { + let i = ((y - clip.y0) * clip.width() as i32 + (x - clip.x0)) as usize * 4; + if px[i + 3] > 0.0 { + drawn += 1; + // The source point this pixel samples is on the far side of the horizon. + if front * inv.w(x as f64 + 0.5, y as f64 + 0.5) <= 0.0 { + behind += 1; + } + } + } + } + assert!(drawn > 1000, "{interp:?}: the front side is drawn ({drawn} px)"); + assert_eq!(behind, 0, "{interp:?}: {behind} pixels come from behind the horizon"); + } + // A quad wholly in front of the horizon is drawn exactly as before. + let ok = Homography::rect_to_quad([0.0, 0.0, 100.0, 100.0], [[0.0, 0.0], [300.0, 0.0], [155.0, 155.0], [0.0, 300.0]]).unwrap(); + assert_eq!(ok.front_side([0.0, 0.0, 100.0, 100.0]), ok.w(50.0, 50.0).signum()); +} + +/// #7557: a Perspective Crop quad low on a strongly converging photo puts the horizon across +/// the layer with most of it (and its centre) on the far side. The clip maps wholly into the +/// quad, so its side is the one drawn, not the source's majority. +#[test] +fn a_clip_wholly_on_one_side_draws_that_side() { + let mut s = rgba(); + s.fill_rect(Rect::new(0, 0, 100, 100), &[1.0, 0.0, 0.0, 1.0]); + let q = [[40.0, 70.0], [60.0, 70.0], [90.0, 95.0], [10.0, 95.0]]; + let h = quad_to_rect(&q, 50.0, 39.0).unwrap(); + assert!(h.front_side([0.0, 0.0, 100.0, 100.0]) * h.w(50.0, 80.0) < 0.0, "the source's majority is behind the quad's side"); + for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] { + let w = warp_surface_clipped(&s, s.content_bounds(), &h, interp, Rect::new(0, 0, 50, 39)).unwrap(); + assert_eq!(w.rgba(25, 20), [1.0, 0.0, 0.0, 1.0], "{interp:?}"); + } +} + +#[test] +fn identity_and_translation_are_exact() { + let mut s = rgba(); + s.fill_rect(Rect::new(4, 4, 20, 12), &[1.0, 0.5, 0.0, 1.0]); + let r = s.content_bounds(); + for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] { + let h = Homography([1.0, 0.0, 7.0, 0.0, 1.0, -3.0, 0.0, 0.0, 1.0]); + let o = warp_surface(&s, r, &h, interp).unwrap(); + assert_eq!(o.content_bounds(), Rect::new(11, 1, 27, 9), "{interp:?}"); + assert_eq!(o.pixel(15, 5), vec![1.0, 128.0 / 255.0, 0.0, 1.0], "{interp:?}"); + } +} + +#[test] +fn translation_preserves_colour_range_at_every_depth() { + use photocraft_color::{ColorMode, SampleType}; + + let h = Homography([1.0, 0.0, 7.0, 0.0, 1.0, -3.0, 0.0, 0.0, 1.0]); + for sample in SampleType::ALL { + for mode in [ColorMode::Rgb, ColorMode::Grayscale] { + for alpha in [false, true] { + let mut s = Surface::new(PixelFormat::new(mode, sample, alpha)); + let mut pixel = if mode == ColorMode::Rgb { vec![2.0, -0.25, 0.5] } else { vec![2.0] }; + if alpha { + pixel.push(0.5); + } + s.fill_rect(Rect::new(4, 4, 8, 8), &pixel); + let mut expected = s.pixel(5, 5); + if !alpha { + expected.push(1.0); + } + for interp in [Interp::Nearest, Interp::Bilinear, Interp::Bicubic] { + let out = warp_surface(&s, s.content_bounds(), &h, interp).unwrap(); + assert_eq!(out.pixel(12, 2), expected, "{sample:?}/{mode:?}/alpha={alpha}/{interp:?}"); + assert_eq!(out.pixel(0, 0).last(), Some(&0.0)); + } + } + } + } +} + +#[test] +fn bilinear_translation_interpolates_signed_hdr_colours() { + let mut s = Surface::new(PixelFormat::RGBA32F); + s.write_pixel(0, 0, &[2.0, -0.5, 0.25, 0.5]); + s.write_pixel(1, 0, &[4.0, -0.25, 0.75, 0.5]); + let h = Homography([1.0, 0.0, 0.5, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + let out = warp_surface(&s, s.content_bounds(), &h, Interp::Bilinear).unwrap(); + assert_eq!(out.pixel(1, 0), vec![3.0, -0.375, 0.5, 0.5]); +} + +#[test] +fn scale_doubles_size_and_rotation_keeps_area() { + let mut s = rgba(); + s.fill_rect(Rect::new(0, 0, 40, 20), &[0.2, 0.4, 0.6, 1.0]); + let r = s.content_bounds(); + let up = + warp_surface(&s, r, &Homography::rect_to_quad([0.0, 0.0, 40.0, 20.0], [[0.0, 0.0], [80.0, 0.0], [80.0, 40.0], [0.0, 40.0]]).unwrap(), Interp::Bicubic) + .unwrap(); + let b = up.content_bounds(); + assert!(b.width() >= 80 && b.width() <= 82 && b.height() >= 40 && b.height() <= 42, "{b:?}"); + // 90° rotation about (20, 10): a 40×20 box becomes 20×40. + let q = [[30.0, -10.0], [30.0, 30.0], [10.0, 30.0], [10.0, -10.0]]; + let rot = warp_surface(&s, r, &Homography::rect_to_quad([0.0, 0.0, 40.0, 20.0], q).unwrap(), Interp::Bilinear).unwrap(); + let b = rot.content_bounds(); + assert!(b.width().abs_diff(20) <= 2 && b.height().abs_diff(40) <= 2, "{b:?}"); + let p = rot.pixel(20, 10); + assert!((p[0] - 0.2).abs() < 0.01 && p[3] > 0.99, "{p:?}"); +} + +/// #6203: a bicubic rotation of a sprite whose edge pixels are partly transparent overshoots +/// its alpha past 1. The colour must stay the sprite's, not grow with the overshoot into a +/// light border. +#[test] +fn rotation_keeps_the_colour_of_a_soft_edged_sprite() { + let mut s = rgba(); + s.fill_rect(Rect::new(10, 10, 30, 30), &[0.8, 0.6, 0.4, 0.5]); + s.fill_rect(Rect::new(11, 11, 29, 29), &[0.8, 0.6, 0.4, 1.0]); + let (c, k) = (20.0, std::f64::consts::FRAC_1_SQRT_2 * 10.0); + let q = [[c, c - 2.0 * k], [c + 2.0 * k, c], [c, c + 2.0 * k], [c - 2.0 * k, c]]; + let h = Homography::rect_to_quad([10.0, 10.0, 30.0, 30.0], q).unwrap(); + for interp in [Interp::Bicubic, Interp::Bilinear] { + let out = warp_surface(&s, s.content_bounds(), &h, interp).unwrap(); + let b = out.content_bounds(); + for y in b.y0..b.y1 { + for x in b.x0..b.x1 { + let p = out.pixel(x, y); + if p[3] > 0.0 { + let off = (0..3).map(|i| (p[i] - [0.8, 0.6, 0.4][i]).abs()).fold(0.0f32, f32::max); + assert!(off <= 1.0 / 255.0, "{interp:?} ({x}, {y}): {p:?}"); + } + } + } + } +} + +#[test] +fn large_downscale_is_prefiltered() { + // A 1px checkerboard shrunk 8× must come out ~50% grey, not aliased black/white. + let mut s = rgba(); + for y in 0..64 { + for x in 0..64 { + let v = ((x + y) % 2) as f32; + s.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, v, v, 1.0]); + } + } + let h = Homography::rect_to_quad([0.0, 0.0, 64.0, 64.0], [[0.0, 0.0], [8.0, 0.0], [8.0, 8.0], [0.0, 8.0]]).unwrap(); + let o = warp_surface(&s, s.content_bounds(), &h, Interp::Bicubic).unwrap(); + let p = o.pixel(4, 4); + assert!((p[0] - 0.5).abs() < 0.1, "{p:?}"); +} + +#[test] +fn surfaces_without_alpha_gain_it() { + let mut s = Surface::new(PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, false)); + s.fill_rect(Rect::new(0, 0, 10, 10), &[1.0, 0.0, 0.0]); + let h = Homography([1.0, 0.0, 5.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + let o = warp_surface(&s, Rect::new(0, 0, 10, 10), &h, Interp::Nearest).unwrap(); + assert!(o.format().alpha); + assert_eq!(o.pixel(2, 2)[3], 0.0); + assert_eq!(o.pixel(7, 2), vec![1.0, 0.0, 0.0, 1.0]); +} + +#[test] +fn homography_is_identity() { + assert!(Homography::IDENTITY.is_identity()); + assert!(Homography([2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 2.0]).is_identity()); + assert!(!Homography([1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).is_identity()); + assert!(!Homography([1.0, 0.1, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).is_identity()); +} From 6288f5a8c1680076db0a10b3aa266845233673cf Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:02 +0000 Subject: [PATCH 015/259] refactor(algo): move blur.rs tests to blur/tests.rs --- crates/algo/src/blur.rs | 463 +--------------------------------- crates/algo/src/blur/tests.rs | 460 +++++++++++++++++++++++++++++++++ 2 files changed, 461 insertions(+), 462 deletions(-) create mode 100644 crates/algo/src/blur/tests.rs diff --git a/crates/algo/src/blur.rs b/crates/algo/src/blur.rs index fb62681222..bd762d073f 100644 --- a/crates/algo/src/blur.rs +++ b/crates/algo/src/blur.rs @@ -784,465 +784,4 @@ fn surface_direct(src: &Image, out: Rect, ctx: &Ctx, r: i32, t: f32) -> Vec } #[cfg(test)] -mod tests { - use super::*; - use photocraft_color::{ColorMode, PixelFormat, SampleType}; - use photocraft_raster::Surface; - - #[test] - fn radial_blur_samples_large_arcs_beyond_64_intervals() { - let bounds = Rect::new(0, 0, 1000, 1000); - let out = Rect::new(999, 500, 1000, 501); - let ctx = Ctx { bounds, mode: photocraft_color::ColorMode::Grayscale, alpha: false }; - let mut img = Image::new(bounds, 1); - let (cx, cy) = (500.0f32, 500.0f32); - let (x, y) = (999.5f32, 500.5f32); - let (dx, dy) = (x - cx, y - cy); - let arc = 100.0f32.to_radians(); - let count = radial_intervals(arc * dx.hypot(dy), RadialQuality::Good); - assert_eq!(count, 256); - assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Draft), 64); - assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Good), 256); - assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Best), 4096); - assert_eq!(radial_intervals(f32::NAN, RadialQuality::Best), 1); - - // Put a small bright patch halfway between two samples from the former 64-interval - // limit. Dense sampling should pick it up; the coarse path misses it entirely. - let sparse_midpoint = (31.5 / 64.0 - 0.5) * arc; - let (s, c) = sparse_midpoint.sin_cos(); - let px = (cx + dx * c - dy * s - 0.5).round() as i32; - let py = (cy + dx * s + dy * c - 0.5).round() as i32; - for yy in py - 1..=py + 1 { - for xx in px - 1..=px + 1 { - let index = (yy - bounds.y0) as usize * bounds.width() as usize + (xx - bounds.x0) as usize; - img.data[index] = 1.0; - } - } - - let sample_path = |x: f32, y: f32, pts: &mut Vec<(f32, f32)>, intervals: usize| { - let (dx, dy) = (x - cx, y - cy); - for i in 0..=intervals { - let t = (i as f32 / intervals as f32 - 0.5) * arc; - let (s, c) = t.sin_cos(); - pts.push((cx + dx * c - dy * s, cy + dx * s + dy * c)); - } - }; - let actual = radial(&img, out, &ctx, 100.0, RadialMethod::Spin, RadialQuality::Good, (0.5, 0.5))[0]; - let expected = average_samples(&img, out, &ctx, |x, y, pts| sample_path(x, y, pts, 8192))[0]; - let coarse = average_samples(&img, out, &ctx, |x, y, pts| sample_path(x, y, pts, 64))[0]; - - assert!(actual > 0.001, "dense radial samples should resolve the bright patch, got {actual}"); - assert!((actual - expected).abs() < 0.0015, "radial result {actual} differs from dense reference {expected}"); - assert!(coarse < expected * 0.1, "former 64-interval sampling unexpectedly resolved the patch: {coarse} vs {expected}"); - } - - #[test] - fn fixed_channel_convolution_matches_scalar_tap_order() { - fn check() { - for width in [1, 7, 256] { - for radius in [0.0, 0.5, 3.0, 4.0] { - let k = gaussian_kernel(radius); - let src: Vec = (0..(width + k.len() - 1) * N).map(|i| ((i * 73) % 251) as f32 / 250.0).collect(); - let mut expected = vec![0.0f32; width * N]; - for x in 0..width { - for (i, w) in k.iter().enumerate() { - for c in 0..N { - expected[x * N + c] += src[(x + i) * N + c] * w; - } - } - } - let mut actual = vec![0.0f32; width * N]; - conv_row::(&src, &mut actual, &k); - assert_eq!(actual, expected, "channels={N} width={width} radius={radius}"); - } - } - } - check::<1>(); - check::<2>(); - check::<3>(); - check::<4>(); - check::<5>(); - } - - #[test] - fn box_gaussian_matches_exact_kernel() { - // A hard vertical edge (premultiplied RGBA-ish, 2 channels) blurred with σ = 12. - let src_rect = Rect::new(-60, -60, 180, 68); - let mut img = Image::new(src_rect, 2); - for y in src_rect.y0..src_rect.y1 { - for x in src_rect.x0..src_rect.x1 { - let i = ((y - src_rect.y0) as usize * src_rect.width() as usize + (x - src_rect.x0) as usize) * 2; - img.data[i] = if x < 60 { 1.0 } else { 0.0 }; - img.data[i + 1] = 1.0; - } - } - let out = Rect::new(0, 0, 120, 8); - let k = gaussian_kernel(12.0); - let exact = conv_sep(&img, out, &k, &k, true); - let fast = box_passes(&img, out, true, &boxes_for_gauss(12.0, 3)); - let err = exact.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(err < 0.02, "max error {err}"); - assert_eq!(boxes_for_gauss(10.0, 3).len(), 3); - } - - #[test] - fn box_passes_match_the_direct_box_kernel() { - // Noisy RGBA with varying alpha, so premultiplication and every channel are exercised. - for r in [5usize, 17, 60] { - let (w, h, m) = (40, 24, r as i32 + 2); - let src_rect = Rect::new(-m, -m, w + m, h + m); - let mut img = Image::new(src_rect, 4); - let mut s = 0x9e37_79b9u32; - for v in img.data.iter_mut() { - s ^= s << 13; - s ^= s >> 17; - s ^= s << 5; - *v = (s % 256) as f32 / 255.0; - } - let out = Rect::new(0, 0, w, h); - let k = vec![1.0 / (2 * r + 1) as f32; 2 * r + 1]; - let direct = conv_sep(&img, out, &k, &k, true); - let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha: true }; - let fast = boxed(&img, out, &ctx, r as f32); - let err = direct.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(err < 1e-5, "radius {r}: max error {err}"); - } - } - - /// The definition the running sums must match: each box applied in turn as a direct - /// convolution (cost per pixel proportional to the radius) to `img`, which covers `out` grown - /// by every box's reach (its own edge handling included). - fn direct_boxes(img: &Image, out: Rect, boxes: &[usize], alpha: bool) -> Vec { - let mut cur = img.clone(); - let mut left: i32 = boxes.iter().map(|w| (w / 2) as i32).sum(); - for &w in boxes { - left -= (w / 2) as i32; - let k = vec![1.0 / w as f32; w]; - let rect = out.inflate(left); - cur = Image { rect, ch: img.ch, data: conv_sep(&cur, rect, &k, &k, alpha) }; - } - cur.data - } - - /// Noisy pixels over `r` (alpha varying, some fully transparent). - fn noisy(fmt: PixelFormat, r: Rect, seed: u32) -> Surface { - let mut s = Surface::new(fmt); - let mut st = seed; - let mut v = Vec::new(); - for _ in 0..r.width() * r.height() { - for c in 0..fmt.channels() { - st ^= st << 13; - st ^= st >> 17; - st ^= st << 5; - let x = (st % 256) as f32 / 255.0; - v.push(if fmt.alpha && c + 1 == fmt.channels() && st.is_multiple_of(5) { 0.0 } else { x }); - } - } - s.write_region(r, &v); - s - } - - #[test] - fn layer_box_blurs_match_direct_convolution_at_any_radius() { - // Gaussian and Box Blur at radii up to several times the layer (37 × 23), filtered as a - // document layer (canvas edge repeated, as Photoshop does) and on their own (transparent - // beyond), at every depth, with and without alpha, 1 to 5 channels. - let canvas = Rect::new(0, 0, 37, 23); - let formats = [ - PixelFormat::RGBA8, - PixelFormat::RGBA16, - PixelFormat::RGBA32F, - PixelFormat::GRAY8, - PixelFormat::CMYKA8, - PixelFormat::new(ColorMode::Lab, SampleType::F32, false), - ]; - let params = [ - FilterParams::GaussianBlur { radius: 4.5 }, - FilterParams::GaussianBlur { radius: 9.3 }, - FilterParams::GaussianBlur { radius: 40.0 }, - FilterParams::BoxBlur { radius: 5.0 }, - FilterParams::BoxBlur { radius: 70.0 }, - ]; - for (i, fmt) in formats.into_iter().enumerate() { - let s = noisy(fmt, canvas, 0x9e37_79b9 + i as u32); - // A level of the depth (colour and alpha are each rounded on write) plus float noise. - let tol = match fmt.sample { - SampleType::U8 => 1.0 / 255.0, - SampleType::U16 => 1.0 / 65535.0, - _ => 0.0, - } + 2e-5; - for p in ¶ms { - let boxes = box_widths(p).expect("a box-pass blur"); - let reach: i32 = boxes.iter().map(|w| (w / 2) as i32).sum(); - let area = crate::output_area(p, s.content_bounds(), canvas, None); - for (got, img, out) in [ - (crate::apply_in(&s, p, area, canvas, None, canvas), Image::read_clamped(&s, canvas.inflate(reach), canvas), canvas), - (crate::apply(&s, p, area, canvas, None), Image::read(&s, area.inflate(reach)), area), - ] { - // Compared alpha-weighted: colour is meaningless where (nearly) transparent. - let (mut got, mut want) = (got.read_region(out), direct_boxes(&img, out, &boxes, fmt.alpha)); - premultiply(&mut got, img.ch, fmt.alpha); - premultiply(&mut want, img.ch, fmt.alpha); - let err = got.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(err <= tol, "{} on {fmt:?} over {out:?}: max error {err}", p.label()); - } - } - } - } - - #[test] - fn layer_box_blurs_mix_by_the_selection_and_stop_when_cancelled() { - let canvas = Rect::new(0, 0, 37, 23); - let s = noisy(PixelFormat::RGBA32F, canvas, 7); - let p = FilterParams::GaussianBlur { radius: 12.0 }; - let full = crate::apply_in(&s, &p, canvas, canvas, None, canvas); - let half = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false), &[0.5]); - let mixed = crate::apply_in(&s, &p, canvas, canvas, Some(&half), canvas); - for (x, y) in [(0, 0), (18, 11), (36, 22)] { - let (o, f, m) = (s.pixel(x, y), full.pixel(x, y), mixed.pixel(x, y)); - assert!((m[3] - (o[3] + f[3]) / 2.0).abs() < 1e-5, "({x},{y}) alpha"); - for c in 0..3 { - assert!((m[c] * m[3] - (o[c] * o[3] + f[c] * f[3]) / 2.0).abs() < 1e-5, "({x},{y}) premultiplied channel {c}"); - } - } - let cancel = || true; - let ctl = Interrupt::cancel_only(&cancel); - assert!(crate::apply_in_with(&s, &p, canvas, canvas, None, canvas, &ctl).is_none()); - } - - #[test] - fn surface_blur_8bit_histogram_matches_the_direct_sum() { - // 8-bit levels with some fully transparent pixels, which the sum skips. - let src_rect = Rect::new(-14, -14, 40, 34); - let mut img = Image::new(src_rect, 4); - let mut s = 0x6c07_8965u32; - for px in img.data.as_chunks_mut::<4>().0 { - for v in px.iter_mut() { - s ^= s << 13; - s ^= s >> 17; - s ^= s << 5; - *v = (s % 256) as f32 / 255.0; - } - if s.is_multiple_of(7) { - px[3] = 0.0; - } - } - let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha: true }; - // The output reaches the source edge, where samples read as transparent. - let out = Rect::new(-2, 0, 26, 20); - for (r, threshold) in [(1, 2.0), (4, 15.0), (12, 60.0), (12, 255.0)] { - let t = (threshold / 255.0) * 2.5; - let reach = ((t * 255.0f32).ceil() as usize).min(255); - let fast = surface_8bit(&img, out, &ctx, r, t, reach).expect("8-bit input"); - let direct = surface_direct(&img, out, &ctx, r, t); - let err = direct.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(err < 1e-5, "r {r} threshold {threshold}: max error {err}"); - } - // Not 8-bit: the histogram declines and the direct sum is used. - // (0, 0) is inside every window above. - let i = (14 * src_rect.width() as usize + 14) * 4; - img.data[i] = 0.5 / 255.0; - assert!(surface_8bit(&img, out, &ctx, 4, 0.1, 26).is_none()); - } - - #[test] - fn motion_kernel_matches_the_per_pixel_samples() { - // Noisy RGBA with some transparent pixels; the output reaches the source edge. - let src_rect = Rect::new(-30, -30, 50, 40); - let mut img = Image::new(src_rect, 4); - let mut s = 0x1b87_3593u32; - for px in img.data.as_chunks_mut::<4>().0 { - for v in px.iter_mut() { - s ^= s << 13; - s ^= s >> 17; - s ^= s << 5; - *v = (s % 1000) as f32 / 999.0; - } - if s.is_multiple_of(5) { - px[3] = 0.0; - } - } - let out = Rect::new(-12, -6, 30, 22); - for alpha in [true, false] { - let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha }; - for (angle, distance) in [(0.0, 1.0), (0.0, 9.0), (30.0, 7.0), (90.0, 12.0), (-45.0, 20.0), (137.0, 33.5), (200.0, 40.0)] { - let fast = motion(&img, out, &ctx, angle, distance); - let offs = motion_offsets(angle, distance); - let slow = average_samples(&img, out, &ctx, |x, y, pts| pts.extend(offs.iter().map(|&(dx, dy)| (x + dx, y + dy)))); - let err = slow.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(err < 1e-5, "alpha {alpha} angle {angle} distance {distance}: max error {err}"); - } - } - } - - /// The direct sum with f64 accumulators: the reference both fast paths are held to. - fn surface_reference(src: &Image, out: Rect, ctx: &Ctx, r: i32, t: f32) -> Vec { - let n = src.ch; - let cc = if ctx.alpha { n - 1 } else { n }; - let mut res = Vec::new(); - for y in out.y0..out.y1 { - for x in out.x0..out.x1 { - let p = src.px(x, y); - for &v0 in p.iter().take(cc) { - let c = res.len() % n; - let (mut acc, mut wsum) = (0.0f64, 0.0f64); - for yy in y - r..=y + r { - for xx in x - r..=x + r { - if ctx.alpha && src.get(xx, yy, n - 1) <= 0.0 { - continue; - } - let v = src.get(xx, yy, c); - let w = (1.0 - (v - v0).abs() / t).max(0.0); - acc += f64::from(v) * f64::from(w); - wsum += f64::from(w); - } - } - res.push(if wsum > 0.0 { (acc / wsum) as f32 } else { v0 }); - } - if ctx.alpha { - res.push(p[n - 1]); - } - } - } - res - } - - #[test] - fn surface_blur_ranked_sums_match_the_weighted_window_at_any_depth() { - // 16-bit levels and arbitrary floats (including negatives and values above 1), with some - // fully transparent pixels, which the sum skips. - for (quant, channels, alpha) in [(Some(65535.0f32), 4, true), (None, 4, true), (None, 1, false)] { - let src_rect = Rect::new(-20, -20, 48, 40); - let mut img = Image::new(src_rect, channels); - let mut s = 0x1b87_3593u32; - for px in img.data.chunks_mut(channels) { - for v in px.iter_mut() { - s ^= s << 13; - s ^= s >> 17; - s ^= s << 5; - let raw = (s % 10_000) as f32 / 10_000.0; - *v = quant.map_or(raw * 1.5 - 0.25, |q| (raw * q).round() / q); - } - if alpha && s.is_multiple_of(7) { - px[channels - 1] = 0.0; - } - } - let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha }; - // The output reaches the source edge, where samples read as 0. - let out = Rect::new(-6, 0, 30, 22); - for (r, threshold) in [(1, 2.0), (4, 15.0), (12, 60.0), (16, 255.0)] { - let t = (threshold / 255.0) * 2.5; - let ranked = surface_ranked(&img, out, &ctx, r, t).expect("finite input"); - let reference = surface_reference(&img, out, &ctx, r, t); - assert_eq!(ranked.len(), reference.len()); - let err = reference.iter().zip(&ranked).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(err < 1e-6, "{quant:?} r {r} threshold {threshold}: max error {err}"); - } - } - } - - #[test] - fn surface_blur_ranked_declines_non_finite_samples_and_handles_empty_output() { - let src_rect = Rect::new(0, 0, 8, 8); - let mut img = Image::new(src_rect, 1); - img.data.fill(0.5); - let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Grayscale, alpha: false }; - assert_eq!(surface_ranked(&img, Rect::new(2, 2, 2, 6), &ctx, 2, 0.1), Some(Vec::new())); - img.data[9] = f32::NAN; - assert!(surface_ranked(&img, Rect::new(0, 0, 8, 8), &ctx, 2, 0.1).is_none()); - // The public entry still answers, through the direct sum. - assert_eq!(surface(&img, Rect::new(0, 0, 8, 8), &ctx, 12.0, 15.0).len(), 64); - } - - /// Release-mode timings of the direct sum and the ranked path on one 256 px tile of - /// 16-bit-like and float noise (`cargo test -p photocraft-algo --release -- --ignored --nocapture surface_timing`). - #[test] - #[ignore] - fn surface_timing() { - for (label, quant) in [("16-bit", Some(65535.0f32)), ("float", None)] { - for r in [2, 4, 8, 16, 32, 64, 100] { - let out = Rect::new(0, 0, 256, 256); - let src_rect = out.inflate(r); - let mut img = Image::new(src_rect, 4); - let mut s = 0x2545_f491u32; - let len = img.data.len(); - for (i, v) in img.data.iter_mut().enumerate() { - s ^= s << 13; - s ^= s >> 17; - s ^= s << 5; - // Smooth gradient plus noise, so the threshold keeps a realistic share. - let x = (i / 4) as f32 / len as f32 * 4.0; - let raw = (0.5 + 0.4 * (x * 6.0).sin() + (s % 1000) as f32 / 20000.0).clamp(0.0, 1.0); - *v = quant.map_or(raw, |q| (raw * q).round() / q); - } - let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha: true }; - let t = (15.0 / 255.0) * 2.5; - let a = std::time::Instant::now(); - let direct = surface_direct(&img, out, &ctx, r, t); - let td = a.elapsed(); - let a = std::time::Instant::now(); - let ranked = surface_ranked(&img, out, &ctx, r, t).expect("finite"); - let tr = a.elapsed(); - let err = direct.iter().zip(&ranked).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - println!("{label} r {r:3}: direct {td:>10.2?} ranked {tr:>10.2?} max err {err:.2e}"); - } - } - } - - /// A column strip's passes stop between passes once cancelled, not only before the strip - /// (#6205); uncancelled, every pass runs. - #[test] - fn line_passes_stop_between_passes_when_cancelled() { - use std::sync::atomic::{AtomicUsize, Ordering}; - let (radii, w, len) = ([2usize, 3, 2], 4usize, 50usize); - let reach: usize = radii.iter().sum(); - let line: Vec = (0..(len + 2 * reach) * w).map(|i| (i % 7) as f32 + 1.0).collect(); - let run = |ctl: &Interrupt| { - let mut s = Scratch { line: line.clone(), ..Scratch::default() }; - let mut dst = vec![0.0f32; len * w]; - line_passes(&mut dst, w, &radii, &mut s, ctl); - dst - }; - assert!(run(&Interrupt::NONE).iter().all(|v| *v > 0.0)); - let calls = AtomicUsize::new(0); - let cancel = || calls.fetch_add(1, Ordering::SeqCst) >= 1; - // Cancelled after the first pass: the last pass (the one writing `dst`) never runs. - assert!(run(&Interrupt::cancel_only(&cancel)).iter().all(|v| *v == 0.0)); - assert_eq!(calls.load(Ordering::SeqCst), 2); - } - - /// A box blur cancelled at any of its checks returns `None` (never a half-blurred result); - /// one that is asked but never cancelled is bit-identical to the uninterruptible run. - #[test] - fn box_blur_honours_a_cancel_at_every_check() { - use std::sync::atomic::{AtomicUsize, Ordering}; - let (n, src) = (4usize, Rect::new(0, 0, 150, 90)); - let px: Vec = (0..src.width() as usize * src.height() as usize * n).map(|i| (i as f32 * 0.13).sin() * 0.5 + 0.5).collect(); - let read = |r: Rect, buf: &mut Vec| { - buf.clear(); - let (x0, x1) = ((r.x0 * n as i32) as usize, (r.x1 * n as i32) as usize); - let row = r.y0 as usize * src.width() as usize * n; - buf.extend_from_slice(&px[row + x0..row + x1]); - }; - let Some(boxes) = box_widths(&FilterParams::GaussianBlur { radius: 12.0 }) else { panic!("box passes") }; - let out = Rect::new(-5, 3, 155, 80); - let want = box_blur(src, &read, out, n, true, &boxes, &Interrupt::NONE).unwrap(); - let checks = AtomicUsize::new(0); - let count = || { - checks.fetch_add(1, Ordering::SeqCst); - false - }; - let got = box_blur(src, &read, out, n, true, &boxes, &Interrupt::cancel_only(&count)).unwrap(); - assert_eq!(got.len(), want.len()); - for ((ta, a), (tb, b)) in got.iter().zip(&want) { - assert_eq!(ta, tb); - assert!(a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits()), "strip {ta:?} differs"); - } - let total = checks.load(Ordering::SeqCst); - for k in (0..total).step_by((total / 40).max(1)) { - let seen = AtomicUsize::new(0); - let cancel = || seen.fetch_add(1, Ordering::SeqCst) >= k; - assert!(box_blur(src, &read, out, n, true, &boxes, &Interrupt::cancel_only(&cancel)).is_none(), "cancelled at check {k}"); - } - } -} +mod tests; diff --git a/crates/algo/src/blur/tests.rs b/crates/algo/src/blur/tests.rs new file mode 100644 index 0000000000..32256bc954 --- /dev/null +++ b/crates/algo/src/blur/tests.rs @@ -0,0 +1,460 @@ +use super::*; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_raster::Surface; + +#[test] +fn radial_blur_samples_large_arcs_beyond_64_intervals() { + let bounds = Rect::new(0, 0, 1000, 1000); + let out = Rect::new(999, 500, 1000, 501); + let ctx = Ctx { bounds, mode: photocraft_color::ColorMode::Grayscale, alpha: false }; + let mut img = Image::new(bounds, 1); + let (cx, cy) = (500.0f32, 500.0f32); + let (x, y) = (999.5f32, 500.5f32); + let (dx, dy) = (x - cx, y - cy); + let arc = 100.0f32.to_radians(); + let count = radial_intervals(arc * dx.hypot(dy), RadialQuality::Good); + assert_eq!(count, 256); + assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Draft), 64); + assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Good), 256); + assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Best), 4096); + assert_eq!(radial_intervals(f32::NAN, RadialQuality::Best), 1); + + // Put a small bright patch halfway between two samples from the former 64-interval + // limit. Dense sampling should pick it up; the coarse path misses it entirely. + let sparse_midpoint = (31.5 / 64.0 - 0.5) * arc; + let (s, c) = sparse_midpoint.sin_cos(); + let px = (cx + dx * c - dy * s - 0.5).round() as i32; + let py = (cy + dx * s + dy * c - 0.5).round() as i32; + for yy in py - 1..=py + 1 { + for xx in px - 1..=px + 1 { + let index = (yy - bounds.y0) as usize * bounds.width() as usize + (xx - bounds.x0) as usize; + img.data[index] = 1.0; + } + } + + let sample_path = |x: f32, y: f32, pts: &mut Vec<(f32, f32)>, intervals: usize| { + let (dx, dy) = (x - cx, y - cy); + for i in 0..=intervals { + let t = (i as f32 / intervals as f32 - 0.5) * arc; + let (s, c) = t.sin_cos(); + pts.push((cx + dx * c - dy * s, cy + dx * s + dy * c)); + } + }; + let actual = radial(&img, out, &ctx, 100.0, RadialMethod::Spin, RadialQuality::Good, (0.5, 0.5))[0]; + let expected = average_samples(&img, out, &ctx, |x, y, pts| sample_path(x, y, pts, 8192))[0]; + let coarse = average_samples(&img, out, &ctx, |x, y, pts| sample_path(x, y, pts, 64))[0]; + + assert!(actual > 0.001, "dense radial samples should resolve the bright patch, got {actual}"); + assert!((actual - expected).abs() < 0.0015, "radial result {actual} differs from dense reference {expected}"); + assert!(coarse < expected * 0.1, "former 64-interval sampling unexpectedly resolved the patch: {coarse} vs {expected}"); +} + +#[test] +fn fixed_channel_convolution_matches_scalar_tap_order() { + fn check() { + for width in [1, 7, 256] { + for radius in [0.0, 0.5, 3.0, 4.0] { + let k = gaussian_kernel(radius); + let src: Vec = (0..(width + k.len() - 1) * N).map(|i| ((i * 73) % 251) as f32 / 250.0).collect(); + let mut expected = vec![0.0f32; width * N]; + for x in 0..width { + for (i, w) in k.iter().enumerate() { + for c in 0..N { + expected[x * N + c] += src[(x + i) * N + c] * w; + } + } + } + let mut actual = vec![0.0f32; width * N]; + conv_row::(&src, &mut actual, &k); + assert_eq!(actual, expected, "channels={N} width={width} radius={radius}"); + } + } + } + check::<1>(); + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); +} + +#[test] +fn box_gaussian_matches_exact_kernel() { + // A hard vertical edge (premultiplied RGBA-ish, 2 channels) blurred with σ = 12. + let src_rect = Rect::new(-60, -60, 180, 68); + let mut img = Image::new(src_rect, 2); + for y in src_rect.y0..src_rect.y1 { + for x in src_rect.x0..src_rect.x1 { + let i = ((y - src_rect.y0) as usize * src_rect.width() as usize + (x - src_rect.x0) as usize) * 2; + img.data[i] = if x < 60 { 1.0 } else { 0.0 }; + img.data[i + 1] = 1.0; + } + } + let out = Rect::new(0, 0, 120, 8); + let k = gaussian_kernel(12.0); + let exact = conv_sep(&img, out, &k, &k, true); + let fast = box_passes(&img, out, true, &boxes_for_gauss(12.0, 3)); + let err = exact.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(err < 0.02, "max error {err}"); + assert_eq!(boxes_for_gauss(10.0, 3).len(), 3); +} + +#[test] +fn box_passes_match_the_direct_box_kernel() { + // Noisy RGBA with varying alpha, so premultiplication and every channel are exercised. + for r in [5usize, 17, 60] { + let (w, h, m) = (40, 24, r as i32 + 2); + let src_rect = Rect::new(-m, -m, w + m, h + m); + let mut img = Image::new(src_rect, 4); + let mut s = 0x9e37_79b9u32; + for v in img.data.iter_mut() { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + *v = (s % 256) as f32 / 255.0; + } + let out = Rect::new(0, 0, w, h); + let k = vec![1.0 / (2 * r + 1) as f32; 2 * r + 1]; + let direct = conv_sep(&img, out, &k, &k, true); + let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha: true }; + let fast = boxed(&img, out, &ctx, r as f32); + let err = direct.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(err < 1e-5, "radius {r}: max error {err}"); + } +} + +/// The definition the running sums must match: each box applied in turn as a direct +/// convolution (cost per pixel proportional to the radius) to `img`, which covers `out` grown +/// by every box's reach (its own edge handling included). +fn direct_boxes(img: &Image, out: Rect, boxes: &[usize], alpha: bool) -> Vec { + let mut cur = img.clone(); + let mut left: i32 = boxes.iter().map(|w| (w / 2) as i32).sum(); + for &w in boxes { + left -= (w / 2) as i32; + let k = vec![1.0 / w as f32; w]; + let rect = out.inflate(left); + cur = Image { rect, ch: img.ch, data: conv_sep(&cur, rect, &k, &k, alpha) }; + } + cur.data +} + +/// Noisy pixels over `r` (alpha varying, some fully transparent). +fn noisy(fmt: PixelFormat, r: Rect, seed: u32) -> Surface { + let mut s = Surface::new(fmt); + let mut st = seed; + let mut v = Vec::new(); + for _ in 0..r.width() * r.height() { + for c in 0..fmt.channels() { + st ^= st << 13; + st ^= st >> 17; + st ^= st << 5; + let x = (st % 256) as f32 / 255.0; + v.push(if fmt.alpha && c + 1 == fmt.channels() && st.is_multiple_of(5) { 0.0 } else { x }); + } + } + s.write_region(r, &v); + s +} + +#[test] +fn layer_box_blurs_match_direct_convolution_at_any_radius() { + // Gaussian and Box Blur at radii up to several times the layer (37 × 23), filtered as a + // document layer (canvas edge repeated, as Photoshop does) and on their own (transparent + // beyond), at every depth, with and without alpha, 1 to 5 channels. + let canvas = Rect::new(0, 0, 37, 23); + let formats = [ + PixelFormat::RGBA8, + PixelFormat::RGBA16, + PixelFormat::RGBA32F, + PixelFormat::GRAY8, + PixelFormat::CMYKA8, + PixelFormat::new(ColorMode::Lab, SampleType::F32, false), + ]; + let params = [ + FilterParams::GaussianBlur { radius: 4.5 }, + FilterParams::GaussianBlur { radius: 9.3 }, + FilterParams::GaussianBlur { radius: 40.0 }, + FilterParams::BoxBlur { radius: 5.0 }, + FilterParams::BoxBlur { radius: 70.0 }, + ]; + for (i, fmt) in formats.into_iter().enumerate() { + let s = noisy(fmt, canvas, 0x9e37_79b9 + i as u32); + // A level of the depth (colour and alpha are each rounded on write) plus float noise. + let tol = match fmt.sample { + SampleType::U8 => 1.0 / 255.0, + SampleType::U16 => 1.0 / 65535.0, + _ => 0.0, + } + 2e-5; + for p in ¶ms { + let boxes = box_widths(p).expect("a box-pass blur"); + let reach: i32 = boxes.iter().map(|w| (w / 2) as i32).sum(); + let area = crate::output_area(p, s.content_bounds(), canvas, None); + for (got, img, out) in [ + (crate::apply_in(&s, p, area, canvas, None, canvas), Image::read_clamped(&s, canvas.inflate(reach), canvas), canvas), + (crate::apply(&s, p, area, canvas, None), Image::read(&s, area.inflate(reach)), area), + ] { + // Compared alpha-weighted: colour is meaningless where (nearly) transparent. + let (mut got, mut want) = (got.read_region(out), direct_boxes(&img, out, &boxes, fmt.alpha)); + premultiply(&mut got, img.ch, fmt.alpha); + premultiply(&mut want, img.ch, fmt.alpha); + let err = got.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(err <= tol, "{} on {fmt:?} over {out:?}: max error {err}", p.label()); + } + } + } +} + +#[test] +fn layer_box_blurs_mix_by_the_selection_and_stop_when_cancelled() { + let canvas = Rect::new(0, 0, 37, 23); + let s = noisy(PixelFormat::RGBA32F, canvas, 7); + let p = FilterParams::GaussianBlur { radius: 12.0 }; + let full = crate::apply_in(&s, &p, canvas, canvas, None, canvas); + let half = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false), &[0.5]); + let mixed = crate::apply_in(&s, &p, canvas, canvas, Some(&half), canvas); + for (x, y) in [(0, 0), (18, 11), (36, 22)] { + let (o, f, m) = (s.pixel(x, y), full.pixel(x, y), mixed.pixel(x, y)); + assert!((m[3] - (o[3] + f[3]) / 2.0).abs() < 1e-5, "({x},{y}) alpha"); + for c in 0..3 { + assert!((m[c] * m[3] - (o[c] * o[3] + f[c] * f[3]) / 2.0).abs() < 1e-5, "({x},{y}) premultiplied channel {c}"); + } + } + let cancel = || true; + let ctl = Interrupt::cancel_only(&cancel); + assert!(crate::apply_in_with(&s, &p, canvas, canvas, None, canvas, &ctl).is_none()); +} + +#[test] +fn surface_blur_8bit_histogram_matches_the_direct_sum() { + // 8-bit levels with some fully transparent pixels, which the sum skips. + let src_rect = Rect::new(-14, -14, 40, 34); + let mut img = Image::new(src_rect, 4); + let mut s = 0x6c07_8965u32; + for px in img.data.as_chunks_mut::<4>().0 { + for v in px.iter_mut() { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + *v = (s % 256) as f32 / 255.0; + } + if s.is_multiple_of(7) { + px[3] = 0.0; + } + } + let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha: true }; + // The output reaches the source edge, where samples read as transparent. + let out = Rect::new(-2, 0, 26, 20); + for (r, threshold) in [(1, 2.0), (4, 15.0), (12, 60.0), (12, 255.0)] { + let t = (threshold / 255.0) * 2.5; + let reach = ((t * 255.0f32).ceil() as usize).min(255); + let fast = surface_8bit(&img, out, &ctx, r, t, reach).expect("8-bit input"); + let direct = surface_direct(&img, out, &ctx, r, t); + let err = direct.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(err < 1e-5, "r {r} threshold {threshold}: max error {err}"); + } + // Not 8-bit: the histogram declines and the direct sum is used. + // (0, 0) is inside every window above. + let i = (14 * src_rect.width() as usize + 14) * 4; + img.data[i] = 0.5 / 255.0; + assert!(surface_8bit(&img, out, &ctx, 4, 0.1, 26).is_none()); +} + +#[test] +fn motion_kernel_matches_the_per_pixel_samples() { + // Noisy RGBA with some transparent pixels; the output reaches the source edge. + let src_rect = Rect::new(-30, -30, 50, 40); + let mut img = Image::new(src_rect, 4); + let mut s = 0x1b87_3593u32; + for px in img.data.as_chunks_mut::<4>().0 { + for v in px.iter_mut() { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + *v = (s % 1000) as f32 / 999.0; + } + if s.is_multiple_of(5) { + px[3] = 0.0; + } + } + let out = Rect::new(-12, -6, 30, 22); + for alpha in [true, false] { + let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha }; + for (angle, distance) in [(0.0, 1.0), (0.0, 9.0), (30.0, 7.0), (90.0, 12.0), (-45.0, 20.0), (137.0, 33.5), (200.0, 40.0)] { + let fast = motion(&img, out, &ctx, angle, distance); + let offs = motion_offsets(angle, distance); + let slow = average_samples(&img, out, &ctx, |x, y, pts| pts.extend(offs.iter().map(|&(dx, dy)| (x + dx, y + dy)))); + let err = slow.iter().zip(&fast).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(err < 1e-5, "alpha {alpha} angle {angle} distance {distance}: max error {err}"); + } + } +} + +/// The direct sum with f64 accumulators: the reference both fast paths are held to. +fn surface_reference(src: &Image, out: Rect, ctx: &Ctx, r: i32, t: f32) -> Vec { + let n = src.ch; + let cc = if ctx.alpha { n - 1 } else { n }; + let mut res = Vec::new(); + for y in out.y0..out.y1 { + for x in out.x0..out.x1 { + let p = src.px(x, y); + for &v0 in p.iter().take(cc) { + let c = res.len() % n; + let (mut acc, mut wsum) = (0.0f64, 0.0f64); + for yy in y - r..=y + r { + for xx in x - r..=x + r { + if ctx.alpha && src.get(xx, yy, n - 1) <= 0.0 { + continue; + } + let v = src.get(xx, yy, c); + let w = (1.0 - (v - v0).abs() / t).max(0.0); + acc += f64::from(v) * f64::from(w); + wsum += f64::from(w); + } + } + res.push(if wsum > 0.0 { (acc / wsum) as f32 } else { v0 }); + } + if ctx.alpha { + res.push(p[n - 1]); + } + } + } + res +} + +#[test] +fn surface_blur_ranked_sums_match_the_weighted_window_at_any_depth() { + // 16-bit levels and arbitrary floats (including negatives and values above 1), with some + // fully transparent pixels, which the sum skips. + for (quant, channels, alpha) in [(Some(65535.0f32), 4, true), (None, 4, true), (None, 1, false)] { + let src_rect = Rect::new(-20, -20, 48, 40); + let mut img = Image::new(src_rect, channels); + let mut s = 0x1b87_3593u32; + for px in img.data.chunks_mut(channels) { + for v in px.iter_mut() { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + let raw = (s % 10_000) as f32 / 10_000.0; + *v = quant.map_or(raw * 1.5 - 0.25, |q| (raw * q).round() / q); + } + if alpha && s.is_multiple_of(7) { + px[channels - 1] = 0.0; + } + } + let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha }; + // The output reaches the source edge, where samples read as 0. + let out = Rect::new(-6, 0, 30, 22); + for (r, threshold) in [(1, 2.0), (4, 15.0), (12, 60.0), (16, 255.0)] { + let t = (threshold / 255.0) * 2.5; + let ranked = surface_ranked(&img, out, &ctx, r, t).expect("finite input"); + let reference = surface_reference(&img, out, &ctx, r, t); + assert_eq!(ranked.len(), reference.len()); + let err = reference.iter().zip(&ranked).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(err < 1e-6, "{quant:?} r {r} threshold {threshold}: max error {err}"); + } + } +} + +#[test] +fn surface_blur_ranked_declines_non_finite_samples_and_handles_empty_output() { + let src_rect = Rect::new(0, 0, 8, 8); + let mut img = Image::new(src_rect, 1); + img.data.fill(0.5); + let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Grayscale, alpha: false }; + assert_eq!(surface_ranked(&img, Rect::new(2, 2, 2, 6), &ctx, 2, 0.1), Some(Vec::new())); + img.data[9] = f32::NAN; + assert!(surface_ranked(&img, Rect::new(0, 0, 8, 8), &ctx, 2, 0.1).is_none()); + // The public entry still answers, through the direct sum. + assert_eq!(surface(&img, Rect::new(0, 0, 8, 8), &ctx, 12.0, 15.0).len(), 64); +} + +/// Release-mode timings of the direct sum and the ranked path on one 256 px tile of +/// 16-bit-like and float noise (`cargo test -p photocraft-algo --release -- --ignored --nocapture surface_timing`). +#[test] +#[ignore] +fn surface_timing() { + for (label, quant) in [("16-bit", Some(65535.0f32)), ("float", None)] { + for r in [2, 4, 8, 16, 32, 64, 100] { + let out = Rect::new(0, 0, 256, 256); + let src_rect = out.inflate(r); + let mut img = Image::new(src_rect, 4); + let mut s = 0x2545_f491u32; + let len = img.data.len(); + for (i, v) in img.data.iter_mut().enumerate() { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + // Smooth gradient plus noise, so the threshold keeps a realistic share. + let x = (i / 4) as f32 / len as f32 * 4.0; + let raw = (0.5 + 0.4 * (x * 6.0).sin() + (s % 1000) as f32 / 20000.0).clamp(0.0, 1.0); + *v = quant.map_or(raw, |q| (raw * q).round() / q); + } + let ctx = Ctx { bounds: src_rect, mode: crate::ColorMode::Rgb, alpha: true }; + let t = (15.0 / 255.0) * 2.5; + let a = std::time::Instant::now(); + let direct = surface_direct(&img, out, &ctx, r, t); + let td = a.elapsed(); + let a = std::time::Instant::now(); + let ranked = surface_ranked(&img, out, &ctx, r, t).expect("finite"); + let tr = a.elapsed(); + let err = direct.iter().zip(&ranked).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + println!("{label} r {r:3}: direct {td:>10.2?} ranked {tr:>10.2?} max err {err:.2e}"); + } + } +} + +/// A column strip's passes stop between passes once cancelled, not only before the strip +/// (#6205); uncancelled, every pass runs. +#[test] +fn line_passes_stop_between_passes_when_cancelled() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let (radii, w, len) = ([2usize, 3, 2], 4usize, 50usize); + let reach: usize = radii.iter().sum(); + let line: Vec = (0..(len + 2 * reach) * w).map(|i| (i % 7) as f32 + 1.0).collect(); + let run = |ctl: &Interrupt| { + let mut s = Scratch { line: line.clone(), ..Scratch::default() }; + let mut dst = vec![0.0f32; len * w]; + line_passes(&mut dst, w, &radii, &mut s, ctl); + dst + }; + assert!(run(&Interrupt::NONE).iter().all(|v| *v > 0.0)); + let calls = AtomicUsize::new(0); + let cancel = || calls.fetch_add(1, Ordering::SeqCst) >= 1; + // Cancelled after the first pass: the last pass (the one writing `dst`) never runs. + assert!(run(&Interrupt::cancel_only(&cancel)).iter().all(|v| *v == 0.0)); + assert_eq!(calls.load(Ordering::SeqCst), 2); +} + +/// A box blur cancelled at any of its checks returns `None` (never a half-blurred result); +/// one that is asked but never cancelled is bit-identical to the uninterruptible run. +#[test] +fn box_blur_honours_a_cancel_at_every_check() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let (n, src) = (4usize, Rect::new(0, 0, 150, 90)); + let px: Vec = (0..src.width() as usize * src.height() as usize * n).map(|i| (i as f32 * 0.13).sin() * 0.5 + 0.5).collect(); + let read = |r: Rect, buf: &mut Vec| { + buf.clear(); + let (x0, x1) = ((r.x0 * n as i32) as usize, (r.x1 * n as i32) as usize); + let row = r.y0 as usize * src.width() as usize * n; + buf.extend_from_slice(&px[row + x0..row + x1]); + }; + let Some(boxes) = box_widths(&FilterParams::GaussianBlur { radius: 12.0 }) else { panic!("box passes") }; + let out = Rect::new(-5, 3, 155, 80); + let want = box_blur(src, &read, out, n, true, &boxes, &Interrupt::NONE).unwrap(); + let checks = AtomicUsize::new(0); + let count = || { + checks.fetch_add(1, Ordering::SeqCst); + false + }; + let got = box_blur(src, &read, out, n, true, &boxes, &Interrupt::cancel_only(&count)).unwrap(); + assert_eq!(got.len(), want.len()); + for ((ta, a), (tb, b)) in got.iter().zip(&want) { + assert_eq!(ta, tb); + assert!(a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits()), "strip {ta:?} differs"); + } + let total = checks.load(Ordering::SeqCst); + for k in (0..total).step_by((total / 40).max(1)) { + let seen = AtomicUsize::new(0); + let cancel = || seen.fetch_add(1, Ordering::SeqCst) >= k; + assert!(box_blur(src, &read, out, n, true, &boxes, &Interrupt::cancel_only(&cancel)).is_none(), "cancelled at check {k}"); + } +} From c602c47dbd4540633b8a9dea481624e355db8dec Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:03 +0000 Subject: [PATCH 016/259] refactor(algo): move content_aware.rs tests to content_aware/tests.rs --- crates/algo/src/content_aware.rs | 448 +------------------------ crates/algo/src/content_aware/tests.rs | 445 ++++++++++++++++++++++++ 2 files changed, 446 insertions(+), 447 deletions(-) create mode 100644 crates/algo/src/content_aware/tests.rs diff --git a/crates/algo/src/content_aware.rs b/crates/algo/src/content_aware.rs index 84b15a215b..955a911119 100644 --- a/crates/algo/src/content_aware.rs +++ b/crates/algo/src/content_aware.rs @@ -723,450 +723,4 @@ pub fn default_brush_size(hole: Rect) -> f64 { } #[cfg(test)] -mod tests { - use super::mosaic_size; - - fn blank(w: usize, h: usize) -> (usize, usize) { - (w, h) - } - - #[test] - fn a_thin_image_with_turned_variants_does_not_get_a_quadratic_mosaic() { - // 40000×1 plus its 90° copy (1×40000): about 1.6 billion mosaic cells for 80000 pixels. - assert_eq!(mosaic_size(40_000, 1, 8, &[blank(1, 40_000)]), None); - assert_eq!(mosaic_size(usize::MAX, 1, 8, &[blank(1, 1)]), None); - assert_eq!(mosaic_size(100, 100, 8, &[blank(100, 100)]), Some((208, 108))); - } - - use super::*; - - /// Vertical stripes (period 6) in grey, with a hole in the middle. - fn stripes(w: usize, h: usize) -> (Vec, Vec) { - let img: Vec = (0..w * h).map(|i| if (i % w) % 6 < 3 { 0.2 } else { 0.8 }).collect(); - let hole: Vec = (0..w * h).map(|i| (i % w).abs_diff(w / 2) < 4 && (i / w).abs_diff(h / 2) < 4).collect(); - (img, hole) - } - - #[test] - fn strokes_paint_their_path_and_leave_a_mismatched_mask_alone() { - let area = Rect::new(10, 20, 50, 40); - let (w, h) = (40, 20); - let strokes = [ - SamplingStroke { add: true, size: 6.0, points: vec![[12.0, 25.0], [40.0, 25.0], [45.0, 35.0]] }, - SamplingStroke { add: false, size: 3.0, points: vec![[30.0, 25.0]] }, - SamplingStroke { add: true, size: 2.0, points: Vec::new() }, - ]; - let mut mask = vec![false; w * h]; - paint_strokes(&mut mask, area, &strokes); - // The same pixels as testing every pixel against every segment of each stroke in turn. - let mut want = vec![false; w * h]; - for s in &strokes { - let r2 = (s.size / 2.0).max(0.5).powi(2); - let segs: Vec<_> = if s.points.len() == 1 { vec![(s.points[0], s.points[0])] } else { s.points.windows(2).map(|p| (p[0], p[1])).collect() }; - for (i, m) in want.iter_mut().enumerate() { - let c = [f64::from(area.x0) + (i % w) as f64 + 0.5, f64::from(area.y0) + (i / w) as f64 + 0.5]; - if segs.iter().any(|(a, b)| seg_dist2(c, *a, *b) <= r2) { - *m = s.add; - } - } - } - assert_eq!(mask, want); - assert!(mask[5 * w + 10] && !mask[5 * w + 20], "added along the path, cleared under the subtracting dab"); - // A mask shorter or longer than the area is not touched (and nothing panics). - for len in [0, 7, w * h - 1, w * h + 3] { - let mut short = vec![false; len]; - paint_strokes(&mut short, area, &strokes); - assert!(short.iter().all(|v| !v), "len {len}"); - } - // Hostile coordinates stay inside the area. - let mut m = vec![false; w * h]; - let wild = [SamplingStroke { add: true, size: 5000.0, points: vec![[f64::MAX, -1e300], [f64::NAN, 1e7]] }]; - paint_strokes(&mut m, area, &wild); - } - - #[test] - fn cancelled_fill_stops_and_progress_reaches_one() { - use std::sync::atomic::{AtomicU32, Ordering}; - let (w, h) = (60, 40); - let (img, hole) = stripes(w, h); - let source = vec![true; w * h]; - let yes = || true; - let cancelled = photocraft_raster::Interrupt::cancel_only(&yes); - assert!(fill_with(w, h, 1, &img, &hole, &source, &FillOptions::default(), &cancelled).is_err()); - let last = AtomicU32::new(0); - let no = || false; - let progress = |f: f32| { - assert!(f >= f32::from_bits(last.load(Ordering::Relaxed)), "progress went backwards"); - last.store(f.to_bits(), Ordering::Relaxed); - }; - let out = fill_with(w, h, 1, &img, &hole, &source, &FillOptions::default(), &photocraft_raster::Interrupt::new(&no, &progress)).unwrap(); - assert_eq!(f32::from_bits(last.load(Ordering::Relaxed)), 1.0); - assert_eq!(out, fill(w, h, 1, &img, &hole, &source, &FillOptions::default()), "same result as the plain fill"); - } - - #[test] - fn filling_in_place_is_filling_a_copy() { - let (w, h) = (90, 70); - let rgb: Vec = noise(w, h, 4).iter().enumerate().map(|(i, v)| v * 0.5 + 0.3 * ((i / 3 % w) % 11 < 5) as u8 as f32).collect(); - let hole: Vec = (0..w * h).map(|i| (30..52).contains(&(i % w)) && (25..44).contains(&(i / w))).collect(); - let source: Vec = (0..w * h).map(|i| i % w < 75).collect(); - let none = Interrupt::NONE; - for opts in [FillOptions::default(), FillOptions { color_adaptation: Adapt::NONE, mirror: true, ..Default::default() }] { - let copy = fill_with(w, h, 3, &rgb, &hole, &source, &opts, &none).unwrap(); - let owned = fill_owned(w, h, 3, rgb.clone(), &hole, &source, &opts, &none).unwrap(); - assert_eq!(copy.iter().map(|v| v.to_bits()).collect::>(), owned.iter().map(|v| v.to_bits()).collect::>()); - // Only the hole changes. - assert!((0..w * h).all(|i| hole[i] || (0..3).all(|c| owned[i * 3 + c].to_bits() == rgb[i * 3 + c].to_bits()))); - } - // Nothing to copy from: the membrane, either way. - let nowhere = vec![false; w * h]; - let copy = fill_with(w, h, 3, &rgb, &hole, &nowhere, &FillOptions::default(), &none).unwrap(); - assert_eq!(copy, fill_owned(w, h, 3, rgb.clone(), &hole, &nowhere, &FillOptions::default(), &none).unwrap()); - } - - #[test] - fn auto_sampling_can_be_cancelled() { - let (w, h) = (200, 160); - let img: Vec = noise(w, h, 5).iter().enumerate().map(|(i, v)| v * 0.1 + if (i / 3) % w < 120 { 0.3 } else { 0.6 }).collect(); - let hole: Vec = (0..w * h).map(|i| (80..110).contains(&(i % w)) && (60..90).contains(&(i / w))).collect(); - let yes = || true; - assert!(auto_sampling_with(w, h, 3, &img, &hole, &Interrupt::cancel_only(&yes)).is_err()); - assert_eq!(auto_sampling_with(w, h, 3, &img, &hole, &Interrupt::NONE).unwrap(), auto_sampling(w, h, 3, &img, &hole)); - } - - #[test] - fn fills_only_the_hole_with_known_texture() { - let (w, h) = (48, 32); - let (img, hole) = stripes(w, h); - let src = vec![true; w * h]; - let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() }); - for i in 0..w * h { - if !hole[i] { - assert_eq!(out[i], img[i]); - } - } - // The hole is filled with stripe values, not a flat average. - let vals: Vec = (0..w * h).filter(|i| hole[*i]).map(|i| out[i]).collect(); - assert!(vals.iter().any(|v| *v < 0.35) && vals.iter().any(|v| *v > 0.65), "{vals:?}"); - } - - #[test] - fn sampling_area_restricts_sources() { - // Left half dark, right half bright; sampling only the right half fills bright. - let (w, h) = (40, 20); - let img: Vec = (0..w * h).map(|i| if i % w < 20 { 0.1 } else { 0.9 }).collect(); - let hole: Vec = (0..w * h).map(|i| (16..24).contains(&(i % w)) && (6..14).contains(&(i / w))).collect(); - let right: Vec = (0..w * h).map(|i| i % w >= 24).collect(); - let out = fill(w, h, 1, &img, &hole, &right, &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() }); - let mean: f32 = (0..w * h).filter(|i| hole[*i]).map(|i| out[i]).sum::() / 64.0; - assert!(mean > 0.8, "mean {mean}"); - } - - #[test] - fn adaptations_run_and_stay_deterministic() { - let (w, h) = (32, 24); - let (img, hole) = stripes(w, h); - let rgb: Vec = img.iter().flat_map(|v| [*v, *v * 0.5, 1.0 - *v]).collect(); - let src = vec![true; w * h]; - let opts = FillOptions { color_adaptation: color_level("high"), rotations: rotation_level("low"), scale: true, mirror: true, seed: 7 }; - let a = fill(w, h, 3, &rgb, &hole, &src, &opts); - let b = fill(w, h, 3, &rgb, &hole, &src, &opts); - assert_eq!(a, b); - assert!(a.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))); - } - - #[test] - fn color_adaptation_follows_a_gradient() { - // A horizontal brightness ramp with a hole: adaptation keeps the fill near the ramp. - let (w, h) = (40, 20); - let img: Vec = (0..w * h).map(|i| (i % w) as f32 / w as f32).collect(); - let hole: Vec = (0..w * h).map(|i| (14..26).contains(&(i % w)) && (5..15).contains(&(i / w))).collect(); - let src = vec![true; w * h]; - let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: color_level("veryHigh"), ..Default::default() }); - let err: f32 = (0..w * h).filter(|i| hole[*i]).map(|i| (out[i] - img[i]).abs()).sum::() / 120.0; - assert!(err < 0.12, "mean error {err}"); - } - - /// A vertical sky gradient (each row one colour) filled at every adaptation level stays the - /// gradient: no tinted blotch where the copied rows' colours were shifted per channel. - #[test] - fn color_adaptation_leaves_a_smooth_gradient_untinted() { - let (w, h) = (120, 60); - let row = |y: usize| { - let t = y as f32 / (h - 1) as f32; - [0.27 + 0.45 * t, 0.53 + 0.32 * t, 0.86 + 0.1 * t] - }; - let img: Vec = (0..w * h).flat_map(|i| row(i / w)).collect(); - let hole: Vec = (0..w * h).map(|i| (50..70).contains(&(i % w)) && (20..40).contains(&(i / w))).collect(); - let src = vec![true; w * h]; - for level in ["none", "default", "high", "veryHigh"] { - let out = fill(w, h, 3, &img, &hole, &src, &FillOptions { color_adaptation: color_level(level), ..Default::default() }); - let (out, img) = (&out, &img); - let worst = (0..w * h).filter(|i| hole[*i]).flat_map(|i| (0..3).map(move |c| (out[i * 3 + c] - img[i * 3 + c]).abs())).fold(0.0f32, f32::max); - assert!(worst < 3.0 / 255.0, "{level}: off by {}", worst * 255.0); - } - } - - /// I.i.d. noise: every value occurs once, so a filled pixel equal to an image pixel was copied. - fn noise(w: usize, h: usize, seed: u64) -> Vec { - let mut z = seed; - (0..w * h * 3) - .map(|_| { - z = z.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - 0.2 + 0.6 * ((z >> 40) as f32 / (1u64 << 24) as f32) - }) - .collect() - } - - #[test] - fn sampling_window_is_photoshops() { - let canvas = Rect::new(0, 0, 800, 800); - let sq = |x0: i32, y0: i32, w: i32, h: i32| Rect::new(x0, y0, x0 + w, y0 + h); - // Photoshop 25.4's sampling overlay: a square of side 4·√(max(w,50)·max(h,50)) centred on - // the selection's bounds. - assert_eq!(sampling_window(sq(375, 375, 50, 50), canvas), sq(300, 300, 200, 200)); - assert_eq!(sampling_window(sq(350, 350, 100, 100), canvas), sq(200, 200, 400, 400)); - assert_eq!(sampling_window(sq(395, 395, 10, 10), canvas), sq(300, 300, 200, 200)); - assert_eq!(sampling_window(sq(370, 370, 60, 60), canvas), sq(280, 280, 240, 240)); - // Long selections (Photoshop's overlay, read off the screen to a pixel: 281, 399, 691). - assert_eq!(sampling_window(sq(350, 385, 100, 30), canvas), sq(258, 258, 283, 283)); - assert_eq!(sampling_window(sq(300, 375, 200, 50), canvas), sq(200, 200, 400, 400)); - assert_eq!(sampling_window(sq(250, 350, 300, 100), canvas), sq(53, 53, 693, 693)); - // At the canvas edge the square slides inwards rather than being cut. - assert_eq!(sampling_window(sq(10, 375, 50, 50), canvas), sq(0, 300, 200, 200)); - assert_eq!(sampling_window(sq(5, 5, 60, 60), canvas), sq(0, 0, 240, 240)); - // A canvas smaller than the square clips it; a very long selection keeps its length. - assert_eq!(sampling_window(sq(40, 40, 50, 50), Rect::new(0, 0, 150, 120)), Rect::new(0, 0, 150, 120)); - assert_eq!(sampling_window(sq(100, 995, 1800, 10), Rect::new(0, 0, 2000, 2000)), sq(100, 400, 1800, 1200)); - assert_eq!(sampling_window(Rect::EMPTY, canvas), Rect::EMPTY); - } - - #[test] - fn auto_sampling_keeps_what_looks_like_the_surroundings() { - // Grey texture, dark on the left, 50 levels brighter on the right; the hole is in the dark - // part near the boundary (Photoshop's Auto leaves the bright part out). - let (w, h) = (200, 200); - let tex = noise(w, h, 3); - let shade = |x: usize, band: bool| { - if band { - if (130..150).contains(&x) { 0.55 } else { 0.35 } - } else if x < 135 { - 0.35 - } else { - 0.55 - } - }; - for band in [false, true] { - let img: Vec = (0..w * h * 3).map(|i| shade((i / 3) % w, band) + (tex[i] - 0.5) * 0.1).collect(); - let hole: Vec = (0..w * h).map(|i| (75..125).contains(&(i % w)) && (75..125).contains(&(i / w))).collect(); - let area = auto_sampling(w, h, 3, &img, &hole); - let frac = |x0: usize, x1: usize| { - let n = (0..w * h).filter(|i| (x0..x1).contains(&(i % w)) && !hole[*i]).count(); - (0..w * h).filter(|i| (x0..x1).contains(&(i % w)) && area[*i]).count() as f32 / n as f32 - }; - assert!(hole.iter().zip(&area).all(|(hl, a)| !(*hl && *a)), "never the hole"); - assert!(frac(0, 125) > 0.95, "the dark side is sampled ({})", frac(0, 125)); - if band { - // A bright band through the window is left out; the dark area beyond it is not. - assert!(frac(133, 147) < 0.05, "the band is excluded ({})", frac(133, 147)); - assert!(frac(155, 200) > 0.9, "beyond the band is sampled ({})", frac(155, 200)); - } else { - assert!(frac(140, 200) < 0.05, "the bright side is excluded ({})", frac(140, 200)); - } - } - } - - #[test] - fn auto_sampling_keeps_the_surroundings_of_every_part_of_a_thin_selection() { - // A long thin selection across a grey ramp, and a small knob selected with it in a red - // corner. Each part keeps its own surroundings; a compact selection is unchanged. - let (w, h) = (900, 600); - let tex = noise(w, h, 4); - let img: Vec = (0..w * h * 3) - .map(|i| { - let (x, y, c) = ((i / 3) % w, (i / 3) / w, i % 3); - let base = if x > 690 && y > 420 { [0.7, 0.25, 0.2][c] } else { 0.2 + 0.5 * x as f32 / w as f32 }; - base + (tex[i] - 0.5) * 0.04 - }) - .collect(); - let line = |i: usize| (30..870).contains(&(i % w)) && (180..192).contains(&(i / w)); - let knob = |i: usize| ((i % w) as f32 - 795.0).hypot((i / w) as f32 - 510.0) < 10.0; - let hole: Vec = (0..w * h).map(|i| line(i) || knob(i)).collect(); - let area = auto_sampling(w, h, 3, &img, &hole); - let around_knob = (0..w * h).filter(|&i| !hole[i] && ((i % w) as f32 - 795.0).hypot((i / w) as f32 - 510.0) < 24.0); - let (n, kept) = around_knob.fold((0, 0), |(n, k), i| (n + 1, k + usize::from(area[i]))); - assert!(kept as f32 > 0.9 * n as f32, "{kept} of {n} pixels around the knob"); - assert!(thin_band(w, h, &hole) >= 20.0, "{}", thin_band(w, h, &hole)); - let disc: Vec = (0..w * h).map(|i| ((i % w) as f32 - 450.0).hypot((i / w) as f32 - 300.0) < 90.0).collect(); - assert_eq!(thin_band(w, h, &disc), 1.5); - } - - #[test] - fn without_colour_adaptation_the_fill_copies_pixels_exactly() { - // A smooth texture with fine noise, so that every value is unique: a filled pixel equal to - // an image pixel was copied from it. Photoshop's fill (colour adaptation None) is such - // copies, joined by narrow seams. - let (w, h) = (120, 120); - let fine = noise(w, h, 9); - let img: Vec = (0..w * h * 3) - .map(|i| { - let (x, y, c) = (((i / 3) % w) as f32, ((i / 3) / w) as f32, i % 3); - 0.5 + 0.2 * (x * 0.21 + c as f32).sin() * (y * 0.17).cos() + 0.1 * (x * 0.05 - y * 0.08).sin() + (fine[i] - 0.5) * 0.08 - }) - .collect(); - let hole: Vec = (0..w * h).map(|i| (40..80).contains(&(i % w)) && (40..80).contains(&(i / w))).collect(); - // Votes of identical copies average to the copy up to float rounding. - let key = |v: &[f32], i: usize| [0, 1, 2].map(|c| (v[i * 3 + c] * 1e5).round() as i64); - let known: std::collections::HashSet<[i64; 3]> = (0..w * h).filter(|i| !hole[*i]).map(|i| key(&img, i)).collect(); - let out = fill(w, h, 3, &img, &hole, &vec![true; w * h], &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() }); - let exact = (0..w * h).filter(|i| hole[*i] && known.contains(&key(&out, *i))).count(); - assert!(exact as f32 > 0.2 * 1600.0, "{exact} of 1600 filled pixels are exact copies"); - // And the fill is as busy as the noise around it, not a blur of it. - let lap = |v: &[f32], x: usize, y: usize| { - let p = |x: usize, y: usize| v[(y * w + x) * 3]; - (4.0 * p(x, y) - p(x - 1, y) - p(x + 1, y) - p(x, y - 1) - p(x, y + 1)).abs() - }; - let mean = |inside: bool| { - let pts: Vec<(usize, usize)> = (1..h - 1).flat_map(|y| (1..w - 1).map(move |x| (x, y))).filter(|&(x, y)| hole[y * w + x] == inside).collect(); - pts.iter().map(|&(x, y)| lap(&out, x, y)).sum::() / pts.len() as f32 - }; - assert!(mean(true) > 0.6 * mean(false), "fill detail {} against {}", mean(true), mean(false)); - } - - #[test] - fn patch_color_shifts_up_to_about_four_hundredths_per_step() { - // Content 0.4 brighter than where it lands (Photoshop's Patch, Color 3 and 10). - let from: Vec = (0..300).map(|i| 0.7 + 0.05 * ((i % 7) as f32 / 7.0)).collect(); - let to: Vec = from.iter().map(|v| v - 0.4).collect(); - let level = from.iter().sum::() / 300.0; - let shift = |c: u8| { - let gb = level_transform(1, &from, &to, color_amount(c)); - level - from.iter().map(|v| gb[0].0 * v + gb[0].1).sum::() / 300.0 - }; - assert_eq!(shift(0), 0.0); - assert!((shift(3) - 0.12).abs() < 0.01, "{}", shift(3)); - assert!((shift(10) - 0.4).abs() < 0.01, "{}", shift(10)); - } - - /// A soft background (gradients, broad out-of-focus blobs of colour, fine noise) with thin, long bright - /// objects over it: three coiled strings 3 to 7 px wide and two straighter ones, each with an - /// anti-aliased edge and a faint halo. Returns the image; what removing the coils should give - /// (the background and the straighter strings, which stay); and the selection a user would draw - /// around the coils, `margin` px wide. - fn strings_scene(w: usize, h: usize, margin: f32) -> (Vec, Vec, Vec) { - let fine = noise(w, h, 11); - // Out-of-focus colour: broad blobs over two gradients. - let blob = noise(3, 3, 5); - let bg: Vec = (0..w * h * 3) - .map(|i| { - let (x, y, c) = (((i / 3) % w) as f32 / w as f32, ((i / 3) / w) as f32 / h as f32, i % 3); - let mut v = [0.18 + 0.25 * x, 0.22 + 0.1 * y, 0.3 - 0.1 * x][c]; - for b in blob.as_chunks::<3>().0 { - let (bx, by, s) = (b[0] * 1.6 - 0.3, b[1] * 1.6 - 0.3, 0.1 + 0.25 * b[2]); - v += (b[(c + 1) % 3] - 0.2) * 0.5 * (-((x - bx).powi(2) + (y - by).powi(2) * 0.56) / (2.0 * s * s)).exp(); - } - v + (fine[i] - 0.5) * 0.03 - }) - .collect(); - // Signed distance to each object's surface, stamped from points along it. - let stamp = |sd: &mut [f32], pts: &mut dyn Iterator, half: f32| { - for (px, py) in pts { - let reach = (half + 4.0) as i32 + 1; - for dy in -reach..=reach { - for dx in -reach..=reach { - let (x, y) = (px as i32 + dx, py as i32 + dy); - if x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h { - let i = y as usize * w + x as usize; - sd[i] = sd[i].min((x as f32 - px).hypot(y as f32 - py) - half); - } - } - } - } - }; - let mut coils = vec![f32::INFINITY; w * h]; - for (k, half) in [1.5f32, 2.5, 3.5].into_iter().enumerate() { - let (y0, r) = ((0.22 + 0.28 * k as f32) * h as f32, 10.0 + 2.0 * k as f32); - let mut pts = (0..4000).map(|j| { - let t = j as f32 / 4000.0; - let a = 8.0 * std::f32::consts::TAU * t; - (18.0 + t * (w as f32 - 60.0) + r * a.cos(), y0 + 6.0 * (6.0 * t).sin() + 0.7 * r * a.sin()) - }); - stamp(&mut coils, &mut pts, half); - } - let mut straight = vec![f32::INFINITY; w * h]; - for y in [0.07, 0.93] { - stamp(&mut straight, &mut (0..2000).map(|j| (j as f32 / 2000.0 * w as f32, y * h as f32 + 3.0 * (j as f32 / 300.0).sin())), 2.0); - } - let draw = |base: &[f32], sd: &[f32]| -> Vec { - let mut img = base.to_vec(); - for i in 0..w * h { - let cover = (0.5 - sd[i]).clamp(0.0, 1.0); - let halo = if sd[i] > 0.0 { 0.08 * (-sd[i] * sd[i] / 2.9).exp() } else { 0.0 }; - for (c, metal) in [0.9f32, 0.85, 0.7].into_iter().enumerate() { - let v = &mut img[i * 3 + c]; - *v = *v * (1.0 - cover) + metal * cover + halo * (1.0 - cover); - } - } - img - }; - let clean = draw(&bg, &straight); - let both: Vec = coils.iter().zip(&straight).map(|(a, b)| a.min(*b)).collect(); - let img = draw(&bg, &both); - let hole = coils.iter().map(|d| *d <= margin).collect(); - (img, clean, hole) - } - - /// RMS over the hole of the error averaged over 7 × 7 pixels (in levels of 255): the noise - /// cancels out, a ghost of the removed outline or a blotch of another shade does not. - fn blotch_error(w: usize, h: usize, out: &[f32], clean: &[f32], hole: &[bool]) -> f32 { - let (mut sum, mut n) = (0.0f64, 0usize); - for y in 3..h - 3 { - for x in 3..w - 3 { - if !hole[y * w + x] { - continue; - } - let mut e = [0.0f32; 3]; - for j in (y - 3..=y + 3).flat_map(|yy| (x - 3..=x + 3).map(move |xx| yy * w + xx)) { - for (c, ec) in e.iter_mut().enumerate() { - *ec += out[j * 3 + c] - clean[j * 3 + c]; - } - } - sum += f64::from(e.iter().map(|v| (v / 49.0).powi(2)).sum::() / 3.0); - n += 1; - } - } - ((sum / n.max(1) as f64).sqrt() * 255.0) as f32 - } - - /// Removing thin, long objects (guitar strings, wires) from a soft background (#1366): the - /// fill is the background, with no ghost of their outline and nothing of their colour copied - /// back in. Their selection is long but only a few pixels thick, so the fill is worked out at - /// a scale where it is still a few pixels thick rather than one where the strings' surroundings - /// have merged into a blur. - #[test] - fn thin_objects_leave_no_ghost_and_none_of_their_colour() { - let (w, h) = (360, 270); - let (img, clean, hole) = strings_scene(w, h, 2.0); - let source = auto_sampling(w, h, 3, &img, &hole); - let out = fill(w, h, 3, &img, &hole, &source, &FillOptions::default()); - let blotch = blotch_error(w, h, &out, &clean, &hole); - let luma = |v: &[f32], i: usize| (v[i * 3] + v[i * 3 + 1] + v[i * 3 + 2]) / 3.0; - let bright = (0..w * h).filter(|&i| hole[i] && luma(&out, i) > luma(&clean, i) + 0.06).count(); - // Before #1366 the outlines stayed as darker and lighter blotches (13 levels of 255) and - // 1121 pixels took the strings' colour. - assert!(blotch < 2.5, "ghosts and blotches: {blotch:.2} levels of 255"); - assert_eq!(bright, 0, "filled pixels with the strings' colour"); - } - - #[test] - fn variant_geometry() { - let img = vec![0.5f32; 10 * 6]; - let ok = vec![true; 60]; - let src = Src { w: 10, h: 6, ch: 1, img: &img, ok: &ok }; - let v = variant(src, 90.0, 1.0, false, &Interrupt::NONE).unwrap(); - assert_eq!((v.w, v.h), (6, 10)); - let v = variant(src, 0.0, 0.8, true, &Interrupt::NONE).unwrap(); - assert_eq!((v.w, v.h), (8, 5)); - assert!(v.ok.iter().filter(|o| **o).count() > 20); - } -} +mod tests; diff --git a/crates/algo/src/content_aware/tests.rs b/crates/algo/src/content_aware/tests.rs new file mode 100644 index 0000000000..183e6e5b88 --- /dev/null +++ b/crates/algo/src/content_aware/tests.rs @@ -0,0 +1,445 @@ +use super::mosaic_size; + +fn blank(w: usize, h: usize) -> (usize, usize) { + (w, h) +} + +#[test] +fn a_thin_image_with_turned_variants_does_not_get_a_quadratic_mosaic() { + // 40000×1 plus its 90° copy (1×40000): about 1.6 billion mosaic cells for 80000 pixels. + assert_eq!(mosaic_size(40_000, 1, 8, &[blank(1, 40_000)]), None); + assert_eq!(mosaic_size(usize::MAX, 1, 8, &[blank(1, 1)]), None); + assert_eq!(mosaic_size(100, 100, 8, &[blank(100, 100)]), Some((208, 108))); +} + +use super::*; + +/// Vertical stripes (period 6) in grey, with a hole in the middle. +fn stripes(w: usize, h: usize) -> (Vec, Vec) { + let img: Vec = (0..w * h).map(|i| if (i % w) % 6 < 3 { 0.2 } else { 0.8 }).collect(); + let hole: Vec = (0..w * h).map(|i| (i % w).abs_diff(w / 2) < 4 && (i / w).abs_diff(h / 2) < 4).collect(); + (img, hole) +} + +#[test] +fn strokes_paint_their_path_and_leave_a_mismatched_mask_alone() { + let area = Rect::new(10, 20, 50, 40); + let (w, h) = (40, 20); + let strokes = [ + SamplingStroke { add: true, size: 6.0, points: vec![[12.0, 25.0], [40.0, 25.0], [45.0, 35.0]] }, + SamplingStroke { add: false, size: 3.0, points: vec![[30.0, 25.0]] }, + SamplingStroke { add: true, size: 2.0, points: Vec::new() }, + ]; + let mut mask = vec![false; w * h]; + paint_strokes(&mut mask, area, &strokes); + // The same pixels as testing every pixel against every segment of each stroke in turn. + let mut want = vec![false; w * h]; + for s in &strokes { + let r2 = (s.size / 2.0).max(0.5).powi(2); + let segs: Vec<_> = if s.points.len() == 1 { vec![(s.points[0], s.points[0])] } else { s.points.windows(2).map(|p| (p[0], p[1])).collect() }; + for (i, m) in want.iter_mut().enumerate() { + let c = [f64::from(area.x0) + (i % w) as f64 + 0.5, f64::from(area.y0) + (i / w) as f64 + 0.5]; + if segs.iter().any(|(a, b)| seg_dist2(c, *a, *b) <= r2) { + *m = s.add; + } + } + } + assert_eq!(mask, want); + assert!(mask[5 * w + 10] && !mask[5 * w + 20], "added along the path, cleared under the subtracting dab"); + // A mask shorter or longer than the area is not touched (and nothing panics). + for len in [0, 7, w * h - 1, w * h + 3] { + let mut short = vec![false; len]; + paint_strokes(&mut short, area, &strokes); + assert!(short.iter().all(|v| !v), "len {len}"); + } + // Hostile coordinates stay inside the area. + let mut m = vec![false; w * h]; + let wild = [SamplingStroke { add: true, size: 5000.0, points: vec![[f64::MAX, -1e300], [f64::NAN, 1e7]] }]; + paint_strokes(&mut m, area, &wild); +} + +#[test] +fn cancelled_fill_stops_and_progress_reaches_one() { + use std::sync::atomic::{AtomicU32, Ordering}; + let (w, h) = (60, 40); + let (img, hole) = stripes(w, h); + let source = vec![true; w * h]; + let yes = || true; + let cancelled = photocraft_raster::Interrupt::cancel_only(&yes); + assert!(fill_with(w, h, 1, &img, &hole, &source, &FillOptions::default(), &cancelled).is_err()); + let last = AtomicU32::new(0); + let no = || false; + let progress = |f: f32| { + assert!(f >= f32::from_bits(last.load(Ordering::Relaxed)), "progress went backwards"); + last.store(f.to_bits(), Ordering::Relaxed); + }; + let out = fill_with(w, h, 1, &img, &hole, &source, &FillOptions::default(), &photocraft_raster::Interrupt::new(&no, &progress)).unwrap(); + assert_eq!(f32::from_bits(last.load(Ordering::Relaxed)), 1.0); + assert_eq!(out, fill(w, h, 1, &img, &hole, &source, &FillOptions::default()), "same result as the plain fill"); +} + +#[test] +fn filling_in_place_is_filling_a_copy() { + let (w, h) = (90, 70); + let rgb: Vec = noise(w, h, 4).iter().enumerate().map(|(i, v)| v * 0.5 + 0.3 * ((i / 3 % w) % 11 < 5) as u8 as f32).collect(); + let hole: Vec = (0..w * h).map(|i| (30..52).contains(&(i % w)) && (25..44).contains(&(i / w))).collect(); + let source: Vec = (0..w * h).map(|i| i % w < 75).collect(); + let none = Interrupt::NONE; + for opts in [FillOptions::default(), FillOptions { color_adaptation: Adapt::NONE, mirror: true, ..Default::default() }] { + let copy = fill_with(w, h, 3, &rgb, &hole, &source, &opts, &none).unwrap(); + let owned = fill_owned(w, h, 3, rgb.clone(), &hole, &source, &opts, &none).unwrap(); + assert_eq!(copy.iter().map(|v| v.to_bits()).collect::>(), owned.iter().map(|v| v.to_bits()).collect::>()); + // Only the hole changes. + assert!((0..w * h).all(|i| hole[i] || (0..3).all(|c| owned[i * 3 + c].to_bits() == rgb[i * 3 + c].to_bits()))); + } + // Nothing to copy from: the membrane, either way. + let nowhere = vec![false; w * h]; + let copy = fill_with(w, h, 3, &rgb, &hole, &nowhere, &FillOptions::default(), &none).unwrap(); + assert_eq!(copy, fill_owned(w, h, 3, rgb.clone(), &hole, &nowhere, &FillOptions::default(), &none).unwrap()); +} + +#[test] +fn auto_sampling_can_be_cancelled() { + let (w, h) = (200, 160); + let img: Vec = noise(w, h, 5).iter().enumerate().map(|(i, v)| v * 0.1 + if (i / 3) % w < 120 { 0.3 } else { 0.6 }).collect(); + let hole: Vec = (0..w * h).map(|i| (80..110).contains(&(i % w)) && (60..90).contains(&(i / w))).collect(); + let yes = || true; + assert!(auto_sampling_with(w, h, 3, &img, &hole, &Interrupt::cancel_only(&yes)).is_err()); + assert_eq!(auto_sampling_with(w, h, 3, &img, &hole, &Interrupt::NONE).unwrap(), auto_sampling(w, h, 3, &img, &hole)); +} + +#[test] +fn fills_only_the_hole_with_known_texture() { + let (w, h) = (48, 32); + let (img, hole) = stripes(w, h); + let src = vec![true; w * h]; + let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() }); + for i in 0..w * h { + if !hole[i] { + assert_eq!(out[i], img[i]); + } + } + // The hole is filled with stripe values, not a flat average. + let vals: Vec = (0..w * h).filter(|i| hole[*i]).map(|i| out[i]).collect(); + assert!(vals.iter().any(|v| *v < 0.35) && vals.iter().any(|v| *v > 0.65), "{vals:?}"); +} + +#[test] +fn sampling_area_restricts_sources() { + // Left half dark, right half bright; sampling only the right half fills bright. + let (w, h) = (40, 20); + let img: Vec = (0..w * h).map(|i| if i % w < 20 { 0.1 } else { 0.9 }).collect(); + let hole: Vec = (0..w * h).map(|i| (16..24).contains(&(i % w)) && (6..14).contains(&(i / w))).collect(); + let right: Vec = (0..w * h).map(|i| i % w >= 24).collect(); + let out = fill(w, h, 1, &img, &hole, &right, &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() }); + let mean: f32 = (0..w * h).filter(|i| hole[*i]).map(|i| out[i]).sum::() / 64.0; + assert!(mean > 0.8, "mean {mean}"); +} + +#[test] +fn adaptations_run_and_stay_deterministic() { + let (w, h) = (32, 24); + let (img, hole) = stripes(w, h); + let rgb: Vec = img.iter().flat_map(|v| [*v, *v * 0.5, 1.0 - *v]).collect(); + let src = vec![true; w * h]; + let opts = FillOptions { color_adaptation: color_level("high"), rotations: rotation_level("low"), scale: true, mirror: true, seed: 7 }; + let a = fill(w, h, 3, &rgb, &hole, &src, &opts); + let b = fill(w, h, 3, &rgb, &hole, &src, &opts); + assert_eq!(a, b); + assert!(a.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))); +} + +#[test] +fn color_adaptation_follows_a_gradient() { + // A horizontal brightness ramp with a hole: adaptation keeps the fill near the ramp. + let (w, h) = (40, 20); + let img: Vec = (0..w * h).map(|i| (i % w) as f32 / w as f32).collect(); + let hole: Vec = (0..w * h).map(|i| (14..26).contains(&(i % w)) && (5..15).contains(&(i / w))).collect(); + let src = vec![true; w * h]; + let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: color_level("veryHigh"), ..Default::default() }); + let err: f32 = (0..w * h).filter(|i| hole[*i]).map(|i| (out[i] - img[i]).abs()).sum::() / 120.0; + assert!(err < 0.12, "mean error {err}"); +} + +/// A vertical sky gradient (each row one colour) filled at every adaptation level stays the +/// gradient: no tinted blotch where the copied rows' colours were shifted per channel. +#[test] +fn color_adaptation_leaves_a_smooth_gradient_untinted() { + let (w, h) = (120, 60); + let row = |y: usize| { + let t = y as f32 / (h - 1) as f32; + [0.27 + 0.45 * t, 0.53 + 0.32 * t, 0.86 + 0.1 * t] + }; + let img: Vec = (0..w * h).flat_map(|i| row(i / w)).collect(); + let hole: Vec = (0..w * h).map(|i| (50..70).contains(&(i % w)) && (20..40).contains(&(i / w))).collect(); + let src = vec![true; w * h]; + for level in ["none", "default", "high", "veryHigh"] { + let out = fill(w, h, 3, &img, &hole, &src, &FillOptions { color_adaptation: color_level(level), ..Default::default() }); + let (out, img) = (&out, &img); + let worst = (0..w * h).filter(|i| hole[*i]).flat_map(|i| (0..3).map(move |c| (out[i * 3 + c] - img[i * 3 + c]).abs())).fold(0.0f32, f32::max); + assert!(worst < 3.0 / 255.0, "{level}: off by {}", worst * 255.0); + } +} + +/// I.i.d. noise: every value occurs once, so a filled pixel equal to an image pixel was copied. +fn noise(w: usize, h: usize, seed: u64) -> Vec { + let mut z = seed; + (0..w * h * 3) + .map(|_| { + z = z.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + 0.2 + 0.6 * ((z >> 40) as f32 / (1u64 << 24) as f32) + }) + .collect() +} + +#[test] +fn sampling_window_is_photoshops() { + let canvas = Rect::new(0, 0, 800, 800); + let sq = |x0: i32, y0: i32, w: i32, h: i32| Rect::new(x0, y0, x0 + w, y0 + h); + // Photoshop 25.4's sampling overlay: a square of side 4·√(max(w,50)·max(h,50)) centred on + // the selection's bounds. + assert_eq!(sampling_window(sq(375, 375, 50, 50), canvas), sq(300, 300, 200, 200)); + assert_eq!(sampling_window(sq(350, 350, 100, 100), canvas), sq(200, 200, 400, 400)); + assert_eq!(sampling_window(sq(395, 395, 10, 10), canvas), sq(300, 300, 200, 200)); + assert_eq!(sampling_window(sq(370, 370, 60, 60), canvas), sq(280, 280, 240, 240)); + // Long selections (Photoshop's overlay, read off the screen to a pixel: 281, 399, 691). + assert_eq!(sampling_window(sq(350, 385, 100, 30), canvas), sq(258, 258, 283, 283)); + assert_eq!(sampling_window(sq(300, 375, 200, 50), canvas), sq(200, 200, 400, 400)); + assert_eq!(sampling_window(sq(250, 350, 300, 100), canvas), sq(53, 53, 693, 693)); + // At the canvas edge the square slides inwards rather than being cut. + assert_eq!(sampling_window(sq(10, 375, 50, 50), canvas), sq(0, 300, 200, 200)); + assert_eq!(sampling_window(sq(5, 5, 60, 60), canvas), sq(0, 0, 240, 240)); + // A canvas smaller than the square clips it; a very long selection keeps its length. + assert_eq!(sampling_window(sq(40, 40, 50, 50), Rect::new(0, 0, 150, 120)), Rect::new(0, 0, 150, 120)); + assert_eq!(sampling_window(sq(100, 995, 1800, 10), Rect::new(0, 0, 2000, 2000)), sq(100, 400, 1800, 1200)); + assert_eq!(sampling_window(Rect::EMPTY, canvas), Rect::EMPTY); +} + +#[test] +fn auto_sampling_keeps_what_looks_like_the_surroundings() { + // Grey texture, dark on the left, 50 levels brighter on the right; the hole is in the dark + // part near the boundary (Photoshop's Auto leaves the bright part out). + let (w, h) = (200, 200); + let tex = noise(w, h, 3); + let shade = |x: usize, band: bool| { + if band { + if (130..150).contains(&x) { 0.55 } else { 0.35 } + } else if x < 135 { + 0.35 + } else { + 0.55 + } + }; + for band in [false, true] { + let img: Vec = (0..w * h * 3).map(|i| shade((i / 3) % w, band) + (tex[i] - 0.5) * 0.1).collect(); + let hole: Vec = (0..w * h).map(|i| (75..125).contains(&(i % w)) && (75..125).contains(&(i / w))).collect(); + let area = auto_sampling(w, h, 3, &img, &hole); + let frac = |x0: usize, x1: usize| { + let n = (0..w * h).filter(|i| (x0..x1).contains(&(i % w)) && !hole[*i]).count(); + (0..w * h).filter(|i| (x0..x1).contains(&(i % w)) && area[*i]).count() as f32 / n as f32 + }; + assert!(hole.iter().zip(&area).all(|(hl, a)| !(*hl && *a)), "never the hole"); + assert!(frac(0, 125) > 0.95, "the dark side is sampled ({})", frac(0, 125)); + if band { + // A bright band through the window is left out; the dark area beyond it is not. + assert!(frac(133, 147) < 0.05, "the band is excluded ({})", frac(133, 147)); + assert!(frac(155, 200) > 0.9, "beyond the band is sampled ({})", frac(155, 200)); + } else { + assert!(frac(140, 200) < 0.05, "the bright side is excluded ({})", frac(140, 200)); + } + } +} + +#[test] +fn auto_sampling_keeps_the_surroundings_of_every_part_of_a_thin_selection() { + // A long thin selection across a grey ramp, and a small knob selected with it in a red + // corner. Each part keeps its own surroundings; a compact selection is unchanged. + let (w, h) = (900, 600); + let tex = noise(w, h, 4); + let img: Vec = (0..w * h * 3) + .map(|i| { + let (x, y, c) = ((i / 3) % w, (i / 3) / w, i % 3); + let base = if x > 690 && y > 420 { [0.7, 0.25, 0.2][c] } else { 0.2 + 0.5 * x as f32 / w as f32 }; + base + (tex[i] - 0.5) * 0.04 + }) + .collect(); + let line = |i: usize| (30..870).contains(&(i % w)) && (180..192).contains(&(i / w)); + let knob = |i: usize| ((i % w) as f32 - 795.0).hypot((i / w) as f32 - 510.0) < 10.0; + let hole: Vec = (0..w * h).map(|i| line(i) || knob(i)).collect(); + let area = auto_sampling(w, h, 3, &img, &hole); + let around_knob = (0..w * h).filter(|&i| !hole[i] && ((i % w) as f32 - 795.0).hypot((i / w) as f32 - 510.0) < 24.0); + let (n, kept) = around_knob.fold((0, 0), |(n, k), i| (n + 1, k + usize::from(area[i]))); + assert!(kept as f32 > 0.9 * n as f32, "{kept} of {n} pixels around the knob"); + assert!(thin_band(w, h, &hole) >= 20.0, "{}", thin_band(w, h, &hole)); + let disc: Vec = (0..w * h).map(|i| ((i % w) as f32 - 450.0).hypot((i / w) as f32 - 300.0) < 90.0).collect(); + assert_eq!(thin_band(w, h, &disc), 1.5); +} + +#[test] +fn without_colour_adaptation_the_fill_copies_pixels_exactly() { + // A smooth texture with fine noise, so that every value is unique: a filled pixel equal to + // an image pixel was copied from it. Photoshop's fill (colour adaptation None) is such + // copies, joined by narrow seams. + let (w, h) = (120, 120); + let fine = noise(w, h, 9); + let img: Vec = (0..w * h * 3) + .map(|i| { + let (x, y, c) = (((i / 3) % w) as f32, ((i / 3) / w) as f32, i % 3); + 0.5 + 0.2 * (x * 0.21 + c as f32).sin() * (y * 0.17).cos() + 0.1 * (x * 0.05 - y * 0.08).sin() + (fine[i] - 0.5) * 0.08 + }) + .collect(); + let hole: Vec = (0..w * h).map(|i| (40..80).contains(&(i % w)) && (40..80).contains(&(i / w))).collect(); + // Votes of identical copies average to the copy up to float rounding. + let key = |v: &[f32], i: usize| [0, 1, 2].map(|c| (v[i * 3 + c] * 1e5).round() as i64); + let known: std::collections::HashSet<[i64; 3]> = (0..w * h).filter(|i| !hole[*i]).map(|i| key(&img, i)).collect(); + let out = fill(w, h, 3, &img, &hole, &vec![true; w * h], &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() }); + let exact = (0..w * h).filter(|i| hole[*i] && known.contains(&key(&out, *i))).count(); + assert!(exact as f32 > 0.2 * 1600.0, "{exact} of 1600 filled pixels are exact copies"); + // And the fill is as busy as the noise around it, not a blur of it. + let lap = |v: &[f32], x: usize, y: usize| { + let p = |x: usize, y: usize| v[(y * w + x) * 3]; + (4.0 * p(x, y) - p(x - 1, y) - p(x + 1, y) - p(x, y - 1) - p(x, y + 1)).abs() + }; + let mean = |inside: bool| { + let pts: Vec<(usize, usize)> = (1..h - 1).flat_map(|y| (1..w - 1).map(move |x| (x, y))).filter(|&(x, y)| hole[y * w + x] == inside).collect(); + pts.iter().map(|&(x, y)| lap(&out, x, y)).sum::() / pts.len() as f32 + }; + assert!(mean(true) > 0.6 * mean(false), "fill detail {} against {}", mean(true), mean(false)); +} + +#[test] +fn patch_color_shifts_up_to_about_four_hundredths_per_step() { + // Content 0.4 brighter than where it lands (Photoshop's Patch, Color 3 and 10). + let from: Vec = (0..300).map(|i| 0.7 + 0.05 * ((i % 7) as f32 / 7.0)).collect(); + let to: Vec = from.iter().map(|v| v - 0.4).collect(); + let level = from.iter().sum::() / 300.0; + let shift = |c: u8| { + let gb = level_transform(1, &from, &to, color_amount(c)); + level - from.iter().map(|v| gb[0].0 * v + gb[0].1).sum::() / 300.0 + }; + assert_eq!(shift(0), 0.0); + assert!((shift(3) - 0.12).abs() < 0.01, "{}", shift(3)); + assert!((shift(10) - 0.4).abs() < 0.01, "{}", shift(10)); +} + +/// A soft background (gradients, broad out-of-focus blobs of colour, fine noise) with thin, long bright +/// objects over it: three coiled strings 3 to 7 px wide and two straighter ones, each with an +/// anti-aliased edge and a faint halo. Returns the image; what removing the coils should give +/// (the background and the straighter strings, which stay); and the selection a user would draw +/// around the coils, `margin` px wide. +fn strings_scene(w: usize, h: usize, margin: f32) -> (Vec, Vec, Vec) { + let fine = noise(w, h, 11); + // Out-of-focus colour: broad blobs over two gradients. + let blob = noise(3, 3, 5); + let bg: Vec = (0..w * h * 3) + .map(|i| { + let (x, y, c) = (((i / 3) % w) as f32 / w as f32, ((i / 3) / w) as f32 / h as f32, i % 3); + let mut v = [0.18 + 0.25 * x, 0.22 + 0.1 * y, 0.3 - 0.1 * x][c]; + for b in blob.as_chunks::<3>().0 { + let (bx, by, s) = (b[0] * 1.6 - 0.3, b[1] * 1.6 - 0.3, 0.1 + 0.25 * b[2]); + v += (b[(c + 1) % 3] - 0.2) * 0.5 * (-((x - bx).powi(2) + (y - by).powi(2) * 0.56) / (2.0 * s * s)).exp(); + } + v + (fine[i] - 0.5) * 0.03 + }) + .collect(); + // Signed distance to each object's surface, stamped from points along it. + let stamp = |sd: &mut [f32], pts: &mut dyn Iterator, half: f32| { + for (px, py) in pts { + let reach = (half + 4.0) as i32 + 1; + for dy in -reach..=reach { + for dx in -reach..=reach { + let (x, y) = (px as i32 + dx, py as i32 + dy); + if x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h { + let i = y as usize * w + x as usize; + sd[i] = sd[i].min((x as f32 - px).hypot(y as f32 - py) - half); + } + } + } + } + }; + let mut coils = vec![f32::INFINITY; w * h]; + for (k, half) in [1.5f32, 2.5, 3.5].into_iter().enumerate() { + let (y0, r) = ((0.22 + 0.28 * k as f32) * h as f32, 10.0 + 2.0 * k as f32); + let mut pts = (0..4000).map(|j| { + let t = j as f32 / 4000.0; + let a = 8.0 * std::f32::consts::TAU * t; + (18.0 + t * (w as f32 - 60.0) + r * a.cos(), y0 + 6.0 * (6.0 * t).sin() + 0.7 * r * a.sin()) + }); + stamp(&mut coils, &mut pts, half); + } + let mut straight = vec![f32::INFINITY; w * h]; + for y in [0.07, 0.93] { + stamp(&mut straight, &mut (0..2000).map(|j| (j as f32 / 2000.0 * w as f32, y * h as f32 + 3.0 * (j as f32 / 300.0).sin())), 2.0); + } + let draw = |base: &[f32], sd: &[f32]| -> Vec { + let mut img = base.to_vec(); + for i in 0..w * h { + let cover = (0.5 - sd[i]).clamp(0.0, 1.0); + let halo = if sd[i] > 0.0 { 0.08 * (-sd[i] * sd[i] / 2.9).exp() } else { 0.0 }; + for (c, metal) in [0.9f32, 0.85, 0.7].into_iter().enumerate() { + let v = &mut img[i * 3 + c]; + *v = *v * (1.0 - cover) + metal * cover + halo * (1.0 - cover); + } + } + img + }; + let clean = draw(&bg, &straight); + let both: Vec = coils.iter().zip(&straight).map(|(a, b)| a.min(*b)).collect(); + let img = draw(&bg, &both); + let hole = coils.iter().map(|d| *d <= margin).collect(); + (img, clean, hole) +} + +/// RMS over the hole of the error averaged over 7 × 7 pixels (in levels of 255): the noise +/// cancels out, a ghost of the removed outline or a blotch of another shade does not. +fn blotch_error(w: usize, h: usize, out: &[f32], clean: &[f32], hole: &[bool]) -> f32 { + let (mut sum, mut n) = (0.0f64, 0usize); + for y in 3..h - 3 { + for x in 3..w - 3 { + if !hole[y * w + x] { + continue; + } + let mut e = [0.0f32; 3]; + for j in (y - 3..=y + 3).flat_map(|yy| (x - 3..=x + 3).map(move |xx| yy * w + xx)) { + for (c, ec) in e.iter_mut().enumerate() { + *ec += out[j * 3 + c] - clean[j * 3 + c]; + } + } + sum += f64::from(e.iter().map(|v| (v / 49.0).powi(2)).sum::() / 3.0); + n += 1; + } + } + ((sum / n.max(1) as f64).sqrt() * 255.0) as f32 +} + +/// Removing thin, long objects (guitar strings, wires) from a soft background (#1366): the +/// fill is the background, with no ghost of their outline and nothing of their colour copied +/// back in. Their selection is long but only a few pixels thick, so the fill is worked out at +/// a scale where it is still a few pixels thick rather than one where the strings' surroundings +/// have merged into a blur. +#[test] +fn thin_objects_leave_no_ghost_and_none_of_their_colour() { + let (w, h) = (360, 270); + let (img, clean, hole) = strings_scene(w, h, 2.0); + let source = auto_sampling(w, h, 3, &img, &hole); + let out = fill(w, h, 3, &img, &hole, &source, &FillOptions::default()); + let blotch = blotch_error(w, h, &out, &clean, &hole); + let luma = |v: &[f32], i: usize| (v[i * 3] + v[i * 3 + 1] + v[i * 3 + 2]) / 3.0; + let bright = (0..w * h).filter(|&i| hole[i] && luma(&out, i) > luma(&clean, i) + 0.06).count(); + // Before #1366 the outlines stayed as darker and lighter blotches (13 levels of 255) and + // 1121 pixels took the strings' colour. + assert!(blotch < 2.5, "ghosts and blotches: {blotch:.2} levels of 255"); + assert_eq!(bright, 0, "filled pixels with the strings' colour"); +} + +#[test] +fn variant_geometry() { + let img = vec![0.5f32; 10 * 6]; + let ok = vec![true; 60]; + let src = Src { w: 10, h: 6, ch: 1, img: &img, ok: &ok }; + let v = variant(src, 90.0, 1.0, false, &Interrupt::NONE).unwrap(); + assert_eq!((v.w, v.h), (6, 10)); + let v = variant(src, 0.0, 0.8, true, &Interrupt::NONE).unwrap(); + assert_eq!((v.w, v.h), (8, 5)); + assert!(v.ok.iter().filter(|o| **o).count() > 20); +} From 388ad984d5ad4a3284eaf155be58342d9c37238a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:03 +0000 Subject: [PATCH 017/259] refactor(algo): move inpaint.rs tests to inpaint/tests.rs --- crates/algo/src/inpaint.rs | 470 +------------------------------ crates/algo/src/inpaint/tests.rs | 467 ++++++++++++++++++++++++++++++ 2 files changed, 468 insertions(+), 469 deletions(-) create mode 100644 crates/algo/src/inpaint/tests.rs diff --git a/crates/algo/src/inpaint.rs b/crates/algo/src/inpaint.rs index 87ed2a3576..e05aa3daac 100644 --- a/crates/algo/src/inpaint.rs +++ b/crates/algo/src/inpaint.rs @@ -2033,472 +2033,4 @@ fn min_cut(across: usize, along: usize, err: impl Fn(usize, usize) -> f32) -> Ve } #[cfg(test)] -mod tests { - use super::*; - - /// The mean is matched first: on a nearly flat bright patch with a noisy deviation ratio the - /// gain stays where the bias can still reach the target's mean. - #[test] - fn fit_matches_the_mean_before_the_contrast() { - let a = Adapt { gain: (0.9, 1.1), bias: 0.04 }; - // Target mean 0.70, source mean 0.70; deviations 0.01 vs 0.004 (ratio 2.5). - let n = 25.0; - let (mt, ms, sdt, sds) = (0.70f32, 0.70f32, 0.01f32, 0.004f32); - let (g, b) = fit(a, n, mt * n, (sdt * sdt + mt * mt) * n, ms * n, (sds * sds + ms * ms) * n); - assert!((g * ms + b - mt).abs() < 1e-5, "mean {} vs {mt} (g {g}, b {b})", g * ms + b); - // Where the mean can't be reached anyway, the limits hold as before. - let (g, b) = fit(a, n, 0.2 * n, 0.04 * n, 0.9 * n, 0.81 * n); - assert!((a.gain.0..=a.gain.1).contains(&g) && b.abs() <= a.bias + 1e-6); - } - - /// A zero-width image has no pixels however tall it is claimed to be: no per-row table. - #[test] - fn zero_width_images_complete_without_sizing_by_height() { - let p = CompleteParams::default(); - assert_eq!(complete(0, 1 << 40, 3, &[], &[], &p), Some(Vec::new())); - assert_eq!(complete(1 << 40, 0, 3, &[], &[], &p), Some(Vec::new())); - } - - /// Smooth gradient plus deterministic fine noise. - fn texture(w: usize, h: usize) -> Vec { - let mut rng = Rng::new(7); - (0..w * h) - .flat_map(|i| { - let (x, y) = ((i % w) as f32, (i / w) as f32); - let n = (rng.next() % 1000) as f32 / 1000.0 * 0.04 - 0.02; - [0.3 + 0.004 * x + n, 0.5 + 0.002 * y + n, 0.4 + n] - }) - .collect() - } - - fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec { - (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect() - } - - fn hole_rmse(a: &[f32], b: &[f32], hole: &[bool], ch: usize) -> f32 { - let (mut e, mut n) = (0.0f32, 0); - for (i, hh) in hole.iter().enumerate() { - if *hh { - for c in 0..ch { - e += (a[i * ch + c] - b[i * ch + c]).powi(2); - n += 1; - } - } - } - (e / n as f32).sqrt() - } - - #[test] - fn completion_fills_blemish_from_texture() { - let (w, h, ch) = (96, 96, 3); - let clean = texture(w, h); - let hole = disc(w, h, 48.0, 48.0, 9.0); - let mut dirty = clean.clone(); - for (i, hh) in hole.iter().enumerate() { - if *hh { - dirty[i * ch..i * ch + ch].copy_from_slice(&[0.02, 0.02, 0.02]); - } - } - let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap(); - let before = hole_rmse(&dirty, &clean, &hole, ch); - let after = hole_rmse(&out, &clean, &hole, ch); - assert!(after < 0.06 && after < before * 0.15, "rmse before {before} after {after}"); - // Outside the hole untouched. - assert!(out.iter().zip(&dirty).zip(hole.iter().flat_map(|h| [*h; 3])).all(|((a, b), h)| h || a == b)); - // Deterministic. - assert_eq!(out, complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap()); - } - - #[test] - fn completion_continues_structure() { - // Vertical stripes: the filled hole should keep the stripes (not a blur). - let (w, h, ch) = (80, 80, 1); - let clean: Vec = (0..w * h).map(|i| if (i % w / 4) % 2 == 0 { 0.2 } else { 0.8 }).collect(); - let hole = disc(w, h, 40.0, 40.0, 7.0); - let dirty: Vec = clean.iter().zip(&hole).map(|(c, h)| if *h { 0.5 } else { *c }).collect(); - let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap(); - let err = hole_rmse(&out, &clean, &hole, ch); - assert!(err < 0.15, "{err}"); - } - - #[test] - fn proximity_finds_matching_offset() { - let (w, h, ch) = (80, 60, 1); - // Periodic pattern with period 10 in x: a match is any multiple-of-10 displacement. - let img: Vec = (0..w * h).map(|i| ((i % w) as f32 * std::f32::consts::TAU / 10.0).sin() * 0.4 + 0.5).collect(); - let hole = disc(w, h, 40.0, 30.0, 5.0); - let (dx, dy) = best_offset(w, h, ch, &img, &hole, 3, 20).unwrap(); - assert_eq!(dx.rem_euclid(10), 0, "dx {dx} dy {dy}"); - assert!((dx, dy) != (0, 0)); - } - - #[test] - fn proximity_search_clamps_hostile_radii_without_overflow_or_hanging() { - let (w, h, ch) = (24, 20, 1); - let img: Vec = (0..w * h).map(|i| (i % w) as f32 / w as f32).collect(); - let hole = disc(w, h, 12.0, 10.0, 2.0); - // User-supplied values used to overflow i32 loops, cast a huge usize - // ring into a negative number, or take billions of search iterations. - let result = best_offset(w, h, ch, &img, &hole, usize::MAX, i32::MAX); - if let Some((dx, dy)) = result { - assert!(dx.abs() <= w as i32 && dy.abs() <= h as i32); - } - assert_eq!(best_offset(w, h, ch, &img, &hole, 2, -1), None); - assert_eq!(best_offset(w, h, ch, &img, &hole, 2, 0), None); - } - - /// Structure, fine noise and flat patches (so that some matches tie exactly), `ch` channels. - fn busy(w: usize, h: usize, ch: usize, seed: u64) -> Vec { - let mut rng = Rng::new(seed); - (0..w * h) - .flat_map(|i| { - let (x, y) = (i % w, i / w); - let flat = (x / 9 + y / 7) % 5 == 0; - let n = (rng.next() % 1000) as f32 / 1000.0; - (0..ch) - .map(move |c| if flat { 0.25 + 0.1 * c as f32 } else { (0.2 + 0.004 * x as f32 + 0.1 * ((x + 2 * y + c) % 6) as f32 + 0.05 * n).min(1.0) }) - }) - .collect() - } - - fn bits(v: &[f32]) -> Vec { - v.iter().map(|x| x.to_bits()).collect() - } - - /// Roles: a hole, a band that is context only, a corner that is no image. - fn roles(w: usize, h: usize, hole: &[bool]) -> Vec { - (0..w * h) - .map(|i| { - let (x, y) = (i % w, i / w); - if hole[i] { - Px::Hole - } else if x < 4 && y < 6 { - Px::Void - } else if (w * 3 / 4..w * 3 / 4 + 3).contains(&x) { - Px::Known - } else { - Px::Source - } - }) - .collect() - } - - #[test] - fn a_hole_is_as_thick_as_it_is_through_not_along() { - let (w, h) = (240, 120); - let all = Bounds { x0: 0, y0: 0, x1: w, y1: h }; - let thickness = |hole: &[bool]| { - let px: Vec = hole.iter().map(|&o| if o { Px::Hole } else { Px::Source }).collect(); - hole_thickness(w, hole_bounds(w, h, &px).unwrap_or(all), &px) - }; - // A band 200 px long and 9 px thick; a disc of radius 20; the band touching the edge - // counts the outside of the image as not hole. - let band: Vec = (0..w * h).map(|i| (20..220).contains(&(i % w)) && (50..59).contains(&(i / w))).collect(); - assert!((9..=11).contains(&thickness(&band)), "{}", thickness(&band)); - assert!((39..=42).contains(&thickness(&disc(w, h, 120.0, 60.0, 20.0)))); - let edge: Vec = (0..w * h).map(|i| i / w < 9).collect(); - assert!((9..=11).contains(&thickness(&edge)), "{}", thickness(&edge)); - } - - /// A long thin hole goes the thin way (a shallow pyramid that starts from a membrane): it is - /// filled, only it changes, and the result does not depend on the thread count either. - #[test] - #[cfg(not(target_arch = "wasm32"))] - fn thin_holes_are_filled_the_same_on_any_number_of_threads() { - let (w, h) = (300, 200); - let img = busy(w, h, 3, 5); - // A wavy line 6 px thick across the image. - let hole: Vec = (0..w * h).map(|i| (((i % w) as f32 * 0.05).sin() * 30.0 + 100.0 - (i / w) as f32).abs() < 3.0).collect(); - let px = roles(w, h, &hole); - let run = |threads: usize| { - let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap(); - pool.install(|| complete_masked(w, h, 3, &img, &px, &CompleteParams::default(), &photocraft_raster::Interrupt::NONE)).unwrap().unwrap() - }; - let one = run(1); - assert_eq!(bits(&one), bits(&run(7))); - assert!((0..w * h).all(|i| hole[i] || (0..3).all(|c| one[i * 3 + c].to_bits() == img[i * 3 + c].to_bits()))); - assert!((0..w * h).filter(|&i| hole[i]).all(|i| (0..3).all(|c| one[i * 3 + c].is_finite()))); - } - - #[test] - #[cfg(not(target_arch = "wasm32"))] - fn results_do_not_depend_on_the_thread_count() { - // Big enough for the parallel passes, and for PatchMatch to sweep in wavefronts where - // there are fewer bands than threads (never with one thread). - let (w, h) = (300, 260); - for (ch, adapt) in [(3, Adapt::NONE), (4, Adapt { gain: (0.9, 1.1), bias: 0.04 })] { - let img = busy(w, h, ch, 3); - let hole = disc(w, h, 140.0, 130.0, 40.0); - let px = roles(w, h, &hole); - let p = CompleteParams { adapt, ..Default::default() }; - let run = |threads: usize| { - let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap(); - bits(&pool.install(|| complete_masked(w, h, ch, &img, &px, &p, &photocraft_raster::Interrupt::NONE)).unwrap().unwrap()) - }; - let one = run(1); - assert_eq!(one, run(3), "{ch} channels, 3 threads"); - assert_eq!(one, run(16), "{ch} channels, 16 threads"); - } - } - - /// The onion peel as first written: every source in order, every known pixel summed. - fn onion_peel_plain(w: usize, h: usize, ch: usize, r: i32, img: &mut [f32], px: &[Px], sources: &[(i32, i32)]) { - let mut known: Vec = px.iter().map(|k| matches!(k, Px::Known | Px::Source)).collect(); - loop { - let front: Vec = (0..w * h) - .filter(|&i| { - let (x, y) = ((i % w) as i32, (i / w) as i32); - !known[i] - && px[i] == Px::Hole - && (-1..=1).any(|dy: i32| { - (-1..=1).any(|dx: i32| { - let (nx, ny) = (x + dx, y + dy); - nx >= 0 && ny >= 0 && (nx as usize) < w && (ny as usize) < h && known[ny as usize * w + nx as usize] - }) - }) - }) - .collect(); - if front.is_empty() { - break; - } - let vals: Vec> = front - .iter() - .map(|&i| { - let (x, y) = ((i % w) as i32, (i / w) as i32); - let mut best = (f32::INFINITY, (0i32, 0i32)); - for &(sx, sy) in sources { - let (mut e, mut n) = (0.0f32, 0usize); - for dy in -r..=r { - for dx in -r..=r { - let (tx, ty) = (x + dx, y + dy); - if tx < 0 || ty < 0 || tx as usize >= w || ty as usize >= h || !known[ty as usize * w + tx as usize] { - continue; - } - let (ti, si) = ((ty as usize * w + tx as usize) * ch, ((sy + dy) as usize * w + (sx + dx) as usize) * ch); - for c in 0..ch { - let d = img[ti + c] - img[si + c]; - e += d * d; - } - n += 1; - } - } - if n > 0 && e / (n as f32) < best.0 { - best = (e / n as f32, (sx, sy)); - } - } - let si = (best.1.1 as usize * w + best.1.0 as usize) * ch; - img[si..si + ch].to_vec() - }) - .collect(); - for (&i, v) in front.iter().zip(vals) { - img[i * ch..(i + 1) * ch].copy_from_slice(&v); - known[i] = true; - } - } - } - - /// #2805's case (upstream's own speed-up of the onion peel, superseded here): repeating - /// texture with many exact ties, two holes; the result must be the plain scan's to the bit. - #[test] - fn onion_peel_picks_exactly_what_the_plain_scan_picks() { - let (w, h, ch, r) = (48, 40, 3, 3); - let mut img = texture(w, h); - for y in 0..h { - for x in 6..w / 2 { - for c in 0..ch { - img[(y * w + x) * ch + c] = img[(y * w + x % 6) * ch + c]; - } - } - } - let none = photocraft_raster::Interrupt::NONE; - for hole in [disc(w, h, 20.0, 18.0, 7.5), disc(w, h, 34.0, 22.0, 5.0)] { - let px: Vec = hole.iter().map(|h| if *h { Px::Hole } else { Px::Source }).collect(); - let near = integral(w, h, &hole); - let sources: Vec<(i32, i32)> = (r..h as i32 - r) - .flat_map(|y| (r..w as i32 - r).map(move |x| (x, y))) - .filter(|&(x, y)| window_count(&near, w, h, x - r, y - r, x + r + 1, y + r + 1) == 0) - .collect(); - let (mut fast, mut plain) = (img.clone(), img.clone()); - onion_peel(w, h, ch, r, &mut fast, &px, hole_bounds(w, h, &px).unwrap(), &sources, &none).unwrap(); - onion_peel_plain(w, h, ch, r, &mut plain, &px, &sources); - assert!(fast.iter().zip(&plain).all(|(a, b)| a.to_bits() == b.to_bits())); - assert_ne!(fast, img); - } - } - - #[test] - fn onion_peel_takes_the_plain_scans_sources() { - let none = photocraft_raster::Interrupt::NONE; - for (w, h, ch, seed) in [(44, 36, 1, 1), (50, 40, 3, 2), (40, 40, 4, 3)] { - let mut img = busy(w, h, ch, seed); - // Also an image of a few exact values, where many sources tie. - if seed == 3 { - img.iter_mut().for_each(|v| *v = (*v * 3.0).round() / 3.0); - } - let hole = disc(w, h, w as f32 * 0.45, h as f32 * 0.5, 7.5); - let px = roles(w, h, &hole); - let valid = valid_sources(w, h, 3, &px, &none).unwrap(); - let sources = Sources::new(&valid, w).all(&valid, w); - let (mut a, mut b) = (img.clone(), img.clone()); - onion_peel(w, h, ch, 3, &mut a, &px, hole_bounds(w, h, &px).unwrap(), &sources, &none).unwrap(); - onion_peel_plain(w, h, ch, 3, &mut b, &px, &sources); - assert_eq!(bits(&a), bits(&b), "{w}×{h}×{ch}"); - } - } - - #[test] - fn least_sum_is_where_the_quotient_crosses() { - let mut rng = Rng::new(5); - for i in 0..4000 { - let n = (1 + rng.next() % 49) as f32; - let v = match i % 4 { - 0 => 0.0, - 1 => (rng.next() % 1000) as f32 * 1e-9, - _ => (rng.next() % 1_000_000) as f32 / 1_000_000.0, - }; - for strict in [true, false] { - let holds = |e: f32| if strict { e / n > v } else { e / n >= v }; - let e = least_sum(v, n, strict); - assert!(holds(e), "{v} {n} {strict}: {e}"); - assert!(e == 0.0 || !holds(e.next_down()), "{v} {n} {strict}: {e} is not the least"); - } - } - assert_eq!(least_sum(f32::INFINITY, 4.0, true), f32::INFINITY); - } - - #[test] - fn valid_sources_are_the_wholly_copyable_patches() { - let (w, h, r) = (37, 29, 2); - let mut rng = Rng::new(9); - let px: Vec = (0..w * h) - .map(|_| match rng.next() % 23 { - 0 => Px::Hole, - 1 => Px::Void, - 2 => Px::Known, - _ => Px::Source, - }) - .collect(); - let valid = valid_sources(w, h, r, &px, &photocraft_raster::Interrupt::NONE).unwrap(); - let source: Vec = px.iter().map(|k| *k == Px::Source).collect(); - let ss = integral(w, h, &source); - let (ri, full) = (r as i32, ((2 * r + 1) * (2 * r + 1)) as u32); - for y in 0..h as i32 { - for x in 0..w as i32 { - let inside = x >= ri && y >= ri && x + ri < w as i32 && y + ri < h as i32; - let want = inside && window_count(&ss, w, h, x - ri, y - ri, x + ri + 1, y + ri + 1) == full; - assert_eq!(valid[y as usize * w + x as usize], want, "({x}, {y})"); - } - } - // Counting per row and block finds the centres in order. - let sources = Sources::new(&valid, w); - let list = sources.all(&valid, w); - assert!(list.len() > 10 && list.len() == sources.len()); - for (k, p) in list.iter().enumerate() { - assert_eq!(sources.nth(k, &valid, w), *p); - } - // And on a grid wider than a block, with empty blocks and rows. - let (w, h) = (300, 9); - let wide: Vec = (0..w * h).map(|i| (i % w) % 7 == 3 && (i % w) / 64 != 2 && i / w != 4).collect(); - let sources = Sources::new(&wide, w); - let list = sources.all(&wide, w); - for (k, p) in list.iter().enumerate() { - assert_eq!(sources.nth(k, &wide, w), *p); - } - } - - #[test] - fn full_patches_measure_as_clipped_ones() { - let (w, h, ch, r) = (46, 38, 4, 3); - let mut img = busy(w, h, ch, 4); - let hole = disc(w, h, 20.0, 18.0, 6.0); - let px = roles(w, h, &hole); - let none = photocraft_raster::Interrupt::NONE; - let hb = hole_bounds(w, h, &px).unwrap(); - let tb = hb.grow(r, w, h); - let valid = valid_sources(w, h, r, &px, &none).unwrap(); - let picks: Vec<(i32, i32)> = Sources::new(&valid, w).all(&valid, w).iter().step_by(37).copied().collect(); - assert!(picks.len() > 5); - for adapt in [Adapt::NONE, Adapt { gain: (0.8, 1.25), bias: 0.08 }] { - for keep in [false, true] { - let targets = targets_around(w, r, &px, hb, tb); - let mut s = Solver { - w, - h, - ch, - r: r as i32, - img: &mut img, - px: &px, - valid: valid.clone(), - targets, - hole_box: hb, - tbox: tb, - full: Vec::new(), - tmom: Vec::new(), - smom: Vec::new(), - adapt, - ctl: none, - }; - s.prepare(keep); - let nnf = vec![picks[0]; tb.area()]; - let mut cost = vec![f32::INFINITY; tb.area()]; - s.costs(&nnf, &mut cost).unwrap(); - let mut checked = 0; - for k in 0..tb.area() { - if !s.targets[k] || !s.full[k] { - continue; - } - let t = ((tb.x0 + k % tb.width()) as i32, (tb.y0 + k / tb.width()) as i32); - for &src in &picks { - if adapt.is_none() { - let exact = s.dist_clipped(t, src, f32::INFINITY); - assert_eq!(s.dist_full(t, src, f32::INFINITY).to_bits(), exact.to_bits()); - for cutoff in [exact * 0.5, exact, exact * 2.0] { - let (a, b) = (s.dist_full(t, src, cutoff), s.dist_clipped(t, src, cutoff)); - assert_eq!(a < cutoff, b < cutoff); - } - } else { - let (mut m1, mut m2) = ([[0.0f32; 5]; 4], [[0.0f32; 5]; 4]); - s.moments_full(k, t, src, &mut m1); - assert_eq!(s.moments(t, src, &mut m2), (2 * r + 1) * (2 * r + 1)); - assert_eq!(m1.map(|c| c.map(f32::to_bits)), m2.map(|c| c.map(f32::to_bits))); - assert_eq!(s.dist_adapted_full(k, t, src).to_bits(), s.dist_adapted(t, src).to_bits()); - } - checked += 1; - } - } - assert!(checked > 100, "{checked}"); - } - } - } - - #[test] - fn owned_completion_fills_in_place_or_gives_the_pixels_back() { - let (w, h, ch) = (64, 52, 3); - let img = busy(w, h, ch, 6); - let hole = disc(w, h, 30.0, 26.0, 8.0); - let px = roles(w, h, &hole); - let (p, none) = (CompleteParams::default(), photocraft_raster::Interrupt::NONE); - let borrowed = complete_masked(w, h, ch, &img, &px, &p, &none).unwrap().unwrap(); - let owned = complete_masked_owned(w, h, ch, img.clone(), &px, &p, &none).unwrap().unwrap(); - assert_eq!(bits(&owned), bits(&borrowed)); - // Nothing may be copied: no completion, and the pixels come back as they were. - let known: Vec = px.iter().map(|k| if *k == Px::Source { Px::Known } else { *k }).collect(); - assert!(complete_masked(w, h, ch, &img, &known, &p, &none).unwrap().is_none()); - let back = complete_masked_owned(w, h, ch, img.clone(), &known, &p, &none).unwrap().unwrap_err(); - assert_eq!(bits(&back), bits(&img)); - // Cancelled, it stops. - let yes = || true; - assert!(complete_masked_owned(w, h, ch, img, &px, &p, &photocraft_raster::Interrupt::cancel_only(&yes)).is_err()); - } - - #[test] - fn synthesis_fills_hole_with_plausible_values() { - let (w, h, ch) = (64, 64, 3); - let clean = texture(w, h); - let hole = disc(w, h, 32.0, 32.0, 6.0); - let out = synthesize(w, h, ch, &clean, &hole, 8, 3); - let err = hole_rmse(&out, &clean, &hole, ch); - assert!(err < 0.15, "{err}"); - assert!(out.iter().all(|v| v.is_finite())); - } -} +mod tests; diff --git a/crates/algo/src/inpaint/tests.rs b/crates/algo/src/inpaint/tests.rs new file mode 100644 index 0000000000..28cb470cd8 --- /dev/null +++ b/crates/algo/src/inpaint/tests.rs @@ -0,0 +1,467 @@ +use super::*; + +/// The mean is matched first: on a nearly flat bright patch with a noisy deviation ratio the +/// gain stays where the bias can still reach the target's mean. +#[test] +fn fit_matches_the_mean_before_the_contrast() { + let a = Adapt { gain: (0.9, 1.1), bias: 0.04 }; + // Target mean 0.70, source mean 0.70; deviations 0.01 vs 0.004 (ratio 2.5). + let n = 25.0; + let (mt, ms, sdt, sds) = (0.70f32, 0.70f32, 0.01f32, 0.004f32); + let (g, b) = fit(a, n, mt * n, (sdt * sdt + mt * mt) * n, ms * n, (sds * sds + ms * ms) * n); + assert!((g * ms + b - mt).abs() < 1e-5, "mean {} vs {mt} (g {g}, b {b})", g * ms + b); + // Where the mean can't be reached anyway, the limits hold as before. + let (g, b) = fit(a, n, 0.2 * n, 0.04 * n, 0.9 * n, 0.81 * n); + assert!((a.gain.0..=a.gain.1).contains(&g) && b.abs() <= a.bias + 1e-6); +} + +/// A zero-width image has no pixels however tall it is claimed to be: no per-row table. +#[test] +fn zero_width_images_complete_without_sizing_by_height() { + let p = CompleteParams::default(); + assert_eq!(complete(0, 1 << 40, 3, &[], &[], &p), Some(Vec::new())); + assert_eq!(complete(1 << 40, 0, 3, &[], &[], &p), Some(Vec::new())); +} + +/// Smooth gradient plus deterministic fine noise. +fn texture(w: usize, h: usize) -> Vec { + let mut rng = Rng::new(7); + (0..w * h) + .flat_map(|i| { + let (x, y) = ((i % w) as f32, (i / w) as f32); + let n = (rng.next() % 1000) as f32 / 1000.0 * 0.04 - 0.02; + [0.3 + 0.004 * x + n, 0.5 + 0.002 * y + n, 0.4 + n] + }) + .collect() +} + +fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec { + (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect() +} + +fn hole_rmse(a: &[f32], b: &[f32], hole: &[bool], ch: usize) -> f32 { + let (mut e, mut n) = (0.0f32, 0); + for (i, hh) in hole.iter().enumerate() { + if *hh { + for c in 0..ch { + e += (a[i * ch + c] - b[i * ch + c]).powi(2); + n += 1; + } + } + } + (e / n as f32).sqrt() +} + +#[test] +fn completion_fills_blemish_from_texture() { + let (w, h, ch) = (96, 96, 3); + let clean = texture(w, h); + let hole = disc(w, h, 48.0, 48.0, 9.0); + let mut dirty = clean.clone(); + for (i, hh) in hole.iter().enumerate() { + if *hh { + dirty[i * ch..i * ch + ch].copy_from_slice(&[0.02, 0.02, 0.02]); + } + } + let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap(); + let before = hole_rmse(&dirty, &clean, &hole, ch); + let after = hole_rmse(&out, &clean, &hole, ch); + assert!(after < 0.06 && after < before * 0.15, "rmse before {before} after {after}"); + // Outside the hole untouched. + assert!(out.iter().zip(&dirty).zip(hole.iter().flat_map(|h| [*h; 3])).all(|((a, b), h)| h || a == b)); + // Deterministic. + assert_eq!(out, complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap()); +} + +#[test] +fn completion_continues_structure() { + // Vertical stripes: the filled hole should keep the stripes (not a blur). + let (w, h, ch) = (80, 80, 1); + let clean: Vec = (0..w * h).map(|i| if (i % w / 4) % 2 == 0 { 0.2 } else { 0.8 }).collect(); + let hole = disc(w, h, 40.0, 40.0, 7.0); + let dirty: Vec = clean.iter().zip(&hole).map(|(c, h)| if *h { 0.5 } else { *c }).collect(); + let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap(); + let err = hole_rmse(&out, &clean, &hole, ch); + assert!(err < 0.15, "{err}"); +} + +#[test] +fn proximity_finds_matching_offset() { + let (w, h, ch) = (80, 60, 1); + // Periodic pattern with period 10 in x: a match is any multiple-of-10 displacement. + let img: Vec = (0..w * h).map(|i| ((i % w) as f32 * std::f32::consts::TAU / 10.0).sin() * 0.4 + 0.5).collect(); + let hole = disc(w, h, 40.0, 30.0, 5.0); + let (dx, dy) = best_offset(w, h, ch, &img, &hole, 3, 20).unwrap(); + assert_eq!(dx.rem_euclid(10), 0, "dx {dx} dy {dy}"); + assert!((dx, dy) != (0, 0)); +} + +#[test] +fn proximity_search_clamps_hostile_radii_without_overflow_or_hanging() { + let (w, h, ch) = (24, 20, 1); + let img: Vec = (0..w * h).map(|i| (i % w) as f32 / w as f32).collect(); + let hole = disc(w, h, 12.0, 10.0, 2.0); + // User-supplied values used to overflow i32 loops, cast a huge usize + // ring into a negative number, or take billions of search iterations. + let result = best_offset(w, h, ch, &img, &hole, usize::MAX, i32::MAX); + if let Some((dx, dy)) = result { + assert!(dx.abs() <= w as i32 && dy.abs() <= h as i32); + } + assert_eq!(best_offset(w, h, ch, &img, &hole, 2, -1), None); + assert_eq!(best_offset(w, h, ch, &img, &hole, 2, 0), None); +} + +/// Structure, fine noise and flat patches (so that some matches tie exactly), `ch` channels. +fn busy(w: usize, h: usize, ch: usize, seed: u64) -> Vec { + let mut rng = Rng::new(seed); + (0..w * h) + .flat_map(|i| { + let (x, y) = (i % w, i / w); + let flat = (x / 9 + y / 7) % 5 == 0; + let n = (rng.next() % 1000) as f32 / 1000.0; + (0..ch) + .map(move |c| if flat { 0.25 + 0.1 * c as f32 } else { (0.2 + 0.004 * x as f32 + 0.1 * ((x + 2 * y + c) % 6) as f32 + 0.05 * n).min(1.0) }) + }) + .collect() +} + +fn bits(v: &[f32]) -> Vec { + v.iter().map(|x| x.to_bits()).collect() +} + +/// Roles: a hole, a band that is context only, a corner that is no image. +fn roles(w: usize, h: usize, hole: &[bool]) -> Vec { + (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + if hole[i] { + Px::Hole + } else if x < 4 && y < 6 { + Px::Void + } else if (w * 3 / 4..w * 3 / 4 + 3).contains(&x) { + Px::Known + } else { + Px::Source + } + }) + .collect() +} + +#[test] +fn a_hole_is_as_thick_as_it_is_through_not_along() { + let (w, h) = (240, 120); + let all = Bounds { x0: 0, y0: 0, x1: w, y1: h }; + let thickness = |hole: &[bool]| { + let px: Vec = hole.iter().map(|&o| if o { Px::Hole } else { Px::Source }).collect(); + hole_thickness(w, hole_bounds(w, h, &px).unwrap_or(all), &px) + }; + // A band 200 px long and 9 px thick; a disc of radius 20; the band touching the edge + // counts the outside of the image as not hole. + let band: Vec = (0..w * h).map(|i| (20..220).contains(&(i % w)) && (50..59).contains(&(i / w))).collect(); + assert!((9..=11).contains(&thickness(&band)), "{}", thickness(&band)); + assert!((39..=42).contains(&thickness(&disc(w, h, 120.0, 60.0, 20.0)))); + let edge: Vec = (0..w * h).map(|i| i / w < 9).collect(); + assert!((9..=11).contains(&thickness(&edge)), "{}", thickness(&edge)); +} + +/// A long thin hole goes the thin way (a shallow pyramid that starts from a membrane): it is +/// filled, only it changes, and the result does not depend on the thread count either. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn thin_holes_are_filled_the_same_on_any_number_of_threads() { + let (w, h) = (300, 200); + let img = busy(w, h, 3, 5); + // A wavy line 6 px thick across the image. + let hole: Vec = (0..w * h).map(|i| (((i % w) as f32 * 0.05).sin() * 30.0 + 100.0 - (i / w) as f32).abs() < 3.0).collect(); + let px = roles(w, h, &hole); + let run = |threads: usize| { + let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap(); + pool.install(|| complete_masked(w, h, 3, &img, &px, &CompleteParams::default(), &photocraft_raster::Interrupt::NONE)).unwrap().unwrap() + }; + let one = run(1); + assert_eq!(bits(&one), bits(&run(7))); + assert!((0..w * h).all(|i| hole[i] || (0..3).all(|c| one[i * 3 + c].to_bits() == img[i * 3 + c].to_bits()))); + assert!((0..w * h).filter(|&i| hole[i]).all(|i| (0..3).all(|c| one[i * 3 + c].is_finite()))); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn results_do_not_depend_on_the_thread_count() { + // Big enough for the parallel passes, and for PatchMatch to sweep in wavefronts where + // there are fewer bands than threads (never with one thread). + let (w, h) = (300, 260); + for (ch, adapt) in [(3, Adapt::NONE), (4, Adapt { gain: (0.9, 1.1), bias: 0.04 })] { + let img = busy(w, h, ch, 3); + let hole = disc(w, h, 140.0, 130.0, 40.0); + let px = roles(w, h, &hole); + let p = CompleteParams { adapt, ..Default::default() }; + let run = |threads: usize| { + let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap(); + bits(&pool.install(|| complete_masked(w, h, ch, &img, &px, &p, &photocraft_raster::Interrupt::NONE)).unwrap().unwrap()) + }; + let one = run(1); + assert_eq!(one, run(3), "{ch} channels, 3 threads"); + assert_eq!(one, run(16), "{ch} channels, 16 threads"); + } +} + +/// The onion peel as first written: every source in order, every known pixel summed. +fn onion_peel_plain(w: usize, h: usize, ch: usize, r: i32, img: &mut [f32], px: &[Px], sources: &[(i32, i32)]) { + let mut known: Vec = px.iter().map(|k| matches!(k, Px::Known | Px::Source)).collect(); + loop { + let front: Vec = (0..w * h) + .filter(|&i| { + let (x, y) = ((i % w) as i32, (i / w) as i32); + !known[i] + && px[i] == Px::Hole + && (-1..=1).any(|dy: i32| { + (-1..=1).any(|dx: i32| { + let (nx, ny) = (x + dx, y + dy); + nx >= 0 && ny >= 0 && (nx as usize) < w && (ny as usize) < h && known[ny as usize * w + nx as usize] + }) + }) + }) + .collect(); + if front.is_empty() { + break; + } + let vals: Vec> = front + .iter() + .map(|&i| { + let (x, y) = ((i % w) as i32, (i / w) as i32); + let mut best = (f32::INFINITY, (0i32, 0i32)); + for &(sx, sy) in sources { + let (mut e, mut n) = (0.0f32, 0usize); + for dy in -r..=r { + for dx in -r..=r { + let (tx, ty) = (x + dx, y + dy); + if tx < 0 || ty < 0 || tx as usize >= w || ty as usize >= h || !known[ty as usize * w + tx as usize] { + continue; + } + let (ti, si) = ((ty as usize * w + tx as usize) * ch, ((sy + dy) as usize * w + (sx + dx) as usize) * ch); + for c in 0..ch { + let d = img[ti + c] - img[si + c]; + e += d * d; + } + n += 1; + } + } + if n > 0 && e / (n as f32) < best.0 { + best = (e / n as f32, (sx, sy)); + } + } + let si = (best.1.1 as usize * w + best.1.0 as usize) * ch; + img[si..si + ch].to_vec() + }) + .collect(); + for (&i, v) in front.iter().zip(vals) { + img[i * ch..(i + 1) * ch].copy_from_slice(&v); + known[i] = true; + } + } +} + +/// #2805's case (upstream's own speed-up of the onion peel, superseded here): repeating +/// texture with many exact ties, two holes; the result must be the plain scan's to the bit. +#[test] +fn onion_peel_picks_exactly_what_the_plain_scan_picks() { + let (w, h, ch, r) = (48, 40, 3, 3); + let mut img = texture(w, h); + for y in 0..h { + for x in 6..w / 2 { + for c in 0..ch { + img[(y * w + x) * ch + c] = img[(y * w + x % 6) * ch + c]; + } + } + } + let none = photocraft_raster::Interrupt::NONE; + for hole in [disc(w, h, 20.0, 18.0, 7.5), disc(w, h, 34.0, 22.0, 5.0)] { + let px: Vec = hole.iter().map(|h| if *h { Px::Hole } else { Px::Source }).collect(); + let near = integral(w, h, &hole); + let sources: Vec<(i32, i32)> = (r..h as i32 - r) + .flat_map(|y| (r..w as i32 - r).map(move |x| (x, y))) + .filter(|&(x, y)| window_count(&near, w, h, x - r, y - r, x + r + 1, y + r + 1) == 0) + .collect(); + let (mut fast, mut plain) = (img.clone(), img.clone()); + onion_peel(w, h, ch, r, &mut fast, &px, hole_bounds(w, h, &px).unwrap(), &sources, &none).unwrap(); + onion_peel_plain(w, h, ch, r, &mut plain, &px, &sources); + assert!(fast.iter().zip(&plain).all(|(a, b)| a.to_bits() == b.to_bits())); + assert_ne!(fast, img); + } +} + +#[test] +fn onion_peel_takes_the_plain_scans_sources() { + let none = photocraft_raster::Interrupt::NONE; + for (w, h, ch, seed) in [(44, 36, 1, 1), (50, 40, 3, 2), (40, 40, 4, 3)] { + let mut img = busy(w, h, ch, seed); + // Also an image of a few exact values, where many sources tie. + if seed == 3 { + img.iter_mut().for_each(|v| *v = (*v * 3.0).round() / 3.0); + } + let hole = disc(w, h, w as f32 * 0.45, h as f32 * 0.5, 7.5); + let px = roles(w, h, &hole); + let valid = valid_sources(w, h, 3, &px, &none).unwrap(); + let sources = Sources::new(&valid, w).all(&valid, w); + let (mut a, mut b) = (img.clone(), img.clone()); + onion_peel(w, h, ch, 3, &mut a, &px, hole_bounds(w, h, &px).unwrap(), &sources, &none).unwrap(); + onion_peel_plain(w, h, ch, 3, &mut b, &px, &sources); + assert_eq!(bits(&a), bits(&b), "{w}×{h}×{ch}"); + } +} + +#[test] +fn least_sum_is_where_the_quotient_crosses() { + let mut rng = Rng::new(5); + for i in 0..4000 { + let n = (1 + rng.next() % 49) as f32; + let v = match i % 4 { + 0 => 0.0, + 1 => (rng.next() % 1000) as f32 * 1e-9, + _ => (rng.next() % 1_000_000) as f32 / 1_000_000.0, + }; + for strict in [true, false] { + let holds = |e: f32| if strict { e / n > v } else { e / n >= v }; + let e = least_sum(v, n, strict); + assert!(holds(e), "{v} {n} {strict}: {e}"); + assert!(e == 0.0 || !holds(e.next_down()), "{v} {n} {strict}: {e} is not the least"); + } + } + assert_eq!(least_sum(f32::INFINITY, 4.0, true), f32::INFINITY); +} + +#[test] +fn valid_sources_are_the_wholly_copyable_patches() { + let (w, h, r) = (37, 29, 2); + let mut rng = Rng::new(9); + let px: Vec = (0..w * h) + .map(|_| match rng.next() % 23 { + 0 => Px::Hole, + 1 => Px::Void, + 2 => Px::Known, + _ => Px::Source, + }) + .collect(); + let valid = valid_sources(w, h, r, &px, &photocraft_raster::Interrupt::NONE).unwrap(); + let source: Vec = px.iter().map(|k| *k == Px::Source).collect(); + let ss = integral(w, h, &source); + let (ri, full) = (r as i32, ((2 * r + 1) * (2 * r + 1)) as u32); + for y in 0..h as i32 { + for x in 0..w as i32 { + let inside = x >= ri && y >= ri && x + ri < w as i32 && y + ri < h as i32; + let want = inside && window_count(&ss, w, h, x - ri, y - ri, x + ri + 1, y + ri + 1) == full; + assert_eq!(valid[y as usize * w + x as usize], want, "({x}, {y})"); + } + } + // Counting per row and block finds the centres in order. + let sources = Sources::new(&valid, w); + let list = sources.all(&valid, w); + assert!(list.len() > 10 && list.len() == sources.len()); + for (k, p) in list.iter().enumerate() { + assert_eq!(sources.nth(k, &valid, w), *p); + } + // And on a grid wider than a block, with empty blocks and rows. + let (w, h) = (300, 9); + let wide: Vec = (0..w * h).map(|i| (i % w) % 7 == 3 && (i % w) / 64 != 2 && i / w != 4).collect(); + let sources = Sources::new(&wide, w); + let list = sources.all(&wide, w); + for (k, p) in list.iter().enumerate() { + assert_eq!(sources.nth(k, &wide, w), *p); + } +} + +#[test] +fn full_patches_measure_as_clipped_ones() { + let (w, h, ch, r) = (46, 38, 4, 3); + let mut img = busy(w, h, ch, 4); + let hole = disc(w, h, 20.0, 18.0, 6.0); + let px = roles(w, h, &hole); + let none = photocraft_raster::Interrupt::NONE; + let hb = hole_bounds(w, h, &px).unwrap(); + let tb = hb.grow(r, w, h); + let valid = valid_sources(w, h, r, &px, &none).unwrap(); + let picks: Vec<(i32, i32)> = Sources::new(&valid, w).all(&valid, w).iter().step_by(37).copied().collect(); + assert!(picks.len() > 5); + for adapt in [Adapt::NONE, Adapt { gain: (0.8, 1.25), bias: 0.08 }] { + for keep in [false, true] { + let targets = targets_around(w, r, &px, hb, tb); + let mut s = Solver { + w, + h, + ch, + r: r as i32, + img: &mut img, + px: &px, + valid: valid.clone(), + targets, + hole_box: hb, + tbox: tb, + full: Vec::new(), + tmom: Vec::new(), + smom: Vec::new(), + adapt, + ctl: none, + }; + s.prepare(keep); + let nnf = vec![picks[0]; tb.area()]; + let mut cost = vec![f32::INFINITY; tb.area()]; + s.costs(&nnf, &mut cost).unwrap(); + let mut checked = 0; + for k in 0..tb.area() { + if !s.targets[k] || !s.full[k] { + continue; + } + let t = ((tb.x0 + k % tb.width()) as i32, (tb.y0 + k / tb.width()) as i32); + for &src in &picks { + if adapt.is_none() { + let exact = s.dist_clipped(t, src, f32::INFINITY); + assert_eq!(s.dist_full(t, src, f32::INFINITY).to_bits(), exact.to_bits()); + for cutoff in [exact * 0.5, exact, exact * 2.0] { + let (a, b) = (s.dist_full(t, src, cutoff), s.dist_clipped(t, src, cutoff)); + assert_eq!(a < cutoff, b < cutoff); + } + } else { + let (mut m1, mut m2) = ([[0.0f32; 5]; 4], [[0.0f32; 5]; 4]); + s.moments_full(k, t, src, &mut m1); + assert_eq!(s.moments(t, src, &mut m2), (2 * r + 1) * (2 * r + 1)); + assert_eq!(m1.map(|c| c.map(f32::to_bits)), m2.map(|c| c.map(f32::to_bits))); + assert_eq!(s.dist_adapted_full(k, t, src).to_bits(), s.dist_adapted(t, src).to_bits()); + } + checked += 1; + } + } + assert!(checked > 100, "{checked}"); + } + } +} + +#[test] +fn owned_completion_fills_in_place_or_gives_the_pixels_back() { + let (w, h, ch) = (64, 52, 3); + let img = busy(w, h, ch, 6); + let hole = disc(w, h, 30.0, 26.0, 8.0); + let px = roles(w, h, &hole); + let (p, none) = (CompleteParams::default(), photocraft_raster::Interrupt::NONE); + let borrowed = complete_masked(w, h, ch, &img, &px, &p, &none).unwrap().unwrap(); + let owned = complete_masked_owned(w, h, ch, img.clone(), &px, &p, &none).unwrap().unwrap(); + assert_eq!(bits(&owned), bits(&borrowed)); + // Nothing may be copied: no completion, and the pixels come back as they were. + let known: Vec = px.iter().map(|k| if *k == Px::Source { Px::Known } else { *k }).collect(); + assert!(complete_masked(w, h, ch, &img, &known, &p, &none).unwrap().is_none()); + let back = complete_masked_owned(w, h, ch, img.clone(), &known, &p, &none).unwrap().unwrap_err(); + assert_eq!(bits(&back), bits(&img)); + // Cancelled, it stops. + let yes = || true; + assert!(complete_masked_owned(w, h, ch, img, &px, &p, &photocraft_raster::Interrupt::cancel_only(&yes)).is_err()); +} + +#[test] +fn synthesis_fills_hole_with_plausible_values() { + let (w, h, ch) = (64, 64, 3); + let clean = texture(w, h); + let hole = disc(w, h, 32.0, 32.0, 6.0); + let out = synthesize(w, h, ch, &clean, &hole, 8, 3); + let err = hole_rmse(&out, &clean, &hole, ch); + assert!(err < 0.15, "{err}"); + assert!(out.iter().all(|v| v.is_finite())); +} From 5215fe875571ac7ef76a90c68a1f93cc82389105 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:04 +0000 Subject: [PATCH 018/259] refactor(algo): move stack.rs tests to stack/tests.rs --- crates/algo/src/stack.rs | 306 +-------------------------------- crates/algo/src/stack/tests.rs | 301 ++++++++++++++++++++++++++++++++ 2 files changed, 302 insertions(+), 305 deletions(-) create mode 100644 crates/algo/src/stack/tests.rs diff --git a/crates/algo/src/stack.rs b/crates/algo/src/stack.rs index dbb5b22e65..3d0c9a87b3 100644 --- a/crates/algo/src/stack.rs +++ b/crates/algo/src/stack.rs @@ -205,308 +205,4 @@ fn combine_with(layers: &[Vec<[f32; 4]>], f: impl Fn(&mut [f32], &mut EntropyScr } #[cfg(test)] -mod tests { - use super::*; - - fn px(v: f32) -> Vec<[f32; 4]> { - vec![[v, v, v, 1.0]] - } - - #[test] - fn basic_statistics() { - let layers = vec![px(0.1), px(0.9), px(0.2), px(0.3), px(0.1)]; - let at = |s| combine(&layers, s)[0][0]; - assert!((at(Stat::Mean) - 0.32).abs() < 1e-6); - assert!((at(Stat::Median) - 0.2).abs() < 1e-6); - assert_eq!(at(Stat::Minimum), 0.1); - assert_eq!(at(Stat::Maximum), 0.9); - assert!((at(Stat::Range) - 0.8).abs() < 1e-6); - assert!((at(Stat::Summation) - 1.6).abs() < 1e-6); - let var = at(Stat::Variance); - assert!((at(Stat::StandardDeviation) - var.sqrt()).abs() < 1e-6); - assert!(at(Stat::Skewness) > 0.5, "right-skewed"); - assert!(at(Stat::Entropy) > 0.0 && at(Stat::Entropy) <= 1.0); - assert!(at(Stat::Kurtosis) > 0.0); - } - - #[test] - fn statistics_preserve_hdr_and_signed_samples() { - let layers = vec![px(-2.0), px(4.0)]; - for (mode, expected) in [ - (Stat::Mean, 1.0), - (Stat::Median, 1.0), - (Stat::Minimum, -2.0), - (Stat::Maximum, 4.0), - (Stat::Range, 6.0), - (Stat::Summation, 2.0), - (Stat::Variance, 9.0), - (Stat::StandardDeviation, 3.0), - ] { - assert_eq!(combine(&layers, mode)[0], [expected, expected, expected, 1.0], "{mode:?}"); - } - for mode in [Stat::Mean, Stat::Median] { - assert_eq!(combine(&[px(2.0), px(4.0)], mode)[0], [3.0, 3.0, 3.0, 1.0]); - assert_eq!(combine(&[px(-2.0), px(-4.0)], mode)[0], [-3.0, -3.0, -3.0, 1.0]); - } - // These display-oriented statistics still apply their own normalisation. - for mode in [Stat::Entropy, Stat::Skewness, Stat::Kurtosis] { - assert!((0.0..=1.0).contains(&combine(&layers, mode)[0][0]), "{mode:?}"); - } - } - - #[test] - fn transparent_samples_are_ignored() { - let layers = vec![vec![[0.5, 0.5, 0.5, 1.0]], vec![[1.0, 1.0, 1.0, 0.0]]]; - assert_eq!(combine(&layers, Stat::Mean)[0], [0.5, 0.5, 0.5, 1.0]); - let empty = vec![vec![[1.0, 1.0, 1.0, 0.0]]]; - assert_eq!(combine(&empty, Stat::Mean)[0][3], 0.0); - } - - #[test] - fn median_removes_outlier() { - let layers = vec![px(0.5), px(0.5), px(1.0)]; - assert_eq!(combine(&layers, Stat::Median)[0][0], 0.5); - } - - /// Five layers over six pixels (the last layer is short). Covers opaque, partly transparent, - /// fully transparent, HDR / negative, single-sample and tied-value pixels. - fn fixture() -> Vec> { - vec![ - vec![[0.10, 0.20, 0.30, 1.0], [0.5, 0.5, 0.5, 1.0], [0.9, 0.9, 0.9, 0.0], [-2.0, 4.0, 0.0, 1.0], [0.7, 0.2, 0.1, 0.5], [0.25, 0.25, 0.25, 1.0]], - vec![[0.90, 0.60, 0.30, 1.0], [0.0, 0.0, 0.0, 0.0], [0.8, 0.8, 0.8, 0.0], [3.0, -1.0, 0.5, 0.75], [0.0, 0.0, 0.0, 0.0], [0.25, 0.75, 0.25, 1.0]], - vec![[0.20, 0.90, 0.30, 0.5], [0.1, 0.2, 0.3, 1.0], [0.7, 0.7, 0.7, 0.0], [0.5, 0.5, 0.5, 1.0], [0.0, 0.0, 0.0, 0.0], [0.5, 0.75, 0.25, 0.25]], - vec![[0.30, 0.05, 0.30, 0.25], [0.3, 0.4, 0.5, 0.5], [0.6, 0.6, 0.6, 0.0], [1.5, 1.5, 1.5, 1.0], [0.0, 0.0, 0.0, 0.0], [0.25, 0.75, 0.5, 1.0]], - vec![[0.10, 0.70, 0.99, 1.0], [0.9, 0.1, 0.2, 1.0], [0.5, 0.5, 0.5, 0.0], [0.0, 0.0, 0.0, 1.0]], - ] - } - - fn bits(px: &[[f32; 4]]) -> Vec<[u32; 4]> { - px.iter().map(|p| p.map(f32::to_bits)).collect() - } - - /// Every mode except Entropy is bit-for-bit what the old serial loop produced. The expected - /// bit patterns were recorded by running the unmodified `combine` on [`fixture`]. - #[test] - fn statistics_are_bit_identical_to_the_serial_implementation() { - let layers = fixture(); - let expected: Vec<(Stat, Vec<[u32; 4]>)> = vec![ - ( - Stat::Kurtosis, - [ - [0x3e96956b, 0x3e182e3f, 0x3ea66664, 0x3f800000], - [0x3e3d004c, 0x3e0b4396, 0x3e030e1f, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x3e594eb2, 0x3e6ef420, 0x3e7ffffe, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x3f000000], - [0x3e6eeeee, 0x3e6eeeee, 0x3e6eeeee, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Maximum, - [ - [0x3f666666, 0x3f666666, 0x3f7d70a4, 0x3f800000], - [0x3f666666, 0x3f000000, 0x3f000000, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x40400000, 0x40800000, 0x3fc00000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], - [0x3f000000, 0x3f400000, 0x3f000000, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Mean, - [ - [0x3ea3d70a, 0x3efae148, 0x3ee0418a, 0x3f800000], - [0x3ee66666, 0x3e99999a, 0x3ec00000, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x3f19999a, 0x3f800000, 0x3f000000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], - [0x3ea00000, 0x3f200000, 0x3ea00000, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Median, - [ - [0x3e4ccccd, 0x3f19999a, 0x3e99999a, 0x3f800000], - [0x3ecccccd, 0x3e99999a, 0x3ecccccd, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x3f000000, 0x3f000000, 0x3f000000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], - [0x3e800000, 0x3f400000, 0x3e800000, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Minimum, - [ - [0x3dcccccd, 0x3d4ccccd, 0x3e99999a, 0x3f800000], - [0x3dcccccd, 0x3dcccccd, 0x3e4ccccd, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0xc0000000, 0xbf800000, 0x00000000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], - [0x3e800000, 0x3e800000, 0x3e800000, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Range, - [ - [0x3f4ccccc, 0x3f599999, 0x3f30a3d7, 0x3f800000], - [0x3f4ccccc, 0x3ecccccd, 0x3e99999a, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x40a00000, 0x40a00000, 0x3fc00000, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x3f000000], - [0x3e800000, 0x3f000000, 0x3e800000, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Skewness, - [ - [0x3f522026, 0x3ee7cf76, 0x3f600000, 0x3f800000], - [0x3f1bd152, 0x3efffffe, 0x3ee4a11b, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x3eedb65a, 0x3f2ea754, 0x3f3a6c7a, 0x3f800000], - [0x3f000000, 0x3f000000, 0x3f000000, 0x3f000000], - [0x3f49e69e, 0x3e58658a, 0x3f49e69e, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::StandardDeviation, - [ - [0x3e99421e, 0x3ea23b6b, 0x3e8d4fdf, 0x3f800000], - [0x3e97739e, 0x3e21e89b, 0x3e050581, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x3fd3e0b1, 0x3fd9f9e5, 0x3f0c378c, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x3f000000], - [0x3dddb3d7, 0x3e5db3d7, 0x3dddb3d7, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Summation, - [ - [0x3fcccccd, 0x401ccccd, 0x400c28f6, 0x3f800000], - [0x3fe66666, 0x3f99999a, 0x3fc00000, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x40400000, 0x40a00000, 0x40200000, 0x3f800000], - [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], - [0x3fa00000, 0x40200000, 0x3fa00000, 0x3f800000], - ] - .to_vec(), - ), - ( - Stat::Variance, - [ - [0x3db78033, 0x3dcd9e83, 0x3d9c022a, 0x3f800000], - [0x3db33332, 0x3ccccccd, 0x3c8a3d70, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x00000000], - [0x402f5c29, 0x4039999a, 0x3e99999a, 0x3f800000], - [0x00000000, 0x00000000, 0x00000000, 0x3f000000], - [0x3c400000, 0x3d400000, 0x3c400000, 0x3f800000], - ] - .to_vec(), - ), - ]; - for (mode, want) in expected { - assert_eq!(bits(&combine(&layers, mode)), want, "{mode:?}"); - } - } - - /// Entropy against values worked out by hand (bits of the 8-bit histogram, over log2(N)). - #[test] - fn entropy_matches_hand_computed_values() { - let out = combine(&fixture(), Stat::Entropy); - let h = |ps: &[f64]| -> f64 { - let n: f64 = ps.iter().sum(); - ps.iter().map(|c| -(c / n) * (c / n).log2()).sum::() / n.log2() - }; - // Pixel 1: four distinct values -> 2 bits / log2(4) = exactly 1. - assert_eq!(out[1][0], 1.0); - // Pixel 2: every sample transparent -> untouched. - assert_eq!(out[2], [0.0; 4]); - // Pixel 3, red: -2 and 0 land in bin 0, 3 and 1.5 clamp into bin 255, 0.5 is alone. - assert!((f64::from(out[3][0]) - h(&[2.0, 2.0, 1.0])).abs() < 1e-6, "{}", out[3][0]); - // Pixel 4: a single contributing sample has no entropy. - assert_eq!(out[4], [0.0, 0.0, 0.0, 0.5]); - // Pixel 5: three samples share a bin, one is alone, in every channel. - for (c, v) in out[5].iter().take(3).enumerate() { - assert!((f64::from(*v) - h(&[3.0, 1.0])).abs() < 1e-6, "channel {c}: {v}"); - } - } - - /// The old HashMap summed in a random order, so Entropy could differ by an ulp between runs. - /// Now the bins are summed in ascending order: repeated runs (and any thread count) agree. - #[test] - fn entropy_is_deterministic() { - let layers: Vec> = (0..7) - .map(|k| { - (0..3 * CHUNK + 17).map(|i| [((i * 7 + k * 13) % 11) as f32 / 10.0, ((i + k) % 5) as f32 / 4.0, ((i * k) % 9) as f32 / 8.0, 1.0]).collect() - }) - .collect(); - let first = bits(&combine(&layers, Stat::Entropy)); - for _ in 0..8 { - assert_eq!(bits(&combine(&layers, Stat::Entropy)), first); - } - } - - /// Chunking is invisible: a multi-chunk image (with a ragged last chunk and layers of unequal - /// length) gives, pixel by pixel, what combining that pixel on its own gives. - #[test] - fn chunked_result_equals_per_pixel_result() { - let len = 2 * CHUNK + 5; - let layer = |k: usize, n: usize| -> Vec<[f32; 4]> { - (0..n) - .map(|i| { - [ - ((i * 31 + k * 7) % 101) as f32 / 100.0, - ((i * 17 + k) % 53) as f32 / 52.0 - 0.2, - ((i + 3 * k) % 29) as f32 / 28.0, - if (i + k).is_multiple_of(4) { 0.0 } else { 0.5 + ((i + k) % 3) as f32 / 4.0 }, - ] - }) - .collect() - }; - let layers = vec![layer(1, len), layer(2, CHUNK + 3), layer(3, len - 1), layer(4, 0), layer(5, len)]; - for mode in [ - Stat::Entropy, - Stat::Kurtosis, - Stat::Maximum, - Stat::Mean, - Stat::Median, - Stat::Minimum, - Stat::Range, - Stat::Skewness, - Stat::StandardDeviation, - Stat::Summation, - Stat::Variance, - ] { - let whole = combine(&layers, mode); - assert_eq!(whole.len(), len); - for i in (0..len).step_by(97).chain([CHUNK - 1, CHUNK, CHUNK + 1, 2 * CHUNK - 1, 2 * CHUNK, len - 1]) { - let one: Vec> = layers.iter().map(|l| l.get(i).map(|p| vec![*p]).unwrap_or_default()).collect(); - assert_eq!(whole[i].map(f32::to_bits), combine(&one, mode)[0].map(f32::to_bits), "{mode:?} pixel {i}"); - } - } - } - - #[test] - fn no_layers_gives_an_empty_result() { - assert!(combine(&[], Stat::Median).is_empty()); - } - - /// [`ipow`] multiplies in the order `x·x²` for the cube and `x²·x²` for the fourth power. - #[test] - fn ipow_squares_and_multiplies() { - for x in [0.58f32, -0.12, -2.6, 2.4, -0.6, 1.0e-3, 0.0] { - assert_eq!(ipow(x, 0).to_bits(), 1.0f32.to_bits()); - assert_eq!(ipow(x, 1).to_bits(), x.to_bits()); - assert_eq!(ipow(x, 2).to_bits(), (x * x).to_bits()); - assert_eq!(ipow(x, 3).to_bits(), (x * (x * x)).to_bits()); - assert_eq!(ipow(x, 4).to_bits(), ((x * x) * (x * x)).to_bits()); - } - } -} +mod tests; diff --git a/crates/algo/src/stack/tests.rs b/crates/algo/src/stack/tests.rs new file mode 100644 index 0000000000..9e14a6be44 --- /dev/null +++ b/crates/algo/src/stack/tests.rs @@ -0,0 +1,301 @@ +use super::*; + +fn px(v: f32) -> Vec<[f32; 4]> { + vec![[v, v, v, 1.0]] +} + +#[test] +fn basic_statistics() { + let layers = vec![px(0.1), px(0.9), px(0.2), px(0.3), px(0.1)]; + let at = |s| combine(&layers, s)[0][0]; + assert!((at(Stat::Mean) - 0.32).abs() < 1e-6); + assert!((at(Stat::Median) - 0.2).abs() < 1e-6); + assert_eq!(at(Stat::Minimum), 0.1); + assert_eq!(at(Stat::Maximum), 0.9); + assert!((at(Stat::Range) - 0.8).abs() < 1e-6); + assert!((at(Stat::Summation) - 1.6).abs() < 1e-6); + let var = at(Stat::Variance); + assert!((at(Stat::StandardDeviation) - var.sqrt()).abs() < 1e-6); + assert!(at(Stat::Skewness) > 0.5, "right-skewed"); + assert!(at(Stat::Entropy) > 0.0 && at(Stat::Entropy) <= 1.0); + assert!(at(Stat::Kurtosis) > 0.0); +} + +#[test] +fn statistics_preserve_hdr_and_signed_samples() { + let layers = vec![px(-2.0), px(4.0)]; + for (mode, expected) in [ + (Stat::Mean, 1.0), + (Stat::Median, 1.0), + (Stat::Minimum, -2.0), + (Stat::Maximum, 4.0), + (Stat::Range, 6.0), + (Stat::Summation, 2.0), + (Stat::Variance, 9.0), + (Stat::StandardDeviation, 3.0), + ] { + assert_eq!(combine(&layers, mode)[0], [expected, expected, expected, 1.0], "{mode:?}"); + } + for mode in [Stat::Mean, Stat::Median] { + assert_eq!(combine(&[px(2.0), px(4.0)], mode)[0], [3.0, 3.0, 3.0, 1.0]); + assert_eq!(combine(&[px(-2.0), px(-4.0)], mode)[0], [-3.0, -3.0, -3.0, 1.0]); + } + // These display-oriented statistics still apply their own normalisation. + for mode in [Stat::Entropy, Stat::Skewness, Stat::Kurtosis] { + assert!((0.0..=1.0).contains(&combine(&layers, mode)[0][0]), "{mode:?}"); + } +} + +#[test] +fn transparent_samples_are_ignored() { + let layers = vec![vec![[0.5, 0.5, 0.5, 1.0]], vec![[1.0, 1.0, 1.0, 0.0]]]; + assert_eq!(combine(&layers, Stat::Mean)[0], [0.5, 0.5, 0.5, 1.0]); + let empty = vec![vec![[1.0, 1.0, 1.0, 0.0]]]; + assert_eq!(combine(&empty, Stat::Mean)[0][3], 0.0); +} + +#[test] +fn median_removes_outlier() { + let layers = vec![px(0.5), px(0.5), px(1.0)]; + assert_eq!(combine(&layers, Stat::Median)[0][0], 0.5); +} + +/// Five layers over six pixels (the last layer is short). Covers opaque, partly transparent, +/// fully transparent, HDR / negative, single-sample and tied-value pixels. +fn fixture() -> Vec> { + vec![ + vec![[0.10, 0.20, 0.30, 1.0], [0.5, 0.5, 0.5, 1.0], [0.9, 0.9, 0.9, 0.0], [-2.0, 4.0, 0.0, 1.0], [0.7, 0.2, 0.1, 0.5], [0.25, 0.25, 0.25, 1.0]], + vec![[0.90, 0.60, 0.30, 1.0], [0.0, 0.0, 0.0, 0.0], [0.8, 0.8, 0.8, 0.0], [3.0, -1.0, 0.5, 0.75], [0.0, 0.0, 0.0, 0.0], [0.25, 0.75, 0.25, 1.0]], + vec![[0.20, 0.90, 0.30, 0.5], [0.1, 0.2, 0.3, 1.0], [0.7, 0.7, 0.7, 0.0], [0.5, 0.5, 0.5, 1.0], [0.0, 0.0, 0.0, 0.0], [0.5, 0.75, 0.25, 0.25]], + vec![[0.30, 0.05, 0.30, 0.25], [0.3, 0.4, 0.5, 0.5], [0.6, 0.6, 0.6, 0.0], [1.5, 1.5, 1.5, 1.0], [0.0, 0.0, 0.0, 0.0], [0.25, 0.75, 0.5, 1.0]], + vec![[0.10, 0.70, 0.99, 1.0], [0.9, 0.1, 0.2, 1.0], [0.5, 0.5, 0.5, 0.0], [0.0, 0.0, 0.0, 1.0]], + ] +} + +fn bits(px: &[[f32; 4]]) -> Vec<[u32; 4]> { + px.iter().map(|p| p.map(f32::to_bits)).collect() +} + +/// Every mode except Entropy is bit-for-bit what the old serial loop produced. The expected +/// bit patterns were recorded by running the unmodified `combine` on [`fixture`]. +#[test] +fn statistics_are_bit_identical_to_the_serial_implementation() { + let layers = fixture(); + let expected: Vec<(Stat, Vec<[u32; 4]>)> = vec![ + ( + Stat::Kurtosis, + [ + [0x3e96956b, 0x3e182e3f, 0x3ea66664, 0x3f800000], + [0x3e3d004c, 0x3e0b4396, 0x3e030e1f, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3e594eb2, 0x3e6ef420, 0x3e7ffffe, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x3e6eeeee, 0x3e6eeeee, 0x3e6eeeee, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Maximum, + [ + [0x3f666666, 0x3f666666, 0x3f7d70a4, 0x3f800000], + [0x3f666666, 0x3f000000, 0x3f000000, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x40400000, 0x40800000, 0x3fc00000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3f000000, 0x3f400000, 0x3f000000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Mean, + [ + [0x3ea3d70a, 0x3efae148, 0x3ee0418a, 0x3f800000], + [0x3ee66666, 0x3e99999a, 0x3ec00000, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3f19999a, 0x3f800000, 0x3f000000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3ea00000, 0x3f200000, 0x3ea00000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Median, + [ + [0x3e4ccccd, 0x3f19999a, 0x3e99999a, 0x3f800000], + [0x3ecccccd, 0x3e99999a, 0x3ecccccd, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3f000000, 0x3f000000, 0x3f000000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3e800000, 0x3f400000, 0x3e800000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Minimum, + [ + [0x3dcccccd, 0x3d4ccccd, 0x3e99999a, 0x3f800000], + [0x3dcccccd, 0x3dcccccd, 0x3e4ccccd, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0xc0000000, 0xbf800000, 0x00000000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3e800000, 0x3e800000, 0x3e800000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Range, + [ + [0x3f4ccccc, 0x3f599999, 0x3f30a3d7, 0x3f800000], + [0x3f4ccccc, 0x3ecccccd, 0x3e99999a, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x40a00000, 0x40a00000, 0x3fc00000, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x3e800000, 0x3f000000, 0x3e800000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Skewness, + [ + [0x3f522026, 0x3ee7cf76, 0x3f600000, 0x3f800000], + [0x3f1bd152, 0x3efffffe, 0x3ee4a11b, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3eedb65a, 0x3f2ea754, 0x3f3a6c7a, 0x3f800000], + [0x3f000000, 0x3f000000, 0x3f000000, 0x3f000000], + [0x3f49e69e, 0x3e58658a, 0x3f49e69e, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::StandardDeviation, + [ + [0x3e99421e, 0x3ea23b6b, 0x3e8d4fdf, 0x3f800000], + [0x3e97739e, 0x3e21e89b, 0x3e050581, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x3fd3e0b1, 0x3fd9f9e5, 0x3f0c378c, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x3dddb3d7, 0x3e5db3d7, 0x3dddb3d7, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Summation, + [ + [0x3fcccccd, 0x401ccccd, 0x400c28f6, 0x3f800000], + [0x3fe66666, 0x3f99999a, 0x3fc00000, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x40400000, 0x40a00000, 0x40200000, 0x3f800000], + [0x3f333333, 0x3e4ccccd, 0x3dcccccd, 0x3f000000], + [0x3fa00000, 0x40200000, 0x3fa00000, 0x3f800000], + ] + .to_vec(), + ), + ( + Stat::Variance, + [ + [0x3db78033, 0x3dcd9e83, 0x3d9c022a, 0x3f800000], + [0x3db33332, 0x3ccccccd, 0x3c8a3d70, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x402f5c29, 0x4039999a, 0x3e99999a, 0x3f800000], + [0x00000000, 0x00000000, 0x00000000, 0x3f000000], + [0x3c400000, 0x3d400000, 0x3c400000, 0x3f800000], + ] + .to_vec(), + ), + ]; + for (mode, want) in expected { + assert_eq!(bits(&combine(&layers, mode)), want, "{mode:?}"); + } +} + +/// Entropy against values worked out by hand (bits of the 8-bit histogram, over log2(N)). +#[test] +fn entropy_matches_hand_computed_values() { + let out = combine(&fixture(), Stat::Entropy); + let h = |ps: &[f64]| -> f64 { + let n: f64 = ps.iter().sum(); + ps.iter().map(|c| -(c / n) * (c / n).log2()).sum::() / n.log2() + }; + // Pixel 1: four distinct values -> 2 bits / log2(4) = exactly 1. + assert_eq!(out[1][0], 1.0); + // Pixel 2: every sample transparent -> untouched. + assert_eq!(out[2], [0.0; 4]); + // Pixel 3, red: -2 and 0 land in bin 0, 3 and 1.5 clamp into bin 255, 0.5 is alone. + assert!((f64::from(out[3][0]) - h(&[2.0, 2.0, 1.0])).abs() < 1e-6, "{}", out[3][0]); + // Pixel 4: a single contributing sample has no entropy. + assert_eq!(out[4], [0.0, 0.0, 0.0, 0.5]); + // Pixel 5: three samples share a bin, one is alone, in every channel. + for (c, v) in out[5].iter().take(3).enumerate() { + assert!((f64::from(*v) - h(&[3.0, 1.0])).abs() < 1e-6, "channel {c}: {v}"); + } +} + +/// The old HashMap summed in a random order, so Entropy could differ by an ulp between runs. +/// Now the bins are summed in ascending order: repeated runs (and any thread count) agree. +#[test] +fn entropy_is_deterministic() { + let layers: Vec> = (0..7) + .map(|k| (0..3 * CHUNK + 17).map(|i| [((i * 7 + k * 13) % 11) as f32 / 10.0, ((i + k) % 5) as f32 / 4.0, ((i * k) % 9) as f32 / 8.0, 1.0]).collect()) + .collect(); + let first = bits(&combine(&layers, Stat::Entropy)); + for _ in 0..8 { + assert_eq!(bits(&combine(&layers, Stat::Entropy)), first); + } +} + +/// Chunking is invisible: a multi-chunk image (with a ragged last chunk and layers of unequal +/// length) gives, pixel by pixel, what combining that pixel on its own gives. +#[test] +fn chunked_result_equals_per_pixel_result() { + let len = 2 * CHUNK + 5; + let layer = |k: usize, n: usize| -> Vec<[f32; 4]> { + (0..n) + .map(|i| { + [ + ((i * 31 + k * 7) % 101) as f32 / 100.0, + ((i * 17 + k) % 53) as f32 / 52.0 - 0.2, + ((i + 3 * k) % 29) as f32 / 28.0, + if (i + k).is_multiple_of(4) { 0.0 } else { 0.5 + ((i + k) % 3) as f32 / 4.0 }, + ] + }) + .collect() + }; + let layers = vec![layer(1, len), layer(2, CHUNK + 3), layer(3, len - 1), layer(4, 0), layer(5, len)]; + for mode in [ + Stat::Entropy, + Stat::Kurtosis, + Stat::Maximum, + Stat::Mean, + Stat::Median, + Stat::Minimum, + Stat::Range, + Stat::Skewness, + Stat::StandardDeviation, + Stat::Summation, + Stat::Variance, + ] { + let whole = combine(&layers, mode); + assert_eq!(whole.len(), len); + for i in (0..len).step_by(97).chain([CHUNK - 1, CHUNK, CHUNK + 1, 2 * CHUNK - 1, 2 * CHUNK, len - 1]) { + let one: Vec> = layers.iter().map(|l| l.get(i).map(|p| vec![*p]).unwrap_or_default()).collect(); + assert_eq!(whole[i].map(f32::to_bits), combine(&one, mode)[0].map(f32::to_bits), "{mode:?} pixel {i}"); + } + } +} + +#[test] +fn no_layers_gives_an_empty_result() { + assert!(combine(&[], Stat::Median).is_empty()); +} + +/// [`ipow`] multiplies in the order `x·x²` for the cube and `x²·x²` for the fourth power. +#[test] +fn ipow_squares_and_multiplies() { + for x in [0.58f32, -0.12, -2.6, 2.4, -0.6, 1.0e-3, 0.0] { + assert_eq!(ipow(x, 0).to_bits(), 1.0f32.to_bits()); + assert_eq!(ipow(x, 1).to_bits(), x.to_bits()); + assert_eq!(ipow(x, 2).to_bits(), (x * x).to_bits()); + assert_eq!(ipow(x, 3).to_bits(), (x * (x * x)).to_bits()); + assert_eq!(ipow(x, 4).to_bits(), ((x * x) * (x * x)).to_bits()); + } +} From ba7399fe0c37359e6360e17bc0231283dc3b7866 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:04 +0000 Subject: [PATCH 019/259] refactor(algo): move seam.rs tests to seam/tests.rs --- crates/algo/src/seam.rs | 574 +--------------------------------- crates/algo/src/seam/tests.rs | 569 +++++++++++++++++++++++++++++++++ 2 files changed, 570 insertions(+), 573 deletions(-) create mode 100644 crates/algo/src/seam/tests.rs diff --git a/crates/algo/src/seam.rs b/crates/algo/src/seam.rs index b85fba5bab..ebf7d5a705 100644 --- a/crates/algo/src/seam.rs +++ b/crates/algo/src/seam.rs @@ -748,576 +748,4 @@ pub fn skin_mask(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - /// The straightforward implementation the per-seam carver replaced (full energy map, fresh - /// seam search and a new buffer per seam), kept as the oracle for `carver_matches_reference`. - mod reference { - use super::super::{protection, resample_protection, transpose}; - - pub(super) fn energy(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec { - let mut e = vec![0.0f32; w * h]; - for y in 0..h { - for x in 0..w { - let (xl, xr) = (x.saturating_sub(1), (x + 1).min(w - 1)); - let (yu, yd) = (y.saturating_sub(1), (y + 1).min(h - 1)); - let at = |xx: usize, yy: usize, c: usize| img[(yy * w + xx) * ch + c]; - let mut s = 0.0; - for c in 0..ch { - let v = at(x, y, c); - s += (at(xr, y, c) - v).abs() + (v - at(xl, y, c)).abs(); - s += (at(x, yd, c) - v).abs() + (v - at(x, yu, c)).abs(); - } - let v = s * 0.5; - e[y * w + x] = if v.is_nan() { f32::INFINITY } else { v }; - } - } - e - } - pub(super) fn find_seam(w: usize, h: usize, energy: &[f32]) -> Vec { - let mut cost = energy[..w].to_vec(); - let mut from = vec![0u8; w * h]; // 0 = up-left, 1 = up, 2 = up-right - let mut next = vec![0.0f32; w]; - for y in 1..h { - for x in 0..w { - let mut best = (cost[x], 1u8); - if x > 0 && cost[x - 1] < best.0 { - best = (cost[x - 1], 0); - } - if x + 1 < w && cost[x + 1] < best.0 { - best = (cost[x + 1], 2); - } - next[x] = best.0 + energy[y * w + x]; - from[y * w + x] = best.1; - } - std::mem::swap(&mut cost, &mut next); - } - let mut x = (0..w).min_by(|a, b| cost[*a].total_cmp(&cost[*b])).unwrap_or(0); - let mut seam = vec![0usize; h]; - for y in (0..h).rev() { - seam[y] = x; - if y > 0 { - x = match from[y * w + x] { - 0 => x - 1, - 2 => x + 1, - _ => x, - }; - } - } - seam - } - fn remove_seam(w: usize, h: usize, ch: usize, img: &[f32], seam: &[usize]) -> Vec { - let mut out = Vec::with_capacity((w - 1) * h * ch); - for (y, &sx) in seam.iter().enumerate().take(h) { - let row = &img[y * w * ch..(y + 1) * w * ch]; - out.extend_from_slice(&row[..sx * ch]); - out.extend_from_slice(&row[(sx + 1) * ch..]); - } - out - } - pub(super) fn carve_width(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize) -> Vec { - let new_w = new_w.max(1); - if new_w == w || w == 0 || h == 0 { - return img.to_vec(); - } - let protect_e = |e: &mut [f32], p: Option<&Vec>| { - if let Some(p) = p { - for (e, &p) in e.iter_mut().zip(p) { - *e += protection(p); - } - } - }; - if new_w < w { - let (mut cur, mut cw) = (img.to_vec(), w); - let mut prot = protect.map(<[f32]>::to_vec); - while cw > new_w { - let mut e = energy(cw, h, ch, &cur); - protect_e(&mut e, prot.as_ref()); - let seam = find_seam(cw, h, &e); - cur = remove_seam(cw, h, ch, &cur, &seam); - prot = prot.map(|p| remove_seam(cw, h, 1, &p, &seam)); - cw -= 1; - } - return cur; - } - // Enlarge in rounds of at most half the current width, each duplicating the k lowest seams. - let (mut cur, mut cw) = (img.to_vec(), w); - let mut prot = protect.map(<[f32]>::to_vec); - while cw < new_w { - let k = (new_w - cw).min((cw / 2).max(1)); - // Find k seams on a shrinking copy, mapping each back to original columns. - let mut idx: Vec> = (0..h).map(|_| (0..cw).collect()).collect(); - let (mut tmp, mut tw) = (cur.clone(), cw); - let mut tprot = prot.clone(); - let mut dup: Vec> = vec![Vec::with_capacity(k); h]; - for _ in 0..k { - // A 1 px wide image's only seam is its one column: take it, so it is duplicated. - if tw == 0 { - break; - } - let mut e = energy(tw, h, ch, &tmp); - protect_e(&mut e, tprot.as_ref()); - let seam = find_seam(tw, h, &e); - for (y, &sx) in seam.iter().enumerate() { - dup[y].push(idx[y].remove(sx)); - } - tmp = remove_seam(tw, h, ch, &tmp, &seam); - tprot = tprot.map(|p| remove_seam(tw, h, 1, &p, &seam)); - tw -= 1; - } - let added = dup[0].len(); - if added == 0 { - break; - } - let nw = cw + added; - let mut out = Vec::with_capacity(nw * h * ch); - let mut nprot = prot.as_ref().map(|_| Vec::with_capacity(nw * h)); - for (y, d) in dup.iter_mut().enumerate() { - d.sort_unstable(); - let row = &cur[y * cw * ch..(y + 1) * cw * ch]; - let mut di = 0; - for x in 0..cw { - out.extend_from_slice(&row[x * ch..(x + 1) * ch]); - if let (Some(np), Some(p)) = (nprot.as_mut(), prot.as_ref()) { - np.push(p[y * cw + x]); - } - while di < d.len() && d[di] == x { - let xr = (x + 1).min(cw - 1); - for c in 0..ch { - out.push((row[x * ch + c] + row[xr * ch + c]) * 0.5); - } - if let (Some(np), Some(p)) = (nprot.as_mut(), prot.as_ref()) { - np.push(p[y * cw + x]); - } - di += 1; - } - } - } - cur = out; - prot = nprot; - cw = nw; - } - cur - } - - pub(super) fn carve(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize, new_h: usize) -> Vec { - let (new_w, new_h) = (new_w.max(1), new_h.max(1)); - let wide = carve_width(w, h, ch, img, protect, new_w); - if new_h == h { - return wide; - } - let prot_t = protect.map(|p| transpose(new_w, h, 1, &resample_protection(w, h, p, new_w))); - let t = transpose(new_w, h, ch, &wide); - let tall = carve_width(h, new_w, ch, &t, prot_t.as_deref(), new_h); - transpose(new_h, new_w, ch, &tall) - } - } - - /// The carver gives bit-identical output to the reference implementation it replaced, over - /// random shapes (including 1 px wide and tall), channel counts, tie-heavy quantised noise, - /// protection, shrinking, enlarging past half the width and both axes at once. - #[test] - fn carver_matches_reference() { - let mut seed = 1u32; - let mut next = |n: usize| { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - seed as usize % n - }; - for case in 0..400u32 { - let (w, h, ch) = (1 + next(24), 1 + next(18), [1, 3, 4][next(3)]); - let levels = [2, 5, 255, 65_536][next(4)]; - let img = noise(w * h * ch, levels, 11 + case); - let protect = (next(3) == 0).then(|| noise(w * h, 3, 101 + case)); - let (nw, nh) = (1 + next(2 * w + 2), 1 + next(2 * h + 2)); - let got = carve(w, h, ch, &img, protect.as_deref(), nw, nh); - let want = reference::carve(w, h, ch, &img, protect.as_deref(), nw, nh); - let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::>(); - assert_eq!(bits(&got), bits(&want), "case {case}: {w}x{h}x{ch} -> {nw}x{nh}, levels {levels}, protect {}", protect.is_some()); - } - // The seam search alone, on raw energy maps full of ties. - for case in 0..200u32 { - let (w, h) = (1 + next(40), 1 + next(30)); - let e = noise(w * h, [2, 3, 1000][next(3)], 7 + case); - assert_eq!(find_seam(w, h, &e), reference::find_seam(w, h, &e), "seam case {case}: {w}x{h}"); - let img = noise(w * h * 3, 7, 3 + case); - let bits = |v: Vec| v.into_iter().map(f32::to_bits).collect::>(); - assert_eq!(bits(energy(w, h, 3, &img)), bits(reference::energy(w, h, 3, &img)), "energy case {case}"); - } - } - - /// After every removal, the carver's incrementally updated seam search matches a full pass - /// over its current energy bit for bit (path costs and the seam traced from them), on images - /// where seams run through the edges, through flat areas full of ties and through protection. - /// Its energy matches a fresh map of the pixels left, and so do the pixels. - #[test] - fn incremental_dp_matches_full_dp() { - let mut ramp = vec![0.0f32; 120 * 90]; - for (i, v) in ramp.iter_mut().enumerate() { - let (x, y) = ((i % 120) as f32, (i / 120) as f32); - *v = ((x * 0.07).sin() * (y * 0.05).cos() * 0.5 + 0.5).clamp(0.0, 1.0); - } - // NaN and infinite samples and NaN protection: infinite energies, never NaN costs. - let mut odd = noise(40 * 30 * 3, 255, 11); - odd.iter_mut().step_by(13).for_each(|v| *v = f32::NAN); - odd.iter_mut().skip(5).step_by(17).for_each(|v| *v = f32::INFINITY); - let mut odd_prot = noise(40 * 30, 3, 12); - odd_prot.iter_mut().step_by(7).for_each(|v| *v = -f32::NAN); - // (w, h, channels, image, protection, seams to remove) - type Case = (usize, usize, usize, Vec, Option>, usize); - let cases: Vec = vec![ - (120, 90, 1, ramp, None, 40), - (97, 64, 3, noise(97 * 64 * 3, 2, 5), None, 90), - (80, 70, 4, noise(80 * 70 * 4, 1000, 6), Some(noise(80 * 70, 3, 7)), 60), - (64, 50, 3, bar(64, 50), None, 63), - (33, 1, 1, noise(33, 5, 8), None, 32), - (2, 40, 3, noise(2 * 40 * 3, 9, 9), None, 2), - (50, 40, 1, vec![0.5; 50 * 40], Some(noise(50 * 40, 2, 10)), 49), - (40, 30, 3, odd, Some(odd_prot), 25), - ]; - let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::>(); - for (case, (w, h, ch, img, prot, seams)) in cases.into_iter().enumerate() { - let mut c = Carver::new(w, h, ch, &img, prot.as_deref()); - for step in 0..=seams { - let rows = Rows { stride: c.w, cw: c.cw, off: &c.off }; - let mut fresh = Dp::default(); - fresh.full(rows, &c.e); - for y in 0..h { - assert_eq!(bits(&c.dp.cost[rows.of(y)]), bits(&fresh.cost[rows.of(y)]), "case {case} step {step} row {y}: costs"); - } - assert_eq!(c.dp.seam(rows), fresh.seam(rows), "case {case} step {step}: seam"); - // The pixels left, packed, and their energy (plus protection) from scratch. - let left: Vec = (0..h) - .flat_map(|y| c.idx[rows.of(y)].iter().flat_map(move |&x| (0..ch).map(move |k| (y * w + x as usize) * ch + k))) - .map(|i| img[i]) - .collect(); - let mut want = energy(c.cw, h, ch, &left); - if let Some(p) = &prot { - let kept = (0..h).flat_map(|y| c.idx[rows.of(y)].iter().map(move |&x| y * w + x as usize)); - for (e, i) in want.iter_mut().zip(kept) { - *e += protection(p[i]); - } - } - let have: Vec = (0..h).flat_map(|y| c.e[rows.of(y)].to_vec()).collect(); - assert_eq!(bits(&have), bits(&want), "case {case} step {step}: energy"); - if step == seams { - assert_eq!(bits(&c.into_pixels()), bits(&left), "case {case}: pixels"); - break; - } - c.remove_seam(); - } - } - } - - /// Hostile but well-formed shapes return early instead of panicking: no channels, empty - /// sizes (also through the height pass), and images or protection maps shorter than their - /// size says (a short map protects nothing). - #[test] - fn degenerate_inputs_do_not_panic() { - assert!(carve(3, 3, 0, &[], None, 2, 2).is_empty()); - assert!(carve(3, 3, 0, &[], None, 5, 5).is_empty()); - assert!(transpose(3, 3, 0, &[]).is_empty()); - assert!(resize_bilinear(3, 3, 0, &[], 2, 2).is_empty()); - assert!(resize_bilinear(3, 3, 1, &[0.5; 9], 0, 2).is_empty()); - assert!(resize_bilinear(3, 3, 1, &[0.5; 9], 2, 0).is_empty()); - assert_eq!(resize_bilinear(3, 3, 1, &[0.5; 4], 2, 2), vec![0.0; 4]); - assert!(carve(0, 5, 3, &[], None, 3, 7).is_empty()); - assert!(carve(0, 5, 3, &[], None, 3, 2).is_empty()); - let img = noise(10 * 5, 7, 3); - assert_eq!(carve(10, 5, 1, &img, Some(&[0.0; 3]), 4, 5), carve(10, 5, 1, &img, None, 4, 5)); - assert_eq!(carve(10, 5, 1, &img, Some(&[0.0; 3]), 4, 3), carve(10, 5, 1, &img, None, 4, 3)); - assert_eq!(carve(10, 5, 3, &[0.5; 20], None, 4, 5), vec![0.5; 20]); - assert_eq!(carve_width(usize::MAX, 2, 4, &[0.5; 8], None, 1), vec![0.5; 8]); - // Values past the size are ignored, through both passes. - let long = noise(20, 7, 4); - assert_eq!(carve(5, 3, 1, &long, None, 3, 3), carve(5, 3, 1, &long[..15], None, 3, 3)); - assert_eq!(carve(5, 3, 1, &long, None, 5, 2), carve(5, 3, 1, &long[..15], None, 5, 2)); - } - - /// Infinite samples, and finite ones whose differences overflow, give energies that aren't - /// numbers; those are the highest energy (pinned deliberately: the code before NaN-free costs - /// fed NaN to the seam search and chose differently). - #[test] - fn infinite_samples_carve_deterministically() { - let inf = f32::INFINITY; - assert_eq!(carve(2, 1, 1, &[inf, 0.5], None, 1, 1), [0.5]); - assert_eq!(carve(2, 1, 1, &[f32::MAX, f32::MAX], None, 6, 1), [f32::MAX, inf, inf, inf, inf, f32::MAX]); - let mut img = noise(30 * 20 * 3, 255, 41); - img.iter_mut().step_by(11).for_each(|v| *v = inf); - img.iter_mut().skip(4).step_by(23).for_each(|v| *v = -inf); - let out = carve(30, 20, 3, &img, None, 21, 14); - assert_eq!(out.len(), 21 * 14 * 3); - assert_eq!(out, carve(30, 20, 3, &img, None, 21, 14)); - } - - /// Infinite protection protects like full protection in the height pass too, where the map - /// is resampled (and an infinity alone would resample to NaN). - #[test] - fn infinite_protection_protects_in_both_passes() { - let (w, h) = (6, 6); - let img: Vec = (0..w * h).map(|i| (i * 7 % 5) as f32 / 4.0).collect(); - let row = |v: f32| (0..w * h).map(|i| if i / w == 2 { v } else { 0.0 }).collect::>(); - let (full, inf) = (row(1.0), row(f32::INFINITY)); - for (nw, nh) in [(6, 3), (4, 3), (3, 6)] { - assert_eq!(carve(w, h, 1, &img, Some(&inf), nw, nh), carve(w, h, 1, &img, Some(&full), nw, nh), "{nw}x{nh}"); - } - let kept = carve(w, h, 1, &img, Some(&inf), 6, 3); - assert!(kept.chunks(6).any(|r| r == &img[12..18]), "the protected row survives"); - } - - /// A cancel that arrives after the seam search, during the tall-image rebuild, still stops - /// the carve. - #[test] - fn proxy_rebuild_observes_cancellation() { - use std::sync::atomic::{AtomicUsize, Ordering}; - let (w, h, ch, new_w) = (128, PROXY_SHRINK_MIN_HEIGHT, 3, 64); - let img = noise(w * h * ch, 7, 5); - let calls = AtomicUsize::new(0); - // One check per seam passes; the first one after the search cancels. - let cancel = || calls.fetch_add(1, Ordering::Relaxed) >= w - new_w; - assert_eq!(carve_width_with(w, h, ch, &img, None, new_w, &Interrupt::cancel_only(&cancel)), Err(Cancelled)); - assert!(calls.load(Ordering::Relaxed) > w - new_w, "the rebuild checked for cancellation"); - } - - /// NaN samples and NaN protection steer seams the same whatever their sign and payload - /// (which arithmetic does not preserve consistently across builds): the same pixels are kept. - #[test] - fn nan_payloads_do_not_steer_seams() { - let (w, h, ch) = (24, 18, 3); - let (base, prot_base) = (noise(w * h * ch, 255, 21), noise(w * h, 3, 22)); - let carve_with_nans = |pixel: f32, prot: f32| { - let (mut img, mut p) = (base.clone(), prot_base.clone()); - img.iter_mut().step_by(37).for_each(|v| *v = pixel); - p.iter_mut().step_by(29).for_each(|v| *v = prot); - carve(w, h, ch, &img, Some(&p), 15, 11) - }; - let canonical = |v: Vec| v.into_iter().map(|f| if f.is_nan() { u32::MAX } else { f.to_bits() }).collect::>(); - let nans = [f32::NAN, -f32::NAN, f32::from_bits(0x7fc0_1234), f32::from_bits(0xffc0_0001)]; - let want = canonical(carve_with_nans(nans[0], nans[0])); - for &a in &nans { - for &b in &nans { - assert_eq!(canonical(carve_with_nans(a, b)), want, "pixel NaN {:#x}, protection NaN {:#x}", a.to_bits(), b.to_bits()); - } - } - } - - #[test] - fn cancelled_carve_stops() { - let (w, h) = (40, 20); - let img = vec![0.5f32; w * h * 3]; - let yes = || true; - assert_eq!(carve_with(w, h, 3, &img, None, 30, 15, &Interrupt::cancel_only(&yes)), Err(Cancelled)); - assert_eq!(carve_with(w, h, 3, &img, None, 30, 15, &Interrupt::NONE).unwrap(), carve(w, h, 3, &img, None, 30, 15)); - } - - /// A flat grey image with a salient vertical bar at x = 10..14 (red/blue columns). - fn bar(w: usize, h: usize) -> Vec { - let mut v = vec![0.5f32; w * h * 3]; - for y in 0..h { - for x in 10..14 { - let c = if x % 2 == 0 { [1.0, 0.0, 0.0] } else { [0.0, 0.0, 1.0] }; - v[(y * w + x) * 3..(y * w + x) * 3 + 3].copy_from_slice(&c); - } - } - v - } - - /// Columns that are pure red or pure blue top to bottom. - fn red_columns(w: usize, h: usize, img: &[f32]) -> usize { - let pure = |p: &[f32]| p[1] < 0.05 && ((p[0] > 0.95 && p[2] < 0.05) || (p[2] > 0.95 && p[0] < 0.05)); - (0..w).filter(|x| (0..h).all(|y| pure(&img[(y * w + x) * 3..(y * w + x) * 3 + 3]))).count() - } - - #[test] - fn seam_follows_low_energy() { - let (w, h) = (5, 4); - let mut e = vec![9.0f32; w * h]; - for y in 0..h { - e[y * w + 2] = 0.0; - } - assert_eq!(find_seam(w, h, &e), vec![2; 4]); - } - - #[test] - fn shrinking_keeps_the_salient_bar() { - let (w, h) = (40, 12); - let img = bar(w, h); - let out = carve(w, h, 3, &img, None, 24, h); - assert_eq!(out.len(), 24 * h * 3); - assert_eq!(red_columns(24, h, &out), 4, "the bar survives intact"); - // Plain resampling squashes it instead. - let plain = resize_bilinear(w, h, 3, &img, 24, h); - assert!(red_columns(24, h, &plain) < 4); - } - - #[test] - fn tall_proxy_shrink_preserves_full_resolution_salient_and_protected_pixels() { - let (w, h, ch, new_w) = (512, PROXY_SHRINK_MIN_HEIGHT, 3, 384); - let mut img = bar(w, h); - let mut protect = vec![0.0; w * h]; - for y in 0..h { - let i = (y * w + 256) * ch; - img[i..i + ch].copy_from_slice(&[0.03, 0.87, 0.42]); - protect[y * w + 256] = 1.0; - } - - let out = carve_width_with(w, h, ch, &img, Some(&protect), new_w, &Interrupt::NONE).unwrap(); - - assert_eq!(out.len(), new_w * h * ch); - assert_eq!(red_columns(new_w, h, &out), 4, "the full-resolution bar survives"); - for y in 0..h { - let row = &out[y * new_w * ch..(y + 1) * new_w * ch]; - assert!(row.chunks_exact(ch).any(|px| px == [0.03, 0.87, 0.42]), "protected mark survives row {y}"); - } - } - - #[test] - fn tall_proxy_shrink_observes_cancellation_before_modifying_source() { - let (w, h, ch) = (128, PROXY_SHRINK_MIN_HEIGHT, 3); - let img = vec![0.5; w * h * ch]; - let cancelled = || true; - assert_eq!(carve_width_with(w, h, ch, &img, None, 64, &Interrupt::cancel_only(&cancelled)), Err(Cancelled)); - } - - #[test] - fn enlarging_duplicates_flat_areas() { - let (w, h) = (30, 8); - let img = bar(w, h); - let out = carve(w, h, 3, &img, None, 50, h); - assert_eq!(out.len(), 50 * h * 3); - assert_eq!(red_columns(50, h, &out), 4); - } - - #[test] - fn height_and_protection() { - let (w, h) = (20, 30); - // Horizontal bar: carve height. - let mut img = vec![0.2f32; w * h]; - for x in 0..w { - img[12 * w + x] = 1.0; - } - let out = carve(w, h, 1, &img, None, w, 18); - assert_eq!(out.len(), w * 18); - assert_eq!((0..18).filter(|y| (0..w).all(|x| out[y * w + x] > 0.9)).count(), 1); - // Protecting a flat region keeps it: the seams go elsewhere. - let flat = vec![0.5f32; 16 * 4]; - let mut protect = vec![0.0f32; 16 * 4]; - for y in 0..4 { - protect[y * 16 + 3] = 1.0; - } - let mut marked = flat.clone(); - for y in 0..4 { - marked[y * 16 + 3] = 0.51; - } - let out = carve(16, 4, 1, &marked, Some(&protect), 8, 4); - assert!((0..4).all(|y| out[y * 8..y * 8 + 8].iter().any(|v| (*v - 0.51).abs() < 1e-6))); - } - - /// Noise quantised to `levels` values, so the energy map is full of exact ties. - fn noise(len: usize, levels: u32, seed: u32) -> Vec { - let mut s = seed | 1; - (0..len) - .map(|_| { - s ^= s << 13; - s ^= s >> 17; - s ^= s << 5; - (s % levels) as f32 / (levels - 1) as f32 - }) - .collect() - } - - fn fnv(v: &[f32]) -> u64 { - v.iter().flat_map(|f| f.to_bits().to_le_bytes()).fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)) - } - - /// The exact output bits of a spread of carves (shrink, enlarge past half the width, both - /// axes, protection, 1/3/4 channels, tie-heavy and smooth images), pinned so that speed work - /// can't change which seams are chosen or how pixels are blended. - #[test] - fn output_bits_are_pinned() { - let cases: [(usize, usize, usize, u32, bool, usize, usize); 8] = [ - (61, 47, 3, 2, false, 40, 47), - (61, 47, 3, 255, false, 61, 30), - (61, 47, 4, 4, true, 35, 29), - (33, 20, 1, 3, false, 80, 20), - (33, 20, 3, 1000, true, 50, 45), - (48, 36, 4, 7, false, 70, 18), - (5, 3, 1, 2, false, 1, 1), - (40, 40, 3, 2, true, 39, 41), - ]; - let got: Vec = cases - .iter() - .enumerate() - .map(|(i, &(w, h, ch, levels, prot, nw, nh))| { - let img = noise(w * h * ch, levels, 7 + i as u32); - let protect = prot.then(|| noise(w * h, 3, 99 + i as u32)); - let out = carve(w, h, ch, &img, protect.as_deref(), nw, nh); - assert_eq!(out.len(), nw * nh * ch); - fnv(&out) - }) - .collect(); - assert_eq!(got, PINNED); - } - - const PINNED: [u64; 8] = [ - 0x24ea_9353_02c2_7c58, - 0x5a6e_8554_a0cb_ebb1, - 0x8b18_d63f_396e_21c9, - 0x1db2_23ad_3e6a_a7c5, - 0x721d_6cc5_34e0_3fdf, - 0x961a_ea6d_e512_ec7d, - 0x4d25_767f_9dce_13f5, - 0x2157_9f86_27d6_b835, - ]; - - /// [`output_bits_are_pinned`] for the reduced-height seam search of tall images (rows at - /// least [`PROXY_SHRINK_MIN_HEIGHT`], at least [`PROXY_SHRINK_MIN_SEAMS`] seams): widths and, - /// through the transposed pass, heights, with and without protection, on tie-heavy and - /// fine-grained noise. - #[test] - fn tall_proxy_output_bits_are_pinned() { - let cases: [(usize, usize, usize, u32, bool, usize, usize); 5] = [ - (96, PROXY_SHRINK_MIN_HEIGHT, 3, 2, false, 30, PROXY_SHRINK_MIN_HEIGHT), - (130, 2_100, 4, 255, true, 64, 2_100), - (80, 2_600, 1, 65_536, false, 16, 2_600), - (PROXY_SHRINK_MIN_HEIGHT, 90, 3, 5, false, PROXY_SHRINK_MIN_HEIGHT, 20), - (2_050, 100, 4, 1000, true, 2_050, 36), - ]; - let got: Vec = cases - .iter() - .enumerate() - .map(|(i, &(w, h, ch, levels, prot, nw, nh))| { - let img = noise(w * h * ch, levels, 31 + i as u32); - let protect = prot.then(|| noise(w * h, 3, 131 + i as u32)); - let out = carve(w, h, ch, &img, protect.as_deref(), nw, nh); - assert_eq!(out.len(), nw * nh * ch); - fnv(&out) - }) - .collect(); - assert_eq!(got, TALL_PINNED); - } - - const TALL_PINNED: [u64; 5] = [0x5657_83ac_cb26_56a5, 0x81a6_b5f7_e299_fdfb, 0xcdf2_9df9_9b83_def5, 0xa713_544a_4dcc_d8d8, 0x3557_de9f_ffb0_881e]; - - #[test] - fn one_pixel_lines_enlarge_by_repeating() { - // Width 1 has no seam to spare: its one column is repeated. Height 1 likewise (through - // the transposed pass), alone or with the other axis. - let col = [0.1f32, 0.2, 0.3, 0.4, 0.5]; - assert_eq!(carve(1, 5, 1, &col, None, 4, 5), col.iter().flat_map(|v| [*v; 4]).collect::>()); - assert_eq!(carve(5, 1, 1, &col, None, 5, 3), col.repeat(3)); - assert_eq!(carve(1, 1, 3, &[0.7, 0.8, 0.9], None, 3, 2), [0.7, 0.8, 0.9].repeat(6)); - for (w, h, nw, nh) in [(1, 5, 6, 10), (1, 17, 6, 34), (16, 1, 21, 2), (7, 1, 3, 8), (2, 1, 1, 8)] { - let img = vec![0.5f32; w * h * 4]; - assert_eq!(carve(w, h, 4, &img, Some(&vec![1.0; w * h]), nw, nh).len(), nw * nh * 4, "{w}x{h} -> {nw}x{nh}"); - } - } - - #[test] - fn skin_rule() { - let px = [0.86f32, 0.62, 0.5, 0.2, 0.4, 0.8]; - assert_eq!(skin_mask(2, 1, 3, &px), vec![1.0, 0.0]); - } -} +mod tests; diff --git a/crates/algo/src/seam/tests.rs b/crates/algo/src/seam/tests.rs new file mode 100644 index 0000000000..5788b03ce2 --- /dev/null +++ b/crates/algo/src/seam/tests.rs @@ -0,0 +1,569 @@ +use super::*; + +/// The straightforward implementation the per-seam carver replaced (full energy map, fresh +/// seam search and a new buffer per seam), kept as the oracle for `carver_matches_reference`. +mod reference { + use super::super::{protection, resample_protection, transpose}; + + pub(super) fn energy(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec { + let mut e = vec![0.0f32; w * h]; + for y in 0..h { + for x in 0..w { + let (xl, xr) = (x.saturating_sub(1), (x + 1).min(w - 1)); + let (yu, yd) = (y.saturating_sub(1), (y + 1).min(h - 1)); + let at = |xx: usize, yy: usize, c: usize| img[(yy * w + xx) * ch + c]; + let mut s = 0.0; + for c in 0..ch { + let v = at(x, y, c); + s += (at(xr, y, c) - v).abs() + (v - at(xl, y, c)).abs(); + s += (at(x, yd, c) - v).abs() + (v - at(x, yu, c)).abs(); + } + let v = s * 0.5; + e[y * w + x] = if v.is_nan() { f32::INFINITY } else { v }; + } + } + e + } + pub(super) fn find_seam(w: usize, h: usize, energy: &[f32]) -> Vec { + let mut cost = energy[..w].to_vec(); + let mut from = vec![0u8; w * h]; // 0 = up-left, 1 = up, 2 = up-right + let mut next = vec![0.0f32; w]; + for y in 1..h { + for x in 0..w { + let mut best = (cost[x], 1u8); + if x > 0 && cost[x - 1] < best.0 { + best = (cost[x - 1], 0); + } + if x + 1 < w && cost[x + 1] < best.0 { + best = (cost[x + 1], 2); + } + next[x] = best.0 + energy[y * w + x]; + from[y * w + x] = best.1; + } + std::mem::swap(&mut cost, &mut next); + } + let mut x = (0..w).min_by(|a, b| cost[*a].total_cmp(&cost[*b])).unwrap_or(0); + let mut seam = vec![0usize; h]; + for y in (0..h).rev() { + seam[y] = x; + if y > 0 { + x = match from[y * w + x] { + 0 => x - 1, + 2 => x + 1, + _ => x, + }; + } + } + seam + } + fn remove_seam(w: usize, h: usize, ch: usize, img: &[f32], seam: &[usize]) -> Vec { + let mut out = Vec::with_capacity((w - 1) * h * ch); + for (y, &sx) in seam.iter().enumerate().take(h) { + let row = &img[y * w * ch..(y + 1) * w * ch]; + out.extend_from_slice(&row[..sx * ch]); + out.extend_from_slice(&row[(sx + 1) * ch..]); + } + out + } + pub(super) fn carve_width(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize) -> Vec { + let new_w = new_w.max(1); + if new_w == w || w == 0 || h == 0 { + return img.to_vec(); + } + let protect_e = |e: &mut [f32], p: Option<&Vec>| { + if let Some(p) = p { + for (e, &p) in e.iter_mut().zip(p) { + *e += protection(p); + } + } + }; + if new_w < w { + let (mut cur, mut cw) = (img.to_vec(), w); + let mut prot = protect.map(<[f32]>::to_vec); + while cw > new_w { + let mut e = energy(cw, h, ch, &cur); + protect_e(&mut e, prot.as_ref()); + let seam = find_seam(cw, h, &e); + cur = remove_seam(cw, h, ch, &cur, &seam); + prot = prot.map(|p| remove_seam(cw, h, 1, &p, &seam)); + cw -= 1; + } + return cur; + } + // Enlarge in rounds of at most half the current width, each duplicating the k lowest seams. + let (mut cur, mut cw) = (img.to_vec(), w); + let mut prot = protect.map(<[f32]>::to_vec); + while cw < new_w { + let k = (new_w - cw).min((cw / 2).max(1)); + // Find k seams on a shrinking copy, mapping each back to original columns. + let mut idx: Vec> = (0..h).map(|_| (0..cw).collect()).collect(); + let (mut tmp, mut tw) = (cur.clone(), cw); + let mut tprot = prot.clone(); + let mut dup: Vec> = vec![Vec::with_capacity(k); h]; + for _ in 0..k { + // A 1 px wide image's only seam is its one column: take it, so it is duplicated. + if tw == 0 { + break; + } + let mut e = energy(tw, h, ch, &tmp); + protect_e(&mut e, tprot.as_ref()); + let seam = find_seam(tw, h, &e); + for (y, &sx) in seam.iter().enumerate() { + dup[y].push(idx[y].remove(sx)); + } + tmp = remove_seam(tw, h, ch, &tmp, &seam); + tprot = tprot.map(|p| remove_seam(tw, h, 1, &p, &seam)); + tw -= 1; + } + let added = dup[0].len(); + if added == 0 { + break; + } + let nw = cw + added; + let mut out = Vec::with_capacity(nw * h * ch); + let mut nprot = prot.as_ref().map(|_| Vec::with_capacity(nw * h)); + for (y, d) in dup.iter_mut().enumerate() { + d.sort_unstable(); + let row = &cur[y * cw * ch..(y + 1) * cw * ch]; + let mut di = 0; + for x in 0..cw { + out.extend_from_slice(&row[x * ch..(x + 1) * ch]); + if let (Some(np), Some(p)) = (nprot.as_mut(), prot.as_ref()) { + np.push(p[y * cw + x]); + } + while di < d.len() && d[di] == x { + let xr = (x + 1).min(cw - 1); + for c in 0..ch { + out.push((row[x * ch + c] + row[xr * ch + c]) * 0.5); + } + if let (Some(np), Some(p)) = (nprot.as_mut(), prot.as_ref()) { + np.push(p[y * cw + x]); + } + di += 1; + } + } + } + cur = out; + prot = nprot; + cw = nw; + } + cur + } + + pub(super) fn carve(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize, new_h: usize) -> Vec { + let (new_w, new_h) = (new_w.max(1), new_h.max(1)); + let wide = carve_width(w, h, ch, img, protect, new_w); + if new_h == h { + return wide; + } + let prot_t = protect.map(|p| transpose(new_w, h, 1, &resample_protection(w, h, p, new_w))); + let t = transpose(new_w, h, ch, &wide); + let tall = carve_width(h, new_w, ch, &t, prot_t.as_deref(), new_h); + transpose(new_h, new_w, ch, &tall) + } +} + +/// The carver gives bit-identical output to the reference implementation it replaced, over +/// random shapes (including 1 px wide and tall), channel counts, tie-heavy quantised noise, +/// protection, shrinking, enlarging past half the width and both axes at once. +#[test] +fn carver_matches_reference() { + let mut seed = 1u32; + let mut next = |n: usize| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed as usize % n + }; + for case in 0..400u32 { + let (w, h, ch) = (1 + next(24), 1 + next(18), [1, 3, 4][next(3)]); + let levels = [2, 5, 255, 65_536][next(4)]; + let img = noise(w * h * ch, levels, 11 + case); + let protect = (next(3) == 0).then(|| noise(w * h, 3, 101 + case)); + let (nw, nh) = (1 + next(2 * w + 2), 1 + next(2 * h + 2)); + let got = carve(w, h, ch, &img, protect.as_deref(), nw, nh); + let want = reference::carve(w, h, ch, &img, protect.as_deref(), nw, nh); + let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::>(); + assert_eq!(bits(&got), bits(&want), "case {case}: {w}x{h}x{ch} -> {nw}x{nh}, levels {levels}, protect {}", protect.is_some()); + } + // The seam search alone, on raw energy maps full of ties. + for case in 0..200u32 { + let (w, h) = (1 + next(40), 1 + next(30)); + let e = noise(w * h, [2, 3, 1000][next(3)], 7 + case); + assert_eq!(find_seam(w, h, &e), reference::find_seam(w, h, &e), "seam case {case}: {w}x{h}"); + let img = noise(w * h * 3, 7, 3 + case); + let bits = |v: Vec| v.into_iter().map(f32::to_bits).collect::>(); + assert_eq!(bits(energy(w, h, 3, &img)), bits(reference::energy(w, h, 3, &img)), "energy case {case}"); + } +} + +/// After every removal, the carver's incrementally updated seam search matches a full pass +/// over its current energy bit for bit (path costs and the seam traced from them), on images +/// where seams run through the edges, through flat areas full of ties and through protection. +/// Its energy matches a fresh map of the pixels left, and so do the pixels. +#[test] +fn incremental_dp_matches_full_dp() { + let mut ramp = vec![0.0f32; 120 * 90]; + for (i, v) in ramp.iter_mut().enumerate() { + let (x, y) = ((i % 120) as f32, (i / 120) as f32); + *v = ((x * 0.07).sin() * (y * 0.05).cos() * 0.5 + 0.5).clamp(0.0, 1.0); + } + // NaN and infinite samples and NaN protection: infinite energies, never NaN costs. + let mut odd = noise(40 * 30 * 3, 255, 11); + odd.iter_mut().step_by(13).for_each(|v| *v = f32::NAN); + odd.iter_mut().skip(5).step_by(17).for_each(|v| *v = f32::INFINITY); + let mut odd_prot = noise(40 * 30, 3, 12); + odd_prot.iter_mut().step_by(7).for_each(|v| *v = -f32::NAN); + // (w, h, channels, image, protection, seams to remove) + type Case = (usize, usize, usize, Vec, Option>, usize); + let cases: Vec = vec![ + (120, 90, 1, ramp, None, 40), + (97, 64, 3, noise(97 * 64 * 3, 2, 5), None, 90), + (80, 70, 4, noise(80 * 70 * 4, 1000, 6), Some(noise(80 * 70, 3, 7)), 60), + (64, 50, 3, bar(64, 50), None, 63), + (33, 1, 1, noise(33, 5, 8), None, 32), + (2, 40, 3, noise(2 * 40 * 3, 9, 9), None, 2), + (50, 40, 1, vec![0.5; 50 * 40], Some(noise(50 * 40, 2, 10)), 49), + (40, 30, 3, odd, Some(odd_prot), 25), + ]; + let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::>(); + for (case, (w, h, ch, img, prot, seams)) in cases.into_iter().enumerate() { + let mut c = Carver::new(w, h, ch, &img, prot.as_deref()); + for step in 0..=seams { + let rows = Rows { stride: c.w, cw: c.cw, off: &c.off }; + let mut fresh = Dp::default(); + fresh.full(rows, &c.e); + for y in 0..h { + assert_eq!(bits(&c.dp.cost[rows.of(y)]), bits(&fresh.cost[rows.of(y)]), "case {case} step {step} row {y}: costs"); + } + assert_eq!(c.dp.seam(rows), fresh.seam(rows), "case {case} step {step}: seam"); + // The pixels left, packed, and their energy (plus protection) from scratch. + let left: Vec = + (0..h).flat_map(|y| c.idx[rows.of(y)].iter().flat_map(move |&x| (0..ch).map(move |k| (y * w + x as usize) * ch + k))).map(|i| img[i]).collect(); + let mut want = energy(c.cw, h, ch, &left); + if let Some(p) = &prot { + let kept = (0..h).flat_map(|y| c.idx[rows.of(y)].iter().map(move |&x| y * w + x as usize)); + for (e, i) in want.iter_mut().zip(kept) { + *e += protection(p[i]); + } + } + let have: Vec = (0..h).flat_map(|y| c.e[rows.of(y)].to_vec()).collect(); + assert_eq!(bits(&have), bits(&want), "case {case} step {step}: energy"); + if step == seams { + assert_eq!(bits(&c.into_pixels()), bits(&left), "case {case}: pixels"); + break; + } + c.remove_seam(); + } + } +} + +/// Hostile but well-formed shapes return early instead of panicking: no channels, empty +/// sizes (also through the height pass), and images or protection maps shorter than their +/// size says (a short map protects nothing). +#[test] +fn degenerate_inputs_do_not_panic() { + assert!(carve(3, 3, 0, &[], None, 2, 2).is_empty()); + assert!(carve(3, 3, 0, &[], None, 5, 5).is_empty()); + assert!(transpose(3, 3, 0, &[]).is_empty()); + assert!(resize_bilinear(3, 3, 0, &[], 2, 2).is_empty()); + assert!(resize_bilinear(3, 3, 1, &[0.5; 9], 0, 2).is_empty()); + assert!(resize_bilinear(3, 3, 1, &[0.5; 9], 2, 0).is_empty()); + assert_eq!(resize_bilinear(3, 3, 1, &[0.5; 4], 2, 2), vec![0.0; 4]); + assert!(carve(0, 5, 3, &[], None, 3, 7).is_empty()); + assert!(carve(0, 5, 3, &[], None, 3, 2).is_empty()); + let img = noise(10 * 5, 7, 3); + assert_eq!(carve(10, 5, 1, &img, Some(&[0.0; 3]), 4, 5), carve(10, 5, 1, &img, None, 4, 5)); + assert_eq!(carve(10, 5, 1, &img, Some(&[0.0; 3]), 4, 3), carve(10, 5, 1, &img, None, 4, 3)); + assert_eq!(carve(10, 5, 3, &[0.5; 20], None, 4, 5), vec![0.5; 20]); + assert_eq!(carve_width(usize::MAX, 2, 4, &[0.5; 8], None, 1), vec![0.5; 8]); + // Values past the size are ignored, through both passes. + let long = noise(20, 7, 4); + assert_eq!(carve(5, 3, 1, &long, None, 3, 3), carve(5, 3, 1, &long[..15], None, 3, 3)); + assert_eq!(carve(5, 3, 1, &long, None, 5, 2), carve(5, 3, 1, &long[..15], None, 5, 2)); +} + +/// Infinite samples, and finite ones whose differences overflow, give energies that aren't +/// numbers; those are the highest energy (pinned deliberately: the code before NaN-free costs +/// fed NaN to the seam search and chose differently). +#[test] +fn infinite_samples_carve_deterministically() { + let inf = f32::INFINITY; + assert_eq!(carve(2, 1, 1, &[inf, 0.5], None, 1, 1), [0.5]); + assert_eq!(carve(2, 1, 1, &[f32::MAX, f32::MAX], None, 6, 1), [f32::MAX, inf, inf, inf, inf, f32::MAX]); + let mut img = noise(30 * 20 * 3, 255, 41); + img.iter_mut().step_by(11).for_each(|v| *v = inf); + img.iter_mut().skip(4).step_by(23).for_each(|v| *v = -inf); + let out = carve(30, 20, 3, &img, None, 21, 14); + assert_eq!(out.len(), 21 * 14 * 3); + assert_eq!(out, carve(30, 20, 3, &img, None, 21, 14)); +} + +/// Infinite protection protects like full protection in the height pass too, where the map +/// is resampled (and an infinity alone would resample to NaN). +#[test] +fn infinite_protection_protects_in_both_passes() { + let (w, h) = (6, 6); + let img: Vec = (0..w * h).map(|i| (i * 7 % 5) as f32 / 4.0).collect(); + let row = |v: f32| (0..w * h).map(|i| if i / w == 2 { v } else { 0.0 }).collect::>(); + let (full, inf) = (row(1.0), row(f32::INFINITY)); + for (nw, nh) in [(6, 3), (4, 3), (3, 6)] { + assert_eq!(carve(w, h, 1, &img, Some(&inf), nw, nh), carve(w, h, 1, &img, Some(&full), nw, nh), "{nw}x{nh}"); + } + let kept = carve(w, h, 1, &img, Some(&inf), 6, 3); + assert!(kept.chunks(6).any(|r| r == &img[12..18]), "the protected row survives"); +} + +/// A cancel that arrives after the seam search, during the tall-image rebuild, still stops +/// the carve. +#[test] +fn proxy_rebuild_observes_cancellation() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let (w, h, ch, new_w) = (128, PROXY_SHRINK_MIN_HEIGHT, 3, 64); + let img = noise(w * h * ch, 7, 5); + let calls = AtomicUsize::new(0); + // One check per seam passes; the first one after the search cancels. + let cancel = || calls.fetch_add(1, Ordering::Relaxed) >= w - new_w; + assert_eq!(carve_width_with(w, h, ch, &img, None, new_w, &Interrupt::cancel_only(&cancel)), Err(Cancelled)); + assert!(calls.load(Ordering::Relaxed) > w - new_w, "the rebuild checked for cancellation"); +} + +/// NaN samples and NaN protection steer seams the same whatever their sign and payload +/// (which arithmetic does not preserve consistently across builds): the same pixels are kept. +#[test] +fn nan_payloads_do_not_steer_seams() { + let (w, h, ch) = (24, 18, 3); + let (base, prot_base) = (noise(w * h * ch, 255, 21), noise(w * h, 3, 22)); + let carve_with_nans = |pixel: f32, prot: f32| { + let (mut img, mut p) = (base.clone(), prot_base.clone()); + img.iter_mut().step_by(37).for_each(|v| *v = pixel); + p.iter_mut().step_by(29).for_each(|v| *v = prot); + carve(w, h, ch, &img, Some(&p), 15, 11) + }; + let canonical = |v: Vec| v.into_iter().map(|f| if f.is_nan() { u32::MAX } else { f.to_bits() }).collect::>(); + let nans = [f32::NAN, -f32::NAN, f32::from_bits(0x7fc0_1234), f32::from_bits(0xffc0_0001)]; + let want = canonical(carve_with_nans(nans[0], nans[0])); + for &a in &nans { + for &b in &nans { + assert_eq!(canonical(carve_with_nans(a, b)), want, "pixel NaN {:#x}, protection NaN {:#x}", a.to_bits(), b.to_bits()); + } + } +} + +#[test] +fn cancelled_carve_stops() { + let (w, h) = (40, 20); + let img = vec![0.5f32; w * h * 3]; + let yes = || true; + assert_eq!(carve_with(w, h, 3, &img, None, 30, 15, &Interrupt::cancel_only(&yes)), Err(Cancelled)); + assert_eq!(carve_with(w, h, 3, &img, None, 30, 15, &Interrupt::NONE).unwrap(), carve(w, h, 3, &img, None, 30, 15)); +} + +/// A flat grey image with a salient vertical bar at x = 10..14 (red/blue columns). +fn bar(w: usize, h: usize) -> Vec { + let mut v = vec![0.5f32; w * h * 3]; + for y in 0..h { + for x in 10..14 { + let c = if x % 2 == 0 { [1.0, 0.0, 0.0] } else { [0.0, 0.0, 1.0] }; + v[(y * w + x) * 3..(y * w + x) * 3 + 3].copy_from_slice(&c); + } + } + v +} + +/// Columns that are pure red or pure blue top to bottom. +fn red_columns(w: usize, h: usize, img: &[f32]) -> usize { + let pure = |p: &[f32]| p[1] < 0.05 && ((p[0] > 0.95 && p[2] < 0.05) || (p[2] > 0.95 && p[0] < 0.05)); + (0..w).filter(|x| (0..h).all(|y| pure(&img[(y * w + x) * 3..(y * w + x) * 3 + 3]))).count() +} + +#[test] +fn seam_follows_low_energy() { + let (w, h) = (5, 4); + let mut e = vec![9.0f32; w * h]; + for y in 0..h { + e[y * w + 2] = 0.0; + } + assert_eq!(find_seam(w, h, &e), vec![2; 4]); +} + +#[test] +fn shrinking_keeps_the_salient_bar() { + let (w, h) = (40, 12); + let img = bar(w, h); + let out = carve(w, h, 3, &img, None, 24, h); + assert_eq!(out.len(), 24 * h * 3); + assert_eq!(red_columns(24, h, &out), 4, "the bar survives intact"); + // Plain resampling squashes it instead. + let plain = resize_bilinear(w, h, 3, &img, 24, h); + assert!(red_columns(24, h, &plain) < 4); +} + +#[test] +fn tall_proxy_shrink_preserves_full_resolution_salient_and_protected_pixels() { + let (w, h, ch, new_w) = (512, PROXY_SHRINK_MIN_HEIGHT, 3, 384); + let mut img = bar(w, h); + let mut protect = vec![0.0; w * h]; + for y in 0..h { + let i = (y * w + 256) * ch; + img[i..i + ch].copy_from_slice(&[0.03, 0.87, 0.42]); + protect[y * w + 256] = 1.0; + } + + let out = carve_width_with(w, h, ch, &img, Some(&protect), new_w, &Interrupt::NONE).unwrap(); + + assert_eq!(out.len(), new_w * h * ch); + assert_eq!(red_columns(new_w, h, &out), 4, "the full-resolution bar survives"); + for y in 0..h { + let row = &out[y * new_w * ch..(y + 1) * new_w * ch]; + assert!(row.chunks_exact(ch).any(|px| px == [0.03, 0.87, 0.42]), "protected mark survives row {y}"); + } +} + +#[test] +fn tall_proxy_shrink_observes_cancellation_before_modifying_source() { + let (w, h, ch) = (128, PROXY_SHRINK_MIN_HEIGHT, 3); + let img = vec![0.5; w * h * ch]; + let cancelled = || true; + assert_eq!(carve_width_with(w, h, ch, &img, None, 64, &Interrupt::cancel_only(&cancelled)), Err(Cancelled)); +} + +#[test] +fn enlarging_duplicates_flat_areas() { + let (w, h) = (30, 8); + let img = bar(w, h); + let out = carve(w, h, 3, &img, None, 50, h); + assert_eq!(out.len(), 50 * h * 3); + assert_eq!(red_columns(50, h, &out), 4); +} + +#[test] +fn height_and_protection() { + let (w, h) = (20, 30); + // Horizontal bar: carve height. + let mut img = vec![0.2f32; w * h]; + for x in 0..w { + img[12 * w + x] = 1.0; + } + let out = carve(w, h, 1, &img, None, w, 18); + assert_eq!(out.len(), w * 18); + assert_eq!((0..18).filter(|y| (0..w).all(|x| out[y * w + x] > 0.9)).count(), 1); + // Protecting a flat region keeps it: the seams go elsewhere. + let flat = vec![0.5f32; 16 * 4]; + let mut protect = vec![0.0f32; 16 * 4]; + for y in 0..4 { + protect[y * 16 + 3] = 1.0; + } + let mut marked = flat.clone(); + for y in 0..4 { + marked[y * 16 + 3] = 0.51; + } + let out = carve(16, 4, 1, &marked, Some(&protect), 8, 4); + assert!((0..4).all(|y| out[y * 8..y * 8 + 8].iter().any(|v| (*v - 0.51).abs() < 1e-6))); +} + +/// Noise quantised to `levels` values, so the energy map is full of exact ties. +fn noise(len: usize, levels: u32, seed: u32) -> Vec { + let mut s = seed | 1; + (0..len) + .map(|_| { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + (s % levels) as f32 / (levels - 1) as f32 + }) + .collect() +} + +fn fnv(v: &[f32]) -> u64 { + v.iter().flat_map(|f| f.to_bits().to_le_bytes()).fold(0xcbf2_9ce4_8422_2325, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)) +} + +/// The exact output bits of a spread of carves (shrink, enlarge past half the width, both +/// axes, protection, 1/3/4 channels, tie-heavy and smooth images), pinned so that speed work +/// can't change which seams are chosen or how pixels are blended. +#[test] +fn output_bits_are_pinned() { + let cases: [(usize, usize, usize, u32, bool, usize, usize); 8] = [ + (61, 47, 3, 2, false, 40, 47), + (61, 47, 3, 255, false, 61, 30), + (61, 47, 4, 4, true, 35, 29), + (33, 20, 1, 3, false, 80, 20), + (33, 20, 3, 1000, true, 50, 45), + (48, 36, 4, 7, false, 70, 18), + (5, 3, 1, 2, false, 1, 1), + (40, 40, 3, 2, true, 39, 41), + ]; + let got: Vec = cases + .iter() + .enumerate() + .map(|(i, &(w, h, ch, levels, prot, nw, nh))| { + let img = noise(w * h * ch, levels, 7 + i as u32); + let protect = prot.then(|| noise(w * h, 3, 99 + i as u32)); + let out = carve(w, h, ch, &img, protect.as_deref(), nw, nh); + assert_eq!(out.len(), nw * nh * ch); + fnv(&out) + }) + .collect(); + assert_eq!(got, PINNED); +} + +const PINNED: [u64; 8] = [ + 0x24ea_9353_02c2_7c58, + 0x5a6e_8554_a0cb_ebb1, + 0x8b18_d63f_396e_21c9, + 0x1db2_23ad_3e6a_a7c5, + 0x721d_6cc5_34e0_3fdf, + 0x961a_ea6d_e512_ec7d, + 0x4d25_767f_9dce_13f5, + 0x2157_9f86_27d6_b835, +]; + +/// [`output_bits_are_pinned`] for the reduced-height seam search of tall images (rows at +/// least [`PROXY_SHRINK_MIN_HEIGHT`], at least [`PROXY_SHRINK_MIN_SEAMS`] seams): widths and, +/// through the transposed pass, heights, with and without protection, on tie-heavy and +/// fine-grained noise. +#[test] +fn tall_proxy_output_bits_are_pinned() { + let cases: [(usize, usize, usize, u32, bool, usize, usize); 5] = [ + (96, PROXY_SHRINK_MIN_HEIGHT, 3, 2, false, 30, PROXY_SHRINK_MIN_HEIGHT), + (130, 2_100, 4, 255, true, 64, 2_100), + (80, 2_600, 1, 65_536, false, 16, 2_600), + (PROXY_SHRINK_MIN_HEIGHT, 90, 3, 5, false, PROXY_SHRINK_MIN_HEIGHT, 20), + (2_050, 100, 4, 1000, true, 2_050, 36), + ]; + let got: Vec = cases + .iter() + .enumerate() + .map(|(i, &(w, h, ch, levels, prot, nw, nh))| { + let img = noise(w * h * ch, levels, 31 + i as u32); + let protect = prot.then(|| noise(w * h, 3, 131 + i as u32)); + let out = carve(w, h, ch, &img, protect.as_deref(), nw, nh); + assert_eq!(out.len(), nw * nh * ch); + fnv(&out) + }) + .collect(); + assert_eq!(got, TALL_PINNED); +} + +const TALL_PINNED: [u64; 5] = [0x5657_83ac_cb26_56a5, 0x81a6_b5f7_e299_fdfb, 0xcdf2_9df9_9b83_def5, 0xa713_544a_4dcc_d8d8, 0x3557_de9f_ffb0_881e]; + +#[test] +fn one_pixel_lines_enlarge_by_repeating() { + // Width 1 has no seam to spare: its one column is repeated. Height 1 likewise (through + // the transposed pass), alone or with the other axis. + let col = [0.1f32, 0.2, 0.3, 0.4, 0.5]; + assert_eq!(carve(1, 5, 1, &col, None, 4, 5), col.iter().flat_map(|v| [*v; 4]).collect::>()); + assert_eq!(carve(5, 1, 1, &col, None, 5, 3), col.repeat(3)); + assert_eq!(carve(1, 1, 3, &[0.7, 0.8, 0.9], None, 3, 2), [0.7, 0.8, 0.9].repeat(6)); + for (w, h, nw, nh) in [(1, 5, 6, 10), (1, 17, 6, 34), (16, 1, 21, 2), (7, 1, 3, 8), (2, 1, 1, 8)] { + let img = vec![0.5f32; w * h * 4]; + assert_eq!(carve(w, h, 4, &img, Some(&vec![1.0; w * h]), nw, nh).len(), nw * nh * 4, "{w}x{h} -> {nw}x{nh}"); + } +} + +#[test] +fn skin_rule() { + let px = [0.86f32, 0.62, 0.5, 0.2, 0.4, 0.8]; + assert_eq!(skin_mask(2, 1, 3, &px), vec![1.0, 0.0]); +} From 812736396f4b830b481140831ea0c9cb91641af3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:05 +0000 Subject: [PATCH 020/259] refactor(algo): move panorama.rs parallel_tests to panorama/parallel_tests.rs --- crates/algo/src/panorama.rs | 405 +-------------------- crates/algo/src/panorama/parallel_tests.rs | 402 ++++++++++++++++++++ 2 files changed, 403 insertions(+), 404 deletions(-) create mode 100644 crates/algo/src/panorama/parallel_tests.rs diff --git a/crates/algo/src/panorama.rs b/crates/algo/src/panorama.rs index 87f8415b99..2be876d89c 100644 --- a/crates/algo/src/panorama.rs +++ b/crates/algo/src/panorama.rs @@ -1677,407 +1677,4 @@ mod tests { /// The row-parallel `reduce` / `expand` / `push_pull` / `multiband` against the serial code they /// replaced, kept below verbatim as the reference. Every output must stay bit for bit the same. #[cfg(test)] -mod parallel_tests { - use super::*; - - fn mix(mut z: u64) -> u64 { - z = z.wrapping_add(0x9E37_79B9_7F4A_7C15); - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - } - - /// Deterministic data from integer arithmetic only (no libm): mostly `0..1`, with negatives, - /// signed zeros and large values so a different order of operations cannot hide. - fn noise(len: usize, seed: u64) -> Vec { - (0..len as u64) - .map(|i| { - let z = mix(seed.wrapping_mul(0x1234_5678_9ABC).wrapping_add(i)); - let v = (z >> 40) as f32 / 16_777_216.0; - match z & 31 { - 0 => -v, - 1 => -0.0, - 2 => v * 1000.0, - 3 => 0.0, - _ => v, - } - }) - .collect() - } - - /// Weights with exact zeros, exact ones and partial values, in blobs and noise. - fn weights(w: usize, h: usize, seed: u64) -> Vec { - (0..w * h) - .map(|i| { - let (x, y) = (i % w, i / w); - let z = mix(seed + i as u64); - if (x / 5 + y / 3) % 3 == 0 { - 0.0 - } else if z.is_multiple_of(7) { - ((z >> 20) % 100) as f32 / 100.0 - } else { - 1.0 - } - }) - .collect() - } - - fn bits(v: &[f32]) -> Vec { - v.iter().map(|x| x.to_bits()).collect() - } - - fn fnv(parts: &[&[f32]]) -> u64 { - let mut h = 0xcbf2_9ce4_8422_2325u64; - for p in parts { - for x in *p { - h ^= x.to_bits() as u64; - h = h.wrapping_mul(0x0000_0100_0000_01b3); - } - } - h - } - - /// Sizes that cross the odd / even and tiny cases (1 wide, 1 high, 1×1, odd, power of two + 1). - const SIZES: [(usize, usize); 12] = [(1, 1), (1, 9), (9, 1), (2, 2), (3, 5), (4, 4), (17, 13), (64, 40), (65, 41), (97, 61), (130, 7), (7, 130)]; - - fn ref_reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usize, Vec) { - let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); - let k = [1.0f32, 4.0, 6.0, 4.0, 1.0]; - // Separable 5-tap binomial, then decimate. - let mut tmp = vec![0.0f32; nw * h * ch]; - for y in 0..h { - for x in 0..nw { - for c in 0..ch { - let mut s = 0.0; - for (t, kv) in k.iter().enumerate() { - let xx = (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize; - s += kv * src[(y * w + xx) * ch + c]; - } - tmp[(y * nw + x) * ch + c] = s / 16.0; - } - } - } - let mut out = vec![0.0f32; nw * nh * ch]; - for y in 0..nh { - for x in 0..nw { - for c in 0..ch { - let mut s = 0.0; - for (t, kv) in k.iter().enumerate() { - let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize; - s += kv * tmp[(yy * nw + x) * ch + c]; - } - out[(y * nw + x) * ch + c] = s / 16.0; - } - } - } - (nw, nh, out) - } - - fn ref_expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Vec { - // Bilinear upsampling at half-pixel-aligned positions. - let mut out = vec![0.0f32; w * h * ch]; - for y in 0..h { - let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32); - let (y0, ty) = (fy.floor() as usize, fy - fy.floor()); - let y1 = (y0 + 1).min(sh - 1); - for x in 0..w { - let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32); - let (x0, tx) = (fx.floor() as usize, fx - fx.floor()); - let x1 = (x0 + 1).min(sw - 1); - for c in 0..ch { - let p = |xx: usize, yy: usize| src[(yy * sw + xx) * ch + c]; - let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx; - let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx; - out[(y * w + x) * ch + c] = top + (bot - top) * ty; - } - } - } - out - } - - fn ref_push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) { - if w <= 1 && h <= 1 { - return; - } - let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); - let mut cpx = vec![0.0f32; nw * nh * ch]; - let mut cw = vec![0.0f32; nw * nh]; - for y in 0..h { - for x in 0..w { - let (i, j) = (y * w + x, (y / 2) * nw + x / 2); - let a = wt[i]; - cw[j] += a; - for c in 0..ch { - cpx[j * ch + c] += a * px[i * ch + c]; - } - } - } - for j in 0..nw * nh { - if cw[j] > 0.0 { - for c in 0..ch { - cpx[j * ch + c] /= cw[j]; - } - cw[j] = 1.0; - } - } - if cw.contains(&0.0) && cw.iter().any(|v| *v > 0.0) { - ref_push_pull(nw, nh, ch, &mut cpx, &cw); - } - for y in 0..h { - for x in 0..w { - let i = y * w + x; - if wt[i] < 1.0 { - let j = (y / 2) * nw + x / 2; - let a = wt[i]; - for c in 0..ch { - px[i * ch + c] = a * px[i * ch + c] + (1.0 - a) * cpx[j * ch + c]; - } - } - } - } - } - - fn ref_multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize) -> (Vec, Vec) { - let ch = imgs.first().map_or(1, |i| i.ch); - let levels = levels.max(1); - let align = 1i32 << (levels - 1); - // Level sizes of the panorama. - let mut sizes = vec![(w, h)]; - for _ in 1..levels { - let Some(&(pw, ph)) = sizes.last() else { break }; - sizes.push((pw.div_ceil(2), ph.div_ceil(2))); - } - let mut acc: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh * ch]).collect(); - let mut wsum: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh]).collect(); - let margin = align * 4; - // Each image on its ROI grown by a margin and aligned to the coarsest level's grid. - let bands = par_map(imgs.len(), |k| { - let im = &imgs[k]; - let gx0 = ((im.x0 - margin).max(0) / align) * align; - let gy0 = ((im.y0 - margin).max(0) / align) * align; - let gx1 = (im.x0 + im.w as i32 + margin).min(w as i32); - let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32); - let (gw, gh) = ((gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize); - let mut px = vec![0.0f32; gw * gh * ch]; - let mut cov = vec![0.0f32; gw * gh]; - let mut wt = vec![0.0f32; gw * gh]; - for y in 0..im.h { - for x in 0..im.w { - let (gx, gy) = (im.x0 + x as i32 - gx0, im.y0 + y as i32 - gy0); - if gx < 0 || gy < 0 || gx as usize >= gw || gy as usize >= gh { - continue; - } - let (i, g) = (y * im.w + x, gy as usize * gw + gx as usize); - cov[g] = im.alpha[i]; - wt[g] = weights[k][i] * im.alpha[i].min(1.0); - px[g * ch..(g + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]); - } - } - let bin: Vec = cov.iter().map(|a| if *a > 0.5 { 1.0 } else { 0.0 }).collect(); - ref_push_pull(gw, gh, ch, &mut px, &bin); - // Laplacian of the colours, Gaussian of the weights. - let mut lap: Vec<(usize, usize, Vec)> = Vec::new(); - let mut gau: Vec> = Vec::new(); - let (mut cw, mut chh, mut cur, mut cwt) = (gw, gh, px, wt); - for l in 0..levels { - if l + 1 == levels { - lap.push((cw, chh, cur.clone())); - gau.push(cwt.clone()); - break; - } - let (nw, nh, down) = ref_reduce(cw, chh, ch, &cur); - let up = ref_expand(nw, nh, ch, &down, cw, chh); - lap.push((cw, chh, cur.iter().zip(&up).map(|(a, b)| a - b).collect())); - gau.push(cwt.clone()); - let (_, _, wdown) = ref_reduce(cw, chh, 1, &cwt); - cw = nw; - chh = nh; - cur = down; - cwt = wdown; - } - (gx0, gy0, lap, gau) - }); - for (gx0, gy0, lap, gau) in &bands { - for (l, ((lw, lh, band), g)) in lap.iter().zip(gau).enumerate() { - let (ox, oy) = ((gx0 >> l) as usize, (gy0 >> l) as usize); - let (pw, ph) = sizes[l]; - for y in 0..*lh { - let py = oy + y; - if py >= ph { - break; - } - for x in 0..*lw { - let px = ox + x; - if px >= pw { - break; - } - let (i, p) = (y * lw + x, py * pw + px); - let k = g[i]; - if k <= 0.0 { - continue; - } - wsum[l][p] += k; - for c in 0..ch { - acc[l][p * ch + c] += k * band[i * ch + c]; - } - } - } - } - } - for l in 0..levels { - let (pw, ph) = sizes[l]; - for p in 0..pw * ph { - let k = wsum[l][p]; - for c in 0..ch { - acc[l][p * ch + c] = if k > 1e-8 { acc[l][p * ch + c] / k } else { 0.0 }; - } - } - } - // Collapse. - // `levels ≥ 1`, so there is always a coarsest level. - let Some(mut cur) = acc.pop() else { return (vec![0.0; w * h * ch], vec![0.0; w * h]) }; - for l in (0..levels - 1).rev() { - let (pw, ph) = sizes[l]; - let (sw, sh) = sizes[l + 1]; - let up = ref_expand(sw, sh, ch, &cur, pw, ph); - cur = acc[l].iter().zip(&up).map(|(a, b)| a + b).collect(); - } - // Coverage: union of the images. - let mut cov = vec![0.0f32; w * h]; - for im in imgs { - for y in 0..im.h { - for x in 0..im.w { - let (px, py) = (im.x0 + x as i32, im.y0 + y as i32); - if px < 0 || py < 0 || px as usize >= w || py as usize >= h { - continue; - } - let p = py as usize * w + px as usize; - cov[p] = cov[p].max(im.alpha[y * im.w + x]); - } - } - } - (cur, cov) - } - - #[test] - fn reduce_and_expand_match_the_serial_code() { - for (n, &(w, h)) in SIZES.iter().enumerate() { - for ch in [1usize, 3, 4] { - let src = noise(w * h * ch, n as u64 * 7 + ch as u64); - let (nw, nh, got) = reduce(w, h, ch, &src); - let (rw, rh, want) = ref_reduce(w, h, ch, &src); - assert_eq!((nw, nh), (rw, rh)); - assert_eq!(bits(&got), bits(&want), "reduce {w}x{h}x{ch}"); - // Expand back to the original size and to sizes that are not twice the source's. - for (ew, eh) in [(w, h), (2 * nw, 2 * nh), (2 * nw - 1, 2 * nh + 1), (w + 3, h + 5)] { - let got = expand(nw, nh, ch, &want, ew, eh); - let want_up = ref_expand(nw, nh, ch, &want, ew, eh); - assert_eq!(bits(&got), bits(&want_up), "expand {nw}x{nh}x{ch} to {ew}x{eh}"); - } - } - } - } - - #[test] - fn push_pull_matches_the_serial_code() { - for (n, &(w, h)) in SIZES.iter().enumerate() { - for ch in [1usize, 3] { - for variant in 0..3u64 { - let wt = match variant { - 0 => weights(w, h, n as u64), - 1 => vec![1.0; w * h], - // A single covered pixel: every level of the recursion has to fill from it. - _ => (0..w * h).map(|i| if i == (w * h) / 3 { 1.0 } else { 0.0 }).collect(), - }; - let px = noise(w * h * ch, 100 + n as u64); - let (mut got, mut want) = (px.clone(), px); - push_pull(w, h, ch, &mut got, &wt); - ref_push_pull(w, h, ch, &mut want, &wt); - assert_eq!(bits(&got), bits(&want), "push_pull {w}x{h}x{ch} variant {variant}"); - } - } - } - } - - /// ROIs of assorted sizes and offsets (some sticking out of the canvas), with holes in the alpha. - fn rois(w: usize, h: usize, ch: usize, seed: u64) -> (Vec, Vec>) { - let specs = - [(0i32, 0i32, w * 2 / 3, h), (w as i32 / 3, -(h as i32) / 5, w * 2 / 3 + 1, h * 3 / 4 + 1), (-(w as i32) / 4, h as i32 / 2, w / 2 + 1, h / 2 + 3)]; - let imgs: Vec = specs - .iter() - .enumerate() - .map(|(k, &(x0, y0, iw, ih))| { - let (iw, ih) = (iw.max(1), ih.max(1)); - let mut alpha = vec![1.0f32; iw * ih]; - for (i, a) in alpha.iter_mut().enumerate() { - let z = mix(seed + k as u64 * 1000 + i as u64); - if (i % iw) / 4 % 5 == 2 && (i / iw) % 6 < 3 { - *a = 0.0; - } else if z.is_multiple_of(11) { - *a = 0.3; - } - } - RoiImage { x0, y0, w: iw, h: ih, ch, px: noise(iw * ih * ch, seed + k as u64), alpha } - }) - .collect(); - let wts = imgs.iter().enumerate().map(|(k, r)| weights(r.w, r.h, seed + 50 + k as u64)).collect(); - (imgs, wts) - } - - #[test] - fn multiband_matches_the_serial_code() { - for (n, &(w, h)) in [(1usize, 1usize), (5, 3), (40, 30), (97, 61), (130, 70), (64, 64), (201, 129)].iter().enumerate() { - for ch in [1usize, 3] { - let (imgs, wts) = rois(w, h, ch, n as u64 * 31 + ch as u64); - for levels in [1usize, 2, 3, 5, 7] { - let got = multiband(w, h, &imgs, &wts, levels); - let want = ref_multiband(w, h, &imgs, &wts, levels); - assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels}"); - assert_eq!(bits(&got.1), bits(&want.1), "coverage {w}x{h}x{ch} levels {levels}"); - } - } - } - // No images at all, and zero levels. - assert_eq!(multiband(9, 7, &[], &[], 3).0.len(), ref_multiband(9, 7, &[], &[], 3).0.len()); - } - - /// Batching the bands (#7758) changes when they are built, not the result. Budgets from none - /// (one image per batch) up to everything in steps of a fifth pass through every split of the - /// three images. - #[test] - fn multiband_batches_match_the_serial_code() { - let budgets: Vec = - std::iter::successors(Some(1024.0f64), |b| Some(b * 1.2)).take_while(|b| *b < 4e6).map(|b| b as usize).chain([0, usize::MAX]).collect(); - for (n, &(w, h)) in [(40usize, 30usize), (97, 61), (201, 129)].iter().enumerate() { - for ch in [1usize, 3] { - let (imgs, wts) = rois(w, h, ch, n as u64 * 17 + ch as u64); - for levels in [1usize, 3, 5] { - let want = ref_multiband(w, h, &imgs, &wts, levels); - for &budget in &budgets { - let got = multiband_batched(w, h, &imgs, &wts, levels, budget); - assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels} budget {budget}"); - assert_eq!(bits(&got.1), bits(&want.1), "coverage {w}x{h}x{ch} levels {levels} budget {budget}"); - } - } - } - } - } - - /// Hashes recorded from the code before it was made parallel (plain f32 arithmetic only, so - /// they hold on every platform). - #[test] - fn multiband_hashes_recorded_from_the_serial_code() { - let (imgs, wts) = rois(97, 61, 3, 5); - let (px, cov) = multiband(97, 61, &imgs, &wts, 5); - assert_eq!(fnv(&[&px, &cov]), 0xf89a5726082ebb6c, "97x61 rgb, 5 levels"); - let (imgs, wts) = rois(130, 70, 1, 9); - let (px, cov) = multiband(130, 70, &imgs, &wts, 7); - assert_eq!(fnv(&[&px, &cov]), 0xb7d7ddc59d201730, "130x70 grey, 7 levels"); - let wt = weights(65, 41, 3); - let mut px = noise(65 * 41 * 3, 4); - push_pull(65, 41, 3, &mut px, &wt); - assert_eq!(fnv(&[&px]), 0x50ea36a84ca9a68f, "push_pull 65x41 rgb"); - let (nw, nh, r) = reduce(65, 41, 3, &px); - assert_eq!(fnv(&[&r, &expand(nw, nh, 3, &r, 65, 41)]), 0x51823acfb4206dd8, "reduce + expand 65x41 rgb"); - } -} +mod parallel_tests; diff --git a/crates/algo/src/panorama/parallel_tests.rs b/crates/algo/src/panorama/parallel_tests.rs new file mode 100644 index 0000000000..77c25b0f98 --- /dev/null +++ b/crates/algo/src/panorama/parallel_tests.rs @@ -0,0 +1,402 @@ +use super::*; + +fn mix(mut z: u64) -> u64 { + z = z.wrapping_add(0x9E37_79B9_7F4A_7C15); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +/// Deterministic data from integer arithmetic only (no libm): mostly `0..1`, with negatives, +/// signed zeros and large values so a different order of operations cannot hide. +fn noise(len: usize, seed: u64) -> Vec { + (0..len as u64) + .map(|i| { + let z = mix(seed.wrapping_mul(0x1234_5678_9ABC).wrapping_add(i)); + let v = (z >> 40) as f32 / 16_777_216.0; + match z & 31 { + 0 => -v, + 1 => -0.0, + 2 => v * 1000.0, + 3 => 0.0, + _ => v, + } + }) + .collect() +} + +/// Weights with exact zeros, exact ones and partial values, in blobs and noise. +fn weights(w: usize, h: usize, seed: u64) -> Vec { + (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let z = mix(seed + i as u64); + if (x / 5 + y / 3) % 3 == 0 { + 0.0 + } else if z.is_multiple_of(7) { + ((z >> 20) % 100) as f32 / 100.0 + } else { + 1.0 + } + }) + .collect() +} + +fn bits(v: &[f32]) -> Vec { + v.iter().map(|x| x.to_bits()).collect() +} + +fn fnv(parts: &[&[f32]]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + for p in parts { + for x in *p { + h ^= x.to_bits() as u64; + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + } + h +} + +/// Sizes that cross the odd / even and tiny cases (1 wide, 1 high, 1×1, odd, power of two + 1). +const SIZES: [(usize, usize); 12] = [(1, 1), (1, 9), (9, 1), (2, 2), (3, 5), (4, 4), (17, 13), (64, 40), (65, 41), (97, 61), (130, 7), (7, 130)]; + +fn ref_reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usize, Vec) { + let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); + let k = [1.0f32, 4.0, 6.0, 4.0, 1.0]; + // Separable 5-tap binomial, then decimate. + let mut tmp = vec![0.0f32; nw * h * ch]; + for y in 0..h { + for x in 0..nw { + for c in 0..ch { + let mut s = 0.0; + for (t, kv) in k.iter().enumerate() { + let xx = (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize; + s += kv * src[(y * w + xx) * ch + c]; + } + tmp[(y * nw + x) * ch + c] = s / 16.0; + } + } + } + let mut out = vec![0.0f32; nw * nh * ch]; + for y in 0..nh { + for x in 0..nw { + for c in 0..ch { + let mut s = 0.0; + for (t, kv) in k.iter().enumerate() { + let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize; + s += kv * tmp[(yy * nw + x) * ch + c]; + } + out[(y * nw + x) * ch + c] = s / 16.0; + } + } + } + (nw, nh, out) +} + +fn ref_expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Vec { + // Bilinear upsampling at half-pixel-aligned positions. + let mut out = vec![0.0f32; w * h * ch]; + for y in 0..h { + let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32); + let (y0, ty) = (fy.floor() as usize, fy - fy.floor()); + let y1 = (y0 + 1).min(sh - 1); + for x in 0..w { + let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32); + let (x0, tx) = (fx.floor() as usize, fx - fx.floor()); + let x1 = (x0 + 1).min(sw - 1); + for c in 0..ch { + let p = |xx: usize, yy: usize| src[(yy * sw + xx) * ch + c]; + let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx; + let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx; + out[(y * w + x) * ch + c] = top + (bot - top) * ty; + } + } + } + out +} + +fn ref_push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) { + if w <= 1 && h <= 1 { + return; + } + let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); + let mut cpx = vec![0.0f32; nw * nh * ch]; + let mut cw = vec![0.0f32; nw * nh]; + for y in 0..h { + for x in 0..w { + let (i, j) = (y * w + x, (y / 2) * nw + x / 2); + let a = wt[i]; + cw[j] += a; + for c in 0..ch { + cpx[j * ch + c] += a * px[i * ch + c]; + } + } + } + for j in 0..nw * nh { + if cw[j] > 0.0 { + for c in 0..ch { + cpx[j * ch + c] /= cw[j]; + } + cw[j] = 1.0; + } + } + if cw.contains(&0.0) && cw.iter().any(|v| *v > 0.0) { + ref_push_pull(nw, nh, ch, &mut cpx, &cw); + } + for y in 0..h { + for x in 0..w { + let i = y * w + x; + if wt[i] < 1.0 { + let j = (y / 2) * nw + x / 2; + let a = wt[i]; + for c in 0..ch { + px[i * ch + c] = a * px[i * ch + c] + (1.0 - a) * cpx[j * ch + c]; + } + } + } + } +} + +fn ref_multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize) -> (Vec, Vec) { + let ch = imgs.first().map_or(1, |i| i.ch); + let levels = levels.max(1); + let align = 1i32 << (levels - 1); + // Level sizes of the panorama. + let mut sizes = vec![(w, h)]; + for _ in 1..levels { + let Some(&(pw, ph)) = sizes.last() else { break }; + sizes.push((pw.div_ceil(2), ph.div_ceil(2))); + } + let mut acc: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh * ch]).collect(); + let mut wsum: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh]).collect(); + let margin = align * 4; + // Each image on its ROI grown by a margin and aligned to the coarsest level's grid. + let bands = par_map(imgs.len(), |k| { + let im = &imgs[k]; + let gx0 = ((im.x0 - margin).max(0) / align) * align; + let gy0 = ((im.y0 - margin).max(0) / align) * align; + let gx1 = (im.x0 + im.w as i32 + margin).min(w as i32); + let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32); + let (gw, gh) = ((gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize); + let mut px = vec![0.0f32; gw * gh * ch]; + let mut cov = vec![0.0f32; gw * gh]; + let mut wt = vec![0.0f32; gw * gh]; + for y in 0..im.h { + for x in 0..im.w { + let (gx, gy) = (im.x0 + x as i32 - gx0, im.y0 + y as i32 - gy0); + if gx < 0 || gy < 0 || gx as usize >= gw || gy as usize >= gh { + continue; + } + let (i, g) = (y * im.w + x, gy as usize * gw + gx as usize); + cov[g] = im.alpha[i]; + wt[g] = weights[k][i] * im.alpha[i].min(1.0); + px[g * ch..(g + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]); + } + } + let bin: Vec = cov.iter().map(|a| if *a > 0.5 { 1.0 } else { 0.0 }).collect(); + ref_push_pull(gw, gh, ch, &mut px, &bin); + // Laplacian of the colours, Gaussian of the weights. + let mut lap: Vec<(usize, usize, Vec)> = Vec::new(); + let mut gau: Vec> = Vec::new(); + let (mut cw, mut chh, mut cur, mut cwt) = (gw, gh, px, wt); + for l in 0..levels { + if l + 1 == levels { + lap.push((cw, chh, cur.clone())); + gau.push(cwt.clone()); + break; + } + let (nw, nh, down) = ref_reduce(cw, chh, ch, &cur); + let up = ref_expand(nw, nh, ch, &down, cw, chh); + lap.push((cw, chh, cur.iter().zip(&up).map(|(a, b)| a - b).collect())); + gau.push(cwt.clone()); + let (_, _, wdown) = ref_reduce(cw, chh, 1, &cwt); + cw = nw; + chh = nh; + cur = down; + cwt = wdown; + } + (gx0, gy0, lap, gau) + }); + for (gx0, gy0, lap, gau) in &bands { + for (l, ((lw, lh, band), g)) in lap.iter().zip(gau).enumerate() { + let (ox, oy) = ((gx0 >> l) as usize, (gy0 >> l) as usize); + let (pw, ph) = sizes[l]; + for y in 0..*lh { + let py = oy + y; + if py >= ph { + break; + } + for x in 0..*lw { + let px = ox + x; + if px >= pw { + break; + } + let (i, p) = (y * lw + x, py * pw + px); + let k = g[i]; + if k <= 0.0 { + continue; + } + wsum[l][p] += k; + for c in 0..ch { + acc[l][p * ch + c] += k * band[i * ch + c]; + } + } + } + } + } + for l in 0..levels { + let (pw, ph) = sizes[l]; + for p in 0..pw * ph { + let k = wsum[l][p]; + for c in 0..ch { + acc[l][p * ch + c] = if k > 1e-8 { acc[l][p * ch + c] / k } else { 0.0 }; + } + } + } + // Collapse. + // `levels ≥ 1`, so there is always a coarsest level. + let Some(mut cur) = acc.pop() else { return (vec![0.0; w * h * ch], vec![0.0; w * h]) }; + for l in (0..levels - 1).rev() { + let (pw, ph) = sizes[l]; + let (sw, sh) = sizes[l + 1]; + let up = ref_expand(sw, sh, ch, &cur, pw, ph); + cur = acc[l].iter().zip(&up).map(|(a, b)| a + b).collect(); + } + // Coverage: union of the images. + let mut cov = vec![0.0f32; w * h]; + for im in imgs { + for y in 0..im.h { + for x in 0..im.w { + let (px, py) = (im.x0 + x as i32, im.y0 + y as i32); + if px < 0 || py < 0 || px as usize >= w || py as usize >= h { + continue; + } + let p = py as usize * w + px as usize; + cov[p] = cov[p].max(im.alpha[y * im.w + x]); + } + } + } + (cur, cov) +} + +#[test] +fn reduce_and_expand_match_the_serial_code() { + for (n, &(w, h)) in SIZES.iter().enumerate() { + for ch in [1usize, 3, 4] { + let src = noise(w * h * ch, n as u64 * 7 + ch as u64); + let (nw, nh, got) = reduce(w, h, ch, &src); + let (rw, rh, want) = ref_reduce(w, h, ch, &src); + assert_eq!((nw, nh), (rw, rh)); + assert_eq!(bits(&got), bits(&want), "reduce {w}x{h}x{ch}"); + // Expand back to the original size and to sizes that are not twice the source's. + for (ew, eh) in [(w, h), (2 * nw, 2 * nh), (2 * nw - 1, 2 * nh + 1), (w + 3, h + 5)] { + let got = expand(nw, nh, ch, &want, ew, eh); + let want_up = ref_expand(nw, nh, ch, &want, ew, eh); + assert_eq!(bits(&got), bits(&want_up), "expand {nw}x{nh}x{ch} to {ew}x{eh}"); + } + } + } +} + +#[test] +fn push_pull_matches_the_serial_code() { + for (n, &(w, h)) in SIZES.iter().enumerate() { + for ch in [1usize, 3] { + for variant in 0..3u64 { + let wt = match variant { + 0 => weights(w, h, n as u64), + 1 => vec![1.0; w * h], + // A single covered pixel: every level of the recursion has to fill from it. + _ => (0..w * h).map(|i| if i == (w * h) / 3 { 1.0 } else { 0.0 }).collect(), + }; + let px = noise(w * h * ch, 100 + n as u64); + let (mut got, mut want) = (px.clone(), px); + push_pull(w, h, ch, &mut got, &wt); + ref_push_pull(w, h, ch, &mut want, &wt); + assert_eq!(bits(&got), bits(&want), "push_pull {w}x{h}x{ch} variant {variant}"); + } + } + } +} + +/// ROIs of assorted sizes and offsets (some sticking out of the canvas), with holes in the alpha. +fn rois(w: usize, h: usize, ch: usize, seed: u64) -> (Vec, Vec>) { + let specs = + [(0i32, 0i32, w * 2 / 3, h), (w as i32 / 3, -(h as i32) / 5, w * 2 / 3 + 1, h * 3 / 4 + 1), (-(w as i32) / 4, h as i32 / 2, w / 2 + 1, h / 2 + 3)]; + let imgs: Vec = specs + .iter() + .enumerate() + .map(|(k, &(x0, y0, iw, ih))| { + let (iw, ih) = (iw.max(1), ih.max(1)); + let mut alpha = vec![1.0f32; iw * ih]; + for (i, a) in alpha.iter_mut().enumerate() { + let z = mix(seed + k as u64 * 1000 + i as u64); + if (i % iw) / 4 % 5 == 2 && (i / iw) % 6 < 3 { + *a = 0.0; + } else if z.is_multiple_of(11) { + *a = 0.3; + } + } + RoiImage { x0, y0, w: iw, h: ih, ch, px: noise(iw * ih * ch, seed + k as u64), alpha } + }) + .collect(); + let wts = imgs.iter().enumerate().map(|(k, r)| weights(r.w, r.h, seed + 50 + k as u64)).collect(); + (imgs, wts) +} + +#[test] +fn multiband_matches_the_serial_code() { + for (n, &(w, h)) in [(1usize, 1usize), (5, 3), (40, 30), (97, 61), (130, 70), (64, 64), (201, 129)].iter().enumerate() { + for ch in [1usize, 3] { + let (imgs, wts) = rois(w, h, ch, n as u64 * 31 + ch as u64); + for levels in [1usize, 2, 3, 5, 7] { + let got = multiband(w, h, &imgs, &wts, levels); + let want = ref_multiband(w, h, &imgs, &wts, levels); + assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels}"); + assert_eq!(bits(&got.1), bits(&want.1), "coverage {w}x{h}x{ch} levels {levels}"); + } + } + } + // No images at all, and zero levels. + assert_eq!(multiband(9, 7, &[], &[], 3).0.len(), ref_multiband(9, 7, &[], &[], 3).0.len()); +} + +/// Batching the bands (#7758) changes when they are built, not the result. Budgets from none +/// (one image per batch) up to everything in steps of a fifth pass through every split of the +/// three images. +#[test] +fn multiband_batches_match_the_serial_code() { + let budgets: Vec = + std::iter::successors(Some(1024.0f64), |b| Some(b * 1.2)).take_while(|b| *b < 4e6).map(|b| b as usize).chain([0, usize::MAX]).collect(); + for (n, &(w, h)) in [(40usize, 30usize), (97, 61), (201, 129)].iter().enumerate() { + for ch in [1usize, 3] { + let (imgs, wts) = rois(w, h, ch, n as u64 * 17 + ch as u64); + for levels in [1usize, 3, 5] { + let want = ref_multiband(w, h, &imgs, &wts, levels); + for &budget in &budgets { + let got = multiband_batched(w, h, &imgs, &wts, levels, budget); + assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels} budget {budget}"); + assert_eq!(bits(&got.1), bits(&want.1), "coverage {w}x{h}x{ch} levels {levels} budget {budget}"); + } + } + } + } +} + +/// Hashes recorded from the code before it was made parallel (plain f32 arithmetic only, so +/// they hold on every platform). +#[test] +fn multiband_hashes_recorded_from_the_serial_code() { + let (imgs, wts) = rois(97, 61, 3, 5); + let (px, cov) = multiband(97, 61, &imgs, &wts, 5); + assert_eq!(fnv(&[&px, &cov]), 0xf89a5726082ebb6c, "97x61 rgb, 5 levels"); + let (imgs, wts) = rois(130, 70, 1, 9); + let (px, cov) = multiband(130, 70, &imgs, &wts, 7); + assert_eq!(fnv(&[&px, &cov]), 0xb7d7ddc59d201730, "130x70 grey, 7 levels"); + let wt = weights(65, 41, 3); + let mut px = noise(65 * 41 * 3, 4); + push_pull(65, 41, 3, &mut px, &wt); + assert_eq!(fnv(&[&px]), 0x50ea36a84ca9a68f, "push_pull 65x41 rgb"); + let (nw, nh, r) = reduce(65, 41, 3, &px); + assert_eq!(fnv(&[&r, &expand(nw, nh, 3, &r, 65, 41)]), 0x51823acfb4206dd8, "reduce + expand 65x41 rgb"); +} From d6e7fcef1348ac9dab5a037320cc8a41713cce88 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:05 +0000 Subject: [PATCH 021/259] refactor(algo): move art_history.rs tests to art_history/tests.rs --- crates/algo/src/art_history.rs | 397 +-------------------------- crates/algo/src/art_history/tests.rs | 393 ++++++++++++++++++++++++++ 2 files changed, 394 insertions(+), 396 deletions(-) create mode 100644 crates/algo/src/art_history/tests.rs diff --git a/crates/algo/src/art_history.rs b/crates/algo/src/art_history.rs index 7fcb286c22..d5895a466f 100644 --- a/crates/algo/src/art_history.rs +++ b/crates/algo/src/art_history.rs @@ -655,399 +655,4 @@ pub fn stamp(p: &mut StampParams<'_>) -> Result { } #[cfg(test)] -mod tests { - use super::*; - - fn fill(w: usize, h: usize, ch: usize, f: impl Fn(i32, i32, usize) -> f32) -> Vec { - let mut v = vec![0.0; w * h * ch]; - for y in 0..h { - for x in 0..w { - for c in 0..ch { - v[(y * w + x) * ch + c] = f(x as i32, y as i32, c); - } - } - } - v - } - - fn horizontal(len: f32) -> Vec<[f32; 2]> { - vec![[10.0, 32.0], [10.0 + len, 32.0]] - } - - #[test] - fn tight_short_emits_more_dabs_than_tight_long() { - let pts = horizontal(100.0); - let short = place_dabs(&pts, 10.0, 50.0, Style::TightShort, RNG_SEED).unwrap(); - let long = place_dabs(&pts, 10.0, 50.0, Style::TightLong, RNG_SEED).unwrap(); - assert!(short.len() > long.len(), "short {} long {}", short.len(), long.len()); - let s = spacing_px(10.0, 50.0, Style::TightShort).unwrap(); - let l = spacing_px(10.0, 50.0, Style::TightLong).unwrap(); - assert!(s < l, "{s} {l}"); - } - - #[test] - fn tight_curl_angles_increase_and_loose_curl_scatters() { - let pts = horizontal(80.0); - let tight = place_dabs(&pts, 12.0, 50.0, Style::TightCurl, RNG_SEED).unwrap(); - let loose = place_dabs(&pts, 12.0, 50.0, Style::LooseCurl, RNG_SEED).unwrap(); - assert!(tight.len() >= 3 && loose.len() >= 3); - let dt: Vec = tight.windows(2).map(|w| w[1].theta - w[0].theta).collect(); - assert!(dt.iter().all(|d| *d > 0.05), "tight curl steps {dt:?}"); - let dl: Vec = loose.windows(2).map(|w| w[1].theta - w[0].theta).collect(); - let mean = |v: &[f32]| v.iter().sum::() / v.len() as f32; - assert!(mean(&dl) > mean(&dt), "loose curl {dl:?} vs tight {dt:?}"); - let scatter_t: f32 = tight.iter().map(|d| (d.y - 32.0).abs()).sum(); - let scatter_l: f32 = loose.iter().map(|d| (d.y - 32.0).abs()).sum(); - assert!(scatter_l > scatter_t, "loose scatter {scatter_l} tight {scatter_t}"); - } - - #[test] - fn seeded_scatter_is_replayable() { - let pts = horizontal(60.0); - let a = place_dabs(&pts, 16.0, 40.0, Style::LooseMedium, RNG_SEED ^ 3).unwrap(); - let b = place_dabs(&pts, 16.0, 40.0, Style::LooseMedium, RNG_SEED ^ 3).unwrap(); - assert_eq!(a, b); - let c = place_dabs(&pts, 16.0, 40.0, Style::LooseMedium, RNG_SEED ^ 4).unwrap(); - assert_ne!(a, c); - } - - fn fixture(ch: usize) -> (usize, usize, Vec, Vec, Dab) { - let (w, h) = (128usize, 96usize); - let src = fill(w, h, ch, |x, y, c| if c + 1 == ch && ch > 1 { 1.0 } else { ((x * 13 + y * 7 + c as i32 * 3).rem_euclid(251) as f32) / 255.0 }); - let dest0 = fill(w, h, ch, |_, _, c| if c + 1 == ch && ch > 1 { 1.0 } else { 0.1 }); - // Centre 1 px inside a 64-tile so the rotated read crosses the seam. - let dab = Dab { x: 63.0, y: 40.0, theta: 0.4, radius: 18.0, pressure: 1.0 }; - (w, h, src, dest0, dab) - } - - #[allow(clippy::too_many_arguments)] - fn stamp_run(w: usize, h: usize, ch: usize, src: &[f32], dest: &mut [f32], dab: &Dab, tile: i32) -> u32 { - stamp_dabs(w, h, ch, src, dest, std::slice::from_ref(dab), tile) - } - - #[allow(clippy::too_many_arguments)] - fn stamp_dabs(w: usize, h: usize, ch: usize, src: &[f32], dest: &mut [f32], dabs: &[Dab], tile: i32) -> u32 { - let mut p = StampParams { - dest, - dest_w: w, - dest_h: h, - dest_origin: (0, 0), - src, - src_w: w, - src_h: h, - src_origin: (0, 0), - ch, - dabs, - hardness: 1.0, - opacity: 1.0, - flow: 1.0, - tolerance: 0.0, - tile, - selection: None, - lock_transparent: false, - alpha: (ch > 1).then_some(ch - 1), - }; - stamp(&mut p).unwrap() - } - - fn max_abs(a: &[f32], b: &[f32]) -> f32 { - a.iter().zip(b).fold(0.0f32, |m, (x, y)| m.max((x - y).abs())) - } - - fn max_u8(a: &[f32], b: &[f32]) -> i32 { - a.iter() - .zip(b) - .map(|(x, y)| { - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; - (q(*x) - q(*y)).abs() - }) - .max() - .unwrap_or(0) - } - - #[test] - fn tiled_stamp_matches_untiled_at_a_tile_seam() { - let (w, h, src, dest0, dab) = fixture(4); - let mut tiled = dest0.clone(); - let mut flat = dest0.clone(); - let n_t = stamp_run(w, h, 4, &src, &mut tiled, &dab, 64); - let n_f = stamp_run(w, h, 4, &src, &mut flat, &dab, 0); - assert!(n_t > 0 && n_f > 0, "wrote {n_t} tiled / {n_f} flat"); - assert_eq!(max_u8(&tiled, &flat), 0, "8-bit seam"); - assert!(max_abs(&tiled, &flat) <= 1.0 / 32_767.0, "16-bit seam {}", max_abs(&tiled, &flat)); - assert!(max_abs(&tiled, &flat) <= 1.0e-5, "32f seam {}", max_abs(&tiled, &flat)); - - let (w, h, src, dest0, dab) = fixture(1); - let mut tiled = dest0.clone(); - let mut flat = dest0; - stamp_run(w, h, 1, &src, &mut tiled, &dab, 64); - stamp_run(w, h, 1, &src, &mut flat, &dab, 0); - assert_eq!(max_u8(&tiled, &flat), 0, "gray 8-bit seam"); - } - - #[test] - fn leftward_and_curl_strokes_match_untiled_across_a_tile_edge() { - let (w, h, ch) = (128usize, 96usize, 4); - let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { ((x * 13 + y * 7 + c as i32 * 3).rem_euclid(251) as f32) / 255.0 }); - let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.1 }); - for style in [Style::TightMedium, Style::TightCurl, Style::LooseCurl] { - let dabs = place_dabs(&[[110.0, 40.0], [20.0, 40.0]], 40.0, 50.0, style, RNG_SEED).unwrap(); - let mut tiled = dest0.clone(); - let mut flat = dest0.clone(); - stamp_dabs(w, h, ch, &src, &mut tiled, &dabs, 64); - stamp_dabs(w, h, ch, &src, &mut flat, &dabs, 0); - assert_eq!(max_abs(&tiled, &flat), 0.0, "{} seam at x = 64", style.as_str()); - } - } - - /// A dab at angle 0 copies the history pixel under each covered pixel, not a blend of it - /// and its lower-right neighbours. - #[test] - fn unrotated_dab_restores_the_source_pixel() { - let (w, h, ch) = (48usize, 48usize, 4); - let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { ((x * 37 + y * 11 + c as i32 * 5).rem_euclid(97) as f32) / 96.0 }); - let mut dest = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.5 }); - let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; - stamp_run(w, h, ch, &src, &mut dest, &dab, 0); - for (x, y) in [(24usize, 24usize), (20, 22), (27, 26)] { - let i = (y * w + x) * ch; - assert_eq!(&dest[i..i + ch], &src[i..i + ch], "pixel {x},{y}"); - } - } - - #[test] - fn halo_covers_rotated_read_reach() { - let size = 40.0; - for style in - [Style::TightShort, Style::TightMedium, Style::TightLong, Style::LooseMedium, Style::LooseLong, Style::Dab, Style::TightCurl, Style::LooseCurl] - { - let halo = halo_radius(size, style).unwrap(); - let side = sample_side(size, style).unwrap(); - let reach = (side + 1) / 2; - assert!(halo >= reach, "{:?}: halo {halo} < reach {reach} (side {side})", style.as_str()); - } - } - - #[test] - fn tolerance_skips_an_unchanged_layer() { - let (w, h, ch) = (48usize, 48usize, 4); - let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { (x + y) as f32 / 100.0 }); - let mut dest = src.clone(); - let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; - let mut p = StampParams { - dest: &mut dest, - dest_w: w, - dest_h: h, - dest_origin: (0, 0), - src: &src, - src_w: w, - src_h: h, - src_origin: (0, 0), - ch, - dabs: std::slice::from_ref(&dab), - hardness: 1.0, - opacity: 1.0, - flow: 1.0, - tolerance: 1.0, - tile: 0, - selection: None, - lock_transparent: false, - alpha: Some(3), - }; - let n = stamp(&mut p).unwrap(); - assert_eq!(n, 0); - assert_eq!(dest, src); - } - - #[test] - fn tolerance_zero_writes_where_history_differs() { - let (w, h, ch) = (48usize, 48usize, 4); - let src = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.9 }); - let mut dest = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.1 }); - let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; - let mut p = StampParams { - dest: &mut dest, - dest_w: w, - dest_h: h, - dest_origin: (0, 0), - src: &src, - src_w: w, - src_h: h, - src_origin: (0, 0), - ch, - dabs: std::slice::from_ref(&dab), - hardness: 1.0, - opacity: 1.0, - flow: 1.0, - tolerance: 0.0, - tile: 0, - selection: None, - lock_transparent: false, - alpha: Some(3), - }; - let n = stamp(&mut p).unwrap(); - assert!(n > 0); - let i = (24 * w + 24) * ch; - assert!((dest[i] - 0.9).abs() < 1.0e-5, "{}", dest[i]); - } - - #[test] - fn tolerance_ignores_unchanged_alpha() { - // Colour moved by 0.3 and alpha did not: the 0.25 threshold must not see a 0.225 average. - let (w, h, ch) = (48usize, 48usize, 4); - let src = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.6 }); - let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.3 }); - let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; - for (tolerance, paints) in [(0.25, true), (0.35, false)] { - let mut dest = dest0.clone(); - let mut p = StampParams { - dest: &mut dest, - dest_w: w, - dest_h: h, - dest_origin: (0, 0), - src: &src, - src_w: w, - src_h: h, - src_origin: (0, 0), - ch, - dabs: std::slice::from_ref(&dab), - hardness: 1.0, - opacity: 1.0, - flow: 1.0, - tolerance, - tile: 0, - selection: None, - lock_transparent: false, - alpha: Some(3), - }; - let n = stamp(&mut p).unwrap(); - assert_eq!(n > 0, paints, "tolerance {tolerance}"); - } - } - - /// The Eraser keeps the colour and lowers only the alpha: an erased patch differs from the - /// history state and is painted back with a tolerance above 0. - #[test] - fn tolerance_sees_an_erased_patch() { - let (w, h, ch) = (48usize, 48usize, 4); - let src = fill(w, h, ch, |_, _, c| if c == 0 || c == 3 { 1.0 } else { 0.0 }); - let mut dest = fill(w, h, ch, |_, _, c| match c { - 0 => 1.0, - 3 => 0.6, - _ => 0.0, - }); - let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; - let mut p = StampParams { - dest: &mut dest, - dest_w: w, - dest_h: h, - dest_origin: (0, 0), - src: &src, - src_w: w, - src_h: h, - src_origin: (0, 0), - ch, - dabs: std::slice::from_ref(&dab), - hardness: 1.0, - opacity: 1.0, - flow: 1.0, - tolerance: 0.25, - tile: 0, - selection: None, - lock_transparent: false, - alpha: Some(3), - }; - assert!(stamp(&mut p).unwrap() > 0, "alpha 1 -> 0.6 is over tolerance 0.25"); - let i = (24 * w + 24) * ch; - assert!((dest[i + 3] - 1.0).abs() < 1.0e-5, "alpha restored, got {}", dest[i + 3]); - } - #[test] - fn empty_or_mismatched_buffers_error() { - let mut dest = vec![0.0f32; 16]; - let src = vec![0.0f32; 16]; - let dab = Dab { x: 1.0, y: 1.0, theta: 0.0, radius: 1.0, pressure: 1.0 }; - let mut p = StampParams { - dest: &mut dest, - dest_w: 0, - dest_h: 4, - dest_origin: (0, 0), - src: &src, - src_w: 4, - src_h: 4, - src_origin: (0, 0), - ch: 1, - dabs: std::slice::from_ref(&dab), - hardness: 1.0, - opacity: 1.0, - flow: 1.0, - tolerance: 0.0, - tile: 0, - selection: None, - lock_transparent: false, - alpha: None, - }; - assert_eq!(stamp(&mut p), Err(StampError::Empty)); - let mut dest = vec![0.0f32; 16]; - let src = vec![0.0f32; 8]; - let mut p = StampParams { - dest: &mut dest, - dest_w: 4, - dest_h: 4, - dest_origin: (0, 0), - src: &src, - src_w: 2, - src_h: 2, - src_origin: (0, 0), - ch: 4, - dabs: std::slice::from_ref(&dab), - hardness: 1.0, - opacity: 1.0, - flow: 1.0, - tolerance: 0.0, - tile: 0, - selection: None, - lock_transparent: false, - alpha: None, - }; - assert!(stamp(&mut p).is_err()); - assert!(place_dabs(&[], 10.0, 50.0, Style::TightMedium, 0).is_err()); - assert!(Style::parse("nope").is_none()); - assert_eq!(Style::parse("tightMedium"), Some(Style::TightMedium)); - } - - #[test] - fn two_stamps_with_the_same_seed_match() { - let pts = horizontal(50.0); - let dabs = place_dabs(&pts, 12.0, 50.0, Style::LooseCurl, RNG_SEED).unwrap(); - let (w, h, ch) = (80usize, 64usize, 4); - let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { (x + 3 * y) as f32 / 200.0 }); - let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.2 }); - let run = |dest: &mut [f32]| { - let mut p = StampParams { - dest, - dest_w: w, - dest_h: h, - dest_origin: (0, 0), - src: &src, - src_w: w, - src_h: h, - src_origin: (0, 0), - ch, - dabs: &dabs, - hardness: 0.8, - opacity: 1.0, - flow: 1.0, - tolerance: 0.0, - tile: 64, - selection: None, - lock_transparent: false, - alpha: Some(3), - }; - stamp(&mut p).unwrap() - }; - let mut a = dest0.clone(); - let mut b = dest0; - assert_eq!(run(&mut a), run(&mut b)); - assert_eq!(a, b); - } -} +mod tests; diff --git a/crates/algo/src/art_history/tests.rs b/crates/algo/src/art_history/tests.rs new file mode 100644 index 0000000000..373cfc304b --- /dev/null +++ b/crates/algo/src/art_history/tests.rs @@ -0,0 +1,393 @@ +use super::*; + +fn fill(w: usize, h: usize, ch: usize, f: impl Fn(i32, i32, usize) -> f32) -> Vec { + let mut v = vec![0.0; w * h * ch]; + for y in 0..h { + for x in 0..w { + for c in 0..ch { + v[(y * w + x) * ch + c] = f(x as i32, y as i32, c); + } + } + } + v +} + +fn horizontal(len: f32) -> Vec<[f32; 2]> { + vec![[10.0, 32.0], [10.0 + len, 32.0]] +} + +#[test] +fn tight_short_emits_more_dabs_than_tight_long() { + let pts = horizontal(100.0); + let short = place_dabs(&pts, 10.0, 50.0, Style::TightShort, RNG_SEED).unwrap(); + let long = place_dabs(&pts, 10.0, 50.0, Style::TightLong, RNG_SEED).unwrap(); + assert!(short.len() > long.len(), "short {} long {}", short.len(), long.len()); + let s = spacing_px(10.0, 50.0, Style::TightShort).unwrap(); + let l = spacing_px(10.0, 50.0, Style::TightLong).unwrap(); + assert!(s < l, "{s} {l}"); +} + +#[test] +fn tight_curl_angles_increase_and_loose_curl_scatters() { + let pts = horizontal(80.0); + let tight = place_dabs(&pts, 12.0, 50.0, Style::TightCurl, RNG_SEED).unwrap(); + let loose = place_dabs(&pts, 12.0, 50.0, Style::LooseCurl, RNG_SEED).unwrap(); + assert!(tight.len() >= 3 && loose.len() >= 3); + let dt: Vec = tight.windows(2).map(|w| w[1].theta - w[0].theta).collect(); + assert!(dt.iter().all(|d| *d > 0.05), "tight curl steps {dt:?}"); + let dl: Vec = loose.windows(2).map(|w| w[1].theta - w[0].theta).collect(); + let mean = |v: &[f32]| v.iter().sum::() / v.len() as f32; + assert!(mean(&dl) > mean(&dt), "loose curl {dl:?} vs tight {dt:?}"); + let scatter_t: f32 = tight.iter().map(|d| (d.y - 32.0).abs()).sum(); + let scatter_l: f32 = loose.iter().map(|d| (d.y - 32.0).abs()).sum(); + assert!(scatter_l > scatter_t, "loose scatter {scatter_l} tight {scatter_t}"); +} + +#[test] +fn seeded_scatter_is_replayable() { + let pts = horizontal(60.0); + let a = place_dabs(&pts, 16.0, 40.0, Style::LooseMedium, RNG_SEED ^ 3).unwrap(); + let b = place_dabs(&pts, 16.0, 40.0, Style::LooseMedium, RNG_SEED ^ 3).unwrap(); + assert_eq!(a, b); + let c = place_dabs(&pts, 16.0, 40.0, Style::LooseMedium, RNG_SEED ^ 4).unwrap(); + assert_ne!(a, c); +} + +fn fixture(ch: usize) -> (usize, usize, Vec, Vec, Dab) { + let (w, h) = (128usize, 96usize); + let src = fill(w, h, ch, |x, y, c| if c + 1 == ch && ch > 1 { 1.0 } else { ((x * 13 + y * 7 + c as i32 * 3).rem_euclid(251) as f32) / 255.0 }); + let dest0 = fill(w, h, ch, |_, _, c| if c + 1 == ch && ch > 1 { 1.0 } else { 0.1 }); + // Centre 1 px inside a 64-tile so the rotated read crosses the seam. + let dab = Dab { x: 63.0, y: 40.0, theta: 0.4, radius: 18.0, pressure: 1.0 }; + (w, h, src, dest0, dab) +} + +#[allow(clippy::too_many_arguments)] +fn stamp_run(w: usize, h: usize, ch: usize, src: &[f32], dest: &mut [f32], dab: &Dab, tile: i32) -> u32 { + stamp_dabs(w, h, ch, src, dest, std::slice::from_ref(dab), tile) +} + +#[allow(clippy::too_many_arguments)] +fn stamp_dabs(w: usize, h: usize, ch: usize, src: &[f32], dest: &mut [f32], dabs: &[Dab], tile: i32) -> u32 { + let mut p = StampParams { + dest, + dest_w: w, + dest_h: h, + dest_origin: (0, 0), + src, + src_w: w, + src_h: h, + src_origin: (0, 0), + ch, + dabs, + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance: 0.0, + tile, + selection: None, + lock_transparent: false, + alpha: (ch > 1).then_some(ch - 1), + }; + stamp(&mut p).unwrap() +} + +fn max_abs(a: &[f32], b: &[f32]) -> f32 { + a.iter().zip(b).fold(0.0f32, |m, (x, y)| m.max((x - y).abs())) +} + +fn max_u8(a: &[f32], b: &[f32]) -> i32 { + a.iter() + .zip(b) + .map(|(x, y)| { + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; + (q(*x) - q(*y)).abs() + }) + .max() + .unwrap_or(0) +} + +#[test] +fn tiled_stamp_matches_untiled_at_a_tile_seam() { + let (w, h, src, dest0, dab) = fixture(4); + let mut tiled = dest0.clone(); + let mut flat = dest0.clone(); + let n_t = stamp_run(w, h, 4, &src, &mut tiled, &dab, 64); + let n_f = stamp_run(w, h, 4, &src, &mut flat, &dab, 0); + assert!(n_t > 0 && n_f > 0, "wrote {n_t} tiled / {n_f} flat"); + assert_eq!(max_u8(&tiled, &flat), 0, "8-bit seam"); + assert!(max_abs(&tiled, &flat) <= 1.0 / 32_767.0, "16-bit seam {}", max_abs(&tiled, &flat)); + assert!(max_abs(&tiled, &flat) <= 1.0e-5, "32f seam {}", max_abs(&tiled, &flat)); + + let (w, h, src, dest0, dab) = fixture(1); + let mut tiled = dest0.clone(); + let mut flat = dest0; + stamp_run(w, h, 1, &src, &mut tiled, &dab, 64); + stamp_run(w, h, 1, &src, &mut flat, &dab, 0); + assert_eq!(max_u8(&tiled, &flat), 0, "gray 8-bit seam"); +} + +#[test] +fn leftward_and_curl_strokes_match_untiled_across_a_tile_edge() { + let (w, h, ch) = (128usize, 96usize, 4); + let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { ((x * 13 + y * 7 + c as i32 * 3).rem_euclid(251) as f32) / 255.0 }); + let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.1 }); + for style in [Style::TightMedium, Style::TightCurl, Style::LooseCurl] { + let dabs = place_dabs(&[[110.0, 40.0], [20.0, 40.0]], 40.0, 50.0, style, RNG_SEED).unwrap(); + let mut tiled = dest0.clone(); + let mut flat = dest0.clone(); + stamp_dabs(w, h, ch, &src, &mut tiled, &dabs, 64); + stamp_dabs(w, h, ch, &src, &mut flat, &dabs, 0); + assert_eq!(max_abs(&tiled, &flat), 0.0, "{} seam at x = 64", style.as_str()); + } +} + +/// A dab at angle 0 copies the history pixel under each covered pixel, not a blend of it +/// and its lower-right neighbours. +#[test] +fn unrotated_dab_restores_the_source_pixel() { + let (w, h, ch) = (48usize, 48usize, 4); + let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { ((x * 37 + y * 11 + c as i32 * 5).rem_euclid(97) as f32) / 96.0 }); + let mut dest = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.5 }); + let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; + stamp_run(w, h, ch, &src, &mut dest, &dab, 0); + for (x, y) in [(24usize, 24usize), (20, 22), (27, 26)] { + let i = (y * w + x) * ch; + assert_eq!(&dest[i..i + ch], &src[i..i + ch], "pixel {x},{y}"); + } +} + +#[test] +fn halo_covers_rotated_read_reach() { + let size = 40.0; + for style in [Style::TightShort, Style::TightMedium, Style::TightLong, Style::LooseMedium, Style::LooseLong, Style::Dab, Style::TightCurl, Style::LooseCurl] + { + let halo = halo_radius(size, style).unwrap(); + let side = sample_side(size, style).unwrap(); + let reach = (side + 1) / 2; + assert!(halo >= reach, "{:?}: halo {halo} < reach {reach} (side {side})", style.as_str()); + } +} + +#[test] +fn tolerance_skips_an_unchanged_layer() { + let (w, h, ch) = (48usize, 48usize, 4); + let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { (x + y) as f32 / 100.0 }); + let mut dest = src.clone(); + let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; + let mut p = StampParams { + dest: &mut dest, + dest_w: w, + dest_h: h, + dest_origin: (0, 0), + src: &src, + src_w: w, + src_h: h, + src_origin: (0, 0), + ch, + dabs: std::slice::from_ref(&dab), + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance: 1.0, + tile: 0, + selection: None, + lock_transparent: false, + alpha: Some(3), + }; + let n = stamp(&mut p).unwrap(); + assert_eq!(n, 0); + assert_eq!(dest, src); +} + +#[test] +fn tolerance_zero_writes_where_history_differs() { + let (w, h, ch) = (48usize, 48usize, 4); + let src = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.9 }); + let mut dest = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.1 }); + let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; + let mut p = StampParams { + dest: &mut dest, + dest_w: w, + dest_h: h, + dest_origin: (0, 0), + src: &src, + src_w: w, + src_h: h, + src_origin: (0, 0), + ch, + dabs: std::slice::from_ref(&dab), + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance: 0.0, + tile: 0, + selection: None, + lock_transparent: false, + alpha: Some(3), + }; + let n = stamp(&mut p).unwrap(); + assert!(n > 0); + let i = (24 * w + 24) * ch; + assert!((dest[i] - 0.9).abs() < 1.0e-5, "{}", dest[i]); +} + +#[test] +fn tolerance_ignores_unchanged_alpha() { + // Colour moved by 0.3 and alpha did not: the 0.25 threshold must not see a 0.225 average. + let (w, h, ch) = (48usize, 48usize, 4); + let src = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.6 }); + let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.3 }); + let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; + for (tolerance, paints) in [(0.25, true), (0.35, false)] { + let mut dest = dest0.clone(); + let mut p = StampParams { + dest: &mut dest, + dest_w: w, + dest_h: h, + dest_origin: (0, 0), + src: &src, + src_w: w, + src_h: h, + src_origin: (0, 0), + ch, + dabs: std::slice::from_ref(&dab), + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance, + tile: 0, + selection: None, + lock_transparent: false, + alpha: Some(3), + }; + let n = stamp(&mut p).unwrap(); + assert_eq!(n > 0, paints, "tolerance {tolerance}"); + } +} + +/// The Eraser keeps the colour and lowers only the alpha: an erased patch differs from the +/// history state and is painted back with a tolerance above 0. +#[test] +fn tolerance_sees_an_erased_patch() { + let (w, h, ch) = (48usize, 48usize, 4); + let src = fill(w, h, ch, |_, _, c| if c == 0 || c == 3 { 1.0 } else { 0.0 }); + let mut dest = fill(w, h, ch, |_, _, c| match c { + 0 => 1.0, + 3 => 0.6, + _ => 0.0, + }); + let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 }; + let mut p = StampParams { + dest: &mut dest, + dest_w: w, + dest_h: h, + dest_origin: (0, 0), + src: &src, + src_w: w, + src_h: h, + src_origin: (0, 0), + ch, + dabs: std::slice::from_ref(&dab), + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance: 0.25, + tile: 0, + selection: None, + lock_transparent: false, + alpha: Some(3), + }; + assert!(stamp(&mut p).unwrap() > 0, "alpha 1 -> 0.6 is over tolerance 0.25"); + let i = (24 * w + 24) * ch; + assert!((dest[i + 3] - 1.0).abs() < 1.0e-5, "alpha restored, got {}", dest[i + 3]); +} +#[test] +fn empty_or_mismatched_buffers_error() { + let mut dest = vec![0.0f32; 16]; + let src = vec![0.0f32; 16]; + let dab = Dab { x: 1.0, y: 1.0, theta: 0.0, radius: 1.0, pressure: 1.0 }; + let mut p = StampParams { + dest: &mut dest, + dest_w: 0, + dest_h: 4, + dest_origin: (0, 0), + src: &src, + src_w: 4, + src_h: 4, + src_origin: (0, 0), + ch: 1, + dabs: std::slice::from_ref(&dab), + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance: 0.0, + tile: 0, + selection: None, + lock_transparent: false, + alpha: None, + }; + assert_eq!(stamp(&mut p), Err(StampError::Empty)); + let mut dest = vec![0.0f32; 16]; + let src = vec![0.0f32; 8]; + let mut p = StampParams { + dest: &mut dest, + dest_w: 4, + dest_h: 4, + dest_origin: (0, 0), + src: &src, + src_w: 2, + src_h: 2, + src_origin: (0, 0), + ch: 4, + dabs: std::slice::from_ref(&dab), + hardness: 1.0, + opacity: 1.0, + flow: 1.0, + tolerance: 0.0, + tile: 0, + selection: None, + lock_transparent: false, + alpha: None, + }; + assert!(stamp(&mut p).is_err()); + assert!(place_dabs(&[], 10.0, 50.0, Style::TightMedium, 0).is_err()); + assert!(Style::parse("nope").is_none()); + assert_eq!(Style::parse("tightMedium"), Some(Style::TightMedium)); +} + +#[test] +fn two_stamps_with_the_same_seed_match() { + let pts = horizontal(50.0); + let dabs = place_dabs(&pts, 12.0, 50.0, Style::LooseCurl, RNG_SEED).unwrap(); + let (w, h, ch) = (80usize, 64usize, 4); + let src = fill(w, h, ch, |x, y, c| if c == 3 { 1.0 } else { (x + 3 * y) as f32 / 200.0 }); + let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.2 }); + let run = |dest: &mut [f32]| { + let mut p = StampParams { + dest, + dest_w: w, + dest_h: h, + dest_origin: (0, 0), + src: &src, + src_w: w, + src_h: h, + src_origin: (0, 0), + ch, + dabs: &dabs, + hardness: 0.8, + opacity: 1.0, + flow: 1.0, + tolerance: 0.0, + tile: 64, + selection: None, + lock_transparent: false, + alpha: Some(3), + }; + stamp(&mut p).unwrap() + }; + let mut a = dest0.clone(); + let mut b = dest0; + assert_eq!(run(&mut a), run(&mut b)); + assert_eq!(a, b); +} From 3edbb00f0dee73c604e2d30a34633da145fac92a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:06 +0000 Subject: [PATCH 022/259] refactor(algo): move resample.rs tests to resample/tests.rs --- crates/algo/src/resample.rs | 405 +----------------------------- crates/algo/src/resample/tests.rs | 402 +++++++++++++++++++++++++++++ 2 files changed, 403 insertions(+), 404 deletions(-) create mode 100644 crates/algo/src/resample/tests.rs diff --git a/crates/algo/src/resample.rs b/crates/algo/src/resample.rs index 4ad84a10c0..4dcf0b6944 100644 --- a/crates/algo/src/resample.rs +++ b/crates/algo/src/resample.rs @@ -514,407 +514,4 @@ pub fn crop_surface(s: &Surface, keep: Rect) -> Surface { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_color::{ColorMode, PixelFormat, SampleType}; - - fn ramp(sample: SampleType) -> Surface { - let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true)); - let r = Rect::new(0, 0, 64, 32); - let v: Vec = (0..32).flat_map(|_| (0..64).flat_map(|x| [x as f32 / 63.0, 0.5, 1.0 - x as f32 / 63.0, 1.0])).collect(); - s.write_region(r, &v); - s - } - - #[test] - fn fixed_channel_rows_match_dynamic_resampling() { - fn check() { - for scale in [0.12, 0.5, 1.0, 2.3] { - for filter in [Kernel::Nearest, Kernel::Bilinear, keys(Resample::Bicubic, scale), keys(Resample::BicubicSharper, scale), Kernel::Lanczos] { - for clamp in [None, Some((-3, 31))] { - let ts = taps(-5, 41, scale, filter, clamp, (-3, 31)); - let row: Vec = (0..35 * N).map(|i| ((i * 73) % 251) as f32 / 250.0).collect(); - let def: Vec = (0..N).map(|i| i as f32 / 7.0).collect(); - let mut expected = vec![0.0; ts.len() * N]; - let mut actual = expected.clone(); - horizontal_dynamic(&row, &mut expected, &ts, -3, &def, N); - horizontal_fixed::(&row, &mut actual, &ts, -3, &def); - assert_eq!(actual, expected, "N={N} scale={scale} filter={filter:?} clamp={clamp:?}"); - } - } - } - } - check::<1>(); - check::<2>(); - check::<3>(); - check::<4>(); - check::<5>(); - } - - /// Photoshop 25.4's Image Size of a 16-bit greyscale pattern, in levels of 32768. Covers the - /// filters and their 2-D rules: Sharper reducing the width while the height grows is designed - /// for the height (not widened) and runs the width first; Bicubic Automatic splits a mixed - /// resize into Sharper and Smoother; Bicubic widens for the height's 0.6 while the width - /// grows; Smoother below ¼ averages down first; Bilinear below ½ averages whole pixels. On black - /// and white the overshoot is clipped between the passes, so their order shows. - #[test] - fn matches_photoshop_image_size() { - // (black and white pattern, filter, size, new size, Photoshop's levels) - type Probe = (bool, Resample, (i32, i32), (i32, i32), &'static [u16]); - let cases: [Probe; 9] = [ - ( - false, - Resample::BicubicSharper, - (12, 10), - (7, 16), - &[ - 3777, 13165, 22219, 16176, 10460, 19488, 29643, 11249, 12634, 21696, 13330, 10319, 18965, 29120, 21280, 11204, 20279, 16184, 8200, 17548, - 27703, 21824, 10182, 19259, 26967, 5238, 16528, 26683, 17366, 8895, 17922, 32768, 2402, 15190, 25345, 17493, 7834, 16903, 31316, 1748, - 14172, 24326, 24718, 6368, 15746, 30390, 0, 13107, 23169, 31215, 4790, 14456, 27639, 5080, 11597, 21880, 29649, 3864, 13507, 24136, 20600, - 10264, 20931, 28009, 0, 12446, 21385, 28735, 8754, 19642, 26154, 4049, 10895, 20832, 23523, 7620, 18485, 23204, 20126, 8787, 19818, 21447, - 6173, 17467, 20390, 31862, 6616, 18480, 24094, 6500, 16129, 19749, 27472, 5810, 17460, 28281, 7655, 15108, 18394, 25515, 4427, 16043, - 28749, 7026, 13691, 17871, 24992, 3904, 15520, 27200, 6075, 13168, - ], - ), - ( - false, - Resample::BicubicAutomatic, - (12, 10), - (7, 16), - &[ - 4201, 12337, 27677, 15894, 4816, 20021, 29631, 10348, 9882, 27304, 14492, 3766, 19574, 29046, 18743, 5944, 25299, 16116, 4147, 17829, - 27787, 19399, 4206, 21790, 23748, 7966, 15117, 26569, 15941, 2695, 19445, 28341, 10104, 13050, 25465, 16251, 2613, 18023, 26770, 8432, - 11951, 24281, 22800, 7141, 15351, 24790, 5953, 11004, 23130, 28322, 10921, 12440, 24940, 9659, 9368, 22012, 27611, 10006, 10488, 26419, - 18657, 7071, 20807, 25492, 6937, 9239, 26574, 22363, 5435, 19688, 24808, 9136, 8184, 25295, 19708, 3939, 18677, 25053, 18234, 7120, 24061, - 17941, 2545, 17568, 24869, 23748, 6081, 21401, 21862, 6018, 15056, 23602, 22177, 4859, 17816, 28450, 11911, 11653, 22253, 20263, 3595, - 15790, 29734, 12969, 9683, 21668, 19678, 3010, 15424, 28429, 11728, 9300, - ], - ), - ( - false, - Resample::Bicubic, - (12, 10), - (20, 6), - &[ - 11517, 10000, 8617, 9364, 12272, 16362, 21396, 25508, 25506, 19474, 10887, 5289, 5842, 10286, 14986, 18566, 21910, 25511, 28611, 29922, - 24788, 17949, 8497, 4593, 7309, 12594, 17150, 20945, 24892, 26196, 22979, 16123, 9691, 7483, 10061, 14653, 18841, 22420, 25514, 26824, - 25702, 23396, 17586, 11378, 8127, 8882, 12310, 17039, 22345, 25871, 24700, 18125, 9951, 5493, 6802, 11215, 15576, 19259, 22384, 23694, - 26692, 26985, 22732, 14270, 6889, 4950, 8348, 13583, 17529, 21570, 25966, 27275, 22817, 14643, 8068, 6911, 10694, 15930, 19443, 20705, - 21499, 23413, 25601, 24336, 18665, 11686, 7800, 8947, 12974, 18067, 22707, 25285, 23077, 16645, 9789, 6586, 8147, 12329, 15935, 17465, - 17962, 20462, 24615, 25377, 20036, 11458, 5421, 5415, 9528, 14134, 17782, 22482, 26926, 27479, 21881, 13308, 7533, 7734, 11549, 13992, - ], - ), - ( - false, - Resample::BicubicSmoother, - (40, 3), - (9, 3), - &[ - 11315, 18740, 17475, 15974, 16503, 16042, 18215, 14712, 16238, 18482, 14351, 14664, 18012, 20260, 13338, 15511, 18468, 18275, 16790, 19168, - 14745, 14998, 20341, 18150, 13819, 16493, 16432, - ], - ), - ( - false, - Resample::Bilinear, - (12, 10), - (5, 4), - &[11316, 14541, 17920, 10855, 24679, 19763, 9933, 23757, 6247, 20070, 25601, 5325, 19149, 17306, 15463, 20992, 16384, 14541, 23143, 10854], - ), - ( - false, - Resample::Nearest, - (12, 10), - (7, 16), - &[ - 1638, 12698, 23757, 3482, 9011, 20070, 31130, 1638, 12698, 23757, 3482, 9011, 20070, 31130, 31130, 10854, 21914, 1638, 7168, 18227, 29286, - 29286, 9011, 20070, 31130, 5325, 16384, 27443, 29286, 9011, 20070, 31130, 5325, 16384, 27443, 27443, 7168, 18227, 29286, 3482, 14541, - 25600, 25600, 5325, 16384, 27443, 1638, 12698, 23757, 25600, 5325, 16384, 27443, 1638, 12698, 23757, 23757, 3482, 14541, 25600, 31130, - 10854, 21914, 23757, 3482, 14541, 25600, 31130, 10854, 21914, 21914, 1638, 12698, 23757, 29286, 9011, 20070, 20070, 31130, 10854, 21914, - 27443, 7168, 18227, 20070, 31130, 10854, 21914, 27443, 7168, 18227, 18227, 29286, 9011, 20070, 25600, 5325, 16384, 16384, 27443, 7168, - 18227, 23757, 3482, 14541, 16384, 27443, 7168, 18227, 23757, 3482, 14541, - ], - ), - ( - true, - Resample::Bicubic, - (12, 10), - (20, 6), - &[ - 9960, 6313, 993, 0, 4525, 14807, 26472, 32768, 32768, 23510, 10514, 0, 0, 0, 10110, 22576, 31764, 32768, 32768, 32768, 26136, 18594, 6164, - 0, 0, 2565, 14499, 26983, 32768, 32768, 26358, 14709, 3969, 0, 0, 6602, 17734, 27952, 32768, 32768, 31590, 27808, 18307, 7429, 0, 0, 3712, - 14435, 26473, 32768, 31131, 20665, 7535, 0, 0, 2177, 13238, 25049, 32768, 32768, 32768, 32768, 26136, 14174, 2548, 0, 0, 6190, 18705, - 30273, 32768, 32768, 25517, 13238, 2177, 0, 0, 7250, 19418, 26624, 32768, 32768, 32768, 28203, 18522, 7200, 0, 0, 3285, 14794, 26862, - 32768, 29913, 19013, 6667, 0, 0, 4443, 14506, 20751, 17344, 23066, 31075, 32361, 23949, 10738, 0, 0, 0, 10110, 22657, 32768, 32768, 32768, - 22658, 10192, 1004, 0, 0, 0, - ], - ), - ( - true, - Resample::BicubicSharper, - (12, 10), - (7, 16), - &[ - 801, 3050, 32489, 16260, 0, 29819, 32767, 9161, 1781, 29578, 14350, 0, 32768, 32767, 21132, 0, 25409, 17862, 0, 26925, 32767, 22769, 0, - 24839, 27566, 0, 9397, 32768, 19813, 0, 27795, 32768, 0, 0, 32768, 20744, 0, 25797, 32768, 0, 0, 32768, 27555, 0, 11184, 32768, 0, 0, - 32768, 32768, 0, 0, 32768, 5110, 0, 30386, 32768, 0, 0, 32768, 20385, 0, 23267, 32768, 0, 0, 32768, 29130, 0, 19191, 32768, 2670, 0, 31290, - 25387, 0, 21263, 32767, 20198, 0, 21586, 24510, 0, 23714, 32768, 32768, 0, 14165, 27804, 1007, 14254, 32768, 30149, 0, 16077, 32112, 2886, - 1884, 21043, 29607, 0, 16384, 32768, 3566, 0, 12683, 29616, 0, 16384, 32768, 3196, 0, - ], - ), - ( - true, - Resample::BicubicSharper, - (12, 10), - (20, 6), - &[ - 9273, 5043, 0, 0, 2698, 14484, 28464, 32768, 32768, 24841, 10877, 0, 0, 0, 9684, 22346, 31492, 32768, 32768, 32768, 25960, 18430, 4978, 0, - 0, 977, 15047, 28475, 32768, 32768, 27939, 14157, 1813, 0, 0, 5296, 17828, 28439, 32768, 32768, 32768, 27849, 17576, 6209, 0, 0, 2169, - 15076, 28935, 32768, 32768, 22167, 7399, 0, 0, 211, 12977, 24638, 32768, 32768, 32768, 32768, 25960, 14244, 824, 0, 0, 5093, 18802, 31993, - 32768, 32768, 26467, 12977, 211, 0, 0, 6300, 19418, 26712, 32768, 32768, 32768, 27907, 17874, 5820, 0, 0, 1853, 16055, 29518, 32768, 32768, - 20889, 5880, 0, 0, 2879, 13798, 20185, 19010, 25565, 32768, 32302, 25431, 11478, 0, 0, 0, 9684, 23083, 32768, 32768, 32768, 23084, 10422, - 1276, 0, 0, 0, - ], - ), - ]; - for (binary, filter, (w, h), (wo, ho), want) in cases { - let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::U16, false)); - let canvas = Rect::new(0, 0, w, h); - let level = |x: i32, y: i32| match ((x * 37 + y * 101) % 17) as f32 { - k if binary => { - if k > 8.0 { - 32767.0 / 32768.0 - } else { - 0.0 - } - } - k => ((k / 16.0 * 0.9 + 0.05) * 32768.0).round() / 32768.0, - }; - let px: Vec = (0..h).flat_map(|y| (0..w).map(move |x| level(x, y))).collect(); - s.write_region(canvas, &px); - let o = resize_surface_in_canvas(&s, wo as f64 / w as f64, ho as f64 / h as f64, filter, canvas); - let got = o.read_region(Rect::new(0, 0, wo, ho)); - assert_eq!(got.len(), want.len(), "{filter:?}"); - let worst = got.iter().zip(want).map(|(g, &p)| (g * 32768.0 - p as f32).abs()).fold(0.0f32, f32::max); - assert!(worst <= 8.0, "{filter:?} {w}x{h} to {wo}x{ho}: {worst} levels of 32768 from Photoshop"); - } - } - - /// Photoshop's Bicubic doubles with the Keys cubic at a = −0.75 (Catmull-Rom is −0.5): an - /// impulse spreads as −9, −27, 67, 225 /256 and back, as Photoshop 25.4 gives it. - #[test] - fn bicubic_is_photoshops_keys_cubic() { - let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false)); - let mut row = [0.25; 30]; - row[10] = 0.75; - s.write_region(Rect::new(0, 0, 30, 1), &row); - let o = resize_surface(&s, 2.0, 1.0, Resample::Bicubic); - let got: Vec = o.read_region(Rect::new(17, 0, 25, 1)).iter().map(|v| (v - 0.25) * 512.0).collect(); - for (g, want) in got.iter().zip([-9.0, -27.0, 67.0, 225.0, 225.0, 67.0, -27.0, -9.0]) { - assert!((g - want).abs() < 1e-3, "{got:?}"); - } - } - - #[test] - fn identity_scale_is_lossless() { - for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] { - let s = ramp(SampleType::U16); - let o = resize_surface(&s, 1.0, 1.0, f); - let r = Rect::new(0, 0, 64, 32); - let (a, b) = (s.read_region(r), o.read_region(r)); - let d = a.iter().zip(&b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max); - assert!(d < 1e-4, "{f:?} {d}"); - } - } - - #[test] - fn half_and_double_sizes() { - for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos, Resample::PreserveDetails] { - let s = ramp(SampleType::F32); - let half = resize_surface(&s, 0.5, 0.5, f); - assert_eq!(half.content_bounds(), Rect::new(0, 0, 32, 16), "{f:?}"); - let p = half.pixel(16, 8); - assert!((p[1] - 0.5).abs() < 0.02 && (p[3] - 1.0).abs() < 1e-3, "{f:?} {p:?}"); - let dbl = resize_surface(&s, 2.0, 2.0, f); - assert_eq!(dbl.content_bounds(), Rect::new(0, 0, 128, 64), "{f:?}"); - // Mid-gray channel and the ramp's monotonicity are preserved. - let row: Vec = (8..120).map(|x| dbl.pixel(x, 30)[0]).collect(); - assert!(row.windows(2).all(|w| w[1] >= w[0] - 0.02), "{f:?}"); - } - } - - #[test] - fn downscale_averages_checkerboard() { - let mut s = Surface::new(PixelFormat::RGBA8); - for y in 0..64 { - for x in 0..64 { - let v = ((x + y) % 2) as f32; - s.write_pixel(x, y, &[v, v, v, 1.0]); - } - } - let o = resize_surface(&s, 0.25, 0.25, Resample::Bicubic); - let p = o.pixel(8, 8); - assert!((p[0] - 0.5).abs() < 0.05, "{p:?}"); - } - - /// A reduction by a tiny scale covers millions of source samples per output sample; only the - /// ones in the content get a weight, the rest fold onto its ends or into `outside`. - #[test] - fn tiny_scales_do_not_get_a_weight_per_covered_sample() { - for kernel in [Kernel::Bilinear, Kernel::Keys { a: -0.5, stretch: 1.0 }] { - for edge in [None, Some((0, 99))] { - let t = taps(0, 3, 1e-6, kernel, edge, (0, 99)); - for t in &t { - assert!(t.weights.len() <= 100, "{}", t.weights.len()); - let total = t.weights.iter().sum::() + t.outside; - assert!((total - 1.0).abs() < 1e-3, "{total}"); - } - } - } - } - - #[test] - fn transparent_edges_do_not_darken() { - let mut s = Surface::new(PixelFormat::RGBA32F); - s.fill_rect(Rect::new(10, 10, 20, 20), &[1.0, 0.0, 0.0, 1.0]); - let o = resize_surface(&s, 1.7, 1.7, Resample::Lanczos); - let edge = o.pixel(17, 25); - assert!(edge[3] > 0.0 && (edge[0] - 1.0).abs() < 0.05 && edge[1].abs() < 0.05, "{edge:?}"); - } - - /// Image Size of a layer that fills the canvas: its edges stay opaque and keep their colour, - /// up or down, at every depth; a layer away from the edges keeps its soft border. - #[test] - fn canvas_edges_repeat_instead_of_fading() { - let canvas = Rect::new(0, 0, 30, 20); - let colour = [0.2, 0.6, 1.0, 1.0]; - let filters = [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos, Resample::PreserveDetails]; - for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { - let fmt = PixelFormat::new(ColorMode::Rgb, sample, true); - let mut s = Surface::new(fmt); - s.fill_rect(canvas, &colour); - for f in filters { - for k in [2.0, 1.37, 0.5] { - let o = resize_surface_in_canvas(&s, k, k, f, canvas); - let dst = scaled_rect(canvas, k, k); - assert_eq!(o.content_bounds(), dst, "{sample:?} {f:?} {k}"); - for (x, y) in [(0, 0), (dst.x1 - 1, 0), (0, dst.y1 - 1), (dst.x1 - 1, dst.y1 - 1), (dst.x1 / 2, 0), (0, dst.y1 / 2)] { - let p = o.pixel(x, y); - let off = p.iter().zip(colour).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(off < 0.01, "{sample:?} {f:?} {k} ({x},{y}): {p:?}"); - } - } - } - // Inside the canvas the default pixel is still what lies around a layer. - let mut inner = Surface::new(fmt); - inner.fill_rect(Rect::new(10, 5, 20, 15), &[1.0, 0.0, 0.0, 1.0]); - let r = Rect::new(0, 0, 60, 40); - let a = resize_surface_in_canvas(&inner, 1.7, 1.7, Resample::Lanczos, canvas); - assert_eq!(a.read_region(r), resize_surface(&inner, 1.7, 1.7, Resample::Lanczos).read_region(r), "{sample:?}"); - } - } - - /// Two tiles in opposite corners of a 100000 px square: the content bounds are huge but - /// almost nothing is stored. Shrinking it to one pixel must neither allocate a window - /// proportional to the scale (#713) nor read the empty middle. - #[test] - fn tiny_target_of_a_huge_sparse_source() { - let mut s = Surface::new(PixelFormat::RGBA32F); - s.fill_rect(Rect::new(0, 0, 256, 256), &[1.0, 1.0, 1.0, 1.0]); - s.fill_rect(Rect::new(99_840, 99_840, 100_096, 100_096), &[1.0, 1.0, 1.0, 1.0]); - let k = 1.0 / 100_096.0; - let o = resize_surface(&s, k, k, Resample::Bicubic); - assert_eq!(o.content_bounds(), Rect::new(0, 0, 1, 1)); - let p = o.pixel(0, 0); - // Two 256² tiles out of 100096²: nearly transparent, and white where it isn't. - assert!(p[3] >= 0.0 && p[3] < 1e-3 && p.iter().all(|v| v.is_finite()), "{p:?}"); - // Squashed to one row but kept wide: the whole height feeds one band of output rows, - // which must not hold a full-height intermediate. - let o = resize_surface(&s, 1000.0 / 100_096.0, k, Resample::Bicubic); - let b = o.content_bounds(); - assert!(b.height() == 1 && (1000..=1001).contains(&b.width()), "{b:?}"); - assert!(o.pixel(0, 0)[3] > 0.0 && o.pixel(500, 0)[3] == 0.0, "{:?} {:?}", o.pixel(0, 0), o.pixel(500, 0)); - } - - /// Tile rows with nothing stored are not read; they count as rows of the default pixel, - /// exactly as reading them would (and within rounding for a non-zero default). - #[test] - fn skipped_empty_rows_match_reading_them() { - for (fmt, def, tol) in [(PixelFormat::RGBA32F, vec![0.0, 0.0, 0.0, 0.0], 0.0), (PixelFormat::GRAY8, vec![1.0], 1e-6)] { - let mut sparse = Surface::with_default(fmt, &def); - sparse.fill_rect(Rect::new(0, 0, 300, 40), &vec![0.5; def.len()]); - sparse.fill_rect(Rect::new(100, 1500, 400, 1540), &vec![0.25; def.len()]); - // The same pixels with the empty rows stored as tiles of the default pixel. - let mut dense = sparse.clone(); - dense.fill_rect(Rect::new(0, 40, 400, 1500), &def); - assert!(dense.tile_count() > sparse.tile_count()); - for f in [Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] { - for (kx, ky) in [(0.013, 0.013), (0.37, 0.37), (1.0, 0.01)] { - let (a, b) = (resize_surface(&sparse, kx, ky, f), resize_surface(&dense, kx, ky, f)); - let r = a.content_bounds().union(&b.content_bounds()); - let d = a.read_region(r).iter().zip(b.read_region(r)).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max); - assert!(d <= tol, "{fmt:?} {f:?} {kx} {ky}: {d}"); - } - } - } - } - - /// Reading the source in row chunks gives exactly what one read of the whole window gives. - #[test] - fn chunked_reads_match_a_single_read() { - let mut s = ramp(SampleType::F32); - s.fill_rect(Rect::new(600, 700, 640, 720), &[0.3, 0.9, 0.1, 0.5]); - let mut mask = Surface::with_default(PixelFormat::GRAY8, &[1.0]); - mask.fill_rect(Rect::new(0, 0, 40, 30), &[0.0]); - mask.fill_rect(Rect::new(500, 900, 530, 940), &[0.25]); - for src in [&s, &mask] { - for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] { - for k in [0.013, 0.37, 1.6] { - let whole = resize_with_budget(src, k, k, f, None, usize::MAX); - let chunked = resize_with_budget(src, k, k, f, None, 1); - let r = whole.content_bounds().union(&chunked.content_bounds()); - assert_eq!(whole.read_region(r), chunked.read_region(r), "{f:?} {k}"); - } - } - } - } - - #[test] - fn masks_keep_default_pixel() { - let fmt = PixelFormat::GRAY8; - let mut m = Surface::with_default(fmt, &[1.0]); - m.fill_rect(Rect::new(0, 0, 10, 10), &[0.0]); - let o = resize_surface(&m, 2.0, 2.0, Resample::Bilinear); - assert_eq!(o.default_pixel(), vec![1.0]); - assert!(o.pixel(5, 5)[0] < 0.01); - } - - #[test] - fn translate_and_crop() { - let s = ramp(SampleType::U8); - let t = translate_surface(&s, 5, -3); - assert_eq!(t.pixel(15, 7), s.pixel(10, 10)); - let c = crop_surface(&s, Rect::new(0, 0, 10, 10)); - assert_eq!(c.content_bounds(), Rect::new(0, 0, 10, 10)); - } - - /// #1114: nearest neighbor reduction must sample single source pixels, never average. - #[test] - fn nearest_neighbor_reduction_does_not_average() { - let mut s = Surface::new(PixelFormat::GRAY8); - for y in 0..8 { - for x in 0..8 { - if (x + y) % 2 == 0 { - s.fill_rect(Rect::new(x, y, x + 1, y + 1), &[1.0]); - } - } - } - let reduced = resize_surface(&s, 0.5, 0.5, Resample::Nearest); - for y in 0..4 { - for x in 0..4 { - let p = reduced.pixel(x, y)[0]; - assert!(p == 0.0 || p == 1.0, "nearest produced an averaged value {p} at ({x}, {y})"); - } - } - } -} +mod tests; diff --git a/crates/algo/src/resample/tests.rs b/crates/algo/src/resample/tests.rs new file mode 100644 index 0000000000..0ee08847e1 --- /dev/null +++ b/crates/algo/src/resample/tests.rs @@ -0,0 +1,402 @@ +use super::*; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; + +fn ramp(sample: SampleType) -> Surface { + let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true)); + let r = Rect::new(0, 0, 64, 32); + let v: Vec = (0..32).flat_map(|_| (0..64).flat_map(|x| [x as f32 / 63.0, 0.5, 1.0 - x as f32 / 63.0, 1.0])).collect(); + s.write_region(r, &v); + s +} + +#[test] +fn fixed_channel_rows_match_dynamic_resampling() { + fn check() { + for scale in [0.12, 0.5, 1.0, 2.3] { + for filter in [Kernel::Nearest, Kernel::Bilinear, keys(Resample::Bicubic, scale), keys(Resample::BicubicSharper, scale), Kernel::Lanczos] { + for clamp in [None, Some((-3, 31))] { + let ts = taps(-5, 41, scale, filter, clamp, (-3, 31)); + let row: Vec = (0..35 * N).map(|i| ((i * 73) % 251) as f32 / 250.0).collect(); + let def: Vec = (0..N).map(|i| i as f32 / 7.0).collect(); + let mut expected = vec![0.0; ts.len() * N]; + let mut actual = expected.clone(); + horizontal_dynamic(&row, &mut expected, &ts, -3, &def, N); + horizontal_fixed::(&row, &mut actual, &ts, -3, &def); + assert_eq!(actual, expected, "N={N} scale={scale} filter={filter:?} clamp={clamp:?}"); + } + } + } + } + check::<1>(); + check::<2>(); + check::<3>(); + check::<4>(); + check::<5>(); +} + +/// Photoshop 25.4's Image Size of a 16-bit greyscale pattern, in levels of 32768. Covers the +/// filters and their 2-D rules: Sharper reducing the width while the height grows is designed +/// for the height (not widened) and runs the width first; Bicubic Automatic splits a mixed +/// resize into Sharper and Smoother; Bicubic widens for the height's 0.6 while the width +/// grows; Smoother below ¼ averages down first; Bilinear below ½ averages whole pixels. On black +/// and white the overshoot is clipped between the passes, so their order shows. +#[test] +fn matches_photoshop_image_size() { + // (black and white pattern, filter, size, new size, Photoshop's levels) + type Probe = (bool, Resample, (i32, i32), (i32, i32), &'static [u16]); + let cases: [Probe; 9] = [ + ( + false, + Resample::BicubicSharper, + (12, 10), + (7, 16), + &[ + 3777, 13165, 22219, 16176, 10460, 19488, 29643, 11249, 12634, 21696, 13330, 10319, 18965, 29120, 21280, 11204, 20279, 16184, 8200, 17548, + 27703, 21824, 10182, 19259, 26967, 5238, 16528, 26683, 17366, 8895, 17922, 32768, 2402, 15190, 25345, 17493, 7834, 16903, 31316, 1748, 14172, + 24326, 24718, 6368, 15746, 30390, 0, 13107, 23169, 31215, 4790, 14456, 27639, 5080, 11597, 21880, 29649, 3864, 13507, 24136, 20600, 10264, + 20931, 28009, 0, 12446, 21385, 28735, 8754, 19642, 26154, 4049, 10895, 20832, 23523, 7620, 18485, 23204, 20126, 8787, 19818, 21447, 6173, + 17467, 20390, 31862, 6616, 18480, 24094, 6500, 16129, 19749, 27472, 5810, 17460, 28281, 7655, 15108, 18394, 25515, 4427, 16043, 28749, 7026, + 13691, 17871, 24992, 3904, 15520, 27200, 6075, 13168, + ], + ), + ( + false, + Resample::BicubicAutomatic, + (12, 10), + (7, 16), + &[ + 4201, 12337, 27677, 15894, 4816, 20021, 29631, 10348, 9882, 27304, 14492, 3766, 19574, 29046, 18743, 5944, 25299, 16116, 4147, 17829, 27787, + 19399, 4206, 21790, 23748, 7966, 15117, 26569, 15941, 2695, 19445, 28341, 10104, 13050, 25465, 16251, 2613, 18023, 26770, 8432, 11951, 24281, + 22800, 7141, 15351, 24790, 5953, 11004, 23130, 28322, 10921, 12440, 24940, 9659, 9368, 22012, 27611, 10006, 10488, 26419, 18657, 7071, 20807, + 25492, 6937, 9239, 26574, 22363, 5435, 19688, 24808, 9136, 8184, 25295, 19708, 3939, 18677, 25053, 18234, 7120, 24061, 17941, 2545, 17568, + 24869, 23748, 6081, 21401, 21862, 6018, 15056, 23602, 22177, 4859, 17816, 28450, 11911, 11653, 22253, 20263, 3595, 15790, 29734, 12969, 9683, + 21668, 19678, 3010, 15424, 28429, 11728, 9300, + ], + ), + ( + false, + Resample::Bicubic, + (12, 10), + (20, 6), + &[ + 11517, 10000, 8617, 9364, 12272, 16362, 21396, 25508, 25506, 19474, 10887, 5289, 5842, 10286, 14986, 18566, 21910, 25511, 28611, 29922, 24788, + 17949, 8497, 4593, 7309, 12594, 17150, 20945, 24892, 26196, 22979, 16123, 9691, 7483, 10061, 14653, 18841, 22420, 25514, 26824, 25702, 23396, + 17586, 11378, 8127, 8882, 12310, 17039, 22345, 25871, 24700, 18125, 9951, 5493, 6802, 11215, 15576, 19259, 22384, 23694, 26692, 26985, 22732, + 14270, 6889, 4950, 8348, 13583, 17529, 21570, 25966, 27275, 22817, 14643, 8068, 6911, 10694, 15930, 19443, 20705, 21499, 23413, 25601, 24336, + 18665, 11686, 7800, 8947, 12974, 18067, 22707, 25285, 23077, 16645, 9789, 6586, 8147, 12329, 15935, 17465, 17962, 20462, 24615, 25377, 20036, + 11458, 5421, 5415, 9528, 14134, 17782, 22482, 26926, 27479, 21881, 13308, 7533, 7734, 11549, 13992, + ], + ), + ( + false, + Resample::BicubicSmoother, + (40, 3), + (9, 3), + &[ + 11315, 18740, 17475, 15974, 16503, 16042, 18215, 14712, 16238, 18482, 14351, 14664, 18012, 20260, 13338, 15511, 18468, 18275, 16790, 19168, + 14745, 14998, 20341, 18150, 13819, 16493, 16432, + ], + ), + ( + false, + Resample::Bilinear, + (12, 10), + (5, 4), + &[11316, 14541, 17920, 10855, 24679, 19763, 9933, 23757, 6247, 20070, 25601, 5325, 19149, 17306, 15463, 20992, 16384, 14541, 23143, 10854], + ), + ( + false, + Resample::Nearest, + (12, 10), + (7, 16), + &[ + 1638, 12698, 23757, 3482, 9011, 20070, 31130, 1638, 12698, 23757, 3482, 9011, 20070, 31130, 31130, 10854, 21914, 1638, 7168, 18227, 29286, + 29286, 9011, 20070, 31130, 5325, 16384, 27443, 29286, 9011, 20070, 31130, 5325, 16384, 27443, 27443, 7168, 18227, 29286, 3482, 14541, 25600, + 25600, 5325, 16384, 27443, 1638, 12698, 23757, 25600, 5325, 16384, 27443, 1638, 12698, 23757, 23757, 3482, 14541, 25600, 31130, 10854, 21914, + 23757, 3482, 14541, 25600, 31130, 10854, 21914, 21914, 1638, 12698, 23757, 29286, 9011, 20070, 20070, 31130, 10854, 21914, 27443, 7168, 18227, + 20070, 31130, 10854, 21914, 27443, 7168, 18227, 18227, 29286, 9011, 20070, 25600, 5325, 16384, 16384, 27443, 7168, 18227, 23757, 3482, 14541, + 16384, 27443, 7168, 18227, 23757, 3482, 14541, + ], + ), + ( + true, + Resample::Bicubic, + (12, 10), + (20, 6), + &[ + 9960, 6313, 993, 0, 4525, 14807, 26472, 32768, 32768, 23510, 10514, 0, 0, 0, 10110, 22576, 31764, 32768, 32768, 32768, 26136, 18594, 6164, 0, + 0, 2565, 14499, 26983, 32768, 32768, 26358, 14709, 3969, 0, 0, 6602, 17734, 27952, 32768, 32768, 31590, 27808, 18307, 7429, 0, 0, 3712, 14435, + 26473, 32768, 31131, 20665, 7535, 0, 0, 2177, 13238, 25049, 32768, 32768, 32768, 32768, 26136, 14174, 2548, 0, 0, 6190, 18705, 30273, 32768, + 32768, 25517, 13238, 2177, 0, 0, 7250, 19418, 26624, 32768, 32768, 32768, 28203, 18522, 7200, 0, 0, 3285, 14794, 26862, 32768, 29913, 19013, + 6667, 0, 0, 4443, 14506, 20751, 17344, 23066, 31075, 32361, 23949, 10738, 0, 0, 0, 10110, 22657, 32768, 32768, 32768, 22658, 10192, 1004, 0, 0, + 0, + ], + ), + ( + true, + Resample::BicubicSharper, + (12, 10), + (7, 16), + &[ + 801, 3050, 32489, 16260, 0, 29819, 32767, 9161, 1781, 29578, 14350, 0, 32768, 32767, 21132, 0, 25409, 17862, 0, 26925, 32767, 22769, 0, 24839, + 27566, 0, 9397, 32768, 19813, 0, 27795, 32768, 0, 0, 32768, 20744, 0, 25797, 32768, 0, 0, 32768, 27555, 0, 11184, 32768, 0, 0, 32768, 32768, 0, + 0, 32768, 5110, 0, 30386, 32768, 0, 0, 32768, 20385, 0, 23267, 32768, 0, 0, 32768, 29130, 0, 19191, 32768, 2670, 0, 31290, 25387, 0, 21263, + 32767, 20198, 0, 21586, 24510, 0, 23714, 32768, 32768, 0, 14165, 27804, 1007, 14254, 32768, 30149, 0, 16077, 32112, 2886, 1884, 21043, 29607, + 0, 16384, 32768, 3566, 0, 12683, 29616, 0, 16384, 32768, 3196, 0, + ], + ), + ( + true, + Resample::BicubicSharper, + (12, 10), + (20, 6), + &[ + 9273, 5043, 0, 0, 2698, 14484, 28464, 32768, 32768, 24841, 10877, 0, 0, 0, 9684, 22346, 31492, 32768, 32768, 32768, 25960, 18430, 4978, 0, 0, + 977, 15047, 28475, 32768, 32768, 27939, 14157, 1813, 0, 0, 5296, 17828, 28439, 32768, 32768, 32768, 27849, 17576, 6209, 0, 0, 2169, 15076, + 28935, 32768, 32768, 22167, 7399, 0, 0, 211, 12977, 24638, 32768, 32768, 32768, 32768, 25960, 14244, 824, 0, 0, 5093, 18802, 31993, 32768, + 32768, 26467, 12977, 211, 0, 0, 6300, 19418, 26712, 32768, 32768, 32768, 27907, 17874, 5820, 0, 0, 1853, 16055, 29518, 32768, 32768, 20889, + 5880, 0, 0, 2879, 13798, 20185, 19010, 25565, 32768, 32302, 25431, 11478, 0, 0, 0, 9684, 23083, 32768, 32768, 32768, 23084, 10422, 1276, 0, 0, + 0, + ], + ), + ]; + for (binary, filter, (w, h), (wo, ho), want) in cases { + let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::U16, false)); + let canvas = Rect::new(0, 0, w, h); + let level = |x: i32, y: i32| match ((x * 37 + y * 101) % 17) as f32 { + k if binary => { + if k > 8.0 { + 32767.0 / 32768.0 + } else { + 0.0 + } + } + k => ((k / 16.0 * 0.9 + 0.05) * 32768.0).round() / 32768.0, + }; + let px: Vec = (0..h).flat_map(|y| (0..w).map(move |x| level(x, y))).collect(); + s.write_region(canvas, &px); + let o = resize_surface_in_canvas(&s, wo as f64 / w as f64, ho as f64 / h as f64, filter, canvas); + let got = o.read_region(Rect::new(0, 0, wo, ho)); + assert_eq!(got.len(), want.len(), "{filter:?}"); + let worst = got.iter().zip(want).map(|(g, &p)| (g * 32768.0 - p as f32).abs()).fold(0.0f32, f32::max); + assert!(worst <= 8.0, "{filter:?} {w}x{h} to {wo}x{ho}: {worst} levels of 32768 from Photoshop"); + } +} + +/// Photoshop's Bicubic doubles with the Keys cubic at a = −0.75 (Catmull-Rom is −0.5): an +/// impulse spreads as −9, −27, 67, 225 /256 and back, as Photoshop 25.4 gives it. +#[test] +fn bicubic_is_photoshops_keys_cubic() { + let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false)); + let mut row = [0.25; 30]; + row[10] = 0.75; + s.write_region(Rect::new(0, 0, 30, 1), &row); + let o = resize_surface(&s, 2.0, 1.0, Resample::Bicubic); + let got: Vec = o.read_region(Rect::new(17, 0, 25, 1)).iter().map(|v| (v - 0.25) * 512.0).collect(); + for (g, want) in got.iter().zip([-9.0, -27.0, 67.0, 225.0, 225.0, 67.0, -27.0, -9.0]) { + assert!((g - want).abs() < 1e-3, "{got:?}"); + } +} + +#[test] +fn identity_scale_is_lossless() { + for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] { + let s = ramp(SampleType::U16); + let o = resize_surface(&s, 1.0, 1.0, f); + let r = Rect::new(0, 0, 64, 32); + let (a, b) = (s.read_region(r), o.read_region(r)); + let d = a.iter().zip(&b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max); + assert!(d < 1e-4, "{f:?} {d}"); + } +} + +#[test] +fn half_and_double_sizes() { + for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos, Resample::PreserveDetails] { + let s = ramp(SampleType::F32); + let half = resize_surface(&s, 0.5, 0.5, f); + assert_eq!(half.content_bounds(), Rect::new(0, 0, 32, 16), "{f:?}"); + let p = half.pixel(16, 8); + assert!((p[1] - 0.5).abs() < 0.02 && (p[3] - 1.0).abs() < 1e-3, "{f:?} {p:?}"); + let dbl = resize_surface(&s, 2.0, 2.0, f); + assert_eq!(dbl.content_bounds(), Rect::new(0, 0, 128, 64), "{f:?}"); + // Mid-gray channel and the ramp's monotonicity are preserved. + let row: Vec = (8..120).map(|x| dbl.pixel(x, 30)[0]).collect(); + assert!(row.windows(2).all(|w| w[1] >= w[0] - 0.02), "{f:?}"); + } +} + +#[test] +fn downscale_averages_checkerboard() { + let mut s = Surface::new(PixelFormat::RGBA8); + for y in 0..64 { + for x in 0..64 { + let v = ((x + y) % 2) as f32; + s.write_pixel(x, y, &[v, v, v, 1.0]); + } + } + let o = resize_surface(&s, 0.25, 0.25, Resample::Bicubic); + let p = o.pixel(8, 8); + assert!((p[0] - 0.5).abs() < 0.05, "{p:?}"); +} + +/// A reduction by a tiny scale covers millions of source samples per output sample; only the +/// ones in the content get a weight, the rest fold onto its ends or into `outside`. +#[test] +fn tiny_scales_do_not_get_a_weight_per_covered_sample() { + for kernel in [Kernel::Bilinear, Kernel::Keys { a: -0.5, stretch: 1.0 }] { + for edge in [None, Some((0, 99))] { + let t = taps(0, 3, 1e-6, kernel, edge, (0, 99)); + for t in &t { + assert!(t.weights.len() <= 100, "{}", t.weights.len()); + let total = t.weights.iter().sum::() + t.outside; + assert!((total - 1.0).abs() < 1e-3, "{total}"); + } + } + } +} + +#[test] +fn transparent_edges_do_not_darken() { + let mut s = Surface::new(PixelFormat::RGBA32F); + s.fill_rect(Rect::new(10, 10, 20, 20), &[1.0, 0.0, 0.0, 1.0]); + let o = resize_surface(&s, 1.7, 1.7, Resample::Lanczos); + let edge = o.pixel(17, 25); + assert!(edge[3] > 0.0 && (edge[0] - 1.0).abs() < 0.05 && edge[1].abs() < 0.05, "{edge:?}"); +} + +/// Image Size of a layer that fills the canvas: its edges stay opaque and keep their colour, +/// up or down, at every depth; a layer away from the edges keeps its soft border. +#[test] +fn canvas_edges_repeat_instead_of_fading() { + let canvas = Rect::new(0, 0, 30, 20); + let colour = [0.2, 0.6, 1.0, 1.0]; + let filters = [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos, Resample::PreserveDetails]; + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let fmt = PixelFormat::new(ColorMode::Rgb, sample, true); + let mut s = Surface::new(fmt); + s.fill_rect(canvas, &colour); + for f in filters { + for k in [2.0, 1.37, 0.5] { + let o = resize_surface_in_canvas(&s, k, k, f, canvas); + let dst = scaled_rect(canvas, k, k); + assert_eq!(o.content_bounds(), dst, "{sample:?} {f:?} {k}"); + for (x, y) in [(0, 0), (dst.x1 - 1, 0), (0, dst.y1 - 1), (dst.x1 - 1, dst.y1 - 1), (dst.x1 / 2, 0), (0, dst.y1 / 2)] { + let p = o.pixel(x, y); + let off = p.iter().zip(colour).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(off < 0.01, "{sample:?} {f:?} {k} ({x},{y}): {p:?}"); + } + } + } + // Inside the canvas the default pixel is still what lies around a layer. + let mut inner = Surface::new(fmt); + inner.fill_rect(Rect::new(10, 5, 20, 15), &[1.0, 0.0, 0.0, 1.0]); + let r = Rect::new(0, 0, 60, 40); + let a = resize_surface_in_canvas(&inner, 1.7, 1.7, Resample::Lanczos, canvas); + assert_eq!(a.read_region(r), resize_surface(&inner, 1.7, 1.7, Resample::Lanczos).read_region(r), "{sample:?}"); + } +} + +/// Two tiles in opposite corners of a 100000 px square: the content bounds are huge but +/// almost nothing is stored. Shrinking it to one pixel must neither allocate a window +/// proportional to the scale (#713) nor read the empty middle. +#[test] +fn tiny_target_of_a_huge_sparse_source() { + let mut s = Surface::new(PixelFormat::RGBA32F); + s.fill_rect(Rect::new(0, 0, 256, 256), &[1.0, 1.0, 1.0, 1.0]); + s.fill_rect(Rect::new(99_840, 99_840, 100_096, 100_096), &[1.0, 1.0, 1.0, 1.0]); + let k = 1.0 / 100_096.0; + let o = resize_surface(&s, k, k, Resample::Bicubic); + assert_eq!(o.content_bounds(), Rect::new(0, 0, 1, 1)); + let p = o.pixel(0, 0); + // Two 256² tiles out of 100096²: nearly transparent, and white where it isn't. + assert!(p[3] >= 0.0 && p[3] < 1e-3 && p.iter().all(|v| v.is_finite()), "{p:?}"); + // Squashed to one row but kept wide: the whole height feeds one band of output rows, + // which must not hold a full-height intermediate. + let o = resize_surface(&s, 1000.0 / 100_096.0, k, Resample::Bicubic); + let b = o.content_bounds(); + assert!(b.height() == 1 && (1000..=1001).contains(&b.width()), "{b:?}"); + assert!(o.pixel(0, 0)[3] > 0.0 && o.pixel(500, 0)[3] == 0.0, "{:?} {:?}", o.pixel(0, 0), o.pixel(500, 0)); +} + +/// Tile rows with nothing stored are not read; they count as rows of the default pixel, +/// exactly as reading them would (and within rounding for a non-zero default). +#[test] +fn skipped_empty_rows_match_reading_them() { + for (fmt, def, tol) in [(PixelFormat::RGBA32F, vec![0.0, 0.0, 0.0, 0.0], 0.0), (PixelFormat::GRAY8, vec![1.0], 1e-6)] { + let mut sparse = Surface::with_default(fmt, &def); + sparse.fill_rect(Rect::new(0, 0, 300, 40), &vec![0.5; def.len()]); + sparse.fill_rect(Rect::new(100, 1500, 400, 1540), &vec![0.25; def.len()]); + // The same pixels with the empty rows stored as tiles of the default pixel. + let mut dense = sparse.clone(); + dense.fill_rect(Rect::new(0, 40, 400, 1500), &def); + assert!(dense.tile_count() > sparse.tile_count()); + for f in [Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] { + for (kx, ky) in [(0.013, 0.013), (0.37, 0.37), (1.0, 0.01)] { + let (a, b) = (resize_surface(&sparse, kx, ky, f), resize_surface(&dense, kx, ky, f)); + let r = a.content_bounds().union(&b.content_bounds()); + let d = a.read_region(r).iter().zip(b.read_region(r)).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max); + assert!(d <= tol, "{fmt:?} {f:?} {kx} {ky}: {d}"); + } + } + } +} + +/// Reading the source in row chunks gives exactly what one read of the whole window gives. +#[test] +fn chunked_reads_match_a_single_read() { + let mut s = ramp(SampleType::F32); + s.fill_rect(Rect::new(600, 700, 640, 720), &[0.3, 0.9, 0.1, 0.5]); + let mut mask = Surface::with_default(PixelFormat::GRAY8, &[1.0]); + mask.fill_rect(Rect::new(0, 0, 40, 30), &[0.0]); + mask.fill_rect(Rect::new(500, 900, 530, 940), &[0.25]); + for src in [&s, &mask] { + for f in [Resample::Nearest, Resample::Bilinear, Resample::Bicubic, Resample::Lanczos] { + for k in [0.013, 0.37, 1.6] { + let whole = resize_with_budget(src, k, k, f, None, usize::MAX); + let chunked = resize_with_budget(src, k, k, f, None, 1); + let r = whole.content_bounds().union(&chunked.content_bounds()); + assert_eq!(whole.read_region(r), chunked.read_region(r), "{f:?} {k}"); + } + } + } +} + +#[test] +fn masks_keep_default_pixel() { + let fmt = PixelFormat::GRAY8; + let mut m = Surface::with_default(fmt, &[1.0]); + m.fill_rect(Rect::new(0, 0, 10, 10), &[0.0]); + let o = resize_surface(&m, 2.0, 2.0, Resample::Bilinear); + assert_eq!(o.default_pixel(), vec![1.0]); + assert!(o.pixel(5, 5)[0] < 0.01); +} + +#[test] +fn translate_and_crop() { + let s = ramp(SampleType::U8); + let t = translate_surface(&s, 5, -3); + assert_eq!(t.pixel(15, 7), s.pixel(10, 10)); + let c = crop_surface(&s, Rect::new(0, 0, 10, 10)); + assert_eq!(c.content_bounds(), Rect::new(0, 0, 10, 10)); +} + +/// #1114: nearest neighbor reduction must sample single source pixels, never average. +#[test] +fn nearest_neighbor_reduction_does_not_average() { + let mut s = Surface::new(PixelFormat::GRAY8); + for y in 0..8 { + for x in 0..8 { + if (x + y) % 2 == 0 { + s.fill_rect(Rect::new(x, y, x + 1, y + 1), &[1.0]); + } + } + } + let reduced = resize_surface(&s, 0.5, 0.5, Resample::Nearest); + for y in 0..4 { + for x in 0..4 { + let p = reduced.pixel(x, y)[0]; + assert!(p == 0.0 || p == 1.0, "nearest produced an averaged value {p} at ({x}, {y})"); + } + } +} From 66c47635949501e518bf477a370db69a7b951c3a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:06 +0000 Subject: [PATCH 023/259] refactor(algo): move quantize.rs tests to quantize/tests.rs --- crates/algo/src/quantize.rs | 445 +----------------------------- crates/algo/src/quantize/tests.rs | 442 +++++++++++++++++++++++++++++ 2 files changed, 443 insertions(+), 444 deletions(-) create mode 100644 crates/algo/src/quantize/tests.rs diff --git a/crates/algo/src/quantize.rs b/crates/algo/src/quantize.rs index 70d5b5c90c..ceb9c332ad 100644 --- a/crates/algo/src/quantize.rs +++ b/crates/algo/src/quantize.rs @@ -731,447 +731,4 @@ pub fn to_bitmap_custom(gray: &mut [f32], w: usize, map: &[f32], mw: usize, mh: } #[cfg(test)] -mod tests { - use super::*; - - fn gradient(w: usize, h: usize) -> Vec<[f32; 4]> { - (0..w * h).map(|i| [(i % w) as f32 / (w - 1) as f32, (i / w) as f32 / (h - 1) as f32, 0.3, 1.0]).collect() - } - - fn to8_reference(v: f32) -> u8 { - (v.clamp(0.0, 1.0) * 255.0).round() as u8 - } - - #[test] - fn to8_matches_round_on_samples_and_edges() { - // Every half-way point and its neighbours, plus a dense sweep of the unit range. - for k in 0..=256u32 { - let mid = (k as f32 + 0.5) / 255.0; - for d in -3i32..=3 { - let v = f32::from_bits((mid.to_bits() as i32 + d) as u32); - assert_eq!(to8(v), to8_reference(v), "{v:e}"); - } - } - for i in 0..200_000u32 { - let v = f32::from_bits(i * 20_000); - assert_eq!(to8(v), to8_reference(v), "{v:e}"); - } - for v in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.0, 0.0, 1.0, -1.0, 2.0, 1e30, -1e30, f32::MIN_POSITIVE, 1e-45] { - assert_eq!(to8(v), to8_reference(v), "{v:e}"); - } - } - - #[test] - #[cfg(not(target_arch = "wasm32"))] - #[ignore = "checks all 2^32 floats, a few seconds in release; run with --release --ignored"] - fn to8_matches_round_for_every_float() { - use rayon::prelude::*; - let bad = (0..=u32::MAX).into_par_iter().filter(|&b| to8(f32::from_bits(b)) != to8_reference(f32::from_bits(b))).count(); - assert_eq!(bad, 0); - } - - /// A repeatable 96x64 image: a gradient with up to 31 levels of integer-hash noise and a - /// few see-through pixels. - fn golden_image() -> Vec<[f32; 4]> { - let (w, h) = (96usize, 64usize); - (0..w * h) - .map(|i| { - let (x, y) = ((i % w) as f32, (i / w) as f32); - let noise = |salt: u32| ((((i as u32).wrapping_mul(2_654_435_761).wrapping_add(salt.wrapping_mul(40_503))) >> 13) & 31) as f32 / 255.0; - let alpha = if i % 17 == 0 { 0.25 } else { 1.0 }; - [x / (w - 1) as f32 * 0.8 + noise(1), y / (h - 1) as f32 * 0.7 + noise(2), ((x + y) / (w + h) as f32) * 0.6 + noise(3), alpha] - }) - .collect() - } - - /// Palettes written down from the version before the speed-up (hash-map histogram, every box - /// rescanned each split, comparison sort, serial k-means). Any change to how the palettes - /// are built has to give these exact colours. - #[test] - fn palettes_match_the_recorded_originals() { - let px = golden_image(); - #[rustfmt::skip] - let cases: Vec<(PaletteKind, usize, Forced, &[Rgb8])> = vec![ - ( - PaletteKind::Adaptive, - 16, - Forced::None, - &[ - [40, 173, 80], [196, 175, 150], [92, 173, 103], [92, 81, 71], [195, 83, 118], [39, 82, 49], - [142, 82, 95], [195, 37, 101], [143, 36, 79], [40, 128, 64], [196, 129, 133], [92, 127, 87], - [91, 36, 56], [38, 35, 33], [144, 128, 111], [144, 174, 127], - ], - ), - ( - PaletteKind::Perceptual, - 16, - Forced::None, - &[ - [104, 111, 87], [51, 129, 68], [48, 178, 79], [110, 74, 77], [165, 46, 93], [205, 50, 107], - [200, 154, 143], [44, 54, 42], [190, 101, 121], [61, 32, 44], [155, 115, 111], [48, 93, 56], - [119, 42, 71], [84, 172, 98], [126, 165, 115], [172, 168, 135], - ], - ), - ( - PaletteKind::Selective, - 24, - Forced::BlackWhite, - &[ - [0, 0, 0], [255, 255, 255], [102, 107, 85], [65, 69, 55], [87, 133, 89], [109, 73, 76], - [164, 42, 92], [204, 51, 102], [199, 153, 142], [54, 170, 84], [199, 107, 126], [65, 33, 45], - [153, 102, 102], [187, 180, 145], [40, 106, 54], [100, 176, 107], [138, 174, 123], [50, 188, 80], - [32, 37, 33], [47, 139, 69], [144, 143, 116], [41, 80, 49], [108, 33, 64], [151, 70, 94], - ], - ), - ( - PaletteKind::Adaptive, - 8, - Forced::Primaries, - &[ - [0, 0, 0], [255, 255, 255], [255, 0, 0], [0, 255, 0], [0, 0, 255], [0, 255, 255], - [255, 0, 255], [255, 255, 0], - ], - ), - ( - PaletteKind::Perceptual, - 12, - Forced::BlackWhite, - &[ - [0, 0, 0], [255, 255, 255], [104, 106, 85], [137, 43, 79], [148, 170, 126], [181, 144, 132], - [66, 172, 87], [88, 49, 60], [57, 118, 67], [42, 54, 41], [183, 101, 118], [196, 50, 105], - ], - ), - ]; - for (kind, colors, forced, expected) in cases { - assert_eq!(build_palette(&px, kind, colors, forced).unwrap(), expected, "{kind:?} {colors} {forced:?}"); - } - } - - /// The pre-speed-up median cut and k-means, kept as the oracle for the faster ones. - fn median_cut_reference(pts: &[([f32; 3], u32)], n: usize) -> Vec<[f32; 3]> { - if pts.is_empty() || n == 0 { - return Vec::new(); - } - let mut boxes: Vec> = vec![pts.to_vec()]; - while boxes.len() < n { - let (bi, axis, score) = boxes - .iter() - .enumerate() - .filter(|(_, b)| b.len() > 1) - .map(|(i, b)| { - let mut best = (0usize, -1.0f32); - for a in 0..3 { - let (lo, hi) = b.iter().fold((f32::MAX, f32::MIN), |(lo, hi), p| (lo.min(p.0[a]), hi.max(p.0[a]))); - if hi - lo > best.1 { - best = (a, hi - lo); - } - } - let w: f32 = b.iter().map(|p| p.1 as f32).sum(); - (i, best.0, best.1 * w.sqrt()) - }) - .fold((usize::MAX, 0, -1.0f32), |acc, x| if x.2 > acc.2 { x } else { acc }); - if bi == usize::MAX || score <= 0.0 { - break; - } - let mut b = boxes.swap_remove(bi); - b.sort_by(|p, q| p.0[axis].total_cmp(&q.0[axis])); - let total: u64 = b.iter().map(|p| u64::from(p.1)).sum(); - let mut acc = 0u64; - let mut cut = 1; - for (i, p) in b.iter().enumerate() { - acc += u64::from(p.1); - if acc * 2 >= total { - cut = (i + 1).clamp(1, b.len() - 1); - break; - } - } - let rest = b.split_off(cut); - boxes.push(b); - boxes.push(rest); - } - boxes - .iter() - .map(|b| { - let w: f64 = b.iter().map(|p| f64::from(p.1)).sum(); - std::array::from_fn(|a| (b.iter().map(|p| f64::from(p.0[a]) * f64::from(p.1)).sum::() / w) as f32) - }) - .collect() - } - - fn kmeans_reference(pts: &[([f32; 3], u32)], centers: &mut [[f32; 3]], iters: usize) { - for _ in 0..iters { - let lookup = Nearest::new(centers.iter().copied()); - let mut sum = vec![[0.0f64; 3]; centers.len()]; - let mut cnt = vec![0.0f64; centers.len()]; - for (p, w) in pts { - let i = lookup.find(*p); - for a in 0..3 { - sum[i][a] += f64::from(p[a]) * f64::from(*w); - } - cnt[i] += f64::from(*w); - } - for (i, c) in centers.iter_mut().enumerate() { - if cnt[i] > 0.0 { - *c = std::array::from_fn(|a| (sum[i][a] / cnt[i]) as f32); - } - } - } - } - - /// Points with many repeated coordinates (ties), negative values, -0.0 and weights up to - /// a few thousand, so the stable-sort and float-order rules are all exercised. - fn tie_heavy_points(n: usize, seed: u64) -> Vec<([f32; 3], u32)> { - let mut s = seed; - let mut next = move || { - s = s.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); - (s >> 33) as u32 - }; - (0..n) - .map(|_| { - let mut c = |range: u32| match next() % 40 { - 0 => -0.0, - 1 => 0.0, - _ => (next() % range) as f32 * 0.5 - (range / 4) as f32, - }; - ([c(24), c(300), c(150)], 1 + next() % 3000) - }) - .collect() - } - - #[test] - fn faster_median_cut_and_kmeans_equal_the_originals_bit_for_bit() { - // 40 000 points cross the 256-point radix threshold on the first splits. - for (n, boxes, seed) in [(40_000, 256, 1), (40_000, 37, 2), (3_000, 256, 3), (200, 64, 4), (2, 8, 5)] { - let pts = tie_heavy_points(n, seed); - let new = median_cut(&pts, boxes); - let old = median_cut_reference(&pts, boxes); - assert_eq!(new.len(), old.len()); - for (a, b) in new.iter().zip(&old) { - assert_eq!(a.map(f32::to_bits), b.map(f32::to_bits), "median cut, n={n} boxes={boxes}"); - } - let (mut a, mut b) = (new, old); - kmeans(&pts, &mut a, 3); - kmeans_reference(&pts, &mut b, 3); - for (x, y) in a.iter().zip(&b) { - assert_eq!(x.map(f32::to_bits), y.map(f32::to_bits), "kmeans, n={n} boxes={boxes}"); - } - } - } - - #[test] - fn radix_sort_is_the_stable_total_cmp_sort() { - for axis in 0..3 { - let mut pts = tie_heavy_points(5_000, 9 + axis as u64); - // The weight field doubles as an id: equal keys must keep their input order. - for (i, p) in pts.iter_mut().enumerate() { - p.1 = i as u32; - } - pts[10].0[axis] = f32::NAN; - pts[11].0[axis] = -f32::NAN; - pts[12].0[axis] = f32::INFINITY; - pts[13].0[axis] = f32::NEG_INFINITY; - let mut expected = pts.clone(); - expected.sort_by(|p, q| p.0[axis].total_cmp(&q.0[axis])); - radix_sort_along(&mut pts, axis); - let bits = |v: &[([f32; 3], u32)]| v.iter().map(|p| (p.0.map(f32::to_bits), p.1)).collect::>(); - assert_eq!(bits(&pts), bits(&expected), "axis {axis}"); - } - } - - #[test] - fn histogram_counts_opaque_pixels_sorted() { - let px = [[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 0.5], [1.0, 0.0, 0.0, 0.49], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]]; - assert_eq!(histogram(&px), vec![([0, 0, 0], 1), ([0, 0, 255], 2), ([255, 0, 0], 2)]); - assert!(histogram(&[]).is_empty()); - } - - #[test] - fn fixed_palettes_have_expected_sizes() { - assert_eq!(web_palette().len(), 216); - assert_eq!(mac_palette().len(), 256); - assert_eq!(windows_palette().len(), 256); - assert_eq!(uniform_palette(27).len(), 27); - let mut m = mac_palette(); - m.sort_unstable(); - m.dedup(); - assert_eq!(m.len(), 256, "mac palette entries are unique"); - } - - #[test] - fn exact_palette_and_failure() { - let px = vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 1.0]]; - assert_eq!(build_palette(&px, PaletteKind::Exact, 256, Forced::None).unwrap().len(), 2); - assert!(build_palette(&gradient(64, 64), PaletteKind::Exact, 256, Forced::None).is_err()); - } - - #[test] - fn adaptive_and_perceptual_respect_count_and_forced() { - let px = gradient(40, 40); - for kind in [PaletteKind::Adaptive, PaletteKind::Perceptual, PaletteKind::Selective] { - let pal = build_palette(&px, kind, 16, Forced::BlackWhite).unwrap(); - assert!(pal.len() <= 16 && pal.len() >= 8, "{kind:?} {}", pal.len()); - assert_eq!(&pal[..2], &[[0, 0, 0], [255, 255, 255]]); - } - } - - #[test] - fn forced_colours_filling_the_count_do_not_panic() { - // 2 colours + Black and White (or 8 + Primaries) leaves no room for - // computed entries; the median cut used to return no centres and - // k-means indexed into the empty list. - let px = vec![[1.0, 1.0, 1.0, 1.0]; 16]; - for kind in [PaletteKind::Adaptive, PaletteKind::Perceptual, PaletteKind::Selective] { - let pal = build_palette(&px, kind, 2, Forced::BlackWhite).unwrap(); - assert_eq!(pal, vec![[0, 0, 0], [255, 255, 255]], "{kind:?}"); - let pal = build_palette(&gradient(8, 8), kind, 8, Forced::Primaries).unwrap(); - assert_eq!(pal.len(), 8, "{kind:?}"); - } - } - - #[test] - #[ignore = "24 MP release timing comparison; run with --release --ignored --nocapture"] - fn indexed_diffusion_24mp_release_comparison() { - let source = gradient(6000, 4000); - let pal = web_palette(); - for run in 0..4 { - let mut linear = source.clone(); - let mut accelerated = source.clone(); - let mut before = None; - let mut after = None; - // Reverse the order on alternating rounds; exclude the first round as warmup. - for old in if run % 2 == 0 { [true, false] } else { [false, true] } { - let start = std::time::Instant::now(); - if old { - let indices = quantize_with(&mut linear, 6000, &pal, Dither::Diffusion, 0.75, None, |c| linear_rgb_nearest(&pal, c)); - before = Some((start.elapsed().as_secs_f64() * 1000.0, indices)); - } else { - let indices = quantize(&mut accelerated, 6000, &pal, Dither::Diffusion, 0.75, None); - after = Some((start.elapsed().as_secs_f64() * 1000.0, indices)); - } - } - let (before_ms, before_indices) = before.unwrap(); - let (after_ms, after_indices) = after.unwrap(); - assert_eq!(before_indices.iter().zip(&after_indices).position(|(a, b)| a != b), None, "first differing index"); - assert_eq!(linear.iter().zip(&accelerated).position(|(a, b)| a != b), None, "first differing pixel"); - println!( - "{}", - serde_json::json!({"run":run,"warmup":run==0,"pixels":24_000_000,"palette_entries":216,"linear_ms":before_ms,"accelerated_ms":after_ms}) - ); - } - } - - fn linear_rgb_nearest(pal: &[Rgb8], c: [f32; 3]) -> usize { - let mut best = (f32::MAX, 0); - for (i, e) in pal.iter().enumerate() { - let d: f32 = (0..3).map(|k| (c[k] * 255.0 - f32::from(e[k])).powi(2)).sum(); - if d < best.0 { - best = (d, i); - } - } - best.1 - } - - #[test] - fn all_dithers_match_the_original_linear_palette_search_exactly() { - let mut source = gradient(93, 61); - for (i, p) in source.iter_mut().enumerate() { - p[2] = (i % 71) as f32 / 70.0; - p[3] = [0.0, 0.2, 0.7, 1.0][i % 4]; - } - for count in [8, 16, 32, 64, 128, 256] { - let pal = build_palette(&source, PaletteKind::Selective, count, Forced::BlackWhite).unwrap(); - for dither in [Dither::None, Dither::Diffusion, Dither::Pattern, Dither::Noise] { - for transparent in [None, Some(1)] { - let mut actual = source.clone(); - let mut expected = source.clone(); - let indices = quantize(&mut actual, 93, &pal, dither, 0.75, transparent); - let old_indices = quantize_with(&mut expected, 93, &pal, dither, 0.75, transparent, |c| linear_rgb_nearest(&pal, c)); - assert_eq!(indices, old_indices, "{count} {dither:?} {transparent:?}"); - assert_eq!(actual, expected, "{count} {dither:?} {transparent:?}"); - } - } - } - } - - #[test] - fn quantize_maps_to_palette_with_each_dither() { - let pal = vec![[0, 0, 0], [255, 255, 255]]; - for d in [Dither::None, Dither::Diffusion, Dither::Pattern, Dither::Noise] { - let mut px: Vec<[f32; 4]> = (0..64) - .map(|i| [i as f32 / 63.0; 4]) - .map(|mut p| { - p[3] = 1.0; - p - }) - .collect(); - let idx = quantize(&mut px, 8, &pal, d, 1.0, None); - assert!(px.iter().all(|p| p[0] == 0.0 || p[0] == 1.0), "{d:?}"); - assert_eq!(idx.len(), 64); - // Mean brightness is preserved by dithering (not by plain thresholding). - if d == Dither::Diffusion { - let mean = px.iter().map(|p| p[0]).sum::() / 64.0; - assert!((mean - 0.5).abs() < 0.08, "{mean}"); - } - } - let mut px = vec![[1.0, 1.0, 1.0, 0.2]]; - let idx = quantize(&mut px, 1, &pal, Dither::None, 1.0, Some(1)); - assert_eq!((idx[0], px[0][3]), (1, 0.0)); - } - - #[test] - fn bitmap_methods_are_binary_and_track_tone() { - for m in [ - BitmapMethod::Threshold, - BitmapMethod::Pattern, - BitmapMethod::Diffusion, - BitmapMethod::Halftone { cell: 6.0, angle: 45.0, shape: HalftoneShape::Round }, - ] { - let mut g = vec![0.25f32; 32 * 32]; - to_bitmap(&mut g, 32, m); - assert!(g.iter().all(|v| *v == 0.0 || *v == 1.0)); - let mean = g.iter().sum::() / g.len() as f32; - if m != BitmapMethod::Threshold { - assert!((mean - 0.25).abs() < 0.15, "{m:?} {mean}"); - } else { - assert_eq!(mean, 0.0); - } - } - } - - /// The first 8-bit gray level (of a 0..=255 ramp) that `t` turns white. - fn first_white(t: f32) -> u32 { - (0..=255).find(|v| *v as f32 / 255.0 >= t).unwrap_or(256) - } - - #[test] - fn custom_pattern_thresholds_match_photoshop() { - // Photoshop (Image › Mode › Bitmap, Custom Pattern) on a 0..255 ramp: the first white - // level per pattern pixel, measured against defined patterns. - let l = |v: &[u8]| v.iter().map(|v| f32::from(*v) / 255.0).collect::>(); - let ramp7 = custom_pattern_thresholds(&l(&[0, 40, 80, 120, 160, 200, 240])); - assert_eq!(ramp7.iter().map(|t| first_white(*t)).collect::>(), [237, 201, 164, 128, 92, 55, 19]); - let five = custom_pattern_thresholds(&l(&[10, 200, 90, 250, 150])); - assert_eq!(five.iter().map(|t| first_white(*t)).collect::>(), [230, 77, 179, 26, 128]); - // Equal pixels share their rank: 100, 100 both sit at 50%. - let ties = custom_pattern_thresholds(&l(&[100, 100, 200, 50])); - assert_eq!(ties.iter().map(|t| first_white(*t)).collect::>(), [128, 128, 32, 224]); - assert!(custom_pattern_thresholds(&[]).is_empty()); - assert_eq!(custom_pattern_thresholds(&[f32::NAN, 0.3]).len(), 2); - } - - #[test] - fn custom_pattern_tiles_from_the_top_left() { - // A 2x1 map: even columns need 75%, odd ones 25%. - let map = [0.75, 0.25]; - let mut g = vec![0.5; 6]; - to_bitmap_custom(&mut g, 3, &map, 2, 1); - assert_eq!(g, [0.0, 1.0, 0.0, 0.0, 1.0, 0.0]); - // A map that doesn't match its size, or an empty image width, is a 50% threshold. - let mut g = vec![0.4, 0.6]; - to_bitmap_custom(&mut g, 2, &map, 3, 1); - assert_eq!(g, [0.0, 1.0]); - let mut g = vec![0.6]; - to_bitmap_custom(&mut g, 0, &map, 2, 1); - assert_eq!(g, [1.0]); - } -} +mod tests; diff --git a/crates/algo/src/quantize/tests.rs b/crates/algo/src/quantize/tests.rs new file mode 100644 index 0000000000..14afa17f56 --- /dev/null +++ b/crates/algo/src/quantize/tests.rs @@ -0,0 +1,442 @@ +use super::*; + +fn gradient(w: usize, h: usize) -> Vec<[f32; 4]> { + (0..w * h).map(|i| [(i % w) as f32 / (w - 1) as f32, (i / w) as f32 / (h - 1) as f32, 0.3, 1.0]).collect() +} + +fn to8_reference(v: f32) -> u8 { + (v.clamp(0.0, 1.0) * 255.0).round() as u8 +} + +#[test] +fn to8_matches_round_on_samples_and_edges() { + // Every half-way point and its neighbours, plus a dense sweep of the unit range. + for k in 0..=256u32 { + let mid = (k as f32 + 0.5) / 255.0; + for d in -3i32..=3 { + let v = f32::from_bits((mid.to_bits() as i32 + d) as u32); + assert_eq!(to8(v), to8_reference(v), "{v:e}"); + } + } + for i in 0..200_000u32 { + let v = f32::from_bits(i * 20_000); + assert_eq!(to8(v), to8_reference(v), "{v:e}"); + } + for v in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.0, 0.0, 1.0, -1.0, 2.0, 1e30, -1e30, f32::MIN_POSITIVE, 1e-45] { + assert_eq!(to8(v), to8_reference(v), "{v:e}"); + } +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +#[ignore = "checks all 2^32 floats, a few seconds in release; run with --release --ignored"] +fn to8_matches_round_for_every_float() { + use rayon::prelude::*; + let bad = (0..=u32::MAX).into_par_iter().filter(|&b| to8(f32::from_bits(b)) != to8_reference(f32::from_bits(b))).count(); + assert_eq!(bad, 0); +} + +/// A repeatable 96x64 image: a gradient with up to 31 levels of integer-hash noise and a +/// few see-through pixels. +fn golden_image() -> Vec<[f32; 4]> { + let (w, h) = (96usize, 64usize); + (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as f32, (i / w) as f32); + let noise = |salt: u32| ((((i as u32).wrapping_mul(2_654_435_761).wrapping_add(salt.wrapping_mul(40_503))) >> 13) & 31) as f32 / 255.0; + let alpha = if i % 17 == 0 { 0.25 } else { 1.0 }; + [x / (w - 1) as f32 * 0.8 + noise(1), y / (h - 1) as f32 * 0.7 + noise(2), ((x + y) / (w + h) as f32) * 0.6 + noise(3), alpha] + }) + .collect() +} + +/// Palettes written down from the version before the speed-up (hash-map histogram, every box +/// rescanned each split, comparison sort, serial k-means). Any change to how the palettes +/// are built has to give these exact colours. +#[test] +fn palettes_match_the_recorded_originals() { + let px = golden_image(); + #[rustfmt::skip] + let cases: Vec<(PaletteKind, usize, Forced, &[Rgb8])> = vec![ + ( + PaletteKind::Adaptive, + 16, + Forced::None, + &[ + [40, 173, 80], [196, 175, 150], [92, 173, 103], [92, 81, 71], [195, 83, 118], [39, 82, 49], + [142, 82, 95], [195, 37, 101], [143, 36, 79], [40, 128, 64], [196, 129, 133], [92, 127, 87], + [91, 36, 56], [38, 35, 33], [144, 128, 111], [144, 174, 127], + ], + ), + ( + PaletteKind::Perceptual, + 16, + Forced::None, + &[ + [104, 111, 87], [51, 129, 68], [48, 178, 79], [110, 74, 77], [165, 46, 93], [205, 50, 107], + [200, 154, 143], [44, 54, 42], [190, 101, 121], [61, 32, 44], [155, 115, 111], [48, 93, 56], + [119, 42, 71], [84, 172, 98], [126, 165, 115], [172, 168, 135], + ], + ), + ( + PaletteKind::Selective, + 24, + Forced::BlackWhite, + &[ + [0, 0, 0], [255, 255, 255], [102, 107, 85], [65, 69, 55], [87, 133, 89], [109, 73, 76], + [164, 42, 92], [204, 51, 102], [199, 153, 142], [54, 170, 84], [199, 107, 126], [65, 33, 45], + [153, 102, 102], [187, 180, 145], [40, 106, 54], [100, 176, 107], [138, 174, 123], [50, 188, 80], + [32, 37, 33], [47, 139, 69], [144, 143, 116], [41, 80, 49], [108, 33, 64], [151, 70, 94], + ], + ), + ( + PaletteKind::Adaptive, + 8, + Forced::Primaries, + &[ + [0, 0, 0], [255, 255, 255], [255, 0, 0], [0, 255, 0], [0, 0, 255], [0, 255, 255], + [255, 0, 255], [255, 255, 0], + ], + ), + ( + PaletteKind::Perceptual, + 12, + Forced::BlackWhite, + &[ + [0, 0, 0], [255, 255, 255], [104, 106, 85], [137, 43, 79], [148, 170, 126], [181, 144, 132], + [66, 172, 87], [88, 49, 60], [57, 118, 67], [42, 54, 41], [183, 101, 118], [196, 50, 105], + ], + ), + ]; + for (kind, colors, forced, expected) in cases { + assert_eq!(build_palette(&px, kind, colors, forced).unwrap(), expected, "{kind:?} {colors} {forced:?}"); + } +} + +/// The pre-speed-up median cut and k-means, kept as the oracle for the faster ones. +fn median_cut_reference(pts: &[([f32; 3], u32)], n: usize) -> Vec<[f32; 3]> { + if pts.is_empty() || n == 0 { + return Vec::new(); + } + let mut boxes: Vec> = vec![pts.to_vec()]; + while boxes.len() < n { + let (bi, axis, score) = boxes + .iter() + .enumerate() + .filter(|(_, b)| b.len() > 1) + .map(|(i, b)| { + let mut best = (0usize, -1.0f32); + for a in 0..3 { + let (lo, hi) = b.iter().fold((f32::MAX, f32::MIN), |(lo, hi), p| (lo.min(p.0[a]), hi.max(p.0[a]))); + if hi - lo > best.1 { + best = (a, hi - lo); + } + } + let w: f32 = b.iter().map(|p| p.1 as f32).sum(); + (i, best.0, best.1 * w.sqrt()) + }) + .fold((usize::MAX, 0, -1.0f32), |acc, x| if x.2 > acc.2 { x } else { acc }); + if bi == usize::MAX || score <= 0.0 { + break; + } + let mut b = boxes.swap_remove(bi); + b.sort_by(|p, q| p.0[axis].total_cmp(&q.0[axis])); + let total: u64 = b.iter().map(|p| u64::from(p.1)).sum(); + let mut acc = 0u64; + let mut cut = 1; + for (i, p) in b.iter().enumerate() { + acc += u64::from(p.1); + if acc * 2 >= total { + cut = (i + 1).clamp(1, b.len() - 1); + break; + } + } + let rest = b.split_off(cut); + boxes.push(b); + boxes.push(rest); + } + boxes + .iter() + .map(|b| { + let w: f64 = b.iter().map(|p| f64::from(p.1)).sum(); + std::array::from_fn(|a| (b.iter().map(|p| f64::from(p.0[a]) * f64::from(p.1)).sum::() / w) as f32) + }) + .collect() +} + +fn kmeans_reference(pts: &[([f32; 3], u32)], centers: &mut [[f32; 3]], iters: usize) { + for _ in 0..iters { + let lookup = Nearest::new(centers.iter().copied()); + let mut sum = vec![[0.0f64; 3]; centers.len()]; + let mut cnt = vec![0.0f64; centers.len()]; + for (p, w) in pts { + let i = lookup.find(*p); + for a in 0..3 { + sum[i][a] += f64::from(p[a]) * f64::from(*w); + } + cnt[i] += f64::from(*w); + } + for (i, c) in centers.iter_mut().enumerate() { + if cnt[i] > 0.0 { + *c = std::array::from_fn(|a| (sum[i][a] / cnt[i]) as f32); + } + } + } +} + +/// Points with many repeated coordinates (ties), negative values, -0.0 and weights up to +/// a few thousand, so the stable-sort and float-order rules are all exercised. +fn tie_heavy_points(n: usize, seed: u64) -> Vec<([f32; 3], u32)> { + let mut s = seed; + let mut next = move || { + s = s.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (s >> 33) as u32 + }; + (0..n) + .map(|_| { + let mut c = |range: u32| match next() % 40 { + 0 => -0.0, + 1 => 0.0, + _ => (next() % range) as f32 * 0.5 - (range / 4) as f32, + }; + ([c(24), c(300), c(150)], 1 + next() % 3000) + }) + .collect() +} + +#[test] +fn faster_median_cut_and_kmeans_equal_the_originals_bit_for_bit() { + // 40 000 points cross the 256-point radix threshold on the first splits. + for (n, boxes, seed) in [(40_000, 256, 1), (40_000, 37, 2), (3_000, 256, 3), (200, 64, 4), (2, 8, 5)] { + let pts = tie_heavy_points(n, seed); + let new = median_cut(&pts, boxes); + let old = median_cut_reference(&pts, boxes); + assert_eq!(new.len(), old.len()); + for (a, b) in new.iter().zip(&old) { + assert_eq!(a.map(f32::to_bits), b.map(f32::to_bits), "median cut, n={n} boxes={boxes}"); + } + let (mut a, mut b) = (new, old); + kmeans(&pts, &mut a, 3); + kmeans_reference(&pts, &mut b, 3); + for (x, y) in a.iter().zip(&b) { + assert_eq!(x.map(f32::to_bits), y.map(f32::to_bits), "kmeans, n={n} boxes={boxes}"); + } + } +} + +#[test] +fn radix_sort_is_the_stable_total_cmp_sort() { + for axis in 0..3 { + let mut pts = tie_heavy_points(5_000, 9 + axis as u64); + // The weight field doubles as an id: equal keys must keep their input order. + for (i, p) in pts.iter_mut().enumerate() { + p.1 = i as u32; + } + pts[10].0[axis] = f32::NAN; + pts[11].0[axis] = -f32::NAN; + pts[12].0[axis] = f32::INFINITY; + pts[13].0[axis] = f32::NEG_INFINITY; + let mut expected = pts.clone(); + expected.sort_by(|p, q| p.0[axis].total_cmp(&q.0[axis])); + radix_sort_along(&mut pts, axis); + let bits = |v: &[([f32; 3], u32)]| v.iter().map(|p| (p.0.map(f32::to_bits), p.1)).collect::>(); + assert_eq!(bits(&pts), bits(&expected), "axis {axis}"); + } +} + +#[test] +fn histogram_counts_opaque_pixels_sorted() { + let px = [[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 0.5], [1.0, 0.0, 0.0, 0.49], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]]; + assert_eq!(histogram(&px), vec![([0, 0, 0], 1), ([0, 0, 255], 2), ([255, 0, 0], 2)]); + assert!(histogram(&[]).is_empty()); +} + +#[test] +fn fixed_palettes_have_expected_sizes() { + assert_eq!(web_palette().len(), 216); + assert_eq!(mac_palette().len(), 256); + assert_eq!(windows_palette().len(), 256); + assert_eq!(uniform_palette(27).len(), 27); + let mut m = mac_palette(); + m.sort_unstable(); + m.dedup(); + assert_eq!(m.len(), 256, "mac palette entries are unique"); +} + +#[test] +fn exact_palette_and_failure() { + let px = vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 1.0]]; + assert_eq!(build_palette(&px, PaletteKind::Exact, 256, Forced::None).unwrap().len(), 2); + assert!(build_palette(&gradient(64, 64), PaletteKind::Exact, 256, Forced::None).is_err()); +} + +#[test] +fn adaptive_and_perceptual_respect_count_and_forced() { + let px = gradient(40, 40); + for kind in [PaletteKind::Adaptive, PaletteKind::Perceptual, PaletteKind::Selective] { + let pal = build_palette(&px, kind, 16, Forced::BlackWhite).unwrap(); + assert!(pal.len() <= 16 && pal.len() >= 8, "{kind:?} {}", pal.len()); + assert_eq!(&pal[..2], &[[0, 0, 0], [255, 255, 255]]); + } +} + +#[test] +fn forced_colours_filling_the_count_do_not_panic() { + // 2 colours + Black and White (or 8 + Primaries) leaves no room for + // computed entries; the median cut used to return no centres and + // k-means indexed into the empty list. + let px = vec![[1.0, 1.0, 1.0, 1.0]; 16]; + for kind in [PaletteKind::Adaptive, PaletteKind::Perceptual, PaletteKind::Selective] { + let pal = build_palette(&px, kind, 2, Forced::BlackWhite).unwrap(); + assert_eq!(pal, vec![[0, 0, 0], [255, 255, 255]], "{kind:?}"); + let pal = build_palette(&gradient(8, 8), kind, 8, Forced::Primaries).unwrap(); + assert_eq!(pal.len(), 8, "{kind:?}"); + } +} + +#[test] +#[ignore = "24 MP release timing comparison; run with --release --ignored --nocapture"] +fn indexed_diffusion_24mp_release_comparison() { + let source = gradient(6000, 4000); + let pal = web_palette(); + for run in 0..4 { + let mut linear = source.clone(); + let mut accelerated = source.clone(); + let mut before = None; + let mut after = None; + // Reverse the order on alternating rounds; exclude the first round as warmup. + for old in if run % 2 == 0 { [true, false] } else { [false, true] } { + let start = std::time::Instant::now(); + if old { + let indices = quantize_with(&mut linear, 6000, &pal, Dither::Diffusion, 0.75, None, |c| linear_rgb_nearest(&pal, c)); + before = Some((start.elapsed().as_secs_f64() * 1000.0, indices)); + } else { + let indices = quantize(&mut accelerated, 6000, &pal, Dither::Diffusion, 0.75, None); + after = Some((start.elapsed().as_secs_f64() * 1000.0, indices)); + } + } + let (before_ms, before_indices) = before.unwrap(); + let (after_ms, after_indices) = after.unwrap(); + assert_eq!(before_indices.iter().zip(&after_indices).position(|(a, b)| a != b), None, "first differing index"); + assert_eq!(linear.iter().zip(&accelerated).position(|(a, b)| a != b), None, "first differing pixel"); + println!( + "{}", + serde_json::json!({"run":run,"warmup":run==0,"pixels":24_000_000,"palette_entries":216,"linear_ms":before_ms,"accelerated_ms":after_ms}) + ); + } +} + +fn linear_rgb_nearest(pal: &[Rgb8], c: [f32; 3]) -> usize { + let mut best = (f32::MAX, 0); + for (i, e) in pal.iter().enumerate() { + let d: f32 = (0..3).map(|k| (c[k] * 255.0 - f32::from(e[k])).powi(2)).sum(); + if d < best.0 { + best = (d, i); + } + } + best.1 +} + +#[test] +fn all_dithers_match_the_original_linear_palette_search_exactly() { + let mut source = gradient(93, 61); + for (i, p) in source.iter_mut().enumerate() { + p[2] = (i % 71) as f32 / 70.0; + p[3] = [0.0, 0.2, 0.7, 1.0][i % 4]; + } + for count in [8, 16, 32, 64, 128, 256] { + let pal = build_palette(&source, PaletteKind::Selective, count, Forced::BlackWhite).unwrap(); + for dither in [Dither::None, Dither::Diffusion, Dither::Pattern, Dither::Noise] { + for transparent in [None, Some(1)] { + let mut actual = source.clone(); + let mut expected = source.clone(); + let indices = quantize(&mut actual, 93, &pal, dither, 0.75, transparent); + let old_indices = quantize_with(&mut expected, 93, &pal, dither, 0.75, transparent, |c| linear_rgb_nearest(&pal, c)); + assert_eq!(indices, old_indices, "{count} {dither:?} {transparent:?}"); + assert_eq!(actual, expected, "{count} {dither:?} {transparent:?}"); + } + } + } +} + +#[test] +fn quantize_maps_to_palette_with_each_dither() { + let pal = vec![[0, 0, 0], [255, 255, 255]]; + for d in [Dither::None, Dither::Diffusion, Dither::Pattern, Dither::Noise] { + let mut px: Vec<[f32; 4]> = (0..64) + .map(|i| [i as f32 / 63.0; 4]) + .map(|mut p| { + p[3] = 1.0; + p + }) + .collect(); + let idx = quantize(&mut px, 8, &pal, d, 1.0, None); + assert!(px.iter().all(|p| p[0] == 0.0 || p[0] == 1.0), "{d:?}"); + assert_eq!(idx.len(), 64); + // Mean brightness is preserved by dithering (not by plain thresholding). + if d == Dither::Diffusion { + let mean = px.iter().map(|p| p[0]).sum::() / 64.0; + assert!((mean - 0.5).abs() < 0.08, "{mean}"); + } + } + let mut px = vec![[1.0, 1.0, 1.0, 0.2]]; + let idx = quantize(&mut px, 1, &pal, Dither::None, 1.0, Some(1)); + assert_eq!((idx[0], px[0][3]), (1, 0.0)); +} + +#[test] +fn bitmap_methods_are_binary_and_track_tone() { + for m in [ + BitmapMethod::Threshold, + BitmapMethod::Pattern, + BitmapMethod::Diffusion, + BitmapMethod::Halftone { cell: 6.0, angle: 45.0, shape: HalftoneShape::Round }, + ] { + let mut g = vec![0.25f32; 32 * 32]; + to_bitmap(&mut g, 32, m); + assert!(g.iter().all(|v| *v == 0.0 || *v == 1.0)); + let mean = g.iter().sum::() / g.len() as f32; + if m != BitmapMethod::Threshold { + assert!((mean - 0.25).abs() < 0.15, "{m:?} {mean}"); + } else { + assert_eq!(mean, 0.0); + } + } +} + +/// The first 8-bit gray level (of a 0..=255 ramp) that `t` turns white. +fn first_white(t: f32) -> u32 { + (0..=255).find(|v| *v as f32 / 255.0 >= t).unwrap_or(256) +} + +#[test] +fn custom_pattern_thresholds_match_photoshop() { + // Photoshop (Image › Mode › Bitmap, Custom Pattern) on a 0..255 ramp: the first white + // level per pattern pixel, measured against defined patterns. + let l = |v: &[u8]| v.iter().map(|v| f32::from(*v) / 255.0).collect::>(); + let ramp7 = custom_pattern_thresholds(&l(&[0, 40, 80, 120, 160, 200, 240])); + assert_eq!(ramp7.iter().map(|t| first_white(*t)).collect::>(), [237, 201, 164, 128, 92, 55, 19]); + let five = custom_pattern_thresholds(&l(&[10, 200, 90, 250, 150])); + assert_eq!(five.iter().map(|t| first_white(*t)).collect::>(), [230, 77, 179, 26, 128]); + // Equal pixels share their rank: 100, 100 both sit at 50%. + let ties = custom_pattern_thresholds(&l(&[100, 100, 200, 50])); + assert_eq!(ties.iter().map(|t| first_white(*t)).collect::>(), [128, 128, 32, 224]); + assert!(custom_pattern_thresholds(&[]).is_empty()); + assert_eq!(custom_pattern_thresholds(&[f32::NAN, 0.3]).len(), 2); +} + +#[test] +fn custom_pattern_tiles_from_the_top_left() { + // A 2x1 map: even columns need 75%, odd ones 25%. + let map = [0.75, 0.25]; + let mut g = vec![0.5; 6]; + to_bitmap_custom(&mut g, 3, &map, 2, 1); + assert_eq!(g, [0.0, 1.0, 0.0, 0.0, 1.0, 0.0]); + // A map that doesn't match its size, or an empty image width, is a 50% threshold. + let mut g = vec![0.4, 0.6]; + to_bitmap_custom(&mut g, 2, &map, 3, 1); + assert_eq!(g, [0.0, 1.0]); + let mut g = vec![0.6]; + to_bitmap_custom(&mut g, 0, &map, 2, 1); + assert_eq!(g, [1.0]); +} From 6ea5fe1fd88f2bbde550b62bd6c95335fd676534 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:07 +0000 Subject: [PATCH 024/259] refactor(algo): move liquify.rs tests to liquify/tests.rs --- crates/algo/src/liquify.rs | 535 +------------------------------ crates/algo/src/liquify/tests.rs | 532 ++++++++++++++++++++++++++++++ 2 files changed, 533 insertions(+), 534 deletions(-) create mode 100644 crates/algo/src/liquify/tests.rs diff --git a/crates/algo/src/liquify.rs b/crates/algo/src/liquify.rs index 5d35f5791b..379500b25c 100644 --- a/crates/algo/src/liquify.rs +++ b/crates/algo/src/liquify.rs @@ -1035,537 +1035,4 @@ impl ProxyImage { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_color::{ColorMode, PixelFormat, SampleType}; - - /// The segment walk before #937: every dab, whether or not it can reach the field. - fn full_walk(f: &mut LiquifyField, s: &LiquifyStroke, a: [f64; 3], b: [f64; 3]) -> Rect { - f.walk_segment(s, a, b, false) - } - - #[test] - fn a_segment_walks_only_the_dabs_that_can_reach_the_field() { - // #937: a segment to a far-off point walked one dab per spacing step along its whole - // length (~3e14 for 1e15 px). Skipping the dabs that can't reach a field node must leave - // every result bit-identical to the full walk. - use LiquifyTool::*; - let bounds = Rect::new(-7, 3, 89, 67); - let segments: [([f64; 3], [f64; 3]); 10] = [ - ([10.0, 20.0, 1.0], [70.0, 50.0, 0.5]), // inside - ([-900.0, 30.0, 1.0], [40.0, 31.0, 1.0]), // in from far left - ([40.0, 30.0, 1.0], [40.0, 4000.0, 0.2]), // out downwards - ([-500.0, -500.0, 1.0], [600.0, 600.0, 1.0]), // diagonal through - ([-300.0, -9.0, 1.0], [300.0, -9.0, 1.0]), // parallel, just above (the brush reaches) - ([-300.0, -400.0, 1.0], [300.0, -400.0, 1.0]), // parallel, far above (reaches nothing) - ([88.5, -50.0, 1.0], [88.5, 120.0, 1.0]), // vertical, along the right edge - ([200.0, 200.0, 1.0], [201.0, 900.0, 1.0]), // entirely outside - ([0.0, 0.0, 1.0], [0.25, 0.1, 1.0]), // shorter than one step - ([60.0, 40.0, 1.0], [-2000.0, 45.0, 1.0]), // continues the stroke before it, out left - ]; - for tool in [ForwardWarp, PushLeft, Reconstruct, Smooth, TwirlCw, TwirlCcw, Pucker, Bloat, Freeze, Thaw] { - for size in [6.0, 40.0] { - for (a, b) in segments { - let s = LiquifyStroke::new(tool, size); - let (mut fast, mut full) = (LiquifyField::new(bounds, 2.0), LiquifyField::new(bounds, 2.0)); - // Some displacement first, so Reconstruct and Smooth have something to undo. - for f in [&mut fast, &mut full] { - f.stroke_segment(&LiquifyStroke::new(ForwardWarp, 30.0), [20.0, 20.0, 1.0], [60.0, 40.0, 1.0]); - } - let dirty = fast.stroke_segment(&s, a, b); - assert_eq!(dirty, full_walk(&mut full, &s, a, b), "{tool:?} {size} {a:?} {b:?}"); - assert!(fast.d == full.d && fast.freeze == full.freeze, "{tool:?} {size} {a:?} {b:?}"); - } - } - } - } - - /// The same path sampled by `parts` pointer events per corner-to-corner leg, unevenly. - fn sampled(path: &[[f64; 3]], parts: usize) -> Vec> { - let mut out = vec![path[0].to_vec()]; - for w in path.windows(2) { - let (a, b) = (w[0], w[1]); - // Uneven steps, as a real pointer gives: t grows quadratically. - for k in 1..=parts { - let t = (k * k) as f64 / (parts * parts) as f64; - out.push((0..3).map(|i| a[i] + (b[i] - a[i]) * t).collect()); - } - } - out - } - - /// #2606: dabs restarted at every pointer event, so a fast mouse (few far-apart events) and a - /// slow one (many close ones) warped the same path differently. Spacing now runs on along the - /// whole stroke: any sampling of a path gives the same field. - #[test] - fn the_result_does_not_depend_on_how_finely_the_path_was_sampled() { - use LiquifyTool::*; - let path = [[20.0, 20.0, 1.0], [62.0, 26.0, 0.6], [70.0, 50.0, 0.9], [28.0, 55.0, 1.0], [30.0, 30.0, 1.0]]; - for tool in [ForwardWarp, PushLeft, TwirlCw, Bloat, Reconstruct, Smooth, Freeze] { - for size in [12.0, 40.0] { - let field = |parts: usize| { - let mut warp = LiquifyStroke::new(ForwardWarp, 30.0); - warp.points = vec![vec![30.0, 30.0], vec![50.0, 40.0]]; - let mut s = LiquifyStroke::new(tool, size); - s.points = sampled(&path, parts); - // Some displacement first, so Reconstruct and Smooth have something to change. - LiquifyField::from_strokes(bounds(), 2.0, &[warp, s]) - }; - let coarse = field(1); - for parts in [3, 17, 60] { - let fine = field(parts); - let dd = coarse.d.iter().zip(&fine.d).map(|(p, q)| (p[0] - q[0]).abs().max((p[1] - q[1]).abs())).fold(0.0f32, f32::max); - let df = coarse.freeze.iter().zip(&fine.freeze).map(|(p, q)| (p - q).abs()).fold(0.0f32, f32::max); - assert!(dd < 1e-3 && df < 1e-4, "{tool:?} {size}px, {parts} events per leg: field differs by {dd} px, mask by {df}"); - } - } - } - } - - /// A long drag whose events land exactly on dab positions, along a diagonal: rounding must not - /// add or drop the dab at a segment's end, or the deep displacement a long Forward Warp builds - /// up differs by a whole dab between a slow and a fast pointer. - #[test] - fn a_long_diagonal_drag_gives_one_field_at_any_event_spacing() { - let field = |step: f64| { - let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); - s.points = (0..=(300.0 / step) as usize).map(|k| vec![40.0 + k as f64 * step * 0.6, 20.0 + k as f64 * step * 0.8]).collect(); - LiquifyField::from_strokes(Rect::new(0, 0, 320, 300), 2.0, &[s]) - }; - let (slow, fast) = (field(2.0), field(60.0)); - let dd = slow.d.iter().zip(&fast.d).map(|(p, q)| (p[0] - q[0]).abs().max((p[1] - q[1]).abs())).fold(0.0f32, f32::max); - assert!(slow.max_displacement() > 50.0, "the drag builds up a deep displacement"); - assert!(dd < 1e-3, "slow and fast pointer fields differ by {dd} px"); - } - - #[test] - fn a_huge_canvas_gets_a_coarser_field_not_a_huge_one() { - // 400000² px at 2 px per node is 4·10¹⁰ nodes. - let f = LiquifyField::new(Rect::new(0, 0, 400_000, 400_000), 2.0); - assert!(f.w * f.h <= MAX_FIELD_NODES && f.d.len() == f.w * f.h && f.freeze.len() == f.d.len()); - assert!(f.cell > 64.0); - assert_eq!(LiquifyField::new(Rect::new(0, 0, 100, 100), 2.0).cell, 2.0); - } - - #[test] - fn a_stroke_interrupted_by_a_jump_restarts_its_spacing() { - // A segment that does not start where the last one ended begins a new run of dabs there. - let s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 20.0); - let mut f = LiquifyField::new(bounds(), 2.0); - f.stroke_begin(&s, [10.0, 10.0, 1.0]); - f.stroke_segment(&s, [10.0, 10.0, 1.0], [10.3, 10.0, 1.0]); - let mut g = LiquifyField::new(bounds(), 2.0); - f.stroke_segment(&s, [40.0, 30.0, 1.0], [50.0, 30.0, 1.0]); - g.stroke_begin(&s, [40.0, 30.0, 1.0]); - g.stroke_segment(&s, [40.0, 30.0, 1.0], [50.0, 30.0, 1.0]); - assert_eq!(f, g); - // Hostile points: nothing panics and the next segment starts afresh. - f.stroke_segment(&s, [f64::NAN, 3.0, 1.0], [4.0, f64::INFINITY, 1.0]); - f.stroke_segment(&s, [4.0, 3.0, f64::NAN], [9.0, 3.0, 1.0]); - } - - #[test] - fn a_segment_to_a_far_off_point_returns() { - // The issue's request: about 3.3e14 steps before the fix. Also a segment whose length - // overflows f64. - let mut f = LiquifyField::new(Rect::new(0, 0, 24, 16), 2.0); - let s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 30.0); - let dirty = f.stroke_segment(&s, [0.0, 0.0, 1.0], [1e15, 0.0, 1.0]); - assert!(!dirty.is_empty() && dirty.x1 <= 64, "{dirty:?}"); - f.stroke_segment(&s, [-1e308, 5.0, 1.0], [1e308, 5.0, 1.0]); - f.stroke_segment(&LiquifyStroke::new(LiquifyTool::Bloat, 30.0), [5.0, -1e15, 1.0], [5.0, 1e15, 1.0]); - } - - fn sample(st: SampleType) -> Surface { - let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, st, true)); - for y in 0..64 { - for x in 0..96 { - let v = ((x / 4 + y / 4) % 2) as f32; - s.write_pixel(x, y, &[v, (x as f32) / 96.0, (y as f32) / 64.0, 1.0]); - } - } - s - } - - fn bounds() -> Rect { - Rect::new(0, 0, 96, 64) - } - - fn worst(a: &Surface, b: &Surface, r: Rect) -> f32 { - a.read_region(r).iter().zip(b.read_region(r)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max) - } - - fn lasso(points: &[[f64; 2]], amount: Option) -> LiquifyStroke { - let mut s = LiquifyStroke::new(LiquifyTool::LassoMask, 1.0); - s.points = points.iter().map(|p| p.to_vec()).collect(); - s.amount = amount; - s - } - - /// Reference even-odd test (ray casting), to check the scanline fill against. - fn inside(p: [f64; 2], poly: &[[f64; 2]]) -> bool { - let mut inside = false; - let mut j = poly.len() - 1; - for (i, a) in poly.iter().enumerate() { - let b = poly[j]; - if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0] { - inside = !inside; - } - j = i; - } - inside - } - - #[test] - fn lasso_freezes_exactly_the_nodes_inside_a_concave_polygon() { - // A concave "C" with a notch, at a non-integer cell size. - let poly = [[10.0, 8.0], [70.0, 8.0], [70.0, 20.0], [30.0, 22.5], [33.0, 40.0], [80.0, 41.0], [60.0, 58.0], [9.0, 55.0]]; - for cell in [1.0, 2.0, 3.5] { - let mut f = LiquifyField::new(bounds(), cell); - let dirty = f.apply_stroke(&lasso(&poly, None)); - assert_eq!(dirty, Rect::new(9, 8, 80, 58)); - for j in 0..f.h { - for i in 0..f.w { - let want = if inside(f.node_pos(i, j), &poly) { 1.0 } else { 0.0 }; - assert_eq!(f.freeze[j * f.w + i], want, "cell {cell}: node ({i}, {j}) at {:?}", f.node_pos(i, j)); - } - } - assert!(f.freeze.contains(&1.0)); - // Strokes replay to the same field (undo rebuilds from the list). - assert_eq!(LiquifyField::from_strokes(bounds(), cell, &[lasso(&poly, None)]), f); - } - } - - #[test] - fn lasso_thaws_with_amount_zero() { - let mut f = LiquifyField::new(bounds(), 2.0); - f.apply_stroke(&LiquifyStroke::new(LiquifyTool::FreezeAll, 1.0)); - assert!(f.freeze.iter().all(|&v| v == 1.0)); - let square = [[20.0, 20.0], [40.0, 20.0], [40.0, 40.0], [20.0, 40.0]]; - f.apply_stroke(&lasso(&square, Some(0.0))); - assert_eq!(f.freeze_at(30.0, 30.0), 0.0, "thawed inside"); - assert_eq!(f.freeze_at(5.0, 5.0), 1.0, "still frozen outside"); - } - - #[test] - fn lasso_ignores_degenerate_and_hostile_polygons() { - let empty = LiquifyField::new(bounds(), 2.0); - let cases: [&[[f64; 2]]; 6] = [ - &[], - &[[10.0, 10.0], [50.0, 50.0]], - &[[f64::NAN, 10.0], [50.0, f64::INFINITY], [20.0, 30.0]], - // Entirely outside the canvas, on every side. - &[[-50.0, -50.0], [-10.0, -50.0], [-10.0, -10.0]], - &[[200.0, 10.0], [300.0, 10.0], [250.0, 50.0]], - &[[10.0, 1e12], [50.0, 1e12], [30.0, 2e12]], - ]; - for poly in cases { - let mut f = empty.clone(); - assert_eq!(f.apply_stroke(&lasso(poly, None)), Rect::EMPTY, "{poly:?}"); - assert_eq!(f, empty, "{poly:?}"); - } - // Huge coordinates around the canvas clamp to it instead of overflowing. - let mut f = empty.clone(); - f.apply_stroke(&lasso(&[[-1e15, -1e15], [1e15, -1e15], [1e15, 1e15], [-1e15, 1e15]], None)); - assert!(f.freeze.iter().all(|&v| v == 1.0)); - // A NaN point among good ones is skipped. - let mut f = empty.clone(); - f.apply_stroke(&lasso(&[[10.0, 10.0], [f64::NAN, 0.0], [50.0, 10.0], [50.0, 50.0], [10.0, 50.0]], None)); - assert_eq!(f.freeze_at(30.0, 30.0), 1.0); - } - - #[test] - fn the_brush_fades_to_nothing_at_its_rim_at_every_density() { - for density in [0.0, 0.25, 0.5, 0.75, 1.0, f64::NAN, -3.0, 7.0] { - assert_eq!(falloff(0.0, density), 1.0, "full strength at the centre ({density})"); - assert_eq!(falloff(1.0, density), 0.0, "nothing at the rim ({density})"); - // Flat at the rim: the last 2 % of the radius moves at most a couple of percent. - assert!(falloff(0.98f64.powi(2), density) < 0.02, "{density}: {}", falloff(0.98f64.powi(2), density)); - let mut prev = 1.0; - for k in 1..=100 { - let v = falloff(k as f64 / 100.0, density); - assert!(v <= prev && v >= 0.0, "{density}: not falling at t² = {k}%"); - prev = v; - } - } - // Density widens the strong core: more strength at every radius, as in Photoshop. - for k in 1..100 { - let t2 = k as f64 / 100.0; - assert!(falloff(t2, 1.0) >= falloff(t2, 0.5) && falloff(t2, 0.5) >= falloff(t2, 0.0), "t² = {t2}"); - } - assert!(falloff(0.5, 1.0) > 0.5 && falloff(0.5, 0.0) < 0.2); - } - - /// #2606: the dab's strength used to stop at 1 - Density at its rim, so a Forward Warp moved - /// everything just inside the brush and nothing just outside, tearing the image along every - /// dab's circle (a hard-edged block at Density 0, half strength at the default 50). - #[test] - fn forward_warp_leaves_the_brush_rim_in_place() { - // A drag of one dab spacing (a twentieth of the radius): one dab, centred where it started. - let (r, drag) = (20.0, 1.0); - for density in [0.0, 50.0, 100.0] { - let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 2.0 * r); - s.density = density; - s.points = vec![vec![48.0, 32.0], vec![48.0 + drag, 32.0]]; - let f = LiquifyField::from_strokes(bounds(), 1.0, &[s]); - let mut rim = 0; - for j in 0..f.h { - for i in 0..f.w { - let p = f.node_pos(i, j); - let t = (p[0] - 48.0).hypot(p[1] - 32.0) / r; - if (0.97..1.0).contains(&t) { - let d = f.d[j * f.w + i]; - assert!(f64::from(d[0].hypot(d[1])) < 0.03 * drag, "density {density}: a node at {t:.3} r moved {d:?}"); - rim += 1; - } - } - } - assert!(rim > 20, "{rim} rim nodes"); - assert!(f.sample(48.0, 32.0)[0] < -0.9 * drag, "density {density}: the centre follows the brush"); - } - } - - #[test] - fn a_wide_integer_translation_keeps_channels_and_tile_edges_at_every_format() { - let b = Rect::new(13, -1, 13 + 70 * 256, 1); - let w = b.width() as usize; - for mode in [ColorMode::Grayscale, ColorMode::Rgb, ColorMode::Cmyk] { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - let format = PixelFormat::new(mode, depth, true); - let n = format.channels(); - let mut data = Vec::new(); - for i in 0..w * 2 { - let alpha = if i % 13 == 0 { 0.0 } else { 0.5 }; - for c in 0..mode.color_channels() { - data.push(if alpha == 0.0 { 0.0 } else { ((i * 19 + c * 43) % 251 + 2) as f32 / 255.0 }); - } - data.push(alpha); - } - let mut source = Surface::new(format); - source.write_region(b, &data); - source.write_pixel(b.x0 - 1, b.y0 - 1, &vec![0.75; n]); - let before = source.read_region(b); - let mut field = LiquifyField::new(b, 2.5); - field.d.fill([-1.0, 0.0]); - let output = apply_liquify(&source, &field); - let after = output.read_region(b); - let tolerance = if depth == SampleType::F32 { 4.0 * f32::EPSILON } else { 0.0 }; - for (original, moved) in before.chunks_exact(w * n).zip(after.chunks_exact(w * n)) { - for (x, pixel) in moved.chunks_exact(n).enumerate() { - let offset = x.saturating_sub(1) * n; - for (actual, expected) in pixel.iter().zip(&original[offset..offset + n]) { - assert!((actual - expected).abs() <= tolerance, "{mode:?}/{depth:?} at column {x}"); - } - } - } - assert_eq!(output.pixel(b.x0 - 1, b.y0 - 1), source.pixel(b.x0 - 1, b.y0 - 1)); - } - } - } - - #[test] - fn no_strokes_is_identity_at_every_depth() { - for st in [SampleType::U8, SampleType::U16, SampleType::F32] { - let s = sample(st); - let f = LiquifyField::new(bounds(), 2.0); - assert_eq!(apply_liquify(&s, &f), s); - // A field with exactly-zero strokes (zero pressure) is still identity. - let mut st0 = LiquifyStroke::new(LiquifyTool::ForwardWarp, 30.0); - st0.pressure = 0.0; - st0.points = vec![vec![40.0, 30.0], vec![60.0, 30.0]]; - let f = LiquifyField::from_strokes(bounds(), 2.0, &[st0]); - assert!(f.is_identity()); - } - } - - #[test] - fn full_resolution_preview_matches_the_unit_scale_proxy_and_partial_updates() { - let canvas = Rect::new(0, 0, 96, 64); - for sample_type in [SampleType::U8, SampleType::U16, SampleType::F32] { - let source = sample(sample_type); - let mut stroke = LiquifyStroke::new(LiquifyTool::ForwardWarp, 32.0); - stroke.points = vec![vec![38.0, 30.0, 1.0], vec![52.0, 34.0, 0.8]]; - let mut field = LiquifyField::from_strokes(canvas, 2.0, &[stroke]); - - let proxy = ProxyImage::new(&source, canvas, 96); - assert_eq!(proxy.scale, 1.0); - let mut want = vec![[0; 4]; proxy.w * proxy.h]; - proxy.render(&field, [0, 0, proxy.w, proxy.h], &mut want); - - let mut got = vec![[0; 4]; proxy.w * proxy.h]; - let mut scratch = Vec::new(); - assert!(ProxyImage::render_full_resolution(&source, &field, canvas, canvas, &mut got, &mut scratch)); - assert_eq!(got, want, "full-resolution render at {sample_type:?}"); - - let mut more = LiquifyStroke::new(LiquifyTool::Bloat, 16.0); - more.points = vec![vec![43.0, 32.0, 1.0]]; - let dirty = field.apply_stroke(&more); - proxy.render(&field, proxy.proxy_rect(dirty), &mut want); - assert!(ProxyImage::render_full_resolution(&source, &field, canvas, dirty, &mut got, &mut scratch)); - assert_eq!(got, want, "partial update at {sample_type:?}"); - } - } - - #[test] - fn forward_warp_displaces_along_the_stroke_and_reconstruct_restores() { - let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); - s.points = vec![vec![40.0, 32.0], vec![52.0, 32.0]]; - let mut f = LiquifyField::from_strokes(bounds(), 2.0, &[s]); - // Content moved right: the output at the end point samples from the left. - let d = f.sample(52.0, 32.0); - assert!(d[0] < -4.0 && d[1].abs() < 0.5, "{d:?}"); - // A pixel-level check: a marker column follows the stroke. - let mut img = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, true)); - img.fill_rect(bounds(), &[0.0, 1.0]); - img.fill_rect(Rect::new(40, 28, 42, 36), &[1.0, 1.0]); - let out = apply_liquify(&img, &f); - let brightest = (30..70).max_by(|a, b| out.pixel(*a, 32)[0].total_cmp(&out.pixel(*b, 32)[0])).unwrap(); - assert!(brightest > 44, "marker moved right: {brightest}"); - // Reconstruct All restores the original exactly. - let mut rec = LiquifyStroke::new(LiquifyTool::ReconstructAll, 10.0); - rec.amount = Some(100.0); - f.apply_stroke(&rec); - assert!(f.is_identity()); - assert_eq!(apply_liquify(&img, &f), img); - } - - #[test] - fn reconstruct_brush_reduces_the_field_and_freeze_protects() { - let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); - s.points = vec![vec![30.0, 32.0], vec![45.0, 32.0]]; - let mut f = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s)); - let before = f.max_displacement(); - let mut r = LiquifyStroke::new(LiquifyTool::Reconstruct, 80.0); - r.points = vec![vec![40.0, 32.0]; 30]; - f.apply_stroke(&r); - assert!(f.max_displacement() < before * 0.2, "{} vs {before}", f.max_displacement()); - // Frozen area doesn't move. - let mut fr = LiquifyStroke::new(LiquifyTool::Freeze, 60.0); - fr.density = 100.0; - fr.points = vec![vec![40.0, 32.0]]; - let mut g = LiquifyField::new(bounds(), 2.0); - g.apply_stroke(&fr); - assert!(g.freeze_at(40.0, 32.0) > 0.99); - g.apply_stroke(&s); - assert!(g.sample(40.0, 32.0)[0].abs() < 1e-3); - // Thaw unfreezes. - let mut th = fr.clone(); - th.tool = LiquifyTool::Thaw; - g.apply_stroke(&th); - assert!(g.freeze_at(40.0, 32.0) < 0.01); - // Mask All / Invert / None. - g.apply_stroke(&LiquifyStroke::new(LiquifyTool::FreezeAll, 1.0)); - assert!(g.freeze.iter().all(|f| *f == 1.0)); - g.apply_stroke(&LiquifyStroke::new(LiquifyTool::InvertFreeze, 1.0)); - assert!(g.freeze.iter().all(|f| *f == 0.0)); - g.apply_stroke(&fr); - g.apply_stroke(&LiquifyStroke::new(LiquifyTool::InvertFreeze, 1.0)); - assert!(g.freeze_at(40.0, 32.0) < 0.01 && g.freeze_at(5.0, 5.0) > 0.99); - g.apply_stroke(&LiquifyStroke::new(LiquifyTool::ThawAll, 1.0)); - assert!(g.freeze.iter().all(|f| *f == 0.0)); - } - - #[test] - fn fully_frozen_pixels_keep_their_mapping_when_an_adjacent_area_is_warped() { - let bounds = bounds(); - let mut src = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::F32, true)); - for y in 0..bounds.height() { - for x in 0..bounds.width() { - src.write_pixel(x as i32, y as i32, &[x as f32 / bounds.width() as f32, y as f32 / bounds.height() as f32, 0.0, 1.0]); - } - } - - let mut mask_only = LiquifyField::new(bounds, 2.0); - mask_only.apply_stroke(&lasso(&[[0.0, 0.0], [40.0, 0.0], [40.0, 64.0], [0.0, 64.0]], None)); - assert_eq!(apply_liquify(&src, &mask_only), src); - - let mut field = LiquifyField::new(bounds, 2.0); - let mut first_warp = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); - first_warp.points = vec![vec![22.0, 32.0], vec![34.0, 32.0]]; - field.apply_stroke(&first_warp); - - field.apply_stroke(&lasso(&[[0.0, 0.0], [40.0, 0.0], [40.0, 64.0], [0.0, 64.0]], None)); - let frozen_pixel = (37, 32); - assert!(field.freeze_at(f64::from(frozen_pixel.0) + 0.5, f64::from(frozen_pixel.1) + 0.5) > 0.999); - let before = apply_liquify(&src, &field).pixel(frozen_pixel.0, frozen_pixel.1); - assert_ne!(before, src.pixel(frozen_pixel.0, frozen_pixel.1), "freezing must retain the earlier warp"); - let neighbor_before = apply_liquify(&src, &field).pixel(43, 32); - - let mut adjacent_warp = LiquifyStroke::new(LiquifyTool::ForwardWarp, 24.0); - adjacent_warp.points = vec![vec![44.0, 32.0], vec![52.0, 32.0]]; - field.apply_stroke(&adjacent_warp); - - let after = apply_liquify(&src, &field).pixel(frozen_pixel.0, frozen_pixel.1); - let neighbor_after = apply_liquify(&src, &field).pixel(43, 32); - assert_eq!(before, after, "a fully frozen pixel must keep its pre-neighbor-warp mapping"); - assert_ne!(neighbor_before, neighbor_after, "an adjacent unfrozen pixel must still move"); - } - - #[test] - fn twirl_pucker_bloat_and_push_left_have_the_right_sense() { - let at = |tool: LiquifyTool, pts: Vec>| { - let mut s = LiquifyStroke::new(tool, 40.0); - s.points = pts; - LiquifyField::from_strokes(bounds(), 2.0, &[s]) - }; - let c = vec![vec![48.0, 32.0]; 10]; - // Pucker pulls content in: the output samples outward (d points away from the centre). - let f = at(LiquifyTool::Pucker, c.clone()); - assert!(f.sample(58.0, 32.0)[0] > 0.1); - let f = at(LiquifyTool::Bloat, c.clone()); - assert!(f.sample(58.0, 32.0)[0] < -0.1); - // Twirl clockwise (y down): content right of centre moves down, so it samples from above. - let f = at(LiquifyTool::TwirlCw, c.clone()); - assert!(f.sample(58.0, 32.0)[1] < -0.1, "{:?}", f.sample(58.0, 32.0)); - let f = at(LiquifyTool::TwirlCcw, c); - assert!(f.sample(58.0, 32.0)[1] > 0.1); - // Push Left while dragging up moves content left (samples from the right). - let f = at(LiquifyTool::PushLeft, vec![vec![48.0, 44.0], vec![48.0, 20.0]]); - assert!(f.sample(48.0, 32.0)[0] > 0.5, "{:?}", f.sample(48.0, 32.0)); - // Smooth reduces sharp field differences. - let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 12.0); - s.points = vec![vec![40.0, 32.0], vec![50.0, 32.0]]; - let mut g = LiquifyField::from_strokes(bounds(), 2.0, &[s]); - let m0 = g.max_displacement(); - let mut sm = LiquifyStroke::new(LiquifyTool::Smooth, 60.0); - sm.points = vec![vec![45.0, 32.0]; 20]; - g.apply_stroke(&sm); - assert!(g.max_displacement() < m0); - } - - #[test] - fn replay_is_deterministic_and_depths_agree() { - let mut s = LiquifyStroke::new(LiquifyTool::TwirlCw, 50.0); - s.points = vec![vec![48.0, 32.0, 0.5], vec![50.0, 33.0, 1.0], vec![52.0, 34.0]]; - let a = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s)); - let b = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s)); - assert_eq!(a, b); - let r8 = apply_liquify(&sample(SampleType::U8), &a); - let r32 = apply_liquify(&sample(SampleType::F32), &a); - assert!(worst(&r8, &r32, bounds()) < 2.0 / 255.0 + 1e-4); - } - - #[test] - fn proxy_matches_the_full_render_roughly() { - let src = sample(SampleType::U8); - let mut s = LiquifyStroke::new(LiquifyTool::Bloat, 40.0); - s.points = vec![vec![48.0, 32.0]; 8]; - let f = LiquifyField::from_strokes(bounds(), 2.0, &[s]); - let p = ProxyImage::new(&src, bounds(), 96); - assert_eq!((p.w, p.h, p.scale), (96, 64, 1.0)); - let mut out = vec![[0u8; 4]; p.w * p.h]; - p.render(&f, [0, 0, p.w, p.h], &mut out); - let full = apply_liquify(&src, &f); - let mut bad = 0; - for y in 0..64 { - for x in 0..96 { - let q = full.pixel(x, y); - let o = out[y as usize * 96 + x as usize]; - if (f32::from(o[1]) / 255.0 - q[1]).abs() > 0.1 { - bad += 1; - } - } - } - assert!(bad < 96 * 64 / 50, "{bad}"); - } -} +mod tests; diff --git a/crates/algo/src/liquify/tests.rs b/crates/algo/src/liquify/tests.rs new file mode 100644 index 0000000000..1cc360b2c3 --- /dev/null +++ b/crates/algo/src/liquify/tests.rs @@ -0,0 +1,532 @@ +use super::*; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; + +/// The segment walk before #937: every dab, whether or not it can reach the field. +fn full_walk(f: &mut LiquifyField, s: &LiquifyStroke, a: [f64; 3], b: [f64; 3]) -> Rect { + f.walk_segment(s, a, b, false) +} + +#[test] +fn a_segment_walks_only_the_dabs_that_can_reach_the_field() { + // #937: a segment to a far-off point walked one dab per spacing step along its whole + // length (~3e14 for 1e15 px). Skipping the dabs that can't reach a field node must leave + // every result bit-identical to the full walk. + use LiquifyTool::*; + let bounds = Rect::new(-7, 3, 89, 67); + let segments: [([f64; 3], [f64; 3]); 10] = [ + ([10.0, 20.0, 1.0], [70.0, 50.0, 0.5]), // inside + ([-900.0, 30.0, 1.0], [40.0, 31.0, 1.0]), // in from far left + ([40.0, 30.0, 1.0], [40.0, 4000.0, 0.2]), // out downwards + ([-500.0, -500.0, 1.0], [600.0, 600.0, 1.0]), // diagonal through + ([-300.0, -9.0, 1.0], [300.0, -9.0, 1.0]), // parallel, just above (the brush reaches) + ([-300.0, -400.0, 1.0], [300.0, -400.0, 1.0]), // parallel, far above (reaches nothing) + ([88.5, -50.0, 1.0], [88.5, 120.0, 1.0]), // vertical, along the right edge + ([200.0, 200.0, 1.0], [201.0, 900.0, 1.0]), // entirely outside + ([0.0, 0.0, 1.0], [0.25, 0.1, 1.0]), // shorter than one step + ([60.0, 40.0, 1.0], [-2000.0, 45.0, 1.0]), // continues the stroke before it, out left + ]; + for tool in [ForwardWarp, PushLeft, Reconstruct, Smooth, TwirlCw, TwirlCcw, Pucker, Bloat, Freeze, Thaw] { + for size in [6.0, 40.0] { + for (a, b) in segments { + let s = LiquifyStroke::new(tool, size); + let (mut fast, mut full) = (LiquifyField::new(bounds, 2.0), LiquifyField::new(bounds, 2.0)); + // Some displacement first, so Reconstruct and Smooth have something to undo. + for f in [&mut fast, &mut full] { + f.stroke_segment(&LiquifyStroke::new(ForwardWarp, 30.0), [20.0, 20.0, 1.0], [60.0, 40.0, 1.0]); + } + let dirty = fast.stroke_segment(&s, a, b); + assert_eq!(dirty, full_walk(&mut full, &s, a, b), "{tool:?} {size} {a:?} {b:?}"); + assert!(fast.d == full.d && fast.freeze == full.freeze, "{tool:?} {size} {a:?} {b:?}"); + } + } + } +} + +/// The same path sampled by `parts` pointer events per corner-to-corner leg, unevenly. +fn sampled(path: &[[f64; 3]], parts: usize) -> Vec> { + let mut out = vec![path[0].to_vec()]; + for w in path.windows(2) { + let (a, b) = (w[0], w[1]); + // Uneven steps, as a real pointer gives: t grows quadratically. + for k in 1..=parts { + let t = (k * k) as f64 / (parts * parts) as f64; + out.push((0..3).map(|i| a[i] + (b[i] - a[i]) * t).collect()); + } + } + out +} + +/// #2606: dabs restarted at every pointer event, so a fast mouse (few far-apart events) and a +/// slow one (many close ones) warped the same path differently. Spacing now runs on along the +/// whole stroke: any sampling of a path gives the same field. +#[test] +fn the_result_does_not_depend_on_how_finely_the_path_was_sampled() { + use LiquifyTool::*; + let path = [[20.0, 20.0, 1.0], [62.0, 26.0, 0.6], [70.0, 50.0, 0.9], [28.0, 55.0, 1.0], [30.0, 30.0, 1.0]]; + for tool in [ForwardWarp, PushLeft, TwirlCw, Bloat, Reconstruct, Smooth, Freeze] { + for size in [12.0, 40.0] { + let field = |parts: usize| { + let mut warp = LiquifyStroke::new(ForwardWarp, 30.0); + warp.points = vec![vec![30.0, 30.0], vec![50.0, 40.0]]; + let mut s = LiquifyStroke::new(tool, size); + s.points = sampled(&path, parts); + // Some displacement first, so Reconstruct and Smooth have something to change. + LiquifyField::from_strokes(bounds(), 2.0, &[warp, s]) + }; + let coarse = field(1); + for parts in [3, 17, 60] { + let fine = field(parts); + let dd = coarse.d.iter().zip(&fine.d).map(|(p, q)| (p[0] - q[0]).abs().max((p[1] - q[1]).abs())).fold(0.0f32, f32::max); + let df = coarse.freeze.iter().zip(&fine.freeze).map(|(p, q)| (p - q).abs()).fold(0.0f32, f32::max); + assert!(dd < 1e-3 && df < 1e-4, "{tool:?} {size}px, {parts} events per leg: field differs by {dd} px, mask by {df}"); + } + } + } +} + +/// A long drag whose events land exactly on dab positions, along a diagonal: rounding must not +/// add or drop the dab at a segment's end, or the deep displacement a long Forward Warp builds +/// up differs by a whole dab between a slow and a fast pointer. +#[test] +fn a_long_diagonal_drag_gives_one_field_at_any_event_spacing() { + let field = |step: f64| { + let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); + s.points = (0..=(300.0 / step) as usize).map(|k| vec![40.0 + k as f64 * step * 0.6, 20.0 + k as f64 * step * 0.8]).collect(); + LiquifyField::from_strokes(Rect::new(0, 0, 320, 300), 2.0, &[s]) + }; + let (slow, fast) = (field(2.0), field(60.0)); + let dd = slow.d.iter().zip(&fast.d).map(|(p, q)| (p[0] - q[0]).abs().max((p[1] - q[1]).abs())).fold(0.0f32, f32::max); + assert!(slow.max_displacement() > 50.0, "the drag builds up a deep displacement"); + assert!(dd < 1e-3, "slow and fast pointer fields differ by {dd} px"); +} + +#[test] +fn a_huge_canvas_gets_a_coarser_field_not_a_huge_one() { + // 400000² px at 2 px per node is 4·10¹⁰ nodes. + let f = LiquifyField::new(Rect::new(0, 0, 400_000, 400_000), 2.0); + assert!(f.w * f.h <= MAX_FIELD_NODES && f.d.len() == f.w * f.h && f.freeze.len() == f.d.len()); + assert!(f.cell > 64.0); + assert_eq!(LiquifyField::new(Rect::new(0, 0, 100, 100), 2.0).cell, 2.0); +} + +#[test] +fn a_stroke_interrupted_by_a_jump_restarts_its_spacing() { + // A segment that does not start where the last one ended begins a new run of dabs there. + let s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 20.0); + let mut f = LiquifyField::new(bounds(), 2.0); + f.stroke_begin(&s, [10.0, 10.0, 1.0]); + f.stroke_segment(&s, [10.0, 10.0, 1.0], [10.3, 10.0, 1.0]); + let mut g = LiquifyField::new(bounds(), 2.0); + f.stroke_segment(&s, [40.0, 30.0, 1.0], [50.0, 30.0, 1.0]); + g.stroke_begin(&s, [40.0, 30.0, 1.0]); + g.stroke_segment(&s, [40.0, 30.0, 1.0], [50.0, 30.0, 1.0]); + assert_eq!(f, g); + // Hostile points: nothing panics and the next segment starts afresh. + f.stroke_segment(&s, [f64::NAN, 3.0, 1.0], [4.0, f64::INFINITY, 1.0]); + f.stroke_segment(&s, [4.0, 3.0, f64::NAN], [9.0, 3.0, 1.0]); +} + +#[test] +fn a_segment_to_a_far_off_point_returns() { + // The issue's request: about 3.3e14 steps before the fix. Also a segment whose length + // overflows f64. + let mut f = LiquifyField::new(Rect::new(0, 0, 24, 16), 2.0); + let s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 30.0); + let dirty = f.stroke_segment(&s, [0.0, 0.0, 1.0], [1e15, 0.0, 1.0]); + assert!(!dirty.is_empty() && dirty.x1 <= 64, "{dirty:?}"); + f.stroke_segment(&s, [-1e308, 5.0, 1.0], [1e308, 5.0, 1.0]); + f.stroke_segment(&LiquifyStroke::new(LiquifyTool::Bloat, 30.0), [5.0, -1e15, 1.0], [5.0, 1e15, 1.0]); +} + +fn sample(st: SampleType) -> Surface { + let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, st, true)); + for y in 0..64 { + for x in 0..96 { + let v = ((x / 4 + y / 4) % 2) as f32; + s.write_pixel(x, y, &[v, (x as f32) / 96.0, (y as f32) / 64.0, 1.0]); + } + } + s +} + +fn bounds() -> Rect { + Rect::new(0, 0, 96, 64) +} + +fn worst(a: &Surface, b: &Surface, r: Rect) -> f32 { + a.read_region(r).iter().zip(b.read_region(r)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max) +} + +fn lasso(points: &[[f64; 2]], amount: Option) -> LiquifyStroke { + let mut s = LiquifyStroke::new(LiquifyTool::LassoMask, 1.0); + s.points = points.iter().map(|p| p.to_vec()).collect(); + s.amount = amount; + s +} + +/// Reference even-odd test (ray casting), to check the scanline fill against. +fn inside(p: [f64; 2], poly: &[[f64; 2]]) -> bool { + let mut inside = false; + let mut j = poly.len() - 1; + for (i, a) in poly.iter().enumerate() { + let b = poly[j]; + if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0] { + inside = !inside; + } + j = i; + } + inside +} + +#[test] +fn lasso_freezes_exactly_the_nodes_inside_a_concave_polygon() { + // A concave "C" with a notch, at a non-integer cell size. + let poly = [[10.0, 8.0], [70.0, 8.0], [70.0, 20.0], [30.0, 22.5], [33.0, 40.0], [80.0, 41.0], [60.0, 58.0], [9.0, 55.0]]; + for cell in [1.0, 2.0, 3.5] { + let mut f = LiquifyField::new(bounds(), cell); + let dirty = f.apply_stroke(&lasso(&poly, None)); + assert_eq!(dirty, Rect::new(9, 8, 80, 58)); + for j in 0..f.h { + for i in 0..f.w { + let want = if inside(f.node_pos(i, j), &poly) { 1.0 } else { 0.0 }; + assert_eq!(f.freeze[j * f.w + i], want, "cell {cell}: node ({i}, {j}) at {:?}", f.node_pos(i, j)); + } + } + assert!(f.freeze.contains(&1.0)); + // Strokes replay to the same field (undo rebuilds from the list). + assert_eq!(LiquifyField::from_strokes(bounds(), cell, &[lasso(&poly, None)]), f); + } +} + +#[test] +fn lasso_thaws_with_amount_zero() { + let mut f = LiquifyField::new(bounds(), 2.0); + f.apply_stroke(&LiquifyStroke::new(LiquifyTool::FreezeAll, 1.0)); + assert!(f.freeze.iter().all(|&v| v == 1.0)); + let square = [[20.0, 20.0], [40.0, 20.0], [40.0, 40.0], [20.0, 40.0]]; + f.apply_stroke(&lasso(&square, Some(0.0))); + assert_eq!(f.freeze_at(30.0, 30.0), 0.0, "thawed inside"); + assert_eq!(f.freeze_at(5.0, 5.0), 1.0, "still frozen outside"); +} + +#[test] +fn lasso_ignores_degenerate_and_hostile_polygons() { + let empty = LiquifyField::new(bounds(), 2.0); + let cases: [&[[f64; 2]]; 6] = [ + &[], + &[[10.0, 10.0], [50.0, 50.0]], + &[[f64::NAN, 10.0], [50.0, f64::INFINITY], [20.0, 30.0]], + // Entirely outside the canvas, on every side. + &[[-50.0, -50.0], [-10.0, -50.0], [-10.0, -10.0]], + &[[200.0, 10.0], [300.0, 10.0], [250.0, 50.0]], + &[[10.0, 1e12], [50.0, 1e12], [30.0, 2e12]], + ]; + for poly in cases { + let mut f = empty.clone(); + assert_eq!(f.apply_stroke(&lasso(poly, None)), Rect::EMPTY, "{poly:?}"); + assert_eq!(f, empty, "{poly:?}"); + } + // Huge coordinates around the canvas clamp to it instead of overflowing. + let mut f = empty.clone(); + f.apply_stroke(&lasso(&[[-1e15, -1e15], [1e15, -1e15], [1e15, 1e15], [-1e15, 1e15]], None)); + assert!(f.freeze.iter().all(|&v| v == 1.0)); + // A NaN point among good ones is skipped. + let mut f = empty.clone(); + f.apply_stroke(&lasso(&[[10.0, 10.0], [f64::NAN, 0.0], [50.0, 10.0], [50.0, 50.0], [10.0, 50.0]], None)); + assert_eq!(f.freeze_at(30.0, 30.0), 1.0); +} + +#[test] +fn the_brush_fades_to_nothing_at_its_rim_at_every_density() { + for density in [0.0, 0.25, 0.5, 0.75, 1.0, f64::NAN, -3.0, 7.0] { + assert_eq!(falloff(0.0, density), 1.0, "full strength at the centre ({density})"); + assert_eq!(falloff(1.0, density), 0.0, "nothing at the rim ({density})"); + // Flat at the rim: the last 2 % of the radius moves at most a couple of percent. + assert!(falloff(0.98f64.powi(2), density) < 0.02, "{density}: {}", falloff(0.98f64.powi(2), density)); + let mut prev = 1.0; + for k in 1..=100 { + let v = falloff(k as f64 / 100.0, density); + assert!(v <= prev && v >= 0.0, "{density}: not falling at t² = {k}%"); + prev = v; + } + } + // Density widens the strong core: more strength at every radius, as in Photoshop. + for k in 1..100 { + let t2 = k as f64 / 100.0; + assert!(falloff(t2, 1.0) >= falloff(t2, 0.5) && falloff(t2, 0.5) >= falloff(t2, 0.0), "t² = {t2}"); + } + assert!(falloff(0.5, 1.0) > 0.5 && falloff(0.5, 0.0) < 0.2); +} + +/// #2606: the dab's strength used to stop at 1 - Density at its rim, so a Forward Warp moved +/// everything just inside the brush and nothing just outside, tearing the image along every +/// dab's circle (a hard-edged block at Density 0, half strength at the default 50). +#[test] +fn forward_warp_leaves_the_brush_rim_in_place() { + // A drag of one dab spacing (a twentieth of the radius): one dab, centred where it started. + let (r, drag) = (20.0, 1.0); + for density in [0.0, 50.0, 100.0] { + let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 2.0 * r); + s.density = density; + s.points = vec![vec![48.0, 32.0], vec![48.0 + drag, 32.0]]; + let f = LiquifyField::from_strokes(bounds(), 1.0, &[s]); + let mut rim = 0; + for j in 0..f.h { + for i in 0..f.w { + let p = f.node_pos(i, j); + let t = (p[0] - 48.0).hypot(p[1] - 32.0) / r; + if (0.97..1.0).contains(&t) { + let d = f.d[j * f.w + i]; + assert!(f64::from(d[0].hypot(d[1])) < 0.03 * drag, "density {density}: a node at {t:.3} r moved {d:?}"); + rim += 1; + } + } + } + assert!(rim > 20, "{rim} rim nodes"); + assert!(f.sample(48.0, 32.0)[0] < -0.9 * drag, "density {density}: the centre follows the brush"); + } +} + +#[test] +fn a_wide_integer_translation_keeps_channels_and_tile_edges_at_every_format() { + let b = Rect::new(13, -1, 13 + 70 * 256, 1); + let w = b.width() as usize; + for mode in [ColorMode::Grayscale, ColorMode::Rgb, ColorMode::Cmyk] { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let format = PixelFormat::new(mode, depth, true); + let n = format.channels(); + let mut data = Vec::new(); + for i in 0..w * 2 { + let alpha = if i % 13 == 0 { 0.0 } else { 0.5 }; + for c in 0..mode.color_channels() { + data.push(if alpha == 0.0 { 0.0 } else { ((i * 19 + c * 43) % 251 + 2) as f32 / 255.0 }); + } + data.push(alpha); + } + let mut source = Surface::new(format); + source.write_region(b, &data); + source.write_pixel(b.x0 - 1, b.y0 - 1, &vec![0.75; n]); + let before = source.read_region(b); + let mut field = LiquifyField::new(b, 2.5); + field.d.fill([-1.0, 0.0]); + let output = apply_liquify(&source, &field); + let after = output.read_region(b); + let tolerance = if depth == SampleType::F32 { 4.0 * f32::EPSILON } else { 0.0 }; + for (original, moved) in before.chunks_exact(w * n).zip(after.chunks_exact(w * n)) { + for (x, pixel) in moved.chunks_exact(n).enumerate() { + let offset = x.saturating_sub(1) * n; + for (actual, expected) in pixel.iter().zip(&original[offset..offset + n]) { + assert!((actual - expected).abs() <= tolerance, "{mode:?}/{depth:?} at column {x}"); + } + } + } + assert_eq!(output.pixel(b.x0 - 1, b.y0 - 1), source.pixel(b.x0 - 1, b.y0 - 1)); + } + } +} + +#[test] +fn no_strokes_is_identity_at_every_depth() { + for st in [SampleType::U8, SampleType::U16, SampleType::F32] { + let s = sample(st); + let f = LiquifyField::new(bounds(), 2.0); + assert_eq!(apply_liquify(&s, &f), s); + // A field with exactly-zero strokes (zero pressure) is still identity. + let mut st0 = LiquifyStroke::new(LiquifyTool::ForwardWarp, 30.0); + st0.pressure = 0.0; + st0.points = vec![vec![40.0, 30.0], vec![60.0, 30.0]]; + let f = LiquifyField::from_strokes(bounds(), 2.0, &[st0]); + assert!(f.is_identity()); + } +} + +#[test] +fn full_resolution_preview_matches_the_unit_scale_proxy_and_partial_updates() { + let canvas = Rect::new(0, 0, 96, 64); + for sample_type in [SampleType::U8, SampleType::U16, SampleType::F32] { + let source = sample(sample_type); + let mut stroke = LiquifyStroke::new(LiquifyTool::ForwardWarp, 32.0); + stroke.points = vec![vec![38.0, 30.0, 1.0], vec![52.0, 34.0, 0.8]]; + let mut field = LiquifyField::from_strokes(canvas, 2.0, &[stroke]); + + let proxy = ProxyImage::new(&source, canvas, 96); + assert_eq!(proxy.scale, 1.0); + let mut want = vec![[0; 4]; proxy.w * proxy.h]; + proxy.render(&field, [0, 0, proxy.w, proxy.h], &mut want); + + let mut got = vec![[0; 4]; proxy.w * proxy.h]; + let mut scratch = Vec::new(); + assert!(ProxyImage::render_full_resolution(&source, &field, canvas, canvas, &mut got, &mut scratch)); + assert_eq!(got, want, "full-resolution render at {sample_type:?}"); + + let mut more = LiquifyStroke::new(LiquifyTool::Bloat, 16.0); + more.points = vec![vec![43.0, 32.0, 1.0]]; + let dirty = field.apply_stroke(&more); + proxy.render(&field, proxy.proxy_rect(dirty), &mut want); + assert!(ProxyImage::render_full_resolution(&source, &field, canvas, dirty, &mut got, &mut scratch)); + assert_eq!(got, want, "partial update at {sample_type:?}"); + } +} + +#[test] +fn forward_warp_displaces_along_the_stroke_and_reconstruct_restores() { + let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); + s.points = vec![vec![40.0, 32.0], vec![52.0, 32.0]]; + let mut f = LiquifyField::from_strokes(bounds(), 2.0, &[s]); + // Content moved right: the output at the end point samples from the left. + let d = f.sample(52.0, 32.0); + assert!(d[0] < -4.0 && d[1].abs() < 0.5, "{d:?}"); + // A pixel-level check: a marker column follows the stroke. + let mut img = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, true)); + img.fill_rect(bounds(), &[0.0, 1.0]); + img.fill_rect(Rect::new(40, 28, 42, 36), &[1.0, 1.0]); + let out = apply_liquify(&img, &f); + let brightest = (30..70).max_by(|a, b| out.pixel(*a, 32)[0].total_cmp(&out.pixel(*b, 32)[0])).unwrap(); + assert!(brightest > 44, "marker moved right: {brightest}"); + // Reconstruct All restores the original exactly. + let mut rec = LiquifyStroke::new(LiquifyTool::ReconstructAll, 10.0); + rec.amount = Some(100.0); + f.apply_stroke(&rec); + assert!(f.is_identity()); + assert_eq!(apply_liquify(&img, &f), img); +} + +#[test] +fn reconstruct_brush_reduces_the_field_and_freeze_protects() { + let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); + s.points = vec![vec![30.0, 32.0], vec![45.0, 32.0]]; + let mut f = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s)); + let before = f.max_displacement(); + let mut r = LiquifyStroke::new(LiquifyTool::Reconstruct, 80.0); + r.points = vec![vec![40.0, 32.0]; 30]; + f.apply_stroke(&r); + assert!(f.max_displacement() < before * 0.2, "{} vs {before}", f.max_displacement()); + // Frozen area doesn't move. + let mut fr = LiquifyStroke::new(LiquifyTool::Freeze, 60.0); + fr.density = 100.0; + fr.points = vec![vec![40.0, 32.0]]; + let mut g = LiquifyField::new(bounds(), 2.0); + g.apply_stroke(&fr); + assert!(g.freeze_at(40.0, 32.0) > 0.99); + g.apply_stroke(&s); + assert!(g.sample(40.0, 32.0)[0].abs() < 1e-3); + // Thaw unfreezes. + let mut th = fr.clone(); + th.tool = LiquifyTool::Thaw; + g.apply_stroke(&th); + assert!(g.freeze_at(40.0, 32.0) < 0.01); + // Mask All / Invert / None. + g.apply_stroke(&LiquifyStroke::new(LiquifyTool::FreezeAll, 1.0)); + assert!(g.freeze.iter().all(|f| *f == 1.0)); + g.apply_stroke(&LiquifyStroke::new(LiquifyTool::InvertFreeze, 1.0)); + assert!(g.freeze.iter().all(|f| *f == 0.0)); + g.apply_stroke(&fr); + g.apply_stroke(&LiquifyStroke::new(LiquifyTool::InvertFreeze, 1.0)); + assert!(g.freeze_at(40.0, 32.0) < 0.01 && g.freeze_at(5.0, 5.0) > 0.99); + g.apply_stroke(&LiquifyStroke::new(LiquifyTool::ThawAll, 1.0)); + assert!(g.freeze.iter().all(|f| *f == 0.0)); +} + +#[test] +fn fully_frozen_pixels_keep_their_mapping_when_an_adjacent_area_is_warped() { + let bounds = bounds(); + let mut src = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::F32, true)); + for y in 0..bounds.height() { + for x in 0..bounds.width() { + src.write_pixel(x as i32, y as i32, &[x as f32 / bounds.width() as f32, y as f32 / bounds.height() as f32, 0.0, 1.0]); + } + } + + let mut mask_only = LiquifyField::new(bounds, 2.0); + mask_only.apply_stroke(&lasso(&[[0.0, 0.0], [40.0, 0.0], [40.0, 64.0], [0.0, 64.0]], None)); + assert_eq!(apply_liquify(&src, &mask_only), src); + + let mut field = LiquifyField::new(bounds, 2.0); + let mut first_warp = LiquifyStroke::new(LiquifyTool::ForwardWarp, 40.0); + first_warp.points = vec![vec![22.0, 32.0], vec![34.0, 32.0]]; + field.apply_stroke(&first_warp); + + field.apply_stroke(&lasso(&[[0.0, 0.0], [40.0, 0.0], [40.0, 64.0], [0.0, 64.0]], None)); + let frozen_pixel = (37, 32); + assert!(field.freeze_at(f64::from(frozen_pixel.0) + 0.5, f64::from(frozen_pixel.1) + 0.5) > 0.999); + let before = apply_liquify(&src, &field).pixel(frozen_pixel.0, frozen_pixel.1); + assert_ne!(before, src.pixel(frozen_pixel.0, frozen_pixel.1), "freezing must retain the earlier warp"); + let neighbor_before = apply_liquify(&src, &field).pixel(43, 32); + + let mut adjacent_warp = LiquifyStroke::new(LiquifyTool::ForwardWarp, 24.0); + adjacent_warp.points = vec![vec![44.0, 32.0], vec![52.0, 32.0]]; + field.apply_stroke(&adjacent_warp); + + let after = apply_liquify(&src, &field).pixel(frozen_pixel.0, frozen_pixel.1); + let neighbor_after = apply_liquify(&src, &field).pixel(43, 32); + assert_eq!(before, after, "a fully frozen pixel must keep its pre-neighbor-warp mapping"); + assert_ne!(neighbor_before, neighbor_after, "an adjacent unfrozen pixel must still move"); +} + +#[test] +fn twirl_pucker_bloat_and_push_left_have_the_right_sense() { + let at = |tool: LiquifyTool, pts: Vec>| { + let mut s = LiquifyStroke::new(tool, 40.0); + s.points = pts; + LiquifyField::from_strokes(bounds(), 2.0, &[s]) + }; + let c = vec![vec![48.0, 32.0]; 10]; + // Pucker pulls content in: the output samples outward (d points away from the centre). + let f = at(LiquifyTool::Pucker, c.clone()); + assert!(f.sample(58.0, 32.0)[0] > 0.1); + let f = at(LiquifyTool::Bloat, c.clone()); + assert!(f.sample(58.0, 32.0)[0] < -0.1); + // Twirl clockwise (y down): content right of centre moves down, so it samples from above. + let f = at(LiquifyTool::TwirlCw, c.clone()); + assert!(f.sample(58.0, 32.0)[1] < -0.1, "{:?}", f.sample(58.0, 32.0)); + let f = at(LiquifyTool::TwirlCcw, c); + assert!(f.sample(58.0, 32.0)[1] > 0.1); + // Push Left while dragging up moves content left (samples from the right). + let f = at(LiquifyTool::PushLeft, vec![vec![48.0, 44.0], vec![48.0, 20.0]]); + assert!(f.sample(48.0, 32.0)[0] > 0.5, "{:?}", f.sample(48.0, 32.0)); + // Smooth reduces sharp field differences. + let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 12.0); + s.points = vec![vec![40.0, 32.0], vec![50.0, 32.0]]; + let mut g = LiquifyField::from_strokes(bounds(), 2.0, &[s]); + let m0 = g.max_displacement(); + let mut sm = LiquifyStroke::new(LiquifyTool::Smooth, 60.0); + sm.points = vec![vec![45.0, 32.0]; 20]; + g.apply_stroke(&sm); + assert!(g.max_displacement() < m0); +} + +#[test] +fn replay_is_deterministic_and_depths_agree() { + let mut s = LiquifyStroke::new(LiquifyTool::TwirlCw, 50.0); + s.points = vec![vec![48.0, 32.0, 0.5], vec![50.0, 33.0, 1.0], vec![52.0, 34.0]]; + let a = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s)); + let b = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&s)); + assert_eq!(a, b); + let r8 = apply_liquify(&sample(SampleType::U8), &a); + let r32 = apply_liquify(&sample(SampleType::F32), &a); + assert!(worst(&r8, &r32, bounds()) < 2.0 / 255.0 + 1e-4); +} + +#[test] +fn proxy_matches_the_full_render_roughly() { + let src = sample(SampleType::U8); + let mut s = LiquifyStroke::new(LiquifyTool::Bloat, 40.0); + s.points = vec![vec![48.0, 32.0]; 8]; + let f = LiquifyField::from_strokes(bounds(), 2.0, &[s]); + let p = ProxyImage::new(&src, bounds(), 96); + assert_eq!((p.w, p.h, p.scale), (96, 64, 1.0)); + let mut out = vec![[0u8; 4]; p.w * p.h]; + p.render(&f, [0, 0, p.w, p.h], &mut out); + let full = apply_liquify(&src, &f); + let mut bad = 0; + for y in 0..64 { + for x in 0..96 { + let q = full.pixel(x, y); + let o = out[y as usize * 96 + x as usize]; + if (f32::from(o[1]) / 255.0 - q[1]).abs() > 0.1 { + bad += 1; + } + } + } + assert!(bad < 96 * 64 / 50, "{bad}"); +} From 851ea2f1e578a6227d8fc0ccce089547ebcb9400 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:07 +0000 Subject: [PATCH 025/259] refactor(algo): move selection.rs tests to selection/tests.rs --- crates/algo/src/selection.rs | 666 +---------------------------- crates/algo/src/selection/tests.rs | 656 ++++++++++++++++++++++++++++ 2 files changed, 657 insertions(+), 665 deletions(-) create mode 100644 crates/algo/src/selection/tests.rs diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index 1e71a502c7..70e815b2b2 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -896,668 +896,4 @@ pub fn polygon(points: &[(f32, f32)], area: Rect, anti_alias: bool) -> Vec } #[cfg(test)] -mod tests { - use super::*; - - fn img(w: usize, h: usize, f: impl Fn(usize, usize) -> [f32; 4]) -> Vec<[f32; 4]> { - (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).map(|(x, y)| f(x, y)).collect() - } - - #[test] - fn wand_contiguous_vs_global() { - // Two separate red squares on white. - let px = img(20, 10, |x, _| if (2..6).contains(&x) || (12..16).contains(&x) { [1.0, 0.0, 0.0, 1.0] } else { [1.0; 4] }); - let a = Rect::new(0, 0, 20, 10); - let c = magic_wand(&px, a, (3, 3), 10.0, true, false); - assert_eq!(c.iter().filter(|v| **v > 0.0).count(), 40); - let g = magic_wand(&px, a, (3, 3), 10.0, false, false); - assert_eq!(g.iter().filter(|v| **v > 0.0).count(), 80); - let aa = magic_wand(&px, a, (3, 3), 10.0, true, true); - assert!(aa[3 * 20 + 6] > 0.0 && aa[3 * 20 + 6] < 1.0); - assert!(magic_wand(&px, a, (50, 3), 10.0, true, false).iter().all(|v| *v == 0.0)); - } - - #[test] - fn wand_tolerance() { - let px = img(10, 1, |x, _| [x as f32 * 10.0 / 255.0, 0.0, 0.0, 1.0]); - let m = magic_wand(&px, Rect::new(0, 0, 10, 1), (0, 0), 25.0, true, false); - assert_eq!(m.iter().filter(|v| **v > 0.0).count(), 3); - } - - #[test] - fn wand_ignores_hidden_rgb_only_when_both_pixels_are_fully_transparent() { - let area = Rect::new(0, 0, 6, 1); - let pixels = [[255, 0, 0, 0], [0, 255, 0, 0], [255, 0, 0, 128], [253, 0, 0, 128], [0, 0, 255, 0], [255, 0, 0, 255]]; - let floats: Vec<_> = pixels.iter().map(|p| p.map(|v| f32::from(v) / 255.0)).collect(); - for (seed, tolerance, contiguous, expected) in [ - ((0, 0), 0.0, true, [1.0, 1.0, 0.0, 0.0, 0.0, 0.0]), - ((0, 0), 0.0, false, [1.0, 1.0, 0.0, 0.0, 1.0, 0.0]), - ((4, 0), 32.0, false, [1.0, 1.0, 0.0, 0.0, 1.0, 0.0]), - ((2, 0), 0.0, false, [0.0, 0.0, 1.0, 0.0, 0.0, 0.0]), - ((2, 0), 2.0, true, [0.0, 0.0, 1.0, 1.0, 0.0, 0.0]), - ((5, 0), 32.0, false, [0.0, 0.0, 0.0, 0.0, 0.0, 1.0]), - ] { - assert_eq!(magic_wand(&floats, area, seed, tolerance, contiguous, false), expected); - let region = wand_region(&pixels, area, seed, tolerance, contiguous, false).unwrap(); - for (x, value) in expected.into_iter().enumerate() { - assert_eq!(region.at(x as i32, 0), value, "seed={seed:?}, tolerance={tolerance}, x={x}"); - } - } - // Hidden RGB cannot introduce extra edges into the anti-aliased selection either. - let plain: Vec<_> = pixels.iter().map(|p| if p[3] == 0 { [0; 4] } else { *p }).collect(); - for contiguous in [false, true] { - assert_eq!(wand_region(&pixels, area, (0, 0), 0.0, contiguous, true), wand_region(&plain, area, (0, 0), 0.0, contiguous, true)); - } - } - - #[test] - fn skin_tones_selects_skin_and_not_cream_or_white() { - let px = |rgb: [u8; 3]| [rgb[0], rgb[1], rgb[2]].map(|v| f32::from(v) / 255.0); - let rgba = |rgb: [u8; 3]| { - let [r, g, b] = px(rgb); - [r, g, b, 1.0] - }; - // Skin in light and shadow, then a cream shirt, a near-white wall, blue denim and black. - let skin = - [[183, 119, 81], [177, 132, 93], [180, 121, 84], [120, 76, 52], [173, 107, 75], [255, 219, 172], [194, 140, 104], [141, 85, 36], [92, 51, 23]] - .map(rgba); - let m = skin_tones(&skin, 40.0); - assert!(m.iter().all(|&v| v > 0.95), "skin {m:?}"); - let other = [[231, 225, 202], [252, 253, 247], [40, 60, 110], [5, 5, 5], [128, 128, 128], [220, 40, 40], [200, 160, 40]].map(rgba); - let m = skin_tones(&other, 40.0); - assert!(m.iter().all(|&v| v < 0.05), "not skin {m:?}"); - // Fuzziness widens the region; transparent pixels are never selected. - let pale = [rgba([230, 215, 200])]; - assert!(skin_tones(&pale, 200.0)[0] > skin_tones(&pale, 0.0)[0]); - assert_eq!(skin_tones(&[[0.7, 0.45, 0.3, 0.0]], 40.0), vec![0.0]); - } - - #[test] - fn color_range_falloff() { - let px = vec![[1.0, 0.0, 0.0, 1.0], [0.9, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 0.0]]; - let m = color_range(&px, [1.0, 0.0, 0.0], 40.0); - assert_eq!(m[0], 1.0); - assert!(m[1] > 0.3 && m[1] < 1.0); - assert_eq!(m[2], 0.0); - assert_eq!(m[3], 0.0); - } - - #[test] - fn color_range_several_samples_and_localized() { - let red = [1.0, 0.0, 0.0, 1.0]; - let blue = [0.0, 0.0, 1.0, 1.0]; - let green = [0.0, 1.0, 0.0, 1.0]; - // 4 × 1: red, blue, green, red. - let px = vec![red, blue, green, red]; - let s = |c: [f32; 4], at: Option<(f32, f32)>| RangeSample { color: [c[0], c[1], c[2]], at }; - let m = color_range_samples(&px, 4, &[s(red, None), s(blue, None)], 10.0, None); - assert_eq!(m, vec![1.0, 1.0, 0.0, 1.0]); - // One sample is exactly the single-colour Color Range. - assert_eq!(color_range_samples(&px, 4, &[s(red, None)], 40.0, None), color_range(&px, [1.0, 0.0, 0.0], 40.0)); - // Localized at x = 0 with a 2 px range: the far red pixel (x = 3) drops out, x = 1 would be half. - let m = color_range_samples(&px, 4, &[s(red, Some((0.0, 0.0)))], 10.0, Some(2.0)); - assert_eq!(m, vec![1.0, 0.0, 0.0, 0.0]); - let reds = vec![red; 4]; - let m = color_range_samples(&reds, 4, &[s(red, Some((0.0, 0.0)))], 10.0, Some(2.0)); - assert_eq!(m, vec![1.0, 0.5, 0.0, 0.0]); - // No samples: nothing selected. - assert!(color_range_samples(&px, 4, &[], 10.0, None).iter().all(|v| *v == 0.0)); - } - - /// Photoshop 2024's own Color Range coverage around the sample Lab (60, 25, 19.9961), read - /// from its selections on a 16-bit Lab document: (Lab in Photoshop's internal scale, where - /// a/b = (v16 − 32768)/256, fuzziness, coverage). - const PHOTOSHOP_COVERAGE: &[([f32; 3], f32, f32)] = &[ - ([61.9989, 25.5977, 20.5742], 40.0, 0.9686), - ([64.9989, 25.5977, 20.5742], 40.0, 0.7961), - ([67.9988, 25.5977, 20.5742], 40.0, 0.4824), - ([71.9997, 25.5977, 20.5742], 40.0, 0.1098), - ([79.9985, 25.5977, 20.5742], 40.0, 0.0), - ([71.9997, 25.5977, 20.5742], 100.0, 0.8118), - ([79.9985, 25.5977, 20.5742], 100.0, 0.4824), - ([60.0, 13.5508, 20.5742], 40.0, 0.0432), - ([60.0, 19.5742, 20.5742], 40.0, 0.6706), - ([60.0, 22.582, 20.5742], 40.0, 0.9333), - ([60.0, 28.6055, 20.5742], 40.0, 0.8549), - ([60.0, 31.6211, 20.5742], 40.0, 0.5098), - ([60.0, 37.6445, 20.5742], 40.0, 0.0078), - ([60.0, 13.5508, 20.5742], 100.0, 0.7647), - ([60.0, 37.6445, 20.5742], 100.0, 0.7137), - ([60.0, 25.5977, 10.5352], 40.0, 0.1725), - ([60.0, 25.5977, 16.5586], 40.0, 0.8667), - ([60.0, 25.5977, 24.5898], 40.0, 0.7647), - ([60.0, 25.5977, 30.6133], 40.0, 0.0863), - ([60.0, 25.5977, 10.5352], 100.0, 0.8392), - ([60.0, 25.5977, 30.6133], 100.0, 0.8), - ]; - - #[test] - fn lab_range_matches_photoshop() { - let r = LabRange::point([60.0, 25.0, 19.9961]); - for &(lab, fz, ps) in PHOTOSHOP_COVERAGE { - let got = lab_range_coverage(lab, &r, fz); - assert!((got - ps).abs() <= 2.0 / 255.0, "{lab:?} at fuzziness {fz}: {got} vs Photoshop {ps}"); - } - // Lightness is three times as forgiving as hue: the same 6-unit step along L and along a. - assert!(lab_range_coverage([66.0, 25.0, 20.0], &r, 40.0) > lab_range_coverage([60.0, 31.0, 20.0], &r, 40.0)); - // The sampled colour itself is always fully selected. - for fz in [1.0, 10.0, 40.0] { - assert_eq!(lab_range_coverage([60.0, 25.0, 19.9961], &r, fz), 1.0); - } - assert_eq!(quantize_lab8([60.1, 25.4, -19.6]), [(153.0f32 / 2.55), 25.0, -20.0]); - } - - #[test] - fn lab_range_box_and_edges() { - let r = LabRange::spanning(&[[50.0, 10.0, 0.0], [60.0, 20.0, 5.0]]).unwrap(); - assert_eq!(r, LabRange { lo: [50.0, 10.0, 0.0], hi: [60.0, 20.0, 5.0] }); - assert!(LabRange::spanning(&[]).is_none()); - // Everything inside the box is fully selected, whatever the fuzziness. - for fz in [1.0, 40.0, 200.0] { - assert_eq!(lab_range_coverage([55.0, 15.0, 2.0], &r, fz), 1.0); - } - // Coverage falls off outside it and is gone a fuzziness away. - let near = lab_range_coverage([55.0, 22.0, 2.0], &r, 40.0); - assert!(near > 0.0 && near < 1.0, "{near}"); - assert_eq!(lab_range_coverage([55.0, 40.0, 2.0], &r, 40.0), 0.0); - // Fuzziness 0: exact colours only. - let p = LabRange::point([50.0, 10.0, -5.0]); - assert_eq!(lab_range_coverage([50.0, 10.0, -5.0], &p, 0.0), 1.0); - assert_eq!(lab_range_coverage([50.0, 11.0, -5.0], &p, 0.0), 0.0); - // Hostile numbers never panic and never select. - for v in [f32::NAN, f32::INFINITY, -f32::INFINITY] { - for fz in [v, 40.0] { - let k = lab_range_coverage([v, 0.0, 0.0], &p, fz); - assert!((0.0..=1.0).contains(&k), "{k}"); - } - } - } - - /// Boxes Photoshop 2024's Color Range dialog returned after Subtract from Sample, at - /// fuzziness 40 unless noted: (lo, hi, subtracted value, fuzziness, new lo, new hi) on one axis. - const PHOTOSHOP_SUBTRACT_A: &[(f32, f32, f32, f32, f32, f32)] = &[ - (0.0, 20.0, 5.0, 40.0, 5.0, 20.0), - (0.0, 20.0, 10.0, 40.0, 0.0, 10.0), - (0.0, 20.0, 15.0, 40.0, 0.0, 15.0), - (0.0, 20.0, 0.0, 40.0, 2.68, 20.0), - (0.0, 20.0, -2.0, 40.0, 0.68, 20.0), - (0.0, 20.0, -3.0, 40.0, 2.36, 20.0), - (0.0, 20.0, -8.0, 40.0, 0.04, 20.0), - (0.0, 20.0, -11.0, 40.0, 2.4, 20.0), - (0.0, 20.0, -13.0, 40.0, 0.4, 20.0), - (0.0, 20.0, -14.0, 40.0, 0.0, 20.0), - (0.0, 20.0, 20.0, 40.0, 0.0, 17.32), - (0.0, 20.0, 23.0, 40.0, 0.0, 17.64), - (0.0, 20.0, 33.0, 40.0, 0.0, 19.6), - (0.0, 20.0, 0.0, 80.0, 5.35, 20.0), - (0.0, 20.0, -12.0, 80.0, 4.05, 20.0), - (0.0, 20.0, -22.0, 80.0, 4.76, 20.0), - (0.0, 20.0, -30.0, 80.0, 0.0, 20.0), - (0.0, 6.0, 4.0, 40.0, 0.0, 4.0), - (0.0, 2.0, 0.0, 40.0, 2.0, 2.0), - (0.0, 2.0, 3.0, 40.0, 0.0, 0.32), - ]; - - #[test] - fn subtract_reshapes_the_box_like_photoshop() { - for &(lo, hi, m, fz, want_lo, want_hi) in PHOTOSHOP_SUBTRACT_A { - let r = LabRange { lo: [50.0, lo, 0.0], hi: [50.0, hi, 0.0] }.subtract(&[50.0, m, 0.0], fz); - assert!( - (r.lo[1] - want_lo).abs() < 0.03 && (r.hi[1] - want_hi).abs() < 0.03, - "a [{lo}, {hi}] − {m} at {fz}: [{}, {}] vs Photoshop [{want_lo}, {want_hi}]", - r.lo[1], - r.hi[1] - ); - } - // Lightness (box 40–60, fuzziness 40): Photoshop gave 43.14, 41.17, 40.79 and 45.1. - for (m, want) in [(40.0, 43.14), (34.902, 41.17), (25.098, 40.79), (45.098, 45.1)] { - let r = LabRange { lo: [40.0, 0.0, 0.0], hi: [60.0, 0.0, 0.0] }.subtract(&[m, 0.0, 0.0], 40.0); - assert!((r.lo[0] - want).abs() < 0.05, "L − {m}: {} vs Photoshop {want}", r.lo[0]); - } - // All three axes at once (Photoshop: two samples, then one colour outside the box). - let r = LabRange { lo: [53.58, 0.0, 0.0], hi: [59.05, 30.56, 25.03] }.subtract(&[53.33, -28.71, 36.45], 40.0); - let want = LabRange { lo: [56.47, 0.0, 0.0], hi: [59.05, 30.56, 23.05] }; - for k in 0..3 { - assert!((r.lo[k] - want.lo[k]).abs() < 0.05 && (r.hi[k] - want.hi[k]).abs() < 0.05, "{r:?} vs {want:?}"); - } - // A single sample can't be subtracted from itself; hostile numbers change nothing. - let p = LabRange::point([50.0, 10.0, 10.0]); - assert_eq!(p.subtract(&[50.0, 10.0, 10.0], 40.0), p); - assert_eq!(p.subtract(&[f32::NAN, f32::INFINITY, -f32::INFINITY], f32::NAN), p); - assert_eq!(LabRange::spanning(&[[50.0, 0.0, 0.0]]).unwrap().grow(&[60.0, -5.0, 3.0]), LabRange { lo: [50.0, -5.0, 0.0], hi: [60.0, 0.0, 3.0] }); - } - - #[test] - fn eight_bit_grid_steps_are_uneven_like_photoshop() { - let r = LabRange::point([50.0, 10.0, -20.0]); - // The sampled colour itself is fully selected at any fuzziness. - for fz in [1.0, 5.0, 10.0, 40.0] { - assert_eq!(lab_range_coverage_8bit([50.0, 10.0, -20.0], &r, fz), 1.0); - } - // One step above on a counts as 1.5 units, one below as 0.5 (×3 weight): at fuzziness 40 - // (width 40.16) that is t = 4.5/40.16 and 1.5/40.16. - let up = lab_range_coverage_8bit([50.0, 11.0, -20.0], &r, 40.0); - let down = lab_range_coverage_8bit([50.0, 9.0, -20.0], &r, 40.0); - let p = |d: f32| (((1.0 - 2.0 * (d / (40.0 * 256.0 / 255.0)).powi(2)) * 256.0).floor().min(255.0)) / 255.0; - assert_eq!((up, down), (p(4.5), p(1.5))); - assert!(down > up); - // Lightness has no such offset; the exact (non-8-bit) coverage is symmetric. - assert_eq!(lab_range_coverage_8bit([51.0, 10.0, -20.0], &r, 40.0), lab_range_coverage_8bit([49.0, 10.0, -20.0], &r, 40.0)); - assert_eq!(lab_range_coverage([50.0, 11.0, -20.0], &r, 40.0), lab_range_coverage([50.0, 9.0, -20.0], &r, 40.0)); - let px = [[50.0, 11.0, -20.0, 1.0], [50.0, 9.0, -20.0, 1.0]]; - assert_eq!(color_range_lab(&px, 2, &r, 40.0, true, None), vec![up, down]); - } - - #[test] - fn color_range_lab_alpha_and_localized() { - let r = LabRange::point([50.0, 0.0, 0.0]); - let px = img(10, 1, |x, _| [50.0, 0.0, 0.0, if x == 0 { 0.0 } else { 1.0 }]); - let m = color_range_lab(&px, 10, &r, 40.0, false, None); - assert_eq!(m[0], 0.0, "transparent pixels are never selected"); - assert!(m[1..].iter().all(|v| *v > 0.9)); - let at = [(1.0, 0.0)]; - let l = color_range_lab(&px, 10, &r, 40.0, false, Some((4.0, &at))); - assert!(l[1] > l[3] && l[3] > 0.0 && l[6] == 0.0, "{l:?}"); - // No positions: localized clusters have nothing to centre on and change nothing. - assert_eq!(color_range_lab(&px, 10, &r, 40.0, false, Some((4.0, &[]))), m); - assert!(color_range_lab(&[], 0, &r, 40.0, false, None).is_empty()); - } - - #[test] - fn hue_families() { - let px = vec![ - [1.0, 0.0, 0.0, 1.0], // red - [1.0, 0.5, 0.0, 1.0], // orange: between red and yellow - [0.5, 0.5, 0.5, 1.0], // grey - [1.0, 0.5, 0.5, 1.0], // pink: a muted red - [0.0, 0.0, 1.0, 1.0], // blue - [1.0, 0.0, 0.0, 0.0], // transparent - ]; - let reds = hue_range(&px, 0.0); - assert_eq!(reds[0], 1.0); - assert!((reds[1] - 0.5).abs() < 1e-5); - assert_eq!(reds[2], 0.0); - assert!((reds[3] - 0.5).abs() < 1e-5); - assert_eq!(reds[4], 0.0); - assert_eq!(reds[5], 0.0); - let yellows = hue_range(&px, 60.0); - assert!((yellows[1] - 0.5).abs() < 1e-5); - assert_eq!(hue_range(&px, 240.0)[4], 1.0); - // Magentas wrap around 360°. - assert_eq!(hue_range(&[[1.0, 0.0, 1.0, 1.0]], 300.0)[0], 1.0); - assert!((hue_range(&[[1.0, 0.0, 0.5, 1.0]], 300.0)[0] - 0.5).abs() < 1e-5); - } - - #[test] - fn hue_families_weigh_dark_colours_like_photoshop() { - // Photoshop 2025's Blues on an 8-bit sRGB document (selection levels 0..255, #5243): the - // muted navy #3d3f54, a dark blue (0, 0, 84) and a mid blue (61, 61, 153). - let c = |r: u8, g: u8, b: u8| [f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0, 1.0]; - let blues = hue_range(&[c(0x3d, 0x3f, 0x54), c(0, 0, 84), c(61, 61, 153)], 240.0); - for (got, want) in blues.iter().zip([35.0, 140.0, 129.0]) { - assert!((got * 255.0 - want).abs() <= 1.0, "{} vs Photoshop {want}", got * 255.0); - } - } - - #[test] - fn tonal_ranges() { - let g = |v: f32| [v / 255.0, v / 255.0, v / 255.0, 1.0]; - let px = vec![g(0.0), g(60.0), g(75.0), g(128.0), g(200.0), g(255.0)]; - let near = |a: &[f32], b: &[f32]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4); - // Shadows up to 65, fading over 20 levels. - let sh = tone_range(&px, 0.0, 65.0, 20.0); - assert!(near(&sh, &[1.0, 1.0, 0.5, 0.0, 0.0, 0.0]), "{sh:?}"); - // Highlights from 190. - let h = tone_range(&px, 190.0, 255.0, 20.0); - assert!(near(&h, &[0.0, 0.0, 0.0, 0.0, 1.0, 1.0]), "{h:?}"); - // Midtones 105..150. - let m = tone_range(&px, 105.0, 150.0, 20.0); - assert!(near(&m, &[0.0, 0.0, 0.0, 1.0, 0.0, 0.0]), "{m:?}"); - } - - fn square(w: usize, h: usize) -> Vec { - (0..w * h).map(|i| if (5..15).contains(&(i % w)) && (5..15).contains(&(i / w)) { 1.0 } else { 0.0 }).collect() - } - - #[test] - fn expand_contract_border() { - let m = square(20, 20); - let e = expand(&m, 20, 20, 2.0); - assert_eq!(e[10 * 20 + 3], 1.0); - assert_eq!(e[10 * 20 + 2], 0.0); - let c = contract(&m, 20, 20, 2.0); - assert_eq!(c[10 * 20 + 6], 0.0); - assert_eq!(c[10 * 20 + 7], 1.0); - let b = border(&m, 20, 20, 4.0); - assert_eq!(b[10 * 20 + 10], 0.0); - assert!(b[10 * 20 + 5] > 0.5 && b[10 * 20 + 4] > 0.5); - } - - /// Photoshop 27.11, measured: a 32×32 rectangle at (16,16) in 64×64, Select › Modify › - /// Border 4 px, filled white. Row y = 32 for x = 8..=24, and the diagonal (16,16)..(24,24). - #[test] - fn border_matches_photoshop() { - let (w, h) = (64, 64); - let m: Vec = (0..w * h).map(|i| if (16..48).contains(&(i % w)) && (16..48).contains(&(i / w)) { 1.0 } else { 0.0 }).collect(); - let b = border(&m, w, h, 4.0); - let v = |x: usize, y: usize| (b[y * w + x] * 255.0).round() as i32; - let row: Vec = (8..=24).map(|x| v(x, 32)).collect(); - let diag: Vec = (16..=24).map(|d| v(d, d)).collect(); - let near = |got: &[i32], want: &[i32]| got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1); - let want_row = [0, 0, 0, 0, 63, 127, 191, 255, 255, 191, 127, 63, 0, 0, 0, 0, 0]; - assert!(near(&row, &want_row), "{row:?}"); - assert!(near(&diag, &[255, 191, 127, 63, 0, 0, 0, 0, 0]), "{diag:?}"); - } - - #[test] - fn smooth_removes_specks_and_feather_softens() { - let mut m = square(20, 20); - m[2 * 20 + 2] = 1.0; - let s = smooth(&m, 20, 20, 1.0); - assert_eq!(s[2 * 20 + 2], 0.0); - assert_eq!(s[10 * 20 + 10], 1.0); - // Radius 2 (σ 2) keeps the blur inside the 20×20 canvas, so no coverage is lost. - let f = feather(&square(20, 20), 20, 20, 2.0); - let edge = f[10 * 20 + 5]; - assert!(edge > 0.3 && edge < 0.8, "{edge}"); - let sum: f32 = f.iter().sum(); - assert!((sum - 100.0).abs() < 1.0); - } - - #[test] - fn polygon_area_and_aa() { - let a = Rect::new(0, 0, 20, 20); - let sq = polygon(&[(2.0, 2.0), (12.0, 2.0), (12.0, 12.0), (2.0, 12.0)], a, true); - let area: f32 = sq.iter().sum(); - assert!((area - 100.0).abs() < 1e-3, "{area}"); - let tri = polygon(&[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)], a, true); - let area: f32 = tri.iter().sum(); - assert!((area - 50.0).abs() < 1.0, "{area}"); - assert!(tri.iter().any(|v| *v > 0.0 && *v < 1.0)); - let hard = polygon(&[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)], a, false); - assert!(hard.iter().all(|v| *v == 0.0 || *v == 1.0)); - assert!(polygon(&[(0.0, 0.0), (1.0, 1.0)], a, true).iter().all(|v| *v == 0.0)); - } - - /// The previous polygon fill (every edge tested on every sub-row), kept as the oracle. - fn old_polygon(points: &[(f32, f32)], area: Rect, anti_alias: bool) -> Vec { - let (w, h) = (area.width() as usize, area.height() as usize); - let mut m = vec![0.0f32; w * h]; - if points.len() < 3 { - return m; - } - let sub = if anti_alias { 4 } else { 1 }; - let mut xs: Vec = Vec::new(); - for py in 0..h { - for s in 0..sub { - let y = area.y0 as f32 + py as f32 + (s as f32 + 0.5) / sub as f32; - xs.clear(); - for i in 0..points.len() { - let (a, b) = (points[i], points[(i + 1) % points.len()]); - if (a.1 <= y && b.1 > y) || (b.1 <= y && a.1 > y) { - xs.push(a.0 + (y - a.1) / (b.1 - a.1) * (b.0 - a.0)); - } - } - xs.sort_by(|a, b| a.total_cmp(b)); - for span in xs.as_chunks::<2>().0 { - let (x0, x1) = ((span[0] - area.x0 as f32).max(0.0), (span[1] - area.x0 as f32).min(w as f32)); - if x1 <= x0 { - continue; - } - let (c0, c1) = (x0.floor() as usize, (x1.ceil() as usize).min(w)); - for cx in c0..c1 { - let cov = if anti_alias { - ((cx + 1) as f32).min(x1) - (cx as f32).max(x0) - } else { - let c = cx as f32 + 0.5; - if c >= x0 && c < x1 { 1.0 } else { 0.0 } - }; - m[py * w + cx] += cov.max(0.0) / sub as f32; - } - } - } - } - for v in &mut m { - *v = v.min(1.0); - } - m - } - - #[test] - fn polygon_matches_the_every_edge_fill_bit_for_bit() { - let mut seed = 0x2545_f491_u32; - let mut rnd = move || { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - seed as f32 / u32::MAX as f32 - }; - // Taller than one 64-row band, offset, and a 1-pixel-wide area. - let areas = [Rect::new(0, 0, 90, 150), Rect::new(-13, 7, 60, 211), Rect::new(5, -40, 6, 30)]; - let mut cases: Vec> = vec![ - // Self-intersecting star, horizontal edges, repeated points, collinear runs. - (0..11) - .map(|i| { - let t = i as f32 * 4.0 * std::f32::consts::PI / 11.0; - (40.0 + 35.0 * t.cos(), 80.0 + 70.0 * t.sin()) - }) - .collect(), - vec![(10.0, 10.0), (50.0, 10.0), (50.0, 10.0), (50.0, 60.0), (30.0, 60.0), (30.0, 30.0), (10.0, 30.0)], - vec![(0.0, 0.0), (20.0, 0.0), (40.0, 0.0), (40.0, 0.0), (0.0, 0.0)], - // Vertices on the sub-row centres and the pixel edges. - vec![(3.125, 2.375), (70.5, 2.375), (70.875, 140.625), (3.0, 140.0), (35.0, 64.0), (35.0, 64.125)], - // Entirely outside, and straddling every side. - vec![(-500.0, -500.0), (-400.0, -500.0), (-450.0, -300.0)], - vec![(-80.0, -60.0), (300.0, 20.0), (60.0, 400.0)], - // Non-finite coordinates and a negative zero. - vec![(10.0, 10.0), (f32::NAN, 40.0), (60.0, 70.0), (20.0, f32::INFINITY), (-0.0, -0.0), (0.0, 0.0)], - ]; - for n in [3, 7, 40, 400] { - for spread in [1.0, 2.0] { - cases.push((0..n).map(|_| (rnd() * 100.0 * spread - 50.0 * (spread - 1.0), rnd() * 220.0 * spread - 60.0 * spread)).collect()); - // Lasso-like: a random walk snapped to quarter pixels. - let (mut x, mut y) = (45.0f32, 75.0f32); - cases.push( - (0..n) - .map(|_| { - x = ((x + (rnd() - 0.5) * 12.0 * spread) * 4.0).round() / 4.0; - y = ((y + (rnd() - 0.5) * 12.0 * spread) * 4.0).round() / 4.0; - (x, y) - }) - .collect(), - ); - } - } - for pts in &cases { - for &area in &areas { - for aa in [true, false] { - let (new, old) = (polygon(pts, area, aa), old_polygon(pts, area, aa)); - assert_eq!(new.len(), old.len()); - let diff = new.iter().zip(&old).position(|(a, b)| a.to_bits() != b.to_bits()); - assert!(diff.is_none(), "{pts:?} {area:?} aa={aa}: first difference at {diff:?}"); - } - } - } - } - - #[test] - fn combine_modes() { - let a = Rect::new(0, 0, 4, 1); - let old = mask_to_surface(&[1.0, 1.0, 0.0, 0.0], a); - let new = [0.0, 1.0, 1.0, 0.0]; - let v = |s: Option| mask_from_surface(s.as_ref(), a); - assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Replace)), vec![0.0, 1.0, 1.0, 0.0]); - assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Add)), vec![1.0, 1.0, 1.0, 0.0]); - assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Subtract)), vec![1.0, 0.0, 0.0, 0.0]); - assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Intersect)), vec![0.0, 1.0, 0.0, 0.0]); - assert!(combine(Some(&old), &[1.0; 4], a, SelectionMode::Subtract).is_none()); - assert_eq!(SelectionMode::parse("add"), SelectionMode::Add); - } - - /// The previous (per-sample) conversions, kept as the oracle for the tiled fast paths. - fn old_mask_to_surface(m: &[f32], area: Rect) -> Surface { - let mut s = Surface::new(PixelFormat::GRAY8); - if !area.is_empty() { - s.write_region(area, m); - } - s.prune(); - s - } - - fn old_combine(old: Option<&Surface>, new: &[f32], area: Rect, mode: SelectionMode) -> Option { - let mut prev = Vec::new(); - match old { - Some(s) => s.read_region_into(area, &mut prev), - None => prev = vec![0.0; new.len()], - } - let q: Vec = new.iter().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0).collect(); - let out: Vec = match mode { - SelectionMode::Replace => q, - SelectionMode::Add => prev.iter().zip(&q).map(|(a, b)| a.max(*b)).collect(), - SelectionMode::Subtract => prev.iter().zip(&q).map(|(a, b)| (a - b).max(0.0)).collect(), - SelectionMode::Intersect => prev.iter().zip(&q).map(|(a, b)| a.min(*b)).collect(), - }; - let out: Vec = out.into_iter().map(|v| if v < 0.5 / 255.0 { 0.0 } else { v }).collect(); - if out.iter().all(|v| *v <= 0.0) { - return None; - } - Some(old_mask_to_surface(&out, area)) - } - - #[test] - fn tiled_conversions_match_per_sample_ones() { - let mut rng = crate::photo_util::Rng(7); - let mut u = move || (rng.next() >> 11) as f32 / (1u64 << 53) as f32; - // Off-grid areas spanning several tiles, including negative origins. - // The last one holds whole tiles, which fully selected masks fill (shared tiles). - for area in - [Rect::new(0, 0, 300, 20), Rect::new(-37, 250, 530, 263), Rect::new(255, -3, 258, 600), Rect::new(5, 5, 6, 6), Rect::new(-37, -300, 530, 263)] - { - let n = area.width() as usize * area.height() as usize; - let old_m: Vec = (0..n).map(|i| if i % 97 < 40 { u() } else { 0.0 }).collect(); - let old = old_mask_to_surface(&old_m, area); - let fast = mask_to_surface(&old_m, area); - assert_eq!(fast, old, "{area:?}"); - let mut slow_read = Vec::new(); - old.read_region_into(area, &mut slow_read); - assert_eq!(mask_from_surface(Some(&old), area), slow_read); - for kind in 0..4 { - let new: Vec = (0..n) - .map(|i| match kind { - 0 => u() * 1.2 - 0.1, - 1 => { - if i % 131 < 50 { - 1.0 - } else { - 0.0 - } - } - 2 => 0.001, - _ => f32::from(u8::from(i >= 1000)), - }) - .collect(); - for mode in [SelectionMode::Replace, SelectionMode::Add, SelectionMode::Subtract, SelectionMode::Intersect] { - for prev in [None, Some(&old)] { - assert_eq!(combine(prev, &new, area, mode), old_combine(prev, &new, area, mode), "{area:?} {kind} {mode:?}"); - } - } - } - } - // A short mask buffer reads as zeros instead of panicking. - let a = Rect::new(0, 0, 10, 10); - assert!(combine(None, &[1.0; 5], a, SelectionMode::Replace).is_some()); - assert_eq!(mask_to_surface(&[], a).tile_count(), 0); - assert!(combine(None, &[], Rect::EMPTY, SelectionMode::Replace).is_none()); - } - - fn blobs(w: i32, h: i32) -> Vec<[u8; 4]> { - // Deterministic blotchy image with gradients and hard edges. - (0..w * h) - .map(|i| { - let (x, y) = (i % w, i / w); - let v = ((x * 7 + y * 3) % 23 + if (x / 5 + y / 4) % 3 == 0 { 120 } else { 0 }) as u8; - [v, v / 2, 255 - v, if x % 11 == 0 { 128 } else { 255 }] - }) - .collect() - } - - #[test] - fn magic_wand_rejects_incomplete_and_overflowing_pixel_inputs() { - let area = Rect::new(0, 0, 4, 4); - let short = vec![[255u8, 0, 0, 255]; 4]; - let floats: Vec<[f32; 4]> = short.iter().map(|p| p.map(|v| f32::from(v) / 255.0)).collect(); - assert_eq!(magic_wand(&floats, area, (1, 1), 0.0, true, false), Vec::::new()); - assert_eq!(wand_region(&short, area, (1, 1), 0.0, true, false), None); - - let huge = Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX); - assert!(magic_wand(&floats, huge, (0, 0), 0.0, false, false).is_empty()); - assert_eq!(wand_region(&short, huge, (0, 0), 0.0, false, false), None); - - let valid = Rect::new(0, 0, 2, 2); - assert_eq!(magic_wand(&floats, valid, (0, 0), 0.0, false, false), vec![1.0; 4]); - assert!(wand_region(&short, valid, (0, 0), 0.0, false, false).is_some()); - } - - #[test] - fn region_coverage_outside_a_short_mask_is_zero() { - let region = Region { bbox: Rect::new(-2, -3, 1, -1), mask: vec![255, 128] }; - assert_eq!(region.at(-2, -3), 1.0); - assert!((region.at(-1, -3) - 128.0 / 255.0).abs() < 1e-6); - assert_eq!(region.at(0, -3), 0.0); - assert_eq!(region.at(-2, -2), 0.0); - assert_eq!(region.at(-3, -3), 0.0); - - let extreme = Region { bbox: Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX), mask: vec![] }; - assert_eq!(extreme.at(i32::MAX - 1, i32::MAX - 1), 0.0); - assert_eq!(extreme.at(i32::MIN, i32::MIN), 0.0); - } - - #[test] - fn wand_region_matches_reference_magic_wand() { - let (w, h) = (37, 29); - let area = Rect::new(3, -2, 3 + w, -2 + h); - let img = blobs(w, h); - let f: Vec<[f32; 4]> = img.iter().map(|p| p.map(|v| v as f32 / 255.0)).collect(); - for (seed, tol, contiguous, aa) in [ - ((10, 5), 10.0, true, true), - ((10, 5), 10.0, true, false), - ((20, 20), 40.0, false, true), - ((4, -2), 0.0, true, true), - ((30, 10), 255.0, true, true), - ] { - let reference = magic_wand(&f, area, seed, tol, contiguous, aa); - let r = wand_region(&img, area, seed, tol, contiguous, aa).unwrap(); - for y in area.y0..area.y1 { - for x in area.x0..area.x1 { - let want = (reference[((y - area.y0) * w + x - area.x0) as usize] * 255.0).round(); - assert!((r.at(x, y) * 255.0 - want).abs() <= 1.0, "{seed:?} {tol} {contiguous} {aa} at {x},{y}: {} vs {want}", r.at(x, y) * 255.0); - } - } - } - assert!(wand_region(&img, area, (0, 0), 10.0, true, true).is_none()); - } - - #[test] - fn combine_region_matches_combine() { - let area = Rect::new(0, 0, 40, 30); - let mut old = Surface::new(PixelFormat::GRAY8); - old.fill_rect(Rect::new(5, 5, 25, 20), &[1.0]); - old.fill_rect(Rect::new(8, 8, 10, 10), &[0.4]); - let img = blobs(40, 30); - let region = wand_region(&img, area, (12, 12), 30.0, true, true).unwrap(); - let full: Vec = (0..area.height()).flat_map(|y| (0..area.width()).map(move |x| (x, y))).map(|(x, y)| region.at(x as i32, y as i32)).collect(); - for mode in [SelectionMode::Replace, SelectionMode::Add, SelectionMode::Subtract, SelectionMode::Intersect] { - let a = combine(Some(&old), &full, area, mode); - let b = combine_region(Some(&old), Some(®ion), mode); - assert_eq!(a.is_some(), b.is_some(), "{mode:?}"); - if let (Some(a), Some(b)) = (a, b) { - for y in 0..30 { - for x in 0..40 { - assert!((a.pixel(x, y)[0] - b.pixel(x, y)[0]).abs() < 1.5 / 255.0, "{mode:?} {x},{y}"); - } - } - } - } - assert!(combine_region(None, None, SelectionMode::Subtract).is_none()); - } -} +mod tests; diff --git a/crates/algo/src/selection/tests.rs b/crates/algo/src/selection/tests.rs new file mode 100644 index 0000000000..368633f03a --- /dev/null +++ b/crates/algo/src/selection/tests.rs @@ -0,0 +1,656 @@ +use super::*; + +fn img(w: usize, h: usize, f: impl Fn(usize, usize) -> [f32; 4]) -> Vec<[f32; 4]> { + (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).map(|(x, y)| f(x, y)).collect() +} + +#[test] +fn wand_contiguous_vs_global() { + // Two separate red squares on white. + let px = img(20, 10, |x, _| if (2..6).contains(&x) || (12..16).contains(&x) { [1.0, 0.0, 0.0, 1.0] } else { [1.0; 4] }); + let a = Rect::new(0, 0, 20, 10); + let c = magic_wand(&px, a, (3, 3), 10.0, true, false); + assert_eq!(c.iter().filter(|v| **v > 0.0).count(), 40); + let g = magic_wand(&px, a, (3, 3), 10.0, false, false); + assert_eq!(g.iter().filter(|v| **v > 0.0).count(), 80); + let aa = magic_wand(&px, a, (3, 3), 10.0, true, true); + assert!(aa[3 * 20 + 6] > 0.0 && aa[3 * 20 + 6] < 1.0); + assert!(magic_wand(&px, a, (50, 3), 10.0, true, false).iter().all(|v| *v == 0.0)); +} + +#[test] +fn wand_tolerance() { + let px = img(10, 1, |x, _| [x as f32 * 10.0 / 255.0, 0.0, 0.0, 1.0]); + let m = magic_wand(&px, Rect::new(0, 0, 10, 1), (0, 0), 25.0, true, false); + assert_eq!(m.iter().filter(|v| **v > 0.0).count(), 3); +} + +#[test] +fn wand_ignores_hidden_rgb_only_when_both_pixels_are_fully_transparent() { + let area = Rect::new(0, 0, 6, 1); + let pixels = [[255, 0, 0, 0], [0, 255, 0, 0], [255, 0, 0, 128], [253, 0, 0, 128], [0, 0, 255, 0], [255, 0, 0, 255]]; + let floats: Vec<_> = pixels.iter().map(|p| p.map(|v| f32::from(v) / 255.0)).collect(); + for (seed, tolerance, contiguous, expected) in [ + ((0, 0), 0.0, true, [1.0, 1.0, 0.0, 0.0, 0.0, 0.0]), + ((0, 0), 0.0, false, [1.0, 1.0, 0.0, 0.0, 1.0, 0.0]), + ((4, 0), 32.0, false, [1.0, 1.0, 0.0, 0.0, 1.0, 0.0]), + ((2, 0), 0.0, false, [0.0, 0.0, 1.0, 0.0, 0.0, 0.0]), + ((2, 0), 2.0, true, [0.0, 0.0, 1.0, 1.0, 0.0, 0.0]), + ((5, 0), 32.0, false, [0.0, 0.0, 0.0, 0.0, 0.0, 1.0]), + ] { + assert_eq!(magic_wand(&floats, area, seed, tolerance, contiguous, false), expected); + let region = wand_region(&pixels, area, seed, tolerance, contiguous, false).unwrap(); + for (x, value) in expected.into_iter().enumerate() { + assert_eq!(region.at(x as i32, 0), value, "seed={seed:?}, tolerance={tolerance}, x={x}"); + } + } + // Hidden RGB cannot introduce extra edges into the anti-aliased selection either. + let plain: Vec<_> = pixels.iter().map(|p| if p[3] == 0 { [0; 4] } else { *p }).collect(); + for contiguous in [false, true] { + assert_eq!(wand_region(&pixels, area, (0, 0), 0.0, contiguous, true), wand_region(&plain, area, (0, 0), 0.0, contiguous, true)); + } +} + +#[test] +fn skin_tones_selects_skin_and_not_cream_or_white() { + let px = |rgb: [u8; 3]| [rgb[0], rgb[1], rgb[2]].map(|v| f32::from(v) / 255.0); + let rgba = |rgb: [u8; 3]| { + let [r, g, b] = px(rgb); + [r, g, b, 1.0] + }; + // Skin in light and shadow, then a cream shirt, a near-white wall, blue denim and black. + let skin = [[183, 119, 81], [177, 132, 93], [180, 121, 84], [120, 76, 52], [173, 107, 75], [255, 219, 172], [194, 140, 104], [141, 85, 36], [92, 51, 23]] + .map(rgba); + let m = skin_tones(&skin, 40.0); + assert!(m.iter().all(|&v| v > 0.95), "skin {m:?}"); + let other = [[231, 225, 202], [252, 253, 247], [40, 60, 110], [5, 5, 5], [128, 128, 128], [220, 40, 40], [200, 160, 40]].map(rgba); + let m = skin_tones(&other, 40.0); + assert!(m.iter().all(|&v| v < 0.05), "not skin {m:?}"); + // Fuzziness widens the region; transparent pixels are never selected. + let pale = [rgba([230, 215, 200])]; + assert!(skin_tones(&pale, 200.0)[0] > skin_tones(&pale, 0.0)[0]); + assert_eq!(skin_tones(&[[0.7, 0.45, 0.3, 0.0]], 40.0), vec![0.0]); +} + +#[test] +fn color_range_falloff() { + let px = vec![[1.0, 0.0, 0.0, 1.0], [0.9, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 0.0]]; + let m = color_range(&px, [1.0, 0.0, 0.0], 40.0); + assert_eq!(m[0], 1.0); + assert!(m[1] > 0.3 && m[1] < 1.0); + assert_eq!(m[2], 0.0); + assert_eq!(m[3], 0.0); +} + +#[test] +fn color_range_several_samples_and_localized() { + let red = [1.0, 0.0, 0.0, 1.0]; + let blue = [0.0, 0.0, 1.0, 1.0]; + let green = [0.0, 1.0, 0.0, 1.0]; + // 4 × 1: red, blue, green, red. + let px = vec![red, blue, green, red]; + let s = |c: [f32; 4], at: Option<(f32, f32)>| RangeSample { color: [c[0], c[1], c[2]], at }; + let m = color_range_samples(&px, 4, &[s(red, None), s(blue, None)], 10.0, None); + assert_eq!(m, vec![1.0, 1.0, 0.0, 1.0]); + // One sample is exactly the single-colour Color Range. + assert_eq!(color_range_samples(&px, 4, &[s(red, None)], 40.0, None), color_range(&px, [1.0, 0.0, 0.0], 40.0)); + // Localized at x = 0 with a 2 px range: the far red pixel (x = 3) drops out, x = 1 would be half. + let m = color_range_samples(&px, 4, &[s(red, Some((0.0, 0.0)))], 10.0, Some(2.0)); + assert_eq!(m, vec![1.0, 0.0, 0.0, 0.0]); + let reds = vec![red; 4]; + let m = color_range_samples(&reds, 4, &[s(red, Some((0.0, 0.0)))], 10.0, Some(2.0)); + assert_eq!(m, vec![1.0, 0.5, 0.0, 0.0]); + // No samples: nothing selected. + assert!(color_range_samples(&px, 4, &[], 10.0, None).iter().all(|v| *v == 0.0)); +} + +/// Photoshop 2024's own Color Range coverage around the sample Lab (60, 25, 19.9961), read +/// from its selections on a 16-bit Lab document: (Lab in Photoshop's internal scale, where +/// a/b = (v16 − 32768)/256, fuzziness, coverage). +const PHOTOSHOP_COVERAGE: &[([f32; 3], f32, f32)] = &[ + ([61.9989, 25.5977, 20.5742], 40.0, 0.9686), + ([64.9989, 25.5977, 20.5742], 40.0, 0.7961), + ([67.9988, 25.5977, 20.5742], 40.0, 0.4824), + ([71.9997, 25.5977, 20.5742], 40.0, 0.1098), + ([79.9985, 25.5977, 20.5742], 40.0, 0.0), + ([71.9997, 25.5977, 20.5742], 100.0, 0.8118), + ([79.9985, 25.5977, 20.5742], 100.0, 0.4824), + ([60.0, 13.5508, 20.5742], 40.0, 0.0432), + ([60.0, 19.5742, 20.5742], 40.0, 0.6706), + ([60.0, 22.582, 20.5742], 40.0, 0.9333), + ([60.0, 28.6055, 20.5742], 40.0, 0.8549), + ([60.0, 31.6211, 20.5742], 40.0, 0.5098), + ([60.0, 37.6445, 20.5742], 40.0, 0.0078), + ([60.0, 13.5508, 20.5742], 100.0, 0.7647), + ([60.0, 37.6445, 20.5742], 100.0, 0.7137), + ([60.0, 25.5977, 10.5352], 40.0, 0.1725), + ([60.0, 25.5977, 16.5586], 40.0, 0.8667), + ([60.0, 25.5977, 24.5898], 40.0, 0.7647), + ([60.0, 25.5977, 30.6133], 40.0, 0.0863), + ([60.0, 25.5977, 10.5352], 100.0, 0.8392), + ([60.0, 25.5977, 30.6133], 100.0, 0.8), +]; + +#[test] +fn lab_range_matches_photoshop() { + let r = LabRange::point([60.0, 25.0, 19.9961]); + for &(lab, fz, ps) in PHOTOSHOP_COVERAGE { + let got = lab_range_coverage(lab, &r, fz); + assert!((got - ps).abs() <= 2.0 / 255.0, "{lab:?} at fuzziness {fz}: {got} vs Photoshop {ps}"); + } + // Lightness is three times as forgiving as hue: the same 6-unit step along L and along a. + assert!(lab_range_coverage([66.0, 25.0, 20.0], &r, 40.0) > lab_range_coverage([60.0, 31.0, 20.0], &r, 40.0)); + // The sampled colour itself is always fully selected. + for fz in [1.0, 10.0, 40.0] { + assert_eq!(lab_range_coverage([60.0, 25.0, 19.9961], &r, fz), 1.0); + } + assert_eq!(quantize_lab8([60.1, 25.4, -19.6]), [(153.0f32 / 2.55), 25.0, -20.0]); +} + +#[test] +fn lab_range_box_and_edges() { + let r = LabRange::spanning(&[[50.0, 10.0, 0.0], [60.0, 20.0, 5.0]]).unwrap(); + assert_eq!(r, LabRange { lo: [50.0, 10.0, 0.0], hi: [60.0, 20.0, 5.0] }); + assert!(LabRange::spanning(&[]).is_none()); + // Everything inside the box is fully selected, whatever the fuzziness. + for fz in [1.0, 40.0, 200.0] { + assert_eq!(lab_range_coverage([55.0, 15.0, 2.0], &r, fz), 1.0); + } + // Coverage falls off outside it and is gone a fuzziness away. + let near = lab_range_coverage([55.0, 22.0, 2.0], &r, 40.0); + assert!(near > 0.0 && near < 1.0, "{near}"); + assert_eq!(lab_range_coverage([55.0, 40.0, 2.0], &r, 40.0), 0.0); + // Fuzziness 0: exact colours only. + let p = LabRange::point([50.0, 10.0, -5.0]); + assert_eq!(lab_range_coverage([50.0, 10.0, -5.0], &p, 0.0), 1.0); + assert_eq!(lab_range_coverage([50.0, 11.0, -5.0], &p, 0.0), 0.0); + // Hostile numbers never panic and never select. + for v in [f32::NAN, f32::INFINITY, -f32::INFINITY] { + for fz in [v, 40.0] { + let k = lab_range_coverage([v, 0.0, 0.0], &p, fz); + assert!((0.0..=1.0).contains(&k), "{k}"); + } + } +} + +/// Boxes Photoshop 2024's Color Range dialog returned after Subtract from Sample, at +/// fuzziness 40 unless noted: (lo, hi, subtracted value, fuzziness, new lo, new hi) on one axis. +const PHOTOSHOP_SUBTRACT_A: &[(f32, f32, f32, f32, f32, f32)] = &[ + (0.0, 20.0, 5.0, 40.0, 5.0, 20.0), + (0.0, 20.0, 10.0, 40.0, 0.0, 10.0), + (0.0, 20.0, 15.0, 40.0, 0.0, 15.0), + (0.0, 20.0, 0.0, 40.0, 2.68, 20.0), + (0.0, 20.0, -2.0, 40.0, 0.68, 20.0), + (0.0, 20.0, -3.0, 40.0, 2.36, 20.0), + (0.0, 20.0, -8.0, 40.0, 0.04, 20.0), + (0.0, 20.0, -11.0, 40.0, 2.4, 20.0), + (0.0, 20.0, -13.0, 40.0, 0.4, 20.0), + (0.0, 20.0, -14.0, 40.0, 0.0, 20.0), + (0.0, 20.0, 20.0, 40.0, 0.0, 17.32), + (0.0, 20.0, 23.0, 40.0, 0.0, 17.64), + (0.0, 20.0, 33.0, 40.0, 0.0, 19.6), + (0.0, 20.0, 0.0, 80.0, 5.35, 20.0), + (0.0, 20.0, -12.0, 80.0, 4.05, 20.0), + (0.0, 20.0, -22.0, 80.0, 4.76, 20.0), + (0.0, 20.0, -30.0, 80.0, 0.0, 20.0), + (0.0, 6.0, 4.0, 40.0, 0.0, 4.0), + (0.0, 2.0, 0.0, 40.0, 2.0, 2.0), + (0.0, 2.0, 3.0, 40.0, 0.0, 0.32), +]; + +#[test] +fn subtract_reshapes_the_box_like_photoshop() { + for &(lo, hi, m, fz, want_lo, want_hi) in PHOTOSHOP_SUBTRACT_A { + let r = LabRange { lo: [50.0, lo, 0.0], hi: [50.0, hi, 0.0] }.subtract(&[50.0, m, 0.0], fz); + assert!( + (r.lo[1] - want_lo).abs() < 0.03 && (r.hi[1] - want_hi).abs() < 0.03, + "a [{lo}, {hi}] − {m} at {fz}: [{}, {}] vs Photoshop [{want_lo}, {want_hi}]", + r.lo[1], + r.hi[1] + ); + } + // Lightness (box 40–60, fuzziness 40): Photoshop gave 43.14, 41.17, 40.79 and 45.1. + for (m, want) in [(40.0, 43.14), (34.902, 41.17), (25.098, 40.79), (45.098, 45.1)] { + let r = LabRange { lo: [40.0, 0.0, 0.0], hi: [60.0, 0.0, 0.0] }.subtract(&[m, 0.0, 0.0], 40.0); + assert!((r.lo[0] - want).abs() < 0.05, "L − {m}: {} vs Photoshop {want}", r.lo[0]); + } + // All three axes at once (Photoshop: two samples, then one colour outside the box). + let r = LabRange { lo: [53.58, 0.0, 0.0], hi: [59.05, 30.56, 25.03] }.subtract(&[53.33, -28.71, 36.45], 40.0); + let want = LabRange { lo: [56.47, 0.0, 0.0], hi: [59.05, 30.56, 23.05] }; + for k in 0..3 { + assert!((r.lo[k] - want.lo[k]).abs() < 0.05 && (r.hi[k] - want.hi[k]).abs() < 0.05, "{r:?} vs {want:?}"); + } + // A single sample can't be subtracted from itself; hostile numbers change nothing. + let p = LabRange::point([50.0, 10.0, 10.0]); + assert_eq!(p.subtract(&[50.0, 10.0, 10.0], 40.0), p); + assert_eq!(p.subtract(&[f32::NAN, f32::INFINITY, -f32::INFINITY], f32::NAN), p); + assert_eq!(LabRange::spanning(&[[50.0, 0.0, 0.0]]).unwrap().grow(&[60.0, -5.0, 3.0]), LabRange { lo: [50.0, -5.0, 0.0], hi: [60.0, 0.0, 3.0] }); +} + +#[test] +fn eight_bit_grid_steps_are_uneven_like_photoshop() { + let r = LabRange::point([50.0, 10.0, -20.0]); + // The sampled colour itself is fully selected at any fuzziness. + for fz in [1.0, 5.0, 10.0, 40.0] { + assert_eq!(lab_range_coverage_8bit([50.0, 10.0, -20.0], &r, fz), 1.0); + } + // One step above on a counts as 1.5 units, one below as 0.5 (×3 weight): at fuzziness 40 + // (width 40.16) that is t = 4.5/40.16 and 1.5/40.16. + let up = lab_range_coverage_8bit([50.0, 11.0, -20.0], &r, 40.0); + let down = lab_range_coverage_8bit([50.0, 9.0, -20.0], &r, 40.0); + let p = |d: f32| (((1.0 - 2.0 * (d / (40.0 * 256.0 / 255.0)).powi(2)) * 256.0).floor().min(255.0)) / 255.0; + assert_eq!((up, down), (p(4.5), p(1.5))); + assert!(down > up); + // Lightness has no such offset; the exact (non-8-bit) coverage is symmetric. + assert_eq!(lab_range_coverage_8bit([51.0, 10.0, -20.0], &r, 40.0), lab_range_coverage_8bit([49.0, 10.0, -20.0], &r, 40.0)); + assert_eq!(lab_range_coverage([50.0, 11.0, -20.0], &r, 40.0), lab_range_coverage([50.0, 9.0, -20.0], &r, 40.0)); + let px = [[50.0, 11.0, -20.0, 1.0], [50.0, 9.0, -20.0, 1.0]]; + assert_eq!(color_range_lab(&px, 2, &r, 40.0, true, None), vec![up, down]); +} + +#[test] +fn color_range_lab_alpha_and_localized() { + let r = LabRange::point([50.0, 0.0, 0.0]); + let px = img(10, 1, |x, _| [50.0, 0.0, 0.0, if x == 0 { 0.0 } else { 1.0 }]); + let m = color_range_lab(&px, 10, &r, 40.0, false, None); + assert_eq!(m[0], 0.0, "transparent pixels are never selected"); + assert!(m[1..].iter().all(|v| *v > 0.9)); + let at = [(1.0, 0.0)]; + let l = color_range_lab(&px, 10, &r, 40.0, false, Some((4.0, &at))); + assert!(l[1] > l[3] && l[3] > 0.0 && l[6] == 0.0, "{l:?}"); + // No positions: localized clusters have nothing to centre on and change nothing. + assert_eq!(color_range_lab(&px, 10, &r, 40.0, false, Some((4.0, &[]))), m); + assert!(color_range_lab(&[], 0, &r, 40.0, false, None).is_empty()); +} + +#[test] +fn hue_families() { + let px = vec![ + [1.0, 0.0, 0.0, 1.0], // red + [1.0, 0.5, 0.0, 1.0], // orange: between red and yellow + [0.5, 0.5, 0.5, 1.0], // grey + [1.0, 0.5, 0.5, 1.0], // pink: a muted red + [0.0, 0.0, 1.0, 1.0], // blue + [1.0, 0.0, 0.0, 0.0], // transparent + ]; + let reds = hue_range(&px, 0.0); + assert_eq!(reds[0], 1.0); + assert!((reds[1] - 0.5).abs() < 1e-5); + assert_eq!(reds[2], 0.0); + assert!((reds[3] - 0.5).abs() < 1e-5); + assert_eq!(reds[4], 0.0); + assert_eq!(reds[5], 0.0); + let yellows = hue_range(&px, 60.0); + assert!((yellows[1] - 0.5).abs() < 1e-5); + assert_eq!(hue_range(&px, 240.0)[4], 1.0); + // Magentas wrap around 360°. + assert_eq!(hue_range(&[[1.0, 0.0, 1.0, 1.0]], 300.0)[0], 1.0); + assert!((hue_range(&[[1.0, 0.0, 0.5, 1.0]], 300.0)[0] - 0.5).abs() < 1e-5); +} + +#[test] +fn hue_families_weigh_dark_colours_like_photoshop() { + // Photoshop 2025's Blues on an 8-bit sRGB document (selection levels 0..255, #5243): the + // muted navy #3d3f54, a dark blue (0, 0, 84) and a mid blue (61, 61, 153). + let c = |r: u8, g: u8, b: u8| [f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0, 1.0]; + let blues = hue_range(&[c(0x3d, 0x3f, 0x54), c(0, 0, 84), c(61, 61, 153)], 240.0); + for (got, want) in blues.iter().zip([35.0, 140.0, 129.0]) { + assert!((got * 255.0 - want).abs() <= 1.0, "{} vs Photoshop {want}", got * 255.0); + } +} + +#[test] +fn tonal_ranges() { + let g = |v: f32| [v / 255.0, v / 255.0, v / 255.0, 1.0]; + let px = vec![g(0.0), g(60.0), g(75.0), g(128.0), g(200.0), g(255.0)]; + let near = |a: &[f32], b: &[f32]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4); + // Shadows up to 65, fading over 20 levels. + let sh = tone_range(&px, 0.0, 65.0, 20.0); + assert!(near(&sh, &[1.0, 1.0, 0.5, 0.0, 0.0, 0.0]), "{sh:?}"); + // Highlights from 190. + let h = tone_range(&px, 190.0, 255.0, 20.0); + assert!(near(&h, &[0.0, 0.0, 0.0, 0.0, 1.0, 1.0]), "{h:?}"); + // Midtones 105..150. + let m = tone_range(&px, 105.0, 150.0, 20.0); + assert!(near(&m, &[0.0, 0.0, 0.0, 1.0, 0.0, 0.0]), "{m:?}"); +} + +fn square(w: usize, h: usize) -> Vec { + (0..w * h).map(|i| if (5..15).contains(&(i % w)) && (5..15).contains(&(i / w)) { 1.0 } else { 0.0 }).collect() +} + +#[test] +fn expand_contract_border() { + let m = square(20, 20); + let e = expand(&m, 20, 20, 2.0); + assert_eq!(e[10 * 20 + 3], 1.0); + assert_eq!(e[10 * 20 + 2], 0.0); + let c = contract(&m, 20, 20, 2.0); + assert_eq!(c[10 * 20 + 6], 0.0); + assert_eq!(c[10 * 20 + 7], 1.0); + let b = border(&m, 20, 20, 4.0); + assert_eq!(b[10 * 20 + 10], 0.0); + assert!(b[10 * 20 + 5] > 0.5 && b[10 * 20 + 4] > 0.5); +} + +/// Photoshop 27.11, measured: a 32×32 rectangle at (16,16) in 64×64, Select › Modify › +/// Border 4 px, filled white. Row y = 32 for x = 8..=24, and the diagonal (16,16)..(24,24). +#[test] +fn border_matches_photoshop() { + let (w, h) = (64, 64); + let m: Vec = (0..w * h).map(|i| if (16..48).contains(&(i % w)) && (16..48).contains(&(i / w)) { 1.0 } else { 0.0 }).collect(); + let b = border(&m, w, h, 4.0); + let v = |x: usize, y: usize| (b[y * w + x] * 255.0).round() as i32; + let row: Vec = (8..=24).map(|x| v(x, 32)).collect(); + let diag: Vec = (16..=24).map(|d| v(d, d)).collect(); + let near = |got: &[i32], want: &[i32]| got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1); + let want_row = [0, 0, 0, 0, 63, 127, 191, 255, 255, 191, 127, 63, 0, 0, 0, 0, 0]; + assert!(near(&row, &want_row), "{row:?}"); + assert!(near(&diag, &[255, 191, 127, 63, 0, 0, 0, 0, 0]), "{diag:?}"); +} + +#[test] +fn smooth_removes_specks_and_feather_softens() { + let mut m = square(20, 20); + m[2 * 20 + 2] = 1.0; + let s = smooth(&m, 20, 20, 1.0); + assert_eq!(s[2 * 20 + 2], 0.0); + assert_eq!(s[10 * 20 + 10], 1.0); + // Radius 2 (σ 2) keeps the blur inside the 20×20 canvas, so no coverage is lost. + let f = feather(&square(20, 20), 20, 20, 2.0); + let edge = f[10 * 20 + 5]; + assert!(edge > 0.3 && edge < 0.8, "{edge}"); + let sum: f32 = f.iter().sum(); + assert!((sum - 100.0).abs() < 1.0); +} + +#[test] +fn polygon_area_and_aa() { + let a = Rect::new(0, 0, 20, 20); + let sq = polygon(&[(2.0, 2.0), (12.0, 2.0), (12.0, 12.0), (2.0, 12.0)], a, true); + let area: f32 = sq.iter().sum(); + assert!((area - 100.0).abs() < 1e-3, "{area}"); + let tri = polygon(&[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)], a, true); + let area: f32 = tri.iter().sum(); + assert!((area - 50.0).abs() < 1.0, "{area}"); + assert!(tri.iter().any(|v| *v > 0.0 && *v < 1.0)); + let hard = polygon(&[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)], a, false); + assert!(hard.iter().all(|v| *v == 0.0 || *v == 1.0)); + assert!(polygon(&[(0.0, 0.0), (1.0, 1.0)], a, true).iter().all(|v| *v == 0.0)); +} + +/// The previous polygon fill (every edge tested on every sub-row), kept as the oracle. +fn old_polygon(points: &[(f32, f32)], area: Rect, anti_alias: bool) -> Vec { + let (w, h) = (area.width() as usize, area.height() as usize); + let mut m = vec![0.0f32; w * h]; + if points.len() < 3 { + return m; + } + let sub = if anti_alias { 4 } else { 1 }; + let mut xs: Vec = Vec::new(); + for py in 0..h { + for s in 0..sub { + let y = area.y0 as f32 + py as f32 + (s as f32 + 0.5) / sub as f32; + xs.clear(); + for i in 0..points.len() { + let (a, b) = (points[i], points[(i + 1) % points.len()]); + if (a.1 <= y && b.1 > y) || (b.1 <= y && a.1 > y) { + xs.push(a.0 + (y - a.1) / (b.1 - a.1) * (b.0 - a.0)); + } + } + xs.sort_by(|a, b| a.total_cmp(b)); + for span in xs.as_chunks::<2>().0 { + let (x0, x1) = ((span[0] - area.x0 as f32).max(0.0), (span[1] - area.x0 as f32).min(w as f32)); + if x1 <= x0 { + continue; + } + let (c0, c1) = (x0.floor() as usize, (x1.ceil() as usize).min(w)); + for cx in c0..c1 { + let cov = if anti_alias { + ((cx + 1) as f32).min(x1) - (cx as f32).max(x0) + } else { + let c = cx as f32 + 0.5; + if c >= x0 && c < x1 { 1.0 } else { 0.0 } + }; + m[py * w + cx] += cov.max(0.0) / sub as f32; + } + } + } + } + for v in &mut m { + *v = v.min(1.0); + } + m +} + +#[test] +fn polygon_matches_the_every_edge_fill_bit_for_bit() { + let mut seed = 0x2545_f491_u32; + let mut rnd = move || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed as f32 / u32::MAX as f32 + }; + // Taller than one 64-row band, offset, and a 1-pixel-wide area. + let areas = [Rect::new(0, 0, 90, 150), Rect::new(-13, 7, 60, 211), Rect::new(5, -40, 6, 30)]; + let mut cases: Vec> = vec![ + // Self-intersecting star, horizontal edges, repeated points, collinear runs. + (0..11) + .map(|i| { + let t = i as f32 * 4.0 * std::f32::consts::PI / 11.0; + (40.0 + 35.0 * t.cos(), 80.0 + 70.0 * t.sin()) + }) + .collect(), + vec![(10.0, 10.0), (50.0, 10.0), (50.0, 10.0), (50.0, 60.0), (30.0, 60.0), (30.0, 30.0), (10.0, 30.0)], + vec![(0.0, 0.0), (20.0, 0.0), (40.0, 0.0), (40.0, 0.0), (0.0, 0.0)], + // Vertices on the sub-row centres and the pixel edges. + vec![(3.125, 2.375), (70.5, 2.375), (70.875, 140.625), (3.0, 140.0), (35.0, 64.0), (35.0, 64.125)], + // Entirely outside, and straddling every side. + vec![(-500.0, -500.0), (-400.0, -500.0), (-450.0, -300.0)], + vec![(-80.0, -60.0), (300.0, 20.0), (60.0, 400.0)], + // Non-finite coordinates and a negative zero. + vec![(10.0, 10.0), (f32::NAN, 40.0), (60.0, 70.0), (20.0, f32::INFINITY), (-0.0, -0.0), (0.0, 0.0)], + ]; + for n in [3, 7, 40, 400] { + for spread in [1.0, 2.0] { + cases.push((0..n).map(|_| (rnd() * 100.0 * spread - 50.0 * (spread - 1.0), rnd() * 220.0 * spread - 60.0 * spread)).collect()); + // Lasso-like: a random walk snapped to quarter pixels. + let (mut x, mut y) = (45.0f32, 75.0f32); + cases.push( + (0..n) + .map(|_| { + x = ((x + (rnd() - 0.5) * 12.0 * spread) * 4.0).round() / 4.0; + y = ((y + (rnd() - 0.5) * 12.0 * spread) * 4.0).round() / 4.0; + (x, y) + }) + .collect(), + ); + } + } + for pts in &cases { + for &area in &areas { + for aa in [true, false] { + let (new, old) = (polygon(pts, area, aa), old_polygon(pts, area, aa)); + assert_eq!(new.len(), old.len()); + let diff = new.iter().zip(&old).position(|(a, b)| a.to_bits() != b.to_bits()); + assert!(diff.is_none(), "{pts:?} {area:?} aa={aa}: first difference at {diff:?}"); + } + } + } +} + +#[test] +fn combine_modes() { + let a = Rect::new(0, 0, 4, 1); + let old = mask_to_surface(&[1.0, 1.0, 0.0, 0.0], a); + let new = [0.0, 1.0, 1.0, 0.0]; + let v = |s: Option| mask_from_surface(s.as_ref(), a); + assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Replace)), vec![0.0, 1.0, 1.0, 0.0]); + assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Add)), vec![1.0, 1.0, 1.0, 0.0]); + assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Subtract)), vec![1.0, 0.0, 0.0, 0.0]); + assert_eq!(v(combine(Some(&old), &new, a, SelectionMode::Intersect)), vec![0.0, 1.0, 0.0, 0.0]); + assert!(combine(Some(&old), &[1.0; 4], a, SelectionMode::Subtract).is_none()); + assert_eq!(SelectionMode::parse("add"), SelectionMode::Add); +} + +/// The previous (per-sample) conversions, kept as the oracle for the tiled fast paths. +fn old_mask_to_surface(m: &[f32], area: Rect) -> Surface { + let mut s = Surface::new(PixelFormat::GRAY8); + if !area.is_empty() { + s.write_region(area, m); + } + s.prune(); + s +} + +fn old_combine(old: Option<&Surface>, new: &[f32], area: Rect, mode: SelectionMode) -> Option { + let mut prev = Vec::new(); + match old { + Some(s) => s.read_region_into(area, &mut prev), + None => prev = vec![0.0; new.len()], + } + let q: Vec = new.iter().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0).collect(); + let out: Vec = match mode { + SelectionMode::Replace => q, + SelectionMode::Add => prev.iter().zip(&q).map(|(a, b)| a.max(*b)).collect(), + SelectionMode::Subtract => prev.iter().zip(&q).map(|(a, b)| (a - b).max(0.0)).collect(), + SelectionMode::Intersect => prev.iter().zip(&q).map(|(a, b)| a.min(*b)).collect(), + }; + let out: Vec = out.into_iter().map(|v| if v < 0.5 / 255.0 { 0.0 } else { v }).collect(); + if out.iter().all(|v| *v <= 0.0) { + return None; + } + Some(old_mask_to_surface(&out, area)) +} + +#[test] +fn tiled_conversions_match_per_sample_ones() { + let mut rng = crate::photo_util::Rng(7); + let mut u = move || (rng.next() >> 11) as f32 / (1u64 << 53) as f32; + // Off-grid areas spanning several tiles, including negative origins. + // The last one holds whole tiles, which fully selected masks fill (shared tiles). + for area in [Rect::new(0, 0, 300, 20), Rect::new(-37, 250, 530, 263), Rect::new(255, -3, 258, 600), Rect::new(5, 5, 6, 6), Rect::new(-37, -300, 530, 263)] { + let n = area.width() as usize * area.height() as usize; + let old_m: Vec = (0..n).map(|i| if i % 97 < 40 { u() } else { 0.0 }).collect(); + let old = old_mask_to_surface(&old_m, area); + let fast = mask_to_surface(&old_m, area); + assert_eq!(fast, old, "{area:?}"); + let mut slow_read = Vec::new(); + old.read_region_into(area, &mut slow_read); + assert_eq!(mask_from_surface(Some(&old), area), slow_read); + for kind in 0..4 { + let new: Vec = (0..n) + .map(|i| match kind { + 0 => u() * 1.2 - 0.1, + 1 => { + if i % 131 < 50 { + 1.0 + } else { + 0.0 + } + } + 2 => 0.001, + _ => f32::from(u8::from(i >= 1000)), + }) + .collect(); + for mode in [SelectionMode::Replace, SelectionMode::Add, SelectionMode::Subtract, SelectionMode::Intersect] { + for prev in [None, Some(&old)] { + assert_eq!(combine(prev, &new, area, mode), old_combine(prev, &new, area, mode), "{area:?} {kind} {mode:?}"); + } + } + } + } + // A short mask buffer reads as zeros instead of panicking. + let a = Rect::new(0, 0, 10, 10); + assert!(combine(None, &[1.0; 5], a, SelectionMode::Replace).is_some()); + assert_eq!(mask_to_surface(&[], a).tile_count(), 0); + assert!(combine(None, &[], Rect::EMPTY, SelectionMode::Replace).is_none()); +} + +fn blobs(w: i32, h: i32) -> Vec<[u8; 4]> { + // Deterministic blotchy image with gradients and hard edges. + (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let v = ((x * 7 + y * 3) % 23 + if (x / 5 + y / 4) % 3 == 0 { 120 } else { 0 }) as u8; + [v, v / 2, 255 - v, if x % 11 == 0 { 128 } else { 255 }] + }) + .collect() +} + +#[test] +fn magic_wand_rejects_incomplete_and_overflowing_pixel_inputs() { + let area = Rect::new(0, 0, 4, 4); + let short = vec![[255u8, 0, 0, 255]; 4]; + let floats: Vec<[f32; 4]> = short.iter().map(|p| p.map(|v| f32::from(v) / 255.0)).collect(); + assert_eq!(magic_wand(&floats, area, (1, 1), 0.0, true, false), Vec::::new()); + assert_eq!(wand_region(&short, area, (1, 1), 0.0, true, false), None); + + let huge = Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX); + assert!(magic_wand(&floats, huge, (0, 0), 0.0, false, false).is_empty()); + assert_eq!(wand_region(&short, huge, (0, 0), 0.0, false, false), None); + + let valid = Rect::new(0, 0, 2, 2); + assert_eq!(magic_wand(&floats, valid, (0, 0), 0.0, false, false), vec![1.0; 4]); + assert!(wand_region(&short, valid, (0, 0), 0.0, false, false).is_some()); +} + +#[test] +fn region_coverage_outside_a_short_mask_is_zero() { + let region = Region { bbox: Rect::new(-2, -3, 1, -1), mask: vec![255, 128] }; + assert_eq!(region.at(-2, -3), 1.0); + assert!((region.at(-1, -3) - 128.0 / 255.0).abs() < 1e-6); + assert_eq!(region.at(0, -3), 0.0); + assert_eq!(region.at(-2, -2), 0.0); + assert_eq!(region.at(-3, -3), 0.0); + + let extreme = Region { bbox: Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX), mask: vec![] }; + assert_eq!(extreme.at(i32::MAX - 1, i32::MAX - 1), 0.0); + assert_eq!(extreme.at(i32::MIN, i32::MIN), 0.0); +} + +#[test] +fn wand_region_matches_reference_magic_wand() { + let (w, h) = (37, 29); + let area = Rect::new(3, -2, 3 + w, -2 + h); + let img = blobs(w, h); + let f: Vec<[f32; 4]> = img.iter().map(|p| p.map(|v| v as f32 / 255.0)).collect(); + for (seed, tol, contiguous, aa) in + [((10, 5), 10.0, true, true), ((10, 5), 10.0, true, false), ((20, 20), 40.0, false, true), ((4, -2), 0.0, true, true), ((30, 10), 255.0, true, true)] + { + let reference = magic_wand(&f, area, seed, tol, contiguous, aa); + let r = wand_region(&img, area, seed, tol, contiguous, aa).unwrap(); + for y in area.y0..area.y1 { + for x in area.x0..area.x1 { + let want = (reference[((y - area.y0) * w + x - area.x0) as usize] * 255.0).round(); + assert!((r.at(x, y) * 255.0 - want).abs() <= 1.0, "{seed:?} {tol} {contiguous} {aa} at {x},{y}: {} vs {want}", r.at(x, y) * 255.0); + } + } + } + assert!(wand_region(&img, area, (0, 0), 10.0, true, true).is_none()); +} + +#[test] +fn combine_region_matches_combine() { + let area = Rect::new(0, 0, 40, 30); + let mut old = Surface::new(PixelFormat::GRAY8); + old.fill_rect(Rect::new(5, 5, 25, 20), &[1.0]); + old.fill_rect(Rect::new(8, 8, 10, 10), &[0.4]); + let img = blobs(40, 30); + let region = wand_region(&img, area, (12, 12), 30.0, true, true).unwrap(); + let full: Vec = (0..area.height()).flat_map(|y| (0..area.width()).map(move |x| (x, y))).map(|(x, y)| region.at(x as i32, y as i32)).collect(); + for mode in [SelectionMode::Replace, SelectionMode::Add, SelectionMode::Subtract, SelectionMode::Intersect] { + let a = combine(Some(&old), &full, area, mode); + let b = combine_region(Some(&old), Some(®ion), mode); + assert_eq!(a.is_some(), b.is_some(), "{mode:?}"); + if let (Some(a), Some(b)) = (a, b) { + for y in 0..30 { + for x in 0..40 { + assert!((a.pixel(x, y)[0] - b.pixel(x, y)[0]).abs() < 1.5 / 255.0, "{mode:?} {x},{y}"); + } + } + } + } + assert!(combine_region(None, None, SelectionMode::Subtract).is_none()); +} From 56a7e9ab471433847b9dba9901c07e82ee6337bd Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:08 +0000 Subject: [PATCH 026/259] refactor(engine): move transform_cmds.rs tests to transform_cmds/tests.rs --- crates/engine/src/transform_cmds.rs | 913 +--------------------- crates/engine/src/transform_cmds/tests.rs | 910 +++++++++++++++++++++ 2 files changed, 911 insertions(+), 912 deletions(-) create mode 100644 crates/engine/src/transform_cmds/tests.rs diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rs index c634441394..d1b9690312 100644 --- a/crates/engine/src/transform_cmds.rs +++ b/crates/engine/src/transform_cmds.rs @@ -873,915 +873,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - fn session() -> Session { - session_depth(8) - } - - fn session_depth(depth: u32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 100, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 20), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s - } - - /// The content bounds of the active layer's pixels. - fn active_bounds(s: &Session) -> Rect { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds() - } - - // ---- Memory budget (#3773, #7807). Tests run with a 20 MB budget (2²⁰ px of 32-bit CMYK with - // alpha), so nothing here comes near the real one. ---- - - /// Memory Usage's default, in bytes. - const DEFAULT_BUDGET: u64 = (crate::prefs::DEFAULT_MEMORY_USAGE_MB as u64) << 20; - - /// Scales of 10⁷ and past are refused by the real budget too, whatever the axis or sign. - #[test] - fn huge_transform_scales_exceed_the_production_budget_before_clipping() { - let src = Rect::new(0, 0, 24, 16); - for scale in [1e7, 1e28, 1e306] { - for (sx, sy) in [(scale, 1.0), (1.0, scale), (-scale, 1.0)] { - let h = Homography([sx, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 1.0]); - assert!(check_budget_with_limit(src, &h, "layer", PixelFormat::RGBA8, DEFAULT_BUDGET).is_err(), "{sx} x {sy} must be refused"); - } - } - } - - /// A 240000 px wide stretch, placed far from the canvas but within the warp's reach, fits. - #[test] - fn an_ordinary_transform_remains_within_the_production_budget() { - let src = Rect::new(0, 0, 24, 16); - let h = Homography([10_000.0, 0.0, 800_000.0, 0.0, 1.0, -900_000.0, 0.0, 0.0, 1.0]); - assert!(check_budget_with_limit(src, &h, "layer", PixelFormat::RGBA8, DEFAULT_BUDGET).is_ok()); - } - - /// The warp places pixels only within ±2²⁰ px ([`WARP_REACH`]): a result that fits Memory - /// Usage but would reach past it, by its size or by where it lands, is refused, not clipped. - #[test] - fn a_result_past_the_warps_reach_is_refused_not_clipped() { - let src = Rect::new(0, 0, 24, 16); - let check = |h: [f64; 9]| check_budget_with_limit(src, &Homography(h), "layer", PixelFormat::RGBA8, DEFAULT_BUDGET); - // 2000016 x 18 px, 138 MB of 8-bit RGBA: from x = 0 it would be cut at 2²⁰; centred it fits. - let err = check([83_334.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).unwrap_err().to_string(); - assert!(err.contains("would reach past ±1048576 px") && err.ends_with("the document was not changed"), "{err}"); - assert!(check([83_334.0, 0.0, -1_000_000.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).is_ok()); - // A small layer moved past the reach, either way on either axis. - for (dx, dy) in [(1_100_000.0, 0.0), (-1_100_000.0, 0.0), (0.0, 1_100_000.0), (0.0, -1_100_000.0)] { - assert!(check([1.0, 0.0, dx, 0.0, 1.0, dy, 0.0, 0.0, 1.0]).is_err(), "{dx}, {dy}"); - } - // Through the command: nothing moves, nothing is lost. - let mut s = session(); - let st = s.active().unwrap(); - let (before, steps) = (st.doc.clone(), st.history.past_len()); - let err = s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 2_000_000, 0]})).unwrap_err().to_string(); - assert!(err.contains("the transformed layer \"Layer 1\" would reach past ±1048576 px"), "{err}"); - let st = s.active().unwrap(); - assert!(st.doc == before && st.history.past_len() == steps, "the document is untouched"); - } - - /// #7807: the stitched layer's 90 % and 15°, a 37708 x 35259 px result that the old 2³⁰ px limit - /// refused, fits the default Memory Usage at 8 bits (5072 MB); at 16 bits it needs Memory Usage - /// raised, and the message says so. - #[test] - fn a_gigapixel_layer_transforms_within_memory_usage() { - let src = Rect::new(0, 0, 35_020, 31_171); - let r = [0.0, 0.0, 35_020.0, 31_171.0]; - let h = relative_matrix(&json!({"scaleX": 90, "scaleY": 90, "rotate": 15}), r).unwrap().unwrap(); - assert_eq!(warp_output_size(src, &h), Some((37_708, 35_259)), "the report's result, past the old limit"); - assert!(check_budget_with_limit(src, &h, "layer \"Layer 1\"", PixelFormat::RGBA8, DEFAULT_BUDGET).is_ok()); - let err = check_budget_with_limit(src, &h, "layer \"Layer 1\"", PixelFormat::RGBA16, DEFAULT_BUDGET).unwrap_err().to_string(); - assert!(err.contains("(10144 MB), more than the 8192 MB Memory Usage allows (Preferences › Performance)"), "{err}"); - assert!(check_budget_with_limit(src, &h, "layer", PixelFormat::RGBA16, 2 * DEFAULT_BUDGET).is_ok()); - // A format without alpha is priced as the warp makes it, with alpha. - let rgb8 = PixelFormat::new(PixelFormat::RGBA8.mode, PixelFormat::RGBA8.sample, false); - assert!(check_budget_with_limit(src, &h, "layer", rgb8, 5071 << 20).is_err()); - } - - /// A 16 x 16 document whose active layer is a 1 x 8 column at x = 10. - fn column() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 2, 11, 10), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s - } - - /// Stretch x by `k` about x = 10 (the column's left edge). - fn stretch(k: f64) -> Value { - json!({"matrix": [k, 0, 0, 1, -10.0 * k, 0], "interpolation": "nearest"}) - } - - /// A stretch past the budget is refused with the limit named, and the document, its revision - /// and History stay as they were; within the budget the same stretch applies unclipped. - #[test] - fn a_scale_past_the_pixel_budget_is_refused_and_changes_nothing() { - let mut s = column(); - let st = s.active().unwrap(); - let (before, revision, steps) = (st.doc.clone(), st.revision, st.history.past_len()); - // 1000000 x 10 px of 8-bit RGBA output: about twice the test budget. - let err = s.execute("edit.transform", stretch(1e6)).unwrap_err().to_string(); - assert!(err.starts_with("too large to transform: the transformed layer \"Layer 1\""), "{err}"); - assert!( - err.contains("would be 1000002 x 10 px (39 MB), more than the 20 MB Memory Usage allows") && err.ends_with("the document was not changed"), - "{err}" - ); - // Nothing was allocated, so nothing ran short (#7807). - assert!(!err.contains("not enough memory"), "{err}"); - let st = s.active().unwrap(); - assert!(st.doc == before, "the document is untouched"); - assert_eq!((st.revision, st.history.past_len()), (revision, steps)); - // Within the budget the same stretch still works, nothing clipped. - s.execute("edit.transform", stretch(1e4)).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(0, 2, 10_000, 10)); - } - - #[test] - fn a_group_with_one_layer_past_the_budget_is_not_half_transformed() { - let mut s = column(); - let wide = s.active().unwrap().active_layer.unwrap(); - // Over the column: a 1 px dot, which fits the budget stretched by the same amount. - s.execute("layer.new.layer", json!({})).unwrap(); - let dot = s.active().unwrap().active_layer.unwrap(); - s.edit("paint", |doc, _| { - doc.layer_mut(dot).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 12, 11, 13), &[0.0, 1.0, 0.0, 1.0]); - // Widen the column to 8 px (x 2..10), so it alone needs 800002 x 10 px (31 MB). - doc.layer_mut(wide).unwrap().surface_mut().unwrap().fill_rect(Rect::new(2, 2, 10, 10), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("layer.select", json!({"layer": wide.0})).unwrap(); - s.execute("layer.select", json!({"layer": dot.0, "mode": "add"})).unwrap(); - let group = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); - let st = s.active().unwrap(); - assert!(matches!(&st.doc.layer(group).unwrap().content, LayerContent::Group(g) if g.children.len() == 2)); - let (before, revision) = (st.doc.clone(), st.revision); - let k = 1e5; - assert!(s.execute("edit.transform", json!({"layer": group.0, "matrix": [k, 0, 0, 1, -10.0 * k, 0]})).is_err()); - let st = s.active().unwrap(); - assert!(st.doc == before && st.revision == revision, "nothing changed"); - // The layer-level check runs before any child is warped, so even the layer itself - // (not just the edit's copy of the document) is left as it was. - let mut l = st.doc.layer(group).unwrap().clone(); - let h = Homography([k, 0.0, -10.0 * k, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); - assert!(transform_layer(None, Locks::default(), &mut l, &h, None, Interp::Nearest).is_err()); - assert!(&l == st.doc.layer(group).unwrap(), "no child was transformed"); - } - - /// Only the result's size is priced: a small layer moved 900000 px away (within the warp's - /// reach) and back keeps every pixel. - #[test] - fn moving_a_small_layer_far_off_the_canvas_is_within_budget() { - let mut s = session(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 900_000, -900_000]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(900_010, -899_990, 900_030, -899_980)); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, -900_000, 900_000]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "and back, every pixel kept"); - } - - /// Each priced at its own format, as the warp makes it: an 8-bit outline, mask or channel with - /// alpha is 2 bytes a pixel, so a canvas-high column of it stretched 10⁶ times (34 MB) is over - /// the test budget. - #[test] - fn selections_masks_and_channels_have_the_same_budget() { - // The selection outline of a layer transform. - let mut s = column(); - s.execute("select.rect", json!({"x": 10, "y": 0, "width": 1, "height": 16})).unwrap(); - let before = s.active().unwrap().doc.clone(); - let err = s.execute("edit.transform", stretch(1e6)).unwrap_err().to_string(); - assert!(err.contains("transformed selection would be"), "{err}"); - // Transform Selection. - let err = s.execute("select.transformSelection", stretch(1e6)).unwrap_err().to_string(); - assert!(err.contains("transformed selection would be"), "{err}"); - assert!(s.active().unwrap().doc == before); - // A targeted alpha channel. - let mut s = column(); - s.execute("channel.new", json!({})).unwrap(); - s.edit("paint channel", |doc, _| { - doc.channels[0].surface.fill_rect(Rect::new(10, 0, 11, 16), &[1.0]); - Ok(()) - }) - .unwrap(); - let before = s.active().unwrap().doc.clone(); - let mut p = stretch(1e6); - p["target"] = json!({"channel": 0}); - let err = s.execute("edit.transform", p).unwrap_err().to_string(); - assert!(err.contains("transformed mask or channel would be"), "{err}"); - assert!(s.active().unwrap().doc == before); - } - - #[test] - fn scale_via_quad_and_undo() { - let mut s = session(); - s.execute("edit.transform", json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]]})).unwrap(); - let b = active_bounds(&s); - assert!(b.width().abs_diff(40) <= 2 && b.height().abs_diff(20) <= 2, "{b:?}"); - s.undo(); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20)); - } - - #[test] - fn affine_matrix_and_perspective() { - let mut s = session(); - // Translate by (40, 50). - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); - // Perspective: top edge narrower than the bottom. - s.execute("edit.transform", json!({"quad": [[55, 60], [65, 60], [75, 70], [45, 70]]})).unwrap(); - let b = active_bounds(&s); - assert!(b.x0 <= 46 && b.x1 >= 74, "{b:?}"); - assert!(s.execute("edit.transform", json!({"quad": [[0, 0], [0, 0], [0, 0], [0, 0]]})).is_err()); - } - - #[test] - fn background_becomes_layer_0() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); - s.execute("edit.transform", json!({"quad": [[0, 0], [20, 0], [20, 20], [0, 20]]})).unwrap(); - let st = s.active().unwrap(); - let l = &st.doc.layers[0]; - assert_eq!(l.name, "Layer 0"); - assert!(l.surface().unwrap().format().alpha); - assert_eq!(l.surface().unwrap().pixel(30, 30)[3], 0.0, "revealed area is transparent"); - } - - /// `locked_for_transform` (what Free Transform asks before its box opens, #2585) agrees with - /// what `edit.transform` refuses at commit: a position lock, its own or a group's; never the - /// Background's (it becomes Layer 0). - #[test] - fn locked_for_transform_matches_the_commit() { - let quad = json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]]}); - let lock = |s: &mut Session, id: LayerId, on: bool| { - s.edit("lock", |doc, _| { - doc.layer_mut(id).unwrap().locks.position = on; - Ok(()) - }) - .unwrap(); - }; - let mut s = session(); - let layer = s.active().unwrap().active_layer.unwrap(); - lock(&mut s, layer, true); - assert!(locked_for_transform(&s.active().unwrap().doc, layer)); - assert!(s.execute("edit.transform", quad.clone()).is_err()); - lock(&mut s, layer, false); - let group = LayerId(s.execute("layer.groupLayers", json!({"layer": layer.0})).unwrap()["layer"].as_u64().unwrap()); - lock(&mut s, group, true); - s.execute("layer.select", json!({"layer": layer.0})).unwrap(); - assert!(locked_for_transform(&s.active().unwrap().doc, layer), "the group's lock reaches the layer"); - assert!(s.execute("edit.transform", quad.clone()).is_err()); - let bg = s.active().unwrap().doc.layers[0].id; - assert!(!locked_for_transform(&s.active().unwrap().doc, bg), "the Background transforms"); - } - - #[test] - fn with_selection_only_selected_pixels_move() { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50]})).unwrap(); - let st = s.active().unwrap(); - let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - assert_eq!(surf.pixel(15, 15)[3], 0.0, "lifted area is cleared"); - assert_eq!(surf.pixel(25, 15)[3], 1.0, "unselected part stays"); - assert_eq!(surf.pixel(15, 65)[3], 1.0, "moved pixels land"); - let sel = st.doc.selection.as_ref().unwrap().content_bounds(); - assert_eq!((sel.y0, sel.y1), (60, 70), "selection moves too"); - } - - #[test] - fn with_selection_bounds_drop_the_vacated_area() { - // #1097: moving every pixel through a selection left transparent but coloured pixels - // behind, so the layer bounds were the union of the old and new positions. - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 10})).unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 50, 0]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(60, 10, 80, 20)); - } - - #[test] - fn type_layers_transform_as_vectors() { - let mut s = session(); - let r = s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi", "size": 20})).unwrap(); - let id = r["layer"].as_u64().unwrap(); - let w0 = active_bounds(&s).width(); - s.execute("edit.transform", json!({"layer": id, "matrix": [2, 0, 0, 2, -10, -50]})).unwrap(); - let w1 = active_bounds(&s).width(); - assert!(w1 as f32 > w0 as f32 * 1.8, "{w0} → {w1}"); - let st = s.active().unwrap(); - let LayerContent::Text(t) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!() }; - assert!((t.transform.m[0] - 2.0).abs() < 1e-9); - // Perspective on type is refused, like Photoshop. - assert!(s.execute("edit.transform", json!({"layer": id, "quad": [[0, 0], [10, 0], [12, 10], [-2, 10]]})).is_err()); - } - - #[test] - fn shapes_move_and_transform_as_vectors() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); - s.execute("layer.translate", json!({"dx": 30, "dy": 5})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(40, 15, 80, 35)); - s.execute("edit.transform", json!({"matrix": [2, 0, 0, 2, -40, -15]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(40, 15, 120, 55)); - // Distort maps the path and keeps a live shape (#3009): the rectangle's corners go to the quad. - let quad = [[40.0, 15.0], [120.0, 15.0], [130.0, 55.0], [30.0, 55.0]]; - s.execute("edit.transform", json!({ "quad": quad })).unwrap(); - let st = s.active().unwrap(); - let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("still a shape layer") }; - let mut anchors: Vec<[f64; 2]> = sh.path.subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); - let mut want = quad.to_vec(); - anchors.sort_by(|a, b| a.partial_cmp(b).unwrap()); - want.sort_by(|a, b| a.partial_cmp(b).unwrap()); - assert!(anchors.iter().zip(&want).all(|(a, b)| (a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6), "{anchors:?}"); - assert!(sh.live.is_none(), "the live rectangle is now a path"); - assert_eq!(active_bounds(&s), Rect::new(30, 15, 130, 55)); - // Warp bends the path too: the arc adds anchors along the curved edges. - s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap(); - let st = s.active().unwrap(); - let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("still a shape layer") }; - assert!(sh.path.subpaths[0].knots.len() > 4, "{}", sh.path.subpaths[0].knots.len()); - assert!(!active_bounds(&s).is_empty()); - } - - /// A gradient fill layer whose mask (a selection when it was made) frames the gradient over - /// 10..40, with the cached render a PSD import gives it: exactly the pixels the fill renders. - fn cached_gradient_fill() -> Session { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); - s.execute("layer.newFillLayer.gradient", json!({"from": "#ff0000", "to": "#0000ff", "angle": 0})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.edit("cache", |doc, active| { - let (fmt, canvas) = (doc.pixel_format(), doc.bounds()); - let l = doc.layer_mut(active.unwrap()).unwrap(); - let LayerContent::Fill(f) = &l.content else { panic!("a fill layer") }; - let buf = photocraft_compose::render_fill_content(l, f, canvas, &[]); - let mut surface = Surface::new(fmt); - let vals: Vec = buf.px.iter().flat_map(|p| photocraft_raster::from_rgba(&fmt, *p)).collect(); - surface.write_region(canvas, &vals); - l.fill_cache = Some(photocraft_doc::FillCache { fill: f.clone(), surface }); - Ok(()) - }) - .unwrap(); - s - } - - /// How far the composite is from the composite with the fill re-rendered from its model - /// (cache dropped): the largest channel difference. - fn off_from_fresh(s: &Session) -> f32 { - let st = s.active().unwrap(); - let mut fresh: Document = (*st.doc).clone(); - fresh.layer_mut(st.active_layer.unwrap()).unwrap().fill_cache = None; - let (a, b) = (photocraft_compose::render(&st.doc, st.doc.bounds()).px, photocraft_compose::render(&fresh, fresh.bounds()).px); - a.iter().zip(&b).flat_map(|(p, q)| p.iter().zip(q).map(|(x, y)| (x - y).abs())).fold(0.0, f32::max) - } - - #[test] - fn transforming_a_fill_layer_drops_its_stale_cached_render() { - let mut s = cached_gradient_fill(); - let off = off_from_fresh(&s); - assert!(off < 0.01, "the cache is the fill's own render: {off}"); - // The mask (and so the gradient's frame) moves 50 px right and doubles in height. - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 2, 50, 0]})).unwrap(); - let off = off_from_fresh(&s); - assert!(off < 0.01, "the composite shows the fill laid out in its new frame, not the old render: {off}"); - } - - #[test] - fn warping_a_fill_layer_drops_its_stale_cached_render() { - let mut s = cached_gradient_fill(); - s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap(); - let off = off_from_fresh(&s); - assert!(off < 0.01, "the composite shows the fill laid out in its new frame, not the old render: {off}"); - } - - #[test] - fn type_moves_with_the_move_command() { - let mut s = session(); - s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi", "size": 20})).unwrap(); - let b0 = active_bounds(&s); - s.execute("layer.translate", json!({"dx": 20, "dy": 10})).unwrap(); - let b1 = active_bounds(&s); - assert_eq!((b1.x0 - b0.x0, b1.y0 - b0.y0), (20, 10)); - } - - // ---- Layer masks and targets (#205) ---- - - /// `session()` plus a reveal-all mask with `hide` painted black (linked unless `linked` is false). - fn masked(hide: &[Rect], linked: bool) -> Session { - masked_depth(hide, linked, 8) - } - - fn masked_depth(hide: &[Rect], linked: bool, depth: u32) -> Session { - let mut s = session_depth(depth); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.edit("mask", |doc, active| { - let m = doc.layer_mut(active.unwrap()).unwrap().mask.as_mut().unwrap(); - for r in hide { - m.surface.fill_rect(*r, &[0.0]); - } - m.linked = linked; - Ok(()) - }) - .unwrap(); - s - } - - fn mask_at(s: &Session, x: i32, y: i32) -> f32 { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0) - } - - fn alpha_at(s: &Session, x: i32, y: i32) -> f32 { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)[3] - } - - #[test] - fn linked_raster_mask_moves_with_the_pixels() { - let mut s = masked(&[Rect::new(10, 10, 20, 20)], true); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); - assert!(mask_at(&s, 55, 65) < 0.01, "the hidden half moved with the pixels"); - assert!(mask_at(&s, 65, 65) > 0.99); - assert!(mask_at(&s, 15, 15) > 0.99, "nothing hidden left behind"); - } - - #[test] - fn linked_mask_with_a_selection_moves_only_the_selected_region() { - // The selection covers the left half of the red rect; the mask hides its left quarter - // (selected) and its right quarter (not selected). - let mut s = masked(&[Rect::new(10, 10, 15, 20), Rect::new(25, 10, 30, 20)], true); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50]})).unwrap(); - // Moved pixels and their mask line up. - assert_eq!(alpha_at(&s, 12, 65), 1.0); - assert!(mask_at(&s, 12, 65) < 0.01, "selected hidden quarter moved"); - assert!(mask_at(&s, 17, 65) > 0.99, "selected visible quarter moved"); - // The vacated area reads as revealed (default), with transparent pixels. - assert_eq!(alpha_at(&s, 12, 15), 0.0); - assert!(mask_at(&s, 12, 15) > 0.99); - // The unselected part of the mask stays, aligned with the unselected pixels. - assert_eq!(alpha_at(&s, 27, 15), 1.0); - assert!(mask_at(&s, 27, 15) < 0.01, "unselected mask stays put"); - assert!(mask_at(&s, 27, 65) > 0.99, "and isn't copied along"); - // Every pixel's mask value is where it was relative to the pixel. - for (x, y) in [(11, 61), (14, 69), (15, 61), (19, 69)] { - let want = if x < 15 { 0.0 } else { 1.0 }; - assert!((mask_at(&s, x, y) - want).abs() < 0.01, "({x},{y})"); - } - } - - #[test] - fn unlinked_mask_stays_put() { - let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); - assert!(mask_at(&s, 15, 15) < 0.01); - assert!(mask_at(&s, 55, 65) > 0.99); - // With a selection too. - let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50]})).unwrap(); - assert!(mask_at(&s, 15, 15) < 0.01 && mask_at(&s, 15, 65) > 0.99); - } - - #[test] - fn targeted_unlinked_mask_transforms_alone() { - let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50], "target": "mask"})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "pixels untouched"); - assert!(mask_at(&s, 55, 65) < 0.01, "mask moved"); - assert!(mask_at(&s, 15, 15) > 0.99, "vacated area reads as the default"); - s.undo(); - assert!(mask_at(&s, 15, 15) < 0.01, "one undo step"); - // With a selection, only its part of the mask. - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 5, "height": 10})).unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50], "target": "mask"})).unwrap(); - assert!(mask_at(&s, 12, 65) < 0.01 && mask_at(&s, 12, 15) > 0.99); - assert!(mask_at(&s, 17, 15) < 0.01, "unselected mask stays"); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "pixels untouched"); - } - - #[test] - fn targeted_linked_mask_moves_with_its_layer() { - // Photoshop: a linked mask can't move without its layer. - let mut s = masked(&[Rect::new(10, 10, 20, 20)], true); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50], "target": "mask"})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); - assert!(mask_at(&s, 55, 65) < 0.01); - } - - #[test] - fn targeted_alpha_channel_transforms_alone() { - let mut s = session(); - s.execute("channel.new", json!({})).unwrap(); - s.edit("paint channel", |doc, _| { - doc.channels[0].surface.fill_rect(Rect::new(10, 10, 20, 20), &[1.0]); - Ok(()) - }) - .unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50], "target": {"channel": 0}})).unwrap(); - let st = s.active().unwrap(); - let ch = &st.doc.channels[0].surface; - assert!(ch.sample_channel(55, 65, 0) > 0.99 && ch.sample_channel(15, 15, 0) < 0.01); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "layer untouched"); - } - - /// The Channels panel targets an alpha channel: Edit › Transform › Flip Horizontal and a - /// 50% `edit.transform` (no `target` param) work on the channel, not the layer (BUG-207-4). - #[test] - fn transforms_follow_the_targeted_alpha_channel() { - let mut s = session(); - s.execute("channel.new", json!({})).unwrap(); - s.edit("paint channel", |doc, _| { - let ch = &mut doc.channels[0].surface; - ch.fill_rect(Rect::new(10, 10, 20, 20), &[1.0]); - ch.fill_rect(Rect::new(10, 10, 12, 20), &[0.5]); - Ok(()) - }) - .unwrap(); - s.execute("channel.target", json!({"channel": 0})).unwrap(); - let layer = |s: &Session| crate::active_layer_of(s).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 100, 100)); - let (pixels, past) = (layer(&s), s.active().unwrap().history.past_len()); - s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); - // 8-bit channel: 0.5 is stored as 128/255. - let ch = |s: &Session, x, y| (s.active().unwrap().doc.channels[0].surface.sample_channel(x, y, 0) * 10.0).round() / 10.0; - assert_eq!((ch(&s, 19, 15), ch(&s, 10, 15)), (0.5, 1.0), "the channel flips within its frame"); - assert!(layer(&s) == pixels, "the layer is untouched"); - assert_eq!(s.active().unwrap().history.past_len(), past + 1, "one undo step"); - s.execute("edit.transform", json!({"matrix": [0.5, 0, 0, 0.5, 0, 0], "interpolation": "nearest"})).unwrap(); - assert_eq!((ch(&s, 7, 7), ch(&s, 15, 15)), (1.0, 0.0), "the channel scales to 50%"); - assert!(layer(&s) == pixels, "the layer is untouched"); - s.undo(); - s.undo(); - assert_eq!((ch(&s, 10, 15), ch(&s, 19, 15)), (0.5, 1.0)); - } - - #[test] - fn transform_targets_fail_gracefully() { - let mut s = session(); - let m = json!([1, 0, 0, 1, 5, 5]); - assert!(s.execute("edit.transform", json!({"matrix": m, "target": "mask"})).is_err(), "no mask"); - assert!(s.execute("edit.transform", json!({"matrix": m, "target": {"channel": 9}})).is_err()); - assert!(s.execute("edit.transform", json!({"matrix": m, "target": "quickMask"})).is_err()); - // Unknown target shapes fall back to the pixels. - s.execute("edit.transform", json!({"matrix": m, "target": 7})).unwrap(); - s.execute("edit.transform", json!({"matrix": m, "target": {"channel": "x"}})).unwrap(); - // Selections that miss the mask entirely transform nothing, without panicking. - let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); - s.execute("select.rect", json!({"x": 80, "y": 80, "width": 5, "height": 5})).unwrap(); - let _ = s.execute("edit.transform", json!({"matrix": [1e9, 0, 0, 1e9, 0, 0], "target": "mask"})); - let _ = s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 1e12, 0], "target": "mask"})); - } - - #[test] - fn split_gray_selected_rejects_non_gray() { - let s = Surface::new(PixelFormat::RGBA8); - let mut sel = Surface::new(PixelFormat::GRAY8); - sel.fill_rect(Rect::new(0, 0, 4, 4), &[1.0]); - assert!(matches!(split_gray_selected(&s, &sel), Ok(None))); - } - - /// #2630: type can't be partly transformed, so a selection doesn't narrow the frame: Free - /// Transform (and the frame-based presets) act on the whole type layer. - #[test] - fn a_selection_does_not_narrow_a_type_layers_frame() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 120})).unwrap(); - s.execute("type.create", json!({"x": 20, "y": 60, "text": "Hello", "size": 36})).unwrap(); - let whole = active_bounds(&s); - s.execute("select.rect", json!({"x": whole.x0, "y": whole.y0, "width": whole.width() / 2, "height": whole.height()})).unwrap(); - let st = s.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); - assert_eq!(transform_bounds(&st.doc, l), whole, "the frame is the whole type layer"); - // Corners of the frame moved 10 px right: a pure translation of the whole text. - let q = [[whole.x0 + 10, whole.y0], [whole.x1 + 10, whole.y0], [whole.x1 + 10, whole.y1], [whole.x0 + 10, whole.y1]]; - s.execute("edit.transform", json!({"quad": q})).unwrap(); - let moved = active_bounds(&s); - assert!(moved.x0.abs_diff(whole.x0 + 10) <= 1 && moved.width().abs_diff(whole.width()) <= 1, "{whole:?} -> {moved:?}"); - // Rotate 180° turns it about its own centre, not the selection's. - s.execute("edit.transform.rotate180", json!({})).unwrap(); - let turned = active_bounds(&s); - assert!(turned.x0.abs_diff(moved.x0) <= 2 && turned.x1.abs_diff(moved.x1) <= 2, "{moved:?} -> {turned:?}"); - // A pixel layer still frames only the selected pixels. - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 5, "height": 10})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(transform_bounds(&st.doc, st.doc.layer(st.active_layer.unwrap()).unwrap()), Rect::new(10, 10, 15, 20)); - } - - /// #5297: the box Free Transform opens with a selection is the selection's own rectangle, - /// not the part of it the layer fills; type still moves whole, and a selection that holds none - /// of the layer leaves nothing to transform. - #[test] - fn the_frame_is_the_selections_own_bounds() { - let mut s = session(); - let frame = |s: &Session| { - let st = s.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); - (transform_frame(&st.doc, l), transform_bounds(&st.doc, l)) - }; - let content = Rect::new(10, 10, 30, 20); - assert_eq!(frame(&s), (content, content), "no selection: the content"); - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 15, "height": 40})).unwrap(); - assert_eq!(frame(&s), (Rect::new(5, 5, 20, 45), Rect::new(10, 10, 20, 20))); - s.execute("select.rect", json!({"x": 60, "y": 60, "width": 10, "height": 10})).unwrap(); - assert!(frame(&s).0.is_empty(), "nothing of the layer is selected"); - - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 120})).unwrap(); - s.execute("type.create", json!({"x": 20, "y": 60, "text": "Hello", "size": 36})).unwrap(); - let whole = active_bounds(&s); - s.execute("select.rect", json!({"x": whole.x0, "y": whole.y0, "width": whole.width() / 2, "height": whole.height()})).unwrap(); - assert_eq!(frame(&s), (whole, whole), "type moves whole"); - } - - #[test] - fn group_transform_ignores_selections_inside_its_children() { - group_transform_with_selection(Rect::new(10, 10, 15, 15)); - } - - #[test] - fn group_transform_ignores_selections_outside_its_children() { - group_transform_with_selection(Rect::new(70, 70, 80, 80)); - } - - #[test] - fn group_transform_presets_rotate_about_the_whole_group() { - for depth in [8, 16, 32] { - for x in [10, 70] { - let mut s = masked_depth(&[Rect::new(10, 10, 15, 20)], true, depth); - let child = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.groupLayers", json!({})).unwrap(); - s.execute("select.rect", json!({"x": x, "y": 10, "width": 5, "height": 5})).unwrap(); - s.execute("edit.transform.rotate180", json!({})).unwrap(); - let layer = s.active().unwrap().doc.layer(child).unwrap(); - assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 30, 20), "rotate about the group's centre, not the selection's"); - let mask = &layer.mask.as_ref().unwrap().surface; - assert_eq!(mask.sample_channel(27, 15, 0), 0.0); - assert_eq!(mask.sample_channel(12, 15, 0), 1.0); - } - } - } - - fn group_transform_with_selection(selection: Rect) { - for depth in [8, 16, 32] { - for nested in [false, true] { - let mut s = masked_depth(&[Rect::new(10, 10, 15, 20)], true, depth); - let child = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.groupLayers", json!({})).unwrap(); - if nested { - s.execute("layer.groupLayers", json!({})).unwrap(); - } - s.execute("select.rect", json!({"x": selection.x0, "y": selection.y0, "width": selection.width(), "height": selection.height()})).unwrap(); - let steps = s.active().unwrap().history.entries().len(); - let result = s.execute("edit.transform", json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]], "interpolation": "nearest"})).unwrap(); - assert_eq!(result["rect"], json!([10.0, 10.0, 30.0, 20.0]), "frame must include the whole group (nested={nested})"); - let st = s.active().unwrap(); - let layer = st.doc.layer(child).unwrap(); - assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 50, 30)); - let mask = &layer.mask.as_ref().unwrap().surface; - assert_eq!(mask.sample_channel(19, 20, 0), 0.0, "the linked mask scales with its complete layer"); - assert_eq!(mask.sample_channel(21, 20, 0), 1.0); - assert_eq!(st.history.entries().len(), steps + 1); - assert!(s.undo()); - let st = s.active().unwrap(); - let layer = st.doc.layer(child).unwrap(); - assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 30, 20)); - assert_eq!(layer.mask.as_ref().unwrap().surface.sample_channel(19, 15, 0), 1.0); - assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), selection); - assert!(s.redo()); - assert_eq!(s.active().unwrap().doc.layer(child).unwrap().surface().unwrap().content_bounds(), Rect::new(10, 10, 50, 30)); - } - } - } - - #[test] - fn feathered_selection_identity_transform_preserves_pixels() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "background": "transparent"})).unwrap(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - s.execute("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); - s.execute("select.modify.feather", json!({"radius": 1})).unwrap(); - - let mut before_px = Vec::new(); - for y in 0..16 { - for x in 0..16 { - before_px.push(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()); - } - } - - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 0], "interpolation": "nearest"})).unwrap(); - - let mut after_px = Vec::new(); - for y in 0..16 { - for x in 0..16 { - after_px.push(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()); - } - } - - assert_eq!(before_px, after_px, "feathered selection identity transform must preserve all pixels"); - let p4_8 = s.execute("document.pixel", json!({"x": 4, "y": 8})).unwrap(); - assert_eq!(p4_8, json!([1.0, 0.0, 0.0, 1.0]), "(4,8) must remain opaque red"); - - // Undo restores original document. - s.execute("edit.undo", json!({})).unwrap(); - let undo_p4_8 = s.execute("document.pixel", json!({"x": 4, "y": 8})).unwrap(); - assert_eq!(undo_p4_8, json!([1.0, 0.0, 0.0, 1.0])); - - // Locked layer still refuses transform even if identity. - s.execute("layer.setProps", json!({"locks": {"position": true}})).unwrap(); - assert!(s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 0]})).is_err(), "locked layer refuses identity transform"); - } - - /// A 1 x 8 px column on a 256 x 256 canvas (#3773). - fn column_session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 256, "height": 256})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - l.surface_mut().unwrap().fill_rect(Rect::new(100, 100, 101, 108), &[0.0, 1.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s - } - - fn opaque_green(s: &Session, x: i32, y: i32) -> bool { - let st = s.active().unwrap(); - let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - (surf.sample_channel(x, y, 1) - 1.0).abs() < 1e-3 && (surf.sample_channel(x, y, 3) - 1.0).abs() < 1e-3 - } - - /// The "pixel stretch" (#3773): scales far past 1000% are taken, and the stretched column stays - /// solid along its whole length. - #[test] - fn a_one_pixel_column_stretches_5000_percent() { - let mut s = column_session(); - s.execute("edit.transform", json!({"quad": [[100, 100], [150, 100], [150, 108], [100, 108]]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(100, 100, 150, 108)); - for x in [100, 101, 125, 149] { - for y in 100..108 { - assert!(opaque_green(&s, x, y), "({x}, {y})"); - } - } - } - - /// The technique as done in Photoshop: select a 1 px column of an image and stretch it across. - #[test] - fn a_selected_column_stretches_solid_over_the_image() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 256, "height": 256})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - surf.fill_rect(Rect::new(0, 0, 256, 256), &[1.0, 0.0, 0.0, 1.0]); - surf.fill_rect(Rect::new(10, 0, 11, 256), &[0.0, 1.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("select.rect", json!({"x": 10, "y": 0, "width": 1, "height": 256})).unwrap(); - s.execute("edit.transform", json!({"quad": [[10, 0], [250, 0], [250, 256], [10, 256]]})).unwrap(); - for x in [10, 11, 100, 200, 249] { - assert!(opaque_green(&s, x, 128), "x = {x}"); - } - let st = s.active().unwrap(); - let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - assert!(surf.sample_channel(250, 128, 0) > 0.999 && surf.sample_channel(9, 128, 0) > 0.999, "the image either side is untouched"); - } - - /// Free Transform keeps pixels moved off the canvas, as Photoshop does: an 8 x 8 layer moved - /// three canvas widths right and back comes back whole. - #[test] - fn a_layer_moved_far_off_the_canvas_and_back_keeps_its_pixels() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in 0..8 { - for x in 0..8 { - surf.fill_rect(Rect::new(20 + x, 20 + y, 21 + x, 21 + y), &[x as f32 / 8.0, y as f32 / 8.0, 0.5, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - let pixels = |s: &Session| { - let st = s.active().unwrap(); - let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - (0..8 * 8 * 4).map(|i| surf.sample_channel(20 + i / 4 % 8, 20 + i / 32, (i % 4) as usize)).collect::>() - }; - let before = pixels(&s); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 192, 0]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(212, 20, 220, 28)); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, -192, 0]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(20, 20, 28, 28)); - assert_eq!(pixels(&s), before); - } - - #[test] - fn relative_params_scale_and_rotate_about_the_frame_centre() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 20, "y": 30, "width": 40, "height": 20})).unwrap(); - s.execute("edit.fill", json!({"contents": "black"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - // 50% about the centre (40, 40), then 10 px right: the content ends at x 40..60, y 35..45. - let r = s.execute("edit.transform", json!({"scaleX": 50, "scaleY": 50, "dx": 10})).unwrap(); - let rect: Vec = serde_json::from_value(r["rect"].clone()).unwrap(); - assert_eq!(rect, [20.0, 30.0, 60.0, 50.0], "the reported frame is the source frame"); - let bounds = |s: &Session| { - let d = s.active().unwrap(); - let b = transform_bounds(&d.doc, d.doc.layer(d.active_layer.unwrap()).unwrap()); - (b.x0, b.y0, b.x1, b.y1) - }; - assert_eq!(bounds(&s), (40, 35, 60, 45)); - // A quarter turn about the centre (50, 40) swaps the frame's sides. - s.execute("edit.transform", json!({"rotate": 90})).unwrap(); - assert_eq!(bounds(&s), (45, 30, 55, 50)); - for bad in [json!({"scaleX": 0}), json!({"rotate": "x"}), json!({"dx": f64::NAN})] { - assert!(s.execute("edit.transform", bad.clone()).is_err(), "{bad}"); - } - } - - /// #5846: a shape's Density and Feather render past its path (over the whole canvas below - /// 100 %), but its transform frame follows the path, as in Photoshop: the same box as the hard - /// shape for Free Transform, the Move tool's controls and snapping, never the canvas. - #[test] - fn a_soft_shapes_frame_follows_its_path() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - let id = s.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 60, 40], "fill": "#000000"})).unwrap()["layer"].as_u64().unwrap(); - let id = photocraft_doc::LayerId(id); - let boxes = |s: &Session| { - let st = s.active().unwrap(); - let l = st.doc.layer(id).unwrap(); - (transform_bounds(&st.doc, l), transform_frame(&st.doc, l), crate::snap::layer_rect(&st.doc, id)) - }; - let hard = boxes(&s); - assert_eq!(hard.0, Rect::new(20, 30, 80, 70), "the hard shape's frame"); - s.execute("layer.vectorMask.edit", json!({"density": 60, "feather": 20})).unwrap(); - { - let st = s.active().unwrap(); - let LayerContent::Shape(sh) = &st.doc.layer(id).unwrap().content else { panic!("a shape") }; - let painted = photocraft_compose::bounds::content_bounds(sh.cache.as_ref().unwrap()); - assert_eq!(painted, st.doc.bounds(), "the soft fill renders over the whole canvas"); - } - let soft = boxes(&s); - assert_eq!(soft, hard, "the frame ignores Density and Feather"); - assert_ne!(soft.1, s.active().unwrap().doc.bounds()); - // Feather alone (density 100 %) leaves the frame on the path too, not grown by the blur. - s.execute("layer.vectorMask.edit", json!({"density": 100, "feather": 20})).unwrap(); - assert_eq!(boxes(&s), hard); - // Free Transform scales about the path's centre, not the canvas's. - s.execute("edit.transform", json!({"layer": id.0, "scaleX": 200})).unwrap(); - let st = s.active().unwrap(); - let LayerContent::Shape(sh) = &st.doc.layer(id).unwrap().content else { panic!("a shape") }; - let (x0, y0, x1, y1) = sh.path.control_bounds().unwrap(); - assert_eq!((x0.round(), y0.round(), x1.round(), y1.round()), (-10.0, 30.0, 110.0, 70.0)); - assert_eq!((sh.density, sh.feather), (1.0, 20.0), "the transform keeps the soft settings"); - } - - /// A stroked soft shape's frame is the hard shape's rendered frame for every stroke alignment: - /// a centred stroke reaches half its width past the path, not its full width; both stop at - /// the canvas edge. - #[test] - fn a_stroked_soft_shapes_frame_matches_the_hard_shapes() { - for (align, reach, x) in [("center", 5, 50), ("inside", 0, 50), ("outside", 10, 50), ("center", 5, -20)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - let stroke = json!({"width": 10, "color": "#ff0000", "align": align, "join": "round"}); - let id = s.execute("shape.create", json!({"kind": "rect", "rect": [x, 50, 60, 40], "fill": "#000000", "stroke": stroke})).unwrap()["layer"] - .as_u64() - .unwrap(); - let id = photocraft_doc::LayerId(id); - let boxes = |s: &Session| { - let st = s.active().unwrap(); - let l = st.doc.layer(id).unwrap(); - (transform_bounds(&st.doc, l), transform_frame(&st.doc, l), crate::snap::layer_rect(&st.doc, id)) - }; - let hard = boxes(&s); - // Hand-computed: the path is x..x + 60 x 50..90, the stroke reaches `reach` px past it. - assert_eq!(hard.0, Rect::new((x - reach).max(0), 50 - reach, x + 60 + reach, 90 + reach), "{align} at {x}: the hard shape's frame"); - s.execute("layer.vectorMask.edit", json!({"density": 60, "feather": 8})).unwrap(); - assert_eq!(boxes(&s), hard, "{align} at {x}: Density and Feather leave the frame"); - s.execute("layer.vectorMask.edit", json!({"density": 100, "feather": 8})).unwrap(); - assert_eq!(boxes(&s), hard, "{align} at {x}: Feather alone leaves the frame"); - } - } -} +mod tests; diff --git a/crates/engine/src/transform_cmds/tests.rs b/crates/engine/src/transform_cmds/tests.rs new file mode 100644 index 0000000000..f8ff204257 --- /dev/null +++ b/crates/engine/src/transform_cmds/tests.rs @@ -0,0 +1,910 @@ +use super::*; + +fn session() -> Session { + session_depth(8) +} + +fn session_depth(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 20), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +/// The content bounds of the active layer's pixels. +fn active_bounds(s: &Session) -> Rect { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds() +} + +// ---- Memory budget (#3773, #7807). Tests run with a 20 MB budget (2²⁰ px of 32-bit CMYK with +// alpha), so nothing here comes near the real one. ---- + +/// Memory Usage's default, in bytes. +const DEFAULT_BUDGET: u64 = (crate::prefs::DEFAULT_MEMORY_USAGE_MB as u64) << 20; + +/// Scales of 10⁷ and past are refused by the real budget too, whatever the axis or sign. +#[test] +fn huge_transform_scales_exceed_the_production_budget_before_clipping() { + let src = Rect::new(0, 0, 24, 16); + for scale in [1e7, 1e28, 1e306] { + for (sx, sy) in [(scale, 1.0), (1.0, scale), (-scale, 1.0)] { + let h = Homography([sx, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 1.0]); + assert!(check_budget_with_limit(src, &h, "layer", PixelFormat::RGBA8, DEFAULT_BUDGET).is_err(), "{sx} x {sy} must be refused"); + } + } +} + +/// A 240000 px wide stretch, placed far from the canvas but within the warp's reach, fits. +#[test] +fn an_ordinary_transform_remains_within_the_production_budget() { + let src = Rect::new(0, 0, 24, 16); + let h = Homography([10_000.0, 0.0, 800_000.0, 0.0, 1.0, -900_000.0, 0.0, 0.0, 1.0]); + assert!(check_budget_with_limit(src, &h, "layer", PixelFormat::RGBA8, DEFAULT_BUDGET).is_ok()); +} + +/// The warp places pixels only within ±2²⁰ px ([`WARP_REACH`]): a result that fits Memory +/// Usage but would reach past it, by its size or by where it lands, is refused, not clipped. +#[test] +fn a_result_past_the_warps_reach_is_refused_not_clipped() { + let src = Rect::new(0, 0, 24, 16); + let check = |h: [f64; 9]| check_budget_with_limit(src, &Homography(h), "layer", PixelFormat::RGBA8, DEFAULT_BUDGET); + // 2000016 x 18 px, 138 MB of 8-bit RGBA: from x = 0 it would be cut at 2²⁰; centred it fits. + let err = check([83_334.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).unwrap_err().to_string(); + assert!(err.contains("would reach past ±1048576 px") && err.ends_with("the document was not changed"), "{err}"); + assert!(check([83_334.0, 0.0, -1_000_000.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).is_ok()); + // A small layer moved past the reach, either way on either axis. + for (dx, dy) in [(1_100_000.0, 0.0), (-1_100_000.0, 0.0), (0.0, 1_100_000.0), (0.0, -1_100_000.0)] { + assert!(check([1.0, 0.0, dx, 0.0, 1.0, dy, 0.0, 0.0, 1.0]).is_err(), "{dx}, {dy}"); + } + // Through the command: nothing moves, nothing is lost. + let mut s = session(); + let st = s.active().unwrap(); + let (before, steps) = (st.doc.clone(), st.history.past_len()); + let err = s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 2_000_000, 0]})).unwrap_err().to_string(); + assert!(err.contains("the transformed layer \"Layer 1\" would reach past ±1048576 px"), "{err}"); + let st = s.active().unwrap(); + assert!(st.doc == before && st.history.past_len() == steps, "the document is untouched"); +} + +/// #7807: the stitched layer's 90 % and 15°, a 37708 x 35259 px result that the old 2³⁰ px limit +/// refused, fits the default Memory Usage at 8 bits (5072 MB); at 16 bits it needs Memory Usage +/// raised, and the message says so. +#[test] +fn a_gigapixel_layer_transforms_within_memory_usage() { + let src = Rect::new(0, 0, 35_020, 31_171); + let r = [0.0, 0.0, 35_020.0, 31_171.0]; + let h = relative_matrix(&json!({"scaleX": 90, "scaleY": 90, "rotate": 15}), r).unwrap().unwrap(); + assert_eq!(warp_output_size(src, &h), Some((37_708, 35_259)), "the report's result, past the old limit"); + assert!(check_budget_with_limit(src, &h, "layer \"Layer 1\"", PixelFormat::RGBA8, DEFAULT_BUDGET).is_ok()); + let err = check_budget_with_limit(src, &h, "layer \"Layer 1\"", PixelFormat::RGBA16, DEFAULT_BUDGET).unwrap_err().to_string(); + assert!(err.contains("(10144 MB), more than the 8192 MB Memory Usage allows (Preferences › Performance)"), "{err}"); + assert!(check_budget_with_limit(src, &h, "layer", PixelFormat::RGBA16, 2 * DEFAULT_BUDGET).is_ok()); + // A format without alpha is priced as the warp makes it, with alpha. + let rgb8 = PixelFormat::new(PixelFormat::RGBA8.mode, PixelFormat::RGBA8.sample, false); + assert!(check_budget_with_limit(src, &h, "layer", rgb8, 5071 << 20).is_err()); +} + +/// A 16 x 16 document whose active layer is a 1 x 8 column at x = 10. +fn column() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 2, 11, 10), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +/// Stretch x by `k` about x = 10 (the column's left edge). +fn stretch(k: f64) -> Value { + json!({"matrix": [k, 0, 0, 1, -10.0 * k, 0], "interpolation": "nearest"}) +} + +/// A stretch past the budget is refused with the limit named, and the document, its revision +/// and History stay as they were; within the budget the same stretch applies unclipped. +#[test] +fn a_scale_past_the_pixel_budget_is_refused_and_changes_nothing() { + let mut s = column(); + let st = s.active().unwrap(); + let (before, revision, steps) = (st.doc.clone(), st.revision, st.history.past_len()); + // 1000000 x 10 px of 8-bit RGBA output: about twice the test budget. + let err = s.execute("edit.transform", stretch(1e6)).unwrap_err().to_string(); + assert!(err.starts_with("too large to transform: the transformed layer \"Layer 1\""), "{err}"); + assert!( + err.contains("would be 1000002 x 10 px (39 MB), more than the 20 MB Memory Usage allows") && err.ends_with("the document was not changed"), + "{err}" + ); + // Nothing was allocated, so nothing ran short (#7807). + assert!(!err.contains("not enough memory"), "{err}"); + let st = s.active().unwrap(); + assert!(st.doc == before, "the document is untouched"); + assert_eq!((st.revision, st.history.past_len()), (revision, steps)); + // Within the budget the same stretch still works, nothing clipped. + s.execute("edit.transform", stretch(1e4)).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(0, 2, 10_000, 10)); +} + +#[test] +fn a_group_with_one_layer_past_the_budget_is_not_half_transformed() { + let mut s = column(); + let wide = s.active().unwrap().active_layer.unwrap(); + // Over the column: a 1 px dot, which fits the budget stretched by the same amount. + s.execute("layer.new.layer", json!({})).unwrap(); + let dot = s.active().unwrap().active_layer.unwrap(); + s.edit("paint", |doc, _| { + doc.layer_mut(dot).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 12, 11, 13), &[0.0, 1.0, 0.0, 1.0]); + // Widen the column to 8 px (x 2..10), so it alone needs 800002 x 10 px (31 MB). + doc.layer_mut(wide).unwrap().surface_mut().unwrap().fill_rect(Rect::new(2, 2, 10, 10), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.select", json!({"layer": wide.0})).unwrap(); + s.execute("layer.select", json!({"layer": dot.0, "mode": "add"})).unwrap(); + let group = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + let st = s.active().unwrap(); + assert!(matches!(&st.doc.layer(group).unwrap().content, LayerContent::Group(g) if g.children.len() == 2)); + let (before, revision) = (st.doc.clone(), st.revision); + let k = 1e5; + assert!(s.execute("edit.transform", json!({"layer": group.0, "matrix": [k, 0, 0, 1, -10.0 * k, 0]})).is_err()); + let st = s.active().unwrap(); + assert!(st.doc == before && st.revision == revision, "nothing changed"); + // The layer-level check runs before any child is warped, so even the layer itself + // (not just the edit's copy of the document) is left as it was. + let mut l = st.doc.layer(group).unwrap().clone(); + let h = Homography([k, 0.0, -10.0 * k, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]); + assert!(transform_layer(None, Locks::default(), &mut l, &h, None, Interp::Nearest).is_err()); + assert!(&l == st.doc.layer(group).unwrap(), "no child was transformed"); +} + +/// Only the result's size is priced: a small layer moved 900000 px away (within the warp's +/// reach) and back keeps every pixel. +#[test] +fn moving_a_small_layer_far_off_the_canvas_is_within_budget() { + let mut s = session(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 900_000, -900_000]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(900_010, -899_990, 900_030, -899_980)); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, -900_000, 900_000]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "and back, every pixel kept"); +} + +/// Each priced at its own format, as the warp makes it: an 8-bit outline, mask or channel with +/// alpha is 2 bytes a pixel, so a canvas-high column of it stretched 10⁶ times (34 MB) is over +/// the test budget. +#[test] +fn selections_masks_and_channels_have_the_same_budget() { + // The selection outline of a layer transform. + let mut s = column(); + s.execute("select.rect", json!({"x": 10, "y": 0, "width": 1, "height": 16})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let err = s.execute("edit.transform", stretch(1e6)).unwrap_err().to_string(); + assert!(err.contains("transformed selection would be"), "{err}"); + // Transform Selection. + let err = s.execute("select.transformSelection", stretch(1e6)).unwrap_err().to_string(); + assert!(err.contains("transformed selection would be"), "{err}"); + assert!(s.active().unwrap().doc == before); + // A targeted alpha channel. + let mut s = column(); + s.execute("channel.new", json!({})).unwrap(); + s.edit("paint channel", |doc, _| { + doc.channels[0].surface.fill_rect(Rect::new(10, 0, 11, 16), &[1.0]); + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let mut p = stretch(1e6); + p["target"] = json!({"channel": 0}); + let err = s.execute("edit.transform", p).unwrap_err().to_string(); + assert!(err.contains("transformed mask or channel would be"), "{err}"); + assert!(s.active().unwrap().doc == before); +} + +#[test] +fn scale_via_quad_and_undo() { + let mut s = session(); + s.execute("edit.transform", json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]]})).unwrap(); + let b = active_bounds(&s); + assert!(b.width().abs_diff(40) <= 2 && b.height().abs_diff(20) <= 2, "{b:?}"); + s.undo(); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20)); +} + +#[test] +fn affine_matrix_and_perspective() { + let mut s = session(); + // Translate by (40, 50). + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); + // Perspective: top edge narrower than the bottom. + s.execute("edit.transform", json!({"quad": [[55, 60], [65, 60], [75, 70], [45, 70]]})).unwrap(); + let b = active_bounds(&s); + assert!(b.x0 <= 46 && b.x1 >= 74, "{b:?}"); + assert!(s.execute("edit.transform", json!({"quad": [[0, 0], [0, 0], [0, 0], [0, 0]]})).is_err()); +} + +#[test] +fn background_becomes_layer_0() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); + s.execute("edit.transform", json!({"quad": [[0, 0], [20, 0], [20, 20], [0, 20]]})).unwrap(); + let st = s.active().unwrap(); + let l = &st.doc.layers[0]; + assert_eq!(l.name, "Layer 0"); + assert!(l.surface().unwrap().format().alpha); + assert_eq!(l.surface().unwrap().pixel(30, 30)[3], 0.0, "revealed area is transparent"); +} + +/// `locked_for_transform` (what Free Transform asks before its box opens, #2585) agrees with +/// what `edit.transform` refuses at commit: a position lock, its own or a group's; never the +/// Background's (it becomes Layer 0). +#[test] +fn locked_for_transform_matches_the_commit() { + let quad = json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]]}); + let lock = |s: &mut Session, id: LayerId, on: bool| { + s.edit("lock", |doc, _| { + doc.layer_mut(id).unwrap().locks.position = on; + Ok(()) + }) + .unwrap(); + }; + let mut s = session(); + let layer = s.active().unwrap().active_layer.unwrap(); + lock(&mut s, layer, true); + assert!(locked_for_transform(&s.active().unwrap().doc, layer)); + assert!(s.execute("edit.transform", quad.clone()).is_err()); + lock(&mut s, layer, false); + let group = LayerId(s.execute("layer.groupLayers", json!({"layer": layer.0})).unwrap()["layer"].as_u64().unwrap()); + lock(&mut s, group, true); + s.execute("layer.select", json!({"layer": layer.0})).unwrap(); + assert!(locked_for_transform(&s.active().unwrap().doc, layer), "the group's lock reaches the layer"); + assert!(s.execute("edit.transform", quad.clone()).is_err()); + let bg = s.active().unwrap().doc.layers[0].id; + assert!(!locked_for_transform(&s.active().unwrap().doc, bg), "the Background transforms"); +} + +#[test] +fn with_selection_only_selected_pixels_move() { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50]})).unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + assert_eq!(surf.pixel(15, 15)[3], 0.0, "lifted area is cleared"); + assert_eq!(surf.pixel(25, 15)[3], 1.0, "unselected part stays"); + assert_eq!(surf.pixel(15, 65)[3], 1.0, "moved pixels land"); + let sel = st.doc.selection.as_ref().unwrap().content_bounds(); + assert_eq!((sel.y0, sel.y1), (60, 70), "selection moves too"); +} + +#[test] +fn with_selection_bounds_drop_the_vacated_area() { + // #1097: moving every pixel through a selection left transparent but coloured pixels + // behind, so the layer bounds were the union of the old and new positions. + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 10})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 50, 0]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(60, 10, 80, 20)); +} + +#[test] +fn type_layers_transform_as_vectors() { + let mut s = session(); + let r = s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi", "size": 20})).unwrap(); + let id = r["layer"].as_u64().unwrap(); + let w0 = active_bounds(&s).width(); + s.execute("edit.transform", json!({"layer": id, "matrix": [2, 0, 0, 2, -10, -50]})).unwrap(); + let w1 = active_bounds(&s).width(); + assert!(w1 as f32 > w0 as f32 * 1.8, "{w0} → {w1}"); + let st = s.active().unwrap(); + let LayerContent::Text(t) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!() }; + assert!((t.transform.m[0] - 2.0).abs() < 1e-9); + // Perspective on type is refused, like Photoshop. + assert!(s.execute("edit.transform", json!({"layer": id, "quad": [[0, 0], [10, 0], [12, 10], [-2, 10]]})).is_err()); +} + +#[test] +fn shapes_move_and_transform_as_vectors() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); + s.execute("layer.translate", json!({"dx": 30, "dy": 5})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(40, 15, 80, 35)); + s.execute("edit.transform", json!({"matrix": [2, 0, 0, 2, -40, -15]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(40, 15, 120, 55)); + // Distort maps the path and keeps a live shape (#3009): the rectangle's corners go to the quad. + let quad = [[40.0, 15.0], [120.0, 15.0], [130.0, 55.0], [30.0, 55.0]]; + s.execute("edit.transform", json!({ "quad": quad })).unwrap(); + let st = s.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("still a shape layer") }; + let mut anchors: Vec<[f64; 2]> = sh.path.subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); + let mut want = quad.to_vec(); + anchors.sort_by(|a, b| a.partial_cmp(b).unwrap()); + want.sort_by(|a, b| a.partial_cmp(b).unwrap()); + assert!(anchors.iter().zip(&want).all(|(a, b)| (a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6), "{anchors:?}"); + assert!(sh.live.is_none(), "the live rectangle is now a path"); + assert_eq!(active_bounds(&s), Rect::new(30, 15, 130, 55)); + // Warp bends the path too: the arc adds anchors along the curved edges. + s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap(); + let st = s.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("still a shape layer") }; + assert!(sh.path.subpaths[0].knots.len() > 4, "{}", sh.path.subpaths[0].knots.len()); + assert!(!active_bounds(&s).is_empty()); +} + +/// A gradient fill layer whose mask (a selection when it was made) frames the gradient over +/// 10..40, with the cached render a PSD import gives it: exactly the pixels the fill renders. +fn cached_gradient_fill() -> Session { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + s.execute("layer.newFillLayer.gradient", json!({"from": "#ff0000", "to": "#0000ff", "angle": 0})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.edit("cache", |doc, active| { + let (fmt, canvas) = (doc.pixel_format(), doc.bounds()); + let l = doc.layer_mut(active.unwrap()).unwrap(); + let LayerContent::Fill(f) = &l.content else { panic!("a fill layer") }; + let buf = photocraft_compose::render_fill_content(l, f, canvas, &[]); + let mut surface = Surface::new(fmt); + let vals: Vec = buf.px.iter().flat_map(|p| photocraft_raster::from_rgba(&fmt, *p)).collect(); + surface.write_region(canvas, &vals); + l.fill_cache = Some(photocraft_doc::FillCache { fill: f.clone(), surface }); + Ok(()) + }) + .unwrap(); + s +} + +/// How far the composite is from the composite with the fill re-rendered from its model +/// (cache dropped): the largest channel difference. +fn off_from_fresh(s: &Session) -> f32 { + let st = s.active().unwrap(); + let mut fresh: Document = (*st.doc).clone(); + fresh.layer_mut(st.active_layer.unwrap()).unwrap().fill_cache = None; + let (a, b) = (photocraft_compose::render(&st.doc, st.doc.bounds()).px, photocraft_compose::render(&fresh, fresh.bounds()).px); + a.iter().zip(&b).flat_map(|(p, q)| p.iter().zip(q).map(|(x, y)| (x - y).abs())).fold(0.0, f32::max) +} + +#[test] +fn transforming_a_fill_layer_drops_its_stale_cached_render() { + let mut s = cached_gradient_fill(); + let off = off_from_fresh(&s); + assert!(off < 0.01, "the cache is the fill's own render: {off}"); + // The mask (and so the gradient's frame) moves 50 px right and doubles in height. + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 2, 50, 0]})).unwrap(); + let off = off_from_fresh(&s); + assert!(off < 0.01, "the composite shows the fill laid out in its new frame, not the old render: {off}"); +} + +#[test] +fn warping_a_fill_layer_drops_its_stale_cached_render() { + let mut s = cached_gradient_fill(); + s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap(); + let off = off_from_fresh(&s); + assert!(off < 0.01, "the composite shows the fill laid out in its new frame, not the old render: {off}"); +} + +#[test] +fn type_moves_with_the_move_command() { + let mut s = session(); + s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi", "size": 20})).unwrap(); + let b0 = active_bounds(&s); + s.execute("layer.translate", json!({"dx": 20, "dy": 10})).unwrap(); + let b1 = active_bounds(&s); + assert_eq!((b1.x0 - b0.x0, b1.y0 - b0.y0), (20, 10)); +} + +// ---- Layer masks and targets (#205) ---- + +/// `session()` plus a reveal-all mask with `hide` painted black (linked unless `linked` is false). +fn masked(hide: &[Rect], linked: bool) -> Session { + masked_depth(hide, linked, 8) +} + +fn masked_depth(hide: &[Rect], linked: bool, depth: u32) -> Session { + let mut s = session_depth(depth); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.edit("mask", |doc, active| { + let m = doc.layer_mut(active.unwrap()).unwrap().mask.as_mut().unwrap(); + for r in hide { + m.surface.fill_rect(*r, &[0.0]); + } + m.linked = linked; + Ok(()) + }) + .unwrap(); + s +} + +fn mask_at(s: &Session, x: i32, y: i32) -> f32 { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0) +} + +fn alpha_at(s: &Session, x: i32, y: i32) -> f32 { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)[3] +} + +#[test] +fn linked_raster_mask_moves_with_the_pixels() { + let mut s = masked(&[Rect::new(10, 10, 20, 20)], true); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); + assert!(mask_at(&s, 55, 65) < 0.01, "the hidden half moved with the pixels"); + assert!(mask_at(&s, 65, 65) > 0.99); + assert!(mask_at(&s, 15, 15) > 0.99, "nothing hidden left behind"); +} + +#[test] +fn linked_mask_with_a_selection_moves_only_the_selected_region() { + // The selection covers the left half of the red rect; the mask hides its left quarter + // (selected) and its right quarter (not selected). + let mut s = masked(&[Rect::new(10, 10, 15, 20), Rect::new(25, 10, 30, 20)], true); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50]})).unwrap(); + // Moved pixels and their mask line up. + assert_eq!(alpha_at(&s, 12, 65), 1.0); + assert!(mask_at(&s, 12, 65) < 0.01, "selected hidden quarter moved"); + assert!(mask_at(&s, 17, 65) > 0.99, "selected visible quarter moved"); + // The vacated area reads as revealed (default), with transparent pixels. + assert_eq!(alpha_at(&s, 12, 15), 0.0); + assert!(mask_at(&s, 12, 15) > 0.99); + // The unselected part of the mask stays, aligned with the unselected pixels. + assert_eq!(alpha_at(&s, 27, 15), 1.0); + assert!(mask_at(&s, 27, 15) < 0.01, "unselected mask stays put"); + assert!(mask_at(&s, 27, 65) > 0.99, "and isn't copied along"); + // Every pixel's mask value is where it was relative to the pixel. + for (x, y) in [(11, 61), (14, 69), (15, 61), (19, 69)] { + let want = if x < 15 { 0.0 } else { 1.0 }; + assert!((mask_at(&s, x, y) - want).abs() < 0.01, "({x},{y})"); + } +} + +#[test] +fn unlinked_mask_stays_put() { + let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); + assert!(mask_at(&s, 15, 15) < 0.01); + assert!(mask_at(&s, 55, 65) > 0.99); + // With a selection too. + let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50]})).unwrap(); + assert!(mask_at(&s, 15, 15) < 0.01 && mask_at(&s, 15, 65) > 0.99); +} + +#[test] +fn targeted_unlinked_mask_transforms_alone() { + let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50], "target": "mask"})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "pixels untouched"); + assert!(mask_at(&s, 55, 65) < 0.01, "mask moved"); + assert!(mask_at(&s, 15, 15) > 0.99, "vacated area reads as the default"); + s.undo(); + assert!(mask_at(&s, 15, 15) < 0.01, "one undo step"); + // With a selection, only its part of the mask. + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 5, "height": 10})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 50], "target": "mask"})).unwrap(); + assert!(mask_at(&s, 12, 65) < 0.01 && mask_at(&s, 12, 15) > 0.99); + assert!(mask_at(&s, 17, 15) < 0.01, "unselected mask stays"); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "pixels untouched"); +} + +#[test] +fn targeted_linked_mask_moves_with_its_layer() { + // Photoshop: a linked mask can't move without its layer. + let mut s = masked(&[Rect::new(10, 10, 20, 20)], true); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50], "target": "mask"})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(50, 60, 70, 70)); + assert!(mask_at(&s, 55, 65) < 0.01); +} + +#[test] +fn targeted_alpha_channel_transforms_alone() { + let mut s = session(); + s.execute("channel.new", json!({})).unwrap(); + s.edit("paint channel", |doc, _| { + doc.channels[0].surface.fill_rect(Rect::new(10, 10, 20, 20), &[1.0]); + Ok(()) + }) + .unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 40, 50], "target": {"channel": 0}})).unwrap(); + let st = s.active().unwrap(); + let ch = &st.doc.channels[0].surface; + assert!(ch.sample_channel(55, 65, 0) > 0.99 && ch.sample_channel(15, 15, 0) < 0.01); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "layer untouched"); +} + +/// The Channels panel targets an alpha channel: Edit › Transform › Flip Horizontal and a +/// 50% `edit.transform` (no `target` param) work on the channel, not the layer (BUG-207-4). +#[test] +fn transforms_follow_the_targeted_alpha_channel() { + let mut s = session(); + s.execute("channel.new", json!({})).unwrap(); + s.edit("paint channel", |doc, _| { + let ch = &mut doc.channels[0].surface; + ch.fill_rect(Rect::new(10, 10, 20, 20), &[1.0]); + ch.fill_rect(Rect::new(10, 10, 12, 20), &[0.5]); + Ok(()) + }) + .unwrap(); + s.execute("channel.target", json!({"channel": 0})).unwrap(); + let layer = |s: &Session| crate::active_layer_of(s).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 100, 100)); + let (pixels, past) = (layer(&s), s.active().unwrap().history.past_len()); + s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); + // 8-bit channel: 0.5 is stored as 128/255. + let ch = |s: &Session, x, y| (s.active().unwrap().doc.channels[0].surface.sample_channel(x, y, 0) * 10.0).round() / 10.0; + assert_eq!((ch(&s, 19, 15), ch(&s, 10, 15)), (0.5, 1.0), "the channel flips within its frame"); + assert!(layer(&s) == pixels, "the layer is untouched"); + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "one undo step"); + s.execute("edit.transform", json!({"matrix": [0.5, 0, 0, 0.5, 0, 0], "interpolation": "nearest"})).unwrap(); + assert_eq!((ch(&s, 7, 7), ch(&s, 15, 15)), (1.0, 0.0), "the channel scales to 50%"); + assert!(layer(&s) == pixels, "the layer is untouched"); + s.undo(); + s.undo(); + assert_eq!((ch(&s, 10, 15), ch(&s, 19, 15)), (0.5, 1.0)); +} + +#[test] +fn transform_targets_fail_gracefully() { + let mut s = session(); + let m = json!([1, 0, 0, 1, 5, 5]); + assert!(s.execute("edit.transform", json!({"matrix": m, "target": "mask"})).is_err(), "no mask"); + assert!(s.execute("edit.transform", json!({"matrix": m, "target": {"channel": 9}})).is_err()); + assert!(s.execute("edit.transform", json!({"matrix": m, "target": "quickMask"})).is_err()); + // Unknown target shapes fall back to the pixels. + s.execute("edit.transform", json!({"matrix": m, "target": 7})).unwrap(); + s.execute("edit.transform", json!({"matrix": m, "target": {"channel": "x"}})).unwrap(); + // Selections that miss the mask entirely transform nothing, without panicking. + let mut s = masked(&[Rect::new(10, 10, 20, 20)], false); + s.execute("select.rect", json!({"x": 80, "y": 80, "width": 5, "height": 5})).unwrap(); + let _ = s.execute("edit.transform", json!({"matrix": [1e9, 0, 0, 1e9, 0, 0], "target": "mask"})); + let _ = s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 1e12, 0], "target": "mask"})); +} + +#[test] +fn split_gray_selected_rejects_non_gray() { + let s = Surface::new(PixelFormat::RGBA8); + let mut sel = Surface::new(PixelFormat::GRAY8); + sel.fill_rect(Rect::new(0, 0, 4, 4), &[1.0]); + assert!(matches!(split_gray_selected(&s, &sel), Ok(None))); +} + +/// #2630: type can't be partly transformed, so a selection doesn't narrow the frame: Free +/// Transform (and the frame-based presets) act on the whole type layer. +#[test] +fn a_selection_does_not_narrow_a_type_layers_frame() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 120})).unwrap(); + s.execute("type.create", json!({"x": 20, "y": 60, "text": "Hello", "size": 36})).unwrap(); + let whole = active_bounds(&s); + s.execute("select.rect", json!({"x": whole.x0, "y": whole.y0, "width": whole.width() / 2, "height": whole.height()})).unwrap(); + let st = s.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert_eq!(transform_bounds(&st.doc, l), whole, "the frame is the whole type layer"); + // Corners of the frame moved 10 px right: a pure translation of the whole text. + let q = [[whole.x0 + 10, whole.y0], [whole.x1 + 10, whole.y0], [whole.x1 + 10, whole.y1], [whole.x0 + 10, whole.y1]]; + s.execute("edit.transform", json!({"quad": q})).unwrap(); + let moved = active_bounds(&s); + assert!(moved.x0.abs_diff(whole.x0 + 10) <= 1 && moved.width().abs_diff(whole.width()) <= 1, "{whole:?} -> {moved:?}"); + // Rotate 180° turns it about its own centre, not the selection's. + s.execute("edit.transform.rotate180", json!({})).unwrap(); + let turned = active_bounds(&s); + assert!(turned.x0.abs_diff(moved.x0) <= 2 && turned.x1.abs_diff(moved.x1) <= 2, "{moved:?} -> {turned:?}"); + // A pixel layer still frames only the selected pixels. + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 5, "height": 10})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(transform_bounds(&st.doc, st.doc.layer(st.active_layer.unwrap()).unwrap()), Rect::new(10, 10, 15, 20)); +} + +/// #5297: the box Free Transform opens with a selection is the selection's own rectangle, +/// not the part of it the layer fills; type still moves whole, and a selection that holds none +/// of the layer leaves nothing to transform. +#[test] +fn the_frame_is_the_selections_own_bounds() { + let mut s = session(); + let frame = |s: &Session| { + let st = s.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + (transform_frame(&st.doc, l), transform_bounds(&st.doc, l)) + }; + let content = Rect::new(10, 10, 30, 20); + assert_eq!(frame(&s), (content, content), "no selection: the content"); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 15, "height": 40})).unwrap(); + assert_eq!(frame(&s), (Rect::new(5, 5, 20, 45), Rect::new(10, 10, 20, 20))); + s.execute("select.rect", json!({"x": 60, "y": 60, "width": 10, "height": 10})).unwrap(); + assert!(frame(&s).0.is_empty(), "nothing of the layer is selected"); + + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 120})).unwrap(); + s.execute("type.create", json!({"x": 20, "y": 60, "text": "Hello", "size": 36})).unwrap(); + let whole = active_bounds(&s); + s.execute("select.rect", json!({"x": whole.x0, "y": whole.y0, "width": whole.width() / 2, "height": whole.height()})).unwrap(); + assert_eq!(frame(&s), (whole, whole), "type moves whole"); +} + +#[test] +fn group_transform_ignores_selections_inside_its_children() { + group_transform_with_selection(Rect::new(10, 10, 15, 15)); +} + +#[test] +fn group_transform_ignores_selections_outside_its_children() { + group_transform_with_selection(Rect::new(70, 70, 80, 80)); +} + +#[test] +fn group_transform_presets_rotate_about_the_whole_group() { + for depth in [8, 16, 32] { + for x in [10, 70] { + let mut s = masked_depth(&[Rect::new(10, 10, 15, 20)], true, depth); + let child = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + s.execute("select.rect", json!({"x": x, "y": 10, "width": 5, "height": 5})).unwrap(); + s.execute("edit.transform.rotate180", json!({})).unwrap(); + let layer = s.active().unwrap().doc.layer(child).unwrap(); + assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 30, 20), "rotate about the group's centre, not the selection's"); + let mask = &layer.mask.as_ref().unwrap().surface; + assert_eq!(mask.sample_channel(27, 15, 0), 0.0); + assert_eq!(mask.sample_channel(12, 15, 0), 1.0); + } + } +} + +fn group_transform_with_selection(selection: Rect) { + for depth in [8, 16, 32] { + for nested in [false, true] { + let mut s = masked_depth(&[Rect::new(10, 10, 15, 20)], true, depth); + let child = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + if nested { + s.execute("layer.groupLayers", json!({})).unwrap(); + } + s.execute("select.rect", json!({"x": selection.x0, "y": selection.y0, "width": selection.width(), "height": selection.height()})).unwrap(); + let steps = s.active().unwrap().history.entries().len(); + let result = s.execute("edit.transform", json!({"quad": [[10, 10], [50, 10], [50, 30], [10, 30]], "interpolation": "nearest"})).unwrap(); + assert_eq!(result["rect"], json!([10.0, 10.0, 30.0, 20.0]), "frame must include the whole group (nested={nested})"); + let st = s.active().unwrap(); + let layer = st.doc.layer(child).unwrap(); + assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 50, 30)); + let mask = &layer.mask.as_ref().unwrap().surface; + assert_eq!(mask.sample_channel(19, 20, 0), 0.0, "the linked mask scales with its complete layer"); + assert_eq!(mask.sample_channel(21, 20, 0), 1.0); + assert_eq!(st.history.entries().len(), steps + 1); + assert!(s.undo()); + let st = s.active().unwrap(); + let layer = st.doc.layer(child).unwrap(); + assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(10, 10, 30, 20)); + assert_eq!(layer.mask.as_ref().unwrap().surface.sample_channel(19, 15, 0), 1.0); + assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), selection); + assert!(s.redo()); + assert_eq!(s.active().unwrap().doc.layer(child).unwrap().surface().unwrap().content_bounds(), Rect::new(10, 10, 50, 30)); + } + } +} + +#[test] +fn feathered_selection_identity_transform_preserves_pixels() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "transparent"})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); + s.execute("select.modify.feather", json!({"radius": 1})).unwrap(); + + let mut before_px = Vec::new(); + for y in 0..16 { + for x in 0..16 { + before_px.push(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()); + } + } + + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 0], "interpolation": "nearest"})).unwrap(); + + let mut after_px = Vec::new(); + for y in 0..16 { + for x in 0..16 { + after_px.push(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()); + } + } + + assert_eq!(before_px, after_px, "feathered selection identity transform must preserve all pixels"); + let p4_8 = s.execute("document.pixel", json!({"x": 4, "y": 8})).unwrap(); + assert_eq!(p4_8, json!([1.0, 0.0, 0.0, 1.0]), "(4,8) must remain opaque red"); + + // Undo restores original document. + s.execute("edit.undo", json!({})).unwrap(); + let undo_p4_8 = s.execute("document.pixel", json!({"x": 4, "y": 8})).unwrap(); + assert_eq!(undo_p4_8, json!([1.0, 0.0, 0.0, 1.0])); + + // Locked layer still refuses transform even if identity. + s.execute("layer.setProps", json!({"locks": {"position": true}})).unwrap(); + assert!(s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 0]})).is_err(), "locked layer refuses identity transform"); +} + +/// A 1 x 8 px column on a 256 x 256 canvas (#3773). +fn column_session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 256, "height": 256})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().fill_rect(Rect::new(100, 100, 101, 108), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +fn opaque_green(s: &Session, x: i32, y: i32) -> bool { + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + (surf.sample_channel(x, y, 1) - 1.0).abs() < 1e-3 && (surf.sample_channel(x, y, 3) - 1.0).abs() < 1e-3 +} + +/// The "pixel stretch" (#3773): scales far past 1000% are taken, and the stretched column stays +/// solid along its whole length. +#[test] +fn a_one_pixel_column_stretches_5000_percent() { + let mut s = column_session(); + s.execute("edit.transform", json!({"quad": [[100, 100], [150, 100], [150, 108], [100, 108]]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(100, 100, 150, 108)); + for x in [100, 101, 125, 149] { + for y in 100..108 { + assert!(opaque_green(&s, x, y), "({x}, {y})"); + } + } +} + +/// The technique as done in Photoshop: select a 1 px column of an image and stretch it across. +#[test] +fn a_selected_column_stretches_solid_over_the_image() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 256, "height": 256})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(Rect::new(0, 0, 256, 256), &[1.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(10, 0, 11, 256), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 0, "width": 1, "height": 256})).unwrap(); + s.execute("edit.transform", json!({"quad": [[10, 0], [250, 0], [250, 256], [10, 256]]})).unwrap(); + for x in [10, 11, 100, 200, 249] { + assert!(opaque_green(&s, x, 128), "x = {x}"); + } + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + assert!(surf.sample_channel(250, 128, 0) > 0.999 && surf.sample_channel(9, 128, 0) > 0.999, "the image either side is untouched"); +} + +/// Free Transform keeps pixels moved off the canvas, as Photoshop does: an 8 x 8 layer moved +/// three canvas widths right and back comes back whole. +#[test] +fn a_layer_moved_far_off_the_canvas_and_back_keeps_its_pixels() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..8 { + for x in 0..8 { + surf.fill_rect(Rect::new(20 + x, 20 + y, 21 + x, 21 + y), &[x as f32 / 8.0, y as f32 / 8.0, 0.5, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + let pixels = |s: &Session| { + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + (0..8 * 8 * 4).map(|i| surf.sample_channel(20 + i / 4 % 8, 20 + i / 32, (i % 4) as usize)).collect::>() + }; + let before = pixels(&s); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 192, 0]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(212, 20, 220, 28)); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, -192, 0]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(20, 20, 28, 28)); + assert_eq!(pixels(&s), before); +} + +#[test] +fn relative_params_scale_and_rotate_about_the_frame_centre() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 20, "y": 30, "width": 40, "height": 20})).unwrap(); + s.execute("edit.fill", json!({"contents": "black"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + // 50% about the centre (40, 40), then 10 px right: the content ends at x 40..60, y 35..45. + let r = s.execute("edit.transform", json!({"scaleX": 50, "scaleY": 50, "dx": 10})).unwrap(); + let rect: Vec = serde_json::from_value(r["rect"].clone()).unwrap(); + assert_eq!(rect, [20.0, 30.0, 60.0, 50.0], "the reported frame is the source frame"); + let bounds = |s: &Session| { + let d = s.active().unwrap(); + let b = transform_bounds(&d.doc, d.doc.layer(d.active_layer.unwrap()).unwrap()); + (b.x0, b.y0, b.x1, b.y1) + }; + assert_eq!(bounds(&s), (40, 35, 60, 45)); + // A quarter turn about the centre (50, 40) swaps the frame's sides. + s.execute("edit.transform", json!({"rotate": 90})).unwrap(); + assert_eq!(bounds(&s), (45, 30, 55, 50)); + for bad in [json!({"scaleX": 0}), json!({"rotate": "x"}), json!({"dx": f64::NAN})] { + assert!(s.execute("edit.transform", bad.clone()).is_err(), "{bad}"); + } +} + +/// #5846: a shape's Density and Feather render past its path (over the whole canvas below +/// 100 %), but its transform frame follows the path, as in Photoshop: the same box as the hard +/// shape for Free Transform, the Move tool's controls and snapping, never the canvas. +#[test] +fn a_soft_shapes_frame_follows_its_path() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + let id = s.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 60, 40], "fill": "#000000"})).unwrap()["layer"].as_u64().unwrap(); + let id = photocraft_doc::LayerId(id); + let boxes = |s: &Session| { + let st = s.active().unwrap(); + let l = st.doc.layer(id).unwrap(); + (transform_bounds(&st.doc, l), transform_frame(&st.doc, l), crate::snap::layer_rect(&st.doc, id)) + }; + let hard = boxes(&s); + assert_eq!(hard.0, Rect::new(20, 30, 80, 70), "the hard shape's frame"); + s.execute("layer.vectorMask.edit", json!({"density": 60, "feather": 20})).unwrap(); + { + let st = s.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(id).unwrap().content else { panic!("a shape") }; + let painted = photocraft_compose::bounds::content_bounds(sh.cache.as_ref().unwrap()); + assert_eq!(painted, st.doc.bounds(), "the soft fill renders over the whole canvas"); + } + let soft = boxes(&s); + assert_eq!(soft, hard, "the frame ignores Density and Feather"); + assert_ne!(soft.1, s.active().unwrap().doc.bounds()); + // Feather alone (density 100 %) leaves the frame on the path too, not grown by the blur. + s.execute("layer.vectorMask.edit", json!({"density": 100, "feather": 20})).unwrap(); + assert_eq!(boxes(&s), hard); + // Free Transform scales about the path's centre, not the canvas's. + s.execute("edit.transform", json!({"layer": id.0, "scaleX": 200})).unwrap(); + let st = s.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(id).unwrap().content else { panic!("a shape") }; + let (x0, y0, x1, y1) = sh.path.control_bounds().unwrap(); + assert_eq!((x0.round(), y0.round(), x1.round(), y1.round()), (-10.0, 30.0, 110.0, 70.0)); + assert_eq!((sh.density, sh.feather), (1.0, 20.0), "the transform keeps the soft settings"); +} + +/// A stroked soft shape's frame is the hard shape's rendered frame for every stroke alignment: +/// a centred stroke reaches half its width past the path, not its full width; both stop at +/// the canvas edge. +#[test] +fn a_stroked_soft_shapes_frame_matches_the_hard_shapes() { + for (align, reach, x) in [("center", 5, 50), ("inside", 0, 50), ("outside", 10, 50), ("center", 5, -20)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + let stroke = json!({"width": 10, "color": "#ff0000", "align": align, "join": "round"}); + let id = s.execute("shape.create", json!({"kind": "rect", "rect": [x, 50, 60, 40], "fill": "#000000", "stroke": stroke})).unwrap()["layer"] + .as_u64() + .unwrap(); + let id = photocraft_doc::LayerId(id); + let boxes = |s: &Session| { + let st = s.active().unwrap(); + let l = st.doc.layer(id).unwrap(); + (transform_bounds(&st.doc, l), transform_frame(&st.doc, l), crate::snap::layer_rect(&st.doc, id)) + }; + let hard = boxes(&s); + // Hand-computed: the path is x..x + 60 x 50..90, the stroke reaches `reach` px past it. + assert_eq!(hard.0, Rect::new((x - reach).max(0), 50 - reach, x + 60 + reach, 90 + reach), "{align} at {x}: the hard shape's frame"); + s.execute("layer.vectorMask.edit", json!({"density": 60, "feather": 8})).unwrap(); + assert_eq!(boxes(&s), hard, "{align} at {x}: Density and Feather leave the frame"); + s.execute("layer.vectorMask.edit", json!({"density": 100, "feather": 8})).unwrap(); + assert_eq!(boxes(&s), hard, "{align} at {x}: Feather alone leaves the frame"); + } +} From c0c06bc58a9f6345f0e958e3ea95fff1862c3cdd Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:09 +0000 Subject: [PATCH 027/259] refactor(engine): move type_cmds.rs tests to type_cmds/tests.rs --- crates/engine/src/type_cmds.rs | 798 +-------------------------- crates/engine/src/type_cmds/tests.rs | 795 ++++++++++++++++++++++++++ 2 files changed, 796 insertions(+), 797 deletions(-) create mode 100644 crates/engine/src/type_cmds/tests.rs diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rs index 82ac7a7915..67fc34be60 100644 --- a/crates/engine/src/type_cmds.rs +++ b/crates/engine/src/type_cmds.rs @@ -1184,800 +1184,4 @@ fn step_size(s: &mut Session, p: &Value, up: bool, default_by: f32) -> Result Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 100, "background": "transparent"})).unwrap(); - s - } - - fn text_layer(s: &Session, id: u64) -> TextLayer { - match &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content { - LayerContent::Text(t) => t.clone(), - other => panic!("{}", other.kind_name()), - } - } - - #[test] - fn named_face_metadata_replaces_old_postscript_identity() { - let mut style = CharStyle { font_family: "Inter".into(), postscript_name: Some("Inter-Regular".into()), ..Default::default() }; - apply_char_props(&mut style, &json!({"fontStyle": "SemiBold"})); - assert_eq!(style.weight, 600); - assert_eq!(style.postscript_name.as_deref(), Some("Inter-SemiBold")); - apply_char_props(&mut style, &json!({"weight": 400})); - // #3556: a style change re-resolves to the installed face instead of leaving it nameless. - assert_eq!(style.postscript_name.as_deref(), Some("Inter-Regular")); - assert!(style.font_style.is_empty()); - apply_char_props(&mut style, &json!({"fontStyle": "unknown-style"})); - assert_eq!(style.postscript_name.as_deref(), Some("Inter-Regular")); - apply_char_props(&mut style, &json!({"fontStyle": "Regular", "postscriptName": "ExplicitFace"})); - assert_eq!(style.postscript_name.as_deref(), Some("ExplicitFace")); - } - - /// #3556: a font named by family stores the installed face's PostScript name, so PSD export - /// names a real font instead of inventing "-Regular" that Photoshop calls missing. - #[test] - fn a_family_font_gets_the_installed_postscript_name() { - let mut style = CharStyle { font_family: "Inter".into(), ..Default::default() }; - apply_char_props(&mut style, &json!({"font": "Inter"})); - assert_eq!(style.font_family, "Inter"); - assert_eq!(style.postscript_name.as_deref(), Some("Inter-Regular"), "resolved from the font database"); - // A weight picks that face's name. - apply_char_props(&mut style, &json!({"font": "Inter", "weight": 600})); - assert_eq!(style.postscript_name.as_deref(), Some("Inter-SemiBold")); - // A weight no face has (a variable font's axis, or between two faces) names no face, so - // layout still matches the requested weight instead of a nearby face's. - apply_char_props(&mut style, &json!({"weight": 650})); - assert!(style.postscript_name.is_none(), "{:?}", style.postscript_name); - // A family PhotoCraft does not have keeps no name; the export falls back as before. - let mut absent = CharStyle { font_family: "No Such Family 123".into(), ..Default::default() }; - apply_char_props(&mut absent, &json!({"font": "No Such Family 123"})); - assert!(absent.postscript_name.is_none()); - } - - /// Picking a style or weight resets the weight axis to it; other axes keep their values (#2985). - #[test] - fn a_style_or_weight_resets_the_weight_axis() { - let mut style = CharStyle::default(); - apply_char_props(&mut style, &json!({"variations": {"wght": 650, "wdth": 80}})); - apply_char_props(&mut style, &json!({"fontStyle": "Bold"})); - let axes = |s: &CharStyle| s.variations.iter().map(|v| (v.axis.clone(), v.value)).collect::>(); - assert_eq!(axes(&style), [("wdth".to_string(), 80.0)]); - apply_char_props(&mut style, &json!({"variations": {"wght": 650}})); - apply_char_props(&mut style, &json!({"weight": 300})); - assert_eq!(axes(&style), [("wdth".to_string(), 80.0)]); - apply_char_props(&mut style, &json!({"fontStyle": "Light", "variations": {"wght": 350}})); - assert_eq!(axes(&style), [("wdth".to_string(), 80.0), ("wght".to_string(), 350.0)], "same-call values apply after the style"); - } - - #[test] - fn absurd_type_size_and_tracking_are_rejected_as_bad_params() { - let mut s = session(); - assert!(matches!( - s.execute("type.create", json!({"text": "abc", "size": 1e30})), - Err(EngineError::BadParams { cmd, .. }) if cmd == "type.create" - )); - - let id = s.execute("type.create", json!({"text": "abc", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - let before = text_layer(&s, id); - for params in [json!({"layer": id, "tracking": 1e30}), json!({"layer": id, "runs": [{"start": 0, "end": 3, "tracking": 1e30}]})] { - assert!(matches!( - s.execute("type.edit", params), - Err(EngineError::BadParams { cmd, .. }) if cmd == "type.edit" - )); - assert_eq!(text_layer(&s, id).runs, before.runs); - } - assert!(matches!( - s.execute("type.setStyle", json!({"layer": id, "tracking": 1e30})), - Err(EngineError::BadParams { cmd, .. }) if cmd == "type.setStyle" - )); - assert_eq!(text_layer(&s, id).runs, before.runs); - } - - /// A font that arrives after the layer was drawn (served fonts on the web) re-renders it with - /// no history step, and a clean document stays clean. - #[test] - fn refreshing_type_layers_takes_no_history_step() { - let mut s = session(); - let id = LayerId(s.execute("type.create", json!({"text": "Hello", "size": 24})).unwrap()["layer"].as_u64().unwrap()); - let doc_id = s.active().unwrap().doc.id; - // Stale pixels, and a document saved in this state. - { - let st = s.active_mut().unwrap(); - let Some(Layer { content: LayerContent::Text(t), .. }) = Arc::make_mut(&mut st.doc).layer_mut(id) else { panic!("not a type layer") }; - t.cache = None; - st.saved_revision = st.revision; - } - let rev = s.active().unwrap().revision; - let unknown = [(doc_id, LayerId(u64::MAX)), (photocraft_doc::DocId(u64::MAX), id)]; - assert!(s.refresh_type_layers(&[&[(doc_id, id)][..], &unknown].concat()).is_empty()); - assert!(text_layer(&s, id.0).cache.is_some()); - let st = s.active().unwrap(); - assert!(st.revision > rev); - assert_eq!(st.saved_revision, st.revision, "still clean"); - // The only history step is still the creation. - assert!(s.undo()); - assert!(s.active().unwrap().doc.layer(id).is_none()); - } - - #[test] - fn create_renders_and_is_undoable() { - let mut s = session(); - let r = s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hello", "size": 24, "color": "#ff0000"})).unwrap(); - let id = r["layer"].as_u64().unwrap(); - let b = r["bounds"].as_array().unwrap(); - assert!(b[0].as_i64().unwrap() >= 9 && b[3].as_i64().unwrap() <= 56, "{b:?}"); - let t = text_layer(&s, id); - assert_eq!(t.text, "Hello"); - assert_eq!(t.runs[0].style.size_pt, 24.0); - assert!(t.cache.is_some() && t.psd_raw.is_some()); - let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); - assert_eq!(l.name, "Hello"); - // Red pixels exist. - let c = t.cache.as_ref().unwrap(); - let r = c.content_bounds(); - assert!(c.read_region(r).as_chunks::<4>().0.iter().any(|p| p[3] > 0.9 && p[0] > 0.9 && p[1] < 0.1)); - // The TySh we generated parses back to the same model. - let back = photocraft_text::psd::text_layer_from_tysh(t.psd_raw.as_ref().unwrap(), 72.0).unwrap(); - assert_eq!(back.text, "Hello"); - let strip = |mut r: Vec| { - for x in &mut r { - x.style.postscript_name = None; - } - r - }; - assert_eq!(strip(back.char_runs()), strip(t.char_runs())); - assert_eq!(back.char_runs()[0].style.postscript_name.as_deref(), Some("Inter-Regular")); - assert!(s.undo()); - assert!(s.active().unwrap().doc.layer(LayerId(id)).is_none()); - } - - fn layer_name_of(s: &Session, id: u64) -> String { - s.active().unwrap().doc.layer(LayerId(id)).unwrap().name.clone() - } - - #[test] - fn auto_name_follows_the_text() { - // The Type tool's flow (#483): a placeholder, selected, then replaced by typing. - let mut s = session(); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Lorem Ipsum", "coalesce": "k"})).unwrap()["layer"].as_u64().unwrap(); - assert_eq!(layer_name_of(&s, id), "Lorem Ipsum"); - s.execute("type.edit", json!({"layer": id, "replace": {"start": 0, "end": 11, "text": "H"}, "coalesce": "k"})).unwrap(); - s.execute("type.edit", json!({"layer": id, "replace": {"start": 1, "end": 1, "text": "eading\nsecond line"}, "coalesce": "k"})).unwrap(); - assert_eq!(layer_name_of(&s, id), "Heading"); - // Emptied, the name is the default one and keeps following. - s.execute("type.edit", json!({"layer": id, "text": ""})).unwrap(); - assert_eq!(layer_name_of(&s, id), "Type Layer"); - s.execute("type.edit", json!({"layer": id, "text": "Title"})).unwrap(); - assert_eq!(layer_name_of(&s, id), "Title"); - assert!(s.undo()); - assert_eq!(layer_name_of(&s, id), "Type Layer"); - } - - #[test] - fn size_keys_step_each_run_and_respect_layer_scale() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "size": 20})).unwrap(); - s.execute("type.increaseSize", json!({})).unwrap(); - let sizes = |s: &Session| text_layer(s, id).char_runs().iter().map(|r| r.style.size_pt).collect::>(); - assert_eq!(sizes(&s), vec![14.0, 22.0], "every run grows by 2 pt"); - s.execute("type.decreaseSizeMore", json!({"range": [0, 5]})).unwrap(); - assert_eq!(sizes(&s)[0], 4.0, "only the range, by 10 pt"); - for _ in 0..2 { - s.execute("type.decreaseSize", json!({"range": [0, 5]})).unwrap(); - } - assert_eq!(sizes(&s)[0], TYPE_SIZE_MIN_PT as f32, "never below the smallest size"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(sizes(&s)[0], 2.0, "one undo step per press"); - - let scaled = s.execute("type.create", json!({"x": 0, "y": 80, "text": "Big", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.edit", json!({"layer": scaled, "transform": [2.0, 0.0, 0.0, 2.0, 0.0, 80.0]})).unwrap(); - s.execute("type.increaseSize", json!({"layer": scaled})).unwrap(); - assert_eq!(text_layer(&s, scaled).char_runs()[0].style.size_pt, 13.0, "a 200% layer shows 24 pt and steps to 26 pt"); - } - - #[test] - fn size_keys_need_a_type_layer() { - let mut s = session(); - assert!(s.execute("type.increaseSize", json!({})).is_err()); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hi", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.increaseSize", json!({"by": "big"})).unwrap(); - s.execute("type.increaseSize", json!({"by": -3})).unwrap(); - s.execute("type.decreaseSize", json!({"by": 1e30, "range": [9, 0]})).unwrap(); - assert_eq!(text_layer(&s, id).char_runs()[0].style.size_pt, TYPE_SIZE_MIN_PT as f32, "bad steps fall back or clamp, never panic"); - assert_eq!(crate::commands::find("type.increaseSize").and_then(|c| c.shortcut), Some("Cmd+Shift+.")); - assert_eq!(crate::commands::find("type.decreaseSize").and_then(|c| c.shortcut), Some("Cmd+Shift+,")); - } - - #[test] - fn auto_name_skips_leading_blank_lines() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "\n \nHello\nworld"})).unwrap()["layer"].as_u64().unwrap(); - assert_eq!(layer_name_of(&s, id), "Hello"); - s.execute("type.edit", json!({"layer": id, "replace": {"start": 0, "end": 0, "text": "\n"}})).unwrap(); - s.execute("type.edit", json!({"layer": id, "text": "\n\nGoodbye"})).unwrap(); - assert_eq!(layer_name_of(&s, id), "Goodbye"); - } - - #[test] - fn custom_name_survives_text_edits() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello", "name": "Logo"})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.edit", json!({"layer": id, "text": "Goodbye"})).unwrap(); - assert_eq!(layer_name_of(&s, id), "Logo"); - // Renamed after creation: kept too. - let id = s.execute("type.create", json!({"x": 0, "y": 80, "text": "Hello"})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.renameLayer", json!({"layer": id, "name": "Caption"})).unwrap(); - s.execute("type.edit", json!({"layer": id, "text": "Goodbye"})).unwrap(); - assert_eq!(layer_name_of(&s, id), "Caption"); - // A name given with the edit wins over the text. - s.execute("type.edit", json!({"layer": id, "text": "Again", "name": "Footer"})).unwrap(); - assert_eq!(layer_name_of(&s, id), "Footer"); - } - - #[test] - fn edit_with_name_is_one_undo_step_for_text_name_and_bounds() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 10, "y": 50, "text": "Before", "size": 20, "name": "Original"})).unwrap()["layer"].as_u64().unwrap(); - let layer = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); - let before_bounds = text_layer(&s, id).cache.unwrap().content_bounds(); - assert_eq!(layer.name, "Original"); - let steps = s.active().unwrap().history.entries().len(); - - s.execute("type.edit", json!({"layer": id, "text": "A much longer edited title that wraps", "box": [10, 10, 50, 60], "name": "Renamed"})).unwrap(); - - let edited = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); - let edited_bounds = text_layer(&s, id).cache.unwrap().content_bounds(); - assert_eq!(edited.name, "Renamed"); - assert_eq!(text_layer(&s, id).text, "A much longer edited title that wraps"); - assert_ne!(edited_bounds, before_bounds); - assert_eq!(s.active().unwrap().history.entries().len(), steps + 1); - - assert!(s.undo()); - let restored = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); - assert_eq!(restored.name, "Original"); - assert_eq!(text_layer(&s, id).text, "Before"); - assert_eq!(text_layer(&s, id).cache.unwrap().content_bounds(), before_bounds); - } - - #[test] - fn edit_replace_keeps_styles() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world"})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "fauxBold": true, "color": [0, 0, 1]})).unwrap(); - let t = text_layer(&s, id); - assert_eq!(t.runs.len(), 2); - assert_eq!(t.runs[0].len, 6); - assert!(t.runs[1].style.faux_bold); - // Insert inside the bold word: inherits bold. - s.execute("type.edit", json!({"layer": id, "replace": {"start": 8, "end": 8, "text": "XX"}})).unwrap(); - let t = text_layer(&s, id); - assert_eq!(t.text, "Hello woXXrld"); - assert_eq!(t.runs[1].len, 7); - // Delete across the style boundary. - s.execute("type.edit", json!({"layer": id, "replace": {"start": 3, "end": 8, "text": ""}})).unwrap(); - let t = text_layer(&s, id); - assert_eq!(t.text, "HelXXrld"); - assert_eq!(t.runs.iter().map(|r| r.len).collect::>(), vec![3, 5]); - // Whole-text replace with a multi-byte string. - let info = s.execute("type.edit", json!({"layer": id, "text": "Größe ✓\nzwei"})).unwrap(); - assert_eq!(info["lines"].as_array().unwrap().len(), 2); - let t = text_layer(&s, id); - assert_eq!(t.runs.iter().map(|r| r.len).sum::(), t.text.len()); - } - - #[test] - fn all_locked_type_edit_rejects_text_replacement_without_history() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 20, "y": 20, "text": "a", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.setProps", json!({"layer": id, "locked": true})).unwrap(); - let history = s.active().unwrap().history.past_len(); - - let result = s.execute("type.edit", json!({"layer": id, "text": "b"})); - assert!(matches!(&result, Err(EngineError::Other(message)) if message.contains("locked")), "{result:?}"); - assert_eq!(text_layer(&s, id).text, "a"); - assert_eq!(s.active().unwrap().history.past_len(), history); - - s.execute("layer.setProps", json!({"layer": id, "locked": false})).unwrap(); - let history = s.active().unwrap().history.past_len(); - s.execute("type.edit", json!({"layer": id, "text": "b"})).unwrap(); - assert_eq!(text_layer(&s, id).text, "b"); - assert_eq!(s.active().unwrap().history.past_len(), history + 1); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(text_layer(&s, id).text, "a"); - assert_eq!(s.active().unwrap().history.past_len(), history); - } - - #[test] - fn all_locked_type_layer_rejects_formatting_without_history() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 20, "y": 20, "text": "a", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - let other = s.execute("type.create", json!({"x": 20, "y": 60, "text": "b", "size": 12})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.setProps", json!({"layer": id, "locked": true})).unwrap(); - let before = text_layer(&s, id); - let history = s.active().unwrap().history.past_len(); - - for (cmd, p) in [ - ("type.setStyle", json!({"layer": id, "size": 40, "fauxBold": true})), - ("type.setStyle", json!({"layers": [other, id], "size": 40})), - ("type.warpText", json!({"layer": id, "style": "arc"})), - ("type.antiAlias.none", json!({"layer": id})), - ("type.orientation.vertical", json!({"layer": id})), - ("type.openType.swash", json!({"layer": id})), - ] { - let result = s.execute(cmd, p); - assert!(matches!(&result, Err(EngineError::Other(message)) if message.contains("locked")), "{cmd}: {result:?}"); - } - assert_eq!(text_layer(&s, id), before); - assert_eq!(text_layer(&s, other).size_pt, 12.0); - assert_eq!(s.active().unwrap().history.past_len(), history); - - s.execute("layer.setProps", json!({"layer": id, "locked": false})).unwrap(); - s.execute("type.setStyle", json!({"layer": id, "size": 40})).unwrap(); - assert_eq!(text_layer(&s, id).size_pt, 40.0); - } - - #[test] - fn trailing_empty_paragraph_styles_without_changing_previous_lines() { - let mut s = session(); - let id = s.execute("type.create", json!({"text":"a\nb\n","x":20,"y":20,"size":12,"font":"Inter","align":"left"})).unwrap()["layer"].as_u64().unwrap(); - let before = s.execute("type.info", json!({"layer":id})).unwrap(); - let previous_line = before["lines"][1].clone(); - - let styled = s.execute("type.setStyle", json!({"layer":id,"range":[4,4],"align":"right"})).unwrap(); - assert_eq!(styled["paragraphs"].as_array().unwrap().len(), 2); - assert_eq!(styled["paragraphs"][0]["start"], 0); - assert_eq!(styled["paragraphs"][0]["end"], 4); - assert_eq!(styled["paragraphs"][0]["style"]["align"], "Left"); - assert_eq!(styled["paragraphs"][1]["start"], 4); - assert_eq!(styled["paragraphs"][1]["end"], 4); - assert_eq!(styled["paragraphs"][1]["style"]["align"], "Right"); - assert_eq!(styled["lines"][1], previous_line, "the preceding paragraph must not move"); - let raw = text_layer(&s, id).psd_raw.clone().unwrap(); - let round_trip = photocraft_text::psd::text_layer_from_tysh(&raw, 72.0).unwrap(); - assert_eq!(round_trip.paragraph_runs().last().unwrap().style.align, TextAlign::Right); - - // Typing directly into the previously empty final paragraph retains its style. - let edited = s.execute("type.edit", json!({"layer":id,"replace":{"start":4,"end":4,"text":"c"}})).unwrap(); - assert_eq!(edited["text"], "a\nb\nc"); - assert_eq!(edited["paragraphs"][0]["end"], 4); - assert_eq!(edited["paragraphs"][0]["style"]["align"], "Left"); - assert_eq!(edited["paragraphs"][1]["start"], 4); - assert_eq!(edited["paragraphs"][1]["end"], 5); - assert_eq!(edited["paragraphs"][1]["style"]["align"], "Right"); - assert_eq!(edited["lines"][1], previous_line, "typing in the final paragraph does not move b"); - } - - #[test] - fn set_style_paragraph_and_box() { - let mut s = session(); - let id = s.execute("type.create", json!({"box": [10, 10, 80, 80], "text": "one two three four five six seven", "size": 12})).unwrap()["layer"] - .as_u64() - .unwrap(); - let info = s.execute("type.setStyle", json!({"layer": id, "align": "center", "leading": 20})).unwrap(); - let lines = info["lines"].as_array().unwrap(); - assert!(lines.len() >= 3); - let b0 = lines[0]["baseline"].as_f64().unwrap(); - let b1 = lines[1]["baseline"].as_f64().unwrap(); - assert!((b1 - b0 - 20.0).abs() < 1e-3, "explicit leading {b0} {b1}"); - assert_eq!(info["paragraphs"][0]["style"]["align"], "Center"); - let t = text_layer(&s, id); - assert!(matches!(t.shape, TextShape::Box { width, .. } if width == 80.0)); - // Pixels stay inside the box horizontally. - let r = t.cache.as_ref().unwrap().content_bounds(); - assert!(r.x0 >= 9 && r.x1 <= 91, "{r:?}"); - // Convert to point text and move. - s.execute("type.edit", json!({"layer": id, "point": [5, 30]})).unwrap(); - s.execute("type.edit", json!({"layer": id, "move": [10, 0]})).unwrap(); - let t = text_layer(&s, id); - assert_eq!(t.shape, TextShape::Point); - assert_eq!(t.transform.m[4], 15.0); - } - - #[test] - fn rasterize_and_fonts() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 5, "y": 30, "text": "Raster"})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.rasterize", json!({"layer": id})).unwrap(); - let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); - assert!(matches!(l.content, LayerContent::Raster(_))); - assert!(l.surface().unwrap().content_bounds().width() > 10); - assert!(s.execute("type.edit", json!({"layer": id, "text": "x"})).is_err()); - let fonts = s.execute("type.fonts", json!({})).unwrap(); - assert!(fonts["families"].as_array().unwrap().iter().any(|f| f == "Inter")); - let faces = s.execute("type.fonts", json!({"family": "Inter"})).unwrap(); - assert!(!faces["faces"].as_array().unwrap().is_empty()); - } - - /// #124: a type edit damages only the layer's old and new pixels (the canvas recomposites - /// that, not the document), and a drag's coalesced steps are one history step. - #[test] - fn type_edits_damage_only_the_layer_and_coalesce() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 3000, "height": 2000})).unwrap(); - let id = s.execute("type.create", json!({"x": 100, "y": 100, "text": "Hi", "size": 20})).unwrap()["layer"].as_u64().unwrap(); - let steps = s.active().unwrap().history.entries().len(); - for k in 0..5 { - s.execute("type.setStyle", json!({"layer": id, "size": 30 + k * 10, "coalesce": "drag"})).unwrap(); - let d = s.active().unwrap().last_damage.expect("damage rect"); - let r = text_layer(&s, id).cache.unwrap().content_bounds(); - assert!(d.intersect(&r) == r && d.width() <= 512 && d.height() <= 512, "{d:?} {r:?}"); - } - assert_eq!(s.active().unwrap().history.entries().len(), steps + 1); - assert!(s.undo()); - assert_eq!(text_layer(&s, id).runs[0].style.size_pt, 20.0); - } - - #[test] - fn edit_rejects_a_reversed_runs_range() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world", "size": 20})).unwrap()["layer"].as_u64().unwrap(); - let before = text_layer(&s, id).char_runs(); - let steps = s.active().unwrap().history.entries().len(); - for runs in [ - json!([{"start": 5, "end": 2, "fauxBold": true}]), - json!([{"start": 0, "end": 3, "fauxBold": true}, {"start": 8, "end": 7}]), - json!([{"end": 0, "start": 1}]), - ] { - let e = s.execute("type.edit", json!({"layer": id, "runs": runs})).unwrap_err(); - assert!(matches!(e, EngineError::BadParams { .. }) && e.to_string().contains("is before `start`"), "{e}"); - } - // Nothing changed and nothing was recorded, not even the valid run before the bad one. - assert_eq!(text_layer(&s, id).char_runs(), before); - assert_eq!(s.active().unwrap().history.entries().len(), steps); - // The same range the right way round still styles it. - s.execute("type.edit", json!({"layer": id, "runs": [{"start": 2, "end": 5, "fauxBold": true}]})).unwrap(); - let runs = text_layer(&s, id).char_runs(); - assert_eq!(runs.iter().map(|r| (r.len, r.style.faux_bold)).collect::>(), [(2, false), (3, true), (6, false)]); - } - - #[test] - fn style_range_reversed_is_a_no_op() { - let mut t = TextLayer::default(); - replace_text(&mut t, 0, 0, "Hello world"); - let before = t.char_runs(); - style_range(&mut t, 5, 2, &|s| s.size_pt = 40.0); - assert_eq!(t.char_runs(), before); - assert_eq!(t.runs.iter().map(|r| r.len).sum::(), t.text.len()); - } - - #[test] - fn style_range_on_empty_text() { - let mut t = TextLayer::default(); - style_range(&mut t, 0, 0, &|s| s.size_pt = 40.0); - assert_eq!(t.runs[0].style.size_pt, 40.0); - replace_text(&mut t, 0, 0, "abc"); - assert_eq!(t.runs.len(), 1); - assert_eq!(t.runs[0].len, 3); - assert_eq!(t.runs[0].style.size_pt, 40.0); - } - - /// Replacing a selected smaller second line (by typing or pasting) keeps its size, not the - /// first line's, whose line break precedes the selection. - #[test] - fn replacing_a_selection_keeps_its_first_characters_style() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "BIG\nsmall", "size": 40})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.edit", json!({"layer": id, "runs": [{"start": 4, "end": 9, "size": 12}]})).unwrap(); - s.execute("type.edit", json!({"layer": id, "replace": {"start": 4, "end": 9, "text": "AIR"}})).unwrap(); - let sizes = |s: &Session| text_layer(s, id).char_runs().iter().map(|r| (r.len, r.style.size_pt)).collect::>(); - assert_eq!(text_layer(&s, id).text, "BIG\nAIR"); - assert_eq!(sizes(&s), [(4, 40.0), (3, 12.0)]); - // A mixed selection takes its first character's style. - s.execute("type.edit", json!({"layer": id, "replace": {"start": 2, "end": 6, "text": "xy"}})).unwrap(); - assert_eq!(sizes(&s), [(4, 40.0), (1, 12.0)]); - // Inserting at a caret still follows the character before it. - s.execute("type.edit", json!({"layer": id, "replace": {"start": 4, "end": 4, "text": "!"}})).unwrap(); - assert_eq!(sizes(&s), [(5, 40.0), (1, 12.0)]); - } - - /// A misspelt `baseline` is an error and keeps superscript, instead of resetting it to Normal. - #[test] - fn unknown_baseline_is_rejected_and_keeps_the_style() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "x2", "size": 30})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [1, 2], "baseline": "superscript"})).unwrap(); - let before = text_layer(&s, id).runs; - for b in [json!("superscipt"), json!("Superscript"), json!(1)] { - assert!(matches!(s.execute("type.setStyle", json!({"layer": id, "baseline": b})), Err(EngineError::BadParams { .. })), "{b}"); - assert!(s.execute("type.edit", json!({"layer": id, "baseline": b})).is_err(), "{b}"); - assert!(s.execute("type.create", json!({"x": 0, "y": 10, "text": "a", "baseline": b})).is_err(), "{b}"); - } - assert_eq!(text_layer(&s, id).runs, before); - s.execute("type.setStyle", json!({"layer": id, "baseline": "normal"})).unwrap(); - assert!(text_layer(&s, id).char_runs().iter().all(|r| r.style.baseline == FontBaseline::Normal)); - } - - fn kerning_of(s: &Session, id: u64) -> Vec<(Kerning, f32)> { - let t = text_layer(s, id); - let mut out = Vec::new(); - let mut at = 0; - for r in t.char_runs() { - out.extend(std::iter::repeat_n((r.style.kerning, r.style.kern), t.text[at..at + r.len].chars().count())); - at += r.len; - } - out - } - - /// #8489: `type.edit {"text"}` changes only what differs, so the rest keeps its styles: an - /// added character takes the style beside it, and a change inside one run stays in it. - #[test] - fn edit_text_keeps_the_styles_of_unchanged_text() { - // (characters, colour) per run. - fn runs(s: &Session, id: u64) -> Vec<(usize, [u8; 4])> { - let t = text_layer(s, id); - let mut at = 0; - t.char_runs() - .into_iter() - .map(|r| { - let n = t.text[at..at + r.len].chars().count(); - at += r.len; - (n, r.style.color.to_rgba8()) - }) - .collect() - } - let (dark, purple) = ([0x1b, 0x1f, 0x4b, 255], [0x5a, 0x3d, 0xf0, 255]); - let mut s = session(); - let id = s.execute("type.create", json!({"x": 20, "y": 50, "text": "Craft Suite in Workshop", "size": 40, "color": "#1b1f4b"})).unwrap()["layer"] - .as_u64() - .unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [15, 23], "color": "#5a3df0"})).unwrap(); - assert_eq!(runs(&s, id), [(15, dark), (8, purple)]); - s.execute("type.edit", json!({"layer": id, "text": "Craft Suite in Workshop!"})).unwrap(); - assert_eq!(runs(&s, id), [(15, dark), (9, purple)], "the added character joins the last run"); - s.execute("type.edit", json!({"layer": id, "text": "Craft Suite in Worksh\u{f6}p!"})).unwrap(); - assert_eq!(runs(&s, id), [(15, dark), (9, purple)], "a change inside a run stays in it"); - s.execute("type.edit", json!({"layer": id, "text": "Kraft Suite in Worksh\u{f6}p!"})).unwrap(); - assert_eq!(runs(&s, id), [(15, dark), (9, purple)]); - // Replacing everything leaves one style, as before. - s.execute("type.edit", json!({"layer": id, "text": "Hello"})).unwrap(); - assert_eq!(text_layer(&s, id).text, "Hello"); - assert_eq!(runs(&s, id).iter().map(|r| r.0).sum::(), 5); - s.execute("type.edit", json!({"layer": id, "text": ""})).unwrap(); - assert_eq!(text_layer(&s, id).text, ""); - - // Text inserted at the start of a paragraph joins that paragraph, which keeps its style. - let id = s - .execute( - "type.create", - json!({"x": 20, "y": 50, "text": "a -b", "size": 20}), - ) - .unwrap()["layer"] - .as_u64() - .unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [2, 3], "align": "right"})).unwrap(); - s.execute( - "type.edit", - json!({"layer": id, "text": "a -Xb"}), - ) - .unwrap(); - let paragraphs: Vec<(usize, photocraft_doc::text::TextAlign)> = - text_layer(&s, id).paragraph_runs().into_iter().map(|r| (r.len, r.style.align)).collect(); - assert_eq!(paragraphs.first().map(|p| p.0), Some(2), "{paragraphs:?}"); - assert_eq!(paragraphs.get(1).copied(), Some((2, photocraft_doc::text::TextAlign::Right)), "{paragraphs:?}"); - } - - /// #206: `type.edit {"kerning"}` over a range takes a number (manual, 1/1000 em) or a mode. - #[test] - fn edit_sets_kerning_over_a_range() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "AVAT", "size": 30})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.edit", json!({"layer": id, "range": [0, 1], "kerning": 100})).unwrap(); - s.execute("type.edit", json!({"layer": id, "range": [2, 4], "kerning": "optical"})).unwrap(); - assert_eq!(kerning_of(&s, id), vec![(Kerning::Off, 100.0), (Kerning::Metrics, 0.0), (Kerning::Optical, 0.0), (Kerning::Optical, 0.0)]); - s.execute("type.edit", json!({"layer": id, "kerning": "metrics"})).unwrap(); - assert!(kerning_of(&s, id).iter().all(|k| *k == (Kerning::Metrics, 0.0))); - // Runs and setStyle take the same values; type.info reports them. - s.execute("type.edit", json!({"layer": id, "runs": [{"start": 1, "end": 2, "kerning": -50}]})).unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [3, 4], "kerning": "off"})).unwrap(); - assert_eq!(kerning_of(&s, id)[1], (Kerning::Off, -50.0)); - assert_eq!(kerning_of(&s, id)[3], (Kerning::Off, 0.0)); - let info = s.execute("type.info", json!({"layer": id})).unwrap(); - assert_eq!(info["runs"][1]["style"]["kern"], json!(-50.0)); - } - - /// Bad kerning params are errors, never panics, and leave the layer alone. - #[test] - fn kerning_params_fail_gracefully() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "AV\nT", "size": 30})).unwrap()["layer"].as_u64().unwrap(); - let before = text_layer(&s, id); - for p in [ - json!({"kerning": "tight"}), - json!({"kerning": 1e9}), - json!({"kerning": -5000}), - json!({"kerning": true}), - json!({"kerning": [1]}), - json!({"runs": [{"start": 0, "end": 1, "kerning": "x"}]}), - json!({"kernPair": 3}), - json!({"kernPair": {"by": 20}}), - json!({"kernPair": {"at": 1}}), - json!({"kernPair": {"at": 1, "by": "20"}}), - json!({"kernPair": {"at": 1, "by": 1e12}}), - json!({"kernPair": {"at": 0, "by": 20}}), - json!({"kernPair": {"at": 4, "by": 20}}), - json!({"kernPair": {"at": 99, "by": 20}}), - json!({"kernPair": {"at": 2, "by": 20}}), - json!({"kernPair": {"at": 3, "by": 20}}), - json!({"kernPair": {"at": -1, "by": 20}}), - ] { - let mut p = p; - p["layer"] = json!(id); - assert!(s.execute("type.edit", p.clone()).is_err(), "{p}"); - } - assert!(s.execute("type.setStyle", json!({"layer": id, "kerning": "tight"})).is_err()); - assert_eq!(text_layer(&s, id).runs, before.runs); - // type.create rejects the same values and creates no layer (#994). - let layers = s.active().unwrap().doc.layer_count(); - for k in [json!("tight"), json!(1e9), json!(-5000), json!(true), json!([1])] { - let p = json!({"x": 0, "y": 10, "text": "AV", "kerning": k}); - assert!(s.execute("type.create", p.clone()).is_err(), "{p}"); - } - assert_eq!(s.active().unwrap().doc.layer_count(), layers); - let id = s.execute("type.create", json!({"x": 0, "y": 10, "text": "AV", "kerning": "optical"})).unwrap()["layer"].as_u64().unwrap(); - assert!(kerning_of(&s, id).iter().all(|k| *k == (Kerning::Optical, 0.0))); - let id = s.execute("type.create", json!({"x": 0, "y": 10, "text": "AV", "kerning": -50})).unwrap()["layer"].as_u64().unwrap(); - assert!(kerning_of(&s, id).iter().all(|k| *k == (Kerning::Off, -50.0))); - } - - /// Cost of one Alt+←/→ press (`kernPair`: two measuring layouts + the edit's re-render) on - /// a headline and on a 2000-character paragraph. Release timings for the dev log: - /// `cargo test --release -p photocraft-engine kern_pair_cost -- --ignored --nocapture`. - #[test] - #[ignore] - fn kern_pair_cost() { - let para = "The quick brown fox jumps over the lazy dog. ".repeat(45); - for (name, text, size, bx, kerning) in [ - ("headline", "AVATAR Wave", 72, false, "metrics"), - ("paragraph", para.as_str(), 12, true, "metrics"), - ("optical paragraph", para.as_str(), 12, true, "optical"), - ] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 2000, "height": 1500})).unwrap(); - let mut p = json!({"x": 20, "y": 100, "text": text, "size": size, "font": "Inter", "kerning": kerning}); - if bx { - p["box"] = json!([20, 20, 900, 1400]); - } - let id = s.execute("type.create", p).unwrap()["layer"].as_u64().unwrap(); - let n = 20; - let t0 = std::time::Instant::now(); - for i in 0..n { - s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1 + i % 3, "by": 20}})).unwrap(); - } - let per = t0.elapsed().as_secs_f64() * 1000.0 / f64::from(n); - let t1 = std::time::Instant::now(); - for i in 0..n { - s.execute("type.setStyle", json!({"layer": id, "range": [1 + i % 3, 2 + i % 3], "tracking": i})).unwrap(); - } - let base = t1.elapsed().as_secs_f64() * 1000.0 / f64::from(n); - eprintln!("{name} ({} chars): kernPair {per:.2} ms/press; a plain style edit {base:.2} ms", text.chars().count()); - } - } - - /// Photoshop's Alt+←/→: the pair before the caret becomes manual, starting from the kerning - /// it shows (the font's pair kerning for "AV"), ±20 per press, one history step each. - #[test] - fn kern_pair_steps_from_the_shown_kerning() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "AVA", "size": 40, "font": "Inter"})).unwrap()["layer"].as_u64().unwrap(); - let metric = { - let t = text_layer(&s, id); - photocraft_text::shared().lock().unwrap().pair_kerning(&t, 72.0, 0).unwrap() - }; - assert!(metric < -10.0, "Inter kerns AV: {metric}"); - let steps = s.active().unwrap().history.entries().len(); - s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1, "by": 20}})).unwrap(); - let k0 = kerning_of(&s, id)[0]; - assert_eq!(k0, (Kerning::Off, metric.round() + 20.0)); - s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1, "by": 100}})).unwrap(); - assert_eq!(kerning_of(&s, id)[0].1, metric.round() + 120.0); - s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1, "by": -20}})).unwrap(); - assert_eq!(kerning_of(&s, id)[0].1, metric.round() + 100.0); - // Other characters are untouched; each press is its own undoable step. - assert_eq!(&kerning_of(&s, id)[1..], &[(Kerning::Metrics, 0.0), (Kerning::Metrics, 0.0)]); - assert_eq!(s.active().unwrap().history.entries().len(), steps + 3); - assert!(s.undo()); - assert_eq!(kerning_of(&s, id)[0].1, metric.round() + 120.0); - assert!(s.undo() && s.undo()); - assert_eq!(kerning_of(&s, id)[0], (Kerning::Metrics, 0.0)); - } - #[test] - fn create_vertical_type_is_atomic_and_invalid_orientation_is_rejected() { - for boxed in [false, true] { - let mut s = session(); - let before = s.active().unwrap().history.entries().len(); - for orientation in [json!("diagonal"), json!(null), json!(true)] { - assert!(s.execute("type.create", json!({"text": "test", "orientation": orientation})).is_err()); - assert_eq!(s.active().unwrap().history.entries().len(), before); - } - let mut p = json!({"text": "test", "orientation": "vertical", "x": 20, "y": 20}); - if boxed { - p["box"] = json!([20, 20, 80, 60]); - } - let id = s.execute("type.create", p).unwrap()["layer"].as_u64().unwrap(); - let t = text_layer(&s, id); - assert_eq!(t.orientation, Orientation::Vertical); - assert_eq!(matches!(t.shape, TextShape::Box { .. }), boxed); - s.execute("edit.undo", json!({})).unwrap(); - assert!(s.active().unwrap().doc.layer(LayerId(id)).is_none()); - } - } - - #[test] - fn missing_font_emits_warning_in_create_set_style_and_edit() { - let mut s = session(); - let r = s.execute("type.create", json!({"x": 10, "y": 20, "text": "Hello", "font": "NoSuchFamily123"})).unwrap(); - assert_eq!(r["warnings"], json!(["font 'NoSuchFamily123' is not installed; text may render using a fallback face"])); - let id = r["layer"].as_u64().unwrap(); - let styled = s.execute("type.setStyle", json!({"layer": id, "font": "StillNoSuchFamily456"})).unwrap(); - assert_eq!(styled["warnings"], json!(["font 'StillNoSuchFamily456' is not installed; text may render using a fallback face"])); - let edited = s.execute("type.edit", json!({"layer": id, "runs": [{"start": 0, "end": 2, "font": "AnotherMissingFont789"}]})).unwrap(); - assert_eq!( - edited["warnings"], - json!([ - "font 'AnotherMissingFont789' is not installed; text may render using a fallback face", - "font 'StillNoSuchFamily456' is not installed; text may render using a fallback face" - ]) - ); - } - - /// `leadingBy`, `baselineShiftBy` and `trackingBy` step every character from its own value - /// (auto leading from its laid-out value), clamp to Photoshop's ranges, and reject hostile - /// steps without changing anything. - #[test] - fn relative_steps_move_each_character_from_its_own_value() { - let mut s = session(); - let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello\nworld", "size": 10})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [8, 11], "leading": 30, "tracking": 50})).unwrap(); - s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "autoLeading": 150})).unwrap(); - let steps = s.active().unwrap().history.entries().len(); - s.execute("type.setStyle", json!({"layer": id, "range": [0, 11], "leadingBy": 2, "baselineShiftBy": -2, "trackingBy": 20})).unwrap(); - assert_eq!(s.active().unwrap().history.entries().len(), steps + 1, "one history step"); - let t = text_layer(&s, id); - let at = |c: usize| { - let byte = byte_at(&t.text, c); - let mut off = 0; - t.char_runs() - .into_iter() - .find(|r| { - off += r.len; - off > byte - }) - .unwrap() - .style - }; - // Auto leading 120% × 10 pt (first paragraph), 150% × 10 pt (second), and a set 30 pt. - assert_eq!(at(0).leading_pt, Some(14.0)); - assert_eq!(at(6).leading_pt, Some(17.0)); - assert_eq!(at(9).leading_pt, Some(32.0)); - assert_eq!((at(0).baseline_shift_pt, at(9).baseline_shift_pt), (-2.0, -2.0)); - assert_eq!((at(0).tracking, at(9).tracking), (20.0, 70.0)); - // Clamped to the ranges. - s.execute("type.setStyle", json!({"layer": id, "leadingBy": -5000, "baselineShiftBy": 10000, "trackingBy": -11000})).unwrap(); - let t = text_layer(&s, id); - assert!(t.char_runs().iter().all(|r| r.style.leading_pt == Some(LEADING_MIN_PT) - && r.style.baseline_shift_pt == BASELINE_SHIFT_MAX_PT - && r.style.tracking == TRACKING_MIN as f32)); - // A collapsed range in non-empty text changes no character. - let before = text_layer(&s, id).char_runs(); - s.execute("type.setStyle", json!({"layer": id, "range": [3, 3], "trackingBy": 100})).unwrap(); - assert_eq!(text_layer(&s, id).char_runs(), before); - // Hostile steps are refused. - let steps = s.active().unwrap().history.entries().len(); - for bad_step in [json!({"leadingBy": "up"}), json!({"trackingBy": 1e30}), json!({"baselineShiftBy": null}), json!({"leadingBy": [1]})] { - let mut p = bad_step.clone(); - p["layer"] = json!(id); - assert!(matches!(s.execute("type.setStyle", p), Err(EngineError::BadParams { .. })), "{bad_step}"); - } - assert_eq!(s.active().unwrap().history.entries().len(), steps); - // Empty text: the step sets the style the next typed characters get. - let empty = s.execute("type.create", json!({"x": 0, "y": 80, "text": "", "size": 10})).unwrap()["layer"].as_u64().unwrap(); - s.execute("type.setStyle", json!({"layer": empty, "range": [0, 0], "leadingBy": -2})).unwrap(); - assert_eq!(text_layer(&s, empty).char_runs()[0].style.leading_pt, Some(10.0)); - } -} +mod tests; diff --git a/crates/engine/src/type_cmds/tests.rs b/crates/engine/src/type_cmds/tests.rs new file mode 100644 index 0000000000..81ce84d699 --- /dev/null +++ b/crates/engine/src/type_cmds/tests.rs @@ -0,0 +1,795 @@ +use super::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 100, "background": "transparent"})).unwrap(); + s +} + +fn text_layer(s: &Session, id: u64) -> TextLayer { + match &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content { + LayerContent::Text(t) => t.clone(), + other => panic!("{}", other.kind_name()), + } +} + +#[test] +fn named_face_metadata_replaces_old_postscript_identity() { + let mut style = CharStyle { font_family: "Inter".into(), postscript_name: Some("Inter-Regular".into()), ..Default::default() }; + apply_char_props(&mut style, &json!({"fontStyle": "SemiBold"})); + assert_eq!(style.weight, 600); + assert_eq!(style.postscript_name.as_deref(), Some("Inter-SemiBold")); + apply_char_props(&mut style, &json!({"weight": 400})); + // #3556: a style change re-resolves to the installed face instead of leaving it nameless. + assert_eq!(style.postscript_name.as_deref(), Some("Inter-Regular")); + assert!(style.font_style.is_empty()); + apply_char_props(&mut style, &json!({"fontStyle": "unknown-style"})); + assert_eq!(style.postscript_name.as_deref(), Some("Inter-Regular")); + apply_char_props(&mut style, &json!({"fontStyle": "Regular", "postscriptName": "ExplicitFace"})); + assert_eq!(style.postscript_name.as_deref(), Some("ExplicitFace")); +} + +/// #3556: a font named by family stores the installed face's PostScript name, so PSD export +/// names a real font instead of inventing "-Regular" that Photoshop calls missing. +#[test] +fn a_family_font_gets_the_installed_postscript_name() { + let mut style = CharStyle { font_family: "Inter".into(), ..Default::default() }; + apply_char_props(&mut style, &json!({"font": "Inter"})); + assert_eq!(style.font_family, "Inter"); + assert_eq!(style.postscript_name.as_deref(), Some("Inter-Regular"), "resolved from the font database"); + // A weight picks that face's name. + apply_char_props(&mut style, &json!({"font": "Inter", "weight": 600})); + assert_eq!(style.postscript_name.as_deref(), Some("Inter-SemiBold")); + // A weight no face has (a variable font's axis, or between two faces) names no face, so + // layout still matches the requested weight instead of a nearby face's. + apply_char_props(&mut style, &json!({"weight": 650})); + assert!(style.postscript_name.is_none(), "{:?}", style.postscript_name); + // A family PhotoCraft does not have keeps no name; the export falls back as before. + let mut absent = CharStyle { font_family: "No Such Family 123".into(), ..Default::default() }; + apply_char_props(&mut absent, &json!({"font": "No Such Family 123"})); + assert!(absent.postscript_name.is_none()); +} + +/// Picking a style or weight resets the weight axis to it; other axes keep their values (#2985). +#[test] +fn a_style_or_weight_resets_the_weight_axis() { + let mut style = CharStyle::default(); + apply_char_props(&mut style, &json!({"variations": {"wght": 650, "wdth": 80}})); + apply_char_props(&mut style, &json!({"fontStyle": "Bold"})); + let axes = |s: &CharStyle| s.variations.iter().map(|v| (v.axis.clone(), v.value)).collect::>(); + assert_eq!(axes(&style), [("wdth".to_string(), 80.0)]); + apply_char_props(&mut style, &json!({"variations": {"wght": 650}})); + apply_char_props(&mut style, &json!({"weight": 300})); + assert_eq!(axes(&style), [("wdth".to_string(), 80.0)]); + apply_char_props(&mut style, &json!({"fontStyle": "Light", "variations": {"wght": 350}})); + assert_eq!(axes(&style), [("wdth".to_string(), 80.0), ("wght".to_string(), 350.0)], "same-call values apply after the style"); +} + +#[test] +fn absurd_type_size_and_tracking_are_rejected_as_bad_params() { + let mut s = session(); + assert!(matches!( + s.execute("type.create", json!({"text": "abc", "size": 1e30})), + Err(EngineError::BadParams { cmd, .. }) if cmd == "type.create" + )); + + let id = s.execute("type.create", json!({"text": "abc", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + let before = text_layer(&s, id); + for params in [json!({"layer": id, "tracking": 1e30}), json!({"layer": id, "runs": [{"start": 0, "end": 3, "tracking": 1e30}]})] { + assert!(matches!( + s.execute("type.edit", params), + Err(EngineError::BadParams { cmd, .. }) if cmd == "type.edit" + )); + assert_eq!(text_layer(&s, id).runs, before.runs); + } + assert!(matches!( + s.execute("type.setStyle", json!({"layer": id, "tracking": 1e30})), + Err(EngineError::BadParams { cmd, .. }) if cmd == "type.setStyle" + )); + assert_eq!(text_layer(&s, id).runs, before.runs); +} + +/// A font that arrives after the layer was drawn (served fonts on the web) re-renders it with +/// no history step, and a clean document stays clean. +#[test] +fn refreshing_type_layers_takes_no_history_step() { + let mut s = session(); + let id = LayerId(s.execute("type.create", json!({"text": "Hello", "size": 24})).unwrap()["layer"].as_u64().unwrap()); + let doc_id = s.active().unwrap().doc.id; + // Stale pixels, and a document saved in this state. + { + let st = s.active_mut().unwrap(); + let Some(Layer { content: LayerContent::Text(t), .. }) = Arc::make_mut(&mut st.doc).layer_mut(id) else { panic!("not a type layer") }; + t.cache = None; + st.saved_revision = st.revision; + } + let rev = s.active().unwrap().revision; + let unknown = [(doc_id, LayerId(u64::MAX)), (photocraft_doc::DocId(u64::MAX), id)]; + assert!(s.refresh_type_layers(&[&[(doc_id, id)][..], &unknown].concat()).is_empty()); + assert!(text_layer(&s, id.0).cache.is_some()); + let st = s.active().unwrap(); + assert!(st.revision > rev); + assert_eq!(st.saved_revision, st.revision, "still clean"); + // The only history step is still the creation. + assert!(s.undo()); + assert!(s.active().unwrap().doc.layer(id).is_none()); +} + +#[test] +fn create_renders_and_is_undoable() { + let mut s = session(); + let r = s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hello", "size": 24, "color": "#ff0000"})).unwrap(); + let id = r["layer"].as_u64().unwrap(); + let b = r["bounds"].as_array().unwrap(); + assert!(b[0].as_i64().unwrap() >= 9 && b[3].as_i64().unwrap() <= 56, "{b:?}"); + let t = text_layer(&s, id); + assert_eq!(t.text, "Hello"); + assert_eq!(t.runs[0].style.size_pt, 24.0); + assert!(t.cache.is_some() && t.psd_raw.is_some()); + let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + assert_eq!(l.name, "Hello"); + // Red pixels exist. + let c = t.cache.as_ref().unwrap(); + let r = c.content_bounds(); + assert!(c.read_region(r).as_chunks::<4>().0.iter().any(|p| p[3] > 0.9 && p[0] > 0.9 && p[1] < 0.1)); + // The TySh we generated parses back to the same model. + let back = photocraft_text::psd::text_layer_from_tysh(t.psd_raw.as_ref().unwrap(), 72.0).unwrap(); + assert_eq!(back.text, "Hello"); + let strip = |mut r: Vec| { + for x in &mut r { + x.style.postscript_name = None; + } + r + }; + assert_eq!(strip(back.char_runs()), strip(t.char_runs())); + assert_eq!(back.char_runs()[0].style.postscript_name.as_deref(), Some("Inter-Regular")); + assert!(s.undo()); + assert!(s.active().unwrap().doc.layer(LayerId(id)).is_none()); +} + +fn layer_name_of(s: &Session, id: u64) -> String { + s.active().unwrap().doc.layer(LayerId(id)).unwrap().name.clone() +} + +#[test] +fn auto_name_follows_the_text() { + // The Type tool's flow (#483): a placeholder, selected, then replaced by typing. + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Lorem Ipsum", "coalesce": "k"})).unwrap()["layer"].as_u64().unwrap(); + assert_eq!(layer_name_of(&s, id), "Lorem Ipsum"); + s.execute("type.edit", json!({"layer": id, "replace": {"start": 0, "end": 11, "text": "H"}, "coalesce": "k"})).unwrap(); + s.execute("type.edit", json!({"layer": id, "replace": {"start": 1, "end": 1, "text": "eading\nsecond line"}, "coalesce": "k"})).unwrap(); + assert_eq!(layer_name_of(&s, id), "Heading"); + // Emptied, the name is the default one and keeps following. + s.execute("type.edit", json!({"layer": id, "text": ""})).unwrap(); + assert_eq!(layer_name_of(&s, id), "Type Layer"); + s.execute("type.edit", json!({"layer": id, "text": "Title"})).unwrap(); + assert_eq!(layer_name_of(&s, id), "Title"); + assert!(s.undo()); + assert_eq!(layer_name_of(&s, id), "Type Layer"); +} + +#[test] +fn size_keys_step_each_run_and_respect_layer_scale() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "size": 20})).unwrap(); + s.execute("type.increaseSize", json!({})).unwrap(); + let sizes = |s: &Session| text_layer(s, id).char_runs().iter().map(|r| r.style.size_pt).collect::>(); + assert_eq!(sizes(&s), vec![14.0, 22.0], "every run grows by 2 pt"); + s.execute("type.decreaseSizeMore", json!({"range": [0, 5]})).unwrap(); + assert_eq!(sizes(&s)[0], 4.0, "only the range, by 10 pt"); + for _ in 0..2 { + s.execute("type.decreaseSize", json!({"range": [0, 5]})).unwrap(); + } + assert_eq!(sizes(&s)[0], TYPE_SIZE_MIN_PT as f32, "never below the smallest size"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(sizes(&s)[0], 2.0, "one undo step per press"); + + let scaled = s.execute("type.create", json!({"x": 0, "y": 80, "text": "Big", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.edit", json!({"layer": scaled, "transform": [2.0, 0.0, 0.0, 2.0, 0.0, 80.0]})).unwrap(); + s.execute("type.increaseSize", json!({"layer": scaled})).unwrap(); + assert_eq!(text_layer(&s, scaled).char_runs()[0].style.size_pt, 13.0, "a 200% layer shows 24 pt and steps to 26 pt"); +} + +#[test] +fn size_keys_need_a_type_layer() { + let mut s = session(); + assert!(s.execute("type.increaseSize", json!({})).is_err()); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hi", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.increaseSize", json!({"by": "big"})).unwrap(); + s.execute("type.increaseSize", json!({"by": -3})).unwrap(); + s.execute("type.decreaseSize", json!({"by": 1e30, "range": [9, 0]})).unwrap(); + assert_eq!(text_layer(&s, id).char_runs()[0].style.size_pt, TYPE_SIZE_MIN_PT as f32, "bad steps fall back or clamp, never panic"); + assert_eq!(crate::commands::find("type.increaseSize").and_then(|c| c.shortcut), Some("Cmd+Shift+.")); + assert_eq!(crate::commands::find("type.decreaseSize").and_then(|c| c.shortcut), Some("Cmd+Shift+,")); +} + +#[test] +fn auto_name_skips_leading_blank_lines() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "\n \nHello\nworld"})).unwrap()["layer"].as_u64().unwrap(); + assert_eq!(layer_name_of(&s, id), "Hello"); + s.execute("type.edit", json!({"layer": id, "replace": {"start": 0, "end": 0, "text": "\n"}})).unwrap(); + s.execute("type.edit", json!({"layer": id, "text": "\n\nGoodbye"})).unwrap(); + assert_eq!(layer_name_of(&s, id), "Goodbye"); +} + +#[test] +fn custom_name_survives_text_edits() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello", "name": "Logo"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.edit", json!({"layer": id, "text": "Goodbye"})).unwrap(); + assert_eq!(layer_name_of(&s, id), "Logo"); + // Renamed after creation: kept too. + let id = s.execute("type.create", json!({"x": 0, "y": 80, "text": "Hello"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.renameLayer", json!({"layer": id, "name": "Caption"})).unwrap(); + s.execute("type.edit", json!({"layer": id, "text": "Goodbye"})).unwrap(); + assert_eq!(layer_name_of(&s, id), "Caption"); + // A name given with the edit wins over the text. + s.execute("type.edit", json!({"layer": id, "text": "Again", "name": "Footer"})).unwrap(); + assert_eq!(layer_name_of(&s, id), "Footer"); +} + +#[test] +fn edit_with_name_is_one_undo_step_for_text_name_and_bounds() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 10, "y": 50, "text": "Before", "size": 20, "name": "Original"})).unwrap()["layer"].as_u64().unwrap(); + let layer = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + let before_bounds = text_layer(&s, id).cache.unwrap().content_bounds(); + assert_eq!(layer.name, "Original"); + let steps = s.active().unwrap().history.entries().len(); + + s.execute("type.edit", json!({"layer": id, "text": "A much longer edited title that wraps", "box": [10, 10, 50, 60], "name": "Renamed"})).unwrap(); + + let edited = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + let edited_bounds = text_layer(&s, id).cache.unwrap().content_bounds(); + assert_eq!(edited.name, "Renamed"); + assert_eq!(text_layer(&s, id).text, "A much longer edited title that wraps"); + assert_ne!(edited_bounds, before_bounds); + assert_eq!(s.active().unwrap().history.entries().len(), steps + 1); + + assert!(s.undo()); + let restored = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + assert_eq!(restored.name, "Original"); + assert_eq!(text_layer(&s, id).text, "Before"); + assert_eq!(text_layer(&s, id).cache.unwrap().content_bounds(), before_bounds); +} + +#[test] +fn edit_replace_keeps_styles() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "fauxBold": true, "color": [0, 0, 1]})).unwrap(); + let t = text_layer(&s, id); + assert_eq!(t.runs.len(), 2); + assert_eq!(t.runs[0].len, 6); + assert!(t.runs[1].style.faux_bold); + // Insert inside the bold word: inherits bold. + s.execute("type.edit", json!({"layer": id, "replace": {"start": 8, "end": 8, "text": "XX"}})).unwrap(); + let t = text_layer(&s, id); + assert_eq!(t.text, "Hello woXXrld"); + assert_eq!(t.runs[1].len, 7); + // Delete across the style boundary. + s.execute("type.edit", json!({"layer": id, "replace": {"start": 3, "end": 8, "text": ""}})).unwrap(); + let t = text_layer(&s, id); + assert_eq!(t.text, "HelXXrld"); + assert_eq!(t.runs.iter().map(|r| r.len).collect::>(), vec![3, 5]); + // Whole-text replace with a multi-byte string. + let info = s.execute("type.edit", json!({"layer": id, "text": "Größe ✓\nzwei"})).unwrap(); + assert_eq!(info["lines"].as_array().unwrap().len(), 2); + let t = text_layer(&s, id); + assert_eq!(t.runs.iter().map(|r| r.len).sum::(), t.text.len()); +} + +#[test] +fn all_locked_type_edit_rejects_text_replacement_without_history() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 20, "y": 20, "text": "a", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": id, "locked": true})).unwrap(); + let history = s.active().unwrap().history.past_len(); + + let result = s.execute("type.edit", json!({"layer": id, "text": "b"})); + assert!(matches!(&result, Err(EngineError::Other(message)) if message.contains("locked")), "{result:?}"); + assert_eq!(text_layer(&s, id).text, "a"); + assert_eq!(s.active().unwrap().history.past_len(), history); + + s.execute("layer.setProps", json!({"layer": id, "locked": false})).unwrap(); + let history = s.active().unwrap().history.past_len(); + s.execute("type.edit", json!({"layer": id, "text": "b"})).unwrap(); + assert_eq!(text_layer(&s, id).text, "b"); + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(text_layer(&s, id).text, "a"); + assert_eq!(s.active().unwrap().history.past_len(), history); +} + +#[test] +fn all_locked_type_layer_rejects_formatting_without_history() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 20, "y": 20, "text": "a", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + let other = s.execute("type.create", json!({"x": 20, "y": 60, "text": "b", "size": 12})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": id, "locked": true})).unwrap(); + let before = text_layer(&s, id); + let history = s.active().unwrap().history.past_len(); + + for (cmd, p) in [ + ("type.setStyle", json!({"layer": id, "size": 40, "fauxBold": true})), + ("type.setStyle", json!({"layers": [other, id], "size": 40})), + ("type.warpText", json!({"layer": id, "style": "arc"})), + ("type.antiAlias.none", json!({"layer": id})), + ("type.orientation.vertical", json!({"layer": id})), + ("type.openType.swash", json!({"layer": id})), + ] { + let result = s.execute(cmd, p); + assert!(matches!(&result, Err(EngineError::Other(message)) if message.contains("locked")), "{cmd}: {result:?}"); + } + assert_eq!(text_layer(&s, id), before); + assert_eq!(text_layer(&s, other).size_pt, 12.0); + assert_eq!(s.active().unwrap().history.past_len(), history); + + s.execute("layer.setProps", json!({"layer": id, "locked": false})).unwrap(); + s.execute("type.setStyle", json!({"layer": id, "size": 40})).unwrap(); + assert_eq!(text_layer(&s, id).size_pt, 40.0); +} + +#[test] +fn trailing_empty_paragraph_styles_without_changing_previous_lines() { + let mut s = session(); + let id = s.execute("type.create", json!({"text":"a\nb\n","x":20,"y":20,"size":12,"font":"Inter","align":"left"})).unwrap()["layer"].as_u64().unwrap(); + let before = s.execute("type.info", json!({"layer":id})).unwrap(); + let previous_line = before["lines"][1].clone(); + + let styled = s.execute("type.setStyle", json!({"layer":id,"range":[4,4],"align":"right"})).unwrap(); + assert_eq!(styled["paragraphs"].as_array().unwrap().len(), 2); + assert_eq!(styled["paragraphs"][0]["start"], 0); + assert_eq!(styled["paragraphs"][0]["end"], 4); + assert_eq!(styled["paragraphs"][0]["style"]["align"], "Left"); + assert_eq!(styled["paragraphs"][1]["start"], 4); + assert_eq!(styled["paragraphs"][1]["end"], 4); + assert_eq!(styled["paragraphs"][1]["style"]["align"], "Right"); + assert_eq!(styled["lines"][1], previous_line, "the preceding paragraph must not move"); + let raw = text_layer(&s, id).psd_raw.clone().unwrap(); + let round_trip = photocraft_text::psd::text_layer_from_tysh(&raw, 72.0).unwrap(); + assert_eq!(round_trip.paragraph_runs().last().unwrap().style.align, TextAlign::Right); + + // Typing directly into the previously empty final paragraph retains its style. + let edited = s.execute("type.edit", json!({"layer":id,"replace":{"start":4,"end":4,"text":"c"}})).unwrap(); + assert_eq!(edited["text"], "a\nb\nc"); + assert_eq!(edited["paragraphs"][0]["end"], 4); + assert_eq!(edited["paragraphs"][0]["style"]["align"], "Left"); + assert_eq!(edited["paragraphs"][1]["start"], 4); + assert_eq!(edited["paragraphs"][1]["end"], 5); + assert_eq!(edited["paragraphs"][1]["style"]["align"], "Right"); + assert_eq!(edited["lines"][1], previous_line, "typing in the final paragraph does not move b"); +} + +#[test] +fn set_style_paragraph_and_box() { + let mut s = session(); + let id = s.execute("type.create", json!({"box": [10, 10, 80, 80], "text": "one two three four five six seven", "size": 12})).unwrap()["layer"] + .as_u64() + .unwrap(); + let info = s.execute("type.setStyle", json!({"layer": id, "align": "center", "leading": 20})).unwrap(); + let lines = info["lines"].as_array().unwrap(); + assert!(lines.len() >= 3); + let b0 = lines[0]["baseline"].as_f64().unwrap(); + let b1 = lines[1]["baseline"].as_f64().unwrap(); + assert!((b1 - b0 - 20.0).abs() < 1e-3, "explicit leading {b0} {b1}"); + assert_eq!(info["paragraphs"][0]["style"]["align"], "Center"); + let t = text_layer(&s, id); + assert!(matches!(t.shape, TextShape::Box { width, .. } if width == 80.0)); + // Pixels stay inside the box horizontally. + let r = t.cache.as_ref().unwrap().content_bounds(); + assert!(r.x0 >= 9 && r.x1 <= 91, "{r:?}"); + // Convert to point text and move. + s.execute("type.edit", json!({"layer": id, "point": [5, 30]})).unwrap(); + s.execute("type.edit", json!({"layer": id, "move": [10, 0]})).unwrap(); + let t = text_layer(&s, id); + assert_eq!(t.shape, TextShape::Point); + assert_eq!(t.transform.m[4], 15.0); +} + +#[test] +fn rasterize_and_fonts() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 5, "y": 30, "text": "Raster"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.rasterize", json!({"layer": id})).unwrap(); + let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + assert!(matches!(l.content, LayerContent::Raster(_))); + assert!(l.surface().unwrap().content_bounds().width() > 10); + assert!(s.execute("type.edit", json!({"layer": id, "text": "x"})).is_err()); + let fonts = s.execute("type.fonts", json!({})).unwrap(); + assert!(fonts["families"].as_array().unwrap().iter().any(|f| f == "Inter")); + let faces = s.execute("type.fonts", json!({"family": "Inter"})).unwrap(); + assert!(!faces["faces"].as_array().unwrap().is_empty()); +} + +/// #124: a type edit damages only the layer's old and new pixels (the canvas recomposites +/// that, not the document), and a drag's coalesced steps are one history step. +#[test] +fn type_edits_damage_only_the_layer_and_coalesce() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 3000, "height": 2000})).unwrap(); + let id = s.execute("type.create", json!({"x": 100, "y": 100, "text": "Hi", "size": 20})).unwrap()["layer"].as_u64().unwrap(); + let steps = s.active().unwrap().history.entries().len(); + for k in 0..5 { + s.execute("type.setStyle", json!({"layer": id, "size": 30 + k * 10, "coalesce": "drag"})).unwrap(); + let d = s.active().unwrap().last_damage.expect("damage rect"); + let r = text_layer(&s, id).cache.unwrap().content_bounds(); + assert!(d.intersect(&r) == r && d.width() <= 512 && d.height() <= 512, "{d:?} {r:?}"); + } + assert_eq!(s.active().unwrap().history.entries().len(), steps + 1); + assert!(s.undo()); + assert_eq!(text_layer(&s, id).runs[0].style.size_pt, 20.0); +} + +#[test] +fn edit_rejects_a_reversed_runs_range() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello world", "size": 20})).unwrap()["layer"].as_u64().unwrap(); + let before = text_layer(&s, id).char_runs(); + let steps = s.active().unwrap().history.entries().len(); + for runs in [ + json!([{"start": 5, "end": 2, "fauxBold": true}]), + json!([{"start": 0, "end": 3, "fauxBold": true}, {"start": 8, "end": 7}]), + json!([{"end": 0, "start": 1}]), + ] { + let e = s.execute("type.edit", json!({"layer": id, "runs": runs})).unwrap_err(); + assert!(matches!(e, EngineError::BadParams { .. }) && e.to_string().contains("is before `start`"), "{e}"); + } + // Nothing changed and nothing was recorded, not even the valid run before the bad one. + assert_eq!(text_layer(&s, id).char_runs(), before); + assert_eq!(s.active().unwrap().history.entries().len(), steps); + // The same range the right way round still styles it. + s.execute("type.edit", json!({"layer": id, "runs": [{"start": 2, "end": 5, "fauxBold": true}]})).unwrap(); + let runs = text_layer(&s, id).char_runs(); + assert_eq!(runs.iter().map(|r| (r.len, r.style.faux_bold)).collect::>(), [(2, false), (3, true), (6, false)]); +} + +#[test] +fn style_range_reversed_is_a_no_op() { + let mut t = TextLayer::default(); + replace_text(&mut t, 0, 0, "Hello world"); + let before = t.char_runs(); + style_range(&mut t, 5, 2, &|s| s.size_pt = 40.0); + assert_eq!(t.char_runs(), before); + assert_eq!(t.runs.iter().map(|r| r.len).sum::(), t.text.len()); +} + +#[test] +fn style_range_on_empty_text() { + let mut t = TextLayer::default(); + style_range(&mut t, 0, 0, &|s| s.size_pt = 40.0); + assert_eq!(t.runs[0].style.size_pt, 40.0); + replace_text(&mut t, 0, 0, "abc"); + assert_eq!(t.runs.len(), 1); + assert_eq!(t.runs[0].len, 3); + assert_eq!(t.runs[0].style.size_pt, 40.0); +} + +/// Replacing a selected smaller second line (by typing or pasting) keeps its size, not the +/// first line's, whose line break precedes the selection. +#[test] +fn replacing_a_selection_keeps_its_first_characters_style() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "BIG\nsmall", "size": 40})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.edit", json!({"layer": id, "runs": [{"start": 4, "end": 9, "size": 12}]})).unwrap(); + s.execute("type.edit", json!({"layer": id, "replace": {"start": 4, "end": 9, "text": "AIR"}})).unwrap(); + let sizes = |s: &Session| text_layer(s, id).char_runs().iter().map(|r| (r.len, r.style.size_pt)).collect::>(); + assert_eq!(text_layer(&s, id).text, "BIG\nAIR"); + assert_eq!(sizes(&s), [(4, 40.0), (3, 12.0)]); + // A mixed selection takes its first character's style. + s.execute("type.edit", json!({"layer": id, "replace": {"start": 2, "end": 6, "text": "xy"}})).unwrap(); + assert_eq!(sizes(&s), [(4, 40.0), (1, 12.0)]); + // Inserting at a caret still follows the character before it. + s.execute("type.edit", json!({"layer": id, "replace": {"start": 4, "end": 4, "text": "!"}})).unwrap(); + assert_eq!(sizes(&s), [(5, 40.0), (1, 12.0)]); +} + +/// A misspelt `baseline` is an error and keeps superscript, instead of resetting it to Normal. +#[test] +fn unknown_baseline_is_rejected_and_keeps_the_style() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "x2", "size": 30})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [1, 2], "baseline": "superscript"})).unwrap(); + let before = text_layer(&s, id).runs; + for b in [json!("superscipt"), json!("Superscript"), json!(1)] { + assert!(matches!(s.execute("type.setStyle", json!({"layer": id, "baseline": b})), Err(EngineError::BadParams { .. })), "{b}"); + assert!(s.execute("type.edit", json!({"layer": id, "baseline": b})).is_err(), "{b}"); + assert!(s.execute("type.create", json!({"x": 0, "y": 10, "text": "a", "baseline": b})).is_err(), "{b}"); + } + assert_eq!(text_layer(&s, id).runs, before); + s.execute("type.setStyle", json!({"layer": id, "baseline": "normal"})).unwrap(); + assert!(text_layer(&s, id).char_runs().iter().all(|r| r.style.baseline == FontBaseline::Normal)); +} + +fn kerning_of(s: &Session, id: u64) -> Vec<(Kerning, f32)> { + let t = text_layer(s, id); + let mut out = Vec::new(); + let mut at = 0; + for r in t.char_runs() { + out.extend(std::iter::repeat_n((r.style.kerning, r.style.kern), t.text[at..at + r.len].chars().count())); + at += r.len; + } + out +} + +/// #8489: `type.edit {"text"}` changes only what differs, so the rest keeps its styles: an +/// added character takes the style beside it, and a change inside one run stays in it. +#[test] +fn edit_text_keeps_the_styles_of_unchanged_text() { + // (characters, colour) per run. + fn runs(s: &Session, id: u64) -> Vec<(usize, [u8; 4])> { + let t = text_layer(s, id); + let mut at = 0; + t.char_runs() + .into_iter() + .map(|r| { + let n = t.text[at..at + r.len].chars().count(); + at += r.len; + (n, r.style.color.to_rgba8()) + }) + .collect() + } + let (dark, purple) = ([0x1b, 0x1f, 0x4b, 255], [0x5a, 0x3d, 0xf0, 255]); + let mut s = session(); + let id = s.execute("type.create", json!({"x": 20, "y": 50, "text": "Craft Suite in Workshop", "size": 40, "color": "#1b1f4b"})).unwrap()["layer"] + .as_u64() + .unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [15, 23], "color": "#5a3df0"})).unwrap(); + assert_eq!(runs(&s, id), [(15, dark), (8, purple)]); + s.execute("type.edit", json!({"layer": id, "text": "Craft Suite in Workshop!"})).unwrap(); + assert_eq!(runs(&s, id), [(15, dark), (9, purple)], "the added character joins the last run"); + s.execute("type.edit", json!({"layer": id, "text": "Craft Suite in Worksh\u{f6}p!"})).unwrap(); + assert_eq!(runs(&s, id), [(15, dark), (9, purple)], "a change inside a run stays in it"); + s.execute("type.edit", json!({"layer": id, "text": "Kraft Suite in Worksh\u{f6}p!"})).unwrap(); + assert_eq!(runs(&s, id), [(15, dark), (9, purple)]); + // Replacing everything leaves one style, as before. + s.execute("type.edit", json!({"layer": id, "text": "Hello"})).unwrap(); + assert_eq!(text_layer(&s, id).text, "Hello"); + assert_eq!(runs(&s, id).iter().map(|r| r.0).sum::(), 5); + s.execute("type.edit", json!({"layer": id, "text": ""})).unwrap(); + assert_eq!(text_layer(&s, id).text, ""); + + // Text inserted at the start of a paragraph joins that paragraph, which keeps its style. + let id = s + .execute( + "type.create", + json!({"x": 20, "y": 50, "text": "a +b", "size": 20}), + ) + .unwrap()["layer"] + .as_u64() + .unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [2, 3], "align": "right"})).unwrap(); + s.execute( + "type.edit", + json!({"layer": id, "text": "a +Xb"}), + ) + .unwrap(); + let paragraphs: Vec<(usize, photocraft_doc::text::TextAlign)> = + text_layer(&s, id).paragraph_runs().into_iter().map(|r| (r.len, r.style.align)).collect(); + assert_eq!(paragraphs.first().map(|p| p.0), Some(2), "{paragraphs:?}"); + assert_eq!(paragraphs.get(1).copied(), Some((2, photocraft_doc::text::TextAlign::Right)), "{paragraphs:?}"); +} + +/// #206: `type.edit {"kerning"}` over a range takes a number (manual, 1/1000 em) or a mode. +#[test] +fn edit_sets_kerning_over_a_range() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "AVAT", "size": 30})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.edit", json!({"layer": id, "range": [0, 1], "kerning": 100})).unwrap(); + s.execute("type.edit", json!({"layer": id, "range": [2, 4], "kerning": "optical"})).unwrap(); + assert_eq!(kerning_of(&s, id), vec![(Kerning::Off, 100.0), (Kerning::Metrics, 0.0), (Kerning::Optical, 0.0), (Kerning::Optical, 0.0)]); + s.execute("type.edit", json!({"layer": id, "kerning": "metrics"})).unwrap(); + assert!(kerning_of(&s, id).iter().all(|k| *k == (Kerning::Metrics, 0.0))); + // Runs and setStyle take the same values; type.info reports them. + s.execute("type.edit", json!({"layer": id, "runs": [{"start": 1, "end": 2, "kerning": -50}]})).unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [3, 4], "kerning": "off"})).unwrap(); + assert_eq!(kerning_of(&s, id)[1], (Kerning::Off, -50.0)); + assert_eq!(kerning_of(&s, id)[3], (Kerning::Off, 0.0)); + let info = s.execute("type.info", json!({"layer": id})).unwrap(); + assert_eq!(info["runs"][1]["style"]["kern"], json!(-50.0)); +} + +/// Bad kerning params are errors, never panics, and leave the layer alone. +#[test] +fn kerning_params_fail_gracefully() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "AV\nT", "size": 30})).unwrap()["layer"].as_u64().unwrap(); + let before = text_layer(&s, id); + for p in [ + json!({"kerning": "tight"}), + json!({"kerning": 1e9}), + json!({"kerning": -5000}), + json!({"kerning": true}), + json!({"kerning": [1]}), + json!({"runs": [{"start": 0, "end": 1, "kerning": "x"}]}), + json!({"kernPair": 3}), + json!({"kernPair": {"by": 20}}), + json!({"kernPair": {"at": 1}}), + json!({"kernPair": {"at": 1, "by": "20"}}), + json!({"kernPair": {"at": 1, "by": 1e12}}), + json!({"kernPair": {"at": 0, "by": 20}}), + json!({"kernPair": {"at": 4, "by": 20}}), + json!({"kernPair": {"at": 99, "by": 20}}), + json!({"kernPair": {"at": 2, "by": 20}}), + json!({"kernPair": {"at": 3, "by": 20}}), + json!({"kernPair": {"at": -1, "by": 20}}), + ] { + let mut p = p; + p["layer"] = json!(id); + assert!(s.execute("type.edit", p.clone()).is_err(), "{p}"); + } + assert!(s.execute("type.setStyle", json!({"layer": id, "kerning": "tight"})).is_err()); + assert_eq!(text_layer(&s, id).runs, before.runs); + // type.create rejects the same values and creates no layer (#994). + let layers = s.active().unwrap().doc.layer_count(); + for k in [json!("tight"), json!(1e9), json!(-5000), json!(true), json!([1])] { + let p = json!({"x": 0, "y": 10, "text": "AV", "kerning": k}); + assert!(s.execute("type.create", p.clone()).is_err(), "{p}"); + } + assert_eq!(s.active().unwrap().doc.layer_count(), layers); + let id = s.execute("type.create", json!({"x": 0, "y": 10, "text": "AV", "kerning": "optical"})).unwrap()["layer"].as_u64().unwrap(); + assert!(kerning_of(&s, id).iter().all(|k| *k == (Kerning::Optical, 0.0))); + let id = s.execute("type.create", json!({"x": 0, "y": 10, "text": "AV", "kerning": -50})).unwrap()["layer"].as_u64().unwrap(); + assert!(kerning_of(&s, id).iter().all(|k| *k == (Kerning::Off, -50.0))); +} + +/// Cost of one Alt+←/→ press (`kernPair`: two measuring layouts + the edit's re-render) on +/// a headline and on a 2000-character paragraph. Release timings for the dev log: +/// `cargo test --release -p photocraft-engine kern_pair_cost -- --ignored --nocapture`. +#[test] +#[ignore] +fn kern_pair_cost() { + let para = "The quick brown fox jumps over the lazy dog. ".repeat(45); + for (name, text, size, bx, kerning) in [ + ("headline", "AVATAR Wave", 72, false, "metrics"), + ("paragraph", para.as_str(), 12, true, "metrics"), + ("optical paragraph", para.as_str(), 12, true, "optical"), + ] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2000, "height": 1500})).unwrap(); + let mut p = json!({"x": 20, "y": 100, "text": text, "size": size, "font": "Inter", "kerning": kerning}); + if bx { + p["box"] = json!([20, 20, 900, 1400]); + } + let id = s.execute("type.create", p).unwrap()["layer"].as_u64().unwrap(); + let n = 20; + let t0 = std::time::Instant::now(); + for i in 0..n { + s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1 + i % 3, "by": 20}})).unwrap(); + } + let per = t0.elapsed().as_secs_f64() * 1000.0 / f64::from(n); + let t1 = std::time::Instant::now(); + for i in 0..n { + s.execute("type.setStyle", json!({"layer": id, "range": [1 + i % 3, 2 + i % 3], "tracking": i})).unwrap(); + } + let base = t1.elapsed().as_secs_f64() * 1000.0 / f64::from(n); + eprintln!("{name} ({} chars): kernPair {per:.2} ms/press; a plain style edit {base:.2} ms", text.chars().count()); + } +} + +/// Photoshop's Alt+←/→: the pair before the caret becomes manual, starting from the kerning +/// it shows (the font's pair kerning for "AV"), ±20 per press, one history step each. +#[test] +fn kern_pair_steps_from_the_shown_kerning() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 5, "y": 50, "text": "AVA", "size": 40, "font": "Inter"})).unwrap()["layer"].as_u64().unwrap(); + let metric = { + let t = text_layer(&s, id); + photocraft_text::shared().lock().unwrap().pair_kerning(&t, 72.0, 0).unwrap() + }; + assert!(metric < -10.0, "Inter kerns AV: {metric}"); + let steps = s.active().unwrap().history.entries().len(); + s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1, "by": 20}})).unwrap(); + let k0 = kerning_of(&s, id)[0]; + assert_eq!(k0, (Kerning::Off, metric.round() + 20.0)); + s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1, "by": 100}})).unwrap(); + assert_eq!(kerning_of(&s, id)[0].1, metric.round() + 120.0); + s.execute("type.edit", json!({"layer": id, "kernPair": {"at": 1, "by": -20}})).unwrap(); + assert_eq!(kerning_of(&s, id)[0].1, metric.round() + 100.0); + // Other characters are untouched; each press is its own undoable step. + assert_eq!(&kerning_of(&s, id)[1..], &[(Kerning::Metrics, 0.0), (Kerning::Metrics, 0.0)]); + assert_eq!(s.active().unwrap().history.entries().len(), steps + 3); + assert!(s.undo()); + assert_eq!(kerning_of(&s, id)[0].1, metric.round() + 120.0); + assert!(s.undo() && s.undo()); + assert_eq!(kerning_of(&s, id)[0], (Kerning::Metrics, 0.0)); +} +#[test] +fn create_vertical_type_is_atomic_and_invalid_orientation_is_rejected() { + for boxed in [false, true] { + let mut s = session(); + let before = s.active().unwrap().history.entries().len(); + for orientation in [json!("diagonal"), json!(null), json!(true)] { + assert!(s.execute("type.create", json!({"text": "test", "orientation": orientation})).is_err()); + assert_eq!(s.active().unwrap().history.entries().len(), before); + } + let mut p = json!({"text": "test", "orientation": "vertical", "x": 20, "y": 20}); + if boxed { + p["box"] = json!([20, 20, 80, 60]); + } + let id = s.execute("type.create", p).unwrap()["layer"].as_u64().unwrap(); + let t = text_layer(&s, id); + assert_eq!(t.orientation, Orientation::Vertical); + assert_eq!(matches!(t.shape, TextShape::Box { .. }), boxed); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.layer(LayerId(id)).is_none()); + } +} + +#[test] +fn missing_font_emits_warning_in_create_set_style_and_edit() { + let mut s = session(); + let r = s.execute("type.create", json!({"x": 10, "y": 20, "text": "Hello", "font": "NoSuchFamily123"})).unwrap(); + assert_eq!(r["warnings"], json!(["font 'NoSuchFamily123' is not installed; text may render using a fallback face"])); + let id = r["layer"].as_u64().unwrap(); + let styled = s.execute("type.setStyle", json!({"layer": id, "font": "StillNoSuchFamily456"})).unwrap(); + assert_eq!(styled["warnings"], json!(["font 'StillNoSuchFamily456' is not installed; text may render using a fallback face"])); + let edited = s.execute("type.edit", json!({"layer": id, "runs": [{"start": 0, "end": 2, "font": "AnotherMissingFont789"}]})).unwrap(); + assert_eq!( + edited["warnings"], + json!([ + "font 'AnotherMissingFont789' is not installed; text may render using a fallback face", + "font 'StillNoSuchFamily456' is not installed; text may render using a fallback face" + ]) + ); +} + +/// `leadingBy`, `baselineShiftBy` and `trackingBy` step every character from its own value +/// (auto leading from its laid-out value), clamp to Photoshop's ranges, and reject hostile +/// steps without changing anything. +#[test] +fn relative_steps_move_each_character_from_its_own_value() { + let mut s = session(); + let id = s.execute("type.create", json!({"x": 0, "y": 40, "text": "Hello\nworld", "size": 10})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [8, 11], "leading": 30, "tracking": 50})).unwrap(); + s.execute("type.setStyle", json!({"layer": id, "range": [6, 11], "autoLeading": 150})).unwrap(); + let steps = s.active().unwrap().history.entries().len(); + s.execute("type.setStyle", json!({"layer": id, "range": [0, 11], "leadingBy": 2, "baselineShiftBy": -2, "trackingBy": 20})).unwrap(); + assert_eq!(s.active().unwrap().history.entries().len(), steps + 1, "one history step"); + let t = text_layer(&s, id); + let at = |c: usize| { + let byte = byte_at(&t.text, c); + let mut off = 0; + t.char_runs() + .into_iter() + .find(|r| { + off += r.len; + off > byte + }) + .unwrap() + .style + }; + // Auto leading 120% × 10 pt (first paragraph), 150% × 10 pt (second), and a set 30 pt. + assert_eq!(at(0).leading_pt, Some(14.0)); + assert_eq!(at(6).leading_pt, Some(17.0)); + assert_eq!(at(9).leading_pt, Some(32.0)); + assert_eq!((at(0).baseline_shift_pt, at(9).baseline_shift_pt), (-2.0, -2.0)); + assert_eq!((at(0).tracking, at(9).tracking), (20.0, 70.0)); + // Clamped to the ranges. + s.execute("type.setStyle", json!({"layer": id, "leadingBy": -5000, "baselineShiftBy": 10000, "trackingBy": -11000})).unwrap(); + let t = text_layer(&s, id); + assert!(t.char_runs().iter().all(|r| r.style.leading_pt == Some(LEADING_MIN_PT) + && r.style.baseline_shift_pt == BASELINE_SHIFT_MAX_PT + && r.style.tracking == TRACKING_MIN as f32)); + // A collapsed range in non-empty text changes no character. + let before = text_layer(&s, id).char_runs(); + s.execute("type.setStyle", json!({"layer": id, "range": [3, 3], "trackingBy": 100})).unwrap(); + assert_eq!(text_layer(&s, id).char_runs(), before); + // Hostile steps are refused. + let steps = s.active().unwrap().history.entries().len(); + for bad_step in [json!({"leadingBy": "up"}), json!({"trackingBy": 1e30}), json!({"baselineShiftBy": null}), json!({"leadingBy": [1]})] { + let mut p = bad_step.clone(); + p["layer"] = json!(id); + assert!(matches!(s.execute("type.setStyle", p), Err(EngineError::BadParams { .. })), "{bad_step}"); + } + assert_eq!(s.active().unwrap().history.entries().len(), steps); + // Empty text: the step sets the style the next typed characters get. + let empty = s.execute("type.create", json!({"x": 0, "y": 80, "text": "", "size": 10})).unwrap()["layer"].as_u64().unwrap(); + s.execute("type.setStyle", json!({"layer": empty, "range": [0, 0], "leadingBy": -2})).unwrap(); + assert_eq!(text_layer(&s, empty).char_runs()[0].style.leading_pt, Some(10.0)); +} From a1c086261314a325eb33119d79fe6c8120d15bfd Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:10 +0000 Subject: [PATCH 028/259] refactor(engine): move edit_cmds.rs tests to edit_cmds/tests.rs --- crates/engine/src/edit_cmds.rs | 1469 +------------------------- crates/engine/src/edit_cmds/tests.rs | 1466 +++++++++++++++++++++++++ 2 files changed, 1467 insertions(+), 1468 deletions(-) create mode 100644 crates/engine/src/edit_cmds/tests.rs diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs index 4631cbae75..eb77590999 100644 --- a/crates/engine/src/edit_cmds.rs +++ b/crates/engine/src/edit_cmds.rs @@ -1108,1471 +1108,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, a| { - doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 50, 30), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s - } - - #[test] - fn new_clipboard_document_rejects_an_unrepresentable_origin() { - let mut s = Session::new(); - let mut surface = Surface::new(PixelFormat::RGBA8); - surface.write_pixel(i32::MIN, 0, &[1.0, 0.0, 0.0, 1.0]); - s.clipboard = Some(Clip { surface, bounds: Rect::from_xywh(i32::MIN, 0, 1, 1), layers: None, resolution: None, source: None }); - let result = new_from_clipboard(&mut s); - assert!(result.unwrap_err().to_string().contains("clipboard origin")); - assert!(s.execute("file.newFromClipboard", json!({})).is_err()); - assert!(s.documents().is_empty()); - assert_eq!(s.clipboard.as_ref().unwrap().surface.rgba(i32::MIN, 0), [1.0, 0.0, 0.0, 1.0]); - } - - /// #8945: pixels copied in one document land in place when pasted back into it, and centred - /// in another, even where their old position would fit (Photoshop's Paste). - #[test] - fn paste_centres_pixels_from_another_document() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap(); - s.execute("select.all", json!({})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - let r = s.execute("edit.paste", json!({})).unwrap(); - assert_eq!(r["offset"], json!([0, 0]), "back into its own document: in place"); - s.execute("file.new", json!({"width": 100, "height": 80, "background": "white"})).unwrap(); - let r = s.execute("edit.paste", json!({})).unwrap(); - assert_eq!(r["offset"], json!([30, 25]), "into another document: centred"); - // An image from another app has no source document: centred too. - s.clipboard = s.clipboard.take().map(|c| Clip { source: None, ..c }); - let r = s.execute("edit.paste", json!({})).unwrap(); - assert_eq!(r["offset"], json!([30, 25])); - // Paste in Place still keeps the position. - let r = s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - assert_eq!(r["offset"], json!([0, 0])); - } - - #[test] - fn paste_centers_clipboard_bounds_near_coordinate_limits() { - for origin in [i32::MAX - 512, i32::MIN + 512] { - let clip = - Clip { surface: Surface::new(PixelFormat::RGBA8), bounds: Rect::from_xywh(origin, origin, 2, 2), layers: None, resolution: None, source: None }; - let (dx, dy) = paste_offset(&clip, DocId(1), Rect::new(0, 0, 20, 20), &json!({}), false); - assert_eq!(i64::from(origin) + i64::from(dx), 9); - assert_eq!(i64::from(origin) + i64::from(dy), 9); - let clip = Clip { bounds: Rect::new(0, 0, 2, 2), ..clip }; - let (dx, dy) = paste_offset(&clip, DocId(1), Rect::from_xywh(origin, origin, 20, 20), &json!({}), false); - assert_eq!(dx, origin + 9); - assert_eq!(dy, origin + 9); - } - } - - #[test] - fn injected_clear_buffer_failure_leaves_the_document_unchanged() { - let mut s = session(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); - let revision = st.revision; - - crate::allocation::fail_next_for_test(); - let result = s.execute("edit.clear", json!({})); - - assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for erasing pixels"))); - let st = s.active().unwrap(); - assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); - assert_eq!(st.revision, revision); - } - - #[test] - fn injected_copy_buffer_failure_does_not_change_document_or_clipboard() { - let mut s = session(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); - let revision = st.revision; - - crate::allocation::fail_next_for_test(); - let result = s.execute("edit.copy", json!({})); - - assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for copying pixels"))); - let st = s.active().unwrap(); - assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); - assert_eq!(st.revision, revision); - assert!(s.clipboard.is_none()); - } - - #[test] - fn injected_fill_result_reservation_failure_keeps_pixels_and_history() { - let mut s = session(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); - let revision = st.revision; - let history_len = st.history.past_len(); - - crate::allocation::fail_next_for_test(); - let result = s.execute("edit.fill", json!({"color": "#00ff00"})); - - assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for blending pixels"))); - let st = s.active().unwrap(); - assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); - assert_eq!(st.revision, revision); - assert_eq!(st.history.past_len(), history_len); - } - - #[test] - fn injected_paste_failure_does_not_change_document_or_clipboard() { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 8, "height": 8})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - let before_clip = s.clipboard.clone(); - let st = s.active().unwrap(); - let before_doc = (*st.doc).clone(); - let revision = st.revision; - let history_len = st.history.past_len(); - - crate::allocation::fail_next_for_test(); - let result = s.execute("edit.paste", json!({})); - - assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for pasting pixels"))); - let st = s.active().unwrap(); - assert_eq!(*st.doc, before_doc); - assert_eq!(st.revision, revision); - assert_eq!(st.history.past_len(), history_len); - let after_clip = s.clipboard.as_ref().expect("clipboard remains available"); - let before_clip = before_clip.as_ref().expect("clipboard was populated"); - assert_eq!(after_clip.bounds, before_clip.bounds); - assert_eq!(after_clip.surface, before_clip.surface); - } - - #[test] - fn injected_transform_failure_keeps_pixels_and_history() { - let mut s = session(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); - let revision = st.revision; - let history_len = st.history.past_len(); - - crate::allocation::fail_next_for_test(); - let result = s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 20, 30]})); - - assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for transforming pixels"))); - let st = s.active().unwrap(); - assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); - assert_eq!(st.revision, revision); - assert_eq!(st.history.past_len(), history_len); - } - - fn active_bounds(s: &Session) -> Rect { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds() - } - - /// New from Clipboard takes the copied document's resolution (Photoshop's Clipboard preset), - /// so a later Image Size by resolution scales from the right size. - #[test] - fn new_from_clipboard_keeps_the_source_resolution() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 60, "height": 40, "resolution": 300})).unwrap(); - s.execute("select.all", json!({})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("file.newFromClipboard", json!({})).unwrap(); - assert_eq!(s.active().unwrap().doc.resolution_dpi, 300.0); - } - - /// #368: the clipboard as a document of its own, from New from Clipboard or a Paste with - /// nothing open, at every depth. - #[test] - fn new_from_clipboard_and_paste_with_no_document() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - assert!(!s.is_enabled("file.newFromClipboard") && !s.is_enabled("edit.paste"), "nothing copied yet"); - assert!(s.execute("file.newFromClipboard", json!({})).is_err()); - s.execute("file.new", json!({"width": 100, "height": 100, "depth": depth})).unwrap(); - assert!(!s.active().unwrap().is_dirty(), "an untouched blank document is clean"); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - s.execute("select.rect", json!({"x": 10, "y": 20, "width": 30, "height": 15})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - // With a document open: a second document, sized to the copy, its pixels at the origin. - let r = s.execute("file.newFromClipboard", json!({})).unwrap(); - assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(30), Some(15)), "{r}"); - assert_eq!(s.documents().len(), 2); - assert!(s.active().unwrap().is_dirty(), "a document made from clipboard pixels needs saving (#4665)"); - let d = &s.active().unwrap().doc; - assert_eq!((d.size.width, d.size.height, d.layers.len()), (30, 15, 1)); - assert_eq!(d.pixel_format().sample, s.documents()[0].doc.pixel_format().sample, "{depth}-bit kept"); - assert_eq!(active_bounds(&s), Rect::new(0, 0, 30, 15)); - let px = d.layers[0].surface().unwrap().rgba(0, 0); - assert!(px[0] > 0.99 && px[1] < 0.01 && px[3] > 0.99, "{px:?}"); - // With nothing open, Paste makes the document too. - while s.active().is_some() { - s.execute("file.close", json!({})).unwrap(); - } - assert!(s.is_enabled("edit.paste") && !s.is_enabled("edit.pasteSpecial.pasteInPlace")); - s.execute("edit.paste", json!({})).unwrap(); - assert_eq!(s.documents().len(), 1); - assert!(s.active().unwrap().is_dirty(), "Paste with no tab also needs a save prompt"); - assert_eq!(active_bounds(&s), Rect::new(0, 0, 30, 15)); - assert!(s.execute("edit.pasteSpecial.pasteInPlace", json!({})).is_ok(), "into the new document"); - } - } - - #[test] - fn copy_paste_in_place_and_centred() { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 30)); - assert!(s.active().unwrap().doc.selection.is_none()); - s.execute("edit.paste", json!({"center": [70, 70]})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(60, 60, 80, 80)); - assert_eq!(s.active().unwrap().doc.layers.len(), 4); - } - - /// A `w`×`h` document with an opaque `cw`×`ch` image from another app on the clipboard. - fn external_clip_session(w: i32, h: i32, cw: i32, ch: i32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": w, "height": h})).unwrap(); - let mut surface = Surface::new(PixelFormat::RGBA8); - surface.fill_rect(Rect::new(0, 0, cw, ch), &[1.0, 0.0, 0.0, 1.0]); - s.clipboard = Some(Clip { surface, bounds: Rect::new(0, 0, cw, ch), layers: None, resolution: None, source: None }); - s - } - - /// #6759: wherever the view is centred, a paste that fits the canvas stays wholly on it. - #[test] - fn paste_that_fits_stays_on_the_canvas() { - for (w, h, center, want) in [ - (60, 100, [40.0, 45.0], Rect::new(0, 0, 60, 100)), - (60, 100, [-500.0, 900.0], Rect::new(0, 0, 60, 100)), - (100, 100, [10.0, 80.0], Rect::new(0, 0, 60, 100)), - (100, 100, [95.0, 50.0], Rect::new(40, 0, 100, 100)), - (100, 120, [50.0, 60.0], Rect::new(20, 10, 80, 110)), - ] { - let mut s = external_clip_session(w, h, 60, 100); - s.execute("edit.paste", json!({ "center": center })).unwrap(); - assert_eq!(active_bounds(&s), want, "{w}x{h} canvas, view centre {center:?}"); - } - } - - /// #6759: a paste larger than the canvas starts at its top-left corner, wherever the view is. - #[test] - fn paste_larger_than_the_canvas_starts_at_its_top_left() { - for center in [[0.0, 0.0], [25.0, 20.0], [1000.0, 1000.0], [-1000.0, 30.0]] { - let mut s = external_clip_session(50, 40, 60, 100); - s.execute("edit.paste", json!({ "center": center })).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(0, 0, 60, 100), "view centre {center:?}"); - } - // Wider but not taller: at the left edge, and wholly inside vertically. - for (center, want) in - [([500.0, 500.0], Rect::new(0, 100, 60, 200)), ([-500.0, -500.0], Rect::new(0, 0, 60, 100)), ([25.0, 120.0], Rect::new(0, 70, 60, 170))] - { - let mut s = external_clip_session(50, 200, 60, 100); - s.execute("edit.paste", json!({ "center": center })).unwrap(); - assert_eq!(active_bounds(&s), want, "view centre {center:?}"); - } - } - - /// Paste Into centres on the selection even where that runs off the canvas. - #[test] - fn paste_into_is_not_clamped_to_the_canvas() { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 90, "y": 90, "width": 10, "height": 10})).unwrap(); - s.execute("edit.pasteSpecial.pasteInto", json!({})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(75, 85, 115, 105)); - } - - /// The clamp never overflows or panics: NaN, infinite and `i32`-limit shifts saturate (Rule 9). - #[test] - fn paste_offset_clamp_survives_extreme_coordinates() { - assert_eq!(clamp_shift(f64::NAN, 0, 10, 0, 100), 0); - assert_eq!(clamp_shift(f64::INFINITY, 0, 10, 0, 100), 90); - assert_eq!(clamp_shift(f64::NEG_INFINITY, i32::MIN, i32::MAX, 0, 1), i32::MAX); - assert_eq!(clamp_shift(1e30, i32::MIN, i32::MIN + 1, i32::MAX - 1, i32::MAX), i32::MAX); - let clip = Clip { - surface: Surface::new(PixelFormat::RGBA8), - bounds: Rect::new(i32::MAX - 2, i32::MAX - 2, i32::MAX, i32::MAX), - layers: None, - resolution: None, - source: None, - }; - let (dx, dy) = paste_offset(&clip, DocId(1), Rect::new(i32::MIN, i32::MIN, i32::MIN + 4, i32::MIN + 4), &json!({}), false); - assert_eq!((dx, dy), (i32::MIN, i32::MIN), "an unrepresentable shift saturates instead of wrapping"); - } - - #[test] - fn paste_with_malformed_center_does_not_panic() { - // A short/empty `center` array must not panic (Rule 9) — it falls back to the canvas centre. - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - for center in [json!([5]), json!([]), json!("nope"), json!([1, 2, 3])] { - // Fresh clipboard each time is unnecessary; copy persists. Must return Ok, never panic. - assert!(s.execute("edit.paste", json!({ "center": center })).is_ok(), "center={center}"); - } - } - - #[test] - fn copy_paste_between_documents() { - // Copy in one tab, paste into another: the clipboard is shared across documents. - let mut s = session(); // doc A (100x100): red rect at (10,10)-(50,30) - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - // Open a second document (a new tab), which becomes active. - s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - assert_eq!(s.active_index().unwrap(), 1, "the new document is the active tab"); - let before = s.active().unwrap().doc.layers.len(); - s.execute("edit.paste", json!({})).unwrap(); - assert_eq!(s.active_index().unwrap(), 1, "paste stays in the second tab"); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers.len(), before + 1, "pasted layer added to the second document"); - let pasted = d.layers.last().unwrap().surface().unwrap(); - let cb = pasted.content_bounds(); - let (cx, cy) = (cb.x0 + cb.width() as i32 / 2, cb.y0 + cb.height() as i32 / 2); - let mut px = [[0.0f32; 4]; 1]; - pasted.read_rgba_into(Rect::new(cx, cy, cx + 1, cy + 1), &mut px); - assert!(px[0][0] > 0.9 && px[0][1] < 0.1 && px[0][2] < 0.1, "pasted content is red: {:?}", px[0]); - } - - /// #2901 (P10/P11): Paste, Paste in Place and Paste Into recomposite only where the pasted - /// layer draws, not the whole document; nothing outside that changes, and undo brings back - /// exactly the old pixels. - #[test] - fn paste_damages_only_the_pasted_layer() { - let render = |s: &Session| photocraft_compose::render(&s.active().unwrap().doc, s.active().unwrap().doc.bounds()); - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 60, "height": 50, "depth": depth, "background": "white"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 8})).unwrap(); - s.execute("edit.fill", json!({"color": "#3366cc"})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - // Half transparent, so an opaque copy pasted in place over it shows. - s.execute("layer.setProps", json!({"opacity": 0.5})).unwrap(); - for (id, p) in [ - ("edit.paste", json!({"center": [40, 30]})), - ("edit.pasteSpecial.pasteInPlace", json!({})), - ("edit.pasteSpecial.pasteInto", json!({"center": [40, 30]})), - ] { - s.execute("select.rect", json!({"x": 36, "y": 27, "width": 6, "height": 4})).unwrap(); - let shown = render(&s); - s.execute(id, p).unwrap(); - let st = s.active().unwrap(); - let area = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); - let damage = st.last_damage.unwrap_or_else(|| panic!("{depth}-bit {id}: bounded damage")); - assert!(!damage.is_empty() && damage.intersect(&area) == damage, "{depth}-bit {id}: {damage:?} within {area:?}"); - let now = render(&s); - assert_ne!(now, shown, "{depth}-bit {id}: the paste shows"); - let w = shown.rect.width() as usize; - for (i, (a, b)) in shown.px.iter().zip(&now.px).enumerate() { - if !damage.contains((i % w) as i32, (i / w) as i32) { - assert_eq!(a, b, "{depth}-bit {id}: pixel {i} outside the damage changed"); - } - } - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(render(&s), shown, "{depth}-bit {id}: undo"); - } - } - } - - /// #1035: a `depth`-bit document with a blue-grey square copied from layer `src` (at - /// (5,5)-(15,15)) and an active layer `m` above it with a hide-all mask. - fn mask_target_session(depth: u32) -> (Session, LayerId, LayerId) { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth})).unwrap(); - let src = LayerId(s.execute("layer.new.layer", json!({"name": "src"})).unwrap()["layer"].as_u64().unwrap()); - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); - s.execute("edit.fill", json!({"color": "#3366cc"})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - let m = LayerId(s.execute("layer.new.layer", json!({"name": "m"})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.layerMask.hideAll", json!({})).unwrap(); - (s, src, m) - } - - /// The luminosity of `src`'s pixel at (`x`, `y`): what a paste into a mask writes there. - fn luminosity(s: &Session, src: LayerId, x: i32, y: i32) -> f32 { - let p = s.active().unwrap().doc.layer(src).unwrap().surface().unwrap().rgba(x, y); - photocraft_color::convert::rgb_to_gray([p[0], p[1], p[2]]) - } - - fn mask_at(s: &Session, id: LayerId, x: i32, y: i32) -> f32 { - s.active().unwrap().doc.layer(id).unwrap().mask.as_ref().unwrap().value(x, y) - } - - #[test] - fn paste_into_a_targeted_mask_writes_the_luminosity_in_one_step() { - for depth in [8, 16, 32] { - let (mut s, src, m) = mask_target_session(depth); - let lum = luminosity(&s, src, 10, 10); - assert!(lum > 0.05 && lum < 0.95, "{depth}-bit: a mid grey ({lum})"); - let (layers, steps) = (s.active().unwrap().doc.layer_count(), s.active().unwrap().history.past_len()); - s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": "mask"})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(st.doc.layer_count(), layers, "{depth}-bit: no new layer"); - assert_eq!(st.history.past_len(), steps + 1, "{depth}-bit: one history step"); - assert_eq!(st.active_layer, Some(m)); - assert!((mask_at(&s, m, 10, 10) - lum).abs() < 2.0 / 255.0, "{depth}-bit: {} vs {lum}", mask_at(&s, m, 10, 10)); - assert_eq!(mask_at(&s, m, 20, 20), 0.0, "{depth}-bit: the mask outside the paste is unchanged"); - assert!(st.doc.layer(m).unwrap().surface().unwrap().content_bounds().is_empty(), "{depth}-bit: the pixels are untouched"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(mask_at(&s, m, 10, 10), 0.0, "{depth}-bit: undo restores the mask"); - } - } - - #[test] - fn copy_with_the_mask_targeted_takes_the_mask_as_grayscale() { - for depth in [8, 16, 32] { - let (mut s, _, m) = mask_target_session(depth); - s.edit("paint mask", |doc, _| { - doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); - Ok(()) - }) - .unwrap(); - let steps = s.active().unwrap().history.past_len(); - let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); - assert_eq!(r["bounds"], json!([0, 0, 40, 40]), "{depth}-bit: a mask copies whole, as in Photoshop"); - assert_eq!(s.active().unwrap().history.past_len(), steps, "{depth}-bit: copy adds no history step"); - let clip = s.clipboard.clone().unwrap(); - let px = clip.surface.rgba(10, 10); - assert!((px[0] - 0.75).abs() < 2.0 / 255.0, "{depth}-bit: {} vs 0.75", px[0]); - assert!(clip.surface.rgba(30, 30)[0] < 0.01, "{depth}-bit: the hidden area copies as black"); - assert!(px[3] > 0.99, "{depth}-bit: the copy is opaque"); - // Paste it into another layer's reveal-all mask: it replaces that mask (the request - // in #2928): the square, and the black around it, land. - let m2 = LayerId(s.execute("layer.new.layer", json!({"name": "m2"})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": "mask"})).unwrap(); - assert!((mask_at(&s, m2, 10, 10) - 0.75).abs() < 2.0 / 255.0, "{depth}-bit: the copied mask lands"); - assert!(mask_at(&s, m2, 30, 30) < 0.01, "{depth}-bit: the copied black replaces the reveal-all"); - } - } - - #[test] - fn an_untouched_mask_copies_the_whole_canvas_at_its_default() { - let (mut s, _, _) = mask_target_session(8); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); - assert_eq!(r["bounds"], json!([0, 0, 40, 40]), "a plain Reveal All mask still transfers"); - assert!(s.clipboard.clone().unwrap().surface.rgba(20, 20)[0] > 0.99); - } - - #[test] - fn mask_copy_takes_only_the_selection() { - let (mut s, _, m) = mask_target_session(8); - s.edit("paint mask", |doc, _| { - doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); - Ok(()) - }) - .unwrap(); - s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); - let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); - assert_eq!(r["bounds"], json!([8, 8, 4, 4])); - let clip = s.clipboard.clone().unwrap(); - assert!((clip.surface.rgba(9, 9)[0] - 0.75).abs() < 2.0 / 255.0); - assert!(clip.surface.rgba(5, 5)[3] < 0.01, "nothing outside the selection"); - } - - #[test] - fn mask_copy_needs_a_mask_and_fails_gracefully() { - let mut s = Session::new(); - assert!(s.execute("edit.copy", json!({"target": "mask"})).is_err(), "no document"); - s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); - assert!(s.execute("edit.copy", json!({"target": "mask"})).is_err(), "the layer has no mask"); - assert!(s.clipboard.is_none(), "a refused copy leaves the clipboard alone"); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - assert!(s.execute("edit.copy", json!({"target": "mask"})).is_ok()); - // An adjustment layer has no pixels of its own: Copy takes the layer whole (#2344), and - // its mask while that is targeted (#2928). - s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); - let a = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.select", json!({"layer": a})).unwrap(); - assert!(s.is_enabled("edit.copy"), "the layer itself can be copied"); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - assert!(s.is_enabled_with("edit.copy", &json!({"target": "mask"})), "the mask can be copied"); - } - - #[test] - fn a_copied_mask_travels_to_another_document() { - let (mut s, _, m) = mask_target_session(8); - s.edit("paint mask", |doc, _| { - doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); - Ok(()) - }) - .unwrap(); - s.execute("edit.copy", json!({"target": "mask"})).unwrap(); - s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); - let n = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": "mask"})).unwrap(); - assert!((mask_at(&s, n, 10, 10) - 0.75).abs() < 2.0 / 255.0, "the mask arrived in the second document"); - assert!(mask_at(&s, n, 30, 30) < 0.01, "it replaced the reveal-all mask there"); - } - - #[test] - fn paste_follows_the_mask_view_and_is_placed_like_a_paste() { - let (mut s, src, m) = mask_target_session(8); - let lum = luminosity(&s, src, 10, 10); - // ⌥-click the mask thumbnail: the canvas shows the mask, and pasting targets it. - s.execute(crate::mask_view_cmds::ID, json!({"layer": m.0, "mode": "gray"})).unwrap(); - let r = s.execute("edit.paste", json!({"center": [30, 30]})).unwrap(); - assert_eq!(r["offset"], json!([20, 20])); - assert!((mask_at(&s, m, 30, 30) - lum).abs() < 2.0 / 255.0); - assert_eq!(mask_at(&s, m, 10, 10), 0.0); - assert_eq!(s.active().unwrap().doc.layers.len(), 3, "Background, src, m"); - } - - #[test] - fn paste_into_and_outside_a_targeted_mask_keep_to_the_selection() { - let (mut s, src, m) = mask_target_session(16); - let lum = luminosity(&s, src, 10, 10); - // The paste is centred on the selection, so lands in place: only the selection takes it. - s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); - s.execute("edit.pasteSpecial.pasteInto", json!({"target": "mask"})).unwrap(); - assert!((mask_at(&s, m, 9, 9) - lum).abs() < 2.0 / 255.0); - assert_eq!(mask_at(&s, m, 7, 7), 0.0, "pasted, but outside the selection"); - assert!(s.active().unwrap().doc.selection.is_none()); - assert_eq!(s.active().unwrap().doc.layers.len(), 3, "no new layer"); - s.execute("layer.layerMask.hideAll", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); - s.execute("edit.pasteSpecial.pasteOutside", json!({"target": "mask"})).unwrap(); - assert_eq!(mask_at(&s, m, 9, 9), 0.0, "Paste Outside leaves the selection alone"); - assert!((mask_at(&s, m, 7, 7) - lum).abs() < 2.0 / 255.0); - } - - #[test] - fn paste_follows_a_targeted_alpha_channel() { - let (mut s, src, _) = mask_target_session(8); - let lum = luminosity(&s, src, 10, 10); - s.execute("channel.new", json!({})).unwrap(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": {"channel": 0}})).unwrap(); - let c = &s.active().unwrap().doc.channels[0].surface; - assert!((c.sample_channel(10, 10, 0) - lum).abs() < 2.0 / 255.0); - assert_eq!(s.active().unwrap().doc.layers.len(), 3, "no new layer"); - } - - #[test] - fn paste_into_a_missing_mask_or_channel_is_an_error() { - let (mut s, _, m) = mask_target_session(8); - s.edit("drop mask", |doc, _| { - doc.layer_mut(m).unwrap().mask = None; - Ok(()) - }) - .unwrap(); - let layers = s.active().unwrap().doc.layer_count(); - for target in [json!("mask"), json!({"channel": 7}), json!("quickMask")] { - for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace"] { - assert!(s.execute(id, json!({ "target": target })).is_err(), "{id} {target}"); - } - } - assert_eq!(s.active().unwrap().doc.layer_count(), layers, "nothing pasted as a layer"); - } - - #[test] - fn paste_between_different_color_modes() { - // Copy from an RGB document, paste into a Grayscale one: the clipboard converts to the - // target document's format (a realistic between-tabs case that must not panic). - let mut s = session(); // RGB, red rect - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("file.new", json!({"width": 120, "height": 120, "mode": "gray"})).unwrap(); - s.execute("edit.paste", json!({})).unwrap(); - let d = &s.active().unwrap().doc; - assert_eq!(d.mode, photocraft_doc::ColorMode::Grayscale); - let pasted = d.layers.last().unwrap().surface().unwrap(); - assert_eq!(pasted.format().mode, photocraft_color::ColorMode::Grayscale, "pasted layer is grayscale"); - assert!(!pasted.content_bounds().is_empty(), "pasted content exists"); - } - - #[test] - fn transform_scale_grows_content() { - let mut s = session(); // red rect (10,10)-(50,30): 40x20 - s.execute("edit.transform", json!({"matrix": [2, 0, 0, 2, 0, 0]})).unwrap(); - let d = &s.active().unwrap().doc; - let cb = d.layers.last().unwrap().surface().unwrap().content_bounds(); - // Scaled ~2x about the origin (≈ 80x40 at ≈ (20,20)); allow ~1px bilinear edge bleed. - assert!((cb.x0 - 20).abs() <= 2 && (cb.y0 - 20).abs() <= 2, "origin ~ (20,20): {cb:?}"); - assert!((cb.width() as i32 - 80).abs() <= 3 && (cb.height() as i32 - 40).abs() <= 3, "size ~ 80x40: {cb:?}"); - } - - #[test] - fn cut_and_clear_on_the_background_fill_with_the_background_colour() { - // The Background keeps its transparency lock: cutting fills with the background colour. - let fresh = || { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); - s.tools.background = [1.0, 0.0, 0.0, 1.0]; - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); - s - }; - let px = |s: &Session, i: usize, x: i32, y: i32| s.active().unwrap().doc.layers[i].surface().unwrap().pixel(x, y); - for cmd in ["edit.cut", "edit.clear", "layer.new.layerViaCut"] { - let mut s = fresh(); - s.execute(cmd, json!({})).unwrap(); - let d = &s.active().unwrap().doc; - assert!(d.is_background(d.layers[0].id), "{cmd}: still the Background"); - assert_eq!(px(&s, 0, 8, 8), vec![1.0, 0.0, 0.0, 1.0], "{cmd}: cut area is the background colour"); - assert_eq!(px(&s, 0, 30, 20), vec![1.0, 1.0, 1.0, 1.0], "{cmd}: outside untouched"); - } - // Layer via Cut still lifts the original pixels onto the new layer. - let mut s = fresh(); - s.execute("layer.new.layerViaCut", json!({})).unwrap(); - assert_eq!(px(&s, 1, 8, 8), vec![1.0, 1.0, 1.0, 1.0]); - // Once it's a normal layer, cutting makes transparency again. - let mut s = fresh(); - s.execute("layer.new.layerFromBackground", json!({})).unwrap(); - s.execute("edit.clear", json!({})).unwrap(); - assert_eq!(px(&s, 0, 8, 8)[3], 0.0); - } - - #[test] - fn layer_via_copy_of_a_background_keeps_colour_and_partial_selection() { - // #668: lift reads only the selected area now; the result must be what converting the - // whole layer gave: the colour, with the selection's coverage as alpha. - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth, "background": "#336699"})).unwrap(); - s.edit("partial selection", |doc, _| { - let mut m = photocraft_raster::Surface::new(PixelFormat::GRAY8); - m.fill_rect(Rect::new(5, 5, 15, 15), &[1.0]); - m.fill_rect(Rect::new(15, 5, 20, 15), &[0.5]); - doc.selection = Some(m); - Ok(()) - }) - .unwrap(); - let id = s.execute("layer.new.layerViaCopy", json!({})).unwrap()["layer"].as_u64().unwrap(); - let d = s.active().unwrap(); - let surf = d.doc.layer(LayerId(id)).unwrap().surface().unwrap(); - assert!(surf.format().alpha, "@{depth}"); - let full = surf.read_region(Rect::new(6, 6, 7, 7)); - let half = surf.read_region(Rect::new(16, 6, 17, 7)); - for (got, want) in full.iter().zip([0.2, 0.4, 0.6, 1.0]) { - assert!((got - want).abs() < 0.01, "@{depth}: {full:?}"); - } - assert!((half[3] - 0.5).abs() < 0.01 && (half[0] - 0.2).abs() < 0.01, "@{depth}: {half:?}"); - assert_eq!(surf.content_bounds(), Rect::new(5, 5, 20, 15), "@{depth}"); - } - } - - #[test] - fn cut_clears_and_layer_via_copy_cut() { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap(); - s.execute("edit.cut", json!({})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(20, 10, 50, 30)); - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap(); - s.execute("layer.new.layerViaCut", json!({})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 20, 30)); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(20, 10, 50, 30)); - // Without a selection ⌘J duplicates the layer. - let mut s = session(); - s.execute("layer.new.layerViaCopy", json!({})).unwrap(); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers.len(), 3); - assert!(d.layers[2].name.ends_with("copy")); - } - - /// #1096: Layer via Copy and Cut deselect, as Photoshop does, so a following Free Transform - /// moves the whole new layer; one undo brings back both the selection and the old layers. - #[test] - fn layer_via_copy_and_cut_deselect_in_one_step() { - for cmd in ["layer.new.layerViaCopy", "layer.new.layerViaCut"] { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap(); - let (layers, steps) = (s.active().unwrap().doc.layers.len(), s.active().unwrap().history.past_len()); - s.execute(cmd, json!({})).unwrap(); - let st = s.active().unwrap(); - assert!(st.doc.selection.is_none(), "{cmd}: deselected"); - assert_eq!((st.doc.layers.len(), st.history.past_len()), (layers + 1, steps + 1), "{cmd}"); - assert!(s.undo()); - let st = s.active().unwrap(); - assert_eq!(st.doc.layers.len(), layers, "{cmd}: undo removes the layer"); - assert!(st.doc.selection.is_some(), "{cmd}: and restores the selection"); - } - } - - /// #2777: with several layers selected and no pixel selection, Layer via Copy (Cmd+J) copies - /// every selected layer in one step, each copy above its original and the copies selected. - /// With a pixel selection it still copies the active layer's selected pixels only. - #[test] - fn layer_via_copy_duplicates_every_selected_layer() { - let mut s = session(); - let a = s.active().unwrap().active_layer.unwrap(); - let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); - let steps = s.active().unwrap().history.past_len(); - s.execute("layer.new.layerViaCopy", json!({})).unwrap(); - let st = s.active().unwrap(); - let ids: Vec = st.doc.layers.iter().map(|l| l.id).collect(); - assert_eq!(ids.len(), 5, "background, a, a copy, b, b copy"); - assert_eq!((ids[1], ids[3]), (a, b), "each copy sits above its original"); - let mut selected = st.selected_layers(); - selected.sort_by_key(|l| l.0); - assert_eq!(selected, vec![ids[2], ids[4]], "the copies become the selection"); - assert_eq!(st.history.past_len(), steps + 1, "one undo step"); - assert!(s.undo()); - s.execute("layer.select", json!({"layer": b.0})).unwrap(); - s.execute("layer.select", json!({"layer": a.0, "mode": "toggle"})).unwrap(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("layer.new.layerViaCopy", json!({})).unwrap(); - assert_eq!(s.active().unwrap().doc.layers.len(), 4, "a pixel selection copies one layer's pixels"); - } - - fn active_content(s: &Session) -> LayerContent { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().content.clone() - } - - /// #541, #2428: with no selection, Copy takes a smart object whole and Paste makes a smart - /// object again, with contents of its own; with a selection, the selected pixels paste as - /// pixels. Cut edits pixels, so it's refused; Layer via Copy and Duplicate Layer copy the layer. - #[test] - fn copy_a_smart_object_layer() { - let mut s = session(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let LayerContent::Smart(original) = active_content(&s) else { panic!("smart object") }; - assert!(s.is_enabled("edit.copy")); - assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([10, 10, 40, 20]), "no selection: the whole layer"); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - let LayerContent::Smart(pasted) = active_content(&s) else { panic!("the paste is a smart object (#2428)") }; - assert_eq!(pasted.source, original.source, "the same contents"); - assert_ne!(pasted.contents_id, original.contents_id, "but not linked to the copied one"); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 50, 30)); - s.execute("edit.paste", json!({"center": [70, 70]})).unwrap(); - assert!(matches!(active_content(&s), LayerContent::Smart(_))); - assert_eq!(active_bounds(&s), Rect::new(50, 60, 90, 80), "placed as pasted pixels are"); - s.undo(); - s.undo(); - assert!(matches!(active_content(&s), LayerContent::Smart(_))); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([10, 10, 10, 10]), "only the selected part"); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - assert!(matches!(active_content(&s), LayerContent::Raster(_)), "a selection copies pixels"); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 20, 20)); - s.undo(); - let cut = s.execute("edit.cut", json!({})).unwrap_err().to_string(); - assert!(cut.contains("not directly editable"), "{cut}"); - assert!(matches!(active_content(&s), LayerContent::Smart(_))); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("layer.new.layerViaCopy", json!({})).unwrap(); - assert!(matches!(active_content(&s), LayerContent::Smart(_)), "⌘J without a selection duplicates the smart object"); - s.execute("layer.duplicate", json!({})).unwrap(); - assert!(matches!(active_content(&s), LayerContent::Smart(_))); - assert_eq!(s.active().unwrap().doc.layers.len(), 4); - } - - /// #2478: with several layers selected and no pixel selection, Copy takes every one of them - /// and Paste recreates them all, in order, as one undo step; with a pixel selection Copy still - /// takes the active layer's selected pixels only. - #[test] - fn copy_and_paste_several_selected_layers() { - let mut s = session(); - let a = s.active().unwrap().active_layer.unwrap(); - let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.edit("paint", |doc, _| { - doc.layer_mut(b).unwrap().surface_mut().unwrap().fill_rect(Rect::new(60, 60, 80, 90), &[0.0, 0.0, 1.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); - assert!(s.is_enabled("edit.copy")); - assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([10, 10, 70, 80]), "both layers' pixels"); - let before = s.active().unwrap().doc.layers.len(); - let steps = s.active().unwrap().history.past_len(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(st.doc.layers.len(), before + 2, "every selected layer is pasted"); - assert_eq!(st.history.past_len(), steps + 1, "one undo step"); - let n = st.doc.layers.len(); - let (pa, pb) = (st.doc.layers[n - 2].surface().unwrap(), st.doc.layers[n - 1].surface().unwrap()); - assert_eq!(pa.content_bounds(), Rect::new(10, 10, 50, 30), "the lower layer first"); - assert_eq!(pb.content_bounds(), Rect::new(60, 60, 80, 90)); - assert!(s.undo()); - assert_eq!(s.active().unwrap().doc.layers.len(), before); - - // A pixel selection takes the active layer's selected pixels, as a single layer. - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - assert_eq!(s.active().unwrap().doc.layers.len(), before + 1); - } - - /// #2478, #3588: several layers copied in one document paste into another, in that document's - /// bit depth and with their own pixels, in order, as one undo step. - #[test] - fn paste_several_layers_into_another_document() { - for depth in [16, 32] { - let mut s = session(); - let a = s.active().unwrap().active_layer.unwrap(); - let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.edit("paint", |doc, _| { - doc.layer_mut(b).unwrap().surface_mut().unwrap().fill_rect(Rect::new(60, 60, 80, 90), &[0.0, 0.0, 1.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - - s.execute("file.new", json!({"width": 120, "height": 120, "depth": depth})).unwrap(); - assert_eq!(s.active_index().unwrap(), 1, "the new document is the active tab"); - let (before, steps) = (s.active().unwrap().doc.layers.len(), s.active().unwrap().history.past_len()); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(st.doc.layers.len(), before + 2, "{depth}-bit: both layers arrive"); - assert_eq!(st.history.past_len(), steps + 1, "{depth}-bit: one undo step"); - let n = st.doc.layers.len(); - let (pa, pb) = (st.doc.layers[n - 2].surface().unwrap(), st.doc.layers[n - 1].surface().unwrap()); - assert_eq!(pa.format().sample, st.doc.depth, "{depth}-bit: converted to the target depth"); - assert_eq!(pb.format().sample, st.doc.depth, "{depth}-bit: converted to the target depth"); - assert_eq!(pa.content_bounds(), Rect::new(10, 10, 50, 30), "{depth}-bit: the lower layer first"); - assert_eq!(pb.content_bounds(), Rect::new(60, 60, 80, 90)); - let (mut red, mut blue) = ([[0.0f32; 4]; 1], [[0.0f32; 4]; 1]); - pa.read_rgba_into(Rect::new(20, 20, 21, 21), &mut red); - pb.read_rgba_into(Rect::new(70, 70, 71, 71), &mut blue); - assert!(red[0][0] > 0.9 && red[0][1] < 0.1 && red[0][2] < 0.1, "{depth}-bit: red kept: {:?}", red[0]); - assert!(blue[0][2] > 0.9 && blue[0][0] < 0.1 && blue[0][1] < 0.1, "{depth}-bit: blue kept: {:?}", blue[0]); - assert!(s.undo()); - assert_eq!(s.active().unwrap().doc.layers.len(), before, "{depth}-bit: undo removes both"); - assert_eq!(s.documents().len(), 2, "the source document is untouched"); - } - } - - /// #2478: the Background in a multi-layer copy pastes as an ordinary, unlocked layer. - #[test] - fn copying_the_background_with_another_layer_pastes_an_ordinary_layer() { - let mut s = session(); - let a = s.active().unwrap().active_layer.unwrap(); - let bg = s.active().unwrap().doc.layers[0].id; - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": bg.0, "mode": "toggle"})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(st.doc.layers.len(), 4); - let pasted = &st.doc.layers[st.doc.layers.len() - 2]; - assert!(!st.doc.is_background(pasted.id)); - assert_eq!(pasted.locks, Default::default()); - assert!(st.doc.is_background(st.doc.layers[0].id), "the real Background is untouched"); - } - - /// #2428: a smart object copied in one document pastes into another as a smart object, in - /// that document's bit depth. - #[test] - fn paste_a_smart_object_into_another_document() { - let mut s = session(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("file.new", json!({"width": 60, "height": 40, "depth": 16})).unwrap(); - s.execute("edit.paste", json!({})).unwrap(); - let LayerContent::Smart(sm) = active_content(&s) else { panic!("the paste is a smart object") }; - assert_eq!(sm.cache.map(|c| c.format().sample), Some(s.active().unwrap().doc.depth), "converted to 16 bits"); - assert_eq!(active_bounds(&s), Rect::new(10, 10, 50, 30), "on the canvas: in place"); - } - - /// #3584: a PSD-embedded linked smart object (its bytes in the document's `lnk2` block, its - /// source a uuid) can still be opened after Copy + Paste into another document. - #[test] - fn paste_keeps_a_psd_embedded_smart_object_openable() { - use std::sync::Arc; - let mut s = session(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let outer = s.active().unwrap().active_layer.unwrap(); - s.edit("embedded linked source", |doc, _| { - let LayerContent::Smart(sm) = &mut doc.layer_mut(outer).ok_or(EngineError::NoDocument)?.content else { - return Err(EngineError::Other("not a smart object".into())); - }; - sm.source = photocraft_doc::SmartSource::Linked { path: "uuid-1".into() }; - let linked = photocraft_io::linked::LinkedFile { uuid: "uuid-1".into(), file_name: "in.png".into(), bytes: vec![1, 2, 3, 4] }; - doc.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", Arc::new(photocraft_io::linked::encode_linked_file(&linked)))); - Ok(()) - }) - .unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); - s.execute("edit.paste", json!({})).unwrap(); - let LayerContent::Smart(sm) = active_content(&s) else { panic!("the paste is a smart object") }; - assert!( - crate::smart_cmds::source_bytes(&s.active().unwrap().doc.metadata, &sm.source).is_some(), - "the pasted PSD-embedded linked source must resolve (#3584)" - ); - } - - /// Type and shape layers copy their rendered pixels too; groups and adjustments have none. - #[test] - fn copy_reads_any_layer_that_shows_pixels() { - let mut s = session(); - s.execute("type.create", json!({"text": "Hi", "size": 30, "x": 20, "y": 60})).unwrap(); - assert!(!s.is_enabled("edit.cut")); - assert!(s.execute("edit.copy", json!({})).is_ok()); - s.execute("layer.groupLayers", json!({})).unwrap(); - assert!(s.is_enabled("edit.copy"), "no selection: the group is copied whole (#2670)"); - s.execute("select.all", json!({})).unwrap(); - assert!(!s.is_enabled("edit.copy")); - } - - /// #2670: with no selection, Copy takes a type layer, a shape layer or a group whole and - /// Paste recreates it, into another document too (with fresh ids, in its bit depth); with a - /// selection, Copy takes pixels. - #[test] - fn copy_paste_keeps_type_shape_and_group_layers() { - let mut s = session(); - s.execute("type.create", json!({"text": "Hi", "size": 30, "x": 20, "y": 60})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - let LayerContent::Text(t) = active_content(&s) else { panic!("the paste is a type layer") }; - assert_eq!(t.text, "Hi"); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("edit.paste", json!({})).unwrap(); - assert!(matches!(active_content(&s), LayerContent::Raster(_)), "a selection copies pixels"); - s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); - s.execute("layer.groupLayers", json!({})).unwrap(); - let LayerContent::Group(src) = active_content(&s) else { panic!("a group") }; - s.execute("edit.copy", json!({})).unwrap(); - s.execute("file.new", json!({"width": 60, "height": 40, "depth": 16})).unwrap(); - s.execute("edit.paste", json!({})).unwrap(); - let LayerContent::Group(g) = active_content(&s) else { panic!("the paste is a group") }; - let [shape] = g.children.as_slice() else { panic!("one child") }; - assert!(matches!(shape.content, LayerContent::Shape(_)), "the shape stays a shape"); - assert_ne!(shape.id, src.children[0].id, "fresh ids"); - assert_eq!(shape.surface().map(|c| c.format().sample), Some(s.active().unwrap().doc.depth), "converted to 16 bits"); - } - - #[test] - fn cross_document_group_paste_renders_shapes_on_destination_canvas() { - for (copy_to_document, depth) in [(false, 8), (true, 16)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width":100,"height":100})).unwrap(); - let mut ids = Vec::new(); - for x in [10, 50] { - s.execute("shape.create", json!({"kind":"rect","rect":[x,20,20,30],"fill":"#ff0000"})).unwrap(); - s.execute("layer.layerStyle.dropShadow", json!({"size":4,"distance":3})).unwrap(); - ids.push(s.active().unwrap().active_layer.unwrap()); - } - s.active_mut().unwrap().selected_layers = ids; - s.execute("layer.groupLayers", json!({})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("file.new", json!({"width":800,"height":600,"depth":depth})).unwrap(); - if copy_to_document { - s.execute("layer.copyToDocument", json!({"source":0,"document":1,"center":true})).unwrap(); - } else { - s.execute("edit.paste", json!({"center":[400,300]})).unwrap(); - } - let st = s.active().unwrap(); - let group = st.doc.layer(st.active_layer.unwrap()).unwrap(); - assert!(!crate::transform_cmds::transform_bounds(&st.doc, group).is_empty()); - assert_eq!(group.children().unwrap().len(), 2); - for child in group.children().unwrap() { - let LayerContent::Shape(shape) = &child.content else { panic!("shape") }; - let cache = shape.cache.as_ref().unwrap(); - assert_eq!(cache.format().sample, st.doc.depth); - assert!(!cache.content_bounds().is_empty(), "destination cache must not be clipped to source canvas"); - assert!(cache.content_bounds().x0 > 100); - let fresh = photocraft_vector::render_shape(shape, st.doc.pixel_format(), st.doc.bounds()); - assert_eq!(cache, &fresh); - } - let before = st.doc.clone(); - s.execute("layer.translate", json!({"dx":10,"dy":10})).unwrap(); - assert_ne!(s.active().unwrap().doc, before); - assert!(s.undo()); - assert_eq!(s.active().unwrap().doc, before); - } - } - - #[test] - fn paste_repairs_uncached_shapes_before_transform_and_effect_rendering() { - let mut s = session(); - s.execute("shape.create", json!({"kind":"rect","rect":[10,10,40,20],"fill":"#ff0000"})).unwrap(); - s.execute("layer.layerStyle.dropShadow", json!({"size":4,"distance":3})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - let layers = s.clipboard.as_mut().unwrap().layers.as_mut().unwrap(); - let LayerContent::Shape(sh) = &mut layers.layers[0].content else { panic!("shape") }; - sh.cache = None; - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - let st = s.active().unwrap(); - let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); - let LayerContent::Shape(sh) = &layer.content else { panic!("shape") }; - assert!(sh.cache.is_some()); - assert!(!crate::transform_cmds::transform_bounds(&st.doc, layer).is_empty()); - let expected = photocraft_vector::render_shape(sh, st.doc.pixel_format(), st.doc.bounds()); - assert_eq!(sh.cache.as_ref().unwrap(), &expected); - let rendered = photocraft_compose::render_layer_in(&st.doc, layer, st.doc.bounds()); - let mut fresh_doc = (*st.doc).clone(); - let snapshot = fresh_doc.clone(); - if let LayerContent::Shape(shape) = &mut fresh_doc.layer_mut(layer.id).unwrap().content { - crate::vector_cmds::refresh_shape(&snapshot, shape); - } - let fresh = photocraft_compose::render_layer_in(&fresh_doc, fresh_doc.layer(layer.id).unwrap(), fresh_doc.bounds()); - assert_eq!(rendered.px, fresh.px, "pasted effects match a freshly rebuilt shape"); - assert!(s.undo()); - assert!(s.redo()); - let st = s.active().unwrap(); - assert!(st.doc.layer(st.active_layer.unwrap()).unwrap().surface().is_some()); - } - - /// #2344: fill and adjustment layers have no pixels of their own, so with no selection Copy - /// takes them whole and Paste recreates them, in the same or another document, in one step. - #[test] - fn copy_paste_keeps_fill_and_adjustment_layers() { - for (depth, other) in [(8, 16), (16, 32), (32, 8)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 60, "height": 40, "depth": depth})).unwrap(); - s.execute("layer.newFillLayer.gradient", json!({"from": "#000000", "to": "#ffffff", "angle": 0})).unwrap(); - let LayerContent::Fill(fill) = active_content(&s) else { panic!("a fill layer") }; - let src = s.active().unwrap().active_layer.unwrap(); - assert!(s.is_enabled("edit.copy"), "{depth}-bit: a fill layer can be copied"); - assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 60, 40]), "{depth}-bit: what it shows"); - let clip = s.clipboard.clone().unwrap(); - assert!(clip.surface.rgba(59, 20)[0] > clip.surface.rgba(0, 20)[0], "{depth}-bit: the clip holds the gradient's pixels"); - let steps = s.active().unwrap().history.past_len(); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{depth}-bit: one history step"); - assert_eq!(active_content(&s), LayerContent::Fill(fill.clone()), "{depth}-bit: the paste is the same fill layer"); - assert_ne!(s.active().unwrap().active_layer, Some(src), "{depth}-bit: a new layer"); - s.undo(); - assert_eq!(s.active().unwrap().active_layer, Some(src), "{depth}-bit: undo removes the paste"); - s.redo(); - assert!(matches!(active_content(&s), LayerContent::Fill(_)), "{depth}-bit: redo brings it back"); - - s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); - let LayerContent::Adjustment(levels) = active_content(&s) else { panic!("an adjustment layer") }; - assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 60, 40]), "{depth}-bit: it applies to the canvas"); - s.execute("file.new", json!({"width": 30, "height": 30, "depth": other})).unwrap(); - s.execute("edit.paste", json!({})).unwrap(); - assert_eq!(active_content(&s), LayerContent::Adjustment(levels), "{depth}-bit: the same Levels layer in the {other}-bit document"); - assert_eq!(s.active().unwrap().doc.layers.len(), 2, "{depth}-bit: pasted above the Background"); - } - } - - /// #2344: several adjustment layers, which show nothing alone, still copy and paste together. - #[test] - fn several_adjustment_layers_copy_together() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); - let a = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); - let b = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.select", json!({"layer": a})).unwrap(); - s.execute("layer.select", json!({"layer": b, "mode": "toggle"})).unwrap(); - assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 40, 40])); - s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers.len(), 5, "both are pasted"); - assert!(d.layers[3..].iter().all(|l| matches!(l.content, LayerContent::Adjustment(_)))); - } - - #[test] - fn merge_visible_keeps_hidden_layers() { - let mut s = session(); - s.execute("layer.new.layer", json!({})).unwrap(); - let hidden = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.setProps", json!({"layer": hidden.0, "visible": false})).unwrap(); - s.execute("layer.mergeVisible", json!({})).unwrap(); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers.len(), 2); - assert_eq!(d.layers[0].name, "Background"); - assert_eq!(d.layers[1].id, hidden); - assert_eq!(d.layers[0].surface().unwrap().pixel(20, 20)[..3], [1.0, 0.0, 0.0]); - } - - #[test] - fn auto_tone_stretches_a_low_contrast_layer() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - s.edit("grey ramp", |doc, _| { - let surf = doc.layers[0].surface_mut().unwrap(); - for x in 0..64 { - let v = 0.3 + 0.4 * x as f32 / 63.0; - surf.fill_rect(Rect::new(x, 0, x + 1, 64), &[v, v * 0.9, v * 0.8, 1.0]); - } - Ok(()) - }) - .unwrap(); - for cmd in ["image.autoTone", "image.autoContrast", "image.autoColor"] { - s.execute(cmd, json!({})).unwrap(); - let d = &s.active().unwrap().doc; - let (a, b) = (d.layers[0].surface().unwrap().pixel(0, 0), d.layers[0].surface().unwrap().pixel(63, 0)); - // Auto Contrast keeps colour (shared points): only the extreme channels reach 0 and 1. - let (lo, hi) = if cmd == "image.autoContrast" { (a[2], b[0]) } else { (a[0], b[0]) }; - assert!(lo < 0.05 && hi > 0.95, "{cmd}: {a:?} {b:?}"); - s.undo(); - } - } - - /// #352: ⌥⇧⌘T steps and repeats: each press adds a copy one transform further on, and each - /// is one undo step. - #[test] - fn transform_again_on_a_copy_steps_and_repeats() { - let mut s = session(); - assert!(s.execute("edit.transform.againCopy", json!({})).is_err(), "nothing to repeat yet"); - assert_eq!(s.active().unwrap().doc.layers.len(), 2, "a refusal leaves no copy"); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 0]})).unwrap(); - let steps = s.active().unwrap().history.past_len(); - for (i, x) in [30, 40].into_iter().enumerate() { - s.execute("edit.transform.againCopy", json!({})).unwrap(); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers.len(), 3 + i); - assert_eq!(active_bounds(&s), Rect::new(x, 10, x + 40, 30), "the copy moved one step further"); - assert_eq!(s.active().unwrap().history.past_len(), steps + 1 + i, "one history step per press"); - } - assert_eq!(s.active().unwrap().history.undo_label(), Some("Transform Again")); - // The original and the first copy stay where they were. - let d = &s.active().unwrap().doc; - let b = |i: usize| d.layers[i].surface().unwrap().content_bounds(); - assert_eq!((b(1), b(2)), (Rect::new(20, 10, 60, 30), Rect::new(30, 10, 70, 30))); - // Undo removes the copy and its move together. - s.undo(); - assert_eq!(s.active().unwrap().doc.layers.len(), 3); - assert_eq!(active_bounds(&s), Rect::new(30, 10, 70, 30)); - // A copy that can't move (position locked) is taken back. - let id = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.setProps", json!({"layer": id.0, "locks": {"position": true}})).unwrap(); - let layers = s.active().unwrap().doc.layers.len(); - assert!(s.execute("edit.transform.againCopy", json!({})).unwrap_err().to_string().contains("locked")); - assert_eq!(s.active().unwrap().doc.layers.len(), layers); - assert!(!s.active().unwrap().history.can_redo(), "nothing to redo"); - } - - #[test] - fn toggle_last_state_and_transform_again() { - let mut s = session(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 0]})).unwrap(); - s.execute("edit.transform.again", json!({})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(30, 10, 70, 30)); - s.execute("edit.toggleLastState", json!({})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(20, 10, 60, 30)); - s.execute("edit.toggleLastState", json!({})).unwrap(); - assert_eq!(active_bounds(&s), Rect::new(30, 10, 70, 30)); - } - - #[test] - fn guides_are_undoable() { - let mut s = session(); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 40})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "horizontal", "position": 12.5})).unwrap(); - s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 0, "position": 60})).unwrap(); - let g = &s.active().unwrap().doc.guides; - assert_eq!((g.vertical.clone(), g.horizontal.clone()), (vec![60.0], vec![12.5])); - s.execute("view.deleteGuide", json!({"orientation": "horizontal", "index": 0})).unwrap(); - s.undo(); - assert_eq!(s.active().unwrap().doc.guides.horizontal, vec![12.5]); - s.execute("view.clearGuides", json!({})).unwrap(); - assert!(s.active().unwrap().doc.guides.vertical.is_empty()); - assert!(s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 3, "position": 1})).is_err()); - } - - /// #2955: the rulers' zero point is set and reset by command, undoable, and bad params are - /// refused without touching the document. - #[test] - fn ruler_origin_is_set_reset_and_undoable() { - let mut s = session(); - assert_eq!(s.active().unwrap().doc.ruler_origin, [0.0, 0.0]); - assert_eq!(s.execute("view.setRulerOrigin", json!({"x": 40, "y": 12.5})).unwrap(), json!({"x": 40.0, "y": 12.5})); - assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]); - s.execute("view.resetRulerOrigin", json!({})).unwrap(); - assert_eq!(s.active().unwrap().doc.ruler_origin, [0.0, 0.0]); - s.undo(); - assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]); - for bad in [json!({}), json!({"x": 1}), json!({"x": "a", "y": 2}), json!({"x": 1e300, "y": 0}), json!({"x": -2e7, "y": 0}), json!(null), json!([1, 2])] - { - assert!(s.execute("view.setRulerOrigin", bad.clone()).is_err(), "{bad} is refused"); - } - assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]); - let mut empty = Session::new(); - assert!(empty.execute("view.setRulerOrigin", json!({"x": 1, "y": 2})).is_err()); - assert!(empty.execute("view.resetRulerOrigin", json!({})).is_err()); - } - - /// The last guide added in `orientation` for `position`. - fn new_guide(s: &mut Session, orientation: &str, position: Value) -> f64 { - s.execute("view.newGuide", json!({"orientation": orientation, "position": position})).unwrap(); - let g = &s.active().unwrap().doc.guides; - *if orientation == "vertical" { &g.vertical } else { &g.horizontal }.last().unwrap() - } - - #[test] - fn guide_positions_take_photoshop_units() { - let mut s = Session::new(); - // 4 × 2 inches at 100 ppi. - s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 100})).unwrap(); - // Percent follows the guide's own axis: the width for a vertical guide, the height for a horizontal one. - assert_eq!(new_guide(&mut s, "vertical", json!("50%")), 200.0); - assert_eq!(new_guide(&mut s, "horizontal", json!("50%")), 100.0); - for one_inch in ["1in", "1 in", "2.54cm", "25.4 mm", "72pt", "6pc", "100px", "100", "1,0 inch"] { - assert!((new_guide(&mut s, "vertical", json!(one_inch)) - 100.0).abs() < 1e-3, "{one_inch}"); - } - // Fractional and negative positions are kept; a plain number is pixels, as before. - assert_eq!(new_guide(&mut s, "horizontal", json!("12.5px")), 12.5); - assert_eq!(new_guide(&mut s, "vertical", json!("-10px")), -10.0); - assert_eq!(new_guide(&mut s, "vertical", json!(40)), 40.0); - // Points and picas follow Units & Rulers › Point Size. - s.execute("prefs.set", json!({"path": "unitsAndRulers.pointSize", "value": "traditional"})).unwrap(); - assert!((new_guide(&mut s, "vertical", json!("72.27pt")) - 100.0).abs() < 1e-3); - // A guide moved with a unit lands where a new one would. - s.execute("view.moveGuide", json!({"orientation": "horizontal", "index": 0, "position": "25%"})).unwrap(); - assert_eq!(s.active().unwrap().doc.guides.horizontal[0], 50.0); - } - - #[test] - fn new_guides_keep_their_own_colour_through_moves_deletes_and_undo() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); - let color = |s: &Session, vertical: bool, p: f64| s.active().unwrap().doc.guides.color(vertical, p); - // Without a colour a guide uses the preference colour, as ruler-drag guides always did. - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10})).unwrap(); - assert_eq!(color(&s, true, 10.0), None); - assert!(s.active().unwrap().doc.guides.colors.is_empty()); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 20, "color": "magenta"})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "horizontal", "position": 20, "color": "#123456"})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 30, "color": "LightBlue"})).unwrap(); - assert_eq!(color(&s, true, 20.0), Some([0xff, 0x00, 0xff])); - assert_eq!(color(&s, false, 20.0), Some([0x12, 0x34, 0x56]), "the same position across is a different guide"); - assert_eq!(color(&s, true, 30.0), Some([0x33, 0x66, 0xff]), "names are case-insensitive"); - // Moving takes the colour along. - s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 1, "position": 25})).unwrap(); - assert_eq!((color(&s, true, 20.0), color(&s, true, 25.0)), (None, Some([0xff, 0x00, 0xff]))); - // Undo restores it where it was. - s.undo(); - assert_eq!((color(&s, true, 20.0), color(&s, true, 25.0)), (Some([0xff, 0x00, 0xff]), None)); - // Deleting drops it; clearing drops them all. - s.execute("view.deleteGuide", json!({"orientation": "vertical", "index": 2})).unwrap(); - assert_eq!(color(&s, true, 30.0), None); - assert_eq!(s.active().unwrap().doc.guides.colors.len(), 2); - s.execute("view.clearGuides", json!({})).unwrap(); - assert!(s.active().unwrap().doc.guides.colors.is_empty()); - } - - #[test] - fn moving_one_of_two_coloured_guides_at_one_position_leaves_the_other_its_colour() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); - for _ in 0..2 { - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 50, "color": "green"})).unwrap(); - } - s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 0, "position": 60})).unwrap(); - let g = &s.active().unwrap().doc.guides; - assert_eq!((g.color(true, 50.0), g.color(true, 60.0)), (Some([0x33, 0xff, 0x33]), Some([0x33, 0xff, 0x33]))); - } - - #[test] - fn cyan_is_the_default_guide_colour_so_ruler_guides_read_as_cyan() { - let default = crate::prefs::Preferences::default().guides_grid_and_slices.guide_color; - let cyan = GUIDE_COLORS.iter().find(|(name, ..)| *name == "cyan").map(|(.., rgb)| *rgb); - assert_eq!(cyan, crate::prefs::parse_hex(&default)); - } - - #[test] - fn bad_guide_colours_are_refused_without_a_guide() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); - let undo_before = s.active().unwrap().history.can_undo(); - for bad in [json!("puce"), json!("#12345"), json!("#gggggg"), json!(""), json!(7), json!(null), json!(["cyan"])] { - assert!(s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10, "color": bad.clone()})).is_err(), "{bad}"); - } - let g = &s.active().unwrap().doc.guides; - assert!(g.vertical.is_empty() && g.colors.is_empty()); - assert_eq!(s.active().unwrap().history.can_undo(), undo_before); - } - - #[test] - fn editing_a_guide_changes_what_is_given_in_one_undoable_step() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 20, "color": "magenta"})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 30})).unwrap(); - let guides = |s: &Session| s.active().unwrap().doc.guides.clone(); - // Position only: the guide keeps its index and its own colour. - s.execute("view.editGuide", json!({"orientation": "vertical", "index": 1, "position": "50%"})).unwrap(); - let g = guides(&s); - assert_eq!(g.vertical, vec![10.0, 200.0, 30.0]); - assert_eq!((g.color(true, 20.0), g.color(true, 200.0)), (None, Some([0xff, 0x00, 0xff]))); - // Colour only: an uncoloured guide gets one; the position stays. - s.execute("view.editGuide", json!({"orientation": "vertical", "index": 0, "color": "#123456"})).unwrap(); - assert_eq!(guides(&s).color(true, 10.0), Some([0x12, 0x34, 0x56])); - // Turning it: % is of the new orientation's extent, and the colour goes along. - s.execute("view.editGuide", json!({"orientation": "vertical", "index": 1, "newOrientation": "horizontal", "position": "25%"})).unwrap(); - let g = guides(&s); - assert_eq!((g.vertical.clone(), g.horizontal.clone()), (vec![10.0, 30.0], vec![50.0])); - assert_eq!((g.color(true, 200.0), g.color(false, 50.0)), (None, Some([0xff, 0x00, 0xff]))); - // One step each: undo restores the vertical guide with its colour. - s.undo(); - let g = guides(&s); - assert_eq!((g.vertical.clone(), g.horizontal.is_empty()), (vec![10.0, 200.0, 30.0], true)); - assert_eq!(g.color(true, 200.0), Some([0xff, 0x00, 0xff])); - } - - #[test] - fn bad_guide_edits_are_refused_without_a_history_step() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10, "color": "green"})).unwrap(); - let before = s.active().unwrap().doc.guides.clone(); - for bad in [ - json!({}), - json!({"orientation": "vertical"}), - json!({"orientation": "vertical", "index": 1}), - json!({"orientation": "horizontal", "index": 0}), - json!({"orientation": "vertical", "index": -1}), - json!({"orientation": "vertical", "index": "0"}), - json!({"orientation": "vertical", "index": u64::MAX}), - json!({"orientation": "diagonal", "index": 0}), - json!({"orientation": "vertical", "index": 0, "newOrientation": 3}), - json!({"orientation": "vertical", "index": 0, "position": "far"}), - json!({"orientation": "vertical", "index": 0, "position": 1e12}), - json!({"orientation": "vertical", "index": 0, "color": "puce"}), - ] { - assert!(s.execute("view.editGuide", bad.clone()).is_err(), "{bad}"); - } - assert_eq!(s.active().unwrap().doc.guides, before); - assert_eq!(s.active().unwrap().history.undo_label(), Some("New Guide")); - } - - #[test] - fn bad_guide_positions_are_refused_without_a_guide() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 100})).unwrap(); - let undo_before = s.active().unwrap().history.can_undo(); - for bad in [ - json!("abc"), - json!("50 furlongs"), - json!(""), - json!("%"), - json!("NaN"), - json!("inf"), - json!("1e400"), - json!("2000000px"), - json!(1e300), - json!(true), - json!([1]), - ] { - assert!(s.execute("view.newGuide", json!({"orientation": "vertical", "position": bad.clone()})).is_err(), "{bad}"); - } - assert!(s.execute("view.newGuide", json!({"orientation": "vertical"})).is_err(), "no position"); - let g = &s.active().unwrap().doc.guides; - assert!(g.vertical.is_empty() && g.horizontal.is_empty()); - assert_eq!(s.active().unwrap().history.can_undo(), undo_before, "a refused guide records no history step"); - } - - /// Guides keep their exact place (#2918): 1 cm at 300 ppi through New Guide and .pcraft, and - /// a 1/32 px PSD position past 2^19 px, where f32 has no 1/32 steps left. - #[test] - fn guides_keep_sub_pixel_positions_through_pcraft_and_psd() { - let (cm, far) = (300.0 / 2.54, 600_000.031_25); - let mut s = session(); - s.execute("view.newGuide", json!({"orientation": "horizontal", "position": cm})).unwrap(); - s.execute("view.newGuide", json!({"orientation": "vertical", "position": far})).unwrap(); - fn wide(v: impl Into) -> f64 { - v.into() - } - let exact = |g: &photocraft_doc::Guides| (wide(g.horizontal[0]), wide(g.vertical[0])); - let doc = &s.active().unwrap().doc; - assert_eq!(exact(&doc.guides), (cm, far)); - let pcraft = photocraft_format::save_to_bytes(doc, &Default::default()).unwrap(); - assert_eq!(exact(&photocraft_format::load_from_bytes(&pcraft).unwrap().guides), (cm, far)); - let psd = photocraft_io::export(doc, "psd", &Default::default()).unwrap().bytes; - let back = photocraft_io::import("g.psd", &psd).unwrap().document.guides; - assert_eq!(wide(back.vertical[0]), far, "1032 stores 1/32 px"); - } - - /// `lift` as it was before #4516: the whole area through one `f32` buffer. The oracle for - /// the tiled version. - fn lift_reference(src: &Surface, sel: Option<&Surface>, canvas: Rect) -> Clip { - let fmt = src.format(); - let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true); - let area = match sel { - Some(m) => m.content_bounds().intersect(&canvas), - None => src.content_bounds().intersect(&canvas), - }; - let mut out = Surface::new(with_alpha); - if area.is_empty() { - return Clip { surface: out, bounds: Rect::EMPTY, layers: None, resolution: None, source: None }; - } - let px = lift_region(src, sel, area, with_alpha.channels()).unwrap(); - out.try_write_region(area, &px).unwrap(); - out.prune(); - let bounds = out.content_bounds(); - Clip { surface: out, bounds, layers: None, resolution: None, source: None } - } - - fn noise(fmt: PixelFormat, r: Rect, seed: u32) -> Surface { - let mut s = Surface::new(fmt); - let n = r.width() as usize * r.height() as usize * fmt.channels(); - let data: Vec = (0..n as u32) - .map(|i| { - let mut h = seed.wrapping_mul(0x9e37_79b9) ^ i.wrapping_mul(0x85eb_ca6b); - h ^= h >> 13; - h = h.wrapping_mul(0xc2b2_ae35); - (h >> 16) as f32 / 65535.0 - }) - .collect(); - s.write_region(r, &data); - s - } - - fn assert_same_clip(a: &Clip, b: &Clip, what: &str) { - assert_eq!(a.bounds, b.bounds, "{what}: bounds"); - assert_eq!(a.surface.format(), b.surface.format(), "{what}: format"); - let r = a.bounds.union(&b.bounds); - if !r.is_empty() { - let (pa, pb) = (a.surface.read_region(r), b.surface.read_region(r)); - assert!(pa.iter().zip(&pb).all(|(x, y)| x.to_bits() == y.to_bits()), "{what}: pixels differ"); - } - } - - /// The tiled `lift` gives exactly the old result (#4516): with and without alpha, at every - /// depth, with no selection, Select All, a partial feathered selection and a selection off - /// the tile grid, and for content reaching past the canvas. - #[test] - fn tiled_lift_matches_the_whole_area_lift() { - use photocraft_color::{ColorMode, SampleType}; - let canvas = Rect::new(0, 0, 700, 600); - for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { - for alpha in [true, false] { - let fmt = PixelFormat::new(ColorMode::Rgb, sample, alpha); - let src = noise(fmt, Rect::new(-40, -30, 760, 640), 7); - let mut all = Surface::new(PixelFormat::GRAY8); - all.fill_rect(canvas, &[1.0]); - let mut partial = Surface::new(PixelFormat::GRAY8); - partial.fill_rect(Rect::new(100, 50, 600, 550), &[1.0]); - partial.write_region(Rect::new(90, 40, 610, 50), &vec![0.5; 520 * 10]); - let off_grid = noise(PixelFormat::GRAY8, Rect::new(13, 270, 333, 290), 9); - for (name, sel) in [("no selection", None), ("select all", Some(&all)), ("partial", Some(&partial)), ("off grid", Some(&off_grid))] { - let what = format!("{sample:?} alpha {alpha} {name}"); - let new = lift(&src, sel, canvas).unwrap(); - assert_same_clip(&new, &lift_reference(&src, sel, canvas), &what); - } - } - } - } - - /// Copy shares the layer's whole tiles instead of copying them. - #[test] - fn copy_shares_whole_tiles_with_the_layer() { - let src = noise(PixelFormat::RGBA8, Rect::new(0, 0, 1024, 768), 3); - let canvas = Rect::new(0, 0, 1024, 768); - let mut all = Surface::new(PixelFormat::GRAY8); - all.fill_rect(canvas, &[1.0]); - for sel in [None, Some(&all)] { - let clip = lift(&src, sel, canvas).unwrap(); - let shared = src.tiles().filter(|(c, t)| clip.surface.tile(**c).is_some_and(|o| std::sync::Arc::ptr_eq(o, t))).count(); - assert_eq!(shared, src.tile_count(), "every tile is shared"); - } - } -} +mod tests; diff --git a/crates/engine/src/edit_cmds/tests.rs b/crates/engine/src/edit_cmds/tests.rs new file mode 100644 index 0000000000..38877661f9 --- /dev/null +++ b/crates/engine/src/edit_cmds/tests.rs @@ -0,0 +1,1466 @@ +use super::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 50, 30), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +#[test] +fn new_clipboard_document_rejects_an_unrepresentable_origin() { + let mut s = Session::new(); + let mut surface = Surface::new(PixelFormat::RGBA8); + surface.write_pixel(i32::MIN, 0, &[1.0, 0.0, 0.0, 1.0]); + s.clipboard = Some(Clip { surface, bounds: Rect::from_xywh(i32::MIN, 0, 1, 1), layers: None, resolution: None, source: None }); + let result = new_from_clipboard(&mut s); + assert!(result.unwrap_err().to_string().contains("clipboard origin")); + assert!(s.execute("file.newFromClipboard", json!({})).is_err()); + assert!(s.documents().is_empty()); + assert_eq!(s.clipboard.as_ref().unwrap().surface.rgba(i32::MIN, 0), [1.0, 0.0, 0.0, 1.0]); +} + +/// #8945: pixels copied in one document land in place when pasted back into it, and centred +/// in another, even where their old position would fit (Photoshop's Paste). +#[test] +fn paste_centres_pixels_from_another_document() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + let r = s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(r["offset"], json!([0, 0]), "back into its own document: in place"); + s.execute("file.new", json!({"width": 100, "height": 80, "background": "white"})).unwrap(); + let r = s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(r["offset"], json!([30, 25]), "into another document: centred"); + // An image from another app has no source document: centred too. + s.clipboard = s.clipboard.take().map(|c| Clip { source: None, ..c }); + let r = s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(r["offset"], json!([30, 25])); + // Paste in Place still keeps the position. + let r = s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + assert_eq!(r["offset"], json!([0, 0])); +} + +#[test] +fn paste_centers_clipboard_bounds_near_coordinate_limits() { + for origin in [i32::MAX - 512, i32::MIN + 512] { + let clip = + Clip { surface: Surface::new(PixelFormat::RGBA8), bounds: Rect::from_xywh(origin, origin, 2, 2), layers: None, resolution: None, source: None }; + let (dx, dy) = paste_offset(&clip, DocId(1), Rect::new(0, 0, 20, 20), &json!({}), false); + assert_eq!(i64::from(origin) + i64::from(dx), 9); + assert_eq!(i64::from(origin) + i64::from(dy), 9); + let clip = Clip { bounds: Rect::new(0, 0, 2, 2), ..clip }; + let (dx, dy) = paste_offset(&clip, DocId(1), Rect::from_xywh(origin, origin, 20, 20), &json!({}), false); + assert_eq!(dx, origin + 9); + assert_eq!(dy, origin + 9); + } +} + +#[test] +fn injected_clear_buffer_failure_leaves_the_document_unchanged() { + let mut s = session(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); + let revision = st.revision; + + crate::allocation::fail_next_for_test(); + let result = s.execute("edit.clear", json!({})); + + assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for erasing pixels"))); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); + assert_eq!(st.revision, revision); +} + +#[test] +fn injected_copy_buffer_failure_does_not_change_document_or_clipboard() { + let mut s = session(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); + let revision = st.revision; + + crate::allocation::fail_next_for_test(); + let result = s.execute("edit.copy", json!({})); + + assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for copying pixels"))); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); + assert_eq!(st.revision, revision); + assert!(s.clipboard.is_none()); +} + +#[test] +fn injected_fill_result_reservation_failure_keeps_pixels_and_history() { + let mut s = session(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); + let revision = st.revision; + let history_len = st.history.past_len(); + + crate::allocation::fail_next_for_test(); + let result = s.execute("edit.fill", json!({"color": "#00ff00"})); + + assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for blending pixels"))); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); + assert_eq!(st.revision, revision); + assert_eq!(st.history.past_len(), history_len); +} + +#[test] +fn injected_paste_failure_does_not_change_document_or_clipboard() { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 8, "height": 8})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + let before_clip = s.clipboard.clone(); + let st = s.active().unwrap(); + let before_doc = (*st.doc).clone(); + let revision = st.revision; + let history_len = st.history.past_len(); + + crate::allocation::fail_next_for_test(); + let result = s.execute("edit.paste", json!({})); + + assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for pasting pixels"))); + let st = s.active().unwrap(); + assert_eq!(*st.doc, before_doc); + assert_eq!(st.revision, revision); + assert_eq!(st.history.past_len(), history_len); + let after_clip = s.clipboard.as_ref().expect("clipboard remains available"); + let before_clip = before_clip.as_ref().expect("clipboard was populated"); + assert_eq!(after_clip.bounds, before_clip.bounds); + assert_eq!(after_clip.surface, before_clip.surface); +} + +#[test] +fn injected_transform_failure_keeps_pixels_and_history() { + let mut s = session(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let before = st.doc.layer(id).unwrap().surface().unwrap().clone(); + let revision = st.revision; + let history_len = st.history.past_len(); + + crate::allocation::fail_next_for_test(); + let result = s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 20, 30]})); + + assert!(result.as_ref().is_err_and(|e| e.to_string().contains("not enough memory for transforming pixels"))); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(id).unwrap().surface(), Some(&before)); + assert_eq!(st.revision, revision); + assert_eq!(st.history.past_len(), history_len); +} + +fn active_bounds(s: &Session) -> Rect { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds() +} + +/// New from Clipboard takes the copied document's resolution (Photoshop's Clipboard preset), +/// so a later Image Size by resolution scales from the right size. +#[test] +fn new_from_clipboard_keeps_the_source_resolution() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 60, "height": 40, "resolution": 300})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("file.newFromClipboard", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.resolution_dpi, 300.0); +} + +/// #368: the clipboard as a document of its own, from New from Clipboard or a Paste with +/// nothing open, at every depth. +#[test] +fn new_from_clipboard_and_paste_with_no_document() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + assert!(!s.is_enabled("file.newFromClipboard") && !s.is_enabled("edit.paste"), "nothing copied yet"); + assert!(s.execute("file.newFromClipboard", json!({})).is_err()); + s.execute("file.new", json!({"width": 100, "height": 100, "depth": depth})).unwrap(); + assert!(!s.active().unwrap().is_dirty(), "an untouched blank document is clean"); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 20, "width": 30, "height": 15})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + // With a document open: a second document, sized to the copy, its pixels at the origin. + let r = s.execute("file.newFromClipboard", json!({})).unwrap(); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(30), Some(15)), "{r}"); + assert_eq!(s.documents().len(), 2); + assert!(s.active().unwrap().is_dirty(), "a document made from clipboard pixels needs saving (#4665)"); + let d = &s.active().unwrap().doc; + assert_eq!((d.size.width, d.size.height, d.layers.len()), (30, 15, 1)); + assert_eq!(d.pixel_format().sample, s.documents()[0].doc.pixel_format().sample, "{depth}-bit kept"); + assert_eq!(active_bounds(&s), Rect::new(0, 0, 30, 15)); + let px = d.layers[0].surface().unwrap().rgba(0, 0); + assert!(px[0] > 0.99 && px[1] < 0.01 && px[3] > 0.99, "{px:?}"); + // With nothing open, Paste makes the document too. + while s.active().is_some() { + s.execute("file.close", json!({})).unwrap(); + } + assert!(s.is_enabled("edit.paste") && !s.is_enabled("edit.pasteSpecial.pasteInPlace")); + s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(s.documents().len(), 1); + assert!(s.active().unwrap().is_dirty(), "Paste with no tab also needs a save prompt"); + assert_eq!(active_bounds(&s), Rect::new(0, 0, 30, 15)); + assert!(s.execute("edit.pasteSpecial.pasteInPlace", json!({})).is_ok(), "into the new document"); + } +} + +#[test] +fn copy_paste_in_place_and_centred() { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 30)); + assert!(s.active().unwrap().doc.selection.is_none()); + s.execute("edit.paste", json!({"center": [70, 70]})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(60, 60, 80, 80)); + assert_eq!(s.active().unwrap().doc.layers.len(), 4); +} + +/// A `w`×`h` document with an opaque `cw`×`ch` image from another app on the clipboard. +fn external_clip_session(w: i32, h: i32, cw: i32, ch: i32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": w, "height": h})).unwrap(); + let mut surface = Surface::new(PixelFormat::RGBA8); + surface.fill_rect(Rect::new(0, 0, cw, ch), &[1.0, 0.0, 0.0, 1.0]); + s.clipboard = Some(Clip { surface, bounds: Rect::new(0, 0, cw, ch), layers: None, resolution: None, source: None }); + s +} + +/// #6759: wherever the view is centred, a paste that fits the canvas stays wholly on it. +#[test] +fn paste_that_fits_stays_on_the_canvas() { + for (w, h, center, want) in [ + (60, 100, [40.0, 45.0], Rect::new(0, 0, 60, 100)), + (60, 100, [-500.0, 900.0], Rect::new(0, 0, 60, 100)), + (100, 100, [10.0, 80.0], Rect::new(0, 0, 60, 100)), + (100, 100, [95.0, 50.0], Rect::new(40, 0, 100, 100)), + (100, 120, [50.0, 60.0], Rect::new(20, 10, 80, 110)), + ] { + let mut s = external_clip_session(w, h, 60, 100); + s.execute("edit.paste", json!({ "center": center })).unwrap(); + assert_eq!(active_bounds(&s), want, "{w}x{h} canvas, view centre {center:?}"); + } +} + +/// #6759: a paste larger than the canvas starts at its top-left corner, wherever the view is. +#[test] +fn paste_larger_than_the_canvas_starts_at_its_top_left() { + for center in [[0.0, 0.0], [25.0, 20.0], [1000.0, 1000.0], [-1000.0, 30.0]] { + let mut s = external_clip_session(50, 40, 60, 100); + s.execute("edit.paste", json!({ "center": center })).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(0, 0, 60, 100), "view centre {center:?}"); + } + // Wider but not taller: at the left edge, and wholly inside vertically. + for (center, want) in + [([500.0, 500.0], Rect::new(0, 100, 60, 200)), ([-500.0, -500.0], Rect::new(0, 0, 60, 100)), ([25.0, 120.0], Rect::new(0, 70, 60, 170))] + { + let mut s = external_clip_session(50, 200, 60, 100); + s.execute("edit.paste", json!({ "center": center })).unwrap(); + assert_eq!(active_bounds(&s), want, "view centre {center:?}"); + } +} + +/// Paste Into centres on the selection even where that runs off the canvas. +#[test] +fn paste_into_is_not_clamped_to_the_canvas() { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 90, "y": 90, "width": 10, "height": 10})).unwrap(); + s.execute("edit.pasteSpecial.pasteInto", json!({})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(75, 85, 115, 105)); +} + +/// The clamp never overflows or panics: NaN, infinite and `i32`-limit shifts saturate (Rule 9). +#[test] +fn paste_offset_clamp_survives_extreme_coordinates() { + assert_eq!(clamp_shift(f64::NAN, 0, 10, 0, 100), 0); + assert_eq!(clamp_shift(f64::INFINITY, 0, 10, 0, 100), 90); + assert_eq!(clamp_shift(f64::NEG_INFINITY, i32::MIN, i32::MAX, 0, 1), i32::MAX); + assert_eq!(clamp_shift(1e30, i32::MIN, i32::MIN + 1, i32::MAX - 1, i32::MAX), i32::MAX); + let clip = Clip { + surface: Surface::new(PixelFormat::RGBA8), + bounds: Rect::new(i32::MAX - 2, i32::MAX - 2, i32::MAX, i32::MAX), + layers: None, + resolution: None, + source: None, + }; + let (dx, dy) = paste_offset(&clip, DocId(1), Rect::new(i32::MIN, i32::MIN, i32::MIN + 4, i32::MIN + 4), &json!({}), false); + assert_eq!((dx, dy), (i32::MIN, i32::MIN), "an unrepresentable shift saturates instead of wrapping"); +} + +#[test] +fn paste_with_malformed_center_does_not_panic() { + // A short/empty `center` array must not panic (Rule 9) — it falls back to the canvas centre. + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + for center in [json!([5]), json!([]), json!("nope"), json!([1, 2, 3])] { + // Fresh clipboard each time is unnecessary; copy persists. Must return Ok, never panic. + assert!(s.execute("edit.paste", json!({ "center": center })).is_ok(), "center={center}"); + } +} + +#[test] +fn copy_paste_between_documents() { + // Copy in one tab, paste into another: the clipboard is shared across documents. + let mut s = session(); // doc A (100x100): red rect at (10,10)-(50,30) + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + // Open a second document (a new tab), which becomes active. + s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + assert_eq!(s.active_index().unwrap(), 1, "the new document is the active tab"); + let before = s.active().unwrap().doc.layers.len(); + s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(s.active_index().unwrap(), 1, "paste stays in the second tab"); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), before + 1, "pasted layer added to the second document"); + let pasted = d.layers.last().unwrap().surface().unwrap(); + let cb = pasted.content_bounds(); + let (cx, cy) = (cb.x0 + cb.width() as i32 / 2, cb.y0 + cb.height() as i32 / 2); + let mut px = [[0.0f32; 4]; 1]; + pasted.read_rgba_into(Rect::new(cx, cy, cx + 1, cy + 1), &mut px); + assert!(px[0][0] > 0.9 && px[0][1] < 0.1 && px[0][2] < 0.1, "pasted content is red: {:?}", px[0]); +} + +/// #2901 (P10/P11): Paste, Paste in Place and Paste Into recomposite only where the pasted +/// layer draws, not the whole document; nothing outside that changes, and undo brings back +/// exactly the old pixels. +#[test] +fn paste_damages_only_the_pasted_layer() { + let render = |s: &Session| photocraft_compose::render(&s.active().unwrap().doc, s.active().unwrap().doc.bounds()); + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 60, "height": 50, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 8})).unwrap(); + s.execute("edit.fill", json!({"color": "#3366cc"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + // Half transparent, so an opaque copy pasted in place over it shows. + s.execute("layer.setProps", json!({"opacity": 0.5})).unwrap(); + for (id, p) in [ + ("edit.paste", json!({"center": [40, 30]})), + ("edit.pasteSpecial.pasteInPlace", json!({})), + ("edit.pasteSpecial.pasteInto", json!({"center": [40, 30]})), + ] { + s.execute("select.rect", json!({"x": 36, "y": 27, "width": 6, "height": 4})).unwrap(); + let shown = render(&s); + s.execute(id, p).unwrap(); + let st = s.active().unwrap(); + let area = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); + let damage = st.last_damage.unwrap_or_else(|| panic!("{depth}-bit {id}: bounded damage")); + assert!(!damage.is_empty() && damage.intersect(&area) == damage, "{depth}-bit {id}: {damage:?} within {area:?}"); + let now = render(&s); + assert_ne!(now, shown, "{depth}-bit {id}: the paste shows"); + let w = shown.rect.width() as usize; + for (i, (a, b)) in shown.px.iter().zip(&now.px).enumerate() { + if !damage.contains((i % w) as i32, (i / w) as i32) { + assert_eq!(a, b, "{depth}-bit {id}: pixel {i} outside the damage changed"); + } + } + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(render(&s), shown, "{depth}-bit {id}: undo"); + } + } +} + +/// #1035: a `depth`-bit document with a blue-grey square copied from layer `src` (at +/// (5,5)-(15,15)) and an active layer `m` above it with a hide-all mask. +fn mask_target_session(depth: u32) -> (Session, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth})).unwrap(); + let src = LayerId(s.execute("layer.new.layer", json!({"name": "src"})).unwrap()["layer"].as_u64().unwrap()); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + s.execute("edit.fill", json!({"color": "#3366cc"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let m = LayerId(s.execute("layer.new.layer", json!({"name": "m"})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.layerMask.hideAll", json!({})).unwrap(); + (s, src, m) +} + +/// The luminosity of `src`'s pixel at (`x`, `y`): what a paste into a mask writes there. +fn luminosity(s: &Session, src: LayerId, x: i32, y: i32) -> f32 { + let p = s.active().unwrap().doc.layer(src).unwrap().surface().unwrap().rgba(x, y); + photocraft_color::convert::rgb_to_gray([p[0], p[1], p[2]]) +} + +fn mask_at(s: &Session, id: LayerId, x: i32, y: i32) -> f32 { + s.active().unwrap().doc.layer(id).unwrap().mask.as_ref().unwrap().value(x, y) +} + +#[test] +fn paste_into_a_targeted_mask_writes_the_luminosity_in_one_step() { + for depth in [8, 16, 32] { + let (mut s, src, m) = mask_target_session(depth); + let lum = luminosity(&s, src, 10, 10); + assert!(lum > 0.05 && lum < 0.95, "{depth}-bit: a mid grey ({lum})"); + let (layers, steps) = (s.active().unwrap().doc.layer_count(), s.active().unwrap().history.past_len()); + s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": "mask"})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer_count(), layers, "{depth}-bit: no new layer"); + assert_eq!(st.history.past_len(), steps + 1, "{depth}-bit: one history step"); + assert_eq!(st.active_layer, Some(m)); + assert!((mask_at(&s, m, 10, 10) - lum).abs() < 2.0 / 255.0, "{depth}-bit: {} vs {lum}", mask_at(&s, m, 10, 10)); + assert_eq!(mask_at(&s, m, 20, 20), 0.0, "{depth}-bit: the mask outside the paste is unchanged"); + assert!(st.doc.layer(m).unwrap().surface().unwrap().content_bounds().is_empty(), "{depth}-bit: the pixels are untouched"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(mask_at(&s, m, 10, 10), 0.0, "{depth}-bit: undo restores the mask"); + } +} + +#[test] +fn copy_with_the_mask_targeted_takes_the_mask_as_grayscale() { + for depth in [8, 16, 32] { + let (mut s, _, m) = mask_target_session(depth); + s.edit("paint mask", |doc, _| { + doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); + Ok(()) + }) + .unwrap(); + let steps = s.active().unwrap().history.past_len(); + let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); + assert_eq!(r["bounds"], json!([0, 0, 40, 40]), "{depth}-bit: a mask copies whole, as in Photoshop"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "{depth}-bit: copy adds no history step"); + let clip = s.clipboard.clone().unwrap(); + let px = clip.surface.rgba(10, 10); + assert!((px[0] - 0.75).abs() < 2.0 / 255.0, "{depth}-bit: {} vs 0.75", px[0]); + assert!(clip.surface.rgba(30, 30)[0] < 0.01, "{depth}-bit: the hidden area copies as black"); + assert!(px[3] > 0.99, "{depth}-bit: the copy is opaque"); + // Paste it into another layer's reveal-all mask: it replaces that mask (the request + // in #2928): the square, and the black around it, land. + let m2 = LayerId(s.execute("layer.new.layer", json!({"name": "m2"})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": "mask"})).unwrap(); + assert!((mask_at(&s, m2, 10, 10) - 0.75).abs() < 2.0 / 255.0, "{depth}-bit: the copied mask lands"); + assert!(mask_at(&s, m2, 30, 30) < 0.01, "{depth}-bit: the copied black replaces the reveal-all"); + } +} + +#[test] +fn an_untouched_mask_copies_the_whole_canvas_at_its_default() { + let (mut s, _, _) = mask_target_session(8); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); + assert_eq!(r["bounds"], json!([0, 0, 40, 40]), "a plain Reveal All mask still transfers"); + assert!(s.clipboard.clone().unwrap().surface.rgba(20, 20)[0] > 0.99); +} + +#[test] +fn mask_copy_takes_only_the_selection() { + let (mut s, _, m) = mask_target_session(8); + s.edit("paint mask", |doc, _| { + doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); + Ok(()) + }) + .unwrap(); + s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); + let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); + assert_eq!(r["bounds"], json!([8, 8, 4, 4])); + let clip = s.clipboard.clone().unwrap(); + assert!((clip.surface.rgba(9, 9)[0] - 0.75).abs() < 2.0 / 255.0); + assert!(clip.surface.rgba(5, 5)[3] < 0.01, "nothing outside the selection"); +} + +#[test] +fn mask_copy_needs_a_mask_and_fails_gracefully() { + let mut s = Session::new(); + assert!(s.execute("edit.copy", json!({"target": "mask"})).is_err(), "no document"); + s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); + assert!(s.execute("edit.copy", json!({"target": "mask"})).is_err(), "the layer has no mask"); + assert!(s.clipboard.is_none(), "a refused copy leaves the clipboard alone"); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + assert!(s.execute("edit.copy", json!({"target": "mask"})).is_ok()); + // An adjustment layer has no pixels of its own: Copy takes the layer whole (#2344), and + // its mask while that is targeted (#2928). + s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); + let a = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.select", json!({"layer": a})).unwrap(); + assert!(s.is_enabled("edit.copy"), "the layer itself can be copied"); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + assert!(s.is_enabled_with("edit.copy", &json!({"target": "mask"})), "the mask can be copied"); +} + +#[test] +fn a_copied_mask_travels_to_another_document() { + let (mut s, _, m) = mask_target_session(8); + s.edit("paint mask", |doc, _| { + doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); + Ok(()) + }) + .unwrap(); + s.execute("edit.copy", json!({"target": "mask"})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); + let n = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": "mask"})).unwrap(); + assert!((mask_at(&s, n, 10, 10) - 0.75).abs() < 2.0 / 255.0, "the mask arrived in the second document"); + assert!(mask_at(&s, n, 30, 30) < 0.01, "it replaced the reveal-all mask there"); +} + +#[test] +fn paste_follows_the_mask_view_and_is_placed_like_a_paste() { + let (mut s, src, m) = mask_target_session(8); + let lum = luminosity(&s, src, 10, 10); + // ⌥-click the mask thumbnail: the canvas shows the mask, and pasting targets it. + s.execute(crate::mask_view_cmds::ID, json!({"layer": m.0, "mode": "gray"})).unwrap(); + let r = s.execute("edit.paste", json!({"center": [30, 30]})).unwrap(); + assert_eq!(r["offset"], json!([20, 20])); + assert!((mask_at(&s, m, 30, 30) - lum).abs() < 2.0 / 255.0); + assert_eq!(mask_at(&s, m, 10, 10), 0.0); + assert_eq!(s.active().unwrap().doc.layers.len(), 3, "Background, src, m"); +} + +#[test] +fn paste_into_and_outside_a_targeted_mask_keep_to_the_selection() { + let (mut s, src, m) = mask_target_session(16); + let lum = luminosity(&s, src, 10, 10); + // The paste is centred on the selection, so lands in place: only the selection takes it. + s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); + s.execute("edit.pasteSpecial.pasteInto", json!({"target": "mask"})).unwrap(); + assert!((mask_at(&s, m, 9, 9) - lum).abs() < 2.0 / 255.0); + assert_eq!(mask_at(&s, m, 7, 7), 0.0, "pasted, but outside the selection"); + assert!(s.active().unwrap().doc.selection.is_none()); + assert_eq!(s.active().unwrap().doc.layers.len(), 3, "no new layer"); + s.execute("layer.layerMask.hideAll", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); + s.execute("edit.pasteSpecial.pasteOutside", json!({"target": "mask"})).unwrap(); + assert_eq!(mask_at(&s, m, 9, 9), 0.0, "Paste Outside leaves the selection alone"); + assert!((mask_at(&s, m, 7, 7) - lum).abs() < 2.0 / 255.0); +} + +#[test] +fn paste_follows_a_targeted_alpha_channel() { + let (mut s, src, _) = mask_target_session(8); + let lum = luminosity(&s, src, 10, 10); + s.execute("channel.new", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": {"channel": 0}})).unwrap(); + let c = &s.active().unwrap().doc.channels[0].surface; + assert!((c.sample_channel(10, 10, 0) - lum).abs() < 2.0 / 255.0); + assert_eq!(s.active().unwrap().doc.layers.len(), 3, "no new layer"); +} + +#[test] +fn paste_into_a_missing_mask_or_channel_is_an_error() { + let (mut s, _, m) = mask_target_session(8); + s.edit("drop mask", |doc, _| { + doc.layer_mut(m).unwrap().mask = None; + Ok(()) + }) + .unwrap(); + let layers = s.active().unwrap().doc.layer_count(); + for target in [json!("mask"), json!({"channel": 7}), json!("quickMask")] { + for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace"] { + assert!(s.execute(id, json!({ "target": target })).is_err(), "{id} {target}"); + } + } + assert_eq!(s.active().unwrap().doc.layer_count(), layers, "nothing pasted as a layer"); +} + +#[test] +fn paste_between_different_color_modes() { + // Copy from an RGB document, paste into a Grayscale one: the clipboard converts to the + // target document's format (a realistic between-tabs case that must not panic). + let mut s = session(); // RGB, red rect + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("file.new", json!({"width": 120, "height": 120, "mode": "gray"})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.mode, photocraft_doc::ColorMode::Grayscale); + let pasted = d.layers.last().unwrap().surface().unwrap(); + assert_eq!(pasted.format().mode, photocraft_color::ColorMode::Grayscale, "pasted layer is grayscale"); + assert!(!pasted.content_bounds().is_empty(), "pasted content exists"); +} + +#[test] +fn transform_scale_grows_content() { + let mut s = session(); // red rect (10,10)-(50,30): 40x20 + s.execute("edit.transform", json!({"matrix": [2, 0, 0, 2, 0, 0]})).unwrap(); + let d = &s.active().unwrap().doc; + let cb = d.layers.last().unwrap().surface().unwrap().content_bounds(); + // Scaled ~2x about the origin (≈ 80x40 at ≈ (20,20)); allow ~1px bilinear edge bleed. + assert!((cb.x0 - 20).abs() <= 2 && (cb.y0 - 20).abs() <= 2, "origin ~ (20,20): {cb:?}"); + assert!((cb.width() as i32 - 80).abs() <= 3 && (cb.height() as i32 - 40).abs() <= 3, "size ~ 80x40: {cb:?}"); +} + +#[test] +fn cut_and_clear_on_the_background_fill_with_the_background_colour() { + // The Background keeps its transparency lock: cutting fills with the background colour. + let fresh = || { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); + s.tools.background = [1.0, 0.0, 0.0, 1.0]; + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + s + }; + let px = |s: &Session, i: usize, x: i32, y: i32| s.active().unwrap().doc.layers[i].surface().unwrap().pixel(x, y); + for cmd in ["edit.cut", "edit.clear", "layer.new.layerViaCut"] { + let mut s = fresh(); + s.execute(cmd, json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.is_background(d.layers[0].id), "{cmd}: still the Background"); + assert_eq!(px(&s, 0, 8, 8), vec![1.0, 0.0, 0.0, 1.0], "{cmd}: cut area is the background colour"); + assert_eq!(px(&s, 0, 30, 20), vec![1.0, 1.0, 1.0, 1.0], "{cmd}: outside untouched"); + } + // Layer via Cut still lifts the original pixels onto the new layer. + let mut s = fresh(); + s.execute("layer.new.layerViaCut", json!({})).unwrap(); + assert_eq!(px(&s, 1, 8, 8), vec![1.0, 1.0, 1.0, 1.0]); + // Once it's a normal layer, cutting makes transparency again. + let mut s = fresh(); + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + s.execute("edit.clear", json!({})).unwrap(); + assert_eq!(px(&s, 0, 8, 8)[3], 0.0); +} + +#[test] +fn layer_via_copy_of_a_background_keeps_colour_and_partial_selection() { + // #668: lift reads only the selected area now; the result must be what converting the + // whole layer gave: the colour, with the selection's coverage as alpha. + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth, "background": "#336699"})).unwrap(); + s.edit("partial selection", |doc, _| { + let mut m = photocraft_raster::Surface::new(PixelFormat::GRAY8); + m.fill_rect(Rect::new(5, 5, 15, 15), &[1.0]); + m.fill_rect(Rect::new(15, 5, 20, 15), &[0.5]); + doc.selection = Some(m); + Ok(()) + }) + .unwrap(); + let id = s.execute("layer.new.layerViaCopy", json!({})).unwrap()["layer"].as_u64().unwrap(); + let d = s.active().unwrap(); + let surf = d.doc.layer(LayerId(id)).unwrap().surface().unwrap(); + assert!(surf.format().alpha, "@{depth}"); + let full = surf.read_region(Rect::new(6, 6, 7, 7)); + let half = surf.read_region(Rect::new(16, 6, 17, 7)); + for (got, want) in full.iter().zip([0.2, 0.4, 0.6, 1.0]) { + assert!((got - want).abs() < 0.01, "@{depth}: {full:?}"); + } + assert!((half[3] - 0.5).abs() < 0.01 && (half[0] - 0.2).abs() < 0.01, "@{depth}: {half:?}"); + assert_eq!(surf.content_bounds(), Rect::new(5, 5, 20, 15), "@{depth}"); + } +} + +#[test] +fn cut_clears_and_layer_via_copy_cut() { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap(); + s.execute("edit.cut", json!({})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(20, 10, 50, 30)); + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap(); + s.execute("layer.new.layerViaCut", json!({})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 20, 30)); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(20, 10, 50, 30)); + // Without a selection ⌘J duplicates the layer. + let mut s = session(); + s.execute("layer.new.layerViaCopy", json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), 3); + assert!(d.layers[2].name.ends_with("copy")); +} + +/// #1096: Layer via Copy and Cut deselect, as Photoshop does, so a following Free Transform +/// moves the whole new layer; one undo brings back both the selection and the old layers. +#[test] +fn layer_via_copy_and_cut_deselect_in_one_step() { + for cmd in ["layer.new.layerViaCopy", "layer.new.layerViaCut"] { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap(); + let (layers, steps) = (s.active().unwrap().doc.layers.len(), s.active().unwrap().history.past_len()); + s.execute(cmd, json!({})).unwrap(); + let st = s.active().unwrap(); + assert!(st.doc.selection.is_none(), "{cmd}: deselected"); + assert_eq!((st.doc.layers.len(), st.history.past_len()), (layers + 1, steps + 1), "{cmd}"); + assert!(s.undo()); + let st = s.active().unwrap(); + assert_eq!(st.doc.layers.len(), layers, "{cmd}: undo removes the layer"); + assert!(st.doc.selection.is_some(), "{cmd}: and restores the selection"); + } +} + +/// #2777: with several layers selected and no pixel selection, Layer via Copy (Cmd+J) copies +/// every selected layer in one step, each copy above its original and the copies selected. +/// With a pixel selection it still copies the active layer's selected pixels only. +#[test] +fn layer_via_copy_duplicates_every_selected_layer() { + let mut s = session(); + let a = s.active().unwrap().active_layer.unwrap(); + let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + s.execute("layer.new.layerViaCopy", json!({})).unwrap(); + let st = s.active().unwrap(); + let ids: Vec = st.doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(ids.len(), 5, "background, a, a copy, b, b copy"); + assert_eq!((ids[1], ids[3]), (a, b), "each copy sits above its original"); + let mut selected = st.selected_layers(); + selected.sort_by_key(|l| l.0); + assert_eq!(selected, vec![ids[2], ids[4]], "the copies become the selection"); + assert_eq!(st.history.past_len(), steps + 1, "one undo step"); + assert!(s.undo()); + s.execute("layer.select", json!({"layer": b.0})).unwrap(); + s.execute("layer.select", json!({"layer": a.0, "mode": "toggle"})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("layer.new.layerViaCopy", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers.len(), 4, "a pixel selection copies one layer's pixels"); +} + +fn active_content(s: &Session) -> LayerContent { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().content.clone() +} + +/// #541, #2428: with no selection, Copy takes a smart object whole and Paste makes a smart +/// object again, with contents of its own; with a selection, the selected pixels paste as +/// pixels. Cut edits pixels, so it's refused; Layer via Copy and Duplicate Layer copy the layer. +#[test] +fn copy_a_smart_object_layer() { + let mut s = session(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let LayerContent::Smart(original) = active_content(&s) else { panic!("smart object") }; + assert!(s.is_enabled("edit.copy")); + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([10, 10, 40, 20]), "no selection: the whole layer"); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let LayerContent::Smart(pasted) = active_content(&s) else { panic!("the paste is a smart object (#2428)") }; + assert_eq!(pasted.source, original.source, "the same contents"); + assert_ne!(pasted.contents_id, original.contents_id, "but not linked to the copied one"); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 50, 30)); + s.execute("edit.paste", json!({"center": [70, 70]})).unwrap(); + assert!(matches!(active_content(&s), LayerContent::Smart(_))); + assert_eq!(active_bounds(&s), Rect::new(50, 60, 90, 80), "placed as pasted pixels are"); + s.undo(); + s.undo(); + assert!(matches!(active_content(&s), LayerContent::Smart(_))); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([10, 10, 10, 10]), "only the selected part"); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + assert!(matches!(active_content(&s), LayerContent::Raster(_)), "a selection copies pixels"); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 20, 20)); + s.undo(); + let cut = s.execute("edit.cut", json!({})).unwrap_err().to_string(); + assert!(cut.contains("not directly editable"), "{cut}"); + assert!(matches!(active_content(&s), LayerContent::Smart(_))); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("layer.new.layerViaCopy", json!({})).unwrap(); + assert!(matches!(active_content(&s), LayerContent::Smart(_)), "⌘J without a selection duplicates the smart object"); + s.execute("layer.duplicate", json!({})).unwrap(); + assert!(matches!(active_content(&s), LayerContent::Smart(_))); + assert_eq!(s.active().unwrap().doc.layers.len(), 4); +} + +/// #2478: with several layers selected and no pixel selection, Copy takes every one of them +/// and Paste recreates them all, in order, as one undo step; with a pixel selection Copy still +/// takes the active layer's selected pixels only. +#[test] +fn copy_and_paste_several_selected_layers() { + let mut s = session(); + let a = s.active().unwrap().active_layer.unwrap(); + let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.edit("paint", |doc, _| { + doc.layer_mut(b).unwrap().surface_mut().unwrap().fill_rect(Rect::new(60, 60, 80, 90), &[0.0, 0.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); + assert!(s.is_enabled("edit.copy")); + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([10, 10, 70, 80]), "both layers' pixels"); + let before = s.active().unwrap().doc.layers.len(); + let steps = s.active().unwrap().history.past_len(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.doc.layers.len(), before + 2, "every selected layer is pasted"); + assert_eq!(st.history.past_len(), steps + 1, "one undo step"); + let n = st.doc.layers.len(); + let (pa, pb) = (st.doc.layers[n - 2].surface().unwrap(), st.doc.layers[n - 1].surface().unwrap()); + assert_eq!(pa.content_bounds(), Rect::new(10, 10, 50, 30), "the lower layer first"); + assert_eq!(pb.content_bounds(), Rect::new(60, 60, 80, 90)); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc.layers.len(), before); + + // A pixel selection takes the active layer's selected pixels, as a single layer. + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers.len(), before + 1); +} + +/// #2478, #3588: several layers copied in one document paste into another, in that document's +/// bit depth and with their own pixels, in order, as one undo step. +#[test] +fn paste_several_layers_into_another_document() { + for depth in [16, 32] { + let mut s = session(); + let a = s.active().unwrap().active_layer.unwrap(); + let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.edit("paint", |doc, _| { + doc.layer_mut(b).unwrap().surface_mut().unwrap().fill_rect(Rect::new(60, 60, 80, 90), &[0.0, 0.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + + s.execute("file.new", json!({"width": 120, "height": 120, "depth": depth})).unwrap(); + assert_eq!(s.active_index().unwrap(), 1, "the new document is the active tab"); + let (before, steps) = (s.active().unwrap().doc.layers.len(), s.active().unwrap().history.past_len()); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.doc.layers.len(), before + 2, "{depth}-bit: both layers arrive"); + assert_eq!(st.history.past_len(), steps + 1, "{depth}-bit: one undo step"); + let n = st.doc.layers.len(); + let (pa, pb) = (st.doc.layers[n - 2].surface().unwrap(), st.doc.layers[n - 1].surface().unwrap()); + assert_eq!(pa.format().sample, st.doc.depth, "{depth}-bit: converted to the target depth"); + assert_eq!(pb.format().sample, st.doc.depth, "{depth}-bit: converted to the target depth"); + assert_eq!(pa.content_bounds(), Rect::new(10, 10, 50, 30), "{depth}-bit: the lower layer first"); + assert_eq!(pb.content_bounds(), Rect::new(60, 60, 80, 90)); + let (mut red, mut blue) = ([[0.0f32; 4]; 1], [[0.0f32; 4]; 1]); + pa.read_rgba_into(Rect::new(20, 20, 21, 21), &mut red); + pb.read_rgba_into(Rect::new(70, 70, 71, 71), &mut blue); + assert!(red[0][0] > 0.9 && red[0][1] < 0.1 && red[0][2] < 0.1, "{depth}-bit: red kept: {:?}", red[0]); + assert!(blue[0][2] > 0.9 && blue[0][0] < 0.1 && blue[0][1] < 0.1, "{depth}-bit: blue kept: {:?}", blue[0]); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc.layers.len(), before, "{depth}-bit: undo removes both"); + assert_eq!(s.documents().len(), 2, "the source document is untouched"); + } +} + +/// #2478: the Background in a multi-layer copy pastes as an ordinary, unlocked layer. +#[test] +fn copying_the_background_with_another_layer_pastes_an_ordinary_layer() { + let mut s = session(); + let a = s.active().unwrap().active_layer.unwrap(); + let bg = s.active().unwrap().doc.layers[0].id; + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": bg.0, "mode": "toggle"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.doc.layers.len(), 4); + let pasted = &st.doc.layers[st.doc.layers.len() - 2]; + assert!(!st.doc.is_background(pasted.id)); + assert_eq!(pasted.locks, Default::default()); + assert!(st.doc.is_background(st.doc.layers[0].id), "the real Background is untouched"); +} + +/// #2428: a smart object copied in one document pastes into another as a smart object, in +/// that document's bit depth. +#[test] +fn paste_a_smart_object_into_another_document() { + let mut s = session(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("file.new", json!({"width": 60, "height": 40, "depth": 16})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + let LayerContent::Smart(sm) = active_content(&s) else { panic!("the paste is a smart object") }; + assert_eq!(sm.cache.map(|c| c.format().sample), Some(s.active().unwrap().doc.depth), "converted to 16 bits"); + assert_eq!(active_bounds(&s), Rect::new(10, 10, 50, 30), "on the canvas: in place"); +} + +/// #3584: a PSD-embedded linked smart object (its bytes in the document's `lnk2` block, its +/// source a uuid) can still be opened after Copy + Paste into another document. +#[test] +fn paste_keeps_a_psd_embedded_smart_object_openable() { + use std::sync::Arc; + let mut s = session(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let outer = s.active().unwrap().active_layer.unwrap(); + s.edit("embedded linked source", |doc, _| { + let LayerContent::Smart(sm) = &mut doc.layer_mut(outer).ok_or(EngineError::NoDocument)?.content else { + return Err(EngineError::Other("not a smart object".into())); + }; + sm.source = photocraft_doc::SmartSource::Linked { path: "uuid-1".into() }; + let linked = photocraft_io::linked::LinkedFile { uuid: "uuid-1".into(), file_name: "in.png".into(), bytes: vec![1, 2, 3, 4] }; + doc.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", Arc::new(photocraft_io::linked::encode_linked_file(&linked)))); + Ok(()) + }) + .unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + let LayerContent::Smart(sm) = active_content(&s) else { panic!("the paste is a smart object") }; + assert!( + crate::smart_cmds::source_bytes(&s.active().unwrap().doc.metadata, &sm.source).is_some(), + "the pasted PSD-embedded linked source must resolve (#3584)" + ); +} + +/// Type and shape layers copy their rendered pixels too; groups and adjustments have none. +#[test] +fn copy_reads_any_layer_that_shows_pixels() { + let mut s = session(); + s.execute("type.create", json!({"text": "Hi", "size": 30, "x": 20, "y": 60})).unwrap(); + assert!(!s.is_enabled("edit.cut")); + assert!(s.execute("edit.copy", json!({})).is_ok()); + s.execute("layer.groupLayers", json!({})).unwrap(); + assert!(s.is_enabled("edit.copy"), "no selection: the group is copied whole (#2670)"); + s.execute("select.all", json!({})).unwrap(); + assert!(!s.is_enabled("edit.copy")); +} + +/// #2670: with no selection, Copy takes a type layer, a shape layer or a group whole and +/// Paste recreates it, into another document too (with fresh ids, in its bit depth); with a +/// selection, Copy takes pixels. +#[test] +fn copy_paste_keeps_type_shape_and_group_layers() { + let mut s = session(); + s.execute("type.create", json!({"text": "Hi", "size": 30, "x": 20, "y": 60})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let LayerContent::Text(t) = active_content(&s) else { panic!("the paste is a type layer") }; + assert_eq!(t.text, "Hi"); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + assert!(matches!(active_content(&s), LayerContent::Raster(_)), "a selection copies pixels"); + s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + let LayerContent::Group(src) = active_content(&s) else { panic!("a group") }; + s.execute("edit.copy", json!({})).unwrap(); + s.execute("file.new", json!({"width": 60, "height": 40, "depth": 16})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + let LayerContent::Group(g) = active_content(&s) else { panic!("the paste is a group") }; + let [shape] = g.children.as_slice() else { panic!("one child") }; + assert!(matches!(shape.content, LayerContent::Shape(_)), "the shape stays a shape"); + assert_ne!(shape.id, src.children[0].id, "fresh ids"); + assert_eq!(shape.surface().map(|c| c.format().sample), Some(s.active().unwrap().doc.depth), "converted to 16 bits"); +} + +#[test] +fn cross_document_group_paste_renders_shapes_on_destination_canvas() { + for (copy_to_document, depth) in [(false, 8), (true, 16)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width":100,"height":100})).unwrap(); + let mut ids = Vec::new(); + for x in [10, 50] { + s.execute("shape.create", json!({"kind":"rect","rect":[x,20,20,30],"fill":"#ff0000"})).unwrap(); + s.execute("layer.layerStyle.dropShadow", json!({"size":4,"distance":3})).unwrap(); + ids.push(s.active().unwrap().active_layer.unwrap()); + } + s.active_mut().unwrap().selected_layers = ids; + s.execute("layer.groupLayers", json!({})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("file.new", json!({"width":800,"height":600,"depth":depth})).unwrap(); + if copy_to_document { + s.execute("layer.copyToDocument", json!({"source":0,"document":1,"center":true})).unwrap(); + } else { + s.execute("edit.paste", json!({"center":[400,300]})).unwrap(); + } + let st = s.active().unwrap(); + let group = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert!(!crate::transform_cmds::transform_bounds(&st.doc, group).is_empty()); + assert_eq!(group.children().unwrap().len(), 2); + for child in group.children().unwrap() { + let LayerContent::Shape(shape) = &child.content else { panic!("shape") }; + let cache = shape.cache.as_ref().unwrap(); + assert_eq!(cache.format().sample, st.doc.depth); + assert!(!cache.content_bounds().is_empty(), "destination cache must not be clipped to source canvas"); + assert!(cache.content_bounds().x0 > 100); + let fresh = photocraft_vector::render_shape(shape, st.doc.pixel_format(), st.doc.bounds()); + assert_eq!(cache, &fresh); + } + let before = st.doc.clone(); + s.execute("layer.translate", json!({"dx":10,"dy":10})).unwrap(); + assert_ne!(s.active().unwrap().doc, before); + assert!(s.undo()); + assert_eq!(s.active().unwrap().doc, before); + } +} + +#[test] +fn paste_repairs_uncached_shapes_before_transform_and_effect_rendering() { + let mut s = session(); + s.execute("shape.create", json!({"kind":"rect","rect":[10,10,40,20],"fill":"#ff0000"})).unwrap(); + s.execute("layer.layerStyle.dropShadow", json!({"size":4,"distance":3})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + let layers = s.clipboard.as_mut().unwrap().layers.as_mut().unwrap(); + let LayerContent::Shape(sh) = &mut layers.layers[0].content else { panic!("shape") }; + sh.cache = None; + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let st = s.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + let LayerContent::Shape(sh) = &layer.content else { panic!("shape") }; + assert!(sh.cache.is_some()); + assert!(!crate::transform_cmds::transform_bounds(&st.doc, layer).is_empty()); + let expected = photocraft_vector::render_shape(sh, st.doc.pixel_format(), st.doc.bounds()); + assert_eq!(sh.cache.as_ref().unwrap(), &expected); + let rendered = photocraft_compose::render_layer_in(&st.doc, layer, st.doc.bounds()); + let mut fresh_doc = (*st.doc).clone(); + let snapshot = fresh_doc.clone(); + if let LayerContent::Shape(shape) = &mut fresh_doc.layer_mut(layer.id).unwrap().content { + crate::vector_cmds::refresh_shape(&snapshot, shape); + } + let fresh = photocraft_compose::render_layer_in(&fresh_doc, fresh_doc.layer(layer.id).unwrap(), fresh_doc.bounds()); + assert_eq!(rendered.px, fresh.px, "pasted effects match a freshly rebuilt shape"); + assert!(s.undo()); + assert!(s.redo()); + let st = s.active().unwrap(); + assert!(st.doc.layer(st.active_layer.unwrap()).unwrap().surface().is_some()); +} + +/// #2344: fill and adjustment layers have no pixels of their own, so with no selection Copy +/// takes them whole and Paste recreates them, in the same or another document, in one step. +#[test] +fn copy_paste_keeps_fill_and_adjustment_layers() { + for (depth, other) in [(8, 16), (16, 32), (32, 8)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 60, "height": 40, "depth": depth})).unwrap(); + s.execute("layer.newFillLayer.gradient", json!({"from": "#000000", "to": "#ffffff", "angle": 0})).unwrap(); + let LayerContent::Fill(fill) = active_content(&s) else { panic!("a fill layer") }; + let src = s.active().unwrap().active_layer.unwrap(); + assert!(s.is_enabled("edit.copy"), "{depth}-bit: a fill layer can be copied"); + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 60, 40]), "{depth}-bit: what it shows"); + let clip = s.clipboard.clone().unwrap(); + assert!(clip.surface.rgba(59, 20)[0] > clip.surface.rgba(0, 20)[0], "{depth}-bit: the clip holds the gradient's pixels"); + let steps = s.active().unwrap().history.past_len(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{depth}-bit: one history step"); + assert_eq!(active_content(&s), LayerContent::Fill(fill.clone()), "{depth}-bit: the paste is the same fill layer"); + assert_ne!(s.active().unwrap().active_layer, Some(src), "{depth}-bit: a new layer"); + s.undo(); + assert_eq!(s.active().unwrap().active_layer, Some(src), "{depth}-bit: undo removes the paste"); + s.redo(); + assert!(matches!(active_content(&s), LayerContent::Fill(_)), "{depth}-bit: redo brings it back"); + + s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); + let LayerContent::Adjustment(levels) = active_content(&s) else { panic!("an adjustment layer") }; + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 60, 40]), "{depth}-bit: it applies to the canvas"); + s.execute("file.new", json!({"width": 30, "height": 30, "depth": other})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(active_content(&s), LayerContent::Adjustment(levels), "{depth}-bit: the same Levels layer in the {other}-bit document"); + assert_eq!(s.active().unwrap().doc.layers.len(), 2, "{depth}-bit: pasted above the Background"); + } +} + +/// #2344: several adjustment layers, which show nothing alone, still copy and paste together. +#[test] +fn several_adjustment_layers_copy_together() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); + let a = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); + let b = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.select", json!({"layer": a})).unwrap(); + s.execute("layer.select", json!({"layer": b, "mode": "toggle"})).unwrap(); + assert_eq!(s.execute("edit.copy", json!({})).unwrap()["bounds"], json!([0, 0, 40, 40])); + s.execute("edit.pasteSpecial.pasteInPlace", json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), 5, "both are pasted"); + assert!(d.layers[3..].iter().all(|l| matches!(l.content, LayerContent::Adjustment(_)))); +} + +#[test] +fn merge_visible_keeps_hidden_layers() { + let mut s = session(); + s.execute("layer.new.layer", json!({})).unwrap(); + let hidden = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.setProps", json!({"layer": hidden.0, "visible": false})).unwrap(); + s.execute("layer.mergeVisible", json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), 2); + assert_eq!(d.layers[0].name, "Background"); + assert_eq!(d.layers[1].id, hidden); + assert_eq!(d.layers[0].surface().unwrap().pixel(20, 20)[..3], [1.0, 0.0, 0.0]); +} + +#[test] +fn auto_tone_stretches_a_low_contrast_layer() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + s.edit("grey ramp", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + for x in 0..64 { + let v = 0.3 + 0.4 * x as f32 / 63.0; + surf.fill_rect(Rect::new(x, 0, x + 1, 64), &[v, v * 0.9, v * 0.8, 1.0]); + } + Ok(()) + }) + .unwrap(); + for cmd in ["image.autoTone", "image.autoContrast", "image.autoColor"] { + s.execute(cmd, json!({})).unwrap(); + let d = &s.active().unwrap().doc; + let (a, b) = (d.layers[0].surface().unwrap().pixel(0, 0), d.layers[0].surface().unwrap().pixel(63, 0)); + // Auto Contrast keeps colour (shared points): only the extreme channels reach 0 and 1. + let (lo, hi) = if cmd == "image.autoContrast" { (a[2], b[0]) } else { (a[0], b[0]) }; + assert!(lo < 0.05 && hi > 0.95, "{cmd}: {a:?} {b:?}"); + s.undo(); + } +} + +/// #352: ⌥⇧⌘T steps and repeats: each press adds a copy one transform further on, and each +/// is one undo step. +#[test] +fn transform_again_on_a_copy_steps_and_repeats() { + let mut s = session(); + assert!(s.execute("edit.transform.againCopy", json!({})).is_err(), "nothing to repeat yet"); + assert_eq!(s.active().unwrap().doc.layers.len(), 2, "a refusal leaves no copy"); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 0]})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + for (i, x) in [30, 40].into_iter().enumerate() { + s.execute("edit.transform.againCopy", json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), 3 + i); + assert_eq!(active_bounds(&s), Rect::new(x, 10, x + 40, 30), "the copy moved one step further"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1 + i, "one history step per press"); + } + assert_eq!(s.active().unwrap().history.undo_label(), Some("Transform Again")); + // The original and the first copy stay where they were. + let d = &s.active().unwrap().doc; + let b = |i: usize| d.layers[i].surface().unwrap().content_bounds(); + assert_eq!((b(1), b(2)), (Rect::new(20, 10, 60, 30), Rect::new(30, 10, 70, 30))); + // Undo removes the copy and its move together. + s.undo(); + assert_eq!(s.active().unwrap().doc.layers.len(), 3); + assert_eq!(active_bounds(&s), Rect::new(30, 10, 70, 30)); + // A copy that can't move (position locked) is taken back. + let id = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.setProps", json!({"layer": id.0, "locks": {"position": true}})).unwrap(); + let layers = s.active().unwrap().doc.layers.len(); + assert!(s.execute("edit.transform.againCopy", json!({})).unwrap_err().to_string().contains("locked")); + assert_eq!(s.active().unwrap().doc.layers.len(), layers); + assert!(!s.active().unwrap().history.can_redo(), "nothing to redo"); +} + +#[test] +fn toggle_last_state_and_transform_again() { + let mut s = session(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 0]})).unwrap(); + s.execute("edit.transform.again", json!({})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(30, 10, 70, 30)); + s.execute("edit.toggleLastState", json!({})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(20, 10, 60, 30)); + s.execute("edit.toggleLastState", json!({})).unwrap(); + assert_eq!(active_bounds(&s), Rect::new(30, 10, 70, 30)); +} + +#[test] +fn guides_are_undoable() { + let mut s = session(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 40})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "horizontal", "position": 12.5})).unwrap(); + s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 0, "position": 60})).unwrap(); + let g = &s.active().unwrap().doc.guides; + assert_eq!((g.vertical.clone(), g.horizontal.clone()), (vec![60.0], vec![12.5])); + s.execute("view.deleteGuide", json!({"orientation": "horizontal", "index": 0})).unwrap(); + s.undo(); + assert_eq!(s.active().unwrap().doc.guides.horizontal, vec![12.5]); + s.execute("view.clearGuides", json!({})).unwrap(); + assert!(s.active().unwrap().doc.guides.vertical.is_empty()); + assert!(s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 3, "position": 1})).is_err()); +} + +/// #2955: the rulers' zero point is set and reset by command, undoable, and bad params are +/// refused without touching the document. +#[test] +fn ruler_origin_is_set_reset_and_undoable() { + let mut s = session(); + assert_eq!(s.active().unwrap().doc.ruler_origin, [0.0, 0.0]); + assert_eq!(s.execute("view.setRulerOrigin", json!({"x": 40, "y": 12.5})).unwrap(), json!({"x": 40.0, "y": 12.5})); + assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]); + s.execute("view.resetRulerOrigin", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.ruler_origin, [0.0, 0.0]); + s.undo(); + assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]); + for bad in [json!({}), json!({"x": 1}), json!({"x": "a", "y": 2}), json!({"x": 1e300, "y": 0}), json!({"x": -2e7, "y": 0}), json!(null), json!([1, 2])] + { + assert!(s.execute("view.setRulerOrigin", bad.clone()).is_err(), "{bad} is refused"); + } + assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]); + let mut empty = Session::new(); + assert!(empty.execute("view.setRulerOrigin", json!({"x": 1, "y": 2})).is_err()); + assert!(empty.execute("view.resetRulerOrigin", json!({})).is_err()); +} + +/// The last guide added in `orientation` for `position`. +fn new_guide(s: &mut Session, orientation: &str, position: Value) -> f64 { + s.execute("view.newGuide", json!({"orientation": orientation, "position": position})).unwrap(); + let g = &s.active().unwrap().doc.guides; + *if orientation == "vertical" { &g.vertical } else { &g.horizontal }.last().unwrap() +} + +#[test] +fn guide_positions_take_photoshop_units() { + let mut s = Session::new(); + // 4 × 2 inches at 100 ppi. + s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 100})).unwrap(); + // Percent follows the guide's own axis: the width for a vertical guide, the height for a horizontal one. + assert_eq!(new_guide(&mut s, "vertical", json!("50%")), 200.0); + assert_eq!(new_guide(&mut s, "horizontal", json!("50%")), 100.0); + for one_inch in ["1in", "1 in", "2.54cm", "25.4 mm", "72pt", "6pc", "100px", "100", "1,0 inch"] { + assert!((new_guide(&mut s, "vertical", json!(one_inch)) - 100.0).abs() < 1e-3, "{one_inch}"); + } + // Fractional and negative positions are kept; a plain number is pixels, as before. + assert_eq!(new_guide(&mut s, "horizontal", json!("12.5px")), 12.5); + assert_eq!(new_guide(&mut s, "vertical", json!("-10px")), -10.0); + assert_eq!(new_guide(&mut s, "vertical", json!(40)), 40.0); + // Points and picas follow Units & Rulers › Point Size. + s.execute("prefs.set", json!({"path": "unitsAndRulers.pointSize", "value": "traditional"})).unwrap(); + assert!((new_guide(&mut s, "vertical", json!("72.27pt")) - 100.0).abs() < 1e-3); + // A guide moved with a unit lands where a new one would. + s.execute("view.moveGuide", json!({"orientation": "horizontal", "index": 0, "position": "25%"})).unwrap(); + assert_eq!(s.active().unwrap().doc.guides.horizontal[0], 50.0); +} + +#[test] +fn new_guides_keep_their_own_colour_through_moves_deletes_and_undo() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + let color = |s: &Session, vertical: bool, p: f64| s.active().unwrap().doc.guides.color(vertical, p); + // Without a colour a guide uses the preference colour, as ruler-drag guides always did. + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10})).unwrap(); + assert_eq!(color(&s, true, 10.0), None); + assert!(s.active().unwrap().doc.guides.colors.is_empty()); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 20, "color": "magenta"})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "horizontal", "position": 20, "color": "#123456"})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 30, "color": "LightBlue"})).unwrap(); + assert_eq!(color(&s, true, 20.0), Some([0xff, 0x00, 0xff])); + assert_eq!(color(&s, false, 20.0), Some([0x12, 0x34, 0x56]), "the same position across is a different guide"); + assert_eq!(color(&s, true, 30.0), Some([0x33, 0x66, 0xff]), "names are case-insensitive"); + // Moving takes the colour along. + s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 1, "position": 25})).unwrap(); + assert_eq!((color(&s, true, 20.0), color(&s, true, 25.0)), (None, Some([0xff, 0x00, 0xff]))); + // Undo restores it where it was. + s.undo(); + assert_eq!((color(&s, true, 20.0), color(&s, true, 25.0)), (Some([0xff, 0x00, 0xff]), None)); + // Deleting drops it; clearing drops them all. + s.execute("view.deleteGuide", json!({"orientation": "vertical", "index": 2})).unwrap(); + assert_eq!(color(&s, true, 30.0), None); + assert_eq!(s.active().unwrap().doc.guides.colors.len(), 2); + s.execute("view.clearGuides", json!({})).unwrap(); + assert!(s.active().unwrap().doc.guides.colors.is_empty()); +} + +#[test] +fn moving_one_of_two_coloured_guides_at_one_position_leaves_the_other_its_colour() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + for _ in 0..2 { + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 50, "color": "green"})).unwrap(); + } + s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 0, "position": 60})).unwrap(); + let g = &s.active().unwrap().doc.guides; + assert_eq!((g.color(true, 50.0), g.color(true, 60.0)), (Some([0x33, 0xff, 0x33]), Some([0x33, 0xff, 0x33]))); +} + +#[test] +fn cyan_is_the_default_guide_colour_so_ruler_guides_read_as_cyan() { + let default = crate::prefs::Preferences::default().guides_grid_and_slices.guide_color; + let cyan = GUIDE_COLORS.iter().find(|(name, ..)| *name == "cyan").map(|(.., rgb)| *rgb); + assert_eq!(cyan, crate::prefs::parse_hex(&default)); +} + +#[test] +fn bad_guide_colours_are_refused_without_a_guide() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + let undo_before = s.active().unwrap().history.can_undo(); + for bad in [json!("puce"), json!("#12345"), json!("#gggggg"), json!(""), json!(7), json!(null), json!(["cyan"])] { + assert!(s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10, "color": bad.clone()})).is_err(), "{bad}"); + } + let g = &s.active().unwrap().doc.guides; + assert!(g.vertical.is_empty() && g.colors.is_empty()); + assert_eq!(s.active().unwrap().history.can_undo(), undo_before); +} + +#[test] +fn editing_a_guide_changes_what_is_given_in_one_undoable_step() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 20, "color": "magenta"})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 30})).unwrap(); + let guides = |s: &Session| s.active().unwrap().doc.guides.clone(); + // Position only: the guide keeps its index and its own colour. + s.execute("view.editGuide", json!({"orientation": "vertical", "index": 1, "position": "50%"})).unwrap(); + let g = guides(&s); + assert_eq!(g.vertical, vec![10.0, 200.0, 30.0]); + assert_eq!((g.color(true, 20.0), g.color(true, 200.0)), (None, Some([0xff, 0x00, 0xff]))); + // Colour only: an uncoloured guide gets one; the position stays. + s.execute("view.editGuide", json!({"orientation": "vertical", "index": 0, "color": "#123456"})).unwrap(); + assert_eq!(guides(&s).color(true, 10.0), Some([0x12, 0x34, 0x56])); + // Turning it: % is of the new orientation's extent, and the colour goes along. + s.execute("view.editGuide", json!({"orientation": "vertical", "index": 1, "newOrientation": "horizontal", "position": "25%"})).unwrap(); + let g = guides(&s); + assert_eq!((g.vertical.clone(), g.horizontal.clone()), (vec![10.0, 30.0], vec![50.0])); + assert_eq!((g.color(true, 200.0), g.color(false, 50.0)), (None, Some([0xff, 0x00, 0xff]))); + // One step each: undo restores the vertical guide with its colour. + s.undo(); + let g = guides(&s); + assert_eq!((g.vertical.clone(), g.horizontal.is_empty()), (vec![10.0, 200.0, 30.0], true)); + assert_eq!(g.color(true, 200.0), Some([0xff, 0x00, 0xff])); +} + +#[test] +fn bad_guide_edits_are_refused_without_a_history_step() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": 10, "color": "green"})).unwrap(); + let before = s.active().unwrap().doc.guides.clone(); + for bad in [ + json!({}), + json!({"orientation": "vertical"}), + json!({"orientation": "vertical", "index": 1}), + json!({"orientation": "horizontal", "index": 0}), + json!({"orientation": "vertical", "index": -1}), + json!({"orientation": "vertical", "index": "0"}), + json!({"orientation": "vertical", "index": u64::MAX}), + json!({"orientation": "diagonal", "index": 0}), + json!({"orientation": "vertical", "index": 0, "newOrientation": 3}), + json!({"orientation": "vertical", "index": 0, "position": "far"}), + json!({"orientation": "vertical", "index": 0, "position": 1e12}), + json!({"orientation": "vertical", "index": 0, "color": "puce"}), + ] { + assert!(s.execute("view.editGuide", bad.clone()).is_err(), "{bad}"); + } + assert_eq!(s.active().unwrap().doc.guides, before); + assert_eq!(s.active().unwrap().history.undo_label(), Some("New Guide")); +} + +#[test] +fn bad_guide_positions_are_refused_without_a_guide() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 200, "resolution": 100})).unwrap(); + let undo_before = s.active().unwrap().history.can_undo(); + for bad in [ + json!("abc"), + json!("50 furlongs"), + json!(""), + json!("%"), + json!("NaN"), + json!("inf"), + json!("1e400"), + json!("2000000px"), + json!(1e300), + json!(true), + json!([1]), + ] { + assert!(s.execute("view.newGuide", json!({"orientation": "vertical", "position": bad.clone()})).is_err(), "{bad}"); + } + assert!(s.execute("view.newGuide", json!({"orientation": "vertical"})).is_err(), "no position"); + let g = &s.active().unwrap().doc.guides; + assert!(g.vertical.is_empty() && g.horizontal.is_empty()); + assert_eq!(s.active().unwrap().history.can_undo(), undo_before, "a refused guide records no history step"); +} + +/// Guides keep their exact place (#2918): 1 cm at 300 ppi through New Guide and .pcraft, and +/// a 1/32 px PSD position past 2^19 px, where f32 has no 1/32 steps left. +#[test] +fn guides_keep_sub_pixel_positions_through_pcraft_and_psd() { + let (cm, far) = (300.0 / 2.54, 600_000.031_25); + let mut s = session(); + s.execute("view.newGuide", json!({"orientation": "horizontal", "position": cm})).unwrap(); + s.execute("view.newGuide", json!({"orientation": "vertical", "position": far})).unwrap(); + fn wide(v: impl Into) -> f64 { + v.into() + } + let exact = |g: &photocraft_doc::Guides| (wide(g.horizontal[0]), wide(g.vertical[0])); + let doc = &s.active().unwrap().doc; + assert_eq!(exact(&doc.guides), (cm, far)); + let pcraft = photocraft_format::save_to_bytes(doc, &Default::default()).unwrap(); + assert_eq!(exact(&photocraft_format::load_from_bytes(&pcraft).unwrap().guides), (cm, far)); + let psd = photocraft_io::export(doc, "psd", &Default::default()).unwrap().bytes; + let back = photocraft_io::import("g.psd", &psd).unwrap().document.guides; + assert_eq!(wide(back.vertical[0]), far, "1032 stores 1/32 px"); +} + +/// `lift` as it was before #4516: the whole area through one `f32` buffer. The oracle for +/// the tiled version. +fn lift_reference(src: &Surface, sel: Option<&Surface>, canvas: Rect) -> Clip { + let fmt = src.format(); + let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true); + let area = match sel { + Some(m) => m.content_bounds().intersect(&canvas), + None => src.content_bounds().intersect(&canvas), + }; + let mut out = Surface::new(with_alpha); + if area.is_empty() { + return Clip { surface: out, bounds: Rect::EMPTY, layers: None, resolution: None, source: None }; + } + let px = lift_region(src, sel, area, with_alpha.channels()).unwrap(); + out.try_write_region(area, &px).unwrap(); + out.prune(); + let bounds = out.content_bounds(); + Clip { surface: out, bounds, layers: None, resolution: None, source: None } +} + +fn noise(fmt: PixelFormat, r: Rect, seed: u32) -> Surface { + let mut s = Surface::new(fmt); + let n = r.width() as usize * r.height() as usize * fmt.channels(); + let data: Vec = (0..n as u32) + .map(|i| { + let mut h = seed.wrapping_mul(0x9e37_79b9) ^ i.wrapping_mul(0x85eb_ca6b); + h ^= h >> 13; + h = h.wrapping_mul(0xc2b2_ae35); + (h >> 16) as f32 / 65535.0 + }) + .collect(); + s.write_region(r, &data); + s +} + +fn assert_same_clip(a: &Clip, b: &Clip, what: &str) { + assert_eq!(a.bounds, b.bounds, "{what}: bounds"); + assert_eq!(a.surface.format(), b.surface.format(), "{what}: format"); + let r = a.bounds.union(&b.bounds); + if !r.is_empty() { + let (pa, pb) = (a.surface.read_region(r), b.surface.read_region(r)); + assert!(pa.iter().zip(&pb).all(|(x, y)| x.to_bits() == y.to_bits()), "{what}: pixels differ"); + } +} + +/// The tiled `lift` gives exactly the old result (#4516): with and without alpha, at every +/// depth, with no selection, Select All, a partial feathered selection and a selection off +/// the tile grid, and for content reaching past the canvas. +#[test] +fn tiled_lift_matches_the_whole_area_lift() { + use photocraft_color::{ColorMode, SampleType}; + let canvas = Rect::new(0, 0, 700, 600); + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + for alpha in [true, false] { + let fmt = PixelFormat::new(ColorMode::Rgb, sample, alpha); + let src = noise(fmt, Rect::new(-40, -30, 760, 640), 7); + let mut all = Surface::new(PixelFormat::GRAY8); + all.fill_rect(canvas, &[1.0]); + let mut partial = Surface::new(PixelFormat::GRAY8); + partial.fill_rect(Rect::new(100, 50, 600, 550), &[1.0]); + partial.write_region(Rect::new(90, 40, 610, 50), &vec![0.5; 520 * 10]); + let off_grid = noise(PixelFormat::GRAY8, Rect::new(13, 270, 333, 290), 9); + for (name, sel) in [("no selection", None), ("select all", Some(&all)), ("partial", Some(&partial)), ("off grid", Some(&off_grid))] { + let what = format!("{sample:?} alpha {alpha} {name}"); + let new = lift(&src, sel, canvas).unwrap(); + assert_same_clip(&new, &lift_reference(&src, sel, canvas), &what); + } + } + } +} + +/// Copy shares the layer's whole tiles instead of copying them. +#[test] +fn copy_shares_whole_tiles_with_the_layer() { + let src = noise(PixelFormat::RGBA8, Rect::new(0, 0, 1024, 768), 3); + let canvas = Rect::new(0, 0, 1024, 768); + let mut all = Surface::new(PixelFormat::GRAY8); + all.fill_rect(canvas, &[1.0]); + for sel in [None, Some(&all)] { + let clip = lift(&src, sel, canvas).unwrap(); + let shared = src.tiles().filter(|(c, t)| clip.surface.tile(**c).is_some_and(|o| std::sync::Arc::ptr_eq(o, t))).count(); + assert_eq!(shared, src.tile_count(), "every tile is shared"); + } +} From 3f4d8ee025da228ae0fc426d97a9b512ed94854f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:10 +0000 Subject: [PATCH 029/259] refactor(engine): move brush_preset_cmds.rs tests to brush_preset_cmds/tests.rs --- crates/engine/src/brush_preset_cmds.rs | 329 +------------------ crates/engine/src/brush_preset_cmds/tests.rs | 326 ++++++++++++++++++ 2 files changed, 327 insertions(+), 328 deletions(-) create mode 100644 crates/engine/src/brush_preset_cmds/tests.rs diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rs index 1c126ec477..cd54b1ff61 100644 --- a/crates/engine/src/brush_preset_cmds.rs +++ b/crates/engine/src/brush_preset_cmds.rs @@ -486,331 +486,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - fn names(s: &Session, g: &str) -> Vec { - s.tools.presets.iter().filter(|x| x.group == g).map(|x| x.name.clone()).collect() - } - - fn with_groups() -> Session { - let mut s = Session::new(); - for (n, g) in [("A1", "Alpha"), ("A2", "Alpha"), ("A3", "Alpha"), ("B1", "Beta"), ("B2", "Beta")] { - s.tools.presets.push(BrushPreset { - name: n.into(), - brush: Default::default(), - builtin: false, - group: g.into(), - folder: Vec::new(), - captures: Default::default(), - }); - } - s - } - - #[test] - fn move_within_and_between_groups() { - let mut s = with_groups(); - let r = s.execute("brush.presets.move", json!({"name": "A3", "before": "A1"})).unwrap(); - assert_eq!(r, json!({"name": "A3", "group": "Alpha", "folder": [], "index": 0})); - assert_eq!(names(&s, "Alpha"), ["A3", "A1", "A2"]); - s.execute("brush.presets.move", json!({"name": "A3", "index": 99})).unwrap(); - assert_eq!(names(&s, "Alpha"), ["A1", "A2", "A3"]); - s.execute("brush.presets.move", json!({"name": "A1", "index": 1})).unwrap(); - assert_eq!(names(&s, "Alpha"), ["A2", "A1", "A3"]); - // Into another group, before a member (the group comes from `before`). - s.execute("brush.presets.move", json!({"name": "A1", "before": "B2"})).unwrap(); - assert_eq!((names(&s, "Alpha"), names(&s, "Beta")), (vec!["A2".to_string(), "A3".into()], vec!["B1".to_string(), "A1".into(), "B2".into()])); - // Into a group by name (appended), and into a new group. - s.execute("brush.presets.move", json!({"name": "A2", "group": "Beta"})).unwrap(); - assert_eq!(names(&s, "Beta"), ["B1", "A1", "B2", "A2"]); - s.execute("brush.presets.move", json!({"name": "A3", "group": "Gamma"})).unwrap(); - assert_eq!(group_order(&s.tools.presets).last().map(String::as_str), Some("Gamma")); - assert!(names(&s, "Alpha").is_empty()); - // A built-in moved to another group becomes the user's. - let b = s.tools.presets.iter().find(|x| x.builtin).unwrap().name.clone(); - s.execute("brush.presets.move", json!({"name": b, "group": "Beta", "index": 0})).unwrap(); - let moved = photocraft_paint::presets::find(&s.tools.presets, &b).unwrap(); - assert!(!moved.builtin && moved.group == "Beta"); - assert_eq!(names(&s, "Beta")[0], b); - } - - #[test] - fn groups_move_rename_and_delete() { - let mut s = with_groups(); - let order = group_order(&s.tools.presets); - let n = order.len(); - assert_eq!(&order[n - 2..], ["Alpha", "Beta"]); - let r = s.execute("brush.presets.moveGroup", json!({"group": "Beta", "index": 0})).unwrap(); - assert_eq!(r["index"], 0); - assert_eq!(group_order(&s.tools.presets)[0], "Beta"); - assert_eq!(names(&s, "Beta"), ["B1", "B2"], "a group moves as a block, in order"); - s.execute("brush.presets.moveGroup", json!({"group": "Alpha", "before": "Beta"})).unwrap(); - assert_eq!(&group_order(&s.tools.presets)[..2], ["Alpha", "Beta"]); - s.execute("brush.presets.moveGroup", json!({"group": "Alpha"})).unwrap(); - assert_eq!(group_order(&s.tools.presets).last().map(String::as_str), Some("Alpha")); - s.execute("brush.presets.renameGroup", json!({"group": "Alpha", "newName": "First"})).unwrap(); - assert_eq!(names(&s, "First"), ["A1", "A2", "A3"]); - assert!(s.execute("brush.presets.renameGroup", json!({"group": "First", "newName": "Beta"})).is_err()); - let r = s.execute("brush.presets.deleteGroup", json!({"group": "First"})).unwrap(); - assert_eq!(r["deleted"], 3); - assert!(names(&s, "First").is_empty()); - } - - #[test] - fn rename_checks_names() { - let mut s = with_groups(); - s.execute("brush.presets.rename", json!({"name": "a1", "newName": "Alpha One"})).unwrap(); - assert!(photocraft_paint::presets::find(&s.tools.presets, "Alpha One").is_some()); - assert!(s.execute("brush.presets.rename", json!({"name": "A2", "newName": "alpha one"})).is_err()); - // Case-only renames of itself are fine. - s.execute("brush.presets.rename", json!({"name": "Alpha One", "newName": "ALPHA ONE"})).unwrap(); - let b = s.tools.presets.iter().find(|x| x.builtin).unwrap().name.clone(); - s.execute("brush.presets.rename", json!({"name": b, "newName": "My Round"})).unwrap(); - assert!(!photocraft_paint::presets::find(&s.tools.presets, "My Round").unwrap().builtin); - } - - #[test] - fn bad_params_fail_without_changes() { - let mut s = with_groups(); - let before = s.tools.presets.clone(); - let long = "x".repeat(MAX_NAME + 1); - for (id, p) in [ - ("brush.presets.move", json!({})), - ("brush.presets.move", json!({"name": "Nope"})), - ("brush.presets.move", json!({"name": "A1", "before": "A1"})), - ("brush.presets.move", json!({"name": "A1", "before": "Nope"})), - ("brush.presets.move", json!({"name": "A1", "group": "Alpha", "before": "B1"})), - ("brush.presets.move", json!({"name": "A1", "index": -1})), - ("brush.presets.move", json!({"name": "A1", "index": "first"})), - ("brush.presets.move", json!({"name": "A1", "group": 7})), - ("brush.presets.move", json!({"name": "A1", "group": long})), - ("brush.presets.rename", json!({"name": "A1"})), - ("brush.presets.rename", json!({"name": "A1", "newName": " "})), - ("brush.presets.rename", json!({"name": "A1", "newName": long})), - ("brush.presets.moveGroup", json!({"group": "Nope"})), - ("brush.presets.moveGroup", json!({"group": "Alpha", "before": "Alpha"})), - ("brush.presets.moveGroup", json!({"group": "Alpha", "index": 1.5})), - ("brush.presets.renameGroup", json!({"group": "Alpha"})), - ("brush.presets.deleteGroup", json!({"group": null})), - ("brush.presets.deleteGroup", json!({"group": "Nope"})), - ] { - assert!(s.execute(id, p.clone()).is_err(), "{id} {p}"); - } - assert_eq!(s.tools.presets, before); - // Huge indices clamp to the end. - s.execute("brush.presets.move", json!({"name": "A1", "index": u64::MAX})).unwrap(); - s.execute("brush.presets.moveGroup", json!({"group": "Alpha", "index": u64::MAX})).unwrap(); - } - - /// Group "Set": S0 at its top level, folders Ink (I1, I2; subfolder Fine: F1) and Dry (D1). - fn with_folders() -> Session { - let mut s = Session::new(); - for (n, f) in [("S0", &[][..]), ("I1", &["Ink"][..]), ("F1", &["Ink", "Fine"][..]), ("I2", &["Ink"][..]), ("D1", &["Dry"][..])] { - let folder = f.iter().map(|x| x.to_string()).collect(); - s.tools.presets.push(BrushPreset { - name: n.into(), - brush: Default::default(), - builtin: false, - group: "Set".into(), - folder, - captures: Default::default(), - }); - } - s - } - - fn folder_of(s: &Session, n: &str) -> Vec { - photocraft_paint::presets::find(&s.tools.presets, n).unwrap().folder.clone() - } - - #[test] - fn presets_move_between_folders() { - let mut s = with_folders(); - // `before` brings its folder. - let r = s.execute("brush.presets.move", json!({"name": "D1", "before": "I2"})).unwrap(); - assert_eq!(r["folder"], json!(["Ink"])); - assert_eq!(folder_of(&s, "D1"), ["Ink"]); - // An explicit folder, appended at the end of it. - s.execute("brush.presets.move", json!({"name": "S0", "folder": ["Ink", "Fine"]})).unwrap(); - assert_eq!(folder_of(&s, "S0"), ["Ink", "Fine"]); - let pos = |n: &str| s.tools.presets.iter().position(|x| x.name == n).unwrap(); - assert_eq!(pos("S0"), pos("F1") + 1); - // Within its group without a folder keeps its folder; to another group without one lands - // at that group's top level; `folder: []` is the group's top level. - s.execute("brush.presets.move", json!({"name": "S0", "index": 0})).unwrap(); - assert_eq!(folder_of(&s, "S0"), ["Ink", "Fine"]); - s.execute("brush.presets.move", json!({"name": "S0", "group": "Other"})).unwrap(); - assert!(folder_of(&s, "S0").is_empty()); - s.execute("brush.presets.move", json!({"name": "I1", "folder": []})).unwrap(); - assert!(folder_of(&s, "I1").is_empty()); - // `before` in another folder than the one named. - assert!(s.execute("brush.presets.move", json!({"name": "I1", "folder": ["Dry"], "before": "I2"})).is_err()); - assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Ink"]); - } - - #[test] - fn folders_move_rename_and_delete() { - let mut s = with_folders(); - assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Ink", "Dry"]); - // Move Dry before Ink: the whole folder moves as a block. - let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"], "before": "Ink"})).unwrap(); - assert_eq!(r, json!({"group": "Set", "folder": ["Dry"], "index": 0})); - assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Dry", "Ink"]); - s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"]})).unwrap(); - assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Ink", "Dry"]); - s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"], "index": 0})).unwrap(); - assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Dry", "Ink"]); - let ink: Vec<&str> = s.tools.presets.iter().filter(|x| x.folder.first().is_some_and(|f| f == "Ink")).map(|x| x.name.as_str()).collect(); - assert_eq!(ink, ["I1", "F1", "I2"], "presets keep their order inside a moved folder"); - // Rename a nested folder: every preset below it follows. - let r = s.execute("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Ink"], "newName": "Inks"})).unwrap(); - assert_eq!(r["folder"], json!(["Inks"])); - assert_eq!(folder_of(&s, "F1"), ["Inks", "Fine"]); - assert!(s.execute("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Inks"], "newName": "Dry"})).is_err()); - // Renaming the group keeps the folders. - s.execute("brush.presets.renameGroup", json!({"group": "Set", "newName": "Kit"})).unwrap(); - assert_eq!(folder_of(&s, "F1"), ["Inks", "Fine"]); - // Delete a nested folder: only the presets in it (and below) go. - let r = s.execute("brush.presets.deleteGroup", json!({"group": "Kit", "folder": ["Inks"]})).unwrap(); - assert_eq!(r["deleted"], 3); - assert!(photocraft_paint::presets::find(&s.tools.presets, "S0").is_some()); - assert!(photocraft_paint::presets::find(&s.tools.presets, "D1").is_some()); - } - - #[test] - fn bad_folder_params_fail_without_changes() { - let mut s = with_folders(); - let before = s.tools.presets.clone(); - let long = "x".repeat(MAX_NAME + 1); - let deep: Vec<&str> = vec!["a"; MAX_FOLDER_DEPTH + 1]; - for (id, p) in [ - ("brush.presets.move", json!({"name": "S0", "folder": "Ink"})), - ("brush.presets.move", json!({"name": "S0", "folder": [""]})), - ("brush.presets.move", json!({"name": "S0", "folder": [7]})), - ("brush.presets.move", json!({"name": "S0", "folder": [long]})), - ("brush.presets.move", json!({"name": "S0", "folder": deep})), - ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Nope"]})), - ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "before": "Ink"})), - ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "before": "Nope"})), - ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "before": 3})), - ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "index": -2})), - ("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Ink"], "newName": ""})), - ("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Ink", "Nope"], "newName": "x"})), - ("brush.presets.deleteGroup", json!({"group": "Set", "folder": ["Dry", "Nope"]})), - ("brush.presets.deleteGroup", json!({"group": "Nope", "folder": ["Dry"]})), - ] { - assert!(s.execute(id, p.clone()).is_err(), "{id} {p}"); - } - assert_eq!(s.tools.presets, before); - s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "index": u64::MAX})).unwrap(); - } - - fn paths(s: &Session) -> Vec { - s.tools.presets.iter().filter(|x| !x.builtin).map(|x| format!("{}:{}:{}", x.group, x.folder.join("/"), x.name)).collect() - } - - /// `with_folders` plus group "Other" holding O1, and folder Box (B1) in it. - fn with_two_groups() -> Session { - let mut s = with_folders(); - for (n, f) in [("O1", &[][..]), ("B1", &["Box"][..])] { - let folder = f.iter().map(|x| x.to_string()).collect(); - s.tools.presets.push(BrushPreset { - name: n.into(), - brush: Default::default(), - builtin: false, - group: "Other".into(), - folder, - captures: Default::default(), - }); - } - s - } - - #[test] - fn folders_move_into_folders_and_groups() { - let mut s = with_two_groups(); - // A nested folder into a sibling folder: its subtree follows, order kept. - let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}})).unwrap(); - assert_eq!(r, json!({"group": "Set", "folder": ["Ink", "Fine", "Dry"], "index": 0})); - assert_eq!(folder_of(&s, "D1"), ["Ink", "Fine", "Dry"]); - // Into another group, before one of its folders. - let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Other"}, "before": "Box"})).unwrap(); - assert_eq!(r["folder"], json!(["Ink"])); - assert_eq!(paths(&s), ["Set::S0", "Other::O1", "Other:Ink:I1", "Other:Ink/Fine:F1", "Other:Ink/Fine/Dry:D1", "Other:Ink:I2", "Other:Box:B1"]); - // Out to the top level: the folder becomes a group of its own. - let r = s.execute("brush.presets.moveGroup", json!({"group": "Other", "folder": ["Ink", "Fine"], "into": {}})).unwrap(); - assert_eq!(r["group"], "Fine"); - assert_eq!(folder_of(&s, "D1"), ["Dry"]); - assert_eq!(photocraft_paint::presets::find(&s.tools.presets, "F1").unwrap().group, "Fine"); - // A whole group into another group's folder. - s.execute("brush.presets.moveGroup", json!({"group": "Fine", "into": {"group": "Set"}})).unwrap(); - assert!(names(&s, "Fine").is_empty()); - assert_eq!(folder_of(&s, "D1"), ["Fine", "Dry"]); - assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Fine"]); - } - - #[test] - fn bad_moves_into_folders_fail_without_changes() { - let mut s = with_two_groups(); - // A chain 31 deep under Set/Deep. - let deep: Vec = std::iter::once("Deep".to_string()).chain((0..30).map(|i| format!("d{i}"))).collect(); - s.tools.presets.push(BrushPreset { - name: "Z".into(), - brush: Default::default(), - builtin: false, - group: "Set".into(), - folder: deep.clone(), - captures: Default::default(), - }); - s.tools.presets.push(BrushPreset { - name: "Y".into(), - brush: Default::default(), - builtin: false, - group: "Other".into(), - folder: vec!["Dry".into()], - captures: Default::default(), - }); - let before = s.tools.presets.clone(); - let deep_json = json!(deep); - for p in [ - // Into itself or its own descendant. - json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": ["Ink"]}}), - json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}}), - json!({"group": "Set", "into": {"group": "Set", "folder": ["Dry"]}}), - json!({"group": "Set", "into": {"group": "Set"}}), - // A group already at the top level; the ungrouped presets. - json!({"group": "Set", "into": {}}), - // A name clash at the destination. - json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other"}}), - json!({"group": "Other", "folder": ["Box"], "into": {"group": "Set", "folder": ["Ink"]}, "before": "Nope"}), - json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Set", "folder": ["Ink"]}, "index": 0}), - // Missing destinations and bad shapes. - json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Nope"}}), - json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other", "folder": ["Nope"]}}), - json!({"group": "Set", "folder": ["Dry"], "into": {"folder": ["Box"]}}), - json!({"group": "Set", "folder": ["Dry"], "into": "Other"}), - json!({"group": "Set", "folder": ["Dry"], "into": {"group": 5}}), - json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other"}, "before": 3}), - // Deeper than MAX_FOLDER_DEPTH once moved (Ink/Fine is 2 deep: 2 + 31 > 32). - json!({"group": "Set", "folder": ["Deep"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}}), - json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": deep_json}}), - ] { - assert!(s.execute("brush.presets.moveGroup", p.clone()).is_err(), "{p}"); - } - assert_eq!(s.tools.presets, before); - // Ink/Fine into Set itself: a clash with nothing, so it moves up a level. - s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "into": {"group": "Set"}})).unwrap(); - assert_eq!(folder_of(&s, "F1"), ["Fine"]); - // An ungrouped preset's group can't move. - s.tools.presets.push(BrushPreset { - name: "U".into(), - brush: Default::default(), - builtin: false, - group: String::new(), - folder: Vec::new(), - captures: Default::default(), - }); - assert!(s.execute("brush.presets.moveGroup", json!({"group": "", "into": {"group": "Set"}})).is_err()); - } -} +mod tests; diff --git a/crates/engine/src/brush_preset_cmds/tests.rs b/crates/engine/src/brush_preset_cmds/tests.rs new file mode 100644 index 0000000000..eeed131bc7 --- /dev/null +++ b/crates/engine/src/brush_preset_cmds/tests.rs @@ -0,0 +1,326 @@ +use super::*; + +fn names(s: &Session, g: &str) -> Vec { + s.tools.presets.iter().filter(|x| x.group == g).map(|x| x.name.clone()).collect() +} + +fn with_groups() -> Session { + let mut s = Session::new(); + for (n, g) in [("A1", "Alpha"), ("A2", "Alpha"), ("A3", "Alpha"), ("B1", "Beta"), ("B2", "Beta")] { + s.tools.presets.push(BrushPreset { + name: n.into(), + brush: Default::default(), + builtin: false, + group: g.into(), + folder: Vec::new(), + captures: Default::default(), + }); + } + s +} + +#[test] +fn move_within_and_between_groups() { + let mut s = with_groups(); + let r = s.execute("brush.presets.move", json!({"name": "A3", "before": "A1"})).unwrap(); + assert_eq!(r, json!({"name": "A3", "group": "Alpha", "folder": [], "index": 0})); + assert_eq!(names(&s, "Alpha"), ["A3", "A1", "A2"]); + s.execute("brush.presets.move", json!({"name": "A3", "index": 99})).unwrap(); + assert_eq!(names(&s, "Alpha"), ["A1", "A2", "A3"]); + s.execute("brush.presets.move", json!({"name": "A1", "index": 1})).unwrap(); + assert_eq!(names(&s, "Alpha"), ["A2", "A1", "A3"]); + // Into another group, before a member (the group comes from `before`). + s.execute("brush.presets.move", json!({"name": "A1", "before": "B2"})).unwrap(); + assert_eq!((names(&s, "Alpha"), names(&s, "Beta")), (vec!["A2".to_string(), "A3".into()], vec!["B1".to_string(), "A1".into(), "B2".into()])); + // Into a group by name (appended), and into a new group. + s.execute("brush.presets.move", json!({"name": "A2", "group": "Beta"})).unwrap(); + assert_eq!(names(&s, "Beta"), ["B1", "A1", "B2", "A2"]); + s.execute("brush.presets.move", json!({"name": "A3", "group": "Gamma"})).unwrap(); + assert_eq!(group_order(&s.tools.presets).last().map(String::as_str), Some("Gamma")); + assert!(names(&s, "Alpha").is_empty()); + // A built-in moved to another group becomes the user's. + let b = s.tools.presets.iter().find(|x| x.builtin).unwrap().name.clone(); + s.execute("brush.presets.move", json!({"name": b, "group": "Beta", "index": 0})).unwrap(); + let moved = photocraft_paint::presets::find(&s.tools.presets, &b).unwrap(); + assert!(!moved.builtin && moved.group == "Beta"); + assert_eq!(names(&s, "Beta")[0], b); +} + +#[test] +fn groups_move_rename_and_delete() { + let mut s = with_groups(); + let order = group_order(&s.tools.presets); + let n = order.len(); + assert_eq!(&order[n - 2..], ["Alpha", "Beta"]); + let r = s.execute("brush.presets.moveGroup", json!({"group": "Beta", "index": 0})).unwrap(); + assert_eq!(r["index"], 0); + assert_eq!(group_order(&s.tools.presets)[0], "Beta"); + assert_eq!(names(&s, "Beta"), ["B1", "B2"], "a group moves as a block, in order"); + s.execute("brush.presets.moveGroup", json!({"group": "Alpha", "before": "Beta"})).unwrap(); + assert_eq!(&group_order(&s.tools.presets)[..2], ["Alpha", "Beta"]); + s.execute("brush.presets.moveGroup", json!({"group": "Alpha"})).unwrap(); + assert_eq!(group_order(&s.tools.presets).last().map(String::as_str), Some("Alpha")); + s.execute("brush.presets.renameGroup", json!({"group": "Alpha", "newName": "First"})).unwrap(); + assert_eq!(names(&s, "First"), ["A1", "A2", "A3"]); + assert!(s.execute("brush.presets.renameGroup", json!({"group": "First", "newName": "Beta"})).is_err()); + let r = s.execute("brush.presets.deleteGroup", json!({"group": "First"})).unwrap(); + assert_eq!(r["deleted"], 3); + assert!(names(&s, "First").is_empty()); +} + +#[test] +fn rename_checks_names() { + let mut s = with_groups(); + s.execute("brush.presets.rename", json!({"name": "a1", "newName": "Alpha One"})).unwrap(); + assert!(photocraft_paint::presets::find(&s.tools.presets, "Alpha One").is_some()); + assert!(s.execute("brush.presets.rename", json!({"name": "A2", "newName": "alpha one"})).is_err()); + // Case-only renames of itself are fine. + s.execute("brush.presets.rename", json!({"name": "Alpha One", "newName": "ALPHA ONE"})).unwrap(); + let b = s.tools.presets.iter().find(|x| x.builtin).unwrap().name.clone(); + s.execute("brush.presets.rename", json!({"name": b, "newName": "My Round"})).unwrap(); + assert!(!photocraft_paint::presets::find(&s.tools.presets, "My Round").unwrap().builtin); +} + +#[test] +fn bad_params_fail_without_changes() { + let mut s = with_groups(); + let before = s.tools.presets.clone(); + let long = "x".repeat(MAX_NAME + 1); + for (id, p) in [ + ("brush.presets.move", json!({})), + ("brush.presets.move", json!({"name": "Nope"})), + ("brush.presets.move", json!({"name": "A1", "before": "A1"})), + ("brush.presets.move", json!({"name": "A1", "before": "Nope"})), + ("brush.presets.move", json!({"name": "A1", "group": "Alpha", "before": "B1"})), + ("brush.presets.move", json!({"name": "A1", "index": -1})), + ("brush.presets.move", json!({"name": "A1", "index": "first"})), + ("brush.presets.move", json!({"name": "A1", "group": 7})), + ("brush.presets.move", json!({"name": "A1", "group": long})), + ("brush.presets.rename", json!({"name": "A1"})), + ("brush.presets.rename", json!({"name": "A1", "newName": " "})), + ("brush.presets.rename", json!({"name": "A1", "newName": long})), + ("brush.presets.moveGroup", json!({"group": "Nope"})), + ("brush.presets.moveGroup", json!({"group": "Alpha", "before": "Alpha"})), + ("brush.presets.moveGroup", json!({"group": "Alpha", "index": 1.5})), + ("brush.presets.renameGroup", json!({"group": "Alpha"})), + ("brush.presets.deleteGroup", json!({"group": null})), + ("brush.presets.deleteGroup", json!({"group": "Nope"})), + ] { + assert!(s.execute(id, p.clone()).is_err(), "{id} {p}"); + } + assert_eq!(s.tools.presets, before); + // Huge indices clamp to the end. + s.execute("brush.presets.move", json!({"name": "A1", "index": u64::MAX})).unwrap(); + s.execute("brush.presets.moveGroup", json!({"group": "Alpha", "index": u64::MAX})).unwrap(); +} + +/// Group "Set": S0 at its top level, folders Ink (I1, I2; subfolder Fine: F1) and Dry (D1). +fn with_folders() -> Session { + let mut s = Session::new(); + for (n, f) in [("S0", &[][..]), ("I1", &["Ink"][..]), ("F1", &["Ink", "Fine"][..]), ("I2", &["Ink"][..]), ("D1", &["Dry"][..])] { + let folder = f.iter().map(|x| x.to_string()).collect(); + s.tools.presets.push(BrushPreset { + name: n.into(), + brush: Default::default(), + builtin: false, + group: "Set".into(), + folder, + captures: Default::default(), + }); + } + s +} + +fn folder_of(s: &Session, n: &str) -> Vec { + photocraft_paint::presets::find(&s.tools.presets, n).unwrap().folder.clone() +} + +#[test] +fn presets_move_between_folders() { + let mut s = with_folders(); + // `before` brings its folder. + let r = s.execute("brush.presets.move", json!({"name": "D1", "before": "I2"})).unwrap(); + assert_eq!(r["folder"], json!(["Ink"])); + assert_eq!(folder_of(&s, "D1"), ["Ink"]); + // An explicit folder, appended at the end of it. + s.execute("brush.presets.move", json!({"name": "S0", "folder": ["Ink", "Fine"]})).unwrap(); + assert_eq!(folder_of(&s, "S0"), ["Ink", "Fine"]); + let pos = |n: &str| s.tools.presets.iter().position(|x| x.name == n).unwrap(); + assert_eq!(pos("S0"), pos("F1") + 1); + // Within its group without a folder keeps its folder; to another group without one lands + // at that group's top level; `folder: []` is the group's top level. + s.execute("brush.presets.move", json!({"name": "S0", "index": 0})).unwrap(); + assert_eq!(folder_of(&s, "S0"), ["Ink", "Fine"]); + s.execute("brush.presets.move", json!({"name": "S0", "group": "Other"})).unwrap(); + assert!(folder_of(&s, "S0").is_empty()); + s.execute("brush.presets.move", json!({"name": "I1", "folder": []})).unwrap(); + assert!(folder_of(&s, "I1").is_empty()); + // `before` in another folder than the one named. + assert!(s.execute("brush.presets.move", json!({"name": "I1", "folder": ["Dry"], "before": "I2"})).is_err()); + assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Ink"]); +} + +#[test] +fn folders_move_rename_and_delete() { + let mut s = with_folders(); + assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Ink", "Dry"]); + // Move Dry before Ink: the whole folder moves as a block. + let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"], "before": "Ink"})).unwrap(); + assert_eq!(r, json!({"group": "Set", "folder": ["Dry"], "index": 0})); + assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Dry", "Ink"]); + s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"]})).unwrap(); + assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Ink", "Dry"]); + s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"], "index": 0})).unwrap(); + assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Dry", "Ink"]); + let ink: Vec<&str> = s.tools.presets.iter().filter(|x| x.folder.first().is_some_and(|f| f == "Ink")).map(|x| x.name.as_str()).collect(); + assert_eq!(ink, ["I1", "F1", "I2"], "presets keep their order inside a moved folder"); + // Rename a nested folder: every preset below it follows. + let r = s.execute("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Ink"], "newName": "Inks"})).unwrap(); + assert_eq!(r["folder"], json!(["Inks"])); + assert_eq!(folder_of(&s, "F1"), ["Inks", "Fine"]); + assert!(s.execute("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Inks"], "newName": "Dry"})).is_err()); + // Renaming the group keeps the folders. + s.execute("brush.presets.renameGroup", json!({"group": "Set", "newName": "Kit"})).unwrap(); + assert_eq!(folder_of(&s, "F1"), ["Inks", "Fine"]); + // Delete a nested folder: only the presets in it (and below) go. + let r = s.execute("brush.presets.deleteGroup", json!({"group": "Kit", "folder": ["Inks"]})).unwrap(); + assert_eq!(r["deleted"], 3); + assert!(photocraft_paint::presets::find(&s.tools.presets, "S0").is_some()); + assert!(photocraft_paint::presets::find(&s.tools.presets, "D1").is_some()); +} + +#[test] +fn bad_folder_params_fail_without_changes() { + let mut s = with_folders(); + let before = s.tools.presets.clone(); + let long = "x".repeat(MAX_NAME + 1); + let deep: Vec<&str> = vec!["a"; MAX_FOLDER_DEPTH + 1]; + for (id, p) in [ + ("brush.presets.move", json!({"name": "S0", "folder": "Ink"})), + ("brush.presets.move", json!({"name": "S0", "folder": [""]})), + ("brush.presets.move", json!({"name": "S0", "folder": [7]})), + ("brush.presets.move", json!({"name": "S0", "folder": [long]})), + ("brush.presets.move", json!({"name": "S0", "folder": deep})), + ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Nope"]})), + ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "before": "Ink"})), + ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "before": "Nope"})), + ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "before": 3})), + ("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "index": -2})), + ("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Ink"], "newName": ""})), + ("brush.presets.renameGroup", json!({"group": "Set", "folder": ["Ink", "Nope"], "newName": "x"})), + ("brush.presets.deleteGroup", json!({"group": "Set", "folder": ["Dry", "Nope"]})), + ("brush.presets.deleteGroup", json!({"group": "Nope", "folder": ["Dry"]})), + ] { + assert!(s.execute(id, p.clone()).is_err(), "{id} {p}"); + } + assert_eq!(s.tools.presets, before); + s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "index": u64::MAX})).unwrap(); +} + +fn paths(s: &Session) -> Vec { + s.tools.presets.iter().filter(|x| !x.builtin).map(|x| format!("{}:{}:{}", x.group, x.folder.join("/"), x.name)).collect() +} + +/// `with_folders` plus group "Other" holding O1, and folder Box (B1) in it. +fn with_two_groups() -> Session { + let mut s = with_folders(); + for (n, f) in [("O1", &[][..]), ("B1", &["Box"][..])] { + let folder = f.iter().map(|x| x.to_string()).collect(); + s.tools.presets.push(BrushPreset { + name: n.into(), + brush: Default::default(), + builtin: false, + group: "Other".into(), + folder, + captures: Default::default(), + }); + } + s +} + +#[test] +fn folders_move_into_folders_and_groups() { + let mut s = with_two_groups(); + // A nested folder into a sibling folder: its subtree follows, order kept. + let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}})).unwrap(); + assert_eq!(r, json!({"group": "Set", "folder": ["Ink", "Fine", "Dry"], "index": 0})); + assert_eq!(folder_of(&s, "D1"), ["Ink", "Fine", "Dry"]); + // Into another group, before one of its folders. + let r = s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Other"}, "before": "Box"})).unwrap(); + assert_eq!(r["folder"], json!(["Ink"])); + assert_eq!(paths(&s), ["Set::S0", "Other::O1", "Other:Ink:I1", "Other:Ink/Fine:F1", "Other:Ink/Fine/Dry:D1", "Other:Ink:I2", "Other:Box:B1"]); + // Out to the top level: the folder becomes a group of its own. + let r = s.execute("brush.presets.moveGroup", json!({"group": "Other", "folder": ["Ink", "Fine"], "into": {}})).unwrap(); + assert_eq!(r["group"], "Fine"); + assert_eq!(folder_of(&s, "D1"), ["Dry"]); + assert_eq!(photocraft_paint::presets::find(&s.tools.presets, "F1").unwrap().group, "Fine"); + // A whole group into another group's folder. + s.execute("brush.presets.moveGroup", json!({"group": "Fine", "into": {"group": "Set"}})).unwrap(); + assert!(names(&s, "Fine").is_empty()); + assert_eq!(folder_of(&s, "D1"), ["Fine", "Dry"]); + assert_eq!(subfolder_order(&s.tools.presets, "Set", &[]), ["Fine"]); +} + +#[test] +fn bad_moves_into_folders_fail_without_changes() { + let mut s = with_two_groups(); + // A chain 31 deep under Set/Deep. + let deep: Vec = std::iter::once("Deep".to_string()).chain((0..30).map(|i| format!("d{i}"))).collect(); + s.tools.presets.push(BrushPreset { + name: "Z".into(), + brush: Default::default(), + builtin: false, + group: "Set".into(), + folder: deep.clone(), + captures: Default::default(), + }); + s.tools.presets.push(BrushPreset { + name: "Y".into(), + brush: Default::default(), + builtin: false, + group: "Other".into(), + folder: vec!["Dry".into()], + captures: Default::default(), + }); + let before = s.tools.presets.clone(); + let deep_json = json!(deep); + for p in [ + // Into itself or its own descendant. + json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": ["Ink"]}}), + json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}}), + json!({"group": "Set", "into": {"group": "Set", "folder": ["Dry"]}}), + json!({"group": "Set", "into": {"group": "Set"}}), + // A group already at the top level; the ungrouped presets. + json!({"group": "Set", "into": {}}), + // A name clash at the destination. + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other"}}), + json!({"group": "Other", "folder": ["Box"], "into": {"group": "Set", "folder": ["Ink"]}, "before": "Nope"}), + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Set", "folder": ["Ink"]}, "index": 0}), + // Missing destinations and bad shapes. + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Nope"}}), + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other", "folder": ["Nope"]}}), + json!({"group": "Set", "folder": ["Dry"], "into": {"folder": ["Box"]}}), + json!({"group": "Set", "folder": ["Dry"], "into": "Other"}), + json!({"group": "Set", "folder": ["Dry"], "into": {"group": 5}}), + json!({"group": "Set", "folder": ["Dry"], "into": {"group": "Other"}, "before": 3}), + // Deeper than MAX_FOLDER_DEPTH once moved (Ink/Fine is 2 deep: 2 + 31 > 32). + json!({"group": "Set", "folder": ["Deep"], "into": {"group": "Set", "folder": ["Ink", "Fine"]}}), + json!({"group": "Set", "folder": ["Ink"], "into": {"group": "Set", "folder": deep_json}}), + ] { + assert!(s.execute("brush.presets.moveGroup", p.clone()).is_err(), "{p}"); + } + assert_eq!(s.tools.presets, before); + // Ink/Fine into Set itself: a clash with nothing, so it moves up a level. + s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "into": {"group": "Set"}})).unwrap(); + assert_eq!(folder_of(&s, "F1"), ["Fine"]); + // An ungrouped preset's group can't move. + s.tools.presets.push(BrushPreset { + name: "U".into(), + brush: Default::default(), + builtin: false, + group: String::new(), + folder: Vec::new(), + captures: Default::default(), + }); + assert!(s.execute("brush.presets.moveGroup", json!({"group": "", "into": {"group": "Set"}})).is_err()); +} From c58e8a6fe28b9134a6e7b5cc926dd1e5a28f96cb Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:11 +0000 Subject: [PATCH 030/259] refactor(engine): move adjust_params.rs tests to adjust_params/tests.rs --- crates/engine/src/adjust_params.rs | 663 +---------------------- crates/engine/src/adjust_params/tests.rs | 660 ++++++++++++++++++++++ 2 files changed, 661 insertions(+), 662 deletions(-) create mode 100644 crates/engine/src/adjust_params/tests.rs diff --git a/crates/engine/src/adjust_params.rs b/crates/engine/src/adjust_params.rs index 69fc2d76f3..1361dbef5e 100644 --- a/crates/engine/src/adjust_params.rs +++ b/crates/engine/src/adjust_params.rs @@ -1081,665 +1081,4 @@ pub fn user_keys(p: &Value) -> Map { } #[cfg(test)] -mod tests { - use super::*; - - const KINDS: [&str; 15] = [ - "invert", - "brightnessContrast", - "threshold", - "posterize", - "exposure", - "vibrance", - "hueSaturation", - "levels", - "curves", - "colorBalance", - "blackWhite", - "photoFilter", - "channelMixer", - "gradientMap", - "selectiveColor", - ]; - - /// A non-default parameter set per kind (RGB channel keys for Levels/Curves). - pub(crate) fn sample(kind: &str) -> Value { - match kind { - "brightnessContrast" => json!({"brightness": 20, "contrast": -10, "legacy": true}), - "threshold" => json!({"level": 100}), - "posterize" => json!({"levels": 7}), - "exposure" => json!({"exposure": 1.5, "offset": 0.1, "gamma": 1.4}), - "vibrance" => json!({"vibrance": 30, "saturation": -20}), - "hueSaturation" => { - json!({"hue": 25, "saturation": -20, "lightness": 10, "reds": {"hue": 10, "saturation": -30, "lightness": 5, "range": [300, 340, 20, 50]}}) - } - "levels" => json!({"inBlack": 10, "inWhite": 240, "outBlack": 5, "outWhite": 250, "gamma": 1.2, "red": {"inBlack": 3, "gamma": 0.8}}), - "curves" => json!({"points": [[0, 0], [128, 150], [255, 255]], "blue": [[0, 20], [255, 235]]}), - "colorBalance" => json!({"shadows": [10, -5, 0], "midtones": [0, 20, -30], "highlights": [5, 5, 5], "preserveLuminosity": false}), - "blackWhite" => json!({"reds": 120, "blues": -40, "tint": true, "tintColor": "#d0a070"}), - "photoFilter" => json!({"color": "#3366cc", "density": 40, "preserveLuminosity": false}), - "channelMixer" => json!({"red": [80, 30, -10, 5], "blue": [0, 10, 90, 0]}), - "gradientMap" => json!({"stops": [[0, "#000000"], [0.5, "#ff0000"], [1, [1, 1, 1]]], "reverse": true, "dither": true}), - "selectiveColor" => json!({"method": "absolute", "reds": [10, 0, -20, 5]}), - _ => json!({}), - } - } - - #[test] - fn every_kind_round_trips_through_params() { - for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Grayscale] { - for kind in KINDS { - let mut p = sample(kind); - if matches!(kind, "levels" | "curves") && default_space(mode) != ToneSpace::Rgb { - // Off RGB the channel keys are the document's. - p.as_object_mut().unwrap().retain(|k, _| !matches!(k.as_str(), "red" | "blue")); - } - let a = from_params(kind, &p, None, mode).unwrap_or_else(|e| panic!("{kind} {mode:?}: {e}")); - assert_ne!(Some(&a), default_for(kind, mode).ok().as_ref().filter(|_| kind != "invert"), "{kind} params ignored"); - let back = from_params(kind, &to_params(&a), None, mode).unwrap(); - assert_eq!(to_params(&back), to_params(&a), "{kind} {mode:?}"); - // A partial update keeps everything it doesn't name. - let again = from_params(kind, &json!({}), Some(&a), mode).unwrap(); - assert_eq!(again, a, "{kind} {mode:?}"); - } - } - } - - #[test] - fn params_reach_the_model() { - let a = from_params("colorBalance", &json!({"midtones": [50, 0, -200]}), None, ColorMode::Rgb).unwrap(); - assert_eq!(a, Adjustment::ColorBalance { shadows: [0.0; 3], midtones: [50.0, 0.0, -100.0], highlights: [0.0; 3], preserve_luminosity: true }); - let a = from_params("channelMixer", &json!({"monochrome": true}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::ChannelMixer { matrix, monochrome: true } if matrix[0] == [0.4, 0.4, 0.2, 0.0])); - let a = from_params("photoFilter", &json!({"filter": "cooling80", "density": 60}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::PhotoFilter { color, density, .. } if color[2] == 1.0 && (density - 0.6).abs() < 1e-6)); - let a = from_params("blackWhite", &json!({"reds": 120, "tint": true}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::BlackWhite { weights, tint: Some(_) } if weights[0] == 120.0 && weights[1] == 60.0)); - let a = from_params("hueSaturation", &json!({"blues": {"hue": 40}}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(&a, Adjustment::HueSaturation { ranges, .. } if ranges[4].hue == 40.0 && ranges[0].is_neutral())); - // Colorize without a saturation starts at 25%; an explicit 0 and an already colorized base are kept. - let a = from_params("hueSaturation", &json!({"colorize": true, "hue": 30}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::HueSaturation { colorize: true, saturation: 25.0, .. }), "{a:?}"); - let a = from_params("hueSaturation", &json!({"colorize": true, "saturation": 0}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::HueSaturation { colorize: true, saturation: 0.0, .. }), "{a:?}"); - let a = from_params("hueSaturation", &json!({"hue": 120}), Some(&a), ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::HueSaturation { colorize: true, saturation: 0.0, hue: 120.0, .. }), "{a:?}"); - let a = from_params("gradientMap", &json!({"stops": [[1, "#ffffff"], [0, "#000000"]], "dither": true}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(&a, Adjustment::GradientMap { stops, dither: true, .. } if stops[0].0 == 0.0)); - // CMYK curves: ink channels; Lab: lightness without a composite. - let a = from_params("curves", &json!({"black": [[0, 0], [255, 200]]}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(&a, Adjustment::Curves { space: ToneSpace::Cmyk, black, .. } if black.len() == 2)); - let a = from_params("curves", &json!({"points": [[0, 40], [255, 255]]}), None, ColorMode::Lab).unwrap(); - assert!(matches!(&a, Adjustment::Curves { space: ToneSpace::Lab, per_channel, .. } if per_channel[0][0].output > 0.1)); - let a = from_params("levels", &json!({"inBlack": 20}), None, ColorMode::Cmyk).unwrap(); - assert!(matches!(&a, Adjustment::Levels { space: ToneSpace::Cmyk, master, .. } if (master.in_black - 20.0 / 255.0).abs() < 1e-6)); - } - - #[test] - fn bad_params_are_errors_not_panics() { - for (kind, p) in [ - ("curves", json!({"points": "abc"})), - ("curves", json!({"points": [[0, 0]]})), - ("curves", json!({"red": [[0, 0], [1]]})), - ("curves", json!({"points": [[5, 5], [5, 9]]})), - ("curves", json!({"pencil": true, "points": [1, 2, 3]})), - ("curves", json!({"pencil": "yes"})), - ("curves", json!({"points": (0..256).map(|k| if k == 9 { json!("x") } else { json!(k) }).collect::>()})), - ("levels", json!({"red": 3})), - ("levels", json!({"inBlack": "x"})), - ("hueSaturation", json!({"reds": {"range": [1, 2]}})), - ("hueSaturation", json!({"colorize": 1})), - ("colorBalance", json!({"shadows": [1, 2]})), - ("blackWhite", json!({"tintColor": "#zz0000"})), - ("photoFilter", json!({"filter": "nope"})), - ("photoFilter", json!({"color": [1]})), - ("channelMixer", json!({"red": [1, 2, 3]})), - ("gradientMap", json!({"stops": [[0, "#000"]]})), - ("gradientMap", json!({"stops": 7})), - ("selectiveColor", json!({"method": 5})), - ("selectiveColor", json!({"reds": "not-an-array"})), - ("selectiveColor", json!({"colors": "reds", "cyan": "50"})), - ("colorLookup", json!({"lut": 42})), - ("colorLookup", json!({"interpolation": 5})), - ("colorLookup", json!({"dither": "yes"})), - ("nope", json!({})), - ("levels", json!([1, 2])), - ] { - assert!(from_params(kind, &p, None, ColorMode::Rgb).is_err(), "{kind} {p}"); - } - // Out-of-range numbers clamp. - let a = from_params("hueSaturation", &json!({"hue": 1e9, "saturation": -1e9}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::HueSaturation { hue: 180.0, saturation: -100.0, .. })); - let a = from_params("levels", &json!({"inBlack": 250, "inWhite": 10}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(a, Adjustment::Levels { master, .. } if master.in_white > master.in_black)); - } - - #[test] - fn curve_points_outside_0_255_are_refused_as_the_message_says() { - // Photoshop refuses them too ("the settings in the file are invalid"); they used to be - // moved onto the edge silently. - for pts in [json!([[0, 0], [300, 255]]), json!([[0, -1], [255, 255]]), json!([[0, 0]])] { - let e = from_params("curves", &json!({ "points": pts }), None, ColorMode::Rgb).unwrap_err().to_string(); - assert!(e.contains("[input, output] pairs in 0..255") && e.contains("`curves adjustment`"), "{e}"); - } - assert!(from_params("curves", &json!({"points": [[0, 0], [128.5, 140], [255, 255]]}), None, ColorMode::Rgb).is_ok()); - } - - fn curves_parts(a: &Adjustment) -> (&[CurvePoint], &[Vec; 3]) { - match a { - Adjustment::Curves { master, per_channel, .. } => (master, per_channel), - _ => panic!("expected curves"), - } - } - - fn tone_output(adjustment: &Adjustment, sample: [f32; 3]) -> [f32; 3] { - let luts = photocraft_compose::adjust::tone_luts(adjustment); - std::array::from_fn(|channel| { - let row = &luts[channel]; - let position = sample[channel].clamp(0.0, 1.0) * (row.len().saturating_sub(1)) as f32; - let lower = position.floor() as usize; - let upper = lower.saturating_add(1).min(row.len().saturating_sub(1)); - let fraction = position - lower as f32; - row.get(lower).copied().unwrap_or(0.0) * (1.0 - fraction) + row.get(upper).copied().unwrap_or(0.0) * fraction - }) - } - - #[test] - fn curves_black_and_white_eyedroppers_move_the_input_references() { - let base = json!({ - "points": [[0, 8], [120, 150], [255, 245]], - "red": [[0, 0], [100, 130], [255, 255]], - "green": [[0, 0], [110, 125], [255, 255]], - "blue": [[0, 0], [90, 120], [255, 255]] - }); - let black = curves_eyedropper(&base, CurvesEyedropper::Black, [0.2, 0.3, 0.4], ColorMode::Rgb).unwrap(); - let (master, channels) = curves_parts(&black); - for (curve, sample) in channels.iter().zip([0.2, 0.3, 0.4]) { - assert!((curve[0].input - sample).abs() < 1e-6 && curve[0].output == 0.0, "{curve:?}"); - assert_eq!(curve.len(), 3, "existing edit points are preserved"); - } - assert_eq!(master[0].output, 0.0, "the composite cannot lift the sampled black"); - assert!(tone_output(&black, [0.2, 0.3, 0.4]).iter().all(|value| *value < 1e-3)); - - let white = curves_eyedropper(&base, CurvesEyedropper::White, [0.6, 0.7, 0.8], ColorMode::Rgb).unwrap(); - let (master, channels) = curves_parts(&white); - for (curve, sample) in channels.iter().zip([0.6, 0.7, 0.8]) { - let end = curve.last().unwrap(); - assert!((end.input - sample).abs() < 1e-6 && end.output == 1.0, "{curve:?}"); - assert_eq!(curve.len(), 3, "existing edit points are preserved"); - } - assert_eq!(master.last().map(|p| p.output), Some(1.0), "the composite cannot lower the sampled white"); - assert!(tone_output(&white, [0.6, 0.7, 0.8]).iter().all(|value| *value > 1.0 - 1e-3)); - - let edge_black = curves_eyedropper(&base, CurvesEyedropper::Black, [1.0, 0.3, 0.4], ColorMode::Rgb).unwrap(); - let (_, edge_channels) = curves_parts(&edge_black); - assert_eq!(edge_channels[0].len(), 3, "edge samples preserve other curve points"); - assert_eq!(edge_channels[0].last().map(|p| p.output), Some(0.0)); - let edge_white = curves_eyedropper(&base, CurvesEyedropper::White, [0.0, 0.7, 0.8], ColorMode::Rgb).unwrap(); - let (_, edge_channels) = curves_parts(&edge_white); - assert_eq!(edge_channels[0].len(), 3, "edge samples preserve other curve points"); - assert_eq!(edge_channels[0].first().map(|p| p.output), Some(1.0)); - } - - #[test] - fn black_and_white_eyedroppers_round_trip_near_serialization_boundaries() { - let cases = [ - (CurvesEyedropper::White, 0.0, 1.0), - (CurvesEyedropper::White, 0.001, 1.0), - (CurvesEyedropper::White, 0.494 / 255.0, 1.0), - // 0.496 level rounds to 0.50; the sample is just below that representable point. - (CurvesEyedropper::White, 0.496 / 255.0, 0.992), - (CurvesEyedropper::White, 0.2, 1.0), - (CurvesEyedropper::Black, 1.0, 0.0), - (CurvesEyedropper::Black, 0.999, 0.0), - (CurvesEyedropper::Black, 1.0 - 0.494 / 255.0, 0.0), - // 254.504 levels rounds to 254.50, leaving a representable 0.50-level gap. - (CurvesEyedropper::Black, 1.0 - 0.496 / 255.0, 0.008), - (CurvesEyedropper::Black, 0.8, 0.0), - ]; - for (picker, sample, expected_output) in cases { - let resolved = curves_eyedropper(&json!({}), picker, [sample; 3], ColorMode::Rgb).unwrap(); - let params = to_params(&resolved); - let parsed = from_params("curves", ¶ms, None, ColorMode::Rgb).unwrap(); - let (master, channels) = curves_parts(&parsed); - for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) { - assert!(curve.len() >= 2, "{picker:?} sample={sample}: {curve:?}"); - assert!(curve.len() <= MAX_CURVE_POINTS, "{picker:?} sample={sample}: {curve:?}"); - assert!(curve.windows(2).all(|pair| pair[0].input < pair[1].input), "{picker:?} sample={sample}: {curve:?}"); - assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{picker:?} sample={sample}: {curve:?}"); - } - let output = tone_output(&parsed, [sample; 3]); - assert!( - output.iter().all(|value| (*value - expected_output).abs() < 1e-3), - "{picker:?} sample={sample} output={output:?} expected={expected_output}" - ); - } - } - - #[test] - fn endpoint_eyedroppers_fall_back_when_serialization_collapses_curve_points() { - let base = json!({ - "points": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]], - "red": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]], - "green": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]], - "blue": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]] - }); - let cases = [(CurvesEyedropper::Black, 0.995, 0.0, true), (CurvesEyedropper::White, 0.005, 1.0, false)]; - for (picker, sample, target, black) in cases { - let resolved = curves_eyedropper(&base, picker, [sample; 3], ColorMode::Rgb).unwrap(); - let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); - let (master, channels) = curves_parts(&parsed); - for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) { - assert_eq!(curve.len(), 5, "collapsed points use the deterministic fallback: {curve:?}"); - for (point, input) in curve.iter().zip([0.0, 64.0, 128.0, 192.0, 255.0]) { - assert!((point.input * 255.0 - input).abs() < 1e-3, "existing point position was retained: {curve:?}"); - } - } - for curve in channels { - let plateau: Vec<_> = if black { curve.iter().rev().take(2).collect() } else { curve.iter().take(2).collect() }; - assert!(plateau.into_iter().all(|point| (point.output - target).abs() < 1e-6), "{curve:?}"); - } - let output = tone_output(&parsed, [sample; 3]); - assert!(output.iter().all(|value| (*value - target).abs() < 0.01), "{picker:?}: {output:?}"); - } - } - - #[test] - fn black_and_white_round_trips_preserve_representable_curve_edits() { - let base = json!({ - "points": [[0, 8], [120, 150], [255, 245]], - "red": [[0, 0], [100, 130], [255, 255]], - "green": [[0, 0], [110, 125], [255, 255]], - "blue": [[0, 0], [90, 120], [255, 255]] - }); - let black = curves_eyedropper(&base, CurvesEyedropper::Black, [0.2, 0.3, 0.4], ColorMode::Rgb).unwrap(); - let black = from_params("curves", &to_params(&black), None, ColorMode::Rgb).unwrap(); - let (_, channels) = curves_parts(&black); - assert_eq!(channels[0].len(), 3); - assert!((channels[0][1].input * 255.0 - 131.0).abs() < 1e-3); - assert!((channels[0][1].output * 255.0 - 130.0).abs() < 1e-3); - - let white = curves_eyedropper(&base, CurvesEyedropper::White, [0.6, 0.7, 0.8], ColorMode::Rgb).unwrap(); - let white = from_params("curves", &to_params(&white), None, ColorMode::Rgb).unwrap(); - let (_, channels) = curves_parts(&white); - assert_eq!(channels[0].len(), 3); - assert!((channels[0][1].input * 255.0 - 60.0).abs() < 1e-3); - assert!((channels[0][1].output * 255.0 - 130.0).abs() < 1e-3); - } - - fn assert_gray_point_preserves_luma_and_existing_curve_edits(sample: [f32; 3]) { - let base = json!({ - "points": [[0, 0], [128, 96], [255, 255]], - "red": [[0, 0], [80, 90], [255, 255]], - "green": [[0, 0], [90, 100], [255, 255]], - "blue": [[0, 0], [70, 80], [255, 255]] - }); - let original = from_params("curves", &base, None, ColorMode::Rgb).unwrap(); - let expected_luma = rgb_luma(sample); - let resolved = curves_eyedropper(&base, CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap(); - let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); - let (master, channels) = curves_parts(&parsed); - let (original_master, original_channels) = curves_parts(&original); - assert_eq!(master, original_master, "the existing master curve is retained"); - for (curve, old_curve) in channels.iter().zip(original_channels) { - let old_edit = old_curve.get(1).expect("the test curve has an interior edit"); - assert!( - curve.iter().any(|point| { (point.input - old_edit.input).abs() < 1e-6 && (point.output - old_edit.output).abs() < 1e-6 }), - "the existing channel edit is retained: {curve:?}" - ); - } - let output = tone_output(&parsed, sample); - assert!((output[0] - output[1]).abs() < 0.002 && (output[1] - output[2]).abs() < 0.002, "sample must become neutral: {output:?}"); - assert!((rgb_luma(output) - expected_luma).abs() < 0.003, "luma changed from {expected_luma} to {} ({output:?})", rgb_luma(output)); - } - - #[test] - fn curves_neutral_gray_preserves_luma_for_a_light_cast_sample() { - assert_gray_point_preserves_luma_and_existing_curve_edits([0.88, 0.76, 0.63]); - } - - #[test] - fn curves_neutral_gray_preserves_luma_for_a_dark_cast_sample() { - assert_gray_point_preserves_luma_and_existing_curve_edits([0.17, 0.105, 0.075]); - } - - #[test] - fn curves_neutral_gray_handles_near_black_and_near_white_samples() { - for sample in [[0.004, 0.006, 0.008], [0.992, 0.996, 0.999], [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]] { - let resolved = curves_eyedropper(&json!({}), CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap(); - let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); - let (master, channels) = curves_parts(&parsed); - for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) { - assert!(curve.len() >= 2, "{sample:?}: {curve:?}"); - assert!(curve.windows(2).all(|pair| pair[0].input < pair[1].input), "{sample:?}: {curve:?}"); - assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{sample:?}: {curve:?}"); - } - let output = tone_output(&parsed, sample); - assert!((output[0] - output[1]).abs() < 0.002 && (output[1] - output[2]).abs() < 0.002, "{sample:?}: {output:?}"); - assert!((rgb_luma(output) - rgb_luma(sample)).abs() < 0.003, "{sample:?}: {output:?}"); - } - } - - #[test] - fn gray_point_fallback_keeps_tightly_spaced_points_round_trip_safe() { - let base = json!({ - "red": [[0, 0], [100, 100], [100.51, 100], [255, 255]], - "green": [[0, 0], [100, 100], [100.51, 100], [255, 255]], - "blue": [[0, 0], [100, 100], [100.51, 100], [255, 255]] - }); - let sample = [100.25 / 255.0, 100.1 / 255.0, 100.4 / 255.0]; - let target = rgb_luma(sample); - let resolved = curves_eyedropper(&base, CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap(); - let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); - let (_, channels) = curves_parts(&parsed); - for (curve, input) in channels.iter().zip(sample) { - assert_eq!(curve.len(), 4, "the fallback keeps every serialized point: {curve:?}"); - assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{curve:?}"); - let sample_pair = curve.windows(2).find(|pair| pair[0].input <= input && input <= pair[1].input).unwrap(); - assert!((sample_pair[0].output - sample_pair[1].output).abs() < 1e-6, "fallback forms a plateau around the sample: {curve:?}"); - assert!((sample_pair[0].output - target).abs() < 0.001, "fallback uses the luma target: {curve:?}"); - } - } - - #[test] - fn curves_eyedropper_param_drives_the_command() { - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); - s.execute("image.adjustments.curves", json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap(); - let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); - assert!(px.iter().take(3).all(|v| *v > 0.99), "the sample becomes white: {px:?}"); - s.execute("image.adjustments.curves", json!({"eyedropper": {"point": "black", "color": [1.0, 1.0, 1.0]}})).unwrap(); - let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); - assert!(px.iter().take(3).all(|v| *v < 0.01), "the given colour becomes black: {px:?}"); - for bad in [ - json!("black"), - json!({"point": "nope", "at": [1, 1]}), - json!({"point": "black"}), - json!({"point": "black", "at": [99, 1]}), - json!({"point": "black", "at": [-1, 1]}), - json!({"point": "black", "at": [1]}), - json!({"point": "gray", "at": [f64::MAX, 1]}), - json!({"point": "black", "color": "red"}), - ] { - assert!(s.execute("image.adjustments.curves", json!({"eyedropper": bad})).is_err(), "{bad}"); - } - } - - /// The Properties panel's pickers on a Curves adjustment layer (UI-217-15): one undoable step - /// that samples the image below the layer, so a repeated click keeps the same curve. - #[test] - fn layer_eyedropper_samples_below_the_curves_layer() { - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); - s.execute("layer.newAdjustmentLayer.curves", json!({})).unwrap(); - let steps = s.active().unwrap().history.past_len(); - let pick = json!({"eyedropper": {"point": "white", "at": [2, 2], "size": 3}}); - s.execute("layer.setAdjustment", pick.clone()).unwrap(); - assert_eq!(s.active().unwrap().history.past_len(), steps + 1); - let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); - assert!(px.iter().take(3).all(|v| *v > 0.99), "the sample becomes white: {px:?}"); - let curve = s.active().unwrap().doc.clone(); - s.execute("layer.setAdjustment", pick).unwrap(); - let same = |a: &photocraft_doc::Document, b: &photocraft_doc::Document| a.layers.last().map(|l| &l.content) == b.layers.last().map(|l| &l.content); - assert!(same(&curve, &s.active().unwrap().doc), "sampled below the layer, not through it"); - s.execute("edit.undo", json!({})).unwrap(); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(s.active().unwrap().history.past_len(), steps); - for bad in [json!({"point": "black", "at": [99, 1]}), json!({"point": "black", "at": [1, 1], "size": 2}), json!({"point": "x", "at": [1, 1]})] { - assert!(s.execute("layer.setAdjustment", json!({"eyedropper": bad})).is_err(), "{bad}"); - } - s.execute("layer.newAdjustmentLayer.hueSaturation", json!({})).unwrap(); - assert!(s.execute("layer.setAdjustment", json!({"eyedropper": {"point": "white", "at": [1, 1]}})).is_err(), "Levels and Curves only"); - } - - /// #3127: on a smart object the eyedropper param records the adjustment it resolved to as - /// the smart filter, not the raw sample (which re-rendered as an identity). - #[test] - fn eyedropper_on_a_smart_object_records_the_resolved_adjustment() { - for kind in ["curves", "levels"] { - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute(&format!("image.adjustments.{kind}"), json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap(); - let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); - assert!(px.iter().take(3).all(|v| *v > 0.99), "{kind}: {px:?}"); - } - } - - /// Levels' Set White/Neutral Gray Point (#3116): the white point maps the sampled colour to - /// white at 8 and 16 bit, the gray point neutralises a tinted grey at its luma on a Levels - /// layer as one undoable step, and bad picks fail. - #[test] - fn levels_eyedroppers_set_white_and_neutral_gray() { - let pixel = |s: &mut crate::Session| -> Vec { serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap() }; - for depth in [8, 16] { - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); - s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); - s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap(); - let px = pixel(&mut s); - assert!(px.iter().take(3).all(|v| *v > 0.995), "{depth}-bit: the sample becomes white: {px:?}"); - } - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); - let before = pixel(&mut s); - s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); - let steps = s.active().unwrap().history.past_len(); - s.execute("layer.setAdjustment", json!({"eyedropper": {"point": "gray", "at": [2, 2]}})).unwrap(); - assert_eq!(s.active().unwrap().history.past_len(), steps + 1); - let px = pixel(&mut s); - let (lo, hi) = px.iter().take(3).fold((1.0f32, 0.0f32), |(lo, hi), v| (lo.min(*v), hi.max(*v))); - assert!(hi - lo < 2.5 / 255.0, "neutral: {px:?}"); - let luma = |c: &[f32]| c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722; - assert!((luma(&px) - luma(&before)).abs() < 2.0 / 255.0, "keeps the luma: {px:?} vs {before:?}"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(pixel(&mut s), before); - for bad in [json!({"point": "gray", "at": [99, 1]}), json!({"point": "x", "at": [1, 1]}), json!({"point": "white", "color": [f64::NAN, 0, 0]})] { - assert!(s.execute("layer.setAdjustment", json!({"eyedropper": bad})).is_err(), "{bad}"); - assert!(s.execute("image.adjustments.levels", json!({"eyedropper": bad})).is_err(), "{bad}"); - } - s.execute("file.new", json!({"width": 8, "height": 8, "mode": "grayscale"})).unwrap(); - assert!(s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "gray", "at": [1, 1]}})).is_err(), "no gray picker in Grayscale"); - s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "black", "color": [1.0, 1.0, 1.0]}})).unwrap(); - } - - #[test] - fn curves_eyedropper_support_is_explicit_and_bad_samples_fail() { - assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [0.4; 3], ColorMode::Grayscale).is_ok()); - assert!(curves_eyedropper(&json!({}), CurvesEyedropper::White, [0.4; 3], ColorMode::Grayscale).is_ok()); - assert!(curves_eyedropper(&json!({}), CurvesEyedropper::NeutralGray, [0.4; 3], ColorMode::Grayscale).is_err()); - for mode in [ColorMode::Cmyk, ColorMode::Lab] { - assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [0.4; 3], mode).is_err()); - } - assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [f32::NAN, 0.0, 0.0], ColorMode::Rgb).is_err()); - } - - #[test] - fn hue_range_sliders_stay_ordered() { - let a = from_params("hueSaturation", &json!({"greens": {"range": [100, 90, 200, 150]}}), None, ColorMode::Rgb).unwrap(); - let Adjustment::HueSaturation { ranges, .. } = a else { panic!() }; - let b = ranges[2].bounds; - assert!(b[0] <= b[1] && b[1] <= b[2] && b[2] <= b[3] && b[3] - b[0] < 360.0, "{b:?}"); - } - - /// A colourful 16×16 document (`mode`, `depth`) for command tests. - fn colourful(mode: &str, depth: u32) -> crate::Session { - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "mode": mode, "depth": depth})).unwrap(); - for (i, c) in ["#c83c28", "#3c8c50", "#2850b4", "#d2b464"].iter().enumerate() { - s.execute("select.rect", json!({"x": (i % 2) * 8, "y": (i / 2) * 8, "width": 8, "height": 8})).unwrap(); - s.execute("edit.fill", json!({"color": c})).unwrap(); - } - s.execute("select.deselect", json!({})).unwrap(); - s - } - - fn pixels(s: &crate::Session) -> Vec> { - let d = s.active().unwrap(); - let bg = d.doc.layers[0].surface().unwrap(); - [(2, 2), (10, 2), (2, 10), (10, 10)].iter().map(|&(x, y)| bg.pixel(x, y)).collect() - } - - #[test] - fn destructive_commands_apply_their_params_at_every_depth() { - for depth in [8, 16, 32] { - for kind in KINDS.iter().filter(|k| **k != "invert") { - let mut s = colourful("rgb", depth); - let before = pixels(&s); - let steps = s.active().unwrap().history.past_len(); - s.execute(&format!("image.adjustments.{kind}"), sample(kind)).unwrap_or_else(|e| panic!("{kind} @{depth}: {e}")); - assert_ne!(pixels(&s), before, "{kind} @{depth} changed nothing"); - assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{kind}: one history step"); - // Identity params leave the pixels alone (within one 8-bit step). - let mut s = colourful("rgb", depth); - s.execute(&format!("image.adjustments.{kind}"), to_params(&default_for(kind, ColorMode::Rgb).unwrap())).unwrap(); - if !matches!(*kind, "threshold" | "posterize" | "blackWhite" | "gradientMap" | "photoFilter") { - for (a, b) in pixels(&s).iter().zip(&before) { - assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1.0 / 255.0 + 1e-4), "{kind} @{depth}: {a:?} vs {b:?}"); - } - } - } - } - } - - #[test] - fn curves_pencil_maps_draw_smooth_and_convert_back() { - // A drawn inversion: 256 output levels. - let inverted: Vec = (0..256).rev().map(|k| k as f32).collect(); - let a = from_params("curves", &json!({"pencil": true, "points": inverted}), None, ColorMode::Rgb).unwrap(); - assert!(matches!(&a, Adjustment::Curves { pencil: true, master, .. } if master.len() == CURVE_MAP_LEN)); - assert!((tone_output(&a, [0.25; 3])[0] - 0.75).abs() < 1e-3); - assert_eq!(from_params("curves", &to_params(&a), None, ColorMode::Rgb).unwrap(), a); - // Smooth evens out a hard step but keeps the endpoints. - let step: Vec = (0..256).map(|k| if k < 128 { 0.0 } else { 255.0 }).collect(); - let s = from_params("curves", &json!({"red": step, "smooth": 2}), Some(&a), ColorMode::Rgb).unwrap(); - let (_, chans) = curves_parts(&s); - assert!(chans[0][127].output > 0.2 && chans[0][128].output < 0.8, "{:?}", &chans[0][120..136]); - assert_eq!((chans[0][0].output, chans[0][255].output), (0.0, 1.0)); - // Edit points: the map is fitted with a point curve that still inverts. - let pts = from_params("curves", &json!({"pencil": false}), Some(&a), ColorMode::Rgb).unwrap(); - let (master, _) = curves_parts(&pts); - assert!(matches!(&pts, Adjustment::Curves { pencil: false, .. }) && master.len() <= MAX_FITTED_POINTS, "{master:?}"); - assert!((tone_output(&pts, [0.25; 3])[0] - 0.75).abs() < 2.0 / 255.0); - // The command draws it at every depth. - for depth in [8, 16, 32] { - let mut s = colourful("rgb", depth); - let before = pixels(&s); - s.execute("image.adjustments.curves", to_params(&a)).unwrap(); - let after = pixels(&s); - assert!((after[0][0] - (1.0 - before[0][0])).abs() < 2.0 / 255.0, "@{depth}: {after:?} vs {before:?}"); - } - } - - #[test] - fn destructive_levels_dont_clip_in_32_bit() { - // Input 15..230, gamma 1.3, output 10..245: integer documents stop at the output range, - // while float documents preserve the curve's signed and HDR values beyond it (the - // compose-side `levels_dont_clip_in_32_bit` pins the same curve, #2592). - let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245}); - for depth in [8, 16, 32] { - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap(); - s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("image.adjustments.levels", params.clone()).unwrap(); - let px = pixels(&s); - if depth == 32 { - assert!(px[0][0].is_finite() && px[0][0] < 0.0, "float black keeps its signed result: {:?}", px[0]); - assert!(px[1][0].is_finite() && px[1][0] > 1.0, "float white keeps its HDR result: {:?}", px[1]); - } else { - assert!((px[0][0] * 255.0 - 10.0).abs() < 0.6, "black @{depth}: {:?}", px[0]); - assert!((px[1][0] * 255.0 - 245.0).abs() < 0.6, "white @{depth}: {:?}", px[1]); - } - } - } - - #[test] - fn cmyk_and_lab_documents_use_their_channels() { - let mut s = colourful("cmyk", 8); - let before = pixels(&s); - // More black ink darkens every patch. - s.execute("image.adjustments.curves", json!({"black": [[0, 0], [255, 180]]})).unwrap(); - let after = pixels(&s); - assert!(after.iter().zip(&before).all(|(a, b)| a[3] > b[3] + 0.05), "{after:?} vs {before:?}"); - let mut s = colourful("lab", 16); - let before = pixels(&s); - s.execute("image.adjustments.levels", json!({"lightness": {"outBlack": 60}})).unwrap(); - let after = pixels(&s); - assert!(after.iter().zip(&before).all(|(a, b)| a[0] >= b[0]), "lightness lifted {after:?} vs {before:?}"); - // The adjustment layer of a CMYK document defaults to ink channels. - let mut s = colourful("cmyk", 8); - s.execute("layer.newAdjustmentLayer.curves", json!({})).unwrap(); - let id = s.active().unwrap().active_layer.unwrap(); - let l = s.active().unwrap().doc.layer(id).unwrap().clone(); - assert!(matches!(l.content, photocraft_doc::LayerContent::Adjustment(Adjustment::Curves { space: ToneSpace::Cmyk, .. }))); - } - - #[test] - fn set_adjustment_merges_and_resets() { - let mut s = colourful("rgb", 8); - s.execute("layer.newAdjustmentLayer.colorBalance", json!({"midtones": [30, 0, 0]})).unwrap(); - s.execute("layer.setAdjustment", json!({"highlights": [0, 0, -20]})).unwrap(); - let id = s.active().unwrap().active_layer.unwrap(); - let adj = |s: &crate::Session| match &s.active().unwrap().doc.layer(id).unwrap().content { - photocraft_doc::LayerContent::Adjustment(a) => a.clone(), - _ => panic!(), - }; - assert!(matches!(adj(&s), Adjustment::ColorBalance { midtones: [30.0, 0.0, 0.0], highlights: [0.0, 0.0, -20.0], .. })); - s.execute("layer.setAdjustment", json!({"layer": id.0})).unwrap(); - assert_eq!(adj(&s), default_for("colorBalance", ColorMode::Rgb).unwrap()); - // Bad params are errors and leave the layer alone. - s.execute("layer.setAdjustment", json!({"midtones": [10, 10, 10]})).unwrap(); - let kept = adj(&s); - for bad in [json!({"midtones": "x"}), json!({"preserveLuminosity": 3}), json!({"shadows": [1]})] { - assert!(s.execute("layer.setAdjustment", bad.clone()).is_err(), "{bad}"); - assert_eq!(adj(&s), kept); - } - } - - #[test] - fn commands_reject_bad_params_gracefully() { - let mut s = colourful("rgb", 8); - for (kind, p) in [ - ("curves", json!({"points": [[0, 0]]})), - ("levels", json!({"red": "dark"})), - ("gradientMap", json!({"stops": [[0, 1, 2]]})), - ("photoFilter", json!({"filter": 3})), - ("channelMixer", json!({"gray": [1, 2]})), - ("hueSaturation", json!({"reds": 4})), - ("blackWhite", json!({"tint": "yes"})), - ] { - for prefix in ["image.adjustments.", "layer.newAdjustmentLayer."] { - let r = s.execute(&format!("{prefix}{kind}"), p.clone()); - assert!(matches!(r, Err(EngineError::BadParams { .. })), "{prefix}{kind} {p}: {r:?}"); - } - } - } - #[test] - fn destructive_levels_match_independent_signed_hdr_endpoints() { - // Input 15..230, gamma 1.3, output 10..245: black and white land on the output range in - // integer documents. Float32 keeps HDR values outside 0..1, as the compositor's real-file - // Levels oracle does. These independently calculated endpoints use the signed-power - // curve at black and white, not display-clipped values. - let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245}); - for (depth, low, high, tolerance) in [(8, 10.0, 245.0, 0.6), (16, 10.0, 245.0, 0.6), (32, -20.308_89, 265.750_3, 0.01)] { - let mut s = crate::Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap(); - s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("image.adjustments.levels", params.clone()).unwrap(); - let px = pixels(&s); - assert!((px[0][0] * 255.0 - low).abs() < tolerance, "black @{depth}: {:?}", px[0]); - assert!((px[1][0] * 255.0 - high).abs() < tolerance, "white @{depth}: {:?}", px[1]); - if depth == 32 { - assert!(px[0][0] < 0.0 && px[1][0] > 1.0, "HDR endpoints must remain unclipped"); - } - } - } -} +mod tests; diff --git a/crates/engine/src/adjust_params/tests.rs b/crates/engine/src/adjust_params/tests.rs new file mode 100644 index 0000000000..cfc152c47f --- /dev/null +++ b/crates/engine/src/adjust_params/tests.rs @@ -0,0 +1,660 @@ +use super::*; + +const KINDS: [&str; 15] = [ + "invert", + "brightnessContrast", + "threshold", + "posterize", + "exposure", + "vibrance", + "hueSaturation", + "levels", + "curves", + "colorBalance", + "blackWhite", + "photoFilter", + "channelMixer", + "gradientMap", + "selectiveColor", +]; + +/// A non-default parameter set per kind (RGB channel keys for Levels/Curves). +pub(crate) fn sample(kind: &str) -> Value { + match kind { + "brightnessContrast" => json!({"brightness": 20, "contrast": -10, "legacy": true}), + "threshold" => json!({"level": 100}), + "posterize" => json!({"levels": 7}), + "exposure" => json!({"exposure": 1.5, "offset": 0.1, "gamma": 1.4}), + "vibrance" => json!({"vibrance": 30, "saturation": -20}), + "hueSaturation" => { + json!({"hue": 25, "saturation": -20, "lightness": 10, "reds": {"hue": 10, "saturation": -30, "lightness": 5, "range": [300, 340, 20, 50]}}) + } + "levels" => json!({"inBlack": 10, "inWhite": 240, "outBlack": 5, "outWhite": 250, "gamma": 1.2, "red": {"inBlack": 3, "gamma": 0.8}}), + "curves" => json!({"points": [[0, 0], [128, 150], [255, 255]], "blue": [[0, 20], [255, 235]]}), + "colorBalance" => json!({"shadows": [10, -5, 0], "midtones": [0, 20, -30], "highlights": [5, 5, 5], "preserveLuminosity": false}), + "blackWhite" => json!({"reds": 120, "blues": -40, "tint": true, "tintColor": "#d0a070"}), + "photoFilter" => json!({"color": "#3366cc", "density": 40, "preserveLuminosity": false}), + "channelMixer" => json!({"red": [80, 30, -10, 5], "blue": [0, 10, 90, 0]}), + "gradientMap" => json!({"stops": [[0, "#000000"], [0.5, "#ff0000"], [1, [1, 1, 1]]], "reverse": true, "dither": true}), + "selectiveColor" => json!({"method": "absolute", "reds": [10, 0, -20, 5]}), + _ => json!({}), + } +} + +#[test] +fn every_kind_round_trips_through_params() { + for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Grayscale] { + for kind in KINDS { + let mut p = sample(kind); + if matches!(kind, "levels" | "curves") && default_space(mode) != ToneSpace::Rgb { + // Off RGB the channel keys are the document's. + p.as_object_mut().unwrap().retain(|k, _| !matches!(k.as_str(), "red" | "blue")); + } + let a = from_params(kind, &p, None, mode).unwrap_or_else(|e| panic!("{kind} {mode:?}: {e}")); + assert_ne!(Some(&a), default_for(kind, mode).ok().as_ref().filter(|_| kind != "invert"), "{kind} params ignored"); + let back = from_params(kind, &to_params(&a), None, mode).unwrap(); + assert_eq!(to_params(&back), to_params(&a), "{kind} {mode:?}"); + // A partial update keeps everything it doesn't name. + let again = from_params(kind, &json!({}), Some(&a), mode).unwrap(); + assert_eq!(again, a, "{kind} {mode:?}"); + } + } +} + +#[test] +fn params_reach_the_model() { + let a = from_params("colorBalance", &json!({"midtones": [50, 0, -200]}), None, ColorMode::Rgb).unwrap(); + assert_eq!(a, Adjustment::ColorBalance { shadows: [0.0; 3], midtones: [50.0, 0.0, -100.0], highlights: [0.0; 3], preserve_luminosity: true }); + let a = from_params("channelMixer", &json!({"monochrome": true}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::ChannelMixer { matrix, monochrome: true } if matrix[0] == [0.4, 0.4, 0.2, 0.0])); + let a = from_params("photoFilter", &json!({"filter": "cooling80", "density": 60}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::PhotoFilter { color, density, .. } if color[2] == 1.0 && (density - 0.6).abs() < 1e-6)); + let a = from_params("blackWhite", &json!({"reds": 120, "tint": true}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::BlackWhite { weights, tint: Some(_) } if weights[0] == 120.0 && weights[1] == 60.0)); + let a = from_params("hueSaturation", &json!({"blues": {"hue": 40}}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(&a, Adjustment::HueSaturation { ranges, .. } if ranges[4].hue == 40.0 && ranges[0].is_neutral())); + // Colorize without a saturation starts at 25%; an explicit 0 and an already colorized base are kept. + let a = from_params("hueSaturation", &json!({"colorize": true, "hue": 30}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::HueSaturation { colorize: true, saturation: 25.0, .. }), "{a:?}"); + let a = from_params("hueSaturation", &json!({"colorize": true, "saturation": 0}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::HueSaturation { colorize: true, saturation: 0.0, .. }), "{a:?}"); + let a = from_params("hueSaturation", &json!({"hue": 120}), Some(&a), ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::HueSaturation { colorize: true, saturation: 0.0, hue: 120.0, .. }), "{a:?}"); + let a = from_params("gradientMap", &json!({"stops": [[1, "#ffffff"], [0, "#000000"]], "dither": true}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(&a, Adjustment::GradientMap { stops, dither: true, .. } if stops[0].0 == 0.0)); + // CMYK curves: ink channels; Lab: lightness without a composite. + let a = from_params("curves", &json!({"black": [[0, 0], [255, 200]]}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(&a, Adjustment::Curves { space: ToneSpace::Cmyk, black, .. } if black.len() == 2)); + let a = from_params("curves", &json!({"points": [[0, 40], [255, 255]]}), None, ColorMode::Lab).unwrap(); + assert!(matches!(&a, Adjustment::Curves { space: ToneSpace::Lab, per_channel, .. } if per_channel[0][0].output > 0.1)); + let a = from_params("levels", &json!({"inBlack": 20}), None, ColorMode::Cmyk).unwrap(); + assert!(matches!(&a, Adjustment::Levels { space: ToneSpace::Cmyk, master, .. } if (master.in_black - 20.0 / 255.0).abs() < 1e-6)); +} + +#[test] +fn bad_params_are_errors_not_panics() { + for (kind, p) in [ + ("curves", json!({"points": "abc"})), + ("curves", json!({"points": [[0, 0]]})), + ("curves", json!({"red": [[0, 0], [1]]})), + ("curves", json!({"points": [[5, 5], [5, 9]]})), + ("curves", json!({"pencil": true, "points": [1, 2, 3]})), + ("curves", json!({"pencil": "yes"})), + ("curves", json!({"points": (0..256).map(|k| if k == 9 { json!("x") } else { json!(k) }).collect::>()})), + ("levels", json!({"red": 3})), + ("levels", json!({"inBlack": "x"})), + ("hueSaturation", json!({"reds": {"range": [1, 2]}})), + ("hueSaturation", json!({"colorize": 1})), + ("colorBalance", json!({"shadows": [1, 2]})), + ("blackWhite", json!({"tintColor": "#zz0000"})), + ("photoFilter", json!({"filter": "nope"})), + ("photoFilter", json!({"color": [1]})), + ("channelMixer", json!({"red": [1, 2, 3]})), + ("gradientMap", json!({"stops": [[0, "#000"]]})), + ("gradientMap", json!({"stops": 7})), + ("selectiveColor", json!({"method": 5})), + ("selectiveColor", json!({"reds": "not-an-array"})), + ("selectiveColor", json!({"colors": "reds", "cyan": "50"})), + ("colorLookup", json!({"lut": 42})), + ("colorLookup", json!({"interpolation": 5})), + ("colorLookup", json!({"dither": "yes"})), + ("nope", json!({})), + ("levels", json!([1, 2])), + ] { + assert!(from_params(kind, &p, None, ColorMode::Rgb).is_err(), "{kind} {p}"); + } + // Out-of-range numbers clamp. + let a = from_params("hueSaturation", &json!({"hue": 1e9, "saturation": -1e9}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::HueSaturation { hue: 180.0, saturation: -100.0, .. })); + let a = from_params("levels", &json!({"inBlack": 250, "inWhite": 10}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(a, Adjustment::Levels { master, .. } if master.in_white > master.in_black)); +} + +#[test] +fn curve_points_outside_0_255_are_refused_as_the_message_says() { + // Photoshop refuses them too ("the settings in the file are invalid"); they used to be + // moved onto the edge silently. + for pts in [json!([[0, 0], [300, 255]]), json!([[0, -1], [255, 255]]), json!([[0, 0]])] { + let e = from_params("curves", &json!({ "points": pts }), None, ColorMode::Rgb).unwrap_err().to_string(); + assert!(e.contains("[input, output] pairs in 0..255") && e.contains("`curves adjustment`"), "{e}"); + } + assert!(from_params("curves", &json!({"points": [[0, 0], [128.5, 140], [255, 255]]}), None, ColorMode::Rgb).is_ok()); +} + +fn curves_parts(a: &Adjustment) -> (&[CurvePoint], &[Vec; 3]) { + match a { + Adjustment::Curves { master, per_channel, .. } => (master, per_channel), + _ => panic!("expected curves"), + } +} + +fn tone_output(adjustment: &Adjustment, sample: [f32; 3]) -> [f32; 3] { + let luts = photocraft_compose::adjust::tone_luts(adjustment); + std::array::from_fn(|channel| { + let row = &luts[channel]; + let position = sample[channel].clamp(0.0, 1.0) * (row.len().saturating_sub(1)) as f32; + let lower = position.floor() as usize; + let upper = lower.saturating_add(1).min(row.len().saturating_sub(1)); + let fraction = position - lower as f32; + row.get(lower).copied().unwrap_or(0.0) * (1.0 - fraction) + row.get(upper).copied().unwrap_or(0.0) * fraction + }) +} + +#[test] +fn curves_black_and_white_eyedroppers_move_the_input_references() { + let base = json!({ + "points": [[0, 8], [120, 150], [255, 245]], + "red": [[0, 0], [100, 130], [255, 255]], + "green": [[0, 0], [110, 125], [255, 255]], + "blue": [[0, 0], [90, 120], [255, 255]] + }); + let black = curves_eyedropper(&base, CurvesEyedropper::Black, [0.2, 0.3, 0.4], ColorMode::Rgb).unwrap(); + let (master, channels) = curves_parts(&black); + for (curve, sample) in channels.iter().zip([0.2, 0.3, 0.4]) { + assert!((curve[0].input - sample).abs() < 1e-6 && curve[0].output == 0.0, "{curve:?}"); + assert_eq!(curve.len(), 3, "existing edit points are preserved"); + } + assert_eq!(master[0].output, 0.0, "the composite cannot lift the sampled black"); + assert!(tone_output(&black, [0.2, 0.3, 0.4]).iter().all(|value| *value < 1e-3)); + + let white = curves_eyedropper(&base, CurvesEyedropper::White, [0.6, 0.7, 0.8], ColorMode::Rgb).unwrap(); + let (master, channels) = curves_parts(&white); + for (curve, sample) in channels.iter().zip([0.6, 0.7, 0.8]) { + let end = curve.last().unwrap(); + assert!((end.input - sample).abs() < 1e-6 && end.output == 1.0, "{curve:?}"); + assert_eq!(curve.len(), 3, "existing edit points are preserved"); + } + assert_eq!(master.last().map(|p| p.output), Some(1.0), "the composite cannot lower the sampled white"); + assert!(tone_output(&white, [0.6, 0.7, 0.8]).iter().all(|value| *value > 1.0 - 1e-3)); + + let edge_black = curves_eyedropper(&base, CurvesEyedropper::Black, [1.0, 0.3, 0.4], ColorMode::Rgb).unwrap(); + let (_, edge_channels) = curves_parts(&edge_black); + assert_eq!(edge_channels[0].len(), 3, "edge samples preserve other curve points"); + assert_eq!(edge_channels[0].last().map(|p| p.output), Some(0.0)); + let edge_white = curves_eyedropper(&base, CurvesEyedropper::White, [0.0, 0.7, 0.8], ColorMode::Rgb).unwrap(); + let (_, edge_channels) = curves_parts(&edge_white); + assert_eq!(edge_channels[0].len(), 3, "edge samples preserve other curve points"); + assert_eq!(edge_channels[0].first().map(|p| p.output), Some(1.0)); +} + +#[test] +fn black_and_white_eyedroppers_round_trip_near_serialization_boundaries() { + let cases = [ + (CurvesEyedropper::White, 0.0, 1.0), + (CurvesEyedropper::White, 0.001, 1.0), + (CurvesEyedropper::White, 0.494 / 255.0, 1.0), + // 0.496 level rounds to 0.50; the sample is just below that representable point. + (CurvesEyedropper::White, 0.496 / 255.0, 0.992), + (CurvesEyedropper::White, 0.2, 1.0), + (CurvesEyedropper::Black, 1.0, 0.0), + (CurvesEyedropper::Black, 0.999, 0.0), + (CurvesEyedropper::Black, 1.0 - 0.494 / 255.0, 0.0), + // 254.504 levels rounds to 254.50, leaving a representable 0.50-level gap. + (CurvesEyedropper::Black, 1.0 - 0.496 / 255.0, 0.008), + (CurvesEyedropper::Black, 0.8, 0.0), + ]; + for (picker, sample, expected_output) in cases { + let resolved = curves_eyedropper(&json!({}), picker, [sample; 3], ColorMode::Rgb).unwrap(); + let params = to_params(&resolved); + let parsed = from_params("curves", ¶ms, None, ColorMode::Rgb).unwrap(); + let (master, channels) = curves_parts(&parsed); + for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) { + assert!(curve.len() >= 2, "{picker:?} sample={sample}: {curve:?}"); + assert!(curve.len() <= MAX_CURVE_POINTS, "{picker:?} sample={sample}: {curve:?}"); + assert!(curve.windows(2).all(|pair| pair[0].input < pair[1].input), "{picker:?} sample={sample}: {curve:?}"); + assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{picker:?} sample={sample}: {curve:?}"); + } + let output = tone_output(&parsed, [sample; 3]); + assert!( + output.iter().all(|value| (*value - expected_output).abs() < 1e-3), + "{picker:?} sample={sample} output={output:?} expected={expected_output}" + ); + } +} + +#[test] +fn endpoint_eyedroppers_fall_back_when_serialization_collapses_curve_points() { + let base = json!({ + "points": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]], + "red": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]], + "green": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]], + "blue": [[0, 0], [64, 50], [128, 100], [192, 200], [255, 255]] + }); + let cases = [(CurvesEyedropper::Black, 0.995, 0.0, true), (CurvesEyedropper::White, 0.005, 1.0, false)]; + for (picker, sample, target, black) in cases { + let resolved = curves_eyedropper(&base, picker, [sample; 3], ColorMode::Rgb).unwrap(); + let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); + let (master, channels) = curves_parts(&parsed); + for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) { + assert_eq!(curve.len(), 5, "collapsed points use the deterministic fallback: {curve:?}"); + for (point, input) in curve.iter().zip([0.0, 64.0, 128.0, 192.0, 255.0]) { + assert!((point.input * 255.0 - input).abs() < 1e-3, "existing point position was retained: {curve:?}"); + } + } + for curve in channels { + let plateau: Vec<_> = if black { curve.iter().rev().take(2).collect() } else { curve.iter().take(2).collect() }; + assert!(plateau.into_iter().all(|point| (point.output - target).abs() < 1e-6), "{curve:?}"); + } + let output = tone_output(&parsed, [sample; 3]); + assert!(output.iter().all(|value| (*value - target).abs() < 0.01), "{picker:?}: {output:?}"); + } +} + +#[test] +fn black_and_white_round_trips_preserve_representable_curve_edits() { + let base = json!({ + "points": [[0, 8], [120, 150], [255, 245]], + "red": [[0, 0], [100, 130], [255, 255]], + "green": [[0, 0], [110, 125], [255, 255]], + "blue": [[0, 0], [90, 120], [255, 255]] + }); + let black = curves_eyedropper(&base, CurvesEyedropper::Black, [0.2, 0.3, 0.4], ColorMode::Rgb).unwrap(); + let black = from_params("curves", &to_params(&black), None, ColorMode::Rgb).unwrap(); + let (_, channels) = curves_parts(&black); + assert_eq!(channels[0].len(), 3); + assert!((channels[0][1].input * 255.0 - 131.0).abs() < 1e-3); + assert!((channels[0][1].output * 255.0 - 130.0).abs() < 1e-3); + + let white = curves_eyedropper(&base, CurvesEyedropper::White, [0.6, 0.7, 0.8], ColorMode::Rgb).unwrap(); + let white = from_params("curves", &to_params(&white), None, ColorMode::Rgb).unwrap(); + let (_, channels) = curves_parts(&white); + assert_eq!(channels[0].len(), 3); + assert!((channels[0][1].input * 255.0 - 60.0).abs() < 1e-3); + assert!((channels[0][1].output * 255.0 - 130.0).abs() < 1e-3); +} + +fn assert_gray_point_preserves_luma_and_existing_curve_edits(sample: [f32; 3]) { + let base = json!({ + "points": [[0, 0], [128, 96], [255, 255]], + "red": [[0, 0], [80, 90], [255, 255]], + "green": [[0, 0], [90, 100], [255, 255]], + "blue": [[0, 0], [70, 80], [255, 255]] + }); + let original = from_params("curves", &base, None, ColorMode::Rgb).unwrap(); + let expected_luma = rgb_luma(sample); + let resolved = curves_eyedropper(&base, CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap(); + let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); + let (master, channels) = curves_parts(&parsed); + let (original_master, original_channels) = curves_parts(&original); + assert_eq!(master, original_master, "the existing master curve is retained"); + for (curve, old_curve) in channels.iter().zip(original_channels) { + let old_edit = old_curve.get(1).expect("the test curve has an interior edit"); + assert!( + curve.iter().any(|point| { (point.input - old_edit.input).abs() < 1e-6 && (point.output - old_edit.output).abs() < 1e-6 }), + "the existing channel edit is retained: {curve:?}" + ); + } + let output = tone_output(&parsed, sample); + assert!((output[0] - output[1]).abs() < 0.002 && (output[1] - output[2]).abs() < 0.002, "sample must become neutral: {output:?}"); + assert!((rgb_luma(output) - expected_luma).abs() < 0.003, "luma changed from {expected_luma} to {} ({output:?})", rgb_luma(output)); +} + +#[test] +fn curves_neutral_gray_preserves_luma_for_a_light_cast_sample() { + assert_gray_point_preserves_luma_and_existing_curve_edits([0.88, 0.76, 0.63]); +} + +#[test] +fn curves_neutral_gray_preserves_luma_for_a_dark_cast_sample() { + assert_gray_point_preserves_luma_and_existing_curve_edits([0.17, 0.105, 0.075]); +} + +#[test] +fn curves_neutral_gray_handles_near_black_and_near_white_samples() { + for sample in [[0.004, 0.006, 0.008], [0.992, 0.996, 0.999], [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]] { + let resolved = curves_eyedropper(&json!({}), CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap(); + let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); + let (master, channels) = curves_parts(&parsed); + for curve in std::iter::once(master).chain(channels.iter().map(Vec::as_slice)) { + assert!(curve.len() >= 2, "{sample:?}: {curve:?}"); + assert!(curve.windows(2).all(|pair| pair[0].input < pair[1].input), "{sample:?}: {curve:?}"); + assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{sample:?}: {curve:?}"); + } + let output = tone_output(&parsed, sample); + assert!((output[0] - output[1]).abs() < 0.002 && (output[1] - output[2]).abs() < 0.002, "{sample:?}: {output:?}"); + assert!((rgb_luma(output) - rgb_luma(sample)).abs() < 0.003, "{sample:?}: {output:?}"); + } +} + +#[test] +fn gray_point_fallback_keeps_tightly_spaced_points_round_trip_safe() { + let base = json!({ + "red": [[0, 0], [100, 100], [100.51, 100], [255, 255]], + "green": [[0, 0], [100, 100], [100.51, 100], [255, 255]], + "blue": [[0, 0], [100, 100], [100.51, 100], [255, 255]] + }); + let sample = [100.25 / 255.0, 100.1 / 255.0, 100.4 / 255.0]; + let target = rgb_luma(sample); + let resolved = curves_eyedropper(&base, CurvesEyedropper::NeutralGray, sample, ColorMode::Rgb).unwrap(); + let parsed = from_params("curves", &to_params(&resolved), None, ColorMode::Rgb).unwrap(); + let (_, channels) = curves_parts(&parsed); + for (curve, input) in channels.iter().zip(sample) { + assert_eq!(curve.len(), 4, "the fallback keeps every serialized point: {curve:?}"); + assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{curve:?}"); + let sample_pair = curve.windows(2).find(|pair| pair[0].input <= input && input <= pair[1].input).unwrap(); + assert!((sample_pair[0].output - sample_pair[1].output).abs() < 1e-6, "fallback forms a plateau around the sample: {curve:?}"); + assert!((sample_pair[0].output - target).abs() < 0.001, "fallback uses the luma target: {curve:?}"); + } +} + +#[test] +fn curves_eyedropper_param_drives_the_command() { + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); + s.execute("image.adjustments.curves", json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap(); + let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); + assert!(px.iter().take(3).all(|v| *v > 0.99), "the sample becomes white: {px:?}"); + s.execute("image.adjustments.curves", json!({"eyedropper": {"point": "black", "color": [1.0, 1.0, 1.0]}})).unwrap(); + let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); + assert!(px.iter().take(3).all(|v| *v < 0.01), "the given colour becomes black: {px:?}"); + for bad in [ + json!("black"), + json!({"point": "nope", "at": [1, 1]}), + json!({"point": "black"}), + json!({"point": "black", "at": [99, 1]}), + json!({"point": "black", "at": [-1, 1]}), + json!({"point": "black", "at": [1]}), + json!({"point": "gray", "at": [f64::MAX, 1]}), + json!({"point": "black", "color": "red"}), + ] { + assert!(s.execute("image.adjustments.curves", json!({"eyedropper": bad})).is_err(), "{bad}"); + } +} + +/// The Properties panel's pickers on a Curves adjustment layer (UI-217-15): one undoable step +/// that samples the image below the layer, so a repeated click keeps the same curve. +#[test] +fn layer_eyedropper_samples_below_the_curves_layer() { + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); + s.execute("layer.newAdjustmentLayer.curves", json!({})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + let pick = json!({"eyedropper": {"point": "white", "at": [2, 2], "size": 3}}); + s.execute("layer.setAdjustment", pick.clone()).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); + let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); + assert!(px.iter().take(3).all(|v| *v > 0.99), "the sample becomes white: {px:?}"); + let curve = s.active().unwrap().doc.clone(); + s.execute("layer.setAdjustment", pick).unwrap(); + let same = |a: &photocraft_doc::Document, b: &photocraft_doc::Document| a.layers.last().map(|l| &l.content) == b.layers.last().map(|l| &l.content); + assert!(same(&curve, &s.active().unwrap().doc), "sampled below the layer, not through it"); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), steps); + for bad in [json!({"point": "black", "at": [99, 1]}), json!({"point": "black", "at": [1, 1], "size": 2}), json!({"point": "x", "at": [1, 1]})] { + assert!(s.execute("layer.setAdjustment", json!({"eyedropper": bad})).is_err(), "{bad}"); + } + s.execute("layer.newAdjustmentLayer.hueSaturation", json!({})).unwrap(); + assert!(s.execute("layer.setAdjustment", json!({"eyedropper": {"point": "white", "at": [1, 1]}})).is_err(), "Levels and Curves only"); +} + +/// #3127: on a smart object the eyedropper param records the adjustment it resolved to as +/// the smart filter, not the raw sample (which re-rendered as an identity). +#[test] +fn eyedropper_on_a_smart_object_records_the_resolved_adjustment() { + for kind in ["curves", "levels"] { + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute(&format!("image.adjustments.{kind}"), json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap(); + let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap(); + assert!(px.iter().take(3).all(|v| *v > 0.99), "{kind}: {px:?}"); + } +} + +/// Levels' Set White/Neutral Gray Point (#3116): the white point maps the sampled colour to +/// white at 8 and 16 bit, the gray point neutralises a tinted grey at its luma on a Levels +/// layer as one undoable step, and bad picks fail. +#[test] +fn levels_eyedroppers_set_white_and_neutral_gray() { + let pixel = |s: &mut crate::Session| -> Vec { serde_json::from_value(s.execute("document.pixel", json!({"x": 2, "y": 2})).unwrap()).unwrap() }; + for depth in [8, 16] { + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); + s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); + s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "white", "at": [2, 2]}})).unwrap(); + let px = pixel(&mut s); + assert!(px.iter().take(3).all(|v| *v > 0.995), "{depth}-bit: the sample becomes white: {px:?}"); + } + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("edit.fill", json!({"color": [0.6, 0.5, 0.4]})).unwrap(); + let before = pixel(&mut s); + s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + s.execute("layer.setAdjustment", json!({"eyedropper": {"point": "gray", "at": [2, 2]}})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); + let px = pixel(&mut s); + let (lo, hi) = px.iter().take(3).fold((1.0f32, 0.0f32), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + assert!(hi - lo < 2.5 / 255.0, "neutral: {px:?}"); + let luma = |c: &[f32]| c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722; + assert!((luma(&px) - luma(&before)).abs() < 2.0 / 255.0, "keeps the luma: {px:?} vs {before:?}"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(pixel(&mut s), before); + for bad in [json!({"point": "gray", "at": [99, 1]}), json!({"point": "x", "at": [1, 1]}), json!({"point": "white", "color": [f64::NAN, 0, 0]})] { + assert!(s.execute("layer.setAdjustment", json!({"eyedropper": bad})).is_err(), "{bad}"); + assert!(s.execute("image.adjustments.levels", json!({"eyedropper": bad})).is_err(), "{bad}"); + } + s.execute("file.new", json!({"width": 8, "height": 8, "mode": "grayscale"})).unwrap(); + assert!(s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "gray", "at": [1, 1]}})).is_err(), "no gray picker in Grayscale"); + s.execute("image.adjustments.levels", json!({"eyedropper": {"point": "black", "color": [1.0, 1.0, 1.0]}})).unwrap(); +} + +#[test] +fn curves_eyedropper_support_is_explicit_and_bad_samples_fail() { + assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [0.4; 3], ColorMode::Grayscale).is_ok()); + assert!(curves_eyedropper(&json!({}), CurvesEyedropper::White, [0.4; 3], ColorMode::Grayscale).is_ok()); + assert!(curves_eyedropper(&json!({}), CurvesEyedropper::NeutralGray, [0.4; 3], ColorMode::Grayscale).is_err()); + for mode in [ColorMode::Cmyk, ColorMode::Lab] { + assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [0.4; 3], mode).is_err()); + } + assert!(curves_eyedropper(&json!({}), CurvesEyedropper::Black, [f32::NAN, 0.0, 0.0], ColorMode::Rgb).is_err()); +} + +#[test] +fn hue_range_sliders_stay_ordered() { + let a = from_params("hueSaturation", &json!({"greens": {"range": [100, 90, 200, 150]}}), None, ColorMode::Rgb).unwrap(); + let Adjustment::HueSaturation { ranges, .. } = a else { panic!() }; + let b = ranges[2].bounds; + assert!(b[0] <= b[1] && b[1] <= b[2] && b[2] <= b[3] && b[3] - b[0] < 360.0, "{b:?}"); +} + +/// A colourful 16×16 document (`mode`, `depth`) for command tests. +fn colourful(mode: &str, depth: u32) -> crate::Session { + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "mode": mode, "depth": depth})).unwrap(); + for (i, c) in ["#c83c28", "#3c8c50", "#2850b4", "#d2b464"].iter().enumerate() { + s.execute("select.rect", json!({"x": (i % 2) * 8, "y": (i / 2) * 8, "width": 8, "height": 8})).unwrap(); + s.execute("edit.fill", json!({"color": c})).unwrap(); + } + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn pixels(s: &crate::Session) -> Vec> { + let d = s.active().unwrap(); + let bg = d.doc.layers[0].surface().unwrap(); + [(2, 2), (10, 2), (2, 10), (10, 10)].iter().map(|&(x, y)| bg.pixel(x, y)).collect() +} + +#[test] +fn destructive_commands_apply_their_params_at_every_depth() { + for depth in [8, 16, 32] { + for kind in KINDS.iter().filter(|k| **k != "invert") { + let mut s = colourful("rgb", depth); + let before = pixels(&s); + let steps = s.active().unwrap().history.past_len(); + s.execute(&format!("image.adjustments.{kind}"), sample(kind)).unwrap_or_else(|e| panic!("{kind} @{depth}: {e}")); + assert_ne!(pixels(&s), before, "{kind} @{depth} changed nothing"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{kind}: one history step"); + // Identity params leave the pixels alone (within one 8-bit step). + let mut s = colourful("rgb", depth); + s.execute(&format!("image.adjustments.{kind}"), to_params(&default_for(kind, ColorMode::Rgb).unwrap())).unwrap(); + if !matches!(*kind, "threshold" | "posterize" | "blackWhite" | "gradientMap" | "photoFilter") { + for (a, b) in pixels(&s).iter().zip(&before) { + assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1.0 / 255.0 + 1e-4), "{kind} @{depth}: {a:?} vs {b:?}"); + } + } + } + } +} + +#[test] +fn curves_pencil_maps_draw_smooth_and_convert_back() { + // A drawn inversion: 256 output levels. + let inverted: Vec = (0..256).rev().map(|k| k as f32).collect(); + let a = from_params("curves", &json!({"pencil": true, "points": inverted}), None, ColorMode::Rgb).unwrap(); + assert!(matches!(&a, Adjustment::Curves { pencil: true, master, .. } if master.len() == CURVE_MAP_LEN)); + assert!((tone_output(&a, [0.25; 3])[0] - 0.75).abs() < 1e-3); + assert_eq!(from_params("curves", &to_params(&a), None, ColorMode::Rgb).unwrap(), a); + // Smooth evens out a hard step but keeps the endpoints. + let step: Vec = (0..256).map(|k| if k < 128 { 0.0 } else { 255.0 }).collect(); + let s = from_params("curves", &json!({"red": step, "smooth": 2}), Some(&a), ColorMode::Rgb).unwrap(); + let (_, chans) = curves_parts(&s); + assert!(chans[0][127].output > 0.2 && chans[0][128].output < 0.8, "{:?}", &chans[0][120..136]); + assert_eq!((chans[0][0].output, chans[0][255].output), (0.0, 1.0)); + // Edit points: the map is fitted with a point curve that still inverts. + let pts = from_params("curves", &json!({"pencil": false}), Some(&a), ColorMode::Rgb).unwrap(); + let (master, _) = curves_parts(&pts); + assert!(matches!(&pts, Adjustment::Curves { pencil: false, .. }) && master.len() <= MAX_FITTED_POINTS, "{master:?}"); + assert!((tone_output(&pts, [0.25; 3])[0] - 0.75).abs() < 2.0 / 255.0); + // The command draws it at every depth. + for depth in [8, 16, 32] { + let mut s = colourful("rgb", depth); + let before = pixels(&s); + s.execute("image.adjustments.curves", to_params(&a)).unwrap(); + let after = pixels(&s); + assert!((after[0][0] - (1.0 - before[0][0])).abs() < 2.0 / 255.0, "@{depth}: {after:?} vs {before:?}"); + } +} + +#[test] +fn destructive_levels_dont_clip_in_32_bit() { + // Input 15..230, gamma 1.3, output 10..245: integer documents stop at the output range, + // while float documents preserve the curve's signed and HDR values beyond it (the + // compose-side `levels_dont_clip_in_32_bit` pins the same curve, #2592). + let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245}); + for depth in [8, 16, 32] { + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap(); + s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("image.adjustments.levels", params.clone()).unwrap(); + let px = pixels(&s); + if depth == 32 { + assert!(px[0][0].is_finite() && px[0][0] < 0.0, "float black keeps its signed result: {:?}", px[0]); + assert!(px[1][0].is_finite() && px[1][0] > 1.0, "float white keeps its HDR result: {:?}", px[1]); + } else { + assert!((px[0][0] * 255.0 - 10.0).abs() < 0.6, "black @{depth}: {:?}", px[0]); + assert!((px[1][0] * 255.0 - 245.0).abs() < 0.6, "white @{depth}: {:?}", px[1]); + } + } +} + +#[test] +fn cmyk_and_lab_documents_use_their_channels() { + let mut s = colourful("cmyk", 8); + let before = pixels(&s); + // More black ink darkens every patch. + s.execute("image.adjustments.curves", json!({"black": [[0, 0], [255, 180]]})).unwrap(); + let after = pixels(&s); + assert!(after.iter().zip(&before).all(|(a, b)| a[3] > b[3] + 0.05), "{after:?} vs {before:?}"); + let mut s = colourful("lab", 16); + let before = pixels(&s); + s.execute("image.adjustments.levels", json!({"lightness": {"outBlack": 60}})).unwrap(); + let after = pixels(&s); + assert!(after.iter().zip(&before).all(|(a, b)| a[0] >= b[0]), "lightness lifted {after:?} vs {before:?}"); + // The adjustment layer of a CMYK document defaults to ink channels. + let mut s = colourful("cmyk", 8); + s.execute("layer.newAdjustmentLayer.curves", json!({})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let l = s.active().unwrap().doc.layer(id).unwrap().clone(); + assert!(matches!(l.content, photocraft_doc::LayerContent::Adjustment(Adjustment::Curves { space: ToneSpace::Cmyk, .. }))); +} + +#[test] +fn set_adjustment_merges_and_resets() { + let mut s = colourful("rgb", 8); + s.execute("layer.newAdjustmentLayer.colorBalance", json!({"midtones": [30, 0, 0]})).unwrap(); + s.execute("layer.setAdjustment", json!({"highlights": [0, 0, -20]})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let adj = |s: &crate::Session| match &s.active().unwrap().doc.layer(id).unwrap().content { + photocraft_doc::LayerContent::Adjustment(a) => a.clone(), + _ => panic!(), + }; + assert!(matches!(adj(&s), Adjustment::ColorBalance { midtones: [30.0, 0.0, 0.0], highlights: [0.0, 0.0, -20.0], .. })); + s.execute("layer.setAdjustment", json!({"layer": id.0})).unwrap(); + assert_eq!(adj(&s), default_for("colorBalance", ColorMode::Rgb).unwrap()); + // Bad params are errors and leave the layer alone. + s.execute("layer.setAdjustment", json!({"midtones": [10, 10, 10]})).unwrap(); + let kept = adj(&s); + for bad in [json!({"midtones": "x"}), json!({"preserveLuminosity": 3}), json!({"shadows": [1]})] { + assert!(s.execute("layer.setAdjustment", bad.clone()).is_err(), "{bad}"); + assert_eq!(adj(&s), kept); + } +} + +#[test] +fn commands_reject_bad_params_gracefully() { + let mut s = colourful("rgb", 8); + for (kind, p) in [ + ("curves", json!({"points": [[0, 0]]})), + ("levels", json!({"red": "dark"})), + ("gradientMap", json!({"stops": [[0, 1, 2]]})), + ("photoFilter", json!({"filter": 3})), + ("channelMixer", json!({"gray": [1, 2]})), + ("hueSaturation", json!({"reds": 4})), + ("blackWhite", json!({"tint": "yes"})), + ] { + for prefix in ["image.adjustments.", "layer.newAdjustmentLayer."] { + let r = s.execute(&format!("{prefix}{kind}"), p.clone()); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{prefix}{kind} {p}: {r:?}"); + } + } +} +#[test] +fn destructive_levels_match_independent_signed_hdr_endpoints() { + // Input 15..230, gamma 1.3, output 10..245: black and white land on the output range in + // integer documents. Float32 keeps HDR values outside 0..1, as the compositor's real-file + // Levels oracle does. These independently calculated endpoints use the signed-power + // curve at black and white, not display-clipped values. + let params = json!({"inBlack": 15, "inWhite": 230, "gamma": 1.3, "outBlack": 10, "outWhite": 245}); + for (depth, low, high, tolerance) in [(8, 10.0, 245.0, 0.6), (16, 10.0, 245.0, 0.6), (32, -20.308_89, 265.750_3, 0.01)] { + let mut s = crate::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth, "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap(); + s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("image.adjustments.levels", params.clone()).unwrap(); + let px = pixels(&s); + assert!((px[0][0] * 255.0 - low).abs() < tolerance, "black @{depth}: {:?}", px[0]); + assert!((px[1][0] * 255.0 - high).abs() < tolerance, "white @{depth}: {:?}", px[1]); + if depth == 32 { + assert!(px[0][0] < 0.0 && px[1][0] > 1.0, "HDR endpoints must remain unclipped"); + } + } +} From 5fd2de8ac25e9fd9f7fe27a67867314e81a8f34d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:11 +0000 Subject: [PATCH 031/259] refactor(engine): move sampler_cmds.rs tests to sampler_cmds/tests.rs --- crates/engine/src/sampler_cmds.rs | 356 +----------------------- crates/engine/src/sampler_cmds/tests.rs | 353 +++++++++++++++++++++++ 2 files changed, 354 insertions(+), 355 deletions(-) create mode 100644 crates/engine/src/sampler_cmds/tests.rs diff --git a/crates/engine/src/sampler_cmds.rs b/crates/engine/src/sampler_cmds.rs index a67b023a6f..2326e43693 100644 --- a/crates/engine/src/sampler_cmds.rs +++ b/crates/engine/src/sampler_cmds.rs @@ -201,358 +201,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_color::{ColorMode, SampleType}; - use photocraft_doc::{Layer, Size}; - use photocraft_geom::Rect; - - /// A 100×80 white document. - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 80, "background": "white"})).unwrap(); - s - } - - fn list(s: &mut Session) -> Value { - s.execute("view.colorSamplers.list", json!({})).unwrap() - } - - fn points(s: &mut Session) -> Vec { - list(s)["samplers"].as_array().cloned().unwrap_or_default() - } - - #[test] - fn add_reads_the_composite_pixel_and_lists_it() { - let mut s = session(); - let r = s.execute("view.colorSamplers.add", json!({"x": 5, "y": 6})).unwrap(); - assert_eq!(r["index"], 0); - assert_eq!(r["count"], 1); - assert_eq!(r["point"]["number"], 1); - assert_eq!(r["point"]["position"], json!([5.0, 6.0])); - assert_eq!(r["point"]["rgb"], json!([255, 255, 255])); - assert_eq!(r["point"]["cmyk"], json!([0, 0, 0, 0])); - let l = list(&mut s); - assert_eq!(l["max"], 10); - assert_eq!(l["samplers"].as_array().unwrap().len(), 1); - assert_eq!(l["samplers"][0]["position"], json!([5.0, 6.0])); - } - - #[test] - fn fractional_clicks_floor_to_the_pixel() { - let mut s = session(); - let r = s.execute("view.colorSamplers.add", json!({"x": 5.9, "y": 6.1})).unwrap(); - assert_eq!(r["point"]["position"], json!([5.0, 6.0])); - } - - #[test] - fn add_reads_an_actual_painted_pixel() { - // A black pixel at (3, 3) of an otherwise white document. - let mut s = session(); - s.edit("paint", |doc, _| { - let surf = doc.layers[0].surface_mut().unwrap(); - let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); - surf.fill_rect(Rect::new(3, 3, 4, 4), &black); - Ok(()) - }) - .unwrap(); - let r = s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); - assert_eq!(r["point"]["rgb"], json!([0, 0, 0])); - assert_eq!(r["point"]["cmyk"], json!(device_cmyk(0.0, 0.0, 0.0)), "the profile's black, not the naive 0/0/0/100"); - // Painting over the point changes its readout (the list is computed live). - s.edit("paint", |doc, _| { - let surf = doc.layers[0].surface_mut().unwrap(); - let red = photocraft_raster::from_rgba(&surf.format(), [1.0, 0.0, 0.0, 1.0]); - surf.fill_rect(Rect::new(3, 3, 4, 4), &red); - Ok(()) - }) - .unwrap(); - assert_eq!(points(&mut s)[0]["rgb"], json!([255, 0, 0])); - } - - #[test] - fn ten_points_then_the_limit() { - let mut s = session(); - for i in 0..10 { - s.execute("view.colorSamplers.add", json!({"x": i, "y": 0})).unwrap(); - } - assert_eq!(points(&mut s).len(), 10); - let err = s.execute("view.colorSamplers.add", json!({"x": 20, "y": 0})).unwrap_err().to_string(); - assert!(err.contains("limit"), "{err}"); - assert_eq!(points(&mut s).len(), 10); - } - - #[test] - fn move_delete_and_clear() { - let mut s = session(); - s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); - s.execute("view.colorSamplers.add", json!({"x": 50, "y": 50})).unwrap(); - let r = s.execute("view.colorSamplers.move", json!({"index": 0, "x": 10, "y": 20})).unwrap(); - assert_eq!(r["point"]["position"], json!([10.0, 20.0])); - assert_eq!(points(&mut s)[0]["position"], json!([10.0, 20.0])); - s.execute("view.colorSamplers.delete", json!({"index": 1})).unwrap(); - assert_eq!(points(&mut s).len(), 1); - // The remaining point is the moved #1. - assert_eq!(points(&mut s)[0]["position"], json!([10.0, 20.0])); - let r = s.execute("view.colorSamplers.clear", json!({})).unwrap(); - assert_eq!(r["deleted"], 1); - assert!(points(&mut s).is_empty()); - } - - #[test] - fn placing_and_moving_add_no_history_and_change_no_pixels() { - let mut s = session(); - let before = s.active().unwrap().doc.layers[0].surface().unwrap().pixel(5, 5); - let past = s.active().unwrap().history.past_len(); - s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); - s.execute("view.colorSamplers.move", json!({"index": 0, "x": 9, "y": 9})).unwrap(); - s.execute("view.colorSamplers.delete", json!({"index": 0})).unwrap(); - assert_eq!(s.active().unwrap().history.past_len(), past, "no history steps"); - assert_eq!(s.active().unwrap().doc.layers[0].surface().unwrap().pixel(5, 5), before, "no pixels changed"); - assert!(!s.active().unwrap().is_dirty(), "a clean document stays clean"); - } - - #[test] - fn points_belong_to_their_document() { - let mut s = session(); - s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); - s.execute("file.new", json!({"width": 40, "height": 40, "background": "white"})).unwrap(); - assert!(points(&mut s).is_empty(), "the new document has no points"); - s.execute("document.activate", json!({"document": 0})).unwrap(); - assert_eq!(points(&mut s).len(), 1, "the first document kept its point"); - // Closing the second document leaves the first's points alone. - s.execute("file.close", json!({"document": 1})).unwrap(); - assert_eq!(points(&mut s).len(), 1); - // Closing the first discards its points with it. - s.execute("file.close", json!({"document": 0})).unwrap(); - assert!(s.execute("view.colorSamplers.list", json!({})).is_err(), "no document open"); - } - - #[test] - fn a_crop_drops_points_outside_the_new_canvas() { - let mut s = session(); - s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); - s.execute("view.colorSamplers.add", json!({"x": 50, "y": 50})).unwrap(); - s.execute("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - let p = points(&mut s); - assert_eq!(p.len(), 1, "the outside point was removed"); - assert_eq!(p[0]["position"], json!([5.0, 5.0])); - assert_eq!(s.take_samplers_removed(), 1, "one removed point reported"); - assert_eq!(s.take_samplers_removed(), 0, "reported once"); - } - - #[test] - fn a_crop_moves_points_with_their_pixels() { - // A crop from a non-zero origin moves the canvas: the point follows its pixel. - let mut s = session(); - s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); - s.execute("image.crop", json!({"x": 40, "y": 30, "width": 20, "height": 20})).unwrap(); - let p = points(&mut s); - assert_eq!(p.len(), 1); - assert_eq!(p[0]["position"], json!([10.0, 10.0]), "moved by (-40, -30)"); - assert_eq!(s.take_samplers_removed(), 0, "nothing removed"); - } - - #[test] - fn a_canvas_size_shift_moves_points() { - // Canvas Size anchored bottom-right shifts the canvas origin by (+20, +20). - let mut s = session(); - s.execute("view.colorSamplers.add", json!({"x": 30, "y": 30})).unwrap(); - s.execute("image.canvasSize", json!({"width": 120, "height": 100, "anchor": "bottomRight"})).unwrap(); - let p = points(&mut s); - assert_eq!(p.len(), 1); - assert_eq!(p[0]["position"], json!([50.0, 50.0]), "moved by the canvas shift"); - } - - #[test] - fn a_right_angle_rotation_moves_points() { - // 90° clockwise about the centre: pixel (x, y) of the 100×80 canvas goes to (79 - y, x). - let mut s = session(); - s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); - s.execute("image.rotation.arbitrary", json!({"angle": 90, "direction": "cw"})).unwrap(); - let p = points(&mut s); - assert_eq!(p.len(), 1); - let pos = p[0]["position"].as_array().unwrap(); - let (x, y) = (pos[0].as_f64().unwrap(), pos[1].as_f64().unwrap()); - assert!((x - 39.0).abs() < 1e-6 && (y - 50.0).abs() < 1e-6, "{pos:?}"); - } - - #[test] - fn flips_and_right_angle_turns_keep_points_on_their_pixel() { - use crate::canvas_geom::Turn; - for (id, turn) in [ - ("image.imageRotation.flipCanvasHorizontal", Turn::FlipHorizontal), - ("image.imageRotation.flipCanvasVertical", Turn::FlipVertical), - ("image.imageRotation.180", Turn::Rotate180), - ("image.imageRotation.90cw", Turn::Cw90), - ("image.imageRotation.90ccw", Turn::Ccw90), - ] { - // A black pixel at (3, 3) of a white 100×80 document, with a point on it. - let mut s = session(); - s.edit("paint", |doc, _| { - let surf = doc.layers[0].surface_mut().unwrap(); - let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); - surf.fill_rect(Rect::new(3, 3, 4, 4), &black); - Ok(()) - }) - .unwrap(); - s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); - s.execute(id, json!({})).unwrap(); - let (x, y) = turn.pixel_map(100, 80)(3, 3); - let p = points(&mut s); - assert_eq!(p.len(), 1, "{id}"); - assert_eq!(p[0]["position"], json!([f64::from(x), f64::from(y)]), "{id}"); - assert_eq!(p[0]["rgb"], json!([0, 0, 0]), "{id}"); - } - } - - #[test] - fn an_arbitrary_rotation_keeps_points_on_their_pixel() { - // The pixel at (3, 3) of the 100×80 document, and where each turn moves it. - for (angle, direction, at) in [(90, "cw", [76.0, 3.0]), (90, "ccw", [3.0, 96.0]), (180, "cw", [96.0, 76.0])] { - let mut s = session(); - s.edit("paint", |doc, _| { - let surf = doc.layers[0].surface_mut().unwrap(); - let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); - surf.fill_rect(Rect::new(3, 3, 4, 4), &black); - Ok(()) - }) - .unwrap(); - s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); - s.execute("view.colorSamplers.add", json!({"x": 0, "y": 0})).unwrap(); - s.execute("image.rotation.arbitrary", json!({"angle": angle, "direction": direction})).unwrap(); - assert_eq!(s.take_samplers_removed(), 0, "{angle} {direction}: the corner point stays on the canvas"); - let p = points(&mut s); - assert_eq!(p.len(), 2, "{angle} {direction}: the corner point stays on the canvas"); - assert_eq!(p[0]["position"], json!(at), "{angle} {direction}"); - assert_eq!(p[0]["rgb"], json!([0, 0, 0]), "{angle} {direction}"); - } - } - - #[test] - fn a_rotated_crop_moves_points() { - // The crop frame is centred on the point's pixel; turned 90° that pixel lands at (10, 9). - let mut s = session(); - s.edit("paint", |doc, _| { - let surf = doc.layers[0].surface_mut().unwrap(); - let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); - surf.fill_rect(Rect::new(50, 40, 51, 41), &black); - Ok(()) - }) - .unwrap(); - s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); - s.execute("image.crop", json!({"x": 40, "y": 30, "width": 20, "height": 20, "angle": 90})).unwrap(); - let p = points(&mut s); - assert_eq!(p.len(), 1); - assert_eq!(p[0]["position"], json!([10.0, 9.0])); - assert_eq!(p[0]["rgb"], json!([0, 0, 0])); - } - - #[test] - fn a_crop_to_a_target_size_scales_points() { - // The crop resamples the 20 x 20 area to 40 x 40: the point (10, 10 after the shift; 10, 9 - // turned 90°, as in `a_rotated_crop_moves_points`) doubles. - for (angle, at) in [(None, [20.0, 20.0]), (Some(90), [20.0, 18.0])] { - let mut s = session(); - s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); - let mut p = json!({"x": 40, "y": 30, "width": 20, "height": 20, "targetWidth": 40, "targetHeight": 40}); - if let Some(a) = angle { - p["angle"] = json!(a); - } - s.execute("image.crop", p).unwrap(); - let p = points(&mut s); - assert_eq!(p.len(), 1, "angle {angle:?}"); - assert_eq!(p[0]["position"], json!(at), "angle {angle:?}"); - assert_eq!(s.take_samplers_removed(), 0, "angle {angle:?}"); - } - } - - #[test] - fn bad_params_and_no_document_are_errors_not_panics() { - let mut s = Session::new(); - for id in ["view.colorSamplers.add", "view.colorSamplers.move", "view.colorSamplers.delete", "view.colorSamplers.clear", "view.colorSamplers.list"] { - assert!(s.execute(id, json!({})).is_err(), "{id} without a document"); - } - let mut s = session(); - for (id, p) in [ - ("view.colorSamplers.add", json!({})), - ("view.colorSamplers.add", json!({"x": "a", "y": 1})), - ("view.colorSamplers.add", json!({"x": 1e300, "y": 1})), - ("view.colorSamplers.add", json!({"x": 5, "y": f64::NAN})), - ("view.colorSamplers.add", json!({"x": -1, "y": 5})), - ("view.colorSamplers.add", json!({"x": 5, "y": 1000})), - ("view.colorSamplers.move", json!({"index": 0, "x": 1, "y": 1})), - ("view.colorSamplers.delete", json!({"index": 0})), - ("view.colorSamplers.delete", json!({})), - ("view.colorSamplers.move", json!({"index": 4_294_967_296u64, "x": 1, "y": 1})), - ] { - assert!(matches!(s.execute(id, p.clone()), Err(EngineError::BadParams { .. }) | Err(EngineError::Other(_))), "{id} {p}"); - } - // An off-canvas point is refused and places nothing. - assert!(points(&mut s).is_empty()); - } - - /// The Info panel and the Color Picker read CMYK through one conversion (#8101): the - /// colour-managed `rgb_to_cmyk`, not a naive formula that disagrees with it by tens of percent. - #[test] - fn device_cmyk_agrees_with_the_color_picker_conversion() { - for rgb in [[1.0, 1.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.5, 0.5, 0.5], [0.2, 0.6, 0.9], [1.0, 0.93, 0.0]] { - let picker = photocraft_color::convert::rgb_to_cmyk(rgb).map(|v| (v * 100.0).round() as i32); - assert_eq!(device_cmyk(rgb[0], rgb[1], rgb[2]), picker, "{rgb:?}"); - } - assert_eq!(device_cmyk(1.0, 1.0, 1.0), [0, 0, 0, 0]); - assert_ne!(device_cmyk(1.0, 0.0, 0.0), [0, 100, 100, 0], "pure red is not the naive 0/100/100/0"); - } - - /// 32-bit samples can lie outside 0..1 (or be NaN); the CMYK readout clamps them like the RGB - /// readout does instead of reporting K:-50% or C:120% (#4191). - #[test] - fn device_cmyk_clamps_out_of_range_and_nan_samples() { - assert_eq!(device_cmyk(1.5, 1.5, 1.5), [0, 0, 0, 0]); - assert_eq!(device_cmyk(2.0, 0.0, 0.0), device_cmyk(1.0, 0.0, 0.0)); - let in_range = |c: [i32; 4]| c.iter().all(|v| (0..=100).contains(v)); - for (r, g, b) in [(-0.2, 0.5, 0.5), (-1.0, -1.0, -1.0), (f32::NAN, 0.5, 0.5), (f32::NAN, f32::NAN, f32::NAN), (f32::INFINITY, f32::NEG_INFINITY, 0.5)] { - let c = device_cmyk(r, g, b); - assert!(in_range(c), "{r} {g} {b} -> {c:?}"); - } - assert_eq!(device_cmyk(f32::NAN, f32::NAN, f32::NAN), device_cmyk(0.0, 0.0, 0.0)); - } - - #[test] - fn hdr_pixel_on_a_32_bit_document_reads_in_range() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "depth": 32, "background": "white"})).unwrap(); - s.edit("paint", |doc, _| { - let surf = doc.layers[0].surface_mut().unwrap(); - let hdr = photocraft_raster::from_rgba(&surf.format(), [2.0, 2.0, 2.0, 1.0]); - surf.fill_rect(Rect::new(3, 3, 4, 4), &hdr); - Ok(()) - }) - .unwrap(); - let r = s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); - assert_eq!(r["point"]["rgb"], json!([255, 255, 255])); - assert_eq!(r["point"]["cmyk"], json!([0, 0, 0, 0])); - } - - #[test] - fn points_work_at_every_depth_and_mode() { - for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("grayscale", 8), ("cmyk", 8), ("lab", 8)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 20, "height": 20, "mode": mode, "depth": depth, "background": "white"})).unwrap(); - let r = s.execute("view.colorSamplers.add", json!({"x": 10, "y": 10})).unwrap(); - let rgb = r["point"]["rgb"].as_array().unwrap(); - assert_eq!(rgb.len(), 3); - assert!(rgb.iter().all(|v| v.as_i64().is_some_and(|n| (0..=255).contains(&n))), "{mode} {depth}: {rgb:?}"); - } - } - - /// The mode and depth only affect the composite the readout samples, not the point model. - #[test] - fn document_helpers_are_not_disturbed() { - let mut d = Document::new("t", Size::new(4, 4), ColorMode::Rgb, SampleType::U8); - d.layers.push(Layer::raster("Background", d.pixel_format())); - assert_eq!(pixel(&d, 0.0, 0.0), Some([0.0, 0.0])); - assert_eq!(pixel(&d, 3.9, 3.9), Some([3.0, 3.0])); - assert_eq!(pixel(&d, 4.0, 0.0), None); - } -} +mod tests; diff --git a/crates/engine/src/sampler_cmds/tests.rs b/crates/engine/src/sampler_cmds/tests.rs new file mode 100644 index 0000000000..14efb3e524 --- /dev/null +++ b/crates/engine/src/sampler_cmds/tests.rs @@ -0,0 +1,353 @@ +use super::*; +use photocraft_color::{ColorMode, SampleType}; +use photocraft_doc::{Layer, Size}; +use photocraft_geom::Rect; + +/// A 100×80 white document. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 80, "background": "white"})).unwrap(); + s +} + +fn list(s: &mut Session) -> Value { + s.execute("view.colorSamplers.list", json!({})).unwrap() +} + +fn points(s: &mut Session) -> Vec { + list(s)["samplers"].as_array().cloned().unwrap_or_default() +} + +#[test] +fn add_reads_the_composite_pixel_and_lists_it() { + let mut s = session(); + let r = s.execute("view.colorSamplers.add", json!({"x": 5, "y": 6})).unwrap(); + assert_eq!(r["index"], 0); + assert_eq!(r["count"], 1); + assert_eq!(r["point"]["number"], 1); + assert_eq!(r["point"]["position"], json!([5.0, 6.0])); + assert_eq!(r["point"]["rgb"], json!([255, 255, 255])); + assert_eq!(r["point"]["cmyk"], json!([0, 0, 0, 0])); + let l = list(&mut s); + assert_eq!(l["max"], 10); + assert_eq!(l["samplers"].as_array().unwrap().len(), 1); + assert_eq!(l["samplers"][0]["position"], json!([5.0, 6.0])); +} + +#[test] +fn fractional_clicks_floor_to_the_pixel() { + let mut s = session(); + let r = s.execute("view.colorSamplers.add", json!({"x": 5.9, "y": 6.1})).unwrap(); + assert_eq!(r["point"]["position"], json!([5.0, 6.0])); +} + +#[test] +fn add_reads_an_actual_painted_pixel() { + // A black pixel at (3, 3) of an otherwise white document. + let mut s = session(); + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(3, 3, 4, 4), &black); + Ok(()) + }) + .unwrap(); + let r = s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); + assert_eq!(r["point"]["rgb"], json!([0, 0, 0])); + assert_eq!(r["point"]["cmyk"], json!(device_cmyk(0.0, 0.0, 0.0)), "the profile's black, not the naive 0/0/0/100"); + // Painting over the point changes its readout (the list is computed live). + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let red = photocraft_raster::from_rgba(&surf.format(), [1.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(3, 3, 4, 4), &red); + Ok(()) + }) + .unwrap(); + assert_eq!(points(&mut s)[0]["rgb"], json!([255, 0, 0])); +} + +#[test] +fn ten_points_then_the_limit() { + let mut s = session(); + for i in 0..10 { + s.execute("view.colorSamplers.add", json!({"x": i, "y": 0})).unwrap(); + } + assert_eq!(points(&mut s).len(), 10); + let err = s.execute("view.colorSamplers.add", json!({"x": 20, "y": 0})).unwrap_err().to_string(); + assert!(err.contains("limit"), "{err}"); + assert_eq!(points(&mut s).len(), 10); +} + +#[test] +fn move_delete_and_clear() { + let mut s = session(); + s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 50, "y": 50})).unwrap(); + let r = s.execute("view.colorSamplers.move", json!({"index": 0, "x": 10, "y": 20})).unwrap(); + assert_eq!(r["point"]["position"], json!([10.0, 20.0])); + assert_eq!(points(&mut s)[0]["position"], json!([10.0, 20.0])); + s.execute("view.colorSamplers.delete", json!({"index": 1})).unwrap(); + assert_eq!(points(&mut s).len(), 1); + // The remaining point is the moved #1. + assert_eq!(points(&mut s)[0]["position"], json!([10.0, 20.0])); + let r = s.execute("view.colorSamplers.clear", json!({})).unwrap(); + assert_eq!(r["deleted"], 1); + assert!(points(&mut s).is_empty()); +} + +#[test] +fn placing_and_moving_add_no_history_and_change_no_pixels() { + let mut s = session(); + let before = s.active().unwrap().doc.layers[0].surface().unwrap().pixel(5, 5); + let past = s.active().unwrap().history.past_len(); + s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); + s.execute("view.colorSamplers.move", json!({"index": 0, "x": 9, "y": 9})).unwrap(); + s.execute("view.colorSamplers.delete", json!({"index": 0})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), past, "no history steps"); + assert_eq!(s.active().unwrap().doc.layers[0].surface().unwrap().pixel(5, 5), before, "no pixels changed"); + assert!(!s.active().unwrap().is_dirty(), "a clean document stays clean"); +} + +#[test] +fn points_belong_to_their_document() { + let mut s = session(); + s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 40, "background": "white"})).unwrap(); + assert!(points(&mut s).is_empty(), "the new document has no points"); + s.execute("document.activate", json!({"document": 0})).unwrap(); + assert_eq!(points(&mut s).len(), 1, "the first document kept its point"); + // Closing the second document leaves the first's points alone. + s.execute("file.close", json!({"document": 1})).unwrap(); + assert_eq!(points(&mut s).len(), 1); + // Closing the first discards its points with it. + s.execute("file.close", json!({"document": 0})).unwrap(); + assert!(s.execute("view.colorSamplers.list", json!({})).is_err(), "no document open"); +} + +#[test] +fn a_crop_drops_points_outside_the_new_canvas() { + let mut s = session(); + s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 50, "y": 50})).unwrap(); + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let p = points(&mut s); + assert_eq!(p.len(), 1, "the outside point was removed"); + assert_eq!(p[0]["position"], json!([5.0, 5.0])); + assert_eq!(s.take_samplers_removed(), 1, "one removed point reported"); + assert_eq!(s.take_samplers_removed(), 0, "reported once"); +} + +#[test] +fn a_crop_moves_points_with_their_pixels() { + // A crop from a non-zero origin moves the canvas: the point follows its pixel. + let mut s = session(); + s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); + s.execute("image.crop", json!({"x": 40, "y": 30, "width": 20, "height": 20})).unwrap(); + let p = points(&mut s); + assert_eq!(p.len(), 1); + assert_eq!(p[0]["position"], json!([10.0, 10.0]), "moved by (-40, -30)"); + assert_eq!(s.take_samplers_removed(), 0, "nothing removed"); +} + +#[test] +fn a_canvas_size_shift_moves_points() { + // Canvas Size anchored bottom-right shifts the canvas origin by (+20, +20). + let mut s = session(); + s.execute("view.colorSamplers.add", json!({"x": 30, "y": 30})).unwrap(); + s.execute("image.canvasSize", json!({"width": 120, "height": 100, "anchor": "bottomRight"})).unwrap(); + let p = points(&mut s); + assert_eq!(p.len(), 1); + assert_eq!(p[0]["position"], json!([50.0, 50.0]), "moved by the canvas shift"); +} + +#[test] +fn a_right_angle_rotation_moves_points() { + // 90° clockwise about the centre: pixel (x, y) of the 100×80 canvas goes to (79 - y, x). + let mut s = session(); + s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); + s.execute("image.rotation.arbitrary", json!({"angle": 90, "direction": "cw"})).unwrap(); + let p = points(&mut s); + assert_eq!(p.len(), 1); + let pos = p[0]["position"].as_array().unwrap(); + let (x, y) = (pos[0].as_f64().unwrap(), pos[1].as_f64().unwrap()); + assert!((x - 39.0).abs() < 1e-6 && (y - 50.0).abs() < 1e-6, "{pos:?}"); +} + +#[test] +fn flips_and_right_angle_turns_keep_points_on_their_pixel() { + use crate::canvas_geom::Turn; + for (id, turn) in [ + ("image.imageRotation.flipCanvasHorizontal", Turn::FlipHorizontal), + ("image.imageRotation.flipCanvasVertical", Turn::FlipVertical), + ("image.imageRotation.180", Turn::Rotate180), + ("image.imageRotation.90cw", Turn::Cw90), + ("image.imageRotation.90ccw", Turn::Ccw90), + ] { + // A black pixel at (3, 3) of a white 100×80 document, with a point on it. + let mut s = session(); + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(3, 3, 4, 4), &black); + Ok(()) + }) + .unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); + s.execute(id, json!({})).unwrap(); + let (x, y) = turn.pixel_map(100, 80)(3, 3); + let p = points(&mut s); + assert_eq!(p.len(), 1, "{id}"); + assert_eq!(p[0]["position"], json!([f64::from(x), f64::from(y)]), "{id}"); + assert_eq!(p[0]["rgb"], json!([0, 0, 0]), "{id}"); + } +} + +#[test] +fn an_arbitrary_rotation_keeps_points_on_their_pixel() { + // The pixel at (3, 3) of the 100×80 document, and where each turn moves it. + for (angle, direction, at) in [(90, "cw", [76.0, 3.0]), (90, "ccw", [3.0, 96.0]), (180, "cw", [96.0, 76.0])] { + let mut s = session(); + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(3, 3, 4, 4), &black); + Ok(()) + }) + .unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 0, "y": 0})).unwrap(); + s.execute("image.rotation.arbitrary", json!({"angle": angle, "direction": direction})).unwrap(); + assert_eq!(s.take_samplers_removed(), 0, "{angle} {direction}: the corner point stays on the canvas"); + let p = points(&mut s); + assert_eq!(p.len(), 2, "{angle} {direction}: the corner point stays on the canvas"); + assert_eq!(p[0]["position"], json!(at), "{angle} {direction}"); + assert_eq!(p[0]["rgb"], json!([0, 0, 0]), "{angle} {direction}"); + } +} + +#[test] +fn a_rotated_crop_moves_points() { + // The crop frame is centred on the point's pixel; turned 90° that pixel lands at (10, 9). + let mut s = session(); + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let black = photocraft_raster::from_rgba(&surf.format(), [0.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(50, 40, 51, 41), &black); + Ok(()) + }) + .unwrap(); + s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); + s.execute("image.crop", json!({"x": 40, "y": 30, "width": 20, "height": 20, "angle": 90})).unwrap(); + let p = points(&mut s); + assert_eq!(p.len(), 1); + assert_eq!(p[0]["position"], json!([10.0, 9.0])); + assert_eq!(p[0]["rgb"], json!([0, 0, 0])); +} + +#[test] +fn a_crop_to_a_target_size_scales_points() { + // The crop resamples the 20 x 20 area to 40 x 40: the point (10, 10 after the shift; 10, 9 + // turned 90°, as in `a_rotated_crop_moves_points`) doubles. + for (angle, at) in [(None, [20.0, 20.0]), (Some(90), [20.0, 18.0])] { + let mut s = session(); + s.execute("view.colorSamplers.add", json!({"x": 50, "y": 40})).unwrap(); + let mut p = json!({"x": 40, "y": 30, "width": 20, "height": 20, "targetWidth": 40, "targetHeight": 40}); + if let Some(a) = angle { + p["angle"] = json!(a); + } + s.execute("image.crop", p).unwrap(); + let p = points(&mut s); + assert_eq!(p.len(), 1, "angle {angle:?}"); + assert_eq!(p[0]["position"], json!(at), "angle {angle:?}"); + assert_eq!(s.take_samplers_removed(), 0, "angle {angle:?}"); + } +} + +#[test] +fn bad_params_and_no_document_are_errors_not_panics() { + let mut s = Session::new(); + for id in ["view.colorSamplers.add", "view.colorSamplers.move", "view.colorSamplers.delete", "view.colorSamplers.clear", "view.colorSamplers.list"] { + assert!(s.execute(id, json!({})).is_err(), "{id} without a document"); + } + let mut s = session(); + for (id, p) in [ + ("view.colorSamplers.add", json!({})), + ("view.colorSamplers.add", json!({"x": "a", "y": 1})), + ("view.colorSamplers.add", json!({"x": 1e300, "y": 1})), + ("view.colorSamplers.add", json!({"x": 5, "y": f64::NAN})), + ("view.colorSamplers.add", json!({"x": -1, "y": 5})), + ("view.colorSamplers.add", json!({"x": 5, "y": 1000})), + ("view.colorSamplers.move", json!({"index": 0, "x": 1, "y": 1})), + ("view.colorSamplers.delete", json!({"index": 0})), + ("view.colorSamplers.delete", json!({})), + ("view.colorSamplers.move", json!({"index": 4_294_967_296u64, "x": 1, "y": 1})), + ] { + assert!(matches!(s.execute(id, p.clone()), Err(EngineError::BadParams { .. }) | Err(EngineError::Other(_))), "{id} {p}"); + } + // An off-canvas point is refused and places nothing. + assert!(points(&mut s).is_empty()); +} + +/// The Info panel and the Color Picker read CMYK through one conversion (#8101): the +/// colour-managed `rgb_to_cmyk`, not a naive formula that disagrees with it by tens of percent. +#[test] +fn device_cmyk_agrees_with_the_color_picker_conversion() { + for rgb in [[1.0, 1.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.5, 0.5, 0.5], [0.2, 0.6, 0.9], [1.0, 0.93, 0.0]] { + let picker = photocraft_color::convert::rgb_to_cmyk(rgb).map(|v| (v * 100.0).round() as i32); + assert_eq!(device_cmyk(rgb[0], rgb[1], rgb[2]), picker, "{rgb:?}"); + } + assert_eq!(device_cmyk(1.0, 1.0, 1.0), [0, 0, 0, 0]); + assert_ne!(device_cmyk(1.0, 0.0, 0.0), [0, 100, 100, 0], "pure red is not the naive 0/100/100/0"); +} + +/// 32-bit samples can lie outside 0..1 (or be NaN); the CMYK readout clamps them like the RGB +/// readout does instead of reporting K:-50% or C:120% (#4191). +#[test] +fn device_cmyk_clamps_out_of_range_and_nan_samples() { + assert_eq!(device_cmyk(1.5, 1.5, 1.5), [0, 0, 0, 0]); + assert_eq!(device_cmyk(2.0, 0.0, 0.0), device_cmyk(1.0, 0.0, 0.0)); + let in_range = |c: [i32; 4]| c.iter().all(|v| (0..=100).contains(v)); + for (r, g, b) in [(-0.2, 0.5, 0.5), (-1.0, -1.0, -1.0), (f32::NAN, 0.5, 0.5), (f32::NAN, f32::NAN, f32::NAN), (f32::INFINITY, f32::NEG_INFINITY, 0.5)] { + let c = device_cmyk(r, g, b); + assert!(in_range(c), "{r} {g} {b} -> {c:?}"); + } + assert_eq!(device_cmyk(f32::NAN, f32::NAN, f32::NAN), device_cmyk(0.0, 0.0, 0.0)); +} + +#[test] +fn hdr_pixel_on_a_32_bit_document_reads_in_range() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": 32, "background": "white"})).unwrap(); + s.edit("paint", |doc, _| { + let surf = doc.layers[0].surface_mut().unwrap(); + let hdr = photocraft_raster::from_rgba(&surf.format(), [2.0, 2.0, 2.0, 1.0]); + surf.fill_rect(Rect::new(3, 3, 4, 4), &hdr); + Ok(()) + }) + .unwrap(); + let r = s.execute("view.colorSamplers.add", json!({"x": 3, "y": 3})).unwrap(); + assert_eq!(r["point"]["rgb"], json!([255, 255, 255])); + assert_eq!(r["point"]["cmyk"], json!([0, 0, 0, 0])); +} + +#[test] +fn points_work_at_every_depth_and_mode() { + for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("grayscale", 8), ("cmyk", 8), ("lab", 8)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 20, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + let r = s.execute("view.colorSamplers.add", json!({"x": 10, "y": 10})).unwrap(); + let rgb = r["point"]["rgb"].as_array().unwrap(); + assert_eq!(rgb.len(), 3); + assert!(rgb.iter().all(|v| v.as_i64().is_some_and(|n| (0..=255).contains(&n))), "{mode} {depth}: {rgb:?}"); + } +} + +/// The mode and depth only affect the composite the readout samples, not the point model. +#[test] +fn document_helpers_are_not_disturbed() { + let mut d = Document::new("t", Size::new(4, 4), ColorMode::Rgb, SampleType::U8); + d.layers.push(Layer::raster("Background", d.pixel_format())); + assert_eq!(pixel(&d, 0.0, 0.0), Some([0.0, 0.0])); + assert_eq!(pixel(&d, 3.9, 3.9), Some([3.0, 3.0])); + assert_eq!(pixel(&d, 4.0, 0.0), None); +} From 356baadcf7d6c7c2985a34a90a7ccb226e5abf3a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:12 +0000 Subject: [PATCH 032/259] refactor(engine): move layer_style.rs tests to layer_style/tests.rs --- crates/engine/src/layer_style.rs | 583 +------------------------ crates/engine/src/layer_style/tests.rs | 580 ++++++++++++++++++++++++ 2 files changed, 581 insertions(+), 582 deletions(-) create mode 100644 crates/engine/src/layer_style/tests.rs diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs index 2527f402f3..7d0e337d34 100644 --- a/crates/engine/src/layer_style.rs +++ b/crates/engine/src/layer_style.rs @@ -1154,585 +1154,4 @@ fn delete_effect(s: &mut Session, p: &Value, effect: &Value) -> Result { } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s - } - - fn effects(s: &Session) -> Vec { - let d = s.active().unwrap(); - d.doc.layer(d.active_layer.unwrap()).unwrap().effects.items.clone() - } - - #[test] - fn bevel_command_sets_technique_contour_and_texture() { - let mut s = session(); - s.execute("layer.layerStyle.bevelEmboss", json!({"style": "pillow", "technique": "chiselHard", "contour": true, "contourRange": 70, "texture": "Bubbles", "textureDepth": -200, "textureInvert": true})).unwrap(); - let fx = effects(&s); - let Effect::BevelEmboss(b) = &fx[0] else { panic!("{fx:?}") }; - assert_eq!((b.style, b.technique), (photocraft_doc::BevelStyle::PillowEmboss, BevelTechnique::ChiselHard)); - assert!((b.contour.as_ref().unwrap().range - 0.7).abs() < 1e-6); - let t = b.texture.as_ref().unwrap(); - assert_eq!((t.name.as_str(), t.depth, t.invert), ("Bubbles", -2.0, true)); - } - - /// #6698 review: a glow's Range runs 1..100 %, as its slider and Photoshop's do. A 0 is - /// held at the 1 % floor, and 100 is kept. - #[test] - fn glow_range_is_held_to_one_through_one_hundred() { - for kind in ["outerGlow", "innerGlow"] { - for (sent, kept) in [(0.0, 0.01), (-5.0, 0.01), (1.0, 0.01), (50.0, 0.5), (100.0, 1.0), (250.0, 1.0)] { - let mut s = session(); - s.execute(&format!("layer.layerStyle.{kind}"), json!({"range": sent})).unwrap(); - let range = match &effects(&s)[0] { - Effect::OuterGlow(g) | Effect::InnerGlow(g) => g.range, - other => panic!("{other:?}"), - }; - assert!((range - kept).abs() < 1e-6, "{kind} range {sent} kept as {range}, not {kept}"); - } - } - let doc = |id: &str| specs().into_iter().find(|c| c.id == id).map(|c| c.params).unwrap_or_default(); - assert!(doc("layer.layerStyle.outerGlow").contains(r#""range":1..100=50"#)); - assert!(doc("layer.layerStyle.innerGlow").contains(r#""range":1..100=50"#)); - } - - #[test] - fn bevel_gloss_anti_alias_is_a_param() { - let mut s = session(); - s.execute("layer.layerStyle.bevelEmboss", json!({"glossContour": "Ring - Double", "glossAntiAlias": true})).unwrap(); - let Effect::BevelEmboss(b) = &effects(&s)[0] else { panic!() }; - assert!(b.gloss_anti_alias); - s.execute("layer.layerStyle.bevelEmboss", json!({"glossAntiAlias": false})).unwrap(); - let Effect::BevelEmboss(b) = &effects(&s)[0] else { panic!() }; - assert!(!b.gloss_anti_alias); - } - - #[test] - fn stroke_overprint_is_a_param() { - let mut s = session(); - s.execute("layer.layerStyle.stroke", json!({"size": 4, "overprint": true})).unwrap(); - let Effect::Stroke(st) = &effects(&s)[0] else { panic!() }; - assert!(st.overprint); - s.execute("layer.layerStyle.stroke", json!({"overprint": false})).unwrap(); - let Effect::Stroke(st) = &effects(&s)[0] else { panic!() }; - assert!(!st.overprint); - } - - #[test] - fn bevel_shading_fields_are_independent_and_preserved_on_partial_edits() { - let mut s = session(); - s.execute( - "layer.layerStyle.bevelEmboss", - json!({ - "highlightBlend": "Normal", "highlightColor": "#ff0000", "highlightOpacity": 35, - "shadowBlend": "Color Burn", "shadowColor": "#0000ff", "shadowOpacity": 60 - }), - ) - .unwrap(); - let fx = effects(&s); - let Effect::BevelEmboss(bevel) = &fx[0] else { panic!("{fx:?}") }; - assert_eq!(bevel.highlight.blend, BlendMode::Normal); - assert_eq!(bevel.highlight_color, Color::rgb(1.0, 0.0, 0.0)); - assert!((bevel.highlight.opacity - 0.35).abs() < 0.001); - assert_eq!(bevel.shadow.blend, BlendMode::ColorBurn); - assert_eq!(bevel.shadow_color, Color::rgb(0.0, 0.0, 1.0)); - assert!((bevel.shadow.opacity - 0.60).abs() < 0.001); - - let mut changed = fx[0].clone(); - overlay_effect(&mut changed, &json!({"size": 12})); - let Effect::BevelEmboss(partial) = &changed else { panic!("expected bevel") }; - assert_eq!(partial.highlight, bevel.highlight); - assert_eq!(partial.highlight_color, bevel.highlight_color); - assert_eq!(partial.shadow, bevel.shadow); - assert_eq!(partial.shadow_color, bevel.shadow_color); - - overlay_effect(&mut changed, &json!({"highlightOpacity": 120, "shadowOpacity": -30})); - let Effect::BevelEmboss(limits) = &changed else { panic!("expected bevel") }; - assert_eq!((limits.highlight.opacity, limits.shadow.opacity), (1.0, 0.0)); - } - - #[test] - fn every_style_command_adds_its_effect() { - for kind in ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "bevelEmboss", "satin"] { - let mut s = session(); - s.execute(&format!("layer.layerStyle.{kind}"), json!({})).unwrap(); - let fx = effects(&s); - assert_eq!(fx.len(), 1, "{kind}"); - assert!(fx[0].enabled()); - } - } - - /// #1543: a Satin or Bevel & Emboss size or softness far past Photoshop's range rendered a - /// blur kernel of 2^62 taps ("capacity overflow"), or ran for minutes at 1e6. The blur width - /// is capped at the effect reach, so the document still renders, quickly. - #[test] - fn oversized_satin_and_bevel_sizes_stay_saveable_and_render() { - for (cmd, p, accepted) in [ - ("satin", json!({"size": 1e308}), false), - ("satin", json!({"size": 1e30}), true), - ("satin", json!({"size": 1_000_000}), true), - ("bevelEmboss", json!({"size": 1e308}), false), - ("bevelEmboss", json!({"soften": 1e308}), false), - ("bevelEmboss", json!({"size": 1e30, "soften": 1e30}), true), - ("bevelEmboss", json!({"size": 1_000_000, "soften": 1_000_000}), true), - ] { - let mut s = session(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - let result = s.execute(&format!("layer.layerStyle.{cmd}"), p.clone()); - if accepted { - result.unwrap(); - } else { - assert!(matches!(result, Err(EngineError::BadParams { .. }))); - } - photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()).unwrap(); - let start = std::time::Instant::now(); - s.execute("document.pixel", json!({"x": 0, "y": 0})).unwrap_or_else(|e| panic!("{cmd} {p}: {e}")); - assert!(start.elapsed().as_secs() < 20, "{cmd} {p}: {:?}", start.elapsed()); - } - } - - #[test] - fn params_are_applied_and_replace_or_add() { - let mut s = session(); - s.execute("layer.layerStyle.stroke", json!({"size": 7, "position": "inside", "color": "#00ff00", "opacity": 50})).unwrap(); - match &effects(&s)[0] { - Effect::Stroke(st) => { - assert_eq!(st.size, 7.0); - assert_eq!(st.position, StrokePosition::Inside); - assert_eq!(st.common.opacity, 0.5); - assert_eq!(st.paint, FxPaint::Color(Color::rgb(0.0, 1.0, 0.0))); - } - other => panic!("{other:?}"), - } - s.execute("layer.layerStyle.stroke", json!({"size": 2})).unwrap(); - assert_eq!(effects(&s).len(), 1, "replaces"); - s.execute("layer.layerStyle.stroke", json!({"size": 4, "add": true})).unwrap(); - assert_eq!(effects(&s).len(), 2, "adds a second instance"); - s.execute("layer.layerStyle.dropShadow", json!({"blend": "normal", "distance": 12})).unwrap(); - assert!(matches!(&effects(&s)[2], Effect::DropShadow(sh) if sh.common.blend == BlendMode::Normal && sh.distance == 12.0)); - } - - /// The gradient overlay and the gradient stroke keep their scale in Photoshop's 10-150 %. - #[test] - fn gradient_overlay_and_stroke_scale_stay_in_range() { - let scale = |s: &Session| match &effects(s)[0] { - Effect::GradientOverlay { gradient, .. } => gradient.scale, - Effect::Stroke(st) => match &st.paint { - FxPaint::Gradient(g) => g.scale, - other => panic!("{other:?}"), - }, - other => panic!("{other:?}"), - }; - for (cmd, p, want) in [ - ("gradientOverlay", json!({"scale": 1000}), 1.5), - ("gradientOverlay", json!({"scale": 1}), 0.1), - ("gradientOverlay", json!({"scale": 80}), 0.8), - ("stroke", json!({"from": "#000000", "to": "#ffffff", "scale": -50}), 0.1), - ("stroke", json!({"from": "#000000", "to": "#ffffff", "scale": 0}), 0.1), - ("stroke", json!({"from": "#000000", "to": "#ffffff", "scale": 400}), 1.5), - ] { - let mut s = session(); - s.execute(&format!("layer.layerStyle.{cmd}"), p.clone()).unwrap(); - assert!((scale(&s) - want).abs() < 1e-6, "{cmd} {p}: {}", scale(&s)); - } - // Beyond f32 range is refused before any edit (commands.rs), not clamped. - let err = session().execute("layer.layerStyle.gradientOverlay", json!({"scale": 1e39})).unwrap_err(); - assert!(format!("{err:?}").contains("finite 32-bit"), "{err:?}"); - } - - #[test] - fn clear_and_undo() { - let mut s = session(); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); - s.execute("layer.layerStyle.clear", json!({})).unwrap(); - assert!(effects(&s).is_empty()); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(effects(&s).len(), 1); - } - - fn pixel(s: &mut Session) -> Vec { - serde_json::from_value(s.execute("document.pixel", json!({"x": 3, "y": 3})).unwrap()).unwrap() - } - - fn list_enabled(s: &Session) -> bool { - let d = s.active().unwrap(); - d.doc.layer(d.active_layer.unwrap()).unwrap().effects.enabled - } - - /// #3648: the Layers panel's "Effects" eye (`layer.setEffectsVisible`) must survive a Layer - /// Style dialog OK: the dialog's whole-list replace re-creates the items but leaves the - /// list's master switch alone. - #[test] - fn replacing_the_list_keeps_a_disabled_effect_list_disabled() { - let mut s = session(); - s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#0000ff"})).unwrap(); - let shown = pixel(&mut s); - s.execute("layer.setEffectsVisible", json!({"visible": false})).unwrap(); - let hidden = pixel(&mut s); - assert_ne!(hidden, shown, "the eye really hides the style"); - let r = s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "colorOverlay", "params": {"color": "#00ff00"}}]})).unwrap(); - assert_eq!(r["effects"], 1, "the list itself is updated"); - assert!(!list_enabled(&s), "the whole-list switch survives the edit"); - assert!(effects(&s)[0].enabled(), "the effect's own state is updated"); - assert_eq!(pixel(&mut s), hidden, "a disabled list still draws nothing"); - s.execute("layer.setEffectsVisible", json!({"visible": true})).unwrap(); - assert_ne!(pixel(&mut s), hidden, "re-showing the list draws the edited effect"); - } - - /// #3648: adding or replacing one effect (`layer.layerStyle.`) also leaves the master - /// switch as the user left it. - #[test] - fn set_effect_keeps_a_disabled_effect_list_disabled() { - let mut s = session(); - s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#0000ff"})).unwrap(); - s.execute("layer.setEffectsVisible", json!({"visible": false})).unwrap(); - let hidden = pixel(&mut s); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#00ff00"})).unwrap(); - assert!(!list_enabled(&s), "the whole-list switch survives the edit"); - assert!(effects(&s)[0].enabled(), "the effect's own state is updated"); - assert_eq!(pixel(&mut s), hidden, "a disabled list still draws nothing"); - } - - /// A layer that never had effects keeps the default: its first effect shows. - #[test] - fn a_first_effect_shows_on_a_layer_that_never_had_effects() { - let mut s = session(); - s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); - let plain = pixel(&mut s); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#00ff00"})).unwrap(); - assert!(list_enabled(&s), "a fresh effects list defaults to enabled"); - assert_ne!(pixel(&mut s), plain, "the first effect renders"); - } - - /// #3102: an effect row dropped on the Delete button deletes only that effect, in one step. - #[test] - fn clear_one_effect_by_index() { - let mut s = session(); - s.execute("layer.layerStyle.dropShadow", json!({})).unwrap(); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); - let layer = s.active().unwrap().active_layer.unwrap().0; - s.execute("layer.layerStyle.clear", json!({"layer": layer, "effect": 0})).unwrap(); - assert!(matches!(effects(&s)[..], [Effect::ColorOverlay { .. }])); - for bad in [json!({"effect": 5}), json!({"effect": -1}), json!({"effect": "x"}), json!({"effect": 0, "layer": u64::MAX})] { - assert!(s.execute("layer.layerStyle.clear", bad).is_err()); - } - assert_eq!(effects(&s).len(), 1, "bad params change nothing"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(effects(&s).len(), 2); - } - - #[test] - fn color_overlay_renders() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); - let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 3, "y": 3})).unwrap()).unwrap(); - assert!(px[0] > 0.99 && px[1] < 0.01, "{px:?}"); - } - - #[test] - fn gradient_styles_parse() { - assert_eq!(gradient_style("Radial"), GradientStyle::Radial); - assert_eq!(gradient_style("diamond"), GradientStyle::Diamond); - assert_eq!(gradient_style("?"), GradientStyle::Linear); - } - - fn snapshot(fx: &Effect) -> Value { - serde_json::to_value(fx).unwrap() - } - - #[test] - fn every_kind_has_factory_defaults() { - for kind in - ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "satin", "bevelEmboss"] - { - assert!(effect_defaults(kind).as_object().is_some_and(|o| !o.is_empty()), "{kind}"); - assert!(effect_from_params(kind, &json!({})).is_some(), "{kind}"); - } - assert!(effect_from_params("nope", &json!({})).is_none()); - } - - #[test] - fn replace_builds_edits_and_preserves_instances() { - let mut s = session(); - // Two strokes: the first edits a snapshot (params overlay), the second is fresh. - let first = Effect::Stroke(StrokeFx { - common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), - size: 7.0, - position: StrokePosition::Outside, - paint: FxPaint::Gradient(Gradient { stops: vec![(0.0, Color::rgb(0.0, 0.0, 1.0)), (1.0, Color::WHITE)], ..Gradient::default() }), - overprint: false, - }); - let r = s - .execute( - "layer.layerStyle.replace", - json!({"effects": [ - {"kind": "stroke", "fx": snapshot(&first), "params": {"opacity": 50}}, - {"kind": "stroke", "params": {"size": 2, "color": "#ffffff"}}, - ]}), - ) - .unwrap(); - assert_eq!(r["effects"], 2); - let fx = effects(&s); - assert_eq!(fx.len(), 2, "order preserved"); - match (&fx[0], &fx[1]) { - (Effect::Stroke(a), Effect::Stroke(b)) => { - assert_eq!(a.common.opacity, 0.5); - // The overlay must not clobber the gradient paint it doesn't model. - assert!(matches!(&a.paint, FxPaint::Gradient(g) if g.stops.len() == 2 && g.stops[0].1 == Color::rgb(0.0, 0.0, 1.0))); - assert_eq!(b.size, 2.0); - assert_eq!(b.paint, FxPaint::Color(Color::rgb(1.0, 1.0, 1.0))); - } - other => panic!("{other:?}"), - } - // Replacing with an empty list clears the layer. - s.execute("layer.layerStyle.replace", json!({"effects": []})).unwrap(); - assert!(effects(&s).is_empty()); - } - - #[test] - fn replace_rejects_bad_entries_gracefully() { - let mut s = session(); - let stroke = Effect::Stroke(StrokeFx { - common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), - size: 3.0, - position: StrokePosition::Outside, - paint: FxPaint::Color(Color::BLACK), - overprint: false, - }); - for p in [ - json!({}), - json!({"effects": "nope"}), - json!({"effects": [{"params": {}}]}), - json!({"effects": [{"kind": "nope"}]}), - json!({"effects": [{"kind": "stroke", "fx": {"Bogus": {}}}]}), - json!({"effects": [{"kind": "stroke", "fx": 3}]}), - json!({"effects": [{"kind": "dropShadow", "fx": snapshot(&stroke)}]}), - json!({"effects": [{"kind": "stroke", "fx": snapshot(&stroke), "params": "nope"}]}), - ] { - assert!(s.execute("layer.layerStyle.replace", p).is_err()); - } - // A long list is refused, not run. - let many: Vec<_> = (0..257).map(|_| json!({"kind": "stroke"})).collect(); - assert!(s.execute("layer.layerStyle.replace", json!({"effects": many})).is_err()); - assert!(effects(&s).is_empty(), "nothing was applied"); - } - - #[test] - fn contour_and_noise_params_edit_existing_effects() { - let mut s = session(); - s.execute("layer.layerStyle.dropShadow", json!({})).unwrap(); - let before = effects(&s); - let Effect::DropShadow(_) = &before[0] else { panic!("{before:?}") }; - let fx0 = snapshot(&before[0]); - // Unknown contour names are carried, not clobbered to Linear. - s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "dropShadow", "fx": fx0, "params": {"contour": "Cone", "noise": 30}}]})).unwrap(); - let fx = effects(&s); - let Effect::DropShadow(sh) = &fx[0] else { panic!("{fx:?}") }; - assert_eq!(sh.contour, builtin_contour("Cone").unwrap(), "known preset applies"); - assert!((sh.noise - 0.3).abs() < 1e-6, "noise in percent"); - // An imported contour with an unknown name survives the same round trip. - let imported = Contour::Custom { - name: "Photoshop contour".into(), - points: vec![photocraft_doc::adjust::CurvePoint { input: 0.0, output: 1.0 }, photocraft_doc::adjust::CurvePoint { input: 1.0, output: 0.0 }], - corners: vec![], - }; - let mut carried = before[0].clone(); - if let Effect::DropShadow(c) = &mut carried { - c.contour = imported.clone(); - } - overlay_effect(&mut carried, &json!({"contour": "Photoshop contour"})); - let Effect::DropShadow(after) = &carried else { panic!() }; - assert_eq!(after.contour, imported); - // Linear applies by name. - let mut back = carried; - overlay_effect(&mut back, &json!({"contour": "Linear"})); - let Effect::DropShadow(lin) = &back else { panic!() }; - assert_eq!(lin.contour, Contour::Linear); - } - - #[test] - fn contour_presets_match_photoshop() { - // Photoshop 27.11, measured through Satin: Cone and Cone − Inverted Satins are identical, - // and Gaussian reads 0.36 at 0.5 through Satin but 0.64 as the preset curve (glows, gloss). - let lut = |name: &str| { - let Some(Contour::Custom { points, corners, .. }) = builtin_contour(name) else { panic!("{name}") }; - photocraft_compose::adjust::contour_curve_lut(&points, &corners) - }; - let satin = |name: &str| photocraft_compose::effects::satin_lut(&builtin_contour(name).unwrap()).unwrap(); - let at = |l: &[f32], x: f32| l[(x * (l.len() - 1) as f32).round() as usize]; - let (cone, inverted) = (satin("Cone"), satin("Cone - Inverted")); - for x in [0.1, 0.25, 0.5, 0.8] { - assert!((at(&cone, x) - at(&inverted, x)).abs() < 0.03, "{x}: {} vs {}", at(&cone, x), at(&inverted, x)); - } - assert!((at(&satin("Gaussian"), 0.5) - 0.36).abs() < 0.04, "{}", at(&satin("Gaussian"), 0.5)); - assert!((at(&lut("Gaussian"), 0.5) - 0.64).abs() < 0.03, "{}", at(&lut("Gaussian"), 0.5)); - assert!((at(&lut("Cove - Deep"), 0.0) - 0.26).abs() < 0.02, "Cove - Deep starts above zero"); - } - - #[test] - fn gradient_overlay_method_matches_photoshop() { - // Photoshop 27.11, Classic Gradient Overlay #000000 → #ffffff (Smoothness 100 %): 0.037 at - // t = 1/16 and 0.5 in the middle; straight stops would give 0.0625. - let mut s = session(); - s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#000000", "to": "#ffffff", "method": "classic"})).unwrap(); - let Effect::GradientOverlay { gradient, .. } = &effects(&s)[0] else { panic!() }; - let at = |t: f32| { - let w = gradient.stops.windows(2).find(|w| t >= w[0].0 && t <= w[1].0).unwrap(); - let u = (t - w[0].0) / (w[1].0 - w[0].0).max(1e-6); - w[0].1.to_rgb()[0] + (w[1].1.to_rgb()[0] - w[0].1.to_rgb()[0]) * u - }; - assert!((at(1.0 / 16.0) - 0.037).abs() < 0.004, "{}", at(1.0 / 16.0)); - assert!((at(0.5) - 0.5).abs() < 0.004, "{}", at(0.5)); - // Without a method the two stops stay as they are. - s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#000000", "to": "#ffffff", "add": true})).unwrap(); - let plain = effects(&s).iter().filter(|e| matches!(e, Effect::GradientOverlay { gradient, .. } if gradient.stops.len() == 2)).count(); - assert_eq!(plain, 1, "the added overlay keeps its two stops"); - } - - #[test] - fn contour_presets_and_custom_curves_apply_in_one_undo_step() { - let mut s = session(); - // Picking Cone: the preset's own curve, its points corners, in one undo step. - s.execute("layer.layerStyle.dropShadow", json!({"contour": "Cone", "antiAlias": true})).unwrap(); - let Effect::DropShadow(sh) = &effects(&s)[0] else { panic!() }; - assert_eq!(sh.contour, builtin_contour("Cone").unwrap()); - assert!(sh.contour.is_corner(1) && sh.anti_alias); - let Contour::Custom { points, corners, .. } = &sh.contour else { panic!() }; - let lut = photocraft_compose::adjust::contour_curve_lut(points, corners); - let at = |x: f32| lut[(x * (lut.len() - 1) as f32).round() as usize]; - // Photoshop's measured Cone: 0 at both ends, a 0.99 peak at 0.5, symmetric. - assert!(at(0.0).abs() < 1e-3 && at(1.0).abs() < 1e-3 && at(0.5) > 0.98, "a Λ: {} {} {}", at(0.0), at(0.5), at(1.0)); - assert!((at(0.25) - at(0.75)).abs() < 0.03, "symmetric: {} vs {}", at(0.25), at(0.75)); - assert_eq!(contour_param(&sh.contour), json!("Cone")); - s.execute("edit.undo", json!({})).unwrap(); - assert!(effects(&s).is_empty(), "one undo removes it"); - - // An edited curve (the Contour Editor's param) round trips exactly, in every effect. - let curve = json!({"name": "Mine", "points": [[0.0, 0.2], [0.4, 0.9], [1.0, 0.1]], "corners": [false, true, false]}); - for kind in ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "satin"] { - let mut fx = fresh_effect(kind).unwrap(); - overlay_effect(&mut fx, &json!({"contour": curve})); - let v = values(&fx, "contour"); - assert_eq!(v, curve, "{kind}"); - } - let mut bevel = fresh_effect("bevelEmboss").unwrap(); - overlay_effect(&mut bevel, &json!({"contour": true, "contourName": curve, "glossContour": "Ring"})); - let Effect::BevelEmboss(b) = &bevel else { panic!() }; - assert_eq!(contour_param(&b.contour.as_ref().unwrap().contour), curve); - assert_eq!(b.gloss_contour, builtin_contour("Ring").unwrap()); - // Malformed curves leave the contour alone. - for bad in [json!({"points": [[0.5, 0.5]]}), json!({"points": [[0.0, "x"], [1.0, 1.0]]}), json!({"points": "no"}), json!(7)] { - let mut fx = fresh_effect("dropShadow").unwrap(); - overlay_effect(&mut fx, &json!({"contour": bad})); - assert_eq!(values(&fx, "contour"), json!("Linear")); - } - - // `.shc` round trip of a curve with a corner. - let mine = contour_from_param(&curve).unwrap(); - let back = contours_from_shc(&contour_to_shc(&mine).unwrap()).unwrap(); - let back = contour_from_param(&back[0]).unwrap(); - let Contour::Custom { points, corners, .. } = &back else { panic!() }; - assert_eq!(corners, &vec![false, true, false]); - assert!((points[1].input - 0.4).abs() < 0.003 && (points[1].output - 0.9).abs() < 0.003, "{points:?}"); - } - - fn values(fx: &Effect, key: &str) -> Value { - let c = match fx { - Effect::DropShadow(s) | Effect::InnerShadow(s) => &s.contour, - Effect::OuterGlow(g) | Effect::InnerGlow(g) => &g.contour, - Effect::Satin(s) => &s.contour, - _ => panic!("{key}: no contour"), - }; - contour_param(c) - } - - #[test] - fn make_default_then_reset_restores_it() { - let mut s = session(); - // Factory default first: Reset without a saved default gives the factory set. - let r = s.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap(); - assert_eq!(r["user"], json!(false)); - assert_eq!(r["params"]["size"], json!(1)); - s.execute( - "layer.layerStyle.makeDefault", - json!({"kind": "stroke", "params": {"size": 9, "position": "inside", "blend": "Normal", "opacity": 100, "color": "#000000"}}), - ) - .unwrap(); - let r = s.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap(); - assert_eq!(r["user"], json!(true)); - assert_eq!(r["params"]["size"], json!(9)); - // Bad kinds and params are graceful errors. - assert!(s.execute("layer.layerStyle.makeDefault", json!({"kind": "nope", "params": {}})).is_err()); - assert!(s.execute("layer.layerStyle.makeDefault", json!({"kind": "stroke", "params": "x"})).is_err()); - assert!(s.execute("layer.layerStyle.defaultFor", json!({"kind": "nope"})).is_err()); - } - - /// #7765: a stroke built without params was red, while the dialog's factory default was - /// black. Both now give Photoshop's Reset to Default: 1 px, inside, Normal, 100 %, black. - #[test] - fn fresh_effects_match_the_dialog_factory_defaults() { - for kind in - ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "satin", "bevelEmboss"] - { - let bare = effect_from_params(kind, &json!({})).unwrap(); - let dialog = effect_from_params(kind, &effect_defaults(kind)).unwrap(); - assert_eq!(bare, dialog, "{kind}"); - } - let Some(Effect::Stroke(st)) = effect_from_params("stroke", &json!({})) else { panic!("no stroke") }; - assert_eq!((st.size, st.position, st.common.blend, st.common.opacity), (1.0, StrokePosition::Inside, BlendMode::Normal, 1.0)); - assert_eq!(st.paint, FxPaint::Color(Color::BLACK)); - } - - #[test] - fn layer_style_defaults_persist_with_presets() { - let mut s = session(); - s.execute("layer.layerStyle.makeDefault", json!({"kind": "stroke", "params": {"size": 9}})).unwrap(); - let blob = s.presets.to_json(&s); - let mut t = Session::new(); - t.load_presets_json(blob); - let r = t.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap(); - assert_eq!(r["user"], json!(true)); - assert_eq!(r["params"]["size"], json!(9)); - } - - #[test] - fn double_stroke_bands_render_and_survive_an_edit() { - // The manga/typesetting case (#157): a 7 px white stroke under a 3 px black one. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 48, "height": 48})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 16, "y": 16, "width": 16, "height": 16})).unwrap(); - s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000", "position": "outside"})).unwrap(); - s.execute("layer.layerStyle.stroke", json!({"size": 7, "color": "#ffffff", "position": "outside", "add": true})).unwrap(); - let px = |s: &mut Session, x: i32, y: i32| -> [f32; 4] { - let mut v: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()).unwrap(); - v.resize(4, 1.0); - [v[0], v[1], v[2], v[3]] - }; - // Bands from the square edge outward: 0..3 px black (the first stroke renders on top), - // 3..7 px white, then the white background. - assert!(px(&mut s, 24, 24)[0] < 0.1, "the square is black"); - assert!(px(&mut s, 24, 14)[0] < 0.1, "the first stroke covers the wider one"); - assert!(px(&mut s, 24, 11)[0] > 0.9, "the second stroke shows outside it"); - assert!(px(&mut s, 24, 5)[0] > 0.9, "background beyond both"); - // A dialog round trip (replace with the same snapshots) keeps both bands. - let before = px(&mut s, 24, 14); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let items = st.doc.layer(id).unwrap().effects.items.clone(); - let entries: Vec = items.iter().map(|fx| json!({"kind": "stroke", "fx": serde_json::to_value(fx).unwrap(), "params": {}})).collect(); - s.execute("layer.layerStyle.replace", json!({"layer": id.0, "effects": entries})).unwrap(); - assert_eq!(px(&mut s, 24, 14), before, "both strokes render identically after the round trip"); - } -} +mod tests; diff --git a/crates/engine/src/layer_style/tests.rs b/crates/engine/src/layer_style/tests.rs new file mode 100644 index 0000000000..95cc631cf5 --- /dev/null +++ b/crates/engine/src/layer_style/tests.rs @@ -0,0 +1,580 @@ +use super::*; +use serde_json::json; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +fn effects(s: &Session) -> Vec { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().effects.items.clone() +} + +#[test] +fn bevel_command_sets_technique_contour_and_texture() { + let mut s = session(); + s.execute("layer.layerStyle.bevelEmboss", json!({"style": "pillow", "technique": "chiselHard", "contour": true, "contourRange": 70, "texture": "Bubbles", "textureDepth": -200, "textureInvert": true})).unwrap(); + let fx = effects(&s); + let Effect::BevelEmboss(b) = &fx[0] else { panic!("{fx:?}") }; + assert_eq!((b.style, b.technique), (photocraft_doc::BevelStyle::PillowEmboss, BevelTechnique::ChiselHard)); + assert!((b.contour.as_ref().unwrap().range - 0.7).abs() < 1e-6); + let t = b.texture.as_ref().unwrap(); + assert_eq!((t.name.as_str(), t.depth, t.invert), ("Bubbles", -2.0, true)); +} + +/// #6698 review: a glow's Range runs 1..100 %, as its slider and Photoshop's do. A 0 is +/// held at the 1 % floor, and 100 is kept. +#[test] +fn glow_range_is_held_to_one_through_one_hundred() { + for kind in ["outerGlow", "innerGlow"] { + for (sent, kept) in [(0.0, 0.01), (-5.0, 0.01), (1.0, 0.01), (50.0, 0.5), (100.0, 1.0), (250.0, 1.0)] { + let mut s = session(); + s.execute(&format!("layer.layerStyle.{kind}"), json!({"range": sent})).unwrap(); + let range = match &effects(&s)[0] { + Effect::OuterGlow(g) | Effect::InnerGlow(g) => g.range, + other => panic!("{other:?}"), + }; + assert!((range - kept).abs() < 1e-6, "{kind} range {sent} kept as {range}, not {kept}"); + } + } + let doc = |id: &str| specs().into_iter().find(|c| c.id == id).map(|c| c.params).unwrap_or_default(); + assert!(doc("layer.layerStyle.outerGlow").contains(r#""range":1..100=50"#)); + assert!(doc("layer.layerStyle.innerGlow").contains(r#""range":1..100=50"#)); +} + +#[test] +fn bevel_gloss_anti_alias_is_a_param() { + let mut s = session(); + s.execute("layer.layerStyle.bevelEmboss", json!({"glossContour": "Ring - Double", "glossAntiAlias": true})).unwrap(); + let Effect::BevelEmboss(b) = &effects(&s)[0] else { panic!() }; + assert!(b.gloss_anti_alias); + s.execute("layer.layerStyle.bevelEmboss", json!({"glossAntiAlias": false})).unwrap(); + let Effect::BevelEmboss(b) = &effects(&s)[0] else { panic!() }; + assert!(!b.gloss_anti_alias); +} + +#[test] +fn stroke_overprint_is_a_param() { + let mut s = session(); + s.execute("layer.layerStyle.stroke", json!({"size": 4, "overprint": true})).unwrap(); + let Effect::Stroke(st) = &effects(&s)[0] else { panic!() }; + assert!(st.overprint); + s.execute("layer.layerStyle.stroke", json!({"overprint": false})).unwrap(); + let Effect::Stroke(st) = &effects(&s)[0] else { panic!() }; + assert!(!st.overprint); +} + +#[test] +fn bevel_shading_fields_are_independent_and_preserved_on_partial_edits() { + let mut s = session(); + s.execute( + "layer.layerStyle.bevelEmboss", + json!({ + "highlightBlend": "Normal", "highlightColor": "#ff0000", "highlightOpacity": 35, + "shadowBlend": "Color Burn", "shadowColor": "#0000ff", "shadowOpacity": 60 + }), + ) + .unwrap(); + let fx = effects(&s); + let Effect::BevelEmboss(bevel) = &fx[0] else { panic!("{fx:?}") }; + assert_eq!(bevel.highlight.blend, BlendMode::Normal); + assert_eq!(bevel.highlight_color, Color::rgb(1.0, 0.0, 0.0)); + assert!((bevel.highlight.opacity - 0.35).abs() < 0.001); + assert_eq!(bevel.shadow.blend, BlendMode::ColorBurn); + assert_eq!(bevel.shadow_color, Color::rgb(0.0, 0.0, 1.0)); + assert!((bevel.shadow.opacity - 0.60).abs() < 0.001); + + let mut changed = fx[0].clone(); + overlay_effect(&mut changed, &json!({"size": 12})); + let Effect::BevelEmboss(partial) = &changed else { panic!("expected bevel") }; + assert_eq!(partial.highlight, bevel.highlight); + assert_eq!(partial.highlight_color, bevel.highlight_color); + assert_eq!(partial.shadow, bevel.shadow); + assert_eq!(partial.shadow_color, bevel.shadow_color); + + overlay_effect(&mut changed, &json!({"highlightOpacity": 120, "shadowOpacity": -30})); + let Effect::BevelEmboss(limits) = &changed else { panic!("expected bevel") }; + assert_eq!((limits.highlight.opacity, limits.shadow.opacity), (1.0, 0.0)); +} + +#[test] +fn every_style_command_adds_its_effect() { + for kind in ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "bevelEmboss", "satin"] { + let mut s = session(); + s.execute(&format!("layer.layerStyle.{kind}"), json!({})).unwrap(); + let fx = effects(&s); + assert_eq!(fx.len(), 1, "{kind}"); + assert!(fx[0].enabled()); + } +} + +/// #1543: a Satin or Bevel & Emboss size or softness far past Photoshop's range rendered a +/// blur kernel of 2^62 taps ("capacity overflow"), or ran for minutes at 1e6. The blur width +/// is capped at the effect reach, so the document still renders, quickly. +#[test] +fn oversized_satin_and_bevel_sizes_stay_saveable_and_render() { + for (cmd, p, accepted) in [ + ("satin", json!({"size": 1e308}), false), + ("satin", json!({"size": 1e30}), true), + ("satin", json!({"size": 1_000_000}), true), + ("bevelEmboss", json!({"size": 1e308}), false), + ("bevelEmboss", json!({"soften": 1e308}), false), + ("bevelEmboss", json!({"size": 1e30, "soften": 1e30}), true), + ("bevelEmboss", json!({"size": 1_000_000, "soften": 1_000_000}), true), + ] { + let mut s = session(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let result = s.execute(&format!("layer.layerStyle.{cmd}"), p.clone()); + if accepted { + result.unwrap(); + } else { + assert!(matches!(result, Err(EngineError::BadParams { .. }))); + } + photocraft_format::save_to_bytes(&s.active().unwrap().doc, &Default::default()).unwrap(); + let start = std::time::Instant::now(); + s.execute("document.pixel", json!({"x": 0, "y": 0})).unwrap_or_else(|e| panic!("{cmd} {p}: {e}")); + assert!(start.elapsed().as_secs() < 20, "{cmd} {p}: {:?}", start.elapsed()); + } +} + +#[test] +fn params_are_applied_and_replace_or_add() { + let mut s = session(); + s.execute("layer.layerStyle.stroke", json!({"size": 7, "position": "inside", "color": "#00ff00", "opacity": 50})).unwrap(); + match &effects(&s)[0] { + Effect::Stroke(st) => { + assert_eq!(st.size, 7.0); + assert_eq!(st.position, StrokePosition::Inside); + assert_eq!(st.common.opacity, 0.5); + assert_eq!(st.paint, FxPaint::Color(Color::rgb(0.0, 1.0, 0.0))); + } + other => panic!("{other:?}"), + } + s.execute("layer.layerStyle.stroke", json!({"size": 2})).unwrap(); + assert_eq!(effects(&s).len(), 1, "replaces"); + s.execute("layer.layerStyle.stroke", json!({"size": 4, "add": true})).unwrap(); + assert_eq!(effects(&s).len(), 2, "adds a second instance"); + s.execute("layer.layerStyle.dropShadow", json!({"blend": "normal", "distance": 12})).unwrap(); + assert!(matches!(&effects(&s)[2], Effect::DropShadow(sh) if sh.common.blend == BlendMode::Normal && sh.distance == 12.0)); +} + +/// The gradient overlay and the gradient stroke keep their scale in Photoshop's 10-150 %. +#[test] +fn gradient_overlay_and_stroke_scale_stay_in_range() { + let scale = |s: &Session| match &effects(s)[0] { + Effect::GradientOverlay { gradient, .. } => gradient.scale, + Effect::Stroke(st) => match &st.paint { + FxPaint::Gradient(g) => g.scale, + other => panic!("{other:?}"), + }, + other => panic!("{other:?}"), + }; + for (cmd, p, want) in [ + ("gradientOverlay", json!({"scale": 1000}), 1.5), + ("gradientOverlay", json!({"scale": 1}), 0.1), + ("gradientOverlay", json!({"scale": 80}), 0.8), + ("stroke", json!({"from": "#000000", "to": "#ffffff", "scale": -50}), 0.1), + ("stroke", json!({"from": "#000000", "to": "#ffffff", "scale": 0}), 0.1), + ("stroke", json!({"from": "#000000", "to": "#ffffff", "scale": 400}), 1.5), + ] { + let mut s = session(); + s.execute(&format!("layer.layerStyle.{cmd}"), p.clone()).unwrap(); + assert!((scale(&s) - want).abs() < 1e-6, "{cmd} {p}: {}", scale(&s)); + } + // Beyond f32 range is refused before any edit (commands.rs), not clamped. + let err = session().execute("layer.layerStyle.gradientOverlay", json!({"scale": 1e39})).unwrap_err(); + assert!(format!("{err:?}").contains("finite 32-bit"), "{err:?}"); +} + +#[test] +fn clear_and_undo() { + let mut s = session(); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); + s.execute("layer.layerStyle.clear", json!({})).unwrap(); + assert!(effects(&s).is_empty()); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(effects(&s).len(), 1); +} + +fn pixel(s: &mut Session) -> Vec { + serde_json::from_value(s.execute("document.pixel", json!({"x": 3, "y": 3})).unwrap()).unwrap() +} + +fn list_enabled(s: &Session) -> bool { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().effects.enabled +} + +/// #3648: the Layers panel's "Effects" eye (`layer.setEffectsVisible`) must survive a Layer +/// Style dialog OK: the dialog's whole-list replace re-creates the items but leaves the +/// list's master switch alone. +#[test] +fn replacing_the_list_keeps_a_disabled_effect_list_disabled() { + let mut s = session(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#0000ff"})).unwrap(); + let shown = pixel(&mut s); + s.execute("layer.setEffectsVisible", json!({"visible": false})).unwrap(); + let hidden = pixel(&mut s); + assert_ne!(hidden, shown, "the eye really hides the style"); + let r = s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "colorOverlay", "params": {"color": "#00ff00"}}]})).unwrap(); + assert_eq!(r["effects"], 1, "the list itself is updated"); + assert!(!list_enabled(&s), "the whole-list switch survives the edit"); + assert!(effects(&s)[0].enabled(), "the effect's own state is updated"); + assert_eq!(pixel(&mut s), hidden, "a disabled list still draws nothing"); + s.execute("layer.setEffectsVisible", json!({"visible": true})).unwrap(); + assert_ne!(pixel(&mut s), hidden, "re-showing the list draws the edited effect"); +} + +/// #3648: adding or replacing one effect (`layer.layerStyle.`) also leaves the master +/// switch as the user left it. +#[test] +fn set_effect_keeps_a_disabled_effect_list_disabled() { + let mut s = session(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#0000ff"})).unwrap(); + s.execute("layer.setEffectsVisible", json!({"visible": false})).unwrap(); + let hidden = pixel(&mut s); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#00ff00"})).unwrap(); + assert!(!list_enabled(&s), "the whole-list switch survives the edit"); + assert!(effects(&s)[0].enabled(), "the effect's own state is updated"); + assert_eq!(pixel(&mut s), hidden, "a disabled list still draws nothing"); +} + +/// A layer that never had effects keeps the default: its first effect shows. +#[test] +fn a_first_effect_shows_on_a_layer_that_never_had_effects() { + let mut s = session(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + let plain = pixel(&mut s); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#00ff00"})).unwrap(); + assert!(list_enabled(&s), "a fresh effects list defaults to enabled"); + assert_ne!(pixel(&mut s), plain, "the first effect renders"); +} + +/// #3102: an effect row dropped on the Delete button deletes only that effect, in one step. +#[test] +fn clear_one_effect_by_index() { + let mut s = session(); + s.execute("layer.layerStyle.dropShadow", json!({})).unwrap(); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); + let layer = s.active().unwrap().active_layer.unwrap().0; + s.execute("layer.layerStyle.clear", json!({"layer": layer, "effect": 0})).unwrap(); + assert!(matches!(effects(&s)[..], [Effect::ColorOverlay { .. }])); + for bad in [json!({"effect": 5}), json!({"effect": -1}), json!({"effect": "x"}), json!({"effect": 0, "layer": u64::MAX})] { + assert!(s.execute("layer.layerStyle.clear", bad).is_err()); + } + assert_eq!(effects(&s).len(), 1, "bad params change nothing"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(effects(&s).len(), 2); +} + +#[test] +fn color_overlay_renders() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); + let px: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 3, "y": 3})).unwrap()).unwrap(); + assert!(px[0] > 0.99 && px[1] < 0.01, "{px:?}"); +} + +#[test] +fn gradient_styles_parse() { + assert_eq!(gradient_style("Radial"), GradientStyle::Radial); + assert_eq!(gradient_style("diamond"), GradientStyle::Diamond); + assert_eq!(gradient_style("?"), GradientStyle::Linear); +} + +fn snapshot(fx: &Effect) -> Value { + serde_json::to_value(fx).unwrap() +} + +#[test] +fn every_kind_has_factory_defaults() { + for kind in + ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "satin", "bevelEmboss"] + { + assert!(effect_defaults(kind).as_object().is_some_and(|o| !o.is_empty()), "{kind}"); + assert!(effect_from_params(kind, &json!({})).is_some(), "{kind}"); + } + assert!(effect_from_params("nope", &json!({})).is_none()); +} + +#[test] +fn replace_builds_edits_and_preserves_instances() { + let mut s = session(); + // Two strokes: the first edits a snapshot (params overlay), the second is fresh. + let first = Effect::Stroke(StrokeFx { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + size: 7.0, + position: StrokePosition::Outside, + paint: FxPaint::Gradient(Gradient { stops: vec![(0.0, Color::rgb(0.0, 0.0, 1.0)), (1.0, Color::WHITE)], ..Gradient::default() }), + overprint: false, + }); + let r = s + .execute( + "layer.layerStyle.replace", + json!({"effects": [ + {"kind": "stroke", "fx": snapshot(&first), "params": {"opacity": 50}}, + {"kind": "stroke", "params": {"size": 2, "color": "#ffffff"}}, + ]}), + ) + .unwrap(); + assert_eq!(r["effects"], 2); + let fx = effects(&s); + assert_eq!(fx.len(), 2, "order preserved"); + match (&fx[0], &fx[1]) { + (Effect::Stroke(a), Effect::Stroke(b)) => { + assert_eq!(a.common.opacity, 0.5); + // The overlay must not clobber the gradient paint it doesn't model. + assert!(matches!(&a.paint, FxPaint::Gradient(g) if g.stops.len() == 2 && g.stops[0].1 == Color::rgb(0.0, 0.0, 1.0))); + assert_eq!(b.size, 2.0); + assert_eq!(b.paint, FxPaint::Color(Color::rgb(1.0, 1.0, 1.0))); + } + other => panic!("{other:?}"), + } + // Replacing with an empty list clears the layer. + s.execute("layer.layerStyle.replace", json!({"effects": []})).unwrap(); + assert!(effects(&s).is_empty()); +} + +#[test] +fn replace_rejects_bad_entries_gracefully() { + let mut s = session(); + let stroke = Effect::Stroke(StrokeFx { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + size: 3.0, + position: StrokePosition::Outside, + paint: FxPaint::Color(Color::BLACK), + overprint: false, + }); + for p in [ + json!({}), + json!({"effects": "nope"}), + json!({"effects": [{"params": {}}]}), + json!({"effects": [{"kind": "nope"}]}), + json!({"effects": [{"kind": "stroke", "fx": {"Bogus": {}}}]}), + json!({"effects": [{"kind": "stroke", "fx": 3}]}), + json!({"effects": [{"kind": "dropShadow", "fx": snapshot(&stroke)}]}), + json!({"effects": [{"kind": "stroke", "fx": snapshot(&stroke), "params": "nope"}]}), + ] { + assert!(s.execute("layer.layerStyle.replace", p).is_err()); + } + // A long list is refused, not run. + let many: Vec<_> = (0..257).map(|_| json!({"kind": "stroke"})).collect(); + assert!(s.execute("layer.layerStyle.replace", json!({"effects": many})).is_err()); + assert!(effects(&s).is_empty(), "nothing was applied"); +} + +#[test] +fn contour_and_noise_params_edit_existing_effects() { + let mut s = session(); + s.execute("layer.layerStyle.dropShadow", json!({})).unwrap(); + let before = effects(&s); + let Effect::DropShadow(_) = &before[0] else { panic!("{before:?}") }; + let fx0 = snapshot(&before[0]); + // Unknown contour names are carried, not clobbered to Linear. + s.execute("layer.layerStyle.replace", json!({"effects": [{"kind": "dropShadow", "fx": fx0, "params": {"contour": "Cone", "noise": 30}}]})).unwrap(); + let fx = effects(&s); + let Effect::DropShadow(sh) = &fx[0] else { panic!("{fx:?}") }; + assert_eq!(sh.contour, builtin_contour("Cone").unwrap(), "known preset applies"); + assert!((sh.noise - 0.3).abs() < 1e-6, "noise in percent"); + // An imported contour with an unknown name survives the same round trip. + let imported = Contour::Custom { + name: "Photoshop contour".into(), + points: vec![photocraft_doc::adjust::CurvePoint { input: 0.0, output: 1.0 }, photocraft_doc::adjust::CurvePoint { input: 1.0, output: 0.0 }], + corners: vec![], + }; + let mut carried = before[0].clone(); + if let Effect::DropShadow(c) = &mut carried { + c.contour = imported.clone(); + } + overlay_effect(&mut carried, &json!({"contour": "Photoshop contour"})); + let Effect::DropShadow(after) = &carried else { panic!() }; + assert_eq!(after.contour, imported); + // Linear applies by name. + let mut back = carried; + overlay_effect(&mut back, &json!({"contour": "Linear"})); + let Effect::DropShadow(lin) = &back else { panic!() }; + assert_eq!(lin.contour, Contour::Linear); +} + +#[test] +fn contour_presets_match_photoshop() { + // Photoshop 27.11, measured through Satin: Cone and Cone − Inverted Satins are identical, + // and Gaussian reads 0.36 at 0.5 through Satin but 0.64 as the preset curve (glows, gloss). + let lut = |name: &str| { + let Some(Contour::Custom { points, corners, .. }) = builtin_contour(name) else { panic!("{name}") }; + photocraft_compose::adjust::contour_curve_lut(&points, &corners) + }; + let satin = |name: &str| photocraft_compose::effects::satin_lut(&builtin_contour(name).unwrap()).unwrap(); + let at = |l: &[f32], x: f32| l[(x * (l.len() - 1) as f32).round() as usize]; + let (cone, inverted) = (satin("Cone"), satin("Cone - Inverted")); + for x in [0.1, 0.25, 0.5, 0.8] { + assert!((at(&cone, x) - at(&inverted, x)).abs() < 0.03, "{x}: {} vs {}", at(&cone, x), at(&inverted, x)); + } + assert!((at(&satin("Gaussian"), 0.5) - 0.36).abs() < 0.04, "{}", at(&satin("Gaussian"), 0.5)); + assert!((at(&lut("Gaussian"), 0.5) - 0.64).abs() < 0.03, "{}", at(&lut("Gaussian"), 0.5)); + assert!((at(&lut("Cove - Deep"), 0.0) - 0.26).abs() < 0.02, "Cove - Deep starts above zero"); +} + +#[test] +fn gradient_overlay_method_matches_photoshop() { + // Photoshop 27.11, Classic Gradient Overlay #000000 → #ffffff (Smoothness 100 %): 0.037 at + // t = 1/16 and 0.5 in the middle; straight stops would give 0.0625. + let mut s = session(); + s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#000000", "to": "#ffffff", "method": "classic"})).unwrap(); + let Effect::GradientOverlay { gradient, .. } = &effects(&s)[0] else { panic!() }; + let at = |t: f32| { + let w = gradient.stops.windows(2).find(|w| t >= w[0].0 && t <= w[1].0).unwrap(); + let u = (t - w[0].0) / (w[1].0 - w[0].0).max(1e-6); + w[0].1.to_rgb()[0] + (w[1].1.to_rgb()[0] - w[0].1.to_rgb()[0]) * u + }; + assert!((at(1.0 / 16.0) - 0.037).abs() < 0.004, "{}", at(1.0 / 16.0)); + assert!((at(0.5) - 0.5).abs() < 0.004, "{}", at(0.5)); + // Without a method the two stops stay as they are. + s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#000000", "to": "#ffffff", "add": true})).unwrap(); + let plain = effects(&s).iter().filter(|e| matches!(e, Effect::GradientOverlay { gradient, .. } if gradient.stops.len() == 2)).count(); + assert_eq!(plain, 1, "the added overlay keeps its two stops"); +} + +#[test] +fn contour_presets_and_custom_curves_apply_in_one_undo_step() { + let mut s = session(); + // Picking Cone: the preset's own curve, its points corners, in one undo step. + s.execute("layer.layerStyle.dropShadow", json!({"contour": "Cone", "antiAlias": true})).unwrap(); + let Effect::DropShadow(sh) = &effects(&s)[0] else { panic!() }; + assert_eq!(sh.contour, builtin_contour("Cone").unwrap()); + assert!(sh.contour.is_corner(1) && sh.anti_alias); + let Contour::Custom { points, corners, .. } = &sh.contour else { panic!() }; + let lut = photocraft_compose::adjust::contour_curve_lut(points, corners); + let at = |x: f32| lut[(x * (lut.len() - 1) as f32).round() as usize]; + // Photoshop's measured Cone: 0 at both ends, a 0.99 peak at 0.5, symmetric. + assert!(at(0.0).abs() < 1e-3 && at(1.0).abs() < 1e-3 && at(0.5) > 0.98, "a Λ: {} {} {}", at(0.0), at(0.5), at(1.0)); + assert!((at(0.25) - at(0.75)).abs() < 0.03, "symmetric: {} vs {}", at(0.25), at(0.75)); + assert_eq!(contour_param(&sh.contour), json!("Cone")); + s.execute("edit.undo", json!({})).unwrap(); + assert!(effects(&s).is_empty(), "one undo removes it"); + + // An edited curve (the Contour Editor's param) round trips exactly, in every effect. + let curve = json!({"name": "Mine", "points": [[0.0, 0.2], [0.4, 0.9], [1.0, 0.1]], "corners": [false, true, false]}); + for kind in ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "satin"] { + let mut fx = fresh_effect(kind).unwrap(); + overlay_effect(&mut fx, &json!({"contour": curve})); + let v = values(&fx, "contour"); + assert_eq!(v, curve, "{kind}"); + } + let mut bevel = fresh_effect("bevelEmboss").unwrap(); + overlay_effect(&mut bevel, &json!({"contour": true, "contourName": curve, "glossContour": "Ring"})); + let Effect::BevelEmboss(b) = &bevel else { panic!() }; + assert_eq!(contour_param(&b.contour.as_ref().unwrap().contour), curve); + assert_eq!(b.gloss_contour, builtin_contour("Ring").unwrap()); + // Malformed curves leave the contour alone. + for bad in [json!({"points": [[0.5, 0.5]]}), json!({"points": [[0.0, "x"], [1.0, 1.0]]}), json!({"points": "no"}), json!(7)] { + let mut fx = fresh_effect("dropShadow").unwrap(); + overlay_effect(&mut fx, &json!({"contour": bad})); + assert_eq!(values(&fx, "contour"), json!("Linear")); + } + + // `.shc` round trip of a curve with a corner. + let mine = contour_from_param(&curve).unwrap(); + let back = contours_from_shc(&contour_to_shc(&mine).unwrap()).unwrap(); + let back = contour_from_param(&back[0]).unwrap(); + let Contour::Custom { points, corners, .. } = &back else { panic!() }; + assert_eq!(corners, &vec![false, true, false]); + assert!((points[1].input - 0.4).abs() < 0.003 && (points[1].output - 0.9).abs() < 0.003, "{points:?}"); +} + +fn values(fx: &Effect, key: &str) -> Value { + let c = match fx { + Effect::DropShadow(s) | Effect::InnerShadow(s) => &s.contour, + Effect::OuterGlow(g) | Effect::InnerGlow(g) => &g.contour, + Effect::Satin(s) => &s.contour, + _ => panic!("{key}: no contour"), + }; + contour_param(c) +} + +#[test] +fn make_default_then_reset_restores_it() { + let mut s = session(); + // Factory default first: Reset without a saved default gives the factory set. + let r = s.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap(); + assert_eq!(r["user"], json!(false)); + assert_eq!(r["params"]["size"], json!(1)); + s.execute( + "layer.layerStyle.makeDefault", + json!({"kind": "stroke", "params": {"size": 9, "position": "inside", "blend": "Normal", "opacity": 100, "color": "#000000"}}), + ) + .unwrap(); + let r = s.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap(); + assert_eq!(r["user"], json!(true)); + assert_eq!(r["params"]["size"], json!(9)); + // Bad kinds and params are graceful errors. + assert!(s.execute("layer.layerStyle.makeDefault", json!({"kind": "nope", "params": {}})).is_err()); + assert!(s.execute("layer.layerStyle.makeDefault", json!({"kind": "stroke", "params": "x"})).is_err()); + assert!(s.execute("layer.layerStyle.defaultFor", json!({"kind": "nope"})).is_err()); +} + +/// #7765: a stroke built without params was red, while the dialog's factory default was +/// black. Both now give Photoshop's Reset to Default: 1 px, inside, Normal, 100 %, black. +#[test] +fn fresh_effects_match_the_dialog_factory_defaults() { + for kind in + ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "satin", "bevelEmboss"] + { + let bare = effect_from_params(kind, &json!({})).unwrap(); + let dialog = effect_from_params(kind, &effect_defaults(kind)).unwrap(); + assert_eq!(bare, dialog, "{kind}"); + } + let Some(Effect::Stroke(st)) = effect_from_params("stroke", &json!({})) else { panic!("no stroke") }; + assert_eq!((st.size, st.position, st.common.blend, st.common.opacity), (1.0, StrokePosition::Inside, BlendMode::Normal, 1.0)); + assert_eq!(st.paint, FxPaint::Color(Color::BLACK)); +} + +#[test] +fn layer_style_defaults_persist_with_presets() { + let mut s = session(); + s.execute("layer.layerStyle.makeDefault", json!({"kind": "stroke", "params": {"size": 9}})).unwrap(); + let blob = s.presets.to_json(&s); + let mut t = Session::new(); + t.load_presets_json(blob); + let r = t.execute("layer.layerStyle.defaultFor", json!({"kind": "stroke"})).unwrap(); + assert_eq!(r["user"], json!(true)); + assert_eq!(r["params"]["size"], json!(9)); +} + +#[test] +fn double_stroke_bands_render_and_survive_an_edit() { + // The manga/typesetting case (#157): a 7 px white stroke under a 3 px black one. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 48, "height": 48})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 16, "y": 16, "width": 16, "height": 16})).unwrap(); + s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000", "position": "outside"})).unwrap(); + s.execute("layer.layerStyle.stroke", json!({"size": 7, "color": "#ffffff", "position": "outside", "add": true})).unwrap(); + let px = |s: &mut Session, x: i32, y: i32| -> [f32; 4] { + let mut v: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()).unwrap(); + v.resize(4, 1.0); + [v[0], v[1], v[2], v[3]] + }; + // Bands from the square edge outward: 0..3 px black (the first stroke renders on top), + // 3..7 px white, then the white background. + assert!(px(&mut s, 24, 24)[0] < 0.1, "the square is black"); + assert!(px(&mut s, 24, 14)[0] < 0.1, "the first stroke covers the wider one"); + assert!(px(&mut s, 24, 11)[0] > 0.9, "the second stroke shows outside it"); + assert!(px(&mut s, 24, 5)[0] > 0.9, "background beyond both"); + // A dialog round trip (replace with the same snapshots) keeps both bands. + let before = px(&mut s, 24, 14); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let items = st.doc.layer(id).unwrap().effects.items.clone(); + let entries: Vec = items.iter().map(|fx| json!({"kind": "stroke", "fx": serde_json::to_value(fx).unwrap(), "params": {}})).collect(); + s.execute("layer.layerStyle.replace", json!({"layer": id.0, "effects": entries})).unwrap(); + assert_eq!(px(&mut s, 24, 14), before, "both strokes render identically after the round trip"); +} From 88daf5e501cd11e4638bfb4e69b762119e19737f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:12 +0000 Subject: [PATCH 033/259] refactor(engine): move paint_cmds.rs tests to paint_cmds/tests.rs --- crates/engine/src/paint_cmds.rs | 334 +------------------------- crates/engine/src/paint_cmds/tests.rs | 331 +++++++++++++++++++++++++ 2 files changed, 332 insertions(+), 333 deletions(-) create mode 100644 crates/engine/src/paint_cmds/tests.rs diff --git a/crates/engine/src/paint_cmds.rs b/crates/engine/src/paint_cmds.rs index 91c0a87356..b0cf8e571b 100644 --- a/crates/engine/src/paint_cmds.rs +++ b/crates/engine/src/paint_cmds.rs @@ -196,336 +196,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_geom::Rect; - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); - s - } - - fn px(s: &Session, x: i32, y: i32) -> Vec { - let d = s.active().unwrap(); - d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y) - } - - /// A visible wall on the Background with an empty, active layer above it. - fn bucket_layers(depth: u32) -> (Session, photocraft_doc::LayerId) { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 20, "height": 10, "depth": depth, "background": "white"})).unwrap(); - let bottom = s.active().unwrap().active_layer.unwrap(); - s.edit("wall", |doc, _| { - doc.layer_mut(bottom).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 0, 11, 10), &[0.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - (s, bottom) - } - - /// The options bar's Mode reaches the fill: Multiply over grey, Clear erases, a bad name or - /// Pass Through is an error and changes nothing. - #[test] - fn bucket_mode_multiplies_clears_and_rejects_bad_names() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - let base = json!({"x": 1, "y": 1, "antiAlias": false, "tolerance": 0}); - let with = |extra: Value| { - let mut p = base.clone(); - p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); - p - }; - s.execute("paint.bucket", with(json!({"color": "#808080"}))).unwrap(); - s.execute("paint.bucket", with(json!({"color": "#ff0000", "mode": "multiply"}))).unwrap(); - let p = px(&s, 3, 3); - assert!((p[0] - 0.5).abs() < 0.01 && p[1] < 0.01 && p[3] > 0.99, "depth {depth}: {p:?}"); - for bad in [json!("passThrough"), json!("sparkle"), json!(3)] { - assert!(s.execute("paint.bucket", with(json!({"mode": bad}))).is_err(), "{bad}"); - } - assert_eq!(px(&s, 3, 3), p, "a refused mode paints nothing"); - s.execute("paint.bucket", with(json!({"mode": "Clear", "opacity": 50}))).unwrap(); - assert!((px(&s, 3, 3)[3] - 0.5).abs() < 0.01, "depth {depth}: half cleared"); - } - } - - #[test] - fn bucket_sample_all_layers_uses_visible_boundaries_at_all_depths() { - for depth in [8, 16, 32] { - for all in [None, Some(false), Some(true)] { - let (mut s, bottom) = bucket_layers(depth); - let before = s.active().unwrap().doc.layer(bottom).unwrap().clone(); - let mut p = json!({"x": 2, "y": 2, "color": "#ff0000", "antiAlias": false, "tolerance": 0}); - if let Some(all) = all { - p["sampleAllLayers"] = json!(all); - } - assert_eq!(s.execute("paint.bucket", p.clone()).unwrap()["filled"], true); - assert_eq!(px(&s, 5, 5), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}, all {all:?}"); - let beyond = if all == Some(true) { vec![0.0; 4] } else { vec![1.0, 0.0, 0.0, 1.0] }; - assert_eq!(px(&s, 15, 5), beyond, "depth {depth}, all {all:?}: sample flag controls the boundary"); - assert_eq!(s.active().unwrap().doc.layer(bottom).unwrap(), &before, "only the active layer is written"); - if all == Some(true) { - assert_eq!(px(&s, 10, 5), vec![0.0; 4], "wall itself is untouched"); - assert!(s.undo()); - p["contiguous"] = json!(false); - s.execute("paint.bucket", p).unwrap(); - assert_eq!(px(&s, 15, 5), vec![1.0, 0.0, 0.0, 1.0], "noncontiguous finds both white regions"); - assert_eq!(px(&s, 10, 5), vec![0.0; 4]); - assert!(s.undo()); - assert_eq!(s.execute("paint.bucket", json!({"x": -1, "y": 2, "sampleAllLayers": true})).unwrap()["filled"], false); - assert_eq!(px(&s, 5, 5), vec![0.0; 4], "an off-canvas sample does not fill the layer"); - } - } - } - } - - #[test] - fn bucket_sample_all_layers_ignores_hidden_layers() { - let (mut s, _) = bucket_layers(8); - s.edit("hidden wall", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - l.surface_mut().unwrap().fill_rect(Rect::new(4, 0, 5, 10), &[0.0, 0.0, 0.0, 1.0]); - l.visible = false; - Ok(()) - }) - .unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("paint.bucket", json!({"x": 2, "y": 2, "color": "#ff0000", "antiAlias": false, "tolerance": 0, "sampleAllLayers": true})).unwrap(); - assert_eq!(px(&s, 4, 5), vec![1.0, 0.0, 0.0, 1.0], "hidden wall does not bound the fill"); - assert_eq!(px(&s, 8, 5), vec![1.0, 0.0, 0.0, 1.0]); - assert_eq!(px(&s, 15, 5), vec![0.0; 4], "visible wall still bounds the fill"); - } - - #[test] - fn bucket_sample_all_layers_keeps_selection_opacity_and_history() { - for depth in [8, 16, 32] { - let (mut s, _) = bucket_layers(depth); - s.execute("select.rect", json!({"x": 0, "y": 2, "width": 20, "height": 6})).unwrap(); - s.edit("feather", |doc, _| { - doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 2, 4, 8), &[0.5]); - Ok(()) - }) - .unwrap(); - let selection = s.active().unwrap().doc.selection.clone(); - s.execute("paint.bucket", json!({"x": 2, "y": 5, "color": "#ff0000", "antiAlias": false, "tolerance": 0, "opacity": 50, "sampleAllLayers": true})) - .unwrap(); - let (feathered, full) = (px(&s, 2, 5), px(&s, 6, 5)); - assert!((feathered[3] - 0.25).abs() < 0.005 && (full[3] - 0.5).abs() < 0.005, "depth {depth}: selection coverage multiplies opacity"); - assert_eq!(full[..3], [1.0, 0.0, 0.0]); - assert_eq!(px(&s, 6, 1), vec![0.0; 4], "outside selection"); - assert_eq!(px(&s, 15, 5), vec![0.0; 4], "outside sampled region"); - assert_eq!(s.active().unwrap().history.undo_label(), Some("Paint Bucket")); - assert!(s.undo()); - assert_eq!(px(&s, 2, 5), vec![0.0; 4]); - assert_eq!(s.active().unwrap().doc.selection, selection); - assert!(s.redo()); - assert_eq!(px(&s, 2, 5), feathered); - assert_eq!(px(&s, 6, 5), full); - assert_eq!(s.active().unwrap().doc.selection, selection); - } - } - - #[test] - fn bucket_sample_all_layers_pattern_uses_the_same_region() { - let (mut s, _) = bucket_layers(8); - s.execute( - "paint.bucket", - json!({"x": 2, "y": 2, "contents": "pattern", "pattern": "Diagonal Lines", "antiAlias": false, "tolerance": 0, "sampleAllLayers": true}), - ) - .unwrap(); - let left: Vec = (0..10).map(|x| px(&s, x, 0)[0]).collect(); - assert!(left.iter().any(|&r| r < 0.3) && left.iter().any(|&r| r > 0.9), "pattern varies inside the region: {left:?}"); - assert_eq!(px(&s, 10, 5), vec![0.0; 4], "wall untouched"); - assert_eq!(px(&s, 15, 5), vec![0.0; 4], "region past the wall untouched"); - } - - #[test] - fn bucket_sample_all_layers_mask_and_channel_targets_keep_their_own_boundaries() { - for target in [json!("mask"), json!({"channel": 0}), json!("quickMask")] { - for all in [false, true] { - let (mut s, _) = bucket_layers(8); - match crate::channel_cmds::target_of(&json!({"target": target})) { - crate::channel_cmds::Target::Mask => { - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - } - crate::channel_cmds::Target::Alpha(_) => { - s.execute("channel.new", json!({"fill": "white"})).unwrap(); - } - crate::channel_cmds::Target::QuickMask => { - s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); - } - _ => panic!("expected a grayscale target"), - } - let p = json!({"x": 2, "y": 2, "color": "#000000", "antiAlias": false, "tolerance": 0, "target": target, "sampleAllLayers": all}); - s.edit("target wall", |doc, active| { - let area = doc.bounds(); - let (surf, _) = crate::channel_cmds::target_surface(doc, *active, &p).unwrap(); - surf.fill_rect(area, &[1.0]); - surf.fill_rect(Rect::new(5, 0, 6, 10), &[0.0]); - Ok(()) - }) - .unwrap(); - s.execute("paint.bucket", p.clone()).unwrap(); - let d = &s.active().unwrap().doc; - let surf = match crate::channel_cmds::target_of(&p) { - crate::channel_cmds::Target::Mask => &d.layer(s.active().unwrap().active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface, - crate::channel_cmds::Target::Alpha(i) => &d.channels[i].surface, - crate::channel_cmds::Target::QuickMask => &d.quick_mask.as_ref().unwrap().surface, - _ => panic!("expected a grayscale target"), - }; - assert_eq!(surf.sample_channel(2, 5, 0), 0.0, "{target}, all {all}: filled target"); - assert_eq!(surf.sample_channel(7, 5, 0), 1.0, "{target}, all {all}: stopped at target wall"); - assert_eq!(px(&s, 2, 5), vec![0.0; 4], "layer pixels remain untouched"); - } - } - } - - #[test] - fn bucket_fill_contiguous() { - let mut s = session(); - s.edit("wall", |doc, _| { - doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(10, 0, 11, 10), &[0.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("paint.bucket", json!({"x": 2, "y": 2, "color": "#ff0000", "antiAlias": false})).unwrap(); - assert_eq!(px(&s, 5, 5), vec![1.0, 0.0, 0.0, 1.0]); - assert_eq!(px(&s, 15, 5), vec![1.0, 1.0, 1.0, 1.0]); - s.execute("paint.bucket", json!({"x": 2, "y": 2, "color": "#0000ff", "contiguous": false, "antiAlias": false, "tolerance": 0})).unwrap(); - assert_eq!(px(&s, 5, 5), vec![0.0, 0.0, 1.0, 1.0]); - } - - /// #4196: the Paint Bucket and Edit > Stroke write a CMYK pick as its inks into a CMYK document, - /// not as its sRGB stand-in converted back (100/0/0/0 cyan would come out as about 100/28/0/17). - #[test] - fn bucket_and_stroke_write_a_cmyk_pick_as_its_inks() { - let cyan = [1.0f32, 0.0, 0.0, 0.0]; - let mut s = session(); - s.execute("image.mode.cmyk", json!({})).unwrap(); - let rgb = photocraft_color::convert::cmyk_to_rgb(cyan).map(|c| c.clamp(0.0, 1.0)); - s.execute("tools.setColors", json!({"foreground": rgb, "foregroundCmyk": cyan})).unwrap(); - let inks_at = |s: &Session, x: i32, y: i32| -> Vec { - let st = s.active().unwrap(); - let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - surf.read_region(Rect::new(x, y, x + 1, y + 1)).into_iter().take(4).collect() - }; - let is_cyan = |got: &[f32]| got.iter().zip(cyan).all(|(a, b)| (a - b).abs() < 0.02); - s.execute("paint.bucket", json!({"x": 2, "y": 2, "antiAlias": false})).unwrap(); - let got = inks_at(&s, 5, 5); - assert!(is_cyan(&got), "bucket: {got:?}"); - s.execute("select.all", json!({})).unwrap(); - s.execute("edit.stroke", json!({"width": 2, "location": "inside", "color": rgb})).unwrap(); - let got = inks_at(&s, 0, 5); - assert!(is_cyan(&got), "stroke: {got:?}"); - } - - #[test] - fn bucket_fills_with_a_pattern() { - // Paint Bucket with contents="pattern" flood-fills the region with a pattern, not a colour. - let mut s = session(); - s.edit("wall", |doc, _| { - doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(10, 0, 11, 10), &[0.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("paint.bucket", json!({"x": 2, "y": 2, "contents": "pattern", "pattern": "Diagonal Lines", "antiAlias": false, "tolerance": 0})).unwrap(); - // The filled region (left of the wall) now carries the pattern's light/dark variation, - // while the wall and the region past it are untouched. - let left: Vec<[f32; 4]> = (0..10) - .map(|x| { - let p = px(&s, x, 0); - [p[0], p[1], p[2], p[3]] - }) - .collect(); - assert!(left.iter().any(|p| p[0] < 0.3) && left.iter().any(|p| p[0] > 0.9), "pattern varies in the fill: {left:?}"); - assert_eq!(px(&s, 15, 5), vec![1.0, 1.0, 1.0, 1.0], "region past the wall untouched"); - } - - #[test] - fn gradient_tool_with_selection_and_reverse() { - let mut s = session(); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [20, 0], "colors": ["#000000", "#ffffff"]})).unwrap(); - assert!(px(&s, 0, 5)[0] < 0.05 && px(&s, 19, 5)[0] > 0.95); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [20, 0], "colors": ["#000000", "#ffffff"], "reverse": true})).unwrap(); - assert!(px(&s, 0, 5)[0] > 0.95); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 5, "height": 10})).unwrap(); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [0, 10], "colors": ["#ff0000"]})).unwrap(); - assert_eq!(px(&s, 2, 5)[..3], [1.0, 0.0, 0.0]); - assert!(px(&s, 10, 5)[1] > 0.4, "outside the selection untouched"); - assert!(s.execute("paint.gradient", json!({"from": [0, 0]})).is_err()); - } - - #[test] - fn gradient_dither_breaks_banding() { - // A flat gradient (same colour both ends) is perfectly smooth with dither off, and gains - // per-pixel noise with dither on (which breaks 8-bit banding). - let run = |dither: bool| { - let mut s = session(); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [19, 0], "colors": [[0.5, 0.5, 0.5, 1.0], [0.5, 0.5, 0.5, 1.0]], "dither": dither})) - .unwrap(); - (0..19).map(|x| px(&s, x, 5)[0]).collect::>() - }; - let smooth = run(false); - assert!(smooth.iter().all(|&v| v == smooth[0]), "no dither: perfectly flat"); - let noisy = run(true); - assert!(noisy.windows(2).any(|w| w[0] != w[1]), "dither: per-pixel variation"); - } - - /// The two commands under test, each painting #808080 over a white document. - fn grey_fill(cmd: &str, opacity: Value) -> Value { - match cmd { - "paint.bucket" => json!({"x": 2, "y": 2, "color": "#808080", "opacity": opacity}), - _ => json!({"from": [0, 0], "to": [19, 0], "colors": ["#808080", "#808080"], "dither": false, "opacity": opacity}), - } - } - - fn white(depth: u32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 20, "height": 10, "depth": depth, "background": "white"})).unwrap(); - s - } - - /// Issue #4167: an opacity above 100 overshot the blend (200 painted near-black on white). - #[test] - fn bucket_and_gradient_clamp_opacity_like_the_magic_eraser() { - for cmd in ["paint.bucket", "paint.gradient"] { - for depth in [8, 16, 32] { - let mut full = white(depth); - full.execute(cmd, grey_fill(cmd, json!(100))).unwrap(); - let expected = px(&full, 5, 5); - assert!((expected[0] - 128.0 / 255.0).abs() < 0.01, "{cmd} depth {depth}: 100% paints #808080, got {expected:?}"); - for over in [200.0, 1e9] { - let mut s = white(depth); - s.execute(cmd, grey_fill(cmd, json!(over))).unwrap(); - assert_eq!(px(&s, 5, 5), expected, "{cmd} depth {depth}: opacity {over} clamps to 100"); - } - let (mut low, mut one) = (white(depth), white(depth)); - low.execute(cmd, grey_fill(cmd, json!(-50))).unwrap(); - one.execute(cmd, grey_fill(cmd, json!(1))).unwrap(); - assert_eq!(px(&low, 5, 5), px(&one, 5, 5), "{cmd} depth {depth}: opacity below 1 clamps to 1"); - assert!(px(&low, 5, 5).iter().all(|v| (0.0..=1.0).contains(v)), "{cmd} depth {depth}: no overshoot"); - } - } - } - - #[test] - fn bucket_and_gradient_reject_non_numeric_opacity_without_editing() { - for cmd in ["paint.bucket", "paint.gradient"] { - for bad in [json!("50"), json!(true), json!([50]), json!({"v": 50})] { - let mut s = white(8); - let (before, steps) = (px(&s, 5, 5), s.active().unwrap().history.past_len()); - let err = s.execute(cmd, grey_fill(cmd, bad.clone())).unwrap_err(); - assert!(matches!(err, EngineError::BadParams { .. }), "{cmd} {bad}: {err:?}"); - assert_eq!(px(&s, 5, 5), before, "{cmd} {bad}: pixels unchanged"); - assert_eq!(s.active().unwrap().history.past_len(), steps, "{cmd} {bad}: no history step"); - } - // An explicit null keeps the default (100%), like the Magic Eraser. - let mut s = white(8); - s.execute(cmd, grey_fill(cmd, Value::Null)).unwrap(); - assert!((px(&s, 5, 5)[0] - 128.0 / 255.0).abs() < 0.01, "{cmd}: null opacity is 100%"); - } - } -} +mod tests; diff --git a/crates/engine/src/paint_cmds/tests.rs b/crates/engine/src/paint_cmds/tests.rs new file mode 100644 index 0000000000..a2d11d3e3c --- /dev/null +++ b/crates/engine/src/paint_cmds/tests.rs @@ -0,0 +1,331 @@ +use super::*; +use photocraft_geom::Rect; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + s +} + +fn px(s: &Session, x: i32, y: i32) -> Vec { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y) +} + +/// A visible wall on the Background with an empty, active layer above it. +fn bucket_layers(depth: u32) -> (Session, photocraft_doc::LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10, "depth": depth, "background": "white"})).unwrap(); + let bottom = s.active().unwrap().active_layer.unwrap(); + s.edit("wall", |doc, _| { + doc.layer_mut(bottom).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 0, 11, 10), &[0.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + (s, bottom) +} + +/// The options bar's Mode reaches the fill: Multiply over grey, Clear erases, a bad name or +/// Pass Through is an error and changes nothing. +#[test] +fn bucket_mode_multiplies_clears_and_rejects_bad_names() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let base = json!({"x": 1, "y": 1, "antiAlias": false, "tolerance": 0}); + let with = |extra: Value| { + let mut p = base.clone(); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + s.execute("paint.bucket", with(json!({"color": "#808080"}))).unwrap(); + s.execute("paint.bucket", with(json!({"color": "#ff0000", "mode": "multiply"}))).unwrap(); + let p = px(&s, 3, 3); + assert!((p[0] - 0.5).abs() < 0.01 && p[1] < 0.01 && p[3] > 0.99, "depth {depth}: {p:?}"); + for bad in [json!("passThrough"), json!("sparkle"), json!(3)] { + assert!(s.execute("paint.bucket", with(json!({"mode": bad}))).is_err(), "{bad}"); + } + assert_eq!(px(&s, 3, 3), p, "a refused mode paints nothing"); + s.execute("paint.bucket", with(json!({"mode": "Clear", "opacity": 50}))).unwrap(); + assert!((px(&s, 3, 3)[3] - 0.5).abs() < 0.01, "depth {depth}: half cleared"); + } +} + +#[test] +fn bucket_sample_all_layers_uses_visible_boundaries_at_all_depths() { + for depth in [8, 16, 32] { + for all in [None, Some(false), Some(true)] { + let (mut s, bottom) = bucket_layers(depth); + let before = s.active().unwrap().doc.layer(bottom).unwrap().clone(); + let mut p = json!({"x": 2, "y": 2, "color": "#ff0000", "antiAlias": false, "tolerance": 0}); + if let Some(all) = all { + p["sampleAllLayers"] = json!(all); + } + assert_eq!(s.execute("paint.bucket", p.clone()).unwrap()["filled"], true); + assert_eq!(px(&s, 5, 5), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}, all {all:?}"); + let beyond = if all == Some(true) { vec![0.0; 4] } else { vec![1.0, 0.0, 0.0, 1.0] }; + assert_eq!(px(&s, 15, 5), beyond, "depth {depth}, all {all:?}: sample flag controls the boundary"); + assert_eq!(s.active().unwrap().doc.layer(bottom).unwrap(), &before, "only the active layer is written"); + if all == Some(true) { + assert_eq!(px(&s, 10, 5), vec![0.0; 4], "wall itself is untouched"); + assert!(s.undo()); + p["contiguous"] = json!(false); + s.execute("paint.bucket", p).unwrap(); + assert_eq!(px(&s, 15, 5), vec![1.0, 0.0, 0.0, 1.0], "noncontiguous finds both white regions"); + assert_eq!(px(&s, 10, 5), vec![0.0; 4]); + assert!(s.undo()); + assert_eq!(s.execute("paint.bucket", json!({"x": -1, "y": 2, "sampleAllLayers": true})).unwrap()["filled"], false); + assert_eq!(px(&s, 5, 5), vec![0.0; 4], "an off-canvas sample does not fill the layer"); + } + } + } +} + +#[test] +fn bucket_sample_all_layers_ignores_hidden_layers() { + let (mut s, _) = bucket_layers(8); + s.edit("hidden wall", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().fill_rect(Rect::new(4, 0, 5, 10), &[0.0, 0.0, 0.0, 1.0]); + l.visible = false; + Ok(()) + }) + .unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("paint.bucket", json!({"x": 2, "y": 2, "color": "#ff0000", "antiAlias": false, "tolerance": 0, "sampleAllLayers": true})).unwrap(); + assert_eq!(px(&s, 4, 5), vec![1.0, 0.0, 0.0, 1.0], "hidden wall does not bound the fill"); + assert_eq!(px(&s, 8, 5), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(px(&s, 15, 5), vec![0.0; 4], "visible wall still bounds the fill"); +} + +#[test] +fn bucket_sample_all_layers_keeps_selection_opacity_and_history() { + for depth in [8, 16, 32] { + let (mut s, _) = bucket_layers(depth); + s.execute("select.rect", json!({"x": 0, "y": 2, "width": 20, "height": 6})).unwrap(); + s.edit("feather", |doc, _| { + doc.selection.as_mut().unwrap().fill_rect(Rect::new(0, 2, 4, 8), &[0.5]); + Ok(()) + }) + .unwrap(); + let selection = s.active().unwrap().doc.selection.clone(); + s.execute("paint.bucket", json!({"x": 2, "y": 5, "color": "#ff0000", "antiAlias": false, "tolerance": 0, "opacity": 50, "sampleAllLayers": true})) + .unwrap(); + let (feathered, full) = (px(&s, 2, 5), px(&s, 6, 5)); + assert!((feathered[3] - 0.25).abs() < 0.005 && (full[3] - 0.5).abs() < 0.005, "depth {depth}: selection coverage multiplies opacity"); + assert_eq!(full[..3], [1.0, 0.0, 0.0]); + assert_eq!(px(&s, 6, 1), vec![0.0; 4], "outside selection"); + assert_eq!(px(&s, 15, 5), vec![0.0; 4], "outside sampled region"); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Paint Bucket")); + assert!(s.undo()); + assert_eq!(px(&s, 2, 5), vec![0.0; 4]); + assert_eq!(s.active().unwrap().doc.selection, selection); + assert!(s.redo()); + assert_eq!(px(&s, 2, 5), feathered); + assert_eq!(px(&s, 6, 5), full); + assert_eq!(s.active().unwrap().doc.selection, selection); + } +} + +#[test] +fn bucket_sample_all_layers_pattern_uses_the_same_region() { + let (mut s, _) = bucket_layers(8); + s.execute( + "paint.bucket", + json!({"x": 2, "y": 2, "contents": "pattern", "pattern": "Diagonal Lines", "antiAlias": false, "tolerance": 0, "sampleAllLayers": true}), + ) + .unwrap(); + let left: Vec = (0..10).map(|x| px(&s, x, 0)[0]).collect(); + assert!(left.iter().any(|&r| r < 0.3) && left.iter().any(|&r| r > 0.9), "pattern varies inside the region: {left:?}"); + assert_eq!(px(&s, 10, 5), vec![0.0; 4], "wall untouched"); + assert_eq!(px(&s, 15, 5), vec![0.0; 4], "region past the wall untouched"); +} + +#[test] +fn bucket_sample_all_layers_mask_and_channel_targets_keep_their_own_boundaries() { + for target in [json!("mask"), json!({"channel": 0}), json!("quickMask")] { + for all in [false, true] { + let (mut s, _) = bucket_layers(8); + match crate::channel_cmds::target_of(&json!({"target": target})) { + crate::channel_cmds::Target::Mask => { + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + } + crate::channel_cmds::Target::Alpha(_) => { + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + } + crate::channel_cmds::Target::QuickMask => { + s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + } + _ => panic!("expected a grayscale target"), + } + let p = json!({"x": 2, "y": 2, "color": "#000000", "antiAlias": false, "tolerance": 0, "target": target, "sampleAllLayers": all}); + s.edit("target wall", |doc, active| { + let area = doc.bounds(); + let (surf, _) = crate::channel_cmds::target_surface(doc, *active, &p).unwrap(); + surf.fill_rect(area, &[1.0]); + surf.fill_rect(Rect::new(5, 0, 6, 10), &[0.0]); + Ok(()) + }) + .unwrap(); + s.execute("paint.bucket", p.clone()).unwrap(); + let d = &s.active().unwrap().doc; + let surf = match crate::channel_cmds::target_of(&p) { + crate::channel_cmds::Target::Mask => &d.layer(s.active().unwrap().active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface, + crate::channel_cmds::Target::Alpha(i) => &d.channels[i].surface, + crate::channel_cmds::Target::QuickMask => &d.quick_mask.as_ref().unwrap().surface, + _ => panic!("expected a grayscale target"), + }; + assert_eq!(surf.sample_channel(2, 5, 0), 0.0, "{target}, all {all}: filled target"); + assert_eq!(surf.sample_channel(7, 5, 0), 1.0, "{target}, all {all}: stopped at target wall"); + assert_eq!(px(&s, 2, 5), vec![0.0; 4], "layer pixels remain untouched"); + } + } +} + +#[test] +fn bucket_fill_contiguous() { + let mut s = session(); + s.edit("wall", |doc, _| { + doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(10, 0, 11, 10), &[0.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("paint.bucket", json!({"x": 2, "y": 2, "color": "#ff0000", "antiAlias": false})).unwrap(); + assert_eq!(px(&s, 5, 5), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(px(&s, 15, 5), vec![1.0, 1.0, 1.0, 1.0]); + s.execute("paint.bucket", json!({"x": 2, "y": 2, "color": "#0000ff", "contiguous": false, "antiAlias": false, "tolerance": 0})).unwrap(); + assert_eq!(px(&s, 5, 5), vec![0.0, 0.0, 1.0, 1.0]); +} + +/// #4196: the Paint Bucket and Edit > Stroke write a CMYK pick as its inks into a CMYK document, +/// not as its sRGB stand-in converted back (100/0/0/0 cyan would come out as about 100/28/0/17). +#[test] +fn bucket_and_stroke_write_a_cmyk_pick_as_its_inks() { + let cyan = [1.0f32, 0.0, 0.0, 0.0]; + let mut s = session(); + s.execute("image.mode.cmyk", json!({})).unwrap(); + let rgb = photocraft_color::convert::cmyk_to_rgb(cyan).map(|c| c.clamp(0.0, 1.0)); + s.execute("tools.setColors", json!({"foreground": rgb, "foregroundCmyk": cyan})).unwrap(); + let inks_at = |s: &Session, x: i32, y: i32| -> Vec { + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + surf.read_region(Rect::new(x, y, x + 1, y + 1)).into_iter().take(4).collect() + }; + let is_cyan = |got: &[f32]| got.iter().zip(cyan).all(|(a, b)| (a - b).abs() < 0.02); + s.execute("paint.bucket", json!({"x": 2, "y": 2, "antiAlias": false})).unwrap(); + let got = inks_at(&s, 5, 5); + assert!(is_cyan(&got), "bucket: {got:?}"); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.stroke", json!({"width": 2, "location": "inside", "color": rgb})).unwrap(); + let got = inks_at(&s, 0, 5); + assert!(is_cyan(&got), "stroke: {got:?}"); +} + +#[test] +fn bucket_fills_with_a_pattern() { + // Paint Bucket with contents="pattern" flood-fills the region with a pattern, not a colour. + let mut s = session(); + s.edit("wall", |doc, _| { + doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(10, 0, 11, 10), &[0.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("paint.bucket", json!({"x": 2, "y": 2, "contents": "pattern", "pattern": "Diagonal Lines", "antiAlias": false, "tolerance": 0})).unwrap(); + // The filled region (left of the wall) now carries the pattern's light/dark variation, + // while the wall and the region past it are untouched. + let left: Vec<[f32; 4]> = (0..10) + .map(|x| { + let p = px(&s, x, 0); + [p[0], p[1], p[2], p[3]] + }) + .collect(); + assert!(left.iter().any(|p| p[0] < 0.3) && left.iter().any(|p| p[0] > 0.9), "pattern varies in the fill: {left:?}"); + assert_eq!(px(&s, 15, 5), vec![1.0, 1.0, 1.0, 1.0], "region past the wall untouched"); +} + +#[test] +fn gradient_tool_with_selection_and_reverse() { + let mut s = session(); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [20, 0], "colors": ["#000000", "#ffffff"]})).unwrap(); + assert!(px(&s, 0, 5)[0] < 0.05 && px(&s, 19, 5)[0] > 0.95); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [20, 0], "colors": ["#000000", "#ffffff"], "reverse": true})).unwrap(); + assert!(px(&s, 0, 5)[0] > 0.95); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 5, "height": 10})).unwrap(); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [0, 10], "colors": ["#ff0000"]})).unwrap(); + assert_eq!(px(&s, 2, 5)[..3], [1.0, 0.0, 0.0]); + assert!(px(&s, 10, 5)[1] > 0.4, "outside the selection untouched"); + assert!(s.execute("paint.gradient", json!({"from": [0, 0]})).is_err()); +} + +#[test] +fn gradient_dither_breaks_banding() { + // A flat gradient (same colour both ends) is perfectly smooth with dither off, and gains + // per-pixel noise with dither on (which breaks 8-bit banding). + let run = |dither: bool| { + let mut s = session(); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [19, 0], "colors": [[0.5, 0.5, 0.5, 1.0], [0.5, 0.5, 0.5, 1.0]], "dither": dither})) + .unwrap(); + (0..19).map(|x| px(&s, x, 5)[0]).collect::>() + }; + let smooth = run(false); + assert!(smooth.iter().all(|&v| v == smooth[0]), "no dither: perfectly flat"); + let noisy = run(true); + assert!(noisy.windows(2).any(|w| w[0] != w[1]), "dither: per-pixel variation"); +} + +/// The two commands under test, each painting #808080 over a white document. +fn grey_fill(cmd: &str, opacity: Value) -> Value { + match cmd { + "paint.bucket" => json!({"x": 2, "y": 2, "color": "#808080", "opacity": opacity}), + _ => json!({"from": [0, 0], "to": [19, 0], "colors": ["#808080", "#808080"], "dither": false, "opacity": opacity}), + } +} + +fn white(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10, "depth": depth, "background": "white"})).unwrap(); + s +} + +/// Issue #4167: an opacity above 100 overshot the blend (200 painted near-black on white). +#[test] +fn bucket_and_gradient_clamp_opacity_like_the_magic_eraser() { + for cmd in ["paint.bucket", "paint.gradient"] { + for depth in [8, 16, 32] { + let mut full = white(depth); + full.execute(cmd, grey_fill(cmd, json!(100))).unwrap(); + let expected = px(&full, 5, 5); + assert!((expected[0] - 128.0 / 255.0).abs() < 0.01, "{cmd} depth {depth}: 100% paints #808080, got {expected:?}"); + for over in [200.0, 1e9] { + let mut s = white(depth); + s.execute(cmd, grey_fill(cmd, json!(over))).unwrap(); + assert_eq!(px(&s, 5, 5), expected, "{cmd} depth {depth}: opacity {over} clamps to 100"); + } + let (mut low, mut one) = (white(depth), white(depth)); + low.execute(cmd, grey_fill(cmd, json!(-50))).unwrap(); + one.execute(cmd, grey_fill(cmd, json!(1))).unwrap(); + assert_eq!(px(&low, 5, 5), px(&one, 5, 5), "{cmd} depth {depth}: opacity below 1 clamps to 1"); + assert!(px(&low, 5, 5).iter().all(|v| (0.0..=1.0).contains(v)), "{cmd} depth {depth}: no overshoot"); + } + } +} + +#[test] +fn bucket_and_gradient_reject_non_numeric_opacity_without_editing() { + for cmd in ["paint.bucket", "paint.gradient"] { + for bad in [json!("50"), json!(true), json!([50]), json!({"v": 50})] { + let mut s = white(8); + let (before, steps) = (px(&s, 5, 5), s.active().unwrap().history.past_len()); + let err = s.execute(cmd, grey_fill(cmd, bad.clone())).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "{cmd} {bad}: {err:?}"); + assert_eq!(px(&s, 5, 5), before, "{cmd} {bad}: pixels unchanged"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "{cmd} {bad}: no history step"); + } + // An explicit null keeps the default (100%), like the Magic Eraser. + let mut s = white(8); + s.execute(cmd, grey_fill(cmd, Value::Null)).unwrap(); + assert!((px(&s, 5, 5)[0] - 128.0 / 255.0).abs() < 0.01, "{cmd}: null opacity is 100%"); + } +} From f3e5fb68d63f05802d3414dc24957ba912c45348 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:13 +0000 Subject: [PATCH 034/259] refactor(engine): move fill_cmds.rs tests to fill_cmds/tests.rs --- crates/engine/src/fill_cmds.rs | 320 +-------------------------- crates/engine/src/fill_cmds/tests.rs | 317 ++++++++++++++++++++++++++ 2 files changed, 318 insertions(+), 319 deletions(-) create mode 100644 crates/engine/src/fill_cmds/tests.rs diff --git a/crates/engine/src/fill_cmds.rs b/crates/engine/src/fill_cmds.rs index 574241681a..35d25119a9 100644 --- a/crates/engine/src/fill_cmds.rs +++ b/crates/engine/src/fill_cmds.rs @@ -505,322 +505,4 @@ fn blend_tile(bytes: &mut [u8], fmt: &photocraft_color::PixelFormat, origin: Rec } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30, "background": "transparent"})).unwrap(); - s - } - - fn px(s: &Session, x: i32, y: i32) -> [f32; 4] { - let st = s.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); - l.surface().unwrap().rgba(x, y) - } - - fn close(a: [f32; 4], b: [f32; 4]) -> bool { - a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1.5 / 255.0) - } - - #[test] - fn history_fill_reads_only_the_selection_inside_the_canvas() { - let mut s = session(); - s.edit("selection", |doc, _| { - let mut selection = Surface::new(photocraft_color::PixelFormat::GRAY8); - selection.write_pixel(-2_000_000_000, -2_000_000_000, &[1.0]); - selection.write_pixel(4, 4, &[1.0]); - doc.selection = Some(selection); - Ok(()) - }) - .unwrap(); - // Reading the full sparse selection rectangle overflows the allocation size; - // only its intersection with this small canvas is meaningful to Fill. - s.execute(CMD, json!({"contents": "history"})).unwrap(); - assert!(s.undo()); - assert!(s.active().unwrap().doc.selection.as_ref().unwrap().sample_channel(4, 4, 0) > 0.0); - } - - #[test] - fn every_constant_contents() { - let mut s = session(); - s.execute("tools.setColors", json!({"foreground": [1.0, 0.0, 0.0, 1.0], "background": [0.0, 0.0, 1.0, 1.0]})).unwrap(); - for (c, want) in [ - ("foreground", [1.0, 0.0, 0.0, 1.0]), - ("background", [0.0, 0.0, 1.0, 1.0]), - ("black", [0.0, 0.0, 0.0, 1.0]), - ("gray", [128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]), - ("white", [1.0; 4]), - ] { - s.execute(CMD, json!({"contents": c})).unwrap(); - assert!(close(px(&s, 5, 5), want), "{c}: {:?}", px(&s, 5, 5)); - } - s.execute(CMD, json!({"contents": "color", "color": "#00ff00"})).unwrap(); - assert!(close(px(&s, 5, 5), [0.0, 1.0, 0.0, 1.0])); - // The old form: a colour, or the foreground. - s.execute(CMD, json!({"color": "#ffff00"})).unwrap(); - assert!(close(px(&s, 5, 5), [1.0, 1.0, 0.0, 1.0])); - } - - #[test] - fn opacity_mode_and_preserve_transparency() { - let mut s = session(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); - s.execute(CMD, json!({"contents": "white"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - // Preserve Transparency: the empty right half stays empty. - s.execute(CMD, json!({"contents": "black", "opacity": 50, "preserveTransparency": true})).unwrap(); - assert!(close(px(&s, 5, 5), [0.5, 0.5, 0.5, 1.0]), "{:?}", px(&s, 5, 5)); - assert_eq!(px(&s, 30, 5)[3], 0.0); - // Multiply with white leaves the grey. - s.execute(CMD, json!({"contents": "white", "mode": "multiply", "preserveTransparency": true})).unwrap(); - assert!(close(px(&s, 5, 5), [0.5, 0.5, 0.5, 1.0])); - // Without it, the transparent half is filled. - s.execute(CMD, json!({"contents": "white", "opacity": 100})).unwrap(); - assert_eq!(px(&s, 30, 5), [1.0; 4]); - // Dissolve paints whole pixels only. - s.execute(CMD, json!({"contents": "black", "mode": "dissolve", "opacity": 50})).unwrap(); - let st = s.active().unwrap(); - let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - let blacks = (0..40).flat_map(|x| (0..30).map(move |y| (x, y))).filter(|&(x, y)| surf.rgba(x, y)[0] < 0.01).count(); - assert!(blacks > 300 && blacks < 900, "{blacks}"); - assert!((0..40).all(|x| { - let v = surf.rgba(x, 3)[0]; - v.is_finite() && !(0.01..=0.99).contains(&v) - })); - } - - #[test] - fn preserve_transparency_blends_source_atop_on_semi_transparent_pixels() { - // White at 50%, then black at 50% keeping alpha: Photoshop gives (127,127,127,128), the - // colour moved halfway, at every depth and in non-Normal modes too (#5783). - for depth in [8, 16, 32] { - for mode in ["normal", "multiply"] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); - s.execute(CMD, json!({"contents": "white", "opacity": 50})).unwrap(); - s.execute(CMD, json!({"contents": "black", "opacity": 50, "mode": mode, "preserveTransparency": true})).unwrap(); - assert!(close(px(&s, 3, 3), [0.5, 0.5, 0.5, 0.5]), "{depth} {mode} {:?}", px(&s, 3, 3)); - } - } - } - - #[test] - fn history_pattern_and_content_aware() { - let mut s = session(); - s.execute(CMD, json!({"contents": "white"})).unwrap(); - s.execute(CMD, json!({"contents": "black"})).unwrap(); - // History: back to state 1 (after the white fill). - s.execute(CMD, json!({"contents": "history", "state": 1})).unwrap(); - assert_eq!(px(&s, 5, 5), [1.0; 4]); - // The default source is the oldest state: the empty layer. - s.execute(CMD, json!({"contents": "history"})).unwrap(); - assert_eq!(px(&s, 5, 5)[3], 0.0); - assert!(s.execute(CMD, json!({"contents": "history", "state": 999})).is_err()); - let r = s.execute(CMD, json!({"contents": "pattern", "pattern": "Diagonal Lines"})).unwrap(); - assert!(r["pattern"].is_string()); - assert!(px(&s, 5, 5)[3] > 0.0); - // Content-Aware fills the hole from what is around it. - s.execute(CMD, json!({"contents": "color", "color": "#336699"})).unwrap(); - s.execute("select.rect", json!({"x": 15, "y": 10, "width": 6, "height": 6})).unwrap(); - s.execute(CMD, json!({"contents": "white"})).unwrap(); - s.execute(CMD, json!({"contents": "contentAware", "colorAdaptation": false})).unwrap(); - assert!(close(px(&s, 17, 12), [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0, 1.0]), "{:?}", px(&s, 17, 12)); - } - - #[test] - fn history_fill_reads_a_source_when_its_pixels_were_locked() { - // Given a white layer locked in history state 1, then unlocked and filled red. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); - s.execute("layer.lockLayers", json!({"pixels": true})).unwrap(); - s.execute("layer.lockLayers", json!({"pixels": false})).unwrap(); - s.execute(CMD, json!({"color": "#ff0000"})).unwrap(); - - // When Fill reads the locked historical pixels. - let result = s.execute(CMD, json!({"contents": "history", "state": 1})); - - // Then it restores white; the historical lock limits edits, not reads. - assert!(result.is_ok(), "{result:?}"); - assert!(close(px(&s, 8, 8), [1.0; 4]), "{:?}", px(&s, 8, 8)); - } - - #[test] - fn history_fill_refuses_a_locked_destination_when_source_is_unlocked() { - // Given an unlocked white source and a red, currently locked destination. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); - s.execute(CMD, json!({"color": "#ff0000"})).unwrap(); - s.execute("layer.lockLayers", json!({"pixels": true})).unwrap(); - - // When Fill reads the unlocked source and attempts to write to the locked destination. - let result = s.execute(CMD, json!({"contents": "history", "state": 0})); - - // Then the destination lock still rejects the edit and preserves red pixels. - assert!(result.is_err()); - assert!(close(px(&s, 8, 8), [1.0, 0.0, 0.0, 1.0]), "{:?}", px(&s, 8, 8)); - } - - /// `cargo test -p photocraft-engine --release --lib fill_cmds::tests::timing_24mp -- --ignored --nocapture` - #[test] - #[ignore] - fn timing_24mp() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 6000, "height": 4000, "background": "white"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute(CMD, json!({"contents": "white"})).unwrap(); - let time = |s: &mut Session, label: &str, p: Value| { - let mut v = Vec::new(); - for i in 0..5 { - let mut p = p.clone(); - if p.get("contents").is_none() { - p["color"] = json!(if i % 2 == 0 { "#336699" } else { "#996633" }); - } - let t = std::time::Instant::now(); - s.execute(CMD, p).unwrap(); - v.push(t.elapsed().as_secs_f64() * 1000.0); - } - v.sort_by(f64::total_cmp); - println!("{label:<48} median {:>8.1} ms min {:>8.1} ms", v[2], v[0]); - }; - time(&mut s, "colour, no selection", json!({})); - time(&mut s, "colour, preserve transparency", json!({"preserveTransparency": true})); - time(&mut s, "colour 50% multiply", json!({"opacity": 50, "mode": "multiply"})); - s.execute("select.rect", json!({"x": 100, "y": 100, "width": 5000, "height": 3000})).unwrap(); - time(&mut s, "colour, 15 MP rectangle selection", json!({})); - s.execute("select.deselect", json!({})).unwrap(); - // The old per-pixel f32 path, for comparison. - let st = s.active().unwrap(); - let mut surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); - let t = std::time::Instant::now(); - crate::pixels::try_fill_surface(&mut surf, Rect::new(0, 0, 6000, 4000), [0.2, 0.4, 0.6, 1.0], None, false).unwrap(); - println!("{:<48} {:>8.1} ms", "fallible fill_surface, no selection", t.elapsed().as_secs_f64() * 1000.0); - } - - #[test] - fn bad_params_are_errors() { - let mut s = session(); - for p in [ - json!({"contents": "plaid"}), - json!({"contents": 3}), - json!({"mode": "sideways"}), - json!({"mode": "passThrough"}), - json!({"opacity": "lots"}), - json!({"preserveTransparency": "yes"}), - json!({"contents": "contentAware"}), - json!({"contents": "pattern", "pattern": "no such pattern"}), - json!({"contents": "history", "state": -1}), - json!({"contents": "contentAware", "colorAdaptation": 1}), - ] { - assert!(s.execute(CMD, p.clone()).is_err(), "{p}"); - } - // Everything selected leaves nothing to sample from. - s.execute("select.all", json!({})).unwrap(); - assert!(s.execute(CMD, json!({"contents": "contentAware"})).is_err()); - // Out-of-range opacity is clamped. - s.execute(CMD, json!({"contents": "white", "opacity": 1e300})).unwrap(); - } - - /// A session whose canvas is `size` and whose selection is the given (sparse) rectangles, as - /// a loaded `.pcraft` can declare (#963): the canvas size is not capped on load and the - /// selection tiles can lie far apart. Nothing here allocates more than a few tiles. - fn huge_selection(size: (u32, u32), rects: &[Rect]) -> Session { - let mut s = session(); - s.execute(CMD, json!({"contents": "color", "color": "#336699"})).unwrap(); - let st = s.active_mut().unwrap(); - let doc = std::sync::Arc::make_mut(&mut st.doc); - doc.size = photocraft_geom::Size::new(size.0, size.1); - let mut sel = Surface::new(photocraft_color::PixelFormat::GRAY8); - for r in rects { - sel.fill_rect(*r, &[1.0]); - } - doc.selection = Some(sel); - s - } - - /// Content-Aware fill on a selection whose extent overflows the sampling-window arithmetic - /// (#963) returns the size error and leaves the document and history untouched. - #[test] - fn content_aware_huge_extent_is_an_error() { - // Largest extent whose `ext * 3` still fits in u32. - const EDGE: i32 = (u32::MAX / 3) as i32; - let max = i32::MAX; - let cases: [(&str, (u32, u32), Vec); 7] = [ - // The issue's repro: a second selection tile 5 600 000 tiles to the right. - ("issue repro", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 8, 8), Rect::new(5_600_000 * TILE_SIZE, 0, 5_600_000 * TILE_SIZE + 8, 8)]), - ("wide, just above", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(EDGE, 0, EDGE + 1, 1)]), - ("tall, just above", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(0, EDGE, 1, EDGE + 1)]), - ("wide, just below", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(EDGE - 1, 0, EDGE, 1)]), - ("tall, just below", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(0, EDGE - 1, 1, EDGE)]), - // The largest canvas a Rect can hold, selected corner to corner, plus a piece off the - // canvas at the most negative coordinate. - ( - "extreme coordinates", - (max as u32, max as u32), - vec![Rect::new(i32::MIN, i32::MIN, i32::MIN + 1, i32::MIN + 1), Rect::new(0, 0, 1, 1), Rect::new(max - 2, max - 2, max - 1, max - 1)], - ), - // A canvas wider than a Rect can hold is treated as empty, never as a panic. - ("canvas beyond i32", (u32::MAX, u32::MAX), vec![Rect::new(0, 0, 1, 1), Rect::new(max - 2, 0, max - 1, 1)]), - ]; - for (name, size, rects) in cases { - let mut s = huge_selection(size, &rects); - let before = s.active().unwrap().doc.clone(); - let past = s.active().unwrap().history.past_len(); - let r = s.execute(CMD, json!({"contents": "contentAware", "colorAdaptation": false})); - let err = r.expect_err(name).to_string(); - assert!(!err.contains("internal error"), "{name}: {err}"); - if name != "canvas beyond i32" { - assert!(err.contains("too large for Content-Aware fill"), "{name}: {err}"); - } - let st = s.active().unwrap(); - assert!(std::sync::Arc::ptr_eq(&before, &st.doc), "{name}: the document changed"); - assert_eq!(st.history.past_len(), past, "{name}: a history step was recorded"); - assert!(close(px(&s, 5, 5), [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0, 1.0]), "{name}"); - } - // Control: an ordinary selection still fills from its surroundings. - let mut s = huge_selection((40, 30), &[Rect::new(15, 10, 21, 16)]); - s.execute(CMD, json!({"contents": "white"})).unwrap(); - s.execute(CMD, json!({"contents": "contentAware", "colorAdaptation": false})).unwrap(); - assert!(close(px(&s, 17, 12), [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0, 1.0]), "{:?}", px(&s, 17, 12)); - } - - /// A Stroke, Fill or Clear inside a selection keeps the tiles the selection doesn't reach as - /// they were (shared with the history), instead of storing a copy of each (#4517). - #[test] - fn unselected_tiles_stay_shared() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 1024, "height": 1024, "background": "white"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("edit.fill", json!({"color": "#336699"})).unwrap(); - let id = s.active().unwrap().active_layer.unwrap(); - let surf = |s: &Session| s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().clone(); - for (cmd, params) in [ - ("edit.fill", json!({"color": "#ff0000"})), - ("edit.stroke", json!({"width": 4, "color": "#00ff00", "location": "inside"})), - ("edit.clear", json!({})), - ] { - // Two small selections in opposite corners (256 px tiles): the selection's bounds - // span every tile, but only the two corner tiles have anything selected. - s.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 100})).unwrap(); - s.execute("select.rect", json!({"x": 900, "y": 900, "width": 100, "height": 100, "mode": "add"})).unwrap(); - let before = surf(&s); - s.execute(cmd, params).unwrap(); - let after = surf(&s); - let corners = [photocraft_geom::Rect::new(0, 0, 256, 256), photocraft_geom::Rect::new(768, 768, 1024, 1024)]; - let mut kept = 0; - for (c, t) in before.tiles() { - if corners.iter().all(|r| c.rect().intersect(r).is_empty()) { - assert!(after.tile(*c).is_some_and(|a| std::sync::Arc::ptr_eq(a, t)), "{cmd}: unselected tile {c:?} was copied"); - kept += 1; - } - } - assert_eq!(kept, 14, "{cmd}: the 14 tiles between the corners"); - for r in corners { - assert_ne!(before.read_region(r), after.read_region(r), "{cmd} changed the selected corner {r:?}"); - } - s.execute("select.deselect", json!({})).unwrap(); - } - } -} +mod tests; diff --git a/crates/engine/src/fill_cmds/tests.rs b/crates/engine/src/fill_cmds/tests.rs new file mode 100644 index 0000000000..3a9dd61d49 --- /dev/null +++ b/crates/engine/src/fill_cmds/tests.rs @@ -0,0 +1,317 @@ +use super::*; +use serde_json::json; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30, "background": "transparent"})).unwrap(); + s +} + +fn px(s: &Session, x: i32, y: i32) -> [f32; 4] { + let st = s.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + l.surface().unwrap().rgba(x, y) +} + +fn close(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1.5 / 255.0) +} + +#[test] +fn history_fill_reads_only_the_selection_inside_the_canvas() { + let mut s = session(); + s.edit("selection", |doc, _| { + let mut selection = Surface::new(photocraft_color::PixelFormat::GRAY8); + selection.write_pixel(-2_000_000_000, -2_000_000_000, &[1.0]); + selection.write_pixel(4, 4, &[1.0]); + doc.selection = Some(selection); + Ok(()) + }) + .unwrap(); + // Reading the full sparse selection rectangle overflows the allocation size; + // only its intersection with this small canvas is meaningful to Fill. + s.execute(CMD, json!({"contents": "history"})).unwrap(); + assert!(s.undo()); + assert!(s.active().unwrap().doc.selection.as_ref().unwrap().sample_channel(4, 4, 0) > 0.0); +} + +#[test] +fn every_constant_contents() { + let mut s = session(); + s.execute("tools.setColors", json!({"foreground": [1.0, 0.0, 0.0, 1.0], "background": [0.0, 0.0, 1.0, 1.0]})).unwrap(); + for (c, want) in [ + ("foreground", [1.0, 0.0, 0.0, 1.0]), + ("background", [0.0, 0.0, 1.0, 1.0]), + ("black", [0.0, 0.0, 0.0, 1.0]), + ("gray", [128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]), + ("white", [1.0; 4]), + ] { + s.execute(CMD, json!({"contents": c})).unwrap(); + assert!(close(px(&s, 5, 5), want), "{c}: {:?}", px(&s, 5, 5)); + } + s.execute(CMD, json!({"contents": "color", "color": "#00ff00"})).unwrap(); + assert!(close(px(&s, 5, 5), [0.0, 1.0, 0.0, 1.0])); + // The old form: a colour, or the foreground. + s.execute(CMD, json!({"color": "#ffff00"})).unwrap(); + assert!(close(px(&s, 5, 5), [1.0, 1.0, 0.0, 1.0])); +} + +#[test] +fn opacity_mode_and_preserve_transparency() { + let mut s = session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); + s.execute(CMD, json!({"contents": "white"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + // Preserve Transparency: the empty right half stays empty. + s.execute(CMD, json!({"contents": "black", "opacity": 50, "preserveTransparency": true})).unwrap(); + assert!(close(px(&s, 5, 5), [0.5, 0.5, 0.5, 1.0]), "{:?}", px(&s, 5, 5)); + assert_eq!(px(&s, 30, 5)[3], 0.0); + // Multiply with white leaves the grey. + s.execute(CMD, json!({"contents": "white", "mode": "multiply", "preserveTransparency": true})).unwrap(); + assert!(close(px(&s, 5, 5), [0.5, 0.5, 0.5, 1.0])); + // Without it, the transparent half is filled. + s.execute(CMD, json!({"contents": "white", "opacity": 100})).unwrap(); + assert_eq!(px(&s, 30, 5), [1.0; 4]); + // Dissolve paints whole pixels only. + s.execute(CMD, json!({"contents": "black", "mode": "dissolve", "opacity": 50})).unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + let blacks = (0..40).flat_map(|x| (0..30).map(move |y| (x, y))).filter(|&(x, y)| surf.rgba(x, y)[0] < 0.01).count(); + assert!(blacks > 300 && blacks < 900, "{blacks}"); + assert!((0..40).all(|x| { + let v = surf.rgba(x, 3)[0]; + v.is_finite() && !(0.01..=0.99).contains(&v) + })); +} + +#[test] +fn preserve_transparency_blends_source_atop_on_semi_transparent_pixels() { + // White at 50%, then black at 50% keeping alpha: Photoshop gives (127,127,127,128), the + // colour moved halfway, at every depth and in non-Normal modes too (#5783). + for depth in [8, 16, 32] { + for mode in ["normal", "multiply"] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); + s.execute(CMD, json!({"contents": "white", "opacity": 50})).unwrap(); + s.execute(CMD, json!({"contents": "black", "opacity": 50, "mode": mode, "preserveTransparency": true})).unwrap(); + assert!(close(px(&s, 3, 3), [0.5, 0.5, 0.5, 0.5]), "{depth} {mode} {:?}", px(&s, 3, 3)); + } + } +} + +#[test] +fn history_pattern_and_content_aware() { + let mut s = session(); + s.execute(CMD, json!({"contents": "white"})).unwrap(); + s.execute(CMD, json!({"contents": "black"})).unwrap(); + // History: back to state 1 (after the white fill). + s.execute(CMD, json!({"contents": "history", "state": 1})).unwrap(); + assert_eq!(px(&s, 5, 5), [1.0; 4]); + // The default source is the oldest state: the empty layer. + s.execute(CMD, json!({"contents": "history"})).unwrap(); + assert_eq!(px(&s, 5, 5)[3], 0.0); + assert!(s.execute(CMD, json!({"contents": "history", "state": 999})).is_err()); + let r = s.execute(CMD, json!({"contents": "pattern", "pattern": "Diagonal Lines"})).unwrap(); + assert!(r["pattern"].is_string()); + assert!(px(&s, 5, 5)[3] > 0.0); + // Content-Aware fills the hole from what is around it. + s.execute(CMD, json!({"contents": "color", "color": "#336699"})).unwrap(); + s.execute("select.rect", json!({"x": 15, "y": 10, "width": 6, "height": 6})).unwrap(); + s.execute(CMD, json!({"contents": "white"})).unwrap(); + s.execute(CMD, json!({"contents": "contentAware", "colorAdaptation": false})).unwrap(); + assert!(close(px(&s, 17, 12), [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0, 1.0]), "{:?}", px(&s, 17, 12)); +} + +#[test] +fn history_fill_reads_a_source_when_its_pixels_were_locked() { + // Given a white layer locked in history state 1, then unlocked and filled red. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); + s.execute("layer.lockLayers", json!({"pixels": true})).unwrap(); + s.execute("layer.lockLayers", json!({"pixels": false})).unwrap(); + s.execute(CMD, json!({"color": "#ff0000"})).unwrap(); + + // When Fill reads the locked historical pixels. + let result = s.execute(CMD, json!({"contents": "history", "state": 1})); + + // Then it restores white; the historical lock limits edits, not reads. + assert!(result.is_ok(), "{result:?}"); + assert!(close(px(&s, 8, 8), [1.0; 4]), "{:?}", px(&s, 8, 8)); +} + +#[test] +fn history_fill_refuses_a_locked_destination_when_source_is_unlocked() { + // Given an unlocked white source and a red, currently locked destination. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); + s.execute(CMD, json!({"color": "#ff0000"})).unwrap(); + s.execute("layer.lockLayers", json!({"pixels": true})).unwrap(); + + // When Fill reads the unlocked source and attempts to write to the locked destination. + let result = s.execute(CMD, json!({"contents": "history", "state": 0})); + + // Then the destination lock still rejects the edit and preserves red pixels. + assert!(result.is_err()); + assert!(close(px(&s, 8, 8), [1.0, 0.0, 0.0, 1.0]), "{:?}", px(&s, 8, 8)); +} + +/// `cargo test -p photocraft-engine --release --lib fill_cmds::tests::timing_24mp -- --ignored --nocapture` +#[test] +#[ignore] +fn timing_24mp() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 6000, "height": 4000, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute(CMD, json!({"contents": "white"})).unwrap(); + let time = |s: &mut Session, label: &str, p: Value| { + let mut v = Vec::new(); + for i in 0..5 { + let mut p = p.clone(); + if p.get("contents").is_none() { + p["color"] = json!(if i % 2 == 0 { "#336699" } else { "#996633" }); + } + let t = std::time::Instant::now(); + s.execute(CMD, p).unwrap(); + v.push(t.elapsed().as_secs_f64() * 1000.0); + } + v.sort_by(f64::total_cmp); + println!("{label:<48} median {:>8.1} ms min {:>8.1} ms", v[2], v[0]); + }; + time(&mut s, "colour, no selection", json!({})); + time(&mut s, "colour, preserve transparency", json!({"preserveTransparency": true})); + time(&mut s, "colour 50% multiply", json!({"opacity": 50, "mode": "multiply"})); + s.execute("select.rect", json!({"x": 100, "y": 100, "width": 5000, "height": 3000})).unwrap(); + time(&mut s, "colour, 15 MP rectangle selection", json!({})); + s.execute("select.deselect", json!({})).unwrap(); + // The old per-pixel f32 path, for comparison. + let st = s.active().unwrap(); + let mut surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); + let t = std::time::Instant::now(); + crate::pixels::try_fill_surface(&mut surf, Rect::new(0, 0, 6000, 4000), [0.2, 0.4, 0.6, 1.0], None, false).unwrap(); + println!("{:<48} {:>8.1} ms", "fallible fill_surface, no selection", t.elapsed().as_secs_f64() * 1000.0); +} + +#[test] +fn bad_params_are_errors() { + let mut s = session(); + for p in [ + json!({"contents": "plaid"}), + json!({"contents": 3}), + json!({"mode": "sideways"}), + json!({"mode": "passThrough"}), + json!({"opacity": "lots"}), + json!({"preserveTransparency": "yes"}), + json!({"contents": "contentAware"}), + json!({"contents": "pattern", "pattern": "no such pattern"}), + json!({"contents": "history", "state": -1}), + json!({"contents": "contentAware", "colorAdaptation": 1}), + ] { + assert!(s.execute(CMD, p.clone()).is_err(), "{p}"); + } + // Everything selected leaves nothing to sample from. + s.execute("select.all", json!({})).unwrap(); + assert!(s.execute(CMD, json!({"contents": "contentAware"})).is_err()); + // Out-of-range opacity is clamped. + s.execute(CMD, json!({"contents": "white", "opacity": 1e300})).unwrap(); +} + +/// A session whose canvas is `size` and whose selection is the given (sparse) rectangles, as +/// a loaded `.pcraft` can declare (#963): the canvas size is not capped on load and the +/// selection tiles can lie far apart. Nothing here allocates more than a few tiles. +fn huge_selection(size: (u32, u32), rects: &[Rect]) -> Session { + let mut s = session(); + s.execute(CMD, json!({"contents": "color", "color": "#336699"})).unwrap(); + let st = s.active_mut().unwrap(); + let doc = std::sync::Arc::make_mut(&mut st.doc); + doc.size = photocraft_geom::Size::new(size.0, size.1); + let mut sel = Surface::new(photocraft_color::PixelFormat::GRAY8); + for r in rects { + sel.fill_rect(*r, &[1.0]); + } + doc.selection = Some(sel); + s +} + +/// Content-Aware fill on a selection whose extent overflows the sampling-window arithmetic +/// (#963) returns the size error and leaves the document and history untouched. +#[test] +fn content_aware_huge_extent_is_an_error() { + // Largest extent whose `ext * 3` still fits in u32. + const EDGE: i32 = (u32::MAX / 3) as i32; + let max = i32::MAX; + let cases: [(&str, (u32, u32), Vec); 7] = [ + // The issue's repro: a second selection tile 5 600 000 tiles to the right. + ("issue repro", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 8, 8), Rect::new(5_600_000 * TILE_SIZE, 0, 5_600_000 * TILE_SIZE + 8, 8)]), + ("wide, just above", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(EDGE, 0, EDGE + 1, 1)]), + ("tall, just above", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(0, EDGE, 1, EDGE + 1)]), + ("wide, just below", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(EDGE - 1, 0, EDGE, 1)]), + ("tall, just below", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(0, EDGE - 1, 1, EDGE)]), + // The largest canvas a Rect can hold, selected corner to corner, plus a piece off the + // canvas at the most negative coordinate. + ( + "extreme coordinates", + (max as u32, max as u32), + vec![Rect::new(i32::MIN, i32::MIN, i32::MIN + 1, i32::MIN + 1), Rect::new(0, 0, 1, 1), Rect::new(max - 2, max - 2, max - 1, max - 1)], + ), + // A canvas wider than a Rect can hold is treated as empty, never as a panic. + ("canvas beyond i32", (u32::MAX, u32::MAX), vec![Rect::new(0, 0, 1, 1), Rect::new(max - 2, 0, max - 1, 1)]), + ]; + for (name, size, rects) in cases { + let mut s = huge_selection(size, &rects); + let before = s.active().unwrap().doc.clone(); + let past = s.active().unwrap().history.past_len(); + let r = s.execute(CMD, json!({"contents": "contentAware", "colorAdaptation": false})); + let err = r.expect_err(name).to_string(); + assert!(!err.contains("internal error"), "{name}: {err}"); + if name != "canvas beyond i32" { + assert!(err.contains("too large for Content-Aware fill"), "{name}: {err}"); + } + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, &st.doc), "{name}: the document changed"); + assert_eq!(st.history.past_len(), past, "{name}: a history step was recorded"); + assert!(close(px(&s, 5, 5), [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0, 1.0]), "{name}"); + } + // Control: an ordinary selection still fills from its surroundings. + let mut s = huge_selection((40, 30), &[Rect::new(15, 10, 21, 16)]); + s.execute(CMD, json!({"contents": "white"})).unwrap(); + s.execute(CMD, json!({"contents": "contentAware", "colorAdaptation": false})).unwrap(); + assert!(close(px(&s, 17, 12), [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0, 1.0]), "{:?}", px(&s, 17, 12)); +} + +/// A Stroke, Fill or Clear inside a selection keeps the tiles the selection doesn't reach as +/// they were (shared with the history), instead of storing a copy of each (#4517). +#[test] +fn unselected_tiles_stay_shared() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1024, "height": 1024, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#336699"})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let surf = |s: &Session| s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().clone(); + for (cmd, params) in [ + ("edit.fill", json!({"color": "#ff0000"})), + ("edit.stroke", json!({"width": 4, "color": "#00ff00", "location": "inside"})), + ("edit.clear", json!({})), + ] { + // Two small selections in opposite corners (256 px tiles): the selection's bounds + // span every tile, but only the two corner tiles have anything selected. + s.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 100})).unwrap(); + s.execute("select.rect", json!({"x": 900, "y": 900, "width": 100, "height": 100, "mode": "add"})).unwrap(); + let before = surf(&s); + s.execute(cmd, params).unwrap(); + let after = surf(&s); + let corners = [photocraft_geom::Rect::new(0, 0, 256, 256), photocraft_geom::Rect::new(768, 768, 1024, 1024)]; + let mut kept = 0; + for (c, t) in before.tiles() { + if corners.iter().all(|r| c.rect().intersect(r).is_empty()) { + assert!(after.tile(*c).is_some_and(|a| std::sync::Arc::ptr_eq(a, t)), "{cmd}: unselected tile {c:?} was copied"); + kept += 1; + } + } + assert_eq!(kept, 14, "{cmd}: the 14 tiles between the corners"); + for r in corners { + assert_ne!(before.read_region(r), after.read_region(r), "{cmd} changed the selected corner {r:?}"); + } + s.execute("select.deselect", json!({})).unwrap(); + } +} From 31899852e3c8ded6e79153f963eed4dd9ecc17af Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:14 +0000 Subject: [PATCH 035/259] refactor(engine): move layer_multi_cmds.rs tests to layer_multi_cmds/tests.rs --- crates/engine/src/layer_multi_cmds.rs | 1388 +------------------ crates/engine/src/layer_multi_cmds/tests.rs | 1385 ++++++++++++++++++ 2 files changed, 1386 insertions(+), 1387 deletions(-) create mode 100644 crates/engine/src/layer_multi_cmds/tests.rs diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs index 47114f7e5d..8942d9dd61 100644 --- a/crates/engine/src/layer_multi_cmds.rs +++ b/crates/engine/src/layer_multi_cmds.rs @@ -1805,1393 +1805,7 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn merge_with_background_preserves_background() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); - let bg_id = s.active().unwrap().doc.layers[0].id; - assert!(s.active().unwrap().doc.is_background(bg_id)); - let l1 = LayerId(s.execute("layer.new.layer", json!({"name": "Generative Fill"})).unwrap()["layer"].as_u64().unwrap()); - set_selection(&mut s, vec![bg_id, l1], Some(l1), Some(bg_id)).unwrap(); - let res = s.execute("layer.mergeLayers", json!({})).unwrap(); - let mid = LayerId(res["layer"].as_u64().unwrap()); - assert_eq!(mid, bg_id); - let doc = &s.active().unwrap().doc; - assert_eq!(doc.layers.len(), 1); - assert!(doc.is_background(mid)); - assert_eq!(doc.layers[0].name, "Background"); - } - - #[test] - fn duplicates_are_numbered_not_stacked() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Layer 1"})).unwrap(); - let name = |s: &Session| { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().name.clone() - }; - s.execute("layer.duplicate", json!({})).unwrap(); - assert_eq!(name(&s), "Layer 1 copy"); - // Duplicating the copy (the active layer) numbers it rather than adding "copy" again. - s.execute("layer.duplicate", json!({})).unwrap(); - assert_eq!(name(&s), "Layer 1 copy 2"); - s.execute("layer.duplicate", json!({})).unwrap(); - assert_eq!(name(&s), "Layer 1 copy 3"); - let doc = &s.active().unwrap().doc; - assert_eq!(doc.copy_name("Layer 1"), "Layer 1 copy 4"); - // Names that merely contain "copy" keep it. - assert_eq!(doc.copy_name("Copywriting"), "Copywriting copy"); - assert_eq!(doc.copy_name("A copyedit"), "A copyedit copy"); - } - - fn session(depth: u32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 80, "depth": depth})).unwrap(); - s - } - - fn doc(s: &Session) -> &Document { - &s.active().unwrap().doc - } - - /// New pixel layer with an opaque red rectangle. - fn rect_layer(s: &mut Session, r: Rect) -> LayerId { - let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.edit("paint", |doc, _| { - doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(r, &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - id - } - - fn bounds(s: &Session, id: LayerId) -> Rect { - layer_bounds(doc(s).layer(id).unwrap()).unwrap() - } - - fn sel(s: &Session) -> Vec { - selected(s) - } - - fn damage(s: &Session) -> Option { - s.active().unwrap().last_damage - } - - /// A Photoshop action's nudge in points moves whole pixels at the document's resolution: - /// 0.36 pt is 1 px at 200 ppi and 1.5 → 2 px at 300 ppi. - #[test] - fn translate_in_points_follows_the_resolution() { - for (res, moved) in [(200, 1), (300, 2), (72, 0)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 80, "resolution": res})).unwrap(); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - s.execute("layer.translate", json!({"dx": 0.36, "dy": -0.36, "units": "pt"})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(10 + moved, 10 - moved, 20 + moved, 20 - moved), "{res} ppi"); - } - let mut s = session(8); - rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - for bad in [json!({"dx": 1, "units": "in"}), json!({"dx": "x", "units": "pt"}), json!({"dx": 1e300, "units": "pt"})] { - assert!(s.execute("layer.translate", bad.clone()).is_err(), "{bad}"); - } - } - - /// `remove` deselects a selected layer, leaves an unselected one alone and never empties the - /// selection. - #[test] - fn select_remove_takes_a_layer_out_of_the_selection() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - let b = rect_layer(&mut s, Rect::new(30, 10, 40, 20)); - let c = rect_layer(&mut s, Rect::new(50, 10, 60, 20)); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); - s.execute("layer.select", json!({"layer": c.0, "mode": "remove"})).unwrap(); - assert_eq!(sel(&s).len(), 2, "an unselected layer stays out"); - s.execute("layer.select", json!({"layer": b.0, "mode": "remove"})).unwrap(); - assert_eq!(sel(&s), vec![a]); - s.execute("layer.select", json!({"layer": a.0, "mode": "remove"})).unwrap(); - assert_eq!(sel(&s), vec![a], "the last selected layer stays"); - } - - /// A mask with its chain off stays put while the layer moves; a linked one moves along. - #[test] - fn translate_leaves_an_unlinked_mask_in_place() { - for depth in [8, 16] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.layerMask.hideAll", json!({})).unwrap(); - s.edit("mask", |doc, _| { - doc.layer_mut(a).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(12, 12, 18, 18), &[1.0]); - Ok(()) - }) - .unwrap(); - let mval = |s: &Session, x, y| doc(s).layer(a).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0); - s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap(); - s.execute("layer.translate", json!({"dx": 30, "dy": 0})).unwrap(); - assert!(mval(&s, 14, 14) > 0.9, "{depth}-bit: unlinked mask stays"); - assert!(mval(&s, 44, 14) < 0.1); - s.execute("edit.undo", json!({})).unwrap(); - s.execute("layer.layerMask.linked", json!({"linked": true})).unwrap(); - s.execute("layer.translate", json!({"dx": 30, "dy": 0})).unwrap(); - assert!(mval(&s, 44, 14) > 0.9, "{depth}-bit: linked mask moves"); - } - } - - /// Aimed at the mask, a move shifts an unlinked mask alone and leaves a linked one with its layer. - #[test] - fn translate_with_the_mask_targeted_moves_an_unlinked_mask_alone() { - for depth in [8, 16] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.layerMask.hideAll", json!({})).unwrap(); - s.edit("mask", |doc, _| { - doc.layer_mut(a).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(12, 12, 18, 18), &[1.0]); - Ok(()) - }) - .unwrap(); - let mval = |s: &Session, x, y| doc(s).layer(a).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0); - // Linked: the layer and its mask move together. - s.execute("layer.translate", json!({"dx": 30, "dy": 0, "target": "mask"})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(40, 10, 50, 20), "{depth}-bit"); - assert!(mval(&s, 44, 14) > 0.9); - s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap(); - s.execute("layer.translate", json!({"dx": -30, "dy": 0, "target": "mask"})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(40, 10, 50, 20), "{depth}-bit: the layer stays"); - assert!(mval(&s, 14, 14) > 0.9, "the mask moved"); - assert!(mval(&s, 44, 14) < 0.1); - s.execute("edit.undo", json!({})).unwrap(); - assert!(mval(&s, 44, 14) > 0.9, "undo puts the mask back"); - } - } - - #[test] - fn moves_and_layer_props_report_only_their_area() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.translate", json!({"dx": 5, "dy": -3})).unwrap(); - assert_eq!(damage(&s), Some(Rect::new(10, 7, 25, 20)), "where the layer was and is"); - s.execute("layer.setProps", json!({"layer": a.0, "visible": false})).unwrap(); - 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. - s.execute("layer.setProps", json!({"layer": a.0, "clipped": true})).unwrap(); - assert_eq!(damage(&s), None); - // An adjustment layer changes everything beneath it. - 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); - // The Background (opaque everywhere): everything. - let bg = doc(&s).layers[0].id; - s.execute("layer.setProps", json!({"layer": bg.0, "opacity": 0.5})).unwrap(); - let all = doc(&s).bounds(); - assert!(damage(&s).is_none_or(|r| r.contains_rect(&all)), "{:?}", damage(&s)); - // Bad params still fail cleanly. - assert!(s.execute("layer.setProps", json!({"layer": u64::MAX, "visible": true})).is_err()); - assert!(s.execute("layer.translate", json!({"layer": u64::MAX, "dx": 1})).is_err()); - } - - /// #1771: a new empty layer or group changes no pixels, so it (and undoing or redoing it) - /// must not make the canvas recomposite every layer of the document. - #[test] - fn new_empty_layers_and_groups_damage_nothing() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - let composite = |s: &Session| photocraft_compose::render(doc(s), doc(s).bounds()); - let shown = composite(&s); - s.execute("layer.new.layer", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit new layer"); - assert_eq!(composite(&s), shown, "an empty layer changes no pixels"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit undo New Layer"); - s.execute("edit.redo", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit redo New Layer"); - s.execute("layer.new.group", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit new group"); - // Inside a group too. - let child = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); - let g = s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.select", json!({"layer": child})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit new layer in a group"); - assert!(doc(&s).layer(LayerId(g)).and_then(Layer::children).is_some_and(|c| c.len() == 2)); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::EMPTY)); - // Undoing a step that painted still reports that area, not nothing. - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.translate", json!({"dx": 5, "dy": 0})).unwrap(); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::new(10, 10, 25, 20))); - } - } - - #[test] - fn new_layers_that_change_clipping_recomposite_everything() { - let mut s = session(8); - let base = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - let clipped = rect_layer(&mut s, Rect::new(0, 0, 100, 80)); - s.edit("green", |doc, _| { - doc.layer_mut(clipped).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 100, 80), &[0.0, 1.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("layer.setProps", json!({"layer": clipped.0, "clipped": true})).unwrap(); - // New Layer between a clipping base and its clipped layer joins their clip group (#2203), - // so it draws nothing; an empty layer there that stayed unclipped would become their base. - s.execute("layer.select", json!({"layer": base.0})).unwrap(); - let shown = photocraft_compose::render(doc(&s), doc(&s).bounds()); - let before = doc(&s).clone(); - s.execute("layer.new.layer", json!({})).unwrap(); - assert_eq!(damage(&s), Some(Rect::EMPTY)); - assert_eq!(photocraft_compose::render(doc(&s), doc(&s).bounds()), shown); - let mut split = before.clone(); - split.insert_above(Some(base), Layer::raster("split", split.pixel_format())); - assert_ne!(photocraft_compose::render(&split, split.bounds()), shown); - assert_eq!(step_damage(&before, &split), None); - assert_eq!(step_damage(&split, &before), None); - s.execute("edit.undo", json!({})).unwrap(); - // A step that adds a layer with pixels (Layer via Copy, paste…) changes where it draws. - let before = doc(&s).clone(); - let mut after = before.clone(); - let mut l = Layer::raster("painted", after.pixel_format()); - l.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 2, 2), &[0.0, 1.0, 0.0, 1.0]); - after.insert_above(None, l); - assert_eq!(step_damage(&before, &after), Some(Rect::new(1, 1, 2, 2))); - assert_eq!(step_damage(&after, &before), Some(Rect::new(1, 1, 2, 2))); - // Unless it becomes the base of clipped layers above it. - let mut based = before.clone(); - let mut l = Layer::raster("base", based.pixel_format()); - l.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 2, 2), &[0.0, 1.0, 0.0, 1.0]); - let under = based.layers.iter().position(|l| l.id == clipped).unwrap(); - 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. - 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); - // Empty layers draw nothing, in any blend mode. - let mut styled = before.clone(); - let mut l = Layer::raster("styled", styled.pixel_format()); - l.blend = photocraft_doc::BlendMode::Multiply; - styled.insert_above(None, l); - assert_eq!(step_damage(&before, &styled), Some(Rect::EMPTY)); - let mut plain = before.clone(); - plain.insert_above(None, Layer::raster("plain", plain.pixel_format())); - assert_eq!(step_damage(&before, &plain), Some(Rect::EMPTY)); - assert_eq!(step_damage(&plain, &before), Some(Rect::EMPTY)); - } - - /// #6535: hiding or showing an adjustment clipped to a layer recomposites only that base's - /// area, also on undo and redo and inside a group, and recompositing just that area gives - /// the same canvas as a full recomposite. - #[test] - fn toggling_a_clipped_adjustment_damages_only_its_base() { - let all = |s: &Session| photocraft_compose::render(doc(s), doc(s).bounds()); - // Recomposite only the reported damage over the previous canvas, as the view does. - let patched = |s: &Session, prev: &photocraft_compose::Buffer| { - let r = damage(s).expect("bounded damage"); - let mut out = prev.clone(); - if r.is_empty() { - return out; - } - let part = photocraft_compose::render(doc(s), r); - let w = out.rect.width() as usize; - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - let i = (y - out.rect.y0) as usize * w + (x - out.rect.x0) as usize; - let k = (y - r.y0) as usize * r.width() as usize + (x - r.x0) as usize; - out.px[i] = part.px[k]; - } - } - out - }; - for grouped in [false, true] { - let mut s = session(16); - let base_rect = Rect::new(10, 10, 30, 25); - let base = rect_layer(&mut s, base_rect); - let adj = LayerId(s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.createClippingMask", json!({"layer": adj.0})).unwrap(); - assert!(doc(&s).layer(adj).unwrap().clipped); - if grouped { - s.execute("layer.select", json!({"layer": base.0})).unwrap(); - s.execute("layer.select", json!({"layer": adj.0, "mode": "toggle"})).unwrap(); - s.execute("layer.groupLayers", json!({})).unwrap(); - assert!(doc(&s).path_of(adj).unwrap().len() == 2, "the pair sits in a group"); - } - let shown = all(&s); - s.execute("layer.hideLayers", json!({"layer": adj.0})).unwrap(); - assert!(!doc(&s).layer(adj).unwrap().visible); - assert_eq!(damage(&s), Some(base_rect), "grouped: {grouped}"); - let hidden = all(&s); - assert_ne!(hidden, shown); - assert_eq!(patched(&s, &shown), hidden); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(damage(&s), Some(base_rect)); - assert_eq!(patched(&s, &hidden), shown); - s.execute("edit.redo", json!({})).unwrap(); - assert_eq!(damage(&s), Some(base_rect)); - assert_eq!(patched(&s, &shown), hidden); - s.execute("layer.showLayers", json!({"layer": adj.0})).unwrap(); - assert_eq!(damage(&s), Some(base_rect)); - assert_eq!(patched(&s, &hidden), shown); - // layer.setProps reports its own damage. - 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. - 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); - } - } - - /// #6535: hiding a clipped adjustment inside a pass-through group that is itself a clip base - /// can switch the group between isolated and pass-through rendering, so the step damages the - /// whole group, on undo, redo and when the adjustment is deleted too. - #[test] - fn clipped_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.5, 0.5, 1.0]); - 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.push(solid("bg", before.bounds(), BlendMode::Normal)); - let mut a = Layer::new("A", LayerContent::Adjustment(Adjustment::Invert)); - a.clipped = true; - 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, 3, 2), BlendMode::Normal); - x.clipped = true; - before.layers.push(x); - let mut after = before.clone(); - let LayerContent::Group(g) = &mut after.layers[2].content else { panic!("group") }; - g.children[1].visible = false; - let group = Some(Rect::new(2, 1, 8, 6)); - assert_eq!(step_damage(&before, &after), group); - assert_eq!(step_damage(&after, &before), group); - let mut deleted = before.clone(); - let LayerContent::Group(g) = &mut deleted.layers[2].content else { panic!("group") }; - g.children.remove(1); - assert_eq!(step_damage(&before, &deleted), group); - let LayerContent::Group(g) = &before.layers[2].content else { panic!("group") }; - let ids = [g.children[1].id]; - assert_eq!(layers_damage(&before, &after, &ids), group); - // Without the layer clipped to the group it stays pass-through: just A's base. - before.layers.truncate(3); - after.layers.truncate(3); - assert_eq!(step_damage(&before, &after), Some(Rect::new(2, 1, 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. - #[test] - fn duplicate_shares_tiles_and_damages_only_the_copy() { - let render = |s: &Session| photocraft_compose::render(doc(s), doc(s).bounds()); - let tiles = - |s: &Session, id: LayerId| doc(s).layer(id).unwrap().surface().unwrap().tiles().map(|(c, t)| (*c, std::sync::Arc::as_ptr(t))).collect::>(); - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - s.execute("layer.setProps", json!({"layer": a.0, "opacity": 0.5})).unwrap(); - let shown = render(&s); - let copy = LayerId(s.execute("layer.duplicate", json!({"layer": a.0})).unwrap()["layer"].as_u64().unwrap()); - assert_eq!(damage(&s), Some(Rect::new(10, 10, 20, 20)), "{depth}-bit: only where the copy draws"); - assert!(!tiles(&s, a).is_empty()); - assert_eq!(tiles(&s, copy), tiles(&s, a), "{depth}-bit: the copy shares the source's tiles"); - let now = render(&s); - assert_ne!(now, shown, "the half-transparent copy darkens its area"); - let w = shown.rect.width() as usize; - for (i, (p, q)) in shown.px.iter().zip(&now.px).enumerate() { - if !Rect::new(10, 10, 20, 20).contains((i % w) as i32, (i / w) as i32) { - assert_eq!(p, q, "{depth}-bit: pixel {i} outside the damage changed"); - } - } - s.execute("edit.undo", json!({})).unwrap(); - assert!(doc(&s).layer(copy).is_none()); - assert_eq!(render(&s), shown); - // A clipping base's copy goes between it and its clipped layer and becomes their base. - let clipped = rect_layer(&mut s, Rect::new(0, 0, 50, 50)); - s.execute("layer.setProps", json!({"layer": clipped.0, "clipped": true})).unwrap(); - s.execute("layer.duplicate", json!({"layer": a.0})).unwrap(); - assert_eq!(damage(&s), None, "{depth}-bit: a new clipping base"); - } - } - - /// The composite of `after` equals `before`'s outside `damage`. - fn unchanged_outside(before: &Document, after: &Document, damage: Rect) -> bool { - let (x, y) = (photocraft_compose::render(before, before.bounds()), photocraft_compose::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)) - } - - /// Duplicate (one layer or several), paste and delete, and their undo and redo, recomposite - /// only where the layers draw; undoing a duplicate used to recomposite the whole document. - #[test] - fn duplicate_paste_and_delete_report_where_the_layer_draws() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - let full = doc(&s).bounds(); - let step = |s: &mut Session, id: &str, p: serde_json::Value| { - let before = doc(s).clone(); - s.execute(id, p).unwrap(); - let d = damage(s).unwrap_or_else(|| panic!("{id}: unbounded damage")); - assert!(d.width() < full.width(), "{id}: {d:?}"); - assert!(unchanged_outside(&before, doc(s), d), "{id}: pixels changed outside {d:?}"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(damage(s), Some(d), "undo {id}"); - s.execute("edit.redo", json!({})).unwrap(); - assert_eq!(damage(s), Some(d), "redo {id}"); - }; - step(&mut s, "layer.duplicate", json!({"layer": a.0})); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("select.rect", json!({"x": 12, "y": 12, "width": 4, "height": 4})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - step(&mut s, "edit.paste", json!({})); - // Duplicating several selected layers reports where the copies draw, too. - let b = rect_layer(&mut s, Rect::new(30, 30, 40, 40)); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); - step(&mut s, "layer.duplicate", json!({})); - assert_eq!(damage(&s), Some(Rect::new(10, 10, 40, 40)), "both copies, nothing else"); - step(&mut s, "layer.delete", json!({"layer": a.0})); - } - - #[test] - fn the_move_preview_matches_the_move() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - let before = s.active().unwrap().doc.clone(); - let ids = move_targets(&before, &[a]); - let shown = moved(&before, &ids, 7, 4).unwrap(); - s.execute("layer.translate", json!({"layer": a.0, "dx": 7, "dy": 4})).unwrap(); - assert_eq!(layer_bounds(shown.layer(a).unwrap()), Some(bounds(&s, a))); - // Locked layers don't move in the preview either. - let mut locked = (*before).clone(); - locked.layer_mut(a).unwrap().locks.position = true; - assert!(moved(&locked, &ids, 1, 1).is_err()); - assert!(moved(&before, &[LayerId(u64::MAX)], 1, 1).is_err()); - } - - #[test] - fn move_stroked_shape_across_canvas_edge_matches_fresh_render() { - let mut s = session(8); - let id = LayerId( - s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 30, 30], "stroke": {"width": 4, "color": "#ff0000"}})).unwrap()["layer"] - .as_u64() - .unwrap(), - ); - let before = doc(&s).clone(); - let ids = move_targets(&before, &[id]); - - // Drag the stroked shape across the left canvas boundary: - let moved_doc = moved(&before, &ids, -25, 0).unwrap(); - let moved_layer = moved_doc.layer(id).unwrap(); - let LayerContent::Shape(sh) = &moved_layer.content else { panic!("not a shape") }; - let cached = sh.cache.as_ref().expect("cached render"); - - let mut fresh_sh = sh.clone(); - crate::vector_cmds::refresh_shape(&moved_doc, &mut fresh_sh); - let fresh = fresh_sh.cache.as_ref().expect("fresh render"); - - assert_eq!(cached, fresh, "dragged shape cached render must match fresh render across canvas edge"); - - // Drag it back inside the canvas: - let moved_back = moved(&moved_doc, &ids, 30, 0).unwrap(); - let back_layer = moved_back.layer(id).unwrap(); - let LayerContent::Shape(back_sh) = &back_layer.content else { panic!("not a shape") }; - let back_cached = back_sh.cache.as_ref().expect("cached render"); - - let mut fresh_back = back_sh.clone(); - crate::vector_cmds::refresh_shape(&moved_back, &mut fresh_back); - let fresh_back_render = fresh_back.cache.as_ref().expect("fresh render"); - - assert_eq!(back_cached, fresh_back_render, "cached render must match fresh render when dragged back"); - } - - fn select_all(s: &mut Session, ids: &[LayerId]) { - s.execute("layer.select", json!({"layer": ids[0].0})).unwrap(); - for id in &ids[1..] { - s.execute("layer.select", json!({"layer": id.0, "mode": "toggle"})).unwrap(); - } - } - - #[test] - fn toggle_and_range_selection() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let d = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - assert_eq!(sel(&s), vec![d]); - s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); - assert_eq!(sel(&s), vec![b, d]); - assert_eq!(s.active().unwrap().active_layer, Some(b)); - // Toggling the active layer off hands "active" to a remaining member. - s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); - assert_eq!(sel(&s), vec![d]); - assert_eq!(s.active().unwrap().active_layer, Some(d)); - // The last selected layer can't be toggled off. - s.execute("layer.select", json!({"layer": d.0, "mode": "toggle"})).unwrap(); - assert_eq!(sel(&s), vec![d]); - // Range from the anchor (a) to c. - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": c.0, "mode": "range"})).unwrap(); - assert_eq!(sel(&s), vec![a, b, c]); - // A second ⇧-click re-ranges from the same anchor. - s.execute("layer.select", json!({"layer": b.0, "mode": "range"})).unwrap(); - assert_eq!(sel(&s), vec![a, b]); - assert!(s.execute("layer.select", json!({"layer": b.0, "mode": "bogus"})).is_err()); - // Selection changes are not edits. - let history = s.active().unwrap().history.entries().len(); - s.execute("select.allLayers", json!({})).unwrap(); - assert_eq!(sel(&s), vec![a, b, c, d], "Select All Layers skips the locked Background"); - s.execute("select.deselectLayers", json!({})).unwrap(); - assert!(sel(&s).is_empty()); - assert_eq!(s.active().unwrap().history.entries().len(), history); - // Nothing selected: a no-op, not an error (#2457). - s.execute("select.deselectLayers", json!({})).unwrap(); - assert_eq!(s.active().unwrap().history.entries().len(), history); - // An explicit layer needs no active layer. - s.execute("layer.hideLayers", json!({"layer": a.0})).unwrap(); - assert!(!s.active().unwrap().doc.layer(a).unwrap().visible); - s.execute("layer.renameLayer", json!({"layer": a.0, "name": "x"})).unwrap(); - assert_eq!(s.active().unwrap().doc.layer(a).unwrap().name, "x"); - s.execute("layer.showLayers", json!({"layer": a.0})).unwrap(); - assert!(s.active().unwrap().doc.layer(a).unwrap().visible); - assert!(s.execute("layer.hideLayers", json!({"layer": u64::MAX})).is_err()); - assert!(s.execute("layer.hideLayers", json!({})).is_err()); - assert!(!s.is_enabled("layer.align.topEdges")); - } - - #[test] - fn find_layers_by_name() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - s.execute("layer.renameLayer", json!({"layer": a.0, "name": "Sky photo"})).unwrap(); - s.execute("layer.renameLayer", json!({"layer": b.0, "name": "Photo of sea"})).unwrap(); - assert_eq!(doc(&s).layer(a).unwrap().name, "Sky photo"); - let r = s.execute("select.findLayers", json!({"name": "PHOTO"})).unwrap(); - assert_eq!(r["selected"], json!([a.0, b.0])); - assert!(s.execute("select.findLayers", json!({"name": "nothing"})).is_err()); - assert!(s.execute("layer.renameLayer", json!({})).is_err()); - } - - #[test] - fn rename_layer_keeps_surrounding_spaces() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - s.execute("layer.renameLayer", json!({"layer": a.0, "name": " black skin bw "})).unwrap(); - assert_eq!(doc(&s).layer(a).unwrap().name, " black skin bw "); - assert!(s.execute("layer.renameLayer", json!({"layer": a.0, "name": " "})).is_err()); - assert_eq!(doc(&s).layer(a).unwrap().name, " black skin bw "); - } - - #[test] - fn align_each_edge() { - for depth in [8, 16, 32] { - let cases: [(&str, [Rect; 2]); 6] = [ - ("topEdges", [Rect::new(10, 5, 20, 15), Rect::new(40, 5, 50, 25)]), - ("bottomEdges", [Rect::new(10, 20, 20, 30), Rect::new(40, 10, 50, 30)]), - // Union 5..30: centre 17.5; half-pixel offsets round towards the top. - ("verticalCenters", [Rect::new(10, 12, 20, 22), Rect::new(40, 7, 50, 27)]), - ("leftEdges", [Rect::new(10, 5, 20, 15), Rect::new(10, 10, 50, 30)]), - ("rightEdges", [Rect::new(40, 5, 50, 15), Rect::new(10, 10, 50, 30)]), - ("horizontalCenters", [Rect::new(25, 5, 35, 15), Rect::new(10, 10, 50, 30)]), - ]; - for (kind, want) in cases { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(10, 5, 20, 15)); - let b = rect_layer(&mut s, Rect::new(40, 10, 50, 30)); - // For the horizontal cases make b wide so it defines the target bounds. - if !matches!(kind, "topEdges" | "bottomEdges" | "verticalCenters") { - s.edit("wide", |doc, _| { - doc.layer_mut(b).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 50, 30), &[0.0, 1.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - } - select_all(&mut s, &[a, b]); - s.execute(&format!("layer.align.{kind}"), json!({})).unwrap(); - assert_eq!([bounds(&s, a), bounds(&s, b)], want, "{kind} at {depth}-bit"); - // Pixels moved, not just bounds. - let r = want[0]; - assert_eq!(doc(&s).layer(a).unwrap().surface().unwrap().pixel(r.x0, r.y0)[..4], [1.0, 0.0, 0.0, 1.0]); - // One undo restores the original positions. - s.undo(); - assert_eq!(bounds(&s, a), Rect::new(10, 5, 20, 15)); - } - } - } - - #[test] - fn align_single_layer_to_selection() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - assert!(s.is_enabled("layer.align.leftEdges"), "one layer aligns to the canvas"); - s.execute("select.rect", json!({"x": 50, "y": 40, "width": 30, "height": 30})).unwrap(); - assert!(s.is_enabled("layer.align.leftEdges")); - s.execute("layer.align.rightEdges", json!({})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(70, 10, 80, 20)); - s.execute("layer.align.verticalCenters", json!({})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(70, 50, 80, 60)); - s.execute("layer.align.topEdges", json!({"to": "canvas"})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(70, 0, 80, 10)); - } - } - - #[test] - fn align_single_layer_to_canvas() { - // Photoshop: a single selected layer with no active selection aligns to the canvas. - let mut s = session(8); // 100 x 80 - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); // 10 x 10 - assert!(s.is_enabled("layer.align.horizontalCenters")); - s.execute("layer.align.horizontalCenters", json!({})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(45, 10, 55, 20), "centred on the 100px-wide canvas"); - s.execute("layer.align.verticalCenters", json!({})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(45, 35, 55, 45), "centred on the 80px-tall canvas"); - s.execute("layer.align.leftEdges", json!({})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(0, 35, 10, 45), "left edge to the canvas"); - } - - #[test] - fn distribute_uneven_layers() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); - let b = rect_layer(&mut s, Rect::new(12, 0, 32, 10)); // 20 wide - let c = rect_layer(&mut s, Rect::new(70, 0, 100, 10)); // 30 wide - select_all(&mut s, &[a, b, c]); - // Undo targets the layers its state had when it was created (#495): reselect. - assert!(s.is_enabled("layer.distribute.leftEdges")); - s.execute("layer.distribute.leftEdges", json!({})).unwrap(); - assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10), "left edges 0, 35, 70"); - s.undo(); - select_all(&mut s, &[a, b, c]); - s.execute("layer.distribute.horizontalCenters", json!({})).unwrap(); - // centres 5 and 85 → middle centre 45 - assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10)); - s.undo(); - select_all(&mut s, &[a, b, c]); - s.execute("layer.distribute.rightEdges", json!({})).unwrap(); - // right edges 10 and 100 → 55 - assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10)); - s.undo(); - select_all(&mut s, &[a, b, c]); - s.execute("layer.distribute.horizontally", json!({})).unwrap(); - // span 100, widths 60 → gaps of 20: b at 30..50 - assert_eq!(bounds(&s, b), Rect::new(30, 0, 50, 10)); - assert_eq!(bounds(&s, a), Rect::new(0, 0, 10, 10)); - assert_eq!(bounds(&s, c), Rect::new(70, 0, 100, 10)); - s.undo(); - assert_eq!(bounds(&s, b), Rect::new(12, 0, 32, 10)); - } - // Vertical: tall layers with uneven heights. - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); - let b = rect_layer(&mut s, Rect::new(0, 50, 10, 54)); - let c = rect_layer(&mut s, Rect::new(0, 60, 10, 80)); - select_all(&mut s, &[a, b, c]); - s.execute("layer.distribute.vertically", json!({})).unwrap(); - // span 80, heights 34 → gaps 23: b at 33..37 - assert_eq!(bounds(&s, b), Rect::new(0, 33, 10, 37)); - s.undo(); - select_all(&mut s, &[a, b, c]); - s.execute("layer.distribute.topEdges", json!({})).unwrap(); - assert_eq!(bounds(&s, b), Rect::new(0, 30, 10, 34)); - s.undo(); - select_all(&mut s, &[a, b, c]); - s.execute("layer.distribute.bottomEdges", json!({})).unwrap(); - assert_eq!(bounds(&s, b), Rect::new(0, 41, 10, 45)); - s.undo(); - select_all(&mut s, &[a, b, c]); - s.execute("layer.distribute.verticalCenters", json!({})).unwrap(); - // centres 5 and 70 → 37.5, b is 4 tall → top 35.5 → rounds to 36 (35 for ties down) - let y0 = bounds(&s, b).y0; - assert!((35..=36).contains(&y0), "{y0}"); - // Two layers can't be distributed. - select_all(&mut s, &[a, b]); - assert!(!s.is_enabled("layer.distribute.leftEdges")); - } - - #[test] - fn merge_keeps_pixels_outside_the_canvas() { - // #5067: the merged layer was cropped to the 100x80 canvas. - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(-30, -20, 10, 10)); - let b = rect_layer(&mut s, Rect::new(90, 70, 140, 120)); - select_all(&mut s, &[a, b]); - let m = LayerId(s.execute("layer.mergeLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); - let ml = doc(&s).layer(m).unwrap(); - assert_eq!(layer_bounds(ml).unwrap(), Rect::new(-30, -20, 140, 120)); - assert_eq!(ml.surface().unwrap().pixel(-10, -5)[3], 1.0); - assert_eq!(ml.surface().unwrap().pixel(130, 110)[3], 1.0); - } - - #[test] - fn merge_down_and_merge_group_keep_pixels_outside_the_canvas() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(-30, -20, 10, 10)); - let b = rect_layer(&mut s, Rect::new(90, 70, 140, 120)); - s.execute("layer.mergeDown", json!({"layer": b.0})).unwrap(); - assert_eq!(layer_bounds(doc(&s).layer(a).unwrap()).unwrap(), Rect::new(-30, -20, 140, 120)); - - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(-30, -20, 10, 10)); - let b = rect_layer(&mut s, Rect::new(90, 70, 140, 120)); - select_all(&mut s, &[a, b]); - let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.mergeGroup", json!({"layer": g.0})).unwrap(); - assert_eq!(layer_bounds(doc(&s).layer(g).unwrap()).unwrap(), Rect::new(-30, -20, 140, 120)); - } - - #[test] - fn merge_selected_into_top_most() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); - let b = rect_layer(&mut s, Rect::new(20, 0, 30, 10)); - let c = rect_layer(&mut s, Rect::new(40, 0, 50, 10)); - s.execute("layer.renameLayer", json!({"layer": c.0, "name": "Top"})).unwrap(); - select_all(&mut s, &[a, c]); - let before = doc(&s).layer_count(); - let m = LayerId(s.execute("layer.mergeLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); - let d = doc(&s); - assert_eq!(d.layer_count(), before - 1); - let ml = d.layer(m).unwrap(); - assert_eq!(ml.name, "Top"); - assert_eq!(layer_bounds(ml).unwrap(), Rect::new(0, 0, 50, 10)); - assert_eq!(ml.surface().unwrap().pixel(5, 5)[..4], [1.0, 0.0, 0.0, 1.0]); - assert_eq!(ml.surface().unwrap().pixel(25, 5)[3], 0.0, "b was not merged"); - assert!(d.layer(b).is_some() && d.layer(a).is_none()); - assert_eq!(d.layers.last().unwrap().id, m, "merged layer sits where the top-most was"); - assert_eq!(sel(&s), vec![m]); - s.undo(); - assert_eq!(doc(&s).layer_count(), before); - assert_eq!(sel(&s), vec![a, c], "undo selects the layers that were merged"); - // One layer selected: Merge Down. - s.execute("layer.select", json!({"layer": c.0})).unwrap(); - s.execute("layer.mergeLayers", json!({})).unwrap(); - assert_eq!(doc(&s).layer_count(), before - 1); - } - } - - #[test] - fn merging_group_children_preserves_their_composite() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let lower = rect_layer(&mut s, Rect::new(10, 12, 40, 42)); - let upper = rect_layer(&mut s, Rect::new(25, 20, 55, 50)); - select_all(&mut s, &[lower, upper]); - let group = LayerId(s.execute("layer.groupLayers", json!({"name": "Merge test group"})).unwrap()["layer"].as_u64().unwrap()); - let doc_before = doc(&s); - let expected = photocraft_compose::render(doc_before, doc_before.bounds()); - let children = doc_before.layer(group).unwrap().children().unwrap().iter().map(|layer| layer.id).collect::>(); - - select_all(&mut s, &children); - s.execute("layer.mergeLayers", json!({})).unwrap(); - let doc_after = doc(&s); - let actual = photocraft_compose::render(doc_after, doc_after.bounds()); - assert_eq!(actual, expected, "depth {depth}: group merge changed rendered pixels"); - assert_eq!(doc_after.layer(group).unwrap().children().unwrap().len(), 1); - } - } - - #[test] - fn merging_keeps_layer_effects_outside_the_pixels() { - // A drop shadow reaches past the layer's pixels; the merge must render that far. - for depth in [8, 16, 32] { - let mut s = session(depth); - let lower = rect_layer(&mut s, Rect::new(10, 10, 30, 30)); - let upper = rect_layer(&mut s, Rect::new(40, 20, 60, 40)); - s.execute("layer.layerStyle.dropShadow", json!({"layer": upper.0, "blend": "normal", "distance": 12, "size": 4})).unwrap(); - let before = photocraft_compose::render(doc(&s), doc(&s).bounds()); - select_all(&mut s, &[lower, upper]); - s.execute("layer.mergeLayers", json!({})).unwrap(); - let after = photocraft_compose::render(doc(&s), doc(&s).bounds()); - let worst = before.px.iter().zip(&after.px).map(|(a, b)| a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max)).fold(0.0f32, f32::max); - assert!(worst <= 1.5 / 255.0, "depth {depth}: merge layers dropped the shadow (off by {worst})"); - } - } - - #[test] - fn merging_a_group_down_preserves_the_composite() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let lower = rect_layer(&mut s, Rect::new(10, 12, 50, 52)); - let child_a = rect_layer(&mut s, Rect::new(24, 20, 64, 60)); - let child_b = rect_layer(&mut s, Rect::new(35, 28, 75, 68)); - select_all(&mut s, &[child_a, child_b]); - let group = LayerId(s.execute("layer.groupLayers", json!({"name": "Merge down group"})).unwrap()["layer"].as_u64().unwrap()); - let doc_before = doc(&s); - let expected = photocraft_compose::render(doc_before, doc_before.bounds()); - - s.execute("layer.mergeDown", json!({"layer": group.0})).unwrap(); - let doc_after = doc(&s); - let actual = photocraft_compose::render(doc_after, doc_after.bounds()); - assert_eq!(actual, expected, "depth {depth}: group merge down changed rendered pixels"); - assert!(doc_after.layer(lower).is_some()); - assert!(doc_after.layer(group).is_none()); - } - } - - #[test] - fn a_locked_group_locks_its_contents() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let g = s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.setProps", json!({"layer": g, "locked": true})).unwrap(); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - for (cmd, p) in [ - ("layer.translate", json!({"dx": 1})), - ("paint.stroke", json!({"points": [[2, 2], [4, 4]]})), - ("edit.fill", json!({"color": "#00ff00"})), - ("edit.transform.flipHorizontal", json!({})), - ] { - assert!(s.execute(cmd, p).is_err(), "{cmd} edited a layer in a locked group"); - } - // Unlocking the group releases its contents. - s.execute("layer.setProps", json!({"layer": g, "locked": false})).unwrap(); - s.execute("layer.translate", json!({"dx": 1})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(1, 0, 6, 5)); - } - - #[test] - fn a_locked_group_keeps_a_grouped_background_locked() { - let mut s = session(8); - let bg = doc(&s).layers[0].id; - s.execute("layer.select", json!({"layer": bg.0})).unwrap(); - let g = s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.setProps", json!({"layer": g, "locked": true})).unwrap(); - s.execute("layer.select", json!({"layer": bg.0})).unwrap(); - for (cmd, p) in [ - ("edit.transform.flipHorizontal", json!({})), - ("edit.transform.warp", json!({"style": "flag", "bend": 50})), - ("edit.puppetWarp", json!({"pins": [{"src": [30, 25], "dst": [36, 29]}]})), - ] { - let e = s.execute(cmd, p).unwrap_err().to_string(); - assert!(e.contains("locked"), "{cmd}: {e}"); - assert_eq!(doc(&s).layer(bg).unwrap().name, "Background", "{cmd}"); - } - } - - #[test] - fn group_from_layers_preserves_order() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let d = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - select_all(&mut s, &[c, a]); - let g = LayerId(s.execute("layer.new.groupFromLayers", json!({"name": "Pair"})).unwrap()["layer"].as_u64().unwrap()); - let docu = doc(&s); - let gl = docu.layer(g).unwrap(); - assert_eq!(gl.name, "Pair"); - assert!(matches!(&gl.content, LayerContent::Group(gr) if !gr.expanded), "created collapsed"); - assert_eq!(gl.children().unwrap().iter().map(|l| l.id).collect::>(), vec![a, c]); - // Root (bottom-to-top): Background, b, Pair (where c was), d. - assert_eq!(docu.layers.iter().map(|l| l.id).skip(1).collect::>(), vec![b, g, d]); - assert_eq!(sel(&s), vec![g]); - s.undo(); - assert_eq!(doc(&s).layers.len(), 5); - // ⌘G with several selected groups them too. - select_all(&mut s, &[b, d]); - let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); - assert_eq!(doc(&s).layers.len(), 4); - // Both create the group collapsed, as Photoshop does (#5571). - assert!(matches!(&doc(&s).layer(g).unwrap().content, LayerContent::Group(gr) if !gr.expanded)); - } - - #[test] - fn grouping_is_capped_at_the_document_nesting_limit() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - select_all(&mut s, &[a]); - for _ in 0..photocraft_doc::MAX_GROUP_DEPTH { - s.execute("layer.groupLayers", json!({})).unwrap(); - } - assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH); - // One more wrapping group would pass the cap: rejected, document untouched. - let err = s.execute("layer.groupLayers", json!({})).unwrap_err(); - assert!(err.to_string().contains("deeper than 100"), "{err}"); - assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH); - // The rejected call recorded no history step: undo still lands one grouping earlier. - s.undo(); - assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH - 1); - } - - #[test] - fn select_linked_layers_excludes_an_unlinked_active_layer() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); - let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); - let other = rect_layer(&mut s, Rect::new(50, 50, 60, 60)); - select_all(&mut s, &[a, b]); - s.execute("layer.linkLayers", json!({})).unwrap(); - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.select", json!({"layer": other.0, "mode": "toggle"})).unwrap(); - assert_eq!(sel(&s), vec![a, other]); - assert_eq!(s.active().unwrap().active_layer, Some(other)); - let past = s.active().unwrap().history.past_len(); - let dirty = s.active().unwrap().is_dirty(); - - let result = s.execute("layer.selectLinkedLayers", json!({})).unwrap(); - assert_eq!(sel(&s), vec![a, b]); - assert_eq!(result["selected"], sel(&s).len()); - assert_eq!(s.active().unwrap().active_layer, Some(b)); - assert_eq!(s.active().unwrap().layer_anchor, Some(b)); - assert_eq!(s.active().unwrap().history.past_len(), past); - assert_eq!(s.active().unwrap().is_dirty(), dirty); - - // A following multi-layer delete must leave the unrelated layer intact. - s.execute("layer.delete", json!({})).unwrap(); - assert!(doc(&s).layer(a).is_none() && doc(&s).layer(b).is_none()); - assert!(doc(&s).layer(other).is_some()); - s.undo(); - assert!(doc(&s).layer(a).is_some() && doc(&s).layer(b).is_some()); - assert!(doc(&s).layer(other).is_some()); - } - } - - #[test] - fn select_linked_layers_preserves_a_linked_active_layer() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); - let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); - select_all(&mut s, &[a, b]); - s.execute("layer.linkLayers", json!({})).unwrap(); - for active in [a, b] { - s.execute("layer.select", json!({"layer": active.0})).unwrap(); - let st = s.active_mut().unwrap(); - st.saved_revision = st.revision; - let past = st.history.past_len(); - for _ in 0..2 { - let result = s.execute("layer.selectLinkedLayers", json!({})).unwrap(); - assert_eq!(sel(&s), vec![a, b]); - assert_eq!(result["selected"], sel(&s).len()); - assert_eq!(s.active().unwrap().active_layer, Some(active)); - assert_eq!(s.active().unwrap().layer_anchor, Some(active)); - assert_eq!(s.active().unwrap().history.past_len(), past); - assert!(!s.active().unwrap().is_dirty()); - } - } - } - } - - #[test] - fn select_linked_layers_requires_a_linked_selection() { - let mut s = Session::new(); - assert!(!s.is_enabled("layer.selectLinkedLayers")); - assert!(s.execute("layer.selectLinkedLayers", json!({})).is_err()); - let mut s = session(8); - let before = sel(&s); - assert!(!s.is_enabled("layer.selectLinkedLayers")); - assert!(s.execute("layer.selectLinkedLayers", json!({})).is_err()); - assert_eq!(sel(&s), before); - } - - #[test] - fn translate_rejects_offsets_that_would_wrap() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - select_all(&mut s, &[a]); - // 2^32 + 50 wrapped to `dx = 50` and 3e9 to a negative offset through `as i32`. - for dx in [4_294_967_346_i64, 3_000_000_000_i64] { - let err = s.execute("layer.translate", json!({"dx": dx, "dy": 0})).unwrap_err(); - assert!(err.to_string().contains("32-bit"), "{err}"); - } - assert_eq!(bounds(&s, a), Rect::new(0, 0, 5, 5), "the layer never moved"); - // Large in-range offsets still work. - s.execute("layer.translate", json!({"dx": -200_000, "dy": 200_000})).unwrap(); - } - - #[test] - fn link_layers_never_reuses_a_group_when_the_largest_id_is_u64_max() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); - let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); - let c = rect_layer(&mut s, Rect::new(50, 50, 60, 60)); - let d = rect_layer(&mut s, Rect::new(70, 70, 80, 80)); - // A stored document can carry any id; `max + 1` once overflowed here. - let st = s.active_mut().unwrap(); - for id in [c, d] { - std::sync::Arc::make_mut(&mut st.doc).layer_mut(id).unwrap().link_group = Some(u64::MAX); - } - select_all(&mut s, &[a, b]); - assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], true); - let g = doc(&s).layer(a).unwrap().link_group; - assert_eq!(g, Some(1)); - assert_eq!(doc(&s).layer(b).unwrap().link_group, g); - for id in [c, d] { - assert_eq!(doc(&s).layer(id).unwrap().link_group, Some(u64::MAX), "the existing group is untouched"); - } - } - - #[test] - fn undo_and_redo_report_only_the_edited_area() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - select_all(&mut s, &[a]); - // A pixel edit on one layer is bounded by that layer's extent on both sides. - s.edit("paint", |doc, _| { - doc.layer_mut(a).unwrap().surface_mut().unwrap().fill_rect(Rect::new(12, 12, 14, 14), &[0.0, 0.0, 1.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.undo(); - assert_eq!(damage(&s), Some(Rect::new(10, 10, 20, 20))); - s.redo(); - assert_eq!(damage(&s), Some(Rect::new(10, 10, 20, 20))); - // A move reports where the layer was and where it landed. - s.execute("layer.translate", json!({"dx": 5, "dy": 0})).unwrap(); - s.undo(); - assert_eq!(damage(&s), Some(Rect::new(10, 10, 25, 20)), "union of where the layer was and is"); - s.redo(); - assert_eq!(damage(&s), Some(Rect::new(10, 10, 25, 20))); - } - - #[test] - fn undo_of_document_wide_steps_still_composites_everything() { - let mut s = session(8); - let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - // A canvas change has no bounded damage. - s.execute("image.crop", json!({"x": 0, "y": 0, "width": 30, "height": 25})).unwrap(); - assert_ne!(doc(&s).size, photocraft_doc::Size::new(100, 80)); - s.undo(); - assert_eq!(damage(&s), None, "a size change recomposites the whole canvas"); - // A layer removed and restored changes only where it draws. - let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - select_all(&mut s, &[b]); - s.execute("layer.delete", json!({})).unwrap(); - s.undo(); - assert_eq!(damage(&s), Some(Rect::new(0, 0, 5, 5))); - } - - #[test] - fn undo_of_compositor_read_document_fields_composites_everything() { - let mut s = session(8); - let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); - // Global Light changes every effect's angle across the document. - s.execute("layer.layerStyle.globalLight", json!({"angle": 90.0})).unwrap(); - s.undo(); - assert_eq!(damage(&s), None, "a global-light change recomposites everything"); - // A mode change that keeps the pixel format (RGB → Indexed maps to RGB) neither. - s.execute("image.mode.indexedColor", json!({})).unwrap(); - s.undo(); - assert_eq!(damage(&s), None, "a mode change recomposites everything"); - } - - #[test] - fn undo_of_clipping_or_channel_exclusion_composites_everything() { - let mut s = session(8); - 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(); - s.undo(); - assert_eq!(damage(&s), None, "a clipping change recomposites everything"); - s.execute("layer.setProps", json!({"channels": [true, false, true]})).unwrap(); - s.undo(); - assert_eq!(damage(&s), None, "an excluded-channel change recomposites everything"); - } - - #[test] - fn linked_layers_move_together_and_undo() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); - let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); - let c = rect_layer(&mut s, Rect::new(50, 50, 60, 60)); - assert!(!s.is_enabled("layer.linkLayers")); - select_all(&mut s, &[a, b]); - assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], true); - let g = doc(&s).layer(a).unwrap().link_group; - assert!(g.is_some() && doc(&s).layer(b).unwrap().link_group == g); - // Move only a: b follows, c stays. - s.execute("layer.select", json!({"layer": a.0})).unwrap(); - s.execute("layer.translate", json!({"dx": 5, "dy": 3})).unwrap(); - assert_eq!(bounds(&s, a), Rect::new(5, 3, 15, 13)); - assert_eq!(bounds(&s, b), Rect::new(25, 23, 35, 33)); - assert_eq!(bounds(&s, c), Rect::new(50, 50, 60, 60)); - s.undo(); - assert_eq!(bounds(&s, a), Rect::new(0, 0, 10, 10)); - assert_eq!(bounds(&s, b), Rect::new(20, 20, 30, 30)); - // Select Linked Layers from just a. - s.execute("layer.selectLinkedLayers", json!({})).unwrap(); - assert_eq!(sel(&s), vec![a, b]); - // Multi-selection translate moves all selected (c added, unlinked). - s.execute("layer.select", json!({"layer": c.0, "mode": "toggle"})).unwrap(); - s.execute("layer.translate", json!({"dx": -1, "dy": 0})).unwrap(); - assert_eq!(bounds(&s, c), Rect::new(49, 50, 59, 60)); - assert_eq!(bounds(&s, a), Rect::new(-1, 0, 9, 10)); - // Toggle: linking the same group again unlinks. - select_all(&mut s, &[a, b]); - assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); - assert!(doc(&s).layer(a).unwrap().link_group.is_none()); - } - } - - /// Plain layers carrying stored link groups, as a loaded `.pcraft` or PSD can hold (#961). - fn stored_groups(s: &mut Session, groups: &[Option]) -> Vec { - let ids: Vec = groups.iter().map(|_| rect_layer(s, Rect::new(0, 0, 4, 4))).collect(); - s.edit("load groups", |doc, _| { - for (id, g) in ids.iter().zip(groups) { - doc.layer_mut(*id).unwrap().link_group = *g; - } - Ok(()) - }) - .unwrap(); - ids - } - - fn group(s: &Session, id: LayerId) -> Option { - doc(s).layer(id).unwrap().link_group - } - - /// Links `ids`, then checks they share one group no other layer uses (#961). - fn link_fresh(s: &mut Session, ids: &[LayerId]) -> u64 { - select_all(s, ids); - let past = s.active().unwrap().history.past_len(); - assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], true); - assert_eq!(s.active().unwrap().history.past_len(), past + 1); - let g = group(s, ids[0]).expect("linked"); - assert!(ids.iter().all(|id| group(s, *id) == Some(g))); - let members = doc(s).walk().iter().filter(|(_, _, l)| l.link_group == Some(g)).count(); - assert_eq!(members, ids.len(), "group {g} is shared with unselected layers"); - g - } - - #[test] - fn link_layers_beside_a_maximal_stored_group() { - // The issue's repro: one layer stored at u64::MAX, link it with an unlinked one. - let mut s = session(8); - let ids = stored_groups(&mut s, &[Some(u64::MAX), None]); - assert_ne!(link_fresh(&mut s, &ids), u64::MAX); - // Unlink and relink the pair: with no groups left, numbering starts over at 1. - assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); - assert!(ids.iter().all(|id| group(&s, *id).is_none())); - assert_eq!(link_fresh(&mut s, &ids), 1); - - // Two other layers linked beside an untouched maximal pair. - let mut s = session(8); - let ids = stored_groups(&mut s, &[Some(u64::MAX), Some(u64::MAX), None, None]); - let g = link_fresh(&mut s, &ids[2..]); - assert_ne!(g, u64::MAX); - assert_eq!((group(&s, ids[0]), group(&s, ids[1])), (Some(u64::MAX), Some(u64::MAX))); - } - - #[test] - fn unlink_a_maximal_stored_group() { - let mut s = session(8); - let ids = stored_groups(&mut s, &[Some(u64::MAX), Some(u64::MAX), None]); - select_all(&mut s, &ids[..2]); - assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); - assert!(ids.iter().all(|id| group(&s, *id).is_none())); - s.undo(); - assert_eq!((group(&s, ids[0]), group(&s, ids[1])), (Some(u64::MAX), Some(u64::MAX))); - // Relinking all three gets a working group. - link_fresh(&mut s, &ids); - } - - #[test] - fn link_layers_when_every_group_is_huge() { - // Unselected groups at the top of the range, including the 0 a wrapped id would join. - let top = [u64::MAX, u64::MAX - 1, u64::MAX - 2, 0, 1, 2]; - let stored: Vec> = top.iter().flat_map(|g| [Some(*g), Some(*g)]).chain([None, None, None, None]).collect(); - let mut s = session(8); - let ids = stored_groups(&mut s, &stored); - let n = top.len() * 2; - let g = link_fresh(&mut s, &ids[n..n + 2]); - assert!(!top.contains(&g), "{g} collides with a stored group"); - // A second link gets yet another group, and existing groups never change. - let h = link_fresh(&mut s, &ids[n + 2..]); - assert!(!top.contains(&h) && h != g); - for (i, t) in top.iter().enumerate() { - assert_eq!((group(&s, ids[2 * i]), group(&s, ids[2 * i + 1])), (Some(*t), Some(*t))); - } - // Moving a newly linked layer leaves the group-0 pair alone. - assert_eq!(with_links(doc(&s), &[ids[n]]), vec![ids[n], ids[n + 1]]); - } - - #[test] - fn link_layers_near_the_maximum() { - // max + 1 still fits: the new group is u64::MAX itself. - let mut s = session(8); - let ids = stored_groups(&mut s, &[Some(u64::MAX - 1), Some(u64::MAX - 1), None, None, None, None]); - assert_eq!(link_fresh(&mut s, &ids[2..4]), u64::MAX); - // The next link no longer fits above the maximum and takes a free id instead. - let g = link_fresh(&mut s, &ids[4..]); - assert!(g != u64::MAX && g != u64::MAX - 1); - } - - #[test] - fn link_layers_assigns_working_groups() { - // Control: ordinary documents keep getting max + 1, starting at 1. - let mut s = session(8); - let ids = stored_groups(&mut s, &[None, None, None, None]); - assert_eq!(link_fresh(&mut s, &ids[..2]), 1); - assert_eq!(link_fresh(&mut s, &ids[2..]), 2); - assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); - assert_eq!((group(&s, ids[2]), group(&s, ids[3])), (None, None)); - assert_eq!((group(&s, ids[0]), group(&s, ids[1])), (Some(1), Some(1))); - } - - #[test] - fn selection_pruned_after_delete_and_undo() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - select_all(&mut s, &[a, c]); - // Deleting one layer explicitly prunes it from the set. - s.execute("layer.delete", json!({"layer": a.0})).unwrap(); - assert_eq!(sel(&s), vec![c]); - s.undo(); - assert!(sel(&s).iter().all(|id| doc(&s).layer(*id).is_some())); - // Deleting with several selected removes them all, then selects the layer below. - select_all(&mut s, &[a, c]); - s.execute("layer.delete", json!({})).unwrap(); - assert!(doc(&s).layer(a).is_none() && doc(&s).layer(c).is_none()); - assert_eq!(doc(&s).layer_count(), 2); - assert_eq!(sel(&s).len(), 1); - assert!(s.active().unwrap().selected_layers.iter().all(|id| doc(&s).layer(*id).is_some())); - s.undo(); - assert_eq!(doc(&s).layer_count(), 4); - let _ = b; - // Redo then undo again keeps the set valid. - s.redo(); - assert!(sel(&s).iter().all(|id| doc(&s).layer(*id).is_some())); - } - - #[test] - fn duplicate_hide_lock_and_reverse_selected() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - select_all(&mut s, &[a, c]); - let r = s.execute("layer.duplicate", json!({})).unwrap(); - assert_eq!(r["layers"].as_array().unwrap().len(), 2); - assert_eq!(doc(&s).layer_count(), 6); - assert_eq!(sel(&s).len(), 2); - assert!(sel(&s).iter().all(|id| *id != a && *id != c)); - s.undo(); - select_all(&mut s, &[a, b]); - s.execute("layer.hideLayers", json!({})).unwrap(); - assert!(!doc(&s).layer(a).unwrap().visible && !doc(&s).layer(b).unwrap().visible && doc(&s).layer(c).unwrap().visible); - s.execute("layer.showLayers", json!({})).unwrap(); - assert!(doc(&s).layer(a).unwrap().visible); - s.execute("layer.lockLayers", json!({})).unwrap(); - assert!(doc(&s).layer(a).unwrap().locks.all && doc(&s).layer(b).unwrap().locks.all); - assert!(s.execute("layer.translate", json!({"dx": 1})).is_err(), "locked layers don't move"); - s.execute("layer.lockLayers", json!({})).unwrap(); - assert!(!doc(&s).layer(a).unwrap().locks.all); - s.execute("layer.lockLayers", json!({"position": true})).unwrap(); - assert!(doc(&s).layer(b).unwrap().locks.position && !doc(&s).layer(c).unwrap().locks.position); - // Reverse a, b, c. - select_all(&mut s, &[a, b, c]); - s.execute("layer.arrange.reverse", json!({})).unwrap(); - assert_eq!(doc(&s).layers.iter().skip(1).map(|l| l.id).collect::>(), vec![c, b, a]); - assert_eq!(s.active().unwrap().history.entries().last().map(|e| e.as_str()), Some("Reverse")); - } - - /// #4892: Lock Image Pixels includes Lock Transparent Pixels, so the two are never both on: - /// locking the pixels clears the transparency lock, which stays off while they are locked, - /// through both `layer.setProps` and `layer.lockLayers`. - #[test] - fn locking_pixels_clears_and_holds_off_the_transparency_lock() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); - let locks = |s: &Session| doc(s).layer(id).unwrap().locks; - s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap(); - assert!(locks(&s).transparency); - s.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap(); - assert!(locks(&s).pixels && !locks(&s).transparency, "locking the pixels clears the transparency lock"); - s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap(); - assert!(!locks(&s).transparency, "and it stays off while the pixels are locked"); - s.execute("layer.setProps", json!({"locks": {"transparency": true, "pixels": true}})).unwrap(); - assert!(locks(&s).pixels && !locks(&s).transparency, "both at once: the pixel lock wins"); - s.execute("layer.lockLayers", json!({"pixels": false})).unwrap(); - s.execute("layer.lockLayers", json!({"transparency": true})).unwrap(); - assert!(locks(&s).transparency && !locks(&s).pixels, "with the pixels unlocked it can be set again"); - s.execute("layer.lockLayers", json!({"pixels": true})).unwrap(); - assert!(locks(&s).pixels && !locks(&s).transparency); - assert!(s.execute("layer.setProps", json!({"locks": {"nope": true}})).is_err()); - } - - /// `document.inspect` lists the selected layers and marks them in the layer list. - #[test] - fn inspect_reports_selection() { - let mut s = session(8); - let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); - select_all(&mut s, &[a, b]); - let v = s.execute("document.inspect", json!({})).unwrap(); - assert_eq!(v["selectedLayers"], json!([a.0, b.0])); - assert_eq!(v["layers"][0]["selected"], true); - } - - /// #7538: `selection: true` moves the selection with the layers in the same step, as the Move - /// tool does with several layers selected; without it the selection stays. - #[test] - fn translate_can_carry_the_selection_in_the_same_step() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 100, "background": "transparent"})).unwrap(); - let a = s.active().unwrap().active_layer.unwrap(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); - s.execute("select.rect", json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap(); - s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - s.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 70, "height": 30})).unwrap(); - let sel = |s: &Session| s.active().unwrap().doc.selection.as_ref().map(|m| m.content_bounds()); - let bounds = |s: &Session, id: LayerId| s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds(); - let steps = s.active().unwrap().history.past_len(); - s.execute("layer.translate", json!({"dx": 7, "dy": 20, "selection": true})).unwrap(); - assert_eq!((bounds(&s, a), bounds(&s, b)), (Rect::new(17, 30, 37, 50), Rect::new(57, 30, 77, 50))); - assert_eq!(sel(&s), Some(Rect::new(12, 25, 82, 55)), "the selection came along"); - assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one step"); - s.undo(); - assert_eq!((sel(&s), bounds(&s, a)), (Some(Rect::new(5, 5, 75, 35)), Rect::new(10, 10, 30, 30)), "undone together"); - s.execute("layer.translate", json!({"dx": 7, "dy": 20})).unwrap(); - assert_eq!(sel(&s), Some(Rect::new(5, 5, 75, 35)), "without it the selection stays"); - let state = |s: &Session| (bounds(s, a), bounds(s, b), sel(s), s.active().unwrap().history.past_len()); - let before = state(&s); - for dx in [1, 0] { - assert!(s.execute("layer.translate", json!({"dx": dx, "selection": "yes"})).is_err(), "dx {dx}: a bad `selection` is an error"); - assert_eq!(state(&s), before, "dx {dx}: and changes nothing"); - } - } -} +mod tests; #[cfg(test)] mod layers_panel_parity_tests { diff --git a/crates/engine/src/layer_multi_cmds/tests.rs b/crates/engine/src/layer_multi_cmds/tests.rs new file mode 100644 index 0000000000..e8dd5a98f3 --- /dev/null +++ b/crates/engine/src/layer_multi_cmds/tests.rs @@ -0,0 +1,1385 @@ +use super::*; + +#[test] +fn merge_with_background_preserves_background() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); + let bg_id = s.active().unwrap().doc.layers[0].id; + assert!(s.active().unwrap().doc.is_background(bg_id)); + let l1 = LayerId(s.execute("layer.new.layer", json!({"name": "Generative Fill"})).unwrap()["layer"].as_u64().unwrap()); + set_selection(&mut s, vec![bg_id, l1], Some(l1), Some(bg_id)).unwrap(); + let res = s.execute("layer.mergeLayers", json!({})).unwrap(); + let mid = LayerId(res["layer"].as_u64().unwrap()); + assert_eq!(mid, bg_id); + let doc = &s.active().unwrap().doc; + assert_eq!(doc.layers.len(), 1); + assert!(doc.is_background(mid)); + assert_eq!(doc.layers[0].name, "Background"); +} + +#[test] +fn duplicates_are_numbered_not_stacked() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Layer 1"})).unwrap(); + let name = |s: &Session| { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().name.clone() + }; + s.execute("layer.duplicate", json!({})).unwrap(); + assert_eq!(name(&s), "Layer 1 copy"); + // Duplicating the copy (the active layer) numbers it rather than adding "copy" again. + s.execute("layer.duplicate", json!({})).unwrap(); + assert_eq!(name(&s), "Layer 1 copy 2"); + s.execute("layer.duplicate", json!({})).unwrap(); + assert_eq!(name(&s), "Layer 1 copy 3"); + let doc = &s.active().unwrap().doc; + assert_eq!(doc.copy_name("Layer 1"), "Layer 1 copy 4"); + // Names that merely contain "copy" keep it. + assert_eq!(doc.copy_name("Copywriting"), "Copywriting copy"); + assert_eq!(doc.copy_name("A copyedit"), "A copyedit copy"); +} + +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 80, "depth": depth})).unwrap(); + s +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +/// New pixel layer with an opaque red rectangle. +fn rect_layer(s: &mut Session, r: Rect) -> LayerId { + let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.edit("paint", |doc, _| { + doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(r, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + id +} + +fn bounds(s: &Session, id: LayerId) -> Rect { + layer_bounds(doc(s).layer(id).unwrap()).unwrap() +} + +fn sel(s: &Session) -> Vec { + selected(s) +} + +fn damage(s: &Session) -> Option { + s.active().unwrap().last_damage +} + +/// A Photoshop action's nudge in points moves whole pixels at the document's resolution: +/// 0.36 pt is 1 px at 200 ppi and 1.5 → 2 px at 300 ppi. +#[test] +fn translate_in_points_follows_the_resolution() { + for (res, moved) in [(200, 1), (300, 2), (72, 0)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 80, "resolution": res})).unwrap(); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + s.execute("layer.translate", json!({"dx": 0.36, "dy": -0.36, "units": "pt"})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(10 + moved, 10 - moved, 20 + moved, 20 - moved), "{res} ppi"); + } + let mut s = session(8); + rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + for bad in [json!({"dx": 1, "units": "in"}), json!({"dx": "x", "units": "pt"}), json!({"dx": 1e300, "units": "pt"})] { + assert!(s.execute("layer.translate", bad.clone()).is_err(), "{bad}"); + } +} + +/// `remove` deselects a selected layer, leaves an unselected one alone and never empties the +/// selection. +#[test] +fn select_remove_takes_a_layer_out_of_the_selection() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + let b = rect_layer(&mut s, Rect::new(30, 10, 40, 20)); + let c = rect_layer(&mut s, Rect::new(50, 10, 60, 20)); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + s.execute("layer.select", json!({"layer": c.0, "mode": "remove"})).unwrap(); + assert_eq!(sel(&s).len(), 2, "an unselected layer stays out"); + s.execute("layer.select", json!({"layer": b.0, "mode": "remove"})).unwrap(); + assert_eq!(sel(&s), vec![a]); + s.execute("layer.select", json!({"layer": a.0, "mode": "remove"})).unwrap(); + assert_eq!(sel(&s), vec![a], "the last selected layer stays"); +} + +/// A mask with its chain off stays put while the layer moves; a linked one moves along. +#[test] +fn translate_leaves_an_unlinked_mask_in_place() { + for depth in [8, 16] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.layerMask.hideAll", json!({})).unwrap(); + s.edit("mask", |doc, _| { + doc.layer_mut(a).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(12, 12, 18, 18), &[1.0]); + Ok(()) + }) + .unwrap(); + let mval = |s: &Session, x, y| doc(s).layer(a).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0); + s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap(); + s.execute("layer.translate", json!({"dx": 30, "dy": 0})).unwrap(); + assert!(mval(&s, 14, 14) > 0.9, "{depth}-bit: unlinked mask stays"); + assert!(mval(&s, 44, 14) < 0.1); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("layer.layerMask.linked", json!({"linked": true})).unwrap(); + s.execute("layer.translate", json!({"dx": 30, "dy": 0})).unwrap(); + assert!(mval(&s, 44, 14) > 0.9, "{depth}-bit: linked mask moves"); + } +} + +/// Aimed at the mask, a move shifts an unlinked mask alone and leaves a linked one with its layer. +#[test] +fn translate_with_the_mask_targeted_moves_an_unlinked_mask_alone() { + for depth in [8, 16] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.layerMask.hideAll", json!({})).unwrap(); + s.edit("mask", |doc, _| { + doc.layer_mut(a).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(12, 12, 18, 18), &[1.0]); + Ok(()) + }) + .unwrap(); + let mval = |s: &Session, x, y| doc(s).layer(a).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0); + // Linked: the layer and its mask move together. + s.execute("layer.translate", json!({"dx": 30, "dy": 0, "target": "mask"})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(40, 10, 50, 20), "{depth}-bit"); + assert!(mval(&s, 44, 14) > 0.9); + s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap(); + s.execute("layer.translate", json!({"dx": -30, "dy": 0, "target": "mask"})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(40, 10, 50, 20), "{depth}-bit: the layer stays"); + assert!(mval(&s, 14, 14) > 0.9, "the mask moved"); + assert!(mval(&s, 44, 14) < 0.1); + s.execute("edit.undo", json!({})).unwrap(); + assert!(mval(&s, 44, 14) > 0.9, "undo puts the mask back"); + } +} + +#[test] +fn moves_and_layer_props_report_only_their_area() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.translate", json!({"dx": 5, "dy": -3})).unwrap(); + assert_eq!(damage(&s), Some(Rect::new(10, 7, 25, 20)), "where the layer was and is"); + s.execute("layer.setProps", json!({"layer": a.0, "visible": false})).unwrap(); + 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. + s.execute("layer.setProps", json!({"layer": a.0, "clipped": true})).unwrap(); + assert_eq!(damage(&s), None); + // An adjustment layer changes everything beneath it. + 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); + // The Background (opaque everywhere): everything. + let bg = doc(&s).layers[0].id; + s.execute("layer.setProps", json!({"layer": bg.0, "opacity": 0.5})).unwrap(); + let all = doc(&s).bounds(); + assert!(damage(&s).is_none_or(|r| r.contains_rect(&all)), "{:?}", damage(&s)); + // Bad params still fail cleanly. + assert!(s.execute("layer.setProps", json!({"layer": u64::MAX, "visible": true})).is_err()); + assert!(s.execute("layer.translate", json!({"layer": u64::MAX, "dx": 1})).is_err()); +} + +/// #1771: a new empty layer or group changes no pixels, so it (and undoing or redoing it) +/// must not make the canvas recomposite every layer of the document. +#[test] +fn new_empty_layers_and_groups_damage_nothing() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + let composite = |s: &Session| photocraft_compose::render(doc(s), doc(s).bounds()); + let shown = composite(&s); + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit new layer"); + assert_eq!(composite(&s), shown, "an empty layer changes no pixels"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit undo New Layer"); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit redo New Layer"); + s.execute("layer.new.group", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit new group"); + // Inside a group too. + let child = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + let g = s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.select", json!({"layer": child})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::EMPTY), "{depth}-bit new layer in a group"); + assert!(doc(&s).layer(LayerId(g)).and_then(Layer::children).is_some_and(|c| c.len() == 2)); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::EMPTY)); + // Undoing a step that painted still reports that area, not nothing. + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.translate", json!({"dx": 5, "dy": 0})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 25, 20))); + } +} + +#[test] +fn new_layers_that_change_clipping_recomposite_everything() { + let mut s = session(8); + let base = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + let clipped = rect_layer(&mut s, Rect::new(0, 0, 100, 80)); + s.edit("green", |doc, _| { + doc.layer_mut(clipped).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 100, 80), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.setProps", json!({"layer": clipped.0, "clipped": true})).unwrap(); + // New Layer between a clipping base and its clipped layer joins their clip group (#2203), + // so it draws nothing; an empty layer there that stayed unclipped would become their base. + s.execute("layer.select", json!({"layer": base.0})).unwrap(); + let shown = photocraft_compose::render(doc(&s), doc(&s).bounds()); + let before = doc(&s).clone(); + s.execute("layer.new.layer", json!({})).unwrap(); + assert_eq!(damage(&s), Some(Rect::EMPTY)); + assert_eq!(photocraft_compose::render(doc(&s), doc(&s).bounds()), shown); + let mut split = before.clone(); + split.insert_above(Some(base), Layer::raster("split", split.pixel_format())); + assert_ne!(photocraft_compose::render(&split, split.bounds()), shown); + assert_eq!(step_damage(&before, &split), None); + assert_eq!(step_damage(&split, &before), None); + s.execute("edit.undo", json!({})).unwrap(); + // A step that adds a layer with pixels (Layer via Copy, paste…) changes where it draws. + let before = doc(&s).clone(); + let mut after = before.clone(); + let mut l = Layer::raster("painted", after.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 2, 2), &[0.0, 1.0, 0.0, 1.0]); + after.insert_above(None, l); + assert_eq!(step_damage(&before, &after), Some(Rect::new(1, 1, 2, 2))); + assert_eq!(step_damage(&after, &before), Some(Rect::new(1, 1, 2, 2))); + // Unless it becomes the base of clipped layers above it. + let mut based = before.clone(); + let mut l = Layer::raster("base", based.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(1, 1, 2, 2), &[0.0, 1.0, 0.0, 1.0]); + let under = based.layers.iter().position(|l| l.id == clipped).unwrap(); + 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. + 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); + // Empty layers draw nothing, in any blend mode. + let mut styled = before.clone(); + let mut l = Layer::raster("styled", styled.pixel_format()); + l.blend = photocraft_doc::BlendMode::Multiply; + styled.insert_above(None, l); + assert_eq!(step_damage(&before, &styled), Some(Rect::EMPTY)); + let mut plain = before.clone(); + plain.insert_above(None, Layer::raster("plain", plain.pixel_format())); + assert_eq!(step_damage(&before, &plain), Some(Rect::EMPTY)); + assert_eq!(step_damage(&plain, &before), Some(Rect::EMPTY)); +} + +/// #6535: hiding or showing an adjustment clipped to a layer recomposites only that base's +/// area, also on undo and redo and inside a group, and recompositing just that area gives +/// the same canvas as a full recomposite. +#[test] +fn toggling_a_clipped_adjustment_damages_only_its_base() { + let all = |s: &Session| photocraft_compose::render(doc(s), doc(s).bounds()); + // Recomposite only the reported damage over the previous canvas, as the view does. + let patched = |s: &Session, prev: &photocraft_compose::Buffer| { + let r = damage(s).expect("bounded damage"); + let mut out = prev.clone(); + if r.is_empty() { + return out; + } + let part = photocraft_compose::render(doc(s), r); + let w = out.rect.width() as usize; + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + let i = (y - out.rect.y0) as usize * w + (x - out.rect.x0) as usize; + let k = (y - r.y0) as usize * r.width() as usize + (x - r.x0) as usize; + out.px[i] = part.px[k]; + } + } + out + }; + for grouped in [false, true] { + let mut s = session(16); + let base_rect = Rect::new(10, 10, 30, 25); + let base = rect_layer(&mut s, base_rect); + let adj = LayerId(s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.createClippingMask", json!({"layer": adj.0})).unwrap(); + assert!(doc(&s).layer(adj).unwrap().clipped); + if grouped { + s.execute("layer.select", json!({"layer": base.0})).unwrap(); + s.execute("layer.select", json!({"layer": adj.0, "mode": "toggle"})).unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + assert!(doc(&s).path_of(adj).unwrap().len() == 2, "the pair sits in a group"); + } + let shown = all(&s); + s.execute("layer.hideLayers", json!({"layer": adj.0})).unwrap(); + assert!(!doc(&s).layer(adj).unwrap().visible); + assert_eq!(damage(&s), Some(base_rect), "grouped: {grouped}"); + let hidden = all(&s); + assert_ne!(hidden, shown); + assert_eq!(patched(&s, &shown), hidden); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(damage(&s), Some(base_rect)); + assert_eq!(patched(&s, &hidden), shown); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(damage(&s), Some(base_rect)); + assert_eq!(patched(&s, &shown), hidden); + s.execute("layer.showLayers", json!({"layer": adj.0})).unwrap(); + assert_eq!(damage(&s), Some(base_rect)); + assert_eq!(patched(&s, &hidden), shown); + // layer.setProps reports its own damage. + 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. + 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); + } +} + +/// #6535: hiding a clipped adjustment inside a pass-through group that is itself a clip base +/// can switch the group between isolated and pass-through rendering, so the step damages the +/// whole group, on undo, redo and when the adjustment is deleted too. +#[test] +fn clipped_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.5, 0.5, 1.0]); + 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.push(solid("bg", before.bounds(), BlendMode::Normal)); + let mut a = Layer::new("A", LayerContent::Adjustment(Adjustment::Invert)); + a.clipped = true; + 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, 3, 2), BlendMode::Normal); + x.clipped = true; + before.layers.push(x); + let mut after = before.clone(); + let LayerContent::Group(g) = &mut after.layers[2].content else { panic!("group") }; + g.children[1].visible = false; + let group = Some(Rect::new(2, 1, 8, 6)); + assert_eq!(step_damage(&before, &after), group); + assert_eq!(step_damage(&after, &before), group); + let mut deleted = before.clone(); + let LayerContent::Group(g) = &mut deleted.layers[2].content else { panic!("group") }; + g.children.remove(1); + assert_eq!(step_damage(&before, &deleted), group); + let LayerContent::Group(g) = &before.layers[2].content else { panic!("group") }; + let ids = [g.children[1].id]; + assert_eq!(layers_damage(&before, &after, &ids), group); + // Without the layer clipped to the group it stays pass-through: just A's base. + before.layers.truncate(3); + after.layers.truncate(3); + assert_eq!(step_damage(&before, &after), Some(Rect::new(2, 1, 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. +#[test] +fn duplicate_shares_tiles_and_damages_only_the_copy() { + let render = |s: &Session| photocraft_compose::render(doc(s), doc(s).bounds()); + let tiles = + |s: &Session, id: LayerId| doc(s).layer(id).unwrap().surface().unwrap().tiles().map(|(c, t)| (*c, std::sync::Arc::as_ptr(t))).collect::>(); + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + s.execute("layer.setProps", json!({"layer": a.0, "opacity": 0.5})).unwrap(); + let shown = render(&s); + let copy = LayerId(s.execute("layer.duplicate", json!({"layer": a.0})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 20, 20)), "{depth}-bit: only where the copy draws"); + assert!(!tiles(&s, a).is_empty()); + assert_eq!(tiles(&s, copy), tiles(&s, a), "{depth}-bit: the copy shares the source's tiles"); + let now = render(&s); + assert_ne!(now, shown, "the half-transparent copy darkens its area"); + let w = shown.rect.width() as usize; + for (i, (p, q)) in shown.px.iter().zip(&now.px).enumerate() { + if !Rect::new(10, 10, 20, 20).contains((i % w) as i32, (i / w) as i32) { + assert_eq!(p, q, "{depth}-bit: pixel {i} outside the damage changed"); + } + } + s.execute("edit.undo", json!({})).unwrap(); + assert!(doc(&s).layer(copy).is_none()); + assert_eq!(render(&s), shown); + // A clipping base's copy goes between it and its clipped layer and becomes their base. + let clipped = rect_layer(&mut s, Rect::new(0, 0, 50, 50)); + s.execute("layer.setProps", json!({"layer": clipped.0, "clipped": true})).unwrap(); + s.execute("layer.duplicate", json!({"layer": a.0})).unwrap(); + assert_eq!(damage(&s), None, "{depth}-bit: a new clipping base"); + } +} + +/// The composite of `after` equals `before`'s outside `damage`. +fn unchanged_outside(before: &Document, after: &Document, damage: Rect) -> bool { + let (x, y) = (photocraft_compose::render(before, before.bounds()), photocraft_compose::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)) +} + +/// Duplicate (one layer or several), paste and delete, and their undo and redo, recomposite +/// only where the layers draw; undoing a duplicate used to recomposite the whole document. +#[test] +fn duplicate_paste_and_delete_report_where_the_layer_draws() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + let full = doc(&s).bounds(); + let step = |s: &mut Session, id: &str, p: serde_json::Value| { + let before = doc(s).clone(); + s.execute(id, p).unwrap(); + let d = damage(s).unwrap_or_else(|| panic!("{id}: unbounded damage")); + assert!(d.width() < full.width(), "{id}: {d:?}"); + assert!(unchanged_outside(&before, doc(s), d), "{id}: pixels changed outside {d:?}"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(damage(s), Some(d), "undo {id}"); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(damage(s), Some(d), "redo {id}"); + }; + step(&mut s, "layer.duplicate", json!({"layer": a.0})); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("select.rect", json!({"x": 12, "y": 12, "width": 4, "height": 4})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + step(&mut s, "edit.paste", json!({})); + // Duplicating several selected layers reports where the copies draw, too. + let b = rect_layer(&mut s, Rect::new(30, 30, 40, 40)); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + step(&mut s, "layer.duplicate", json!({})); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 40, 40)), "both copies, nothing else"); + step(&mut s, "layer.delete", json!({"layer": a.0})); +} + +#[test] +fn the_move_preview_matches_the_move() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + let before = s.active().unwrap().doc.clone(); + let ids = move_targets(&before, &[a]); + let shown = moved(&before, &ids, 7, 4).unwrap(); + s.execute("layer.translate", json!({"layer": a.0, "dx": 7, "dy": 4})).unwrap(); + assert_eq!(layer_bounds(shown.layer(a).unwrap()), Some(bounds(&s, a))); + // Locked layers don't move in the preview either. + let mut locked = (*before).clone(); + locked.layer_mut(a).unwrap().locks.position = true; + assert!(moved(&locked, &ids, 1, 1).is_err()); + assert!(moved(&before, &[LayerId(u64::MAX)], 1, 1).is_err()); +} + +#[test] +fn move_stroked_shape_across_canvas_edge_matches_fresh_render() { + let mut s = session(8); + let id = LayerId( + s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 30, 30], "stroke": {"width": 4, "color": "#ff0000"}})).unwrap()["layer"] + .as_u64() + .unwrap(), + ); + let before = doc(&s).clone(); + let ids = move_targets(&before, &[id]); + + // Drag the stroked shape across the left canvas boundary: + let moved_doc = moved(&before, &ids, -25, 0).unwrap(); + let moved_layer = moved_doc.layer(id).unwrap(); + let LayerContent::Shape(sh) = &moved_layer.content else { panic!("not a shape") }; + let cached = sh.cache.as_ref().expect("cached render"); + + let mut fresh_sh = sh.clone(); + crate::vector_cmds::refresh_shape(&moved_doc, &mut fresh_sh); + let fresh = fresh_sh.cache.as_ref().expect("fresh render"); + + assert_eq!(cached, fresh, "dragged shape cached render must match fresh render across canvas edge"); + + // Drag it back inside the canvas: + let moved_back = moved(&moved_doc, &ids, 30, 0).unwrap(); + let back_layer = moved_back.layer(id).unwrap(); + let LayerContent::Shape(back_sh) = &back_layer.content else { panic!("not a shape") }; + let back_cached = back_sh.cache.as_ref().expect("cached render"); + + let mut fresh_back = back_sh.clone(); + crate::vector_cmds::refresh_shape(&moved_back, &mut fresh_back); + let fresh_back_render = fresh_back.cache.as_ref().expect("fresh render"); + + assert_eq!(back_cached, fresh_back_render, "cached render must match fresh render when dragged back"); +} + +fn select_all(s: &mut Session, ids: &[LayerId]) { + s.execute("layer.select", json!({"layer": ids[0].0})).unwrap(); + for id in &ids[1..] { + s.execute("layer.select", json!({"layer": id.0, "mode": "toggle"})).unwrap(); + } +} + +#[test] +fn toggle_and_range_selection() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let d = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + assert_eq!(sel(&s), vec![d]); + s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); + assert_eq!(sel(&s), vec![b, d]); + assert_eq!(s.active().unwrap().active_layer, Some(b)); + // Toggling the active layer off hands "active" to a remaining member. + s.execute("layer.select", json!({"layer": b.0, "mode": "toggle"})).unwrap(); + assert_eq!(sel(&s), vec![d]); + assert_eq!(s.active().unwrap().active_layer, Some(d)); + // The last selected layer can't be toggled off. + s.execute("layer.select", json!({"layer": d.0, "mode": "toggle"})).unwrap(); + assert_eq!(sel(&s), vec![d]); + // Range from the anchor (a) to c. + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": c.0, "mode": "range"})).unwrap(); + assert_eq!(sel(&s), vec![a, b, c]); + // A second ⇧-click re-ranges from the same anchor. + s.execute("layer.select", json!({"layer": b.0, "mode": "range"})).unwrap(); + assert_eq!(sel(&s), vec![a, b]); + assert!(s.execute("layer.select", json!({"layer": b.0, "mode": "bogus"})).is_err()); + // Selection changes are not edits. + let history = s.active().unwrap().history.entries().len(); + s.execute("select.allLayers", json!({})).unwrap(); + assert_eq!(sel(&s), vec![a, b, c, d], "Select All Layers skips the locked Background"); + s.execute("select.deselectLayers", json!({})).unwrap(); + assert!(sel(&s).is_empty()); + assert_eq!(s.active().unwrap().history.entries().len(), history); + // Nothing selected: a no-op, not an error (#2457). + s.execute("select.deselectLayers", json!({})).unwrap(); + assert_eq!(s.active().unwrap().history.entries().len(), history); + // An explicit layer needs no active layer. + s.execute("layer.hideLayers", json!({"layer": a.0})).unwrap(); + assert!(!s.active().unwrap().doc.layer(a).unwrap().visible); + s.execute("layer.renameLayer", json!({"layer": a.0, "name": "x"})).unwrap(); + assert_eq!(s.active().unwrap().doc.layer(a).unwrap().name, "x"); + s.execute("layer.showLayers", json!({"layer": a.0})).unwrap(); + assert!(s.active().unwrap().doc.layer(a).unwrap().visible); + assert!(s.execute("layer.hideLayers", json!({"layer": u64::MAX})).is_err()); + assert!(s.execute("layer.hideLayers", json!({})).is_err()); + assert!(!s.is_enabled("layer.align.topEdges")); +} + +#[test] +fn find_layers_by_name() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + s.execute("layer.renameLayer", json!({"layer": a.0, "name": "Sky photo"})).unwrap(); + s.execute("layer.renameLayer", json!({"layer": b.0, "name": "Photo of sea"})).unwrap(); + assert_eq!(doc(&s).layer(a).unwrap().name, "Sky photo"); + let r = s.execute("select.findLayers", json!({"name": "PHOTO"})).unwrap(); + assert_eq!(r["selected"], json!([a.0, b.0])); + assert!(s.execute("select.findLayers", json!({"name": "nothing"})).is_err()); + assert!(s.execute("layer.renameLayer", json!({})).is_err()); +} + +#[test] +fn rename_layer_keeps_surrounding_spaces() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + s.execute("layer.renameLayer", json!({"layer": a.0, "name": " black skin bw "})).unwrap(); + assert_eq!(doc(&s).layer(a).unwrap().name, " black skin bw "); + assert!(s.execute("layer.renameLayer", json!({"layer": a.0, "name": " "})).is_err()); + assert_eq!(doc(&s).layer(a).unwrap().name, " black skin bw "); +} + +#[test] +fn align_each_edge() { + for depth in [8, 16, 32] { + let cases: [(&str, [Rect; 2]); 6] = [ + ("topEdges", [Rect::new(10, 5, 20, 15), Rect::new(40, 5, 50, 25)]), + ("bottomEdges", [Rect::new(10, 20, 20, 30), Rect::new(40, 10, 50, 30)]), + // Union 5..30: centre 17.5; half-pixel offsets round towards the top. + ("verticalCenters", [Rect::new(10, 12, 20, 22), Rect::new(40, 7, 50, 27)]), + ("leftEdges", [Rect::new(10, 5, 20, 15), Rect::new(10, 10, 50, 30)]), + ("rightEdges", [Rect::new(40, 5, 50, 15), Rect::new(10, 10, 50, 30)]), + ("horizontalCenters", [Rect::new(25, 5, 35, 15), Rect::new(10, 10, 50, 30)]), + ]; + for (kind, want) in cases { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(10, 5, 20, 15)); + let b = rect_layer(&mut s, Rect::new(40, 10, 50, 30)); + // For the horizontal cases make b wide so it defines the target bounds. + if !matches!(kind, "topEdges" | "bottomEdges" | "verticalCenters") { + s.edit("wide", |doc, _| { + doc.layer_mut(b).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 50, 30), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + } + select_all(&mut s, &[a, b]); + s.execute(&format!("layer.align.{kind}"), json!({})).unwrap(); + assert_eq!([bounds(&s, a), bounds(&s, b)], want, "{kind} at {depth}-bit"); + // Pixels moved, not just bounds. + let r = want[0]; + assert_eq!(doc(&s).layer(a).unwrap().surface().unwrap().pixel(r.x0, r.y0)[..4], [1.0, 0.0, 0.0, 1.0]); + // One undo restores the original positions. + s.undo(); + assert_eq!(bounds(&s, a), Rect::new(10, 5, 20, 15)); + } + } +} + +#[test] +fn align_single_layer_to_selection() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + assert!(s.is_enabled("layer.align.leftEdges"), "one layer aligns to the canvas"); + s.execute("select.rect", json!({"x": 50, "y": 40, "width": 30, "height": 30})).unwrap(); + assert!(s.is_enabled("layer.align.leftEdges")); + s.execute("layer.align.rightEdges", json!({})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(70, 10, 80, 20)); + s.execute("layer.align.verticalCenters", json!({})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(70, 50, 80, 60)); + s.execute("layer.align.topEdges", json!({"to": "canvas"})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(70, 0, 80, 10)); + } +} + +#[test] +fn align_single_layer_to_canvas() { + // Photoshop: a single selected layer with no active selection aligns to the canvas. + let mut s = session(8); // 100 x 80 + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); // 10 x 10 + assert!(s.is_enabled("layer.align.horizontalCenters")); + s.execute("layer.align.horizontalCenters", json!({})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(45, 10, 55, 20), "centred on the 100px-wide canvas"); + s.execute("layer.align.verticalCenters", json!({})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(45, 35, 55, 45), "centred on the 80px-tall canvas"); + s.execute("layer.align.leftEdges", json!({})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(0, 35, 10, 45), "left edge to the canvas"); +} + +#[test] +fn distribute_uneven_layers() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); + let b = rect_layer(&mut s, Rect::new(12, 0, 32, 10)); // 20 wide + let c = rect_layer(&mut s, Rect::new(70, 0, 100, 10)); // 30 wide + select_all(&mut s, &[a, b, c]); + // Undo targets the layers its state had when it was created (#495): reselect. + assert!(s.is_enabled("layer.distribute.leftEdges")); + s.execute("layer.distribute.leftEdges", json!({})).unwrap(); + assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10), "left edges 0, 35, 70"); + s.undo(); + select_all(&mut s, &[a, b, c]); + s.execute("layer.distribute.horizontalCenters", json!({})).unwrap(); + // centres 5 and 85 → middle centre 45 + assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10)); + s.undo(); + select_all(&mut s, &[a, b, c]); + s.execute("layer.distribute.rightEdges", json!({})).unwrap(); + // right edges 10 and 100 → 55 + assert_eq!(bounds(&s, b), Rect::new(35, 0, 55, 10)); + s.undo(); + select_all(&mut s, &[a, b, c]); + s.execute("layer.distribute.horizontally", json!({})).unwrap(); + // span 100, widths 60 → gaps of 20: b at 30..50 + assert_eq!(bounds(&s, b), Rect::new(30, 0, 50, 10)); + assert_eq!(bounds(&s, a), Rect::new(0, 0, 10, 10)); + assert_eq!(bounds(&s, c), Rect::new(70, 0, 100, 10)); + s.undo(); + assert_eq!(bounds(&s, b), Rect::new(12, 0, 32, 10)); + } + // Vertical: tall layers with uneven heights. + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); + let b = rect_layer(&mut s, Rect::new(0, 50, 10, 54)); + let c = rect_layer(&mut s, Rect::new(0, 60, 10, 80)); + select_all(&mut s, &[a, b, c]); + s.execute("layer.distribute.vertically", json!({})).unwrap(); + // span 80, heights 34 → gaps 23: b at 33..37 + assert_eq!(bounds(&s, b), Rect::new(0, 33, 10, 37)); + s.undo(); + select_all(&mut s, &[a, b, c]); + s.execute("layer.distribute.topEdges", json!({})).unwrap(); + assert_eq!(bounds(&s, b), Rect::new(0, 30, 10, 34)); + s.undo(); + select_all(&mut s, &[a, b, c]); + s.execute("layer.distribute.bottomEdges", json!({})).unwrap(); + assert_eq!(bounds(&s, b), Rect::new(0, 41, 10, 45)); + s.undo(); + select_all(&mut s, &[a, b, c]); + s.execute("layer.distribute.verticalCenters", json!({})).unwrap(); + // centres 5 and 70 → 37.5, b is 4 tall → top 35.5 → rounds to 36 (35 for ties down) + let y0 = bounds(&s, b).y0; + assert!((35..=36).contains(&y0), "{y0}"); + // Two layers can't be distributed. + select_all(&mut s, &[a, b]); + assert!(!s.is_enabled("layer.distribute.leftEdges")); +} + +#[test] +fn merge_keeps_pixels_outside_the_canvas() { + // #5067: the merged layer was cropped to the 100x80 canvas. + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(-30, -20, 10, 10)); + let b = rect_layer(&mut s, Rect::new(90, 70, 140, 120)); + select_all(&mut s, &[a, b]); + let m = LayerId(s.execute("layer.mergeLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + let ml = doc(&s).layer(m).unwrap(); + assert_eq!(layer_bounds(ml).unwrap(), Rect::new(-30, -20, 140, 120)); + assert_eq!(ml.surface().unwrap().pixel(-10, -5)[3], 1.0); + assert_eq!(ml.surface().unwrap().pixel(130, 110)[3], 1.0); +} + +#[test] +fn merge_down_and_merge_group_keep_pixels_outside_the_canvas() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(-30, -20, 10, 10)); + let b = rect_layer(&mut s, Rect::new(90, 70, 140, 120)); + s.execute("layer.mergeDown", json!({"layer": b.0})).unwrap(); + assert_eq!(layer_bounds(doc(&s).layer(a).unwrap()).unwrap(), Rect::new(-30, -20, 140, 120)); + + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(-30, -20, 10, 10)); + let b = rect_layer(&mut s, Rect::new(90, 70, 140, 120)); + select_all(&mut s, &[a, b]); + let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.mergeGroup", json!({"layer": g.0})).unwrap(); + assert_eq!(layer_bounds(doc(&s).layer(g).unwrap()).unwrap(), Rect::new(-30, -20, 140, 120)); +} + +#[test] +fn merge_selected_into_top_most() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); + let b = rect_layer(&mut s, Rect::new(20, 0, 30, 10)); + let c = rect_layer(&mut s, Rect::new(40, 0, 50, 10)); + s.execute("layer.renameLayer", json!({"layer": c.0, "name": "Top"})).unwrap(); + select_all(&mut s, &[a, c]); + let before = doc(&s).layer_count(); + let m = LayerId(s.execute("layer.mergeLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + let d = doc(&s); + assert_eq!(d.layer_count(), before - 1); + let ml = d.layer(m).unwrap(); + assert_eq!(ml.name, "Top"); + assert_eq!(layer_bounds(ml).unwrap(), Rect::new(0, 0, 50, 10)); + assert_eq!(ml.surface().unwrap().pixel(5, 5)[..4], [1.0, 0.0, 0.0, 1.0]); + assert_eq!(ml.surface().unwrap().pixel(25, 5)[3], 0.0, "b was not merged"); + assert!(d.layer(b).is_some() && d.layer(a).is_none()); + assert_eq!(d.layers.last().unwrap().id, m, "merged layer sits where the top-most was"); + assert_eq!(sel(&s), vec![m]); + s.undo(); + assert_eq!(doc(&s).layer_count(), before); + assert_eq!(sel(&s), vec![a, c], "undo selects the layers that were merged"); + // One layer selected: Merge Down. + s.execute("layer.select", json!({"layer": c.0})).unwrap(); + s.execute("layer.mergeLayers", json!({})).unwrap(); + assert_eq!(doc(&s).layer_count(), before - 1); + } +} + +#[test] +fn merging_group_children_preserves_their_composite() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let lower = rect_layer(&mut s, Rect::new(10, 12, 40, 42)); + let upper = rect_layer(&mut s, Rect::new(25, 20, 55, 50)); + select_all(&mut s, &[lower, upper]); + let group = LayerId(s.execute("layer.groupLayers", json!({"name": "Merge test group"})).unwrap()["layer"].as_u64().unwrap()); + let doc_before = doc(&s); + let expected = photocraft_compose::render(doc_before, doc_before.bounds()); + let children = doc_before.layer(group).unwrap().children().unwrap().iter().map(|layer| layer.id).collect::>(); + + select_all(&mut s, &children); + s.execute("layer.mergeLayers", json!({})).unwrap(); + let doc_after = doc(&s); + let actual = photocraft_compose::render(doc_after, doc_after.bounds()); + assert_eq!(actual, expected, "depth {depth}: group merge changed rendered pixels"); + assert_eq!(doc_after.layer(group).unwrap().children().unwrap().len(), 1); + } +} + +#[test] +fn merging_keeps_layer_effects_outside_the_pixels() { + // A drop shadow reaches past the layer's pixels; the merge must render that far. + for depth in [8, 16, 32] { + let mut s = session(depth); + let lower = rect_layer(&mut s, Rect::new(10, 10, 30, 30)); + let upper = rect_layer(&mut s, Rect::new(40, 20, 60, 40)); + s.execute("layer.layerStyle.dropShadow", json!({"layer": upper.0, "blend": "normal", "distance": 12, "size": 4})).unwrap(); + let before = photocraft_compose::render(doc(&s), doc(&s).bounds()); + select_all(&mut s, &[lower, upper]); + s.execute("layer.mergeLayers", json!({})).unwrap(); + let after = photocraft_compose::render(doc(&s), doc(&s).bounds()); + let worst = before.px.iter().zip(&after.px).map(|(a, b)| a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max)).fold(0.0f32, f32::max); + assert!(worst <= 1.5 / 255.0, "depth {depth}: merge layers dropped the shadow (off by {worst})"); + } +} + +#[test] +fn merging_a_group_down_preserves_the_composite() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let lower = rect_layer(&mut s, Rect::new(10, 12, 50, 52)); + let child_a = rect_layer(&mut s, Rect::new(24, 20, 64, 60)); + let child_b = rect_layer(&mut s, Rect::new(35, 28, 75, 68)); + select_all(&mut s, &[child_a, child_b]); + let group = LayerId(s.execute("layer.groupLayers", json!({"name": "Merge down group"})).unwrap()["layer"].as_u64().unwrap()); + let doc_before = doc(&s); + let expected = photocraft_compose::render(doc_before, doc_before.bounds()); + + s.execute("layer.mergeDown", json!({"layer": group.0})).unwrap(); + let doc_after = doc(&s); + let actual = photocraft_compose::render(doc_after, doc_after.bounds()); + assert_eq!(actual, expected, "depth {depth}: group merge down changed rendered pixels"); + assert!(doc_after.layer(lower).is_some()); + assert!(doc_after.layer(group).is_none()); + } +} + +#[test] +fn a_locked_group_locks_its_contents() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let g = s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": g, "locked": true})).unwrap(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + for (cmd, p) in [ + ("layer.translate", json!({"dx": 1})), + ("paint.stroke", json!({"points": [[2, 2], [4, 4]]})), + ("edit.fill", json!({"color": "#00ff00"})), + ("edit.transform.flipHorizontal", json!({})), + ] { + assert!(s.execute(cmd, p).is_err(), "{cmd} edited a layer in a locked group"); + } + // Unlocking the group releases its contents. + s.execute("layer.setProps", json!({"layer": g, "locked": false})).unwrap(); + s.execute("layer.translate", json!({"dx": 1})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(1, 0, 6, 5)); +} + +#[test] +fn a_locked_group_keeps_a_grouped_background_locked() { + let mut s = session(8); + let bg = doc(&s).layers[0].id; + s.execute("layer.select", json!({"layer": bg.0})).unwrap(); + let g = s.execute("layer.new.groupFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": g, "locked": true})).unwrap(); + s.execute("layer.select", json!({"layer": bg.0})).unwrap(); + for (cmd, p) in [ + ("edit.transform.flipHorizontal", json!({})), + ("edit.transform.warp", json!({"style": "flag", "bend": 50})), + ("edit.puppetWarp", json!({"pins": [{"src": [30, 25], "dst": [36, 29]}]})), + ] { + let e = s.execute(cmd, p).unwrap_err().to_string(); + assert!(e.contains("locked"), "{cmd}: {e}"); + assert_eq!(doc(&s).layer(bg).unwrap().name, "Background", "{cmd}"); + } +} + +#[test] +fn group_from_layers_preserves_order() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let d = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[c, a]); + let g = LayerId(s.execute("layer.new.groupFromLayers", json!({"name": "Pair"})).unwrap()["layer"].as_u64().unwrap()); + let docu = doc(&s); + let gl = docu.layer(g).unwrap(); + assert_eq!(gl.name, "Pair"); + assert!(matches!(&gl.content, LayerContent::Group(gr) if !gr.expanded), "created collapsed"); + assert_eq!(gl.children().unwrap().iter().map(|l| l.id).collect::>(), vec![a, c]); + // Root (bottom-to-top): Background, b, Pair (where c was), d. + assert_eq!(docu.layers.iter().map(|l| l.id).skip(1).collect::>(), vec![b, g, d]); + assert_eq!(sel(&s), vec![g]); + s.undo(); + assert_eq!(doc(&s).layers.len(), 5); + // ⌘G with several selected groups them too. + select_all(&mut s, &[b, d]); + let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + assert_eq!(doc(&s).layers.len(), 4); + // Both create the group collapsed, as Photoshop does (#5571). + assert!(matches!(&doc(&s).layer(g).unwrap().content, LayerContent::Group(gr) if !gr.expanded)); +} + +#[test] +fn grouping_is_capped_at_the_document_nesting_limit() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[a]); + for _ in 0..photocraft_doc::MAX_GROUP_DEPTH { + s.execute("layer.groupLayers", json!({})).unwrap(); + } + assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH); + // One more wrapping group would pass the cap: rejected, document untouched. + let err = s.execute("layer.groupLayers", json!({})).unwrap_err(); + assert!(err.to_string().contains("deeper than 100"), "{err}"); + assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH); + // The rejected call recorded no history step: undo still lands one grouping earlier. + s.undo(); + assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH - 1); +} + +#[test] +fn select_linked_layers_excludes_an_unlinked_active_layer() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); + let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); + let other = rect_layer(&mut s, Rect::new(50, 50, 60, 60)); + select_all(&mut s, &[a, b]); + s.execute("layer.linkLayers", json!({})).unwrap(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": other.0, "mode": "toggle"})).unwrap(); + assert_eq!(sel(&s), vec![a, other]); + assert_eq!(s.active().unwrap().active_layer, Some(other)); + let past = s.active().unwrap().history.past_len(); + let dirty = s.active().unwrap().is_dirty(); + + let result = s.execute("layer.selectLinkedLayers", json!({})).unwrap(); + assert_eq!(sel(&s), vec![a, b]); + assert_eq!(result["selected"], sel(&s).len()); + assert_eq!(s.active().unwrap().active_layer, Some(b)); + assert_eq!(s.active().unwrap().layer_anchor, Some(b)); + assert_eq!(s.active().unwrap().history.past_len(), past); + assert_eq!(s.active().unwrap().is_dirty(), dirty); + + // A following multi-layer delete must leave the unrelated layer intact. + s.execute("layer.delete", json!({})).unwrap(); + assert!(doc(&s).layer(a).is_none() && doc(&s).layer(b).is_none()); + assert!(doc(&s).layer(other).is_some()); + s.undo(); + assert!(doc(&s).layer(a).is_some() && doc(&s).layer(b).is_some()); + assert!(doc(&s).layer(other).is_some()); + } +} + +#[test] +fn select_linked_layers_preserves_a_linked_active_layer() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); + let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); + select_all(&mut s, &[a, b]); + s.execute("layer.linkLayers", json!({})).unwrap(); + for active in [a, b] { + s.execute("layer.select", json!({"layer": active.0})).unwrap(); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let past = st.history.past_len(); + for _ in 0..2 { + let result = s.execute("layer.selectLinkedLayers", json!({})).unwrap(); + assert_eq!(sel(&s), vec![a, b]); + assert_eq!(result["selected"], sel(&s).len()); + assert_eq!(s.active().unwrap().active_layer, Some(active)); + assert_eq!(s.active().unwrap().layer_anchor, Some(active)); + assert_eq!(s.active().unwrap().history.past_len(), past); + assert!(!s.active().unwrap().is_dirty()); + } + } + } +} + +#[test] +fn select_linked_layers_requires_a_linked_selection() { + let mut s = Session::new(); + assert!(!s.is_enabled("layer.selectLinkedLayers")); + assert!(s.execute("layer.selectLinkedLayers", json!({})).is_err()); + let mut s = session(8); + let before = sel(&s); + assert!(!s.is_enabled("layer.selectLinkedLayers")); + assert!(s.execute("layer.selectLinkedLayers", json!({})).is_err()); + assert_eq!(sel(&s), before); +} + +#[test] +fn translate_rejects_offsets_that_would_wrap() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[a]); + // 2^32 + 50 wrapped to `dx = 50` and 3e9 to a negative offset through `as i32`. + for dx in [4_294_967_346_i64, 3_000_000_000_i64] { + let err = s.execute("layer.translate", json!({"dx": dx, "dy": 0})).unwrap_err(); + assert!(err.to_string().contains("32-bit"), "{err}"); + } + assert_eq!(bounds(&s, a), Rect::new(0, 0, 5, 5), "the layer never moved"); + // Large in-range offsets still work. + s.execute("layer.translate", json!({"dx": -200_000, "dy": 200_000})).unwrap(); +} + +#[test] +fn link_layers_never_reuses_a_group_when_the_largest_id_is_u64_max() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); + let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); + let c = rect_layer(&mut s, Rect::new(50, 50, 60, 60)); + let d = rect_layer(&mut s, Rect::new(70, 70, 80, 80)); + // A stored document can carry any id; `max + 1` once overflowed here. + let st = s.active_mut().unwrap(); + for id in [c, d] { + std::sync::Arc::make_mut(&mut st.doc).layer_mut(id).unwrap().link_group = Some(u64::MAX); + } + select_all(&mut s, &[a, b]); + assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], true); + let g = doc(&s).layer(a).unwrap().link_group; + assert_eq!(g, Some(1)); + assert_eq!(doc(&s).layer(b).unwrap().link_group, g); + for id in [c, d] { + assert_eq!(doc(&s).layer(id).unwrap().link_group, Some(u64::MAX), "the existing group is untouched"); + } +} + +#[test] +fn undo_and_redo_report_only_the_edited_area() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + select_all(&mut s, &[a]); + // A pixel edit on one layer is bounded by that layer's extent on both sides. + s.edit("paint", |doc, _| { + doc.layer_mut(a).unwrap().surface_mut().unwrap().fill_rect(Rect::new(12, 12, 14, 14), &[0.0, 0.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.undo(); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 20, 20))); + s.redo(); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 20, 20))); + // A move reports where the layer was and where it landed. + s.execute("layer.translate", json!({"dx": 5, "dy": 0})).unwrap(); + s.undo(); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 25, 20)), "union of where the layer was and is"); + s.redo(); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 25, 20))); +} + +#[test] +fn undo_of_document_wide_steps_still_composites_everything() { + let mut s = session(8); + let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + // A canvas change has no bounded damage. + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 30, "height": 25})).unwrap(); + assert_ne!(doc(&s).size, photocraft_doc::Size::new(100, 80)); + s.undo(); + assert_eq!(damage(&s), None, "a size change recomposites the whole canvas"); + // A layer removed and restored changes only where it draws. + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[b]); + s.execute("layer.delete", json!({})).unwrap(); + s.undo(); + assert_eq!(damage(&s), Some(Rect::new(0, 0, 5, 5))); +} + +#[test] +fn undo_of_compositor_read_document_fields_composites_everything() { + let mut s = session(8); + let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20)); + // Global Light changes every effect's angle across the document. + s.execute("layer.layerStyle.globalLight", json!({"angle": 90.0})).unwrap(); + s.undo(); + assert_eq!(damage(&s), None, "a global-light change recomposites everything"); + // A mode change that keeps the pixel format (RGB → Indexed maps to RGB) neither. + s.execute("image.mode.indexedColor", json!({})).unwrap(); + s.undo(); + assert_eq!(damage(&s), None, "a mode change recomposites everything"); +} + +#[test] +fn undo_of_clipping_or_channel_exclusion_composites_everything() { + let mut s = session(8); + 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(); + s.undo(); + assert_eq!(damage(&s), None, "a clipping change recomposites everything"); + s.execute("layer.setProps", json!({"channels": [true, false, true]})).unwrap(); + s.undo(); + assert_eq!(damage(&s), None, "an excluded-channel change recomposites everything"); +} + +#[test] +fn linked_layers_move_together_and_undo() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let a = rect_layer(&mut s, Rect::new(0, 0, 10, 10)); + let b = rect_layer(&mut s, Rect::new(20, 20, 30, 30)); + let c = rect_layer(&mut s, Rect::new(50, 50, 60, 60)); + assert!(!s.is_enabled("layer.linkLayers")); + select_all(&mut s, &[a, b]); + assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], true); + let g = doc(&s).layer(a).unwrap().link_group; + assert!(g.is_some() && doc(&s).layer(b).unwrap().link_group == g); + // Move only a: b follows, c stays. + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.translate", json!({"dx": 5, "dy": 3})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(5, 3, 15, 13)); + assert_eq!(bounds(&s, b), Rect::new(25, 23, 35, 33)); + assert_eq!(bounds(&s, c), Rect::new(50, 50, 60, 60)); + s.undo(); + assert_eq!(bounds(&s, a), Rect::new(0, 0, 10, 10)); + assert_eq!(bounds(&s, b), Rect::new(20, 20, 30, 30)); + // Select Linked Layers from just a. + s.execute("layer.selectLinkedLayers", json!({})).unwrap(); + assert_eq!(sel(&s), vec![a, b]); + // Multi-selection translate moves all selected (c added, unlinked). + s.execute("layer.select", json!({"layer": c.0, "mode": "toggle"})).unwrap(); + s.execute("layer.translate", json!({"dx": -1, "dy": 0})).unwrap(); + assert_eq!(bounds(&s, c), Rect::new(49, 50, 59, 60)); + assert_eq!(bounds(&s, a), Rect::new(-1, 0, 9, 10)); + // Toggle: linking the same group again unlinks. + select_all(&mut s, &[a, b]); + assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); + assert!(doc(&s).layer(a).unwrap().link_group.is_none()); + } +} + +/// Plain layers carrying stored link groups, as a loaded `.pcraft` or PSD can hold (#961). +fn stored_groups(s: &mut Session, groups: &[Option]) -> Vec { + let ids: Vec = groups.iter().map(|_| rect_layer(s, Rect::new(0, 0, 4, 4))).collect(); + s.edit("load groups", |doc, _| { + for (id, g) in ids.iter().zip(groups) { + doc.layer_mut(*id).unwrap().link_group = *g; + } + Ok(()) + }) + .unwrap(); + ids +} + +fn group(s: &Session, id: LayerId) -> Option { + doc(s).layer(id).unwrap().link_group +} + +/// Links `ids`, then checks they share one group no other layer uses (#961). +fn link_fresh(s: &mut Session, ids: &[LayerId]) -> u64 { + select_all(s, ids); + let past = s.active().unwrap().history.past_len(); + assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], true); + assert_eq!(s.active().unwrap().history.past_len(), past + 1); + let g = group(s, ids[0]).expect("linked"); + assert!(ids.iter().all(|id| group(s, *id) == Some(g))); + let members = doc(s).walk().iter().filter(|(_, _, l)| l.link_group == Some(g)).count(); + assert_eq!(members, ids.len(), "group {g} is shared with unselected layers"); + g +} + +#[test] +fn link_layers_beside_a_maximal_stored_group() { + // The issue's repro: one layer stored at u64::MAX, link it with an unlinked one. + let mut s = session(8); + let ids = stored_groups(&mut s, &[Some(u64::MAX), None]); + assert_ne!(link_fresh(&mut s, &ids), u64::MAX); + // Unlink and relink the pair: with no groups left, numbering starts over at 1. + assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); + assert!(ids.iter().all(|id| group(&s, *id).is_none())); + assert_eq!(link_fresh(&mut s, &ids), 1); + + // Two other layers linked beside an untouched maximal pair. + let mut s = session(8); + let ids = stored_groups(&mut s, &[Some(u64::MAX), Some(u64::MAX), None, None]); + let g = link_fresh(&mut s, &ids[2..]); + assert_ne!(g, u64::MAX); + assert_eq!((group(&s, ids[0]), group(&s, ids[1])), (Some(u64::MAX), Some(u64::MAX))); +} + +#[test] +fn unlink_a_maximal_stored_group() { + let mut s = session(8); + let ids = stored_groups(&mut s, &[Some(u64::MAX), Some(u64::MAX), None]); + select_all(&mut s, &ids[..2]); + assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); + assert!(ids.iter().all(|id| group(&s, *id).is_none())); + s.undo(); + assert_eq!((group(&s, ids[0]), group(&s, ids[1])), (Some(u64::MAX), Some(u64::MAX))); + // Relinking all three gets a working group. + link_fresh(&mut s, &ids); +} + +#[test] +fn link_layers_when_every_group_is_huge() { + // Unselected groups at the top of the range, including the 0 a wrapped id would join. + let top = [u64::MAX, u64::MAX - 1, u64::MAX - 2, 0, 1, 2]; + let stored: Vec> = top.iter().flat_map(|g| [Some(*g), Some(*g)]).chain([None, None, None, None]).collect(); + let mut s = session(8); + let ids = stored_groups(&mut s, &stored); + let n = top.len() * 2; + let g = link_fresh(&mut s, &ids[n..n + 2]); + assert!(!top.contains(&g), "{g} collides with a stored group"); + // A second link gets yet another group, and existing groups never change. + let h = link_fresh(&mut s, &ids[n + 2..]); + assert!(!top.contains(&h) && h != g); + for (i, t) in top.iter().enumerate() { + assert_eq!((group(&s, ids[2 * i]), group(&s, ids[2 * i + 1])), (Some(*t), Some(*t))); + } + // Moving a newly linked layer leaves the group-0 pair alone. + assert_eq!(with_links(doc(&s), &[ids[n]]), vec![ids[n], ids[n + 1]]); +} + +#[test] +fn link_layers_near_the_maximum() { + // max + 1 still fits: the new group is u64::MAX itself. + let mut s = session(8); + let ids = stored_groups(&mut s, &[Some(u64::MAX - 1), Some(u64::MAX - 1), None, None, None, None]); + assert_eq!(link_fresh(&mut s, &ids[2..4]), u64::MAX); + // The next link no longer fits above the maximum and takes a free id instead. + let g = link_fresh(&mut s, &ids[4..]); + assert!(g != u64::MAX && g != u64::MAX - 1); +} + +#[test] +fn link_layers_assigns_working_groups() { + // Control: ordinary documents keep getting max + 1, starting at 1. + let mut s = session(8); + let ids = stored_groups(&mut s, &[None, None, None, None]); + assert_eq!(link_fresh(&mut s, &ids[..2]), 1); + assert_eq!(link_fresh(&mut s, &ids[2..]), 2); + assert_eq!(s.execute("layer.linkLayers", json!({})).unwrap()["linked"], false); + assert_eq!((group(&s, ids[2]), group(&s, ids[3])), (None, None)); + assert_eq!((group(&s, ids[0]), group(&s, ids[1])), (Some(1), Some(1))); +} + +#[test] +fn selection_pruned_after_delete_and_undo() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[a, c]); + // Deleting one layer explicitly prunes it from the set. + s.execute("layer.delete", json!({"layer": a.0})).unwrap(); + assert_eq!(sel(&s), vec![c]); + s.undo(); + assert!(sel(&s).iter().all(|id| doc(&s).layer(*id).is_some())); + // Deleting with several selected removes them all, then selects the layer below. + select_all(&mut s, &[a, c]); + s.execute("layer.delete", json!({})).unwrap(); + assert!(doc(&s).layer(a).is_none() && doc(&s).layer(c).is_none()); + assert_eq!(doc(&s).layer_count(), 2); + assert_eq!(sel(&s).len(), 1); + assert!(s.active().unwrap().selected_layers.iter().all(|id| doc(&s).layer(*id).is_some())); + s.undo(); + assert_eq!(doc(&s).layer_count(), 4); + let _ = b; + // Redo then undo again keeps the set valid. + s.redo(); + assert!(sel(&s).iter().all(|id| doc(&s).layer(*id).is_some())); +} + +#[test] +fn duplicate_hide_lock_and_reverse_selected() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let c = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[a, c]); + let r = s.execute("layer.duplicate", json!({})).unwrap(); + assert_eq!(r["layers"].as_array().unwrap().len(), 2); + assert_eq!(doc(&s).layer_count(), 6); + assert_eq!(sel(&s).len(), 2); + assert!(sel(&s).iter().all(|id| *id != a && *id != c)); + s.undo(); + select_all(&mut s, &[a, b]); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(!doc(&s).layer(a).unwrap().visible && !doc(&s).layer(b).unwrap().visible && doc(&s).layer(c).unwrap().visible); + s.execute("layer.showLayers", json!({})).unwrap(); + assert!(doc(&s).layer(a).unwrap().visible); + s.execute("layer.lockLayers", json!({})).unwrap(); + assert!(doc(&s).layer(a).unwrap().locks.all && doc(&s).layer(b).unwrap().locks.all); + assert!(s.execute("layer.translate", json!({"dx": 1})).is_err(), "locked layers don't move"); + s.execute("layer.lockLayers", json!({})).unwrap(); + assert!(!doc(&s).layer(a).unwrap().locks.all); + s.execute("layer.lockLayers", json!({"position": true})).unwrap(); + assert!(doc(&s).layer(b).unwrap().locks.position && !doc(&s).layer(c).unwrap().locks.position); + // Reverse a, b, c. + select_all(&mut s, &[a, b, c]); + s.execute("layer.arrange.reverse", json!({})).unwrap(); + assert_eq!(doc(&s).layers.iter().skip(1).map(|l| l.id).collect::>(), vec![c, b, a]); + assert_eq!(s.active().unwrap().history.entries().last().map(|e| e.as_str()), Some("Reverse")); +} + +/// #4892: Lock Image Pixels includes Lock Transparent Pixels, so the two are never both on: +/// locking the pixels clears the transparency lock, which stays off while they are locked, +/// through both `layer.setProps` and `layer.lockLayers`. +#[test] +fn locking_pixels_clears_and_holds_off_the_transparency_lock() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + let locks = |s: &Session| doc(s).layer(id).unwrap().locks; + s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap(); + assert!(locks(&s).transparency); + s.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap(); + assert!(locks(&s).pixels && !locks(&s).transparency, "locking the pixels clears the transparency lock"); + s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap(); + assert!(!locks(&s).transparency, "and it stays off while the pixels are locked"); + s.execute("layer.setProps", json!({"locks": {"transparency": true, "pixels": true}})).unwrap(); + assert!(locks(&s).pixels && !locks(&s).transparency, "both at once: the pixel lock wins"); + s.execute("layer.lockLayers", json!({"pixels": false})).unwrap(); + s.execute("layer.lockLayers", json!({"transparency": true})).unwrap(); + assert!(locks(&s).transparency && !locks(&s).pixels, "with the pixels unlocked it can be set again"); + s.execute("layer.lockLayers", json!({"pixels": true})).unwrap(); + assert!(locks(&s).pixels && !locks(&s).transparency); + assert!(s.execute("layer.setProps", json!({"locks": {"nope": true}})).is_err()); +} + +/// `document.inspect` lists the selected layers and marks them in the layer list. +#[test] +fn inspect_reports_selection() { + let mut s = session(8); + let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5)); + select_all(&mut s, &[a, b]); + let v = s.execute("document.inspect", json!({})).unwrap(); + assert_eq!(v["selectedLayers"], json!([a.0, b.0])); + assert_eq!(v["layers"][0]["selected"], true); +} + +/// #7538: `selection: true` moves the selection with the layers in the same step, as the Move +/// tool does with several layers selected; without it the selection stays. +#[test] +fn translate_can_carry_the_selection_in_the_same_step() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100, "background": "transparent"})).unwrap(); + let a = s.active().unwrap().active_layer.unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("select.rect", json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 70, "height": 30})).unwrap(); + let sel = |s: &Session| s.active().unwrap().doc.selection.as_ref().map(|m| m.content_bounds()); + let bounds = |s: &Session, id: LayerId| s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds(); + let steps = s.active().unwrap().history.past_len(); + s.execute("layer.translate", json!({"dx": 7, "dy": 20, "selection": true})).unwrap(); + assert_eq!((bounds(&s, a), bounds(&s, b)), (Rect::new(17, 30, 37, 50), Rect::new(57, 30, 77, 50))); + assert_eq!(sel(&s), Some(Rect::new(12, 25, 82, 55)), "the selection came along"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one step"); + s.undo(); + assert_eq!((sel(&s), bounds(&s, a)), (Some(Rect::new(5, 5, 75, 35)), Rect::new(10, 10, 30, 30)), "undone together"); + s.execute("layer.translate", json!({"dx": 7, "dy": 20})).unwrap(); + assert_eq!(sel(&s), Some(Rect::new(5, 5, 75, 35)), "without it the selection stays"); + let state = |s: &Session| (bounds(s, a), bounds(s, b), sel(s), s.active().unwrap().history.past_len()); + let before = state(&s); + for dx in [1, 0] { + assert!(s.execute("layer.translate", json!({"dx": dx, "selection": "yes"})).is_err(), "dx {dx}: a bad `selection` is an error"); + assert_eq!(state(&s), before, "dx {dx}: and changes nothing"); + } +} From 740db3772a11ef27cb7a1751e068c8ba9483efc0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:14 +0000 Subject: [PATCH 036/259] refactor(engine): move layer_multi_cmds.rs layers_panel_parity_tests to layer_multi_cmds/layers_panel_parity_tests.rs --- crates/engine/src/layer_multi_cmds.rs | 316 +----------------- .../layers_panel_parity_tests.rs | 313 +++++++++++++++++ 2 files changed, 314 insertions(+), 315 deletions(-) create mode 100644 crates/engine/src/layer_multi_cmds/layers_panel_parity_tests.rs diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs index 8942d9dd61..726920571f 100644 --- a/crates/engine/src/layer_multi_cmds.rs +++ b/crates/engine/src/layer_multi_cmds.rs @@ -1808,318 +1808,4 @@ pub fn specs() -> Vec { mod tests; #[cfg(test)] -mod layers_panel_parity_tests { - use super::*; - - /// A 24×16 document with three layers, "Test 0" to "Test 2", above the Background; the last one is active. - fn new_session() -> (Session, Vec) { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 24, "height": 16})).unwrap(); - let ids = (0..3).map(|n| LayerId(s.execute("layer.new.layer", json!({"name": format!("Test {n}")})).unwrap()["layer"].as_u64().unwrap())).collect(); - (s, ids) - } - - /// Set one Layers panel option in the preferences, as the Panel Options dialog does. - fn option(s: &mut Session, key: &str, enabled: bool) { - s.prefs.edit(|p| { - let val = p.dialogs.entry("ui.layersPanelOptions".into()).or_insert_with(|| json!({})); - if let Some(o) = val.as_object_mut() { - o.insert(key.to_owned(), json!(enabled)); - } - }); - } - - /// The drag preview equals the committed `layer.moveTo` result and never touches the document or its history. - #[test] - fn preview_matches_real_move_and_never_edits_document_or_history() { - let (mut s, ids) = new_session(); - let params = json!({"layer": ids[0].0, "target": ids[2].0, "position": "above"}); - let before = s.active().unwrap().doc.clone(); - let undo_before = s.active().unwrap().history.entries().len(); - let candidate = preview_move(&before, ¶ms, true).unwrap(); - assert_eq!(*before, *s.active().unwrap().doc); - assert_eq!(s.active().unwrap().history.entries().len(), undo_before); - s.execute("layer.moveTo", params).unwrap(); - assert_eq!(candidate, *s.active().unwrap().doc, "visual preview must match committed layer order"); - } - - /// A previewed ⌥-drag copy names its layers like the committed copy, with and without the "copy" suffix option. - #[test] - fn preview_copy_and_no_copy_suffix_option_match_committed_layers() { - let (mut s, ids) = new_session(); - option(&mut s, "addCopyToCopiedLayersAndGroups", false); - let params = json!({"layer": ids[0].0, "target": ids[2].0, "position": "below", "copy": true}); - let before = s.active().unwrap().doc.clone(); - let candidate = preview_move(&before, ¶ms, false).unwrap(); - s.execute("layer.moveTo", params).unwrap(); - let actual = &s.active().unwrap().doc; - assert_eq!(candidate.layers.iter().map(|l| l.name.as_str()).collect::>(), actual.layers.iter().map(|l| l.name.as_str()).collect::>()); - assert_eq!(actual.layer_count(), before.layer_count() + 1); - assert_eq!(actual.layers.iter().filter(|l| l.name == "Test 0").count(), 2); - let d = s.execute("layer.duplicate", json!({"layer": ids[1].0})).unwrap(); - let duplicate = LayerId(d["layer"].as_u64().unwrap()); - assert_eq!(s.active().unwrap().doc.layer(duplicate).unwrap().name, "Test 1"); - option(&mut s, "addCopyToCopiedLayersAndGroups", true); - let d = s.execute("layer.duplicate", json!({"layer": ids[1].0})).unwrap(); - assert!(s.active().unwrap().doc.layer(LayerId(d["layer"].as_u64().unwrap())).unwrap().name.contains("copy")); - } - - /// Drops the command refuses (or ignores) give no preview and leave the document alone; a multi-layer preview follows the committed stack order. - #[test] - fn preview_rejects_invalid_drop_unchanged() { - let (mut s, ids) = new_session(); - let before = s.active().unwrap().doc.clone(); - // Dropping a layer on itself is a no-op for the command, the others are errors. - for (p, command_rejects) in [ - (json!({"layer": ids[1].0, "target": ids[1].0, "position": "above"}), false), - (json!({"layer": ids[1].0, "target": 999999, "position": "below"}), true), - (json!({"layer": ids[1].0, "target": ids[2].0, "position": "into"}), true), - (json!({"layer": ids[1].0, "target": ids[2].0, "position": "invalid"}), true), - ] { - assert!(preview_move(&before, &p, true).is_none(), "{p}"); - let result = s.execute("layer.moveTo", p.clone()); - if command_rejects { - assert!(result.is_err(), "{p}"); - } else { - assert_eq!(result.unwrap(), Value::Null, "{p}"); - } - assert_eq!(*before, *s.active().unwrap().doc, "{p}"); - } - // Multi-layer preview and commit follow the same stack order regardless of params order. - let p = json!({"layers": [ids[2].0, ids[0].0], "target": ids[1].0, "position": "below"}); - let candidate = preview_move(&before, &p, true).unwrap(); - s.execute("layer.moveTo", p).unwrap(); - assert_eq!(candidate, *s.active().unwrap().doc); - } - - /// A 16×16 document holding `spec` (bottom to top, `*` = clipped) above its Background. Every - /// layer is a translucent, differently placed rectangle, so the stack order and the clip - /// groups both show in the composite. - fn clip_stack(spec: &str) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); - for (n, name) in spec.split_whitespace().enumerate() { - let id = LayerId(s.execute("layer.new.layer", json!({"name": name.trim_end_matches('*')})).unwrap()["layer"].as_u64().unwrap()); - let n = n as i32; - let colour = [(n % 3) as f32 * 0.5, ((n + 1) % 3) as f32 * 0.5, ((n + 2) % 3) as f32 * 0.5, 0.6]; - s.edit("paint", |doc, _| { - let layer = doc.layer_mut(id).unwrap(); - layer.clipped = name.ends_with('*'); - layer.surface_mut().unwrap().fill_rect(Rect::new(n * 2, 0, n * 2 + 10, 16), &colour); - Ok(()) - }) - .unwrap(); - } - s - } - - /// Every layer of `doc` from the bottom, `*` marking the clipped ones. - fn stack_text(doc: &Document) -> String { - doc.layers.iter().map(|l| format!("{}{}", l.name, if l.clipped { "*" } else { "" })).collect::>().join(" ") - } - - /// The id of the layer called `name`, searching the whole layer tree. - fn id_of(s: &Session, name: &str) -> u64 { - s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == name).unwrap().2.id.0 - } - - /// The preview of `params` and the committed `layer.moveTo` show the same stack (names, clip - /// flags) and the same composite, and both are `want`. - fn assert_preview_is_commit(mut s: Session, params: Value, want: &str) { - let before = s.active().unwrap().doc.clone(); - let preview = preview_move(&before, ¶ms, true).expect("the drop has a preview"); - s.execute("layer.moveTo", params.clone()).unwrap(); - let committed = &s.active().unwrap().doc; - assert_eq!(stack_text(&preview), want, "preview of {params}"); - assert_eq!(stack_text(committed), want, "commit of {params}"); - assert_eq!(photocraft_compose::flatten(&preview).px, photocraft_compose::flatten(committed).px, "composite of {params}"); - } - - /// Previewed moves join and release clipping groups exactly as the committed reorder does, copies included. - #[test] - fn preview_follows_clip_groups_like_the_committed_reorder() { - // The fixtures of `clip_group::reorder_joins_and_leaves_groups`. - for (spec, layers, target, pos, want) in [ - // A layer dropped into a clip group joins it. - ("B C1* C2* U", vec!["U"], "C1", "above", "Background B C1* U* C2*"), - ("B C1* C2* U V", vec!["U", "V"], "C1", "above", "Background B C1* U* V* C2*"), - // A clipped layer dropped off its group is released. - ("B C1* C2* U", vec!["C1"], "U", "above", "Background B C2* U C1"), - // A base moved away releases the layers clipped to it. - ("B C1* C2* U", vec!["B"], "U", "above", "Background C1 C2 U B"), - // A base moved up into its own group joins it, and the layers it left are released. - ("B C1* C2*", vec!["B"], "C1", "above", "Background C1 B* C2"), - ("X B C1* C2* U", vec!["B", "C1"], "U", "above", "Background X C2 U B C1*"), - ] { - let s = clip_stack(spec); - let ids: Vec = layers.iter().map(|n| id_of(&s, n)).collect(); - let t = id_of(&s, target); - assert_preview_is_commit(s, json!({"layers": ids, "target": t, "position": pos}), want); - } - // An option-drag copy joins the clip group it lands in too. - let s = clip_stack("B C1* C2* U"); - let (u, c1) = (id_of(&s, "U"), id_of(&s, "C1")); - assert_preview_is_commit(s, json!({"layer": u, "target": c1, "position": "above", "copy": true}), "Background B C1* U copy* C2* U"); - } - - /// Copying the locked Background in a preview gives the same unlocked copy, joining the clip group it lands in, as the command. - #[test] - fn preview_copies_the_background_like_the_committed_copy() { - let mut s = clip_stack("A B*"); - let (bg, a) = (s.active().unwrap().doc.background().unwrap().id, id_of(&s, "A")); - let before = s.active().unwrap().doc.clone(); - assert_ne!(before.layer(bg).unwrap().locks, Default::default(), "the Background is locked"); - let p = json!({"layer": bg.0, "target": a, "position": "above", "copy": true}); - let preview = preview_move(&before, &p, true).unwrap(); - s.execute("layer.moveTo", p).unwrap(); - let committed = &s.active().unwrap().doc; - // The copy is an ordinary, unlocked layer that joins the clip group it lands in. - assert_eq!(stack_text(committed), "Background A Background copy* B*"); - assert_eq!(stack_text(&preview), stack_text(committed)); - for doc in [&preview, committed] { - assert_eq!(doc.layers.get(2).unwrap().locks, Default::default()); - assert!(doc.layers.first().unwrap().locks != Default::default()); - } - assert_eq!(photocraft_compose::flatten(&preview).px, photocraft_compose::flatten(committed).px); - } - - /// A drop that would move the Background off the bottom has no preview, as the command refuses it. - #[test] - fn preview_refuses_what_would_leave_the_background_off_the_bottom() { - let mut s = clip_stack("A B"); - let (bg, a) = (s.active().unwrap().doc.background().unwrap().id, id_of(&s, "A")); - let before = s.active().unwrap().doc.clone(); - for p in [ - json!({"layer": a, "target": bg.0, "position": "below"}), - json!({"layer": bg.0, "target": bg.0, "position": "below", "copy": true}), - json!({"layer": a, "target": bg.0, "position": "below", "copy": true}), - ] { - assert!(preview_move(&before, &p, true).is_none(), "{p}"); - assert!(s.execute("layer.moveTo", p.clone()).is_err(), "{p}"); - assert_eq!(*before, *s.active().unwrap().doc, "{p}"); - } - } - - /// The UI runs commands through `start`; Expand New Effects applies there as well as to `execute`. - #[test] - fn expand_new_effects_applies_to_ui_start_dispatch_too() { - let (mut s, ids) = new_session(); - option(&mut s, "expandNewEffects", false); - let target = ids[0]; - let started = s.start("layer.layerStyle.dropShadow", json!({"layer": target.0})).unwrap(); - assert!(matches!(started, crate::jobs::Started::Done(_))); - assert!(s.active().unwrap().fx_collapsed.contains(&target)); - } - - /// New Solid Color and Gradient fill layers get the default mask only while Use Default Masks on Fill Layers is on. - #[test] - fn fill_layers_respect_use_default_masks_option() { - let (mut s, _) = new_session(); - option(&mut s, "useDefaultMasksOnFillLayers", false); - let new = s.execute("layer.newFillLayer.solidColor", json!({"color": "#112233"})).unwrap(); - let id = LayerId(new["layer"].as_u64().unwrap()); - assert!(s.active().unwrap().doc.layer(id).unwrap().mask.is_none()); - option(&mut s, "useDefaultMasksOnFillLayers", true); - let new = s.execute("layer.newFillLayer.gradient", json!({})).unwrap(); - let id = LayerId(new["layer"].as_u64().unwrap()); - assert!(s.active().unwrap().doc.layer(id).unwrap().mask.is_some()); - } - - /// With the option off only the default reveal-all mask goes away: an active selection still - /// becomes the layer mask and an explicit path still becomes the vector mask (path first). - #[test] - fn fill_layers_without_default_masks_keep_selection_and_explicit_path_masks() { - const KINDS: [(&str, &str); 3] = [ - ("layer.newFillLayer.solidColor", r##"{"color": "#112233"}"##), - ("layer.newFillLayer.gradient", "{}"), - ("layer.newFillLayer.pattern", r#"{"pattern": "Checkerboard"}"#), - ]; - let path = json!({"subpaths": [{"closed": true, "knots": [[2, 2], [10, 2], [10, 10], [2, 10]]}]}); - let (mut s, _) = new_session(); - option(&mut s, "useDefaultMasksOnFillLayers", false); - // Creates the fill layer; returns its raster mask and whether it has a vector mask. - let create = |s: &mut Session, cmd: &str, params: &str, path: Option<&Value>| { - let mut p: Value = serde_json::from_str(params).unwrap(); - if let Some(path) = path { - p["path"] = path.clone(); - } - let id = LayerId(s.execute(cmd, p).unwrap()["layer"].as_u64().unwrap()); - let l = s.active().unwrap().doc.layer(id).unwrap(); - (l.mask.clone(), l.vector_mask.is_some()) - }; - - for (cmd, params) in KINDS { - let (mask, vector) = create(&mut s, cmd, params, None); - assert!(mask.is_none() && !vector, "{cmd}: no selection, no path: no mask at all"); - } - - s.execute("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 6})).unwrap(); - for (cmd, params) in KINDS { - let (mask, vector) = create(&mut s, cmd, params, None); - let mask = mask.unwrap_or_else(|| panic!("{cmd}: the selection still becomes the layer mask")); - assert!(!vector, "{cmd}"); - assert!(mask.surface.pixel(6, 6)[0] > 0.99, "{cmd}: inside the selection reveals"); - assert!(mask.surface.pixel(20, 12)[0] < 0.01, "{cmd}: outside the selection hides"); - } - - // An explicit path wins over the selection, as with the option on. - for selected in [true, false] { - if !selected { - s.execute("select.deselect", json!({})).unwrap(); - } - for (cmd, params) in KINDS { - let (mask, vector) = create(&mut s, cmd, params, Some(&path)); - assert!(vector, "{cmd}: the explicit path becomes the vector mask (selection: {selected})"); - assert!(mask.is_none(), "{cmd}: no raster mask next to the vector mask (selection: {selected})"); - } - } - } - - /// Whether new effects start expanded is view state: it adds no history step, and editing an existing effect keeps its disclosure. - #[test] - fn expand_new_effects_is_view_state_and_keeps_edit_history_clean() { - let (mut s, ids) = new_session(); - option(&mut s, "expandNewEffects", false); - let target = ids[0]; - let history = s.active().unwrap().history.entries().len(); - s.execute("layer.layerStyle.dropShadow", json!({"layer": target.0, "size": 2})).unwrap(); - assert_eq!(s.active().unwrap().history.entries().len(), history + 1); - assert!(s.active().unwrap().fx_collapsed.contains(&target)); - option(&mut s, "expandNewEffects", true); - let other = ids[1]; - s.execute("layer.layerStyle.stroke", json!({"layer": other.0, "size": 2})).unwrap(); - assert!(!s.active().unwrap().fx_collapsed.contains(&other)); - // Editing the existing effect must not unexpectedly change its disclosure. - s.execute("layer.layerStyle.dropShadow", json!({"layer": target.0, "size": 5})).unwrap(); - assert!(s.active().unwrap().fx_collapsed.contains(&target)); - } - - /// The disclosure follows the layer the command changes, however the command names it: a - /// layer given by name is not the active one. - #[test] - fn expand_new_effects_follows_a_layer_named_by_its_name() { - let (mut s, ids) = new_session(); - option(&mut s, "expandNewEffects", false); - let (named, active) = (ids[0], ids[2]); - assert_eq!(s.active().unwrap().active_layer, Some(active)); - s.execute("layer.layerStyle.dropShadow", json!({"layer": "Test 0", "size": 2})).unwrap(); - assert!(s.active().unwrap().doc.layer(named).is_some_and(|l| !l.effects.items.is_empty())); - assert!(s.active().unwrap().fx_collapsed.contains(&named), "the named layer's new effects start collapsed"); - assert!(!s.active().unwrap().fx_collapsed.contains(&active), "the active layer is not the one changed"); - } - - /// Transfer Effects changes the layer it moves the effects to, so that is the layer whose - /// disclosure follows the option, not the active layer or the one the effects came from. - #[test] - fn expand_new_effects_follows_the_transfer_destination() { - let (mut s, ids) = new_session(); - let (from, to, active) = (ids[0], ids[1], ids[2]); - s.execute("layer.layerStyle.dropShadow", json!({"layer": from.0, "size": 2})).unwrap(); - option(&mut s, "expandNewEffects", false); - assert_eq!(s.active().unwrap().active_layer, Some(active)); - s.execute("layer.layerStyle.transferEffects", json!({"from": from.0, "to": to.0, "copy": true})).unwrap(); - assert!(s.active().unwrap().doc.layer(to).is_some_and(|l| !l.effects.items.is_empty())); - assert!(s.active().unwrap().fx_collapsed.contains(&to), "the destination's new effects start collapsed"); - assert!(!s.active().unwrap().fx_collapsed.contains(&active), "the active layer is not the one changed"); - } -} +mod layers_panel_parity_tests; diff --git a/crates/engine/src/layer_multi_cmds/layers_panel_parity_tests.rs b/crates/engine/src/layer_multi_cmds/layers_panel_parity_tests.rs new file mode 100644 index 0000000000..3982eb9cff --- /dev/null +++ b/crates/engine/src/layer_multi_cmds/layers_panel_parity_tests.rs @@ -0,0 +1,313 @@ +use super::*; + +/// A 24×16 document with three layers, "Test 0" to "Test 2", above the Background; the last one is active. +fn new_session() -> (Session, Vec) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 24, "height": 16})).unwrap(); + let ids = (0..3).map(|n| LayerId(s.execute("layer.new.layer", json!({"name": format!("Test {n}")})).unwrap()["layer"].as_u64().unwrap())).collect(); + (s, ids) +} + +/// Set one Layers panel option in the preferences, as the Panel Options dialog does. +fn option(s: &mut Session, key: &str, enabled: bool) { + s.prefs.edit(|p| { + let val = p.dialogs.entry("ui.layersPanelOptions".into()).or_insert_with(|| json!({})); + if let Some(o) = val.as_object_mut() { + o.insert(key.to_owned(), json!(enabled)); + } + }); +} + +/// The drag preview equals the committed `layer.moveTo` result and never touches the document or its history. +#[test] +fn preview_matches_real_move_and_never_edits_document_or_history() { + let (mut s, ids) = new_session(); + let params = json!({"layer": ids[0].0, "target": ids[2].0, "position": "above"}); + let before = s.active().unwrap().doc.clone(); + let undo_before = s.active().unwrap().history.entries().len(); + let candidate = preview_move(&before, ¶ms, true).unwrap(); + assert_eq!(*before, *s.active().unwrap().doc); + assert_eq!(s.active().unwrap().history.entries().len(), undo_before); + s.execute("layer.moveTo", params).unwrap(); + assert_eq!(candidate, *s.active().unwrap().doc, "visual preview must match committed layer order"); +} + +/// A previewed ⌥-drag copy names its layers like the committed copy, with and without the "copy" suffix option. +#[test] +fn preview_copy_and_no_copy_suffix_option_match_committed_layers() { + let (mut s, ids) = new_session(); + option(&mut s, "addCopyToCopiedLayersAndGroups", false); + let params = json!({"layer": ids[0].0, "target": ids[2].0, "position": "below", "copy": true}); + let before = s.active().unwrap().doc.clone(); + let candidate = preview_move(&before, ¶ms, false).unwrap(); + s.execute("layer.moveTo", params).unwrap(); + let actual = &s.active().unwrap().doc; + assert_eq!(candidate.layers.iter().map(|l| l.name.as_str()).collect::>(), actual.layers.iter().map(|l| l.name.as_str()).collect::>()); + assert_eq!(actual.layer_count(), before.layer_count() + 1); + assert_eq!(actual.layers.iter().filter(|l| l.name == "Test 0").count(), 2); + let d = s.execute("layer.duplicate", json!({"layer": ids[1].0})).unwrap(); + let duplicate = LayerId(d["layer"].as_u64().unwrap()); + assert_eq!(s.active().unwrap().doc.layer(duplicate).unwrap().name, "Test 1"); + option(&mut s, "addCopyToCopiedLayersAndGroups", true); + let d = s.execute("layer.duplicate", json!({"layer": ids[1].0})).unwrap(); + assert!(s.active().unwrap().doc.layer(LayerId(d["layer"].as_u64().unwrap())).unwrap().name.contains("copy")); +} + +/// Drops the command refuses (or ignores) give no preview and leave the document alone; a multi-layer preview follows the committed stack order. +#[test] +fn preview_rejects_invalid_drop_unchanged() { + let (mut s, ids) = new_session(); + let before = s.active().unwrap().doc.clone(); + // Dropping a layer on itself is a no-op for the command, the others are errors. + for (p, command_rejects) in [ + (json!({"layer": ids[1].0, "target": ids[1].0, "position": "above"}), false), + (json!({"layer": ids[1].0, "target": 999999, "position": "below"}), true), + (json!({"layer": ids[1].0, "target": ids[2].0, "position": "into"}), true), + (json!({"layer": ids[1].0, "target": ids[2].0, "position": "invalid"}), true), + ] { + assert!(preview_move(&before, &p, true).is_none(), "{p}"); + let result = s.execute("layer.moveTo", p.clone()); + if command_rejects { + assert!(result.is_err(), "{p}"); + } else { + assert_eq!(result.unwrap(), Value::Null, "{p}"); + } + assert_eq!(*before, *s.active().unwrap().doc, "{p}"); + } + // Multi-layer preview and commit follow the same stack order regardless of params order. + let p = json!({"layers": [ids[2].0, ids[0].0], "target": ids[1].0, "position": "below"}); + let candidate = preview_move(&before, &p, true).unwrap(); + s.execute("layer.moveTo", p).unwrap(); + assert_eq!(candidate, *s.active().unwrap().doc); +} + +/// A 16×16 document holding `spec` (bottom to top, `*` = clipped) above its Background. Every +/// layer is a translucent, differently placed rectangle, so the stack order and the clip +/// groups both show in the composite. +fn clip_stack(spec: &str) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + for (n, name) in spec.split_whitespace().enumerate() { + let id = LayerId(s.execute("layer.new.layer", json!({"name": name.trim_end_matches('*')})).unwrap()["layer"].as_u64().unwrap()); + let n = n as i32; + let colour = [(n % 3) as f32 * 0.5, ((n + 1) % 3) as f32 * 0.5, ((n + 2) % 3) as f32 * 0.5, 0.6]; + s.edit("paint", |doc, _| { + let layer = doc.layer_mut(id).unwrap(); + layer.clipped = name.ends_with('*'); + layer.surface_mut().unwrap().fill_rect(Rect::new(n * 2, 0, n * 2 + 10, 16), &colour); + Ok(()) + }) + .unwrap(); + } + s +} + +/// Every layer of `doc` from the bottom, `*` marking the clipped ones. +fn stack_text(doc: &Document) -> String { + doc.layers.iter().map(|l| format!("{}{}", l.name, if l.clipped { "*" } else { "" })).collect::>().join(" ") +} + +/// The id of the layer called `name`, searching the whole layer tree. +fn id_of(s: &Session, name: &str) -> u64 { + s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == name).unwrap().2.id.0 +} + +/// The preview of `params` and the committed `layer.moveTo` show the same stack (names, clip +/// flags) and the same composite, and both are `want`. +fn assert_preview_is_commit(mut s: Session, params: Value, want: &str) { + let before = s.active().unwrap().doc.clone(); + let preview = preview_move(&before, ¶ms, true).expect("the drop has a preview"); + s.execute("layer.moveTo", params.clone()).unwrap(); + let committed = &s.active().unwrap().doc; + assert_eq!(stack_text(&preview), want, "preview of {params}"); + assert_eq!(stack_text(committed), want, "commit of {params}"); + assert_eq!(photocraft_compose::flatten(&preview).px, photocraft_compose::flatten(committed).px, "composite of {params}"); +} + +/// Previewed moves join and release clipping groups exactly as the committed reorder does, copies included. +#[test] +fn preview_follows_clip_groups_like_the_committed_reorder() { + // The fixtures of `clip_group::reorder_joins_and_leaves_groups`. + for (spec, layers, target, pos, want) in [ + // A layer dropped into a clip group joins it. + ("B C1* C2* U", vec!["U"], "C1", "above", "Background B C1* U* C2*"), + ("B C1* C2* U V", vec!["U", "V"], "C1", "above", "Background B C1* U* V* C2*"), + // A clipped layer dropped off its group is released. + ("B C1* C2* U", vec!["C1"], "U", "above", "Background B C2* U C1"), + // A base moved away releases the layers clipped to it. + ("B C1* C2* U", vec!["B"], "U", "above", "Background C1 C2 U B"), + // A base moved up into its own group joins it, and the layers it left are released. + ("B C1* C2*", vec!["B"], "C1", "above", "Background C1 B* C2"), + ("X B C1* C2* U", vec!["B", "C1"], "U", "above", "Background X C2 U B C1*"), + ] { + let s = clip_stack(spec); + let ids: Vec = layers.iter().map(|n| id_of(&s, n)).collect(); + let t = id_of(&s, target); + assert_preview_is_commit(s, json!({"layers": ids, "target": t, "position": pos}), want); + } + // An option-drag copy joins the clip group it lands in too. + let s = clip_stack("B C1* C2* U"); + let (u, c1) = (id_of(&s, "U"), id_of(&s, "C1")); + assert_preview_is_commit(s, json!({"layer": u, "target": c1, "position": "above", "copy": true}), "Background B C1* U copy* C2* U"); +} + +/// Copying the locked Background in a preview gives the same unlocked copy, joining the clip group it lands in, as the command. +#[test] +fn preview_copies_the_background_like_the_committed_copy() { + let mut s = clip_stack("A B*"); + let (bg, a) = (s.active().unwrap().doc.background().unwrap().id, id_of(&s, "A")); + let before = s.active().unwrap().doc.clone(); + assert_ne!(before.layer(bg).unwrap().locks, Default::default(), "the Background is locked"); + let p = json!({"layer": bg.0, "target": a, "position": "above", "copy": true}); + let preview = preview_move(&before, &p, true).unwrap(); + s.execute("layer.moveTo", p).unwrap(); + let committed = &s.active().unwrap().doc; + // The copy is an ordinary, unlocked layer that joins the clip group it lands in. + assert_eq!(stack_text(committed), "Background A Background copy* B*"); + assert_eq!(stack_text(&preview), stack_text(committed)); + for doc in [&preview, committed] { + assert_eq!(doc.layers.get(2).unwrap().locks, Default::default()); + assert!(doc.layers.first().unwrap().locks != Default::default()); + } + assert_eq!(photocraft_compose::flatten(&preview).px, photocraft_compose::flatten(committed).px); +} + +/// A drop that would move the Background off the bottom has no preview, as the command refuses it. +#[test] +fn preview_refuses_what_would_leave_the_background_off_the_bottom() { + let mut s = clip_stack("A B"); + let (bg, a) = (s.active().unwrap().doc.background().unwrap().id, id_of(&s, "A")); + let before = s.active().unwrap().doc.clone(); + for p in [ + json!({"layer": a, "target": bg.0, "position": "below"}), + json!({"layer": bg.0, "target": bg.0, "position": "below", "copy": true}), + json!({"layer": a, "target": bg.0, "position": "below", "copy": true}), + ] { + assert!(preview_move(&before, &p, true).is_none(), "{p}"); + assert!(s.execute("layer.moveTo", p.clone()).is_err(), "{p}"); + assert_eq!(*before, *s.active().unwrap().doc, "{p}"); + } +} + +/// The UI runs commands through `start`; Expand New Effects applies there as well as to `execute`. +#[test] +fn expand_new_effects_applies_to_ui_start_dispatch_too() { + let (mut s, ids) = new_session(); + option(&mut s, "expandNewEffects", false); + let target = ids[0]; + let started = s.start("layer.layerStyle.dropShadow", json!({"layer": target.0})).unwrap(); + assert!(matches!(started, crate::jobs::Started::Done(_))); + assert!(s.active().unwrap().fx_collapsed.contains(&target)); +} + +/// New Solid Color and Gradient fill layers get the default mask only while Use Default Masks on Fill Layers is on. +#[test] +fn fill_layers_respect_use_default_masks_option() { + let (mut s, _) = new_session(); + option(&mut s, "useDefaultMasksOnFillLayers", false); + let new = s.execute("layer.newFillLayer.solidColor", json!({"color": "#112233"})).unwrap(); + let id = LayerId(new["layer"].as_u64().unwrap()); + assert!(s.active().unwrap().doc.layer(id).unwrap().mask.is_none()); + option(&mut s, "useDefaultMasksOnFillLayers", true); + let new = s.execute("layer.newFillLayer.gradient", json!({})).unwrap(); + let id = LayerId(new["layer"].as_u64().unwrap()); + assert!(s.active().unwrap().doc.layer(id).unwrap().mask.is_some()); +} + +/// With the option off only the default reveal-all mask goes away: an active selection still +/// becomes the layer mask and an explicit path still becomes the vector mask (path first). +#[test] +fn fill_layers_without_default_masks_keep_selection_and_explicit_path_masks() { + const KINDS: [(&str, &str); 3] = [ + ("layer.newFillLayer.solidColor", r##"{"color": "#112233"}"##), + ("layer.newFillLayer.gradient", "{}"), + ("layer.newFillLayer.pattern", r#"{"pattern": "Checkerboard"}"#), + ]; + let path = json!({"subpaths": [{"closed": true, "knots": [[2, 2], [10, 2], [10, 10], [2, 10]]}]}); + let (mut s, _) = new_session(); + option(&mut s, "useDefaultMasksOnFillLayers", false); + // Creates the fill layer; returns its raster mask and whether it has a vector mask. + let create = |s: &mut Session, cmd: &str, params: &str, path: Option<&Value>| { + let mut p: Value = serde_json::from_str(params).unwrap(); + if let Some(path) = path { + p["path"] = path.clone(); + } + let id = LayerId(s.execute(cmd, p).unwrap()["layer"].as_u64().unwrap()); + let l = s.active().unwrap().doc.layer(id).unwrap(); + (l.mask.clone(), l.vector_mask.is_some()) + }; + + for (cmd, params) in KINDS { + let (mask, vector) = create(&mut s, cmd, params, None); + assert!(mask.is_none() && !vector, "{cmd}: no selection, no path: no mask at all"); + } + + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 6})).unwrap(); + for (cmd, params) in KINDS { + let (mask, vector) = create(&mut s, cmd, params, None); + let mask = mask.unwrap_or_else(|| panic!("{cmd}: the selection still becomes the layer mask")); + assert!(!vector, "{cmd}"); + assert!(mask.surface.pixel(6, 6)[0] > 0.99, "{cmd}: inside the selection reveals"); + assert!(mask.surface.pixel(20, 12)[0] < 0.01, "{cmd}: outside the selection hides"); + } + + // An explicit path wins over the selection, as with the option on. + for selected in [true, false] { + if !selected { + s.execute("select.deselect", json!({})).unwrap(); + } + for (cmd, params) in KINDS { + let (mask, vector) = create(&mut s, cmd, params, Some(&path)); + assert!(vector, "{cmd}: the explicit path becomes the vector mask (selection: {selected})"); + assert!(mask.is_none(), "{cmd}: no raster mask next to the vector mask (selection: {selected})"); + } + } +} + +/// Whether new effects start expanded is view state: it adds no history step, and editing an existing effect keeps its disclosure. +#[test] +fn expand_new_effects_is_view_state_and_keeps_edit_history_clean() { + let (mut s, ids) = new_session(); + option(&mut s, "expandNewEffects", false); + let target = ids[0]; + let history = s.active().unwrap().history.entries().len(); + s.execute("layer.layerStyle.dropShadow", json!({"layer": target.0, "size": 2})).unwrap(); + assert_eq!(s.active().unwrap().history.entries().len(), history + 1); + assert!(s.active().unwrap().fx_collapsed.contains(&target)); + option(&mut s, "expandNewEffects", true); + let other = ids[1]; + s.execute("layer.layerStyle.stroke", json!({"layer": other.0, "size": 2})).unwrap(); + assert!(!s.active().unwrap().fx_collapsed.contains(&other)); + // Editing the existing effect must not unexpectedly change its disclosure. + s.execute("layer.layerStyle.dropShadow", json!({"layer": target.0, "size": 5})).unwrap(); + assert!(s.active().unwrap().fx_collapsed.contains(&target)); +} + +/// The disclosure follows the layer the command changes, however the command names it: a +/// layer given by name is not the active one. +#[test] +fn expand_new_effects_follows_a_layer_named_by_its_name() { + let (mut s, ids) = new_session(); + option(&mut s, "expandNewEffects", false); + let (named, active) = (ids[0], ids[2]); + assert_eq!(s.active().unwrap().active_layer, Some(active)); + s.execute("layer.layerStyle.dropShadow", json!({"layer": "Test 0", "size": 2})).unwrap(); + assert!(s.active().unwrap().doc.layer(named).is_some_and(|l| !l.effects.items.is_empty())); + assert!(s.active().unwrap().fx_collapsed.contains(&named), "the named layer's new effects start collapsed"); + assert!(!s.active().unwrap().fx_collapsed.contains(&active), "the active layer is not the one changed"); +} + +/// Transfer Effects changes the layer it moves the effects to, so that is the layer whose +/// disclosure follows the option, not the active layer or the one the effects came from. +#[test] +fn expand_new_effects_follows_the_transfer_destination() { + let (mut s, ids) = new_session(); + let (from, to, active) = (ids[0], ids[1], ids[2]); + s.execute("layer.layerStyle.dropShadow", json!({"layer": from.0, "size": 2})).unwrap(); + option(&mut s, "expandNewEffects", false); + assert_eq!(s.active().unwrap().active_layer, Some(active)); + s.execute("layer.layerStyle.transferEffects", json!({"from": from.0, "to": to.0, "copy": true})).unwrap(); + assert!(s.active().unwrap().doc.layer(to).is_some_and(|l| !l.effects.items.is_empty())); + assert!(s.active().unwrap().fx_collapsed.contains(&to), "the destination's new effects start collapsed"); + assert!(!s.active().unwrap().fx_collapsed.contains(&active), "the active layer is not the one changed"); +} From 19dd5d25f8437e1a561e23bd9bb1dccf4cafd9f7 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:15 +0000 Subject: [PATCH 037/259] refactor(engine): move align_cmds.rs tests to align_cmds/tests.rs --- crates/engine/src/align_cmds.rs | 588 +------------------------- crates/engine/src/align_cmds/tests.rs | 585 +++++++++++++++++++++++++ 2 files changed, 586 insertions(+), 587 deletions(-) create mode 100644 crates/engine/src/align_cmds/tests.rs diff --git a/crates/engine/src/align_cmds.rs b/crates/engine/src/align_cmds.rs index 99e3c8a590..869d29b724 100644 --- a/crates/engine/src/align_cmds.rs +++ b/crates/engine/src/align_cmds.rs @@ -358,590 +358,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - /// Deterministic texture written into a layer at offset (dx, dy). - fn texture_layer(s: &mut Session, name: &str, dx: i32, dy: i32) -> LayerId { - s.execute("layer.new.layer", json!({"name": name})).unwrap(); - let id = s.active().unwrap().active_layer.unwrap(); - paint_texture(s, id, dx, dy); - id - } - - /// Writes the deterministic texture into layer `id` at offset (dx, dy). - fn paint_texture(s: &mut Session, id: LayerId, dx: i32, dy: i32) { - s.edit("tex", |doc, _| { - let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); - let mut seed = 99u64; - let mut rnd = || { - seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - (seed >> 33) as f64 / (1u64 << 31) as f64 - }; - surf.fill_rect(Rect::new(dx, dy, dx + 240, dy + 180), &[0.4, 0.4, 0.4, 1.0]); - for _ in 0..120 { - let (x, y) = ((rnd() * 220.0) as i32, (rnd() * 160.0) as i32); - let (sw, sh) = (4 + (rnd() * 14.0) as i32, 4 + (rnd() * 10.0) as i32); - let v = rnd() as f32; - surf.fill_rect(Rect::new(dx + x, dy + y, dx + x + sw, dy + y + sh), &[v, 1.0 - v, v * 0.5, 1.0]); - } - Ok(()) - }) - .unwrap(); - } - - fn select(s: &mut Session, ids: &[LayerId]) { - s.execute("layer.select", json!({"layer": ids[0].0})).unwrap(); - for id in &ids[1..] { - s.execute("layer.select", json!({"layer": id.0, "mode": "add"})).unwrap(); - } - } - - #[test] - fn auto_align_repositions_at_all_depths() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 300, "height": 240, "depth": depth, "background": "transparent"})).unwrap(); - let a = texture_layer(&mut s, "A", 20, 20); - let b = texture_layer(&mut s, "B", 31, 13); - assert!(!s.is_enabled("edit.autoAlignLayers"), "one layer selected"); - select(&mut s, &[a, b]); - assert!(s.is_enabled("edit.autoAlignLayers")); - let r = s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).unwrap(); - assert_eq!(r["reference"], a.0); - let bb = s.active().unwrap().doc.layer(b).unwrap().surface().unwrap().content_bounds(); - assert!((bb.x0 - 20).abs() <= 1 && (bb.y0 - 20).abs() <= 1, "depth {depth}: {bb:?} {r}"); - s.undo(); - let bb = s.active().unwrap().doc.layer(b).unwrap().surface().unwrap().content_bounds(); - assert_eq!((bb.x0, bb.y0), (31, 13)); - } - } - - #[test] - fn auto_align_auto_projection_and_errors() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); - let a = texture_layer(&mut s, "A", 20, 20); - let b = texture_layer(&mut s, "B", 26, 25); - select(&mut s, &[a, b]); - let r = s.execute("edit.autoAlignLayers", json!({})).unwrap(); - let m = r["aligned"][0]["matrix"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::>(); - assert!((m[2] + 6.0).abs() < 1.0 && (m[5] + 5.0).abs() < 1.0, "{r}"); - assert!(s.execute("edit.autoAlignLayers", json!({"projection": "sideways"})).is_err()); - assert!(s.execute("edit.autoAlignLayers", json!({"reference": u64::MAX})).is_err()); - } - - /// As in Photoshop, a locked layer stays where it is: it becomes the reference and the - /// others move onto it (#7080). - #[test] - fn auto_align_keeps_a_locked_layer_as_the_reference() { - for lock in ["all", "position", "pixels"] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); - let a = texture_layer(&mut s, "A", 20, 20); - let b = texture_layer(&mut s, "B", 31, 13); - s.edit("lock", |doc, _| { - doc.layer_mut(b).unwrap().locks.set(lock, true); - Ok(()) - }) - .unwrap(); - select(&mut s, &[a, b]); - let r = s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).unwrap(); - assert_eq!(r["reference"], b.0, "{lock}: {r}"); - let doc = &s.active().unwrap().doc; - let bb = doc.layer(b).unwrap().surface().unwrap().content_bounds(); - assert_eq!((bb.x0, bb.y0), (31, 13), "{lock}: the locked layer stays put"); - let ab = doc.layer(a).unwrap().surface().unwrap().content_bounds(); - assert!((ab.x0 - 31).abs() <= 1 && (ab.y0 - 13).abs() <= 1, "{lock}: {ab:?} {r}"); - // An explicit reference that would move the locked layer is refused. - s.undo(); - assert!(s.execute("edit.autoAlignLayers", json!({"projection": "reposition", "reference": a.0})).is_err()); - // Two locked layers: nothing may move. - s.edit("lock", |doc, _| { - doc.layer_mut(a).unwrap().locks.set(lock, true); - Ok(()) - }) - .unwrap(); - assert!(s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).is_err()); - let bb = s.active().unwrap().doc.layer(a).unwrap().surface().unwrap().content_bounds(); - assert_eq!((bb.x0, bb.y0), (20, 20)); - } - } - - /// The Background doesn't block Auto-Align: when a projection reprojects every layer - /// (Cylindrical, Spherical, or Auto choosing one), or another layer is the reference, it - /// becomes a normal layer ("Layer 0") and moves, as in Photoshop and as Free Transform does. - #[test] - fn auto_align_moves_the_background_as_a_normal_layer() { - let setup = || { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 300, "height": 240, "background": "white"})).unwrap(); - let bg = s.active().unwrap().doc.background().unwrap().id; - paint_texture(&mut s, bg, 20, 20); - let b = texture_layer(&mut s, "B", 31, 13); - select(&mut s, &[bg, b]); - (s, bg, b) - }; - for projection in ["cylindrical", "spherical", "auto"] { - let (mut s, bg, b) = setup(); - let r = s.execute("edit.autoAlignLayers", json!({"projection": projection})).unwrap_or_else(|e| panic!("{projection}: {e}")); - let doc = &s.active().unwrap().doc; - let moved = r["aligned"].as_array().unwrap().iter().any(|a| a["layer"] == bg.0); - assert_eq!(moved, projection != "auto" || r["layout"] != "perspective", "{projection}: {r}"); - assert_eq!(doc.is_background(bg), !moved, "{projection}: a moved Background is a normal layer: {r}"); - if moved { - assert_eq!(doc.layer(bg).unwrap().name, "Layer 0", "{projection}"); - } - assert!(doc.layer(b).is_some(), "{projection}"); - s.undo(); - assert!(s.active().unwrap().doc.is_background(bg), "{projection}: undo restores the Background"); - } - // Planar, with the other layer as the reference: the Background moves onto it. - let (mut s, bg, b) = setup(); - s.execute("edit.autoAlignLayers", json!({"projection": "reposition", "reference": b.0})).unwrap(); - let doc = &s.active().unwrap().doc; - assert!(!doc.is_background(bg)); - // Default reference: the Background (bottom) stays put and stays the Background. - let (mut s, bg, b) = setup(); - let r = s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).unwrap(); - assert_eq!(r["reference"], bg.0, "{r}"); - let doc = &s.active().unwrap().doc; - assert!(doc.is_background(bg)); - let bb = doc.layer(b).unwrap().surface().unwrap().content_bounds(); - assert!((bb.x0 - 20).abs() <= 1 && (bb.y0 - 20).abs() <= 1, "{bb:?} {r}"); - } - - /// The moving layer's mask is warped as a mask: one grey channel whose outside keeps its - /// default (reveal-all stays revealed, hide-all stays hidden), for planar and mesh warps. - #[test] - fn auto_align_warps_layer_masks_keeping_their_default() { - for (projection, reveal) in [("reposition", true), ("reposition", false), ("cylindrical", true)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); - let a = texture_layer(&mut s, "A", 20, 20); - let b = texture_layer(&mut s, "B", 31, 13); - let (inside, outside) = if reveal { (0.0, 1.0) } else { (1.0, 0.0) }; - s.edit("mask", |doc, _| { - let mut m = if reveal { LayerMask::reveal_all() } else { LayerMask::hide_all() }; - m.surface.fill_rect(Rect::new(100, 100, 110, 110), &[inside]); - doc.layer_mut(b).unwrap().mask = Some(m); - Ok(()) - }) - .unwrap(); - select(&mut s, &[a, b]); - let r = s.execute("edit.autoAlignLayers", json!({"projection": projection})).unwrap(); - let doc = &s.active().unwrap().doc; - let m = doc.layer(b).unwrap().mask.as_ref().unwrap(); - assert_eq!(m.surface.format().channels(), 1, "{projection}: {r}"); - assert_eq!(m.value(250, 200), outside, "{projection} reveal={reveal}: {r}"); - assert_eq!(m.value(5, 5), outside, "{projection} reveal={reveal}: {r}"); - if projection == "reposition" { - // The square moved with the layer (by about (-11, +7)). - assert!((m.value(94, 112) - inside).abs() < 0.01, "{r}"); - } - } - } - - #[test] - fn auto_blend_panorama_masks_and_seamless_layer() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 60, "depth": depth, "background": "transparent"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "left"})).unwrap(); - s.edit("l", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 130, 60), &[0.2, 0.3, 0.8, 1.0]); - Ok(()) - }) - .unwrap(); - let left = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); - s.edit("r", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(70, 0, 200, 60), &[0.9, 0.6, 0.2, 1.0]); - Ok(()) - }) - .unwrap(); - let right = s.active().unwrap().active_layer.unwrap(); - select(&mut s, &[left, right]); - let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); - let doc = &s.active().unwrap().doc; - let ml = doc.layer(left).unwrap().mask.as_ref().unwrap(); - let mr = doc.layer(right).unwrap().mask.as_ref().unwrap(); - assert_eq!((ml.value(10, 30), mr.value(10, 30)), (1.0, 0.0), "depth {depth}"); - assert_eq!((ml.value(190, 30), mr.value(190, 30)), (0.0, 1.0)); - let blended = LayerId(r["blended"].as_u64().unwrap()); - let px = doc.layer(blended).unwrap().surface().unwrap().pixel(5, 30); - assert!((px[2] - 0.8).abs() < 0.02, "{px:?}"); - s.undo(); - assert!(s.active().unwrap().doc.layer(left).unwrap().mask.is_none()); - } - } - - /// #5745: the Background can't take a mask, so Auto-Blend turns it into a normal layer first. - #[test] - fn auto_blend_turns_the_background_into_a_layer() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 60, "background": "white"})).unwrap(); - let bg = s.active().unwrap().doc.background().unwrap().id; - s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); - s.edit("r", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(70, 0, 200, 60), &[0.9, 0.6, 0.2, 1.0]); - Ok(()) - }) - .unwrap(); - let right = s.active().unwrap().active_layer.unwrap(); - select(&mut s, &[bg, right]); - s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); - let doc = &s.active().unwrap().doc; - assert!(!doc.is_background(bg), "the Background became a layer to take its mask"); - assert!(doc.layer(bg).unwrap().mask.is_some()); - s.undo(); - assert!(s.active().unwrap().doc.is_background(bg), "undo restores the Background"); - } - - /// Seamless Tones and Colors evens out a 10% exposure step between two panorama layers. - #[test] - fn auto_blend_panorama_seamless_matches_exposure() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap(); - let mut ids = Vec::new(); - for (name, x0, x1, gain) in [("left", 0, 130, 1.0f32), ("right", 70, 200, 1.1)] { - s.execute("layer.new.layer", json!({ "name": name })).unwrap(); - s.edit(name, |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(x0, 0, x1, 60), &[0.2 * gain, 0.4 * gain, 0.5 * gain, 1.0]); - Ok(()) - }) - .unwrap(); - ids.push(s.active().unwrap().active_layer.unwrap()); - } - select(&mut s, &ids); - let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); - let doc = &s.active().unwrap().doc; - let blended = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap(); - let (a, b) = (blended.pixel(10, 30), blended.pixel(190, 30)); - // 0.5 vs 0.55 without gain compensation. - assert!((a[2] - b[2]).abs() < 0.015, "{a:?} {b:?}"); - } - - /// #5745: the top layer hangs off the canvas's right edge, so cropped to the canvas it lies - /// wholly over the bottom one. It used to get an all-black mask; now it shows on its side. - #[test] - fn auto_blend_panorama_of_a_layer_the_canvas_crops_to_all_overlap() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "left"})).unwrap(); - s.edit("l", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 200, 60), &[0.2, 0.4, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - let left = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); - s.edit("r", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(120, 0, 320, 60), &[0.2, 0.4, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - let right = s.active().unwrap().active_layer.unwrap(); - select(&mut s, &[left, right]); - s.execute("edit.autoBlendLayers", json!({"method": "panorama", "seamlessTones": false})).unwrap(); - let doc = &s.active().unwrap().doc; - let ml = doc.layer(left).unwrap().mask.as_ref().unwrap(); - let mr = doc.layer(right).unwrap().mask.as_ref().unwrap(); - assert_eq!((ml.value(10, 30), mr.value(10, 30)), (1.0, 0.0)); - assert_eq!((ml.value(195, 30), mr.value(195, 30)), (0.0, 1.0)); - for x in 0..200 { - assert_eq!(ml.value(x, 30) + mr.value(x, 30), 1.0, "x {x} shows one layer"); - } - } - - /// #5745: a layer Auto-Align left partly off the canvas is masked and blended over all of - /// its bounds, not cut off at the canvas edge. - #[test] - fn auto_blend_panorama_masks_past_the_canvas() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "left"})).unwrap(); - s.edit("l", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 150, 60), &[0.2, 0.4, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - let left = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); - s.edit("r", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(120, 0, 320, 60), &[0.2, 0.4, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - let right = s.active().unwrap().active_layer.unwrap(); - select(&mut s, &[left, right]); - let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); - let doc = &s.active().unwrap().doc; - let ml = doc.layer(left).unwrap().mask.as_ref().unwrap(); - let mr = doc.layer(right).unwrap().mask.as_ref().unwrap(); - assert_eq!((ml.value(10, 30), mr.value(10, 30)), (1.0, 0.0)); - assert_eq!((ml.value(300, 30), mr.value(300, 30)), (0.0, 1.0), "off the canvas"); - let blended = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap(); - assert_eq!(blended.pixel(300, 30)[3], 1.0, "the merged layer covers the off-canvas part"); - } - - /// A sparse layer whose bounds are huge (a dot at each far corner) raises its own content - /// estimate, so the extent past the canvas is capped independently: it keeps to the canvas. - #[test] - fn auto_blend_sparse_huge_bounds_keep_to_the_canvas() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "a"})).unwrap(); - s.edit("a", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - surf.fill_rect(Rect::new(0, 0, 150, 200), &[0.2, 0.4, 0.5, 1.0]); - surf.fill_rect(Rect::new(100_000, 100_000, 100_001, 100_001), &[0.2, 0.4, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - let a = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "b"})).unwrap(); - s.edit("b", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(50, 0, 200, 200), &[0.2, 0.4, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - let b = s.active().unwrap().active_layer.unwrap(); - select(&mut s, &[a, b]); - let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); - let doc = &s.active().unwrap().doc; - let bb = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap().content_bounds(); - assert!(bb.x1 <= 200 && bb.y1 <= 200, "{bb:?}"); - } - - /// The budget past the canvas counts every layer's buffers, not just the work-area pixels. - #[test] - fn auto_blend_budget_counts_layers_and_channels() { - // Two RGBA layers: 4 bytes × (2 layers × (4 channels + luma, alpha, weight) + merged + depth). - assert_eq!(blend_bytes_per_pixel(2, 4), 88); - assert!(blend_bytes_per_pixel(5, 4) > blend_bytes_per_pixel(2, 4)); - // A 2^27-pixel area would need about 11 GiB for just two RGBA layers: it keeps to the canvas. - assert!((1u64 << 27).saturating_mul(blend_bytes_per_pixel(2, 4)) > MAX_BLEND_BYTES); - assert_eq!(blend_bytes_per_pixel(u64::MAX, 4), u64::MAX, "saturates instead of overflowing"); - } - - #[test] - fn auto_blend_stack_without_seamless() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "sharp"})).unwrap(); - s.edit("checker", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in (0..64).step_by(2) { - for x in (0..64).step_by(2) { - let v = if (x / 2 + y / 2) % 2 == 0 { 0.1 } else { 0.9 }; - surf.fill_rect(Rect::new(x, y, x + 2, y + 2), &[v, v, v, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - let a = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "flat"})).unwrap(); - s.edit("flat", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 64, 64), &[0.5, 0.5, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - let flat = s.active().unwrap().active_layer.unwrap(); - select(&mut s, &[a, flat]); - let r = s.execute("edit.autoBlendLayers", json!({"method": "stack", "seamlessTones": false})).unwrap(); - assert!(r["blended"].is_null()); - let doc = &s.active().unwrap().doc; - // The detailed layer is sharper everywhere. - let shown = (0..64).filter(|x| doc.layer(a).unwrap().mask.as_ref().unwrap().value(*x, 32) > 0.5).count(); - assert_eq!(shown, 64); - assert_eq!(doc.layer(flat).unwrap().mask.as_ref().unwrap().value(10, 10), 0.0); - assert!(s.execute("edit.autoBlendLayers", json!({"method": "sideways"})).is_err()); - } - - /// A smooth layer (soft blobs on a gradient) and the same picture a few pixels away: the - /// intensity registration finds the shift to a fraction of a pixel at every motion model. - fn smooth_layer(s: &mut Session, name: &str, dx: i32, dy: i32) -> LayerId { - s.execute("layer.new.layer", json!({"name": name})).unwrap(); - s.edit("smooth", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in 0..150 { - for x in 0..200 { - let (u, v) = ((x - dx) as f32, (y - dy) as f32); - let blob = (-((u - 90.0).powi(2) + (v - 70.0).powi(2)) / (2.0 * 25.0f32.powi(2))).exp(); - let blob2 = (-((u - 150.0).powi(2) + (v - 40.0).powi(2)) / (2.0 * 15.0f32.powi(2))).exp(); - let g = 0.2 + 0.5 * blob + 0.25 * blob2 + 0.001 * u; - surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[g, g * 0.8, g * 0.6, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - s.active().unwrap().active_layer.unwrap() - } - - #[test] - fn auto_align_registers_a_smooth_bracket_by_intensity() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 150, "depth": depth, "background": "transparent"})).unwrap(); - let a = smooth_layer(&mut s, "A", 0, 0); - let b = smooth_layer(&mut s, "B", 4, 3); - select(&mut s, &[a, b]); - assert!(s.execute("edit.autoAlignLayers", json!({"registration": "sideways"})).is_err()); - assert!(s.execute("edit.autoAlignLayers", json!({"projection": "cylindrical", "registration": "intensity"})).is_err()); - for (params, model) in [ - (json!({"projection": "reposition", "registration": "intensity"}), "reposition"), - (json!({"registration": "intensity"}), "collage"), - (json!({"projection": "perspective", "registration": "intensity"}), "perspective"), - ] { - let r = s.execute("edit.autoAlignLayers", params).unwrap(); - assert_eq!(r["registration"], "intensity", "depth {depth}: {r}"); - assert_eq!(r["aligned"][0]["model"], model); - let m = r["aligned"][0]["matrix"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::>(); - assert!((m[2] + 4.0).abs() < 0.25 && (m[5] + 3.0).abs() < 0.25, "depth {depth} {model}: {r}"); - // B now shows A's picture. - let doc = &s.active().unwrap().doc; - let (pa, pb) = (doc.layer(a).unwrap().surface().unwrap().pixel(90, 70), doc.layer(b).unwrap().surface().unwrap().pixel(90, 70)); - assert!((pa[0] - pb[0]).abs() < 0.02, "depth {depth} {model}: {pa:?} vs {pb:?}"); - s.undo(); - } - } - } - - /// Layers with nothing in common are no fit: the intensity registration says so instead of - /// moving them by whatever pose its search box ends at. - #[test] - fn auto_align_rejects_unrelated_layers_instead_of_guessing_a_pose() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 150, "depth": 8, "background": "transparent"})).unwrap(); - let a = smooth_layer(&mut s, "A", 0, 0); - s.execute("layer.new.layer", json!({"name": "stripes"})).unwrap(); - s.edit("stripes", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in 0..150 { - for x in 0..200 { - let g = if (x / 7 + y / 11) % 2 == 0 { 0.9 } else { 0.1 }; - surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[g, g, g, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - let b = s.active().unwrap().active_layer.unwrap(); - select(&mut s, &[a, b]); - for registration in ["intensity", "auto"] { - let err = s.execute("edit.autoAlignLayers", json!({"registration": registration})).unwrap_err().to_string(); - assert_eq!(err, NO_DETAIL, "{registration}"); - } - // A layer that is mostly empty overlaps too little to be placed. - let c = smooth_layer(&mut s, "C", 2, 1); - s.edit("hole", |doc, _| { - let surf = doc.layer_mut(c).unwrap().surface_mut().unwrap(); - surf.fill_rect(Rect::new(0, 0, 200, 120), &[0.0, 0.0, 0.0, 0.0]); - Ok(()) - }) - .unwrap(); - select(&mut s, &[a, c]); - assert_eq!(s.execute("edit.autoAlignLayers", json!({"registration": "intensity"})).unwrap_err().to_string(), NO_DETAIL); - } - - /// Two layers, each sharp on one half: the merged layer takes each half from the sharp layer. - #[test] - fn auto_blend_stack_fuses_the_sharp_halves() { - let checker = |x: i32, y: i32| if (x / 3 + y / 3) % 2 == 0 { 0.2 } else { 0.8 }; - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 96, "height": 64, "depth": depth, "background": "transparent"})).unwrap(); - let mut ids = Vec::new(); - for (name, sharp_left) in [("left", true), ("right", false)] { - s.execute("layer.new.layer", json!({"name": name})).unwrap(); - s.edit(name, |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in 0..64 { - for x in 0..96 { - // The sharp half is the checker, the other half its local mean (flat gray). - let v = if (x < 48) == sharp_left { checker(x, y) } else { 0.5 }; - surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, v, v, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - ids.push(s.active().unwrap().active_layer.unwrap()); - } - select(&mut s, &ids); - for halo in [0.0, 2.0] { - let r = s.execute("edit.autoBlendLayers", json!({"method": "stack", "haloControl": halo})).unwrap(); - let doc = &s.active().unwrap().doc; - let blended = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap(); - for (x, y) in [(10, 20), (20, 40), (76, 20), (85, 40)] { - let px = blended.pixel(x, y); - assert!((px[0] - checker(x, y)).abs() < 0.08, "depth {depth} halo {halo} ({x},{y}): {px:?}"); - assert!((px[3] - 1.0).abs() < 1e-3, "{px:?}"); - } - // The masks still pick per pixel. - assert_eq!(doc.layer(ids[0]).unwrap().mask.as_ref().unwrap().value(10, 20), 1.0); - assert_eq!(doc.layer(ids[1]).unwrap().mask.as_ref().unwrap().value(85, 40), 1.0); - s.undo(); - assert!(s.active().unwrap().doc.layer(ids[0]).unwrap().mask.is_none()); - } - for bad in [json!(-1), json!(9), json!("hard")] { - assert!(s.execute("edit.autoBlendLayers", json!({"method": "stack", "haloControl": bad})).is_err(), "{bad}"); - } - } - } - - /// Three layers, each sharp in one third: the Depth layer says which, black to white from - /// the bottom layer to the top, hidden, and undone with the rest. - #[test] - fn auto_blend_stack_depth_map() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 96, "height": 48, "depth": depth, "background": "transparent"})).unwrap(); - let mut ids = Vec::new(); - for k in 0..3 { - s.execute("layer.new.layer", json!({"name": format!("L{k}")})).unwrap(); - s.edit("third", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in 0..48 { - for x in 0..96 { - let v = if x / 32 == k && ((x / 2) + (y / 2)) % 2 == 0 { - 0.2 - } else if x / 32 == k { - 0.8 - } else { - 0.5 - }; - surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, v, v, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - ids.push(s.active().unwrap().active_layer.unwrap()); - } - select(&mut s, &ids); - assert!(s.execute("edit.autoBlendLayers", json!({"method": "panorama", "depthMap": true})).is_err()); - for seamless in [false, true] { - let r = s.execute("edit.autoBlendLayers", json!({"method": "stack", "seamlessTones": seamless, "depthMap": true})).unwrap(); - let doc = &s.active().unwrap().doc; - let d = doc.layer(LayerId(r["depth"].as_u64().unwrap())).unwrap(); - assert!(!d.visible && d.name.starts_with("Depth"), "depth {depth}: {} visible {} {r}", d.name, d.visible); - let surf = d.surface().unwrap(); - for (x, want) in [(8, 0.0), (48, 0.5), (88, 1.0)] { - let px = surf.pixel(x, 24); - assert!((px[0] - want).abs() < 0.2 && (px[3] - 1.0).abs() < 1e-3, "depth {depth} seamless {seamless} x {x}: {px:?}"); - } - assert_eq!(r["blended"].is_null(), !seamless); - if seamless { - // The merged layer sits above the depth layer and is the active one. - assert_eq!(s.active().unwrap().active_layer, Some(LayerId(r["blended"].as_u64().unwrap()))); - } - s.undo(); - assert!(s.active().unwrap().doc.layer(LayerId(r["depth"].as_u64().unwrap())).is_none()); - } - } - } -} +mod tests; diff --git a/crates/engine/src/align_cmds/tests.rs b/crates/engine/src/align_cmds/tests.rs new file mode 100644 index 0000000000..e456a70814 --- /dev/null +++ b/crates/engine/src/align_cmds/tests.rs @@ -0,0 +1,585 @@ +use super::*; + +/// Deterministic texture written into a layer at offset (dx, dy). +fn texture_layer(s: &mut Session, name: &str, dx: i32, dy: i32) -> LayerId { + s.execute("layer.new.layer", json!({"name": name})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + paint_texture(s, id, dx, dy); + id +} + +/// Writes the deterministic texture into layer `id` at offset (dx, dy). +fn paint_texture(s: &mut Session, id: LayerId, dx: i32, dy: i32) { + s.edit("tex", |doc, _| { + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + let mut seed = 99u64; + let mut rnd = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as f64 / (1u64 << 31) as f64 + }; + surf.fill_rect(Rect::new(dx, dy, dx + 240, dy + 180), &[0.4, 0.4, 0.4, 1.0]); + for _ in 0..120 { + let (x, y) = ((rnd() * 220.0) as i32, (rnd() * 160.0) as i32); + let (sw, sh) = (4 + (rnd() * 14.0) as i32, 4 + (rnd() * 10.0) as i32); + let v = rnd() as f32; + surf.fill_rect(Rect::new(dx + x, dy + y, dx + x + sw, dy + y + sh), &[v, 1.0 - v, v * 0.5, 1.0]); + } + Ok(()) + }) + .unwrap(); +} + +fn select(s: &mut Session, ids: &[LayerId]) { + s.execute("layer.select", json!({"layer": ids[0].0})).unwrap(); + for id in &ids[1..] { + s.execute("layer.select", json!({"layer": id.0, "mode": "add"})).unwrap(); + } +} + +#[test] +fn auto_align_repositions_at_all_depths() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 240, "depth": depth, "background": "transparent"})).unwrap(); + let a = texture_layer(&mut s, "A", 20, 20); + let b = texture_layer(&mut s, "B", 31, 13); + assert!(!s.is_enabled("edit.autoAlignLayers"), "one layer selected"); + select(&mut s, &[a, b]); + assert!(s.is_enabled("edit.autoAlignLayers")); + let r = s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).unwrap(); + assert_eq!(r["reference"], a.0); + let bb = s.active().unwrap().doc.layer(b).unwrap().surface().unwrap().content_bounds(); + assert!((bb.x0 - 20).abs() <= 1 && (bb.y0 - 20).abs() <= 1, "depth {depth}: {bb:?} {r}"); + s.undo(); + let bb = s.active().unwrap().doc.layer(b).unwrap().surface().unwrap().content_bounds(); + assert_eq!((bb.x0, bb.y0), (31, 13)); + } +} + +#[test] +fn auto_align_auto_projection_and_errors() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); + let a = texture_layer(&mut s, "A", 20, 20); + let b = texture_layer(&mut s, "B", 26, 25); + select(&mut s, &[a, b]); + let r = s.execute("edit.autoAlignLayers", json!({})).unwrap(); + let m = r["aligned"][0]["matrix"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::>(); + assert!((m[2] + 6.0).abs() < 1.0 && (m[5] + 5.0).abs() < 1.0, "{r}"); + assert!(s.execute("edit.autoAlignLayers", json!({"projection": "sideways"})).is_err()); + assert!(s.execute("edit.autoAlignLayers", json!({"reference": u64::MAX})).is_err()); +} + +/// As in Photoshop, a locked layer stays where it is: it becomes the reference and the +/// others move onto it (#7080). +#[test] +fn auto_align_keeps_a_locked_layer_as_the_reference() { + for lock in ["all", "position", "pixels"] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); + let a = texture_layer(&mut s, "A", 20, 20); + let b = texture_layer(&mut s, "B", 31, 13); + s.edit("lock", |doc, _| { + doc.layer_mut(b).unwrap().locks.set(lock, true); + Ok(()) + }) + .unwrap(); + select(&mut s, &[a, b]); + let r = s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).unwrap(); + assert_eq!(r["reference"], b.0, "{lock}: {r}"); + let doc = &s.active().unwrap().doc; + let bb = doc.layer(b).unwrap().surface().unwrap().content_bounds(); + assert_eq!((bb.x0, bb.y0), (31, 13), "{lock}: the locked layer stays put"); + let ab = doc.layer(a).unwrap().surface().unwrap().content_bounds(); + assert!((ab.x0 - 31).abs() <= 1 && (ab.y0 - 13).abs() <= 1, "{lock}: {ab:?} {r}"); + // An explicit reference that would move the locked layer is refused. + s.undo(); + assert!(s.execute("edit.autoAlignLayers", json!({"projection": "reposition", "reference": a.0})).is_err()); + // Two locked layers: nothing may move. + s.edit("lock", |doc, _| { + doc.layer_mut(a).unwrap().locks.set(lock, true); + Ok(()) + }) + .unwrap(); + assert!(s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).is_err()); + let bb = s.active().unwrap().doc.layer(a).unwrap().surface().unwrap().content_bounds(); + assert_eq!((bb.x0, bb.y0), (20, 20)); + } +} + +/// The Background doesn't block Auto-Align: when a projection reprojects every layer +/// (Cylindrical, Spherical, or Auto choosing one), or another layer is the reference, it +/// becomes a normal layer ("Layer 0") and moves, as in Photoshop and as Free Transform does. +#[test] +fn auto_align_moves_the_background_as_a_normal_layer() { + let setup = || { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 240, "background": "white"})).unwrap(); + let bg = s.active().unwrap().doc.background().unwrap().id; + paint_texture(&mut s, bg, 20, 20); + let b = texture_layer(&mut s, "B", 31, 13); + select(&mut s, &[bg, b]); + (s, bg, b) + }; + for projection in ["cylindrical", "spherical", "auto"] { + let (mut s, bg, b) = setup(); + let r = s.execute("edit.autoAlignLayers", json!({"projection": projection})).unwrap_or_else(|e| panic!("{projection}: {e}")); + let doc = &s.active().unwrap().doc; + let moved = r["aligned"].as_array().unwrap().iter().any(|a| a["layer"] == bg.0); + assert_eq!(moved, projection != "auto" || r["layout"] != "perspective", "{projection}: {r}"); + assert_eq!(doc.is_background(bg), !moved, "{projection}: a moved Background is a normal layer: {r}"); + if moved { + assert_eq!(doc.layer(bg).unwrap().name, "Layer 0", "{projection}"); + } + assert!(doc.layer(b).is_some(), "{projection}"); + s.undo(); + assert!(s.active().unwrap().doc.is_background(bg), "{projection}: undo restores the Background"); + } + // Planar, with the other layer as the reference: the Background moves onto it. + let (mut s, bg, b) = setup(); + s.execute("edit.autoAlignLayers", json!({"projection": "reposition", "reference": b.0})).unwrap(); + let doc = &s.active().unwrap().doc; + assert!(!doc.is_background(bg)); + // Default reference: the Background (bottom) stays put and stays the Background. + let (mut s, bg, b) = setup(); + let r = s.execute("edit.autoAlignLayers", json!({"projection": "reposition"})).unwrap(); + assert_eq!(r["reference"], bg.0, "{r}"); + let doc = &s.active().unwrap().doc; + assert!(doc.is_background(bg)); + let bb = doc.layer(b).unwrap().surface().unwrap().content_bounds(); + assert!((bb.x0 - 20).abs() <= 1 && (bb.y0 - 20).abs() <= 1, "{bb:?} {r}"); +} + +/// The moving layer's mask is warped as a mask: one grey channel whose outside keeps its +/// default (reveal-all stays revealed, hide-all stays hidden), for planar and mesh warps. +#[test] +fn auto_align_warps_layer_masks_keeping_their_default() { + for (projection, reveal) in [("reposition", true), ("reposition", false), ("cylindrical", true)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 240, "background": "transparent"})).unwrap(); + let a = texture_layer(&mut s, "A", 20, 20); + let b = texture_layer(&mut s, "B", 31, 13); + let (inside, outside) = if reveal { (0.0, 1.0) } else { (1.0, 0.0) }; + s.edit("mask", |doc, _| { + let mut m = if reveal { LayerMask::reveal_all() } else { LayerMask::hide_all() }; + m.surface.fill_rect(Rect::new(100, 100, 110, 110), &[inside]); + doc.layer_mut(b).unwrap().mask = Some(m); + Ok(()) + }) + .unwrap(); + select(&mut s, &[a, b]); + let r = s.execute("edit.autoAlignLayers", json!({"projection": projection})).unwrap(); + let doc = &s.active().unwrap().doc; + let m = doc.layer(b).unwrap().mask.as_ref().unwrap(); + assert_eq!(m.surface.format().channels(), 1, "{projection}: {r}"); + assert_eq!(m.value(250, 200), outside, "{projection} reveal={reveal}: {r}"); + assert_eq!(m.value(5, 5), outside, "{projection} reveal={reveal}: {r}"); + if projection == "reposition" { + // The square moved with the layer (by about (-11, +7)). + assert!((m.value(94, 112) - inside).abs() < 0.01, "{r}"); + } + } +} + +#[test] +fn auto_blend_panorama_masks_and_seamless_layer() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 60, "depth": depth, "background": "transparent"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "left"})).unwrap(); + s.edit("l", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 130, 60), &[0.2, 0.3, 0.8, 1.0]); + Ok(()) + }) + .unwrap(); + let left = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); + s.edit("r", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(70, 0, 200, 60), &[0.9, 0.6, 0.2, 1.0]); + Ok(()) + }) + .unwrap(); + let right = s.active().unwrap().active_layer.unwrap(); + select(&mut s, &[left, right]); + let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); + let doc = &s.active().unwrap().doc; + let ml = doc.layer(left).unwrap().mask.as_ref().unwrap(); + let mr = doc.layer(right).unwrap().mask.as_ref().unwrap(); + assert_eq!((ml.value(10, 30), mr.value(10, 30)), (1.0, 0.0), "depth {depth}"); + assert_eq!((ml.value(190, 30), mr.value(190, 30)), (0.0, 1.0)); + let blended = LayerId(r["blended"].as_u64().unwrap()); + let px = doc.layer(blended).unwrap().surface().unwrap().pixel(5, 30); + assert!((px[2] - 0.8).abs() < 0.02, "{px:?}"); + s.undo(); + assert!(s.active().unwrap().doc.layer(left).unwrap().mask.is_none()); + } +} + +/// #5745: the Background can't take a mask, so Auto-Blend turns it into a normal layer first. +#[test] +fn auto_blend_turns_the_background_into_a_layer() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 60, "background": "white"})).unwrap(); + let bg = s.active().unwrap().doc.background().unwrap().id; + s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); + s.edit("r", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(70, 0, 200, 60), &[0.9, 0.6, 0.2, 1.0]); + Ok(()) + }) + .unwrap(); + let right = s.active().unwrap().active_layer.unwrap(); + select(&mut s, &[bg, right]); + s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); + let doc = &s.active().unwrap().doc; + assert!(!doc.is_background(bg), "the Background became a layer to take its mask"); + assert!(doc.layer(bg).unwrap().mask.is_some()); + s.undo(); + assert!(s.active().unwrap().doc.is_background(bg), "undo restores the Background"); +} + +/// Seamless Tones and Colors evens out a 10% exposure step between two panorama layers. +#[test] +fn auto_blend_panorama_seamless_matches_exposure() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap(); + let mut ids = Vec::new(); + for (name, x0, x1, gain) in [("left", 0, 130, 1.0f32), ("right", 70, 200, 1.1)] { + s.execute("layer.new.layer", json!({ "name": name })).unwrap(); + s.edit(name, |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(x0, 0, x1, 60), &[0.2 * gain, 0.4 * gain, 0.5 * gain, 1.0]); + Ok(()) + }) + .unwrap(); + ids.push(s.active().unwrap().active_layer.unwrap()); + } + select(&mut s, &ids); + let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); + let doc = &s.active().unwrap().doc; + let blended = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap(); + let (a, b) = (blended.pixel(10, 30), blended.pixel(190, 30)); + // 0.5 vs 0.55 without gain compensation. + assert!((a[2] - b[2]).abs() < 0.015, "{a:?} {b:?}"); +} + +/// #5745: the top layer hangs off the canvas's right edge, so cropped to the canvas it lies +/// wholly over the bottom one. It used to get an all-black mask; now it shows on its side. +#[test] +fn auto_blend_panorama_of_a_layer_the_canvas_crops_to_all_overlap() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "left"})).unwrap(); + s.edit("l", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 200, 60), &[0.2, 0.4, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + let left = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); + s.edit("r", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(120, 0, 320, 60), &[0.2, 0.4, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + let right = s.active().unwrap().active_layer.unwrap(); + select(&mut s, &[left, right]); + s.execute("edit.autoBlendLayers", json!({"method": "panorama", "seamlessTones": false})).unwrap(); + let doc = &s.active().unwrap().doc; + let ml = doc.layer(left).unwrap().mask.as_ref().unwrap(); + let mr = doc.layer(right).unwrap().mask.as_ref().unwrap(); + assert_eq!((ml.value(10, 30), mr.value(10, 30)), (1.0, 0.0)); + assert_eq!((ml.value(195, 30), mr.value(195, 30)), (0.0, 1.0)); + for x in 0..200 { + assert_eq!(ml.value(x, 30) + mr.value(x, 30), 1.0, "x {x} shows one layer"); + } +} + +/// #5745: a layer Auto-Align left partly off the canvas is masked and blended over all of +/// its bounds, not cut off at the canvas edge. +#[test] +fn auto_blend_panorama_masks_past_the_canvas() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 60, "background": "transparent"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "left"})).unwrap(); + s.edit("l", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 150, 60), &[0.2, 0.4, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + let left = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "right"})).unwrap(); + s.edit("r", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(120, 0, 320, 60), &[0.2, 0.4, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + let right = s.active().unwrap().active_layer.unwrap(); + select(&mut s, &[left, right]); + let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); + let doc = &s.active().unwrap().doc; + let ml = doc.layer(left).unwrap().mask.as_ref().unwrap(); + let mr = doc.layer(right).unwrap().mask.as_ref().unwrap(); + assert_eq!((ml.value(10, 30), mr.value(10, 30)), (1.0, 0.0)); + assert_eq!((ml.value(300, 30), mr.value(300, 30)), (0.0, 1.0), "off the canvas"); + let blended = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap(); + assert_eq!(blended.pixel(300, 30)[3], 1.0, "the merged layer covers the off-canvas part"); +} + +/// A sparse layer whose bounds are huge (a dot at each far corner) raises its own content +/// estimate, so the extent past the canvas is capped independently: it keeps to the canvas. +#[test] +fn auto_blend_sparse_huge_bounds_keep_to_the_canvas() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "a"})).unwrap(); + s.edit("a", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(Rect::new(0, 0, 150, 200), &[0.2, 0.4, 0.5, 1.0]); + surf.fill_rect(Rect::new(100_000, 100_000, 100_001, 100_001), &[0.2, 0.4, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + let a = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "b"})).unwrap(); + s.edit("b", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(50, 0, 200, 200), &[0.2, 0.4, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + let b = s.active().unwrap().active_layer.unwrap(); + select(&mut s, &[a, b]); + let r = s.execute("edit.autoBlendLayers", json!({"method": "panorama"})).unwrap(); + let doc = &s.active().unwrap().doc; + let bb = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap().content_bounds(); + assert!(bb.x1 <= 200 && bb.y1 <= 200, "{bb:?}"); +} + +/// The budget past the canvas counts every layer's buffers, not just the work-area pixels. +#[test] +fn auto_blend_budget_counts_layers_and_channels() { + // Two RGBA layers: 4 bytes × (2 layers × (4 channels + luma, alpha, weight) + merged + depth). + assert_eq!(blend_bytes_per_pixel(2, 4), 88); + assert!(blend_bytes_per_pixel(5, 4) > blend_bytes_per_pixel(2, 4)); + // A 2^27-pixel area would need about 11 GiB for just two RGBA layers: it keeps to the canvas. + assert!((1u64 << 27).saturating_mul(blend_bytes_per_pixel(2, 4)) > MAX_BLEND_BYTES); + assert_eq!(blend_bytes_per_pixel(u64::MAX, 4), u64::MAX, "saturates instead of overflowing"); +} + +#[test] +fn auto_blend_stack_without_seamless() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "sharp"})).unwrap(); + s.edit("checker", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in (0..64).step_by(2) { + for x in (0..64).step_by(2) { + let v = if (x / 2 + y / 2) % 2 == 0 { 0.1 } else { 0.9 }; + surf.fill_rect(Rect::new(x, y, x + 2, y + 2), &[v, v, v, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + let a = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "flat"})).unwrap(); + s.edit("flat", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 64, 64), &[0.5, 0.5, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + let flat = s.active().unwrap().active_layer.unwrap(); + select(&mut s, &[a, flat]); + let r = s.execute("edit.autoBlendLayers", json!({"method": "stack", "seamlessTones": false})).unwrap(); + assert!(r["blended"].is_null()); + let doc = &s.active().unwrap().doc; + // The detailed layer is sharper everywhere. + let shown = (0..64).filter(|x| doc.layer(a).unwrap().mask.as_ref().unwrap().value(*x, 32) > 0.5).count(); + assert_eq!(shown, 64); + assert_eq!(doc.layer(flat).unwrap().mask.as_ref().unwrap().value(10, 10), 0.0); + assert!(s.execute("edit.autoBlendLayers", json!({"method": "sideways"})).is_err()); +} + +/// A smooth layer (soft blobs on a gradient) and the same picture a few pixels away: the +/// intensity registration finds the shift to a fraction of a pixel at every motion model. +fn smooth_layer(s: &mut Session, name: &str, dx: i32, dy: i32) -> LayerId { + s.execute("layer.new.layer", json!({"name": name})).unwrap(); + s.edit("smooth", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..150 { + for x in 0..200 { + let (u, v) = ((x - dx) as f32, (y - dy) as f32); + let blob = (-((u - 90.0).powi(2) + (v - 70.0).powi(2)) / (2.0 * 25.0f32.powi(2))).exp(); + let blob2 = (-((u - 150.0).powi(2) + (v - 40.0).powi(2)) / (2.0 * 15.0f32.powi(2))).exp(); + let g = 0.2 + 0.5 * blob + 0.25 * blob2 + 0.001 * u; + surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[g, g * 0.8, g * 0.6, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + s.active().unwrap().active_layer.unwrap() +} + +#[test] +fn auto_align_registers_a_smooth_bracket_by_intensity() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 150, "depth": depth, "background": "transparent"})).unwrap(); + let a = smooth_layer(&mut s, "A", 0, 0); + let b = smooth_layer(&mut s, "B", 4, 3); + select(&mut s, &[a, b]); + assert!(s.execute("edit.autoAlignLayers", json!({"registration": "sideways"})).is_err()); + assert!(s.execute("edit.autoAlignLayers", json!({"projection": "cylindrical", "registration": "intensity"})).is_err()); + for (params, model) in [ + (json!({"projection": "reposition", "registration": "intensity"}), "reposition"), + (json!({"registration": "intensity"}), "collage"), + (json!({"projection": "perspective", "registration": "intensity"}), "perspective"), + ] { + let r = s.execute("edit.autoAlignLayers", params).unwrap(); + assert_eq!(r["registration"], "intensity", "depth {depth}: {r}"); + assert_eq!(r["aligned"][0]["model"], model); + let m = r["aligned"][0]["matrix"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::>(); + assert!((m[2] + 4.0).abs() < 0.25 && (m[5] + 3.0).abs() < 0.25, "depth {depth} {model}: {r}"); + // B now shows A's picture. + let doc = &s.active().unwrap().doc; + let (pa, pb) = (doc.layer(a).unwrap().surface().unwrap().pixel(90, 70), doc.layer(b).unwrap().surface().unwrap().pixel(90, 70)); + assert!((pa[0] - pb[0]).abs() < 0.02, "depth {depth} {model}: {pa:?} vs {pb:?}"); + s.undo(); + } + } +} + +/// Layers with nothing in common are no fit: the intensity registration says so instead of +/// moving them by whatever pose its search box ends at. +#[test] +fn auto_align_rejects_unrelated_layers_instead_of_guessing_a_pose() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 150, "depth": 8, "background": "transparent"})).unwrap(); + let a = smooth_layer(&mut s, "A", 0, 0); + s.execute("layer.new.layer", json!({"name": "stripes"})).unwrap(); + s.edit("stripes", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..150 { + for x in 0..200 { + let g = if (x / 7 + y / 11) % 2 == 0 { 0.9 } else { 0.1 }; + surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[g, g, g, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + let b = s.active().unwrap().active_layer.unwrap(); + select(&mut s, &[a, b]); + for registration in ["intensity", "auto"] { + let err = s.execute("edit.autoAlignLayers", json!({"registration": registration})).unwrap_err().to_string(); + assert_eq!(err, NO_DETAIL, "{registration}"); + } + // A layer that is mostly empty overlaps too little to be placed. + let c = smooth_layer(&mut s, "C", 2, 1); + s.edit("hole", |doc, _| { + let surf = doc.layer_mut(c).unwrap().surface_mut().unwrap(); + surf.fill_rect(Rect::new(0, 0, 200, 120), &[0.0, 0.0, 0.0, 0.0]); + Ok(()) + }) + .unwrap(); + select(&mut s, &[a, c]); + assert_eq!(s.execute("edit.autoAlignLayers", json!({"registration": "intensity"})).unwrap_err().to_string(), NO_DETAIL); +} + +/// Two layers, each sharp on one half: the merged layer takes each half from the sharp layer. +#[test] +fn auto_blend_stack_fuses_the_sharp_halves() { + let checker = |x: i32, y: i32| if (x / 3 + y / 3) % 2 == 0 { 0.2 } else { 0.8 }; + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 96, "height": 64, "depth": depth, "background": "transparent"})).unwrap(); + let mut ids = Vec::new(); + for (name, sharp_left) in [("left", true), ("right", false)] { + s.execute("layer.new.layer", json!({"name": name})).unwrap(); + s.edit(name, |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..64 { + for x in 0..96 { + // The sharp half is the checker, the other half its local mean (flat gray). + let v = if (x < 48) == sharp_left { checker(x, y) } else { 0.5 }; + surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, v, v, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + ids.push(s.active().unwrap().active_layer.unwrap()); + } + select(&mut s, &ids); + for halo in [0.0, 2.0] { + let r = s.execute("edit.autoBlendLayers", json!({"method": "stack", "haloControl": halo})).unwrap(); + let doc = &s.active().unwrap().doc; + let blended = doc.layer(LayerId(r["blended"].as_u64().unwrap())).unwrap().surface().unwrap(); + for (x, y) in [(10, 20), (20, 40), (76, 20), (85, 40)] { + let px = blended.pixel(x, y); + assert!((px[0] - checker(x, y)).abs() < 0.08, "depth {depth} halo {halo} ({x},{y}): {px:?}"); + assert!((px[3] - 1.0).abs() < 1e-3, "{px:?}"); + } + // The masks still pick per pixel. + assert_eq!(doc.layer(ids[0]).unwrap().mask.as_ref().unwrap().value(10, 20), 1.0); + assert_eq!(doc.layer(ids[1]).unwrap().mask.as_ref().unwrap().value(85, 40), 1.0); + s.undo(); + assert!(s.active().unwrap().doc.layer(ids[0]).unwrap().mask.is_none()); + } + for bad in [json!(-1), json!(9), json!("hard")] { + assert!(s.execute("edit.autoBlendLayers", json!({"method": "stack", "haloControl": bad})).is_err(), "{bad}"); + } + } +} + +/// Three layers, each sharp in one third: the Depth layer says which, black to white from +/// the bottom layer to the top, hidden, and undone with the rest. +#[test] +fn auto_blend_stack_depth_map() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 96, "height": 48, "depth": depth, "background": "transparent"})).unwrap(); + let mut ids = Vec::new(); + for k in 0..3 { + s.execute("layer.new.layer", json!({"name": format!("L{k}")})).unwrap(); + s.edit("third", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..48 { + for x in 0..96 { + let v = if x / 32 == k && ((x / 2) + (y / 2)) % 2 == 0 { + 0.2 + } else if x / 32 == k { + 0.8 + } else { + 0.5 + }; + surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, v, v, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + ids.push(s.active().unwrap().active_layer.unwrap()); + } + select(&mut s, &ids); + assert!(s.execute("edit.autoBlendLayers", json!({"method": "panorama", "depthMap": true})).is_err()); + for seamless in [false, true] { + let r = s.execute("edit.autoBlendLayers", json!({"method": "stack", "seamlessTones": seamless, "depthMap": true})).unwrap(); + let doc = &s.active().unwrap().doc; + let d = doc.layer(LayerId(r["depth"].as_u64().unwrap())).unwrap(); + assert!(!d.visible && d.name.starts_with("Depth"), "depth {depth}: {} visible {} {r}", d.name, d.visible); + let surf = d.surface().unwrap(); + for (x, want) in [(8, 0.0), (48, 0.5), (88, 1.0)] { + let px = surf.pixel(x, 24); + assert!((px[0] - want).abs() < 0.2 && (px[3] - 1.0).abs() < 1e-3, "depth {depth} seamless {seamless} x {x}: {px:?}"); + } + assert_eq!(r["blended"].is_null(), !seamless); + if seamless { + // The merged layer sits above the depth layer and is the active one. + assert_eq!(s.active().unwrap().active_layer, Some(LayerId(r["blended"].as_u64().unwrap()))); + } + s.undo(); + assert!(s.active().unwrap().doc.layer(LayerId(r["depth"].as_u64().unwrap())).is_none()); + } + } +} From aad7e989e3a63c1b7ede5bdb4e97daa2eb4de23f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:16 +0000 Subject: [PATCH 038/259] refactor(engine): move warp_cmds.rs tests to warp_cmds/tests.rs --- crates/engine/src/warp_cmds.rs | 463 +-------------------------- crates/engine/src/warp_cmds/tests.rs | 460 ++++++++++++++++++++++++++ 2 files changed, 461 insertions(+), 462 deletions(-) create mode 100644 crates/engine/src/warp_cmds/tests.rs diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rs index 6a98b608fb..c5c04132d5 100644 --- a/crates/engine/src/warp_cmds.rs +++ b/crates/engine/src/warp_cmds.rs @@ -728,465 +728,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_warp_box_holding_the_whole_layer_gives_what_compositing_over_the_cleared_layer_did() { - for depth in [8, 16, 32] { - let s = session(depth); - let st = s.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); - let surf = l.surface().unwrap().clone(); - let rect = surf.content_bounds(); - let w = Warp::preset(WarpStyle::Flag, 35.0, rect_f(rect)); - // What the warp built before the shortcut: the warp composited over the cleared layer. - let map = |x: f64, y: f64| w.map(x, y); - let warped = warp_mesh_surface_with(&surf, rect, &map, Interp::Bicubic, &Interrupt::NONE).unwrap(); - let mut want = surf.clone(); - crate::pixels::try_clear_surface(&mut want, rect, None).unwrap(); - crate::transform_cmds::composite_over(&mut want, &warped); - want.prune(); - let mut got = l.clone(); - warp_layer(None, Locks::default(), &mut got, &w, rect, Interp::Bicubic, None, &Interrupt::NONE).unwrap(); - let got = got.surface().unwrap(); - let b = want.content_bounds(); - assert_eq!(got.content_bounds(), b, "depth {depth}"); - let (g, wv) = (got.read_region(b), want.read_region(b)); - // Exact at 8 and 16 bits. At 32 the composite's `t·a / a` rounds a few values by an - // ulp; the shortcut keeps the warp's own. - let tol = if depth == 32 { 1e-6 } else { 0.0 }; - let worst = g.iter().zip(&wv).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(worst <= tol, "depth {depth}: off by {worst}"); - } - } - - fn session(depth: u64) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 80, "height": 60, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - let surf = l.surface_mut().unwrap(); - for y in 10..40 { - for x in 10..60 { - let v = ((x * 3 + y * 5) % 11) as f32 / 10.0; - surf.write_pixel(x, y, &[v, 1.0 - v, 0.5, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - s - } - - fn active_surface(s: &Session) -> Surface { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone() - } - - /// Warp on type sets its Warp Text (#3004): the layer stays type, one step; a custom mesh is - /// refused rather than rasterizing. - #[test] - fn warp_style_on_type_is_warp_text() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); - s.execute("type.create", json!({"x": 10, "y": 60, "text": "Hi"})).unwrap(); - let n = s.active().unwrap().history.past_len(); - s.execute("edit.transform.warp", json!({"style": "arc", "bend": 30})).unwrap(); - let st = s.active().unwrap(); - let LayerContent::Text(t) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("type") }; - assert_eq!(t.warp.as_ref().map(|w| (w.style.as_str(), w.value)), Some(("warpArc", 30.0))); - assert_eq!(st.history.past_len(), n + 1); - let mesh = BezierMesh::identity([0.0, 0.0, 10.0, 10.0], 1, 1).map_points(|p| [p[0] * 2.0, p[1]]); - assert!(s.execute("edit.transform.warp", json!({"warp": Warp::custom(mesh, [0.0, 0.0, 10.0, 10.0])})).is_err()); - } - - /// The seven values of a cylinder over the session's painted box (x 10..60, y 10..40). - const CYL: [f64; 7] = [10.0, 40.0, 60.0, 10.0, 0.3, 0.3, 0.5]; - - /// `style: "cylinder"` takes its seven values (#4112); anything that isn't a horizontal - /// cylinder is refused, never a silent no-op, and the layer is left alone. - #[test] - fn cylinder_style_needs_its_values() { - let mut s = session(8); - let before = active_surface(&s); - for p in [ - json!({"style": "cylinder"}), - json!({"style": "cylinder", "values": [10, 40, 60, 10, 0.3, 0.3]}), - json!({"style": "cylinder", "values": [60, 40, 10, 10, 0.3, 0.3, 0.5]}), - json!({"style": "cylinder", "values": [10, 40, 60, 10, 0.3, 0.3, "x"]}), - json!({"style": "cylinder", "values": "seven"}), - json!({"style": "cylinder", "values": CYL, "vertical": true}), - json!({"style": "cylinder", "values": CYL, "hDistort": 10}), - json!({"warp": {"style": "cylinder", "bounds": [10.0, 10.0, 60.0, 40.0]}}), - json!({"warp": {"style": "cylinder", "values": CYL, "bounds": [10.0, 10.0, 60.0, 40.0], "vertical": true}}), - json!({"warp": {"style": "cylinder", "values": CYL, "bounds": [10.0, 10.0, 60.0, 40.0], "hDistort": 10.0}}), - json!({"warp": {"style": "cylinder", "values": CYL, "bounds": [10.0, 10.0, 60.0, 40.0], "vDistort": -5.0}}), - ] { - let e = s.execute("edit.transform.warp", p.clone()).unwrap_err().to_string(); - assert!(e.contains("cylinder"), "{p}: {e}"); - } - assert_eq!(active_surface(&s), before); - // On type it is refused like a custom mesh: Warp Text has no cylinder. - s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi"})).unwrap(); - assert!(s.execute("edit.transform.warp", json!({"style": "cylinder", "values": CYL})).is_err()); - } - - #[test] - fn cylinder_warps_pixels_at_every_depth() { - for depth in [8u64, 16, 32] { - let mut s = session(depth); - let r = s.execute("edit.transform.warp", json!({"style": "cylinder", "values": CYL})).unwrap(); - assert_eq!(r["changed"], true, "{depth}"); - let after = active_surface(&s); - let b = after.content_bounds(); - // Between the silhouettes, the edges bowed down by the ellipses. - assert!(b.x0 >= 9 && b.x1 <= 61 && b.y0 >= 9 && b.y1 > 40, "{depth}: {b:?}"); - // The same cylinder as a full warp object (its mesh rebuilt from the values) agrees. - let mut t = session(depth); - let w = Warp::cylinder(&CYL, [10.0, 10.0, 60.0, 40.0]).unwrap(); - let mut garbled = w.clone(); - garbled.mesh = None; - t.execute("edit.transform.warp", json!({"warp": garbled})).unwrap(); - assert_eq!(active_surface(&t), after, "{depth}"); - } - } - - /// On a smart object the cylinder is stored in source space: still a cylinder (so it goes to - /// PSD as one) when the placement only scales and moves, its mesh when it rotates. - #[test] - fn smart_object_cylinder_is_stored_in_source_space() { - let stored = |s: &Session| { - let st = s.active().unwrap(); - let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("smart") }; - sm.warp.clone().unwrap() - }; - let mut s = session(8); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": CYL, "rect": [10, 10, 60, 40]})).unwrap(); - let w = stored(&s); - assert_eq!(w.style, WarpStyle::Cylinder); - let LayerContent::Smart(sm) = &s.active().unwrap().doc.layers[1].content else { panic!("smart") }; - let inv = crate::smart_cmds::placement(sm).inverse().unwrap(); - let src = |x: f64, y: f64| inv.apply(x, y); - let ((l, t), (r, bt)) = (src(10.0, 10.0), src(60.0, 40.0)); - for (a, b) in w.values.iter().zip([l, bt, r, t, 0.3, 0.3, 0.5]) { - assert!((a - b).abs() < 1e-9, "{:?}", w.values); - } - // Twice as wide: the silhouettes double, the ellipses' depth (in half axes) halves. - let mut s = session(8); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("edit.transform", json!({"scaleX": 200, "scaleY": 100})).unwrap(); - let wide = [-15.0, 40.0, 85.0, 10.0, 0.3, 0.3, 0.5]; - s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": wide, "rect": [-15, 10, 85, 40]})).unwrap(); - let w = stored(&s); - assert_eq!(w.style, WarpStyle::Cylinder); - assert!((w.values[4] - 0.6).abs() < 1e-9 && (w.values[5] - 0.6).abs() < 1e-9, "{:?}", w.values); - // The silhouettes land on the source's own edges (its contents span the scaled box). - let LayerContent::Smart(sm) = &s.active().unwrap().doc.layers[1].content else { panic!("smart") }; - let inv = crate::smart_cmds::placement(sm).inverse().unwrap(); - assert!((w.values[0] - inv.apply(-15.0, 10.0).0).abs() < 1e-9 && (w.values[2] - inv.apply(85.0, 10.0).0).abs() < 1e-9, "{:?}", w.values); - // Rotated: a custom mesh with the same shape. - let mut s = session(8); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("edit.transform", json!({"rotate": 30})).unwrap(); - s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": CYL, "rect": [10, 10, 60, 40]})).unwrap(); - let w = stored(&s); - assert_eq!(w.style, WarpStyle::Custom); - 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. - #[test] - fn untouched_cylinder_committed_from_warp_mode_stays_a_cylinder() { - for scale in [100, 150] { - let mut s = session(8); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("edit.transform", json!({"scaleX": scale, "scaleY": 100})).unwrap(); - let id = s.active().unwrap().active_layer.unwrap(); - let rect = warp_bounds(&s.active().unwrap().doc, s.active().unwrap().doc.layer(id).unwrap()); - let [x0, x1] = [f64::from(rect.x0), f64::from(rect.x1)]; - let values = [x0, 40.0, x1, 10.0, 0.3, 0.3, 0.5]; - s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": values, "rect": [rect.x0, 10, rect.x1, 40]})).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() - }; - 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"); - // The same mesh over another box is another warp. - let mut wider = shown.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(); - 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"); - } - } - - #[test] - fn identity_and_bend_zero_are_no_ops_at_every_depth() { - for depth in [8u64, 16, 32] { - let mut s = session(depth); - let before = active_surface(&s); - let r = s.execute("edit.transform.warp", json!({"style": "custom"})).unwrap(); - assert_eq!(r["changed"], false); - s.execute("edit.transform.warp", json!({"style": "flag", "bend": 0})).unwrap(); - // A custom identity mesh passed explicitly (forces a resample) stays within 1/255. - let m = BezierMesh::identity([10.0, 10.0, 60.0, 40.0], 2, 2); - let mut w = Warp::custom(m, [10.0, 10.0, 60.0, 40.0]); - w.mesh.as_mut().unwrap().points[5][0] += 1e-12; // not exactly identity - s.execute("edit.transform.warp", json!({"warp": w})).unwrap(); - let after = active_surface(&s); - let r = Rect::new(10, 10, 60, 40); - assert_eq!(after.content_bounds(), r, "{depth}"); - let worst = before.read_region(r).iter().zip(after.read_region(r)).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(worst <= 1.0 / 255.0, "{depth}: {worst}"); - } - } - - #[test] - fn arc_warps_pixels_and_undoes() { - let mut s = session(8); - let before = active_surface(&s); - s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap(); - let after = active_surface(&s); - // As in Photoshop: the bottom edge keeps its corners, the top rises and spreads. - let c = after.content_bounds(); - assert!(c.y1 <= 41 && c.y0 < 8 && c.x0 < 8 && c.x1 > 62, "{c:?}"); - s.undo(); - assert_eq!(active_surface(&s), before); - assert!(s.execute("edit.transform.warp", json!({"style": "spiral"})).is_err()); - assert!(s.execute("edit.transform.warp", json!({})).is_err()); - assert!(s.execute("edit.transform.warp", json!({"mesh": {"us": [0, 1], "vs": [0, 1], "points": [[0, 0]]}})).is_err()); - } - - #[test] - fn custom_mesh_moves_a_control_point() { - let mut s = session(16); - let mut m = BezierMesh::identity([10.0, 10.0, 60.0, 40.0], 1, 1); - m.points[15] = [70.0, 50.0]; // bottom-right corner - s.execute("edit.transform.warp", json!({"mesh": m})).unwrap(); - let b = active_surface(&s).content_bounds(); - assert!(b.x1 >= 69 && b.y1 >= 49, "{b:?}"); - } - - #[test] - fn split_cuts_existing_sections_instead_of_replacing_the_grid() { - let b = [0.0, 0.0, 90.0, 60.0]; - let plain = Warp::custom(BezierMesh::identity(b, 1, 1), b); - let cut = split_warp(&plain, Some([b[0] + 0.25 * 90.0, 30.0]), Split::Vertical).unwrap(); - let m = cut.mesh.unwrap(); - for u in [0.0, 0.25, 1.0 / 3.0, 2.0 / 3.0, 1.0] { - assert!(m.us.iter().any(|k| (k - u).abs() < 1e-6), "default guides stay, cut at 0.25: {:?}", m.us); - } - assert_eq!(m.vs, vec![0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]); - let grid = BezierMesh::identity(b, 3, 3); - let cut = split_warp(&Warp::custom(grid.clone(), b), Some([45.0, 10.0]), Split::Vertical).unwrap(); - let m = cut.mesh.unwrap(); - assert_eq!(m.vs, grid.vs); - assert_eq!(m.us.len(), grid.us.len() + 1); - for u in [0.0, 1.0 / 3.0, 0.5, 2.0 / 3.0, 1.0] { - assert!(m.us.iter().any(|k| (k - u).abs() < 1e-6), "{:?}", m.us); - } - let (nx0, nx1) = (grid.nx(), m.nx()); - for j in 0..grid.ny() { - for i in 0..3 { - assert_eq!(m.points[j * nx1 + i], grid.points[j * nx0 + i]); - } - } - } - - #[test] - fn split_commands_edit_meshes_exactly() { - let mut s = session(8); - let w = Warp::preset(WarpStyle::Bulge, 30.0, [10.0, 10.0, 60.0, 40.0]); - let r = s.execute("edit.transform.splitWarpCrosswise", json!({"warp": w, "at": [30.0, 20.0]})).unwrap(); - let split: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); - let m = split.mesh.as_ref().unwrap(); - assert_eq!((m.nx(), m.ny()), (7, 7)); - let r = s.execute("edit.transform.splitWarpVertically", json!({"warp": split})).unwrap(); - let v: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); - assert_eq!(v.mesh.as_ref().unwrap().us.len(), 4); - let r = s.execute("edit.transform.removeWarpSplit", json!({"warp": v, "at": [30.0, 20.0]})).unwrap(); - let back: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); - assert!(back.mesh.as_ref().unwrap().us.len() + back.mesh.as_ref().unwrap().vs.len() < 7); - // Splitting never changes the shape. - for (x, y) in [(15.0, 15.0), (40.0, 33.0)] { - let (a, b) = (w.map(x, y), split.map(x, y)); - assert!((a.0 - b.0).abs() < 0.6 && (a.1 - b.1).abs() < 0.6, "{a:?} {b:?}"); - } - } - - #[test] - fn smart_object_warp_is_lossless() { - for depth in [8u64, 16, 32] { - let mut s = session(depth); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let original = active_surface(&s); - s.execute("layer.smartObjects.warp", json!({"style": "wave", "bend": 60})).unwrap(); - let warped = active_surface(&s); - assert_ne!(warped, original); - let st = s.active().unwrap(); - let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!() }; - assert!(sm.warp.is_some()); - // Removing the warp re-renders the source exactly (no accumulated resampling). - s.execute("layer.smartObjects.warp", json!({"style": "none"})).unwrap(); - assert_eq!(active_surface(&s), original, "{depth}"); - // Warping twice equals warping once with the second warp. - s.execute("layer.smartObjects.warp", json!({"style": "arc", "bend": 20})).unwrap(); - s.execute("layer.smartObjects.warp", json!({"style": "wave", "bend": 60})).unwrap(); - assert_eq!(active_surface(&s), warped, "{depth}"); - // Split on the stored warp keeps the appearance (within resampling of the mesh fit). - s.execute("edit.transform.splitWarpCrosswise", json!({})).unwrap(); - let st = s.active().unwrap(); - let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!() }; - assert_eq!(sm.warp.as_ref().unwrap().style, WarpStyle::Custom); - } - } - - #[test] - fn crosswise_split_of_an_identity_custom_warp_is_four_by_four() { - let mut s = session(8); - let r = s.execute("edit.transform.splitWarpCrosswise", json!({"style": "custom", "rect": [0.0, 0.0, 90.0, 60.0]})).unwrap(); - let out: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); - let m = out.mesh.unwrap(); - assert_eq!((m.us.len(), m.vs.len()), (5, 5), "thirds, then the centre cut: {:?}", (m.us.clone(), m.vs.clone())); - for u in [0.0, 1.0 / 3.0, 0.5, 2.0 / 3.0, 1.0] { - assert!(m.us.iter().any(|k| (k - u).abs() < 1e-6), "{:?}", m.us); - assert!(m.vs.iter().any(|k| (k - u).abs() < 1e-6), "{:?}", m.vs); - } - } - - #[test] - fn extreme_rect_is_bad_params_not_a_giant_warp() { - let mut s = session(8); - for cmd in ["edit.transform.warp", "layer.smartObjects.warp"] { - if cmd == "layer.smartObjects.warp" { - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - } - let e = s.execute(cmd, json!({"style": "arc", "bend": 50, "rect": [-1e30, -1e30, 1e30, 1e30]})).unwrap_err(); - assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg.contains("rect too large")), "{cmd}: {e}"); - } - s.execute("layer.smartObjects.warp", json!({"style": "arc", "bend": 50, "rect": [10, 10, 60, 40]})).unwrap(); - } - - #[test] - fn warp_grid_fits_the_surface_and_rejects_bad_sizes() { - let mut s = session(8); - assert!(s.execute("edit.transform.warpGrid", json!({})).is_err()); - assert!(s.execute("edit.transform.warpGrid", json!({"size": 0})).is_err()); - assert!(s.execute("edit.transform.warpGrid", json!({"size": -3})).is_err()); - assert!(s.execute("edit.transform.warpGrid", json!({"size": 65})).is_err()); - assert!(s.execute("edit.transform.warpGrid", json!({"size": 1.5})).is_err()); - assert!(s.execute("edit.transform.warpGrid", json!({"size": "custom"})).is_err()); - assert!(s.execute("edit.transform.warpGrid", json!({"size": "nope"})).is_err()); - assert!(s.execute("edit.transform.warpGrid", json!({"grid": [3, 3]})).is_err()); - let b = [10.0, 10.0, 60.0, 40.0]; - let mut bent = BezierMesh::identity(b, 1, 1); - bent.points[0][0] += 12.0; - let r = s.execute("edit.transform.warpGrid", json!({"warp": Warp::custom(bent.clone(), b), "size": 4})).unwrap(); - let out: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); - let m = out.mesh.unwrap(); - assert_eq!(out.style, WarpStyle::Custom); - assert_eq!(m.us, vec![0.0, 0.25, 0.5, 0.75, 1.0]); - assert_eq!(m.vs, m.us); - assert!((m.eval(0.0, 0.0)[0] - bent.eval(0.0, 0.0)[0]).abs() < 1e-3); - assert!((m.eval(1.0, 1.0)[0] - b[2]).abs() < 1e-3); - let r = s.execute("edit.transform.warpGrid", json!({"warp": Warp::custom(m, b), "size": "default"})).unwrap(); - let back: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); - assert_eq!(back.mesh.unwrap().us.len(), 2); - } - - /// A selection limits the warp of a linked mask too, as it does the pixels (#4175; Free - /// Transform and Perspective Warp did this already, #3083): the moved part of the mask lines - /// up with the moved pixels and the unselected part stays put. - #[test] - fn linked_mask_with_a_selection_warps_only_the_selected_region() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 20), &[1.0, 0.0, 0.0, 1.0]); - // Hide the left quarter (selected) and the right quarter (not selected). - let m = l.mask.as_mut().unwrap(); - m.surface.fill_rect(Rect::new(10, 10, 15, 20), &[0.0]); - m.surface.fill_rect(Rect::new(25, 10, 30, 20), &[0.0]); - m.linked = true; - Ok(()) - }) - .unwrap(); - let mask_at = |s: &Session, x, y| { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0) - }; - let alpha_at = |s: &Session, x, y| { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)[3] - }; - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - // A mesh that translates the selected box 50 px down. - let b = [10.0, 10.0, 20.0, 20.0]; - let mesh = BezierMesh::identity(b, 1, 1).map_points(|p| [p[0], p[1] + 50.0]); - s.execute("edit.transform.warp", json!({"rect": [10, 10, 20, 20], "mesh": mesh})).unwrap(); - // Moved pixels and their mask line up. - assert!(alpha_at(&s, 12, 65) > 0.99); - assert!(mask_at(&s, 12, 65) < 0.01, "selected hidden quarter moved"); - assert!(mask_at(&s, 17, 65) > 0.99, "selected visible quarter moved"); - // The vacated area reads as revealed, with transparent pixels. - assert!(alpha_at(&s, 12, 15) < 0.01); - assert!(mask_at(&s, 12, 15) > 0.99); - // The unselected part of the mask stays, aligned with the unselected pixels. - assert!(alpha_at(&s, 27, 15) > 0.99); - assert!(mask_at(&s, 27, 15) < 0.01, "unselected mask stays put"); - assert!(mask_at(&s, 27, 65) > 0.99, "and isn't copied along"); - for (x, y) in [(11, 61), (13, 68), (16, 61), (18, 68)] { - let want = if x < 15 { 0.0 } else { 1.0 }; - assert!((mask_at(&s, x, y) - want).abs() < 0.01, "({x},{y}): {}", mask_at(&s, x, y)); - } - } - - /// Esc stops the warp of a selected linked mask too, not only of the pixels. A fill layer has - /// no pixels to warp, so the mask is the only part that can see the cancel. - #[test] - fn a_cancelled_warp_stops_in_a_selected_linked_mask() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); - s.execute("layer.newFillLayer.solidColor", json!({})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.edit("link", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().mask.as_mut().unwrap().linked = true; - Ok(()) - }) - .unwrap(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - let st = s.active().unwrap(); - let (sel, mut l) = (st.doc.selection.clone().unwrap(), st.doc.layer(st.active_layer.unwrap()).unwrap().clone()); - let rect = Rect::new(10, 10, 20, 20); - let w = Warp::preset(WarpStyle::Flag, 35.0, rect_f(rect)); - let ctl = Interrupt::cancel_only(&|| true); - let r = warp_layer(Some(&sel), Locks::default(), &mut l, &w, rect, Interp::Bicubic, None, &ctl); - assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); - } -} +mod tests; diff --git a/crates/engine/src/warp_cmds/tests.rs b/crates/engine/src/warp_cmds/tests.rs new file mode 100644 index 0000000000..08130688c6 --- /dev/null +++ b/crates/engine/src/warp_cmds/tests.rs @@ -0,0 +1,460 @@ +use super::*; + +#[test] +fn a_warp_box_holding_the_whole_layer_gives_what_compositing_over_the_cleared_layer_did() { + for depth in [8, 16, 32] { + let s = session(depth); + let st = s.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + let surf = l.surface().unwrap().clone(); + let rect = surf.content_bounds(); + let w = Warp::preset(WarpStyle::Flag, 35.0, rect_f(rect)); + // What the warp built before the shortcut: the warp composited over the cleared layer. + let map = |x: f64, y: f64| w.map(x, y); + let warped = warp_mesh_surface_with(&surf, rect, &map, Interp::Bicubic, &Interrupt::NONE).unwrap(); + let mut want = surf.clone(); + crate::pixels::try_clear_surface(&mut want, rect, None).unwrap(); + crate::transform_cmds::composite_over(&mut want, &warped); + want.prune(); + let mut got = l.clone(); + warp_layer(None, Locks::default(), &mut got, &w, rect, Interp::Bicubic, None, &Interrupt::NONE).unwrap(); + let got = got.surface().unwrap(); + let b = want.content_bounds(); + assert_eq!(got.content_bounds(), b, "depth {depth}"); + let (g, wv) = (got.read_region(b), want.read_region(b)); + // Exact at 8 and 16 bits. At 32 the composite's `t·a / a` rounds a few values by an + // ulp; the shortcut keeps the warp's own. + let tol = if depth == 32 { 1e-6 } else { 0.0 }; + let worst = g.iter().zip(&wv).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(worst <= tol, "depth {depth}: off by {worst}"); + } +} + +fn session(depth: u64) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 80, "height": 60, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + let surf = l.surface_mut().unwrap(); + for y in 10..40 { + for x in 10..60 { + let v = ((x * 3 + y * 5) % 11) as f32 / 10.0; + surf.write_pixel(x, y, &[v, 1.0 - v, 0.5, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + s +} + +fn active_surface(s: &Session) -> Surface { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone() +} + +/// Warp on type sets its Warp Text (#3004): the layer stays type, one step; a custom mesh is +/// refused rather than rasterizing. +#[test] +fn warp_style_on_type_is_warp_text() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + s.execute("type.create", json!({"x": 10, "y": 60, "text": "Hi"})).unwrap(); + let n = s.active().unwrap().history.past_len(); + s.execute("edit.transform.warp", json!({"style": "arc", "bend": 30})).unwrap(); + let st = s.active().unwrap(); + let LayerContent::Text(t) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("type") }; + assert_eq!(t.warp.as_ref().map(|w| (w.style.as_str(), w.value)), Some(("warpArc", 30.0))); + assert_eq!(st.history.past_len(), n + 1); + let mesh = BezierMesh::identity([0.0, 0.0, 10.0, 10.0], 1, 1).map_points(|p| [p[0] * 2.0, p[1]]); + assert!(s.execute("edit.transform.warp", json!({"warp": Warp::custom(mesh, [0.0, 0.0, 10.0, 10.0])})).is_err()); +} + +/// The seven values of a cylinder over the session's painted box (x 10..60, y 10..40). +const CYL: [f64; 7] = [10.0, 40.0, 60.0, 10.0, 0.3, 0.3, 0.5]; + +/// `style: "cylinder"` takes its seven values (#4112); anything that isn't a horizontal +/// cylinder is refused, never a silent no-op, and the layer is left alone. +#[test] +fn cylinder_style_needs_its_values() { + let mut s = session(8); + let before = active_surface(&s); + for p in [ + json!({"style": "cylinder"}), + json!({"style": "cylinder", "values": [10, 40, 60, 10, 0.3, 0.3]}), + json!({"style": "cylinder", "values": [60, 40, 10, 10, 0.3, 0.3, 0.5]}), + json!({"style": "cylinder", "values": [10, 40, 60, 10, 0.3, 0.3, "x"]}), + json!({"style": "cylinder", "values": "seven"}), + json!({"style": "cylinder", "values": CYL, "vertical": true}), + json!({"style": "cylinder", "values": CYL, "hDistort": 10}), + json!({"warp": {"style": "cylinder", "bounds": [10.0, 10.0, 60.0, 40.0]}}), + json!({"warp": {"style": "cylinder", "values": CYL, "bounds": [10.0, 10.0, 60.0, 40.0], "vertical": true}}), + json!({"warp": {"style": "cylinder", "values": CYL, "bounds": [10.0, 10.0, 60.0, 40.0], "hDistort": 10.0}}), + json!({"warp": {"style": "cylinder", "values": CYL, "bounds": [10.0, 10.0, 60.0, 40.0], "vDistort": -5.0}}), + ] { + let e = s.execute("edit.transform.warp", p.clone()).unwrap_err().to_string(); + assert!(e.contains("cylinder"), "{p}: {e}"); + } + assert_eq!(active_surface(&s), before); + // On type it is refused like a custom mesh: Warp Text has no cylinder. + s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi"})).unwrap(); + assert!(s.execute("edit.transform.warp", json!({"style": "cylinder", "values": CYL})).is_err()); +} + +#[test] +fn cylinder_warps_pixels_at_every_depth() { + for depth in [8u64, 16, 32] { + let mut s = session(depth); + let r = s.execute("edit.transform.warp", json!({"style": "cylinder", "values": CYL})).unwrap(); + assert_eq!(r["changed"], true, "{depth}"); + let after = active_surface(&s); + let b = after.content_bounds(); + // Between the silhouettes, the edges bowed down by the ellipses. + assert!(b.x0 >= 9 && b.x1 <= 61 && b.y0 >= 9 && b.y1 > 40, "{depth}: {b:?}"); + // The same cylinder as a full warp object (its mesh rebuilt from the values) agrees. + let mut t = session(depth); + let w = Warp::cylinder(&CYL, [10.0, 10.0, 60.0, 40.0]).unwrap(); + let mut garbled = w.clone(); + garbled.mesh = None; + t.execute("edit.transform.warp", json!({"warp": garbled})).unwrap(); + assert_eq!(active_surface(&t), after, "{depth}"); + } +} + +/// On a smart object the cylinder is stored in source space: still a cylinder (so it goes to +/// PSD as one) when the placement only scales and moves, its mesh when it rotates. +#[test] +fn smart_object_cylinder_is_stored_in_source_space() { + let stored = |s: &Session| { + let st = s.active().unwrap(); + let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("smart") }; + sm.warp.clone().unwrap() + }; + let mut s = session(8); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": CYL, "rect": [10, 10, 60, 40]})).unwrap(); + let w = stored(&s); + assert_eq!(w.style, WarpStyle::Cylinder); + let LayerContent::Smart(sm) = &s.active().unwrap().doc.layers[1].content else { panic!("smart") }; + let inv = crate::smart_cmds::placement(sm).inverse().unwrap(); + let src = |x: f64, y: f64| inv.apply(x, y); + let ((l, t), (r, bt)) = (src(10.0, 10.0), src(60.0, 40.0)); + for (a, b) in w.values.iter().zip([l, bt, r, t, 0.3, 0.3, 0.5]) { + assert!((a - b).abs() < 1e-9, "{:?}", w.values); + } + // Twice as wide: the silhouettes double, the ellipses' depth (in half axes) halves. + let mut s = session(8); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("edit.transform", json!({"scaleX": 200, "scaleY": 100})).unwrap(); + let wide = [-15.0, 40.0, 85.0, 10.0, 0.3, 0.3, 0.5]; + s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": wide, "rect": [-15, 10, 85, 40]})).unwrap(); + let w = stored(&s); + assert_eq!(w.style, WarpStyle::Cylinder); + assert!((w.values[4] - 0.6).abs() < 1e-9 && (w.values[5] - 0.6).abs() < 1e-9, "{:?}", w.values); + // The silhouettes land on the source's own edges (its contents span the scaled box). + let LayerContent::Smart(sm) = &s.active().unwrap().doc.layers[1].content else { panic!("smart") }; + let inv = crate::smart_cmds::placement(sm).inverse().unwrap(); + assert!((w.values[0] - inv.apply(-15.0, 10.0).0).abs() < 1e-9 && (w.values[2] - inv.apply(85.0, 10.0).0).abs() < 1e-9, "{:?}", w.values); + // Rotated: a custom mesh with the same shape. + let mut s = session(8); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("edit.transform", json!({"rotate": 30})).unwrap(); + s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": CYL, "rect": [10, 10, 60, 40]})).unwrap(); + let w = stored(&s); + assert_eq!(w.style, WarpStyle::Custom); + 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. +#[test] +fn untouched_cylinder_committed_from_warp_mode_stays_a_cylinder() { + for scale in [100, 150] { + let mut s = session(8); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("edit.transform", json!({"scaleX": scale, "scaleY": 100})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let rect = warp_bounds(&s.active().unwrap().doc, s.active().unwrap().doc.layer(id).unwrap()); + let [x0, x1] = [f64::from(rect.x0), f64::from(rect.x1)]; + let values = [x0, 40.0, x1, 10.0, 0.3, 0.3, 0.5]; + s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": values, "rect": [rect.x0, 10, rect.x1, 40]})).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() + }; + 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"); + // The same mesh over another box is another warp. + let mut wider = shown.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(); + 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"); + } +} + +#[test] +fn identity_and_bend_zero_are_no_ops_at_every_depth() { + for depth in [8u64, 16, 32] { + let mut s = session(depth); + let before = active_surface(&s); + let r = s.execute("edit.transform.warp", json!({"style": "custom"})).unwrap(); + assert_eq!(r["changed"], false); + s.execute("edit.transform.warp", json!({"style": "flag", "bend": 0})).unwrap(); + // A custom identity mesh passed explicitly (forces a resample) stays within 1/255. + let m = BezierMesh::identity([10.0, 10.0, 60.0, 40.0], 2, 2); + let mut w = Warp::custom(m, [10.0, 10.0, 60.0, 40.0]); + w.mesh.as_mut().unwrap().points[5][0] += 1e-12; // not exactly identity + s.execute("edit.transform.warp", json!({"warp": w})).unwrap(); + let after = active_surface(&s); + let r = Rect::new(10, 10, 60, 40); + assert_eq!(after.content_bounds(), r, "{depth}"); + let worst = before.read_region(r).iter().zip(after.read_region(r)).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(worst <= 1.0 / 255.0, "{depth}: {worst}"); + } +} + +#[test] +fn arc_warps_pixels_and_undoes() { + let mut s = session(8); + let before = active_surface(&s); + s.execute("edit.transform.warp", json!({"style": "arc", "bend": 50})).unwrap(); + let after = active_surface(&s); + // As in Photoshop: the bottom edge keeps its corners, the top rises and spreads. + let c = after.content_bounds(); + assert!(c.y1 <= 41 && c.y0 < 8 && c.x0 < 8 && c.x1 > 62, "{c:?}"); + s.undo(); + assert_eq!(active_surface(&s), before); + assert!(s.execute("edit.transform.warp", json!({"style": "spiral"})).is_err()); + assert!(s.execute("edit.transform.warp", json!({})).is_err()); + assert!(s.execute("edit.transform.warp", json!({"mesh": {"us": [0, 1], "vs": [0, 1], "points": [[0, 0]]}})).is_err()); +} + +#[test] +fn custom_mesh_moves_a_control_point() { + let mut s = session(16); + let mut m = BezierMesh::identity([10.0, 10.0, 60.0, 40.0], 1, 1); + m.points[15] = [70.0, 50.0]; // bottom-right corner + s.execute("edit.transform.warp", json!({"mesh": m})).unwrap(); + let b = active_surface(&s).content_bounds(); + assert!(b.x1 >= 69 && b.y1 >= 49, "{b:?}"); +} + +#[test] +fn split_cuts_existing_sections_instead_of_replacing_the_grid() { + let b = [0.0, 0.0, 90.0, 60.0]; + let plain = Warp::custom(BezierMesh::identity(b, 1, 1), b); + let cut = split_warp(&plain, Some([b[0] + 0.25 * 90.0, 30.0]), Split::Vertical).unwrap(); + let m = cut.mesh.unwrap(); + for u in [0.0, 0.25, 1.0 / 3.0, 2.0 / 3.0, 1.0] { + assert!(m.us.iter().any(|k| (k - u).abs() < 1e-6), "default guides stay, cut at 0.25: {:?}", m.us); + } + assert_eq!(m.vs, vec![0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]); + let grid = BezierMesh::identity(b, 3, 3); + let cut = split_warp(&Warp::custom(grid.clone(), b), Some([45.0, 10.0]), Split::Vertical).unwrap(); + let m = cut.mesh.unwrap(); + assert_eq!(m.vs, grid.vs); + assert_eq!(m.us.len(), grid.us.len() + 1); + for u in [0.0, 1.0 / 3.0, 0.5, 2.0 / 3.0, 1.0] { + assert!(m.us.iter().any(|k| (k - u).abs() < 1e-6), "{:?}", m.us); + } + let (nx0, nx1) = (grid.nx(), m.nx()); + for j in 0..grid.ny() { + for i in 0..3 { + assert_eq!(m.points[j * nx1 + i], grid.points[j * nx0 + i]); + } + } +} + +#[test] +fn split_commands_edit_meshes_exactly() { + let mut s = session(8); + let w = Warp::preset(WarpStyle::Bulge, 30.0, [10.0, 10.0, 60.0, 40.0]); + let r = s.execute("edit.transform.splitWarpCrosswise", json!({"warp": w, "at": [30.0, 20.0]})).unwrap(); + let split: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); + let m = split.mesh.as_ref().unwrap(); + assert_eq!((m.nx(), m.ny()), (7, 7)); + let r = s.execute("edit.transform.splitWarpVertically", json!({"warp": split})).unwrap(); + let v: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); + assert_eq!(v.mesh.as_ref().unwrap().us.len(), 4); + let r = s.execute("edit.transform.removeWarpSplit", json!({"warp": v, "at": [30.0, 20.0]})).unwrap(); + let back: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); + assert!(back.mesh.as_ref().unwrap().us.len() + back.mesh.as_ref().unwrap().vs.len() < 7); + // Splitting never changes the shape. + for (x, y) in [(15.0, 15.0), (40.0, 33.0)] { + let (a, b) = (w.map(x, y), split.map(x, y)); + assert!((a.0 - b.0).abs() < 0.6 && (a.1 - b.1).abs() < 0.6, "{a:?} {b:?}"); + } +} + +#[test] +fn smart_object_warp_is_lossless() { + for depth in [8u64, 16, 32] { + let mut s = session(depth); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let original = active_surface(&s); + s.execute("layer.smartObjects.warp", json!({"style": "wave", "bend": 60})).unwrap(); + let warped = active_surface(&s); + assert_ne!(warped, original); + let st = s.active().unwrap(); + let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!() }; + assert!(sm.warp.is_some()); + // Removing the warp re-renders the source exactly (no accumulated resampling). + s.execute("layer.smartObjects.warp", json!({"style": "none"})).unwrap(); + assert_eq!(active_surface(&s), original, "{depth}"); + // Warping twice equals warping once with the second warp. + s.execute("layer.smartObjects.warp", json!({"style": "arc", "bend": 20})).unwrap(); + s.execute("layer.smartObjects.warp", json!({"style": "wave", "bend": 60})).unwrap(); + assert_eq!(active_surface(&s), warped, "{depth}"); + // Split on the stored warp keeps the appearance (within resampling of the mesh fit). + s.execute("edit.transform.splitWarpCrosswise", json!({})).unwrap(); + let st = s.active().unwrap(); + let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!() }; + assert_eq!(sm.warp.as_ref().unwrap().style, WarpStyle::Custom); + } +} + +#[test] +fn crosswise_split_of_an_identity_custom_warp_is_four_by_four() { + let mut s = session(8); + let r = s.execute("edit.transform.splitWarpCrosswise", json!({"style": "custom", "rect": [0.0, 0.0, 90.0, 60.0]})).unwrap(); + let out: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); + let m = out.mesh.unwrap(); + assert_eq!((m.us.len(), m.vs.len()), (5, 5), "thirds, then the centre cut: {:?}", (m.us.clone(), m.vs.clone())); + for u in [0.0, 1.0 / 3.0, 0.5, 2.0 / 3.0, 1.0] { + assert!(m.us.iter().any(|k| (k - u).abs() < 1e-6), "{:?}", m.us); + assert!(m.vs.iter().any(|k| (k - u).abs() < 1e-6), "{:?}", m.vs); + } +} + +#[test] +fn extreme_rect_is_bad_params_not_a_giant_warp() { + let mut s = session(8); + for cmd in ["edit.transform.warp", "layer.smartObjects.warp"] { + if cmd == "layer.smartObjects.warp" { + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + } + let e = s.execute(cmd, json!({"style": "arc", "bend": 50, "rect": [-1e30, -1e30, 1e30, 1e30]})).unwrap_err(); + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg.contains("rect too large")), "{cmd}: {e}"); + } + s.execute("layer.smartObjects.warp", json!({"style": "arc", "bend": 50, "rect": [10, 10, 60, 40]})).unwrap(); +} + +#[test] +fn warp_grid_fits_the_surface_and_rejects_bad_sizes() { + let mut s = session(8); + assert!(s.execute("edit.transform.warpGrid", json!({})).is_err()); + assert!(s.execute("edit.transform.warpGrid", json!({"size": 0})).is_err()); + assert!(s.execute("edit.transform.warpGrid", json!({"size": -3})).is_err()); + assert!(s.execute("edit.transform.warpGrid", json!({"size": 65})).is_err()); + assert!(s.execute("edit.transform.warpGrid", json!({"size": 1.5})).is_err()); + assert!(s.execute("edit.transform.warpGrid", json!({"size": "custom"})).is_err()); + assert!(s.execute("edit.transform.warpGrid", json!({"size": "nope"})).is_err()); + assert!(s.execute("edit.transform.warpGrid", json!({"grid": [3, 3]})).is_err()); + let b = [10.0, 10.0, 60.0, 40.0]; + let mut bent = BezierMesh::identity(b, 1, 1); + bent.points[0][0] += 12.0; + let r = s.execute("edit.transform.warpGrid", json!({"warp": Warp::custom(bent.clone(), b), "size": 4})).unwrap(); + let out: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); + let m = out.mesh.unwrap(); + assert_eq!(out.style, WarpStyle::Custom); + assert_eq!(m.us, vec![0.0, 0.25, 0.5, 0.75, 1.0]); + assert_eq!(m.vs, m.us); + assert!((m.eval(0.0, 0.0)[0] - bent.eval(0.0, 0.0)[0]).abs() < 1e-3); + assert!((m.eval(1.0, 1.0)[0] - b[2]).abs() < 1e-3); + let r = s.execute("edit.transform.warpGrid", json!({"warp": Warp::custom(m, b), "size": "default"})).unwrap(); + let back: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); + assert_eq!(back.mesh.unwrap().us.len(), 2); +} + +/// A selection limits the warp of a linked mask too, as it does the pixels (#4175; Free +/// Transform and Perspective Warp did this already, #3083): the moved part of the mask lines +/// up with the moved pixels and the unselected part stays put. +#[test] +fn linked_mask_with_a_selection_warps_only_the_selected_region() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 20), &[1.0, 0.0, 0.0, 1.0]); + // Hide the left quarter (selected) and the right quarter (not selected). + let m = l.mask.as_mut().unwrap(); + m.surface.fill_rect(Rect::new(10, 10, 15, 20), &[0.0]); + m.surface.fill_rect(Rect::new(25, 10, 30, 20), &[0.0]); + m.linked = true; + Ok(()) + }) + .unwrap(); + let mask_at = |s: &Session, x, y| { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0) + }; + let alpha_at = |s: &Session, x, y| { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)[3] + }; + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + // A mesh that translates the selected box 50 px down. + let b = [10.0, 10.0, 20.0, 20.0]; + let mesh = BezierMesh::identity(b, 1, 1).map_points(|p| [p[0], p[1] + 50.0]); + s.execute("edit.transform.warp", json!({"rect": [10, 10, 20, 20], "mesh": mesh})).unwrap(); + // Moved pixels and their mask line up. + assert!(alpha_at(&s, 12, 65) > 0.99); + assert!(mask_at(&s, 12, 65) < 0.01, "selected hidden quarter moved"); + assert!(mask_at(&s, 17, 65) > 0.99, "selected visible quarter moved"); + // The vacated area reads as revealed, with transparent pixels. + assert!(alpha_at(&s, 12, 15) < 0.01); + assert!(mask_at(&s, 12, 15) > 0.99); + // The unselected part of the mask stays, aligned with the unselected pixels. + assert!(alpha_at(&s, 27, 15) > 0.99); + assert!(mask_at(&s, 27, 15) < 0.01, "unselected mask stays put"); + assert!(mask_at(&s, 27, 65) > 0.99, "and isn't copied along"); + for (x, y) in [(11, 61), (13, 68), (16, 61), (18, 68)] { + let want = if x < 15 { 0.0 } else { 1.0 }; + assert!((mask_at(&s, x, y) - want).abs() < 0.01, "({x},{y}): {}", mask_at(&s, x, y)); + } +} + +/// Esc stops the warp of a selected linked mask too, not only of the pixels. A fill layer has +/// no pixels to warp, so the mask is the only part that can see the cancel. +#[test] +fn a_cancelled_warp_stops_in_a_selected_linked_mask() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("layer.newFillLayer.solidColor", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.edit("link", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().mask.as_mut().unwrap().linked = true; + Ok(()) + }) + .unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + let st = s.active().unwrap(); + let (sel, mut l) = (st.doc.selection.clone().unwrap(), st.doc.layer(st.active_layer.unwrap()).unwrap().clone()); + let rect = Rect::new(10, 10, 20, 20); + let w = Warp::preset(WarpStyle::Flag, 35.0, rect_f(rect)); + let ctl = Interrupt::cancel_only(&|| true); + let r = warp_layer(Some(&sel), Locks::default(), &mut l, &w, rect, Interp::Bicubic, None, &ctl); + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); +} From 50e27b0f41a93cddf18a41e125d21ab45322545f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:18 +0000 Subject: [PATCH 039/259] refactor(engine): move actions_cmds.rs tests to actions_cmds/tests.rs --- crates/engine/src/actions_cmds.rs | 1048 +---------------------- crates/engine/src/actions_cmds/tests.rs | 1045 ++++++++++++++++++++++ 2 files changed, 1046 insertions(+), 1047 deletions(-) create mode 100644 crates/engine/src/actions_cmds/tests.rs diff --git a/crates/engine/src/actions_cmds.rs b/crates/engine/src/actions_cmds.rs index 7f9b52ff85..4dcb8bb8b9 100644 --- a/crates/engine/src/actions_cmds.rs +++ b/crates/engine/src/actions_cmds.rs @@ -780,1053 +780,7 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn pixel(s: &Session, layer: usize, x: i32, y: i32) -> Vec { - s.active().unwrap().doc.layers[layer].surface().unwrap().pixel(x, y) - } - - #[test] - fn deselect_with_nothing_selected_is_a_noop_in_playback() { - // #6744: imported actions often start with Deselect; with no selection Photoshop plays on. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - let before = s.active().unwrap().history.past_len(); - // Outside playback the command stays disabled, like Photoshop's greyed menu item. - assert!(s.execute("select.deselect", json!({})).is_err()); - assert!(s.active().unwrap().doc.selection.is_none()); - assert_eq!(s.active().unwrap().history.past_len(), before, "rejection adds no history step"); - let deselect = crate::commands::find("select.deselect").unwrap(); - assert_eq!((deselect.run)(&mut s, &json!({})).unwrap(), Value::Null); - assert_eq!(s.active().unwrap().history.past_len(), before, "no history step"); - - let steps = vec![("select.deselect".to_string(), json!({})), ("layer.new.layer".to_string(), json!({"name": "A"}))]; - s.actions.list.push(Action::new("Clear", steps)); - let played = s.execute("actions.play", json!({"action": 0})).unwrap(); - assert_eq!(played["ran"], 2, "{played}"); - assert_eq!(s.active().unwrap().doc.layers.last().unwrap().name, "A"); - } - - #[test] - fn unchecked_steps_are_skipped_and_follow_move_and_delete() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - let step = |name: &str| ("layer.new.layer".to_string(), json!({"name": name})); - s.actions.list.push(Action::new("Three", vec![step("A"), step("B"), step("C")])); - let names = |s: &Session| s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.clone()).collect::>(); - - assert_eq!(s.execute("actions.toggle", json!({"action": "Three", "step": 1})).unwrap()["disabled"], json!([1])); - let played = s.execute("actions.play", json!({"action": 0})).unwrap(); - assert_eq!(played["ran"], 2); - assert_eq!(names(&s), ["A", "C"], "the unchecked step is skipped"); - assert_eq!(s.execute("actions.get", json!({"action": 0})).unwrap()["disabled"], json!([1])); - - // Moving step 3 to the top keeps B (now step 2) unchecked; deleting the moved step shifts it to 1. - s.execute("actions.move", json!({"action": 0, "step": 2, "to": 0})).unwrap(); - let ids: Vec<_> = s.actions.list[0].steps.iter().map(|(_, p)| p["name"].as_str().unwrap()).collect(); - assert_eq!((ids, s.actions.list[0].disabled.iter().copied().collect::>()), (vec!["C", "A", "B"], vec![2])); - s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); - assert_eq!(s.actions.list[0].steps, [step("A"), step("B")], "deleting removes only that step"); - assert_eq!(s.actions.list[0].disabled.iter().copied().collect::>(), [1]); - - // The action's own check: all on unless all already are. - s.execute("actions.toggle", json!({"action": 0})).unwrap(); - assert!(s.actions.list[0].disabled.is_empty()); - s.execute("actions.toggle", json!({"action": 0})).unwrap(); - assert_eq!(s.actions.list[0].disabled.len(), 2); - s.execute("actions.toggle", json!({"action": 0, "step": 0, "enabled": true})).unwrap(); - assert_eq!(s.actions.list[0].disabled.iter().copied().collect::>(), [1]); - - for bad in [ - json!({"action": 0, "step": 2}), - json!({"action": 0, "step": -1}), - json!({"action": 0, "step": "x"}), - json!({"action": 0, "step": 0, "enabled": "yes"}), - json!({"action": 7, "step": 0}), - json!({}), - ] { - assert!(s.execute("actions.toggle", bad.clone()).is_err(), "{bad}"); - } - assert_eq!(s.actions.list[0].disabled.iter().copied().collect::>(), [1], "rejected toggles change nothing"); - } - - #[test] - fn rename_keeps_calls_and_function_key_and_rejects_bad_names() { - let mut s = Session::new(); - s.actions.list.push(Action { - name: "Action 1".into(), - steps: vec![("layer.new.layer".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - s.actions.list.push(Action { - name: "Caller".into(), - steps: vec![("actions.play".into(), json!({"action": "Action 1"}))], - disabled: Default::default(), - ..Default::default() - }); - s.edit_prefs(|p| p.shortcuts.insert(format!("{PLAY_SHORTCUT_PREFIX}Action 1"), "F2".into())); - assert_eq!(s.execute("actions.rename", json!({"action": 0, "name": "Sepia"})).unwrap()["action"], "Sepia"); - assert_eq!(s.execute("actions.list", json!({})).unwrap()["actions"][0]["name"], "Sepia"); - assert_eq!(s.actions.list[1].steps[0].1["action"], "Sepia"); - assert_eq!(s.prefs().shortcuts.get("actions.play:Sepia").map(String::as_str), Some("F2")); - assert!(!s.prefs().shortcuts.contains_key("actions.play:Action 1")); - for bad in [ - json!({"action": 0, "name": ""}), - json!({"action": 0, "name": " "}), - json!({"action": 0, "name": "Caller"}), - json!({"action": 0, "name": 7}), - json!({"action": 9, "name": "X"}), - json!({"action": 0}), - ] { - assert!(s.execute("actions.rename", bad.clone()).is_err(), "{bad}"); - } - assert_eq!(s.actions.list[0].name, "Sepia"); - } - - #[test] - fn rename_follows_conditional_branches() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - for name in ["B", "Other"] { - s.actions.list.push(Action { name: name.into(), steps: vec![("layer.new.layer".into(), json!({}))], ..Default::default() }); - } - s.actions.list.push(Action { - name: "Main".into(), - steps: vec![ - ("actions.conditional".into(), json!({"if": "always", "then": "B", "else": "Other"})), - ("actions.conditional".into(), json!({"if": "never", "then": "Other", "else": "B"})), - ], - ..Default::default() - }); - s.execute("actions.rename", json!({"action": "B", "name": "C"})).unwrap(); - let steps = &s.actions.list[2].steps; - assert_eq!(steps[0].1, json!({"if": "always", "then": "C", "else": "Other"})); - assert_eq!(steps[1].1, json!({"if": "never", "then": "Other", "else": "C"})); - let r = s.execute("actions.play", json!({"action": "Main"})).unwrap(); - assert!(r.get("failed").is_none(), "{r}"); - } - - #[test] - fn delete_action_drops_its_function_key_but_deleting_a_step_keeps_it() { - let mut s = Session::new(); - let key = format!("{PLAY_SHORTCUT_PREFIX}Action 1"); - s.actions.list.push(Action::new("Action 1", vec![("layer.new.layer".into(), json!({})), ("layer.new.layer".into(), json!({}))])); - s.edit_prefs(|p| p.shortcuts.insert(key.clone(), "F2".into())); - s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); - assert_eq!(s.prefs().shortcuts.get(&key).map(String::as_str), Some("F2"), "deleting a step keeps the key"); - assert_eq!(s.execute("actions.delete", json!({"action": 0})).unwrap()["deleted"], "Action 1"); - assert!(!s.prefs().shortcuts.contains_key(&key), "the deleted action's function key is gone"); - s.execute("actions.record", json!({})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].name, "Action 1"); - assert!(!s.prefs().shortcuts.contains_key(&key), "a new action with the same name starts unbound"); - } - - fn record_red(s: &mut Session, depth: u32) { - s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth})).unwrap(); - s.execute("actions.record", json!({"name": "Red"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - let _ = s.execute("document.pixel", json!({"x": 1, "y": 1})); - let _ = s.execute("actions.list", json!({})); - s.execute("actions.stop", json!({})).unwrap(); - } - - fn translated_square(s: &mut Session, depth: u32) { - s.execute("file.new", json!({"width": 20, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); - s.edit("red square", |doc, _| { - doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 2, 2, 4), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 4, 0], "interpolation": "nearest"})).unwrap(); - assert_eq!(pixel(s, 0, 4, 2), vec![1.0, 0.0, 0.0, 1.0]); - } - - #[test] - fn record_transform_again_replays_one_concrete_transform_at_each_depth() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - translated_square(&mut s, depth); - let from = s.journal.len(); - s.execute("actions.record", json!({"name": "Again"})).unwrap(); - s.execute("edit.transform.again", json!({})).unwrap(); - let ids: Vec<&str> = s.journal.iter().skip(from).map(|(id, _)| id.as_str()).collect(); - assert_eq!(ids, ["edit.transform", "edit.transform.again"], "both commands stay in the journal during recording"); - let live_count = s.journal.iter().skip(from).filter(|(id, _)| replayable(id)).count(); - s.execute("actions.stop", json!({})).unwrap(); - let recorded = s.execute("actions.get", json!({"action": "Again"})).unwrap(); - let steps = recorded["steps"].as_array().unwrap(); - assert_eq!(steps.len(), 1, "depth {depth}: record the concrete transform once"); - assert_eq!(live_count, 1, "depth {depth}: the live Actions count agrees"); - assert_eq!(steps[0][0], "edit.transform"); - assert_eq!(steps[0][1]["matrix"], json!([1, 0, 0, 1, 4, 0])); - assert_eq!(steps[0][1]["interpolation"], "nearest"); - - translated_square(&mut s, depth); - let before = s.active().unwrap().history.past_len(); - let played = s.execute("actions.play", json!({"action": "Again"})).unwrap(); - assert!(played.get("failed").is_none(), "depth {depth}: {played}"); - assert_eq!(played["ran"], 1, "depth {depth}: apply the recorded transform once"); - assert_eq!(s.active().unwrap().history.past_len(), before + 1, "depth {depth}: one undo step"); - assert_eq!(pixel(&s, 0, 8, 2), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}: moved four pixels"); - assert_eq!(pixel(&s, 0, 12, 2), vec![0.0; 4], "depth {depth}: no second transform"); - assert!(s.undo()); - assert_eq!(pixel(&s, 0, 4, 2), vec![1.0, 0.0, 0.0, 1.0]); - assert_eq!(pixel(&s, 0, 8, 2), vec![0.0; 4]); - assert!(s.redo()); - assert_eq!(pixel(&s, 0, 8, 2), vec![1.0, 0.0, 0.0, 1.0]); - assert_eq!(pixel(&s, 0, 4, 2), vec![0.0; 4]); - } - } - - #[test] - fn record_transform_again_on_a_copy_replays_in_a_session_without_a_transform() { - for depth in [8, 16] { - let mut s = Session::new(); - translated_square(&mut s, depth); - s.execute("actions.record", json!({"name": "Step"})).unwrap(); - s.execute("edit.transform.againCopy", json!({})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - let got = s.execute("actions.get", json!({"action": "Step"})).unwrap(); - let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect(); - assert_eq!(ids, ["layer.duplicate", "edit.transform"], "depth {depth}: the concrete steps, not the wrapper"); - let action = s.actions.list[0].clone(); - - // A new session has no transform to repeat: the concrete steps still play. - let mut fresh = Session::new(); - fresh.execute("file.new", json!({"width": 20, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); - fresh - .edit("red square", |doc, _| { - doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(4, 2, 6, 4), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - fresh.actions.list.push(action); - let played = fresh.execute("actions.play", json!({"action": "Step"})).unwrap(); - assert!(played.get("failed").is_none(), "depth {depth}: {played}"); - assert_eq!(played["ran"], 2, "depth {depth}"); - assert_eq!(fresh.active().unwrap().doc.layers.len(), 2, "depth {depth}: one copy"); - assert_eq!(pixel(&fresh, 0, 4, 2), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}: the original stays"); - assert_eq!(pixel(&fresh, 1, 8, 2), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}: the copy moved four pixels"); - assert_eq!(pixel(&fresh, 1, 4, 2), vec![0.0; 4], "depth {depth}: moved once"); - } - } - - #[test] - fn record_drops_the_steps_of_a_command_that_failed_and_was_taken_back() { - // Transform Again on a Copy of a position-locked layer duplicates it, fails to move the - // copy and takes the copy back: nothing is left to record. - let mut s = Session::new(); - translated_square(&mut s, 8); - let id = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.setProps", json!({"layer": id.0, "locks": {"position": true}})).unwrap(); - s.execute("actions.record", json!({"name": "Locked"})).unwrap(); - assert!(s.execute("edit.transform.againCopy", json!({})).is_err()); - 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); - 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_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"); - } - - #[test] - fn record_script_that_plays_an_action_keeps_each_step_once() { - let mut s = Session::new(); - translated_square(&mut s, 8); - s.execute("actions.record", json!({"name": "Inner"})).unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 1, 0], "interpolation": "nearest"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - - // Browse records the concrete steps it ran, not itself (#3057): the script's transform and - // the action call, each once, in order. - let script = json!({"steps": [["edit.transform", {"matrix": [1, 0, 0, 1, 2, 0], "interpolation": "nearest"}], ["actions.play", {"action": "Inner"}]]}); - s.execute("actions.record", json!({"name": "Outer"})).unwrap(); - s.execute("file.scripts.browse", script.clone()).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - let got = s.execute("actions.get", json!({"action": "Outer"})).unwrap(); - assert_eq!(got["steps"], script["steps"]); - } - - #[test] - fn record_explicit_transform_keeps_one_replayable_step() { - let mut s = Session::new(); - translated_square(&mut s, 8); - s.execute("actions.record", json!({"name": "Move"})).unwrap(); - s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 4, 0], "interpolation": "nearest"})).unwrap(); - assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 1); - let recorded = s.execute("actions.get", json!({"action": "Move"})).unwrap(); - assert_eq!(recorded["steps"][0][0], "edit.transform"); - - translated_square(&mut s, 8); - let before = s.active().unwrap().history.past_len(); - let played = s.execute("actions.play", json!({"action": "Move"})).unwrap(); - assert!(played.get("failed").is_none(), "{played}"); - assert_eq!(played["ran"], 1); - assert_eq!(s.active().unwrap().history.past_len(), before + 1); - assert_eq!(pixel(&s, 0, 8, 2), vec![1.0, 0.0, 0.0, 1.0]); - assert_eq!(pixel(&s, 0, 12, 2), vec![0.0; 4]); - } - - /// A Background with a red bar and a slanted ruler line, ready for Straighten. - fn ruled_background(s: &mut Session, depth: u32) { - s.execute("file.new", json!({"width": 80, "height": 60, "depth": depth})).unwrap(); - s.edit("red bar", |doc, _| { - doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 20, 60, 8), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .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); - 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(); - 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); - 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}"); - assert_eq!(played["ran"], 2, "depth {depth}"); - assert_eq!(s.active().unwrap().history.past_len(), before + 1, "depth {depth}: one Straighten step (the ruler is no step)"); - let replayed = s.active().unwrap().doc.clone(); - assert_eq!(replayed.size, direct.size, "depth {depth}: rotated and cropped once"); - let r = photocraft_geom::Rect::new(0, 0, direct.size.width as i32, direct.size.height as i32); - let px = |d: &photocraft_doc::Document| d.layers[0].surface().unwrap().read_region(r); - assert_eq!(px(&replayed), px(&direct), "depth {depth}: same pixels as the direct run"); - } - } - - #[test] - fn record_keeps_only_replayable_steps() { - let mut s = Session::new(); - record_red(&mut s, 8); - let got = s.execute("actions.get", json!({"action": "Red"})).unwrap(); - let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect(); - assert_eq!(ids, ["layer.new.layer", "select.rect", "edit.fill"]); - assert!(s.journal.iter().all(|(id, _)| !id.starts_with("actions."))); - let listed = s.execute("actions.list", json!({})).unwrap(); - assert_eq!(listed["actions"][0]["steps"], 3); - assert!(listed["recording"].is_null()); - } - - #[test] - fn play_on_another_document_matches_pixels_at_each_depth() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - record_red(&mut s, depth); - s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth})).unwrap(); - let before = s.active().unwrap().history.past_len(); - let r = s.execute("actions.play", json!({"action": 0})).unwrap(); - assert!(r.get("failed").is_none(), "depth {depth}: {r}"); - assert_eq!(r["ran"], 3, "depth {depth}"); - assert_eq!(s.active().unwrap().doc.layers.len(), 2, "depth {depth}"); - assert_eq!(s.active().unwrap().history.past_len(), before + 3, "depth {depth}: one history step per played step"); - let px = pixel(&s, 1, 5, 5); - assert!(px.iter().zip([1.0, 0.0, 0.0, 1.0]).all(|(a, b)| (a - b).abs() < 1.0e-5), "depth {depth}: {px:?}"); - assert_eq!(s.actions.playing, 0); - } - } - - #[test] - fn recorded_layer_selection_replays_by_name_on_another_document() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); - let original = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.setProps", json!({"name": "Photo"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "LogoBase"})).unwrap(); - s.execute("actions.record", json!({"name": "Duplicate photo"})).unwrap(); - s.execute("layer.select", json!({"layer": original.0, "mode": "replace"})).unwrap(); - // The target name must be captured now, not when recording stops. - s.execute("layer.setProps", json!({"name": "Retouched"})).unwrap(); - s.execute("layer.duplicate", json!({})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps[0].1, json!({"name":"Photo", "mode":"replace"})); - // Persisted actions must work in an entirely different session too. - let saved = serde_json::to_string(&s.actions.list).unwrap(); - let mut replay = Session::new(); - replay.actions.list = serde_json::from_str(&saved).unwrap(); - replay.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); - replay.execute("layer.setProps", json!({"name": "Photo"})).unwrap(); - let target = replay.active().unwrap().active_layer.unwrap(); - assert_ne!(original, target); - replay.execute("layer.new.layer", json!({"name": "LogoBase"})).unwrap(); - let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); - assert!(result.get("failed").is_none(), "{result}"); - assert_eq!(result["ran"], 3); - assert_eq!(replay.active().unwrap().doc.layer(target).unwrap().name, "Retouched"); - let active = replay.active().unwrap().active_layer.unwrap(); - assert_eq!(replay.active().unwrap().doc.layer(active).unwrap().name, "Retouched copy"); - } - } - - /// #7845: dragging a layer in the Layers panel while recording keeps the drop target by name, - /// so the action plays on another document (whose layer ids differ) instead of failing with - /// "no such layer". The reporter's steps, replayed on a new document. - #[test] - fn recorded_layer_drag_replays_on_another_document() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap(); - s.execute("actions.record", json!({"name": "Retouch"})).unwrap(); - s.execute("layer.stampVisible", json!({})).unwrap(); - let layer1 = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layerViaCopy", json!({})).unwrap(); - let layer2 = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.select", json!({"layer": layer1.0, "mode": "replace"})).unwrap(); - s.execute("filter.noise.median", json!({"radius": 6})).unwrap(); - s.execute("layer.new.layerViaCopy", json!({})).unwrap(); - let copy = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.moveTo", json!({"layer": copy.0, "target": layer2.0, "position": "above"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - let (id, step) = s.actions.list[0].steps.last().unwrap(); - assert_eq!((id.as_str(), step), ("layer.moveTo", &json!({"target": "Layer 1 copy", "position": "above"}))); - let names = |s: &Session| s.active().unwrap().doc.layers.iter().rev().map(|l| l.name.clone()).collect::>(); - let recorded = names(&s); - let saved = serde_json::to_string(&s.actions.list).unwrap(); - let mut replay = Session::new(); - replay.actions.list = serde_json::from_str(&saved).unwrap(); - replay.execute("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap(); - let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); - assert!(result.get("failed").is_none(), "{depth}: {result}"); - assert_eq!(names(&replay), recorded, "{depth}: the same stack"); - } - // Several layers of the drop target's name: the recorded occurrence picks the right one. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); - let upper = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "Mover"})).unwrap(); - let mover = s.active().unwrap().active_layer.unwrap(); - s.execute("actions.record", json!({"name": "Drop"})).unwrap(); - s.execute("layer.moveTo", json!({"layer": mover.0, "target": upper.0, "position": "below"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps[0].1, json!({"target": "Twin", "targetOccurrence": 1, "position": "below"})); - // The moved layer shares the target's name: the occurrence counts the other "Twin"s only, - // so it means the same layer before the move (on replay) as after it (when recorded). - let build = |s: &mut Session| { - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - for _ in 0..3 { - s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); - } - s.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>() - }; - let mut s = Session::new(); - let ids = build(&mut s); - let (lowest, top) = (ids[1], ids[3]); - s.execute("actions.record", json!({"name": "Twins"})).unwrap(); - s.execute("layer.moveTo", json!({"layer": top.0, "target": lowest.0, "position": "below"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps[0].1, json!({"target": "Twin", "targetOccurrence": 0, "position": "below"})); - let order = |s: &Session| s.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); - let want: Vec<_> = order(&s).iter().map(|id| ids.iter().position(|x| x == id).unwrap()).collect(); - let saved = serde_json::to_string(&s.actions.list).unwrap(); - let mut replay = Session::new(); - replay.actions.list = serde_json::from_str(&saved).unwrap(); - let ids2 = build(&mut replay); - let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); - assert!(result.get("failed").is_none(), "{result}"); - let got: Vec<_> = order(&replay).iter().map(|id| ids2.iter().position(|x| x == id).unwrap()).collect(); - assert_eq!(got, want, "the same layer became the lowest"); - // A moved group holding a same-named layer: its contents don't count either, or moving the - // group past another "Twin" would shift the occurrence between recording and replay. - let build_group = |s: &mut Session| { - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); - s.execute("layer.groupLayers", json!({})).unwrap(); - let group = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); - let top = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.select", json!({"layer": group.0, "mode": "replace"})).unwrap(); - (group, top) - }; - let mut g = Session::new(); - let (group, top) = build_group(&mut g); - g.execute("actions.record", json!({"name": "Group"})).unwrap(); - g.execute("layer.moveTo", json!({"layer": group.0, "target": top.0, "position": "above"})).unwrap(); - g.execute("actions.stop", json!({})).unwrap(); - let recorded = g.actions.list[0].steps[0].1.clone(); - let saved = serde_json::to_string(&g.actions.list).unwrap(); - let mut replay = Session::new(); - replay.actions.list = serde_json::from_str(&saved).unwrap(); - let (group2, _) = build_group(&mut replay); - let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); - assert!(result.get("failed").is_none(), "{recorded}: {result}"); - let top_layer = |s: &Session| s.active().unwrap().doc.layers.last().map(|l| l.id); - assert_eq!(top_layer(&replay), Some(group2), "{recorded}: the group went to the top"); - // Several moved layers named like the target are left out too, so the name is unambiguous. - let mut m = Session::new(); - m.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - let a = photocraft_doc::LayerId(m.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); - let b = photocraft_doc::LayerId(m.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); - let target = photocraft_doc::LayerId(m.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); - m.execute("layer.moveTo", json!({"layers": [a.0, b.0], "target": "Twin", "position": "above"})).unwrap(); - assert_eq!(m.active().unwrap().doc.layers.last().map(|l| l.id), Some(b), "both moved above the third Twin"); - assert_eq!(m.active().unwrap().doc.layers.iter().rev().nth(2).map(|l| l.id), Some(target)); - // An ⌥-drag copy of the selected layer beside itself replays by name too. - let mut c = Session::new(); - c.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - let src = photocraft_doc::LayerId(c.execute("layer.new.layer", json!({"name": "Solo"})).unwrap()["layer"].as_u64().unwrap()); - c.execute("actions.record", json!({"name": "Copy"})).unwrap(); - c.execute("layer.moveTo", json!({"layer": src.0, "target": src.0, "position": "above", "copy": true})).unwrap(); - c.execute("actions.stop", json!({})).unwrap(); - assert_eq!(c.actions.list[0].steps[0].1, json!({"target": "Solo", "position": "above", "copy": true})); - let saved = serde_json::to_string(&c.actions.list).unwrap(); - let mut replay = Session::new(); - replay.actions.list = serde_json::from_str(&saved).unwrap(); - replay.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - replay.execute("layer.new.layer", json!({"name": "Solo"})).unwrap(); - let before = replay.active().unwrap().doc.layers.len(); - let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); - assert!(result.get("failed").is_none(), "{result}"); - assert_eq!(replay.active().unwrap().doc.layers.len(), before + 1, "one copy"); - // Copying a group holding a layer named like the target: the new copy's contents (made - // before the step is recorded) don't count, so the occurrence matches the replay. - let build_copy = |s: &mut Session| { - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); - s.execute("layer.groupLayers", json!({})).unwrap(); - let group = s.active().unwrap().active_layer.unwrap(); - let a = photocraft_doc::LayerId(s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); - let b = photocraft_doc::LayerId(s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); - s.execute("layer.select", json!({"layer": group.0, "mode": "replace"})).unwrap(); - (group, a, b) - }; - let mut gc = Session::new(); - let (group, a, _) = build_copy(&mut gc); - gc.execute("actions.record", json!({"name": "Copy group"})).unwrap(); - // Below `a`: the copy's "Twin" then comes before `a` in document order. - gc.execute("layer.moveTo", json!({"layer": group.0, "target": a.0, "position": "below", "copy": true})).unwrap(); - gc.execute("actions.stop", json!({})).unwrap(); - let saved = serde_json::to_string(&gc.actions.list).unwrap(); - let mut replay = Session::new(); - replay.actions.list = serde_json::from_str(&saved).unwrap(); - let (_, a2, _) = build_copy(&mut replay); - let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); - assert!(result.get("failed").is_none(), "{result}"); - let layers = &replay.active().unwrap().doc.layers; - let at = layers.iter().position(|l| l.id == a2).unwrap(); - let below = at.checked_sub(1).and_then(|i| layers.get(i)).map(|l| l.name.as_str()); - assert_eq!(below, Some("Group 1 copy"), "the copy landed below the same Twin"); - // A drag of several layers keeps its ids (not covered by name). - s.execute("actions.record", json!({"name": "Several"})).unwrap(); - s.execute("layer.moveTo", json!({"layers": [ids[2].0, ids[3].0], "target": ids[1].0, "position": "above"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[1].steps[0].1["target"], json!(ids[1].0)); - // Bad targets are errors, not panics. - for bad in [ - json!({"target": "Nobody"}), - json!({"target": "Twin"}), - json!({"target": "Twin", "targetOccurrence": 9}), - json!({"target": "Twin", "targetOccurrence": -1}), - json!({"target": true}), - ] { - assert!(s.execute("layer.moveTo", bad.clone()).is_err(), "{bad}"); - } - } - - /// An Alt-drag copy records `inPlace` (#7200), which only matters for an artboard: a plain - /// layer's recorded copy must still export to .atn, while an artboard's must be refused rather - /// than exported as a copy beside the original. - #[test] - fn recorded_in_place_duplicate_keeps_in_place_only_for_artboards() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("actions.record", json!({"name": "Layer copy"})).unwrap(); - s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - s.execute("layer.new.artboard", json!({"name": "Board", "rect": [0, 0, 8, 8]})).unwrap(); - s.execute("actions.record", json!({"name": "Board copy"})).unwrap(); - s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps, vec![("layer.duplicate".to_string(), json!({}))]); - assert_eq!(s.actions.list[1].steps, vec![("layer.duplicate".to_string(), json!({"inPlace": true}))]); - assert!(crate::atn_cmds::export("Audit", &[&s.actions.list[0]], &[], false).is_ok()); - assert!(crate::atn_cmds::export("Audit", &[&s.actions.list[1]], &[], false).is_err()); - // Several selected layers are copied together: one artboard among them keeps `inPlace`. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - let photo = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({"name": "Logo"})).unwrap(); - s.execute("layer.select", json!({"layer": photo.0, "mode": "add"})).unwrap(); - s.execute("actions.record", json!({"name": "Layers copy"})).unwrap(); - s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.active().unwrap().selected_layers().len(), 2, "both layers were copied"); - s.execute("layer.new.artboard", json!({"name": "Board", "rect": [0, 0, 8, 8]})).unwrap(); - s.execute("layer.select", json!({"layer": photo.0, "mode": "add"})).unwrap(); - s.execute("actions.record", json!({"name": "Mixed copy"})).unwrap(); - s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps, vec![("layer.duplicate".to_string(), json!({}))]); - assert_eq!(s.actions.list[1].steps, vec![("layer.duplicate".to_string(), json!({"inPlace": true}))]); - } - - #[test] - fn named_selection_preserves_modes_and_duplicate_occurrences() { - let mut s = Session::new(); - s.execute("file.new", json!({"width":4,"height":4})).unwrap(); - s.execute("layer.setProps", json!({"name":"Photo"})).unwrap(); - let first = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.group", json!({"name":"Group"})).unwrap(); - // A duplicate nested in a group must be found even when that group is collapsed. - let second = s - .edit("child", |doc, active| { - let child = photocraft_doc::Layer::raster("Photo", doc.pixel_format()); - let id = child.id; - if let photocraft_doc::LayerContent::Group(group) = &mut doc.layer_mut(active.unwrap()).unwrap().content { - group.children.push(child); - group.expanded = false; - } - Ok(id) - }) - .unwrap(); - s.execute("actions.record", json!({"name":"Select duplicates"})).unwrap(); - s.execute("layer.select", json!({"layer":first.0})).unwrap(); - s.execute("layer.select", json!({"layer":second.0,"mode":"add"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps[0].1, json!({"name":"Photo","occurrence":0})); - assert_eq!(s.actions.list[0].steps[1].1, json!({"name":"Photo","occurrence":1,"mode":"add"})); - s.execute("layer.select", json!({"layer":first.0})).unwrap(); - let r = s.execute("actions.play", json!({"action":0})).unwrap(); - assert!(r.get("failed").is_none(), "{r}"); - assert_eq!(s.active().unwrap().selected_layers(), vec![first, second]); - s.execute("layer.select", json!({"name":"Photo","occurrence":1,"mode":"toggle"})).unwrap(); - assert_eq!(s.active().unwrap().selected_layers(), vec![first]); - s.execute("layer.select", json!({"name":"Photo","occurrence":1,"mode":"range"})).unwrap(); - assert!(s.active().unwrap().selected_layers().contains(&second)); - // Main's imported .atn steps use a string-valued `layer` and choose the topmost match. - s.execute("layer.select", json!({"layer":"Photo"})).unwrap(); - assert_eq!(s.active().unwrap().selected_layers(), vec![second]); - s.execute("layer.select", json!({"name":"Photo","occurrence":0,"mode":"add"})).unwrap(); - s.execute("layer.select", json!({"name":"Photo","occurrence":1,"mode":"remove"})).unwrap(); - assert_eq!(s.active().unwrap().selected_layers(), vec![first]); - // Removing an unselected layer does not add it; removing the last target keeps it. - s.execute("layer.select", json!({"layer":"Photo","mode":"remove"})).unwrap(); - s.execute("layer.select", json!({"name":"Photo","occurrence":0,"mode":"remove"})).unwrap(); - assert_eq!(s.active().unwrap().selected_layers(), vec![first]); - for p in [ - json!({"name":"absent"}), - json!({"name":"Photo"}), - json!({"name":1}), - json!({"name":"Photo","occurrence":-1}), - json!({"name":"Photo","occurrence":1.5}), - json!({"name":"Photo","occurrence":99}), - json!({"name":"Photo","layer":first.0}), - json!({"layer":first.0,"occurrence":0}), - ] { - let before = s.active().unwrap().selected_layers(); - assert!(s.execute("layer.select", p.clone()).is_err(), "{p}"); - assert_eq!(s.active().unwrap().selected_layers(), before); - } - s.actions.list.push(Action { - name: "Missing".into(), - steps: vec![("layer.select".into(), json!({"name":"absent"})), ("layer.duplicate".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - let before = s.active().unwrap().doc.walk().len(); - let result = s.execute("actions.play", json!({"action":"Missing"})).unwrap(); - assert_eq!(result["ran"], 0); - assert!(result["failed"]["error"].as_str().unwrap().contains("absent")); - assert_eq!(s.active().unwrap().doc.walk().len(), before); - } - - #[test] - fn play_stops_at_the_failing_step_and_reports_it() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); - s.execute("actions.record", json!({})).unwrap(); - s.execute("layer.new.layer", json!({"name": "One"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - s.actions.list[0].steps.push(("not.a.command".into(), json!({}))); - s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); - let r = s.execute("actions.play", json!({"action": "Action 1"})).unwrap(); - assert_eq!(r["ran"], 1); - assert_eq!(r["failed"]["step"], 1); - assert_eq!(r["failed"]["id"], "not.a.command"); - assert!(r["failed"]["error"].as_str().unwrap().contains("unknown command")); - assert_eq!(s.active().unwrap().doc.layers.len(), 2, "the step before the failure is kept"); - assert_eq!(s.actions.playing, 0); - // A later play still runs. - assert_eq!(s.execute("actions.play", json!({"action": 0, "from": 1})).unwrap()["ran"], 0); - } - - #[test] - fn play_refuses_recursion() { - let mut s = Session::new(); - s.actions.list.push(Action { - name: "Loop".into(), - steps: vec![("actions.play".into(), json!({"action": "Loop"}))], - disabled: Default::default(), - ..Default::default() - }); - let r = s.execute("actions.play", json!({"action": "Loop"})).unwrap(); - assert_eq!(r["ran"], 0); - assert_eq!(r["failed"]["id"], "actions.play"); - assert!(r["failed"]["error"].as_str().unwrap().contains("recursive action"), "{r}"); - assert_eq!(s.actions.playing, 0); - } - - #[test] - fn play_checks_each_step_with_the_authorize_hook() { - fn deny_file(id: &str, _: &Value) -> Result<()> { - if id.starts_with("file.") { Err(EngineError::Other(format!("automation command `{id}` is disabled"))) } else { Ok(()) } - } - let mut s = Session::new(); - s.authorize = Some(deny_file); - s.actions.list.push(Action { - name: "Open".into(), - steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - let r = s.execute("actions.play", json!({"action": "Open"})).unwrap(); - assert_eq!(r["ran"], 0); - assert_eq!(r["failed"]["step"], 0); - assert_eq!(r["failed"]["id"], "file.open"); - assert!(r["failed"]["error"].as_str().unwrap().contains("disabled"), "{r}"); - assert!(s.documents().is_empty(), "the refused step does not open a document"); - } - - #[test] - fn append_delete_and_from_step() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); - let started = s.execute("actions.record", json!({"name": "Grow"})).unwrap(); - assert_eq!(started["index"], 0); - s.execute("layer.new.layer", json!({"name": "One"})).unwrap(); - assert!(s.execute("actions.record", json!({})).is_err(), "already recording"); - assert!(s.execute("actions.delete", json!({"action": 0})).is_err(), "delete while recording"); - let stopped = s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(stopped["steps"], 1); - s.execute("actions.record", json!({"action": "Grow"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Two"})).unwrap(); - assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 2); - assert!(s.execute("actions.stop", json!({})).is_err(), "not recording"); - let before = s.active().unwrap().doc.layers.len(); - let r = s.execute("actions.play", json!({"action": "Grow", "from": 1})).unwrap(); - assert_eq!(r["ran"], 1); - assert_eq!(s.active().unwrap().doc.layers.len(), before + 1); - assert_eq!(s.execute("actions.delete", json!({"action": "Grow"})).unwrap()["deleted"], "Grow"); - assert!(s.actions.list.is_empty()); - assert!(s.execute("actions.get", json!({"action": "Grow"})).is_err()); - } - - #[test] - fn delete_one_step_while_recording_keeps_journal_and_remaining_steps() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("actions.record", json!({"name": "Edit"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Kept"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Removed"})).unwrap(); - let journal = s.journal.clone(); - let rev = s.actions.rev; - let before = s.actions.clone(); - for step in [json!(-1), json!(2), json!(0.5), json!(null), json!("0"), json!(u64::MAX)] { - assert!(s.execute("actions.delete", json!({"action": 0, "step": step})).is_err()); - assert_eq!(s.actions, before, "invalid deletion is atomic"); - } - assert_eq!(pending_steps(&s, 0).count(), 2); - let result = s.execute("actions.delete", json!({"action": 0, "step": 1})).unwrap(); - assert_eq!(result["steps"], 1); - assert_eq!(s.journal, journal, "deleting a recording does not erase executed commands"); - assert_eq!(s.active().unwrap().doc.layers.len(), 3, "it does not undo document edits"); - assert!(s.actions.recording.is_some()); - assert!(s.actions.rev > rev); - s.execute("layer.new.layer", json!({"name": "After"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps.iter().map(|(_, p)| p["name"].as_str().unwrap()).collect::>(), ["Kept", "After"]); - s.execute("actions.delete", json!({"action": "Edit", "step": 0})).unwrap(); - assert_eq!(s.actions.list[0].steps[0].1["name"], "After"); - let saved = serde_json::to_string(&s.actions.list).unwrap(); - s.actions.list = serde_json::from_str(&saved).unwrap(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - assert_eq!(s.execute("actions.play", json!({"action": 0})).unwrap()["ran"], 1); - assert_eq!(s.active().unwrap().doc.layers[1].name, "After"); - s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); - assert_eq!(s.actions.list.len(), 1, "an empty action still exists"); - assert!(s.actions.list[0].steps.is_empty()); - } - - #[test] - fn nested_call_records_one_named_step_and_tracks_child_edits() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); - s.actions.list.push(Action { - name: "Child".into(), - steps: vec![("layer.new.layer".into(), json!({"name": "Child layer"}))], - disabled: Default::default(), - ..Default::default() - }); - s.execute("actions.record", json!({"name": "Parent"})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Before"})).unwrap(); - s.execute("actions.play", json!({"action": 0})).unwrap(); - assert_eq!(pending_steps(&s, 1).cloned().collect::>(), [("actions.play".into(), json!({"action": "Child"}))]); - s.execute("layer.new.layer", json!({"name": "After"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[1].steps.iter().map(|st| st.0.as_str()).collect::>(), ["layer.new.layer", "actions.play", "layer.new.layer"]); - s.actions.list[0].steps.push(("layer.new.layer".into(), json!({"name": "Added later"}))); - s.execute("actions.move", json!({"action": "Child", "to": 1})).unwrap(); - let saved = serde_json::to_string(&s.actions.list).unwrap(); - s.actions.list = serde_json::from_str(&saved).unwrap(); - s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); - let result = s.execute("actions.play", json!({"action": "Parent"})).unwrap(); - assert!(result.get("failed").is_none(), "{result}"); - assert_eq!( - s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.as_str()).collect::>(), - ["Before", "Child layer", "Added later", "After"] - ); - assert!(s.actions.playback_stack.is_empty()); - } - - #[test] - fn nested_failure_cycles_depth_and_authorization_stop_parent() { - let mut s = Session::new(); - s.actions.list.push(Action { - name: "A".into(), - steps: vec![("actions.play".into(), json!({"action": "B"})), ("file.new".into(), json!({"width": 2,"height": 2}))], - disabled: Default::default(), - ..Default::default() - }); - s.actions.list.push(Action { - name: "B".into(), - steps: vec![("actions.play".into(), json!({"action": "A"}))], - disabled: Default::default(), - ..Default::default() - }); - let r = s.execute("actions.play", json!({"action": "A"})).unwrap(); - assert!(r["failed"]["error"].as_str().unwrap().contains("recursive")); - assert!(s.documents().is_empty()); - s.actions.list[1].steps = vec![("file.new".into(), json!({"width": 2,"height": 2}))]; - s.authorize = Some(|id, _| if id == "file.new" { Err(EngineError::Other("denied nested file".into())) } else { Ok(()) }); - let r = s.execute("actions.play", json!({"action": "A"})).unwrap(); - assert!(r["failed"]["error"].as_str().unwrap().contains("denied nested file")); - assert!(s.documents().is_empty()); - s.authorize = None; - s.actions.list.clear(); - for i in 0..17 { - s.actions.list.push(Action { - name: format!("N{i}"), - steps: if i < 16 { vec![("actions.play".into(), json!({"action":format!("N{}", i + 1)}))] } else { vec![] }, - disabled: Default::default(), - ..Default::default() - }); - } - let r = s.execute("actions.play", json!({"action": "N0"})).unwrap(); - assert!(r["failed"]["error"].as_str().unwrap().contains("16 levels")); - assert_eq!(s.actions.playing, 0); - assert!(s.actions.playback_stack.is_empty()); - s.actions.list[15].steps.clear(); - assert!(s.execute("actions.play", json!({"action": "N0"})).unwrap().get("failed").is_none()); - } - - #[test] - fn move_pending_steps_is_atomic_persists_and_changes_playback_order() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); - s.execute("actions.record", json!({"name": "Order"})).unwrap(); - for name in ["One", "Two", "Three"] { - s.execute("layer.new.layer", json!({"name": name})).unwrap(); - } - let before = s.actions.clone(); - for params in [ - json!({"action":0,"step":0,"to":3}), - json!({"action":0,"step":99,"to":0}), - json!({"action":0,"step":0.5,"to":0}), - json!({"action":0,"to":-1}), - json!({"action":0,"to":null}), - ] { - assert!(s.execute("actions.move", params).is_err()); - assert_eq!(s.actions, before); - } - let journal = s.journal.clone(); - s.execute("actions.move", json!({"action":0,"step":0,"to":2})).unwrap(); - s.execute("actions.move", json!({"action":0,"step":1,"to":0})).unwrap(); - assert_eq!(s.journal, journal); - s.execute("layer.new.layer", json!({"name":"Four"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[0].steps.iter().map(|st| st.1["name"].as_str().unwrap()).collect::>(), ["Three", "Two", "One", "Four"]); - s.execute("file.new", json!({"width":4,"height":4})).unwrap(); - s.execute("actions.play", json!({"action":0})).unwrap(); - assert_eq!(s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.as_str()).collect::>(), ["Three", "Two", "One", "Four"]); - } - - #[test] - fn new_names_do_not_collide_with_named_calls() { - let mut s = Session::new(); - s.actions.list.push(Action { name: "Action 2".into(), steps: vec![], disabled: Default::default(), ..Default::default() }); - assert_eq!(s.execute("actions.record", json!({})).unwrap()["action"], "Action 3"); - s.execute("actions.stop", json!({})).unwrap(); - assert!(s.execute("actions.record", json!({"name":"Action 2"})).is_err()); - assert!(s.actions.recording.is_none()); - } - - #[test] - fn moving_action_keeps_recording_attached_to_it() { - let mut s = Session::new(); - s.execute("file.new", json!({"width":4,"height":4})).unwrap(); - for name in ["A", "B", "C"] { - s.actions.list.push(Action { name: name.into(), steps: vec![], disabled: Default::default(), ..Default::default() }); - } - s.execute("actions.record", json!({"action":"B"})).unwrap(); - s.execute("layer.new.layer", json!({"name":"before"})).unwrap(); - s.execute("actions.move", json!({"action":"B","to":2})).unwrap(); - s.execute("actions.move", json!({"action":"A","to":2})).unwrap(); - s.execute("layer.new.layer", json!({"name":"after"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - assert_eq!(s.actions.list[1].name, "B"); - assert_eq!(s.actions.list[1].steps.len(), 2); - } - - #[test] - fn bad_params_do_not_panic() { - let mut s = Session::new(); - let junk = [ - Value::Null, - json!([]), - json!("x"), - json!(1), - json!({"action": true}), - json!({"action": -1}), - json!({"action": 99}), - json!({"action": ""}), - json!({"name": 1}), - json!({"name": ""}), - json!({"from": "start"}), - json!({"from": -3}), - json!({"action": "missing", "from": 4}), - ]; - for id in ["actions.list", "actions.get", "actions.record", "actions.stop", "actions.play", "actions.delete", "actions.move"] { - for p in &junk { - let _ = s.execute(id, p.clone()); - } - } - assert_eq!(s.actions.playing, 0); - assert!(crate::commands::command_specs().iter().any(|c| c.id == "actions.play" && !c.journal && c.menu.is_empty())); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn actions_persist_with_the_preset_store() { - let dir = std::env::temp_dir().join(format!("pc-actions-{}-persist", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let mut s = Session::new(); - let warnings = s.attach_preset_store(crate::preset_store::open_dir(&dir)); - assert!(warnings.iter().all(|w| !w.contains("actions")), "{warnings:?}"); - s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); - s.execute("actions.record", json!({"name": "Kept"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - drop(s); - - let mut t = Session::new(); - t.attach_preset_store(crate::preset_store::open_dir(&dir)); - let listed = t.execute("actions.list", json!({})).unwrap(); - assert_eq!(listed["actions"][0]["name"], "Kept"); - assert_eq!(listed["actions"][0]["steps"], 1); - assert_eq!(t.execute("actions.get", json!({"action": "Kept"})).unwrap()["steps"][0][0], "layer.new.layer"); - - // An action created before the store finishes loading is kept, and a different one on - // disk is merged in. - let mut early = Session::new(); - early.execute("actions.record", json!({"name": "Early"})).unwrap(); - early.execute("actions.stop", json!({})).unwrap(); - early.attach_preset_store(crate::preset_store::open_dir(&dir)); - let names: Vec = early.actions.list.iter().map(|a| a.name.clone()).collect(); - assert!(names.contains(&"Early".into()) && names.contains(&"Kept".into()), "{names:?}"); - - std::fs::write(dir.join("actions.json"), b"{").unwrap(); - let mut bad = Session::new(); - let warnings = bad.attach_preset_store(crate::preset_store::open_dir(&dir)); - assert!(warnings.iter().any(|w| w.contains("actions")), "{warnings:?}"); - assert!(bad.actions.list.is_empty()); - let _ = std::fs::remove_dir_all(&dir); - } - - /// AUTO-219-4: a recording made on one document replays on a second one — a crop, a filter, - /// a selection fill and styled text all act on the document the replay runs in. - #[test] - fn a_recorded_edit_run_replays_on_a_second_document() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); - s.execute("actions.record", json!({"name": "Studio"})).unwrap(); - s.execute("image.crop", json!({"x": 8, "y": 8, "width": 48, "height": 48})).unwrap(); - s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 12, "height": 12})).unwrap(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("type.create", json!({"x": 10, "y": 36, "text": "Hi", "size": 12, "color": "#000000"})).unwrap(); - s.execute("type.setStyle", json!({"fauxBold": true})).unwrap(); - let stopped = s.execute("actions.stop", json!({})).unwrap(); - let steps = stopped["steps"].as_u64().unwrap(); - assert!(steps >= 7, "the recording keeps every family: {stopped}"); - - // The second document: a different size, background and name. The replay must act here. - s.execute("file.new", json!({"width": 100, "height": 80, "background": "black", "name": "Second"})).unwrap(); - let played = s.execute("actions.play", json!({"action": "Studio"})).unwrap(); - assert!(played.get("failed").is_none(), "replay: {played}"); - assert_eq!(played["ran"].as_u64(), Some(steps), "every step ran: {played}"); - let d = &s.active().unwrap().doc; - assert_eq!((d.size.width, d.size.height), (48, 48), "the crop replayed onto the second document"); - assert_eq!(pixel(&s, 0, 16, 16), vec![1.0, 0.0, 0.0, 1.0], "the selection fill replayed"); - assert_eq!(pixel(&s, 0, 2, 2), vec![0.0, 0.0, 0.0, 1.0], "outside the selection stays black"); - let last = d.layers.last().unwrap(); - match &last.content { - photocraft_doc::LayerContent::Text(t) => { - assert_eq!(t.text, "Hi", "the styled text replayed"); - assert!(t.char_runs().iter().any(|r| r.style.faux_bold), "the bold run replayed"); - } - other => panic!("expected the recorded type layer, got {other:?}"), - } - // The first document is untouched. - let first = &s.documents()[0].doc; - assert_eq!((first.size.width, first.size.height), (48, 48), "the recording document keeps its own crop"); - } - - #[test] - fn button_color_is_one_of_the_photoshop_swatches() { - let mut s = Session::new(); - s.execute("actions.record", json!({"name": "Print"})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - let set = s.execute("actions.setColor", json!({"action": "Print", "color": "blue"})).unwrap(); - assert_eq!(set["color"], "blue"); - assert_eq!(s.actions.list[0].color, "blue"); - assert_eq!(s.execute("actions.get", json!({"action": 0})).unwrap()["color"], "blue"); - let saved = serde_json::to_string(&s.actions.list).unwrap(); - assert!(saved.contains("blue")); - s.execute("actions.setColor", json!({"action": 0, "color": ""})).unwrap(); - assert!(s.actions.list[0].color.is_empty()); - assert!(!serde_json::to_string(&s.actions.list).unwrap().contains("color"), "an empty colour is omitted"); - for bad in [json!({"action": 0, "color": "pink"}), json!({"action": 0}), json!({"action": 4, "color": "red"}), json!({"color": "red"})] { - assert!(s.execute("actions.setColor", bad).is_err()); - } - assert!(s.actions.list[0].color.is_empty(), "rejected colours change nothing"); - } -} +mod tests; #[cfg(test)] mod security_tests { diff --git a/crates/engine/src/actions_cmds/tests.rs b/crates/engine/src/actions_cmds/tests.rs new file mode 100644 index 0000000000..77f8fefc78 --- /dev/null +++ b/crates/engine/src/actions_cmds/tests.rs @@ -0,0 +1,1045 @@ +use super::*; +use serde_json::json; + +fn pixel(s: &Session, layer: usize, x: i32, y: i32) -> Vec { + s.active().unwrap().doc.layers[layer].surface().unwrap().pixel(x, y) +} + +#[test] +fn deselect_with_nothing_selected_is_a_noop_in_playback() { + // #6744: imported actions often start with Deselect; with no selection Photoshop plays on. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let before = s.active().unwrap().history.past_len(); + // Outside playback the command stays disabled, like Photoshop's greyed menu item. + assert!(s.execute("select.deselect", json!({})).is_err()); + assert!(s.active().unwrap().doc.selection.is_none()); + assert_eq!(s.active().unwrap().history.past_len(), before, "rejection adds no history step"); + let deselect = crate::commands::find("select.deselect").unwrap(); + assert_eq!((deselect.run)(&mut s, &json!({})).unwrap(), Value::Null); + assert_eq!(s.active().unwrap().history.past_len(), before, "no history step"); + + let steps = vec![("select.deselect".to_string(), json!({})), ("layer.new.layer".to_string(), json!({"name": "A"}))]; + s.actions.list.push(Action::new("Clear", steps)); + let played = s.execute("actions.play", json!({"action": 0})).unwrap(); + assert_eq!(played["ran"], 2, "{played}"); + assert_eq!(s.active().unwrap().doc.layers.last().unwrap().name, "A"); +} + +#[test] +fn unchecked_steps_are_skipped_and_follow_move_and_delete() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let step = |name: &str| ("layer.new.layer".to_string(), json!({"name": name})); + s.actions.list.push(Action::new("Three", vec![step("A"), step("B"), step("C")])); + let names = |s: &Session| s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.clone()).collect::>(); + + assert_eq!(s.execute("actions.toggle", json!({"action": "Three", "step": 1})).unwrap()["disabled"], json!([1])); + let played = s.execute("actions.play", json!({"action": 0})).unwrap(); + assert_eq!(played["ran"], 2); + assert_eq!(names(&s), ["A", "C"], "the unchecked step is skipped"); + assert_eq!(s.execute("actions.get", json!({"action": 0})).unwrap()["disabled"], json!([1])); + + // Moving step 3 to the top keeps B (now step 2) unchecked; deleting the moved step shifts it to 1. + s.execute("actions.move", json!({"action": 0, "step": 2, "to": 0})).unwrap(); + let ids: Vec<_> = s.actions.list[0].steps.iter().map(|(_, p)| p["name"].as_str().unwrap()).collect(); + assert_eq!((ids, s.actions.list[0].disabled.iter().copied().collect::>()), (vec!["C", "A", "B"], vec![2])); + s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); + assert_eq!(s.actions.list[0].steps, [step("A"), step("B")], "deleting removes only that step"); + assert_eq!(s.actions.list[0].disabled.iter().copied().collect::>(), [1]); + + // The action's own check: all on unless all already are. + s.execute("actions.toggle", json!({"action": 0})).unwrap(); + assert!(s.actions.list[0].disabled.is_empty()); + s.execute("actions.toggle", json!({"action": 0})).unwrap(); + assert_eq!(s.actions.list[0].disabled.len(), 2); + s.execute("actions.toggle", json!({"action": 0, "step": 0, "enabled": true})).unwrap(); + assert_eq!(s.actions.list[0].disabled.iter().copied().collect::>(), [1]); + + for bad in [ + json!({"action": 0, "step": 2}), + json!({"action": 0, "step": -1}), + json!({"action": 0, "step": "x"}), + json!({"action": 0, "step": 0, "enabled": "yes"}), + json!({"action": 7, "step": 0}), + json!({}), + ] { + assert!(s.execute("actions.toggle", bad.clone()).is_err(), "{bad}"); + } + assert_eq!(s.actions.list[0].disabled.iter().copied().collect::>(), [1], "rejected toggles change nothing"); +} + +#[test] +fn rename_keeps_calls_and_function_key_and_rejects_bad_names() { + let mut s = Session::new(); + s.actions.list.push(Action { + name: "Action 1".into(), + steps: vec![("layer.new.layer".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + s.actions.list.push(Action { + name: "Caller".into(), + steps: vec![("actions.play".into(), json!({"action": "Action 1"}))], + disabled: Default::default(), + ..Default::default() + }); + s.edit_prefs(|p| p.shortcuts.insert(format!("{PLAY_SHORTCUT_PREFIX}Action 1"), "F2".into())); + assert_eq!(s.execute("actions.rename", json!({"action": 0, "name": "Sepia"})).unwrap()["action"], "Sepia"); + assert_eq!(s.execute("actions.list", json!({})).unwrap()["actions"][0]["name"], "Sepia"); + assert_eq!(s.actions.list[1].steps[0].1["action"], "Sepia"); + assert_eq!(s.prefs().shortcuts.get("actions.play:Sepia").map(String::as_str), Some("F2")); + assert!(!s.prefs().shortcuts.contains_key("actions.play:Action 1")); + for bad in [ + json!({"action": 0, "name": ""}), + json!({"action": 0, "name": " "}), + json!({"action": 0, "name": "Caller"}), + json!({"action": 0, "name": 7}), + json!({"action": 9, "name": "X"}), + json!({"action": 0}), + ] { + assert!(s.execute("actions.rename", bad.clone()).is_err(), "{bad}"); + } + assert_eq!(s.actions.list[0].name, "Sepia"); +} + +#[test] +fn rename_follows_conditional_branches() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + for name in ["B", "Other"] { + s.actions.list.push(Action { name: name.into(), steps: vec![("layer.new.layer".into(), json!({}))], ..Default::default() }); + } + s.actions.list.push(Action { + name: "Main".into(), + steps: vec![ + ("actions.conditional".into(), json!({"if": "always", "then": "B", "else": "Other"})), + ("actions.conditional".into(), json!({"if": "never", "then": "Other", "else": "B"})), + ], + ..Default::default() + }); + s.execute("actions.rename", json!({"action": "B", "name": "C"})).unwrap(); + let steps = &s.actions.list[2].steps; + assert_eq!(steps[0].1, json!({"if": "always", "then": "C", "else": "Other"})); + assert_eq!(steps[1].1, json!({"if": "never", "then": "Other", "else": "C"})); + let r = s.execute("actions.play", json!({"action": "Main"})).unwrap(); + assert!(r.get("failed").is_none(), "{r}"); +} + +#[test] +fn delete_action_drops_its_function_key_but_deleting_a_step_keeps_it() { + let mut s = Session::new(); + let key = format!("{PLAY_SHORTCUT_PREFIX}Action 1"); + s.actions.list.push(Action::new("Action 1", vec![("layer.new.layer".into(), json!({})), ("layer.new.layer".into(), json!({}))])); + s.edit_prefs(|p| p.shortcuts.insert(key.clone(), "F2".into())); + s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); + assert_eq!(s.prefs().shortcuts.get(&key).map(String::as_str), Some("F2"), "deleting a step keeps the key"); + assert_eq!(s.execute("actions.delete", json!({"action": 0})).unwrap()["deleted"], "Action 1"); + assert!(!s.prefs().shortcuts.contains_key(&key), "the deleted action's function key is gone"); + s.execute("actions.record", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].name, "Action 1"); + assert!(!s.prefs().shortcuts.contains_key(&key), "a new action with the same name starts unbound"); +} + +fn record_red(s: &mut Session, depth: u32) { + s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth})).unwrap(); + s.execute("actions.record", json!({"name": "Red"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let _ = s.execute("document.pixel", json!({"x": 1, "y": 1})); + let _ = s.execute("actions.list", json!({})); + s.execute("actions.stop", json!({})).unwrap(); +} + +fn translated_square(s: &mut Session, depth: u32) { + s.execute("file.new", json!({"width": 20, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); + s.edit("red square", |doc, _| { + doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 2, 2, 4), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 4, 0], "interpolation": "nearest"})).unwrap(); + assert_eq!(pixel(s, 0, 4, 2), vec![1.0, 0.0, 0.0, 1.0]); +} + +#[test] +fn record_transform_again_replays_one_concrete_transform_at_each_depth() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + translated_square(&mut s, depth); + let from = s.journal.len(); + s.execute("actions.record", json!({"name": "Again"})).unwrap(); + s.execute("edit.transform.again", json!({})).unwrap(); + let ids: Vec<&str> = s.journal.iter().skip(from).map(|(id, _)| id.as_str()).collect(); + assert_eq!(ids, ["edit.transform", "edit.transform.again"], "both commands stay in the journal during recording"); + let live_count = s.journal.iter().skip(from).filter(|(id, _)| replayable(id)).count(); + s.execute("actions.stop", json!({})).unwrap(); + let recorded = s.execute("actions.get", json!({"action": "Again"})).unwrap(); + let steps = recorded["steps"].as_array().unwrap(); + assert_eq!(steps.len(), 1, "depth {depth}: record the concrete transform once"); + assert_eq!(live_count, 1, "depth {depth}: the live Actions count agrees"); + assert_eq!(steps[0][0], "edit.transform"); + assert_eq!(steps[0][1]["matrix"], json!([1, 0, 0, 1, 4, 0])); + assert_eq!(steps[0][1]["interpolation"], "nearest"); + + translated_square(&mut s, depth); + let before = s.active().unwrap().history.past_len(); + let played = s.execute("actions.play", json!({"action": "Again"})).unwrap(); + assert!(played.get("failed").is_none(), "depth {depth}: {played}"); + assert_eq!(played["ran"], 1, "depth {depth}: apply the recorded transform once"); + assert_eq!(s.active().unwrap().history.past_len(), before + 1, "depth {depth}: one undo step"); + assert_eq!(pixel(&s, 0, 8, 2), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}: moved four pixels"); + assert_eq!(pixel(&s, 0, 12, 2), vec![0.0; 4], "depth {depth}: no second transform"); + assert!(s.undo()); + assert_eq!(pixel(&s, 0, 4, 2), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(pixel(&s, 0, 8, 2), vec![0.0; 4]); + assert!(s.redo()); + assert_eq!(pixel(&s, 0, 8, 2), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(pixel(&s, 0, 4, 2), vec![0.0; 4]); + } +} + +#[test] +fn record_transform_again_on_a_copy_replays_in_a_session_without_a_transform() { + for depth in [8, 16] { + let mut s = Session::new(); + translated_square(&mut s, depth); + s.execute("actions.record", json!({"name": "Step"})).unwrap(); + s.execute("edit.transform.againCopy", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let got = s.execute("actions.get", json!({"action": "Step"})).unwrap(); + let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect(); + assert_eq!(ids, ["layer.duplicate", "edit.transform"], "depth {depth}: the concrete steps, not the wrapper"); + let action = s.actions.list[0].clone(); + + // A new session has no transform to repeat: the concrete steps still play. + let mut fresh = Session::new(); + fresh.execute("file.new", json!({"width": 20, "height": 8, "depth": depth, "background": "transparent"})).unwrap(); + fresh + .edit("red square", |doc, _| { + doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(4, 2, 6, 4), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + fresh.actions.list.push(action); + let played = fresh.execute("actions.play", json!({"action": "Step"})).unwrap(); + assert!(played.get("failed").is_none(), "depth {depth}: {played}"); + assert_eq!(played["ran"], 2, "depth {depth}"); + assert_eq!(fresh.active().unwrap().doc.layers.len(), 2, "depth {depth}: one copy"); + assert_eq!(pixel(&fresh, 0, 4, 2), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}: the original stays"); + assert_eq!(pixel(&fresh, 1, 8, 2), vec![1.0, 0.0, 0.0, 1.0], "depth {depth}: the copy moved four pixels"); + assert_eq!(pixel(&fresh, 1, 4, 2), vec![0.0; 4], "depth {depth}: moved once"); + } +} + +#[test] +fn record_drops_the_steps_of_a_command_that_failed_and_was_taken_back() { + // Transform Again on a Copy of a position-locked layer duplicates it, fails to move the + // copy and takes the copy back: nothing is left to record. + let mut s = Session::new(); + translated_square(&mut s, 8); + let id = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.setProps", json!({"layer": id.0, "locks": {"position": true}})).unwrap(); + s.execute("actions.record", json!({"name": "Locked"})).unwrap(); + assert!(s.execute("edit.transform.againCopy", json!({})).is_err()); + 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); + 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_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"); +} + +#[test] +fn record_script_that_plays_an_action_keeps_each_step_once() { + let mut s = Session::new(); + translated_square(&mut s, 8); + s.execute("actions.record", json!({"name": "Inner"})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 1, 0], "interpolation": "nearest"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + + // Browse records the concrete steps it ran, not itself (#3057): the script's transform and + // the action call, each once, in order. + let script = json!({"steps": [["edit.transform", {"matrix": [1, 0, 0, 1, 2, 0], "interpolation": "nearest"}], ["actions.play", {"action": "Inner"}]]}); + s.execute("actions.record", json!({"name": "Outer"})).unwrap(); + s.execute("file.scripts.browse", script.clone()).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let got = s.execute("actions.get", json!({"action": "Outer"})).unwrap(); + assert_eq!(got["steps"], script["steps"]); +} + +#[test] +fn record_explicit_transform_keeps_one_replayable_step() { + let mut s = Session::new(); + translated_square(&mut s, 8); + s.execute("actions.record", json!({"name": "Move"})).unwrap(); + s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 4, 0], "interpolation": "nearest"})).unwrap(); + assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 1); + let recorded = s.execute("actions.get", json!({"action": "Move"})).unwrap(); + assert_eq!(recorded["steps"][0][0], "edit.transform"); + + translated_square(&mut s, 8); + let before = s.active().unwrap().history.past_len(); + let played = s.execute("actions.play", json!({"action": "Move"})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert_eq!(played["ran"], 1); + assert_eq!(s.active().unwrap().history.past_len(), before + 1); + assert_eq!(pixel(&s, 0, 8, 2), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(pixel(&s, 0, 12, 2), vec![0.0; 4]); +} + +/// A Background with a red bar and a slanted ruler line, ready for Straighten. +fn ruled_background(s: &mut Session, depth: u32) { + s.execute("file.new", json!({"width": 80, "height": 60, "depth": depth})).unwrap(); + s.edit("red bar", |doc, _| { + doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 20, 60, 8), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .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); + 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(); + 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); + 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}"); + assert_eq!(played["ran"], 2, "depth {depth}"); + assert_eq!(s.active().unwrap().history.past_len(), before + 1, "depth {depth}: one Straighten step (the ruler is no step)"); + let replayed = s.active().unwrap().doc.clone(); + assert_eq!(replayed.size, direct.size, "depth {depth}: rotated and cropped once"); + let r = photocraft_geom::Rect::new(0, 0, direct.size.width as i32, direct.size.height as i32); + let px = |d: &photocraft_doc::Document| d.layers[0].surface().unwrap().read_region(r); + assert_eq!(px(&replayed), px(&direct), "depth {depth}: same pixels as the direct run"); + } +} + +#[test] +fn record_keeps_only_replayable_steps() { + let mut s = Session::new(); + record_red(&mut s, 8); + let got = s.execute("actions.get", json!({"action": "Red"})).unwrap(); + let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect(); + assert_eq!(ids, ["layer.new.layer", "select.rect", "edit.fill"]); + assert!(s.journal.iter().all(|(id, _)| !id.starts_with("actions."))); + let listed = s.execute("actions.list", json!({})).unwrap(); + assert_eq!(listed["actions"][0]["steps"], 3); + assert!(listed["recording"].is_null()); +} + +#[test] +fn play_on_another_document_matches_pixels_at_each_depth() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + record_red(&mut s, depth); + s.execute("file.new", json!({"width": 40, "height": 40, "depth": depth})).unwrap(); + let before = s.active().unwrap().history.past_len(); + let r = s.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(r.get("failed").is_none(), "depth {depth}: {r}"); + assert_eq!(r["ran"], 3, "depth {depth}"); + assert_eq!(s.active().unwrap().doc.layers.len(), 2, "depth {depth}"); + assert_eq!(s.active().unwrap().history.past_len(), before + 3, "depth {depth}: one history step per played step"); + let px = pixel(&s, 1, 5, 5); + assert!(px.iter().zip([1.0, 0.0, 0.0, 1.0]).all(|(a, b)| (a - b).abs() < 1.0e-5), "depth {depth}: {px:?}"); + assert_eq!(s.actions.playing, 0); + } +} + +#[test] +fn recorded_layer_selection_replays_by_name_on_another_document() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); + let original = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.setProps", json!({"name": "Photo"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "LogoBase"})).unwrap(); + s.execute("actions.record", json!({"name": "Duplicate photo"})).unwrap(); + s.execute("layer.select", json!({"layer": original.0, "mode": "replace"})).unwrap(); + // The target name must be captured now, not when recording stops. + s.execute("layer.setProps", json!({"name": "Retouched"})).unwrap(); + s.execute("layer.duplicate", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps[0].1, json!({"name":"Photo", "mode":"replace"})); + // Persisted actions must work in an entirely different session too. + let saved = serde_json::to_string(&s.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + replay.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); + replay.execute("layer.setProps", json!({"name": "Photo"})).unwrap(); + let target = replay.active().unwrap().active_layer.unwrap(); + assert_ne!(original, target); + replay.execute("layer.new.layer", json!({"name": "LogoBase"})).unwrap(); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert_eq!(result["ran"], 3); + assert_eq!(replay.active().unwrap().doc.layer(target).unwrap().name, "Retouched"); + let active = replay.active().unwrap().active_layer.unwrap(); + assert_eq!(replay.active().unwrap().doc.layer(active).unwrap().name, "Retouched copy"); + } +} + +/// #7845: dragging a layer in the Layers panel while recording keeps the drop target by name, +/// so the action plays on another document (whose layer ids differ) instead of failing with +/// "no such layer". The reporter's steps, replayed on a new document. +#[test] +fn recorded_layer_drag_replays_on_another_document() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap(); + s.execute("actions.record", json!({"name": "Retouch"})).unwrap(); + s.execute("layer.stampVisible", json!({})).unwrap(); + let layer1 = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layerViaCopy", json!({})).unwrap(); + let layer2 = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.select", json!({"layer": layer1.0, "mode": "replace"})).unwrap(); + s.execute("filter.noise.median", json!({"radius": 6})).unwrap(); + s.execute("layer.new.layerViaCopy", json!({})).unwrap(); + let copy = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.moveTo", json!({"layer": copy.0, "target": layer2.0, "position": "above"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let (id, step) = s.actions.list[0].steps.last().unwrap(); + assert_eq!((id.as_str(), step), ("layer.moveTo", &json!({"target": "Layer 1 copy", "position": "above"}))); + let names = |s: &Session| s.active().unwrap().doc.layers.iter().rev().map(|l| l.name.clone()).collect::>(); + let recorded = names(&s); + let saved = serde_json::to_string(&s.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + replay.execute("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap(); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{depth}: {result}"); + assert_eq!(names(&replay), recorded, "{depth}: the same stack"); + } + // Several layers of the drop target's name: the recorded occurrence picks the right one. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); + let upper = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "Mover"})).unwrap(); + let mover = s.active().unwrap().active_layer.unwrap(); + s.execute("actions.record", json!({"name": "Drop"})).unwrap(); + s.execute("layer.moveTo", json!({"layer": mover.0, "target": upper.0, "position": "below"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps[0].1, json!({"target": "Twin", "targetOccurrence": 1, "position": "below"})); + // The moved layer shares the target's name: the occurrence counts the other "Twin"s only, + // so it means the same layer before the move (on replay) as after it (when recorded). + let build = |s: &mut Session| { + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + for _ in 0..3 { + s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); + } + s.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>() + }; + let mut s = Session::new(); + let ids = build(&mut s); + let (lowest, top) = (ids[1], ids[3]); + s.execute("actions.record", json!({"name": "Twins"})).unwrap(); + s.execute("layer.moveTo", json!({"layer": top.0, "target": lowest.0, "position": "below"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps[0].1, json!({"target": "Twin", "targetOccurrence": 0, "position": "below"})); + let order = |s: &Session| s.active().unwrap().doc.layers.iter().map(|l| l.id).collect::>(); + let want: Vec<_> = order(&s).iter().map(|id| ids.iter().position(|x| x == id).unwrap()).collect(); + let saved = serde_json::to_string(&s.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + let ids2 = build(&mut replay); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + let got: Vec<_> = order(&replay).iter().map(|id| ids2.iter().position(|x| x == id).unwrap()).collect(); + assert_eq!(got, want, "the same layer became the lowest"); + // A moved group holding a same-named layer: its contents don't count either, or moving the + // group past another "Twin" would shift the occurrence between recording and replay. + let build_group = |s: &mut Session| { + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + let group = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); + let top = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.select", json!({"layer": group.0, "mode": "replace"})).unwrap(); + (group, top) + }; + let mut g = Session::new(); + let (group, top) = build_group(&mut g); + g.execute("actions.record", json!({"name": "Group"})).unwrap(); + g.execute("layer.moveTo", json!({"layer": group.0, "target": top.0, "position": "above"})).unwrap(); + g.execute("actions.stop", json!({})).unwrap(); + let recorded = g.actions.list[0].steps[0].1.clone(); + let saved = serde_json::to_string(&g.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + let (group2, _) = build_group(&mut replay); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{recorded}: {result}"); + let top_layer = |s: &Session| s.active().unwrap().doc.layers.last().map(|l| l.id); + assert_eq!(top_layer(&replay), Some(group2), "{recorded}: the group went to the top"); + // Several moved layers named like the target are left out too, so the name is unambiguous. + let mut m = Session::new(); + m.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let a = photocraft_doc::LayerId(m.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); + let b = photocraft_doc::LayerId(m.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); + let target = photocraft_doc::LayerId(m.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); + m.execute("layer.moveTo", json!({"layers": [a.0, b.0], "target": "Twin", "position": "above"})).unwrap(); + assert_eq!(m.active().unwrap().doc.layers.last().map(|l| l.id), Some(b), "both moved above the third Twin"); + assert_eq!(m.active().unwrap().doc.layers.iter().rev().nth(2).map(|l| l.id), Some(target)); + // An ⌥-drag copy of the selected layer beside itself replays by name too. + let mut c = Session::new(); + c.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let src = photocraft_doc::LayerId(c.execute("layer.new.layer", json!({"name": "Solo"})).unwrap()["layer"].as_u64().unwrap()); + c.execute("actions.record", json!({"name": "Copy"})).unwrap(); + c.execute("layer.moveTo", json!({"layer": src.0, "target": src.0, "position": "above", "copy": true})).unwrap(); + c.execute("actions.stop", json!({})).unwrap(); + assert_eq!(c.actions.list[0].steps[0].1, json!({"target": "Solo", "position": "above", "copy": true})); + let saved = serde_json::to_string(&c.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + replay.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + replay.execute("layer.new.layer", json!({"name": "Solo"})).unwrap(); + let before = replay.active().unwrap().doc.layers.len(); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert_eq!(replay.active().unwrap().doc.layers.len(), before + 1, "one copy"); + // Copying a group holding a layer named like the target: the new copy's contents (made + // before the step is recorded) don't count, so the occurrence matches the replay. + let build_copy = |s: &mut Session| { + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + let group = s.active().unwrap().active_layer.unwrap(); + let a = photocraft_doc::LayerId(s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); + let b = photocraft_doc::LayerId(s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.select", json!({"layer": group.0, "mode": "replace"})).unwrap(); + (group, a, b) + }; + let mut gc = Session::new(); + let (group, a, _) = build_copy(&mut gc); + gc.execute("actions.record", json!({"name": "Copy group"})).unwrap(); + // Below `a`: the copy's "Twin" then comes before `a` in document order. + gc.execute("layer.moveTo", json!({"layer": group.0, "target": a.0, "position": "below", "copy": true})).unwrap(); + gc.execute("actions.stop", json!({})).unwrap(); + let saved = serde_json::to_string(&gc.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + let (_, a2, _) = build_copy(&mut replay); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + let layers = &replay.active().unwrap().doc.layers; + let at = layers.iter().position(|l| l.id == a2).unwrap(); + let below = at.checked_sub(1).and_then(|i| layers.get(i)).map(|l| l.name.as_str()); + assert_eq!(below, Some("Group 1 copy"), "the copy landed below the same Twin"); + // A drag of several layers keeps its ids (not covered by name). + s.execute("actions.record", json!({"name": "Several"})).unwrap(); + s.execute("layer.moveTo", json!({"layers": [ids[2].0, ids[3].0], "target": ids[1].0, "position": "above"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[1].steps[0].1["target"], json!(ids[1].0)); + // Bad targets are errors, not panics. + for bad in [ + json!({"target": "Nobody"}), + json!({"target": "Twin"}), + json!({"target": "Twin", "targetOccurrence": 9}), + json!({"target": "Twin", "targetOccurrence": -1}), + json!({"target": true}), + ] { + assert!(s.execute("layer.moveTo", bad.clone()).is_err(), "{bad}"); + } +} + +/// An Alt-drag copy records `inPlace` (#7200), which only matters for an artboard: a plain +/// layer's recorded copy must still export to .atn, while an artboard's must be refused rather +/// than exported as a copy beside the original. +#[test] +fn recorded_in_place_duplicate_keeps_in_place_only_for_artboards() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("actions.record", json!({"name": "Layer copy"})).unwrap(); + s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + s.execute("layer.new.artboard", json!({"name": "Board", "rect": [0, 0, 8, 8]})).unwrap(); + s.execute("actions.record", json!({"name": "Board copy"})).unwrap(); + s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps, vec![("layer.duplicate".to_string(), json!({}))]); + assert_eq!(s.actions.list[1].steps, vec![("layer.duplicate".to_string(), json!({"inPlace": true}))]); + assert!(crate::atn_cmds::export("Audit", &[&s.actions.list[0]], &[], false).is_ok()); + assert!(crate::atn_cmds::export("Audit", &[&s.actions.list[1]], &[], false).is_err()); + // Several selected layers are copied together: one artboard among them keeps `inPlace`. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let photo = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "Logo"})).unwrap(); + s.execute("layer.select", json!({"layer": photo.0, "mode": "add"})).unwrap(); + s.execute("actions.record", json!({"name": "Layers copy"})).unwrap(); + s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.active().unwrap().selected_layers().len(), 2, "both layers were copied"); + s.execute("layer.new.artboard", json!({"name": "Board", "rect": [0, 0, 8, 8]})).unwrap(); + s.execute("layer.select", json!({"layer": photo.0, "mode": "add"})).unwrap(); + s.execute("actions.record", json!({"name": "Mixed copy"})).unwrap(); + s.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps, vec![("layer.duplicate".to_string(), json!({}))]); + assert_eq!(s.actions.list[1].steps, vec![("layer.duplicate".to_string(), json!({"inPlace": true}))]); +} + +#[test] +fn named_selection_preserves_modes_and_duplicate_occurrences() { + let mut s = Session::new(); + s.execute("file.new", json!({"width":4,"height":4})).unwrap(); + s.execute("layer.setProps", json!({"name":"Photo"})).unwrap(); + let first = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.group", json!({"name":"Group"})).unwrap(); + // A duplicate nested in a group must be found even when that group is collapsed. + let second = s + .edit("child", |doc, active| { + let child = photocraft_doc::Layer::raster("Photo", doc.pixel_format()); + let id = child.id; + if let photocraft_doc::LayerContent::Group(group) = &mut doc.layer_mut(active.unwrap()).unwrap().content { + group.children.push(child); + group.expanded = false; + } + Ok(id) + }) + .unwrap(); + s.execute("actions.record", json!({"name":"Select duplicates"})).unwrap(); + s.execute("layer.select", json!({"layer":first.0})).unwrap(); + s.execute("layer.select", json!({"layer":second.0,"mode":"add"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps[0].1, json!({"name":"Photo","occurrence":0})); + assert_eq!(s.actions.list[0].steps[1].1, json!({"name":"Photo","occurrence":1,"mode":"add"})); + s.execute("layer.select", json!({"layer":first.0})).unwrap(); + let r = s.execute("actions.play", json!({"action":0})).unwrap(); + assert!(r.get("failed").is_none(), "{r}"); + assert_eq!(s.active().unwrap().selected_layers(), vec![first, second]); + s.execute("layer.select", json!({"name":"Photo","occurrence":1,"mode":"toggle"})).unwrap(); + assert_eq!(s.active().unwrap().selected_layers(), vec![first]); + s.execute("layer.select", json!({"name":"Photo","occurrence":1,"mode":"range"})).unwrap(); + assert!(s.active().unwrap().selected_layers().contains(&second)); + // Main's imported .atn steps use a string-valued `layer` and choose the topmost match. + s.execute("layer.select", json!({"layer":"Photo"})).unwrap(); + assert_eq!(s.active().unwrap().selected_layers(), vec![second]); + s.execute("layer.select", json!({"name":"Photo","occurrence":0,"mode":"add"})).unwrap(); + s.execute("layer.select", json!({"name":"Photo","occurrence":1,"mode":"remove"})).unwrap(); + assert_eq!(s.active().unwrap().selected_layers(), vec![first]); + // Removing an unselected layer does not add it; removing the last target keeps it. + s.execute("layer.select", json!({"layer":"Photo","mode":"remove"})).unwrap(); + s.execute("layer.select", json!({"name":"Photo","occurrence":0,"mode":"remove"})).unwrap(); + assert_eq!(s.active().unwrap().selected_layers(), vec![first]); + for p in [ + json!({"name":"absent"}), + json!({"name":"Photo"}), + json!({"name":1}), + json!({"name":"Photo","occurrence":-1}), + json!({"name":"Photo","occurrence":1.5}), + json!({"name":"Photo","occurrence":99}), + json!({"name":"Photo","layer":first.0}), + json!({"layer":first.0,"occurrence":0}), + ] { + let before = s.active().unwrap().selected_layers(); + assert!(s.execute("layer.select", p.clone()).is_err(), "{p}"); + assert_eq!(s.active().unwrap().selected_layers(), before); + } + s.actions.list.push(Action { + name: "Missing".into(), + steps: vec![("layer.select".into(), json!({"name":"absent"})), ("layer.duplicate".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + let before = s.active().unwrap().doc.walk().len(); + let result = s.execute("actions.play", json!({"action":"Missing"})).unwrap(); + assert_eq!(result["ran"], 0); + assert!(result["failed"]["error"].as_str().unwrap().contains("absent")); + assert_eq!(s.active().unwrap().doc.walk().len(), before); +} + +#[test] +fn play_stops_at_the_failing_step_and_reports_it() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + s.execute("actions.record", json!({})).unwrap(); + s.execute("layer.new.layer", json!({"name": "One"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + s.actions.list[0].steps.push(("not.a.command".into(), json!({}))); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + let r = s.execute("actions.play", json!({"action": "Action 1"})).unwrap(); + assert_eq!(r["ran"], 1); + assert_eq!(r["failed"]["step"], 1); + assert_eq!(r["failed"]["id"], "not.a.command"); + assert!(r["failed"]["error"].as_str().unwrap().contains("unknown command")); + assert_eq!(s.active().unwrap().doc.layers.len(), 2, "the step before the failure is kept"); + assert_eq!(s.actions.playing, 0); + // A later play still runs. + assert_eq!(s.execute("actions.play", json!({"action": 0, "from": 1})).unwrap()["ran"], 0); +} + +#[test] +fn play_refuses_recursion() { + let mut s = Session::new(); + s.actions.list.push(Action { + name: "Loop".into(), + steps: vec![("actions.play".into(), json!({"action": "Loop"}))], + disabled: Default::default(), + ..Default::default() + }); + let r = s.execute("actions.play", json!({"action": "Loop"})).unwrap(); + assert_eq!(r["ran"], 0); + assert_eq!(r["failed"]["id"], "actions.play"); + assert!(r["failed"]["error"].as_str().unwrap().contains("recursive action"), "{r}"); + assert_eq!(s.actions.playing, 0); +} + +#[test] +fn play_checks_each_step_with_the_authorize_hook() { + fn deny_file(id: &str, _: &Value) -> Result<()> { + if id.starts_with("file.") { Err(EngineError::Other(format!("automation command `{id}` is disabled"))) } else { Ok(()) } + } + let mut s = Session::new(); + s.authorize = Some(deny_file); + s.actions.list.push(Action { + name: "Open".into(), + steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + let r = s.execute("actions.play", json!({"action": "Open"})).unwrap(); + assert_eq!(r["ran"], 0); + assert_eq!(r["failed"]["step"], 0); + assert_eq!(r["failed"]["id"], "file.open"); + assert!(r["failed"]["error"].as_str().unwrap().contains("disabled"), "{r}"); + assert!(s.documents().is_empty(), "the refused step does not open a document"); +} + +#[test] +fn append_delete_and_from_step() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + let started = s.execute("actions.record", json!({"name": "Grow"})).unwrap(); + assert_eq!(started["index"], 0); + s.execute("layer.new.layer", json!({"name": "One"})).unwrap(); + assert!(s.execute("actions.record", json!({})).is_err(), "already recording"); + assert!(s.execute("actions.delete", json!({"action": 0})).is_err(), "delete while recording"); + let stopped = s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(stopped["steps"], 1); + s.execute("actions.record", json!({"action": "Grow"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Two"})).unwrap(); + assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 2); + assert!(s.execute("actions.stop", json!({})).is_err(), "not recording"); + let before = s.active().unwrap().doc.layers.len(); + let r = s.execute("actions.play", json!({"action": "Grow", "from": 1})).unwrap(); + assert_eq!(r["ran"], 1); + assert_eq!(s.active().unwrap().doc.layers.len(), before + 1); + assert_eq!(s.execute("actions.delete", json!({"action": "Grow"})).unwrap()["deleted"], "Grow"); + assert!(s.actions.list.is_empty()); + assert!(s.execute("actions.get", json!({"action": "Grow"})).is_err()); +} + +#[test] +fn delete_one_step_while_recording_keeps_journal_and_remaining_steps() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("actions.record", json!({"name": "Edit"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Kept"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Removed"})).unwrap(); + let journal = s.journal.clone(); + let rev = s.actions.rev; + let before = s.actions.clone(); + for step in [json!(-1), json!(2), json!(0.5), json!(null), json!("0"), json!(u64::MAX)] { + assert!(s.execute("actions.delete", json!({"action": 0, "step": step})).is_err()); + assert_eq!(s.actions, before, "invalid deletion is atomic"); + } + assert_eq!(pending_steps(&s, 0).count(), 2); + let result = s.execute("actions.delete", json!({"action": 0, "step": 1})).unwrap(); + assert_eq!(result["steps"], 1); + assert_eq!(s.journal, journal, "deleting a recording does not erase executed commands"); + assert_eq!(s.active().unwrap().doc.layers.len(), 3, "it does not undo document edits"); + assert!(s.actions.recording.is_some()); + assert!(s.actions.rev > rev); + s.execute("layer.new.layer", json!({"name": "After"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps.iter().map(|(_, p)| p["name"].as_str().unwrap()).collect::>(), ["Kept", "After"]); + s.execute("actions.delete", json!({"action": "Edit", "step": 0})).unwrap(); + assert_eq!(s.actions.list[0].steps[0].1["name"], "After"); + let saved = serde_json::to_string(&s.actions.list).unwrap(); + s.actions.list = serde_json::from_str(&saved).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + assert_eq!(s.execute("actions.play", json!({"action": 0})).unwrap()["ran"], 1); + assert_eq!(s.active().unwrap().doc.layers[1].name, "After"); + s.execute("actions.delete", json!({"action": 0, "step": 0})).unwrap(); + assert_eq!(s.actions.list.len(), 1, "an empty action still exists"); + assert!(s.actions.list[0].steps.is_empty()); +} + +#[test] +fn nested_call_records_one_named_step_and_tracks_child_edits() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + s.actions.list.push(Action { + name: "Child".into(), + steps: vec![("layer.new.layer".into(), json!({"name": "Child layer"}))], + disabled: Default::default(), + ..Default::default() + }); + s.execute("actions.record", json!({"name": "Parent"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Before"})).unwrap(); + s.execute("actions.play", json!({"action": 0})).unwrap(); + assert_eq!(pending_steps(&s, 1).cloned().collect::>(), [("actions.play".into(), json!({"action": "Child"}))]); + s.execute("layer.new.layer", json!({"name": "After"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[1].steps.iter().map(|st| st.0.as_str()).collect::>(), ["layer.new.layer", "actions.play", "layer.new.layer"]); + s.actions.list[0].steps.push(("layer.new.layer".into(), json!({"name": "Added later"}))); + s.execute("actions.move", json!({"action": "Child", "to": 1})).unwrap(); + let saved = serde_json::to_string(&s.actions.list).unwrap(); + s.actions.list = serde_json::from_str(&saved).unwrap(); + s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + let result = s.execute("actions.play", json!({"action": "Parent"})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert_eq!( + s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.as_str()).collect::>(), + ["Before", "Child layer", "Added later", "After"] + ); + assert!(s.actions.playback_stack.is_empty()); +} + +#[test] +fn nested_failure_cycles_depth_and_authorization_stop_parent() { + let mut s = Session::new(); + s.actions.list.push(Action { + name: "A".into(), + steps: vec![("actions.play".into(), json!({"action": "B"})), ("file.new".into(), json!({"width": 2,"height": 2}))], + disabled: Default::default(), + ..Default::default() + }); + s.actions.list.push(Action { + name: "B".into(), + steps: vec![("actions.play".into(), json!({"action": "A"}))], + disabled: Default::default(), + ..Default::default() + }); + let r = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert!(r["failed"]["error"].as_str().unwrap().contains("recursive")); + assert!(s.documents().is_empty()); + s.actions.list[1].steps = vec![("file.new".into(), json!({"width": 2,"height": 2}))]; + s.authorize = Some(|id, _| if id == "file.new" { Err(EngineError::Other("denied nested file".into())) } else { Ok(()) }); + let r = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert!(r["failed"]["error"].as_str().unwrap().contains("denied nested file")); + assert!(s.documents().is_empty()); + s.authorize = None; + s.actions.list.clear(); + for i in 0..17 { + s.actions.list.push(Action { + name: format!("N{i}"), + steps: if i < 16 { vec![("actions.play".into(), json!({"action":format!("N{}", i + 1)}))] } else { vec![] }, + disabled: Default::default(), + ..Default::default() + }); + } + let r = s.execute("actions.play", json!({"action": "N0"})).unwrap(); + assert!(r["failed"]["error"].as_str().unwrap().contains("16 levels")); + assert_eq!(s.actions.playing, 0); + assert!(s.actions.playback_stack.is_empty()); + s.actions.list[15].steps.clear(); + assert!(s.execute("actions.play", json!({"action": "N0"})).unwrap().get("failed").is_none()); +} + +#[test] +fn move_pending_steps_is_atomic_persists_and_changes_playback_order() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + s.execute("actions.record", json!({"name": "Order"})).unwrap(); + for name in ["One", "Two", "Three"] { + s.execute("layer.new.layer", json!({"name": name})).unwrap(); + } + let before = s.actions.clone(); + for params in [ + json!({"action":0,"step":0,"to":3}), + json!({"action":0,"step":99,"to":0}), + json!({"action":0,"step":0.5,"to":0}), + json!({"action":0,"to":-1}), + json!({"action":0,"to":null}), + ] { + assert!(s.execute("actions.move", params).is_err()); + assert_eq!(s.actions, before); + } + let journal = s.journal.clone(); + s.execute("actions.move", json!({"action":0,"step":0,"to":2})).unwrap(); + s.execute("actions.move", json!({"action":0,"step":1,"to":0})).unwrap(); + assert_eq!(s.journal, journal); + s.execute("layer.new.layer", json!({"name":"Four"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps.iter().map(|st| st.1["name"].as_str().unwrap()).collect::>(), ["Three", "Two", "One", "Four"]); + s.execute("file.new", json!({"width":4,"height":4})).unwrap(); + s.execute("actions.play", json!({"action":0})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.as_str()).collect::>(), ["Three", "Two", "One", "Four"]); +} + +#[test] +fn new_names_do_not_collide_with_named_calls() { + let mut s = Session::new(); + s.actions.list.push(Action { name: "Action 2".into(), steps: vec![], disabled: Default::default(), ..Default::default() }); + assert_eq!(s.execute("actions.record", json!({})).unwrap()["action"], "Action 3"); + s.execute("actions.stop", json!({})).unwrap(); + assert!(s.execute("actions.record", json!({"name":"Action 2"})).is_err()); + assert!(s.actions.recording.is_none()); +} + +#[test] +fn moving_action_keeps_recording_attached_to_it() { + let mut s = Session::new(); + s.execute("file.new", json!({"width":4,"height":4})).unwrap(); + for name in ["A", "B", "C"] { + s.actions.list.push(Action { name: name.into(), steps: vec![], disabled: Default::default(), ..Default::default() }); + } + s.execute("actions.record", json!({"action":"B"})).unwrap(); + s.execute("layer.new.layer", json!({"name":"before"})).unwrap(); + s.execute("actions.move", json!({"action":"B","to":2})).unwrap(); + s.execute("actions.move", json!({"action":"A","to":2})).unwrap(); + s.execute("layer.new.layer", json!({"name":"after"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[1].name, "B"); + assert_eq!(s.actions.list[1].steps.len(), 2); +} + +#[test] +fn bad_params_do_not_panic() { + let mut s = Session::new(); + let junk = [ + Value::Null, + json!([]), + json!("x"), + json!(1), + json!({"action": true}), + json!({"action": -1}), + json!({"action": 99}), + json!({"action": ""}), + json!({"name": 1}), + json!({"name": ""}), + json!({"from": "start"}), + json!({"from": -3}), + json!({"action": "missing", "from": 4}), + ]; + for id in ["actions.list", "actions.get", "actions.record", "actions.stop", "actions.play", "actions.delete", "actions.move"] { + for p in &junk { + let _ = s.execute(id, p.clone()); + } + } + assert_eq!(s.actions.playing, 0); + assert!(crate::commands::command_specs().iter().any(|c| c.id == "actions.play" && !c.journal && c.menu.is_empty())); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn actions_persist_with_the_preset_store() { + let dir = std::env::temp_dir().join(format!("pc-actions-{}-persist", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + let warnings = s.attach_preset_store(crate::preset_store::open_dir(&dir)); + assert!(warnings.iter().all(|w| !w.contains("actions")), "{warnings:?}"); + s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + s.execute("actions.record", json!({"name": "Kept"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + drop(s); + + let mut t = Session::new(); + t.attach_preset_store(crate::preset_store::open_dir(&dir)); + let listed = t.execute("actions.list", json!({})).unwrap(); + assert_eq!(listed["actions"][0]["name"], "Kept"); + assert_eq!(listed["actions"][0]["steps"], 1); + assert_eq!(t.execute("actions.get", json!({"action": "Kept"})).unwrap()["steps"][0][0], "layer.new.layer"); + + // An action created before the store finishes loading is kept, and a different one on + // disk is merged in. + let mut early = Session::new(); + early.execute("actions.record", json!({"name": "Early"})).unwrap(); + early.execute("actions.stop", json!({})).unwrap(); + early.attach_preset_store(crate::preset_store::open_dir(&dir)); + let names: Vec = early.actions.list.iter().map(|a| a.name.clone()).collect(); + assert!(names.contains(&"Early".into()) && names.contains(&"Kept".into()), "{names:?}"); + + std::fs::write(dir.join("actions.json"), b"{").unwrap(); + let mut bad = Session::new(); + let warnings = bad.attach_preset_store(crate::preset_store::open_dir(&dir)); + assert!(warnings.iter().any(|w| w.contains("actions")), "{warnings:?}"); + assert!(bad.actions.list.is_empty()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// AUTO-219-4: a recording made on one document replays on a second one — a crop, a filter, +/// a selection fill and styled text all act on the document the replay runs in. +#[test] +fn a_recorded_edit_run_replays_on_a_second_document() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); + s.execute("actions.record", json!({"name": "Studio"})).unwrap(); + s.execute("image.crop", json!({"x": 8, "y": 8, "width": 48, "height": 48})).unwrap(); + s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 12, "height": 12})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("type.create", json!({"x": 10, "y": 36, "text": "Hi", "size": 12, "color": "#000000"})).unwrap(); + s.execute("type.setStyle", json!({"fauxBold": true})).unwrap(); + let stopped = s.execute("actions.stop", json!({})).unwrap(); + let steps = stopped["steps"].as_u64().unwrap(); + assert!(steps >= 7, "the recording keeps every family: {stopped}"); + + // The second document: a different size, background and name. The replay must act here. + s.execute("file.new", json!({"width": 100, "height": 80, "background": "black", "name": "Second"})).unwrap(); + let played = s.execute("actions.play", json!({"action": "Studio"})).unwrap(); + assert!(played.get("failed").is_none(), "replay: {played}"); + assert_eq!(played["ran"].as_u64(), Some(steps), "every step ran: {played}"); + let d = &s.active().unwrap().doc; + assert_eq!((d.size.width, d.size.height), (48, 48), "the crop replayed onto the second document"); + assert_eq!(pixel(&s, 0, 16, 16), vec![1.0, 0.0, 0.0, 1.0], "the selection fill replayed"); + assert_eq!(pixel(&s, 0, 2, 2), vec![0.0, 0.0, 0.0, 1.0], "outside the selection stays black"); + let last = d.layers.last().unwrap(); + match &last.content { + photocraft_doc::LayerContent::Text(t) => { + assert_eq!(t.text, "Hi", "the styled text replayed"); + assert!(t.char_runs().iter().any(|r| r.style.faux_bold), "the bold run replayed"); + } + other => panic!("expected the recorded type layer, got {other:?}"), + } + // The first document is untouched. + let first = &s.documents()[0].doc; + assert_eq!((first.size.width, first.size.height), (48, 48), "the recording document keeps its own crop"); +} + +#[test] +fn button_color_is_one_of_the_photoshop_swatches() { + let mut s = Session::new(); + s.execute("actions.record", json!({"name": "Print"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let set = s.execute("actions.setColor", json!({"action": "Print", "color": "blue"})).unwrap(); + assert_eq!(set["color"], "blue"); + assert_eq!(s.actions.list[0].color, "blue"); + assert_eq!(s.execute("actions.get", json!({"action": 0})).unwrap()["color"], "blue"); + let saved = serde_json::to_string(&s.actions.list).unwrap(); + assert!(saved.contains("blue")); + s.execute("actions.setColor", json!({"action": 0, "color": ""})).unwrap(); + assert!(s.actions.list[0].color.is_empty()); + assert!(!serde_json::to_string(&s.actions.list).unwrap().contains("color"), "an empty colour is omitted"); + for bad in [json!({"action": 0, "color": "pink"}), json!({"action": 0}), json!({"action": 4, "color": "red"}), json!({"color": "red"})] { + assert!(s.execute("actions.setColor", bad).is_err()); + } + assert!(s.actions.list[0].color.is_empty(), "rejected colours change nothing"); +} From 7224203641bee7ff234b1b2d68d7007134bc2363 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:19 +0000 Subject: [PATCH 040/259] refactor(engine): move selection_cmds.rs tests to selection_cmds/tests.rs --- crates/engine/src/selection_cmds.rs | 730 +--------------------- crates/engine/src/selection_cmds/tests.rs | 727 +++++++++++++++++++++ 2 files changed, 728 insertions(+), 729 deletions(-) create mode 100644 crates/engine/src/selection_cmds/tests.rs diff --git a/crates/engine/src/selection_cmds.rs b/crates/engine/src/selection_cmds.rs index d6fc50aeea..4b8da7e796 100644 --- a/crates/engine/src/selection_cmds.rs +++ b/crates/engine/src/selection_cmds.rs @@ -710,732 +710,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - bg.fill_rect(Rect::new(5, 5, 15, 15), &[1.0, 0.0, 0.0, 1.0]); - bg.fill_rect(Rect::new(25, 5, 35, 15), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s - } - - fn coverage(s: &Session, x: i32, y: i32) -> f32 { - s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0)) - } - - fn clear_selection(s: &mut Session) { - if s.active().unwrap().doc.selection.is_some() { - s.execute("select.deselect", json!({})).unwrap(); - } - } - - #[test] - fn color_range_skin_tones_selects_skin_not_cream_and_refuses_detect_faces() { - let mut s = session(); - let rgb = |c: [u8; 3]| [f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0]; - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - bg.fill_rect(Rect::new(0, 0, 40, 30), &rgb([252, 253, 247])); - bg.fill_rect(Rect::new(5, 5, 15, 15), &rgb([183, 119, 81])); - bg.fill_rect(Rect::new(25, 5, 35, 15), &rgb([231, 225, 202])); - Ok(()) - }) - .unwrap(); - s.execute("select.colorRange", json!({"select": "skinTones"})).unwrap(); - assert!(coverage(&s, 10, 10) > 0.95, "skin"); - assert!(coverage(&s, 30, 10) < 0.05, "cream"); - assert!(coverage(&s, 2, 2) < 0.05, "near-white background"); - // Subtracting skin from a selection of both squares keeps only the cream one. - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 30, "height": 10})).unwrap(); - s.execute("select.colorRange", json!({"select": "skinTones", "mode": "subtract"})).unwrap(); - assert!(coverage(&s, 10, 10) < 0.05 && coverage(&s, 30, 10) > 0.95, "{} {}", coverage(&s, 10, 10), coverage(&s, 30, 10)); - let err = s.execute("select.colorRange", json!({"select": "skinTones", "detectFaces": true})).unwrap_err(); - assert!(err.to_string().contains("detectFaces"), "{err}"); - } - - #[test] - fn selection_sampling_refuses_oversized_canvases_before_reading_pixels() { - let mut s = Session::new(); - s.add_document( - photocraft_doc::Document::new( - "large", - photocraft_geom::Size::new(300_000, 300_000), - photocraft_color::ColorMode::Rgb, - photocraft_color::SampleType::U8, - ), - None, - ); - for all_layers in [false, true] { - assert!(sample_pixels(&s, all_layers).unwrap_err().to_string().contains("too large to sample")); - } - assert!(!s.active().unwrap().history.can_undo()); - } - - #[test] - fn selection_sampling_allocation_failure_keeps_the_selection() { - let mut s = session(); - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 4, "height": 4})).unwrap(); - let before = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.entries(); - crate::allocation::fail_next_for_test(); - let result = s.execute("select.similar", json!({"sampleAllLayers": false})); - let _ = crate::allocation::capacity::(0, "reset failpoint"); - assert!(result.is_err()); - assert_eq!(*s.active().unwrap().doc, *before); - assert_eq!(s.active().unwrap().history.entries(), history); - } - - #[test] - fn modify_rejects_oversized_canvases_before_reading_the_mask() { - let mut s = Session::new(); - let mut doc = photocraft_doc::Document::new( - "large", - photocraft_geom::Size::new(300_000, 300_000), - photocraft_color::ColorMode::Rgb, - photocraft_color::SampleType::U8, - ); - let mut selection = photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8); - selection.write_pixel(0, 0, &[1.0]); - doc.selection = Some(selection); - s.add_document(doc, None); - let before = s.active().unwrap().doc.clone(); - for op in ["expand", "contract", "border", "smooth", "feather"] { - let error = s.execute(&format!("select.modify.{op}"), json!({"radius": 1})).unwrap_err(); - assert!(error.to_string().contains("too large to modify")); - assert_eq!(*s.active().unwrap().doc, *before); - assert!(!s.active().unwrap().history.can_undo()); - } - } - - #[test] - fn color_range_replace_is_bounded_by_existing_selection() { - for params in [json!({"color": "#ff0000", "fuzziness": 0}), json!({"select": "reds"})] { - let mut s = session(); - // Both red squares match, but only the left is inside the original selection. - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); - s.execute("select.colorRange", params).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0); - assert_eq!(coverage(&s, 30, 10), 0.0); - assert_eq!(coverage(&s, 2, 2), 0.0); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0); - assert_eq!(coverage(&s, 30, 10), 0.0); - } - } - - #[test] - fn color_range_invert_and_partial_masks_stay_within_prior_selection() { - let mut s = session(); - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); - s.execute("select.colorRange", json!({"select": "highlights", "invert": true})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0, "inverted white excludes the white background"); - assert_eq!(coverage(&s, 20, 20), 0.0, "invert must not select outside the old boundary"); - - let mut s = session(); - s.edit("soft selection", |doc, _| { - let mut mask = vec![0.0; 40 * 30]; - mask[10 * 40 + 10] = 128.0 / 255.0; - doc.selection = Some(sel::mask_to_surface(&mask, doc.bounds())); - Ok(()) - }) - .unwrap(); - s.execute("select.colorRange", json!({"select": "reds"})).unwrap(); - assert!((coverage(&s, 10, 10) - 128.0 / 255.0).abs() < 0.001); - assert_eq!(coverage(&s, 30, 10), 0.0); - } - - #[test] - fn color_range_eyedropper_samples_anywhere_but_the_result_stays_in_the_selection() { - // #5244: as in Photoshop, a colour picked outside the active selection is accepted; only - // the result is limited to the selection. - let mut s = session(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); - let outside = json!({"points": [[30, 10]], "fuzziness": 0}); - assert!(ColorRangeSamples::new(&s, &outside).is_ok()); - s.execute("select.colorRange", outside).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0, "the red inside the selection is selected"); - assert_eq!(coverage(&s, 30, 10), 0.0, "the sampled red outside it stays out"); - assert_eq!(coverage(&s, 2, 2), 0.0, "white is not the sampled colour"); - } - - #[test] - fn color_range_eyedropper_respects_selection_but_add_can_extend_it() { - let mut s = session(); - s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); - s.execute("select.colorRange", json!({"points": [[10, 10]], "fuzziness": 0})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0); - assert_eq!(coverage(&s, 30, 10), 0.0); - - // Explicitly adding a matching colour is still allowed to grow the selection. - s.execute("select.colorRange", json!({"points": [[30, 10]], "fuzziness": 0, "mode": "add"})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0); - assert_eq!(coverage(&s, 30, 10), 1.0); - - clear_selection(&mut s); - s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 0})).unwrap(); - assert_eq!(coverage(&s, 30, 10), 1.0, "an unbounded color range still searches the canvas"); - } - - #[test] - fn magic_wand_selects_the_visible_alpha_or_mask_not_the_rgb() { - let mut s = session(); - // Alpha covers the first red square and the pixels beside it. RGB would stop at the red. - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - s.execute("channel.new", json!({"fill": "selection", "name": "Alpha"})).unwrap(); - s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 7, 7), 1.0); - assert_eq!(coverage(&s, 2, 2), 1.0, "the white alpha includes pixels that are not the red square"); - assert_eq!(coverage(&s, 30, 10), 0.0, "outside the alpha stays unselected"); - // Colour channels back on: the wand reads RGB again. - s.execute("channel.setVisible", json!({"channel": "composite", "visible": true})).unwrap(); - s.execute("channel.setVisible", json!({"channel": 0, "visible": false})).unwrap(); - s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 7, 7), 1.0); - assert_eq!(coverage(&s, 2, 2), 0.0, "RGB sampling stops at the red square"); - // Eyes off again, Alpha still the picture. - s.execute("channel.setVisible", json!({"channel": 0, "visible": true})).unwrap(); - s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); - s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 2, 2), 1.0); - - let mut s = session(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); - s.execute("view.layerMask", json!({"mode": "gray"})).unwrap(); - s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 2, 2), 1.0, "gray mask view selects the mask"); - assert_eq!(coverage(&s, 30, 10), 0.0); - s.execute("view.layerMask", json!({"mode": "off"})).unwrap(); - for name in ["red", "green", "blue"] { - s.execute("channel.setVisible", json!({"channel": name, "visible": false})).unwrap(); - } - s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 2, 2), 1.0, "a layer mask shown alone is what the wand reads"); - assert_eq!(coverage(&s, 30, 10), 0.0); - } - - #[test] - fn magic_wand_contiguous_and_modes() { - let mut s = session(); - s.execute("select.magicWand", json!({"x": 7, "y": 7, "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0); - assert_eq!(coverage(&s, 30, 10), 0.0); - s.execute("select.magicWand", json!({"x": 30, "y": 7, "mode": "add", "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 30, 10), 1.0); - s.execute("select.magicWand", json!({"x": 7, "y": 7, "mode": "subtract", "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 0.0); - s.execute("select.magicWand", json!({"x": 7, "y": 7, "contiguous": false, "antiAlias": false})).unwrap(); - assert_eq!(coverage(&s, 30, 10), 1.0); - } - - #[test] - fn color_range_prepared_query_matches_the_command_at_all_depths() { - use photocraft_doc::{Color, ColorMode, SampleType, Size}; - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for profile in [None, Some(photocraft_cms::Builtin::DisplayP3.profile().to_bytes())] { - let mut doc = Document::with_background("samples", Size::new(24, 12), ColorMode::Rgb, depth, Color::WHITE); - doc.icc_profile = profile; - let layer = doc.layers[0].surface_mut().unwrap(); - layer.fill_rect(Rect::new(0, 0, 8, 12), &[0.65, 0.3, 0.2, 1.0]); - layer.fill_rect(Rect::new(8, 0, 16, 12), &[0.2, 0.3, 0.65, 1.0]); - let mut s = Session::new(); - s.add_document(doc, None); - for p in [ - json!({"points": [[2, 3]], "fuzziness": 0}), - json!({"points": [[2, 3], [10, 3]], "subtractPoints": [[10, 3]], "order": ["+", "+", "-"], "fuzziness": 40}), - json!({"points": [[2, 3]], "localized": true, "range": 50, "fuzziness": 80}), - ] { - clear_selection(&mut s); - let q = ColorRangeSamples::new(&s, &p).unwrap(); - let doc = s.active().unwrap().doc.clone(); - let pixels = photocraft_compose::render(&doc, doc.bounds()); - let preview = q.coverage(&pixels.px, 24, 1.0, [0.0, 0.0]); - s.execute("select.colorRange", p).unwrap(); - let actual = current_mask(&s.active().unwrap().doc).1; - for (shown, selected) in preview.iter().zip(actual) { - let rounded = (shown.clamp(0.0, 1.0) * 255.0 + 0.5).floor() / 255.0; - assert_eq!(rounded, selected, "{depth:?}: original-pixel preview and OK differ"); - } - } - } - } - } - - #[test] - fn color_range_prepared_query_samples_visible_layers_not_the_active_layer() { - use photocraft_doc::{Layer, LayerContent}; - let mut s = session_colours(); - let doc = s.active().unwrap().doc.clone(); - let mut top = Layer::new("blue foreground", LayerContent::Raster(doc.layers[0].surface().unwrap().clone())); - top.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 40, 30), &[0.0, 0.0, 1.0, 1.0]); - let mut hidden = Layer::new("hidden green", LayerContent::Raster(top.surface().unwrap().clone())); - hidden.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 40, 30), &[0.0, 1.0, 0.0, 1.0]); - hidden.visible = false; - s.edit("layers", |doc, _| { - doc.layers.push(top); - doc.layers.push(hidden); - Ok(()) - }) - .unwrap(); - for all_layers in [false, true] { - clear_selection(&mut s); - let p = json!({"points": [[7, 7]], "sampleAllLayers": all_layers, "fuzziness": 0}); - let query = ColorRangeSamples::new(&s, &p).unwrap(); - let (area, px) = sample_pixels(&s, all_layers).unwrap(); - let shown = query.coverage(&px, area.width() as usize, 1.0, [0.0, 0.0]); - s.execute("select.colorRange", p).unwrap(); - assert_eq!(shown[7 * 40 + 7], coverage(&s, 7, 7)); - assert_eq!(shown[24 * 40 + 10], coverage(&s, 10, 24)); - } - for p in [json!({"points": [[-1, 0]]}), json!({"points": [[40, 1]]}), json!({"points": "wrong"}), json!({"points": [[null, 0]]})] { - assert!(ColorRangeSamples::new(&s, &p).is_err(), "{p}"); - } - } - - #[test] - fn color_range_selects_by_colour() { - let mut s = session(); - s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 40})).unwrap(); - // The sampled colour itself is fully selected (as with Photoshop's eyedropper). - assert_eq!(coverage(&s, 10, 10), 1.0); - assert_eq!(coverage(&s, 20, 20), 0.0); - s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 100})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0); - assert_eq!(coverage(&s, 20, 20), 0.0); - } - - #[test] - fn color_range_compares_in_lab_like_photoshop() { - // Photoshop weighs hue (Lab a/b) three times as much as lightness; a per-channel RGB - // distance can't tell a lighter shade from a redder one. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 30, "height": 10})).unwrap(); - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - let v = |c: u8| f32::from(c) / 255.0; - bg.fill_rect(Rect::new(0, 0, 10, 10), &[v(200), v(140), v(120), 1.0]); // skin - bg.fill_rect(Rect::new(10, 0, 20, 10), &[v(220), v(160), v(140), 1.0]); // lighter skin - bg.fill_rect(Rect::new(20, 0, 30, 10), &[v(220), v(140), v(120), 1.0]); // redder skin - Ok(()) - }) - .unwrap(); - s.execute("select.colorRange", json!({"points": [[5, 5]], "fuzziness": 40})).unwrap(); - assert!(coverage(&s, 5, 5) > 0.98); - // Both differ from the sample by 20 levels in one RGB channel, yet the lighter one is - // kept clearly more (about 0.55 vs 0.31). - let (lighter, redder) = (coverage(&s, 15, 5), coverage(&s, 25, 5)); - assert!(lighter > redder + 0.15 && redder > 0.0, "lighter {lighter}, redder {redder}"); - } - - #[test] - fn color_range_fuzziness_zero_selects_exact_match_only() { - // Sampled Colors at Fuzziness 0 selects only the exact match (TOOL-214-3, #214). - let mut s = Session::new(); - s.execute("file.new", json!({"width": 50, "height": 10})).unwrap(); - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - let v = |c: u8| f32::from(c) / 255.0; - // Exact target color [200, 140, 120] - bg.fill_rect(Rect::new(0, 0, 10, 10), &[v(200), v(140), v(120), 1.0]); - // Off by 1 level in red [201, 140, 120] - bg.fill_rect(Rect::new(10, 0, 20, 10), &[v(201), v(140), v(120), 1.0]); - // Off by 1 level in green [200, 141, 120] - bg.fill_rect(Rect::new(20, 0, 30, 10), &[v(200), v(141), v(120), 1.0]); - // Off by 2 levels in blue [200, 140, 122] (crosses 8-bit Lab grid threshold) - bg.fill_rect(Rect::new(30, 0, 40, 10), &[v(200), v(140), v(122), 1.0]); - // Exact target color again at a different position - bg.fill_rect(Rect::new(40, 0, 50, 10), &[v(200), v(140), v(120), 1.0]); - Ok(()) - }) - .unwrap(); - - // Sampled via eyedropper point at [5, 5] with Fuzziness 0 - s.execute("select.colorRange", json!({"points": [[5, 5]], "fuzziness": 0})).unwrap(); - assert_eq!(coverage(&s, 5, 5), 1.0, "sampled pixel itself is fully selected"); - assert_eq!(coverage(&s, 45, 5), 1.0, "identical color elsewhere on canvas is fully selected"); - assert_eq!(coverage(&s, 15, 5), 0.0, "1 level off in red is unselected at fuzziness 0"); - assert_eq!(coverage(&s, 25, 5), 0.0, "1 level off in green is unselected at fuzziness 0"); - assert_eq!(coverage(&s, 35, 5), 0.0, "1 level off in blue is unselected at fuzziness 0"); - - // Sampled via hex color with Fuzziness 0 - s.execute("select.colorRange", json!({"color": "#c88c78", "fuzziness": 0})).unwrap(); - assert_eq!(coverage(&s, 5, 5), 1.0, "exact color match from hex is fully selected"); - assert_eq!(coverage(&s, 45, 5), 1.0, "identical color elsewhere on canvas is fully selected"); - assert_eq!(coverage(&s, 15, 5), 0.0, "1 level off in red is unselected for hex at fuzziness 0"); - assert_eq!(coverage(&s, 25, 5), 0.0, "1 level off in green is unselected for hex at fuzziness 0"); - assert_eq!(coverage(&s, 35, 5), 0.0, "1 level off in blue is unselected for hex at fuzziness 0"); - } - - /// Red squares (from `session`), a blue square, a black and a mid-grey strip on white. - fn session_colours() -> Session { - let mut s = session(); - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - bg.fill_rect(Rect::new(5, 20, 15, 28), &[0.0, 0.0, 1.0, 1.0]); - bg.fill_rect(Rect::new(20, 20, 25, 28), &[0.0, 0.0, 0.0, 1.0]); - bg.fill_rect(Rect::new(30, 20, 35, 28), &[0.5, 0.5, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - s - } - - #[test] - fn color_range_several_samples_points_and_invert() { - let mut s = session_colours(); - // Several samples span one Lab box (Photoshop's Minimum/Maximum): red and blue take - // both squares, black, grey and white stay out. - s.execute("select.colorRange", json!({"colors": ["#ff0000", "#0000ff"], "fuzziness": 100})).unwrap(); - assert_eq!((coverage(&s, 10, 10), coverage(&s, 30, 10), coverage(&s, 10, 24)), (1.0, 1.0, 1.0)); - assert_eq!((coverage(&s, 2, 2), coverage(&s, 22, 24), coverage(&s, 32, 24)), (0.0, 0.0, 0.0)); - // Eyedropper point on the blue square; `invert` flips the result. - clear_selection(&mut s); - s.execute("select.colorRange", json!({"points": [[7, 22]], "fuzziness": 100, "invert": true})).unwrap(); - assert_eq!((coverage(&s, 10, 24), coverage(&s, 10, 10), coverage(&s, 2, 2)), (0.0, 1.0, 1.0)); - // Localized clusters: picked on the left red square, a 25% range (10 px) leaves the right one. - clear_selection(&mut s); - s.execute("select.colorRange", json!({"points": [[10, 10]], "fuzziness": 100, "localized": true, "range": 25})).unwrap(); - assert_eq!(coverage(&s, 10, 10), 1.0); - assert!(coverage(&s, 13, 10) > 0.5); - assert_eq!(coverage(&s, 30, 10), 0.0); - // Undo restores the empty selection that preceded the most recent Color Range. - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(coverage(&s, 2, 2), 0.0); - } - - #[test] - fn color_range_subtract_follows_photoshop_and_the_click_order() { - // Grey strips from dark to light; samples at both ends span the whole run. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 50, "height": 10})).unwrap(); - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - for (i, v) in [0.30f32, 0.40, 0.50, 0.60, 0.70].iter().enumerate() { - bg.fill_rect(Rect::new(i as i32 * 10, 0, i as i32 * 10 + 10, 10), &[*v, *v, *v, 1.0]); - } - Ok(()) - }) - .unwrap(); - let run = |s: &mut Session, extra: Value| { - clear_selection(s); - let mut p = json!({"points": [[5, 5], [45, 5]], "fuzziness": 10}); - p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); - s.execute("select.colorRange", p).unwrap(); - (0..5).map(|i| coverage(s, i * 10 + 5, 5)).collect::>() - }; - assert!(run(&mut s, json!({})).iter().all(|v| *v > 0.99), "both samples span every strip"); - // Subtracting a colour inside the range moves the nearer edge onto it: the strips beyond - // it drop out, the subtracted grey itself stays selected (Photoshop does the same). - let cut = run(&mut s, json!({"subtractPoints": [[15, 5]]})); - assert!(cut[0] < 0.5 && cut[1] > 0.99 && cut[4] > 0.99, "{cut:?}"); - // Order matters: adding the dark strip back after the subtraction restores it. - let readd = run(&mut s, json!({"points": [[5, 5], [45, 5], [5, 5]], "subtractPoints": [[15, 5]], "order": ["+", "+", "-", "+"]})); - assert!(readd[0] > 0.99, "{readd:?}"); - let sub_last = run(&mut s, json!({"points": [[5, 5], [45, 5], [5, 5]], "subtractPoints": [[15, 5]], "order": ["+", "+", "+", "-"]})); - assert!(sub_last[0] < 0.5, "{sub_last:?}"); - // A malformed or inconsistent order is an error, never a panic. - clear_selection(&mut s); - for bad in [json!(["+"]), json!(["+", "+", "x"]), json!("+-"), json!(["-", "-", "+"])] { - assert!(s.execute("select.colorRange", json!({"points": [[5, 5], [45, 5]], "subtractPoints": [[15, 5]], "order": bad})).is_err(), "{bad}"); - } - } - - #[test] - fn color_range_presets() { - let mut s = session_colours(); - s.execute("select.colorRange", json!({"select": "reds"})).unwrap(); - assert_eq!((coverage(&s, 10, 10), coverage(&s, 30, 10)), (1.0, 1.0)); - assert_eq!((coverage(&s, 10, 24), coverage(&s, 2, 2), coverage(&s, 32, 24)), (0.0, 0.0, 0.0)); - clear_selection(&mut s); - s.execute("select.colorRange", json!({"select": "blues"})).unwrap(); - assert_eq!((coverage(&s, 10, 24), coverage(&s, 10, 10)), (1.0, 0.0)); - clear_selection(&mut s); - s.execute("select.colorRange", json!({"select": "greens"})).unwrap(); - assert!(s.active().unwrap().doc.selection.is_none() || coverage(&s, 10, 10) == 0.0); - // Tones: black is a shadow, white a highlight, 50% grey (128) a midtone. - clear_selection(&mut s); - s.execute("select.colorRange", json!({"select": "shadows"})).unwrap(); - assert_eq!((coverage(&s, 22, 24), coverage(&s, 2, 2), coverage(&s, 32, 24)), (1.0, 0.0, 0.0)); - clear_selection(&mut s); - s.execute("select.colorRange", json!({"select": "highlights"})).unwrap(); - assert_eq!((coverage(&s, 22, 24), coverage(&s, 2, 2)), (0.0, 1.0)); - clear_selection(&mut s); - s.execute("select.colorRange", json!({"select": "midtones", "fuzziness": 0})).unwrap(); - assert_eq!((coverage(&s, 32, 24), coverage(&s, 2, 2), coverage(&s, 22, 24)), (1.0, 0.0, 0.0)); - // A wider shadow range takes the grey too. - clear_selection(&mut s); - s.execute("select.colorRange", json!({"select": "shadows", "tonalRange": 140, "fuzziness": 0})).unwrap(); - assert_eq!(coverage(&s, 32, 24), 1.0); - // Modes combine as for the other selection commands. - s.execute("select.colorRange", json!({"select": "reds", "mode": "add"})).unwrap(); - assert_eq!((coverage(&s, 32, 24), coverage(&s, 10, 10)), (1.0, 1.0)); - } - - #[test] - fn color_range_out_of_gamut_matches_the_gamut_warning() { - let mut s = session(); - s.edit("paint", |doc, _| { - // Saturated sRGB blue is outside the default CMYK proof; mid grey is inside. - let bg = doc.layers[0].surface_mut().unwrap(); - bg.fill_rect(Rect::new(0, 20, 20, 30), &[0.0, 0.0, 1.0, 1.0]); - bg.fill_rect(Rect::new(20, 20, 40, 30), &[0.5, 0.5, 0.5, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("select.colorRange", json!({"select": "outOfGamut"})).unwrap(); - assert_eq!((coverage(&s, 5, 25), coverage(&s, 30, 25)), (1.0, 0.0)); - let warn = s.execute("view.gamutWarning", json!({"on": true})).unwrap(); - let sel = s.active().unwrap().doc.selection.clone().unwrap(); - let mut n = 0; - for y in 0..30 { - for x in 0..40 { - n += usize::from(sel.sample_channel(x, y, 0) > 0.5); - } - } - assert_eq!(warn["outOfGamut"].as_u64(), Some(n as u64)); - } - - #[test] - fn color_range_rejects_bad_params() { - let mut s = session_colours(); - for p in [ - json!({"select": "skin"}), - json!({"select": 3}), - json!({"points": [[100, 2]]}), - json!({"points": [[1]]}), - json!({"points": "here"}), - json!({"colors": "#ff0000"}), - json!({"localized": true}), - json!({"select": "midtones", "tonalRange": [200, 100]}), - json!({"select": "shadows", "tonalRange": 300}), - ] { - assert!(s.execute("select.colorRange", p.clone()).is_err(), "{p}"); - } - assert!(s.active().unwrap().doc.selection.is_none()); - } - - #[test] - fn modify_commands() { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("select.modify.expand", json!({"radius": 2})).unwrap(); - assert_eq!(coverage(&s, 8, 15), 1.0); - s.execute("select.modify.contract", json!({"radius": 4})).unwrap(); - assert_eq!(coverage(&s, 11, 15), 0.0); - assert_eq!(coverage(&s, 15, 15), 1.0); - s.execute("select.modify.border", json!({"radius": 2})).unwrap(); - assert_eq!(coverage(&s, 15, 15), 0.0); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("select.modify.feather", json!({"radius": 4})).unwrap(); - let e = coverage(&s, 10, 15); - assert!(e > 0.2 && e < 0.8, "{e}"); - s.execute("select.modify.smooth", json!({"radius": 2})).unwrap(); - assert!(s.active().unwrap().doc.selection.is_some()); - assert!(!s.is_enabled("select.nothing")); - // Out-of-range or non-finite radii are refused and leave the selection alone. - for op in ["feather", "smooth", "expand", "contract", "border"] { - for r in [json!(1e300), json!(5000), json!(f64::MAX), json!(-5), json!(-0.5), json!(f64::MIN)] { - assert!(s.execute(&format!("select.modify.{op}"), json!({"radius": r})).is_err(), "{op} {r}"); - } - } - assert!(s.active().unwrap().doc.selection.is_some()); - } - - #[test] - fn modify_select_all_honours_canvas_bounds() { - let all = || { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); - s.execute("select.all", json!({})).unwrap(); - s - }; - // Off (Photoshop's default): the selection continues past the canvas, so the edges stay. - for op in ["contract", "smooth", "expand", "feather"] { - let mut s = all(); - s.execute(&format!("select.modify.{op}"), json!({"radius": 4})).unwrap(); - assert_eq!(coverage(&s, 0, 15), 1.0, "{op}"); - assert_eq!(coverage(&s, 20, 0), 1.0, "{op}"); - } - // On: the canvas edge is a selection edge (#1277). - let mut s = all(); - s.execute("select.modify.contract", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap(); - assert_eq!(coverage(&s, 2, 15), 0.0); - assert_eq!(coverage(&s, 20, 28), 0.0); - assert_eq!(coverage(&s, 20, 15), 1.0); - let mut s = all(); - s.execute("select.modify.feather", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap(); - let e = coverage(&s, 0, 15); - assert!(e > 0.2 && e < 0.8, "{e}"); - assert_eq!(coverage(&s, 20, 15), 1.0); - let mut s = all(); - s.execute("select.modify.smooth", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap(); - assert!(coverage(&s, 0, 0) < 1.0); - // Border always follows the canvas edge: a band inside it, not an empty selection. - let mut s = all(); - s.execute("select.modify.border", json!({"radius": 4})).unwrap(); - assert!(coverage(&s, 0, 15) > 0.0); - assert_eq!(coverage(&s, 20, 15), 0.0); - } - - #[test] - fn modify_away_from_the_canvas_edge_ignores_canvas_bounds() { - for at in [false, true] { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("select.modify.contract", json!({"radius": 4, "applyAtCanvasBounds": at})).unwrap(); - assert_eq!(coverage(&s, 11, 15), 0.0); - assert_eq!(coverage(&s, 15, 15), 1.0); - } - } - - #[test] - fn modify_refuses_radii_below_the_minimum() { - let mut s = session(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - // Below each dialog's minimum (1 px, Feather 0.1 px) is refused, not clamped to 0: a - // negative Border radius used to clear the selection and report success (#993). - let below = [ - ("border", -5.0), - ("border", 0.5), - ("smooth", -5.0), - ("smooth", 0.0), - ("expand", -5.0), - ("expand", 0.0), - ("contract", -5.0), - ("contract", 0.9), - ("feather", -5.0), - ("feather", 0.0), - ("feather", 0.05), - ]; - let before = current_mask(&s.active().unwrap().doc).1; - for (op, r) in below { - let err = s.execute(&format!("select.modify.{op}"), json!({"radius": r})).unwrap_err(); - assert!(matches!(err, EngineError::BadParams { .. }), "{op} {r}: {err}"); - assert!(current_mask(&s.active().unwrap().doc).1 == before, "{op} {r}: the selection changed"); - } - // The minimum itself is still accepted. - s.execute("select.modify.feather", json!({"radius": 0.1})).unwrap(); - s.execute("select.modify.expand", json!({"radius": 1})).unwrap(); - assert_eq!(coverage(&s, 9, 15), 1.0); - } - - #[test] - fn geometry_params_that_would_wrap_are_rejected() { - let mut s = session(); - // 2^32 + 50 wrapped to `x = 50` and 3e9 to a negative coordinate through `as i32`; - // both are bad-params errors now, whatever the front door (UI, CLI, control, MCP). - for x in [4_294_967_346_i64, 3_000_000_000_i64] { - let err = s.execute("select.rect", json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap_err(); - assert!(err.to_string().contains("32-bit"), "{err}"); - } - let err = s.execute("document.pixel", json!({"x": 4_294_967_346_i64, "y": 0})).unwrap_err(); - assert!(err.to_string().contains("32 bits"), "{err}"); - // In-range coordinates, including negative and past-canvas ones, are unaffected. - s.execute("select.rect", json!({"x": -100, "y": -100, "width": 500, "height": 500})).unwrap(); - s.execute("document.pixel", json!({"x": 0, "y": 0})).unwrap(); - } - - #[test] - fn grow_and_similar() { - let mut s = session(); - s.execute("select.rect", json!({"x": 6, "y": 6, "width": 2, "height": 2})).unwrap(); - s.execute("select.grow", json!({"tolerance": 5})).unwrap(); - assert_eq!(coverage(&s, 14, 14), 1.0); - assert_eq!(coverage(&s, 30, 10), 0.0); - s.execute("select.similar", json!({"tolerance": 5})).unwrap(); - assert_eq!(coverage(&s, 30, 10), 1.0); - assert_eq!(coverage(&s, 20, 20), 0.0); - } - - #[test] - fn lasso_polygon() { - let mut s = session(); - s.execute("select.lasso", json!({"points": [[0, 0], [20, 0], [0, 20]]})).unwrap(); - assert_eq!(coverage(&s, 2, 2), 1.0); - assert_eq!(coverage(&s, 18, 18), 0.0); - assert!(s.execute("select.lasso", json!({"points": [[0, 0], [1, 1]]})).is_err()); - s.execute("select.lasso", json!({"points": [[0, 0], [20, 0], [0, 20]], "mode": "subtract"})).unwrap(); - assert!(s.active().unwrap().doc.selection.is_none()); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(coverage(&s, 2, 2), 1.0); - } - - /// The previous per-sample padding and cropping, kept as the oracle for the row-wise ones. - fn old_pad_mask(m: &[f32], w: usize, h: usize, pad: usize, outside_empty: bool) -> Vec { - let pw = w + 2 * pad; - let mut out = vec![0.0f32; pw * (h + 2 * pad)]; - for (py, row) in out.chunks_exact_mut(pw).enumerate() { - let inside_y = (pad..pad + h).contains(&py); - if outside_empty && !inside_y { - continue; - } - let y = py.saturating_sub(pad).min(h - 1); - for (px, v) in row.iter_mut().enumerate() { - if outside_empty && !(pad..pad + w).contains(&px) { - continue; - } - *v = m.get(y * w + px.saturating_sub(pad).min(w - 1)).copied().unwrap_or(0.0); - } - } - out - } - - #[test] - fn row_wise_pad_and_crop_match_per_sample_ones() { - let mut seed = 0x2545_f491_4f6c_dd1du64; - let (w, h) = (37, 23); - let m: Vec = (0..w * h) - .map(|_| { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - (seed % 1000) as f32 / 999.0 - }) - .collect(); - for pad in [0, 1, 5, 40] { - for outside_empty in [false, true] { - let padded = pad_mask(&m, w, h, pad, outside_empty); - assert_eq!(padded, old_pad_mask(&m, w, h, pad, outside_empty), "pad {pad} {outside_empty}"); - assert_eq!(crop_mask(&padded, w + 2 * pad, pad, w, h), m, "pad {pad}"); - } - } - } - - /// The lasso over the polygon's rows gives exactly the whole-canvas result (#4532): random - /// polygons, partly off the canvas, with and without anti-aliasing, in every mode over an - /// existing selection. - #[test] - fn lasso_over_its_rows_matches_the_whole_canvas() { - let mut seed = 0x2545_f491_u32; - let mut rnd = |lo: f32, hi: f32| { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - lo + (seed % 10_000) as f32 / 10_000.0 * (hi - lo) - }; - for case in 0..24 { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 300, "height": 520})).unwrap(); - s.execute("select.rect", json!({"x": 40, "y": 60, "width": 200, "height": 300})).unwrap(); - let n = 3 + case % 7; - let pts: Vec<(f32, f32)> = (0..n).map(|_| (rnd(-30.0, 330.0), rnd(100.0, 420.0))).collect(); - let aa = case % 2 == 0; - let m = ["replace", "add", "subtract", "intersect"][case % 4]; - let doc = s.active().unwrap().doc.clone(); - let area = doc.bounds(); - let want = sel::combine(doc.selection.as_ref(), &sel::polygon(&pts, area, aa), area, SelectionMode::parse(m)); - let points: Vec<[f32; 2]> = pts.iter().map(|p| [p.0, p.1]).collect(); - s.execute("select.lasso", json!({"points": points, "antiAlias": aa, "mode": m})).unwrap(); - let got = s.active().unwrap().doc.selection.clone(); - let read = |x: &Option| x.as_ref().map(|s| s.read_region(area)); - assert_eq!(read(&got), read(&want), "case {case}: {m}, anti-alias {aa}, {pts:?}"); - } - } -} +mod tests; diff --git a/crates/engine/src/selection_cmds/tests.rs b/crates/engine/src/selection_cmds/tests.rs new file mode 100644 index 0000000000..602262dc7f --- /dev/null +++ b/crates/engine/src/selection_cmds/tests.rs @@ -0,0 +1,727 @@ +use super::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + bg.fill_rect(Rect::new(5, 5, 15, 15), &[1.0, 0.0, 0.0, 1.0]); + bg.fill_rect(Rect::new(25, 5, 35, 15), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +fn coverage(s: &Session, x: i32, y: i32) -> f32 { + s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0)) +} + +fn clear_selection(s: &mut Session) { + if s.active().unwrap().doc.selection.is_some() { + s.execute("select.deselect", json!({})).unwrap(); + } +} + +#[test] +fn color_range_skin_tones_selects_skin_not_cream_and_refuses_detect_faces() { + let mut s = session(); + let rgb = |c: [u8; 3]| [f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0]; + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + bg.fill_rect(Rect::new(0, 0, 40, 30), &rgb([252, 253, 247])); + bg.fill_rect(Rect::new(5, 5, 15, 15), &rgb([183, 119, 81])); + bg.fill_rect(Rect::new(25, 5, 35, 15), &rgb([231, 225, 202])); + Ok(()) + }) + .unwrap(); + s.execute("select.colorRange", json!({"select": "skinTones"})).unwrap(); + assert!(coverage(&s, 10, 10) > 0.95, "skin"); + assert!(coverage(&s, 30, 10) < 0.05, "cream"); + assert!(coverage(&s, 2, 2) < 0.05, "near-white background"); + // Subtracting skin from a selection of both squares keeps only the cream one. + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 30, "height": 10})).unwrap(); + s.execute("select.colorRange", json!({"select": "skinTones", "mode": "subtract"})).unwrap(); + assert!(coverage(&s, 10, 10) < 0.05 && coverage(&s, 30, 10) > 0.95, "{} {}", coverage(&s, 10, 10), coverage(&s, 30, 10)); + let err = s.execute("select.colorRange", json!({"select": "skinTones", "detectFaces": true})).unwrap_err(); + assert!(err.to_string().contains("detectFaces"), "{err}"); +} + +#[test] +fn selection_sampling_refuses_oversized_canvases_before_reading_pixels() { + let mut s = Session::new(); + s.add_document( + photocraft_doc::Document::new( + "large", + photocraft_geom::Size::new(300_000, 300_000), + photocraft_color::ColorMode::Rgb, + photocraft_color::SampleType::U8, + ), + None, + ); + for all_layers in [false, true] { + assert!(sample_pixels(&s, all_layers).unwrap_err().to_string().contains("too large to sample")); + } + assert!(!s.active().unwrap().history.can_undo()); +} + +#[test] +fn selection_sampling_allocation_failure_keeps_the_selection() { + let mut s = session(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 4, "height": 4})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.entries(); + crate::allocation::fail_next_for_test(); + let result = s.execute("select.similar", json!({"sampleAllLayers": false})); + let _ = crate::allocation::capacity::(0, "reset failpoint"); + assert!(result.is_err()); + assert_eq!(*s.active().unwrap().doc, *before); + assert_eq!(s.active().unwrap().history.entries(), history); +} + +#[test] +fn modify_rejects_oversized_canvases_before_reading_the_mask() { + let mut s = Session::new(); + let mut doc = photocraft_doc::Document::new( + "large", + photocraft_geom::Size::new(300_000, 300_000), + photocraft_color::ColorMode::Rgb, + photocraft_color::SampleType::U8, + ); + let mut selection = photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8); + selection.write_pixel(0, 0, &[1.0]); + doc.selection = Some(selection); + s.add_document(doc, None); + let before = s.active().unwrap().doc.clone(); + for op in ["expand", "contract", "border", "smooth", "feather"] { + let error = s.execute(&format!("select.modify.{op}"), json!({"radius": 1})).unwrap_err(); + assert!(error.to_string().contains("too large to modify")); + assert_eq!(*s.active().unwrap().doc, *before); + assert!(!s.active().unwrap().history.can_undo()); + } +} + +#[test] +fn color_range_replace_is_bounded_by_existing_selection() { + for params in [json!({"color": "#ff0000", "fuzziness": 0}), json!({"select": "reds"})] { + let mut s = session(); + // Both red squares match, but only the left is inside the original selection. + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + s.execute("select.colorRange", params).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 30, 10), 0.0); + assert_eq!(coverage(&s, 2, 2), 0.0); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 30, 10), 0.0); + } +} + +#[test] +fn color_range_invert_and_partial_masks_stay_within_prior_selection() { + let mut s = session(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + s.execute("select.colorRange", json!({"select": "highlights", "invert": true})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0, "inverted white excludes the white background"); + assert_eq!(coverage(&s, 20, 20), 0.0, "invert must not select outside the old boundary"); + + let mut s = session(); + s.edit("soft selection", |doc, _| { + let mut mask = vec![0.0; 40 * 30]; + mask[10 * 40 + 10] = 128.0 / 255.0; + doc.selection = Some(sel::mask_to_surface(&mask, doc.bounds())); + Ok(()) + }) + .unwrap(); + s.execute("select.colorRange", json!({"select": "reds"})).unwrap(); + assert!((coverage(&s, 10, 10) - 128.0 / 255.0).abs() < 0.001); + assert_eq!(coverage(&s, 30, 10), 0.0); +} + +#[test] +fn color_range_eyedropper_samples_anywhere_but_the_result_stays_in_the_selection() { + // #5244: as in Photoshop, a colour picked outside the active selection is accepted; only + // the result is limited to the selection. + let mut s = session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); + let outside = json!({"points": [[30, 10]], "fuzziness": 0}); + assert!(ColorRangeSamples::new(&s, &outside).is_ok()); + s.execute("select.colorRange", outside).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0, "the red inside the selection is selected"); + assert_eq!(coverage(&s, 30, 10), 0.0, "the sampled red outside it stays out"); + assert_eq!(coverage(&s, 2, 2), 0.0, "white is not the sampled colour"); +} + +#[test] +fn color_range_eyedropper_respects_selection_but_add_can_extend_it() { + let mut s = session(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + s.execute("select.colorRange", json!({"points": [[10, 10]], "fuzziness": 0})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 30, 10), 0.0); + + // Explicitly adding a matching colour is still allowed to grow the selection. + s.execute("select.colorRange", json!({"points": [[30, 10]], "fuzziness": 0, "mode": "add"})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 30, 10), 1.0); + + clear_selection(&mut s); + s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 0})).unwrap(); + assert_eq!(coverage(&s, 30, 10), 1.0, "an unbounded color range still searches the canvas"); +} + +#[test] +fn magic_wand_selects_the_visible_alpha_or_mask_not_the_rgb() { + let mut s = session(); + // Alpha covers the first red square and the pixels beside it. RGB would stop at the red. + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + s.execute("channel.new", json!({"fill": "selection", "name": "Alpha"})).unwrap(); + s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 7, 7), 1.0); + assert_eq!(coverage(&s, 2, 2), 1.0, "the white alpha includes pixels that are not the red square"); + assert_eq!(coverage(&s, 30, 10), 0.0, "outside the alpha stays unselected"); + // Colour channels back on: the wand reads RGB again. + s.execute("channel.setVisible", json!({"channel": "composite", "visible": true})).unwrap(); + s.execute("channel.setVisible", json!({"channel": 0, "visible": false})).unwrap(); + s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 7, 7), 1.0); + assert_eq!(coverage(&s, 2, 2), 0.0, "RGB sampling stops at the red square"); + // Eyes off again, Alpha still the picture. + s.execute("channel.setVisible", json!({"channel": 0, "visible": true})).unwrap(); + s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); + s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 2, 2), 1.0); + + let mut s = session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + s.execute("view.layerMask", json!({"mode": "gray"})).unwrap(); + s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 2, 2), 1.0, "gray mask view selects the mask"); + assert_eq!(coverage(&s, 30, 10), 0.0); + s.execute("view.layerMask", json!({"mode": "off"})).unwrap(); + for name in ["red", "green", "blue"] { + s.execute("channel.setVisible", json!({"channel": name, "visible": false})).unwrap(); + } + s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 2, 2), 1.0, "a layer mask shown alone is what the wand reads"); + assert_eq!(coverage(&s, 30, 10), 0.0); +} + +#[test] +fn magic_wand_contiguous_and_modes() { + let mut s = session(); + s.execute("select.magicWand", json!({"x": 7, "y": 7, "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 30, 10), 0.0); + s.execute("select.magicWand", json!({"x": 30, "y": 7, "mode": "add", "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 30, 10), 1.0); + s.execute("select.magicWand", json!({"x": 7, "y": 7, "mode": "subtract", "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 0.0); + s.execute("select.magicWand", json!({"x": 7, "y": 7, "contiguous": false, "antiAlias": false})).unwrap(); + assert_eq!(coverage(&s, 30, 10), 1.0); +} + +#[test] +fn color_range_prepared_query_matches_the_command_at_all_depths() { + use photocraft_doc::{Color, ColorMode, SampleType, Size}; + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for profile in [None, Some(photocraft_cms::Builtin::DisplayP3.profile().to_bytes())] { + let mut doc = Document::with_background("samples", Size::new(24, 12), ColorMode::Rgb, depth, Color::WHITE); + doc.icc_profile = profile; + let layer = doc.layers[0].surface_mut().unwrap(); + layer.fill_rect(Rect::new(0, 0, 8, 12), &[0.65, 0.3, 0.2, 1.0]); + layer.fill_rect(Rect::new(8, 0, 16, 12), &[0.2, 0.3, 0.65, 1.0]); + let mut s = Session::new(); + s.add_document(doc, None); + for p in [ + json!({"points": [[2, 3]], "fuzziness": 0}), + json!({"points": [[2, 3], [10, 3]], "subtractPoints": [[10, 3]], "order": ["+", "+", "-"], "fuzziness": 40}), + json!({"points": [[2, 3]], "localized": true, "range": 50, "fuzziness": 80}), + ] { + clear_selection(&mut s); + let q = ColorRangeSamples::new(&s, &p).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let pixels = photocraft_compose::render(&doc, doc.bounds()); + let preview = q.coverage(&pixels.px, 24, 1.0, [0.0, 0.0]); + s.execute("select.colorRange", p).unwrap(); + let actual = current_mask(&s.active().unwrap().doc).1; + for (shown, selected) in preview.iter().zip(actual) { + let rounded = (shown.clamp(0.0, 1.0) * 255.0 + 0.5).floor() / 255.0; + assert_eq!(rounded, selected, "{depth:?}: original-pixel preview and OK differ"); + } + } + } + } +} + +#[test] +fn color_range_prepared_query_samples_visible_layers_not_the_active_layer() { + use photocraft_doc::{Layer, LayerContent}; + let mut s = session_colours(); + let doc = s.active().unwrap().doc.clone(); + let mut top = Layer::new("blue foreground", LayerContent::Raster(doc.layers[0].surface().unwrap().clone())); + top.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 40, 30), &[0.0, 0.0, 1.0, 1.0]); + let mut hidden = Layer::new("hidden green", LayerContent::Raster(top.surface().unwrap().clone())); + hidden.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 40, 30), &[0.0, 1.0, 0.0, 1.0]); + hidden.visible = false; + s.edit("layers", |doc, _| { + doc.layers.push(top); + doc.layers.push(hidden); + Ok(()) + }) + .unwrap(); + for all_layers in [false, true] { + clear_selection(&mut s); + let p = json!({"points": [[7, 7]], "sampleAllLayers": all_layers, "fuzziness": 0}); + let query = ColorRangeSamples::new(&s, &p).unwrap(); + let (area, px) = sample_pixels(&s, all_layers).unwrap(); + let shown = query.coverage(&px, area.width() as usize, 1.0, [0.0, 0.0]); + s.execute("select.colorRange", p).unwrap(); + assert_eq!(shown[7 * 40 + 7], coverage(&s, 7, 7)); + assert_eq!(shown[24 * 40 + 10], coverage(&s, 10, 24)); + } + for p in [json!({"points": [[-1, 0]]}), json!({"points": [[40, 1]]}), json!({"points": "wrong"}), json!({"points": [[null, 0]]})] { + assert!(ColorRangeSamples::new(&s, &p).is_err(), "{p}"); + } +} + +#[test] +fn color_range_selects_by_colour() { + let mut s = session(); + s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 40})).unwrap(); + // The sampled colour itself is fully selected (as with Photoshop's eyedropper). + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 20, 20), 0.0); + s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 100})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 20, 20), 0.0); +} + +#[test] +fn color_range_compares_in_lab_like_photoshop() { + // Photoshop weighs hue (Lab a/b) three times as much as lightness; a per-channel RGB + // distance can't tell a lighter shade from a redder one. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 30, "height": 10})).unwrap(); + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + let v = |c: u8| f32::from(c) / 255.0; + bg.fill_rect(Rect::new(0, 0, 10, 10), &[v(200), v(140), v(120), 1.0]); // skin + bg.fill_rect(Rect::new(10, 0, 20, 10), &[v(220), v(160), v(140), 1.0]); // lighter skin + bg.fill_rect(Rect::new(20, 0, 30, 10), &[v(220), v(140), v(120), 1.0]); // redder skin + Ok(()) + }) + .unwrap(); + s.execute("select.colorRange", json!({"points": [[5, 5]], "fuzziness": 40})).unwrap(); + assert!(coverage(&s, 5, 5) > 0.98); + // Both differ from the sample by 20 levels in one RGB channel, yet the lighter one is + // kept clearly more (about 0.55 vs 0.31). + let (lighter, redder) = (coverage(&s, 15, 5), coverage(&s, 25, 5)); + assert!(lighter > redder + 0.15 && redder > 0.0, "lighter {lighter}, redder {redder}"); +} + +#[test] +fn color_range_fuzziness_zero_selects_exact_match_only() { + // Sampled Colors at Fuzziness 0 selects only the exact match (TOOL-214-3, #214). + let mut s = Session::new(); + s.execute("file.new", json!({"width": 50, "height": 10})).unwrap(); + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + let v = |c: u8| f32::from(c) / 255.0; + // Exact target color [200, 140, 120] + bg.fill_rect(Rect::new(0, 0, 10, 10), &[v(200), v(140), v(120), 1.0]); + // Off by 1 level in red [201, 140, 120] + bg.fill_rect(Rect::new(10, 0, 20, 10), &[v(201), v(140), v(120), 1.0]); + // Off by 1 level in green [200, 141, 120] + bg.fill_rect(Rect::new(20, 0, 30, 10), &[v(200), v(141), v(120), 1.0]); + // Off by 2 levels in blue [200, 140, 122] (crosses 8-bit Lab grid threshold) + bg.fill_rect(Rect::new(30, 0, 40, 10), &[v(200), v(140), v(122), 1.0]); + // Exact target color again at a different position + bg.fill_rect(Rect::new(40, 0, 50, 10), &[v(200), v(140), v(120), 1.0]); + Ok(()) + }) + .unwrap(); + + // Sampled via eyedropper point at [5, 5] with Fuzziness 0 + s.execute("select.colorRange", json!({"points": [[5, 5]], "fuzziness": 0})).unwrap(); + assert_eq!(coverage(&s, 5, 5), 1.0, "sampled pixel itself is fully selected"); + assert_eq!(coverage(&s, 45, 5), 1.0, "identical color elsewhere on canvas is fully selected"); + assert_eq!(coverage(&s, 15, 5), 0.0, "1 level off in red is unselected at fuzziness 0"); + assert_eq!(coverage(&s, 25, 5), 0.0, "1 level off in green is unselected at fuzziness 0"); + assert_eq!(coverage(&s, 35, 5), 0.0, "1 level off in blue is unselected at fuzziness 0"); + + // Sampled via hex color with Fuzziness 0 + s.execute("select.colorRange", json!({"color": "#c88c78", "fuzziness": 0})).unwrap(); + assert_eq!(coverage(&s, 5, 5), 1.0, "exact color match from hex is fully selected"); + assert_eq!(coverage(&s, 45, 5), 1.0, "identical color elsewhere on canvas is fully selected"); + assert_eq!(coverage(&s, 15, 5), 0.0, "1 level off in red is unselected for hex at fuzziness 0"); + assert_eq!(coverage(&s, 25, 5), 0.0, "1 level off in green is unselected for hex at fuzziness 0"); + assert_eq!(coverage(&s, 35, 5), 0.0, "1 level off in blue is unselected for hex at fuzziness 0"); +} + +/// Red squares (from `session`), a blue square, a black and a mid-grey strip on white. +fn session_colours() -> Session { + let mut s = session(); + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + bg.fill_rect(Rect::new(5, 20, 15, 28), &[0.0, 0.0, 1.0, 1.0]); + bg.fill_rect(Rect::new(20, 20, 25, 28), &[0.0, 0.0, 0.0, 1.0]); + bg.fill_rect(Rect::new(30, 20, 35, 28), &[0.5, 0.5, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +#[test] +fn color_range_several_samples_points_and_invert() { + let mut s = session_colours(); + // Several samples span one Lab box (Photoshop's Minimum/Maximum): red and blue take + // both squares, black, grey and white stay out. + s.execute("select.colorRange", json!({"colors": ["#ff0000", "#0000ff"], "fuzziness": 100})).unwrap(); + assert_eq!((coverage(&s, 10, 10), coverage(&s, 30, 10), coverage(&s, 10, 24)), (1.0, 1.0, 1.0)); + assert_eq!((coverage(&s, 2, 2), coverage(&s, 22, 24), coverage(&s, 32, 24)), (0.0, 0.0, 0.0)); + // Eyedropper point on the blue square; `invert` flips the result. + clear_selection(&mut s); + s.execute("select.colorRange", json!({"points": [[7, 22]], "fuzziness": 100, "invert": true})).unwrap(); + assert_eq!((coverage(&s, 10, 24), coverage(&s, 10, 10), coverage(&s, 2, 2)), (0.0, 1.0, 1.0)); + // Localized clusters: picked on the left red square, a 25% range (10 px) leaves the right one. + clear_selection(&mut s); + s.execute("select.colorRange", json!({"points": [[10, 10]], "fuzziness": 100, "localized": true, "range": 25})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert!(coverage(&s, 13, 10) > 0.5); + assert_eq!(coverage(&s, 30, 10), 0.0); + // Undo restores the empty selection that preceded the most recent Color Range. + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(coverage(&s, 2, 2), 0.0); +} + +#[test] +fn color_range_subtract_follows_photoshop_and_the_click_order() { + // Grey strips from dark to light; samples at both ends span the whole run. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 50, "height": 10})).unwrap(); + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + for (i, v) in [0.30f32, 0.40, 0.50, 0.60, 0.70].iter().enumerate() { + bg.fill_rect(Rect::new(i as i32 * 10, 0, i as i32 * 10 + 10, 10), &[*v, *v, *v, 1.0]); + } + Ok(()) + }) + .unwrap(); + let run = |s: &mut Session, extra: Value| { + clear_selection(s); + let mut p = json!({"points": [[5, 5], [45, 5]], "fuzziness": 10}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + s.execute("select.colorRange", p).unwrap(); + (0..5).map(|i| coverage(s, i * 10 + 5, 5)).collect::>() + }; + assert!(run(&mut s, json!({})).iter().all(|v| *v > 0.99), "both samples span every strip"); + // Subtracting a colour inside the range moves the nearer edge onto it: the strips beyond + // it drop out, the subtracted grey itself stays selected (Photoshop does the same). + let cut = run(&mut s, json!({"subtractPoints": [[15, 5]]})); + assert!(cut[0] < 0.5 && cut[1] > 0.99 && cut[4] > 0.99, "{cut:?}"); + // Order matters: adding the dark strip back after the subtraction restores it. + let readd = run(&mut s, json!({"points": [[5, 5], [45, 5], [5, 5]], "subtractPoints": [[15, 5]], "order": ["+", "+", "-", "+"]})); + assert!(readd[0] > 0.99, "{readd:?}"); + let sub_last = run(&mut s, json!({"points": [[5, 5], [45, 5], [5, 5]], "subtractPoints": [[15, 5]], "order": ["+", "+", "+", "-"]})); + assert!(sub_last[0] < 0.5, "{sub_last:?}"); + // A malformed or inconsistent order is an error, never a panic. + clear_selection(&mut s); + for bad in [json!(["+"]), json!(["+", "+", "x"]), json!("+-"), json!(["-", "-", "+"])] { + assert!(s.execute("select.colorRange", json!({"points": [[5, 5], [45, 5]], "subtractPoints": [[15, 5]], "order": bad})).is_err(), "{bad}"); + } +} + +#[test] +fn color_range_presets() { + let mut s = session_colours(); + s.execute("select.colorRange", json!({"select": "reds"})).unwrap(); + assert_eq!((coverage(&s, 10, 10), coverage(&s, 30, 10)), (1.0, 1.0)); + assert_eq!((coverage(&s, 10, 24), coverage(&s, 2, 2), coverage(&s, 32, 24)), (0.0, 0.0, 0.0)); + clear_selection(&mut s); + s.execute("select.colorRange", json!({"select": "blues"})).unwrap(); + assert_eq!((coverage(&s, 10, 24), coverage(&s, 10, 10)), (1.0, 0.0)); + clear_selection(&mut s); + s.execute("select.colorRange", json!({"select": "greens"})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_none() || coverage(&s, 10, 10) == 0.0); + // Tones: black is a shadow, white a highlight, 50% grey (128) a midtone. + clear_selection(&mut s); + s.execute("select.colorRange", json!({"select": "shadows"})).unwrap(); + assert_eq!((coverage(&s, 22, 24), coverage(&s, 2, 2), coverage(&s, 32, 24)), (1.0, 0.0, 0.0)); + clear_selection(&mut s); + s.execute("select.colorRange", json!({"select": "highlights"})).unwrap(); + assert_eq!((coverage(&s, 22, 24), coverage(&s, 2, 2)), (0.0, 1.0)); + clear_selection(&mut s); + s.execute("select.colorRange", json!({"select": "midtones", "fuzziness": 0})).unwrap(); + assert_eq!((coverage(&s, 32, 24), coverage(&s, 2, 2), coverage(&s, 22, 24)), (1.0, 0.0, 0.0)); + // A wider shadow range takes the grey too. + clear_selection(&mut s); + s.execute("select.colorRange", json!({"select": "shadows", "tonalRange": 140, "fuzziness": 0})).unwrap(); + assert_eq!(coverage(&s, 32, 24), 1.0); + // Modes combine as for the other selection commands. + s.execute("select.colorRange", json!({"select": "reds", "mode": "add"})).unwrap(); + assert_eq!((coverage(&s, 32, 24), coverage(&s, 10, 10)), (1.0, 1.0)); +} + +#[test] +fn color_range_out_of_gamut_matches_the_gamut_warning() { + let mut s = session(); + s.edit("paint", |doc, _| { + // Saturated sRGB blue is outside the default CMYK proof; mid grey is inside. + let bg = doc.layers[0].surface_mut().unwrap(); + bg.fill_rect(Rect::new(0, 20, 20, 30), &[0.0, 0.0, 1.0, 1.0]); + bg.fill_rect(Rect::new(20, 20, 40, 30), &[0.5, 0.5, 0.5, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("select.colorRange", json!({"select": "outOfGamut"})).unwrap(); + assert_eq!((coverage(&s, 5, 25), coverage(&s, 30, 25)), (1.0, 0.0)); + let warn = s.execute("view.gamutWarning", json!({"on": true})).unwrap(); + let sel = s.active().unwrap().doc.selection.clone().unwrap(); + let mut n = 0; + for y in 0..30 { + for x in 0..40 { + n += usize::from(sel.sample_channel(x, y, 0) > 0.5); + } + } + assert_eq!(warn["outOfGamut"].as_u64(), Some(n as u64)); +} + +#[test] +fn color_range_rejects_bad_params() { + let mut s = session_colours(); + for p in [ + json!({"select": "skin"}), + json!({"select": 3}), + json!({"points": [[100, 2]]}), + json!({"points": [[1]]}), + json!({"points": "here"}), + json!({"colors": "#ff0000"}), + json!({"localized": true}), + json!({"select": "midtones", "tonalRange": [200, 100]}), + json!({"select": "shadows", "tonalRange": 300}), + ] { + assert!(s.execute("select.colorRange", p.clone()).is_err(), "{p}"); + } + assert!(s.active().unwrap().doc.selection.is_none()); +} + +#[test] +fn modify_commands() { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("select.modify.expand", json!({"radius": 2})).unwrap(); + assert_eq!(coverage(&s, 8, 15), 1.0); + s.execute("select.modify.contract", json!({"radius": 4})).unwrap(); + assert_eq!(coverage(&s, 11, 15), 0.0); + assert_eq!(coverage(&s, 15, 15), 1.0); + s.execute("select.modify.border", json!({"radius": 2})).unwrap(); + assert_eq!(coverage(&s, 15, 15), 0.0); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("select.modify.feather", json!({"radius": 4})).unwrap(); + let e = coverage(&s, 10, 15); + assert!(e > 0.2 && e < 0.8, "{e}"); + s.execute("select.modify.smooth", json!({"radius": 2})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_some()); + assert!(!s.is_enabled("select.nothing")); + // Out-of-range or non-finite radii are refused and leave the selection alone. + for op in ["feather", "smooth", "expand", "contract", "border"] { + for r in [json!(1e300), json!(5000), json!(f64::MAX), json!(-5), json!(-0.5), json!(f64::MIN)] { + assert!(s.execute(&format!("select.modify.{op}"), json!({"radius": r})).is_err(), "{op} {r}"); + } + } + assert!(s.active().unwrap().doc.selection.is_some()); +} + +#[test] +fn modify_select_all_honours_canvas_bounds() { + let all = || { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s + }; + // Off (Photoshop's default): the selection continues past the canvas, so the edges stay. + for op in ["contract", "smooth", "expand", "feather"] { + let mut s = all(); + s.execute(&format!("select.modify.{op}"), json!({"radius": 4})).unwrap(); + assert_eq!(coverage(&s, 0, 15), 1.0, "{op}"); + assert_eq!(coverage(&s, 20, 0), 1.0, "{op}"); + } + // On: the canvas edge is a selection edge (#1277). + let mut s = all(); + s.execute("select.modify.contract", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap(); + assert_eq!(coverage(&s, 2, 15), 0.0); + assert_eq!(coverage(&s, 20, 28), 0.0); + assert_eq!(coverage(&s, 20, 15), 1.0); + let mut s = all(); + s.execute("select.modify.feather", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap(); + let e = coverage(&s, 0, 15); + assert!(e > 0.2 && e < 0.8, "{e}"); + assert_eq!(coverage(&s, 20, 15), 1.0); + let mut s = all(); + s.execute("select.modify.smooth", json!({"radius": 4, "applyAtCanvasBounds": true})).unwrap(); + assert!(coverage(&s, 0, 0) < 1.0); + // Border always follows the canvas edge: a band inside it, not an empty selection. + let mut s = all(); + s.execute("select.modify.border", json!({"radius": 4})).unwrap(); + assert!(coverage(&s, 0, 15) > 0.0); + assert_eq!(coverage(&s, 20, 15), 0.0); +} + +#[test] +fn modify_away_from_the_canvas_edge_ignores_canvas_bounds() { + for at in [false, true] { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("select.modify.contract", json!({"radius": 4, "applyAtCanvasBounds": at})).unwrap(); + assert_eq!(coverage(&s, 11, 15), 0.0); + assert_eq!(coverage(&s, 15, 15), 1.0); + } +} + +#[test] +fn modify_refuses_radii_below_the_minimum() { + let mut s = session(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + // Below each dialog's minimum (1 px, Feather 0.1 px) is refused, not clamped to 0: a + // negative Border radius used to clear the selection and report success (#993). + let below = [ + ("border", -5.0), + ("border", 0.5), + ("smooth", -5.0), + ("smooth", 0.0), + ("expand", -5.0), + ("expand", 0.0), + ("contract", -5.0), + ("contract", 0.9), + ("feather", -5.0), + ("feather", 0.0), + ("feather", 0.05), + ]; + let before = current_mask(&s.active().unwrap().doc).1; + for (op, r) in below { + let err = s.execute(&format!("select.modify.{op}"), json!({"radius": r})).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "{op} {r}: {err}"); + assert!(current_mask(&s.active().unwrap().doc).1 == before, "{op} {r}: the selection changed"); + } + // The minimum itself is still accepted. + s.execute("select.modify.feather", json!({"radius": 0.1})).unwrap(); + s.execute("select.modify.expand", json!({"radius": 1})).unwrap(); + assert_eq!(coverage(&s, 9, 15), 1.0); +} + +#[test] +fn geometry_params_that_would_wrap_are_rejected() { + let mut s = session(); + // 2^32 + 50 wrapped to `x = 50` and 3e9 to a negative coordinate through `as i32`; + // both are bad-params errors now, whatever the front door (UI, CLI, control, MCP). + for x in [4_294_967_346_i64, 3_000_000_000_i64] { + let err = s.execute("select.rect", json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap_err(); + assert!(err.to_string().contains("32-bit"), "{err}"); + } + let err = s.execute("document.pixel", json!({"x": 4_294_967_346_i64, "y": 0})).unwrap_err(); + assert!(err.to_string().contains("32 bits"), "{err}"); + // In-range coordinates, including negative and past-canvas ones, are unaffected. + s.execute("select.rect", json!({"x": -100, "y": -100, "width": 500, "height": 500})).unwrap(); + s.execute("document.pixel", json!({"x": 0, "y": 0})).unwrap(); +} + +#[test] +fn grow_and_similar() { + let mut s = session(); + s.execute("select.rect", json!({"x": 6, "y": 6, "width": 2, "height": 2})).unwrap(); + s.execute("select.grow", json!({"tolerance": 5})).unwrap(); + assert_eq!(coverage(&s, 14, 14), 1.0); + assert_eq!(coverage(&s, 30, 10), 0.0); + s.execute("select.similar", json!({"tolerance": 5})).unwrap(); + assert_eq!(coverage(&s, 30, 10), 1.0); + assert_eq!(coverage(&s, 20, 20), 0.0); +} + +#[test] +fn lasso_polygon() { + let mut s = session(); + s.execute("select.lasso", json!({"points": [[0, 0], [20, 0], [0, 20]]})).unwrap(); + assert_eq!(coverage(&s, 2, 2), 1.0); + assert_eq!(coverage(&s, 18, 18), 0.0); + assert!(s.execute("select.lasso", json!({"points": [[0, 0], [1, 1]]})).is_err()); + s.execute("select.lasso", json!({"points": [[0, 0], [20, 0], [0, 20]], "mode": "subtract"})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_none()); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(coverage(&s, 2, 2), 1.0); +} + +/// The previous per-sample padding and cropping, kept as the oracle for the row-wise ones. +fn old_pad_mask(m: &[f32], w: usize, h: usize, pad: usize, outside_empty: bool) -> Vec { + let pw = w + 2 * pad; + let mut out = vec![0.0f32; pw * (h + 2 * pad)]; + for (py, row) in out.chunks_exact_mut(pw).enumerate() { + let inside_y = (pad..pad + h).contains(&py); + if outside_empty && !inside_y { + continue; + } + let y = py.saturating_sub(pad).min(h - 1); + for (px, v) in row.iter_mut().enumerate() { + if outside_empty && !(pad..pad + w).contains(&px) { + continue; + } + *v = m.get(y * w + px.saturating_sub(pad).min(w - 1)).copied().unwrap_or(0.0); + } + } + out +} + +#[test] +fn row_wise_pad_and_crop_match_per_sample_ones() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let (w, h) = (37, 23); + let m: Vec = (0..w * h) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % 1000) as f32 / 999.0 + }) + .collect(); + for pad in [0, 1, 5, 40] { + for outside_empty in [false, true] { + let padded = pad_mask(&m, w, h, pad, outside_empty); + assert_eq!(padded, old_pad_mask(&m, w, h, pad, outside_empty), "pad {pad} {outside_empty}"); + assert_eq!(crop_mask(&padded, w + 2 * pad, pad, w, h), m, "pad {pad}"); + } + } +} + +/// The lasso over the polygon's rows gives exactly the whole-canvas result (#4532): random +/// polygons, partly off the canvas, with and without anti-aliasing, in every mode over an +/// existing selection. +#[test] +fn lasso_over_its_rows_matches_the_whole_canvas() { + let mut seed = 0x2545_f491_u32; + let mut rnd = |lo: f32, hi: f32| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + lo + (seed % 10_000) as f32 / 10_000.0 * (hi - lo) + }; + for case in 0..24 { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 520})).unwrap(); + s.execute("select.rect", json!({"x": 40, "y": 60, "width": 200, "height": 300})).unwrap(); + let n = 3 + case % 7; + let pts: Vec<(f32, f32)> = (0..n).map(|_| (rnd(-30.0, 330.0), rnd(100.0, 420.0))).collect(); + let aa = case % 2 == 0; + let m = ["replace", "add", "subtract", "intersect"][case % 4]; + let doc = s.active().unwrap().doc.clone(); + let area = doc.bounds(); + let want = sel::combine(doc.selection.as_ref(), &sel::polygon(&pts, area, aa), area, SelectionMode::parse(m)); + let points: Vec<[f32; 2]> = pts.iter().map(|p| [p.0, p.1]).collect(); + s.execute("select.lasso", json!({"points": points, "antiAlias": aa, "mode": m})).unwrap(); + let got = s.active().unwrap().doc.selection.clone(); + let read = |x: &Option| x.as_ref().map(|s| s.read_region(area)); + assert_eq!(read(&got), read(&want), "case {case}: {m}, anti-alias {aa}, {pts:?}"); + } +} From c46f273c85fdfffa1dbef1d6b4b2f9aeda1adc02 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:20 +0000 Subject: [PATCH 041/259] refactor(engine): move filters.rs tests to filters/tests.rs --- crates/engine/src/filters.rs | 518 +---------------------------- crates/engine/src/filters/tests.rs | 515 ++++++++++++++++++++++++++++ 2 files changed, 516 insertions(+), 517 deletions(-) create mode 100644 crates/engine/src/filters/tests.rs diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs index b115a9f5e0..4d8db05213 100644 --- a/crates/engine/src/filters.rs +++ b/crates/engine/src/filters.rs @@ -498,520 +498,4 @@ pub fn last_filter(s: &Session) -> Option<(String, Value)> { } #[cfg(test)] -mod tests { - use super::*; - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 48, "height": 32})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("edit.fill", json!({"color": "#3366cc"})).ok(); - s - } - - fn active_pixels(s: &Session) -> Vec { - let d = s.active().unwrap(); - let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); - l.surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 48, 32)) - } - - fn mask_session(reveal_selection: bool) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); - if reveal_selection { - s.execute("select.all", json!({})).unwrap(); - s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); - } else { - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - } - s - } - - fn mask_pixels(s: &Session) -> Vec { - let d = s.active().unwrap(); - let mask = d.doc.layer(d.active_layer.unwrap()).unwrap().mask.as_ref().unwrap(); - mask.surface.read_region(d.doc.bounds()) - } - - fn canvas_pixels(s: &Session) -> Vec { - let d = s.active().unwrap(); - d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().read_region(d.doc.bounds()) - } - - fn paint_pattern(s: &mut Session) { - s.edit("pattern", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - let surf = l.surface_mut().unwrap(); - for y in 0..32 { - for x in 0..48 { - let v = ((x * 5 + y * 3) % 17) as f32 / 16.0; - surf.write_pixel(x, y, &[v, 1.0 - v, (x % 3) as f32 / 2.0, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - } - - const ALL: [&str; 24] = [ - "filter.blur.gaussianBlur", - "filter.blur.boxBlur", - "filter.blur.motionBlur", - "filter.blur.radialBlur", - "filter.blur.surfaceBlur", - "filter.sharpen.unsharpMask", - "filter.sharpen.smartSharpen", - "filter.noise.addNoise", - "filter.noise.median", - "filter.noise.dustAndScratches", - "filter.pixelate.mosaic", - "filter.stylize.emboss", - "filter.stylize.findEdges", - "filter.stylize.solarize", - "filter.distort.twirl", - "filter.distort.pinch", - "filter.distort.spherize", - "filter.distort.wave", - "filter.distort.ripple", - "filter.distort.polarCoordinates", - "filter.other.highPass", - "filter.other.minimum", - "filter.other.maximum", - "filter.other.offset", - ]; - - #[test] - fn every_filter_command_runs_changes_pixels_and_undoes() { - for id in ALL { - let mut s = session(); - paint_pattern(&mut s); - let before = active_pixels(&s); - let params = match id { - "filter.other.offset" => json!({"horizontal": 5, "vertical": 2}), - "filter.noise.dustAndScratches" => json!({"radius": 2, "threshold": 0}), - "filter.noise.median" => json!({"radius": 2}), - _ => json!({}), - }; - let r = s.execute(id, params).unwrap_or_else(|e| panic!("{id}: {e}")); - assert!(r.get("filter").is_some(), "{id}"); - assert_ne!(active_pixels(&s), before, "{id} changed nothing"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(active_pixels(&s), before, "{id} undo"); - } - } - - #[test] - fn preset_filters_record_their_own_name() { - // #528: one-step presets run a generic algorithm but name the step after themselves; - // the generic commands keep the algorithm's name. - let specs = specs(); - for (id, name) in [ - ("filter.blur.blur", "Blur"), - ("filter.blur.blurMore", "Blur More"), - ("filter.sharpen.sharpen", "Sharpen"), - ("filter.sharpen.sharpenMore", "Sharpen More"), - ("filter.sharpen.sharpenEdges", "Sharpen Edges"), - ("filter.noise.despeckle", "Despeckle"), - ("filter.blur.gaussianBlur", "Gaussian Blur"), - ("filter.sharpen.unsharpMask", "Unsharp Mask"), - ("filter.blur.surfaceBlur", "Surface Blur"), - ] { - let mut s = session(); - let steps = s.active().unwrap().history.past_len(); - s.execute(id, json!({})).unwrap(); - let h = &s.active().unwrap().history; - assert_eq!((h.past_len(), h.undo_label()), (steps + 1, Some(name)), "{id}"); - let label = specs.iter().find(|c| c.id == id).unwrap().label; - assert_eq!(label.trim_end_matches('…'), name, "{id}: the step is named like the command"); - } - } - - #[test] - fn specs_are_complete_and_documented() { - let specs = specs(); - for id in ALL { - let spec = specs.iter().find(|c| c.id == id).unwrap_or_else(|| panic!("missing {id}")); - assert!(spec.params.starts_with('{'), "{id}"); - assert!(!spec.menu.is_empty(), "{id}"); - } - } - - #[test] - fn disabled_without_pixel_layer() { - let mut s = Session::new(); - assert!(!s.is_enabled("filter.blur.gaussianBlur")); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); - assert!(matches!(s.execute("filter.blur.gaussianBlur", json!({})), Err(EngineError::Disabled(..)))); - } - - #[test] - fn selection_limits_the_filter() { - let mut s = session(); - paint_pattern(&mut s); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - let has_sel = s.active().unwrap().doc.selection.is_some(); - assert!(has_sel); - let before = active_pixels(&s); - s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap(); - let after = active_pixels(&s); - if has_sel { - // A pixel far from the selection is unchanged. - let i = (30 * 48 + 40) * 4; - assert_eq!(after[i..i + 4], before[i..i + 4]); - let j = (5 * 48 + 5) * 4; - assert_ne!(after[j..j + 4], before[j..j + 4]); - } - } - - #[test] - fn solarize_and_add_noise_process_untouched_reveal_all_masks() { - for (id, params) in [ - ("filter.stylize.solarize", json!({"target": "mask"})), - ("filter.noise.addNoise", json!({"amount": 100, "seed": 1, "monochromatic": true, "target": "mask"})), - ] { - let mut reveal_all = mask_session(false); - let mut reveal_selection = mask_session(true); - let all_mask = reveal_all.active().unwrap().doc.layer(reveal_all.active().unwrap().active_layer.unwrap()).unwrap().mask.as_ref().unwrap(); - assert!(all_mask.surface.content_bounds().is_empty(), "{id}: Reveal All stores its white canvas in the default pixel"); - let initial_all = mask_pixels(&reveal_all); - let initial_selection = mask_pixels(&reveal_selection); - assert_eq!(initial_all, initial_selection, "{id}: masks start with equal white values"); - assert_eq!(initial_all, vec![1.0; 16 * 16], "{id}: the full canvas starts revealed"); - let pixels_before = canvas_pixels(&reveal_all); - - reveal_all.execute(id, params.clone()).unwrap(); - reveal_selection.execute(id, params).unwrap(); - - let actual = mask_pixels(&reveal_all); - let expected = mask_pixels(&reveal_selection); - assert!( - actual == expected, - "{id}: Reveal All differs from Reveal Selection: first={:?}/{:?}, changed pixels={}/{}", - actual[0], - expected[0], - actual.iter().filter(|&&v| v != 1.0).count(), - expected.iter().filter(|&&v| v != 1.0).count() - ); - assert_eq!(canvas_pixels(&reveal_all), pixels_before, "{id}: the mask target must leave layer pixels unchanged"); - if id == "filter.stylize.solarize" { - assert!(actual.iter().all(|&v| v == 0.0), "Solarize maps the white mask to black"); - } else { - assert!(actual.iter().any(|&v| v != 1.0), "seeded Add Noise changes the Reveal All mask"); - } - } - } - - #[test] - fn minimum_signed_offset_matches_its_wrapped_distance() { - for depth in [8, 16, 32] { - let make_session = || { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 48, "height": 32, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - paint_pattern(&mut s); - s - }; - let mut actual = make_session(); - let before = active_pixels(&actual); - actual.execute("filter.other.offset", json!({"horizontal": i32::MIN, "vertical": i32::MIN})).unwrap(); - let mut expected = make_session(); - expected.execute("filter.other.offset", json!({"horizontal": i32::MIN.rem_euclid(48), "vertical": i32::MIN.rem_euclid(32)})).unwrap(); - let after = active_pixels(&actual); - assert_eq!(after, active_pixels(&expected), "depth {depth}"); - assert_ne!(after, before); - actual.execute("edit.undo", json!({})).unwrap(); - assert_eq!(active_pixels(&actual), before); - actual.execute("edit.redo", json!({})).unwrap(); - assert_eq!(active_pixels(&actual), after); - } - } - #[test] - fn huge_offsets_clamp_instead_of_wrapping() { - // 3e9 wrapped to a negative offset through `as i32`; it saturates now, so it - // equals the maximal in-range offset instead of shifting the other way. - let mut a = session(); - a.execute("filter.other.offset", json!({"horizontal": 3_000_000_000_i64, "vertical": 0})).unwrap(); - let mut b = session(); - b.execute("filter.other.offset", json!({"horizontal": 2_147_483_647_i64, "vertical": 0})).unwrap(); - assert_eq!(active_pixels(&a), active_pixels(&b)); - } - - #[test] - fn last_filter_repeats_with_same_params() { - let mut s = session(); - paint_pattern(&mut s); - assert!(!s.is_enabled("filter.lastFilter")); - s.execute("filter.other.offset", json!({"horizontal": 3})).unwrap(); - let once = active_pixels(&s); - s.execute("filter.lastFilter", json!({})).unwrap(); - let twice = active_pixels(&s); - assert_ne!(once, twice); - // Offsetting 3 twice equals offsetting 6 once. - let mut s2 = session(); - paint_pattern(&mut s2); - s2.execute("filter.other.offset", json!({"horizontal": 6})).unwrap(); - assert_eq!(active_pixels(&s2), twice); - } - - #[test] - fn recorded_last_filter_replays_the_filter_it_repeated() { - // #3089: the action holds the filter with its settings, not a "repeat whatever ran - // last" step that fails in a new session. - let mut s = session(); - paint_pattern(&mut s); - s.execute("filter.other.offset", json!({"horizontal": 3})).unwrap(); - s.execute("actions.record", json!({"name": "Again"})).unwrap(); - s.execute("filter.lastFilter", json!({})).unwrap(); - s.execute("actions.stop", json!({})).unwrap(); - let steps = s.execute("actions.get", json!({"action": "Again"})).unwrap()["steps"].clone(); - assert_eq!(steps, json!([["filter.other.offset", {"horizontal": 3}]])); - let action = s.actions.list[0].clone(); - - let mut fresh = session(); - paint_pattern(&mut fresh); - fresh.actions.list.push(action); - let played = fresh.execute("actions.play", json!({"action": "Again"})).unwrap(); - assert!(played.get("failed").is_none(), "{played}"); - let mut direct = session(); - paint_pattern(&mut direct); - direct.execute("filter.other.offset", json!({"horizontal": 3})).unwrap(); - assert_eq!(active_pixels(&fresh), active_pixels(&direct)); - } - - #[test] - fn last_filter_applies_to_the_active_layer() { - let mut s = session(); - paint_pattern(&mut s); - let first = s.active().unwrap().active_layer.unwrap(); - // Dialogs (Filter Gallery, Camera Raw…) record the layer they ran on. - s.execute("filter.other.offset", json!({"horizontal": 3, "layer": first.0})).unwrap(); - let first_once = active_pixels(&s); - s.execute("layer.new.layer", json!({})).unwrap(); - paint_pattern(&mut s); - let before = active_pixels(&s); - s.execute("filter.lastFilter", json!({})).unwrap(); - assert_ne!(active_pixels(&s), before, "the active layer is filtered"); - let d = s.active().unwrap(); - let l = d.doc.layer(first).unwrap(); - assert_eq!(l.surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 48, 32)), first_once, "the first layer is left alone"); - } - - #[test] - fn params_map_to_algorithm_units() { - assert_eq!(params_for("filter.blur.gaussianBlur", &json!({"radius": 4.5})), Some(FilterParams::GaussianBlur { radius: 4.5 })); - assert_eq!( - params_for("filter.blur.radialBlur", &json!({"quality": "best"})), - Some(FilterParams::RadialBlur { amount: 10.0, method: RadialMethod::Spin, quality: RadialQuality::Best, center_x: 0.5, center_y: 0.5 }) - ); - assert_eq!( - params_for("filter.noise.addNoise", &json!({"amount": 10, "distribution": "gaussian", "monochromatic": true})), - Some(FilterParams::AddNoise { amount: 10.0, distribution: Distribution::Gaussian, monochromatic: true, seed: 0 }) - ); - assert_eq!(params_for("filter.blur.gaussianBlur", &json!({"radius": -3})), Some(FilterParams::GaussianBlur { radius: 0.1 })); - assert!(params_for("filter.nope", &json!({})).is_none()); - } - - #[test] - fn minimum_maximum_preserve_roundness() { - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 48, "height": 32, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - // A white dot on black. - s.edit("dot", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - surf.fill_rect(photocraft_geom::Rect::new(0, 0, 48, 32), &[0.0, 0.0, 0.0, 1.0]); - surf.write_pixel(24, 16, &[1.0, 1.0, 1.0, 1.0]); - Ok(()) - }) - .unwrap(); - let before = active_pixels(&s); - let lit = |s: &Session, x: usize, y: usize| active_pixels(s)[(y * 48 + x) * 4] > 0.5; - s.execute("filter.other.maximum", json!({"radius": 4, "preserve": "roundness"})).unwrap(); - // Grown into a disc of radius 4: (4, 0) and (2, 3) are in, the square's corner isn't. - assert!(lit(&s, 28, 16) && lit(&s, 26, 19), "depth {depth}"); - assert!(!lit(&s, 28, 20) && !lit(&s, 27, 19), "depth {depth}"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(active_pixels(&s), before); - // The default is Squareness: the corner is taken. - s.execute("filter.other.maximum", json!({"radius": 4})).unwrap(); - assert!(lit(&s, 28, 20), "depth {depth}"); - // Minimum with roundness: only the centre of that 9×9 square holds a whole disc. - s.execute("filter.other.minimum", json!({"radius": 4, "preserve": "roundness"})).unwrap(); - assert!(!lit(&s, 20, 12) && lit(&s, 24, 16), "depth {depth}"); - } - assert_eq!( - params_for("filter.other.minimum", &json!({"radius": 2, "preserve": "roundness"})), - Some(FilterParams::Minimum { radius: 2.0, preserve: Preserve::Roundness }) - ); - assert_eq!(params_for("filter.other.maximum", &json!({})), Some(FilterParams::Maximum { radius: 1.0, preserve: Preserve::Squareness })); - } - - #[test] - fn smart_object_records_smart_filter() { - use photocraft_doc::{Layer, SmartObject, SmartSource}; - let mut s = session(); - s.edit("smart", |doc, active| { - let mut cache = photocraft_raster::Surface::new(doc.pixel_format()); - cache.fill_rect(photocraft_geom::Rect::new(0, 0, 10, 10), &[1.0, 0.0, 0.0, 1.0]); - let l = Layer::new( - "so", - LayerContent::Smart(SmartObject { - contents_id: photocraft_doc::SmartContentsId::fresh(), - source: SmartSource::Linked { path: String::new() }, - transform: photocraft_geom::Affine::IDENTITY, - smart_filters: vec![], - cache: Some(cache), - psd_raw: None, - filters_enabled: true, - filter_mask: None, - warp: None, - stack_mode: None, - perspective: None, - }), - ); - *active = Some(doc.insert_above(*active, l)); - Ok(()) - }) - .unwrap(); - s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); - let d = s.active().unwrap(); - let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!() }; - assert_eq!(sm.smart_filters.len(), 1); - assert_eq!(sm.smart_filters[0].command, "filter.blur.gaussianBlur"); - assert_eq!(sm.smart_filters[0].params["radius"], json!(2)); - assert!(sm.cache.as_ref().unwrap().pixel(10, 5)[3] > 0.0, "cache was blurred"); - } - - /// The serial `keep_alpha` before #6205, kept as the oracle for the parallel one. - fn keep_alpha_serial(old: &photocraft_raster::Surface, new: &mut photocraft_raster::Surface) { - if old.format() != new.format() || !new.format().alpha { - return; - } - let mut coords: Vec<_> = new.tiles().filter(|(c, t)| old.tile(**c).is_none_or(|o| !std::sync::Arc::ptr_eq(o, t))).map(|(c, _)| *c).collect(); - coords.extend(old.tiles().filter(|(c, _)| new.tile(**c).is_none()).map(|(c, _)| *c)); - let n = new.channels(); - for c in coords { - let r = c.rect(); - let o = old.read_region(r); - let mut v = new.read_region(r); - for (pn, po) in v.chunks_exact_mut(n).zip(o.chunks_exact(n)) { - if let (Some(a), Some(b)) = (pn.last_mut(), po.last()) { - *a = *b; - } - } - new.write_region(r, &v); - } - new.prune(); - } - - /// A layer before and after a filter: tiles the filter changed, one it left shared, one it - /// emptied (only in `old`) and one it added (only in `new`). - fn alpha_pair(sample: photocraft_color::SampleType) -> (photocraft_raster::Surface, photocraft_raster::Surface) { - use photocraft_geom::Rect; - use photocraft_raster::Surface; - let fmt = photocraft_color::PixelFormat { mode: photocraft_color::ColorMode::Rgb, sample, alpha: true }; - let pattern = |r: Rect, k: f32| -> Vec { - (0..r.width() as usize * r.height() as usize * 4).map(|i| ((i as f32 * 0.37 + k).sin() * 0.5 + 0.5).clamp(0.0, 1.0)).collect() - }; - let mut old = Surface::new(fmt); - let r = Rect::new(-40, -20, 700, 300); - old.write_region(r, &pattern(r, 0.0)); - let mut new = old.clone(); - let changed = Rect::new(-40, -20, 400, 300); - new.write_region(changed, &pattern(changed, 1.3)); - let emptied = photocraft_geom::TileCoord::containing(600, 100).rect(); - drop(new.take_tiles(emptied)); - let added = Rect::new(800, 0, 900, 50); - new.write_region(added, &pattern(added, 2.1)); - (old, new) - } - - #[test] - fn keep_alpha_matches_the_serial_pass_at_every_depth() { - use photocraft_color::SampleType; - for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { - let (old, new) = alpha_pair(sample); - let mut want = new.clone(); - keep_alpha_serial(&old, &mut want); - let mut got = new.clone(); - keep_alpha(&old, &mut got, &|| false).unwrap(); - assert!(got == want, "{sample:?}: parallel keep_alpha differs from the serial pass"); - assert_ne!(got, new, "{sample:?}: alpha was put back"); - } - } - - #[test] - fn keep_alpha_stops_when_cancelled_and_keeps_the_tiles() { - let (old, new) = alpha_pair(photocraft_color::SampleType::U8); - let mut got = new.clone(); - let calls = std::sync::atomic::AtomicUsize::new(0); - let cancel = || calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 2; - assert!(matches!(keep_alpha(&old, &mut got, &cancel), Err(EngineError::Cancelled))); - // The cancel was seen inside the pass (after some tiles), and no tile went missing. - assert!(calls.load(std::sync::atomic::Ordering::SeqCst) > 2); - assert!(new.tiles().all(|(c, _)| got.tile(*c).is_some())); - } - - /// #7423: Displace on a Smart Object keeps its map (read from an open document) in the smart - /// filter, as Photoshop embeds it, so the filter displaces and keeps displacing when the - /// object re-renders. A map chosen again replaces it. - #[test] - fn displace_on_a_smart_object_embeds_its_map() { - let mut s = Session::new(); - // Documents 0 and 1: a white and a black displacement map. - s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); - s.execute("file.new", json!({"width": 8, "height": 8, "background": "black"})).unwrap(); - s.execute("file.new", json!({"width": 48, "height": 32, "background": "transparent"})).unwrap(); - s.edit("square", |doc, active| { - let fmt = doc.pixel_format(); - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - surf.fill_rect(photocraft_geom::Rect::new(10, 10, 20, 12), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); - Ok(()) - }) - .unwrap(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let original = { - let d = s.active().unwrap(); - let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; - sm.cache.as_ref().unwrap().read_region(d.doc.bounds()) - }; - let smart = |s: &Session| { - let d = s.active().unwrap(); - let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; - (sm.smart_filters[0].params.clone(), sm.cache.as_ref().unwrap().read_region(d.doc.bounds())) - }; - let first_value = |params: &Value| photocraft_io::smart_map::displace_embedded_map(params).expect("an embedded map").data[0]; - - s.execute("filter.distort.displace", json!({"horizontal": 10, "vertical": 0, "mapDocument": 0})).unwrap(); - let (params, displaced) = smart(&s); - assert!(params.get("mapDocument").is_none(), "{params}"); - assert_eq!(first_value(¶ms), 1.0, "the white map"); - assert_ne!(displaced, original, "the smart object is displaced"); - // Re-rendered from its params alone (the filter hidden and shown again): still displaced. - s.execute("layer.smartFilter.setVisible", json!({"index": 0, "visible": false})).unwrap(); - assert_eq!(smart(&s).1, original); - s.execute("layer.smartFilter.setVisible", json!({"index": 0, "visible": true})).unwrap(); - assert_eq!(smart(&s).1, displaced); - - // Another map chosen for the filter replaces the embedded one. - s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": {"mapDocument": 1}})).unwrap(); - let (params, again) = smart(&s); - assert!(params.get("mapDocument").is_none(), "{params}"); - assert_eq!(first_value(¶ms), 0.0, "the black map"); - assert_ne!(again, displaced, "displaced the other way"); - - // The stored params passed back whole (the old embedded map included) with another map - // named: the named map wins, for the filter's own edit and for a new Displace alike. - let mut back = params.as_object().unwrap().clone(); - back.insert("mapDocument".into(), json!(0)); - s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": back.clone()})).unwrap(); - assert_eq!(first_value(&smart(&s).0), 1.0, "the white map, not the embedded black one"); - back.insert("mapDocument".into(), json!(1)); - s.execute("filter.distort.displace", Value::Object(back)).unwrap(); - let d = s.active().unwrap(); - let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; - assert_eq!(first_value(&sm.smart_filters[1].params), 0.0, "the black map, not the passed-back white one"); - } -} +mod tests; diff --git a/crates/engine/src/filters/tests.rs b/crates/engine/src/filters/tests.rs new file mode 100644 index 0000000000..5b3f3a3703 --- /dev/null +++ b/crates/engine/src/filters/tests.rs @@ -0,0 +1,515 @@ +use super::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 48, "height": 32})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#3366cc"})).ok(); + s +} + +fn active_pixels(s: &Session) -> Vec { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + l.surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 48, 32)) +} + +fn mask_session(reveal_selection: bool) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); + if reveal_selection { + s.execute("select.all", json!({})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + } else { + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + } + s +} + +fn mask_pixels(s: &Session) -> Vec { + let d = s.active().unwrap(); + let mask = d.doc.layer(d.active_layer.unwrap()).unwrap().mask.as_ref().unwrap(); + mask.surface.read_region(d.doc.bounds()) +} + +fn canvas_pixels(s: &Session) -> Vec { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().read_region(d.doc.bounds()) +} + +fn paint_pattern(s: &mut Session) { + s.edit("pattern", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + let surf = l.surface_mut().unwrap(); + for y in 0..32 { + for x in 0..48 { + let v = ((x * 5 + y * 3) % 17) as f32 / 16.0; + surf.write_pixel(x, y, &[v, 1.0 - v, (x % 3) as f32 / 2.0, 1.0]); + } + } + Ok(()) + }) + .unwrap(); +} + +const ALL: [&str; 24] = [ + "filter.blur.gaussianBlur", + "filter.blur.boxBlur", + "filter.blur.motionBlur", + "filter.blur.radialBlur", + "filter.blur.surfaceBlur", + "filter.sharpen.unsharpMask", + "filter.sharpen.smartSharpen", + "filter.noise.addNoise", + "filter.noise.median", + "filter.noise.dustAndScratches", + "filter.pixelate.mosaic", + "filter.stylize.emboss", + "filter.stylize.findEdges", + "filter.stylize.solarize", + "filter.distort.twirl", + "filter.distort.pinch", + "filter.distort.spherize", + "filter.distort.wave", + "filter.distort.ripple", + "filter.distort.polarCoordinates", + "filter.other.highPass", + "filter.other.minimum", + "filter.other.maximum", + "filter.other.offset", +]; + +#[test] +fn every_filter_command_runs_changes_pixels_and_undoes() { + for id in ALL { + let mut s = session(); + paint_pattern(&mut s); + let before = active_pixels(&s); + let params = match id { + "filter.other.offset" => json!({"horizontal": 5, "vertical": 2}), + "filter.noise.dustAndScratches" => json!({"radius": 2, "threshold": 0}), + "filter.noise.median" => json!({"radius": 2}), + _ => json!({}), + }; + let r = s.execute(id, params).unwrap_or_else(|e| panic!("{id}: {e}")); + assert!(r.get("filter").is_some(), "{id}"); + assert_ne!(active_pixels(&s), before, "{id} changed nothing"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(active_pixels(&s), before, "{id} undo"); + } +} + +#[test] +fn preset_filters_record_their_own_name() { + // #528: one-step presets run a generic algorithm but name the step after themselves; + // the generic commands keep the algorithm's name. + let specs = specs(); + for (id, name) in [ + ("filter.blur.blur", "Blur"), + ("filter.blur.blurMore", "Blur More"), + ("filter.sharpen.sharpen", "Sharpen"), + ("filter.sharpen.sharpenMore", "Sharpen More"), + ("filter.sharpen.sharpenEdges", "Sharpen Edges"), + ("filter.noise.despeckle", "Despeckle"), + ("filter.blur.gaussianBlur", "Gaussian Blur"), + ("filter.sharpen.unsharpMask", "Unsharp Mask"), + ("filter.blur.surfaceBlur", "Surface Blur"), + ] { + let mut s = session(); + let steps = s.active().unwrap().history.past_len(); + s.execute(id, json!({})).unwrap(); + let h = &s.active().unwrap().history; + assert_eq!((h.past_len(), h.undo_label()), (steps + 1, Some(name)), "{id}"); + let label = specs.iter().find(|c| c.id == id).unwrap().label; + assert_eq!(label.trim_end_matches('…'), name, "{id}: the step is named like the command"); + } +} + +#[test] +fn specs_are_complete_and_documented() { + let specs = specs(); + for id in ALL { + let spec = specs.iter().find(|c| c.id == id).unwrap_or_else(|| panic!("missing {id}")); + assert!(spec.params.starts_with('{'), "{id}"); + assert!(!spec.menu.is_empty(), "{id}"); + } +} + +#[test] +fn disabled_without_pixel_layer() { + let mut s = Session::new(); + assert!(!s.is_enabled("filter.blur.gaussianBlur")); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + assert!(matches!(s.execute("filter.blur.gaussianBlur", json!({})), Err(EngineError::Disabled(..)))); +} + +#[test] +fn selection_limits_the_filter() { + let mut s = session(); + paint_pattern(&mut s); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let has_sel = s.active().unwrap().doc.selection.is_some(); + assert!(has_sel); + let before = active_pixels(&s); + s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap(); + let after = active_pixels(&s); + if has_sel { + // A pixel far from the selection is unchanged. + let i = (30 * 48 + 40) * 4; + assert_eq!(after[i..i + 4], before[i..i + 4]); + let j = (5 * 48 + 5) * 4; + assert_ne!(after[j..j + 4], before[j..j + 4]); + } +} + +#[test] +fn solarize_and_add_noise_process_untouched_reveal_all_masks() { + for (id, params) in [ + ("filter.stylize.solarize", json!({"target": "mask"})), + ("filter.noise.addNoise", json!({"amount": 100, "seed": 1, "monochromatic": true, "target": "mask"})), + ] { + let mut reveal_all = mask_session(false); + let mut reveal_selection = mask_session(true); + let all_mask = reveal_all.active().unwrap().doc.layer(reveal_all.active().unwrap().active_layer.unwrap()).unwrap().mask.as_ref().unwrap(); + assert!(all_mask.surface.content_bounds().is_empty(), "{id}: Reveal All stores its white canvas in the default pixel"); + let initial_all = mask_pixels(&reveal_all); + let initial_selection = mask_pixels(&reveal_selection); + assert_eq!(initial_all, initial_selection, "{id}: masks start with equal white values"); + assert_eq!(initial_all, vec![1.0; 16 * 16], "{id}: the full canvas starts revealed"); + let pixels_before = canvas_pixels(&reveal_all); + + reveal_all.execute(id, params.clone()).unwrap(); + reveal_selection.execute(id, params).unwrap(); + + let actual = mask_pixels(&reveal_all); + let expected = mask_pixels(&reveal_selection); + assert!( + actual == expected, + "{id}: Reveal All differs from Reveal Selection: first={:?}/{:?}, changed pixels={}/{}", + actual[0], + expected[0], + actual.iter().filter(|&&v| v != 1.0).count(), + expected.iter().filter(|&&v| v != 1.0).count() + ); + assert_eq!(canvas_pixels(&reveal_all), pixels_before, "{id}: the mask target must leave layer pixels unchanged"); + if id == "filter.stylize.solarize" { + assert!(actual.iter().all(|&v| v == 0.0), "Solarize maps the white mask to black"); + } else { + assert!(actual.iter().any(|&v| v != 1.0), "seeded Add Noise changes the Reveal All mask"); + } + } +} + +#[test] +fn minimum_signed_offset_matches_its_wrapped_distance() { + for depth in [8, 16, 32] { + let make_session = || { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 48, "height": 32, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + paint_pattern(&mut s); + s + }; + let mut actual = make_session(); + let before = active_pixels(&actual); + actual.execute("filter.other.offset", json!({"horizontal": i32::MIN, "vertical": i32::MIN})).unwrap(); + let mut expected = make_session(); + expected.execute("filter.other.offset", json!({"horizontal": i32::MIN.rem_euclid(48), "vertical": i32::MIN.rem_euclid(32)})).unwrap(); + let after = active_pixels(&actual); + assert_eq!(after, active_pixels(&expected), "depth {depth}"); + assert_ne!(after, before); + actual.execute("edit.undo", json!({})).unwrap(); + assert_eq!(active_pixels(&actual), before); + actual.execute("edit.redo", json!({})).unwrap(); + assert_eq!(active_pixels(&actual), after); + } +} +#[test] +fn huge_offsets_clamp_instead_of_wrapping() { + // 3e9 wrapped to a negative offset through `as i32`; it saturates now, so it + // equals the maximal in-range offset instead of shifting the other way. + let mut a = session(); + a.execute("filter.other.offset", json!({"horizontal": 3_000_000_000_i64, "vertical": 0})).unwrap(); + let mut b = session(); + b.execute("filter.other.offset", json!({"horizontal": 2_147_483_647_i64, "vertical": 0})).unwrap(); + assert_eq!(active_pixels(&a), active_pixels(&b)); +} + +#[test] +fn last_filter_repeats_with_same_params() { + let mut s = session(); + paint_pattern(&mut s); + assert!(!s.is_enabled("filter.lastFilter")); + s.execute("filter.other.offset", json!({"horizontal": 3})).unwrap(); + let once = active_pixels(&s); + s.execute("filter.lastFilter", json!({})).unwrap(); + let twice = active_pixels(&s); + assert_ne!(once, twice); + // Offsetting 3 twice equals offsetting 6 once. + let mut s2 = session(); + paint_pattern(&mut s2); + s2.execute("filter.other.offset", json!({"horizontal": 6})).unwrap(); + assert_eq!(active_pixels(&s2), twice); +} + +#[test] +fn recorded_last_filter_replays_the_filter_it_repeated() { + // #3089: the action holds the filter with its settings, not a "repeat whatever ran + // last" step that fails in a new session. + let mut s = session(); + paint_pattern(&mut s); + s.execute("filter.other.offset", json!({"horizontal": 3})).unwrap(); + s.execute("actions.record", json!({"name": "Again"})).unwrap(); + s.execute("filter.lastFilter", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let steps = s.execute("actions.get", json!({"action": "Again"})).unwrap()["steps"].clone(); + assert_eq!(steps, json!([["filter.other.offset", {"horizontal": 3}]])); + let action = s.actions.list[0].clone(); + + let mut fresh = session(); + paint_pattern(&mut fresh); + fresh.actions.list.push(action); + let played = fresh.execute("actions.play", json!({"action": "Again"})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + let mut direct = session(); + paint_pattern(&mut direct); + direct.execute("filter.other.offset", json!({"horizontal": 3})).unwrap(); + assert_eq!(active_pixels(&fresh), active_pixels(&direct)); +} + +#[test] +fn last_filter_applies_to_the_active_layer() { + let mut s = session(); + paint_pattern(&mut s); + let first = s.active().unwrap().active_layer.unwrap(); + // Dialogs (Filter Gallery, Camera Raw…) record the layer they ran on. + s.execute("filter.other.offset", json!({"horizontal": 3, "layer": first.0})).unwrap(); + let first_once = active_pixels(&s); + s.execute("layer.new.layer", json!({})).unwrap(); + paint_pattern(&mut s); + let before = active_pixels(&s); + s.execute("filter.lastFilter", json!({})).unwrap(); + assert_ne!(active_pixels(&s), before, "the active layer is filtered"); + let d = s.active().unwrap(); + let l = d.doc.layer(first).unwrap(); + assert_eq!(l.surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 48, 32)), first_once, "the first layer is left alone"); +} + +#[test] +fn params_map_to_algorithm_units() { + assert_eq!(params_for("filter.blur.gaussianBlur", &json!({"radius": 4.5})), Some(FilterParams::GaussianBlur { radius: 4.5 })); + assert_eq!( + params_for("filter.blur.radialBlur", &json!({"quality": "best"})), + Some(FilterParams::RadialBlur { amount: 10.0, method: RadialMethod::Spin, quality: RadialQuality::Best, center_x: 0.5, center_y: 0.5 }) + ); + assert_eq!( + params_for("filter.noise.addNoise", &json!({"amount": 10, "distribution": "gaussian", "monochromatic": true})), + Some(FilterParams::AddNoise { amount: 10.0, distribution: Distribution::Gaussian, monochromatic: true, seed: 0 }) + ); + assert_eq!(params_for("filter.blur.gaussianBlur", &json!({"radius": -3})), Some(FilterParams::GaussianBlur { radius: 0.1 })); + assert!(params_for("filter.nope", &json!({})).is_none()); +} + +#[test] +fn minimum_maximum_preserve_roundness() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 48, "height": 32, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + // A white dot on black. + s.edit("dot", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(photocraft_geom::Rect::new(0, 0, 48, 32), &[0.0, 0.0, 0.0, 1.0]); + surf.write_pixel(24, 16, &[1.0, 1.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + let before = active_pixels(&s); + let lit = |s: &Session, x: usize, y: usize| active_pixels(s)[(y * 48 + x) * 4] > 0.5; + s.execute("filter.other.maximum", json!({"radius": 4, "preserve": "roundness"})).unwrap(); + // Grown into a disc of radius 4: (4, 0) and (2, 3) are in, the square's corner isn't. + assert!(lit(&s, 28, 16) && lit(&s, 26, 19), "depth {depth}"); + assert!(!lit(&s, 28, 20) && !lit(&s, 27, 19), "depth {depth}"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(active_pixels(&s), before); + // The default is Squareness: the corner is taken. + s.execute("filter.other.maximum", json!({"radius": 4})).unwrap(); + assert!(lit(&s, 28, 20), "depth {depth}"); + // Minimum with roundness: only the centre of that 9×9 square holds a whole disc. + s.execute("filter.other.minimum", json!({"radius": 4, "preserve": "roundness"})).unwrap(); + assert!(!lit(&s, 20, 12) && lit(&s, 24, 16), "depth {depth}"); + } + assert_eq!( + params_for("filter.other.minimum", &json!({"radius": 2, "preserve": "roundness"})), + Some(FilterParams::Minimum { radius: 2.0, preserve: Preserve::Roundness }) + ); + assert_eq!(params_for("filter.other.maximum", &json!({})), Some(FilterParams::Maximum { radius: 1.0, preserve: Preserve::Squareness })); +} + +#[test] +fn smart_object_records_smart_filter() { + use photocraft_doc::{Layer, SmartObject, SmartSource}; + let mut s = session(); + s.edit("smart", |doc, active| { + let mut cache = photocraft_raster::Surface::new(doc.pixel_format()); + cache.fill_rect(photocraft_geom::Rect::new(0, 0, 10, 10), &[1.0, 0.0, 0.0, 1.0]); + let l = Layer::new( + "so", + LayerContent::Smart(SmartObject { + contents_id: photocraft_doc::SmartContentsId::fresh(), + source: SmartSource::Linked { path: String::new() }, + transform: photocraft_geom::Affine::IDENTITY, + smart_filters: vec![], + cache: Some(cache), + psd_raw: None, + filters_enabled: true, + filter_mask: None, + warp: None, + stack_mode: None, + perspective: None, + }), + ); + *active = Some(doc.insert_above(*active, l)); + Ok(()) + }) + .unwrap(); + s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); + let d = s.active().unwrap(); + let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!() }; + assert_eq!(sm.smart_filters.len(), 1); + assert_eq!(sm.smart_filters[0].command, "filter.blur.gaussianBlur"); + assert_eq!(sm.smart_filters[0].params["radius"], json!(2)); + assert!(sm.cache.as_ref().unwrap().pixel(10, 5)[3] > 0.0, "cache was blurred"); +} + +/// The serial `keep_alpha` before #6205, kept as the oracle for the parallel one. +fn keep_alpha_serial(old: &photocraft_raster::Surface, new: &mut photocraft_raster::Surface) { + if old.format() != new.format() || !new.format().alpha { + return; + } + let mut coords: Vec<_> = new.tiles().filter(|(c, t)| old.tile(**c).is_none_or(|o| !std::sync::Arc::ptr_eq(o, t))).map(|(c, _)| *c).collect(); + coords.extend(old.tiles().filter(|(c, _)| new.tile(**c).is_none()).map(|(c, _)| *c)); + let n = new.channels(); + for c in coords { + let r = c.rect(); + let o = old.read_region(r); + let mut v = new.read_region(r); + for (pn, po) in v.chunks_exact_mut(n).zip(o.chunks_exact(n)) { + if let (Some(a), Some(b)) = (pn.last_mut(), po.last()) { + *a = *b; + } + } + new.write_region(r, &v); + } + new.prune(); +} + +/// A layer before and after a filter: tiles the filter changed, one it left shared, one it +/// emptied (only in `old`) and one it added (only in `new`). +fn alpha_pair(sample: photocraft_color::SampleType) -> (photocraft_raster::Surface, photocraft_raster::Surface) { + use photocraft_geom::Rect; + use photocraft_raster::Surface; + let fmt = photocraft_color::PixelFormat { mode: photocraft_color::ColorMode::Rgb, sample, alpha: true }; + let pattern = |r: Rect, k: f32| -> Vec { + (0..r.width() as usize * r.height() as usize * 4).map(|i| ((i as f32 * 0.37 + k).sin() * 0.5 + 0.5).clamp(0.0, 1.0)).collect() + }; + let mut old = Surface::new(fmt); + let r = Rect::new(-40, -20, 700, 300); + old.write_region(r, &pattern(r, 0.0)); + let mut new = old.clone(); + let changed = Rect::new(-40, -20, 400, 300); + new.write_region(changed, &pattern(changed, 1.3)); + let emptied = photocraft_geom::TileCoord::containing(600, 100).rect(); + drop(new.take_tiles(emptied)); + let added = Rect::new(800, 0, 900, 50); + new.write_region(added, &pattern(added, 2.1)); + (old, new) +} + +#[test] +fn keep_alpha_matches_the_serial_pass_at_every_depth() { + use photocraft_color::SampleType; + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let (old, new) = alpha_pair(sample); + let mut want = new.clone(); + keep_alpha_serial(&old, &mut want); + let mut got = new.clone(); + keep_alpha(&old, &mut got, &|| false).unwrap(); + assert!(got == want, "{sample:?}: parallel keep_alpha differs from the serial pass"); + assert_ne!(got, new, "{sample:?}: alpha was put back"); + } +} + +#[test] +fn keep_alpha_stops_when_cancelled_and_keeps_the_tiles() { + let (old, new) = alpha_pair(photocraft_color::SampleType::U8); + let mut got = new.clone(); + let calls = std::sync::atomic::AtomicUsize::new(0); + let cancel = || calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 2; + assert!(matches!(keep_alpha(&old, &mut got, &cancel), Err(EngineError::Cancelled))); + // The cancel was seen inside the pass (after some tiles), and no tile went missing. + assert!(calls.load(std::sync::atomic::Ordering::SeqCst) > 2); + assert!(new.tiles().all(|(c, _)| got.tile(*c).is_some())); +} + +/// #7423: Displace on a Smart Object keeps its map (read from an open document) in the smart +/// filter, as Photoshop embeds it, so the filter displaces and keeps displacing when the +/// object re-renders. A map chosen again replaces it. +#[test] +fn displace_on_a_smart_object_embeds_its_map() { + let mut s = Session::new(); + // Documents 0 and 1: a white and a black displacement map. + s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "black"})).unwrap(); + s.execute("file.new", json!({"width": 48, "height": 32, "background": "transparent"})).unwrap(); + s.edit("square", |doc, active| { + let fmt = doc.pixel_format(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(photocraft_geom::Rect::new(10, 10, 20, 12), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + Ok(()) + }) + .unwrap(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let original = { + let d = s.active().unwrap(); + let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; + sm.cache.as_ref().unwrap().read_region(d.doc.bounds()) + }; + let smart = |s: &Session| { + let d = s.active().unwrap(); + let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; + (sm.smart_filters[0].params.clone(), sm.cache.as_ref().unwrap().read_region(d.doc.bounds())) + }; + let first_value = |params: &Value| photocraft_io::smart_map::displace_embedded_map(params).expect("an embedded map").data[0]; + + s.execute("filter.distort.displace", json!({"horizontal": 10, "vertical": 0, "mapDocument": 0})).unwrap(); + let (params, displaced) = smart(&s); + assert!(params.get("mapDocument").is_none(), "{params}"); + assert_eq!(first_value(¶ms), 1.0, "the white map"); + assert_ne!(displaced, original, "the smart object is displaced"); + // Re-rendered from its params alone (the filter hidden and shown again): still displaced. + s.execute("layer.smartFilter.setVisible", json!({"index": 0, "visible": false})).unwrap(); + assert_eq!(smart(&s).1, original); + s.execute("layer.smartFilter.setVisible", json!({"index": 0, "visible": true})).unwrap(); + assert_eq!(smart(&s).1, displaced); + + // Another map chosen for the filter replaces the embedded one. + s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": {"mapDocument": 1}})).unwrap(); + let (params, again) = smart(&s); + assert!(params.get("mapDocument").is_none(), "{params}"); + assert_eq!(first_value(¶ms), 0.0, "the black map"); + assert_ne!(again, displaced, "displaced the other way"); + + // The stored params passed back whole (the old embedded map included) with another map + // named: the named map wins, for the filter's own edit and for a new Displace alike. + let mut back = params.as_object().unwrap().clone(); + back.insert("mapDocument".into(), json!(0)); + s.execute("layer.smartFilter.setParams", json!({"index": 0, "params": back.clone()})).unwrap(); + assert_eq!(first_value(&smart(&s).0), 1.0, "the white map, not the embedded black one"); + back.insert("mapDocument".into(), json!(1)); + s.execute("filter.distort.displace", Value::Object(back)).unwrap(); + let d = s.active().unwrap(); + let LayerContent::Smart(sm) = &d.doc.layer(d.active_layer.unwrap()).unwrap().content else { panic!("not a smart object") }; + assert_eq!(first_value(&sm.smart_filters[1].params), 0.0, "the black map, not the passed-back white one"); +} From b6f8d5227f98bc84dc4cccf50e7f4896ea22d1e4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:21 +0000 Subject: [PATCH 042/259] refactor(engine): move smartselect_cmds.rs tests to smartselect_cmds/tests.rs --- crates/engine/src/smartselect_cmds.rs | 689 +------------------- crates/engine/src/smartselect_cmds/tests.rs | 686 +++++++++++++++++++ 2 files changed, 687 insertions(+), 688 deletions(-) create mode 100644 crates/engine/src/smartselect_cmds/tests.rs diff --git a/crates/engine/src/smartselect_cmds.rs b/crates/engine/src/smartselect_cmds.rs index cfd1b333e0..b8beea5a80 100644 --- a/crates/engine/src/smartselect_cmds.rs +++ b/crates/engine/src/smartselect_cmds.rs @@ -567,691 +567,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_algo::segment::Rng; - - /// A document whose background shows `px(x, y)` (RGB, 0–1), at the given depth. - fn session_with(w: u32, h: u32, depth: u32, px: impl Fn(u32, u32) -> [f32; 3]) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap(); - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - let n = bg.channels(); - let mut data = Vec::with_capacity((w * h) as usize * n); - for y in 0..h { - for x in 0..w { - let c = px(x, y); - data.extend_from_slice(&c[..n.min(3)]); - if n == 4 { - data.push(1.0); - } - } - } - bg.write_region(Rect::new(0, 0, w as i32, h as i32), &data); - Ok(()) - }) - .unwrap(); - s - } - - fn noise_field(w: u32, h: u32, seed: u64) -> Vec { - let mut rng = Rng::new(seed); - (0..w * h).map(|_| rng.normal()).collect() - } - - /// Warm textured left part (x < 60), cool right part. - fn two_regions(depth: u32) -> Session { - let nz = noise_field(140, 100, 1); - session_with(140, 100, depth, move |x, y| { - let n = 0.04 * nz[(y * 140 + x) as usize]; - if x < 60 { [0.8 + n, 0.5 + n, 0.3] } else { [0.2, 0.35 + n, 0.6 + n] }.map(|v| v.clamp(0.0, 1.0)) - }) - } - - /// Textured disc (centre (100, 80), radius 45) on a noisy background. - fn disc(depth: u32) -> (Session, impl Fn(i32, i32) -> bool) { - let nz = noise_field(200, 160, 2); - let inside = |x: i32, y: i32| { - let (dx, dy) = (x as f32 + 0.5 - 100.0, y as f32 + 0.5 - 80.0); - dx * dx + dy * dy <= 45.0 * 45.0 - }; - let s = session_with(200, 160, depth, move |x, y| { - let n = 0.05 * nz[(y * 200 + x) as usize]; - if inside(x as i32, y as i32) { - let t = ((x + y) as f32 * 0.35).sin() * 0.5 + 0.5; - [0.85 + 0.05 * t + n, 0.2 + 0.3 * t + n, 0.15 + n] - } else { - [0.25 + n, 0.45 + n, 0.7 + n] - } - .map(|v| v.clamp(0.0, 1.0)) - }); - (s, inside) - } - - fn cov(s: &Session, x: i32, y: i32) -> f32 { - s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0)) - } - - fn sel_iou(s: &Session, w: i32, h: i32, truth: impl Fn(i32, i32) -> bool) -> f32 { - let (mut i, mut u) = (0, 0); - for y in 0..h { - for x in 0..w { - let (a, b) = (cov(s, x, y) >= 0.5, truth(x, y)); - i += (a && b) as i32; - u += (a || b) as i32; - } - } - i as f32 / u.max(1) as f32 - } - - #[test] - fn quick_selection_add_subtract_undo() { - for depth in [8, 16] { - let mut s = two_regions(depth); - let r = s.execute("select.quick", json!({"points": [[20, 50], [35, 50]], "size": 8})).unwrap(); - assert_eq!(r["selected"], true); - for y in (0..100).step_by(7) { - for x in (0..140).step_by(3) { - let c = cov(&s, x, y); - if x < 57 { - assert!(c >= 0.5, "depth {depth}: ({x},{y}) not selected"); - } else if x > 62 { - assert!(c < 0.5, "depth {depth}: leaked to ({x},{y})"); - } - } - } - // A second stroke on the right adds it. - s.execute("select.quick", json!({"points": [[100, 50]], "size": 8})).unwrap(); - assert!(cov(&s, 130, 90) >= 0.5 && cov(&s, 10, 10) >= 0.5); - // Subtract the left region again. - s.execute("select.quick", json!({"points": [[20, 50]], "size": 8, "mode": "subtract"})).unwrap(); - assert!(cov(&s, 10, 10) < 0.5 && cov(&s, 130, 90) >= 0.5); - s.execute("edit.undo", json!({})).unwrap(); - assert!(cov(&s, 10, 10) >= 0.5); - assert!(s.execute("select.quick", json!({"points": []})).is_err()); - } - } - - #[test] - fn quick_selection_subtract_from_select_all_and_enhance() { - let mut s = two_regions(8); - s.execute("select.all", json!({})).unwrap(); - s.execute("select.quick", json!({"points": [[100, 30], [110, 70]], "size": 10, "mode": "subtract"})).unwrap(); - assert!(cov(&s, 10, 50) >= 0.99); - assert!(cov(&s, 120, 20) < 0.01 && cov(&s, 70, 90) < 0.01); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("select.quick", json!({"points": [[20, 50]], "size": 8, "enhanceEdge": true})).unwrap(); - assert!(cov(&s, 10, 10) >= 0.5 && cov(&s, 100, 50) < 0.5); - } - - #[test] - fn empty_result_keeps_the_selection_in_every_mode() { - // Finding nothing must never wipe the selection, whatever the mode: Select Subject - // and Object Selection run heuristics that often miss on busy photos, and a missed - // Quick Selection dab must not destroy the work either. - for m in ["add", "subtract", "replace"] { - let mut s = two_regions(8); - s.execute("select.all", json!({})).unwrap(); - let r = s.execute("select.quick", json!({"points": [[-5000, -5000]], "size": 8, "mode": m})).unwrap(); - assert_eq!(r["changed"], false, "mode {m}"); - assert_eq!(r["selected"], true, "mode {m}"); - assert!(cov(&s, 10, 50) >= 0.99, "mode {m}: Select All survived an empty result"); - } - // Select Subject on a flat field finds nothing and keeps the selection too. - let mut s = session_with(140, 100, 8, |_, _| [0.5, 0.5, 0.5]); - s.execute("select.all", json!({})).unwrap(); - let r = s.execute("select.subject", json!({})).unwrap(); - assert_eq!(r["changed"], false); - assert!(cov(&s, 10, 10) >= 0.99); - } - - #[test] - fn object_selection_point_selects_the_object_under_it() { - for depth in [8, 16, 32] { - let (mut s, inside) = disc(depth); - let r = s.execute("select.object", json!({"point": [100, 80]})).unwrap(); - assert_eq!(r["changed"], true, "depth {depth}"); - let v = sel_iou(&s, 200, 160, &inside); - assert!(v > 0.9, "depth {depth}: IoU {v}"); - } - // The background is no object: nothing changes. - let (mut s, _) = disc(8); - let r = s.execute("select.object", json!({"point": [3, 3]})).unwrap(); - assert_eq!(r["changed"], false); - assert!(s.active().unwrap().doc.selection.is_none()); - assert!(s.execute("select.object", json!({"point": ["a", 1]})).is_err()); - } - - #[test] - fn object_selection_finds_a_large_foreground_at_each_depth_and_undoes() { - for depth in [8, 16, 32] { - let inside = |x: i32, y: i32| (10..190).contains(&x) && (8..152).contains(&y); - let mut s = session_with(200, 160, depth, |x, y| if inside(x as i32, y as i32) { [0.8, 0.2, 0.1] } else { [0.1, 0.2, 0.8] }); - let r = s.execute("select.object", json!({"point": [100, 80]})).unwrap(); - assert_eq!(r["changed"], true, "depth {depth}"); - assert!(sel_iou(&s, 200, 160, inside) > 0.95, "depth {depth}"); - s.execute("edit.undo", json!({})).unwrap(); - assert!(s.active().unwrap().doc.selection.is_none()); - let r = s.execute("select.object", json!({"point": [1, 1]})).unwrap(); - assert_eq!(r["changed"], false, "background at depth {depth}"); - assert!(s.active().unwrap().doc.selection.is_none()); - } - } - - #[test] - fn object_selection_point_honours_the_modes() { - let (mut s, _) = disc(8); - s.execute("select.all", json!({})).unwrap(); - s.execute("select.object", json!({"point": [100, 80], "mode": "subtract"})).unwrap(); - assert!(cov(&s, 100, 80) < 0.5 && cov(&s, 3, 3) >= 0.5); - s.execute("select.object", json!({"point": [100, 80], "mode": "add"})).unwrap(); - assert!(cov(&s, 100, 80) >= 0.5 && cov(&s, 3, 3) >= 0.5); - s.execute("select.object", json!({"point": [100, 80], "mode": "intersect"})).unwrap(); - assert!(cov(&s, 100, 80) >= 0.5 && cov(&s, 3, 3) < 0.5); - } - - #[test] - fn object_finder_cache_serves_the_whole_object_until_pixels_change() { - let (mut s, _) = disc(8); - let d = s.active().unwrap(); - let doc = std::sync::Arc::clone(&d.doc); - let target = sampled_target(&doc, d.active_layer, false); - assert!(s.object_finder.lookup(&doc, target, 100.0, 80.0).is_none()); - let r = std::sync::Arc::new(find_object(&doc, d.active_layer, false, 100.0, 80.0).unwrap()); - s.object_finder.insert(&doc, target, std::sync::Arc::clone(&r)); - // Any point on the object hits; the background and another target miss. - assert!(std::sync::Arc::ptr_eq(&s.object_finder.lookup(&doc, target, 120.0, 90.0).unwrap(), &r)); - assert!(s.object_finder.lookup(&doc, target, 3.0, 3.0).is_none()); - assert!(s.object_finder.lookup(&doc, Some(LayerId(u64::MAX)), 100.0, 80.0).is_none()); - // The click reuses it, and a selection-only edit keeps it. - s.execute("select.object", json!({"point": [110, 70]})).unwrap(); - assert_eq!(s.object_finder.len(), 1); - s.execute("select.deselect", json!({})).unwrap(); - let d = s.active().unwrap(); - assert!(s.object_finder.lookup(&std::sync::Arc::clone(&d.doc), target, 100.0, 80.0).is_some()); - // A pixel edit drops it. - s.execute("paint.pencil", json!({"points": [[5, 5], [30, 5]], "size": 4, "color": "#000000"})).unwrap(); - assert!(s.object_finder.is_empty()); - } - - #[test] - fn object_selection_disc() { - for depth in [8, 16, 32] { - let (mut s, inside) = disc(depth); - s.execute("select.object", json!({"rect": [40, 20, 120, 120]})).unwrap(); - let v = sel_iou(&s, 200, 160, &inside); - assert!(v > 0.95, "depth {depth}: IoU {v}"); - } - let (mut s, _) = disc(8); - assert!(s.execute("select.object", json!({"rect": [1, 2]})).is_err()); - // Negative width/height (drag up-left) work too. - s.execute("select.object", json!({"rect": [160, 140, -120, -120]})).unwrap(); - assert!(cov(&s, 100, 80) >= 0.5); - } - - #[test] - fn object_selection_on_an_empty_active_layer_says_so() { - // #5246: an empty layer above the photo used to find nothing without a word. - let (mut s, inside) = disc(8); - s.execute("layer.new.layer", json!({})).unwrap(); - for p in [json!({"rect": [40, 20, 120, 120]}), json!({"point": [100, 80]})] { - let e = s.execute("select.object", p.clone()).unwrap_err().to_string(); - assert!(e.contains("active layer is empty") && e.contains("sampleAllLayers"), "{p}: {e}"); - assert!(s.active().unwrap().doc.selection.is_none()); - } - // Sampling all layers finds the disc below. - s.execute("select.object", json!({"rect": [40, 20, 120, 120], "sampleAllLayers": true})).unwrap(); - assert!(sel_iou(&s, 200, 160, &inside) > 0.95); - // A layer with pixels elsewhere: the rectangle holds none of them. - s.execute("select.deselect", json!({})).unwrap(); - s.execute("paint.pencil", json!({"points": [[5, 5], [10, 5]], "size": 2, "color": "#000000"})).unwrap(); - let e = s.execute("select.object", json!({"rect": [60, 60, 100, 80]})).unwrap_err().to_string(); - assert!(e.contains("no pixels in that area"), "{e}"); - } - - #[test] - fn select_subject_centred_object() { - let (mut s, inside) = disc(8); - assert!(s.is_enabled("select.subject")); - s.execute("select.subject", json!({})).unwrap(); - let v = sel_iou(&s, 200, 160, inside); - assert!(v > 0.9, "IoU {v}"); - s.execute("edit.undo", json!({})).unwrap(); - assert!(s.active().unwrap().doc.selection.is_none()); - } - - /// #2865: a repeat on unchanged pixels reuses the last mask (an identical selection, even - /// after Deselect); sampling something else or a pixel edit computes it again. - #[test] - fn select_subject_repeat_reuses_the_mask_until_pixels_change() { - let (mut s, _) = disc(8); - let sel = |s: &Session| { - let mut v = Vec::new(); - s.active().unwrap().doc.selection.as_ref().unwrap().read_region_into(Rect::new(0, 0, 200, 160), &mut v); - v - }; - let cached = |s: &Session| s.subject_cache.region.clone().unwrap(); - s.execute("select.subject", json!({})).unwrap(); - let (first, mask) = (sel(&s), cached(&s)); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("select.subject", json!({})).unwrap(); - assert!(std::sync::Arc::ptr_eq(&mask, &cached(&s)), "the repeat recomputed the mask"); - assert_eq!(sel(&s), first); - // Another sampled target (the layer rather than the composite) is a miss. - s.execute("select.subject", json!({"sampleAllLayers": false})).unwrap(); - assert!(!std::sync::Arc::ptr_eq(&mask, &cached(&s))); - // A pixel edit drops the entry; the next run recomputes it. - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - let n = bg.channels(); - bg.write_region(Rect::new(0, 0, 1, 1), &vec![1.0; n]); - Ok(()) - }) - .unwrap(); - assert!(s.subject_cache.region.is_none()); - s.execute("select.subject", json!({})).unwrap(); - assert_eq!(sel(&s), first); - } - - /// A vertical Gaussian-blurred edge at x = 40 (warm left, cool right) with the left half selected. - fn blurred_edge_selected() -> Session { - blurred_edge_selected_at(8) - } - - fn blurred_edge_selected_at(depth: u32) -> Session { - let mut s = session_with(80, 40, depth, |x, _| { - let t = 1.0 / (1.0 + ((x as f32 + 0.5 - 40.0) / 1.8).exp()); - [0.9 * t + 0.1 * (1.0 - t), 0.8 * t + 0.2 * (1.0 - t), 0.2 * t + 0.6 * (1.0 - t)] - }); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap(); - s - } - - fn soft_count(s: &photocraft_raster::Surface, y: i32) -> usize { - (0..80) - .filter(|x| { - let v = s.sample_channel(*x, y, 0); - v > 0.05 && v < 0.95 - }) - .count() - } - - #[test] - fn refine_edge_outputs_and_undo() { - // Selection output: the hard edge becomes a soft matte following the blur. - let mut s = blurred_edge_selected(); - assert!(s.is_enabled("select.refineEdge")); - s.execute("select.refineEdge", json!({"radius": 8})).unwrap(); - let sel = s.active().unwrap().doc.selection.clone().unwrap(); - assert!(soft_count(&sel, 20) >= 4, "selection edge not soft"); - assert!(sel.sample_channel(5, 20, 0) > 0.99 && sel.sample_channel(75, 20, 0) < 0.01); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(soft_count(s.active().unwrap().doc.selection.as_ref().unwrap(), 20), 0); - - // Layer mask output. - let layers_before = s.active().unwrap().doc.layer_count(); - let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "layerMask"})).unwrap(); - let d = s.active().unwrap(); - let l = d.doc.layer(photocraft_doc::LayerId(r["layer"].as_u64().unwrap())).unwrap(); - let m = l.mask.as_ref().unwrap(); - assert!(soft_count(&m.surface, 20) >= 4); - assert!(m.value(5, 20) > 0.99 && m.value(75, 20) < 0.01); - assert!(d.doc.selection.is_none()); - assert_eq!(d.doc.layer_count(), layers_before); - s.execute("edit.undo", json!({})).unwrap(); - assert!(s.active().unwrap().doc.layers[0].mask.is_none()); - assert!(s.active().unwrap().doc.selection.is_some()); - - // Existing mask settings (density, feather, linked) are preserved - s.edit("set mask", |doc, _| { - doc.layers[0].mask = Some(photocraft_doc::LayerMask { - surface: photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8), - density: 0.75, - feather: 3.5, - linked: false, - enabled: true, - }); - Ok(()) - }) - .unwrap(); - let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "layerMask"})).unwrap(); - let l = s.active().unwrap().doc.layer(photocraft_doc::LayerId(r["layer"].as_u64().unwrap())).unwrap(); - let m = l.mask.as_ref().unwrap(); - assert_eq!(m.density, 0.75); - assert_eq!(m.feather, 3.5); - assert!(!m.linked); - s.execute("edit.undo", json!({})).unwrap(); - s.edit("clear mask", |doc, _| { - doc.layers[0].mask = None; - Ok(()) - }) - .unwrap(); - - // New layer: pixels with the refined alpha; the source is hidden. - let r = s.execute("select.refineEdge", json!({"radius": 8, "feather": 1, "output": "newLayer"})).unwrap(); - let d = s.active().unwrap(); - let nid = photocraft_doc::LayerId(r["layer"].as_u64().unwrap()); - assert_eq!(d.active_layer, Some(nid)); - assert_eq!(d.doc.layer_count(), layers_before + 1); - let nl = d.doc.layer(nid).unwrap(); - let surf = nl.surface().unwrap(); - assert!(surf.format().alpha); - let a = |x: i32| surf.pixel(x, 20)[3]; - assert!(a(5) > 0.99 && a(75) == 0.0 && a(40) > 0.05 && a(40) < 0.95); - assert!(!d.doc.layers[0].visible); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(s.active().unwrap().doc.layer_count(), layers_before); - assert!(s.active().unwrap().doc.layers[0].visible); - - // New layer with mask + decontamination (selection output upgrades to it). - let r = s.execute("select.refineEdge", json!({"radius": 8, "decontaminate": true, "amount": 100})).unwrap(); - assert_eq!(r["output"], "newLayerWithMask"); - let d = s.active().unwrap(); - let nl = d.doc.layer(photocraft_doc::LayerId(r["layer"].as_u64().unwrap())).unwrap(); - assert!(nl.mask.is_some()); - let px = nl.surface().unwrap().pixel(41, 20); - let orig = d.doc.layers[0].surface().unwrap().pixel(41, 20); - // The fringe colour moved towards the warm foreground (more red, less blue). - assert!(px[0] > orig[0] + 0.05 && px[2] < orig[2] - 0.05, "{px:?} vs {orig:?}"); - s.execute("edit.undo", json!({})).unwrap(); - assert!(s.execute("select.refineEdge", json!({"output": "bogus"})).is_err()); - s.execute("select.deselect", json!({})).unwrap(); - assert!(!s.is_enabled("select.refineEdge")); - } - - /// Output To New Document (with or without a layer mask) opens a document like the source, - /// at every depth, and leaves the source document as it was. - #[test] - fn refine_edge_outputs_to_a_new_document() { - for depth in [8, 16, 32] { - let mut s = blurred_edge_selected_at(depth); - s.edit("profile", |doc, _| { - doc.resolution_dpi = 300.0; - Ok(()) - }) - .unwrap(); - let before = s.active().unwrap().doc.clone(); - let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "newDocument"})).unwrap(); - assert_eq!((r["output"].as_str(), r["document"].as_u64()), (Some("newDocument"), Some(1)), "depth {depth}"); - assert_eq!(s.active_index(), Some(1)); - let nd = &s.active().unwrap().doc; - assert_eq!((nd.size, nd.mode, nd.depth, nd.resolution_dpi), (before.size, before.mode, before.depth, 300.0)); - assert_eq!(nd.layers.len(), 1); - assert!(nd.selection.is_none() && nd.layers[0].mask.is_none()); - let surf = nd.layers[0].surface().unwrap(); - let a = |x: i32| surf.pixel(x, 20)[3]; - assert!(a(5) > 0.99 && a(75) == 0.0 && a(40) > 0.05 && a(40) < 0.95, "depth {depth}: {} {} {}", a(5), a(40), a(75)); - // The source is untouched: same layers, still visible, selection kept, no history step. - let src = &s.documents()[0]; - assert_eq!(src.doc.layers, before.layers); - assert_eq!(src.doc.selection, before.selection); - assert_eq!(src.history.undo_label(), Some("profile")); - - // With a layer mask: full pixels, the refined matte as the mask. - s.execute("file.close", json!({"document": 1})).unwrap(); - let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "newDocumentWithMask"})).unwrap(); - assert_eq!(r["output"], "newDocumentWithMask"); - let nd = &s.active().unwrap().doc; - let l = &nd.layers[0]; - assert_eq!(l.surface().unwrap().pixel(75, 20), before.layers[0].surface().unwrap().pixel(75, 20), "depth {depth}"); - let m = l.mask.as_ref().unwrap(); - assert!(soft_count(&m.surface, 20) >= 4, "depth {depth}"); - assert!(m.value(5, 20) > 0.99 && m.value(75, 20) < 0.01, "depth {depth}"); - } - } - - #[test] - fn refine_edge_shift_and_contrast() { - let mut s = blurred_edge_selected(); - s.execute("select.refineEdge", json!({"shiftEdge": 100})).unwrap(); - assert!(cov(&s, 42, 20) > 0.99); - s.execute("edit.undo", json!({})).unwrap(); - s.execute("select.refineEdge", json!({"feather": 8, "contrast": 100})).unwrap(); - assert!(cov(&s, 38, 20) == 1.0 && cov(&s, 42, 20) == 0.0); - } - - /// The Refine Edge Brush adds strands beyond the radius band, at every depth, and rejects - /// malformed strokes. - #[test] - fn refine_edge_brush_strokes() { - for depth in [8, 16, 32] { - // Warm subject (x < 40) with warm strands every 4th column from x = 60, on blue. - let strand = |x: u32| x < 40 || ((60..84).contains(&x) && x.is_multiple_of(4)); - let mut s = session_with(120, 40, depth, |x, _| if strand(x) { [0.9, 0.7, 0.2] } else { [0.1, 0.3, 0.8] }); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap(); - let stroke = json!([{"points": [[70, 5], [70, 35]], "size": 30}]); - s.execute("select.refineEdge", json!({"radius": 4, "refineStrokes": stroke})).unwrap(); - assert!(cov(&s, 64, 20) > 0.9 && cov(&s, 72, 20) > 0.9, "depth {depth}: strands {}", cov(&s, 64, 20)); - assert!(cov(&s, 66, 20) < 0.1 && cov(&s, 100, 20) < 0.01, "depth {depth}: background"); - s.execute("edit.undo", json!({})).unwrap(); - // Subtract over the same place paints the refinement out again. - let both = json!([{"points": [[70, 5], [70, 35]], "size": 30}, {"points": [[70, 5], [70, 35]], "size": 40, "mode": "subtract"}]); - s.execute("select.refineEdge", json!({"radius": 4, "refineStrokes": both})).unwrap(); - assert!(cov(&s, 64, 20) < 0.01, "depth {depth}"); - s.execute("edit.undo", json!({})).unwrap(); - for bad in [ - json!(7), - json!([5]), - json!([{"points": []}]), - json!([{"points": [[1, "x"]]}]), - json!([{"points": [[1, 2, 3]]}]), - json!([{"points": [[1, 2]], "size": 0}]), - json!([{"points": [[1, 2]], "size": 1e9}]), - json!([{"points": [[1, 2]], "mode": "xor"}]), - json!([{"points": [[0, 0], [1e6, 1e6], [0, 0], [1e6, 1e6]], "size": 5000}]), - ] { - assert!(s.execute("select.refineEdge", json!({"refineStrokes": bad})).is_err(), "{bad}"); - } - } - } - - #[test] - fn refine_edge_works_on_layer_mask_without_selection() { - let mut s = blurred_edge_selected(); - s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); - assert!(s.active().unwrap().doc.selection.is_none()); - assert!(s.active().unwrap().doc.layers[0].mask.is_some()); - assert!(s.is_enabled("select.refineEdge")); - - let r = s.execute("select.refineEdge", json!({"radius": 8})).unwrap(); - assert_eq!(r["output"], "layerMask"); - let d = s.active().unwrap(); - let m = d.doc.layers[0].mask.as_ref().unwrap(); - assert!(soft_count(&m.surface, 20) >= 4); - } - - #[test] - fn focus_area_command() { - let nz = noise_field(160, 100, 3); - let mut blurred = vec![0.0f32; nz.len()]; - for y in 0..100i32 { - for x in 0..160i32 { - let mut a = 0.0; - for dy in -4..=4 { - for dx in -4..=4 { - a += nz[((y + dy).clamp(0, 99) * 160 + (x + dx).clamp(0, 159)) as usize]; - } - } - blurred[(y * 160 + x) as usize] = a / 81.0; - } - } - let mut s = session_with(160, 100, 8, move |x, y| { - let i = (y * 160 + x) as usize; - let v = 0.5 + 0.15 * if x < 80 { nz[i] } else { blurred[i] * 3.0 }; - [v, v, v].map(|c| c.clamp(0.0, 1.0)) - }); - s.execute("select.focusArea", json!({})).unwrap(); - assert!(cov(&s, 30, 50) >= 0.5 && cov(&s, 130, 50) < 0.5); - } - /// The selection as 8-bit coverage over `w × h`, to compare two selections exactly. - fn sel_bytes(s: &Session, w: i32, h: i32) -> Vec { - (0..h).flat_map(|y| (0..w).map(move |x| (cov(s, x, y) * 255.0).round() as u8)).collect() - } - - /// The #8783 review: a refine whose result would be dense over more than - /// [`matting::MAX_REFINE_AREA`] pixels is refused, not allocated: a thin Brush edit across a - /// huge canvas (its edited selection spans the canvas) and a selection of the whole canvas. - /// The selection stays as it was. - #[test] - fn refine_edge_refuses_a_selection_too_large_to_refine() { - let mut s = Session::new(); - s.add_document( - Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8), - None, - ); - s.execute("select.rect", json!({"x": 10, "y": 60, "width": 10, "height": 10})).unwrap(); - let small = s.active().and_then(|d| d.doc.selection.clone()).expect("selected"); - let diagonal = json!({"edits": [{"tool": "brush", "points": [[0, 0], [99_999, 99_999]], "size": 1}]}); - let t = std::time::Instant::now(); - let e = s.execute("select.refineEdge", diagonal).expect_err("too large to refine"); - assert!(e.to_string().contains("too large to refine"), "{e}"); - assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&small), "the selection is unchanged"); - // The small selection itself still refines. - s.execute("select.refineEdge", json!({"radius": 4})).unwrap(); - s.execute("edit.undo", json!({})).unwrap(); - s.execute("select.all", json!({})).unwrap(); - let all = s.active().and_then(|d| d.doc.selection.clone()).expect("selected"); - assert!(s.execute("select.refineEdge", json!({"radius": 4})).is_err()); - assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&all)); - assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed()); - } - - /// The #8783 review: Brush and Lasso edits and Refine Edge Brush strokes that would paint - /// too many tiles of a huge canvas are refused before anything is painted, and the selection - /// stays as it was. - #[test] - fn refine_edge_refuses_edits_that_cross_too_many_tiles() { - let mut s = Session::new(); - s.add_document( - Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8), - None, - ); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - let before = s.active().and_then(|d| d.doc.selection.clone()).expect("selected"); - let zigzag: Vec<[f32; 2]> = (0..20).map(|i| [if i % 2 == 0 { 0.0 } else { 99_999.0 }, i as f32 * 5000.0]).collect(); - for p in [ - json!({"edits": [{"tool": "brush", "points": zigzag, "size": 1}]}), - json!({"edits": [{"tool": "lasso", "points": zigzag}]}), - json!({"refineStrokes": [{"points": zigzag, "size": 1}]}), - ] { - let e = s.execute("select.refineEdge", p.clone()).expect_err("refused"); - assert!(e.to_string().contains("too many tiles"), "{p}: {e}"); - assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&before), "{p}: the selection is unchanged"); - } - } - - /// Select and Mask's own tools (#7069, #8148): each edit changes the selection before the - /// edge is refined, at every depth, and the whole run is one history step. - #[test] - fn refine_edge_edits_apply_each_tool_at_every_depth() { - for depth in [8, 16, 32] { - let mut s = two_regions(depth); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - let start = sel_bytes(&s, 140, 100); - let run = |s: &mut Session, edits: Value| { - s.execute("select.refineEdge", json!({"edits": edits})).unwrap(); - let after = sel_bytes(s, 140, 100); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(sel_bytes(s, 140, 100), start, "depth {depth}: one undo restores the selection"); - after - }; - let at = |b: &[u8], x: usize, y: usize| b[y * 140 + x]; - // Quick Selection grows across the cool region; subtracting it again leaves the start. - let quick = run(&mut s, json!([{"tool": "quick", "points": [[100, 50], [110, 50]], "size": 8}])); - assert!(at(&quick, 120, 80) >= 128 && at(&quick, 5, 5) >= 128 && at(&quick, 40, 60) < 128, "depth {depth}: quick"); - let back = run( - &mut s, - json!([{"tool": "quick", "points": [[100, 50]], "size": 8}, {"tool": "quick", "points": [[100, 50]], "size": 8, "mode": "subtract"}]), - ); - assert!(at(&back, 120, 80) < 128 && at(&back, 5, 5) >= 128, "depth {depth}: quick subtract"); - // The Brush paints exactly where it goes. - let brush = run(&mut s, json!([{"tool": "brush", "points": [[30, 80], [60, 80]], "size": 10}])); - assert!(at(&brush, 45, 80) == 255 && at(&brush, 45, 90) == 0, "depth {depth}: brush"); - let erased = run(&mut s, json!([{"tool": "brush", "points": [[10, 10]], "size": 6, "mode": "subtract"}])); - assert!(at(&erased, 10, 10) == 0 && at(&erased, 2, 2) == 255, "depth {depth}: brush subtract"); - // Lasso adds and subtracts polygons. - let lasso = run(&mut s, json!([{"tool": "lasso", "points": [[50, 50], [90, 50], [90, 90], [50, 90]]}])); - assert!(at(&lasso, 70, 70) == 255 && at(&lasso, 95, 70) == 0 && at(&lasso, 5, 5) == 255, "depth {depth}: lasso"); - let cut = run(&mut s, json!([{"tool": "lasso", "points": [[0, 0], [10, 0], [10, 10], [0, 10]], "mode": "subtract"}])); - assert!(at(&cut, 5, 5) == 0 && at(&cut, 15, 15) == 255, "depth {depth}: lasso subtract"); - // Clear Selection, then Invert of nothing: everything. - let all = run(&mut s, json!([{"tool": "clear"}, {"tool": "invert"}])); - assert!(all.iter().all(|v| *v == 255), "depth {depth}: clear + invert"); - let inverted = run(&mut s, json!([{"tool": "invert"}])); - assert!(at(&inverted, 5, 5) == 0 && at(&inverted, 100, 50) == 255, "depth {depth}: invert"); - } - } - - /// Object Selection and Select Subject inside the workspace find what the standalone tools find. - #[test] - fn refine_edge_edits_object_and_subject() { - for depth in [8, 16, 32] { - let (mut s, inside) = disc(depth); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - s.execute("select.refineEdge", json!({"edits": [{"tool": "object", "rect": [40, 20, 120, 120]}, {"tool": "lasso", "points": [[0, 0], [10, 0], [10, 10], [0, 10]], "mode": "subtract"}]})).unwrap(); - let v = sel_iou(&s, 200, 160, &inside); - assert!(v > 0.95, "depth {depth}: object rect IoU {v}"); - s.execute("select.refineEdge", json!({"edits": [{"tool": "clear"}, {"tool": "object", "point": [3, 3]}, {"tool": "object", "point": [100, 80]}]})) - .unwrap(); - let v = sel_iou(&s, 200, 160, &inside); - assert!(v > 0.9, "depth {depth}: object point IoU {v} (the background point finds nothing)"); - } - let (mut s, inside) = disc(8); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - s.execute("select.refineEdge", json!({"edits": [{"tool": "subject"}]})).unwrap(); - let v = sel_iou(&s, 200, 160, &inside); - assert!(v > 0.9, "subject replaces the selection: IoU {v}"); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - s.execute("select.refineEdge", json!({"edits": [{"tool": "subject", "mode": "add"}]})).unwrap(); - assert!(cov(&s, 5, 5) >= 0.5 && cov(&s, 100, 80) >= 0.5, "subject added to the selection"); - } - - /// An edit gives what the standalone tool gives, then the edge is refined as usual, and the - /// result reaches every output. - #[test] - fn refine_edge_edits_match_the_tools_and_reach_the_outputs() { - let mut tool = two_regions(8); - tool.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - tool.execute("select.quick", json!({"points": [[100, 50], [110, 50]], "size": 8})).unwrap(); - let mut ws = two_regions(8); - ws.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - ws.execute("select.refineEdge", json!({"edits": [{"tool": "quick", "points": [[100, 50], [110, 50]], "size": 8}]})).unwrap(); - assert_eq!(sel_bytes(&ws, 140, 100), sel_bytes(&tool, 140, 100)); - // Refinement runs on the edited selection: Shift Edge contracts the brushed bar too. - let mut s = two_regions(8); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - s.execute("select.refineEdge", json!({"shiftEdge": -100, "edits": [{"tool": "brush", "points": [[30, 80], [100, 80]], "size": 20}]})).unwrap(); - assert!(cov(&s, 60, 80) >= 0.5 && cov(&s, 60, 88) < 0.5 && cov(&s, 60, 72) < 0.5, "the 20 px bar shrank"); - // Layer mask and new-layer outputs take the edited selection. - let mut s = blurred_edge_selected(); - let r = s.execute("select.refineEdge", json!({"output": "layerMask", "edits": [{"tool": "invert"}]})).unwrap(); - assert_eq!(r["output"], "layerMask"); - let m = s.active().unwrap().doc.layers[0].mask.as_ref().unwrap(); - assert!(m.surface.sample_channel(10, 20, 0) < 0.01 && m.surface.sample_channel(70, 20, 0) > 0.99); - let mut s = blurred_edge_selected(); - let r = s.execute("select.refineEdge", json!({"output": "newLayerWithMask", "edits": [{"tool": "invert"}]})).unwrap(); - assert_eq!(r["output"], "newLayerWithMask"); - let d = s.active().unwrap(); - let m = d.doc.layers.iter().find_map(|l| l.mask.as_ref()).unwrap(); - assert!(m.surface.sample_channel(10, 20, 0) < 0.01 && m.surface.sample_channel(70, 20, 0) > 0.99); - // Clearing everything deselects. - let mut s = blurred_edge_selected(); - let r = s.execute("select.refineEdge", json!({"edits": [{"tool": "clear"}]})).unwrap(); - assert_eq!(r["selected"], false); - assert!(s.active().unwrap().doc.selection.is_none()); - } - - /// Bad edits are refused before anything changes. - #[test] - fn refine_edge_rejects_bad_edits_and_keeps_the_selection() { - let mut s = blurred_edge_selected(); - let before = sel_bytes(&s, 80, 40); - for bad in - [json!(7), json!([{"tool": "nope"}]), json!([{"tool": "lasso", "points": [[0, 0]]}]), json!([{"tool": "brush", "points": [[0, 0]], "size": -1}])] - { - assert!(s.execute("select.refineEdge", json!({"edits": bad})).is_err(), "{bad}"); - assert_eq!(sel_bytes(&s, 80, 40), before, "{bad}"); - } - } -} +mod tests; diff --git a/crates/engine/src/smartselect_cmds/tests.rs b/crates/engine/src/smartselect_cmds/tests.rs new file mode 100644 index 0000000000..f71cae6f85 --- /dev/null +++ b/crates/engine/src/smartselect_cmds/tests.rs @@ -0,0 +1,686 @@ +use super::*; +use photocraft_algo::segment::Rng; + +/// A document whose background shows `px(x, y)` (RGB, 0–1), at the given depth. +fn session_with(w: u32, h: u32, depth: u32, px: impl Fn(u32, u32) -> [f32; 3]) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap(); + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + let n = bg.channels(); + let mut data = Vec::with_capacity((w * h) as usize * n); + for y in 0..h { + for x in 0..w { + let c = px(x, y); + data.extend_from_slice(&c[..n.min(3)]); + if n == 4 { + data.push(1.0); + } + } + } + bg.write_region(Rect::new(0, 0, w as i32, h as i32), &data); + Ok(()) + }) + .unwrap(); + s +} + +fn noise_field(w: u32, h: u32, seed: u64) -> Vec { + let mut rng = Rng::new(seed); + (0..w * h).map(|_| rng.normal()).collect() +} + +/// Warm textured left part (x < 60), cool right part. +fn two_regions(depth: u32) -> Session { + let nz = noise_field(140, 100, 1); + session_with(140, 100, depth, move |x, y| { + let n = 0.04 * nz[(y * 140 + x) as usize]; + if x < 60 { [0.8 + n, 0.5 + n, 0.3] } else { [0.2, 0.35 + n, 0.6 + n] }.map(|v| v.clamp(0.0, 1.0)) + }) +} + +/// Textured disc (centre (100, 80), radius 45) on a noisy background. +fn disc(depth: u32) -> (Session, impl Fn(i32, i32) -> bool) { + let nz = noise_field(200, 160, 2); + let inside = |x: i32, y: i32| { + let (dx, dy) = (x as f32 + 0.5 - 100.0, y as f32 + 0.5 - 80.0); + dx * dx + dy * dy <= 45.0 * 45.0 + }; + let s = session_with(200, 160, depth, move |x, y| { + let n = 0.05 * nz[(y * 200 + x) as usize]; + if inside(x as i32, y as i32) { + let t = ((x + y) as f32 * 0.35).sin() * 0.5 + 0.5; + [0.85 + 0.05 * t + n, 0.2 + 0.3 * t + n, 0.15 + n] + } else { + [0.25 + n, 0.45 + n, 0.7 + n] + } + .map(|v| v.clamp(0.0, 1.0)) + }); + (s, inside) +} + +fn cov(s: &Session, x: i32, y: i32) -> f32 { + s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0)) +} + +fn sel_iou(s: &Session, w: i32, h: i32, truth: impl Fn(i32, i32) -> bool) -> f32 { + let (mut i, mut u) = (0, 0); + for y in 0..h { + for x in 0..w { + let (a, b) = (cov(s, x, y) >= 0.5, truth(x, y)); + i += (a && b) as i32; + u += (a || b) as i32; + } + } + i as f32 / u.max(1) as f32 +} + +#[test] +fn quick_selection_add_subtract_undo() { + for depth in [8, 16] { + let mut s = two_regions(depth); + let r = s.execute("select.quick", json!({"points": [[20, 50], [35, 50]], "size": 8})).unwrap(); + assert_eq!(r["selected"], true); + for y in (0..100).step_by(7) { + for x in (0..140).step_by(3) { + let c = cov(&s, x, y); + if x < 57 { + assert!(c >= 0.5, "depth {depth}: ({x},{y}) not selected"); + } else if x > 62 { + assert!(c < 0.5, "depth {depth}: leaked to ({x},{y})"); + } + } + } + // A second stroke on the right adds it. + s.execute("select.quick", json!({"points": [[100, 50]], "size": 8})).unwrap(); + assert!(cov(&s, 130, 90) >= 0.5 && cov(&s, 10, 10) >= 0.5); + // Subtract the left region again. + s.execute("select.quick", json!({"points": [[20, 50]], "size": 8, "mode": "subtract"})).unwrap(); + assert!(cov(&s, 10, 10) < 0.5 && cov(&s, 130, 90) >= 0.5); + s.execute("edit.undo", json!({})).unwrap(); + assert!(cov(&s, 10, 10) >= 0.5); + assert!(s.execute("select.quick", json!({"points": []})).is_err()); + } +} + +#[test] +fn quick_selection_subtract_from_select_all_and_enhance() { + let mut s = two_regions(8); + s.execute("select.all", json!({})).unwrap(); + s.execute("select.quick", json!({"points": [[100, 30], [110, 70]], "size": 10, "mode": "subtract"})).unwrap(); + assert!(cov(&s, 10, 50) >= 0.99); + assert!(cov(&s, 120, 20) < 0.01 && cov(&s, 70, 90) < 0.01); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("select.quick", json!({"points": [[20, 50]], "size": 8, "enhanceEdge": true})).unwrap(); + assert!(cov(&s, 10, 10) >= 0.5 && cov(&s, 100, 50) < 0.5); +} + +#[test] +fn empty_result_keeps_the_selection_in_every_mode() { + // Finding nothing must never wipe the selection, whatever the mode: Select Subject + // and Object Selection run heuristics that often miss on busy photos, and a missed + // Quick Selection dab must not destroy the work either. + for m in ["add", "subtract", "replace"] { + let mut s = two_regions(8); + s.execute("select.all", json!({})).unwrap(); + let r = s.execute("select.quick", json!({"points": [[-5000, -5000]], "size": 8, "mode": m})).unwrap(); + assert_eq!(r["changed"], false, "mode {m}"); + assert_eq!(r["selected"], true, "mode {m}"); + assert!(cov(&s, 10, 50) >= 0.99, "mode {m}: Select All survived an empty result"); + } + // Select Subject on a flat field finds nothing and keeps the selection too. + let mut s = session_with(140, 100, 8, |_, _| [0.5, 0.5, 0.5]); + s.execute("select.all", json!({})).unwrap(); + let r = s.execute("select.subject", json!({})).unwrap(); + assert_eq!(r["changed"], false); + assert!(cov(&s, 10, 10) >= 0.99); +} + +#[test] +fn object_selection_point_selects_the_object_under_it() { + for depth in [8, 16, 32] { + let (mut s, inside) = disc(depth); + let r = s.execute("select.object", json!({"point": [100, 80]})).unwrap(); + assert_eq!(r["changed"], true, "depth {depth}"); + let v = sel_iou(&s, 200, 160, &inside); + assert!(v > 0.9, "depth {depth}: IoU {v}"); + } + // The background is no object: nothing changes. + let (mut s, _) = disc(8); + let r = s.execute("select.object", json!({"point": [3, 3]})).unwrap(); + assert_eq!(r["changed"], false); + assert!(s.active().unwrap().doc.selection.is_none()); + assert!(s.execute("select.object", json!({"point": ["a", 1]})).is_err()); +} + +#[test] +fn object_selection_finds_a_large_foreground_at_each_depth_and_undoes() { + for depth in [8, 16, 32] { + let inside = |x: i32, y: i32| (10..190).contains(&x) && (8..152).contains(&y); + let mut s = session_with(200, 160, depth, |x, y| if inside(x as i32, y as i32) { [0.8, 0.2, 0.1] } else { [0.1, 0.2, 0.8] }); + let r = s.execute("select.object", json!({"point": [100, 80]})).unwrap(); + assert_eq!(r["changed"], true, "depth {depth}"); + assert!(sel_iou(&s, 200, 160, inside) > 0.95, "depth {depth}"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_none()); + let r = s.execute("select.object", json!({"point": [1, 1]})).unwrap(); + assert_eq!(r["changed"], false, "background at depth {depth}"); + assert!(s.active().unwrap().doc.selection.is_none()); + } +} + +#[test] +fn object_selection_point_honours_the_modes() { + let (mut s, _) = disc(8); + s.execute("select.all", json!({})).unwrap(); + s.execute("select.object", json!({"point": [100, 80], "mode": "subtract"})).unwrap(); + assert!(cov(&s, 100, 80) < 0.5 && cov(&s, 3, 3) >= 0.5); + s.execute("select.object", json!({"point": [100, 80], "mode": "add"})).unwrap(); + assert!(cov(&s, 100, 80) >= 0.5 && cov(&s, 3, 3) >= 0.5); + s.execute("select.object", json!({"point": [100, 80], "mode": "intersect"})).unwrap(); + assert!(cov(&s, 100, 80) >= 0.5 && cov(&s, 3, 3) < 0.5); +} + +#[test] +fn object_finder_cache_serves_the_whole_object_until_pixels_change() { + let (mut s, _) = disc(8); + let d = s.active().unwrap(); + let doc = std::sync::Arc::clone(&d.doc); + let target = sampled_target(&doc, d.active_layer, false); + assert!(s.object_finder.lookup(&doc, target, 100.0, 80.0).is_none()); + let r = std::sync::Arc::new(find_object(&doc, d.active_layer, false, 100.0, 80.0).unwrap()); + s.object_finder.insert(&doc, target, std::sync::Arc::clone(&r)); + // Any point on the object hits; the background and another target miss. + assert!(std::sync::Arc::ptr_eq(&s.object_finder.lookup(&doc, target, 120.0, 90.0).unwrap(), &r)); + assert!(s.object_finder.lookup(&doc, target, 3.0, 3.0).is_none()); + assert!(s.object_finder.lookup(&doc, Some(LayerId(u64::MAX)), 100.0, 80.0).is_none()); + // The click reuses it, and a selection-only edit keeps it. + s.execute("select.object", json!({"point": [110, 70]})).unwrap(); + assert_eq!(s.object_finder.len(), 1); + s.execute("select.deselect", json!({})).unwrap(); + let d = s.active().unwrap(); + assert!(s.object_finder.lookup(&std::sync::Arc::clone(&d.doc), target, 100.0, 80.0).is_some()); + // A pixel edit drops it. + s.execute("paint.pencil", json!({"points": [[5, 5], [30, 5]], "size": 4, "color": "#000000"})).unwrap(); + assert!(s.object_finder.is_empty()); +} + +#[test] +fn object_selection_disc() { + for depth in [8, 16, 32] { + let (mut s, inside) = disc(depth); + s.execute("select.object", json!({"rect": [40, 20, 120, 120]})).unwrap(); + let v = sel_iou(&s, 200, 160, &inside); + assert!(v > 0.95, "depth {depth}: IoU {v}"); + } + let (mut s, _) = disc(8); + assert!(s.execute("select.object", json!({"rect": [1, 2]})).is_err()); + // Negative width/height (drag up-left) work too. + s.execute("select.object", json!({"rect": [160, 140, -120, -120]})).unwrap(); + assert!(cov(&s, 100, 80) >= 0.5); +} + +#[test] +fn object_selection_on_an_empty_active_layer_says_so() { + // #5246: an empty layer above the photo used to find nothing without a word. + let (mut s, inside) = disc(8); + s.execute("layer.new.layer", json!({})).unwrap(); + for p in [json!({"rect": [40, 20, 120, 120]}), json!({"point": [100, 80]})] { + let e = s.execute("select.object", p.clone()).unwrap_err().to_string(); + assert!(e.contains("active layer is empty") && e.contains("sampleAllLayers"), "{p}: {e}"); + assert!(s.active().unwrap().doc.selection.is_none()); + } + // Sampling all layers finds the disc below. + s.execute("select.object", json!({"rect": [40, 20, 120, 120], "sampleAllLayers": true})).unwrap(); + assert!(sel_iou(&s, 200, 160, &inside) > 0.95); + // A layer with pixels elsewhere: the rectangle holds none of them. + s.execute("select.deselect", json!({})).unwrap(); + s.execute("paint.pencil", json!({"points": [[5, 5], [10, 5]], "size": 2, "color": "#000000"})).unwrap(); + let e = s.execute("select.object", json!({"rect": [60, 60, 100, 80]})).unwrap_err().to_string(); + assert!(e.contains("no pixels in that area"), "{e}"); +} + +#[test] +fn select_subject_centred_object() { + let (mut s, inside) = disc(8); + assert!(s.is_enabled("select.subject")); + s.execute("select.subject", json!({})).unwrap(); + let v = sel_iou(&s, 200, 160, inside); + assert!(v > 0.9, "IoU {v}"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_none()); +} + +/// #2865: a repeat on unchanged pixels reuses the last mask (an identical selection, even +/// after Deselect); sampling something else or a pixel edit computes it again. +#[test] +fn select_subject_repeat_reuses_the_mask_until_pixels_change() { + let (mut s, _) = disc(8); + let sel = |s: &Session| { + let mut v = Vec::new(); + s.active().unwrap().doc.selection.as_ref().unwrap().read_region_into(Rect::new(0, 0, 200, 160), &mut v); + v + }; + let cached = |s: &Session| s.subject_cache.region.clone().unwrap(); + s.execute("select.subject", json!({})).unwrap(); + let (first, mask) = (sel(&s), cached(&s)); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("select.subject", json!({})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&mask, &cached(&s)), "the repeat recomputed the mask"); + assert_eq!(sel(&s), first); + // Another sampled target (the layer rather than the composite) is a miss. + s.execute("select.subject", json!({"sampleAllLayers": false})).unwrap(); + assert!(!std::sync::Arc::ptr_eq(&mask, &cached(&s))); + // A pixel edit drops the entry; the next run recomputes it. + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + let n = bg.channels(); + bg.write_region(Rect::new(0, 0, 1, 1), &vec![1.0; n]); + Ok(()) + }) + .unwrap(); + assert!(s.subject_cache.region.is_none()); + s.execute("select.subject", json!({})).unwrap(); + assert_eq!(sel(&s), first); +} + +/// A vertical Gaussian-blurred edge at x = 40 (warm left, cool right) with the left half selected. +fn blurred_edge_selected() -> Session { + blurred_edge_selected_at(8) +} + +fn blurred_edge_selected_at(depth: u32) -> Session { + let mut s = session_with(80, 40, depth, |x, _| { + let t = 1.0 / (1.0 + ((x as f32 + 0.5 - 40.0) / 1.8).exp()); + [0.9 * t + 0.1 * (1.0 - t), 0.8 * t + 0.2 * (1.0 - t), 0.2 * t + 0.6 * (1.0 - t)] + }); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap(); + s +} + +fn soft_count(s: &photocraft_raster::Surface, y: i32) -> usize { + (0..80) + .filter(|x| { + let v = s.sample_channel(*x, y, 0); + v > 0.05 && v < 0.95 + }) + .count() +} + +#[test] +fn refine_edge_outputs_and_undo() { + // Selection output: the hard edge becomes a soft matte following the blur. + let mut s = blurred_edge_selected(); + assert!(s.is_enabled("select.refineEdge")); + s.execute("select.refineEdge", json!({"radius": 8})).unwrap(); + let sel = s.active().unwrap().doc.selection.clone().unwrap(); + assert!(soft_count(&sel, 20) >= 4, "selection edge not soft"); + assert!(sel.sample_channel(5, 20, 0) > 0.99 && sel.sample_channel(75, 20, 0) < 0.01); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(soft_count(s.active().unwrap().doc.selection.as_ref().unwrap(), 20), 0); + + // Layer mask output. + let layers_before = s.active().unwrap().doc.layer_count(); + let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "layerMask"})).unwrap(); + let d = s.active().unwrap(); + let l = d.doc.layer(photocraft_doc::LayerId(r["layer"].as_u64().unwrap())).unwrap(); + let m = l.mask.as_ref().unwrap(); + assert!(soft_count(&m.surface, 20) >= 4); + assert!(m.value(5, 20) > 0.99 && m.value(75, 20) < 0.01); + assert!(d.doc.selection.is_none()); + assert_eq!(d.doc.layer_count(), layers_before); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.active().unwrap().doc.layers[0].mask.is_none()); + assert!(s.active().unwrap().doc.selection.is_some()); + + // Existing mask settings (density, feather, linked) are preserved + s.edit("set mask", |doc, _| { + doc.layers[0].mask = Some(photocraft_doc::LayerMask { + surface: photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8), + density: 0.75, + feather: 3.5, + linked: false, + enabled: true, + }); + Ok(()) + }) + .unwrap(); + let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "layerMask"})).unwrap(); + let l = s.active().unwrap().doc.layer(photocraft_doc::LayerId(r["layer"].as_u64().unwrap())).unwrap(); + let m = l.mask.as_ref().unwrap(); + assert_eq!(m.density, 0.75); + assert_eq!(m.feather, 3.5); + assert!(!m.linked); + s.execute("edit.undo", json!({})).unwrap(); + s.edit("clear mask", |doc, _| { + doc.layers[0].mask = None; + Ok(()) + }) + .unwrap(); + + // New layer: pixels with the refined alpha; the source is hidden. + let r = s.execute("select.refineEdge", json!({"radius": 8, "feather": 1, "output": "newLayer"})).unwrap(); + let d = s.active().unwrap(); + let nid = photocraft_doc::LayerId(r["layer"].as_u64().unwrap()); + assert_eq!(d.active_layer, Some(nid)); + assert_eq!(d.doc.layer_count(), layers_before + 1); + let nl = d.doc.layer(nid).unwrap(); + let surf = nl.surface().unwrap(); + assert!(surf.format().alpha); + let a = |x: i32| surf.pixel(x, 20)[3]; + assert!(a(5) > 0.99 && a(75) == 0.0 && a(40) > 0.05 && a(40) < 0.95); + assert!(!d.doc.layers[0].visible); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.layer_count(), layers_before); + assert!(s.active().unwrap().doc.layers[0].visible); + + // New layer with mask + decontamination (selection output upgrades to it). + let r = s.execute("select.refineEdge", json!({"radius": 8, "decontaminate": true, "amount": 100})).unwrap(); + assert_eq!(r["output"], "newLayerWithMask"); + let d = s.active().unwrap(); + let nl = d.doc.layer(photocraft_doc::LayerId(r["layer"].as_u64().unwrap())).unwrap(); + assert!(nl.mask.is_some()); + let px = nl.surface().unwrap().pixel(41, 20); + let orig = d.doc.layers[0].surface().unwrap().pixel(41, 20); + // The fringe colour moved towards the warm foreground (more red, less blue). + assert!(px[0] > orig[0] + 0.05 && px[2] < orig[2] - 0.05, "{px:?} vs {orig:?}"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.execute("select.refineEdge", json!({"output": "bogus"})).is_err()); + s.execute("select.deselect", json!({})).unwrap(); + assert!(!s.is_enabled("select.refineEdge")); +} + +/// Output To New Document (with or without a layer mask) opens a document like the source, +/// at every depth, and leaves the source document as it was. +#[test] +fn refine_edge_outputs_to_a_new_document() { + for depth in [8, 16, 32] { + let mut s = blurred_edge_selected_at(depth); + s.edit("profile", |doc, _| { + doc.resolution_dpi = 300.0; + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "newDocument"})).unwrap(); + assert_eq!((r["output"].as_str(), r["document"].as_u64()), (Some("newDocument"), Some(1)), "depth {depth}"); + assert_eq!(s.active_index(), Some(1)); + let nd = &s.active().unwrap().doc; + assert_eq!((nd.size, nd.mode, nd.depth, nd.resolution_dpi), (before.size, before.mode, before.depth, 300.0)); + assert_eq!(nd.layers.len(), 1); + assert!(nd.selection.is_none() && nd.layers[0].mask.is_none()); + let surf = nd.layers[0].surface().unwrap(); + let a = |x: i32| surf.pixel(x, 20)[3]; + assert!(a(5) > 0.99 && a(75) == 0.0 && a(40) > 0.05 && a(40) < 0.95, "depth {depth}: {} {} {}", a(5), a(40), a(75)); + // The source is untouched: same layers, still visible, selection kept, no history step. + let src = &s.documents()[0]; + assert_eq!(src.doc.layers, before.layers); + assert_eq!(src.doc.selection, before.selection); + assert_eq!(src.history.undo_label(), Some("profile")); + + // With a layer mask: full pixels, the refined matte as the mask. + s.execute("file.close", json!({"document": 1})).unwrap(); + let r = s.execute("select.refineEdge", json!({"radius": 8, "output": "newDocumentWithMask"})).unwrap(); + assert_eq!(r["output"], "newDocumentWithMask"); + let nd = &s.active().unwrap().doc; + let l = &nd.layers[0]; + assert_eq!(l.surface().unwrap().pixel(75, 20), before.layers[0].surface().unwrap().pixel(75, 20), "depth {depth}"); + let m = l.mask.as_ref().unwrap(); + assert!(soft_count(&m.surface, 20) >= 4, "depth {depth}"); + assert!(m.value(5, 20) > 0.99 && m.value(75, 20) < 0.01, "depth {depth}"); + } +} + +#[test] +fn refine_edge_shift_and_contrast() { + let mut s = blurred_edge_selected(); + s.execute("select.refineEdge", json!({"shiftEdge": 100})).unwrap(); + assert!(cov(&s, 42, 20) > 0.99); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("select.refineEdge", json!({"feather": 8, "contrast": 100})).unwrap(); + assert!(cov(&s, 38, 20) == 1.0 && cov(&s, 42, 20) == 0.0); +} + +/// The Refine Edge Brush adds strands beyond the radius band, at every depth, and rejects +/// malformed strokes. +#[test] +fn refine_edge_brush_strokes() { + for depth in [8, 16, 32] { + // Warm subject (x < 40) with warm strands every 4th column from x = 60, on blue. + let strand = |x: u32| x < 40 || ((60..84).contains(&x) && x.is_multiple_of(4)); + let mut s = session_with(120, 40, depth, |x, _| if strand(x) { [0.9, 0.7, 0.2] } else { [0.1, 0.3, 0.8] }); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap(); + let stroke = json!([{"points": [[70, 5], [70, 35]], "size": 30}]); + s.execute("select.refineEdge", json!({"radius": 4, "refineStrokes": stroke})).unwrap(); + assert!(cov(&s, 64, 20) > 0.9 && cov(&s, 72, 20) > 0.9, "depth {depth}: strands {}", cov(&s, 64, 20)); + assert!(cov(&s, 66, 20) < 0.1 && cov(&s, 100, 20) < 0.01, "depth {depth}: background"); + s.execute("edit.undo", json!({})).unwrap(); + // Subtract over the same place paints the refinement out again. + let both = json!([{"points": [[70, 5], [70, 35]], "size": 30}, {"points": [[70, 5], [70, 35]], "size": 40, "mode": "subtract"}]); + s.execute("select.refineEdge", json!({"radius": 4, "refineStrokes": both})).unwrap(); + assert!(cov(&s, 64, 20) < 0.01, "depth {depth}"); + s.execute("edit.undo", json!({})).unwrap(); + for bad in [ + json!(7), + json!([5]), + json!([{"points": []}]), + json!([{"points": [[1, "x"]]}]), + json!([{"points": [[1, 2, 3]]}]), + json!([{"points": [[1, 2]], "size": 0}]), + json!([{"points": [[1, 2]], "size": 1e9}]), + json!([{"points": [[1, 2]], "mode": "xor"}]), + json!([{"points": [[0, 0], [1e6, 1e6], [0, 0], [1e6, 1e6]], "size": 5000}]), + ] { + assert!(s.execute("select.refineEdge", json!({"refineStrokes": bad})).is_err(), "{bad}"); + } + } +} + +#[test] +fn refine_edge_works_on_layer_mask_without_selection() { + let mut s = blurred_edge_selected(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_none()); + assert!(s.active().unwrap().doc.layers[0].mask.is_some()); + assert!(s.is_enabled("select.refineEdge")); + + let r = s.execute("select.refineEdge", json!({"radius": 8})).unwrap(); + assert_eq!(r["output"], "layerMask"); + let d = s.active().unwrap(); + let m = d.doc.layers[0].mask.as_ref().unwrap(); + assert!(soft_count(&m.surface, 20) >= 4); +} + +#[test] +fn focus_area_command() { + let nz = noise_field(160, 100, 3); + let mut blurred = vec![0.0f32; nz.len()]; + for y in 0..100i32 { + for x in 0..160i32 { + let mut a = 0.0; + for dy in -4..=4 { + for dx in -4..=4 { + a += nz[((y + dy).clamp(0, 99) * 160 + (x + dx).clamp(0, 159)) as usize]; + } + } + blurred[(y * 160 + x) as usize] = a / 81.0; + } + } + let mut s = session_with(160, 100, 8, move |x, y| { + let i = (y * 160 + x) as usize; + let v = 0.5 + 0.15 * if x < 80 { nz[i] } else { blurred[i] * 3.0 }; + [v, v, v].map(|c| c.clamp(0.0, 1.0)) + }); + s.execute("select.focusArea", json!({})).unwrap(); + assert!(cov(&s, 30, 50) >= 0.5 && cov(&s, 130, 50) < 0.5); +} +/// The selection as 8-bit coverage over `w × h`, to compare two selections exactly. +fn sel_bytes(s: &Session, w: i32, h: i32) -> Vec { + (0..h).flat_map(|y| (0..w).map(move |x| (cov(s, x, y) * 255.0).round() as u8)).collect() +} + +/// The #8783 review: a refine whose result would be dense over more than +/// [`matting::MAX_REFINE_AREA`] pixels is refused, not allocated: a thin Brush edit across a +/// huge canvas (its edited selection spans the canvas) and a selection of the whole canvas. +/// The selection stays as it was. +#[test] +fn refine_edge_refuses_a_selection_too_large_to_refine() { + let mut s = Session::new(); + s.add_document( + Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8), + None, + ); + s.execute("select.rect", json!({"x": 10, "y": 60, "width": 10, "height": 10})).unwrap(); + let small = s.active().and_then(|d| d.doc.selection.clone()).expect("selected"); + let diagonal = json!({"edits": [{"tool": "brush", "points": [[0, 0], [99_999, 99_999]], "size": 1}]}); + let t = std::time::Instant::now(); + let e = s.execute("select.refineEdge", diagonal).expect_err("too large to refine"); + assert!(e.to_string().contains("too large to refine"), "{e}"); + assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&small), "the selection is unchanged"); + // The small selection itself still refines. + s.execute("select.refineEdge", json!({"radius": 4})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + let all = s.active().and_then(|d| d.doc.selection.clone()).expect("selected"); + assert!(s.execute("select.refineEdge", json!({"radius": 4})).is_err()); + assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&all)); + assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed()); +} + +/// The #8783 review: Brush and Lasso edits and Refine Edge Brush strokes that would paint +/// too many tiles of a huge canvas are refused before anything is painted, and the selection +/// stays as it was. +#[test] +fn refine_edge_refuses_edits_that_cross_too_many_tiles() { + let mut s = Session::new(); + s.add_document( + Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8), + None, + ); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + let before = s.active().and_then(|d| d.doc.selection.clone()).expect("selected"); + let zigzag: Vec<[f32; 2]> = (0..20).map(|i| [if i % 2 == 0 { 0.0 } else { 99_999.0 }, i as f32 * 5000.0]).collect(); + for p in [ + json!({"edits": [{"tool": "brush", "points": zigzag, "size": 1}]}), + json!({"edits": [{"tool": "lasso", "points": zigzag}]}), + json!({"refineStrokes": [{"points": zigzag, "size": 1}]}), + ] { + let e = s.execute("select.refineEdge", p.clone()).expect_err("refused"); + assert!(e.to_string().contains("too many tiles"), "{p}: {e}"); + assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&before), "{p}: the selection is unchanged"); + } +} + +/// Select and Mask's own tools (#7069, #8148): each edit changes the selection before the +/// edge is refined, at every depth, and the whole run is one history step. +#[test] +fn refine_edge_edits_apply_each_tool_at_every_depth() { + for depth in [8, 16, 32] { + let mut s = two_regions(depth); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + let start = sel_bytes(&s, 140, 100); + let run = |s: &mut Session, edits: Value| { + s.execute("select.refineEdge", json!({"edits": edits})).unwrap(); + let after = sel_bytes(s, 140, 100); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(sel_bytes(s, 140, 100), start, "depth {depth}: one undo restores the selection"); + after + }; + let at = |b: &[u8], x: usize, y: usize| b[y * 140 + x]; + // Quick Selection grows across the cool region; subtracting it again leaves the start. + let quick = run(&mut s, json!([{"tool": "quick", "points": [[100, 50], [110, 50]], "size": 8}])); + assert!(at(&quick, 120, 80) >= 128 && at(&quick, 5, 5) >= 128 && at(&quick, 40, 60) < 128, "depth {depth}: quick"); + let back = run( + &mut s, + json!([{"tool": "quick", "points": [[100, 50]], "size": 8}, {"tool": "quick", "points": [[100, 50]], "size": 8, "mode": "subtract"}]), + ); + assert!(at(&back, 120, 80) < 128 && at(&back, 5, 5) >= 128, "depth {depth}: quick subtract"); + // The Brush paints exactly where it goes. + let brush = run(&mut s, json!([{"tool": "brush", "points": [[30, 80], [60, 80]], "size": 10}])); + assert!(at(&brush, 45, 80) == 255 && at(&brush, 45, 90) == 0, "depth {depth}: brush"); + let erased = run(&mut s, json!([{"tool": "brush", "points": [[10, 10]], "size": 6, "mode": "subtract"}])); + assert!(at(&erased, 10, 10) == 0 && at(&erased, 2, 2) == 255, "depth {depth}: brush subtract"); + // Lasso adds and subtracts polygons. + let lasso = run(&mut s, json!([{"tool": "lasso", "points": [[50, 50], [90, 50], [90, 90], [50, 90]]}])); + assert!(at(&lasso, 70, 70) == 255 && at(&lasso, 95, 70) == 0 && at(&lasso, 5, 5) == 255, "depth {depth}: lasso"); + let cut = run(&mut s, json!([{"tool": "lasso", "points": [[0, 0], [10, 0], [10, 10], [0, 10]], "mode": "subtract"}])); + assert!(at(&cut, 5, 5) == 0 && at(&cut, 15, 15) == 255, "depth {depth}: lasso subtract"); + // Clear Selection, then Invert of nothing: everything. + let all = run(&mut s, json!([{"tool": "clear"}, {"tool": "invert"}])); + assert!(all.iter().all(|v| *v == 255), "depth {depth}: clear + invert"); + let inverted = run(&mut s, json!([{"tool": "invert"}])); + assert!(at(&inverted, 5, 5) == 0 && at(&inverted, 100, 50) == 255, "depth {depth}: invert"); + } +} + +/// Object Selection and Select Subject inside the workspace find what the standalone tools find. +#[test] +fn refine_edge_edits_object_and_subject() { + for depth in [8, 16, 32] { + let (mut s, inside) = disc(depth); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s.execute("select.refineEdge", json!({"edits": [{"tool": "object", "rect": [40, 20, 120, 120]}, {"tool": "lasso", "points": [[0, 0], [10, 0], [10, 10], [0, 10]], "mode": "subtract"}]})).unwrap(); + let v = sel_iou(&s, 200, 160, &inside); + assert!(v > 0.95, "depth {depth}: object rect IoU {v}"); + s.execute("select.refineEdge", json!({"edits": [{"tool": "clear"}, {"tool": "object", "point": [3, 3]}, {"tool": "object", "point": [100, 80]}]})) + .unwrap(); + let v = sel_iou(&s, 200, 160, &inside); + assert!(v > 0.9, "depth {depth}: object point IoU {v} (the background point finds nothing)"); + } + let (mut s, inside) = disc(8); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s.execute("select.refineEdge", json!({"edits": [{"tool": "subject"}]})).unwrap(); + let v = sel_iou(&s, 200, 160, &inside); + assert!(v > 0.9, "subject replaces the selection: IoU {v}"); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s.execute("select.refineEdge", json!({"edits": [{"tool": "subject", "mode": "add"}]})).unwrap(); + assert!(cov(&s, 5, 5) >= 0.5 && cov(&s, 100, 80) >= 0.5, "subject added to the selection"); +} + +/// An edit gives what the standalone tool gives, then the edge is refined as usual, and the +/// result reaches every output. +#[test] +fn refine_edge_edits_match_the_tools_and_reach_the_outputs() { + let mut tool = two_regions(8); + tool.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + tool.execute("select.quick", json!({"points": [[100, 50], [110, 50]], "size": 8})).unwrap(); + let mut ws = two_regions(8); + ws.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + ws.execute("select.refineEdge", json!({"edits": [{"tool": "quick", "points": [[100, 50], [110, 50]], "size": 8}]})).unwrap(); + assert_eq!(sel_bytes(&ws, 140, 100), sel_bytes(&tool, 140, 100)); + // Refinement runs on the edited selection: Shift Edge contracts the brushed bar too. + let mut s = two_regions(8); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + s.execute("select.refineEdge", json!({"shiftEdge": -100, "edits": [{"tool": "brush", "points": [[30, 80], [100, 80]], "size": 20}]})).unwrap(); + assert!(cov(&s, 60, 80) >= 0.5 && cov(&s, 60, 88) < 0.5 && cov(&s, 60, 72) < 0.5, "the 20 px bar shrank"); + // Layer mask and new-layer outputs take the edited selection. + let mut s = blurred_edge_selected(); + let r = s.execute("select.refineEdge", json!({"output": "layerMask", "edits": [{"tool": "invert"}]})).unwrap(); + assert_eq!(r["output"], "layerMask"); + let m = s.active().unwrap().doc.layers[0].mask.as_ref().unwrap(); + assert!(m.surface.sample_channel(10, 20, 0) < 0.01 && m.surface.sample_channel(70, 20, 0) > 0.99); + let mut s = blurred_edge_selected(); + let r = s.execute("select.refineEdge", json!({"output": "newLayerWithMask", "edits": [{"tool": "invert"}]})).unwrap(); + assert_eq!(r["output"], "newLayerWithMask"); + let d = s.active().unwrap(); + let m = d.doc.layers.iter().find_map(|l| l.mask.as_ref()).unwrap(); + assert!(m.surface.sample_channel(10, 20, 0) < 0.01 && m.surface.sample_channel(70, 20, 0) > 0.99); + // Clearing everything deselects. + let mut s = blurred_edge_selected(); + let r = s.execute("select.refineEdge", json!({"edits": [{"tool": "clear"}]})).unwrap(); + assert_eq!(r["selected"], false); + assert!(s.active().unwrap().doc.selection.is_none()); +} + +/// Bad edits are refused before anything changes. +#[test] +fn refine_edge_rejects_bad_edits_and_keeps_the_selection() { + let mut s = blurred_edge_selected(); + let before = sel_bytes(&s, 80, 40); + for bad in + [json!(7), json!([{"tool": "nope"}]), json!([{"tool": "lasso", "points": [[0, 0]]}]), json!([{"tool": "brush", "points": [[0, 0]], "size": -1}])] + { + assert!(s.execute("select.refineEdge", json!({"edits": bad})).is_err(), "{bad}"); + assert_eq!(sel_bytes(&s, 80, 40), before, "{bad}"); + } +} From fb63ad5f7d160ad90d68befbab2663a2ef17a49a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:22 +0000 Subject: [PATCH 043/259] refactor(engine): move photo_cmds.rs tests to photo_cmds/tests.rs --- crates/engine/src/photo_cmds.rs | 358 +------------------------- crates/engine/src/photo_cmds/tests.rs | 355 +++++++++++++++++++++++++ 2 files changed, 356 insertions(+), 357 deletions(-) create mode 100644 crates/engine/src/photo_cmds/tests.rs diff --git a/crates/engine/src/photo_cmds.rs b/crates/engine/src/photo_cmds.rs index a1201ecc71..2aa2a383b8 100644 --- a/crates/engine/src/photo_cmds.rs +++ b/crates/engine/src/photo_cmds.rs @@ -991,360 +991,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - /// A textured RGB scene (deterministic blobs on a gradient). - fn scene(w: usize, h: usize, seed: u64) -> Vec<[f32; 4]> { - let mut z = seed; - let mut rnd = || { - z = z.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - (z >> 33) as f64 / (1u64 << 31) as f64 - }; - let mut px: Vec<[f32; 4]> = (0..w * h) - .map(|i| { - let x = (i % w) as f32 / w as f32; - [0.3 + 0.2 * x, 0.35, 0.4 - 0.1 * x, 1.0] - }) - .collect(); - for _ in 0..(w * h / 700) { - let (cx, cy, r) = (rnd() * w as f64, rnd() * h as f64, 3.0 + rnd() * 9.0); - let col = [rnd() as f32, rnd() as f32, rnd() as f32, 1.0]; - for y in (cy - r).max(0.0) as usize..((cy + r) as usize + 1).min(h) { - for x in (cx - r).max(0.0) as usize..((cx + r) as usize + 1).min(w) { - if (x as f64 - cx).hypot(y as f64 - cy) < r { - px[y * w + x] = col; - } - } - } - } - px - } - - fn doc_from(name: &str, px: &[[f32; 4]], w: usize, h: usize, depth: SampleType) -> Document { - let mut d = Document::new(name, Size::new(w as u32, h as u32), ColorMode::Rgb, depth); - let fmt = d.pixel_format(); - let n = fmt.channels(); - let mut data = vec![0.0f32; w * h * n]; - for (q, o) in px.iter().zip(data.chunks_exact_mut(n)) { - photocraft_raster::from_rgba_into(&fmt, *q, o); - } - let mut s = Surface::new(fmt); - s.write_region(Rect::new(0, 0, w as i32, h as i32), &data); - d.layers.push(Layer::new("Background", LayerContent::Raster(s))); - d - } - - fn crop(px: &[[f32; 4]], sw: usize, x0: usize, y0: usize, w: usize, h: usize, gain: f32) -> Vec<[f32; 4]> { - (0..w * h) - .map(|i| { - let q = px[(y0 + i / w) * sw + x0 + i % w]; - [q[0] * gain, q[1] * gain, q[2] * gain, 1.0] - }) - .collect() - } - - #[test] - fn photomerge_open_documents_reposition_and_perspective() { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - let (sw, sh) = (520, 220); - let sc = scene(sw, sh, 5); - let mut s = Session::new(); - // Three overlapping crops, the middle one 15 % brighter (gain compensation). - for (k, (x0, g)) in [(0usize, 1.0f32), (130, 1.15), (260, 1.0)].into_iter().enumerate() { - s.add_document(doc_from(&format!("img{k}"), &crop(&sc, sw, x0, 10, 220, 200, g), 220, 200, depth), None); - } - let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "reposition"})).unwrap(); - assert_eq!(r["placed"].as_array().unwrap().len(), 3, "{r}"); - let (w, h) = (r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()); - assert!((w as i64 - 480).abs() <= 2 && (h as i64 - 200).abs() <= 2, "{depth:?} {w}×{h}"); - let d = &s.active().unwrap().doc; - assert_eq!(d.layers.len(), 3); - assert!(d.layers.iter().all(|l| l.mask.is_some())); - // Masks partition the panorama: every covered pixel is shown by exactly one layer. - for &(x, y) in &[(20, 100), (200, 50), (380, 150), (470, 120)] { - let shown: f32 = d.layers.iter().map(|l| l.mask.as_ref().unwrap().value(x, y) * l.surface().unwrap().rgba(x, y)[3]).sum(); - assert!((shown - 1.0).abs() < 0.01, "({x},{y}) {shown}"); - } - // The composite matches the scene up to the global gain. - let comp = photocraft_compose::flatten(d); - let at = |x: i32, y: i32| comp.px[(y * comp.rect.width() as i32 + x) as usize]; - let gains = r["photometric"]["gains"].as_array().unwrap(); - assert!(gains[1][0].as_f64().unwrap() > gains[0][0].as_f64().unwrap() * 1.05, "{r}"); - let probe = at(160, 100); - let truth = sc[110 * sw + 160]; - assert!((probe[1] - truth[1]).abs() < 0.08, "{probe:?} vs {truth:?}"); - } - // Perspective + no blending: plain layers, no masks. - let (sw, sh) = (520, 220); - let sc = scene(sw, sh, 8); - let mut s = Session::new(); - for (k, x0) in [0usize, 180].into_iter().enumerate() { - s.add_document(doc_from(&format!("p{k}"), &crop(&sc, sw, x0, 10, 260, 200, 1.0), 260, 200, SampleType::U8), None); - } - let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "perspective", "blend": false})).unwrap(); - assert_eq!(r["layout"], "perspective"); - let d = &s.active().unwrap().doc; - assert!(d.layers.iter().all(|l| l.mask.is_none())); - assert!((r["width"].as_i64().unwrap() - 440).abs() <= 8, "{r}"); - assert!(s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "zigzag"})).is_err()); - let mut empty = Session::new(); - assert!(empty.execute("file.automate.photomerge", json!({})).is_err()); - } - - #[test] - fn photomerge_cylindrical_with_fill() { - let (sw, sh) = (900, 260); - let sc = scene(sw, sh, 21); - let f = 260.0f64; - let mut s = Session::new(); - let (tw, th) = (260usize, 200usize); - for (k, pan) in [-0.45f64, 0.0, 0.45].into_iter().enumerate() { - let px: Vec<[f32; 4]> = (0..tw * th) - .map(|i| { - let (dx, dy) = ((i % tw) as f64 - tw as f64 / 2.0, (i / tw) as f64 - th as f64 / 2.0); - let (u, v) = (sw as f64 / 2.0 + f * (dx.atan2(f) + pan), sh as f64 / 2.0 + f * dy / dx.hypot(f)); - sc[(v.round().clamp(0.0, sh as f64 - 1.0) as usize) * sw + u.round().clamp(0.0, sw as f64 - 1.0) as usize] - }) - .collect(); - s.add_document(doc_from(&format!("c{k}"), &px, tw, th, SampleType::U8), None); - } - let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "cylindrical", "contentAwareFill": true})).unwrap(); - assert_eq!(r["layout"], "cylindrical"); - assert_eq!(r["placed"].as_array().unwrap().len(), 3, "{r}"); - let d = &s.active().unwrap().doc; - let top = d.layers.last().unwrap(); - assert_eq!(top.name, "Content-Aware Fill"); - // The fill layer is opaque everywhere (the bow-tie corners are filled). - let b = d.bounds(); - assert!(top.surface().unwrap().rgba(1, 1)[3] > 0.99 && top.surface().unwrap().rgba(b.x1 - 2, b.y1 - 2)[3] > 0.99); - } - - #[test] - fn hdr_merge_from_synthetic_exposures() { - let (w, h) = (96usize, 64usize); - let radiance: Vec<[f32; 3]> = (0..w * h) - .map(|i| { - let x = (i % w) as f32 / w as f32; - let b = 0.003 * 2f32.powf(x * 11.0) * (1.0 + 0.2 * ((i / w) as f32 * 0.3).sin()); - [b, b * 0.9, b * 0.7] - }) - .collect(); - let shoot = |dt: f32| -> Vec<[f32; 4]> { - radiance - .iter() - .map(|r| { - let f = |v: f32| photocraft_algo_srgb((v * dt).min(1.0)); - [f(r[0]), f(r[1]), f(r[2]), 1.0] - }) - .collect() - }; - let mut s = Session::new(); - for (k, dt) in [0.25f32, 1.0, 4.0].into_iter().enumerate() { - let mut d = doc_from(&format!("e{k}"), &shoot(dt), w, h, SampleType::U8); - d.metadata.exif = Some(std::sync::Arc::new(exif::build(&exif::CameraInfo { - exposure_time: Some(dt as f64 / 100.0), - f_number: Some(8.0), - iso: Some(100.0), - ..Default::default() - }))); - s.add_document(d, None); - } - let r = s.execute("file.automate.mergeToHdrPro", json!({"useOpenDocuments": true})).unwrap(); - assert_eq!(r["exposureSource"], "exif"); - let ev: Vec = r["ev"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); - assert!((ev[1] - 2.0).abs() < 1e-6 && (ev[2] - 4.0).abs() < 1e-6, "{ev:?}"); - let d = &s.active().unwrap().doc; - assert_eq!(d.depth, SampleType::F32); - assert!(d.is_background(d.layers[0].id), "the merged layer is a real (locked) Background"); - let l = d.layers[0].surface().unwrap(); - // Linear output: ratios across the ramp follow the radiance. - let (a, b) = (l.rgba(20, 30)[1] as f64, l.rgba(80, 30)[1] as f64); - let expect = radiance[30 * w + 80][1] as f64 / radiance[30 * w + 20][1] as f64; - assert!(((b / a) / expect).ln().abs() < 0.3, "{} vs {expect}", b / a); - assert!(r["stops"].as_f64().unwrap() > 7.0, "{r}"); - let out = r["document"].as_u64().unwrap() as usize; - s.close(out); - // 8-bit tone-mapped output with explicit EVs. - for method in ["localAdaptation", "exposureGamma", "highlightCompression", "equalizeHistogram"] { - let r = s - .execute("file.automate.mergeToHdrPro", json!({"paths": [], "useOpenDocuments": true, "exposures": [0, 2, 4], "mode": "8", "method": method})) - .unwrap(); - assert_eq!(r["exposureSource"], "params"); - let d = &s.active().unwrap().doc; - assert_eq!(d.depth, SampleType::U8); - let out = r["document"].as_u64().unwrap() as usize; - s.close(out); - } - assert!(s.execute("file.automate.mergeToHdrPro", json!({"useOpenDocuments": true, "exposures": [0, 1]})).is_err()); - } - - fn photocraft_algo_srgb(v: f32) -> f32 { - if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } - } - - /// A light scan with one dark tilted print on it. - fn scan_with_one_photo() -> Document { - let (w, h) = (300usize, 220usize); - let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; - let (s, co) = 5.0f64.to_radians().sin_cos(); - for y in 0..h { - for x in 0..w { - let (dx, dy) = (x as f64 + 0.5 - 150.0, y as f64 + 0.5 - 110.0); - let (u, v) = (co * dx + s * dy, -s * dx + co * dy); - if u.abs() < 80.0 && v.abs() < 55.0 { - px[y * w + x] = [0.2 + (u / 160.0) as f32 * 0.3, 0.25, 0.3, 1.0]; - } - } - } - doc_from("scan", &px, w, h, SampleType::U8) - } - - #[test] - fn crop_and_straighten_keeps_duotone_inks() { - let mut s = Session::new(); - s.add_document(scan_with_one_photo(), None); - s.execute("image.mode.grayscale", json!({})).unwrap(); - s.execute( - "image.mode.duotone", - json!({"type": "duotone", "inks": [{"name": "Black", "color": [0, 0, 0]}, {"name": "Orange", "color": [255, 128, 0]}]}), - ) - .unwrap(); - let src = s.documents()[0].doc.duotone.clone(); - assert!(src.is_some()); - let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); - assert_eq!(r["photos"].as_array().unwrap().len(), 1, "{r}"); - let d = &s.documents()[1].doc; - assert_eq!(d.mode, ColorMode::Duotone); - assert_eq!(d.duotone, src); - } - - #[test] - fn crop_and_straighten_disabled_for_indexed() { - // Photoshop greys the command out for Indexed Color documents. - let mut s = Session::new(); - s.add_document(scan_with_one_photo(), None); - s.execute("image.mode.indexedColor", json!({})).unwrap(); - assert_eq!(s.documents()[0].doc.mode, ColorMode::Indexed); - assert!(!s.is_enabled("file.automate.cropAndStraightenPhotos")); - assert!(s.execute("file.automate.cropAndStraightenPhotos", json!({})).is_err()); - assert_eq!(s.documents().len(), 1); - } - - #[test] - fn crop_and_straighten_only_processes_the_selection() { - // Photoshop: with a selection, only the photos inside it are split off. - let (w, h) = (480usize, 340usize); - let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; - // Upright photos: red 160x110 at (40, 60), blue 150x120 at (290, 180). - for (x0, y0, pw, ph, c) in [(40, 60, 160, 110, [0.6f32, 0.1, 0.1, 1.0]), (290, 180, 150, 120, [0.1, 0.2, 0.6, 1.0])] { - for y in y0..y0 + ph { - px[y * w + x0..y * w + x0 + pw].fill(c); - } - } - let mut s = Session::new(); - s.add_document(doc_from("scan", &px, w, h, SampleType::U8), None); - s.execute("select.rect", json!({"x": 270, "y": 160, "width": 190, "height": 160})).unwrap(); - let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); - let found = r["photos"].as_array().unwrap(); - assert_eq!(found.len(), 1, "{r}"); - assert_eq!(s.documents().len(), 2); - // The reported centre is in the scan's coordinates. - let c = &found[0]["center"]; - assert!((c[0].as_f64().unwrap() - 365.0).abs() < 3.0 && (c[1].as_f64().unwrap() - 240.0).abs() < 3.0, "{c}"); - let d = &s.documents()[1].doc; - assert!((d.size.width as i64 - 150).abs() <= 4 && (d.size.height as i64 - 120).abs() <= 4, "{:?}", d.size); - let q = d.layers[0].surface().unwrap().rgba(d.size.width as i32 / 2, d.size.height as i32 / 2); - assert!(q[2] > 0.5 && q[0] < 0.2, "{q:?}"); - // Without a selection both photos are found. - s.set_active(0); - s.execute("select.deselect", json!({})).unwrap(); - let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); - assert_eq!(r["photos"].as_array().unwrap().len(), 2, "{r}"); - } - - #[test] - fn crop_and_straighten_skips_photos_between_selected_regions() { - // Two selected rectangles: a photo in the gap between them lies inside - // their bounding box but outside the selection, so it is not split off. - let (w, h) = (480usize, 340usize); - let mut px = vec![[0.75f32, 0.75, 0.75, 1.0]; w * h]; - // Red 160x110 at (40, 60) and blue 150x120 at (290, 180) are selected; green 130x80 at (280, 50) is not. - for (x0, y0, pw, ph, c) in - [(40, 60, 160, 110, [0.6f32, 0.1, 0.1, 1.0]), (290, 180, 150, 120, [0.1, 0.2, 0.6, 1.0]), (280, 50, 130, 80, [0.1, 0.6, 0.1, 1.0])] - { - for y in y0..y0 + ph { - px[y * w + x0..y * w + x0 + pw].fill(c); - } - } - let mut s = Session::new(); - s.add_document(doc_from("scan", &px, w, h, SampleType::U8), None); - s.execute("select.rect", json!({"x": 20, "y": 40, "width": 200, "height": 150})).unwrap(); - s.execute("select.rect", json!({"x": 270, "y": 160, "width": 190, "height": 160, "mode": "add"})).unwrap(); - let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); - let found = r["photos"].as_array().unwrap(); - assert_eq!(found.len(), 2, "{r}"); - for f in found { - let c = &f["center"]; - let (cx, cy) = (c[0].as_f64().unwrap(), c[1].as_f64().unwrap()); - let near = |x: f64, y: f64| (cx - x).abs() < 3.0 && (cy - y).abs() < 3.0; - assert!(near(120.0, 115.0) || near(365.0, 240.0), "{c}"); - } - } - - #[test] - fn crop_and_straighten_refuses_a_selection_under_half_coverage() { - // A faint (strongly feathered) selection has no pixel at or above 50%: - // like Photoshop, nothing counts as selected, so no photo is split off - // from the unmasked bounding box. - let (w, h) = (480usize, 340usize); - let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; - for y in 180..300 { - px[y * w + 290..y * w + 440].fill([0.1, 0.2, 0.6, 1.0]); - } - let mut s = Session::new(); - s.add_document(doc_from("scan", &px, w, h, SampleType::U8), None); - let mut m = Surface::new(photocraft_color::PixelFormat::GRAY8); - m.fill_rect(Rect::new(270, 160, 460, 320), &[0.3]); - std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).selection = Some(m); - let e = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap_err(); - assert!(e.to_string().contains("50%"), "{e}"); - assert_eq!(s.documents().len(), 1); - } - - #[test] - fn crop_and_straighten_makes_documents() { - let (w, h) = (500usize, 360usize); - let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; - let photos = [([140.0f64, 120.0f64], 160.0f64, 110.0f64, 6.0f64), ([360.0, 240.0], 150.0, 120.0, -9.0)]; - for (c, pw, ph, ang) in photos { - let (s, co) = ang.to_radians().sin_cos(); - for y in 0..h { - for x in 0..w { - let (dx, dy) = (x as f64 + 0.5 - c[0], y as f64 + 0.5 - c[1]); - let (u, v) = (co * dx + s * dy, -s * dx + co * dy); - if u.abs() < pw / 2.0 && v.abs() < ph / 2.0 { - px[y * w + x] = [0.2 + (u / pw) as f32 * 0.3, 0.3, 0.6, 1.0]; - } - } - } - } - let mut s = Session::new(); - s.add_document(doc_from("scan", &px, w, h, SampleType::U16), None); - assert!(s.is_enabled("file.automate.cropAndStraightenPhotos")); - let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); - let found = r["photos"].as_array().unwrap(); - assert_eq!(found.len(), 2, "{r}"); - assert_eq!(s.documents().len(), 3); - assert!((found[0]["angle"].as_f64().unwrap() - 6.0).abs() < 1.0); - let d = &s.documents()[1].doc; - assert!((d.size.width as i64 - 158).abs() <= 4 && (d.size.height as i64 - 108).abs() <= 4, "{:?}", d.size); - assert_eq!(d.depth, SampleType::U16); - // Upright: the photo's horizontal gradient runs along x. - let l = d.layers[0].surface().unwrap(); - let (a, b) = (l.rgba(10, d.size.height as i32 / 2)[0], l.rgba(d.size.width as i32 - 10, d.size.height as i32 / 2)[0]); - assert!(b > a + 0.15, "{a} {b}"); - let (c, e) = (l.rgba(d.size.width as i32 / 2, 6)[0], l.rgba(d.size.width as i32 / 2, d.size.height as i32 - 6)[0]); - assert!((c - e).abs() < 0.05); - } -} +mod tests; diff --git a/crates/engine/src/photo_cmds/tests.rs b/crates/engine/src/photo_cmds/tests.rs new file mode 100644 index 0000000000..1fdf35f8b2 --- /dev/null +++ b/crates/engine/src/photo_cmds/tests.rs @@ -0,0 +1,355 @@ +use super::*; + +/// A textured RGB scene (deterministic blobs on a gradient). +fn scene(w: usize, h: usize, seed: u64) -> Vec<[f32; 4]> { + let mut z = seed; + let mut rnd = || { + z = z.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (z >> 33) as f64 / (1u64 << 31) as f64 + }; + let mut px: Vec<[f32; 4]> = (0..w * h) + .map(|i| { + let x = (i % w) as f32 / w as f32; + [0.3 + 0.2 * x, 0.35, 0.4 - 0.1 * x, 1.0] + }) + .collect(); + for _ in 0..(w * h / 700) { + let (cx, cy, r) = (rnd() * w as f64, rnd() * h as f64, 3.0 + rnd() * 9.0); + let col = [rnd() as f32, rnd() as f32, rnd() as f32, 1.0]; + for y in (cy - r).max(0.0) as usize..((cy + r) as usize + 1).min(h) { + for x in (cx - r).max(0.0) as usize..((cx + r) as usize + 1).min(w) { + if (x as f64 - cx).hypot(y as f64 - cy) < r { + px[y * w + x] = col; + } + } + } + } + px +} + +fn doc_from(name: &str, px: &[[f32; 4]], w: usize, h: usize, depth: SampleType) -> Document { + let mut d = Document::new(name, Size::new(w as u32, h as u32), ColorMode::Rgb, depth); + let fmt = d.pixel_format(); + let n = fmt.channels(); + let mut data = vec![0.0f32; w * h * n]; + for (q, o) in px.iter().zip(data.chunks_exact_mut(n)) { + photocraft_raster::from_rgba_into(&fmt, *q, o); + } + let mut s = Surface::new(fmt); + s.write_region(Rect::new(0, 0, w as i32, h as i32), &data); + d.layers.push(Layer::new("Background", LayerContent::Raster(s))); + d +} + +fn crop(px: &[[f32; 4]], sw: usize, x0: usize, y0: usize, w: usize, h: usize, gain: f32) -> Vec<[f32; 4]> { + (0..w * h) + .map(|i| { + let q = px[(y0 + i / w) * sw + x0 + i % w]; + [q[0] * gain, q[1] * gain, q[2] * gain, 1.0] + }) + .collect() +} + +#[test] +fn photomerge_open_documents_reposition_and_perspective() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let (sw, sh) = (520, 220); + let sc = scene(sw, sh, 5); + let mut s = Session::new(); + // Three overlapping crops, the middle one 15 % brighter (gain compensation). + for (k, (x0, g)) in [(0usize, 1.0f32), (130, 1.15), (260, 1.0)].into_iter().enumerate() { + s.add_document(doc_from(&format!("img{k}"), &crop(&sc, sw, x0, 10, 220, 200, g), 220, 200, depth), None); + } + let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "reposition"})).unwrap(); + assert_eq!(r["placed"].as_array().unwrap().len(), 3, "{r}"); + let (w, h) = (r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()); + assert!((w as i64 - 480).abs() <= 2 && (h as i64 - 200).abs() <= 2, "{depth:?} {w}×{h}"); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), 3); + assert!(d.layers.iter().all(|l| l.mask.is_some())); + // Masks partition the panorama: every covered pixel is shown by exactly one layer. + for &(x, y) in &[(20, 100), (200, 50), (380, 150), (470, 120)] { + let shown: f32 = d.layers.iter().map(|l| l.mask.as_ref().unwrap().value(x, y) * l.surface().unwrap().rgba(x, y)[3]).sum(); + assert!((shown - 1.0).abs() < 0.01, "({x},{y}) {shown}"); + } + // The composite matches the scene up to the global gain. + let comp = photocraft_compose::flatten(d); + let at = |x: i32, y: i32| comp.px[(y * comp.rect.width() as i32 + x) as usize]; + let gains = r["photometric"]["gains"].as_array().unwrap(); + assert!(gains[1][0].as_f64().unwrap() > gains[0][0].as_f64().unwrap() * 1.05, "{r}"); + let probe = at(160, 100); + let truth = sc[110 * sw + 160]; + assert!((probe[1] - truth[1]).abs() < 0.08, "{probe:?} vs {truth:?}"); + } + // Perspective + no blending: plain layers, no masks. + let (sw, sh) = (520, 220); + let sc = scene(sw, sh, 8); + let mut s = Session::new(); + for (k, x0) in [0usize, 180].into_iter().enumerate() { + s.add_document(doc_from(&format!("p{k}"), &crop(&sc, sw, x0, 10, 260, 200, 1.0), 260, 200, SampleType::U8), None); + } + let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "perspective", "blend": false})).unwrap(); + assert_eq!(r["layout"], "perspective"); + let d = &s.active().unwrap().doc; + assert!(d.layers.iter().all(|l| l.mask.is_none())); + assert!((r["width"].as_i64().unwrap() - 440).abs() <= 8, "{r}"); + assert!(s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "zigzag"})).is_err()); + let mut empty = Session::new(); + assert!(empty.execute("file.automate.photomerge", json!({})).is_err()); +} + +#[test] +fn photomerge_cylindrical_with_fill() { + let (sw, sh) = (900, 260); + let sc = scene(sw, sh, 21); + let f = 260.0f64; + let mut s = Session::new(); + let (tw, th) = (260usize, 200usize); + for (k, pan) in [-0.45f64, 0.0, 0.45].into_iter().enumerate() { + let px: Vec<[f32; 4]> = (0..tw * th) + .map(|i| { + let (dx, dy) = ((i % tw) as f64 - tw as f64 / 2.0, (i / tw) as f64 - th as f64 / 2.0); + let (u, v) = (sw as f64 / 2.0 + f * (dx.atan2(f) + pan), sh as f64 / 2.0 + f * dy / dx.hypot(f)); + sc[(v.round().clamp(0.0, sh as f64 - 1.0) as usize) * sw + u.round().clamp(0.0, sw as f64 - 1.0) as usize] + }) + .collect(); + s.add_document(doc_from(&format!("c{k}"), &px, tw, th, SampleType::U8), None); + } + let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "cylindrical", "contentAwareFill": true})).unwrap(); + assert_eq!(r["layout"], "cylindrical"); + assert_eq!(r["placed"].as_array().unwrap().len(), 3, "{r}"); + let d = &s.active().unwrap().doc; + let top = d.layers.last().unwrap(); + assert_eq!(top.name, "Content-Aware Fill"); + // The fill layer is opaque everywhere (the bow-tie corners are filled). + let b = d.bounds(); + assert!(top.surface().unwrap().rgba(1, 1)[3] > 0.99 && top.surface().unwrap().rgba(b.x1 - 2, b.y1 - 2)[3] > 0.99); +} + +#[test] +fn hdr_merge_from_synthetic_exposures() { + let (w, h) = (96usize, 64usize); + let radiance: Vec<[f32; 3]> = (0..w * h) + .map(|i| { + let x = (i % w) as f32 / w as f32; + let b = 0.003 * 2f32.powf(x * 11.0) * (1.0 + 0.2 * ((i / w) as f32 * 0.3).sin()); + [b, b * 0.9, b * 0.7] + }) + .collect(); + let shoot = |dt: f32| -> Vec<[f32; 4]> { + radiance + .iter() + .map(|r| { + let f = |v: f32| photocraft_algo_srgb((v * dt).min(1.0)); + [f(r[0]), f(r[1]), f(r[2]), 1.0] + }) + .collect() + }; + let mut s = Session::new(); + for (k, dt) in [0.25f32, 1.0, 4.0].into_iter().enumerate() { + let mut d = doc_from(&format!("e{k}"), &shoot(dt), w, h, SampleType::U8); + d.metadata.exif = Some(std::sync::Arc::new(exif::build(&exif::CameraInfo { + exposure_time: Some(dt as f64 / 100.0), + f_number: Some(8.0), + iso: Some(100.0), + ..Default::default() + }))); + s.add_document(d, None); + } + let r = s.execute("file.automate.mergeToHdrPro", json!({"useOpenDocuments": true})).unwrap(); + assert_eq!(r["exposureSource"], "exif"); + let ev: Vec = r["ev"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + assert!((ev[1] - 2.0).abs() < 1e-6 && (ev[2] - 4.0).abs() < 1e-6, "{ev:?}"); + let d = &s.active().unwrap().doc; + assert_eq!(d.depth, SampleType::F32); + assert!(d.is_background(d.layers[0].id), "the merged layer is a real (locked) Background"); + let l = d.layers[0].surface().unwrap(); + // Linear output: ratios across the ramp follow the radiance. + let (a, b) = (l.rgba(20, 30)[1] as f64, l.rgba(80, 30)[1] as f64); + let expect = radiance[30 * w + 80][1] as f64 / radiance[30 * w + 20][1] as f64; + assert!(((b / a) / expect).ln().abs() < 0.3, "{} vs {expect}", b / a); + assert!(r["stops"].as_f64().unwrap() > 7.0, "{r}"); + let out = r["document"].as_u64().unwrap() as usize; + s.close(out); + // 8-bit tone-mapped output with explicit EVs. + for method in ["localAdaptation", "exposureGamma", "highlightCompression", "equalizeHistogram"] { + let r = s + .execute("file.automate.mergeToHdrPro", json!({"paths": [], "useOpenDocuments": true, "exposures": [0, 2, 4], "mode": "8", "method": method})) + .unwrap(); + assert_eq!(r["exposureSource"], "params"); + let d = &s.active().unwrap().doc; + assert_eq!(d.depth, SampleType::U8); + let out = r["document"].as_u64().unwrap() as usize; + s.close(out); + } + assert!(s.execute("file.automate.mergeToHdrPro", json!({"useOpenDocuments": true, "exposures": [0, 1]})).is_err()); +} + +fn photocraft_algo_srgb(v: f32) -> f32 { + if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } +} + +/// A light scan with one dark tilted print on it. +fn scan_with_one_photo() -> Document { + let (w, h) = (300usize, 220usize); + let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; + let (s, co) = 5.0f64.to_radians().sin_cos(); + for y in 0..h { + for x in 0..w { + let (dx, dy) = (x as f64 + 0.5 - 150.0, y as f64 + 0.5 - 110.0); + let (u, v) = (co * dx + s * dy, -s * dx + co * dy); + if u.abs() < 80.0 && v.abs() < 55.0 { + px[y * w + x] = [0.2 + (u / 160.0) as f32 * 0.3, 0.25, 0.3, 1.0]; + } + } + } + doc_from("scan", &px, w, h, SampleType::U8) +} + +#[test] +fn crop_and_straighten_keeps_duotone_inks() { + let mut s = Session::new(); + s.add_document(scan_with_one_photo(), None); + s.execute("image.mode.grayscale", json!({})).unwrap(); + s.execute( + "image.mode.duotone", + json!({"type": "duotone", "inks": [{"name": "Black", "color": [0, 0, 0]}, {"name": "Orange", "color": [255, 128, 0]}]}), + ) + .unwrap(); + let src = s.documents()[0].doc.duotone.clone(); + assert!(src.is_some()); + let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); + assert_eq!(r["photos"].as_array().unwrap().len(), 1, "{r}"); + let d = &s.documents()[1].doc; + assert_eq!(d.mode, ColorMode::Duotone); + assert_eq!(d.duotone, src); +} + +#[test] +fn crop_and_straighten_disabled_for_indexed() { + // Photoshop greys the command out for Indexed Color documents. + let mut s = Session::new(); + s.add_document(scan_with_one_photo(), None); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + assert_eq!(s.documents()[0].doc.mode, ColorMode::Indexed); + assert!(!s.is_enabled("file.automate.cropAndStraightenPhotos")); + assert!(s.execute("file.automate.cropAndStraightenPhotos", json!({})).is_err()); + assert_eq!(s.documents().len(), 1); +} + +#[test] +fn crop_and_straighten_only_processes_the_selection() { + // Photoshop: with a selection, only the photos inside it are split off. + let (w, h) = (480usize, 340usize); + let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; + // Upright photos: red 160x110 at (40, 60), blue 150x120 at (290, 180). + for (x0, y0, pw, ph, c) in [(40, 60, 160, 110, [0.6f32, 0.1, 0.1, 1.0]), (290, 180, 150, 120, [0.1, 0.2, 0.6, 1.0])] { + for y in y0..y0 + ph { + px[y * w + x0..y * w + x0 + pw].fill(c); + } + } + let mut s = Session::new(); + s.add_document(doc_from("scan", &px, w, h, SampleType::U8), None); + s.execute("select.rect", json!({"x": 270, "y": 160, "width": 190, "height": 160})).unwrap(); + let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); + let found = r["photos"].as_array().unwrap(); + assert_eq!(found.len(), 1, "{r}"); + assert_eq!(s.documents().len(), 2); + // The reported centre is in the scan's coordinates. + let c = &found[0]["center"]; + assert!((c[0].as_f64().unwrap() - 365.0).abs() < 3.0 && (c[1].as_f64().unwrap() - 240.0).abs() < 3.0, "{c}"); + let d = &s.documents()[1].doc; + assert!((d.size.width as i64 - 150).abs() <= 4 && (d.size.height as i64 - 120).abs() <= 4, "{:?}", d.size); + let q = d.layers[0].surface().unwrap().rgba(d.size.width as i32 / 2, d.size.height as i32 / 2); + assert!(q[2] > 0.5 && q[0] < 0.2, "{q:?}"); + // Without a selection both photos are found. + s.set_active(0); + s.execute("select.deselect", json!({})).unwrap(); + let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); + assert_eq!(r["photos"].as_array().unwrap().len(), 2, "{r}"); +} + +#[test] +fn crop_and_straighten_skips_photos_between_selected_regions() { + // Two selected rectangles: a photo in the gap between them lies inside + // their bounding box but outside the selection, so it is not split off. + let (w, h) = (480usize, 340usize); + let mut px = vec![[0.75f32, 0.75, 0.75, 1.0]; w * h]; + // Red 160x110 at (40, 60) and blue 150x120 at (290, 180) are selected; green 130x80 at (280, 50) is not. + for (x0, y0, pw, ph, c) in + [(40, 60, 160, 110, [0.6f32, 0.1, 0.1, 1.0]), (290, 180, 150, 120, [0.1, 0.2, 0.6, 1.0]), (280, 50, 130, 80, [0.1, 0.6, 0.1, 1.0])] + { + for y in y0..y0 + ph { + px[y * w + x0..y * w + x0 + pw].fill(c); + } + } + let mut s = Session::new(); + s.add_document(doc_from("scan", &px, w, h, SampleType::U8), None); + s.execute("select.rect", json!({"x": 20, "y": 40, "width": 200, "height": 150})).unwrap(); + s.execute("select.rect", json!({"x": 270, "y": 160, "width": 190, "height": 160, "mode": "add"})).unwrap(); + let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); + let found = r["photos"].as_array().unwrap(); + assert_eq!(found.len(), 2, "{r}"); + for f in found { + let c = &f["center"]; + let (cx, cy) = (c[0].as_f64().unwrap(), c[1].as_f64().unwrap()); + let near = |x: f64, y: f64| (cx - x).abs() < 3.0 && (cy - y).abs() < 3.0; + assert!(near(120.0, 115.0) || near(365.0, 240.0), "{c}"); + } +} + +#[test] +fn crop_and_straighten_refuses_a_selection_under_half_coverage() { + // A faint (strongly feathered) selection has no pixel at or above 50%: + // like Photoshop, nothing counts as selected, so no photo is split off + // from the unmasked bounding box. + let (w, h) = (480usize, 340usize); + let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; + for y in 180..300 { + px[y * w + 290..y * w + 440].fill([0.1, 0.2, 0.6, 1.0]); + } + let mut s = Session::new(); + s.add_document(doc_from("scan", &px, w, h, SampleType::U8), None); + let mut m = Surface::new(photocraft_color::PixelFormat::GRAY8); + m.fill_rect(Rect::new(270, 160, 460, 320), &[0.3]); + std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).selection = Some(m); + let e = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap_err(); + assert!(e.to_string().contains("50%"), "{e}"); + assert_eq!(s.documents().len(), 1); +} + +#[test] +fn crop_and_straighten_makes_documents() { + let (w, h) = (500usize, 360usize); + let mut px = vec![[0.98f32, 0.98, 0.98, 1.0]; w * h]; + let photos = [([140.0f64, 120.0f64], 160.0f64, 110.0f64, 6.0f64), ([360.0, 240.0], 150.0, 120.0, -9.0)]; + for (c, pw, ph, ang) in photos { + let (s, co) = ang.to_radians().sin_cos(); + for y in 0..h { + for x in 0..w { + let (dx, dy) = (x as f64 + 0.5 - c[0], y as f64 + 0.5 - c[1]); + let (u, v) = (co * dx + s * dy, -s * dx + co * dy); + if u.abs() < pw / 2.0 && v.abs() < ph / 2.0 { + px[y * w + x] = [0.2 + (u / pw) as f32 * 0.3, 0.3, 0.6, 1.0]; + } + } + } + } + let mut s = Session::new(); + s.add_document(doc_from("scan", &px, w, h, SampleType::U16), None); + assert!(s.is_enabled("file.automate.cropAndStraightenPhotos")); + let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); + let found = r["photos"].as_array().unwrap(); + assert_eq!(found.len(), 2, "{r}"); + assert_eq!(s.documents().len(), 3); + assert!((found[0]["angle"].as_f64().unwrap() - 6.0).abs() < 1.0); + let d = &s.documents()[1].doc; + assert!((d.size.width as i64 - 158).abs() <= 4 && (d.size.height as i64 - 108).abs() <= 4, "{:?}", d.size); + assert_eq!(d.depth, SampleType::U16); + // Upright: the photo's horizontal gradient runs along x. + let l = d.layers[0].surface().unwrap(); + let (a, b) = (l.rgba(10, d.size.height as i32 / 2)[0], l.rgba(d.size.width as i32 - 10, d.size.height as i32 / 2)[0]); + assert!(b > a + 0.15, "{a} {b}"); + let (c, e) = (l.rgba(d.size.width as i32 / 2, 6)[0], l.rgba(d.size.width as i32 / 2, d.size.height as i32 - 6)[0]); + assert!((c - e).abs() < 0.05); +} From 0e2ee0a858ff2603e74ee33ba9252accb7d7bce0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:23 +0000 Subject: [PATCH 044/259] refactor(engine): move image_cmds.rs tests to image_cmds/tests.rs --- crates/engine/src/image_cmds.rs | 972 +------------------------- crates/engine/src/image_cmds/tests.rs | 969 +++++++++++++++++++++++++ 2 files changed, 970 insertions(+), 971 deletions(-) create mode 100644 crates/engine/src/image_cmds/tests.rs diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index 1efc9c0a0e..17f87691c8 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -1038,974 +1038,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn crop_rejects_rectangles_that_would_wrap() { - let mut s = session(); - // 2^32 + 100 wrapped to `x = 100` through the narrowing casts: a crop rectangle - // somewhere unrelated to the numbers passed. - let err = s.execute("image.crop", json!({"x": 4_294_967_396_i64, "y": 0, "width": 10, "height": 10})).unwrap_err(); - assert!(err.to_string().contains("32-bit"), "{err}"); - // In-range rectangles past the canvas still work (clamped by the crop itself). - s.execute("image.crop", json!({"x": -10, "y": -10, "width": 1000, "height": 1000})).unwrap(); - } - - /// A crop whose translation to the origin can't be represented in i32 is rejected before - /// anything changes (#959): `-i32::MIN` overflowed the negation in `crop_doc`, `x + width` - /// past i32::MAX silently shortened the crop, and an origin one past i32::MIN moved the - /// layer pixels beyond i32::MAX (a length-mismatch panic while translating surfaces). - #[test] - fn crop_rejects_origins_that_cannot_move_to_zero() { - const MIN: i64 = i32::MIN as i64; - const MAX: i64 = i32::MAX as i64; - let cases = [ - json!({"x": MIN, "y": 0, "width": 1, "height": 1}), - json!({"x": 0, "y": MIN, "width": 1, "height": 1}), - json!({"x": MIN, "y": MIN, "width": 1, "height": 1}), - json!({"x": MIN, "y": 0, "width": 1, "height": 1, "deleteCroppedPixels": false}), - json!({"x": MAX - 5, "y": 0, "width": 10, "height": 1}), - json!({"x": 0, "y": MAX - 5, "width": 1, "height": 10}), - json!({"x": MIN + 1, "y": 0, "width": 1, "height": 1, "deleteCroppedPixels": false}), - json!({"x": 0, "y": MIN + 1, "width": 1, "height": 1, "deleteCroppedPixels": false}), - ]; - for p in cases { - let mut s = session(); - let before = s.active().unwrap().doc.clone(); - let (rev, steps) = (s.active().unwrap().revision, s.active().unwrap().history.entries().len()); - let err = s.execute("image.crop", p.clone()).unwrap_err(); - assert!(matches!(err, EngineError::BadParams { .. }), "{p}: {err}"); - assert!(err.to_string().contains("32-bit"), "{p}: {err}"); - let st = s.active().unwrap(); - assert!(std::sync::Arc::ptr_eq(&st.doc, &before), "{p}: document changed"); - assert_eq!(st.doc.size, Size::new(40, 20), "{p}"); - assert_eq!(st.doc.layers[1].surface().unwrap().content_bounds(), Rect::new(10, 5, 20, 15), "{p}"); - assert_eq!((st.revision, st.history.entries().len()), (rev, steps), "{p}: history step recorded"); - } - // Control: a legal negative origin past the canvas still crops (and extends) the canvas. - let mut s = session(); - s.execute("image.crop", json!({"x": -10, "y": -5, "width": 60, "height": 30})).unwrap(); - assert_eq!(doc(&s).size, Size::new(60, 30)); - assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 10), vec![1.0, 0.0, 0.0, 1.0]); - // A far-off crop that deletes the (non-overlapping) pixels has nothing left to move. - let mut s = session(); - s.execute("image.crop", json!({"x": MIN + 1, "y": 0, "width": 1, "height": 1})).unwrap(); - assert_eq!(doc(&s).size, Size::new(1, 1)); - } - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 20})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - l.surface_mut().unwrap().fill_rect(Rect::new(10, 5, 20, 15), &[1.0, 0.0, 0.0, 1.0]); - l.mask = Some(photocraft_doc::LayerMask::reveal_all()); - l.effects.items.push(Effect::default_drop_shadow()); - Ok(()) - }) - .unwrap(); - s - } - - fn doc(s: &Session) -> &Document { - &s.active().unwrap().doc - } - - /// Document-wide conversions must move every stored video frame, not just the displayed one (#4956). - #[test] - fn crop_moves_stored_video_frames() { - let mut s = session(); - s.edit("video", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - let frame = l.surface().unwrap().clone(); - let mut v = photocraft_doc::VideoData::new(vec![frame.clone(), frame.clone()], 24.0); - v.original_frames = Some(vec![frame.clone(), frame]); - l.video = Some(v); - Ok(()) - }) - .unwrap(); - s.execute("image.crop", json!({"x": -10, "y": -5, "width": 60, "height": 30})).unwrap(); - let v = doc(&s).layers[1].video.as_ref().unwrap(); - let red = vec![1.0, 0.0, 0.0, 1.0]; - for frame in v.frames.iter().chain(v.original_frames.iter().flatten()) { - assert_eq!(frame.pixel(20, 10), red); - assert_eq!(frame.pixel(5, 5)[3], 0.0); - } - } - - /// Delete Cropped Pixels on a shrinking crop deletes the cropped area from every stored video - /// frame (and the original footage), not just the displayed one (#4956). - #[test] - fn delete_cropped_pixels_crops_stored_video_frames() { - let mut s = session(); - s.edit("video", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - let red = l.surface().unwrap().clone(); - let mut blue = red.clone(); - blue.fill_rect(Rect::new(0, 0, 40, 20), &[0.0, 0.0, 1.0, 1.0]); - let mut v = photocraft_doc::VideoData::new(vec![red.clone(), blue.clone()], 24.0); - v.original_frames = Some(vec![red, blue]); - l.video = Some(v); - Ok(()) - }) - .unwrap(); - s.execute("image.crop", json!({"x": 15, "y": 0, "width": 25, "height": 20, "deleteCroppedPixels": true})).unwrap(); - assert_eq!(doc(&s).size, Size::new(25, 20)); - let v = doc(&s).layers[1].video.as_ref().unwrap(); - let originals = v.original_frames.as_ref().unwrap(); - assert_eq!((v.frames.len(), originals.len()), (2, 2)); - for frames in [&v.frames, originals] { - // The red square (10..20, 5..15) keeps only its right half; the full blue frame - // keeps exactly the 25×20 crop. - assert_eq!(frames[0].content_bounds(), Rect::new(0, 5, 5, 15)); - assert_eq!(frames[0].pixel(2, 10), vec![1.0, 0.0, 0.0, 1.0]); - assert_eq!(frames[1].content_bounds(), Rect::new(0, 0, 25, 20)); - assert_eq!(frames[1].pixel(24, 19), vec![0.0, 0.0, 1.0, 1.0]); - } - } - - /// Resample on with only a new resolution keeps the print size, as Photoshop's Image Size - /// does (an action's `imageSize` with `Rslt` alone); without `keepPrintSize` only the - /// resolution changes. - #[test] - fn image_size_keep_print_size_resamples_to_the_resolution() { - let mut s = session(); - s.execute("image.imageSize", json!({"resolution": 144, "resample": "bicubic"})).unwrap(); - assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(40, 20), 144.0)); - s.execute("image.imageSize", json!({"resolution": 288, "resample": "bicubic", "keepPrintSize": true})).unwrap(); - assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(80, 40), 288.0)); - // An explicit side still wins. - s.execute("image.imageSize", json!({"width": 20, "resolution": 72, "resample": "bicubic", "keepPrintSize": true})).unwrap(); - assert_eq!(doc(&s).size, Size::new(20, 10)); - } - - #[test] - fn image_size_scales_everything() { - for resample in ["bicubic", "bicubicSmoother", "bicubicSharper", "bicubicAutomatic", "automatic", "bilinear", "nearest", "lanczos", "preserveDetails"] { - let mut s = session(); - s.execute("image.imageSize", json!({"width": 80, "resample": resample})).unwrap(); - let d = doc(&s); - assert_eq!(d.size, Size::new(80, 40), "{resample}"); - let l = &d.layers[1]; - let b = l.surface().unwrap().content_bounds(); - assert!((b.x0 - 20).abs() <= 1 && (b.x1 - 40).abs() <= 1, "{resample} {b:?}"); - let Effect::DropShadow(sh) = &l.effects.items[0] else { panic!() }; - assert_eq!(sh.distance, 10.0); - assert_eq!(l.mask.as_ref().unwrap().surface.default_pixel(), vec![1.0]); - } - } - - /// #6019: Image Size on an Indexed Color document makes no colours the colour table doesn't have. - #[test] - fn image_size_resamples_indexed_color_with_nearest_neighbor() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 2, "height": 1})).unwrap(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - s.execute("select.rect", json!({"x": 1, "y": 0, "width": 1, "height": 1})).unwrap(); - s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("image.mode.indexedColor", json!({})).unwrap(); - for resample in ["bicubic", "automatic", "bilinear", "lanczos", "preserveDetails"] { - s.execute("image.imageSize", json!({"width": 8, "resample": resample})).unwrap(); - let st = s.active().unwrap(); - let surf = st.doc.layers[0].surface().unwrap(); - for x in 0..8 { - let px = surf.pixel(x, 0); - assert!(px[..3] == [1.0, 0.0, 0.0] || px[..3] == [0.0, 0.0, 1.0], "{resample}: no blended colour at x {x}: {px:?}"); - } - s.execute("history.undo", json!({})).unwrap(); - } - } - - /// The canvas border stays opaque after Image Size (it used to fade into transparency, so a - /// Background or a 200 % export got a translucent frame), and a full selection stays full. - /// #1544: 64 x 48 to 300000 x 300000 (90 billion pixels) started allocating resampled bands - /// without a budget. It is refused before any allocation and the document is untouched; a - /// change of resolution only, and an ordinary resize, still work. - #[test] - fn image_size_refuses_a_raster_past_the_budget() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); - let before = (doc(&s).size, s.active().unwrap().history.past_len()); - let err = s.execute("image.imageSize", json!({"width": 300_000, "height": 300_000})).unwrap_err().to_string(); - assert!(err.contains("megapixels"), "{err}"); - assert_eq!((doc(&s).size, s.active().unwrap().history.past_len()), before); - s.execute("image.imageSize", json!({"width": 300_000, "height": 300_000, "resample": "none", "resolution": 300})).unwrap(); - s.execute("image.imageSize", json!({"width": 128, "height": 96})).unwrap(); - assert_eq!(doc(&s).size, Size::new(128, 96)); - } - - #[test] - fn image_size_keeps_canvas_edges_opaque() { - for depth in [8, 16, 32] { - for (w, resample) in [ - (60, "bicubic"), - (41, "lanczos"), - (15, "bilinear"), - (77, "preserveDetails"), - (21, "bicubicSharper"), - (47, "automatic"), - (9, "bicubicAutomatic"), - ] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 30, "height": 20, "depth": depth, "background": "#336699"})).unwrap(); - s.execute("select.all", json!({})).unwrap(); - s.execute("image.imageSize", json!({"width": w, "resample": resample})).unwrap(); - let d = doc(&s); - let flat = photocraft_compose::flatten(d); - let (w, h) = (flat.rect.width() as usize, flat.rect.height() as usize); - let mid = flat.px[(h / 2) * w + w / 2]; - assert!((mid[3] - 1.0).abs() < 1e-3, "{depth} {resample}: {mid:?}"); - for p in &flat.px { - let off = p.iter().zip(mid).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(off < 0.01, "{depth} {resample} {w}: {p:?} vs {mid:?}"); - } - let sel = d.selection.as_ref().unwrap(); - let (x1, y1) = (d.size.width as i32 - 1, d.size.height as i32 - 1); - for (x, y) in [(0, 0), (x1, 0), (0, y1), (x1, y1)] { - assert!(sel.pixel(x, y)[0] > 0.99, "{depth} {resample}: selection at ({x},{y})"); - } - } - } - } - - #[test] - fn resolution_only_change() { - let mut s = session(); - let r = s.execute("image.imageSize", json!({"resolution": 300, "resample": "none", "width": 999})).unwrap(); - assert_eq!(doc(&s).size, Size::new(40, 20)); - assert_eq!(doc(&s).resolution_dpi, 300.0); - // #1815: the result is the size the document has, not the ignored request. - assert_eq!(r, json!({"width": 40, "height": 20})); - } - - /// Type keeps its pixel size across a resolution change: resampled 2x at twice the ppi it is - /// twice as tall (not 4x), with Resample off it stays, and a later re-render doesn't jump. - #[test] - fn image_size_with_a_new_resolution_scales_type_with_the_pixels_only() { - for (params, k) in [(json!({"width": 200, "height": 200, "resolution": 144}), 2), (json!({"resolution": 144, "resample": "none"}), 1)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); - s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi", "size": 12})).unwrap(); - let height = |s: &Session| doc(s).layers.last().unwrap().surface().unwrap().content_bounds().height(); - let h0 = height(&s); - assert!(h0 > 4, "{h0}"); - s.execute("image.imageSize", params.clone()).unwrap(); - assert!(height(&s).abs_diff(h0 * k) <= 2, "{params}: {h0} -> {}", height(&s)); - let d = doc(&s); - let LayerContent::Text(t) = &d.layers.last().unwrap().content else { panic!("type layer") }; - let mut t = t.clone(); - crate::type_cmds::refresh(d, &mut t); - let after = t.cache.unwrap().content_bounds().height(); - assert!(after.abs_diff(h0 * k) <= 2, "{params}: re-rendered {h0} -> {after}"); - } - } - - #[test] - fn image_size_reports_the_size_it_applied() { - // #1815: every path reports the document's size afterwards, at every depth. - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth})).unwrap(); - let size = |s: &Session| json!({"width": doc(s).size.width, "height": doc(s).size.height}); - for p in [ - json!({"width": 999, "height": 777, "resample": "none", "resolution": 150}), - json!({"width": 32}), - json!({"height": 96, "resample": "nearest"}), - json!({"width": 96, "height": 72, "resample": "none"}), - json!({}), - ] { - let r = s.execute("image.imageSize", p.clone()).unwrap(); - assert_eq!(r, size(&s), "{depth}-bit {p}"); - } - // 64×48 → (none) → 32×24 → 128×96 (aspect kept) → (none) → unchanged. - assert_eq!(doc(&s).size, Size::new(128, 96), "{depth}-bit"); - } - } - - /// #1114: nearest neighbor reduction keeps source values without averaging. - #[test] - fn nearest_neighbor_reduction_keeps_source_values() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); - s.execute("tools.setColors", json!({"foreground": "#000000", "background": "#ffffff"})).unwrap(); - for y in 0..8 { - for x in 0..8 { - if (x + y) % 2 == 0 { - s.execute("select.rect", json!({"x": x, "y": y, "width": 1, "height": 1})).unwrap(); - s.execute("edit.fill", json!({"contents": "foreground"})).unwrap(); - } - } - } - s.execute("select.deselect", json!({})).unwrap(); - let st = s.active().unwrap(); - let before = st.doc.layers[0].surface().unwrap().rgba(0, 0); - assert!(before[0] < 0.01, "setup: (0,0) should be black, got {before:?}"); - s.execute("image.imageSize", json!({"width": 4, "height": 4, "resample": "nearest"})).unwrap(); - let st = s.active().unwrap(); - let surf = st.doc.layers[0].surface().unwrap(); - for (x, y) in [(0, 0), (1, 1), (2, 3)] { - let v = surf.rgba(x, y)[0]; - assert!(v.is_finite() && !(0.01..=0.99).contains(&v), "nearest produced an averaged value {v} at ({x},{y})"); - } - } - - #[test] - fn canvas_size_anchors_and_extends_background() { - let mut s = session(); - s.execute("image.canvasSize", json!({"width": 60, "height": 30, "anchor": "topLeft", "extensionColor": "#00ff00"})).unwrap(); - let d = doc(&s); - assert_eq!(d.size, Size::new(60, 30)); - assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(10, 5, 20, 15)); - let bg = d.layers[0].surface().unwrap(); - assert_eq!(bg.pixel(50, 25), vec![0.0, 1.0, 0.0, 1.0]); - assert_eq!(bg.pixel(5, 5), vec![1.0, 1.0, 1.0, 1.0]); - let mut s = session(); - s.execute("image.canvasSize", json!({"width": 20, "height": 10, "relative": true, "anchor": "center"})).unwrap(); - assert_eq!(doc(&s).layers[1].surface().unwrap().content_bounds(), Rect::new(20, 10, 30, 20)); - } - - #[test] - fn canvas_size_anchor_offsets_and_rejects_unlisted() { - // 64x48 -> 100x80: dx spans 36 and dy spans 32, so each anchor factor lands on a known - // offset. All nine documented values must anchor exactly where they do today (#2946). - let expected = [ - ("topLeft", [0, 0]), - ("top", [18, 0]), - ("topRight", [36, 0]), - ("left", [0, 16]), - ("center", [18, 16]), - ("right", [36, 16]), - ("bottomLeft", [0, 32]), - ("bottom", [18, 32]), - ("bottomRight", [36, 32]), - ]; - for (anchor, off) in expected { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); - let r = s.execute("image.canvasSize", json!({"width": 100, "height": 80, "anchor": anchor})).unwrap(); - assert_eq!(r["offset"], json!(off), "anchor {anchor}"); - } - // An omitted anchor still defaults to center. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); - assert_eq!(s.execute("image.canvasSize", json!({"width": 100, "height": 80})).unwrap()["offset"], json!([18, 16])); - // A misspelling or unknown value is a BadParams error naming `anchor`, never an anchor - // between two of the nine (the old independent-axis matching produced top-centre etc.). - for anchor in ["topleft", "TopLeft", "TOPLEFT", "bottomleft", "bottomright", "middle", "", "NOPE"] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); - let err = s.execute("image.canvasSize", json!({"width": 100, "height": 80, "anchor": anchor})).unwrap_err(); - assert!(matches!(err, EngineError::BadParams { .. }), "anchor {anchor:?} must be rejected, got {err:?}"); - assert!(err.to_string().contains("anchor"), "the error for {anchor:?} must name `anchor`: {err}"); - } - } - - #[test] - fn crop_to_selection_and_trim() { - let mut s = session(); - assert!(s.execute("image.crop", json!({})).is_err(), "no selection, no rect"); - s.execute("select.rect", json!({"x": 5, "y": 2, "width": 20, "height": 10})).unwrap(); - s.execute("image.crop", json!({})).unwrap(); - let d = doc(&s); - assert_eq!(d.size, Size::new(20, 10)); - assert!(d.selection.is_none()); - assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(5, 3, 15, 10)); - // Trim transparent: hide the background, trim to the red square. - let mut s = session(); - s.execute("layer.setProps", json!({"layer": doc(&s).layers[0].id.0, "visible": false})).unwrap(); - s.execute("image.trim", json!({"basedOn": "transparent"})).unwrap(); - // The red square (10×10) plus its drop shadow (distance 5, size 5). - let size = doc(&s).size; - assert!(size.width > 10 && size.width < 30 && size.height > 10 && size.height < 25, "{size:?}"); - } - - #[test] - fn crop_to_explicit_rect_can_extend_canvas() { - let mut s = session(); - s.execute("image.crop", json!({"x": 10, "y": 5, "width": 10, "height": 10})).unwrap(); - assert_eq!(doc(&s).size, Size::new(10, 10)); - assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(0, 0), vec![1.0, 0.0, 0.0, 1.0]); - let mut s = session(); - s.execute("image.crop", json!({"x": -10, "y": 0, "width": 60, "height": 20})).unwrap(); - assert_eq!(doc(&s).size, Size::new(60, 20)); - assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 5), vec![1.0, 0.0, 0.0, 1.0]); - } - - #[test] - fn crop_extension_fills_the_background_with_the_background_colour() { - let mut shrink = Session::new(); - shrink.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); - shrink.execute("image.crop", json!({"x": 2, "y": 0, "width": 12, "height": 16})).unwrap(); - let layer = &doc(&shrink).layers[0]; - assert_eq!(layer.name, "Background", "a shrink-only crop keeps the Background"); - assert!(layer.locks.transparency && layer.locks.position); - - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); - s.tools.background = [0.0, 1.0, 0.0, 1.0]; - s.execute("image.crop", json!({"x": -4, "y": 0, "width": 20, "height": 16})).unwrap(); - let layer = &doc(&s).layers[0]; - assert_eq!(layer.name, "Background", "an extending crop keeps the Background (#3081)"); - assert!(layer.locks.transparency && layer.locks.position); - assert_eq!(layer.surface().unwrap().rgba(1, 8), [0.0, 1.0, 0.0, 1.0], "the added border takes the background colour"); - assert_eq!(layer.surface().unwrap().rgba(8, 8), [1.0, 0.0, 0.0, 1.0], "the original pixels stay"); - - s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - let layer = &doc(&s).layers[0]; - assert_eq!(layer.surface().unwrap().rgba(1, 8), [0.0, 0.0, 1.0, 1.0], "Fill paints the extended border"); - assert_eq!(layer.surface().unwrap().rgba(8, 8), [0.0, 0.0, 1.0, 1.0]); - - s.execute("edit.undo", json!({})).unwrap(); - s.execute("edit.undo", json!({})).unwrap(); - let layer = &doc(&s).layers[0]; - assert_eq!(doc(&s).size, Size::new(16, 16)); - assert_eq!(layer.surface().unwrap().rgba(8, 8), [1.0, 0.0, 0.0, 1.0]); - assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(0, 0, 16, 16), "undo removes the filled border"); - - // A normal layer gets transparent pixels in the added area. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); - s.execute("layer.new.layerFromBackground", json!({})).unwrap(); - s.execute("image.crop", json!({"x": -4, "y": 0, "width": 20, "height": 16})).unwrap(); - assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(1, 8), [0.0; 4]); - } - - /// Delete Cropped Pixels deletes pixel-layer data only: type and smart objects keep what lies - /// outside the frame, so moving them later doesn't show them cut at the old edge. - #[test] - fn delete_cropped_pixels_keeps_type_and_smart_objects_whole() { - let mut s = session(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("type.create", json!({"x": 10, "y": 15, "text": "Hi", "size": 12})).unwrap(); - let bounds = |s: &Session| -> Vec { doc(s).layers[1..].iter().map(|l| l.surface().unwrap().content_bounds()).collect() }; - let before = bounds(&s); - assert!(before.iter().all(|b| b.x0 < 15 && b.x1 > 15), "both cross the crop edge: {before:?}"); - s.execute("image.crop", json!({"x": 15, "y": 0, "width": 25, "height": 20})).unwrap(); - assert!(matches!(doc(&s).layers[1].content, LayerContent::Smart(_)) && matches!(doc(&s).layers[2].content, LayerContent::Text(_))); - assert_eq!(bounds(&s), before.iter().map(|b| b.translate(-15, 0)).collect::>()); - } - - /// A turned crop deleting pixels keeps type and smart objects whole too, also a smart object - /// whose source is unavailable (the rotation can't re-render it, so it keeps its cache): each - /// ends up exactly as the same turned crop with Delete Cropped Pixels off leaves it. - #[test] - fn turned_crop_deleting_pixels_keeps_type_and_smart_objects_whole() { - let [deleted, kept] = [true, false].map(|delete| { - let mut s = session(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.edit("unlink", |doc, active| { - if let LayerContent::Smart(sm) = &mut doc.layer_mut(active.unwrap()).unwrap().content { - sm.source = photocraft_doc::SmartSource::Linked { path: "missing-photocraft-test-source.psd".into() }; - } - Ok(()) - }) - .unwrap(); - s.execute("type.create", json!({"x": 10, "y": 15, "text": "Hi", "size": 12})).unwrap(); - s.execute("image.crop", json!({"x": 20, "y": 0, "width": 20, "height": 20, "angle": 2.0, "deleteCroppedPixels": delete})).unwrap(); - s - }); - let (a, b) = (doc(&deleted), doc(&kept)); - assert!(matches!(a.layers[1].content, LayerContent::Smart(_)) && matches!(a.layers[2].content, LayerContent::Text(_))); - for i in [1, 2] { - let (sa, sb) = (a.layers[i].surface().unwrap(), b.layers[i].surface().unwrap()); - let r = sb.content_bounds(); - assert!(r.x0 < 0, "layer {i} reaches past the crop's left edge: {r:?}"); - assert_eq!(sa.content_bounds(), r, "layer {i}"); - assert_eq!(sa.read_region(r), sb.read_region(r), "layer {i}"); - } - } - - /// The Background keeps the pixels a crop with Delete Cropped Pixels off hid: extending the - /// canvas over them again (Reveal All, Canvas Size) shows them rather than painting them over - /// with the background colour (#7086). - #[test] - fn extending_the_canvas_keeps_the_backgrounds_hidden_pixels() { - for depth in [8, 16, 32] { - let hidden = |s: &mut Session| { - s.execute("file.new", json!({"width": 100, "height": 100, "depth": depth, "background": "white"})).unwrap(); - s.edit("paint", |doc, _| { - let bg = doc.background_mut().unwrap(); - bg.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 50, 100), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - s.execute("image.crop", json!({"x": 50, "y": 0, "width": 50, "height": 100, "deleteCroppedPixels": false})).unwrap(); - s.tools.background = [0.0, 0.0, 0.0, 1.0]; - }; - let mut s = Session::new(); - hidden(&mut s); - s.execute("image.revealAll", json!({})).unwrap(); - let surf = doc(&s).background().unwrap().surface().unwrap(); - assert_eq!(doc(&s).size, Size::new(100, 100), "{depth}-bit"); - assert_eq!(surf.rgba(10, 50), [1.0, 0.0, 0.0, 1.0], "{depth}-bit: Reveal All shows the hidden red half"); - assert_eq!(surf.rgba(80, 50), [1.0, 1.0, 1.0, 1.0], "{depth}-bit"); - - // Canvas Size wider than the hidden pixels: they show, the rest takes the colour. - let mut s = Session::new(); - hidden(&mut s); - s.execute("image.canvasSize", json!({"width": 120, "height": 100, "anchor": "right"})).unwrap(); - let surf = doc(&s).background().unwrap().surface().unwrap(); - assert_eq!(surf.rgba(5, 50), [0.0, 0.0, 0.0, 1.0], "{depth}-bit: past the hidden pixels the background colour"); - assert_eq!(surf.rgba(30, 50), [1.0, 0.0, 0.0, 1.0], "{depth}-bit: Canvas Size shows the hidden red half"); - assert_eq!(surf.rgba(100, 50), [1.0, 1.0, 1.0, 1.0], "{depth}-bit"); - } - } - - /// A Background without an alpha channel (a Grayscale PSD import) has no hidden pixels to tell - /// from empty ones: the added area takes the colour, the kept area stays (#7086). - #[test] - fn an_alpha_less_background_extension_takes_the_colour() { - let mut surf = Surface::new(photocraft_color::PixelFormat::GRAY8); - surf.fill_rect(Rect::new(-50, 0, 100, 100), &[0.6]); - let kept = surf.pixel(50, 50); - fill_background_extension(&mut surf, Rect::new(-60, 0, 100, 100), Rect::new(0, 0, 100, 100), &[0.0]); - assert_eq!(surf.pixel(-55, 50), vec![0.0], "past the old pixels the colour"); - assert_eq!(surf.pixel(-30, 50), vec![0.0], "no alpha: the added area takes the colour"); - assert_eq!(surf.pixel(50, 50), kept, "the kept area is unchanged"); - } - - /// A document (`mode`, `depth`) with a white Background and a layer holding a red pixel at - /// (12, 8) and a blue one at (30, 3). - fn marked(mode: &str, depth: u32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 20, "mode": mode, "depth": depth, "background": "white"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - for (x, y, c) in [(12, 8, "#ff0000"), (30, 3, "#0000ff")] { - s.execute("select.rect", json!({"x": x, "y": y, "width": 1, "height": 1})).unwrap(); - s.execute("edit.fill", json!({"color": c})).unwrap(); - } - s.execute("select.deselect", json!({})).unwrap(); - s - } - - fn layer_rgba(s: &Session, layer: usize, x: i32, y: i32) -> [f32; 4] { - doc(s).layers[layer].surface().unwrap().rgba(x, y) - } - - /// #1792: a frame turned 90° clockwise crops what Image Rotation › Arbitrary 90° CCW and a - /// plain crop give, in one undo step that restores the document, at 8, 16 and 32 bits. - #[test] - fn crop_at_90_degrees_is_rotate_then_crop_in_one_step() { - for depth in [8, 16, 32] { - let mut s = marked("rgb", depth); - let before = doc(&s).clone(); - let past = s.active().unwrap().history.past_len(); - // The 10 × 20 frame at (10, 0), turned 90° about (15, 10), covers x 5..25, y 5..15. - let r = s.execute("image.crop", json!({"x": 10, "y": 0, "width": 10, "height": 20, "angle": 90})).unwrap(); - assert_eq!(r["angle"], json!(90.0), "{depth}"); - assert_eq!(doc(&s).size, Size::new(10, 20), "{depth}"); - assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{depth}: one undo step"); - // (12, 8) is 2.5 left of and 1.5 above the centre: in the upright frame, 1.5 left of - // and 2.5 below its centre (5, 10). - let red = layer_rgba(&s, 1, 3, 12); - assert!(red[0] > 0.9 && red[1] < 0.1 && red[3] > 0.9, "{depth}: {red:?}"); - let mut reference = marked("rgb", depth); - reference.execute("image.rotation.arbitrary", json!({"angle": 90, "direction": "ccw"})).unwrap(); - reference.execute("image.crop", json!({"x": 5, "y": 15, "width": 10, "height": 20})).unwrap(); - for l in 0..2 { - for y in 0..20 { - for x in 0..10 { - let (a, b) = (layer_rgba(&s, l, x, y), layer_rgba(&reference, l, x, y)); - // A fully transparent pixel's colour is invisible, and the turned crop - // doesn't turn the pixels it deletes, which the warp spreads colour from. - let n = if b[3] > 1e-3 { 4 } else { 1 }; - assert!(a.iter().rev().zip(b.iter().rev()).take(n).all(|(p, q)| (p - q).abs() < 1e-3), "{depth} layer {l} ({x}, {y}): {a:?} vs {b:?}"); - } - } - } - s.execute("edit.undo", json!({})).unwrap(); - let d = doc(&s); - assert_eq!(d.size, before.size, "{depth}"); - assert_eq!(d.depth, before.depth); - for y in 0..20 { - for x in 0..40 { - assert_eq!(layer_rgba(&s, 1, x, y), before.layers[1].surface().unwrap().rgba(x, y), "{depth} undo at ({x}, {y})"); - } - } - } - } - - /// A slightly turned frame keeps its own size, the pixel under its centre and the Background's - /// colour; the turn's sign matters (a counter-clockwise frame is a negative angle). - #[test] - fn crop_at_a_small_angle_keeps_the_frame_size_in_every_mode() { - for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("grayscale", 16), ("cmyk", 8), ("lab", 16)] { - for angle in [5.0, -7.5, 365.0] { - let mut s = marked(mode, depth); - s.execute("image.crop", json!({"x": 2, "y": 1, "width": 21, "height": 15, "angle": angle})).unwrap(); - let d = doc(&s); - assert_eq!(d.size, Size::new(21, 15), "{mode} {depth} {angle}"); - assert_eq!(d.depth.bytes() * 8, depth as usize, "{mode} {depth}"); - assert_eq!(format!("{:?}", d.mode).to_lowercase(), mode, "{mode} {depth}"); - assert_eq!(d.layers.len(), 2); - // The frame's centre (12.5, 8.5) is the red pixel (the layer's only paint nearby); - // it stays at the centre, its colour kept. - let want = layer_rgba(&marked(mode, depth), 1, 12, 8); - let red = layer_rgba(&s, 1, 10, 7); - assert!(red[3] > 0.5 && (0..3).all(|c| (red[c] - want[c]).abs() < 0.2), "{mode} {depth} {angle}: {red:?} vs {want:?}"); - // The Background stays opaque white inside the canvas it came from. - let bg = layer_rgba(&s, 0, 10, 7); - assert!(bg.iter().all(|v| (v - 1.0).abs() < 0.02), "{mode} {depth} {angle}: {bg:?}"); - } - } - } - - /// A turned crop that deletes the cropped pixels turns only what lands in the frame; inside the - /// new canvas every layer, mask and channel is exactly what turning everything gives (the - /// frame spans several tiles, at several depths and angles). - #[test] - fn turned_crop_deleting_pixels_matches_turning_the_whole_canvas() { - use photocraft_color::PixelFormat; - let pixels = || (0..500).flat_map(|y| (0..700).map(move |x| (x, y))); - for depth in [8, 16, 32] { - for angle in [3.0, -7.5, 33.0, 181.0] { - let mut sessions = [true, false].map(|delete| { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 700, "height": 500, "depth": depth, "background": "white"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let wave = |x: i32, y: i32, k: i32| ((x * 7 + y * 13 + k * 31) % 97) as f32 / 96.0; - let all = Rect::new(0, 0, 700, 500); - let rgba: Vec = pixels().flat_map(|(x, y)| [wave(x, y, 0), wave(x, y, 1), wave(x, y, 2), wave(y, x, 3)]).collect(); - let gray: Vec = pixels().map(|(x, y)| wave(y, x, 4)).collect(); - let l = doc.layer_mut(active.unwrap()).unwrap(); - l.surface_mut().unwrap().write_region(all, &rgba); - let mut mask = photocraft_doc::LayerMask::reveal_all(); - mask.surface.write_region(all, &gray); - l.mask = Some(mask); - let bg = doc.background_mut().unwrap().surface_mut().unwrap(); - bg.write_region(all, &pixels().flat_map(|(x, y)| [wave(x, y, 5), wave(x, y, 6), wave(x, y, 7), 1.0]).collect::>()); - let fmt = PixelFormat::new(ColorMode::Grayscale, doc.pixel_format().sample, false); - let mut ch = Surface::new(fmt); - ch.write_region(all, &gray); - doc.channels.push(photocraft_doc::AlphaChannel::new("Alpha 1", ch)); - Ok(()) - }) - .unwrap(); - let p = json!({"x": 150, "y": 120, "width": 330, "height": 290, "angle": angle, "deleteCroppedPixels": delete}); - s.execute("image.crop", p).unwrap(); - s - }); - let [deleted, kept] = &mut sessions; - let (a, b) = (doc(deleted), doc(kept)); - assert_eq!(a.size, b.size, "{depth} {angle}"); - let canvas = a.bounds(); - for (la, lb) in a.layers.iter().zip(&b.layers) { - let (sa, sb) = (la.surface().unwrap(), lb.surface().unwrap()); - assert!(sa.to_interleaved(canvas) == sb.to_interleaved(canvas), "{depth} {angle}: layer {}", la.name); - if let (Some(ma), Some(mb)) = (&la.mask, &lb.mask) { - assert!(ma.surface.to_interleaved(canvas) == mb.surface.to_interleaved(canvas), "{depth} {angle}: mask of {}", la.name); - } - } - assert!(a.channels[0].surface.to_interleaved(canvas) == b.channels[0].surface.to_interleaved(canvas), "{depth} {angle}: alpha channel"); - // Deleting keeps nothing past the canvas. - let layer = a.layers[1].surface().unwrap(); - assert!(canvas.contains_rect(&layer.content_bounds()), "{depth} {angle}: {:?}", layer.content_bounds()); - } - } - } - - /// Angle 0 (or a whole turn) is the plain crop: no resampling, the same document. - #[test] - fn crop_at_angle_zero_is_the_plain_crop() { - let mut plain = marked("rgb", 16); - plain.execute("image.crop", json!({"x": 3, "y": 2, "width": 30, "height": 10})).unwrap(); - for angle in [json!(0), json!(0.0), json!(360), json!(-720), json!(null)] { - let mut s = marked("rgb", 16); - let r = s.execute("image.crop", json!({"x": 3, "y": 2, "width": 30, "height": 10, "angle": angle})).unwrap(); - assert!(r.get("angle").is_none(), "{angle}: {r}"); - assert_eq!(doc(&s).size, Size::new(30, 10)); - for l in 0..2 { - for y in 0..10 { - for x in 0..30 { - assert_eq!(layer_rgba(&s, l, x, y), layer_rgba(&plain, l, x, y), "{angle} layer {l} ({x}, {y})"); - } - } - } - } - } - - /// Bad angles fail cleanly, before anything changes. - #[test] - fn crop_angle_rejects_bad_values_without_changing_the_document() { - let bad = [ - json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": "NaN"}), - json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": "12"}), - json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": [1]}), - json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": true}), - json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": 1e308}), - json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": -3601}), - json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": f64::MAX}), - // An angle needs the frame: a selection crop has none. - json!({"angle": 10}), - json!({"x": 0, "y": 0, "width": 0, "height": 10, "angle": 10}), - json!({"x": 0, "y": 0, "width": 300_001, "height": 10, "angle": 10}), - json!({"x": i32::MAX - 5, "y": 0, "width": 10, "height": 10, "angle": 10}), - ]; - for p in bad { - let mut s = marked("rgb", 8); - s.execute("select.all", json!({})).unwrap(); - let before = doc(&s).clone(); - let past = s.active().unwrap().history.past_len(); - assert!(s.execute("image.crop", p.clone()).is_err(), "{p}"); - assert_eq!(doc(&s).size, before.size, "{p}"); - assert_eq!(s.active().unwrap().history.past_len(), past, "{p}"); - } - // Far-off but representable frames turn and crop without panicking. - for (x, y) in [(-1_000_000, 0), (0, 1_000_000), (i32::MIN / 4, i32::MAX / 4)] { - let mut s = marked("rgb", 8); - s.execute("image.crop", json!({"x": x, "y": y, "width": 4, "height": 3, "angle": 33.3})).unwrap(); - assert_eq!(doc(&s).size, Size::new(4, 3)); - } - } - - #[test] - fn crop_refuses_a_canvas_side_past_the_new_document_limit() { - // #960: an unbounded explicit crop left a canvas that a later Trim or Duplicate Merged - // could only abort on allocating. - for (w, h) in [(100_000_000, 100_000_000), (300_001, 10), (10, 300_001)] { - let mut s = session(); - let (size, past) = (doc(&s).size, s.active().unwrap().history.past_len()); - let err = s.execute("image.crop", json!({"x": 0, "y": 0, "width": w, "height": h})).unwrap_err(); - assert!(err.to_string().contains("300000 px limit"), "{w} x {h}: {err}"); - assert_eq!((doc(&s).size, s.active().unwrap().history.past_len()), (size, past), "{w} x {h}: nothing changed"); - } - // At the limit it still extends the canvas (the tiles stay lazy). - let mut s = session(); - s.execute("image.crop", json!({"x": 0, "y": 0, "width": 300_000, "height": 2})).unwrap(); - assert_eq!(doc(&s).size, Size::new(300_000, 2)); - } - - /// #2443: the Crop tool's W x H x Resolution crops, resamples the cropped area to exactly the - /// target size and sets the resolution, in one undo step, at 8 and 16 bits. - #[test] - fn crop_to_a_target_size_and_resolution_is_one_step() { - for depth in [8, 16] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(100, 100, 200, 225), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - let past = s.active().unwrap().history.past_len(); - // 4 x 5 in at 300 ppi from a 100 x 125 px frame. - let r = s - .execute("image.crop", json!({"x": 100, "y": 100, "width": 100, "height": 125, "targetWidth": 1200, "targetHeight": 1500, "resolution": 300})) - .unwrap(); - assert_eq!((r["documentWidth"].as_u64(), r["documentHeight"].as_u64()), (Some(1200), Some(1500)), "{depth}: {r}"); - assert_eq!(r["resolution"].as_f64(), Some(300.0), "{depth}"); - let d = doc(&s); - assert_eq!(d.size, Size::new(1200, 1500), "{depth}"); - assert_eq!(d.resolution_dpi, 300.0, "{depth}"); - assert_eq!(d.layers[0].surface().unwrap().format().sample, if depth == 8 { SampleType::U8 } else { SampleType::U16 }); - // The red frame filled the crop; it fills the result. - let red = d.layers[1].surface().unwrap(); - for (x, y) in [(0, 0), (600, 750), (1199, 1499)] { - assert_eq!(red.pixel(x, y), vec![1.0, 0.0, 0.0, 1.0], "{depth}: ({x}, {y})"); - } - assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{depth}: one history step"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(400, 300), 72.0), "{depth}: undo restores the original"); - } - } - - #[test] - fn crop_target_resamples_after_a_turned_crop_and_resolution_alone_keeps_the_pixels() { - let mut s = session(); - let past = s.active().unwrap().history.past_len(); - s.execute("image.crop", json!({"x": 10, "y": 0, "width": 10, "height": 20, "angle": 90, "targetWidth": 30, "targetHeight": 60, "resample": "nearest"})) - .unwrap(); - assert_eq!(doc(&s).size, Size::new(30, 60)); - assert_eq!(s.active().unwrap().history.past_len(), past + 1, "rotate, crop and resample: one step"); - let mut s = session(); - s.execute("image.crop", json!({"x": 2, "y": 3, "width": 30, "height": 10, "resolution": 150})).unwrap(); - assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(30, 10), 150.0)); - } - - /// #7722: a W x H crop of an Indexed Color document resamples like Image Size (#6019), with - /// Nearest Neighbor, so no pixel gets a blend that isn't in the colour table. - #[test] - fn crop_target_resamples_indexed_color_with_nearest_neighbor() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 2, "height": 1})).unwrap(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - s.execute("select.rect", json!({"x": 1, "y": 0, "width": 1, "height": 1})).unwrap(); - s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("image.mode.indexedColor", json!({})).unwrap(); - for resample in [None, Some("bicubic"), Some("automatic"), Some("bilinear"), Some("lanczos")] { - let mut p = json!({"x": 0, "y": 0, "width": 2, "height": 1, "targetWidth": 8, "targetHeight": 1}); - if let Some(r) = resample { - p["resample"] = json!(r); - } - s.execute("image.crop", p).unwrap(); - let surf = doc(&s).layers[0].surface().unwrap(); - for x in 0..8 { - let px = surf.pixel(x, 0); - assert!(px[..3] == [1.0, 0.0, 0.0] || px[..3] == [0.0, 0.0, 1.0], "{resample:?}: no blended colour at x {x}: {px:?}"); - } - s.execute("history.undo", json!({})).unwrap(); - } - } - - #[test] - fn crop_target_accepts_whole_number_floats() { - // `json.dumps(100.0)` and many other JSON writers send whole numbers as floats. - let mut s = session(); - s.execute("image.crop", json!({"x": 0, "y": 0, "width": 20, "height": 10, "targetWidth": 40.0, "targetHeight": 20.0})).unwrap(); - assert_eq!(doc(&s).size, Size::new(40, 20)); - } - - #[test] - fn crop_target_rejects_bad_params_without_changing_the_document() { - let rect = json!({"x": 0, "y": 0, "width": 10, "height": 10}); - let bad_params = [ - json!({"targetWidth": 100}), - json!({"targetHeight": 100}), - json!({"targetWidth": 0, "targetHeight": 10}), - json!({"targetWidth": -5, "targetHeight": 10}), - json!({"targetWidth": 10.5, "targetHeight": 10}), - json!({"targetWidth": -1.0, "targetHeight": 10}), - json!({"targetWidth": 0.0, "targetHeight": 10}), - json!({"targetWidth": 1e39, "targetHeight": 10}), - json!({"targetWidth": 300_001.0, "targetHeight": 10}), - json!({"targetWidth": "10", "targetHeight": 10}), - json!({"targetWidth": 300_001, "targetHeight": 10}), - json!({"targetWidth": 4_294_967_306_u64, "targetHeight": 10}), - json!({"targetWidth": 300_000, "targetHeight": 300_000}), - json!({"targetWidth": 10, "targetHeight": 10, "resample": "none"}), - json!({"targetWidth": 10, "targetHeight": 10, "resample": 3}), - json!({"resolution": 0}), - json!({"resolution": -72}), - json!({"resolution": 1e9}), - json!({"resolution": "300"}), - ]; - for extra in bad_params { - let mut s = session(); - let (size, dpi, past) = (doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len()); - let mut p = rect.clone(); - if let (Some(o), Some(e)) = (p.as_object_mut(), extra.as_object()) { - o.extend(e.clone()); - } - assert!(s.execute("image.crop", p.clone()).is_err(), "{p}"); - assert_eq!((doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len()), (size, dpi, past), "{p}: nothing changed"); - } - } - - #[test] - fn trim_based_on_top_left_colour() { - let mut s = session(); - s.edit("no fx", |doc, _| { - doc.layers[1].effects.items.clear(); - Ok(()) - }) - .unwrap(); - s.execute("image.trim", json!({"basedOn": "topLeft"})).unwrap(); - assert_eq!(doc(&s).size, Size::new(10, 10)); - } - - #[test] - fn thirty_two_bit_holds_linear_light() { - // Photoshop 27.11: an 8-bit sRGB grey 128 becomes 0.2159 in 32 bits (and 32 → 0.0144), - // and comes back unchanged; alpha keeps its value. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 4, "height": 1, "background": "white"})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("paint", |doc, active| { - let l = doc.layer_mut(active.unwrap()).unwrap(); - l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 2, 1), &[128.0 / 255.0, 32.0 / 255.0, 1.0, 0.5]); - Ok(()) - }) - .unwrap(); - s.execute("image.mode.bits32", json!({})).unwrap(); - let px = doc(&s).layers[1].surface().unwrap().pixel(0, 0); - for (got, want) in px.iter().zip([0.2159, 0.0144, 1.0, 128.0 / 255.0]) { - assert!((got - want).abs() < 2e-4, "{px:?}"); - } - s.execute("image.mode.bits8", json!({})).unwrap(); - let px = doc(&s).layers[1].surface().unwrap().pixel(0, 0); - for (got, want) in px.iter().zip([128.0 / 255.0, 32.0 / 255.0, 1.0, 128.0 / 255.0]) { - assert!((got - want).abs() < 0.6 / 255.0, "{px:?}"); - } - } - - #[test] - fn grayscale_conversion_matches_photoshop() { - // Photoshop 27.11, default Color Settings (working gray Dot Gain 20 %): Image > Mode > - // Grayscale turns sRGB 64 / 128 / 192 grey and pure red into 46 / 105 / 177 / 107. - let mut s = Session::new(); - s.execute("file.new", json!({"width": 4, "height": 1, "background": "white"})).unwrap(); - s.edit("paint", |doc, _| { - let l = doc.layers.first_mut().unwrap(); - let surf = l.surface_mut().unwrap(); - for (x, c) in [[64.0, 64.0, 64.0], [128.0, 128.0, 128.0], [192.0, 192.0, 192.0], [255.0, 0.0, 0.0]].iter().enumerate() { - surf.fill_rect(Rect::new(x as i32, 0, x as i32 + 1, 1), &[c[0] / 255.0, c[1] / 255.0, c[2] / 255.0, 1.0]); - } - Ok(()) - }) - .unwrap(); - s.execute("image.mode.grayscale", json!({})).unwrap(); - let surf = doc(&s).layers[0].surface().unwrap(); - for (x, want) in [46.0, 105.0, 177.0, 107.0].iter().enumerate() { - let got = surf.pixel(x as i32, 0)[0] * 255.0; - assert!((got - want).abs() <= 1.5, "pixel {x}: {got} vs {want}"); - } - } - - #[test] - fn mode_and_depth_conversions() { - let mut s = session(); - s.execute("image.mode.grayscale", json!({})).unwrap(); - assert_eq!(doc(&s).mode, ColorMode::Grayscale); - assert_eq!(doc(&s).layers[1].surface().unwrap().format().mode, ColorMode::Grayscale); - s.execute("image.mode.bits16", json!({})).unwrap(); - assert_eq!(doc(&s).depth, SampleType::U16); - assert_eq!(doc(&s).layers[1].surface().unwrap().format().sample, SampleType::U16); - assert_eq!(doc(&s).layers[1].mask.as_ref().unwrap().surface.format().sample, SampleType::U16); - s.execute("image.mode.cmyk", json!({})).unwrap(); - s.execute("image.mode.bits32", json!({})).unwrap(); - s.execute("image.mode.lab", json!({})).unwrap(); - s.execute("image.mode.rgb", json!({})).unwrap(); - s.execute("image.mode.bits8", json!({})).unwrap(); - let d = doc(&s); - assert_eq!((d.mode, d.depth), (ColorMode::Rgb, SampleType::U8)); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(doc(&s).depth, SampleType::F32); - let revision = s.active().unwrap().revision; - s.execute("image.mode.bits32", json!({})).unwrap(); - assert_eq!(s.active().unwrap().revision, revision, "an unchanged bit depth must preserve the history branch"); - assert!(s.redo(), "selecting the current depth must not discard the undone conversion"); - assert_eq!(doc(&s).depth, SampleType::U8); - } - - /// Duplicate › Merged Layers Only gives one locked Background when the source has one and a - /// plain "Layer 1" (keeping transparency) when it doesn't, as Photoshop does. - #[test] - fn merged_duplicate_is_a_background_only_when_the_source_has_one() { - let mut s = session(); - s.execute("image.duplicate", json!({"mergedOnly": true})).unwrap(); - let d = doc(&s); - assert!(d.is_background(d.layers[0].id), "source has a Background: the merged copy is one"); - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap(); - s.execute("image.duplicate", json!({"mergedOnly": true})).unwrap(); - let d = doc(&s); - assert!(d.background().is_none(), "transparent source: no Background in the copy"); - assert_eq!(d.layers[0].name, "Layer 1"); - } - - #[test] - fn duplicate_document() { - let mut s = session(); - let r = s.execute("image.duplicate", json!({"mergedOnly": true})).unwrap(); - assert_eq!(r["document"], json!(1)); - assert_eq!(s.documents().len(), 2); - assert_eq!(doc(&s).layers.len(), 1); - assert!(doc(&s).name.ends_with("copy")); - } -} +mod tests; diff --git a/crates/engine/src/image_cmds/tests.rs b/crates/engine/src/image_cmds/tests.rs new file mode 100644 index 0000000000..3b9dc7f03f --- /dev/null +++ b/crates/engine/src/image_cmds/tests.rs @@ -0,0 +1,969 @@ +use super::*; + +#[test] +fn crop_rejects_rectangles_that_would_wrap() { + let mut s = session(); + // 2^32 + 100 wrapped to `x = 100` through the narrowing casts: a crop rectangle + // somewhere unrelated to the numbers passed. + let err = s.execute("image.crop", json!({"x": 4_294_967_396_i64, "y": 0, "width": 10, "height": 10})).unwrap_err(); + assert!(err.to_string().contains("32-bit"), "{err}"); + // In-range rectangles past the canvas still work (clamped by the crop itself). + s.execute("image.crop", json!({"x": -10, "y": -10, "width": 1000, "height": 1000})).unwrap(); +} + +/// A crop whose translation to the origin can't be represented in i32 is rejected before +/// anything changes (#959): `-i32::MIN` overflowed the negation in `crop_doc`, `x + width` +/// past i32::MAX silently shortened the crop, and an origin one past i32::MIN moved the +/// layer pixels beyond i32::MAX (a length-mismatch panic while translating surfaces). +#[test] +fn crop_rejects_origins_that_cannot_move_to_zero() { + const MIN: i64 = i32::MIN as i64; + const MAX: i64 = i32::MAX as i64; + let cases = [ + json!({"x": MIN, "y": 0, "width": 1, "height": 1}), + json!({"x": 0, "y": MIN, "width": 1, "height": 1}), + json!({"x": MIN, "y": MIN, "width": 1, "height": 1}), + json!({"x": MIN, "y": 0, "width": 1, "height": 1, "deleteCroppedPixels": false}), + json!({"x": MAX - 5, "y": 0, "width": 10, "height": 1}), + json!({"x": 0, "y": MAX - 5, "width": 1, "height": 10}), + json!({"x": MIN + 1, "y": 0, "width": 1, "height": 1, "deleteCroppedPixels": false}), + json!({"x": 0, "y": MIN + 1, "width": 1, "height": 1, "deleteCroppedPixels": false}), + ]; + for p in cases { + let mut s = session(); + let before = s.active().unwrap().doc.clone(); + let (rev, steps) = (s.active().unwrap().revision, s.active().unwrap().history.entries().len()); + let err = s.execute("image.crop", p.clone()).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "{p}: {err}"); + assert!(err.to_string().contains("32-bit"), "{p}: {err}"); + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &before), "{p}: document changed"); + assert_eq!(st.doc.size, Size::new(40, 20), "{p}"); + assert_eq!(st.doc.layers[1].surface().unwrap().content_bounds(), Rect::new(10, 5, 20, 15), "{p}"); + assert_eq!((st.revision, st.history.entries().len()), (rev, steps), "{p}: history step recorded"); + } + // Control: a legal negative origin past the canvas still crops (and extends) the canvas. + let mut s = session(); + s.execute("image.crop", json!({"x": -10, "y": -5, "width": 60, "height": 30})).unwrap(); + assert_eq!(doc(&s).size, Size::new(60, 30)); + assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 10), vec![1.0, 0.0, 0.0, 1.0]); + // A far-off crop that deletes the (non-overlapping) pixels has nothing left to move. + let mut s = session(); + s.execute("image.crop", json!({"x": MIN + 1, "y": 0, "width": 1, "height": 1})).unwrap(); + assert_eq!(doc(&s).size, Size::new(1, 1)); +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 5, 20, 15), &[1.0, 0.0, 0.0, 1.0]); + l.mask = Some(photocraft_doc::LayerMask::reveal_all()); + l.effects.items.push(Effect::default_drop_shadow()); + Ok(()) + }) + .unwrap(); + s +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +/// Document-wide conversions must move every stored video frame, not just the displayed one (#4956). +#[test] +fn crop_moves_stored_video_frames() { + let mut s = session(); + s.edit("video", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + let frame = l.surface().unwrap().clone(); + let mut v = photocraft_doc::VideoData::new(vec![frame.clone(), frame.clone()], 24.0); + v.original_frames = Some(vec![frame.clone(), frame]); + l.video = Some(v); + Ok(()) + }) + .unwrap(); + s.execute("image.crop", json!({"x": -10, "y": -5, "width": 60, "height": 30})).unwrap(); + let v = doc(&s).layers[1].video.as_ref().unwrap(); + let red = vec![1.0, 0.0, 0.0, 1.0]; + for frame in v.frames.iter().chain(v.original_frames.iter().flatten()) { + assert_eq!(frame.pixel(20, 10), red); + assert_eq!(frame.pixel(5, 5)[3], 0.0); + } +} + +/// Delete Cropped Pixels on a shrinking crop deletes the cropped area from every stored video +/// frame (and the original footage), not just the displayed one (#4956). +#[test] +fn delete_cropped_pixels_crops_stored_video_frames() { + let mut s = session(); + s.edit("video", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + let red = l.surface().unwrap().clone(); + let mut blue = red.clone(); + blue.fill_rect(Rect::new(0, 0, 40, 20), &[0.0, 0.0, 1.0, 1.0]); + let mut v = photocraft_doc::VideoData::new(vec![red.clone(), blue.clone()], 24.0); + v.original_frames = Some(vec![red, blue]); + l.video = Some(v); + Ok(()) + }) + .unwrap(); + s.execute("image.crop", json!({"x": 15, "y": 0, "width": 25, "height": 20, "deleteCroppedPixels": true})).unwrap(); + assert_eq!(doc(&s).size, Size::new(25, 20)); + let v = doc(&s).layers[1].video.as_ref().unwrap(); + let originals = v.original_frames.as_ref().unwrap(); + assert_eq!((v.frames.len(), originals.len()), (2, 2)); + for frames in [&v.frames, originals] { + // The red square (10..20, 5..15) keeps only its right half; the full blue frame + // keeps exactly the 25×20 crop. + assert_eq!(frames[0].content_bounds(), Rect::new(0, 5, 5, 15)); + assert_eq!(frames[0].pixel(2, 10), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(frames[1].content_bounds(), Rect::new(0, 0, 25, 20)); + assert_eq!(frames[1].pixel(24, 19), vec![0.0, 0.0, 1.0, 1.0]); + } +} + +/// Resample on with only a new resolution keeps the print size, as Photoshop's Image Size +/// does (an action's `imageSize` with `Rslt` alone); without `keepPrintSize` only the +/// resolution changes. +#[test] +fn image_size_keep_print_size_resamples_to_the_resolution() { + let mut s = session(); + s.execute("image.imageSize", json!({"resolution": 144, "resample": "bicubic"})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(40, 20), 144.0)); + s.execute("image.imageSize", json!({"resolution": 288, "resample": "bicubic", "keepPrintSize": true})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(80, 40), 288.0)); + // An explicit side still wins. + s.execute("image.imageSize", json!({"width": 20, "resolution": 72, "resample": "bicubic", "keepPrintSize": true})).unwrap(); + assert_eq!(doc(&s).size, Size::new(20, 10)); +} + +#[test] +fn image_size_scales_everything() { + for resample in ["bicubic", "bicubicSmoother", "bicubicSharper", "bicubicAutomatic", "automatic", "bilinear", "nearest", "lanczos", "preserveDetails"] { + let mut s = session(); + s.execute("image.imageSize", json!({"width": 80, "resample": resample})).unwrap(); + let d = doc(&s); + assert_eq!(d.size, Size::new(80, 40), "{resample}"); + let l = &d.layers[1]; + let b = l.surface().unwrap().content_bounds(); + assert!((b.x0 - 20).abs() <= 1 && (b.x1 - 40).abs() <= 1, "{resample} {b:?}"); + let Effect::DropShadow(sh) = &l.effects.items[0] else { panic!() }; + assert_eq!(sh.distance, 10.0); + assert_eq!(l.mask.as_ref().unwrap().surface.default_pixel(), vec![1.0]); + } +} + +/// #6019: Image Size on an Indexed Color document makes no colours the colour table doesn't have. +#[test] +fn image_size_resamples_indexed_color_with_nearest_neighbor() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.rect", json!({"x": 1, "y": 0, "width": 1, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + for resample in ["bicubic", "automatic", "bilinear", "lanczos", "preserveDetails"] { + s.execute("image.imageSize", json!({"width": 8, "resample": resample})).unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layers[0].surface().unwrap(); + for x in 0..8 { + let px = surf.pixel(x, 0); + assert!(px[..3] == [1.0, 0.0, 0.0] || px[..3] == [0.0, 0.0, 1.0], "{resample}: no blended colour at x {x}: {px:?}"); + } + s.execute("history.undo", json!({})).unwrap(); + } +} + +/// The canvas border stays opaque after Image Size (it used to fade into transparency, so a +/// Background or a 200 % export got a translucent frame), and a full selection stays full. +/// #1544: 64 x 48 to 300000 x 300000 (90 billion pixels) started allocating resampled bands +/// without a budget. It is refused before any allocation and the document is untouched; a +/// change of resolution only, and an ordinary resize, still work. +#[test] +fn image_size_refuses_a_raster_past_the_budget() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + let before = (doc(&s).size, s.active().unwrap().history.past_len()); + let err = s.execute("image.imageSize", json!({"width": 300_000, "height": 300_000})).unwrap_err().to_string(); + assert!(err.contains("megapixels"), "{err}"); + assert_eq!((doc(&s).size, s.active().unwrap().history.past_len()), before); + s.execute("image.imageSize", json!({"width": 300_000, "height": 300_000, "resample": "none", "resolution": 300})).unwrap(); + s.execute("image.imageSize", json!({"width": 128, "height": 96})).unwrap(); + assert_eq!(doc(&s).size, Size::new(128, 96)); +} + +#[test] +fn image_size_keeps_canvas_edges_opaque() { + for depth in [8, 16, 32] { + for (w, resample) in [ + (60, "bicubic"), + (41, "lanczos"), + (15, "bilinear"), + (77, "preserveDetails"), + (21, "bicubicSharper"), + (47, "automatic"), + (9, "bicubicAutomatic"), + ] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 30, "height": 20, "depth": depth, "background": "#336699"})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("image.imageSize", json!({"width": w, "resample": resample})).unwrap(); + let d = doc(&s); + let flat = photocraft_compose::flatten(d); + let (w, h) = (flat.rect.width() as usize, flat.rect.height() as usize); + let mid = flat.px[(h / 2) * w + w / 2]; + assert!((mid[3] - 1.0).abs() < 1e-3, "{depth} {resample}: {mid:?}"); + for p in &flat.px { + let off = p.iter().zip(mid).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(off < 0.01, "{depth} {resample} {w}: {p:?} vs {mid:?}"); + } + let sel = d.selection.as_ref().unwrap(); + let (x1, y1) = (d.size.width as i32 - 1, d.size.height as i32 - 1); + for (x, y) in [(0, 0), (x1, 0), (0, y1), (x1, y1)] { + assert!(sel.pixel(x, y)[0] > 0.99, "{depth} {resample}: selection at ({x},{y})"); + } + } + } +} + +#[test] +fn resolution_only_change() { + let mut s = session(); + let r = s.execute("image.imageSize", json!({"resolution": 300, "resample": "none", "width": 999})).unwrap(); + assert_eq!(doc(&s).size, Size::new(40, 20)); + assert_eq!(doc(&s).resolution_dpi, 300.0); + // #1815: the result is the size the document has, not the ignored request. + assert_eq!(r, json!({"width": 40, "height": 20})); +} + +/// Type keeps its pixel size across a resolution change: resampled 2x at twice the ppi it is +/// twice as tall (not 4x), with Resample off it stays, and a later re-render doesn't jump. +#[test] +fn image_size_with_a_new_resolution_scales_type_with_the_pixels_only() { + for (params, k) in [(json!({"width": 200, "height": 200, "resolution": 144}), 2), (json!({"resolution": 144, "resample": "none"}), 1)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + s.execute("type.create", json!({"x": 10, "y": 50, "text": "Hi", "size": 12})).unwrap(); + let height = |s: &Session| doc(s).layers.last().unwrap().surface().unwrap().content_bounds().height(); + let h0 = height(&s); + assert!(h0 > 4, "{h0}"); + s.execute("image.imageSize", params.clone()).unwrap(); + assert!(height(&s).abs_diff(h0 * k) <= 2, "{params}: {h0} -> {}", height(&s)); + let d = doc(&s); + let LayerContent::Text(t) = &d.layers.last().unwrap().content else { panic!("type layer") }; + let mut t = t.clone(); + crate::type_cmds::refresh(d, &mut t); + let after = t.cache.unwrap().content_bounds().height(); + assert!(after.abs_diff(h0 * k) <= 2, "{params}: re-rendered {h0} -> {after}"); + } +} + +#[test] +fn image_size_reports_the_size_it_applied() { + // #1815: every path reports the document's size afterwards, at every depth. + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth})).unwrap(); + let size = |s: &Session| json!({"width": doc(s).size.width, "height": doc(s).size.height}); + for p in [ + json!({"width": 999, "height": 777, "resample": "none", "resolution": 150}), + json!({"width": 32}), + json!({"height": 96, "resample": "nearest"}), + json!({"width": 96, "height": 72, "resample": "none"}), + json!({}), + ] { + let r = s.execute("image.imageSize", p.clone()).unwrap(); + assert_eq!(r, size(&s), "{depth}-bit {p}"); + } + // 64×48 → (none) → 32×24 → 128×96 (aspect kept) → (none) → unchanged. + assert_eq!(doc(&s).size, Size::new(128, 96), "{depth}-bit"); + } +} + +/// #1114: nearest neighbor reduction keeps source values without averaging. +#[test] +fn nearest_neighbor_reduction_keeps_source_values() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + s.execute("tools.setColors", json!({"foreground": "#000000", "background": "#ffffff"})).unwrap(); + for y in 0..8 { + for x in 0..8 { + if (x + y) % 2 == 0 { + s.execute("select.rect", json!({"x": x, "y": y, "width": 1, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"contents": "foreground"})).unwrap(); + } + } + } + s.execute("select.deselect", json!({})).unwrap(); + let st = s.active().unwrap(); + let before = st.doc.layers[0].surface().unwrap().rgba(0, 0); + assert!(before[0] < 0.01, "setup: (0,0) should be black, got {before:?}"); + s.execute("image.imageSize", json!({"width": 4, "height": 4, "resample": "nearest"})).unwrap(); + let st = s.active().unwrap(); + let surf = st.doc.layers[0].surface().unwrap(); + for (x, y) in [(0, 0), (1, 1), (2, 3)] { + let v = surf.rgba(x, y)[0]; + assert!(v.is_finite() && !(0.01..=0.99).contains(&v), "nearest produced an averaged value {v} at ({x},{y})"); + } +} + +#[test] +fn canvas_size_anchors_and_extends_background() { + let mut s = session(); + s.execute("image.canvasSize", json!({"width": 60, "height": 30, "anchor": "topLeft", "extensionColor": "#00ff00"})).unwrap(); + let d = doc(&s); + assert_eq!(d.size, Size::new(60, 30)); + assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(10, 5, 20, 15)); + let bg = d.layers[0].surface().unwrap(); + assert_eq!(bg.pixel(50, 25), vec![0.0, 1.0, 0.0, 1.0]); + assert_eq!(bg.pixel(5, 5), vec![1.0, 1.0, 1.0, 1.0]); + let mut s = session(); + s.execute("image.canvasSize", json!({"width": 20, "height": 10, "relative": true, "anchor": "center"})).unwrap(); + assert_eq!(doc(&s).layers[1].surface().unwrap().content_bounds(), Rect::new(20, 10, 30, 20)); +} + +#[test] +fn canvas_size_anchor_offsets_and_rejects_unlisted() { + // 64x48 -> 100x80: dx spans 36 and dy spans 32, so each anchor factor lands on a known + // offset. All nine documented values must anchor exactly where they do today (#2946). + let expected = [ + ("topLeft", [0, 0]), + ("top", [18, 0]), + ("topRight", [36, 0]), + ("left", [0, 16]), + ("center", [18, 16]), + ("right", [36, 16]), + ("bottomLeft", [0, 32]), + ("bottom", [18, 32]), + ("bottomRight", [36, 32]), + ]; + for (anchor, off) in expected { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); + let r = s.execute("image.canvasSize", json!({"width": 100, "height": 80, "anchor": anchor})).unwrap(); + assert_eq!(r["offset"], json!(off), "anchor {anchor}"); + } + // An omitted anchor still defaults to center. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); + assert_eq!(s.execute("image.canvasSize", json!({"width": 100, "height": 80})).unwrap()["offset"], json!([18, 16])); + // A misspelling or unknown value is a BadParams error naming `anchor`, never an anchor + // between two of the nine (the old independent-axis matching produced top-centre etc.). + for anchor in ["topleft", "TopLeft", "TOPLEFT", "bottomleft", "bottomright", "middle", "", "NOPE"] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); + let err = s.execute("image.canvasSize", json!({"width": 100, "height": 80, "anchor": anchor})).unwrap_err(); + assert!(matches!(err, EngineError::BadParams { .. }), "anchor {anchor:?} must be rejected, got {err:?}"); + assert!(err.to_string().contains("anchor"), "the error for {anchor:?} must name `anchor`: {err}"); + } +} + +#[test] +fn crop_to_selection_and_trim() { + let mut s = session(); + assert!(s.execute("image.crop", json!({})).is_err(), "no selection, no rect"); + s.execute("select.rect", json!({"x": 5, "y": 2, "width": 20, "height": 10})).unwrap(); + s.execute("image.crop", json!({})).unwrap(); + let d = doc(&s); + assert_eq!(d.size, Size::new(20, 10)); + assert!(d.selection.is_none()); + assert_eq!(d.layers[1].surface().unwrap().content_bounds(), Rect::new(5, 3, 15, 10)); + // Trim transparent: hide the background, trim to the red square. + let mut s = session(); + s.execute("layer.setProps", json!({"layer": doc(&s).layers[0].id.0, "visible": false})).unwrap(); + s.execute("image.trim", json!({"basedOn": "transparent"})).unwrap(); + // The red square (10×10) plus its drop shadow (distance 5, size 5). + let size = doc(&s).size; + assert!(size.width > 10 && size.width < 30 && size.height > 10 && size.height < 25, "{size:?}"); +} + +#[test] +fn crop_to_explicit_rect_can_extend_canvas() { + let mut s = session(); + s.execute("image.crop", json!({"x": 10, "y": 5, "width": 10, "height": 10})).unwrap(); + assert_eq!(doc(&s).size, Size::new(10, 10)); + assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(0, 0), vec![1.0, 0.0, 0.0, 1.0]); + let mut s = session(); + s.execute("image.crop", json!({"x": -10, "y": 0, "width": 60, "height": 20})).unwrap(); + assert_eq!(doc(&s).size, Size::new(60, 20)); + assert_eq!(doc(&s).layers[1].surface().unwrap().pixel(20, 5), vec![1.0, 0.0, 0.0, 1.0]); +} + +#[test] +fn crop_extension_fills_the_background_with_the_background_colour() { + let mut shrink = Session::new(); + shrink.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); + shrink.execute("image.crop", json!({"x": 2, "y": 0, "width": 12, "height": 16})).unwrap(); + let layer = &doc(&shrink).layers[0]; + assert_eq!(layer.name, "Background", "a shrink-only crop keeps the Background"); + assert!(layer.locks.transparency && layer.locks.position); + + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); + s.tools.background = [0.0, 1.0, 0.0, 1.0]; + s.execute("image.crop", json!({"x": -4, "y": 0, "width": 20, "height": 16})).unwrap(); + let layer = &doc(&s).layers[0]; + assert_eq!(layer.name, "Background", "an extending crop keeps the Background (#3081)"); + assert!(layer.locks.transparency && layer.locks.position); + assert_eq!(layer.surface().unwrap().rgba(1, 8), [0.0, 1.0, 0.0, 1.0], "the added border takes the background colour"); + assert_eq!(layer.surface().unwrap().rgba(8, 8), [1.0, 0.0, 0.0, 1.0], "the original pixels stay"); + + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + let layer = &doc(&s).layers[0]; + assert_eq!(layer.surface().unwrap().rgba(1, 8), [0.0, 0.0, 1.0, 1.0], "Fill paints the extended border"); + assert_eq!(layer.surface().unwrap().rgba(8, 8), [0.0, 0.0, 1.0, 1.0]); + + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + let layer = &doc(&s).layers[0]; + assert_eq!(doc(&s).size, Size::new(16, 16)); + assert_eq!(layer.surface().unwrap().rgba(8, 8), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(layer.surface().unwrap().content_bounds(), Rect::new(0, 0, 16, 16), "undo removes the filled border"); + + // A normal layer gets transparent pixels in the added area. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap(); + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + s.execute("image.crop", json!({"x": -4, "y": 0, "width": 20, "height": 16})).unwrap(); + assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(1, 8), [0.0; 4]); +} + +/// Delete Cropped Pixels deletes pixel-layer data only: type and smart objects keep what lies +/// outside the frame, so moving them later doesn't show them cut at the old edge. +#[test] +fn delete_cropped_pixels_keeps_type_and_smart_objects_whole() { + let mut s = session(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("type.create", json!({"x": 10, "y": 15, "text": "Hi", "size": 12})).unwrap(); + let bounds = |s: &Session| -> Vec { doc(s).layers[1..].iter().map(|l| l.surface().unwrap().content_bounds()).collect() }; + let before = bounds(&s); + assert!(before.iter().all(|b| b.x0 < 15 && b.x1 > 15), "both cross the crop edge: {before:?}"); + s.execute("image.crop", json!({"x": 15, "y": 0, "width": 25, "height": 20})).unwrap(); + assert!(matches!(doc(&s).layers[1].content, LayerContent::Smart(_)) && matches!(doc(&s).layers[2].content, LayerContent::Text(_))); + assert_eq!(bounds(&s), before.iter().map(|b| b.translate(-15, 0)).collect::>()); +} + +/// A turned crop deleting pixels keeps type and smart objects whole too, also a smart object +/// whose source is unavailable (the rotation can't re-render it, so it keeps its cache): each +/// ends up exactly as the same turned crop with Delete Cropped Pixels off leaves it. +#[test] +fn turned_crop_deleting_pixels_keeps_type_and_smart_objects_whole() { + let [deleted, kept] = [true, false].map(|delete| { + let mut s = session(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.edit("unlink", |doc, active| { + if let LayerContent::Smart(sm) = &mut doc.layer_mut(active.unwrap()).unwrap().content { + sm.source = photocraft_doc::SmartSource::Linked { path: "missing-photocraft-test-source.psd".into() }; + } + Ok(()) + }) + .unwrap(); + s.execute("type.create", json!({"x": 10, "y": 15, "text": "Hi", "size": 12})).unwrap(); + s.execute("image.crop", json!({"x": 20, "y": 0, "width": 20, "height": 20, "angle": 2.0, "deleteCroppedPixels": delete})).unwrap(); + s + }); + let (a, b) = (doc(&deleted), doc(&kept)); + assert!(matches!(a.layers[1].content, LayerContent::Smart(_)) && matches!(a.layers[2].content, LayerContent::Text(_))); + for i in [1, 2] { + let (sa, sb) = (a.layers[i].surface().unwrap(), b.layers[i].surface().unwrap()); + let r = sb.content_bounds(); + assert!(r.x0 < 0, "layer {i} reaches past the crop's left edge: {r:?}"); + assert_eq!(sa.content_bounds(), r, "layer {i}"); + assert_eq!(sa.read_region(r), sb.read_region(r), "layer {i}"); + } +} + +/// The Background keeps the pixels a crop with Delete Cropped Pixels off hid: extending the +/// canvas over them again (Reveal All, Canvas Size) shows them rather than painting them over +/// with the background colour (#7086). +#[test] +fn extending_the_canvas_keeps_the_backgrounds_hidden_pixels() { + for depth in [8, 16, 32] { + let hidden = |s: &mut Session| { + s.execute("file.new", json!({"width": 100, "height": 100, "depth": depth, "background": "white"})).unwrap(); + s.edit("paint", |doc, _| { + let bg = doc.background_mut().unwrap(); + bg.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 50, 100), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("image.crop", json!({"x": 50, "y": 0, "width": 50, "height": 100, "deleteCroppedPixels": false})).unwrap(); + s.tools.background = [0.0, 0.0, 0.0, 1.0]; + }; + let mut s = Session::new(); + hidden(&mut s); + s.execute("image.revealAll", json!({})).unwrap(); + let surf = doc(&s).background().unwrap().surface().unwrap(); + assert_eq!(doc(&s).size, Size::new(100, 100), "{depth}-bit"); + assert_eq!(surf.rgba(10, 50), [1.0, 0.0, 0.0, 1.0], "{depth}-bit: Reveal All shows the hidden red half"); + assert_eq!(surf.rgba(80, 50), [1.0, 1.0, 1.0, 1.0], "{depth}-bit"); + + // Canvas Size wider than the hidden pixels: they show, the rest takes the colour. + let mut s = Session::new(); + hidden(&mut s); + s.execute("image.canvasSize", json!({"width": 120, "height": 100, "anchor": "right"})).unwrap(); + let surf = doc(&s).background().unwrap().surface().unwrap(); + assert_eq!(surf.rgba(5, 50), [0.0, 0.0, 0.0, 1.0], "{depth}-bit: past the hidden pixels the background colour"); + assert_eq!(surf.rgba(30, 50), [1.0, 0.0, 0.0, 1.0], "{depth}-bit: Canvas Size shows the hidden red half"); + assert_eq!(surf.rgba(100, 50), [1.0, 1.0, 1.0, 1.0], "{depth}-bit"); + } +} + +/// A Background without an alpha channel (a Grayscale PSD import) has no hidden pixels to tell +/// from empty ones: the added area takes the colour, the kept area stays (#7086). +#[test] +fn an_alpha_less_background_extension_takes_the_colour() { + let mut surf = Surface::new(photocraft_color::PixelFormat::GRAY8); + surf.fill_rect(Rect::new(-50, 0, 100, 100), &[0.6]); + let kept = surf.pixel(50, 50); + fill_background_extension(&mut surf, Rect::new(-60, 0, 100, 100), Rect::new(0, 0, 100, 100), &[0.0]); + assert_eq!(surf.pixel(-55, 50), vec![0.0], "past the old pixels the colour"); + assert_eq!(surf.pixel(-30, 50), vec![0.0], "no alpha: the added area takes the colour"); + assert_eq!(surf.pixel(50, 50), kept, "the kept area is unchanged"); +} + +/// A document (`mode`, `depth`) with a white Background and a layer holding a red pixel at +/// (12, 8) and a blue one at (30, 3). +fn marked(mode: &str, depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + for (x, y, c) in [(12, 8, "#ff0000"), (30, 3, "#0000ff")] { + s.execute("select.rect", json!({"x": x, "y": y, "width": 1, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"color": c})).unwrap(); + } + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn layer_rgba(s: &Session, layer: usize, x: i32, y: i32) -> [f32; 4] { + doc(s).layers[layer].surface().unwrap().rgba(x, y) +} + +/// #1792: a frame turned 90° clockwise crops what Image Rotation › Arbitrary 90° CCW and a +/// plain crop give, in one undo step that restores the document, at 8, 16 and 32 bits. +#[test] +fn crop_at_90_degrees_is_rotate_then_crop_in_one_step() { + for depth in [8, 16, 32] { + let mut s = marked("rgb", depth); + let before = doc(&s).clone(); + let past = s.active().unwrap().history.past_len(); + // The 10 × 20 frame at (10, 0), turned 90° about (15, 10), covers x 5..25, y 5..15. + let r = s.execute("image.crop", json!({"x": 10, "y": 0, "width": 10, "height": 20, "angle": 90})).unwrap(); + assert_eq!(r["angle"], json!(90.0), "{depth}"); + assert_eq!(doc(&s).size, Size::new(10, 20), "{depth}"); + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{depth}: one undo step"); + // (12, 8) is 2.5 left of and 1.5 above the centre: in the upright frame, 1.5 left of + // and 2.5 below its centre (5, 10). + let red = layer_rgba(&s, 1, 3, 12); + assert!(red[0] > 0.9 && red[1] < 0.1 && red[3] > 0.9, "{depth}: {red:?}"); + let mut reference = marked("rgb", depth); + reference.execute("image.rotation.arbitrary", json!({"angle": 90, "direction": "ccw"})).unwrap(); + reference.execute("image.crop", json!({"x": 5, "y": 15, "width": 10, "height": 20})).unwrap(); + for l in 0..2 { + for y in 0..20 { + for x in 0..10 { + let (a, b) = (layer_rgba(&s, l, x, y), layer_rgba(&reference, l, x, y)); + // A fully transparent pixel's colour is invisible, and the turned crop + // doesn't turn the pixels it deletes, which the warp spreads colour from. + let n = if b[3] > 1e-3 { 4 } else { 1 }; + assert!(a.iter().rev().zip(b.iter().rev()).take(n).all(|(p, q)| (p - q).abs() < 1e-3), "{depth} layer {l} ({x}, {y}): {a:?} vs {b:?}"); + } + } + } + s.execute("edit.undo", json!({})).unwrap(); + let d = doc(&s); + assert_eq!(d.size, before.size, "{depth}"); + assert_eq!(d.depth, before.depth); + for y in 0..20 { + for x in 0..40 { + assert_eq!(layer_rgba(&s, 1, x, y), before.layers[1].surface().unwrap().rgba(x, y), "{depth} undo at ({x}, {y})"); + } + } + } +} + +/// A slightly turned frame keeps its own size, the pixel under its centre and the Background's +/// colour; the turn's sign matters (a counter-clockwise frame is a negative angle). +#[test] +fn crop_at_a_small_angle_keeps_the_frame_size_in_every_mode() { + for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("grayscale", 16), ("cmyk", 8), ("lab", 16)] { + for angle in [5.0, -7.5, 365.0] { + let mut s = marked(mode, depth); + s.execute("image.crop", json!({"x": 2, "y": 1, "width": 21, "height": 15, "angle": angle})).unwrap(); + let d = doc(&s); + assert_eq!(d.size, Size::new(21, 15), "{mode} {depth} {angle}"); + assert_eq!(d.depth.bytes() * 8, depth as usize, "{mode} {depth}"); + assert_eq!(format!("{:?}", d.mode).to_lowercase(), mode, "{mode} {depth}"); + assert_eq!(d.layers.len(), 2); + // The frame's centre (12.5, 8.5) is the red pixel (the layer's only paint nearby); + // it stays at the centre, its colour kept. + let want = layer_rgba(&marked(mode, depth), 1, 12, 8); + let red = layer_rgba(&s, 1, 10, 7); + assert!(red[3] > 0.5 && (0..3).all(|c| (red[c] - want[c]).abs() < 0.2), "{mode} {depth} {angle}: {red:?} vs {want:?}"); + // The Background stays opaque white inside the canvas it came from. + let bg = layer_rgba(&s, 0, 10, 7); + assert!(bg.iter().all(|v| (v - 1.0).abs() < 0.02), "{mode} {depth} {angle}: {bg:?}"); + } + } +} + +/// A turned crop that deletes the cropped pixels turns only what lands in the frame; inside the +/// new canvas every layer, mask and channel is exactly what turning everything gives (the +/// frame spans several tiles, at several depths and angles). +#[test] +fn turned_crop_deleting_pixels_matches_turning_the_whole_canvas() { + use photocraft_color::PixelFormat; + let pixels = || (0..500).flat_map(|y| (0..700).map(move |x| (x, y))); + for depth in [8, 16, 32] { + for angle in [3.0, -7.5, 33.0, 181.0] { + let mut sessions = [true, false].map(|delete| { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 700, "height": 500, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let wave = |x: i32, y: i32, k: i32| ((x * 7 + y * 13 + k * 31) % 97) as f32 / 96.0; + let all = Rect::new(0, 0, 700, 500); + let rgba: Vec = pixels().flat_map(|(x, y)| [wave(x, y, 0), wave(x, y, 1), wave(x, y, 2), wave(y, x, 3)]).collect(); + let gray: Vec = pixels().map(|(x, y)| wave(y, x, 4)).collect(); + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().write_region(all, &rgba); + let mut mask = photocraft_doc::LayerMask::reveal_all(); + mask.surface.write_region(all, &gray); + l.mask = Some(mask); + let bg = doc.background_mut().unwrap().surface_mut().unwrap(); + bg.write_region(all, &pixels().flat_map(|(x, y)| [wave(x, y, 5), wave(x, y, 6), wave(x, y, 7), 1.0]).collect::>()); + let fmt = PixelFormat::new(ColorMode::Grayscale, doc.pixel_format().sample, false); + let mut ch = Surface::new(fmt); + ch.write_region(all, &gray); + doc.channels.push(photocraft_doc::AlphaChannel::new("Alpha 1", ch)); + Ok(()) + }) + .unwrap(); + let p = json!({"x": 150, "y": 120, "width": 330, "height": 290, "angle": angle, "deleteCroppedPixels": delete}); + s.execute("image.crop", p).unwrap(); + s + }); + let [deleted, kept] = &mut sessions; + let (a, b) = (doc(deleted), doc(kept)); + assert_eq!(a.size, b.size, "{depth} {angle}"); + let canvas = a.bounds(); + for (la, lb) in a.layers.iter().zip(&b.layers) { + let (sa, sb) = (la.surface().unwrap(), lb.surface().unwrap()); + assert!(sa.to_interleaved(canvas) == sb.to_interleaved(canvas), "{depth} {angle}: layer {}", la.name); + if let (Some(ma), Some(mb)) = (&la.mask, &lb.mask) { + assert!(ma.surface.to_interleaved(canvas) == mb.surface.to_interleaved(canvas), "{depth} {angle}: mask of {}", la.name); + } + } + assert!(a.channels[0].surface.to_interleaved(canvas) == b.channels[0].surface.to_interleaved(canvas), "{depth} {angle}: alpha channel"); + // Deleting keeps nothing past the canvas. + let layer = a.layers[1].surface().unwrap(); + assert!(canvas.contains_rect(&layer.content_bounds()), "{depth} {angle}: {:?}", layer.content_bounds()); + } + } +} + +/// Angle 0 (or a whole turn) is the plain crop: no resampling, the same document. +#[test] +fn crop_at_angle_zero_is_the_plain_crop() { + let mut plain = marked("rgb", 16); + plain.execute("image.crop", json!({"x": 3, "y": 2, "width": 30, "height": 10})).unwrap(); + for angle in [json!(0), json!(0.0), json!(360), json!(-720), json!(null)] { + let mut s = marked("rgb", 16); + let r = s.execute("image.crop", json!({"x": 3, "y": 2, "width": 30, "height": 10, "angle": angle})).unwrap(); + assert!(r.get("angle").is_none(), "{angle}: {r}"); + assert_eq!(doc(&s).size, Size::new(30, 10)); + for l in 0..2 { + for y in 0..10 { + for x in 0..30 { + assert_eq!(layer_rgba(&s, l, x, y), layer_rgba(&plain, l, x, y), "{angle} layer {l} ({x}, {y})"); + } + } + } + } +} + +/// Bad angles fail cleanly, before anything changes. +#[test] +fn crop_angle_rejects_bad_values_without_changing_the_document() { + let bad = [ + json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": "NaN"}), + json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": "12"}), + json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": [1]}), + json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": true}), + json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": 1e308}), + json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": -3601}), + json!({"x": 0, "y": 0, "width": 10, "height": 10, "angle": f64::MAX}), + // An angle needs the frame: a selection crop has none. + json!({"angle": 10}), + json!({"x": 0, "y": 0, "width": 0, "height": 10, "angle": 10}), + json!({"x": 0, "y": 0, "width": 300_001, "height": 10, "angle": 10}), + json!({"x": i32::MAX - 5, "y": 0, "width": 10, "height": 10, "angle": 10}), + ]; + for p in bad { + let mut s = marked("rgb", 8); + s.execute("select.all", json!({})).unwrap(); + let before = doc(&s).clone(); + let past = s.active().unwrap().history.past_len(); + assert!(s.execute("image.crop", p.clone()).is_err(), "{p}"); + assert_eq!(doc(&s).size, before.size, "{p}"); + assert_eq!(s.active().unwrap().history.past_len(), past, "{p}"); + } + // Far-off but representable frames turn and crop without panicking. + for (x, y) in [(-1_000_000, 0), (0, 1_000_000), (i32::MIN / 4, i32::MAX / 4)] { + let mut s = marked("rgb", 8); + s.execute("image.crop", json!({"x": x, "y": y, "width": 4, "height": 3, "angle": 33.3})).unwrap(); + assert_eq!(doc(&s).size, Size::new(4, 3)); + } +} + +#[test] +fn crop_refuses_a_canvas_side_past_the_new_document_limit() { + // #960: an unbounded explicit crop left a canvas that a later Trim or Duplicate Merged + // could only abort on allocating. + for (w, h) in [(100_000_000, 100_000_000), (300_001, 10), (10, 300_001)] { + let mut s = session(); + let (size, past) = (doc(&s).size, s.active().unwrap().history.past_len()); + let err = s.execute("image.crop", json!({"x": 0, "y": 0, "width": w, "height": h})).unwrap_err(); + assert!(err.to_string().contains("300000 px limit"), "{w} x {h}: {err}"); + assert_eq!((doc(&s).size, s.active().unwrap().history.past_len()), (size, past), "{w} x {h}: nothing changed"); + } + // At the limit it still extends the canvas (the tiles stay lazy). + let mut s = session(); + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 300_000, "height": 2})).unwrap(); + assert_eq!(doc(&s).size, Size::new(300_000, 2)); +} + +/// #2443: the Crop tool's W x H x Resolution crops, resamples the cropped area to exactly the +/// target size and sets the resolution, in one undo step, at 8 and 16 bits. +#[test] +fn crop_to_a_target_size_and_resolution_is_one_step() { + for depth in [8, 16] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300, "resolution": 72, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(100, 100, 200, 225), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let past = s.active().unwrap().history.past_len(); + // 4 x 5 in at 300 ppi from a 100 x 125 px frame. + let r = s + .execute("image.crop", json!({"x": 100, "y": 100, "width": 100, "height": 125, "targetWidth": 1200, "targetHeight": 1500, "resolution": 300})) + .unwrap(); + assert_eq!((r["documentWidth"].as_u64(), r["documentHeight"].as_u64()), (Some(1200), Some(1500)), "{depth}: {r}"); + assert_eq!(r["resolution"].as_f64(), Some(300.0), "{depth}"); + let d = doc(&s); + assert_eq!(d.size, Size::new(1200, 1500), "{depth}"); + assert_eq!(d.resolution_dpi, 300.0, "{depth}"); + assert_eq!(d.layers[0].surface().unwrap().format().sample, if depth == 8 { SampleType::U8 } else { SampleType::U16 }); + // The red frame filled the crop; it fills the result. + let red = d.layers[1].surface().unwrap(); + for (x, y) in [(0, 0), (600, 750), (1199, 1499)] { + assert_eq!(red.pixel(x, y), vec![1.0, 0.0, 0.0, 1.0], "{depth}: ({x}, {y})"); + } + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{depth}: one history step"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(400, 300), 72.0), "{depth}: undo restores the original"); + } +} + +#[test] +fn crop_target_resamples_after_a_turned_crop_and_resolution_alone_keeps_the_pixels() { + let mut s = session(); + let past = s.active().unwrap().history.past_len(); + s.execute("image.crop", json!({"x": 10, "y": 0, "width": 10, "height": 20, "angle": 90, "targetWidth": 30, "targetHeight": 60, "resample": "nearest"})) + .unwrap(); + assert_eq!(doc(&s).size, Size::new(30, 60)); + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "rotate, crop and resample: one step"); + let mut s = session(); + s.execute("image.crop", json!({"x": 2, "y": 3, "width": 30, "height": 10, "resolution": 150})).unwrap(); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi), (Size::new(30, 10), 150.0)); +} + +/// #7722: a W x H crop of an Indexed Color document resamples like Image Size (#6019), with +/// Nearest Neighbor, so no pixel gets a blend that isn't in the colour table. +#[test] +fn crop_target_resamples_indexed_color_with_nearest_neighbor() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("select.rect", json!({"x": 1, "y": 0, "width": 1, "height": 1})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + for resample in [None, Some("bicubic"), Some("automatic"), Some("bilinear"), Some("lanczos")] { + let mut p = json!({"x": 0, "y": 0, "width": 2, "height": 1, "targetWidth": 8, "targetHeight": 1}); + if let Some(r) = resample { + p["resample"] = json!(r); + } + s.execute("image.crop", p).unwrap(); + let surf = doc(&s).layers[0].surface().unwrap(); + for x in 0..8 { + let px = surf.pixel(x, 0); + assert!(px[..3] == [1.0, 0.0, 0.0] || px[..3] == [0.0, 0.0, 1.0], "{resample:?}: no blended colour at x {x}: {px:?}"); + } + s.execute("history.undo", json!({})).unwrap(); + } +} + +#[test] +fn crop_target_accepts_whole_number_floats() { + // `json.dumps(100.0)` and many other JSON writers send whole numbers as floats. + let mut s = session(); + s.execute("image.crop", json!({"x": 0, "y": 0, "width": 20, "height": 10, "targetWidth": 40.0, "targetHeight": 20.0})).unwrap(); + assert_eq!(doc(&s).size, Size::new(40, 20)); +} + +#[test] +fn crop_target_rejects_bad_params_without_changing_the_document() { + let rect = json!({"x": 0, "y": 0, "width": 10, "height": 10}); + let bad_params = [ + json!({"targetWidth": 100}), + json!({"targetHeight": 100}), + json!({"targetWidth": 0, "targetHeight": 10}), + json!({"targetWidth": -5, "targetHeight": 10}), + json!({"targetWidth": 10.5, "targetHeight": 10}), + json!({"targetWidth": -1.0, "targetHeight": 10}), + json!({"targetWidth": 0.0, "targetHeight": 10}), + json!({"targetWidth": 1e39, "targetHeight": 10}), + json!({"targetWidth": 300_001.0, "targetHeight": 10}), + json!({"targetWidth": "10", "targetHeight": 10}), + json!({"targetWidth": 300_001, "targetHeight": 10}), + json!({"targetWidth": 4_294_967_306_u64, "targetHeight": 10}), + json!({"targetWidth": 300_000, "targetHeight": 300_000}), + json!({"targetWidth": 10, "targetHeight": 10, "resample": "none"}), + json!({"targetWidth": 10, "targetHeight": 10, "resample": 3}), + json!({"resolution": 0}), + json!({"resolution": -72}), + json!({"resolution": 1e9}), + json!({"resolution": "300"}), + ]; + for extra in bad_params { + let mut s = session(); + let (size, dpi, past) = (doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len()); + let mut p = rect.clone(); + if let (Some(o), Some(e)) = (p.as_object_mut(), extra.as_object()) { + o.extend(e.clone()); + } + assert!(s.execute("image.crop", p.clone()).is_err(), "{p}"); + assert_eq!((doc(&s).size, doc(&s).resolution_dpi, s.active().unwrap().history.past_len()), (size, dpi, past), "{p}: nothing changed"); + } +} + +#[test] +fn trim_based_on_top_left_colour() { + let mut s = session(); + s.edit("no fx", |doc, _| { + doc.layers[1].effects.items.clear(); + Ok(()) + }) + .unwrap(); + s.execute("image.trim", json!({"basedOn": "topLeft"})).unwrap(); + assert_eq!(doc(&s).size, Size::new(10, 10)); +} + +#[test] +fn thirty_two_bit_holds_linear_light() { + // Photoshop 27.11: an 8-bit sRGB grey 128 becomes 0.2159 in 32 bits (and 32 → 0.0144), + // and comes back unchanged; alpha keeps its value. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 1, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + let l = doc.layer_mut(active.unwrap()).unwrap(); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 2, 1), &[128.0 / 255.0, 32.0 / 255.0, 1.0, 0.5]); + Ok(()) + }) + .unwrap(); + s.execute("image.mode.bits32", json!({})).unwrap(); + let px = doc(&s).layers[1].surface().unwrap().pixel(0, 0); + for (got, want) in px.iter().zip([0.2159, 0.0144, 1.0, 128.0 / 255.0]) { + assert!((got - want).abs() < 2e-4, "{px:?}"); + } + s.execute("image.mode.bits8", json!({})).unwrap(); + let px = doc(&s).layers[1].surface().unwrap().pixel(0, 0); + for (got, want) in px.iter().zip([128.0 / 255.0, 32.0 / 255.0, 1.0, 128.0 / 255.0]) { + assert!((got - want).abs() < 0.6 / 255.0, "{px:?}"); + } +} + +#[test] +fn grayscale_conversion_matches_photoshop() { + // Photoshop 27.11, default Color Settings (working gray Dot Gain 20 %): Image > Mode > + // Grayscale turns sRGB 64 / 128 / 192 grey and pure red into 46 / 105 / 177 / 107. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 1, "background": "white"})).unwrap(); + s.edit("paint", |doc, _| { + let l = doc.layers.first_mut().unwrap(); + let surf = l.surface_mut().unwrap(); + for (x, c) in [[64.0, 64.0, 64.0], [128.0, 128.0, 128.0], [192.0, 192.0, 192.0], [255.0, 0.0, 0.0]].iter().enumerate() { + surf.fill_rect(Rect::new(x as i32, 0, x as i32 + 1, 1), &[c[0] / 255.0, c[1] / 255.0, c[2] / 255.0, 1.0]); + } + Ok(()) + }) + .unwrap(); + s.execute("image.mode.grayscale", json!({})).unwrap(); + let surf = doc(&s).layers[0].surface().unwrap(); + for (x, want) in [46.0, 105.0, 177.0, 107.0].iter().enumerate() { + let got = surf.pixel(x as i32, 0)[0] * 255.0; + assert!((got - want).abs() <= 1.5, "pixel {x}: {got} vs {want}"); + } +} + +#[test] +fn mode_and_depth_conversions() { + let mut s = session(); + s.execute("image.mode.grayscale", json!({})).unwrap(); + assert_eq!(doc(&s).mode, ColorMode::Grayscale); + assert_eq!(doc(&s).layers[1].surface().unwrap().format().mode, ColorMode::Grayscale); + s.execute("image.mode.bits16", json!({})).unwrap(); + assert_eq!(doc(&s).depth, SampleType::U16); + assert_eq!(doc(&s).layers[1].surface().unwrap().format().sample, SampleType::U16); + assert_eq!(doc(&s).layers[1].mask.as_ref().unwrap().surface.format().sample, SampleType::U16); + s.execute("image.mode.cmyk", json!({})).unwrap(); + s.execute("image.mode.bits32", json!({})).unwrap(); + s.execute("image.mode.lab", json!({})).unwrap(); + s.execute("image.mode.rgb", json!({})).unwrap(); + s.execute("image.mode.bits8", json!({})).unwrap(); + let d = doc(&s); + assert_eq!((d.mode, d.depth), (ColorMode::Rgb, SampleType::U8)); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(doc(&s).depth, SampleType::F32); + let revision = s.active().unwrap().revision; + s.execute("image.mode.bits32", json!({})).unwrap(); + assert_eq!(s.active().unwrap().revision, revision, "an unchanged bit depth must preserve the history branch"); + assert!(s.redo(), "selecting the current depth must not discard the undone conversion"); + assert_eq!(doc(&s).depth, SampleType::U8); +} + +/// Duplicate › Merged Layers Only gives one locked Background when the source has one and a +/// plain "Layer 1" (keeping transparency) when it doesn't, as Photoshop does. +#[test] +fn merged_duplicate_is_a_background_only_when_the_source_has_one() { + let mut s = session(); + s.execute("image.duplicate", json!({"mergedOnly": true})).unwrap(); + let d = doc(&s); + assert!(d.is_background(d.layers[0].id), "source has a Background: the merged copy is one"); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap(); + s.execute("image.duplicate", json!({"mergedOnly": true})).unwrap(); + let d = doc(&s); + assert!(d.background().is_none(), "transparent source: no Background in the copy"); + assert_eq!(d.layers[0].name, "Layer 1"); +} + +#[test] +fn duplicate_document() { + let mut s = session(); + let r = s.execute("image.duplicate", json!({"mergedOnly": true})).unwrap(); + assert_eq!(r["document"], json!(1)); + assert_eq!(s.documents().len(), 2); + assert_eq!(doc(&s).layers.len(), 1); + assert!(doc(&s).name.ends_with("copy")); +} From 038c3745cf7c8aacec5f8776db7ec250ccaafb48 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:24 +0000 Subject: [PATCH 045/259] refactor(engine): move extra_cmds.rs tests to extra_cmds/tests.rs --- crates/engine/src/extra_cmds.rs | 823 +------------------------- crates/engine/src/extra_cmds/tests.rs | 820 +++++++++++++++++++++++++ 2 files changed, 821 insertions(+), 822 deletions(-) create mode 100644 crates/engine/src/extra_cmds/tests.rs diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs index d5364cfd88..4a3190ec72 100644 --- a/crates/engine/src/extra_cmds.rs +++ b/crates/engine/src/extra_cmds.rs @@ -1058,825 +1058,4 @@ pub fn specs() -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - fn session(depth: u32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s - } - - fn doc(s: &Session) -> &Document { - &s.active().unwrap().doc - } - - #[test] - fn equalize_average_and_clouds_edit_the_targeted_channel() { - // #935: these four ran through `map_pixels`, which always rewrote the active layer, so - // with an alpha channel or the Quick Mask targeted they changed the layer and left the - // channel alone. - let cmds = ["image.adjustments.equalize", "filter.blur.average", "filter.render.clouds", "filter.render.differenceClouds"]; - for depth in [8, 16, 32] { - for target in ["quickMask", "alpha", "mask"] { - for cmd in cmds { - let mut s = session(depth); - 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 { - "quickMask" => { - s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); - json!({"seed": 1}) - } - "alpha" => { - s.execute("channel.new", json!({"fill": "white"})).unwrap(); - s.execute("channel.target", json!({"channel": 0})).unwrap(); - json!({"seed": 1}) - } - _ => { - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - json!({"seed": 1, "target": "mask"}) - } - }; - // 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| { - let (surf, _) = crate::channel_cmds::target_surface(doc, *active, &edit_target).unwrap(); - surf.fill_rect(Rect::new(0, 0, 20, 30), &[0.4]); - surf.fill_rect(Rect::new(20, 0, 40, 30), &[0.5]); - Ok(()) - }) - .unwrap(); - let full = Rect::new(0, 0, 40, 30); - let read = |s: &Session| { - let d = doc(s); - let layer = d.layer(s.active().unwrap().active_layer.unwrap()).unwrap(); - let t = match target { - "quickMask" => d.quick_mask.as_ref().unwrap().surface.read_region(full), - "alpha" => d.channels[0].surface.read_region(full), - _ => layer.mask.as_ref().unwrap().surface.read_region(full), - }; - (layer.surface().unwrap().read_region(full), t) - }; - let ((layer0, target0), past) = (read(&s), s.active().unwrap().history.past_len()); - s.execute(cmd, p).unwrap(); - let (layer1, target1) = read(&s); - 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"); - assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{case}"); - s.undo(); - assert_eq!(read(&s).1, target0, "{case}: undo restores the target"); - } - } - } - } - - fn active(s: &Session) -> &Layer { - let d = s.active().unwrap(); - d.doc.layer(d.active_layer.unwrap()).unwrap() - } - - fn pixel(s: &Session, x: i32, y: i32) -> Vec { - active(s).surface().unwrap().pixel(x, y) - } - - fn paint_square(s: &mut Session, r: Rect, c: [f32; 4]) { - s.edit("paint", |doc, a| { - doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(r, &c); - Ok(()) - }) - .unwrap(); - } - - #[test] - fn stroke_locations_at_several_depths() { - for depth in [8, 16, 32] { - for (loc, inside, outside) in [("inside", 1.0, 0.0), ("outside", 0.0, 1.0), ("center", 1.0, 1.0)] { - let mut s = session(depth); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - s.execute("edit.stroke", json!({"width": 2, "color": "#ff0000", "location": loc})).unwrap(); - assert!((pixel(&s, 10, 15)[3] - inside).abs() < 0.02, "{depth} {loc} inside {:?}", pixel(&s, 10, 15)); - assert!((pixel(&s, 9, 15)[3] - outside).abs() < 0.02, "{depth} {loc} outside {:?}", pixel(&s, 9, 15)); - assert_eq!(pixel(&s, 15, 15)[3], 0.0, "centre untouched"); - } - } - // Without a selection the layer's opaque edge is stroked. - let mut s = session(8); - paint_square(&mut s, Rect::new(10, 10, 20, 20), [0.0, 0.0, 1.0, 1.0]); - s.execute("edit.stroke", json!({"width": 3, "color": "#00ff00", "location": "outside"})).unwrap(); - assert_eq!(pixel(&s, 8, 15), vec![0.0, 1.0, 0.0, 1.0]); - assert_eq!(pixel(&s, 15, 15), vec![0.0, 0.0, 1.0, 1.0]); - } - - /// Photoshop's Edit › Stroke on a selection (checked by hand): Center puts ceil(w/2) px inside - /// and floor(w/2) outside (1 px is all inside), fractional widths round up, and every stroked - /// pixel is fully opaque, on every edge, horizontal ones included. Inside and Outside are - /// w px on their side. - #[test] - fn stroke_widths_are_whole_opaque_pixels_like_photoshop() { - // Selection x 10..30, y 10..30; the edge pixels inside are 10 and 29 on each axis. - let band = |loc: &str, w: i32| -> (i32, i32) { - match loc { - "inside" => (w, 0), - "outside" => (0, w), - _ => ((w + 1) / 2, w / 2), - } - }; - let mut wrong = Vec::new(); - for depth in [8, 16, 32] { - for loc in ["center", "inside", "outside"] { - for (param, w) in [(json!(1), 1), (json!(2), 2), (json!(3), 3), (json!(4), 4), (json!(5), 5), (json!(0.5), 1), (json!(2.5), 3)] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 50, "height": 50, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - s.execute("edit.stroke", json!({"width": param, "color": "#ff0000", "location": loc})).unwrap(); - let (inside, outside) = band(loc, w); - // (edge pixel inside, step inward) for left, right, top and bottom; the other - // coordinate is the middle of the edge. - for (name, first_in, inward, horizontal) in - [("left", 10, 1, false), ("right", 29, -1, false), ("top", 10, 1, true), ("bottom", 29, -1, true)] - { - for k in -7..7 { - // k ≥ 0: k px inside from the edge; k < 0: -k px outside. - let c = first_in + k * inward; - let (x, y) = if horizontal { (20, c) } else { (c, 20) }; - let want = if (k >= 0 && k < inside) || (k < 0 && -k <= outside) { 1.0 } else { 0.0 }; - let a = pixel(&s, x, y)[3]; - if (a - want).abs() > 0.004 { - wrong.push(format!("{depth}-bit {loc} width {param} {name} edge, {k:+} px: alpha {a}, want {want}")); - } - } - } - } - } - } - assert!(wrong.is_empty(), "{} pixels differ from Photoshop:\n{}", wrong.len(), wrong.iter().take(40).cloned().collect::>().join("\n")); - } - - /// Photoshop's 6 px Outside stroke of a 14 px circle selection made without anti-aliasing, - /// read pixel by pixel from Photoshop (`#` stroked, `.` not; the hole is the selection). A - /// hard selection gives a hard stroke: a pixel is stroked when its centre is less than - /// width + 1 from a selected pixel's centre (no partial pixels on the curve). - const PS_CIRCLE_OUTSIDE_6: [&str; 31] = [ - "..................................", - "..................................", - "...........############...........", - "..........##############..........", - ".........################.........", - "........##################........", - ".......####################.......", - "......######################......", - ".....#########......#########.....", - "....#########........#########....", - "....########..........########....", - "....#######............#######....", - "....######..............######....", - "....######..............######....", - "....######..............######....", - "....######..............######....", - "....######..............######....", - "....######..............######....", - "....#######............#######....", - "....########..........########....", - "....#########........#########....", - ".....#########......#########.....", - "......######################......", - ".......####################.......", - "........##################........", - ".........################.........", - "..........##############..........", - "...........############...........", - "..................................", - "..................................", - "..................................", - ]; - - /// Photoshop's 3 px Inside stroke of the same 14 px hard circle (the selection is the ring - /// plus its hole). Inside, a pixel is stroked when its centre is less than width + ½ from an - /// unselected pixel's: that offset is the one fitting this, the 5 px and the 6 px samples - /// (any value from +0.41 to +0.60), so 6 px fills this circle (its deepest pixel is 6.4 px in). - const PS_CIRCLE_INSIDE_3: [&str; 17] = [ - "...................", - "......######.......", - ".....########......", - "....##########.....", - "...####....####....", - "..####......####...", - "..###........###...", - "..###........###...", - "..###........###...", - "..###........###...", - "..####......####...", - "...####....####....", - "....##########.....", - ".....########......", - "......######.......", - "...................", - "...................", - ]; - - /// The selection of a Photoshop sample grid: an Outside stroke's hole, or an Inside stroke's - /// ring and hole. - fn grid_selection(rows: &[&str], outside: bool) -> Vec { - let (w, h) = (rows[0].len(), rows.len()); - let mut mask = vec![0.0f32; w * h]; - for (y, row) in rows.iter().enumerate() { - let b = row.as_bytes(); - if let (Some(first), Some(last)) = (b.iter().position(|c| *c == b'#'), b.iter().rposition(|c| *c == b'#')) { - for x in first..=last { - if !outside || b[x] == b'.' { - mask[y * w + x] = 1.0; - } - } - } - } - mask - } - - /// Strokes `mask` as the selection of a `w` × `h` layer and returns its alpha per pixel. - fn stroke_alpha(mask: &[f32], w: usize, h: usize, depth: u32, params: Value) -> Vec { - let mut s = Session::new(); - s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("select", |doc, _| { - doc.selection = Some(sel::mask_to_surface(mask, doc.bounds())); - Ok(()) - }) - .unwrap(); - s.execute("edit.stroke", params).unwrap(); - (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).map(|(x, y)| pixel(&s, x as i32, y as i32)[3]).collect() - } - - #[test] - fn a_hard_circle_strokes_inside_like_photoshop() { - let rows = PS_CIRCLE_INSIDE_3; - let (w, h) = (rows[0].len(), rows.len()); - let mask = grid_selection(&rows, false); - for depth in [8, 16, 32] { - let got = stroke_alpha(&mask, w, h, depth, json!({"width": 3, "color": "#000000", "location": "inside"})); - let wrong: Vec = rows - .iter() - .enumerate() - .flat_map(|(y, row)| row.bytes().enumerate().map(move |(x, c)| (x, y, c))) - .filter_map(|(x, y, c)| { - let want = if c == b'#' { 1.0 } else { 0.0 }; - let a = got[y * w + x]; - ((a - want).abs() > 0.004).then(|| format!("({x}, {y}): {a}, Photoshop {want}")) - }) - .collect(); - assert!(wrong.is_empty(), "{depth}-bit: {} pixels differ from Photoshop: {wrong:?}", wrong.len()); - // Checked in Photoshop: a 5 px Inside stroke leaves a plus-shaped hole of 12 pixels in - // the middle (rows 2, 4, 4, 2 wide), and 6 px fills the whole circle. - let hole = [(8, 6), (9, 6), (7, 7), (8, 7), (9, 7), (10, 7), (7, 8), (8, 8), (9, 8), (10, 8), (8, 9), (9, 9)]; - let five = stroke_alpha(&mask, w, h, depth, json!({"width": 5, "color": "#000000", "location": "inside"})); - for (i, m) in mask.iter().enumerate() { - let stroked = *m > 0.0 && !hole.contains(&(i % w, i / w)); - assert_eq!(five[i] > 0.996, stroked, "{depth}-bit 5 px Inside at ({}, {})", i % w, i / w); - } - let full = stroke_alpha(&mask, w, h, depth, json!({"width": 6, "color": "#000000", "location": "inside"})); - for (i, m) in mask.iter().enumerate() { - assert_eq!(full[i] > 0.996, *m > 0.0, "{depth}-bit 6 px Inside at ({}, {})", i % w, i / w); - } - } - } - - #[test] - fn a_hard_circle_strokes_like_photoshop() { - let rows = PS_CIRCLE_OUTSIDE_6; - let (w, h) = (rows[0].len(), rows.len()); - // The selection: the `.` cells enclosed by the ring on each row. - let mask = grid_selection(&rows, true); - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("select", |doc, _| { - doc.selection = Some(sel::mask_to_surface(&mask, doc.bounds())); - Ok(()) - }) - .unwrap(); - s.execute("edit.stroke", json!({"width": 6, "color": "#000000", "location": "outside"})).unwrap(); - let mut wrong = Vec::new(); - for (y, row) in rows.iter().enumerate() { - for (x, c) in row.bytes().enumerate() { - let want = if c == b'#' { 1.0 } else { 0.0 }; - let a = pixel(&s, x as i32, y as i32)[3]; - if (a - want).abs() > 0.004 { - wrong.push(format!("({x}, {y}): {a}, Photoshop {want}")); - } - } - } - assert!(wrong.is_empty(), "{depth}-bit: {} pixels differ from Photoshop: {wrong:?}", wrong.len()); - } - } - - /// Select All, then Stroke › Inside draws a border around the canvas (a common Photoshop - /// technique): the canvas edge is a selection edge like any other, on all four sides. - #[test] - fn stroking_a_selection_at_the_canvas_edge_draws_that_edge() { - for depth in [8, 16, 32] { - for (loc, w, inside) in [("inside", 3, 3), ("center", 3, 2), ("center", 1, 1)] { - let mut s = session(depth); - s.execute("select.all", json!({})).unwrap(); - s.execute("edit.stroke", json!({"width": w, "color": "#ff0000", "location": loc})).unwrap(); - // 40 × 30 canvas: k px in from each side, in the middle of the side. - for name in ["left", "right", "top", "bottom"] { - for k in 0..6 { - let (x, y) = match name { - "left" => (k, 15), - "right" => (39 - k, 15), - "top" => (20, k), - _ => (20, 29 - k), - }; - let want = if k < inside { 1.0 } else { 0.0 }; - let a = pixel(&s, x, y)[3]; - assert!((a - want).abs() < 0.004, "{depth}-bit {loc} {w} px, {name} side, {k} px in: alpha {a}, want {want}"); - } - } - } - } - } - - #[test] - fn stroke_uses_fill_blending_and_preserves_transparency_at_every_depth() { - for depth in [8, 16, 32] { - let mut s = session(depth); - paint_square(&mut s, Rect::new(10, 10, 20, 20), [0.5, 0.5, 0.5, 1.0]); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - - let past = s.active().unwrap().history.past_len(); - s.execute( - "edit.stroke", - json!({"width": 2, "color": "#ffffff", "location": "inside", "mode": "multiply", "opacity": 100, "preserveTransparency": true}), - ) - .unwrap(); - assert_eq!(s.active().unwrap().history.past_len(), past + 1, "Stroke is one history step"); - let edge = pixel(&s, 10, 15); - assert!((edge[0] - 0.5).abs() < 0.015, "{depth}-bit Multiply must preserve gray: {edge:?}"); - assert_eq!(edge[3], 1.0); - - s.execute("edit.stroke", json!({"width": 2, "color": "#ffffff", "location": "outside", "preserveTransparency": true})).unwrap(); - assert_eq!(pixel(&s, 9, 15)[3], 0.0, "{depth}-bit transparency lock prevents new outer pixels"); - - s.execute("edit.stroke", json!({"width": 2, "color": "#ffffff", "location": "outside", "opacity": 50})).unwrap(); - let out = pixel(&s, 9, 15); - assert!((out[3] - 0.5).abs() < 0.015, "{depth}-bit 50% stroke opacity: {out:?}"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(pixel(&s, 9, 15)[3], 0.0); - } - } - - #[test] - fn stroke_rejects_invalid_blending_options_without_modifying_the_document() { - let mut s = session(8); - s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); - let past = s.active().unwrap().history.past_len(); - for params in [ - json!({"mode": "unknown-mode"}), - json!({"mode": 42}), - json!({"mode": "passThrough"}), - json!({"opacity": "lots"}), - json!({"preserveTransparency": "true"}), - ] { - assert!(s.execute("edit.stroke", params.clone()).is_err(), "{params}"); - assert_eq!(s.active().unwrap().history.past_len(), past, "{params} should not create a history step"); - } - } - - #[test] - fn transform_presets_are_exact() { - let mut s = session(8); - paint_square(&mut s, Rect::new(10, 10, 20, 14), [1.0, 0.0, 0.0, 1.0]); - paint_square(&mut s, Rect::new(10, 10, 11, 11), [0.0, 1.0, 0.0, 1.0]); - s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); - assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); - assert_eq!(pixel(&s, 19, 10), vec![0.0, 1.0, 0.0, 1.0]); - s.execute("edit.transform.flipVertical", json!({})).unwrap(); - assert_eq!(pixel(&s, 19, 13), vec![0.0, 1.0, 0.0, 1.0]); - s.execute("edit.transform.rotate180", json!({})).unwrap(); - assert_eq!(pixel(&s, 10, 10), vec![0.0, 1.0, 0.0, 1.0]); - s.execute("edit.transform.rotate90Cw", json!({})).unwrap(); - let b = active(&s).surface().unwrap().content_bounds(); - assert_eq!((b.width(), b.height()), (4, 10)); - // Top-left corner goes to the top-right after a clockwise turn. - assert_eq!(pixel(&s, b.x1 - 1, b.y0), vec![0.0, 1.0, 0.0, 1.0]); - s.execute("edit.transform.rotate90Ccw", json!({})).unwrap(); - assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); - assert_eq!(pixel(&s, 10, 10), vec![0.0, 1.0, 0.0, 1.0]); - } - - /// #6928: with a selection, the presets flip and turn about the selection's own bounds, as - /// in Photoshop: Select All mirrors across the canvas, a marquee across its own centre. - /// Without a selection they keep turning about the content (above). - #[test] - fn transform_presets_turn_about_the_selection() { - let mut s = session(8); - paint_square(&mut s, Rect::new(10, 10, 20, 14), [1.0, 0.0, 0.0, 1.0]); - paint_square(&mut s, Rect::new(10, 10, 11, 11), [0.0, 1.0, 0.0, 1.0]); - let green = vec![0.0, 1.0, 0.0, 1.0]; - // Select All on the 40 × 30 canvas: across the canvas's centre lines. - s.execute("select.all", json!({})).unwrap(); - let past = s.active().unwrap().history.past_len(); - s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); - assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(20, 10, 30, 14)); - assert_eq!(pixel(&s, 29, 10), green); - assert_eq!(s.active().unwrap().history.past_len(), past + 1, "one undo step"); - s.execute("edit.transform.flipVertical", json!({})).unwrap(); - assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(20, 16, 30, 20)); - assert_eq!(pixel(&s, 29, 19), green); - s.execute("edit.transform.rotate180", json!({})).unwrap(); - assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); - assert_eq!(pixel(&s, 10, 10), green); - // A marquee (0, 0)–(24, 30) holding the whole square: across x = 12. - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 24, "height": 30})).unwrap(); - s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); - assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(4, 10, 14, 14)); - assert_eq!(pixel(&s, 13, 10), green); - // Undo puts it back where it was. - s.undo(); - assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); - // A targeted alpha channel turns about the selection's bounds too. - s.execute("channel.new", json!({})).unwrap(); - s.edit("paint channel", |doc, _| { - doc.channels[0].surface.fill_rect(Rect::new(10, 10, 20, 20), &[1.0]); - Ok(()) - }) - .unwrap(); - s.execute("channel.target", json!({"channel": 0})).unwrap(); - s.execute("select.all", json!({})).unwrap(); - s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); - assert_eq!(s.active().unwrap().doc.channels[0].surface.content_bounds(), Rect::new(20, 10, 30, 20)); - } - - #[test] - fn reselect_restores_the_last_selection() { - let mut s = session(8); - assert!(!s.is_enabled("select.reselect")); - s.execute("select.rect", json!({"x": 2, "y": 3, "width": 5, "height": 6})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - assert!(doc(&s).selection.is_none()); - s.execute("select.reselect", json!({})).unwrap(); - assert_eq!(doc(&s).selection.as_ref().unwrap().content_bounds(), Rect::new(2, 3, 7, 9)); - assert!(!s.is_enabled("select.reselect"), "nothing to reselect while a selection exists"); - } - - #[test] - fn equalize_spreads_values() { - for depth in [8, 16] { - let mut s = session(depth); - paint_square(&mut s, Rect::new(0, 0, 40, 15), [0.4, 0.4, 0.4, 1.0]); - paint_square(&mut s, Rect::new(0, 15, 40, 30), [0.5, 0.5, 0.5, 1.0]); - s.execute("image.adjustments.equalize", json!({})).unwrap(); - let (dark, light) = (pixel(&s, 1, 1)[0], pixel(&s, 1, 20)[0]); - assert!(dark < 0.05 && light > 0.95, "{depth}: {dark} {light}"); - } - } - - /// A selection masks Clouds but doesn't change their size: inside it they are the canvas's - /// clouds, as when Clouds sized itself by the document (before it became a filter). - #[test] - fn clouds_in_a_selection_are_the_canvas_clouds() { - // Big enough that the canvas (cloud size 100 px) and the selection (16 px) size differently. - let big = |depth: u32| { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s - }; - for depth in [8, 16, 32] { - let mut whole = big(depth); - whole.execute("filter.render.clouds", json!({"seed": 4})).unwrap(); - let mut s = big(depth); - s.execute("select.rect", json!({"x": 50, "y": 40, "width": 60, "height": 50})).unwrap(); - s.execute("filter.render.clouds", json!({"seed": 4})).unwrap(); - for (x, y) in [(50, 40), (75, 60), (100, 85), (109, 89)] { - let (a, b) = (pixel(&s, x, y), pixel(&whole, x, y)); - assert!((0..4).all(|c| (a[c] - b[c]).abs() < 1e-3), "depth {depth} at {x},{y}: {a:?} vs {b:?}"); - } - assert_eq!(pixel(&s, 300, 200)[3], 0.0, "outside the selection the layer stays empty"); - } - } - - #[test] - fn average_and_clouds() { - let mut s = session(8); - paint_square(&mut s, Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 1.0]); - paint_square(&mut s, Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 1.0]); - s.execute("filter.blur.average", json!({})).unwrap(); - let p = pixel(&s, 5, 5); - assert!((p[0] - 0.5).abs() < 0.01 && (p[2] - 0.5).abs() < 0.01, "{p:?}"); - s.execute("filter.render.clouds", json!({"seed": 3})).unwrap(); - let vals: Vec = (0..40).map(|x| pixel(&s, x, 12)[0]).collect(); - let (lo, hi) = vals.iter().fold((1.0f32, 0.0f32), |(a, b), v| (a.min(*v), b.max(*v))); - assert!(hi - lo > 0.05, "clouds vary: {lo}..{hi}"); - assert!(vals.windows(2).all(|w| (w[0] - w[1]).abs() < 0.2), "clouds are smooth"); - // Difference Clouds over itself with the same seed cancels to black. - s.execute("filter.render.differenceClouds", json!({"seed": 3})).unwrap(); - assert!(pixel(&s, 7, 7)[..3].iter().all(|v| *v < 0.01), "{:?}", pixel(&s, 7, 7)); - } - - #[test] - fn paste_into_masks_to_the_selection() { - let mut s = session(8); - paint_square(&mut s, Rect::new(0, 0, 10, 10), [1.0, 0.0, 0.0, 1.0]); - s.execute("select.all", json!({})).unwrap(); - s.execute("edit.copy", json!({})).unwrap(); - let steps = s.active().unwrap().history.past_len(); - s.execute("select.rect", json!({"x": 20, "y": 10, "width": 8, "height": 8})).unwrap(); - s.execute("edit.pasteSpecial.pasteInto", json!({})).unwrap(); - let l = active(&s); - let m = l.mask.as_ref().unwrap(); - assert!(!m.linked); - assert_eq!(m.surface.content_bounds(), Rect::new(20, 10, 28, 18)); - assert_eq!(m.value(0, 0), 0.0); - assert!(doc(&s).selection.is_none()); - assert_eq!(s.active().unwrap().history.past_len(), steps + 2, "select + one Paste Into step"); - // Paste Outside reveals everything but the selection. - s.execute("select.rect", json!({"x": 20, "y": 10, "width": 8, "height": 8})).unwrap(); - s.execute("edit.pasteSpecial.pasteOutside", json!({})).unwrap(); - let m = active(&s).mask.as_ref().unwrap(); - assert_eq!((m.value(0, 0), m.value(22, 12)), (1.0, 0.0)); - } - - #[test] - fn option_click_eye_shows_one_layer_then_restores() { - let mut s = session(8); - s.execute("layer.new.layer", json!({})).unwrap(); - let ids: Vec = doc(&s).layers.iter().map(|l| l.id).collect(); - // Background, Layer 1 (hidden beforehand), Layer 2. - s.execute("layer.hideLayers", json!({"layer": ids[1].0})).unwrap(); - let vis = |s: &Session| doc(s).layers.iter().map(|l| l.visible).collect::>(); - assert_eq!(s.execute("layer.showOnly", json!({"layer": ids[1].0})).unwrap()["shownAlone"], true); - assert_eq!(vis(&s), [false, true, false]); - // Another eye moves the solo; the original snapshot survives. - s.execute("layer.showOnly", json!({"layer": ids[2].0})).unwrap(); - assert_eq!(vis(&s), [false, false, true]); - assert_eq!(s.execute("layer.showOnly", json!({"layer": ids[2].0})).unwrap()["shownAlone"], false); - assert_eq!(vis(&s), [true, false, true], "restored, with Layer 1 still hidden"); - // One history step each way. - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(vis(&s), [false, false, true]); - } - - #[test] - fn show_only_keeps_groups_and_their_contents() { - let mut s = session(8); - s.execute("layer.new.layer", json!({})).unwrap(); - let inner = active(&s).id; - let group = s.execute("layer.groupLayers", json!({"layer": inner.0})).unwrap()["layer"].as_u64().map(LayerId).unwrap(); - let shown = |s: &Session| doc(s).walk().iter().map(|(_, _, l)| l.visible).collect::>(); - // Background, Layer 1, Group 1, Layer 2 (inside the group). - s.execute("layer.showOnly", json!({"layer": inner.0})).unwrap(); - assert_eq!(shown(&s), [false, false, true, true], "the enclosing group stays visible"); - // An undo ends the solo, so the next ⌥-click solos again from the current state. - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(s.execute("layer.showOnly", json!({"layer": inner.0})).unwrap()["shownAlone"], true); - s.execute("edit.undo", json!({})).unwrap(); - // Showing a group alone leaves its contents as they are. - s.execute("layer.setProps", json!({"layer": inner.0, "visible": false})).unwrap(); - s.execute("layer.showOnly", json!({"layer": group.0})).unwrap(); - assert_eq!(shown(&s), [false, false, true, false]); - s.execute("layer.showOnly", json!({"layer": group.0})).unwrap(); - assert_eq!(shown(&s), [true, true, true, false]); - } - - #[test] - fn show_only_without_a_snapshot_shows_every_layer() { - let mut s = session(16); - let bg = doc(&s).layers[0].id; - s.execute("layer.hideLayers", json!({"layer": bg.0})).unwrap(); - // Layer 1 is already the only visible layer: ⌥-clicking it shows everything. - assert_eq!(s.execute("layer.showOnly", json!({})).unwrap()["shownAlone"], false); - assert!(doc(&s).layers.iter().all(|l| l.visible)); - assert!(s.execute("layer.showOnly", json!({"layer": u64::MAX})).is_err()); - assert!(Session::new().execute("layer.showOnly", json!({})).is_err()); - } - - #[test] - fn a_mask_turns_the_background_into_a_layer() { - for (cmd, needs_selection) in [ - ("layer.layerMask.revealAll", false), - ("layer.layerMask.hideAll", false), - ("layer.layerMask.revealSelection", true), - ("layer.layerMask.hideSelection", true), - ] { - let mut s = session(8); - let bg = doc(&s).layers[0].id; - if needs_selection { - s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); - } - s.execute(cmd, json!({"layer": bg.0})).unwrap(); - let l = &doc(&s).layers[0]; - assert!(l.mask.is_some() && l.name == "Layer 0" && !l.locks.transparency && !l.locks.position, "{cmd}"); - assert!(!s.is_enabled("layer.new.layerFromBackground"), "{cmd}"); - // One step: undo brings the locked Background back, without a mask. - assert!(s.undo()); - let l = &doc(&s).layers[0]; - assert!(l.mask.is_none() && l.name == "Background" && l.locks.transparency, "{cmd}"); - } - // Other layers keep their name and locks. - let mut s = session(8); - let top = doc(&s).layers[1].id; - s.execute("layer.setProps", json!({"layer": top.0, "locks": {"position": true}})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({"layer": top.0})).unwrap(); - let l = doc(&s).layer(top).unwrap(); - assert!(l.mask.is_some() && l.name != "Layer 0" && l.locks.position); - assert_eq!(doc(&s).layers[0].name, "Background"); - } - - #[test] - fn hide_layers_toggles_once_every_target_is_hidden() { - let mut s = session(8); - s.execute("layer.new.layer", json!({})).unwrap(); - let b = active(&s).id; - let visible = |s: &Session| doc(s).layer(b).unwrap().visible; - // Select › All Layers leaves out the Background, as in Photoshop. - let all = |s: &Session| crate::layer_multi_cmds::selected(s).iter().map(|id| doc(s).layer(*id).unwrap().visible).collect::>(); - s.execute("layer.hideLayers", json!({})).unwrap(); - assert!(!visible(&s)); - s.execute("layer.hideLayers", json!({})).unwrap(); - assert!(visible(&s), "⌘, again shows it"); - // Several selected: any one still shown means hide them all; then they all come back. - s.execute("layer.hideLayers", json!({"layer": b.0})).unwrap(); - s.execute("select.allLayers", json!({})).unwrap(); - assert!(all(&s).len() > 1); - s.execute("layer.hideLayers", json!({})).unwrap(); - assert!(all(&s).iter().all(|v| !v)); - s.execute("layer.hideLayers", json!({})).unwrap(); - assert!(all(&s).iter().all(|v| *v)); - } - - #[test] - fn slash_toggles_lock_transparent_pixels_but_not_on_the_background() { - let mut s = session(8); - let bg = doc(&s).layers[0].id; - assert!(doc(&s).is_background(bg)); - s.execute("layer.new.layer", json!({})).unwrap(); - let top = active(&s).id; - let locked = |s: &Session, id: LayerId| doc(s).layer(id).unwrap().locks.transparency; - assert_eq!(s.execute("layer.toggleLockTransparency", json!({})).unwrap()["locked"], true); - assert!(locked(&s, top)); - s.execute("layer.toggleLockTransparency", json!({})).unwrap(); - assert!(!locked(&s, top)); - s.undo(); - assert!(locked(&s, top), "one undoable step each"); - let bg_locks = doc(&s).layer(bg).unwrap().locks; - assert!(s.execute("layer.toggleLockTransparency", json!({"layer": bg.0})).is_err()); - assert_eq!(doc(&s).layer(bg).unwrap().locks, bg_locks, "the Background is left alone"); - assert!(s.execute("layer.toggleLockTransparency", json!({"layer": u64::MAX})).is_err()); - } - - #[test] - fn layer_utilities() { - let mut s = session(8); - // Layer from Background. - assert!(s.is_enabled("layer.new.layerFromBackground")); - s.execute("layer.new.layerFromBackground", json!({})).unwrap(); - assert_eq!(doc(&s).layers[0].name, "Layer 0"); - assert!(!doc(&s).layers[0].locks.transparency); - assert!(!s.is_enabled("layer.new.layerFromBackground")); - // Copy / paste style and hide all effects. - s.execute("layer.layerStyle.dropShadow", json!({})).unwrap(); - s.execute("layer.layerStyle.copyLayerStyle", json!({})).unwrap(); - let top = doc(&s).layers[1].id; - s.execute("layer.layerStyle.pasteLayerStyle", json!({"layer": top.0})).unwrap(); - assert_eq!(doc(&s).layers[1].effects.items.len(), 1); - s.execute("layer.layerStyle.hideAllEffects", json!({})).unwrap(); - assert!(doc(&s).walk().iter().all(|(_, _, l)| l.effects.items.is_empty() || !l.effects.enabled)); - // Mask toggles. - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("layer.layerMask.enabled", json!({})).unwrap(); - assert!(!active(&s).mask.as_ref().unwrap().enabled); - s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap(); - assert!(!active(&s).mask.as_ref().unwrap().linked); - // Hide, delete hidden, delete empty. - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("layer.hideLayers", json!({})).unwrap(); - assert!(!active(&s).visible); - assert_eq!(s.execute("layer.delete.hiddenLayers", json!({})).unwrap()["deleted"], 1); - s.execute("layer.new.layer", json!({})).unwrap(); - let n = doc(&s).layer_count(); - assert_eq!(s.execute("file.scripts.deleteAllEmptyLayers", json!({})).unwrap()["deleted"], 1); - assert_eq!(doc(&s).layer_count(), n - 1); - } - - #[test] - fn ungroup_restores_children_in_order() { - let mut s = session(8); - let a = active(&s).id; - s.execute("layer.groupLayers", json!({})).unwrap(); - assert!(active(&s).is_group()); - s.execute("layer.ungroupLayers", json!({})).unwrap(); - assert_eq!(s.active().unwrap().active_layer, Some(a)); - assert!(doc(&s).layers.iter().all(|l| !l.is_group())); - assert_eq!(doc(&s).layers.len(), 2); - } - - #[test] - fn reveal_all_grows_the_canvas() { - let mut s = session(8); - s.execute("layer.translate", json!({"dx": 0, "dy": 0})).ok(); - paint_square(&mut s, Rect::new(-5, 0, 10, 10), [1.0, 0.0, 0.0, 1.0]); - assert_eq!(reveal_all_bounds(doc(&s)), Rect::new(-5, 0, 40, 30)); - let steps = s.active().unwrap().history.past_len(); - s.execute("image.revealAll", json!({})).unwrap(); - assert_eq!((doc(&s).size.width, doc(&s).size.height), (45, 30)); - let history = &s.active().unwrap().history; - assert_eq!(history.past_len(), steps + 1, "one step"); - assert_eq!(history.entries().last().map(String::as_str), Some("Reveal All"), "named as in Photoshop, not Crop"); - assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], false); - } - - #[test] - fn reveal_all_skips_erased_pixels() { - // #9379: the Eraser only clears alpha, so erased pixels keep their colour bytes; Reveal - // All grew the canvas to them although nothing there is visible. - // No Background: its off-canvas pixels are opaque and would be revealed anyway. - for depth in [8, 16, 32] { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth, "background": "transparent"})).unwrap(); - paint_square(&mut s, Rect::new(0, 0, 40, 30), [1.0, 0.0, 0.0, 1.0]); - let erase = json!({"points": [[32, -10], [32, 40]], "size": 28, "erase": true, "brush": {"hardness": 1.0}}); - s.execute("paint.stroke", erase).unwrap(); - assert_eq!(pixel(&s, 30, 15)[3], 0.0, "{depth}: erased"); - s.execute("image.canvasSize", json!({"width": 20, "height": 30, "anchor": "topLeft"})).unwrap(); - assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], false, "{depth}"); - assert_eq!((doc(&s).size.width, doc(&s).size.height), (20, 30), "{depth}"); - // A pixel that is only partly erased is still there to reveal. - paint_square(&mut s, Rect::new(25, 5, 26, 6), [0.0, 0.0, 1.0, 0.5]); - assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], true, "{depth}"); - assert_eq!((doc(&s).size.width, doc(&s).size.height), (26, 30), "{depth}"); - } - } - - #[test] - fn rasterize_fill_and_all_in_one_step() { - let mut s = session(8); - s.execute("layer.newFillLayer.solidColor", json!({"color": "#00ff00"})).unwrap(); - s.execute("layer.newFillLayer.solidColor", json!({"color": "#0000ff"})).unwrap(); - s.execute("layer.rasterize.fillContent", json!({})).unwrap(); - assert!(matches!(active(&s).content, LayerContent::Raster(_))); - assert_eq!(pixel(&s, 3, 3), vec![0.0, 0.0, 1.0, 1.0]); - assert!(s.execute("layer.rasterize.type", json!({})).is_err()); - let steps = s.active().unwrap().history.past_len(); - assert_eq!(s.execute("layer.rasterize.allLayers", json!({})).unwrap()["rasterized"], 1); - assert_eq!(s.active().unwrap().history.past_len(), steps + 1); - assert!(doc(&s).walk().iter().all(|(_, _, l)| !matches!(l.content, LayerContent::Fill(_)))); - } - - #[test] - fn rasterize_smart_object_layer() { - let mut s = session(8); - s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); - let px_before = pixel(&s, 5, 5); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - assert!(matches!(active(&s).content, LayerContent::Smart(_))); - s.execute("layer.rasterize.smartObject", json!({})).unwrap(); - assert!(matches!(active(&s).content, LayerContent::Raster(_))); - let px_after = pixel(&s, 5, 5); - assert_eq!(px_after, px_before); - - // Case 2: New layer above background - let mut s2 = session(8); - s2.execute("layer.new.layer", json!({})).unwrap(); - s2.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - s2.execute("edit.fill", json!({"contents": "color", "color": "#00ff00"})).unwrap(); - s2.execute("select.deselect", json!({})).unwrap(); - let px_mid = pixel(&s2, 20, 20); - assert_eq!(px_mid[1], 1.0); // green - s2.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - assert!(matches!(active(&s2).content, LayerContent::Smart(_))); - s2.execute("layer.rasterize.smartObject", json!({})).unwrap(); - assert!(matches!(active(&s2).content, LayerContent::Raster(_))); - let px_after_rast = pixel(&s2, 20, 20); - assert_eq!(px_after_rast, px_mid); - - // Case 3: Shape layer converted to smart object then rasterized - let mut s3 = session(8); - s3.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 40], "fill": "#0000ff"})).unwrap(); - let px_shape = pixel(&s3, 20, 20); - s3.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - assert!(matches!(active(&s3).content, LayerContent::Smart(_))); - s3.execute("layer.rasterize.layer", json!({})).unwrap(); - assert!(matches!(active(&s3).content, LayerContent::Raster(_))); - let px_after_shape = pixel(&s3, 20, 20); - assert_eq!(px_after_shape, px_shape); - - // Case 4: Transformed smart object - let mut s4 = session(8); - s4.execute("layer.new.layer", json!({})).unwrap(); - s4.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - s4.execute("edit.fill", json!({"contents": "color", "color": "#ffff00"})).unwrap(); - s4.execute("select.deselect", json!({})).unwrap(); - s4.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - // Move smart object by 10, 10 - s4.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 10]})).unwrap(); - s4.execute("layer.rasterize.smartObject", json!({})).unwrap(); - assert!(matches!(active(&s4).content, LayerContent::Raster(_))); - assert_eq!(pixel(&s4, 30, 30), vec![1.0, 1.0, 0.0, 1.0]); - } -} +mod tests; diff --git a/crates/engine/src/extra_cmds/tests.rs b/crates/engine/src/extra_cmds/tests.rs new file mode 100644 index 0000000000..b4c6908d3f --- /dev/null +++ b/crates/engine/src/extra_cmds/tests.rs @@ -0,0 +1,820 @@ +use super::*; + +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +#[test] +fn equalize_average_and_clouds_edit_the_targeted_channel() { + // #935: these four ran through `map_pixels`, which always rewrote the active layer, so + // with an alpha channel or the Quick Mask targeted they changed the layer and left the + // channel alone. + let cmds = ["image.adjustments.equalize", "filter.blur.average", "filter.render.clouds", "filter.render.differenceClouds"]; + for depth in [8, 16, 32] { + for target in ["quickMask", "alpha", "mask"] { + for cmd in cmds { + let mut s = session(depth); + 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 { + "quickMask" => { + s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + json!({"seed": 1}) + } + "alpha" => { + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + s.execute("channel.target", json!({"channel": 0})).unwrap(); + json!({"seed": 1}) + } + _ => { + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + json!({"seed": 1, "target": "mask"}) + } + }; + // 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| { + let (surf, _) = crate::channel_cmds::target_surface(doc, *active, &edit_target).unwrap(); + surf.fill_rect(Rect::new(0, 0, 20, 30), &[0.4]); + surf.fill_rect(Rect::new(20, 0, 40, 30), &[0.5]); + Ok(()) + }) + .unwrap(); + let full = Rect::new(0, 0, 40, 30); + let read = |s: &Session| { + let d = doc(s); + let layer = d.layer(s.active().unwrap().active_layer.unwrap()).unwrap(); + let t = match target { + "quickMask" => d.quick_mask.as_ref().unwrap().surface.read_region(full), + "alpha" => d.channels[0].surface.read_region(full), + _ => layer.mask.as_ref().unwrap().surface.read_region(full), + }; + (layer.surface().unwrap().read_region(full), t) + }; + let ((layer0, target0), past) = (read(&s), s.active().unwrap().history.past_len()); + s.execute(cmd, p).unwrap(); + let (layer1, target1) = read(&s); + 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"); + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{case}"); + s.undo(); + assert_eq!(read(&s).1, target0, "{case}: undo restores the target"); + } + } + } +} + +fn active(s: &Session) -> &Layer { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap() +} + +fn pixel(s: &Session, x: i32, y: i32) -> Vec { + active(s).surface().unwrap().pixel(x, y) +} + +fn paint_square(s: &mut Session, r: Rect, c: [f32; 4]) { + s.edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(r, &c); + Ok(()) + }) + .unwrap(); +} + +#[test] +fn stroke_locations_at_several_depths() { + for depth in [8, 16, 32] { + for (loc, inside, outside) in [("inside", 1.0, 0.0), ("outside", 0.0, 1.0), ("center", 1.0, 1.0)] { + let mut s = session(depth); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + s.execute("edit.stroke", json!({"width": 2, "color": "#ff0000", "location": loc})).unwrap(); + assert!((pixel(&s, 10, 15)[3] - inside).abs() < 0.02, "{depth} {loc} inside {:?}", pixel(&s, 10, 15)); + assert!((pixel(&s, 9, 15)[3] - outside).abs() < 0.02, "{depth} {loc} outside {:?}", pixel(&s, 9, 15)); + assert_eq!(pixel(&s, 15, 15)[3], 0.0, "centre untouched"); + } + } + // Without a selection the layer's opaque edge is stroked. + let mut s = session(8); + paint_square(&mut s, Rect::new(10, 10, 20, 20), [0.0, 0.0, 1.0, 1.0]); + s.execute("edit.stroke", json!({"width": 3, "color": "#00ff00", "location": "outside"})).unwrap(); + assert_eq!(pixel(&s, 8, 15), vec![0.0, 1.0, 0.0, 1.0]); + assert_eq!(pixel(&s, 15, 15), vec![0.0, 0.0, 1.0, 1.0]); +} + +/// Photoshop's Edit › Stroke on a selection (checked by hand): Center puts ceil(w/2) px inside +/// and floor(w/2) outside (1 px is all inside), fractional widths round up, and every stroked +/// pixel is fully opaque, on every edge, horizontal ones included. Inside and Outside are +/// w px on their side. +#[test] +fn stroke_widths_are_whole_opaque_pixels_like_photoshop() { + // Selection x 10..30, y 10..30; the edge pixels inside are 10 and 29 on each axis. + let band = |loc: &str, w: i32| -> (i32, i32) { + match loc { + "inside" => (w, 0), + "outside" => (0, w), + _ => ((w + 1) / 2, w / 2), + } + }; + let mut wrong = Vec::new(); + for depth in [8, 16, 32] { + for loc in ["center", "inside", "outside"] { + for (param, w) in [(json!(1), 1), (json!(2), 2), (json!(3), 3), (json!(4), 4), (json!(5), 5), (json!(0.5), 1), (json!(2.5), 3)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 50, "height": 50, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("edit.stroke", json!({"width": param, "color": "#ff0000", "location": loc})).unwrap(); + let (inside, outside) = band(loc, w); + // (edge pixel inside, step inward) for left, right, top and bottom; the other + // coordinate is the middle of the edge. + for (name, first_in, inward, horizontal) in + [("left", 10, 1, false), ("right", 29, -1, false), ("top", 10, 1, true), ("bottom", 29, -1, true)] + { + for k in -7..7 { + // k ≥ 0: k px inside from the edge; k < 0: -k px outside. + let c = first_in + k * inward; + let (x, y) = if horizontal { (20, c) } else { (c, 20) }; + let want = if (k >= 0 && k < inside) || (k < 0 && -k <= outside) { 1.0 } else { 0.0 }; + let a = pixel(&s, x, y)[3]; + if (a - want).abs() > 0.004 { + wrong.push(format!("{depth}-bit {loc} width {param} {name} edge, {k:+} px: alpha {a}, want {want}")); + } + } + } + } + } + } + assert!(wrong.is_empty(), "{} pixels differ from Photoshop:\n{}", wrong.len(), wrong.iter().take(40).cloned().collect::>().join("\n")); +} + +/// Photoshop's 6 px Outside stroke of a 14 px circle selection made without anti-aliasing, +/// read pixel by pixel from Photoshop (`#` stroked, `.` not; the hole is the selection). A +/// hard selection gives a hard stroke: a pixel is stroked when its centre is less than +/// width + 1 from a selected pixel's centre (no partial pixels on the curve). +const PS_CIRCLE_OUTSIDE_6: [&str; 31] = [ + "..................................", + "..................................", + "...........############...........", + "..........##############..........", + ".........################.........", + "........##################........", + ".......####################.......", + "......######################......", + ".....#########......#########.....", + "....#########........#########....", + "....########..........########....", + "....#######............#######....", + "....######..............######....", + "....######..............######....", + "....######..............######....", + "....######..............######....", + "....######..............######....", + "....######..............######....", + "....#######............#######....", + "....########..........########....", + "....#########........#########....", + ".....#########......#########.....", + "......######################......", + ".......####################.......", + "........##################........", + ".........################.........", + "..........##############..........", + "...........############...........", + "..................................", + "..................................", + "..................................", +]; + +/// Photoshop's 3 px Inside stroke of the same 14 px hard circle (the selection is the ring +/// plus its hole). Inside, a pixel is stroked when its centre is less than width + ½ from an +/// unselected pixel's: that offset is the one fitting this, the 5 px and the 6 px samples +/// (any value from +0.41 to +0.60), so 6 px fills this circle (its deepest pixel is 6.4 px in). +const PS_CIRCLE_INSIDE_3: [&str; 17] = [ + "...................", + "......######.......", + ".....########......", + "....##########.....", + "...####....####....", + "..####......####...", + "..###........###...", + "..###........###...", + "..###........###...", + "..###........###...", + "..####......####...", + "...####....####....", + "....##########.....", + ".....########......", + "......######.......", + "...................", + "...................", +]; + +/// The selection of a Photoshop sample grid: an Outside stroke's hole, or an Inside stroke's +/// ring and hole. +fn grid_selection(rows: &[&str], outside: bool) -> Vec { + let (w, h) = (rows[0].len(), rows.len()); + let mut mask = vec![0.0f32; w * h]; + for (y, row) in rows.iter().enumerate() { + let b = row.as_bytes(); + if let (Some(first), Some(last)) = (b.iter().position(|c| *c == b'#'), b.iter().rposition(|c| *c == b'#')) { + for x in first..=last { + if !outside || b[x] == b'.' { + mask[y * w + x] = 1.0; + } + } + } + } + mask +} + +/// Strokes `mask` as the selection of a `w` × `h` layer and returns its alpha per pixel. +fn stroke_alpha(mask: &[f32], w: usize, h: usize, depth: u32, params: Value) -> Vec { + let mut s = Session::new(); + s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("select", |doc, _| { + doc.selection = Some(sel::mask_to_surface(mask, doc.bounds())); + Ok(()) + }) + .unwrap(); + s.execute("edit.stroke", params).unwrap(); + (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).map(|(x, y)| pixel(&s, x as i32, y as i32)[3]).collect() +} + +#[test] +fn a_hard_circle_strokes_inside_like_photoshop() { + let rows = PS_CIRCLE_INSIDE_3; + let (w, h) = (rows[0].len(), rows.len()); + let mask = grid_selection(&rows, false); + for depth in [8, 16, 32] { + let got = stroke_alpha(&mask, w, h, depth, json!({"width": 3, "color": "#000000", "location": "inside"})); + let wrong: Vec = rows + .iter() + .enumerate() + .flat_map(|(y, row)| row.bytes().enumerate().map(move |(x, c)| (x, y, c))) + .filter_map(|(x, y, c)| { + let want = if c == b'#' { 1.0 } else { 0.0 }; + let a = got[y * w + x]; + ((a - want).abs() > 0.004).then(|| format!("({x}, {y}): {a}, Photoshop {want}")) + }) + .collect(); + assert!(wrong.is_empty(), "{depth}-bit: {} pixels differ from Photoshop: {wrong:?}", wrong.len()); + // Checked in Photoshop: a 5 px Inside stroke leaves a plus-shaped hole of 12 pixels in + // the middle (rows 2, 4, 4, 2 wide), and 6 px fills the whole circle. + let hole = [(8, 6), (9, 6), (7, 7), (8, 7), (9, 7), (10, 7), (7, 8), (8, 8), (9, 8), (10, 8), (8, 9), (9, 9)]; + let five = stroke_alpha(&mask, w, h, depth, json!({"width": 5, "color": "#000000", "location": "inside"})); + for (i, m) in mask.iter().enumerate() { + let stroked = *m > 0.0 && !hole.contains(&(i % w, i / w)); + assert_eq!(five[i] > 0.996, stroked, "{depth}-bit 5 px Inside at ({}, {})", i % w, i / w); + } + let full = stroke_alpha(&mask, w, h, depth, json!({"width": 6, "color": "#000000", "location": "inside"})); + for (i, m) in mask.iter().enumerate() { + assert_eq!(full[i] > 0.996, *m > 0.0, "{depth}-bit 6 px Inside at ({}, {})", i % w, i / w); + } + } +} + +#[test] +fn a_hard_circle_strokes_like_photoshop() { + let rows = PS_CIRCLE_OUTSIDE_6; + let (w, h) = (rows[0].len(), rows.len()); + // The selection: the `.` cells enclosed by the ring on each row. + let mask = grid_selection(&rows, true); + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": w, "height": h, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("select", |doc, _| { + doc.selection = Some(sel::mask_to_surface(&mask, doc.bounds())); + Ok(()) + }) + .unwrap(); + s.execute("edit.stroke", json!({"width": 6, "color": "#000000", "location": "outside"})).unwrap(); + let mut wrong = Vec::new(); + for (y, row) in rows.iter().enumerate() { + for (x, c) in row.bytes().enumerate() { + let want = if c == b'#' { 1.0 } else { 0.0 }; + let a = pixel(&s, x as i32, y as i32)[3]; + if (a - want).abs() > 0.004 { + wrong.push(format!("({x}, {y}): {a}, Photoshop {want}")); + } + } + } + assert!(wrong.is_empty(), "{depth}-bit: {} pixels differ from Photoshop: {wrong:?}", wrong.len()); + } +} + +/// Select All, then Stroke › Inside draws a border around the canvas (a common Photoshop +/// technique): the canvas edge is a selection edge like any other, on all four sides. +#[test] +fn stroking_a_selection_at_the_canvas_edge_draws_that_edge() { + for depth in [8, 16, 32] { + for (loc, w, inside) in [("inside", 3, 3), ("center", 3, 2), ("center", 1, 1)] { + let mut s = session(depth); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.stroke", json!({"width": w, "color": "#ff0000", "location": loc})).unwrap(); + // 40 × 30 canvas: k px in from each side, in the middle of the side. + for name in ["left", "right", "top", "bottom"] { + for k in 0..6 { + let (x, y) = match name { + "left" => (k, 15), + "right" => (39 - k, 15), + "top" => (20, k), + _ => (20, 29 - k), + }; + let want = if k < inside { 1.0 } else { 0.0 }; + let a = pixel(&s, x, y)[3]; + assert!((a - want).abs() < 0.004, "{depth}-bit {loc} {w} px, {name} side, {k} px in: alpha {a}, want {want}"); + } + } + } + } +} + +#[test] +fn stroke_uses_fill_blending_and_preserves_transparency_at_every_depth() { + for depth in [8, 16, 32] { + let mut s = session(depth); + paint_square(&mut s, Rect::new(10, 10, 20, 20), [0.5, 0.5, 0.5, 1.0]); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + + let past = s.active().unwrap().history.past_len(); + s.execute( + "edit.stroke", + json!({"width": 2, "color": "#ffffff", "location": "inside", "mode": "multiply", "opacity": 100, "preserveTransparency": true}), + ) + .unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "Stroke is one history step"); + let edge = pixel(&s, 10, 15); + assert!((edge[0] - 0.5).abs() < 0.015, "{depth}-bit Multiply must preserve gray: {edge:?}"); + assert_eq!(edge[3], 1.0); + + s.execute("edit.stroke", json!({"width": 2, "color": "#ffffff", "location": "outside", "preserveTransparency": true})).unwrap(); + assert_eq!(pixel(&s, 9, 15)[3], 0.0, "{depth}-bit transparency lock prevents new outer pixels"); + + s.execute("edit.stroke", json!({"width": 2, "color": "#ffffff", "location": "outside", "opacity": 50})).unwrap(); + let out = pixel(&s, 9, 15); + assert!((out[3] - 0.5).abs() < 0.015, "{depth}-bit 50% stroke opacity: {out:?}"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(pixel(&s, 9, 15)[3], 0.0); + } +} + +#[test] +fn stroke_rejects_invalid_blending_options_without_modifying_the_document() { + let mut s = session(8); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + let past = s.active().unwrap().history.past_len(); + for params in [ + json!({"mode": "unknown-mode"}), + json!({"mode": 42}), + json!({"mode": "passThrough"}), + json!({"opacity": "lots"}), + json!({"preserveTransparency": "true"}), + ] { + assert!(s.execute("edit.stroke", params.clone()).is_err(), "{params}"); + assert_eq!(s.active().unwrap().history.past_len(), past, "{params} should not create a history step"); + } +} + +#[test] +fn transform_presets_are_exact() { + let mut s = session(8); + paint_square(&mut s, Rect::new(10, 10, 20, 14), [1.0, 0.0, 0.0, 1.0]); + paint_square(&mut s, Rect::new(10, 10, 11, 11), [0.0, 1.0, 0.0, 1.0]); + s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); + assert_eq!(pixel(&s, 19, 10), vec![0.0, 1.0, 0.0, 1.0]); + s.execute("edit.transform.flipVertical", json!({})).unwrap(); + assert_eq!(pixel(&s, 19, 13), vec![0.0, 1.0, 0.0, 1.0]); + s.execute("edit.transform.rotate180", json!({})).unwrap(); + assert_eq!(pixel(&s, 10, 10), vec![0.0, 1.0, 0.0, 1.0]); + s.execute("edit.transform.rotate90Cw", json!({})).unwrap(); + let b = active(&s).surface().unwrap().content_bounds(); + assert_eq!((b.width(), b.height()), (4, 10)); + // Top-left corner goes to the top-right after a clockwise turn. + assert_eq!(pixel(&s, b.x1 - 1, b.y0), vec![0.0, 1.0, 0.0, 1.0]); + s.execute("edit.transform.rotate90Ccw", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); + assert_eq!(pixel(&s, 10, 10), vec![0.0, 1.0, 0.0, 1.0]); +} + +/// #6928: with a selection, the presets flip and turn about the selection's own bounds, as +/// in Photoshop: Select All mirrors across the canvas, a marquee across its own centre. +/// Without a selection they keep turning about the content (above). +#[test] +fn transform_presets_turn_about_the_selection() { + let mut s = session(8); + paint_square(&mut s, Rect::new(10, 10, 20, 14), [1.0, 0.0, 0.0, 1.0]); + paint_square(&mut s, Rect::new(10, 10, 11, 11), [0.0, 1.0, 0.0, 1.0]); + let green = vec![0.0, 1.0, 0.0, 1.0]; + // Select All on the 40 × 30 canvas: across the canvas's centre lines. + s.execute("select.all", json!({})).unwrap(); + let past = s.active().unwrap().history.past_len(); + s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(20, 10, 30, 14)); + assert_eq!(pixel(&s, 29, 10), green); + assert_eq!(s.active().unwrap().history.past_len(), past + 1, "one undo step"); + s.execute("edit.transform.flipVertical", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(20, 16, 30, 20)); + assert_eq!(pixel(&s, 29, 19), green); + s.execute("edit.transform.rotate180", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); + assert_eq!(pixel(&s, 10, 10), green); + // A marquee (0, 0)–(24, 30) holding the whole square: across x = 12. + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 24, "height": 30})).unwrap(); + s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(4, 10, 14, 14)); + assert_eq!(pixel(&s, 13, 10), green); + // Undo puts it back where it was. + s.undo(); + assert_eq!(active(&s).surface().unwrap().content_bounds(), Rect::new(10, 10, 20, 14)); + // A targeted alpha channel turns about the selection's bounds too. + s.execute("channel.new", json!({})).unwrap(); + s.edit("paint channel", |doc, _| { + doc.channels[0].surface.fill_rect(Rect::new(10, 10, 20, 20), &[1.0]); + Ok(()) + }) + .unwrap(); + s.execute("channel.target", json!({"channel": 0})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.channels[0].surface.content_bounds(), Rect::new(20, 10, 30, 20)); +} + +#[test] +fn reselect_restores_the_last_selection() { + let mut s = session(8); + assert!(!s.is_enabled("select.reselect")); + s.execute("select.rect", json!({"x": 2, "y": 3, "width": 5, "height": 6})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + assert!(doc(&s).selection.is_none()); + s.execute("select.reselect", json!({})).unwrap(); + assert_eq!(doc(&s).selection.as_ref().unwrap().content_bounds(), Rect::new(2, 3, 7, 9)); + assert!(!s.is_enabled("select.reselect"), "nothing to reselect while a selection exists"); +} + +#[test] +fn equalize_spreads_values() { + for depth in [8, 16] { + let mut s = session(depth); + paint_square(&mut s, Rect::new(0, 0, 40, 15), [0.4, 0.4, 0.4, 1.0]); + paint_square(&mut s, Rect::new(0, 15, 40, 30), [0.5, 0.5, 0.5, 1.0]); + s.execute("image.adjustments.equalize", json!({})).unwrap(); + let (dark, light) = (pixel(&s, 1, 1)[0], pixel(&s, 1, 20)[0]); + assert!(dark < 0.05 && light > 0.95, "{depth}: {dark} {light}"); + } +} + +/// A selection masks Clouds but doesn't change their size: inside it they are the canvas's +/// clouds, as when Clouds sized itself by the document (before it became a filter). +#[test] +fn clouds_in_a_selection_are_the_canvas_clouds() { + // Big enough that the canvas (cloud size 100 px) and the selection (16 px) size differently. + let big = |depth: u32| { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s + }; + for depth in [8, 16, 32] { + let mut whole = big(depth); + whole.execute("filter.render.clouds", json!({"seed": 4})).unwrap(); + let mut s = big(depth); + s.execute("select.rect", json!({"x": 50, "y": 40, "width": 60, "height": 50})).unwrap(); + s.execute("filter.render.clouds", json!({"seed": 4})).unwrap(); + for (x, y) in [(50, 40), (75, 60), (100, 85), (109, 89)] { + let (a, b) = (pixel(&s, x, y), pixel(&whole, x, y)); + assert!((0..4).all(|c| (a[c] - b[c]).abs() < 1e-3), "depth {depth} at {x},{y}: {a:?} vs {b:?}"); + } + assert_eq!(pixel(&s, 300, 200)[3], 0.0, "outside the selection the layer stays empty"); + } +} + +#[test] +fn average_and_clouds() { + let mut s = session(8); + paint_square(&mut s, Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 1.0]); + paint_square(&mut s, Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 1.0]); + s.execute("filter.blur.average", json!({})).unwrap(); + let p = pixel(&s, 5, 5); + assert!((p[0] - 0.5).abs() < 0.01 && (p[2] - 0.5).abs() < 0.01, "{p:?}"); + s.execute("filter.render.clouds", json!({"seed": 3})).unwrap(); + let vals: Vec = (0..40).map(|x| pixel(&s, x, 12)[0]).collect(); + let (lo, hi) = vals.iter().fold((1.0f32, 0.0f32), |(a, b), v| (a.min(*v), b.max(*v))); + assert!(hi - lo > 0.05, "clouds vary: {lo}..{hi}"); + assert!(vals.windows(2).all(|w| (w[0] - w[1]).abs() < 0.2), "clouds are smooth"); + // Difference Clouds over itself with the same seed cancels to black. + s.execute("filter.render.differenceClouds", json!({"seed": 3})).unwrap(); + assert!(pixel(&s, 7, 7)[..3].iter().all(|v| *v < 0.01), "{:?}", pixel(&s, 7, 7)); +} + +#[test] +fn paste_into_masks_to_the_selection() { + let mut s = session(8); + paint_square(&mut s, Rect::new(0, 0, 10, 10), [1.0, 0.0, 0.0, 1.0]); + s.execute("select.all", json!({})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + s.execute("select.rect", json!({"x": 20, "y": 10, "width": 8, "height": 8})).unwrap(); + s.execute("edit.pasteSpecial.pasteInto", json!({})).unwrap(); + let l = active(&s); + let m = l.mask.as_ref().unwrap(); + assert!(!m.linked); + assert_eq!(m.surface.content_bounds(), Rect::new(20, 10, 28, 18)); + assert_eq!(m.value(0, 0), 0.0); + assert!(doc(&s).selection.is_none()); + assert_eq!(s.active().unwrap().history.past_len(), steps + 2, "select + one Paste Into step"); + // Paste Outside reveals everything but the selection. + s.execute("select.rect", json!({"x": 20, "y": 10, "width": 8, "height": 8})).unwrap(); + s.execute("edit.pasteSpecial.pasteOutside", json!({})).unwrap(); + let m = active(&s).mask.as_ref().unwrap(); + assert_eq!((m.value(0, 0), m.value(22, 12)), (1.0, 0.0)); +} + +#[test] +fn option_click_eye_shows_one_layer_then_restores() { + let mut s = session(8); + s.execute("layer.new.layer", json!({})).unwrap(); + let ids: Vec = doc(&s).layers.iter().map(|l| l.id).collect(); + // Background, Layer 1 (hidden beforehand), Layer 2. + s.execute("layer.hideLayers", json!({"layer": ids[1].0})).unwrap(); + let vis = |s: &Session| doc(s).layers.iter().map(|l| l.visible).collect::>(); + assert_eq!(s.execute("layer.showOnly", json!({"layer": ids[1].0})).unwrap()["shownAlone"], true); + assert_eq!(vis(&s), [false, true, false]); + // Another eye moves the solo; the original snapshot survives. + s.execute("layer.showOnly", json!({"layer": ids[2].0})).unwrap(); + assert_eq!(vis(&s), [false, false, true]); + assert_eq!(s.execute("layer.showOnly", json!({"layer": ids[2].0})).unwrap()["shownAlone"], false); + assert_eq!(vis(&s), [true, false, true], "restored, with Layer 1 still hidden"); + // One history step each way. + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(vis(&s), [false, false, true]); +} + +#[test] +fn show_only_keeps_groups_and_their_contents() { + let mut s = session(8); + s.execute("layer.new.layer", json!({})).unwrap(); + let inner = active(&s).id; + let group = s.execute("layer.groupLayers", json!({"layer": inner.0})).unwrap()["layer"].as_u64().map(LayerId).unwrap(); + let shown = |s: &Session| doc(s).walk().iter().map(|(_, _, l)| l.visible).collect::>(); + // Background, Layer 1, Group 1, Layer 2 (inside the group). + s.execute("layer.showOnly", json!({"layer": inner.0})).unwrap(); + assert_eq!(shown(&s), [false, false, true, true], "the enclosing group stays visible"); + // An undo ends the solo, so the next ⌥-click solos again from the current state. + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(s.execute("layer.showOnly", json!({"layer": inner.0})).unwrap()["shownAlone"], true); + s.execute("edit.undo", json!({})).unwrap(); + // Showing a group alone leaves its contents as they are. + s.execute("layer.setProps", json!({"layer": inner.0, "visible": false})).unwrap(); + s.execute("layer.showOnly", json!({"layer": group.0})).unwrap(); + assert_eq!(shown(&s), [false, false, true, false]); + s.execute("layer.showOnly", json!({"layer": group.0})).unwrap(); + assert_eq!(shown(&s), [true, true, true, false]); +} + +#[test] +fn show_only_without_a_snapshot_shows_every_layer() { + let mut s = session(16); + let bg = doc(&s).layers[0].id; + s.execute("layer.hideLayers", json!({"layer": bg.0})).unwrap(); + // Layer 1 is already the only visible layer: ⌥-clicking it shows everything. + assert_eq!(s.execute("layer.showOnly", json!({})).unwrap()["shownAlone"], false); + assert!(doc(&s).layers.iter().all(|l| l.visible)); + assert!(s.execute("layer.showOnly", json!({"layer": u64::MAX})).is_err()); + assert!(Session::new().execute("layer.showOnly", json!({})).is_err()); +} + +#[test] +fn a_mask_turns_the_background_into_a_layer() { + for (cmd, needs_selection) in [ + ("layer.layerMask.revealAll", false), + ("layer.layerMask.hideAll", false), + ("layer.layerMask.revealSelection", true), + ("layer.layerMask.hideSelection", true), + ] { + let mut s = session(8); + let bg = doc(&s).layers[0].id; + if needs_selection { + s.execute("select.rect", json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap(); + } + s.execute(cmd, json!({"layer": bg.0})).unwrap(); + let l = &doc(&s).layers[0]; + assert!(l.mask.is_some() && l.name == "Layer 0" && !l.locks.transparency && !l.locks.position, "{cmd}"); + assert!(!s.is_enabled("layer.new.layerFromBackground"), "{cmd}"); + // One step: undo brings the locked Background back, without a mask. + assert!(s.undo()); + let l = &doc(&s).layers[0]; + assert!(l.mask.is_none() && l.name == "Background" && l.locks.transparency, "{cmd}"); + } + // Other layers keep their name and locks. + let mut s = session(8); + let top = doc(&s).layers[1].id; + s.execute("layer.setProps", json!({"layer": top.0, "locks": {"position": true}})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({"layer": top.0})).unwrap(); + let l = doc(&s).layer(top).unwrap(); + assert!(l.mask.is_some() && l.name != "Layer 0" && l.locks.position); + assert_eq!(doc(&s).layers[0].name, "Background"); +} + +#[test] +fn hide_layers_toggles_once_every_target_is_hidden() { + let mut s = session(8); + s.execute("layer.new.layer", json!({})).unwrap(); + let b = active(&s).id; + let visible = |s: &Session| doc(s).layer(b).unwrap().visible; + // Select › All Layers leaves out the Background, as in Photoshop. + let all = |s: &Session| crate::layer_multi_cmds::selected(s).iter().map(|id| doc(s).layer(*id).unwrap().visible).collect::>(); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(!visible(&s)); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(visible(&s), "⌘, again shows it"); + // Several selected: any one still shown means hide them all; then they all come back. + s.execute("layer.hideLayers", json!({"layer": b.0})).unwrap(); + s.execute("select.allLayers", json!({})).unwrap(); + assert!(all(&s).len() > 1); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(all(&s).iter().all(|v| !v)); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(all(&s).iter().all(|v| *v)); +} + +#[test] +fn slash_toggles_lock_transparent_pixels_but_not_on_the_background() { + let mut s = session(8); + let bg = doc(&s).layers[0].id; + assert!(doc(&s).is_background(bg)); + s.execute("layer.new.layer", json!({})).unwrap(); + let top = active(&s).id; + let locked = |s: &Session, id: LayerId| doc(s).layer(id).unwrap().locks.transparency; + assert_eq!(s.execute("layer.toggleLockTransparency", json!({})).unwrap()["locked"], true); + assert!(locked(&s, top)); + s.execute("layer.toggleLockTransparency", json!({})).unwrap(); + assert!(!locked(&s, top)); + s.undo(); + assert!(locked(&s, top), "one undoable step each"); + let bg_locks = doc(&s).layer(bg).unwrap().locks; + assert!(s.execute("layer.toggleLockTransparency", json!({"layer": bg.0})).is_err()); + assert_eq!(doc(&s).layer(bg).unwrap().locks, bg_locks, "the Background is left alone"); + assert!(s.execute("layer.toggleLockTransparency", json!({"layer": u64::MAX})).is_err()); +} + +#[test] +fn layer_utilities() { + let mut s = session(8); + // Layer from Background. + assert!(s.is_enabled("layer.new.layerFromBackground")); + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + assert_eq!(doc(&s).layers[0].name, "Layer 0"); + assert!(!doc(&s).layers[0].locks.transparency); + assert!(!s.is_enabled("layer.new.layerFromBackground")); + // Copy / paste style and hide all effects. + s.execute("layer.layerStyle.dropShadow", json!({})).unwrap(); + s.execute("layer.layerStyle.copyLayerStyle", json!({})).unwrap(); + let top = doc(&s).layers[1].id; + s.execute("layer.layerStyle.pasteLayerStyle", json!({"layer": top.0})).unwrap(); + assert_eq!(doc(&s).layers[1].effects.items.len(), 1); + s.execute("layer.layerStyle.hideAllEffects", json!({})).unwrap(); + assert!(doc(&s).walk().iter().all(|(_, _, l)| l.effects.items.is_empty() || !l.effects.enabled)); + // Mask toggles. + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("layer.layerMask.enabled", json!({})).unwrap(); + assert!(!active(&s).mask.as_ref().unwrap().enabled); + s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap(); + assert!(!active(&s).mask.as_ref().unwrap().linked); + // Hide, delete hidden, delete empty. + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(!active(&s).visible); + assert_eq!(s.execute("layer.delete.hiddenLayers", json!({})).unwrap()["deleted"], 1); + s.execute("layer.new.layer", json!({})).unwrap(); + let n = doc(&s).layer_count(); + assert_eq!(s.execute("file.scripts.deleteAllEmptyLayers", json!({})).unwrap()["deleted"], 1); + assert_eq!(doc(&s).layer_count(), n - 1); +} + +#[test] +fn ungroup_restores_children_in_order() { + let mut s = session(8); + let a = active(&s).id; + s.execute("layer.groupLayers", json!({})).unwrap(); + assert!(active(&s).is_group()); + s.execute("layer.ungroupLayers", json!({})).unwrap(); + assert_eq!(s.active().unwrap().active_layer, Some(a)); + assert!(doc(&s).layers.iter().all(|l| !l.is_group())); + assert_eq!(doc(&s).layers.len(), 2); +} + +#[test] +fn reveal_all_grows_the_canvas() { + let mut s = session(8); + s.execute("layer.translate", json!({"dx": 0, "dy": 0})).ok(); + paint_square(&mut s, Rect::new(-5, 0, 10, 10), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(reveal_all_bounds(doc(&s)), Rect::new(-5, 0, 40, 30)); + let steps = s.active().unwrap().history.past_len(); + s.execute("image.revealAll", json!({})).unwrap(); + assert_eq!((doc(&s).size.width, doc(&s).size.height), (45, 30)); + let history = &s.active().unwrap().history; + assert_eq!(history.past_len(), steps + 1, "one step"); + assert_eq!(history.entries().last().map(String::as_str), Some("Reveal All"), "named as in Photoshop, not Crop"); + assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], false); +} + +#[test] +fn reveal_all_skips_erased_pixels() { + // #9379: the Eraser only clears alpha, so erased pixels keep their colour bytes; Reveal + // All grew the canvas to them although nothing there is visible. + // No Background: its off-canvas pixels are opaque and would be revealed anyway. + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth, "background": "transparent"})).unwrap(); + paint_square(&mut s, Rect::new(0, 0, 40, 30), [1.0, 0.0, 0.0, 1.0]); + let erase = json!({"points": [[32, -10], [32, 40]], "size": 28, "erase": true, "brush": {"hardness": 1.0}}); + s.execute("paint.stroke", erase).unwrap(); + assert_eq!(pixel(&s, 30, 15)[3], 0.0, "{depth}: erased"); + s.execute("image.canvasSize", json!({"width": 20, "height": 30, "anchor": "topLeft"})).unwrap(); + assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], false, "{depth}"); + assert_eq!((doc(&s).size.width, doc(&s).size.height), (20, 30), "{depth}"); + // A pixel that is only partly erased is still there to reveal. + paint_square(&mut s, Rect::new(25, 5, 26, 6), [0.0, 0.0, 1.0, 0.5]); + assert_eq!(s.execute("image.revealAll", json!({})).unwrap()["changed"], true, "{depth}"); + assert_eq!((doc(&s).size.width, doc(&s).size.height), (26, 30), "{depth}"); + } +} + +#[test] +fn rasterize_fill_and_all_in_one_step() { + let mut s = session(8); + s.execute("layer.newFillLayer.solidColor", json!({"color": "#00ff00"})).unwrap(); + s.execute("layer.newFillLayer.solidColor", json!({"color": "#0000ff"})).unwrap(); + s.execute("layer.rasterize.fillContent", json!({})).unwrap(); + assert!(matches!(active(&s).content, LayerContent::Raster(_))); + assert_eq!(pixel(&s, 3, 3), vec![0.0, 0.0, 1.0, 1.0]); + assert!(s.execute("layer.rasterize.type", json!({})).is_err()); + let steps = s.active().unwrap().history.past_len(); + assert_eq!(s.execute("layer.rasterize.allLayers", json!({})).unwrap()["rasterized"], 1); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); + assert!(doc(&s).walk().iter().all(|(_, _, l)| !matches!(l.content, LayerContent::Fill(_)))); +} + +#[test] +fn rasterize_smart_object_layer() { + let mut s = session(8); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + let px_before = pixel(&s, 5, 5); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + assert!(matches!(active(&s).content, LayerContent::Smart(_))); + s.execute("layer.rasterize.smartObject", json!({})).unwrap(); + assert!(matches!(active(&s).content, LayerContent::Raster(_))); + let px_after = pixel(&s, 5, 5); + assert_eq!(px_after, px_before); + + // Case 2: New layer above background + let mut s2 = session(8); + s2.execute("layer.new.layer", json!({})).unwrap(); + s2.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s2.execute("edit.fill", json!({"contents": "color", "color": "#00ff00"})).unwrap(); + s2.execute("select.deselect", json!({})).unwrap(); + let px_mid = pixel(&s2, 20, 20); + assert_eq!(px_mid[1], 1.0); // green + s2.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + assert!(matches!(active(&s2).content, LayerContent::Smart(_))); + s2.execute("layer.rasterize.smartObject", json!({})).unwrap(); + assert!(matches!(active(&s2).content, LayerContent::Raster(_))); + let px_after_rast = pixel(&s2, 20, 20); + assert_eq!(px_after_rast, px_mid); + + // Case 3: Shape layer converted to smart object then rasterized + let mut s3 = session(8); + s3.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 40], "fill": "#0000ff"})).unwrap(); + let px_shape = pixel(&s3, 20, 20); + s3.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + assert!(matches!(active(&s3).content, LayerContent::Smart(_))); + s3.execute("layer.rasterize.layer", json!({})).unwrap(); + assert!(matches!(active(&s3).content, LayerContent::Raster(_))); + let px_after_shape = pixel(&s3, 20, 20); + assert_eq!(px_after_shape, px_shape); + + // Case 4: Transformed smart object + let mut s4 = session(8); + s4.execute("layer.new.layer", json!({})).unwrap(); + s4.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s4.execute("edit.fill", json!({"contents": "color", "color": "#ffff00"})).unwrap(); + s4.execute("select.deselect", json!({})).unwrap(); + s4.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + // Move smart object by 10, 10 + s4.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 10, 10]})).unwrap(); + s4.execute("layer.rasterize.smartObject", json!({})).unwrap(); + assert!(matches!(active(&s4).content, LayerContent::Raster(_))); + assert_eq!(pixel(&s4, 30, 30), vec![1.0, 1.0, 0.0, 1.0]); +} From a94321e0f34d75a4c0922ffaf36523e92848c270 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:24 +0000 Subject: [PATCH 046/259] refactor(engine): move filters/validation.rs tests to filters/validation/tests.rs --- crates/engine/src/filters/validation.rs | 366 +----------------- crates/engine/src/filters/validation/tests.rs | 363 +++++++++++++++++ 2 files changed, 364 insertions(+), 365 deletions(-) create mode 100644 crates/engine/src/filters/validation/tests.rs diff --git a/crates/engine/src/filters/validation.rs b/crates/engine/src/filters/validation.rs index f9bc1a4eec..2744524a85 100644 --- a/crates/engine/src/filters/validation.rs +++ b/crates/engine/src/filters/validation.rs @@ -176,368 +176,4 @@ pub(crate) fn validate_params(id: &str, params: &Value) -> Result<()> { } #[cfg(test)] -mod tests { - use std::sync::Arc; - - use photocraft_geom::Rect; - use serde_json::json; - - use super::*; - use crate::Session; - - fn session(depth: u32) -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width":16,"height":12,"depth":depth})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.edit("pattern", |doc, active| { - let surface = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - surface.fill_rect(Rect::new(0, 0, 8, 12), &[0.2, 0.6, 0.8, 1.0]); - Ok(()) - }) - .unwrap(); - s - } - - fn rejected(s: &mut Session, id: &str, key: &str, value: Value) { - let doc = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.entries(); - let journal = s.journal.clone(); - let active = s.active().unwrap().active_layer; - let error = s.execute(id, json!({key:value})).unwrap_err(); - assert!(matches!(error, EngineError::BadParams { .. }), "{id}: {error}"); - let error = error.to_string(); - assert!(error.contains(id) && error.contains(key), "{error}"); - assert!(Arc::ptr_eq(&s.active().unwrap().doc, &doc), "{id}: {key}"); - assert_eq!(s.active().unwrap().history.entries(), history); - assert_eq!(s.active().unwrap().active_layer, active); - assert_eq!(s.journal, journal); - assert!(s.jobs().is_empty()); - } - - #[test] - fn every_core_filter_rejects_unknown_keys_without_editing() { - for depth in [8, 16, 32] { - let mut s = session(depth); - for spec in crate::filters::specs().into_iter().filter(|s| s.id != "filter.lastFilter") { - rejected(&mut s, spec.id, "radus", json!(3)); - } - } - } - - #[test] - fn core_filter_numbers_reject_wrong_types_and_documented_range_violations() { - // Each numeric field in the core registry, independently of the validation table. - let cases = [ - ("blur.gaussianBlur", "radius", 0.1, 1000.0), - ("blur.boxBlur", "radius", 1.0, 2000.0), - ("blur.motionBlur", "angle", -360.0, 360.0), - ("blur.motionBlur", "distance", 1.0, 2000.0), - ("blur.radialBlur", "amount", 1.0, 100.0), - ("blur.radialBlur", "centerX", 0.0, 1.0), - ("blur.radialBlur", "centerY", 0.0, 1.0), - ("blur.surfaceBlur", "radius", 1.0, 100.0), - ("blur.surfaceBlur", "threshold", 2.0, 255.0), - ("sharpen.unsharpMask", "amount", 1.0, 500.0), - ("sharpen.unsharpMask", "radius", 0.1, 1000.0), - ("sharpen.unsharpMask", "threshold", 0.0, 255.0), - ("sharpen.smartSharpen", "amount", 1.0, 500.0), - ("sharpen.smartSharpen", "radius", 0.1, 64.0), - ("sharpen.smartSharpen", "reduceNoise", 0.0, 100.0), - ("noise.addNoise", "amount", 0.1, 400.0), - ("noise.median", "radius", 1.0, 500.0), - ("noise.dustAndScratches", "radius", 1.0, 500.0), - ("noise.dustAndScratches", "threshold", 0.0, 255.0), - ("pixelate.mosaic", "cellSize", 2.0, 200.0), - ("stylize.emboss", "angle", -180.0, 180.0), - ("stylize.emboss", "height", 1.0, 100.0), - ("stylize.emboss", "amount", 1.0, 500.0), - ("distort.twirl", "angle", -999.0, 999.0), - ("distort.pinch", "amount", -100.0, 100.0), - ("distort.spherize", "amount", -100.0, 100.0), - ("distort.wave", "generators", 1.0, 999.0), - ("distort.wave", "wavelengthMin", 1.0, 998.0), - ("distort.wave", "wavelengthMax", 2.0, 999.0), - ("distort.wave", "amplitudeMin", 1.0, 998.0), - ("distort.wave", "amplitudeMax", 1.0, 999.0), - ("distort.ripple", "amount", -999.0, 999.0), - ("other.highPass", "radius", 0.1, 1000.0), - ("other.minimum", "radius", 0.2, 500.0), - ("other.maximum", "radius", 0.2, 500.0), - ]; - for depth in [8, 16, 32] { - let mut s = session(depth); - for (suffix, key, min, max) in cases { - let id = format!("filter.{suffix}"); - for value in [json!("big"), json!(true), Value::Null, json!([]), json!({}), json!(min - 0.01), json!(max + 0.01)] { - rejected(&mut s, &id, key, value); - } - // Large limits are validated without allocating a large blur kernel. - for value in [min, max] { - validate_params(&id, &json!({key:value})).unwrap(); - } - } - for key in ["horizontal", "vertical"] { - rejected(&mut s, "filter.other.offset", key, json!("4")); - } - } - } - - #[test] - fn core_filter_choices_booleans_seeds_and_shared_fields_are_validated() { - let mut s = session(8); - for (suffix, key, choices) in [ - ("blur.radialBlur", "method", "spin|zoom"), - ("blur.radialBlur", "quality", "draft|good|best"), - ("noise.addNoise", "distribution", "uniform|gaussian"), - ("distort.spherize", "mode", "normal|horizontalOnly|verticalOnly"), - ("distort.wave", "type", "sine|triangle|square"), - ("distort.wave", "undefinedAreas", "wrap|repeat"), - ("distort.ripple", "size", "small|medium|large"), - ("distort.polarCoordinates", "mode", "rectangularToPolar|polarToRectangular"), - ("other.minimum", "preserve", "squareness|roundness"), - ("other.maximum", "preserve", "squareness|roundness"), - ("other.offset", "undefinedAreas", "wrap|repeat|transparent"), - ] { - let id = format!("filter.{suffix}"); - for value in [json!("typo"), json!(false), json!(1), Value::Null] { - rejected(&mut s, &id, key, value); - } - for value in choices.split('|') { - validate_params(&id, &json!({key:value})).unwrap(); - } - } - for value in [json!("true"), json!(0), Value::Null] { - rejected(&mut s, "filter.noise.addNoise", "monochromatic", value); - } - for id in ["filter.noise.addNoise", "filter.distort.wave"] { - for value in [json!(-1), json!(4_294_967_296_u64), json!(0.5), json!("12")] { - rejected(&mut s, id, "seed", value); - } - // A valid u32 seed must not be saturated through an i32 helper. - let result = s.execute(id, json!({"seed":u32::MAX})).unwrap(); - assert_eq!(result["filter"]["seed"], json!(u32::MAX)); - } - for (key, value) in [("layer", json!("2")), ("target", json!("typo")), ("target", json!({"channel":-1})), ("coalesce", json!(false))] { - rejected(&mut s, "filter.blur.gaussianBlur", key, value); - } - } - - #[test] - fn extended_filter_choices_match_their_specs_and_reject_unlisted_values() { - let mut s = session(8); - let specs = crate::filters_ext::specs(); - let ids = [ - "filter.pixelate.mezzotint", - "filter.stylize.diffuse", - "filter.stylize.extrude", - "filter.stylize.tiles", - "filter.stylize.traceContour", - "filter.stylize.wind", - "filter.distort.displace", - "filter.distort.shear", - "filter.distort.zigZag", - "filter.render.lensFlare", - "filter.render.lightingEffects", - "filter.blur.lensBlur", - "filter.other.hsbHsl", - "filter.video.deInterlace", - ]; - for id in ids { - let doc = specs.iter().find(|spec| spec.id == id).unwrap().params; - for &(key, allowed) in choices(id).unwrap() { - // The table repeats the registry's params doc, so the two cannot drift apart. - assert!(doc.contains(&format!("\"{key}\":\"{allowed}\"")), "{id}.{key}"); - for value in [json!("zzbogus"), json!(false), json!(1), Value::Null] { - rejected(&mut s, id, key, value); - } - for value in allowed.split('|') { - validate_params(id, &json!({key:value})).unwrap(); - } - } - } - // Keys `prepare` injects, and undocumented ones, stay accepted as before. - s.execute("filter.stylize.tiles", json!({"count":4,"foreground":[1,0,0,1]})).unwrap(); - s.execute("filter.stylize.wind", json!({"direction":"fromLeft"})).unwrap(); - } - - const STRICT_EXTENDED: [&str; 3] = ["filter.blur.smartBlur", "filter.blur.shapeBlur", "filter.noise.reduceNoise"]; - - #[test] - fn strict_extended_filters_reject_bad_fields_without_editing() { - let numbers = [ - ("filter.blur.smartBlur", "radius", 0.1, 100.0), - ("filter.blur.smartBlur", "threshold", 0.1, 100.0), - ("filter.blur.shapeBlur", "radius", 5.0, 1000.0), - ("filter.noise.reduceNoise", "strength", 0.0, 10.0), - ("filter.noise.reduceNoise", "preserveDetails", 0.0, 100.0), - ("filter.noise.reduceNoise", "reduceColorNoise", 0.0, 100.0), - ("filter.noise.reduceNoise", "sharpenDetails", 0.0, 100.0), - ]; - let specs = crate::filters_ext::specs(); - for depth in [8, 16, 32] { - let mut s = session(depth); - for (id, key, min, max) in numbers { - let doc = specs.iter().find(|spec| spec.id == id).unwrap().params; - assert!(doc.contains(&format!("\"{key}\":{min}..{max}=")), "{id}.{key}"); - for value in [json!("3"), json!(true), Value::Null, json!([]), json!({}), json!(min - 0.01), json!(max + 0.01), json!(1e300)] { - rejected(&mut s, id, key, value); - } - // Validate large endpoints without allocating large blur kernels. - for value in [min, max] { - validate_params(id, &json!({key:value})).unwrap(); - } - } - for id in STRICT_EXTENDED { - for (key, value) in [("radus", json!(3)), ("layer", json!("2")), ("target", json!("typo")), ("coalesce", json!(false))] { - rejected(&mut s, id, key, value); - } - for value in [json!([]), json!(false), json!(3), json!("params")] { - assert!(matches!(validate_params(id, &value), Err(EngineError::BadParams { .. }))); - } - } - for value in [json!("true"), json!(1), Value::Null, json!([]), json!({})] { - rejected(&mut s, "filter.noise.reduceNoise", "removeJpegArtifact", value); - } - } - for value in [false, true] { - validate_params("filter.noise.reduceNoise", &json!({"removeJpegArtifact":value})).unwrap(); - } - for (id, key, allowed) in [ - ("filter.blur.smartBlur", "quality", "high|medium|low"), - ("filter.blur.smartBlur", "mode", "normal|edgeOnly|overlayEdge"), - ("filter.blur.shapeBlur", "shape", "circle|ring|square|diamond|triangle|hexagon|star|heart|cross"), - ] { - let doc = specs.iter().find(|spec| spec.id == id).unwrap().params; - assert!(doc.contains(&format!("\"{key}\":\"{allowed}\"")), "{id}.{key}"); - let mut s = session(8); - for value in [json!("typo"), json!(false), json!(1), Value::Null] { - rejected(&mut s, id, key, value); - } - for value in allowed.split('|') { - validate_params(id, &json!({key:value})).unwrap(); - } - } - } - - #[test] - fn strict_extended_filters_validate_before_floating_selection_commit_and_jobs() { - let mut s = session(16); - s.execute("select.rect", json!({"x":0,"y":0,"width":4,"height":4})).unwrap(); - s.execute("select.float", json!({"dx":8})).unwrap(); - for id in STRICT_EXTENDED { - rejected(&mut s, id, "radus", json!(3)); - let doc = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.entries(); - let journal = s.journal.clone(); - let params = json!({"radus":3}); - assert!(matches!(s.start(id, params.clone()), Err(EngineError::BadParams { .. }))); - let spec = crate::commands::find(id).unwrap(); - assert!(matches!((spec.run)(&mut s, ¶ms), Err(EngineError::BadParams { .. }))); - assert!(crate::float_cmds::floating(s.active().unwrap()).is_some()); - assert!(Arc::ptr_eq(&s.active().unwrap().doc, &doc)); - assert_eq!(s.active().unwrap().history.entries(), history); - assert_eq!(s.journal, journal); - assert!(s.jobs().is_empty()); - } - } - - #[test] - fn strict_extended_filters_keep_defaults_targets_history_and_last_filter() { - for depth in [8, 16, 32] { - for id in STRICT_EXTENDED { - let mut s = session(depth); - let layer = s.active().unwrap().active_layer.unwrap(); - for params in [Value::Null, json!({}), json!({"layer":layer.0,"target":"pixels","coalesce":"extended"})] { - let before = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.past_len(); - s.execute(id, params).unwrap(); - assert_eq!(s.active().unwrap().history.past_len(), history + 1); - let after = s.active().unwrap().doc.clone(); - s.undo(); - assert_eq!(*s.active().unwrap().doc, *before); - s.redo(); - assert_eq!(*s.active().unwrap().doc, *after); - } - s.execute("filter.lastFilter", json!({})).unwrap(); - // The session injects this target when editing an alpha channel. - s.execute("channel.new", json!({"fill":"white"})).unwrap(); - s.execute(id, json!({})).unwrap(); - } - } - } - - #[test] - fn stored_extended_filter_records_still_decode_tolerantly() { - use photocraft_algo::{BlurQuality, BlurShape, FilterParams, SmartBlurMode}; - let smart = - crate::filters::params_for("filter.blur.smartBlur", &json!({"radius":-2,"threshold":900,"quality":"old","mode":false,"extra":true})).unwrap(); - assert!(matches!(smart, FilterParams::SmartBlur { radius: 0.1, threshold: 100.0, quality: BlurQuality::High, mode: SmartBlurMode::Normal })); - let shape = crate::filters::params_for("filter.blur.shapeBlur", &json!({"radius":2000,"shape":"old"})).unwrap(); - assert!(matches!(shape, FilterParams::ShapeBlur { radius: 1000.0, shape: BlurShape::Circle })); - let noise = crate::filters::params_for("filter.noise.reduceNoise", &json!({"strength":-1,"preserveDetails":101,"removeJpegArtifact":"yes"})).unwrap(); - assert!(matches!(noise, FilterParams::ReduceNoise { strength: 0.0, preserve_details: 100.0, remove_jpeg_artifact: false, .. })); - } - - #[test] - fn invalid_filters_leave_floating_selection_and_background_jobs_alone() { - let mut s = session(16); - s.execute("select.rect", json!({"x":0,"y":0,"width":4,"height":4})).unwrap(); - s.execute("select.float", json!({"dx":8})).unwrap(); - let doc = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.entries(); - for params in [json!({"radius":"big"}), json!({"radus":3}), json!({"radius":5000}), json!({"radius":-4})] { - assert!(s.start("filter.blur.gaussianBlur", params.clone()).is_err()); - let spec = crate::commands::find("filter.blur.gaussianBlur").unwrap(); - assert!((spec.run)(&mut s, ¶ms).is_err()); - assert!(crate::float_cmds::floating(s.active().unwrap()).is_some()); - assert!(Arc::ptr_eq(&s.active().unwrap().doc, &doc)); - assert_eq!(s.active().unwrap().history.entries(), history); - assert!(s.jobs().is_empty()); - } - } - - #[test] - fn valid_filters_keep_defaults_explicit_targets_and_undo_redo() { - for depth in [8, 16, 32] { - let mut s = session(depth); - let layer = s.active().unwrap().active_layer.unwrap(); - let pixels = |s: &Session| s.active().unwrap().doc.layer(layer).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 16, 12)); - let before = pixels(&s); - for params in [Value::Null, json!({})] { - let result = s.execute("filter.blur.gaussianBlur", params).unwrap(); - assert_eq!(result["filter"]["radius"], json!(1.0)); - assert_ne!(pixels(&s), before); - s.undo(); - assert_eq!(pixels(&s), before); - } - s.execute("layer.new.layer", json!({})).unwrap(); - let other = s.active().unwrap().active_layer.unwrap(); - let result = s.execute("filter.blur.gaussianBlur", json!({"radius":3,"layer":layer.0,"target":"pixels","coalesce":"blur"})).unwrap(); - assert_eq!(result["filter"]["radius"], json!(3.0)); - let after = pixels(&s); - assert_ne!(after, before); - assert_eq!(s.active().unwrap().doc.layer(other).unwrap().surface().unwrap().tile_count(), 0); - s.undo(); - assert_eq!(pixels(&s), before); - s.redo(); - assert_eq!(pixels(&s), after); - } - } - - #[test] - fn injected_channel_targets_and_extended_filter_colours_keep_working() { - let mut s = session(8); - s.execute("channel.new", json!({"fill":"white"})).unwrap(); - let pixels = s.active().unwrap().doc.layers.clone(); - s.execute("filter.noise.addNoise", json!({"amount":40,"seed":2})).unwrap(); - assert_eq!(s.active().unwrap().doc.layers, pixels); - assert!(s.active().unwrap().doc.channels[0].surface.read_region(Rect::new(0, 0, 16, 12)).iter().any(|&v| v < 0.99)); - s.execute("channel.target", json!({"channel":"composite"})).unwrap(); - s.tools.foreground = [0.0, 0.0, 1.0, 1.0]; - s.tools.background = [1.0, 0.0, 0.0, 1.0]; - let params = crate::filters_ext::prepare(&s, "filter.render.fibers", &json!({})); - assert_eq!(params["foreground"], json!(s.tools.foreground)); - assert_eq!(params["background"], json!(s.tools.background)); - s.execute("filter.render.fibers", params).unwrap(); - } -} +mod tests; diff --git a/crates/engine/src/filters/validation/tests.rs b/crates/engine/src/filters/validation/tests.rs new file mode 100644 index 0000000000..3541fe8807 --- /dev/null +++ b/crates/engine/src/filters/validation/tests.rs @@ -0,0 +1,363 @@ +use std::sync::Arc; + +use photocraft_geom::Rect; +use serde_json::json; + +use super::*; +use crate::Session; + +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width":16,"height":12,"depth":depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("pattern", |doc, active| { + let surface = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surface.fill_rect(Rect::new(0, 0, 8, 12), &[0.2, 0.6, 0.8, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +fn rejected(s: &mut Session, id: &str, key: &str, value: Value) { + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.entries(); + let journal = s.journal.clone(); + let active = s.active().unwrap().active_layer; + let error = s.execute(id, json!({key:value})).unwrap_err(); + assert!(matches!(error, EngineError::BadParams { .. }), "{id}: {error}"); + let error = error.to_string(); + assert!(error.contains(id) && error.contains(key), "{error}"); + assert!(Arc::ptr_eq(&s.active().unwrap().doc, &doc), "{id}: {key}"); + assert_eq!(s.active().unwrap().history.entries(), history); + assert_eq!(s.active().unwrap().active_layer, active); + assert_eq!(s.journal, journal); + assert!(s.jobs().is_empty()); +} + +#[test] +fn every_core_filter_rejects_unknown_keys_without_editing() { + for depth in [8, 16, 32] { + let mut s = session(depth); + for spec in crate::filters::specs().into_iter().filter(|s| s.id != "filter.lastFilter") { + rejected(&mut s, spec.id, "radus", json!(3)); + } + } +} + +#[test] +fn core_filter_numbers_reject_wrong_types_and_documented_range_violations() { + // Each numeric field in the core registry, independently of the validation table. + let cases = [ + ("blur.gaussianBlur", "radius", 0.1, 1000.0), + ("blur.boxBlur", "radius", 1.0, 2000.0), + ("blur.motionBlur", "angle", -360.0, 360.0), + ("blur.motionBlur", "distance", 1.0, 2000.0), + ("blur.radialBlur", "amount", 1.0, 100.0), + ("blur.radialBlur", "centerX", 0.0, 1.0), + ("blur.radialBlur", "centerY", 0.0, 1.0), + ("blur.surfaceBlur", "radius", 1.0, 100.0), + ("blur.surfaceBlur", "threshold", 2.0, 255.0), + ("sharpen.unsharpMask", "amount", 1.0, 500.0), + ("sharpen.unsharpMask", "radius", 0.1, 1000.0), + ("sharpen.unsharpMask", "threshold", 0.0, 255.0), + ("sharpen.smartSharpen", "amount", 1.0, 500.0), + ("sharpen.smartSharpen", "radius", 0.1, 64.0), + ("sharpen.smartSharpen", "reduceNoise", 0.0, 100.0), + ("noise.addNoise", "amount", 0.1, 400.0), + ("noise.median", "radius", 1.0, 500.0), + ("noise.dustAndScratches", "radius", 1.0, 500.0), + ("noise.dustAndScratches", "threshold", 0.0, 255.0), + ("pixelate.mosaic", "cellSize", 2.0, 200.0), + ("stylize.emboss", "angle", -180.0, 180.0), + ("stylize.emboss", "height", 1.0, 100.0), + ("stylize.emboss", "amount", 1.0, 500.0), + ("distort.twirl", "angle", -999.0, 999.0), + ("distort.pinch", "amount", -100.0, 100.0), + ("distort.spherize", "amount", -100.0, 100.0), + ("distort.wave", "generators", 1.0, 999.0), + ("distort.wave", "wavelengthMin", 1.0, 998.0), + ("distort.wave", "wavelengthMax", 2.0, 999.0), + ("distort.wave", "amplitudeMin", 1.0, 998.0), + ("distort.wave", "amplitudeMax", 1.0, 999.0), + ("distort.ripple", "amount", -999.0, 999.0), + ("other.highPass", "radius", 0.1, 1000.0), + ("other.minimum", "radius", 0.2, 500.0), + ("other.maximum", "radius", 0.2, 500.0), + ]; + for depth in [8, 16, 32] { + let mut s = session(depth); + for (suffix, key, min, max) in cases { + let id = format!("filter.{suffix}"); + for value in [json!("big"), json!(true), Value::Null, json!([]), json!({}), json!(min - 0.01), json!(max + 0.01)] { + rejected(&mut s, &id, key, value); + } + // Large limits are validated without allocating a large blur kernel. + for value in [min, max] { + validate_params(&id, &json!({key:value})).unwrap(); + } + } + for key in ["horizontal", "vertical"] { + rejected(&mut s, "filter.other.offset", key, json!("4")); + } + } +} + +#[test] +fn core_filter_choices_booleans_seeds_and_shared_fields_are_validated() { + let mut s = session(8); + for (suffix, key, choices) in [ + ("blur.radialBlur", "method", "spin|zoom"), + ("blur.radialBlur", "quality", "draft|good|best"), + ("noise.addNoise", "distribution", "uniform|gaussian"), + ("distort.spherize", "mode", "normal|horizontalOnly|verticalOnly"), + ("distort.wave", "type", "sine|triangle|square"), + ("distort.wave", "undefinedAreas", "wrap|repeat"), + ("distort.ripple", "size", "small|medium|large"), + ("distort.polarCoordinates", "mode", "rectangularToPolar|polarToRectangular"), + ("other.minimum", "preserve", "squareness|roundness"), + ("other.maximum", "preserve", "squareness|roundness"), + ("other.offset", "undefinedAreas", "wrap|repeat|transparent"), + ] { + let id = format!("filter.{suffix}"); + for value in [json!("typo"), json!(false), json!(1), Value::Null] { + rejected(&mut s, &id, key, value); + } + for value in choices.split('|') { + validate_params(&id, &json!({key:value})).unwrap(); + } + } + for value in [json!("true"), json!(0), Value::Null] { + rejected(&mut s, "filter.noise.addNoise", "monochromatic", value); + } + for id in ["filter.noise.addNoise", "filter.distort.wave"] { + for value in [json!(-1), json!(4_294_967_296_u64), json!(0.5), json!("12")] { + rejected(&mut s, id, "seed", value); + } + // A valid u32 seed must not be saturated through an i32 helper. + let result = s.execute(id, json!({"seed":u32::MAX})).unwrap(); + assert_eq!(result["filter"]["seed"], json!(u32::MAX)); + } + for (key, value) in [("layer", json!("2")), ("target", json!("typo")), ("target", json!({"channel":-1})), ("coalesce", json!(false))] { + rejected(&mut s, "filter.blur.gaussianBlur", key, value); + } +} + +#[test] +fn extended_filter_choices_match_their_specs_and_reject_unlisted_values() { + let mut s = session(8); + let specs = crate::filters_ext::specs(); + let ids = [ + "filter.pixelate.mezzotint", + "filter.stylize.diffuse", + "filter.stylize.extrude", + "filter.stylize.tiles", + "filter.stylize.traceContour", + "filter.stylize.wind", + "filter.distort.displace", + "filter.distort.shear", + "filter.distort.zigZag", + "filter.render.lensFlare", + "filter.render.lightingEffects", + "filter.blur.lensBlur", + "filter.other.hsbHsl", + "filter.video.deInterlace", + ]; + for id in ids { + let doc = specs.iter().find(|spec| spec.id == id).unwrap().params; + for &(key, allowed) in choices(id).unwrap() { + // The table repeats the registry's params doc, so the two cannot drift apart. + assert!(doc.contains(&format!("\"{key}\":\"{allowed}\"")), "{id}.{key}"); + for value in [json!("zzbogus"), json!(false), json!(1), Value::Null] { + rejected(&mut s, id, key, value); + } + for value in allowed.split('|') { + validate_params(id, &json!({key:value})).unwrap(); + } + } + } + // Keys `prepare` injects, and undocumented ones, stay accepted as before. + s.execute("filter.stylize.tiles", json!({"count":4,"foreground":[1,0,0,1]})).unwrap(); + s.execute("filter.stylize.wind", json!({"direction":"fromLeft"})).unwrap(); +} + +const STRICT_EXTENDED: [&str; 3] = ["filter.blur.smartBlur", "filter.blur.shapeBlur", "filter.noise.reduceNoise"]; + +#[test] +fn strict_extended_filters_reject_bad_fields_without_editing() { + let numbers = [ + ("filter.blur.smartBlur", "radius", 0.1, 100.0), + ("filter.blur.smartBlur", "threshold", 0.1, 100.0), + ("filter.blur.shapeBlur", "radius", 5.0, 1000.0), + ("filter.noise.reduceNoise", "strength", 0.0, 10.0), + ("filter.noise.reduceNoise", "preserveDetails", 0.0, 100.0), + ("filter.noise.reduceNoise", "reduceColorNoise", 0.0, 100.0), + ("filter.noise.reduceNoise", "sharpenDetails", 0.0, 100.0), + ]; + let specs = crate::filters_ext::specs(); + for depth in [8, 16, 32] { + let mut s = session(depth); + for (id, key, min, max) in numbers { + let doc = specs.iter().find(|spec| spec.id == id).unwrap().params; + assert!(doc.contains(&format!("\"{key}\":{min}..{max}=")), "{id}.{key}"); + for value in [json!("3"), json!(true), Value::Null, json!([]), json!({}), json!(min - 0.01), json!(max + 0.01), json!(1e300)] { + rejected(&mut s, id, key, value); + } + // Validate large endpoints without allocating large blur kernels. + for value in [min, max] { + validate_params(id, &json!({key:value})).unwrap(); + } + } + for id in STRICT_EXTENDED { + for (key, value) in [("radus", json!(3)), ("layer", json!("2")), ("target", json!("typo")), ("coalesce", json!(false))] { + rejected(&mut s, id, key, value); + } + for value in [json!([]), json!(false), json!(3), json!("params")] { + assert!(matches!(validate_params(id, &value), Err(EngineError::BadParams { .. }))); + } + } + for value in [json!("true"), json!(1), Value::Null, json!([]), json!({})] { + rejected(&mut s, "filter.noise.reduceNoise", "removeJpegArtifact", value); + } + } + for value in [false, true] { + validate_params("filter.noise.reduceNoise", &json!({"removeJpegArtifact":value})).unwrap(); + } + for (id, key, allowed) in [ + ("filter.blur.smartBlur", "quality", "high|medium|low"), + ("filter.blur.smartBlur", "mode", "normal|edgeOnly|overlayEdge"), + ("filter.blur.shapeBlur", "shape", "circle|ring|square|diamond|triangle|hexagon|star|heart|cross"), + ] { + let doc = specs.iter().find(|spec| spec.id == id).unwrap().params; + assert!(doc.contains(&format!("\"{key}\":\"{allowed}\"")), "{id}.{key}"); + let mut s = session(8); + for value in [json!("typo"), json!(false), json!(1), Value::Null] { + rejected(&mut s, id, key, value); + } + for value in allowed.split('|') { + validate_params(id, &json!({key:value})).unwrap(); + } + } +} + +#[test] +fn strict_extended_filters_validate_before_floating_selection_commit_and_jobs() { + let mut s = session(16); + s.execute("select.rect", json!({"x":0,"y":0,"width":4,"height":4})).unwrap(); + s.execute("select.float", json!({"dx":8})).unwrap(); + for id in STRICT_EXTENDED { + rejected(&mut s, id, "radus", json!(3)); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.entries(); + let journal = s.journal.clone(); + let params = json!({"radus":3}); + assert!(matches!(s.start(id, params.clone()), Err(EngineError::BadParams { .. }))); + let spec = crate::commands::find(id).unwrap(); + assert!(matches!((spec.run)(&mut s, ¶ms), Err(EngineError::BadParams { .. }))); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some()); + assert!(Arc::ptr_eq(&s.active().unwrap().doc, &doc)); + assert_eq!(s.active().unwrap().history.entries(), history); + assert_eq!(s.journal, journal); + assert!(s.jobs().is_empty()); + } +} + +#[test] +fn strict_extended_filters_keep_defaults_targets_history_and_last_filter() { + for depth in [8, 16, 32] { + for id in STRICT_EXTENDED { + let mut s = session(depth); + let layer = s.active().unwrap().active_layer.unwrap(); + for params in [Value::Null, json!({}), json!({"layer":layer.0,"target":"pixels","coalesce":"extended"})] { + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + s.execute(id, params).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + let after = s.active().unwrap().doc.clone(); + s.undo(); + assert_eq!(*s.active().unwrap().doc, *before); + s.redo(); + assert_eq!(*s.active().unwrap().doc, *after); + } + s.execute("filter.lastFilter", json!({})).unwrap(); + // The session injects this target when editing an alpha channel. + s.execute("channel.new", json!({"fill":"white"})).unwrap(); + s.execute(id, json!({})).unwrap(); + } + } +} + +#[test] +fn stored_extended_filter_records_still_decode_tolerantly() { + use photocraft_algo::{BlurQuality, BlurShape, FilterParams, SmartBlurMode}; + let smart = + crate::filters::params_for("filter.blur.smartBlur", &json!({"radius":-2,"threshold":900,"quality":"old","mode":false,"extra":true})).unwrap(); + assert!(matches!(smart, FilterParams::SmartBlur { radius: 0.1, threshold: 100.0, quality: BlurQuality::High, mode: SmartBlurMode::Normal })); + let shape = crate::filters::params_for("filter.blur.shapeBlur", &json!({"radius":2000,"shape":"old"})).unwrap(); + assert!(matches!(shape, FilterParams::ShapeBlur { radius: 1000.0, shape: BlurShape::Circle })); + let noise = crate::filters::params_for("filter.noise.reduceNoise", &json!({"strength":-1,"preserveDetails":101,"removeJpegArtifact":"yes"})).unwrap(); + assert!(matches!(noise, FilterParams::ReduceNoise { strength: 0.0, preserve_details: 100.0, remove_jpeg_artifact: false, .. })); +} + +#[test] +fn invalid_filters_leave_floating_selection_and_background_jobs_alone() { + let mut s = session(16); + s.execute("select.rect", json!({"x":0,"y":0,"width":4,"height":4})).unwrap(); + s.execute("select.float", json!({"dx":8})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.entries(); + for params in [json!({"radius":"big"}), json!({"radus":3}), json!({"radius":5000}), json!({"radius":-4})] { + assert!(s.start("filter.blur.gaussianBlur", params.clone()).is_err()); + let spec = crate::commands::find("filter.blur.gaussianBlur").unwrap(); + assert!((spec.run)(&mut s, ¶ms).is_err()); + assert!(crate::float_cmds::floating(s.active().unwrap()).is_some()); + assert!(Arc::ptr_eq(&s.active().unwrap().doc, &doc)); + assert_eq!(s.active().unwrap().history.entries(), history); + assert!(s.jobs().is_empty()); + } +} + +#[test] +fn valid_filters_keep_defaults_explicit_targets_and_undo_redo() { + for depth in [8, 16, 32] { + let mut s = session(depth); + let layer = s.active().unwrap().active_layer.unwrap(); + let pixels = |s: &Session| s.active().unwrap().doc.layer(layer).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 16, 12)); + let before = pixels(&s); + for params in [Value::Null, json!({})] { + let result = s.execute("filter.blur.gaussianBlur", params).unwrap(); + assert_eq!(result["filter"]["radius"], json!(1.0)); + assert_ne!(pixels(&s), before); + s.undo(); + assert_eq!(pixels(&s), before); + } + s.execute("layer.new.layer", json!({})).unwrap(); + let other = s.active().unwrap().active_layer.unwrap(); + let result = s.execute("filter.blur.gaussianBlur", json!({"radius":3,"layer":layer.0,"target":"pixels","coalesce":"blur"})).unwrap(); + assert_eq!(result["filter"]["radius"], json!(3.0)); + let after = pixels(&s); + assert_ne!(after, before); + assert_eq!(s.active().unwrap().doc.layer(other).unwrap().surface().unwrap().tile_count(), 0); + s.undo(); + assert_eq!(pixels(&s), before); + s.redo(); + assert_eq!(pixels(&s), after); + } +} + +#[test] +fn injected_channel_targets_and_extended_filter_colours_keep_working() { + let mut s = session(8); + s.execute("channel.new", json!({"fill":"white"})).unwrap(); + let pixels = s.active().unwrap().doc.layers.clone(); + s.execute("filter.noise.addNoise", json!({"amount":40,"seed":2})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers, pixels); + assert!(s.active().unwrap().doc.channels[0].surface.read_region(Rect::new(0, 0, 16, 12)).iter().any(|&v| v < 0.99)); + s.execute("channel.target", json!({"channel":"composite"})).unwrap(); + s.tools.foreground = [0.0, 0.0, 1.0, 1.0]; + s.tools.background = [1.0, 0.0, 0.0, 1.0]; + let params = crate::filters_ext::prepare(&s, "filter.render.fibers", &json!({})); + assert_eq!(params["foreground"], json!(s.tools.foreground)); + assert_eq!(params["background"], json!(s.tools.background)); + s.execute("filter.render.fibers", params).unwrap(); +} From 22352ef31786dc11d35ce07b9b15142a261362ad Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:25 +0000 Subject: [PATCH 047/259] refactor(geom): move warp.rs tests to warp/tests.rs --- crates/geom/src/warp.rs | 470 +--------------------------------- crates/geom/src/warp/tests.rs | 459 +++++++++++++++++++++++++++++++++ 2 files changed, 460 insertions(+), 469 deletions(-) create mode 100644 crates/geom/src/warp/tests.rs diff --git a/crates/geom/src/warp.rs b/crates/geom/src/warp.rs index 0ca3c36b98..90c70cc30f 100644 --- a/crates/geom/src/warp.rs +++ b/crates/geom/src/warp.rs @@ -1215,472 +1215,4 @@ impl Warp { } #[cfg(test)] -mod tests { - use super::*; - - const B: [f64; 4] = [10.0, 20.0, 110.0, 70.0]; - - /// The largest mismatch between the tangents on the two sides of any interior grid line. - fn tangent_defect(m: &BezierMesh) -> f64 { - let nx = m.nx(); - let mut worst: f64 = 0.0; - for a in 1..m.us.len() - 1 { - let (hl, hr) = (m.us[a] - m.us[a - 1], m.us[a + 1] - m.us[a]); - for j in 0..m.ny() { - let (l, c, r) = (m.points[j * nx + 3 * a - 1], m.points[j * nx + 3 * a], m.points[j * nx + 3 * a + 1]); - for k in 0..2 { - worst = worst.max(((c[k] - l[k]) / hl - (r[k] - c[k]) / hr).abs()); - } - } - } - for b in 1..m.vs.len() - 1 { - let (hl, hr) = (m.vs[b] - m.vs[b - 1], m.vs[b + 1] - m.vs[b]); - for i in 0..nx { - let (l, c, r) = (m.points[(3 * b - 1) * nx + i], m.points[3 * b * nx + i], m.points[(3 * b + 1) * nx + i]); - for k in 0..2 { - worst = worst.max(((c[k] - l[k]) / hl - (r[k] - c[k]) / hr).abs()); - } - } - } - worst - } - - #[test] - fn dragging_an_anchor_or_handle_keeps_the_surface_smooth_across_the_lines() { - let mut base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 1, 1); - for s in [0.3, 0.55, 0.9] { - assert!(base.split_u(s)); - assert!(base.split_v(s)); - } - let nx = base.nx(); - // Every kind of point on a grid line, interior and border: anchors, handles each way. - for (i, j) in [(6, 6), (7, 6), (5, 6), (6, 7), (6, 5), (3, 9), (9, 3), (0, 6), (6, 0), (4, 3), (3, 4), (12, 12)] { - let mut m = base.clone(); - m.drag_point(&base.points, j * nx + i, [23.0, -31.0]); - assert_eq!(m.points[j * nx + i], [base.points[j * nx + i][0] + 23.0, base.points[j * nx + i][1] - 31.0], "({i}, {j}) lands on the pointer"); - assert!(tangent_defect(&m) < 1e-6, "({i}, {j}): {}", tangent_defect(&m)); - } - } - - /// Fraction of the surface where the map folds over itself (its Jacobian is not positive). - fn fold_fraction(m: &BezierMesh) -> f64 { - let (n, h) = (80, 1e-4); - let mut bad = 0; - for j in 0..n { - for i in 0..n { - let (s, t) = ((i as f64 + 0.5) / n as f64, (j as f64 + 0.5) / n as f64); - let q = m.eval(s, t); - let (qs, qt) = (m.eval(s + h, t), m.eval(s, t + h)); - if (qs[0] - q[0]) * (qt[1] - q[1]) - (qt[0] - q[0]) * (qs[1] - q[1]) <= 0.0 { - bad += 1; - } - } - } - bad as f64 / (n * n) as f64 - } - - #[test] - fn a_pull_within_a_quarter_cell_never_folds_the_surface() { - // 75 px cells: dragging a quarter of a cell, any direction, anywhere in the grid must not tear the picture. - let base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 4, 4); - for (s, t) in [(0.42, 0.42), (0.75, 0.2), (0.2, 0.2), (0.5, 0.5), (0.85, 0.7), (0.3, 0.7)] { - for (dx, dy) in [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0), (0.7, 0.7), (-0.7, 0.7)] { - let mut m = base.clone(); - m.pull(&base.points, s, t, [dx * 19.0, dy * 19.0]); - assert_eq!(fold_fraction(&m), 0.0, "({s}, {t}) by ({dx}, {dy}) quarter cells"); - } - } - } - - #[test] - fn a_pull_in_the_middle_leaves_the_border_where_it_is() { - let mut base = BezierMesh::identity([0.0, 0.0, 600.0, 800.0], 1, 1); - for s in [0.33, 0.66] { - assert!(base.split_u(s)); - } - assert!(base.split_v(0.5)); - let (nx, ny) = (base.nx(), base.ny()); - let on_border = |i: usize, j: usize| i == 0 || j == 0 || i == nx - 1 || j == ny - 1; - let mut m = base.clone(); - m.pull(&base.points, 0.5, 0.5, [-180.0, 40.0]); - for j in 0..ny { - for i in 0..nx { - if on_border(i, j) { - let (a, b) = (m.points[j * nx + i], base.points[j * nx + i]); - assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "border point ({i}, {j}) moved"); - } - } - } - // The pull itself still lands exactly. - let (before, after) = (base.eval(0.5, 0.5), m.eval(0.5, 0.5)); - assert!((after[0] - before[0] + 180.0).abs() < 1e-4 && (after[1] - before[1] - 40.0).abs() < 1e-4); - } - - #[test] - fn a_pull_anywhere_away_from_the_border_never_moves_the_border() { - // The default one-patch grid and a cut one; grabs all over, none within 12% of an edge. - let one = BezierMesh::identity([0.0, 0.0, 600.0, 800.0], 1, 1); - let mut cut = one.clone(); - assert!(cut.split_u(0.4) && cut.split_u(0.7) && cut.split_v(0.35) && cut.split_v(0.8)); - for base in [one, cut] { - let (nx, ny) = (base.nx(), base.ny()); - for (s, t) in [(0.5, 0.5), (0.2, 0.5), (0.8, 0.3), (0.3, 0.85), (0.14, 0.14), (0.86, 0.5)] { - for d in [[-400.0, 0.0], [250.0, -90.0], [0.0, 300.0]] { - let mut m = base.clone(); - m.pull(&base.points, s, t, d); - for j in 0..ny { - for i in 0..nx { - if i == 0 || j == 0 || i == nx - 1 || j == ny - 1 { - let (a, b) = (m.points[j * nx + i], base.points[j * nx + i]); - assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "({s}, {t}) by {d:?} moved border point ({i}, {j})"); - } - } - } - let (before, after) = (base.eval(s, t), m.eval(s, t)); - assert!((after[0] - before[0] - d[0]).abs() < 1e-3 && (after[1] - before[1] - d[1]).abs() < 1e-3, "({s}, {t}) by {d:?}: {after:?}"); - } - } - } - } - - #[test] - fn pulling_on_the_border_bows_it_and_leaves_the_corners_put() { - // A one-patch grid, grabbed on the middle of its right edge and pulled 170 px out. - let base = BezierMesh::identity([0.0, 0.0, 800.0, 1200.0], 1, 1); - let mut m = base.clone(); - m.pull(&base.points, 1.0, 0.5, [170.0, 0.0]); - let at = m.eval(1.0, 0.5); - assert!((at[0] - 970.0).abs() < 1e-3 && (at[1] - 600.0).abs() < 1e-3, "{at:?}"); - for (s, t) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] { - let (a, b) = (m.eval(s, t), base.eval(s, t)); - assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "corner ({s}, {t}) moved"); - } - // The other three edges did not move. - for k in 0..=10 { - let u = k as f64 / 10.0; - for (s, t) in [(0.0, u), (u, 0.0), (u, 1.0)] { - let (a, b) = (m.eval(s, t), base.eval(s, t)); - assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "edge point ({s}, {t}) moved"); - } - } - // Only the right edge's two handles carry the pull. - let nx = base.nx(); - let moved: Vec = (0..m.points.len()).filter(|k| m.points[*k] != base.points[*k]).collect(); - assert_eq!(moved, vec![nx + 3, 2 * nx + 3], "{moved:?}"); - assert_eq!(fold_fraction(&m), 0.0); - } - - #[test] - fn pull_keeps_the_surface_smooth_across_the_grid_lines() { - // A grid cut unevenly both ways, then pulled hard inside one cell and then another. - let mut base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 1, 1); - for s in [0.3, 0.55, 0.9] { - assert!(base.split_u(s)); - assert!(base.split_v(s)); - } - assert!(tangent_defect(&base) < 1e-9, "cuts are exact"); - for (s, t, d) in [(0.42, 0.42, [60.0, -35.0]), (0.75, 0.2, [-40.0, 50.0]), (0.1, 0.95, [30.0, 30.0])] { - let mut m = base.clone(); - m.pull(&base.points, s, t, d); - assert!(tangent_defect(&m) < 1e-6, "({s}, {t}): {}", tangent_defect(&m)); - let before = base.eval(s, t); - let after = m.eval(s, t); - assert!((after[0] - before[0] - d[0]).abs() < 1e-4 && (after[1] - before[1] - d[1]).abs() < 1e-4, "{after:?}"); - } - } - - #[test] - fn pull_moves_the_grabbed_surface_point_exactly_and_stays_local() { - let base = BezierMesh::identity(B, 3, 2); - for (s, t) in [(0.5, 0.5), (0.1, 0.9), (0.4, 0.25), (0.0, 0.5), (1.0, 0.3)] { - let mut m = base.clone(); - let before = base.eval(s, t); - m.pull(&base.points, s, t, [7.0, -4.5]); - let after = m.eval(s, t); - assert!((after[0] - before[0] - 7.0).abs() < 1e-4 && (after[1] - before[1] + 4.5).abs() < 1e-4, "({s}, {t}): {after:?}"); - } - // The pull stays near the grabbed patch: the far end of the grid does not move. - let mut m = base.clone(); - m.pull(&base.points, 0.1, 0.25, [5.0, 5.0]); - let nx = base.nx(); - let moved = |k: usize| (m.points[k][0] - base.points[k][0]).abs() > 1e-6 || (m.points[k][1] - base.points[k][1]).abs() > 1e-6; - assert!((0..base.ny()).all(|j| !moved(j * nx + nx - 1)), "last column stays put"); - assert!((0..nx).any(moved), "something moved"); - // Pulling again from the same base replaces the pull (a drag is not cumulative). - m.pull(&base.points, 0.5, 0.25, [0.0, 0.0]); - assert!(m.points.iter().zip(&base.points).all(|(a, b)| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9)); - } - - fn close(a: (f64, f64), b: (f64, f64), eps: f64) -> bool { - (a.0 - b.0).abs() < eps && (a.1 - b.1).abs() < eps - } - - #[test] - fn styles_parse_and_round_trip_names() { - for s in WarpStyle::all() { - assert_eq!(WarpStyle::parse(s.id()), Some(s)); - assert_eq!(WarpStyle::parse(s.psd_name()), Some(s)); - assert_eq!(WarpStyle::parse(s.label()), Some(s), "{s:?}"); - } - assert_eq!(WarpStyle::parse("spiral"), None); - } - - #[test] - fn presets_at_bend_zero_are_identity() { - for s in WarpStyle::PRESETS { - let w = Warp::preset(s, 0.0, B); - assert!(w.is_identity()); - assert_eq!(w.map(33.0, 44.0), (33.0, 44.0)); - } - } - - #[test] - fn identity_mesh_is_exact_and_fit_reproduces_affine() { - let m = BezierMesh::identity(B, 1, 1); - assert_eq!((m.nx(), m.ny()), (4, 4)); - let w = Warp::custom(m, B); - assert!(w.is_identity()); - assert!(close(w.map(37.5, 61.25), (37.5, 61.25), 1e-9)); - // Affine maps fit exactly. - let f = |s: f64, t: f64| [3.0 + 2.0 * s - t, 1.0 + 0.5 * s + 4.0 * t]; - let m = BezierMesh::fit(&f, vec![0.0, 1.0], vec![0.0, 0.4, 1.0]); - for (s, t) in [(0.1, 0.9), (0.5, 0.2), (0.77, 0.41)] { - let p = m.eval(s, t); - let e = f(s, t); - assert!((p[0] - e[0]).abs() < 1e-9 && (p[1] - e[1]).abs() < 1e-9); - } - } - - #[test] - fn remove_split_u_rejects_out_of_range_indices() { - let original = BezierMesh::identity(B, 2, 3); - for k in [0, original.us.len() - 1, original.us.len(), usize::MAX - 1, usize::MAX] { - let mut mesh = original.clone(); - assert!(!mesh.remove_split_u(k), "index {k}"); - assert_eq!(mesh, original, "index {k} must leave the mesh unchanged"); - } - } - - #[test] - fn remove_split_v_rejects_out_of_range_indices() { - let original = BezierMesh::identity(B, 2, 3); - for k in [0, original.vs.len() - 1, original.vs.len(), usize::MAX - 1, usize::MAX] { - let mut mesh = original.clone(); - assert!(!mesh.remove_split_v(k), "index {k}"); - assert_eq!(mesh, original, "index {k} must leave the mesh unchanged"); - } - } - - #[test] - fn splits_are_exact_and_removable() { - let mut m = BezierMesh::identity(B, 1, 1); - // Bend it: move an inner control point. - m.points[5] = [50.0, 10.0]; - let before: Vec<[f64; 2]> = (0..=10).flat_map(|j| (0..=10).map(move |i| (i, j))).map(|(i, j)| m.eval(i as f64 / 10.0, j as f64 / 10.0)).collect(); - let orig = m.clone(); - assert!(m.split_u(0.3)); - assert!(m.split_v(0.6)); - assert!(!m.split_u(0.3), "existing boundary"); - assert_eq!((m.nx(), m.ny()), (7, 7)); - assert!(m.is_valid()); - let after: Vec<[f64; 2]> = (0..=10).flat_map(|j| (0..=10).map(move |i| (i, j))).map(|(i, j)| m.eval(i as f64 / 10.0, j as f64 / 10.0)).collect(); - for (a, b) in before.iter().zip(&after) { - assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9); - } - let (ls, lt) = m.param_at(m.eval(0.42, 0.77)); - assert!((ls - 0.42).abs() < 1e-6 && (lt - 0.77).abs() < 1e-6, "{ls},{lt}"); - assert!(m.remove_split_u(1)); - assert!(m.remove_split_v(1)); - assert_eq!(m.us, orig.us); - for (a, b) in m.points.iter().zip(&orig.points) { - assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9); - } - } - - const SQUARE: [f64; 4] = [128.0, 128.0, 384.0, 384.0]; - const WIDE: [f64; 4] = [128.0, 208.0, 384.0, 304.0]; - const TALL: [f64; 4] = [208.0, 128.0, 304.0, 384.0]; - - /// Photoshop 27.11, measured: a 256 px grid image whose colours encode each pixel's own - /// position, warped in a 512 px document over the box (128, 128)–(384, 384). Each pair is a - /// source point and where Photoshop put it. - #[test] - fn presets_match_photoshop() { - type Case = (WarpStyle, f64, f64, f64, bool, [([f64; 2], [f64; 2]); 3]); - let cases: [Case; 9] = [ - (WarpStyle::Arc, 50.0, 0.0, 0.0, false, [([272.5, 155.5], [296.5, 104.5]), ([331.5, 182.5], [424.5, 168.5]), ([259.5, 157.5], [264.5, 104.5])]), - (WarpStyle::Arc, -100.0, 0.0, 0.0, false, [([277.5, 354.5], [344.5, 472.5]), ([140.5, 218.5], [40.5, 168.5]), ([172.5, 237.5], [56.5, 264.5])]), - (WarpStyle::Flag, 50.0, 0.0, 0.0, false, [([136.5, 143.5], [136.5, 120.5]), ([136.5, 159.5], [136.5, 136.5]), ([136.5, 175.5], [136.5, 152.5])]), - (WarpStyle::Twist, -50.0, 0.0, 0.0, false, [([148.5, 205.5], [152.5, 216.5]), ([197.5, 212.5], [200.5, 232.5]), ([134.5, 212.5], [136.5, 216.5])]), - ( - WarpStyle::ShellLower, - 50.0, - 0.0, - 0.0, - false, - [([248.5, 136.5], [248.5, 136.5]), ([264.5, 136.5], [264.5, 136.5]), ([232.5, 136.5], [232.5, 136.5])], - ), - (WarpStyle::Fish, -100.0, 0.0, 0.0, false, [([296.5, 355.5], [296.5, 440.5]), ([344.5, 298.5], [344.5, 344.5]), ([328.5, 356.5], [328.5, 472.5])]), - (WarpStyle::Bulge, 50.0, 50.0, 0.0, false, [([293.5, 147.5], [296.5, 88.5]), ([293.5, 375.5], [296.5, 440.5]), ([340.5, 281.5], [344.5, 296.5])]), - (WarpStyle::Arc, 50.0, 0.0, -50.0, false, [([181.5, 350.5], [184.5, 328.5]), ([291.5, 372.5], [280.5, 344.5]), ([232.5, 349.5], [232.5, 312.5])]), - (WarpStyle::Arc, 50.0, 0.0, 0.0, true, [([155.5, 272.5], [104.5, 296.5]), ([182.5, 331.5], [168.5, 424.5]), ([157.5, 259.5], [104.5, 264.5])]), - ]; - // Wide (256 × 96 at 128, 208) and tall (96 × 256 at 208, 128) boxes, and a vertical warp - // with distortion. - type Boxed = (WarpStyle, f64, f64, f64, bool, [f64; 4], [([f64; 2], [f64; 2]); 2]); - let boxed: [Boxed; 6] = [ - (WarpStyle::Arc, 50.0, 0.0, 0.0, false, WIDE, [([144.5, 269.6], [120.5, 264.5]), ([271.5, 220.42], [280.5, 168.5])]), - (WarpStyle::Bulge, 50.0, 0.0, 0.0, false, TALL, [([249.11, 374.5], [248.5, 392.5]), ([249.11, 360.5], [248.5, 376.5])]), - (WarpStyle::Flag, 50.0, 0.0, 0.0, true, WIDE, [([137.5, 296.42], [184.5, 296.5]), ([153.5, 296.42], [200.5, 296.5])]), - (WarpStyle::Rise, 50.0, 0.0, 0.0, true, TALL, [([250.97, 152.5], [344.5, 152.5]), ([301.26, 264.5], [344.5, 264.5])]), - (WarpStyle::Bulge, 60.0, 20.0, -10.0, false, WIDE, [([208.5, 224.15], [200.5, 184.5]), ([219.5, 277.42], [216.5, 296.5])]), - (WarpStyle::Arc, 50.0, 30.0, 0.0, true, SQUARE, [([331.5, 327.5], [296.5, 360.5]), ([318.5, 240.5], [264.5, 232.5])]), - ]; - let all = - cases.iter().map(|c| (c.0, c.1, c.2, c.3, c.4, SQUARE, c.5.to_vec())).chain(boxed.iter().map(|c| (c.0, c.1, c.2, c.3, c.4, c.5, c.6.to_vec()))); - for (style, bend, hd, vd, vertical, bounds, pairs) in all { - let w = Warp { h_distort: hd, v_distort: vd, vertical, ..Warp::preset(style, bend, bounds) }; - for (src, want) in pairs { - let got = w.map(src[0], src[1]); - let d = (got.0 - want[0]).hypot(got.1 - want[1]); - assert!(d < 1.5, "{style:?} {bend} h{hd} v{vd} vertical {vertical} {bounds:?}: {src:?} -> {got:?}, Photoshop {want:?}"); - } - } - } - - #[test] - fn preset_fits_closely_as_mesh_and_affine_composes() { - let w = Warp::preset(WarpStyle::Bulge, 40.0, B); - let m = Warp::custom(w.to_mesh(4, 4), B); - for (x, y) in [(20.0, 30.0), (60.0, 45.0), (100.0, 65.0)] { - assert!(close(w.map(x, y), m.map(x, y), 0.5), "{:?} vs {:?}", w.map(x, y), m.map(x, y)); - } - let t = Warp::custom(BezierMesh::identity(B, 1, 1), B).then_affine([1.0, 0.0, 0.0, 1.0, 5.0, -2.0]); - assert!(close(t.map(50.0, 50.0), (55.0, 48.0), 1e-9)); - let ob = Warp::none(B).output_bounds(); - assert!((ob[0] - 10.0).abs() < 1e-9 && (ob[3] - 70.0).abs() < 1e-9); - } - - /// A cylinder over a 1000 × 1000 source like #4112's: silhouettes at x 100 and 900, edges at - /// y 200 (top) and 800 (bottom), ellipses 0.3 deep, half wrapped round. - const CYL: [f64; 7] = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5]; - - #[test] - fn cylinder_style_is_read_and_named_but_not_a_bend_preset() { - for s in ["cylinder", "warpCylinder", "Cylinder"] { - assert_eq!(WarpStyle::parse(s), Some(WarpStyle::Cylinder), "{s}"); - } - assert_eq!(WarpStyle::Cylinder.psd_name(), "warpCylinder"); - assert_eq!(WarpStyle::Cylinder.id(), "cylinder"); - assert!(!WarpStyle::Cylinder.is_preset()); - assert!(StyleWarp::new(WarpStyle::Cylinder, 50.0, 0.0, 0.0, false, B).is_none()); - // The Warp menus list what they can edit. - assert!(WarpStyle::all().all(|s| s != WarpStyle::Cylinder)); - assert_eq!(WarpStyle::all().filter(|s| s.is_preset()).count(), 15); - } - - #[test] - fn cylinder_values_that_describe_no_cylinder_are_refused() { - assert!(cylinder_mesh(&CYL[..6]).is_none(), "six values"); - assert!(cylinder_mesh(&[CYL.as_slice(), &[0.0]].concat()).is_none(), "eight values"); - for i in 0..7 { - for bad in [f64::NAN, f64::INFINITY] { - let mut v = CYL; - v[i] = bad; - assert!(cylinder_mesh(&v).is_none(), "value {i} = {bad}"); - } - } - let mut v = CYL; - v[2] = v[0]; - assert!(Warp::cylinder(&v, [0.0, 0.0, 1000.0, 1000.0]).is_none(), "no width"); - v[2] = 50.0; - assert!(Warp::cylinder(&v, [0.0, 0.0, 1000.0, 1000.0]).is_none(), "right silhouette left of the left one"); - } - - #[test] - fn cylinder_wraps_the_contents_between_its_silhouettes() { - let w = Warp::cylinder(&CYL, [0.0, 0.0, 1000.0, 1000.0]).unwrap(); - assert_eq!(w.style, WarpStyle::Cylinder); - assert_eq!(w.values, CYL); - assert!(!w.is_identity()); - let m = w.mesh.as_ref().unwrap(); - assert_eq!((m.nx(), m.ny()), (13, 4)); - let [ul, ..] = cylinder_shape(0.5); - assert!((m.us[1] - ul).abs() < 1e-12 && (m.us[3] - (1.0 - ul)).abs() < 1e-12); - // The middle of the contents is at the front: centred, on the ellipses' near side. - assert!(close(w.map(500.0, 0.0), (500.0, 200.0 + 0.3 * 400.0), 1e-9)); - assert!(close(w.map(500.0, 1000.0), (500.0, 800.0 + 0.3 * 400.0), 1e-9)); - // What wraps round the back lies on the silhouettes, at the edges' ends. - for x in [0.0, ul * 500.0, ul * 1000.0] { - assert!(close(w.map(x, 0.0), (100.0, 200.0), 1e-9), "{x}"); - assert!(close(w.map(1000.0 - x, 1000.0), (900.0, 800.0), 1e-9), "{x}"); - } - // Across the front x only grows, and the two halves mirror each other. - let mut last = f64::MIN; - for i in 0..=200 { - let x = 1000.0 * (ul + (1.0 - 2.0 * ul) * f64::from(i) / 200.0); - let (px, py) = w.map(x, 400.0); - assert!(px >= last - 1e-9, "x {x}"); - last = px; - let (qx, qy) = w.map(1000.0 - x, 400.0); - assert!(close((px - 500.0, py), (500.0 - qx, qy), 1e-9), "x {x}"); - } - // Every point stays inside the control-point box the placement frames. - let cb = m.control_bounds(); - let ob = w.output_bounds(); - assert!(ob[0] >= cb[0] - 1e-9 && ob[1] >= cb[1] - 1e-9 && ob[2] <= cb[2] + 1e-9 && ob[3] <= cb[3] + 1e-9); - assert!((cb[0] - 100.0).abs() < 1e-9 && (cb[2] - 900.0).abs() < 1e-9); - // The box's bottom is the lower ellipse's deepest control point (`my` > 1). - assert!((cb[3] - (800.0 + 0.3 * 400.0 * cylinder_shape(0.5)[3])).abs() < 1e-9); - assert_eq!(w.to_mesh(4, 4), *m, "a cylinder is its own mesh"); - } - - #[test] - fn cylinder_shape_follows_the_measured_rows() { - assert_eq!(cylinder_shape(0.0), CYLINDER_SHAPE[0]); - assert_eq!(cylinder_shape(1.0), CYLINDER_SHAPE[40]); - assert_eq!(cylinder_shape(-3.0), CYLINDER_SHAPE[0]); - assert_eq!(cylinder_shape(7.0), CYLINDER_SHAPE[40]); - assert_eq!(cylinder_shape(f64::NAN), CYLINDER_SHAPE[0]); - let mid = cylinder_shape(0.0125); - for k in 0..4 { - assert!((mid[k] - (CYLINDER_SHAPE[0][k] + CYLINDER_SHAPE[1][k]) / 2.0).abs() < 1e-12); - } - // The more it wraps, the less of the contents is on the back. - assert!(CYLINDER_SHAPE.windows(2).all(|r| r[1][0] < r[0][0])); - } - - #[test] - fn is_identity_rejects_malformed_custom_mesh_without_allocating() { - let us: Vec = (0..=1000).map(|i| i as f64 / 1000.0).collect(); - let vs: Vec = (0..=1000).map(|i| i as f64 / 1000.0).collect(); - let malformed = BezierMesh { us, vs, points: Vec::new() }; - assert!(!malformed.is_valid()); - let w = Warp::custom(malformed.clone(), B); - assert!(!w.is_identity()); - assert_eq!(malformed.eval(0.5, 0.5), [0.0, 0.0]); - } - - #[test] - fn locate_binary_search_matches_linear_scan() { - let knots = [0.0, 0.1, 0.25, 0.5, 0.85, 1.0]; - let linear = |s: f64| { - let n = knots.len() - 1; - let s = if s.is_finite() { s.clamp(0.0, 1.0) } else { 0.0 }; - let mut i = 0; - while i + 1 < n && s > knots[i + 1] { - i += 1; - } - let w = knots[i + 1] - knots[i]; - (i, if w > 0.0 { (s - knots[i]) / w } else { 0.0 }) - }; - for k in -10..=110 { - let s = k as f64 / 100.0; - assert_eq!(BezierMesh::locate(&knots, s), linear(s), "s={s}"); - } - for &s in &knots { - assert_eq!(BezierMesh::locate(&knots, s), linear(s), "knot={s}"); - } - assert_eq!(BezierMesh::locate(&knots, f64::NAN), linear(f64::NAN)); - } -} +mod tests; diff --git a/crates/geom/src/warp/tests.rs b/crates/geom/src/warp/tests.rs new file mode 100644 index 0000000000..1fc9612316 --- /dev/null +++ b/crates/geom/src/warp/tests.rs @@ -0,0 +1,459 @@ +use super::*; + +const B: [f64; 4] = [10.0, 20.0, 110.0, 70.0]; + +/// The largest mismatch between the tangents on the two sides of any interior grid line. +fn tangent_defect(m: &BezierMesh) -> f64 { + let nx = m.nx(); + let mut worst: f64 = 0.0; + for a in 1..m.us.len() - 1 { + let (hl, hr) = (m.us[a] - m.us[a - 1], m.us[a + 1] - m.us[a]); + for j in 0..m.ny() { + let (l, c, r) = (m.points[j * nx + 3 * a - 1], m.points[j * nx + 3 * a], m.points[j * nx + 3 * a + 1]); + for k in 0..2 { + worst = worst.max(((c[k] - l[k]) / hl - (r[k] - c[k]) / hr).abs()); + } + } + } + for b in 1..m.vs.len() - 1 { + let (hl, hr) = (m.vs[b] - m.vs[b - 1], m.vs[b + 1] - m.vs[b]); + for i in 0..nx { + let (l, c, r) = (m.points[(3 * b - 1) * nx + i], m.points[3 * b * nx + i], m.points[(3 * b + 1) * nx + i]); + for k in 0..2 { + worst = worst.max(((c[k] - l[k]) / hl - (r[k] - c[k]) / hr).abs()); + } + } + } + worst +} + +#[test] +fn dragging_an_anchor_or_handle_keeps_the_surface_smooth_across_the_lines() { + let mut base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 1, 1); + for s in [0.3, 0.55, 0.9] { + assert!(base.split_u(s)); + assert!(base.split_v(s)); + } + let nx = base.nx(); + // Every kind of point on a grid line, interior and border: anchors, handles each way. + for (i, j) in [(6, 6), (7, 6), (5, 6), (6, 7), (6, 5), (3, 9), (9, 3), (0, 6), (6, 0), (4, 3), (3, 4), (12, 12)] { + let mut m = base.clone(); + m.drag_point(&base.points, j * nx + i, [23.0, -31.0]); + assert_eq!(m.points[j * nx + i], [base.points[j * nx + i][0] + 23.0, base.points[j * nx + i][1] - 31.0], "({i}, {j}) lands on the pointer"); + assert!(tangent_defect(&m) < 1e-6, "({i}, {j}): {}", tangent_defect(&m)); + } +} + +/// Fraction of the surface where the map folds over itself (its Jacobian is not positive). +fn fold_fraction(m: &BezierMesh) -> f64 { + let (n, h) = (80, 1e-4); + let mut bad = 0; + for j in 0..n { + for i in 0..n { + let (s, t) = ((i as f64 + 0.5) / n as f64, (j as f64 + 0.5) / n as f64); + let q = m.eval(s, t); + let (qs, qt) = (m.eval(s + h, t), m.eval(s, t + h)); + if (qs[0] - q[0]) * (qt[1] - q[1]) - (qt[0] - q[0]) * (qs[1] - q[1]) <= 0.0 { + bad += 1; + } + } + } + bad as f64 / (n * n) as f64 +} + +#[test] +fn a_pull_within_a_quarter_cell_never_folds_the_surface() { + // 75 px cells: dragging a quarter of a cell, any direction, anywhere in the grid must not tear the picture. + let base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 4, 4); + for (s, t) in [(0.42, 0.42), (0.75, 0.2), (0.2, 0.2), (0.5, 0.5), (0.85, 0.7), (0.3, 0.7)] { + for (dx, dy) in [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0), (0.7, 0.7), (-0.7, 0.7)] { + let mut m = base.clone(); + m.pull(&base.points, s, t, [dx * 19.0, dy * 19.0]); + assert_eq!(fold_fraction(&m), 0.0, "({s}, {t}) by ({dx}, {dy}) quarter cells"); + } + } +} + +#[test] +fn a_pull_in_the_middle_leaves_the_border_where_it_is() { + let mut base = BezierMesh::identity([0.0, 0.0, 600.0, 800.0], 1, 1); + for s in [0.33, 0.66] { + assert!(base.split_u(s)); + } + assert!(base.split_v(0.5)); + let (nx, ny) = (base.nx(), base.ny()); + let on_border = |i: usize, j: usize| i == 0 || j == 0 || i == nx - 1 || j == ny - 1; + let mut m = base.clone(); + m.pull(&base.points, 0.5, 0.5, [-180.0, 40.0]); + for j in 0..ny { + for i in 0..nx { + if on_border(i, j) { + let (a, b) = (m.points[j * nx + i], base.points[j * nx + i]); + assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "border point ({i}, {j}) moved"); + } + } + } + // The pull itself still lands exactly. + let (before, after) = (base.eval(0.5, 0.5), m.eval(0.5, 0.5)); + assert!((after[0] - before[0] + 180.0).abs() < 1e-4 && (after[1] - before[1] - 40.0).abs() < 1e-4); +} + +#[test] +fn a_pull_anywhere_away_from_the_border_never_moves_the_border() { + // The default one-patch grid and a cut one; grabs all over, none within 12% of an edge. + let one = BezierMesh::identity([0.0, 0.0, 600.0, 800.0], 1, 1); + let mut cut = one.clone(); + assert!(cut.split_u(0.4) && cut.split_u(0.7) && cut.split_v(0.35) && cut.split_v(0.8)); + for base in [one, cut] { + let (nx, ny) = (base.nx(), base.ny()); + for (s, t) in [(0.5, 0.5), (0.2, 0.5), (0.8, 0.3), (0.3, 0.85), (0.14, 0.14), (0.86, 0.5)] { + for d in [[-400.0, 0.0], [250.0, -90.0], [0.0, 300.0]] { + let mut m = base.clone(); + m.pull(&base.points, s, t, d); + for j in 0..ny { + for i in 0..nx { + if i == 0 || j == 0 || i == nx - 1 || j == ny - 1 { + let (a, b) = (m.points[j * nx + i], base.points[j * nx + i]); + assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "({s}, {t}) by {d:?} moved border point ({i}, {j})"); + } + } + } + let (before, after) = (base.eval(s, t), m.eval(s, t)); + assert!((after[0] - before[0] - d[0]).abs() < 1e-3 && (after[1] - before[1] - d[1]).abs() < 1e-3, "({s}, {t}) by {d:?}: {after:?}"); + } + } + } +} + +#[test] +fn pulling_on_the_border_bows_it_and_leaves_the_corners_put() { + // A one-patch grid, grabbed on the middle of its right edge and pulled 170 px out. + let base = BezierMesh::identity([0.0, 0.0, 800.0, 1200.0], 1, 1); + let mut m = base.clone(); + m.pull(&base.points, 1.0, 0.5, [170.0, 0.0]); + let at = m.eval(1.0, 0.5); + assert!((at[0] - 970.0).abs() < 1e-3 && (at[1] - 600.0).abs() < 1e-3, "{at:?}"); + for (s, t) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)] { + let (a, b) = (m.eval(s, t), base.eval(s, t)); + assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "corner ({s}, {t}) moved"); + } + // The other three edges did not move. + for k in 0..=10 { + let u = k as f64 / 10.0; + for (s, t) in [(0.0, u), (u, 0.0), (u, 1.0)] { + let (a, b) = (m.eval(s, t), base.eval(s, t)); + assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "edge point ({s}, {t}) moved"); + } + } + // Only the right edge's two handles carry the pull. + let nx = base.nx(); + let moved: Vec = (0..m.points.len()).filter(|k| m.points[*k] != base.points[*k]).collect(); + assert_eq!(moved, vec![nx + 3, 2 * nx + 3], "{moved:?}"); + assert_eq!(fold_fraction(&m), 0.0); +} + +#[test] +fn pull_keeps_the_surface_smooth_across_the_grid_lines() { + // A grid cut unevenly both ways, then pulled hard inside one cell and then another. + let mut base = BezierMesh::identity([0.0, 0.0, 300.0, 300.0], 1, 1); + for s in [0.3, 0.55, 0.9] { + assert!(base.split_u(s)); + assert!(base.split_v(s)); + } + assert!(tangent_defect(&base) < 1e-9, "cuts are exact"); + for (s, t, d) in [(0.42, 0.42, [60.0, -35.0]), (0.75, 0.2, [-40.0, 50.0]), (0.1, 0.95, [30.0, 30.0])] { + let mut m = base.clone(); + m.pull(&base.points, s, t, d); + assert!(tangent_defect(&m) < 1e-6, "({s}, {t}): {}", tangent_defect(&m)); + let before = base.eval(s, t); + let after = m.eval(s, t); + assert!((after[0] - before[0] - d[0]).abs() < 1e-4 && (after[1] - before[1] - d[1]).abs() < 1e-4, "{after:?}"); + } +} + +#[test] +fn pull_moves_the_grabbed_surface_point_exactly_and_stays_local() { + let base = BezierMesh::identity(B, 3, 2); + for (s, t) in [(0.5, 0.5), (0.1, 0.9), (0.4, 0.25), (0.0, 0.5), (1.0, 0.3)] { + let mut m = base.clone(); + let before = base.eval(s, t); + m.pull(&base.points, s, t, [7.0, -4.5]); + let after = m.eval(s, t); + assert!((after[0] - before[0] - 7.0).abs() < 1e-4 && (after[1] - before[1] + 4.5).abs() < 1e-4, "({s}, {t}): {after:?}"); + } + // The pull stays near the grabbed patch: the far end of the grid does not move. + let mut m = base.clone(); + m.pull(&base.points, 0.1, 0.25, [5.0, 5.0]); + let nx = base.nx(); + let moved = |k: usize| (m.points[k][0] - base.points[k][0]).abs() > 1e-6 || (m.points[k][1] - base.points[k][1]).abs() > 1e-6; + assert!((0..base.ny()).all(|j| !moved(j * nx + nx - 1)), "last column stays put"); + assert!((0..nx).any(moved), "something moved"); + // Pulling again from the same base replaces the pull (a drag is not cumulative). + m.pull(&base.points, 0.5, 0.25, [0.0, 0.0]); + assert!(m.points.iter().zip(&base.points).all(|(a, b)| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9)); +} + +fn close(a: (f64, f64), b: (f64, f64), eps: f64) -> bool { + (a.0 - b.0).abs() < eps && (a.1 - b.1).abs() < eps +} + +#[test] +fn styles_parse_and_round_trip_names() { + for s in WarpStyle::all() { + assert_eq!(WarpStyle::parse(s.id()), Some(s)); + assert_eq!(WarpStyle::parse(s.psd_name()), Some(s)); + assert_eq!(WarpStyle::parse(s.label()), Some(s), "{s:?}"); + } + assert_eq!(WarpStyle::parse("spiral"), None); +} + +#[test] +fn presets_at_bend_zero_are_identity() { + for s in WarpStyle::PRESETS { + let w = Warp::preset(s, 0.0, B); + assert!(w.is_identity()); + assert_eq!(w.map(33.0, 44.0), (33.0, 44.0)); + } +} + +#[test] +fn identity_mesh_is_exact_and_fit_reproduces_affine() { + let m = BezierMesh::identity(B, 1, 1); + assert_eq!((m.nx(), m.ny()), (4, 4)); + let w = Warp::custom(m, B); + assert!(w.is_identity()); + assert!(close(w.map(37.5, 61.25), (37.5, 61.25), 1e-9)); + // Affine maps fit exactly. + let f = |s: f64, t: f64| [3.0 + 2.0 * s - t, 1.0 + 0.5 * s + 4.0 * t]; + let m = BezierMesh::fit(&f, vec![0.0, 1.0], vec![0.0, 0.4, 1.0]); + for (s, t) in [(0.1, 0.9), (0.5, 0.2), (0.77, 0.41)] { + let p = m.eval(s, t); + let e = f(s, t); + assert!((p[0] - e[0]).abs() < 1e-9 && (p[1] - e[1]).abs() < 1e-9); + } +} + +#[test] +fn remove_split_u_rejects_out_of_range_indices() { + let original = BezierMesh::identity(B, 2, 3); + for k in [0, original.us.len() - 1, original.us.len(), usize::MAX - 1, usize::MAX] { + let mut mesh = original.clone(); + assert!(!mesh.remove_split_u(k), "index {k}"); + assert_eq!(mesh, original, "index {k} must leave the mesh unchanged"); + } +} + +#[test] +fn remove_split_v_rejects_out_of_range_indices() { + let original = BezierMesh::identity(B, 2, 3); + for k in [0, original.vs.len() - 1, original.vs.len(), usize::MAX - 1, usize::MAX] { + let mut mesh = original.clone(); + assert!(!mesh.remove_split_v(k), "index {k}"); + assert_eq!(mesh, original, "index {k} must leave the mesh unchanged"); + } +} + +#[test] +fn splits_are_exact_and_removable() { + let mut m = BezierMesh::identity(B, 1, 1); + // Bend it: move an inner control point. + m.points[5] = [50.0, 10.0]; + let before: Vec<[f64; 2]> = (0..=10).flat_map(|j| (0..=10).map(move |i| (i, j))).map(|(i, j)| m.eval(i as f64 / 10.0, j as f64 / 10.0)).collect(); + let orig = m.clone(); + assert!(m.split_u(0.3)); + assert!(m.split_v(0.6)); + assert!(!m.split_u(0.3), "existing boundary"); + assert_eq!((m.nx(), m.ny()), (7, 7)); + assert!(m.is_valid()); + let after: Vec<[f64; 2]> = (0..=10).flat_map(|j| (0..=10).map(move |i| (i, j))).map(|(i, j)| m.eval(i as f64 / 10.0, j as f64 / 10.0)).collect(); + for (a, b) in before.iter().zip(&after) { + assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9); + } + let (ls, lt) = m.param_at(m.eval(0.42, 0.77)); + assert!((ls - 0.42).abs() < 1e-6 && (lt - 0.77).abs() < 1e-6, "{ls},{lt}"); + assert!(m.remove_split_u(1)); + assert!(m.remove_split_v(1)); + assert_eq!(m.us, orig.us); + for (a, b) in m.points.iter().zip(&orig.points) { + assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9); + } +} + +const SQUARE: [f64; 4] = [128.0, 128.0, 384.0, 384.0]; +const WIDE: [f64; 4] = [128.0, 208.0, 384.0, 304.0]; +const TALL: [f64; 4] = [208.0, 128.0, 304.0, 384.0]; + +/// Photoshop 27.11, measured: a 256 px grid image whose colours encode each pixel's own +/// position, warped in a 512 px document over the box (128, 128)–(384, 384). Each pair is a +/// source point and where Photoshop put it. +#[test] +fn presets_match_photoshop() { + type Case = (WarpStyle, f64, f64, f64, bool, [([f64; 2], [f64; 2]); 3]); + let cases: [Case; 9] = [ + (WarpStyle::Arc, 50.0, 0.0, 0.0, false, [([272.5, 155.5], [296.5, 104.5]), ([331.5, 182.5], [424.5, 168.5]), ([259.5, 157.5], [264.5, 104.5])]), + (WarpStyle::Arc, -100.0, 0.0, 0.0, false, [([277.5, 354.5], [344.5, 472.5]), ([140.5, 218.5], [40.5, 168.5]), ([172.5, 237.5], [56.5, 264.5])]), + (WarpStyle::Flag, 50.0, 0.0, 0.0, false, [([136.5, 143.5], [136.5, 120.5]), ([136.5, 159.5], [136.5, 136.5]), ([136.5, 175.5], [136.5, 152.5])]), + (WarpStyle::Twist, -50.0, 0.0, 0.0, false, [([148.5, 205.5], [152.5, 216.5]), ([197.5, 212.5], [200.5, 232.5]), ([134.5, 212.5], [136.5, 216.5])]), + (WarpStyle::ShellLower, 50.0, 0.0, 0.0, false, [([248.5, 136.5], [248.5, 136.5]), ([264.5, 136.5], [264.5, 136.5]), ([232.5, 136.5], [232.5, 136.5])]), + (WarpStyle::Fish, -100.0, 0.0, 0.0, false, [([296.5, 355.5], [296.5, 440.5]), ([344.5, 298.5], [344.5, 344.5]), ([328.5, 356.5], [328.5, 472.5])]), + (WarpStyle::Bulge, 50.0, 50.0, 0.0, false, [([293.5, 147.5], [296.5, 88.5]), ([293.5, 375.5], [296.5, 440.5]), ([340.5, 281.5], [344.5, 296.5])]), + (WarpStyle::Arc, 50.0, 0.0, -50.0, false, [([181.5, 350.5], [184.5, 328.5]), ([291.5, 372.5], [280.5, 344.5]), ([232.5, 349.5], [232.5, 312.5])]), + (WarpStyle::Arc, 50.0, 0.0, 0.0, true, [([155.5, 272.5], [104.5, 296.5]), ([182.5, 331.5], [168.5, 424.5]), ([157.5, 259.5], [104.5, 264.5])]), + ]; + // Wide (256 × 96 at 128, 208) and tall (96 × 256 at 208, 128) boxes, and a vertical warp + // with distortion. + type Boxed = (WarpStyle, f64, f64, f64, bool, [f64; 4], [([f64; 2], [f64; 2]); 2]); + let boxed: [Boxed; 6] = [ + (WarpStyle::Arc, 50.0, 0.0, 0.0, false, WIDE, [([144.5, 269.6], [120.5, 264.5]), ([271.5, 220.42], [280.5, 168.5])]), + (WarpStyle::Bulge, 50.0, 0.0, 0.0, false, TALL, [([249.11, 374.5], [248.5, 392.5]), ([249.11, 360.5], [248.5, 376.5])]), + (WarpStyle::Flag, 50.0, 0.0, 0.0, true, WIDE, [([137.5, 296.42], [184.5, 296.5]), ([153.5, 296.42], [200.5, 296.5])]), + (WarpStyle::Rise, 50.0, 0.0, 0.0, true, TALL, [([250.97, 152.5], [344.5, 152.5]), ([301.26, 264.5], [344.5, 264.5])]), + (WarpStyle::Bulge, 60.0, 20.0, -10.0, false, WIDE, [([208.5, 224.15], [200.5, 184.5]), ([219.5, 277.42], [216.5, 296.5])]), + (WarpStyle::Arc, 50.0, 30.0, 0.0, true, SQUARE, [([331.5, 327.5], [296.5, 360.5]), ([318.5, 240.5], [264.5, 232.5])]), + ]; + let all = cases.iter().map(|c| (c.0, c.1, c.2, c.3, c.4, SQUARE, c.5.to_vec())).chain(boxed.iter().map(|c| (c.0, c.1, c.2, c.3, c.4, c.5, c.6.to_vec()))); + for (style, bend, hd, vd, vertical, bounds, pairs) in all { + let w = Warp { h_distort: hd, v_distort: vd, vertical, ..Warp::preset(style, bend, bounds) }; + for (src, want) in pairs { + let got = w.map(src[0], src[1]); + let d = (got.0 - want[0]).hypot(got.1 - want[1]); + assert!(d < 1.5, "{style:?} {bend} h{hd} v{vd} vertical {vertical} {bounds:?}: {src:?} -> {got:?}, Photoshop {want:?}"); + } + } +} + +#[test] +fn preset_fits_closely_as_mesh_and_affine_composes() { + let w = Warp::preset(WarpStyle::Bulge, 40.0, B); + let m = Warp::custom(w.to_mesh(4, 4), B); + for (x, y) in [(20.0, 30.0), (60.0, 45.0), (100.0, 65.0)] { + assert!(close(w.map(x, y), m.map(x, y), 0.5), "{:?} vs {:?}", w.map(x, y), m.map(x, y)); + } + let t = Warp::custom(BezierMesh::identity(B, 1, 1), B).then_affine([1.0, 0.0, 0.0, 1.0, 5.0, -2.0]); + assert!(close(t.map(50.0, 50.0), (55.0, 48.0), 1e-9)); + let ob = Warp::none(B).output_bounds(); + assert!((ob[0] - 10.0).abs() < 1e-9 && (ob[3] - 70.0).abs() < 1e-9); +} + +/// A cylinder over a 1000 × 1000 source like #4112's: silhouettes at x 100 and 900, edges at +/// y 200 (top) and 800 (bottom), ellipses 0.3 deep, half wrapped round. +const CYL: [f64; 7] = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5]; + +#[test] +fn cylinder_style_is_read_and_named_but_not_a_bend_preset() { + for s in ["cylinder", "warpCylinder", "Cylinder"] { + assert_eq!(WarpStyle::parse(s), Some(WarpStyle::Cylinder), "{s}"); + } + assert_eq!(WarpStyle::Cylinder.psd_name(), "warpCylinder"); + assert_eq!(WarpStyle::Cylinder.id(), "cylinder"); + assert!(!WarpStyle::Cylinder.is_preset()); + assert!(StyleWarp::new(WarpStyle::Cylinder, 50.0, 0.0, 0.0, false, B).is_none()); + // The Warp menus list what they can edit. + assert!(WarpStyle::all().all(|s| s != WarpStyle::Cylinder)); + assert_eq!(WarpStyle::all().filter(|s| s.is_preset()).count(), 15); +} + +#[test] +fn cylinder_values_that_describe_no_cylinder_are_refused() { + assert!(cylinder_mesh(&CYL[..6]).is_none(), "six values"); + assert!(cylinder_mesh(&[CYL.as_slice(), &[0.0]].concat()).is_none(), "eight values"); + for i in 0..7 { + for bad in [f64::NAN, f64::INFINITY] { + let mut v = CYL; + v[i] = bad; + assert!(cylinder_mesh(&v).is_none(), "value {i} = {bad}"); + } + } + let mut v = CYL; + v[2] = v[0]; + assert!(Warp::cylinder(&v, [0.0, 0.0, 1000.0, 1000.0]).is_none(), "no width"); + v[2] = 50.0; + assert!(Warp::cylinder(&v, [0.0, 0.0, 1000.0, 1000.0]).is_none(), "right silhouette left of the left one"); +} + +#[test] +fn cylinder_wraps_the_contents_between_its_silhouettes() { + let w = Warp::cylinder(&CYL, [0.0, 0.0, 1000.0, 1000.0]).unwrap(); + assert_eq!(w.style, WarpStyle::Cylinder); + assert_eq!(w.values, CYL); + assert!(!w.is_identity()); + let m = w.mesh.as_ref().unwrap(); + assert_eq!((m.nx(), m.ny()), (13, 4)); + let [ul, ..] = cylinder_shape(0.5); + assert!((m.us[1] - ul).abs() < 1e-12 && (m.us[3] - (1.0 - ul)).abs() < 1e-12); + // The middle of the contents is at the front: centred, on the ellipses' near side. + assert!(close(w.map(500.0, 0.0), (500.0, 200.0 + 0.3 * 400.0), 1e-9)); + assert!(close(w.map(500.0, 1000.0), (500.0, 800.0 + 0.3 * 400.0), 1e-9)); + // What wraps round the back lies on the silhouettes, at the edges' ends. + for x in [0.0, ul * 500.0, ul * 1000.0] { + assert!(close(w.map(x, 0.0), (100.0, 200.0), 1e-9), "{x}"); + assert!(close(w.map(1000.0 - x, 1000.0), (900.0, 800.0), 1e-9), "{x}"); + } + // Across the front x only grows, and the two halves mirror each other. + let mut last = f64::MIN; + for i in 0..=200 { + let x = 1000.0 * (ul + (1.0 - 2.0 * ul) * f64::from(i) / 200.0); + let (px, py) = w.map(x, 400.0); + assert!(px >= last - 1e-9, "x {x}"); + last = px; + let (qx, qy) = w.map(1000.0 - x, 400.0); + assert!(close((px - 500.0, py), (500.0 - qx, qy), 1e-9), "x {x}"); + } + // Every point stays inside the control-point box the placement frames. + let cb = m.control_bounds(); + let ob = w.output_bounds(); + assert!(ob[0] >= cb[0] - 1e-9 && ob[1] >= cb[1] - 1e-9 && ob[2] <= cb[2] + 1e-9 && ob[3] <= cb[3] + 1e-9); + assert!((cb[0] - 100.0).abs() < 1e-9 && (cb[2] - 900.0).abs() < 1e-9); + // The box's bottom is the lower ellipse's deepest control point (`my` > 1). + assert!((cb[3] - (800.0 + 0.3 * 400.0 * cylinder_shape(0.5)[3])).abs() < 1e-9); + assert_eq!(w.to_mesh(4, 4), *m, "a cylinder is its own mesh"); +} + +#[test] +fn cylinder_shape_follows_the_measured_rows() { + assert_eq!(cylinder_shape(0.0), CYLINDER_SHAPE[0]); + assert_eq!(cylinder_shape(1.0), CYLINDER_SHAPE[40]); + assert_eq!(cylinder_shape(-3.0), CYLINDER_SHAPE[0]); + assert_eq!(cylinder_shape(7.0), CYLINDER_SHAPE[40]); + assert_eq!(cylinder_shape(f64::NAN), CYLINDER_SHAPE[0]); + let mid = cylinder_shape(0.0125); + for k in 0..4 { + assert!((mid[k] - (CYLINDER_SHAPE[0][k] + CYLINDER_SHAPE[1][k]) / 2.0).abs() < 1e-12); + } + // The more it wraps, the less of the contents is on the back. + assert!(CYLINDER_SHAPE.windows(2).all(|r| r[1][0] < r[0][0])); +} + +#[test] +fn is_identity_rejects_malformed_custom_mesh_without_allocating() { + let us: Vec = (0..=1000).map(|i| i as f64 / 1000.0).collect(); + let vs: Vec = (0..=1000).map(|i| i as f64 / 1000.0).collect(); + let malformed = BezierMesh { us, vs, points: Vec::new() }; + assert!(!malformed.is_valid()); + let w = Warp::custom(malformed.clone(), B); + assert!(!w.is_identity()); + assert_eq!(malformed.eval(0.5, 0.5), [0.0, 0.0]); +} + +#[test] +fn locate_binary_search_matches_linear_scan() { + let knots = [0.0, 0.1, 0.25, 0.5, 0.85, 1.0]; + let linear = |s: f64| { + let n = knots.len() - 1; + let s = if s.is_finite() { s.clamp(0.0, 1.0) } else { 0.0 }; + let mut i = 0; + while i + 1 < n && s > knots[i + 1] { + i += 1; + } + let w = knots[i + 1] - knots[i]; + (i, if w > 0.0 { (s - knots[i]) / w } else { 0.0 }) + }; + for k in -10..=110 { + let s = k as f64 / 100.0; + assert_eq!(BezierMesh::locate(&knots, s), linear(s), "s={s}"); + } + for &s in &knots { + assert_eq!(BezierMesh::locate(&knots, s), linear(s), "knot={s}"); + } + assert_eq!(BezierMesh::locate(&knots, f64::NAN), linear(f64::NAN)); +} From dc9e4c16b8fa90e25d60d84ff4e8503f7c83a0e1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:26 +0000 Subject: [PATCH 048/259] refactor(color): move blend.rs tests to blend/tests.rs --- crates/color/src/blend.rs | 404 +------------------------------- crates/color/src/blend/tests.rs | 401 +++++++++++++++++++++++++++++++ 2 files changed, 402 insertions(+), 403 deletions(-) create mode 100644 crates/color/src/blend/tests.rs diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs index 508c26977e..101a84fb91 100644 --- a/crates/color/src/blend.rs +++ b/crates/color/src/blend.rs @@ -486,406 +486,4 @@ pub fn composite_atop(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opa } #[cfg(test)] -mod tests { - use super::*; - - const E: f32 = 1e-5; - - fn close(a: f32, b: f32) -> bool { - (a - b).abs() < E - } - - #[test] - fn psd_keys_roundtrip_and_unique() { - let mut seen = std::collections::HashSet::new(); - for m in std::iter::once(BlendMode::PassThrough).chain(BlendMode::LAYER_MODES) { - assert!(seen.insert(m.psd_key()), "duplicate key {m:?}"); - assert_eq!(BlendMode::from_psd_key(m.psd_key()), Some(m)); - } - assert_eq!(BlendMode::from_psd_key(*b"zzzz"), None); - assert_eq!(seen.len(), 28); - } - - #[test] - fn paint_net_modes_keep_their_math_and_distinct_psd_status() { - assert!(close(blend_channel(BlendMode::Reflect, 0.5, 0.5), 0.5)); - assert!(close(blend_channel(BlendMode::Reflect, 0.2, 0.0), 0.04)); - assert!(close(blend_channel(BlendMode::Glow, 0.5, 0.2), 0.08)); - assert!(close(blend_channel(BlendMode::Negation, 0.2, 0.7), 0.9)); - assert_eq!(blend_channel(BlendMode::Reflect, 0.0, 1.0), 1.0); - assert_eq!(blend_channel(BlendMode::Glow, 1.0, 0.0), 1.0); - assert_eq!(blend_channel(BlendMode::PaintNetColorBurn, 1.0, 0.0), 0.0); - assert_eq!(blend_channel(BlendMode::PaintNetColorDodge, 0.0, 1.0), 1.0); - for b in 0..=255u8 { - for s in 0..=255u8 { - assert!(close(blend_channel(BlendMode::Xor, f32::from(b) / 255.0, f32::from(s) / 255.0), f32::from(b ^ s) / 255.0)); - } - } - for mode in BlendMode::PAINT_NET_MODES { - assert!(!mode.has_psd_equivalent()); - assert_eq!(mode.psd_key(), *b"norm"); - for b in [0.0, 0.1, 0.5, 1.0] { - for s in [0.0, 0.1, 0.5, 1.0] { - let v = blend_channel(mode, b, s); - assert!(v.is_finite() && (0.0..=1.0).contains(&v), "{mode:?}"); - } - } - } - assert_eq!(BlendMode::layer_modes().count(), 33); - } - - #[test] - fn normal_is_source() { - for &(cb, cs) in &[(0.2, 0.7), (1.0, 0.0), (0.0, 1.0)] { - assert!(close(blend_channel(BlendMode::Normal, cb, cs), cs)); - } - } - - #[test] - fn identities_with_white_and_black() { - // Multiply by white / screen with black / add black / darken with white leave backdrop unchanged. - for cb in [0.0f32, 0.1, 0.5, 0.9, 1.0] { - assert!(close(blend_channel(BlendMode::Multiply, cb, 1.0), cb)); - assert!(close(blend_channel(BlendMode::Screen, cb, 0.0), cb)); - assert!(close(blend_channel(BlendMode::LinearDodge, cb, 0.0), cb)); - assert!(close(blend_channel(BlendMode::Darken, cb, 1.0), cb)); - assert!(close(blend_channel(BlendMode::Lighten, cb, 0.0), cb)); - assert!(close(blend_channel(BlendMode::Difference, cb, 0.0), cb)); - assert!(close(blend_channel(BlendMode::Subtract, cb, 0.0), cb)); - assert!(close(blend_channel(BlendMode::LinearBurn, cb, 1.0), cb)); - assert!(close(blend_channel(BlendMode::Exclusion, cb, 0.0), cb)); - // 50% gray is neutral for the "light" family - assert!(close(blend_channel(BlendMode::HardLight, cb, 0.5), cb)); - assert!(close(blend_channel(BlendMode::SoftLight, cb, 0.5), cb)); - assert!(close(blend_channel(BlendMode::LinearLight, cb, 0.5), cb)); - } - } - - #[test] - fn known_values() { - assert!(close(blend_channel(BlendMode::Multiply, 0.5, 0.5), 0.25)); - assert!(close(blend_channel(BlendMode::Screen, 0.5, 0.5), 0.75)); - assert!(close(blend_channel(BlendMode::Overlay, 0.25, 0.5), 0.25)); - assert!(close(blend_channel(BlendMode::Overlay, 0.75, 1.0), 1.0)); - assert!(close(blend_channel(BlendMode::ColorDodge, 0.5, 0.5), 1.0)); - assert!(close(blend_channel(BlendMode::ColorBurn, 0.5, 0.5), 0.0)); - assert!(close(blend_channel(BlendMode::ColorBurn, 1.0, 0.0), 1.0)); - assert!(close(blend_channel(BlendMode::ColorDodge, 0.0, 1.0), 0.0)); - assert!(close(blend_channel(BlendMode::Divide, 0.25, 0.5), 0.5)); - assert!(close(blend_channel(BlendMode::Divide, 0.0, 0.0), 0.0)); - assert!(close(blend_channel(BlendMode::Divide, 0.3, 0.0), 1.0)); - assert!(close(blend_channel(BlendMode::Exclusion, 0.5, 0.5), 0.5)); - assert!(close(blend_channel(BlendMode::PinLight, 0.8, 0.2), 0.4)); - assert!(close(blend_channel(BlendMode::PinLight, 0.1, 0.9), 0.8)); - assert!(close(blend_channel(BlendMode::HardMix, 0.6, 0.4), 1.0)); - assert!(close(blend_channel(BlendMode::HardMix, 0.6, 0.3), 0.0)); - } - - /// #8804: Photoshop's Soft Light over a dark backdrop (cb ≤ 0.25, cs > 0.5) follows the W3C - /// curve `D(cb) = ((16·cb − 12)·cb + 4)·cb`, not `sqrt(cb)`. Measured on psd-tools - /// `blend-modes/rgb-blend-modes.psd` (Photoshop's merged image), in 8-bit levels: - /// (backdrop, source, Photoshop). - #[test] - fn soft_light_follows_photoshop_over_dark_backdrops() { - for (cb, cs, ps) in [(4u8, 247u8, 11.0f32), (6, 254, 19.0), (9, 252, 25.0), (10, 237, 32.0), (14, 253, 46.0)] { - let got = blend_channel(BlendMode::SoftLight, f32::from(cb) / 255.0, f32::from(cs) / 255.0) * 255.0; - assert!((got - ps).abs() <= 7.0, "cb {cb} cs {cs}: {got} vs Photoshop {ps}"); - } - } - - #[test] - fn soft_light_is_the_w3c_formula() { - let d = |cb: f32| if cb <= 0.25 { ((16.0 * cb - 12.0) * cb + 4.0) * cb } else { cb.sqrt() }; - let w3c = |cb: f32, cs: f32| if cs <= 0.5 { cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb) } else { cb + (2.0 * cs - 1.0) * (d(cb) - cb) }; - for b in (0..=255u8).step_by(3) { - for s in (0..=255u8).step_by(5) { - let (cb, cs) = (f32::from(b) / 255.0, f32::from(s) / 255.0); - let got = blend_channel(BlendMode::SoftLight, cb, cs); - assert!((got - w3c(cb, cs)).abs() < 1e-5, "cb {b} cs {s}: {got} vs {}", w3c(cb, cs)); - } - } - // Continuous where the two halves of D meet (both give 0.5 at cb = 0.25). - let below = blend_channel(BlendMode::SoftLight, 0.25, 1.0); - let above = blend_channel(BlendMode::SoftLight, 0.25 + 1e-6, 1.0); - assert!(close(below, 0.5) && (above - below).abs() < 1e-4, "{below} {above}"); - // A negative backdrop (32-bit documents) counts as black under a light source, as before. - assert!(close(blend_channel(BlendMode::SoftLight, -0.1, 1.0), 0.0)); - } - - #[test] - fn vivid_light_source_extremes_and_interior_values() { - for cb in [0.0, 0.25, 0.5, 0.75, 1.0] { - assert_eq!(blend_channel(BlendMode::VividLight, cb, 0.0), 0.0); - assert_eq!(blend_channel(BlendMode::VividLight, cb, 1.0), 1.0); - } - assert!(close(blend_channel(BlendMode::VividLight, 0.75, 0.25), 0.5)); - assert!(close(blend_channel(BlendMode::VividLight, 0.25, 0.75), 0.5)); - } - - #[test] - fn hard_mix_matches_photoshop_extremes_and_interior_values() { - assert_eq!(blend_channel(BlendMode::HardMix, 1.0, 0.0), 1.0); - assert_eq!(blend_channel(BlendMode::HardMix, 0.0, 1.0), 0.0); - assert_eq!(blend_channel(BlendMode::HardMix, 1.0 - 1e-5, 0.0), 1.0); - assert_eq!(blend_channel(BlendMode::HardMix, 1e-5, 1.0), 0.0); - assert_eq!(blend_channel(BlendMode::HardMix, 0.6, 0.4), 1.0); - assert_eq!(blend_channel(BlendMode::HardMix, 0.6, 0.3), 0.0); - } - - #[test] - fn vivid_light_and_hard_mix_composite_extremes() { - assert_eq!(composite(BlendMode::VividLight, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0], 1.0), [0.0, 0.0, 0.0, 1.0]); - assert_eq!(composite(BlendMode::VividLight, [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], 1.0), [1.0, 1.0, 1.0, 1.0]); - assert_eq!(composite(BlendMode::HardMix, [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], 1.0), [0.0, 0.0, 0.0, 1.0]); - assert_eq!(composite(BlendMode::HardMix, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0], 1.0), [1.0, 1.0, 1.0, 1.0]); - } - - #[test] - fn separable_outputs_stay_in_unit_range() { - let steps: Vec = (0..=20).map(|i| i as f32 / 20.0).collect(); - for m in BlendMode::LAYER_MODES { - for &cb in &steps { - for &cs in &steps { - let v = blend_rgb(m, [cb, cs, 0.5], [cs, cb, 0.25]); - for c in v { - assert!((-E..=1.0 + E).contains(&c), "{m:?} cb={cb} cs={cs} -> {c}"); - } - } - } - } - } - - #[test] - fn add_and_divide_clip_at_integer_depths_but_not_in_float() { - // Integer depths: Photoshop clips Linear Dodge (Add) and Divide at 1. - assert_eq!(blend_channel(BlendMode::LinearDodge, 2.0, 0.5), 1.0); - assert_eq!(blend_channel(BlendMode::LinearDodge, 0.75, 0.5), 1.0); - assert_eq!(blend_channel(BlendMode::Divide, 2.0, 0.5), 1.0); - assert_eq!(blend_channel(BlendMode::Divide, 0.5, 0.25), 1.0); - // 32-bit float: light adds up past 1 (adding light never darkens). - assert!(close(blend_channel_hdr(BlendMode::LinearDodge, 2.0, 0.5), 2.5)); - assert!(close(blend_channel_hdr(BlendMode::LinearDodge, 0.75, 0.5), 1.25)); - assert!(close(blend_channel_hdr(BlendMode::Divide, 2.0, 0.5), 4.0)); - assert!(close(blend_channel_hdr(BlendMode::Divide, 0.5, 0.25), 2.0)); - assert_eq!(blend_rgb_hdr(BlendMode::LinearDodge, [2.0, 0.5, 4.0], [0.5, 0.25, 0.5]), [2.5, 0.75, 4.5]); - assert_eq!(blend_rgb_hdr(BlendMode::Divide, [2.0, 0.5, 4.0], [0.5, 0.25, 0.5]), [4.0, 2.0, 8.0]); - // Divide by zero keeps its guard; overflow stays finite. - assert_eq!(blend_channel_hdr(BlendMode::Divide, 0.0, 0.0), 0.0); - assert_eq!(blend_channel_hdr(BlendMode::Divide, 3.0, 0.0), 1.0); - assert_eq!(blend_channel_hdr(BlendMode::Divide, 3.0, -1.0), 1.0); - assert_eq!(blend_channel_hdr(BlendMode::Divide, f32::MAX, 1e-30), f32::MAX); - assert_eq!(blend_channel_hdr(BlendMode::LinearDodge, f32::MAX, f32::MAX), f32::MAX); - assert!(blend_channel_hdr(BlendMode::LinearDodge, f32::INFINITY, 1.0).is_finite()); - // Every other separable mode is unchanged (the non-separable ones keep values above 1: - // blend_rgb_within), and the in-range results agree. - for m in BlendMode::LAYER_MODES.into_iter().filter(|m| m.is_separable() && !matches!(m, BlendMode::LinearDodge | BlendMode::Divide)) { - for (cb, cs) in [(0.2, 0.3), (0.9, 0.05), (2.0, 0.5), (0.4, 1.5)] { - assert_eq!(blend_rgb(m, [cb, cs, 0.5], [cs, cb, 0.25]), blend_rgb_hdr(m, [cb, cs, 0.5], [cs, cb, 0.25]), "{m:?} cb={cb} cs={cs}"); - } - } - let (cb, cs) = ([0.2, 0.3, 0.1], [0.3, 0.4, 0.4]); - assert_eq!(blend_rgb_hdr(BlendMode::LinearDodge, cb, cs), blend_rgb(BlendMode::LinearDodge, cb, cs)); - assert_eq!(blend_rgb_hdr(BlendMode::Divide, cb, cs), blend_rgb(BlendMode::Divide, cb, cs)); - } - - #[test] - fn luminosity_and_color_swap_components() { - let cb = [0.8, 0.2, 0.2]; - let cs = [0.1, 0.1, 0.9]; - let l = blend_rgb(BlendMode::Luminosity, cb, cs); - assert!(close(lum(l), lum(cs))); - let c = blend_rgb(BlendMode::Color, cb, cs); - assert!(close(lum(c), lum(cb))); - let h = blend_rgb(BlendMode::Hue, cb, cs); - assert!(close(lum(h), lum(cb))); - let s = blend_rgb(BlendMode::Saturation, cb, [0.5, 0.5, 0.5]); - // zero-saturation source desaturates the backdrop - assert!(close(s[0], s[1]) && close(s[1], s[2])); - } - - /// ClipColor exactly as ISO 32000 / W3C write it (what `clip_color` was before it guarded - /// out-of-range luminosities). - fn spec_clip_color(c: [f32; 3]) -> [f32; 3] { - let l = lum(c); - let n = c[0].min(c[1]).min(c[2]); - let x = c[0].max(c[1]).max(c[2]); - let mut out = c; - if n < 0.0 { - let d = l - n; - for v in &mut out { - *v = if d.abs() < 1e-12 { l } else { l + (*v - l) * l / d }; - } - } - if x > 1.0 { - let d = x - l; - for v in &mut out { - *v = if d.abs() < 1e-12 { l } else { l + (*v - l) * (1.0 - l) / d }; - } - } - out - } - - fn spec_blend_rgb(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] { - let set_lum = |c: [f32; 3], l: f32| { - let d = l - lum(c); - spec_clip_color([c[0] + d, c[1] + d, c[2] + d]) - }; - match mode { - BlendMode::Hue => set_lum(set_sat(cs, sat(cb)), lum(cb)), - BlendMode::Saturation => set_lum(set_sat(cb, sat(cs)), lum(cb)), - BlendMode::Color => set_lum(cs, lum(cb)), - BlendMode::Luminosity => set_lum(cb, lum(cs)), - m => blend_rgb(m, cb, cs), - } - } - - const NON_SEPARABLE: [BlendMode; 4] = [BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity]; - - #[test] - fn non_separable_modes_unchanged_on_integer_inputs() { - // 8/16-bit documents only hold 0..1, where the luminosity stays in range (up to a - // rounding step at white) and ClipColor is the plain ISO 32000 formula. - let mut edges: Vec = vec![0.0, 1.0 / 255.0, 0.5, 254.0 / 255.0, 65534.0 / 65535.0, 1.0]; - edges.extend((0..=8).map(|i| i as f32 / 8.0)); - let mut colors = Vec::new(); - for &r in &edges { - for &g in &edges { - for &b in &edges { - colors.push([r, g, b]); - } - } - } - let mut seed = 0x1234_5678u32; - let mut next = |levels: u32| { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - ((seed >> 8) % (levels + 1)) as f32 / levels as f32 - }; - for _ in 0..2000 { - let levels = if next(1) > 0.5 { 255 } else { 65535 }; - colors.push([next(levels), next(levels), next(levels)]); - } - let mut worst = 0.0f32; - for (i, &cb) in colors.iter().enumerate() { - for &cs in colors.iter().skip(i % 7).step_by(7) { - for m in NON_SEPARABLE { - let (got, want) = (blend_rgb(m, cb, cs), spec_blend_rgb(m, cb, cs)); - for k in 0..3 { - worst = worst.max((got[k] - want[k]).abs()); - } - } - } - } - // Only white-ish colours whose luminosity rounds a step above 1 can differ, by a rounding step. - assert!(worst <= 1e-6, "{worst}"); - } - - #[test] - fn non_separable_modes_stable_when_luminosity_is_out_of_range() { - // The spec formula divided by `max − lum`, which is rounding noise for a grey above 1 and - // turns colours inside out when the luminosity is above 1: Luminosity of a grey of 2 over - // (0.5, 0.25, 0.125) gave (1.0, 2.32, 2.99). - let spec = spec_blend_rgb(BlendMode::Luminosity, [0.5, 0.25, 0.125], [2.0; 3]); - assert!(spec[0] < spec[2], "{spec:?}"); - let colors: [[f32; 3]; 10] = [ - [1.0, 1.0, 1.0], - [1.5, 1.5, 1.5], - [2.0, 2.0, 2.0], - [4.0, 4.0, 4.0], - [1000.0, 1000.0, 1000.0], - [2.0, 2.0, 1.999_999], - [4.0, 3.999_9, 4.0], - [3.0, 0.25, 0.125], - [1.25, 0.875, 3.75], - [-0.25, 0.5, 1.375], - ]; - for top in [1.0, f32::MAX] { - for m in NON_SEPARABLE { - for cb in colors { - for cs in colors { - let r = blend_rgb_within(m, cb, cs, top); - assert!(r.iter().all(|v| v.is_finite()), "{m:?} {cb:?} {cs:?} {top}: {r:?}"); - // The target luminosity is kept, at any depth. - let want = if m == BlendMode::Luminosity { lum(cs) } else { lum(cb) }; - if want >= 0.0 { - assert!((lum(r) - want).abs() <= 1e-4 * want.max(1.0), "{m:?} {cb:?} {cs:?} {top}: {r:?}"); - } - let (lo, hi) = (r[0].min(r[1]).min(r[2]), r[0].max(r[1]).max(r[2])); - if top == 1.0 { - // In gamut, or (a luminosity above 1 has no in-gamut colour) its grey. - assert!((lo >= 0.0 && hi <= 1.0 + E) || hi - lo <= 1e-6 * hi, "{m:?} {cb:?} {cs:?}: {r:?}"); - } else { - assert!(lo >= -1e-6 * hi.max(1.0), "{m:?} {cb:?} {cs:?}: {r:?}"); - } - } - } - } - } - // 32-bit: a grey backdrop gives a grey of its own luminosity in Hue and Saturation, a - // grey source a grey in Color, and bright colours keep their values above 1. - for g in [1.5f32, 2.0, 4.0, 1000.0] { - let grey = [g; 3]; - for cs in colors { - for m in [BlendMode::Hue, BlendMode::Saturation] { - let r = blend_rgb_within(m, grey, cs, f32::MAX); - assert!(r.iter().all(|&v| (v - lum(grey)).abs() <= 1e-5 * g), "{m:?} {g} {cs:?}: {r:?}"); - } - } - let r = blend_rgb_within(BlendMode::Luminosity, [0.5, 0.25, 0.125], grey, f32::MAX); - assert!(r[0] > 1.0 && r[0] > r[1] && r[1] > r[2], "{g}: {r:?}"); - let r = blend_rgb_within(BlendMode::Color, grey, [3.0, 0.25, 0.125], f32::MAX); - assert!(r[0] > 1.0 && r[0] > r[1] && r[1] > r[2], "{g}: {r:?}"); - // Integer documents: no colour of that luminosity fits in 0..1, so it is its grey. - let r = blend_rgb_within(BlendMode::Luminosity, [0.5, 0.25, 0.125], grey, 1.0); - assert!(r.iter().all(|&v| (v - lum(grey)).abs() <= 1e-5 * g), "{g}: {r:?}"); - } - // Continuous across near-greys: the result barely moves from the grey's. - for m in NON_SEPARABLE { - let a = blend_rgb_within(m, [2.0, 2.0, 2.0], [4.0, 4.0, 4.0], f32::MAX); - let b = blend_rgb_within(m, [2.0, 2.0, 1.999_999], [4.0, 3.999_999, 4.0], f32::MAX); - assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1e-4), "{m:?}: {a:?} {b:?}"); - } - } - - #[test] - fn darker_lighter_color_pick_whole_pixel() { - let a = [0.9, 0.1, 0.1]; - let b = [0.2, 0.6, 0.2]; - assert_eq!(blend_rgb(BlendMode::DarkerColor, a, b), if lum(b) < lum(a) { b } else { a }); - assert_eq!(blend_rgb(BlendMode::LighterColor, a, b), if lum(b) > lum(a) { b } else { a }); - } - - #[test] - fn composite_alpha_rules() { - let bg = [0.2, 0.4, 0.6, 1.0]; - // Transparent source leaves backdrop. - assert_eq!(composite(BlendMode::Multiply, bg, [1.0, 0.0, 0.0, 0.0], 1.0), bg); - // Opaque normal source replaces. - let r = composite(BlendMode::Normal, bg, [1.0, 0.0, 0.0, 1.0], 1.0); - assert!(close(r[0], 1.0) && close(r[3], 1.0)); - // Half opacity normal = lerp. - let r = composite(BlendMode::Normal, bg, [1.0, 1.0, 1.0, 1.0], 0.5); - assert!(close(r[0], 0.6) && close(r[1], 0.7) && close(r[2], 0.8)); - // Blend over transparent backdrop yields source regardless of mode. - let r = composite(BlendMode::Multiply, [0.0; 4], [0.3, 0.5, 0.7, 1.0], 1.0); - assert!(close(r[0], 0.3) && close(r[1], 0.5) && close(r[2], 0.7) && close(r[3], 1.0)); - // Alpha accumulates. - let r = composite(BlendMode::Screen, [0.0, 0.0, 0.0, 0.5], [0.0, 0.0, 0.0, 0.5], 1.0); - assert!(close(r[3], 0.75)); - } - - #[test] - fn composite_atop_keeps_alpha_and_moves_colour_by_source_alpha() { - let bg = [1.0, 1.0, 1.0, 0.5]; - // Half-transparent white, black at 50%: halfway, alpha kept (#5783). - let r = composite_atop(BlendMode::Normal, bg, [0.0, 0.0, 0.0, 1.0], 0.5); - assert!(close(r[0], 0.5) && close(r[2], 0.5) && r[3] == 0.5, "{r:?}"); - // Non-Normal modes blend against the backdrop as it is: Multiply by black at 50% halves it. - let r = composite_atop(BlendMode::Multiply, bg, [0.0, 0.0, 0.0, 1.0], 0.5); - assert!(close(r[0], 0.5) && r[3] == 0.5, "{r:?}"); - // Opaque backdrops agree with source-over. - let opaque = [0.2, 0.4, 0.6, 1.0]; - assert_eq!(composite_atop(BlendMode::Screen, opaque, [0.5, 0.5, 0.5, 0.7], 0.8), composite(BlendMode::Screen, opaque, [0.5, 0.5, 0.5, 0.7], 0.8)); - // A transparent source leaves the backdrop. - assert_eq!(composite_atop(BlendMode::Normal, bg, [0.0, 0.0, 0.0, 0.0], 1.0), bg); - } -} +mod tests; diff --git a/crates/color/src/blend/tests.rs b/crates/color/src/blend/tests.rs new file mode 100644 index 0000000000..156580e206 --- /dev/null +++ b/crates/color/src/blend/tests.rs @@ -0,0 +1,401 @@ +use super::*; + +const E: f32 = 1e-5; + +fn close(a: f32, b: f32) -> bool { + (a - b).abs() < E +} + +#[test] +fn psd_keys_roundtrip_and_unique() { + let mut seen = std::collections::HashSet::new(); + for m in std::iter::once(BlendMode::PassThrough).chain(BlendMode::LAYER_MODES) { + assert!(seen.insert(m.psd_key()), "duplicate key {m:?}"); + assert_eq!(BlendMode::from_psd_key(m.psd_key()), Some(m)); + } + assert_eq!(BlendMode::from_psd_key(*b"zzzz"), None); + assert_eq!(seen.len(), 28); +} + +#[test] +fn paint_net_modes_keep_their_math_and_distinct_psd_status() { + assert!(close(blend_channel(BlendMode::Reflect, 0.5, 0.5), 0.5)); + assert!(close(blend_channel(BlendMode::Reflect, 0.2, 0.0), 0.04)); + assert!(close(blend_channel(BlendMode::Glow, 0.5, 0.2), 0.08)); + assert!(close(blend_channel(BlendMode::Negation, 0.2, 0.7), 0.9)); + assert_eq!(blend_channel(BlendMode::Reflect, 0.0, 1.0), 1.0); + assert_eq!(blend_channel(BlendMode::Glow, 1.0, 0.0), 1.0); + assert_eq!(blend_channel(BlendMode::PaintNetColorBurn, 1.0, 0.0), 0.0); + assert_eq!(blend_channel(BlendMode::PaintNetColorDodge, 0.0, 1.0), 1.0); + for b in 0..=255u8 { + for s in 0..=255u8 { + assert!(close(blend_channel(BlendMode::Xor, f32::from(b) / 255.0, f32::from(s) / 255.0), f32::from(b ^ s) / 255.0)); + } + } + for mode in BlendMode::PAINT_NET_MODES { + assert!(!mode.has_psd_equivalent()); + assert_eq!(mode.psd_key(), *b"norm"); + for b in [0.0, 0.1, 0.5, 1.0] { + for s in [0.0, 0.1, 0.5, 1.0] { + let v = blend_channel(mode, b, s); + assert!(v.is_finite() && (0.0..=1.0).contains(&v), "{mode:?}"); + } + } + } + assert_eq!(BlendMode::layer_modes().count(), 33); +} + +#[test] +fn normal_is_source() { + for &(cb, cs) in &[(0.2, 0.7), (1.0, 0.0), (0.0, 1.0)] { + assert!(close(blend_channel(BlendMode::Normal, cb, cs), cs)); + } +} + +#[test] +fn identities_with_white_and_black() { + // Multiply by white / screen with black / add black / darken with white leave backdrop unchanged. + for cb in [0.0f32, 0.1, 0.5, 0.9, 1.0] { + assert!(close(blend_channel(BlendMode::Multiply, cb, 1.0), cb)); + assert!(close(blend_channel(BlendMode::Screen, cb, 0.0), cb)); + assert!(close(blend_channel(BlendMode::LinearDodge, cb, 0.0), cb)); + assert!(close(blend_channel(BlendMode::Darken, cb, 1.0), cb)); + assert!(close(blend_channel(BlendMode::Lighten, cb, 0.0), cb)); + assert!(close(blend_channel(BlendMode::Difference, cb, 0.0), cb)); + assert!(close(blend_channel(BlendMode::Subtract, cb, 0.0), cb)); + assert!(close(blend_channel(BlendMode::LinearBurn, cb, 1.0), cb)); + assert!(close(blend_channel(BlendMode::Exclusion, cb, 0.0), cb)); + // 50% gray is neutral for the "light" family + assert!(close(blend_channel(BlendMode::HardLight, cb, 0.5), cb)); + assert!(close(blend_channel(BlendMode::SoftLight, cb, 0.5), cb)); + assert!(close(blend_channel(BlendMode::LinearLight, cb, 0.5), cb)); + } +} + +#[test] +fn known_values() { + assert!(close(blend_channel(BlendMode::Multiply, 0.5, 0.5), 0.25)); + assert!(close(blend_channel(BlendMode::Screen, 0.5, 0.5), 0.75)); + assert!(close(blend_channel(BlendMode::Overlay, 0.25, 0.5), 0.25)); + assert!(close(blend_channel(BlendMode::Overlay, 0.75, 1.0), 1.0)); + assert!(close(blend_channel(BlendMode::ColorDodge, 0.5, 0.5), 1.0)); + assert!(close(blend_channel(BlendMode::ColorBurn, 0.5, 0.5), 0.0)); + assert!(close(blend_channel(BlendMode::ColorBurn, 1.0, 0.0), 1.0)); + assert!(close(blend_channel(BlendMode::ColorDodge, 0.0, 1.0), 0.0)); + assert!(close(blend_channel(BlendMode::Divide, 0.25, 0.5), 0.5)); + assert!(close(blend_channel(BlendMode::Divide, 0.0, 0.0), 0.0)); + assert!(close(blend_channel(BlendMode::Divide, 0.3, 0.0), 1.0)); + assert!(close(blend_channel(BlendMode::Exclusion, 0.5, 0.5), 0.5)); + assert!(close(blend_channel(BlendMode::PinLight, 0.8, 0.2), 0.4)); + assert!(close(blend_channel(BlendMode::PinLight, 0.1, 0.9), 0.8)); + assert!(close(blend_channel(BlendMode::HardMix, 0.6, 0.4), 1.0)); + assert!(close(blend_channel(BlendMode::HardMix, 0.6, 0.3), 0.0)); +} + +/// #8804: Photoshop's Soft Light over a dark backdrop (cb ≤ 0.25, cs > 0.5) follows the W3C +/// curve `D(cb) = ((16·cb − 12)·cb + 4)·cb`, not `sqrt(cb)`. Measured on psd-tools +/// `blend-modes/rgb-blend-modes.psd` (Photoshop's merged image), in 8-bit levels: +/// (backdrop, source, Photoshop). +#[test] +fn soft_light_follows_photoshop_over_dark_backdrops() { + for (cb, cs, ps) in [(4u8, 247u8, 11.0f32), (6, 254, 19.0), (9, 252, 25.0), (10, 237, 32.0), (14, 253, 46.0)] { + let got = blend_channel(BlendMode::SoftLight, f32::from(cb) / 255.0, f32::from(cs) / 255.0) * 255.0; + assert!((got - ps).abs() <= 7.0, "cb {cb} cs {cs}: {got} vs Photoshop {ps}"); + } +} + +#[test] +fn soft_light_is_the_w3c_formula() { + let d = |cb: f32| if cb <= 0.25 { ((16.0 * cb - 12.0) * cb + 4.0) * cb } else { cb.sqrt() }; + let w3c = |cb: f32, cs: f32| if cs <= 0.5 { cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb) } else { cb + (2.0 * cs - 1.0) * (d(cb) - cb) }; + for b in (0..=255u8).step_by(3) { + for s in (0..=255u8).step_by(5) { + let (cb, cs) = (f32::from(b) / 255.0, f32::from(s) / 255.0); + let got = blend_channel(BlendMode::SoftLight, cb, cs); + assert!((got - w3c(cb, cs)).abs() < 1e-5, "cb {b} cs {s}: {got} vs {}", w3c(cb, cs)); + } + } + // Continuous where the two halves of D meet (both give 0.5 at cb = 0.25). + let below = blend_channel(BlendMode::SoftLight, 0.25, 1.0); + let above = blend_channel(BlendMode::SoftLight, 0.25 + 1e-6, 1.0); + assert!(close(below, 0.5) && (above - below).abs() < 1e-4, "{below} {above}"); + // A negative backdrop (32-bit documents) counts as black under a light source, as before. + assert!(close(blend_channel(BlendMode::SoftLight, -0.1, 1.0), 0.0)); +} + +#[test] +fn vivid_light_source_extremes_and_interior_values() { + for cb in [0.0, 0.25, 0.5, 0.75, 1.0] { + assert_eq!(blend_channel(BlendMode::VividLight, cb, 0.0), 0.0); + assert_eq!(blend_channel(BlendMode::VividLight, cb, 1.0), 1.0); + } + assert!(close(blend_channel(BlendMode::VividLight, 0.75, 0.25), 0.5)); + assert!(close(blend_channel(BlendMode::VividLight, 0.25, 0.75), 0.5)); +} + +#[test] +fn hard_mix_matches_photoshop_extremes_and_interior_values() { + assert_eq!(blend_channel(BlendMode::HardMix, 1.0, 0.0), 1.0); + assert_eq!(blend_channel(BlendMode::HardMix, 0.0, 1.0), 0.0); + assert_eq!(blend_channel(BlendMode::HardMix, 1.0 - 1e-5, 0.0), 1.0); + assert_eq!(blend_channel(BlendMode::HardMix, 1e-5, 1.0), 0.0); + assert_eq!(blend_channel(BlendMode::HardMix, 0.6, 0.4), 1.0); + assert_eq!(blend_channel(BlendMode::HardMix, 0.6, 0.3), 0.0); +} + +#[test] +fn vivid_light_and_hard_mix_composite_extremes() { + assert_eq!(composite(BlendMode::VividLight, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0], 1.0), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(composite(BlendMode::VividLight, [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], 1.0), [1.0, 1.0, 1.0, 1.0]); + assert_eq!(composite(BlendMode::HardMix, [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], 1.0), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(composite(BlendMode::HardMix, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0], 1.0), [1.0, 1.0, 1.0, 1.0]); +} + +#[test] +fn separable_outputs_stay_in_unit_range() { + let steps: Vec = (0..=20).map(|i| i as f32 / 20.0).collect(); + for m in BlendMode::LAYER_MODES { + for &cb in &steps { + for &cs in &steps { + let v = blend_rgb(m, [cb, cs, 0.5], [cs, cb, 0.25]); + for c in v { + assert!((-E..=1.0 + E).contains(&c), "{m:?} cb={cb} cs={cs} -> {c}"); + } + } + } + } +} + +#[test] +fn add_and_divide_clip_at_integer_depths_but_not_in_float() { + // Integer depths: Photoshop clips Linear Dodge (Add) and Divide at 1. + assert_eq!(blend_channel(BlendMode::LinearDodge, 2.0, 0.5), 1.0); + assert_eq!(blend_channel(BlendMode::LinearDodge, 0.75, 0.5), 1.0); + assert_eq!(blend_channel(BlendMode::Divide, 2.0, 0.5), 1.0); + assert_eq!(blend_channel(BlendMode::Divide, 0.5, 0.25), 1.0); + // 32-bit float: light adds up past 1 (adding light never darkens). + assert!(close(blend_channel_hdr(BlendMode::LinearDodge, 2.0, 0.5), 2.5)); + assert!(close(blend_channel_hdr(BlendMode::LinearDodge, 0.75, 0.5), 1.25)); + assert!(close(blend_channel_hdr(BlendMode::Divide, 2.0, 0.5), 4.0)); + assert!(close(blend_channel_hdr(BlendMode::Divide, 0.5, 0.25), 2.0)); + assert_eq!(blend_rgb_hdr(BlendMode::LinearDodge, [2.0, 0.5, 4.0], [0.5, 0.25, 0.5]), [2.5, 0.75, 4.5]); + assert_eq!(blend_rgb_hdr(BlendMode::Divide, [2.0, 0.5, 4.0], [0.5, 0.25, 0.5]), [4.0, 2.0, 8.0]); + // Divide by zero keeps its guard; overflow stays finite. + assert_eq!(blend_channel_hdr(BlendMode::Divide, 0.0, 0.0), 0.0); + assert_eq!(blend_channel_hdr(BlendMode::Divide, 3.0, 0.0), 1.0); + assert_eq!(blend_channel_hdr(BlendMode::Divide, 3.0, -1.0), 1.0); + assert_eq!(blend_channel_hdr(BlendMode::Divide, f32::MAX, 1e-30), f32::MAX); + assert_eq!(blend_channel_hdr(BlendMode::LinearDodge, f32::MAX, f32::MAX), f32::MAX); + assert!(blend_channel_hdr(BlendMode::LinearDodge, f32::INFINITY, 1.0).is_finite()); + // Every other separable mode is unchanged (the non-separable ones keep values above 1: + // blend_rgb_within), and the in-range results agree. + for m in BlendMode::LAYER_MODES.into_iter().filter(|m| m.is_separable() && !matches!(m, BlendMode::LinearDodge | BlendMode::Divide)) { + for (cb, cs) in [(0.2, 0.3), (0.9, 0.05), (2.0, 0.5), (0.4, 1.5)] { + assert_eq!(blend_rgb(m, [cb, cs, 0.5], [cs, cb, 0.25]), blend_rgb_hdr(m, [cb, cs, 0.5], [cs, cb, 0.25]), "{m:?} cb={cb} cs={cs}"); + } + } + let (cb, cs) = ([0.2, 0.3, 0.1], [0.3, 0.4, 0.4]); + assert_eq!(blend_rgb_hdr(BlendMode::LinearDodge, cb, cs), blend_rgb(BlendMode::LinearDodge, cb, cs)); + assert_eq!(blend_rgb_hdr(BlendMode::Divide, cb, cs), blend_rgb(BlendMode::Divide, cb, cs)); +} + +#[test] +fn luminosity_and_color_swap_components() { + let cb = [0.8, 0.2, 0.2]; + let cs = [0.1, 0.1, 0.9]; + let l = blend_rgb(BlendMode::Luminosity, cb, cs); + assert!(close(lum(l), lum(cs))); + let c = blend_rgb(BlendMode::Color, cb, cs); + assert!(close(lum(c), lum(cb))); + let h = blend_rgb(BlendMode::Hue, cb, cs); + assert!(close(lum(h), lum(cb))); + let s = blend_rgb(BlendMode::Saturation, cb, [0.5, 0.5, 0.5]); + // zero-saturation source desaturates the backdrop + assert!(close(s[0], s[1]) && close(s[1], s[2])); +} + +/// ClipColor exactly as ISO 32000 / W3C write it (what `clip_color` was before it guarded +/// out-of-range luminosities). +fn spec_clip_color(c: [f32; 3]) -> [f32; 3] { + let l = lum(c); + let n = c[0].min(c[1]).min(c[2]); + let x = c[0].max(c[1]).max(c[2]); + let mut out = c; + if n < 0.0 { + let d = l - n; + for v in &mut out { + *v = if d.abs() < 1e-12 { l } else { l + (*v - l) * l / d }; + } + } + if x > 1.0 { + let d = x - l; + for v in &mut out { + *v = if d.abs() < 1e-12 { l } else { l + (*v - l) * (1.0 - l) / d }; + } + } + out +} + +fn spec_blend_rgb(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] { + let set_lum = |c: [f32; 3], l: f32| { + let d = l - lum(c); + spec_clip_color([c[0] + d, c[1] + d, c[2] + d]) + }; + match mode { + BlendMode::Hue => set_lum(set_sat(cs, sat(cb)), lum(cb)), + BlendMode::Saturation => set_lum(set_sat(cb, sat(cs)), lum(cb)), + BlendMode::Color => set_lum(cs, lum(cb)), + BlendMode::Luminosity => set_lum(cb, lum(cs)), + m => blend_rgb(m, cb, cs), + } +} + +const NON_SEPARABLE: [BlendMode; 4] = [BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity]; + +#[test] +fn non_separable_modes_unchanged_on_integer_inputs() { + // 8/16-bit documents only hold 0..1, where the luminosity stays in range (up to a + // rounding step at white) and ClipColor is the plain ISO 32000 formula. + let mut edges: Vec = vec![0.0, 1.0 / 255.0, 0.5, 254.0 / 255.0, 65534.0 / 65535.0, 1.0]; + edges.extend((0..=8).map(|i| i as f32 / 8.0)); + let mut colors = Vec::new(); + for &r in &edges { + for &g in &edges { + for &b in &edges { + colors.push([r, g, b]); + } + } + } + let mut seed = 0x1234_5678u32; + let mut next = |levels: u32| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + ((seed >> 8) % (levels + 1)) as f32 / levels as f32 + }; + for _ in 0..2000 { + let levels = if next(1) > 0.5 { 255 } else { 65535 }; + colors.push([next(levels), next(levels), next(levels)]); + } + let mut worst = 0.0f32; + for (i, &cb) in colors.iter().enumerate() { + for &cs in colors.iter().skip(i % 7).step_by(7) { + for m in NON_SEPARABLE { + let (got, want) = (blend_rgb(m, cb, cs), spec_blend_rgb(m, cb, cs)); + for k in 0..3 { + worst = worst.max((got[k] - want[k]).abs()); + } + } + } + } + // Only white-ish colours whose luminosity rounds a step above 1 can differ, by a rounding step. + assert!(worst <= 1e-6, "{worst}"); +} + +#[test] +fn non_separable_modes_stable_when_luminosity_is_out_of_range() { + // The spec formula divided by `max − lum`, which is rounding noise for a grey above 1 and + // turns colours inside out when the luminosity is above 1: Luminosity of a grey of 2 over + // (0.5, 0.25, 0.125) gave (1.0, 2.32, 2.99). + let spec = spec_blend_rgb(BlendMode::Luminosity, [0.5, 0.25, 0.125], [2.0; 3]); + assert!(spec[0] < spec[2], "{spec:?}"); + let colors: [[f32; 3]; 10] = [ + [1.0, 1.0, 1.0], + [1.5, 1.5, 1.5], + [2.0, 2.0, 2.0], + [4.0, 4.0, 4.0], + [1000.0, 1000.0, 1000.0], + [2.0, 2.0, 1.999_999], + [4.0, 3.999_9, 4.0], + [3.0, 0.25, 0.125], + [1.25, 0.875, 3.75], + [-0.25, 0.5, 1.375], + ]; + for top in [1.0, f32::MAX] { + for m in NON_SEPARABLE { + for cb in colors { + for cs in colors { + let r = blend_rgb_within(m, cb, cs, top); + assert!(r.iter().all(|v| v.is_finite()), "{m:?} {cb:?} {cs:?} {top}: {r:?}"); + // The target luminosity is kept, at any depth. + let want = if m == BlendMode::Luminosity { lum(cs) } else { lum(cb) }; + if want >= 0.0 { + assert!((lum(r) - want).abs() <= 1e-4 * want.max(1.0), "{m:?} {cb:?} {cs:?} {top}: {r:?}"); + } + let (lo, hi) = (r[0].min(r[1]).min(r[2]), r[0].max(r[1]).max(r[2])); + if top == 1.0 { + // In gamut, or (a luminosity above 1 has no in-gamut colour) its grey. + assert!((lo >= 0.0 && hi <= 1.0 + E) || hi - lo <= 1e-6 * hi, "{m:?} {cb:?} {cs:?}: {r:?}"); + } else { + assert!(lo >= -1e-6 * hi.max(1.0), "{m:?} {cb:?} {cs:?}: {r:?}"); + } + } + } + } + } + // 32-bit: a grey backdrop gives a grey of its own luminosity in Hue and Saturation, a + // grey source a grey in Color, and bright colours keep their values above 1. + for g in [1.5f32, 2.0, 4.0, 1000.0] { + let grey = [g; 3]; + for cs in colors { + for m in [BlendMode::Hue, BlendMode::Saturation] { + let r = blend_rgb_within(m, grey, cs, f32::MAX); + assert!(r.iter().all(|&v| (v - lum(grey)).abs() <= 1e-5 * g), "{m:?} {g} {cs:?}: {r:?}"); + } + } + let r = blend_rgb_within(BlendMode::Luminosity, [0.5, 0.25, 0.125], grey, f32::MAX); + assert!(r[0] > 1.0 && r[0] > r[1] && r[1] > r[2], "{g}: {r:?}"); + let r = blend_rgb_within(BlendMode::Color, grey, [3.0, 0.25, 0.125], f32::MAX); + assert!(r[0] > 1.0 && r[0] > r[1] && r[1] > r[2], "{g}: {r:?}"); + // Integer documents: no colour of that luminosity fits in 0..1, so it is its grey. + let r = blend_rgb_within(BlendMode::Luminosity, [0.5, 0.25, 0.125], grey, 1.0); + assert!(r.iter().all(|&v| (v - lum(grey)).abs() <= 1e-5 * g), "{g}: {r:?}"); + } + // Continuous across near-greys: the result barely moves from the grey's. + for m in NON_SEPARABLE { + let a = blend_rgb_within(m, [2.0, 2.0, 2.0], [4.0, 4.0, 4.0], f32::MAX); + let b = blend_rgb_within(m, [2.0, 2.0, 1.999_999], [4.0, 3.999_999, 4.0], f32::MAX); + assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1e-4), "{m:?}: {a:?} {b:?}"); + } +} + +#[test] +fn darker_lighter_color_pick_whole_pixel() { + let a = [0.9, 0.1, 0.1]; + let b = [0.2, 0.6, 0.2]; + assert_eq!(blend_rgb(BlendMode::DarkerColor, a, b), if lum(b) < lum(a) { b } else { a }); + assert_eq!(blend_rgb(BlendMode::LighterColor, a, b), if lum(b) > lum(a) { b } else { a }); +} + +#[test] +fn composite_alpha_rules() { + let bg = [0.2, 0.4, 0.6, 1.0]; + // Transparent source leaves backdrop. + assert_eq!(composite(BlendMode::Multiply, bg, [1.0, 0.0, 0.0, 0.0], 1.0), bg); + // Opaque normal source replaces. + let r = composite(BlendMode::Normal, bg, [1.0, 0.0, 0.0, 1.0], 1.0); + assert!(close(r[0], 1.0) && close(r[3], 1.0)); + // Half opacity normal = lerp. + let r = composite(BlendMode::Normal, bg, [1.0, 1.0, 1.0, 1.0], 0.5); + assert!(close(r[0], 0.6) && close(r[1], 0.7) && close(r[2], 0.8)); + // Blend over transparent backdrop yields source regardless of mode. + let r = composite(BlendMode::Multiply, [0.0; 4], [0.3, 0.5, 0.7, 1.0], 1.0); + assert!(close(r[0], 0.3) && close(r[1], 0.5) && close(r[2], 0.7) && close(r[3], 1.0)); + // Alpha accumulates. + let r = composite(BlendMode::Screen, [0.0, 0.0, 0.0, 0.5], [0.0, 0.0, 0.0, 0.5], 1.0); + assert!(close(r[3], 0.75)); +} + +#[test] +fn composite_atop_keeps_alpha_and_moves_colour_by_source_alpha() { + let bg = [1.0, 1.0, 1.0, 0.5]; + // Half-transparent white, black at 50%: halfway, alpha kept (#5783). + let r = composite_atop(BlendMode::Normal, bg, [0.0, 0.0, 0.0, 1.0], 0.5); + assert!(close(r[0], 0.5) && close(r[2], 0.5) && r[3] == 0.5, "{r:?}"); + // Non-Normal modes blend against the backdrop as it is: Multiply by black at 50% halves it. + let r = composite_atop(BlendMode::Multiply, bg, [0.0, 0.0, 0.0, 1.0], 0.5); + assert!(close(r[0], 0.5) && r[3] == 0.5, "{r:?}"); + // Opaque backdrops agree with source-over. + let opaque = [0.2, 0.4, 0.6, 1.0]; + assert_eq!(composite_atop(BlendMode::Screen, opaque, [0.5, 0.5, 0.5, 0.7], 0.8), composite(BlendMode::Screen, opaque, [0.5, 0.5, 0.5, 0.7], 0.8)); + // A transparent source leaves the backdrop. + assert_eq!(composite_atop(BlendMode::Normal, bg, [0.0, 0.0, 0.0, 0.0], 1.0), bg); +} From dead54707980f3b22f0222a5378af0ee4ece5663 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:26 +0000 Subject: [PATCH 049/259] refactor(text): move psd_path.rs tests to psd_path/tests.rs --- crates/text/src/psd_path.rs | 339 +----------------------------- crates/text/src/psd_path/tests.rs | 334 +++++++++++++++++++++++++++++ 2 files changed, 335 insertions(+), 338 deletions(-) create mode 100644 crates/text/src/psd_path/tests.rs diff --git a/crates/text/src/psd_path.rs b/crates/text/src/psd_path.rs index 68b4af6229..3d61fdf851 100644 --- a/crates/text/src/psd_path.rs +++ b/crates/text/src/psd_path.rs @@ -301,341 +301,4 @@ pub(crate) fn update_frame(entry: &mut E, shape: &TextShape) { } #[cfg(test)] -mod tests { - use super::*; - use crate::engine_data::parse; - - fn frame(src: &str) -> E { - parse(src.as_bytes()).unwrap() - } - - /// The frame of `text/path-circle.psd` (Photoshop 2026). - const CIRCLE: &str = "<< /1 << /0 [ 32.0 128.0 32.0 74.98067 74.98067 32.0 128.0 32.0 128.0 32.0 181.01933 32.0 224.0 74.98067 224.0 128.0 224.0 128.0 224.0 181.01933 181.01933 224.0 128.0 224.0 128.0 224.0 74.98067 224.0 32.0 181.01933 32.0 128.0 ] >> /2 << /0 2 /2 [ 1.0 0.0 0.0 1.0 -32.0 -32.0 ] /6 [ -1.0 -1.0 ] >> >>"; - /// The frame of `text/path-wave-open.psd` (Photoshop 2026). - const WAVE: &str = "<< /1 << /0 [ 16.0 100.0 46.0 40.0 120.0 40.0 160.0 80.0 160.0 80.0 200.0 120.0 274.0 100.0 304.0 60.0 ] >> /2 << /0 2 /2 [ 1.0 0.0 0.0 1.0 -16.0 -52.12246 ] /6 [ -1.0 -1.0 ] >> >>"; - - #[test] - fn photoshop_path_frames_read_into_text_space() { - let wave = read(&frame(WAVE)).unwrap(); - assert!(!wave.closed); - assert_eq!(wave.knots.len(), 3); - let p = |x: f64, y: f64| Point::new(x - 16.0, y - 52.12246); - let k = &wave.knots; - assert!(same(k[0].anchor, p(16.0, 100.0)) && same(k[0].in_ctrl, p(16.0, 100.0)) && same(k[0].out_ctrl, p(46.0, 40.0))); - assert!(same(k[1].in_ctrl, p(120.0, 40.0)) && same(k[1].anchor, p(160.0, 80.0)) && same(k[1].out_ctrl, p(200.0, 120.0)) && k[1].smooth); - assert!(same(k[2].in_ctrl, p(274.0, 100.0)) && same(k[2].anchor, p(304.0, 60.0))); - - let circle = read(&frame(CIRCLE)).unwrap(); - assert!(circle.closed); - assert_eq!(circle.knots.len(), 4); - // The type starts at the bottom anchor (Photoshop's glyph 0) and runs to the left one. - assert!(same(circle.knots[0].anchor, Point::new(96.0, 192.0))); - assert!(same(circle.knots[1].anchor, Point::new(0.0, 96.0))); - assert!(circle.knots.iter().all(|k| k.smooth)); - } - - #[test] - fn written_frames_read_back() { - for src in [CIRCLE, WAVE] { - let path = read(&frame(src)).unwrap(); - let mut entry = E::Dict(vec![("0".into(), frame(src))]); - let before = entry.clone(); - update_frame(&mut entry, &TextShape::Path { path: path.clone(), start: 0.0, flip: false }); - assert_eq!(entry, before, "an unchanged path keeps Photoshop's frame"); - let mut moved = path.clone(); - for k in &mut moved.knots { - *k = k.transform(&Affine::translate(5.0, -3.0)); - } - update_frame(&mut entry, &TextShape::Path { path: moved.clone(), start: 0.0, flip: false }); - let back = read(entry.get("0").unwrap()).unwrap(); - assert!(same_path(&back, &moved), "{back:?}"); - assert_eq!(entry.path(&["0", "2", "6"]), before.path(&["0", "2", "6"]), "the frame's other keys stay"); - } - } - - /// Flipped type and a moved start are written into the path, which lays the type out the same. - #[test] - fn flip_and_start_are_baked_into_the_frame() { - use crate::warp::Warp; - for src in [CIRCLE, WAVE] { - let path = read(&frame(src)).unwrap(); - for (start, flip) in [(40.0, false), (0.0, true), (25.0, true)] { - let shape = TextShape::Path { path: path.clone(), start, flip }; - let baked = TextShape::Path { path: frame_path(&path, start, flip), start: 0.0, flip: false }; - let (a, b) = (Warp::on_path(&shape).unwrap(), Warp::on_path(&baked).unwrap()); - for x in [0.0, 10.0, 50.0, 120.0] { - for y in [-12.0, 0.0, 4.0] { - let (p, q) = (a.apply(x, y), b.apply(x, y)); - assert!((p.0 - q.0).hypot(p.1 - q.1) < 0.5, "{src:.10} start {start} flip {flip} at ({x}, {y}): {p:?} vs {q:?}"); - } - } - } - } - } - - #[test] - fn hostile_frames_are_errors() { - for src in [ - "<< /2 << /0 2 >> >>", - "<< /1 << /0 [ ] >> /2 << /0 2 >> >>", - "<< /1 << /0 [ 1.0 2.0 3.0 ] >> /2 << /0 2 >> >>", - "<< /1 << /0 [ 0 0 1 1 2 2 (x) 3 ] >> /2 << /0 2 >> >>", - "<< /1 << /0 [ 0 0 1 1 2 2 1e999 3 ] >> /2 << /0 2 >> >>", - "<< /1 << /0 [ 0 0 1 1 2 2 3 3 ] >> /2 << /0 2 /2 [ 0 0 0 0 0 0 ] >> >>", - "<< /1 << /0 [ 0 0 1 1 2 2 3 3 ] >> /2 << /0 2 /2 [ 1 0 0 ] >> >>", - "<< /1 << /0 [ 0 0 1 1 2 2 3 3 ] >> /2 << /0 2 /2 [ 1e300 0 0 1e300 0 0 ] >> >>", - "<< /1 << /0 [ 0 0 1 1 2 2 3 3 50 50 60 60 70 70 80 80 ] >> /2 << /0 2 >> >>", - "<< /1 << /0 [ 5 5 5 5 5 5 5 5 ] >> /2 << /0 2 >> >>", - "<< /1 << /0 (path) >> /2 << /0 2 >> >>", - ] { - assert!(read(&frame(src)).is_err(), "{src}"); - } - let many = format!("<< /1 << /0 [ {} ] >> /2 << /0 2 >> >>", "0 0 1 1 2 2 0 0 ".repeat(MAX_SEGMENTS + 1)); - assert!(read(&frame(&many)).is_err()); - } - - fn d(items: Vec<(&str, E)>) -> E { - E::Dict(items.into_iter().map(|(k, v)| (k.to_string(), v)).collect()) - } - - /// A Photoshop-shaped `Txt2` block with one point-text object for `text` (`\r` breaks, trailing - /// `\r`) drawn in frame 0. - fn photoshop_txt2(text: &str) -> Vec { - photoshop_txt2_in(text, point_frame()) - } - - /// [`photoshop_txt2`] with the frame list entry `frame`. - fn photoshop_txt2_in(text: &str, frame: E) -> Vec { - photoshop_txt2_of(vec![photoshop_object(text, 0)], vec![frame]) - } - - /// A Photoshop-shaped `Txt2` block holding `objects` and the frame list `frames`. - fn photoshop_txt2_of(objects: Vec, frames: Vec) -> Vec { - crate::engine_data::write_bare(&[ - ("98".into(), d(vec![("0", E::Int(14))])), - ("0".into(), d(vec![("8", d(vec![("0", E::Array(frames))]))])), - ("1".into(), d(vec![("1", E::Array(objects))])), - ]) - } - - /// A Photoshop-shaped text object for `text` drawn in frame `at`. - fn photoshop_object(text: &str, at: i64) -> E { - let len = text.encode_utf16().count() as i64; - let run = || { - d(vec![("0", d(vec![("0", d(vec![("0", E::String(String::new())), ("6", d(vec![("0", E::Int(0)), ("1", E::Real(12.0))]))]))])), ("1", E::Int(len))]) - }; - let model = d(vec![("0", E::String(text.into())), ("5", d(vec![("0", E::Array(vec![run()]))])), ("6", d(vec![("0", E::Array(vec![run()]))]))]); - let strike = d(vec![("99", E::Name("PC".into())), ("6", E::Array(vec![d(vec![("99", E::Name("F".into())), ("10", E::Int(at))])]))]); - let view = d(vec![ - ("0", E::Array(vec![d(vec![("0", E::Int(at))])])), - ("1", d(vec![("0", E::Array(vec![d(vec![("0", d(vec![("1", E::Int(1))])), ("1", E::Int(len))])]))])), - ("2", E::Array(vec![strike])), - ]); - d(vec![("0", model), ("1", view)]) - } - - fn layer(text: &str, shape: TextShape) -> photocraft_doc::TextLayer { - use photocraft_doc::text::{CharStyle, TextRun}; - let mut t = photocraft_doc::TextLayer { - text: text.into(), - runs: vec![TextRun { len: text.len(), style: CharStyle { size_pt: 12.0, ..Default::default() } }], - shape, - transform: Affine::translate(32.0, 20.0), - ..Default::default() - }; - t.sync_summary(); - t - } - - /// A layer read back, with what [`crate::psd::apply_txt2_path`] said. - type Opened = (photocraft_doc::TextLayer, Result); - - /// Saves `layers` (object `i` each) into a file whose `Txt2` is `prev`, then reads each back: - /// its `TySh` and what [`crate::psd::apply_txt2_path`] makes of the saved `Txt2`. - fn save_and_open(layers: &[&photocraft_doc::TextLayer], prev: &[u8]) -> (Vec, Vec) { - let objects: Vec<(i32, &photocraft_doc::TextLayer)> = layers.iter().enumerate().map(|(i, l)| (i as i32, *l)).collect(); - let txt2 = crate::psd::build_txt2(&objects, Some(prev)); - let parsed = crate::psd::parse_txt2(&txt2).unwrap(); - let back = objects - .iter() - .map(|(i, l)| { - let tysh = crate::psd::set_text_index(&crate::psd::build_tysh(l, 72.0, None), *i).unwrap(); - let mut back = crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap(); - crate::psd::apply_txt2(&mut back, &tysh, &parsed); - let applied = crate::psd::apply_txt2_path(&mut back, &tysh, &parsed); - crate::psd::apply_txt2_frame(&mut back, &tysh, &parsed); - (back, applied) - }) - .collect(); - (txt2, back) - } - - /// #7962: type on a path survives a PSD save and open, for the file's own text object and for - /// a layer the file had no object for; a moved start and flipped type come back laid out the - /// same, in the path; a second save changes nothing. - #[test] - fn path_text_round_trips_through_tysh_and_txt2() { - let circle = read(&frame(CIRCLE)).unwrap(); - let wave = read(&frame(WAVE)).unwrap(); - let a = layer("On a circle", TextShape::Path { path: circle.clone(), start: 0.0, flip: false }); - let b = layer("Along a wave", TextShape::Path { path: wave.clone(), start: 30.0, flip: true }); - let prev = photoshop_txt2("On a circle\r"); - let (txt2, back) = save_and_open(&[&a, &b], &prev); - for ((l, applied), (want, start, flip)) in back.iter().zip([(&circle, 0.0, false), (&wave, 30.0, true)]) { - assert_eq!(applied, &Ok(true), "{}", l.text); - let TextShape::Path { path, start: s, flip: f } = &l.shape else { panic!("{}: {:?}", l.text, l.shape) }; - assert_eq!((*s, *f), (0.0, false)); - assert!(same_path(path, &frame_path(want, start, flip)), "{}: {path:?}", l.text); - assert_eq!(l.transform, Affine::translate(32.0, 20.0), "the frame's matrix is not applied twice"); - } - let (again, _) = save_and_open(&[&back[0].0, &back[1].0], &txt2); - assert_eq!(again, txt2, "a re-save of the opened file changes nothing"); - // Off its path, the layer opens as point text again. - let detached = layer("On a circle", TextShape::Point); - let (_, back) = save_and_open(&[&detached], &txt2); - assert_eq!(back[0].1, Ok(false)); - assert_eq!(back[0].0.shape, TextShape::Point); - } - - /// A malformed path frame leaves the layer as EngineData describes it, with the reason. - #[test] - fn a_malformed_path_frame_keeps_the_engine_data_shape() { - let a = layer("Hostile", TextShape::Box { x: 0.0, y: 0.0, width: 50.0, height: 20.0 }); - let tysh = crate::psd::set_text_index(&crate::psd::build_tysh(&a, 72.0, None), 0).unwrap(); - for bad in ["<< /1 << /0 [ 1 2 3 ] >> /2 << /0 2 >> >>", "<< /1 << /0 [ 0 0 1 1 2 2 3 3 ] >> /2 << /0 2 /2 [ 0 0 0 0 0 0 ] >> >>"] { - let entry = E::Dict(vec![("0".into(), frame(bad))]); - let txt2 = crate::psd::parse_txt2(&photoshop_txt2_in("Hostile\r", entry)).unwrap(); - let mut l = crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap(); - let before = l.shape.clone(); - assert!(crate::psd::apply_txt2_path(&mut l, &tysh, &txt2).is_err(), "{bad}"); - assert_eq!(l.shape, before); - } - } - - /// A layer taken off its path doesn't keep its path frame (it would reopen on the path). - #[test] - fn a_layer_off_its_path_loses_the_path_frame() { - let mut entry = E::Dict(vec![("0".into(), frame(CIRCLE))]); - update_frame(&mut entry, &TextShape::Point); - assert_eq!(entry, point_frame()); - let mut entry = E::Dict(vec![("0".into(), frame(WAVE))]); - update_frame(&mut entry, &TextShape::Box { x: 1.0, y: 2.0, width: 30.0, height: 40.0 }); - assert_eq!(entry.get("0").map(frame_kind), Some(BOX_FRAME)); - assert_eq!( - entry.path(&["0", "1", "0"]).and_then(numbers).unwrap()[..8], - [1.0, 2.0, 1.0, 2.0, 31.0, 2.0, 31.0, 2.0], - "Photoshop's box outline: corners as straight segments from the top left" - ); - // A point or box frame is left alone. - let mut point = point_frame(); - update_frame(&mut point, &TextShape::Point); - assert_eq!(point, point_frame()); - } - - /// A path frame the import could not read (the layer opened as EngineData's box or point - /// text) is saved back as it was, not replaced by a box or point frame. - #[test] - fn an_unreadable_path_frame_is_kept() { - let two_pieces = "<< /1 << /0 [ 0 0 1 1 2 2 3 3 50 50 60 60 70 70 80 80 ] >> /2 << /0 2 >> >>"; - for shape in [TextShape::Point, TextShape::Box { x: 0.0, y: 0.0, width: 80.0, height: 80.0 }] { - let mut entry = E::Dict(vec![("0".into(), frame(two_pieces))]); - let before = entry.clone(); - update_frame(&mut entry, &shape); - assert_eq!(entry, before, "{shape:?}"); - } - } - - /// The frame number the object at `index` of the saved `txt2` names, and that frame. - fn saved_frame(txt2: &[u8], index: usize) -> (i64, E) { - let t = crate::psd::parse_txt2(txt2).unwrap(); - let object = &t.path(&["1", "1"]).and_then(E::as_array).unwrap()[index]; - let at = object.path(&["1", "0"]).and_then(E::as_array).unwrap()[0].get("0").and_then(E::as_i64).unwrap(); - (at, t.path(&["0", "8", "0"]).and_then(E::as_array).unwrap()[at as usize].clone()) - } - - /// An edited layer whose object the save can't refit keeps drawing in that object's own frame, - /// not in the frame its slot number names, which is the path layer's here. - #[test] - fn an_object_rebuilt_from_a_template_keeps_its_own_frame() { - let circle = read(&frame(CIRCLE)).unwrap(); - let on_path = layer("On a circle", TextShape::Path { path: circle, start: 0.0, flip: false }); - // Object 1's style run has a length that is no count, so it can't be refitted. - let mut broken = photoshop_object("Old\r", 0); - let run = d(vec![("0", d(vec![("0", d(vec![("0", E::String(String::new()))]))])), ("1", E::String("x".into()))]); - broken.get_mut("0").unwrap().set("6", d(vec![("0", E::Array(vec![run]))])); - let path_frame = E::Dict(vec![("0".into(), frame(CIRCLE))]); - let prev = photoshop_txt2_of(vec![photoshop_object("On a circle\r", 1), broken], vec![point_frame(), path_frame.clone()]); - let (txt2, back) = save_and_open(&[&on_path, &layer("New", TextShape::Point)], &prev); - assert_eq!(saved_frame(&txt2, 1).0, 0, "the rebuilt object draws in its own frame"); - assert_eq!(saved_frame(&txt2, 0), (1, path_frame)); - assert_eq!(back[0].1, Ok(true)); - assert!(matches!(back[0].0.shape, TextShape::Path { .. }), "{:?}", back[0].0.shape); - } - - /// A new layer whose slot number is the frame another object is drawn in gets a frame of its - /// own: neither layer takes the other's shape, on this save or the next. - #[test] - fn a_new_object_gets_a_frame_no_other_object_is_drawn_in() { - let circle = read(&frame(CIRCLE)).unwrap(); - let on_path = layer("On a circle", TextShape::Path { path: circle, start: 0.0, flip: false }); - let path_frame = E::Dict(vec![("0".into(), frame(CIRCLE))]); - let prev = photoshop_txt2_of(vec![photoshop_object("On a circle\r", 1)], vec![point_frame(), path_frame.clone()]); - let new = layer("New", TextShape::Point); - let (txt2, back) = save_and_open(&[&on_path, &new], &prev); - assert_eq!(saved_frame(&txt2, 1), (2, point_frame()), "a frame past the file's own"); - assert_eq!(saved_frame(&txt2, 0), (1, path_frame)); - assert_eq!(back[0].1, Ok(true)); - assert_eq!((&back[1].1, &back[1].0.shape), (&Ok(false), &TextShape::Point)); - // The path layer taken off its path on the next save loses its path frame. - let (again, _) = save_and_open(&[&layer("On a circle", TextShape::Point), &new], &txt2); - assert_eq!(saved_frame(&again, 0), (1, point_frame())); - } - - /// A rebuilt object whose old frame number is past the frame list doesn't name a frame the - /// block lacks (Photoshop refuses such files, #7698). - #[test] - fn a_rebuilt_object_never_names_a_missing_frame() { - let mut broken = photoshop_object("Old\r", 70_000); - let run = d(vec![("0", d(vec![("0", d(vec![("0", E::String(String::new()))]))])), ("1", E::String("x".into()))]); - broken.get_mut("0").unwrap().set("6", d(vec![("0", E::Array(vec![run]))])); - let path_frame = E::Dict(vec![("0".into(), frame(CIRCLE))]); - let prev = photoshop_txt2_of(vec![photoshop_object("On a circle\r", 1), broken], vec![point_frame(), path_frame.clone()]); - let on_path = layer("On a circle", TextShape::Path { path: read(&frame(CIRCLE)).unwrap(), start: 0.0, flip: false }); - let (txt2, _) = save_and_open(&[&on_path, &layer("New", TextShape::Point)], &prev); - assert_eq!(saved_frame(&txt2, 1), (2, point_frame())); - assert_eq!(saved_frame(&txt2, 0), (1, path_frame)); - } - - /// An object the file keeps that names a frame past the frame list doesn't grow the list (to - /// 65536 point frames here). - #[test] - fn a_kept_object_naming_a_far_frame_adds_no_frames() { - let prev = photoshop_txt2_of(vec![photoshop_object("Far\r", crate::psd::MAX_TEXT_INDEX.into())], vec![point_frame()]); - let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &layer("Far", TextShape::Point))], Some(&prev))).unwrap(); - assert_eq!(out.path(&["0", "8", "0"]).and_then(E::as_array).map(<[E]>::len), Some(1)); - } - - /// A frame the file already has two objects drawn in is left as the file has it, not given - /// the shape of whichever layer comes last. - #[test] - fn a_frame_two_objects_name_is_kept() { - let circle = read(&frame(CIRCLE)).unwrap(); - let on_path = layer("On a circle", TextShape::Path { path: circle, start: 0.0, flip: false }); - let path_frame = E::Dict(vec![("0".into(), frame(CIRCLE))]); - let objects = vec![photoshop_object("On a circle\r", 1), photoshop_object("Point\r", 1)]; - let prev = photoshop_txt2_of(objects, vec![point_frame(), path_frame.clone()]); - let (txt2, _) = save_and_open(&[&on_path, &layer("Point", TextShape::Point)], &prev); - assert_eq!(saved_frame(&txt2, 0), (1, path_frame)); - assert_eq!(saved_frame(&txt2, 1).0, 1); - } - - /// Area type's frame becomes a text box over its path's bounds, as its EngineData describes it. - #[test] - fn an_area_layer_gets_a_box_frame() { - let square = - photocraft_doc::vector::Path::new(vec![photocraft_doc::vector::Subpath::polygon(&[(10.0, 20.0), (50.0, 20.0), (50.0, 80.0), (10.0, 80.0)])]); - let mut entry = E::Dict(vec![("0".into(), frame(CIRCLE))]); - update_frame(&mut entry, &TextShape::Area { path: square }); - assert_eq!(entry, box_frame(10.0, 20.0, 40.0, 60.0)); - } -} +mod tests; diff --git a/crates/text/src/psd_path/tests.rs b/crates/text/src/psd_path/tests.rs new file mode 100644 index 0000000000..8e3a07383a --- /dev/null +++ b/crates/text/src/psd_path/tests.rs @@ -0,0 +1,334 @@ +use super::*; +use crate::engine_data::parse; + +fn frame(src: &str) -> E { + parse(src.as_bytes()).unwrap() +} + +/// The frame of `text/path-circle.psd` (Photoshop 2026). +const CIRCLE: &str = "<< /1 << /0 [ 32.0 128.0 32.0 74.98067 74.98067 32.0 128.0 32.0 128.0 32.0 181.01933 32.0 224.0 74.98067 224.0 128.0 224.0 128.0 224.0 181.01933 181.01933 224.0 128.0 224.0 128.0 224.0 74.98067 224.0 32.0 181.01933 32.0 128.0 ] >> /2 << /0 2 /2 [ 1.0 0.0 0.0 1.0 -32.0 -32.0 ] /6 [ -1.0 -1.0 ] >> >>"; +/// The frame of `text/path-wave-open.psd` (Photoshop 2026). +const WAVE: &str = "<< /1 << /0 [ 16.0 100.0 46.0 40.0 120.0 40.0 160.0 80.0 160.0 80.0 200.0 120.0 274.0 100.0 304.0 60.0 ] >> /2 << /0 2 /2 [ 1.0 0.0 0.0 1.0 -16.0 -52.12246 ] /6 [ -1.0 -1.0 ] >> >>"; + +#[test] +fn photoshop_path_frames_read_into_text_space() { + let wave = read(&frame(WAVE)).unwrap(); + assert!(!wave.closed); + assert_eq!(wave.knots.len(), 3); + let p = |x: f64, y: f64| Point::new(x - 16.0, y - 52.12246); + let k = &wave.knots; + assert!(same(k[0].anchor, p(16.0, 100.0)) && same(k[0].in_ctrl, p(16.0, 100.0)) && same(k[0].out_ctrl, p(46.0, 40.0))); + assert!(same(k[1].in_ctrl, p(120.0, 40.0)) && same(k[1].anchor, p(160.0, 80.0)) && same(k[1].out_ctrl, p(200.0, 120.0)) && k[1].smooth); + assert!(same(k[2].in_ctrl, p(274.0, 100.0)) && same(k[2].anchor, p(304.0, 60.0))); + + let circle = read(&frame(CIRCLE)).unwrap(); + assert!(circle.closed); + assert_eq!(circle.knots.len(), 4); + // The type starts at the bottom anchor (Photoshop's glyph 0) and runs to the left one. + assert!(same(circle.knots[0].anchor, Point::new(96.0, 192.0))); + assert!(same(circle.knots[1].anchor, Point::new(0.0, 96.0))); + assert!(circle.knots.iter().all(|k| k.smooth)); +} + +#[test] +fn written_frames_read_back() { + for src in [CIRCLE, WAVE] { + let path = read(&frame(src)).unwrap(); + let mut entry = E::Dict(vec![("0".into(), frame(src))]); + let before = entry.clone(); + update_frame(&mut entry, &TextShape::Path { path: path.clone(), start: 0.0, flip: false }); + assert_eq!(entry, before, "an unchanged path keeps Photoshop's frame"); + let mut moved = path.clone(); + for k in &mut moved.knots { + *k = k.transform(&Affine::translate(5.0, -3.0)); + } + update_frame(&mut entry, &TextShape::Path { path: moved.clone(), start: 0.0, flip: false }); + let back = read(entry.get("0").unwrap()).unwrap(); + assert!(same_path(&back, &moved), "{back:?}"); + assert_eq!(entry.path(&["0", "2", "6"]), before.path(&["0", "2", "6"]), "the frame's other keys stay"); + } +} + +/// Flipped type and a moved start are written into the path, which lays the type out the same. +#[test] +fn flip_and_start_are_baked_into_the_frame() { + use crate::warp::Warp; + for src in [CIRCLE, WAVE] { + let path = read(&frame(src)).unwrap(); + for (start, flip) in [(40.0, false), (0.0, true), (25.0, true)] { + let shape = TextShape::Path { path: path.clone(), start, flip }; + let baked = TextShape::Path { path: frame_path(&path, start, flip), start: 0.0, flip: false }; + let (a, b) = (Warp::on_path(&shape).unwrap(), Warp::on_path(&baked).unwrap()); + for x in [0.0, 10.0, 50.0, 120.0] { + for y in [-12.0, 0.0, 4.0] { + let (p, q) = (a.apply(x, y), b.apply(x, y)); + assert!((p.0 - q.0).hypot(p.1 - q.1) < 0.5, "{src:.10} start {start} flip {flip} at ({x}, {y}): {p:?} vs {q:?}"); + } + } + } + } +} + +#[test] +fn hostile_frames_are_errors() { + for src in [ + "<< /2 << /0 2 >> >>", + "<< /1 << /0 [ ] >> /2 << /0 2 >> >>", + "<< /1 << /0 [ 1.0 2.0 3.0 ] >> /2 << /0 2 >> >>", + "<< /1 << /0 [ 0 0 1 1 2 2 (x) 3 ] >> /2 << /0 2 >> >>", + "<< /1 << /0 [ 0 0 1 1 2 2 1e999 3 ] >> /2 << /0 2 >> >>", + "<< /1 << /0 [ 0 0 1 1 2 2 3 3 ] >> /2 << /0 2 /2 [ 0 0 0 0 0 0 ] >> >>", + "<< /1 << /0 [ 0 0 1 1 2 2 3 3 ] >> /2 << /0 2 /2 [ 1 0 0 ] >> >>", + "<< /1 << /0 [ 0 0 1 1 2 2 3 3 ] >> /2 << /0 2 /2 [ 1e300 0 0 1e300 0 0 ] >> >>", + "<< /1 << /0 [ 0 0 1 1 2 2 3 3 50 50 60 60 70 70 80 80 ] >> /2 << /0 2 >> >>", + "<< /1 << /0 [ 5 5 5 5 5 5 5 5 ] >> /2 << /0 2 >> >>", + "<< /1 << /0 (path) >> /2 << /0 2 >> >>", + ] { + assert!(read(&frame(src)).is_err(), "{src}"); + } + let many = format!("<< /1 << /0 [ {} ] >> /2 << /0 2 >> >>", "0 0 1 1 2 2 0 0 ".repeat(MAX_SEGMENTS + 1)); + assert!(read(&frame(&many)).is_err()); +} + +fn d(items: Vec<(&str, E)>) -> E { + E::Dict(items.into_iter().map(|(k, v)| (k.to_string(), v)).collect()) +} + +/// A Photoshop-shaped `Txt2` block with one point-text object for `text` (`\r` breaks, trailing +/// `\r`) drawn in frame 0. +fn photoshop_txt2(text: &str) -> Vec { + photoshop_txt2_in(text, point_frame()) +} + +/// [`photoshop_txt2`] with the frame list entry `frame`. +fn photoshop_txt2_in(text: &str, frame: E) -> Vec { + photoshop_txt2_of(vec![photoshop_object(text, 0)], vec![frame]) +} + +/// A Photoshop-shaped `Txt2` block holding `objects` and the frame list `frames`. +fn photoshop_txt2_of(objects: Vec, frames: Vec) -> Vec { + crate::engine_data::write_bare(&[ + ("98".into(), d(vec![("0", E::Int(14))])), + ("0".into(), d(vec![("8", d(vec![("0", E::Array(frames))]))])), + ("1".into(), d(vec![("1", E::Array(objects))])), + ]) +} + +/// A Photoshop-shaped text object for `text` drawn in frame `at`. +fn photoshop_object(text: &str, at: i64) -> E { + let len = text.encode_utf16().count() as i64; + let run = + || d(vec![("0", d(vec![("0", d(vec![("0", E::String(String::new())), ("6", d(vec![("0", E::Int(0)), ("1", E::Real(12.0))]))]))])), ("1", E::Int(len))]); + let model = d(vec![("0", E::String(text.into())), ("5", d(vec![("0", E::Array(vec![run()]))])), ("6", d(vec![("0", E::Array(vec![run()]))]))]); + let strike = d(vec![("99", E::Name("PC".into())), ("6", E::Array(vec![d(vec![("99", E::Name("F".into())), ("10", E::Int(at))])]))]); + let view = d(vec![ + ("0", E::Array(vec![d(vec![("0", E::Int(at))])])), + ("1", d(vec![("0", E::Array(vec![d(vec![("0", d(vec![("1", E::Int(1))])), ("1", E::Int(len))])]))])), + ("2", E::Array(vec![strike])), + ]); + d(vec![("0", model), ("1", view)]) +} + +fn layer(text: &str, shape: TextShape) -> photocraft_doc::TextLayer { + use photocraft_doc::text::{CharStyle, TextRun}; + let mut t = photocraft_doc::TextLayer { + text: text.into(), + runs: vec![TextRun { len: text.len(), style: CharStyle { size_pt: 12.0, ..Default::default() } }], + shape, + transform: Affine::translate(32.0, 20.0), + ..Default::default() + }; + t.sync_summary(); + t +} + +/// A layer read back, with what [`crate::psd::apply_txt2_path`] said. +type Opened = (photocraft_doc::TextLayer, Result); + +/// Saves `layers` (object `i` each) into a file whose `Txt2` is `prev`, then reads each back: +/// its `TySh` and what [`crate::psd::apply_txt2_path`] makes of the saved `Txt2`. +fn save_and_open(layers: &[&photocraft_doc::TextLayer], prev: &[u8]) -> (Vec, Vec) { + let objects: Vec<(i32, &photocraft_doc::TextLayer)> = layers.iter().enumerate().map(|(i, l)| (i as i32, *l)).collect(); + let txt2 = crate::psd::build_txt2(&objects, Some(prev)); + let parsed = crate::psd::parse_txt2(&txt2).unwrap(); + let back = objects + .iter() + .map(|(i, l)| { + let tysh = crate::psd::set_text_index(&crate::psd::build_tysh(l, 72.0, None), *i).unwrap(); + let mut back = crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap(); + crate::psd::apply_txt2(&mut back, &tysh, &parsed); + let applied = crate::psd::apply_txt2_path(&mut back, &tysh, &parsed); + crate::psd::apply_txt2_frame(&mut back, &tysh, &parsed); + (back, applied) + }) + .collect(); + (txt2, back) +} + +/// #7962: type on a path survives a PSD save and open, for the file's own text object and for +/// a layer the file had no object for; a moved start and flipped type come back laid out the +/// same, in the path; a second save changes nothing. +#[test] +fn path_text_round_trips_through_tysh_and_txt2() { + let circle = read(&frame(CIRCLE)).unwrap(); + let wave = read(&frame(WAVE)).unwrap(); + let a = layer("On a circle", TextShape::Path { path: circle.clone(), start: 0.0, flip: false }); + let b = layer("Along a wave", TextShape::Path { path: wave.clone(), start: 30.0, flip: true }); + let prev = photoshop_txt2("On a circle\r"); + let (txt2, back) = save_and_open(&[&a, &b], &prev); + for ((l, applied), (want, start, flip)) in back.iter().zip([(&circle, 0.0, false), (&wave, 30.0, true)]) { + assert_eq!(applied, &Ok(true), "{}", l.text); + let TextShape::Path { path, start: s, flip: f } = &l.shape else { panic!("{}: {:?}", l.text, l.shape) }; + assert_eq!((*s, *f), (0.0, false)); + assert!(same_path(path, &frame_path(want, start, flip)), "{}: {path:?}", l.text); + assert_eq!(l.transform, Affine::translate(32.0, 20.0), "the frame's matrix is not applied twice"); + } + let (again, _) = save_and_open(&[&back[0].0, &back[1].0], &txt2); + assert_eq!(again, txt2, "a re-save of the opened file changes nothing"); + // Off its path, the layer opens as point text again. + let detached = layer("On a circle", TextShape::Point); + let (_, back) = save_and_open(&[&detached], &txt2); + assert_eq!(back[0].1, Ok(false)); + assert_eq!(back[0].0.shape, TextShape::Point); +} + +/// A malformed path frame leaves the layer as EngineData describes it, with the reason. +#[test] +fn a_malformed_path_frame_keeps_the_engine_data_shape() { + let a = layer("Hostile", TextShape::Box { x: 0.0, y: 0.0, width: 50.0, height: 20.0 }); + let tysh = crate::psd::set_text_index(&crate::psd::build_tysh(&a, 72.0, None), 0).unwrap(); + for bad in ["<< /1 << /0 [ 1 2 3 ] >> /2 << /0 2 >> >>", "<< /1 << /0 [ 0 0 1 1 2 2 3 3 ] >> /2 << /0 2 /2 [ 0 0 0 0 0 0 ] >> >>"] { + let entry = E::Dict(vec![("0".into(), frame(bad))]); + let txt2 = crate::psd::parse_txt2(&photoshop_txt2_in("Hostile\r", entry)).unwrap(); + let mut l = crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap(); + let before = l.shape.clone(); + assert!(crate::psd::apply_txt2_path(&mut l, &tysh, &txt2).is_err(), "{bad}"); + assert_eq!(l.shape, before); + } +} + +/// A layer taken off its path doesn't keep its path frame (it would reopen on the path). +#[test] +fn a_layer_off_its_path_loses_the_path_frame() { + let mut entry = E::Dict(vec![("0".into(), frame(CIRCLE))]); + update_frame(&mut entry, &TextShape::Point); + assert_eq!(entry, point_frame()); + let mut entry = E::Dict(vec![("0".into(), frame(WAVE))]); + update_frame(&mut entry, &TextShape::Box { x: 1.0, y: 2.0, width: 30.0, height: 40.0 }); + assert_eq!(entry.get("0").map(frame_kind), Some(BOX_FRAME)); + assert_eq!( + entry.path(&["0", "1", "0"]).and_then(numbers).unwrap()[..8], + [1.0, 2.0, 1.0, 2.0, 31.0, 2.0, 31.0, 2.0], + "Photoshop's box outline: corners as straight segments from the top left" + ); + // A point or box frame is left alone. + let mut point = point_frame(); + update_frame(&mut point, &TextShape::Point); + assert_eq!(point, point_frame()); +} + +/// A path frame the import could not read (the layer opened as EngineData's box or point +/// text) is saved back as it was, not replaced by a box or point frame. +#[test] +fn an_unreadable_path_frame_is_kept() { + let two_pieces = "<< /1 << /0 [ 0 0 1 1 2 2 3 3 50 50 60 60 70 70 80 80 ] >> /2 << /0 2 >> >>"; + for shape in [TextShape::Point, TextShape::Box { x: 0.0, y: 0.0, width: 80.0, height: 80.0 }] { + let mut entry = E::Dict(vec![("0".into(), frame(two_pieces))]); + let before = entry.clone(); + update_frame(&mut entry, &shape); + assert_eq!(entry, before, "{shape:?}"); + } +} + +/// The frame number the object at `index` of the saved `txt2` names, and that frame. +fn saved_frame(txt2: &[u8], index: usize) -> (i64, E) { + let t = crate::psd::parse_txt2(txt2).unwrap(); + let object = &t.path(&["1", "1"]).and_then(E::as_array).unwrap()[index]; + let at = object.path(&["1", "0"]).and_then(E::as_array).unwrap()[0].get("0").and_then(E::as_i64).unwrap(); + (at, t.path(&["0", "8", "0"]).and_then(E::as_array).unwrap()[at as usize].clone()) +} + +/// An edited layer whose object the save can't refit keeps drawing in that object's own frame, +/// not in the frame its slot number names, which is the path layer's here. +#[test] +fn an_object_rebuilt_from_a_template_keeps_its_own_frame() { + let circle = read(&frame(CIRCLE)).unwrap(); + let on_path = layer("On a circle", TextShape::Path { path: circle, start: 0.0, flip: false }); + // Object 1's style run has a length that is no count, so it can't be refitted. + let mut broken = photoshop_object("Old\r", 0); + let run = d(vec![("0", d(vec![("0", d(vec![("0", E::String(String::new()))]))])), ("1", E::String("x".into()))]); + broken.get_mut("0").unwrap().set("6", d(vec![("0", E::Array(vec![run]))])); + let path_frame = E::Dict(vec![("0".into(), frame(CIRCLE))]); + let prev = photoshop_txt2_of(vec![photoshop_object("On a circle\r", 1), broken], vec![point_frame(), path_frame.clone()]); + let (txt2, back) = save_and_open(&[&on_path, &layer("New", TextShape::Point)], &prev); + assert_eq!(saved_frame(&txt2, 1).0, 0, "the rebuilt object draws in its own frame"); + assert_eq!(saved_frame(&txt2, 0), (1, path_frame)); + assert_eq!(back[0].1, Ok(true)); + assert!(matches!(back[0].0.shape, TextShape::Path { .. }), "{:?}", back[0].0.shape); +} + +/// A new layer whose slot number is the frame another object is drawn in gets a frame of its +/// own: neither layer takes the other's shape, on this save or the next. +#[test] +fn a_new_object_gets_a_frame_no_other_object_is_drawn_in() { + let circle = read(&frame(CIRCLE)).unwrap(); + let on_path = layer("On a circle", TextShape::Path { path: circle, start: 0.0, flip: false }); + let path_frame = E::Dict(vec![("0".into(), frame(CIRCLE))]); + let prev = photoshop_txt2_of(vec![photoshop_object("On a circle\r", 1)], vec![point_frame(), path_frame.clone()]); + let new = layer("New", TextShape::Point); + let (txt2, back) = save_and_open(&[&on_path, &new], &prev); + assert_eq!(saved_frame(&txt2, 1), (2, point_frame()), "a frame past the file's own"); + assert_eq!(saved_frame(&txt2, 0), (1, path_frame)); + assert_eq!(back[0].1, Ok(true)); + assert_eq!((&back[1].1, &back[1].0.shape), (&Ok(false), &TextShape::Point)); + // The path layer taken off its path on the next save loses its path frame. + let (again, _) = save_and_open(&[&layer("On a circle", TextShape::Point), &new], &txt2); + assert_eq!(saved_frame(&again, 0), (1, point_frame())); +} + +/// A rebuilt object whose old frame number is past the frame list doesn't name a frame the +/// block lacks (Photoshop refuses such files, #7698). +#[test] +fn a_rebuilt_object_never_names_a_missing_frame() { + let mut broken = photoshop_object("Old\r", 70_000); + let run = d(vec![("0", d(vec![("0", d(vec![("0", E::String(String::new()))]))])), ("1", E::String("x".into()))]); + broken.get_mut("0").unwrap().set("6", d(vec![("0", E::Array(vec![run]))])); + let path_frame = E::Dict(vec![("0".into(), frame(CIRCLE))]); + let prev = photoshop_txt2_of(vec![photoshop_object("On a circle\r", 1), broken], vec![point_frame(), path_frame.clone()]); + let on_path = layer("On a circle", TextShape::Path { path: read(&frame(CIRCLE)).unwrap(), start: 0.0, flip: false }); + let (txt2, _) = save_and_open(&[&on_path, &layer("New", TextShape::Point)], &prev); + assert_eq!(saved_frame(&txt2, 1), (2, point_frame())); + assert_eq!(saved_frame(&txt2, 0), (1, path_frame)); +} + +/// An object the file keeps that names a frame past the frame list doesn't grow the list (to +/// 65536 point frames here). +#[test] +fn a_kept_object_naming_a_far_frame_adds_no_frames() { + let prev = photoshop_txt2_of(vec![photoshop_object("Far\r", crate::psd::MAX_TEXT_INDEX.into())], vec![point_frame()]); + let out = crate::psd::parse_txt2(&crate::psd::build_txt2(&[(0, &layer("Far", TextShape::Point))], Some(&prev))).unwrap(); + assert_eq!(out.path(&["0", "8", "0"]).and_then(E::as_array).map(<[E]>::len), Some(1)); +} + +/// A frame the file already has two objects drawn in is left as the file has it, not given +/// the shape of whichever layer comes last. +#[test] +fn a_frame_two_objects_name_is_kept() { + let circle = read(&frame(CIRCLE)).unwrap(); + let on_path = layer("On a circle", TextShape::Path { path: circle, start: 0.0, flip: false }); + let path_frame = E::Dict(vec![("0".into(), frame(CIRCLE))]); + let objects = vec![photoshop_object("On a circle\r", 1), photoshop_object("Point\r", 1)]; + let prev = photoshop_txt2_of(objects, vec![point_frame(), path_frame.clone()]); + let (txt2, _) = save_and_open(&[&on_path, &layer("Point", TextShape::Point)], &prev); + assert_eq!(saved_frame(&txt2, 0), (1, path_frame)); + assert_eq!(saved_frame(&txt2, 1).0, 1); +} + +/// Area type's frame becomes a text box over its path's bounds, as its EngineData describes it. +#[test] +fn an_area_layer_gets_a_box_frame() { + let square = photocraft_doc::vector::Path::new(vec![photocraft_doc::vector::Subpath::polygon(&[(10.0, 20.0), (50.0, 20.0), (50.0, 80.0), (10.0, 80.0)])]); + let mut entry = E::Dict(vec![("0".into(), frame(CIRCLE))]); + update_frame(&mut entry, &TextShape::Area { path: square }); + assert_eq!(entry, box_frame(10.0, 20.0, 40.0, 60.0)); +} From d06176256697f302227be429a1de18f097ba66d5 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:27 +0000 Subject: [PATCH 050/259] refactor(ops): move lib.rs tests to tests.rs --- crates/ops/src/lib.rs | 752 +--------------------------------------- crates/ops/src/tests.rs | 749 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 750 insertions(+), 751 deletions(-) create mode 100644 crates/ops/src/tests.rs diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs index 498c1deb8e..06d24e35ed 100644 --- a/crates/ops/src/lib.rs +++ b/crates/ops/src/lib.rs @@ -483,754 +483,4 @@ fn tile_bytes(doc: &Document, seen: &mut HashSet) -> usize { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_doc::{Color, ColorMode, Layer, SampleType, Size}; - - fn base() -> Document { - Document::with_background("h", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE) - } - - /// Apply an edit the way the engine does: snapshot, mutate a clone, record. - fn edit(h: &mut History, cur: &mut Arc, label: &str, f: impl FnOnce(&mut Document)) { - let before = cur.clone(); - let mut d = (**cur).clone(); - f(&mut d); - *cur = Arc::new(d); - h.record(label, before, LayerTarget::default()); - } - - #[test] - fn undo_redo_cycle() { - let mut h = History::default(); - let mut cur = Arc::new(base()); - edit(&mut h, &mut cur, "New Layer", |d| { - d.insert_above(None, Layer::raster("L", d.pixel_format())); - }); - assert_eq!(cur.layers.len(), 2); - assert_eq!(h.undo_label(), Some("New Layer")); - cur = h.undo(cur).unwrap().0; - assert_eq!(cur.layers.len(), 1); - assert_eq!(h.redo_label(), Some("New Layer")); - cur = h.redo(cur).unwrap().0; - assert_eq!(cur.layers.len(), 2); - assert!(h.redo(cur.clone()).is_none()); - } - - #[test] - fn undo_and_redo_return_the_layers_each_state_targeted_when_created() { - let mut h = History::default(); - let open = Arc::new(base()); - let bg = open.layers[0].id; - let target = |id: LayerId| LayerTarget { active: Some(id), selected: vec![id] }; - h.set_current_layers(target(bg)); - // New Layer targets the new layer; the background is then selected (not a step) and filled. - let mut d = (*open).clone(); - let new = d.insert_above(None, Layer::raster("L", d.pixel_format())); - let layered = Arc::new(d); - h.record("New Layer", open, target(new)); - let mut d = (*layered).clone(); - d.name = "filled".into(); - h.record("Fill", layered, target(bg)); - let (d, layers) = h.undo(Arc::new(d)).unwrap(); - assert_eq!(layers, target(new), "New Layer's state targeted the new layer when created"); - let (d, layers) = h.undo(d).unwrap(); - assert_eq!(layers, target(bg), "the opened document's target"); - let (d, layers) = h.redo(d).unwrap(); - assert_eq!(layers, target(new)); - let (_, layers) = h.redo(d).unwrap(); - assert_eq!(layers, target(bg), "Fill's state targeted the background"); - } - - #[test] - fn state_accessor_matches_entries() { - let mut h = History::default(); - let mut cur = Arc::new(base()); - let open = cur.clone(); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); - assert_eq!(h.entries().len(), h.past_len() + 1); - assert!(Arc::ptr_eq(&h.state(0).unwrap(), &open)); - assert_eq!(h.state(1).unwrap().name, "a"); - assert!(h.state(2).is_none(), "the current document is not held"); - cur = h.undo(cur).unwrap().0; - h.undo(cur).unwrap(); - assert_eq!(h.redo_labels().collect::>(), ["A", "B"], "next redo first"); - } - - /// The History Brush source is a state, not an index: it stays on its state through undo, - /// redo and older states falling off, is kept when it would fall off itself, and is gone - /// (no source) once a new step discards it. - #[test] - fn brush_source_follows_its_state() { - let mut h = History::new(3); - let mut cur = Arc::new(base()); - assert_eq!(h.brush_source(), Some(0), "default: the oldest state"); - assert!(!h.set_brush_source(1), "no such row yet"); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); - assert!(h.set_brush_source(1)); - assert_eq!(h.row_doc(1, &cur).unwrap().name, "a"); - // Undo / redo: the rows stay put, and A's state is still row 1. - cur = h.undo(cur).unwrap().0; - assert_eq!((h.brush_source(), h.row_doc(1, &cur).unwrap().name.as_str()), (Some(1), "a")); - assert_eq!(h.row_doc(2, &cur).unwrap().name, "b", "a redo row"); - cur = h.redo(cur).unwrap().0; - // Open falls off the 3-state limit: A's state moves up to row 0 and stays the source. - edit(&mut h, &mut cur, "C", |d| d.name = "c".into()); - edit(&mut h, &mut cur, "D", |d| d.name = "d".into()); - assert_eq!(h.entries(), ["A", "B", "C", "D"]); - assert_eq!(h.brush_source(), Some(0)); - // A would fall off next: it is kept, and the states after it fall off instead. - edit(&mut h, &mut cur, "E", |d| d.name = "e".into()); - edit(&mut h, &mut cur, "F", |d| d.name = "f".into()); - assert_eq!(h.entries(), ["A", "D", "E", "F"]); - assert_eq!((h.brush_source(), h.row_doc(0, &cur).unwrap().name.as_str()), (Some(0), "a")); - // A redo state as the source, discarded by a new step: no source until one is set. - cur = h.undo(cur).unwrap().0; - assert!(h.set_brush_source(3), "the greyed F row"); - assert_eq!((h.brush_source(), h.row_doc(3, &cur).unwrap().name.as_str()), (Some(3), "f")); - assert!(h.row_doc(4, &cur).is_none() && h.row_id(4).is_none()); - edit(&mut h, &mut cur, "G", |d| d.name = "g".into()); - assert_eq!(h.brush_source(), None); - // The current state as the source keeps it once it becomes a past state; once it is no - // longer the source, it falls off as usual. - assert!(h.set_brush_source(3)); - edit(&mut h, &mut cur, "H", |d| d.name = "h".into()); - assert_eq!((h.brush_source(), h.row_doc(2, &cur).unwrap().name.as_str()), (Some(2), "g")); - assert!(h.set_brush_source(1)); - edit(&mut h, &mut cur, "I", |d| d.name = "i".into()); - assert_eq!(h.entries(), ["E", "G", "H", "I"]); - } - - #[test] - fn byte_budget_keeps_the_brush_source() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - for i in 0..5 { - edit(&mut h, &mut cur, &format!("paint {i}"), |d| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); - }); - } - assert!(h.set_brush_source(1)); - h.max_bytes = 1; - let dropped = h.trim(&cur); - assert_eq!(h.entries(), ["paint 0", "paint 3", "paint 4"], "the source is kept with the last step"); - assert_eq!(dropped, 3); - assert_eq!(h.brush_source(), Some(0)); - } - - /// The pinned source counts against the byte budget: with room for three states, the - /// source and the two newest are kept, never more than the budget (#3536 review). - #[test] - fn byte_budget_counts_the_brush_source_first() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - let tile = h.pixel_bytes(&cur); - assert!(tile > 0); - for i in 0..5 { - edit(&mut h, &mut cur, &format!("paint {i}"), |d| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); - }); - } - // Every state holds one tile of its own; the source is the oldest (Open). - assert!(h.set_brush_source(0)); - h.max_bytes = tile * 4; - assert_eq!(h.trim(&cur), 2); - assert_eq!(h.entries(), ["Open", "paint 2", "paint 3", "paint 4"]); - assert!(h.pixel_bytes(&cur) <= h.max_bytes, "{} > {}", h.pixel_bytes(&cur), h.max_bytes); - assert_eq!(h.trim(&cur), 0, "it fits now"); - // A new step trims to the budget again, still keeping the source. - edit(&mut h, &mut cur, "paint 5", |d| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[1.0, 0.0, 0.0, 1.0]); - }); - assert_eq!(h.trim(&cur), 1); - assert_eq!(h.entries(), ["Open", "paint 3", "paint 4", "paint 5"]); - assert!(h.pixel_bytes(&cur) <= h.max_bytes); - assert_eq!(h.brush_source(), Some(0)); - } - - /// Edit › Purge › Histories clears every state: a source set on one of them goes back to the - /// default (the oldest state held) instead of leaving no source (#3536 review). - #[test] - fn clear_resets_the_brush_source() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); - assert!(h.set_brush_source(1)); - h.clear(); - assert_eq!(h.brush_source(), Some(0)); - assert_eq!(h.row_doc(0, &cur).unwrap().name, "b"); - } - - /// History panel › Clear History leaves a usable (default) source, and its undo restores the - /// source set on a past state. - #[test] - fn clear_states_resets_the_brush_source_until_undo() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); - assert!(h.set_brush_source(1)); - assert!(h.clear_states()); - assert_eq!(h.brush_source(), Some(0)); - assert_eq!(h.row_doc(0, &cur).unwrap().name, "b"); - cur = h.undo(cur).unwrap().0; - assert_eq!((h.brush_source(), h.row_doc(1, &cur).unwrap().name.as_str()), (Some(1), "a")); - } - - #[test] - fn new_edit_clears_redo() { - let mut h = History::default(); - let mut cur = Arc::new(base()); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - cur = h.undo(cur).unwrap().0; - edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); - assert!(!h.can_redo()); - assert_eq!(h.entries(), vec!["Open".to_string(), "B".to_string()]); - } - - #[test] - fn max_states_bound() { - let mut h = History::new(3); - let mut cur = Arc::new(base()); - for i in 0..10 { - edit(&mut h, &mut cur, &format!("step {i}"), |d| d.name = format!("{i}")); - } - let mut n = 0; - while let Some((d, _)) = h.undo(cur.clone()) { - cur = d; - n += 1; - } - assert_eq!(n, 3); - assert_eq!(cur.name, "6"); - } - - #[test] - fn byte_budget_drops_oldest_states_but_keeps_one() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - let tile = 256 * 256 * 4; - // Each step repaints the background's tile: one unique tile per state. - for i in 0..6 { - edit(&mut h, &mut cur, &format!("paint {i}"), |d| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); - }); - } - assert_eq!(h.trim(&cur), 0, "unlimited by default"); - assert_eq!(h.past_len(), 6); - // The current tile plus three history tiles fit. - h.max_bytes = 4 * tile; - assert_eq!(h.trim(&cur), 3); - assert_eq!(h.past_len(), 3); - assert_eq!(h.unique_bytes(&cur), 3 * tile); - assert_eq!(h.pixel_bytes(&cur), 4 * tile, "the current tile plus history's"); - assert_eq!(h.entries()[0], "paint 2"); - // A budget smaller than one state still keeps the last step undoable. - h.max_bytes = 1; - h.trim(&cur); - assert_eq!(h.past_len(), 1); - assert!(h.undo(cur.clone()).is_some()); - } - - /// Snapshot-only tiles count against the budget (#4530); tiles a snapshot shares with the - /// document or a state count once, and a purge frees only what no snapshot keeps. - #[test] - fn snapshot_tiles_count_against_the_budget() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - let tile = 256 * 256 * 4; - let paint = |d: &mut Document, v: f32| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[v, 0.0, 0.0, 1.0]); - }; - // A snapshot holding a tile nothing else does, then one sharing the first state's tile. - let mut own = (*cur).clone(); - paint(&mut own, 0.9); - edit(&mut h, &mut cur, "paint 0", |d| paint(d, 0.1)); - let shared = h.state(0).unwrap(); - for i in 1..6 { - edit(&mut h, &mut cur, &format!("paint {i}"), |d| paint(d, i as f32 / 8.0)); - } - let snaps = [&own, &*shared]; - assert_eq!(h.extra_bytes(&cur, &snaps), tile, "the shared tile is history's"); - assert_eq!(h.extra_bytes(&cur, &[]), 0); - assert_eq!(h.unique_bytes(&cur), 6 * tile); - assert_eq!(h.unique_bytes_besides(&cur, &snaps), 5 * tile, "clearing keeps the shared tile"); - // Both snapshot tiles stay whatever is trimmed (the shared one too), so beside the - // current tile they leave room for two history tiles; without them, four would fit. - h.max_bytes = 5 * tile; - assert_eq!(h.trim_with(&cur, &snaps), 4); - assert_eq!(h.past_len(), 2); - assert_eq!(h.pixel_bytes(&cur) + h.extra_bytes(&cur, &snaps), 5 * tile); - // Still keeps the last step undoable. - h.max_bytes = 1; - h.trim_with(&cur, &snaps); - assert_eq!(h.past_len(), 1); - } - - #[test] - fn history_shares_untouched_tiles() { - let mut h = History::default(); - let mut cur = Arc::new(base()); - assert_eq!(h.unique_bytes(&cur), 0); - // rename only: no pixel changes, history holds no unique tiles - edit(&mut h, &mut cur, "Rename", |d| d.name = "x".into()); - assert_eq!(h.unique_bytes(&cur), 0); - // paint one pixel: exactly one tile becomes unique to history - edit(&mut h, &mut cur, "Paint", |d| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[0.0, 0.0, 0.0, 1.0]); - }); - assert_eq!(h.unique_bytes(&cur), 256 * 256 * 4); - } - - #[test] - fn fill_caches_and_smart_filter_masks_count_toward_history_bytes() { - use photocraft_doc::{Affine, Fill, FillCache, LayerContent, LayerMask, PixelFormat, SmartObject, SmartSource, Surface}; - let mut doc = Document::new("fills", Size::new(64, 64), ColorMode::Rgb, SampleType::U8); - let mut fill = Layer::new("Fill", LayerContent::Fill(Fill::Solid(Color::WHITE))); - let mut cache = Surface::new(PixelFormat::GRAY8); - cache.write_pixel(1, 1, &[1.0]); - fill.fill_cache = Some(FillCache { fill: Fill::Solid(Color::WHITE), surface: cache }); - doc.insert_above(None, fill); - let mut smart_obj = SmartObject::new(SmartSource::Linked { path: "a.png".into() }, Affine::IDENTITY, None); - let mut mask = LayerMask::reveal_all(); - mask.surface.write_pixel(1, 1, &[0.5]); - smart_obj.filter_mask = Some(mask); - doc.insert_above(None, Layer::new("Smart", LayerContent::Smart(smart_obj))); - let tile = 256 * 256; - let mut cur = Arc::new(doc); - let mut h = History { max_bytes: usize::MAX, ..History::default() }; - assert_eq!(h.pixel_bytes(&cur), 2 * tile, "fill cache and smart filter mask are counted"); - edit(&mut h, &mut cur, "Rename", |doc| doc.name = "renamed".into()); - assert_eq!(h.pixel_bytes(&cur), 2 * tile, "shared tiles count once"); - edit(&mut h, &mut cur, "Fill cache", |doc| { - let id = doc.layers[0].id; - if let Some(cache) = doc.layer_mut(id).and_then(|l| l.fill_cache.as_mut()) { - cache.surface.write_pixel(1, 1, &[0.0]); - } - }); - assert_eq!(h.pixel_bytes(&cur), 3 * tile, "the copied fill cache tile is history-only"); - assert_eq!(h.unique_bytes(&cur), tile); - h.trim(&cur); - assert_counter(&h, &cur); - h.max_bytes = 2 * tile; - assert_eq!(h.trim(&cur), 1, "the copied fill cache tile pushes history over budget"); - assert_eq!(h.pixel_bytes(&cur), 3 * tile, "the most recent undo state is always kept"); - assert_counter(&h, &cur); - } - - #[test] - fn selection_tiles_count_current_and_history_without_double_counting() { - use photocraft_doc::{PixelFormat, Surface}; - for depth in SampleType::ALL { - let mut doc = Document::new("selection", Size::new(300, 64), ColorMode::Rgb, depth); - let mut selection = Surface::new(PixelFormat::new(ColorMode::Grayscale, depth, false)); - selection.write_pixel(1, 1, &[1.0]); - selection.write_pixel(257, 1, &[1.0]); - doc.selection = Some(selection); - let mut cur = Arc::new(doc); - let tile = match depth { - SampleType::U8 => 65_536, - SampleType::U16 => 131_072, - SampleType::F32 => 262_144, - }; - let mut h = History { max_bytes: usize::MAX, ..History::default() }; - assert_eq!(h.pixel_bytes(&cur), 2 * tile, "current selection counts without any history"); - assert_eq!(h.unique_bytes(&cur), 0); - edit(&mut h, &mut cur, "Rename", |doc| doc.name = "renamed".into()); - assert_eq!(h.pixel_bytes(&cur), 2 * tile, "the shared selection tiles count once"); - edit(&mut h, &mut cur, "Selection", |doc| { - doc.selection.as_mut().unwrap().write_pixel(1, 1, &[0.5]); - }); - assert_eq!(h.pixel_bytes(&cur), 3 * tile, "only the changed selection tile is copied"); - assert_eq!(h.unique_bytes(&cur), tile); - h.trim(&cur); - assert_counter(&h, &cur); - let selected_value = cur.selection.as_ref().unwrap().sample_channel(1, 1, 0); - edit(&mut h, &mut cur, "Deselect", |doc| doc.selection = None); - assert_eq!(h.pixel_bytes(&cur), 3 * tile, "deselecting leaves the previous masks in history"); - assert_eq!(h.unique_bytes(&cur), 3 * tile); - assert_counter(&h, &cur); - cur = h.undo(cur).unwrap().0; - assert_eq!(cur.selection.as_ref().unwrap().sample_channel(1, 1, 0), selected_value); - assert_eq!(h.pixel_bytes(&cur), 3 * tile); - assert_eq!(h.unique_bytes(&cur), tile); - assert_counter(&h, &cur); - // Coalescing can change the current mask without recording another state. - Arc::make_mut(&mut cur).selection.as_mut().unwrap().write_pixel(257, 1, &[0.25]); - assert_eq!(h.pixel_bytes(&cur), 4 * tile); - assert_eq!(h.trim(&cur), 0); - assert_counter(&h, &cur); - cur = h.redo(cur).unwrap().0; - assert!(cur.selection.is_none()); - assert_eq!(h.pixel_bytes(&cur), 4 * tile); - assert_counter(&h, &cur); - } - } - - #[test] - fn selection_byte_budget_drops_old_masks_and_keeps_the_last_undo() { - use photocraft_doc::{PixelFormat, Surface}; - for depth in SampleType::ALL { - let mut doc = Document::new("selection", Size::new(64, 64), ColorMode::Rgb, depth); - doc.selection = Some(Surface::new(PixelFormat::new(ColorMode::Grayscale, depth, false))); - let mut cur = Arc::new(doc); - let tile = 256 * 256 * depth.bytes(); - let mut h = History::default(); - for i in 1..=6 { - edit(&mut h, &mut cur, "Selection", |doc| { - doc.selection.as_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0]); - }); - } - assert_eq!(h.pixel_bytes(&cur), 6 * tile); - h.max_bytes = 3 * tile; - assert_eq!(h.trim(&cur), 4); - assert_eq!(h.past_len(), 2); - assert_eq!(h.pixel_bytes(&cur), 3 * tile); - assert_eq!(h.unique_bytes(&cur), 2 * tile); - assert_counter(&h, &cur); - h.max_bytes = 1; - assert_eq!(h.trim(&cur), 1); - assert_eq!(h.past_len(), 1, "the most recent undo survives even below one mask's size"); - assert_eq!(h.pixel_bytes(&cur), 2 * tile); - cur = h.undo(cur).unwrap().0; - assert_counter(&h, &cur); - } - } - - fn assert_counter(h: &History, current: &Document) { - let counter = h.tiles.as_ref().expect("budget initializes the counter"); - let total = tile_bytes(current, &mut HashSet::new()).saturating_add(h.unique_bytes(current)); - assert_eq!(counter.bytes_with(current), total as u128); - assert_eq!(h.pixel_bytes(current), total); - let mut seen = HashSet::new(); - let retained: usize = h.held_states().map(|s| tile_bytes(&s.doc, &mut seen)).sum(); - let empty = Document::new("empty", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); - assert_eq!(counter.bytes_with(&empty), retained as u128); - } - - fn video_document(depth: SampleType, frames: usize) -> Document { - let mut doc = Document::new("video", Size::new(64, 64), ColorMode::Rgb, depth); - let mut layer = Layer::raster("Video", doc.pixel_format()); - let footage: Vec<_> = (0..frames) - .map(|i| { - let mut surface = photocraft_doc::Surface::new(doc.pixel_format()); - surface.write_pixel(1, 1, &[i as f32 / frames as f32, 0.0, 0.0, 1.0]); - surface - }) - .collect(); - layer.content = photocraft_doc::LayerContent::Raster(footage[0].clone()); - layer.video = Some(photocraft_doc::VideoData::new(footage, 24.0)); - doc.layers.push(layer); - doc - } - - #[test] - fn video_memory_counts_originals_and_deduplicates_displayed_frames() { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - let mut doc = video_document(depth, 3); - let tile = doc.layers[0].surface().unwrap().tiles().next().unwrap().1.bytes().len(); - let video = doc.layers[0].video.as_mut().unwrap(); - video.original_frames = Some(video.frames.clone()); - // Original footage and the displayed frame alias the stack, except this painted frame. - video.frames[2].write_pixel(1, 1, &[0.0, 1.0, 0.0, 1.0]); - let mut cur = Arc::new(doc); - let mut h = History { max_bytes: usize::MAX, ..History::default() }; - assert_eq!(h.pixel_bytes(&cur), 4 * tile); - for name in ["A", "B"] { - edit(&mut h, &mut cur, "Rename", |doc| doc.name = name.into()); - h.trim(&cur); - } - assert_counter(&h, &cur); - assert_eq!(h.pixel_bytes(&cur), 4 * tile); - assert_eq!(h.unique_bytes(&cur), 0); - // Rasterizing keeps the displayed frame; the rest of the clip survives only in undo. - edit(&mut h, &mut cur, "Rasterize", |doc| doc.layers[0].video = None); - assert_eq!(h.unique_bytes(&cur), 3 * tile); - assert_eq!(h.pixel_bytes(&cur), 4 * tile); - assert_counter(&h, &cur); - cur = h.undo(cur).unwrap().0; - assert_eq!(h.unique_bytes(&cur), 0); - assert_counter(&h, &cur); - cur = h.redo(cur).unwrap().0; - assert_eq!(h.unique_bytes(&cur), 3 * tile); - assert_counter(&h, &cur); - h.clear(); - assert_eq!(h.pixel_bytes(&cur), tile); - } - } - - #[test] - fn video_memory_budget_evicts_deleted_off_playhead_frames() { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - let mut cur = Arc::new(video_document(depth, 6)); - let tile = cur.layers[0].surface().unwrap().tiles().next().unwrap().1.bytes().len(); - let mut h = History::default(); - for _ in 0..4 { - edit(&mut h, &mut cur, "Delete Frame", |doc| { - doc.layers[0].video.as_mut().unwrap().frames.remove(1); - }); - } - assert_eq!(h.pixel_bytes(&cur), 6 * tile); - assert_eq!(h.unique_bytes(&cur), 4 * tile); - h.max_bytes = 3 * tile; - assert_eq!(h.trim(&cur), 3); - assert_eq!(h.past_len(), 1); - assert_eq!(h.pixel_bytes(&cur), 3 * tile); - assert_eq!(h.unique_bytes(&cur), tile); - assert_counter(&h, &cur); - cur = h.undo(cur).unwrap().0; - assert_eq!(cur.layers[0].video.as_ref().unwrap().frames.len(), 3); - assert_counter(&h, &cur); - cur = h.redo(cur).unwrap().0; - assert_eq!(cur.layers[0].video.as_ref().unwrap().frames.len(), 2); - assert_counter(&h, &cur); - // A budget below the remaining clip still keeps the latest step undoable. - h.max_bytes = 1; - assert_eq!(h.trim(&cur), 0); - assert!(h.can_undo()); - } - } - - /// A pattern fill or layer style copies its pattern into the document, so the pattern's tiles - /// count like layer pixels, shared ones once; undoing that step leaves them to the redo states. - #[test] - fn document_patterns_count_as_document_pixels() { - use photocraft_doc::{Pattern, Surface}; - for depth in SampleType::ALL { - let tile = 4 * 256 * 256 * depth.bytes(); - let mut cur = Arc::new(Document::new("patterns", Size::new(64, 64), ColorMode::Rgb, depth)); - let mut h = History { max_bytes: usize::MAX, ..History::default() }; - for name in ["A", "B"] { - edit(&mut h, &mut cur, "Rename", |doc| doc.name = name.into()); - h.trim(&cur); - } - let mut surface = Surface::new(cur.pixel_format()); - surface.write_pixel(1, 1, &[0.0, 0.0, 1.0, 1.0]); - let pattern = Pattern::new("Pattern", surface, 4, 4); - edit(&mut h, &mut cur, "Pattern Fill", |doc| doc.patterns.push(pattern)); - assert_eq!(h.pixel_bytes(&cur), tile, "the document's pattern"); - assert_eq!(h.unique_bytes(&cur), 0); - assert_counter(&h, &cur); - edit(&mut h, &mut cur, "Rename", |doc| doc.name = "C".into()); - assert_eq!(h.pixel_bytes(&cur), tile, "shared with history, it counts once"); - assert_counter(&h, &cur); - for _ in 0..2 { - cur = h.undo(cur).unwrap().0; - assert_counter(&h, &cur); - } - assert!(cur.patterns.is_empty()); - assert_eq!(h.unique_bytes(&cur), tile, "only the redo states hold the pattern"); - assert_eq!(h.pixel_bytes(&cur), tile); - cur = h.redo(cur).unwrap().0; - assert_eq!(h.unique_bytes(&cur), 0); - assert_counter(&h, &cur); - h.clear(); - assert_eq!(h.pixel_bytes(&cur), tile); - } - } - - #[test] - fn counter_tracks_eviction_undo_redo_branching_purge_and_clones() { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - let mut cur = Arc::new(Document::with_background("h", Size::new(300, 64), ColorMode::Rgb, depth, Color::WHITE)); - Arc::make_mut(&mut cur).selection = Some(photocraft_doc::Surface::new(photocraft_doc::PixelFormat::GRAY8)); - let mut h = History::new(4); - h.max_bytes = usize::MAX; - for i in 0..8 { - edit(&mut h, &mut cur, "Paint", |doc| { - doc.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 10.0, 0.0, 0.0, 1.0]); - doc.selection.as_mut().unwrap().write_pixel(1, 1, &[i as f32 / 10.0]); - }); - h.trim(&cur); - if i >= 1 { - assert_counter(&h, &cur); - } - } - cur = h.undo(cur).unwrap().0; - assert_counter(&h, &cur); - cur = h.undo(cur).unwrap().0; - assert_counter(&h, &cur); - cur = h.redo(cur).unwrap().0; - assert_counter(&h, &cur); - let copy = h.clone(); - edit(&mut h, &mut cur, "Branch", |doc| doc.name = "branch".into()); - assert!(!h.can_redo()); - assert_counter(&h, &cur); - assert_counter(©, &cur); - cur = h.undo(cur).unwrap().0; - h.clear_redo(); - assert_counter(&h, &cur); - h.purge_last(); - assert_counter(&h, &cur); - h.clear(); - assert!(h.tiles.is_none()); - assert_eq!(h.pixel_bytes(&cur), tile_bytes(&cur, &mut HashSet::new())); - } - } - - #[test] - fn shared_masks_channels_and_repeated_snapshot_references_count_once() { - use photocraft_doc::{AlphaChannel, LayerMask, PixelFormat, Surface}; - let mut doc = base(); - let mut gray = Surface::new(PixelFormat::GRAY8); - gray.write_pixel(1, 1, &[1.0]); - doc.layers[0].mask = Some(LayerMask { surface: gray.clone(), ..LayerMask::reveal_all() }); - doc.channels.push(AlphaChannel::new("alpha", gray.clone())); - doc.selection = Some(gray.clone()); - doc.quick_mask = Some(AlphaChannel::new("quick", gray)); - doc.layers.push(doc.layers[0].clone()); - let mut cur = Arc::new(doc); - let bytes = tile_bytes(&cur, &mut HashSet::new()); - let mut h = History::new(50); - // Counting current separately would double count its tiles; the exact union fits. - h.max_bytes = bytes; - for _ in 0..6 { - h.record("Same", cur.clone(), LayerTarget::default()); - assert_eq!(h.trim(&cur), 0); - } - assert_counter(&h, &cur); - for _ in 0..3 { - cur = h.undo(cur).unwrap().0; - assert_counter(&h, &cur); - } - h.clear_redo(); - h.purge_last(); - assert_counter(&h, &cur); - assert_eq!(h.pixel_bytes(&cur), bytes); - } - - #[test] - fn threshold_rechecks_coalesced_current_and_changed_budget() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - h.max_bytes = usize::MAX; - for i in 0..6 { - edit(&mut h, &mut cur, "Paint", |doc| { - doc.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 10.0, 0.0, 0.0, 1.0]); - }); - h.trim(&cur); - } - // A coalesced edit may change current without recording another history state. - Arc::make_mut(&mut cur).layers[0].surface_mut().unwrap().write_pixel(300, 1, &[1.0; 4]); - let tile = 256 * 256 * 4; - h.max_bytes = 4 * tile; - assert_eq!(h.trim(&cur), 4); - assert_eq!(h.past_len(), 2); - assert_counter(&h, &cur); - cur = h.undo(cur).unwrap().0; - assert_counter(&h, &cur); - h.max_bytes = 0; - edit(&mut h, &mut cur, "Unlimited", |doc| doc.name = "u".into()); - assert!(h.tiles.is_none()); - h.max_bytes = 1; - h.trim(&cur); - assert_eq!(h.past_len(), 1, "always retain the most recent undo"); - assert_counter(&h, &cur); - } - - #[test] - fn transferred_tiles_cannot_make_the_budget_check_underestimate_current() { - use photocraft_doc::{PixelFormat, Surface}; - let before = Arc::new(base()); - let mut current = (*before).clone(); - let mut large = Surface::new(PixelFormat::new(ColorMode::Cmyk, SampleType::F32, true)); - large.write_pixel(256, 0, &[1.0; 5]); - current.layers[0].surface_mut().unwrap().put_tiles(large.take_tiles(photocraft_doc::Rect::from_xywh(256, 0, 1, 1))); - let mut h = History::new(50); - h.max_bytes = tile_bytes(¤t, &mut HashSet::new()) - 1; - h.record("A", before.clone(), LayerTarget::default()); - h.record("B", before, LayerTarget::default()); - assert_eq!(h.trim(¤t), 1, "current alone exceeds the budget; only the mandatory undo survives"); - assert_counter(&h, ¤t); - } - - #[test] - fn clear_states_keeps_the_document_and_undo_brings_the_list_back() { - let mut h = History::new(10); - let mut cur = Arc::new(base()); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); - edit(&mut h, &mut cur, "C", |d| d.name = "c".into()); - let (d, _) = h.undo(cur.clone()).unwrap(); - cur = d; - let entries = h.entries(); - assert_eq!(entries, ["Open", "A", "B"]); - assert!(h.clear_states()); - assert_eq!(h.entries(), ["B"], "only the current state is left"); - assert!(!h.can_redo() && h.can_undo() && h.is_cleared()); - assert_eq!(h.undo_label(), Some(CLEAR_HISTORY_LABEL)); - assert!(!h.clear_states(), "nothing left to clear"); - assert!(h.is_cleared(), "and the cleared states are still held"); - let (d, _) = h.undo(cur.clone()).unwrap(); - assert!(Arc::ptr_eq(&d, &cur), "undoing Clear History doesn't change the document"); - assert_eq!(h.entries(), entries); - assert_eq!(h.redo_labels().collect::>(), ["C"], "the redo state is back too"); - assert!(!h.is_cleared()); - } - - #[test] - fn cleared_states_still_count_in_the_memory_figures_and_the_budget() { - let mut h = History::new(50); - let mut cur = Arc::new(base()); - let tile = 256 * 256 * 4; - for i in 0..5 { - edit(&mut h, &mut cur, &format!("paint {i}"), |d| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); - }); - } - cur = h.undo(cur).unwrap().0; - let (unique, pixels) = (h.unique_bytes(&cur), h.pixel_bytes(&cur)); - assert_eq!(unique, 5 * tile, "four undo states and one redo state"); - assert!(h.clear_states()); - assert_eq!(h.unique_bytes(&cur), unique, "Clear History frees nothing while it can be undone"); - assert_eq!(h.pixel_bytes(&cur), pixels); - assert_eq!(h.extra_bytes(&cur, &[&base()]), tile, "a snapshot's own tile, not the cleared states'"); - assert_eq!(h.unique_bytes_besides(&cur, &[]), unique); - // The budget counts them too: the oldest cleared states go first. - h.max_bytes = 4 * tile; - assert_eq!(h.trim(&cur), 2); - assert_counter(&h, &cur); - assert_eq!(h.pixel_bytes(&cur), 4 * tile); - assert!(h.is_cleared() && h.past_len() == 0, "the list stays cleared"); - h.undo(cur.clone()).unwrap(); - assert_eq!(h.entries(), ["paint 1", "paint 2", "paint 3"], "undo brings back what the budget kept"); - assert_eq!(h.redo_labels().collect::>(), ["paint 4"]); - // A new step after Clear History forgets the cleared states, and the counter with them. - assert!(h.clear_states()); - h.trim(&cur); - edit(&mut h, &mut cur, "paint 5", |d| { - let id = d.layers[0].id; - d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[1.0, 0.0, 0.0, 1.0]); - }); - assert_eq!(h.unique_bytes(&cur), tile, "only the state before the new step"); - assert_eq!(h.pixel_bytes(&cur), 2 * tile); - } - - #[test] - fn a_new_step_or_purge_forgets_the_cleared_states() { - let mut h = History::new(10); - let mut cur = Arc::new(base()); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - assert!(h.clear_states()); - edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); - assert_eq!(h.entries(), ["A", "B"]); - assert!(!h.is_cleared()); - assert!(h.undo(cur.clone()).is_some()); - assert!(!h.can_undo(), "the cleared states are gone"); - let mut h = History::new(10); - edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); - assert!(h.clear_states()); - assert!(h.purge_last()); - assert!(!h.can_undo() && !h.is_cleared()); - assert!(!h.clear_states(), "a single state can't be cleared"); - } -} +mod tests; diff --git a/crates/ops/src/tests.rs b/crates/ops/src/tests.rs new file mode 100644 index 0000000000..1ac12b2885 --- /dev/null +++ b/crates/ops/src/tests.rs @@ -0,0 +1,749 @@ +use super::*; +use photocraft_doc::{Color, ColorMode, Layer, SampleType, Size}; + +fn base() -> Document { + Document::with_background("h", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE) +} + +/// Apply an edit the way the engine does: snapshot, mutate a clone, record. +fn edit(h: &mut History, cur: &mut Arc, label: &str, f: impl FnOnce(&mut Document)) { + let before = cur.clone(); + let mut d = (**cur).clone(); + f(&mut d); + *cur = Arc::new(d); + h.record(label, before, LayerTarget::default()); +} + +#[test] +fn undo_redo_cycle() { + let mut h = History::default(); + let mut cur = Arc::new(base()); + edit(&mut h, &mut cur, "New Layer", |d| { + d.insert_above(None, Layer::raster("L", d.pixel_format())); + }); + assert_eq!(cur.layers.len(), 2); + assert_eq!(h.undo_label(), Some("New Layer")); + cur = h.undo(cur).unwrap().0; + assert_eq!(cur.layers.len(), 1); + assert_eq!(h.redo_label(), Some("New Layer")); + cur = h.redo(cur).unwrap().0; + assert_eq!(cur.layers.len(), 2); + assert!(h.redo(cur.clone()).is_none()); +} + +#[test] +fn undo_and_redo_return_the_layers_each_state_targeted_when_created() { + let mut h = History::default(); + let open = Arc::new(base()); + let bg = open.layers[0].id; + let target = |id: LayerId| LayerTarget { active: Some(id), selected: vec![id] }; + h.set_current_layers(target(bg)); + // New Layer targets the new layer; the background is then selected (not a step) and filled. + let mut d = (*open).clone(); + let new = d.insert_above(None, Layer::raster("L", d.pixel_format())); + let layered = Arc::new(d); + h.record("New Layer", open, target(new)); + let mut d = (*layered).clone(); + d.name = "filled".into(); + h.record("Fill", layered, target(bg)); + let (d, layers) = h.undo(Arc::new(d)).unwrap(); + assert_eq!(layers, target(new), "New Layer's state targeted the new layer when created"); + let (d, layers) = h.undo(d).unwrap(); + assert_eq!(layers, target(bg), "the opened document's target"); + let (d, layers) = h.redo(d).unwrap(); + assert_eq!(layers, target(new)); + let (_, layers) = h.redo(d).unwrap(); + assert_eq!(layers, target(bg), "Fill's state targeted the background"); +} + +#[test] +fn state_accessor_matches_entries() { + let mut h = History::default(); + let mut cur = Arc::new(base()); + let open = cur.clone(); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); + assert_eq!(h.entries().len(), h.past_len() + 1); + assert!(Arc::ptr_eq(&h.state(0).unwrap(), &open)); + assert_eq!(h.state(1).unwrap().name, "a"); + assert!(h.state(2).is_none(), "the current document is not held"); + cur = h.undo(cur).unwrap().0; + h.undo(cur).unwrap(); + assert_eq!(h.redo_labels().collect::>(), ["A", "B"], "next redo first"); +} + +/// The History Brush source is a state, not an index: it stays on its state through undo, +/// redo and older states falling off, is kept when it would fall off itself, and is gone +/// (no source) once a new step discards it. +#[test] +fn brush_source_follows_its_state() { + let mut h = History::new(3); + let mut cur = Arc::new(base()); + assert_eq!(h.brush_source(), Some(0), "default: the oldest state"); + assert!(!h.set_brush_source(1), "no such row yet"); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); + assert!(h.set_brush_source(1)); + assert_eq!(h.row_doc(1, &cur).unwrap().name, "a"); + // Undo / redo: the rows stay put, and A's state is still row 1. + cur = h.undo(cur).unwrap().0; + assert_eq!((h.brush_source(), h.row_doc(1, &cur).unwrap().name.as_str()), (Some(1), "a")); + assert_eq!(h.row_doc(2, &cur).unwrap().name, "b", "a redo row"); + cur = h.redo(cur).unwrap().0; + // Open falls off the 3-state limit: A's state moves up to row 0 and stays the source. + edit(&mut h, &mut cur, "C", |d| d.name = "c".into()); + edit(&mut h, &mut cur, "D", |d| d.name = "d".into()); + assert_eq!(h.entries(), ["A", "B", "C", "D"]); + assert_eq!(h.brush_source(), Some(0)); + // A would fall off next: it is kept, and the states after it fall off instead. + edit(&mut h, &mut cur, "E", |d| d.name = "e".into()); + edit(&mut h, &mut cur, "F", |d| d.name = "f".into()); + assert_eq!(h.entries(), ["A", "D", "E", "F"]); + assert_eq!((h.brush_source(), h.row_doc(0, &cur).unwrap().name.as_str()), (Some(0), "a")); + // A redo state as the source, discarded by a new step: no source until one is set. + cur = h.undo(cur).unwrap().0; + assert!(h.set_brush_source(3), "the greyed F row"); + assert_eq!((h.brush_source(), h.row_doc(3, &cur).unwrap().name.as_str()), (Some(3), "f")); + assert!(h.row_doc(4, &cur).is_none() && h.row_id(4).is_none()); + edit(&mut h, &mut cur, "G", |d| d.name = "g".into()); + assert_eq!(h.brush_source(), None); + // The current state as the source keeps it once it becomes a past state; once it is no + // longer the source, it falls off as usual. + assert!(h.set_brush_source(3)); + edit(&mut h, &mut cur, "H", |d| d.name = "h".into()); + assert_eq!((h.brush_source(), h.row_doc(2, &cur).unwrap().name.as_str()), (Some(2), "g")); + assert!(h.set_brush_source(1)); + edit(&mut h, &mut cur, "I", |d| d.name = "i".into()); + assert_eq!(h.entries(), ["E", "G", "H", "I"]); +} + +#[test] +fn byte_budget_keeps_the_brush_source() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + for i in 0..5 { + edit(&mut h, &mut cur, &format!("paint {i}"), |d| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + } + assert!(h.set_brush_source(1)); + h.max_bytes = 1; + let dropped = h.trim(&cur); + assert_eq!(h.entries(), ["paint 0", "paint 3", "paint 4"], "the source is kept with the last step"); + assert_eq!(dropped, 3); + assert_eq!(h.brush_source(), Some(0)); +} + +/// The pinned source counts against the byte budget: with room for three states, the +/// source and the two newest are kept, never more than the budget (#3536 review). +#[test] +fn byte_budget_counts_the_brush_source_first() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + let tile = h.pixel_bytes(&cur); + assert!(tile > 0); + for i in 0..5 { + edit(&mut h, &mut cur, &format!("paint {i}"), |d| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + } + // Every state holds one tile of its own; the source is the oldest (Open). + assert!(h.set_brush_source(0)); + h.max_bytes = tile * 4; + assert_eq!(h.trim(&cur), 2); + assert_eq!(h.entries(), ["Open", "paint 2", "paint 3", "paint 4"]); + assert!(h.pixel_bytes(&cur) <= h.max_bytes, "{} > {}", h.pixel_bytes(&cur), h.max_bytes); + assert_eq!(h.trim(&cur), 0, "it fits now"); + // A new step trims to the budget again, still keeping the source. + edit(&mut h, &mut cur, "paint 5", |d| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[1.0, 0.0, 0.0, 1.0]); + }); + assert_eq!(h.trim(&cur), 1); + assert_eq!(h.entries(), ["Open", "paint 3", "paint 4", "paint 5"]); + assert!(h.pixel_bytes(&cur) <= h.max_bytes); + assert_eq!(h.brush_source(), Some(0)); +} + +/// Edit › Purge › Histories clears every state: a source set on one of them goes back to the +/// default (the oldest state held) instead of leaving no source (#3536 review). +#[test] +fn clear_resets_the_brush_source() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); + assert!(h.set_brush_source(1)); + h.clear(); + assert_eq!(h.brush_source(), Some(0)); + assert_eq!(h.row_doc(0, &cur).unwrap().name, "b"); +} + +/// History panel › Clear History leaves a usable (default) source, and its undo restores the +/// source set on a past state. +#[test] +fn clear_states_resets_the_brush_source_until_undo() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); + assert!(h.set_brush_source(1)); + assert!(h.clear_states()); + assert_eq!(h.brush_source(), Some(0)); + assert_eq!(h.row_doc(0, &cur).unwrap().name, "b"); + cur = h.undo(cur).unwrap().0; + assert_eq!((h.brush_source(), h.row_doc(1, &cur).unwrap().name.as_str()), (Some(1), "a")); +} + +#[test] +fn new_edit_clears_redo() { + let mut h = History::default(); + let mut cur = Arc::new(base()); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + cur = h.undo(cur).unwrap().0; + edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); + assert!(!h.can_redo()); + assert_eq!(h.entries(), vec!["Open".to_string(), "B".to_string()]); +} + +#[test] +fn max_states_bound() { + let mut h = History::new(3); + let mut cur = Arc::new(base()); + for i in 0..10 { + edit(&mut h, &mut cur, &format!("step {i}"), |d| d.name = format!("{i}")); + } + let mut n = 0; + while let Some((d, _)) = h.undo(cur.clone()) { + cur = d; + n += 1; + } + assert_eq!(n, 3); + assert_eq!(cur.name, "6"); +} + +#[test] +fn byte_budget_drops_oldest_states_but_keeps_one() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + let tile = 256 * 256 * 4; + // Each step repaints the background's tile: one unique tile per state. + for i in 0..6 { + edit(&mut h, &mut cur, &format!("paint {i}"), |d| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + } + assert_eq!(h.trim(&cur), 0, "unlimited by default"); + assert_eq!(h.past_len(), 6); + // The current tile plus three history tiles fit. + h.max_bytes = 4 * tile; + assert_eq!(h.trim(&cur), 3); + assert_eq!(h.past_len(), 3); + assert_eq!(h.unique_bytes(&cur), 3 * tile); + assert_eq!(h.pixel_bytes(&cur), 4 * tile, "the current tile plus history's"); + assert_eq!(h.entries()[0], "paint 2"); + // A budget smaller than one state still keeps the last step undoable. + h.max_bytes = 1; + h.trim(&cur); + assert_eq!(h.past_len(), 1); + assert!(h.undo(cur.clone()).is_some()); +} + +/// Snapshot-only tiles count against the budget (#4530); tiles a snapshot shares with the +/// document or a state count once, and a purge frees only what no snapshot keeps. +#[test] +fn snapshot_tiles_count_against_the_budget() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + let tile = 256 * 256 * 4; + let paint = |d: &mut Document, v: f32| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[v, 0.0, 0.0, 1.0]); + }; + // A snapshot holding a tile nothing else does, then one sharing the first state's tile. + let mut own = (*cur).clone(); + paint(&mut own, 0.9); + edit(&mut h, &mut cur, "paint 0", |d| paint(d, 0.1)); + let shared = h.state(0).unwrap(); + for i in 1..6 { + edit(&mut h, &mut cur, &format!("paint {i}"), |d| paint(d, i as f32 / 8.0)); + } + let snaps = [&own, &*shared]; + assert_eq!(h.extra_bytes(&cur, &snaps), tile, "the shared tile is history's"); + assert_eq!(h.extra_bytes(&cur, &[]), 0); + assert_eq!(h.unique_bytes(&cur), 6 * tile); + assert_eq!(h.unique_bytes_besides(&cur, &snaps), 5 * tile, "clearing keeps the shared tile"); + // Both snapshot tiles stay whatever is trimmed (the shared one too), so beside the + // current tile they leave room for two history tiles; without them, four would fit. + h.max_bytes = 5 * tile; + assert_eq!(h.trim_with(&cur, &snaps), 4); + assert_eq!(h.past_len(), 2); + assert_eq!(h.pixel_bytes(&cur) + h.extra_bytes(&cur, &snaps), 5 * tile); + // Still keeps the last step undoable. + h.max_bytes = 1; + h.trim_with(&cur, &snaps); + assert_eq!(h.past_len(), 1); +} + +#[test] +fn history_shares_untouched_tiles() { + let mut h = History::default(); + let mut cur = Arc::new(base()); + assert_eq!(h.unique_bytes(&cur), 0); + // rename only: no pixel changes, history holds no unique tiles + edit(&mut h, &mut cur, "Rename", |d| d.name = "x".into()); + assert_eq!(h.unique_bytes(&cur), 0); + // paint one pixel: exactly one tile becomes unique to history + edit(&mut h, &mut cur, "Paint", |d| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[0.0, 0.0, 0.0, 1.0]); + }); + assert_eq!(h.unique_bytes(&cur), 256 * 256 * 4); +} + +#[test] +fn fill_caches_and_smart_filter_masks_count_toward_history_bytes() { + use photocraft_doc::{Affine, Fill, FillCache, LayerContent, LayerMask, PixelFormat, SmartObject, SmartSource, Surface}; + let mut doc = Document::new("fills", Size::new(64, 64), ColorMode::Rgb, SampleType::U8); + let mut fill = Layer::new("Fill", LayerContent::Fill(Fill::Solid(Color::WHITE))); + let mut cache = Surface::new(PixelFormat::GRAY8); + cache.write_pixel(1, 1, &[1.0]); + fill.fill_cache = Some(FillCache { fill: Fill::Solid(Color::WHITE), surface: cache }); + doc.insert_above(None, fill); + let mut smart_obj = SmartObject::new(SmartSource::Linked { path: "a.png".into() }, Affine::IDENTITY, None); + let mut mask = LayerMask::reveal_all(); + mask.surface.write_pixel(1, 1, &[0.5]); + smart_obj.filter_mask = Some(mask); + doc.insert_above(None, Layer::new("Smart", LayerContent::Smart(smart_obj))); + let tile = 256 * 256; + let mut cur = Arc::new(doc); + let mut h = History { max_bytes: usize::MAX, ..History::default() }; + assert_eq!(h.pixel_bytes(&cur), 2 * tile, "fill cache and smart filter mask are counted"); + edit(&mut h, &mut cur, "Rename", |doc| doc.name = "renamed".into()); + assert_eq!(h.pixel_bytes(&cur), 2 * tile, "shared tiles count once"); + edit(&mut h, &mut cur, "Fill cache", |doc| { + let id = doc.layers[0].id; + if let Some(cache) = doc.layer_mut(id).and_then(|l| l.fill_cache.as_mut()) { + cache.surface.write_pixel(1, 1, &[0.0]); + } + }); + assert_eq!(h.pixel_bytes(&cur), 3 * tile, "the copied fill cache tile is history-only"); + assert_eq!(h.unique_bytes(&cur), tile); + h.trim(&cur); + assert_counter(&h, &cur); + h.max_bytes = 2 * tile; + assert_eq!(h.trim(&cur), 1, "the copied fill cache tile pushes history over budget"); + assert_eq!(h.pixel_bytes(&cur), 3 * tile, "the most recent undo state is always kept"); + assert_counter(&h, &cur); +} + +#[test] +fn selection_tiles_count_current_and_history_without_double_counting() { + use photocraft_doc::{PixelFormat, Surface}; + for depth in SampleType::ALL { + let mut doc = Document::new("selection", Size::new(300, 64), ColorMode::Rgb, depth); + let mut selection = Surface::new(PixelFormat::new(ColorMode::Grayscale, depth, false)); + selection.write_pixel(1, 1, &[1.0]); + selection.write_pixel(257, 1, &[1.0]); + doc.selection = Some(selection); + let mut cur = Arc::new(doc); + let tile = match depth { + SampleType::U8 => 65_536, + SampleType::U16 => 131_072, + SampleType::F32 => 262_144, + }; + let mut h = History { max_bytes: usize::MAX, ..History::default() }; + assert_eq!(h.pixel_bytes(&cur), 2 * tile, "current selection counts without any history"); + assert_eq!(h.unique_bytes(&cur), 0); + edit(&mut h, &mut cur, "Rename", |doc| doc.name = "renamed".into()); + assert_eq!(h.pixel_bytes(&cur), 2 * tile, "the shared selection tiles count once"); + edit(&mut h, &mut cur, "Selection", |doc| { + doc.selection.as_mut().unwrap().write_pixel(1, 1, &[0.5]); + }); + assert_eq!(h.pixel_bytes(&cur), 3 * tile, "only the changed selection tile is copied"); + assert_eq!(h.unique_bytes(&cur), tile); + h.trim(&cur); + assert_counter(&h, &cur); + let selected_value = cur.selection.as_ref().unwrap().sample_channel(1, 1, 0); + edit(&mut h, &mut cur, "Deselect", |doc| doc.selection = None); + assert_eq!(h.pixel_bytes(&cur), 3 * tile, "deselecting leaves the previous masks in history"); + assert_eq!(h.unique_bytes(&cur), 3 * tile); + assert_counter(&h, &cur); + cur = h.undo(cur).unwrap().0; + assert_eq!(cur.selection.as_ref().unwrap().sample_channel(1, 1, 0), selected_value); + assert_eq!(h.pixel_bytes(&cur), 3 * tile); + assert_eq!(h.unique_bytes(&cur), tile); + assert_counter(&h, &cur); + // Coalescing can change the current mask without recording another state. + Arc::make_mut(&mut cur).selection.as_mut().unwrap().write_pixel(257, 1, &[0.25]); + assert_eq!(h.pixel_bytes(&cur), 4 * tile); + assert_eq!(h.trim(&cur), 0); + assert_counter(&h, &cur); + cur = h.redo(cur).unwrap().0; + assert!(cur.selection.is_none()); + assert_eq!(h.pixel_bytes(&cur), 4 * tile); + assert_counter(&h, &cur); + } +} + +#[test] +fn selection_byte_budget_drops_old_masks_and_keeps_the_last_undo() { + use photocraft_doc::{PixelFormat, Surface}; + for depth in SampleType::ALL { + let mut doc = Document::new("selection", Size::new(64, 64), ColorMode::Rgb, depth); + doc.selection = Some(Surface::new(PixelFormat::new(ColorMode::Grayscale, depth, false))); + let mut cur = Arc::new(doc); + let tile = 256 * 256 * depth.bytes(); + let mut h = History::default(); + for i in 1..=6 { + edit(&mut h, &mut cur, "Selection", |doc| { + doc.selection.as_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0]); + }); + } + assert_eq!(h.pixel_bytes(&cur), 6 * tile); + h.max_bytes = 3 * tile; + assert_eq!(h.trim(&cur), 4); + assert_eq!(h.past_len(), 2); + assert_eq!(h.pixel_bytes(&cur), 3 * tile); + assert_eq!(h.unique_bytes(&cur), 2 * tile); + assert_counter(&h, &cur); + h.max_bytes = 1; + assert_eq!(h.trim(&cur), 1); + assert_eq!(h.past_len(), 1, "the most recent undo survives even below one mask's size"); + assert_eq!(h.pixel_bytes(&cur), 2 * tile); + cur = h.undo(cur).unwrap().0; + assert_counter(&h, &cur); + } +} + +fn assert_counter(h: &History, current: &Document) { + let counter = h.tiles.as_ref().expect("budget initializes the counter"); + let total = tile_bytes(current, &mut HashSet::new()).saturating_add(h.unique_bytes(current)); + assert_eq!(counter.bytes_with(current), total as u128); + assert_eq!(h.pixel_bytes(current), total); + let mut seen = HashSet::new(); + let retained: usize = h.held_states().map(|s| tile_bytes(&s.doc, &mut seen)).sum(); + let empty = Document::new("empty", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); + assert_eq!(counter.bytes_with(&empty), retained as u128); +} + +fn video_document(depth: SampleType, frames: usize) -> Document { + let mut doc = Document::new("video", Size::new(64, 64), ColorMode::Rgb, depth); + let mut layer = Layer::raster("Video", doc.pixel_format()); + let footage: Vec<_> = (0..frames) + .map(|i| { + let mut surface = photocraft_doc::Surface::new(doc.pixel_format()); + surface.write_pixel(1, 1, &[i as f32 / frames as f32, 0.0, 0.0, 1.0]); + surface + }) + .collect(); + layer.content = photocraft_doc::LayerContent::Raster(footage[0].clone()); + layer.video = Some(photocraft_doc::VideoData::new(footage, 24.0)); + doc.layers.push(layer); + doc +} + +#[test] +fn video_memory_counts_originals_and_deduplicates_displayed_frames() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut doc = video_document(depth, 3); + let tile = doc.layers[0].surface().unwrap().tiles().next().unwrap().1.bytes().len(); + let video = doc.layers[0].video.as_mut().unwrap(); + video.original_frames = Some(video.frames.clone()); + // Original footage and the displayed frame alias the stack, except this painted frame. + video.frames[2].write_pixel(1, 1, &[0.0, 1.0, 0.0, 1.0]); + let mut cur = Arc::new(doc); + let mut h = History { max_bytes: usize::MAX, ..History::default() }; + assert_eq!(h.pixel_bytes(&cur), 4 * tile); + for name in ["A", "B"] { + edit(&mut h, &mut cur, "Rename", |doc| doc.name = name.into()); + h.trim(&cur); + } + assert_counter(&h, &cur); + assert_eq!(h.pixel_bytes(&cur), 4 * tile); + assert_eq!(h.unique_bytes(&cur), 0); + // Rasterizing keeps the displayed frame; the rest of the clip survives only in undo. + edit(&mut h, &mut cur, "Rasterize", |doc| doc.layers[0].video = None); + assert_eq!(h.unique_bytes(&cur), 3 * tile); + assert_eq!(h.pixel_bytes(&cur), 4 * tile); + assert_counter(&h, &cur); + cur = h.undo(cur).unwrap().0; + assert_eq!(h.unique_bytes(&cur), 0); + assert_counter(&h, &cur); + cur = h.redo(cur).unwrap().0; + assert_eq!(h.unique_bytes(&cur), 3 * tile); + assert_counter(&h, &cur); + h.clear(); + assert_eq!(h.pixel_bytes(&cur), tile); + } +} + +#[test] +fn video_memory_budget_evicts_deleted_off_playhead_frames() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut cur = Arc::new(video_document(depth, 6)); + let tile = cur.layers[0].surface().unwrap().tiles().next().unwrap().1.bytes().len(); + let mut h = History::default(); + for _ in 0..4 { + edit(&mut h, &mut cur, "Delete Frame", |doc| { + doc.layers[0].video.as_mut().unwrap().frames.remove(1); + }); + } + assert_eq!(h.pixel_bytes(&cur), 6 * tile); + assert_eq!(h.unique_bytes(&cur), 4 * tile); + h.max_bytes = 3 * tile; + assert_eq!(h.trim(&cur), 3); + assert_eq!(h.past_len(), 1); + assert_eq!(h.pixel_bytes(&cur), 3 * tile); + assert_eq!(h.unique_bytes(&cur), tile); + assert_counter(&h, &cur); + cur = h.undo(cur).unwrap().0; + assert_eq!(cur.layers[0].video.as_ref().unwrap().frames.len(), 3); + assert_counter(&h, &cur); + cur = h.redo(cur).unwrap().0; + assert_eq!(cur.layers[0].video.as_ref().unwrap().frames.len(), 2); + assert_counter(&h, &cur); + // A budget below the remaining clip still keeps the latest step undoable. + h.max_bytes = 1; + assert_eq!(h.trim(&cur), 0); + assert!(h.can_undo()); + } +} + +/// A pattern fill or layer style copies its pattern into the document, so the pattern's tiles +/// count like layer pixels, shared ones once; undoing that step leaves them to the redo states. +#[test] +fn document_patterns_count_as_document_pixels() { + use photocraft_doc::{Pattern, Surface}; + for depth in SampleType::ALL { + let tile = 4 * 256 * 256 * depth.bytes(); + let mut cur = Arc::new(Document::new("patterns", Size::new(64, 64), ColorMode::Rgb, depth)); + let mut h = History { max_bytes: usize::MAX, ..History::default() }; + for name in ["A", "B"] { + edit(&mut h, &mut cur, "Rename", |doc| doc.name = name.into()); + h.trim(&cur); + } + let mut surface = Surface::new(cur.pixel_format()); + surface.write_pixel(1, 1, &[0.0, 0.0, 1.0, 1.0]); + let pattern = Pattern::new("Pattern", surface, 4, 4); + edit(&mut h, &mut cur, "Pattern Fill", |doc| doc.patterns.push(pattern)); + assert_eq!(h.pixel_bytes(&cur), tile, "the document's pattern"); + assert_eq!(h.unique_bytes(&cur), 0); + assert_counter(&h, &cur); + edit(&mut h, &mut cur, "Rename", |doc| doc.name = "C".into()); + assert_eq!(h.pixel_bytes(&cur), tile, "shared with history, it counts once"); + assert_counter(&h, &cur); + for _ in 0..2 { + cur = h.undo(cur).unwrap().0; + assert_counter(&h, &cur); + } + assert!(cur.patterns.is_empty()); + assert_eq!(h.unique_bytes(&cur), tile, "only the redo states hold the pattern"); + assert_eq!(h.pixel_bytes(&cur), tile); + cur = h.redo(cur).unwrap().0; + assert_eq!(h.unique_bytes(&cur), 0); + assert_counter(&h, &cur); + h.clear(); + assert_eq!(h.pixel_bytes(&cur), tile); + } +} + +#[test] +fn counter_tracks_eviction_undo_redo_branching_purge_and_clones() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut cur = Arc::new(Document::with_background("h", Size::new(300, 64), ColorMode::Rgb, depth, Color::WHITE)); + Arc::make_mut(&mut cur).selection = Some(photocraft_doc::Surface::new(photocraft_doc::PixelFormat::GRAY8)); + let mut h = History::new(4); + h.max_bytes = usize::MAX; + for i in 0..8 { + edit(&mut h, &mut cur, "Paint", |doc| { + doc.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 10.0, 0.0, 0.0, 1.0]); + doc.selection.as_mut().unwrap().write_pixel(1, 1, &[i as f32 / 10.0]); + }); + h.trim(&cur); + if i >= 1 { + assert_counter(&h, &cur); + } + } + cur = h.undo(cur).unwrap().0; + assert_counter(&h, &cur); + cur = h.undo(cur).unwrap().0; + assert_counter(&h, &cur); + cur = h.redo(cur).unwrap().0; + assert_counter(&h, &cur); + let copy = h.clone(); + edit(&mut h, &mut cur, "Branch", |doc| doc.name = "branch".into()); + assert!(!h.can_redo()); + assert_counter(&h, &cur); + assert_counter(©, &cur); + cur = h.undo(cur).unwrap().0; + h.clear_redo(); + assert_counter(&h, &cur); + h.purge_last(); + assert_counter(&h, &cur); + h.clear(); + assert!(h.tiles.is_none()); + assert_eq!(h.pixel_bytes(&cur), tile_bytes(&cur, &mut HashSet::new())); + } +} + +#[test] +fn shared_masks_channels_and_repeated_snapshot_references_count_once() { + use photocraft_doc::{AlphaChannel, LayerMask, PixelFormat, Surface}; + let mut doc = base(); + let mut gray = Surface::new(PixelFormat::GRAY8); + gray.write_pixel(1, 1, &[1.0]); + doc.layers[0].mask = Some(LayerMask { surface: gray.clone(), ..LayerMask::reveal_all() }); + doc.channels.push(AlphaChannel::new("alpha", gray.clone())); + doc.selection = Some(gray.clone()); + doc.quick_mask = Some(AlphaChannel::new("quick", gray)); + doc.layers.push(doc.layers[0].clone()); + let mut cur = Arc::new(doc); + let bytes = tile_bytes(&cur, &mut HashSet::new()); + let mut h = History::new(50); + // Counting current separately would double count its tiles; the exact union fits. + h.max_bytes = bytes; + for _ in 0..6 { + h.record("Same", cur.clone(), LayerTarget::default()); + assert_eq!(h.trim(&cur), 0); + } + assert_counter(&h, &cur); + for _ in 0..3 { + cur = h.undo(cur).unwrap().0; + assert_counter(&h, &cur); + } + h.clear_redo(); + h.purge_last(); + assert_counter(&h, &cur); + assert_eq!(h.pixel_bytes(&cur), bytes); +} + +#[test] +fn threshold_rechecks_coalesced_current_and_changed_budget() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + h.max_bytes = usize::MAX; + for i in 0..6 { + edit(&mut h, &mut cur, "Paint", |doc| { + doc.layers[0].surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 10.0, 0.0, 0.0, 1.0]); + }); + h.trim(&cur); + } + // A coalesced edit may change current without recording another history state. + Arc::make_mut(&mut cur).layers[0].surface_mut().unwrap().write_pixel(300, 1, &[1.0; 4]); + let tile = 256 * 256 * 4; + h.max_bytes = 4 * tile; + assert_eq!(h.trim(&cur), 4); + assert_eq!(h.past_len(), 2); + assert_counter(&h, &cur); + cur = h.undo(cur).unwrap().0; + assert_counter(&h, &cur); + h.max_bytes = 0; + edit(&mut h, &mut cur, "Unlimited", |doc| doc.name = "u".into()); + assert!(h.tiles.is_none()); + h.max_bytes = 1; + h.trim(&cur); + assert_eq!(h.past_len(), 1, "always retain the most recent undo"); + assert_counter(&h, &cur); +} + +#[test] +fn transferred_tiles_cannot_make_the_budget_check_underestimate_current() { + use photocraft_doc::{PixelFormat, Surface}; + let before = Arc::new(base()); + let mut current = (*before).clone(); + let mut large = Surface::new(PixelFormat::new(ColorMode::Cmyk, SampleType::F32, true)); + large.write_pixel(256, 0, &[1.0; 5]); + current.layers[0].surface_mut().unwrap().put_tiles(large.take_tiles(photocraft_doc::Rect::from_xywh(256, 0, 1, 1))); + let mut h = History::new(50); + h.max_bytes = tile_bytes(¤t, &mut HashSet::new()) - 1; + h.record("A", before.clone(), LayerTarget::default()); + h.record("B", before, LayerTarget::default()); + assert_eq!(h.trim(¤t), 1, "current alone exceeds the budget; only the mandatory undo survives"); + assert_counter(&h, ¤t); +} + +#[test] +fn clear_states_keeps_the_document_and_undo_brings_the_list_back() { + let mut h = History::new(10); + let mut cur = Arc::new(base()); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); + edit(&mut h, &mut cur, "C", |d| d.name = "c".into()); + let (d, _) = h.undo(cur.clone()).unwrap(); + cur = d; + let entries = h.entries(); + assert_eq!(entries, ["Open", "A", "B"]); + assert!(h.clear_states()); + assert_eq!(h.entries(), ["B"], "only the current state is left"); + assert!(!h.can_redo() && h.can_undo() && h.is_cleared()); + assert_eq!(h.undo_label(), Some(CLEAR_HISTORY_LABEL)); + assert!(!h.clear_states(), "nothing left to clear"); + assert!(h.is_cleared(), "and the cleared states are still held"); + let (d, _) = h.undo(cur.clone()).unwrap(); + assert!(Arc::ptr_eq(&d, &cur), "undoing Clear History doesn't change the document"); + assert_eq!(h.entries(), entries); + assert_eq!(h.redo_labels().collect::>(), ["C"], "the redo state is back too"); + assert!(!h.is_cleared()); +} + +#[test] +fn cleared_states_still_count_in_the_memory_figures_and_the_budget() { + let mut h = History::new(50); + let mut cur = Arc::new(base()); + let tile = 256 * 256 * 4; + for i in 0..5 { + edit(&mut h, &mut cur, &format!("paint {i}"), |d| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[i as f32 / 8.0, 0.0, 0.0, 1.0]); + }); + } + cur = h.undo(cur).unwrap().0; + let (unique, pixels) = (h.unique_bytes(&cur), h.pixel_bytes(&cur)); + assert_eq!(unique, 5 * tile, "four undo states and one redo state"); + assert!(h.clear_states()); + assert_eq!(h.unique_bytes(&cur), unique, "Clear History frees nothing while it can be undone"); + assert_eq!(h.pixel_bytes(&cur), pixels); + assert_eq!(h.extra_bytes(&cur, &[&base()]), tile, "a snapshot's own tile, not the cleared states'"); + assert_eq!(h.unique_bytes_besides(&cur, &[]), unique); + // The budget counts them too: the oldest cleared states go first. + h.max_bytes = 4 * tile; + assert_eq!(h.trim(&cur), 2); + assert_counter(&h, &cur); + assert_eq!(h.pixel_bytes(&cur), 4 * tile); + assert!(h.is_cleared() && h.past_len() == 0, "the list stays cleared"); + h.undo(cur.clone()).unwrap(); + assert_eq!(h.entries(), ["paint 1", "paint 2", "paint 3"], "undo brings back what the budget kept"); + assert_eq!(h.redo_labels().collect::>(), ["paint 4"]); + // A new step after Clear History forgets the cleared states, and the counter with them. + assert!(h.clear_states()); + h.trim(&cur); + edit(&mut h, &mut cur, "paint 5", |d| { + let id = d.layers[0].id; + d.layer_mut(id).unwrap().surface_mut().unwrap().write_pixel(1, 1, &[1.0, 0.0, 0.0, 1.0]); + }); + assert_eq!(h.unique_bytes(&cur), tile, "only the state before the new step"); + assert_eq!(h.pixel_bytes(&cur), 2 * tile); +} + +#[test] +fn a_new_step_or_purge_forgets_the_cleared_states() { + let mut h = History::new(10); + let mut cur = Arc::new(base()); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + assert!(h.clear_states()); + edit(&mut h, &mut cur, "B", |d| d.name = "b".into()); + assert_eq!(h.entries(), ["A", "B"]); + assert!(!h.is_cleared()); + assert!(h.undo(cur.clone()).is_some()); + assert!(!h.can_undo(), "the cleared states are gone"); + let mut h = History::new(10); + edit(&mut h, &mut cur, "A", |d| d.name = "a".into()); + assert!(h.clear_states()); + assert!(h.purge_last()); + assert!(!h.can_undo() && !h.is_cleared()); + assert!(!h.clear_states(), "a single state can't be cleared"); +} From 0714ed10248b471fb0b28f87eb2f996c713079d0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:28 +0000 Subject: [PATCH 051/259] refactor(ui-egui): move snap_ui.rs tests to snap_ui/tests.rs --- crates/ui-egui/src/snap_ui.rs | 760 +--------------------------- crates/ui-egui/src/snap_ui/tests.rs | 757 +++++++++++++++++++++++++++ 2 files changed, 758 insertions(+), 759 deletions(-) create mode 100644 crates/ui-egui/src/snap_ui/tests.rs diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rs index e19c95a2e7..05365dab54 100644 --- a/crates/ui-egui/src/snap_ui.rs +++ b/crates/ui-egui/src/snap_ui.rs @@ -602,762 +602,4 @@ fn draw_line(painter: &egui::Painter, xf: &ViewXform, l: &SnapLine, color: Color } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn app_with_box() -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - app.sync_views(); - app.ui.views[0].zoom = 1.0; - app.ui.views[0].fit_pending = false; - // Two boxes: a target at (300..350, 200..260) and the moving one at (40..90, 40..80). - app.run("layer.new.layer", json!({"name": "target"})).unwrap(); - app.run("select.rect", json!({"x": 300, "y": 200, "width": 50, "height": 60})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.run("layer.new.layer", json!({"name": "mover"})).unwrap(); - app.run("select.rect", json!({"x": 40, "y": 40, "width": 50, "height": 40})).unwrap(); - app.run("edit.fill", json!({"color": "#0000ff"})).unwrap(); - app.run("select.deselect", json!({})).unwrap(); - app - } - - /// #7538: moving selected pixels snaps (and frames) the pixels, not a loose marquee round them. - /// Snapping starts before the press cuts them, so the cut retargets it to their outline. - #[test] - fn moving_selected_pixels_snaps_their_bounds_not_the_marquee() { - for alt in [false, true] { - let mut app = app_with_box(); - app.ui.tool = Tool::Move; - app.run("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); - let m = egui::Modifiers { alt, ..Default::default() }; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); - let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); - assert_eq!(gesture, Some(Gesture::Move { rect: [40.0, 40.0, 90.0, 80.0] }), "alt {alt}: the blue box, not the marquee"); - // 263 px right puts the box's left edge 3 px from the target's (the marquee's 20 px off). - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 323.0, y: 100.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); - app.run("select.drop", json!({})).unwrap(); - let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds().x0); - assert_eq!(sel, Some(300), "alt {alt}: snapped to the target's edge"); - } - // A marquee's ⌘-drag cuts them the same way. - let mut app = app_with_box(); - app.ui.tool = Tool::RectMarquee; - app.run("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); - let cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, cmd); - let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); - assert_eq!(gesture, Some(Gesture::SelectionMove { rect: [40.0, 40.0, 90.0, 80.0] }), "⌘-drag with the marquee"); - // The Background has no transparency to shrink to. - let mut app = app_with_box(); - app.ui.tool = Tool::Move; - app.run("layer.select", json!({"name": "Background"})).unwrap(); - app.run("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, egui::Modifiers::NONE); - let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); - assert_eq!(gesture, Some(Gesture::Move { rect: [20.0, 20.0, 120.0, 110.0] }), "the Background"); - } - - fn mover_bounds(app: &PhotocraftApp) -> photocraft_geom::Rect { - let st = app.session.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds() - } - - #[test] - fn drawing_a_new_crop_snaps_its_corner_not_the_default_frame() { - // In both crop modes: the default mode draws a new box inside the untouched frame too. - for (classic, snap, end) in [(true, false, [300.0, 220.0]), (true, true, [294.0, 217.0]), (false, false, [300.0, 220.0]), (false, true, [294.0, 217.0])] - { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 640, "height": 480, "background": "white"})).unwrap(); - app.run("shape.create", json!({"kind": "rect", "rect": [100, 80, 200, 140], "fill": "#d59b40"})).unwrap(); - app.sync_views(); - app.ppp = 2.0; - app.ui.views[0].zoom = 1.0; - app.ui.views[0].fit_pending = false; - app.ui.tool = Tool::Crop; - app.ui.tool_options.crop_shield.classic_mode = classic; - app.ui.extras.snap = snap; - app.ui.view.show.smart_guides = true; - crate::crop_ui::ensure_frame(&mut app); - let view = app.ui.views[0].clone(); - let history = app.session.active().unwrap().history.past_len(); - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 80.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: end[0], y: end[1], pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: end[0], y: end[1] }, m); - // Smart Guides must not snap the old canvas-sized frame as if it were moving. - // With View Snap on, the new corner still snaps to the nearby shape's edges. - assert_eq!(app.ui.crop_rect, Some([100.0, 80.0, 300.0, 220.0]), "Classic Mode: {classic}, View Snap: {snap}"); - // The default mode's Auto Center Preview re-centres the drawn box; Classic Mode keeps the view. - if classic { - assert_eq!(app.ui.views[0], view); - } - assert_eq!(app.session.active().unwrap().history.past_len(), history); - } - } - - #[test] - fn move_tool_snaps_to_other_layer_edges_with_smart_guides() { - let mut app = app_with_box(); - app.ui.tool = Tool::Move; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); - // Drag so the mover's left edge lands 3 px right of the target's (x = 303). - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 323.0, y: 100.0, pressure: 1.0 }, m); - assert!(app.prefs_rt.snap_lines.iter().any(|l| l.vertical && l.pos == 300.0 && l.kind.is_smart()), "{:?}", app.prefs_rt.snap_lines); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); - assert_eq!(mover_bounds(&app).x0, 300); - assert!(app.prefs_rt.snap.is_none()); - } - - /// Puppet Warp's pins go where they are dragged: they don't snap, with View › Snap on or - /// off, whatever tool was active when it started. With the Move tool a pin drag took the - /// layer move's Smart Guides and jumped to the other layer's edges. - #[test] - fn puppet_warp_pins_never_snap() { - for (tool, snap) in [(Tool::Move, false), (Tool::Move, true), (Tool::RectMarquee, true), (Tool::Brush, false)] { - let mut app = app_with_box(); - app.ui.tool = tool; - app.ui.extras.snap = snap; - app.ui.view.show.smart_guides = true; - app.run("view.newGuide", json!({"orientation": "vertical", "position": 321})).unwrap(); - let ctx = egui::Context::default(); - crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); - // The mover's left edge 3 px right of the target's, the pin 2 px from the guide. - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 323.0, y: 100.0, pressure: 1.0 }, m); - assert!(app.prefs_rt.snap_lines.is_empty(), "{tool:?}, snap {snap}: {:?}", app.prefs_rt.snap_lines); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); - let pins = &app.distort.puppet.as_ref().unwrap().warp.pins; - assert_eq!(pins.iter().map(|p| p.dst).collect::>(), vec![[323.0, 100.0]], "{tool:?}, snap {snap}"); - } - } - - /// ⌘ turns a painting tool, or a marquee outside the selection, into the Move tool for the - /// drag: it gets the Move tool's box and smart-guide snapping, not the selected tool's. - #[test] - fn command_drag_temporary_move_snaps_like_the_move_tool() { - for tool in [Tool::Brush, Tool::RectMarquee] { - let mut app = app_with_box(); - app.ui.tool = tool; - let cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, cmd); - let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); - assert_eq!(gesture, Some(Gesture::Move { rect: [40.0, 40.0, 90.0, 80.0] }), "{tool:?}: the mover's box"); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, cmd); - assert_eq!(mover_bounds(&app).x0, 300, "{tool:?}: snapped to the target's edge"); - } - } - - /// The drag's box and snapping belong to the layer Auto-Select picks on the press, not to the - /// one selected before: another layer (its box would move instead), or an empty layer (no box, - /// no snapping at all). - #[test] - fn move_tool_box_and_snapping_follow_the_auto_selected_layer() { - for before in ["target", "empty"] { - let mut app = app_with_box(); - let mover = app.session.active().unwrap().active_layer.unwrap(); - if before == "empty" { - app.run("layer.new.layer", json!({"name": "empty"})).unwrap(); - } else { - let st = app.session.active().unwrap(); - let target = st.doc.walk().into_iter().find(|(_, _, l)| l.name == "target").unwrap().2.id; - app.run("layer.select", json!({"layer": target.0})).unwrap(); - } - app.ui.tool = Tool::Move; - app.ui.tool_options.move_auto_select = true; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); - assert_eq!(app.session.active().unwrap().active_layer, Some(mover), "{before}: Auto-Select picked the mover"); - let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); - assert_eq!(gesture, Some(Gesture::Move { rect: [40.0, 40.0, 90.0, 80.0] }), "{before}: the box is the mover's"); - // The mover's left edge lands 3 px right of the target's and snaps to it. - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 323.0, y: 100.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); - assert_eq!(mover_bounds(&app).x0, 300, "{before}: snapped to the target's edge"); - } - } - - #[test] - fn view_snap_off_blocks_smart_guide_snapping() { - let mut app = app_with_box(); - app.ui.tool = Tool::Move; - app.ui.view.show.smart_guides = true; - app.ui.extras.snap = false; - app.ui.tool_options.move_auto_select = false; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); - assert_eq!(mover_bounds(&app).x0, 303, "View › Snap off must not snap via smart guides"); - } - - #[test] - fn ctrl_or_snap_off_disables_snapping() { - let mut app = app_with_box(); - app.ui.tool = Tool::Move; - app.ui.view.show.smart_guides = false; - app.ui.extras.snap = false; - // The presses land beside the moved layer: keep moving it (no Auto-Select pick). - app.ui.tool_options.move_auto_select = false; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); - assert_eq!(mover_bounds(&app).x0, 303); - app.ui.extras.snap = true; - let ctrl = egui::Modifiers { ctrl: true, ..Default::default() }; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 62.0, y: 60.0 }, ctrl); - assert_eq!(mover_bounds(&app).x0, 305, "no snap to the target's right edge at 350? (moved freely)"); - // Ctrl only at the press (Ctrl-click auto-select) doesn't turn snapping off for the drag. - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, ctrl); - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 61.0, y: 60.0, pressure: 1.0 }, m); - assert!(!app.prefs_rt.snap.as_ref().is_some_and(|s| s.disabled)); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 61.0, y: 60.0 }, m); - // ⌘ on the Mac is not the override. - let cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; - assert!(!override_held(cmd) && override_held(ctrl)); - } - - #[test] - fn snap_off_disables_all_snapping_even_with_smart_guides() { - let mut app = app_with_box(); - app.ui.tool = Tool::Move; - assert!(app.ui.view.show.smart_guides); - app.ui.extras.snap = false; - app.ui.tool_options.move_auto_select = false; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); - assert_eq!(mover_bounds(&app).x0, 303); - assert!(app.prefs_rt.snap_lines.is_empty()); - } - - #[test] - fn marquee_corner_snaps_to_guides_and_document_edges() { - let mut app = app_with_box(); - app.run("view.newGuide", json!({"orientation": "vertical", "position": 120})).unwrap(); - app.ui.tool = Tool::RectMarquee; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 3.0, y: 2.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 116.0, y: 50.0 }, m); - let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); - assert_eq!((sel.x0, sel.y0, sel.x1), (0, 0, 120)); - // Zoomed in to 800%, 4 px is beyond the 1 px threshold: no snap. - app.ui.views[0].zoom = 8.0; - // (Deselect first: a drag starting inside the selection would move it.) - app.run("select.deselect", json!({})).unwrap(); - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 116.0, y: 50.0 }, m); - let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); - assert_eq!(sel.x1, 116); - } - - /// Space while drawing a marquee, Object Selection box or shape moves it: its edges snap, not - /// only the corner under the pointer; with Space released the corner snaps again. - #[test] - fn drawing_repositioned_with_space_snaps_its_edges() { - for tool in [Tool::RectMarquee, Tool::EllipseMarquee, Tool::ObjectSelection, Tool::Rectangle, Tool::Line] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - app.sync_views(); - app.ui.views[0].zoom = 1.0; - app.ui.views[0].fit_pending = false; - app.run("view.newGuide", json!({"orientation": "vertical", "position": 220})).unwrap(); - app.ui.tool = tool; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 150.0, y: 140.0, pressure: 1.0 }, m); - // Space down: the 50 × 40 box moves so its left edge lands 4 px short of the guide; - // the pointer corner (x = 266) is near nothing. - app.drag.as_mut().unwrap().reposition = true; - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 266.0, y: 140.0, pressure: 1.0 }, m); - assert_eq!(app.drag.as_ref().unwrap().start, [220.0, 100.0], "{tool:?}"); - if tool != Tool::RectMarquee { - continue; - } - // Space up: sizing resumes and the corner snaps to the document's right edge. - app.drag.as_mut().unwrap().reposition = false; - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 397.0, y: 140.0 }, m); - let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); - assert_eq!((sel.x0, sel.y0, sel.x1, sel.y1), (220, 100, 400, 140)); - } - } - - /// Dragging inside a selection with a marquee or lasso moves the outline (⌘ cuts the pixels - /// into a floating piece): its bounds snap, not the pointer. - #[test] - fn selection_drag_snaps_the_selection_bounds() { - for (tool, cut) in [(Tool::RectMarquee, false), (Tool::Lasso, false), (Tool::RectMarquee, true)] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); - app.sync_views(); - app.ui.views[0].zoom = 1.0; - app.ui.views[0].fit_pending = false; - app.run("view.newGuide", json!({"orientation": "vertical", "position": 220})).unwrap(); - app.run("select.rect", json!({"x": 100, "y": 100, "width": 50, "height": 40})).unwrap(); - app.ui.tool = tool; - let m = if cut { egui::Modifiers { mac_cmd: true, command: true, ..Default::default() } } else { egui::Modifiers::NONE }; - // The outline's right edge lands 2 px short of the guide (x = 218); the pointer ends - // 7 px from the document centre (x = 200), which it must not snap to. - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 125.0, y: 117.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 193.0, y: 117.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 193.0, y: 117.0 }, m); - let st = app.session.active().unwrap(); - let off = photocraft_engine::float_cmds::floating(st).map_or((0, 0), |f| f.offset); - let sel = st.doc.selection.as_ref().unwrap().content_bounds().translate(off.0, off.1); - assert_eq!((sel.x0, sel.y0, sel.x1, sel.y1), (170, 100, 220, 140), "{tool:?} cut: {cut}"); - } - } - - #[test] - fn distort_corner_snaps_from_positive_grab_offset() { - distort_corner_snaps_from_grab_offset([4.0, 3.0]); - } - - #[test] - fn distort_corner_snaps_from_negative_grab_offset() { - distort_corner_snaps_from_grab_offset([-4.0, -3.0]); - } - - fn distort_corner_snaps_from_grab_offset(offset: [f64; 2]) { - let mut app = app_with_box(); - app.run("view.newGuide", json!({"orientation": "vertical", "position": 110})).unwrap(); - app.run("view.newGuide", json!({"orientation": "horizontal", "position": 30})).unwrap(); - let ctx = egui::Context::default(); - crate::menus::invoke(&mut app, &ctx, "edit.transform.distort", json!({})).unwrap(); - let before = app.ui.transform.as_ref().unwrap().quad; - let press = [before[1][0] + offset[0], before[1][1] + offset[1]]; - // The proposed corner is (108, 32); the pointer keeps its original grab offset. - let release = [108.0 + offset[0], 32.0 + offset[1]]; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: press[0], y: press[1], pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: release[0], y: release[1], pressure: 1.0 }, m); - let moved = app.ui.transform.as_ref().unwrap().quad; - assert_eq!(moved[1], [110.0, 30.0], "grab offset {offset:?}"); - assert_eq!([moved[0], moved[2], moved[3]], [before[0], before[2], before[3]]); - assert!(app.prefs_rt.snap_lines.iter().any(|l| l.vertical && l.pos == 110.0 && l.kind == SnapKind::Guide)); - assert!(app.prefs_rt.snap_lines.iter().any(|l| !l.vertical && l.pos == 30.0 && l.kind == SnapKind::Guide)); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: release[0], y: release[1] }, m); - assert_eq!(app.ui.transform.as_ref().unwrap().quad, moved); - assert!(app.prefs_rt.snap.is_none() && app.prefs_rt.snap_lines.is_empty()); - } - - fn app_with_corner_guides(menu: &str) -> PhotocraftApp { - let mut app = app_with_box(); - app.run("view.newGuide", json!({"orientation": "vertical", "position": 110})).unwrap(); - app.run("view.newGuide", json!({"orientation": "horizontal", "position": 30})).unwrap(); - crate::menus::invoke(&mut app, &egui::Context::default(), menu, json!({})).unwrap(); - app - } - - fn move_corner(app: &mut PhotocraftApp, index: usize, offset: [f64; 2], end: [f64; 2], down: egui::Modifiers, moving: egui::Modifiers) { - let corner = app.ui.transform.as_ref().unwrap().quad[index]; - crate::canvas::tool_event(app, ToolEvent::Down { x: corner[0] + offset[0], y: corner[1] + offset[1], pressure: 1.0 }, down); - crate::canvas::tool_event(app, ToolEvent::Move { x: end[0] + offset[0], y: end[1] + offset[1], pressure: 1.0 }, moving); - } - - #[test] - fn distort_corner_respects_guide_axes_tolerance_and_toggles() { - for (snap, shown, guides, end, expected) in [ - (true, true, true, [108.0, 20.0], [110.0, 20.0]), - (true, true, true, [100.0, 32.0], [100.0, 30.0]), - (true, true, true, [100.0, 20.0], [100.0, 20.0]), - (false, true, true, [108.0, 32.0], [108.0, 32.0]), - (true, false, true, [108.0, 32.0], [108.0, 32.0]), - (true, true, false, [108.0, 32.0], [108.0, 32.0]), - ] { - let mut app = app_with_corner_guides("edit.transform.distort"); - app.ui.extras.snap = snap; - app.ui.extras.guides = shown; - app.ui.view.snap_to.guides = guides; - move_corner(&mut app, 1, [4.0, 3.0], end, egui::Modifiers::NONE, egui::Modifiers::NONE); - assert_eq!(app.ui.transform.as_ref().unwrap().quad[1], expected, "Snap: {snap}, shown: {shown}, guides: {guides}, proposed: {end:?}"); - assert!(app.prefs_rt.snap_lines.iter().all(|line| (if line.vertical { expected[0] } else { expected[1] } - line.pos).abs() < 1e-6)); - } - } - - #[test] - fn free_transform_command_corner_snaps_with_the_real_grab_offset() { - let windows = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; - let mac = egui::Modifiers { command: true, mac_cmd: true, ..egui::Modifiers::NONE }; - for m in [windows, mac] { - for offset in [[4.0, 3.0], [-4.0, -3.0], [0.0, 0.0]] { - for down in [m, egui::Modifiers::NONE] { - let mut app = app_with_corner_guides("edit.freeTransform"); - let before = app.ui.transform.as_ref().unwrap().quad; - move_corner(&mut app, 1, offset, [108.0, 32.0], down, m); - let moved = app.ui.transform.as_ref().unwrap().quad; - assert_eq!(moved[1], [110.0, 30.0], "{m:?}, press {down:?}, offset {offset:?}"); - assert_eq!([moved[0], moved[2], moved[3]], [before[0], before[2], before[3]]); - assert_eq!(app.prefs_rt.snap_lines.len(), 2); - assert!(!app.prefs_rt.snap.as_ref().unwrap().disabled); - } - } - } - } - - #[test] - fn control_alone_still_disables_snapping_in_menu_distort() { - let mut app = app_with_corner_guides("edit.transform.distort"); - let ctrl = egui::Modifiers { ctrl: true, ..egui::Modifiers::NONE }; - move_corner(&mut app, 1, [4.0, 3.0], [108.0, 32.0], ctrl, ctrl); - assert_eq!(app.ui.transform.as_ref().unwrap().quad[1], [108.0, 32.0]); - assert!(app.prefs_rt.snap.as_ref().unwrap().disabled); - assert!(app.prefs_rt.snap_lines.is_empty()); - } - - #[test] - fn skew_control_corner_keeps_its_axis_instead_of_snapping_as_distort() { - let ctrl = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; - for legacy in [false, true] { - for (menu, expected, snapping) in [ - ("edit.transform.skew", [[40.0, 40.0], [108.0, 40.0], [90.0, 80.0], [40.0, 80.0]], false), - ("edit.transform.distort", [[40.0, 40.0], [110.0, 30.0], [90.0, 80.0], [40.0, 80.0]], true), - ("edit.transform.perspective", [[22.0, 40.0], [108.0, 40.0], [90.0, 80.0], [40.0, 80.0]], false), - ] { - let mut app = app_with_corner_guides(menu); - app.run("prefs.set", json!({"path": "general.useLegacyFreeTransform", "value": legacy})).unwrap(); - let doc = app.session.active().unwrap().doc.clone(); - let past = app.session.active().unwrap().history.past_len(); - let prefs = serde_json::to_value(app.session.prefs()).unwrap(); - // Ctrl arrives after the raw, off-centre press, as on the actual canvas path. - move_corner(&mut app, 1, [4.0, 3.0], [108.0, 32.0], egui::Modifiers::NONE, ctrl); - assert_eq!(app.ui.transform.as_ref().unwrap().quad, expected, "{menu}, legacy {legacy}"); - assert_eq!(!app.prefs_rt.snap.as_ref().unwrap().disabled, snapping, "{menu}"); - assert_eq!(app.prefs_rt.snap_lines.len(), if snapping { 2 } else { 0 }, "{menu}"); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 112.0, y: 35.0 }, ctrl); - assert_eq!(app.ui.transform.as_ref().unwrap().quad, expected, "release preserves {menu}"); - crate::transform_tool::cancel(&mut app); - assert!(app.ui.transform.is_none() && app.prefs_rt.snap.is_none() && app.prefs_rt.snap_lines.is_empty()); - assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &doc), "cancel preserves {menu}'s document"); - assert_eq!(app.session.active().unwrap().history.past_len(), past, "cancel preserves {menu}'s history"); - assert_eq!(serde_json::to_value(app.session.prefs()).unwrap(), prefs, "{menu} does not change preferences"); - } - } - } - - #[test] - fn skew_control_corner_on_editable_type_slides_the_whole_edge() { - let ctrl = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; - for legacy in [false, true] { - let mut app = app_with_box(); - app.run("type.create", json!({"x": 40, "y": 60, "text": "Hello"})).unwrap(); - app.run("prefs.set", json!({"path": "general.useLegacyFreeTransform", "value": legacy})).unwrap(); - crate::menus::invoke(&mut app, &egui::Context::default(), "edit.transform.skew", json!({})).unwrap(); - let before = app.ui.transform.as_ref().unwrap().quad; - let end = [before[1][0] + 18.0, before[1][1] - 8.0]; - let doc = app.session.active().unwrap().doc.clone(); - let past = app.session.active().unwrap().history.past_len(); - move_corner(&mut app, 1, [2.0, 1.0], end, egui::Modifiers::NONE, ctrl); - let mut expected = before; - expected[0][0] += 18.0; - expected[1][0] += 18.0; - assert_eq!(app.ui.transform.as_ref().unwrap().quad, expected, "type remains affine, legacy {legacy}"); - assert!(app.prefs_rt.snap.as_ref().unwrap().disabled && app.prefs_rt.snap_lines.is_empty()); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: end[0] + 2.0, y: end[1] + 1.0 }, ctrl); - assert_eq!(app.ui.transform.as_ref().unwrap().quad, expected, "release preserves the type's edge"); - crate::transform_tool::cancel(&mut app); - assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &doc)); - assert_eq!(app.session.active().unwrap().history.past_len(), past); - } - } - - #[test] - fn transform_non_distortion_gestures_keep_control_snap_override() { - let ctrl = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; - let perspective = egui::Modifiers { alt: true, shift: true, ..ctrl }; - for (menu, press, m) in [ - ("edit.freeTransform", [65.0, 40.0], ctrl), // edge - ("edit.freeTransform", [65.0, 60.0], ctrl), // pivot - ("edit.freeTransform", [55.0, 52.0], ctrl), // inside - ("edit.freeTransform", [90.0, 40.0], perspective), - ("edit.transform.perspective", [90.0, 40.0], ctrl), - ("edit.transform.warp", [90.0, 40.0], ctrl), - ("edit.contentAwareScale", [90.0, 40.0], ctrl), - ] { - let mut app = app_with_corner_guides(menu); - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: press[0], y: press[1], pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 108.0, y: 32.0, pressure: 1.0 }, m); - assert!(app.prefs_rt.snap.as_ref().unwrap().disabled, "{menu}, {press:?}, {m:?}"); - assert!(app.prefs_rt.snap_lines.is_empty(), "{menu}, {press:?}"); - } - } - - #[test] - fn editable_type_refusal_keeps_control_snap_override() { - let mut app = app_with_box(); - app.run("type.create", json!({"x": 40, "y": 60, "text": "Hello"})).unwrap(); - crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); - let corner = app.ui.transform.as_ref().unwrap().quad[1]; - app.run("view.newGuide", json!({"orientation": "vertical", "position": corner[0] + 20.0})).unwrap(); - app.run("view.newGuide", json!({"orientation": "horizontal", "position": corner[1] - 10.0})).unwrap(); - let ctrl = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; - move_corner(&mut app, 1, [0.0, 0.0], [corner[0] + 18.0, corner[1] - 8.0], ctrl, ctrl); - assert!(app.prefs_rt.snap.as_ref().unwrap().disabled); - assert!(app.prefs_rt.snap_lines.is_empty()); - let q = app.ui.transform.as_ref().unwrap().quad; - assert_eq!(q[0][1], q[1][1], "editable type still scales, rather than distorting"); - } - - #[test] - fn a_foldover_constraint_never_claims_a_guide_alignment() { - let mut app = app_with_corner_guides("edit.transform.distort"); - app.run("view.newGuide", json!({"orientation": "horizontal", "position": 100})).unwrap(); - let before = app.ui.transform.as_ref().unwrap().quad; - move_corner(&mut app, 0, [4.0, 3.0], [108.0, 98.0], egui::Modifiers::NONE, egui::Modifiers::NONE); - let q = app.ui.transform.as_ref().unwrap().quad; - assert_ne!(q[0], [110.0, 100.0], "the guide intersection would fold the quad"); - assert_eq!([q[1], q[2], q[3]], [before[1], before[2], before[3]]); - for i in 0..4 { - let (a, b, c) = (q[i], q[(i + 1) % 4], q[(i + 2) % 4]); - assert!((b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) > 0.0, "still convex: {q:?}"); - } - assert!(app.prefs_rt.snap_lines.is_empty(), "{:?}", app.prefs_rt.snap_lines); - } - - #[test] - fn a_snapped_distort_commits_one_undoable_transform() { - let mut app = app_with_corner_guides("edit.transform.distort"); - let before_doc = app.session.active().unwrap().doc.clone(); - let before_bounds = mover_bounds(&app); - let past = app.session.active().unwrap().history.past_len(); - move_corner(&mut app, 1, [4.0, 3.0], [108.0, 32.0], egui::Modifiers::NONE, egui::Modifiers::NONE); - assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &before_doc), "preview does not edit the document"); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 112.0, y: 35.0 }, egui::Modifiers::NONE); - crate::transform_tool::commit(&mut app); - assert!(!app.ui.status_error, "{}", app.ui.status); - let after_bounds = mover_bounds(&app); - assert_ne!(after_bounds, before_bounds); - assert_eq!(app.session.active().unwrap().history.past_len(), past + 1); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(mover_bounds(&app), before_bounds); - app.run("edit.redo", json!({})).unwrap(); - assert_eq!(mover_bounds(&app), after_bounds); - } - - #[test] - fn transform_corner_press_is_not_adjusted_near_an_original_guide() { - for menu in ["edit.transform.distort", "edit.freeTransform"] { - let mut app = app_with_corner_guides(menu); - app.run("view.newGuide", json!({"orientation": "vertical", "position": 95})).unwrap(); - app.run("view.newGuide", json!({"orientation": "horizontal", "position": 45})).unwrap(); - let raw = ToolEvent::Down { x: 94.0, y: 43.0, pressure: 1.0 }; - let ToolEvent::Down { x, y, .. } = filter_event(&mut app, raw, egui::Modifiers::NONE) else { panic!("still a press") }; - assert_eq!([x, y], [94.0, 43.0], "{menu}: filtering must preserve the handle press"); - } - } - - #[test] - fn corner_near_original_guides_keeps_the_raw_press_in_the_canvas_path() { - for (menu, m) in - [("edit.transform.distort", egui::Modifiers::NONE), ("edit.freeTransform", egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE })] - { - let mut app = app_with_corner_guides(menu); - app.run("view.newGuide", json!({"orientation": "vertical", "position": 95})).unwrap(); - app.run("view.newGuide", json!({"orientation": "horizontal", "position": 45})).unwrap(); - let before = app.ui.transform.as_ref().unwrap().quad; - // The command modifier is added after Down, including in Free Transform. - move_corner(&mut app, 1, [4.0, 3.0], [93.0, 43.0], egui::Modifiers::NONE, m); - let q = app.ui.transform.as_ref().unwrap().quad; - assert_eq!(q[1], [95.0, 45.0], "{menu}"); - assert_eq!([q[0], q[2], q[3]], [before[0], before[2], before[3]]); - } - } - - #[test] - fn corner_distortion_does_not_snap_to_guides_hidden_by_view_flags() { - for menu in ["edit.transform.distort", "edit.freeTransform"] { - for hide_extras in [false, true] { - let mut app = app_with_corner_guides(menu); - if hide_extras { - app.ui.view.extras = false; - } else { - app.ui.view.show.canvas_guides = false; - } - let m = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; - move_corner(&mut app, 1, [4.0, 3.0], [108.0, 32.0], m, m); - assert_eq!(app.ui.transform.as_ref().unwrap().quad[1], [108.0, 32.0], "{menu}, hide Extras: {hide_extras}"); - assert!(app.prefs_rt.snap_lines.is_empty()); - } - } - } - - #[test] - fn marquee_and_corner_snapping_share_the_canvas_guide_visibility() { - for (extras, canvas_guides, shown) in [(true, true, true), (false, true, false), (true, false, false)] { - let mut app = app_with_box(); - app.run("view.newGuide", json!({"orientation": "vertical", "position": 110})).unwrap(); - app.run("view.newGuide", json!({"orientation": "horizontal", "position": 30})).unwrap(); - app.ui.tool = Tool::RectMarquee; - // Isolate guides: the mover's y=40 edge would otherwise be a valid fallback target. - app.ui.view.snap_to.layers = false; - app.ui.view.snap_to.document_bounds = false; - app.ui.view.snap_to.grid = false; - app.ui.view.extras = extras; - app.ui.view.show.canvas_guides = canvas_guides; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 12.0, y: 12.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 108.0, y: 32.0 }, m); - let rect = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); - assert_eq!((rect.x0, rect.y0), (12, 12)); - assert_eq!((rect.x1, rect.y1), if shown { (110, 30) } else { (108, 32) }, "Extras: {extras}, Canvas Guides: {canvas_guides}"); - } - } - - #[test] - fn distort_corner_does_not_snap_to_layer_edges() { - let mut app = app_with_box(); - let ctx = egui::Context::default(); - crate::menus::invoke(&mut app, &ctx, "edit.transform.distort", json!({})).unwrap(); - let q = app.ui.transform.as_ref().unwrap().quad; - let m = egui::Modifiers::NONE; - // Drag the top-right corner to 2 px short of the target's right edge (x = 350). - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[1][0], y: q[1][1], pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 348.0, y: q[1][1] }, m); - let q = app.ui.transform.as_ref().unwrap().quad; - assert_eq!(q[1][0], 348.0, "the corner stays where it was dropped"); - assert!(app.prefs_rt.snap_lines.is_empty()); - } - - #[test] - fn free_transform_drags_and_handles_snap() { - let mut app = app_with_box(); - let ctx = egui::Context::default(); - crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); - assert!(app.ui.transform.is_some()); - let m = egui::Modifiers::NONE; - // Drag from inside the box (40..90 × 40..80) so its left edge lands 2 px from x = 300. - // (Away from the centre, which holds the reference point.) - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 50.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 312.0, y: 50.0 }, m); - let q = app.ui.transform.as_ref().unwrap().quad; - assert!((q[0][0] - 300.0).abs() < 1e-6, "{q:?}"); - // The right-edge handle snaps to the target's right edge (x = 350). - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[1][0], y: (q[1][1] + q[2][1]) / 2.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 353.0, y: 60.0 }, m); - let q = app.ui.transform.as_ref().unwrap().quad; - assert!((q[1][0] - 350.0).abs() < 1e-6, "{q:?}"); - crate::transform_tool::commit(&mut app); - assert_eq!(mover_bounds(&app).x0, 300); - } - - /// #5751: a Rectangle drawn on a 1080 px canvas, then resized with Free Transform under the - /// Move tool. With Snap Vector Tools and Transforms to Pixel Grid on (the default) the box's - /// edges stay on whole pixels: the grab offset and a proportional scale used to leave them at - /// 20.6 and 1040.4. Off, the box follows the pointer exactly. - #[test] - fn free_transform_of_a_shape_keeps_whole_pixels() { - for grid in [true, false] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 1080, "height": 1080, "resolution": 72})).unwrap(); - app.run("prefs.set", json!({"path": "tools.snapVectorToolsAndTransformsToPixelGrid", "value": grid})).unwrap(); - app.sync_views(); - app.ui.views[0].zoom = 0.6; - app.ui.views[0].fit_pending = false; - app.ui.tool = Tool::Rectangle; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 40.0, y: 31.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 300.0, y: 700.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 481.0, y: 1000.0 }, m); - app.ui.tool = Tool::Move; - crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); - let whole = |q: [[f64; 2]; 4]| q.iter().flatten().all(|v| v.fract() == 0.0); - // The left edge handle, grabbed 1.3 px inside, dropped away from any snap target. - let q = app.ui.transform.as_ref().unwrap().quad; - let mid_y = (q[0][1] + q[3][1]) / 2.0; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[0][0] + 1.3, y: mid_y, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 60.0, y: mid_y, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 80.6, y: mid_y }, m); - let q = app.ui.transform.as_ref().unwrap().quad; - assert_eq!(whole(q), grid, "grid {grid}: left edge {q:?}"); - // The bottom-right corner scaled proportionally (the default), off any snap target. - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[2][0], y: q[2][1], pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 450.4, y: 900.1 }, m); - let q = app.ui.transform.as_ref().unwrap().quad; - assert_eq!(whole(q), grid, "grid {grid}: corner {q:?}"); - crate::transform_tool::commit(&mut app); - let st = app.session.active().unwrap(); - let photocraft_doc::LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("a shape layer") }; - let (x0, y0, x1, y1) = sh.path.control_bounds().unwrap(); - if grid { - for v in [x0, y0, x1, y1] { - assert!((v - v.round()).abs() < 1e-6, "committed shape {:?}", (x0, y0, x1, y1)); - } - } - } - } - - #[test] - fn guides_snap_to_layer_edges() { - let mut app = app_with_box(); - assert_eq!(snap_guide(&mut app, true, 297.0), 300.0); - assert_eq!(snap_guide(&mut app, false, 150.0), 150.0, "document centre"); - assert_eq!(snap_guide(&mut app, false, 170.0), 170.0); - // Dragging an existing guide with the Move tool while a selection is active still snaps to the selection. - app.run("view.newGuide", json!({"orientation": "vertical", "position": 10})).unwrap(); - app.run("select.rect", json!({"x": 100, "y": 100, "width": 50, "height": 40})).unwrap(); - app.ui.tool = Tool::Move; - begin(&mut app, [10.0, 50.0], egui::Modifiers::NONE); - assert_eq!(apply(&mut app, [98.0, 50.0], egui::Modifiers::NONE)[0], 100.0); - app.ui.extras.snap = false; - assert_eq!(snap_guide(&mut app, true, 297.0), 297.0); - } - - /// The cached ruler-guide targets follow the Snap To options, not just document edits. - #[test] - fn guide_targets_follow_snap_to_options() { - let mut app = app_with_box(); - app.run( - "prefs.set", - json!({"values": {"guidesGridAndSlices.gridlineEvery": 100, "guidesGridAndSlices.gridUnit": "pixels", "guidesGridAndSlices.subdivisions": 4}}), - ) - .unwrap(); - app.ui.extras.grid = false; - assert_eq!(snap_guide(&mut app, true, 23.0), 23.0, "grid hidden"); - app.ui.extras.grid = true; - app.ui.view.snap_to.grid = true; - assert_eq!(snap_guide(&mut app, true, 23.0), 25.0, "grid shown"); - app.ui.extras.grid = false; - app.ui.view.snap_to.layers = false; - assert_eq!(snap_guide(&mut app, true, 297.0), 297.0, "Snap To Layers off"); - } - - #[test] - fn percentage_grid_snaps_at_separate_axis_intervals() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 1280, "height": 720})).unwrap(); - app.ui.extras.grid = true; - app.ui.view.snap_to.grid = true; - app.run( - "prefs.set", - json!({"values": {"guidesGridAndSlices.gridlineEvery": 20, "guidesGridAndSlices.gridUnit": "percent", "guidesGridAndSlices.subdivisions": 2}}), - ) - .unwrap(); - let opts = options(&app); - assert_eq!(opts.grid_step, [128.0, 72.0]); - let targets = SnapTargets::from_document(&app.session.active().unwrap().doc, &opts, &[]); - assert_eq!(targets.snap_point([127.0, 71.0], 2.0).0, [128.0, 72.0]); - } - - #[test] - fn grid_snapping_uses_preferences() { - let mut app = app_with_box(); - app.ui.extras.grid = true; - app.run( - "prefs.set", - json!({"values": {"guidesGridAndSlices.gridlineEvery": 100, "guidesGridAndSlices.gridUnit": "pixels", "guidesGridAndSlices.subdivisions": 4}}), - ) - .unwrap(); - assert_eq!(options(&app).grid_step, [25.0; 2]); - app.ui.tool = Tool::RectMarquee; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 152.0, y: 127.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 199.0, y: 176.0 }, m); - let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); - assert_eq!((sel.x0, sel.y0, sel.x1, sel.y1), (150, 125, 200, 175)); - } -} +mod tests; diff --git a/crates/ui-egui/src/snap_ui/tests.rs b/crates/ui-egui/src/snap_ui/tests.rs new file mode 100644 index 0000000000..8f763efc12 --- /dev/null +++ b/crates/ui-egui/src/snap_ui/tests.rs @@ -0,0 +1,757 @@ +use super::*; +use serde_json::json; + +fn app_with_box() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + // Two boxes: a target at (300..350, 200..260) and the moving one at (40..90, 40..80). + app.run("layer.new.layer", json!({"name": "target"})).unwrap(); + app.run("select.rect", json!({"x": 300, "y": 200, "width": 50, "height": 60})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("layer.new.layer", json!({"name": "mover"})).unwrap(); + app.run("select.rect", json!({"x": 40, "y": 40, "width": 50, "height": 40})).unwrap(); + app.run("edit.fill", json!({"color": "#0000ff"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app +} + +/// #7538: moving selected pixels snaps (and frames) the pixels, not a loose marquee round them. +/// Snapping starts before the press cuts them, so the cut retargets it to their outline. +#[test] +fn moving_selected_pixels_snaps_their_bounds_not_the_marquee() { + for alt in [false, true] { + let mut app = app_with_box(); + app.ui.tool = Tool::Move; + app.run("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + let m = egui::Modifiers { alt, ..Default::default() }; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); + assert_eq!(gesture, Some(Gesture::Move { rect: [40.0, 40.0, 90.0, 80.0] }), "alt {alt}: the blue box, not the marquee"); + // 263 px right puts the box's left edge 3 px from the target's (the marquee's 20 px off). + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 323.0, y: 100.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); + app.run("select.drop", json!({})).unwrap(); + let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds().x0); + assert_eq!(sel, Some(300), "alt {alt}: snapped to the target's edge"); + } + // A marquee's ⌘-drag cuts them the same way. + let mut app = app_with_box(); + app.ui.tool = Tool::RectMarquee; + app.run("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + let cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, cmd); + let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); + assert_eq!(gesture, Some(Gesture::SelectionMove { rect: [40.0, 40.0, 90.0, 80.0] }), "⌘-drag with the marquee"); + // The Background has no transparency to shrink to. + let mut app = app_with_box(); + app.ui.tool = Tool::Move; + app.run("layer.select", json!({"name": "Background"})).unwrap(); + app.run("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, egui::Modifiers::NONE); + let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); + assert_eq!(gesture, Some(Gesture::Move { rect: [20.0, 20.0, 120.0, 110.0] }), "the Background"); +} + +fn mover_bounds(app: &PhotocraftApp) -> photocraft_geom::Rect { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds() +} + +#[test] +fn drawing_a_new_crop_snaps_its_corner_not_the_default_frame() { + // In both crop modes: the default mode draws a new box inside the untouched frame too. + for (classic, snap, end) in [(true, false, [300.0, 220.0]), (true, true, [294.0, 217.0]), (false, false, [300.0, 220.0]), (false, true, [294.0, 217.0])] + { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 640, "height": 480, "background": "white"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [100, 80, 200, 140], "fill": "#d59b40"})).unwrap(); + app.sync_views(); + app.ppp = 2.0; + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + app.ui.tool = Tool::Crop; + app.ui.tool_options.crop_shield.classic_mode = classic; + app.ui.extras.snap = snap; + app.ui.view.show.smart_guides = true; + crate::crop_ui::ensure_frame(&mut app); + let view = app.ui.views[0].clone(); + let history = app.session.active().unwrap().history.past_len(); + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 80.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: end[0], y: end[1], pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: end[0], y: end[1] }, m); + // Smart Guides must not snap the old canvas-sized frame as if it were moving. + // With View Snap on, the new corner still snaps to the nearby shape's edges. + assert_eq!(app.ui.crop_rect, Some([100.0, 80.0, 300.0, 220.0]), "Classic Mode: {classic}, View Snap: {snap}"); + // The default mode's Auto Center Preview re-centres the drawn box; Classic Mode keeps the view. + if classic { + assert_eq!(app.ui.views[0], view); + } + assert_eq!(app.session.active().unwrap().history.past_len(), history); + } +} + +#[test] +fn move_tool_snaps_to_other_layer_edges_with_smart_guides() { + let mut app = app_with_box(); + app.ui.tool = Tool::Move; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + // Drag so the mover's left edge lands 3 px right of the target's (x = 303). + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 323.0, y: 100.0, pressure: 1.0 }, m); + assert!(app.prefs_rt.snap_lines.iter().any(|l| l.vertical && l.pos == 300.0 && l.kind.is_smart()), "{:?}", app.prefs_rt.snap_lines); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); + assert_eq!(mover_bounds(&app).x0, 300); + assert!(app.prefs_rt.snap.is_none()); +} + +/// Puppet Warp's pins go where they are dragged: they don't snap, with View › Snap on or +/// off, whatever tool was active when it started. With the Move tool a pin drag took the +/// layer move's Smart Guides and jumped to the other layer's edges. +#[test] +fn puppet_warp_pins_never_snap() { + for (tool, snap) in [(Tool::Move, false), (Tool::Move, true), (Tool::RectMarquee, true), (Tool::Brush, false)] { + let mut app = app_with_box(); + app.ui.tool = tool; + app.ui.extras.snap = snap; + app.ui.view.show.smart_guides = true; + app.run("view.newGuide", json!({"orientation": "vertical", "position": 321})).unwrap(); + let ctx = egui::Context::default(); + crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + // The mover's left edge 3 px right of the target's, the pin 2 px from the guide. + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 323.0, y: 100.0, pressure: 1.0 }, m); + assert!(app.prefs_rt.snap_lines.is_empty(), "{tool:?}, snap {snap}: {:?}", app.prefs_rt.snap_lines); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); + let pins = &app.distort.puppet.as_ref().unwrap().warp.pins; + assert_eq!(pins.iter().map(|p| p.dst).collect::>(), vec![[323.0, 100.0]], "{tool:?}, snap {snap}"); + } +} + +/// ⌘ turns a painting tool, or a marquee outside the selection, into the Move tool for the +/// drag: it gets the Move tool's box and smart-guide snapping, not the selected tool's. +#[test] +fn command_drag_temporary_move_snaps_like_the_move_tool() { + for tool in [Tool::Brush, Tool::RectMarquee] { + let mut app = app_with_box(); + app.ui.tool = tool; + let cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, cmd); + let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); + assert_eq!(gesture, Some(Gesture::Move { rect: [40.0, 40.0, 90.0, 80.0] }), "{tool:?}: the mover's box"); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, cmd); + assert_eq!(mover_bounds(&app).x0, 300, "{tool:?}: snapped to the target's edge"); + } +} + +/// The drag's box and snapping belong to the layer Auto-Select picks on the press, not to the +/// one selected before: another layer (its box would move instead), or an empty layer (no box, +/// no snapping at all). +#[test] +fn move_tool_box_and_snapping_follow_the_auto_selected_layer() { + for before in ["target", "empty"] { + let mut app = app_with_box(); + let mover = app.session.active().unwrap().active_layer.unwrap(); + if before == "empty" { + app.run("layer.new.layer", json!({"name": "empty"})).unwrap(); + } else { + let st = app.session.active().unwrap(); + let target = st.doc.walk().into_iter().find(|(_, _, l)| l.name == "target").unwrap().2.id; + app.run("layer.select", json!({"layer": target.0})).unwrap(); + } + app.ui.tool = Tool::Move; + app.ui.tool_options.move_auto_select = true; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + assert_eq!(app.session.active().unwrap().active_layer, Some(mover), "{before}: Auto-Select picked the mover"); + let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); + assert_eq!(gesture, Some(Gesture::Move { rect: [40.0, 40.0, 90.0, 80.0] }), "{before}: the box is the mover's"); + // The mover's left edge lands 3 px right of the target's and snaps to it. + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 323.0, y: 100.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); + assert_eq!(mover_bounds(&app).x0, 300, "{before}: snapped to the target's edge"); + } +} + +#[test] +fn view_snap_off_blocks_smart_guide_snapping() { + let mut app = app_with_box(); + app.ui.tool = Tool::Move; + app.ui.view.show.smart_guides = true; + app.ui.extras.snap = false; + app.ui.tool_options.move_auto_select = false; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); + assert_eq!(mover_bounds(&app).x0, 303, "View › Snap off must not snap via smart guides"); +} + +#[test] +fn ctrl_or_snap_off_disables_snapping() { + let mut app = app_with_box(); + app.ui.tool = Tool::Move; + app.ui.view.show.smart_guides = false; + app.ui.extras.snap = false; + // The presses land beside the moved layer: keep moving it (no Auto-Select pick). + app.ui.tool_options.move_auto_select = false; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); + assert_eq!(mover_bounds(&app).x0, 303); + app.ui.extras.snap = true; + let ctrl = egui::Modifiers { ctrl: true, ..Default::default() }; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 62.0, y: 60.0 }, ctrl); + assert_eq!(mover_bounds(&app).x0, 305, "no snap to the target's right edge at 350? (moved freely)"); + // Ctrl only at the press (Ctrl-click auto-select) doesn't turn snapping off for the drag. + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, ctrl); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 61.0, y: 60.0, pressure: 1.0 }, m); + assert!(!app.prefs_rt.snap.as_ref().is_some_and(|s| s.disabled)); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 61.0, y: 60.0 }, m); + // ⌘ on the Mac is not the override. + let cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; + assert!(!override_held(cmd) && override_held(ctrl)); +} + +#[test] +fn snap_off_disables_all_snapping_even_with_smart_guides() { + let mut app = app_with_box(); + app.ui.tool = Tool::Move; + assert!(app.ui.view.show.smart_guides); + app.ui.extras.snap = false; + app.ui.tool_options.move_auto_select = false; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 323.0, y: 100.0 }, m); + assert_eq!(mover_bounds(&app).x0, 303); + assert!(app.prefs_rt.snap_lines.is_empty()); +} + +#[test] +fn marquee_corner_snaps_to_guides_and_document_edges() { + let mut app = app_with_box(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 120})).unwrap(); + app.ui.tool = Tool::RectMarquee; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 3.0, y: 2.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 116.0, y: 50.0 }, m); + let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + assert_eq!((sel.x0, sel.y0, sel.x1), (0, 0, 120)); + // Zoomed in to 800%, 4 px is beyond the 1 px threshold: no snap. + app.ui.views[0].zoom = 8.0; + // (Deselect first: a drag starting inside the selection would move it.) + app.run("select.deselect", json!({})).unwrap(); + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 116.0, y: 50.0 }, m); + let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + assert_eq!(sel.x1, 116); +} + +/// Space while drawing a marquee, Object Selection box or shape moves it: its edges snap, not +/// only the corner under the pointer; with Space released the corner snaps again. +#[test] +fn drawing_repositioned_with_space_snaps_its_edges() { + for tool in [Tool::RectMarquee, Tool::EllipseMarquee, Tool::ObjectSelection, Tool::Rectangle, Tool::Line] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + app.run("view.newGuide", json!({"orientation": "vertical", "position": 220})).unwrap(); + app.ui.tool = tool; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 150.0, y: 140.0, pressure: 1.0 }, m); + // Space down: the 50 × 40 box moves so its left edge lands 4 px short of the guide; + // the pointer corner (x = 266) is near nothing. + app.drag.as_mut().unwrap().reposition = true; + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 266.0, y: 140.0, pressure: 1.0 }, m); + assert_eq!(app.drag.as_ref().unwrap().start, [220.0, 100.0], "{tool:?}"); + if tool != Tool::RectMarquee { + continue; + } + // Space up: sizing resumes and the corner snaps to the document's right edge. + app.drag.as_mut().unwrap().reposition = false; + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 397.0, y: 140.0 }, m); + let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + assert_eq!((sel.x0, sel.y0, sel.x1, sel.y1), (220, 100, 400, 140)); + } +} + +/// Dragging inside a selection with a marquee or lasso moves the outline (⌘ cuts the pixels +/// into a floating piece): its bounds snap, not the pointer. +#[test] +fn selection_drag_snaps_the_selection_bounds() { + for (tool, cut) in [(Tool::RectMarquee, false), (Tool::Lasso, false), (Tool::RectMarquee, true)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].fit_pending = false; + app.run("view.newGuide", json!({"orientation": "vertical", "position": 220})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 50, "height": 40})).unwrap(); + app.ui.tool = tool; + let m = if cut { egui::Modifiers { mac_cmd: true, command: true, ..Default::default() } } else { egui::Modifiers::NONE }; + // The outline's right edge lands 2 px short of the guide (x = 218); the pointer ends + // 7 px from the document centre (x = 200), which it must not snap to. + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 125.0, y: 117.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 193.0, y: 117.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 193.0, y: 117.0 }, m); + let st = app.session.active().unwrap(); + let off = photocraft_engine::float_cmds::floating(st).map_or((0, 0), |f| f.offset); + let sel = st.doc.selection.as_ref().unwrap().content_bounds().translate(off.0, off.1); + assert_eq!((sel.x0, sel.y0, sel.x1, sel.y1), (170, 100, 220, 140), "{tool:?} cut: {cut}"); + } +} + +#[test] +fn distort_corner_snaps_from_positive_grab_offset() { + distort_corner_snaps_from_grab_offset([4.0, 3.0]); +} + +#[test] +fn distort_corner_snaps_from_negative_grab_offset() { + distort_corner_snaps_from_grab_offset([-4.0, -3.0]); +} + +fn distort_corner_snaps_from_grab_offset(offset: [f64; 2]) { + let mut app = app_with_box(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 110})).unwrap(); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 30})).unwrap(); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "edit.transform.distort", json!({})).unwrap(); + let before = app.ui.transform.as_ref().unwrap().quad; + let press = [before[1][0] + offset[0], before[1][1] + offset[1]]; + // The proposed corner is (108, 32); the pointer keeps its original grab offset. + let release = [108.0 + offset[0], 32.0 + offset[1]]; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: press[0], y: press[1], pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: release[0], y: release[1], pressure: 1.0 }, m); + let moved = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(moved[1], [110.0, 30.0], "grab offset {offset:?}"); + assert_eq!([moved[0], moved[2], moved[3]], [before[0], before[2], before[3]]); + assert!(app.prefs_rt.snap_lines.iter().any(|l| l.vertical && l.pos == 110.0 && l.kind == SnapKind::Guide)); + assert!(app.prefs_rt.snap_lines.iter().any(|l| !l.vertical && l.pos == 30.0 && l.kind == SnapKind::Guide)); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: release[0], y: release[1] }, m); + assert_eq!(app.ui.transform.as_ref().unwrap().quad, moved); + assert!(app.prefs_rt.snap.is_none() && app.prefs_rt.snap_lines.is_empty()); +} + +fn app_with_corner_guides(menu: &str) -> PhotocraftApp { + let mut app = app_with_box(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 110})).unwrap(); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 30})).unwrap(); + crate::menus::invoke(&mut app, &egui::Context::default(), menu, json!({})).unwrap(); + app +} + +fn move_corner(app: &mut PhotocraftApp, index: usize, offset: [f64; 2], end: [f64; 2], down: egui::Modifiers, moving: egui::Modifiers) { + let corner = app.ui.transform.as_ref().unwrap().quad[index]; + crate::canvas::tool_event(app, ToolEvent::Down { x: corner[0] + offset[0], y: corner[1] + offset[1], pressure: 1.0 }, down); + crate::canvas::tool_event(app, ToolEvent::Move { x: end[0] + offset[0], y: end[1] + offset[1], pressure: 1.0 }, moving); +} + +#[test] +fn distort_corner_respects_guide_axes_tolerance_and_toggles() { + for (snap, shown, guides, end, expected) in [ + (true, true, true, [108.0, 20.0], [110.0, 20.0]), + (true, true, true, [100.0, 32.0], [100.0, 30.0]), + (true, true, true, [100.0, 20.0], [100.0, 20.0]), + (false, true, true, [108.0, 32.0], [108.0, 32.0]), + (true, false, true, [108.0, 32.0], [108.0, 32.0]), + (true, true, false, [108.0, 32.0], [108.0, 32.0]), + ] { + let mut app = app_with_corner_guides("edit.transform.distort"); + app.ui.extras.snap = snap; + app.ui.extras.guides = shown; + app.ui.view.snap_to.guides = guides; + move_corner(&mut app, 1, [4.0, 3.0], end, egui::Modifiers::NONE, egui::Modifiers::NONE); + assert_eq!(app.ui.transform.as_ref().unwrap().quad[1], expected, "Snap: {snap}, shown: {shown}, guides: {guides}, proposed: {end:?}"); + assert!(app.prefs_rt.snap_lines.iter().all(|line| (if line.vertical { expected[0] } else { expected[1] } - line.pos).abs() < 1e-6)); + } +} + +#[test] +fn free_transform_command_corner_snaps_with_the_real_grab_offset() { + let windows = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; + let mac = egui::Modifiers { command: true, mac_cmd: true, ..egui::Modifiers::NONE }; + for m in [windows, mac] { + for offset in [[4.0, 3.0], [-4.0, -3.0], [0.0, 0.0]] { + for down in [m, egui::Modifiers::NONE] { + let mut app = app_with_corner_guides("edit.freeTransform"); + let before = app.ui.transform.as_ref().unwrap().quad; + move_corner(&mut app, 1, offset, [108.0, 32.0], down, m); + let moved = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(moved[1], [110.0, 30.0], "{m:?}, press {down:?}, offset {offset:?}"); + assert_eq!([moved[0], moved[2], moved[3]], [before[0], before[2], before[3]]); + assert_eq!(app.prefs_rt.snap_lines.len(), 2); + assert!(!app.prefs_rt.snap.as_ref().unwrap().disabled); + } + } + } +} + +#[test] +fn control_alone_still_disables_snapping_in_menu_distort() { + let mut app = app_with_corner_guides("edit.transform.distort"); + let ctrl = egui::Modifiers { ctrl: true, ..egui::Modifiers::NONE }; + move_corner(&mut app, 1, [4.0, 3.0], [108.0, 32.0], ctrl, ctrl); + assert_eq!(app.ui.transform.as_ref().unwrap().quad[1], [108.0, 32.0]); + assert!(app.prefs_rt.snap.as_ref().unwrap().disabled); + assert!(app.prefs_rt.snap_lines.is_empty()); +} + +#[test] +fn skew_control_corner_keeps_its_axis_instead_of_snapping_as_distort() { + let ctrl = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; + for legacy in [false, true] { + for (menu, expected, snapping) in [ + ("edit.transform.skew", [[40.0, 40.0], [108.0, 40.0], [90.0, 80.0], [40.0, 80.0]], false), + ("edit.transform.distort", [[40.0, 40.0], [110.0, 30.0], [90.0, 80.0], [40.0, 80.0]], true), + ("edit.transform.perspective", [[22.0, 40.0], [108.0, 40.0], [90.0, 80.0], [40.0, 80.0]], false), + ] { + let mut app = app_with_corner_guides(menu); + app.run("prefs.set", json!({"path": "general.useLegacyFreeTransform", "value": legacy})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let past = app.session.active().unwrap().history.past_len(); + let prefs = serde_json::to_value(app.session.prefs()).unwrap(); + // Ctrl arrives after the raw, off-centre press, as on the actual canvas path. + move_corner(&mut app, 1, [4.0, 3.0], [108.0, 32.0], egui::Modifiers::NONE, ctrl); + assert_eq!(app.ui.transform.as_ref().unwrap().quad, expected, "{menu}, legacy {legacy}"); + assert_eq!(!app.prefs_rt.snap.as_ref().unwrap().disabled, snapping, "{menu}"); + assert_eq!(app.prefs_rt.snap_lines.len(), if snapping { 2 } else { 0 }, "{menu}"); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 112.0, y: 35.0 }, ctrl); + assert_eq!(app.ui.transform.as_ref().unwrap().quad, expected, "release preserves {menu}"); + crate::transform_tool::cancel(&mut app); + assert!(app.ui.transform.is_none() && app.prefs_rt.snap.is_none() && app.prefs_rt.snap_lines.is_empty()); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &doc), "cancel preserves {menu}'s document"); + assert_eq!(app.session.active().unwrap().history.past_len(), past, "cancel preserves {menu}'s history"); + assert_eq!(serde_json::to_value(app.session.prefs()).unwrap(), prefs, "{menu} does not change preferences"); + } + } +} + +#[test] +fn skew_control_corner_on_editable_type_slides_the_whole_edge() { + let ctrl = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; + for legacy in [false, true] { + let mut app = app_with_box(); + app.run("type.create", json!({"x": 40, "y": 60, "text": "Hello"})).unwrap(); + app.run("prefs.set", json!({"path": "general.useLegacyFreeTransform", "value": legacy})).unwrap(); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.transform.skew", json!({})).unwrap(); + let before = app.ui.transform.as_ref().unwrap().quad; + let end = [before[1][0] + 18.0, before[1][1] - 8.0]; + let doc = app.session.active().unwrap().doc.clone(); + let past = app.session.active().unwrap().history.past_len(); + move_corner(&mut app, 1, [2.0, 1.0], end, egui::Modifiers::NONE, ctrl); + let mut expected = before; + expected[0][0] += 18.0; + expected[1][0] += 18.0; + assert_eq!(app.ui.transform.as_ref().unwrap().quad, expected, "type remains affine, legacy {legacy}"); + assert!(app.prefs_rt.snap.as_ref().unwrap().disabled && app.prefs_rt.snap_lines.is_empty()); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: end[0] + 2.0, y: end[1] + 1.0 }, ctrl); + assert_eq!(app.ui.transform.as_ref().unwrap().quad, expected, "release preserves the type's edge"); + crate::transform_tool::cancel(&mut app); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), past); + } +} + +#[test] +fn transform_non_distortion_gestures_keep_control_snap_override() { + let ctrl = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; + let perspective = egui::Modifiers { alt: true, shift: true, ..ctrl }; + for (menu, press, m) in [ + ("edit.freeTransform", [65.0, 40.0], ctrl), // edge + ("edit.freeTransform", [65.0, 60.0], ctrl), // pivot + ("edit.freeTransform", [55.0, 52.0], ctrl), // inside + ("edit.freeTransform", [90.0, 40.0], perspective), + ("edit.transform.perspective", [90.0, 40.0], ctrl), + ("edit.transform.warp", [90.0, 40.0], ctrl), + ("edit.contentAwareScale", [90.0, 40.0], ctrl), + ] { + let mut app = app_with_corner_guides(menu); + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: press[0], y: press[1], pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 108.0, y: 32.0, pressure: 1.0 }, m); + assert!(app.prefs_rt.snap.as_ref().unwrap().disabled, "{menu}, {press:?}, {m:?}"); + assert!(app.prefs_rt.snap_lines.is_empty(), "{menu}, {press:?}"); + } +} + +#[test] +fn editable_type_refusal_keeps_control_snap_override() { + let mut app = app_with_box(); + app.run("type.create", json!({"x": 40, "y": 60, "text": "Hello"})).unwrap(); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let corner = app.ui.transform.as_ref().unwrap().quad[1]; + app.run("view.newGuide", json!({"orientation": "vertical", "position": corner[0] + 20.0})).unwrap(); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": corner[1] - 10.0})).unwrap(); + let ctrl = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; + move_corner(&mut app, 1, [0.0, 0.0], [corner[0] + 18.0, corner[1] - 8.0], ctrl, ctrl); + assert!(app.prefs_rt.snap.as_ref().unwrap().disabled); + assert!(app.prefs_rt.snap_lines.is_empty()); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(q[0][1], q[1][1], "editable type still scales, rather than distorting"); +} + +#[test] +fn a_foldover_constraint_never_claims_a_guide_alignment() { + let mut app = app_with_corner_guides("edit.transform.distort"); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 100})).unwrap(); + let before = app.ui.transform.as_ref().unwrap().quad; + move_corner(&mut app, 0, [4.0, 3.0], [108.0, 98.0], egui::Modifiers::NONE, egui::Modifiers::NONE); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_ne!(q[0], [110.0, 100.0], "the guide intersection would fold the quad"); + assert_eq!([q[1], q[2], q[3]], [before[1], before[2], before[3]]); + for i in 0..4 { + let (a, b, c) = (q[i], q[(i + 1) % 4], q[(i + 2) % 4]); + assert!((b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) > 0.0, "still convex: {q:?}"); + } + assert!(app.prefs_rt.snap_lines.is_empty(), "{:?}", app.prefs_rt.snap_lines); +} + +#[test] +fn a_snapped_distort_commits_one_undoable_transform() { + let mut app = app_with_corner_guides("edit.transform.distort"); + let before_doc = app.session.active().unwrap().doc.clone(); + let before_bounds = mover_bounds(&app); + let past = app.session.active().unwrap().history.past_len(); + move_corner(&mut app, 1, [4.0, 3.0], [108.0, 32.0], egui::Modifiers::NONE, egui::Modifiers::NONE); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &before_doc), "preview does not edit the document"); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 112.0, y: 35.0 }, egui::Modifiers::NONE); + crate::transform_tool::commit(&mut app); + assert!(!app.ui.status_error, "{}", app.ui.status); + let after_bounds = mover_bounds(&app); + assert_ne!(after_bounds, before_bounds); + assert_eq!(app.session.active().unwrap().history.past_len(), past + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(mover_bounds(&app), before_bounds); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(mover_bounds(&app), after_bounds); +} + +#[test] +fn transform_corner_press_is_not_adjusted_near_an_original_guide() { + for menu in ["edit.transform.distort", "edit.freeTransform"] { + let mut app = app_with_corner_guides(menu); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 95})).unwrap(); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 45})).unwrap(); + let raw = ToolEvent::Down { x: 94.0, y: 43.0, pressure: 1.0 }; + let ToolEvent::Down { x, y, .. } = filter_event(&mut app, raw, egui::Modifiers::NONE) else { panic!("still a press") }; + assert_eq!([x, y], [94.0, 43.0], "{menu}: filtering must preserve the handle press"); + } +} + +#[test] +fn corner_near_original_guides_keeps_the_raw_press_in_the_canvas_path() { + for (menu, m) in + [("edit.transform.distort", egui::Modifiers::NONE), ("edit.freeTransform", egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE })] + { + let mut app = app_with_corner_guides(menu); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 95})).unwrap(); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 45})).unwrap(); + let before = app.ui.transform.as_ref().unwrap().quad; + // The command modifier is added after Down, including in Free Transform. + move_corner(&mut app, 1, [4.0, 3.0], [93.0, 43.0], egui::Modifiers::NONE, m); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(q[1], [95.0, 45.0], "{menu}"); + assert_eq!([q[0], q[2], q[3]], [before[0], before[2], before[3]]); + } +} + +#[test] +fn corner_distortion_does_not_snap_to_guides_hidden_by_view_flags() { + for menu in ["edit.transform.distort", "edit.freeTransform"] { + for hide_extras in [false, true] { + let mut app = app_with_corner_guides(menu); + if hide_extras { + app.ui.view.extras = false; + } else { + app.ui.view.show.canvas_guides = false; + } + let m = egui::Modifiers { command: true, ctrl: true, ..egui::Modifiers::NONE }; + move_corner(&mut app, 1, [4.0, 3.0], [108.0, 32.0], m, m); + assert_eq!(app.ui.transform.as_ref().unwrap().quad[1], [108.0, 32.0], "{menu}, hide Extras: {hide_extras}"); + assert!(app.prefs_rt.snap_lines.is_empty()); + } + } +} + +#[test] +fn marquee_and_corner_snapping_share_the_canvas_guide_visibility() { + for (extras, canvas_guides, shown) in [(true, true, true), (false, true, false), (true, false, false)] { + let mut app = app_with_box(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 110})).unwrap(); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 30})).unwrap(); + app.ui.tool = Tool::RectMarquee; + // Isolate guides: the mover's y=40 edge would otherwise be a valid fallback target. + app.ui.view.snap_to.layers = false; + app.ui.view.snap_to.document_bounds = false; + app.ui.view.snap_to.grid = false; + app.ui.view.extras = extras; + app.ui.view.show.canvas_guides = canvas_guides; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 12.0, y: 12.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 108.0, y: 32.0 }, m); + let rect = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + assert_eq!((rect.x0, rect.y0), (12, 12)); + assert_eq!((rect.x1, rect.y1), if shown { (110, 30) } else { (108, 32) }, "Extras: {extras}, Canvas Guides: {canvas_guides}"); + } +} + +#[test] +fn distort_corner_does_not_snap_to_layer_edges() { + let mut app = app_with_box(); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "edit.transform.distort", json!({})).unwrap(); + let q = app.ui.transform.as_ref().unwrap().quad; + let m = egui::Modifiers::NONE; + // Drag the top-right corner to 2 px short of the target's right edge (x = 350). + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[1][0], y: q[1][1], pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 348.0, y: q[1][1] }, m); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(q[1][0], 348.0, "the corner stays where it was dropped"); + assert!(app.prefs_rt.snap_lines.is_empty()); +} + +#[test] +fn free_transform_drags_and_handles_snap() { + let mut app = app_with_box(); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + assert!(app.ui.transform.is_some()); + let m = egui::Modifiers::NONE; + // Drag from inside the box (40..90 × 40..80) so its left edge lands 2 px from x = 300. + // (Away from the centre, which holds the reference point.) + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 50.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 312.0, y: 50.0 }, m); + let q = app.ui.transform.as_ref().unwrap().quad; + assert!((q[0][0] - 300.0).abs() < 1e-6, "{q:?}"); + // The right-edge handle snaps to the target's right edge (x = 350). + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[1][0], y: (q[1][1] + q[2][1]) / 2.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 353.0, y: 60.0 }, m); + let q = app.ui.transform.as_ref().unwrap().quad; + assert!((q[1][0] - 350.0).abs() < 1e-6, "{q:?}"); + crate::transform_tool::commit(&mut app); + assert_eq!(mover_bounds(&app).x0, 300); +} + +/// #5751: a Rectangle drawn on a 1080 px canvas, then resized with Free Transform under the +/// Move tool. With Snap Vector Tools and Transforms to Pixel Grid on (the default) the box's +/// edges stay on whole pixels: the grab offset and a proportional scale used to leave them at +/// 20.6 and 1040.4. Off, the box follows the pointer exactly. +#[test] +fn free_transform_of_a_shape_keeps_whole_pixels() { + for grid in [true, false] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 1080, "height": 1080, "resolution": 72})).unwrap(); + app.run("prefs.set", json!({"path": "tools.snapVectorToolsAndTransformsToPixelGrid", "value": grid})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = 0.6; + app.ui.views[0].fit_pending = false; + app.ui.tool = Tool::Rectangle; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 40.0, y: 31.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 300.0, y: 700.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 481.0, y: 1000.0 }, m); + app.ui.tool = Tool::Move; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let whole = |q: [[f64; 2]; 4]| q.iter().flatten().all(|v| v.fract() == 0.0); + // The left edge handle, grabbed 1.3 px inside, dropped away from any snap target. + let q = app.ui.transform.as_ref().unwrap().quad; + let mid_y = (q[0][1] + q[3][1]) / 2.0; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[0][0] + 1.3, y: mid_y, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 60.0, y: mid_y, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 80.6, y: mid_y }, m); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(whole(q), grid, "grid {grid}: left edge {q:?}"); + // The bottom-right corner scaled proportionally (the default), off any snap target. + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: q[2][0], y: q[2][1], pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 450.4, y: 900.1 }, m); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(whole(q), grid, "grid {grid}: corner {q:?}"); + crate::transform_tool::commit(&mut app); + let st = app.session.active().unwrap(); + let photocraft_doc::LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("a shape layer") }; + let (x0, y0, x1, y1) = sh.path.control_bounds().unwrap(); + if grid { + for v in [x0, y0, x1, y1] { + assert!((v - v.round()).abs() < 1e-6, "committed shape {:?}", (x0, y0, x1, y1)); + } + } + } +} + +#[test] +fn guides_snap_to_layer_edges() { + let mut app = app_with_box(); + assert_eq!(snap_guide(&mut app, true, 297.0), 300.0); + assert_eq!(snap_guide(&mut app, false, 150.0), 150.0, "document centre"); + assert_eq!(snap_guide(&mut app, false, 170.0), 170.0); + // Dragging an existing guide with the Move tool while a selection is active still snaps to the selection. + app.run("view.newGuide", json!({"orientation": "vertical", "position": 10})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 50, "height": 40})).unwrap(); + app.ui.tool = Tool::Move; + begin(&mut app, [10.0, 50.0], egui::Modifiers::NONE); + assert_eq!(apply(&mut app, [98.0, 50.0], egui::Modifiers::NONE)[0], 100.0); + app.ui.extras.snap = false; + assert_eq!(snap_guide(&mut app, true, 297.0), 297.0); +} + +/// The cached ruler-guide targets follow the Snap To options, not just document edits. +#[test] +fn guide_targets_follow_snap_to_options() { + let mut app = app_with_box(); + app.run( + "prefs.set", + json!({"values": {"guidesGridAndSlices.gridlineEvery": 100, "guidesGridAndSlices.gridUnit": "pixels", "guidesGridAndSlices.subdivisions": 4}}), + ) + .unwrap(); + app.ui.extras.grid = false; + assert_eq!(snap_guide(&mut app, true, 23.0), 23.0, "grid hidden"); + app.ui.extras.grid = true; + app.ui.view.snap_to.grid = true; + assert_eq!(snap_guide(&mut app, true, 23.0), 25.0, "grid shown"); + app.ui.extras.grid = false; + app.ui.view.snap_to.layers = false; + assert_eq!(snap_guide(&mut app, true, 297.0), 297.0, "Snap To Layers off"); +} + +#[test] +fn percentage_grid_snaps_at_separate_axis_intervals() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 1280, "height": 720})).unwrap(); + app.ui.extras.grid = true; + app.ui.view.snap_to.grid = true; + app.run( + "prefs.set", + json!({"values": {"guidesGridAndSlices.gridlineEvery": 20, "guidesGridAndSlices.gridUnit": "percent", "guidesGridAndSlices.subdivisions": 2}}), + ) + .unwrap(); + let opts = options(&app); + assert_eq!(opts.grid_step, [128.0, 72.0]); + let targets = SnapTargets::from_document(&app.session.active().unwrap().doc, &opts, &[]); + assert_eq!(targets.snap_point([127.0, 71.0], 2.0).0, [128.0, 72.0]); +} + +#[test] +fn grid_snapping_uses_preferences() { + let mut app = app_with_box(); + app.ui.extras.grid = true; + app.run( + "prefs.set", + json!({"values": {"guidesGridAndSlices.gridlineEvery": 100, "guidesGridAndSlices.gridUnit": "pixels", "guidesGridAndSlices.subdivisions": 4}}), + ) + .unwrap(); + assert_eq!(options(&app).grid_step, [25.0; 2]); + app.ui.tool = Tool::RectMarquee; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 152.0, y: 127.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 199.0, y: 176.0 }, m); + let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + assert_eq!((sel.x0, sel.y0, sel.x1, sel.y1), (150, 125, 200, 175)); +} From b714980037ee1873526ab21b6711bf8e0f6b9121 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:30 +0000 Subject: [PATCH 052/259] refactor(ui-egui): move vector_ui.rs tests to vector_ui/tests.rs --- crates/ui-egui/src/vector_ui.rs | 1350 +------------------------ crates/ui-egui/src/vector_ui/tests.rs | 1347 ++++++++++++++++++++++++ 2 files changed, 1348 insertions(+), 1349 deletions(-) create mode 100644 crates/ui-egui/src/vector_ui/tests.rs diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index e139a80163..36755732ad 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -2016,1355 +2016,7 @@ pub fn paths_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } #[cfg(test)] -mod tests { - use super::*; - - /// #4084: zoomed in, a curve's chords stay within a fraction of a pixel of the true curve - /// (16 fixed chords showed corners), and a straight segment stays one chord. - #[test] - fn path_curves_stay_smooth_at_any_zoom() { - let (p0, c0, c1, p1) = ([0.0, 100.0], [20.0, -60.0], [80.0, -60.0], [100.0, 100.0]); - for zoom in [0.25, 1.0, 8.0, 64.0, 320.0] { - let xf = move |q: [f64; 2]| pos2((q[0] * zoom) as f32 + 10.0, (q[1] * zoom) as f32 - 5.0); - let pts = curve_points(p0, c0, c1, p1, &xf); - let n = pts.len() - 1; - assert_eq!((pts[0], pts[n]), (xf(p0), xf(p1)), "the ends are the anchors"); - for (k, w) in pts.windows(2).enumerate() { - let curve = xf(bezier(p0, c0, c1, p1, (k as f64 + 0.5) / n as f64)); - let chord = w[0] + (w[1] - w[0]) * 0.5; - assert!((chord - curve).length() <= 0.35, "zoom {zoom}: chord {k} of {n} is {} px off", (chord - curve).length()); - } - // Zoomed out it stays cheap. - if zoom <= 1.0 { - assert!(n <= 32, "zoom {zoom}: {n} chords"); - } - } - let xf = |q: [f64; 2]| pos2((q[0] * 320.0) as f32, (q[1] * 320.0) as f32); - // Retracted handles, and handles along the line: one chord. - assert_eq!(curve_points([0.0, 0.0], [0.0, 0.0], [50.0, 50.0], [50.0, 50.0], &xf).len(), 2); - assert_eq!(curve_points([0.0, 0.0], [10.0, 10.0], [40.0, 40.0], [50.0, 50.0], &xf).len(), 2); - // A handle past the end is a curve that doubles back, not a line. - assert!(curve_points([0.0, 0.0], [0.0, 0.0], [80.0, 80.0], [50.0, 50.0], &xf).len() > 2); - // Hostile coordinates: no panic, a bounded number of points. - for bad in [f64::NAN, f64::INFINITY, 1e300] { - assert!(curve_points([0.0, 0.0], [bad, 0.0], [0.0, bad], [1.0, 1.0], &xf).len() <= MAX_CURVE_PIECES + 1); - } - // Through path_lines too: a closed subpath of two curved segments. - let mut path = Path::default(); - path.subpaths.push(photocraft_doc::vector::Subpath { - knots: vec![ - photocraft_doc::vector::Knot { - anchor: photocraft_geom::Point::new(0.0, 0.0), - in_ctrl: photocraft_geom::Point::new(0.0, 40.0), - out_ctrl: photocraft_geom::Point::new(0.0, -40.0), - smooth: true, - }, - photocraft_doc::vector::Knot { - anchor: photocraft_geom::Point::new(60.0, 0.0), - in_ctrl: photocraft_geom::Point::new(60.0, -40.0), - out_ctrl: photocraft_geom::Point::new(60.0, 40.0), - smooth: true, - }, - ], - closed: true, - ..Default::default() - }); - let lines = path_lines(&path, &xf); - assert!(lines[0].1 && lines[0].0.len() > 2 * 17, "zoomed in, more than the old 16 chords per segment: {}", lines[0].0.len()); - } - - #[test] - fn all_shape_tools_and_open_pen_use_the_complete_stroke_defaults() { - for tool in [Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line, Tool::CustomShape] { - let mut a = app(); - a.ui.tool_options.stroke_width = 5.0; - a.ui.tool_options.shape_stroke = crate::shape_stroke_ui::StrokeOptions { - cap: photocraft_doc::LineCap::Square, - join: photocraft_doc::LineJoin::Bevel, - dashes: vec![4.0, 2.0, 1.0, 3.0], - dash_offset: -0.5, - opacity: 0.4, - ..Default::default() - }; - let history = a.session.active().unwrap().history.past_len(); - finish_shape(&mut a, tool, [20.0, 20.0], [120.0, 100.0], Default::default()); - let info = a.run("shape.info", json!({})).unwrap(); - assert_eq!(info["stroke"]["dashes"], json!([4.0, 2.0, 1.0, 3.0])); - assert_eq!(info["stroke"]["cap"], "square"); - assert_eq!(info["stroke"]["width"], 5.0); - assert_eq!(a.session.active().unwrap().history.past_len(), history + 1); - a.run("edit.undo", json!({})).unwrap(); - a.run("edit.redo", json!({})).unwrap(); - assert_eq!(a.run("shape.info", json!({})).unwrap(), info); - a.ui.tool_options.vector_mode = "shape".into(); - a.ui.pen = Some(PenPath { knots: vec![[[30.0, 40.0]; 3], [[80.0, 40.0]; 3]], ..Default::default() }); - pen_commit(&mut a, false); - let open = a.run("shape.info", json!({})).unwrap(); - assert_eq!(open["stroke"]["dashes"], info["stroke"]["dashes"]); - assert_eq!(open["path"]["subpaths"][0]["closed"], false); - } - } - - fn app() -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - app.sync_views(); - app - } - - #[test] - fn paths_context_menu_uses_the_clicked_row_and_dispatches_commands() { - let mut app = app(); - let path = json!({"subpaths": [{"closed": true, "knots": [ - {"anchor": [10, 10], "in": [10, 10], "out": [10, 10]}, - {"anchor": [80, 10], "in": [80, 10], "out": [80, 10]}, - {"anchor": [80, 80], "in": [80, 80], "out": [80, 80]} - ]}]}); - app.run("path.set", json!({"name": "First", "path": path})).unwrap(); - app.run("path.set", json!({"name": "Second", "path": path})).unwrap(); - let doc = &app.session.active().unwrap().doc; - let first = path_rows(doc, None).into_iter().find(|r| r.name == "First").unwrap(); - let entries = path_context_actions(&first, doc, None); - assert_eq!(entries[0].1, "path.toSelection"); - assert_eq!(entries[0].2["name"], "First"); - assert!(entries.iter().all(|(_, id, _)| photocraft_engine::commands::find(id).is_some())); - let (_, id, params) = entries.into_iter().find(|(_, id, _)| *id == "path.toSelection").unwrap(); - app.run(id, params).unwrap(); - assert!(app.session.active().unwrap().doc.selection.is_some()); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("path.toSelection")); - - app.run("path.set", json!({"name": "First copy 1", "path": path})).unwrap(); - let doc = &app.session.active().unwrap().doc; - let first = path_rows(doc, None).into_iter().find(|r| r.name == "First").unwrap(); - let (_, _, duplicate) = path_context_actions(&first, doc, None).into_iter().find(|(_, id, _)| *id == "path.set").unwrap(); - assert_eq!(duplicate["name"], "First copy 2", "duplicate must not overwrite an existing path"); - } - - #[test] - fn work_path_context_save_and_layer_path_deletion_rules() { - let mut app = app(); - let path = json!({"subpaths": []}); - app.run("path.set", json!({"name": "work", "path": path})).unwrap(); - let doc = &app.session.active().unwrap().doc; - let work = path_rows(doc, None).into_iter().find(|r| r.kind == PathRow::Work).unwrap(); - let entries = path_context_actions(&work, doc, None); - assert!(entries.iter().any(|(_, id, _)| *id == "path.rename")); - assert!(!entries.iter().any(|(_, id, _)| *id == "path.set")); - let layer = PathEntry { kind: PathRow::Layer, ..work }; - let entries = path_context_actions(&layer, doc, None); - assert!(!entries.iter().any(|(_, id, _)| *id == "path.delete")); - } - - /// #6552: a shape layer's " Shape Path" row offers Delete Path, and it deletes the - /// shape layer, as Photoshop's Delete Path does (measured: one "Delete Layer" step). - #[test] - fn shape_path_row_delete_path_deletes_the_shape_layer() { - let mut app = app(); - app.run("shape.create", json!({"kind": "ellipse", "rect": [20, 20, 100, 70]})).unwrap(); - let st = app.session.active().unwrap(); - let (doc, shape) = (st.doc.clone(), st.active_layer); - let layers = doc.layers.len(); - let row = path_rows(&doc, shape).into_iter().find(|r| r.kind == PathRow::Layer).unwrap(); - assert!(row.name.ends_with(" Shape Path"), "{}", row.name); - let (_, id, params) = - path_context_actions(&row, &doc, shape).into_iter().find(|(label, _, _)| *label == "Delete Path").expect("Delete Path is offered"); - app.run(id, params).unwrap(); - let doc = &app.session.active().unwrap().doc; - assert_eq!(doc.layers.len(), layers - 1); - assert!(shape.and_then(|id| doc.layer(id)).is_none(), "the shape layer is gone"); - app.run("edit.undo", json!({})).unwrap(); - assert!(shape.and_then(|id| app.session.active().unwrap().doc.layer(id)).is_some(), "one undo step brings it back"); - } - - /// #6238: double-clicking a saved path's name renames it in place, and double-clicking the - /// Work Path saves it under the name typed (it used to save it as "Path N" straight away). - #[test] - fn double_clicking_a_path_name_renames_it_in_place() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = app(); - let path = json!({"subpaths": [{"closed": true, "knots": [ - {"anchor": [10, 10], "in": [10, 10], "out": [10, 10]}, - {"anchor": [80, 10], "in": [80, 10], "out": [80, 10]}, - {"anchor": [80, 80], "in": [80, 80], "out": [80, 80]} - ]}]}); - app.run("path.set", json!({"name": "First", "path": path})).unwrap(); - app.run("path.set", json!({"name": "work", "path": path})).unwrap(); - // 60 fps steps, so two clicks a frame apart count as a double-click. - let mut h = Harness::builder().with_size(vec2(320.0, 260.0)).with_step_dt(1.0 / 60.0).build_ui_state(|ui, app| paths_panel(app, ui), app); - h.run_steps(3); - let rename = |h: &mut Harness<'_, PhotocraftApp>, row: &str, text: &str| { - let name = h.get_by_label(row).rect().left_center() + vec2(60.0, 0.0); - h.event(egui::Event::PointerMoved(name)); - h.run_steps(30); - for pressed in [true, false, true, false] { - h.event(egui::Event::PointerButton { pos: name, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); - h.step(); - } - h.run_steps(3); - h.event(egui::Event::Text(text.into())); - h.run_steps(1); - h.key_press(egui::Key::Enter); - h.run_steps(3); - }; - let names = |h: &Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().doc.paths.iter().map(|p| p.name.clone()).collect::>(); - rename(&mut h, "First", "Outline"); - assert_eq!(names(&h), ["Outline"]); - assert!(h.state().session.active().unwrap().doc.work_path.is_some(), "renaming a saved path leaves the work path alone"); - rename(&mut h, "Work Path", "Circle"); - assert_eq!(names(&h), ["Outline", "Circle"]); - assert!(h.state().session.active().unwrap().doc.work_path.is_none()); - assert_eq!(h.state().ui.selected_path.as_deref(), Some("Circle")); - } - - /// #6238: a saved path's context menu offers Rename Path…, as the Layers panel's does. - #[test] - fn saved_path_context_menu_offers_rename() { - let mut app = app(); - app.run("path.set", json!({"name": "First", "path": {"subpaths": []}})).unwrap(); - app.run("path.set", json!({"name": "work", "path": {"subpaths": []}})).unwrap(); - let doc = &app.session.active().unwrap().doc; - let rename = |kind| { - let entry = path_rows(doc, None).into_iter().find(|r| r.kind == kind).unwrap(); - path_context_actions(&entry, doc, None).into_iter().find(|(label, _, _)| *label == "Rename Path…").map(|(_, id, p)| (id, p)) - }; - assert_eq!(rename(PathRow::Saved), Some(("path.rename", json!({"name": "First"})))); - assert_eq!(rename(PathRow::Work), None, "the work path is saved, not renamed"); - } - - /// How many shapes the path overlay paints for `app` this frame. - fn overlay_shapes(app: &PhotocraftApp, ctx: &egui::Context) -> usize { - let doc = app.session.active().unwrap().doc.clone(); - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { - let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 400.0)); - let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); - let xf = ViewXform { rect, zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; - draw_overlay(app, &painter, &xf, &doc); - }); - out.textures_delta.clear(); - out.shapes.len() - } - - #[test] - fn pen_keeps_anchors_of_a_finished_path() { - // #6884: a path finished with Enter, or by closing it, lost its anchor squares while the - // Pen stayed active, so it looked gone and could not be edited. - let ctx = egui::Context::default(); - let mut app = app(); - app.ui.tool = Tool::Pen; - let knots = vec![[[10.0, 10.0]; 3], [[80.0, 10.0]; 3], [[80.0, 80.0]; 3]]; - app.ui.pen = Some(PenPath { knots, ..Default::default() }); - pen_commit(&mut app, true); - assert!(app.ui.pen.is_none()); - assert!(app.session.active().unwrap().doc.work_path.is_some()); - let with_pen = overlay_shapes(&app, &ctx); - app.ui.tool = Tool::Brush; - let outline_only = overlay_shapes(&app, &ctx); - assert!(outline_only > 0, "the outline is drawn with any tool"); - // Each of the three anchors adds its square (fill and stroke). - assert!(with_pen >= outline_only + 3, "Pen draws the anchors: {with_pen} vs {outline_only}"); - for tool in [Tool::Pen, Tool::FreeformPen, Tool::CurvaturePen, Tool::PathSelection] { - assert!(shows_anchors(tool), "{tool:?}"); - } - assert!(!shows_anchors(Tool::Brush) && !shows_anchors(Tool::Move)); - } - - #[test] - fn an_unselected_work_path_is_not_drawn_over_the_canvas() { - // #6551: Ctrl-click Load as Selection leaves the Paths panel's selection alone, yet the Work - // Path stayed drawn over the new selection's edge. Photoshop draws it only while selected - // in the Paths panel (or a path tool is active). - let ctx = egui::Context::default(); - let mut app = app(); - let path = json!({"subpaths": [{"closed": true, "knots": [ - {"anchor": [20, 20], "in": [20, 20], "out": [20, 20]}, - {"anchor": [90, 20], "in": [90, 20], "out": [90, 20]}, - {"anchor": [90, 90], "in": [90, 90], "out": [90, 90]} - ]}]}); - app.run("path.set", json!({"name": "work", "path": path})).unwrap(); - app.run("path.toSelection", json!({"name": "work", "mode": "replace"})).unwrap(); - assert!(app.ui.selected_path.is_none()); - for tool in [Tool::Move, Tool::Brush, Tool::Rectangle, Tool::Zoom] { - app.ui.tool = tool; - assert_eq!(overlay_shapes(&app, &ctx), 0, "{tool:?}: an unselected Work Path stays off the canvas"); - } - // Selected in the Paths panel: drawn with any tool. - app.ui.selected_path = Some("work".into()); - for tool in [Tool::Move, Tool::Brush] { - app.ui.tool = tool; - assert!(overlay_shapes(&app, &ctx) > 0, "{tool:?}: the selected Work Path is drawn"); - } - // Another path selected: the Work Path is not the target path. - app.ui.selected_path = Some("Saved".into()); - app.ui.tool = Tool::Move; - assert_eq!(overlay_shapes(&app, &ctx), 0); - // A path tool shows the Work Path it edits even when the panel selection was cleared. - app.ui.selected_path = None; - for tool in [Tool::Pen, Tool::PathSelection] { - app.ui.tool = tool; - assert!(overlay_shapes(&app, &ctx) > 0, "{tool:?}: path tools draw the Work Path"); - } - } - - #[test] - fn show_target_path_and_extras_hide_the_path_outlines() { - // #1119: View › Show › Target Path only flipped its checkmark; the canvas kept drawing the - // work path and the active shape's path. - let ctx = egui::Context::default(); - let mut app = app(); - let path = json!({"subpaths": [{"closed": true, "knots": [ - {"anchor": [10, 10], "in": [10, 10], "out": [10, 10]}, - {"anchor": [80, 10], "in": [80, 10], "out": [80, 10]}, - {"anchor": [80, 80], "in": [80, 80], "out": [80, 80]} - ]}]}); - app.run("path.set", json!({"path": path})).unwrap(); - assert!(app.session.active().unwrap().doc.work_path.is_some()); - finish_shape(&mut app, Tool::Rectangle, [100.0, 100.0], [160.0, 150.0], egui::Modifiers::NONE); - let toggle = |app: &mut PhotocraftApp, id: &str| crate::menus::invoke(app, &ctx, id, Value::Null).unwrap(); - for tool in [Tool::Pen, Tool::PathSelection, Tool::DirectSelection, Tool::Rectangle] { - app.ui.tool = tool; - assert!(app.ui.view.show.target_path && app.ui.view.extras); - assert!(overlay_shapes(&app, &ctx) > 0, "{tool:?}: the paths are drawn by default"); - toggle(&mut app, "view.show.targetPath"); - assert!(!app.ui.view.show.target_path); - assert_eq!(overlay_shapes(&app, &ctx), 0, "{tool:?}: Target Path off"); - toggle(&mut app, "view.show.targetPath"); - toggle(&mut app, "view.extras"); - assert!(!app.ui.view.extras); - assert_eq!(overlay_shapes(&app, &ctx), 0, "{tool:?}: Extras off"); - toggle(&mut app, "view.extras"); - assert!(overlay_shapes(&app, &ctx) > 0, "{tool:?}: shown again"); - } - // The Pen's path in progress is a gesture, not the target path: it stays visible. - app.ui.tool = Tool::Pen; - app.ui.pen = Some(PenPath { knots: vec![[[20.0, 20.0]; 3], [[60.0, 40.0]; 3]], ..Default::default() }); - toggle(&mut app, "view.show.targetPath"); - assert!(overlay_shapes(&app, &ctx) > 0, "the pen path in progress is still drawn"); - } - - #[test] - fn the_saved_path_selected_in_the_paths_panel_is_drawn() { - // #6550: selecting a saved path in the Paths panel drew nothing on the canvas. - let ctx = egui::Context::default(); - let mut app = app(); - let tri = |o: f64| { - json!({"subpaths": [{"closed": true, "knots": [ - {"anchor": [20.0 + o, 20], "in": [20.0 + o, 20], "out": [20.0 + o, 20]}, - {"anchor": [90.0 + o, 20], "in": [90.0 + o, 20], "out": [90.0 + o, 20]}, - {"anchor": [90.0 + o, 90], "in": [90.0 + o, 90], "out": [90.0 + o, 90]} - ]}]}) - }; - app.run("path.set", json!({"name": "Path 1", "path": tri(0.0)})).unwrap(); - app.run("path.set", json!({"name": "Path 2", "path": tri(10.0)})).unwrap(); - assert!(app.session.active().unwrap().doc.work_path.is_none()); - for tool in [Tool::Move, Tool::Brush, Tool::Pen, Tool::PathSelection, Tool::DirectSelection] { - app.ui.tool = tool; - app.ui.selected_path = None; - assert_eq!(overlay_shapes(&app, &ctx), 0, "{tool:?}: nothing selected, nothing drawn"); - app.ui.selected_path = Some("Path 1".into()); - assert_eq!(selected_saved_path(&app).map(|p| p.subpaths[0].knots[0].anchor.x), Some(20.0)); - assert!(overlay_shapes(&app, &ctx) > 0, "{tool:?}: the selected saved path is drawn"); - app.ui.selected_path = Some("Path 2".into()); - assert_eq!(selected_saved_path(&app).map(|p| p.subpaths[0].knots[0].anchor.x), Some(30.0)); - app.ui.selected_path = Some("Gone".into()); - assert_eq!(overlay_shapes(&app, &ctx), 0, "{tool:?}: a missing path draws nothing"); - app.ui.selected_path = Some("Path 1".into()); - app.ui.view.show.target_path = false; - assert_eq!(overlay_shapes(&app, &ctx), 0, "{tool:?}: View > Show > Target Path off"); - app.ui.view.show.target_path = true; - } - // Path Selection (and the Pen tools, as for the work path) add anchor squares. - app.ui.tool = Tool::Move; - let plain = overlay_shapes(&app, &ctx); - app.ui.tool = Tool::PathSelection; - assert!(overlay_shapes(&app, &ctx) > plain); - app.ui.tool = Tool::Pen; - assert!(overlay_shapes(&app, &ctx) > plain); - } - - #[test] - fn shape_drag_creates_layers_with_modifiers() { - let mut app = app(); - finish_shape(&mut app, Tool::Rectangle, [10.0, 10.0], [60.0, 30.0], egui::Modifiers::SHIFT); - let st = app.session.active().unwrap(); - let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); - assert_eq!((b.width(), b.height()), (50, 50), "shift = square"); - finish_shape(&mut app, Tool::EllipseShape, [100.0, 100.0], [120.0, 110.0], egui::Modifiers::ALT); - let st = app.session.active().unwrap(); - let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); - assert!(b.x0.abs_diff(80) <= 1 && b.width().abs_diff(40) <= 1, "alt = from centre: {b:?}"); - finish_shape(&mut app, Tool::Line, [10.0, 150.0], [90.0, 152.0], egui::Modifiers::SHIFT); - assert_eq!(app.session.active().unwrap().doc.layers.len(), 4); - } - - #[test] - fn shift_pressed_during_a_shape_drag_constrains_it() { - // #668: ⇧ only counted when held at the press; Photoshop constrains when it is pressed - // mid-drag (and stops when it is released). - use crate::canvas::{ToolEvent, tool_event}; - for (tool, sides) in [(Tool::Polygon, 6), (Tool::Rectangle, 4), (Tool::EllipseShape, 0)] { - let mut app = app(); - app.ui.tool = tool; - app.ui.tool_options.polygon_sides = 6; - let none = egui::Modifiers::NONE; - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, none); - tool_event(&mut app, ToolEvent::Move { x: 40.0, y: 30.0, pressure: 1.0 }, none); - tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::SHIFT); - tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 40.0 }, egui::Modifiers::SHIFT); - let st = app.session.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); - assert!(matches!(l.content, LayerContent::Shape(_)), "{tool:?} ({sides} sides): a shape layer"); - let b = l.surface().unwrap().content_bounds(); - // The drag is 60 × 30; constrained, the shape's box is 60 × 60 (a hexagon is narrower - // than its box, so the height tells). - assert!(b.height().abs_diff(60) <= 1 && b.width() <= 61, "{tool:?}: ⇧ mid-drag keeps proportions: {b:?}"); - } - } - - #[test] - fn shape_preview_is_the_committed_path() { - let mut app = app(); - app.ui.tool_options.corner_radius = 8.0; - let preview = |app: &PhotocraftApp, tool, end| { - shape_geometry(&app.ui.tool_options, tool, [10.0, 10.0], end, egui::Modifiers::ALT) - .and_then(|p| photocraft_engine::vector_cmds::shape_path(&p).ok()) - }; - for tool in [Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line] { - let shown = preview(&app, tool, [60.0, 30.0]).unwrap(); - finish_shape(&mut app, tool, [10.0, 10.0], [60.0, 30.0], egui::Modifiers::ALT); - let st = app.session.active().unwrap(); - let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("{tool:?}: no shape layer") }; - assert_eq!(sh.path, shown, "{tool:?}"); - } - assert!(preview(&app, Tool::Rectangle, [10.2, 40.0]).is_none(), "too thin to draw"); - assert!(photocraft_engine::vector_cmds::shape_path(&json!({"kind": "nope", "rect": [0, 0, 5, 5]})).is_err()); - assert!(photocraft_engine::vector_cmds::shape_path(&json!({"kind": "rect"})).is_err()); - } - - #[test] - fn pen_shows_the_close_cue_only_over_the_first_anchor_of_a_real_segment() { - let mut app = app(); - app.ui.tool = Tool::Pen; - pen_down(&mut app, 20.0, 20.0, false); - pen_up(&mut app); - let one = app.ui.pen.clone().unwrap(); - assert!(!over_first_anchor(&one, [20.0, 20.0], 6.0), "a single anchor has nothing to close"); - pen_down(&mut app, 120.0, 20.0, false); - pen_up(&mut app); - let two = app.ui.pen.clone().unwrap(); - assert!(over_first_anchor(&two, [22.0, 21.0], 6.0)); - assert!(!over_first_anchor(&two, [60.0, 60.0], 6.0)); - } - - #[test] - fn pen_builds_and_closes_a_work_path() { - let mut app = app(); - app.ui.tool = Tool::Pen; - for (x, y) in [(20.0, 20.0), (120.0, 20.0)] { - pen_down(&mut app, x, y, false); - pen_up(&mut app); - } - pen_down(&mut app, 120.0, 120.0, false); - pen_move(&mut app, 140.0, 140.0, false); // smooth knot - pen_up(&mut app); - pen_down(&mut app, 20.5, 20.5, false); // click the first anchor: close - pen_up(&mut app); - assert!(app.ui.pen.is_none()); - let wp = app.session.active().unwrap().doc.work_path.clone().unwrap(); - assert!(wp.subpaths[0].closed && wp.subpaths[0].knots.len() == 3); - assert!(wp.subpaths[0].knots[2].smooth); - // Path Selection moves it. - path_selection_finish(&mut app, [50.0, 50.0], [60.0, 55.0]); - let wp = app.session.active().unwrap().doc.work_path.clone().unwrap(); - assert_eq!((wp.subpaths[0].knots[0].anchor.x, wp.subpaths[0].knots[0].anchor.y), (30.0, 25.0)); - } - - fn close(a: [f64; 2], b: [f64; 2]) -> bool { - (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9 - } - - #[test] - fn pen_shift_click_puts_the_next_anchor_on_a_45_degree_ray() { - let mut app = app(); - app.ui.tool = Tool::Pen; - // The first anchor has nothing to constrain against: it lands where clicked. - pen_down(&mut app, 20.0, 20.0, true); - pen_up(&mut app); - assert_eq!(app.ui.pen.as_ref().unwrap().knots[0][0], [20.0, 20.0]); - // ~30° below horizontal snaps to the 45° diagonal at the pointer's projection. - let (dx, dy) = (100.0 * 30f64.to_radians().cos(), 100.0 * 30f64.to_radians().sin()); - pen_down(&mut app, 20.0 + dx, 20.0 + dy, true); - pen_up(&mut app); - let k = app.ui.pen.as_ref().unwrap().knots[1]; - let t = 100.0 * 15f64.to_radians().cos() / std::f64::consts::SQRT_2; - assert!(close(k[0], [20.0 + t, 20.0 + t]), "{:?}", k[0]); - assert!(k[1] == k[0] && k[2] == k[0], "a click stays a corner"); - // ~10° off vertical snaps to straight down from the previous anchor. - let prev = k[0]; - pen_down(&mut app, prev[0] + 8.0, prev[1] + 50.0, true); - pen_up(&mut app); - assert!(close(app.ui.pen.as_ref().unwrap().knots[2][0], [prev[0], prev[1] + 50.0])); - // Without ⇧ the anchor stays at the pointer. - pen_down(&mut app, 200.0, 190.0, false); - pen_up(&mut app); - assert_eq!(app.ui.pen.as_ref().unwrap().knots[3][0], [200.0, 190.0]); - // ⇧ does not stop a click on the first anchor from closing the path. - pen_down(&mut app, 20.5, 20.5, true); - pen_up(&mut app); - assert!(app.ui.pen.is_none()); - assert!(app.session.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].closed); - } - - #[test] - fn pen_shift_drag_turns_handles_to_45_degrees_live() { - let mut app = app(); - app.ui.tool = Tool::Pen; - pen_down(&mut app, 20.0, 20.0, false); - pen_up(&mut app); - pen_down(&mut app, 100.0, 100.0, false); - // Without ⇧ the handle follows the pointer. - pen_move(&mut app, 130.0, 110.0, false); - assert_eq!(app.ui.pen.as_ref().unwrap().knots[1][2], [130.0, 110.0]); - // Pressing ⇧ mid-drag snaps the handle (~18°) to horizontal; the opposite handle mirrors it. - pen_move(&mut app, 130.0, 110.0, true); - let k = app.ui.pen.as_ref().unwrap().knots[1]; - assert!(close(k[2], [130.0, 100.0]) && close(k[1], [70.0, 100.0]), "{k:?}"); - assert_eq!(k[0], [100.0, 100.0], "the anchor does not move"); - // Releasing ⇧ frees it again. - pen_move(&mut app, 120.0, 140.0, false); - assert_eq!(app.ui.pen.as_ref().unwrap().knots[1][2], [120.0, 140.0]); - // ⌥ breaks the pair; ⇧ then constrains the outgoing handle alone (~63° → 45°). - pen_break_handle(&mut app); - pen_move(&mut app, 120.0, 140.0, true); - let k = app.ui.pen.as_ref().unwrap().knots[1]; - assert!(close(k[2], [130.0, 130.0]), "{k:?}"); - assert_eq!(k[1], [80.0, 60.0], "the incoming handle stays where it was"); - pen_up(&mut app); - // Degenerate: ⇧ with the pointer on the anchor leaves the handle on it. - pen_down(&mut app, 200.0, 100.0, false); - pen_move(&mut app, 200.0, 100.0, true); - let k = app.ui.pen.as_ref().unwrap().knots[2]; - assert!(k.iter().all(|p| *p == [200.0, 100.0]), "{k:?}"); - pen_up(&mut app); - } - - /// #5373: an unfinished path stays with its own document through same-frame switches. - #[test] - fn an_unclosed_path_stays_with_its_document() { - // Both pens claim the document at their first anchor. - let open_path = |app: &mut PhotocraftApp| { - for (x, y) in [(20.0, 20.0), (120.0, 60.0)] { - if app.ui.tool == Tool::CurvaturePen { - curvature_down(app, x, y); - curvature_up(app); - } else { - pen_down(app, x, y, false); - pen_up(app); - } - } - }; - let work = |app: &PhotocraftApp, i: usize| app.session.documents()[i].doc.work_path.clone(); - // File › New commits the path to its original document. - for tool in [Tool::Pen, Tool::CurvaturePen] { - let mut app = app(); - app.ui.tool = tool; - open_path(&mut app); - assert!(app.ui.pen.is_some() && app.ui.pen_doc.is_some(), "{tool:?}: claimed by its document"); - app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); - assert!(app.ui.pen.is_none() && app.ui.pen_doc.is_none(), "{tool:?}: the first document's path is gone"); - assert!(work(&app, 0).is_some(), "{tool:?}: the original keeps its Work Path"); - assert_eq!(work(&app, 1), None, "{tool:?}: the new document is blank"); - } - // Two documents; the path below is drawn on the second (active) one. - let mut app = app(); - app.ui.tool = Tool::Pen; - app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); - open_path(&mut app); - assert!(app.session.set_active(0)); - pen_commit(&mut app, false); - assert!(app.ui.pen.is_none()); - assert!(work(&app, 0).is_none(), "the active document stays untouched"); - assert!(work(&app, 1).is_some(), "the owner keeps its Work Path"); - // Staying on its own document, the path still commits there. - open_path(&mut app); - pen_commit(&mut app, false); - assert!(work(&app, 0).is_some(), "it commits to the document it was drawn on"); - assert!(work(&app, 1).is_some()); - for act in [0, 1, 2] { - open_path(&mut app); - assert!(app.session.set_active(1)); - match act { - 0 => pen_down(&mut app, 50.0, 50.0, false), - 1 => curvature_down(&mut app, 50.0, 50.0), - _ => assert!(!pen_undo_last_point(&mut app), "nothing of this document's to undo"), - } - let knots = app.ui.pen.as_ref().map_or(0, |p| p.knots.len()); - assert!(knots <= 1, "act {act}: a new path, not the other document's (knots {knots})"); - // The two drawing entry points start a path of their own here; undo has none to take. - let expected = if act == 2 { None } else { app.session.active().map(|st| st.doc.id) }; - assert_eq!(app.ui.pen_doc, expected, "act {act}"); - app.ui.pen = None; - app.ui.pen_doc = None; - assert!(app.session.set_active(0)); - } - open_path(&mut app); - let shapes = |app: &PhotocraftApp| { - let ctx = egui::Context::default(); - let doc = app.session.active().unwrap().doc.clone(); - let xf = ViewXform { - rect: egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(400.0, 300.0)), - zoom: 1.0, - center: [100.0, 75.0], - flip: false, - rotation: 0.0, - aspect: 1.0, - }; - let mut out = ctx.run_ui(Default::default(), |ui| draw_overlay(app, ui.painter(), &xf, &doc)); - out.textures_delta.clear(); - out.shapes.len() - }; - // Same view, pen present vs absent: the difference is the path itself, nothing else. - let drawn = |app: &mut PhotocraftApp| { - let with_pen = shapes(app); - let pen = app.ui.pen.take(); - let without = shapes(app); - app.ui.pen = pen; - with_pen - without - }; - assert!(drawn(&mut app) > 0, "its own document draws the path"); - assert!(app.session.set_active(1)); - assert_eq!(drawn(&mut app), 0, "the other document draws nothing of it"); - assert!(app.session.set_active(0)); - app.ui.pen = None; - app.ui.pen_doc = None; - open_path(&mut app); - app.ui.direct_selection.target = Some(crate::direct_select::PathRef::Pen); - app.ui.direct_selection.anchors = vec![[0, 1]]; - app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); - assert_eq!(app.ui.direct_selection, Default::default(), "the anchors went with the path"); - } - - #[test] - fn pen_overlay_uses_the_view_document_even_during_direct_selection() { - let mut app = app(); - app.ui.tool = Tool::Pen; - pen_down(&mut app, 20.0, 20.0, false); - pen_up(&mut app); - pen_down(&mut app, 80.0, 60.0, false); - pen_up(&mut app); - let owner = app.session.active().unwrap().doc.clone(); - app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - let other = app.session.active().unwrap().doc.clone(); - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let shapes = |app: &PhotocraftApp, doc: &Document, modifiers| { - let ctx = egui::Context::default(); - let mut output = ctx.run_ui(egui::RawInput { events: vec![egui::Event::ModifiersChanged(modifiers)], ..Default::default() }, |ui| { - draw_overlay(app, ui.painter(), &xf, doc) - }); - output.textures_delta.clear(); - output.shapes.len() - }; - for active in [0, 1] { - assert!(app.session.set_active(active)); - for tool in [Tool::Pen, Tool::DirectSelection] { - app.ui.tool = tool; - for modifiers in [egui::Modifiers::NONE, egui::Modifiers::COMMAND] { - for (doc, visible) in [(&owner, true), (&other, false)] { - let with_pen = shapes(&app, doc, modifiers); - let pen = app.ui.pen.take(); - let without = shapes(&app, doc, modifiers); - app.ui.pen = pen; - assert_eq!(with_pen > without, visible, "active {active}, {tool:?}, {modifiers:?}"); - } - } - } - } - } - - #[test] - fn failed_stale_pen_commit_preserves_the_draft_until_retry() { - for action in ["pen", "curvature", "undo", "commit", "command"] { - let mut app = app(); - app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[5, 5], [10, 10]]}]}})).unwrap(); - let original = app.session.active().unwrap().doc.work_path.clone().unwrap(); - app.ui.tool = Tool::Pen; - for (x, y) in [(20.0, 20.0), (80.0, 60.0)] { - pen_down(&mut app, x, y, false); - pen_up(&mut app); - } - let draft = app.ui.pen.clone(); - let owner = app.ui.pen_doc; - app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - app.ui.tool_options.vector_mode = "shape".into(); - app.ui.selected_path = Some("foreign named path".into()); - app.session.authorize = Some(|_, _| Err(photocraft_engine::EngineError::Other("test rejection".into()))); - match action { - "pen" => pen_down(&mut app, 150.0, 150.0, false), - "curvature" => curvature_down(&mut app, 150.0, 150.0), - "undo" => assert!(!pen_undo_last_point(&mut app)), - "commit" => pen_commit(&mut app, true), - _ => { - assert!(app.run("file.close", json!({})).is_err()); - } - } - assert_eq!(app.ui.pen, draft, "{action}: failed save retains all anchors"); - assert_eq!(app.ui.pen_doc, owner); - assert_eq!(app.session.active_index(), Some(1)); - assert_eq!(app.session.documents()[0].doc.work_path.as_ref(), Some(&original)); - assert!(app.session.documents()[1].doc.work_path.is_none()); - assert!(app.ui.status_error); - assert!(!crate::direct_select::candidates(&app).iter().any(|(target, _)| *target == crate::direct_select::PathRef::Pen)); - app.session.authorize = None; - app.sync_views(); - assert!(app.ui.pen.is_none()); - assert_eq!(app.session.active_index(), Some(1)); - assert_eq!(app.ui.selected_path.as_deref(), Some("foreign named path")); - let saved = app.session.documents()[0].doc.work_path.clone().unwrap(); - assert_eq!(saved.subpaths.len(), original.subpaths.len() + 1); - assert_eq!(saved.subpaths[0], original.subpaths[0]); - app.sync_views(); - assert_eq!(app.session.documents()[0].doc.work_path.as_ref(), Some(&saved), "retry never duplicates the path"); - assert!(app.session.set_active(0)); - assert!(app.session.undo()); - assert_eq!(app.session.active().unwrap().doc.work_path.as_ref(), Some(&original)); - } - } - - #[test] - fn new_document_reports_a_failed_work_path_save_and_retains_the_draft() { - let mut app = app(); - pen_down(&mut app, 20.0, 20.0, false); - pen_up(&mut app); - pen_down(&mut app, 80.0, 60.0, false); - pen_up(&mut app); - let draft = app.ui.pen.clone(); - app.session.authorize = Some(|id, _| if id == "path.set" { Err(photocraft_engine::EngineError::Other("test rejection".into())) } else { Ok(()) }); - app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); - assert!(app.ui.status_error); - assert!(app.ui.status.contains("test rejection")); - assert_eq!(app.ui.pen, draft); - assert_eq!(app.session.active_index(), Some(1)); - assert!(app.session.documents().iter().all(|d| d.doc.work_path.is_none())); - app.session.authorize = None; - app.sync_views(); - assert!(app.ui.pen.is_none()); - assert!(app.session.documents()[0].doc.work_path.is_some()); - assert!(app.session.documents()[1].doc.work_path.is_none()); - } - - #[test] - fn new_document_preserves_a_single_pen_anchor_as_a_work_path() { - for tool in [Tool::Pen, Tool::CurvaturePen] { - let mut app = app(); - app.ui.tool = tool; - if tool == Tool::Pen { - pen_down(&mut app, 20.0, 30.0, false); - pen_up(&mut app); - } else { - curvature_down(&mut app, 20.0, 30.0); - curvature_up(&mut app); - } - app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); - assert!(app.ui.pen.is_none()); - let path = app.session.documents()[0].doc.work_path.as_ref().unwrap(); - assert_eq!(path.subpaths[0].knots.len(), 1); - assert_eq!(path.subpaths[0].knots[0].anchor, photocraft_geom::Point::new(20.0, 30.0)); - assert!(app.session.active().unwrap().doc.work_path.is_none()); - } - } - - #[test] - fn stale_pen_commits_to_its_owner_across_document_changes() { - use photocraft_doc::{ColorMode, SampleType, Size}; - for tool in [Tool::Pen, Tool::CurvaturePen] { - for action in ["switch", "open", "closeOther", "pen", "curvature", "undo", "commit"] { - let mut app = app(); - app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); - app.ui.tool = tool; - for (x, y) in [(20.0, 20.0), (80.0, 60.0), (120.0, 30.0)] { - if tool == Tool::Pen { - pen_down(&mut app, x, y, false); - pen_up(&mut app); - } else { - curvature_down(&mut app, x, y); - curvature_up(&mut app); - } - } - let owner = app.ui.pen_doc.unwrap(); - let expected = photocraft_engine::vector_cmds::parse_path(&pen_to_json(app.ui.pen.as_ref().unwrap(), false)).unwrap(); - app.ui.direct_selection.target = Some(crate::direct_select::PathRef::Pen); - app.ui.direct_selection.anchors = vec![[0, 1]]; - assert!(app.session.set_active(0)); - match action { - "open" => { - app.services.import = - Some(Box::new(|name, _, _| Ok((Document::new(name, Size::new(4, 4), ColorMode::Rgb, SampleType::U8), Vec::new())))); - app.open_file("synthetic.png", &[]).unwrap(); - } - "closeOther" => { - app.run("file.close", json!({"document": 0})).unwrap(); - } - "pen" => pen_down(&mut app, 150.0, 150.0, false), - "curvature" => curvature_down(&mut app, 150.0, 150.0), - "undo" => assert!(!pen_undo_last_point(&mut app)), - "commit" => pen_commit(&mut app, true), - _ => app.sync_views(), - } - let source = app.session.documents().iter().find(|d| d.doc.id == owner).unwrap(); - let path = source.doc.work_path.as_ref().expect("the owner keeps the unfinished path"); - assert_eq!(path, &expected, "{tool:?} {action}"); - assert!(app.session.documents().iter().filter(|d| d.doc.id != owner).all(|d| d.doc.work_path.is_none())); - if action != "closeOther" { - assert_ne!(app.session.active().unwrap().doc.id, owner, "the active document is restored"); - } - assert_eq!(app.ui.direct_selection, Default::default()); - let index = app.session.documents().iter().position(|d| d.doc.id == owner).unwrap(); - assert!(app.session.set_active(index)); - assert!(app.session.undo()); - assert!(app.session.active().unwrap().doc.work_path.is_none()); - assert!(app.session.redo()); - assert!(app.session.active().unwrap().doc.work_path.is_some()); - } - } - } - - /// #4721: a second Pen path joins the Work Path it was drawn after (still selected), as a new - /// subpath, instead of replacing it; a saved path that is selected takes it instead; with no - /// path selected, the new path replaces the Work Path, as in Photoshop. - #[test] - fn a_new_pen_path_joins_the_selected_path() { - let mut app = app(); - app.ui.tool = Tool::Pen; - let draw = |app: &mut PhotocraftApp, x: f64| { - for (dx, dy) in [(0.0, 0.0), (40.0, 0.0), (40.0, 40.0)] { - pen_down(app, x + dx, 20.0 + dy, false); - pen_up(app); - } - pen_down(app, x + 0.5, 20.5, false); // close - pen_up(app); - }; - let work = |app: &PhotocraftApp| app.session.active().unwrap().doc.work_path.clone().unwrap(); - draw(&mut app, 20.0); - assert_eq!(app.ui.selected_path.as_deref(), Some("work")); - draw(&mut app, 120.0); - let wp = work(&app); - assert_eq!(wp.subpaths.len(), 2, "the first path stays"); - assert!(wp.subpaths.iter().all(|s| s.closed && s.knots.len() == 3)); - assert_eq!(wp.subpaths[0].knots[0].anchor.x, 20.0); - assert_eq!(wp.subpaths[1].knots[0].anchor.x, 120.0); - // One History step per path. - app.session.undo(); - assert_eq!(work(&app).subpaths.len(), 1, "undo takes back only the second path"); - app.session.redo(); - // A selected saved path takes the next one. - app.run("path.set", json!({"name": "Saved", "path": {"subpaths": [{"knots": [[2, 2], [12, 2], [12, 8]]}]}})).unwrap(); - app.ui.selected_path = Some("Saved".into()); - draw(&mut app, 220.0); - let saved = app.session.active().unwrap().doc.paths.iter().find(|p| p.name == "Saved").unwrap().path.clone(); - assert_eq!(saved.subpaths.len(), 2); - assert_eq!(work(&app).subpaths.len(), 2, "the Work Path is left alone"); - assert_eq!(app.ui.selected_path.as_deref(), Some("Saved")); - // No path selected: a new Work Path replaces the old one. - app.ui.selected_path = None; - draw(&mut app, 320.0); - let wp = work(&app); - assert_eq!(wp.subpaths.len(), 1); - assert_eq!(wp.subpaths[0].knots[0].anchor.x, 320.0); - assert_eq!(app.ui.selected_path.as_deref(), Some("work")); - } - - /// #4596: the close-path pointer shows where a click would close the path, and only there: - /// over the first anchor once the Pen has two anchors (the Curvature Pen three), not while an - /// anchor is being dragged. - #[test] - fn close_path_pointer_shows_where_a_click_closes() { - let mut app = app(); - app.ui.tool = Tool::Pen; - assert!(!closes_path_at(&app, Tool::Pen, 20.0, 20.0), "no path yet"); - pen_down(&mut app, 20.0, 20.0, false); - pen_up(&mut app); - assert!(!closes_path_at(&app, Tool::Pen, 20.0, 20.0), "one anchor: a click there doesn't close"); - pen_down(&mut app, 120.0, 20.0, false); - assert!(!closes_path_at(&app, Tool::Pen, 20.0, 20.0), "not while dragging the new anchor"); - pen_up(&mut app); - assert!(closes_path_at(&app, Tool::Pen, 21.0, 22.0), "over the first anchor"); - assert!(!closes_path_at(&app, Tool::Pen, 120.0, 20.0) && !closes_path_at(&app, Tool::Pen, 60.0, 60.0), "the last anchor and empty canvas"); - assert!(!closes_path_at(&app, Tool::CurvaturePen, 20.0, 20.0), "a Pen path isn't the Curvature Pen's"); - pen_down(&mut app, 21.0, 22.0, false); - pen_up(&mut app); - assert!(app.ui.pen.is_none() && !closes_path_at(&app, Tool::Pen, 20.0, 20.0), "the click closed it"); - - app.ui.tool = Tool::CurvaturePen; - for (x, y) in [(20.0, 20.0), (120.0, 20.0)] { - curvature_down(&mut app, x, y); - curvature_up(&mut app); - } - assert!(!closes_path_at(&app, Tool::CurvaturePen, 20.0, 20.0), "two anchors: the Curvature Pen moves the first"); - curvature_down(&mut app, 120.0, 120.0); - curvature_up(&mut app); - assert!(closes_path_at(&app, Tool::CurvaturePen, 20.0, 20.0)); - assert!(!closes_path_at(&app, Tool::CurvaturePen, 120.0, 120.0)); - } - - #[test] - fn pen_point_undo_preserves_earlier_knots_and_document_history() { - let mut app = app(); - app.ui.tool = Tool::Pen; - app.run("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 40], "fill": "#ff0000"})).unwrap(); - let old_history = app.session.active().unwrap().history.past_len(); - - pen_down(&mut app, 20.0, 20.0, false); - pen_up(&mut app); - pen_down(&mut app, 120.0, 20.0, false); - pen_move(&mut app, 120.0, 60.0, false); - pen_up(&mut app); - pen_down(&mut app, 120.0, 120.0, false); - pen_up(&mut app); - - let original_first_two = app.ui.pen.as_ref().unwrap().knots[..2].to_vec(); - assert!(pen_undo_last_point(&mut app)); - let pen = app.ui.pen.as_ref().unwrap(); - assert_eq!(pen.knots, original_first_two); - assert!(!pen.dragging, "undo releases the current Pen drag"); - assert_eq!(app.session.active().unwrap().history.past_len(), old_history, "undo must not roll back previous document changes"); - assert!(app.session.active().unwrap().doc.work_path.is_none(), "path is not committed yet"); - - pen_commit(&mut app, false); - let work = app.session.active().unwrap().doc.work_path.as_ref().unwrap(); - assert_eq!(work.subpaths[0].knots.len(), 2); - assert!(work.subpaths[0].knots[1].smooth, "retained smooth handles are unchanged"); - } - - #[test] - fn pen_undo_of_first_anchor_cancels_empty_draft() { - let mut app = app(); - assert!(!pen_undo_last_point(&mut app)); - pen_down(&mut app, 15.0, 17.0, false); - pen_up(&mut app); - assert!(pen_undo_last_point(&mut app)); - assert!(app.ui.pen.is_none()); - assert!(!pen_undo_last_point(&mut app)); - assert_eq!(app.session.active().unwrap().history.past_len(), 0); - assert!(app.session.active().unwrap().doc.work_path.is_none()); - } - - /// #1419: Solid Color (and every new fill or adjustment layer) made while a path is selected - /// in the Paths panel takes it as its vector mask; with the path deselected, the selection - /// is its layer mask again. - #[test] - fn new_fill_layer_takes_the_selected_path_as_its_vector_mask() { - let mut app = app(); - let layer = |app: &PhotocraftApp, r: Result| { - let id = photocraft_doc::LayerId(r.unwrap()["layer"].as_u64().unwrap()); - app.session.active().unwrap().doc.layer(id).unwrap().clone() - }; - // Drawing a work path with the Pen selects it. - app.ui.tool = Tool::Pen; - for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { - pen_down(&mut app, x, y, false); - pen_up(&mut app); - } - pen_down(&mut app, 20.5, 20.5, false); - pen_up(&mut app); - assert_eq!(app.ui.selected_path.as_deref(), Some("work")); - let wp = app.session.active().unwrap().doc.work_path.clone().unwrap(); - app.run("select.rect", json!({"x": 150, "y": 150, "width": 20, "height": 20})).unwrap(); - for id in ["layer.newFillLayer.solidColor", "layer.newFillLayer.gradient", "layer.newAdjustmentLayer.invert"] { - app.ui.selected_path = Some("work".into()); - let r = app.run(id, json!({})); - let l = layer(&app, r); - assert_eq!(l.vector_mask.as_ref().map(|v| &v.path), Some(&wp), "{id}: the work path is the vector mask"); - assert!(l.mask.is_none(), "{id}: the path wins over the selection"); - // The new layer's vector mask is now the active path, not the work path. - assert_eq!(app.ui.selected_path.as_deref(), Some("layer"), "{id}"); - } - // So the next fill layer isn't masked by the work path again. - let r = app.run("layer.newFillLayer.solidColor", json!({})); - assert!(layer(&app, r).vector_mask.is_none()); - // A caller can opt out. - let r = app.run("layer.newFillLayer.solidColor", json!({"path": null})); - assert!(layer(&app, r).vector_mask.is_none()); - // A selected saved path is used. - app.run("path.set", json!({"name": "Saved", "path": {"subpaths": [{"closed": true, "knots": [[0, 0], [9, 0], [9, 9]]}]}})).unwrap(); - app.ui.selected_path = Some("Saved".into()); - let saved = app.session.active().unwrap().doc.paths[0].path.clone(); - let r = app.run("layer.newFillLayer.solidColor", json!({})); - assert_eq!(layer(&app, r).vector_mask.map(|v| v.path), Some(saved)); - // Deselected (or a stale name): the selection is the layer mask, no vector mask. - for sel in [None, Some("Gone".to_string())] { - app.ui.selected_path = sel; - let r = app.run("layer.newFillLayer.solidColor", json!({})); - let l = layer(&app, r); - assert!(l.vector_mask.is_none() && l.mask.is_some()); - } - // Make Work Path selects the new work path. - app.run("select.toWorkPath", json!({"tolerance": 2.0})).unwrap(); - assert_eq!(app.ui.selected_path.as_deref(), Some("work")); - } - - /// #1482: clicking an existing final Pen anchor breaks its outgoing handle without - /// deleting the preceding curve or creating another knot; dragging changes only that handle. - #[test] - fn pen_last_anchor_can_be_broken_and_reshaped_while_drawing() { - use crate::canvas::{ToolEvent, tool_event}; - let mut app = app(); - app.ui.tool = Tool::Pen; - let down = |app: &mut PhotocraftApp, x, y| tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE); - let move_to = |app: &mut PhotocraftApp, x, y| tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, egui::Modifiers::NONE); - let up = |app: &mut PhotocraftApp, x, y| tool_event(app, ToolEvent::Up { x, y }, egui::Modifiers::NONE); - - down(&mut app, 20.0, 20.0); - up(&mut app, 20.0, 20.0); - down(&mut app, 100.0, 20.0); - move_to(&mut app, 120.0, 40.0); - up(&mut app, 120.0, 40.0); - let original = app.ui.pen.as_ref().unwrap().knots[1]; - assert_eq!(original, [[100.0, 20.0], [80.0, 0.0], [120.0, 40.0]]); - - // Bare click breaks the outgoing handle, preserving the preceding segment's tangent. - down(&mut app, 100.0, 20.0); - up(&mut app, 100.0, 20.0); - let pen = app.ui.pen.as_ref().unwrap(); - assert_eq!(pen.knots.len(), 2); - assert_eq!(pen.knots[1], [[100.0, 20.0], [80.0, 0.0], [100.0, 20.0]]); - assert!(!pen.dragging && !pen.adjusting_last); - - // Re-dragging the same final anchor moves only its outgoing handle (a cusp). - down(&mut app, 100.0, 20.0); - move_to(&mut app, 110.0, 60.0); - up(&mut app, 110.0, 60.0); - let pen = app.ui.pen.as_ref().unwrap(); - assert_eq!(pen.knots.len(), 2); - assert_eq!(pen.knots[1], [[100.0, 20.0], [80.0, 0.0], [110.0, 60.0]]); - - // Drawing on still adds a separate next anchor and keeps the cusp in the work path. - down(&mut app, 150.0, 100.0); - up(&mut app, 150.0, 100.0); - assert_eq!(app.ui.pen.as_ref().unwrap().knots.len(), 3); - pen_commit(&mut app, false); - let work = app.session.active().unwrap().doc.work_path.as_ref().unwrap(); - let k = &work.subpaths[0].knots[1]; - assert_eq!([k.in_ctrl.x, k.in_ctrl.y], [80.0, 0.0]); - assert_eq!([k.out_ctrl.x, k.out_ctrl.y], [110.0, 60.0]); - assert!(!k.smooth, "breaking the handle must persist as an unlinked PSD/vector knot"); - } - - #[test] - fn pen_last_anchor_hit_tolerance_tracks_zoom_and_draft_round_trips() { - for zoom in [0.25, 1.0, 4.0] { - let mut app = app(); - app.ui.views[0].zoom = zoom; - pen_down(&mut app, 20.0, 20.0, false); - pen_up(&mut app); - pen_down(&mut app, 100.0, 100.0, false); - pen_move(&mut app, 110.0, 120.0, false); - pen_up(&mut app); - let incoming = app.ui.pen.as_ref().unwrap().knots[1][1]; - pen_down(&mut app, 100.0 + 5.0 / f64::from(zoom), 100.0, false); - pen_up(&mut app); - let pen = app.ui.pen.as_ref().unwrap(); - assert_eq!(pen.knots.len(), 2); - assert_eq!(pen.knots[1][1], incoming); - assert_eq!(pen.knots[1][2], pen.knots[1][0]); - let saved = serde_json::to_value(pen).unwrap(); - let restored: PenPath = serde_json::from_value(saved).unwrap(); - assert_eq!(restored, *pen); - assert_eq!(pen_to_json(&restored, false)["subpaths"][0]["knots"][1]["smooth"], false); - pen_down(&mut app, 100.0 + 7.0 / f64::from(zoom), 100.0, false); - assert_eq!(app.ui.pen.as_ref().unwrap().knots.len(), 3); - } - let legacy: PenPath = serde_json::from_value(json!({"knots": [[[10, 10], [10, 10], [10, 10]]]})).unwrap(); - assert!(legacy.unlinked.is_empty()); - assert!(!legacy.dragging && !legacy.adjusting_last); - } - - /// #1520: changing one corner through the Properties command must keep the other three - /// independent, remain a live rectangle, and undo/redo as one geometry edit. - #[test] - fn live_rectangle_corner_radius_edit_preserves_other_corners_and_history() { - let mut app = app(); - let created = app.run("shape.create", json!({"kind": "roundedRect", "rect": [10, 10, 150, 100], "radii": [5, 10, 15, 20]})).unwrap(); - let id = created["layer"].as_u64().unwrap(); - let get_radii = |app: &PhotocraftApp| { - let st = app.session.active().unwrap(); - let shape = st.doc.layer(photocraft_doc::LayerId(id)).unwrap(); - match &shape.content { - LayerContent::Shape(sh) => match &sh.live { - Some(photocraft_doc::vector::LiveShape::Rect { radii, .. }) => *radii, - _ => panic!("rectangle must remain a live shape"), - }, - _ => panic!("expected shape layer"), - } - }; - assert_eq!(get_radii(&app), [5.0, 10.0, 15.0, 20.0]); - let mut patch = corner_radii_patch(get_radii(&app), 1, 30.0); - patch["layer"] = json!(id); - app.run("shape.edit", patch).unwrap(); - assert_eq!(get_radii(&app), [5.0, 30.0, 15.0, 20.0]); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(get_radii(&app), [5.0, 10.0, 15.0, 20.0]); - app.run("edit.redo", json!({})).unwrap(); - assert_eq!(get_radii(&app), [5.0, 30.0, 15.0, 20.0]); - for corner in 0..4 { - let before = get_radii(&app); - let radius = 35.0 + corner as f32; - let mut expected = before; - expected[corner] = f64::from(radius); - let mut patch = corner_radii_patch(before, corner, radius); - patch["layer"] = json!(id); - app.run("shape.edit", patch).unwrap(); - assert_eq!(get_radii(&app), expected); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(get_radii(&app), before); - app.run("edit.redo", json!({})).unwrap(); - assert_eq!(get_radii(&app), expected); - } - app.run("shape.edit", json!({"layer": id, "radii": 12})).unwrap(); - assert_eq!(get_radii(&app), [12.0; 4]); - } - - /// #534: dragging in a shape's fill picker, opened from the Properties panel at the right edge - /// of the window, keeps the picker in place (it flipped from side to side as its width - /// followed the colour readouts, which moved it under the pointer). - #[test] - fn shape_colour_picker_stays_put_while_dragging() { - use egui::{PointerButton, vec2}; - use egui_kittest::kittest::Queryable; - let mut app = app(); - let id = app.run("shape.create", json!({"kind": "rect", "rect": [10, 10, 100, 60], "fill": "#3070c0"})).unwrap()["layer"].as_u64().unwrap(); - let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state( - move |ui, app: &mut PhotocraftApp| { - // Fonts set up after the first frame only apply from the next one. - if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - egui::Panel::right("properties").resizable(false).exact_size(285.0).show(ui, |ui| shape_properties(app, ui, photocraft_doc::LayerId(id))); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); - h.run_steps(4); - let label = h.query_all(egui_kittest::kittest::by().label("Fill").include_labels()).next().expect("the Fill label").rect(); - // The swatch is right of its label. - let swatch = egui::pos2(label.right() + 17.0, label.center().y); - let press = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>, pos, pressed| { - h.event(egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); - h.step(); - }; - h.hover_at(swatch); - h.step(); - press(&mut h, swatch, true); - press(&mut h, swatch, false); - h.run_steps(3); - let popup = |h: &egui_kittest::Harness<'_, PhotocraftApp>| { - h.ctx.memory(|m| m.areas().visible_layer_ids().into_iter().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))) - }; - let opened = popup(&h).expect("the picker opened"); - let fill = |h: &egui_kittest::Harness<'_, PhotocraftApp>| { - let st = h.state().session.active().unwrap(); - match &st.doc.layer(photocraft_doc::LayerId(id)).unwrap().content { - LayerContent::Shape(sh) => sh.fill.clone(), - _ => None, - } - }; - let before = fill(&h); - // Drag across the picker's colour area. - let start = opened.min + vec2(60.0, opened.height() * 0.5); - h.hover_at(start); - h.step(); - press(&mut h, start, true); - for i in 1..=10 { - h.event(egui::Event::PointerMoved(start + vec2(i as f32 * 5.0, i as f32))); - h.step(); - let r = popup(&h).expect("the picker stays open"); - assert_eq!(r.left_top(), opened.left_top(), "step {i}: the picker moved from {opened:?} to {r:?}"); - assert!(h.ctx.content_rect().contains_rect(r), "step {i}: {r:?} runs off the window"); - } - press(&mut h, start, false); - assert_ne!(fill(&h), before, "the drag picked a colour"); - } - - /// The options bar edits the selected shape's fill and stroke. - #[test] - fn shape_options_bar_edits_the_selected_shape() { - use egui::accesskit::Role; - use egui_kittest::kittest::Queryable; - let mut app = app(); - app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); - finish_shape(&mut app, Tool::Rectangle, [20.0, 20.0], [120.0, 100.0], Default::default()); - let shape = |app: &PhotocraftApp| { - let st = app.session.active().unwrap(); - match &st.doc.layer(st.active_layer.unwrap()).unwrap().content { - LayerContent::Shape(sh) => (sh.fill.clone(), sh.stroke.clone()), - _ => panic!("not a shape layer"), - } - }; - assert!(shape(&app).0.is_some() && shape(&app).1.is_none()); - let mut h = egui_kittest::Harness::builder().with_size(vec2(1100.0, 48.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - ui.horizontal_centered(|ui| options_bar(app, ui, Tool::Rectangle)); - } - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run_steps(4); - let click_fill = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>| { - let label = h.query_all(egui_kittest::kittest::by().label("Fill:").include_labels()).next().expect("the Fill label").rect(); - let at = egui::pos2(label.right() + h.ctx.global_style().spacing.item_spacing.x + 7.0, label.center().y); - h.hover_at(at); - h.step(); - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); - h.step(); - } - h.run_steps(2); - }; - // Stroke width. - h.get_all_by_role(Role::SpinButton).next().expect("the stroke width").click(); - h.run(); - for c in "6".chars() { - h.event(egui::Event::Text(c.to_string())); - h.run(); - } - h.key_press(egui::Key::Enter); - h.run_steps(2); - let stroke = shape(h.state()).1.expect("the width field stroked the shape"); - assert_eq!(stroke.width, 6.0); - assert_eq!(stroke.paint, photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(0.0, 0.0, 1.0, 1.0))); - // Fill off. - click_fill(&mut h); - assert_eq!(shape(h.state()).0, None, "unchecking Fill removed the shape's fill"); - assert!(!h.state().ui.tool_options.shape_fill, "and the next shape has none either"); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert!(shape(h.state()).0.is_some()); - // No shape selected: no edit. - h.state_mut().run("layer.new.layer", json!({})).unwrap(); - let history = h.state().session.active().unwrap().history.past_len(); - h.run_steps(2); - click_fill(&mut h); - assert_eq!(h.state().session.active().unwrap().history.past_len(), history); - } - - /// #3915: Path Selection and Direct Selection options bars show Fill, Stroke, and Radius - /// controls when a shape is selected, and editing them edits the selected shape. - #[test] - fn path_selection_options_bar_edits_the_selected_shape() { - use egui::accesskit::Role; - use egui_kittest::kittest::Queryable; - let mut app = app(); - app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); - finish_shape(&mut app, Tool::Rectangle, [20.0, 20.0], [120.0, 100.0], Default::default()); - let shape = |app: &PhotocraftApp| { - let st = app.session.active().unwrap(); - match &st.doc.layer(st.active_layer.unwrap()).unwrap().content { - LayerContent::Shape(sh) => (sh.fill.clone(), sh.stroke.clone()), - _ => panic!("not a shape layer"), - } - }; - assert!(shape(&app).0.is_some() && shape(&app).1.is_none()); - let mut h = egui_kittest::Harness::builder().with_size(vec2(1100.0, 48.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - ui.horizontal_centered(|ui| options_bar(app, ui, Tool::PathSelection)); - } - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run_steps(4); - let click_fill = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>| { - let label = h.query_all(egui_kittest::kittest::by().label("Fill:").include_labels()).next().expect("the Fill label").rect(); - let at = egui::pos2(label.right() + h.ctx.global_style().spacing.item_spacing.x + 7.0, label.center().y); - h.hover_at(at); - h.step(); - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); - h.step(); - } - h.run_steps(2); - }; - // Stroke width field is available on Path Selection bar too. - h.get_all_by_role(Role::SpinButton).next().expect("the stroke width").click(); - h.run(); - for c in "6".chars() { - h.event(egui::Event::Text(c.to_string())); - h.run(); - } - h.key_press(egui::Key::Enter); - h.run_steps(2); - let stroke = shape(h.state()).1.expect("the width field stroked the shape"); - assert_eq!(stroke.width, 6.0); - assert_eq!(stroke.paint, photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(0.0, 0.0, 1.0, 1.0))); - // Fill toggle. - click_fill(&mut h); - assert_eq!(shape(h.state()).0, None, "unchecking Fill removed the shape's fill"); - // No shape selected: renders hint text instead. - h.state_mut().run("layer.new.layer", json!({})).unwrap(); - h.run_steps(2); - assert!(h.query_all(egui_kittest::kittest::by().label("Fill:").include_labels()).next().is_none()); - } - - /// #6553: a Paths row dragged onto the footer's trash is deleted, whichever row is selected, - /// and a shape layer's path row does not start a drag. - #[test] - fn path_rows_dragged_onto_the_trash_are_deleted() { - use egui_kittest::kittest::Queryable; - let mut app = app(); - let path = json!({"subpaths": [{"closed": true, "knots": [ - {"anchor": [10, 10], "in": [10, 10], "out": [10, 10]}, - {"anchor": [80, 10], "in": [80, 10], "out": [80, 10]}, - {"anchor": [80, 80], "in": [80, 80], "out": [80, 80]} - ]}]}); - app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); - app.run("path.set", json!({"name": "work", "path": path})).unwrap(); - app.ui.selected_path = Some("work".into()); - let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state(|ui, app: &mut PhotocraftApp| paths_panel(app, ui), app); - h.run_steps(3); - let trash = |h: &egui_kittest::Harness<'_, PhotocraftApp>| { - let buttons: Vec = h - .ctx - .viewport(|v| v.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).filter(|w| w.rect.size() == vec2(26.0, 26.0)).map(|w| w.rect).collect()); - buttons.into_iter().max_by(|a, b| a.center().x.total_cmp(&b.center().x)).unwrap().center() - }; - let drag = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>, from: Pos2, to: Pos2| { - h.event(egui::Event::PointerMoved(from)); - h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); - h.step(); - for k in 1..=10 { - h.event(egui::Event::PointerMoved(from + (to - from) * (k as f32 / 10.0))); - h.step(); - } - h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); - h.run_steps(3); - }; - // The saved path, while the work path is selected: only the dragged row goes. - let (row, to) = (h.get_by_label("Path 1").rect().center(), trash(&h)); - drag(&mut h, row, to); - let doc = &h.state().session.active().unwrap().doc; - assert!(doc.paths.is_empty(), "the dragged saved path is deleted"); - assert!(doc.work_path.is_some(), "the selected work path is kept"); - // The work path. - let (row, to) = (h.get_by_label("Work Path").rect().center(), trash(&h)); - drag(&mut h, row, to); - assert!(h.state().session.active().unwrap().doc.work_path.is_none(), "the dragged work path is deleted"); - // A drop elsewhere deletes nothing. - h.state_mut().run("path.set", json!({"name": "Path 2", "path": path})).unwrap(); - h.run_steps(2); - let row = h.get_by_label("Path 2").rect().center(); - drag(&mut h, row, row + vec2(0.0, 120.0)); - assert_eq!(h.state().session.active().unwrap().doc.paths.len(), 1, "a drop off the trash keeps the path"); - // A shape layer's path row is not dragged onto the trash (its deletion is #6552's). - h.state_mut().run("shape.create", json!({"kind": "ellipse", "rect": [20, 20, 100, 70]})).unwrap(); - h.run_steps(2); - let layers = h.state().session.active().unwrap().doc.layers.len(); - let (row, to) = (h.get_by_label("Ellipse 1 Shape Path").rect().center(), trash(&h)); - drag(&mut h, row, to); - let doc = &h.state().session.active().unwrap().doc; - assert_eq!((doc.layers.len(), doc.paths.len()), (layers, 1), "nothing is deleted"); - } -} +mod tests; #[cfg(test)] #[path = "path_selection_tests.rs"] diff --git a/crates/ui-egui/src/vector_ui/tests.rs b/crates/ui-egui/src/vector_ui/tests.rs new file mode 100644 index 0000000000..85935eff16 --- /dev/null +++ b/crates/ui-egui/src/vector_ui/tests.rs @@ -0,0 +1,1347 @@ +use super::*; + +/// #4084: zoomed in, a curve's chords stay within a fraction of a pixel of the true curve +/// (16 fixed chords showed corners), and a straight segment stays one chord. +#[test] +fn path_curves_stay_smooth_at_any_zoom() { + let (p0, c0, c1, p1) = ([0.0, 100.0], [20.0, -60.0], [80.0, -60.0], [100.0, 100.0]); + for zoom in [0.25, 1.0, 8.0, 64.0, 320.0] { + let xf = move |q: [f64; 2]| pos2((q[0] * zoom) as f32 + 10.0, (q[1] * zoom) as f32 - 5.0); + let pts = curve_points(p0, c0, c1, p1, &xf); + let n = pts.len() - 1; + assert_eq!((pts[0], pts[n]), (xf(p0), xf(p1)), "the ends are the anchors"); + for (k, w) in pts.windows(2).enumerate() { + let curve = xf(bezier(p0, c0, c1, p1, (k as f64 + 0.5) / n as f64)); + let chord = w[0] + (w[1] - w[0]) * 0.5; + assert!((chord - curve).length() <= 0.35, "zoom {zoom}: chord {k} of {n} is {} px off", (chord - curve).length()); + } + // Zoomed out it stays cheap. + if zoom <= 1.0 { + assert!(n <= 32, "zoom {zoom}: {n} chords"); + } + } + let xf = |q: [f64; 2]| pos2((q[0] * 320.0) as f32, (q[1] * 320.0) as f32); + // Retracted handles, and handles along the line: one chord. + assert_eq!(curve_points([0.0, 0.0], [0.0, 0.0], [50.0, 50.0], [50.0, 50.0], &xf).len(), 2); + assert_eq!(curve_points([0.0, 0.0], [10.0, 10.0], [40.0, 40.0], [50.0, 50.0], &xf).len(), 2); + // A handle past the end is a curve that doubles back, not a line. + assert!(curve_points([0.0, 0.0], [0.0, 0.0], [80.0, 80.0], [50.0, 50.0], &xf).len() > 2); + // Hostile coordinates: no panic, a bounded number of points. + for bad in [f64::NAN, f64::INFINITY, 1e300] { + assert!(curve_points([0.0, 0.0], [bad, 0.0], [0.0, bad], [1.0, 1.0], &xf).len() <= MAX_CURVE_PIECES + 1); + } + // Through path_lines too: a closed subpath of two curved segments. + let mut path = Path::default(); + path.subpaths.push(photocraft_doc::vector::Subpath { + knots: vec![ + photocraft_doc::vector::Knot { + anchor: photocraft_geom::Point::new(0.0, 0.0), + in_ctrl: photocraft_geom::Point::new(0.0, 40.0), + out_ctrl: photocraft_geom::Point::new(0.0, -40.0), + smooth: true, + }, + photocraft_doc::vector::Knot { + anchor: photocraft_geom::Point::new(60.0, 0.0), + in_ctrl: photocraft_geom::Point::new(60.0, -40.0), + out_ctrl: photocraft_geom::Point::new(60.0, 40.0), + smooth: true, + }, + ], + closed: true, + ..Default::default() + }); + let lines = path_lines(&path, &xf); + assert!(lines[0].1 && lines[0].0.len() > 2 * 17, "zoomed in, more than the old 16 chords per segment: {}", lines[0].0.len()); +} + +#[test] +fn all_shape_tools_and_open_pen_use_the_complete_stroke_defaults() { + for tool in [Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line, Tool::CustomShape] { + let mut a = app(); + a.ui.tool_options.stroke_width = 5.0; + a.ui.tool_options.shape_stroke = crate::shape_stroke_ui::StrokeOptions { + cap: photocraft_doc::LineCap::Square, + join: photocraft_doc::LineJoin::Bevel, + dashes: vec![4.0, 2.0, 1.0, 3.0], + dash_offset: -0.5, + opacity: 0.4, + ..Default::default() + }; + let history = a.session.active().unwrap().history.past_len(); + finish_shape(&mut a, tool, [20.0, 20.0], [120.0, 100.0], Default::default()); + let info = a.run("shape.info", json!({})).unwrap(); + assert_eq!(info["stroke"]["dashes"], json!([4.0, 2.0, 1.0, 3.0])); + assert_eq!(info["stroke"]["cap"], "square"); + assert_eq!(info["stroke"]["width"], 5.0); + assert_eq!(a.session.active().unwrap().history.past_len(), history + 1); + a.run("edit.undo", json!({})).unwrap(); + a.run("edit.redo", json!({})).unwrap(); + assert_eq!(a.run("shape.info", json!({})).unwrap(), info); + a.ui.tool_options.vector_mode = "shape".into(); + a.ui.pen = Some(PenPath { knots: vec![[[30.0, 40.0]; 3], [[80.0, 40.0]; 3]], ..Default::default() }); + pen_commit(&mut a, false); + let open = a.run("shape.info", json!({})).unwrap(); + assert_eq!(open["stroke"]["dashes"], info["stroke"]["dashes"]); + assert_eq!(open["path"]["subpaths"][0]["closed"], false); + } +} + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + app +} + +#[test] +fn paths_context_menu_uses_the_clicked_row_and_dispatches_commands() { + let mut app = app(); + let path = json!({"subpaths": [{"closed": true, "knots": [ + {"anchor": [10, 10], "in": [10, 10], "out": [10, 10]}, + {"anchor": [80, 10], "in": [80, 10], "out": [80, 10]}, + {"anchor": [80, 80], "in": [80, 80], "out": [80, 80]} + ]}]}); + app.run("path.set", json!({"name": "First", "path": path})).unwrap(); + app.run("path.set", json!({"name": "Second", "path": path})).unwrap(); + let doc = &app.session.active().unwrap().doc; + let first = path_rows(doc, None).into_iter().find(|r| r.name == "First").unwrap(); + let entries = path_context_actions(&first, doc, None); + assert_eq!(entries[0].1, "path.toSelection"); + assert_eq!(entries[0].2["name"], "First"); + assert!(entries.iter().all(|(_, id, _)| photocraft_engine::commands::find(id).is_some())); + let (_, id, params) = entries.into_iter().find(|(_, id, _)| *id == "path.toSelection").unwrap(); + app.run(id, params).unwrap(); + assert!(app.session.active().unwrap().doc.selection.is_some()); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("path.toSelection")); + + app.run("path.set", json!({"name": "First copy 1", "path": path})).unwrap(); + let doc = &app.session.active().unwrap().doc; + let first = path_rows(doc, None).into_iter().find(|r| r.name == "First").unwrap(); + let (_, _, duplicate) = path_context_actions(&first, doc, None).into_iter().find(|(_, id, _)| *id == "path.set").unwrap(); + assert_eq!(duplicate["name"], "First copy 2", "duplicate must not overwrite an existing path"); +} + +#[test] +fn work_path_context_save_and_layer_path_deletion_rules() { + let mut app = app(); + let path = json!({"subpaths": []}); + app.run("path.set", json!({"name": "work", "path": path})).unwrap(); + let doc = &app.session.active().unwrap().doc; + let work = path_rows(doc, None).into_iter().find(|r| r.kind == PathRow::Work).unwrap(); + let entries = path_context_actions(&work, doc, None); + assert!(entries.iter().any(|(_, id, _)| *id == "path.rename")); + assert!(!entries.iter().any(|(_, id, _)| *id == "path.set")); + let layer = PathEntry { kind: PathRow::Layer, ..work }; + let entries = path_context_actions(&layer, doc, None); + assert!(!entries.iter().any(|(_, id, _)| *id == "path.delete")); +} + +/// #6552: a shape layer's " Shape Path" row offers Delete Path, and it deletes the +/// shape layer, as Photoshop's Delete Path does (measured: one "Delete Layer" step). +#[test] +fn shape_path_row_delete_path_deletes_the_shape_layer() { + let mut app = app(); + app.run("shape.create", json!({"kind": "ellipse", "rect": [20, 20, 100, 70]})).unwrap(); + let st = app.session.active().unwrap(); + let (doc, shape) = (st.doc.clone(), st.active_layer); + let layers = doc.layers.len(); + let row = path_rows(&doc, shape).into_iter().find(|r| r.kind == PathRow::Layer).unwrap(); + assert!(row.name.ends_with(" Shape Path"), "{}", row.name); + let (_, id, params) = + path_context_actions(&row, &doc, shape).into_iter().find(|(label, _, _)| *label == "Delete Path").expect("Delete Path is offered"); + app.run(id, params).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert_eq!(doc.layers.len(), layers - 1); + assert!(shape.and_then(|id| doc.layer(id)).is_none(), "the shape layer is gone"); + app.run("edit.undo", json!({})).unwrap(); + assert!(shape.and_then(|id| app.session.active().unwrap().doc.layer(id)).is_some(), "one undo step brings it back"); +} + +/// #6238: double-clicking a saved path's name renames it in place, and double-clicking the +/// Work Path saves it under the name typed (it used to save it as "Path N" straight away). +#[test] +fn double_clicking_a_path_name_renames_it_in_place() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = app(); + let path = json!({"subpaths": [{"closed": true, "knots": [ + {"anchor": [10, 10], "in": [10, 10], "out": [10, 10]}, + {"anchor": [80, 10], "in": [80, 10], "out": [80, 10]}, + {"anchor": [80, 80], "in": [80, 80], "out": [80, 80]} + ]}]}); + app.run("path.set", json!({"name": "First", "path": path})).unwrap(); + app.run("path.set", json!({"name": "work", "path": path})).unwrap(); + // 60 fps steps, so two clicks a frame apart count as a double-click. + let mut h = Harness::builder().with_size(vec2(320.0, 260.0)).with_step_dt(1.0 / 60.0).build_ui_state(|ui, app| paths_panel(app, ui), app); + h.run_steps(3); + let rename = |h: &mut Harness<'_, PhotocraftApp>, row: &str, text: &str| { + let name = h.get_by_label(row).rect().left_center() + vec2(60.0, 0.0); + h.event(egui::Event::PointerMoved(name)); + h.run_steps(30); + for pressed in [true, false, true, false] { + h.event(egui::Event::PointerButton { pos: name, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.step(); + } + h.run_steps(3); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(3); + }; + let names = |h: &Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().doc.paths.iter().map(|p| p.name.clone()).collect::>(); + rename(&mut h, "First", "Outline"); + assert_eq!(names(&h), ["Outline"]); + assert!(h.state().session.active().unwrap().doc.work_path.is_some(), "renaming a saved path leaves the work path alone"); + rename(&mut h, "Work Path", "Circle"); + assert_eq!(names(&h), ["Outline", "Circle"]); + assert!(h.state().session.active().unwrap().doc.work_path.is_none()); + assert_eq!(h.state().ui.selected_path.as_deref(), Some("Circle")); +} + +/// #6238: a saved path's context menu offers Rename Path…, as the Layers panel's does. +#[test] +fn saved_path_context_menu_offers_rename() { + let mut app = app(); + app.run("path.set", json!({"name": "First", "path": {"subpaths": []}})).unwrap(); + app.run("path.set", json!({"name": "work", "path": {"subpaths": []}})).unwrap(); + let doc = &app.session.active().unwrap().doc; + let rename = |kind| { + let entry = path_rows(doc, None).into_iter().find(|r| r.kind == kind).unwrap(); + path_context_actions(&entry, doc, None).into_iter().find(|(label, _, _)| *label == "Rename Path…").map(|(_, id, p)| (id, p)) + }; + assert_eq!(rename(PathRow::Saved), Some(("path.rename", json!({"name": "First"})))); + assert_eq!(rename(PathRow::Work), None, "the work path is saved, not renamed"); +} + +/// How many shapes the path overlay paints for `app` this frame. +fn overlay_shapes(app: &PhotocraftApp, ctx: &egui::Context) -> usize { + let doc = app.session.active().unwrap().doc.clone(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 400.0)); + let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); + let xf = ViewXform { rect, zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + draw_overlay(app, &painter, &xf, &doc); + }); + out.textures_delta.clear(); + out.shapes.len() +} + +#[test] +fn pen_keeps_anchors_of_a_finished_path() { + // #6884: a path finished with Enter, or by closing it, lost its anchor squares while the + // Pen stayed active, so it looked gone and could not be edited. + let ctx = egui::Context::default(); + let mut app = app(); + app.ui.tool = Tool::Pen; + let knots = vec![[[10.0, 10.0]; 3], [[80.0, 10.0]; 3], [[80.0, 80.0]; 3]]; + app.ui.pen = Some(PenPath { knots, ..Default::default() }); + pen_commit(&mut app, true); + assert!(app.ui.pen.is_none()); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + let with_pen = overlay_shapes(&app, &ctx); + app.ui.tool = Tool::Brush; + let outline_only = overlay_shapes(&app, &ctx); + assert!(outline_only > 0, "the outline is drawn with any tool"); + // Each of the three anchors adds its square (fill and stroke). + assert!(with_pen >= outline_only + 3, "Pen draws the anchors: {with_pen} vs {outline_only}"); + for tool in [Tool::Pen, Tool::FreeformPen, Tool::CurvaturePen, Tool::PathSelection] { + assert!(shows_anchors(tool), "{tool:?}"); + } + assert!(!shows_anchors(Tool::Brush) && !shows_anchors(Tool::Move)); +} + +#[test] +fn an_unselected_work_path_is_not_drawn_over_the_canvas() { + // #6551: Ctrl-click Load as Selection leaves the Paths panel's selection alone, yet the Work + // Path stayed drawn over the new selection's edge. Photoshop draws it only while selected + // in the Paths panel (or a path tool is active). + let ctx = egui::Context::default(); + let mut app = app(); + let path = json!({"subpaths": [{"closed": true, "knots": [ + {"anchor": [20, 20], "in": [20, 20], "out": [20, 20]}, + {"anchor": [90, 20], "in": [90, 20], "out": [90, 20]}, + {"anchor": [90, 90], "in": [90, 90], "out": [90, 90]} + ]}]}); + app.run("path.set", json!({"name": "work", "path": path})).unwrap(); + app.run("path.toSelection", json!({"name": "work", "mode": "replace"})).unwrap(); + assert!(app.ui.selected_path.is_none()); + for tool in [Tool::Move, Tool::Brush, Tool::Rectangle, Tool::Zoom] { + app.ui.tool = tool; + assert_eq!(overlay_shapes(&app, &ctx), 0, "{tool:?}: an unselected Work Path stays off the canvas"); + } + // Selected in the Paths panel: drawn with any tool. + app.ui.selected_path = Some("work".into()); + for tool in [Tool::Move, Tool::Brush] { + app.ui.tool = tool; + assert!(overlay_shapes(&app, &ctx) > 0, "{tool:?}: the selected Work Path is drawn"); + } + // Another path selected: the Work Path is not the target path. + app.ui.selected_path = Some("Saved".into()); + app.ui.tool = Tool::Move; + assert_eq!(overlay_shapes(&app, &ctx), 0); + // A path tool shows the Work Path it edits even when the panel selection was cleared. + app.ui.selected_path = None; + for tool in [Tool::Pen, Tool::PathSelection] { + app.ui.tool = tool; + assert!(overlay_shapes(&app, &ctx) > 0, "{tool:?}: path tools draw the Work Path"); + } +} + +#[test] +fn show_target_path_and_extras_hide_the_path_outlines() { + // #1119: View › Show › Target Path only flipped its checkmark; the canvas kept drawing the + // work path and the active shape's path. + let ctx = egui::Context::default(); + let mut app = app(); + let path = json!({"subpaths": [{"closed": true, "knots": [ + {"anchor": [10, 10], "in": [10, 10], "out": [10, 10]}, + {"anchor": [80, 10], "in": [80, 10], "out": [80, 10]}, + {"anchor": [80, 80], "in": [80, 80], "out": [80, 80]} + ]}]}); + app.run("path.set", json!({"path": path})).unwrap(); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + finish_shape(&mut app, Tool::Rectangle, [100.0, 100.0], [160.0, 150.0], egui::Modifiers::NONE); + let toggle = |app: &mut PhotocraftApp, id: &str| crate::menus::invoke(app, &ctx, id, Value::Null).unwrap(); + for tool in [Tool::Pen, Tool::PathSelection, Tool::DirectSelection, Tool::Rectangle] { + app.ui.tool = tool; + assert!(app.ui.view.show.target_path && app.ui.view.extras); + assert!(overlay_shapes(&app, &ctx) > 0, "{tool:?}: the paths are drawn by default"); + toggle(&mut app, "view.show.targetPath"); + assert!(!app.ui.view.show.target_path); + assert_eq!(overlay_shapes(&app, &ctx), 0, "{tool:?}: Target Path off"); + toggle(&mut app, "view.show.targetPath"); + toggle(&mut app, "view.extras"); + assert!(!app.ui.view.extras); + assert_eq!(overlay_shapes(&app, &ctx), 0, "{tool:?}: Extras off"); + toggle(&mut app, "view.extras"); + assert!(overlay_shapes(&app, &ctx) > 0, "{tool:?}: shown again"); + } + // The Pen's path in progress is a gesture, not the target path: it stays visible. + app.ui.tool = Tool::Pen; + app.ui.pen = Some(PenPath { knots: vec![[[20.0, 20.0]; 3], [[60.0, 40.0]; 3]], ..Default::default() }); + toggle(&mut app, "view.show.targetPath"); + assert!(overlay_shapes(&app, &ctx) > 0, "the pen path in progress is still drawn"); +} + +#[test] +fn the_saved_path_selected_in_the_paths_panel_is_drawn() { + // #6550: selecting a saved path in the Paths panel drew nothing on the canvas. + let ctx = egui::Context::default(); + let mut app = app(); + let tri = |o: f64| { + json!({"subpaths": [{"closed": true, "knots": [ + {"anchor": [20.0 + o, 20], "in": [20.0 + o, 20], "out": [20.0 + o, 20]}, + {"anchor": [90.0 + o, 20], "in": [90.0 + o, 20], "out": [90.0 + o, 20]}, + {"anchor": [90.0 + o, 90], "in": [90.0 + o, 90], "out": [90.0 + o, 90]} + ]}]}) + }; + app.run("path.set", json!({"name": "Path 1", "path": tri(0.0)})).unwrap(); + app.run("path.set", json!({"name": "Path 2", "path": tri(10.0)})).unwrap(); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + for tool in [Tool::Move, Tool::Brush, Tool::Pen, Tool::PathSelection, Tool::DirectSelection] { + app.ui.tool = tool; + app.ui.selected_path = None; + assert_eq!(overlay_shapes(&app, &ctx), 0, "{tool:?}: nothing selected, nothing drawn"); + app.ui.selected_path = Some("Path 1".into()); + assert_eq!(selected_saved_path(&app).map(|p| p.subpaths[0].knots[0].anchor.x), Some(20.0)); + assert!(overlay_shapes(&app, &ctx) > 0, "{tool:?}: the selected saved path is drawn"); + app.ui.selected_path = Some("Path 2".into()); + assert_eq!(selected_saved_path(&app).map(|p| p.subpaths[0].knots[0].anchor.x), Some(30.0)); + app.ui.selected_path = Some("Gone".into()); + assert_eq!(overlay_shapes(&app, &ctx), 0, "{tool:?}: a missing path draws nothing"); + app.ui.selected_path = Some("Path 1".into()); + app.ui.view.show.target_path = false; + assert_eq!(overlay_shapes(&app, &ctx), 0, "{tool:?}: View > Show > Target Path off"); + app.ui.view.show.target_path = true; + } + // Path Selection (and the Pen tools, as for the work path) add anchor squares. + app.ui.tool = Tool::Move; + let plain = overlay_shapes(&app, &ctx); + app.ui.tool = Tool::PathSelection; + assert!(overlay_shapes(&app, &ctx) > plain); + app.ui.tool = Tool::Pen; + assert!(overlay_shapes(&app, &ctx) > plain); +} + +#[test] +fn shape_drag_creates_layers_with_modifiers() { + let mut app = app(); + finish_shape(&mut app, Tool::Rectangle, [10.0, 10.0], [60.0, 30.0], egui::Modifiers::SHIFT); + let st = app.session.active().unwrap(); + let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); + assert_eq!((b.width(), b.height()), (50, 50), "shift = square"); + finish_shape(&mut app, Tool::EllipseShape, [100.0, 100.0], [120.0, 110.0], egui::Modifiers::ALT); + let st = app.session.active().unwrap(); + let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); + assert!(b.x0.abs_diff(80) <= 1 && b.width().abs_diff(40) <= 1, "alt = from centre: {b:?}"); + finish_shape(&mut app, Tool::Line, [10.0, 150.0], [90.0, 152.0], egui::Modifiers::SHIFT); + assert_eq!(app.session.active().unwrap().doc.layers.len(), 4); +} + +#[test] +fn shift_pressed_during_a_shape_drag_constrains_it() { + // #668: ⇧ only counted when held at the press; Photoshop constrains when it is pressed + // mid-drag (and stops when it is released). + use crate::canvas::{ToolEvent, tool_event}; + for (tool, sides) in [(Tool::Polygon, 6), (Tool::Rectangle, 4), (Tool::EllipseShape, 0)] { + let mut app = app(); + app.ui.tool = tool; + app.ui.tool_options.polygon_sides = 6; + let none = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, none); + tool_event(&mut app, ToolEvent::Move { x: 40.0, y: 30.0, pressure: 1.0 }, none); + tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::SHIFT); + tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 40.0 }, egui::Modifiers::SHIFT); + let st = app.session.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert!(matches!(l.content, LayerContent::Shape(_)), "{tool:?} ({sides} sides): a shape layer"); + let b = l.surface().unwrap().content_bounds(); + // The drag is 60 × 30; constrained, the shape's box is 60 × 60 (a hexagon is narrower + // than its box, so the height tells). + assert!(b.height().abs_diff(60) <= 1 && b.width() <= 61, "{tool:?}: ⇧ mid-drag keeps proportions: {b:?}"); + } +} + +#[test] +fn shape_preview_is_the_committed_path() { + let mut app = app(); + app.ui.tool_options.corner_radius = 8.0; + let preview = |app: &PhotocraftApp, tool, end| { + shape_geometry(&app.ui.tool_options, tool, [10.0, 10.0], end, egui::Modifiers::ALT) + .and_then(|p| photocraft_engine::vector_cmds::shape_path(&p).ok()) + }; + for tool in [Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line] { + let shown = preview(&app, tool, [60.0, 30.0]).unwrap(); + finish_shape(&mut app, tool, [10.0, 10.0], [60.0, 30.0], egui::Modifiers::ALT); + let st = app.session.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("{tool:?}: no shape layer") }; + assert_eq!(sh.path, shown, "{tool:?}"); + } + assert!(preview(&app, Tool::Rectangle, [10.2, 40.0]).is_none(), "too thin to draw"); + assert!(photocraft_engine::vector_cmds::shape_path(&json!({"kind": "nope", "rect": [0, 0, 5, 5]})).is_err()); + assert!(photocraft_engine::vector_cmds::shape_path(&json!({"kind": "rect"})).is_err()); +} + +#[test] +fn pen_shows_the_close_cue_only_over_the_first_anchor_of_a_real_segment() { + let mut app = app(); + app.ui.tool = Tool::Pen; + pen_down(&mut app, 20.0, 20.0, false); + pen_up(&mut app); + let one = app.ui.pen.clone().unwrap(); + assert!(!over_first_anchor(&one, [20.0, 20.0], 6.0), "a single anchor has nothing to close"); + pen_down(&mut app, 120.0, 20.0, false); + pen_up(&mut app); + let two = app.ui.pen.clone().unwrap(); + assert!(over_first_anchor(&two, [22.0, 21.0], 6.0)); + assert!(!over_first_anchor(&two, [60.0, 60.0], 6.0)); +} + +#[test] +fn pen_builds_and_closes_a_work_path() { + let mut app = app(); + app.ui.tool = Tool::Pen; + for (x, y) in [(20.0, 20.0), (120.0, 20.0)] { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } + pen_down(&mut app, 120.0, 120.0, false); + pen_move(&mut app, 140.0, 140.0, false); // smooth knot + pen_up(&mut app); + pen_down(&mut app, 20.5, 20.5, false); // click the first anchor: close + pen_up(&mut app); + assert!(app.ui.pen.is_none()); + let wp = app.session.active().unwrap().doc.work_path.clone().unwrap(); + assert!(wp.subpaths[0].closed && wp.subpaths[0].knots.len() == 3); + assert!(wp.subpaths[0].knots[2].smooth); + // Path Selection moves it. + path_selection_finish(&mut app, [50.0, 50.0], [60.0, 55.0]); + let wp = app.session.active().unwrap().doc.work_path.clone().unwrap(); + assert_eq!((wp.subpaths[0].knots[0].anchor.x, wp.subpaths[0].knots[0].anchor.y), (30.0, 25.0)); +} + +fn close(a: [f64; 2], b: [f64; 2]) -> bool { + (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9 +} + +#[test] +fn pen_shift_click_puts_the_next_anchor_on_a_45_degree_ray() { + let mut app = app(); + app.ui.tool = Tool::Pen; + // The first anchor has nothing to constrain against: it lands where clicked. + pen_down(&mut app, 20.0, 20.0, true); + pen_up(&mut app); + assert_eq!(app.ui.pen.as_ref().unwrap().knots[0][0], [20.0, 20.0]); + // ~30° below horizontal snaps to the 45° diagonal at the pointer's projection. + let (dx, dy) = (100.0 * 30f64.to_radians().cos(), 100.0 * 30f64.to_radians().sin()); + pen_down(&mut app, 20.0 + dx, 20.0 + dy, true); + pen_up(&mut app); + let k = app.ui.pen.as_ref().unwrap().knots[1]; + let t = 100.0 * 15f64.to_radians().cos() / std::f64::consts::SQRT_2; + assert!(close(k[0], [20.0 + t, 20.0 + t]), "{:?}", k[0]); + assert!(k[1] == k[0] && k[2] == k[0], "a click stays a corner"); + // ~10° off vertical snaps to straight down from the previous anchor. + let prev = k[0]; + pen_down(&mut app, prev[0] + 8.0, prev[1] + 50.0, true); + pen_up(&mut app); + assert!(close(app.ui.pen.as_ref().unwrap().knots[2][0], [prev[0], prev[1] + 50.0])); + // Without ⇧ the anchor stays at the pointer. + pen_down(&mut app, 200.0, 190.0, false); + pen_up(&mut app); + assert_eq!(app.ui.pen.as_ref().unwrap().knots[3][0], [200.0, 190.0]); + // ⇧ does not stop a click on the first anchor from closing the path. + pen_down(&mut app, 20.5, 20.5, true); + pen_up(&mut app); + assert!(app.ui.pen.is_none()); + assert!(app.session.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].closed); +} + +#[test] +fn pen_shift_drag_turns_handles_to_45_degrees_live() { + let mut app = app(); + app.ui.tool = Tool::Pen; + pen_down(&mut app, 20.0, 20.0, false); + pen_up(&mut app); + pen_down(&mut app, 100.0, 100.0, false); + // Without ⇧ the handle follows the pointer. + pen_move(&mut app, 130.0, 110.0, false); + assert_eq!(app.ui.pen.as_ref().unwrap().knots[1][2], [130.0, 110.0]); + // Pressing ⇧ mid-drag snaps the handle (~18°) to horizontal; the opposite handle mirrors it. + pen_move(&mut app, 130.0, 110.0, true); + let k = app.ui.pen.as_ref().unwrap().knots[1]; + assert!(close(k[2], [130.0, 100.0]) && close(k[1], [70.0, 100.0]), "{k:?}"); + assert_eq!(k[0], [100.0, 100.0], "the anchor does not move"); + // Releasing ⇧ frees it again. + pen_move(&mut app, 120.0, 140.0, false); + assert_eq!(app.ui.pen.as_ref().unwrap().knots[1][2], [120.0, 140.0]); + // ⌥ breaks the pair; ⇧ then constrains the outgoing handle alone (~63° → 45°). + pen_break_handle(&mut app); + pen_move(&mut app, 120.0, 140.0, true); + let k = app.ui.pen.as_ref().unwrap().knots[1]; + assert!(close(k[2], [130.0, 130.0]), "{k:?}"); + assert_eq!(k[1], [80.0, 60.0], "the incoming handle stays where it was"); + pen_up(&mut app); + // Degenerate: ⇧ with the pointer on the anchor leaves the handle on it. + pen_down(&mut app, 200.0, 100.0, false); + pen_move(&mut app, 200.0, 100.0, true); + let k = app.ui.pen.as_ref().unwrap().knots[2]; + assert!(k.iter().all(|p| *p == [200.0, 100.0]), "{k:?}"); + pen_up(&mut app); +} + +/// #5373: an unfinished path stays with its own document through same-frame switches. +#[test] +fn an_unclosed_path_stays_with_its_document() { + // Both pens claim the document at their first anchor. + let open_path = |app: &mut PhotocraftApp| { + for (x, y) in [(20.0, 20.0), (120.0, 60.0)] { + if app.ui.tool == Tool::CurvaturePen { + curvature_down(app, x, y); + curvature_up(app); + } else { + pen_down(app, x, y, false); + pen_up(app); + } + } + }; + let work = |app: &PhotocraftApp, i: usize| app.session.documents()[i].doc.work_path.clone(); + // File › New commits the path to its original document. + for tool in [Tool::Pen, Tool::CurvaturePen] { + let mut app = app(); + app.ui.tool = tool; + open_path(&mut app); + assert!(app.ui.pen.is_some() && app.ui.pen_doc.is_some(), "{tool:?}: claimed by its document"); + app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); + assert!(app.ui.pen.is_none() && app.ui.pen_doc.is_none(), "{tool:?}: the first document's path is gone"); + assert!(work(&app, 0).is_some(), "{tool:?}: the original keeps its Work Path"); + assert_eq!(work(&app, 1), None, "{tool:?}: the new document is blank"); + } + // Two documents; the path below is drawn on the second (active) one. + let mut app = app(); + app.ui.tool = Tool::Pen; + app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); + open_path(&mut app); + assert!(app.session.set_active(0)); + pen_commit(&mut app, false); + assert!(app.ui.pen.is_none()); + assert!(work(&app, 0).is_none(), "the active document stays untouched"); + assert!(work(&app, 1).is_some(), "the owner keeps its Work Path"); + // Staying on its own document, the path still commits there. + open_path(&mut app); + pen_commit(&mut app, false); + assert!(work(&app, 0).is_some(), "it commits to the document it was drawn on"); + assert!(work(&app, 1).is_some()); + for act in [0, 1, 2] { + open_path(&mut app); + assert!(app.session.set_active(1)); + match act { + 0 => pen_down(&mut app, 50.0, 50.0, false), + 1 => curvature_down(&mut app, 50.0, 50.0), + _ => assert!(!pen_undo_last_point(&mut app), "nothing of this document's to undo"), + } + let knots = app.ui.pen.as_ref().map_or(0, |p| p.knots.len()); + assert!(knots <= 1, "act {act}: a new path, not the other document's (knots {knots})"); + // The two drawing entry points start a path of their own here; undo has none to take. + let expected = if act == 2 { None } else { app.session.active().map(|st| st.doc.id) }; + assert_eq!(app.ui.pen_doc, expected, "act {act}"); + app.ui.pen = None; + app.ui.pen_doc = None; + assert!(app.session.set_active(0)); + } + open_path(&mut app); + let shapes = |app: &PhotocraftApp| { + let ctx = egui::Context::default(); + let doc = app.session.active().unwrap().doc.clone(); + let xf = ViewXform { + rect: egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(400.0, 300.0)), + zoom: 1.0, + center: [100.0, 75.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + }; + let mut out = ctx.run_ui(Default::default(), |ui| draw_overlay(app, ui.painter(), &xf, &doc)); + out.textures_delta.clear(); + out.shapes.len() + }; + // Same view, pen present vs absent: the difference is the path itself, nothing else. + let drawn = |app: &mut PhotocraftApp| { + let with_pen = shapes(app); + let pen = app.ui.pen.take(); + let without = shapes(app); + app.ui.pen = pen; + with_pen - without + }; + assert!(drawn(&mut app) > 0, "its own document draws the path"); + assert!(app.session.set_active(1)); + assert_eq!(drawn(&mut app), 0, "the other document draws nothing of it"); + assert!(app.session.set_active(0)); + app.ui.pen = None; + app.ui.pen_doc = None; + open_path(&mut app); + app.ui.direct_selection.target = Some(crate::direct_select::PathRef::Pen); + app.ui.direct_selection.anchors = vec![[0, 1]]; + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + assert_eq!(app.ui.direct_selection, Default::default(), "the anchors went with the path"); +} + +#[test] +fn pen_overlay_uses_the_view_document_even_during_direct_selection() { + let mut app = app(); + app.ui.tool = Tool::Pen; + pen_down(&mut app, 20.0, 20.0, false); + pen_up(&mut app); + pen_down(&mut app, 80.0, 60.0, false); + pen_up(&mut app); + let owner = app.session.active().unwrap().doc.clone(); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + let other = app.session.active().unwrap().doc.clone(); + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let shapes = |app: &PhotocraftApp, doc: &Document, modifiers| { + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(egui::RawInput { events: vec![egui::Event::ModifiersChanged(modifiers)], ..Default::default() }, |ui| { + draw_overlay(app, ui.painter(), &xf, doc) + }); + output.textures_delta.clear(); + output.shapes.len() + }; + for active in [0, 1] { + assert!(app.session.set_active(active)); + for tool in [Tool::Pen, Tool::DirectSelection] { + app.ui.tool = tool; + for modifiers in [egui::Modifiers::NONE, egui::Modifiers::COMMAND] { + for (doc, visible) in [(&owner, true), (&other, false)] { + let with_pen = shapes(&app, doc, modifiers); + let pen = app.ui.pen.take(); + let without = shapes(&app, doc, modifiers); + app.ui.pen = pen; + assert_eq!(with_pen > without, visible, "active {active}, {tool:?}, {modifiers:?}"); + } + } + } + } +} + +#[test] +fn failed_stale_pen_commit_preserves_the_draft_until_retry() { + for action in ["pen", "curvature", "undo", "commit", "command"] { + let mut app = app(); + app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[5, 5], [10, 10]]}]}})).unwrap(); + let original = app.session.active().unwrap().doc.work_path.clone().unwrap(); + app.ui.tool = Tool::Pen; + for (x, y) in [(20.0, 20.0), (80.0, 60.0)] { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } + let draft = app.ui.pen.clone(); + let owner = app.ui.pen_doc; + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.tool_options.vector_mode = "shape".into(); + app.ui.selected_path = Some("foreign named path".into()); + app.session.authorize = Some(|_, _| Err(photocraft_engine::EngineError::Other("test rejection".into()))); + match action { + "pen" => pen_down(&mut app, 150.0, 150.0, false), + "curvature" => curvature_down(&mut app, 150.0, 150.0), + "undo" => assert!(!pen_undo_last_point(&mut app)), + "commit" => pen_commit(&mut app, true), + _ => { + assert!(app.run("file.close", json!({})).is_err()); + } + } + assert_eq!(app.ui.pen, draft, "{action}: failed save retains all anchors"); + assert_eq!(app.ui.pen_doc, owner); + assert_eq!(app.session.active_index(), Some(1)); + assert_eq!(app.session.documents()[0].doc.work_path.as_ref(), Some(&original)); + assert!(app.session.documents()[1].doc.work_path.is_none()); + assert!(app.ui.status_error); + assert!(!crate::direct_select::candidates(&app).iter().any(|(target, _)| *target == crate::direct_select::PathRef::Pen)); + app.session.authorize = None; + app.sync_views(); + assert!(app.ui.pen.is_none()); + assert_eq!(app.session.active_index(), Some(1)); + assert_eq!(app.ui.selected_path.as_deref(), Some("foreign named path")); + let saved = app.session.documents()[0].doc.work_path.clone().unwrap(); + assert_eq!(saved.subpaths.len(), original.subpaths.len() + 1); + assert_eq!(saved.subpaths[0], original.subpaths[0]); + app.sync_views(); + assert_eq!(app.session.documents()[0].doc.work_path.as_ref(), Some(&saved), "retry never duplicates the path"); + assert!(app.session.set_active(0)); + assert!(app.session.undo()); + assert_eq!(app.session.active().unwrap().doc.work_path.as_ref(), Some(&original)); + } +} + +#[test] +fn new_document_reports_a_failed_work_path_save_and_retains_the_draft() { + let mut app = app(); + pen_down(&mut app, 20.0, 20.0, false); + pen_up(&mut app); + pen_down(&mut app, 80.0, 60.0, false); + pen_up(&mut app); + let draft = app.ui.pen.clone(); + app.session.authorize = Some(|id, _| if id == "path.set" { Err(photocraft_engine::EngineError::Other("test rejection".into())) } else { Ok(()) }); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + assert!(app.ui.status_error); + assert!(app.ui.status.contains("test rejection")); + assert_eq!(app.ui.pen, draft); + assert_eq!(app.session.active_index(), Some(1)); + assert!(app.session.documents().iter().all(|d| d.doc.work_path.is_none())); + app.session.authorize = None; + app.sync_views(); + assert!(app.ui.pen.is_none()); + assert!(app.session.documents()[0].doc.work_path.is_some()); + assert!(app.session.documents()[1].doc.work_path.is_none()); +} + +#[test] +fn new_document_preserves_a_single_pen_anchor_as_a_work_path() { + for tool in [Tool::Pen, Tool::CurvaturePen] { + let mut app = app(); + app.ui.tool = tool; + if tool == Tool::Pen { + pen_down(&mut app, 20.0, 30.0, false); + pen_up(&mut app); + } else { + curvature_down(&mut app, 20.0, 30.0); + curvature_up(&mut app); + } + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + assert!(app.ui.pen.is_none()); + let path = app.session.documents()[0].doc.work_path.as_ref().unwrap(); + assert_eq!(path.subpaths[0].knots.len(), 1); + assert_eq!(path.subpaths[0].knots[0].anchor, photocraft_geom::Point::new(20.0, 30.0)); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + } +} + +#[test] +fn stale_pen_commits_to_its_owner_across_document_changes() { + use photocraft_doc::{ColorMode, SampleType, Size}; + for tool in [Tool::Pen, Tool::CurvaturePen] { + for action in ["switch", "open", "closeOther", "pen", "curvature", "undo", "commit"] { + let mut app = app(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.tool = tool; + for (x, y) in [(20.0, 20.0), (80.0, 60.0), (120.0, 30.0)] { + if tool == Tool::Pen { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } else { + curvature_down(&mut app, x, y); + curvature_up(&mut app); + } + } + let owner = app.ui.pen_doc.unwrap(); + let expected = photocraft_engine::vector_cmds::parse_path(&pen_to_json(app.ui.pen.as_ref().unwrap(), false)).unwrap(); + app.ui.direct_selection.target = Some(crate::direct_select::PathRef::Pen); + app.ui.direct_selection.anchors = vec![[0, 1]]; + assert!(app.session.set_active(0)); + match action { + "open" => { + app.services.import = + Some(Box::new(|name, _, _| Ok((Document::new(name, Size::new(4, 4), ColorMode::Rgb, SampleType::U8), Vec::new())))); + app.open_file("synthetic.png", &[]).unwrap(); + } + "closeOther" => { + app.run("file.close", json!({"document": 0})).unwrap(); + } + "pen" => pen_down(&mut app, 150.0, 150.0, false), + "curvature" => curvature_down(&mut app, 150.0, 150.0), + "undo" => assert!(!pen_undo_last_point(&mut app)), + "commit" => pen_commit(&mut app, true), + _ => app.sync_views(), + } + let source = app.session.documents().iter().find(|d| d.doc.id == owner).unwrap(); + let path = source.doc.work_path.as_ref().expect("the owner keeps the unfinished path"); + assert_eq!(path, &expected, "{tool:?} {action}"); + assert!(app.session.documents().iter().filter(|d| d.doc.id != owner).all(|d| d.doc.work_path.is_none())); + if action != "closeOther" { + assert_ne!(app.session.active().unwrap().doc.id, owner, "the active document is restored"); + } + assert_eq!(app.ui.direct_selection, Default::default()); + let index = app.session.documents().iter().position(|d| d.doc.id == owner).unwrap(); + assert!(app.session.set_active(index)); + assert!(app.session.undo()); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + assert!(app.session.redo()); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + } + } +} + +/// #4721: a second Pen path joins the Work Path it was drawn after (still selected), as a new +/// subpath, instead of replacing it; a saved path that is selected takes it instead; with no +/// path selected, the new path replaces the Work Path, as in Photoshop. +#[test] +fn a_new_pen_path_joins_the_selected_path() { + let mut app = app(); + app.ui.tool = Tool::Pen; + let draw = |app: &mut PhotocraftApp, x: f64| { + for (dx, dy) in [(0.0, 0.0), (40.0, 0.0), (40.0, 40.0)] { + pen_down(app, x + dx, 20.0 + dy, false); + pen_up(app); + } + pen_down(app, x + 0.5, 20.5, false); // close + pen_up(app); + }; + let work = |app: &PhotocraftApp| app.session.active().unwrap().doc.work_path.clone().unwrap(); + draw(&mut app, 20.0); + assert_eq!(app.ui.selected_path.as_deref(), Some("work")); + draw(&mut app, 120.0); + let wp = work(&app); + assert_eq!(wp.subpaths.len(), 2, "the first path stays"); + assert!(wp.subpaths.iter().all(|s| s.closed && s.knots.len() == 3)); + assert_eq!(wp.subpaths[0].knots[0].anchor.x, 20.0); + assert_eq!(wp.subpaths[1].knots[0].anchor.x, 120.0); + // One History step per path. + app.session.undo(); + assert_eq!(work(&app).subpaths.len(), 1, "undo takes back only the second path"); + app.session.redo(); + // A selected saved path takes the next one. + app.run("path.set", json!({"name": "Saved", "path": {"subpaths": [{"knots": [[2, 2], [12, 2], [12, 8]]}]}})).unwrap(); + app.ui.selected_path = Some("Saved".into()); + draw(&mut app, 220.0); + let saved = app.session.active().unwrap().doc.paths.iter().find(|p| p.name == "Saved").unwrap().path.clone(); + assert_eq!(saved.subpaths.len(), 2); + assert_eq!(work(&app).subpaths.len(), 2, "the Work Path is left alone"); + assert_eq!(app.ui.selected_path.as_deref(), Some("Saved")); + // No path selected: a new Work Path replaces the old one. + app.ui.selected_path = None; + draw(&mut app, 320.0); + let wp = work(&app); + assert_eq!(wp.subpaths.len(), 1); + assert_eq!(wp.subpaths[0].knots[0].anchor.x, 320.0); + assert_eq!(app.ui.selected_path.as_deref(), Some("work")); +} + +/// #4596: the close-path pointer shows where a click would close the path, and only there: +/// over the first anchor once the Pen has two anchors (the Curvature Pen three), not while an +/// anchor is being dragged. +#[test] +fn close_path_pointer_shows_where_a_click_closes() { + let mut app = app(); + app.ui.tool = Tool::Pen; + assert!(!closes_path_at(&app, Tool::Pen, 20.0, 20.0), "no path yet"); + pen_down(&mut app, 20.0, 20.0, false); + pen_up(&mut app); + assert!(!closes_path_at(&app, Tool::Pen, 20.0, 20.0), "one anchor: a click there doesn't close"); + pen_down(&mut app, 120.0, 20.0, false); + assert!(!closes_path_at(&app, Tool::Pen, 20.0, 20.0), "not while dragging the new anchor"); + pen_up(&mut app); + assert!(closes_path_at(&app, Tool::Pen, 21.0, 22.0), "over the first anchor"); + assert!(!closes_path_at(&app, Tool::Pen, 120.0, 20.0) && !closes_path_at(&app, Tool::Pen, 60.0, 60.0), "the last anchor and empty canvas"); + assert!(!closes_path_at(&app, Tool::CurvaturePen, 20.0, 20.0), "a Pen path isn't the Curvature Pen's"); + pen_down(&mut app, 21.0, 22.0, false); + pen_up(&mut app); + assert!(app.ui.pen.is_none() && !closes_path_at(&app, Tool::Pen, 20.0, 20.0), "the click closed it"); + + app.ui.tool = Tool::CurvaturePen; + for (x, y) in [(20.0, 20.0), (120.0, 20.0)] { + curvature_down(&mut app, x, y); + curvature_up(&mut app); + } + assert!(!closes_path_at(&app, Tool::CurvaturePen, 20.0, 20.0), "two anchors: the Curvature Pen moves the first"); + curvature_down(&mut app, 120.0, 120.0); + curvature_up(&mut app); + assert!(closes_path_at(&app, Tool::CurvaturePen, 20.0, 20.0)); + assert!(!closes_path_at(&app, Tool::CurvaturePen, 120.0, 120.0)); +} + +#[test] +fn pen_point_undo_preserves_earlier_knots_and_document_history() { + let mut app = app(); + app.ui.tool = Tool::Pen; + app.run("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 40], "fill": "#ff0000"})).unwrap(); + let old_history = app.session.active().unwrap().history.past_len(); + + pen_down(&mut app, 20.0, 20.0, false); + pen_up(&mut app); + pen_down(&mut app, 120.0, 20.0, false); + pen_move(&mut app, 120.0, 60.0, false); + pen_up(&mut app); + pen_down(&mut app, 120.0, 120.0, false); + pen_up(&mut app); + + let original_first_two = app.ui.pen.as_ref().unwrap().knots[..2].to_vec(); + assert!(pen_undo_last_point(&mut app)); + let pen = app.ui.pen.as_ref().unwrap(); + assert_eq!(pen.knots, original_first_two); + assert!(!pen.dragging, "undo releases the current Pen drag"); + assert_eq!(app.session.active().unwrap().history.past_len(), old_history, "undo must not roll back previous document changes"); + assert!(app.session.active().unwrap().doc.work_path.is_none(), "path is not committed yet"); + + pen_commit(&mut app, false); + let work = app.session.active().unwrap().doc.work_path.as_ref().unwrap(); + assert_eq!(work.subpaths[0].knots.len(), 2); + assert!(work.subpaths[0].knots[1].smooth, "retained smooth handles are unchanged"); +} + +#[test] +fn pen_undo_of_first_anchor_cancels_empty_draft() { + let mut app = app(); + assert!(!pen_undo_last_point(&mut app)); + pen_down(&mut app, 15.0, 17.0, false); + pen_up(&mut app); + assert!(pen_undo_last_point(&mut app)); + assert!(app.ui.pen.is_none()); + assert!(!pen_undo_last_point(&mut app)); + assert_eq!(app.session.active().unwrap().history.past_len(), 0); + assert!(app.session.active().unwrap().doc.work_path.is_none()); +} + +/// #1419: Solid Color (and every new fill or adjustment layer) made while a path is selected +/// in the Paths panel takes it as its vector mask; with the path deselected, the selection +/// is its layer mask again. +#[test] +fn new_fill_layer_takes_the_selected_path_as_its_vector_mask() { + let mut app = app(); + let layer = |app: &PhotocraftApp, r: Result| { + let id = photocraft_doc::LayerId(r.unwrap()["layer"].as_u64().unwrap()); + app.session.active().unwrap().doc.layer(id).unwrap().clone() + }; + // Drawing a work path with the Pen selects it. + app.ui.tool = Tool::Pen; + for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } + pen_down(&mut app, 20.5, 20.5, false); + pen_up(&mut app); + assert_eq!(app.ui.selected_path.as_deref(), Some("work")); + let wp = app.session.active().unwrap().doc.work_path.clone().unwrap(); + app.run("select.rect", json!({"x": 150, "y": 150, "width": 20, "height": 20})).unwrap(); + for id in ["layer.newFillLayer.solidColor", "layer.newFillLayer.gradient", "layer.newAdjustmentLayer.invert"] { + app.ui.selected_path = Some("work".into()); + let r = app.run(id, json!({})); + let l = layer(&app, r); + assert_eq!(l.vector_mask.as_ref().map(|v| &v.path), Some(&wp), "{id}: the work path is the vector mask"); + assert!(l.mask.is_none(), "{id}: the path wins over the selection"); + // The new layer's vector mask is now the active path, not the work path. + assert_eq!(app.ui.selected_path.as_deref(), Some("layer"), "{id}"); + } + // So the next fill layer isn't masked by the work path again. + let r = app.run("layer.newFillLayer.solidColor", json!({})); + assert!(layer(&app, r).vector_mask.is_none()); + // A caller can opt out. + let r = app.run("layer.newFillLayer.solidColor", json!({"path": null})); + assert!(layer(&app, r).vector_mask.is_none()); + // A selected saved path is used. + app.run("path.set", json!({"name": "Saved", "path": {"subpaths": [{"closed": true, "knots": [[0, 0], [9, 0], [9, 9]]}]}})).unwrap(); + app.ui.selected_path = Some("Saved".into()); + let saved = app.session.active().unwrap().doc.paths[0].path.clone(); + let r = app.run("layer.newFillLayer.solidColor", json!({})); + assert_eq!(layer(&app, r).vector_mask.map(|v| v.path), Some(saved)); + // Deselected (or a stale name): the selection is the layer mask, no vector mask. + for sel in [None, Some("Gone".to_string())] { + app.ui.selected_path = sel; + let r = app.run("layer.newFillLayer.solidColor", json!({})); + let l = layer(&app, r); + assert!(l.vector_mask.is_none() && l.mask.is_some()); + } + // Make Work Path selects the new work path. + app.run("select.toWorkPath", json!({"tolerance": 2.0})).unwrap(); + assert_eq!(app.ui.selected_path.as_deref(), Some("work")); +} + +/// #1482: clicking an existing final Pen anchor breaks its outgoing handle without +/// deleting the preceding curve or creating another knot; dragging changes only that handle. +#[test] +fn pen_last_anchor_can_be_broken_and_reshaped_while_drawing() { + use crate::canvas::{ToolEvent, tool_event}; + let mut app = app(); + app.ui.tool = Tool::Pen; + let down = |app: &mut PhotocraftApp, x, y| tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE); + let move_to = |app: &mut PhotocraftApp, x, y| tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, egui::Modifiers::NONE); + let up = |app: &mut PhotocraftApp, x, y| tool_event(app, ToolEvent::Up { x, y }, egui::Modifiers::NONE); + + down(&mut app, 20.0, 20.0); + up(&mut app, 20.0, 20.0); + down(&mut app, 100.0, 20.0); + move_to(&mut app, 120.0, 40.0); + up(&mut app, 120.0, 40.0); + let original = app.ui.pen.as_ref().unwrap().knots[1]; + assert_eq!(original, [[100.0, 20.0], [80.0, 0.0], [120.0, 40.0]]); + + // Bare click breaks the outgoing handle, preserving the preceding segment's tangent. + down(&mut app, 100.0, 20.0); + up(&mut app, 100.0, 20.0); + let pen = app.ui.pen.as_ref().unwrap(); + assert_eq!(pen.knots.len(), 2); + assert_eq!(pen.knots[1], [[100.0, 20.0], [80.0, 0.0], [100.0, 20.0]]); + assert!(!pen.dragging && !pen.adjusting_last); + + // Re-dragging the same final anchor moves only its outgoing handle (a cusp). + down(&mut app, 100.0, 20.0); + move_to(&mut app, 110.0, 60.0); + up(&mut app, 110.0, 60.0); + let pen = app.ui.pen.as_ref().unwrap(); + assert_eq!(pen.knots.len(), 2); + assert_eq!(pen.knots[1], [[100.0, 20.0], [80.0, 0.0], [110.0, 60.0]]); + + // Drawing on still adds a separate next anchor and keeps the cusp in the work path. + down(&mut app, 150.0, 100.0); + up(&mut app, 150.0, 100.0); + assert_eq!(app.ui.pen.as_ref().unwrap().knots.len(), 3); + pen_commit(&mut app, false); + let work = app.session.active().unwrap().doc.work_path.as_ref().unwrap(); + let k = &work.subpaths[0].knots[1]; + assert_eq!([k.in_ctrl.x, k.in_ctrl.y], [80.0, 0.0]); + assert_eq!([k.out_ctrl.x, k.out_ctrl.y], [110.0, 60.0]); + assert!(!k.smooth, "breaking the handle must persist as an unlinked PSD/vector knot"); +} + +#[test] +fn pen_last_anchor_hit_tolerance_tracks_zoom_and_draft_round_trips() { + for zoom in [0.25, 1.0, 4.0] { + let mut app = app(); + app.ui.views[0].zoom = zoom; + pen_down(&mut app, 20.0, 20.0, false); + pen_up(&mut app); + pen_down(&mut app, 100.0, 100.0, false); + pen_move(&mut app, 110.0, 120.0, false); + pen_up(&mut app); + let incoming = app.ui.pen.as_ref().unwrap().knots[1][1]; + pen_down(&mut app, 100.0 + 5.0 / f64::from(zoom), 100.0, false); + pen_up(&mut app); + let pen = app.ui.pen.as_ref().unwrap(); + assert_eq!(pen.knots.len(), 2); + assert_eq!(pen.knots[1][1], incoming); + assert_eq!(pen.knots[1][2], pen.knots[1][0]); + let saved = serde_json::to_value(pen).unwrap(); + let restored: PenPath = serde_json::from_value(saved).unwrap(); + assert_eq!(restored, *pen); + assert_eq!(pen_to_json(&restored, false)["subpaths"][0]["knots"][1]["smooth"], false); + pen_down(&mut app, 100.0 + 7.0 / f64::from(zoom), 100.0, false); + assert_eq!(app.ui.pen.as_ref().unwrap().knots.len(), 3); + } + let legacy: PenPath = serde_json::from_value(json!({"knots": [[[10, 10], [10, 10], [10, 10]]]})).unwrap(); + assert!(legacy.unlinked.is_empty()); + assert!(!legacy.dragging && !legacy.adjusting_last); +} + +/// #1520: changing one corner through the Properties command must keep the other three +/// independent, remain a live rectangle, and undo/redo as one geometry edit. +#[test] +fn live_rectangle_corner_radius_edit_preserves_other_corners_and_history() { + let mut app = app(); + let created = app.run("shape.create", json!({"kind": "roundedRect", "rect": [10, 10, 150, 100], "radii": [5, 10, 15, 20]})).unwrap(); + let id = created["layer"].as_u64().unwrap(); + let get_radii = |app: &PhotocraftApp| { + let st = app.session.active().unwrap(); + let shape = st.doc.layer(photocraft_doc::LayerId(id)).unwrap(); + match &shape.content { + LayerContent::Shape(sh) => match &sh.live { + Some(photocraft_doc::vector::LiveShape::Rect { radii, .. }) => *radii, + _ => panic!("rectangle must remain a live shape"), + }, + _ => panic!("expected shape layer"), + } + }; + assert_eq!(get_radii(&app), [5.0, 10.0, 15.0, 20.0]); + let mut patch = corner_radii_patch(get_radii(&app), 1, 30.0); + patch["layer"] = json!(id); + app.run("shape.edit", patch).unwrap(); + assert_eq!(get_radii(&app), [5.0, 30.0, 15.0, 20.0]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(get_radii(&app), [5.0, 10.0, 15.0, 20.0]); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(get_radii(&app), [5.0, 30.0, 15.0, 20.0]); + for corner in 0..4 { + let before = get_radii(&app); + let radius = 35.0 + corner as f32; + let mut expected = before; + expected[corner] = f64::from(radius); + let mut patch = corner_radii_patch(before, corner, radius); + patch["layer"] = json!(id); + app.run("shape.edit", patch).unwrap(); + assert_eq!(get_radii(&app), expected); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(get_radii(&app), before); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(get_radii(&app), expected); + } + app.run("shape.edit", json!({"layer": id, "radii": 12})).unwrap(); + assert_eq!(get_radii(&app), [12.0; 4]); +} + +/// #534: dragging in a shape's fill picker, opened from the Properties panel at the right edge +/// of the window, keeps the picker in place (it flipped from side to side as its width +/// followed the colour readouts, which moved it under the pointer). +#[test] +fn shape_colour_picker_stays_put_while_dragging() { + use egui::{PointerButton, vec2}; + use egui_kittest::kittest::Queryable; + let mut app = app(); + let id = app.run("shape.create", json!({"kind": "rect", "rect": [10, 10, 100, 60], "fill": "#3070c0"})).unwrap()["layer"].as_u64().unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + // Fonts set up after the first frame only apply from the next one. + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::Panel::right("properties").resizable(false).exact_size(285.0).show(ui, |ui| shape_properties(app, ui, photocraft_doc::LayerId(id))); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); + h.run_steps(4); + let label = h.query_all(egui_kittest::kittest::by().label("Fill").include_labels()).next().expect("the Fill label").rect(); + // The swatch is right of its label. + let swatch = egui::pos2(label.right() + 17.0, label.center().y); + let press = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>, pos, pressed| { + h.event(egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.step(); + }; + h.hover_at(swatch); + h.step(); + press(&mut h, swatch, true); + press(&mut h, swatch, false); + h.run_steps(3); + let popup = |h: &egui_kittest::Harness<'_, PhotocraftApp>| { + h.ctx.memory(|m| m.areas().visible_layer_ids().into_iter().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))) + }; + let opened = popup(&h).expect("the picker opened"); + let fill = |h: &egui_kittest::Harness<'_, PhotocraftApp>| { + let st = h.state().session.active().unwrap(); + match &st.doc.layer(photocraft_doc::LayerId(id)).unwrap().content { + LayerContent::Shape(sh) => sh.fill.clone(), + _ => None, + } + }; + let before = fill(&h); + // Drag across the picker's colour area. + let start = opened.min + vec2(60.0, opened.height() * 0.5); + h.hover_at(start); + h.step(); + press(&mut h, start, true); + for i in 1..=10 { + h.event(egui::Event::PointerMoved(start + vec2(i as f32 * 5.0, i as f32))); + h.step(); + let r = popup(&h).expect("the picker stays open"); + assert_eq!(r.left_top(), opened.left_top(), "step {i}: the picker moved from {opened:?} to {r:?}"); + assert!(h.ctx.content_rect().contains_rect(r), "step {i}: {r:?} runs off the window"); + } + press(&mut h, start, false); + assert_ne!(fill(&h), before, "the drag picked a colour"); +} + +/// The options bar edits the selected shape's fill and stroke. +#[test] +fn shape_options_bar_edits_the_selected_shape() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut app = app(); + app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); + finish_shape(&mut app, Tool::Rectangle, [20.0, 20.0], [120.0, 100.0], Default::default()); + let shape = |app: &PhotocraftApp| { + let st = app.session.active().unwrap(); + match &st.doc.layer(st.active_layer.unwrap()).unwrap().content { + LayerContent::Shape(sh) => (sh.fill.clone(), sh.stroke.clone()), + _ => panic!("not a shape layer"), + } + }; + assert!(shape(&app).0.is_some() && shape(&app).1.is_none()); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1100.0, 48.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + ui.horizontal_centered(|ui| options_bar(app, ui, Tool::Rectangle)); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(4); + let click_fill = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>| { + let label = h.query_all(egui_kittest::kittest::by().label("Fill:").include_labels()).next().expect("the Fill label").rect(); + let at = egui::pos2(label.right() + h.ctx.global_style().spacing.item_spacing.x + 7.0, label.center().y); + h.hover_at(at); + h.step(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.step(); + } + h.run_steps(2); + }; + // Stroke width. + h.get_all_by_role(Role::SpinButton).next().expect("the stroke width").click(); + h.run(); + for c in "6".chars() { + h.event(egui::Event::Text(c.to_string())); + h.run(); + } + h.key_press(egui::Key::Enter); + h.run_steps(2); + let stroke = shape(h.state()).1.expect("the width field stroked the shape"); + assert_eq!(stroke.width, 6.0); + assert_eq!(stroke.paint, photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(0.0, 0.0, 1.0, 1.0))); + // Fill off. + click_fill(&mut h); + assert_eq!(shape(h.state()).0, None, "unchecking Fill removed the shape's fill"); + assert!(!h.state().ui.tool_options.shape_fill, "and the next shape has none either"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert!(shape(h.state()).0.is_some()); + // No shape selected: no edit. + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + let history = h.state().session.active().unwrap().history.past_len(); + h.run_steps(2); + click_fill(&mut h); + assert_eq!(h.state().session.active().unwrap().history.past_len(), history); +} + +/// #3915: Path Selection and Direct Selection options bars show Fill, Stroke, and Radius +/// controls when a shape is selected, and editing them edits the selected shape. +#[test] +fn path_selection_options_bar_edits_the_selected_shape() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut app = app(); + app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); + finish_shape(&mut app, Tool::Rectangle, [20.0, 20.0], [120.0, 100.0], Default::default()); + let shape = |app: &PhotocraftApp| { + let st = app.session.active().unwrap(); + match &st.doc.layer(st.active_layer.unwrap()).unwrap().content { + LayerContent::Shape(sh) => (sh.fill.clone(), sh.stroke.clone()), + _ => panic!("not a shape layer"), + } + }; + assert!(shape(&app).0.is_some() && shape(&app).1.is_none()); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1100.0, 48.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + ui.horizontal_centered(|ui| options_bar(app, ui, Tool::PathSelection)); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(4); + let click_fill = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>| { + let label = h.query_all(egui_kittest::kittest::by().label("Fill:").include_labels()).next().expect("the Fill label").rect(); + let at = egui::pos2(label.right() + h.ctx.global_style().spacing.item_spacing.x + 7.0, label.center().y); + h.hover_at(at); + h.step(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.step(); + } + h.run_steps(2); + }; + // Stroke width field is available on Path Selection bar too. + h.get_all_by_role(Role::SpinButton).next().expect("the stroke width").click(); + h.run(); + for c in "6".chars() { + h.event(egui::Event::Text(c.to_string())); + h.run(); + } + h.key_press(egui::Key::Enter); + h.run_steps(2); + let stroke = shape(h.state()).1.expect("the width field stroked the shape"); + assert_eq!(stroke.width, 6.0); + assert_eq!(stroke.paint, photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(0.0, 0.0, 1.0, 1.0))); + // Fill toggle. + click_fill(&mut h); + assert_eq!(shape(h.state()).0, None, "unchecking Fill removed the shape's fill"); + // No shape selected: renders hint text instead. + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + h.run_steps(2); + assert!(h.query_all(egui_kittest::kittest::by().label("Fill:").include_labels()).next().is_none()); +} + +/// #6553: a Paths row dragged onto the footer's trash is deleted, whichever row is selected, +/// and a shape layer's path row does not start a drag. +#[test] +fn path_rows_dragged_onto_the_trash_are_deleted() { + use egui_kittest::kittest::Queryable; + let mut app = app(); + let path = json!({"subpaths": [{"closed": true, "knots": [ + {"anchor": [10, 10], "in": [10, 10], "out": [10, 10]}, + {"anchor": [80, 10], "in": [80, 10], "out": [80, 10]}, + {"anchor": [80, 80], "in": [80, 80], "out": [80, 80]} + ]}]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.run("path.set", json!({"name": "work", "path": path})).unwrap(); + app.ui.selected_path = Some("work".into()); + let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 400.0)).build_ui_state(|ui, app: &mut PhotocraftApp| paths_panel(app, ui), app); + h.run_steps(3); + let trash = |h: &egui_kittest::Harness<'_, PhotocraftApp>| { + let buttons: Vec = h + .ctx + .viewport(|v| v.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).filter(|w| w.rect.size() == vec2(26.0, 26.0)).map(|w| w.rect).collect()); + buttons.into_iter().max_by(|a, b| a.center().x.total_cmp(&b.center().x)).unwrap().center() + }; + let drag = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>, from: Pos2, to: Pos2| { + h.event(egui::Event::PointerMoved(from)); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.step(); + for k in 1..=10 { + h.event(egui::Event::PointerMoved(from + (to - from) * (k as f32 / 10.0))); + h.step(); + } + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); + }; + // The saved path, while the work path is selected: only the dragged row goes. + let (row, to) = (h.get_by_label("Path 1").rect().center(), trash(&h)); + drag(&mut h, row, to); + let doc = &h.state().session.active().unwrap().doc; + assert!(doc.paths.is_empty(), "the dragged saved path is deleted"); + assert!(doc.work_path.is_some(), "the selected work path is kept"); + // The work path. + let (row, to) = (h.get_by_label("Work Path").rect().center(), trash(&h)); + drag(&mut h, row, to); + assert!(h.state().session.active().unwrap().doc.work_path.is_none(), "the dragged work path is deleted"); + // A drop elsewhere deletes nothing. + h.state_mut().run("path.set", json!({"name": "Path 2", "path": path})).unwrap(); + h.run_steps(2); + let row = h.get_by_label("Path 2").rect().center(); + drag(&mut h, row, row + vec2(0.0, 120.0)); + assert_eq!(h.state().session.active().unwrap().doc.paths.len(), 1, "a drop off the trash keeps the path"); + // A shape layer's path row is not dragged onto the trash (its deletion is #6552's). + h.state_mut().run("shape.create", json!({"kind": "ellipse", "rect": [20, 20, 100, 70]})).unwrap(); + h.run_steps(2); + let layers = h.state().session.active().unwrap().doc.layers.len(); + let (row, to) = (h.get_by_label("Ellipse 1 Shape Path").rect().center(), trash(&h)); + drag(&mut h, row, to); + let doc = &h.state().session.active().unwrap().doc; + assert_eq!((doc.layers.len(), doc.paths.len()), (layers, 1), "nothing is deleted"); +} From 03733c166947b8e2697e78eb74f1b4ebde18741b Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:30 +0000 Subject: [PATCH 053/259] refactor(ui-egui): move blend_keys.rs tests to blend_keys/tests.rs --- crates/ui-egui/src/blend_keys.rs | 435 +------------------------ crates/ui-egui/src/blend_keys/tests.rs | 432 ++++++++++++++++++++++++ 2 files changed, 433 insertions(+), 434 deletions(-) create mode 100644 crates/ui-egui/src/blend_keys/tests.rs diff --git a/crates/ui-egui/src/blend_keys.rs b/crates/ui-egui/src/blend_keys.rs index f954cbd3c4..6339b64c24 100644 --- a/crates/ui-egui/src/blend_keys.rs +++ b/crates/ui-egui/src/blend_keys.rs @@ -279,437 +279,4 @@ pub fn pick_mode(app: &mut PhotocraftApp, pick: Pick) { } #[cfg(test)] -mod tests { - use super::*; - - 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 - } - - fn layer_blend(app: &PhotocraftApp) -> BlendMode { - let st = app.session.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().blend - } - - /// Feeds one key press with `modifiers` through the app's shortcut handling. - fn key(app: &mut PhotocraftApp, ctx: &egui::Context, key: Key, modifiers: egui::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(); - } - - /// #3102: on a German layout ⇧+ types `*`, which egui reports as the physical `]`, and ⇧- types - /// `_` as the physical `/`. With the Brush they step its mode, not its hardness; a US ⇧] (`}`) - /// still raises the hardness. - #[test] - fn german_shift_plus_and_minus_step_the_mode_and_us_shift_bracket_keeps_the_hardness() { - let ctx = egui::Context::default(); - let mut a = app(Tool::Brush); - a.session.tools.brush.hardness = 0.5; - let shift = egui::Modifiers::SHIFT; - let typed = |a: &mut PhotocraftApp, key: Key, physical_key: Key, text: &str| { - let press = egui::Event::Key { key, physical_key: Some(physical_key), pressed: true, repeat: false, modifiers: shift }; - let raw = egui::RawInput { events: vec![egui::Event::ModifiersChanged(shift), press, egui::Event::Text(text.into())], ..Default::default() }; - ctx.begin_pass(raw); - crate::shortcuts::handle(a, &ctx); - ctx.end_pass().textures_delta.clear(); - }; - typed(&mut a, Key::CloseBracket, Key::CloseBracket, "*"); - assert_eq!(a.session.tools.brush.mode, BlendMode::Dissolve); - assert_eq!(a.session.tools.brush.hardness, 0.5, "not Increase Brush Hardness"); - typed(&mut a, Key::Slash, Key::Slash, "_"); - assert_eq!(a.session.tools.brush.mode, BlendMode::Normal); - // US: ⇧] arrives as `}` from the physical `]`. - typed(&mut a, Key::CloseCurlyBracket, Key::CloseBracket, "}"); - assert!(a.session.tools.brush.hardness > 0.5); - assert_eq!(a.session.tools.brush.mode, BlendMode::Normal); - } - - #[test] - fn stepping_wraps_at_both_ends() { - let m = BlendMode::LAYER_MODES; - assert_eq!(stepped(&m, BlendMode::Normal, 1), Some(BlendMode::Dissolve)); - assert_eq!(stepped(&m, BlendMode::Normal, -1), m.last().copied()); - assert_eq!(stepped(&m, m[m.len() - 1], 1), Some(BlendMode::Normal)); - assert_eq!(stepped(&[], BlendMode::Normal, 1), None); - } - - /// #3102: with the Move tool ⇧+ / ⇧− step the active layer's mode, one undo step each; with - /// the Brush they step the brush's mode and leave the layer alone. - #[test] - fn shift_plus_and_minus_step_the_layer_or_the_brush_mode() { - let ctx = egui::Context::default(); - let mut a = app(Tool::Move); - let undo = a.session.active().unwrap().history.past_len(); - key(&mut a, &ctx, Key::Plus, egui::Modifiers::SHIFT); - assert_eq!(layer_blend(&a), BlendMode::Dissolve); - key(&mut a, &ctx, Key::Plus, egui::Modifiers::SHIFT); - assert_eq!(layer_blend(&a), BlendMode::Darken); - key(&mut a, &ctx, Key::Minus, egui::Modifiers::SHIFT); - assert_eq!(layer_blend(&a), BlendMode::Dissolve); - assert_eq!(a.session.active().unwrap().history.past_len(), undo + 3, "one undo step per press"); - // Unshifted or ⌘ presses are not blend-mode keys. - key(&mut a, &ctx, Key::Minus, egui::Modifiers::NONE); - key(&mut a, &ctx, Key::Plus, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT); - assert_eq!(layer_blend(&a), BlendMode::Dissolve); - a.ui.tool = Tool::Brush; - key(&mut a, &ctx, Key::Minus, egui::Modifiers::SHIFT); - assert_eq!(a.session.tools.brush.mode, BlendMode::LAYER_MODES[BlendMode::LAYER_MODES.len() - 1]); - assert_eq!(layer_blend(&a), BlendMode::Dissolve, "the layer is untouched"); - // The Background keeps Normal; no document is a no-op. - a.ui.tool = Tool::Move; - let bg = a.session.active().unwrap().doc.layers[0].id; - a.run("layer.select", json!({"layer": bg.0})).unwrap(); - key(&mut a, &ctx, Key::Plus, egui::Modifiers::SHIFT); - assert_eq!(a.session.active().unwrap().doc.layers[0].blend, BlendMode::Normal); - let mut none = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - press(&mut none, 1); - } - - /// Feeds one ⇧⌥ press of `key`, reported by the platform as `physical` too. - fn alt_shift(app: &mut PhotocraftApp, ctx: &egui::Context, key: Key, physical: Key) { - let m = egui::Modifiers::SHIFT | egui::Modifiers::ALT; - let raw = egui::RawInput { - events: vec![egui::Event::ModifiersChanged(m), egui::Event::Key { key, physical_key: Some(physical), pressed: true, repeat: false, modifiers: m }], - ..Default::default() - }; - ctx.begin_pass(raw); - crate::shortcuts::handle(app, ctx); - ctx.end_pass().textures_delta.clear(); - } - - fn blend_of(app: &PhotocraftApp, i: usize) -> BlendMode { - app.session.active().unwrap().doc.layers[i].blend - } - - /// Photoshop's letters: 26 keys, each a different mode, and the four modes without one. - #[test] - fn every_letter_picks_its_own_mode() { - let keys: Vec = "NIQRPKMBAGSDWOFHVJZLEXUTCY".chars().filter_map(|c| Key::from_name(&c.to_string())).collect(); - assert_eq!(keys.len(), 26); - let picks: Vec = keys.iter().filter_map(|k| letter_pick(*k)).collect(); - assert_eq!(picks.len(), keys.len()); - for (i, p) in picks.iter().enumerate() { - assert!(!picks[..i].contains(p), "{p:?} has two letters"); - } - assert_eq!(letter_pick(Key::M), Some(Pick::Mode(BlendMode::Multiply))); - assert_eq!(letter_pick(Key::W), Some(Pick::Mode(BlendMode::LinearDodge))); - assert_eq!(letter_pick(Key::Y), Some(Pick::Mode(BlendMode::Luminosity))); - for m in [BlendMode::DarkerColor, BlendMode::LighterColor, BlendMode::Subtract, BlendMode::Divide] { - assert!(!picks.contains(&Pick::Mode(m)), "{m:?} has no letter in Photoshop"); - } - for k in [Key::Num1, Key::Space] { - assert_eq!(letter_pick(k), None); - } - } - - /// With the Move tool ⇧⌥M makes the active layer Multiply in one undo step, and doesn't switch - /// to the Marquee tool's M. Clear and Behind are painting modes: a layer ignores them. - #[test] - fn alt_shift_letter_sets_the_layer_mode_and_keeps_the_tool() { - let ctx = egui::Context::default(); - let mut a = app(Tool::Move); - let undo = a.session.active().unwrap().history.past_len(); - alt_shift(&mut a, &ctx, Key::M, Key::M); - assert_eq!(layer_blend(&a), BlendMode::Multiply); - assert_eq!(a.ui.tool, Tool::Move, "not the Marquee tool"); - assert_eq!(a.session.active().unwrap().history.past_len(), undo + 1); - alt_shift(&mut a, &ctx, Key::R, Key::R); - alt_shift(&mut a, &ctx, Key::Q, Key::Q); - alt_shift(&mut a, &ctx, Key::P, Key::P); - assert_eq!(layer_blend(&a), BlendMode::Multiply, "no Clear, Behind or Pass Through on a layer"); - assert_eq!(a.ui.tool, Tool::Move); - // ⇧⌥ letters that are tool keys pick modes too. - alt_shift(&mut a, &ctx, Key::S, Key::S); - assert_eq!(layer_blend(&a), BlendMode::Screen); - assert_eq!(a.ui.tool, Tool::Move); - } - - /// A Mac's ⌥ turns the letter into another character; egui then reports the physical key. - /// A German layout's Z (physical Y) is still Pin Light: the typed letter wins. - #[test] - fn the_typed_letter_wins_and_the_physical_key_is_the_fallback() { - let ctx = egui::Context::default(); - let mut a = app(Tool::Move); - alt_shift(&mut a, &ctx, Key::Backtick, Key::O); - assert_eq!(layer_blend(&a), BlendMode::Overlay); - alt_shift(&mut a, &ctx, Key::Z, Key::Y); - assert_eq!(layer_blend(&a), BlendMode::PinLight); - } - - /// Every selected layer takes the mode, all in one undo step; the Background keeps Normal. - /// ⇧+ steps them all to the mode after the active layer's. - #[test] - fn mode_keys_set_every_selected_layer_in_one_undo_step() { - let ctx = egui::Context::default(); - let mut a = app(Tool::Move); - let ids: Vec = a.session.active().unwrap().doc.layers.iter().map(|l| l.id.0).collect(); - a.run("layer.new.layer", json!({})).unwrap(); - for id in &ids { - a.run("layer.select", json!({"layer": id, "mode": "add"})).unwrap(); - } - assert_eq!(a.session.active().unwrap().selected_layers().len(), 3); - let undo = a.session.active().unwrap().history.past_len(); - alt_shift(&mut a, &ctx, Key::S, Key::S); - assert_eq!([blend_of(&a, 0), blend_of(&a, 1), blend_of(&a, 2)], [BlendMode::Normal, BlendMode::Screen, BlendMode::Screen]); - assert_eq!(a.session.active().unwrap().history.past_len(), undo + 1, "one undo step for both layers"); - key(&mut a, &ctx, Key::Plus, egui::Modifiers::SHIFT); - assert_eq!([blend_of(&a, 1), blend_of(&a, 2)], [BlendMode::ColorDodge, BlendMode::ColorDodge]); - assert_eq!(a.session.active().unwrap().history.past_len(), undo + 2); - a.session.undo(); - assert_eq!([blend_of(&a, 1), blend_of(&a, 2)], [BlendMode::Screen, BlendMode::Screen]); - } - - /// ⇧⌥P is Pass Through, for groups only. - #[test] - fn pass_through_is_for_groups() { - let ctx = egui::Context::default(); - let mut a = app(Tool::Move); - a.run("layer.new.group", json!({})).unwrap(); - alt_shift(&mut a, &ctx, Key::N, Key::N); - assert_eq!(layer_blend(&a), BlendMode::Normal); - alt_shift(&mut a, &ctx, Key::P, Key::P); - assert_eq!(layer_blend(&a), BlendMode::PassThrough); - } - - /// With the Brush the letters set the brush's mode, Clear included, and never the layer's; - /// ⇧+ from Dissolve reaches Clear, as in the dropdown. The Pencil keeps its own Clear. - #[test] - fn with_a_painting_tool_the_letters_set_only_its_mode() { - let ctx = egui::Context::default(); - let mut a = app(Tool::Brush); - alt_shift(&mut a, &ctx, Key::M, Key::M); - assert_eq!(a.session.tools.brush.mode, BlendMode::Multiply); - assert_eq!(layer_blend(&a), BlendMode::Normal, "the layer is untouched"); - assert_eq!(a.ui.tool, Tool::Brush); - alt_shift(&mut a, &ctx, Key::R, Key::R); - assert!(a.ui.tool_options.brush_clear); - alt_shift(&mut a, &ctx, Key::P, Key::P); - assert!(a.ui.tool_options.brush_clear, "no Pass Through for a brush"); - alt_shift(&mut a, &ctx, Key::I, Key::I); - assert!(!a.ui.tool_options.brush_clear); - assert_eq!(a.session.tools.brush.mode, BlendMode::Dissolve); - key(&mut a, &ctx, Key::Plus, egui::Modifiers::SHIFT); - assert!(a.ui.tool_options.brush_clear, "Clear follows Dissolve"); - key(&mut a, &ctx, Key::Plus, egui::Modifiers::SHIFT); - assert!(!a.ui.tool_options.brush_clear); - assert_eq!(a.session.tools.brush.mode, BlendMode::Darken); - assert!(!a.ui.tool_options.pencil_clear); - a.ui.tool = Tool::Pencil; - alt_shift(&mut a, &ctx, Key::R, Key::R); - assert!(a.ui.tool_options.pencil_clear); - assert_eq!(layer_blend(&a), BlendMode::Normal); - } - - /// The Gradient takes the letters; Smudge, which has a blend mode in Photoshop but no Mode - /// control here yet, ignores them rather than changing the layer. - #[test] - fn gradient_takes_the_letters_and_smudge_ignores_them() { - let ctx = egui::Context::default(); - let mut a = app(Tool::Gradient); - alt_shift(&mut a, &ctx, Key::O, Key::O); - assert_eq!(a.ui.tool_options.gradient_blend_mode, BlendMode::Overlay); - alt_shift(&mut a, &ctx, Key::R, Key::R); - assert_eq!(a.ui.tool_options.gradient_blend_mode, BlendMode::Overlay, "no Clear for the Gradient"); - a.ui.tool = Tool::Smudge; - alt_shift(&mut a, &ctx, Key::M, Key::M); - assert_eq!(layer_blend(&a), BlendMode::Normal); - assert_eq!(a.ui.tool, Tool::Smudge); - let mut none = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - pick_mode(&mut none, Pick::Mode(BlendMode::Multiply)); - } - - /// With a Free Transform box open, ⇧⌥ letters and the number keys still go where the tool - /// sends them: the Brush's mode and opacity with the Brush, the layer's with the Move tool. - /// They never pick a tool, so the box stays open, and Enter keeps both the transform and the - /// layer's new mode. Puppet Warp keeps them to itself: its preview is a snapshot taken when it - /// started, so a change made meanwhile wouldn't show, and Esc wouldn't take it back. - #[test] - fn keys_follow_the_tool_while_a_transform_is_open_and_a_warp_keeps_them() { - let ctx = egui::Context::default(); - let mut a = app(Tool::Brush); - a.run("select.rect", json!({"x": 4, "y": 4, "width": 12, "height": 12})).unwrap(); - a.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - a.run("select.deselect", json!({})).unwrap(); - a.sync_views(); - crate::transform_tool::begin(&mut a, &ctx).unwrap(); - crate::transform_tool::nudge(&mut a, 3.0, 0.0); - let shift_alt = egui::Modifiers::SHIFT | egui::Modifiers::ALT; - let opacity = |a: &PhotocraftApp| { - let st = a.session.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().opacity - }; - // The Brush: its own mode and opacity. - key(&mut a, &ctx, Key::M, shift_alt); - assert_eq!(a.session.tools.brush.mode, BlendMode::Multiply); - key(&mut a, &ctx, Key::Num5, egui::Modifiers::NONE); - assert!((a.session.tools.brush.opacity - 0.5).abs() < 1e-6); - assert_eq!((layer_blend(&a), opacity(&a)), (BlendMode::Normal, 1.0), "the layer is left alone"); - assert!(a.ui.transform.is_some(), "the box stays open"); - assert_eq!(a.ui.tool, Tool::Brush, "no tool letter"); - // The Move tool: the layer's. - a.ui.tool = Tool::Move; - a.opacity_keys = None; - key(&mut a, &ctx, Key::E, shift_alt); - key(&mut a, &ctx, Key::Num7, egui::Modifiers::NONE); - assert_eq!(layer_blend(&a), BlendMode::Difference); - assert!((opacity(&a) - 0.7).abs() < 1e-6, "{}", opacity(&a)); - assert!(a.ui.transform.is_some()); - key(&mut a, &ctx, Key::Enter, egui::Modifiers::NONE); - assert!(a.ui.transform.is_none()); - let st = a.session.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); - assert_eq!(l.blend, BlendMode::Difference, "the commit keeps it"); - assert_eq!(l.surface().unwrap().content_bounds().x0, 7, "and the move"); - let l_opacity = l.opacity; - // Puppet Warp: nothing reaches the layer, the Brush or the History. - crate::distort_ui::menu(&mut a, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); - assert!(a.distort.puppet.is_some()); - let undo = a.session.active().unwrap().history.past_len(); - a.opacity_keys = None; - key(&mut a, &ctx, Key::S, shift_alt); - key(&mut a, &ctx, Key::Plus, egui::Modifiers::SHIFT); - key(&mut a, &ctx, Key::Num3, egui::Modifiers::NONE); - a.ui.tool = Tool::Brush; - key(&mut a, &ctx, Key::H, shift_alt); - key(&mut a, &ctx, Key::Num9, egui::Modifiers::NONE); - assert_eq!((layer_blend(&a), opacity(&a)), (BlendMode::Difference, l_opacity), "the layer under the warp is left alone"); - assert_eq!(a.session.tools.brush.mode, BlendMode::Multiply); - assert!((a.session.tools.brush.opacity - 0.5).abs() < 1e-6); - assert_eq!(a.session.active().unwrap().history.past_len(), undo, "no History step behind the warp"); - assert!(a.distort.puppet.is_some(), "the warp stays open"); - // Perspective Warp too. - key(&mut a, &ctx, Key::Escape, egui::Modifiers::NONE); - assert!(a.distort.puppet.is_none()); - a.ui.tool = Tool::Move; - crate::distort_ui::menu(&mut a, &ctx, "edit.perspectiveWarp", &json!({})).unwrap().unwrap(); - assert!(a.distort.perspective.is_some()); - key(&mut a, &ctx, Key::S, shift_alt); - key(&mut a, &ctx, Key::Num3, egui::Modifiers::NONE); - assert_eq!((layer_blend(&a), opacity(&a)), (BlendMode::Difference, l_opacity)); - assert_eq!(a.session.active().unwrap().history.past_len(), undo); - assert!(a.distort.perspective.is_some()); - } - - /// The stamps and the History Brush keep their mode in their own brush: the keys set it there, - /// never the layer's, and another tool's brush keeps its own. - #[test] - fn clone_stamp_pattern_stamp_and_history_brush_take_the_keys_into_their_own_brush() { - let ctx = egui::Context::default(); - let mut a = app(Tool::Brush); - alt_shift(&mut a, &ctx, Key::M, Key::M); - for (tool, key, mode) in - [(Tool::CloneStamp, Key::S, BlendMode::Screen), (Tool::PatternStamp, Key::O, BlendMode::Overlay), (Tool::HistoryBrush, Key::K, BlendMode::Darken)] - { - a.ui.tool = tool; - assert_eq!(tool_mode(&mut a), Some(BlendMode::Normal), "{tool:?} starts in Normal"); - alt_shift(&mut a, &ctx, key, key); - assert_eq!(tool_mode(&mut a), Some(mode), "{tool:?}"); - alt_shift(&mut a, &ctx, Key::R, Key::R); - assert_eq!(tool_mode(&mut a), Some(mode), "{tool:?} has no Clear"); - key_press(&mut a, &ctx, 1); - assert_ne!(tool_mode(&mut a), Some(mode), "{tool:?} steps"); - assert_eq!(layer_blend(&a), BlendMode::Normal, "{tool:?} leaves the layer alone"); - } - a.ui.tool = Tool::Brush; - assert_eq!(tool_mode(&mut a), Some(BlendMode::Multiply), "the Brush keeps its own mode"); - } - - fn key_press(a: &mut PhotocraftApp, ctx: &egui::Context, step: i32) { - key(a, ctx, if step > 0 { Key::Plus } else { Key::Minus }, egui::Modifiers::SHIFT); - } - - /// The Healing Brush's menu is short: letters outside it do nothing, and ⇧+ steps within it. - #[test] - fn healing_brush_takes_only_its_own_modes() { - let ctx = egui::Context::default(); - let mut a = app(Tool::Healing); - alt_shift(&mut a, &ctx, Key::O, Key::O); - assert_eq!(tool_mode(&mut a), Some(BlendMode::Normal), "Overlay isn't a Healing mode"); - alt_shift(&mut a, &ctx, Key::Y, Key::Y); - assert_eq!(tool_mode(&mut a), Some(BlendMode::Luminosity)); - key_press(&mut a, &ctx, 1); - assert_eq!(tool_mode(&mut a), Some(BlendMode::Normal), "wraps within the Healing list"); - key_press(&mut a, &ctx, 1); - assert_eq!(tool_mode(&mut a), Some(BlendMode::Multiply)); - assert_eq!(layer_blend(&a), BlendMode::Normal); - } - - /// A Healing Brush whose brush holds Overlay (outside its menu) counts as Normal for the keys, - /// as for its stroke: ⇧+ steps on to Multiply. - #[test] - fn healing_brush_with_a_mode_outside_its_menu_steps_from_normal() { - let ctx = egui::Context::default(); - let mut a = app(Tool::Healing); - crate::paint_mouse::sync_tool_brush(&mut a); - a.session.tools.brush.mode = BlendMode::Overlay; - assert_eq!(tool_mode(&mut a), Some(BlendMode::Normal)); - key_press(&mut a, &ctx, 1); - assert_eq!(tool_mode(&mut a), Some(BlendMode::Multiply)); - } - - /// The Paint Bucket has its own Mode, Clear included. - #[test] - fn paint_bucket_takes_the_keys_with_clear() { - let ctx = egui::Context::default(); - let mut a = app(Tool::PaintBucket); - alt_shift(&mut a, &ctx, Key::M, Key::M); - assert_eq!(a.ui.tool_options.bucket_blend_mode, BlendMode::Multiply); - alt_shift(&mut a, &ctx, Key::R, Key::R); - assert!(a.ui.tool_options.bucket_clear); - key_press(&mut a, &ctx, 1); - assert!(!a.ui.tool_options.bucket_clear); - assert_eq!(a.ui.tool_options.bucket_blend_mode, BlendMode::Darken, "Clear is followed by Darken"); - assert_eq!(layer_blend(&a), BlendMode::Normal); - } - - /// Tools without a blend mode of their own (the Erasers, the Mixer Brush) pass the keys to the - /// selected layers, as Photoshop does. - #[test] - fn tools_without_a_blend_mode_set_the_layer() { - let ctx = egui::Context::default(); - for (tool, key, mode) in - [(Tool::Eraser, Key::M, BlendMode::Multiply), (Tool::MagicEraser, Key::S, BlendMode::Screen), (Tool::MixerBrush, Key::E, BlendMode::Difference)] - { - let mut a = app(tool); - alt_shift(&mut a, &ctx, key, key); - assert_eq!(layer_blend(&a), mode, "{tool:?}"); - assert_eq!(a.ui.tool, tool); - } - } - - /// Dodge, Burn and Sponge use ⇧⌥S/M/H and ⇧⌥D/S for their own Range and mode in Photoshop, so - /// neither the letters nor ⇧+ change the layer's blend mode. - #[test] - fn dodge_burn_and_sponge_leave_the_layer_alone() { - let ctx = egui::Context::default(); - for tool in [Tool::Dodge, Tool::Burn, Tool::Sponge] { - let mut a = app(tool); - for k in [Key::S, Key::M, Key::H, Key::D] { - alt_shift(&mut a, &ctx, k, k); - } - key_press(&mut a, &ctx, 1); - assert_eq!(layer_blend(&a), BlendMode::Normal, "{tool:?}"); - assert_eq!(a.ui.tool, tool); - } - } - - #[test] - fn art_history_brush_leaves_the_layer_alone() { - // Photoshop's Art History Brush has a Mode of its own; ours has no Mode control yet. - let ctx = egui::Context::default(); - let mut a = app(Tool::ArtHistoryBrush); - alt_shift(&mut a, &ctx, Key::M, Key::M); - key_press(&mut a, &ctx, 1); - assert_eq!(layer_blend(&a), BlendMode::Normal); - assert_eq!(a.ui.tool, Tool::ArtHistoryBrush); - } -} +mod tests; diff --git a/crates/ui-egui/src/blend_keys/tests.rs b/crates/ui-egui/src/blend_keys/tests.rs new file mode 100644 index 0000000000..d9ef4d1a8b --- /dev/null +++ b/crates/ui-egui/src/blend_keys/tests.rs @@ -0,0 +1,432 @@ +use super::*; + +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 +} + +fn layer_blend(app: &PhotocraftApp) -> BlendMode { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().blend +} + +/// Feeds one key press with `modifiers` through the app's shortcut handling. +fn key(app: &mut PhotocraftApp, ctx: &egui::Context, key: Key, modifiers: egui::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(); +} + +/// #3102: on a German layout ⇧+ types `*`, which egui reports as the physical `]`, and ⇧- types +/// `_` as the physical `/`. With the Brush they step its mode, not its hardness; a US ⇧] (`}`) +/// still raises the hardness. +#[test] +fn german_shift_plus_and_minus_step_the_mode_and_us_shift_bracket_keeps_the_hardness() { + let ctx = egui::Context::default(); + let mut a = app(Tool::Brush); + a.session.tools.brush.hardness = 0.5; + let shift = egui::Modifiers::SHIFT; + let typed = |a: &mut PhotocraftApp, key: Key, physical_key: Key, text: &str| { + let press = egui::Event::Key { key, physical_key: Some(physical_key), pressed: true, repeat: false, modifiers: shift }; + let raw = egui::RawInput { events: vec![egui::Event::ModifiersChanged(shift), press, egui::Event::Text(text.into())], ..Default::default() }; + ctx.begin_pass(raw); + crate::shortcuts::handle(a, &ctx); + ctx.end_pass().textures_delta.clear(); + }; + typed(&mut a, Key::CloseBracket, Key::CloseBracket, "*"); + assert_eq!(a.session.tools.brush.mode, BlendMode::Dissolve); + assert_eq!(a.session.tools.brush.hardness, 0.5, "not Increase Brush Hardness"); + typed(&mut a, Key::Slash, Key::Slash, "_"); + assert_eq!(a.session.tools.brush.mode, BlendMode::Normal); + // US: ⇧] arrives as `}` from the physical `]`. + typed(&mut a, Key::CloseCurlyBracket, Key::CloseBracket, "}"); + assert!(a.session.tools.brush.hardness > 0.5); + assert_eq!(a.session.tools.brush.mode, BlendMode::Normal); +} + +#[test] +fn stepping_wraps_at_both_ends() { + let m = BlendMode::LAYER_MODES; + assert_eq!(stepped(&m, BlendMode::Normal, 1), Some(BlendMode::Dissolve)); + assert_eq!(stepped(&m, BlendMode::Normal, -1), m.last().copied()); + assert_eq!(stepped(&m, m[m.len() - 1], 1), Some(BlendMode::Normal)); + assert_eq!(stepped(&[], BlendMode::Normal, 1), None); +} + +/// #3102: with the Move tool ⇧+ / ⇧− step the active layer's mode, one undo step each; with +/// the Brush they step the brush's mode and leave the layer alone. +#[test] +fn shift_plus_and_minus_step_the_layer_or_the_brush_mode() { + let ctx = egui::Context::default(); + let mut a = app(Tool::Move); + let undo = a.session.active().unwrap().history.past_len(); + key(&mut a, &ctx, Key::Plus, egui::Modifiers::SHIFT); + assert_eq!(layer_blend(&a), BlendMode::Dissolve); + key(&mut a, &ctx, Key::Plus, egui::Modifiers::SHIFT); + assert_eq!(layer_blend(&a), BlendMode::Darken); + key(&mut a, &ctx, Key::Minus, egui::Modifiers::SHIFT); + assert_eq!(layer_blend(&a), BlendMode::Dissolve); + assert_eq!(a.session.active().unwrap().history.past_len(), undo + 3, "one undo step per press"); + // Unshifted or ⌘ presses are not blend-mode keys. + key(&mut a, &ctx, Key::Minus, egui::Modifiers::NONE); + key(&mut a, &ctx, Key::Plus, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT); + assert_eq!(layer_blend(&a), BlendMode::Dissolve); + a.ui.tool = Tool::Brush; + key(&mut a, &ctx, Key::Minus, egui::Modifiers::SHIFT); + assert_eq!(a.session.tools.brush.mode, BlendMode::LAYER_MODES[BlendMode::LAYER_MODES.len() - 1]); + assert_eq!(layer_blend(&a), BlendMode::Dissolve, "the layer is untouched"); + // The Background keeps Normal; no document is a no-op. + a.ui.tool = Tool::Move; + let bg = a.session.active().unwrap().doc.layers[0].id; + a.run("layer.select", json!({"layer": bg.0})).unwrap(); + key(&mut a, &ctx, Key::Plus, egui::Modifiers::SHIFT); + assert_eq!(a.session.active().unwrap().doc.layers[0].blend, BlendMode::Normal); + let mut none = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + press(&mut none, 1); +} + +/// Feeds one ⇧⌥ press of `key`, reported by the platform as `physical` too. +fn alt_shift(app: &mut PhotocraftApp, ctx: &egui::Context, key: Key, physical: Key) { + let m = egui::Modifiers::SHIFT | egui::Modifiers::ALT; + let raw = egui::RawInput { + events: vec![egui::Event::ModifiersChanged(m), egui::Event::Key { key, physical_key: Some(physical), pressed: true, repeat: false, modifiers: m }], + ..Default::default() + }; + ctx.begin_pass(raw); + crate::shortcuts::handle(app, ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn blend_of(app: &PhotocraftApp, i: usize) -> BlendMode { + app.session.active().unwrap().doc.layers[i].blend +} + +/// Photoshop's letters: 26 keys, each a different mode, and the four modes without one. +#[test] +fn every_letter_picks_its_own_mode() { + let keys: Vec = "NIQRPKMBAGSDWOFHVJZLEXUTCY".chars().filter_map(|c| Key::from_name(&c.to_string())).collect(); + assert_eq!(keys.len(), 26); + let picks: Vec = keys.iter().filter_map(|k| letter_pick(*k)).collect(); + assert_eq!(picks.len(), keys.len()); + for (i, p) in picks.iter().enumerate() { + assert!(!picks[..i].contains(p), "{p:?} has two letters"); + } + assert_eq!(letter_pick(Key::M), Some(Pick::Mode(BlendMode::Multiply))); + assert_eq!(letter_pick(Key::W), Some(Pick::Mode(BlendMode::LinearDodge))); + assert_eq!(letter_pick(Key::Y), Some(Pick::Mode(BlendMode::Luminosity))); + for m in [BlendMode::DarkerColor, BlendMode::LighterColor, BlendMode::Subtract, BlendMode::Divide] { + assert!(!picks.contains(&Pick::Mode(m)), "{m:?} has no letter in Photoshop"); + } + for k in [Key::Num1, Key::Space] { + assert_eq!(letter_pick(k), None); + } +} + +/// With the Move tool ⇧⌥M makes the active layer Multiply in one undo step, and doesn't switch +/// to the Marquee tool's M. Clear and Behind are painting modes: a layer ignores them. +#[test] +fn alt_shift_letter_sets_the_layer_mode_and_keeps_the_tool() { + let ctx = egui::Context::default(); + let mut a = app(Tool::Move); + let undo = a.session.active().unwrap().history.past_len(); + alt_shift(&mut a, &ctx, Key::M, Key::M); + assert_eq!(layer_blend(&a), BlendMode::Multiply); + assert_eq!(a.ui.tool, Tool::Move, "not the Marquee tool"); + assert_eq!(a.session.active().unwrap().history.past_len(), undo + 1); + alt_shift(&mut a, &ctx, Key::R, Key::R); + alt_shift(&mut a, &ctx, Key::Q, Key::Q); + alt_shift(&mut a, &ctx, Key::P, Key::P); + assert_eq!(layer_blend(&a), BlendMode::Multiply, "no Clear, Behind or Pass Through on a layer"); + assert_eq!(a.ui.tool, Tool::Move); + // ⇧⌥ letters that are tool keys pick modes too. + alt_shift(&mut a, &ctx, Key::S, Key::S); + assert_eq!(layer_blend(&a), BlendMode::Screen); + assert_eq!(a.ui.tool, Tool::Move); +} + +/// A Mac's ⌥ turns the letter into another character; egui then reports the physical key. +/// A German layout's Z (physical Y) is still Pin Light: the typed letter wins. +#[test] +fn the_typed_letter_wins_and_the_physical_key_is_the_fallback() { + let ctx = egui::Context::default(); + let mut a = app(Tool::Move); + alt_shift(&mut a, &ctx, Key::Backtick, Key::O); + assert_eq!(layer_blend(&a), BlendMode::Overlay); + alt_shift(&mut a, &ctx, Key::Z, Key::Y); + assert_eq!(layer_blend(&a), BlendMode::PinLight); +} + +/// Every selected layer takes the mode, all in one undo step; the Background keeps Normal. +/// ⇧+ steps them all to the mode after the active layer's. +#[test] +fn mode_keys_set_every_selected_layer_in_one_undo_step() { + let ctx = egui::Context::default(); + let mut a = app(Tool::Move); + let ids: Vec = a.session.active().unwrap().doc.layers.iter().map(|l| l.id.0).collect(); + a.run("layer.new.layer", json!({})).unwrap(); + for id in &ids { + a.run("layer.select", json!({"layer": id, "mode": "add"})).unwrap(); + } + assert_eq!(a.session.active().unwrap().selected_layers().len(), 3); + let undo = a.session.active().unwrap().history.past_len(); + alt_shift(&mut a, &ctx, Key::S, Key::S); + assert_eq!([blend_of(&a, 0), blend_of(&a, 1), blend_of(&a, 2)], [BlendMode::Normal, BlendMode::Screen, BlendMode::Screen]); + assert_eq!(a.session.active().unwrap().history.past_len(), undo + 1, "one undo step for both layers"); + key(&mut a, &ctx, Key::Plus, egui::Modifiers::SHIFT); + assert_eq!([blend_of(&a, 1), blend_of(&a, 2)], [BlendMode::ColorDodge, BlendMode::ColorDodge]); + assert_eq!(a.session.active().unwrap().history.past_len(), undo + 2); + a.session.undo(); + assert_eq!([blend_of(&a, 1), blend_of(&a, 2)], [BlendMode::Screen, BlendMode::Screen]); +} + +/// ⇧⌥P is Pass Through, for groups only. +#[test] +fn pass_through_is_for_groups() { + let ctx = egui::Context::default(); + let mut a = app(Tool::Move); + a.run("layer.new.group", json!({})).unwrap(); + alt_shift(&mut a, &ctx, Key::N, Key::N); + assert_eq!(layer_blend(&a), BlendMode::Normal); + alt_shift(&mut a, &ctx, Key::P, Key::P); + assert_eq!(layer_blend(&a), BlendMode::PassThrough); +} + +/// With the Brush the letters set the brush's mode, Clear included, and never the layer's; +/// ⇧+ from Dissolve reaches Clear, as in the dropdown. The Pencil keeps its own Clear. +#[test] +fn with_a_painting_tool_the_letters_set_only_its_mode() { + let ctx = egui::Context::default(); + let mut a = app(Tool::Brush); + alt_shift(&mut a, &ctx, Key::M, Key::M); + assert_eq!(a.session.tools.brush.mode, BlendMode::Multiply); + assert_eq!(layer_blend(&a), BlendMode::Normal, "the layer is untouched"); + assert_eq!(a.ui.tool, Tool::Brush); + alt_shift(&mut a, &ctx, Key::R, Key::R); + assert!(a.ui.tool_options.brush_clear); + alt_shift(&mut a, &ctx, Key::P, Key::P); + assert!(a.ui.tool_options.brush_clear, "no Pass Through for a brush"); + alt_shift(&mut a, &ctx, Key::I, Key::I); + assert!(!a.ui.tool_options.brush_clear); + assert_eq!(a.session.tools.brush.mode, BlendMode::Dissolve); + key(&mut a, &ctx, Key::Plus, egui::Modifiers::SHIFT); + assert!(a.ui.tool_options.brush_clear, "Clear follows Dissolve"); + key(&mut a, &ctx, Key::Plus, egui::Modifiers::SHIFT); + assert!(!a.ui.tool_options.brush_clear); + assert_eq!(a.session.tools.brush.mode, BlendMode::Darken); + assert!(!a.ui.tool_options.pencil_clear); + a.ui.tool = Tool::Pencil; + alt_shift(&mut a, &ctx, Key::R, Key::R); + assert!(a.ui.tool_options.pencil_clear); + assert_eq!(layer_blend(&a), BlendMode::Normal); +} + +/// The Gradient takes the letters; Smudge, which has a blend mode in Photoshop but no Mode +/// control here yet, ignores them rather than changing the layer. +#[test] +fn gradient_takes_the_letters_and_smudge_ignores_them() { + let ctx = egui::Context::default(); + let mut a = app(Tool::Gradient); + alt_shift(&mut a, &ctx, Key::O, Key::O); + assert_eq!(a.ui.tool_options.gradient_blend_mode, BlendMode::Overlay); + alt_shift(&mut a, &ctx, Key::R, Key::R); + assert_eq!(a.ui.tool_options.gradient_blend_mode, BlendMode::Overlay, "no Clear for the Gradient"); + a.ui.tool = Tool::Smudge; + alt_shift(&mut a, &ctx, Key::M, Key::M); + assert_eq!(layer_blend(&a), BlendMode::Normal); + assert_eq!(a.ui.tool, Tool::Smudge); + let mut none = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + pick_mode(&mut none, Pick::Mode(BlendMode::Multiply)); +} + +/// With a Free Transform box open, ⇧⌥ letters and the number keys still go where the tool +/// sends them: the Brush's mode and opacity with the Brush, the layer's with the Move tool. +/// They never pick a tool, so the box stays open, and Enter keeps both the transform and the +/// layer's new mode. Puppet Warp keeps them to itself: its preview is a snapshot taken when it +/// started, so a change made meanwhile wouldn't show, and Esc wouldn't take it back. +#[test] +fn keys_follow_the_tool_while_a_transform_is_open_and_a_warp_keeps_them() { + let ctx = egui::Context::default(); + let mut a = app(Tool::Brush); + a.run("select.rect", json!({"x": 4, "y": 4, "width": 12, "height": 12})).unwrap(); + a.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + a.run("select.deselect", json!({})).unwrap(); + a.sync_views(); + crate::transform_tool::begin(&mut a, &ctx).unwrap(); + crate::transform_tool::nudge(&mut a, 3.0, 0.0); + let shift_alt = egui::Modifiers::SHIFT | egui::Modifiers::ALT; + let opacity = |a: &PhotocraftApp| { + let st = a.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().opacity + }; + // The Brush: its own mode and opacity. + key(&mut a, &ctx, Key::M, shift_alt); + assert_eq!(a.session.tools.brush.mode, BlendMode::Multiply); + key(&mut a, &ctx, Key::Num5, egui::Modifiers::NONE); + assert!((a.session.tools.brush.opacity - 0.5).abs() < 1e-6); + assert_eq!((layer_blend(&a), opacity(&a)), (BlendMode::Normal, 1.0), "the layer is left alone"); + assert!(a.ui.transform.is_some(), "the box stays open"); + assert_eq!(a.ui.tool, Tool::Brush, "no tool letter"); + // The Move tool: the layer's. + a.ui.tool = Tool::Move; + a.opacity_keys = None; + key(&mut a, &ctx, Key::E, shift_alt); + key(&mut a, &ctx, Key::Num7, egui::Modifiers::NONE); + assert_eq!(layer_blend(&a), BlendMode::Difference); + assert!((opacity(&a) - 0.7).abs() < 1e-6, "{}", opacity(&a)); + assert!(a.ui.transform.is_some()); + key(&mut a, &ctx, Key::Enter, egui::Modifiers::NONE); + assert!(a.ui.transform.is_none()); + let st = a.session.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert_eq!(l.blend, BlendMode::Difference, "the commit keeps it"); + assert_eq!(l.surface().unwrap().content_bounds().x0, 7, "and the move"); + let l_opacity = l.opacity; + // Puppet Warp: nothing reaches the layer, the Brush or the History. + crate::distort_ui::menu(&mut a, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); + assert!(a.distort.puppet.is_some()); + let undo = a.session.active().unwrap().history.past_len(); + a.opacity_keys = None; + key(&mut a, &ctx, Key::S, shift_alt); + key(&mut a, &ctx, Key::Plus, egui::Modifiers::SHIFT); + key(&mut a, &ctx, Key::Num3, egui::Modifiers::NONE); + a.ui.tool = Tool::Brush; + key(&mut a, &ctx, Key::H, shift_alt); + key(&mut a, &ctx, Key::Num9, egui::Modifiers::NONE); + assert_eq!((layer_blend(&a), opacity(&a)), (BlendMode::Difference, l_opacity), "the layer under the warp is left alone"); + assert_eq!(a.session.tools.brush.mode, BlendMode::Multiply); + assert!((a.session.tools.brush.opacity - 0.5).abs() < 1e-6); + assert_eq!(a.session.active().unwrap().history.past_len(), undo, "no History step behind the warp"); + assert!(a.distort.puppet.is_some(), "the warp stays open"); + // Perspective Warp too. + key(&mut a, &ctx, Key::Escape, egui::Modifiers::NONE); + assert!(a.distort.puppet.is_none()); + a.ui.tool = Tool::Move; + crate::distort_ui::menu(&mut a, &ctx, "edit.perspectiveWarp", &json!({})).unwrap().unwrap(); + assert!(a.distort.perspective.is_some()); + key(&mut a, &ctx, Key::S, shift_alt); + key(&mut a, &ctx, Key::Num3, egui::Modifiers::NONE); + assert_eq!((layer_blend(&a), opacity(&a)), (BlendMode::Difference, l_opacity)); + assert_eq!(a.session.active().unwrap().history.past_len(), undo); + assert!(a.distort.perspective.is_some()); +} + +/// The stamps and the History Brush keep their mode in their own brush: the keys set it there, +/// never the layer's, and another tool's brush keeps its own. +#[test] +fn clone_stamp_pattern_stamp_and_history_brush_take_the_keys_into_their_own_brush() { + let ctx = egui::Context::default(); + let mut a = app(Tool::Brush); + alt_shift(&mut a, &ctx, Key::M, Key::M); + for (tool, key, mode) in + [(Tool::CloneStamp, Key::S, BlendMode::Screen), (Tool::PatternStamp, Key::O, BlendMode::Overlay), (Tool::HistoryBrush, Key::K, BlendMode::Darken)] + { + a.ui.tool = tool; + assert_eq!(tool_mode(&mut a), Some(BlendMode::Normal), "{tool:?} starts in Normal"); + alt_shift(&mut a, &ctx, key, key); + assert_eq!(tool_mode(&mut a), Some(mode), "{tool:?}"); + alt_shift(&mut a, &ctx, Key::R, Key::R); + assert_eq!(tool_mode(&mut a), Some(mode), "{tool:?} has no Clear"); + key_press(&mut a, &ctx, 1); + assert_ne!(tool_mode(&mut a), Some(mode), "{tool:?} steps"); + assert_eq!(layer_blend(&a), BlendMode::Normal, "{tool:?} leaves the layer alone"); + } + a.ui.tool = Tool::Brush; + assert_eq!(tool_mode(&mut a), Some(BlendMode::Multiply), "the Brush keeps its own mode"); +} + +fn key_press(a: &mut PhotocraftApp, ctx: &egui::Context, step: i32) { + key(a, ctx, if step > 0 { Key::Plus } else { Key::Minus }, egui::Modifiers::SHIFT); +} + +/// The Healing Brush's menu is short: letters outside it do nothing, and ⇧+ steps within it. +#[test] +fn healing_brush_takes_only_its_own_modes() { + let ctx = egui::Context::default(); + let mut a = app(Tool::Healing); + alt_shift(&mut a, &ctx, Key::O, Key::O); + assert_eq!(tool_mode(&mut a), Some(BlendMode::Normal), "Overlay isn't a Healing mode"); + alt_shift(&mut a, &ctx, Key::Y, Key::Y); + assert_eq!(tool_mode(&mut a), Some(BlendMode::Luminosity)); + key_press(&mut a, &ctx, 1); + assert_eq!(tool_mode(&mut a), Some(BlendMode::Normal), "wraps within the Healing list"); + key_press(&mut a, &ctx, 1); + assert_eq!(tool_mode(&mut a), Some(BlendMode::Multiply)); + assert_eq!(layer_blend(&a), BlendMode::Normal); +} + +/// A Healing Brush whose brush holds Overlay (outside its menu) counts as Normal for the keys, +/// as for its stroke: ⇧+ steps on to Multiply. +#[test] +fn healing_brush_with_a_mode_outside_its_menu_steps_from_normal() { + let ctx = egui::Context::default(); + let mut a = app(Tool::Healing); + crate::paint_mouse::sync_tool_brush(&mut a); + a.session.tools.brush.mode = BlendMode::Overlay; + assert_eq!(tool_mode(&mut a), Some(BlendMode::Normal)); + key_press(&mut a, &ctx, 1); + assert_eq!(tool_mode(&mut a), Some(BlendMode::Multiply)); +} + +/// The Paint Bucket has its own Mode, Clear included. +#[test] +fn paint_bucket_takes_the_keys_with_clear() { + let ctx = egui::Context::default(); + let mut a = app(Tool::PaintBucket); + alt_shift(&mut a, &ctx, Key::M, Key::M); + assert_eq!(a.ui.tool_options.bucket_blend_mode, BlendMode::Multiply); + alt_shift(&mut a, &ctx, Key::R, Key::R); + assert!(a.ui.tool_options.bucket_clear); + key_press(&mut a, &ctx, 1); + assert!(!a.ui.tool_options.bucket_clear); + assert_eq!(a.ui.tool_options.bucket_blend_mode, BlendMode::Darken, "Clear is followed by Darken"); + assert_eq!(layer_blend(&a), BlendMode::Normal); +} + +/// Tools without a blend mode of their own (the Erasers, the Mixer Brush) pass the keys to the +/// selected layers, as Photoshop does. +#[test] +fn tools_without_a_blend_mode_set_the_layer() { + let ctx = egui::Context::default(); + for (tool, key, mode) in + [(Tool::Eraser, Key::M, BlendMode::Multiply), (Tool::MagicEraser, Key::S, BlendMode::Screen), (Tool::MixerBrush, Key::E, BlendMode::Difference)] + { + let mut a = app(tool); + alt_shift(&mut a, &ctx, key, key); + assert_eq!(layer_blend(&a), mode, "{tool:?}"); + assert_eq!(a.ui.tool, tool); + } +} + +/// Dodge, Burn and Sponge use ⇧⌥S/M/H and ⇧⌥D/S for their own Range and mode in Photoshop, so +/// neither the letters nor ⇧+ change the layer's blend mode. +#[test] +fn dodge_burn_and_sponge_leave_the_layer_alone() { + let ctx = egui::Context::default(); + for tool in [Tool::Dodge, Tool::Burn, Tool::Sponge] { + let mut a = app(tool); + for k in [Key::S, Key::M, Key::H, Key::D] { + alt_shift(&mut a, &ctx, k, k); + } + key_press(&mut a, &ctx, 1); + assert_eq!(layer_blend(&a), BlendMode::Normal, "{tool:?}"); + assert_eq!(a.ui.tool, tool); + } +} + +#[test] +fn art_history_brush_leaves_the_layer_alone() { + // Photoshop's Art History Brush has a Mode of its own; ours has no Mode control yet. + let ctx = egui::Context::default(); + let mut a = app(Tool::ArtHistoryBrush); + alt_shift(&mut a, &ctx, Key::M, Key::M); + key_press(&mut a, &ctx, 1); + assert_eq!(layer_blend(&a), BlendMode::Normal); + assert_eq!(a.ui.tool, Tool::ArtHistoryBrush); +} From 5d9906c515d6f6ef03f64bdf3d1b30a22ce1a1a2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:31 +0000 Subject: [PATCH 054/259] refactor(ui-egui): move move_mods.rs tests to move_mods/tests.rs --- crates/ui-egui/src/move_mods.rs | 488 +------------------------- crates/ui-egui/src/move_mods/tests.rs | 485 +++++++++++++++++++++++++ 2 files changed, 486 insertions(+), 487 deletions(-) create mode 100644 crates/ui-egui/src/move_mods/tests.rs diff --git a/crates/ui-egui/src/move_mods.rs b/crates/ui-egui/src/move_mods.rs index 42ea6aa8af..ffd302add0 100644 --- a/crates/ui-egui/src/move_mods.rs +++ b/crates/ui-egui/src/move_mods.rs @@ -313,490 +313,4 @@ fn selection_arrow_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { } #[cfg(test)] -mod tests { - use super::*; - - fn near(a: [f64; 2], b: [f64; 2]) -> bool { - (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9 - } - - #[test] - fn shift_picks_the_dominant_axis() { - assert!(near(constrain([10.0, 3.0], None, 4), [10.0, 0.0])); - assert!(near(constrain([-2.0, -9.0], None, 4), [0.0, -9.0])); - assert!(near(constrain([0.0, 0.0], None, 4), [0.0, 0.0])); - // Eight directions: a near-diagonal drag lands on 45°. - let d = constrain([10.0, 9.0], None, 8); - assert!((d[0] - d[1]).abs() < 1e-9 && d[0] > 9.0, "{d:?}"); - assert!(near(constrain([10.0, 1.0], None, 8), [10.0, 0.0])); - // Hostile input never panics and stays finite or passes through. - let _ = constrain([f64::NAN, 1.0], None, 4); - let _ = constrain([f64::INFINITY, 1.0], Some([f64::NAN, 0.0]), 0); - } - - #[test] - fn shift_axis_switches_once_the_pointer_is_clearly_nearer_the_other_one() { - let h = constrain([20.0, 2.0], None, 4); - assert!(near(h, [20.0, 0.0])); - // Just past the diagonal: hysteresis keeps horizontal. - let still = constrain([20.0, 21.0], Some(h), 4); - assert!(near(still, [20.0, 0.0]), "{still:?}"); - // Far enough the other way: switches to vertical. - let v = constrain([20.0, 40.0], Some(h), 4); - assert!(near(v, [0.0, 40.0]), "{v:?}"); - // And back. - assert!(near(constrain([30.0, 20.0], Some(v), 4), [30.0, 0.0])); - } - - fn app_with_layer() -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, a| { - doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 24, 24), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - app.ui.tool = Tool::Move; - app.ui.tool_options.move_auto_select = false; - // Snapping (to the document centre with a 1:1 test view) would shift the expected offsets. - app.ui.extras.snap = false; - app.ui.view.show.smart_guides = false; - app - } - - fn bounds(app: &PhotocraftApp, id: photocraft_doc::LayerId) -> photocraft_geom::Rect { - app.session.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds() - } - - fn drag(app: &mut PhotocraftApp, pts: &[[f64; 2]], mods: egui::Modifiers) { - crate::canvas::tool_event(app, ToolEvent::Down { x: pts[0][0], y: pts[0][1], pressure: 1.0 }, mods); - for p in &pts[1..pts.len() - 1] { - crate::canvas::tool_event(app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }, mods); - } - let e = pts[pts.len() - 1]; - crate::canvas::tool_event(app, ToolEvent::Up { x: e[0], y: e[1] }, mods); - } - - #[test] - fn shift_drag_moves_along_one_axis_only() { - let mut app = app_with_layer(); - let id = app.session.active().unwrap().active_layer.unwrap(); - drag(&mut app, &[[16.0, 16.0], [22.0, 18.0], [26.0, 19.0]], egui::Modifiers::SHIFT); - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(18, 8, 34, 24)); - // Switching axis mid-drag: the end point decides. - drag(&mut app, &[[16.0, 16.0], [22.0, 17.0], [18.0, 30.0], [17.0, 36.0]], egui::Modifiers::SHIFT); - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(18, 28, 34, 44)); - } - - #[test] - fn alt_drag_duplicates_and_moves_the_copy_in_one_step() { - let mut app = app_with_layer(); - let orig = app.session.active().unwrap().active_layer.unwrap(); - let n0 = app.session.active().unwrap().doc.layers.len(); - let h0 = app.session.active().unwrap().history.past_len(); - drag(&mut app, &[[16.0, 16.0], [20.0, 16.0], [26.0, 21.0]], egui::Modifiers::ALT); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.layers.len(), n0 + 1, "one copy"); - let copy = st.active_layer.unwrap(); - assert_ne!(copy, orig); - assert_eq!(bounds(&app, orig), photocraft_geom::Rect::new(8, 8, 24, 24), "original untouched"); - assert_eq!(bounds(&app, copy), photocraft_geom::Rect::new(18, 13, 34, 29)); - let st = app.session.active().unwrap(); - assert_eq!(st.history.past_len(), h0 + 1, "one undo step"); - assert_eq!(st.history.undo_label(), Some(DUPLICATE_MOVE_LABEL)); - assert!(app.session.undo()); - assert_eq!(app.session.active().unwrap().doc.layers.len(), n0); - assert_eq!(bounds(&app, orig), photocraft_geom::Rect::new(8, 8, 24, 24)); - // ⌥-click without a drag makes no copy. - drag(&mut app, &[[16.0, 16.0], [16.0, 16.0]], egui::Modifiers::ALT); - assert_eq!(app.session.active().unwrap().doc.layers.len(), n0); - // ⇧⌥: a copy moved along one axis. - drag(&mut app, &[[16.0, 16.0], [30.0, 19.0]], egui::Modifiers::SHIFT | egui::Modifiers::ALT); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.layers.len(), n0 + 1); - assert_eq!(bounds(&app, st.active_layer.unwrap()), photocraft_geom::Rect::new(22, 8, 38, 24)); - } - - #[test] - fn alt_drag_duplicates_every_selected_layer() { - let mut app = app_with_layer(); - let a = app.session.active().unwrap().active_layer.unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - let b = app.session.active().unwrap().active_layer.unwrap(); - app.session.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); - let n0 = app.session.active().unwrap().doc.layers.len(); - let h0 = app.session.active().unwrap().history.past_len(); - drag(&mut app, &[[16.0, 16.0], [26.0, 16.0]], egui::Modifiers::ALT); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.layers.len(), n0 + 2); - assert_eq!(st.history.past_len(), h0 + 1); - assert_eq!(bounds(&app, a), photocraft_geom::Rect::new(8, 8, 24, 24)); - assert!(st.doc.layer(b).is_some()); - } - - #[test] - fn nudge_moves_layers_or_the_transform_box() { - let mut app = app_with_layer(); - let id = app.session.active().unwrap().active_layer.unwrap(); - nudge(&mut app, 10.0, 0.0, false); - nudge(&mut app, 0.0, -1.0, false); - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(18, 7, 34, 23)); - let n0 = app.session.active().unwrap().doc.layers.len(); - nudge(&mut app, 1.0, 0.0, true); - assert_eq!(app.session.active().unwrap().doc.layers.len(), n0 + 1); - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(18, 7, 34, 23)); - let ctx = egui::Context::default(); - crate::transform_tool::begin(&mut app, &ctx).unwrap(); - let q0 = app.ui.transform.as_ref().unwrap().quad; - nudge(&mut app, 0.0, 10.0, false); - assert_eq!(app.ui.transform.as_ref().unwrap().quad[0], [q0[0][0], q0[0][1] + 10.0]); - } - - /// One key press through `arrow_keys`, as egui delivers it. - fn press(app: &mut PhotocraftApp, key: egui::Key, mods: egui::Modifiers) -> bool { - press_at(app, key, mods, 0.0) - } - - /// [`press`] at egui time `time` (seconds). - fn press_at(app: &mut PhotocraftApp, key: egui::Key, mods: egui::Modifiers, time: f64) -> bool { - let ctx = egui::Context::default(); - ctx.input_mut(|i| { - i.time = time; - i.modifiers = mods; - i.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: mods }); - }); - arrow_keys(app, &ctx) - } - - /// Photoshop's ← / → with a painting tool turn the brush tip 1°, ⇧ 15°; → is clockwise. Other - /// tools keep their arrows (the Hand has none, the marquee nudges the selection). - #[test] - fn arrows_turn_the_brush_tip_for_painting_tools_only() { - let mut app = app_with_layer(); - for tool in [Tool::Brush, Tool::Eraser, Tool::CloneStamp] { - app.ui.tool = tool; - app.run("tools.setBrush", json!({"brush": {"angle": 0}})).unwrap(); - assert!(press(&mut app, egui::Key::ArrowLeft, egui::Modifiers::NONE), "{tool:?}"); - assert_eq!(app.session.tools.brush.angle, 1.0, "{tool:?}: ← anticlockwise"); - assert!(press(&mut app, egui::Key::ArrowRight, egui::Modifiers::SHIFT)); - assert_eq!(app.session.tools.brush.angle, -14.0, "{tool:?}: ⇧→ 15° clockwise"); - } - app.run("tools.setBrush", json!({"brush": {"angle": 0}})).unwrap(); - // ⌥-arrows are not the brush's (they kern type, and ⌘ moves). - assert!(!press(&mut app, egui::Key::ArrowLeft, egui::Modifiers::ALT)); - app.ui.tool = Tool::Hand; - assert!(!press(&mut app, egui::Key::ArrowLeft, egui::Modifiers::NONE)); - assert_eq!(app.session.tools.brush.angle, 0.0); - } - - /// Real key events: ⇧ nudges 10 px and ⌥ duplicates first (egui ignores extra ⇧ / ⌥ when - /// matching, so the plain arrow must not be tried first). - #[test] - fn arrow_key_modifiers_reach_the_move_tool() { - let mut app = app_with_layer(); - let id = app.session.active().unwrap().active_layer.unwrap(); - let n0 = app.session.active().unwrap().doc.layers.len(); - assert!(press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE)); - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(9, 8, 25, 24)); - assert!(press(&mut app, egui::Key::ArrowDown, egui::Modifiers::SHIFT)); - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(9, 18, 25, 34)); - assert!(press(&mut app, egui::Key::ArrowLeft, egui::Modifiers::ALT)); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.layers.len(), n0 + 1, "⌥ duplicated first"); - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(9, 18, 25, 34), "the original stays"); - } - - /// ⌘ as a Mac sends it, and Ctrl as Windows and Linux send it (`command` is Ctrl there). - const MAC_CMD: egui::Modifiers = egui::Modifiers { alt: false, ctrl: false, shift: false, mac_cmd: true, command: true }; - const CTRL: egui::Modifiers = egui::Modifiers { alt: false, ctrl: true, shift: false, mac_cmd: false, command: true }; - - /// #2474: ⌘ is the temporary Move tool, so ⌘-arrows nudge the layer from the Brush (⌘⇧ 10 px, - /// ⌘⌥ duplicates first); the plain arrows still do nothing there. - #[test] - fn cmd_arrows_nudge_the_layer_from_the_brush() { - let mut app = app_with_layer(); - app.ui.tool = Tool::Brush; - let id = app.session.active().unwrap().active_layer.unwrap(); - let n0 = app.session.active().unwrap().doc.layers.len(); - // A plain arrow turns the Brush's tip (below), never the layer. - assert!(press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE)); - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(8, 8, 24, 24)); - assert_eq!(app.session.tools.brush.angle, -1.0); - app.run("tools.setBrush", json!({"brush": {"angle": 0}})).unwrap(); - for cmd in [CTRL, MAC_CMD] { - assert!(press(&mut app, egui::Key::ArrowRight, cmd)); - } - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(10, 8, 26, 24), "1 px per press"); - assert!(press(&mut app, egui::Key::ArrowDown, CTRL | egui::Modifiers::SHIFT)); - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(10, 18, 26, 34), "⌘⇧: 10 px"); - assert!(press(&mut app, egui::Key::ArrowLeft, CTRL | egui::Modifiers::ALT)); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.layers.len(), n0 + 1, "⌘⌥ duplicated first"); - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(10, 18, 26, 34), "the original stays"); - assert_eq!(bounds(&app, st.active_layer.unwrap()), photocraft_geom::Rect::new(9, 18, 25, 34), "the copy moved"); - assert_eq!(app.ui.tool, Tool::Brush); - // The Move tool itself takes ⌘-arrows as plain ones. - app.ui.tool = Tool::Move; - assert!(press(&mut app, egui::Key::ArrowUp, CTRL)); - let copy = app.session.active().unwrap().active_layer.unwrap(); - assert_eq!(bounds(&app, copy), photocraft_geom::Rect::new(9, 17, 25, 33)); - } - - /// #2474: tools where ⌘ means something else in Photoshop (Pen and path tools, Hand, Zoom, - /// Crop, Type) keep ⌘-arrows away from the layer, as does an active Free Transform. - #[test] - fn cmd_arrows_leave_the_layer_alone_where_cmd_is_not_the_move_tool() { - let mut app = app_with_layer(); - let id = app.session.active().unwrap().active_layer.unwrap(); - for tool in [Tool::Pen, Tool::PathSelection, Tool::DirectSelection, Tool::Rectangle, Tool::Hand, Tool::Zoom, Tool::Crop, Tool::Type] { - app.ui.tool = tool; - assert!(!press(&mut app, egui::Key::ArrowRight, CTRL), "{tool:?}"); - assert!(!press(&mut app, egui::Key::ArrowRight, MAC_CMD | egui::Modifiers::SHIFT), "{tool:?}"); - } - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(8, 8, 24, 24)); - app.ui.tool = Tool::Brush; - crate::transform_tool::begin(&mut app, &egui::Context::default()).unwrap(); - let q0 = app.ui.transform.as_ref().unwrap().quad; - assert!(!press(&mut app, egui::Key::ArrowRight, CTRL)); - assert_eq!(app.ui.transform.as_ref().unwrap().quad, q0); - } - - /// #2474: with a selection tool ⌘-arrows move the selected pixels (the temporary Move tool), the - /// plain arrows the outline. - #[test] - fn cmd_arrows_move_the_selected_pixels_with_a_selection_tool() { - let mut app = app_with_layer(); - app.ui.tool = Tool::RectMarquee; - app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 8, "height": 8})).unwrap(); - assert!(press(&mut app, egui::Key::ArrowRight, CTRL)); - let offset = |app: &PhotocraftApp| photocraft_engine::float_cmds::floating(app.session.active().unwrap()).map(|f| f.offset); - assert_eq!(offset(&app), Some((1, 0)), "the selected pixels float, 1 px to the right"); - assert!(press(&mut app, egui::Key::ArrowDown, CTRL | egui::Modifiers::SHIFT)); - assert_eq!(offset(&app), Some((1, 10)), "⌘⇧: 10 px"); - assert_eq!(app.ui.tool, Tool::RectMarquee); - // Not while a polygon is being drawn. - app.ui.tool = Tool::PolygonLasso; - app.ui.polygon = vec![[1.0, 1.0]]; - assert!(!press(&mut app, egui::Key::ArrowRight, CTRL)); - } - - /// #1428: with a selection tool the arrows nudge the selection outline (⇧ 10 px); the layer - /// stays put. Without a selection they are left alone. One step each with Bundle Arrow-Key - /// Nudges off (#2259). - #[test] - fn arrow_keys_nudge_the_selection_with_a_selection_tool() { - let mut app = app_with_layer(); - app.session.edit_prefs(|p| p.tools.bundle_nudges = false); - let id = app.session.active().unwrap().active_layer.unwrap(); - app.ui.tool = Tool::Lasso; - assert!(!press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE), "no selection: not used"); - app.session.execute("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); - let sel = |app: &PhotocraftApp| app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); - let h0 = app.session.active().unwrap().history.past_len(); - assert!(press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE)); - assert!(press(&mut app, egui::Key::ArrowDown, egui::Modifiers::SHIFT)); - assert_eq!(sel(&app), photocraft_geom::Rect::new(5, 14, 15, 24)); - assert_eq!(app.session.active().unwrap().history.past_len(), h0 + 2); - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(8, 8, 24, 24), "pixels stay put"); - // Not while a polygon is being drawn. - app.ui.tool = Tool::PolygonLasso; - app.ui.polygon = vec![[1.0, 1.0]]; - assert!(!press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE)); - } - fn history(app: &PhotocraftApp) -> usize { - app.session.active().unwrap().history.past_len() - } - - fn left_edge(app: &PhotocraftApp, id: photocraft_doc::LayerId) -> i32 { - bounds(app, id).x0 - } - - /// #2259: tapping or holding an arrow key is one History state, so one Undo takes the whole - /// run back (Photoshop folds a run of nudges into one "Move"). - #[test] - fn a_run_of_arrow_nudges_is_one_history_step() { - let mut app = app_with_layer(); - let id = app.session.active().unwrap().active_layer.unwrap(); - let h0 = history(&app); - // Twelve taps, 0.2 s apart, then ⇧ for ten more px: still the same run. - for i in 0..12 { - assert!(press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 5.0 + 0.2 * f64::from(i))); - } - assert!(press_at(&mut app, egui::Key::ArrowDown, egui::Modifiers::SHIFT, 7.6)); - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(20, 18, 36, 34)); - assert_eq!(history(&app), h0 + 1, "thirteen presses, one state"); - assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Move")); - assert!(app.session.undo()); - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(8, 8, 24, 24), "one Undo takes back the run"); - assert!(app.session.redo()); - assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(20, 18, 36, 34), "and one Redo does it again"); - } - - /// A pause longer than Nudge Bundle Pause starts a new run; a longer pause setting keeps it. - #[test] - fn a_pause_ends_the_run() { - let mut app = app_with_layer(); - let id = app.session.active().unwrap().active_layer.unwrap(); - let h0 = history(&app); - press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 1.0); - press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 1.9); - assert_eq!(history(&app), h0 + 1, "0.9 s: the same run"); - press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 3.0); - assert_eq!(history(&app), h0 + 2, "1.1 s of quiet: a new run"); - app.session.edit_prefs(|p| p.tools.nudge_bundle_pause_ms = 5000); - press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 7.0); - assert_eq!(history(&app), h0 + 2, "4 s with a 5 s pause: the same run"); - assert_eq!(left_edge(&app, id), 12); - assert!(app.session.undo()); - assert_eq!(left_edge(&app, id), 10, "Undo takes back the second run only"); - } - - /// With Bundle Arrow-Key Nudges off every press is a state, as before (#2259). - #[test] - fn every_press_is_a_step_with_bundling_off() { - let mut app = app_with_layer(); - let id = app.session.active().unwrap().active_layer.unwrap(); - app.session.edit_prefs(|p| p.tools.bundle_nudges = false); - let h0 = history(&app); - for _ in 0..5 { - assert!(press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE)); - } - assert_eq!(history(&app), h0 + 5); - assert!(app.session.undo()); - assert_eq!(left_edge(&app, id), 12, "one pixel back"); - // Turning it back on bundles the next run, which doesn't swallow the earlier steps. - app.session.edit_prefs(|p| p.tools.bundle_nudges = true); - for _ in 0..3 { - press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE); - } - assert_eq!(history(&app), h0 + 5); - assert_eq!(left_edge(&app, id), 15); - } - - /// Any other change to the document ends the run: another edit, Undo, a different layer - /// selected, a save. - #[test] - fn other_changes_end_the_run() { - let mut app = app_with_layer(); - let a = app.session.active().unwrap().active_layer.unwrap(); - let tap = |app: &mut PhotocraftApp| assert!(press(app, egui::Key::ArrowRight, egui::Modifiers::NONE)); - let h0 = history(&app); - tap(&mut app); - tap(&mut app); - assert_eq!(history(&app), h0 + 1); - // An edit of another kind between two nudges. - app.session.execute("layer.setProps", json!({"opacity": 0.5})).unwrap(); - tap(&mut app); - tap(&mut app); - assert_eq!(history(&app), h0 + 3, "nudges, the edit, nudges"); - // Undo ends it too: the next nudge is a state of its own, not folded into the one before. - assert!(app.session.undo()); - tap(&mut app); - assert_eq!(history(&app), h0 + 3); - assert!(app.session.undo()); - assert_eq!(left_edge(&app, a), 10, "the new run was undone alone"); - // Saving keeps the saved state a step of its own. - tap(&mut app); - tap(&mut app); - let before = history(&app); - let st = app.session.active_mut().unwrap(); - st.saved_revision = st.revision; - tap(&mut app); - assert_eq!(history(&app), before + 1, "a save between two nudges ends the run"); - // Selecting another layer: the same keys now move that one, in a run of its own. - let b = { - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session.active().unwrap().active_layer.unwrap() - }; - assert_ne!(a, b); - let before = history(&app); - app.session - .edit("paint", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[0.0, 1.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - tap(&mut app); - app.session.select_layer(a).unwrap(); - tap(&mut app); - assert_eq!(history(&app), before + 3, "paint, a nudge of the new layer, a nudge of the first"); - } - - /// ⌥ copies, so ⌥-nudges are never folded into a run (the copy is part of each step). - #[test] - fn alt_nudges_do_not_join_a_run() { - let mut app = app_with_layer(); - let h0 = history(&app); - press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE); - press(&mut app, egui::Key::ArrowRight, egui::Modifiers::ALT); - press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE); - assert_eq!(history(&app), h0 + 3); - assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Move"), "the run after the copy is a state of its own"); - } - - /// #2259: nudges of the selection outline bundle the same way. - #[test] - fn selection_outline_nudges_bundle_into_one_step() { - let mut app = app_with_layer(); - app.ui.tool = Tool::Lasso; - app.session.execute("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); - let sel = |app: &PhotocraftApp| app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); - let h0 = history(&app); - for i in 0..5 { - assert!(press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 2.0 + 0.1 * f64::from(i))); - } - assert!(press_at(&mut app, egui::Key::ArrowDown, egui::Modifiers::SHIFT, 2.6)); - assert_eq!(sel(&app), photocraft_geom::Rect::new(9, 14, 19, 24)); - assert_eq!(history(&app), h0 + 1); - assert!(app.session.undo()); - assert_eq!(sel(&app), photocraft_geom::Rect::new(4, 4, 14, 14), "Undo takes the outline back where it was drawn"); - // The layer nudge and the outline nudge are different runs even back to back. - app.session.execute("select.deselect", json!({})).unwrap(); - app.ui.tool = Tool::Move; - let h1 = history(&app); - press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 3.0); - assert_eq!(history(&app), h1 + 1); - } - - /// Free Transform: nudges of the box that follow each other are one Undo step of the session - /// (it has its own history); a drag or a pause starts another. - #[test] - fn free_transform_nudges_bundle_into_one_undo_step() { - let mut app = app_with_layer(); - let ctx = egui::Context::default(); - crate::transform_tool::begin(&mut app, &ctx).unwrap(); - let quad = |app: &PhotocraftApp| app.ui.transform.as_ref().unwrap().quad; - let q0 = quad(&app); - let moved = |dx: f64, dy: f64| q0.map(|q| [q[0] + dx, q[1] + dy]); - let settle = |app: &mut PhotocraftApp| crate::transform_tool::track_steps(app, &ctx); - for i in 0..6 { - assert!(press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 4.0 + 0.1 * f64::from(i))); - settle(&mut app); - } - assert_eq!(quad(&app), moved(6.0, 0.0)); - // A pause, and the next nudge is a step of its own. - assert!(press_at(&mut app, egui::Key::ArrowDown, egui::Modifiers::NONE, 9.0)); - settle(&mut app); - assert_eq!( - quad(&app), - [[q0[0][0] + 6.0, q0[0][1] + 1.0], [q0[1][0] + 6.0, q0[1][1] + 1.0], [q0[2][0] + 6.0, q0[2][1] + 1.0], [q0[3][0] + 6.0, q0[3][1] + 1.0]] - ); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(quad(&app), moved(6.0, 0.0), "Undo takes back the late nudge only"); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(quad(&app), q0, "and the next one the six that were bundled"); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(quad(&app), q0, "nothing is left of the session to undo"); - // With bundling off every nudge is a step. - app.session.edit_prefs(|p| p.tools.bundle_nudges = false); - for i in 0..3 { - press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 20.0 + 0.1 * f64::from(i)); - settle(&mut app); - } - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(quad(&app), moved(2.0, 0.0)); - } -} +mod tests; diff --git a/crates/ui-egui/src/move_mods/tests.rs b/crates/ui-egui/src/move_mods/tests.rs new file mode 100644 index 0000000000..27118357fe --- /dev/null +++ b/crates/ui-egui/src/move_mods/tests.rs @@ -0,0 +1,485 @@ +use super::*; + +fn near(a: [f64; 2], b: [f64; 2]) -> bool { + (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9 +} + +#[test] +fn shift_picks_the_dominant_axis() { + assert!(near(constrain([10.0, 3.0], None, 4), [10.0, 0.0])); + assert!(near(constrain([-2.0, -9.0], None, 4), [0.0, -9.0])); + assert!(near(constrain([0.0, 0.0], None, 4), [0.0, 0.0])); + // Eight directions: a near-diagonal drag lands on 45°. + let d = constrain([10.0, 9.0], None, 8); + assert!((d[0] - d[1]).abs() < 1e-9 && d[0] > 9.0, "{d:?}"); + assert!(near(constrain([10.0, 1.0], None, 8), [10.0, 0.0])); + // Hostile input never panics and stays finite or passes through. + let _ = constrain([f64::NAN, 1.0], None, 4); + let _ = constrain([f64::INFINITY, 1.0], Some([f64::NAN, 0.0]), 0); +} + +#[test] +fn shift_axis_switches_once_the_pointer_is_clearly_nearer_the_other_one() { + let h = constrain([20.0, 2.0], None, 4); + assert!(near(h, [20.0, 0.0])); + // Just past the diagonal: hysteresis keeps horizontal. + let still = constrain([20.0, 21.0], Some(h), 4); + assert!(near(still, [20.0, 0.0]), "{still:?}"); + // Far enough the other way: switches to vertical. + let v = constrain([20.0, 40.0], Some(h), 4); + assert!(near(v, [0.0, 40.0]), "{v:?}"); + // And back. + assert!(near(constrain([30.0, 20.0], Some(v), 4), [30.0, 0.0])); +} + +fn app_with_layer() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 24, 24), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_auto_select = false; + // Snapping (to the document centre with a 1:1 test view) would shift the expected offsets. + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + app +} + +fn bounds(app: &PhotocraftApp, id: photocraft_doc::LayerId) -> photocraft_geom::Rect { + app.session.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds() +} + +fn drag(app: &mut PhotocraftApp, pts: &[[f64; 2]], mods: egui::Modifiers) { + crate::canvas::tool_event(app, ToolEvent::Down { x: pts[0][0], y: pts[0][1], pressure: 1.0 }, mods); + for p in &pts[1..pts.len() - 1] { + crate::canvas::tool_event(app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }, mods); + } + let e = pts[pts.len() - 1]; + crate::canvas::tool_event(app, ToolEvent::Up { x: e[0], y: e[1] }, mods); +} + +#[test] +fn shift_drag_moves_along_one_axis_only() { + let mut app = app_with_layer(); + let id = app.session.active().unwrap().active_layer.unwrap(); + drag(&mut app, &[[16.0, 16.0], [22.0, 18.0], [26.0, 19.0]], egui::Modifiers::SHIFT); + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(18, 8, 34, 24)); + // Switching axis mid-drag: the end point decides. + drag(&mut app, &[[16.0, 16.0], [22.0, 17.0], [18.0, 30.0], [17.0, 36.0]], egui::Modifiers::SHIFT); + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(18, 28, 34, 44)); +} + +#[test] +fn alt_drag_duplicates_and_moves_the_copy_in_one_step() { + let mut app = app_with_layer(); + let orig = app.session.active().unwrap().active_layer.unwrap(); + let n0 = app.session.active().unwrap().doc.layers.len(); + let h0 = app.session.active().unwrap().history.past_len(); + drag(&mut app, &[[16.0, 16.0], [20.0, 16.0], [26.0, 21.0]], egui::Modifiers::ALT); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers.len(), n0 + 1, "one copy"); + let copy = st.active_layer.unwrap(); + assert_ne!(copy, orig); + assert_eq!(bounds(&app, orig), photocraft_geom::Rect::new(8, 8, 24, 24), "original untouched"); + assert_eq!(bounds(&app, copy), photocraft_geom::Rect::new(18, 13, 34, 29)); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), h0 + 1, "one undo step"); + assert_eq!(st.history.undo_label(), Some(DUPLICATE_MOVE_LABEL)); + assert!(app.session.undo()); + assert_eq!(app.session.active().unwrap().doc.layers.len(), n0); + assert_eq!(bounds(&app, orig), photocraft_geom::Rect::new(8, 8, 24, 24)); + // ⌥-click without a drag makes no copy. + drag(&mut app, &[[16.0, 16.0], [16.0, 16.0]], egui::Modifiers::ALT); + assert_eq!(app.session.active().unwrap().doc.layers.len(), n0); + // ⇧⌥: a copy moved along one axis. + drag(&mut app, &[[16.0, 16.0], [30.0, 19.0]], egui::Modifiers::SHIFT | egui::Modifiers::ALT); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers.len(), n0 + 1); + assert_eq!(bounds(&app, st.active_layer.unwrap()), photocraft_geom::Rect::new(22, 8, 38, 24)); +} + +#[test] +fn alt_drag_duplicates_every_selected_layer() { + let mut app = app_with_layer(); + let a = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + let b = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); + let n0 = app.session.active().unwrap().doc.layers.len(); + let h0 = app.session.active().unwrap().history.past_len(); + drag(&mut app, &[[16.0, 16.0], [26.0, 16.0]], egui::Modifiers::ALT); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers.len(), n0 + 2); + assert_eq!(st.history.past_len(), h0 + 1); + assert_eq!(bounds(&app, a), photocraft_geom::Rect::new(8, 8, 24, 24)); + assert!(st.doc.layer(b).is_some()); +} + +#[test] +fn nudge_moves_layers_or_the_transform_box() { + let mut app = app_with_layer(); + let id = app.session.active().unwrap().active_layer.unwrap(); + nudge(&mut app, 10.0, 0.0, false); + nudge(&mut app, 0.0, -1.0, false); + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(18, 7, 34, 23)); + let n0 = app.session.active().unwrap().doc.layers.len(); + nudge(&mut app, 1.0, 0.0, true); + assert_eq!(app.session.active().unwrap().doc.layers.len(), n0 + 1); + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(18, 7, 34, 23)); + let ctx = egui::Context::default(); + crate::transform_tool::begin(&mut app, &ctx).unwrap(); + let q0 = app.ui.transform.as_ref().unwrap().quad; + nudge(&mut app, 0.0, 10.0, false); + assert_eq!(app.ui.transform.as_ref().unwrap().quad[0], [q0[0][0], q0[0][1] + 10.0]); +} + +/// One key press through `arrow_keys`, as egui delivers it. +fn press(app: &mut PhotocraftApp, key: egui::Key, mods: egui::Modifiers) -> bool { + press_at(app, key, mods, 0.0) +} + +/// [`press`] at egui time `time` (seconds). +fn press_at(app: &mut PhotocraftApp, key: egui::Key, mods: egui::Modifiers, time: f64) -> bool { + let ctx = egui::Context::default(); + ctx.input_mut(|i| { + i.time = time; + i.modifiers = mods; + i.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: mods }); + }); + arrow_keys(app, &ctx) +} + +/// Photoshop's ← / → with a painting tool turn the brush tip 1°, ⇧ 15°; → is clockwise. Other +/// tools keep their arrows (the Hand has none, the marquee nudges the selection). +#[test] +fn arrows_turn_the_brush_tip_for_painting_tools_only() { + let mut app = app_with_layer(); + for tool in [Tool::Brush, Tool::Eraser, Tool::CloneStamp] { + app.ui.tool = tool; + app.run("tools.setBrush", json!({"brush": {"angle": 0}})).unwrap(); + assert!(press(&mut app, egui::Key::ArrowLeft, egui::Modifiers::NONE), "{tool:?}"); + assert_eq!(app.session.tools.brush.angle, 1.0, "{tool:?}: ← anticlockwise"); + assert!(press(&mut app, egui::Key::ArrowRight, egui::Modifiers::SHIFT)); + assert_eq!(app.session.tools.brush.angle, -14.0, "{tool:?}: ⇧→ 15° clockwise"); + } + app.run("tools.setBrush", json!({"brush": {"angle": 0}})).unwrap(); + // ⌥-arrows are not the brush's (they kern type, and ⌘ moves). + assert!(!press(&mut app, egui::Key::ArrowLeft, egui::Modifiers::ALT)); + app.ui.tool = Tool::Hand; + assert!(!press(&mut app, egui::Key::ArrowLeft, egui::Modifiers::NONE)); + assert_eq!(app.session.tools.brush.angle, 0.0); +} + +/// Real key events: ⇧ nudges 10 px and ⌥ duplicates first (egui ignores extra ⇧ / ⌥ when +/// matching, so the plain arrow must not be tried first). +#[test] +fn arrow_key_modifiers_reach_the_move_tool() { + let mut app = app_with_layer(); + let id = app.session.active().unwrap().active_layer.unwrap(); + let n0 = app.session.active().unwrap().doc.layers.len(); + assert!(press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE)); + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(9, 8, 25, 24)); + assert!(press(&mut app, egui::Key::ArrowDown, egui::Modifiers::SHIFT)); + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(9, 18, 25, 34)); + assert!(press(&mut app, egui::Key::ArrowLeft, egui::Modifiers::ALT)); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers.len(), n0 + 1, "⌥ duplicated first"); + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(9, 18, 25, 34), "the original stays"); +} + +/// ⌘ as a Mac sends it, and Ctrl as Windows and Linux send it (`command` is Ctrl there). +const MAC_CMD: egui::Modifiers = egui::Modifiers { alt: false, ctrl: false, shift: false, mac_cmd: true, command: true }; +const CTRL: egui::Modifiers = egui::Modifiers { alt: false, ctrl: true, shift: false, mac_cmd: false, command: true }; + +/// #2474: ⌘ is the temporary Move tool, so ⌘-arrows nudge the layer from the Brush (⌘⇧ 10 px, +/// ⌘⌥ duplicates first); the plain arrows still do nothing there. +#[test] +fn cmd_arrows_nudge_the_layer_from_the_brush() { + let mut app = app_with_layer(); + app.ui.tool = Tool::Brush; + let id = app.session.active().unwrap().active_layer.unwrap(); + let n0 = app.session.active().unwrap().doc.layers.len(); + // A plain arrow turns the Brush's tip (below), never the layer. + assert!(press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE)); + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(8, 8, 24, 24)); + assert_eq!(app.session.tools.brush.angle, -1.0); + app.run("tools.setBrush", json!({"brush": {"angle": 0}})).unwrap(); + for cmd in [CTRL, MAC_CMD] { + assert!(press(&mut app, egui::Key::ArrowRight, cmd)); + } + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(10, 8, 26, 24), "1 px per press"); + assert!(press(&mut app, egui::Key::ArrowDown, CTRL | egui::Modifiers::SHIFT)); + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(10, 18, 26, 34), "⌘⇧: 10 px"); + assert!(press(&mut app, egui::Key::ArrowLeft, CTRL | egui::Modifiers::ALT)); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers.len(), n0 + 1, "⌘⌥ duplicated first"); + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(10, 18, 26, 34), "the original stays"); + assert_eq!(bounds(&app, st.active_layer.unwrap()), photocraft_geom::Rect::new(9, 18, 25, 34), "the copy moved"); + assert_eq!(app.ui.tool, Tool::Brush); + // The Move tool itself takes ⌘-arrows as plain ones. + app.ui.tool = Tool::Move; + assert!(press(&mut app, egui::Key::ArrowUp, CTRL)); + let copy = app.session.active().unwrap().active_layer.unwrap(); + assert_eq!(bounds(&app, copy), photocraft_geom::Rect::new(9, 17, 25, 33)); +} + +/// #2474: tools where ⌘ means something else in Photoshop (Pen and path tools, Hand, Zoom, +/// Crop, Type) keep ⌘-arrows away from the layer, as does an active Free Transform. +#[test] +fn cmd_arrows_leave_the_layer_alone_where_cmd_is_not_the_move_tool() { + let mut app = app_with_layer(); + let id = app.session.active().unwrap().active_layer.unwrap(); + for tool in [Tool::Pen, Tool::PathSelection, Tool::DirectSelection, Tool::Rectangle, Tool::Hand, Tool::Zoom, Tool::Crop, Tool::Type] { + app.ui.tool = tool; + assert!(!press(&mut app, egui::Key::ArrowRight, CTRL), "{tool:?}"); + assert!(!press(&mut app, egui::Key::ArrowRight, MAC_CMD | egui::Modifiers::SHIFT), "{tool:?}"); + } + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(8, 8, 24, 24)); + app.ui.tool = Tool::Brush; + crate::transform_tool::begin(&mut app, &egui::Context::default()).unwrap(); + let q0 = app.ui.transform.as_ref().unwrap().quad; + assert!(!press(&mut app, egui::Key::ArrowRight, CTRL)); + assert_eq!(app.ui.transform.as_ref().unwrap().quad, q0); +} + +/// #2474: with a selection tool ⌘-arrows move the selected pixels (the temporary Move tool), the +/// plain arrows the outline. +#[test] +fn cmd_arrows_move_the_selected_pixels_with_a_selection_tool() { + let mut app = app_with_layer(); + app.ui.tool = Tool::RectMarquee; + app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 8, "height": 8})).unwrap(); + assert!(press(&mut app, egui::Key::ArrowRight, CTRL)); + let offset = |app: &PhotocraftApp| photocraft_engine::float_cmds::floating(app.session.active().unwrap()).map(|f| f.offset); + assert_eq!(offset(&app), Some((1, 0)), "the selected pixels float, 1 px to the right"); + assert!(press(&mut app, egui::Key::ArrowDown, CTRL | egui::Modifiers::SHIFT)); + assert_eq!(offset(&app), Some((1, 10)), "⌘⇧: 10 px"); + assert_eq!(app.ui.tool, Tool::RectMarquee); + // Not while a polygon is being drawn. + app.ui.tool = Tool::PolygonLasso; + app.ui.polygon = vec![[1.0, 1.0]]; + assert!(!press(&mut app, egui::Key::ArrowRight, CTRL)); +} + +/// #1428: with a selection tool the arrows nudge the selection outline (⇧ 10 px); the layer +/// stays put. Without a selection they are left alone. One step each with Bundle Arrow-Key +/// Nudges off (#2259). +#[test] +fn arrow_keys_nudge_the_selection_with_a_selection_tool() { + let mut app = app_with_layer(); + app.session.edit_prefs(|p| p.tools.bundle_nudges = false); + let id = app.session.active().unwrap().active_layer.unwrap(); + app.ui.tool = Tool::Lasso; + assert!(!press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE), "no selection: not used"); + app.session.execute("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); + let sel = |app: &PhotocraftApp| app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + let h0 = app.session.active().unwrap().history.past_len(); + assert!(press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE)); + assert!(press(&mut app, egui::Key::ArrowDown, egui::Modifiers::SHIFT)); + assert_eq!(sel(&app), photocraft_geom::Rect::new(5, 14, 15, 24)); + assert_eq!(app.session.active().unwrap().history.past_len(), h0 + 2); + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(8, 8, 24, 24), "pixels stay put"); + // Not while a polygon is being drawn. + app.ui.tool = Tool::PolygonLasso; + app.ui.polygon = vec![[1.0, 1.0]]; + assert!(!press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE)); +} +fn history(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn left_edge(app: &PhotocraftApp, id: photocraft_doc::LayerId) -> i32 { + bounds(app, id).x0 +} + +/// #2259: tapping or holding an arrow key is one History state, so one Undo takes the whole +/// run back (Photoshop folds a run of nudges into one "Move"). +#[test] +fn a_run_of_arrow_nudges_is_one_history_step() { + let mut app = app_with_layer(); + let id = app.session.active().unwrap().active_layer.unwrap(); + let h0 = history(&app); + // Twelve taps, 0.2 s apart, then ⇧ for ten more px: still the same run. + for i in 0..12 { + assert!(press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 5.0 + 0.2 * f64::from(i))); + } + assert!(press_at(&mut app, egui::Key::ArrowDown, egui::Modifiers::SHIFT, 7.6)); + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(20, 18, 36, 34)); + assert_eq!(history(&app), h0 + 1, "thirteen presses, one state"); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Move")); + assert!(app.session.undo()); + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(8, 8, 24, 24), "one Undo takes back the run"); + assert!(app.session.redo()); + assert_eq!(bounds(&app, id), photocraft_geom::Rect::new(20, 18, 36, 34), "and one Redo does it again"); +} + +/// A pause longer than Nudge Bundle Pause starts a new run; a longer pause setting keeps it. +#[test] +fn a_pause_ends_the_run() { + let mut app = app_with_layer(); + let id = app.session.active().unwrap().active_layer.unwrap(); + let h0 = history(&app); + press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 1.0); + press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 1.9); + assert_eq!(history(&app), h0 + 1, "0.9 s: the same run"); + press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 3.0); + assert_eq!(history(&app), h0 + 2, "1.1 s of quiet: a new run"); + app.session.edit_prefs(|p| p.tools.nudge_bundle_pause_ms = 5000); + press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 7.0); + assert_eq!(history(&app), h0 + 2, "4 s with a 5 s pause: the same run"); + assert_eq!(left_edge(&app, id), 12); + assert!(app.session.undo()); + assert_eq!(left_edge(&app, id), 10, "Undo takes back the second run only"); +} + +/// With Bundle Arrow-Key Nudges off every press is a state, as before (#2259). +#[test] +fn every_press_is_a_step_with_bundling_off() { + let mut app = app_with_layer(); + let id = app.session.active().unwrap().active_layer.unwrap(); + app.session.edit_prefs(|p| p.tools.bundle_nudges = false); + let h0 = history(&app); + for _ in 0..5 { + assert!(press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE)); + } + assert_eq!(history(&app), h0 + 5); + assert!(app.session.undo()); + assert_eq!(left_edge(&app, id), 12, "one pixel back"); + // Turning it back on bundles the next run, which doesn't swallow the earlier steps. + app.session.edit_prefs(|p| p.tools.bundle_nudges = true); + for _ in 0..3 { + press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE); + } + assert_eq!(history(&app), h0 + 5); + assert_eq!(left_edge(&app, id), 15); +} + +/// Any other change to the document ends the run: another edit, Undo, a different layer +/// selected, a save. +#[test] +fn other_changes_end_the_run() { + let mut app = app_with_layer(); + let a = app.session.active().unwrap().active_layer.unwrap(); + let tap = |app: &mut PhotocraftApp| assert!(press(app, egui::Key::ArrowRight, egui::Modifiers::NONE)); + let h0 = history(&app); + tap(&mut app); + tap(&mut app); + assert_eq!(history(&app), h0 + 1); + // An edit of another kind between two nudges. + app.session.execute("layer.setProps", json!({"opacity": 0.5})).unwrap(); + tap(&mut app); + tap(&mut app); + assert_eq!(history(&app), h0 + 3, "nudges, the edit, nudges"); + // Undo ends it too: the next nudge is a state of its own, not folded into the one before. + assert!(app.session.undo()); + tap(&mut app); + assert_eq!(history(&app), h0 + 3); + assert!(app.session.undo()); + assert_eq!(left_edge(&app, a), 10, "the new run was undone alone"); + // Saving keeps the saved state a step of its own. + tap(&mut app); + tap(&mut app); + let before = history(&app); + let st = app.session.active_mut().unwrap(); + st.saved_revision = st.revision; + tap(&mut app); + assert_eq!(history(&app), before + 1, "a save between two nudges ends the run"); + // Selecting another layer: the same keys now move that one, in a run of its own. + let b = { + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.active().unwrap().active_layer.unwrap() + }; + assert_ne!(a, b); + let before = history(&app); + app.session + .edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + tap(&mut app); + app.session.select_layer(a).unwrap(); + tap(&mut app); + assert_eq!(history(&app), before + 3, "paint, a nudge of the new layer, a nudge of the first"); +} + +/// ⌥ copies, so ⌥-nudges are never folded into a run (the copy is part of each step). +#[test] +fn alt_nudges_do_not_join_a_run() { + let mut app = app_with_layer(); + let h0 = history(&app); + press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE); + press(&mut app, egui::Key::ArrowRight, egui::Modifiers::ALT); + press(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE); + assert_eq!(history(&app), h0 + 3); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Move"), "the run after the copy is a state of its own"); +} + +/// #2259: nudges of the selection outline bundle the same way. +#[test] +fn selection_outline_nudges_bundle_into_one_step() { + let mut app = app_with_layer(); + app.ui.tool = Tool::Lasso; + app.session.execute("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); + let sel = |app: &PhotocraftApp| app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + let h0 = history(&app); + for i in 0..5 { + assert!(press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 2.0 + 0.1 * f64::from(i))); + } + assert!(press_at(&mut app, egui::Key::ArrowDown, egui::Modifiers::SHIFT, 2.6)); + assert_eq!(sel(&app), photocraft_geom::Rect::new(9, 14, 19, 24)); + assert_eq!(history(&app), h0 + 1); + assert!(app.session.undo()); + assert_eq!(sel(&app), photocraft_geom::Rect::new(4, 4, 14, 14), "Undo takes the outline back where it was drawn"); + // The layer nudge and the outline nudge are different runs even back to back. + app.session.execute("select.deselect", json!({})).unwrap(); + app.ui.tool = Tool::Move; + let h1 = history(&app); + press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 3.0); + assert_eq!(history(&app), h1 + 1); +} + +/// Free Transform: nudges of the box that follow each other are one Undo step of the session +/// (it has its own history); a drag or a pause starts another. +#[test] +fn free_transform_nudges_bundle_into_one_undo_step() { + let mut app = app_with_layer(); + let ctx = egui::Context::default(); + crate::transform_tool::begin(&mut app, &ctx).unwrap(); + let quad = |app: &PhotocraftApp| app.ui.transform.as_ref().unwrap().quad; + let q0 = quad(&app); + let moved = |dx: f64, dy: f64| q0.map(|q| [q[0] + dx, q[1] + dy]); + let settle = |app: &mut PhotocraftApp| crate::transform_tool::track_steps(app, &ctx); + for i in 0..6 { + assert!(press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 4.0 + 0.1 * f64::from(i))); + settle(&mut app); + } + assert_eq!(quad(&app), moved(6.0, 0.0)); + // A pause, and the next nudge is a step of its own. + assert!(press_at(&mut app, egui::Key::ArrowDown, egui::Modifiers::NONE, 9.0)); + settle(&mut app); + assert_eq!( + quad(&app), + [[q0[0][0] + 6.0, q0[0][1] + 1.0], [q0[1][0] + 6.0, q0[1][1] + 1.0], [q0[2][0] + 6.0, q0[2][1] + 1.0], [q0[3][0] + 6.0, q0[3][1] + 1.0]] + ); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(quad(&app), moved(6.0, 0.0), "Undo takes back the late nudge only"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(quad(&app), q0, "and the next one the six that were bundled"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(quad(&app), q0, "nothing is left of the session to undo"); + // With bundling off every nudge is a step. + app.session.edit_prefs(|p| p.tools.bundle_nudges = false); + for i in 0..3 { + press_at(&mut app, egui::Key::ArrowRight, egui::Modifiers::NONE, 20.0 + 0.1 * f64::from(i)); + settle(&mut app); + } + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(quad(&app), moved(2.0, 0.0)); +} From d3ff9f6b8190564db90efef7b29e347bad7643cf Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:32 +0000 Subject: [PATCH 055/259] refactor(ui-egui): move crop_ui.rs tests to crop_ui/tests.rs --- crates/ui-egui/src/crop_ui.rs | 1138 +-------------------------- crates/ui-egui/src/crop_ui/tests.rs | 1135 ++++++++++++++++++++++++++ 2 files changed, 1136 insertions(+), 1137 deletions(-) create mode 100644 crates/ui-egui/src/crop_ui/tests.rs diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index d922aa3290..dc852d47c1 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -1044,1140 +1044,4 @@ fn resize_icon(hx: i8, hy: i8, deg: f64, flip: bool) -> CursorIcon { } #[cfg(test)] -mod tests { - use super::*; - use crate::canvas::tool_event; - use photocraft_doc::{Color, ColorMode, Document, SampleType, Size}; - use serde_json::json; - - const NONE: Modifiers = Modifiers::NONE; - const SHIFT: Modifiers = Modifiers::SHIFT; - - fn app(depth: SampleType) -> PhotocraftApp { - let doc = Document::with_background("crop", Size::new(200, 100), ColorMode::Rgb, depth, 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::Crop; - // These tests pin Classic Mode (the frame moves and turns over the image); the default - // mode's are in `crop_mode`. - app.ui.tool_options.crop_shield.classic_mode = true; - app.ui.extras.snap = false; - app.ui.view.show.smart_guides = false; - app - } - - fn drag(app: &mut PhotocraftApp, pts: &[[f64; 2]], mods: Modifiers) { - let (first, last) = (pts[0], pts[pts.len() - 1]); - tool_event(app, ToolEvent::Down { x: first[0], y: first[1], pressure: 1.0 }, mods); - for p in &pts[1..] { - tool_event(app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }, mods); - } - tool_event(app, ToolEvent::Up { x: last[0], y: last[1] }, mods); - } - - #[test] - fn fitting_a_ratio_keeps_the_centre_angle_and_area() { - let mut app = app(SampleType::U8); - app.ui.crop_rect = Some([20.0, 10.0, 180.0, 90.0]); - app.ui.crop_angle = 25.0; - for key in ["1:1", "16:9", "9:16", "", "0:0"] { - let before = app.ui.crop_rect.unwrap(); - app.ui.tool_options.crop_ratio = key.into(); - crate::crop_size::chosen(&mut app); - let after = app.ui.crop_rect.unwrap(); - assert_eq!(center(after), center(before)); - assert_eq!(app.ui.crop_angle, 25.0); - assert!(after[0] >= before[0] && after[1] >= before[1] && after[2] <= before[2] && after[3] <= before[3]); - if let Some(ratio) = preset_ratio(&app) { - assert!(((after[2] - after[0]) / (after[3] - after[1]) - ratio).abs() < 1e-10); - } else { - assert_eq!(after, before); - } - } - for ratio in [0.0, -1.0, f64::NAN, f64::INFINITY] { - assert!(fitted_ratio([0.0, 0.0, 200.0, 100.0], ratio).is_none()); - } - assert!(fitted_ratio([-f64::MAX, 0.0, f64::MAX, 100.0], 1.0).is_none()); - } - - #[test] - fn choosing_a_ratio_fits_and_commits_without_a_resize() { - for classic in [false, true] { - let mut app = app(SampleType::U8); - app.ui.tool_options.crop_shield.classic_mode = classic; - ensure_frame(&mut app); - app.ui.tool_options.crop_ratio = "1:1".into(); - crate::crop_size::chosen(&mut app); - assert_eq!(app.ui.crop_rect, Some([50.0, 0.0, 150.0, 100.0])); - crate::canvas::commit_crop(&mut app); - assert_eq!(app.session.active().unwrap().doc.size, Size::new(100, 100)); - } - } - - #[test] - fn entering_crop_with_a_saved_ratio_fits_the_selection_or_canvas() { - let mut app = app(SampleType::U8); - app.ui.tool_options.crop_ratio = "1:1".into(); - ensure_frame(&mut app); - assert_eq!(app.ui.crop_rect, Some([50.0, 0.0, 150.0, 100.0])); - cancel(&mut app); - app.run("select.rect", json!({"x": 20, "y": 10, "width": 80, "height": 40})).unwrap(); - ensure_frame(&mut app); - assert_eq!(app.ui.crop_rect, Some([40.0, 10.0, 80.0, 50.0])); - } - - #[test] - fn picking_the_tool_frames_the_canvas_or_the_selection() { - // #668: the Crop tool started with no frame. - let mut app = app(SampleType::U8); - ensure_frame(&mut app); - assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 200.0, 100.0])); - // Committing the untouched frame crops nothing. - let steps = app.session.active().unwrap().history.past_len(); - crate::canvas::commit_crop(&mut app); - assert_eq!(app.session.active().unwrap().history.past_len(), steps); - assert_eq!(app.session.active().unwrap().doc.size, Size::new(200, 100)); - // A drag inside the untouched frame draws a new one instead of moving it. - ensure_frame(&mut app); - drag(&mut app, &[[50.0, 20.0], [80.0, 40.0], [120.0, 70.0]], NONE); - assert_eq!(app.ui.crop_rect, Some([50.0, 20.0, 120.0, 70.0])); - // Now it's a real frame: a drag inside moves it. - drag(&mut app, &[[60.0, 30.0], [70.0, 30.0]], NONE); - assert_eq!(app.ui.crop_rect, Some([60.0, 20.0, 130.0, 70.0])); - // Cancelling frames the selection's bounds when there is one. - app.run("select.rect", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); - app.ui.crop_rect = None; - ensure_frame(&mut app); - assert_eq!(app.ui.crop_rect, Some([10.0, 10.0, 40.0, 30.0])); - // Leaving the tool drops the untouched frame. - app.ui.tool = Tool::Brush; - ensure_frame(&mut app); - assert_eq!(app.ui.crop_rect, None); - } - - #[test] - fn enter_on_the_selection_frame_crops_to_it_at_8_and_16_bit() { - // #1789: selection, C, ↵ did nothing, as the untouched frame was always treated as a no-op. - for depth in [SampleType::U8, SampleType::U16] { - let mut app = app(depth); - app.run("select.rect", json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap(); - ensure_frame(&mut app); - assert_eq!(app.ui.crop_rect, Some([10.0, 20.0, 40.0, 60.0])); - crate::canvas::commit_crop(&mut app); - let doc = &app.session.active().unwrap().doc; - assert_eq!(doc.size, Size::new(30, 40), "{depth:?}"); - assert_eq!(doc.depth, depth); - assert!(doc.selection.is_none(), "cropping to the selection deselects, as in Photoshop"); - // The new default frame is the whole (cropped) canvas: ↵ on it does nothing. - ensure_frame(&mut app); - assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 30.0, 40.0])); - let steps = app.session.active().unwrap().history.past_len(); - crate::canvas::commit_crop(&mut app); - let st = app.session.active().unwrap(); - assert_eq!((st.doc.size, st.history.past_len()), (Size::new(30, 40), steps), "{depth:?}"); - } - } - - #[test] - fn the_frame_is_edited_from_a_press_until_commit_cancel_or_another_tool() { - let mut app = app(SampleType::U8); - ensure_frame(&mut app); - assert!(!shows_beyond_canvas(&app), "a new frame is not being edited"); - assert!(press(&mut app)); - assert!(shows_beyond_canvas(&app)); - assert!(!press(&mut app), "only the first press is news"); - // A click on the frame keeps it edited. - drag(&mut app, &[[50.0, 50.0]], NONE); - assert!(shows_beyond_canvas(&app)); - // Esc drops the frame: the new default one isn't edited. - app.ui.crop_rect = None; - ensure_frame(&mut app); - assert!(!shows_beyond_canvas(&app)); - // A drawn frame is edited until it is committed. - drag(&mut app, &[[10.0, 10.0], [60.0, 40.0]], NONE); - assert!(shows_beyond_canvas(&app)); - crate::canvas::commit_crop(&mut app); - ensure_frame(&mut app); - assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 50.0, 30.0])); - assert!(!shows_beyond_canvas(&app)); - // Or until another tool is picked. - drag(&mut app, &[[5.0, 5.0], [20.0, 20.0]], NONE); - app.ui.tool = Tool::Brush; - ensure_frame(&mut app); - assert!(!app.crop.editing && !shows_beyond_canvas(&app)); - assert!(!press(&mut app), "no frame without the Crop tool"); - } - - #[test] - fn hit_test_finds_handles_inside_and_outside() { - let r = [10.0, 10.0, 110.0, 60.0]; - assert_eq!(hit(r, [10.0, 10.0], 4.0), Hit::Handle(-1, -1)); - assert_eq!(hit(r, [112.0, 61.0], 4.0), Hit::Handle(1, 1)); - assert_eq!(hit(r, [60.0, 8.0], 4.0), Hit::Handle(0, -1)); - assert_eq!(hit(r, [108.0, 30.0], 4.0), Hit::Handle(1, 0)); - assert_eq!(hit(r, [60.0, 30.0], 4.0), Hit::Inside); - assert_eq!(hit(r, [150.0, 30.0], 4.0), Hit::Outside); - // A tiny frame keeps a movable middle. - assert_eq!(hit([0.0, 0.0, 4.0, 4.0], [2.0, 2.0], 8.0), Hit::Inside); - } - - #[test] - fn dragging_inside_moves_the_frame() { - let mut app = app(SampleType::U8); - drag(&mut app, &[[20.0, 20.0], [80.0, 60.0]], NONE); - assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 80.0, 60.0])); - drag(&mut app, &[[50.0, 40.0], [60.0, 45.0], [70.0, 50.0]], NONE); - assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0]), "moved, not redrawn"); - // A click outside keeps the frame (and leaves it upright). - drag(&mut app, &[[5.0, 5.0]], NONE); - assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0])); - assert_eq!(app.ui.crop_angle, 0.0); - // Outside, a drag turns the frame rather than drawing a new one (#1792). - drag(&mut app, &[[150.0, 50.0], [190.0, 90.0]], NONE); - assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0])); - assert!(app.ui.crop_angle > 10.0, "{}", app.ui.crop_angle); - } - - #[test] - fn dragging_outside_turns_the_frame_about_its_centre() { - let mut app = app(SampleType::U8); - app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]); - // Centre (70, 50): from straight right to straight below is a quarter turn clockwise. - drag(&mut app, &[[150.0, 50.0], [140.0, 70.0], [70.0, 95.0]], NONE); - assert!((app.ui.crop_angle - 90.0).abs() < 1e-9, "{}", app.ui.crop_angle); - assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0]), "turning keeps the frame"); - // Back the other way, past -180 (normalised). - drag(&mut app, &[[70.0, 120.0], [-10.0, 50.0], [70.0, -20.0]], NONE); - assert!((app.ui.crop_angle - -90.0).abs() < 1e-9, "{}", app.ui.crop_angle); - // ⇧ snaps the angle to 15° steps. - app.ui.crop_angle = 0.0; - let a = 22.0f64.to_radians(); - drag(&mut app, &[[150.0, 50.0], [70.0 + 80.0 * a.cos(), 50.0 + 80.0 * a.sin()]], SHIFT); - assert_eq!(app.ui.crop_angle, 15.0); - assert_eq!(cursor(&app, [150.0, 50.0]), Some(CursorIcon::None), "outside: the drawn turn cursor"); - // Turning the untouched default frame makes it a real frame; a click outside it doesn't. - let mut app = super::tests::app(SampleType::U8); - ensure_frame(&mut app); - drag(&mut app, &[[250.0, 50.0]], NONE); - assert!(app.crop.default_frame, "a click outside keeps the default frame"); - drag(&mut app, &[[250.0, 50.0], [250.0, 80.0]], NONE); - assert!(!app.crop.default_frame && app.ui.crop_angle > 0.0); - // Esc (no frame) starts the next one upright. - app.ui.crop_rect = None; - ensure_frame(&mut app); - assert_eq!((app.ui.crop_rect, app.ui.crop_angle), (Some([0.0, 0.0, 200.0, 100.0]), 0.0)); - } - - #[test] - fn hit_testing_a_turned_frame_uses_its_own_axes() { - let r = [40.0, 30.0, 100.0, 70.0]; - // A quarter turn: the frame covers x 50..90, y 20..80 on the page. - assert_eq!(hit_turned(r, 90.0, [70.0, 75.0], 2.0), Hit::Inside, "inside the turned frame only"); - assert_eq!(hit(r, [70.0, 75.0], 2.0), Hit::Outside); - assert_eq!(hit_turned(r, 90.0, [45.0, 50.0], 2.0), Hit::Outside, "inside the upright frame only: the rotate zone"); - // The upright frame's top-left corner turns to the top-right of the page. - assert_eq!(hit_turned(r, 90.0, [90.0, 20.0], 2.0), Hit::Handle(-1, -1)); - // Its right edge's middle is now at the bottom. - assert_eq!(hit_turned(r, 90.0, [70.0, 80.0], 2.0), Hit::Handle(1, 0)); - let c = corners(r, 90.0); - for (a, b) in c.iter().zip([[90.0, 20.0], [90.0, 80.0], [50.0, 80.0], [50.0, 20.0]]) { - assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9, "{c:?}"); - } - let b = turned_bounds(r, 90.0); - assert!((b[0] - 50.0).abs() < 1e-9 && (b[3] - 80.0).abs() < 1e-9, "{b:?}"); - // Handle arrows turn with the frame. - assert_eq!(resize_icon(1, 0, 0.0, false), CursorIcon::ResizeHorizontal); - assert_eq!(resize_icon(1, 0, 90.0, false), CursorIcon::ResizeVertical); - assert_eq!(resize_icon(1, 0, 45.0, false), CursorIcon::ResizeNwSe); - assert_eq!(resize_icon(-1, -1, 90.0, false), CursorIcon::ResizeNeSw); - assert_eq!(normalized_angle(540.0), 180.0); - assert_eq!(normalized_angle(-190.0), 170.0); - assert_eq!(normalized_angle(f64::NAN), 0.0); - } - - #[test] - fn resizing_a_turned_frame_moves_along_its_axes_and_keeps_the_opposite_edge() { - let r = [40.0, 30.0, 100.0, 70.0]; - // At 90°, the right edge (local +x) faces down the page: dragging down 10 grows the width. - let n = resized_turned(r, 90.0, 1, 0, [0.0, 10.0], None, false); - assert!(((n[2] - n[0]) - 70.0).abs() < 1e-9 && ((n[3] - n[1]) - 40.0).abs() < 1e-9, "{n:?}"); - // The opposite (left) edge stays put on the page: at y = 20 with x 50..90. - let (old, new) = (corners(r, 90.0), corners(n, 90.0)); - for (i, (a, b)) in [(0, 0), (3, 3)].map(|(i, j)| (old[i], new[j])).iter().enumerate() { - assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9, "corner {i}: {a:?} vs {b:?}"); - } - // A sideways drag does nothing to that handle. - let same = resized_turned(r, 90.0, 1, 0, [25.0, 0.0], None, false); - assert!(same.iter().zip(r).all(|(a, b)| (a - b).abs() < 1e-9), "{same:?}"); - // At 0° it is the plain resize. - assert_eq!(resized_turned(r, 0.0, 1, 1, [5.0, 6.0], None, false), resized(r, 1, 1, [5.0, 6.0], None, false)); - // Through the pointer: grabbing the turned right-edge handle and dragging down 10. - let mut app = app(SampleType::U8); - app.ui.crop_rect = Some(r); - app.ui.crop_angle = 90.0; - drag(&mut app, &[[70.0, 80.0], [70.0, 90.0]], NONE); - let got = app.ui.crop_rect.unwrap(); - assert!(got.iter().zip(n).all(|(a, b)| (a - b).abs() < 1e-9), "{got:?} vs {n:?}"); - // Moving a turned frame is a plain translation, angle kept. - drag(&mut app, &[[70.0, 50.0], [80.0, 55.0]], NONE); - let moved = app.ui.crop_rect.unwrap(); - assert!(moved.iter().zip([n[0] + 10.0, n[1] + 5.0, n[2] + 10.0, n[3] + 5.0]).all(|(a, b)| (a - b).abs() < 1e-9), "{moved:?}"); - assert_eq!(app.ui.crop_angle, 90.0); - } - - /// ↵ on a turned frame crops the turned document (one step), at 8, 16 and 32 bits. - #[test] - fn commit_crops_to_the_turned_frame() { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - let mut app = app(depth); - app.run("select.rect", json!({"x": 60, "y": 40, "width": 1, "height": 1})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.run("select.deselect", json!({})).unwrap(); - let past = app.session.active().unwrap().history.past_len(); - // A 40 × 20 frame centred on (60, 40), turned 90° by a drag outside it. - app.ui.crop_rect = Some([40.0, 30.0, 80.0, 50.0]); - app.crop.default_frame = false; - drag(&mut app, &[[120.0, 40.0], [60.0, 100.0]], NONE); - assert!((app.ui.crop_angle - 90.0).abs() < 1e-6, "{depth:?}: {}", app.ui.crop_angle); - crate::canvas::commit_crop(&mut app); - assert!(app.ui.crop_rect.is_none()); - assert_eq!(app.ui.crop_angle, 0.0, "the next frame starts upright"); - let st = app.session.active().unwrap(); - assert_eq!(st.history.past_len(), past + 1, "{depth:?}: one undo step"); - assert_eq!((st.doc.size.width, st.doc.size.height), (40, 20), "{depth:?}"); - assert_eq!(st.doc.depth, depth); - // The red pixel was at the frame's centre: it is at the cropped image's centre. - let surf = st.doc.layers[0].surface().unwrap(); - let red = (19..=21).flat_map(|x| (9..=11).map(move |y| (x, y))).map(|(x, y)| surf.rgba(x, y)).find(|px| px[0] > 0.6 && px[1] < 0.4); - assert!(red.is_some(), "{depth:?}: no red at the centre"); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(app.session.active().unwrap().doc.size, Size::new(200, 100), "{depth:?}"); - } - } - - /// Fill › Content-Aware Fill (#3823): ↵ on an extending frame fills the added canvas from the - /// image instead of the background colour; Background (Default) keeps the colour. - #[test] - fn commit_passes_the_fill_choice() { - for content_aware in [false, true] { - let mut app = app(SampleType::U16); - app.run("tools.setColors", json!({"foreground": "#808080", "background": "#000000"})).unwrap(); - app.run("edit.fill", json!({"contents": "foreground"})).unwrap(); - app.ui.tool_options.crop_content_aware = content_aware; - app.ui.crop_rect = Some([-10.0, -10.0, 210.0, 110.0]); - app.crop.default_frame = false; - crate::canvas::commit_crop(&mut app); - let st = app.session.active().unwrap(); - assert_eq!((st.doc.size.width, st.doc.size.height), (220, 120)); - let corner = st.doc.layers[0].surface().unwrap().rgba(0, 0); - if content_aware { - assert!((corner[0] - 0.5).abs() < 0.05, "filled from the grey image: {corner:?}"); - } else { - assert!(corner[0] < 0.05, "the background colour: {corner:?}"); - } - } - } - - #[test] - fn moving_the_frame_snaps_its_edges() { - let mut app = app(SampleType::U8); - app.ui.extras.snap = true; - app.ui.crop_rect = Some([10.0, 10.0, 50.0, 40.0]); - drag(&mut app, &[[30.0, 25.0], [23.0, 25.0]], NONE); - assert_eq!(app.ui.crop_rect, Some([0.0, 10.0, 40.0, 40.0]), "left edge snaps to the document edge"); - } - - /// #3145: Edit › Undo while a crop is pending steps the *box*, not the document (Photoshop keeps - /// Undo live during a crop), so a moved frame comes back. - #[test] - fn edit_undo_steps_the_crop_box_not_the_document() { - let mut app = app(SampleType::U8); - app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]); - app.crop.default_frame = false; - let before = app.ui.crop_rect.unwrap(); - let doc_steps = app.session.active().unwrap().history.past_len(); - drag(&mut app, &[[70.0, 50.0], [90.0, 50.0]], NONE); // move the frame right 20 - let moved = app.ui.crop_rect.unwrap(); - assert!((moved[0] - 60.0).abs() < 1e-3, "{moved:?}"); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(app.ui.crop_rect, Some(before), "undo restores the box"); - assert_eq!(app.session.active().unwrap().history.past_len(), doc_steps, "the document is untouched"); - app.run("edit.redo", json!({})).unwrap(); - assert!((app.ui.crop_rect.unwrap()[0] - 60.0).abs() < 1e-3, "redo re-applies the move"); - } - - /// Once the box has no step left in one direction, that command greys out rather than staying - /// live over the document's history and doing nothing (as the Free Transform box does). - #[test] - fn box_undo_and_redo_grey_out_when_their_stack_is_empty() { - let mut app = app(SampleType::U8); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - assert!(app.session.active().unwrap().history.can_undo()); - app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]); - app.crop.default_frame = false; - drag(&mut app, &[[70.0, 50.0], [90.0, 50.0]], NONE); - assert!(crate::menus::is_enabled(&app, "edit.undo")); - assert!(!crate::menus::is_enabled(&app, "edit.redo"), "no box step to redo"); - app.run("edit.undo", json!({})).unwrap(); - assert!(!crate::menus::is_enabled(&app, "edit.undo"), "no box step left to undo"); - assert!(crate::menus::is_enabled(&app, "edit.redo")); - } - - #[test] - fn handles_resize_with_shift_and_alt() { - let mut app = app(SampleType::U8); - app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); - // Right edge. - drag(&mut app, &[[100.0, 40.0], [120.0, 50.0]], NONE); - assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 120.0, 60.0])); - // Bottom-right corner, free. - drag(&mut app, &[[120.0, 60.0], [140.0, 70.0]], NONE); - assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 140.0, 70.0])); - // ⇧ keeps 120:50 from the top-left corner: the larger relative extent wins. - app.ui.crop_rect = Some([20.0, 20.0, 140.0, 70.0]); - drag(&mut app, &[[20.0, 20.0], [10.0, 0.0]], SHIFT); - let r = app.ui.crop_rect.unwrap(); - assert_eq!((r[2], r[3]), (140.0, 70.0), "opposite corner fixed"); - assert!(((r[2] - r[0]) / (r[3] - r[1]) - 120.0 / 50.0).abs() < 1e-9, "{r:?}"); - assert_eq!(r[3] - r[1], 70.0); - // ⌥ resizes about the centre. - app.ui.crop_rect = Some([40.0, 20.0, 80.0, 60.0]); - drag(&mut app, &[[80.0, 40.0], [90.0, 40.0]], Modifiers::ALT); - assert_eq!(app.ui.crop_rect, Some([30.0, 20.0, 90.0, 60.0])); - // An options-bar ratio holds on an edge drag, centred on the other axis. - app.ui.tool_options.crop_ratio = "1:1".into(); - app.ui.crop_rect = Some([40.0, 20.0, 80.0, 60.0]); - drag(&mut app, &[[80.0, 40.0], [100.0, 40.0]], NONE); - assert_eq!(app.ui.crop_rect, Some([40.0, 10.0, 100.0, 70.0])); - } - - #[test] - fn dragging_a_handle_past_the_other_side_flips_and_collapse_reverts() { - let mut app = app(SampleType::U8); - app.ui.crop_rect = Some([20.0, 20.0, 60.0, 60.0]); - drag(&mut app, &[[60.0, 40.0], [10.0, 40.0]], NONE); - assert_eq!(app.ui.crop_rect, Some([10.0, 20.0, 20.0, 60.0])); - // Collapsing to nothing restores the frame the gesture started from. - drag(&mut app, &[[20.0, 40.0], [10.0, 40.0]], NONE); - assert_eq!(app.ui.crop_rect, Some([10.0, 20.0, 20.0, 60.0])); - } - - #[test] - fn space_repositions_the_frame_being_drawn() { - let mut app = app(SampleType::U8); - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, NONE); - tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 40.0, pressure: 1.0 }, NONE); - assert!(active(&app)); - set_space(&mut app, true); - tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 50.0, pressure: 1.0 }, NONE); - assert_eq!(app.ui.crop_rect, Some([30.0, 20.0, 70.0, 50.0]), "same size, moved"); - set_space(&mut app, false); - tool_event(&mut app, ToolEvent::Move { x: 90.0, y: 60.0, pressure: 1.0 }, NONE); - tool_event(&mut app, ToolEvent::Up { x: 90.0, y: 60.0 }, NONE); - assert_eq!(app.ui.crop_rect, Some([30.0, 20.0, 90.0, 60.0]), "sizing resumes from the moved anchor"); - assert!(!active(&app)); - } - - /// Real egui input on the canvas: holding Space mid-draw moves the frame instead of panning. - #[test] - fn space_on_the_canvas_moves_the_frame_not_the_view() { - use egui::{Event, Key, PointerButton, pos2}; - let mut a = app(SampleType::U8); - let view = crate::state::View { - zoom: 2.0, - center: [100.0, 50.0], - fit_pending: false, - fill_pending: false, - doc_size: [200, 100], - rotation: 0.0, - zoom_animating: false, - zoom_anchor: None, - display_camera: None, - zoom_transition: None, - }; - a.ui.views = vec![view.clone()]; - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - let v = app.ui.views[0].clone(); - crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true); - }, - a, - ); - h.run_steps(2); - let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; - let space = |pressed| Event::Key { key: Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; - let p0 = pos2(200.0, 150.0); - h.event(Event::PointerMoved(p0)); - h.event(button(p0, true)); - h.step(); - for p in [pos2(220.0, 170.0), pos2(260.0, 190.0)] { - h.event(Event::PointerMoved(p)); - h.step(); - } - let drawn = h.state().ui.crop_rect.unwrap(); - // The frame starts where the button went down (200, 150), not at the first move past - // egui's drag threshold (#123). - assert_eq!((drawn[2] - drawn[0], drawn[3] - drawn[1]), (30.0, 20.0), "60x40 screen px at 200%"); - h.event(space(true)); - h.step(); - for p in [pos2(280.0, 200.0), pos2(300.0, 210.0)] { - h.event(Event::PointerMoved(p)); - h.step(); - } - let moved = h.state().ui.crop_rect.unwrap(); - assert_eq!(moved, [drawn[0] + 20.0, drawn[1] + 10.0, drawn[2] + 20.0, drawn[3] + 10.0], "moved by 40x20 screen px"); - h.event(space(false)); - h.event(button(pos2(300.0, 210.0), false)); - h.step(); - let st = h.state(); - assert_eq!(st.ui.crop_rect, Some(moved)); - assert_eq!(st.ui.views[0].center, view.center, "the view did not pan"); - assert!(st.crop.drag.is_none()); - } - - /// #1918: a pending crop belongs to the document it was drawn on. File › New, opening a file - /// or switching tabs cancels it; it never shows on, or crops, another document. - /// A turned pending frame is dropped with its angle when another document becomes active, and - /// Esc drops both too, so the next frame starts upright. - #[test] - fn cancelling_a_turned_crop_resets_its_angle() { - let mut app = app(SampleType::U8); - drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); - app.ui.crop_angle = 30.0; - app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); - app.sync_views(); - assert_eq!(app.ui.crop_angle, 0.0); - drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); - app.ui.crop_angle = -12.5; - cancel(&mut app); - assert_eq!((app.ui.crop_rect, app.ui.crop_angle, app.crop.drag), (None, 0.0, None)); - } - - #[test] - fn a_pending_crop_stays_with_its_document() { - let size = |app: &PhotocraftApp| app.session.active().map(|st| st.doc.size); - // File › New. - let mut app = app(SampleType::U8); - drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); - assert_eq!(app.ui.crop_rect, Some([10.0, 10.0, 50.0, 40.0])); - app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); - assert_eq!(app.ui.crop_rect, None, "the first document's frame is gone"); - assert!(app.crop.drag.is_none() && !app.crop.editing && !app.crop.default_frame); - crate::canvas::commit_crop(&mut app); - assert_eq!(size(&app), Some(Size::new(300, 150)), "↵ crops nothing"); - // The new document gets its own default frame. - ensure_frame(&mut app); - assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 300.0, 150.0])); - assert!(app.crop.default_frame); - // Switching tabs (outside a command), even before the next frame's sync: ↵ never crops - // the other document. - drag(&mut app, &[[20.0, 20.0], [60.0, 60.0]], NONE); - assert!(app.session.set_active(0)); - crate::canvas::commit_crop(&mut app); - assert_eq!(size(&app), Some(Size::new(200, 100))); - assert_eq!(app.session.documents()[1].doc.size, Size::new(300, 150)); - assert_eq!(app.ui.crop_rect, None); - // The next frame's sync also drops a frame left on a tab switched away from. - drag(&mut app, &[[20.0, 20.0], [60.0, 60.0]], NONE); - assert!(app.session.set_active(1)); - app.sync_views(); - assert_eq!(app.ui.crop_rect, None); - // Closing another document keeps the pending crop; closing its own cancels it. - drag(&mut app, &[[20.0, 20.0], [60.0, 60.0]], NONE); - app.session.close(0); - app.sync_views(); - assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 60.0, 60.0]), "still its document"); - crate::canvas::commit_crop(&mut app); - assert_eq!(size(&app), Some(Size::new(40, 40))); - drag(&mut app, &[[5.0, 5.0], [25.0, 25.0]], NONE); - app.session.close(0); - app.sync_views(); - assert!(app.session.active().is_none()); - assert_eq!(app.ui.crop_rect, None); - assert!(app.crop.drag.is_none()); - crate::canvas::commit_crop(&mut app); - ensure_frame(&mut app); - assert_eq!(app.ui.crop_rect, None, "no document, no frame"); - } - - /// A drag in progress when its document goes away is dropped too, not finished elsewhere. - #[test] - fn a_crop_drag_ends_with_its_document() { - let mut app = app(SampleType::U8); - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, NONE); - tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 40.0, pressure: 1.0 }, NONE); - app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); - tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 50.0 }, NONE); - assert_eq!(app.ui.crop_rect, None); - crate::canvas::commit_crop(&mut app); - assert_eq!(app.session.active().map(|st| st.doc.size), Some(Size::new(300, 150))); - } - - /// #1918: as in Photoshop, a pending crop (not the untouched default frame) greys almost every - /// menu command; the ones Photoshop keeps stay available, and commit or cancel frees the rest. - /// Walks the whole menu catalog. - #[test] - fn a_pending_crop_greys_the_menus_photoshop_greys() { - let mut app = app(SampleType::U8); - ensure_frame(&mut app); - assert!(app.crop.default_frame); - let ids: Vec<&str> = crate::menu_catalog::CATALOG.iter().map(|e| e.3).filter(|id| *id != "---").collect(); - for id in &ids { - assert!(!blocks(&app, id), "default frame: {id} stays as it was"); - } - drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); - assert!(pending(&app)); - let kept = [ - "file.close", - "file.save", - "file.saveAs", - "file.saveACopy", - "edit.undo", - "edit.redo", - "edit.toggleLastState", - "edit.search", - "image.crop", - "view.proofColors", - "view.gamutWarning", - "view.zoomIn", - "view.zoomOut", - "view.fitOnScreen", - "view.actualPixels", - "view.twoHundredPercent", - "view.printSize", - "view.extras", - "view.show.grid", - "view.rulers", - "view.snap", - "view.snapTo.guides", - "view.lockSlices", - "view.newGuide", - "window.arrange.tile", - "window.panel.layers", - "help.about", - ]; - let greyed = [ - "file.new", - "file.open", - "file.openAs", - "file.openExrParts", - "file.closeAll", - "file.revert", - "file.export.exportAs", - "file.placeEmbedded", - "file.automate.batch", - "file.scripts.browse", - "file.import.notes", - "file.fileInfo", - "file.print", - "edit.cut", - "edit.fill", - "edit.freeTransform", - "edit.colorSettings", - "edit.preferences.general", - "image.imageSize", - "image.mode.grayscale", - "layer.new.layer", - "select.all", - "filter.blur.gaussianBlur", - "view.proofSetup.workingCmyk", - "view.pixelAspectRatio.square", - "view.pixelAspectRatioCorrection", - "view.thirtyTwoBitPreviewOptions", - "view.flipHorizontal", - "view.screenMode.fullScreen", - "window.workspace.essentials", - "window.panel.adjustments", - "help.systemInfo", - ]; - for id in kept { - assert!(!blocks(&app, id), "{id} stays available"); - } - for id in greyed { - assert!(blocks(&app, id), "{id} is greyed"); - assert!(!crate::menus::is_enabled(&app, id), "{id} greyed in the menus"); - assert!(!crate::menus::modal_allows(&app, id), "{id} refused over the menu gate"); - } - assert!( - ids.iter() - .filter(|id| id.starts_with("layer.") || id.starts_with("type.") || id.starts_with("select.") || id.starts_with("filter.")) - .all(|id| blocks(&app, id)) - ); - // Committing still runs `image.crop` itself, and frees the menus again. - crate::canvas::commit_crop(&mut app); - assert_eq!(app.session.active().unwrap().doc.size, Size::new(40, 30)); - assert!(!pending(&app) && crate::menus::is_enabled(&app, "file.new")); - // Cancelling does too. - drag(&mut app, &[[5.0, 5.0], [20.0, 20.0]], NONE); - assert!(blocks(&app, "file.new")); - cancel(&mut app); - assert!(!blocks(&app, "file.new")); - // Another tool: nothing is pending. - drag(&mut app, &[[5.0, 5.0], [20.0, 20.0]], NONE); - app.ui.tool = Tool::Brush; - assert!(!blocks(&app, "file.new")); - } - - /// #3368: as in Photoshop, picking another tool (toolbar or its key) with a drawn frame - /// commits the crop silently, and the new tool is current. - #[test] - fn another_tool_commits_a_drawn_frame_at_8_and_16_bit() { - for depth in [SampleType::U8, SampleType::U16] { - let mut app = app(depth); - drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); - assert!(pending(&app)); - app.ui.tool = Tool::Move; - ensure_frame(&mut app); - let st = app.session.active().unwrap(); - assert_eq!((st.doc.size, st.doc.depth), (Size::new(40, 30), depth)); - assert_eq!(st.history.undo_label(), Some("Crop")); - assert_eq!(app.ui.tool, Tool::Move); - assert_eq!((app.ui.crop_rect, app.ui.crop_angle), (None, 0.0)); - // Nothing is left to commit: back on the Crop tool, the new canvas gets a default frame. - ensure_frame(&mut app); - assert_eq!(app.session.active().unwrap().doc.size, Size::new(40, 30)); - app.ui.tool = Tool::Crop; - ensure_frame(&mut app); - assert!(app.crop.default_frame && app.ui.crop_rect == Some([0.0, 0.0, 40.0, 30.0])); - } - } - - /// #3368, default mode: a turned frame crops turned, and the view it turned is left upright. - #[test] - fn another_tool_commits_a_turned_frame_and_leaves_the_view_upright() { - let mut app = app(SampleType::U8); - app.sync_views(); - app.ui.tool_options.crop_shield.classic_mode = false; - app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]); - app.ui.crop_angle = 10.0; - ensure_frame(&mut app); - assert!(pending(&app) && crate::crop_mode::view_rotation(&app) != 0.0); - app.ui.tool = Tool::Brush; - ensure_frame(&mut app); - assert_eq!(app.session.active().unwrap().doc.size, Size::new(60, 40)); - assert_eq!(crate::crop_mode::view_rotation(&app), 0.0); - assert_eq!((app.ui.tool, app.ui.crop_rect), (Tool::Brush, None)); - } - - /// #3368: the untouched default frame (the canvas, or the selection's bounds) is just dropped - /// on leaving the tool: nothing is cropped. - #[test] - fn another_tool_drops_an_untouched_default_frame() { - for select in [false, true] { - let mut app = app(SampleType::U8); - if select { - app.run("select.rect", json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap(); - } - ensure_frame(&mut app); - assert!(app.crop.default_frame && app.ui.crop_rect.is_some()); - let steps = app.session.active().unwrap().history.past_len(); - app.ui.tool = Tool::Move; - ensure_frame(&mut app); - let st = app.session.active().unwrap(); - assert_eq!((st.doc.size, st.history.past_len()), (Size::new(200, 100), steps), "selection: {select}"); - assert_eq!(app.ui.crop_rect, None); - } - } - - /// #6750: a ratio preset that shrinks the untouched default frame does not make it a drawn - /// one: leaving the tool drops the frame and crops nothing, as with the plain default frame. - /// Picking the ratio before entering the tool (the issue's repro) and while it is picked both - /// stay untouched; editing the fitted frame makes it a drawn one that leaving commits (#3368). - #[test] - fn another_tool_drops_an_untouched_ratio_fitted_frame() { - // Entering the Crop tool with a saved ratio: the frame is fitted but untouched. - let mut app = app(SampleType::U8); - app.ui.tool_options.crop_ratio = "1:1".into(); - ensure_frame(&mut app); - assert_eq!(app.ui.crop_rect, Some([50.0, 0.0, 150.0, 100.0]), "the default frame is fitted to the ratio"); - assert!(app.crop.default_frame, "fitting it is not an edit"); - let steps = app.session.active().unwrap().history.past_len(); - app.ui.tool = Tool::Move; - ensure_frame(&mut app); - let st = app.session.active().unwrap(); - assert_eq!((st.doc.size, st.history.past_len()), (Size::new(200, 100), steps), "switching tools must not crop"); - assert_eq!(app.ui.crop_rect, None); - // Choosing the ratio with the Crop tool already picked: the same untouched fit. - let mut app2 = self::app(SampleType::U8); - ensure_frame(&mut app2); - app2.ui.tool_options.crop_ratio = "1:1".into(); - crate::crop_size::chosen(&mut app2); - assert_eq!(app2.ui.crop_rect, Some([50.0, 0.0, 150.0, 100.0])); - assert!(app2.crop.default_frame); - let steps = app2.session.active().unwrap().history.past_len(); - app2.ui.tool = Tool::Move; - ensure_frame(&mut app2); - let st = app2.session.active().unwrap(); - assert_eq!((st.doc.size, st.history.past_len()), (Size::new(200, 100), steps)); - // Resizing a handle of the fitted frame is an edit: leaving commits it (#3368). - let mut app3 = self::app(SampleType::U8); - app3.ui.tool_options.crop_ratio = "1:1".into(); - ensure_frame(&mut app3); - drag(&mut app3, &[[50.0, 0.0], [70.0, 20.0]], NONE); - assert!(!app3.crop.default_frame, "the resize made it a drawn frame"); - app3.ui.tool = Tool::Move; - ensure_frame(&mut app3); - assert_eq!(app3.session.active().unwrap().doc.size, Size::new(80, 80), "the edited frame crops"); - // Default (non-classic) mode, the issue's exact scenario: the fitted preview stays a - // preview; pressing V neither crops nor applies anything. - let mut app4 = self::app(SampleType::U8); - app4.ui.tool_options.crop_shield.classic_mode = false; - app4.sync_views(); - app4.ui.tool_options.crop_ratio = "1:1".into(); - ensure_frame(&mut app4); - assert!(app4.crop.default_frame, "the fitted preview is still the untouched frame"); - let steps = app4.session.active().unwrap().history.past_len(); - app4.ui.tool = Tool::Move; - ensure_frame(&mut app4); - let st = app4.session.active().unwrap(); - assert_eq!((st.doc.size, st.history.past_len()), (Size::new(200, 100), steps)); - } - - /// The pen's eraser end stands in for the Crop tool only until the tip comes back (`stylus`), - /// and a gesture still in progress isn't cut short: neither commits the frame. - #[test] - fn the_stylus_eraser_and_a_gesture_in_progress_keep_the_frame_pending() { - let mut app = app(SampleType::U8); - drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); - app.stylus.tool_before_eraser = Some(Tool::Crop); - app.ui.tool = Tool::Eraser; - ensure_frame(&mut app); - assert_eq!(app.session.active().unwrap().doc.size, Size::new(200, 100)); - app.ui.tool = app.stylus.tool_before_eraser.take().unwrap(); - ensure_frame(&mut app); - assert!(pending(&app) && app.ui.crop_rect == Some([10.0, 10.0, 50.0, 40.0])); - - tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, NONE); - assert!(app.crop.drag.is_some()); - app.ui.tool = Tool::Move; - ensure_frame(&mut app); - assert_eq!(app.session.active().unwrap().doc.size, Size::new(200, 100)); - } - - /// Image › Crop with a pending crop commits the frame (the one Image item Photoshop keeps). - #[test] - fn image_crop_menu_commits_a_pending_crop() { - let mut app = app(SampleType::U8); - drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); - let ctx = egui::Context::default(); - crate::menus::invoke(&mut app, &ctx, "image.crop", json!({})).unwrap(); - assert_eq!(app.session.active().unwrap().doc.size, Size::new(40, 30)); - assert!(app.ui.crop_rect.is_none() || app.crop.default_frame); - } - - #[test] - fn commit_crops_to_the_moved_frame_at_8_and_16_bit() { - for depth in [SampleType::U8, SampleType::U16] { - let mut app = app(depth); - app.run("select.rect", json!({"x": 60, "y": 40, "width": 1, "height": 1})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.run("select.deselect", json!({})).unwrap(); - drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); - drag(&mut app, &[[30.0, 25.0], [70.0, 45.0]], NONE); - assert_eq!(app.ui.crop_rect, Some([50.0, 30.0, 90.0, 60.0])); - crate::canvas::commit_crop(&mut app); - assert!(app.ui.crop_rect.is_none()); - let doc = &app.session.active().unwrap().doc; - assert_eq!((doc.size.width, doc.size.height), (40, 30), "{depth:?}"); - assert_eq!(doc.depth, depth); - let px = doc.layers[0].surface().unwrap().rgba(10, 10); - assert!(px[0] > 0.99 && px[1] < 0.01, "{depth:?} {px:?}"); - } - } - - #[test] - fn enter_during_a_drag_ends_the_drag() { - // ↵ while the frame is still being dragged commits it; the release after must not bring - // back a frame in the old document's coordinates as a pending crop. - let mut app = app(SampleType::U8); - app.ui.crop_rect = Some([20.0, 20.0, 120.0, 70.0]); - tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }, NONE); - tool_event(&mut app, ToolEvent::Move { x: 60.0, y: 40.0, pressure: 1.0 }, NONE); - crate::canvas::commit_crop(&mut app); - tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 40.0 }, NONE); - ensure_frame(&mut app); - assert_eq!(app.session.active().unwrap().doc.size, Size::new(100, 50)); - assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 100.0, 50.0])); - assert!(!pending(&app)); - } - - #[test] - fn degenerate_and_bad_input_never_panics() { - let mut app = app(SampleType::U8); - for r in [[0.0; 4], [5.0, 5.0, 5.0, 5.0], [10.0, 10.0, 0.0, 0.0], [f64::NAN, 0.0, 10.0, 10.0], [f64::INFINITY, 0.0, f64::MAX, 1e300]] { - app.ui.crop_rect = Some(r); - for m in [NONE, SHIFT, Modifiers::ALT, SHIFT | Modifiers::ALT] { - drag(&mut app, &[[5.0, 5.0], [f64::NAN, 3.0], [1e300, -1e300], [6.0, 7.0]], m); - let _ = cursor(&app, [5.0, 5.0]); - app.ui.crop_rect = Some(r); - } - } - // Odd angles (the control channel can set any) turn, resize and commit without panicking. - for a in [f64::NAN, f64::INFINITY, -1e300, 1e-300, 720.0] { - app.ui.crop_rect = Some([10.0, 10.0, 50.0, 40.0]); - app.ui.crop_angle = a; - for pts in [[[30.0, 25.0], [f64::NAN, 1.0]], [[30.0, 25.0], [1e300, 2.0]], [[50.0, 40.0], [60.0, 45.0]], [[90.0, 90.0], [-1e300, 1e300]]] { - drag(&mut app, &pts, SHIFT); - let _ = cursor(&app, [5.0, 5.0]); - } - assert!(app.ui.crop_angle.is_finite() || !a.is_finite()); - crate::canvas::commit_crop(&mut app); - app.run("edit.undo", json!({})).ok(); - } - app.ui.tool_options.crop_ratio = "0:0".into(); - app.ui.crop_rect = Some([0.0, 0.0, 10.0, 10.0]); - drag(&mut app, &[[10.0, 10.0], [30.0, 30.0]], SHIFT); - crate::canvas::commit_crop(&mut app); - // No document: events are swallowed quietly. - let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - empty.ui.tool = Tool::Crop; - drag(&mut empty, &[[1.0, 1.0], [9.0, 9.0]], NONE); - assert!(empty.ui.crop_rect.is_none()); - } - - /// #1792: outside the frame the turn cursor bends towards the corner of the pointer's quadrant - /// (four variants, as in Photoshop) and turns with the frame; no turn cursor inside or on a handle. - #[test] - fn turn_cursor_points_at_the_quadrant_corner() { - let mut app = app(SampleType::U8); - app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); - let h = std::f64::consts::FRAC_1_SQRT_2; - let near = |d: Option<[f64; 2]>, want: [f64; 2]| d.is_some_and(|d| (d[0] - want[0]).abs() < 1e-9 && (d[1] - want[1]).abs() < 1e-9); - assert!(near(turn_cursor_dir(&app, [0.0, 0.0]), [h, h]), "top-left: towards the top-left corner"); - assert!(near(turn_cursor_dir(&app, [130.0, 5.0]), [-h, h]), "top-right"); - assert!(near(turn_cursor_dir(&app, [130.0, 90.0]), [-h, -h]), "bottom-right"); - assert!(near(turn_cursor_dir(&app, [5.0, 90.0]), [h, -h]), "bottom-left"); - assert!(near(turn_cursor_dir(&app, [150.0, 30.0]), [-h, h]), "beside the right edge, upper half"); - assert_eq!(turn_cursor_dir(&app, [60.0, 40.0]), None, "inside"); - assert_eq!(turn_cursor_dir(&app, [20.0, 20.0]), None, "on a handle"); - // A frame turned 45° turns the cursor with it: the diagonal becomes horizontal. - app.ui.crop_angle = 45.0; - assert!(near(turn_cursor_dir(&app, [0.0, 0.0]), [1.0, 0.0]), "{:?}", turn_cursor_dir(&app, [0.0, 0.0])); - app.ui.crop_angle = f64::NAN; - assert!(turn_cursor_dir(&app, [f64::NAN, 0.0]).is_none()); - app.ui.tool = Tool::Brush; - assert_eq!(turn_cursor_dir(&app, [0.0, 0.0]), None); - } - - /// A double-click inside the frame commits it, as ↵ does; on a handle or outside it doesn't. - #[test] - fn double_click_inside_the_frame_commits() { - let mut app = app(SampleType::U8); - app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); - assert!(commits_at(&app, [60.0, 40.0])); - assert!(!commits_at(&app, [20.0, 20.0]), "on a handle"); - assert!(!commits_at(&app, [150.0, 40.0]), "outside: that turns the frame"); - app.ui.crop_angle = 30.0; - assert!(commits_at(&app, [60.0, 40.0]), "inside a turned frame"); - assert!(!commits_at(&app, [25.0, 22.0]), "inside the upright frame but outside the turned one"); - app.ui.crop_angle = 0.0; - app.ui.crop_rect = None; - assert!(!commits_at(&app, [60.0, 40.0]), "no frame"); - app.ui.crop_rect = Some([f64::NAN, 0.0, 1.0, 1.0]); - assert!(!commits_at(&app, [0.5, 0.5])); - app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); - app.ui.tool = Tool::Brush; - assert!(!commits_at(&app, [60.0, 40.0])); - } - - #[test] - fn cursor_follows_the_frame() { - let mut app = app(SampleType::U8); - assert_eq!(cursor(&app, [5.0, 5.0]), None, "no frame yet: the default crosshair"); - app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); - assert_eq!(cursor(&app, [20.0, 20.0]), Some(CursorIcon::ResizeNwSe)); - assert_eq!(cursor(&app, [100.0, 20.0]), Some(CursorIcon::ResizeNeSw)); - assert_eq!(cursor(&app, [60.0, 60.0]), Some(CursorIcon::ResizeVertical)); - assert_eq!(cursor(&app, [60.0, 40.0]), Some(CursorIcon::Move)); - assert_eq!(cursor(&app, [150.0, 40.0]), Some(CursorIcon::None), "outside: the drawn turn cursor"); - // View › Flip Horizontal shows the top-left corner at the top right: its arrow mirrors too. - app.ui.view.flip_horizontal = true; - assert_eq!(cursor(&app, [20.0, 20.0]), Some(CursorIcon::ResizeNeSw), "flipped view"); - assert_eq!(cursor(&app, [100.0, 20.0]), Some(CursorIcon::ResizeNwSe), "flipped view"); - assert_eq!(cursor(&app, [60.0, 60.0]), Some(CursorIcon::ResizeVertical), "flipped view"); - app.ui.view.flip_horizontal = false; - app.ui.tool = Tool::Brush; - assert_eq!(cursor(&app, [60.0, 40.0]), None); - } - - /// #4461: inside the untouched default frame a drag draws a new frame, so the pointer is the - /// drawing crosshair there, not the move cursor; once the frame is changed a drag moves it. - #[test] - fn cursor_inside_the_default_frame_draws() { - let mut app = app(SampleType::U8); - ensure_frame(&mut app); - assert!(app.crop.default_frame && app.ui.crop_rect == Some([0.0, 0.0, 200.0, 100.0])); - assert_eq!(cursor(&app, [100.0, 50.0]), Some(CursorIcon::Crosshair)); - assert_eq!(cursor(&app, [200.0, 50.0]), Some(CursorIcon::ResizeHorizontal), "its handles still resize"); - drag(&mut app, &[[200.0, 50.0], [150.0, 50.0]], NONE); - assert!(!app.crop.default_frame && app.ui.crop_rect == Some([0.0, 0.0, 150.0, 100.0])); - assert_eq!(cursor(&app, [100.0, 50.0]), Some(CursorIcon::Move)); - } - - /// One key press through the app's keyboard handling (`shortcuts::handle`). - fn key(app: &mut PhotocraftApp, key: egui::Key, modifiers: Modifiers) { - let ctx = egui::Context::default(); - let raw = egui::RawInput { - events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], - ..Default::default() - }; - let mut out = ctx.run_ui(raw, |ui| crate::shortcuts::handle(app, ui.ctx())); - out.textures_delta.clear(); - } - - fn layer_offset(app: &PhotocraftApp) -> (i32, i32) { - let st = app.session.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); - l.surface().map_or((0, 0), |s| (s.content_bounds().x0, s.content_bounds().y0)) - } - - /// #1919: with a pending frame the arrow keys nudge it 1 px (⇧ 10 px), turned or not, and - /// never the selection or layer; without one they keep their usual job. - #[test] - fn arrow_keys_nudge_the_pending_frame() { - use egui::Key; - let mut app = app(SampleType::U8); - app.run("select.rect", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); - app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); - let steps = app.session.active().unwrap().history.past_len(); - key(&mut app, Key::ArrowRight, NONE); - assert_eq!(app.ui.crop_rect, Some([21.0, 20.0, 101.0, 60.0])); - key(&mut app, Key::ArrowDown, SHIFT); - assert_eq!(app.ui.crop_rect, Some([21.0, 30.0, 101.0, 70.0])); - key(&mut app, Key::ArrowLeft, SHIFT); - key(&mut app, Key::ArrowUp, NONE); - assert_eq!(app.ui.crop_rect, Some([11.0, 29.0, 91.0, 69.0])); - assert!(app.crop.editing && !app.crop.default_frame); - assert_eq!(app.session.active().unwrap().history.past_len(), steps, "nothing in the document moved"); - assert_eq!(app_selection_bounds(&app), Some((10, 10, 40, 30))); - assert_eq!(layer_offset(&app), (0, 0)); - // A turned frame moves on the page and keeps its angle and shape. - app.ui.crop_angle = 30.0; - let before = corners(app.ui.crop_rect.unwrap(), 30.0); - key(&mut app, Key::ArrowRight, SHIFT); - let after = corners(app.ui.crop_rect.unwrap(), angle(&app)); - for (a, b) in before.iter().zip(after) { - assert!((b[0] - a[0] - 10.0).abs() < 1e-9 && (b[1] - a[1]).abs() < 1e-9); - } - assert_eq!(app.ui.crop_angle, 30.0); - // The untouched default frame becomes a real one. - app.ui.crop_rect = None; - app.ui.crop_angle = 0.0; - app.run("select.deselect", json!({})).unwrap(); - ensure_frame(&mut app); - assert!(app.crop.default_frame); - assert!(nudge(&mut app, 1.0, 0.0)); - assert_eq!(app.ui.crop_rect, Some([1.0, 0.0, 201.0, 100.0])); - assert!(!app.crop.default_frame); - // No frame: not the Crop tool's key. With a selection tool the arrows nudge the selection. - app.ui.crop_rect = None; - assert!(!nudge(&mut app, 1.0, 0.0)); - app.ui.tool = Tool::RectMarquee; - app.run("select.rect", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); - key(&mut app, Key::ArrowRight, NONE); - assert_eq!(app_selection_bounds(&app), Some((11, 10, 41, 30))); - // Not mid-gesture, nor with another tool, nor for a non-finite frame or step. - app.ui.tool = Tool::Crop; - app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); - app.crop.drag = Some(CropDrag::Move { start: [0.0, 0.0], rect: [20.0, 20.0, 100.0, 60.0] }); - assert!(!nudge(&mut app, 1.0, 0.0)); - app.crop.drag = None; - assert!(nudge(&mut app, f64::NAN, f64::INFINITY), "the key is the Crop tool's"); - assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 100.0, 60.0]), "but the frame stays put"); - app.ui.crop_rect = Some([f64::MAX, 0.0, f64::MAX, 1.0]); - assert!(nudge(&mut app, f64::MAX, 0.0)); - assert_eq!(app.ui.crop_rect, Some([f64::MAX, 0.0, f64::MAX, 1.0]), "an overflow leaves it"); - app.ui.crop_rect = Some([f64::NAN, 0.0, 1.0, 1.0]); - assert!(!nudge(&mut app, 1.0, 0.0)); - app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); - app.ui.tool = Tool::Brush; - assert!(!nudge(&mut app, 1.0, 0.0)); - } - - fn app_selection_bounds(app: &PhotocraftApp) -> Option<(i32, i32, i32, i32)> { - let b = app.session.active()?.doc.selection.as_ref()?.content_bounds(); - Some((b.x0, b.y0, b.x1, b.y1)) - } - - /// #1919: X swaps the pending frame between portrait and landscape about its centre (keeping - /// its angle and swapping a ratio preset); without a frame X still swaps the colours. - #[test] - fn x_swaps_the_frame_orientation_not_the_colours() { - use egui::Key; - let mut app = app(SampleType::U16); - app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); - let fg = |app: &PhotocraftApp| app.session.tools.foreground; - let red = fg(&app); - app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); - app.ui.crop_angle = 25.0; - key(&mut app, Key::X, NONE); - assert_eq!(app.ui.crop_rect, Some([40.0, 0.0, 80.0, 80.0]), "40 x 80 about the centre (60, 40)"); - assert_eq!(app.ui.crop_angle, 25.0); - assert_eq!(fg(&app), red, "the colours stay"); - key(&mut app, Key::X, NONE); - assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 100.0, 60.0]), "and back"); - // A ratio preset swaps with the frame, as the options bar's ⇄ does. - app.ui.tool_options.crop_ratio = "16:9".into(); - assert!(swap_orientation(&mut app)); - assert_eq!(app.ui.tool_options.crop_ratio, "9:16"); - app.ui.tool_options.crop_ratio = "original".into(); - assert!(swap_orientation(&mut app)); - assert_eq!(app.ui.tool_options.crop_ratio, "100:200", "the document's size on its side"); - app.ui.tool_options.crop_ratio = String::new(); - assert!(swap_orientation(&mut app)); - assert_eq!(app.ui.tool_options.crop_ratio, "", "no ratio stays none"); - assert_eq!(swapped_ratio("1.414:1", 1.0, 1.0).as_deref(), Some("1:1.414"), "decimals survive the swap (#6487)"); - assert_eq!(swapped_ratio("0:5", 1.0, 1.0), None); - assert_eq!(swapped_ratio("nonsense", 1.0, 1.0), None); - // No frame, or another tool: X is Switch Foreground and Background Colors. - app.ui.crop_rect = None; - key(&mut app, Key::X, NONE); - assert_ne!(fg(&app), red, "swapped"); - app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); - app.ui.tool = Tool::Brush; - key(&mut app, Key::X, NONE); - assert_eq!(fg(&app), red, "swapped back"); - assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 100.0, 60.0])); - // Huge or broken frames never panic and are never made non-finite. - app.ui.tool = Tool::Crop; - app.ui.crop_rect = Some([-f64::MAX, 0.0, f64::MAX, 1.0]); - assert!(swap_orientation(&mut app)); - assert_eq!(app.ui.crop_rect, Some([-f64::MAX, 0.0, f64::MAX, 1.0])); - app.ui.crop_rect = Some([f64::NAN, 0.0, 1.0, 1.0]); - assert!(!swap_orientation(&mut app)); - } - - /// #1919: W × H beside the pointer while the frame is drawn or resized (its own size when - /// turned), not while it moves or turns or between gestures. - #[test] - fn readout_shows_the_frame_size_while_drawing_or_resizing() { - let mut app = app(SampleType::U8); - let ev = |app: &mut PhotocraftApp, e: ToolEvent| tool_event(app, e, NONE); - ev(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }); - assert_eq!(sizing(&app), None, "nothing drawn yet"); - ev(&mut app, ToolEvent::Move { x: 70.4, y: 50.6, pressure: 1.0 }); - assert_eq!(sizing(&app), Some([60.0, 41.0]), "rounded as ↵ crops it"); - ev(&mut app, ToolEvent::Up { x: 70.4, y: 50.6 }); - assert_eq!(sizing(&app), None); - // Resizing a turned frame by its right edge: the frame's own width grows. - app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); - app.ui.crop_angle = 30.0; - let grab = turn([100.0, 40.0], [60.0, 40.0], 30.0); - let to = [grab[0] + 10.0 * 30f64.to_radians().cos(), grab[1] + 10.0 * 30f64.to_radians().sin()]; - ev(&mut app, ToolEvent::Down { x: grab[0], y: grab[1], pressure: 1.0 }); - ev(&mut app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }); - assert!(matches!(app.crop.drag, Some(CropDrag::Resize { .. }))); - assert_eq!(sizing(&app), Some([90.0, 40.0])); - ev(&mut app, ToolEvent::Up { x: to[0], y: to[1] }); - // Moving shows no size. - ev(&mut app, ToolEvent::Down { x: 60.0, y: 40.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Move { x: 62.0, y: 40.0, pressure: 1.0 }); - assert!(matches!(app.crop.drag, Some(CropDrag::Move { .. }))); - assert_eq!(sizing(&app), None); - ev(&mut app, ToolEvent::Up { x: 62.0, y: 40.0 }); - assert_eq!(frame_size([0.0, 0.0, 0.2, 0.4]), Some([1.0, 1.0])); - assert_eq!(frame_size([f64::NAN, 0.0, 1.0, 1.0]), None); - assert_eq!(frame_size([-f64::MAX, 0.0, f64::MAX, 1.0]), None); - } -} +mod tests; diff --git a/crates/ui-egui/src/crop_ui/tests.rs b/crates/ui-egui/src/crop_ui/tests.rs new file mode 100644 index 0000000000..ffe9914527 --- /dev/null +++ b/crates/ui-egui/src/crop_ui/tests.rs @@ -0,0 +1,1135 @@ +use super::*; +use crate::canvas::tool_event; +use photocraft_doc::{Color, ColorMode, Document, SampleType, Size}; +use serde_json::json; + +const NONE: Modifiers = Modifiers::NONE; +const SHIFT: Modifiers = Modifiers::SHIFT; + +fn app(depth: SampleType) -> PhotocraftApp { + let doc = Document::with_background("crop", Size::new(200, 100), ColorMode::Rgb, depth, 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::Crop; + // These tests pin Classic Mode (the frame moves and turns over the image); the default + // mode's are in `crop_mode`. + app.ui.tool_options.crop_shield.classic_mode = true; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + app +} + +fn drag(app: &mut PhotocraftApp, pts: &[[f64; 2]], mods: Modifiers) { + let (first, last) = (pts[0], pts[pts.len() - 1]); + tool_event(app, ToolEvent::Down { x: first[0], y: first[1], pressure: 1.0 }, mods); + for p in &pts[1..] { + tool_event(app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }, mods); + } + tool_event(app, ToolEvent::Up { x: last[0], y: last[1] }, mods); +} + +#[test] +fn fitting_a_ratio_keeps_the_centre_angle_and_area() { + let mut app = app(SampleType::U8); + app.ui.crop_rect = Some([20.0, 10.0, 180.0, 90.0]); + app.ui.crop_angle = 25.0; + for key in ["1:1", "16:9", "9:16", "", "0:0"] { + let before = app.ui.crop_rect.unwrap(); + app.ui.tool_options.crop_ratio = key.into(); + crate::crop_size::chosen(&mut app); + let after = app.ui.crop_rect.unwrap(); + assert_eq!(center(after), center(before)); + assert_eq!(app.ui.crop_angle, 25.0); + assert!(after[0] >= before[0] && after[1] >= before[1] && after[2] <= before[2] && after[3] <= before[3]); + if let Some(ratio) = preset_ratio(&app) { + assert!(((after[2] - after[0]) / (after[3] - after[1]) - ratio).abs() < 1e-10); + } else { + assert_eq!(after, before); + } + } + for ratio in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert!(fitted_ratio([0.0, 0.0, 200.0, 100.0], ratio).is_none()); + } + assert!(fitted_ratio([-f64::MAX, 0.0, f64::MAX, 100.0], 1.0).is_none()); +} + +#[test] +fn choosing_a_ratio_fits_and_commits_without_a_resize() { + for classic in [false, true] { + let mut app = app(SampleType::U8); + app.ui.tool_options.crop_shield.classic_mode = classic; + ensure_frame(&mut app); + app.ui.tool_options.crop_ratio = "1:1".into(); + crate::crop_size::chosen(&mut app); + assert_eq!(app.ui.crop_rect, Some([50.0, 0.0, 150.0, 100.0])); + crate::canvas::commit_crop(&mut app); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(100, 100)); + } +} + +#[test] +fn entering_crop_with_a_saved_ratio_fits_the_selection_or_canvas() { + let mut app = app(SampleType::U8); + app.ui.tool_options.crop_ratio = "1:1".into(); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([50.0, 0.0, 150.0, 100.0])); + cancel(&mut app); + app.run("select.rect", json!({"x": 20, "y": 10, "width": 80, "height": 40})).unwrap(); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([40.0, 10.0, 80.0, 50.0])); +} + +#[test] +fn picking_the_tool_frames_the_canvas_or_the_selection() { + // #668: the Crop tool started with no frame. + let mut app = app(SampleType::U8); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 200.0, 100.0])); + // Committing the untouched frame crops nothing. + let steps = app.session.active().unwrap().history.past_len(); + crate::canvas::commit_crop(&mut app); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(200, 100)); + // A drag inside the untouched frame draws a new one instead of moving it. + ensure_frame(&mut app); + drag(&mut app, &[[50.0, 20.0], [80.0, 40.0], [120.0, 70.0]], NONE); + assert_eq!(app.ui.crop_rect, Some([50.0, 20.0, 120.0, 70.0])); + // Now it's a real frame: a drag inside moves it. + drag(&mut app, &[[60.0, 30.0], [70.0, 30.0]], NONE); + assert_eq!(app.ui.crop_rect, Some([60.0, 20.0, 130.0, 70.0])); + // Cancelling frames the selection's bounds when there is one. + app.run("select.rect", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + app.ui.crop_rect = None; + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([10.0, 10.0, 40.0, 30.0])); + // Leaving the tool drops the untouched frame. + app.ui.tool = Tool::Brush; + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, None); +} + +#[test] +fn enter_on_the_selection_frame_crops_to_it_at_8_and_16_bit() { + // #1789: selection, C, ↵ did nothing, as the untouched frame was always treated as a no-op. + for depth in [SampleType::U8, SampleType::U16] { + let mut app = app(depth); + app.run("select.rect", json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap(); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([10.0, 20.0, 40.0, 60.0])); + crate::canvas::commit_crop(&mut app); + let doc = &app.session.active().unwrap().doc; + assert_eq!(doc.size, Size::new(30, 40), "{depth:?}"); + assert_eq!(doc.depth, depth); + assert!(doc.selection.is_none(), "cropping to the selection deselects, as in Photoshop"); + // The new default frame is the whole (cropped) canvas: ↵ on it does nothing. + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 30.0, 40.0])); + let steps = app.session.active().unwrap().history.past_len(); + crate::canvas::commit_crop(&mut app); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.size, st.history.past_len()), (Size::new(30, 40), steps), "{depth:?}"); + } +} + +#[test] +fn the_frame_is_edited_from_a_press_until_commit_cancel_or_another_tool() { + let mut app = app(SampleType::U8); + ensure_frame(&mut app); + assert!(!shows_beyond_canvas(&app), "a new frame is not being edited"); + assert!(press(&mut app)); + assert!(shows_beyond_canvas(&app)); + assert!(!press(&mut app), "only the first press is news"); + // A click on the frame keeps it edited. + drag(&mut app, &[[50.0, 50.0]], NONE); + assert!(shows_beyond_canvas(&app)); + // Esc drops the frame: the new default one isn't edited. + app.ui.crop_rect = None; + ensure_frame(&mut app); + assert!(!shows_beyond_canvas(&app)); + // A drawn frame is edited until it is committed. + drag(&mut app, &[[10.0, 10.0], [60.0, 40.0]], NONE); + assert!(shows_beyond_canvas(&app)); + crate::canvas::commit_crop(&mut app); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 50.0, 30.0])); + assert!(!shows_beyond_canvas(&app)); + // Or until another tool is picked. + drag(&mut app, &[[5.0, 5.0], [20.0, 20.0]], NONE); + app.ui.tool = Tool::Brush; + ensure_frame(&mut app); + assert!(!app.crop.editing && !shows_beyond_canvas(&app)); + assert!(!press(&mut app), "no frame without the Crop tool"); +} + +#[test] +fn hit_test_finds_handles_inside_and_outside() { + let r = [10.0, 10.0, 110.0, 60.0]; + assert_eq!(hit(r, [10.0, 10.0], 4.0), Hit::Handle(-1, -1)); + assert_eq!(hit(r, [112.0, 61.0], 4.0), Hit::Handle(1, 1)); + assert_eq!(hit(r, [60.0, 8.0], 4.0), Hit::Handle(0, -1)); + assert_eq!(hit(r, [108.0, 30.0], 4.0), Hit::Handle(1, 0)); + assert_eq!(hit(r, [60.0, 30.0], 4.0), Hit::Inside); + assert_eq!(hit(r, [150.0, 30.0], 4.0), Hit::Outside); + // A tiny frame keeps a movable middle. + assert_eq!(hit([0.0, 0.0, 4.0, 4.0], [2.0, 2.0], 8.0), Hit::Inside); +} + +#[test] +fn dragging_inside_moves_the_frame() { + let mut app = app(SampleType::U8); + drag(&mut app, &[[20.0, 20.0], [80.0, 60.0]], NONE); + assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 80.0, 60.0])); + drag(&mut app, &[[50.0, 40.0], [60.0, 45.0], [70.0, 50.0]], NONE); + assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0]), "moved, not redrawn"); + // A click outside keeps the frame (and leaves it upright). + drag(&mut app, &[[5.0, 5.0]], NONE); + assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0])); + assert_eq!(app.ui.crop_angle, 0.0); + // Outside, a drag turns the frame rather than drawing a new one (#1792). + drag(&mut app, &[[150.0, 50.0], [190.0, 90.0]], NONE); + assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0])); + assert!(app.ui.crop_angle > 10.0, "{}", app.ui.crop_angle); +} + +#[test] +fn dragging_outside_turns_the_frame_about_its_centre() { + let mut app = app(SampleType::U8); + app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]); + // Centre (70, 50): from straight right to straight below is a quarter turn clockwise. + drag(&mut app, &[[150.0, 50.0], [140.0, 70.0], [70.0, 95.0]], NONE); + assert!((app.ui.crop_angle - 90.0).abs() < 1e-9, "{}", app.ui.crop_angle); + assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0]), "turning keeps the frame"); + // Back the other way, past -180 (normalised). + drag(&mut app, &[[70.0, 120.0], [-10.0, 50.0], [70.0, -20.0]], NONE); + assert!((app.ui.crop_angle - -90.0).abs() < 1e-9, "{}", app.ui.crop_angle); + // ⇧ snaps the angle to 15° steps. + app.ui.crop_angle = 0.0; + let a = 22.0f64.to_radians(); + drag(&mut app, &[[150.0, 50.0], [70.0 + 80.0 * a.cos(), 50.0 + 80.0 * a.sin()]], SHIFT); + assert_eq!(app.ui.crop_angle, 15.0); + assert_eq!(cursor(&app, [150.0, 50.0]), Some(CursorIcon::None), "outside: the drawn turn cursor"); + // Turning the untouched default frame makes it a real frame; a click outside it doesn't. + let mut app = super::tests::app(SampleType::U8); + ensure_frame(&mut app); + drag(&mut app, &[[250.0, 50.0]], NONE); + assert!(app.crop.default_frame, "a click outside keeps the default frame"); + drag(&mut app, &[[250.0, 50.0], [250.0, 80.0]], NONE); + assert!(!app.crop.default_frame && app.ui.crop_angle > 0.0); + // Esc (no frame) starts the next one upright. + app.ui.crop_rect = None; + ensure_frame(&mut app); + assert_eq!((app.ui.crop_rect, app.ui.crop_angle), (Some([0.0, 0.0, 200.0, 100.0]), 0.0)); +} + +#[test] +fn hit_testing_a_turned_frame_uses_its_own_axes() { + let r = [40.0, 30.0, 100.0, 70.0]; + // A quarter turn: the frame covers x 50..90, y 20..80 on the page. + assert_eq!(hit_turned(r, 90.0, [70.0, 75.0], 2.0), Hit::Inside, "inside the turned frame only"); + assert_eq!(hit(r, [70.0, 75.0], 2.0), Hit::Outside); + assert_eq!(hit_turned(r, 90.0, [45.0, 50.0], 2.0), Hit::Outside, "inside the upright frame only: the rotate zone"); + // The upright frame's top-left corner turns to the top-right of the page. + assert_eq!(hit_turned(r, 90.0, [90.0, 20.0], 2.0), Hit::Handle(-1, -1)); + // Its right edge's middle is now at the bottom. + assert_eq!(hit_turned(r, 90.0, [70.0, 80.0], 2.0), Hit::Handle(1, 0)); + let c = corners(r, 90.0); + for (a, b) in c.iter().zip([[90.0, 20.0], [90.0, 80.0], [50.0, 80.0], [50.0, 20.0]]) { + assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9, "{c:?}"); + } + let b = turned_bounds(r, 90.0); + assert!((b[0] - 50.0).abs() < 1e-9 && (b[3] - 80.0).abs() < 1e-9, "{b:?}"); + // Handle arrows turn with the frame. + assert_eq!(resize_icon(1, 0, 0.0, false), CursorIcon::ResizeHorizontal); + assert_eq!(resize_icon(1, 0, 90.0, false), CursorIcon::ResizeVertical); + assert_eq!(resize_icon(1, 0, 45.0, false), CursorIcon::ResizeNwSe); + assert_eq!(resize_icon(-1, -1, 90.0, false), CursorIcon::ResizeNeSw); + assert_eq!(normalized_angle(540.0), 180.0); + assert_eq!(normalized_angle(-190.0), 170.0); + assert_eq!(normalized_angle(f64::NAN), 0.0); +} + +#[test] +fn resizing_a_turned_frame_moves_along_its_axes_and_keeps_the_opposite_edge() { + let r = [40.0, 30.0, 100.0, 70.0]; + // At 90°, the right edge (local +x) faces down the page: dragging down 10 grows the width. + let n = resized_turned(r, 90.0, 1, 0, [0.0, 10.0], None, false); + assert!(((n[2] - n[0]) - 70.0).abs() < 1e-9 && ((n[3] - n[1]) - 40.0).abs() < 1e-9, "{n:?}"); + // The opposite (left) edge stays put on the page: at y = 20 with x 50..90. + let (old, new) = (corners(r, 90.0), corners(n, 90.0)); + for (i, (a, b)) in [(0, 0), (3, 3)].map(|(i, j)| (old[i], new[j])).iter().enumerate() { + assert!((a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9, "corner {i}: {a:?} vs {b:?}"); + } + // A sideways drag does nothing to that handle. + let same = resized_turned(r, 90.0, 1, 0, [25.0, 0.0], None, false); + assert!(same.iter().zip(r).all(|(a, b)| (a - b).abs() < 1e-9), "{same:?}"); + // At 0° it is the plain resize. + assert_eq!(resized_turned(r, 0.0, 1, 1, [5.0, 6.0], None, false), resized(r, 1, 1, [5.0, 6.0], None, false)); + // Through the pointer: grabbing the turned right-edge handle and dragging down 10. + let mut app = app(SampleType::U8); + app.ui.crop_rect = Some(r); + app.ui.crop_angle = 90.0; + drag(&mut app, &[[70.0, 80.0], [70.0, 90.0]], NONE); + let got = app.ui.crop_rect.unwrap(); + assert!(got.iter().zip(n).all(|(a, b)| (a - b).abs() < 1e-9), "{got:?} vs {n:?}"); + // Moving a turned frame is a plain translation, angle kept. + drag(&mut app, &[[70.0, 50.0], [80.0, 55.0]], NONE); + let moved = app.ui.crop_rect.unwrap(); + assert!(moved.iter().zip([n[0] + 10.0, n[1] + 5.0, n[2] + 10.0, n[3] + 5.0]).all(|(a, b)| (a - b).abs() < 1e-9), "{moved:?}"); + assert_eq!(app.ui.crop_angle, 90.0); +} + +/// ↵ on a turned frame crops the turned document (one step), at 8, 16 and 32 bits. +#[test] +fn commit_crops_to_the_turned_frame() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut app = app(depth); + app.run("select.rect", json!({"x": 60, "y": 40, "width": 1, "height": 1})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let past = app.session.active().unwrap().history.past_len(); + // A 40 × 20 frame centred on (60, 40), turned 90° by a drag outside it. + app.ui.crop_rect = Some([40.0, 30.0, 80.0, 50.0]); + app.crop.default_frame = false; + drag(&mut app, &[[120.0, 40.0], [60.0, 100.0]], NONE); + assert!((app.ui.crop_angle - 90.0).abs() < 1e-6, "{depth:?}: {}", app.ui.crop_angle); + crate::canvas::commit_crop(&mut app); + assert!(app.ui.crop_rect.is_none()); + assert_eq!(app.ui.crop_angle, 0.0, "the next frame starts upright"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), past + 1, "{depth:?}: one undo step"); + assert_eq!((st.doc.size.width, st.doc.size.height), (40, 20), "{depth:?}"); + assert_eq!(st.doc.depth, depth); + // The red pixel was at the frame's centre: it is at the cropped image's centre. + let surf = st.doc.layers[0].surface().unwrap(); + let red = (19..=21).flat_map(|x| (9..=11).map(move |y| (x, y))).map(|(x, y)| surf.rgba(x, y)).find(|px| px[0] > 0.6 && px[1] < 0.4); + assert!(red.is_some(), "{depth:?}: no red at the centre"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(200, 100), "{depth:?}"); + } +} + +/// Fill › Content-Aware Fill (#3823): ↵ on an extending frame fills the added canvas from the +/// image instead of the background colour; Background (Default) keeps the colour. +#[test] +fn commit_passes_the_fill_choice() { + for content_aware in [false, true] { + let mut app = app(SampleType::U16); + app.run("tools.setColors", json!({"foreground": "#808080", "background": "#000000"})).unwrap(); + app.run("edit.fill", json!({"contents": "foreground"})).unwrap(); + app.ui.tool_options.crop_content_aware = content_aware; + app.ui.crop_rect = Some([-10.0, -10.0, 210.0, 110.0]); + app.crop.default_frame = false; + crate::canvas::commit_crop(&mut app); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.size.width, st.doc.size.height), (220, 120)); + let corner = st.doc.layers[0].surface().unwrap().rgba(0, 0); + if content_aware { + assert!((corner[0] - 0.5).abs() < 0.05, "filled from the grey image: {corner:?}"); + } else { + assert!(corner[0] < 0.05, "the background colour: {corner:?}"); + } + } +} + +#[test] +fn moving_the_frame_snaps_its_edges() { + let mut app = app(SampleType::U8); + app.ui.extras.snap = true; + app.ui.crop_rect = Some([10.0, 10.0, 50.0, 40.0]); + drag(&mut app, &[[30.0, 25.0], [23.0, 25.0]], NONE); + assert_eq!(app.ui.crop_rect, Some([0.0, 10.0, 40.0, 40.0]), "left edge snaps to the document edge"); +} + +/// #3145: Edit › Undo while a crop is pending steps the *box*, not the document (Photoshop keeps +/// Undo live during a crop), so a moved frame comes back. +#[test] +fn edit_undo_steps_the_crop_box_not_the_document() { + let mut app = app(SampleType::U8); + app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]); + app.crop.default_frame = false; + let before = app.ui.crop_rect.unwrap(); + let doc_steps = app.session.active().unwrap().history.past_len(); + drag(&mut app, &[[70.0, 50.0], [90.0, 50.0]], NONE); // move the frame right 20 + let moved = app.ui.crop_rect.unwrap(); + assert!((moved[0] - 60.0).abs() < 1e-3, "{moved:?}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.ui.crop_rect, Some(before), "undo restores the box"); + assert_eq!(app.session.active().unwrap().history.past_len(), doc_steps, "the document is untouched"); + app.run("edit.redo", json!({})).unwrap(); + assert!((app.ui.crop_rect.unwrap()[0] - 60.0).abs() < 1e-3, "redo re-applies the move"); +} + +/// Once the box has no step left in one direction, that command greys out rather than staying +/// live over the document's history and doing nothing (as the Free Transform box does). +#[test] +fn box_undo_and_redo_grey_out_when_their_stack_is_empty() { + let mut app = app(SampleType::U8); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + assert!(app.session.active().unwrap().history.can_undo()); + app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]); + app.crop.default_frame = false; + drag(&mut app, &[[70.0, 50.0], [90.0, 50.0]], NONE); + assert!(crate::menus::is_enabled(&app, "edit.undo")); + assert!(!crate::menus::is_enabled(&app, "edit.redo"), "no box step to redo"); + app.run("edit.undo", json!({})).unwrap(); + assert!(!crate::menus::is_enabled(&app, "edit.undo"), "no box step left to undo"); + assert!(crate::menus::is_enabled(&app, "edit.redo")); +} + +#[test] +fn handles_resize_with_shift_and_alt() { + let mut app = app(SampleType::U8); + app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); + // Right edge. + drag(&mut app, &[[100.0, 40.0], [120.0, 50.0]], NONE); + assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 120.0, 60.0])); + // Bottom-right corner, free. + drag(&mut app, &[[120.0, 60.0], [140.0, 70.0]], NONE); + assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 140.0, 70.0])); + // ⇧ keeps 120:50 from the top-left corner: the larger relative extent wins. + app.ui.crop_rect = Some([20.0, 20.0, 140.0, 70.0]); + drag(&mut app, &[[20.0, 20.0], [10.0, 0.0]], SHIFT); + let r = app.ui.crop_rect.unwrap(); + assert_eq!((r[2], r[3]), (140.0, 70.0), "opposite corner fixed"); + assert!(((r[2] - r[0]) / (r[3] - r[1]) - 120.0 / 50.0).abs() < 1e-9, "{r:?}"); + assert_eq!(r[3] - r[1], 70.0); + // ⌥ resizes about the centre. + app.ui.crop_rect = Some([40.0, 20.0, 80.0, 60.0]); + drag(&mut app, &[[80.0, 40.0], [90.0, 40.0]], Modifiers::ALT); + assert_eq!(app.ui.crop_rect, Some([30.0, 20.0, 90.0, 60.0])); + // An options-bar ratio holds on an edge drag, centred on the other axis. + app.ui.tool_options.crop_ratio = "1:1".into(); + app.ui.crop_rect = Some([40.0, 20.0, 80.0, 60.0]); + drag(&mut app, &[[80.0, 40.0], [100.0, 40.0]], NONE); + assert_eq!(app.ui.crop_rect, Some([40.0, 10.0, 100.0, 70.0])); +} + +#[test] +fn dragging_a_handle_past_the_other_side_flips_and_collapse_reverts() { + let mut app = app(SampleType::U8); + app.ui.crop_rect = Some([20.0, 20.0, 60.0, 60.0]); + drag(&mut app, &[[60.0, 40.0], [10.0, 40.0]], NONE); + assert_eq!(app.ui.crop_rect, Some([10.0, 20.0, 20.0, 60.0])); + // Collapsing to nothing restores the frame the gesture started from. + drag(&mut app, &[[20.0, 40.0], [10.0, 40.0]], NONE); + assert_eq!(app.ui.crop_rect, Some([10.0, 20.0, 20.0, 60.0])); +} + +#[test] +fn space_repositions_the_frame_being_drawn() { + let mut app = app(SampleType::U8); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 40.0, pressure: 1.0 }, NONE); + assert!(active(&app)); + set_space(&mut app, true); + tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 50.0, pressure: 1.0 }, NONE); + assert_eq!(app.ui.crop_rect, Some([30.0, 20.0, 70.0, 50.0]), "same size, moved"); + set_space(&mut app, false); + tool_event(&mut app, ToolEvent::Move { x: 90.0, y: 60.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Up { x: 90.0, y: 60.0 }, NONE); + assert_eq!(app.ui.crop_rect, Some([30.0, 20.0, 90.0, 60.0]), "sizing resumes from the moved anchor"); + assert!(!active(&app)); +} + +/// Real egui input on the canvas: holding Space mid-draw moves the frame instead of panning. +#[test] +fn space_on_the_canvas_moves_the_frame_not_the_view() { + use egui::{Event, Key, PointerButton, pos2}; + let mut a = app(SampleType::U8); + let view = crate::state::View { + zoom: 2.0, + center: [100.0, 50.0], + fit_pending: false, + fill_pending: false, + doc_size: [200, 100], + rotation: 0.0, + zoom_animating: false, + zoom_anchor: None, + display_camera: None, + zoom_transition: None, + }; + a.ui.views = vec![view.clone()]; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 400.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let v = app.ui.views[0].clone(); + crate::canvas::canvas_view(app, ui, 0, ui.max_rect(), v, true); + }, + a, + ); + h.run_steps(2); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + let space = |pressed| Event::Key { key: Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + let p0 = pos2(200.0, 150.0); + h.event(Event::PointerMoved(p0)); + h.event(button(p0, true)); + h.step(); + for p in [pos2(220.0, 170.0), pos2(260.0, 190.0)] { + h.event(Event::PointerMoved(p)); + h.step(); + } + let drawn = h.state().ui.crop_rect.unwrap(); + // The frame starts where the button went down (200, 150), not at the first move past + // egui's drag threshold (#123). + assert_eq!((drawn[2] - drawn[0], drawn[3] - drawn[1]), (30.0, 20.0), "60x40 screen px at 200%"); + h.event(space(true)); + h.step(); + for p in [pos2(280.0, 200.0), pos2(300.0, 210.0)] { + h.event(Event::PointerMoved(p)); + h.step(); + } + let moved = h.state().ui.crop_rect.unwrap(); + assert_eq!(moved, [drawn[0] + 20.0, drawn[1] + 10.0, drawn[2] + 20.0, drawn[3] + 10.0], "moved by 40x20 screen px"); + h.event(space(false)); + h.event(button(pos2(300.0, 210.0), false)); + h.step(); + let st = h.state(); + assert_eq!(st.ui.crop_rect, Some(moved)); + assert_eq!(st.ui.views[0].center, view.center, "the view did not pan"); + assert!(st.crop.drag.is_none()); +} + +/// #1918: a pending crop belongs to the document it was drawn on. File › New, opening a file +/// or switching tabs cancels it; it never shows on, or crops, another document. +/// A turned pending frame is dropped with its angle when another document becomes active, and +/// Esc drops both too, so the next frame starts upright. +#[test] +fn cancelling_a_turned_crop_resets_its_angle() { + let mut app = app(SampleType::U8); + drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); + app.ui.crop_angle = 30.0; + app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); + app.sync_views(); + assert_eq!(app.ui.crop_angle, 0.0); + drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); + app.ui.crop_angle = -12.5; + cancel(&mut app); + assert_eq!((app.ui.crop_rect, app.ui.crop_angle, app.crop.drag), (None, 0.0, None)); +} + +#[test] +fn a_pending_crop_stays_with_its_document() { + let size = |app: &PhotocraftApp| app.session.active().map(|st| st.doc.size); + // File › New. + let mut app = app(SampleType::U8); + drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); + assert_eq!(app.ui.crop_rect, Some([10.0, 10.0, 50.0, 40.0])); + app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); + assert_eq!(app.ui.crop_rect, None, "the first document's frame is gone"); + assert!(app.crop.drag.is_none() && !app.crop.editing && !app.crop.default_frame); + crate::canvas::commit_crop(&mut app); + assert_eq!(size(&app), Some(Size::new(300, 150)), "↵ crops nothing"); + // The new document gets its own default frame. + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 300.0, 150.0])); + assert!(app.crop.default_frame); + // Switching tabs (outside a command), even before the next frame's sync: ↵ never crops + // the other document. + drag(&mut app, &[[20.0, 20.0], [60.0, 60.0]], NONE); + assert!(app.session.set_active(0)); + crate::canvas::commit_crop(&mut app); + assert_eq!(size(&app), Some(Size::new(200, 100))); + assert_eq!(app.session.documents()[1].doc.size, Size::new(300, 150)); + assert_eq!(app.ui.crop_rect, None); + // The next frame's sync also drops a frame left on a tab switched away from. + drag(&mut app, &[[20.0, 20.0], [60.0, 60.0]], NONE); + assert!(app.session.set_active(1)); + app.sync_views(); + assert_eq!(app.ui.crop_rect, None); + // Closing another document keeps the pending crop; closing its own cancels it. + drag(&mut app, &[[20.0, 20.0], [60.0, 60.0]], NONE); + app.session.close(0); + app.sync_views(); + assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 60.0, 60.0]), "still its document"); + crate::canvas::commit_crop(&mut app); + assert_eq!(size(&app), Some(Size::new(40, 40))); + drag(&mut app, &[[5.0, 5.0], [25.0, 25.0]], NONE); + app.session.close(0); + app.sync_views(); + assert!(app.session.active().is_none()); + assert_eq!(app.ui.crop_rect, None); + assert!(app.crop.drag.is_none()); + crate::canvas::commit_crop(&mut app); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, None, "no document, no frame"); +} + +/// A drag in progress when its document goes away is dropped too, not finished elsewhere. +#[test] +fn a_crop_drag_ends_with_its_document() { + let mut app = app(SampleType::U8); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 40.0, pressure: 1.0 }, NONE); + app.run("file.new", json!({"width": 300, "height": 150})).unwrap(); + tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 50.0 }, NONE); + assert_eq!(app.ui.crop_rect, None); + crate::canvas::commit_crop(&mut app); + assert_eq!(app.session.active().map(|st| st.doc.size), Some(Size::new(300, 150))); +} + +/// #1918: as in Photoshop, a pending crop (not the untouched default frame) greys almost every +/// menu command; the ones Photoshop keeps stay available, and commit or cancel frees the rest. +/// Walks the whole menu catalog. +#[test] +fn a_pending_crop_greys_the_menus_photoshop_greys() { + let mut app = app(SampleType::U8); + ensure_frame(&mut app); + assert!(app.crop.default_frame); + let ids: Vec<&str> = crate::menu_catalog::CATALOG.iter().map(|e| e.3).filter(|id| *id != "---").collect(); + for id in &ids { + assert!(!blocks(&app, id), "default frame: {id} stays as it was"); + } + drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); + assert!(pending(&app)); + let kept = [ + "file.close", + "file.save", + "file.saveAs", + "file.saveACopy", + "edit.undo", + "edit.redo", + "edit.toggleLastState", + "edit.search", + "image.crop", + "view.proofColors", + "view.gamutWarning", + "view.zoomIn", + "view.zoomOut", + "view.fitOnScreen", + "view.actualPixels", + "view.twoHundredPercent", + "view.printSize", + "view.extras", + "view.show.grid", + "view.rulers", + "view.snap", + "view.snapTo.guides", + "view.lockSlices", + "view.newGuide", + "window.arrange.tile", + "window.panel.layers", + "help.about", + ]; + let greyed = [ + "file.new", + "file.open", + "file.openAs", + "file.openExrParts", + "file.closeAll", + "file.revert", + "file.export.exportAs", + "file.placeEmbedded", + "file.automate.batch", + "file.scripts.browse", + "file.import.notes", + "file.fileInfo", + "file.print", + "edit.cut", + "edit.fill", + "edit.freeTransform", + "edit.colorSettings", + "edit.preferences.general", + "image.imageSize", + "image.mode.grayscale", + "layer.new.layer", + "select.all", + "filter.blur.gaussianBlur", + "view.proofSetup.workingCmyk", + "view.pixelAspectRatio.square", + "view.pixelAspectRatioCorrection", + "view.thirtyTwoBitPreviewOptions", + "view.flipHorizontal", + "view.screenMode.fullScreen", + "window.workspace.essentials", + "window.panel.adjustments", + "help.systemInfo", + ]; + for id in kept { + assert!(!blocks(&app, id), "{id} stays available"); + } + for id in greyed { + assert!(blocks(&app, id), "{id} is greyed"); + assert!(!crate::menus::is_enabled(&app, id), "{id} greyed in the menus"); + assert!(!crate::menus::modal_allows(&app, id), "{id} refused over the menu gate"); + } + assert!( + ids.iter() + .filter(|id| id.starts_with("layer.") || id.starts_with("type.") || id.starts_with("select.") || id.starts_with("filter.")) + .all(|id| blocks(&app, id)) + ); + // Committing still runs `image.crop` itself, and frees the menus again. + crate::canvas::commit_crop(&mut app); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(40, 30)); + assert!(!pending(&app) && crate::menus::is_enabled(&app, "file.new")); + // Cancelling does too. + drag(&mut app, &[[5.0, 5.0], [20.0, 20.0]], NONE); + assert!(blocks(&app, "file.new")); + cancel(&mut app); + assert!(!blocks(&app, "file.new")); + // Another tool: nothing is pending. + drag(&mut app, &[[5.0, 5.0], [20.0, 20.0]], NONE); + app.ui.tool = Tool::Brush; + assert!(!blocks(&app, "file.new")); +} + +/// #3368: as in Photoshop, picking another tool (toolbar or its key) with a drawn frame +/// commits the crop silently, and the new tool is current. +#[test] +fn another_tool_commits_a_drawn_frame_at_8_and_16_bit() { + for depth in [SampleType::U8, SampleType::U16] { + let mut app = app(depth); + drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); + assert!(pending(&app)); + app.ui.tool = Tool::Move; + ensure_frame(&mut app); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.size, st.doc.depth), (Size::new(40, 30), depth)); + assert_eq!(st.history.undo_label(), Some("Crop")); + assert_eq!(app.ui.tool, Tool::Move); + assert_eq!((app.ui.crop_rect, app.ui.crop_angle), (None, 0.0)); + // Nothing is left to commit: back on the Crop tool, the new canvas gets a default frame. + ensure_frame(&mut app); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(40, 30)); + app.ui.tool = Tool::Crop; + ensure_frame(&mut app); + assert!(app.crop.default_frame && app.ui.crop_rect == Some([0.0, 0.0, 40.0, 30.0])); + } +} + +/// #3368, default mode: a turned frame crops turned, and the view it turned is left upright. +#[test] +fn another_tool_commits_a_turned_frame_and_leaves_the_view_upright() { + let mut app = app(SampleType::U8); + app.sync_views(); + app.ui.tool_options.crop_shield.classic_mode = false; + app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]); + app.ui.crop_angle = 10.0; + ensure_frame(&mut app); + assert!(pending(&app) && crate::crop_mode::view_rotation(&app) != 0.0); + app.ui.tool = Tool::Brush; + ensure_frame(&mut app); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(60, 40)); + assert_eq!(crate::crop_mode::view_rotation(&app), 0.0); + assert_eq!((app.ui.tool, app.ui.crop_rect), (Tool::Brush, None)); +} + +/// #3368: the untouched default frame (the canvas, or the selection's bounds) is just dropped +/// on leaving the tool: nothing is cropped. +#[test] +fn another_tool_drops_an_untouched_default_frame() { + for select in [false, true] { + let mut app = app(SampleType::U8); + if select { + app.run("select.rect", json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap(); + } + ensure_frame(&mut app); + assert!(app.crop.default_frame && app.ui.crop_rect.is_some()); + let steps = app.session.active().unwrap().history.past_len(); + app.ui.tool = Tool::Move; + ensure_frame(&mut app); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.size, st.history.past_len()), (Size::new(200, 100), steps), "selection: {select}"); + assert_eq!(app.ui.crop_rect, None); + } +} + +/// #6750: a ratio preset that shrinks the untouched default frame does not make it a drawn +/// one: leaving the tool drops the frame and crops nothing, as with the plain default frame. +/// Picking the ratio before entering the tool (the issue's repro) and while it is picked both +/// stay untouched; editing the fitted frame makes it a drawn one that leaving commits (#3368). +#[test] +fn another_tool_drops_an_untouched_ratio_fitted_frame() { + // Entering the Crop tool with a saved ratio: the frame is fitted but untouched. + let mut app = app(SampleType::U8); + app.ui.tool_options.crop_ratio = "1:1".into(); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([50.0, 0.0, 150.0, 100.0]), "the default frame is fitted to the ratio"); + assert!(app.crop.default_frame, "fitting it is not an edit"); + let steps = app.session.active().unwrap().history.past_len(); + app.ui.tool = Tool::Move; + ensure_frame(&mut app); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.size, st.history.past_len()), (Size::new(200, 100), steps), "switching tools must not crop"); + assert_eq!(app.ui.crop_rect, None); + // Choosing the ratio with the Crop tool already picked: the same untouched fit. + let mut app2 = self::app(SampleType::U8); + ensure_frame(&mut app2); + app2.ui.tool_options.crop_ratio = "1:1".into(); + crate::crop_size::chosen(&mut app2); + assert_eq!(app2.ui.crop_rect, Some([50.0, 0.0, 150.0, 100.0])); + assert!(app2.crop.default_frame); + let steps = app2.session.active().unwrap().history.past_len(); + app2.ui.tool = Tool::Move; + ensure_frame(&mut app2); + let st = app2.session.active().unwrap(); + assert_eq!((st.doc.size, st.history.past_len()), (Size::new(200, 100), steps)); + // Resizing a handle of the fitted frame is an edit: leaving commits it (#3368). + let mut app3 = self::app(SampleType::U8); + app3.ui.tool_options.crop_ratio = "1:1".into(); + ensure_frame(&mut app3); + drag(&mut app3, &[[50.0, 0.0], [70.0, 20.0]], NONE); + assert!(!app3.crop.default_frame, "the resize made it a drawn frame"); + app3.ui.tool = Tool::Move; + ensure_frame(&mut app3); + assert_eq!(app3.session.active().unwrap().doc.size, Size::new(80, 80), "the edited frame crops"); + // Default (non-classic) mode, the issue's exact scenario: the fitted preview stays a + // preview; pressing V neither crops nor applies anything. + let mut app4 = self::app(SampleType::U8); + app4.ui.tool_options.crop_shield.classic_mode = false; + app4.sync_views(); + app4.ui.tool_options.crop_ratio = "1:1".into(); + ensure_frame(&mut app4); + assert!(app4.crop.default_frame, "the fitted preview is still the untouched frame"); + let steps = app4.session.active().unwrap().history.past_len(); + app4.ui.tool = Tool::Move; + ensure_frame(&mut app4); + let st = app4.session.active().unwrap(); + assert_eq!((st.doc.size, st.history.past_len()), (Size::new(200, 100), steps)); +} + +/// The pen's eraser end stands in for the Crop tool only until the tip comes back (`stylus`), +/// and a gesture still in progress isn't cut short: neither commits the frame. +#[test] +fn the_stylus_eraser_and_a_gesture_in_progress_keep_the_frame_pending() { + let mut app = app(SampleType::U8); + drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); + app.stylus.tool_before_eraser = Some(Tool::Crop); + app.ui.tool = Tool::Eraser; + ensure_frame(&mut app); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(200, 100)); + app.ui.tool = app.stylus.tool_before_eraser.take().unwrap(); + ensure_frame(&mut app); + assert!(pending(&app) && app.ui.crop_rect == Some([10.0, 10.0, 50.0, 40.0])); + + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, NONE); + assert!(app.crop.drag.is_some()); + app.ui.tool = Tool::Move; + ensure_frame(&mut app); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(200, 100)); +} + +/// Image › Crop with a pending crop commits the frame (the one Image item Photoshop keeps). +#[test] +fn image_crop_menu_commits_a_pending_crop() { + let mut app = app(SampleType::U8); + drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "image.crop", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(40, 30)); + assert!(app.ui.crop_rect.is_none() || app.crop.default_frame); +} + +#[test] +fn commit_crops_to_the_moved_frame_at_8_and_16_bit() { + for depth in [SampleType::U8, SampleType::U16] { + let mut app = app(depth); + app.run("select.rect", json!({"x": 60, "y": 40, "width": 1, "height": 1})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); + drag(&mut app, &[[30.0, 25.0], [70.0, 45.0]], NONE); + assert_eq!(app.ui.crop_rect, Some([50.0, 30.0, 90.0, 60.0])); + crate::canvas::commit_crop(&mut app); + assert!(app.ui.crop_rect.is_none()); + let doc = &app.session.active().unwrap().doc; + assert_eq!((doc.size.width, doc.size.height), (40, 30), "{depth:?}"); + assert_eq!(doc.depth, depth); + let px = doc.layers[0].surface().unwrap().rgba(10, 10); + assert!(px[0] > 0.99 && px[1] < 0.01, "{depth:?} {px:?}"); + } +} + +#[test] +fn enter_during_a_drag_ends_the_drag() { + // ↵ while the frame is still being dragged commits it; the release after must not bring + // back a frame in the old document's coordinates as a pending crop. + let mut app = app(SampleType::U8); + app.ui.crop_rect = Some([20.0, 20.0, 120.0, 70.0]); + tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Move { x: 60.0, y: 40.0, pressure: 1.0 }, NONE); + crate::canvas::commit_crop(&mut app); + tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 40.0 }, NONE); + ensure_frame(&mut app); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(100, 50)); + assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 100.0, 50.0])); + assert!(!pending(&app)); +} + +#[test] +fn degenerate_and_bad_input_never_panics() { + let mut app = app(SampleType::U8); + for r in [[0.0; 4], [5.0, 5.0, 5.0, 5.0], [10.0, 10.0, 0.0, 0.0], [f64::NAN, 0.0, 10.0, 10.0], [f64::INFINITY, 0.0, f64::MAX, 1e300]] { + app.ui.crop_rect = Some(r); + for m in [NONE, SHIFT, Modifiers::ALT, SHIFT | Modifiers::ALT] { + drag(&mut app, &[[5.0, 5.0], [f64::NAN, 3.0], [1e300, -1e300], [6.0, 7.0]], m); + let _ = cursor(&app, [5.0, 5.0]); + app.ui.crop_rect = Some(r); + } + } + // Odd angles (the control channel can set any) turn, resize and commit without panicking. + for a in [f64::NAN, f64::INFINITY, -1e300, 1e-300, 720.0] { + app.ui.crop_rect = Some([10.0, 10.0, 50.0, 40.0]); + app.ui.crop_angle = a; + for pts in [[[30.0, 25.0], [f64::NAN, 1.0]], [[30.0, 25.0], [1e300, 2.0]], [[50.0, 40.0], [60.0, 45.0]], [[90.0, 90.0], [-1e300, 1e300]]] { + drag(&mut app, &pts, SHIFT); + let _ = cursor(&app, [5.0, 5.0]); + } + assert!(app.ui.crop_angle.is_finite() || !a.is_finite()); + crate::canvas::commit_crop(&mut app); + app.run("edit.undo", json!({})).ok(); + } + app.ui.tool_options.crop_ratio = "0:0".into(); + app.ui.crop_rect = Some([0.0, 0.0, 10.0, 10.0]); + drag(&mut app, &[[10.0, 10.0], [30.0, 30.0]], SHIFT); + crate::canvas::commit_crop(&mut app); + // No document: events are swallowed quietly. + let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + empty.ui.tool = Tool::Crop; + drag(&mut empty, &[[1.0, 1.0], [9.0, 9.0]], NONE); + assert!(empty.ui.crop_rect.is_none()); +} + +/// #1792: outside the frame the turn cursor bends towards the corner of the pointer's quadrant +/// (four variants, as in Photoshop) and turns with the frame; no turn cursor inside or on a handle. +#[test] +fn turn_cursor_points_at_the_quadrant_corner() { + let mut app = app(SampleType::U8); + app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); + let h = std::f64::consts::FRAC_1_SQRT_2; + let near = |d: Option<[f64; 2]>, want: [f64; 2]| d.is_some_and(|d| (d[0] - want[0]).abs() < 1e-9 && (d[1] - want[1]).abs() < 1e-9); + assert!(near(turn_cursor_dir(&app, [0.0, 0.0]), [h, h]), "top-left: towards the top-left corner"); + assert!(near(turn_cursor_dir(&app, [130.0, 5.0]), [-h, h]), "top-right"); + assert!(near(turn_cursor_dir(&app, [130.0, 90.0]), [-h, -h]), "bottom-right"); + assert!(near(turn_cursor_dir(&app, [5.0, 90.0]), [h, -h]), "bottom-left"); + assert!(near(turn_cursor_dir(&app, [150.0, 30.0]), [-h, h]), "beside the right edge, upper half"); + assert_eq!(turn_cursor_dir(&app, [60.0, 40.0]), None, "inside"); + assert_eq!(turn_cursor_dir(&app, [20.0, 20.0]), None, "on a handle"); + // A frame turned 45° turns the cursor with it: the diagonal becomes horizontal. + app.ui.crop_angle = 45.0; + assert!(near(turn_cursor_dir(&app, [0.0, 0.0]), [1.0, 0.0]), "{:?}", turn_cursor_dir(&app, [0.0, 0.0])); + app.ui.crop_angle = f64::NAN; + assert!(turn_cursor_dir(&app, [f64::NAN, 0.0]).is_none()); + app.ui.tool = Tool::Brush; + assert_eq!(turn_cursor_dir(&app, [0.0, 0.0]), None); +} + +/// A double-click inside the frame commits it, as ↵ does; on a handle or outside it doesn't. +#[test] +fn double_click_inside_the_frame_commits() { + let mut app = app(SampleType::U8); + app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); + assert!(commits_at(&app, [60.0, 40.0])); + assert!(!commits_at(&app, [20.0, 20.0]), "on a handle"); + assert!(!commits_at(&app, [150.0, 40.0]), "outside: that turns the frame"); + app.ui.crop_angle = 30.0; + assert!(commits_at(&app, [60.0, 40.0]), "inside a turned frame"); + assert!(!commits_at(&app, [25.0, 22.0]), "inside the upright frame but outside the turned one"); + app.ui.crop_angle = 0.0; + app.ui.crop_rect = None; + assert!(!commits_at(&app, [60.0, 40.0]), "no frame"); + app.ui.crop_rect = Some([f64::NAN, 0.0, 1.0, 1.0]); + assert!(!commits_at(&app, [0.5, 0.5])); + app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); + app.ui.tool = Tool::Brush; + assert!(!commits_at(&app, [60.0, 40.0])); +} + +#[test] +fn cursor_follows_the_frame() { + let mut app = app(SampleType::U8); + assert_eq!(cursor(&app, [5.0, 5.0]), None, "no frame yet: the default crosshair"); + app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); + assert_eq!(cursor(&app, [20.0, 20.0]), Some(CursorIcon::ResizeNwSe)); + assert_eq!(cursor(&app, [100.0, 20.0]), Some(CursorIcon::ResizeNeSw)); + assert_eq!(cursor(&app, [60.0, 60.0]), Some(CursorIcon::ResizeVertical)); + assert_eq!(cursor(&app, [60.0, 40.0]), Some(CursorIcon::Move)); + assert_eq!(cursor(&app, [150.0, 40.0]), Some(CursorIcon::None), "outside: the drawn turn cursor"); + // View › Flip Horizontal shows the top-left corner at the top right: its arrow mirrors too. + app.ui.view.flip_horizontal = true; + assert_eq!(cursor(&app, [20.0, 20.0]), Some(CursorIcon::ResizeNeSw), "flipped view"); + assert_eq!(cursor(&app, [100.0, 20.0]), Some(CursorIcon::ResizeNwSe), "flipped view"); + assert_eq!(cursor(&app, [60.0, 60.0]), Some(CursorIcon::ResizeVertical), "flipped view"); + app.ui.view.flip_horizontal = false; + app.ui.tool = Tool::Brush; + assert_eq!(cursor(&app, [60.0, 40.0]), None); +} + +/// #4461: inside the untouched default frame a drag draws a new frame, so the pointer is the +/// drawing crosshair there, not the move cursor; once the frame is changed a drag moves it. +#[test] +fn cursor_inside_the_default_frame_draws() { + let mut app = app(SampleType::U8); + ensure_frame(&mut app); + assert!(app.crop.default_frame && app.ui.crop_rect == Some([0.0, 0.0, 200.0, 100.0])); + assert_eq!(cursor(&app, [100.0, 50.0]), Some(CursorIcon::Crosshair)); + assert_eq!(cursor(&app, [200.0, 50.0]), Some(CursorIcon::ResizeHorizontal), "its handles still resize"); + drag(&mut app, &[[200.0, 50.0], [150.0, 50.0]], NONE); + assert!(!app.crop.default_frame && app.ui.crop_rect == Some([0.0, 0.0, 150.0, 100.0])); + assert_eq!(cursor(&app, [100.0, 50.0]), Some(CursorIcon::Move)); +} + +/// One key press through the app's keyboard handling (`shortcuts::handle`). +fn key(app: &mut PhotocraftApp, key: egui::Key, modifiers: Modifiers) { + let ctx = egui::Context::default(); + let raw = egui::RawInput { + events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| crate::shortcuts::handle(app, ui.ctx())); + out.textures_delta.clear(); +} + +fn layer_offset(app: &PhotocraftApp) -> (i32, i32) { + let st = app.session.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + l.surface().map_or((0, 0), |s| (s.content_bounds().x0, s.content_bounds().y0)) +} + +/// #1919: with a pending frame the arrow keys nudge it 1 px (⇧ 10 px), turned or not, and +/// never the selection or layer; without one they keep their usual job. +#[test] +fn arrow_keys_nudge_the_pending_frame() { + use egui::Key; + let mut app = app(SampleType::U8); + app.run("select.rect", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); + let steps = app.session.active().unwrap().history.past_len(); + key(&mut app, Key::ArrowRight, NONE); + assert_eq!(app.ui.crop_rect, Some([21.0, 20.0, 101.0, 60.0])); + key(&mut app, Key::ArrowDown, SHIFT); + assert_eq!(app.ui.crop_rect, Some([21.0, 30.0, 101.0, 70.0])); + key(&mut app, Key::ArrowLeft, SHIFT); + key(&mut app, Key::ArrowUp, NONE); + assert_eq!(app.ui.crop_rect, Some([11.0, 29.0, 91.0, 69.0])); + assert!(app.crop.editing && !app.crop.default_frame); + assert_eq!(app.session.active().unwrap().history.past_len(), steps, "nothing in the document moved"); + assert_eq!(app_selection_bounds(&app), Some((10, 10, 40, 30))); + assert_eq!(layer_offset(&app), (0, 0)); + // A turned frame moves on the page and keeps its angle and shape. + app.ui.crop_angle = 30.0; + let before = corners(app.ui.crop_rect.unwrap(), 30.0); + key(&mut app, Key::ArrowRight, SHIFT); + let after = corners(app.ui.crop_rect.unwrap(), angle(&app)); + for (a, b) in before.iter().zip(after) { + assert!((b[0] - a[0] - 10.0).abs() < 1e-9 && (b[1] - a[1]).abs() < 1e-9); + } + assert_eq!(app.ui.crop_angle, 30.0); + // The untouched default frame becomes a real one. + app.ui.crop_rect = None; + app.ui.crop_angle = 0.0; + app.run("select.deselect", json!({})).unwrap(); + ensure_frame(&mut app); + assert!(app.crop.default_frame); + assert!(nudge(&mut app, 1.0, 0.0)); + assert_eq!(app.ui.crop_rect, Some([1.0, 0.0, 201.0, 100.0])); + assert!(!app.crop.default_frame); + // No frame: not the Crop tool's key. With a selection tool the arrows nudge the selection. + app.ui.crop_rect = None; + assert!(!nudge(&mut app, 1.0, 0.0)); + app.ui.tool = Tool::RectMarquee; + app.run("select.rect", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + key(&mut app, Key::ArrowRight, NONE); + assert_eq!(app_selection_bounds(&app), Some((11, 10, 41, 30))); + // Not mid-gesture, nor with another tool, nor for a non-finite frame or step. + app.ui.tool = Tool::Crop; + app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); + app.crop.drag = Some(CropDrag::Move { start: [0.0, 0.0], rect: [20.0, 20.0, 100.0, 60.0] }); + assert!(!nudge(&mut app, 1.0, 0.0)); + app.crop.drag = None; + assert!(nudge(&mut app, f64::NAN, f64::INFINITY), "the key is the Crop tool's"); + assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 100.0, 60.0]), "but the frame stays put"); + app.ui.crop_rect = Some([f64::MAX, 0.0, f64::MAX, 1.0]); + assert!(nudge(&mut app, f64::MAX, 0.0)); + assert_eq!(app.ui.crop_rect, Some([f64::MAX, 0.0, f64::MAX, 1.0]), "an overflow leaves it"); + app.ui.crop_rect = Some([f64::NAN, 0.0, 1.0, 1.0]); + assert!(!nudge(&mut app, 1.0, 0.0)); + app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); + app.ui.tool = Tool::Brush; + assert!(!nudge(&mut app, 1.0, 0.0)); +} + +fn app_selection_bounds(app: &PhotocraftApp) -> Option<(i32, i32, i32, i32)> { + let b = app.session.active()?.doc.selection.as_ref()?.content_bounds(); + Some((b.x0, b.y0, b.x1, b.y1)) +} + +/// #1919: X swaps the pending frame between portrait and landscape about its centre (keeping +/// its angle and swapping a ratio preset); without a frame X still swaps the colours. +#[test] +fn x_swaps_the_frame_orientation_not_the_colours() { + use egui::Key; + let mut app = app(SampleType::U16); + app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); + let fg = |app: &PhotocraftApp| app.session.tools.foreground; + let red = fg(&app); + app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); + app.ui.crop_angle = 25.0; + key(&mut app, Key::X, NONE); + assert_eq!(app.ui.crop_rect, Some([40.0, 0.0, 80.0, 80.0]), "40 x 80 about the centre (60, 40)"); + assert_eq!(app.ui.crop_angle, 25.0); + assert_eq!(fg(&app), red, "the colours stay"); + key(&mut app, Key::X, NONE); + assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 100.0, 60.0]), "and back"); + // A ratio preset swaps with the frame, as the options bar's ⇄ does. + app.ui.tool_options.crop_ratio = "16:9".into(); + assert!(swap_orientation(&mut app)); + assert_eq!(app.ui.tool_options.crop_ratio, "9:16"); + app.ui.tool_options.crop_ratio = "original".into(); + assert!(swap_orientation(&mut app)); + assert_eq!(app.ui.tool_options.crop_ratio, "100:200", "the document's size on its side"); + app.ui.tool_options.crop_ratio = String::new(); + assert!(swap_orientation(&mut app)); + assert_eq!(app.ui.tool_options.crop_ratio, "", "no ratio stays none"); + assert_eq!(swapped_ratio("1.414:1", 1.0, 1.0).as_deref(), Some("1:1.414"), "decimals survive the swap (#6487)"); + assert_eq!(swapped_ratio("0:5", 1.0, 1.0), None); + assert_eq!(swapped_ratio("nonsense", 1.0, 1.0), None); + // No frame, or another tool: X is Switch Foreground and Background Colors. + app.ui.crop_rect = None; + key(&mut app, Key::X, NONE); + assert_ne!(fg(&app), red, "swapped"); + app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); + app.ui.tool = Tool::Brush; + key(&mut app, Key::X, NONE); + assert_eq!(fg(&app), red, "swapped back"); + assert_eq!(app.ui.crop_rect, Some([20.0, 20.0, 100.0, 60.0])); + // Huge or broken frames never panic and are never made non-finite. + app.ui.tool = Tool::Crop; + app.ui.crop_rect = Some([-f64::MAX, 0.0, f64::MAX, 1.0]); + assert!(swap_orientation(&mut app)); + assert_eq!(app.ui.crop_rect, Some([-f64::MAX, 0.0, f64::MAX, 1.0])); + app.ui.crop_rect = Some([f64::NAN, 0.0, 1.0, 1.0]); + assert!(!swap_orientation(&mut app)); +} + +/// #1919: W × H beside the pointer while the frame is drawn or resized (its own size when +/// turned), not while it moves or turns or between gestures. +#[test] +fn readout_shows_the_frame_size_while_drawing_or_resizing() { + let mut app = app(SampleType::U8); + let ev = |app: &mut PhotocraftApp, e: ToolEvent| tool_event(app, e, NONE); + ev(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }); + assert_eq!(sizing(&app), None, "nothing drawn yet"); + ev(&mut app, ToolEvent::Move { x: 70.4, y: 50.6, pressure: 1.0 }); + assert_eq!(sizing(&app), Some([60.0, 41.0]), "rounded as ↵ crops it"); + ev(&mut app, ToolEvent::Up { x: 70.4, y: 50.6 }); + assert_eq!(sizing(&app), None); + // Resizing a turned frame by its right edge: the frame's own width grows. + app.ui.crop_rect = Some([20.0, 20.0, 100.0, 60.0]); + app.ui.crop_angle = 30.0; + let grab = turn([100.0, 40.0], [60.0, 40.0], 30.0); + let to = [grab[0] + 10.0 * 30f64.to_radians().cos(), grab[1] + 10.0 * 30f64.to_radians().sin()]; + ev(&mut app, ToolEvent::Down { x: grab[0], y: grab[1], pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }); + assert!(matches!(app.crop.drag, Some(CropDrag::Resize { .. }))); + assert_eq!(sizing(&app), Some([90.0, 40.0])); + ev(&mut app, ToolEvent::Up { x: to[0], y: to[1] }); + // Moving shows no size. + ev(&mut app, ToolEvent::Down { x: 60.0, y: 40.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 62.0, y: 40.0, pressure: 1.0 }); + assert!(matches!(app.crop.drag, Some(CropDrag::Move { .. }))); + assert_eq!(sizing(&app), None); + ev(&mut app, ToolEvent::Up { x: 62.0, y: 40.0 }); + assert_eq!(frame_size([0.0, 0.0, 0.2, 0.4]), Some([1.0, 1.0])); + assert_eq!(frame_size([f64::NAN, 0.0, 1.0, 1.0]), None); + assert_eq!(frame_size([-f64::MAX, 0.0, f64::MAX, 1.0]), None); +} From 56f5a483e71c983f4381b6f90387491fdf7a9f4f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:33 +0000 Subject: [PATCH 056/259] refactor(ui-egui): move color_range_ui.rs tests to color_range_ui/tests.rs --- crates/ui-egui/src/color_range_ui.rs | 560 +-------------------- crates/ui-egui/src/color_range_ui/tests.rs | 557 ++++++++++++++++++++ 2 files changed, 558 insertions(+), 559 deletions(-) create mode 100644 crates/ui-egui/src/color_range_ui/tests.rs diff --git a/crates/ui-egui/src/color_range_ui.rs b/crates/ui-egui/src/color_range_ui.rs index a21d3ef71f..75fe3c67b9 100644 --- a/crates/ui-egui/src/color_range_ui.rs +++ b/crates/ui-egui/src/color_range_ui.rs @@ -745,562 +745,4 @@ fn order(f: &Map, add: usize, sub: usize) -> Option { } #[cfg(test)] -mod tests { - use super::*; - use egui_kittest::{ - Harness, - kittest::{NodeT, Queryable}, - }; - use photocraft_doc::{Color, ColorMode, SampleType, Size}; - use photocraft_geom::Rect as GRect; - - /// 40 × 30: red block (0..20, 0..15), blue block (20..40, 0..15), black and white below. - fn app_with_doc() -> PhotocraftApp { - let mut doc = Document::with_background("cr", Size::new(40, 30), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let bg = doc.layers[0].surface_mut().unwrap(); - bg.fill_rect(GRect::new(0, 0, 20, 15), &[1.0, 0.0, 0.0, 1.0]); - bg.fill_rect(GRect::new(20, 0, 40, 15), &[0.0, 0.0, 1.0, 1.0]); - bg.fill_rect(GRect::new(0, 15, 20, 30), &[0.0, 0.0, 0.0, 1.0]); - let mut s = photocraft_engine::Session::new(); - s.add_document(doc, None); - PhotocraftApp::new(s, crate::Services::default()) - } - - fn coverage(app: &PhotocraftApp, x: i32, y: i32) -> f32 { - app.session.active().unwrap().doc.selection.as_ref().map_or(0.0, |s| s.sample_channel(x, y, 0)) - } - - fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( - |ui, app| { - crate::menus::menu_bar(app, ui); - crate::dialogs::show(app, ui.ctx()); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.run_steps(2); - h - } - - fn dialog_id(app: &PhotocraftApp) -> u64 { - app.ui.dialogs.iter().find(|d| owns(&d.fields)).map(|d| d.id).expect("Color Range dialog open") - } - - fn set(h: &mut Harness<'static, PhotocraftApp>, key: &str, v: Value) { - let id = dialog_id(h.state()); - h.state_mut().ui.dialog_mut(id).unwrap().fields.insert(key.into(), v); - h.run_steps(3); - } - - /// OK / Cancel are painted buttons without accessibility labels; the dialog's keys do the same. - fn ok(h: &mut Harness<'static, PhotocraftApp>) { - h.key_press(egui::Key::Enter); - } - - fn click(h: &mut Harness<'static, PhotocraftApp>, at: egui::Pos2) { - h.hover_at(at); - h.run_steps(1); - h.drag_at(at); - h.run_steps(1); - h.drop_at(at); - } - - fn disabled(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool { - // A slider row names both its number and its slider with the caption; either reports it. - h.query_all_by_label(label).next().unwrap_or_else(|| panic!("`{label}`")).accesskit_node().is_disabled() - } - - #[test] - fn preview_and_eyedropper_keep_the_original_selection_boundary() { - let mut app = app_with_doc(); - app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); - let doc = app.session.active().unwrap().doc.clone(); - for params in [json!({"select": "sampledColors", "color": "#ff0000", "fuzziness": 0}), json!({"select": "reds"})] { - let mask = proxy_mask(&app, &doc, 1, ¶ms).unwrap(); - assert_eq!(mask[5 * 40 + 5], 1.0, "red inside the selection stays visible"); - assert_eq!(mask[5 * 40 + 25], 0.0, "the blue outside the selection stays excluded"); - } - for params in [json!({"select": "sampledColors", "color": "#ffffff", "invert": true}), json!({"select": "outOfGamut", "invert": true})] { - let mask = proxy_mask(&app, &doc, 1, ¶ms).unwrap(); - assert_eq!(mask[5 * 40 + 25], 0.0, "even inverted previews stay within the selection"); - } - - // As in Photoshop, the eyedropper samples anywhere; only the result is scoped (#5244). - open(&mut app); - assert!(pick_top(&mut app, [25.0, 5.0], egui::Modifiers::NONE)); - assert_eq!(points(&app.ui.dialogs.last().unwrap().fields, "points"), vec![[25.0, 5.0]], "a colour outside the selection is sampled"); - let mask = proxy_mask(&app, &doc, 1, &json!({"select": "sampledColors", "points": [[25, 5]], "fuzziness": 0})).unwrap(); - assert_eq!(mask[5 * 40 + 25], 0.0, "but the preview stays within the selection"); - assert!(pick_top(&mut app, [5.0, 5.0], egui::Modifiers::NONE)); - assert_eq!(points(&app.ui.dialogs.last().unwrap().fields, "points"), vec![[5.0, 5.0]]); - } - - #[test] - fn preview_cache_refreshes_after_foreground_and_proof_changes() { - let mut app = app_with_doc(); - let p = json!({"select": "outOfGamut"}); - let mut previous = query_key(&app, &p); - app.session.tools.foreground = [0.2, 0.3, 0.4, 1.0]; - let key = query_key(&app, &p); - assert_ne!(key, previous); - previous = key; - for setup in [ - json!({"profile": "srgb"}), - json!({"profile": "linear-srgb"}), - json!({"profile": "linear-srgb", "intent": "perceptual"}), - json!({"profile": "linear-srgb", "intent": "perceptual", "bpc": false}), - json!({"profile": "linear-srgb", "intent": "perceptual", "bpc": false, "simulatePaper": true}), - ] { - app.run("view.proofSetup", setup).unwrap(); - let key = query_key(&app, &p); - assert_ne!(key, previous, "changed proof settings must invalidate the preview"); - assert_eq!(key, query_key(&app, &p), "an unchanged ICC profile must keep its cache key"); - previous = key; - } - app.run("view.gamutWarning", json!({"on": true, "threshold": 8})).unwrap(); - assert_ne!(previous, query_key(&app, &p)); - previous = query_key(&app, &p); - app.run("view.gamutWarning", json!({"on": true, "threshold": 16})).unwrap(); - assert_ne!(previous, query_key(&app, &p)); - assert_ne!(query_key(&app, &p), query_key(&app, &json!({"select": "outOfGamut", "invert": true}))); - } - - #[test] - fn eyedropper_hover_reuses_preview_textures_without_sampling() { - let mut h = Harness::builder().with_size(vec2(1200.0, 900.0)).build_eframe(|cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app_with_doc() - }); - h.state_mut().ui.views[0].zoom = 20.0; - h.state_mut().ui.views[0].center = [20.0, 15.0]; - h.state_mut().ui.views[0].fit_pending = false; - h.run_steps(3); - let id = open(h.state_mut()); - set(&mut h, "__selectionPreview", json!("quickMask")); - let fields = h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone(); - let cached = |app: &PhotocraftApp| { - let p = app.color_range.as_ref().unwrap(); - (p.mask_key, p.overlay_key, p.mask.as_ref().unwrap().id(), p.overlay.as_ref().unwrap().id(), Arc::as_ptr(&p.proxy)) - }; - let before = cached(h.state()); - let st = h.state().session.active().unwrap(); - let document = (st.revision, st.history.past_len()); - for i in 0..12 { - let at = crate::canvas::ViewXform::active(h.state()).unwrap().to_screen(4.0 + i as f32 * 0.5, 15.0); - h.hover_at(at); - h.run_steps(1); - assert_eq!(cached(h.state()), before, "hover must reuse the mask, overlay and proxy"); - } - assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields, fields, "hover must not pick a colour"); - let st = h.state().session.active().unwrap(); - assert_eq!((st.revision, st.history.past_len()), document); - } - - #[test] - fn opens_from_the_select_menu_without_touching_the_document() { - let mut h = harness(app_with_doc()); - let rev = h.state().session.active().unwrap().revision; - h.get_by_label("Select").click(); - h.run_steps(2); - h.get_by_label("Color Range…").click(); - h.run_steps(3); - assert!(h.state().ui.dialogs.iter().any(|d| owns(&d.fields)), "Select › Color Range… must open the dialog"); - for label in ["Color Range", "Fuzziness:", "Localized Color Clusters", "Invert", "Selection", "Color Range preview", "Add to Sample"] { - assert!(h.query_all_by_label(label).next().is_some(), "missing {label}"); - } - assert_eq!(h.query_all_by_label("Image").count(), 2, "the Image menu and the Image preview radio"); - assert_eq!(h.state().session.active().unwrap().revision, rev, "opening must not edit the document"); - // Automation and the generic command dialog get the same dialog. - let ctx = egui::Context::default(); - let r = crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap(); - assert!(r.get("dialog").is_some(), "{r}"); - } - - #[test] - fn select_mode_switches_the_enabled_controls() { - let mut h = harness(app_with_doc()); - open(h.state_mut()); - h.run_steps(4); - // Sampled Colors: Fuzziness, eyedroppers and Localized Color Clusters; Range only when localized. - assert!(!disabled(&h, "Fuzziness:") && !disabled(&h, "Localized Color Clusters") && !disabled(&h, "Add to Sample")); - assert!(h.query_all_by_label("Range:").next().is_none()); - h.get_by_label("Localized Color Clusters").click(); - h.run_steps(2); - assert!(h.query_all_by_label("Range:").next().is_some(), "Range shows with Localized Color Clusters"); - // A hue family: no Fuzziness, eyedroppers or clusters (Photoshop disables them). - set(&mut h, "select", json!("reds")); - assert!(disabled(&h, "Fuzziness:") && disabled(&h, "Localized Color Clusters") && disabled(&h, "Add to Sample")); - assert!(h.query_all_by_label("Range:").next().is_none()); - assert!(!disabled(&h, "Invert")); - // Tones: Fuzziness and the tonal range. - set(&mut h, "select", json!("shadows")); - assert!(!disabled(&h, "Fuzziness:") && disabled(&h, "Localized Color Clusters")); - assert!(h.query_all_by_label("Shadows up to:").next().is_some()); - set(&mut h, "select", json!("midtones")); - assert!(h.query_all_by_label("Midtones from:").next().is_some() && h.query_all_by_label("Midtones to:").next().is_some()); - set(&mut h, "select", json!("outOfGamut")); - assert!(disabled(&h, "Fuzziness:") && h.query_all_by_label("Midtones from:").next().is_none()); - // Skin Tones: Fuzziness (the colour one), no eyedroppers or clusters. - set(&mut h, "select", json!("skinTones")); - assert!(!disabled(&h, "Fuzziness:") && disabled(&h, "Localized Color Clusters") && disabled(&h, "Add to Sample")); - let skin: Map = serde_json::from_value(json!({"select": "skinTones", "fuzziness": 25.0, "points": [[1, 1]]})).unwrap(); - assert_eq!(params(&skin), json!({"select": "skinTones", "invert": false, "fuzziness": 25.0})); - assert_eq!( - controls(&serde_json::from_value(json!({"select": "highlights"})).unwrap()), - Controls { fuzziness: true, sampling: false, range: false, tonal: true } - ); - } - - #[test] - fn dialog_shrinks_back_when_a_mode_needs_fewer_controls() { - let mut h = harness(app_with_doc()); - open(h.state_mut()); - h.run_steps(4); - let area = egui::Id::unique(("dialog", dialog_id(h.state()))); - let rect = |h: &Harness<'static, PhotocraftApp>| h.ctx.memory(|m| m.area_rect(area)).unwrap_or(egui::Rect::NOTHING); - set(&mut h, "select", json!("outOfGamut")); - let short = rect(&h); - set(&mut h, "select", json!("midtones")); - let tall = rect(&h); - assert!(tall.height() > short.height() + 40.0, "Midtones adds two sliders: {short:?} → {tall:?}"); - assert_eq!(tall.min, short.min, "the dialog grows downward, it doesn't re-centre"); - set(&mut h, "select", json!("outOfGamut")); - let back = rect(&h); - assert!((back.height() - short.height()).abs() < 1.0, "the dialog must shrink back, not keep an empty band above OK: {short:?} → {tall:?} → {back:?}"); - assert_eq!(back.min, short.min); - } - - #[test] - fn ok_applies_one_undo_step() { - let mut h = harness(app_with_doc()); - // The prior selection covers the left red square: Color Range is scoped to it (#3313). - h.state_mut().run("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); - let past = h.state().session.active().unwrap().history.past_len(); - open(h.state_mut()); - h.run_steps(4); - set(&mut h, "select", json!("reds")); - ok(&mut h); - h.run_steps(2); - assert!(!h.state().ui.dialogs.iter().any(|d| owns(&d.fields)), "OK closes the dialog"); - let app = h.state(); - assert_eq!((coverage(app, 5, 5), coverage(app, 30, 5), coverage(app, 2, 22)), (1.0, 0.0, 0.0)); - assert_eq!(app.session.active().unwrap().history.past_len(), past + 1, "one history step"); - assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Color Range")); - h.state_mut().run("edit.undo", json!({})).unwrap(); - let app = h.state(); - assert_eq!((coverage(app, 5, 5), coverage(app, 2, 22), coverage(app, 30, 5)), (1.0, 1.0, 0.0), "undo restores the previous selection"); - } - - #[test] - fn cancel_keeps_the_previous_selection() { - let mut h = harness(app_with_doc()); - h.state_mut().run("select.rect", json!({"x": 0, "y": 20, "width": 5, "height": 5})).unwrap(); - let (rev, past) = { - let st = h.state().session.active().unwrap(); - (st.revision, st.history.past_len()) - }; - open(h.state_mut()); - h.run_steps(4); - set(&mut h, "select", json!("blues")); - h.get_by_label("Invert").click(); - h.run_steps(2); - h.key_press(egui::Key::Escape); - h.run_steps(2); - assert!(h.state().ui.dialogs.is_empty()); - let app = h.state(); - let st = app.session.active().unwrap(); - assert_eq!((st.revision, st.history.past_len()), (rev, past)); - assert_eq!((coverage(app, 2, 22), coverage(app, 30, 5), coverage(app, 5, 5)), (1.0, 0.0, 0.0)); - } - - #[test] - fn invert_flips_the_selection() { - let mut h = harness(app_with_doc()); - open(h.state_mut()); - h.run_steps(4); - set(&mut h, "select", json!("reds")); - h.get_by_label("Invert").click(); - h.run_steps(2); - let id = dialog_id(h.state()); - assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields.get("invert"), Some(&json!(true))); - ok(&mut h); - h.run_steps(2); - let app = h.state(); - assert_eq!((coverage(app, 5, 5), coverage(app, 30, 5), coverage(app, 5, 22), coverage(app, 30, 22)), (0.0, 1.0, 1.0, 1.0)); - } - - #[test] - fn eyedroppers_pick_on_the_preview() { - let mut h = harness(app_with_doc()); - open(h.state_mut()); - h.run_steps(4); - // 40 × 30 at 200 pt: 5 pt per pixel; the image is centred vertically (150 pt tall). - let at = |h: &Harness<'static, PhotocraftApp>, x: f32, y: f32| { - h.get_by_label("Color Range preview").rect().left_top() + egui::vec2(x * 5.0 + 2.5, 25.0 + y * 5.0 + 2.5) - }; - let p = at(&h, 30.0, 5.0); - click(&mut h, p); - h.run_steps(2); - let f = |h: &Harness<'static, PhotocraftApp>| h.state().ui.dialogs.iter().find(|d| owns(&d.fields)).unwrap().fields.clone(); - assert_eq!(points(&f(&h), "points"), vec![[30.0, 5.0]]); - // Add to Sample: the red block too; the selection then covers both. - h.get_by_label("Add to Sample").click(); - h.run_steps(1); - let p = at(&h, 5.0, 5.0); - click(&mut h, p); - h.run_steps(2); - assert_eq!(points(&f(&h), "points").len(), 2); - // Subtract from Sample: take the blue back out. - h.get_by_label("Subtract from Sample").click(); - h.run_steps(1); - let p = at(&h, 35.0, 10.0); - click(&mut h, p); - h.run_steps(2); - assert_eq!(points(&f(&h), "subtractPoints"), vec![[35.0, 10.0]]); - let p = params(&f(&h)); - assert_eq!(p["select"], "sampledColors"); - assert_eq!(p["order"], json!(["+", "+", "-"])); - ok(&mut h); - h.run_steps(2); - let app = h.state(); - // The sampled red stays fully selected. - assert_eq!(coverage(app, 5, 5), 1.0); - // Like Photoshop, subtracting a colour on the edge of the samples' range only trims that - // edge by a fifth of the falloff: the blue stays mostly selected (Photoshop: 232 of 255 - // for the same case), black never was. - let blue = coverage(app, 30, 5); - assert!(blue > 0.85 && blue < 0.95, "{blue}"); - assert_eq!(coverage(app, 5, 22), 0.0); - } - - #[test] - fn selection_preview_modes_cover_only_unselected_pixels() { - assert_eq!(overlay_pixel("grayscale", 1.0), Color32::WHITE); - assert_eq!(overlay_pixel("grayscale", 0.0), Color32::BLACK); - assert_eq!(overlay_pixel("grayscale", 0.5), Color32::from_gray(128)); - for mode in ["blackMatte", "whiteMatte", "quickMask"] { - assert_eq!(overlay_pixel(mode, 1.0).a(), 0, "{mode}: selected pixels stay visible"); - } - assert_eq!(overlay_pixel("blackMatte", 0.0), Color32::BLACK); - assert_eq!(overlay_pixel("whiteMatte", 0.0), Color32::WHITE); - assert_eq!(overlay_pixel("quickMask", 0.0).a(), 128); - assert_eq!(overlay_pixel("quickMask", 0.5).a(), 64); - assert_eq!(overlay_pixel("none", 0.0), Color32::TRANSPARENT); - } - - #[test] - fn preview_mode_is_view_state_and_cancel_preserves_selection() { - let mut h = harness(app_with_doc()); - h.state_mut().run("select.rect", json!({"x": 0, "y": 20, "width": 5, "height": 5})).unwrap(); - let original = h.state().session.active().unwrap(); - let past = original.history.past_len(); - let revision = original.revision; - let id = open(h.state_mut()); - h.run_steps(3); - for (mode, _) in PREVIEWS { - set(&mut h, "__selectionPreview", json!(mode)); - let f = &h.state().ui.dialogs.last().unwrap().fields; - assert!(params(f).get("__selectionPreview").is_none()); - let painter = h.ctx.layer_painter(egui::LayerId::background()); - let doc = h.state().session.active().unwrap().doc.id; - let ctx = h.ctx.clone(); - paint_selection_preview(h.state_mut(), &ctx, &painter, doc, Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)), false); - let st = h.state().session.active().unwrap(); - assert_eq!((st.revision, st.history.past_len()), (revision, past)); - assert_eq!(coverage(h.state(), 2, 22), 1.0); - } - h.state_mut().ui.close_dialog(id); - let painter = h.ctx.layer_painter(egui::LayerId::background()); - let ctx = h.ctx.clone(); - let doc = h.state().session.active().unwrap().doc.id; - paint_selection_preview(h.state_mut(), &ctx, &painter, doc, Rect::EVERYTHING, false); - assert_eq!(coverage(h.state(), 2, 22), 1.0); - } - - #[test] - fn repeated_subtraction_clicks_are_not_discarded() { - let mut app = app_with_doc(); - let id = open(&mut app); - let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); - pick(&app, &mut f, [2.0, 2.0], egui::Modifiers::NONE); - pick(&app, &mut f, [30.0, 2.0], egui::Modifiers::SHIFT); - pick(&app, &mut f, [30.0, 2.0], egui::Modifiers::ALT); - pick(&app, &mut f, [30.0, 2.0], egui::Modifiers::ALT); - assert_eq!(params(&f)["order"], json!(["+", "+", "-", "-"])); - } - - #[test] - fn control_pointer_drag_samples_and_never_paints_under_the_dialog() { - let mut h = harness(app_with_doc()); - let app = h.state_mut(); - open(app); - let doc = app.session.active().unwrap(); - let before = doc.revision; - let history = doc.history.past_len(); - let ctx = h.ctx.clone(); - for (events, shift) in [ - (json!([{"kind":"down","x":2,"y":2},{"kind":"move","x":3,"y":2},{"kind":"up","x":3,"y":2}]), false), - (json!([{"kind":"down","x":30,"y":2},{"kind":"move","x":31,"y":2},{"kind":"up","x":31,"y":2}]), true), - ] { - let (req, _) = crate::control::ControlRequest::new("ui.pointer", json!({"events":events,"shift":shift})); - let _ = crate::control::handle(h.state_mut(), &ctx, &req); - } - let fields = &h.state().ui.dialogs.last().unwrap().fields; - assert_eq!(points(fields, "points"), [[3.0, 2.0], [30.0, 2.0], [31.0, 2.0]]); - let doc = h.state().session.active().unwrap(); - assert_eq!((doc.revision, doc.history.past_len()), (before, history)); - assert!(h.state().drag.is_none()); - assert!(!pick_top(h.state_mut(), [-1.0, 0.0], egui::Modifiers::NONE)); - } - - #[test] - fn modifier_temporarily_swaps_image_and_selection_thumbnail() { - let mut h = harness(app_with_doc()); - let id = open(h.state_mut()); - h.run_steps(3); - let f = h.state().ui.dialogs.last().unwrap().fields.clone(); - let ctx = h.ctx.clone(); - let selection = preview(h.state_mut(), &ctx, &f).unwrap().0; - h.event(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND)); - h.run_steps(2); - let image = preview(h.state_mut(), &ctx, &f).unwrap().0; - assert_ne!(image, selection); - assert_eq!(h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["__view"], "selection"); - h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); - h.run_steps(2); - assert_eq!(preview(h.state_mut(), &ctx, &f).unwrap().0, selection); - } - - /// A sample between thumbnail pixels must use the original pixel, not its neighbour. - #[test] - fn reduced_preview_matches_the_original_eyedropper_sample() { - let mut doc = Document::with_background("fine detail", Size::new(400, 4), ColorMode::Rgb, SampleType::U8, Color::rgb(1.0, 0.0, 0.0)); - let surface = doc.layers[0].surface_mut().unwrap(); - surface.fill_rect(GRect::new(200, 0, 400, 4), &[0.0, 0.0, 1.0, 1.0]); - surface.fill_rect(GRect::new(101, 0, 102, 4), &[0.0, 0.0, 1.0, 1.0]); - let mut session = photocraft_engine::Session::new(); - session.add_document(doc, None); - let mut app = PhotocraftApp::new(session, crate::Services::default()); - let id = open(&mut app); - let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone(); - pick(&app, &mut fields, [101.0, 1.0], egui::Modifiers::NONE); - fields.insert("fuzziness".into(), json!(0.0)); - let original = app.session.active().unwrap().doc.clone(); - let proxy = crate::proxy::proxy_document(&original, 2); - let mut old = photocraft_engine::Session::new(); - old.add_document(proxy.clone(), None); - old.execute(COMMAND, json!({"points": [[50, 0]], "fuzziness": 0})).unwrap(); - assert_eq!( - old.active().unwrap().doc.selection.as_ref().unwrap().sample_channel(150, 0, 0), - 0.0, - "sampling the thumbnail instead selects the red neighbour" - ); - let shown = proxy_mask(&app, &proxy, 2, ¶ms(&fields)).unwrap(); - confirm(&mut app, &fields).unwrap(); - assert_eq!(coverage(&app, 300, 0), 1.0); - assert_eq!(shown[150], coverage(&app, 300, 0), "preview must show the same blue pixels as OK"); - assert_eq!(shown[0], coverage(&app, 0, 0), "preview must leave the red background unselected"); - } - - /// `sampleAllLayers: false` judges the active layer in the preview, as OK does. - #[test] - fn preview_honours_sample_all_layers_like_ok() { - let mut app = app_with_doc(); - let doc = app.session.active().unwrap().doc.clone(); - let mut top = photocraft_doc::Layer::new("blue cover", photocraft_doc::LayerContent::Raster(doc.layers[0].surface().unwrap().clone())); - top.surface_mut().unwrap().fill_rect(GRect::new(0, 0, 40, 30), &[0.0, 0.0, 1.0, 1.0]); - app.session - .edit("layers", |doc, _| { - doc.layers.push(top); - Ok(()) - }) - .unwrap(); - for all_layers in [false, true] { - let p = json!({"select": "sampledColors", "points": [[5, 5]], "fuzziness": 0, "sampleAllLayers": all_layers}); - let proxy = crate::proxy::proxy_document(&app.session.active().unwrap().doc, 1); - let shown = proxy_mask(&app, &proxy, 1, &p).unwrap(); - app.run(COMMAND, p).unwrap(); - for (x, y) in [(5, 5), (30, 5), (5, 20), (30, 20)] { - assert_eq!(shown[y * 40 + x], coverage(&app, x as i32, y as i32), "all_layers={all_layers} at ({x}, {y})"); - } - } - } - - #[test] - fn params_send_only_what_the_mode_uses() { - let mut app = app_with_doc(); - let id = open(&mut app); - let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); - assert_eq!(params(&f), json!({"select": "sampledColors", "invert": false, "fuzziness": 40.0})); - // Localized needs a picked point. - f.insert("localized".into(), json!(true)); - assert!(params(&f).get("localized").is_none()); - pick(&app, &mut f, [3.0, 4.0], egui::Modifiers::NONE); - pick(&app, &mut f, [99.0, -4.0], egui::Modifiers::SHIFT); - pick(&app, &mut f, [1.0, 1.0], egui::Modifiers::ALT); - assert_eq!( - params(&f), - json!({"select": "sampledColors", "invert": false, "fuzziness": 40.0, "points": [[3.0, 4.0], [39.0, 0.0]], "subtractPoints": [[1.0, 1.0]], "order": ["+", "+", "-"], "localized": true, "range": 100.0}) - ); - f.insert("select".into(), json!("midtones")); - f.insert("midtonesLow".into(), json!(160.0)); - assert_eq!(params(&f), json!({"select": "midtones", "invert": false, "fuzziness": 20.0, "tonalRange": [150.0, 160.0]})); - f.insert("select".into(), json!("highlights")); - assert_eq!(params(&f)["tonalRange"], json!(190.0)); - f.insert("select".into(), json!("cyans")); - assert_eq!(params(&f), json!({"select": "cyans", "invert": false})); - // Every Select entry is accepted by the engine. - for (v, _) in SELECTS { - f.insert("select".into(), json!(v)); - app.run(COMMAND, params(&f)).unwrap(); - } - } - - /// #145: the whole app without a GPU (no wgpu render state: the CPU canvas, as on a Linux - /// machine whose adapter can't run the GPU canvas), on a small window. Select › Color Range… - /// from the menu opens the dialog on screen and draws both previews. - #[test] - fn opens_and_previews_in_the_full_app_without_a_gpu() { - let mut h = Harness::builder().with_size(egui::vec2(1024.0, 600.0)).build_eframe(|cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - assert!(cc.wgpu_render_state.is_none(), "this test covers the no-GPU path"); - app_with_doc() - }); - h.run_steps(6); - assert!(h.state().gpu.is_none(), "the CPU canvas"); - h.get_all_by_label("Select").next().expect("the Select menu").click(); - h.run_steps(3); - h.get_by_label("Color Range…").click(); - h.run_steps(6); - let id = dialog_id(h.state()); - let area = h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", id)))).expect("the dialog is drawn"); - assert!(h.ctx.content_rect().contains_rect(area), "the dialog is on screen: {area:?}"); - assert!(h.query_by_label("Color Range preview").is_some()); - let p = h.state().color_range.as_ref().expect("the preview is cached"); - assert!(p.mask.is_some() && p.error.is_none(), "the selection preview is drawn: {:?}", p.error); - set(&mut h, "__view", json!("image")); - let p = h.state().color_range.as_ref().unwrap(); - assert!(p.image.is_some() && p.error.is_none(), "the image preview is drawn: {:?}", p.error); - set(&mut h, "select", json!("reds")); - ok(&mut h); - h.run_steps(3); - assert_eq!(coverage(h.state(), 5, 5), 1.0); - } - - #[test] - fn a_preview_failure_is_shown_not_silent() { - let mut h = harness(app_with_doc()); - open(h.state_mut()); - h.run_steps(3); - // The engine refuses these params: the preview says so instead of staying blank. - let id = dialog_id(h.state()); - h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("select".into(), json!("noSuchMode")); - h.run_steps(3); - let err = h.state().color_range.as_ref().and_then(|p| p.error.clone()); - assert!(err.is_some(), "the failure is recorded"); - assert!(h.query_by_label_contains("Color Range preview unavailable").is_some(), "and shown"); - set(&mut h, "select", json!("reds")); - assert!(h.state().color_range.as_ref().unwrap().error.is_none(), "and cleared once the preview works again"); - } -} +mod tests; diff --git a/crates/ui-egui/src/color_range_ui/tests.rs b/crates/ui-egui/src/color_range_ui/tests.rs new file mode 100644 index 0000000000..cf819941cd --- /dev/null +++ b/crates/ui-egui/src/color_range_ui/tests.rs @@ -0,0 +1,557 @@ +use super::*; +use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, +}; +use photocraft_doc::{Color, ColorMode, SampleType, Size}; +use photocraft_geom::Rect as GRect; + +/// 40 × 30: red block (0..20, 0..15), blue block (20..40, 0..15), black and white below. +fn app_with_doc() -> PhotocraftApp { + let mut doc = Document::with_background("cr", Size::new(40, 30), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let bg = doc.layers[0].surface_mut().unwrap(); + bg.fill_rect(GRect::new(0, 0, 20, 15), &[1.0, 0.0, 0.0, 1.0]); + bg.fill_rect(GRect::new(20, 0, 40, 15), &[0.0, 0.0, 1.0, 1.0]); + bg.fill_rect(GRect::new(0, 15, 20, 30), &[0.0, 0.0, 0.0, 1.0]); + let mut s = photocraft_engine::Session::new(); + s.add_document(doc, None); + PhotocraftApp::new(s, crate::Services::default()) +} + +fn coverage(app: &PhotocraftApp, x: i32, y: i32) -> f32 { + app.session.active().unwrap().doc.selection.as_ref().map_or(0.0, |s| s.sample_channel(x, y, 0)) +} + +fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( + |ui, app| { + crate::menus::menu_bar(app, ui); + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(2); + h +} + +fn dialog_id(app: &PhotocraftApp) -> u64 { + app.ui.dialogs.iter().find(|d| owns(&d.fields)).map(|d| d.id).expect("Color Range dialog open") +} + +fn set(h: &mut Harness<'static, PhotocraftApp>, key: &str, v: Value) { + let id = dialog_id(h.state()); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert(key.into(), v); + h.run_steps(3); +} + +/// OK / Cancel are painted buttons without accessibility labels; the dialog's keys do the same. +fn ok(h: &mut Harness<'static, PhotocraftApp>) { + h.key_press(egui::Key::Enter); +} + +fn click(h: &mut Harness<'static, PhotocraftApp>, at: egui::Pos2) { + h.hover_at(at); + h.run_steps(1); + h.drag_at(at); + h.run_steps(1); + h.drop_at(at); +} + +fn disabled(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool { + // A slider row names both its number and its slider with the caption; either reports it. + h.query_all_by_label(label).next().unwrap_or_else(|| panic!("`{label}`")).accesskit_node().is_disabled() +} + +#[test] +fn preview_and_eyedropper_keep_the_original_selection_boundary() { + let mut app = app_with_doc(); + app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + for params in [json!({"select": "sampledColors", "color": "#ff0000", "fuzziness": 0}), json!({"select": "reds"})] { + let mask = proxy_mask(&app, &doc, 1, ¶ms).unwrap(); + assert_eq!(mask[5 * 40 + 5], 1.0, "red inside the selection stays visible"); + assert_eq!(mask[5 * 40 + 25], 0.0, "the blue outside the selection stays excluded"); + } + for params in [json!({"select": "sampledColors", "color": "#ffffff", "invert": true}), json!({"select": "outOfGamut", "invert": true})] { + let mask = proxy_mask(&app, &doc, 1, ¶ms).unwrap(); + assert_eq!(mask[5 * 40 + 25], 0.0, "even inverted previews stay within the selection"); + } + + // As in Photoshop, the eyedropper samples anywhere; only the result is scoped (#5244). + open(&mut app); + assert!(pick_top(&mut app, [25.0, 5.0], egui::Modifiers::NONE)); + assert_eq!(points(&app.ui.dialogs.last().unwrap().fields, "points"), vec![[25.0, 5.0]], "a colour outside the selection is sampled"); + let mask = proxy_mask(&app, &doc, 1, &json!({"select": "sampledColors", "points": [[25, 5]], "fuzziness": 0})).unwrap(); + assert_eq!(mask[5 * 40 + 25], 0.0, "but the preview stays within the selection"); + assert!(pick_top(&mut app, [5.0, 5.0], egui::Modifiers::NONE)); + assert_eq!(points(&app.ui.dialogs.last().unwrap().fields, "points"), vec![[5.0, 5.0]]); +} + +#[test] +fn preview_cache_refreshes_after_foreground_and_proof_changes() { + let mut app = app_with_doc(); + let p = json!({"select": "outOfGamut"}); + let mut previous = query_key(&app, &p); + app.session.tools.foreground = [0.2, 0.3, 0.4, 1.0]; + let key = query_key(&app, &p); + assert_ne!(key, previous); + previous = key; + for setup in [ + json!({"profile": "srgb"}), + json!({"profile": "linear-srgb"}), + json!({"profile": "linear-srgb", "intent": "perceptual"}), + json!({"profile": "linear-srgb", "intent": "perceptual", "bpc": false}), + json!({"profile": "linear-srgb", "intent": "perceptual", "bpc": false, "simulatePaper": true}), + ] { + app.run("view.proofSetup", setup).unwrap(); + let key = query_key(&app, &p); + assert_ne!(key, previous, "changed proof settings must invalidate the preview"); + assert_eq!(key, query_key(&app, &p), "an unchanged ICC profile must keep its cache key"); + previous = key; + } + app.run("view.gamutWarning", json!({"on": true, "threshold": 8})).unwrap(); + assert_ne!(previous, query_key(&app, &p)); + previous = query_key(&app, &p); + app.run("view.gamutWarning", json!({"on": true, "threshold": 16})).unwrap(); + assert_ne!(previous, query_key(&app, &p)); + assert_ne!(query_key(&app, &p), query_key(&app, &json!({"select": "outOfGamut", "invert": true}))); +} + +#[test] +fn eyedropper_hover_reuses_preview_textures_without_sampling() { + let mut h = Harness::builder().with_size(vec2(1200.0, 900.0)).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app_with_doc() + }); + h.state_mut().ui.views[0].zoom = 20.0; + h.state_mut().ui.views[0].center = [20.0, 15.0]; + h.state_mut().ui.views[0].fit_pending = false; + h.run_steps(3); + let id = open(h.state_mut()); + set(&mut h, "__selectionPreview", json!("quickMask")); + let fields = h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone(); + let cached = |app: &PhotocraftApp| { + let p = app.color_range.as_ref().unwrap(); + (p.mask_key, p.overlay_key, p.mask.as_ref().unwrap().id(), p.overlay.as_ref().unwrap().id(), Arc::as_ptr(&p.proxy)) + }; + let before = cached(h.state()); + let st = h.state().session.active().unwrap(); + let document = (st.revision, st.history.past_len()); + for i in 0..12 { + let at = crate::canvas::ViewXform::active(h.state()).unwrap().to_screen(4.0 + i as f32 * 0.5, 15.0); + h.hover_at(at); + h.run_steps(1); + assert_eq!(cached(h.state()), before, "hover must reuse the mask, overlay and proxy"); + } + assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields, fields, "hover must not pick a colour"); + let st = h.state().session.active().unwrap(); + assert_eq!((st.revision, st.history.past_len()), document); +} + +#[test] +fn opens_from_the_select_menu_without_touching_the_document() { + let mut h = harness(app_with_doc()); + let rev = h.state().session.active().unwrap().revision; + h.get_by_label("Select").click(); + h.run_steps(2); + h.get_by_label("Color Range…").click(); + h.run_steps(3); + assert!(h.state().ui.dialogs.iter().any(|d| owns(&d.fields)), "Select › Color Range… must open the dialog"); + for label in ["Color Range", "Fuzziness:", "Localized Color Clusters", "Invert", "Selection", "Color Range preview", "Add to Sample"] { + assert!(h.query_all_by_label(label).next().is_some(), "missing {label}"); + } + assert_eq!(h.query_all_by_label("Image").count(), 2, "the Image menu and the Image preview radio"); + assert_eq!(h.state().session.active().unwrap().revision, rev, "opening must not edit the document"); + // Automation and the generic command dialog get the same dialog. + let ctx = egui::Context::default(); + let r = crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap(); + assert!(r.get("dialog").is_some(), "{r}"); +} + +#[test] +fn select_mode_switches_the_enabled_controls() { + let mut h = harness(app_with_doc()); + open(h.state_mut()); + h.run_steps(4); + // Sampled Colors: Fuzziness, eyedroppers and Localized Color Clusters; Range only when localized. + assert!(!disabled(&h, "Fuzziness:") && !disabled(&h, "Localized Color Clusters") && !disabled(&h, "Add to Sample")); + assert!(h.query_all_by_label("Range:").next().is_none()); + h.get_by_label("Localized Color Clusters").click(); + h.run_steps(2); + assert!(h.query_all_by_label("Range:").next().is_some(), "Range shows with Localized Color Clusters"); + // A hue family: no Fuzziness, eyedroppers or clusters (Photoshop disables them). + set(&mut h, "select", json!("reds")); + assert!(disabled(&h, "Fuzziness:") && disabled(&h, "Localized Color Clusters") && disabled(&h, "Add to Sample")); + assert!(h.query_all_by_label("Range:").next().is_none()); + assert!(!disabled(&h, "Invert")); + // Tones: Fuzziness and the tonal range. + set(&mut h, "select", json!("shadows")); + assert!(!disabled(&h, "Fuzziness:") && disabled(&h, "Localized Color Clusters")); + assert!(h.query_all_by_label("Shadows up to:").next().is_some()); + set(&mut h, "select", json!("midtones")); + assert!(h.query_all_by_label("Midtones from:").next().is_some() && h.query_all_by_label("Midtones to:").next().is_some()); + set(&mut h, "select", json!("outOfGamut")); + assert!(disabled(&h, "Fuzziness:") && h.query_all_by_label("Midtones from:").next().is_none()); + // Skin Tones: Fuzziness (the colour one), no eyedroppers or clusters. + set(&mut h, "select", json!("skinTones")); + assert!(!disabled(&h, "Fuzziness:") && disabled(&h, "Localized Color Clusters") && disabled(&h, "Add to Sample")); + let skin: Map = serde_json::from_value(json!({"select": "skinTones", "fuzziness": 25.0, "points": [[1, 1]]})).unwrap(); + assert_eq!(params(&skin), json!({"select": "skinTones", "invert": false, "fuzziness": 25.0})); + assert_eq!( + controls(&serde_json::from_value(json!({"select": "highlights"})).unwrap()), + Controls { fuzziness: true, sampling: false, range: false, tonal: true } + ); +} + +#[test] +fn dialog_shrinks_back_when_a_mode_needs_fewer_controls() { + let mut h = harness(app_with_doc()); + open(h.state_mut()); + h.run_steps(4); + let area = egui::Id::unique(("dialog", dialog_id(h.state()))); + let rect = |h: &Harness<'static, PhotocraftApp>| h.ctx.memory(|m| m.area_rect(area)).unwrap_or(egui::Rect::NOTHING); + set(&mut h, "select", json!("outOfGamut")); + let short = rect(&h); + set(&mut h, "select", json!("midtones")); + let tall = rect(&h); + assert!(tall.height() > short.height() + 40.0, "Midtones adds two sliders: {short:?} → {tall:?}"); + assert_eq!(tall.min, short.min, "the dialog grows downward, it doesn't re-centre"); + set(&mut h, "select", json!("outOfGamut")); + let back = rect(&h); + assert!((back.height() - short.height()).abs() < 1.0, "the dialog must shrink back, not keep an empty band above OK: {short:?} → {tall:?} → {back:?}"); + assert_eq!(back.min, short.min); +} + +#[test] +fn ok_applies_one_undo_step() { + let mut h = harness(app_with_doc()); + // The prior selection covers the left red square: Color Range is scoped to it (#3313). + h.state_mut().run("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); + let past = h.state().session.active().unwrap().history.past_len(); + open(h.state_mut()); + h.run_steps(4); + set(&mut h, "select", json!("reds")); + ok(&mut h); + h.run_steps(2); + assert!(!h.state().ui.dialogs.iter().any(|d| owns(&d.fields)), "OK closes the dialog"); + let app = h.state(); + assert_eq!((coverage(app, 5, 5), coverage(app, 30, 5), coverage(app, 2, 22)), (1.0, 0.0, 0.0)); + assert_eq!(app.session.active().unwrap().history.past_len(), past + 1, "one history step"); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Color Range")); + h.state_mut().run("edit.undo", json!({})).unwrap(); + let app = h.state(); + assert_eq!((coverage(app, 5, 5), coverage(app, 2, 22), coverage(app, 30, 5)), (1.0, 1.0, 0.0), "undo restores the previous selection"); +} + +#[test] +fn cancel_keeps_the_previous_selection() { + let mut h = harness(app_with_doc()); + h.state_mut().run("select.rect", json!({"x": 0, "y": 20, "width": 5, "height": 5})).unwrap(); + let (rev, past) = { + let st = h.state().session.active().unwrap(); + (st.revision, st.history.past_len()) + }; + open(h.state_mut()); + h.run_steps(4); + set(&mut h, "select", json!("blues")); + h.get_by_label("Invert").click(); + h.run_steps(2); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.dialogs.is_empty()); + let app = h.state(); + let st = app.session.active().unwrap(); + assert_eq!((st.revision, st.history.past_len()), (rev, past)); + assert_eq!((coverage(app, 2, 22), coverage(app, 30, 5), coverage(app, 5, 5)), (1.0, 0.0, 0.0)); +} + +#[test] +fn invert_flips_the_selection() { + let mut h = harness(app_with_doc()); + open(h.state_mut()); + h.run_steps(4); + set(&mut h, "select", json!("reds")); + h.get_by_label("Invert").click(); + h.run_steps(2); + let id = dialog_id(h.state()); + assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields.get("invert"), Some(&json!(true))); + ok(&mut h); + h.run_steps(2); + let app = h.state(); + assert_eq!((coverage(app, 5, 5), coverage(app, 30, 5), coverage(app, 5, 22), coverage(app, 30, 22)), (0.0, 1.0, 1.0, 1.0)); +} + +#[test] +fn eyedroppers_pick_on_the_preview() { + let mut h = harness(app_with_doc()); + open(h.state_mut()); + h.run_steps(4); + // 40 × 30 at 200 pt: 5 pt per pixel; the image is centred vertically (150 pt tall). + let at = |h: &Harness<'static, PhotocraftApp>, x: f32, y: f32| { + h.get_by_label("Color Range preview").rect().left_top() + egui::vec2(x * 5.0 + 2.5, 25.0 + y * 5.0 + 2.5) + }; + let p = at(&h, 30.0, 5.0); + click(&mut h, p); + h.run_steps(2); + let f = |h: &Harness<'static, PhotocraftApp>| h.state().ui.dialogs.iter().find(|d| owns(&d.fields)).unwrap().fields.clone(); + assert_eq!(points(&f(&h), "points"), vec![[30.0, 5.0]]); + // Add to Sample: the red block too; the selection then covers both. + h.get_by_label("Add to Sample").click(); + h.run_steps(1); + let p = at(&h, 5.0, 5.0); + click(&mut h, p); + h.run_steps(2); + assert_eq!(points(&f(&h), "points").len(), 2); + // Subtract from Sample: take the blue back out. + h.get_by_label("Subtract from Sample").click(); + h.run_steps(1); + let p = at(&h, 35.0, 10.0); + click(&mut h, p); + h.run_steps(2); + assert_eq!(points(&f(&h), "subtractPoints"), vec![[35.0, 10.0]]); + let p = params(&f(&h)); + assert_eq!(p["select"], "sampledColors"); + assert_eq!(p["order"], json!(["+", "+", "-"])); + ok(&mut h); + h.run_steps(2); + let app = h.state(); + // The sampled red stays fully selected. + assert_eq!(coverage(app, 5, 5), 1.0); + // Like Photoshop, subtracting a colour on the edge of the samples' range only trims that + // edge by a fifth of the falloff: the blue stays mostly selected (Photoshop: 232 of 255 + // for the same case), black never was. + let blue = coverage(app, 30, 5); + assert!(blue > 0.85 && blue < 0.95, "{blue}"); + assert_eq!(coverage(app, 5, 22), 0.0); +} + +#[test] +fn selection_preview_modes_cover_only_unselected_pixels() { + assert_eq!(overlay_pixel("grayscale", 1.0), Color32::WHITE); + assert_eq!(overlay_pixel("grayscale", 0.0), Color32::BLACK); + assert_eq!(overlay_pixel("grayscale", 0.5), Color32::from_gray(128)); + for mode in ["blackMatte", "whiteMatte", "quickMask"] { + assert_eq!(overlay_pixel(mode, 1.0).a(), 0, "{mode}: selected pixels stay visible"); + } + assert_eq!(overlay_pixel("blackMatte", 0.0), Color32::BLACK); + assert_eq!(overlay_pixel("whiteMatte", 0.0), Color32::WHITE); + assert_eq!(overlay_pixel("quickMask", 0.0).a(), 128); + assert_eq!(overlay_pixel("quickMask", 0.5).a(), 64); + assert_eq!(overlay_pixel("none", 0.0), Color32::TRANSPARENT); +} + +#[test] +fn preview_mode_is_view_state_and_cancel_preserves_selection() { + let mut h = harness(app_with_doc()); + h.state_mut().run("select.rect", json!({"x": 0, "y": 20, "width": 5, "height": 5})).unwrap(); + let original = h.state().session.active().unwrap(); + let past = original.history.past_len(); + let revision = original.revision; + let id = open(h.state_mut()); + h.run_steps(3); + for (mode, _) in PREVIEWS { + set(&mut h, "__selectionPreview", json!(mode)); + let f = &h.state().ui.dialogs.last().unwrap().fields; + assert!(params(f).get("__selectionPreview").is_none()); + let painter = h.ctx.layer_painter(egui::LayerId::background()); + let doc = h.state().session.active().unwrap().doc.id; + let ctx = h.ctx.clone(); + paint_selection_preview(h.state_mut(), &ctx, &painter, doc, Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)), false); + let st = h.state().session.active().unwrap(); + assert_eq!((st.revision, st.history.past_len()), (revision, past)); + assert_eq!(coverage(h.state(), 2, 22), 1.0); + } + h.state_mut().ui.close_dialog(id); + let painter = h.ctx.layer_painter(egui::LayerId::background()); + let ctx = h.ctx.clone(); + let doc = h.state().session.active().unwrap().doc.id; + paint_selection_preview(h.state_mut(), &ctx, &painter, doc, Rect::EVERYTHING, false); + assert_eq!(coverage(h.state(), 2, 22), 1.0); +} + +#[test] +fn repeated_subtraction_clicks_are_not_discarded() { + let mut app = app_with_doc(); + let id = open(&mut app); + let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); + pick(&app, &mut f, [2.0, 2.0], egui::Modifiers::NONE); + pick(&app, &mut f, [30.0, 2.0], egui::Modifiers::SHIFT); + pick(&app, &mut f, [30.0, 2.0], egui::Modifiers::ALT); + pick(&app, &mut f, [30.0, 2.0], egui::Modifiers::ALT); + assert_eq!(params(&f)["order"], json!(["+", "+", "-", "-"])); +} + +#[test] +fn control_pointer_drag_samples_and_never_paints_under_the_dialog() { + let mut h = harness(app_with_doc()); + let app = h.state_mut(); + open(app); + let doc = app.session.active().unwrap(); + let before = doc.revision; + let history = doc.history.past_len(); + let ctx = h.ctx.clone(); + for (events, shift) in [ + (json!([{"kind":"down","x":2,"y":2},{"kind":"move","x":3,"y":2},{"kind":"up","x":3,"y":2}]), false), + (json!([{"kind":"down","x":30,"y":2},{"kind":"move","x":31,"y":2},{"kind":"up","x":31,"y":2}]), true), + ] { + let (req, _) = crate::control::ControlRequest::new("ui.pointer", json!({"events":events,"shift":shift})); + let _ = crate::control::handle(h.state_mut(), &ctx, &req); + } + let fields = &h.state().ui.dialogs.last().unwrap().fields; + assert_eq!(points(fields, "points"), [[3.0, 2.0], [30.0, 2.0], [31.0, 2.0]]); + let doc = h.state().session.active().unwrap(); + assert_eq!((doc.revision, doc.history.past_len()), (before, history)); + assert!(h.state().drag.is_none()); + assert!(!pick_top(h.state_mut(), [-1.0, 0.0], egui::Modifiers::NONE)); +} + +#[test] +fn modifier_temporarily_swaps_image_and_selection_thumbnail() { + let mut h = harness(app_with_doc()); + let id = open(h.state_mut()); + h.run_steps(3); + let f = h.state().ui.dialogs.last().unwrap().fields.clone(); + let ctx = h.ctx.clone(); + let selection = preview(h.state_mut(), &ctx, &f).unwrap().0; + h.event(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND)); + h.run_steps(2); + let image = preview(h.state_mut(), &ctx, &f).unwrap().0; + assert_ne!(image, selection); + assert_eq!(h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["__view"], "selection"); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(2); + assert_eq!(preview(h.state_mut(), &ctx, &f).unwrap().0, selection); +} + +/// A sample between thumbnail pixels must use the original pixel, not its neighbour. +#[test] +fn reduced_preview_matches_the_original_eyedropper_sample() { + let mut doc = Document::with_background("fine detail", Size::new(400, 4), ColorMode::Rgb, SampleType::U8, Color::rgb(1.0, 0.0, 0.0)); + let surface = doc.layers[0].surface_mut().unwrap(); + surface.fill_rect(GRect::new(200, 0, 400, 4), &[0.0, 0.0, 1.0, 1.0]); + surface.fill_rect(GRect::new(101, 0, 102, 4), &[0.0, 0.0, 1.0, 1.0]); + let mut session = photocraft_engine::Session::new(); + session.add_document(doc, None); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + let id = open(&mut app); + let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone(); + pick(&app, &mut fields, [101.0, 1.0], egui::Modifiers::NONE); + fields.insert("fuzziness".into(), json!(0.0)); + let original = app.session.active().unwrap().doc.clone(); + let proxy = crate::proxy::proxy_document(&original, 2); + let mut old = photocraft_engine::Session::new(); + old.add_document(proxy.clone(), None); + old.execute(COMMAND, json!({"points": [[50, 0]], "fuzziness": 0})).unwrap(); + assert_eq!( + old.active().unwrap().doc.selection.as_ref().unwrap().sample_channel(150, 0, 0), + 0.0, + "sampling the thumbnail instead selects the red neighbour" + ); + let shown = proxy_mask(&app, &proxy, 2, ¶ms(&fields)).unwrap(); + confirm(&mut app, &fields).unwrap(); + assert_eq!(coverage(&app, 300, 0), 1.0); + assert_eq!(shown[150], coverage(&app, 300, 0), "preview must show the same blue pixels as OK"); + assert_eq!(shown[0], coverage(&app, 0, 0), "preview must leave the red background unselected"); +} + +/// `sampleAllLayers: false` judges the active layer in the preview, as OK does. +#[test] +fn preview_honours_sample_all_layers_like_ok() { + let mut app = app_with_doc(); + let doc = app.session.active().unwrap().doc.clone(); + let mut top = photocraft_doc::Layer::new("blue cover", photocraft_doc::LayerContent::Raster(doc.layers[0].surface().unwrap().clone())); + top.surface_mut().unwrap().fill_rect(GRect::new(0, 0, 40, 30), &[0.0, 0.0, 1.0, 1.0]); + app.session + .edit("layers", |doc, _| { + doc.layers.push(top); + Ok(()) + }) + .unwrap(); + for all_layers in [false, true] { + let p = json!({"select": "sampledColors", "points": [[5, 5]], "fuzziness": 0, "sampleAllLayers": all_layers}); + let proxy = crate::proxy::proxy_document(&app.session.active().unwrap().doc, 1); + let shown = proxy_mask(&app, &proxy, 1, &p).unwrap(); + app.run(COMMAND, p).unwrap(); + for (x, y) in [(5, 5), (30, 5), (5, 20), (30, 20)] { + assert_eq!(shown[y * 40 + x], coverage(&app, x as i32, y as i32), "all_layers={all_layers} at ({x}, {y})"); + } + } +} + +#[test] +fn params_send_only_what_the_mode_uses() { + let mut app = app_with_doc(); + let id = open(&mut app); + let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); + assert_eq!(params(&f), json!({"select": "sampledColors", "invert": false, "fuzziness": 40.0})); + // Localized needs a picked point. + f.insert("localized".into(), json!(true)); + assert!(params(&f).get("localized").is_none()); + pick(&app, &mut f, [3.0, 4.0], egui::Modifiers::NONE); + pick(&app, &mut f, [99.0, -4.0], egui::Modifiers::SHIFT); + pick(&app, &mut f, [1.0, 1.0], egui::Modifiers::ALT); + assert_eq!( + params(&f), + json!({"select": "sampledColors", "invert": false, "fuzziness": 40.0, "points": [[3.0, 4.0], [39.0, 0.0]], "subtractPoints": [[1.0, 1.0]], "order": ["+", "+", "-"], "localized": true, "range": 100.0}) + ); + f.insert("select".into(), json!("midtones")); + f.insert("midtonesLow".into(), json!(160.0)); + assert_eq!(params(&f), json!({"select": "midtones", "invert": false, "fuzziness": 20.0, "tonalRange": [150.0, 160.0]})); + f.insert("select".into(), json!("highlights")); + assert_eq!(params(&f)["tonalRange"], json!(190.0)); + f.insert("select".into(), json!("cyans")); + assert_eq!(params(&f), json!({"select": "cyans", "invert": false})); + // Every Select entry is accepted by the engine. + for (v, _) in SELECTS { + f.insert("select".into(), json!(v)); + app.run(COMMAND, params(&f)).unwrap(); + } +} + +/// #145: the whole app without a GPU (no wgpu render state: the CPU canvas, as on a Linux +/// machine whose adapter can't run the GPU canvas), on a small window. Select › Color Range… +/// from the menu opens the dialog on screen and draws both previews. +#[test] +fn opens_and_previews_in_the_full_app_without_a_gpu() { + let mut h = Harness::builder().with_size(egui::vec2(1024.0, 600.0)).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + assert!(cc.wgpu_render_state.is_none(), "this test covers the no-GPU path"); + app_with_doc() + }); + h.run_steps(6); + assert!(h.state().gpu.is_none(), "the CPU canvas"); + h.get_all_by_label("Select").next().expect("the Select menu").click(); + h.run_steps(3); + h.get_by_label("Color Range…").click(); + h.run_steps(6); + let id = dialog_id(h.state()); + let area = h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", id)))).expect("the dialog is drawn"); + assert!(h.ctx.content_rect().contains_rect(area), "the dialog is on screen: {area:?}"); + assert!(h.query_by_label("Color Range preview").is_some()); + let p = h.state().color_range.as_ref().expect("the preview is cached"); + assert!(p.mask.is_some() && p.error.is_none(), "the selection preview is drawn: {:?}", p.error); + set(&mut h, "__view", json!("image")); + let p = h.state().color_range.as_ref().unwrap(); + assert!(p.image.is_some() && p.error.is_none(), "the image preview is drawn: {:?}", p.error); + set(&mut h, "select", json!("reds")); + ok(&mut h); + h.run_steps(3); + assert_eq!(coverage(h.state(), 5, 5), 1.0); +} + +#[test] +fn a_preview_failure_is_shown_not_silent() { + let mut h = harness(app_with_doc()); + open(h.state_mut()); + h.run_steps(3); + // The engine refuses these params: the preview says so instead of staying blank. + let id = dialog_id(h.state()); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("select".into(), json!("noSuchMode")); + h.run_steps(3); + let err = h.state().color_range.as_ref().and_then(|p| p.error.clone()); + assert!(err.is_some(), "the failure is recorded"); + assert!(h.query_by_label_contains("Color Range preview unavailable").is_some(), "and shown"); + set(&mut h, "select", json!("reds")); + assert!(h.state().color_range.as_ref().unwrap().error.is_none(), "and cleared once the preview works again"); +} From 97113021f3885805cb583fe235c4372ab4fb44a3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:34 +0000 Subject: [PATCH 057/259] refactor(ui-egui): move titlebar.rs tests to titlebar/tests.rs --- crates/ui-egui/src/titlebar.rs | 494 +-------------------------- crates/ui-egui/src/titlebar/tests.rs | 491 ++++++++++++++++++++++++++ 2 files changed, 492 insertions(+), 493 deletions(-) create mode 100644 crates/ui-egui/src/titlebar/tests.rs diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs index b7044e4caf..da1e44b452 100644 --- a/crates/ui-egui/src/titlebar.rs +++ b/crates/ui-egui/src/titlebar.rs @@ -547,496 +547,4 @@ pub fn resize_zones(ui: &mut Ui) { } #[cfg(test)] -mod tests { - use super::*; - use egui::{Event, Pos2, RawInput, ViewportId}; - use photocraft_engine::Session; - - /// #5826: the drag overlay under a dialog doesn't depend on the custom title bar. On macOS - /// (OS traffic lights over the app's own title strip) a dialog left the window undraggable. - #[test] - fn a_dialog_keeps_the_title_strip_draggable_with_either_title_bar() { - for custom in [false, true] { - let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); - app.custom_titlebar = custom; - app.run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); - assert!(!app.titlebar_modal_drag(true), "no dialog, no overlay"); - crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); - assert!(app.titlebar_modal_drag(true), "custom title bar: {custom}"); - assert!(!app.titlebar_modal_drag(false), "chrome hidden (full screen): no title strip"); - app.ui.panels.menu_bar = false; - assert!(!app.titlebar_modal_drag(true), "no menu bar, no title strip"); - } - } - - /// A headless window `width` pt wide showing the title bar and the resize zones. - struct Win { - ctx: egui::Context, - app: PhotocraftApp, - width: f32, - time: f64, - maximized: bool, - } - - impl Win { - fn new(width: f32) -> Self { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); - app.custom_titlebar = true; - Self { ctx, app, width, time: 0.0, maximized: false } - } - - fn frame(&mut self, events: Vec) -> egui::FullOutput { - self.frame_with_modal(events, false) - } - - fn frame_with_modal(&mut self, events: Vec, modal: bool) -> egui::FullOutput { - self.time += 0.05; - let mut input = - RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(self.width, 600.0))), time: Some(self.time), events, ..Default::default() }; - if let Some(v) = input.viewports.get_mut(&ViewportId::ROOT) { - v.maximized = Some(self.maximized); - } - // What `PhotocraftApp::raw_input_hook` does. - release_after_os_resize(&self.ctx, &mut input); - let app = &mut self.app; - let mut out = self.ctx.run_ui(input, |ui| { - crate::panels::title_bar(app, ui); - if modal { - egui::Modal::new(Id::unique("titlebar-drag-test-modal")).backdrop_color(Color32::TRANSPARENT).show(ui.ctx(), |ui| { - ui.label("Modal dialog"); - }); - modal_drag_overlay(ui.ctx()); - } - resize_zones(ui); - }); - out.textures_delta.clear(); - out - } - - /// Frames for a pointer gesture: move to `path[0]`, press, move along `path`, release. The - /// viewport commands the frames sent. - fn gesture(&mut self, path: &[Pos2]) -> Vec { - self.gesture_with_modal(path, false) - } - - fn gesture_with_modal(&mut self, path: &[Pos2], modal: bool) -> Vec { - self.gesture_by(path, modal, egui::PointerButton::Primary) - } - - fn gesture_by(&mut self, path: &[Pos2], modal: bool, btn: egui::PointerButton) -> Vec { - let mut events = vec![vec![Event::PointerMoved(path[0])], vec![button(path[0], true, btn)]]; - events.extend(path[1..].iter().map(|p| vec![Event::PointerMoved(*p)])); - events.push(vec![button(*path.last().unwrap_or(&path[0]), false, btn)]); - events - .into_iter() - .flat_map(|e| self.frame_with_modal(e, modal).viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default()) - .collect() - } - - fn click(&mut self, p: Pos2) -> Vec { - self.gesture(&[p]) - } - - fn caption(&self, c: Caption) -> Rect { - self.ctx.read_response(caption_id(c)).map(|r| r.rect).unwrap_or(Rect::NOTHING) - } - - /// The bar's clickable widgets other than its drag gap and the caption buttons. - fn bar_widgets(&self) -> Vec { - let skip = CAPTIONS.map(caption_id); - self.ctx.viewport(|v| { - v.prev_pass - .widgets - .layers() - .filter(|(l, _)| l.order != Order::Foreground) - .flat_map(|(_, ws)| ws.iter()) - .filter(|w| w.sense.senses_click() && !w.sense.senses_drag() && w.rect.top() < 30.0 && !skip.contains(&w.id)) - .map(|w| w.rect) - .collect() - }) - } - } - - fn texts(out: &egui::FullOutput) -> Vec<(String, Rect)> { - fn walk(s: &egui::Shape, v: &mut Vec<(String, Rect)>) { - match s { - egui::Shape::Text(t) => v.push((t.galley.text().to_string(), Rect::from_min_size(t.pos, t.galley.size()))), - egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)), - _ => {} - } - } - let mut v = vec![]; - out.shapes.iter().for_each(|c| walk(&c.shape, &mut v)); - v - } - - fn button(p: Pos2, pressed: bool, button: egui::PointerButton) -> Event { - Event::PointerButton { pos: p, button, pressed, modifiers: Default::default() } - } - - #[test] - fn caption_buttons_take_the_right_end_and_nothing_overlaps_them() { - for width in [760.0, 1100.0, 1440.0] { - let mut w = Win::new(width); - w.frame(vec![]); - w.frame(vec![]); - let [min, max, close] = CAPTIONS.map(|c| w.caption(c)); - assert_eq!((close.right(), close.top()), (width, 0.0), "Close sits in the window's corner at {width}"); - // The bar's bottom point is the panel's separator line, which the buttons leave visible. - assert!(close.height() >= 31.0 && [min, max, close].iter().all(|r| r.width() == BUTTON_WIDTH)); - assert_eq!((min.right(), max.right()), (max.left(), close.left())); - let widgets = w.bar_widgets(); - assert!(widgets.len() >= 10, "menus, search, theme, workspace: {widgets:?}"); - for a in &widgets { - assert!(a.right() <= min.left(), "{a:?} runs into the caption buttons at {width}"); - } - } - } - - #[test] - fn the_title_bar_promotes_no_community_chat() { - // Issue #1726: only the always-visible title-bar button is removed. The start-screen - // and About buttons and Help › Discord remain available. - for width in [760.0, 1100.0, 1440.0] { - let mut w = Win::new(width); - w.frame(vec![]); - let out = w.frame(vec![]); - assert!(!texts(&out).iter().any(|(t, _)| t.contains("Discord")), "no Discord in the bar at {width}"); - } - } - - #[test] - fn the_brand_mark_leads_the_bar() { - let mut w = Win::new(1440.0); - w.frame(vec![]); - let out = w.frame(vec![]); - let mark = crate::brand::mark_rect(&w.ctx).expect("the brand mark is painted"); - let file = texts(&out).into_iter().find(|(t, _)| t == "File").map(|(_, r)| r).expect("the File menu title"); - assert!(mark.right() < file.left(), "the mark sits left of the menus: {mark:?} {file:?}"); - assert!(mark.left() < 20.0 && mark.width() >= 16.0, "{mark:?}"); - } - - #[test] - fn close_runs_file_exit_which_asks_about_unsaved_work() { - let mut w = Win::new(1100.0); - w.frame(vec![]); - let close = w.caption(Caption::Close).center(); - let cmds = w.click(close); - // File › Exit asks the window to close; the unsaved-changes guard (`discard_ui`) then - // decides, so the caption button and the menu item behave the same. - assert!(cmds.iter().any(|c| matches!(c, ViewportCommand::Close)), "{cmds:?}"); - } - - /// After the window's GPU device is lost, the prompt asking about unsaved work could never be - /// drawn: the close button quits instead of opening it (see `discard_ui::intercept`). - #[test] - fn close_quits_without_a_prompt_once_the_window_device_is_lost() { - let mut w = Win::new(1100.0); - w.app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - w.app.run("layer.new.layer", json!({})).unwrap(); - w.frame(vec![]); - let close = w.caption(Caption::Close).center(); - let asks = w.click(close); - assert!(!asks.iter().any(|c| matches!(c, ViewportCommand::Close)), "a window that can draw asks first: {asks:?}"); - assert!(w.app.discard.is_some()); - w.app.discard = None; - w.app.window_lost = true; - let quits = w.click(close); - assert!(quits.iter().any(|c| matches!(c, ViewportCommand::Close)), "{quits:?}"); - assert!(w.app.discard.is_none(), "no prompt opened"); - } - - #[test] - fn minimize_and_maximize_follow_the_window_state() { - let mut w = Win::new(1100.0); - w.frame(vec![]); - let (min, max) = (w.caption(Caption::Minimize).center(), w.caption(Caption::Maximize).center()); - assert!(w.click(min).contains(&ViewportCommand::Minimized(true))); - assert!(w.click(max).contains(&ViewportCommand::Maximized(true))); - w.maximized = true; - assert!(w.click(max).contains(&ViewportCommand::Maximized(false)), "Restore"); - } - - #[test] - fn empty_bar_space_drags_and_double_click_maximizes() { - let mut w = Win::new(1440.0); - w.frame(vec![]); - let empty = pos2(980.0, 16.0); - assert!(w.bar_widgets().iter().all(|r| !r.contains(empty)), "the probe point must be empty bar space"); - let cmds = w.gesture(&[empty, empty + vec2(12.0, 4.0), empty + vec2(30.0, 8.0)]); - assert_eq!(cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(), 1, "{cmds:?}"); - let mut cmds = w.click(empty); - cmds.extend(w.click(empty)); - assert!(cmds.contains(&ViewportCommand::Maximized(true)), "{cmds:?}"); - w.maximized = true; - w.time += 1.0; - let mut cmds = w.click(empty); - cmds.extend(w.click(empty)); - assert!(cmds.contains(&ViewportCommand::Maximized(false)), "{cmds:?}"); - // Widgets keep their clicks: dragging from a menu title doesn't move the window. - let file = texts(&w.frame(vec![])).into_iter().find(|(t, _)| t == "File").map(|(_, r)| r.center()); - let file = file.expect("the File menu title"); - let cmds = w.gesture(&[file, file + vec2(12.0, 4.0), file + vec2(30.0, 8.0)]); - assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}"); - } - - #[test] - fn empty_bar_space_still_drags_with_a_modal_open() { - let mut w = Win::new(1440.0); - w.frame(vec![]); - w.frame_with_modal(vec![], true); - let empty = pos2(980.0, 16.0); - let drag_area = w.ctx.data(|d| d.get_temp::(modal_drag_area_id())); - assert!(drag_area.is_some_and(|r| r.contains(empty)), "the test point must be in the current title-bar gap: {drag_area:?}"); - assert!(w.bar_widgets().iter().all(|r| !r.contains(empty)), "the probe point must be empty bar space"); - let cmds = w.gesture_with_modal(&[empty, empty + vec2(12.0, 4.0), empty + vec2(30.0, 8.0)], true); - assert_eq!(cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(), 1, "{cmds:?}"); - } - - #[test] - fn middle_button_drag_in_the_gap_does_not_start_a_window_drag() { - let mut w = Win::new(1440.0); - w.frame(vec![]); - let empty = pos2(980.0, 16.0); - let path = [empty, empty + vec2(12.0, 4.0), empty + vec2(30.0, 8.0)]; - let cmds = w.gesture_by(&path, false, egui::PointerButton::Middle); - assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}"); - // An ordinary left drag afterwards still moves the window. - let cmds = w.gesture(&path); - assert_eq!(cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(), 1, "{cmds:?}"); - // Same with a modal open (the overlay over the gap). - w.frame_with_modal(vec![], true); - let cmds = w.gesture_by(&path, true, egui::PointerButton::Middle); - assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}"); - } - - #[test] - fn modal_drag_overlay_does_not_cover_a_dialog_moved_into_the_gap() { - let mut w = Win::new(1440.0); - w.frame(vec![]); - w.frame_with_modal(vec![], true); - let area = w.ctx.data(|d| d.get_temp::(modal_drag_area_id())).unwrap_or(Rect::NOTHING); - assert!(area.contains(pos2(980.0, 16.0)), "the probe point must be in the gap: {area:?}"); - w.ctx.data_mut(|d| d.insert_temp(Id::unique("pc-dialog-rects"), vec![area])); - let cmds = w.gesture_with_modal(&[area.center(), area.center() + vec2(12.0, 4.0)], true); - assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}"); - } - - /// #1581: KDE Wayland keeps the button release of an OS resize. egui then kept the edge - /// pressed (no hover until the next click) and egui-winit never re-sent the resize cursor that - /// the compositor had replaced: the cursor came back only on every other press. - #[test] - fn after_an_os_resize_the_edge_hovers_and_shows_its_cursor_again() { - let mut w = Win::new(1000.0); - w.frame(vec![]); - let p = pos2(3.0, 300.0); - // Press and drag; the compositor takes over, so no release ever arrives. - let mut cmds = vec![]; - for e in [vec![Event::PointerMoved(p)], vec![button(p, true, egui::PointerButton::Primary)], vec![Event::PointerMoved(p + vec2(6.0, 0.0))]] { - cmds.extend(w.frame(e).viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default()); - } - assert!(cmds.contains(&ViewportCommand::BeginResize(ResizeDirection::West)), "{cmds:?}"); - w.frame(vec![]); - assert!(!w.ctx.input(|i| i.pointer.primary_down()), "the press ends with the hand-off"); - // The pointer comes back: one frame of the default cursor, so the next one is re-sent. - let out = w.frame(vec![Event::PointerMoved(p)]); - assert_eq!(out.platform_output.cursor_icon, CursorIcon::Default); - let out = w.frame(vec![Event::PointerMoved(p + vec2(1.0, 0.0))]); - assert_eq!(out.platform_output.cursor_icon, CursorIcon::ResizeWest); - // And the next press resizes again (it alternated before). - assert!(w.gesture(&[p, p + vec2(6.0, 0.0)]).contains(&ViewportCommand::BeginResize(ResizeDirection::West))); - } - - /// Where the OS does send the release of a resize (Windows), no second one is added: a - /// release right after it could count as a click on what lies under the edge. - #[test] - fn a_release_the_os_sends_is_not_doubled() { - let mut w = Win::new(1000.0); - w.frame(vec![]); - let p = pos2(3.0, 300.0); - w.frame(vec![Event::PointerMoved(p)]); - w.frame(vec![button(p, true, egui::PointerButton::Primary)]); - w.frame(vec![Event::PointerMoved(p + vec2(6.0, 0.0))]); - // The release arrives with the next input. - let mut raw = RawInput { events: vec![button(p + vec2(6.0, 0.0), false, egui::PointerButton::Primary)], ..Default::default() }; - release_after_os_resize(&w.ctx, &mut raw); - assert_eq!(raw.events.len(), 1, "{:?}", raw.events); - // Or it already arrived in an earlier input: egui has the button up, nothing to end. - let mut w = Win::new(1000.0); - w.frame(vec![]); - w.gesture(&[p, p + vec2(6.0, 0.0)]); - let mut raw = RawInput::default(); - release_after_os_resize(&w.ctx, &mut raw); - assert!(raw.events.is_empty(), "{:?}", raw.events); - } - - /// #5725: the window manager keeps the button release of an OS move just as of a resize, so - /// egui kept the drag: every other move of the window failed, and so did a resize right after one. - #[test] - fn after_an_os_move_the_bar_and_the_edges_take_the_next_press() { - /// Press and drag along `path`; the window manager takes over, so no release ever arrives. - fn handed_off(w: &mut Win, path: &[Pos2]) -> Vec { - let mut events = vec![vec![Event::PointerMoved(path[0])], vec![button(path[0], true, egui::PointerButton::Primary)]]; - events.extend(path[1..].iter().map(|p| vec![Event::PointerMoved(*p)])); - events.push(vec![]); - events.into_iter().flat_map(|e| w.frame(e).viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default()).collect() - } - let moves = |cmds: &[ViewportCommand]| cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(); - let mut w = Win::new(1440.0); - w.frame(vec![]); - let empty = pos2(980.0, 16.0); - assert!(w.bar_widgets().iter().all(|r| !r.contains(empty)), "the probe point must be empty bar space"); - let drag = [empty, empty + vec2(12.0, 4.0), empty + vec2(30.0, 8.0)]; - assert_eq!(moves(&handed_off(&mut w, &drag)), 1); - assert!(!w.ctx.input(|i| i.pointer.primary_down()), "the press ends with the hand-off"); - assert_eq!(moves(&w.gesture(&drag)), 1, "the next move"); - assert_eq!(moves(&handed_off(&mut w, &drag)), 1); - let edge = pos2(3.0, 300.0); - assert!(w.gesture(&[edge, edge + vec2(6.0, 0.0)]).contains(&ViewportCommand::BeginResize(ResizeDirection::West)), "a resize after a move"); - } - - #[test] - fn edge_zones_resize_unless_maximized() { - use ResizeDirection::*; - let mut w = Win::new(1000.0); - w.frame(vec![]); - for (p, dir) in [ - (pos2(1.0, 300.0), West), - (pos2(998.0, 300.0), East), - (pos2(500.0, 1.0), North), - (pos2(500.0, 598.0), South), - (pos2(2.0, 2.0), NorthWest), - (pos2(997.0, 3.0), NorthEast), - (pos2(3.0, 597.0), SouthWest), - (pos2(998.0, 598.0), SouthEast), - ] { - let cmds = w.gesture(&[p, p + vec2(6.0, 6.0)]); - assert_eq!(cmds, vec![ViewportCommand::BeginResize(dir)], "at {p:?}"); - } - // The first motion after those resizes shows the default cursor for a frame (see - // `reshow_cursor_after_os_resize`). - w.frame(vec![Event::PointerMoved(pos2(500.0, 300.0))]); - // One-sided cursors, which every cursor theme has (#1581), anywhere in the 8 pt edge. - for (p, cursor) in [ - (pos2(7.0, 300.0), CursorIcon::ResizeWest), - (pos2(993.0, 300.0), CursorIcon::ResizeEast), - (pos2(500.0, 7.0), CursorIcon::ResizeNorth), - (pos2(500.0, 593.0), CursorIcon::ResizeSouth), - (pos2(2.0, 2.0), CursorIcon::ResizeNwSe), - (pos2(997.0, 3.0), CursorIcon::ResizeNeSw), - (pos2(3.0, 597.0), CursorIcon::ResizeNeSw), - (pos2(998.0, 598.0), CursorIcon::ResizeNwSe), - ] { - let out = w.frame(vec![Event::PointerMoved(p)]); - assert_eq!(out.platform_output.cursor_icon, cursor, "at {p:?}"); - } - let cmds = w.gesture(&[pos2(7.0, 300.0), pos2(13.0, 306.0)]); - assert_eq!(cmds, vec![ViewportCommand::BeginResize(West)], "the edge zone is 8 pt deep"); - // Clear of the zone and of egui's interact radius around it. - let cmds = w.gesture(&[pos2(20.0, 300.0), pos2(26.0, 306.0)]); - assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::BeginResize(_))), "{cmds:?}"); - // Maximized: no zones, and the window's top-right corner is Close. - w.maximized = true; - let cmds = w.gesture(&[pos2(1.0, 300.0), pos2(8.0, 300.0)]); - assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::BeginResize(_))), "{cmds:?}"); - assert!(w.click(pos2(999.5, 0.5)).iter().any(|c| matches!(c, ViewportCommand::Close))); - } - - #[test] - fn gtk_layouts_pick_the_buttons_and_their_sides() { - use Caption::*; - let s = CaptionStyle::from_gtk_layout(CaptionFamily::Adwaita, "appmenu:minimize,maximize,close"); - assert_eq!((s.left, s.right), (vec![], vec![Minimize, Maximize, Close])); - // Unknown names are skipped, spaces trimmed, a repeat placed once, a second colon is a name. - let s = CaptionStyle::from_gtk_layout(CaptionFamily::Adwaita, "close,close , minimize:icon,maximize:close"); - assert_eq!((s.left, s.right), (vec![Close, Minimize], vec![])); - let s = CaptionStyle::from_gtk_layout(CaptionFamily::Breeze, "minimize,close"); - assert_eq!((s.left, s.right), (vec![Minimize, Close], vec![]), "no colon: GTK puts them all at the start"); - let s = CaptionStyle::from_gtk_layout(CaptionFamily::Breeze, ""); - assert!(s.left.is_empty() && s.right.is_empty()); - assert_eq!(CaptionFamily::parse(" Breeze "), Some(CaptionFamily::Breeze)); - assert_eq!(CaptionFamily::parse("aqua"), None); - assert_eq!(CaptionStyle::default(), CaptionStyle { family: CaptionFamily::Windows, left: vec![], right: CAPTIONS.to_vec(), icons: None }); - } - - #[test] - fn linux_buttons_sit_where_the_layout_says_and_drag_the_window() { - use Caption::*; - for (family, size, gap, end) in [(CaptionFamily::Adwaita, 24.0, 6.5, 10.0), (CaptionFamily::Breeze, 18.0, 4.5, 8.0)] { - let width = 1100.0; - let mut w = Win::new(width); - w.app.services.caption_style = Some(Box::new(move |_| CaptionStyle { family, left: vec![Close], right: vec![Minimize, Maximize], icons: None })); - w.frame(vec![]); - w.frame(vec![]); - let [min, max, close] = CAPTIONS.map(|c| w.caption(c)); - // Flush with the window's edges, the edge gap outermost, the hit areas touching. - assert_eq!((close.left(), close.width()), (0.0, end + size + gap), "{family:?}"); - assert_eq!((max.right(), max.width()), (width, gap + size + end), "{family:?}"); - assert_eq!((min.right(), min.width()), (max.left(), 2.0 * gap + size), "{family:?}"); - // GNOME's header bars are taller than Photoshop's bar; KDE's are not. - if family == CaptionFamily::Adwaita { - assert_eq!(close.height(), 46.0); - } else { - assert!((31.0..46.0).contains(&close.height()), "{close:?}"); - } - let mark = crate::brand::mark_rect(&w.ctx).expect("the brand mark is painted"); - assert!(mark.left() > close.right(), "the bar starts after the left buttons: {mark:?} {close:?}"); - for a in w.bar_widgets() { - assert!(a.left() >= close.right() && a.right() <= min.left(), "{a:?} runs into the caption buttons ({family:?})"); - } - assert!(w.click(max.center()).contains(&ViewportCommand::Maximized(true))); - assert!(w.click(close.center()).iter().any(|c| matches!(c, ViewportCommand::Close))); - // A drag that starts on a button moves the window instead of pressing it. - let at = min.center(); - let cmds = w.gesture(&[at, at + vec2(12.0, 4.0), at + vec2(30.0, 8.0)]); - assert_eq!(cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(), 1, "{cmds:?}"); - assert!(!cmds.contains(&ViewportCommand::Minimized(true)), "{cmds:?}"); - } - } - - /// A side without buttons reserves nothing; without the custom title bar, neither does any. - #[test] - fn only_sides_with_buttons_take_room() { - let mut w = Win::new(1000.0); - w.app.services.caption_style = Some(Box::new(|_| CaptionStyle::from_gtk_layout(CaptionFamily::Adwaita, "appmenu:close"))); - assert_eq!(reserved(&w.app, &w.ctx), (0.0, 6.5 + 24.0 + 10.0)); - w.app.custom_titlebar = false; - assert_eq!(reserved(&w.app, &w.ctx), (0.0, 0.0)); - w.app.custom_titlebar = true; - w.app.services.caption_style = None; - assert_eq!(reserved(&w.app, &w.ctx), (0.0, 3.0 * BUTTON_WIDTH)); - } - - /// Theme glyphs upload once per theme and size; an icon the theme lacks, a wrong-sized mask or - /// an absurd size gives `None`, so the button draws its own glyph. - #[test] - fn theme_icons_are_cached_and_fall_back() { - use std::sync::atomic::{AtomicUsize, Ordering}; - let calls = std::sync::Arc::new(AtomicUsize::new(0)); - let counter = std::sync::Arc::clone(&calls); - let render = move |icon: CaptionIcon, px: u32| { - counter.fetch_add(1, Ordering::Relaxed); - match icon { - CaptionIcon::Close => Some(vec![255; (px * px) as usize]), - CaptionIcon::Minimize => Some(vec![255; 3]), - _ => None, - } - }; - let icons = CaptionIcons { theme: "Test".into(), render: std::sync::Arc::new(render) }; - let ctx = egui::Context::default(); - let mut out = ctx.run_ui(RawInput::default(), |ui| { - let tex = theme_icon(ui.ctx(), &icons, CaptionIcon::Close, 16).expect("rendered"); - assert_eq!(tex.size(), [16, 16]); - assert!(theme_icon(ui.ctx(), &icons, CaptionIcon::Close, 16).is_some()); - assert!(theme_icon(ui.ctx(), &icons, CaptionIcon::Restore, 16).is_none()); - assert!(theme_icon(ui.ctx(), &icons, CaptionIcon::Restore, 16).is_none()); - assert!(theme_icon(ui.ctx(), &icons, CaptionIcon::Minimize, 16).is_none(), "a mask of the wrong size"); - assert!(theme_icon(ui.ctx(), &icons, CaptionIcon::Close, 0).is_none()); - assert!(theme_icon(ui.ctx(), &icons, CaptionIcon::Close, 100_000).is_none()); - }); - out.textures_delta.clear(); - assert_eq!(calls.load(Ordering::Relaxed), 3, "each icon and size rendered once; absurd sizes never"); - } -} +mod tests; diff --git a/crates/ui-egui/src/titlebar/tests.rs b/crates/ui-egui/src/titlebar/tests.rs new file mode 100644 index 0000000000..7cb98aec55 --- /dev/null +++ b/crates/ui-egui/src/titlebar/tests.rs @@ -0,0 +1,491 @@ +use super::*; +use egui::{Event, Pos2, RawInput, ViewportId}; +use photocraft_engine::Session; + +/// #5826: the drag overlay under a dialog doesn't depend on the custom title bar. On macOS +/// (OS traffic lights over the app's own title strip) a dialog left the window undraggable. +#[test] +fn a_dialog_keeps_the_title_strip_draggable_with_either_title_bar() { + for custom in [false, true] { + let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); + app.custom_titlebar = custom; + app.run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); + assert!(!app.titlebar_modal_drag(true), "no dialog, no overlay"); + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + assert!(app.titlebar_modal_drag(true), "custom title bar: {custom}"); + assert!(!app.titlebar_modal_drag(false), "chrome hidden (full screen): no title strip"); + app.ui.panels.menu_bar = false; + assert!(!app.titlebar_modal_drag(true), "no menu bar, no title strip"); + } +} + +/// A headless window `width` pt wide showing the title bar and the resize zones. +struct Win { + ctx: egui::Context, + app: PhotocraftApp, + width: f32, + time: f64, + maximized: bool, +} + +impl Win { + fn new(width: f32) -> Self { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); + app.custom_titlebar = true; + Self { ctx, app, width, time: 0.0, maximized: false } + } + + fn frame(&mut self, events: Vec) -> egui::FullOutput { + self.frame_with_modal(events, false) + } + + fn frame_with_modal(&mut self, events: Vec, modal: bool) -> egui::FullOutput { + self.time += 0.05; + let mut input = + RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(self.width, 600.0))), time: Some(self.time), events, ..Default::default() }; + if let Some(v) = input.viewports.get_mut(&ViewportId::ROOT) { + v.maximized = Some(self.maximized); + } + // What `PhotocraftApp::raw_input_hook` does. + release_after_os_resize(&self.ctx, &mut input); + let app = &mut self.app; + let mut out = self.ctx.run_ui(input, |ui| { + crate::panels::title_bar(app, ui); + if modal { + egui::Modal::new(Id::unique("titlebar-drag-test-modal")).backdrop_color(Color32::TRANSPARENT).show(ui.ctx(), |ui| { + ui.label("Modal dialog"); + }); + modal_drag_overlay(ui.ctx()); + } + resize_zones(ui); + }); + out.textures_delta.clear(); + out + } + + /// Frames for a pointer gesture: move to `path[0]`, press, move along `path`, release. The + /// viewport commands the frames sent. + fn gesture(&mut self, path: &[Pos2]) -> Vec { + self.gesture_with_modal(path, false) + } + + fn gesture_with_modal(&mut self, path: &[Pos2], modal: bool) -> Vec { + self.gesture_by(path, modal, egui::PointerButton::Primary) + } + + fn gesture_by(&mut self, path: &[Pos2], modal: bool, btn: egui::PointerButton) -> Vec { + let mut events = vec![vec![Event::PointerMoved(path[0])], vec![button(path[0], true, btn)]]; + events.extend(path[1..].iter().map(|p| vec![Event::PointerMoved(*p)])); + events.push(vec![button(*path.last().unwrap_or(&path[0]), false, btn)]); + events + .into_iter() + .flat_map(|e| self.frame_with_modal(e, modal).viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default()) + .collect() + } + + fn click(&mut self, p: Pos2) -> Vec { + self.gesture(&[p]) + } + + fn caption(&self, c: Caption) -> Rect { + self.ctx.read_response(caption_id(c)).map(|r| r.rect).unwrap_or(Rect::NOTHING) + } + + /// The bar's clickable widgets other than its drag gap and the caption buttons. + fn bar_widgets(&self) -> Vec { + let skip = CAPTIONS.map(caption_id); + self.ctx.viewport(|v| { + v.prev_pass + .widgets + .layers() + .filter(|(l, _)| l.order != Order::Foreground) + .flat_map(|(_, ws)| ws.iter()) + .filter(|w| w.sense.senses_click() && !w.sense.senses_drag() && w.rect.top() < 30.0 && !skip.contains(&w.id)) + .map(|w| w.rect) + .collect() + }) + } +} + +fn texts(out: &egui::FullOutput) -> Vec<(String, Rect)> { + fn walk(s: &egui::Shape, v: &mut Vec<(String, Rect)>) { + match s { + egui::Shape::Text(t) => v.push((t.galley.text().to_string(), Rect::from_min_size(t.pos, t.galley.size()))), + egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut v = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut v)); + v +} + +fn button(p: Pos2, pressed: bool, button: egui::PointerButton) -> Event { + Event::PointerButton { pos: p, button, pressed, modifiers: Default::default() } +} + +#[test] +fn caption_buttons_take_the_right_end_and_nothing_overlaps_them() { + for width in [760.0, 1100.0, 1440.0] { + let mut w = Win::new(width); + w.frame(vec![]); + w.frame(vec![]); + let [min, max, close] = CAPTIONS.map(|c| w.caption(c)); + assert_eq!((close.right(), close.top()), (width, 0.0), "Close sits in the window's corner at {width}"); + // The bar's bottom point is the panel's separator line, which the buttons leave visible. + assert!(close.height() >= 31.0 && [min, max, close].iter().all(|r| r.width() == BUTTON_WIDTH)); + assert_eq!((min.right(), max.right()), (max.left(), close.left())); + let widgets = w.bar_widgets(); + assert!(widgets.len() >= 10, "menus, search, theme, workspace: {widgets:?}"); + for a in &widgets { + assert!(a.right() <= min.left(), "{a:?} runs into the caption buttons at {width}"); + } + } +} + +#[test] +fn the_title_bar_promotes_no_community_chat() { + // Issue #1726: only the always-visible title-bar button is removed. The start-screen + // and About buttons and Help › Discord remain available. + for width in [760.0, 1100.0, 1440.0] { + let mut w = Win::new(width); + w.frame(vec![]); + let out = w.frame(vec![]); + assert!(!texts(&out).iter().any(|(t, _)| t.contains("Discord")), "no Discord in the bar at {width}"); + } +} + +#[test] +fn the_brand_mark_leads_the_bar() { + let mut w = Win::new(1440.0); + w.frame(vec![]); + let out = w.frame(vec![]); + let mark = crate::brand::mark_rect(&w.ctx).expect("the brand mark is painted"); + let file = texts(&out).into_iter().find(|(t, _)| t == "File").map(|(_, r)| r).expect("the File menu title"); + assert!(mark.right() < file.left(), "the mark sits left of the menus: {mark:?} {file:?}"); + assert!(mark.left() < 20.0 && mark.width() >= 16.0, "{mark:?}"); +} + +#[test] +fn close_runs_file_exit_which_asks_about_unsaved_work() { + let mut w = Win::new(1100.0); + w.frame(vec![]); + let close = w.caption(Caption::Close).center(); + let cmds = w.click(close); + // File › Exit asks the window to close; the unsaved-changes guard (`discard_ui`) then + // decides, so the caption button and the menu item behave the same. + assert!(cmds.iter().any(|c| matches!(c, ViewportCommand::Close)), "{cmds:?}"); +} + +/// After the window's GPU device is lost, the prompt asking about unsaved work could never be +/// drawn: the close button quits instead of opening it (see `discard_ui::intercept`). +#[test] +fn close_quits_without_a_prompt_once_the_window_device_is_lost() { + let mut w = Win::new(1100.0); + w.app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + w.app.run("layer.new.layer", json!({})).unwrap(); + w.frame(vec![]); + let close = w.caption(Caption::Close).center(); + let asks = w.click(close); + assert!(!asks.iter().any(|c| matches!(c, ViewportCommand::Close)), "a window that can draw asks first: {asks:?}"); + assert!(w.app.discard.is_some()); + w.app.discard = None; + w.app.window_lost = true; + let quits = w.click(close); + assert!(quits.iter().any(|c| matches!(c, ViewportCommand::Close)), "{quits:?}"); + assert!(w.app.discard.is_none(), "no prompt opened"); +} + +#[test] +fn minimize_and_maximize_follow_the_window_state() { + let mut w = Win::new(1100.0); + w.frame(vec![]); + let (min, max) = (w.caption(Caption::Minimize).center(), w.caption(Caption::Maximize).center()); + assert!(w.click(min).contains(&ViewportCommand::Minimized(true))); + assert!(w.click(max).contains(&ViewportCommand::Maximized(true))); + w.maximized = true; + assert!(w.click(max).contains(&ViewportCommand::Maximized(false)), "Restore"); +} + +#[test] +fn empty_bar_space_drags_and_double_click_maximizes() { + let mut w = Win::new(1440.0); + w.frame(vec![]); + let empty = pos2(980.0, 16.0); + assert!(w.bar_widgets().iter().all(|r| !r.contains(empty)), "the probe point must be empty bar space"); + let cmds = w.gesture(&[empty, empty + vec2(12.0, 4.0), empty + vec2(30.0, 8.0)]); + assert_eq!(cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(), 1, "{cmds:?}"); + let mut cmds = w.click(empty); + cmds.extend(w.click(empty)); + assert!(cmds.contains(&ViewportCommand::Maximized(true)), "{cmds:?}"); + w.maximized = true; + w.time += 1.0; + let mut cmds = w.click(empty); + cmds.extend(w.click(empty)); + assert!(cmds.contains(&ViewportCommand::Maximized(false)), "{cmds:?}"); + // Widgets keep their clicks: dragging from a menu title doesn't move the window. + let file = texts(&w.frame(vec![])).into_iter().find(|(t, _)| t == "File").map(|(_, r)| r.center()); + let file = file.expect("the File menu title"); + let cmds = w.gesture(&[file, file + vec2(12.0, 4.0), file + vec2(30.0, 8.0)]); + assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}"); +} + +#[test] +fn empty_bar_space_still_drags_with_a_modal_open() { + let mut w = Win::new(1440.0); + w.frame(vec![]); + w.frame_with_modal(vec![], true); + let empty = pos2(980.0, 16.0); + let drag_area = w.ctx.data(|d| d.get_temp::(modal_drag_area_id())); + assert!(drag_area.is_some_and(|r| r.contains(empty)), "the test point must be in the current title-bar gap: {drag_area:?}"); + assert!(w.bar_widgets().iter().all(|r| !r.contains(empty)), "the probe point must be empty bar space"); + let cmds = w.gesture_with_modal(&[empty, empty + vec2(12.0, 4.0), empty + vec2(30.0, 8.0)], true); + assert_eq!(cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(), 1, "{cmds:?}"); +} + +#[test] +fn middle_button_drag_in_the_gap_does_not_start_a_window_drag() { + let mut w = Win::new(1440.0); + w.frame(vec![]); + let empty = pos2(980.0, 16.0); + let path = [empty, empty + vec2(12.0, 4.0), empty + vec2(30.0, 8.0)]; + let cmds = w.gesture_by(&path, false, egui::PointerButton::Middle); + assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}"); + // An ordinary left drag afterwards still moves the window. + let cmds = w.gesture(&path); + assert_eq!(cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(), 1, "{cmds:?}"); + // Same with a modal open (the overlay over the gap). + w.frame_with_modal(vec![], true); + let cmds = w.gesture_by(&path, true, egui::PointerButton::Middle); + assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}"); +} + +#[test] +fn modal_drag_overlay_does_not_cover_a_dialog_moved_into_the_gap() { + let mut w = Win::new(1440.0); + w.frame(vec![]); + w.frame_with_modal(vec![], true); + let area = w.ctx.data(|d| d.get_temp::(modal_drag_area_id())).unwrap_or(Rect::NOTHING); + assert!(area.contains(pos2(980.0, 16.0)), "the probe point must be in the gap: {area:?}"); + w.ctx.data_mut(|d| d.insert_temp(Id::unique("pc-dialog-rects"), vec![area])); + let cmds = w.gesture_with_modal(&[area.center(), area.center() + vec2(12.0, 4.0)], true); + assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}"); +} + +/// #1581: KDE Wayland keeps the button release of an OS resize. egui then kept the edge +/// pressed (no hover until the next click) and egui-winit never re-sent the resize cursor that +/// the compositor had replaced: the cursor came back only on every other press. +#[test] +fn after_an_os_resize_the_edge_hovers_and_shows_its_cursor_again() { + let mut w = Win::new(1000.0); + w.frame(vec![]); + let p = pos2(3.0, 300.0); + // Press and drag; the compositor takes over, so no release ever arrives. + let mut cmds = vec![]; + for e in [vec![Event::PointerMoved(p)], vec![button(p, true, egui::PointerButton::Primary)], vec![Event::PointerMoved(p + vec2(6.0, 0.0))]] { + cmds.extend(w.frame(e).viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default()); + } + assert!(cmds.contains(&ViewportCommand::BeginResize(ResizeDirection::West)), "{cmds:?}"); + w.frame(vec![]); + assert!(!w.ctx.input(|i| i.pointer.primary_down()), "the press ends with the hand-off"); + // The pointer comes back: one frame of the default cursor, so the next one is re-sent. + let out = w.frame(vec![Event::PointerMoved(p)]); + assert_eq!(out.platform_output.cursor_icon, CursorIcon::Default); + let out = w.frame(vec![Event::PointerMoved(p + vec2(1.0, 0.0))]); + assert_eq!(out.platform_output.cursor_icon, CursorIcon::ResizeWest); + // And the next press resizes again (it alternated before). + assert!(w.gesture(&[p, p + vec2(6.0, 0.0)]).contains(&ViewportCommand::BeginResize(ResizeDirection::West))); +} + +/// Where the OS does send the release of a resize (Windows), no second one is added: a +/// release right after it could count as a click on what lies under the edge. +#[test] +fn a_release_the_os_sends_is_not_doubled() { + let mut w = Win::new(1000.0); + w.frame(vec![]); + let p = pos2(3.0, 300.0); + w.frame(vec![Event::PointerMoved(p)]); + w.frame(vec![button(p, true, egui::PointerButton::Primary)]); + w.frame(vec![Event::PointerMoved(p + vec2(6.0, 0.0))]); + // The release arrives with the next input. + let mut raw = RawInput { events: vec![button(p + vec2(6.0, 0.0), false, egui::PointerButton::Primary)], ..Default::default() }; + release_after_os_resize(&w.ctx, &mut raw); + assert_eq!(raw.events.len(), 1, "{:?}", raw.events); + // Or it already arrived in an earlier input: egui has the button up, nothing to end. + let mut w = Win::new(1000.0); + w.frame(vec![]); + w.gesture(&[p, p + vec2(6.0, 0.0)]); + let mut raw = RawInput::default(); + release_after_os_resize(&w.ctx, &mut raw); + assert!(raw.events.is_empty(), "{:?}", raw.events); +} + +/// #5725: the window manager keeps the button release of an OS move just as of a resize, so +/// egui kept the drag: every other move of the window failed, and so did a resize right after one. +#[test] +fn after_an_os_move_the_bar_and_the_edges_take_the_next_press() { + /// Press and drag along `path`; the window manager takes over, so no release ever arrives. + fn handed_off(w: &mut Win, path: &[Pos2]) -> Vec { + let mut events = vec![vec![Event::PointerMoved(path[0])], vec![button(path[0], true, egui::PointerButton::Primary)]]; + events.extend(path[1..].iter().map(|p| vec![Event::PointerMoved(*p)])); + events.push(vec![]); + events.into_iter().flat_map(|e| w.frame(e).viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default()).collect() + } + let moves = |cmds: &[ViewportCommand]| cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(); + let mut w = Win::new(1440.0); + w.frame(vec![]); + let empty = pos2(980.0, 16.0); + assert!(w.bar_widgets().iter().all(|r| !r.contains(empty)), "the probe point must be empty bar space"); + let drag = [empty, empty + vec2(12.0, 4.0), empty + vec2(30.0, 8.0)]; + assert_eq!(moves(&handed_off(&mut w, &drag)), 1); + assert!(!w.ctx.input(|i| i.pointer.primary_down()), "the press ends with the hand-off"); + assert_eq!(moves(&w.gesture(&drag)), 1, "the next move"); + assert_eq!(moves(&handed_off(&mut w, &drag)), 1); + let edge = pos2(3.0, 300.0); + assert!(w.gesture(&[edge, edge + vec2(6.0, 0.0)]).contains(&ViewportCommand::BeginResize(ResizeDirection::West)), "a resize after a move"); +} + +#[test] +fn edge_zones_resize_unless_maximized() { + use ResizeDirection::*; + let mut w = Win::new(1000.0); + w.frame(vec![]); + for (p, dir) in [ + (pos2(1.0, 300.0), West), + (pos2(998.0, 300.0), East), + (pos2(500.0, 1.0), North), + (pos2(500.0, 598.0), South), + (pos2(2.0, 2.0), NorthWest), + (pos2(997.0, 3.0), NorthEast), + (pos2(3.0, 597.0), SouthWest), + (pos2(998.0, 598.0), SouthEast), + ] { + let cmds = w.gesture(&[p, p + vec2(6.0, 6.0)]); + assert_eq!(cmds, vec![ViewportCommand::BeginResize(dir)], "at {p:?}"); + } + // The first motion after those resizes shows the default cursor for a frame (see + // `reshow_cursor_after_os_resize`). + w.frame(vec![Event::PointerMoved(pos2(500.0, 300.0))]); + // One-sided cursors, which every cursor theme has (#1581), anywhere in the 8 pt edge. + for (p, cursor) in [ + (pos2(7.0, 300.0), CursorIcon::ResizeWest), + (pos2(993.0, 300.0), CursorIcon::ResizeEast), + (pos2(500.0, 7.0), CursorIcon::ResizeNorth), + (pos2(500.0, 593.0), CursorIcon::ResizeSouth), + (pos2(2.0, 2.0), CursorIcon::ResizeNwSe), + (pos2(997.0, 3.0), CursorIcon::ResizeNeSw), + (pos2(3.0, 597.0), CursorIcon::ResizeNeSw), + (pos2(998.0, 598.0), CursorIcon::ResizeNwSe), + ] { + let out = w.frame(vec![Event::PointerMoved(p)]); + assert_eq!(out.platform_output.cursor_icon, cursor, "at {p:?}"); + } + let cmds = w.gesture(&[pos2(7.0, 300.0), pos2(13.0, 306.0)]); + assert_eq!(cmds, vec![ViewportCommand::BeginResize(West)], "the edge zone is 8 pt deep"); + // Clear of the zone and of egui's interact radius around it. + let cmds = w.gesture(&[pos2(20.0, 300.0), pos2(26.0, 306.0)]); + assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::BeginResize(_))), "{cmds:?}"); + // Maximized: no zones, and the window's top-right corner is Close. + w.maximized = true; + let cmds = w.gesture(&[pos2(1.0, 300.0), pos2(8.0, 300.0)]); + assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::BeginResize(_))), "{cmds:?}"); + assert!(w.click(pos2(999.5, 0.5)).iter().any(|c| matches!(c, ViewportCommand::Close))); +} + +#[test] +fn gtk_layouts_pick_the_buttons_and_their_sides() { + use Caption::*; + let s = CaptionStyle::from_gtk_layout(CaptionFamily::Adwaita, "appmenu:minimize,maximize,close"); + assert_eq!((s.left, s.right), (vec![], vec![Minimize, Maximize, Close])); + // Unknown names are skipped, spaces trimmed, a repeat placed once, a second colon is a name. + let s = CaptionStyle::from_gtk_layout(CaptionFamily::Adwaita, "close,close , minimize:icon,maximize:close"); + assert_eq!((s.left, s.right), (vec![Close, Minimize], vec![])); + let s = CaptionStyle::from_gtk_layout(CaptionFamily::Breeze, "minimize,close"); + assert_eq!((s.left, s.right), (vec![Minimize, Close], vec![]), "no colon: GTK puts them all at the start"); + let s = CaptionStyle::from_gtk_layout(CaptionFamily::Breeze, ""); + assert!(s.left.is_empty() && s.right.is_empty()); + assert_eq!(CaptionFamily::parse(" Breeze "), Some(CaptionFamily::Breeze)); + assert_eq!(CaptionFamily::parse("aqua"), None); + assert_eq!(CaptionStyle::default(), CaptionStyle { family: CaptionFamily::Windows, left: vec![], right: CAPTIONS.to_vec(), icons: None }); +} + +#[test] +fn linux_buttons_sit_where_the_layout_says_and_drag_the_window() { + use Caption::*; + for (family, size, gap, end) in [(CaptionFamily::Adwaita, 24.0, 6.5, 10.0), (CaptionFamily::Breeze, 18.0, 4.5, 8.0)] { + let width = 1100.0; + let mut w = Win::new(width); + w.app.services.caption_style = Some(Box::new(move |_| CaptionStyle { family, left: vec![Close], right: vec![Minimize, Maximize], icons: None })); + w.frame(vec![]); + w.frame(vec![]); + let [min, max, close] = CAPTIONS.map(|c| w.caption(c)); + // Flush with the window's edges, the edge gap outermost, the hit areas touching. + assert_eq!((close.left(), close.width()), (0.0, end + size + gap), "{family:?}"); + assert_eq!((max.right(), max.width()), (width, gap + size + end), "{family:?}"); + assert_eq!((min.right(), min.width()), (max.left(), 2.0 * gap + size), "{family:?}"); + // GNOME's header bars are taller than Photoshop's bar; KDE's are not. + if family == CaptionFamily::Adwaita { + assert_eq!(close.height(), 46.0); + } else { + assert!((31.0..46.0).contains(&close.height()), "{close:?}"); + } + let mark = crate::brand::mark_rect(&w.ctx).expect("the brand mark is painted"); + assert!(mark.left() > close.right(), "the bar starts after the left buttons: {mark:?} {close:?}"); + for a in w.bar_widgets() { + assert!(a.left() >= close.right() && a.right() <= min.left(), "{a:?} runs into the caption buttons ({family:?})"); + } + assert!(w.click(max.center()).contains(&ViewportCommand::Maximized(true))); + assert!(w.click(close.center()).iter().any(|c| matches!(c, ViewportCommand::Close))); + // A drag that starts on a button moves the window instead of pressing it. + let at = min.center(); + let cmds = w.gesture(&[at, at + vec2(12.0, 4.0), at + vec2(30.0, 8.0)]); + assert_eq!(cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(), 1, "{cmds:?}"); + assert!(!cmds.contains(&ViewportCommand::Minimized(true)), "{cmds:?}"); + } +} + +/// A side without buttons reserves nothing; without the custom title bar, neither does any. +#[test] +fn only_sides_with_buttons_take_room() { + let mut w = Win::new(1000.0); + w.app.services.caption_style = Some(Box::new(|_| CaptionStyle::from_gtk_layout(CaptionFamily::Adwaita, "appmenu:close"))); + assert_eq!(reserved(&w.app, &w.ctx), (0.0, 6.5 + 24.0 + 10.0)); + w.app.custom_titlebar = false; + assert_eq!(reserved(&w.app, &w.ctx), (0.0, 0.0)); + w.app.custom_titlebar = true; + w.app.services.caption_style = None; + assert_eq!(reserved(&w.app, &w.ctx), (0.0, 3.0 * BUTTON_WIDTH)); +} + +/// Theme glyphs upload once per theme and size; an icon the theme lacks, a wrong-sized mask or +/// an absurd size gives `None`, so the button draws its own glyph. +#[test] +fn theme_icons_are_cached_and_fall_back() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let calls = std::sync::Arc::new(AtomicUsize::new(0)); + let counter = std::sync::Arc::clone(&calls); + let render = move |icon: CaptionIcon, px: u32| { + counter.fetch_add(1, Ordering::Relaxed); + match icon { + CaptionIcon::Close => Some(vec![255; (px * px) as usize]), + CaptionIcon::Minimize => Some(vec![255; 3]), + _ => None, + } + }; + let icons = CaptionIcons { theme: "Test".into(), render: std::sync::Arc::new(render) }; + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(RawInput::default(), |ui| { + let tex = theme_icon(ui.ctx(), &icons, CaptionIcon::Close, 16).expect("rendered"); + assert_eq!(tex.size(), [16, 16]); + assert!(theme_icon(ui.ctx(), &icons, CaptionIcon::Close, 16).is_some()); + assert!(theme_icon(ui.ctx(), &icons, CaptionIcon::Restore, 16).is_none()); + assert!(theme_icon(ui.ctx(), &icons, CaptionIcon::Restore, 16).is_none()); + assert!(theme_icon(ui.ctx(), &icons, CaptionIcon::Minimize, 16).is_none(), "a mask of the wrong size"); + assert!(theme_icon(ui.ctx(), &icons, CaptionIcon::Close, 0).is_none()); + assert!(theme_icon(ui.ctx(), &icons, CaptionIcon::Close, 100_000).is_none()); + }); + out.textures_delta.clear(); + assert_eq!(calls.load(Ordering::Relaxed), 3, "each icon and size rendered once; absurd sizes never"); +} From 1791e3ddb2bb02076f4508aca00962a26538db38 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:35 +0000 Subject: [PATCH 058/259] refactor(ui-egui): move crop_mode.rs tests to crop_mode/tests.rs --- crates/ui-egui/src/crop_mode.rs | 779 +------------------------- crates/ui-egui/src/crop_mode/tests.rs | 776 +++++++++++++++++++++++++ 2 files changed, 777 insertions(+), 778 deletions(-) create mode 100644 crates/ui-egui/src/crop_mode/tests.rs diff --git a/crates/ui-egui/src/crop_mode.rs b/crates/ui-egui/src/crop_mode.rs index 36bc4d659a..cc946b30b9 100644 --- a/crates/ui-egui/src/crop_mode.rs +++ b/crates/ui-egui/src/crop_mode.rs @@ -284,781 +284,4 @@ pub fn auto_center(app: &mut PhotocraftApp) { } #[cfg(test)] -mod tests { - use super::*; - use crate::canvas::{ToolEvent, tool_event}; - use crate::crop_ui::{CropDrag, corners}; - use egui::{Modifiers, Pos2, pos2}; - use photocraft_doc::{Color, ColorMode, Document, SampleType, Size}; - use serde_json::json; - - const NONE: Modifiers = Modifiers::NONE; - - /// A 200 × 100 document in a 800 × 600 canvas at 100 %, centred, the Crop tool in default mode. - fn app() -> PhotocraftApp { - let doc = Document::with_background("crop", Size::new(200, 100), 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.sync_views(); - app.ui.tool = Tool::Crop; - app.ui.extras.snap = false; - app.ui.extras.rulers = false; - app.ui.view.show.smart_guides = false; - app.last_canvas_rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); - let v = &mut app.ui.views[0]; - (v.zoom, v.center, v.fit_pending, v.rotation) = (1.0, [100.0, 50.0], false, 0.0); - assert!(!classic(&app), "Photoshop's default mode is the default"); - app - } - - fn xf(app: &PhotocraftApp) -> ViewXform { - ViewXform::active(app).unwrap() - } - - /// A drag through screen points, each mapped through the view as it is at that moment (as the - /// canvas does every frame). - fn screen_drag(app: &mut PhotocraftApp, pts: &[Pos2], mods: Modifiers) { - let at = |app: &PhotocraftApp, p: Pos2| xf(app).to_doc(p); - let d = at(app, pts[0]); - tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: 1.0 }, mods); - for p in &pts[1..] { - let d = at(app, *p); - tool_event(app, ToolEvent::Move { x: d[0], y: d[1], pressure: 1.0 }, mods); - } - let d = at(app, pts[pts.len() - 1]); - tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, mods); - } - - fn screen_box(app: &PhotocraftApp) -> [Pos2; 4] { - let x = xf(app); - corners(app.ui.crop_rect.unwrap(), crate::crop_ui::angle(app)).map(|p| x.to_screen(p[0] as f32, p[1] as f32)) - } - - fn assert_upright(q: [Pos2; 4]) { - let ok = (q[0].y - q[1].y).abs() < 0.01 && (q[2].y - q[3].y).abs() < 0.01 && (q[0].x - q[3].x).abs() < 0.01 && (q[1].x - q[2].x).abs() < 0.01; - assert!(ok && q[1].x > q[0].x && q[3].y > q[0].y, "not an upright box on screen: {q:?}"); - } - - fn close(a: [Pos2; 4], b: [Pos2; 4]) -> bool { - a.iter().zip(b).all(|(p, q)| p.distance(q) < 0.02) - } - - /// A real (not default) frame [40, 30, 100, 70], centred at (70, 50) = screen (370, 300). - fn with_frame(app: &mut PhotocraftApp) { - crate::crop_ui::ensure_frame(app); - app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]); - app.crop.default_frame = false; - } - - #[test] - fn a_live_resize_snaps_the_handle_without_feedback_from_the_camera() { - for (hx, hy) in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)] { - for alt in [false, true] { - for (zoom, ppp, flip, ratio) in [(1.0, 1.0, false, false), (0.5, 1.0, false, true), (3.0, 2.0, false, false), (3.0, 2.0, true, true)] { - let mut app = app(); - app.ppp = ppp; - app.ui.views[0].zoom = zoom; - app.ui.view.flip_horizontal = flip; - if ratio { - app.ui.tool_options.crop_ratio = "original".into(); - } - app.ui.extras.snap = true; - crate::crop_ui::ensure_frame(&mut app); - let box0 = screen_box(&app); - let c = mid_of(box0); - let from = xf(&app).to_screen(100.0 + hx as f32 * 100.0, 50.0 + hy as f32 * 50.0); - let direction = (from - c).normalized(); - let mods = if alt { Modifiers::ALT } else { NONE }; - let d = xf(&app).to_doc(from); - tool_event(&mut app, ToolEvent::Down { x: d[0], y: d[1], pressure: 1.0 }, mods); - // Leave the snap radius, then return just inside it. A still pointer must - // settle on the canvas edge instead of alternating on opposite sides of it. - for offset in [20.0, -2.0, -2.0, -2.0, -2.0, -2.0] { - let p = from + direction * offset; - let d = xf(&app).to_doc(p); - tool_event(&mut app, ToolEvent::Move { x: d[0], y: d[1], pressure: 1.0 }, mods); - if offset == -2.0 { - assert!(close(screen_box(&app), box0), "handle ({hx}, {hy}), Alt {alt}: {:?}", app.ui.crop_rect); - } - } - let d = xf(&app).to_doc(from + direction * -2.0); - tool_event(&mut app, ToolEvent::Up { x: d[0], y: d[1] }, mods); - assert!(close(screen_box(&app), box0), "release: {:?}", app.ui.crop_rect); - } - } - } - } - - #[test] - fn dragging_outside_turns_the_image_and_the_box_stays_upright() { - let mut app = app(); - with_frame(&mut app); - let before = screen_box(&app); - // From straight right of the box centre to straight below it: a quarter turn clockwise - // on screen, so the image turns clockwise and the frame turns -90° on it. - screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(440.0, 320.0), pos2(370.0, 380.0)], NONE); - assert!((crate::crop_ui::angle(&app) - -90.0).abs() < 0.01, "{}", app.ui.crop_angle); - assert!((view_rotation(&app) - 90.0).abs() < 0.01, "the view turned with it"); - assert_upright(screen_box(&app)); - assert!(close(screen_box(&app), before), "the box doesn't move on screen: {:?} vs {before:?}", screen_box(&app)); - assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0]), "turning keeps the frame"); - // ⇧ steps of 15°, still upright. - let a = 22.0f32.to_radians(); - screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(370.0 + 80.0 * a.cos(), 300.0 + 80.0 * a.sin())], Modifiers::SHIFT); - assert!((crate::crop_ui::angle(&app) - -105.0).abs() < 0.01, "{}", app.ui.crop_angle); - assert_upright(screen_box(&app)); - assert!(close(screen_box(&app), before)); - assert!(crate::crop_ui::turning(&app).is_none()); - } - - /// Even with Auto Center Preview, a drag inside an off-centre box (after a pan, say) leaves the - /// box where it is on screen: only the image moves (Photoshop 25.1). - #[test] - fn a_move_never_recentres_the_box() { - let mut app = app(); - assert!(app.ui.tool_options.crop_shield.auto_center_preview); - with_frame(&mut app); - assert!(mid_of(screen_box(&app)).distance(pos2(370.0, 300.0)) < 0.01); - screen_drag(&mut app, &[pos2(370.0, 300.0), pos2(380.0, 300.0), pos2(390.0, 300.0)], NONE); - assert!(mid_of(screen_box(&app)).distance(pos2(370.0, 300.0)) < 0.01, "{:?}", mid_of(screen_box(&app))); - let r = app.ui.crop_rect.unwrap(); - assert!(r.iter().zip([20.0, 30.0, 80.0, 70.0]).all(|(a, b)| (a - b).abs() < 1e-3), "{r:?}"); - } - - /// Moves the image under the box from document point `from` by `d` (both in the view at the - /// press), checks the snap lines before release, and returns where the box's centre started - /// on screen. - fn image_drag(app: &mut PhotocraftApp, from: [f32; 2], d: [f32; 2], line: Option<(bool, f64)>) -> Pos2 { - let (a, b) = (xf(app).to_screen(from[0], from[1]), xf(app).to_screen(from[0] + d[0], from[1] + d[1])); - let mid = mid_of(screen_box(app)); - let p = xf(app).to_doc(a); - tool_event(app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, NONE); - assert_eq!(app.prefs_rt.snap.as_ref().map(|s| &s.gesture), Some(&crate::snap_ui::Gesture::CropImage)); - for t in [0.5, 1.0] { - let p = xf(app).to_doc(a + (b - a) * t); - tool_event(app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }, NONE); - } - if let Some((vertical, pos)) = line { - assert!(app.prefs_rt.snap_lines.iter().any(|l| l.vertical == vertical && l.pos == pos), "{:?}", app.prefs_rt.snap_lines); - } - let p = xf(app).to_doc(b); - tool_event(app, ToolEvent::Up { x: p[0], y: p[1] }, NONE); - mid - } - - fn assert_frame(app: &PhotocraftApp, want: [f64; 4], what: &str) { - let r = app.ui.crop_rect.unwrap(); - assert!(r.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-3), "{what}: {r:?}, want {want:?}"); - } - - /// #8580: moving the image under the box snaps the frame's edges and centre with View › Snap - /// on, so the content can be centred in it without leaving the Crop tool. The box stays put. - #[test] - fn moving_the_image_snaps_the_frame_to_the_document_centre() { - for (snap, zoom, flip) in [(false, 1.0, false), (true, 1.0, false), (true, 2.0, false), (true, 1.0, true)] { - let mut app = app(); - app.ui.extras.snap = snap; - app.ui.views[0].zoom = zoom; - app.ui.view.flip_horizontal = flip; - with_frame(&mut app); - // The frame [40, 30, 100, 70] goes 27 px right over the image: its centre lands 3 px - // short of the document's (100, 50), inside the snap radius at either zoom. - let mid = image_drag(&mut app, [70.0, 50.0], [-27.0, 0.0], snap.then_some((true, 100.0))); - let what = format!("snap {snap}, zoom {zoom}, flip {flip}"); - assert_frame(&app, if snap { [70.0, 30.0, 130.0, 70.0] } else { [67.0, 30.0, 127.0, 70.0] }, &what); - assert!(mid_of(screen_box(&app)).distance(mid) < 0.01, "{what}: the box moved on screen"); - assert!(app.prefs_rt.snap.is_none() && app.prefs_rt.snap_lines.is_empty()); - } - } - - /// The issue's case: a box larger than the canvas (to extend it) centres on the content's - /// layer, both ways. A turned box doesn't snap (its edges don't line up with anything). - #[test] - fn moving_the_image_centres_a_larger_box_on_a_layer() { - let mut app = app(); - app.ui.extras.snap = true; - app.run("layer.new.layer", json!({"name": "logo"})).unwrap(); - app.run("select.rect", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.run("select.deselect", json!({})).unwrap(); - crate::crop_ui::ensure_frame(&mut app); - app.ui.crop_rect = Some([-40.0, -60.0, 140.0, 120.0]); - app.crop.default_frame = false; - // Its centre (50, 30) goes to (42, 38): 2 px from the logo's centre (40, 40). - image_drag(&mut app, [50.0, 30.0], [8.0, -8.0], Some((false, 40.0))); - assert_frame(&app, [-50.0, -50.0, 130.0, 130.0], "centred on the logo"); - - app.ui.crop_angle = 30.0; - sync(&mut app, None); - let p = xf(&app).to_doc(mid_of(screen_box(&app))); - tool_event(&mut app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, NONE); - assert!(matches!(app.crop.drag, Some(CropDrag::MoveImage { .. }))); - assert!(app.prefs_rt.snap.is_none(), "a turned box doesn't snap"); - tool_event(&mut app, ToolEvent::Up { x: p[0], y: p[1] }, NONE); - } - - /// With View › Snap To › Layers off, smart guides still centre the box on a layer, although - /// the document's bounds are snap targets that aren't within reach. - #[test] - fn moving_the_image_snaps_to_smart_guides_beside_out_of_reach_targets() { - for smart in [false, true] { - let mut app = app(); - app.ui.extras.snap = true; - app.ui.view.snap_to.layers = false; - app.ui.view.show.smart_guides = smart; - app.run("layer.new.layer", json!({"name": "logo"})).unwrap(); - app.run("select.rect", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.run("select.deselect", json!({})).unwrap(); - crate::crop_ui::ensure_frame(&mut app); - app.ui.crop_rect = Some([-40.0, -60.0, 140.0, 120.0]); - app.crop.default_frame = false; - image_drag(&mut app, [50.0, 30.0], [8.0, -8.0], smart.then_some((false, 40.0))); - let want = if smart { [-50.0, -50.0, 130.0, 130.0] } else { [-48.0, -52.0, 132.0, 128.0] }; - assert_frame(&app, want, &format!("smart guides {smart}")); - } - } - - /// #7088: the box's own Undo/Redo of a move (or a turn) in default mode puts the frame back - /// and moves the image, not the box: it stays put on screen (Auto Center Preview off) or goes - /// to the middle of the canvas (on). - #[test] - fn box_undo_and_redo_keep_the_box_put() { - for auto in [false, true] { - let mut app = app(); - app.ui.tool_options.crop_shield.auto_center_preview = auto; - with_frame(&mut app); - // A quarter turn, then a move inside: two box steps. - screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(370.0, 380.0)], NONE); - let turned = app.ui.crop_rect; - screen_drag(&mut app, &[pos2(370.0, 300.0), pos2(380.0, 305.0), pos2(390.0, 310.0)], NONE); - let moved = app.ui.crop_rect; - assert_ne!(moved, turned); - let want = if auto { pos2(400.0, 300.0) } else { pos2(370.0, 300.0) }; - let check = |app: &PhotocraftApp, what: &str| { - let q = screen_box(app); - assert_upright(q); - assert!(mid_of(q).distance(want) < 0.05, "auto={auto} {what}: the box moved on screen to {:?}", mid_of(q)); - }; - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(app.ui.crop_rect, turned, "auto={auto}: the move is undone"); - check(&app, "undo move"); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0])); - assert!(crate::crop_ui::angle(&app).abs() < 1e-9, "the turn is undone"); - check(&app, "undo turn"); - app.run("edit.redo", json!({})).unwrap(); - check(&app, "redo turn"); - app.run("edit.redo", json!({})).unwrap(); - assert_eq!(app.ui.crop_rect, moved, "auto={auto}: the move is redone"); - check(&app, "redo move"); - } - } - - fn mid_of(q: [Pos2; 4]) -> Pos2 { - pos2((q[0].x + q[2].x) / 2.0, (q[0].y + q[2].y) / 2.0) - } - - #[test] - fn dragging_inside_moves_the_image_under_the_box() { - let mut app = app(); - with_frame(&mut app); - let before = screen_box(&app); - screen_drag(&mut app, &[pos2(370.0, 300.0), pos2(380.0, 305.0), pos2(390.0, 310.0)], NONE); - // The image followed the pointer 20, 10 to the right and down: the frame lies that much - // further up-left on it. - let r = app.ui.crop_rect.unwrap(); - assert!(r.iter().zip([20.0, 20.0, 80.0, 60.0]).all(|(a, b)| (a - b).abs() < 1e-3), "{r:?}"); - assert!(close(screen_box(&app), before), "the box stays put on screen"); - // Turned 30° first: the move follows the pointer on screen, along the turned image. - screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(370.0 + 80.0 * 30f32.to_radians().cos(), 300.0 + 80.0 * 30f32.to_radians().sin())], NONE); - assert!((crate::crop_ui::angle(&app) - -30.0).abs() < 0.01); - let (before, c0) = (screen_box(&app), crate::crop_ui::center(app.ui.crop_rect.unwrap())); - let img = |app: &PhotocraftApp| xf(app).to_screen(0.0, 0.0); - let origin = img(&app); - screen_drag(&mut app, &[pos2(370.0, 300.0), pos2(400.0, 300.0)], NONE); - assert!(close(screen_box(&app), before), "box put"); - assert!((img(&app) - origin - vec2(30.0, 0.0)).length() < 0.05, "the image moved 30 right on screen"); - let c1 = crate::crop_ui::center(app.ui.crop_rect.unwrap()); - assert!(((c1[0] - c0[0]).hypot(c1[1] - c0[1]) - 30.0).abs() < 1e-3); - } - - /// A `ui.pointer` click (down and up at the same point, no move) changes nothing, upright or - /// turned: reading the point in the press view used to round it through `f32` and the view, - /// nudging the frame by a hair and pushing a box Undo step that undid nothing visible. - #[test] - fn a_ui_pointer_click_changes_nothing() { - let ctx = egui::Context::default(); - for deg in [0.0, -30.0, 41.5] { - let mut app = app(); - with_frame(&mut app); - app.ui.crop_angle = deg; - sync_frame(&mut app); - let (rect, angle) = (app.ui.crop_rect, app.ui.crop_angle); - // Inside the frame (moves the image) and outside it (turns the image). - for p in [[70.3, 50.7], [55.17, 41.9], [83.01, 59.33], [150.3, 50.7], [10.9, 90.1]] { - let ev = json!([{"kind": "down", "x": p[0], "y": p[1]}, {"kind": "up", "x": p[0], "y": p[1]}]); - let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"events": ev})); - let crate::control::Outcome::Done(v) = crate::control::handle(&mut app, &ctx, &req) else { panic!("ui.pointer didn't finish") }; - assert_eq!(v["ok"], true, "{v}"); - assert_eq!((app.ui.crop_rect, app.ui.crop_angle), (rect, angle), "click at {p:?}, frame at {deg}°"); - assert_eq!(crate::crop_ui::is_enabled(&app, "edit.undo"), None, "click at {p:?}, frame at {deg}°: a box Undo step"); - } - } - } - - #[test] - fn the_readout_is_the_images_turn_clockwise_positive() { - let mut app = app(); - with_frame(&mut app); - // A 30° clockwise sweep on screen, held mid-drag. - let d = |app: &PhotocraftApp, p: Pos2| xf(app).to_doc(p); - let a = 30f32.to_radians(); - let (p0, p1) = (pos2(450.0, 300.0), pos2(370.0 + 80.0 * a.cos(), 300.0 + 80.0 * a.sin())); - let s = d(&app, p0); - tool_event(&mut app, ToolEvent::Down { x: s[0], y: s[1], pressure: 1.0 }, NONE); - let m = d(&app, p1); - tool_event(&mut app, ToolEvent::Move { x: m[0], y: m[1], pressure: 1.0 }, NONE); - let shown = crate::crop_ui::turning(&app).unwrap(); - assert!((shown - 30.0).abs() < 0.01, "clockwise is positive: {shown}"); - assert!((crate::crop_ui::angle(&app) - -30.0).abs() < 0.01, "the frame turns the other way on the image"); - let m = d(&app, p1); - tool_event(&mut app, ToolEvent::Up { x: m[0], y: m[1] }, NONE); - assert_eq!(image_turn(0.0).to_string(), "0", "never -0"); - // Classic Mode shows the frame's own turn, clockwise positive as before. - let mut app = self::app(); - app.ui.tool_options.crop_shield.classic_mode = true; - with_frame(&mut app); - let s = d(&app, p0); - tool_event(&mut app, ToolEvent::Down { x: s[0], y: s[1], pressure: 1.0 }, NONE); - let m = d(&app, p1); - tool_event(&mut app, ToolEvent::Move { x: m[0], y: m[1], pressure: 1.0 }, NONE); - assert!((crate::crop_ui::turning(&app).unwrap() - 30.0).abs() < 0.01); - } - - #[test] - fn auto_center_keeps_the_box_centred_while_a_handle_is_dragged() { - for auto in [true, false] { - let mut app = app(); - app.ui.tool_options.crop_shield.auto_center_preview = auto; - with_frame(&mut app); - // Turn 90° clockwise on screen first: the frame is at -90° in the image. - screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(370.0, 380.0)], NONE); - let q = screen_box(&app); - assert_upright(q); - let mid = |q: [Pos2; 4]| pos2((q[0].x + q[2].x) / 2.0, (q[0].y + q[2].y) / 2.0); - // The box's right edge on screen, dragged 10 then 20 further right. - let right = pos2(q[1].x, (q[1].y + q[2].y) / 2.0); - assert_eq!(crate::crop_ui::cursor(&app, xf(&app).to_doc(right)), Some(egui::CursorIcon::ResizeHorizontal), "screen-space arrow"); - let at = |app: &PhotocraftApp, p: Pos2| xf(app).to_doc(p); - let s = at(&app, right); - tool_event(&mut app, ToolEvent::Down { x: s[0], y: s[1], pressure: 1.0 }, NONE); - for dx in [10.0, 20.0] { - let m = at(&app, right + vec2(dx, 0.0)); - tool_event(&mut app, ToolEvent::Move { x: m[0], y: m[1], pressure: 1.0 }, NONE); - let n = screen_box(&app); - assert_upright(n); - assert!((n[1].x - (right.x + dx)).abs() < 0.02, "auto={auto} dx={dx}: the handle follows the pointer: {n:?}"); - if auto { - assert!(mid(n).distance(mid(q)) < 0.02, "dx={dx}: live, the box stays centred: {:?} vs {:?}", mid(n), mid(q)); - assert!(((n[1].x - n[0].x) - (q[1].x - q[0].x) - 2.0 * dx).abs() < 0.02, "it grows on both sides"); - } else { - assert!((n[0].x - q[0].x).abs() < 0.02, "the left edge stays put"); - } - assert!(((n[3].y - n[0].y) - (q[3].y - q[0].y)).abs() < 0.02); - } - let m = at(&app, right + vec2(20.0, 0.0)); - tool_event(&mut app, ToolEvent::Up { x: m[0], y: m[1] }, NONE); - let n = screen_box(&app); - if auto { - assert!(mid(n).distance(mid(q)) < 0.05, "on release it stays where its centre was: {:?} vs {:?}", mid(n), mid(q)); - // On the image, the opposite edge stayed put: the frame grew 40 px from it. - let r = app.ui.crop_rect.unwrap(); - assert!(((r[2] - r[0]) - 100.0).abs() < 1e-3 && ((r[3] - r[1]) - 40.0).abs() < 1e-3, "{r:?}"); - let left = corners(r, crate::crop_ui::angle(&app))[0]; - let was = corners([40.0, 30.0, 100.0, 70.0], -90.0)[0]; - assert!((left[0] - was[0]).abs() < 1e-3 && (left[1] - was[1]).abs() < 1e-3, "{left:?} vs {was:?}"); - } else { - assert!(mid(n).distance(pos2(380.0, 300.0)) < 0.05, "{:?}", mid(n)); - } - } - // ⌥: about the centre, and a collapsed drag puts frame and view back. - let mut app = app(); - with_frame(&mut app); - let q = screen_box(&app); - let center = app.ui.views[0].center; - let right = pos2(q[1].x, (q[1].y + q[2].y) / 2.0); - screen_drag(&mut app, &[right, right + vec2(10.0, 0.0)], Modifiers::ALT); - let r = app.ui.crop_rect.unwrap(); - assert!(((r[0] + r[2]) / 2.0 - 70.0).abs() < 1e-3 && ((r[2] - r[0]) - 80.0).abs() < 1e-3, "{r:?}"); - let mut app = self::app(); - with_frame(&mut app); - screen_drag(&mut app, &[right, pos2(370.0, 300.0)], NONE); - assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0]), "too small: the frame is back"); - assert_eq!(app.ui.views[0].center, center, "and the view"); - } - - /// The same frame and angle commit the same crop in both modes, and in both the view stays - /// upright after a commit or a cancel (Photoshop 25.1 doesn't restore a Rotate View turn). - #[test] - fn commit_is_the_same_in_both_modes_and_the_view_stays_upright() { - let mut out = Vec::new(); - for classic in [true, false] { - let mut app = app(); - app.run("select.rect", json!({"x": 70, "y": 50, "width": 2, "height": 2})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.run("select.deselect", json!({})).unwrap(); - app.ui.tool_options.crop_shield.classic_mode = classic; - app.ui.views[0].rotation = 20.0; - with_frame(&mut app); - app.ui.crop_angle = 30.0; - app.crop.editing = true; - crate::crop_ui::ensure_frame(&mut app); - let want = if classic { 0.0 } else { -30.0 }; - assert!((view_rotation(&app) - want).abs() < 1e-4, "classic={classic}: {}", view_rotation(&app)); - if !classic { - assert_upright(screen_box(&app)); - } - let past = app.session.active().unwrap().history.past_len(); - crate::canvas::commit_crop(&mut app); - assert_eq!(view_rotation(&app), 0.0, "classic={classic}: after ↵"); - crate::crop_ui::ensure_frame(&mut app); - assert_eq!(view_rotation(&app), 0.0, "classic={classic}: with the next frame"); - let st = app.session.active().unwrap(); - assert_eq!(st.history.past_len(), past + 1, "one undo step"); - let surf = st.doc.layers[0].surface().unwrap(); - let px: Vec<[f32; 4]> = - (0..st.doc.size.width as i32).flat_map(|x| (0..st.doc.size.height as i32).map(move |y| (x, y))).map(|(x, y)| surf.rgba(x, y)).collect(); - out.push((st.doc.size, px)); - // Esc. - let mut app = self::app(); - app.ui.tool_options.crop_shield.classic_mode = classic; - app.ui.views[0].rotation = -45.0; - with_frame(&mut app); - screen_drag(&mut app, &[pos2(500.0, 300.0), pos2(370.0, 420.0)], NONE); - crate::crop_ui::cancel(&mut app); - crate::crop_ui::ensure_frame(&mut app); - assert_eq!(view_rotation(&app), 0.0, "classic={classic}: Esc"); - } - assert_eq!(out[0].0, out[1].0, "same size"); - assert!(out[0].1 == out[1].1, "same pixels"); - } - - #[test] - fn picking_the_crop_tool_turns_a_rotated_view_upright() { - let mut app = app(); - app.ui.tool = Tool::Brush; - app.ui.views[0].rotation = 30.0; - let center = app.ui.views[0].center; - app.ui.tool = Tool::Crop; - crate::crop_ui::ensure_frame(&mut app); - assert!(app.crop.default_frame && !app.crop.editing, "no click needed"); - assert_eq!(view_rotation(&app), 0.0); - assert_eq!(app.ui.views[0].center, center, "about the view's centre"); - // Leaving the tool doesn't bring the turn back. - app.ui.tool = Tool::Brush; - crate::crop_ui::ensure_frame(&mut app); - assert_eq!(view_rotation(&app), 0.0); - // Classic Mode too (Photoshop 25.1): the camera goes upright about the view's centre and - // the frame stays on the same image area, keeping its own turn. - let mut app = self::app(); - app.ui.tool_options.crop_shield.classic_mode = true; - app.ui.tool = Tool::Brush; - app.ui.views[0].rotation = 30.0; - app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]); - app.ui.crop_angle = 12.0; - app.ui.tool = Tool::Crop; - crate::crop_ui::ensure_frame(&mut app); - assert_eq!(view_rotation(&app), 0.0); - assert_eq!(app.ui.views[0].center, center, "about the view's centre"); - assert_eq!((app.ui.crop_rect, app.ui.crop_angle), (Some([40.0, 30.0, 100.0, 70.0]), 12.0), "the frame is unchanged"); - // P switches modes without bringing the R turn back: default mode turns the view with the - // frame, Classic Mode puts the camera upright again. - let press_p = |app: &mut PhotocraftApp| { - let ctx = egui::Context::default(); - ctx.input_mut(|i| i.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: NONE })); - assert!(crate::crop_shield::keys(app, &ctx)); - }; - press_p(&mut app); - assert!(!classic(&app)); - assert!((view_rotation(&app) - -12.0).abs() < 1e-4, "{}", view_rotation(&app)); - press_p(&mut app); - assert!(classic(&app)); - assert_eq!(view_rotation(&app), 0.0); - crate::crop_ui::cancel(&mut app); - crate::crop_ui::ensure_frame(&mut app); - assert_eq!(view_rotation(&app), 0.0, "Esc in Classic Mode: still upright"); - } - - fn key(app: &mut PhotocraftApp, key: egui::Key, modifiers: Modifiers) { - let ctx = egui::Context::default(); - ctx.input_mut(|i| i.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers })); - crate::shortcuts::handle(app, &ctx); - } - - #[test] - fn arrows_nudge_the_image_shift_by_ten_and_x_recentres() { - let mut app = app(); - with_frame(&mut app); - app.crop.editing = true; - app.ui.crop_angle = -90.0; - crate::crop_ui::ensure_frame(&mut app); - let before = screen_box(&app); - let img = |app: &PhotocraftApp| xf(app).to_screen(0.0, 0.0); - let origin = img(&app); - key(&mut app, egui::Key::ArrowRight, NONE); - assert!(close(screen_box(&app), before), "the box stays put"); - assert!((img(&app) - origin - vec2(1.0, 0.0)).length() < 0.02, "the image moved 1 px right on screen"); - key(&mut app, egui::Key::ArrowDown, Modifiers::SHIFT); - assert!((img(&app) - origin - vec2(1.0, 10.0)).length() < 0.02, "⇧: 10 px"); - assert!(close(screen_box(&app), before)); - assert!(crate::crop_ui::swap_orientation(&mut app)); - assert_upright(screen_box(&app)); - let q = screen_box(&app); - assert!(pos2((q[0].x + q[2].x) / 2.0, (q[0].y + q[2].y) / 2.0).distance(pos2(400.0, 300.0)) < 0.05, "Auto Center Preview"); - } - - /// Photoshop 25.1 greys out Show Cropped Area and Auto Center Preview in Classic Mode. Show - /// Cropped Area then acts as on (an assumption) and H does nothing; the stored choice stays. - #[test] - fn classic_mode_shows_the_cropped_area_and_h_does_nothing() { - let mut app = app(); - crate::crop_ui::ensure_frame(&mut app); - app.ui.tool_options.crop_shield.show_cropped_area = false; - assert!(crate::crop_shield::hides_outside(&app)); - app.ui.tool_options.crop_shield.classic_mode = true; - assert!(!crate::crop_shield::hides_outside(&app)); - let canvas = egui::Color32::from_rgb(40, 40, 40); - assert_ne!(crate::crop_shield::fill(&app.ui.tool_options.crop_shield, canvas, false), Some(canvas), "the shield, not the opaque canvas"); - key(&mut app, egui::Key::H, NONE); - assert_eq!(app.ui.tool, Tool::Crop, "H is taken, not the Hand tool"); - assert!(!app.ui.tool_options.crop_shield.show_cropped_area, "and changes nothing"); - app.ui.tool_options.crop_shield.classic_mode = false; - assert!(crate::crop_shield::hides_outside(&app), "the stored choice is back"); - key(&mut app, egui::Key::H, NONE); - assert!(app.ui.tool_options.crop_shield.show_cropped_area); - } - - #[test] - fn p_toggles_classic_mode_while_the_crop_tool_shows_a_box() { - let mut app = app(); - crate::crop_ui::ensure_frame(&mut app); - let press = |app: &mut PhotocraftApp| { - let ctx = egui::Context::default(); - ctx.input_mut(|i| i.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: NONE })); - crate::shortcuts::handle(app, &ctx); - }; - press(&mut app); - assert!(classic(&app) && app.ui.tool == Tool::Crop, "P doesn't pick the Pen tool"); - press(&mut app); - assert!(!classic(&app)); - // Mid-drag P is left alone; without a box P is the Pen key. - app.crop.drag = Some(CropDrag::Move { start: [0.0, 0.0], rect: [0.0, 0.0, 10.0, 10.0] }); - let ctx = egui::Context::default(); - ctx.input_mut(|i| i.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: NONE })); - assert!(!crate::crop_shield::keys(&mut app, &ctx)); - assert!(!classic(&app)); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.ui.tool = Tool::Crop; - press(&mut app); - assert_ne!(app.ui.tool, Tool::Crop); - assert!(!classic(&app)); - } - - #[test] - fn straighten_turns_the_image_so_the_line_is_level_on_screen() { - let mut app = app(); - crate::crop_ui::ensure_frame(&mut app); - crate::crop_straighten::toggle(&mut app); - // A horizon falling to the right, drawn on screen. - let (a, b) = (pos2(320.0, 290.0), pos2(480.0, 310.0)); - let (da, db) = (xf(&app).to_doc(a), xf(&app).to_doc(b)); - screen_drag(&mut app, &[a, b], NONE); - assert!(crate::crop_ui::angle(&app) > 5.0, "{}", app.ui.crop_angle); - let (sa, sb) = (xf(&app).to_screen(da[0] as f32, da[1] as f32), xf(&app).to_screen(db[0] as f32, db[1] as f32)); - assert!((sa.y - sb.y).abs() < 0.01, "the line is level: {sa:?} {sb:?}"); - assert_upright(screen_box(&app)); - } - - /// `ui.pointer` points are read in the view at the press, so an `up` where the last `move` was - /// doesn't move or turn the image a second time. - #[test] - fn ui_pointer_drives_the_default_mode_in_press_coordinates() { - let mut app = app(); - app.ui.tool_options.crop_shield.auto_center_preview = false; - with_frame(&mut app); - let ctx = egui::Context::default(); - let pointer = |app: &mut PhotocraftApp, pts: [[f64; 2]; 2]| { - let ev = json!([ - {"kind": "down", "x": pts[0][0], "y": pts[0][1]}, - {"kind": "move", "x": pts[1][0], "y": pts[1][1]}, - {"kind": "up", "x": pts[1][0], "y": pts[1][1]}, - ]); - let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"events": ev})); - let crate::control::Outcome::Done(v) = crate::control::handle(app, &ctx, &req) else { panic!("ui.pointer didn't finish") }; - assert_eq!(v["ok"], true, "{v}"); - }; - pointer(&mut app, [[70.0, 50.0], [80.0, 55.0]]); - let r = app.ui.crop_rect.unwrap(); - assert!(r.iter().zip([30.0, 25.0, 90.0, 65.0]).all(|(a, b)| (a - b).abs() < 1e-3), "{r:?}"); - assert!((app.ui.views[0].center[0] - 90.0).abs() < 1e-3 && (app.ui.views[0].center[1] - 45.0).abs() < 1e-3); - // Outside: from right of the centre (60, 45) to below it, a quarter turn of the image. - pointer(&mut app, [[140.0, 45.0], [60.0, 125.0]]); - assert!((crate::crop_ui::angle(&app) - -90.0).abs() < 0.01, "{}", app.ui.crop_angle); - assert_upright(screen_box(&app)); - } - - #[test] - fn degenerate_input_never_panics() { - let mut app = app(); - for frame in - [[0.0, 0.0, 0.0, 0.0], [5.0, 5.0, 5.0, 5.0], [f64::NAN, 0.0, 10.0, 10.0], [f64::INFINITY, 0.0, 1e300, 1e300], [-1e300, -1e300, 1e300, 1e300]] - { - for angle in [0.0, f64::NAN, f64::INFINITY, 1e300, -720.5] { - app.ui.crop_rect = Some(frame); - app.ui.crop_angle = angle; - app.crop.default_frame = false; - app.crop.editing = true; - crate::crop_ui::ensure_frame(&mut app); - for p in [pos2(400.0, 300.0), pos2(10.0, 10.0), pos2(f32::NAN, 3.0), pos2(1e30, -1e30)] { - screen_drag(&mut app, &[p, p + vec2(15.0, 7.0)], NONE); - screen_drag(&mut app, &[p, p + vec2(15.0, 7.0)], Modifiers::SHIFT | Modifiers::ALT); - } - crate::crop_ui::nudge(&mut app, f64::NAN, 1.0); - crate::crop_ui::nudge(&mut app, 1.0, 1.0); - crate::crop_ui::swap_orientation(&mut app); - auto_center(&mut app); - shift_image(&mut app, [f64::NAN, f64::INFINITY]); - let press = PressView { rotation: f32::NAN, center: [f32::INFINITY, 0.0] }; - let g = LiveResize { rect: frame, deg: angle, hx: 1, hy: -1, start: [0.0, f64::NAN], q: [1e300, -1e300], ratio: Some(f64::NAN), alt: false }; - live_resize(&mut app, g, press); - assert!(app.ui.crop_rect.is_none_or(|r| r.iter().all(|v| v.is_finite()) || r == frame), "{frame:?} {angle}"); - let v = &app.ui.views[0]; - assert!(v.rotation.is_finite() && v.center.iter().all(|c| c.is_finite()), "{frame:?} {angle}: {v:?}"); - crate::crop_ui::cancel(&mut app); - } - } - assert_eq!(pivot_center([1.0, 2.0], [f64::NAN, 0.0], 0.0, 90.0, false), [1.0, 2.0]); - assert_eq!(pivot_center([1.0, 2.0], [0.0, 0.0], f32::NAN, 90.0, true), [1.0, 2.0]); - // No view at all (no document). - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.ui.tool = Tool::Crop; - app.ui.crop_rect = Some([0.0, 0.0, 10.0, 10.0]); - app.crop.editing = true; - sync(&mut app, None); - auto_center(&mut app); - shift_image(&mut app, [1.0, 1.0]); - upright(&mut app); - } - - #[test] - fn the_options_default_to_photoshops_and_older_settings_load() { - let s = crate::crop_shield::CropShield::default(); - assert!(!s.classic_mode && s.auto_center_preview); - let s: crate::crop_shield::CropShield = serde_json::from_str(r#"{"enabled": false}"#).unwrap(); - assert!(!s.classic_mode && s.auto_center_preview); - let s: crate::crop_shield::CropShield = serde_json::from_str(r#"{"classic_mode": true, "auto_center_preview": false}"#).unwrap(); - assert!(s.classic_mode && !s.auto_center_preview); - } - - #[test] - fn pivoting_keeps_the_point_on_screen() { - for flip in [false, true] { - for (from, to) in [(0.0, 30.0), (45.0, -90.0), (170.0, -170.0)] { - let center = [100.0f32, 50.0]; - let c = [70.0, 20.0]; - let a = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), zoom: 2.0, center, flip, rotation: from, aspect: 1.0 }; - let n = pivot_center(center, c, from, to, flip); - let b = ViewXform { center: n, rotation: to, ..a }; - let (p, q) = (a.to_screen(70.0, 20.0), b.to_screen(70.0, 20.0)); - assert!(p.distance(q) < 0.01, "{flip} {from} {to}: {p:?} vs {q:?}"); - } - } - } - - /// #1919: with Delete Cropped Pixels off, a second crop's handle dragged out toward the hidden - /// pixels snaps exactly onto their edge (a layer edge), however far from the handle's centre - /// the press grabbed it, in both modes, with and without Auto Center Preview: the committed - /// crop has no transparent strip. - #[test] - fn a_recrop_handle_snaps_exactly_to_the_hidden_pixels_edge() { - // The image 200 × 100 cropped to [40, 20, 140, 70]: its pixels stay at [-40, -20, 160, 80]. - let hidden = [-40.0, -20.0, 160.0, 80.0]; - for classic in [false, true] { - for auto in [true, false] { - for (hx, hy) in [(1i8, 0i8), (0, -1), (-1, -1), (1, 1)] { - // A corner also with the image's 2:1 ratio held, which both hidden corners keep. - for (grab, ratio) in [(-4.0f32, false), (0.0, false), (4.0, false), (-4.0, true), (4.0, true)] { - if ratio && (hx == 0 || hy == 0) { - continue; - } - let what = format!("Classic Mode {classic}, Auto Center {auto}, handle ({hx}, {hy}), grabbed {grab} px off, ratio {ratio}"); - let mut app = app(); - app.ui.tool_options.crop_delete = false; - app.ui.tool_options.crop_shield.classic_mode = classic; - app.ui.tool_options.crop_shield.auto_center_preview = auto; - crate::crop_ui::ensure_frame(&mut app); - app.ui.crop_rect = Some([40.0, 20.0, 140.0, 70.0]); - app.crop.default_frame = false; - crate::canvas::commit_crop(&mut app); - let v = &mut app.ui.views[0]; - (v.zoom, v.center, v.fit_pending, v.rotation) = (1.0, [50.0, 25.0], false, 0.0); - app.ui.extras.snap = true; - crate::crop_ui::ensure_frame(&mut app); - assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 100.0, 50.0])); - if ratio { - app.ui.tool_options.crop_ratio = "original".into(); - } - let grab = vec2(f32::from(hx), f32::from(hy)) * grab; - let from = xf(&app).to_screen(50.0 + f32::from(hx) * 50.0, 25.0 + f32::from(hy) * 25.0) + grab; - // Toward the hidden corner (or edge), a screen pixel at a time on the longer axis. - let gap = vec2(f32::from(hx) * if hx < 0 { 40.0 } else { 60.0 }, f32::from(hy) * if hy < 0 { 20.0 } else { 30.0 }); - let dir = gap / gap.x.abs().max(gap.y.abs()); - let d = xf(&app).to_doc(from); - tool_event(&mut app, ToolEvent::Down { x: d[0], y: d[1], pressure: 1.0 }, NONE); - // Drag outward a screen pixel at a time; let go once the moving edges show - // the snap to the hidden pixels' edges (as the user would). - let snapped = |app: &PhotocraftApp| { - let on = |vertical: bool, pos: f64| { - app.prefs_rt - .snap_lines - .iter() - .any(|l| l.vertical == vertical && l.pos == pos && l.kind == photocraft_engine::snap::SnapKind::LayerEdge) - }; - (hx == 0 || on(true, if hx < 0 { hidden[0] } else { hidden[2] })) - && (hy == 0 || on(false, if hy < 0 { hidden[1] } else { hidden[3] })) - }; - let mut end = None; - for i in 1..=80 { - let d = xf(&app).to_doc(from + dir * i as f32); - tool_event(&mut app, ToolEvent::Move { x: d[0], y: d[1], pressure: 1.0 }, NONE); - if snapped(&app) { - end = Some(from + dir * i as f32); - break; - } - } - let end = end.unwrap_or_else(|| panic!("{what}: never snapped to the hidden edge")); - // Released where it stopped, read through the view as it is now. - let end = xf(&app).to_doc(end); - tool_event(&mut app, ToolEvent::Up { x: end[0], y: end[1] }, NONE); - let pick = |h: i8, lo: f64, hi: f64, a: f64, b: f64| match h { - -1 => [a, hi], - 1 => [lo, b], - _ => [lo, hi], - }; - let [x0, x1] = pick(hx, 0.0, 100.0, hidden[0], hidden[2]); - let [y0, y1] = pick(hy, 0.0, 50.0, hidden[1], hidden[3]); - assert_eq!(app.ui.crop_rect, Some([x0, y0, x1, y1]), "{what}: the frame lands exactly on the hidden edge"); - crate::canvas::commit_crop(&mut app); - let st = app.session.active().unwrap(); - assert_eq!((st.doc.size.width, st.doc.size.height), ((x1 - x0) as u32, (y1 - y0) as u32), "{what}"); - let layer = st.doc.walk().into_iter().map(|(_, _, l)| l.id).next().unwrap(); - let r = photocraft_engine::snap::layer_rect(&st.doc, layer).unwrap(); - assert_eq!(r, [hidden[0] - x0, hidden[1] - y0, hidden[2] - x0, hidden[3] - y0], "{what}: no transparent strip"); - } - } - } - } - } -} +mod tests; diff --git a/crates/ui-egui/src/crop_mode/tests.rs b/crates/ui-egui/src/crop_mode/tests.rs new file mode 100644 index 0000000000..0abd3c40f4 --- /dev/null +++ b/crates/ui-egui/src/crop_mode/tests.rs @@ -0,0 +1,776 @@ +use super::*; +use crate::canvas::{ToolEvent, tool_event}; +use crate::crop_ui::{CropDrag, corners}; +use egui::{Modifiers, Pos2, pos2}; +use photocraft_doc::{Color, ColorMode, Document, SampleType, Size}; +use serde_json::json; + +const NONE: Modifiers = Modifiers::NONE; + +/// A 200 × 100 document in a 800 × 600 canvas at 100 %, centred, the Crop tool in default mode. +fn app() -> PhotocraftApp { + let doc = Document::with_background("crop", Size::new(200, 100), 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.sync_views(); + app.ui.tool = Tool::Crop; + app.ui.extras.snap = false; + app.ui.extras.rulers = false; + app.ui.view.show.smart_guides = false; + app.last_canvas_rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let v = &mut app.ui.views[0]; + (v.zoom, v.center, v.fit_pending, v.rotation) = (1.0, [100.0, 50.0], false, 0.0); + assert!(!classic(&app), "Photoshop's default mode is the default"); + app +} + +fn xf(app: &PhotocraftApp) -> ViewXform { + ViewXform::active(app).unwrap() +} + +/// A drag through screen points, each mapped through the view as it is at that moment (as the +/// canvas does every frame). +fn screen_drag(app: &mut PhotocraftApp, pts: &[Pos2], mods: Modifiers) { + let at = |app: &PhotocraftApp, p: Pos2| xf(app).to_doc(p); + let d = at(app, pts[0]); + tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: 1.0 }, mods); + for p in &pts[1..] { + let d = at(app, *p); + tool_event(app, ToolEvent::Move { x: d[0], y: d[1], pressure: 1.0 }, mods); + } + let d = at(app, pts[pts.len() - 1]); + tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, mods); +} + +fn screen_box(app: &PhotocraftApp) -> [Pos2; 4] { + let x = xf(app); + corners(app.ui.crop_rect.unwrap(), crate::crop_ui::angle(app)).map(|p| x.to_screen(p[0] as f32, p[1] as f32)) +} + +fn assert_upright(q: [Pos2; 4]) { + let ok = (q[0].y - q[1].y).abs() < 0.01 && (q[2].y - q[3].y).abs() < 0.01 && (q[0].x - q[3].x).abs() < 0.01 && (q[1].x - q[2].x).abs() < 0.01; + assert!(ok && q[1].x > q[0].x && q[3].y > q[0].y, "not an upright box on screen: {q:?}"); +} + +fn close(a: [Pos2; 4], b: [Pos2; 4]) -> bool { + a.iter().zip(b).all(|(p, q)| p.distance(q) < 0.02) +} + +/// A real (not default) frame [40, 30, 100, 70], centred at (70, 50) = screen (370, 300). +fn with_frame(app: &mut PhotocraftApp) { + crate::crop_ui::ensure_frame(app); + app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]); + app.crop.default_frame = false; +} + +#[test] +fn a_live_resize_snaps_the_handle_without_feedback_from_the_camera() { + for (hx, hy) in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)] { + for alt in [false, true] { + for (zoom, ppp, flip, ratio) in [(1.0, 1.0, false, false), (0.5, 1.0, false, true), (3.0, 2.0, false, false), (3.0, 2.0, true, true)] { + let mut app = app(); + app.ppp = ppp; + app.ui.views[0].zoom = zoom; + app.ui.view.flip_horizontal = flip; + if ratio { + app.ui.tool_options.crop_ratio = "original".into(); + } + app.ui.extras.snap = true; + crate::crop_ui::ensure_frame(&mut app); + let box0 = screen_box(&app); + let c = mid_of(box0); + let from = xf(&app).to_screen(100.0 + hx as f32 * 100.0, 50.0 + hy as f32 * 50.0); + let direction = (from - c).normalized(); + let mods = if alt { Modifiers::ALT } else { NONE }; + let d = xf(&app).to_doc(from); + tool_event(&mut app, ToolEvent::Down { x: d[0], y: d[1], pressure: 1.0 }, mods); + // Leave the snap radius, then return just inside it. A still pointer must + // settle on the canvas edge instead of alternating on opposite sides of it. + for offset in [20.0, -2.0, -2.0, -2.0, -2.0, -2.0] { + let p = from + direction * offset; + let d = xf(&app).to_doc(p); + tool_event(&mut app, ToolEvent::Move { x: d[0], y: d[1], pressure: 1.0 }, mods); + if offset == -2.0 { + assert!(close(screen_box(&app), box0), "handle ({hx}, {hy}), Alt {alt}: {:?}", app.ui.crop_rect); + } + } + let d = xf(&app).to_doc(from + direction * -2.0); + tool_event(&mut app, ToolEvent::Up { x: d[0], y: d[1] }, mods); + assert!(close(screen_box(&app), box0), "release: {:?}", app.ui.crop_rect); + } + } + } +} + +#[test] +fn dragging_outside_turns_the_image_and_the_box_stays_upright() { + let mut app = app(); + with_frame(&mut app); + let before = screen_box(&app); + // From straight right of the box centre to straight below it: a quarter turn clockwise + // on screen, so the image turns clockwise and the frame turns -90° on it. + screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(440.0, 320.0), pos2(370.0, 380.0)], NONE); + assert!((crate::crop_ui::angle(&app) - -90.0).abs() < 0.01, "{}", app.ui.crop_angle); + assert!((view_rotation(&app) - 90.0).abs() < 0.01, "the view turned with it"); + assert_upright(screen_box(&app)); + assert!(close(screen_box(&app), before), "the box doesn't move on screen: {:?} vs {before:?}", screen_box(&app)); + assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0]), "turning keeps the frame"); + // ⇧ steps of 15°, still upright. + let a = 22.0f32.to_radians(); + screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(370.0 + 80.0 * a.cos(), 300.0 + 80.0 * a.sin())], Modifiers::SHIFT); + assert!((crate::crop_ui::angle(&app) - -105.0).abs() < 0.01, "{}", app.ui.crop_angle); + assert_upright(screen_box(&app)); + assert!(close(screen_box(&app), before)); + assert!(crate::crop_ui::turning(&app).is_none()); +} + +/// Even with Auto Center Preview, a drag inside an off-centre box (after a pan, say) leaves the +/// box where it is on screen: only the image moves (Photoshop 25.1). +#[test] +fn a_move_never_recentres_the_box() { + let mut app = app(); + assert!(app.ui.tool_options.crop_shield.auto_center_preview); + with_frame(&mut app); + assert!(mid_of(screen_box(&app)).distance(pos2(370.0, 300.0)) < 0.01); + screen_drag(&mut app, &[pos2(370.0, 300.0), pos2(380.0, 300.0), pos2(390.0, 300.0)], NONE); + assert!(mid_of(screen_box(&app)).distance(pos2(370.0, 300.0)) < 0.01, "{:?}", mid_of(screen_box(&app))); + let r = app.ui.crop_rect.unwrap(); + assert!(r.iter().zip([20.0, 30.0, 80.0, 70.0]).all(|(a, b)| (a - b).abs() < 1e-3), "{r:?}"); +} + +/// Moves the image under the box from document point `from` by `d` (both in the view at the +/// press), checks the snap lines before release, and returns where the box's centre started +/// on screen. +fn image_drag(app: &mut PhotocraftApp, from: [f32; 2], d: [f32; 2], line: Option<(bool, f64)>) -> Pos2 { + let (a, b) = (xf(app).to_screen(from[0], from[1]), xf(app).to_screen(from[0] + d[0], from[1] + d[1])); + let mid = mid_of(screen_box(app)); + let p = xf(app).to_doc(a); + tool_event(app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, NONE); + assert_eq!(app.prefs_rt.snap.as_ref().map(|s| &s.gesture), Some(&crate::snap_ui::Gesture::CropImage)); + for t in [0.5, 1.0] { + let p = xf(app).to_doc(a + (b - a) * t); + tool_event(app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }, NONE); + } + if let Some((vertical, pos)) = line { + assert!(app.prefs_rt.snap_lines.iter().any(|l| l.vertical == vertical && l.pos == pos), "{:?}", app.prefs_rt.snap_lines); + } + let p = xf(app).to_doc(b); + tool_event(app, ToolEvent::Up { x: p[0], y: p[1] }, NONE); + mid +} + +fn assert_frame(app: &PhotocraftApp, want: [f64; 4], what: &str) { + let r = app.ui.crop_rect.unwrap(); + assert!(r.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-3), "{what}: {r:?}, want {want:?}"); +} + +/// #8580: moving the image under the box snaps the frame's edges and centre with View › Snap +/// on, so the content can be centred in it without leaving the Crop tool. The box stays put. +#[test] +fn moving_the_image_snaps_the_frame_to_the_document_centre() { + for (snap, zoom, flip) in [(false, 1.0, false), (true, 1.0, false), (true, 2.0, false), (true, 1.0, true)] { + let mut app = app(); + app.ui.extras.snap = snap; + app.ui.views[0].zoom = zoom; + app.ui.view.flip_horizontal = flip; + with_frame(&mut app); + // The frame [40, 30, 100, 70] goes 27 px right over the image: its centre lands 3 px + // short of the document's (100, 50), inside the snap radius at either zoom. + let mid = image_drag(&mut app, [70.0, 50.0], [-27.0, 0.0], snap.then_some((true, 100.0))); + let what = format!("snap {snap}, zoom {zoom}, flip {flip}"); + assert_frame(&app, if snap { [70.0, 30.0, 130.0, 70.0] } else { [67.0, 30.0, 127.0, 70.0] }, &what); + assert!(mid_of(screen_box(&app)).distance(mid) < 0.01, "{what}: the box moved on screen"); + assert!(app.prefs_rt.snap.is_none() && app.prefs_rt.snap_lines.is_empty()); + } +} + +/// The issue's case: a box larger than the canvas (to extend it) centres on the content's +/// layer, both ways. A turned box doesn't snap (its edges don't line up with anything). +#[test] +fn moving_the_image_centres_a_larger_box_on_a_layer() { + let mut app = app(); + app.ui.extras.snap = true; + app.run("layer.new.layer", json!({"name": "logo"})).unwrap(); + app.run("select.rect", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + crate::crop_ui::ensure_frame(&mut app); + app.ui.crop_rect = Some([-40.0, -60.0, 140.0, 120.0]); + app.crop.default_frame = false; + // Its centre (50, 30) goes to (42, 38): 2 px from the logo's centre (40, 40). + image_drag(&mut app, [50.0, 30.0], [8.0, -8.0], Some((false, 40.0))); + assert_frame(&app, [-50.0, -50.0, 130.0, 130.0], "centred on the logo"); + + app.ui.crop_angle = 30.0; + sync(&mut app, None); + let p = xf(&app).to_doc(mid_of(screen_box(&app))); + tool_event(&mut app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, NONE); + assert!(matches!(app.crop.drag, Some(CropDrag::MoveImage { .. }))); + assert!(app.prefs_rt.snap.is_none(), "a turned box doesn't snap"); + tool_event(&mut app, ToolEvent::Up { x: p[0], y: p[1] }, NONE); +} + +/// With View › Snap To › Layers off, smart guides still centre the box on a layer, although +/// the document's bounds are snap targets that aren't within reach. +#[test] +fn moving_the_image_snaps_to_smart_guides_beside_out_of_reach_targets() { + for smart in [false, true] { + let mut app = app(); + app.ui.extras.snap = true; + app.ui.view.snap_to.layers = false; + app.ui.view.show.smart_guides = smart; + app.run("layer.new.layer", json!({"name": "logo"})).unwrap(); + app.run("select.rect", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + crate::crop_ui::ensure_frame(&mut app); + app.ui.crop_rect = Some([-40.0, -60.0, 140.0, 120.0]); + app.crop.default_frame = false; + image_drag(&mut app, [50.0, 30.0], [8.0, -8.0], smart.then_some((false, 40.0))); + let want = if smart { [-50.0, -50.0, 130.0, 130.0] } else { [-48.0, -52.0, 132.0, 128.0] }; + assert_frame(&app, want, &format!("smart guides {smart}")); + } +} + +/// #7088: the box's own Undo/Redo of a move (or a turn) in default mode puts the frame back +/// and moves the image, not the box: it stays put on screen (Auto Center Preview off) or goes +/// to the middle of the canvas (on). +#[test] +fn box_undo_and_redo_keep_the_box_put() { + for auto in [false, true] { + let mut app = app(); + app.ui.tool_options.crop_shield.auto_center_preview = auto; + with_frame(&mut app); + // A quarter turn, then a move inside: two box steps. + screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(370.0, 380.0)], NONE); + let turned = app.ui.crop_rect; + screen_drag(&mut app, &[pos2(370.0, 300.0), pos2(380.0, 305.0), pos2(390.0, 310.0)], NONE); + let moved = app.ui.crop_rect; + assert_ne!(moved, turned); + let want = if auto { pos2(400.0, 300.0) } else { pos2(370.0, 300.0) }; + let check = |app: &PhotocraftApp, what: &str| { + let q = screen_box(app); + assert_upright(q); + assert!(mid_of(q).distance(want) < 0.05, "auto={auto} {what}: the box moved on screen to {:?}", mid_of(q)); + }; + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.ui.crop_rect, turned, "auto={auto}: the move is undone"); + check(&app, "undo move"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0])); + assert!(crate::crop_ui::angle(&app).abs() < 1e-9, "the turn is undone"); + check(&app, "undo turn"); + app.run("edit.redo", json!({})).unwrap(); + check(&app, "redo turn"); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(app.ui.crop_rect, moved, "auto={auto}: the move is redone"); + check(&app, "redo move"); + } +} + +fn mid_of(q: [Pos2; 4]) -> Pos2 { + pos2((q[0].x + q[2].x) / 2.0, (q[0].y + q[2].y) / 2.0) +} + +#[test] +fn dragging_inside_moves_the_image_under_the_box() { + let mut app = app(); + with_frame(&mut app); + let before = screen_box(&app); + screen_drag(&mut app, &[pos2(370.0, 300.0), pos2(380.0, 305.0), pos2(390.0, 310.0)], NONE); + // The image followed the pointer 20, 10 to the right and down: the frame lies that much + // further up-left on it. + let r = app.ui.crop_rect.unwrap(); + assert!(r.iter().zip([20.0, 20.0, 80.0, 60.0]).all(|(a, b)| (a - b).abs() < 1e-3), "{r:?}"); + assert!(close(screen_box(&app), before), "the box stays put on screen"); + // Turned 30° first: the move follows the pointer on screen, along the turned image. + screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(370.0 + 80.0 * 30f32.to_radians().cos(), 300.0 + 80.0 * 30f32.to_radians().sin())], NONE); + assert!((crate::crop_ui::angle(&app) - -30.0).abs() < 0.01); + let (before, c0) = (screen_box(&app), crate::crop_ui::center(app.ui.crop_rect.unwrap())); + let img = |app: &PhotocraftApp| xf(app).to_screen(0.0, 0.0); + let origin = img(&app); + screen_drag(&mut app, &[pos2(370.0, 300.0), pos2(400.0, 300.0)], NONE); + assert!(close(screen_box(&app), before), "box put"); + assert!((img(&app) - origin - vec2(30.0, 0.0)).length() < 0.05, "the image moved 30 right on screen"); + let c1 = crate::crop_ui::center(app.ui.crop_rect.unwrap()); + assert!(((c1[0] - c0[0]).hypot(c1[1] - c0[1]) - 30.0).abs() < 1e-3); +} + +/// A `ui.pointer` click (down and up at the same point, no move) changes nothing, upright or +/// turned: reading the point in the press view used to round it through `f32` and the view, +/// nudging the frame by a hair and pushing a box Undo step that undid nothing visible. +#[test] +fn a_ui_pointer_click_changes_nothing() { + let ctx = egui::Context::default(); + for deg in [0.0, -30.0, 41.5] { + let mut app = app(); + with_frame(&mut app); + app.ui.crop_angle = deg; + sync_frame(&mut app); + let (rect, angle) = (app.ui.crop_rect, app.ui.crop_angle); + // Inside the frame (moves the image) and outside it (turns the image). + for p in [[70.3, 50.7], [55.17, 41.9], [83.01, 59.33], [150.3, 50.7], [10.9, 90.1]] { + let ev = json!([{"kind": "down", "x": p[0], "y": p[1]}, {"kind": "up", "x": p[0], "y": p[1]}]); + let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"events": ev})); + let crate::control::Outcome::Done(v) = crate::control::handle(&mut app, &ctx, &req) else { panic!("ui.pointer didn't finish") }; + assert_eq!(v["ok"], true, "{v}"); + assert_eq!((app.ui.crop_rect, app.ui.crop_angle), (rect, angle), "click at {p:?}, frame at {deg}°"); + assert_eq!(crate::crop_ui::is_enabled(&app, "edit.undo"), None, "click at {p:?}, frame at {deg}°: a box Undo step"); + } + } +} + +#[test] +fn the_readout_is_the_images_turn_clockwise_positive() { + let mut app = app(); + with_frame(&mut app); + // A 30° clockwise sweep on screen, held mid-drag. + let d = |app: &PhotocraftApp, p: Pos2| xf(app).to_doc(p); + let a = 30f32.to_radians(); + let (p0, p1) = (pos2(450.0, 300.0), pos2(370.0 + 80.0 * a.cos(), 300.0 + 80.0 * a.sin())); + let s = d(&app, p0); + tool_event(&mut app, ToolEvent::Down { x: s[0], y: s[1], pressure: 1.0 }, NONE); + let m = d(&app, p1); + tool_event(&mut app, ToolEvent::Move { x: m[0], y: m[1], pressure: 1.0 }, NONE); + let shown = crate::crop_ui::turning(&app).unwrap(); + assert!((shown - 30.0).abs() < 0.01, "clockwise is positive: {shown}"); + assert!((crate::crop_ui::angle(&app) - -30.0).abs() < 0.01, "the frame turns the other way on the image"); + let m = d(&app, p1); + tool_event(&mut app, ToolEvent::Up { x: m[0], y: m[1] }, NONE); + assert_eq!(image_turn(0.0).to_string(), "0", "never -0"); + // Classic Mode shows the frame's own turn, clockwise positive as before. + let mut app = self::app(); + app.ui.tool_options.crop_shield.classic_mode = true; + with_frame(&mut app); + let s = d(&app, p0); + tool_event(&mut app, ToolEvent::Down { x: s[0], y: s[1], pressure: 1.0 }, NONE); + let m = d(&app, p1); + tool_event(&mut app, ToolEvent::Move { x: m[0], y: m[1], pressure: 1.0 }, NONE); + assert!((crate::crop_ui::turning(&app).unwrap() - 30.0).abs() < 0.01); +} + +#[test] +fn auto_center_keeps_the_box_centred_while_a_handle_is_dragged() { + for auto in [true, false] { + let mut app = app(); + app.ui.tool_options.crop_shield.auto_center_preview = auto; + with_frame(&mut app); + // Turn 90° clockwise on screen first: the frame is at -90° in the image. + screen_drag(&mut app, &[pos2(450.0, 300.0), pos2(370.0, 380.0)], NONE); + let q = screen_box(&app); + assert_upright(q); + let mid = |q: [Pos2; 4]| pos2((q[0].x + q[2].x) / 2.0, (q[0].y + q[2].y) / 2.0); + // The box's right edge on screen, dragged 10 then 20 further right. + let right = pos2(q[1].x, (q[1].y + q[2].y) / 2.0); + assert_eq!(crate::crop_ui::cursor(&app, xf(&app).to_doc(right)), Some(egui::CursorIcon::ResizeHorizontal), "screen-space arrow"); + let at = |app: &PhotocraftApp, p: Pos2| xf(app).to_doc(p); + let s = at(&app, right); + tool_event(&mut app, ToolEvent::Down { x: s[0], y: s[1], pressure: 1.0 }, NONE); + for dx in [10.0, 20.0] { + let m = at(&app, right + vec2(dx, 0.0)); + tool_event(&mut app, ToolEvent::Move { x: m[0], y: m[1], pressure: 1.0 }, NONE); + let n = screen_box(&app); + assert_upright(n); + assert!((n[1].x - (right.x + dx)).abs() < 0.02, "auto={auto} dx={dx}: the handle follows the pointer: {n:?}"); + if auto { + assert!(mid(n).distance(mid(q)) < 0.02, "dx={dx}: live, the box stays centred: {:?} vs {:?}", mid(n), mid(q)); + assert!(((n[1].x - n[0].x) - (q[1].x - q[0].x) - 2.0 * dx).abs() < 0.02, "it grows on both sides"); + } else { + assert!((n[0].x - q[0].x).abs() < 0.02, "the left edge stays put"); + } + assert!(((n[3].y - n[0].y) - (q[3].y - q[0].y)).abs() < 0.02); + } + let m = at(&app, right + vec2(20.0, 0.0)); + tool_event(&mut app, ToolEvent::Up { x: m[0], y: m[1] }, NONE); + let n = screen_box(&app); + if auto { + assert!(mid(n).distance(mid(q)) < 0.05, "on release it stays where its centre was: {:?} vs {:?}", mid(n), mid(q)); + // On the image, the opposite edge stayed put: the frame grew 40 px from it. + let r = app.ui.crop_rect.unwrap(); + assert!(((r[2] - r[0]) - 100.0).abs() < 1e-3 && ((r[3] - r[1]) - 40.0).abs() < 1e-3, "{r:?}"); + let left = corners(r, crate::crop_ui::angle(&app))[0]; + let was = corners([40.0, 30.0, 100.0, 70.0], -90.0)[0]; + assert!((left[0] - was[0]).abs() < 1e-3 && (left[1] - was[1]).abs() < 1e-3, "{left:?} vs {was:?}"); + } else { + assert!(mid(n).distance(pos2(380.0, 300.0)) < 0.05, "{:?}", mid(n)); + } + } + // ⌥: about the centre, and a collapsed drag puts frame and view back. + let mut app = app(); + with_frame(&mut app); + let q = screen_box(&app); + let center = app.ui.views[0].center; + let right = pos2(q[1].x, (q[1].y + q[2].y) / 2.0); + screen_drag(&mut app, &[right, right + vec2(10.0, 0.0)], Modifiers::ALT); + let r = app.ui.crop_rect.unwrap(); + assert!(((r[0] + r[2]) / 2.0 - 70.0).abs() < 1e-3 && ((r[2] - r[0]) - 80.0).abs() < 1e-3, "{r:?}"); + let mut app = self::app(); + with_frame(&mut app); + screen_drag(&mut app, &[right, pos2(370.0, 300.0)], NONE); + assert_eq!(app.ui.crop_rect, Some([40.0, 30.0, 100.0, 70.0]), "too small: the frame is back"); + assert_eq!(app.ui.views[0].center, center, "and the view"); +} + +/// The same frame and angle commit the same crop in both modes, and in both the view stays +/// upright after a commit or a cancel (Photoshop 25.1 doesn't restore a Rotate View turn). +#[test] +fn commit_is_the_same_in_both_modes_and_the_view_stays_upright() { + let mut out = Vec::new(); + for classic in [true, false] { + let mut app = app(); + app.run("select.rect", json!({"x": 70, "y": 50, "width": 2, "height": 2})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool_options.crop_shield.classic_mode = classic; + app.ui.views[0].rotation = 20.0; + with_frame(&mut app); + app.ui.crop_angle = 30.0; + app.crop.editing = true; + crate::crop_ui::ensure_frame(&mut app); + let want = if classic { 0.0 } else { -30.0 }; + assert!((view_rotation(&app) - want).abs() < 1e-4, "classic={classic}: {}", view_rotation(&app)); + if !classic { + assert_upright(screen_box(&app)); + } + let past = app.session.active().unwrap().history.past_len(); + crate::canvas::commit_crop(&mut app); + assert_eq!(view_rotation(&app), 0.0, "classic={classic}: after ↵"); + crate::crop_ui::ensure_frame(&mut app); + assert_eq!(view_rotation(&app), 0.0, "classic={classic}: with the next frame"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), past + 1, "one undo step"); + let surf = st.doc.layers[0].surface().unwrap(); + let px: Vec<[f32; 4]> = + (0..st.doc.size.width as i32).flat_map(|x| (0..st.doc.size.height as i32).map(move |y| (x, y))).map(|(x, y)| surf.rgba(x, y)).collect(); + out.push((st.doc.size, px)); + // Esc. + let mut app = self::app(); + app.ui.tool_options.crop_shield.classic_mode = classic; + app.ui.views[0].rotation = -45.0; + with_frame(&mut app); + screen_drag(&mut app, &[pos2(500.0, 300.0), pos2(370.0, 420.0)], NONE); + crate::crop_ui::cancel(&mut app); + crate::crop_ui::ensure_frame(&mut app); + assert_eq!(view_rotation(&app), 0.0, "classic={classic}: Esc"); + } + assert_eq!(out[0].0, out[1].0, "same size"); + assert!(out[0].1 == out[1].1, "same pixels"); +} + +#[test] +fn picking_the_crop_tool_turns_a_rotated_view_upright() { + let mut app = app(); + app.ui.tool = Tool::Brush; + app.ui.views[0].rotation = 30.0; + let center = app.ui.views[0].center; + app.ui.tool = Tool::Crop; + crate::crop_ui::ensure_frame(&mut app); + assert!(app.crop.default_frame && !app.crop.editing, "no click needed"); + assert_eq!(view_rotation(&app), 0.0); + assert_eq!(app.ui.views[0].center, center, "about the view's centre"); + // Leaving the tool doesn't bring the turn back. + app.ui.tool = Tool::Brush; + crate::crop_ui::ensure_frame(&mut app); + assert_eq!(view_rotation(&app), 0.0); + // Classic Mode too (Photoshop 25.1): the camera goes upright about the view's centre and + // the frame stays on the same image area, keeping its own turn. + let mut app = self::app(); + app.ui.tool_options.crop_shield.classic_mode = true; + app.ui.tool = Tool::Brush; + app.ui.views[0].rotation = 30.0; + app.ui.crop_rect = Some([40.0, 30.0, 100.0, 70.0]); + app.ui.crop_angle = 12.0; + app.ui.tool = Tool::Crop; + crate::crop_ui::ensure_frame(&mut app); + assert_eq!(view_rotation(&app), 0.0); + assert_eq!(app.ui.views[0].center, center, "about the view's centre"); + assert_eq!((app.ui.crop_rect, app.ui.crop_angle), (Some([40.0, 30.0, 100.0, 70.0]), 12.0), "the frame is unchanged"); + // P switches modes without bringing the R turn back: default mode turns the view with the + // frame, Classic Mode puts the camera upright again. + let press_p = |app: &mut PhotocraftApp| { + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: NONE })); + assert!(crate::crop_shield::keys(app, &ctx)); + }; + press_p(&mut app); + assert!(!classic(&app)); + assert!((view_rotation(&app) - -12.0).abs() < 1e-4, "{}", view_rotation(&app)); + press_p(&mut app); + assert!(classic(&app)); + assert_eq!(view_rotation(&app), 0.0); + crate::crop_ui::cancel(&mut app); + crate::crop_ui::ensure_frame(&mut app); + assert_eq!(view_rotation(&app), 0.0, "Esc in Classic Mode: still upright"); +} + +fn key(app: &mut PhotocraftApp, key: egui::Key, modifiers: Modifiers) { + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers })); + crate::shortcuts::handle(app, &ctx); +} + +#[test] +fn arrows_nudge_the_image_shift_by_ten_and_x_recentres() { + let mut app = app(); + with_frame(&mut app); + app.crop.editing = true; + app.ui.crop_angle = -90.0; + crate::crop_ui::ensure_frame(&mut app); + let before = screen_box(&app); + let img = |app: &PhotocraftApp| xf(app).to_screen(0.0, 0.0); + let origin = img(&app); + key(&mut app, egui::Key::ArrowRight, NONE); + assert!(close(screen_box(&app), before), "the box stays put"); + assert!((img(&app) - origin - vec2(1.0, 0.0)).length() < 0.02, "the image moved 1 px right on screen"); + key(&mut app, egui::Key::ArrowDown, Modifiers::SHIFT); + assert!((img(&app) - origin - vec2(1.0, 10.0)).length() < 0.02, "⇧: 10 px"); + assert!(close(screen_box(&app), before)); + assert!(crate::crop_ui::swap_orientation(&mut app)); + assert_upright(screen_box(&app)); + let q = screen_box(&app); + assert!(pos2((q[0].x + q[2].x) / 2.0, (q[0].y + q[2].y) / 2.0).distance(pos2(400.0, 300.0)) < 0.05, "Auto Center Preview"); +} + +/// Photoshop 25.1 greys out Show Cropped Area and Auto Center Preview in Classic Mode. Show +/// Cropped Area then acts as on (an assumption) and H does nothing; the stored choice stays. +#[test] +fn classic_mode_shows_the_cropped_area_and_h_does_nothing() { + let mut app = app(); + crate::crop_ui::ensure_frame(&mut app); + app.ui.tool_options.crop_shield.show_cropped_area = false; + assert!(crate::crop_shield::hides_outside(&app)); + app.ui.tool_options.crop_shield.classic_mode = true; + assert!(!crate::crop_shield::hides_outside(&app)); + let canvas = egui::Color32::from_rgb(40, 40, 40); + assert_ne!(crate::crop_shield::fill(&app.ui.tool_options.crop_shield, canvas, false), Some(canvas), "the shield, not the opaque canvas"); + key(&mut app, egui::Key::H, NONE); + assert_eq!(app.ui.tool, Tool::Crop, "H is taken, not the Hand tool"); + assert!(!app.ui.tool_options.crop_shield.show_cropped_area, "and changes nothing"); + app.ui.tool_options.crop_shield.classic_mode = false; + assert!(crate::crop_shield::hides_outside(&app), "the stored choice is back"); + key(&mut app, egui::Key::H, NONE); + assert!(app.ui.tool_options.crop_shield.show_cropped_area); +} + +#[test] +fn p_toggles_classic_mode_while_the_crop_tool_shows_a_box() { + let mut app = app(); + crate::crop_ui::ensure_frame(&mut app); + let press = |app: &mut PhotocraftApp| { + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: NONE })); + crate::shortcuts::handle(app, &ctx); + }; + press(&mut app); + assert!(classic(&app) && app.ui.tool == Tool::Crop, "P doesn't pick the Pen tool"); + press(&mut app); + assert!(!classic(&app)); + // Mid-drag P is left alone; without a box P is the Pen key. + app.crop.drag = Some(CropDrag::Move { start: [0.0, 0.0], rect: [0.0, 0.0, 10.0, 10.0] }); + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: NONE })); + assert!(!crate::crop_shield::keys(&mut app, &ctx)); + assert!(!classic(&app)); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.tool = Tool::Crop; + press(&mut app); + assert_ne!(app.ui.tool, Tool::Crop); + assert!(!classic(&app)); +} + +#[test] +fn straighten_turns_the_image_so_the_line_is_level_on_screen() { + let mut app = app(); + crate::crop_ui::ensure_frame(&mut app); + crate::crop_straighten::toggle(&mut app); + // A horizon falling to the right, drawn on screen. + let (a, b) = (pos2(320.0, 290.0), pos2(480.0, 310.0)); + let (da, db) = (xf(&app).to_doc(a), xf(&app).to_doc(b)); + screen_drag(&mut app, &[a, b], NONE); + assert!(crate::crop_ui::angle(&app) > 5.0, "{}", app.ui.crop_angle); + let (sa, sb) = (xf(&app).to_screen(da[0] as f32, da[1] as f32), xf(&app).to_screen(db[0] as f32, db[1] as f32)); + assert!((sa.y - sb.y).abs() < 0.01, "the line is level: {sa:?} {sb:?}"); + assert_upright(screen_box(&app)); +} + +/// `ui.pointer` points are read in the view at the press, so an `up` where the last `move` was +/// doesn't move or turn the image a second time. +#[test] +fn ui_pointer_drives_the_default_mode_in_press_coordinates() { + let mut app = app(); + app.ui.tool_options.crop_shield.auto_center_preview = false; + with_frame(&mut app); + let ctx = egui::Context::default(); + let pointer = |app: &mut PhotocraftApp, pts: [[f64; 2]; 2]| { + let ev = json!([ + {"kind": "down", "x": pts[0][0], "y": pts[0][1]}, + {"kind": "move", "x": pts[1][0], "y": pts[1][1]}, + {"kind": "up", "x": pts[1][0], "y": pts[1][1]}, + ]); + let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"events": ev})); + let crate::control::Outcome::Done(v) = crate::control::handle(app, &ctx, &req) else { panic!("ui.pointer didn't finish") }; + assert_eq!(v["ok"], true, "{v}"); + }; + pointer(&mut app, [[70.0, 50.0], [80.0, 55.0]]); + let r = app.ui.crop_rect.unwrap(); + assert!(r.iter().zip([30.0, 25.0, 90.0, 65.0]).all(|(a, b)| (a - b).abs() < 1e-3), "{r:?}"); + assert!((app.ui.views[0].center[0] - 90.0).abs() < 1e-3 && (app.ui.views[0].center[1] - 45.0).abs() < 1e-3); + // Outside: from right of the centre (60, 45) to below it, a quarter turn of the image. + pointer(&mut app, [[140.0, 45.0], [60.0, 125.0]]); + assert!((crate::crop_ui::angle(&app) - -90.0).abs() < 0.01, "{}", app.ui.crop_angle); + assert_upright(screen_box(&app)); +} + +#[test] +fn degenerate_input_never_panics() { + let mut app = app(); + for frame in + [[0.0, 0.0, 0.0, 0.0], [5.0, 5.0, 5.0, 5.0], [f64::NAN, 0.0, 10.0, 10.0], [f64::INFINITY, 0.0, 1e300, 1e300], [-1e300, -1e300, 1e300, 1e300]] + { + for angle in [0.0, f64::NAN, f64::INFINITY, 1e300, -720.5] { + app.ui.crop_rect = Some(frame); + app.ui.crop_angle = angle; + app.crop.default_frame = false; + app.crop.editing = true; + crate::crop_ui::ensure_frame(&mut app); + for p in [pos2(400.0, 300.0), pos2(10.0, 10.0), pos2(f32::NAN, 3.0), pos2(1e30, -1e30)] { + screen_drag(&mut app, &[p, p + vec2(15.0, 7.0)], NONE); + screen_drag(&mut app, &[p, p + vec2(15.0, 7.0)], Modifiers::SHIFT | Modifiers::ALT); + } + crate::crop_ui::nudge(&mut app, f64::NAN, 1.0); + crate::crop_ui::nudge(&mut app, 1.0, 1.0); + crate::crop_ui::swap_orientation(&mut app); + auto_center(&mut app); + shift_image(&mut app, [f64::NAN, f64::INFINITY]); + let press = PressView { rotation: f32::NAN, center: [f32::INFINITY, 0.0] }; + let g = LiveResize { rect: frame, deg: angle, hx: 1, hy: -1, start: [0.0, f64::NAN], q: [1e300, -1e300], ratio: Some(f64::NAN), alt: false }; + live_resize(&mut app, g, press); + assert!(app.ui.crop_rect.is_none_or(|r| r.iter().all(|v| v.is_finite()) || r == frame), "{frame:?} {angle}"); + let v = &app.ui.views[0]; + assert!(v.rotation.is_finite() && v.center.iter().all(|c| c.is_finite()), "{frame:?} {angle}: {v:?}"); + crate::crop_ui::cancel(&mut app); + } + } + assert_eq!(pivot_center([1.0, 2.0], [f64::NAN, 0.0], 0.0, 90.0, false), [1.0, 2.0]); + assert_eq!(pivot_center([1.0, 2.0], [0.0, 0.0], f32::NAN, 90.0, true), [1.0, 2.0]); + // No view at all (no document). + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.tool = Tool::Crop; + app.ui.crop_rect = Some([0.0, 0.0, 10.0, 10.0]); + app.crop.editing = true; + sync(&mut app, None); + auto_center(&mut app); + shift_image(&mut app, [1.0, 1.0]); + upright(&mut app); +} + +#[test] +fn the_options_default_to_photoshops_and_older_settings_load() { + let s = crate::crop_shield::CropShield::default(); + assert!(!s.classic_mode && s.auto_center_preview); + let s: crate::crop_shield::CropShield = serde_json::from_str(r#"{"enabled": false}"#).unwrap(); + assert!(!s.classic_mode && s.auto_center_preview); + let s: crate::crop_shield::CropShield = serde_json::from_str(r#"{"classic_mode": true, "auto_center_preview": false}"#).unwrap(); + assert!(s.classic_mode && !s.auto_center_preview); +} + +#[test] +fn pivoting_keeps_the_point_on_screen() { + for flip in [false, true] { + for (from, to) in [(0.0, 30.0), (45.0, -90.0), (170.0, -170.0)] { + let center = [100.0f32, 50.0]; + let c = [70.0, 20.0]; + let a = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), zoom: 2.0, center, flip, rotation: from, aspect: 1.0 }; + let n = pivot_center(center, c, from, to, flip); + let b = ViewXform { center: n, rotation: to, ..a }; + let (p, q) = (a.to_screen(70.0, 20.0), b.to_screen(70.0, 20.0)); + assert!(p.distance(q) < 0.01, "{flip} {from} {to}: {p:?} vs {q:?}"); + } + } +} + +/// #1919: with Delete Cropped Pixels off, a second crop's handle dragged out toward the hidden +/// pixels snaps exactly onto their edge (a layer edge), however far from the handle's centre +/// the press grabbed it, in both modes, with and without Auto Center Preview: the committed +/// crop has no transparent strip. +#[test] +fn a_recrop_handle_snaps_exactly_to_the_hidden_pixels_edge() { + // The image 200 × 100 cropped to [40, 20, 140, 70]: its pixels stay at [-40, -20, 160, 80]. + let hidden = [-40.0, -20.0, 160.0, 80.0]; + for classic in [false, true] { + for auto in [true, false] { + for (hx, hy) in [(1i8, 0i8), (0, -1), (-1, -1), (1, 1)] { + // A corner also with the image's 2:1 ratio held, which both hidden corners keep. + for (grab, ratio) in [(-4.0f32, false), (0.0, false), (4.0, false), (-4.0, true), (4.0, true)] { + if ratio && (hx == 0 || hy == 0) { + continue; + } + let what = format!("Classic Mode {classic}, Auto Center {auto}, handle ({hx}, {hy}), grabbed {grab} px off, ratio {ratio}"); + let mut app = app(); + app.ui.tool_options.crop_delete = false; + app.ui.tool_options.crop_shield.classic_mode = classic; + app.ui.tool_options.crop_shield.auto_center_preview = auto; + crate::crop_ui::ensure_frame(&mut app); + app.ui.crop_rect = Some([40.0, 20.0, 140.0, 70.0]); + app.crop.default_frame = false; + crate::canvas::commit_crop(&mut app); + let v = &mut app.ui.views[0]; + (v.zoom, v.center, v.fit_pending, v.rotation) = (1.0, [50.0, 25.0], false, 0.0); + app.ui.extras.snap = true; + crate::crop_ui::ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 100.0, 50.0])); + if ratio { + app.ui.tool_options.crop_ratio = "original".into(); + } + let grab = vec2(f32::from(hx), f32::from(hy)) * grab; + let from = xf(&app).to_screen(50.0 + f32::from(hx) * 50.0, 25.0 + f32::from(hy) * 25.0) + grab; + // Toward the hidden corner (or edge), a screen pixel at a time on the longer axis. + let gap = vec2(f32::from(hx) * if hx < 0 { 40.0 } else { 60.0 }, f32::from(hy) * if hy < 0 { 20.0 } else { 30.0 }); + let dir = gap / gap.x.abs().max(gap.y.abs()); + let d = xf(&app).to_doc(from); + tool_event(&mut app, ToolEvent::Down { x: d[0], y: d[1], pressure: 1.0 }, NONE); + // Drag outward a screen pixel at a time; let go once the moving edges show + // the snap to the hidden pixels' edges (as the user would). + let snapped = |app: &PhotocraftApp| { + let on = |vertical: bool, pos: f64| { + app.prefs_rt + .snap_lines + .iter() + .any(|l| l.vertical == vertical && l.pos == pos && l.kind == photocraft_engine::snap::SnapKind::LayerEdge) + }; + (hx == 0 || on(true, if hx < 0 { hidden[0] } else { hidden[2] })) + && (hy == 0 || on(false, if hy < 0 { hidden[1] } else { hidden[3] })) + }; + let mut end = None; + for i in 1..=80 { + let d = xf(&app).to_doc(from + dir * i as f32); + tool_event(&mut app, ToolEvent::Move { x: d[0], y: d[1], pressure: 1.0 }, NONE); + if snapped(&app) { + end = Some(from + dir * i as f32); + break; + } + } + let end = end.unwrap_or_else(|| panic!("{what}: never snapped to the hidden edge")); + // Released where it stopped, read through the view as it is now. + let end = xf(&app).to_doc(end); + tool_event(&mut app, ToolEvent::Up { x: end[0], y: end[1] }, NONE); + let pick = |h: i8, lo: f64, hi: f64, a: f64, b: f64| match h { + -1 => [a, hi], + 1 => [lo, b], + _ => [lo, hi], + }; + let [x0, x1] = pick(hx, 0.0, 100.0, hidden[0], hidden[2]); + let [y0, y1] = pick(hy, 0.0, 50.0, hidden[1], hidden[3]); + assert_eq!(app.ui.crop_rect, Some([x0, y0, x1, y1]), "{what}: the frame lands exactly on the hidden edge"); + crate::canvas::commit_crop(&mut app); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.size.width, st.doc.size.height), ((x1 - x0) as u32, (y1 - y0) as u32), "{what}"); + let layer = st.doc.walk().into_iter().map(|(_, _, l)| l.id).next().unwrap(); + let r = photocraft_engine::snap::layer_rect(&st.doc, layer).unwrap(); + assert_eq!(r, [hidden[0] - x0, hidden[1] - y0, hidden[2] - x0, hidden[3] - y0], "{what}: no transparent strip"); + } + } + } + } +} From 9b4bfca974758c2712a9517d4d0d4c47ad16c26d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:36 +0000 Subject: [PATCH 059/259] refactor(ui-egui): move rulers.rs tests to rulers/tests.rs --- crates/ui-egui/src/rulers.rs | 871 +---------------------------- crates/ui-egui/src/rulers/tests.rs | 868 ++++++++++++++++++++++++++++ 2 files changed, 869 insertions(+), 870 deletions(-) create mode 100644 crates/ui-egui/src/rulers/tests.rs diff --git a/crates/ui-egui/src/rulers.rs b/crates/ui-egui/src/rulers.rs index ccec19c4cb..923e81140a 100644 --- a/crates/ui-egui/src/rulers.rs +++ b/crates/ui-egui/src/rulers.rs @@ -576,873 +576,4 @@ fn corner_origin(app: &mut PhotocraftApp, ui: &egui::Ui, resp: &egui::Response, } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn ruler_ticks_labels_and_pointer_stay_out_of_the_origin_corner() { - let mut failures = Vec::new(); - for theme in crate::theme::ThemeKind::ALL { - for (zoom, flip, rotation, width) in [(1.0, false, 0.0, 560.0), (1.0, false, 0.0, 800.0), (0.25, true, 0.0, 560.0), (2.0, false, 30.0, 560.0)] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); - let full = Rect::from_min_size(pos2(32.0, 32.0), vec2(width - 80.0, 320.0)); - let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)); - let builder = egui_kittest::Harness::builder().with_size(vec2(width, 400.0)); - let mut h = builder.build_ui_state( - move |ui, app| { - let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); - let xf = ViewXform { rect, zoom, center: [(width - 80.0) / 2.0, 160.0], flip, rotation, aspect: 1.0 }; - draw_rulers(app, ui, full, &xf); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, theme); - h.event(egui::Event::PointerMoved(corner.center())); - h.run_steps(4); - let mut ticks = 0; - let mut labels = 0; - for shape in &h.output().shapes { - if matches!(shape.shape, egui::Shape::LineSegment { .. } | egui::Shape::Text(_)) { - ticks += usize::from(matches!(shape.shape, egui::Shape::LineSegment { .. })); - labels += usize::from(matches!(shape.shape, egui::Shape::Text(_))); - let visible = shape.shape.visual_bounding_rect().intersect(shape.clip_rect); - if visible.intersect(corner.shrink(0.5)).is_positive() { - failures.push(format!("{theme:?}: zoom={zoom}, flip={flip}, rotation={rotation}, {visible:?}")); - } - } - } - assert!(ticks > 2 && labels > 0, "rulers still draw ticks and labels"); - } - } - assert!(failures.is_empty(), "ruler drawing overlaps the origin corner: {failures:?}"); - } - - /// #7314: the stacked characters of the left ruler's labels are centred on the strip, so a - /// narrow "1" lines up with a wide "0". - #[test] - fn left_ruler_label_characters_are_centred() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); - let (mut h, full, _) = ruler_harness(app); - h.run_steps(2); - let centres: Vec = h - .output() - .shapes - .iter() - .filter_map(|s| if let egui::Shape::Text(t) = &s.shape { Some(t) } else { None }) - .filter(|t| t.pos.x < full.min.x + RULER && t.pos.y > full.min.y + RULER) - .map(|t| t.pos.x + t.galley.size().x * 0.5) - .collect(); - assert!(centres.len() > 2, "the left ruler draws labels: {centres:?}"); - for c in ¢res { - assert!((c - (full.min.x + RULER * 0.5)).abs() < 0.01, "character centre {c} in {centres:?}"); - } - } - - #[test] - fn shift_snaps_the_zero_point_to_ruler_ticks_from_the_current_origin() { - assert_eq!(snap_px_to_tick(47.0, 0.0, 10.0), 50.0); - assert_eq!(snap_px_to_tick(44.9, 0.0, 10.0), 40.0); - // Ticks run from the current zero point, so they sit at 3 + 10k. - assert_eq!(snap_px_to_tick(47.0, 3.0, 10.0), 43.0); - assert_eq!(snap_px_to_tick(-8.0, 3.0, 10.0), -7.0); - // A degenerate tick never panics or moves the point. - for tick in [0.0, -1.0, f64::NAN, f64::INFINITY] { - assert_eq!(snap_px_to_tick(47.5, 3.0, tick), 47.5); - } - } - - /// Rulers alone in a 400×300 frame at 100 %, centred on a 256×128 document. - fn ruler_harness(app: PhotocraftApp) -> (egui_kittest::Harness<'static, PhotocraftApp>, Rect, ViewXform) { - let full = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)); - let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); - let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let h = egui_kittest::Harness::builder() - .with_size(vec2(400.0, 300.0)) - .with_step_dt(1.0 / 60.0) - .build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), app); - (h, full, xf) - } - - fn press(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, pos: Pos2, pressed: bool, modifiers: egui::Modifiers) { - h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }); - h.run_steps(2); - } - - fn drag_corner_to(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, full: Rect, to: Pos2, modifiers: egui::Modifiers) { - let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center(); - h.event(egui::Event::ModifiersChanged(modifiers)); - h.event(egui::Event::PointerMoved(corner)); - h.run_steps(1); - press(h, corner, true, modifiers); - for p in [corner + vec2(10.0, 10.0), to] { - h.event(egui::Event::PointerMoved(p)); - h.run_steps(2); - } - press(h, to, false, modifiers); - h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); - h.run_steps(1); - } - - fn origin(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> [f64; 2] { - h.state().session.active().unwrap().doc.ruler_origin - } - - /// #2955: dragging out of the ruler corner sets the zero point (cross hairs while dragging), - /// the rulers then read 0 there, Shift snaps it to a tick, and double-clicking the corner - /// resets it. - #[test] - fn dragging_the_ruler_corner_sets_the_zero_point_and_double_click_resets_it() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); - app.ui.extras.snap = false; - let (mut h, full, xf) = ruler_harness(app); - h.run_steps(2); - let target = xf.to_screen(100.0, 40.0); - drag_corner_to(&mut h, full, target, egui::Modifiers::NONE); - let o = origin(&h); - assert!((o[0] - 100.0).abs() < 0.01 && (o[1] - 40.0).abs() < 0.01, "zero point lands under the pointer: {o:?}"); - // The top ruler's "0" now sits at the new zero point, "100" (a distance, unsigned as in - // Photoshop) at the image's left edge. - h.run_steps(2); - let labels: Vec<(String, f32)> = h - .output() - .shapes - .iter() - .filter_map(|s| if let egui::Shape::Text(t) = &s.shape { Some((t.galley.text().to_string(), t.pos.x)) } else { None }) - .collect(); - let near = |text: &str, x: f32| labels.iter().any(|(t, lx)| t == text && (lx - (x + 2.0)).abs() < 1.0); - assert!(near("0", target.x), "a 0 label at the zero point: {labels:?}"); - assert!(near("100", xf.to_screen(0.0, 0.0).x), "100 at the image's left edge: {labels:?}"); - - // Mid-drag, cross hairs run through the pointer across the canvas. - let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center(); - let mid = xf.to_screen(150.0, 90.0); - press(&mut h, corner, true, egui::Modifiers::NONE); - for p in [corner + vec2(10.0, 10.0), mid] { - h.event(egui::Event::PointerMoved(p)); - h.run_steps(2); - } - let crosshair = h.output().shapes.iter().any(|s| { - matches!(s.shape, egui::Shape::LineSegment { points: [a, b], .. } if (a.x - mid.x).abs() < 0.5 && (b.x - mid.x).abs() < 0.5 && (b.y - a.y).abs() > 200.0) - }); - assert!(crosshair, "a vertical cross-hair line through the pointer while dragging"); - assert_eq!(origin(&h), o, "the zero point moves on release only"); - press(&mut h, mid, false, egui::Modifiers::NONE); - assert_eq!(origin(&h), [150.0, 90.0]); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(origin(&h), o, "setting the zero point is undoable"); - - // A drag dropped back on the corner leaves it alone. - drag_corner_to(&mut h, full, full.min + vec2(4.0, 4.0), egui::Modifiers::NONE); - assert_eq!(origin(&h), o); - - // Shift: ticks are 10 px apart at 100 %, measured from the current zero point (100, 40). - drag_corner_to(&mut h, full, xf.to_screen(123.0, 57.0), egui::Modifiers::SHIFT); - assert_eq!(origin(&h), [120.0, 60.0]); - - for _ in 0..40 { - h.step(); - } - let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center(); - h.event(egui::Event::PointerMoved(corner)); - h.step(); - for _ in 0..2 { - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: corner, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); - h.step(); - } - } - h.run_steps(2); - assert_eq!(origin(&h), [0.0, 0.0], "double-clicking the corner resets the zero point"); - } - - /// #2955: the Info panel's X/Y are measured from the rulers' zero point. - #[test] - fn info_panel_position_reads_from_the_zero_point() { - use egui_kittest::kittest::Queryable; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); - app.run("view.setRulerOrigin", json!({"x": 20, "y": 5})).unwrap(); - app.hover_doc = Some([50.5, 20.5]); - let mut h = egui_kittest::Harness::builder() - .with_size(vec2(260.0, 240.0)) - .build_ui_state(|ui, app| crate::panels::dock_body(app, ui, crate::dock::Group::Navigator, 2), app); - h.run_steps(2); - assert!(h.query_by_label("30").is_some() && h.query_by_label("15").is_some(), "X 30, Y 15 from the zero point at (20, 5)"); - assert!(h.query_by_label("50").is_none(), "not the raw image x"); - } - - /// #5728: dragging a guide shows its coordinate in the Info panel on one axis only. - #[test] - fn info_panel_shows_guide_drag_position_outside_canvas() { - use egui_kittest::kittest::Queryable; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); - app.hover_doc = None; - app.guide_drag = Some(GuideDrag { vertical: true, index: None, pos: 42.0, press: 42.0, over_ruler: false }); - let mut h = egui_kittest::Harness::builder() - .with_size(vec2(260.0, 240.0)) - .build_ui_state(|ui, app| crate::panels::dock_body(app, ui, crate::dock::Group::Navigator, 2), app); - h.run_steps(2); - assert!(h.query_by_label("42").is_some(), "vertical guide: X readout"); - h.state_mut().guide_drag = Some(GuideDrag { vertical: false, index: None, pos: 17.0, press: 17.0, over_ruler: false }); - h.run_steps(2); - assert!(h.query_by_label("17").is_some(), "horizontal guide: Y readout"); - } - - /// A dragged guide shows its position beside the pointer: X for a vertical guide, Y for a - /// horizontal one, from the zero point, in the ruler unit (pixels to one decimal). - #[test] - fn guide_drag_shows_its_position_beside_the_pointer() { - use egui_kittest::kittest::Queryable; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); - let v = GuideDrag { vertical: true, index: Some(0), pos: 103.24, press: 50.0, over_ruler: false }; - assert_eq!(guide_drag_readout(&app, v), Some(("X:", "103.2 px".to_owned()))); - let h = GuideDrag { vertical: false, index: None, pos: 40.0, press: 40.0, over_ruler: false }; - assert_eq!(guide_drag_readout(&app, h), Some(("Y:", "40 px".to_owned()))); - app.run("view.setRulerOrigin", json!({"x": 3.0, "y": 10.0})).unwrap(); - assert_eq!(guide_drag_readout(&app, h), Some(("Y:", "30 px".to_owned())), "from the zero point"); - app.run("view.resetRulerOrigin", json!({})).unwrap(); - app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "percent"})).unwrap(); - assert_eq!(guide_drag_readout(&app, GuideDrag { vertical: true, index: None, pos: 103.0, press: 0.0, over_ruler: false }).map(|r| r.0), Some("X:")); - app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "pixels"})).unwrap(); - - app.guide_drag = Some(v); - let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 200.0)).build_ui_state(|ui, app| draw_guide_drag_readout(app, ui.ctx()), app); - h.event(egui::Event::PointerMoved(pos2(50.0, 50.0))); - h.run_steps(2); - assert!(h.query_by_label("X:").is_some() && h.query_by_label("103.2 px").is_some()); - h.state_mut().guide_drag = None; - h.run_steps(2); - assert!(h.query_by_label("X:").is_none(), "no readout once the drag ends"); - } - - type AppHarness = egui_kittest::Harness<'static, PhotocraftApp>; - - /// The real canvas on a 400 × 300 document with a horizontal guide at y = 100, at 100 %, - /// with the Move tool and snapping off. - fn canvas_harness(rulers: bool) -> AppHarness { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - app.run("view.newGuide", json!({"orientation": "horizontal", "position": 100})).unwrap(); - app.sync_views(); - app.ui.extras.rulers = rulers; - app.ui.extras.snap = false; - app.ui.tool = crate::state::Tool::Move; - let mut h = egui_kittest::Harness::builder().with_size(vec2(800.0, 600.0)).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::ALL[0]); - h.run_steps(4); - let v = &mut h.state_mut().ui.views[0]; - (v.zoom, v.center, v.fit_pending) = (1.0, [200.0, 150.0], false); - h.run_steps(2); - h - } - - /// Screen point of document point `(x, y)` in [`canvas_harness`]. - fn canvas_at(h: &AppHarness, x: f32, y: f32) -> Pos2 { - let app = h.state(); - let v = &app.ui.views[0]; - let rect = content_rect(app, app.last_canvas_rect); - ViewXform { rect, zoom: v.zoom, center: v.center, flip: false, rotation: 0.0, aspect: 1.0 }.to_screen(x, y) - } - - /// Moving a horizontal guide with the Move tool on the real canvas: `Y:` follows the pointer. - #[test] - fn moving_a_guide_on_the_canvas_shows_its_y() { - use egui_kittest::kittest::Queryable; - let mut h = canvas_harness(false); - let at = canvas_at; - let press = at(&h, 200.0, 100.0); - h.event(egui::Event::PointerMoved(press)); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: press, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); - h.run_steps(1); - for y in [110.0, 125.0, 140.0] { - h.event(egui::Event::PointerMoved(at(&h, 210.0, y))); - h.run_steps(2); - } - assert!(h.state().guide_drag.is_some_and(|d| !d.vertical), "a horizontal guide is being dragged"); - assert!(h.query_by_label("Y:").is_some() && h.query_by_label("140 px").is_some(), "Y readout at the guide"); - assert!(h.query_by_label("X:").is_none()); - let up = at(&h, 210.0, 140.0); - h.event(egui::Event::PointerButton { pos: up, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); - h.run_steps(2); - assert_eq!(h.state().session.active().unwrap().doc.guides.horizontal, vec![140.0]); - assert!(h.query_by_label("Y:").is_none(), "gone after the drop"); - } - - /// A guide dragged out of the top ruler: in each frame the readout shows where the guide is - /// after that frame's pointer move (the ruler handles the drag after the canvas is drawn), and - /// the frame that drops it shows none. - #[test] - fn ruler_drag_readout_is_current_every_frame() { - use egui_kittest::kittest::Queryable; - let mut h = canvas_harness(true); - let from = pos2(canvas_at(&h, 200.0, 0.0).x, h.state().last_canvas_rect.top() + RULER / 2.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); - for y in [40.0, 60.0, 75.0] { - h.event(egui::Event::PointerMoved(canvas_at(&h, 200.0, y))); - // egui 0.37 lays an Area's contents out a pass after it is shown; step to the settled - // frame with the pointer still at `y` (readout included) rather than the first pass. - h.run_steps(2); - let pos = h.state().guide_drag.map(|d| d.pos); - assert_eq!(pos, Some(f64::from(y)), "the drag follows the pointer"); - assert!(h.query_by_label(&format!("{y} px")).is_some(), "readout at {y} in the same frame"); - } - let up = canvas_at(&h, 200.0, 75.0); - h.event(egui::Event::PointerButton { pos: up, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); - h.run_steps(2); - assert!(h.state().guide_drag.is_none()); - assert!(h.query_by_label("Y:").is_none(), "no readout in the frame that drops the guide"); - assert!(h.state().session.active().unwrap().doc.guides.horizontal.contains(&75.0), "the guide lands at y = 75"); - } - - #[test] - fn percentage_grid_spacing_uses_both_canvas_dimensions() { - let mut g = GuidesGridAndSlices { grid_unit: Unit::Percent, gridline_every: 20.0, subdivisions: 2, ..Default::default() }; - assert_eq!(grid_major_px(&g, 72.0, [1280.0, 720.0], 72.0), [256.0, 144.0]); - // Absolute units remain equal on both axes, irrespective of aspect ratio. - g.grid_unit = Unit::Pixels; - g.gridline_every = 100.0; - assert_eq!(grid_major_px(&g, 72.0, [1280.0, 720.0], 72.0), [100.0, 100.0]); - } - - #[test] - fn unit_steps_allow_fractions() { - assert_eq!(nice_step(0.3, false), 0.5); - assert_eq!(nice_step(0.2, false), 0.2); - assert_eq!(nice_step(0.22, false), 0.25); - assert_eq!(nice_step(0.3, true), 1.0); - assert_eq!(nice_step(23.0, true), 50.0); - } - - #[test] - fn ticks_follow_1_2_5_series() { - assert_eq!(tick_step(1.0), 100.0); - assert_eq!(tick_step(0.1), 1000.0); - assert_eq!(tick_step(4.0), 20.0); - assert_eq!(tick_step(64.0), 1.0); - assert_eq!(tick_step(0.25), 500.0); - } - - #[test] - fn hidden_guides_are_not_hit_tested() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); - app.sync_views(); - app.session.execute("view.newGuide", json!({"orientation": "vertical", "position": 50})).unwrap(); - app.session.execute("view.newGuide", json!({"orientation": "horizontal", "position": 25})).unwrap(); - let positions = app.session.active().unwrap().doc.guides.clone(); - - // Visible, unlocked guides remain interactive in either orientation. - assert_eq!(guide_at(&app, 50.0, 10.0), Some((true, 0))); - assert_eq!(guide_at(&app, 10.0, 25.0), Some((false, 0))); - - // All ways to hide the canvas guides must also disable hit testing. - app.ui.extras.guides = false; - assert_eq!(guide_at(&app, 50.0, 10.0), None); - assert_eq!(guide_at(&app, 10.0, 25.0), None); - app.ui.extras.guides = true; - - app.ui.view.show.canvas_guides = false; - assert_eq!(guide_at(&app, 50.0, 10.0), None); - assert_eq!(guide_at(&app, 10.0, 25.0), None); - app.ui.view.show.canvas_guides = true; - - app.ui.view.extras = false; - assert_eq!(guide_at(&app, 50.0, 10.0), None); - assert_eq!(guide_at(&app, 10.0, 25.0), None); - app.ui.view.extras = true; - - // Hiding/showing must not change the stored guide positions. - assert_eq!(app.session.active().unwrap().doc.guides, positions); - assert_eq!(guide_at(&app, 50.0, 10.0), Some((true, 0))); - assert_eq!(guide_at(&app, 10.0, 25.0), Some((false, 0))); - - app.ui.extras.lock_guides = true; - assert_eq!(guide_at(&app, 50.0, 10.0), None); - assert_eq!(guide_at(&app, 10.0, 25.0), None); - } - - #[test] - fn unit_menu_lists_every_unit_with_the_current_one_checked() { - let items = unit_menu_items(Unit::Inches, &UNITS); - assert_eq!(items.len(), Unit::NAMES.len()); - // Every unit is offered, labelled, and in the preference's order. - assert_eq!(items[0], ("Pixels".to_string(), "pixels", false)); - assert_eq!(items.iter().find(|(_, name, _)| *name == "cm").unwrap().0, "Centimeters"); - // Exactly the current unit is checked. - let checked: Vec<_> = items.iter().filter(|(_, _, c)| *c).map(|(_, name, _)| *name).collect(); - assert_eq!(checked, vec!["inches"]); - } - - #[test] - fn picking_a_ruler_unit_changes_the_preference() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - assert_eq!(app.session.prefs().units_and_rulers.rulers, Unit::Pixels); - // The context menu applies its pick exactly as the preference pane does. - app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "cm"})).unwrap(); - assert_eq!(app.session.prefs().units_and_rulers.rulers, Unit::Centimeters); - } - - /// View › Rulers is remembered: the next launch, and every document created or opened in it, - /// shows the rulers as last set, on or off (#2918). - #[test] - fn rulers_open_as_last_set_after_a_restart() { - use std::{cell::RefCell, rc::Rc}; - let saved = Rc::new(RefCell::new(None::)); - let launch = |saved: &Rc>>| { - let (load, store) = (saved.clone(), saved.clone()); - PhotocraftApp::new( - photocraft_engine::Session::new(), - crate::Services { - load_prefs: Some(Box::new(move || load.borrow().clone())), - save_prefs: Some(Box::new(move |text| { - *store.borrow_mut() = Some(text.to_string()); - Ok(()) - })), - ..Default::default() - }, - ) - }; - for on in [true, false] { - let mut app = launch(&saved); - assert_eq!(crate::menus::invoke(&mut app, &egui::Context::default(), "view.rulers", json!({})).unwrap(), json!(on)); - crate::prefs_ui::save_preferences(&mut app).unwrap(); - let mut next = launch(&saved); - next.session.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); - next.sync_views(); - assert_eq!(next.ui.extras.rulers, on, "a new document after a restart shows the rulers as last set"); - } - } - - #[test] - fn guide_drags_create_move_and_delete() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); - app.sync_views(); - finish_drag(&mut app, GuideDrag { vertical: true, index: None, pos: 50.0, press: 50.0, over_ruler: false }); - finish_drag(&mut app, GuideDrag { vertical: false, index: None, pos: 500.0, press: 500.0, over_ruler: false }); // off canvas: ignored - assert_eq!(app.session.active().unwrap().doc.guides.vertical, vec![50.0]); - assert!(app.session.active().unwrap().doc.guides.horizontal.is_empty()); - assert_eq!(guide_at(&app, 51.0, 10.0), Some((true, 0))); - finish_drag(&mut app, GuideDrag { vertical: true, index: Some(0), pos: 120.0, press: 50.0, over_ruler: false }); - assert_eq!(app.session.active().unwrap().doc.guides.vertical, vec![120.0]); - finish_drag(&mut app, GuideDrag { vertical: true, index: Some(0), pos: -30.0, press: 120.0, over_ruler: false }); - assert!(app.session.active().unwrap().doc.guides.vertical.is_empty()); - app.ui.extras.lock_guides = true; - assert_eq!(guide_at(&app, 0.0, 0.0), None); - } - - /// ⌘ is the Move tool with any tool, so a ⌘-drag over a guide moves the guide, never the layer - /// (#2690); with Lock Guides a ⌘-drag with a marquee moves the layer as before. - #[test] - fn command_drag_over_a_guide_moves_the_guide_with_any_tool() { - use crate::canvas::{ToolEvent, tool_event}; - use crate::state::Tool; - for (tool, locked) in [ - (Tool::Brush, false), - (Tool::Eraser, false), - (Tool::Gradient, false), - (Tool::Frame, false), - (Tool::Artboard, false), - (Tool::RectMarquee, false), - (Tool::Lasso, false), - (Tool::MagicWand, false), - (Tool::RectMarquee, true), - ] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 80, "height": 60, "background": "transparent"})).unwrap(); - app.sync_views(); - app.ui.tool = tool; - app.ui.extras.lock_guides = locked; - let layer = app.session.active().unwrap().active_layer.unwrap(); - app.session - .edit("paint", |doc, _| { - doc.layer_mut(layer).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - app.run("view.newGuide", json!({"orientation": "vertical", "position": 50})).unwrap(); - let cmd = egui::Modifiers::COMMAND; - tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }, cmd); - tool_event(&mut app, ToolEvent::Move { x: 65.0, y: 40.0, pressure: 1.0 }, cmd); - tool_event(&mut app, ToolEvent::Up { x: 65.0, y: 40.0 }, cmd); - let doc = &app.session.active().unwrap().doc; - let moved = doc.layer(layer).unwrap().surface().unwrap().rgba(12, 12)[3] == 0.0; - if locked { - assert_eq!((doc.guides.vertical.clone(), moved), (vec![50.0], true), "{tool:?}, guides locked: the layer moves"); - } else { - assert_eq!((doc.guides.vertical.clone(), moved), (vec![65.0], false), "{tool:?}: the guide moves, the layer stays"); - } - } - } - - /// #3233: a rotated view keeps the rulers level and fully ticked at zoom scale. The top ruler - /// spans the same number of document pixels as the unrotated view, the ticks map back onto - /// its ends, and both rulers read 0 at the screen position of the (rotated) document origin, - /// as Photoshop does. - #[test] - fn rotated_view_keeps_full_rulers() { - let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); - let (a, b) = (rect.left_top(), rect.right_top()); - for rotation in [0.0f32, 30.0, 45.0, 90.0, -119.0, 180.0] { - for flip in [false, true] { - let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip, rotation, aspect: 1.0 }; - let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, [0.0; 2]); - assert!((u1 - u0 - 1600.0).abs() < 1e-2, "rotation {rotation}: top ruler covers {u0}..{u1}"); - let (first, last) = if flip { (u1, u0) } else { (u0, u1) }; - assert!((ruler_pos(&xf, false, first, 1.0, [0.0; 2]) - a.x).abs() < 1e-2, "rotation {rotation}: first tick"); - assert!((ruler_pos(&xf, false, last, 1.0, [0.0; 2]) - b.x).abs() < 1e-2, "rotation {rotation}: last tick"); - // 0 at the projected origin, 500 document px = 500 × zoom screen px further on. - let origin = xf.to_screen(0.0, 0.0); - assert!((ruler_pos(&xf, false, 0.0, 1.0, [0.0; 2]) - origin.x).abs() < 1e-2, "rotation {rotation}: top ruler 0"); - assert!((ruler_pos(&xf, true, 0.0, 1.0, [0.0; 2]) - origin.y).abs() < 1e-2, "rotation {rotation}: left ruler 0"); - let dir = if flip { -1.0 } else { 1.0 }; - assert!((ruler_pos(&xf, false, 500.0, 1.0, [0.0; 2]) - origin.x - dir * 250.0).abs() < 1e-2, "rotation {rotation}: top scale"); - assert!((ruler_pos(&xf, true, 500.0, 1.0, [0.0; 2]) - origin.y - 250.0).abs() < 1e-2, "rotation {rotation}: left scale"); - } - } - // Distances left of / above the origin read without a minus sign, as in Photoshop. - let xf = ViewXform { rect, zoom: 0.5, center: [0.0, 0.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, [0.0; 2]); - assert!(u0 < -500.0 && u1 > 500.0, "the view spans the origin: {u0}..{u1}"); - for (step, whole) in [(100.0, true), (100.0, false), (0.25, false)] { - let mut v = (u0 / step).floor() * step; - while v <= u1 { - let s = ruler_label(v, step, whole); - assert!(!s.contains('-'), "tick {v} (step {step}) is labelled {s:?}"); - v += step; - } - } - assert_eq!(ruler_label(-500.0, 100.0, true), "500"); - assert_eq!(ruler_label(-0.25, 0.25, false), "0.25"); - } - - /// #2955 with #3233: a zero point moved off the image's top-left reads 0 where the canvas draws - /// it, also on a rotated or flipped view, and the ruler keeps its full length and scale. - #[test] - fn rulers_count_from_the_zero_point_on_a_rotated_view() { - let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); - let (a, b) = (rect.left_top(), rect.right_top()); - let zero = [300.0, 120.0]; - for rotation in [0.0f32, 30.0, 90.0, -119.0] { - for flip in [false, true] { - let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip, rotation, aspect: 1.0 }; - let at = xf.to_screen(zero[0] as f32, zero[1] as f32); - assert!((ruler_pos(&xf, false, 0.0, 1.0, zero) - at.x).abs() < 1e-2, "rotation {rotation}: top ruler 0"); - assert!((ruler_pos(&xf, true, 0.0, 1.0, zero) - at.y).abs() < 1e-2, "rotation {rotation}: left ruler 0"); - let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, zero); - assert!((u1 - u0 - 1600.0).abs() < 1e-2, "rotation {rotation}: top ruler covers {u0}..{u1}"); - let dir = if flip { -1.0 } else { 1.0 }; - assert!((ruler_pos(&xf, false, 500.0, 1.0, zero) - at.x - dir * 250.0).abs() < 1e-2, "rotation {rotation}: top scale"); - } - } - // Unrotated, ruler value u sits over document x = zero + u. - let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip: false, rotation: 0.0, aspect: 1.0 }; - assert!((ruler_pos(&xf, false, -300.0, 1.0, zero) - xf.to_screen(0.0, 0.0).x).abs() < 1e-2); - assert!((ruler_pos(&xf, true, 80.0, 1.0, zero) - xf.to_screen(0.0, 200.0).y).abs() < 1e-2); - } - - /// #3277: guides belong to the document, so a rotated view draws them along the document - /// line; unrotated they still span the whole clip rect. - #[test] - fn guides_turn_with_a_rotated_view() { - let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); - let level = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let [a, b] = guide_segment(&level, rect, true, 500.0); - assert!((a.x - b.x).abs() < 1e-3 && (a.y - rect.top()).abs() < 1e-3 && (b.y - rect.bottom()).abs() < 1e-3, "{a:?} {b:?}"); - for rotation in [30.0f32, 90.0, -119.0] { - let xf = ViewXform { rotation, ..level }; - for (vertical, pos) in [(true, 500.0), (false, 900.0)] { - for end in guide_segment(&xf, rect, vertical, pos) { - let d = xf.to_doc(end); - let on_line = if vertical { d[0] } else { d[1] }; - assert!((on_line - pos).abs() < 1e-2, "rotation {rotation}: {end:?} maps to {d:?}, off the guide at {pos}"); - } - } - } - } - - /// The cursor over a guide turns with the view as the guide does: on a view turned 90°, a - /// vertical guide shows as a horizontal line and moves up and down. - #[test] - fn guide_cursors_turn_with_a_rotated_view() { - use egui::CursorIcon::{ResizeHorizontal as H, ResizeNeSw as NeSw, ResizeNwSe as NwSe, ResizeVertical as V}; - let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); - let level = ViewXform { rect, zoom: 1.0, center: [400.0, 300.0], flip: false, rotation: 0.0, aspect: 1.0 }; - // View rotation, flip → the cursor over a vertical guide, over a horizontal guide. - for (rotation, flip, want) in [(0.0, false, [H, V]), (90.0, false, [V, H]), (45.0, false, [NwSe, NeSw]), (0.0, true, [H, V])] { - let xf = ViewXform { rotation, flip, ..level }; - assert_eq!([guide_cursor(&xf, true), guide_cursor(&xf, false)], want, "view turned {rotation}°, flip {flip}"); - } - } - - #[test] - fn ruler_range_is_normalised_when_flipped() { - // #1814: with View > Flip Horizontal, `to_doc` negates x, so the raw - // (d0, d1) comes out reversed. ruler_range must normalise to (min, max) - // so the tick loop still runs. Exercises the production helper. - let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); - let top = Rect::from_min_size(rect.min, vec2(rect.width(), RULER)); - for flip in [false, true] { - let xf = ViewXform { rect, zoom: 1.0, center: [400.0, 300.0], flip, rotation: 0.0, aspect: 1.0 }; - let (u0, u1) = ruler_range(&xf, top.left_top(), top.right_top(), 0, 1.0, [0.0; 2]); - assert!(u0 <= u1, "flip={flip}: u0 ({u0}) must be <= u1 ({u1})"); - assert!(u1 - u0 > 0.0, "flip={flip}: range is empty"); - } - } - - /// #5698: as in Photoshop, an Alt-drag out of the top ruler makes a vertical guide and one out - /// of the left ruler a horizontal guide; without Alt each ruler makes its own kind. - #[test] - fn alt_drags_a_guide_of_the_other_orientation_out_of_a_ruler() { - let full = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); - let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); - let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let drag = |from: Pos2, modifiers: egui::Modifiers| { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); - let mut h = egui_kittest::Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), app); - let to = xf.to_screen(37.0, 90.0); - h.event_modifiers(egui::Event::PointerMoved(from), modifiers); - h.event_modifiers(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }, modifiers); - h.run_steps(1); - h.event_modifiers(egui::Event::PointerMoved(to), modifiers); - h.run_steps(1); - h.event_modifiers(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }, modifiers); - h.run_steps(2); - let g = &h.state().session.active().unwrap().doc.guides; - (g.vertical.clone(), g.horizontal.clone()) - }; - let (top, left) = (pos2(200.0, RULER / 2.0), pos2(RULER / 2.0, 150.0)); - assert_eq!(drag(top, egui::Modifiers::NONE), (vec![], vec![90.0]), "top ruler: horizontal"); - assert_eq!(drag(left, egui::Modifiers::NONE), (vec![37.0], vec![]), "left ruler: vertical"); - assert_eq!(drag(top, egui::Modifiers::ALT), (vec![37.0], vec![]), "Alt from the top ruler: vertical"); - assert_eq!(drag(left, egui::Modifiers::ALT), (vec![], vec![90.0]), "Alt from the left ruler: horizontal"); - } - - /// #6286: a guide let go over a ruler is removed, whichever ruler it is. The top ruler measures - /// document x and the left one y, so a horizontal guide released on the left ruler is still - /// inside the document on its own axis, and used to be placed instead of discarded. - #[test] - fn a_guide_dropped_on_either_ruler_is_removed() { - let new_app = || { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); - app.ui.extras.rulers = true; - // No snapping, so a guide that is kept lands exactly where it is let go. - app.ui.extras.snap = false; - app - }; - let drag = |from: Pos2, to: Pos2| { - let (mut h, _, _) = ruler_harness(new_app()); - h.event(egui::Event::PointerMoved(from)); - press(&mut h, from, true, egui::Modifiers::NONE); - h.event(egui::Event::PointerMoved(to)); - h.run_steps(1); - press(&mut h, to, false, egui::Modifiers::NONE); - let g = &h.state().session.active().unwrap().doc.guides; - (g.vertical.clone(), g.horizontal.clone()) - }; - // #5698: out of the top ruler is a horizontal guide, out of the left one a vertical guide. - let (top, left) = (pos2(200.0, RULER / 2.0), pos2(RULER / 2.0, 150.0)); - assert_eq!(drag(top, left), (vec![], vec![]), "out of the top ruler, released on the left ruler"); - assert_eq!(drag(left, top), (vec![], vec![]), "out of the left ruler, released on the top ruler"); - // Released on the canvas the guide lands where it was let go, as before. - assert_eq!(drag(top, pos2(200.0, 150.0)), (vec![], vec![56.0]), "released on the canvas"); - assert_eq!(drag(left, pos2(120.0, 150.0)), (vec![40.0], vec![]), "released on the canvas"); - } - - /// #6286: the guide is removed when it is let go over a ruler, and moved when it is not. The - /// release can be inside the document on the guide's own axis and still be a ruler drop, so the - /// two are told apart by where the pointer is, not by the position it reads. - #[test] - fn a_guide_let_go_on_a_ruler_is_removed_not_moved() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); - app.sync_views(); - let horizontal = |app: &PhotocraftApp| app.session.active().unwrap().doc.guides.horizontal.clone(); - for drag in [ - GuideDrag { vertical: false, index: Some(0), pos: 50.0, press: 10.0, over_ruler: true }, - // Dragged sideways onto the left ruler, a horizontal guide holds its y, which on its own - // reads as a click: the ruler still removes it. - GuideDrag { vertical: false, index: Some(0), pos: 50.0, press: 50.0, over_ruler: true }, - ] { - app.run("view.newGuide", json!({"orientation": "horizontal", "position": 50})).unwrap(); - finish_drag(&mut app, drag); - assert!(horizontal(&app).is_empty(), "let go on a ruler: removed, {drag:?}"); - } - app.run("view.newGuide", json!({"orientation": "horizontal", "position": 50})).unwrap(); - finish_drag(&mut app, GuideDrag { vertical: false, index: Some(0), pos: 80.0, press: 10.0, over_ruler: false }); - assert_eq!(horizontal(&app), vec![80.0], "let go on the canvas: moved"); - // Clicked where it was pressed, on the canvas: selected and kept, as before. - finish_drag(&mut app, GuideDrag { vertical: false, index: Some(0), pos: 80.0, press: 80.0, over_ruler: false }); - assert_eq!(horizontal(&app), vec![80.0], "clicked on the canvas: kept"); - assert!(app.ui.selected_guide.is_some(), "clicked on the canvas: selected"); - } - - /// The ruler bands are the strips the rulers take off the canvas rect, and only while the rulers - /// are shown: with them hidden the whole canvas rect is canvas (#6286). - #[test] - fn only_the_ruler_bands_count_as_a_ruler() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let full = Rect::from_min_size(pos2(16.0, 42.0), vec2(968.0, 642.0)); - let content = Rect::from_min_size(pos2(32.0, 58.0), vec2(952.0, 626.0)); - app.ui.extras.rulers = true; - assert!(dropped_on_a_ruler(&app, full, pos2(full.min.x + RULER / 2.0, 371.0)), "the left ruler"); - assert!(dropped_on_a_ruler(&app, full, pos2(508.0, full.min.y + RULER / 2.0)), "the top ruler"); - assert!(dropped_on_a_ruler(&app, full, full.min), "the ruler corner"); - assert!(!dropped_on_a_ruler(&app, full, pos2(508.0, 371.0)), "the canvas"); - assert!(!dropped_on_a_ruler(&app, full, content.min), "the canvas' own top-left corner"); - assert!(!dropped_on_a_ruler(&app, full, pos2(content.min.x + 0.5, 371.0)), "the first canvas column"); - assert!(!dropped_on_a_ruler(&app, full, pos2(508.0, content.min.y + 0.5)), "the first canvas row"); - assert!(!dropped_on_a_ruler(&app, full, pos2(full.min.x - 1.0, 371.0)), "outside the canvas rect"); - app.ui.extras.rulers = false; - for p in [pos2(full.min.x + RULER / 2.0, 371.0), pos2(508.0, full.min.y + RULER / 2.0), full.min] { - assert!(!dropped_on_a_ruler(&app, full, p), "rulers hidden: no band at {p:?}"); - } - } - - /// The canvas the guides live on, rulers on, at 100 %. - fn tool_canvas_harness(tool: crate::state::Tool) -> egui_kittest::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 = true; - app.ui.extras.snap = false; - app.ui.tool = tool; - let mut h = egui_kittest::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::ALL[0]); - h.run_steps(4); - let v = &mut h.state_mut().ui.views[0]; - v.zoom = 1.0; - v.center = [200.0, 150.0]; - v.fit_pending = false; - h.run_steps(2); - h - } - - /// #6286: an existing guide dragged onto a ruler with the Move tool is deleted, though the - /// release is inside the document on the guide's own axis: the left ruler measures y, so a - /// horizontal guide let go there still reads a y inside the canvas and used to be moved. Held - /// level, that release reads as a click on the guide, which a ruler drop also outranks. - #[test] - fn a_guide_dragged_onto_a_ruler_is_deleted_through_the_canvas() { - for below in [50.0f32, 0.0] { - let mut h = tool_canvas_harness(crate::state::Tool::Move); - h.state_mut().run("view.newGuide", json!({"orientation": "horizontal", "position": 150})).unwrap(); - h.run_steps(1); - let at = |h: &egui_kittest::Harness<'static, PhotocraftApp>, x: f32, y: f32| { - let app = h.state(); - let v = &app.ui.views[0]; - let xf = ViewXform { - rect: content_rect(app, app.last_canvas_rect), - zoom: v.zoom, - center: v.center, - flip: app.ui.view.flip_horizontal, - rotation: v.rotation, - aspect: app.ui.view.display_aspect(), - }; - xf.to_screen(x, y) - }; - let on_the_guide = at(&h, 200.0, 150.0); - // In the left ruler's band, `below` document px under the press: inside the canvas on the - // guide's own axis, which is where the old code moved the guide instead of removing it. - let canvas = h.state().last_canvas_rect; - let onto_the_left_ruler = pos2(canvas.min.x + RULER / 2.0, on_the_guide.y + below); - // Along the guide, so a held-level release keeps its y, the way a sideways drag does. - let dragged = pos2(on_the_guide.x - 12.0, on_the_guide.y); - h.event(egui::Event::PointerMoved(on_the_guide)); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: on_the_guide, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); - h.run_steps(1); - // Past egui's click distance, so the drag starts at the press, on the guide. - h.event(egui::Event::PointerMoved(dragged)); - h.run_steps(2); - assert!(h.state().guide_drag.is_some(), "the Move tool takes the guide"); - h.event(egui::Event::PointerMoved(onto_the_left_ruler)); - h.run_steps(1); - h.event(egui::Event::PointerButton { - pos: onto_the_left_ruler, - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }); - h.run_steps(2); - let g = &h.state().session.active().unwrap().doc.guides; - assert!(g.horizontal.is_empty(), "{below} px below the press, released on the left ruler: got {:?}", g.horizontal); - assert!(h.state().guide_drag.is_none(), "the drag is over"); - } - } - - /// #3770: a guide Shift-dragged out of a ruler lands on the nearest tick the ruler draws - /// (tenths of the labelled step, in the ruler unit); without Shift it lands where it's dropped. - #[test] - fn shift_dragged_guides_land_on_ruler_ticks() { - let full = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); - let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); - let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let new_app = || { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); - app - }; - let drag_guide = |modifiers: egui::Modifiers| { - let builder = egui_kittest::Harness::builder().with_size(vec2(400.0, 300.0)); - let mut h = builder.build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), new_app()); - // Out of the left ruler: a vertical guide, dropped at document x = 37. - let (from, to) = (pos2(RULER / 2.0, 100.0), xf.to_screen(37.0, 64.0)); - h.event_modifiers(egui::Event::PointerMoved(from), modifiers); - h.event_modifiers(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }, modifiers); - h.run_steps(1); - h.event_modifiers(egui::Event::PointerMoved(to), modifiers); - h.run_steps(1); - h.event_modifiers(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }, modifiers); - h.run_steps(2); - h.state().session.active().unwrap().doc.guides.vertical.clone() - }; - assert_eq!(drag_guide(egui::Modifiers::NONE), vec![37.0]); - // #5698: Alt turns it into a horizontal guide (at the drop's y, the document's centre). - assert_eq!(drag_guide(egui::Modifiers::ALT), Vec::::new(), "no vertical guide with Alt"); - // Pixels at 100%: labels every 100 px, ticks every 10 px. - assert_eq!(drag_guide(egui::Modifiers::SHIFT), vec![40.0]); - - let mut app = new_app(); - // At 200% the labels are every 50 px, so the ticks every 5 px. - assert_eq!(snap_to_tick(&app, &ViewXform { zoom: 2.0, ..xf }, true, 37.0), 35.0); - // Percent of each side: ticks every 2.5% of 256 px across, every 5% of 128 px down. - app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "percent"})).unwrap(); - assert!((snap_to_tick(&app, &xf, true, 37.0) - 38.4).abs() < 1e-9); - assert!((snap_to_tick(&app, &xf, false, 37.0) - 38.4).abs() < 1e-9); - // Ticks count from the zero point (#2955): a vertical guide follows the x origin only. - let mut app = new_app(); - app.run("view.setRulerOrigin", json!({"x": 3, "y": 0})).unwrap(); - assert_eq!(snap_to_tick(&app, &xf, true, 37.0), 33.0); - assert_eq!(snap_to_tick(&app, &xf, false, 37.0), 40.0); - } -} +mod tests; diff --git a/crates/ui-egui/src/rulers/tests.rs b/crates/ui-egui/src/rulers/tests.rs new file mode 100644 index 0000000000..33684c9b7f --- /dev/null +++ b/crates/ui-egui/src/rulers/tests.rs @@ -0,0 +1,868 @@ +use super::*; + +#[test] +fn ruler_ticks_labels_and_pointer_stay_out_of_the_origin_corner() { + let mut failures = Vec::new(); + for theme in crate::theme::ThemeKind::ALL { + for (zoom, flip, rotation, width) in [(1.0, false, 0.0, 560.0), (1.0, false, 0.0, 800.0), (0.25, true, 0.0, 560.0), (2.0, false, 30.0, 560.0)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + let full = Rect::from_min_size(pos2(32.0, 32.0), vec2(width - 80.0, 320.0)); + let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)); + let builder = egui_kittest::Harness::builder().with_size(vec2(width, 400.0)); + let mut h = builder.build_ui_state( + move |ui, app| { + let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); + let xf = ViewXform { rect, zoom, center: [(width - 80.0) / 2.0, 160.0], flip, rotation, aspect: 1.0 }; + draw_rulers(app, ui, full, &xf); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, theme); + h.event(egui::Event::PointerMoved(corner.center())); + h.run_steps(4); + let mut ticks = 0; + let mut labels = 0; + for shape in &h.output().shapes { + if matches!(shape.shape, egui::Shape::LineSegment { .. } | egui::Shape::Text(_)) { + ticks += usize::from(matches!(shape.shape, egui::Shape::LineSegment { .. })); + labels += usize::from(matches!(shape.shape, egui::Shape::Text(_))); + let visible = shape.shape.visual_bounding_rect().intersect(shape.clip_rect); + if visible.intersect(corner.shrink(0.5)).is_positive() { + failures.push(format!("{theme:?}: zoom={zoom}, flip={flip}, rotation={rotation}, {visible:?}")); + } + } + } + assert!(ticks > 2 && labels > 0, "rulers still draw ticks and labels"); + } + } + assert!(failures.is_empty(), "ruler drawing overlaps the origin corner: {failures:?}"); +} + +/// #7314: the stacked characters of the left ruler's labels are centred on the strip, so a +/// narrow "1" lines up with a wide "0". +#[test] +fn left_ruler_label_characters_are_centred() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + let (mut h, full, _) = ruler_harness(app); + h.run_steps(2); + let centres: Vec = h + .output() + .shapes + .iter() + .filter_map(|s| if let egui::Shape::Text(t) = &s.shape { Some(t) } else { None }) + .filter(|t| t.pos.x < full.min.x + RULER && t.pos.y > full.min.y + RULER) + .map(|t| t.pos.x + t.galley.size().x * 0.5) + .collect(); + assert!(centres.len() > 2, "the left ruler draws labels: {centres:?}"); + for c in ¢res { + assert!((c - (full.min.x + RULER * 0.5)).abs() < 0.01, "character centre {c} in {centres:?}"); + } +} + +#[test] +fn shift_snaps_the_zero_point_to_ruler_ticks_from_the_current_origin() { + assert_eq!(snap_px_to_tick(47.0, 0.0, 10.0), 50.0); + assert_eq!(snap_px_to_tick(44.9, 0.0, 10.0), 40.0); + // Ticks run from the current zero point, so they sit at 3 + 10k. + assert_eq!(snap_px_to_tick(47.0, 3.0, 10.0), 43.0); + assert_eq!(snap_px_to_tick(-8.0, 3.0, 10.0), -7.0); + // A degenerate tick never panics or moves the point. + for tick in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert_eq!(snap_px_to_tick(47.5, 3.0, tick), 47.5); + } +} + +/// Rulers alone in a 400×300 frame at 100 %, centred on a 256×128 document. +fn ruler_harness(app: PhotocraftApp) -> (egui_kittest::Harness<'static, PhotocraftApp>, Rect, ViewXform) { + let full = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)); + let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); + let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let h = egui_kittest::Harness::builder() + .with_size(vec2(400.0, 300.0)) + .with_step_dt(1.0 / 60.0) + .build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), app); + (h, full, xf) +} + +fn press(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, pos: Pos2, pressed: bool, modifiers: egui::Modifiers) { + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }); + h.run_steps(2); +} + +fn drag_corner_to(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, full: Rect, to: Pos2, modifiers: egui::Modifiers) { + let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center(); + h.event(egui::Event::ModifiersChanged(modifiers)); + h.event(egui::Event::PointerMoved(corner)); + h.run_steps(1); + press(h, corner, true, modifiers); + for p in [corner + vec2(10.0, 10.0), to] { + h.event(egui::Event::PointerMoved(p)); + h.run_steps(2); + } + press(h, to, false, modifiers); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(1); +} + +fn origin(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> [f64; 2] { + h.state().session.active().unwrap().doc.ruler_origin +} + +/// #2955: dragging out of the ruler corner sets the zero point (cross hairs while dragging), +/// the rulers then read 0 there, Shift snaps it to a tick, and double-clicking the corner +/// resets it. +#[test] +fn dragging_the_ruler_corner_sets_the_zero_point_and_double_click_resets_it() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + app.ui.extras.snap = false; + let (mut h, full, xf) = ruler_harness(app); + h.run_steps(2); + let target = xf.to_screen(100.0, 40.0); + drag_corner_to(&mut h, full, target, egui::Modifiers::NONE); + let o = origin(&h); + assert!((o[0] - 100.0).abs() < 0.01 && (o[1] - 40.0).abs() < 0.01, "zero point lands under the pointer: {o:?}"); + // The top ruler's "0" now sits at the new zero point, "100" (a distance, unsigned as in + // Photoshop) at the image's left edge. + h.run_steps(2); + let labels: Vec<(String, f32)> = h + .output() + .shapes + .iter() + .filter_map(|s| if let egui::Shape::Text(t) = &s.shape { Some((t.galley.text().to_string(), t.pos.x)) } else { None }) + .collect(); + let near = |text: &str, x: f32| labels.iter().any(|(t, lx)| t == text && (lx - (x + 2.0)).abs() < 1.0); + assert!(near("0", target.x), "a 0 label at the zero point: {labels:?}"); + assert!(near("100", xf.to_screen(0.0, 0.0).x), "100 at the image's left edge: {labels:?}"); + + // Mid-drag, cross hairs run through the pointer across the canvas. + let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center(); + let mid = xf.to_screen(150.0, 90.0); + press(&mut h, corner, true, egui::Modifiers::NONE); + for p in [corner + vec2(10.0, 10.0), mid] { + h.event(egui::Event::PointerMoved(p)); + h.run_steps(2); + } + let crosshair = h.output().shapes.iter().any(|s| { + matches!(s.shape, egui::Shape::LineSegment { points: [a, b], .. } if (a.x - mid.x).abs() < 0.5 && (b.x - mid.x).abs() < 0.5 && (b.y - a.y).abs() > 200.0) + }); + assert!(crosshair, "a vertical cross-hair line through the pointer while dragging"); + assert_eq!(origin(&h), o, "the zero point moves on release only"); + press(&mut h, mid, false, egui::Modifiers::NONE); + assert_eq!(origin(&h), [150.0, 90.0]); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(origin(&h), o, "setting the zero point is undoable"); + + // A drag dropped back on the corner leaves it alone. + drag_corner_to(&mut h, full, full.min + vec2(4.0, 4.0), egui::Modifiers::NONE); + assert_eq!(origin(&h), o); + + // Shift: ticks are 10 px apart at 100 %, measured from the current zero point (100, 40). + drag_corner_to(&mut h, full, xf.to_screen(123.0, 57.0), egui::Modifiers::SHIFT); + assert_eq!(origin(&h), [120.0, 60.0]); + + for _ in 0..40 { + h.step(); + } + let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center(); + h.event(egui::Event::PointerMoved(corner)); + h.step(); + for _ in 0..2 { + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: corner, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.step(); + } + } + h.run_steps(2); + assert_eq!(origin(&h), [0.0, 0.0], "double-clicking the corner resets the zero point"); +} + +/// #2955: the Info panel's X/Y are measured from the rulers' zero point. +#[test] +fn info_panel_position_reads_from_the_zero_point() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("view.setRulerOrigin", json!({"x": 20, "y": 5})).unwrap(); + app.hover_doc = Some([50.5, 20.5]); + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(260.0, 240.0)) + .build_ui_state(|ui, app| crate::panels::dock_body(app, ui, crate::dock::Group::Navigator, 2), app); + h.run_steps(2); + assert!(h.query_by_label("30").is_some() && h.query_by_label("15").is_some(), "X 30, Y 15 from the zero point at (20, 5)"); + assert!(h.query_by_label("50").is_none(), "not the raw image x"); +} + +/// #5728: dragging a guide shows its coordinate in the Info panel on one axis only. +#[test] +fn info_panel_shows_guide_drag_position_outside_canvas() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.hover_doc = None; + app.guide_drag = Some(GuideDrag { vertical: true, index: None, pos: 42.0, press: 42.0, over_ruler: false }); + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(260.0, 240.0)) + .build_ui_state(|ui, app| crate::panels::dock_body(app, ui, crate::dock::Group::Navigator, 2), app); + h.run_steps(2); + assert!(h.query_by_label("42").is_some(), "vertical guide: X readout"); + h.state_mut().guide_drag = Some(GuideDrag { vertical: false, index: None, pos: 17.0, press: 17.0, over_ruler: false }); + h.run_steps(2); + assert!(h.query_by_label("17").is_some(), "horizontal guide: Y readout"); +} + +/// A dragged guide shows its position beside the pointer: X for a vertical guide, Y for a +/// horizontal one, from the zero point, in the ruler unit (pixels to one decimal). +#[test] +fn guide_drag_shows_its_position_beside_the_pointer() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let v = GuideDrag { vertical: true, index: Some(0), pos: 103.24, press: 50.0, over_ruler: false }; + assert_eq!(guide_drag_readout(&app, v), Some(("X:", "103.2 px".to_owned()))); + let h = GuideDrag { vertical: false, index: None, pos: 40.0, press: 40.0, over_ruler: false }; + assert_eq!(guide_drag_readout(&app, h), Some(("Y:", "40 px".to_owned()))); + app.run("view.setRulerOrigin", json!({"x": 3.0, "y": 10.0})).unwrap(); + assert_eq!(guide_drag_readout(&app, h), Some(("Y:", "30 px".to_owned())), "from the zero point"); + app.run("view.resetRulerOrigin", json!({})).unwrap(); + app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "percent"})).unwrap(); + assert_eq!(guide_drag_readout(&app, GuideDrag { vertical: true, index: None, pos: 103.0, press: 0.0, over_ruler: false }).map(|r| r.0), Some("X:")); + app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "pixels"})).unwrap(); + + app.guide_drag = Some(v); + let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 200.0)).build_ui_state(|ui, app| draw_guide_drag_readout(app, ui.ctx()), app); + h.event(egui::Event::PointerMoved(pos2(50.0, 50.0))); + h.run_steps(2); + assert!(h.query_by_label("X:").is_some() && h.query_by_label("103.2 px").is_some()); + h.state_mut().guide_drag = None; + h.run_steps(2); + assert!(h.query_by_label("X:").is_none(), "no readout once the drag ends"); +} + +type AppHarness = egui_kittest::Harness<'static, PhotocraftApp>; + +/// The real canvas on a 400 × 300 document with a horizontal guide at y = 100, at 100 %, +/// with the Move tool and snapping off. +fn canvas_harness(rulers: bool) -> AppHarness { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 100})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = rulers; + app.ui.extras.snap = false; + app.ui.tool = crate::state::Tool::Move; + let mut h = egui_kittest::Harness::builder().with_size(vec2(800.0, 600.0)).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::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + (v.zoom, v.center, v.fit_pending) = (1.0, [200.0, 150.0], false); + h.run_steps(2); + h +} + +/// Screen point of document point `(x, y)` in [`canvas_harness`]. +fn canvas_at(h: &AppHarness, x: f32, y: f32) -> Pos2 { + let app = h.state(); + let v = &app.ui.views[0]; + let rect = content_rect(app, app.last_canvas_rect); + ViewXform { rect, zoom: v.zoom, center: v.center, flip: false, rotation: 0.0, aspect: 1.0 }.to_screen(x, y) +} + +/// Moving a horizontal guide with the Move tool on the real canvas: `Y:` follows the pointer. +#[test] +fn moving_a_guide_on_the_canvas_shows_its_y() { + use egui_kittest::kittest::Queryable; + let mut h = canvas_harness(false); + let at = canvas_at; + let press = at(&h, 200.0, 100.0); + h.event(egui::Event::PointerMoved(press)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: press, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + for y in [110.0, 125.0, 140.0] { + h.event(egui::Event::PointerMoved(at(&h, 210.0, y))); + h.run_steps(2); + } + assert!(h.state().guide_drag.is_some_and(|d| !d.vertical), "a horizontal guide is being dragged"); + assert!(h.query_by_label("Y:").is_some() && h.query_by_label("140 px").is_some(), "Y readout at the guide"); + assert!(h.query_by_label("X:").is_none()); + let up = at(&h, 210.0, 140.0); + h.event(egui::Event::PointerButton { pos: up, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(2); + assert_eq!(h.state().session.active().unwrap().doc.guides.horizontal, vec![140.0]); + assert!(h.query_by_label("Y:").is_none(), "gone after the drop"); +} + +/// A guide dragged out of the top ruler: in each frame the readout shows where the guide is +/// after that frame's pointer move (the ruler handles the drag after the canvas is drawn), and +/// the frame that drops it shows none. +#[test] +fn ruler_drag_readout_is_current_every_frame() { + use egui_kittest::kittest::Queryable; + let mut h = canvas_harness(true); + let from = pos2(canvas_at(&h, 200.0, 0.0).x, h.state().last_canvas_rect.top() + RULER / 2.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); + for y in [40.0, 60.0, 75.0] { + h.event(egui::Event::PointerMoved(canvas_at(&h, 200.0, y))); + // egui 0.37 lays an Area's contents out a pass after it is shown; step to the settled + // frame with the pointer still at `y` (readout included) rather than the first pass. + h.run_steps(2); + let pos = h.state().guide_drag.map(|d| d.pos); + assert_eq!(pos, Some(f64::from(y)), "the drag follows the pointer"); + assert!(h.query_by_label(&format!("{y} px")).is_some(), "readout at {y} in the same frame"); + } + let up = canvas_at(&h, 200.0, 75.0); + h.event(egui::Event::PointerButton { pos: up, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(2); + assert!(h.state().guide_drag.is_none()); + assert!(h.query_by_label("Y:").is_none(), "no readout in the frame that drops the guide"); + assert!(h.state().session.active().unwrap().doc.guides.horizontal.contains(&75.0), "the guide lands at y = 75"); +} + +#[test] +fn percentage_grid_spacing_uses_both_canvas_dimensions() { + let mut g = GuidesGridAndSlices { grid_unit: Unit::Percent, gridline_every: 20.0, subdivisions: 2, ..Default::default() }; + assert_eq!(grid_major_px(&g, 72.0, [1280.0, 720.0], 72.0), [256.0, 144.0]); + // Absolute units remain equal on both axes, irrespective of aspect ratio. + g.grid_unit = Unit::Pixels; + g.gridline_every = 100.0; + assert_eq!(grid_major_px(&g, 72.0, [1280.0, 720.0], 72.0), [100.0, 100.0]); +} + +#[test] +fn unit_steps_allow_fractions() { + assert_eq!(nice_step(0.3, false), 0.5); + assert_eq!(nice_step(0.2, false), 0.2); + assert_eq!(nice_step(0.22, false), 0.25); + assert_eq!(nice_step(0.3, true), 1.0); + assert_eq!(nice_step(23.0, true), 50.0); +} + +#[test] +fn ticks_follow_1_2_5_series() { + assert_eq!(tick_step(1.0), 100.0); + assert_eq!(tick_step(0.1), 1000.0); + assert_eq!(tick_step(4.0), 20.0); + assert_eq!(tick_step(64.0), 1.0); + assert_eq!(tick_step(0.25), 500.0); +} + +#[test] +fn hidden_guides_are_not_hit_tested() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.sync_views(); + app.session.execute("view.newGuide", json!({"orientation": "vertical", "position": 50})).unwrap(); + app.session.execute("view.newGuide", json!({"orientation": "horizontal", "position": 25})).unwrap(); + let positions = app.session.active().unwrap().doc.guides.clone(); + + // Visible, unlocked guides remain interactive in either orientation. + assert_eq!(guide_at(&app, 50.0, 10.0), Some((true, 0))); + assert_eq!(guide_at(&app, 10.0, 25.0), Some((false, 0))); + + // All ways to hide the canvas guides must also disable hit testing. + app.ui.extras.guides = false; + assert_eq!(guide_at(&app, 50.0, 10.0), None); + assert_eq!(guide_at(&app, 10.0, 25.0), None); + app.ui.extras.guides = true; + + app.ui.view.show.canvas_guides = false; + assert_eq!(guide_at(&app, 50.0, 10.0), None); + assert_eq!(guide_at(&app, 10.0, 25.0), None); + app.ui.view.show.canvas_guides = true; + + app.ui.view.extras = false; + assert_eq!(guide_at(&app, 50.0, 10.0), None); + assert_eq!(guide_at(&app, 10.0, 25.0), None); + app.ui.view.extras = true; + + // Hiding/showing must not change the stored guide positions. + assert_eq!(app.session.active().unwrap().doc.guides, positions); + assert_eq!(guide_at(&app, 50.0, 10.0), Some((true, 0))); + assert_eq!(guide_at(&app, 10.0, 25.0), Some((false, 0))); + + app.ui.extras.lock_guides = true; + assert_eq!(guide_at(&app, 50.0, 10.0), None); + assert_eq!(guide_at(&app, 10.0, 25.0), None); +} + +#[test] +fn unit_menu_lists_every_unit_with_the_current_one_checked() { + let items = unit_menu_items(Unit::Inches, &UNITS); + assert_eq!(items.len(), Unit::NAMES.len()); + // Every unit is offered, labelled, and in the preference's order. + assert_eq!(items[0], ("Pixels".to_string(), "pixels", false)); + assert_eq!(items.iter().find(|(_, name, _)| *name == "cm").unwrap().0, "Centimeters"); + // Exactly the current unit is checked. + let checked: Vec<_> = items.iter().filter(|(_, _, c)| *c).map(|(_, name, _)| *name).collect(); + assert_eq!(checked, vec!["inches"]); +} + +#[test] +fn picking_a_ruler_unit_changes_the_preference() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + assert_eq!(app.session.prefs().units_and_rulers.rulers, Unit::Pixels); + // The context menu applies its pick exactly as the preference pane does. + app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "cm"})).unwrap(); + assert_eq!(app.session.prefs().units_and_rulers.rulers, Unit::Centimeters); +} + +/// View › Rulers is remembered: the next launch, and every document created or opened in it, +/// shows the rulers as last set, on or off (#2918). +#[test] +fn rulers_open_as_last_set_after_a_restart() { + use std::{cell::RefCell, rc::Rc}; + let saved = Rc::new(RefCell::new(None::)); + let launch = |saved: &Rc>>| { + let (load, store) = (saved.clone(), saved.clone()); + PhotocraftApp::new( + photocraft_engine::Session::new(), + crate::Services { + load_prefs: Some(Box::new(move || load.borrow().clone())), + save_prefs: Some(Box::new(move |text| { + *store.borrow_mut() = Some(text.to_string()); + Ok(()) + })), + ..Default::default() + }, + ) + }; + for on in [true, false] { + let mut app = launch(&saved); + assert_eq!(crate::menus::invoke(&mut app, &egui::Context::default(), "view.rulers", json!({})).unwrap(), json!(on)); + crate::prefs_ui::save_preferences(&mut app).unwrap(); + let mut next = launch(&saved); + next.session.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + next.sync_views(); + assert_eq!(next.ui.extras.rulers, on, "a new document after a restart shows the rulers as last set"); + } +} + +#[test] +fn guide_drags_create_move_and_delete() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.sync_views(); + finish_drag(&mut app, GuideDrag { vertical: true, index: None, pos: 50.0, press: 50.0, over_ruler: false }); + finish_drag(&mut app, GuideDrag { vertical: false, index: None, pos: 500.0, press: 500.0, over_ruler: false }); // off canvas: ignored + assert_eq!(app.session.active().unwrap().doc.guides.vertical, vec![50.0]); + assert!(app.session.active().unwrap().doc.guides.horizontal.is_empty()); + assert_eq!(guide_at(&app, 51.0, 10.0), Some((true, 0))); + finish_drag(&mut app, GuideDrag { vertical: true, index: Some(0), pos: 120.0, press: 50.0, over_ruler: false }); + assert_eq!(app.session.active().unwrap().doc.guides.vertical, vec![120.0]); + finish_drag(&mut app, GuideDrag { vertical: true, index: Some(0), pos: -30.0, press: 120.0, over_ruler: false }); + assert!(app.session.active().unwrap().doc.guides.vertical.is_empty()); + app.ui.extras.lock_guides = true; + assert_eq!(guide_at(&app, 0.0, 0.0), None); +} + +/// ⌘ is the Move tool with any tool, so a ⌘-drag over a guide moves the guide, never the layer +/// (#2690); with Lock Guides a ⌘-drag with a marquee moves the layer as before. +#[test] +fn command_drag_over_a_guide_moves_the_guide_with_any_tool() { + use crate::canvas::{ToolEvent, tool_event}; + use crate::state::Tool; + for (tool, locked) in [ + (Tool::Brush, false), + (Tool::Eraser, false), + (Tool::Gradient, false), + (Tool::Frame, false), + (Tool::Artboard, false), + (Tool::RectMarquee, false), + (Tool::Lasso, false), + (Tool::MagicWand, false), + (Tool::RectMarquee, true), + ] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 60, "background": "transparent"})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + app.ui.extras.lock_guides = locked; + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.session + .edit("paint", |doc, _| { + doc.layer_mut(layer).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(10, 10, 30, 30), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 50})).unwrap(); + let cmd = egui::Modifiers::COMMAND; + tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }, cmd); + tool_event(&mut app, ToolEvent::Move { x: 65.0, y: 40.0, pressure: 1.0 }, cmd); + tool_event(&mut app, ToolEvent::Up { x: 65.0, y: 40.0 }, cmd); + let doc = &app.session.active().unwrap().doc; + let moved = doc.layer(layer).unwrap().surface().unwrap().rgba(12, 12)[3] == 0.0; + if locked { + assert_eq!((doc.guides.vertical.clone(), moved), (vec![50.0], true), "{tool:?}, guides locked: the layer moves"); + } else { + assert_eq!((doc.guides.vertical.clone(), moved), (vec![65.0], false), "{tool:?}: the guide moves, the layer stays"); + } + } +} + +/// #3233: a rotated view keeps the rulers level and fully ticked at zoom scale. The top ruler +/// spans the same number of document pixels as the unrotated view, the ticks map back onto +/// its ends, and both rulers read 0 at the screen position of the (rotated) document origin, +/// as Photoshop does. +#[test] +fn rotated_view_keeps_full_rulers() { + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); + let (a, b) = (rect.left_top(), rect.right_top()); + for rotation in [0.0f32, 30.0, 45.0, 90.0, -119.0, 180.0] { + for flip in [false, true] { + let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip, rotation, aspect: 1.0 }; + let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, [0.0; 2]); + assert!((u1 - u0 - 1600.0).abs() < 1e-2, "rotation {rotation}: top ruler covers {u0}..{u1}"); + let (first, last) = if flip { (u1, u0) } else { (u0, u1) }; + assert!((ruler_pos(&xf, false, first, 1.0, [0.0; 2]) - a.x).abs() < 1e-2, "rotation {rotation}: first tick"); + assert!((ruler_pos(&xf, false, last, 1.0, [0.0; 2]) - b.x).abs() < 1e-2, "rotation {rotation}: last tick"); + // 0 at the projected origin, 500 document px = 500 × zoom screen px further on. + let origin = xf.to_screen(0.0, 0.0); + assert!((ruler_pos(&xf, false, 0.0, 1.0, [0.0; 2]) - origin.x).abs() < 1e-2, "rotation {rotation}: top ruler 0"); + assert!((ruler_pos(&xf, true, 0.0, 1.0, [0.0; 2]) - origin.y).abs() < 1e-2, "rotation {rotation}: left ruler 0"); + let dir = if flip { -1.0 } else { 1.0 }; + assert!((ruler_pos(&xf, false, 500.0, 1.0, [0.0; 2]) - origin.x - dir * 250.0).abs() < 1e-2, "rotation {rotation}: top scale"); + assert!((ruler_pos(&xf, true, 500.0, 1.0, [0.0; 2]) - origin.y - 250.0).abs() < 1e-2, "rotation {rotation}: left scale"); + } + } + // Distances left of / above the origin read without a minus sign, as in Photoshop. + let xf = ViewXform { rect, zoom: 0.5, center: [0.0, 0.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, [0.0; 2]); + assert!(u0 < -500.0 && u1 > 500.0, "the view spans the origin: {u0}..{u1}"); + for (step, whole) in [(100.0, true), (100.0, false), (0.25, false)] { + let mut v = (u0 / step).floor() * step; + while v <= u1 { + let s = ruler_label(v, step, whole); + assert!(!s.contains('-'), "tick {v} (step {step}) is labelled {s:?}"); + v += step; + } + } + assert_eq!(ruler_label(-500.0, 100.0, true), "500"); + assert_eq!(ruler_label(-0.25, 0.25, false), "0.25"); +} + +/// #2955 with #3233: a zero point moved off the image's top-left reads 0 where the canvas draws +/// it, also on a rotated or flipped view, and the ruler keeps its full length and scale. +#[test] +fn rulers_count_from_the_zero_point_on_a_rotated_view() { + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); + let (a, b) = (rect.left_top(), rect.right_top()); + let zero = [300.0, 120.0]; + for rotation in [0.0f32, 30.0, 90.0, -119.0] { + for flip in [false, true] { + let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip, rotation, aspect: 1.0 }; + let at = xf.to_screen(zero[0] as f32, zero[1] as f32); + assert!((ruler_pos(&xf, false, 0.0, 1.0, zero) - at.x).abs() < 1e-2, "rotation {rotation}: top ruler 0"); + assert!((ruler_pos(&xf, true, 0.0, 1.0, zero) - at.y).abs() < 1e-2, "rotation {rotation}: left ruler 0"); + let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, zero); + assert!((u1 - u0 - 1600.0).abs() < 1e-2, "rotation {rotation}: top ruler covers {u0}..{u1}"); + let dir = if flip { -1.0 } else { 1.0 }; + assert!((ruler_pos(&xf, false, 500.0, 1.0, zero) - at.x - dir * 250.0).abs() < 1e-2, "rotation {rotation}: top scale"); + } + } + // Unrotated, ruler value u sits over document x = zero + u. + let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip: false, rotation: 0.0, aspect: 1.0 }; + assert!((ruler_pos(&xf, false, -300.0, 1.0, zero) - xf.to_screen(0.0, 0.0).x).abs() < 1e-2); + assert!((ruler_pos(&xf, true, 80.0, 1.0, zero) - xf.to_screen(0.0, 200.0).y).abs() < 1e-2); +} + +/// #3277: guides belong to the document, so a rotated view draws them along the document +/// line; unrotated they still span the whole clip rect. +#[test] +fn guides_turn_with_a_rotated_view() { + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); + let level = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let [a, b] = guide_segment(&level, rect, true, 500.0); + assert!((a.x - b.x).abs() < 1e-3 && (a.y - rect.top()).abs() < 1e-3 && (b.y - rect.bottom()).abs() < 1e-3, "{a:?} {b:?}"); + for rotation in [30.0f32, 90.0, -119.0] { + let xf = ViewXform { rotation, ..level }; + for (vertical, pos) in [(true, 500.0), (false, 900.0)] { + for end in guide_segment(&xf, rect, vertical, pos) { + let d = xf.to_doc(end); + let on_line = if vertical { d[0] } else { d[1] }; + assert!((on_line - pos).abs() < 1e-2, "rotation {rotation}: {end:?} maps to {d:?}, off the guide at {pos}"); + } + } + } +} + +/// The cursor over a guide turns with the view as the guide does: on a view turned 90°, a +/// vertical guide shows as a horizontal line and moves up and down. +#[test] +fn guide_cursors_turn_with_a_rotated_view() { + use egui::CursorIcon::{ResizeHorizontal as H, ResizeNeSw as NeSw, ResizeNwSe as NwSe, ResizeVertical as V}; + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); + let level = ViewXform { rect, zoom: 1.0, center: [400.0, 300.0], flip: false, rotation: 0.0, aspect: 1.0 }; + // View rotation, flip → the cursor over a vertical guide, over a horizontal guide. + for (rotation, flip, want) in [(0.0, false, [H, V]), (90.0, false, [V, H]), (45.0, false, [NwSe, NeSw]), (0.0, true, [H, V])] { + let xf = ViewXform { rotation, flip, ..level }; + assert_eq!([guide_cursor(&xf, true), guide_cursor(&xf, false)], want, "view turned {rotation}°, flip {flip}"); + } +} + +#[test] +fn ruler_range_is_normalised_when_flipped() { + // #1814: with View > Flip Horizontal, `to_doc` negates x, so the raw + // (d0, d1) comes out reversed. ruler_range must normalise to (min, max) + // so the tick loop still runs. Exercises the production helper. + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)); + let top = Rect::from_min_size(rect.min, vec2(rect.width(), RULER)); + for flip in [false, true] { + let xf = ViewXform { rect, zoom: 1.0, center: [400.0, 300.0], flip, rotation: 0.0, aspect: 1.0 }; + let (u0, u1) = ruler_range(&xf, top.left_top(), top.right_top(), 0, 1.0, [0.0; 2]); + assert!(u0 <= u1, "flip={flip}: u0 ({u0}) must be <= u1 ({u1})"); + assert!(u1 - u0 > 0.0, "flip={flip}: range is empty"); + } +} + +/// #5698: as in Photoshop, an Alt-drag out of the top ruler makes a vertical guide and one out +/// of the left ruler a horizontal guide; without Alt each ruler makes its own kind. +#[test] +fn alt_drags_a_guide_of_the_other_orientation_out_of_a_ruler() { + let full = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); + let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let drag = |from: Pos2, modifiers: egui::Modifiers| { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), app); + let to = xf.to_screen(37.0, 90.0); + h.event_modifiers(egui::Event::PointerMoved(from), modifiers); + h.event_modifiers(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }, modifiers); + h.run_steps(1); + h.event_modifiers(egui::Event::PointerMoved(to), modifiers); + h.run_steps(1); + h.event_modifiers(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }, modifiers); + h.run_steps(2); + let g = &h.state().session.active().unwrap().doc.guides; + (g.vertical.clone(), g.horizontal.clone()) + }; + let (top, left) = (pos2(200.0, RULER / 2.0), pos2(RULER / 2.0, 150.0)); + assert_eq!(drag(top, egui::Modifiers::NONE), (vec![], vec![90.0]), "top ruler: horizontal"); + assert_eq!(drag(left, egui::Modifiers::NONE), (vec![37.0], vec![]), "left ruler: vertical"); + assert_eq!(drag(top, egui::Modifiers::ALT), (vec![37.0], vec![]), "Alt from the top ruler: vertical"); + assert_eq!(drag(left, egui::Modifiers::ALT), (vec![], vec![90.0]), "Alt from the left ruler: horizontal"); +} + +/// #6286: a guide let go over a ruler is removed, whichever ruler it is. The top ruler measures +/// document x and the left one y, so a horizontal guide released on the left ruler is still +/// inside the document on its own axis, and used to be placed instead of discarded. +#[test] +fn a_guide_dropped_on_either_ruler_is_removed() { + let new_app = || { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + app.ui.extras.rulers = true; + // No snapping, so a guide that is kept lands exactly where it is let go. + app.ui.extras.snap = false; + app + }; + let drag = |from: Pos2, to: Pos2| { + let (mut h, _, _) = ruler_harness(new_app()); + h.event(egui::Event::PointerMoved(from)); + press(&mut h, from, true, egui::Modifiers::NONE); + h.event(egui::Event::PointerMoved(to)); + h.run_steps(1); + press(&mut h, to, false, egui::Modifiers::NONE); + let g = &h.state().session.active().unwrap().doc.guides; + (g.vertical.clone(), g.horizontal.clone()) + }; + // #5698: out of the top ruler is a horizontal guide, out of the left one a vertical guide. + let (top, left) = (pos2(200.0, RULER / 2.0), pos2(RULER / 2.0, 150.0)); + assert_eq!(drag(top, left), (vec![], vec![]), "out of the top ruler, released on the left ruler"); + assert_eq!(drag(left, top), (vec![], vec![]), "out of the left ruler, released on the top ruler"); + // Released on the canvas the guide lands where it was let go, as before. + assert_eq!(drag(top, pos2(200.0, 150.0)), (vec![], vec![56.0]), "released on the canvas"); + assert_eq!(drag(left, pos2(120.0, 150.0)), (vec![40.0], vec![]), "released on the canvas"); +} + +/// #6286: the guide is removed when it is let go over a ruler, and moved when it is not. The +/// release can be inside the document on the guide's own axis and still be a ruler drop, so the +/// two are told apart by where the pointer is, not by the position it reads. +#[test] +fn a_guide_let_go_on_a_ruler_is_removed_not_moved() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.sync_views(); + let horizontal = |app: &PhotocraftApp| app.session.active().unwrap().doc.guides.horizontal.clone(); + for drag in [ + GuideDrag { vertical: false, index: Some(0), pos: 50.0, press: 10.0, over_ruler: true }, + // Dragged sideways onto the left ruler, a horizontal guide holds its y, which on its own + // reads as a click: the ruler still removes it. + GuideDrag { vertical: false, index: Some(0), pos: 50.0, press: 50.0, over_ruler: true }, + ] { + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 50})).unwrap(); + finish_drag(&mut app, drag); + assert!(horizontal(&app).is_empty(), "let go on a ruler: removed, {drag:?}"); + } + app.run("view.newGuide", json!({"orientation": "horizontal", "position": 50})).unwrap(); + finish_drag(&mut app, GuideDrag { vertical: false, index: Some(0), pos: 80.0, press: 10.0, over_ruler: false }); + assert_eq!(horizontal(&app), vec![80.0], "let go on the canvas: moved"); + // Clicked where it was pressed, on the canvas: selected and kept, as before. + finish_drag(&mut app, GuideDrag { vertical: false, index: Some(0), pos: 80.0, press: 80.0, over_ruler: false }); + assert_eq!(horizontal(&app), vec![80.0], "clicked on the canvas: kept"); + assert!(app.ui.selected_guide.is_some(), "clicked on the canvas: selected"); +} + +/// The ruler bands are the strips the rulers take off the canvas rect, and only while the rulers +/// are shown: with them hidden the whole canvas rect is canvas (#6286). +#[test] +fn only_the_ruler_bands_count_as_a_ruler() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let full = Rect::from_min_size(pos2(16.0, 42.0), vec2(968.0, 642.0)); + let content = Rect::from_min_size(pos2(32.0, 58.0), vec2(952.0, 626.0)); + app.ui.extras.rulers = true; + assert!(dropped_on_a_ruler(&app, full, pos2(full.min.x + RULER / 2.0, 371.0)), "the left ruler"); + assert!(dropped_on_a_ruler(&app, full, pos2(508.0, full.min.y + RULER / 2.0)), "the top ruler"); + assert!(dropped_on_a_ruler(&app, full, full.min), "the ruler corner"); + assert!(!dropped_on_a_ruler(&app, full, pos2(508.0, 371.0)), "the canvas"); + assert!(!dropped_on_a_ruler(&app, full, content.min), "the canvas' own top-left corner"); + assert!(!dropped_on_a_ruler(&app, full, pos2(content.min.x + 0.5, 371.0)), "the first canvas column"); + assert!(!dropped_on_a_ruler(&app, full, pos2(508.0, content.min.y + 0.5)), "the first canvas row"); + assert!(!dropped_on_a_ruler(&app, full, pos2(full.min.x - 1.0, 371.0)), "outside the canvas rect"); + app.ui.extras.rulers = false; + for p in [pos2(full.min.x + RULER / 2.0, 371.0), pos2(508.0, full.min.y + RULER / 2.0), full.min] { + assert!(!dropped_on_a_ruler(&app, full, p), "rulers hidden: no band at {p:?}"); + } +} + +/// The canvas the guides live on, rulers on, at 100 %. +fn tool_canvas_harness(tool: crate::state::Tool) -> egui_kittest::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 = true; + app.ui.extras.snap = false; + app.ui.tool = tool; + let mut h = egui_kittest::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::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = [200.0, 150.0]; + v.fit_pending = false; + h.run_steps(2); + h +} + +/// #6286: an existing guide dragged onto a ruler with the Move tool is deleted, though the +/// release is inside the document on the guide's own axis: the left ruler measures y, so a +/// horizontal guide let go there still reads a y inside the canvas and used to be moved. Held +/// level, that release reads as a click on the guide, which a ruler drop also outranks. +#[test] +fn a_guide_dragged_onto_a_ruler_is_deleted_through_the_canvas() { + for below in [50.0f32, 0.0] { + let mut h = tool_canvas_harness(crate::state::Tool::Move); + h.state_mut().run("view.newGuide", json!({"orientation": "horizontal", "position": 150})).unwrap(); + h.run_steps(1); + let at = |h: &egui_kittest::Harness<'static, PhotocraftApp>, x: f32, y: f32| { + let app = h.state(); + let v = &app.ui.views[0]; + let xf = ViewXform { + rect: content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + aspect: app.ui.view.display_aspect(), + }; + xf.to_screen(x, y) + }; + let on_the_guide = at(&h, 200.0, 150.0); + // In the left ruler's band, `below` document px under the press: inside the canvas on the + // guide's own axis, which is where the old code moved the guide instead of removing it. + let canvas = h.state().last_canvas_rect; + let onto_the_left_ruler = pos2(canvas.min.x + RULER / 2.0, on_the_guide.y + below); + // Along the guide, so a held-level release keeps its y, the way a sideways drag does. + let dragged = pos2(on_the_guide.x - 12.0, on_the_guide.y); + h.event(egui::Event::PointerMoved(on_the_guide)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: on_the_guide, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + // Past egui's click distance, so the drag starts at the press, on the guide. + h.event(egui::Event::PointerMoved(dragged)); + h.run_steps(2); + assert!(h.state().guide_drag.is_some(), "the Move tool takes the guide"); + h.event(egui::Event::PointerMoved(onto_the_left_ruler)); + h.run_steps(1); + h.event(egui::Event::PointerButton { + pos: onto_the_left_ruler, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(2); + let g = &h.state().session.active().unwrap().doc.guides; + assert!(g.horizontal.is_empty(), "{below} px below the press, released on the left ruler: got {:?}", g.horizontal); + assert!(h.state().guide_drag.is_none(), "the drag is over"); + } +} + +/// #3770: a guide Shift-dragged out of a ruler lands on the nearest tick the ruler draws +/// (tenths of the labelled step, in the ruler unit); without Shift it lands where it's dropped. +#[test] +fn shift_dragged_guides_land_on_ruler_ticks() { + let full = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max); + let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let new_app = || { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 256, "height": 128})).unwrap(); + app + }; + let drag_guide = |modifiers: egui::Modifiers| { + let builder = egui_kittest::Harness::builder().with_size(vec2(400.0, 300.0)); + let mut h = builder.build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), new_app()); + // Out of the left ruler: a vertical guide, dropped at document x = 37. + let (from, to) = (pos2(RULER / 2.0, 100.0), xf.to_screen(37.0, 64.0)); + h.event_modifiers(egui::Event::PointerMoved(from), modifiers); + h.event_modifiers(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers }, modifiers); + h.run_steps(1); + h.event_modifiers(egui::Event::PointerMoved(to), modifiers); + h.run_steps(1); + h.event_modifiers(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers }, modifiers); + h.run_steps(2); + h.state().session.active().unwrap().doc.guides.vertical.clone() + }; + assert_eq!(drag_guide(egui::Modifiers::NONE), vec![37.0]); + // #5698: Alt turns it into a horizontal guide (at the drop's y, the document's centre). + assert_eq!(drag_guide(egui::Modifiers::ALT), Vec::::new(), "no vertical guide with Alt"); + // Pixels at 100%: labels every 100 px, ticks every 10 px. + assert_eq!(drag_guide(egui::Modifiers::SHIFT), vec![40.0]); + + let mut app = new_app(); + // At 200% the labels are every 50 px, so the ticks every 5 px. + assert_eq!(snap_to_tick(&app, &ViewXform { zoom: 2.0, ..xf }, true, 37.0), 35.0); + // Percent of each side: ticks every 2.5% of 256 px across, every 5% of 128 px down. + app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "percent"})).unwrap(); + assert!((snap_to_tick(&app, &xf, true, 37.0) - 38.4).abs() < 1e-9); + assert!((snap_to_tick(&app, &xf, false, 37.0) - 38.4).abs() < 1e-9); + // Ticks count from the zero point (#2955): a vertical guide follows the x origin only. + let mut app = new_app(); + app.run("view.setRulerOrigin", json!({"x": 3, "y": 0})).unwrap(); + assert_eq!(snap_to_tick(&app, &xf, true, 37.0), 33.0); + assert_eq!(snap_to_tick(&app, &xf, false, 37.0), 40.0); +} From b00aecfe932713d1a16436939c69b60be83a457a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:36 +0000 Subject: [PATCH 060/259] refactor(ui-egui): move gradient_ui.rs tests to gradient_ui/tests.rs --- crates/ui-egui/src/gradient_ui.rs | 444 +----------------------- crates/ui-egui/src/gradient_ui/tests.rs | 441 +++++++++++++++++++++++ 2 files changed, 442 insertions(+), 443 deletions(-) create mode 100644 crates/ui-egui/src/gradient_ui/tests.rs diff --git a/crates/ui-egui/src/gradient_ui.rs b/crates/ui-egui/src/gradient_ui.rs index a1d7574244..729a24dc67 100644 --- a/crates/ui-egui/src/gradient_ui.rs +++ b/crates/ui-egui/src/gradient_ui.rs @@ -1029,446 +1029,4 @@ fn stop_strip(ui: &mut egui::Ui, key: egui::Id, f: &Fill, midpoints: bool, pendi } #[cfg(test)] -mod tests { - use super::*; - - fn app_with_gradient(style: &str) -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); - app.ui.tool = Tool::Gradient; - app.ui.tool_options.gradient_style = style.into(); - app - } - - fn mods() -> egui::Modifiers { - egui::Modifiers::NONE - } - - fn drag(app: &mut PhotocraftApp, a: [f64; 2], b: [f64; 2]) { - crate::canvas::tool_event(app, ToolEvent::Down { x: a[0], y: a[1], pressure: 1.0 }, mods()); - crate::canvas::tool_event(app, ToolEvent::Move { x: (a[0] + b[0]) / 2.0, y: (a[1] + b[1]) / 2.0, pressure: 1.0 }, mods()); - crate::canvas::tool_event(app, ToolEvent::Move { x: b[0], y: b[1], pressure: 1.0 }, mods()); - crate::canvas::tool_event(app, ToolEvent::Up { x: b[0], y: b[1] }, mods()); - } - - fn get(app: &mut PhotocraftApp) -> Value { - app.run(cmds::GET, json!({})).unwrap() - } - - #[test] - fn thumbnails_show_the_gradient() { - use photocraft_color::Color; - // Black to white, left to right: the left edge is dark, the right light, top = bottom. - let f = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false); - let img = thumbnail_image(&f).unwrap(); - let n = img.size[0]; - let at = |x: usize, y: usize| img.pixels[y * n + x]; - assert!(at(0, n / 2).r() < 10 && at(n - 1, n / 2).r() > 245, "{:?} {:?}", at(0, n / 2), at(n - 1, n / 2)); - assert_eq!(at(n / 3, 0), at(n / 3, n - 1)); - // Reverse flips colour and opacity alike; a transparent stop lets the checkerboard through. - let mut r = f.clone(); - if let Fill::Gradient { reverse, opacity_stops, .. } = &mut r { - *reverse = true; - *opacity_stops = vec![(0.0, 1.0), (1.0, 0.0)]; - } - let img = thumbnail_image(&r).unwrap(); - let (left, right) = (img.pixels[n / 2 * n], img.pixels[n / 2 * n + n - 1]); - assert!(left.a() < 10 && right.r() < 10 && right.a() > 245, "{left:?} {right:?}"); - // A radial thumbnail is centred. - let rad = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Radial, false); - let img = thumbnail_image(&rad).unwrap(); - assert!(img.pixels[n / 2 * n + n / 2].r() < img.pixels[0].r()); - assert!(thumbnail_image(&Fill::Solid(Color::WHITE)).is_none()); - } - - #[test] - fn options_bar_swatch_opens_the_editor_and_reaches_the_gradients_panel() { - use egui_kittest::{Harness, kittest::Queryable}; - let app = app_with_gradient("linear"); - let mut h = Harness::builder().with_size(vec2(440.0, 560.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - if preset_swatch(app, ui) { - app.ui.panels.gradient_editor = true; - } - let ctx = ui.ctx().clone(); - editor_window(app, &ctx); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); - h.run_steps(2); - // The swatch opens the Gradient Editor window (Photoshop's behaviour), not a popup. - h.get_by_label("Gradient picker").click(); - h.run_steps(2); - assert!(h.state().ui.panels.gradient_editor, "the swatch opened the editor window"); - // Quick preset picking lives in the editor: its Gradients button shows the Gradients panel. - h.get_by_label("Gradients").click(); - h.run_steps(2); - assert!(h.state().ui.panels.color, "the Gradients panel opened"); - assert_eq!(h.state().ui.dock_tabs.color, 2, "on the Gradients tab"); - assert_eq!(h.state().session.active().unwrap().doc.layers.len(), 1, "no document layers edited"); - } - - #[test] - fn live_drag_creates_a_fill_layer_and_handles_edit_it() { - let mut app = app_with_gradient("linear"); - drag(&mut app, [20.0, 60.0], [180.0, 60.0]); - assert_eq!(app.session.active().unwrap().doc.layers.len(), 2, "a Gradient Fill layer"); - let g = get(&mut app); - assert!((g["to"][0].as_f64().unwrap() - 180.0).abs() < 1e-3); - // Drag the end handle: one history step. - let before = app.session.active().unwrap().history.past_len(); - drag(&mut app, [180.0, 60.0], [150.0, 100.0]); - let g = get(&mut app); - assert!((g["to"][0].as_f64().unwrap() - 150.0).abs() < 1e-3 && (g["to"][1].as_f64().unwrap() - 100.0).abs() < 1e-3, "{g}"); - assert_eq!(app.session.active().unwrap().history.past_len(), before + 1); - // Click on the line adds a stop; dragging it off the line deletes it. - let (s, e) = ([20.0, 60.0], [150.0, 100.0]); - // A third of the way (the midpoint diamond sits half-way). - let mid = [s[0] + (e[0] - s[0]) / 3.0, s[1] + (e[1] - s[1]) / 3.0]; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: mid[0], y: mid[1], pressure: 1.0 }, mods()); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: mid[0], y: mid[1] }, mods()); - assert_eq!(get(&mut app)["stops"].as_array().unwrap().len(), 3); - drag(&mut app, mid, [mid[0], mid[1] - 80.0]); - assert_eq!(get(&mut app)["stops"].as_array().unwrap().len(), 2); - // A drag away from the widget redraws the selected gradient (no new layer). - drag(&mut app, [100.0, 10.0], [100.0, 110.0]); - assert_eq!(app.session.active().unwrap().doc.layers.len(), 2); - assert!((get(&mut app)["from"][1].as_f64().unwrap() - 10.0).abs() < 1e-3); - } - - #[test] - fn dragging_the_midpoint_diamond_moves_it() { - let mut app = app_with_gradient("linear"); - drag(&mut app, [20.0, 60.0], [180.0, 60.0]); - // The untouched midpoint sits at the segment centre (doc x = 100). Drag it to a quarter. - drag(&mut app, [100.0, 60.0], [60.0, 60.0]); - let g = get(&mut app); - assert_eq!(g["stops"].as_array().map(Vec::len), Some(2), "a midpoint drag must not add a stop: {g}"); - let m = g["midpoints"][0].as_f64().unwrap_or(f64::NAN); - assert!((m - 0.25).abs() < 1e-3, "the midpoint did not move: {g}"); - } - - #[test] - fn shift_snaps_live_drags_to_45_degrees() { - let mut app = app_with_gradient("linear"); - let shift = egui::Modifiers::SHIFT; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, shift); - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 62.0, pressure: 1.0 }, shift); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 90.0, y: 84.0 }, shift); - let g = get(&mut app); - let (fx, fy, tx, ty) = (g["from"][0].as_f64().unwrap(), g["from"][1].as_f64().unwrap(), g["to"][0].as_f64().unwrap(), g["to"][1].as_f64().unwrap()); - assert!(((tx - fx) - (ty - fy)).abs() < 1e-2 && tx > 80.0, "45°: {g}"); - // Dragging the end handle with ⇧ snaps too (horizontal here). - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: tx, y: ty, pressure: 1.0 }, shift); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 120.0, y: 26.0 }, shift); - let g = get(&mut app); - assert!((g["to"][1].as_f64().unwrap() - fy).abs() < 1e-2, "horizontal: {g}"); - } - - #[test] - fn classic_mode_paints_pixels() { - let mut app = app_with_gradient("linear"); - app.ui.tool_options.gradient_classic = true; - drag(&mut app, [20.0, 60.0], [180.0, 60.0]); - assert_eq!(app.session.active().unwrap().doc.layers.len(), 1, "no fill layer in classic mode"); - } - - #[test] - fn classic_drag_preserves_preset_transparency_at_all_depths() { - for depth in [8, 16, 32] { - for reverse in [false, true] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 200, "height": 120, "depth": depth, "background": "transparent"})).unwrap(); - app.ui.tool = Tool::Gradient; - app.ui.tool_options.gradient_classic = true; - app.ui.tool_options.gradient_reverse = reverse; - app.ui.tool_options.gradient_dither = false; - app.ui.tool_options.fill_opacity = 50.0; - app.session.tools.foreground = [1.0, 0.0, 0.0, 1.0]; - app.run("gradient.presets.select", json!({"preset": "Foreground to Transparent"})).unwrap(); - let before = app.session.active().unwrap().history.past_len(); - drag(&mut app, [20.0, 60.0], [180.0, 60.0]); - let st = app.session.active().unwrap(); - let surface = st.doc.layers[0].surface().unwrap(); - for x in [0, 100, 199] { - let u = ((x as f32 - 20.0) / 160.0).clamp(0.0, 1.0); - let expected = 0.5 * if reverse { u } else { 1.0 - u }; - let px = surface.pixel(x, 60); - assert!((px[3] - expected).abs() < 0.01, "depth {depth}, reverse {reverse}, x {x}: {px:?}"); - if expected > 0.01 { - assert!(px[0] > 0.99 && px[1] < 0.01 && px[2] < 0.01, "preset colour: {px:?}"); - } - } - assert_eq!(st.history.past_len(), before + 1); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(app.session.active().unwrap().doc.layers[0].surface().unwrap().pixel(100, 60)[3], 0.0); - app.run("gradient.presets.select", json!({"stops": [[0, "#00ff00"], [1, "#00ff00"]], "transparency": [[0, 60], [1, 20]]})).unwrap(); - drag(&mut app, [20.0, 60.0], [180.0, 60.0]); - let px = app.session.active().unwrap().doc.layers[0].surface().unwrap().pixel(100, 60); - assert!((px[3] - 0.2).abs() < 0.01 && px[1] > 0.99 && px[0] < 0.01, "custom semi-transparent colour: {px:?}"); - } - } - } - - #[test] - fn sidebar_transparent_preset_reaches_classic_canvas_over_existing_art() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = app_with_gradient("linear"); - app.run("paint.gradient", json!({"from": [0, 0], "to": [199, 0], "colors": ["#ff0000", "#ff0000"]})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.ui.tool_options.gradient_classic = true; - app.ui.tool_options.gradient_dither = false; - let mut h = Harness::builder().with_size(vec2(420.0, 600.0)).build_ui_state(|ui, app| crate::preset_panels::gradients_panel(app, ui), app); - h.get_by_label("Foreground to Transparent").click(); - h.run(); - assert_eq!(h.state().session.presets.gradient.name, "Foreground to Transparent"); - drag(h.state_mut(), [20.0, 60.0], [180.0, 60.0]); - let st = h.state().session.active().unwrap(); - assert_eq!(st.doc.layers.len(), 2); - let surface = st.doc.layers[1].surface().unwrap(); - assert!(surface.pixel(0, 60)[3] > 0.99); - assert!((surface.pixel(100, 60)[3] - 0.5).abs() < 0.01); - assert!(surface.pixel(199, 60)[3] < 0.01, "transparent end reveals existing art"); - assert_eq!(st.doc.layers[0].surface().unwrap().pixel(100, 60), vec![1.0, 0.0, 0.0, 1.0], "existing art is unchanged"); - } - - #[test] - fn gradient_blend_mode_reaches_live_and_classic_drags() { - use photocraft_color::BlendMode; - for mode in [BlendMode::Difference, BlendMode::Multiply, BlendMode::Screen, BlendMode::Exclusion] { - let mut live = app_with_gradient("linear"); - live.ui.tool_options.gradient_blend_mode = mode; - drag(&mut live, [20.0, 60.0], [180.0, 60.0]); - let layer = live.session.active().unwrap().doc.layers.last().unwrap(); - assert_eq!(layer.blend, mode, "live {mode:?}"); - - let mut classic = app_with_gradient("linear"); - classic.ui.tool_options.gradient_classic = true; - classic.ui.tool_options.gradient_blend_mode = mode; - classic.session.tools.foreground = [1.0, 0.0, 0.0, 1.0]; - classic.session.tools.background = [1.0, 0.0, 0.0, 1.0]; - drag(&mut classic, [20.0, 60.0], [180.0, 60.0]); - let st = classic.session.active().unwrap(); - let px = st.doc.layers[0].surface().unwrap().pixel(60, 60); - let expected = match mode { - BlendMode::Difference | BlendMode::Exclusion => [0.0, 1.0, 1.0], - BlendMode::Multiply => [1.0, 0.0, 0.0], - BlendMode::Screen => [1.0, 1.0, 1.0], - _ => [1.0, 1.0, 1.0], - }; - for (actual, want) in px.iter().zip(expected) { - assert!((actual - want).abs() < 0.02, "classic {mode:?}: {px:?}"); - } - } - } - - #[test] - fn changing_live_gradient_mode_updates_selected_fill_layer() { - use photocraft_color::BlendMode; - let mut app = app_with_gradient("linear"); - drag(&mut app, [20.0, 60.0], [180.0, 60.0]); - let before = app.ui.tool_options.clone(); - app.ui.tool_options.gradient_blend_mode = BlendMode::Difference; - options_changed(&mut app, &before); - let layer = app.session.active().unwrap().doc.layers.last().unwrap(); - assert_eq!(layer.blend, BlendMode::Difference); - } - - #[test] - fn changing_live_gradient_opacity_updates_selected_fill_layer() { - let mut app = app_with_gradient("linear"); - drag(&mut app, [20.0, 60.0], [180.0, 60.0]); - let past = app.session.active().unwrap().history.past_len(); - // A scrub is live on every frame and one undo step. - for pct in [70.0, 55.0, 40.0] { - app.ui.tool_options.fill_opacity = pct; - opacity_changed(&mut app, Some(7)); - } - opacity_changed(&mut app, None); - let st = app.session.active().unwrap(); - assert!((st.doc.layers.last().unwrap().opacity - 0.4).abs() < 1e-6); - assert_eq!(st.history.past_len(), past + 1, "one undo step, none for an unchanged value"); - // Classic mode paints pixels: the options bar leaves the layer alone. - app.ui.tool_options.gradient_classic = true; - app.ui.tool_options.fill_opacity = 80.0; - opacity_changed(&mut app, None); - assert!((app.session.active().unwrap().doc.layers.last().unwrap().opacity - 0.4).abs() < 1e-6); - } - - #[test] - fn preview_shows_the_drag_before_commit() { - let mut app = app_with_gradient("radial"); - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 60.0, pressure: 1.0 }, mods()); - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 140.0, y: 60.0, pressure: 1.0 }, mods()); - let (doc, key) = display_doc(&mut app, 0).expect("a preview while drawing"); - assert!(key & TAG != 0); - assert!(doc.layer(PREVIEW_LAYER).is_some(), "the new layer previews"); - assert_eq!(app.session.active().unwrap().doc.layers.len(), 1, "nothing committed yet"); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 140.0, y: 60.0 }, mods()); - assert!(display_doc(&mut app, 0).is_none()); - } - - /// Regression: the options bar's gradient swatch could not open anything. In live mode it - /// sensed hover only, so `clicked()` was never true; in classic mode it sensed clicks and - /// promised "Click to edit the gradient" but never read the response. Both now open the - /// Gradient Editor window. - #[test] - fn the_options_bar_swatch_opens_the_gradient_editor_in_both_modes() { - use egui_kittest::kittest::Queryable; - - for classic in [false, true] { - let mut app = app_with_gradient("linear"); - app.ui.tool_options.gradient_classic = classic; - let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - crate::panels::options_bar(app, ui); - let ctx = ui.ctx().clone(); - editor_window(app, &ctx); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.run_steps(4); - assert!(!h.state().ui.panels.gradient_editor, "classic={classic}: starts closed"); - h.get_by_label("Gradient picker").click(); - h.run_steps(3); - assert!(h.state().ui.panels.gradient_editor, "classic={classic}: the swatch opened the editor"); - } - } - - /// The editor itself renders in both states: with a gradient fill layer selected it shows the - /// full stops editor, and with none selected it must still draw (and say what to do) instead of - /// opening an empty window or panicking. - #[test] - fn the_editor_window_renders_with_and_without_a_gradient_layer() { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - // `run_ui` hands back a `FullOutput` whose texture deltas the caller has to consume. - let run = |app: &mut PhotocraftApp| { - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| editor_window(app, ui.ctx())); - out.textures_delta.clear(); - }; - - // Nothing selected. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.ui.panels.gradient_editor = true; - run(&mut app); - assert!(app.ui.panels.gradient_editor, "the window stays open"); - - // A committed live gradient fill layer: `selected_gradient` finds it, so the full editor - // (combined stops and Gradient Options) is what gets built. - let mut app = app_with_gradient("linear"); - drag(&mut app, [10.0, 10.0], [150.0, 90.0]); - assert!(selected_gradient(&app).is_some(), "the drag left a gradient fill layer selected"); - app.ui.panels.gradient_editor = true; - run(&mut app); - assert!(app.ui.panels.gradient_editor); - - // Closed: the window draws nothing and leaves the flag alone. - app.ui.panels.gradient_editor = false; - run(&mut app); - assert!(!app.ui.panels.gradient_editor); - } - - /// With no gradient fill layer selected the editor edits the Gradient tool's current gradient - /// in place (Photoshop's editor edits the tool gradient): a click on the strip adds a stop to - /// it instead of only pointing at the Gradients panel's presets. - #[test] - fn the_editor_edits_the_current_gradient_without_a_layer() { - use egui_kittest::kittest::Queryable; - - let app = app_with_gradient("linear"); - let before = app.session.presets.gradient.stops.len(); - let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - let ctx = ui.ctx().clone(); - editor_window(app, &ctx); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - // Open the window once the fonts are bound (the build's first frame runs without them). - h.run_steps(2); - h.state_mut().ui.panels.gradient_editor = true; - h.run_steps(4); - h.get_by_label("Gradient stops").click(); - h.run_steps(3); - assert_eq!(h.state().session.presets.gradient.stops.len(), before + 1, "the click added a stop to the current gradient"); - } - - /// The editor's Save As Preset button files the current gradient into the Gradients panel - /// under a fresh "Custom" name. - #[test] - fn the_editor_saves_the_current_gradient_as_a_preset() { - use egui_kittest::kittest::Queryable; - - let app = app_with_gradient("linear"); - let has_custom = |s: &PhotocraftApp| s.session.presets.gradients.iter().any(|g| g.items.iter().any(|p| p.name == "Custom")); - let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - let ctx = ui.ctx().clone(); - editor_window(app, &ctx); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.run_steps(2); - h.state_mut().ui.panels.gradient_editor = true; - h.run_steps(4); - assert!(!has_custom(h.state()), "no Custom preset yet"); - h.get_by_label("Save As Preset").click(); - h.run_steps(3); - assert!(has_custom(h.state()), "the button saved the current gradient as a preset"); - } - - /// A hidden gradient fill layer is still editable from the editor (the Properties panel edits - /// it whether or not it is drawn), so the window must not require visibility. - #[test] - fn the_editor_finds_a_hidden_gradient_layer() { - let mut app = app_with_gradient("linear"); - drag(&mut app, [10.0, 10.0], [150.0, 90.0]); - let id = app.session.active().unwrap().active_layer.unwrap(); - app.run("layer.setProps", json!({"layer": id.0, "visible": false})).unwrap(); - assert!(active_gradient(&app).is_none(), "the canvas widget skips a hidden layer"); - assert!(selected_gradient(&app).is_some(), "the editor still edits it"); - } - - /// #4577: the tessellator snaps the checkerboard's rects to whole pixels but leaves the ramp's - /// mesh where it was laid out, so at a half-pixel offset the ramp stopped a pixel short of the - /// checker and a row of it showed under the gradient. The ramp must cover the checker exactly. - #[test] - fn the_ramp_covers_its_checkerboard_at_half_pixel_offsets() { - let ctx = egui::Context::default(); - for ppp in [1.0, 2.0] { - ctx.set_pixels_per_point(ppp); - let r = Rect::from_min_size(pos2(10.0 + 0.5 / ppp, 7.0 + 0.5 / ppp), vec2(96.0, 20.0)); - // The new scale applies from the next frame. - ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); - let mut painted_at = 0.0; - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { - painted_at = ui.ctx().pixels_per_point(); - paint_ramp(ui.painter(), r, |u| [u, u, u, 1.0]); - }); - out.textures_delta.clear(); - assert_eq!(painted_at, ppp); - let checker = out - .shapes - .iter() - .find_map(|s| match &s.shape { - egui::Shape::Rect(rs) if rs.fill == Color32::from_gray(250) => Some(rs.rect), - _ => None, - }) - .expect("the checkerboard's base rect"); - let ramp = out - .shapes - .iter() - .find_map(|s| match &s.shape { - egui::Shape::Mesh(m) => Some(m.calc_bounds()), - _ => None, - }) - .expect("the ramp mesh"); - assert_eq!(ramp, checker.round_to_pixels(ppp), "{ppp}x: the ramp covers every pixel of the checker"); - } - } -} +mod tests; diff --git a/crates/ui-egui/src/gradient_ui/tests.rs b/crates/ui-egui/src/gradient_ui/tests.rs new file mode 100644 index 0000000000..22e0355b2c --- /dev/null +++ b/crates/ui-egui/src/gradient_ui/tests.rs @@ -0,0 +1,441 @@ +use super::*; + +fn app_with_gradient(style: &str) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.ui.tool = Tool::Gradient; + app.ui.tool_options.gradient_style = style.into(); + app +} + +fn mods() -> egui::Modifiers { + egui::Modifiers::NONE +} + +fn drag(app: &mut PhotocraftApp, a: [f64; 2], b: [f64; 2]) { + crate::canvas::tool_event(app, ToolEvent::Down { x: a[0], y: a[1], pressure: 1.0 }, mods()); + crate::canvas::tool_event(app, ToolEvent::Move { x: (a[0] + b[0]) / 2.0, y: (a[1] + b[1]) / 2.0, pressure: 1.0 }, mods()); + crate::canvas::tool_event(app, ToolEvent::Move { x: b[0], y: b[1], pressure: 1.0 }, mods()); + crate::canvas::tool_event(app, ToolEvent::Up { x: b[0], y: b[1] }, mods()); +} + +fn get(app: &mut PhotocraftApp) -> Value { + app.run(cmds::GET, json!({})).unwrap() +} + +#[test] +fn thumbnails_show_the_gradient() { + use photocraft_color::Color; + // Black to white, left to right: the left edge is dark, the right light, top = bottom. + let f = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false); + let img = thumbnail_image(&f).unwrap(); + let n = img.size[0]; + let at = |x: usize, y: usize| img.pixels[y * n + x]; + assert!(at(0, n / 2).r() < 10 && at(n - 1, n / 2).r() > 245, "{:?} {:?}", at(0, n / 2), at(n - 1, n / 2)); + assert_eq!(at(n / 3, 0), at(n / 3, n - 1)); + // Reverse flips colour and opacity alike; a transparent stop lets the checkerboard through. + let mut r = f.clone(); + if let Fill::Gradient { reverse, opacity_stops, .. } = &mut r { + *reverse = true; + *opacity_stops = vec![(0.0, 1.0), (1.0, 0.0)]; + } + let img = thumbnail_image(&r).unwrap(); + let (left, right) = (img.pixels[n / 2 * n], img.pixels[n / 2 * n + n - 1]); + assert!(left.a() < 10 && right.r() < 10 && right.a() > 245, "{left:?} {right:?}"); + // A radial thumbnail is centred. + let rad = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Radial, false); + let img = thumbnail_image(&rad).unwrap(); + assert!(img.pixels[n / 2 * n + n / 2].r() < img.pixels[0].r()); + assert!(thumbnail_image(&Fill::Solid(Color::WHITE)).is_none()); +} + +#[test] +fn options_bar_swatch_opens_the_editor_and_reaches_the_gradients_panel() { + use egui_kittest::{Harness, kittest::Queryable}; + let app = app_with_gradient("linear"); + let mut h = Harness::builder().with_size(vec2(440.0, 560.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if preset_swatch(app, ui) { + app.ui.panels.gradient_editor = true; + } + let ctx = ui.ctx().clone(); + editor_window(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); + h.run_steps(2); + // The swatch opens the Gradient Editor window (Photoshop's behaviour), not a popup. + h.get_by_label("Gradient picker").click(); + h.run_steps(2); + assert!(h.state().ui.panels.gradient_editor, "the swatch opened the editor window"); + // Quick preset picking lives in the editor: its Gradients button shows the Gradients panel. + h.get_by_label("Gradients").click(); + h.run_steps(2); + assert!(h.state().ui.panels.color, "the Gradients panel opened"); + assert_eq!(h.state().ui.dock_tabs.color, 2, "on the Gradients tab"); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), 1, "no document layers edited"); +} + +#[test] +fn live_drag_creates_a_fill_layer_and_handles_edit_it() { + let mut app = app_with_gradient("linear"); + drag(&mut app, [20.0, 60.0], [180.0, 60.0]); + assert_eq!(app.session.active().unwrap().doc.layers.len(), 2, "a Gradient Fill layer"); + let g = get(&mut app); + assert!((g["to"][0].as_f64().unwrap() - 180.0).abs() < 1e-3); + // Drag the end handle: one history step. + let before = app.session.active().unwrap().history.past_len(); + drag(&mut app, [180.0, 60.0], [150.0, 100.0]); + let g = get(&mut app); + assert!((g["to"][0].as_f64().unwrap() - 150.0).abs() < 1e-3 && (g["to"][1].as_f64().unwrap() - 100.0).abs() < 1e-3, "{g}"); + assert_eq!(app.session.active().unwrap().history.past_len(), before + 1); + // Click on the line adds a stop; dragging it off the line deletes it. + let (s, e) = ([20.0, 60.0], [150.0, 100.0]); + // A third of the way (the midpoint diamond sits half-way). + let mid = [s[0] + (e[0] - s[0]) / 3.0, s[1] + (e[1] - s[1]) / 3.0]; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: mid[0], y: mid[1], pressure: 1.0 }, mods()); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: mid[0], y: mid[1] }, mods()); + assert_eq!(get(&mut app)["stops"].as_array().unwrap().len(), 3); + drag(&mut app, mid, [mid[0], mid[1] - 80.0]); + assert_eq!(get(&mut app)["stops"].as_array().unwrap().len(), 2); + // A drag away from the widget redraws the selected gradient (no new layer). + drag(&mut app, [100.0, 10.0], [100.0, 110.0]); + assert_eq!(app.session.active().unwrap().doc.layers.len(), 2); + assert!((get(&mut app)["from"][1].as_f64().unwrap() - 10.0).abs() < 1e-3); +} + +#[test] +fn dragging_the_midpoint_diamond_moves_it() { + let mut app = app_with_gradient("linear"); + drag(&mut app, [20.0, 60.0], [180.0, 60.0]); + // The untouched midpoint sits at the segment centre (doc x = 100). Drag it to a quarter. + drag(&mut app, [100.0, 60.0], [60.0, 60.0]); + let g = get(&mut app); + assert_eq!(g["stops"].as_array().map(Vec::len), Some(2), "a midpoint drag must not add a stop: {g}"); + let m = g["midpoints"][0].as_f64().unwrap_or(f64::NAN); + assert!((m - 0.25).abs() < 1e-3, "the midpoint did not move: {g}"); +} + +#[test] +fn shift_snaps_live_drags_to_45_degrees() { + let mut app = app_with_gradient("linear"); + let shift = egui::Modifiers::SHIFT; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, shift); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 62.0, pressure: 1.0 }, shift); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 90.0, y: 84.0 }, shift); + let g = get(&mut app); + let (fx, fy, tx, ty) = (g["from"][0].as_f64().unwrap(), g["from"][1].as_f64().unwrap(), g["to"][0].as_f64().unwrap(), g["to"][1].as_f64().unwrap()); + assert!(((tx - fx) - (ty - fy)).abs() < 1e-2 && tx > 80.0, "45°: {g}"); + // Dragging the end handle with ⇧ snaps too (horizontal here). + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: tx, y: ty, pressure: 1.0 }, shift); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 120.0, y: 26.0 }, shift); + let g = get(&mut app); + assert!((g["to"][1].as_f64().unwrap() - fy).abs() < 1e-2, "horizontal: {g}"); +} + +#[test] +fn classic_mode_paints_pixels() { + let mut app = app_with_gradient("linear"); + app.ui.tool_options.gradient_classic = true; + drag(&mut app, [20.0, 60.0], [180.0, 60.0]); + assert_eq!(app.session.active().unwrap().doc.layers.len(), 1, "no fill layer in classic mode"); +} + +#[test] +fn classic_drag_preserves_preset_transparency_at_all_depths() { + for depth in [8, 16, 32] { + for reverse in [false, true] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 120, "depth": depth, "background": "transparent"})).unwrap(); + app.ui.tool = Tool::Gradient; + app.ui.tool_options.gradient_classic = true; + app.ui.tool_options.gradient_reverse = reverse; + app.ui.tool_options.gradient_dither = false; + app.ui.tool_options.fill_opacity = 50.0; + app.session.tools.foreground = [1.0, 0.0, 0.0, 1.0]; + app.run("gradient.presets.select", json!({"preset": "Foreground to Transparent"})).unwrap(); + let before = app.session.active().unwrap().history.past_len(); + drag(&mut app, [20.0, 60.0], [180.0, 60.0]); + let st = app.session.active().unwrap(); + let surface = st.doc.layers[0].surface().unwrap(); + for x in [0, 100, 199] { + let u = ((x as f32 - 20.0) / 160.0).clamp(0.0, 1.0); + let expected = 0.5 * if reverse { u } else { 1.0 - u }; + let px = surface.pixel(x, 60); + assert!((px[3] - expected).abs() < 0.01, "depth {depth}, reverse {reverse}, x {x}: {px:?}"); + if expected > 0.01 { + assert!(px[0] > 0.99 && px[1] < 0.01 && px[2] < 0.01, "preset colour: {px:?}"); + } + } + assert_eq!(st.history.past_len(), before + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.layers[0].surface().unwrap().pixel(100, 60)[3], 0.0); + app.run("gradient.presets.select", json!({"stops": [[0, "#00ff00"], [1, "#00ff00"]], "transparency": [[0, 60], [1, 20]]})).unwrap(); + drag(&mut app, [20.0, 60.0], [180.0, 60.0]); + let px = app.session.active().unwrap().doc.layers[0].surface().unwrap().pixel(100, 60); + assert!((px[3] - 0.2).abs() < 0.01 && px[1] > 0.99 && px[0] < 0.01, "custom semi-transparent colour: {px:?}"); + } + } +} + +#[test] +fn sidebar_transparent_preset_reaches_classic_canvas_over_existing_art() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = app_with_gradient("linear"); + app.run("paint.gradient", json!({"from": [0, 0], "to": [199, 0], "colors": ["#ff0000", "#ff0000"]})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool_options.gradient_classic = true; + app.ui.tool_options.gradient_dither = false; + let mut h = Harness::builder().with_size(vec2(420.0, 600.0)).build_ui_state(|ui, app| crate::preset_panels::gradients_panel(app, ui), app); + h.get_by_label("Foreground to Transparent").click(); + h.run(); + assert_eq!(h.state().session.presets.gradient.name, "Foreground to Transparent"); + drag(h.state_mut(), [20.0, 60.0], [180.0, 60.0]); + let st = h.state().session.active().unwrap(); + assert_eq!(st.doc.layers.len(), 2); + let surface = st.doc.layers[1].surface().unwrap(); + assert!(surface.pixel(0, 60)[3] > 0.99); + assert!((surface.pixel(100, 60)[3] - 0.5).abs() < 0.01); + assert!(surface.pixel(199, 60)[3] < 0.01, "transparent end reveals existing art"); + assert_eq!(st.doc.layers[0].surface().unwrap().pixel(100, 60), vec![1.0, 0.0, 0.0, 1.0], "existing art is unchanged"); +} + +#[test] +fn gradient_blend_mode_reaches_live_and_classic_drags() { + use photocraft_color::BlendMode; + for mode in [BlendMode::Difference, BlendMode::Multiply, BlendMode::Screen, BlendMode::Exclusion] { + let mut live = app_with_gradient("linear"); + live.ui.tool_options.gradient_blend_mode = mode; + drag(&mut live, [20.0, 60.0], [180.0, 60.0]); + let layer = live.session.active().unwrap().doc.layers.last().unwrap(); + assert_eq!(layer.blend, mode, "live {mode:?}"); + + let mut classic = app_with_gradient("linear"); + classic.ui.tool_options.gradient_classic = true; + classic.ui.tool_options.gradient_blend_mode = mode; + classic.session.tools.foreground = [1.0, 0.0, 0.0, 1.0]; + classic.session.tools.background = [1.0, 0.0, 0.0, 1.0]; + drag(&mut classic, [20.0, 60.0], [180.0, 60.0]); + let st = classic.session.active().unwrap(); + let px = st.doc.layers[0].surface().unwrap().pixel(60, 60); + let expected = match mode { + BlendMode::Difference | BlendMode::Exclusion => [0.0, 1.0, 1.0], + BlendMode::Multiply => [1.0, 0.0, 0.0], + BlendMode::Screen => [1.0, 1.0, 1.0], + _ => [1.0, 1.0, 1.0], + }; + for (actual, want) in px.iter().zip(expected) { + assert!((actual - want).abs() < 0.02, "classic {mode:?}: {px:?}"); + } + } +} + +#[test] +fn changing_live_gradient_mode_updates_selected_fill_layer() { + use photocraft_color::BlendMode; + let mut app = app_with_gradient("linear"); + drag(&mut app, [20.0, 60.0], [180.0, 60.0]); + let before = app.ui.tool_options.clone(); + app.ui.tool_options.gradient_blend_mode = BlendMode::Difference; + options_changed(&mut app, &before); + let layer = app.session.active().unwrap().doc.layers.last().unwrap(); + assert_eq!(layer.blend, BlendMode::Difference); +} + +#[test] +fn changing_live_gradient_opacity_updates_selected_fill_layer() { + let mut app = app_with_gradient("linear"); + drag(&mut app, [20.0, 60.0], [180.0, 60.0]); + let past = app.session.active().unwrap().history.past_len(); + // A scrub is live on every frame and one undo step. + for pct in [70.0, 55.0, 40.0] { + app.ui.tool_options.fill_opacity = pct; + opacity_changed(&mut app, Some(7)); + } + opacity_changed(&mut app, None); + let st = app.session.active().unwrap(); + assert!((st.doc.layers.last().unwrap().opacity - 0.4).abs() < 1e-6); + assert_eq!(st.history.past_len(), past + 1, "one undo step, none for an unchanged value"); + // Classic mode paints pixels: the options bar leaves the layer alone. + app.ui.tool_options.gradient_classic = true; + app.ui.tool_options.fill_opacity = 80.0; + opacity_changed(&mut app, None); + assert!((app.session.active().unwrap().doc.layers.last().unwrap().opacity - 0.4).abs() < 1e-6); +} + +#[test] +fn preview_shows_the_drag_before_commit() { + let mut app = app_with_gradient("radial"); + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 60.0, pressure: 1.0 }, mods()); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 140.0, y: 60.0, pressure: 1.0 }, mods()); + let (doc, key) = display_doc(&mut app, 0).expect("a preview while drawing"); + assert!(key & TAG != 0); + assert!(doc.layer(PREVIEW_LAYER).is_some(), "the new layer previews"); + assert_eq!(app.session.active().unwrap().doc.layers.len(), 1, "nothing committed yet"); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 140.0, y: 60.0 }, mods()); + assert!(display_doc(&mut app, 0).is_none()); +} + +/// Regression: the options bar's gradient swatch could not open anything. In live mode it +/// sensed hover only, so `clicked()` was never true; in classic mode it sensed clicks and +/// promised "Click to edit the gradient" but never read the response. Both now open the +/// Gradient Editor window. +#[test] +fn the_options_bar_swatch_opens_the_gradient_editor_in_both_modes() { + use egui_kittest::kittest::Queryable; + + for classic in [false, true] { + let mut app = app_with_gradient("linear"); + app.ui.tool_options.gradient_classic = classic; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + crate::panels::options_bar(app, ui); + let ctx = ui.ctx().clone(); + editor_window(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + assert!(!h.state().ui.panels.gradient_editor, "classic={classic}: starts closed"); + h.get_by_label("Gradient picker").click(); + h.run_steps(3); + assert!(h.state().ui.panels.gradient_editor, "classic={classic}: the swatch opened the editor"); + } +} + +/// The editor itself renders in both states: with a gradient fill layer selected it shows the +/// full stops editor, and with none selected it must still draw (and say what to do) instead of +/// opening an empty window or panicking. +#[test] +fn the_editor_window_renders_with_and_without_a_gradient_layer() { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + // `run_ui` hands back a `FullOutput` whose texture deltas the caller has to consume. + let run = |app: &mut PhotocraftApp| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| editor_window(app, ui.ctx())); + out.textures_delta.clear(); + }; + + // Nothing selected. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.panels.gradient_editor = true; + run(&mut app); + assert!(app.ui.panels.gradient_editor, "the window stays open"); + + // A committed live gradient fill layer: `selected_gradient` finds it, so the full editor + // (combined stops and Gradient Options) is what gets built. + let mut app = app_with_gradient("linear"); + drag(&mut app, [10.0, 10.0], [150.0, 90.0]); + assert!(selected_gradient(&app).is_some(), "the drag left a gradient fill layer selected"); + app.ui.panels.gradient_editor = true; + run(&mut app); + assert!(app.ui.panels.gradient_editor); + + // Closed: the window draws nothing and leaves the flag alone. + app.ui.panels.gradient_editor = false; + run(&mut app); + assert!(!app.ui.panels.gradient_editor); +} + +/// With no gradient fill layer selected the editor edits the Gradient tool's current gradient +/// in place (Photoshop's editor edits the tool gradient): a click on the strip adds a stop to +/// it instead of only pointing at the Gradients panel's presets. +#[test] +fn the_editor_edits_the_current_gradient_without_a_layer() { + use egui_kittest::kittest::Queryable; + + let app = app_with_gradient("linear"); + let before = app.session.presets.gradient.stops.len(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + editor_window(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + // Open the window once the fonts are bound (the build's first frame runs without them). + h.run_steps(2); + h.state_mut().ui.panels.gradient_editor = true; + h.run_steps(4); + h.get_by_label("Gradient stops").click(); + h.run_steps(3); + assert_eq!(h.state().session.presets.gradient.stops.len(), before + 1, "the click added a stop to the current gradient"); +} + +/// The editor's Save As Preset button files the current gradient into the Gradients panel +/// under a fresh "Custom" name. +#[test] +fn the_editor_saves_the_current_gradient_as_a_preset() { + use egui_kittest::kittest::Queryable; + + let app = app_with_gradient("linear"); + let has_custom = |s: &PhotocraftApp| s.session.presets.gradients.iter().any(|g| g.items.iter().any(|p| p.name == "Custom")); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + editor_window(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(2); + h.state_mut().ui.panels.gradient_editor = true; + h.run_steps(4); + assert!(!has_custom(h.state()), "no Custom preset yet"); + h.get_by_label("Save As Preset").click(); + h.run_steps(3); + assert!(has_custom(h.state()), "the button saved the current gradient as a preset"); +} + +/// A hidden gradient fill layer is still editable from the editor (the Properties panel edits +/// it whether or not it is drawn), so the window must not require visibility. +#[test] +fn the_editor_finds_a_hidden_gradient_layer() { + let mut app = app_with_gradient("linear"); + drag(&mut app, [10.0, 10.0], [150.0, 90.0]); + let id = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.setProps", json!({"layer": id.0, "visible": false})).unwrap(); + assert!(active_gradient(&app).is_none(), "the canvas widget skips a hidden layer"); + assert!(selected_gradient(&app).is_some(), "the editor still edits it"); +} + +/// #4577: the tessellator snaps the checkerboard's rects to whole pixels but leaves the ramp's +/// mesh where it was laid out, so at a half-pixel offset the ramp stopped a pixel short of the +/// checker and a row of it showed under the gradient. The ramp must cover the checker exactly. +#[test] +fn the_ramp_covers_its_checkerboard_at_half_pixel_offsets() { + let ctx = egui::Context::default(); + for ppp in [1.0, 2.0] { + ctx.set_pixels_per_point(ppp); + let r = Rect::from_min_size(pos2(10.0 + 0.5 / ppp, 7.0 + 0.5 / ppp), vec2(96.0, 20.0)); + // The new scale applies from the next frame. + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + let mut painted_at = 0.0; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + painted_at = ui.ctx().pixels_per_point(); + paint_ramp(ui.painter(), r, |u| [u, u, u, 1.0]); + }); + out.textures_delta.clear(); + assert_eq!(painted_at, ppp); + let checker = out + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Rect(rs) if rs.fill == Color32::from_gray(250) => Some(rs.rect), + _ => None, + }) + .expect("the checkerboard's base rect"); + let ramp = out + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Mesh(m) => Some(m.calc_bounds()), + _ => None, + }) + .expect("the ramp mesh"); + assert_eq!(ramp, checker.round_to_pixels(ppp), "{ppp}x: the ramp covers every pixel of the checker"); + } +} From 8754ea3d5c837f9f97cf55432bef4dc071b51aed Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:37 +0000 Subject: [PATCH 061/259] refactor(ui-egui): move color_picker_ui.rs tests to color_picker_ui/tests.rs --- crates/ui-egui/src/color_picker_ui.rs | 620 +------------------- crates/ui-egui/src/color_picker_ui/tests.rs | 617 +++++++++++++++++++ 2 files changed, 618 insertions(+), 619 deletions(-) create mode 100644 crates/ui-egui/src/color_picker_ui/tests.rs diff --git a/crates/ui-egui/src/color_picker_ui.rs b/crates/ui-egui/src/color_picker_ui.rs index 2c0286a4c9..46ecbce0e8 100644 --- a/crates/ui-egui/src/color_picker_ui.rs +++ b/crates/ui-egui/src/color_picker_ui.rs @@ -809,625 +809,7 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result = m.vertices.iter().map(|v| v.color).collect(); - assert!(distinct.len() > 1 && distinct.len() <= 216); - } - - fn picker(color: &str) -> Harness<'static, Map> { - let mut f = Map::new(); - f.insert("__colorPicker".into(), json!("foreground")); - f.insert("color".into(), json!(color)); - f.insert("__orig".into(), json!(color)); - let mut h = Harness::builder().with_size(vec2(700.0, 500.0)).build_ui_state( - |ui, f: &mut Map| { - if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { - body(ui, f); - } - }, - f, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.run_steps(2); - h - } - - /// Type `text` into the focused field one key per frame, like a person typing. - fn type_keys(h: &mut Harness<'static, Map>, text: &str) { - for ch in text.chars() { - h.event(egui::Event::Text(ch.to_string())); - h.run_steps(1); - } - } - - fn color(h: &Harness<'static, Map>) -> String { - h.state().get("color").and_then(Value::as_str).unwrap().to_string() - } - - /// Press at `at` and hold, with no release and no time passing, then run one frame. - fn press(h: &mut Harness<'static, S>, at: egui::Pos2) { - press_button(h, at, egui::PointerButton::Primary, true); - } - - fn press_button(h: &mut Harness<'static, S>, at: egui::Pos2, button: egui::PointerButton, pressed: bool) { - h.event(egui::Event::PointerMoved(at)); - h.event(egui::Event::PointerButton { pos: at, button, pressed, modifiers: egui::Modifiers::NONE }); - h.run_steps(1); - } - - /// #7793: the field and the slider pick on the frame the button goes down, not after the - /// pointer has travelled past egui's click threshold or been held for a while, and follow - /// moves of a few points. - #[test] - fn field_and_slider_pick_on_press_and_follow_small_moves() { - let mut f = Map::new(); - f.insert("color".into(), json!("#336699")); - let mut h = Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state( - |ui, f: &mut Map| { - ui.horizontal(|ui| { - let o = ui.cursor().min; - let gap = ui.spacing().item_spacing.x; - ui.data_mut(|d| d.insert_temp(egui::Id::unique("test-origin"), (o, gap))); - color_field(ui, f); - }); - }, - f, - ); - h.run_steps(2); - let (o, gap) = h.ctx.data(|d| d.get_temp::<(egui::Pos2, f32)>(egui::Id::unique("test-origin"))).unwrap(); - // Field: saturation across, brightness down (hue mode). - let at = o + vec2(FIELD * 0.5, FIELD * 0.5); - press(&mut h, at); - let picked = color(&h); - assert_ne!(picked, "#336699", "the press itself picks"); - let hsv = rgb_to_hsb(parse_hex(&picked).unwrap()); - assert!((hsv[1] - 0.5).abs() < 0.02 && (hsv[2] - 0.5).abs() < 0.02, "{picked} {hsv:?}"); - // A 3-point nudge (under the 6-point click threshold) moves the pick. - h.event(egui::Event::PointerMoved(at + vec2(3.0, 0.0))); - h.run_steps(1); - assert_ne!(color(&h), picked, "a small drag adjusts the pick"); - h.event(egui::Event::PointerButton { - pos: at + vec2(3.0, 0.0), - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }); - h.run_steps(2); - // Hue slider: a press near the bottom picks a hue near 0 at once. - let before = color(&h); - press(&mut h, o + vec2(FIELD + gap + 9.0, FIELD * 0.95)); - assert_ne!(color(&h), before, "the slider picks on press"); - let hue = rgb_to_hsb(parse_hex(&color(&h)).unwrap())[0]; - assert!(hue < 30.0 || hue > 330.0, "hue {hue}"); - } - - /// Only the primary button picks: a right or middle press (and its release) on the field or - /// the slider leaves the colour alone. - #[test] - fn field_and_slider_ignore_secondary_and_middle_presses() { - let mut f = Map::new(); - f.insert("color".into(), json!("#336699")); - let mut h = Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state( - |ui, f: &mut Map| { - ui.horizontal(|ui| { - let o = ui.cursor().min; - let gap = ui.spacing().item_spacing.x; - ui.data_mut(|d| d.insert_temp(egui::Id::unique("test-origin"), (o, gap))); - color_field(ui, f); - }); - }, - f, - ); - h.run_steps(2); - let (o, gap) = h.ctx.data(|d| d.get_temp::<(egui::Pos2, f32)>(egui::Id::unique("test-origin"))).unwrap(); - for at in [o + vec2(FIELD * 0.5, FIELD * 0.5), o + vec2(FIELD + gap + 9.0, FIELD * 0.95)] { - for button in [egui::PointerButton::Secondary, egui::PointerButton::Middle] { - press_button(&mut h, at, button, true); - assert_eq!(color(&h), "#336699", "{button:?} press at {at:?}"); - h.event(egui::Event::PointerMoved(at + vec2(3.0, 0.0))); - h.run_steps(1); - press_button(&mut h, at + vec2(3.0, 0.0), button, false); - h.run_steps(1); - assert_eq!(color(&h), "#336699", "{button:?} drag and release at {at:?}"); - } - } - } - - #[test] - fn hex_field_shows_uppercase_without_rewriting_the_selected_color() { - let h = picker("#12abef"); - assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("12ABEF")); - assert_eq!(color(&h), "#12abef", "casing is presentation only"); - } - - /// #6937: pressing the hue strip must update the colour on the press frame, not only when - /// the button is released (Photoshop updates immediately on click-and-hold). - #[test] - fn hue_strip_updates_the_color_on_press_not_on_release() { - let mut h = picker("#0000ff"); // pure blue: hue 240° - let web = h.get_by_label("Only Web Colors").rect(); - let pick = h.get_by_label("Pick screen color").rect(); - // The strip is 18 pt wide, 6 pt right of the 200 pt field whose left edge is the column's - // (the screen-colour button shares it); its bottom edge is just above the checkbox. - // Press near the bottom: hue ~5°, a red the blue starting colour cannot produce via the field. - let press = pos2(pick.left() + FIELD + 15.0, web.top() - 20.0); - h.event(egui::Event::PointerMoved(press)); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: press, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); - h.run_steps(1); - let held = color(&h); - assert_ne!(held, "#0000ff", "holding the button on the strip must already change the colour"); - // The colour is the red-ish hue near the strip's bottom, not the old blue: had the press - // landed on the field instead of the strip, the hue (and the blue channel) would survive. - let [r, _, b] = parse_hex(&held).unwrap(); - assert!(r > 0.5 && b < 0.2, "expected a red-ish hue from the strip, got {held}"); - h.event(egui::Event::PointerButton { pos: press, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); - h.run_steps(1); - assert_eq!(color(&h), held, "releasing must not move the colour again"); - } - - #[test] - fn hex_field_takes_typed_digits() { - let mut h = picker("#000000"); - h.get_by_role(Role::TextInput).click(); - h.run_steps(1); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.run_steps(1); - type_keys(&mut h, "ff88"); - // Partial input stays in the field instead of snapping back to the colour. - assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("ff88")); - assert_eq!(color(&h), "#000000"); - type_keys(&mut h, "00"); - assert_eq!(color(&h), "#ff8800"); - h.key_press(egui::Key::Tab); - h.run_steps(2); - assert_eq!(color(&h), "#ff8800"); - } - - #[test] - fn hex_field_takes_every_paste_with_or_without_hash() { - let mut h = picker("#336699"); - for (paste, want) in [("ff8800", "#ff8800"), ("#00ff00", "#00ff00"), (" 1234AB\n", "#1234ab")] { - h.event(egui::Event::Paste(paste.into())); - h.run_steps(2); - assert_eq!(color(&h), want, "paste {paste:?}"); - assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some(&want[1..].to_ascii_uppercase()[..])); - } - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.run_steps(1); - h.event(egui::Event::Paste("ff".into())); - h.run_steps(2); - assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("ff")); - assert_eq!(color(&h), "#1234ab"); - } - - #[test] - fn color_picker_opens_with_hex_focused_and_selected() { - let mut h = picker("#336699"); - let hex_field = h.get_by_role(Role::TextInput); - assert!(hex_field.is_focused(), "the hex field automatically has focus on open"); - // Typing directly replaces the selected hex digits without manual clicking or Command+A. - type_keys(&mut h, "ff8800"); - assert_eq!(color(&h), "#ff8800", "typing replaces the selected hex code"); - } - - #[test] - fn color_picker_dialog_hex_field_is_in_tab_order_and_confirms_typed_color() { - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut h = Harness::builder().with_size(vec2(760.0, 480.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - open(h.state_mut(), "foreground"); - h.run_steps(3); - assert!(h.get_by_role(Role::TextInput).is_focused(), "hex field has focus in dialog frame"); - for ch in "ff8800".chars() { - h.event(egui::Event::Text(ch.to_string())); - h.run_steps(1); - } - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(hex([h.state().session.tools.foreground[0], h.state().session.tools.foreground[1], h.state().session.tools.foreground[2]]), "#ff8800"); - } - - #[test] - fn alt_reset_restores_orig_color() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.tools.foreground = [0.2, 0.4, 0.6, 1.0]; - let id = open(&mut app, "foreground"); - let f = &mut app.ui.dialog_mut(id).unwrap().fields; - f.insert("color".into(), json!("#ff0000")); - reset(f); - assert_eq!(f["color"], json!(hex([0.2, 0.4, 0.6]))); - assert_eq!(f["__orig"], json!(hex([0.2, 0.4, 0.6]))); - } - - #[test] - fn lab_and_cmyk_fields_take_multi_digit_values() { - let base = parse_hex("#336699").unwrap(); - let lab = photocraft_color::convert::srgb_to_lab(base); - let cmyk = photocraft_color::convert::rgb_to_cmyk(base); - // Fields in order: H S B R G B, L a b, C M Y K. - for (field, typed, want) in [ - (6, "60", photocraft_color::convert::lab_to_srgb([60.0, lab[1], lab[2]])), - (7, "30", photocraft_color::convert::lab_to_srgb([lab[0], 30.0, lab[2]])), - (9, "40", photocraft_color::convert::cmyk_to_rgb([0.4, cmyk[1], cmyk[2], cmyk[3]])), - ] { - let mut h = picker("#336699"); - h.query_all_by_role(Role::SpinButton).nth(field).unwrap().click(); - h.run_steps(1); - type_keys(&mut h, typed); - h.key_press(egui::Key::Tab); - h.run_steps(2); - assert_eq!(color(&h), hex(want), "field {field} <- {typed}"); - } - } - - #[test] - fn picker_places_actions_above_two_columns_and_web_colors_under_the_field() { - let h = picker("#336699"); - let inputs: Vec<_> = h.query_all_by_role(Role::SpinButton).map(|n| n.rect()).collect(); - assert_eq!(inputs.len(), 13); - let (hue, red, lightness, cyan, black) = (inputs[0], inputs[3], inputs[6], inputs[9], inputs[12]); - assert!(lightness.left() > hue.right(), "Lab is beside HSB, not below RGB"); - assert!((lightness.top() - hue.top()).abs() < 1.0); - assert!((cyan.top() - red.top()).abs() < 1.0, "CMYK and RGB start at the same height"); - let ok = h.get_by_label("OK").rect(); - let cancel = h.get_by_label("Cancel").rect(); - assert!(ok.left() > hue.left() && ok.bottom() < hue.top(), "actions are above the values and beside the preview: {ok:?}, {hue:?}"); - assert!((ok.left() - cancel.left()).abs() < 1.0 && cancel.top() > ok.bottom()); - assert_eq!(h.query_all_by_label("OK").count(), 1); - let web = h.get_by_label("Only Web Colors").rect(); - assert!(web.left() < hue.left() && web.top() > hue.bottom()); - // The full dialog should fit even in PhotoCraft's minimum 760 x 480 window. - assert!(black.bottom() - ok.top() < 360.0); - assert!(black.right() - web.left() < 600.0); - let hex = h.get_by_role(Role::TextInput).rect(); - assert!(hex.left() < lightness.left() && hex.top() > inputs[5].bottom()); - } - - /// The whole Color Picker window (title, frame and all) is no bigger than Photoshop's: about - /// 534 x 376 points (Photoshop 27.11 on macOS, measured from a screenshot at the same scale as - /// PhotoCraft's, which was 682 x 438). - #[test] - fn the_picker_window_is_no_bigger_than_photoshops() { - let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_max_steps(64).build_eframe(|cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()) - }); - h.run_steps(4); - let id = open(h.state_mut(), "foreground"); - h.run_steps(6); - let rect = h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", id)))).expect("the picker window"); - assert!(rect.width() <= 534.0 && rect.height() <= 376.0, "Color Picker window {} x {} points, Photoshop's 534 x 376", rect.width(), rect.height()); - // Everything still shows: the three actions and all 13 component fields. - for label in ["OK", "Cancel", "Add to Swatches", "Only Web Colors"] { - assert!(rect.contains_rect(h.get_by_label(label).rect()), "{label} inside the window"); - } - assert_eq!(h.query_all_by_role(Role::SpinButton).filter(|n| rect.contains_rect(n.rect())).count(), 13); - // The actions are as wide as the longest label ("Add to Swatches" is about 133 points in - // the button font), not stretched across the column (160). Photoshop's are about 116. - let widths: Vec = ["OK", "Cancel", "Add to Swatches"].iter().map(|l| h.get_by_label(l).rect().width()).collect(); - assert!(widths.iter().all(|w| (w - widths[0]).abs() < 0.5), "one width for all three actions: {widths:?}"); - assert!(widths[0] <= 136.0, "actions {} points wide, Photoshop's about 116", widths[0]); - } - - #[test] - fn web_colors_and_current_swatch_still_update_the_picker() { - let mut h = picker("#123456"); - h.get_by_label("Only Web Colors").click(); - h.run_steps(2); - assert_eq!(color(&h), "#003366"); - assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("003366"), "hex field follows the snap while it has focus"); - h.get_by_label("Only Web Colors").click(); - h.run_steps(2); - h.get_by_label("Click to restore the current colour").click(); - h.run_steps(2); - assert_eq!(color(&h), "#123456"); - } - - /// Only Web Colors snaps hex, field and component edits to web-safe colours. - #[test] - fn web_only_snaps_hex_field_and_component_edits() { - let mut f = Map::new(); - f.insert("color".into(), json!("#123456")); - f.insert("__webOnly".into(), json!(true)); - set_rgb(&mut f, parse_hex("#ff8800").unwrap(), Keep::Nothing); - assert_eq!(f["color"], json!("#ff9900")); - set_rgb(&mut f, hsb_to_rgb([40.0, 1.0, 1.0]), Keep::Hsv([40.0, 1.0, 1.0])); - assert_eq!(f["color"], json!("#ff9900")); - assert!(f.get("__hsv").is_none(), "kept HSV does not outlive a web snap"); - set_rgb(&mut f, photocraft_color::convert::lab_to_srgb([50.0, 40.0, 20.0]).map(|c| c.clamp(0.0, 1.0)), Keep::Lab([50.0, 40.0, 20.0])); - assert_eq!(not_web_safe(parse_hex(f["color"].as_str().unwrap()).unwrap()), None); - assert!(f.get("__lab").is_none()); - } - - #[test] - fn web_only_survives_reopen_and_other_picker_targets() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.ui.color_panel.web_only = true; - let id = open(&mut app, "foreground"); - let f = &app.ui.dialog_mut(id).unwrap().fields; - assert_eq!(f["__webOnly"], json!(true)); - assert_eq!(f["color"], json!(hex(web_safe([app.session.tools.foreground[0], app.session.tools.foreground[1], app.session.tools.foreground[2]])))); - assert_eq!(f["__orig"], f["color"], "the opening snap moves __orig too, so OK with no edit is unchanged"); - app.ui.dialogs.clear(); - let id = open_for_target(&mut app, "noteColor", "Color Picker", [1.0, 0.53, 0.0]); - let f = &app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields; - assert_eq!(f["__webOnly"], json!(true)); - assert_eq!(f["color"], json!("#ff9900")); - assert_eq!(f["__orig"], json!("#ff9900"), "a non-web-safe start colour is not committed by opening the picker"); - } - - #[test] - fn sample_at_snaps_when_only_web_colors_is_on() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let id = open(&mut app, "foreground"); - let f = &mut app.ui.dialog_mut(id).unwrap().fields; - f.insert("__webOnly".into(), json!(true)); - set_rgb(f, [0.07, 0.2, 0.34], Keep::Nothing); - assert_eq!(f["color"], json!("#003366")); - } - - #[test] - fn side_buttons_and_keyboard_confirm_or_cancel_without_changing_the_other_color() { - for target in ["foreground", "background"] { - for action in ["OK", "Cancel", "Enter", "Escape"] { - let app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let mut h = Harness::builder().with_size(vec2(760.0, 480.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - let original_fg = h.state().session.tools.foreground; - let original_bg = h.state().session.tools.background; - let id = open(h.state_mut(), target); - h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("color".into(), json!("#336699")); - h.run_steps(4); - let screen = Rect::from_min_size(pos2(0.0, 0.0), vec2(760.0, 480.0)); - for node in h.query_all_by_role(Role::SpinButton) { - assert!(screen.contains_rect(node.rect()), "numeric inputs fit the minimum window"); - } - for label in ["OK", "Cancel", "Only Web Colors"] { - assert!(screen.contains_rect(h.get_by_label(label).rect()), "{label} fits the minimum window"); - } - match action { - "Enter" => h.key_press(egui::Key::Enter), - "Escape" => h.key_press(egui::Key::Escape), - _ => h.get_by_label(action).click(), - } - h.run_steps(3); - assert!(h.state().ui.dialogs.is_empty(), "{target}: {action} closes the picker"); - let confirm = matches!(action, "OK" | "Enter"); - let tools = &h.state().session.tools; - if confirm && target == "foreground" { - assert_eq!(hex([tools.foreground[0], tools.foreground[1], tools.foreground[2]]), "#336699"); - } else { - assert_eq!(tools.foreground, original_fg); - } - if confirm && target == "background" { - assert_eq!(hex([tools.background[0], tools.background[1], tools.background[2]]), "#336699"); - } else { - assert_eq!(tools.background, original_bg); - } - } - } - } - - /// Hex parsing refuses text whose bytes split a character instead of panicking. - #[test] - fn parse_hex_rejects_multibyte_text() { - // Six bytes, three characters: the byte range 0..2 splits "é", which used to panic. - assert_eq!(parse_hex("aé€"), None); - assert_eq!(parse_hex("#ff880"), None); - } - - /// The shared HSB conversions give bit-identical output to the picker's old copies. - #[test] - fn shared_hsb_output_matches_the_old_picker_conversions() { - /// The picker's HSB to sRGB before it used photocraft-color. - fn old_hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] { - let h = (h.rem_euclid(360.0)) / 60.0; - let c = v * s; - let x = c * (1.0 - (h % 2.0 - 1.0).abs()); - let (r, g, b) = match h as u32 { - 0 => (c, x, 0.0), - 1 => (x, c, 0.0), - 2 => (0.0, c, x), - 3 => (0.0, x, c), - 4 => (x, 0.0, c), - _ => (c, 0.0, x), - }; - let m = v - c; - [r + m, g + m, b + m] - } - /// The picker's sRGB to HSB before it used photocraft-color. - fn old_rgb_to_hsv(c: [f32; 3]) -> [f32; 3] { - let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2])); - let d = mx - mn; - let h = if d <= 0.0 { - 0.0 - } else if mx == c[0] { - 60.0 * ((c[1] - c[2]) / d).rem_euclid(6.0) - } else if mx == c[1] { - 60.0 * ((c[2] - c[0]) / d + 2.0) - } else { - 60.0 * ((c[0] - c[1]) / d + 4.0) - }; - [h, if mx <= 0.0 { 0.0 } else { d / mx }, mx] - } - let bits = |c: [f32; 3]| c.map(f32::to_bits); - for h in (0..=720).map(|i| i as f32 * 0.5) { - for s in (0..=20).map(|i| i as f32 / 20.0) { - for v in (0..=20).map(|i| i as f32 / 20.0) { - assert_eq!(bits(hsb_to_rgb([h, s, v])), bits(old_hsv_to_rgb(h, s, v)), "{h} {s} {v}"); - } - } - } - for r in 0..=32 { - for g in 0..=32 { - for b in 0..=32 { - let c = [r as f32 / 32.0, g as f32 / 32.0, b as f32 / 32.0]; - assert_eq!(bits(rgb_to_hsb(c)), bits(old_rgb_to_hsv(c)), "{c:?}"); - } - } - } - } - - /// HSB and hex round-trip sRGB colours. - #[test] - fn parse_hex_rejects_signs() { - assert_eq!(parse_hex("#+f+f+f"), None); - assert_eq!(parse_hex("+1+2+3"), None); - assert!(parse_hex("#0f0f0f").is_some()); - } - - #[test] - fn hsv_round_trips() { - for c in [[1.0, 0.0, 0.0], [0.2, 0.6, 0.4], [0.5, 0.5, 0.5], [0.0, 0.0, 1.0], [0.9, 0.8, 0.1]] { - let h = rgb_to_hsb(c); - let back = hsb_to_rgb(h); - for i in 0..3 { - assert!((back[i] - c[i]).abs() < 1e-5, "{c:?} -> {h:?} -> {back:?}"); - } - } - assert_eq!(hex([1.0, 0.5, 0.0]), "#ff8000"); - assert_eq!(parse_hex("#FF8000").map(hex).as_deref(), Some("#ff8000")); - } - - /// Locating a colour on the field and reading the field back agree in every mode. - #[test] - fn field_and_locate_are_inverse_in_every_mode() { - let rgb = [0.8, 0.3, 0.2]; - let (hsv, lab) = (rgb_to_hsb(rgb), photocraft_color::convert::srgb_to_lab(rgb)); - for (m, _) in MODES.iter().chain(LAB_MODES) { - let (x, y, z) = locate(m, hsv, rgb, lab); - let c = field_color(m, z, x, y); - assert_eq!(hex(c), hex(rgb), "mode {m}"); - } - } - - #[test] - fn lab_fields_are_laid_out_like_photoshops() { - // Photoshop 25.4. L: a across (green to red), b upwards (blue to yellow). - let l = |x, y| photocraft_color::convert::srgb_to_lab(field_color("lab_l", 0.6, x, y)); - assert!(l(0.0, 0.5)[1] < -40.0 && l(1.0, 0.5)[1] > 40.0, "{:?} {:?}", l(0.0, 0.5), l(1.0, 0.5)); - assert!(l(0.5, 1.0)[2] < -40.0 && l(0.5, 0.0)[2] > 40.0, "{:?} {:?}", l(0.5, 1.0), l(0.5, 0.0)); - // a: b across, L upwards (white at the top, black at the bottom). - assert!(field_color("lab_a", 0.5, 0.5, 0.0).iter().all(|&c| c > 0.99), "white at the top"); - assert!(field_color("lab_a", 0.5, 0.5, 1.0).iter().all(|&c| c < 0.01), "black at the bottom"); - let a = |x| photocraft_color::convert::srgb_to_lab(field_color("lab_a", 0.5, x, 0.5)); - assert!(a(0.0)[2] < -40.0 && a(1.0)[2] > 40.0); - // b: a across, L upwards; its slider runs from yellow (top) to blue. - let b = |x| photocraft_color::convert::srgb_to_lab(field_color("lab_b", 0.5, x, 0.5)); - assert!(b(0.0)[1] < -40.0 && b(1.0)[1] > 40.0); - let lab = [60.0, 0.0, 0.0]; - let top = photocraft_color::convert::srgb_to_lab(slider_color("lab_b", 1.0, [0.0; 3], [0.0; 3], lab)); - let bottom = photocraft_color::convert::srgb_to_lab(slider_color("lab_b", 0.0, [0.0; 3], [0.0; 3], lab)); - assert!(top[2] > 40.0 && bottom[2] < -40.0, "{top:?} {bottom:?}"); - } - - #[test] - fn gamut_and_web_warnings() { - // Photoshop 25.4: #714343 is printable but not a web colour; #fd0303 is neither. - let rgb = |h| parse_hex(h).unwrap(); - assert_eq!(out_of_gamut(rgb("#714343")), None); - assert!(out_of_gamut(rgb("#fd0303")).is_some()); - assert_eq!(out_of_gamut(rgb("#000000")), None, "black prints"); - assert_eq!(out_of_gamut(rgb("#ffffff")), None); - assert_eq!(not_web_safe(rgb("#714343")).map(hex).as_deref(), Some("#663333")); - assert_eq!(not_web_safe(rgb("#cc3366")), None); - } - - #[test] - fn hue_survives_grey_and_ok_sets_the_colour() { - let mut f = Map::new(); - f.insert("color".into(), json!("#808080")); - f.insert("__hsv".into(), json!([200.0, 0.0, 128.0 / 255.0])); - assert_eq!(current(&f).hsv[0], 200.0); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let id = open(&mut app, "background"); - let d = app.ui.dialog_mut(id).unwrap(); - d.fields.insert("color".into(), json!("#3366cc")); - let fields = d.fields.clone(); - confirm(&mut app, &fields).unwrap(); - assert_eq!(hex([app.session.tools.background[0], app.session.tools.background[1], app.session.tools.background[2]]), "#3366cc"); - } - - /// #4196: CMYK values typed into the picker survive OK, so the colour fills a CMYK document with those inks and - /// reopening the picker shows them again. - #[test] - fn cmyk_values_survive_ok_and_a_reopen() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let cyan = [1.0, 0.0, 0.0, 0.0]; - let id = open(&mut app, "foreground"); - let d = app.ui.dialog_mut(id).unwrap(); - set_rgb(&mut d.fields, photocraft_color::convert::cmyk_to_rgb(cyan).map(|c| c.clamp(0.0, 1.0)), Keep::Cmyk(cyan)); - let fields = d.fields.clone(); - confirm(&mut app, &fields).unwrap(); - let fg = app.session.tools.foreground; - assert_eq!(app.session.tools.picked_cmyk([fg[0], fg[1], fg[2]]), Some(cyan)); - let id = open(&mut app, "foreground"); - let again = current(&app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields); - assert_eq!(again.cmyk, cyan); - } - - fn dialog_color(app: &PhotocraftApp, id: u64) -> &str { - app.ui.dialogs.iter().find(|d| d.id == id).and_then(|d| d.fields.get("color")).and_then(Value::as_str).unwrap() - } - - #[test] - fn the_top_picker_samples_the_image() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 40, "height": 20, "background": "transparent"})).unwrap(); - app.run("shape.create", json!({"kind": "rect", "rect": [0, 0, 20, 20], "fill": "#ff0000"})).unwrap(); - app.run("shape.create", json!({"kind": "rect", "rect": [20, 0, 10, 20], "fill": "#00ff00"})).unwrap(); - let id = open(&mut app, "foreground"); - assert_eq!(top(&app), Some(id)); - sample_at(&mut app, 25.5, 5.5); - assert_eq!(dialog_color(&app, id), "#00ff00"); - assert_eq!(app.ui.dialog_mut(id).unwrap().fields["__orig"], json!("#000000"), "the current colour stays"); - // Off the image or over transparency nothing changes. - for (x, y) in [(35.0, 5.0), (-3.0, 5.0), (5.0, 20.0), (1e12, -1e12), (f64::NAN, f64::INFINITY)] { - sample_at(&mut app, x, y); - assert_eq!(dialog_color(&app, id), "#00ff00", "({x}, {y})"); - } - - // Agents: `ui.pointer` samples into the picker instead of driving the tool. - app.ui.tool = crate::state::Tool::Brush; - let rev = app.session.active().unwrap().revision; - let ctx = egui::Context::default(); - let events = json!([{"kind": "down", "x": 5, "y": 5}, {"kind": "up", "x": 5, "y": 5}]); - let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"events": events})); - let _ = crate::control::handle(&mut app, &ctx, &req); - assert_eq!(dialog_color(&app, id), "#ff0000"); - assert_eq!(app.session.active().unwrap().revision, rev, "the Brush must not paint"); - assert_eq!(app.session.tools.foreground, [0.0, 0.0, 0.0, 1.0], "only OK sets the foreground"); - - // A dialog opened over the picker takes the input. - let about = app.ui.open_dialog(DialogKind::About, Map::new()); - assert_eq!(top(&app), None); - sample_at(&mut app, 25.0, 5.0); - assert_eq!(dialog_color(&app, id), "#ff0000"); - app.ui.close_dialog(about); - sample_at(&mut app, 25.0, 5.0); - assert_eq!(dialog_color(&app, id), "#00ff00"); - } -} +mod tests; #[cfg(test)] mod screen_integration_tests { diff --git a/crates/ui-egui/src/color_picker_ui/tests.rs b/crates/ui-egui/src/color_picker_ui/tests.rs new file mode 100644 index 0000000000..02f6b0af20 --- /dev/null +++ b/crates/ui-egui/src/color_picker_ui/tests.rs @@ -0,0 +1,617 @@ +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; + +use super::*; + +/// #4107: with Only Web Colors on, the field is drawn in flat web-safe bands. +#[test] +fn web_only_field_is_flat_web_safe_bands() { + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(200.0, 200.0)); + let m = flat_grid_mesh(rect, WEB_CELLS, |x, y| web_safe(field_color("h", 0.3, x, y))); + let ramp = [0u8, 51, 102, 153, 204, 255]; + for v in &m.vertices { + assert!([v.color.r(), v.color.g(), v.color.b()].iter().all(|c| ramp.contains(c)), "{:?}", v.color); + } + // Each cell's four corners share one colour (no blending between bands). + for q in m.vertices.chunks(4) { + assert!(q.iter().all(|v| v.color == q[0].color)); + } + let distinct: std::collections::HashSet<_> = m.vertices.iter().map(|v| v.color).collect(); + assert!(distinct.len() > 1 && distinct.len() <= 216); +} + +fn picker(color: &str) -> Harness<'static, Map> { + let mut f = Map::new(); + f.insert("__colorPicker".into(), json!("foreground")); + f.insert("color".into(), json!(color)); + f.insert("__orig".into(), json!(color)); + let mut h = Harness::builder().with_size(vec2(700.0, 500.0)).build_ui_state( + |ui, f: &mut Map| { + if ui.ctx().fonts(|fonts| fonts.families().contains(&egui::FontFamily::Name("medium".into()))) { + body(ui, f); + } + }, + f, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(2); + h +} + +/// Type `text` into the focused field one key per frame, like a person typing. +fn type_keys(h: &mut Harness<'static, Map>, text: &str) { + for ch in text.chars() { + h.event(egui::Event::Text(ch.to_string())); + h.run_steps(1); + } +} + +fn color(h: &Harness<'static, Map>) -> String { + h.state().get("color").and_then(Value::as_str).unwrap().to_string() +} + +/// Press at `at` and hold, with no release and no time passing, then run one frame. +fn press(h: &mut Harness<'static, S>, at: egui::Pos2) { + press_button(h, at, egui::PointerButton::Primary, true); +} + +fn press_button(h: &mut Harness<'static, S>, at: egui::Pos2, button: egui::PointerButton, pressed: bool) { + h.event(egui::Event::PointerMoved(at)); + h.event(egui::Event::PointerButton { pos: at, button, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); +} + +/// #7793: the field and the slider pick on the frame the button goes down, not after the +/// pointer has travelled past egui's click threshold or been held for a while, and follow +/// moves of a few points. +#[test] +fn field_and_slider_pick_on_press_and_follow_small_moves() { + let mut f = Map::new(); + f.insert("color".into(), json!("#336699")); + let mut h = Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state( + |ui, f: &mut Map| { + ui.horizontal(|ui| { + let o = ui.cursor().min; + let gap = ui.spacing().item_spacing.x; + ui.data_mut(|d| d.insert_temp(egui::Id::unique("test-origin"), (o, gap))); + color_field(ui, f); + }); + }, + f, + ); + h.run_steps(2); + let (o, gap) = h.ctx.data(|d| d.get_temp::<(egui::Pos2, f32)>(egui::Id::unique("test-origin"))).unwrap(); + // Field: saturation across, brightness down (hue mode). + let at = o + vec2(FIELD * 0.5, FIELD * 0.5); + press(&mut h, at); + let picked = color(&h); + assert_ne!(picked, "#336699", "the press itself picks"); + let hsv = rgb_to_hsb(parse_hex(&picked).unwrap()); + assert!((hsv[1] - 0.5).abs() < 0.02 && (hsv[2] - 0.5).abs() < 0.02, "{picked} {hsv:?}"); + // A 3-point nudge (under the 6-point click threshold) moves the pick. + h.event(egui::Event::PointerMoved(at + vec2(3.0, 0.0))); + h.run_steps(1); + assert_ne!(color(&h), picked, "a small drag adjusts the pick"); + h.event(egui::Event::PointerButton { + pos: at + vec2(3.0, 0.0), + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(2); + // Hue slider: a press near the bottom picks a hue near 0 at once. + let before = color(&h); + press(&mut h, o + vec2(FIELD + gap + 9.0, FIELD * 0.95)); + assert_ne!(color(&h), before, "the slider picks on press"); + let hue = rgb_to_hsb(parse_hex(&color(&h)).unwrap())[0]; + assert!(hue < 30.0 || hue > 330.0, "hue {hue}"); +} + +/// Only the primary button picks: a right or middle press (and its release) on the field or +/// the slider leaves the colour alone. +#[test] +fn field_and_slider_ignore_secondary_and_middle_presses() { + let mut f = Map::new(); + f.insert("color".into(), json!("#336699")); + let mut h = Harness::builder().with_size(vec2(400.0, 300.0)).build_ui_state( + |ui, f: &mut Map| { + ui.horizontal(|ui| { + let o = ui.cursor().min; + let gap = ui.spacing().item_spacing.x; + ui.data_mut(|d| d.insert_temp(egui::Id::unique("test-origin"), (o, gap))); + color_field(ui, f); + }); + }, + f, + ); + h.run_steps(2); + let (o, gap) = h.ctx.data(|d| d.get_temp::<(egui::Pos2, f32)>(egui::Id::unique("test-origin"))).unwrap(); + for at in [o + vec2(FIELD * 0.5, FIELD * 0.5), o + vec2(FIELD + gap + 9.0, FIELD * 0.95)] { + for button in [egui::PointerButton::Secondary, egui::PointerButton::Middle] { + press_button(&mut h, at, button, true); + assert_eq!(color(&h), "#336699", "{button:?} press at {at:?}"); + h.event(egui::Event::PointerMoved(at + vec2(3.0, 0.0))); + h.run_steps(1); + press_button(&mut h, at + vec2(3.0, 0.0), button, false); + h.run_steps(1); + assert_eq!(color(&h), "#336699", "{button:?} drag and release at {at:?}"); + } + } +} + +#[test] +fn hex_field_shows_uppercase_without_rewriting_the_selected_color() { + let h = picker("#12abef"); + assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("12ABEF")); + assert_eq!(color(&h), "#12abef", "casing is presentation only"); +} + +/// #6937: pressing the hue strip must update the colour on the press frame, not only when +/// the button is released (Photoshop updates immediately on click-and-hold). +#[test] +fn hue_strip_updates_the_color_on_press_not_on_release() { + let mut h = picker("#0000ff"); // pure blue: hue 240° + let web = h.get_by_label("Only Web Colors").rect(); + let pick = h.get_by_label("Pick screen color").rect(); + // The strip is 18 pt wide, 6 pt right of the 200 pt field whose left edge is the column's + // (the screen-colour button shares it); its bottom edge is just above the checkbox. + // Press near the bottom: hue ~5°, a red the blue starting colour cannot produce via the field. + let press = pos2(pick.left() + FIELD + 15.0, web.top() - 20.0); + h.event(egui::Event::PointerMoved(press)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: press, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + let held = color(&h); + assert_ne!(held, "#0000ff", "holding the button on the strip must already change the colour"); + // The colour is the red-ish hue near the strip's bottom, not the old blue: had the press + // landed on the field instead of the strip, the hue (and the blue channel) would survive. + let [r, _, b] = parse_hex(&held).unwrap(); + assert!(r > 0.5 && b < 0.2, "expected a red-ish hue from the strip, got {held}"); + h.event(egui::Event::PointerButton { pos: press, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + assert_eq!(color(&h), held, "releasing must not move the colour again"); +} + +#[test] +fn hex_field_takes_typed_digits() { + let mut h = picker("#000000"); + h.get_by_role(Role::TextInput).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + type_keys(&mut h, "ff88"); + // Partial input stays in the field instead of snapping back to the colour. + assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("ff88")); + assert_eq!(color(&h), "#000000"); + type_keys(&mut h, "00"); + assert_eq!(color(&h), "#ff8800"); + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert_eq!(color(&h), "#ff8800"); +} + +#[test] +fn hex_field_takes_every_paste_with_or_without_hash() { + let mut h = picker("#336699"); + for (paste, want) in [("ff8800", "#ff8800"), ("#00ff00", "#00ff00"), (" 1234AB\n", "#1234ab")] { + h.event(egui::Event::Paste(paste.into())); + h.run_steps(2); + assert_eq!(color(&h), want, "paste {paste:?}"); + assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some(&want[1..].to_ascii_uppercase()[..])); + } + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.event(egui::Event::Paste("ff".into())); + h.run_steps(2); + assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("ff")); + assert_eq!(color(&h), "#1234ab"); +} + +#[test] +fn color_picker_opens_with_hex_focused_and_selected() { + let mut h = picker("#336699"); + let hex_field = h.get_by_role(Role::TextInput); + assert!(hex_field.is_focused(), "the hex field automatically has focus on open"); + // Typing directly replaces the selected hex digits without manual clicking or Command+A. + type_keys(&mut h, "ff8800"); + assert_eq!(color(&h), "#ff8800", "typing replaces the selected hex code"); +} + +#[test] +fn color_picker_dialog_hex_field_is_in_tab_order_and_confirms_typed_color() { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut h = Harness::builder().with_size(vec2(760.0, 480.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut(), "foreground"); + h.run_steps(3); + assert!(h.get_by_role(Role::TextInput).is_focused(), "hex field has focus in dialog frame"); + for ch in "ff8800".chars() { + h.event(egui::Event::Text(ch.to_string())); + h.run_steps(1); + } + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(hex([h.state().session.tools.foreground[0], h.state().session.tools.foreground[1], h.state().session.tools.foreground[2]]), "#ff8800"); +} + +#[test] +fn alt_reset_restores_orig_color() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.tools.foreground = [0.2, 0.4, 0.6, 1.0]; + let id = open(&mut app, "foreground"); + let f = &mut app.ui.dialog_mut(id).unwrap().fields; + f.insert("color".into(), json!("#ff0000")); + reset(f); + assert_eq!(f["color"], json!(hex([0.2, 0.4, 0.6]))); + assert_eq!(f["__orig"], json!(hex([0.2, 0.4, 0.6]))); +} + +#[test] +fn lab_and_cmyk_fields_take_multi_digit_values() { + let base = parse_hex("#336699").unwrap(); + let lab = photocraft_color::convert::srgb_to_lab(base); + let cmyk = photocraft_color::convert::rgb_to_cmyk(base); + // Fields in order: H S B R G B, L a b, C M Y K. + for (field, typed, want) in [ + (6, "60", photocraft_color::convert::lab_to_srgb([60.0, lab[1], lab[2]])), + (7, "30", photocraft_color::convert::lab_to_srgb([lab[0], 30.0, lab[2]])), + (9, "40", photocraft_color::convert::cmyk_to_rgb([0.4, cmyk[1], cmyk[2], cmyk[3]])), + ] { + let mut h = picker("#336699"); + h.query_all_by_role(Role::SpinButton).nth(field).unwrap().click(); + h.run_steps(1); + type_keys(&mut h, typed); + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert_eq!(color(&h), hex(want), "field {field} <- {typed}"); + } +} + +#[test] +fn picker_places_actions_above_two_columns_and_web_colors_under_the_field() { + let h = picker("#336699"); + let inputs: Vec<_> = h.query_all_by_role(Role::SpinButton).map(|n| n.rect()).collect(); + assert_eq!(inputs.len(), 13); + let (hue, red, lightness, cyan, black) = (inputs[0], inputs[3], inputs[6], inputs[9], inputs[12]); + assert!(lightness.left() > hue.right(), "Lab is beside HSB, not below RGB"); + assert!((lightness.top() - hue.top()).abs() < 1.0); + assert!((cyan.top() - red.top()).abs() < 1.0, "CMYK and RGB start at the same height"); + let ok = h.get_by_label("OK").rect(); + let cancel = h.get_by_label("Cancel").rect(); + assert!(ok.left() > hue.left() && ok.bottom() < hue.top(), "actions are above the values and beside the preview: {ok:?}, {hue:?}"); + assert!((ok.left() - cancel.left()).abs() < 1.0 && cancel.top() > ok.bottom()); + assert_eq!(h.query_all_by_label("OK").count(), 1); + let web = h.get_by_label("Only Web Colors").rect(); + assert!(web.left() < hue.left() && web.top() > hue.bottom()); + // The full dialog should fit even in PhotoCraft's minimum 760 x 480 window. + assert!(black.bottom() - ok.top() < 360.0); + assert!(black.right() - web.left() < 600.0); + let hex = h.get_by_role(Role::TextInput).rect(); + assert!(hex.left() < lightness.left() && hex.top() > inputs[5].bottom()); +} + +/// The whole Color Picker window (title, frame and all) is no bigger than Photoshop's: about +/// 534 x 376 points (Photoshop 27.11 on macOS, measured from a screenshot at the same scale as +/// PhotoCraft's, which was 682 x 438). +#[test] +fn the_picker_window_is_no_bigger_than_photoshops() { + let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()) + }); + h.run_steps(4); + let id = open(h.state_mut(), "foreground"); + h.run_steps(6); + let rect = h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", id)))).expect("the picker window"); + assert!(rect.width() <= 534.0 && rect.height() <= 376.0, "Color Picker window {} x {} points, Photoshop's 534 x 376", rect.width(), rect.height()); + // Everything still shows: the three actions and all 13 component fields. + for label in ["OK", "Cancel", "Add to Swatches", "Only Web Colors"] { + assert!(rect.contains_rect(h.get_by_label(label).rect()), "{label} inside the window"); + } + assert_eq!(h.query_all_by_role(Role::SpinButton).filter(|n| rect.contains_rect(n.rect())).count(), 13); + // The actions are as wide as the longest label ("Add to Swatches" is about 133 points in + // the button font), not stretched across the column (160). Photoshop's are about 116. + let widths: Vec = ["OK", "Cancel", "Add to Swatches"].iter().map(|l| h.get_by_label(l).rect().width()).collect(); + assert!(widths.iter().all(|w| (w - widths[0]).abs() < 0.5), "one width for all three actions: {widths:?}"); + assert!(widths[0] <= 136.0, "actions {} points wide, Photoshop's about 116", widths[0]); +} + +#[test] +fn web_colors_and_current_swatch_still_update_the_picker() { + let mut h = picker("#123456"); + h.get_by_label("Only Web Colors").click(); + h.run_steps(2); + assert_eq!(color(&h), "#003366"); + assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("003366"), "hex field follows the snap while it has focus"); + h.get_by_label("Only Web Colors").click(); + h.run_steps(2); + h.get_by_label("Click to restore the current colour").click(); + h.run_steps(2); + assert_eq!(color(&h), "#123456"); +} + +/// Only Web Colors snaps hex, field and component edits to web-safe colours. +#[test] +fn web_only_snaps_hex_field_and_component_edits() { + let mut f = Map::new(); + f.insert("color".into(), json!("#123456")); + f.insert("__webOnly".into(), json!(true)); + set_rgb(&mut f, parse_hex("#ff8800").unwrap(), Keep::Nothing); + assert_eq!(f["color"], json!("#ff9900")); + set_rgb(&mut f, hsb_to_rgb([40.0, 1.0, 1.0]), Keep::Hsv([40.0, 1.0, 1.0])); + assert_eq!(f["color"], json!("#ff9900")); + assert!(f.get("__hsv").is_none(), "kept HSV does not outlive a web snap"); + set_rgb(&mut f, photocraft_color::convert::lab_to_srgb([50.0, 40.0, 20.0]).map(|c| c.clamp(0.0, 1.0)), Keep::Lab([50.0, 40.0, 20.0])); + assert_eq!(not_web_safe(parse_hex(f["color"].as_str().unwrap()).unwrap()), None); + assert!(f.get("__lab").is_none()); +} + +#[test] +fn web_only_survives_reopen_and_other_picker_targets() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.color_panel.web_only = true; + let id = open(&mut app, "foreground"); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!(f["__webOnly"], json!(true)); + assert_eq!(f["color"], json!(hex(web_safe([app.session.tools.foreground[0], app.session.tools.foreground[1], app.session.tools.foreground[2]])))); + assert_eq!(f["__orig"], f["color"], "the opening snap moves __orig too, so OK with no edit is unchanged"); + app.ui.dialogs.clear(); + let id = open_for_target(&mut app, "noteColor", "Color Picker", [1.0, 0.53, 0.0]); + let f = &app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields; + assert_eq!(f["__webOnly"], json!(true)); + assert_eq!(f["color"], json!("#ff9900")); + assert_eq!(f["__orig"], json!("#ff9900"), "a non-web-safe start colour is not committed by opening the picker"); +} + +#[test] +fn sample_at_snaps_when_only_web_colors_is_on() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let id = open(&mut app, "foreground"); + let f = &mut app.ui.dialog_mut(id).unwrap().fields; + f.insert("__webOnly".into(), json!(true)); + set_rgb(f, [0.07, 0.2, 0.34], Keep::Nothing); + assert_eq!(f["color"], json!("#003366")); +} + +#[test] +fn side_buttons_and_keyboard_confirm_or_cancel_without_changing_the_other_color() { + for target in ["foreground", "background"] { + for action in ["OK", "Cancel", "Enter", "Escape"] { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let mut h = Harness::builder().with_size(vec2(760.0, 480.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let original_fg = h.state().session.tools.foreground; + let original_bg = h.state().session.tools.background; + let id = open(h.state_mut(), target); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("color".into(), json!("#336699")); + h.run_steps(4); + let screen = Rect::from_min_size(pos2(0.0, 0.0), vec2(760.0, 480.0)); + for node in h.query_all_by_role(Role::SpinButton) { + assert!(screen.contains_rect(node.rect()), "numeric inputs fit the minimum window"); + } + for label in ["OK", "Cancel", "Only Web Colors"] { + assert!(screen.contains_rect(h.get_by_label(label).rect()), "{label} fits the minimum window"); + } + match action { + "Enter" => h.key_press(egui::Key::Enter), + "Escape" => h.key_press(egui::Key::Escape), + _ => h.get_by_label(action).click(), + } + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty(), "{target}: {action} closes the picker"); + let confirm = matches!(action, "OK" | "Enter"); + let tools = &h.state().session.tools; + if confirm && target == "foreground" { + assert_eq!(hex([tools.foreground[0], tools.foreground[1], tools.foreground[2]]), "#336699"); + } else { + assert_eq!(tools.foreground, original_fg); + } + if confirm && target == "background" { + assert_eq!(hex([tools.background[0], tools.background[1], tools.background[2]]), "#336699"); + } else { + assert_eq!(tools.background, original_bg); + } + } + } +} + +/// Hex parsing refuses text whose bytes split a character instead of panicking. +#[test] +fn parse_hex_rejects_multibyte_text() { + // Six bytes, three characters: the byte range 0..2 splits "é", which used to panic. + assert_eq!(parse_hex("aé€"), None); + assert_eq!(parse_hex("#ff880"), None); +} + +/// The shared HSB conversions give bit-identical output to the picker's old copies. +#[test] +fn shared_hsb_output_matches_the_old_picker_conversions() { + /// The picker's HSB to sRGB before it used photocraft-color. + fn old_hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] { + let h = (h.rem_euclid(360.0)) / 60.0; + let c = v * s; + let x = c * (1.0 - (h % 2.0 - 1.0).abs()); + let (r, g, b) = match h as u32 { + 0 => (c, x, 0.0), + 1 => (x, c, 0.0), + 2 => (0.0, c, x), + 3 => (0.0, x, c), + 4 => (x, 0.0, c), + _ => (c, 0.0, x), + }; + let m = v - c; + [r + m, g + m, b + m] + } + /// The picker's sRGB to HSB before it used photocraft-color. + fn old_rgb_to_hsv(c: [f32; 3]) -> [f32; 3] { + let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2])); + let d = mx - mn; + let h = if d <= 0.0 { + 0.0 + } else if mx == c[0] { + 60.0 * ((c[1] - c[2]) / d).rem_euclid(6.0) + } else if mx == c[1] { + 60.0 * ((c[2] - c[0]) / d + 2.0) + } else { + 60.0 * ((c[0] - c[1]) / d + 4.0) + }; + [h, if mx <= 0.0 { 0.0 } else { d / mx }, mx] + } + let bits = |c: [f32; 3]| c.map(f32::to_bits); + for h in (0..=720).map(|i| i as f32 * 0.5) { + for s in (0..=20).map(|i| i as f32 / 20.0) { + for v in (0..=20).map(|i| i as f32 / 20.0) { + assert_eq!(bits(hsb_to_rgb([h, s, v])), bits(old_hsv_to_rgb(h, s, v)), "{h} {s} {v}"); + } + } + } + for r in 0..=32 { + for g in 0..=32 { + for b in 0..=32 { + let c = [r as f32 / 32.0, g as f32 / 32.0, b as f32 / 32.0]; + assert_eq!(bits(rgb_to_hsb(c)), bits(old_rgb_to_hsv(c)), "{c:?}"); + } + } + } +} + +/// HSB and hex round-trip sRGB colours. +#[test] +fn parse_hex_rejects_signs() { + assert_eq!(parse_hex("#+f+f+f"), None); + assert_eq!(parse_hex("+1+2+3"), None); + assert!(parse_hex("#0f0f0f").is_some()); +} + +#[test] +fn hsv_round_trips() { + for c in [[1.0, 0.0, 0.0], [0.2, 0.6, 0.4], [0.5, 0.5, 0.5], [0.0, 0.0, 1.0], [0.9, 0.8, 0.1]] { + let h = rgb_to_hsb(c); + let back = hsb_to_rgb(h); + for i in 0..3 { + assert!((back[i] - c[i]).abs() < 1e-5, "{c:?} -> {h:?} -> {back:?}"); + } + } + assert_eq!(hex([1.0, 0.5, 0.0]), "#ff8000"); + assert_eq!(parse_hex("#FF8000").map(hex).as_deref(), Some("#ff8000")); +} + +/// Locating a colour on the field and reading the field back agree in every mode. +#[test] +fn field_and_locate_are_inverse_in_every_mode() { + let rgb = [0.8, 0.3, 0.2]; + let (hsv, lab) = (rgb_to_hsb(rgb), photocraft_color::convert::srgb_to_lab(rgb)); + for (m, _) in MODES.iter().chain(LAB_MODES) { + let (x, y, z) = locate(m, hsv, rgb, lab); + let c = field_color(m, z, x, y); + assert_eq!(hex(c), hex(rgb), "mode {m}"); + } +} + +#[test] +fn lab_fields_are_laid_out_like_photoshops() { + // Photoshop 25.4. L: a across (green to red), b upwards (blue to yellow). + let l = |x, y| photocraft_color::convert::srgb_to_lab(field_color("lab_l", 0.6, x, y)); + assert!(l(0.0, 0.5)[1] < -40.0 && l(1.0, 0.5)[1] > 40.0, "{:?} {:?}", l(0.0, 0.5), l(1.0, 0.5)); + assert!(l(0.5, 1.0)[2] < -40.0 && l(0.5, 0.0)[2] > 40.0, "{:?} {:?}", l(0.5, 1.0), l(0.5, 0.0)); + // a: b across, L upwards (white at the top, black at the bottom). + assert!(field_color("lab_a", 0.5, 0.5, 0.0).iter().all(|&c| c > 0.99), "white at the top"); + assert!(field_color("lab_a", 0.5, 0.5, 1.0).iter().all(|&c| c < 0.01), "black at the bottom"); + let a = |x| photocraft_color::convert::srgb_to_lab(field_color("lab_a", 0.5, x, 0.5)); + assert!(a(0.0)[2] < -40.0 && a(1.0)[2] > 40.0); + // b: a across, L upwards; its slider runs from yellow (top) to blue. + let b = |x| photocraft_color::convert::srgb_to_lab(field_color("lab_b", 0.5, x, 0.5)); + assert!(b(0.0)[1] < -40.0 && b(1.0)[1] > 40.0); + let lab = [60.0, 0.0, 0.0]; + let top = photocraft_color::convert::srgb_to_lab(slider_color("lab_b", 1.0, [0.0; 3], [0.0; 3], lab)); + let bottom = photocraft_color::convert::srgb_to_lab(slider_color("lab_b", 0.0, [0.0; 3], [0.0; 3], lab)); + assert!(top[2] > 40.0 && bottom[2] < -40.0, "{top:?} {bottom:?}"); +} + +#[test] +fn gamut_and_web_warnings() { + // Photoshop 25.4: #714343 is printable but not a web colour; #fd0303 is neither. + let rgb = |h| parse_hex(h).unwrap(); + assert_eq!(out_of_gamut(rgb("#714343")), None); + assert!(out_of_gamut(rgb("#fd0303")).is_some()); + assert_eq!(out_of_gamut(rgb("#000000")), None, "black prints"); + assert_eq!(out_of_gamut(rgb("#ffffff")), None); + assert_eq!(not_web_safe(rgb("#714343")).map(hex).as_deref(), Some("#663333")); + assert_eq!(not_web_safe(rgb("#cc3366")), None); +} + +#[test] +fn hue_survives_grey_and_ok_sets_the_colour() { + let mut f = Map::new(); + f.insert("color".into(), json!("#808080")); + f.insert("__hsv".into(), json!([200.0, 0.0, 128.0 / 255.0])); + assert_eq!(current(&f).hsv[0], 200.0); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let id = open(&mut app, "background"); + let d = app.ui.dialog_mut(id).unwrap(); + d.fields.insert("color".into(), json!("#3366cc")); + let fields = d.fields.clone(); + confirm(&mut app, &fields).unwrap(); + assert_eq!(hex([app.session.tools.background[0], app.session.tools.background[1], app.session.tools.background[2]]), "#3366cc"); +} + +/// #4196: CMYK values typed into the picker survive OK, so the colour fills a CMYK document with those inks and +/// reopening the picker shows them again. +#[test] +fn cmyk_values_survive_ok_and_a_reopen() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let cyan = [1.0, 0.0, 0.0, 0.0]; + let id = open(&mut app, "foreground"); + let d = app.ui.dialog_mut(id).unwrap(); + set_rgb(&mut d.fields, photocraft_color::convert::cmyk_to_rgb(cyan).map(|c| c.clamp(0.0, 1.0)), Keep::Cmyk(cyan)); + let fields = d.fields.clone(); + confirm(&mut app, &fields).unwrap(); + let fg = app.session.tools.foreground; + assert_eq!(app.session.tools.picked_cmyk([fg[0], fg[1], fg[2]]), Some(cyan)); + let id = open(&mut app, "foreground"); + let again = current(&app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields); + assert_eq!(again.cmyk, cyan); +} + +fn dialog_color(app: &PhotocraftApp, id: u64) -> &str { + app.ui.dialogs.iter().find(|d| d.id == id).and_then(|d| d.fields.get("color")).and_then(Value::as_str).unwrap() +} + +#[test] +fn the_top_picker_samples_the_image() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 40, "height": 20, "background": "transparent"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [0, 0, 20, 20], "fill": "#ff0000"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [20, 0, 10, 20], "fill": "#00ff00"})).unwrap(); + let id = open(&mut app, "foreground"); + assert_eq!(top(&app), Some(id)); + sample_at(&mut app, 25.5, 5.5); + assert_eq!(dialog_color(&app, id), "#00ff00"); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["__orig"], json!("#000000"), "the current colour stays"); + // Off the image or over transparency nothing changes. + for (x, y) in [(35.0, 5.0), (-3.0, 5.0), (5.0, 20.0), (1e12, -1e12), (f64::NAN, f64::INFINITY)] { + sample_at(&mut app, x, y); + assert_eq!(dialog_color(&app, id), "#00ff00", "({x}, {y})"); + } + + // Agents: `ui.pointer` samples into the picker instead of driving the tool. + app.ui.tool = crate::state::Tool::Brush; + let rev = app.session.active().unwrap().revision; + let ctx = egui::Context::default(); + let events = json!([{"kind": "down", "x": 5, "y": 5}, {"kind": "up", "x": 5, "y": 5}]); + let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"events": events})); + let _ = crate::control::handle(&mut app, &ctx, &req); + assert_eq!(dialog_color(&app, id), "#ff0000"); + assert_eq!(app.session.active().unwrap().revision, rev, "the Brush must not paint"); + assert_eq!(app.session.tools.foreground, [0.0, 0.0, 0.0, 1.0], "only OK sets the foreground"); + + // A dialog opened over the picker takes the input. + let about = app.ui.open_dialog(DialogKind::About, Map::new()); + assert_eq!(top(&app), None); + sample_at(&mut app, 25.0, 5.0); + assert_eq!(dialog_color(&app, id), "#ff0000"); + app.ui.close_dialog(about); + sample_at(&mut app, 25.0, 5.0); + assert_eq!(dialog_color(&app, id), "#00ff00"); +} From 7ac0c649b6c9bb639d6fb1eaa630c1d6c5fd73b7 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:39 +0000 Subject: [PATCH 062/259] refactor(ui-egui): move dialogs.rs tests to dialogs/tests.rs --- crates/ui-egui/src/dialogs.rs | 434 +--------------------------- crates/ui-egui/src/dialogs/tests.rs | 431 +++++++++++++++++++++++++++ 2 files changed, 432 insertions(+), 433 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/tests.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6dfa4f70d1..e99864ded8 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -980,439 +980,7 @@ pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str) } #[cfg(test)] -mod tests { - use super::*; - - /// A filter dialog over a 256×256 layer, with the preview the canvas computed for it on screen. - fn filter_dialog_with_preview(background: bool) -> (PhotocraftApp, u64) { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.background_jobs = background; - app.run("file.new", serde_json::json!({"width": 256, "height": 256, "background": "#3366cc"})).unwrap(); - let id = open_command_dialog(&mut app, "filter.blur.gaussianBlur", "Gaussian Blur"); - let st = app.session.active().unwrap(); - let result = crate::filter_dialog::preview_document(&st.doc, st.active_layer, "filter.blur.gaussianBlur", &serde_json::json!({"radius": 4.0}), 1); - let key = crate::filter_dialog::FilterPreviewKey { - doc: st.doc.id, - revision: st.revision, - dialog: id, - active: st.active_layer, - target: st.channel_view.target, - command: "filter.blur.gaussianBlur".into(), - params: serde_json::json!({"radius": 4.0}), - k: 1, - }; - app.filter_preview = Some(crate::filter_dialog::FilterPreview { key, result: result.map(std::sync::Arc::new), committing: false }); - (app, id) - } - - #[test] - fn a_filters_preview_stays_on_screen_until_its_job_lands() { - // OK dropped the preview and the filter ran as a background job, so the canvas flashed - // the unfiltered image until the job finished. - let (mut app, id) = filter_dialog_with_preview(true); - let revision = app.session.active().unwrap().revision; - confirm(&mut app, id).unwrap(); - let doc = app.session.active().unwrap().doc.id; - let job = app.session.job_on(doc).expect("the blur runs as a background job").id; - assert!(matches!(crate::canvas::committed_filter_preview(&mut app, 0), Some(Some((1, _, [256, 256])))), "the preview is shown"); - // The job lands: the document changes and the preview goes. - app.session.wait_job(job).unwrap(); - assert_ne!(app.session.active().unwrap().revision, revision); - assert_eq!(crate::canvas::committed_filter_preview(&mut app, 0), Some(None)); - assert!(app.filter_preview.is_none()); - - // A cancelled job leaves the document as it was, so its preview goes too. - let (mut app, id) = filter_dialog_with_preview(true); - confirm(&mut app, id).unwrap(); - let doc = app.session.active().unwrap().doc.id; - let job = app.session.job_on(doc).unwrap().id; - assert!(matches!(crate::canvas::committed_filter_preview(&mut app, 0), Some(Some(_)))); - assert!(app.session.cancel_job(job)); - assert_eq!(crate::canvas::committed_filter_preview(&mut app, 0), Some(None)); - assert!(app.filter_preview.is_none()); - - // Inline (no background jobs): the filter has already landed, nothing is held. - let (mut app, id) = filter_dialog_with_preview(false); - confirm(&mut app, id).unwrap(); - assert!(app.filter_preview.is_none()); - assert_eq!(crate::canvas::committed_filter_preview(&mut app, 0), None); - } - - /// #5496: a pointer click on the title bar's close box does what Cancel does: the dialog - /// closes, the live preview goes and nothing reaches the document or the journal. On macOS - /// dialogs have no close box. - #[test] - fn the_title_bar_close_box_cancels_like_cancel() { - use egui_kittest::kittest::Queryable; - let close = |button: &str| { - let (mut app, _) = filter_dialog_with_preview(false); - let revision = app.session.active().unwrap().revision; - let journal = app.session.journal.len(); - // The fonts are set up after the harness's first frame: the dialog appears after it. - let dialogs = std::mem::take(&mut app.ui.dialogs); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.state_mut().ui.dialogs = dialogs; - h.run_steps(4); - assert!(h.state().filter_preview.is_some(), "the preview is on screen"); - if !CLOSE_BOX { - assert_eq!(h.query_all_by_label("Close").count(), 0, "no close box on macOS"); - } - let target = h.query_by_label(button).map(|n| n.rect().center())?; - h.hover_at(target); - h.drag_at(target); - h.drop_at(target); - h.run_steps(3); - let app = h.state(); - Some(( - app.ui.dialogs.is_empty(), - app.filter_preview.is_none(), - app.session.active().unwrap().revision == revision, - app.session.journal.len() == journal, - )) - }; - let cancel = close("Cancel"); - assert_eq!(cancel, Some((true, true, true, true)), "Cancel closes, drops the preview and changes nothing"); - if CLOSE_BOX { - assert_eq!(close("Close"), cancel, "the × is Cancel"); - } - } - - /// #5496: the close box sits at the title band's right end, and the band stays a drag handle - /// around it: a drag that starts on the × neither moves nor closes the dialog, and the band - /// just left of the × still moves it. - #[test] - fn the_close_box_and_the_title_drag_keep_apart() { - use egui_kittest::kittest::Queryable; - if !CLOSE_BOX { - return; - } - let mut h = dialog_harness(egui::vec2(1280.0, 800.0), "filter.blur.gaussianBlur"); - let title = h.get_by_label("Gaussian Blur").rect(); - let x = h.get_by_label("Close").rect(); - let frame = rects(&h.ctx)[0]; - assert!((x.center().y - title.center().y).abs() < 2.0 && x.left() > title.right(), "the × is on the title row: {x:?}, {title:?}"); - assert!(frame.right() - x.right() < 16.0, "at its right end: {x:?} in {frame:?}"); - let drag = |h: &mut egui_kittest::Harness<'static, PhotocraftApp>, from: egui::Pos2, to: egui::Pos2| { - h.hover_at(from); - h.drag_at(from); - h.run_steps(2); - for i in 1..=8 { - h.hover_at(from + (to - from) * (i as f32 / 8.0)); - h.run_steps(1); - } - h.drop_at(to); - h.run_steps(3); - }; - drag(&mut h, x.center(), x.center() + egui::vec2(-80.0, 60.0)); - assert_eq!(h.state().ui.dialogs.len(), 1, "a drag from the × doesn't close the dialog"); - assert!((h.get_by_label("Gaussian Blur").rect().min - title.min).length() < 1.0, "nor move it"); - let x = h.get_by_label("Close").rect(); - let beside = x.left_center() - egui::vec2(4.0, 0.0); - drag(&mut h, beside, beside + egui::vec2(-120.0, 40.0)); - assert_eq!(h.state().ui.dialogs.len(), 1, "a title drag doesn't close the dialog"); - let moved = h.get_by_label("Gaussian Blur").rect().min - title.min; - assert!((moved - egui::vec2(-120.0, 40.0)).length() < 2.0, "the band beside the × moved the dialog: {moved:?}"); - } - - /// #6810: dragging a dialog's title moves the dialog under the pointer, so the press origin is - /// no longer inside it; that drag must not pan the canvas or reach a canvas tool. - #[test] - fn dragging_a_dialog_title_does_not_pan_the_canvas() { - let ctx = egui::Context::default(); - let canvas = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1000.0, 800.0)); - let at_press = egui::Rect::from_min_max(egui::pos2(100.0, 100.0), egui::pos2(300.0, 200.0)); - let moved = egui::Rect::from_min_max(egui::pos2(550.0, 480.0), egui::pos2(750.0, 580.0)); - let run = |rect: egui::Rect, events: Vec| { - ctx.data_mut(|m| m.insert_temp(egui::Id::unique(RECTS), vec![rect])); - ctx.begin_pass(egui::RawInput { events, ..Default::default() }); - let out = (pan_delta(&ctx, canvas, true), free_press(&ctx, canvas)); - ctx.end_pass().textures_delta.clear(); - out - }; - let press = - egui::Event::PointerButton { pos: egui::pos2(150.0, 120.0), button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; - let (pan, click) = run(at_press, vec![egui::Event::PointerMoved(egui::pos2(150.0, 120.0)), press]); - assert!(pan.is_none() && click.is_none(), "the press is on the dialog"); - let (pan, click) = run(moved, vec![egui::Event::PointerMoved(egui::pos2(600.0, 500.0))]); - assert!(pan.is_none(), "the dialog moved away from the press origin: {pan:?}"); - assert!(click.is_none(), "and the drag is not a canvas tool drag: {click:?}"); - } - - #[test] - fn color_picker_has_inset_content_and_actions_at_the_right_edge() { - use egui_kittest::{Harness, kittest::Queryable}; - - for size in [egui::vec2(760.0, 480.0), egui::vec2(960.0, 640.0)] { - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut h = Harness::builder().with_size(size).build_ui_state(|ui, app| show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - crate::color_picker_ui::open(h.state_mut(), "foreground"); - h.run_steps(4); - let frame = rects(&h.ctx)[0]; - let title = h.get_by_label("Color Picker (Foreground Color)").rect(); - let ok = h.get_by_label("OK").rect(); - let cancel = h.get_by_label("Cancel").rect(); - let web = h.get_by_label("Only Web Colors").rect(); - assert!((ok.right() - title.right()).abs() < 1.0, "OK aligns with the right content edge: {ok:?} vs {title:?}"); - assert!((cancel.right() - ok.right()).abs() < 1.0); - assert!(frame.right() - ok.right() >= 16.0, "buttons retain the window's padding"); - assert!(web.left() - frame.left() >= 16.0, "checkbox has comfortable left padding"); - assert!(frame.bottom() - web.bottom() >= 16.0, "checkbox has comfortable bottom padding"); - assert!(title.top() - frame.top() >= 16.0, "title has top padding"); - assert!(egui::Rect::from_min_size(egui::Pos2::ZERO, size).contains_rect(frame), "padded picker fits {size:?}: {frame:?}"); - // A click anywhere inside the added margin must stay out of the canvas eyedropper. - let margin = egui::pos2(frame.left() + 8.0, web.center().y); - h.hover_at(margin); - h.run_steps(1); - assert!(free_pointer_over(&h.ctx, egui::Rect::from_min_size(egui::Pos2::ZERO, size)).is_none()); - } - } - - #[test] - fn layer_style_title_gutters_can_start_drags() { - use egui_kittest::{Harness, kittest::Queryable}; - - for point in 0..5 { - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.state_mut().ui.open_dialog(DialogKind::LayerStyle, serde_json::Map::new()); - h.run_steps(3); - let before = h.get_by_label("Layer Style").rect(); - let from = match point { - 0 => egui::pos2(before.left() - 5.0, before.bottom() - 4.0), - 1 => egui::pos2(before.right() + 5.0, before.bottom() - 4.0), - 2 => egui::pos2(before.center().x, before.bottom() + 3.0), - 3 => egui::pos2(before.center().x, before.top() - 5.0), - _ => egui::pos2(before.center().x, before.bottom() - 3.0), - }; - h.hover_at(from); - h.drag_at(from); - h.run_steps(2); - for i in 1..=8 { - h.hover_at(from + egui::vec2(64.0, -32.0) * (i as f32 / 8.0)); - h.run_steps(1); - } - h.drop_at(from + egui::vec2(64.0, -32.0)); - h.run_steps(3); - let delta = h.get_by_label("Layer Style").rect().min - before.min; - assert!((delta - egui::vec2(64.0, -32.0)).length() < 2.0, "point {point}: moved {delta:?}"); - assert_eq!(h.state().ui.dialogs.len(), 1); - } - } - - #[test] - fn dragging_the_title_bar_moves_the_dialog() { - use egui_kittest::{Harness, kittest::Queryable}; - - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut harness = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); - harness.state_mut().ui.open_dialog(DialogKind::LayerStyle, serde_json::Map::new()); - harness.run_steps(3); - let before = harness.get_by_label("Layer Style").rect(); - - // Grab the title text itself: it must move the dialog, not select the text. - let from = before.center(); - harness.hover_at(from); - harness.drag_at(from); - harness.run_steps(2); - for i in 1..=10 { - harness.hover_at(from + egui::vec2(-12.0, 8.0) * i as f32); - harness.run_steps(1); - } - harness.drop_at(from + egui::vec2(-120.0, 80.0)); - harness.run_steps(3); - - let moved = harness.get_by_label("Layer Style").rect().min - before.min; - assert!((moved - egui::vec2(-120.0, 80.0)).length() < 1.0, "dialog moved by {moved:?}"); - assert_eq!(harness.state().ui.dialogs.len(), 1, "dragging must not close the dialog"); - } - - /// #4872: an alert (Error, About) closes with ↩ as with OK, but not on the ↩ that raised it. - #[test] - fn enter_closes_an_alert_but_not_the_enter_that_opened_it() { - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 600.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.run_steps(2); - let alert = |h: &mut egui_kittest::Harness<'static, PhotocraftApp>| { - h.state_mut().ui.open_dialog(DialogKind::Error, json!({"message": crate::move_lock::MESSAGE}).as_object().cloned().unwrap_or_default()) - }; - // Raised in the frame its own ↩ arrives: that ↩ leaves it open. - alert(&mut h); - h.key_press(egui::Key::Enter); - h.run_steps(2); - assert_eq!(h.state().ui.dialogs.len(), 1, "the ↩ that raised the alert doesn't close it"); - h.key_press(egui::Key::Enter); - h.run_steps(2); - assert!(h.state().ui.dialogs.is_empty(), "↩ is OK"); - // A new alert starts over, and Esc still closes it. - alert(&mut h); - h.run_steps(2); - h.key_press(egui::Key::Escape); - h.run_steps(2); - assert!(h.state().ui.dialogs.is_empty(), "Esc too"); - } - - fn dialog_harness(size: egui::Vec2, command: &str) -> egui_kittest::Harness<'static, PhotocraftApp> { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); - let mut h = egui_kittest::Harness::builder().with_size(size).build_ui_state(|ui, app| show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - crate::filter_dialog::open(h.state_mut(), command).unwrap(); - h.run_steps(4); - h - } - - /// #3152: Motion Blur's angle is a dial, as in Photoshop. Clicking or dragging it points the - /// blur; the field still takes the whole -360..360 range. - #[test] - fn motion_blur_angle_dial_sets_the_angle_by_click_and_drag() { - use egui_kittest::kittest::Queryable; - let mut h = dialog_harness(egui::vec2(1280.0, 800.0), "filter.blur.motionBlur"); - let angle = |h: &egui_kittest::Harness<'static, PhotocraftApp>| h.state().ui.dialogs.last().and_then(|d| d.fields["angle"].as_f64()); - let centre = |h: &egui_kittest::Harness<'static, PhotocraftApp>| h.get_by_role_and_label(egui::accesskit::Role::Slider, "Angle").rect().center(); - let press = |h: &mut egui_kittest::Harness<'static, PhotocraftApp>, pos: egui::Pos2, pressed: bool| { - h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); - }; - assert_eq!(angle(&h), Some(0.0)); - // The dial's field is the dialog's first number, so it opens focused (#1757). - let first = h.get_all_by_role(egui::accesskit::Role::SpinButton).next().unwrap(); - let distance = h.query_all_by_label("Distance").next().expect("the Distance field").rect(); - assert!(first.is_focused() && first.rect().center().y < distance.center().y, "the Angle field has focus"); - // Click above the centre: straight up is 90°. - let up = centre(&h) + egui::vec2(0.0, -15.0); - h.event(egui::Event::PointerMoved(up)); - press(&mut h, up, true); - h.step(); - press(&mut h, up, false); - h.run_steps(3); - assert_eq!(angle(&h), Some(90.0)); - // Drag from the right (0°) round to the lower left (-135°). - let c = centre(&h); - let from = c + egui::vec2(15.0, 0.0); - h.event(egui::Event::PointerMoved(from)); - press(&mut h, from, true); - h.step(); - for (k, to) in [egui::vec2(12.0, 12.0), egui::vec2(0.0, 15.0), egui::vec2(-12.0, 12.0)].into_iter().enumerate() { - h.event(egui::Event::PointerMoved(c + to)); - h.step(); - assert_eq!(angle(&h), Some([-45.0, -90.0, -135.0][k]), "dragged to {to:?}"); - } - press(&mut h, c + egui::vec2(-12.0, 12.0), false); - h.run_steps(3); - assert_eq!(angle(&h), Some(-135.0)); - // A remembered or typed angle past half a turn is kept, not clamped to the dial's ±180°. - if let Some(d) = h.state_mut().ui.dialogs.last_mut() { - d.fields.insert("angle".into(), json!(270.0)); - } - h.run_steps(3); - assert_eq!(angle(&h), Some(270.0)); - } - - #[test] - fn a_tall_filter_dialog_keeps_its_title_and_buttons_in_a_small_window() { - // Filter › Render › Flame was taller than a 1000×560 window: OK and Cancel were cut off. - use egui_kittest::kittest::Queryable; - let size = egui::vec2(1000.0, 560.0); - let h = dialog_harness(size, "filter.render.flame"); - for label in ["Flame", "OK", "Cancel"] { - let r = h.get_by_label(label).rect(); - assert!(r.top() >= 0.0 && r.bottom() <= size.y, "{label} at {r:?} is outside the {size:?} window"); - } - } - - #[test] - fn a_moved_dialog_reopens_where_it_was_left() { - use egui_kittest::kittest::Queryable; - let size = egui::vec2(1280.0, 800.0); - let mut h = dialog_harness(size, "filter.blur.gaussianBlur"); - let centred = h.get_by_label("Gaussian Blur").rect(); - // Drag the title bar up and to the left. - let (from, by) = (centred.center(), egui::vec2(-240.0, -150.0)); - h.event(egui::Event::PointerMoved(from)); - h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); - for k in 1..=6 { - h.event(egui::Event::PointerMoved(from + by * (k as f32 / 6.0))); - h.step(); - } - h.event(egui::Event::PointerButton { pos: from + by, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); - h.run_steps(3); - let moved = h.get_by_label("Gaussian Blur").rect(); - assert!((moved.min - (centred.min + by)).length() < 2.0, "dragged: {centred:?} → {moved:?}"); - h.get_by_label("Cancel").click(); - h.run_steps(3); - assert!(h.state().ui.dialogs.is_empty()); - // Reopened: where it was left. - crate::filter_dialog::open(h.state_mut(), "filter.blur.gaussianBlur").unwrap(); - h.run_steps(4); - let reopened = h.get_by_label("Gaussian Blur").rect(); - assert!((reopened.min - moved.min).length() < 2.0, "reopened at {reopened:?}, left at {moved:?}"); - h.get_by_label("Cancel").click(); - h.run_steps(3); - // Another dialog keeps its own place: never moved, it opens centred. - crate::filter_dialog::open(h.state_mut(), "filter.blur.motionBlur").unwrap(); - h.run_steps(4); - let other = h.get_by_label("Motion Blur").rect(); - assert!(other.min.x > moved.min.x + 100.0, "Motion Blur opened centred: {other:?}"); - } - - /// #1757: like Photoshop, a value dialog opens on its first number with the text selected, so - /// typing replaces it and Enter applies it; it reopens with the value applied last time, and a - /// cancelled edit is not remembered. - #[test] - fn a_value_dialog_opens_on_its_first_number_selected_and_remembers_it() { - use egui_kittest::kittest::Queryable; - const BLUR: &str = "filter.blur.gaussianBlur"; - let mut h = dialog_harness(egui::vec2(1280.0, 800.0), BLUR); - let radius = |h: &egui_kittest::Harness<'static, PhotocraftApp>| h.state().ui.dialogs.last().and_then(|d| d.fields["radius"].as_f64()); - assert_eq!(radius(&h), Some(1.0), "the default the first time"); - assert!(h.get_by_role(egui::accesskit::Role::SpinButton).is_focused(), "the Radius field has focus"); - h.event(egui::Event::Text("5".into())); - h.run_steps(1); - assert_eq!(radius(&h), Some(5.0), "typing replaced the selected 1"); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert!(h.state().ui.dialogs.is_empty(), "Enter is OK"); - assert_eq!(h.state().session.journal.last(), Some(&(BLUR.to_string(), json!({"radius": 5.0})))); - - crate::filter_dialog::open(h.state_mut(), BLUR).unwrap(); - h.run_steps(4); - assert_eq!(radius(&h), Some(5.0), "reopens with the last value"); - assert!(h.get_by_role(egui::accesskit::Role::SpinButton).is_focused(), "focused again"); - h.event(egui::Event::Text("9".into())); - h.run_steps(1); - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert!(h.state().ui.dialogs.is_empty(), "Esc is Cancel"); - crate::filter_dialog::open(h.state_mut(), BLUR).unwrap(); - h.run_steps(2); - assert_eq!(radius(&h), Some(5.0), "a cancelled 9 is not remembered"); - } - - /// #4673: File › Automate › Fit Image holds two numbers and a check box, so its window is as - /// wide as that content and its buttons, not the 380-point floor of the larger dialogs. - #[test] - fn fit_image_is_as_narrow_as_its_content() { - 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(); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - let ctx = h.ctx.clone(); - let d = crate::menus::invoke(h.state_mut(), &ctx, "file.automate.fitImage", json!({})).unwrap()["dialog"].as_u64().unwrap(); - h.run_steps(4); - let window = h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", d)))).expect("the Fit Image window"); - assert!(window.width() < 300.0, "Fit Image is {} points wide", window.width()); - for label in ["Fit Image", "Width", "Height", "OK", "Cancel"] { - // A caption and the field it names share the label; either sits inside the window. - let node = h.query_all_by_label(label).next().unwrap_or_else(|| panic!("{label} in the dialog")); - assert!(window.contains_rect(node.rect()), "{label} inside the window"); - } - } -} +mod tests; #[cfg(test)] mod preference_resize_tests { diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs new file mode 100644 index 0000000000..5635b56ead --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -0,0 +1,431 @@ +use super::*; + +/// A filter dialog over a 256×256 layer, with the preview the canvas computed for it on screen. +fn filter_dialog_with_preview(background: bool) -> (PhotocraftApp, u64) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = background; + app.run("file.new", serde_json::json!({"width": 256, "height": 256, "background": "#3366cc"})).unwrap(); + let id = open_command_dialog(&mut app, "filter.blur.gaussianBlur", "Gaussian Blur"); + let st = app.session.active().unwrap(); + let result = crate::filter_dialog::preview_document(&st.doc, st.active_layer, "filter.blur.gaussianBlur", &serde_json::json!({"radius": 4.0}), 1); + let key = crate::filter_dialog::FilterPreviewKey { + doc: st.doc.id, + revision: st.revision, + dialog: id, + active: st.active_layer, + target: st.channel_view.target, + command: "filter.blur.gaussianBlur".into(), + params: serde_json::json!({"radius": 4.0}), + k: 1, + }; + app.filter_preview = Some(crate::filter_dialog::FilterPreview { key, result: result.map(std::sync::Arc::new), committing: false }); + (app, id) +} + +#[test] +fn a_filters_preview_stays_on_screen_until_its_job_lands() { + // OK dropped the preview and the filter ran as a background job, so the canvas flashed + // the unfiltered image until the job finished. + let (mut app, id) = filter_dialog_with_preview(true); + let revision = app.session.active().unwrap().revision; + confirm(&mut app, id).unwrap(); + let doc = app.session.active().unwrap().doc.id; + let job = app.session.job_on(doc).expect("the blur runs as a background job").id; + assert!(matches!(crate::canvas::committed_filter_preview(&mut app, 0), Some(Some((1, _, [256, 256])))), "the preview is shown"); + // The job lands: the document changes and the preview goes. + app.session.wait_job(job).unwrap(); + assert_ne!(app.session.active().unwrap().revision, revision); + assert_eq!(crate::canvas::committed_filter_preview(&mut app, 0), Some(None)); + assert!(app.filter_preview.is_none()); + + // A cancelled job leaves the document as it was, so its preview goes too. + let (mut app, id) = filter_dialog_with_preview(true); + confirm(&mut app, id).unwrap(); + let doc = app.session.active().unwrap().doc.id; + let job = app.session.job_on(doc).unwrap().id; + assert!(matches!(crate::canvas::committed_filter_preview(&mut app, 0), Some(Some(_)))); + assert!(app.session.cancel_job(job)); + assert_eq!(crate::canvas::committed_filter_preview(&mut app, 0), Some(None)); + assert!(app.filter_preview.is_none()); + + // Inline (no background jobs): the filter has already landed, nothing is held. + let (mut app, id) = filter_dialog_with_preview(false); + confirm(&mut app, id).unwrap(); + assert!(app.filter_preview.is_none()); + assert_eq!(crate::canvas::committed_filter_preview(&mut app, 0), None); +} + +/// #5496: a pointer click on the title bar's close box does what Cancel does: the dialog +/// closes, the live preview goes and nothing reaches the document or the journal. On macOS +/// dialogs have no close box. +#[test] +fn the_title_bar_close_box_cancels_like_cancel() { + use egui_kittest::kittest::Queryable; + let close = |button: &str| { + let (mut app, _) = filter_dialog_with_preview(false); + let revision = app.session.active().unwrap().revision; + let journal = app.session.journal.len(); + // The fonts are set up after the harness's first frame: the dialog appears after it. + let dialogs = std::mem::take(&mut app.ui.dialogs); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.state_mut().ui.dialogs = dialogs; + h.run_steps(4); + assert!(h.state().filter_preview.is_some(), "the preview is on screen"); + if !CLOSE_BOX { + assert_eq!(h.query_all_by_label("Close").count(), 0, "no close box on macOS"); + } + let target = h.query_by_label(button).map(|n| n.rect().center())?; + h.hover_at(target); + h.drag_at(target); + h.drop_at(target); + h.run_steps(3); + let app = h.state(); + Some(( + app.ui.dialogs.is_empty(), + app.filter_preview.is_none(), + app.session.active().unwrap().revision == revision, + app.session.journal.len() == journal, + )) + }; + let cancel = close("Cancel"); + assert_eq!(cancel, Some((true, true, true, true)), "Cancel closes, drops the preview and changes nothing"); + if CLOSE_BOX { + assert_eq!(close("Close"), cancel, "the × is Cancel"); + } +} + +/// #5496: the close box sits at the title band's right end, and the band stays a drag handle +/// around it: a drag that starts on the × neither moves nor closes the dialog, and the band +/// just left of the × still moves it. +#[test] +fn the_close_box_and_the_title_drag_keep_apart() { + use egui_kittest::kittest::Queryable; + if !CLOSE_BOX { + return; + } + let mut h = dialog_harness(egui::vec2(1280.0, 800.0), "filter.blur.gaussianBlur"); + let title = h.get_by_label("Gaussian Blur").rect(); + let x = h.get_by_label("Close").rect(); + let frame = rects(&h.ctx)[0]; + assert!((x.center().y - title.center().y).abs() < 2.0 && x.left() > title.right(), "the × is on the title row: {x:?}, {title:?}"); + assert!(frame.right() - x.right() < 16.0, "at its right end: {x:?} in {frame:?}"); + let drag = |h: &mut egui_kittest::Harness<'static, PhotocraftApp>, from: egui::Pos2, to: egui::Pos2| { + h.hover_at(from); + h.drag_at(from); + h.run_steps(2); + for i in 1..=8 { + h.hover_at(from + (to - from) * (i as f32 / 8.0)); + h.run_steps(1); + } + h.drop_at(to); + h.run_steps(3); + }; + drag(&mut h, x.center(), x.center() + egui::vec2(-80.0, 60.0)); + assert_eq!(h.state().ui.dialogs.len(), 1, "a drag from the × doesn't close the dialog"); + assert!((h.get_by_label("Gaussian Blur").rect().min - title.min).length() < 1.0, "nor move it"); + let x = h.get_by_label("Close").rect(); + let beside = x.left_center() - egui::vec2(4.0, 0.0); + drag(&mut h, beside, beside + egui::vec2(-120.0, 40.0)); + assert_eq!(h.state().ui.dialogs.len(), 1, "a title drag doesn't close the dialog"); + let moved = h.get_by_label("Gaussian Blur").rect().min - title.min; + assert!((moved - egui::vec2(-120.0, 40.0)).length() < 2.0, "the band beside the × moved the dialog: {moved:?}"); +} + +/// #6810: dragging a dialog's title moves the dialog under the pointer, so the press origin is +/// no longer inside it; that drag must not pan the canvas or reach a canvas tool. +#[test] +fn dragging_a_dialog_title_does_not_pan_the_canvas() { + let ctx = egui::Context::default(); + let canvas = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1000.0, 800.0)); + let at_press = egui::Rect::from_min_max(egui::pos2(100.0, 100.0), egui::pos2(300.0, 200.0)); + let moved = egui::Rect::from_min_max(egui::pos2(550.0, 480.0), egui::pos2(750.0, 580.0)); + let run = |rect: egui::Rect, events: Vec| { + ctx.data_mut(|m| m.insert_temp(egui::Id::unique(RECTS), vec![rect])); + ctx.begin_pass(egui::RawInput { events, ..Default::default() }); + let out = (pan_delta(&ctx, canvas, true), free_press(&ctx, canvas)); + ctx.end_pass().textures_delta.clear(); + out + }; + let press = + egui::Event::PointerButton { pos: egui::pos2(150.0, 120.0), button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + let (pan, click) = run(at_press, vec![egui::Event::PointerMoved(egui::pos2(150.0, 120.0)), press]); + assert!(pan.is_none() && click.is_none(), "the press is on the dialog"); + let (pan, click) = run(moved, vec![egui::Event::PointerMoved(egui::pos2(600.0, 500.0))]); + assert!(pan.is_none(), "the dialog moved away from the press origin: {pan:?}"); + assert!(click.is_none(), "and the drag is not a canvas tool drag: {click:?}"); +} + +#[test] +fn color_picker_has_inset_content_and_actions_at_the_right_edge() { + use egui_kittest::{Harness, kittest::Queryable}; + + for size in [egui::vec2(760.0, 480.0), egui::vec2(960.0, 640.0)] { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut h = Harness::builder().with_size(size).build_ui_state(|ui, app| show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + crate::color_picker_ui::open(h.state_mut(), "foreground"); + h.run_steps(4); + let frame = rects(&h.ctx)[0]; + let title = h.get_by_label("Color Picker (Foreground Color)").rect(); + let ok = h.get_by_label("OK").rect(); + let cancel = h.get_by_label("Cancel").rect(); + let web = h.get_by_label("Only Web Colors").rect(); + assert!((ok.right() - title.right()).abs() < 1.0, "OK aligns with the right content edge: {ok:?} vs {title:?}"); + assert!((cancel.right() - ok.right()).abs() < 1.0); + assert!(frame.right() - ok.right() >= 16.0, "buttons retain the window's padding"); + assert!(web.left() - frame.left() >= 16.0, "checkbox has comfortable left padding"); + assert!(frame.bottom() - web.bottom() >= 16.0, "checkbox has comfortable bottom padding"); + assert!(title.top() - frame.top() >= 16.0, "title has top padding"); + assert!(egui::Rect::from_min_size(egui::Pos2::ZERO, size).contains_rect(frame), "padded picker fits {size:?}: {frame:?}"); + // A click anywhere inside the added margin must stay out of the canvas eyedropper. + let margin = egui::pos2(frame.left() + 8.0, web.center().y); + h.hover_at(margin); + h.run_steps(1); + assert!(free_pointer_over(&h.ctx, egui::Rect::from_min_size(egui::Pos2::ZERO, size)).is_none()); + } +} + +#[test] +fn layer_style_title_gutters_can_start_drags() { + use egui_kittest::{Harness, kittest::Queryable}; + + for point in 0..5 { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.state_mut().ui.open_dialog(DialogKind::LayerStyle, serde_json::Map::new()); + h.run_steps(3); + let before = h.get_by_label("Layer Style").rect(); + let from = match point { + 0 => egui::pos2(before.left() - 5.0, before.bottom() - 4.0), + 1 => egui::pos2(before.right() + 5.0, before.bottom() - 4.0), + 2 => egui::pos2(before.center().x, before.bottom() + 3.0), + 3 => egui::pos2(before.center().x, before.top() - 5.0), + _ => egui::pos2(before.center().x, before.bottom() - 3.0), + }; + h.hover_at(from); + h.drag_at(from); + h.run_steps(2); + for i in 1..=8 { + h.hover_at(from + egui::vec2(64.0, -32.0) * (i as f32 / 8.0)); + h.run_steps(1); + } + h.drop_at(from + egui::vec2(64.0, -32.0)); + h.run_steps(3); + let delta = h.get_by_label("Layer Style").rect().min - before.min; + assert!((delta - egui::vec2(64.0, -32.0)).length() < 2.0, "point {point}: moved {delta:?}"); + assert_eq!(h.state().ui.dialogs.len(), 1); + } +} + +#[test] +fn dragging_the_title_bar_moves_the_dialog() { + use egui_kittest::{Harness, kittest::Queryable}; + + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut harness = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + harness.state_mut().ui.open_dialog(DialogKind::LayerStyle, serde_json::Map::new()); + harness.run_steps(3); + let before = harness.get_by_label("Layer Style").rect(); + + // Grab the title text itself: it must move the dialog, not select the text. + let from = before.center(); + harness.hover_at(from); + harness.drag_at(from); + harness.run_steps(2); + for i in 1..=10 { + harness.hover_at(from + egui::vec2(-12.0, 8.0) * i as f32); + harness.run_steps(1); + } + harness.drop_at(from + egui::vec2(-120.0, 80.0)); + harness.run_steps(3); + + let moved = harness.get_by_label("Layer Style").rect().min - before.min; + assert!((moved - egui::vec2(-120.0, 80.0)).length() < 1.0, "dialog moved by {moved:?}"); + assert_eq!(harness.state().ui.dialogs.len(), 1, "dragging must not close the dialog"); +} + +/// #4872: an alert (Error, About) closes with ↩ as with OK, but not on the ↩ that raised it. +#[test] +fn enter_closes_an_alert_but_not_the_enter_that_opened_it() { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 600.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(2); + let alert = |h: &mut egui_kittest::Harness<'static, PhotocraftApp>| { + h.state_mut().ui.open_dialog(DialogKind::Error, json!({"message": crate::move_lock::MESSAGE}).as_object().cloned().unwrap_or_default()) + }; + // Raised in the frame its own ↩ arrives: that ↩ leaves it open. + alert(&mut h); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(h.state().ui.dialogs.len(), 1, "the ↩ that raised the alert doesn't close it"); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(h.state().ui.dialogs.is_empty(), "↩ is OK"); + // A new alert starts over, and Esc still closes it. + alert(&mut h); + h.run_steps(2); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.dialogs.is_empty(), "Esc too"); +} + +fn dialog_harness(size: egui::Vec2, command: &str) -> egui_kittest::Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(size).build_ui_state(|ui, app| show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + crate::filter_dialog::open(h.state_mut(), command).unwrap(); + h.run_steps(4); + h +} + +/// #3152: Motion Blur's angle is a dial, as in Photoshop. Clicking or dragging it points the +/// blur; the field still takes the whole -360..360 range. +#[test] +fn motion_blur_angle_dial_sets_the_angle_by_click_and_drag() { + use egui_kittest::kittest::Queryable; + let mut h = dialog_harness(egui::vec2(1280.0, 800.0), "filter.blur.motionBlur"); + let angle = |h: &egui_kittest::Harness<'static, PhotocraftApp>| h.state().ui.dialogs.last().and_then(|d| d.fields["angle"].as_f64()); + let centre = |h: &egui_kittest::Harness<'static, PhotocraftApp>| h.get_by_role_and_label(egui::accesskit::Role::Slider, "Angle").rect().center(); + let press = |h: &mut egui_kittest::Harness<'static, PhotocraftApp>, pos: egui::Pos2, pressed: bool| { + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + }; + assert_eq!(angle(&h), Some(0.0)); + // The dial's field is the dialog's first number, so it opens focused (#1757). + let first = h.get_all_by_role(egui::accesskit::Role::SpinButton).next().unwrap(); + let distance = h.query_all_by_label("Distance").next().expect("the Distance field").rect(); + assert!(first.is_focused() && first.rect().center().y < distance.center().y, "the Angle field has focus"); + // Click above the centre: straight up is 90°. + let up = centre(&h) + egui::vec2(0.0, -15.0); + h.event(egui::Event::PointerMoved(up)); + press(&mut h, up, true); + h.step(); + press(&mut h, up, false); + h.run_steps(3); + assert_eq!(angle(&h), Some(90.0)); + // Drag from the right (0°) round to the lower left (-135°). + let c = centre(&h); + let from = c + egui::vec2(15.0, 0.0); + h.event(egui::Event::PointerMoved(from)); + press(&mut h, from, true); + h.step(); + for (k, to) in [egui::vec2(12.0, 12.0), egui::vec2(0.0, 15.0), egui::vec2(-12.0, 12.0)].into_iter().enumerate() { + h.event(egui::Event::PointerMoved(c + to)); + h.step(); + assert_eq!(angle(&h), Some([-45.0, -90.0, -135.0][k]), "dragged to {to:?}"); + } + press(&mut h, c + egui::vec2(-12.0, 12.0), false); + h.run_steps(3); + assert_eq!(angle(&h), Some(-135.0)); + // A remembered or typed angle past half a turn is kept, not clamped to the dial's ±180°. + if let Some(d) = h.state_mut().ui.dialogs.last_mut() { + d.fields.insert("angle".into(), json!(270.0)); + } + h.run_steps(3); + assert_eq!(angle(&h), Some(270.0)); +} + +#[test] +fn a_tall_filter_dialog_keeps_its_title_and_buttons_in_a_small_window() { + // Filter › Render › Flame was taller than a 1000×560 window: OK and Cancel were cut off. + use egui_kittest::kittest::Queryable; + let size = egui::vec2(1000.0, 560.0); + let h = dialog_harness(size, "filter.render.flame"); + for label in ["Flame", "OK", "Cancel"] { + let r = h.get_by_label(label).rect(); + assert!(r.top() >= 0.0 && r.bottom() <= size.y, "{label} at {r:?} is outside the {size:?} window"); + } +} + +#[test] +fn a_moved_dialog_reopens_where_it_was_left() { + use egui_kittest::kittest::Queryable; + let size = egui::vec2(1280.0, 800.0); + let mut h = dialog_harness(size, "filter.blur.gaussianBlur"); + let centred = h.get_by_label("Gaussian Blur").rect(); + // Drag the title bar up and to the left. + let (from, by) = (centred.center(), egui::vec2(-240.0, -150.0)); + h.event(egui::Event::PointerMoved(from)); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + for k in 1..=6 { + h.event(egui::Event::PointerMoved(from + by * (k as f32 / 6.0))); + h.step(); + } + h.event(egui::Event::PointerButton { pos: from + by, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); + let moved = h.get_by_label("Gaussian Blur").rect(); + assert!((moved.min - (centred.min + by)).length() < 2.0, "dragged: {centred:?} → {moved:?}"); + h.get_by_label("Cancel").click(); + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty()); + // Reopened: where it was left. + crate::filter_dialog::open(h.state_mut(), "filter.blur.gaussianBlur").unwrap(); + h.run_steps(4); + let reopened = h.get_by_label("Gaussian Blur").rect(); + assert!((reopened.min - moved.min).length() < 2.0, "reopened at {reopened:?}, left at {moved:?}"); + h.get_by_label("Cancel").click(); + h.run_steps(3); + // Another dialog keeps its own place: never moved, it opens centred. + crate::filter_dialog::open(h.state_mut(), "filter.blur.motionBlur").unwrap(); + h.run_steps(4); + let other = h.get_by_label("Motion Blur").rect(); + assert!(other.min.x > moved.min.x + 100.0, "Motion Blur opened centred: {other:?}"); +} + +/// #1757: like Photoshop, a value dialog opens on its first number with the text selected, so +/// typing replaces it and Enter applies it; it reopens with the value applied last time, and a +/// cancelled edit is not remembered. +#[test] +fn a_value_dialog_opens_on_its_first_number_selected_and_remembers_it() { + use egui_kittest::kittest::Queryable; + const BLUR: &str = "filter.blur.gaussianBlur"; + let mut h = dialog_harness(egui::vec2(1280.0, 800.0), BLUR); + let radius = |h: &egui_kittest::Harness<'static, PhotocraftApp>| h.state().ui.dialogs.last().and_then(|d| d.fields["radius"].as_f64()); + assert_eq!(radius(&h), Some(1.0), "the default the first time"); + assert!(h.get_by_role(egui::accesskit::Role::SpinButton).is_focused(), "the Radius field has focus"); + h.event(egui::Event::Text("5".into())); + h.run_steps(1); + assert_eq!(radius(&h), Some(5.0), "typing replaced the selected 1"); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty(), "Enter is OK"); + assert_eq!(h.state().session.journal.last(), Some(&(BLUR.to_string(), json!({"radius": 5.0})))); + + crate::filter_dialog::open(h.state_mut(), BLUR).unwrap(); + h.run_steps(4); + assert_eq!(radius(&h), Some(5.0), "reopens with the last value"); + assert!(h.get_by_role(egui::accesskit::Role::SpinButton).is_focused(), "focused again"); + h.event(egui::Event::Text("9".into())); + h.run_steps(1); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty(), "Esc is Cancel"); + crate::filter_dialog::open(h.state_mut(), BLUR).unwrap(); + h.run_steps(2); + assert_eq!(radius(&h), Some(5.0), "a cancelled 9 is not remembered"); +} + +/// #4673: File › Automate › Fit Image holds two numbers and a check box, so its window is as +/// wide as that content and its buttons, not the 380-point floor of the larger dialogs. +#[test] +fn fit_image_is_as_narrow_as_its_content() { + 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(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let ctx = h.ctx.clone(); + let d = crate::menus::invoke(h.state_mut(), &ctx, "file.automate.fitImage", json!({})).unwrap()["dialog"].as_u64().unwrap(); + h.run_steps(4); + let window = h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", d)))).expect("the Fit Image window"); + assert!(window.width() < 300.0, "Fit Image is {} points wide", window.width()); + for label in ["Fit Image", "Width", "Height", "OK", "Cancel"] { + // A caption and the field it names share the label; either sits inside the window. + let node = h.query_all_by_label(label).next().unwrap_or_else(|| panic!("{label} in the dialog")); + assert!(window.contains_rect(node.rect()), "{label} inside the window"); + } +} From 7d61b23dda4f74c7c76f6f70ad6a74fdc73f0f2f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:44 +0000 Subject: [PATCH 063/259] refactor(ui-egui): move canvas.rs tests to canvas/tests.rs --- crates/ui-egui/src/canvas.rs | 2913 +--------------------------- crates/ui-egui/src/canvas/tests.rs | 2910 +++++++++++++++++++++++++++ 2 files changed, 2911 insertions(+), 2912 deletions(-) create mode 100644 crates/ui-egui/src/canvas/tests.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f00f2c7ce8..7454639278 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -7090,2918 +7090,7 @@ mod tap_pressure_tests { mod tabs_tests; #[cfg(test)] -mod tests { - /// #5472: a ⇧ square pressed between pixels snapped to 101 × 102; the short side grows to - /// match, on the side the drag points to. - #[test] - fn square_px_equalises_the_sides_away_from_the_press_point() { - use super::{marquee_px, square_px}; - // Down-right drag: the continuous square (50.3, 50.7)..(150.8, 151.2) snaps unevenly. - let r = marquee_px([50.3, 50.7], [150.8, 151.2]); - assert_eq!(r, [50.0, 50.0, 151.0, 152.0], "uneven before the fix"); - assert_eq!(square_px(r, [50.3, 50.7], [150.8, 90.0]), [50.0, 50.0, 152.0, 152.0]); - // Up-left drag: the short side grows towards lower coordinates. - let r = marquee_px([150.8, 151.2], [50.3, 50.7]); - assert_eq!(square_px(r, [150.8, 151.2], [60.0, 50.7]), [49.0, 50.0, 151.0, 152.0]); - // Already square: unchanged. - assert_eq!(square_px([10.0, 20.0, 30.0, 40.0], [10.0, 20.0], [30.0, 40.0]), [10.0, 20.0, 30.0, 40.0]); - } - - /// #6015: a Fixed Size marquee pressed between pixels selected one pixel more on each side. - #[test] - fn fixed_size_px_is_exactly_the_size() { - use super::fixed_size_px; - // Down-right from (10.4, 20.6): 10 × 10 from the closest pixel edges. - assert_eq!(fixed_size_px([10.4, 20.6], [20.4, 30.6], 10.0, 10.0), [10.0, 21.0, 20.0, 31.0]); - // Up-left: the far corner is the low one; still exactly the size. - assert_eq!(fixed_size_px([10.4, 20.6], [-53.6, -11.4], 64.0, 32.0), [-54.0, -11.0, 10.0, 21.0]); - // 1 × 1 is one pixel, and a fractional size rounds to whole pixels. - assert_eq!(fixed_size_px([3.5, 3.5], [4.5, 4.5], 1.0, 1.0), [4.0, 4.0, 5.0, 5.0]); - assert_eq!(fixed_size_px([0.0, 0.0], [2.6, 2.4], 2.6, 2.4), [0.0, 0.0, 3.0, 2.0]); - } - - #[test] - fn display_image_matches_egui_unmultiplied_conversion() { - // Several parallel pieces and a ragged one; translucent, out-of-range and NaN values. - let n: usize = 3 * 16 * 1024 + 77; - let px: Vec<[f32; 4]> = (0..n) - .map(|i| { - let v = match i % 9 { - 0 => f32::NAN, - 1 => -0.5, - 2 => 3.25, - _ => (i % 1001) as f32 / 1000.0, - }; - [v, (i % 257) as f32 / 256.0, 1.0 - (i % 113) as f32 / 112.0, (i % 6) as f32 / 5.0] - }) - .collect(); - let buf = photocraft_compose::Buffer { rect: photocraft_geom::Rect::new(0, 0, n as i32, 1), px }; - let reference = |img: photocraft_raster::Rgba8Image| egui::ColorImage::from_rgba_unmultiplied([img.width as usize, img.height as usize], &img.pixels); - assert_eq!(super::display_image(None, &buf).pixels, reference(buf.to_rgba8()).pixels); - let mut doc = photocraft_doc::Document::new("t", photocraft_geom::Size::new(1, 1), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); - doc.icc_profile = Some(photocraft_cms::Builtin::AdobeRgbCompat.profile().to_bytes()); - let mut color = photocraft_engine::color_cmds::ColorState::default(); - color.settings.monitor_profile = "srgb".into(); - let d = color.canvas_display(&doc).unwrap(); - assert!(!d.is_identity()); - assert_eq!(super::display_image(Some(&d), &buf).pixels, reference(d.to_rgba8(&buf)).pixels); - } - - /// #7490: the inline (web) preview path composites and uploads each changed preview once, as - /// the background worker does. It used to flatten and upload it twice and record it twice, - /// so the frame's refresh time counted the preview twice. - /// The CPU canvas (no usable GPU; a flipped or pixel-aspect-corrected view, or a GPU fallback, - /// on a GPU machine) shows a filter dialog's live preview. It showed the document unfiltered. - #[test] - fn the_cpu_canvas_shows_a_filter_dialogs_preview() { - let pixels = |ctx: &egui::Context, id: egui::TextureId| { - let mut delta = ctx.tex_manager().write().take_delta(); - let egui::ImageData::Color(image) = &delta.set.get(&id).and_then(|d| d.last()).expect("the canvas texture was written").image; - let (size, px) = (image.size, image.pixels.clone()); - delta.clear(); - (size, px) - }; - for (size, zoom) in [([64u32, 48u32], 1.0f32), ([2400, 2200], 0.25)] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.background_jobs = false; - app.run("file.new", json!({"width": size[0], "height": size[1], "background": "white"})).unwrap(); - app.run("edit.fill", json!({"color": "#3399cc"})).unwrap(); - app.ui.views.get_mut(0).expect("the view").zoom = zoom; - let ctx = egui::Context::default(); - let (tex, _) = ensure_texture(&mut app, &ctx, 0, None).unwrap(); - let (_, plain) = pixels(&ctx, tex); - crate::filter_dialog::open(&mut app, "filter.stylize.solarize").unwrap(); - let (tex, _) = ensure_texture(&mut app, &ctx, 0, None).unwrap(); - let (tex_size, shown) = pixels(&ctx, tex); - let preview = app.filter_preview.as_ref().and_then(|p| p.result.clone()).expect("the dialog's preview"); - let (display, _) = canvas_display(&app, &preview, None); - let expected = display_image(display.as_deref(), &photocraft_compose::flatten(&preview)); - assert_eq!(tex_size, expected.size, "{size:?}: the preview's own size (a proxy when zoomed out)"); - assert_eq!(shown, expected.pixels, "{size:?}: the canvas shows the preview"); - assert_ne!(shown.first(), plain.first(), "{size:?}: not the unfiltered document"); - } - // A preview that changes the canvas's dimensions covers its own area, centred on the - // document's (as the GPU canvas centres it), rather than being stretched over it. - let size = |w, h| photocraft_geom::Size::new(w, h); - assert_eq!(preview_bounds(size(64, 32), size(64, 32), 1), DRect::new(0, 0, 64, 32)); - assert_eq!(preview_bounds(size(2401, 2200), size(1201, 1100), 2), DRect::new(0, 0, 2401, 2200), "a proxy"); - assert_eq!(preview_bounds(size(64, 32), size(32, 64), 1), DRect::new(16, -16, 48, 48), "rotated"); - assert_eq!(preview_bounds(size(64, 32), size(80, 40), 1), DRect::new(-8, -4, 72, 36), "canvas grown"); - assert_eq!(preview_bounds(size(4000, 2000), size(1000, 2000), 2), DRect::new(1000, -1000, 3000, 3000), "a rotated proxy"); - - // Image › Image Rotation › Arbitrary 90° on a 64×32 document: its 32×64 preview is drawn over - // the centred 32×64 area. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.background_jobs = false; - app.run("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap(); - let id = crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap(); - let d = app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap(); - d.fields.insert("angle".into(), json!(90.0)); - d.fields.insert("__preview".into(), json!(true)); - let ctx = egui::Context::default(); - let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap(); - let (size, _) = pixels(&ctx, t.texture); - assert_eq!(size, [32, 64], "the rotated preview's texture"); - assert_eq!(t.bounds, DRect::new(16, -16, 48, 48), "centred on the document"); - let centre = |r: DRect| (r.x0 + r.x1, r.y0 + r.y1); - assert_eq!(centre(t.bounds), centre(app.session.active().unwrap().doc.bounds()), "the same centre, so the view's pan holds"); - // Preview off, then Cancel: the document again, unchanged. - let revision = app.session.active().unwrap().revision; - app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap().fields.insert("__preview".into(), json!(false)); - let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap(); - assert_eq!(t.bounds, DRect::new(0, 0, 64, 32), "Preview off"); - crate::dialogs::cancel(&mut app, id).unwrap(); - let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap(); - assert_eq!(t.bounds, DRect::new(0, 0, 64, 32), "after Cancel"); - assert_eq!(app.session.active().unwrap().revision, revision, "the document untouched"); - assert_eq!(app.session.active().unwrap().doc.size, photocraft_geom::Size::new(64, 32)); - } - - /// A channel overlay drawn from a size-changing preview covers the preview's own area, as the - /// image does, not the document's: a 90° rotation of a 64×32 document shows a 32×64 overlay. - #[test] - fn a_channel_overlay_follows_a_size_changing_preview() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.background_jobs = false; - app.run("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap(); - app.run("channel.new", json!({"name": "Alpha", "fill": "black"})).unwrap(); - let id = crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap(); - let d = app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap(); - d.fields.insert("angle".into(), json!(90.0)); - d.fields.insert("__preview".into(), json!(true)); - let ctx = egui::Context::default(); - for rotation in [0.0f32, 30.0] { - let view = View { zoom: 4.0, center: [32.0, 16.0], rotation, ..app.ui.views[0].clone() }; - let mut output = ctx.run_ui(Default::default(), |ui| { - canvas_view(&mut app, ui, 0, Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), view.clone(), true); - }); - output.textures_delta.clear(); - let overlay = crate::channel_view::ensure(&mut app, &ctx, 0).expect("the channel overlay"); - let mesh = output - .shapes - .iter() - .find_map(|s| match &s.shape { - egui::Shape::Mesh(m) if m.texture_id == overlay => Some(m.clone()), - _ => None, - }) - .expect("the overlay is painted"); - // The quad's sides, in screen points: the two shortest distances from a corner (the - // third is the diagonal; a rotated view turns the quad, not its side lengths). - let v: Vec = mesh.vertices.iter().map(|v| v.pos).collect(); - let mut d: Vec = v[1..4].iter().map(|p| v[0].distance(*p)).collect(); - d.sort_by(f32::total_cmp); - let (short, long) = (d[0], d[1]); - // Which side is the width: the one along the view's x axis turned by the rotation. - let along = |p: Pos2| { - let r = rotation.to_radians(); - ((p - v[0]).x * r.cos() + (p - v[0]).y * r.sin()).abs() - }; - let width = v[1..4].iter().map(|p| along(*p)).fold(0.0f32, f32::max); - assert!((long / short - 2.0).abs() < 0.01, "rotation {rotation}: sides {short}×{long}, the preview's 1:2"); - assert!((width - short).abs() < 0.5, "rotation {rotation}: the short side ({short}) runs across the view (width {width})"); - } - } - - #[test] - fn inline_filter_preview_is_composited_and_recorded_once() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.background_jobs = false; - app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); - crate::filter_dialog::open(&mut app, "filter.stylize.solarize").unwrap(); - app.perf.frame_refresh_ms = 0.0; - let (_, _, size) = ensure_filter_preview(&mut app, 0, &egui::Context::default()).expect("a preview"); - assert_eq!(size, [320, 240]); - assert_eq!(app.perf.last_refresh, "filter-preview"); - assert_eq!(app.perf.last_refresh_px, 320 * 240); - assert_eq!(app.perf.frame_refresh_ms, app.perf.composite_ms + app.perf.upload_ms, "one record per preview"); - // Unchanged request: nothing is recomputed or recorded again. - ensure_filter_preview(&mut app, 0, &egui::Context::default()).expect("the same preview"); - assert_eq!(app.perf.frame_refresh_ms, app.perf.composite_ms + app.perf.upload_ms); - } - - /// #6326: a filter's live preview is never coarser than the screen. On a document big enough - /// for a reduced proxy, the view at 100 % previews at full resolution, and only a view zoomed - /// out far enough uses the proxy. Through `ensure_filter_preview`, so the factor the canvas - /// actually requests is the one under test. - #[test] - fn filter_preview_at_100_percent_is_full_resolution() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.background_jobs = false; - app.run("file.new", json!({"width": 2400, "height": 2200})).unwrap(); - assert_eq!(crate::proxy::preview_factor(&app.session.active().unwrap().doc, true), 2, "big enough for a proxy"); - crate::filter_dialog::open(&mut app, "filter.stylize.solarize").unwrap(); - let ctx = egui::Context::default(); - let preview_at = |app: &mut PhotocraftApp, zoom: f32| { - app.ui.views.get_mut(0).expect("the new document's view").zoom = zoom; - assert_eq!(app.current_zoom(), zoom); - let (k, _, size) = ensure_filter_preview(app, 0, &ctx).expect("a preview"); - (k, size) - }; - assert_eq!(preview_at(&mut app, 1.0), (1, [2400, 2200]), "100 %: every pixel"); - assert_eq!(preview_at(&mut app, 0.25), (2, [1200, 1100]), "zoomed out: the document's proxy"); - // Low Resolution Previews off: full resolution at any zoom, exactly as before #6326. - app.run("prefs.set", json!({"path": "performance.lowResolutionPreviews", "value": false})).unwrap(); - assert_eq!(preview_at(&mut app, 0.25), (1, [2400, 2200]), "the preference still decides"); - } - - /// The factor itself over the zoom range, and that Preferences › Performance › Low - /// Resolution Previews still decides whether there is a proxy at all (#6326). - #[test] - fn filter_preview_factor_caps_at_the_view_without_overriding_the_preference() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - // 9 MP: reduced previews halve it (empty tiles, so nothing is allocated). - app.run("file.new", json!({"width": 3000, "height": 3000, "background": "transparent"})).unwrap(); - let doc = app.session.active().unwrap().doc.clone(); - let params = json!({"amount": 100, "radius": 4.0, "threshold": 0}); - let k = |app: &mut PhotocraftApp, zoom: f32| { - app.ui.views.get_mut(0).expect("the new document's view").zoom = zoom; - super::filter_preview_factor(app, &doc, "filter.sharpen.unsharpMask", ¶ms) - }; - assert_eq!(k(&mut app, 0.25), 2, "zoomed out the preview stays reduced"); - assert_eq!(k(&mut app, 0.5), 2); - assert_eq!(k(&mut app, 0.75), 1, "past the proxy's resolution it shows every pixel"); - assert_eq!(k(&mut app, 1.0), 1); - assert_eq!(k(&mut app, 4.0), 1); - // A corrupt or unset zoom must not pick a coarser proxy than the document's own. - assert_eq!(k(&mut app, f32::NAN), 1); - assert_eq!(k(&mut app, 0.0), 1); - // Low Resolution Previews off: full resolution at any zoom, the cap a no-op. - app.run("prefs.set", json!({"path": "performance.lowResolutionPreviews", "value": false})).unwrap(); - for zoom in [0.1, 0.25, 1.0, 4.0] { - assert_eq!(k(&mut app, zoom), 1, "zoom {zoom}"); - } - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn every_filter_previews_off_the_ui_thread_and_a_newer_value_cancels_the_old() { - // Dragging Gaussian Blur's radius to 1000 px froze the window: the preview ran inline in - // the frame, and every slider step waited for the previous blur to finish. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - app.background_jobs = true; - crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); - let ctx = egui::Context::default(); - let wait_for = |app: &mut PhotocraftApp, radius: f64| { - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while app.filter_preview.as_ref().is_none_or(|p| p.key.params["radius"].as_f64() != Some(radius)) { - assert!(std::time::Instant::now() < deadline, "no preview for radius {radius}"); - ensure_filter_preview(app, 0, &ctx); - std::thread::sleep(std::time::Duration::from_millis(1)); - } - }; - // The first frame hands the blur to the worker and returns. - assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none()); - assert!(app.filter_preview_worker.busy(), "the preview computes on the worker"); - let first = app.ui.dialogs[0].fields["radius"].as_f64().unwrap(); - wait_for(&mut app, first); - assert!(app.filter_preview.as_ref().unwrap().result.is_some()); - - // A preview for old values occupies the worker until it is cancelled. - let st = app.session.active().unwrap(); - let d = &app.ui.dialogs[0]; - let stale = crate::filter_dialog::FilterPreviewKey { - doc: st.doc.id, - revision: st.revision, - dialog: d.id, - active: st.active_layer, - target: st.channel_view.target, - command: "filter.blur.gaussianBlur".into(), - params: json!({"radius": 999.0}), - k: 1, - }; - let (told, cancelled) = std::sync::mpsc::channel(); - app.filter_preview_worker - .start(stale, ctx.clone(), move |job| { - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - while !job.cancelled() && std::time::Instant::now() < deadline { - std::thread::sleep(std::time::Duration::from_millis(1)); - } - let _ = told.send(job.cancelled()); - crate::filter_preview_worker::Computed { result: None, ms: 0.0 } - }) - .unwrap(); - // The slider moves on and stops: once the value settles, the stale preview is cancelled - // instead of being waited out. - app.ui.dialogs[0].fields.insert("radius".into(), json!(12.0)); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - let was_cancelled = loop { - ensure_filter_preview(&mut app, 0, &ctx); - if let Ok(c) = cancelled.try_recv() { - break c; - } - assert!(std::time::Instant::now() < deadline, "the stale preview was never cancelled"); - std::thread::sleep(std::time::Duration::from_millis(5)); - }; - assert!(was_cancelled, "the stale preview stopped because it was cancelled, not by timing out"); - wait_for(&mut app, 12.0); - assert!(app.filter_preview.as_ref().unwrap().result.is_some()); - } - - // Starts a worker job that computes a real preview for the dialog as it stands, but only - // finishes when the returned sender is signalled. Gating it here keeps these tests off the - // clock: `supersede` cancels a running job once the values have been still for SETTLE_MS, so a - // test that relies on a real blur beating a 150 ms timer is a test that fails on a loaded box. - #[cfg(not(target_arch = "wasm32"))] - fn gated_blur_preview(app: &mut PhotocraftApp, ctx: &egui::Context) -> (std::sync::mpsc::Sender<()>, f64) { - let d = app.ui.dialogs.first().expect("a dialog is open"); - let st = app.session.active().expect("a document is active"); - let command = "filter.blur.gaussianBlur"; - let params = app.with_mask_target(command, crate::filter_dialog::params_of(&d.fields)); - assert_eq!( - crate::filter_dialog::preview_factor(command, ¶ms, 1), - 1, - "a 64x48 document previews at full resolution, and these tests rely on k staying 1" - ); - let key = crate::filter_dialog::FilterPreviewKey { - doc: st.doc.id, - revision: st.revision, - dialog: d.id, - active: st.active_layer, - target: st.channel_view.target, - command: command.into(), - params, - k: 1, - }; - let doc = app.session.documents()[0].doc.clone(); - let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); - let radius = key.params["radius"].as_f64().expect("the dialog seeds a radius"); - let (release, wait) = std::sync::mpsc::channel::<()>(); - app.filter_preview_worker - .start(key.clone(), ctx.clone(), move |_| { - wait.recv_timeout(std::time::Duration::from_secs(60)).expect("the test releases the job"); - let result = crate::filter_dialog::preview_document_for_target( - &doc, - key.active, - &key.command, - &key.params, - key.k, - None, - key.target, - &documents, - &Default::default(), - ) - .map(|d| { - let buffer = photocraft_compose::flatten(&d); - (std::sync::Arc::new(d), buffer) - }); - crate::filter_preview_worker::Computed { result, ms: 0.0 } - }) - .expect("the worker starts"); - (release, radius) - } - - // The worker hands its result to the channel only after `compute` returns, so a signal sent - // from inside `compute` would still race that send. These tests drive the canvas until the - // state they need appears instead of assuming a timing. - #[cfg(not(target_arch = "wasm32"))] - fn drive_until(app: &mut PhotocraftApp, ctx: &egui::Context, what: &str, done: impl Fn(&PhotocraftApp) -> bool) { - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); - while !done(app) { - assert!(std::time::Instant::now() < deadline, "timed out waiting for {what}"); - ensure_filter_preview(app, 0, ctx); - std::thread::sleep(std::time::Duration::from_millis(1)); - } - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn a_preview_computed_mid_drag_reaches_the_canvas_and_then_converges() { - // A drag used to paint nothing at all: every completion was dropped for carrying stale - // parameters, so the canvas only ever showed an effect once the pointer had come to rest. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - app.background_jobs = true; - crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); - let ctx = egui::Context::default(); - let (release, first) = gated_blur_preview(&mut app, &ctx); - - // The pointer moves on before the frame lands. - let moved = first + 4.0; - app.ui.dialogs[0].fields.insert("radius".into(), json!(moved)); - release.send(()).expect("released"); - drive_until(&mut app, &ctx, "the mid-drag frame", |a| a.filter_preview.is_some()); - - // The finished frame is painted even though the dialog has moved on. - let shown = app.filter_preview.as_ref().expect("the mid-drag frame was published"); - assert_eq!(shown.key.params["radius"].as_f64(), Some(first), "the frame is the one the worker finished"); - assert!(shown.result.is_some()); - assert_eq!(app.ui.dialogs[0].fields["radius"].as_f64(), Some(moved), "the slider kept moving"); - // The display gate lets it through, so the canvas has something to draw: this is what - // re-adding `params` to that gate would break. - assert!(ensure_filter_preview(&mut app, 0, &ctx).is_some(), "the canvas draws the mid-drag frame"); - - // And the preview still converges on the value the dialog holds. `fresh` has to stay an - // exact match for that: relaxed, the canvas would believe it already had the current - // request after the first frame of a drag and never compute again. - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while app.filter_preview.as_ref().is_none_or(|p| p.key.params["radius"].as_f64() != Some(moved)) { - assert!(std::time::Instant::now() < deadline, "the preview never converged on the current radius"); - ensure_filter_preview(&mut app, 0, &ctx); - std::thread::sleep(std::time::Duration::from_millis(1)); - } - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn a_mid_drag_frame_does_not_replace_a_frame_that_is_already_exact() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - app.background_jobs = true; - crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); - let ctx = egui::Context::default(); - - // A frame for the radius the dialog holds right now reaches the canvas. This also proves - // the hand-built key is the one the canvas builds: it can only be published by the exact - // arm, which requires `finished == request`. - let (release, first) = gated_blur_preview(&mut app, &ctx); - release.send(()).expect("released"); - drive_until(&mut app, &ctx, "the first frame", |a| a.filter_preview.is_some()); - assert_eq!(app.filter_preview.as_ref().expect("published").key.params["radius"].as_f64(), Some(first)); - - // The slider moves away and a frame for the new radius is computed... - let moved = first + 4.0; - app.ui.dialogs[0].fields.insert("radius".into(), json!(moved)); - let (release_moved, _) = gated_blur_preview(&mut app, &ctx); - // ...and back to `first` before that frame lands. - app.ui.dialogs[0].fields.insert("radius".into(), json!(first)); - release_moved.send(()).expect("released"); - - // The frame for `moved` arrives late. It belongs to this preview, but the frame on screen - // is already exact for the dialog, so it must never be shown in place of it. Checked on - // every pass: a wrong frame published and then overwritten before the loop ends would - // otherwise never be seen. - drive_until(&mut app, &ctx, "the late frame to arrive", |a| { - if let Some(shown) = &a.filter_preview { - assert_ne!(shown.key.params["radius"].as_f64(), Some(moved), "a late frame replaced an exact one"); - } - !a.filter_preview_worker.busy() - }); - let shown = app.filter_preview.as_ref().expect("a frame is on screen"); - assert_eq!(shown.key.params["radius"].as_f64(), Some(first), "a late frame replaced an exact one"); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn a_mid_drag_empty_result_leaves_the_preview_alone() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - app.background_jobs = true; - crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); - let ctx = egui::Context::default(); - - let (release, first) = gated_blur_preview(&mut app, &ctx); - release.send(()).expect("released"); - drive_until(&mut app, &ctx, "the first frame", |a| a.filter_preview.is_some()); - assert!(app.filter_preview.as_ref().expect("published").result.is_some()); - - // The slider moves and a job for the new radius is started, then the slider moves again - // before that job lands: its result is stale by the time it arrives. - let moved = first + 4.0; - app.ui.dialogs[0].fields.insert("radius".into(), json!(moved)); - let d = app.ui.dialogs.first().expect("a dialog is open"); - let st = app.session.active().expect("a document is active"); - let key = crate::filter_dialog::FilterPreviewKey { - doc: st.doc.id, - revision: st.revision, - dialog: d.id, - active: st.active_layer, - target: st.channel_view.target, - command: "filter.blur.gaussianBlur".into(), - params: json!({"radius": moved}), - k: 1, - }; - let (release_empty, wait) = std::sync::mpsc::channel::<()>(); - app.filter_preview_worker - .start(key, ctx.clone(), move |_| { - wait.recv_timeout(std::time::Duration::from_secs(60)).expect("released"); - crate::filter_preview_worker::Computed { result: None, ms: 0.0 } - }) - .expect("the worker starts"); - app.ui.dialogs[0].fields.insert("radius".into(), json!(moved + 4.0)); - release_empty.send(()).expect("released"); - - // Storing an empty result here would drop the canvas back to the unfiltered layer for a - // frame. The exact request may still store one; a stale one may not. Checked on every - // pass, because the reopened preview that follows would otherwise repair the symptom. - drive_until(&mut app, &ctx, "the empty frame to arrive", |a| { - if let Some(shown) = &a.filter_preview { - assert!(shown.result.is_some(), "an empty mid-drag result blanked the canvas"); - } - !a.filter_preview_worker.busy() - }); - assert!(app.filter_preview.as_ref().expect("a preview is still shown").result.is_some(), "an empty mid-drag result blanked the canvas"); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn a_reopened_dialog_never_paints_the_previous_dialogs_preview() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - app.background_jobs = true; - crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); - let ctx = egui::Context::default(); - let first_dialog = app.ui.dialogs.first().expect("a dialog is open").id; - let (release, _) = gated_blur_preview(&mut app, &ctx); - - // Close that dialog and open another one for the same layer and the same command. Only the - // dialog id differs, which is exactly what `same_target` has to notice. - app.ui.dialogs.clear(); - crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); - let second_dialog = app.ui.dialogs.first().expect("a dialog is open").id; - assert_ne!(second_dialog, first_dialog, "a reopened dialog gets a new id"); - release.send(()).expect("released"); - - // The first dialog's frame arrives late and must not be painted under the second one. - // `discard_closed` usually reclaims it a frame earlier, which is why this drives the gate - // directly: the id check is the part that has to hold when that cleanup misses. The - // invariant is checked on every pass, not only at the end, because a wrongly published - // frame can still be replaced by the reopened dialog's own preview before we stop. - drive_until(&mut app, &ctx, "the first dialog's frame to arrive", |a| { - if let Some(preview) = &a.filter_preview { - assert_ne!(preview.key.dialog, first_dialog, "a reopened dialog painted the previous dialog's preview"); - } - !a.filter_preview_worker.busy() - }); - } - - #[test] - fn windows_uses_a_visible_crosshair() { - // #737: Windows' inverting crosshair vanishes over mid-grey; use a black/white glyph. - let ctx = egui::Context::default(); - let painter = egui::Painter::new(ctx, egui::LayerId::background(), egui::Rect::EVERYTHING); - let p = egui::pos2(10.0, 10.0); - assert_eq!(super::visible_crosshair(egui::CursorIcon::Crosshair, &painter, p, true), egui::CursorIcon::None); - assert_eq!(super::visible_crosshair(egui::CursorIcon::Crosshair, &painter, p, false), egui::CursorIcon::Crosshair); - assert_eq!(super::visible_crosshair(egui::CursorIcon::Move, &painter, p, true), egui::CursorIcon::Move); - } - - use super::*; - - /// #569: displays 1 (sRGB) and 4 (Display P3) side by side, and a document filled with an - /// sRGB colour. - fn app_on_two_displays() -> PhotocraftApp { - use photocraft_engine::color_cmds::resolve_profile; - use photocraft_engine::display_color::Display; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.run("edit.fill", json!({"color": "#cc8040"})).unwrap(); - let icc = |id: &str| Some(resolve_profile(id, None, None).unwrap().to_bytes()); - app.session.color.set_displays(Ok(vec![ - Display { id: 1, name: "A".into(), frame: [0.0, 0.0, 100.0, 100.0], profile_name: None, icc: icc("srgb") }, - Display { id: 4, name: "B".into(), frame: [100.0, 0.0, 100.0, 100.0], profile_name: None, icc: icc("display-p3") }, - ])); - app - } - - #[test] - #[ignore = "manual texture-retention measurement on six 6 MP documents"] - fn closed_canvas_memory_measurement() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - ctx.input_mut(|i| i.max_texture_side = 8192); - for cycle in 1..=6 { - app.run("file.new", json!({"width":3000,"height":2000})).unwrap(); - ensure_texture(&mut app, &ctx, 0, None).unwrap(); - // Drain uploaded image deltas just as a renderer does; count live texture owners. - ctx.tex_manager().write().take_delta().clear(); - app.run("file.close", json!({})).unwrap(); - let bytes: usize = ctx.tex_manager().read().allocated().map(|(_, m)| m.bytes_used()).sum(); - println!("closed cycle={cycle} texture_bytes={bytes} rss={:?}", photocraft_testkit::perf::current_rss_bytes()); - } - } - - #[test] - fn closed_documents_release_navigator_but_keep_open_document_textures() { - let mut app = app_on_two_displays(); - let ctx = egui::Context::default(); - let first = app.session.active().unwrap().doc.clone(); - let a = ensure_texture(&mut app, &ctx, 0, Some(1)).unwrap().0; - // The same handle ownership as navigator_texture, without requiring a GPU adapter. - let tex = ctx.load_texture("navigator-test", egui::ColorImage::filled([64, 64], egui::Color32::WHITE), TextureOptions::LINEAR); - let nav = tex.id(); - app.navigator_textures.insert(first.id, (std::sync::Arc::downgrade(&first), 0, 0, tex)); - app.run("file.new", json!({"width":32,"height":32})).unwrap(); - let other = app.session.active().unwrap().doc.id; - let b = ensure_texture(&mut app, &ctx, 1, Some(1)).unwrap().0; - drop(app.session.close(0)); - app.sync_views(); - assert!(ctx.tex_manager().read().meta(a).is_none()); - assert!(ctx.tex_manager().read().meta(nav).is_none()); - assert!(ctx.tex_manager().read().meta(b).is_some()); - assert!(app.canvases.keys().all(|(id, _)| *id == other)); - assert!(app.navigator_textures.is_empty()); - app.session.add_document((*first).clone(), None); - app.sync_views(); - assert_ne!(ensure_texture(&mut app, &ctx, 1, Some(1)).unwrap().0, a, "reopening a preserved ID creates a fresh texture"); - } - - #[test] - fn only_themes_with_a_dot_pattern_tile_the_canvas_surround() { - // #4542: switching to Pro filled the empty workspace with red blocks on one GPU. Pro's - // dots are its canvas colour, so the tiled texture had nothing to show in the first place. - use crate::theme::ThemeKind; - let tiles = |ctx: &egui::Context, kind: ThemeKind| { - crate::theme::apply(ctx, kind); - let mut output = ctx.run_ui(Default::default(), |ui| paint_dots(ui, ui.max_rect(), true)); - output.textures_delta.clear(); - output.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Mesh(_))) - }; - let uploaded = |ctx: &egui::Context| ctx.tex_manager().read().allocated().filter(|(_, meta)| meta.name == "canvas-dots").count(); - for kind in ThemeKind::ALL { - let ctx = egui::Context::default(); - let dotted = matches!(kind, ThemeKind::Studio | ThemeKind::StudioLight | ThemeKind::SolarizedDark); - assert_eq!(tiles(&ctx, kind), dotted, "{kind:?}"); - assert_eq!(uploaded(&ctx), usize::from(dotted), "{kind:?}"); - } - // The reported switch: a dotted theme, then Pro. - let ctx = egui::Context::default(); - assert!(tiles(&ctx, ThemeKind::Studio)); - assert!(!tiles(&ctx, ThemeKind::Pro)); - assert!(!tiles(&ctx, ThemeKind::ProMedium)); - assert_eq!(uploaded(&ctx), 1, "only Studio's dots were uploaded"); - } - - #[test] - fn closed_documents_release_cpu_canvas_textures() { - let mut app = app_on_two_displays(); - let ctx = egui::Context::default(); - let original = app.session.active().unwrap().doc.clone(); - for cycle in 0..12 { - if cycle > 0 { - app.session.add_document((*original).clone(), None); - app.sync_views(); - } - let a = ensure_texture(&mut app, &ctx, 0, Some(1)).unwrap().0; - let b = ensure_texture(&mut app, &ctx, 0, Some(4)).unwrap().0; - assert_ne!(a, b); - app.run("file.close", json!({})).unwrap(); - assert!(app.canvases.is_empty(), "closed canvas metadata retained at cycle {cycle}"); - assert!(ctx.tex_manager().read().meta(a).is_none(), "first display texture retained"); - assert!(ctx.tex_manager().read().meta(b).is_none(), "second display texture retained"); - } - } - - #[test] - fn cpu_canvas_textures_are_per_display() { - // Two windows of one document on different displays: each has its own texture of - // monitor values, and drawing them in turn re-renders neither. - let mut app = app_on_two_displays(); - let ctx = egui::Context::default(); - let id = app.session.documents()[0].doc.id; - let a = ensure_texture(&mut app, &ctx, 0, Some(1)).unwrap().0; - let b = ensure_texture(&mut app, &ctx, 0, Some(4)).unwrap().0; - assert_ne!(a, b); - app.perf.last_refresh = ""; - for _ in 0..3 { - assert_eq!(ensure_texture(&mut app, &ctx, 0, Some(1)).unwrap().0, a); - assert_eq!(ensure_texture(&mut app, &ctx, 0, Some(4)).unwrap().0, b); - } - assert_eq!(app.perf.last_refresh, "", "no re-render"); - let doc = app.session.documents()[0].doc.clone(); - assert!(canvas_display(&app, &doc, Some(1)).0.unwrap().is_identity()); - assert!(!canvas_display(&app, &doc, Some(4)).0.unwrap().is_identity()); - assert_ne!(app.canvases[&(id, 1)].tex_preview_key, app.canvases[&(id, 4)].tex_preview_key); - // An edit updates both. - app.run("edit.fill", json!({"color": "#2060c0"})).unwrap(); - ensure_texture(&mut app, &ctx, 0, Some(1)); - ensure_texture(&mut app, &ctx, 0, Some(4)); - let rev = app.session.documents()[0].revision; - assert_eq!((app.canvases[&(id, 1)].tex_revision, app.canvases[&(id, 4)].tex_revision), (rev, rev)); - } - - #[test] - fn cpu_canvas_shows_crisp_pixels_when_zoomed_in() { - // #4810: above 100% the CPU canvas shows each pixel as a square, like the GPU canvas's - // sharp nearest filter; below 100% it still filters. Both the first upload and a - // damage-rect update carry the sampling, since the renderer takes it from each delta. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 2, "height": 2})).unwrap(); - let ctx = egui::Context::default(); - let tex = ensure_texture(&mut app, &ctx, 0, None).unwrap().0; - let uploads = |ctx: &egui::Context| { - let mut delta = ctx.tex_manager().write().take_delta(); - let seen = delta.set.get(&tex).into_iter().flatten().map(|d| (d.pos.is_some(), d.options)).collect::>(); - delta.clear(); - seen - }; - let crisp = TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR }; - assert_eq!(uploads(&ctx), vec![(false, crisp)]); - app.run("select.rect", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap(); - ensure_texture(&mut app, &ctx, 0, None).unwrap(); - uploads(&ctx); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - assert_eq!(ensure_texture(&mut app, &ctx, 0, None).unwrap().0, tex); - assert_eq!(uploads(&ctx), vec![(true, crisp)], "a partial update keeps the crisp sampling"); - } - - /// A device that allows smaller textures than MAX_TEXTURE (2048 on some older GPUs and WebGL - /// contexts, and on the fallback adapter the GPU tests sometimes get under load): the canvas - /// texture is reduced to fit it. A 2600 px document was uploaded at full size, which egui - /// asserts on and the backend can't create. - #[test] - fn cpu_canvas_texture_fits_the_device_limit() { - for (side, (w, h), want) in [(2048, (2600, 1700), [1300, 850]), (2048, (5000, 2000), [1666, 666]), (8192, (5000, 2000), [2500, 1000])] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": w, "height": h})).unwrap(); - let ctx = egui::Context::default(); - ctx.input_mut(|i| i.max_texture_side = side); - let (tex, _) = ensure_texture(&mut app, &ctx, 0, None).unwrap(); - let mut delta = ctx.tex_manager().write().take_delta(); - let sizes: Vec<_> = delta.set.get(&tex).into_iter().flatten().map(|d| d.image.size()).collect(); - delta.clear(); - assert_eq!(sizes, vec![want], "{w}x{h} on a {side} px device"); - } - } - - #[test] - fn cpu_canvas_of_a_reduced_document_stays_bilinear() { - // Over MAX_TEXTURE the texture holds one texel per `factor` pixels: a texel is not a - // document pixel, so showing it as a square would draw blocks that aren't in the image. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": MAX_TEXTURE + 1, "height": 2})).unwrap(); - let ctx = egui::Context::default(); - let (tex, scale) = ensure_texture(&mut app, &ctx, 0, None).unwrap(); - assert!(scale < 1.0); - let mut delta = ctx.tex_manager().write().take_delta(); - let uploads: Vec<_> = delta.set.get(&tex).into_iter().flatten().map(|d| d.options).collect(); - delta.clear(); - assert_eq!(uploads, vec![TextureOptions::LINEAR]); - } - - /// #7568: a document over the texture limit was drawn from one reduced texture, so at 100 % - /// it was magnified and blurred. The view now gets the part in sight at one texel per - /// document pixel, about the window's size, whatever the device's limit. - #[test] - fn cpu_canvas_detail_plan_shows_large_documents_at_full_resolution() { - let size = [12000, 8000]; - // A 1920×1080 view in the middle (`visible_doc_rect` adds 2 px around it). - let screen = DRect::new(4998, 2998, 6922, 4082); - for limit in [16384, 8192, 4096, 2048] { - let side = clamp_texture_side(limit); - assert!(texture_factor(size, side) > 1, "the whole document is reduced on a {limit} px device"); - for zoom in [1.0, 2.0, 8.0] { - let plan = detail_plan(size, side, zoom, screen).unwrap_or_else(|| panic!("{limit} px device at {zoom}")); - assert_eq!(plan.factor, 1, "one texel per document pixel at {zoom} on a {limit} px device"); - assert!(plan.region.contains_rect(&screen), "{plan:?}"); - assert!(plan.region.width() <= 1924 + 2 * 256 && plan.region.height() <= 1084 + 2 * 256, "about the view's size: {plan:?}"); - assert!(plan.region.width() < side && plan.region.height() < side, "{plan:?}"); - } - } - // A small pan reuses the region (no new composite). - assert_eq!(detail_plan(size, 4096, 1.0, screen), detail_plan(size, 4096, 1.0, screen.translate(8, -8))); - // A window wider than a small device's limit coarsens rather than exceed it. - let wide = DRect::new(0, 0, 3000, 2000); - let plan = detail_plan(size, 2048, 1.0, wide).unwrap(); - assert_eq!(plan.factor, 2); - assert!(plan.region.width() / 2 < 2048 && plan.region.contains_rect(&wide), "{plan:?}"); - // Zoomed out a little: finer than the reduced whole, as fine as the screen. - let plan = detail_plan(size, 4096, 0.4, DRect::new(0, 0, 4800, 2700)).unwrap(); - assert_eq!(plan.factor, 2); - // Zoomed out far enough, the reduced whole is as fine as the screen: nothing to add. - let whole = DRect::new(0, 0, 12000, 8000); - assert_eq!(detail_plan(size, 4096, 0.25, whole), None); - assert_eq!(detail_plan(size, 4096, 1.0 / 3.0, whole), None, "a detail as large as the document would not fit"); - // A document that fits is uploaded whole at full resolution. - assert_eq!(detail_plan([4000, 3000], 4096, 1.0, screen), None); - // Nothing of the document in view, or a broken zoom. - assert_eq!(detail_plan(size, 4096, 1.0, DRect::new(-500, -500, -10, -10)), None); - for zoom in [0.0, -1.0, f32::NAN, f32::INFINITY] { - assert_eq!(detail_plan(size, 4096, zoom, screen), None, "{zoom}"); - } - assert_eq!(detail_plan([0, 0], 4096, 1.0, screen), None); - assert_eq!(detail_plan([u32::MAX, 8], 4096, 1.0, screen), None); - } - - #[test] - fn cpu_canvas_detail_shows_a_large_documents_own_pixels_at_100_percent() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 3 * MAX_TEXTURE, "height": 8})).unwrap(); - app.run("select.rect", json!({"x": 101, "y": 0, "width": 1, "height": 8})).unwrap(); - app.run("edit.fill", json!({"color": "#000000"})).unwrap(); - app.run("select.deselect", json!({})).unwrap(); - let ctx = egui::Context::default(); - ctx.input_mut(|i| i.max_texture_side = 16384); - let uploads = |ctx: &egui::Context, tex: egui::TextureId| { - let mut delta = ctx.tex_manager().write().take_delta(); - let seen: Vec<_> = delta.set.get(&tex).into_iter().flatten().map(|d| (d.pos, d.options, d.image.clone())).collect(); - delta.clear(); - seen - }; - let row = |image: &egui::ImageData| { - let egui::ImageData::Color(image) = image; - (image.size, image.pixels.clone()) - }; - let view = InView { visible: DRect::new(0, 0, 1000, 8), zoom: 1.0, key: 1 }; - let t = ensure_texture_in_view(&mut app, &ctx, 0, None, Some(view)).unwrap(); - assert!(t.scale < 1.0, "the whole document is reduced"); - let (detail, area) = t.detail.expect("a detail texture at 100 %"); - assert_eq!(area, [0.0, 0.0, 1024.0, 8.0]); - let crisp = TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR }; - let up = uploads(&ctx, detail); - assert_eq!(up.len(), 1); - let (pos, options, image) = &up[0]; - assert_eq!((*pos, *options), (None, crisp)); - let (size, px) = row(image); - assert_eq!(size, [1024, 8]); - assert_eq!((px[100], px[101], px[102]), (Color32::WHITE, Color32::BLACK, Color32::WHITE), "the 1 px line stays 1 px"); - // Unchanged: nothing is composited again, and a small pan keeps the region. - let panned = InView { visible: DRect::new(4, 0, 1004, 8), ..view }; - assert_eq!(ensure_texture_in_view(&mut app, &ctx, 0, None, Some(panned)).unwrap().detail, Some((detail, area))); - assert!(uploads(&ctx, detail).is_empty()); - // The Navigator's call (no view) leaves the view's detail alone. - ensure_texture(&mut app, &ctx, 0, None).unwrap(); - assert_eq!(app.canvases.values().map(|c| c.detail.len()).sum::(), 1); - // An edit in view updates just its texels. - app.run("select.rect", json!({"x": 300, "y": 0, "width": 1, "height": 8})).unwrap(); - ensure_texture_in_view(&mut app, &ctx, 0, None, Some(view)).unwrap(); - uploads(&ctx, detail); - app.run("edit.fill", json!({"color": "#000000"})).unwrap(); - assert_eq!(ensure_texture_in_view(&mut app, &ctx, 0, None, Some(view)).unwrap().detail.map(|d| d.0), Some(detail)); - let up = uploads(&ctx, detail); - assert_eq!(up.len(), 1); - let (pos, options, image) = &up[0]; - assert_eq!(*options, crisp); - let [x, y] = pos.expect("a partial update"); - let (size, px) = row(image); - assert!(y == 0 && x < 300 && x + size[0] > 300, "the edit's texels: {x} {size:?}"); - assert_eq!((px[299 - x], px[300 - x]), (Color32::WHITE, Color32::BLACK)); - // Zoomed out, the reduced texture is enough: the detail goes. - let far = InView { zoom: 0.25, ..view }; - assert!(ensure_texture_in_view(&mut app, &ctx, 0, None, Some(far)).unwrap().detail.is_none()); - assert!(app.canvases.values().all(|c| c.detail.is_empty())); - } - - #[test] - fn gpu_display_luts_are_per_display() { - let _gpu = photocraft_testkit::gpu_lock(); - let Ok(rs) = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) else { - eprintln!("skipping: no GPU adapter"); - return; - }; - let mut app = app_on_two_displays(); - app.set_wgpu(rs); - let doc = app.session.documents()[0].doc.clone(); - let key = doc.id.0; - // sRGB on the sRGB display needs no LUT; on the P3 display it does. - assert_eq!(sync_display_lut(&mut app, &doc, key, Some(1)), 0); - assert_eq!(sync_display_lut(&mut app, &doc, key, Some(4)), 3); - let gpu = app.gpu.clone().unwrap(); - let (s1, s4) = (gpu.display_lut_signature(key, 1).unwrap(), gpu.display_lut_signature(key, 4).unwrap()); - assert_ne!(s1.0, s4.0); - assert!(gpu.has_display_lut(key, 4) && !gpu.has_display_lut(key, 1)); - // Drawing one window leaves the other's LUT alone. - for _ in 0..3 { - assert_eq!(sync_display_lut(&mut app, &doc, key, Some(1)), 0); - assert_eq!(sync_display_lut(&mut app, &doc, key, Some(4)), 3); - } - assert_eq!((gpu.display_lut_signature(key, 1), gpu.display_lut_signature(key, 4)), (Some(s1), Some(s4))); - assert!(gpu.has_display_lut(key, 4)); - // The shared texture's key is the same for both displays. - assert_eq!(texture_key(canvas_display(&app, &doc, Some(1)).0.as_deref()), texture_key(canvas_display(&app, &doc, Some(4)).0.as_deref())); - } - - /// The navigator's update after an edit (its image with the edit's damage, grown by the - /// effect reach, rendered over it) equals a new thumbnail of the edited document. - #[test] - fn navigator_damage_updates_match_a_full_thumbnail() { - use photocraft_compose::{render_reduced_damage, thumbnail_buffer, thumbnail_size}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 1500, "height": 900, "background": "white"})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("select.rect", json!({"x": 200, "y": 150, "width": 300, "height": 200})).unwrap(); - app.run("edit.fill", json!({"color": "#3070a0"})).unwrap(); - app.run("select.deselect", json!({})).unwrap(); - app.run("layer.layerStyle.dropShadow", json!({"distance": 30, "size": 20})).unwrap(); - let steps = [ - ("layer.translate", json!({"dx": 37, "dy": -11})), - ("layer.setProps", json!({"opacity": 0.4})), - ("paint.stroke", json!({"points": [[700, 500], [900, 520]], "size": 25})), - ("layer.setProps", json!({"blend": "Multiply"})), - ("layer.new.layer", json!({})), - ]; - for (id, p) in steps { - let before = app.session.active().unwrap().doc.clone(); - app.run(id, p).unwrap(); - let st = app.session.active().unwrap(); - let d = st.last_damage.unwrap_or_else(|| panic!("{id}: a bounded damage")); - let (w, h) = thumbnail_size(&st.doc, NAVIGATOR_SIDE); - let mut shown = thumbnail_buffer(&before, NAVIGATOR_SIDE); - assert_eq!((shown.rect.width(), shown.rect.height()), (w, h)); - if !d.is_empty() { - let patch = render_reduced_damage(&st.doc, w, h, d.inflate(effect_reach(&st.doc.layers))); - let r = patch.rect; - for y in 0..r.height() as usize { - let at = (r.y0 as usize + y) * w as usize + r.x0 as usize; - shown.px[at..at + r.width() as usize].copy_from_slice(&patch.px[y * r.width() as usize..][..r.width() as usize]); - } - } - assert!(shown.px == thumbnail_buffer(&st.doc, NAVIGATOR_SIDE).px, "{id}: the updated navigator differs from a new thumbnail"); - } - } - - #[test] - fn tab_context_uses_clicked_document_and_existing_close_commands() { - let items = tab_context_items(2, 3, true); - assert_eq!(items.iter().map(|(_, id, _, _)| *id).collect::>(), ["file.close", "file.closeOthers", "file.closeAll", "file.revealInFinder"]); - assert_eq!(items[0].2, json!({"document": 2})); - assert_eq!(items[1].2, json!({"document": 2})); - assert_eq!(items[2].2, json!({})); - assert_eq!(items[3].2, json!({"document": 2})); - assert!(items[3].3, "a saved document can be revealed in the file manager"); - assert!(!tab_context_items(2, 3, false)[3].3, "an unsaved document cannot"); - assert!(!tab_context_items(0, 1, false)[1].3); - assert!(items.iter().all(|(_, id, _, _)| photocraft_engine::commands::find(id).is_some())); - } - - #[test] - fn tab_context_reveal_names_the_platform_file_manager() { - let (label, id, _, _) = &tab_context_items(0, 1, true)[3]; - assert_eq!((*label, *id), (crate::menus::reveal_label(), "file.revealInFinder")); - } - - /// Photoshop's document tab × is after the title on Windows and Linux, before it on macOS (#619). - #[test] - fn document_tab_close_button_sits_on_the_platform_side() { - use egui::os::OperatingSystem as Os; - use egui_kittest::kittest::Queryable; - for (os, after_title) in [(Os::Windows, true), (Os::Nix, true), (Os::Mac, false)] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - app.sync_views(); - // Drawn from the second frame, once the Pro theme is set. - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 40.0)).build_ui_state( - |ui, (app, ready): &mut (PhotocraftApp, bool)| { - if *ready { - tabs(app, ui); - } - }, - (app, false), - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); - h.ctx.set_os(os); - h.state_mut().1 = true; - h.run_steps(2); - let tab = h.get_by_label_contains("Untitled @").rect(); - let x = h.get_by_label("Close").rect(); - assert!(tab.contains_rect(x), "{os:?}: the × is inside its tab"); - assert_eq!(x.center().x > tab.center().x, after_title, "{os:?}: × at {x:?} in tab {tab:?}"); - h.get_by_label("Close").click(); - h.run_steps(2); - assert!(h.state().0.session.documents().is_empty(), "{os:?}: the × closes the document"); - } - } - - /// Middle-clicking a document tab closes it (#2570), in both tab strips, and the tab under the - /// pointer is the one that goes even when another document is active. - #[test] - fn middle_clicking_a_tab_closes_that_document() { - use egui_kittest::kittest::Queryable; - for kind in [crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::Pro] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - for name in ["keep", "doomed", "active"] { - app.run("file.new", json!({"width": 8, "height": 8, "name": name})).unwrap(); - } - app.sync_views(); - assert_eq!(app.session.active_index(), Some(2)); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 40.0)).build_ui_state( - |ui, (app, ready): &mut (PhotocraftApp, bool)| { - if *ready { - tabs(app, ui); - } - }, - (app, false), - ); - PhotocraftApp::setup_context(&h.ctx, kind); - h.state_mut().1 = true; - h.run_steps(2); - h.get_by_label_contains("doomed").click_button(egui::PointerButton::Middle); - h.run_steps(2); - let names: Vec = h.state().0.session.documents().iter().map(|d| d.doc.name.clone()).collect(); - assert_eq!(names, ["keep", "active"], "{kind:?}: the middle-clicked tab closed"); - // A clean document closes straight away; a dirty one would park in `discard`. - assert!(h.state().0.discard.is_none(), "{kind:?}: nothing to prompt about"); - } - } - - /// A middle click goes through the same guarded `file.close` as the ×, so unsaved changes - /// still get the Save / Don’t Save / Cancel prompt instead of being thrown away (#2570). - #[test] - fn middle_clicking_an_edited_tab_prompts_instead_of_discarding() { - use egui_kittest::kittest::Queryable; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 8, "name": "edited"})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.sync_views(); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 40.0)).build_ui_state( - |ui, (app, ready): &mut (PhotocraftApp, bool)| { - if *ready { - tabs(app, ui); - } - }, - (app, false), - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); - h.state_mut().1 = true; - h.run_steps(2); - h.get_by_label_contains("edited").click_button(egui::PointerButton::Middle); - h.run_steps(2); - assert!(h.state().0.discard.is_some(), "the unsaved-changes prompt must come up"); - assert_eq!(h.state().0.session.documents().len(), 1, "and the document is still open"); - } - - #[test] - fn spectrum_document_tabs_meet_canvas_without_a_gap() { - for kind in [crate::theme::ThemeKind::Pro, crate::theme::ThemeKind::ProMedium] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 80, "height": 60})).unwrap(); - app.sync_views(); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(680.0, 480.0)).build_ui_state( - |ui, (app, ready): &mut (PhotocraftApp, bool)| { - if *ready { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); - } - }, - (app, false), - ); - PhotocraftApp::setup_context(&h.ctx, kind); - h.state_mut().1 = true; - h.run_steps(3); - let app = &h.state().0; - let strip = app.tab_strip.as_ref().expect("a document opens with tabs").rect; - let gap = app.last_canvas_rect.top() - strip.bottom(); - assert!(gap.abs() < 0.1, "{kind:?}: document strip should touch canvas, got {gap} pt"); - } - } - - #[test] - fn large_tabs_preference_increases_tab_strip_height() { - use egui_kittest::kittest::Queryable; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - app.sync_views(); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 60.0)).build_ui_state( - |ui, (app, ready): &mut (PhotocraftApp, bool)| { - if *ready { - tabs(app, ui); - } - }, - (app, false), - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); - h.state_mut().1 = true; - h.run_steps(2); - let normal_h = h.get_by_label_contains("Untitled @").rect().height(); - assert_eq!(normal_h, 26.0); - - h.state_mut().0.session.execute("prefs.set", json!({"values": {"workspace.largeTabs": true}})).unwrap(); - h.run_steps(2); - let large_h = h.get_by_label_contains("Untitled @").rect().height(); - assert_eq!(large_h, 34.0); - } - - #[test] - fn tab_close_others_prompts_for_unsaved_nonactive_document() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 8, "name": "Keep"})).unwrap(); - app.run("file.new", json!({"width": 8, "height": 8, "name": "Edited"})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - assert_eq!(app.session.active_index(), Some(1)); - let (_, id, params, _) = tab_context_items(0, 2, false)[1].clone(); - crate::menus::invoke(&mut app, &egui::Context::default(), id, params).unwrap(); - assert!(app.discard.is_some(), "close others must ask before discarding the edited tab"); - assert_eq!(app.session.documents().len(), 2); - } - - /// The pure half of tab drag-to-reorder (UI-217-6): where a drop lands and which - /// `document.move` target that is. - #[test] - fn tab_drop_index_and_move_target_cover_reorder_drops() { - let r = |x: f32| Rect::from_min_size(egui::pos2(x, 0.0), egui::vec2(100.0, 26.0)); - let placed = vec![(0, r(0.0)), (1, r(100.0)), (2, r(200.0))]; - assert_eq!(tab_drop_index(&placed, 10.0), 0); - assert_eq!(tab_drop_index(&placed, 160.0), 2); - assert_eq!(tab_drop_index(&placed, 350.0), 3, "past the end lands after the last shown tab"); - assert_eq!(tab_move_target(0, 3), 2); - assert_eq!(tab_move_target(2, 0), 0); - assert_eq!(tab_move_target(1, 1), 1, "before itself: no move"); - assert_eq!(tab_move_target(1, 2), 1, "just after itself: no move"); - assert_eq!(tab_move_target(0, 1), 0); - } - - /// Dragging a tab onto another's slot reorders the open documents (UI-217-6), in both the - /// studio and the Photoshop-style strips. - #[test] - fn dragging_a_tab_reorders_the_documents() { - use egui_kittest::kittest::Queryable; - for kind in [crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::Pro] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - for name in ["a", "b", "c"] { - app.run("file.new", json!({"width": 8, "height": 8, "name": name})).unwrap(); - } - app.sync_views(); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 40.0)).build_ui_state( - |ui, (app, ready): &mut (PhotocraftApp, bool)| { - if *ready { - tabs(app, ui); - } - }, - (app, false), - ); - PhotocraftApp::setup_context(&h.ctx, kind); - h.state_mut().1 = true; - h.run_steps(2); - let b = h.get_by_label_contains("b").rect(); - let a = h.get_by_label_contains("a").rect(); - let target = egui::pos2(a.left() + 2.0, a.center().y); - h.drag_at(b.center()); - h.run_steps(1); - h.hover_at(target); - h.run_steps(1); - h.drop_at(target); - h.run_steps(2); - let names: Vec = h.state().0.session.documents().iter().map(|d| d.doc.name.clone()).collect(); - assert_eq!(names, ["b", "a", "c"], "{kind:?}: the dragged tab took the dropped slot"); - } - } - - /// Dragging a tab off the strip floats its document in its own OS window instead of - /// reordering (#3733), in both strips; a short wobble below the strip still reorders. - #[test] - fn dragging_a_tab_off_the_strip_floats_it_in_a_window() { - use egui_kittest::kittest::Queryable; - let strip = Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(700.0, 26.0)); - assert!(!torn_off(strip, egui::pos2(50.0, 13.0))); - assert!(!torn_off(strip, egui::pos2(50.0, 26.0 + TEAR_OFF - 1.0)), "a wobble below the strip still reorders"); - assert!(torn_off(strip, egui::pos2(50.0, 26.0 + TEAR_OFF + 1.0))); - assert!(torn_off(strip, egui::pos2(50.0, -TEAR_OFF - 1.0)), "dragged up, off the window's top"); - for kind in [crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::Pro] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - for name in ["a", "b", "c"] { - app.run("file.new", json!({"width": 8, "height": 8, "name": name})).unwrap(); - } - app.sync_views(); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 300.0)).build_ui_state( - |ui, (app, ready): &mut (PhotocraftApp, bool)| { - if *ready { - tabs(app, ui); - } - }, - (app, false), - ); - PhotocraftApp::setup_context(&h.ctx, kind); - h.state_mut().1 = true; - h.run_steps(2); - let b = h.get_by_label_contains("b").rect(); - let target = egui::pos2(b.center().x, b.bottom() + 150.0); - h.drag_at(b.center()); - h.run_steps(1); - h.hover_at(target); - h.run_steps(1); - h.drop_at(target); - h.run_steps(2); - let app = &h.state().0; - let names: Vec<&str> = app.session.documents().iter().map(|d| d.doc.name.as_str()).collect(); - assert_eq!(names, ["a", "b", "c"], "{kind:?}: tearing off doesn't reorder"); - assert_eq!(app.ui.windows.iter().map(|w| w.document).collect::>(), [1], "{kind:?}: b floats in its own window"); - assert_eq!(app.session.active_index(), Some(1), "{kind:?}: the floated document is active"); - } - } - - #[test] - fn clone_overlay_is_circular_and_respects_visibility() { - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.run("cloneSource.set", json!({"source": [16,16]})).unwrap(); - app.ui.tool = Tool::CloneStamp; - app.session.tools.brush.size = 20.0; - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let revision = app.session.active().unwrap().revision; - let mut output = ctx.run_ui(Default::default(), |ui| { - let ctx = ui.ctx(); - let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); - draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); - }); - output.textures_delta.clear(); - let mesh = output - .shapes - .iter() - .find_map(|s| match &s.shape { - egui::Shape::Mesh(m) => Some(m), - _ => None, - }) - .unwrap(); - assert_eq!(mesh.indices.len(), 64 * 3); - let center = xf.to_screen(32.0, 32.0); - assert!(mesh.vertices.iter().all(|v| v.pos.distance(center) <= 10.01)); - assert_eq!(app.session.active().unwrap().revision, revision); - assert!(app.session.presets.clone.active().anchor.is_none()); - let ordinary_key = app.clone_preview.as_ref().unwrap().key.clone(); - app.ui.view.pattern_preview = true; - let mut periodic_output = ctx.run_ui(Default::default(), |ui| { - let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); - draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); - }); - assert_ne!(app.clone_preview.as_ref().unwrap().key, ordinary_key, "toggling Pattern Preview invalidates source pixels"); - assert!(!periodic_output.textures_delta.set.is_empty(), "the overlay texture is refreshed without a document edit"); - periodic_output.textures_delta.clear(); - assert_eq!(app.session.active().unwrap().revision, revision); - app.session.presets.clone.overlay.show = false; - let mut output = ctx.run_ui(Default::default(), |ui| { - let ctx = ui.ctx(); - let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); - draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); - }); - output.textures_delta.clear(); - assert!(output.shapes.iter().all(|s| !matches!(s.shape, egui::Shape::Mesh(_)))); - } - - #[test] - fn clone_overlay_keeps_magnified_pixels_crisp_on_upload_and_refresh() { - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.run("cloneSource.set", json!({"source": [16, 16]})).unwrap(); - app.ui.tool = Tool::CloneStamp; - app.session.tools.brush.size = 20.0; - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 4.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; - for invert in [false, true] { - app.session.presets.clone.overlay.invert = invert; - let mut output = ctx.run_ui(Default::default(), |ui| { - draw_clone_preview(&mut app, ui.painter(), &xf, [32.0, 32.0], None); - }); - let upload = output.textures_delta.set.values().flatten().find(|d| d.image.size() == [20, 20]).expect("clone overlay upload"); - let options = upload.options; - output.textures_delta.clear(); - assert_eq!(options.magnification, egui::TextureFilter::Nearest, "invert={invert}"); - assert_eq!(options.minification, egui::TextureFilter::Linear, "zoomed-out previews remain filtered"); - } - } - - #[test] - fn clone_overlay_blend_mode_mixes_with_the_image_under_the_brush() { - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.run("cloneSource.set", json!({"source": [16,16]})).unwrap(); - app.ui.tool = Tool::CloneStamp; - app.session.tools.brush.size = 20.0; - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; - // The centre texel of the overlay texture uploaded for `mode`. - let mut centre = |mode: &str| { - app.run("cloneSource.overlay", json!({"blend": mode})).unwrap(); - let mut output = ctx.run_ui(Default::default(), |ui| { - let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); - draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); - }); - // The brush's 20 × 20 px square (the font atlas may upload too). - let image = output.textures_delta.set.values().flatten().find_map(|d| match &d.image { - egui::ImageData::Color(c) if c.size == [20, 20] => Some(c.clone()), - _ => None, - }); - output.textures_delta.clear(); - let image = image.expect("the overlay uploads a texture"); - image.pixels[image.width() * (image.height() / 2) + image.width() / 2] - }; - // A white source over the white image: Normal shows white, Difference black. - assert_eq!(centre("normal"), Color32::WHITE); - assert_eq!(centre("difference"), Color32::BLACK, "Difference turns black where source and image match"); - assert_eq!(centre("lighten"), Color32::WHITE); - } - - /// A shaped tip clips the Clone Source overlay to its outline, not to the brush circle. - #[test] - fn clone_overlay_is_clipped_to_a_shaped_tip() { - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.run("cloneSource.set", json!({"source": [16,16]})).unwrap(); - app.ui.tool = Tool::CloneStamp; - app.session.tools.brush.size = 20.0; - app.session.tools.brush.roundness = 0.25; - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let mut output = ctx.run_ui(Default::default(), |ui| { - let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); - draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); - }); - let image = output - .textures_delta - .set - .values() - .flatten() - .find_map(|d| match &d.image { - egui::ImageData::Color(c) if c.size == [20, 20] => Some(c.clone()), - _ => None, - }) - .expect("the overlay uploads a texture"); - output.textures_delta.clear(); - let alpha = |x: usize, y: usize| image.pixels[y * image.width() + x].a(); - assert_eq!(alpha(10, 10), 255, "the tip's centre shows the source"); - assert_eq!(alpha(10, 2), 0, "inside the circle but outside the flat tip: clipped"); - assert_eq!(alpha(1, 10), 255, "the tip's long axis stays"); - } - - #[test] - fn wayland_start_screen_hint_does_not_claim_file_drop_works() { - let x11 = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let wayland = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { is_wayland: true, ..Default::default() }); - assert!(start_screen_drop_hint(&x11).starts_with("Drop")); - // Pasting a copied image file works on Wayland (#338): the hint says how. - let hint = start_screen_drop_hint(&wayland); - assert!(!hint.contains("Drop"), "{hint}"); - assert!(hint.ends_with(&format!("paste a copied image with {}.", crate::notices::paste_hint(&wayland))), "{hint}"); - } - - /// A tiling window manager can hand PhotoCraft a canvas narrower than the Home card (460 - /// points): the two buttons must stay inside the window instead of being clipped at its edges. - #[test] - fn start_screen_buttons_stay_inside_a_narrow_canvas() { - use egui_kittest::kittest::Queryable; - for width in [390.0, 420.0, 520.0] { - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(width, 760.0)).build_ui_state( - |ui, (app, ready): &mut (PhotocraftApp, bool)| { - if *ready { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); - } - }, - (app, false), - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); - h.state_mut().1 = true; - h.run_steps(3); - for label in ["New document", "Join us on Discord"] { - for node in h.query_all_by_label_contains(label) { - let r = node.rect(); - assert!(r.left() >= 0.0 && r.right() <= width, "`{label}` is clipped in a {width}-point-wide canvas: {r:?}"); - } - } - } - } - - /// #4382: Interface › Show home recent files off hides the Home screen's list, not the recents. - #[test] - fn home_recent_list_hides_when_the_preference_is_off() { - use egui_kittest::kittest::Queryable; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.push_recent("/tmp/photocraft-217/hidden.psd"); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 760.0)).build_ui_state( - |ui, (app, ready): &mut (PhotocraftApp, bool)| { - if *ready { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); - } - }, - (app, false), - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); - h.state_mut().1 = true; - h.run_steps(3); - assert!(h.query_by_label("hidden.psd").is_some(), "listed by default"); - h.state_mut().0.run("prefs.set", serde_json::json!({"values": {"interface.showHomeRecentFiles": false}})).unwrap(); - h.run_steps(3); - assert!(h.query_by_label("hidden.psd").is_none(), "hidden when off"); - assert_eq!(h.state().0.ui.recent_files.len(), 1, "the list itself is kept"); - } - - /// The Home screen's × takes a file off Recent without opening it, and its right-click menu - /// removes one entry or clears the list; the preferences keep the change (#2691). - #[test] - fn home_recent_entries_can_be_removed() { - use egui_kittest::kittest::Queryable; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - for name in ["c.tif", "b.psd", "a.png"] { - app.push_recent(&format!("/tmp/photocraft-2691/{name}")); - } - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 760.0)).build_ui_state( - |ui, (app, ready): &mut (PhotocraftApp, bool)| { - if *ready { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); - } - }, - (app, false), - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); - h.state_mut().1 = true; - h.run_steps(3); - let listed = |h: &egui_kittest::Harness<'_, (PhotocraftApp, bool)>| { - let app = &h.state().0; - assert_eq!(app.session.prefs().file_handling.recent_files, app.ui.recent_files, "stored in the preferences"); - app.ui.recent_files.iter().map(|p| crate::file_open::display_name(p)).collect::>() - }; - assert_eq!(listed(&h), ["a.png", "b.psd", "c.tif"]); - assert!(h.query_by_label("Remove b.psd from Recent").is_none(), "the × shows on the hovered row only"); - - h.get_by_label("b.psd").hover(); - h.run_steps(2); - h.get_by_label("Remove b.psd from Recent").click(); - h.run_steps(2); - assert_eq!(listed(&h), ["a.png", "c.tif"]); - assert!(h.state().0.session.documents().is_empty(), "the file was not opened"); - - h.get_by_label("c.tif").click_secondary(); - h.run_steps(2); - h.get_by_label("Remove from Recent").click(); - h.run_steps(2); - assert_eq!(listed(&h), ["a.png"]); - - h.get_by_label("a.png").click_secondary(); - h.run_steps(2); - h.get_by_label("Clear Recent Files").click(); - h.run_steps(2); - assert!(listed(&h).is_empty()); - assert!(h.state().0.session.documents().is_empty()); - } - - #[test] - fn pointer_moves_are_bounded_by_the_press_and_release() { - use egui::{Event, PointerButton, pos2}; - let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; - let events = [ - Event::PointerMoved(pos2(1.0, 0.0)), - button(pos2(2.0, 0.0), true), - Event::PointerMoved(pos2(3.0, 0.0)), - Event::PointerMoved(pos2(4.0, 0.0)), - button(pos2(5.0, 0.0), false), - Event::PointerMoved(pos2(6.0, 0.0)), - ]; - // The press is in this frame: only the moves between press and release count. - assert_eq!(pointer_moves(&events, PointerButton::Primary, false), vec![pos2(3.0, 0.0), pos2(4.0, 0.0)]); - // The button was already down when the frame began: the move before the release counts, - // the one after it does not. - assert_eq!(pointer_moves(&events, PointerButton::Primary, true), vec![pos2(1.0, 0.0), pos2(3.0, 0.0), pos2(4.0, 0.0)]); - } - - #[test] - fn freehand_tools_are_the_ones_that_follow_a_path() { - for t in [ - Tool::Brush, - Tool::Pencil, - Tool::MixerBrush, - Tool::ColorReplacement, - Tool::Eraser, - Tool::BackgroundEraser, - Tool::CloneStamp, - Tool::PatternStamp, - Tool::Smudge, - Tool::Dodge, - Tool::Lasso, - Tool::QuickSelection, - ] { - assert!(freehand_tool(t), "{t:?} paints or retouches along a path"); - } - for t in [Tool::Move, Tool::Eyedropper, Tool::Gradient, Tool::Crop, Tool::RectMarquee, Tool::Type, Tool::Hand] { - assert!(!freehand_tool(t), "{t:?} is driven by the pointer's latest position"); - } - } - - #[test] - fn clone_stamp_centre_appears_only_with_option() { - assert!(!brush_tip_centre(Tool::CloneStamp, false, false)); - assert!(brush_tip_centre(Tool::CloneStamp, true, false)); - assert!(brush_tip_centre(Tool::Healing, true, false)); - assert!(!brush_tip_centre(Tool::Healing, false, false)); - assert!(brush_tip_centre(Tool::CloneStamp, false, true)); - assert!(!brush_tip_centre(Tool::PatternStamp, true, false), "Pattern Stamp keeps the brush cursor; Option does not switch it to a clone-source mark"); - assert!(!brush_tip_centre(Tool::QuickSelection, false, true)); - assert!(brush_tip_centre(Tool::BackgroundEraser, false, false)); - } - - #[test] - fn brush_tip_centre_follows_the_crosshair_preference_at_any_size() { - // A large tip used to show the centre mark whatever Show Crosshair in Brush Tip said. - for tool in [Tool::Brush, Tool::Eraser, Tool::PatternStamp, Tool::Dodge] { - assert!(!brush_tip_centre(tool, false, false), "{tool:?}: off"); - assert!(brush_tip_centre(tool, false, true), "{tool:?}: on"); - } - } - - #[test] - fn view_transform_roundtrip() { - for flip in [false, true] { - let xf = ViewXform { - rect: Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0)), - zoom: 2.5, - center: [320.0, 240.0], - flip, - rotation: 0.0, - aspect: 1.0, - }; - let s = xf.to_screen(10.0, 20.0); - let d = xf.to_doc(s); - assert!((d[0] - 10.0).abs() < 1e-3 && (d[1] - 20.0).abs() < 1e-3); - assert_eq!(xf.to_screen(320.0, 240.0), xf.rect.center()); - // Flipped, document x grows to the left. - assert_eq!(xf.to_screen(330.0, 240.0).x > xf.rect.center().x, !flip); - let r = xf.doc_rect(DRect::new(0, 0, 10, 10)); - assert!(r.width() > 0.0 && r.height() > 0.0); - } - } - - #[test] - fn eyedropper_ring_colors_pair_the_sampled_and_current_colours() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 40, "height": 20, "background": "transparent"})).unwrap(); - app.run("shape.create", json!({"kind": "rect", "rect": [0, 0, 20, 20], "fill": "#ff0000"})).unwrap(); - app.run("tools.setColors", json!({"foreground": [0.0, 0.2, 1.0, 1.0]})).unwrap(); - let (new, current) = super::eyedropper_ring_colors(&mut app, 10.0, 10.0).expect("over the red square"); - let near = |c: egui::Color32, r: u8, g: u8, b: u8| { - let d = |a: u8, b: u8| i32::from(a).abs_diff(i32::from(b)); - d(c.r(), r) <= 1 && d(c.g(), g) <= 1 && d(c.b(), b) <= 1 - }; - assert!(near(new, 255, 0, 0), "{new:?}"); - assert!(near(current, 0, 51, 255), "{current:?}"); - // Transparency and points outside the canvas have nothing to compare. - assert!(super::eyedropper_ring_colors(&mut app, 30.0, 10.0).is_none()); - assert!(super::eyedropper_ring_colors(&mut app, -1.0, 10.0).is_none()); - } - - #[test] - fn eyedropper_drag_updates_the_sampled_colour() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 40, "height": 20, "background": "transparent"})).unwrap(); - app.run("shape.create", json!({"kind": "rect", "rect": [0, 0, 20, 20], "fill": "#ff0000"})).unwrap(); - app.run("shape.create", json!({"kind": "rect", "rect": [20, 0, 20, 20], "fill": "#00ff00"})).unwrap(); - app.ui.tool = Tool::Eyedropper; - - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, egui::Modifiers::NONE); - assert!(app.session.tools.foreground[0] > 0.99 && app.session.tools.foreground[1] < 0.01); - - tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 10.0, pressure: 1.0 }, egui::Modifiers::NONE); - assert!(app.session.tools.foreground[1] > 0.99 && app.session.tools.foreground[0] < 0.01); - } - - /// #4298: an adjustment layer has no pixels, so after its icon thumbnail is clicked (the - /// Layers panel no longer targets the mask) Fill, the fill keys and the Paint Bucket still - /// edit its mask, as in Photoshop, instead of failing with "not a pixel layer". - #[test] - fn fills_on_an_adjustment_layer_edit_its_mask_when_the_icon_is_targeted() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 40, "height": 20, "background": "white"})).unwrap(); - app.run("layer.newAdjustmentLayer.curves", json!({})).unwrap(); - // Click the Curves icon thumbnail: the panel targets the layer, not its mask. - app.ui.mask_target = false; - app.sync_mask_targets(); - assert!(!app.ui.mask_target, "the panel's target is the icon"); - let mask_at = |app: &PhotocraftApp| { - let st = app.session.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(10, 10, 0) - }; - assert_eq!(paint_target(&app), json!("mask")); - assert!(crate::menus::is_enabled(&app, "edit.fill"), "Edit > Fill (⇧F5) is enabled"); - assert!(crate::menus::is_enabled(&app, "edit.fillForeground")); - app.ui.tool = Tool::PaintBucket; - app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 0.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]})).unwrap(); - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, egui::Modifiers::NONE); - tool_event(&mut app, ToolEvent::Up { x: 10.0, y: 10.0 }, egui::Modifiers::NONE); - assert_eq!(mask_at(&app), 0.0, "the Paint Bucket filled the mask black"); - app.run("edit.fill", json!({"contents": "white"})).unwrap(); - assert_eq!(mask_at(&app), 1.0, "Edit > Fill filled the mask white"); - assert!(!app.ui.mask_target, "filling doesn't move the panel's target"); - // A pixel layer with an untargeted mask still paints its pixels. - app.run("layer.new.layer", json!({})).unwrap(); - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - app.ui.mask_target = false; - assert_eq!(paint_target(&app), json!("pixels")); - assert!(!app.layer_mask_targeted()); - } - - #[test] - fn alt_with_a_painting_tool_samples_the_foreground_instead_of_painting() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 40, "height": 20, "background": "transparent"})).unwrap(); - app.run("shape.create", json!({"kind": "rect", "rect": [0, 0, 20, 20], "fill": "#ff0000"})).unwrap(); - app.run("shape.create", json!({"kind": "rect", "rect": [20, 0, 20, 20], "fill": "#00ff00"})).unwrap(); - let alt = egui::Modifiers::ALT; - for tool in [Tool::Brush, Tool::Pencil, Tool::Gradient, Tool::PaintBucket] { - app.ui.tool = tool; - app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 1.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]})).unwrap(); - let rev = app.session.active().unwrap().revision; - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, alt); - assert_eq!(app.session.tools.foreground, [1.0, 0.0, 0.0, 1.0], "{tool:?}: ⌥-click sets the foreground"); - // A drag keeps sampling, even after ⌥ is let go; the background is untouched. - tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 10.0, pressure: 1.0 }, egui::Modifiers::NONE); - assert_eq!(app.session.tools.foreground, [0.0, 1.0, 0.0, 1.0], "{tool:?}"); - tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 10.0 }, egui::Modifiers::NONE); - assert_eq!(app.session.tools.background, [1.0, 1.0, 1.0, 1.0]); - assert_eq!(app.session.active().unwrap().revision, rev, "{tool:?}: sampling must not edit the document"); - assert!(app.drag.is_none() && !app.alt_sampling); - } - // Agents get the same through `ui.pointer` (MCP `ui_pointer`). - app.ui.tool = Tool::Brush; - let ctx = egui::Context::default(); - let events = json!([{"kind": "down", "x": 10, "y": 10}, {"kind": "up", "x": 10, "y": 10}]); - let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"modifiers": {"alt": true}, "events": events})); - let _ = crate::control::handle(&mut app, &ctx, &req); - assert_eq!(app.session.tools.foreground, [1.0, 0.0, 0.0, 1.0]); - app.run("tools.setColors", json!({"foreground": [0.0, 1.0, 0.0, 1.0]})).unwrap(); - // Without ⌥ the Brush paints again, and ⌥ pressed mid-stroke doesn't switch to sampling. - app.run("layer.new.layer", json!({})).unwrap(); - let rev = app.session.active().unwrap().revision; - tool_event(&mut app, ToolEvent::Down { x: 5.0, y: 5.0, pressure: 1.0 }, egui::Modifiers::NONE); - tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 5.0, pressure: 1.0 }, alt); - tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 5.0 }, alt); - assert_eq!(app.session.tools.foreground, [0.0, 1.0, 0.0, 1.0]); - assert!(app.session.active().unwrap().revision > rev, "the stroke was painted"); - // Control+Alt stays the brush-resize gesture, never a sample. - assert!(!alt_samples(Tool::Brush, egui::Modifiers { alt: true, ctrl: true, ..Default::default() })); - assert!(!alt_samples(Tool::Eraser, alt), "⌥ with the Eraser is not the Eyedropper"); - } - - /// #2078: the opaque mask-view texture must show the live stroke, not cover it with - /// the committed mask until the mouse is released. - #[test] - fn mask_view_uploads_each_live_stroke_before_release() { - for depth in [8, 16, 32] { - for mode in ["gray", "overlay"] { - for (width, factor) in [(120u32, 1u32), (513, 3)] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": width, "height": 60, "depth": depth})).unwrap(); - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - app.run("view.layerMask", json!({"mode": mode})).unwrap(); - app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 0.0, 1.0]})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 12, "hardness": 1.0, "smoothing": {"amount": 0.0}}})).unwrap(); - app.ui.tool = Tool::Brush; - let ctx = egui::Context::default(); - ctx.input_mut(|i| i.max_texture_side = 256); - let tex = crate::channel_view::ensure(&mut app, &ctx, 0).unwrap(); - ctx.tex_manager().write().take_delta().clear(); - let revision = app.session.documents()[0].revision; - let steps = app.session.documents()[0].history.past_len(); - let layer = app.session.documents()[0].active_layer.unwrap(); - let original = app.session.documents()[0].doc.layer(layer).unwrap().clone(); - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); - for x in [30.0, 50.0, 70.0] { - tool_event(&mut app, ToolEvent::Move { x, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); - let shown = display_doc(&mut app, 0).0; - assert!(shown.layer(layer).unwrap().mask.as_ref().unwrap().value(x as i32, 30) < 0.1); - assert_eq!(crate::channel_view::ensure(&mut app, &ctx, 0), Some(tex)); - let mut delta = ctx.tex_manager().write().take_delta(); - let uploads = delta.set.get(&tex).unwrap_or_else(|| panic!("{depth}-bit {mode}: live mask texture must upload before release at {x}")); - assert_eq!(uploads.len(), 1); - let upload = &uploads[0]; - let pos = upload.pos.expect("only the damaged region is uploaded"); - let egui::ImageData::Color(image) = &upload.image; - assert!(image.pixels.len() < (width.div_ceil(factor) * 60u32.div_ceil(factor)) as usize, "the whole mask is not uploaded"); - let f = factor as i32; - let r = DRect::new(pos[0] as i32 * f, pos[1] as i32 * f, (pos[0] + image.size[0]) as i32 * f, (pos[1] + image.size[1]) as i32 * f) - .intersect(&shown.bounds()); - let expected = crate::channel_view::render( - &shown, - &app.session.documents()[0].channel_view, - r, - factor, - crate::channel_view::Look::default(), - app.session.documents()[0].active_layer, - ) - .unwrap(); - assert_eq!(image.pixels, expected, "uploaded mask values match the live stroke"); - delta.clear(); - assert_eq!(app.session.documents()[0].revision, revision); - assert_eq!(app.session.documents()[0].history.past_len(), steps); - assert_eq!(app.session.documents()[0].doc.layer(layer).unwrap(), &original); - crate::channel_view::ensure(&mut app, &ctx, 0); - assert!(ctx.tex_manager().write().take_delta().set.is_empty(), "idle frame does not upload"); - } - tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 30.0 }, egui::Modifiers::NONE); - let st = &app.session.documents()[0]; - assert_eq!(st.history.past_len(), steps + 1); - assert!(st.doc.layer(layer).unwrap().mask.as_ref().unwrap().value(50, 30) < 0.1); - assert_eq!(st.doc.layer(layer).unwrap().content, original.content); - crate::channel_view::ensure(&mut app, &ctx, 0); - let mut delta = ctx.tex_manager().write().take_delta(); - // The commit takes the live stroke's pixels, which the texture already shows: at - // most a partial upload, never the whole mask again. - assert!(delta.set.get(&tex).is_none_or(|u| u.iter().all(|u| u.pos.is_some())), "commit keeps its partial upload"); - delta.clear(); - app.session.undo(); - assert_eq!(app.session.documents()[0].doc.layer(layer).unwrap(), &original); - crate::channel_view::ensure(&mut app, &ctx, 0); - let mut delta = ctx.tex_manager().write().take_delta(); - let egui::ImageData::Color(image) = &delta.set.get(&tex).unwrap()[0].image; - let st = &app.session.documents()[0]; - assert_eq!( - image.pixels, - crate::channel_view::render(&st.doc, &st.channel_view, st.doc.bounds(), factor, crate::channel_view::Look::default(), st.active_layer) - .unwrap(), - "undo restores the shown mask" - ); - delta.clear(); - } - } - } - } - - #[test] - fn channel_views_show_live_targets_and_discarded_strokes() { - for target in ["quickMask", "alpha", "red"] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); - match target { - "quickMask" => { - app.run("select.rect", json!({"x": 0, "y": 0, "width": 120, "height": 60})).unwrap(); - app.run("select.editInQuickMaskMode", json!({})).unwrap(); - } - "alpha" => { - app.run("channel.new", json!({"fill": "white"})).unwrap(); - } - _ => { - app.run("channel.target", json!({"channel": "red"})).unwrap(); - } - } - app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 0.0, 1.0]})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 12, "hardness": 1.0, "smoothing": {"amount": 0.0}}})).unwrap(); - app.ui.tool = Tool::Brush; - let ctx = egui::Context::default(); - let tex = crate::channel_view::ensure(&mut app, &ctx, 0).unwrap(); - ctx.tex_manager().write().take_delta().clear(); - let original = app.session.documents()[0].doc.clone(); - let steps = app.session.documents()[0].history.past_len(); - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); - tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); - let shown = display_doc(&mut app, 0).0; - crate::channel_view::ensure(&mut app, &ctx, 0); - let mut delta = ctx.tex_manager().write().take_delta(); - let upload = &delta.set.get(&tex).expect("live channel upload")[0]; - let pos = upload.pos.expect("partial channel upload"); - let egui::ImageData::Color(image) = &upload.image; - let r = DRect::new(pos[0] as i32, pos[1] as i32, (pos[0] + image.size[0]) as i32, (pos[1] + image.size[1]) as i32); - assert_eq!( - image.pixels, - crate::channel_view::render( - &shown, - &app.session.documents()[0].channel_view, - r, - 1, - crate::channel_view::Look::default(), - app.session.documents()[0].active_layer - ) - .unwrap(), - "{target}" - ); - assert_ne!( - image.pixels, - crate::channel_view::render( - &original, - &app.session.documents()[0].channel_view, - r, - 1, - crate::channel_view::Look::default(), - app.session.documents()[0].active_layer - ) - .unwrap(), - "target was painted" - ); - delta.clear(); - assert_eq!(app.session.documents()[0].history.past_len(), steps); - assert!(std::sync::Arc::ptr_eq(&original, &app.session.documents()[0].doc)); - // Dropping a preview without committing must restore its texture, even though the - // document revision did not change. There is no committed damage rectangle to use. - app.drag = None; - app.live_stroke = None; - crate::channel_view::ensure(&mut app, &ctx, 0); - let mut delta = ctx.tex_manager().write().take_delta(); - let upload = &delta.set.get(&tex).unwrap()[0]; - assert!(upload.pos.is_none(), "discarding a preview refreshes the view"); - let egui::ImageData::Color(image) = &upload.image; - assert_eq!( - image.pixels, - crate::channel_view::render( - &original, - &app.session.documents()[0].channel_view, - original.bounds(), - 1, - crate::channel_view::Look::default(), - app.session.documents()[0].active_layer - ) - .unwrap() - ); - delta.clear(); - } - } - - /// The held drag shows true mixed paint while Alt sampling remains separate from painting. - #[test] - fn mixer_drag_shows_actual_mixed_paint_before_release_and_alt_never_paints() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("tools.setColors", json!({"foreground":"#ff0000"})).unwrap(); - app.run("tools.setBrush", json!({"brush":{"size":16,"mixer":{"wet":1.0,"mix":0.7,"sampleAllLayers":true},"smoothing":{"amount":0.0}}})).unwrap(); - app.ui.tool = Tool::MixerBrush; - let before = app.session.active().unwrap().doc.clone(); - let count = app.session.active().unwrap().history.past_len(); - let alt = egui::Modifiers { alt: true, ..Default::default() }; - tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, alt); - tool_event(&mut app, ToolEvent::Move { x: 35.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); - tool_event(&mut app, ToolEvent::Up { x: 35.0, y: 30.0 }, egui::Modifiers::NONE); - assert!(app.drag.is_none()); - assert!(app.session.tools.mixer.spatial.is_some()); - assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); - app.run("brush.mixer.load", json!({})).unwrap(); - tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); - tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 30.0, pressure: 0.6 }, egui::Modifiers::NONE); - assert!(app.live_stroke.is_some()); - let shown = display_doc(&mut app, 0).0; - let id = app.session.active().unwrap().active_layer.unwrap(); - let pixel = shown.layer(id).unwrap().surface().unwrap().rgba(45, 30); - assert!(pixel[0] > 0.0 && pixel[1] > 0.0 && pixel[3] > 0.0, "actual red/green mixture {pixel:?}"); - assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); - assert_eq!(app.session.active().unwrap().history.past_len(), count); - tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 30.0 }, egui::Modifiers::NONE); - let st = app.session.active().unwrap(); - assert_eq!(st.history.past_len(), count + 1); - assert_eq!( - shown.layer(id).unwrap().surface().unwrap().read_region(before.bounds()), - st.doc.layer(id).unwrap().surface().unwrap().read_region(before.bounds()) - ); - app.session.undo(); - assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().surface().unwrap().rgba(45, 30)[3], 0.0); - } - - /// Release incorporates its final endpoint and deferred samples in both live and fallback paths. - #[test] - fn mixer_release_includes_a_new_endpoint_and_deferred_frame_samples() { - for (deferred, failed) in [(false, false), (true, false), (false, true)] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("tools.setBrush", json!({"size":12,"pressureSize":false})).unwrap(); - app.ui.tool = Tool::MixerBrush; - let before = app.session.active().unwrap().doc.clone(); - let m = egui::Modifiers::NONE; - tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, m); - app.defer_live_stroke = deferred; - if failed { - app.live_stroke.as_mut().unwrap().preview_failed = true; - } - tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 30.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x: 95.0, y: 30.0 }, m); - let doc = app.session.active().unwrap().doc.clone(); - let id = app.session.active().unwrap().active_layer.unwrap(); - assert!(doc.layer(id).unwrap().surface().unwrap().rgba(92, 30)[3] > 0.0); - let params = app.session.journal.iter().rev().find(|(name, _)| name == "paint.mixerBrush").unwrap().1.clone(); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(*app.session.active().unwrap().doc, *before); - app.run("paint.mixerBrush", params).unwrap(); - assert_eq!(*app.session.active().unwrap().doc, *doc); - } - } - - /// Reproduce a tool change and release in one control call, before a UI frame can cancel the old gesture. - #[test] - fn mixer_control_tool_switch_before_release_cancels_every_preview_path() { - for preview in 0..3 { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("tools.setBrush", json!({"size":12,"pressureSize":false})).unwrap(); - let before = app.session.active().unwrap().doc.clone(); - let steps = app.session.active().unwrap().history.past_len(); - let anchor = app.last_stroke_end; - let ctx = egui::Context::default(); - let (request, _reply) = crate::control::ControlRequest::new( - "ui.pointer", - json!({"tool":"mixerBrush","events":[{"kind":"down","x":20,"y":30},{"kind":"move","x":50,"y":30}]}), - ); - let _ = crate::control::handle(&mut app, &ctx, &request); - assert!(app.drag.is_some() && app.live_stroke.is_some()); - if preview == 1 { - app.live_stroke.as_mut().unwrap().preview_failed = true; - } else if preview == 2 { - app.live_stroke = None; - } - // No intervening UI frame: control selects the new tool before dispatching Up. - let (request, _reply) = crate::control::ControlRequest::new("ui.pointer", json!({"tool":"brush","events":[{"kind":"up","x":95,"y":30}]})); - let _ = crate::control::handle(&mut app, &ctx, &request); - assert_eq!(app.ui.tool, Tool::Brush); - assert!(app.drag.is_none() && app.live_stroke.is_none()); - assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); - assert_eq!(app.session.active().unwrap().history.past_len(), steps); - assert_eq!(app.last_stroke_end, anchor); - assert!(!app.session.journal.iter().any(|(id, _)| id == "paint.mixerBrush")); - } - } - - /// Escape and tool changes cancel both ordinary previews and failed-preview fallback gestures. - #[test] - fn mixer_escape_and_tool_switch_cancel_without_an_edit() { - for mode in 0..4 { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.ui.tool = Tool::MixerBrush; - let before = app.session.active().unwrap().doc.clone(); - let steps = app.session.active().unwrap().history.past_len(); - tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); - assert!(app.live_stroke.is_some()); - if mode >= 2 { - app.live_stroke.as_mut().unwrap().preview_failed = true; - } - let mode = mode % 2; - let ctx = egui::Context::default(); - let mut raw = egui::RawInput { focused: true, ..Default::default() }; - if mode == 0 { - raw.events.push(egui::Event::Key { - key: egui::Key::Escape, - physical_key: None, - pressed: true, - repeat: false, - modifiers: egui::Modifiers::NONE, - }); - } - if mode == 1 { - app.ui.tool = Tool::Brush; - } - ctx.begin_pass(raw); - assert!(cancel_mixer_on_context_change(&mut app, &ctx)); - let mut output = ctx.end_pass(); - output.textures_delta.clear(); - tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }, egui::Modifiers::NONE); - assert!(app.drag.is_none() && app.live_stroke.is_none()); - assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); - assert_eq!(app.session.active().unwrap().history.past_len(), steps); - } - } - - /// Control-driven strokes remain live in a background window, matching the ordinary Brush. - #[test] - fn mixer_background_window_keeps_and_commits_control_strokes() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width":120,"height":60,"background":"transparent"})).unwrap(); - app.run("tools.setBrush", json!({"brush":{"size":12,"pressureSize":false}})).unwrap(); - let steps = app.session.active().unwrap().history.past_len(); - let ctx = egui::Context::default(); - ctx.begin_pass(egui::RawInput { focused: false, ..Default::default() }); - let (request, _reply) = crate::control::ControlRequest::new( - "ui.pointer", - json!({"tool":"mixerBrush","events":[{"kind":"down","x":20,"y":30},{"kind":"move","x":60,"y":30}]}), - ); - let _ = crate::control::handle(&mut app, &ctx, &request); - assert!(!cancel_mixer_on_context_change(&mut app, &ctx)); - assert!(app.drag.is_some()); - let (request, _reply) = crate::control::ControlRequest::new("ui.pointer", json!({"tool":"mixerBrush","events":[{"kind":"up","x":95,"y":30}]})); - let _ = crate::control::handle(&mut app, &ctx, &request); - let mut output = ctx.end_pass(); - output.textures_delta.clear(); - assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); - assert!(app.session.journal.iter().any(|(id, _)| id == "paint.mixerBrush")); - let st = app.session.active().unwrap(); - assert!(st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(60, 30)[3] > 0.0); - } - - /// A tip above the live preview's 1024 px paints on release, as main and Photoshop paint it - /// up to 5000 px; a stroke that can't paint at all is still refused on press. - #[test] - fn mixer_drag_above_the_preview_size_paints_on_release() { - for locked in [false, true] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - if locked { - app.run("layer.lockLayers", json!({"pixels": true})).unwrap(); - } - app.run("tools.setColors", json!({"foreground":"#ff0000"})).unwrap(); - app.run("tools.setBrush", json!({"brush":{"size":2000,"hardness":1.0,"pressureSize":false,"mixer":{"wet":0.0,"mix":0.0}}})).unwrap(); - app.ui.tool = Tool::MixerBrush; - let steps = app.session.active().unwrap().history.past_len(); - let m = egui::Modifiers::NONE; - tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, m); - assert!(app.live_stroke.is_none(), "no live preview above 1024 px"); - assert_eq!(app.drag.is_some(), !locked, "a valid 2000 px stroke is kept for release"); - assert_eq!(app.ui.status_error, locked, "{}", app.ui.status); - tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 30.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 30.0 }, m); - let st = app.session.active().unwrap(); - assert_eq!(st.history.past_len(), steps + usize::from(!locked)); - let pixel = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(60, 30); - assert_eq!(pixel[0] > 0.9 && pixel[3] > 0.9, !locked, "{pixel:?}"); - } - } - - /// ⌥ with a held temporary tool (macOS ⌘ = Move) is that tool's, not a Mixer Brush paint load. - #[test] - fn mixer_alt_with_a_held_temporary_tool_does_not_load_paint() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.ui.tool = Tool::MixerBrush; - app.tool_override = Some(Tool::Move); - let alt = egui::Modifiers { alt: true, ..Default::default() }; - tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, alt); - tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }, alt); - assert!(app.session.tools.mixer.spatial.is_none(), "the held Move tool doesn't sample"); - app.tool_override = None; - tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, alt); - assert!(app.session.tools.mixer.spatial.is_some(), "⌥ with the Mixer Brush itself samples"); - } - - #[test] - fn brush_drag_shows_the_real_stroke_and_commits_it() { - // The drag used to draw a hard, flat stand-in and only showed the soft brush on release. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 120, "height": 60, "background": "transparent"})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 0.0}})).unwrap(); - app.ui.tool = Tool::Brush; - let m = egui::Modifiers::NONE; - let alpha = |d: &Document, x, y| d.layers[0].surface().unwrap().rgba(x, y)[3]; - let rev = app.session.documents()[0].revision; - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, m); - for x in [40.0, 70.0, 100.0] { - tool_event(&mut app, ToolEvent::Move { x, y: 30.0, pressure: 1.0 }, m); - } - let (shown, key) = display_doc(&mut app, 0); - assert_ne!(key, 0); - // A partial value two thirds of the way out: the soft tip, not a hard flat stand-in. - assert!(alpha(&shown, 40, 30) > 0.5 && (0.01..0.95).contains(&alpha(&shown, 40, 36)), "soft stroke while drawing"); - 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(); - 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(); - assert!(app.live_stroke.is_none() && display_doc(&mut app, 0).1 == 0); - assert_eq!((alpha(&doc, 40, 30), alpha(&doc, 40, 38)), (alpha(&shown, 40, 30), alpha(&shown, 40, 38)), "commit matches the preview"); - } - - #[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 - // is wider than MAX_TEXTURE, so the CPU texture is reduced (factor 2) and each step - // must update only the reduced pixels it touched. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - ctx.input_mut(|i| i.max_texture_side = 8192); - app.run("file.new", json!({"width": 4097, "height": 90, "background": "transparent"})).unwrap(); - let tilt = json!({"size": 30, "hardness": 1.0, "spacing": 0.05, "shapeDynamics": {"enabled": true, "size": {"control": "penTilt"}}}); - app.run("tools.setBrush", json!({ "brush": tilt })).unwrap(); - app.ui.tool = Tool::Brush; - assert_eq!(ensure_texture(&mut app, &ctx, 0, None).map(|t| t.1), Some(0.5)); - let m = egui::Modifiers::NONE; - app.stylus.feed.set(Some(crate::stylus::PenSample { pressure: 1.0, tilt_x: 60.0, tilt_y: 0.0, rotation: 0.0, eraser: false })); - tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 45.0, pressure: 1.0 }, m); - for x in [300.0, 600.0, 900.0] { - tool_event(&mut app, ToolEvent::Move { x, y: 45.0, pressure: 1.0 }, m); - ensure_texture(&mut app, &ctx, 0, None); - assert_eq!(app.perf.last_refresh, "rect"); - assert!(app.perf.last_refresh_px < 4097 * 90 / 4, "{}", app.perf.last_refresh_px); - } - let shown = display_doc(&mut app, 0).0; - tool_event(&mut app, ToolEvent::Up { x: 900.0, y: 45.0 }, m); - ensure_texture(&mut app, &ctx, 0, None); - assert_eq!(app.perf.last_refresh, "rect", "the commit refreshes only the stroke"); - let doc = app.session.documents()[0].doc.clone(); - let (a, b) = (doc.layers[0].surface().unwrap(), shown.layers[0].surface().unwrap()); - // 60° tilt shrinks the dab well below 30 px: the preview shows that size, as committed. - assert!(a.rgba(500, 45)[3] > 0.5 && a.rgba(500, 45 + 12)[3] == 0.0); - // (The smoothed tail catches up to the end point only when the stroke finishes.) - assert!((0..90).all(|y| (0..700).all(|x| a.rgba(x, y) == b.rgba(x, y))), "commit matches the preview"); - } - - /// Brush drag along y = 40 with one canvas frame per pointer move; returns the document the - /// canvas showed at the last move, the committed one, and whether the release refreshed only - /// the stroke's rectangle. - fn drag_frames(smoothing: f32, xs: &[f64]) -> (std::sync::Arc, std::sync::Arc, bool, PhotocraftApp) { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 200, "height": 80, "background": "transparent"})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 16, "hardness": 0.5}})).unwrap(); - // What the options bar's Smoothing field writes. - app.session.tools.brush.smoothing.amount = smoothing; - app.ui.tool = Tool::Brush; - ensure_texture(&mut app, &ctx, 0, None); - let m = egui::Modifiers::NONE; - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 1.0 }, m); - for &x in xs { - tool_event(&mut app, ToolEvent::Move { x, y: 40.0 + (x / 7.0).sin() * 8.0, pressure: 1.0 }, m); - ensure_texture(&mut app, &ctx, 0, None); - } - let live = display_doc(&mut app, 0).0; - let last = *xs.last().unwrap(); - tool_event(&mut app, ToolEvent::Up { x: last, y: 40.0 + (last / 7.0).sin() * 8.0 }, m); - let (next, key) = display_doc(&mut app, 0); - assert_eq!(key, 0, "the frame after release shows the committed document"); - ensure_texture(&mut app, &ctx, 0, None); - let partial = app.perf.last_refresh == "rect"; - (live, next, partial, app) - } - - fn same_pixels(a: &Document, b: &Document) -> bool { - let (a, b) = (a.layers[0].surface().unwrap(), b.layers[0].surface().unwrap()); - (0..80).all(|y| (0..200).all(|x| a.rgba(x, y) == b.rgba(x, y))) - } - - #[test] - fn release_shows_nothing_new_without_smoothing() { - // #73: at 0 % the stroke follows the pointer; the last frame drawn while dragging is - // exactly the committed stroke, so release changes nothing on screen. - let (live, done, partial, app) = drag_frames(0.0, &[40.0, 70.0, 100.0, 130.0, 160.0]); - assert!(same_pixels(&live, &done), "preview at the last move = committed stroke"); - assert!(partial, "the handover refreshes only the stroke"); - let p = app.session.journal.iter().rev().find(|(id, _)| id == "paint.stroke").map(|(_, p)| p.clone()).unwrap(); - assert!(p.get("smoothing").is_none(), "the commit uses the session brush's smoothing, not a hard-coded one"); - } - - #[test] - fn navigator_keeps_its_image_during_a_live_brush_stroke() { - // #1631: every step of a live stroke is a new preview key, so a navigator keyed by it - // re-composited the whole document per frame while painting. It waits for the release. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 200, "height": 80, "background": "transparent"})).unwrap(); - app.ui.tool = Tool::Brush; - let m = egui::Modifiers::NONE; - assert!(!navigator_waits_for_drag(&app, 0)); - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 1.0 }, m); - let mut keys = Vec::new(); - for x in [40.0, 70.0, 100.0] { - tool_event(&mut app, ToolEvent::Move { x, y: 40.0, pressure: 1.0 }, m); - keys.push(display_doc(&mut app, 0).1); - assert!(navigator_waits_for_drag(&app, 0), "painting at x = {x}"); - } - assert!(keys.windows(2).all(|k| k[0] != k[1]), "each step is a new preview: {keys:?}"); - tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 40.0 }, m); - assert!(!navigator_waits_for_drag(&app, 0), "the navigator catches up on release"); - } - - #[test] - fn smoothed_stroke_shows_its_catch_up_tail_while_drawing() { - // #73: with smoothing the brush lags behind the pointer and catches up at the end; the - // preview draws that tail live, so no frame after release is missing the end. - let xs = [30.0, 50.0, 70.0, 90.0, 110.0, 130.0, 150.0, 170.0]; - let (live, done, partial, _) = drag_frames(0.5, &xs); - assert!(same_pixels(&live, &done), "preview at the last move = committed stroke, tail included"); - assert!(partial); - let end = |d: &Document| (0..200).rev().find(|&x| (0..80).any(|y| d.layers[0].surface().unwrap().rgba(x, y)[3] > 0.0)).unwrap(); - assert!(end(&live) >= 170, "the end reaches the pointer while drawing ({})", end(&live)); - // The options-bar value reaches the stroke: 50 % smooths the wiggle, 0 % doesn't. - let (_, rough, _, _) = drag_frames(0.0, &xs); - assert!(!same_pixels(&rough, &done), "smoothing changes the stroke"); - // And the commit is what `paint.stroke` gives with that smoothing. - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 200, "height": 80, "background": "transparent"})).unwrap(); - s.execute("tools.setBrush", json!({"brush": {"size": 16, "hardness": 0.5, "smoothing": {"amount": 0.5}}})).unwrap(); - let mut pts = vec![json!([10.0, 40.0, 1.0])]; - pts.extend(xs.iter().map(|&x| json!([x, 40.0 + (x / 7.0).sin() * 8.0, 1.0]))); - // (Round tips without dynamics draw the same for any seed.) - s.execute("paint.stroke", json!({"points": pts, "seed": 0})).unwrap(); - assert!(same_pixels(&s.active().unwrap().doc, &done)); - } - - #[test] - fn smoothing_preview_redraws_the_tail_each_step() { - // The tail drawn at one step must not linger once the brush moves on: a sharp turn would - // leave a stale tail behind if it weren't restored. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 200, "height": 120, "background": "transparent"})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 10, "hardness": 1.0, "smoothing": {"amount": 0.6}}})).unwrap(); - app.ui.tool = Tool::Brush; - let m = egui::Modifiers::NONE; - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 20.0, pressure: 1.0 }, m); - for (x, y) in [(60.0, 20.0), (110.0, 20.0), (110.0, 70.0), (110.0, 110.0), (60.0, 110.0)] { - tool_event(&mut app, ToolEvent::Move { x, y, pressure: 1.0 }, m); - } - let live = display_doc(&mut app, 0).0; - tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 110.0 }, m); - let done = app.session.documents()[0].doc.clone(); - let (a, b) = (live.layers[0].surface().unwrap(), done.layers[0].surface().unwrap()); - assert!((0..120).all(|y| (0..200).all(|x| a.rgba(x, y) == b.rgba(x, y))), "no stale tails in the preview"); - } - - /// Shapes the drag preview paints for `app` this frame. - fn drag_preview_shapes(app: &mut PhotocraftApp, ctx: &egui::Context, zoom: f32) -> Vec { - let out = ctx.run_ui(egui::RawInput::default(), |ui| { - let ctx = ui.ctx(); - let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); - let painter = ctx.layer_painter(egui::LayerId::background()).with_clip_rect(rect); - let xf = ViewXform { rect, zoom, center: [60.0, 30.0], flip: false, rotation: 0.0, aspect: 1.0 }; - draw_drag_preview(app, &painter, &xf); - }); - let egui::FullOutput { mut textures_delta, shapes, .. } = out; - textures_delta.clear(); - shapes - } - - #[test] - fn a_huge_view_centre_draws_the_selection_outline_without_overflow() { - // #980: `ui.set` takes any finite centre, and the outline's visible region was quantised - // with unchecked i32 arithmetic: the frame panicked ("attempt to multiply/subtract with - // overflow") and release builds wrapped to an inverted region. - let ctx = egui::Context::default(); - // Zoomed far out the quantisation step, and so the padding, is largest (64 · 256 px). - let cases = [([1e30, 1e30], false), ([-1e30, -1e30], false), ([3e9, -3e9], false), ([512.0, 512.0], true)]; - for ((centre, traced), zoom) in cases.into_iter().flat_map(|c| [(c, 1.0), (c, 1.0 / 64.0)]) { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 1024, "height": 1024})).unwrap(); - app.run("select.rect", json!({"x": 0, "y": 0, "width": 512, "height": 512})).unwrap(); - app.sync_views(); - let (req, _rx) = crate::control::ControlRequest::new("ui.set", json!({ "center": centre, "zoom": zoom })); - let _ = crate::control::handle(&mut app, &ctx, &req); - let view = app.ui.views[0].clone(); - assert_eq!(view.zoom, zoom, "ui.set applied the zoom"); - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { - canvas_view(&mut app, ui, 0, Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), view.clone(), false); - }); - out.textures_delta.clear(); - // Control: a centre on the selection's corner still traces the outline (the selection - // spans several 64 px trace cells even zoomed out). - let segs = app.outline_cache.as_ref().map_or(0, |(_, _, s)| s.len()); - assert_eq!(segs > 0, traced, "{centre:?} at zoom {zoom}"); - } - } - - #[test] - fn a_one_pixel_selection_traces_at_hundred_percent_on_a_scaled_display() { - // #1943 review: the outline step is display resolution in device pixels, not points, so a - // 1 px selection still traces at 100 % on a 2x display (a points-based step sampled every - // second pixel and lost it: zero segments). - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); - app.run("select.rect", json!({"x": 50, "y": 50, "width": 1, "height": 100})).unwrap(); - app.run("view.actualPixels", json!({})).unwrap(); - app.sync_views(); - let view = app.ui.views[0].clone(); - let mut input = egui::RawInput::default(); - input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(2.0); - let mut out = ctx.run_ui(input, |ui| { - canvas_view(&mut app, ui, 0, Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), view.clone(), true); - }); - out.textures_delta.clear(); - assert_eq!(app.ppp, 2.0, "the primary canvas records the display scale"); - let segs = app.outline_cache.as_ref().map_or(0, |(_, _, s)| s.len()); - assert!(segs > 0, "a 1 px selection traces at 100 % on a 2x display"); - } - - #[test] - fn a_secondary_canvas_does_not_overwrite_the_main_canvas_scale() { - // #1943 review: a document window can sit on a display with another scale; only the - // primary canvas records `app.ppp`, so the main mapping doesn't change under it. - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - app.run("view.actualPixels", json!({})).unwrap(); - app.sync_views(); - let view = app.ui.views[0].clone(); - let frame = |app: &mut PhotocraftApp, ppp: f32, primary: bool| { - let mut input = egui::RawInput::default(); - input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(ppp); - let mut out = ctx.run_ui(input, |ui| { - canvas_view(app, ui, 0, Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), view.clone(), primary); - }); - out.textures_delta.clear(); - }; - frame(&mut app, 2.0, true); - assert_eq!(app.ppp, 2.0); - frame(&mut app, 1.0, false); - assert_eq!(app.ppp, 2.0, "a secondary window's scale doesn't replace the main canvas's"); - // The main canvas mapping still uses its own scale: 100 % is 1 doc px per physical px. - let xf = ViewXform::active(&app).unwrap(); - let step = xf.to_screen(1.0, 0.0) - xf.to_screen(0.0, 0.0); - assert!((step.x - 0.5).abs() < 1e-3, "{step:?}"); - } - - #[test] - fn a_flicked_hand_drag_glides_on_only_with_flick_panning() { - // #204: Preferences › Tools › Enable Flick Panning. A fast Hand drag let go while moving - // keeps the view gliding for a while; off, the view stops where the drag ended. - for flick in [true, false] { - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 2000, "height": 1500})).unwrap(); - app.run("prefs.set", json!({"path": "tools.enableFlickPanning", "value": flick})).unwrap(); - app.ui.tool = Tool::Hand; - app.sync_views(); - let mut view = app.ui.views[0].clone(); - view.zoom = 1.0; - view.center = [1000.0, 750.0]; - view.fit_pending = false; - view.fill_pending = false; - let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); - let mut frame = |app: &mut PhotocraftApp, events: Vec| -> View { - let input = egui::RawInput { screen_rect: Some(rect), events, ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| { - view = canvas_view(app, ui, 0, rect, view.clone(), true); - }); - out.textures_delta.clear(); - view.clone() - }; - 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 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)]).center; - let mut centers = vec![released]; - for _ in 0..5 { - centers.push(frame(&mut app, vec![]).center); - } - if flick { - // Dragged left: the image follows the pointer, the view keeps moving right. - for w in centers.windows(2) { - assert!(w[1][0] > w[0][0], "glides on: {centers:?}"); - } - // ...and comes to rest. - let mut last = *centers.last().unwrap(); - for _ in 0..120 { - last = frame(&mut app, vec![]).center; - } - assert_eq!(frame(&mut app, vec![]).center, last, "the glide stops"); - } else { - assert!(centers.iter().all(|c| *c == released), "no glide when off: {centers:?}"); - } - } - } - - #[test] - fn a_secondary_canvas_hand_pans_while_a_transform_is_open() { - // #2302 review: `app.ui.transform` is global, but only the primary canvas draws and drives - // the box. A secondary window's Hand must still pan while the main window transforms. - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.run("select.deselect", json!({})).unwrap(); - app.run("view.actualPixels", json!({})).unwrap(); - app.ui.tool = Tool::Hand; - app.sync_views(); - crate::transform_tool::begin(&mut app, &ctx).expect("a transform starts"); - let mut view0 = app.ui.views[0].clone(); - view0.zoom = 1.0; - view0.center = [200.0, 150.0]; - view0.fit_pending = false; - view0.fill_pending = false; - let center0 = view0.center; - let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); - let frame = |app: &mut PhotocraftApp, events: Vec| -> View { - let input = egui::RawInput { screen_rect: Some(rect), events, ..Default::default() }; - let mut seen = view0.clone(); - let mut out = ctx.run_ui(input, |ui| { - seen = canvas_view(app, ui, 0, rect, view0.clone(), false); - }); - out.textures_delta.clear(); - seen - }; - 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)]); - for dx in [10.0, 20.0, 40.0] { - frame(&mut app, vec![egui::Event::PointerMoved(start + vec2(dx, 0.0))]); - } - let dragged = frame(&mut app, vec![egui::Event::PointerMoved(start + vec2(60.0, 0.0))]); - frame(&mut app, vec![press(start + vec2(60.0, 0.0), false)]); - assert_ne!(dragged.center, center0, "a secondary window's Hand pans while transforming"); - } - - #[test] - fn letting_go_of_alt_during_an_alt_sample_press_does_not_paint() { - // #7802: Alt-pressing with the Brush samples a colour on the press. If Alt was let go - // before egui recognised the drag, that drag started a stroke from the sampled point. - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("view.actualPixels", json!({})).unwrap(); - app.ui.tool = Tool::Brush; - app.sync_views(); - let mut view = app.ui.views[0].clone(); - view.zoom = 1.0; - view.center = [200.0, 150.0]; - view.fit_pending = false; - view.fill_pending = false; - let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); - let 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| { - canvas_view(app, ui, 0, rect, view.clone(), true); - }); - out.textures_delta.clear(); - }; - let alt = egui::Modifiers::ALT; - let none = egui::Modifiers::NONE; - let start = Pos2::new(200.0, 150.0); - let press = - |pos: Pos2, pressed: bool, modifiers: egui::Modifiers| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; - // Alt released mid-press, and Alt held throughout: both only sample. - for release_alt in [true, false] { - app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 1.0, 1.0]})).unwrap(); - let rev = app.session.active().unwrap().revision; - frame(&mut app, vec![egui::Event::ModifiersChanged(alt), egui::Event::PointerMoved(start)]); - frame(&mut app, vec![press(start, true, alt)]); - assert_eq!(app.session.tools.foreground, [1.0, 1.0, 1.0, 1.0], "the press sampled the white canvas"); - let later = if release_alt { none } else { alt }; - let end = start + vec2(20.0, 0.0); - frame(&mut app, vec![egui::Event::ModifiersChanged(later), egui::Event::PointerMoved(end)]); - frame(&mut app, vec![press(end, false, later)]); - frame(&mut app, vec![egui::Event::ModifiersChanged(none)]); - assert_eq!(app.session.active().unwrap().revision, rev, "release_alt={release_alt}: an Alt-sample press must not paint"); - assert!(app.drag.is_none() && !app.alt_sampling, "release_alt={release_alt}"); - } - // Without Alt the same gesture paints. - let rev = app.session.active().unwrap().revision; - frame(&mut app, vec![egui::Event::PointerMoved(start)]); - frame(&mut app, vec![press(start, true, none)]); - frame(&mut app, vec![egui::Event::PointerMoved(start + vec2(20.0, 0.0))]); - frame(&mut app, vec![press(start + vec2(20.0, 0.0), false, none)]); - assert!(app.session.active().unwrap().revision > rev, "a plain drag paints"); - } - - #[test] - fn letting_go_of_alt_during_a_mixer_brush_sample_press_does_not_paint() { - // As #7802 for the Brush: an Alt-press with the Mixer Brush loads paint from the canvas. - // If Alt was let go before egui recognised the drag, that drag started a Mixer stroke. - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("view.actualPixels", json!({})).unwrap(); - app.ui.tool = Tool::MixerBrush; - app.sync_views(); - let mut view = app.ui.views[0].clone(); - view.zoom = 1.0; - view.center = [200.0, 150.0]; - view.fit_pending = false; - view.fill_pending = false; - let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); - let 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| { - canvas_view(app, ui, 0, rect, view.clone(), true); - }); - out.textures_delta.clear(); - }; - let (alt, none) = (egui::Modifiers::ALT, egui::Modifiers::NONE); - let start = Pos2::new(200.0, 150.0); - let press = - |pos: Pos2, pressed: bool, modifiers: egui::Modifiers| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; - // Alt released mid-press, and Alt held throughout: both only load paint. - for release_alt in [true, false] { - let rev = app.session.active().unwrap().revision; - frame(&mut app, vec![egui::Event::ModifiersChanged(alt), egui::Event::PointerMoved(start)]); - frame(&mut app, vec![press(start, true, alt)]); - let later = if release_alt { none } else { alt }; - let end = start + vec2(20.0, 0.0); - frame(&mut app, vec![egui::Event::ModifiersChanged(later), egui::Event::PointerMoved(end)]); - frame(&mut app, vec![press(end, false, later)]); - frame(&mut app, vec![egui::Event::ModifiersChanged(none)]); - assert_eq!(app.session.active().unwrap().revision, rev, "release_alt={release_alt}: an Alt-sample press must not paint"); - assert!(app.drag.is_none() && !app.mixer_sampling, "release_alt={release_alt}"); - } - // Without Alt the same gesture paints. - let rev = app.session.active().unwrap().revision; - frame(&mut app, vec![egui::Event::PointerMoved(start)]); - frame(&mut app, vec![press(start, true, none)]); - frame(&mut app, vec![egui::Event::PointerMoved(start + vec2(20.0, 0.0))]); - frame(&mut app, vec![press(start + vec2(20.0, 0.0), false, none)]); - assert!(app.session.active().unwrap().revision > rev, "a plain drag paints"); - } - - #[test] - fn guides_draw_over_the_transform_preview_and_under_its_box() { - // #5086: a guide crossing a layer under Free Transform was hidden behind the preview of - // the moving pixels. The preview is image content, drawn before the grid and guides like - // the document is; the box and handles still go over them, as in Photoshop. - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.run("select.deselect", json!({})).unwrap(); - app.run("view.newGuide", json!({"orientation": "vertical", "position": 150})).unwrap(); - app.ui.extras.guides = true; - app.ui.extras.rulers = false; - app.sync_views(); - crate::transform_tool::begin(&mut app, &ctx).expect("a transform starts"); - let mut view = app.ui.views[0].clone(); - view.zoom = 1.0; - view.center = [200.0, 150.0]; - view.fit_pending = false; - view.fill_pending = false; - let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); - let input = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| { - canvas_view(&mut app, ui, 0, rect, view.clone(), true); - }); - out.textures_delta.clear(); - // At 100 % centred on the document, screen and document coordinates coincide. - let layer = Rect::from_min_max(pos2(100.0, 100.0), pos2(200.0, 160.0)); - let near = |r: Rect| (r.min - layer.min).length() < 1.0 && (r.max - layer.max).length() < 1.0; - let position = |pred: &dyn Fn(&egui::Shape) -> bool| out.shapes.iter().position(|s| pred(&s.shape)); - // The moving pixels: the mesh that spans the layer's box. - let preview = position(&|s| matches!(s, egui::Shape::Mesh(m) if near(m.calc_bounds()))); - // The guide: a vertical line at x = 150. - let guide = position(&|s| matches!(s, egui::Shape::LineSegment { points, .. } if points.iter().all(|p| (p.x - 150.0).abs() < 0.01))); - // The box: the closed four-point outline round the layer. - let frame = position(&|s| matches!(s, egui::Shape::Path(p) if p.closed && p.points.len() == 4 && near(Rect::from_points(&p.points)))); - let (Some(preview), Some(guide), Some(frame)) = (preview, guide, frame) else { - panic!("all painted: preview {preview:?}, guide {guide:?}, box {frame:?}"); - }; - assert!(preview < guide, "the guide ({guide}) draws over the transform preview ({preview})"); - assert!(guide < frame, "the box ({frame}) draws over the guide ({guide})"); - } - - #[test] - fn guides_draw_over_the_puppet_perspective_and_vanishing_point_previews() { - // #7781: like Free Transform's (#5086), the warped pixels of Puppet Warp and Perspective - // Warp and Vanishing Point's paste are image content. They were drawn with their pins and - // planes, after the guides, hiding every guide across them; the guides now go over them, - // the mesh lines, pins and planes over the guides, as in Photoshop. - for command in ["edit.puppetWarp", "edit.perspectiveWarp", photocraft_engine::vp_cmds::VP] { - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - if command == photocraft_engine::vp_cmds::VP { - app.run("edit.copy", json!({})).unwrap(); - } - app.run("select.deselect", json!({})).unwrap(); - app.run("view.newGuide", json!({"orientation": "vertical", "position": 150})).unwrap(); - app.ui.extras.guides = true; - app.ui.extras.rulers = false; - app.sync_views(); - crate::distort_ui::menu(&mut app, &ctx, command, &json!({})).expect("an on-canvas mode").expect("it starts"); - if command == photocraft_engine::vp_cmds::VP { - // A plane over the document; the clipboard pastes onto it. - for (x, y) in [(20.0, 280.0), (380.0, 280.0), (300.0, 40.0), (100.0, 40.0)] { - crate::distort_ui::pointer(&mut app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE); - crate::distort_ui::pointer(&mut app, ToolEvent::Up { x, y }, egui::Modifiers::NONE); - } - } else if command == "edit.perspectiveWarp" { - // One plane, dragged out across the guide. - crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 60.0, y: 70.0, pressure: 1.0 }, egui::Modifiers::NONE); - crate::distort_ui::pointer(&mut app, ToolEvent::Move { x: 240.0, y: 190.0, pressure: 1.0 }, egui::Modifiers::NONE); - crate::distort_ui::pointer(&mut app, ToolEvent::Up { x: 240.0, y: 190.0 }, egui::Modifiers::NONE); - assert_eq!(app.distort.perspective.as_ref().map(|s| s.planes.len()), Some(1), "the drag makes a plane"); - } - let mut view = app.ui.views[0].clone(); - view.zoom = 1.0; - view.center = [200.0, 150.0]; - view.fit_pending = false; - view.fill_pending = false; - let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); - let input = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| { - canvas_view(&mut app, ui, 0, rect, view.clone(), true); - }); - out.textures_delta.clear(); - // At 100 % centred on the document, screen and document coordinates coincide. - let layer = Rect::from_min_max(pos2(100.0, 100.0), pos2(200.0, 160.0)); - // Puppet Warp's mesh reaches its Expansion (2 px) past the pixels. - let near = |r: Rect| (r.min - layer.min).length() < 4.0 && (r.max - layer.max).length() < 4.0; - let shapes: Vec<&egui::Shape> = out.shapes.iter().map(|s| &s.shape).collect(); - // The warped pixels (or the paste): a textured mesh over the layer (or on the plane, - // well inside the document, unlike the checkerboard and document image). - let preview = shapes.iter().position(|s| match s { - egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => { - let r = m.calc_bounds(); - if command == photocraft_engine::vp_cmds::VP { - r.width() > 10.0 && r.width() < 300.0 && r.min.x < 150.0 && r.max.x > 150.0 - } else { - near(r) - } - } - _ => false, - }); - // The guide: a vertical line at x = 150 across the whole view. - let is_guide = |s: &egui::Shape| matches!(s, egui::Shape::LineSegment { points, .. } if points.iter().all(|p| (p.x - 150.0).abs() < 0.01) && (points[1].y - points[0].y).abs() > 200.0); - let guide = shapes.iter().position(|s| is_guide(s)); - // Over the guide: Puppet Warp's mesh lines, the Vanishing Point plane's outline, the - // Perspective Warp plane's outline (exactly the dragged rectangle). - let plane = Rect::from_min_max(pos2(60.0, 70.0), pos2(240.0, 190.0)); - let overlay = shapes.iter().position(|s| match s { - egui::Shape::LineSegment { points, .. } => { - command != "edit.perspectiveWarp" && !is_guide(s) && points.iter().all(|p| layer.expand(3.0).contains(*p)) - } - egui::Shape::Path(p) => { - p.closed - && p.points.len() == 4 - && (command != "edit.perspectiveWarp" - || (Rect::from_points(&p.points).min - plane.min).length() + (Rect::from_points(&p.points).max - plane.max).length() < 0.5) - } - _ => false, - }); - let (Some(preview), Some(guide)) = (preview, guide) else { - panic!("{command}: all painted: preview {preview:?}, guide {guide:?}"); - }; - assert!(preview < guide, "{command}: the guide ({guide}) draws over the warped pixels ({preview})"); - let Some(overlay) = overlay else { panic!("{command}: its mesh or plane is drawn") }; - assert!(guide < overlay, "{command}: the mesh or plane ({overlay}) draws over the guide ({guide})"); - } - } - - #[test] - fn brush_drags_paint_no_stand_in_shape_over_the_canvas() { - // #189: v0.1 drew the stroke being dragged as a foreground-coloured egui polyline as wide - // as the brush; zoomed in, egui tessellated it into hard black wedges fanning out from the - // start. The canvas shows the real stroke (`LiveStroke`) and nothing is drawn over it. - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 30, "hardness": 0.0}})).unwrap(); - // A smoothed stroke also draws its string line (see - // `smoothed_brush_drag_draws_the_string_from_brush_to_pointer`): that is no stand-in shape. - let overlay = |app: &mut PhotocraftApp, ctx: &egui::Context| { - drag_preview_shapes(app, ctx, 12.0).iter().filter(|s| !matches!(s.shape, egui::Shape::LineSegment { .. } | egui::Shape::Circle(_))).count() - }; - for tool in [Tool::Brush, Tool::Eraser] { - app.ui.tool = tool; - let idle = overlay(&mut app, &ctx); - tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); - for i in 1..40 { - let t = f64::from(i); - tool_event(&mut app, ToolEvent::Move { x: 20.0 + t, y: 30.0 + (t / 3.0).sin() * 4.0, pressure: 1.0 }, egui::Modifiers::NONE); - } - assert!(app.live_stroke.is_some(), "{tool:?}: the canvas shows the live stroke"); - assert_eq!(overlay(&mut app, &ctx), idle, "{tool:?}: no overlay while dragging"); - tool_event(&mut app, ToolEvent::Up { x: 59.0, y: 30.0 }, egui::Modifiers::NONE); - } - } - - #[test] - fn smoothed_brush_drag_draws_the_string_from_brush_to_pointer() { - // #3479: with smoothing the brush lags behind the pointer; a line joins them while drawing. - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); - app.ui.tool = Tool::Brush; - let lines = |app: &mut PhotocraftApp| drag_preview_shapes(app, &ctx, 4.0).iter().filter(|s| matches!(s.shape, egui::Shape::LineSegment { .. })).count(); - for (amount, string) in [(0.0, false), (0.8, true)] { - app.run("tools.setBrush", json!({"brush": {"size": 10, "smoothing": {"amount": amount}}})).unwrap(); - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); - for x in [30.0, 60.0, 90.0] { - tool_event(&mut app, ToolEvent::Move { x, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); - } - assert_eq!(lines(&mut app) > 0, string, "smoothing {amount}"); - tool_event(&mut app, ToolEvent::Up { x: 90.0, y: 30.0 }, egui::Modifiers::NONE); - } - } - - #[test] - fn retouch_drags_show_the_footprint_without_wedges() { - // The retouching tools' trail was the same brush-wide polyline (#189): now a mask of the - // footprint, with nothing outside the brush radius of the path, however small the steps. - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 30}})).unwrap(); - // Remove: the dab tools draw their stroke live instead of a trail, and Spot Healing's - // trail is its dabs' coverage. - app.ui.tool = Tool::Remove; - tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); - let mut pts = vec![[20.0, 30.0]]; - for i in 1..80 { - let t = f64::from(i) * 0.5; - let p = [20.0 + t, 30.0 + (t / 2.0).sin() * 3.0]; - tool_event(&mut app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }, egui::Modifiers::NONE); - pts.push(p); - if i % 20 == 0 { - // One mesh for the trail, however long the drag. - let shapes = drag_preview_shapes(&mut app, &ctx, 12.0); - assert!(!shapes.iter().any(|s| matches!(s.shape, egui::Shape::Path(_))), "no polyline"); - } - } - drag_preview_shapes(&mut app, &ctx, 12.0); - let trail = app.trail.as_ref().unwrap(); - assert_eq!(trail.scale(), 1.0); - for y in 0..60 { - for x in 0..120 { - let d = pts.iter().map(|p| (x as f64 + 0.5 - p[0]).hypot(y as f64 + 0.5 - p[1])).fold(f64::MAX, f64::min); - if d < 14.0 { - assert_eq!(trail.coverage(x, y), 255, "({x}, {y}) inside the footprint"); - } else if d > 16.0 { - assert_eq!(trail.coverage(x, y), 0, "({x}, {y}) outside the footprint"); - } - } - } - tool_event(&mut app, ToolEvent::Up { x: 59.5, y: 30.0 }, egui::Modifiers::NONE); - drag_preview_shapes(&mut app, &ctx, 12.0); - assert!(app.trail.is_none(), "the trail ends with the drag"); - } - - #[test] - fn spot_healing_trail_is_the_coverage_the_heal_uses() { - // #2364: a soft brush with pen-pressure size showed as a hard footprint at full size. - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); - let brush = json!({"size": 30, "hardness": 0.0, "shapeDynamics": {"enabled": true, "size": {"control": "penPressure"}}}); - app.run("tools.setBrush", json!({ "brush": brush })).unwrap(); - app.ui.tool = Tool::SpotHealing; - tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 0.5 }, egui::Modifiers::NONE); - for x in [40.0, 60.0, 80.0] { - tool_event(&mut app, ToolEvent::Move { x, y: 30.0, pressure: 0.5 }, egui::Modifiers::NONE); - drag_preview_shapes(&mut app, &ctx, 12.0); - } - // The stroke the heal gets on release, and its coverage. - let points = app.drag.as_ref().unwrap().points.iter().map(|p| photocraft_paint::StrokePoint::new(p[0], p[1], p[2] as f32)).collect(); - let brush = photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &json!({})); - let (b, cov) = photocraft_paint::retouch::stroke_coverage(&photocraft_paint::Stroke { brush, points }); - let trail = app.trail.as_ref().unwrap(); - let mut soft = 0; - for y in 0..60 { - for x in 0..120 { - let want = if b.contains(x, y) { cov[(y - b.y0) as usize * b.width() as usize + (x - b.x0) as usize] } else { 0.0 }; - let got = trail.coverage(x as usize, y as usize); - assert!((f32::from(got) - want * 255.0).abs() <= 1.0, "({x}, {y}): trail {got}, heal {want}"); - soft += usize::from(got > 0 && got < 200); - } - } - assert!(soft > 50, "a soft brush shows a soft edge"); - // Half pressure halves the 30 px tip: nothing past its (soft) reach. - let reach = photocraft_paint::tip_reach(7.5, app.session.tools.brush.hardness).ceil() as usize + 2; - assert_eq!(trail.coverage(50, 30 + reach), 0, "half pressure halves the 30 px tip"); - } - - #[test] - fn layer_style_dialog_previews_live_and_cancel_restores() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - let fx = |d: &Document| d.layers.iter().map(|l| l.effects.items.len()).sum::(); - let id = crate::layer_style::open(&mut app, Some("colorOverlay")).unwrap(); - let (shown, key) = display_doc(&mut app, 0); - assert_eq!((fx(&shown), fx(&app.session.documents()[0].doc)), (1, 0), "previewed, not committed"); - // Adding a stroke through the dialog's instance list re-renders the canvas. - if let Some(d) = app.ui.dialog_mut(id) { - d.fields["effects"].as_array_mut().unwrap().push(json!({"id": "fx9", "kind": "stroke", "on": true, "params": {"size": 3}})); - } - let (shown, key2) = display_doc(&mut app, 0); - assert_eq!(fx(&shown), 2); - assert_ne!(key, key2, "an edit re-renders the canvas"); - app.ui.close_dialog(id); - let (shown, key) = display_doc(&mut app, 0); - assert_eq!((fx(&shown), key), (0, 0)); - assert!(app.style_preview.is_none()); - } - - /// Layer Style opened while Free Transform is open applies the box first, as Photoshop does, - /// so the dialog previews on the transformed layer (#4821): a dropped file (placed in the box, - /// untouched) and a box opened by hand and moved. - #[test] - fn layer_style_opened_during_free_transform_applies_the_box_and_previews() { - for placed in [true, false] { - 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("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); - app.run("edit.fill", json!({"color": "#0000ff"})).unwrap(); - app.run("select.deselect", json!({})).unwrap(); - app.sync_views(); - let ctx = egui::Context::default(); - let dx = if placed { - crate::transform_tool::begin_placed(&mut app, &ctx).unwrap(); - 0 - } else { - crate::transform_tool::begin(&mut app, &ctx).unwrap(); - app.ui.transform.as_mut().unwrap().quad = [[28.0, 8.0], [44.0, 8.0], [44.0, 24.0], [28.0, 24.0]]; - 20 - }; - crate::layer_style::open(&mut app, Some("dropShadow")).unwrap(); - assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "placed {placed}: the box is applied"); - let (shown, _) = display_doc(&mut app, 0); - let rect = photocraft_geom::Rect::new(0, 0, 64, 64); - let with = photocraft_compose::render(&shown, rect); - let without = photocraft_compose::render(&app.session.documents()[0].doc, rect); - assert!( - with.get(16 + dx, 16)[0] < 0.1 && with.get(16 + dx, 16)[2] > 0.9, - "placed {placed}: the blue block where the box left it, not the white under it" - ); - // The shadow darkens the white around the block, which the document doesn't have yet. - let block = |x: i32, y: i32| (8 + dx..24 + dx).contains(&x) && (8..24).contains(&y); - let shadow = - (0..64).flat_map(|y| (0..64).map(move |x| (x, y))).filter(|&(x, y)| !block(x, y) && without.get(x, y)[0] - with.get(x, y)[0] > 0.05).count(); - assert!(shadow > 20, "placed {placed}: the Drop Shadow is previewed ({shadow} px)"); - } - } - - #[test] - fn fill_view_covers_the_canvas_and_centres_the_document() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); - let doc = app.session.active().unwrap().doc.clone(); - let mut view = View { fill_pending: true, ..View::default() }; - - fill_view(&mut view, &doc, vec2(600.0, 600.0), 1.0, 1.0); - - assert_eq!(view.zoom, 3.0, "the short edge fills the available height"); - assert_eq!(view.center, [200.0, 100.0]); - assert!(!view.fill_pending); - - // A scaled display stores the physical factor: the same point zoom is 2× the device px. - let mut view = View { fill_pending: true, ..View::default() }; - fill_view(&mut view, &doc, vec2(600.0, 600.0), 2.0, 1.0); - assert_eq!(view.zoom, 6.0); - - // Fit never magnifies past 100% = one image pixel per physical pixel, at any display - // scale (it used to cap at one per *point*, so a 150% display opened images at 150%). - for ppp in [1.0f32, 1.5, 2.0] { - let mut view = View { fit_pending: true, ..View::default() }; - fit_view(&mut view, &doc, vec2(600.0, 600.0), ppp, 1.0); - assert_eq!(view.zoom, 1.0, "ppp {ppp}: a small image opens at 100%"); - } - // A large image still shrinks to fit: 1000×500 into 440 points is 0.44 pt/px, so 0.66 - // physical at ppp 1.5. - let big = { - app.run("file.new", json!({"width": 1000, "height": 500})).unwrap(); - app.session.active().unwrap().doc.clone() - }; - let mut view = View { fit_pending: true, ..View::default() }; - fit_view(&mut view, &big, vec2(480.0, 480.0), 1.5, 1.0); - assert!((view.zoom - 0.66).abs() < 1e-5, "{}", view.zoom); - } - - #[test] - fn a_hundred_percent_is_one_physical_pixel_per_document_pixel() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); - app.sync_views(); - for ppp in [1.0f32, 1.25, 2.0] { - app.ppp = ppp; - let xf = ViewXform::active(&app).unwrap(); - // 100% zoom: one document pixel is one physical pixel, i.e. 1/ppp egui points. - let step = xf.to_screen(1.0, 0.0) - xf.to_screen(0.0, 0.0); - // `to_screen` differences around the view centre cancel in f32; 1e-3 is still exact - // enough to see a wrong ppp factor (which would be a 20–100% error). - assert!((step.x - 1.0 / ppp).abs() < 1e-3, "ppp {ppp}: {step:?} want {:?}", 1.0 / ppp); - assert!((app.point_zoom() - 1.0 / ppp).abs() < 1e-5, "ppp {ppp}: {}", app.point_zoom()); - // Screen ↔ document stays an exact round trip. - let back = xf.to_doc(xf.to_screen(123.0, 45.0)); - assert!((back[0] - 123.0).abs() < 1e-3 && (back[1] - 45.0).abs() < 1e-3, "ppp {ppp}: {back:?}"); - } - } - - #[test] - fn wheel_anchor_is_the_pointer_over_the_image_and_the_nearest_image_point_off_it() { - let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); - for (rotation, flip) in [(0.0, false), (30.0, false), (90.0, true)] { - let xf = ViewXform { rect, zoom: 0.5, center: [400.0, 300.0], flip, rotation, aspect: 1.0 }; - let inside = xf.to_screen(100.0, 200.0); - assert_eq!(wheel_anchor(&xf, inside, [800, 600]), inside); - for (p, want) in [((-300.0, -200.0), [0.0, 0.0]), ((1200.0, 300.0), [800.0, 300.0]), ((400.0, 900.0), [400.0, 600.0])] { - let a = xf.to_doc(wheel_anchor(&xf, xf.to_screen(p.0, p.1), [800, 600])); - assert!((a[0] - want[0]).abs() < 0.01 && (a[1] - want[1]).abs() < 0.01, "rot {rotation}: {p:?} -> {a:?}"); - } - } - let p = pos2(5.0, 5.0); - let xf = ViewXform { rect, zoom: 1.0, center: [400.0, 300.0], flip: false, rotation: 0.0, aspect: 1.0 }; - assert_eq!(wheel_anchor(&xf, p, [0, 0]), p, "no document: the pointer"); - } - - #[test] - fn zoom_about_centres_the_clicked_point_with_the_preference() { - let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); - let p = pos2(600.0, 200.0); - for ppp in [1.0f32, 2.0] { - // `View::zoom` is physical; the transform works in points. - let xf = ViewXform { rect, zoom: 1.0 / ppp, center: [400.0, 300.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let doc = xf.to_doc(p); - // Off: the document point under the pointer stays under it. - let mut view = View { zoom: 1.0, center: [400.0, 300.0], ..Default::default() }; - zoom_about(&mut view, &xf, p, 2.0, false, ppp); - let after = ViewXform { rect, zoom: 2.0 / ppp, center: view.center, flip: false, rotation: 0.0, aspect: 1.0 }; - let s = after.to_screen(doc[0] as f32, doc[1] as f32); - assert!((s - p).length() < 0.5, "ppp {ppp}: {s:?} vs {p:?}"); - // On: the clicked point is the view centre. - let mut view = View { zoom: 1.0, center: [400.0, 300.0], ..Default::default() }; - zoom_about(&mut view, &xf, p, 2.0, true, ppp); - assert!((view.center[0] - doc[0] as f32).abs() < 0.5, "ppp {ppp}: {:?}", view.center); - assert!((view.center[1] - doc[1] as f32).abs() < 0.5, "ppp {ppp}: {:?}", view.center); - } - } - - #[test] - fn damage_grows_by_nested_effect_reach() { - use photocraft_doc::{Effect, Layer}; - let fmt = photocraft_color::PixelFormat::RGBA8; - assert_eq!(effect_reach(&[Layer::raster("plain", fmt)]), 0); - let mut inner = Layer::raster("inner", fmt); - inner.effects.items.push(Effect::default_drop_shadow()); - let m = photocraft_compose::effects::margin(&inner); - let mut group = Layer::group("g", vec![inner.clone()]); - group.effects.items.push(Effect::default_drop_shadow()); - assert_eq!(effect_reach(std::slice::from_ref(&inner)), m); - // A child's edit moves the group's shape, whose effects reach further. - assert_eq!(effect_reach(&[group.clone()]), 2 * m); - group.visible = false; - assert_eq!(effect_reach(&[group]), 0); - } -} +mod tests; #[cfg(test)] mod transform_controls_tests { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs new file mode 100644 index 0000000000..1036161ad5 --- /dev/null +++ b/crates/ui-egui/src/canvas/tests.rs @@ -0,0 +1,2910 @@ +/// #5472: a ⇧ square pressed between pixels snapped to 101 × 102; the short side grows to +/// match, on the side the drag points to. +#[test] +fn square_px_equalises_the_sides_away_from_the_press_point() { + use super::{marquee_px, square_px}; + // Down-right drag: the continuous square (50.3, 50.7)..(150.8, 151.2) snaps unevenly. + let r = marquee_px([50.3, 50.7], [150.8, 151.2]); + assert_eq!(r, [50.0, 50.0, 151.0, 152.0], "uneven before the fix"); + assert_eq!(square_px(r, [50.3, 50.7], [150.8, 90.0]), [50.0, 50.0, 152.0, 152.0]); + // Up-left drag: the short side grows towards lower coordinates. + let r = marquee_px([150.8, 151.2], [50.3, 50.7]); + assert_eq!(square_px(r, [150.8, 151.2], [60.0, 50.7]), [49.0, 50.0, 151.0, 152.0]); + // Already square: unchanged. + assert_eq!(square_px([10.0, 20.0, 30.0, 40.0], [10.0, 20.0], [30.0, 40.0]), [10.0, 20.0, 30.0, 40.0]); +} + +/// #6015: a Fixed Size marquee pressed between pixels selected one pixel more on each side. +#[test] +fn fixed_size_px_is_exactly_the_size() { + use super::fixed_size_px; + // Down-right from (10.4, 20.6): 10 × 10 from the closest pixel edges. + assert_eq!(fixed_size_px([10.4, 20.6], [20.4, 30.6], 10.0, 10.0), [10.0, 21.0, 20.0, 31.0]); + // Up-left: the far corner is the low one; still exactly the size. + assert_eq!(fixed_size_px([10.4, 20.6], [-53.6, -11.4], 64.0, 32.0), [-54.0, -11.0, 10.0, 21.0]); + // 1 × 1 is one pixel, and a fractional size rounds to whole pixels. + assert_eq!(fixed_size_px([3.5, 3.5], [4.5, 4.5], 1.0, 1.0), [4.0, 4.0, 5.0, 5.0]); + assert_eq!(fixed_size_px([0.0, 0.0], [2.6, 2.4], 2.6, 2.4), [0.0, 0.0, 3.0, 2.0]); +} + +#[test] +fn display_image_matches_egui_unmultiplied_conversion() { + // Several parallel pieces and a ragged one; translucent, out-of-range and NaN values. + let n: usize = 3 * 16 * 1024 + 77; + let px: Vec<[f32; 4]> = (0..n) + .map(|i| { + let v = match i % 9 { + 0 => f32::NAN, + 1 => -0.5, + 2 => 3.25, + _ => (i % 1001) as f32 / 1000.0, + }; + [v, (i % 257) as f32 / 256.0, 1.0 - (i % 113) as f32 / 112.0, (i % 6) as f32 / 5.0] + }) + .collect(); + let buf = photocraft_compose::Buffer { rect: photocraft_geom::Rect::new(0, 0, n as i32, 1), px }; + let reference = |img: photocraft_raster::Rgba8Image| egui::ColorImage::from_rgba_unmultiplied([img.width as usize, img.height as usize], &img.pixels); + assert_eq!(super::display_image(None, &buf).pixels, reference(buf.to_rgba8()).pixels); + let mut doc = photocraft_doc::Document::new("t", photocraft_geom::Size::new(1, 1), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); + doc.icc_profile = Some(photocraft_cms::Builtin::AdobeRgbCompat.profile().to_bytes()); + let mut color = photocraft_engine::color_cmds::ColorState::default(); + color.settings.monitor_profile = "srgb".into(); + let d = color.canvas_display(&doc).unwrap(); + assert!(!d.is_identity()); + assert_eq!(super::display_image(Some(&d), &buf).pixels, reference(d.to_rgba8(&buf)).pixels); +} + +/// #7490: the inline (web) preview path composites and uploads each changed preview once, as +/// the background worker does. It used to flatten and upload it twice and record it twice, +/// so the frame's refresh time counted the preview twice. +/// The CPU canvas (no usable GPU; a flipped or pixel-aspect-corrected view, or a GPU fallback, +/// on a GPU machine) shows a filter dialog's live preview. It showed the document unfiltered. +#[test] +fn the_cpu_canvas_shows_a_filter_dialogs_preview() { + let pixels = |ctx: &egui::Context, id: egui::TextureId| { + let mut delta = ctx.tex_manager().write().take_delta(); + let egui::ImageData::Color(image) = &delta.set.get(&id).and_then(|d| d.last()).expect("the canvas texture was written").image; + let (size, px) = (image.size, image.pixels.clone()); + delta.clear(); + (size, px) + }; + for (size, zoom) in [([64u32, 48u32], 1.0f32), ([2400, 2200], 0.25)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": size[0], "height": size[1], "background": "white"})).unwrap(); + app.run("edit.fill", json!({"color": "#3399cc"})).unwrap(); + app.ui.views.get_mut(0).expect("the view").zoom = zoom; + let ctx = egui::Context::default(); + let (tex, _) = ensure_texture(&mut app, &ctx, 0, None).unwrap(); + let (_, plain) = pixels(&ctx, tex); + crate::filter_dialog::open(&mut app, "filter.stylize.solarize").unwrap(); + let (tex, _) = ensure_texture(&mut app, &ctx, 0, None).unwrap(); + let (tex_size, shown) = pixels(&ctx, tex); + let preview = app.filter_preview.as_ref().and_then(|p| p.result.clone()).expect("the dialog's preview"); + let (display, _) = canvas_display(&app, &preview, None); + let expected = display_image(display.as_deref(), &photocraft_compose::flatten(&preview)); + assert_eq!(tex_size, expected.size, "{size:?}: the preview's own size (a proxy when zoomed out)"); + assert_eq!(shown, expected.pixels, "{size:?}: the canvas shows the preview"); + assert_ne!(shown.first(), plain.first(), "{size:?}: not the unfiltered document"); + } + // A preview that changes the canvas's dimensions covers its own area, centred on the + // document's (as the GPU canvas centres it), rather than being stretched over it. + let size = |w, h| photocraft_geom::Size::new(w, h); + assert_eq!(preview_bounds(size(64, 32), size(64, 32), 1), DRect::new(0, 0, 64, 32)); + assert_eq!(preview_bounds(size(2401, 2200), size(1201, 1100), 2), DRect::new(0, 0, 2401, 2200), "a proxy"); + assert_eq!(preview_bounds(size(64, 32), size(32, 64), 1), DRect::new(16, -16, 48, 48), "rotated"); + assert_eq!(preview_bounds(size(64, 32), size(80, 40), 1), DRect::new(-8, -4, 72, 36), "canvas grown"); + assert_eq!(preview_bounds(size(4000, 2000), size(1000, 2000), 2), DRect::new(1000, -1000, 3000, 3000), "a rotated proxy"); + + // Image › Image Rotation › Arbitrary 90° on a 64×32 document: its 32×64 preview is drawn over + // the centred 32×64 area. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap(); + let id = crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap(); + let d = app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap(); + d.fields.insert("angle".into(), json!(90.0)); + d.fields.insert("__preview".into(), json!(true)); + let ctx = egui::Context::default(); + let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap(); + let (size, _) = pixels(&ctx, t.texture); + assert_eq!(size, [32, 64], "the rotated preview's texture"); + assert_eq!(t.bounds, DRect::new(16, -16, 48, 48), "centred on the document"); + let centre = |r: DRect| (r.x0 + r.x1, r.y0 + r.y1); + assert_eq!(centre(t.bounds), centre(app.session.active().unwrap().doc.bounds()), "the same centre, so the view's pan holds"); + // Preview off, then Cancel: the document again, unchanged. + let revision = app.session.active().unwrap().revision; + app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap().fields.insert("__preview".into(), json!(false)); + let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap(); + assert_eq!(t.bounds, DRect::new(0, 0, 64, 32), "Preview off"); + crate::dialogs::cancel(&mut app, id).unwrap(); + let t = ensure_texture_in_view(&mut app, &ctx, 0, None, None).unwrap(); + assert_eq!(t.bounds, DRect::new(0, 0, 64, 32), "after Cancel"); + assert_eq!(app.session.active().unwrap().revision, revision, "the document untouched"); + assert_eq!(app.session.active().unwrap().doc.size, photocraft_geom::Size::new(64, 32)); +} + +/// A channel overlay drawn from a size-changing preview covers the preview's own area, as the +/// image does, not the document's: a 90° rotation of a 64×32 document shows a 32×64 overlay. +#[test] +fn a_channel_overlay_follows_a_size_changing_preview() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap(); + app.run("channel.new", json!({"name": "Alpha", "fill": "black"})).unwrap(); + let id = crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap(); + let d = app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap(); + d.fields.insert("angle".into(), json!(90.0)); + d.fields.insert("__preview".into(), json!(true)); + let ctx = egui::Context::default(); + for rotation in [0.0f32, 30.0] { + let view = View { zoom: 4.0, center: [32.0, 16.0], rotation, ..app.ui.views[0].clone() }; + let mut output = ctx.run_ui(Default::default(), |ui| { + canvas_view(&mut app, ui, 0, Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), view.clone(), true); + }); + output.textures_delta.clear(); + let overlay = crate::channel_view::ensure(&mut app, &ctx, 0).expect("the channel overlay"); + let mesh = output + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Mesh(m) if m.texture_id == overlay => Some(m.clone()), + _ => None, + }) + .expect("the overlay is painted"); + // The quad's sides, in screen points: the two shortest distances from a corner (the + // third is the diagonal; a rotated view turns the quad, not its side lengths). + let v: Vec = mesh.vertices.iter().map(|v| v.pos).collect(); + let mut d: Vec = v[1..4].iter().map(|p| v[0].distance(*p)).collect(); + d.sort_by(f32::total_cmp); + let (short, long) = (d[0], d[1]); + // Which side is the width: the one along the view's x axis turned by the rotation. + let along = |p: Pos2| { + let r = rotation.to_radians(); + ((p - v[0]).x * r.cos() + (p - v[0]).y * r.sin()).abs() + }; + let width = v[1..4].iter().map(|p| along(*p)).fold(0.0f32, f32::max); + assert!((long / short - 2.0).abs() < 0.01, "rotation {rotation}: sides {short}×{long}, the preview's 1:2"); + assert!((width - short).abs() < 0.5, "rotation {rotation}: the short side ({short}) runs across the view (width {width})"); + } +} + +#[test] +fn inline_filter_preview_is_composited_and_recorded_once() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); + crate::filter_dialog::open(&mut app, "filter.stylize.solarize").unwrap(); + app.perf.frame_refresh_ms = 0.0; + let (_, _, size) = ensure_filter_preview(&mut app, 0, &egui::Context::default()).expect("a preview"); + assert_eq!(size, [320, 240]); + assert_eq!(app.perf.last_refresh, "filter-preview"); + assert_eq!(app.perf.last_refresh_px, 320 * 240); + assert_eq!(app.perf.frame_refresh_ms, app.perf.composite_ms + app.perf.upload_ms, "one record per preview"); + // Unchanged request: nothing is recomputed or recorded again. + ensure_filter_preview(&mut app, 0, &egui::Context::default()).expect("the same preview"); + assert_eq!(app.perf.frame_refresh_ms, app.perf.composite_ms + app.perf.upload_ms); +} + +/// #6326: a filter's live preview is never coarser than the screen. On a document big enough +/// for a reduced proxy, the view at 100 % previews at full resolution, and only a view zoomed +/// out far enough uses the proxy. Through `ensure_filter_preview`, so the factor the canvas +/// actually requests is the one under test. +#[test] +fn filter_preview_at_100_percent_is_full_resolution() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 2400, "height": 2200})).unwrap(); + assert_eq!(crate::proxy::preview_factor(&app.session.active().unwrap().doc, true), 2, "big enough for a proxy"); + crate::filter_dialog::open(&mut app, "filter.stylize.solarize").unwrap(); + let ctx = egui::Context::default(); + let preview_at = |app: &mut PhotocraftApp, zoom: f32| { + app.ui.views.get_mut(0).expect("the new document's view").zoom = zoom; + assert_eq!(app.current_zoom(), zoom); + let (k, _, size) = ensure_filter_preview(app, 0, &ctx).expect("a preview"); + (k, size) + }; + assert_eq!(preview_at(&mut app, 1.0), (1, [2400, 2200]), "100 %: every pixel"); + assert_eq!(preview_at(&mut app, 0.25), (2, [1200, 1100]), "zoomed out: the document's proxy"); + // Low Resolution Previews off: full resolution at any zoom, exactly as before #6326. + app.run("prefs.set", json!({"path": "performance.lowResolutionPreviews", "value": false})).unwrap(); + assert_eq!(preview_at(&mut app, 0.25), (1, [2400, 2200]), "the preference still decides"); +} + +/// The factor itself over the zoom range, and that Preferences › Performance › Low +/// Resolution Previews still decides whether there is a proxy at all (#6326). +#[test] +fn filter_preview_factor_caps_at_the_view_without_overriding_the_preference() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + // 9 MP: reduced previews halve it (empty tiles, so nothing is allocated). + app.run("file.new", json!({"width": 3000, "height": 3000, "background": "transparent"})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let params = json!({"amount": 100, "radius": 4.0, "threshold": 0}); + let k = |app: &mut PhotocraftApp, zoom: f32| { + app.ui.views.get_mut(0).expect("the new document's view").zoom = zoom; + super::filter_preview_factor(app, &doc, "filter.sharpen.unsharpMask", ¶ms) + }; + assert_eq!(k(&mut app, 0.25), 2, "zoomed out the preview stays reduced"); + assert_eq!(k(&mut app, 0.5), 2); + assert_eq!(k(&mut app, 0.75), 1, "past the proxy's resolution it shows every pixel"); + assert_eq!(k(&mut app, 1.0), 1); + assert_eq!(k(&mut app, 4.0), 1); + // A corrupt or unset zoom must not pick a coarser proxy than the document's own. + assert_eq!(k(&mut app, f32::NAN), 1); + assert_eq!(k(&mut app, 0.0), 1); + // Low Resolution Previews off: full resolution at any zoom, the cap a no-op. + app.run("prefs.set", json!({"path": "performance.lowResolutionPreviews", "value": false})).unwrap(); + for zoom in [0.1, 0.25, 1.0, 4.0] { + assert_eq!(k(&mut app, zoom), 1, "zoom {zoom}"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn every_filter_previews_off_the_ui_thread_and_a_newer_value_cancels_the_old() { + // Dragging Gaussian Blur's radius to 1000 px froze the window: the preview ran inline in + // the frame, and every slider step waited for the previous blur to finish. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.background_jobs = true; + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let ctx = egui::Context::default(); + let wait_for = |app: &mut PhotocraftApp, radius: f64| { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while app.filter_preview.as_ref().is_none_or(|p| p.key.params["radius"].as_f64() != Some(radius)) { + assert!(std::time::Instant::now() < deadline, "no preview for radius {radius}"); + ensure_filter_preview(app, 0, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + }; + // The first frame hands the blur to the worker and returns. + assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none()); + assert!(app.filter_preview_worker.busy(), "the preview computes on the worker"); + let first = app.ui.dialogs[0].fields["radius"].as_f64().unwrap(); + wait_for(&mut app, first); + assert!(app.filter_preview.as_ref().unwrap().result.is_some()); + + // A preview for old values occupies the worker until it is cancelled. + let st = app.session.active().unwrap(); + let d = &app.ui.dialogs[0]; + let stale = crate::filter_dialog::FilterPreviewKey { + doc: st.doc.id, + revision: st.revision, + dialog: d.id, + active: st.active_layer, + target: st.channel_view.target, + command: "filter.blur.gaussianBlur".into(), + params: json!({"radius": 999.0}), + k: 1, + }; + let (told, cancelled) = std::sync::mpsc::channel(); + app.filter_preview_worker + .start(stale, ctx.clone(), move |job| { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while !job.cancelled() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let _ = told.send(job.cancelled()); + crate::filter_preview_worker::Computed { result: None, ms: 0.0 } + }) + .unwrap(); + // The slider moves on and stops: once the value settles, the stale preview is cancelled + // instead of being waited out. + app.ui.dialogs[0].fields.insert("radius".into(), json!(12.0)); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + let was_cancelled = loop { + ensure_filter_preview(&mut app, 0, &ctx); + if let Ok(c) = cancelled.try_recv() { + break c; + } + assert!(std::time::Instant::now() < deadline, "the stale preview was never cancelled"); + std::thread::sleep(std::time::Duration::from_millis(5)); + }; + assert!(was_cancelled, "the stale preview stopped because it was cancelled, not by timing out"); + wait_for(&mut app, 12.0); + assert!(app.filter_preview.as_ref().unwrap().result.is_some()); +} + +// Starts a worker job that computes a real preview for the dialog as it stands, but only +// finishes when the returned sender is signalled. Gating it here keeps these tests off the +// clock: `supersede` cancels a running job once the values have been still for SETTLE_MS, so a +// test that relies on a real blur beating a 150 ms timer is a test that fails on a loaded box. +#[cfg(not(target_arch = "wasm32"))] +fn gated_blur_preview(app: &mut PhotocraftApp, ctx: &egui::Context) -> (std::sync::mpsc::Sender<()>, f64) { + let d = app.ui.dialogs.first().expect("a dialog is open"); + let st = app.session.active().expect("a document is active"); + let command = "filter.blur.gaussianBlur"; + let params = app.with_mask_target(command, crate::filter_dialog::params_of(&d.fields)); + assert_eq!( + crate::filter_dialog::preview_factor(command, ¶ms, 1), + 1, + "a 64x48 document previews at full resolution, and these tests rely on k staying 1" + ); + let key = crate::filter_dialog::FilterPreviewKey { + doc: st.doc.id, + revision: st.revision, + dialog: d.id, + active: st.active_layer, + target: st.channel_view.target, + command: command.into(), + params, + k: 1, + }; + let doc = app.session.documents()[0].doc.clone(); + let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); + let radius = key.params["radius"].as_f64().expect("the dialog seeds a radius"); + let (release, wait) = std::sync::mpsc::channel::<()>(); + app.filter_preview_worker + .start(key.clone(), ctx.clone(), move |_| { + wait.recv_timeout(std::time::Duration::from_secs(60)).expect("the test releases the job"); + let result = crate::filter_dialog::preview_document_for_target( + &doc, + key.active, + &key.command, + &key.params, + key.k, + None, + key.target, + &documents, + &Default::default(), + ) + .map(|d| { + let buffer = photocraft_compose::flatten(&d); + (std::sync::Arc::new(d), buffer) + }); + crate::filter_preview_worker::Computed { result, ms: 0.0 } + }) + .expect("the worker starts"); + (release, radius) +} + +// The worker hands its result to the channel only after `compute` returns, so a signal sent +// from inside `compute` would still race that send. These tests drive the canvas until the +// state they need appears instead of assuming a timing. +#[cfg(not(target_arch = "wasm32"))] +fn drive_until(app: &mut PhotocraftApp, ctx: &egui::Context, what: &str, done: impl Fn(&PhotocraftApp) -> bool) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !done(app) { + assert!(std::time::Instant::now() < deadline, "timed out waiting for {what}"); + ensure_filter_preview(app, 0, ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_preview_computed_mid_drag_reaches_the_canvas_and_then_converges() { + // A drag used to paint nothing at all: every completion was dropped for carrying stale + // parameters, so the canvas only ever showed an effect once the pointer had come to rest. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.background_jobs = true; + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let ctx = egui::Context::default(); + let (release, first) = gated_blur_preview(&mut app, &ctx); + + // The pointer moves on before the frame lands. + let moved = first + 4.0; + app.ui.dialogs[0].fields.insert("radius".into(), json!(moved)); + release.send(()).expect("released"); + drive_until(&mut app, &ctx, "the mid-drag frame", |a| a.filter_preview.is_some()); + + // The finished frame is painted even though the dialog has moved on. + let shown = app.filter_preview.as_ref().expect("the mid-drag frame was published"); + assert_eq!(shown.key.params["radius"].as_f64(), Some(first), "the frame is the one the worker finished"); + assert!(shown.result.is_some()); + assert_eq!(app.ui.dialogs[0].fields["radius"].as_f64(), Some(moved), "the slider kept moving"); + // The display gate lets it through, so the canvas has something to draw: this is what + // re-adding `params` to that gate would break. + assert!(ensure_filter_preview(&mut app, 0, &ctx).is_some(), "the canvas draws the mid-drag frame"); + + // And the preview still converges on the value the dialog holds. `fresh` has to stay an + // exact match for that: relaxed, the canvas would believe it already had the current + // request after the first frame of a drag and never compute again. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while app.filter_preview.as_ref().is_none_or(|p| p.key.params["radius"].as_f64() != Some(moved)) { + assert!(std::time::Instant::now() < deadline, "the preview never converged on the current radius"); + ensure_filter_preview(&mut app, 0, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_mid_drag_frame_does_not_replace_a_frame_that_is_already_exact() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.background_jobs = true; + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let ctx = egui::Context::default(); + + // A frame for the radius the dialog holds right now reaches the canvas. This also proves + // the hand-built key is the one the canvas builds: it can only be published by the exact + // arm, which requires `finished == request`. + let (release, first) = gated_blur_preview(&mut app, &ctx); + release.send(()).expect("released"); + drive_until(&mut app, &ctx, "the first frame", |a| a.filter_preview.is_some()); + assert_eq!(app.filter_preview.as_ref().expect("published").key.params["radius"].as_f64(), Some(first)); + + // The slider moves away and a frame for the new radius is computed... + let moved = first + 4.0; + app.ui.dialogs[0].fields.insert("radius".into(), json!(moved)); + let (release_moved, _) = gated_blur_preview(&mut app, &ctx); + // ...and back to `first` before that frame lands. + app.ui.dialogs[0].fields.insert("radius".into(), json!(first)); + release_moved.send(()).expect("released"); + + // The frame for `moved` arrives late. It belongs to this preview, but the frame on screen + // is already exact for the dialog, so it must never be shown in place of it. Checked on + // every pass: a wrong frame published and then overwritten before the loop ends would + // otherwise never be seen. + drive_until(&mut app, &ctx, "the late frame to arrive", |a| { + if let Some(shown) = &a.filter_preview { + assert_ne!(shown.key.params["radius"].as_f64(), Some(moved), "a late frame replaced an exact one"); + } + !a.filter_preview_worker.busy() + }); + let shown = app.filter_preview.as_ref().expect("a frame is on screen"); + assert_eq!(shown.key.params["radius"].as_f64(), Some(first), "a late frame replaced an exact one"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_mid_drag_empty_result_leaves_the_preview_alone() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.background_jobs = true; + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let ctx = egui::Context::default(); + + let (release, first) = gated_blur_preview(&mut app, &ctx); + release.send(()).expect("released"); + drive_until(&mut app, &ctx, "the first frame", |a| a.filter_preview.is_some()); + assert!(app.filter_preview.as_ref().expect("published").result.is_some()); + + // The slider moves and a job for the new radius is started, then the slider moves again + // before that job lands: its result is stale by the time it arrives. + let moved = first + 4.0; + app.ui.dialogs[0].fields.insert("radius".into(), json!(moved)); + let d = app.ui.dialogs.first().expect("a dialog is open"); + let st = app.session.active().expect("a document is active"); + let key = crate::filter_dialog::FilterPreviewKey { + doc: st.doc.id, + revision: st.revision, + dialog: d.id, + active: st.active_layer, + target: st.channel_view.target, + command: "filter.blur.gaussianBlur".into(), + params: json!({"radius": moved}), + k: 1, + }; + let (release_empty, wait) = std::sync::mpsc::channel::<()>(); + app.filter_preview_worker + .start(key, ctx.clone(), move |_| { + wait.recv_timeout(std::time::Duration::from_secs(60)).expect("released"); + crate::filter_preview_worker::Computed { result: None, ms: 0.0 } + }) + .expect("the worker starts"); + app.ui.dialogs[0].fields.insert("radius".into(), json!(moved + 4.0)); + release_empty.send(()).expect("released"); + + // Storing an empty result here would drop the canvas back to the unfiltered layer for a + // frame. The exact request may still store one; a stale one may not. Checked on every + // pass, because the reopened preview that follows would otherwise repair the symptom. + drive_until(&mut app, &ctx, "the empty frame to arrive", |a| { + if let Some(shown) = &a.filter_preview { + assert!(shown.result.is_some(), "an empty mid-drag result blanked the canvas"); + } + !a.filter_preview_worker.busy() + }); + assert!(app.filter_preview.as_ref().expect("a preview is still shown").result.is_some(), "an empty mid-drag result blanked the canvas"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_reopened_dialog_never_paints_the_previous_dialogs_preview() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.background_jobs = true; + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let ctx = egui::Context::default(); + let first_dialog = app.ui.dialogs.first().expect("a dialog is open").id; + let (release, _) = gated_blur_preview(&mut app, &ctx); + + // Close that dialog and open another one for the same layer and the same command. Only the + // dialog id differs, which is exactly what `same_target` has to notice. + app.ui.dialogs.clear(); + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let second_dialog = app.ui.dialogs.first().expect("a dialog is open").id; + assert_ne!(second_dialog, first_dialog, "a reopened dialog gets a new id"); + release.send(()).expect("released"); + + // The first dialog's frame arrives late and must not be painted under the second one. + // `discard_closed` usually reclaims it a frame earlier, which is why this drives the gate + // directly: the id check is the part that has to hold when that cleanup misses. The + // invariant is checked on every pass, not only at the end, because a wrongly published + // frame can still be replaced by the reopened dialog's own preview before we stop. + drive_until(&mut app, &ctx, "the first dialog's frame to arrive", |a| { + if let Some(preview) = &a.filter_preview { + assert_ne!(preview.key.dialog, first_dialog, "a reopened dialog painted the previous dialog's preview"); + } + !a.filter_preview_worker.busy() + }); +} + +#[test] +fn windows_uses_a_visible_crosshair() { + // #737: Windows' inverting crosshair vanishes over mid-grey; use a black/white glyph. + let ctx = egui::Context::default(); + let painter = egui::Painter::new(ctx, egui::LayerId::background(), egui::Rect::EVERYTHING); + let p = egui::pos2(10.0, 10.0); + assert_eq!(super::visible_crosshair(egui::CursorIcon::Crosshair, &painter, p, true), egui::CursorIcon::None); + assert_eq!(super::visible_crosshair(egui::CursorIcon::Crosshair, &painter, p, false), egui::CursorIcon::Crosshair); + assert_eq!(super::visible_crosshair(egui::CursorIcon::Move, &painter, p, true), egui::CursorIcon::Move); +} + +use super::*; + +/// #569: displays 1 (sRGB) and 4 (Display P3) side by side, and a document filled with an +/// sRGB colour. +fn app_on_two_displays() -> PhotocraftApp { + use photocraft_engine::color_cmds::resolve_profile; + use photocraft_engine::display_color::Display; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("edit.fill", json!({"color": "#cc8040"})).unwrap(); + let icc = |id: &str| Some(resolve_profile(id, None, None).unwrap().to_bytes()); + app.session.color.set_displays(Ok(vec![ + Display { id: 1, name: "A".into(), frame: [0.0, 0.0, 100.0, 100.0], profile_name: None, icc: icc("srgb") }, + Display { id: 4, name: "B".into(), frame: [100.0, 0.0, 100.0, 100.0], profile_name: None, icc: icc("display-p3") }, + ])); + app +} + +#[test] +#[ignore = "manual texture-retention measurement on six 6 MP documents"] +fn closed_canvas_memory_measurement() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.max_texture_side = 8192); + for cycle in 1..=6 { + app.run("file.new", json!({"width":3000,"height":2000})).unwrap(); + ensure_texture(&mut app, &ctx, 0, None).unwrap(); + // Drain uploaded image deltas just as a renderer does; count live texture owners. + ctx.tex_manager().write().take_delta().clear(); + app.run("file.close", json!({})).unwrap(); + let bytes: usize = ctx.tex_manager().read().allocated().map(|(_, m)| m.bytes_used()).sum(); + println!("closed cycle={cycle} texture_bytes={bytes} rss={:?}", photocraft_testkit::perf::current_rss_bytes()); + } +} + +#[test] +fn closed_documents_release_navigator_but_keep_open_document_textures() { + let mut app = app_on_two_displays(); + let ctx = egui::Context::default(); + let first = app.session.active().unwrap().doc.clone(); + let a = ensure_texture(&mut app, &ctx, 0, Some(1)).unwrap().0; + // The same handle ownership as navigator_texture, without requiring a GPU adapter. + let tex = ctx.load_texture("navigator-test", egui::ColorImage::filled([64, 64], egui::Color32::WHITE), TextureOptions::LINEAR); + let nav = tex.id(); + app.navigator_textures.insert(first.id, (std::sync::Arc::downgrade(&first), 0, 0, tex)); + app.run("file.new", json!({"width":32,"height":32})).unwrap(); + let other = app.session.active().unwrap().doc.id; + let b = ensure_texture(&mut app, &ctx, 1, Some(1)).unwrap().0; + drop(app.session.close(0)); + app.sync_views(); + assert!(ctx.tex_manager().read().meta(a).is_none()); + assert!(ctx.tex_manager().read().meta(nav).is_none()); + assert!(ctx.tex_manager().read().meta(b).is_some()); + assert!(app.canvases.keys().all(|(id, _)| *id == other)); + assert!(app.navigator_textures.is_empty()); + app.session.add_document((*first).clone(), None); + app.sync_views(); + assert_ne!(ensure_texture(&mut app, &ctx, 1, Some(1)).unwrap().0, a, "reopening a preserved ID creates a fresh texture"); +} + +#[test] +fn only_themes_with_a_dot_pattern_tile_the_canvas_surround() { + // #4542: switching to Pro filled the empty workspace with red blocks on one GPU. Pro's + // dots are its canvas colour, so the tiled texture had nothing to show in the first place. + use crate::theme::ThemeKind; + let tiles = |ctx: &egui::Context, kind: ThemeKind| { + crate::theme::apply(ctx, kind); + let mut output = ctx.run_ui(Default::default(), |ui| paint_dots(ui, ui.max_rect(), true)); + output.textures_delta.clear(); + output.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Mesh(_))) + }; + let uploaded = |ctx: &egui::Context| ctx.tex_manager().read().allocated().filter(|(_, meta)| meta.name == "canvas-dots").count(); + for kind in ThemeKind::ALL { + let ctx = egui::Context::default(); + let dotted = matches!(kind, ThemeKind::Studio | ThemeKind::StudioLight | ThemeKind::SolarizedDark); + assert_eq!(tiles(&ctx, kind), dotted, "{kind:?}"); + assert_eq!(uploaded(&ctx), usize::from(dotted), "{kind:?}"); + } + // The reported switch: a dotted theme, then Pro. + let ctx = egui::Context::default(); + assert!(tiles(&ctx, ThemeKind::Studio)); + assert!(!tiles(&ctx, ThemeKind::Pro)); + assert!(!tiles(&ctx, ThemeKind::ProMedium)); + assert_eq!(uploaded(&ctx), 1, "only Studio's dots were uploaded"); +} + +#[test] +fn closed_documents_release_cpu_canvas_textures() { + let mut app = app_on_two_displays(); + let ctx = egui::Context::default(); + let original = app.session.active().unwrap().doc.clone(); + for cycle in 0..12 { + if cycle > 0 { + app.session.add_document((*original).clone(), None); + app.sync_views(); + } + let a = ensure_texture(&mut app, &ctx, 0, Some(1)).unwrap().0; + let b = ensure_texture(&mut app, &ctx, 0, Some(4)).unwrap().0; + assert_ne!(a, b); + app.run("file.close", json!({})).unwrap(); + assert!(app.canvases.is_empty(), "closed canvas metadata retained at cycle {cycle}"); + assert!(ctx.tex_manager().read().meta(a).is_none(), "first display texture retained"); + assert!(ctx.tex_manager().read().meta(b).is_none(), "second display texture retained"); + } +} + +#[test] +fn cpu_canvas_textures_are_per_display() { + // Two windows of one document on different displays: each has its own texture of + // monitor values, and drawing them in turn re-renders neither. + let mut app = app_on_two_displays(); + let ctx = egui::Context::default(); + let id = app.session.documents()[0].doc.id; + let a = ensure_texture(&mut app, &ctx, 0, Some(1)).unwrap().0; + let b = ensure_texture(&mut app, &ctx, 0, Some(4)).unwrap().0; + assert_ne!(a, b); + app.perf.last_refresh = ""; + for _ in 0..3 { + assert_eq!(ensure_texture(&mut app, &ctx, 0, Some(1)).unwrap().0, a); + assert_eq!(ensure_texture(&mut app, &ctx, 0, Some(4)).unwrap().0, b); + } + assert_eq!(app.perf.last_refresh, "", "no re-render"); + let doc = app.session.documents()[0].doc.clone(); + assert!(canvas_display(&app, &doc, Some(1)).0.unwrap().is_identity()); + assert!(!canvas_display(&app, &doc, Some(4)).0.unwrap().is_identity()); + assert_ne!(app.canvases[&(id, 1)].tex_preview_key, app.canvases[&(id, 4)].tex_preview_key); + // An edit updates both. + app.run("edit.fill", json!({"color": "#2060c0"})).unwrap(); + ensure_texture(&mut app, &ctx, 0, Some(1)); + ensure_texture(&mut app, &ctx, 0, Some(4)); + let rev = app.session.documents()[0].revision; + assert_eq!((app.canvases[&(id, 1)].tex_revision, app.canvases[&(id, 4)].tex_revision), (rev, rev)); +} + +#[test] +fn cpu_canvas_shows_crisp_pixels_when_zoomed_in() { + // #4810: above 100% the CPU canvas shows each pixel as a square, like the GPU canvas's + // sharp nearest filter; below 100% it still filters. Both the first upload and a + // damage-rect update carry the sampling, since the renderer takes it from each delta. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 2, "height": 2})).unwrap(); + let ctx = egui::Context::default(); + let tex = ensure_texture(&mut app, &ctx, 0, None).unwrap().0; + let uploads = |ctx: &egui::Context| { + let mut delta = ctx.tex_manager().write().take_delta(); + let seen = delta.set.get(&tex).into_iter().flatten().map(|d| (d.pos.is_some(), d.options)).collect::>(); + delta.clear(); + seen + }; + let crisp = TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR }; + assert_eq!(uploads(&ctx), vec![(false, crisp)]); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap(); + ensure_texture(&mut app, &ctx, 0, None).unwrap(); + uploads(&ctx); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + assert_eq!(ensure_texture(&mut app, &ctx, 0, None).unwrap().0, tex); + assert_eq!(uploads(&ctx), vec![(true, crisp)], "a partial update keeps the crisp sampling"); +} + +/// A device that allows smaller textures than MAX_TEXTURE (2048 on some older GPUs and WebGL +/// contexts, and on the fallback adapter the GPU tests sometimes get under load): the canvas +/// texture is reduced to fit it. A 2600 px document was uploaded at full size, which egui +/// asserts on and the backend can't create. +#[test] +fn cpu_canvas_texture_fits_the_device_limit() { + for (side, (w, h), want) in [(2048, (2600, 1700), [1300, 850]), (2048, (5000, 2000), [1666, 666]), (8192, (5000, 2000), [2500, 1000])] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": w, "height": h})).unwrap(); + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.max_texture_side = side); + let (tex, _) = ensure_texture(&mut app, &ctx, 0, None).unwrap(); + let mut delta = ctx.tex_manager().write().take_delta(); + let sizes: Vec<_> = delta.set.get(&tex).into_iter().flatten().map(|d| d.image.size()).collect(); + delta.clear(); + assert_eq!(sizes, vec![want], "{w}x{h} on a {side} px device"); + } +} + +#[test] +fn cpu_canvas_of_a_reduced_document_stays_bilinear() { + // Over MAX_TEXTURE the texture holds one texel per `factor` pixels: a texel is not a + // document pixel, so showing it as a square would draw blocks that aren't in the image. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": MAX_TEXTURE + 1, "height": 2})).unwrap(); + let ctx = egui::Context::default(); + let (tex, scale) = ensure_texture(&mut app, &ctx, 0, None).unwrap(); + assert!(scale < 1.0); + let mut delta = ctx.tex_manager().write().take_delta(); + let uploads: Vec<_> = delta.set.get(&tex).into_iter().flatten().map(|d| d.options).collect(); + delta.clear(); + assert_eq!(uploads, vec![TextureOptions::LINEAR]); +} + +/// #7568: a document over the texture limit was drawn from one reduced texture, so at 100 % +/// it was magnified and blurred. The view now gets the part in sight at one texel per +/// document pixel, about the window's size, whatever the device's limit. +#[test] +fn cpu_canvas_detail_plan_shows_large_documents_at_full_resolution() { + let size = [12000, 8000]; + // A 1920×1080 view in the middle (`visible_doc_rect` adds 2 px around it). + let screen = DRect::new(4998, 2998, 6922, 4082); + for limit in [16384, 8192, 4096, 2048] { + let side = clamp_texture_side(limit); + assert!(texture_factor(size, side) > 1, "the whole document is reduced on a {limit} px device"); + for zoom in [1.0, 2.0, 8.0] { + let plan = detail_plan(size, side, zoom, screen).unwrap_or_else(|| panic!("{limit} px device at {zoom}")); + assert_eq!(plan.factor, 1, "one texel per document pixel at {zoom} on a {limit} px device"); + assert!(plan.region.contains_rect(&screen), "{plan:?}"); + assert!(plan.region.width() <= 1924 + 2 * 256 && plan.region.height() <= 1084 + 2 * 256, "about the view's size: {plan:?}"); + assert!(plan.region.width() < side && plan.region.height() < side, "{plan:?}"); + } + } + // A small pan reuses the region (no new composite). + assert_eq!(detail_plan(size, 4096, 1.0, screen), detail_plan(size, 4096, 1.0, screen.translate(8, -8))); + // A window wider than a small device's limit coarsens rather than exceed it. + let wide = DRect::new(0, 0, 3000, 2000); + let plan = detail_plan(size, 2048, 1.0, wide).unwrap(); + assert_eq!(plan.factor, 2); + assert!(plan.region.width() / 2 < 2048 && plan.region.contains_rect(&wide), "{plan:?}"); + // Zoomed out a little: finer than the reduced whole, as fine as the screen. + let plan = detail_plan(size, 4096, 0.4, DRect::new(0, 0, 4800, 2700)).unwrap(); + assert_eq!(plan.factor, 2); + // Zoomed out far enough, the reduced whole is as fine as the screen: nothing to add. + let whole = DRect::new(0, 0, 12000, 8000); + assert_eq!(detail_plan(size, 4096, 0.25, whole), None); + assert_eq!(detail_plan(size, 4096, 1.0 / 3.0, whole), None, "a detail as large as the document would not fit"); + // A document that fits is uploaded whole at full resolution. + assert_eq!(detail_plan([4000, 3000], 4096, 1.0, screen), None); + // Nothing of the document in view, or a broken zoom. + assert_eq!(detail_plan(size, 4096, 1.0, DRect::new(-500, -500, -10, -10)), None); + for zoom in [0.0, -1.0, f32::NAN, f32::INFINITY] { + assert_eq!(detail_plan(size, 4096, zoom, screen), None, "{zoom}"); + } + assert_eq!(detail_plan([0, 0], 4096, 1.0, screen), None); + assert_eq!(detail_plan([u32::MAX, 8], 4096, 1.0, screen), None); +} + +#[test] +fn cpu_canvas_detail_shows_a_large_documents_own_pixels_at_100_percent() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 3 * MAX_TEXTURE, "height": 8})).unwrap(); + app.run("select.rect", json!({"x": 101, "y": 0, "width": 1, "height": 8})).unwrap(); + app.run("edit.fill", json!({"color": "#000000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.max_texture_side = 16384); + let uploads = |ctx: &egui::Context, tex: egui::TextureId| { + let mut delta = ctx.tex_manager().write().take_delta(); + let seen: Vec<_> = delta.set.get(&tex).into_iter().flatten().map(|d| (d.pos, d.options, d.image.clone())).collect(); + delta.clear(); + seen + }; + let row = |image: &egui::ImageData| { + let egui::ImageData::Color(image) = image; + (image.size, image.pixels.clone()) + }; + let view = InView { visible: DRect::new(0, 0, 1000, 8), zoom: 1.0, key: 1 }; + let t = ensure_texture_in_view(&mut app, &ctx, 0, None, Some(view)).unwrap(); + assert!(t.scale < 1.0, "the whole document is reduced"); + let (detail, area) = t.detail.expect("a detail texture at 100 %"); + assert_eq!(area, [0.0, 0.0, 1024.0, 8.0]); + let crisp = TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR }; + let up = uploads(&ctx, detail); + assert_eq!(up.len(), 1); + let (pos, options, image) = &up[0]; + assert_eq!((*pos, *options), (None, crisp)); + let (size, px) = row(image); + assert_eq!(size, [1024, 8]); + assert_eq!((px[100], px[101], px[102]), (Color32::WHITE, Color32::BLACK, Color32::WHITE), "the 1 px line stays 1 px"); + // Unchanged: nothing is composited again, and a small pan keeps the region. + let panned = InView { visible: DRect::new(4, 0, 1004, 8), ..view }; + assert_eq!(ensure_texture_in_view(&mut app, &ctx, 0, None, Some(panned)).unwrap().detail, Some((detail, area))); + assert!(uploads(&ctx, detail).is_empty()); + // The Navigator's call (no view) leaves the view's detail alone. + ensure_texture(&mut app, &ctx, 0, None).unwrap(); + assert_eq!(app.canvases.values().map(|c| c.detail.len()).sum::(), 1); + // An edit in view updates just its texels. + app.run("select.rect", json!({"x": 300, "y": 0, "width": 1, "height": 8})).unwrap(); + ensure_texture_in_view(&mut app, &ctx, 0, None, Some(view)).unwrap(); + uploads(&ctx, detail); + app.run("edit.fill", json!({"color": "#000000"})).unwrap(); + assert_eq!(ensure_texture_in_view(&mut app, &ctx, 0, None, Some(view)).unwrap().detail.map(|d| d.0), Some(detail)); + let up = uploads(&ctx, detail); + assert_eq!(up.len(), 1); + let (pos, options, image) = &up[0]; + assert_eq!(*options, crisp); + let [x, y] = pos.expect("a partial update"); + let (size, px) = row(image); + assert!(y == 0 && x < 300 && x + size[0] > 300, "the edit's texels: {x} {size:?}"); + assert_eq!((px[299 - x], px[300 - x]), (Color32::WHITE, Color32::BLACK)); + // Zoomed out, the reduced texture is enough: the detail goes. + let far = InView { zoom: 0.25, ..view }; + assert!(ensure_texture_in_view(&mut app, &ctx, 0, None, Some(far)).unwrap().detail.is_none()); + assert!(app.canvases.values().all(|c| c.detail.is_empty())); +} + +#[test] +fn gpu_display_luts_are_per_display() { + let _gpu = photocraft_testkit::gpu_lock(); + let Ok(rs) = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let mut app = app_on_two_displays(); + app.set_wgpu(rs); + let doc = app.session.documents()[0].doc.clone(); + let key = doc.id.0; + // sRGB on the sRGB display needs no LUT; on the P3 display it does. + assert_eq!(sync_display_lut(&mut app, &doc, key, Some(1)), 0); + assert_eq!(sync_display_lut(&mut app, &doc, key, Some(4)), 3); + let gpu = app.gpu.clone().unwrap(); + let (s1, s4) = (gpu.display_lut_signature(key, 1).unwrap(), gpu.display_lut_signature(key, 4).unwrap()); + assert_ne!(s1.0, s4.0); + assert!(gpu.has_display_lut(key, 4) && !gpu.has_display_lut(key, 1)); + // Drawing one window leaves the other's LUT alone. + for _ in 0..3 { + assert_eq!(sync_display_lut(&mut app, &doc, key, Some(1)), 0); + assert_eq!(sync_display_lut(&mut app, &doc, key, Some(4)), 3); + } + assert_eq!((gpu.display_lut_signature(key, 1), gpu.display_lut_signature(key, 4)), (Some(s1), Some(s4))); + assert!(gpu.has_display_lut(key, 4)); + // The shared texture's key is the same for both displays. + assert_eq!(texture_key(canvas_display(&app, &doc, Some(1)).0.as_deref()), texture_key(canvas_display(&app, &doc, Some(4)).0.as_deref())); +} + +/// The navigator's update after an edit (its image with the edit's damage, grown by the +/// effect reach, rendered over it) equals a new thumbnail of the edited document. +#[test] +fn navigator_damage_updates_match_a_full_thumbnail() { + use photocraft_compose::{render_reduced_damage, thumbnail_buffer, thumbnail_size}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 1500, "height": 900, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 200, "y": 150, "width": 300, "height": 200})).unwrap(); + app.run("edit.fill", json!({"color": "#3070a0"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.run("layer.layerStyle.dropShadow", json!({"distance": 30, "size": 20})).unwrap(); + let steps = [ + ("layer.translate", json!({"dx": 37, "dy": -11})), + ("layer.setProps", json!({"opacity": 0.4})), + ("paint.stroke", json!({"points": [[700, 500], [900, 520]], "size": 25})), + ("layer.setProps", json!({"blend": "Multiply"})), + ("layer.new.layer", json!({})), + ]; + for (id, p) in steps { + let before = app.session.active().unwrap().doc.clone(); + app.run(id, p).unwrap(); + let st = app.session.active().unwrap(); + let d = st.last_damage.unwrap_or_else(|| panic!("{id}: a bounded damage")); + let (w, h) = thumbnail_size(&st.doc, NAVIGATOR_SIDE); + let mut shown = thumbnail_buffer(&before, NAVIGATOR_SIDE); + assert_eq!((shown.rect.width(), shown.rect.height()), (w, h)); + if !d.is_empty() { + let patch = render_reduced_damage(&st.doc, w, h, d.inflate(effect_reach(&st.doc.layers))); + let r = patch.rect; + for y in 0..r.height() as usize { + let at = (r.y0 as usize + y) * w as usize + r.x0 as usize; + shown.px[at..at + r.width() as usize].copy_from_slice(&patch.px[y * r.width() as usize..][..r.width() as usize]); + } + } + assert!(shown.px == thumbnail_buffer(&st.doc, NAVIGATOR_SIDE).px, "{id}: the updated navigator differs from a new thumbnail"); + } +} + +#[test] +fn tab_context_uses_clicked_document_and_existing_close_commands() { + let items = tab_context_items(2, 3, true); + assert_eq!(items.iter().map(|(_, id, _, _)| *id).collect::>(), ["file.close", "file.closeOthers", "file.closeAll", "file.revealInFinder"]); + assert_eq!(items[0].2, json!({"document": 2})); + assert_eq!(items[1].2, json!({"document": 2})); + assert_eq!(items[2].2, json!({})); + assert_eq!(items[3].2, json!({"document": 2})); + assert!(items[3].3, "a saved document can be revealed in the file manager"); + assert!(!tab_context_items(2, 3, false)[3].3, "an unsaved document cannot"); + assert!(!tab_context_items(0, 1, false)[1].3); + assert!(items.iter().all(|(_, id, _, _)| photocraft_engine::commands::find(id).is_some())); +} + +#[test] +fn tab_context_reveal_names_the_platform_file_manager() { + let (label, id, _, _) = &tab_context_items(0, 1, true)[3]; + assert_eq!((*label, *id), (crate::menus::reveal_label(), "file.revealInFinder")); +} + +/// Photoshop's document tab × is after the title on Windows and Linux, before it on macOS (#619). +#[test] +fn document_tab_close_button_sits_on_the_platform_side() { + use egui::os::OperatingSystem as Os; + use egui_kittest::kittest::Queryable; + for (os, after_title) in [(Os::Windows, true), (Os::Nix, true), (Os::Mac, false)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.sync_views(); + // Drawn from the second frame, once the Pro theme is set. + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 40.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + tabs(app, ui); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); + h.ctx.set_os(os); + h.state_mut().1 = true; + h.run_steps(2); + let tab = h.get_by_label_contains("Untitled @").rect(); + let x = h.get_by_label("Close").rect(); + assert!(tab.contains_rect(x), "{os:?}: the × is inside its tab"); + assert_eq!(x.center().x > tab.center().x, after_title, "{os:?}: × at {x:?} in tab {tab:?}"); + h.get_by_label("Close").click(); + h.run_steps(2); + assert!(h.state().0.session.documents().is_empty(), "{os:?}: the × closes the document"); + } +} + +/// Middle-clicking a document tab closes it (#2570), in both tab strips, and the tab under the +/// pointer is the one that goes even when another document is active. +#[test] +fn middle_clicking_a_tab_closes_that_document() { + use egui_kittest::kittest::Queryable; + for kind in [crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::Pro] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for name in ["keep", "doomed", "active"] { + app.run("file.new", json!({"width": 8, "height": 8, "name": name})).unwrap(); + } + app.sync_views(); + assert_eq!(app.session.active_index(), Some(2)); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 40.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + tabs(app, ui); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, kind); + h.state_mut().1 = true; + h.run_steps(2); + h.get_by_label_contains("doomed").click_button(egui::PointerButton::Middle); + h.run_steps(2); + let names: Vec = h.state().0.session.documents().iter().map(|d| d.doc.name.clone()).collect(); + assert_eq!(names, ["keep", "active"], "{kind:?}: the middle-clicked tab closed"); + // A clean document closes straight away; a dirty one would park in `discard`. + assert!(h.state().0.discard.is_none(), "{kind:?}: nothing to prompt about"); + } +} + +/// A middle click goes through the same guarded `file.close` as the ×, so unsaved changes +/// still get the Save / Don’t Save / Cancel prompt instead of being thrown away (#2570). +#[test] +fn middle_clicking_an_edited_tab_prompts_instead_of_discarding() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8, "name": "edited"})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.sync_views(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 40.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + tabs(app, ui); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); + h.state_mut().1 = true; + h.run_steps(2); + h.get_by_label_contains("edited").click_button(egui::PointerButton::Middle); + h.run_steps(2); + assert!(h.state().0.discard.is_some(), "the unsaved-changes prompt must come up"); + assert_eq!(h.state().0.session.documents().len(), 1, "and the document is still open"); +} + +#[test] +fn spectrum_document_tabs_meet_canvas_without_a_gap() { + for kind in [crate::theme::ThemeKind::Pro, crate::theme::ThemeKind::ProMedium] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 60})).unwrap(); + app.sync_views(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(680.0, 480.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, kind); + h.state_mut().1 = true; + h.run_steps(3); + let app = &h.state().0; + let strip = app.tab_strip.as_ref().expect("a document opens with tabs").rect; + let gap = app.last_canvas_rect.top() - strip.bottom(); + assert!(gap.abs() < 0.1, "{kind:?}: document strip should touch canvas, got {gap} pt"); + } +} + +#[test] +fn large_tabs_preference_increases_tab_strip_height() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.sync_views(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(600.0, 60.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + tabs(app, ui); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); + h.state_mut().1 = true; + h.run_steps(2); + let normal_h = h.get_by_label_contains("Untitled @").rect().height(); + assert_eq!(normal_h, 26.0); + + h.state_mut().0.session.execute("prefs.set", json!({"values": {"workspace.largeTabs": true}})).unwrap(); + h.run_steps(2); + let large_h = h.get_by_label_contains("Untitled @").rect().height(); + assert_eq!(large_h, 34.0); +} + +#[test] +fn tab_close_others_prompts_for_unsaved_nonactive_document() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8, "name": "Keep"})).unwrap(); + app.run("file.new", json!({"width": 8, "height": 8, "name": "Edited"})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + assert_eq!(app.session.active_index(), Some(1)); + let (_, id, params, _) = tab_context_items(0, 2, false)[1].clone(); + crate::menus::invoke(&mut app, &egui::Context::default(), id, params).unwrap(); + assert!(app.discard.is_some(), "close others must ask before discarding the edited tab"); + assert_eq!(app.session.documents().len(), 2); +} + +/// The pure half of tab drag-to-reorder (UI-217-6): where a drop lands and which +/// `document.move` target that is. +#[test] +fn tab_drop_index_and_move_target_cover_reorder_drops() { + let r = |x: f32| Rect::from_min_size(egui::pos2(x, 0.0), egui::vec2(100.0, 26.0)); + let placed = vec![(0, r(0.0)), (1, r(100.0)), (2, r(200.0))]; + assert_eq!(tab_drop_index(&placed, 10.0), 0); + assert_eq!(tab_drop_index(&placed, 160.0), 2); + assert_eq!(tab_drop_index(&placed, 350.0), 3, "past the end lands after the last shown tab"); + assert_eq!(tab_move_target(0, 3), 2); + assert_eq!(tab_move_target(2, 0), 0); + assert_eq!(tab_move_target(1, 1), 1, "before itself: no move"); + assert_eq!(tab_move_target(1, 2), 1, "just after itself: no move"); + assert_eq!(tab_move_target(0, 1), 0); +} + +/// Dragging a tab onto another's slot reorders the open documents (UI-217-6), in both the +/// studio and the Photoshop-style strips. +#[test] +fn dragging_a_tab_reorders_the_documents() { + use egui_kittest::kittest::Queryable; + for kind in [crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::Pro] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for name in ["a", "b", "c"] { + app.run("file.new", json!({"width": 8, "height": 8, "name": name})).unwrap(); + } + app.sync_views(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 40.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + tabs(app, ui); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, kind); + h.state_mut().1 = true; + h.run_steps(2); + let b = h.get_by_label_contains("b").rect(); + let a = h.get_by_label_contains("a").rect(); + let target = egui::pos2(a.left() + 2.0, a.center().y); + h.drag_at(b.center()); + h.run_steps(1); + h.hover_at(target); + h.run_steps(1); + h.drop_at(target); + h.run_steps(2); + let names: Vec = h.state().0.session.documents().iter().map(|d| d.doc.name.clone()).collect(); + assert_eq!(names, ["b", "a", "c"], "{kind:?}: the dragged tab took the dropped slot"); + } +} + +/// Dragging a tab off the strip floats its document in its own OS window instead of +/// reordering (#3733), in both strips; a short wobble below the strip still reorders. +#[test] +fn dragging_a_tab_off_the_strip_floats_it_in_a_window() { + use egui_kittest::kittest::Queryable; + let strip = Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(700.0, 26.0)); + assert!(!torn_off(strip, egui::pos2(50.0, 13.0))); + assert!(!torn_off(strip, egui::pos2(50.0, 26.0 + TEAR_OFF - 1.0)), "a wobble below the strip still reorders"); + assert!(torn_off(strip, egui::pos2(50.0, 26.0 + TEAR_OFF + 1.0))); + assert!(torn_off(strip, egui::pos2(50.0, -TEAR_OFF - 1.0)), "dragged up, off the window's top"); + for kind in [crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::Pro] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for name in ["a", "b", "c"] { + app.run("file.new", json!({"width": 8, "height": 8, "name": name})).unwrap(); + } + app.sync_views(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(700.0, 300.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + tabs(app, ui); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, kind); + h.state_mut().1 = true; + h.run_steps(2); + let b = h.get_by_label_contains("b").rect(); + let target = egui::pos2(b.center().x, b.bottom() + 150.0); + h.drag_at(b.center()); + h.run_steps(1); + h.hover_at(target); + h.run_steps(1); + h.drop_at(target); + h.run_steps(2); + let app = &h.state().0; + let names: Vec<&str> = app.session.documents().iter().map(|d| d.doc.name.as_str()).collect(); + assert_eq!(names, ["a", "b", "c"], "{kind:?}: tearing off doesn't reorder"); + assert_eq!(app.ui.windows.iter().map(|w| w.document).collect::>(), [1], "{kind:?}: b floats in its own window"); + assert_eq!(app.session.active_index(), Some(1), "{kind:?}: the floated document is active"); + } +} + +#[test] +fn clone_overlay_is_circular_and_respects_visibility() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("cloneSource.set", json!({"source": [16,16]})).unwrap(); + app.ui.tool = Tool::CloneStamp; + app.session.tools.brush.size = 20.0; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let revision = app.session.active().unwrap().revision; + let mut output = ctx.run_ui(Default::default(), |ui| { + let ctx = ui.ctx(); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); + draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); + }); + output.textures_delta.clear(); + let mesh = output + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Mesh(m) => Some(m), + _ => None, + }) + .unwrap(); + assert_eq!(mesh.indices.len(), 64 * 3); + let center = xf.to_screen(32.0, 32.0); + assert!(mesh.vertices.iter().all(|v| v.pos.distance(center) <= 10.01)); + assert_eq!(app.session.active().unwrap().revision, revision); + assert!(app.session.presets.clone.active().anchor.is_none()); + let ordinary_key = app.clone_preview.as_ref().unwrap().key.clone(); + app.ui.view.pattern_preview = true; + let mut periodic_output = ctx.run_ui(Default::default(), |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); + draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); + }); + assert_ne!(app.clone_preview.as_ref().unwrap().key, ordinary_key, "toggling Pattern Preview invalidates source pixels"); + assert!(!periodic_output.textures_delta.set.is_empty(), "the overlay texture is refreshed without a document edit"); + periodic_output.textures_delta.clear(); + assert_eq!(app.session.active().unwrap().revision, revision); + app.session.presets.clone.overlay.show = false; + let mut output = ctx.run_ui(Default::default(), |ui| { + let ctx = ui.ctx(); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); + draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); + }); + output.textures_delta.clear(); + assert!(output.shapes.iter().all(|s| !matches!(s.shape, egui::Shape::Mesh(_)))); +} + +#[test] +fn clone_overlay_keeps_magnified_pixels_crisp_on_upload_and_refresh() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("cloneSource.set", json!({"source": [16, 16]})).unwrap(); + app.ui.tool = Tool::CloneStamp; + app.session.tools.brush.size = 20.0; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 4.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; + for invert in [false, true] { + app.session.presets.clone.overlay.invert = invert; + let mut output = ctx.run_ui(Default::default(), |ui| { + draw_clone_preview(&mut app, ui.painter(), &xf, [32.0, 32.0], None); + }); + let upload = output.textures_delta.set.values().flatten().find(|d| d.image.size() == [20, 20]).expect("clone overlay upload"); + let options = upload.options; + output.textures_delta.clear(); + assert_eq!(options.magnification, egui::TextureFilter::Nearest, "invert={invert}"); + assert_eq!(options.minification, egui::TextureFilter::Linear, "zoomed-out previews remain filtered"); + } +} + +#[test] +fn clone_overlay_blend_mode_mixes_with_the_image_under_the_brush() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("cloneSource.set", json!({"source": [16,16]})).unwrap(); + app.ui.tool = Tool::CloneStamp; + app.session.tools.brush.size = 20.0; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; + // The centre texel of the overlay texture uploaded for `mode`. + let mut centre = |mode: &str| { + app.run("cloneSource.overlay", json!({"blend": mode})).unwrap(); + let mut output = ctx.run_ui(Default::default(), |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); + draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); + }); + // The brush's 20 × 20 px square (the font atlas may upload too). + let image = output.textures_delta.set.values().flatten().find_map(|d| match &d.image { + egui::ImageData::Color(c) if c.size == [20, 20] => Some(c.clone()), + _ => None, + }); + output.textures_delta.clear(); + let image = image.expect("the overlay uploads a texture"); + image.pixels[image.width() * (image.height() / 2) + image.width() / 2] + }; + // A white source over the white image: Normal shows white, Difference black. + assert_eq!(centre("normal"), Color32::WHITE); + assert_eq!(centre("difference"), Color32::BLACK, "Difference turns black where source and image match"); + assert_eq!(centre("lighten"), Color32::WHITE); +} + +/// A shaped tip clips the Clone Source overlay to its outline, not to the brush circle. +#[test] +fn clone_overlay_is_clipped_to_a_shaped_tip() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("cloneSource.set", json!({"source": [16,16]})).unwrap(); + app.ui.tool = Tool::CloneStamp; + app.session.tools.brush.size = 20.0; + app.session.tools.brush.roundness = 0.25; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let mut output = ctx.run_ui(Default::default(), |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); + draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); + }); + let image = output + .textures_delta + .set + .values() + .flatten() + .find_map(|d| match &d.image { + egui::ImageData::Color(c) if c.size == [20, 20] => Some(c.clone()), + _ => None, + }) + .expect("the overlay uploads a texture"); + output.textures_delta.clear(); + let alpha = |x: usize, y: usize| image.pixels[y * image.width() + x].a(); + assert_eq!(alpha(10, 10), 255, "the tip's centre shows the source"); + assert_eq!(alpha(10, 2), 0, "inside the circle but outside the flat tip: clipped"); + assert_eq!(alpha(1, 10), 255, "the tip's long axis stays"); +} + +#[test] +fn wayland_start_screen_hint_does_not_claim_file_drop_works() { + let x11 = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let wayland = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { is_wayland: true, ..Default::default() }); + assert!(start_screen_drop_hint(&x11).starts_with("Drop")); + // Pasting a copied image file works on Wayland (#338): the hint says how. + let hint = start_screen_drop_hint(&wayland); + assert!(!hint.contains("Drop"), "{hint}"); + assert!(hint.ends_with(&format!("paste a copied image with {}.", crate::notices::paste_hint(&wayland))), "{hint}"); +} + +/// A tiling window manager can hand PhotoCraft a canvas narrower than the Home card (460 +/// points): the two buttons must stay inside the window instead of being clipped at its edges. +#[test] +fn start_screen_buttons_stay_inside_a_narrow_canvas() { + use egui_kittest::kittest::Queryable; + for width in [390.0, 420.0, 520.0] { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(width, 760.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.state_mut().1 = true; + h.run_steps(3); + for label in ["New document", "Join us on Discord"] { + for node in h.query_all_by_label_contains(label) { + let r = node.rect(); + assert!(r.left() >= 0.0 && r.right() <= width, "`{label}` is clipped in a {width}-point-wide canvas: {r:?}"); + } + } + } +} + +/// #4382: Interface › Show home recent files off hides the Home screen's list, not the recents. +#[test] +fn home_recent_list_hides_when_the_preference_is_off() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.push_recent("/tmp/photocraft-217/hidden.psd"); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 760.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.state_mut().1 = true; + h.run_steps(3); + assert!(h.query_by_label("hidden.psd").is_some(), "listed by default"); + h.state_mut().0.run("prefs.set", serde_json::json!({"values": {"interface.showHomeRecentFiles": false}})).unwrap(); + h.run_steps(3); + assert!(h.query_by_label("hidden.psd").is_none(), "hidden when off"); + assert_eq!(h.state().0.ui.recent_files.len(), 1, "the list itself is kept"); +} + +/// The Home screen's × takes a file off Recent without opening it, and its right-click menu +/// removes one entry or clears the list; the preferences keep the change (#2691). +#[test] +fn home_recent_entries_can_be_removed() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for name in ["c.tif", "b.psd", "a.png"] { + app.push_recent(&format!("/tmp/photocraft-2691/{name}")); + } + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 760.0)).build_ui_state( + |ui, (app, ready): &mut (PhotocraftApp, bool)| { + if *ready { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| document_area(app, ui)); + } + }, + (app, false), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.state_mut().1 = true; + h.run_steps(3); + let listed = |h: &egui_kittest::Harness<'_, (PhotocraftApp, bool)>| { + let app = &h.state().0; + assert_eq!(app.session.prefs().file_handling.recent_files, app.ui.recent_files, "stored in the preferences"); + app.ui.recent_files.iter().map(|p| crate::file_open::display_name(p)).collect::>() + }; + assert_eq!(listed(&h), ["a.png", "b.psd", "c.tif"]); + assert!(h.query_by_label("Remove b.psd from Recent").is_none(), "the × shows on the hovered row only"); + + h.get_by_label("b.psd").hover(); + h.run_steps(2); + h.get_by_label("Remove b.psd from Recent").click(); + h.run_steps(2); + assert_eq!(listed(&h), ["a.png", "c.tif"]); + assert!(h.state().0.session.documents().is_empty(), "the file was not opened"); + + h.get_by_label("c.tif").click_secondary(); + h.run_steps(2); + h.get_by_label("Remove from Recent").click(); + h.run_steps(2); + assert_eq!(listed(&h), ["a.png"]); + + h.get_by_label("a.png").click_secondary(); + h.run_steps(2); + h.get_by_label("Clear Recent Files").click(); + h.run_steps(2); + assert!(listed(&h).is_empty()); + assert!(h.state().0.session.documents().is_empty()); +} + +#[test] +fn pointer_moves_are_bounded_by_the_press_and_release() { + use egui::{Event, PointerButton, pos2}; + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let events = [ + Event::PointerMoved(pos2(1.0, 0.0)), + button(pos2(2.0, 0.0), true), + Event::PointerMoved(pos2(3.0, 0.0)), + Event::PointerMoved(pos2(4.0, 0.0)), + button(pos2(5.0, 0.0), false), + Event::PointerMoved(pos2(6.0, 0.0)), + ]; + // The press is in this frame: only the moves between press and release count. + assert_eq!(pointer_moves(&events, PointerButton::Primary, false), vec![pos2(3.0, 0.0), pos2(4.0, 0.0)]); + // The button was already down when the frame began: the move before the release counts, + // the one after it does not. + assert_eq!(pointer_moves(&events, PointerButton::Primary, true), vec![pos2(1.0, 0.0), pos2(3.0, 0.0), pos2(4.0, 0.0)]); +} + +#[test] +fn freehand_tools_are_the_ones_that_follow_a_path() { + for t in [ + Tool::Brush, + Tool::Pencil, + Tool::MixerBrush, + Tool::ColorReplacement, + Tool::Eraser, + Tool::BackgroundEraser, + Tool::CloneStamp, + Tool::PatternStamp, + Tool::Smudge, + Tool::Dodge, + Tool::Lasso, + Tool::QuickSelection, + ] { + assert!(freehand_tool(t), "{t:?} paints or retouches along a path"); + } + for t in [Tool::Move, Tool::Eyedropper, Tool::Gradient, Tool::Crop, Tool::RectMarquee, Tool::Type, Tool::Hand] { + assert!(!freehand_tool(t), "{t:?} is driven by the pointer's latest position"); + } +} + +#[test] +fn clone_stamp_centre_appears_only_with_option() { + assert!(!brush_tip_centre(Tool::CloneStamp, false, false)); + assert!(brush_tip_centre(Tool::CloneStamp, true, false)); + assert!(brush_tip_centre(Tool::Healing, true, false)); + assert!(!brush_tip_centre(Tool::Healing, false, false)); + assert!(brush_tip_centre(Tool::CloneStamp, false, true)); + assert!(!brush_tip_centre(Tool::PatternStamp, true, false), "Pattern Stamp keeps the brush cursor; Option does not switch it to a clone-source mark"); + assert!(!brush_tip_centre(Tool::QuickSelection, false, true)); + assert!(brush_tip_centre(Tool::BackgroundEraser, false, false)); +} + +#[test] +fn brush_tip_centre_follows_the_crosshair_preference_at_any_size() { + // A large tip used to show the centre mark whatever Show Crosshair in Brush Tip said. + for tool in [Tool::Brush, Tool::Eraser, Tool::PatternStamp, Tool::Dodge] { + assert!(!brush_tip_centre(tool, false, false), "{tool:?}: off"); + assert!(brush_tip_centre(tool, false, true), "{tool:?}: on"); + } +} + +#[test] +fn view_transform_roundtrip() { + for flip in [false, true] { + let xf = ViewXform { + rect: Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0)), + zoom: 2.5, + center: [320.0, 240.0], + flip, + rotation: 0.0, + aspect: 1.0, + }; + let s = xf.to_screen(10.0, 20.0); + let d = xf.to_doc(s); + assert!((d[0] - 10.0).abs() < 1e-3 && (d[1] - 20.0).abs() < 1e-3); + assert_eq!(xf.to_screen(320.0, 240.0), xf.rect.center()); + // Flipped, document x grows to the left. + assert_eq!(xf.to_screen(330.0, 240.0).x > xf.rect.center().x, !flip); + let r = xf.doc_rect(DRect::new(0, 0, 10, 10)); + assert!(r.width() > 0.0 && r.height() > 0.0); + } +} + +#[test] +fn eyedropper_ring_colors_pair_the_sampled_and_current_colours() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 40, "height": 20, "background": "transparent"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [0, 0, 20, 20], "fill": "#ff0000"})).unwrap(); + app.run("tools.setColors", json!({"foreground": [0.0, 0.2, 1.0, 1.0]})).unwrap(); + let (new, current) = super::eyedropper_ring_colors(&mut app, 10.0, 10.0).expect("over the red square"); + let near = |c: egui::Color32, r: u8, g: u8, b: u8| { + let d = |a: u8, b: u8| i32::from(a).abs_diff(i32::from(b)); + d(c.r(), r) <= 1 && d(c.g(), g) <= 1 && d(c.b(), b) <= 1 + }; + assert!(near(new, 255, 0, 0), "{new:?}"); + assert!(near(current, 0, 51, 255), "{current:?}"); + // Transparency and points outside the canvas have nothing to compare. + assert!(super::eyedropper_ring_colors(&mut app, 30.0, 10.0).is_none()); + assert!(super::eyedropper_ring_colors(&mut app, -1.0, 10.0).is_none()); +} + +#[test] +fn eyedropper_drag_updates_the_sampled_colour() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 40, "height": 20, "background": "transparent"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [0, 0, 20, 20], "fill": "#ff0000"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [20, 0, 20, 20], "fill": "#00ff00"})).unwrap(); + app.ui.tool = Tool::Eyedropper; + + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert!(app.session.tools.foreground[0] > 0.99 && app.session.tools.foreground[1] < 0.01); + + tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 10.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert!(app.session.tools.foreground[1] > 0.99 && app.session.tools.foreground[0] < 0.01); +} + +/// #4298: an adjustment layer has no pixels, so after its icon thumbnail is clicked (the +/// Layers panel no longer targets the mask) Fill, the fill keys and the Paint Bucket still +/// edit its mask, as in Photoshop, instead of failing with "not a pixel layer". +#[test] +fn fills_on_an_adjustment_layer_edit_its_mask_when_the_icon_is_targeted() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 40, "height": 20, "background": "white"})).unwrap(); + app.run("layer.newAdjustmentLayer.curves", json!({})).unwrap(); + // Click the Curves icon thumbnail: the panel targets the layer, not its mask. + app.ui.mask_target = false; + app.sync_mask_targets(); + assert!(!app.ui.mask_target, "the panel's target is the icon"); + let mask_at = |app: &PhotocraftApp| { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(10, 10, 0) + }; + assert_eq!(paint_target(&app), json!("mask")); + assert!(crate::menus::is_enabled(&app, "edit.fill"), "Edit > Fill (⇧F5) is enabled"); + assert!(crate::menus::is_enabled(&app, "edit.fillForeground")); + app.ui.tool = Tool::PaintBucket; + app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 0.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]})).unwrap(); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 10.0, y: 10.0 }, egui::Modifiers::NONE); + assert_eq!(mask_at(&app), 0.0, "the Paint Bucket filled the mask black"); + app.run("edit.fill", json!({"contents": "white"})).unwrap(); + assert_eq!(mask_at(&app), 1.0, "Edit > Fill filled the mask white"); + assert!(!app.ui.mask_target, "filling doesn't move the panel's target"); + // A pixel layer with an untargeted mask still paints its pixels. + app.run("layer.new.layer", json!({})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.ui.mask_target = false; + assert_eq!(paint_target(&app), json!("pixels")); + assert!(!app.layer_mask_targeted()); +} + +#[test] +fn alt_with_a_painting_tool_samples_the_foreground_instead_of_painting() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 40, "height": 20, "background": "transparent"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [0, 0, 20, 20], "fill": "#ff0000"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [20, 0, 20, 20], "fill": "#00ff00"})).unwrap(); + let alt = egui::Modifiers::ALT; + for tool in [Tool::Brush, Tool::Pencil, Tool::Gradient, Tool::PaintBucket] { + app.ui.tool = tool; + app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 1.0, 1.0], "background": [1.0, 1.0, 1.0, 1.0]})).unwrap(); + let rev = app.session.active().unwrap().revision; + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, alt); + assert_eq!(app.session.tools.foreground, [1.0, 0.0, 0.0, 1.0], "{tool:?}: ⌥-click sets the foreground"); + // A drag keeps sampling, even after ⌥ is let go; the background is untouched. + tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 10.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert_eq!(app.session.tools.foreground, [0.0, 1.0, 0.0, 1.0], "{tool:?}"); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 10.0 }, egui::Modifiers::NONE); + assert_eq!(app.session.tools.background, [1.0, 1.0, 1.0, 1.0]); + assert_eq!(app.session.active().unwrap().revision, rev, "{tool:?}: sampling must not edit the document"); + assert!(app.drag.is_none() && !app.alt_sampling); + } + // Agents get the same through `ui.pointer` (MCP `ui_pointer`). + app.ui.tool = Tool::Brush; + let ctx = egui::Context::default(); + let events = json!([{"kind": "down", "x": 10, "y": 10}, {"kind": "up", "x": 10, "y": 10}]); + let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"modifiers": {"alt": true}, "events": events})); + let _ = crate::control::handle(&mut app, &ctx, &req); + assert_eq!(app.session.tools.foreground, [1.0, 0.0, 0.0, 1.0]); + app.run("tools.setColors", json!({"foreground": [0.0, 1.0, 0.0, 1.0]})).unwrap(); + // Without ⌥ the Brush paints again, and ⌥ pressed mid-stroke doesn't switch to sampling. + app.run("layer.new.layer", json!({})).unwrap(); + let rev = app.session.active().unwrap().revision; + tool_event(&mut app, ToolEvent::Down { x: 5.0, y: 5.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 5.0, pressure: 1.0 }, alt); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 5.0 }, alt); + assert_eq!(app.session.tools.foreground, [0.0, 1.0, 0.0, 1.0]); + assert!(app.session.active().unwrap().revision > rev, "the stroke was painted"); + // Control+Alt stays the brush-resize gesture, never a sample. + assert!(!alt_samples(Tool::Brush, egui::Modifiers { alt: true, ctrl: true, ..Default::default() })); + assert!(!alt_samples(Tool::Eraser, alt), "⌥ with the Eraser is not the Eyedropper"); +} + +/// #2078: the opaque mask-view texture must show the live stroke, not cover it with +/// the committed mask until the mouse is released. +#[test] +fn mask_view_uploads_each_live_stroke_before_release() { + for depth in [8, 16, 32] { + for mode in ["gray", "overlay"] { + for (width, factor) in [(120u32, 1u32), (513, 3)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": width, "height": 60, "depth": depth})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.run("view.layerMask", json!({"mode": mode})).unwrap(); + app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 0.0, 1.0]})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 12, "hardness": 1.0, "smoothing": {"amount": 0.0}}})).unwrap(); + app.ui.tool = Tool::Brush; + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.max_texture_side = 256); + let tex = crate::channel_view::ensure(&mut app, &ctx, 0).unwrap(); + ctx.tex_manager().write().take_delta().clear(); + let revision = app.session.documents()[0].revision; + let steps = app.session.documents()[0].history.past_len(); + let layer = app.session.documents()[0].active_layer.unwrap(); + let original = app.session.documents()[0].doc.layer(layer).unwrap().clone(); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + for x in [30.0, 50.0, 70.0] { + tool_event(&mut app, ToolEvent::Move { x, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + let shown = display_doc(&mut app, 0).0; + assert!(shown.layer(layer).unwrap().mask.as_ref().unwrap().value(x as i32, 30) < 0.1); + assert_eq!(crate::channel_view::ensure(&mut app, &ctx, 0), Some(tex)); + let mut delta = ctx.tex_manager().write().take_delta(); + let uploads = delta.set.get(&tex).unwrap_or_else(|| panic!("{depth}-bit {mode}: live mask texture must upload before release at {x}")); + assert_eq!(uploads.len(), 1); + let upload = &uploads[0]; + let pos = upload.pos.expect("only the damaged region is uploaded"); + let egui::ImageData::Color(image) = &upload.image; + assert!(image.pixels.len() < (width.div_ceil(factor) * 60u32.div_ceil(factor)) as usize, "the whole mask is not uploaded"); + let f = factor as i32; + let r = DRect::new(pos[0] as i32 * f, pos[1] as i32 * f, (pos[0] + image.size[0]) as i32 * f, (pos[1] + image.size[1]) as i32 * f) + .intersect(&shown.bounds()); + let expected = crate::channel_view::render( + &shown, + &app.session.documents()[0].channel_view, + r, + factor, + crate::channel_view::Look::default(), + app.session.documents()[0].active_layer, + ) + .unwrap(); + assert_eq!(image.pixels, expected, "uploaded mask values match the live stroke"); + delta.clear(); + assert_eq!(app.session.documents()[0].revision, revision); + assert_eq!(app.session.documents()[0].history.past_len(), steps); + assert_eq!(app.session.documents()[0].doc.layer(layer).unwrap(), &original); + crate::channel_view::ensure(&mut app, &ctx, 0); + assert!(ctx.tex_manager().write().take_delta().set.is_empty(), "idle frame does not upload"); + } + tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 30.0 }, egui::Modifiers::NONE); + let st = &app.session.documents()[0]; + assert_eq!(st.history.past_len(), steps + 1); + assert!(st.doc.layer(layer).unwrap().mask.as_ref().unwrap().value(50, 30) < 0.1); + assert_eq!(st.doc.layer(layer).unwrap().content, original.content); + crate::channel_view::ensure(&mut app, &ctx, 0); + let mut delta = ctx.tex_manager().write().take_delta(); + // The commit takes the live stroke's pixels, which the texture already shows: at + // most a partial upload, never the whole mask again. + assert!(delta.set.get(&tex).is_none_or(|u| u.iter().all(|u| u.pos.is_some())), "commit keeps its partial upload"); + delta.clear(); + app.session.undo(); + assert_eq!(app.session.documents()[0].doc.layer(layer).unwrap(), &original); + crate::channel_view::ensure(&mut app, &ctx, 0); + let mut delta = ctx.tex_manager().write().take_delta(); + let egui::ImageData::Color(image) = &delta.set.get(&tex).unwrap()[0].image; + let st = &app.session.documents()[0]; + assert_eq!( + image.pixels, + crate::channel_view::render(&st.doc, &st.channel_view, st.doc.bounds(), factor, crate::channel_view::Look::default(), st.active_layer) + .unwrap(), + "undo restores the shown mask" + ); + delta.clear(); + } + } + } +} + +#[test] +fn channel_views_show_live_targets_and_discarded_strokes() { + for target in ["quickMask", "alpha", "red"] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); + match target { + "quickMask" => { + app.run("select.rect", json!({"x": 0, "y": 0, "width": 120, "height": 60})).unwrap(); + app.run("select.editInQuickMaskMode", json!({})).unwrap(); + } + "alpha" => { + app.run("channel.new", json!({"fill": "white"})).unwrap(); + } + _ => { + app.run("channel.target", json!({"channel": "red"})).unwrap(); + } + } + app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 0.0, 1.0]})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 12, "hardness": 1.0, "smoothing": {"amount": 0.0}}})).unwrap(); + app.ui.tool = Tool::Brush; + let ctx = egui::Context::default(); + let tex = crate::channel_view::ensure(&mut app, &ctx, 0).unwrap(); + ctx.tex_manager().write().take_delta().clear(); + let original = app.session.documents()[0].doc.clone(); + let steps = app.session.documents()[0].history.past_len(); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + let shown = display_doc(&mut app, 0).0; + crate::channel_view::ensure(&mut app, &ctx, 0); + let mut delta = ctx.tex_manager().write().take_delta(); + let upload = &delta.set.get(&tex).expect("live channel upload")[0]; + let pos = upload.pos.expect("partial channel upload"); + let egui::ImageData::Color(image) = &upload.image; + let r = DRect::new(pos[0] as i32, pos[1] as i32, (pos[0] + image.size[0]) as i32, (pos[1] + image.size[1]) as i32); + assert_eq!( + image.pixels, + crate::channel_view::render( + &shown, + &app.session.documents()[0].channel_view, + r, + 1, + crate::channel_view::Look::default(), + app.session.documents()[0].active_layer + ) + .unwrap(), + "{target}" + ); + assert_ne!( + image.pixels, + crate::channel_view::render( + &original, + &app.session.documents()[0].channel_view, + r, + 1, + crate::channel_view::Look::default(), + app.session.documents()[0].active_layer + ) + .unwrap(), + "target was painted" + ); + delta.clear(); + assert_eq!(app.session.documents()[0].history.past_len(), steps); + assert!(std::sync::Arc::ptr_eq(&original, &app.session.documents()[0].doc)); + // Dropping a preview without committing must restore its texture, even though the + // document revision did not change. There is no committed damage rectangle to use. + app.drag = None; + app.live_stroke = None; + crate::channel_view::ensure(&mut app, &ctx, 0); + let mut delta = ctx.tex_manager().write().take_delta(); + let upload = &delta.set.get(&tex).unwrap()[0]; + assert!(upload.pos.is_none(), "discarding a preview refreshes the view"); + let egui::ImageData::Color(image) = &upload.image; + assert_eq!( + image.pixels, + crate::channel_view::render( + &original, + &app.session.documents()[0].channel_view, + original.bounds(), + 1, + crate::channel_view::Look::default(), + app.session.documents()[0].active_layer + ) + .unwrap() + ); + delta.clear(); + } +} + +/// The held drag shows true mixed paint while Alt sampling remains separate from painting. +#[test] +fn mixer_drag_shows_actual_mixed_paint_before_release_and_alt_never_paints() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setColors", json!({"foreground":"#ff0000"})).unwrap(); + app.run("tools.setBrush", json!({"brush":{"size":16,"mixer":{"wet":1.0,"mix":0.7,"sampleAllLayers":true},"smoothing":{"amount":0.0}}})).unwrap(); + app.ui.tool = Tool::MixerBrush; + let before = app.session.active().unwrap().doc.clone(); + let count = app.session.active().unwrap().history.past_len(); + let alt = egui::Modifiers { alt: true, ..Default::default() }; + tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, alt); + tool_event(&mut app, ToolEvent::Move { x: 35.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 35.0, y: 30.0 }, egui::Modifiers::NONE); + assert!(app.drag.is_none()); + assert!(app.session.tools.mixer.spatial.is_some()); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + app.run("brush.mixer.load", json!({})).unwrap(); + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 30.0, pressure: 0.6 }, egui::Modifiers::NONE); + assert!(app.live_stroke.is_some()); + let shown = display_doc(&mut app, 0).0; + let id = app.session.active().unwrap().active_layer.unwrap(); + let pixel = shown.layer(id).unwrap().surface().unwrap().rgba(45, 30); + assert!(pixel[0] > 0.0 && pixel[1] > 0.0 && pixel[3] > 0.0, "actual red/green mixture {pixel:?}"); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), count); + tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 30.0 }, egui::Modifiers::NONE); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), count + 1); + assert_eq!( + shown.layer(id).unwrap().surface().unwrap().read_region(before.bounds()), + st.doc.layer(id).unwrap().surface().unwrap().read_region(before.bounds()) + ); + app.session.undo(); + assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().surface().unwrap().rgba(45, 30)[3], 0.0); +} + +/// Release incorporates its final endpoint and deferred samples in both live and fallback paths. +#[test] +fn mixer_release_includes_a_new_endpoint_and_deferred_frame_samples() { + for (deferred, failed) in [(false, false), (true, false), (false, true)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setBrush", json!({"size":12,"pressureSize":false})).unwrap(); + app.ui.tool = Tool::MixerBrush; + let before = app.session.active().unwrap().doc.clone(); + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, m); + app.defer_live_stroke = deferred; + if failed { + app.live_stroke.as_mut().unwrap().preview_failed = true; + } + tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 95.0, y: 30.0 }, m); + let doc = app.session.active().unwrap().doc.clone(); + let id = app.session.active().unwrap().active_layer.unwrap(); + assert!(doc.layer(id).unwrap().surface().unwrap().rgba(92, 30)[3] > 0.0); + let params = app.session.journal.iter().rev().find(|(name, _)| name == "paint.mixerBrush").unwrap().1.clone(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(*app.session.active().unwrap().doc, *before); + app.run("paint.mixerBrush", params).unwrap(); + assert_eq!(*app.session.active().unwrap().doc, *doc); + } +} + +/// Reproduce a tool change and release in one control call, before a UI frame can cancel the old gesture. +#[test] +fn mixer_control_tool_switch_before_release_cancels_every_preview_path() { + for preview in 0..3 { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setBrush", json!({"size":12,"pressureSize":false})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let steps = app.session.active().unwrap().history.past_len(); + let anchor = app.last_stroke_end; + let ctx = egui::Context::default(); + let (request, _reply) = crate::control::ControlRequest::new( + "ui.pointer", + json!({"tool":"mixerBrush","events":[{"kind":"down","x":20,"y":30},{"kind":"move","x":50,"y":30}]}), + ); + let _ = crate::control::handle(&mut app, &ctx, &request); + assert!(app.drag.is_some() && app.live_stroke.is_some()); + if preview == 1 { + app.live_stroke.as_mut().unwrap().preview_failed = true; + } else if preview == 2 { + app.live_stroke = None; + } + // No intervening UI frame: control selects the new tool before dispatching Up. + let (request, _reply) = crate::control::ControlRequest::new("ui.pointer", json!({"tool":"brush","events":[{"kind":"up","x":95,"y":30}]})); + let _ = crate::control::handle(&mut app, &ctx, &request); + assert_eq!(app.ui.tool, Tool::Brush); + assert!(app.drag.is_none() && app.live_stroke.is_none()); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + assert_eq!(app.last_stroke_end, anchor); + assert!(!app.session.journal.iter().any(|(id, _)| id == "paint.mixerBrush")); + } +} + +/// Escape and tool changes cancel both ordinary previews and failed-preview fallback gestures. +#[test] +fn mixer_escape_and_tool_switch_cancel_without_an_edit() { + for mode in 0..4 { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = Tool::MixerBrush; + let before = app.session.active().unwrap().doc.clone(); + let steps = app.session.active().unwrap().history.past_len(); + tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert!(app.live_stroke.is_some()); + if mode >= 2 { + app.live_stroke.as_mut().unwrap().preview_failed = true; + } + let mode = mode % 2; + let ctx = egui::Context::default(); + let mut raw = egui::RawInput { focused: true, ..Default::default() }; + if mode == 0 { + raw.events.push(egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }); + } + if mode == 1 { + app.ui.tool = Tool::Brush; + } + ctx.begin_pass(raw); + assert!(cancel_mixer_on_context_change(&mut app, &ctx)); + let mut output = ctx.end_pass(); + output.textures_delta.clear(); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }, egui::Modifiers::NONE); + assert!(app.drag.is_none() && app.live_stroke.is_none()); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc)); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + } +} + +/// Control-driven strokes remain live in a background window, matching the ordinary Brush. +#[test] +fn mixer_background_window_keeps_and_commits_control_strokes() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"transparent"})).unwrap(); + app.run("tools.setBrush", json!({"brush":{"size":12,"pressureSize":false}})).unwrap(); + let steps = app.session.active().unwrap().history.past_len(); + let ctx = egui::Context::default(); + ctx.begin_pass(egui::RawInput { focused: false, ..Default::default() }); + let (request, _reply) = crate::control::ControlRequest::new( + "ui.pointer", + json!({"tool":"mixerBrush","events":[{"kind":"down","x":20,"y":30},{"kind":"move","x":60,"y":30}]}), + ); + let _ = crate::control::handle(&mut app, &ctx, &request); + assert!(!cancel_mixer_on_context_change(&mut app, &ctx)); + assert!(app.drag.is_some()); + let (request, _reply) = crate::control::ControlRequest::new("ui.pointer", json!({"tool":"mixerBrush","events":[{"kind":"up","x":95,"y":30}]})); + let _ = crate::control::handle(&mut app, &ctx, &request); + let mut output = ctx.end_pass(); + output.textures_delta.clear(); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); + assert!(app.session.journal.iter().any(|(id, _)| id == "paint.mixerBrush")); + let st = app.session.active().unwrap(); + assert!(st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(60, 30)[3] > 0.0); +} + +/// A tip above the live preview's 1024 px paints on release, as main and Photoshop paint it +/// up to 5000 px; a stroke that can't paint at all is still refused on press. +#[test] +fn mixer_drag_above_the_preview_size_paints_on_release() { + for locked in [false, true] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + if locked { + app.run("layer.lockLayers", json!({"pixels": true})).unwrap(); + } + app.run("tools.setColors", json!({"foreground":"#ff0000"})).unwrap(); + app.run("tools.setBrush", json!({"brush":{"size":2000,"hardness":1.0,"pressureSize":false,"mixer":{"wet":0.0,"mix":0.0}}})).unwrap(); + app.ui.tool = Tool::MixerBrush; + let steps = app.session.active().unwrap().history.past_len(); + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, m); + assert!(app.live_stroke.is_none(), "no live preview above 1024 px"); + assert_eq!(app.drag.is_some(), !locked, "a valid 2000 px stroke is kept for release"); + assert_eq!(app.ui.status_error, locked, "{}", app.ui.status); + tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 30.0 }, m); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), steps + usize::from(!locked)); + let pixel = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(60, 30); + assert_eq!(pixel[0] > 0.9 && pixel[3] > 0.9, !locked, "{pixel:?}"); + } +} + +/// ⌥ with a held temporary tool (macOS ⌘ = Move) is that tool's, not a Mixer Brush paint load. +#[test] +fn mixer_alt_with_a_held_temporary_tool_does_not_load_paint() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width":120,"height":60,"background":"#00ff00"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = Tool::MixerBrush; + app.tool_override = Some(Tool::Move); + let alt = egui::Modifiers { alt: true, ..Default::default() }; + tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, alt); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }, alt); + assert!(app.session.tools.mixer.spatial.is_none(), "the held Move tool doesn't sample"); + app.tool_override = None; + tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, alt); + assert!(app.session.tools.mixer.spatial.is_some(), "⌥ with the Mixer Brush itself samples"); +} + +#[test] +fn brush_drag_shows_the_real_stroke_and_commits_it() { + // The drag used to draw a hard, flat stand-in and only showed the soft brush on release. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 120, "height": 60, "background": "transparent"})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 0.0}})).unwrap(); + app.ui.tool = Tool::Brush; + let m = egui::Modifiers::NONE; + let alpha = |d: &Document, x, y| d.layers[0].surface().unwrap().rgba(x, y)[3]; + let rev = app.session.documents()[0].revision; + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, m); + for x in [40.0, 70.0, 100.0] { + tool_event(&mut app, ToolEvent::Move { x, y: 30.0, pressure: 1.0 }, m); + } + let (shown, key) = display_doc(&mut app, 0); + assert_ne!(key, 0); + // A partial value two thirds of the way out: the soft tip, not a hard flat stand-in. + assert!(alpha(&shown, 40, 30) > 0.5 && (0.01..0.95).contains(&alpha(&shown, 40, 36)), "soft stroke while drawing"); + 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(); + 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(); + assert!(app.live_stroke.is_none() && display_doc(&mut app, 0).1 == 0); + assert_eq!((alpha(&doc, 40, 30), alpha(&doc, 40, 38)), (alpha(&shown, 40, 30), alpha(&shown, 40, 38)), "commit matches the preview"); +} + +#[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 + // is wider than MAX_TEXTURE, so the CPU texture is reduced (factor 2) and each step + // must update only the reduced pixels it touched. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + ctx.input_mut(|i| i.max_texture_side = 8192); + app.run("file.new", json!({"width": 4097, "height": 90, "background": "transparent"})).unwrap(); + let tilt = json!({"size": 30, "hardness": 1.0, "spacing": 0.05, "shapeDynamics": {"enabled": true, "size": {"control": "penTilt"}}}); + app.run("tools.setBrush", json!({ "brush": tilt })).unwrap(); + app.ui.tool = Tool::Brush; + assert_eq!(ensure_texture(&mut app, &ctx, 0, None).map(|t| t.1), Some(0.5)); + let m = egui::Modifiers::NONE; + app.stylus.feed.set(Some(crate::stylus::PenSample { pressure: 1.0, tilt_x: 60.0, tilt_y: 0.0, rotation: 0.0, eraser: false })); + tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 45.0, pressure: 1.0 }, m); + for x in [300.0, 600.0, 900.0] { + tool_event(&mut app, ToolEvent::Move { x, y: 45.0, pressure: 1.0 }, m); + ensure_texture(&mut app, &ctx, 0, None); + assert_eq!(app.perf.last_refresh, "rect"); + assert!(app.perf.last_refresh_px < 4097 * 90 / 4, "{}", app.perf.last_refresh_px); + } + let shown = display_doc(&mut app, 0).0; + tool_event(&mut app, ToolEvent::Up { x: 900.0, y: 45.0 }, m); + ensure_texture(&mut app, &ctx, 0, None); + assert_eq!(app.perf.last_refresh, "rect", "the commit refreshes only the stroke"); + let doc = app.session.documents()[0].doc.clone(); + let (a, b) = (doc.layers[0].surface().unwrap(), shown.layers[0].surface().unwrap()); + // 60° tilt shrinks the dab well below 30 px: the preview shows that size, as committed. + assert!(a.rgba(500, 45)[3] > 0.5 && a.rgba(500, 45 + 12)[3] == 0.0); + // (The smoothed tail catches up to the end point only when the stroke finishes.) + assert!((0..90).all(|y| (0..700).all(|x| a.rgba(x, y) == b.rgba(x, y))), "commit matches the preview"); +} + +/// Brush drag along y = 40 with one canvas frame per pointer move; returns the document the +/// canvas showed at the last move, the committed one, and whether the release refreshed only +/// the stroke's rectangle. +fn drag_frames(smoothing: f32, xs: &[f64]) -> (std::sync::Arc, std::sync::Arc, bool, PhotocraftApp) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 200, "height": 80, "background": "transparent"})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 16, "hardness": 0.5}})).unwrap(); + // What the options bar's Smoothing field writes. + app.session.tools.brush.smoothing.amount = smoothing; + app.ui.tool = Tool::Brush; + ensure_texture(&mut app, &ctx, 0, None); + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 1.0 }, m); + for &x in xs { + tool_event(&mut app, ToolEvent::Move { x, y: 40.0 + (x / 7.0).sin() * 8.0, pressure: 1.0 }, m); + ensure_texture(&mut app, &ctx, 0, None); + } + let live = display_doc(&mut app, 0).0; + let last = *xs.last().unwrap(); + tool_event(&mut app, ToolEvent::Up { x: last, y: 40.0 + (last / 7.0).sin() * 8.0 }, m); + let (next, key) = display_doc(&mut app, 0); + assert_eq!(key, 0, "the frame after release shows the committed document"); + ensure_texture(&mut app, &ctx, 0, None); + let partial = app.perf.last_refresh == "rect"; + (live, next, partial, app) +} + +fn same_pixels(a: &Document, b: &Document) -> bool { + let (a, b) = (a.layers[0].surface().unwrap(), b.layers[0].surface().unwrap()); + (0..80).all(|y| (0..200).all(|x| a.rgba(x, y) == b.rgba(x, y))) +} + +#[test] +fn release_shows_nothing_new_without_smoothing() { + // #73: at 0 % the stroke follows the pointer; the last frame drawn while dragging is + // exactly the committed stroke, so release changes nothing on screen. + let (live, done, partial, app) = drag_frames(0.0, &[40.0, 70.0, 100.0, 130.0, 160.0]); + assert!(same_pixels(&live, &done), "preview at the last move = committed stroke"); + assert!(partial, "the handover refreshes only the stroke"); + let p = app.session.journal.iter().rev().find(|(id, _)| id == "paint.stroke").map(|(_, p)| p.clone()).unwrap(); + assert!(p.get("smoothing").is_none(), "the commit uses the session brush's smoothing, not a hard-coded one"); +} + +#[test] +fn navigator_keeps_its_image_during_a_live_brush_stroke() { + // #1631: every step of a live stroke is a new preview key, so a navigator keyed by it + // re-composited the whole document per frame while painting. It waits for the release. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 80, "background": "transparent"})).unwrap(); + app.ui.tool = Tool::Brush; + let m = egui::Modifiers::NONE; + assert!(!navigator_waits_for_drag(&app, 0)); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 1.0 }, m); + let mut keys = Vec::new(); + for x in [40.0, 70.0, 100.0] { + tool_event(&mut app, ToolEvent::Move { x, y: 40.0, pressure: 1.0 }, m); + keys.push(display_doc(&mut app, 0).1); + assert!(navigator_waits_for_drag(&app, 0), "painting at x = {x}"); + } + assert!(keys.windows(2).all(|k| k[0] != k[1]), "each step is a new preview: {keys:?}"); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 40.0 }, m); + assert!(!navigator_waits_for_drag(&app, 0), "the navigator catches up on release"); +} + +#[test] +fn smoothed_stroke_shows_its_catch_up_tail_while_drawing() { + // #73: with smoothing the brush lags behind the pointer and catches up at the end; the + // preview draws that tail live, so no frame after release is missing the end. + let xs = [30.0, 50.0, 70.0, 90.0, 110.0, 130.0, 150.0, 170.0]; + let (live, done, partial, _) = drag_frames(0.5, &xs); + assert!(same_pixels(&live, &done), "preview at the last move = committed stroke, tail included"); + assert!(partial); + let end = |d: &Document| (0..200).rev().find(|&x| (0..80).any(|y| d.layers[0].surface().unwrap().rgba(x, y)[3] > 0.0)).unwrap(); + assert!(end(&live) >= 170, "the end reaches the pointer while drawing ({})", end(&live)); + // The options-bar value reaches the stroke: 50 % smooths the wiggle, 0 % doesn't. + let (_, rough, _, _) = drag_frames(0.0, &xs); + assert!(!same_pixels(&rough, &done), "smoothing changes the stroke"); + // And the commit is what `paint.stroke` gives with that smoothing. + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 200, "height": 80, "background": "transparent"})).unwrap(); + s.execute("tools.setBrush", json!({"brush": {"size": 16, "hardness": 0.5, "smoothing": {"amount": 0.5}}})).unwrap(); + let mut pts = vec![json!([10.0, 40.0, 1.0])]; + pts.extend(xs.iter().map(|&x| json!([x, 40.0 + (x / 7.0).sin() * 8.0, 1.0]))); + // (Round tips without dynamics draw the same for any seed.) + s.execute("paint.stroke", json!({"points": pts, "seed": 0})).unwrap(); + assert!(same_pixels(&s.active().unwrap().doc, &done)); +} + +#[test] +fn smoothing_preview_redraws_the_tail_each_step() { + // The tail drawn at one step must not linger once the brush moves on: a sharp turn would + // leave a stale tail behind if it weren't restored. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 120, "background": "transparent"})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 10, "hardness": 1.0, "smoothing": {"amount": 0.6}}})).unwrap(); + app.ui.tool = Tool::Brush; + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 20.0, pressure: 1.0 }, m); + for (x, y) in [(60.0, 20.0), (110.0, 20.0), (110.0, 70.0), (110.0, 110.0), (60.0, 110.0)] { + tool_event(&mut app, ToolEvent::Move { x, y, pressure: 1.0 }, m); + } + let live = display_doc(&mut app, 0).0; + tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 110.0 }, m); + let done = app.session.documents()[0].doc.clone(); + let (a, b) = (live.layers[0].surface().unwrap(), done.layers[0].surface().unwrap()); + assert!((0..120).all(|y| (0..200).all(|x| a.rgba(x, y) == b.rgba(x, y))), "no stale tails in the preview"); +} + +/// Shapes the drag preview paints for `app` this frame. +fn drag_preview_shapes(app: &mut PhotocraftApp, ctx: &egui::Context, zoom: f32) -> Vec { + let out = ctx.run_ui(egui::RawInput::default(), |ui| { + let ctx = ui.ctx(); + let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let painter = ctx.layer_painter(egui::LayerId::background()).with_clip_rect(rect); + let xf = ViewXform { rect, zoom, center: [60.0, 30.0], flip: false, rotation: 0.0, aspect: 1.0 }; + draw_drag_preview(app, &painter, &xf); + }); + let egui::FullOutput { mut textures_delta, shapes, .. } = out; + textures_delta.clear(); + shapes +} + +#[test] +fn a_huge_view_centre_draws_the_selection_outline_without_overflow() { + // #980: `ui.set` takes any finite centre, and the outline's visible region was quantised + // with unchecked i32 arithmetic: the frame panicked ("attempt to multiply/subtract with + // overflow") and release builds wrapped to an inverted region. + let ctx = egui::Context::default(); + // Zoomed far out the quantisation step, and so the padding, is largest (64 · 256 px). + let cases = [([1e30, 1e30], false), ([-1e30, -1e30], false), ([3e9, -3e9], false), ([512.0, 512.0], true)]; + for ((centre, traced), zoom) in cases.into_iter().flat_map(|c| [(c, 1.0), (c, 1.0 / 64.0)]) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 1024, "height": 1024})).unwrap(); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 512, "height": 512})).unwrap(); + app.sync_views(); + let (req, _rx) = crate::control::ControlRequest::new("ui.set", json!({ "center": centre, "zoom": zoom })); + let _ = crate::control::handle(&mut app, &ctx, &req); + let view = app.ui.views[0].clone(); + assert_eq!(view.zoom, zoom, "ui.set applied the zoom"); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + canvas_view(&mut app, ui, 0, Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), view.clone(), false); + }); + out.textures_delta.clear(); + // Control: a centre on the selection's corner still traces the outline (the selection + // spans several 64 px trace cells even zoomed out). + let segs = app.outline_cache.as_ref().map_or(0, |(_, _, s)| s.len()); + assert_eq!(segs > 0, traced, "{centre:?} at zoom {zoom}"); + } +} + +#[test] +fn a_one_pixel_selection_traces_at_hundred_percent_on_a_scaled_display() { + // #1943 review: the outline step is display resolution in device pixels, not points, so a + // 1 px selection still traces at 100 % on a 2x display (a points-based step sampled every + // second pixel and lost it: zero segments). + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("select.rect", json!({"x": 50, "y": 50, "width": 1, "height": 100})).unwrap(); + app.run("view.actualPixels", json!({})).unwrap(); + app.sync_views(); + let view = app.ui.views[0].clone(); + let mut input = egui::RawInput::default(); + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(2.0); + let mut out = ctx.run_ui(input, |ui| { + canvas_view(&mut app, ui, 0, Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), view.clone(), true); + }); + out.textures_delta.clear(); + assert_eq!(app.ppp, 2.0, "the primary canvas records the display scale"); + let segs = app.outline_cache.as_ref().map_or(0, |(_, _, s)| s.len()); + assert!(segs > 0, "a 1 px selection traces at 100 % on a 2x display"); +} + +#[test] +fn a_secondary_canvas_does_not_overwrite_the_main_canvas_scale() { + // #1943 review: a document window can sit on a display with another scale; only the + // primary canvas records `app.ppp`, so the main mapping doesn't change under it. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("view.actualPixels", json!({})).unwrap(); + app.sync_views(); + let view = app.ui.views[0].clone(); + let frame = |app: &mut PhotocraftApp, ppp: f32, primary: bool| { + let mut input = egui::RawInput::default(); + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(ppp); + let mut out = ctx.run_ui(input, |ui| { + canvas_view(app, ui, 0, Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), view.clone(), primary); + }); + out.textures_delta.clear(); + }; + frame(&mut app, 2.0, true); + assert_eq!(app.ppp, 2.0); + frame(&mut app, 1.0, false); + assert_eq!(app.ppp, 2.0, "a secondary window's scale doesn't replace the main canvas's"); + // The main canvas mapping still uses its own scale: 100 % is 1 doc px per physical px. + let xf = ViewXform::active(&app).unwrap(); + let step = xf.to_screen(1.0, 0.0) - xf.to_screen(0.0, 0.0); + assert!((step.x - 0.5).abs() < 1e-3, "{step:?}"); +} + +#[test] +fn a_flicked_hand_drag_glides_on_only_with_flick_panning() { + // #204: Preferences › Tools › Enable Flick Panning. A fast Hand drag let go while moving + // keeps the view gliding for a while; off, the view stops where the drag ended. + for flick in [true, false] { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 2000, "height": 1500})).unwrap(); + app.run("prefs.set", json!({"path": "tools.enableFlickPanning", "value": flick})).unwrap(); + app.ui.tool = Tool::Hand; + app.sync_views(); + let mut view = app.ui.views[0].clone(); + view.zoom = 1.0; + view.center = [1000.0, 750.0]; + view.fit_pending = false; + view.fill_pending = false; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let mut frame = |app: &mut PhotocraftApp, events: Vec| -> View { + let input = egui::RawInput { screen_rect: Some(rect), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + view = canvas_view(app, ui, 0, rect, view.clone(), true); + }); + out.textures_delta.clear(); + view.clone() + }; + 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 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)]).center; + let mut centers = vec![released]; + for _ in 0..5 { + centers.push(frame(&mut app, vec![]).center); + } + if flick { + // Dragged left: the image follows the pointer, the view keeps moving right. + for w in centers.windows(2) { + assert!(w[1][0] > w[0][0], "glides on: {centers:?}"); + } + // ...and comes to rest. + let mut last = *centers.last().unwrap(); + for _ in 0..120 { + last = frame(&mut app, vec![]).center; + } + assert_eq!(frame(&mut app, vec![]).center, last, "the glide stops"); + } else { + assert!(centers.iter().all(|c| *c == released), "no glide when off: {centers:?}"); + } + } +} + +#[test] +fn a_secondary_canvas_hand_pans_while_a_transform_is_open() { + // #2302 review: `app.ui.transform` is global, but only the primary canvas draws and drives + // the box. A secondary window's Hand must still pan while the main window transforms. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.run("view.actualPixels", json!({})).unwrap(); + app.ui.tool = Tool::Hand; + app.sync_views(); + crate::transform_tool::begin(&mut app, &ctx).expect("a transform starts"); + let mut view0 = app.ui.views[0].clone(); + view0.zoom = 1.0; + view0.center = [200.0, 150.0]; + view0.fit_pending = false; + view0.fill_pending = false; + let center0 = view0.center; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let frame = |app: &mut PhotocraftApp, events: Vec| -> View { + let input = egui::RawInput { screen_rect: Some(rect), events, ..Default::default() }; + let mut seen = view0.clone(); + let mut out = ctx.run_ui(input, |ui| { + seen = canvas_view(app, ui, 0, rect, view0.clone(), false); + }); + out.textures_delta.clear(); + seen + }; + 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)]); + for dx in [10.0, 20.0, 40.0] { + frame(&mut app, vec![egui::Event::PointerMoved(start + vec2(dx, 0.0))]); + } + let dragged = frame(&mut app, vec![egui::Event::PointerMoved(start + vec2(60.0, 0.0))]); + frame(&mut app, vec![press(start + vec2(60.0, 0.0), false)]); + assert_ne!(dragged.center, center0, "a secondary window's Hand pans while transforming"); +} + +#[test] +fn letting_go_of_alt_during_an_alt_sample_press_does_not_paint() { + // #7802: Alt-pressing with the Brush samples a colour on the press. If Alt was let go + // before egui recognised the drag, that drag started a stroke from the sampled point. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("view.actualPixels", json!({})).unwrap(); + app.ui.tool = Tool::Brush; + app.sync_views(); + let mut view = app.ui.views[0].clone(); + view.zoom = 1.0; + view.center = [200.0, 150.0]; + view.fit_pending = false; + view.fill_pending = false; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let 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| { + canvas_view(app, ui, 0, rect, view.clone(), true); + }); + out.textures_delta.clear(); + }; + let alt = egui::Modifiers::ALT; + let none = egui::Modifiers::NONE; + let start = Pos2::new(200.0, 150.0); + let press = + |pos: Pos2, pressed: bool, modifiers: egui::Modifiers| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + // Alt released mid-press, and Alt held throughout: both only sample. + for release_alt in [true, false] { + app.run("tools.setColors", json!({"foreground": [0.0, 0.0, 1.0, 1.0]})).unwrap(); + let rev = app.session.active().unwrap().revision; + frame(&mut app, vec![egui::Event::ModifiersChanged(alt), egui::Event::PointerMoved(start)]); + frame(&mut app, vec![press(start, true, alt)]); + assert_eq!(app.session.tools.foreground, [1.0, 1.0, 1.0, 1.0], "the press sampled the white canvas"); + let later = if release_alt { none } else { alt }; + let end = start + vec2(20.0, 0.0); + frame(&mut app, vec![egui::Event::ModifiersChanged(later), egui::Event::PointerMoved(end)]); + frame(&mut app, vec![press(end, false, later)]); + frame(&mut app, vec![egui::Event::ModifiersChanged(none)]); + assert_eq!(app.session.active().unwrap().revision, rev, "release_alt={release_alt}: an Alt-sample press must not paint"); + assert!(app.drag.is_none() && !app.alt_sampling, "release_alt={release_alt}"); + } + // Without Alt the same gesture paints. + let rev = app.session.active().unwrap().revision; + frame(&mut app, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, vec![press(start, true, none)]); + frame(&mut app, vec![egui::Event::PointerMoved(start + vec2(20.0, 0.0))]); + frame(&mut app, vec![press(start + vec2(20.0, 0.0), false, none)]); + assert!(app.session.active().unwrap().revision > rev, "a plain drag paints"); +} + +#[test] +fn letting_go_of_alt_during_a_mixer_brush_sample_press_does_not_paint() { + // As #7802 for the Brush: an Alt-press with the Mixer Brush loads paint from the canvas. + // If Alt was let go before egui recognised the drag, that drag started a Mixer stroke. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("view.actualPixels", json!({})).unwrap(); + app.ui.tool = Tool::MixerBrush; + app.sync_views(); + let mut view = app.ui.views[0].clone(); + view.zoom = 1.0; + view.center = [200.0, 150.0]; + view.fit_pending = false; + view.fill_pending = false; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let 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| { + canvas_view(app, ui, 0, rect, view.clone(), true); + }); + out.textures_delta.clear(); + }; + let (alt, none) = (egui::Modifiers::ALT, egui::Modifiers::NONE); + let start = Pos2::new(200.0, 150.0); + let press = + |pos: Pos2, pressed: bool, modifiers: egui::Modifiers| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + // Alt released mid-press, and Alt held throughout: both only load paint. + for release_alt in [true, false] { + let rev = app.session.active().unwrap().revision; + frame(&mut app, vec![egui::Event::ModifiersChanged(alt), egui::Event::PointerMoved(start)]); + frame(&mut app, vec![press(start, true, alt)]); + let later = if release_alt { none } else { alt }; + let end = start + vec2(20.0, 0.0); + frame(&mut app, vec![egui::Event::ModifiersChanged(later), egui::Event::PointerMoved(end)]); + frame(&mut app, vec![press(end, false, later)]); + frame(&mut app, vec![egui::Event::ModifiersChanged(none)]); + assert_eq!(app.session.active().unwrap().revision, rev, "release_alt={release_alt}: an Alt-sample press must not paint"); + assert!(app.drag.is_none() && !app.mixer_sampling, "release_alt={release_alt}"); + } + // Without Alt the same gesture paints. + let rev = app.session.active().unwrap().revision; + frame(&mut app, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, vec![press(start, true, none)]); + frame(&mut app, vec![egui::Event::PointerMoved(start + vec2(20.0, 0.0))]); + frame(&mut app, vec![press(start + vec2(20.0, 0.0), false, none)]); + assert!(app.session.active().unwrap().revision > rev, "a plain drag paints"); +} + +#[test] +fn guides_draw_over_the_transform_preview_and_under_its_box() { + // #5086: a guide crossing a layer under Free Transform was hidden behind the preview of + // the moving pixels. The preview is image content, drawn before the grid and guides like + // the document is; the box and handles still go over them, as in Photoshop. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 150})).unwrap(); + app.ui.extras.guides = true; + app.ui.extras.rulers = false; + app.sync_views(); + crate::transform_tool::begin(&mut app, &ctx).expect("a transform starts"); + let mut view = app.ui.views[0].clone(); + view.zoom = 1.0; + view.center = [200.0, 150.0]; + view.fit_pending = false; + view.fill_pending = false; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let input = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + canvas_view(&mut app, ui, 0, rect, view.clone(), true); + }); + out.textures_delta.clear(); + // At 100 % centred on the document, screen and document coordinates coincide. + let layer = Rect::from_min_max(pos2(100.0, 100.0), pos2(200.0, 160.0)); + let near = |r: Rect| (r.min - layer.min).length() < 1.0 && (r.max - layer.max).length() < 1.0; + let position = |pred: &dyn Fn(&egui::Shape) -> bool| out.shapes.iter().position(|s| pred(&s.shape)); + // The moving pixels: the mesh that spans the layer's box. + let preview = position(&|s| matches!(s, egui::Shape::Mesh(m) if near(m.calc_bounds()))); + // The guide: a vertical line at x = 150. + let guide = position(&|s| matches!(s, egui::Shape::LineSegment { points, .. } if points.iter().all(|p| (p.x - 150.0).abs() < 0.01))); + // The box: the closed four-point outline round the layer. + let frame = position(&|s| matches!(s, egui::Shape::Path(p) if p.closed && p.points.len() == 4 && near(Rect::from_points(&p.points)))); + let (Some(preview), Some(guide), Some(frame)) = (preview, guide, frame) else { + panic!("all painted: preview {preview:?}, guide {guide:?}, box {frame:?}"); + }; + assert!(preview < guide, "the guide ({guide}) draws over the transform preview ({preview})"); + assert!(guide < frame, "the box ({frame}) draws over the guide ({guide})"); +} + +#[test] +fn guides_draw_over_the_puppet_perspective_and_vanishing_point_previews() { + // #7781: like Free Transform's (#5086), the warped pixels of Puppet Warp and Perspective + // Warp and Vanishing Point's paste are image content. They were drawn with their pins and + // planes, after the guides, hiding every guide across them; the guides now go over them, + // the mesh lines, pins and planes over the guides, as in Photoshop. + for command in ["edit.puppetWarp", "edit.perspectiveWarp", photocraft_engine::vp_cmds::VP] { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + if command == photocraft_engine::vp_cmds::VP { + app.run("edit.copy", json!({})).unwrap(); + } + app.run("select.deselect", json!({})).unwrap(); + app.run("view.newGuide", json!({"orientation": "vertical", "position": 150})).unwrap(); + app.ui.extras.guides = true; + app.ui.extras.rulers = false; + app.sync_views(); + crate::distort_ui::menu(&mut app, &ctx, command, &json!({})).expect("an on-canvas mode").expect("it starts"); + if command == photocraft_engine::vp_cmds::VP { + // A plane over the document; the clipboard pastes onto it. + for (x, y) in [(20.0, 280.0), (380.0, 280.0), (300.0, 40.0), (100.0, 40.0)] { + crate::distort_ui::pointer(&mut app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE); + crate::distort_ui::pointer(&mut app, ToolEvent::Up { x, y }, egui::Modifiers::NONE); + } + } else if command == "edit.perspectiveWarp" { + // One plane, dragged out across the guide. + crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 60.0, y: 70.0, pressure: 1.0 }, egui::Modifiers::NONE); + crate::distort_ui::pointer(&mut app, ToolEvent::Move { x: 240.0, y: 190.0, pressure: 1.0 }, egui::Modifiers::NONE); + crate::distort_ui::pointer(&mut app, ToolEvent::Up { x: 240.0, y: 190.0 }, egui::Modifiers::NONE); + assert_eq!(app.distort.perspective.as_ref().map(|s| s.planes.len()), Some(1), "the drag makes a plane"); + } + let mut view = app.ui.views[0].clone(); + view.zoom = 1.0; + view.center = [200.0, 150.0]; + view.fit_pending = false; + view.fill_pending = false; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let input = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + canvas_view(&mut app, ui, 0, rect, view.clone(), true); + }); + out.textures_delta.clear(); + // At 100 % centred on the document, screen and document coordinates coincide. + let layer = Rect::from_min_max(pos2(100.0, 100.0), pos2(200.0, 160.0)); + // Puppet Warp's mesh reaches its Expansion (2 px) past the pixels. + let near = |r: Rect| (r.min - layer.min).length() < 4.0 && (r.max - layer.max).length() < 4.0; + let shapes: Vec<&egui::Shape> = out.shapes.iter().map(|s| &s.shape).collect(); + // The warped pixels (or the paste): a textured mesh over the layer (or on the plane, + // well inside the document, unlike the checkerboard and document image). + let preview = shapes.iter().position(|s| match s { + egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => { + let r = m.calc_bounds(); + if command == photocraft_engine::vp_cmds::VP { + r.width() > 10.0 && r.width() < 300.0 && r.min.x < 150.0 && r.max.x > 150.0 + } else { + near(r) + } + } + _ => false, + }); + // The guide: a vertical line at x = 150 across the whole view. + let is_guide = |s: &egui::Shape| matches!(s, egui::Shape::LineSegment { points, .. } if points.iter().all(|p| (p.x - 150.0).abs() < 0.01) && (points[1].y - points[0].y).abs() > 200.0); + let guide = shapes.iter().position(|s| is_guide(s)); + // Over the guide: Puppet Warp's mesh lines, the Vanishing Point plane's outline, the + // Perspective Warp plane's outline (exactly the dragged rectangle). + let plane = Rect::from_min_max(pos2(60.0, 70.0), pos2(240.0, 190.0)); + let overlay = shapes.iter().position(|s| match s { + egui::Shape::LineSegment { points, .. } => { + command != "edit.perspectiveWarp" && !is_guide(s) && points.iter().all(|p| layer.expand(3.0).contains(*p)) + } + egui::Shape::Path(p) => { + p.closed + && p.points.len() == 4 + && (command != "edit.perspectiveWarp" + || (Rect::from_points(&p.points).min - plane.min).length() + (Rect::from_points(&p.points).max - plane.max).length() < 0.5) + } + _ => false, + }); + let (Some(preview), Some(guide)) = (preview, guide) else { + panic!("{command}: all painted: preview {preview:?}, guide {guide:?}"); + }; + assert!(preview < guide, "{command}: the guide ({guide}) draws over the warped pixels ({preview})"); + let Some(overlay) = overlay else { panic!("{command}: its mesh or plane is drawn") }; + assert!(guide < overlay, "{command}: the mesh or plane ({overlay}) draws over the guide ({guide})"); + } +} + +#[test] +fn brush_drags_paint_no_stand_in_shape_over_the_canvas() { + // #189: v0.1 drew the stroke being dragged as a foreground-coloured egui polyline as wide + // as the brush; zoomed in, egui tessellated it into hard black wedges fanning out from the + // start. The canvas shows the real stroke (`LiveStroke`) and nothing is drawn over it. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 30, "hardness": 0.0}})).unwrap(); + // A smoothed stroke also draws its string line (see + // `smoothed_brush_drag_draws_the_string_from_brush_to_pointer`): that is no stand-in shape. + let overlay = |app: &mut PhotocraftApp, ctx: &egui::Context| { + drag_preview_shapes(app, ctx, 12.0).iter().filter(|s| !matches!(s.shape, egui::Shape::LineSegment { .. } | egui::Shape::Circle(_))).count() + }; + for tool in [Tool::Brush, Tool::Eraser] { + app.ui.tool = tool; + let idle = overlay(&mut app, &ctx); + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + for i in 1..40 { + let t = f64::from(i); + tool_event(&mut app, ToolEvent::Move { x: 20.0 + t, y: 30.0 + (t / 3.0).sin() * 4.0, pressure: 1.0 }, egui::Modifiers::NONE); + } + assert!(app.live_stroke.is_some(), "{tool:?}: the canvas shows the live stroke"); + assert_eq!(overlay(&mut app, &ctx), idle, "{tool:?}: no overlay while dragging"); + tool_event(&mut app, ToolEvent::Up { x: 59.0, y: 30.0 }, egui::Modifiers::NONE); + } +} + +#[test] +fn smoothed_brush_drag_draws_the_string_from_brush_to_pointer() { + // #3479: with smoothing the brush lags behind the pointer; a line joins them while drawing. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); + app.ui.tool = Tool::Brush; + let lines = |app: &mut PhotocraftApp| drag_preview_shapes(app, &ctx, 4.0).iter().filter(|s| matches!(s.shape, egui::Shape::LineSegment { .. })).count(); + for (amount, string) in [(0.0, false), (0.8, true)] { + app.run("tools.setBrush", json!({"brush": {"size": 10, "smoothing": {"amount": amount}}})).unwrap(); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + for x in [30.0, 60.0, 90.0] { + tool_event(&mut app, ToolEvent::Move { x, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + } + assert_eq!(lines(&mut app) > 0, string, "smoothing {amount}"); + tool_event(&mut app, ToolEvent::Up { x: 90.0, y: 30.0 }, egui::Modifiers::NONE); + } +} + +#[test] +fn retouch_drags_show_the_footprint_without_wedges() { + // The retouching tools' trail was the same brush-wide polyline (#189): now a mask of the + // footprint, with nothing outside the brush radius of the path, however small the steps. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 30}})).unwrap(); + // Remove: the dab tools draw their stroke live instead of a trail, and Spot Healing's + // trail is its dabs' coverage. + app.ui.tool = Tool::Remove; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + let mut pts = vec![[20.0, 30.0]]; + for i in 1..80 { + let t = f64::from(i) * 0.5; + let p = [20.0 + t, 30.0 + (t / 2.0).sin() * 3.0]; + tool_event(&mut app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }, egui::Modifiers::NONE); + pts.push(p); + if i % 20 == 0 { + // One mesh for the trail, however long the drag. + let shapes = drag_preview_shapes(&mut app, &ctx, 12.0); + assert!(!shapes.iter().any(|s| matches!(s.shape, egui::Shape::Path(_))), "no polyline"); + } + } + drag_preview_shapes(&mut app, &ctx, 12.0); + let trail = app.trail.as_ref().unwrap(); + assert_eq!(trail.scale(), 1.0); + for y in 0..60 { + for x in 0..120 { + let d = pts.iter().map(|p| (x as f64 + 0.5 - p[0]).hypot(y as f64 + 0.5 - p[1])).fold(f64::MAX, f64::min); + if d < 14.0 { + assert_eq!(trail.coverage(x, y), 255, "({x}, {y}) inside the footprint"); + } else if d > 16.0 { + assert_eq!(trail.coverage(x, y), 0, "({x}, {y}) outside the footprint"); + } + } + } + tool_event(&mut app, ToolEvent::Up { x: 59.5, y: 30.0 }, egui::Modifiers::NONE); + drag_preview_shapes(&mut app, &ctx, 12.0); + assert!(app.trail.is_none(), "the trail ends with the drag"); +} + +#[test] +fn spot_healing_trail_is_the_coverage_the_heal_uses() { + // #2364: a soft brush with pen-pressure size showed as a hard footprint at full size. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); + let brush = json!({"size": 30, "hardness": 0.0, "shapeDynamics": {"enabled": true, "size": {"control": "penPressure"}}}); + app.run("tools.setBrush", json!({ "brush": brush })).unwrap(); + app.ui.tool = Tool::SpotHealing; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 0.5 }, egui::Modifiers::NONE); + for x in [40.0, 60.0, 80.0] { + tool_event(&mut app, ToolEvent::Move { x, y: 30.0, pressure: 0.5 }, egui::Modifiers::NONE); + drag_preview_shapes(&mut app, &ctx, 12.0); + } + // The stroke the heal gets on release, and its coverage. + let points = app.drag.as_ref().unwrap().points.iter().map(|p| photocraft_paint::StrokePoint::new(p[0], p[1], p[2] as f32)).collect(); + let brush = photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &json!({})); + let (b, cov) = photocraft_paint::retouch::stroke_coverage(&photocraft_paint::Stroke { brush, points }); + let trail = app.trail.as_ref().unwrap(); + let mut soft = 0; + for y in 0..60 { + for x in 0..120 { + let want = if b.contains(x, y) { cov[(y - b.y0) as usize * b.width() as usize + (x - b.x0) as usize] } else { 0.0 }; + let got = trail.coverage(x as usize, y as usize); + assert!((f32::from(got) - want * 255.0).abs() <= 1.0, "({x}, {y}): trail {got}, heal {want}"); + soft += usize::from(got > 0 && got < 200); + } + } + assert!(soft > 50, "a soft brush shows a soft edge"); + // Half pressure halves the 30 px tip: nothing past its (soft) reach. + let reach = photocraft_paint::tip_reach(7.5, app.session.tools.brush.hardness).ceil() as usize + 2; + assert_eq!(trail.coverage(50, 30 + reach), 0, "half pressure halves the 30 px tip"); +} + +#[test] +fn layer_style_dialog_previews_live_and_cancel_restores() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let fx = |d: &Document| d.layers.iter().map(|l| l.effects.items.len()).sum::(); + let id = crate::layer_style::open(&mut app, Some("colorOverlay")).unwrap(); + let (shown, key) = display_doc(&mut app, 0); + assert_eq!((fx(&shown), fx(&app.session.documents()[0].doc)), (1, 0), "previewed, not committed"); + // Adding a stroke through the dialog's instance list re-renders the canvas. + if let Some(d) = app.ui.dialog_mut(id) { + d.fields["effects"].as_array_mut().unwrap().push(json!({"id": "fx9", "kind": "stroke", "on": true, "params": {"size": 3}})); + } + let (shown, key2) = display_doc(&mut app, 0); + assert_eq!(fx(&shown), 2); + assert_ne!(key, key2, "an edit re-renders the canvas"); + app.ui.close_dialog(id); + let (shown, key) = display_doc(&mut app, 0); + assert_eq!((fx(&shown), key), (0, 0)); + assert!(app.style_preview.is_none()); +} + +/// Layer Style opened while Free Transform is open applies the box first, as Photoshop does, +/// so the dialog previews on the transformed layer (#4821): a dropped file (placed in the box, +/// untouched) and a box opened by hand and moved. +#[test] +fn layer_style_opened_during_free_transform_applies_the_box_and_previews() { + for placed in [true, false] { + 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("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); + app.run("edit.fill", json!({"color": "#0000ff"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.sync_views(); + let ctx = egui::Context::default(); + let dx = if placed { + crate::transform_tool::begin_placed(&mut app, &ctx).unwrap(); + 0 + } else { + crate::transform_tool::begin(&mut app, &ctx).unwrap(); + app.ui.transform.as_mut().unwrap().quad = [[28.0, 8.0], [44.0, 8.0], [44.0, 24.0], [28.0, 24.0]]; + 20 + }; + crate::layer_style::open(&mut app, Some("dropShadow")).unwrap(); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "placed {placed}: the box is applied"); + let (shown, _) = display_doc(&mut app, 0); + let rect = photocraft_geom::Rect::new(0, 0, 64, 64); + let with = photocraft_compose::render(&shown, rect); + let without = photocraft_compose::render(&app.session.documents()[0].doc, rect); + assert!( + with.get(16 + dx, 16)[0] < 0.1 && with.get(16 + dx, 16)[2] > 0.9, + "placed {placed}: the blue block where the box left it, not the white under it" + ); + // The shadow darkens the white around the block, which the document doesn't have yet. + let block = |x: i32, y: i32| (8 + dx..24 + dx).contains(&x) && (8..24).contains(&y); + let shadow = + (0..64).flat_map(|y| (0..64).map(move |x| (x, y))).filter(|&(x, y)| !block(x, y) && without.get(x, y)[0] - with.get(x, y)[0] > 0.05).count(); + assert!(shadow > 20, "placed {placed}: the Drop Shadow is previewed ({shadow} px)"); + } +} + +#[test] +fn fill_view_covers_the_canvas_and_centres_the_document() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let mut view = View { fill_pending: true, ..View::default() }; + + fill_view(&mut view, &doc, vec2(600.0, 600.0), 1.0, 1.0); + + assert_eq!(view.zoom, 3.0, "the short edge fills the available height"); + assert_eq!(view.center, [200.0, 100.0]); + assert!(!view.fill_pending); + + // A scaled display stores the physical factor: the same point zoom is 2× the device px. + let mut view = View { fill_pending: true, ..View::default() }; + fill_view(&mut view, &doc, vec2(600.0, 600.0), 2.0, 1.0); + assert_eq!(view.zoom, 6.0); + + // Fit never magnifies past 100% = one image pixel per physical pixel, at any display + // scale (it used to cap at one per *point*, so a 150% display opened images at 150%). + for ppp in [1.0f32, 1.5, 2.0] { + let mut view = View { fit_pending: true, ..View::default() }; + fit_view(&mut view, &doc, vec2(600.0, 600.0), ppp, 1.0); + assert_eq!(view.zoom, 1.0, "ppp {ppp}: a small image opens at 100%"); + } + // A large image still shrinks to fit: 1000×500 into 440 points is 0.44 pt/px, so 0.66 + // physical at ppp 1.5. + let big = { + app.run("file.new", json!({"width": 1000, "height": 500})).unwrap(); + app.session.active().unwrap().doc.clone() + }; + let mut view = View { fit_pending: true, ..View::default() }; + fit_view(&mut view, &big, vec2(480.0, 480.0), 1.5, 1.0); + assert!((view.zoom - 0.66).abs() < 1e-5, "{}", view.zoom); +} + +#[test] +fn a_hundred_percent_is_one_physical_pixel_per_document_pixel() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.sync_views(); + for ppp in [1.0f32, 1.25, 2.0] { + app.ppp = ppp; + let xf = ViewXform::active(&app).unwrap(); + // 100% zoom: one document pixel is one physical pixel, i.e. 1/ppp egui points. + let step = xf.to_screen(1.0, 0.0) - xf.to_screen(0.0, 0.0); + // `to_screen` differences around the view centre cancel in f32; 1e-3 is still exact + // enough to see a wrong ppp factor (which would be a 20–100% error). + assert!((step.x - 1.0 / ppp).abs() < 1e-3, "ppp {ppp}: {step:?} want {:?}", 1.0 / ppp); + assert!((app.point_zoom() - 1.0 / ppp).abs() < 1e-5, "ppp {ppp}: {}", app.point_zoom()); + // Screen ↔ document stays an exact round trip. + let back = xf.to_doc(xf.to_screen(123.0, 45.0)); + assert!((back[0] - 123.0).abs() < 1e-3 && (back[1] - 45.0).abs() < 1e-3, "ppp {ppp}: {back:?}"); + } +} + +#[test] +fn wheel_anchor_is_the_pointer_over_the_image_and_the_nearest_image_point_off_it() { + let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + for (rotation, flip) in [(0.0, false), (30.0, false), (90.0, true)] { + let xf = ViewXform { rect, zoom: 0.5, center: [400.0, 300.0], flip, rotation, aspect: 1.0 }; + let inside = xf.to_screen(100.0, 200.0); + assert_eq!(wheel_anchor(&xf, inside, [800, 600]), inside); + for (p, want) in [((-300.0, -200.0), [0.0, 0.0]), ((1200.0, 300.0), [800.0, 300.0]), ((400.0, 900.0), [400.0, 600.0])] { + let a = xf.to_doc(wheel_anchor(&xf, xf.to_screen(p.0, p.1), [800, 600])); + assert!((a[0] - want[0]).abs() < 0.01 && (a[1] - want[1]).abs() < 0.01, "rot {rotation}: {p:?} -> {a:?}"); + } + } + let p = pos2(5.0, 5.0); + let xf = ViewXform { rect, zoom: 1.0, center: [400.0, 300.0], flip: false, rotation: 0.0, aspect: 1.0 }; + assert_eq!(wheel_anchor(&xf, p, [0, 0]), p, "no document: the pointer"); +} + +#[test] +fn zoom_about_centres_the_clicked_point_with_the_preference() { + let rect = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let p = pos2(600.0, 200.0); + for ppp in [1.0f32, 2.0] { + // `View::zoom` is physical; the transform works in points. + let xf = ViewXform { rect, zoom: 1.0 / ppp, center: [400.0, 300.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let doc = xf.to_doc(p); + // Off: the document point under the pointer stays under it. + let mut view = View { zoom: 1.0, center: [400.0, 300.0], ..Default::default() }; + zoom_about(&mut view, &xf, p, 2.0, false, ppp); + let after = ViewXform { rect, zoom: 2.0 / ppp, center: view.center, flip: false, rotation: 0.0, aspect: 1.0 }; + let s = after.to_screen(doc[0] as f32, doc[1] as f32); + assert!((s - p).length() < 0.5, "ppp {ppp}: {s:?} vs {p:?}"); + // On: the clicked point is the view centre. + let mut view = View { zoom: 1.0, center: [400.0, 300.0], ..Default::default() }; + zoom_about(&mut view, &xf, p, 2.0, true, ppp); + assert!((view.center[0] - doc[0] as f32).abs() < 0.5, "ppp {ppp}: {:?}", view.center); + assert!((view.center[1] - doc[1] as f32).abs() < 0.5, "ppp {ppp}: {:?}", view.center); + } +} + +#[test] +fn damage_grows_by_nested_effect_reach() { + use photocraft_doc::{Effect, Layer}; + let fmt = photocraft_color::PixelFormat::RGBA8; + assert_eq!(effect_reach(&[Layer::raster("plain", fmt)]), 0); + let mut inner = Layer::raster("inner", fmt); + inner.effects.items.push(Effect::default_drop_shadow()); + let m = photocraft_compose::effects::margin(&inner); + let mut group = Layer::group("g", vec![inner.clone()]); + group.effects.items.push(Effect::default_drop_shadow()); + assert_eq!(effect_reach(std::slice::from_ref(&inner)), m); + // A child's edit moves the group's shape, whose effects reach further. + assert_eq!(effect_reach(&[group.clone()]), 2 * m); + group.visible = false; + assert_eq!(effect_reach(&[group]), 0); +} From e285fb5251a19cd43d514db533ee049c1afba269 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:46 +0000 Subject: [PATCH 064/259] refactor(ui-egui): move canvas.rs transform_controls_tests to canvas/transform_controls_tests.rs --- crates/ui-egui/src/canvas.rs | 360 +----------------- .../src/canvas/transform_controls_tests.rs | 357 +++++++++++++++++ 2 files changed, 358 insertions(+), 359 deletions(-) create mode 100644 crates/ui-egui/src/canvas/transform_controls_tests.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 7454639278..e71a5253c2 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -7093,365 +7093,7 @@ mod tabs_tests; mod tests; #[cfg(test)] -mod transform_controls_tests { - use super::*; - use serde_json::json; - - /// #7538: as in Photoshop, the box frames a loose selection until its pixels are moved, then - /// the pixels themselves, while they float and once dropped. - #[test] - fn transform_controls_frame_the_moved_pixels_not_the_marquee() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap(); - app.session.execute("select.rect", json!({"x": 40, "y": 40, "width": 50, "height": 40})).unwrap(); - app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.session.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); - app.sync_views(); - app.ui.tool = Tool::Move; - app.ui.tool_options.move_show_transform = true; - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let frame = |app: &PhotocraftApp| { - let r = transform_controls_rect(app, &xf).unwrap(); - let (lt, rb) = (xf.to_doc(r.left_top()), xf.to_doc(r.right_bottom())); - [lt[0], lt[1], rb[0], rb[1]].map(|v| v.round() as i32) - }; - assert_eq!(frame(&app), [20, 20, 120, 110], "the selection, before anything moves"); - app.run("select.float", json!({"dx": 10, "dy": 5})).unwrap(); - assert_eq!(frame(&app), [50, 45, 100, 85], "the floating pixels"); - app.run("select.drop", json!({})).unwrap(); - assert_eq!(frame(&app), [50, 45, 100, 85], "dropped"); - } - - /// #7538: with several layers selected the Move tool moves them whole, and the selection goes - /// with them, as in Photoshop: its ants follow the drag and it lands with them in one step. - #[test] - fn moving_several_layers_carries_the_selection() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap(); - let a = app.session.active().unwrap().active_layer.unwrap(); - app.session.execute("select.rect", json!({"x": 40, "y": 40, "width": 50, "height": 40})).unwrap(); - app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session.execute("select.rect", json!({"x": 120, "y": 120, "width": 30, "height": 30})).unwrap(); - app.session.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - app.session.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); - app.session.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); - app.sync_views(); - app.ui.tool = Tool::Move; - app.ui.tool_options.move_auto_select = false; - app.ui.extras.snap = false; - app.ui.view.show.smart_guides = false; - let steps = app.session.active().unwrap().history.past_len(); - let m = egui::Modifiers::NONE; - tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Move { x: 72.0, y: 68.0, pressure: 1.0 }, m); - assert_eq!(selection_shown_offset(&app), Some((12, 8)), "the ants follow the layers"); - tool_event(&mut app, ToolEvent::Up { x: 72.0, y: 68.0 }, m); - let st = app.session.active().unwrap(); - assert!(photocraft_engine::float_cmds::floating(st).is_none(), "whole layers moved, nothing floats"); - assert_eq!(st.doc.selection.as_ref().map(|s| s.content_bounds()), Some(photocraft_geom::Rect::new(32, 28, 132, 118))); - assert_eq!(st.doc.layer(a).unwrap().surface().unwrap().content_bounds(), photocraft_geom::Rect::new(52, 48, 102, 88)); - assert_eq!(st.history.past_len(), steps + 1, "one Move step"); - assert!(app.session.undo()); - let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds()); - assert_eq!(sel, Some(photocraft_geom::Rect::new(20, 20, 120, 110)), "Undo takes the selection back too"); - - // A piece floating (a marquee ⌘-drag with both selected) when the layers are dragged: the - // press drops it first, so the ants follow the drag from where it was dropped. - app.run("select.float", json!({"dx": 10, "dy": 5})).unwrap(); - let outline = photocraft_engine::float_cmds::floating(app.session.active().unwrap()).unwrap().parts.outline().unwrap().content_bounds(); - tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); - let st = app.session.active().unwrap(); - assert!(photocraft_engine::float_cmds::floating(st).is_none(), "the press dropped the piece"); - assert_eq!(st.doc.selection.as_ref().map(|s| s.content_bounds()), Some(outline.translate(10, 5)), "at its offset"); - tool_event(&mut app, ToolEvent::Move { x: 72.0, y: 68.0, pressure: 1.0 }, m); - assert_eq!(selection_shown_offset(&app), Some((12, 8)), "then the ants follow the drag"); - tool_event(&mut app, ToolEvent::Up { x: 72.0, y: 68.0 }, m); - let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds()); - assert_eq!(sel, Some(outline.translate(22, 13)), "released where the ants were"); - } - - /// A transparent 200² document: a red square (40..90, 40..80) on its layer, a loose marquee - /// (20..120, 20..110) round it, cut and floated 10, 5 to the right and down. - fn floating_square() -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap(); - app.session.execute("select.rect", json!({"x": 40, "y": 40, "width": 50, "height": 40})).unwrap(); - app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.session.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); - app.sync_views(); - app.session.execute("select.float", json!({"dx": 10, "dy": 5})).unwrap(); - app - } - - /// #7538: a selection tool's press on a floating piece's ants drags it; one in the margin its - /// cut left of the loose marquee draws a new selection, as the ants say. - #[test] - fn a_press_in_the_margin_of_a_floating_piece_starts_a_new_selection() { - let app = floating_square(); - let none = egui::Modifiers::NONE; - for tool in [Tool::RectMarquee, Tool::Lasso] { - assert_eq!(selection_drag_kind(&app, tool, [70.0, 60.0], none), Some(true), "{tool:?}: on the square drags it"); - assert_eq!(selection_drag_kind(&app, tool, [33.0, 28.0], none), None, "{tool:?}: in the old marquee's margin"); - } - } - - /// Several selected layers keep one frame round them all while the active one's pixels float: - /// the piece's outline frames it only when it is the only layer framed. - #[test] - fn a_floating_piece_among_several_selected_layers_keeps_the_shared_frame() { - let mut app = floating_square(); - app.session.execute("select.drop", json!({})).unwrap(); - let a = app.session.active().unwrap().active_layer.unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session.execute("select.rect", json!({"x": 150, "y": 150, "width": 20, "height": 20})).unwrap(); - app.session.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - app.session.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); - app.session.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); - app.ui.tool = Tool::Move; - app.ui.tool_options.move_show_transform = true; - assert!(transform_controls_several(&app), "two layers framed"); - app.session.execute("select.float", json!({"dx": 5, "dy": 0})).unwrap(); - assert!(photocraft_engine::float_cmds::floating(app.session.active().unwrap()).is_some()); - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let r = transform_controls_rect(&app, &xf).unwrap(); - let (lt, rb) = (xf.to_doc(r.left_top()), xf.to_doc(r.right_bottom())); - assert!(rb[0] - lt[0] > 60.0 && rb[1] - lt[1] > 60.0, "the frame isn't shrunk to the one piece: {lt:?} {rb:?}"); - } - - #[test] - fn several_selected_layers_share_one_frame_without_handles() { - // As in Photoshop: Show Transform Controls frames every selected layer. Free Transform - // works on one layer, so the shared frame doesn't start it. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 40, 40], "fill": "#ff0000"})).unwrap(); - let a = app.session.active().unwrap().active_layer.unwrap(); - app.session.execute("shape.create", json!({"kind": "rect", "rect": [100, 120, 50, 30], "fill": "#ff0000"})).unwrap(); - app.sync_views(); - app.ui.tool = Tool::Move; - app.ui.tool_options.move_show_transform = true; - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let one = transform_controls_rect(&app, &xf).unwrap(); - assert!(!transform_controls_several(&app)); - app.session.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); - assert!(transform_controls_several(&app)); - let both = transform_controls_rect(&app, &xf).unwrap(); - assert!(both.contains_rect(one) && both.width() > one.width() && both.height() > one.height(), "{both:?} frames both"); - let (lt, rb) = (xf.to_doc(both.left_top()), xf.to_doc(both.right_bottom())); - assert!((lt[0] - 20.0).abs() < 1e-3 && (lt[1] - 30.0).abs() < 1e-3 && (rb[0] - 150.0).abs() < 1e-3 && (rb[1] - 150.0).abs() < 1e-3, "{lt:?} {rb:?}"); - let ctx = egui::Context::default(); - assert!(!begin_transform_controls_at(&mut app, &ctx, &xf, both.right_bottom())); - assert!(app.ui.transform.is_none()); - // The Background never joins the frame. - let bg = app.session.active().unwrap().doc.layers[0].id; - app.session.execute("layer.select", json!({"layer": bg.0, "mode": "add"})).unwrap(); - assert_eq!(transform_controls_layers(&app).len(), 2); - } - - #[test] - fn move_transform_controls_start_free_transform_for_vector_shapes() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 80, 40], "fill": "#ff0000"})).unwrap(); - app.sync_views(); - app.ui.tool = Tool::Move; - app.ui.tool_options.move_show_transform = true; - - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let r = transform_controls_rect(&app, &xf).expect("shape layers have transform bounds"); - assert!(transform_controls_hit(r, r.right_bottom())); - - let ctx = egui::Context::default(); - assert!(begin_transform_controls_at(&mut app, &ctx, &xf, r.right_bottom())); - let t = app.ui.transform.as_ref().expect("control press starts Free Transform"); - assert_eq!(t.rect, [20.0, 30.0, 100.0, 70.0]); - } - - #[test] - fn hiding_extras_hides_the_move_transform_controls() { - // #6699: as in Photoshop, View › Extras (⌘H) hides the Move tool's transform box and - // handles; again brings them back. Show Transform Controls and the layer stay as they were. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 80, 40], "fill": "#ff0000"})).unwrap(); - app.sync_views(); - app.ui.tool = Tool::Move; - app.ui.tool_options.move_show_transform = true; - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let ctx = egui::Context::default(); - let shown = transform_controls_rect(&app, &xf).expect("the box shows with Extras on"); - let layer = app.session.active().unwrap().doc.layers.clone(); - let painted = |app: &mut PhotocraftApp| { - let out = ctx.run_ui(egui::RawInput::default(), |ui| { - let painter = ui.ctx().layer_painter(egui::LayerId::background()); - draw_transform_controls(app, &painter, &xf); - }); - let egui::FullOutput { mut textures_delta, shapes, .. } = out; - textures_delta.clear(); - shapes.len() - }; - // The shape's outline, the box and its eight handles. - assert!(painted(&mut app) > 8, "the box and handles are drawn"); - - crate::menus::invoke(&mut app, &ctx, "view.extras", json!({})).unwrap(); - assert!(!app.ui.view.extras); - assert!(transform_controls_rect(&app, &xf).is_none(), "no box with Extras hidden"); - assert_eq!(painted(&mut app), 0, "nothing is drawn"); - // Hidden handles don't act: a press on a corner doesn't start Free Transform. - assert!(!begin_transform_controls_at(&mut app, &ctx, &xf, shown.right_bottom())); - assert!(app.ui.transform.is_none()); - assert!(app.ui.tool_options.move_show_transform, "Show Transform Controls is unchanged"); - assert_eq!(app.session.active().unwrap().doc.layers, layer, "the layer is unchanged"); - - crate::menus::invoke(&mut app, &ctx, "view.extras", json!({})).unwrap(); - assert!(app.ui.view.extras); - assert_eq!(transform_controls_rect(&app, &xf), Some(shown), "⌘H again restores the box"); - } - - #[test] - fn move_transform_controls_follow_floating_selected_pixels() { - 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("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.ui.tool = Tool::Move; - app.ui.tool_options.move_show_transform = true; - assert!(crate::move_ui::float_selected(&mut app, false, 100.0, 50.0)); - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), zoom: 1.0, center: [200.0, 150.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let r = transform_controls_rect(&app, &xf).unwrap(); - assert_eq!(r, Rect::from_min_max(pos2(200.0, 150.0), pos2(300.0, 210.0))); - let ctx = egui::Context::default(); - assert!(begin_transform_controls_at(&mut app, &ctx, &xf, r.right_bottom())); - assert_eq!(app.ui.transform.as_ref().unwrap().rect, [200.0, 150.0, 300.0, 210.0]); - } - - /// #5297: with a selection the Move tool's transform controls are the selection's rectangle, - /// though the layer fills only part of it, and a press on them opens that box. - #[test] - fn move_transform_controls_frame_the_selection() { - 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("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.run("select.rect", json!({"x": 60, "y": 80, "width": 100, "height": 120})).unwrap(); - app.ui.tool = Tool::Move; - app.ui.tool_options.move_show_transform = true; - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), zoom: 1.0, center: [200.0, 150.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let r = transform_controls_rect(&app, &xf).unwrap(); - assert_eq!(r, Rect::from_min_max(pos2(60.0, 80.0), pos2(160.0, 200.0))); - let ctx = egui::Context::default(); - assert!(begin_transform_controls_at(&mut app, &ctx, &xf, r.right_bottom())); - assert_eq!(app.ui.transform.as_ref().unwrap().rect, [60.0, 80.0, 160.0, 200.0]); - } - - /// #2585: Free Transform on a position-locked layer is refused before the box opens, with - /// Photoshop's alert, from ⌘T and from the Move tool's transform controls alike. It used to - /// open, preview every drag and fail only at commit. - #[test] - fn free_transform_on_a_locked_layer_is_refused_up_front() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 80, 40], "fill": "#ff0000"})).unwrap(); - app.session - .edit("lock", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().locks.position = true; - Ok(()) - }) - .unwrap(); - app.sync_views(); - let errors = |app: &PhotocraftApp| -> Vec { - app.ui - .dialogs - .iter() - .filter(|d| d.kind == crate::state::DialogKind::Error) - .filter_map(|d| d.fields.get("message")?.as_str().map(String::from)) - .collect() - }; - let ctx = egui::Context::default(); - // ⌘T. - let r = crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})); - assert_eq!(r, Err(crate::transform_tool::LOCKED.to_string())); - assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "no box opened"); - assert_eq!(errors(&app), [crate::transform_tool::LOCKED]); - app.ui.dialogs.clear(); - // The Move tool's transform controls. - app.ui.tool = Tool::Move; - app.ui.tool_options.move_show_transform = true; - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; - let r = transform_controls_rect(&app, &xf).unwrap(); - assert!(!begin_transform_controls_at(&mut app, &ctx, &xf, r.right_bottom())); - assert!(app.ui.transform.is_none()); - assert_eq!(errors(&app), [crate::transform_tool::LOCKED]); - } - - #[test] - fn move_transform_controls_show_resize_and_rotate_cursors_before_first_interaction() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); - app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 80, 40], "fill": "#ff0000"})).unwrap(); - app.sync_views(); - app.ui.tool = Tool::Move; - app.ui.tool_options.move_show_transform = true; - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; - - let r = transform_controls_rect(&app, &xf).expect("visible shape controls"); - assert!(app.ui.transform.is_none(), "no transform session is needed for hover"); - for (p, expected) in [ - (r.left_top(), egui::CursorIcon::ResizeNwSe), - (r.right_bottom(), egui::CursorIcon::ResizeNwSe), - (r.right_top(), egui::CursorIcon::ResizeNeSw), - (r.left_bottom(), egui::CursorIcon::ResizeNeSw), - (r.center_top(), egui::CursorIcon::ResizeVertical), - (r.center_bottom(), egui::CursorIcon::ResizeVertical), - (r.right_center(), egui::CursorIcon::ResizeHorizontal), - (r.left_center(), egui::CursorIcon::ResizeHorizontal), - // Between handles: the rotation band (a point above the top-centre handle is that handle), - // where the curved rotate arrow replaces the pointer (#4658). - (pos2(r.left() + r.width() * 0.25, r.top() - 12.0), egui::CursorIcon::None), - ] { - assert_eq!(transform_controls_cursor(r, p), Some(expected), "hover at {p:?}"); - assert!(transform_controls_hit(r, p), "same region must start a transform"); - } - assert_eq!(transform_controls_cursor(r, r.center()), None, "interior stays Move"); - assert_eq!(transform_controls_cursor(r, pos2(r.center().x, r.top() - 30.0)), None); - // The rotate arrow bends round the nearest corner, pointing into the box; handles and the - // interior have none. - let into = |p: Pos2| transform_controls_turn(r, p).map(|v| (v.x.signum(), v.y.signum())); - assert_eq!(into(pos2(r.left() + r.width() * 0.25, r.top() - 12.0)), Some((1.0, 1.0)), "top left"); - assert_eq!(into(pos2(r.right() + 12.0, r.bottom() - r.height() * 0.25)), Some((-1.0, -1.0)), "bottom right"); - assert_eq!(into(pos2(r.left() - 12.0, r.bottom() + 12.0)), Some((1.0, -1.0)), "beyond the bottom-left corner"); - assert_eq!(into(r.left_top()), None); - assert_eq!(into(r.center()), None); - - // Changing the active shape changes the hover bounds without requiring a drag first. - app.session.execute("shape.create", json!({"kind": "rect", "rect": [120, 100, 40, 50], "fill": "#00ff00"})).unwrap(); - let next = transform_controls_rect(&app, &xf).expect("new active shape controls"); - assert_ne!(r, next); - assert_eq!(transform_controls_cursor(next, next.right_bottom()), Some(egui::CursorIcon::ResizeNwSe)); - assert_eq!(transform_controls_cursor(next, next.center()), None); - } - - #[test] - fn transform_control_hit_keeps_move_interior_free_and_has_rotation_band() { - let r = Rect::from_min_max(pos2(20.0, 30.0), pos2(100.0, 70.0)); - assert!(transform_controls_hit(r, r.left_top())); - assert!(transform_controls_hit(r, pos2(60.0, 18.0))); - assert!(!transform_controls_hit(r, r.center())); - assert!(!transform_controls_hit(r, pos2(60.0, 4.0))); - } -} +mod transform_controls_tests; #[cfg(test)] mod layer_edges_tests; diff --git a/crates/ui-egui/src/canvas/transform_controls_tests.rs b/crates/ui-egui/src/canvas/transform_controls_tests.rs new file mode 100644 index 0000000000..957ae3589d --- /dev/null +++ b/crates/ui-egui/src/canvas/transform_controls_tests.rs @@ -0,0 +1,357 @@ +use super::*; +use serde_json::json; + +/// #7538: as in Photoshop, the box frames a loose selection until its pixels are moved, then +/// the pixels themselves, while they float and once dropped. +#[test] +fn transform_controls_frame_the_moved_pixels_not_the_marquee() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap(); + app.session.execute("select.rect", json!({"x": 40, "y": 40, "width": 50, "height": 40})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let frame = |app: &PhotocraftApp| { + let r = transform_controls_rect(app, &xf).unwrap(); + let (lt, rb) = (xf.to_doc(r.left_top()), xf.to_doc(r.right_bottom())); + [lt[0], lt[1], rb[0], rb[1]].map(|v| v.round() as i32) + }; + assert_eq!(frame(&app), [20, 20, 120, 110], "the selection, before anything moves"); + app.run("select.float", json!({"dx": 10, "dy": 5})).unwrap(); + assert_eq!(frame(&app), [50, 45, 100, 85], "the floating pixels"); + app.run("select.drop", json!({})).unwrap(); + assert_eq!(frame(&app), [50, 45, 100, 85], "dropped"); +} + +/// #7538: with several layers selected the Move tool moves them whole, and the selection goes +/// with them, as in Photoshop: its ants follow the drag and it lands with them in one step. +#[test] +fn moving_several_layers_carries_the_selection() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap(); + let a = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("select.rect", json!({"x": 40, "y": 40, "width": 50, "height": 40})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.execute("select.rect", json!({"x": 120, "y": 120, "width": 30, "height": 30})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + app.session.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); + app.session.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_auto_select = false; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + let steps = app.session.active().unwrap().history.past_len(); + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 72.0, y: 68.0, pressure: 1.0 }, m); + assert_eq!(selection_shown_offset(&app), Some((12, 8)), "the ants follow the layers"); + tool_event(&mut app, ToolEvent::Up { x: 72.0, y: 68.0 }, m); + let st = app.session.active().unwrap(); + assert!(photocraft_engine::float_cmds::floating(st).is_none(), "whole layers moved, nothing floats"); + assert_eq!(st.doc.selection.as_ref().map(|s| s.content_bounds()), Some(photocraft_geom::Rect::new(32, 28, 132, 118))); + assert_eq!(st.doc.layer(a).unwrap().surface().unwrap().content_bounds(), photocraft_geom::Rect::new(52, 48, 102, 88)); + assert_eq!(st.history.past_len(), steps + 1, "one Move step"); + assert!(app.session.undo()); + let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds()); + assert_eq!(sel, Some(photocraft_geom::Rect::new(20, 20, 120, 110)), "Undo takes the selection back too"); + + // A piece floating (a marquee ⌘-drag with both selected) when the layers are dragged: the + // press drops it first, so the ants follow the drag from where it was dropped. + app.run("select.float", json!({"dx": 10, "dy": 5})).unwrap(); + let outline = photocraft_engine::float_cmds::floating(app.session.active().unwrap()).unwrap().parts.outline().unwrap().content_bounds(); + tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m); + let st = app.session.active().unwrap(); + assert!(photocraft_engine::float_cmds::floating(st).is_none(), "the press dropped the piece"); + assert_eq!(st.doc.selection.as_ref().map(|s| s.content_bounds()), Some(outline.translate(10, 5)), "at its offset"); + tool_event(&mut app, ToolEvent::Move { x: 72.0, y: 68.0, pressure: 1.0 }, m); + assert_eq!(selection_shown_offset(&app), Some((12, 8)), "then the ants follow the drag"); + tool_event(&mut app, ToolEvent::Up { x: 72.0, y: 68.0 }, m); + let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds()); + assert_eq!(sel, Some(outline.translate(22, 13)), "released where the ants were"); +} + +/// A transparent 200² document: a red square (40..90, 40..80) on its layer, a loose marquee +/// (20..120, 20..110) round it, cut and floated 10, 5 to the right and down. +fn floating_square() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap(); + app.session.execute("select.rect", json!({"x": 40, "y": 40, "width": 50, "height": 40})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + app.sync_views(); + app.session.execute("select.float", json!({"dx": 10, "dy": 5})).unwrap(); + app +} + +/// #7538: a selection tool's press on a floating piece's ants drags it; one in the margin its +/// cut left of the loose marquee draws a new selection, as the ants say. +#[test] +fn a_press_in_the_margin_of_a_floating_piece_starts_a_new_selection() { + let app = floating_square(); + let none = egui::Modifiers::NONE; + for tool in [Tool::RectMarquee, Tool::Lasso] { + assert_eq!(selection_drag_kind(&app, tool, [70.0, 60.0], none), Some(true), "{tool:?}: on the square drags it"); + assert_eq!(selection_drag_kind(&app, tool, [33.0, 28.0], none), None, "{tool:?}: in the old marquee's margin"); + } +} + +/// Several selected layers keep one frame round them all while the active one's pixels float: +/// the piece's outline frames it only when it is the only layer framed. +#[test] +fn a_floating_piece_among_several_selected_layers_keeps_the_shared_frame() { + let mut app = floating_square(); + app.session.execute("select.drop", json!({})).unwrap(); + let a = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.execute("select.rect", json!({"x": 150, "y": 150, "width": 20, "height": 20})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + app.session.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); + app.session.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + assert!(transform_controls_several(&app), "two layers framed"); + app.session.execute("select.float", json!({"dx": 5, "dy": 0})).unwrap(); + assert!(photocraft_engine::float_cmds::floating(app.session.active().unwrap()).is_some()); + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let r = transform_controls_rect(&app, &xf).unwrap(); + let (lt, rb) = (xf.to_doc(r.left_top()), xf.to_doc(r.right_bottom())); + assert!(rb[0] - lt[0] > 60.0 && rb[1] - lt[1] > 60.0, "the frame isn't shrunk to the one piece: {lt:?} {rb:?}"); +} + +#[test] +fn several_selected_layers_share_one_frame_without_handles() { + // As in Photoshop: Show Transform Controls frames every selected layer. Free Transform + // works on one layer, so the shared frame doesn't start it. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 40, 40], "fill": "#ff0000"})).unwrap(); + let a = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("shape.create", json!({"kind": "rect", "rect": [100, 120, 50, 30], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let one = transform_controls_rect(&app, &xf).unwrap(); + assert!(!transform_controls_several(&app)); + app.session.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); + assert!(transform_controls_several(&app)); + let both = transform_controls_rect(&app, &xf).unwrap(); + assert!(both.contains_rect(one) && both.width() > one.width() && both.height() > one.height(), "{both:?} frames both"); + let (lt, rb) = (xf.to_doc(both.left_top()), xf.to_doc(both.right_bottom())); + assert!((lt[0] - 20.0).abs() < 1e-3 && (lt[1] - 30.0).abs() < 1e-3 && (rb[0] - 150.0).abs() < 1e-3 && (rb[1] - 150.0).abs() < 1e-3, "{lt:?} {rb:?}"); + let ctx = egui::Context::default(); + assert!(!begin_transform_controls_at(&mut app, &ctx, &xf, both.right_bottom())); + assert!(app.ui.transform.is_none()); + // The Background never joins the frame. + let bg = app.session.active().unwrap().doc.layers[0].id; + app.session.execute("layer.select", json!({"layer": bg.0, "mode": "add"})).unwrap(); + assert_eq!(transform_controls_layers(&app).len(), 2); +} + +#[test] +fn move_transform_controls_start_free_transform_for_vector_shapes() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 80, 40], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let r = transform_controls_rect(&app, &xf).expect("shape layers have transform bounds"); + assert!(transform_controls_hit(r, r.right_bottom())); + + let ctx = egui::Context::default(); + assert!(begin_transform_controls_at(&mut app, &ctx, &xf, r.right_bottom())); + let t = app.ui.transform.as_ref().expect("control press starts Free Transform"); + assert_eq!(t.rect, [20.0, 30.0, 100.0, 70.0]); +} + +#[test] +fn hiding_extras_hides_the_move_transform_controls() { + // #6699: as in Photoshop, View › Extras (⌘H) hides the Move tool's transform box and + // handles; again brings them back. Show Transform Controls and the layer stay as they were. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 80, 40], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let ctx = egui::Context::default(); + let shown = transform_controls_rect(&app, &xf).expect("the box shows with Extras on"); + let layer = app.session.active().unwrap().doc.layers.clone(); + let painted = |app: &mut PhotocraftApp| { + let out = ctx.run_ui(egui::RawInput::default(), |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::background()); + draw_transform_controls(app, &painter, &xf); + }); + let egui::FullOutput { mut textures_delta, shapes, .. } = out; + textures_delta.clear(); + shapes.len() + }; + // The shape's outline, the box and its eight handles. + assert!(painted(&mut app) > 8, "the box and handles are drawn"); + + crate::menus::invoke(&mut app, &ctx, "view.extras", json!({})).unwrap(); + assert!(!app.ui.view.extras); + assert!(transform_controls_rect(&app, &xf).is_none(), "no box with Extras hidden"); + assert_eq!(painted(&mut app), 0, "nothing is drawn"); + // Hidden handles don't act: a press on a corner doesn't start Free Transform. + assert!(!begin_transform_controls_at(&mut app, &ctx, &xf, shown.right_bottom())); + assert!(app.ui.transform.is_none()); + assert!(app.ui.tool_options.move_show_transform, "Show Transform Controls is unchanged"); + assert_eq!(app.session.active().unwrap().doc.layers, layer, "the layer is unchanged"); + + crate::menus::invoke(&mut app, &ctx, "view.extras", json!({})).unwrap(); + assert!(app.ui.view.extras); + assert_eq!(transform_controls_rect(&app, &xf), Some(shown), "⌘H again restores the box"); +} + +#[test] +fn move_transform_controls_follow_floating_selected_pixels() { + 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("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + assert!(crate::move_ui::float_selected(&mut app, false, 100.0, 50.0)); + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), zoom: 1.0, center: [200.0, 150.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let r = transform_controls_rect(&app, &xf).unwrap(); + assert_eq!(r, Rect::from_min_max(pos2(200.0, 150.0), pos2(300.0, 210.0))); + let ctx = egui::Context::default(); + assert!(begin_transform_controls_at(&mut app, &ctx, &xf, r.right_bottom())); + assert_eq!(app.ui.transform.as_ref().unwrap().rect, [200.0, 150.0, 300.0, 210.0]); +} + +/// #5297: with a selection the Move tool's transform controls are the selection's rectangle, +/// though the layer fills only part of it, and a press on them opens that box. +#[test] +fn move_transform_controls_frame_the_selection() { + 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("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.rect", json!({"x": 60, "y": 80, "width": 100, "height": 120})).unwrap(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), zoom: 1.0, center: [200.0, 150.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let r = transform_controls_rect(&app, &xf).unwrap(); + assert_eq!(r, Rect::from_min_max(pos2(60.0, 80.0), pos2(160.0, 200.0))); + let ctx = egui::Context::default(); + assert!(begin_transform_controls_at(&mut app, &ctx, &xf, r.right_bottom())); + assert_eq!(app.ui.transform.as_ref().unwrap().rect, [60.0, 80.0, 160.0, 200.0]); +} + +/// #2585: Free Transform on a position-locked layer is refused before the box opens, with +/// Photoshop's alert, from ⌘T and from the Move tool's transform controls alike. It used to +/// open, preview every drag and fail only at commit. +#[test] +fn free_transform_on_a_locked_layer_is_refused_up_front() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 80, 40], "fill": "#ff0000"})).unwrap(); + app.session + .edit("lock", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().locks.position = true; + Ok(()) + }) + .unwrap(); + app.sync_views(); + let errors = |app: &PhotocraftApp| -> Vec { + app.ui + .dialogs + .iter() + .filter(|d| d.kind == crate::state::DialogKind::Error) + .filter_map(|d| d.fields.get("message")?.as_str().map(String::from)) + .collect() + }; + let ctx = egui::Context::default(); + // ⌘T. + let r = crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})); + assert_eq!(r, Err(crate::transform_tool::LOCKED.to_string())); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "no box opened"); + assert_eq!(errors(&app), [crate::transform_tool::LOCKED]); + app.ui.dialogs.clear(); + // The Move tool's transform controls. + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let r = transform_controls_rect(&app, &xf).unwrap(); + assert!(!begin_transform_controls_at(&mut app, &ctx, &xf, r.right_bottom())); + assert!(app.ui.transform.is_none()); + assert_eq!(errors(&app), [crate::transform_tool::LOCKED]); +} + +#[test] +fn move_transform_controls_show_resize_and_rotate_cursors_before_first_interaction() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.create", json!({"kind": "rect", "rect": [20, 30, 80, 40], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_show_transform = true; + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + + let r = transform_controls_rect(&app, &xf).expect("visible shape controls"); + assert!(app.ui.transform.is_none(), "no transform session is needed for hover"); + for (p, expected) in [ + (r.left_top(), egui::CursorIcon::ResizeNwSe), + (r.right_bottom(), egui::CursorIcon::ResizeNwSe), + (r.right_top(), egui::CursorIcon::ResizeNeSw), + (r.left_bottom(), egui::CursorIcon::ResizeNeSw), + (r.center_top(), egui::CursorIcon::ResizeVertical), + (r.center_bottom(), egui::CursorIcon::ResizeVertical), + (r.right_center(), egui::CursorIcon::ResizeHorizontal), + (r.left_center(), egui::CursorIcon::ResizeHorizontal), + // Between handles: the rotation band (a point above the top-centre handle is that handle), + // where the curved rotate arrow replaces the pointer (#4658). + (pos2(r.left() + r.width() * 0.25, r.top() - 12.0), egui::CursorIcon::None), + ] { + assert_eq!(transform_controls_cursor(r, p), Some(expected), "hover at {p:?}"); + assert!(transform_controls_hit(r, p), "same region must start a transform"); + } + assert_eq!(transform_controls_cursor(r, r.center()), None, "interior stays Move"); + assert_eq!(transform_controls_cursor(r, pos2(r.center().x, r.top() - 30.0)), None); + // The rotate arrow bends round the nearest corner, pointing into the box; handles and the + // interior have none. + let into = |p: Pos2| transform_controls_turn(r, p).map(|v| (v.x.signum(), v.y.signum())); + assert_eq!(into(pos2(r.left() + r.width() * 0.25, r.top() - 12.0)), Some((1.0, 1.0)), "top left"); + assert_eq!(into(pos2(r.right() + 12.0, r.bottom() - r.height() * 0.25)), Some((-1.0, -1.0)), "bottom right"); + assert_eq!(into(pos2(r.left() - 12.0, r.bottom() + 12.0)), Some((1.0, -1.0)), "beyond the bottom-left corner"); + assert_eq!(into(r.left_top()), None); + assert_eq!(into(r.center()), None); + + // Changing the active shape changes the hover bounds without requiring a drag first. + app.session.execute("shape.create", json!({"kind": "rect", "rect": [120, 100, 40, 50], "fill": "#00ff00"})).unwrap(); + let next = transform_controls_rect(&app, &xf).expect("new active shape controls"); + assert_ne!(r, next); + assert_eq!(transform_controls_cursor(next, next.right_bottom()), Some(egui::CursorIcon::ResizeNwSe)); + assert_eq!(transform_controls_cursor(next, next.center()), None); +} + +#[test] +fn transform_control_hit_keeps_move_interior_free_and_has_rotation_band() { + let r = Rect::from_min_max(pos2(20.0, 30.0), pos2(100.0, 70.0)); + assert!(transform_controls_hit(r, r.left_top())); + assert!(transform_controls_hit(r, pos2(60.0, 18.0))); + assert!(!transform_controls_hit(r, r.center())); + assert!(!transform_controls_hit(r, pos2(60.0, 4.0))); +} From b3d9bac34d87ef3f1bb75939d1c26d1fa572b550 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:47 +0000 Subject: [PATCH 065/259] refactor(ui-egui): move export_dialog.rs tests to export_dialog/tests.rs --- crates/ui-egui/src/export_dialog.rs | 654 +--------------------- crates/ui-egui/src/export_dialog/tests.rs | 651 +++++++++++++++++++++ 2 files changed, 652 insertions(+), 653 deletions(-) create mode 100644 crates/ui-egui/src/export_dialog/tests.rs diff --git a/crates/ui-egui/src/export_dialog.rs b/crates/ui-egui/src/export_dialog.rs index c014947aa3..7fd65f68c8 100644 --- a/crates/ui-egui/src/export_dialog.rs +++ b/crates/ui-egui/src/export_dialog.rs @@ -1119,656 +1119,4 @@ fn quick_export(app: &mut PhotocraftApp, p: Value) -> Result { } #[cfg(test)] -mod tests { - #[test] - fn ico_export_is_available_and_rejects_oversize_output() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); - let mut f = Map::new(); - f.insert("format".into(), json!("ico")); - f.insert("scale".into(), json!(100)); - assert!(FORMATS.iter().any(|(ext, _)| *ext == "ico")); - assert!(export_document(&app.session.active().unwrap().doc, &f, None).err().is_some_and(|e| e.contains("256"))); - f.insert("scale".into(), json!(50)); - let resized = export_document(&app.session.active().unwrap().doc, &f, None).unwrap(); - assert_eq!((resized.size.width, resized.size.height), (150, 100)); - } - - use super::*; - - /// Export As reopens with the settings it was used with last (Preferences ▸ remembered - /// dialog settings), and a value no control accepts keeps its default. - #[test] - fn export_as_opens_with_the_settings_used_last() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 20, "height": 10})).unwrap(); - app.session.prefs.edit(|p| { - p.dialogs.insert( - COMMAND.into(), - json!({"format": "jpg", "quality": 88, "scale": 37, "transparency": false, "metadata": "all", "tgaBits": "24", "lossless": true}), - ); - }); - let id = open(&mut app).unwrap(); - let f = &app.ui.dialog_mut(id).unwrap().fields; - assert_eq!(f["format"], "jpg"); - assert_eq!(f["quality"], json!(88.0)); - assert_eq!(f["scale"], json!(37.0)); - assert_eq!(f["transparency"], false); - assert_eq!(f["metadata"], "all"); - assert_eq!(f["tgaBits"], "24"); - - app.session.prefs.edit(|p| { - p.dialogs.insert(COMMAND.into(), json!({"format": "nope", "scale": 0, "metadata": "sometimes"})); - }); - let id = open(&mut app).unwrap(); - let f = &app.ui.dialog_mut(id).unwrap().fields; - assert_eq!(f["format"], "png"); - assert_eq!(f["scale"], 100); - assert_eq!(f["metadata"], "none"); - } - - /// A recorded Export As step replays only with a destination and a format Export As writes - /// (#7207); anything else is an error, not a guess. - #[test] - fn a_replayed_export_needs_a_path_and_a_known_format() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - assert!(replay(&mut app, &json!({"path": "/x.png"})).unwrap_err().contains("document")); - app.run("file.new", json!({"width": 4, "height": 4})).unwrap(); - for bad in [json!({}), json!({"path": ""}), json!("nope"), json!({"path": 3})] { - assert!(replay(&mut app, &bad).unwrap_err().contains("path"), "{bad}"); - } - for format in [json!("bmp"), json!(7)] { - assert!(replay(&mut app, &json!({"path": "/x.bmp", "format": format})).unwrap_err().contains("format"), "{format}"); - } - // A setting of the wrong type or out of the dialog's range is an error, not its default. - for (key, v) in [ - ("scale", json!("50")), - ("scale", json!(5000)), - ("quality", json!(0)), - ("transparency", json!("yes")), - ("metadata", json!("some")), - ("width", json!(-3)), - ] { - let mut step = json!({"path": "/x.png", "format": "png"}); - step[key] = v.clone(); - assert!(replay(&mut app, &step).unwrap_err().contains(key), "{key}: {v}"); - } - } - - /// Layer › Export As opens with the layer's trimmed size, not the document's: `open` seeds the - /// size fields from the document, and the layer replaces them in scale mode. A remembered - /// percent scales the layer; remembered exact pixels stay the size the user asked for. - #[test] - fn layer_export_as_opens_with_the_layer_size() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 40, "height": 30})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("select.rect", json!({"x": 4, "y": 2, "width": 10, "height": 6})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - let layer = app.session.active().unwrap().active_layer.unwrap(); - let id = open_layer(&mut app, layer).unwrap(); - let f = &app.ui.dialog_mut(id).unwrap().fields; - assert_eq!((f["__w"].as_f64(), f["__h"].as_f64()), (Some(10.0), Some(6.0))); - assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(10.0), Some(6.0))); - - app.session.prefs.edit(|p| p.dialogs.insert(COMMAND.into(), json!({"scale": 50}))); - let id = open_layer(&mut app, layer).unwrap(); - let f = &app.ui.dialog_mut(id).unwrap().fields; - assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(5.0), Some(3.0))); - - app.session.prefs.edit(|p| p.dialogs.insert(COMMAND.into(), json!({"sizing": "pixels", "width": 120, "height": 80}))); - let id = open_layer(&mut app, layer).unwrap(); - let f = &app.ui.dialog_mut(id).unwrap().fields; - assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(120.0), Some(80.0))); - } - - /// Only the dialog's own settings are remembered: not the destination, the document size or - /// the layer the dialog was opened with. - #[test] - fn remembering_keeps_only_the_dialog_settings() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut f = Map::new(); - f.insert("format".into(), json!("webp")); - f.insert("scale".into(), json!(50)); - f.insert("path".into(), json!("/tmp/x.webp")); - f.insert("__w".into(), json!(1200)); - f.insert("__layer".into(), json!(3)); - remember(&mut app, &f); - let saved = app.session.prefs().dialogs.get(COMMAND).cloned().unwrap(); - assert_eq!(saved["format"], "webp"); - assert_eq!(saved["scale"], 50); - assert!(saved.get("path").is_none() && saved.get("__w").is_none() && saved.get("__layer").is_none()); - } - - /// A red/blue checkerboard at `depth`, one pixel per square. - fn checker_doc(depth: photocraft_doc::SampleType) -> Document { - use photocraft_doc::{Color, ColorMode, Size}; - let mut doc = Document::with_background("checker", Size::new(5, 3), ColorMode::Rgb, depth, Color::WHITE); - let b = doc.bounds(); - let surf = doc.layers[0].surface_mut().unwrap(); - let fmt = surf.format(); - let mut data = Vec::new(); - for y in b.y0..b.y1 { - for x in b.x0..b.x1 { - data.extend(photocraft_raster::from_rgba(&fmt, checker(x, y))); - } - } - surf.write_region(b, &data); - doc - } - - fn checker(x: i32, y: i32) -> [f32; 4] { - if (x + y) % 2 == 0 { [1.0, 0.0, 0.0, 1.0] } else { [0.0, 0.0, 1.0, 1.0] } - } - - /// Export As › Resample › Nearest Neighbor at 200 %: every source pixel becomes an exact - /// 2 × 2 block, at 8 and 16 bits, and the document keeps its pixels. Bicubic Automatic (the - /// default) blends the squares instead. - #[test] - fn nearest_neighbor_doubles_each_pixel_into_an_exact_block() { - use photocraft_doc::SampleType; - for depth in [SampleType::U8, SampleType::U16] { - let doc = checker_doc(depth); - let before = doc.clone(); - let mut f = Map::new(); - f.insert("format".into(), json!("png")); - f.insert("scale".into(), json!(200)); - f.insert("resample".into(), json!("nearest")); - let out = export_document(&doc, &f, None).unwrap(); - assert_eq!((out.size.width, out.size.height), (10, 6)); - assert_eq!(out.depth, depth); - let surf = out.layers[0].surface().unwrap(); - for y in 0..6 { - for x in 0..10 { - assert_eq!(surf.rgba(x, y), checker(x / 2, y / 2), "{depth:?} pixel {x},{y}"); - } - } - assert_eq!(doc, before, "{depth:?}: export leaves the source document unchanged"); - - // The preview proxy keeps Nearest Neighbor's hard edges too. - let proxy = export_document(&doc, &f, Some(512)).unwrap(); - assert_eq!(proxy.layers[0].surface().unwrap().rgba(1, 1), checker(0, 0), "{depth:?}: preview proxy is nearest as well"); - assert_eq!(preview_filter(&f), egui::TextureOptions::NEAREST); - - f.insert("resample".into(), json!(DEFAULT_RESAMPLE)); - let smooth = export_document(&doc, &f, None).unwrap(); - let blended = (0..6).flat_map(|y| (0..10).map(move |x| (x, y))).any(|(x, y)| { - let p = smooth.layers[0].surface().unwrap().rgba(x, y); - p[0] > 0.01 && p[2] > 0.01 - }); - assert!(blended, "{depth:?}: Bicubic Automatic blends neighbouring squares"); - assert_eq!(preview_filter(&f), egui::TextureOptions::LINEAR); - } - } - - /// Every Resample choice reaches Image Size; a method Export As does not offer is an error - /// naming the choices, never a silent Bicubic, and a missing one is Bicubic Automatic. - #[test] - fn resample_choices_are_checked() { - let doc = checker_doc(photocraft_doc::SampleType::U8); - let mut f = Map::new(); - f.insert("scale".into(), json!(300)); - for (method, _) in RESAMPLE { - f.insert("resample".into(), json!(method)); - let out = export_document(&doc, &f, None).unwrap(); - assert_eq!((out.size.width, out.size.height), (15, 9), "{method}"); - } - for bad in [json!("lanczos"), json!("NEAREST"), json!(""), json!(1), json!({"m": "nearest"})] { - f.insert("resample".into(), bad.clone()); - let err = export_document(&doc, &f, None).unwrap_err(); - assert!(err.contains("resample must be"), "{bad}: {err}"); - assert!(export_document(&doc, &f, Some(512)).is_err(), "{bad}: the preview reports it too"); - } - f.remove("resample"); - assert_eq!(resample_method(&f, None).unwrap(), "bicubicAutomatic"); - assert_eq!(resample_method(&f, Some(512)).unwrap(), "bilinear", "the preview stays on the fast path"); - } - - /// Resample is remembered with the other settings; a saved value the menu does not offer - /// opens the dialog with the default. - #[test] - fn resample_is_remembered_and_a_bad_saved_value_falls_back() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 20, "height": 10})).unwrap(); - let id = open(&mut app).unwrap(); - assert_eq!(app.ui.dialog_mut(id).unwrap().fields["resample"], DEFAULT_RESAMPLE, "Photoshop's default"); - let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); - f.insert("resample".into(), json!("nearest")); - remember(&mut app, &f); - assert_eq!(app.session.prefs().dialogs[COMMAND]["resample"], "nearest"); - let id = open(&mut app).unwrap(); - assert_eq!(app.ui.dialog_mut(id).unwrap().fields["resample"], "nearest"); - - for bad in [json!("lanczos"), json!(7), json!(null)] { - app.session.prefs.edit(|p| { - p.dialogs.insert(COMMAND.into(), json!({"resample": bad})); - }); - let id = open(&mut app).unwrap(); - assert_eq!(app.ui.dialog_mut(id).unwrap().fields["resample"], DEFAULT_RESAMPLE, "saved {bad}"); - } - } - - #[test] - fn export_document_scales_height_when_rounded_width_is_unchanged() { - use photocraft_doc::{Color, ColorMode, SampleType, Size}; - - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for (width, height, scale, expected) in [ - (1, 100, 50, (1, 50)), - (1, 200, 50, (1, 100)), - (10, 100, 99, (10, 99)), - (10, 100, 101, (10, 101)), - (400, 300, 50, (200, 150)), - (400, 300, 100, (400, 300)), - ] { - let doc = Document::with_background("x", Size::new(width, height), ColorMode::Rgb, depth, Color::WHITE); - let before = doc.clone(); - let mut f = Map::new(); - f.insert("format".into(), json!("png")); - f.insert("scale".into(), json!(scale)); - let out = export_document(&doc, &f, None).unwrap(); - assert_eq!((out.size.width, out.size.height), expected, "{width} × {height} at {scale}%, {depth:?}"); - assert_eq!(out.depth, depth, "export preserves the document's depth"); - assert_eq!(doc, before, "export leaves the source document unchanged"); - } - } - } - - #[test] - fn export_document_proxy_limits_both_dimensions_before_rounding() { - use photocraft_doc::{Color, ColorMode, SampleType, Size}; - - for (width, height, scale, max_side, expected) in - [(1, 1000, 100, 360, (1, 360)), (1, 1000, 50, 360, (1, 360)), (1, 1000, 25, 360, (1, 250)), (13, 20, 50, 8, (5, 8)), (20, 13, 50, 8, (8, 5))] - { - let doc = Document::with_background("x", Size::new(width, height), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let before = doc.clone(); - let mut f = Map::new(); - f.insert("format".into(), json!("png")); - f.insert("scale".into(), json!(scale)); - let out = export_document(&doc, &f, Some(max_side)).unwrap(); - assert_eq!((out.size.width, out.size.height), expected, "{width} × {height} at {scale}%, proxy limit {max_side}"); - assert!(out.size.width.max(out.size.height) <= max_side, "proxy respects its longest-side limit"); - assert_eq!(doc, before, "preview leaves the source document unchanged"); - } - } - - /// #6595: Export As shows the size the file will have, as Photoshop does. The proxy estimate - /// read 36–81 % of it for a detailed image; up to `EXACT_ESTIMATE_PX` the full export is - /// encoded off the UI thread instead. - #[test] - fn the_estimate_is_the_exported_files_size() { - let mut doc = Document::with_background( - "x", - photocraft_doc::Size::new(900, 300), - photocraft_doc::ColorMode::Rgb, - photocraft_doc::SampleType::U8, - photocraft_doc::Color::WHITE, - ); - let id = doc.layers[0].id; - let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); - let mut seed = 12345u32; - for y in (0..300).step_by(2) { - for x in (0..900).step_by(2) { - seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); - let v = (seed >> 24) as f32 / 255.0; - surf.fill_rect(photocraft_geom::Rect::new(x, y, x + 2, y + 2), &[v, x as f32 / 900.0, y as f32 / 300.0, 1.0]); - } - } - let doc = Arc::new(doc); - let f = Map::from_iter([("format".into(), json!("jpg")), ("scale".into(), json!(100)), ("quality".into(), json!(32))]); - let actual = photocraft_io::export(&export_document(&doc, &f, None).unwrap(), "x.jpg", &settings(&f).io_options()).unwrap().bytes.len() as u64; - let proxy = preview_proxy(&doc, &f).unwrap(); - let old = estimate_native(&doc, &proxy, &f).unwrap(); - assert!((old as f64 / actual as f64 - 1.0).abs() > 0.1, "the proxy estimate was off: {old} vs {actual}"); - - let ctx = egui::Context::default(); - let key = egui::Id::unique("exact-estimate-test"); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); - let size = loop { - let mut size = None; - let mut output = ctx.run_ui(Default::default(), |ctx| { - egui::CentralPanel::default().show(ctx, |ui| size = poll_or_start_exact_estimate(ui, key, "jpg32", doc.clone(), &f)); - }); - output.textures_delta.clear(); - if let Some(size) = size { - break size; - } - assert!(std::time::Instant::now() < deadline, "the exact estimate did not arrive"); - std::thread::sleep(std::time::Duration::from_millis(10)); - }; - assert_eq!(size, Some(actual)); - // Over the limit there is no exact size; the proxy estimate stays. - let huge = Map::from_iter([ - ("format".into(), json!("jpg")), - ("sizing".into(), json!("pixels")), - ("width".into(), json!(10_000)), - ("height".into(), json!(10_000)), - ]); - assert_eq!(exact_estimate(&doc, &huge), None); - // In scale mode the size comes from the scale, as the export's does, not from stale pixels. - let big = Arc::new(Document::with_background( - "big", - photocraft_doc::Size::new(1000, 1000), - photocraft_doc::ColorMode::Rgb, - photocraft_doc::SampleType::U8, - photocraft_doc::Color::WHITE, - )); - let stale = Map::from_iter([ - ("format".into(), json!("png")), - ("sizing".into(), json!("scale")), - ("scale".into(), json!(1000)), - ("width".into(), json!(100)), - ("height".into(), json!(100)), - ]); - assert_eq!(exact_estimate(&big, &stale), None, "10000 × 10000 at 1000 %, over the limit"); - let small = Map::from_iter([ - ("format".into(), json!("png")), - ("sizing".into(), json!("scale")), - ("scale".into(), json!(10)), - ("width".into(), json!(9000)), - ("height".into(), json!(9000)), - ]); - let at_10 = photocraft_io::export(&export_document(&big, &small, None).unwrap(), "x.png", &settings(&small).io_options()).unwrap().bytes.len() as u64; - assert_eq!(exact_estimate(&big, &small), Some(at_10), "100 × 100 at 10 %, within it"); - } - - /// #8341: Export As and its reduced preview carry the stroke width with the path. - #[test] - fn export_as_downscales_stroke_only_shapes_and_preview() { - for depth in [8, 16, 32] { - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width": 1024, "height": 1024, "depth": depth, "background": "transparent"})).unwrap(); - let id = session.execute("shape.create", json!({"rect": [256, 256, 512, 512], "fill": null, "stroke": {"width": 32}})).unwrap()["layer"] - .as_u64() - .unwrap(); - let doc = session.active().unwrap().doc.clone(); - let fields = Map::from_iter([("format".into(), json!("png")), ("scale".into(), json!(25))]); - for limit in [None, Some(128)] { - let out = export_document(&doc, &fields, limit).unwrap(); - let side = if limit.is_some() { 128 } else { 256 }; - assert_eq!((out.size.width, out.size.height), (side, side)); - let shape = out.layer(photocraft_doc::LayerId(id)).unwrap(); - let photocraft_doc::LayerContent::Shape(shape) = &shape.content else { - panic!("shape lost"); - }; - assert_eq!(shape.stroke.as_ref().unwrap().width, side as f32 / 32.0); - let pixels = photocraft_compose::flatten(&out); - let row = (side / 2 * side) as usize; - assert!(pixels.px[row + (side / 4) as usize][3] > 0.99); - assert!(pixels.px[row + (side / 4 - side / 32) as usize][3] < 0.01); - assert!(pixels.px[row + (side / 2) as usize][3] < 0.01); - } - assert_eq!(session.active().unwrap().doc, doc, "export leaves the source unchanged"); - } - } - - #[test] - fn export_document_scales_and_flattens() { - let doc = Document::with_background( - "x", - photocraft_doc::Size::new(200, 100), - photocraft_doc::ColorMode::Rgb, - photocraft_doc::SampleType::U8, - photocraft_doc::Color::WHITE, - ); - let mut f = Map::new(); - f.insert("format".into(), json!("jpg")); - f.insert("scale".into(), json!(50)); - let out = export_document(&doc, &f, None).unwrap(); - assert_eq!((out.size.width, out.size.height), (100, 50)); - assert_eq!(out.layers.len(), 1); - let proxy = export_document(&doc, &f, Some(40)).unwrap(); - assert_eq!(proxy.size.width, 40); - assert_eq!(settings(&f).jpeg_quality, Some(85)); - } - - /// #1353: a scale that changes only the height (the width rounds back to the original) - /// used to be skipped, so the exported file kept the original size while the dialog - /// labelled it as scaled. - #[test] - fn export_document_scales_when_only_the_height_changes() { - let mut f = Map::new(); - f.insert("format".into(), json!("png")); - f.insert("scale".into(), json!(50)); - for (src_h, want_h) in [(100u32, 50u32), (200, 100)] { - let doc = Document::with_background( - "x", - photocraft_doc::Size::new(1, src_h), - photocraft_doc::ColorMode::Rgb, - photocraft_doc::SampleType::U8, - photocraft_doc::Color::WHITE, - ); - let out = export_document(&doc, &f, None).unwrap(); - assert_eq!((out.size.width, out.size.height), (1, want_h), "1 × {src_h} at 50%"); - // The preview proxy takes the same path. - let proxy = export_document(&doc, &f, Some(40)).unwrap(); - assert_eq!((proxy.size.width, proxy.size.height), (1, 40), "proxy of 1 × {src_h}"); - } - // The label and the export agree, and neither side drops below 1 px. - assert_eq!(scaled_size(1.0, 100.0, 0.5), (1.0, 50.0)); - assert_eq!(scaled_size(10.0, 300.0, 0.01), (1.0, 3.0)); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn layered_preview_runs_outside_the_ui_frame() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 32, "height": 16})).unwrap(); - for _ in 0..33 { - app.run("layer.new.layer", json!({})).unwrap(); - } - let doc = app.session.active().unwrap().doc.clone(); - assert!(background_preview_needed(&doc)); - let fields = Map::from_iter([("format".into(), json!("png")), ("scale".into(), json!(100))]); - let ctx = egui::Context::default(); - let key = egui::Id::unique("layered-preview-test"); - let mut result = None; - let mut output = ctx.run_ui(Default::default(), |ctx| { - egui::CentralPanel::default().show(ctx, |ui| { - result = poll_or_start_preview(ui, key, "png100", doc.clone(), &fields); - }); - }); - output.textures_delta.clear(); - assert!(result.is_none(), "the first UI frame must only start the worker"); - - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); - loop { - let mut output = ctx.run_ui(Default::default(), |ctx| { - egui::CentralPanel::default().show(ctx, |ui| { - result = poll_or_start_preview(ui, key, "png100", doc.clone(), &fields); - }); - }); - output.textures_delta.clear(); - if let Some(preview) = result { - let preview = preview.unwrap(); - assert_eq!((preview.width, preview.height), (32, 16)); - assert_eq!(preview.rgba.len(), 32 * 16 * 4); - assert!(preview.estimate.is_some_and(|bytes| bytes > 0)); - break; - } - assert!(std::time::Instant::now() < deadline, "background preview did not complete"); - std::thread::sleep(std::time::Duration::from_millis(10)); - } - - let tiff_fields = Map::from_iter([("format".into(), json!("tif")), ("scale".into(), json!(100))]); - let proxy = preview_proxy(&doc, &tiff_fields).unwrap(); - let options = photocraft_io::ExportOptions { tiff_layers: true, xmp: photocraft_io::XmpEmbed::None, ..Default::default() }; - let actual_bytes = photocraft_io::export(&proxy, "estimate.tif", &options).unwrap().bytes.len(); - assert_eq!(estimate_native(&doc, &proxy, &tiff_fields), Some(scaled_estimate(actual_bytes, &doc, &proxy, &tiff_fields))); - } - - #[test] - fn switching_export_formats_uses_independent_quality_preferences() { - let prefs = photocraft_engine::prefs::Export { jpeg_quality: 43, webp_quality: 72, webp_lossless: false, ..Default::default() }; - let mut fields = Map::new(); - set_format_defaults(&mut fields, "webp", &prefs); - assert_eq!(fields["quality"], 72); - assert_eq!(fields["lossless"], false); - let s = settings(&fields); - assert!(!s.webp_lossless); - assert_eq!(s.webp_quality, Some(72)); - assert_eq!(s.jpeg_quality, None); - - set_format_defaults(&mut fields, "jpg", &prefs); - assert_eq!(fields["quality"], 43); - assert_eq!(settings(&fields).jpeg_quality, Some(43)); - assert_eq!(settings(&fields).webp_quality, None); - - set_format_defaults(&mut fields, "webp", &photocraft_engine::prefs::Export::default()); - assert!(settings(&fields).webp_lossless, "default WebP Quick Export mode is lossless"); - assert_eq!(settings(&fields).webp_quality, None); - } - - #[test] - fn webp_settings_follow_the_lossless_switch() { - let mut f = Map::new(); - f.insert("format".into(), json!("webp")); - f.insert("quality".into(), json!(70)); - let s = settings(&f); - assert!(!s.webp_lossless, "Export As writes lossy WebP unless asked"); - assert_eq!(s.webp_quality, Some(70)); - assert_eq!(s.jpeg_quality, None); - f.insert("lossless".into(), json!(true)); - let s = settings(&f); - assert!(s.webp_lossless); - assert_eq!(s.webp_quality, None); - f.insert("format".into(), json!("png")); - assert!(settings(&f).webp_lossless, "other formats leave the WebP default alone"); - } - - /// TGA's Resolution (bits per pixel): Auto leaves the choice to the export; 24 and 32 force it, and only - /// for TGA. - #[test] - fn tga_settings_follow_the_bits_per_pixel() { - use photocraft_io::TgaBits; - let mut f = Map::new(); - f.insert("format".into(), json!("tga")); - assert_eq!(settings(&f).tga_bits, None, "no choice made"); - for (v, want) in [("auto", None), ("24", Some(TgaBits::Bits24)), ("32", Some(TgaBits::Bits32)), ("16", None)] { - f.insert("tgaBits".into(), json!(v)); - assert_eq!(settings(&f).tga_bits, want, "{v}"); - } - f.insert("format".into(), json!("png")); - assert_eq!(settings(&f).tga_bits, None, "only TGA has bits per pixel"); - } - - #[test] - fn exact_pixels_lock_aspect_and_leave_the_source() { - let linked = resize_from_scale(400.0, 200.0, 50.0).unwrap(); - assert_eq!((linked.width, linked.height, linked.scale), (200.0, 100.0, 50.0)); - let from_width = resize_from_side(400.0, 200.0, 100.0, 200.0, true, true).unwrap(); - assert_eq!((from_width.width, from_width.height), (100.0, 50.0)); - let from_height = resize_from_side(400.0, 200.0, 100.0, 40.0, true, false).unwrap(); - assert_eq!((from_height.width, from_height.height), (80.0, 40.0)); - let free = resize_from_side(400.0, 200.0, 100.0, 80.0, false, true).unwrap(); - assert_eq!((free.width, free.height), (100.0, 80.0)); - assert!(resize_from_scale(400.0, 200.0, 0.0).is_err()); - assert!(resize_from_side(400.0, 200.0, 0.0, 10.0, false, true).is_err()); - assert!(resize_from_side(10.0, 10.0, 400_000.0, 10.0, false, true).is_err()); - - let doc = Document::with_background( - "x", - photocraft_doc::Size::new(400, 200), - photocraft_doc::ColorMode::Rgb, - photocraft_doc::SampleType::U8, - photocraft_doc::Color::WHITE, - ); - let before = doc.clone(); - let mut f = Map::new(); - f.insert("format".into(), json!("png")); - f.insert("scale".into(), json!(100)); - f.insert("sizing".into(), json!("pixels")); - f.insert("width".into(), json!(120)); - f.insert("height".into(), json!(40)); - let out = export_document(&doc, &f, None).unwrap(); - assert_eq!((out.size.width, out.size.height), (120, 40), "explicit pixels win over the percent scale"); - let proxy = export_document(&doc, &f, Some(20)).unwrap(); - assert_eq!((proxy.size.width, proxy.size.height), (20, 7)); - assert_eq!(doc, before, "export leaves the source document unchanged"); - } - - #[test] - fn profile_and_metadata_follow_the_existing_exporter() { - use photocraft_cms::Builtin; - - let mut f = Map::new(); - f.insert("format".into(), json!("jpg")); - assert!(settings(&f).embed_metadata, "a missing metadata choice keeps EXIF and resolution"); - assert!(settings(&f).embed_icc); - f.insert("metadata".into(), json!("none")); - f.insert("embedProfile".into(), json!(false)); - let none = settings(&f); - assert!(!none.xmp_all && !none.embed_metadata && !none.embed_icc); - f.insert("metadata".into(), json!("exif")); - let exif = settings(&f); - assert!(!exif.xmp_all && exif.embed_metadata); - f.insert("metadata".into(), json!("all")); - f.insert("embedProfile".into(), json!(true)); - let all = settings(&f); - assert!(all.xmp_all && all.embed_metadata && all.embed_icc); - - let mut doc = Document::with_background( - "x", - photocraft_doc::Size::new(8, 8), - photocraft_doc::ColorMode::Rgb, - photocraft_doc::SampleType::U8, - photocraft_doc::Color::WHITE, - ); - doc.icc_profile = Some(Builtin::DisplayP3.profile().to_bytes()); - doc.metadata.xmp = Some("secret".into()); - let before = doc.clone(); - f.insert("profile".into(), json!("srgb")); - f.insert("width".into(), json!(8)); - f.insert("height".into(), json!(8)); - f.insert("metadata".into(), json!("none")); - f.insert("embedProfile".into(), json!(false)); - let converted = export_document(&doc, &f, None).unwrap(); - let parsed = photocraft_cms::Profile::parse(converted.icc_profile.as_deref().unwrap()).unwrap(); - assert!(parsed.same_colors(Builtin::Srgb.profile()), "Convert to sRGB replaces the document profile"); - let stripped = photocraft_io::export(&converted, "out.jpg", &settings(&f).io_options()).unwrap().bytes; - assert!(!stripped.windows(b"ICC_PROFILE".len()).any(|w| w == b"ICC_PROFILE")); - assert!(!stripped.windows(b"secret".len()).any(|w| w == b"secret")); - f.insert("metadata".into(), json!("all")); - f.insert("embedProfile".into(), json!(true)); - let kept = photocraft_io::export(&converted, "out.jpg", &settings(&f).io_options()).unwrap().bytes; - assert!(kept.windows(b"ICC_PROFILE".len()).any(|w| w == b"ICC_PROFILE")); - assert!(kept.windows(b"secret".len()).any(|w| w == b"secret")); - assert_eq!(doc, before); - } - - #[test] - fn applying_a_preset_restores_its_size_mode() { - use photocraft_engine::export_preset_cmds::ExportPresetSettings; - - let pixels = ExportPresetSettings { - format: "png".into(), - quality: 80, - lossless: false, - transparency: true, - scale: 100.0, - width: 64, - height: 32, - lock_aspect: false, - sizing: "pixels".into(), - metadata: "exif".into(), - profile: "document".into(), - embed_profile: false, - tga_bits: "auto".into(), - resample: "nearest".into(), - }; - let mut f = Map::new(); - apply_preset(&mut f, &pixels, 400.0, 200.0); - assert_eq!(f.get("resample"), Some(&json!("nearest")), "a preset restores its Resample method"); - assert_eq!(preset_settings(&f)["resample"], "nearest", "and saves it"); - assert_eq!(f.get("width"), Some(&json!(64))); - assert_eq!(f.get("height"), Some(&json!(32))); - assert_eq!(f.get("sizing"), Some(&json!("pixels"))); - assert_eq!(f.get("embedProfile"), Some(&json!(false))); - let scale = ExportPresetSettings { sizing: "scale".into(), scale: 25.0, ..pixels }; - apply_preset(&mut f, &scale, 400.0, 200.0); - assert_eq!(f.get("width"), Some(&json!(100.0))); - assert_eq!(f.get("height"), Some(&json!(50.0))); - assert_eq!(f.get("sizing"), Some(&json!("scale"))); - } -} +mod tests; diff --git a/crates/ui-egui/src/export_dialog/tests.rs b/crates/ui-egui/src/export_dialog/tests.rs new file mode 100644 index 0000000000..b5815fd700 --- /dev/null +++ b/crates/ui-egui/src/export_dialog/tests.rs @@ -0,0 +1,651 @@ +#[test] +fn ico_export_is_available_and_rejects_oversize_output() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let mut f = Map::new(); + f.insert("format".into(), json!("ico")); + f.insert("scale".into(), json!(100)); + assert!(FORMATS.iter().any(|(ext, _)| *ext == "ico")); + assert!(export_document(&app.session.active().unwrap().doc, &f, None).err().is_some_and(|e| e.contains("256"))); + f.insert("scale".into(), json!(50)); + let resized = export_document(&app.session.active().unwrap().doc, &f, None).unwrap(); + assert_eq!((resized.size.width, resized.size.height), (150, 100)); +} + +use super::*; + +/// Export As reopens with the settings it was used with last (Preferences ▸ remembered +/// dialog settings), and a value no control accepts keeps its default. +#[test] +fn export_as_opens_with_the_settings_used_last() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 20, "height": 10})).unwrap(); + app.session.prefs.edit(|p| { + p.dialogs.insert( + COMMAND.into(), + json!({"format": "jpg", "quality": 88, "scale": 37, "transparency": false, "metadata": "all", "tgaBits": "24", "lossless": true}), + ); + }); + let id = open(&mut app).unwrap(); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!(f["format"], "jpg"); + assert_eq!(f["quality"], json!(88.0)); + assert_eq!(f["scale"], json!(37.0)); + assert_eq!(f["transparency"], false); + assert_eq!(f["metadata"], "all"); + assert_eq!(f["tgaBits"], "24"); + + app.session.prefs.edit(|p| { + p.dialogs.insert(COMMAND.into(), json!({"format": "nope", "scale": 0, "metadata": "sometimes"})); + }); + let id = open(&mut app).unwrap(); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!(f["format"], "png"); + assert_eq!(f["scale"], 100); + assert_eq!(f["metadata"], "none"); +} + +/// A recorded Export As step replays only with a destination and a format Export As writes +/// (#7207); anything else is an error, not a guess. +#[test] +fn a_replayed_export_needs_a_path_and_a_known_format() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + assert!(replay(&mut app, &json!({"path": "/x.png"})).unwrap_err().contains("document")); + app.run("file.new", json!({"width": 4, "height": 4})).unwrap(); + for bad in [json!({}), json!({"path": ""}), json!("nope"), json!({"path": 3})] { + assert!(replay(&mut app, &bad).unwrap_err().contains("path"), "{bad}"); + } + for format in [json!("bmp"), json!(7)] { + assert!(replay(&mut app, &json!({"path": "/x.bmp", "format": format})).unwrap_err().contains("format"), "{format}"); + } + // A setting of the wrong type or out of the dialog's range is an error, not its default. + for (key, v) in [ + ("scale", json!("50")), + ("scale", json!(5000)), + ("quality", json!(0)), + ("transparency", json!("yes")), + ("metadata", json!("some")), + ("width", json!(-3)), + ] { + let mut step = json!({"path": "/x.png", "format": "png"}); + step[key] = v.clone(); + assert!(replay(&mut app, &step).unwrap_err().contains(key), "{key}: {v}"); + } +} + +/// Layer › Export As opens with the layer's trimmed size, not the document's: `open` seeds the +/// size fields from the document, and the layer replaces them in scale mode. A remembered +/// percent scales the layer; remembered exact pixels stay the size the user asked for. +#[test] +fn layer_export_as_opens_with_the_layer_size() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 40, "height": 30})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 4, "y": 2, "width": 10, "height": 6})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + let id = open_layer(&mut app, layer).unwrap(); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!((f["__w"].as_f64(), f["__h"].as_f64()), (Some(10.0), Some(6.0))); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(10.0), Some(6.0))); + + app.session.prefs.edit(|p| p.dialogs.insert(COMMAND.into(), json!({"scale": 50}))); + let id = open_layer(&mut app, layer).unwrap(); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(5.0), Some(3.0))); + + app.session.prefs.edit(|p| p.dialogs.insert(COMMAND.into(), json!({"sizing": "pixels", "width": 120, "height": 80}))); + let id = open_layer(&mut app, layer).unwrap(); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(120.0), Some(80.0))); +} + +/// Only the dialog's own settings are remembered: not the destination, the document size or +/// the layer the dialog was opened with. +#[test] +fn remembering_keeps_only_the_dialog_settings() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut f = Map::new(); + f.insert("format".into(), json!("webp")); + f.insert("scale".into(), json!(50)); + f.insert("path".into(), json!("/tmp/x.webp")); + f.insert("__w".into(), json!(1200)); + f.insert("__layer".into(), json!(3)); + remember(&mut app, &f); + let saved = app.session.prefs().dialogs.get(COMMAND).cloned().unwrap(); + assert_eq!(saved["format"], "webp"); + assert_eq!(saved["scale"], 50); + assert!(saved.get("path").is_none() && saved.get("__w").is_none() && saved.get("__layer").is_none()); +} + +/// A red/blue checkerboard at `depth`, one pixel per square. +fn checker_doc(depth: photocraft_doc::SampleType) -> Document { + use photocraft_doc::{Color, ColorMode, Size}; + let mut doc = Document::with_background("checker", Size::new(5, 3), ColorMode::Rgb, depth, Color::WHITE); + let b = doc.bounds(); + let surf = doc.layers[0].surface_mut().unwrap(); + let fmt = surf.format(); + let mut data = Vec::new(); + for y in b.y0..b.y1 { + for x in b.x0..b.x1 { + data.extend(photocraft_raster::from_rgba(&fmt, checker(x, y))); + } + } + surf.write_region(b, &data); + doc +} + +fn checker(x: i32, y: i32) -> [f32; 4] { + if (x + y) % 2 == 0 { [1.0, 0.0, 0.0, 1.0] } else { [0.0, 0.0, 1.0, 1.0] } +} + +/// Export As › Resample › Nearest Neighbor at 200 %: every source pixel becomes an exact +/// 2 × 2 block, at 8 and 16 bits, and the document keeps its pixels. Bicubic Automatic (the +/// default) blends the squares instead. +#[test] +fn nearest_neighbor_doubles_each_pixel_into_an_exact_block() { + use photocraft_doc::SampleType; + for depth in [SampleType::U8, SampleType::U16] { + let doc = checker_doc(depth); + let before = doc.clone(); + let mut f = Map::new(); + f.insert("format".into(), json!("png")); + f.insert("scale".into(), json!(200)); + f.insert("resample".into(), json!("nearest")); + let out = export_document(&doc, &f, None).unwrap(); + assert_eq!((out.size.width, out.size.height), (10, 6)); + assert_eq!(out.depth, depth); + let surf = out.layers[0].surface().unwrap(); + for y in 0..6 { + for x in 0..10 { + assert_eq!(surf.rgba(x, y), checker(x / 2, y / 2), "{depth:?} pixel {x},{y}"); + } + } + assert_eq!(doc, before, "{depth:?}: export leaves the source document unchanged"); + + // The preview proxy keeps Nearest Neighbor's hard edges too. + let proxy = export_document(&doc, &f, Some(512)).unwrap(); + assert_eq!(proxy.layers[0].surface().unwrap().rgba(1, 1), checker(0, 0), "{depth:?}: preview proxy is nearest as well"); + assert_eq!(preview_filter(&f), egui::TextureOptions::NEAREST); + + f.insert("resample".into(), json!(DEFAULT_RESAMPLE)); + let smooth = export_document(&doc, &f, None).unwrap(); + let blended = (0..6).flat_map(|y| (0..10).map(move |x| (x, y))).any(|(x, y)| { + let p = smooth.layers[0].surface().unwrap().rgba(x, y); + p[0] > 0.01 && p[2] > 0.01 + }); + assert!(blended, "{depth:?}: Bicubic Automatic blends neighbouring squares"); + assert_eq!(preview_filter(&f), egui::TextureOptions::LINEAR); + } +} + +/// Every Resample choice reaches Image Size; a method Export As does not offer is an error +/// naming the choices, never a silent Bicubic, and a missing one is Bicubic Automatic. +#[test] +fn resample_choices_are_checked() { + let doc = checker_doc(photocraft_doc::SampleType::U8); + let mut f = Map::new(); + f.insert("scale".into(), json!(300)); + for (method, _) in RESAMPLE { + f.insert("resample".into(), json!(method)); + let out = export_document(&doc, &f, None).unwrap(); + assert_eq!((out.size.width, out.size.height), (15, 9), "{method}"); + } + for bad in [json!("lanczos"), json!("NEAREST"), json!(""), json!(1), json!({"m": "nearest"})] { + f.insert("resample".into(), bad.clone()); + let err = export_document(&doc, &f, None).unwrap_err(); + assert!(err.contains("resample must be"), "{bad}: {err}"); + assert!(export_document(&doc, &f, Some(512)).is_err(), "{bad}: the preview reports it too"); + } + f.remove("resample"); + assert_eq!(resample_method(&f, None).unwrap(), "bicubicAutomatic"); + assert_eq!(resample_method(&f, Some(512)).unwrap(), "bilinear", "the preview stays on the fast path"); +} + +/// Resample is remembered with the other settings; a saved value the menu does not offer +/// opens the dialog with the default. +#[test] +fn resample_is_remembered_and_a_bad_saved_value_falls_back() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 20, "height": 10})).unwrap(); + let id = open(&mut app).unwrap(); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["resample"], DEFAULT_RESAMPLE, "Photoshop's default"); + let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); + f.insert("resample".into(), json!("nearest")); + remember(&mut app, &f); + assert_eq!(app.session.prefs().dialogs[COMMAND]["resample"], "nearest"); + let id = open(&mut app).unwrap(); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["resample"], "nearest"); + + for bad in [json!("lanczos"), json!(7), json!(null)] { + app.session.prefs.edit(|p| { + p.dialogs.insert(COMMAND.into(), json!({"resample": bad})); + }); + let id = open(&mut app).unwrap(); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["resample"], DEFAULT_RESAMPLE, "saved {bad}"); + } +} + +#[test] +fn export_document_scales_height_when_rounded_width_is_unchanged() { + use photocraft_doc::{Color, ColorMode, SampleType, Size}; + + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for (width, height, scale, expected) in [ + (1, 100, 50, (1, 50)), + (1, 200, 50, (1, 100)), + (10, 100, 99, (10, 99)), + (10, 100, 101, (10, 101)), + (400, 300, 50, (200, 150)), + (400, 300, 100, (400, 300)), + ] { + let doc = Document::with_background("x", Size::new(width, height), ColorMode::Rgb, depth, Color::WHITE); + let before = doc.clone(); + let mut f = Map::new(); + f.insert("format".into(), json!("png")); + f.insert("scale".into(), json!(scale)); + let out = export_document(&doc, &f, None).unwrap(); + assert_eq!((out.size.width, out.size.height), expected, "{width} × {height} at {scale}%, {depth:?}"); + assert_eq!(out.depth, depth, "export preserves the document's depth"); + assert_eq!(doc, before, "export leaves the source document unchanged"); + } + } +} + +#[test] +fn export_document_proxy_limits_both_dimensions_before_rounding() { + use photocraft_doc::{Color, ColorMode, SampleType, Size}; + + for (width, height, scale, max_side, expected) in + [(1, 1000, 100, 360, (1, 360)), (1, 1000, 50, 360, (1, 360)), (1, 1000, 25, 360, (1, 250)), (13, 20, 50, 8, (5, 8)), (20, 13, 50, 8, (8, 5))] + { + let doc = Document::with_background("x", Size::new(width, height), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let before = doc.clone(); + let mut f = Map::new(); + f.insert("format".into(), json!("png")); + f.insert("scale".into(), json!(scale)); + let out = export_document(&doc, &f, Some(max_side)).unwrap(); + assert_eq!((out.size.width, out.size.height), expected, "{width} × {height} at {scale}%, proxy limit {max_side}"); + assert!(out.size.width.max(out.size.height) <= max_side, "proxy respects its longest-side limit"); + assert_eq!(doc, before, "preview leaves the source document unchanged"); + } +} + +/// #6595: Export As shows the size the file will have, as Photoshop does. The proxy estimate +/// read 36–81 % of it for a detailed image; up to `EXACT_ESTIMATE_PX` the full export is +/// encoded off the UI thread instead. +#[test] +fn the_estimate_is_the_exported_files_size() { + let mut doc = Document::with_background( + "x", + photocraft_doc::Size::new(900, 300), + photocraft_doc::ColorMode::Rgb, + photocraft_doc::SampleType::U8, + photocraft_doc::Color::WHITE, + ); + let id = doc.layers[0].id; + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + let mut seed = 12345u32; + for y in (0..300).step_by(2) { + for x in (0..900).step_by(2) { + seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); + let v = (seed >> 24) as f32 / 255.0; + surf.fill_rect(photocraft_geom::Rect::new(x, y, x + 2, y + 2), &[v, x as f32 / 900.0, y as f32 / 300.0, 1.0]); + } + } + let doc = Arc::new(doc); + let f = Map::from_iter([("format".into(), json!("jpg")), ("scale".into(), json!(100)), ("quality".into(), json!(32))]); + let actual = photocraft_io::export(&export_document(&doc, &f, None).unwrap(), "x.jpg", &settings(&f).io_options()).unwrap().bytes.len() as u64; + let proxy = preview_proxy(&doc, &f).unwrap(); + let old = estimate_native(&doc, &proxy, &f).unwrap(); + assert!((old as f64 / actual as f64 - 1.0).abs() > 0.1, "the proxy estimate was off: {old} vs {actual}"); + + let ctx = egui::Context::default(); + let key = egui::Id::unique("exact-estimate-test"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + let size = loop { + let mut size = None; + let mut output = ctx.run_ui(Default::default(), |ctx| { + egui::CentralPanel::default().show(ctx, |ui| size = poll_or_start_exact_estimate(ui, key, "jpg32", doc.clone(), &f)); + }); + output.textures_delta.clear(); + if let Some(size) = size { + break size; + } + assert!(std::time::Instant::now() < deadline, "the exact estimate did not arrive"); + std::thread::sleep(std::time::Duration::from_millis(10)); + }; + assert_eq!(size, Some(actual)); + // Over the limit there is no exact size; the proxy estimate stays. + let huge = Map::from_iter([ + ("format".into(), json!("jpg")), + ("sizing".into(), json!("pixels")), + ("width".into(), json!(10_000)), + ("height".into(), json!(10_000)), + ]); + assert_eq!(exact_estimate(&doc, &huge), None); + // In scale mode the size comes from the scale, as the export's does, not from stale pixels. + let big = Arc::new(Document::with_background( + "big", + photocraft_doc::Size::new(1000, 1000), + photocraft_doc::ColorMode::Rgb, + photocraft_doc::SampleType::U8, + photocraft_doc::Color::WHITE, + )); + let stale = Map::from_iter([ + ("format".into(), json!("png")), + ("sizing".into(), json!("scale")), + ("scale".into(), json!(1000)), + ("width".into(), json!(100)), + ("height".into(), json!(100)), + ]); + assert_eq!(exact_estimate(&big, &stale), None, "10000 × 10000 at 1000 %, over the limit"); + let small = Map::from_iter([ + ("format".into(), json!("png")), + ("sizing".into(), json!("scale")), + ("scale".into(), json!(10)), + ("width".into(), json!(9000)), + ("height".into(), json!(9000)), + ]); + let at_10 = photocraft_io::export(&export_document(&big, &small, None).unwrap(), "x.png", &settings(&small).io_options()).unwrap().bytes.len() as u64; + assert_eq!(exact_estimate(&big, &small), Some(at_10), "100 × 100 at 10 %, within it"); +} + +/// #8341: Export As and its reduced preview carry the stroke width with the path. +#[test] +fn export_as_downscales_stroke_only_shapes_and_preview() { + for depth in [8, 16, 32] { + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 1024, "height": 1024, "depth": depth, "background": "transparent"})).unwrap(); + let id = session.execute("shape.create", json!({"rect": [256, 256, 512, 512], "fill": null, "stroke": {"width": 32}})).unwrap()["layer"] + .as_u64() + .unwrap(); + let doc = session.active().unwrap().doc.clone(); + let fields = Map::from_iter([("format".into(), json!("png")), ("scale".into(), json!(25))]); + for limit in [None, Some(128)] { + let out = export_document(&doc, &fields, limit).unwrap(); + let side = if limit.is_some() { 128 } else { 256 }; + assert_eq!((out.size.width, out.size.height), (side, side)); + let shape = out.layer(photocraft_doc::LayerId(id)).unwrap(); + let photocraft_doc::LayerContent::Shape(shape) = &shape.content else { + panic!("shape lost"); + }; + assert_eq!(shape.stroke.as_ref().unwrap().width, side as f32 / 32.0); + let pixels = photocraft_compose::flatten(&out); + let row = (side / 2 * side) as usize; + assert!(pixels.px[row + (side / 4) as usize][3] > 0.99); + assert!(pixels.px[row + (side / 4 - side / 32) as usize][3] < 0.01); + assert!(pixels.px[row + (side / 2) as usize][3] < 0.01); + } + assert_eq!(session.active().unwrap().doc, doc, "export leaves the source unchanged"); + } +} + +#[test] +fn export_document_scales_and_flattens() { + let doc = Document::with_background( + "x", + photocraft_doc::Size::new(200, 100), + photocraft_doc::ColorMode::Rgb, + photocraft_doc::SampleType::U8, + photocraft_doc::Color::WHITE, + ); + let mut f = Map::new(); + f.insert("format".into(), json!("jpg")); + f.insert("scale".into(), json!(50)); + let out = export_document(&doc, &f, None).unwrap(); + assert_eq!((out.size.width, out.size.height), (100, 50)); + assert_eq!(out.layers.len(), 1); + let proxy = export_document(&doc, &f, Some(40)).unwrap(); + assert_eq!(proxy.size.width, 40); + assert_eq!(settings(&f).jpeg_quality, Some(85)); +} + +/// #1353: a scale that changes only the height (the width rounds back to the original) +/// used to be skipped, so the exported file kept the original size while the dialog +/// labelled it as scaled. +#[test] +fn export_document_scales_when_only_the_height_changes() { + let mut f = Map::new(); + f.insert("format".into(), json!("png")); + f.insert("scale".into(), json!(50)); + for (src_h, want_h) in [(100u32, 50u32), (200, 100)] { + let doc = Document::with_background( + "x", + photocraft_doc::Size::new(1, src_h), + photocraft_doc::ColorMode::Rgb, + photocraft_doc::SampleType::U8, + photocraft_doc::Color::WHITE, + ); + let out = export_document(&doc, &f, None).unwrap(); + assert_eq!((out.size.width, out.size.height), (1, want_h), "1 × {src_h} at 50%"); + // The preview proxy takes the same path. + let proxy = export_document(&doc, &f, Some(40)).unwrap(); + assert_eq!((proxy.size.width, proxy.size.height), (1, 40), "proxy of 1 × {src_h}"); + } + // The label and the export agree, and neither side drops below 1 px. + assert_eq!(scaled_size(1.0, 100.0, 0.5), (1.0, 50.0)); + assert_eq!(scaled_size(10.0, 300.0, 0.01), (1.0, 3.0)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn layered_preview_runs_outside_the_ui_frame() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 16})).unwrap(); + for _ in 0..33 { + app.run("layer.new.layer", json!({})).unwrap(); + } + let doc = app.session.active().unwrap().doc.clone(); + assert!(background_preview_needed(&doc)); + let fields = Map::from_iter([("format".into(), json!("png")), ("scale".into(), json!(100))]); + let ctx = egui::Context::default(); + let key = egui::Id::unique("layered-preview-test"); + let mut result = None; + let mut output = ctx.run_ui(Default::default(), |ctx| { + egui::CentralPanel::default().show(ctx, |ui| { + result = poll_or_start_preview(ui, key, "png100", doc.clone(), &fields); + }); + }); + output.textures_delta.clear(); + assert!(result.is_none(), "the first UI frame must only start the worker"); + + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + loop { + let mut output = ctx.run_ui(Default::default(), |ctx| { + egui::CentralPanel::default().show(ctx, |ui| { + result = poll_or_start_preview(ui, key, "png100", doc.clone(), &fields); + }); + }); + output.textures_delta.clear(); + if let Some(preview) = result { + let preview = preview.unwrap(); + assert_eq!((preview.width, preview.height), (32, 16)); + assert_eq!(preview.rgba.len(), 32 * 16 * 4); + assert!(preview.estimate.is_some_and(|bytes| bytes > 0)); + break; + } + assert!(std::time::Instant::now() < deadline, "background preview did not complete"); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + + let tiff_fields = Map::from_iter([("format".into(), json!("tif")), ("scale".into(), json!(100))]); + let proxy = preview_proxy(&doc, &tiff_fields).unwrap(); + let options = photocraft_io::ExportOptions { tiff_layers: true, xmp: photocraft_io::XmpEmbed::None, ..Default::default() }; + let actual_bytes = photocraft_io::export(&proxy, "estimate.tif", &options).unwrap().bytes.len(); + assert_eq!(estimate_native(&doc, &proxy, &tiff_fields), Some(scaled_estimate(actual_bytes, &doc, &proxy, &tiff_fields))); +} + +#[test] +fn switching_export_formats_uses_independent_quality_preferences() { + let prefs = photocraft_engine::prefs::Export { jpeg_quality: 43, webp_quality: 72, webp_lossless: false, ..Default::default() }; + let mut fields = Map::new(); + set_format_defaults(&mut fields, "webp", &prefs); + assert_eq!(fields["quality"], 72); + assert_eq!(fields["lossless"], false); + let s = settings(&fields); + assert!(!s.webp_lossless); + assert_eq!(s.webp_quality, Some(72)); + assert_eq!(s.jpeg_quality, None); + + set_format_defaults(&mut fields, "jpg", &prefs); + assert_eq!(fields["quality"], 43); + assert_eq!(settings(&fields).jpeg_quality, Some(43)); + assert_eq!(settings(&fields).webp_quality, None); + + set_format_defaults(&mut fields, "webp", &photocraft_engine::prefs::Export::default()); + assert!(settings(&fields).webp_lossless, "default WebP Quick Export mode is lossless"); + assert_eq!(settings(&fields).webp_quality, None); +} + +#[test] +fn webp_settings_follow_the_lossless_switch() { + let mut f = Map::new(); + f.insert("format".into(), json!("webp")); + f.insert("quality".into(), json!(70)); + let s = settings(&f); + assert!(!s.webp_lossless, "Export As writes lossy WebP unless asked"); + assert_eq!(s.webp_quality, Some(70)); + assert_eq!(s.jpeg_quality, None); + f.insert("lossless".into(), json!(true)); + let s = settings(&f); + assert!(s.webp_lossless); + assert_eq!(s.webp_quality, None); + f.insert("format".into(), json!("png")); + assert!(settings(&f).webp_lossless, "other formats leave the WebP default alone"); +} + +/// TGA's Resolution (bits per pixel): Auto leaves the choice to the export; 24 and 32 force it, and only +/// for TGA. +#[test] +fn tga_settings_follow_the_bits_per_pixel() { + use photocraft_io::TgaBits; + let mut f = Map::new(); + f.insert("format".into(), json!("tga")); + assert_eq!(settings(&f).tga_bits, None, "no choice made"); + for (v, want) in [("auto", None), ("24", Some(TgaBits::Bits24)), ("32", Some(TgaBits::Bits32)), ("16", None)] { + f.insert("tgaBits".into(), json!(v)); + assert_eq!(settings(&f).tga_bits, want, "{v}"); + } + f.insert("format".into(), json!("png")); + assert_eq!(settings(&f).tga_bits, None, "only TGA has bits per pixel"); +} + +#[test] +fn exact_pixels_lock_aspect_and_leave_the_source() { + let linked = resize_from_scale(400.0, 200.0, 50.0).unwrap(); + assert_eq!((linked.width, linked.height, linked.scale), (200.0, 100.0, 50.0)); + let from_width = resize_from_side(400.0, 200.0, 100.0, 200.0, true, true).unwrap(); + assert_eq!((from_width.width, from_width.height), (100.0, 50.0)); + let from_height = resize_from_side(400.0, 200.0, 100.0, 40.0, true, false).unwrap(); + assert_eq!((from_height.width, from_height.height), (80.0, 40.0)); + let free = resize_from_side(400.0, 200.0, 100.0, 80.0, false, true).unwrap(); + assert_eq!((free.width, free.height), (100.0, 80.0)); + assert!(resize_from_scale(400.0, 200.0, 0.0).is_err()); + assert!(resize_from_side(400.0, 200.0, 0.0, 10.0, false, true).is_err()); + assert!(resize_from_side(10.0, 10.0, 400_000.0, 10.0, false, true).is_err()); + + let doc = Document::with_background( + "x", + photocraft_doc::Size::new(400, 200), + photocraft_doc::ColorMode::Rgb, + photocraft_doc::SampleType::U8, + photocraft_doc::Color::WHITE, + ); + let before = doc.clone(); + let mut f = Map::new(); + f.insert("format".into(), json!("png")); + f.insert("scale".into(), json!(100)); + f.insert("sizing".into(), json!("pixels")); + f.insert("width".into(), json!(120)); + f.insert("height".into(), json!(40)); + let out = export_document(&doc, &f, None).unwrap(); + assert_eq!((out.size.width, out.size.height), (120, 40), "explicit pixels win over the percent scale"); + let proxy = export_document(&doc, &f, Some(20)).unwrap(); + assert_eq!((proxy.size.width, proxy.size.height), (20, 7)); + assert_eq!(doc, before, "export leaves the source document unchanged"); +} + +#[test] +fn profile_and_metadata_follow_the_existing_exporter() { + use photocraft_cms::Builtin; + + let mut f = Map::new(); + f.insert("format".into(), json!("jpg")); + assert!(settings(&f).embed_metadata, "a missing metadata choice keeps EXIF and resolution"); + assert!(settings(&f).embed_icc); + f.insert("metadata".into(), json!("none")); + f.insert("embedProfile".into(), json!(false)); + let none = settings(&f); + assert!(!none.xmp_all && !none.embed_metadata && !none.embed_icc); + f.insert("metadata".into(), json!("exif")); + let exif = settings(&f); + assert!(!exif.xmp_all && exif.embed_metadata); + f.insert("metadata".into(), json!("all")); + f.insert("embedProfile".into(), json!(true)); + let all = settings(&f); + assert!(all.xmp_all && all.embed_metadata && all.embed_icc); + + let mut doc = Document::with_background( + "x", + photocraft_doc::Size::new(8, 8), + photocraft_doc::ColorMode::Rgb, + photocraft_doc::SampleType::U8, + photocraft_doc::Color::WHITE, + ); + doc.icc_profile = Some(Builtin::DisplayP3.profile().to_bytes()); + doc.metadata.xmp = Some("secret".into()); + let before = doc.clone(); + f.insert("profile".into(), json!("srgb")); + f.insert("width".into(), json!(8)); + f.insert("height".into(), json!(8)); + f.insert("metadata".into(), json!("none")); + f.insert("embedProfile".into(), json!(false)); + let converted = export_document(&doc, &f, None).unwrap(); + let parsed = photocraft_cms::Profile::parse(converted.icc_profile.as_deref().unwrap()).unwrap(); + assert!(parsed.same_colors(Builtin::Srgb.profile()), "Convert to sRGB replaces the document profile"); + let stripped = photocraft_io::export(&converted, "out.jpg", &settings(&f).io_options()).unwrap().bytes; + assert!(!stripped.windows(b"ICC_PROFILE".len()).any(|w| w == b"ICC_PROFILE")); + assert!(!stripped.windows(b"secret".len()).any(|w| w == b"secret")); + f.insert("metadata".into(), json!("all")); + f.insert("embedProfile".into(), json!(true)); + let kept = photocraft_io::export(&converted, "out.jpg", &settings(&f).io_options()).unwrap().bytes; + assert!(kept.windows(b"ICC_PROFILE".len()).any(|w| w == b"ICC_PROFILE")); + assert!(kept.windows(b"secret".len()).any(|w| w == b"secret")); + assert_eq!(doc, before); +} + +#[test] +fn applying_a_preset_restores_its_size_mode() { + use photocraft_engine::export_preset_cmds::ExportPresetSettings; + + let pixels = ExportPresetSettings { + format: "png".into(), + quality: 80, + lossless: false, + transparency: true, + scale: 100.0, + width: 64, + height: 32, + lock_aspect: false, + sizing: "pixels".into(), + metadata: "exif".into(), + profile: "document".into(), + embed_profile: false, + tga_bits: "auto".into(), + resample: "nearest".into(), + }; + let mut f = Map::new(); + apply_preset(&mut f, &pixels, 400.0, 200.0); + assert_eq!(f.get("resample"), Some(&json!("nearest")), "a preset restores its Resample method"); + assert_eq!(preset_settings(&f)["resample"], "nearest", "and saves it"); + assert_eq!(f.get("width"), Some(&json!(64))); + assert_eq!(f.get("height"), Some(&json!(32))); + assert_eq!(f.get("sizing"), Some(&json!("pixels"))); + assert_eq!(f.get("embedProfile"), Some(&json!(false))); + let scale = ExportPresetSettings { sizing: "scale".into(), scale: 25.0, ..pixels }; + apply_preset(&mut f, &scale, 400.0, 200.0); + assert_eq!(f.get("width"), Some(&json!(100.0))); + assert_eq!(f.get("height"), Some(&json!(50.0))); + assert_eq!(f.get("sizing"), Some(&json!("scale"))); +} From 5718c1ebf49db82631ce6718520d0aae4f7cdfaa Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:49 +0000 Subject: [PATCH 066/259] refactor(ui-egui): move canvas_tool_menu.rs tests to canvas_tool_menu/tests.rs --- crates/ui-egui/src/canvas_tool_menu.rs | 1210 +----------------- crates/ui-egui/src/canvas_tool_menu/tests.rs | 1207 +++++++++++++++++ 2 files changed, 1208 insertions(+), 1209 deletions(-) create mode 100644 crates/ui-egui/src/canvas_tool_menu/tests.rs diff --git a/crates/ui-egui/src/canvas_tool_menu.rs b/crates/ui-egui/src/canvas_tool_menu.rs index 1f5ae2e066..dd9b635e64 100644 --- a/crates/ui-egui/src/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas_tool_menu.rs @@ -1177,1212 +1177,4 @@ pub fn show(app: &mut PhotocraftApp, ctx: &Context) { } #[cfg(test)] -mod tests { - use super::*; - use egui::{Modifiers, PointerButton, Pos2, vec2}; - use egui_kittest::{Harness, kittest::Queryable}; - - 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(); - app - } - - fn work_path(app: &mut PhotocraftApp) { - app.run( - "path.set", - json!({"name": "work", "path": {"subpaths": [{"closed": true, "knots": [ - {"anchor": [2, 2], "in": [2, 2], "out": [2, 2]}, - {"anchor": [20, 2], "in": [20, 2], "out": [20, 2]}, - {"anchor": [20, 20], "in": [20, 20], "out": [20, 20]} - ]}]}}), - ) - .unwrap(); - } - - fn choose_open(app: &mut PhotocraftApp, command: &str) { - assert!(open(app, &Context::default(), Tool::Pen, [10.0, 10.0])); - choose(app, &Context::default(), command); - } - - fn harness(mut app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { - app.sync_views(); - 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; - } - 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 - } - - fn right_click(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, modifiers: Modifiers) { - h.event(egui::Event::ModifiersChanged(modifiers)); - h.event(egui::Event::PointerMoved(p)); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers }); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers }); - h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); - h.run_steps(2); - } - - #[test] - fn canvas_gesture_preserves_selection_and_command_override() { - let mut app = app(); - app.ui.tool = Tool::Lasso; - app.run("select.rect", json!({"x": 1, "y": 1, "width": 8, "height": 8})).unwrap(); - let mut h = harness(app); - let center = h.state().last_canvas_rect.center(); - let revision = h.state().session.active().unwrap().revision; - right_click(&mut h, center, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.is_some()); - assert_eq!(h.state().session.active().unwrap().revision, revision, "right-click cannot alter selection"); - h.key_press(egui::Key::Escape); - h.run_steps(2); - assert!(h.state().ui.canvas_tool_menu.is_none()); - right_click(&mut h, center, Modifiers::COMMAND); - assert!(h.state().ui.canvas_tool_menu.is_none(), "command right-click belongs to layer picker"); - } - - /// A type layer reading "Hello", being edited with every character selected. - fn editing_type(app: &mut PhotocraftApp) -> u64 { - app.ui.tool = Tool::Type; - let id = app.run("type.create", json!({"text": "Hello", "size": 12, "x": 4, "y": 20})).unwrap()["layer"].as_u64().unwrap(); - crate::menus::invoke(app, &Context::default(), "type.editText", json!({})).unwrap(); - id - } - - fn text_of(app: &PhotocraftApp, id: u64) -> Option { - match &app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content { - LayerContent::Text(t) => Some(t.clone()), - _ => None, - } - } - - #[test] - fn right_click_while_typing_opens_the_type_edit_menu_and_esc_keeps_the_edit() { - let mut app = app(); - editing_type(&mut app); - app.sync_views(); - 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; - } - // The app's order: shortcuts (inline type's keys among them), then the canvas. - 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); - let center = h.state().last_canvas_rect.center(); - right_click(&mut h, center, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().expect("right-click in a type edit opens a menu"); - assert!(menu.text && !menu.pasteboard && !menu.transform); - assert_eq!(rows(&menu), TYPE_EDIT_MENU); - let edit = h.state().ui.text_edit.clone().expect("the edit goes on under the menu"); - assert_eq!((edit.anchor, edit.caret), (0, 5), "the right-click keeps the selection for Cut and Copy"); - h.key_press(egui::Key::Escape); - h.run_steps(2); - assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu"); - assert!(h.state().ui.text_edit.is_some(), "and only the menu: the edit isn't committed"); - } - - #[test] - fn type_edit_menu_rows_act_on_the_text_and_the_layer() { - let mut app = app(); - let id = editing_type(&mut app); - let ctx = Context::default(); - let reopen = |app: &mut PhotocraftApp| assert!(open(app, &Context::default(), Tool::Type, [10.0, 10.0])); - // Faux Bold toggles the style of the selected characters, and shows checked. - reopen(&mut app); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - assert!(!mode_checked(&app, &menu, FAUX_BOLD) && mode_checked(&app, &menu, "type.antiAlias.smooth")); - choose(&mut app, &ctx, FAUX_BOLD); - assert!(text_of(&app, id).unwrap().char_runs().iter().all(|r| r.style.faux_bold)); - assert!(mode_checked(&app, &menu, FAUX_BOLD)); - // Cut takes the selection out of the text; with nothing selected Copy and Cut grey out. - reopen(&mut app); - choose(&mut app, &ctx, "edit.cut"); - assert_eq!(text_of(&app, id).unwrap().text, ""); - reopen(&mut app); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - assert!(!entry_enabled(&app, &menu, "edit.copy") && !entry_enabled(&app, &menu, "edit.cut")); - app.ui.canvas_tool_menu = None; - crate::menus::invoke(&mut app, &ctx, "edit.undo", json!({})).unwrap(); - assert_eq!(text_of(&app, id).unwrap().text, "Hello"); - // Select All selects every character, not the canvas. - reopen(&mut app); - choose(&mut app, &ctx, "select.all"); - let edit = app.ui.text_edit.clone().unwrap(); - assert_eq!((edit.anchor, edit.caret), (0, 5)); - assert!(app.session.active().unwrap().doc.selection.is_none()); - // Warp Text… opens its dialog; Rasterize Type ends the edit and rasterizes the layer. - reopen(&mut app); - choose(&mut app, &ctx, "type.warpText"); - assert!(!app.ui.dialogs.is_empty(), "Warp Text… asks for its settings"); - app.ui.dialogs.clear(); - reopen(&mut app); - choose(&mut app, &ctx, "type.rasterizeTypeLayer"); - assert!(app.ui.text_edit.is_none() && text_of(&app, id).is_none(), "the type layer is pixels now"); - } - - /// A committed type layer reading "Hello" over the middle of the canvas, no edit running. - fn committed_type(app: &mut PhotocraftApp) -> u64 { - app.ui.tool = Tool::Type; - let id = app.run("type.create", json!({"text": "Hello", "size": 14, "x": 1, "y": 22})).unwrap()["layer"].as_u64().unwrap(); - assert!(app.ui.text_edit.is_none()); - id - } - - #[test] - fn right_click_on_committed_type_opens_the_type_layer_menu() { - use photocraft_doc::text::Orientation; - let mut app = app(); - let id = committed_type(&mut app); - assert_eq!(crate::type_tool::hit_layer(&mut app, 16.0, 16.0).map(|l| l.0), Some(id), "the canvas centre is on the type"); - let mut h = harness(app); - let center = h.state().last_canvas_rect.center(); - right_click(&mut h, center, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().expect("right-click on committed type opens a menu (#7324)"); - assert!(menu.type_layer && !menu.text && !menu.pasteboard); - assert_eq!(rows(&menu), TYPE_LAYER_MENU); - assert!(h.state().ui.text_edit.is_none(), "the right-click doesn't start an edit"); - h.run_steps(2); - assert!(h.state().ui.canvas_tool_menu.is_some(), "the menu stays open without an edit"); - // An edit started some other way (here, as an agent's Type › Edit Text would) closes the - // menu, which has no text edit rows. - crate::menus::invoke(h.state_mut(), &Context::default(), "type.editText", json!({})).unwrap(); - h.run_steps(2); - assert!(h.state().ui.canvas_tool_menu.is_none(), "an edit closes the type layer menu"); - crate::type_tool::commit(h.state_mut()); - right_click(&mut h, center, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().expect("committed again, the menu opens again"); - assert!(menu.type_layer && mode_checked(h.state(), &menu, "type.orientation.horizontal")); - choose(h.state_mut(), &Context::default(), "type.orientation.vertical"); - assert_eq!(text_of(h.state(), id).unwrap().orientation, Orientation::Vertical); - } - - #[test] - fn type_layer_menu_targets_the_type_under_the_pointer() { - let mut app = app(); - let id = committed_type(&mut app); - app.run("layer.new.layer", json!({})).unwrap(); - let ctx = Context::default(); - let active = |app: &PhotocraftApp| app.session.active().unwrap().active_layer.map(|l| l.0); - assert_ne!(active(&app), Some(id)); - // Away from the type, or with a Type Mask tool, nothing opens and nothing is selected. - assert!(!open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([30.0, 2.0]))); - assert!(!open_at(&mut app, &ctx, Tool::HorizontalTypeMask, [10.0, 10.0], Some([16.0, 16.0]))); - assert!(!open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([f64::NAN, 16.0]))); - assert_ne!(active(&app), Some(id)); - // Over the type: its layer becomes the target, and the menu has no text edit rows. - assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([16.0, 16.0]))); - assert_eq!(active(&app), Some(id)); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - for edit_row in ["edit.undo", "edit.cut", "edit.copy", "edit.paste", "select.all", FAUX_BOLD, FAUX_ITALIC] { - assert!(!available(&app, &menu, edit_row), "{edit_row} belongs to the edit menu only"); - } - assert!(entry_enabled(&app, &menu, "type.convertToParagraphText") && !entry_enabled(&app, &menu, "type.convertToPointText")); - choose(&mut app, &ctx, "type.rasterizeTypeLayer"); - assert!(text_of(&app, id).is_none(), "the type layer is pixels now"); - assert!(app.ui.text_edit.is_none()); - } - - /// Two selected type layers: the one right-clicked becomes active, and the selection stays. - #[test] - fn type_layer_menu_in_a_multiselection_acts_on_the_clicked_type() { - 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::Type; - let top = app.run("type.create", json!({"text": "Top", "size": 30, "x": 10, "y": 40})).unwrap()["layer"].as_u64().unwrap(); - let bottom = app.run("type.create", json!({"text": "Low", "size": 30, "x": 10, "y": 90})).unwrap()["layer"].as_u64().unwrap(); - app.run("layer.select", json!({"layer": bottom})).unwrap(); - app.run("layer.select", json!({"layer": top, "mode": "add"})).unwrap(); - let at = [25.0, 80.0]; - assert_eq!(crate::type_tool::hit_layer(&mut app, at[0], at[1]).map(|l| l.0), Some(bottom)); - assert_eq!(app.session.active().unwrap().active_layer.map(|l| l.0), Some(top)); - let ctx = Context::default(); - assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some(at))); - let st = app.session.active().unwrap(); - assert_eq!(st.active_layer.map(|l| l.0), Some(bottom), "the clicked type is the target"); - assert_eq!(st.selected_layers().len(), 2, "the multiselection stays"); - choose(&mut app, &ctx, "type.rasterizeTypeLayer"); - assert!(text_of(&app, bottom).is_none(), "the clicked type is rasterized"); - assert!(text_of(&app, top).is_some(), "not the other selected type"); - } - - #[test] - fn type_edit_menu_lists_spelling_suggestions_for_the_word_under_the_pointer() { - let mut app = app(); - app.ui.tool = Tool::Type; - let id = app.run("type.create", json!({"text": "Teh cat", "size": 12, "x": 4, "y": 20})).unwrap()["layer"].as_u64().unwrap(); - let ctx = Context::default(); - crate::menus::invoke(&mut app, &ctx, "type.editText", json!({})).unwrap(); - // Away from the misspelling (past the end of the line): no spelling rows. - assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([600.0, 15.0]))); - assert!(spelling_rows(app.ui.canvas_tool_menu.as_ref().unwrap()).is_empty()); - // Over "Teh": its suggestions head the menu, then Add to Dictionary. - assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([5.0, 15.0]))); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - let rows = spelling_rows(&menu); - assert!(rows.iter().any(|(l, _)| l == "The"), "{rows:?}"); - assert_eq!(rows.last().map(|(_, id)| id.as_str()), Some(SPELLING_ADD)); - assert!(rows.len() <= MAX_SUGGESTIONS + 1, "at most {MAX_SUGGESTIONS} suggestions and Add to Dictionary: {rows:?}"); - assert!(available(&app, &menu, &rows[0].1)); - let pick = rows.iter().find(|(l, _)| l == "The").unwrap().1.clone(); - choose(&mut app, &ctx, &pick); - assert_eq!(text_of(&app, id).unwrap().text, "The cat"); - assert_eq!(app.ui.text_edit.as_ref().map(|e| (e.caret, e.anchor)), Some((3, 3)), "the caret lands after the replacement"); - // Add to Dictionary stops flagging a word. - app.run("type.insertText", json!({"layer": id, "text": " Zqx"})).unwrap(); - assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([600.0, 15.0]))); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - assert!(menu.spelling.as_ref().is_some_and(|s| s.word == "Zqx")); - choose(&mut app, &ctx, SPELLING_ADD); - assert!(app.session.prefs().user_dictionary.iter().any(|w| w == "Zqx")); - } - - #[test] - fn right_click_outside_the_image_picks_the_pasteboard_color() { - let mut app = app(); - app.ui.tool = Tool::RectMarquee; - let mut h = harness(app); - let rect = h.state().last_canvas_rect; - let outside = rect.min + vec2(5.0, 5.0); - right_click(&mut h, rect.center(), Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| !m.pasteboard), "inside: the tool's own menu"); - h.state_mut().ui.canvas_tool_menu = None; - right_click(&mut h, outside, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().unwrap(); - assert!(menu.pasteboard && rows(&menu) == PASTEBOARD_MENU, "outside: the pasteboard menu"); - let ctx = h.ctx.clone(); - choose(h.state_mut(), &ctx, "pasteboard.black"); - assert_eq!(crate::prefs_ui::pasteboard_color(h.state()), Some(egui::Color32::BLACK)); - // Select Custom Color… opens the Color Picker; OK makes its colour the custom pasteboard. - right_click(&mut h, outside, Modifiers::NONE); - choose(h.state_mut(), &ctx, PASTEBOARD_PICK); - let mut f = h.state().ui.dialogs.last().unwrap().fields.clone(); - f.insert("color".into(), json!("#123456")); - crate::color_picker_ui::confirm(h.state_mut(), &f).unwrap(); - assert_eq!(crate::prefs_ui::pasteboard_color(h.state()), Some(egui::Color32::from_rgb(0x12, 0x34, 0x56))); - // A painting tool keeps its Brush Preset picker there. - h.state_mut().ui.tool = Tool::Brush; - h.run_steps(2); - right_click(&mut h, outside, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.is_none() && h.state().ui.brush_picker.is_some()); - } - - /// #2832: right-click over an open Free Transform box: Photoshop's transform menu. Skew - /// switches the box's mode; Rotate and Flip turn the box about its reference point without - /// committing it; Content-Aware Scale and Puppet Warp are greyed. - #[test] - fn right_click_during_free_transform_switches_modes_rotates_and_flips_the_box() { - let mut app = app(); - app.ui.tool = Tool::RectMarquee; - app.run("layer.new.layer", json!({})).unwrap(); - app.run("select.rect", json!({"x": 4, "y": 6, "width": 10, "height": 8})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.run("select.deselect", json!({})).unwrap(); - let mut h = harness(app); - let ctx = h.ctx.clone(); - crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); - h.run_steps(2); - let center = h.state().last_canvas_rect.center(); - let (revision, journal) = (h.state().session.active().unwrap().revision, h.state().session.journal.len()); - right_click(&mut h, center, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().expect("the transform menu"); - assert!(menu.transform && rows(&menu) == TRANSFORM_MENU); - for (id, on) in - [("edit.contentAwareScale", false), ("edit.puppetWarp", false), ("edit.transform.rotate90Cw", true), ("edit.transform.flipVertical", true)] - { - assert_eq!(entry_enabled(h.state(), &menu, id), on, "{id}"); - } - choose(h.state_mut(), &ctx, "edit.transform.skew"); - assert_eq!(h.state().ui.transform.as_ref().unwrap().mode, crate::state::TransformMode::Skew); - let t = h.state().ui.transform.clone().unwrap(); - let (q0, c) = (t.quad, t.pivot); - right_click(&mut h, center, Modifiers::NONE); - choose(h.state_mut(), &ctx, "edit.transform.flipHorizontal"); - let q = h.state().ui.transform.as_ref().expect("the box stays open").quad; - for (a, b) in q.iter().zip(q0) { - assert!((a[0] - (2.0 * c[0] - b[0])).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9, "mirrored about the reference point: {q0:?} -> {q:?}"); - } - right_click(&mut h, center, Modifiers::NONE); - choose(h.state_mut(), &ctx, "edit.transform.rotate180"); - let q = h.state().ui.transform.as_ref().unwrap().quad; - for (a, b) in q.iter().zip(q0) { - assert!((a[1] - (2.0 * c[1] - b[1])).abs() < 1e-9 && (a[0] - b[0]).abs() < 1e-9, "flipped then turned 180°: {q0:?} -> {q:?}"); - } - let st = h.state().session.active().unwrap(); - assert_eq!((st.revision, h.state().session.journal.len()), (revision, journal), "nothing is committed"); - } - - #[test] - fn transform_menu_follows_photoshop_order() { - assert_eq!( - labels(TRANSFORM_MENU), - vec![ - Some("Free Transform"), - Some("Scale"), - Some("Rotate"), - Some("Skew"), - Some("Distort"), - Some("Perspective"), - Some("Warp"), - None, - Some("Content-Aware Scale"), - Some("Puppet Warp"), - None, - Some("Rotate 180°"), - Some("Rotate 90° Clockwise"), - Some("Rotate 90° Counter Clockwise"), - None, - Some("Flip Horizontal"), - Some("Flip Vertical"), - ] - ); - // Over a box on editable type, Distort and Perspective are greyed (#2630). - let mut app = app(); - app.run("type.create", json!({"x": 2, "y": 20, "text": "Hi", "size": 16})).unwrap(); - crate::transform_tool::begin(&mut app, &Context::default()).unwrap(); - assert!(open_transform(&mut app, &Context::default(), [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - for (id, on) in [("edit.transform.skew", true), ("edit.transform.distort", false), ("edit.transform.perspective", false)] { - assert_eq!(entry_enabled(&app, &menu, id), on, "{id}"); - } - } - - fn labels(rows: &[Row]) -> Vec> { - rows.iter().map(|row| row.map(|(label, _)| label)).collect() - } - - #[test] - fn selection_menus_follow_photoshop_order() { - assert_eq!( - labels(SELECTION_MENU), - vec![ - Some("Deselect"), - Some("Select Inverse"), - Some("Feather…"), - Some("Select and Mask…"), - None, - Some("Save Selection…"), - Some("Make Work Path…"), - None, - Some("Layer via Copy"), - Some("Layer via Cut"), - Some("New Layer…"), - None, - Some("Free Transform"), - Some("Transform Selection"), - Some("Distort"), - Some("Perspective"), - None, - Some("Delete and Fill Selection"), - Some("Fill…"), - Some("Stroke…"), - Some("Content-Aware Fill…"), - None, - Some("Last Filter"), - None, - Some("Fade…"), - ] - ); - assert_eq!(labels(NO_SELECTION_MENU), vec![Some("Select All"), Some("Reselect"), Some("Color Range…"), None, Some("Load Selection…")]); - // Every row runs a real command: one the menu bar has, or an engine command. - let app = app(); - let items = crate::menus::menu_items(&app); - for (label, id) in [SELECTION_MENU, NO_SELECTION_MENU, PEN_MENU, TRANSFORM_MENU].into_iter().flatten().flatten() { - assert!(items.iter().any(|i| i.id == *id) || photocraft_engine::commands::find(id).is_some(), "{label}: unknown command {id}"); - } - } - - #[test] - fn selection_menu_routes_actions_through_commands() { - let mut app = app(); - app.ui.tool = Tool::RectMarquee; - app.run("select.rect", json!({"x": 1, "y": 1, "width": 8, "height": 8})).unwrap(); - assert!(open(&mut app, &Context::default(), Tool::RectMarquee, [10.0, 10.0])); - assert_eq!(rows(app.ui.canvas_tool_menu.as_ref().unwrap()), SELECTION_MENU); - let before = app.session.journal.len(); - choose(&mut app, &Context::default(), "select.inverse"); - assert!(app.ui.canvas_tool_menu.is_none()); - assert!(app.session.journal[before..].iter().any(|(id, _)| id == "select.inverse")); - let before = app.session.journal.len(); - assert!(open(&mut app, &Context::default(), Tool::RectMarquee, [10.0, 10.0])); - choose(&mut app, &Context::default(), "select.deselect"); - assert!(app.session.active().unwrap().doc.selection.is_none()); - assert!(app.session.journal[before..].iter().any(|(id, _)| id == "select.deselect")); - // Nothing selected: the menu that makes a selection. - assert!(open(&mut app, &Context::default(), Tool::RectMarquee, [10.0, 10.0])); - assert_eq!(rows(app.ui.canvas_tool_menu.as_ref().unwrap()), NO_SELECTION_MENU); - choose(&mut app, &Context::default(), "select.reselect"); - assert!(app.session.active().unwrap().doc.selection.is_some()); - assert!(app.session.journal.iter().any(|(id, _)| id == "select.reselect")); - app.run("select.deselect", json!({})).unwrap(); - assert!(open(&mut app, &Context::default(), Tool::Lasso, [10.0, 10.0])); - choose(&mut app, &Context::default(), "select.all"); - assert!(app.session.active().unwrap().doc.selection.is_some()); - } - - #[test] - fn selection_menu_layer_and_path_actions() { - let mut app = app(); - app.ui.tool = Tool::EllipseMarquee; - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.run("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); - let layers = app.session.active().unwrap().doc.layers.len(); - assert!(open(&mut app, &Context::default(), Tool::EllipseMarquee, [10.0, 10.0])); - choose(&mut app, &Context::default(), "layer.new.layerViaCopy"); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1, "Layer via Copy adds a layer"); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("layer.new.layerViaCopy")); - // Make Work Path… asks for the tolerance, then traces the selection. - app.run("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); - assert!(open(&mut app, &Context::default(), Tool::EllipseMarquee, [10.0, 10.0])); - choose(&mut app, &Context::default(), "select.toWorkPath"); - let dialog = app.ui.dialogs.last().map(|d| d.id).expect("tolerance dialog"); - assert!(app.session.active().unwrap().doc.work_path.is_none(), "nothing happens before OK"); - crate::dialogs::confirm(&mut app, dialog).unwrap(); - assert!(app.session.active().unwrap().doc.work_path.is_some()); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("select.toWorkPath")); - } - - #[test] - fn disabled_selection_rows_do_nothing() { - let mut app = app(); - app.ui.tool = Tool::MagicWand; - app.run("select.rect", json!({"x": 1, "y": 1, "width": 8, "height": 8})).unwrap(); - assert!(open(&mut app, &Context::default(), Tool::MagicWand, [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - // No filter has run and nothing can be faded yet. - for id in ["filter.lastFilter", "edit.fade"] { - assert!(!entry_enabled(&app, &menu, id), "{id} is greyed out"); - } - let before = app.session.journal.len(); - choose(&mut app, &Context::default(), "edit.fade"); - assert_eq!(app.session.journal.len(), before); - assert!(app.ui.dialogs.is_empty()); - // Rows of the other variant are not part of this menu. - assert!(open(&mut app, &Context::default(), Tool::MagicWand, [10.0, 10.0])); - choose(&mut app, &Context::default(), "select.all"); - assert_eq!(app.session.journal.len(), before); - } - - /// Photoshop's Zoom tool menu is Fit on Screen, 100%, 200%, Print Size, then Zoom In and Zoom - /// Out after a separator (#6005); Fill Screen (the Hand tool's) keeps its place by Fit on Screen. - #[test] - fn view_menu_follows_photoshop_order() { - assert_eq!( - labels(VIEW_MENU), - vec![Some("Fit on Screen"), Some("Fill Screen"), Some("100%"), Some("200%"), Some("Print Size"), None, Some("Zoom In"), Some("Zoom Out")] - ); - // Every row but Fill Screen (the Hand tool's options-bar button) is a View menu command. - let app = app(); - let items = crate::menus::menu_items(&app); - for (label, id) in VIEW_MENU.iter().flatten().filter(|(_, id)| *id != FILL_SCREEN) { - assert!(items.iter().any(|i| i.id == *id), "{label}: unknown command {id}"); - } - } - - fn zoom_app(w: u32, h: u32) -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": w, "height": h})).unwrap(); - app - } - - fn screen_of(app: &PhotocraftApp, doc: [f32; 2]) -> Pos2 { - crate::canvas::ViewXform::active(app).unwrap().to_screen(doc[0], doc[1]) - } - - #[test] - fn zoom_and_hand_right_click_opens_the_view_menu() { - for tool in [Tool::Zoom, Tool::Hand] { - let mut app = zoom_app(400, 300); - app.ui.tool = tool; - let mut h = harness(app); - let zoom = h.state().ui.views[0].zoom; - 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"); - 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. - h.state_mut().ui.canvas_tool_menu = None; - let outside = h.state().last_canvas_rect.min + vec2(5.0, 5.0); - right_click(&mut h, outside, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "{tool:?}: pasteboard menu outside"); - } - } - - #[test] - fn view_menu_zoom_in_keeps_the_clicked_point_under_the_pointer() { - 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 doc = [300.0, 100.0]; - let p = screen_of(h.state(), doc); - right_click(&mut h, p, Modifiers::NONE); - // Chosen in the menu itself: the canvas frame that draws the menu must keep the new view. - h.get_by_label("Zoom In").click(); - h.run_steps(3); - 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().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); - h.get_by_label("Zoom Out").click(); - h.run_steps(3); - assert_eq!(h.state().ui.views[0].zoom, zoom); - assert!((screen_of(h.state(), doc) - p).length() < 1.0); - } - - #[test] - fn animated_zoom_off_view_menu_keeps_the_anchor_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 doc = [300.0, 100.0]; - let p = screen_of(h.state(), doc); - right_click(&mut h, p, Modifiers::NONE); - let ctx = h.ctx.clone(); - choose(h.state_mut(), &ctx, command); - assert!(!h.state().ui.views[0].zoom_animating, "{command}"); - h.step(); - let v = &h.state().ui.views[0]; - let xf = crate::canvas::ViewXform::active(h.state()).unwrap(); - 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"); - } - } - } - - #[test] - fn view_menu_zoom_keeps_its_anchor_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 doc = [300.0, 100.0]; - let p = screen_of(h.state(), doc); - right_click(&mut h, p, Modifiers::NONE); - let ctx = h.ctx.clone(); - // Choose without the widget click helper, which runs repaint frames until settled. - choose(h.state_mut(), &ctx, "view.zoomIn"); - h.step(); - h.input_mut().time = Some(ctx.input(|i| i.time) + 0.11); - 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); - h.input_mut().time = Some(ctx.input(|i| i.time) + 0.3); - h.step(); - assert!(!h.state().ui.views[0].zoom_animating); - } - - #[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; - app.run("prefs.set", json!({"path": "tools.zoomClickedPointToCenter", "value": true})).unwrap(); - let mut h = harness(app); - let doc = [300.0, 100.0]; - let p = screen_of(h.state(), doc); - right_click(&mut h, p, Modifiers::NONE); - h.get_by_label("Zoom In").click(); - h.run_steps(3); - assert_eq!(h.state().ui.views[0].center, doc); - } - - #[test] - fn view_menu_fits_fills_and_sets_fixed_zooms() { - let mut app = zoom_app(400, 300); - app.ui.tool = Tool::Zoom; - let mut h = harness(app); - let p = screen_of(h.state(), [200.0, 150.0]); - let area = crate::rulers::content_rect(h.state(), h.state().last_canvas_rect).size(); - let ppp = h.state().canvas_ppp(); - let pick = |h: &mut Harness<'static, PhotocraftApp>, label: &str| { - right_click(h, p, Modifiers::NONE); - h.get_by_label(label).click(); - h.run_steps(3); - h.state().ui.views[0].zoom - }; - assert_eq!(pick(&mut h, "200%"), 2.0); - // Fill Screen: the image covers the whole canvas (one axis can overflow). - let fill = pick(&mut h, "Fill Screen") / ppp; - assert!(400.0 * fill >= area.x - 1.0 && 300.0 * fill >= area.y - 1.0, "fill {fill} for {area:?}"); - assert!(400.0 * fill <= area.x + 1.0 || 300.0 * fill <= area.y + 1.0, "fill {fill} for {area:?}"); - assert_eq!(h.state().ui.views[0].center, [200.0, 150.0]); - // Fit on Screen: back to the whole image (capped at 100%, as on open). - let fit = pick(&mut h, "Fit on Screen") / ppp; - assert!(400.0 * fit <= area.x && 300.0 * fit <= area.y && fit < fill, "fit {fit} fill {fill}"); - } - - #[test] - fn view_menu_needs_finite_points_and_a_view_tool() { - let mut app = app(); - assert!(!open_view(&mut app, &Context::default(), Tool::Brush, [1.0, 1.0], [1.0, 1.0])); - assert!(!open_view(&mut app, &Context::default(), Tool::Zoom, [f32::NAN, 1.0], [1.0, 1.0])); - assert!(!open_view(&mut app, &Context::default(), Tool::Zoom, [1.0, 1.0], [f64::INFINITY, 1.0])); - assert!(app.ui.canvas_tool_menu.is_none()); - assert!(open_view(&mut app, &Context::default(), Tool::Zoom, [1.0, 1.0], [1.0, 1.0])); - let before = app.session.journal.len(); - choose(&mut app, &Context::default(), "select.all"); - assert_eq!(app.session.journal.len(), before, "the view menu cannot run another menu's row"); - // With no document every row is greyed out and choosing one does nothing. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - assert!(open_view(&mut app, &Context::default(), Tool::Hand, [1.0, 1.0], [1.0, 1.0])); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - for (_, id) in VIEW_MENU.iter().flatten() { - assert!(!entry_enabled(&app, &menu, id), "{id} is greyed out with no document"); - } - choose(&mut app, &Context::default(), FILL_SCREEN); - choose(&mut app, &Context::default(), "view.zoomIn"); - } - - #[test] - fn unsupported_tools_and_nonfinite_positions_do_not_open_menu() { - let mut app = app(); - assert!(!open(&mut app, &Context::default(), Tool::Brush, [1.0, 1.0])); - assert!(!open(&mut app, &Context::default(), Tool::Lasso, [f32::NAN, 1.0])); - assert!(app.ui.canvas_tool_menu.is_none()); - assert!(open(&mut app, &Context::default(), Tool::MagicWand, [1.0, 1.0])); - let before = app.session.journal.len(); - choose(&mut app, &Context::default(), "file.new"); - assert_eq!(app.session.journal.len(), before, "context menu cannot invoke an unrelated command"); - } - - #[test] - fn completed_pen_path_right_click_makes_selection() { - let mut app = app(); - app.ui.tool = Tool::Pen; - for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { - crate::vector_ui::pen_down(&mut app, x, y, false); - crate::vector_ui::pen_up(&mut app); - } - crate::vector_ui::pen_commit(&mut app, true); - assert!(app.session.active().unwrap().doc.work_path.is_some()); - let mut h = harness(app); - let center = h.state().last_canvas_rect.center(); - right_click(&mut h, center, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.tool == Tool::Pen && m.has_path)); - let ctx = h.ctx.clone(); - choose(h.state_mut(), &ctx, "path.toSelection"); - let dialog = h.state().ui.dialogs.last().map(|d| d.id).unwrap(); - crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); - assert!(h.state().session.active().unwrap().doc.selection.is_some()); - assert_eq!(h.state().session.journal.last().map(|(id, _)| id.as_str()), Some("path.toSelection")); - } - - #[test] - fn pen_menu_finishes_in_progress_path_before_selection() { - let mut app = app(); - app.ui.tool = Tool::Pen; - for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { - crate::vector_ui::pen_down(&mut app, x, y, false); - crate::vector_ui::pen_up(&mut app); - } - assert!(app.session.active().unwrap().doc.work_path.is_none()); - assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); - assert!(entry_enabled(&app, menu, "path.toSelection")); - choose(&mut app, &Context::default(), "path.toSelection"); - let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); - crate::dialogs::confirm(&mut app, dialog).unwrap(); - assert!(app.session.active().unwrap().doc.work_path.is_some()); - assert!(app.session.active().unwrap().doc.selection.is_some()); - } - - /// #5703: the Pen options bar's Make Selection (Path mode) opens the same dialog for the path - /// being drawn (finished into the Work Path first), and OK selects inside it; with no path at - /// all it reports that instead. - #[test] - fn pen_options_bar_makes_a_selection_from_the_path() { - let mut app = app(); - app.ui.tool = Tool::Pen; - assert!(make_selection(&mut app).is_err(), "no path yet"); - assert!(app.ui.dialogs.is_empty()); - for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { - crate::vector_ui::pen_down(&mut app, x, y, false); - crate::vector_ui::pen_up(&mut app); - } - make_selection(&mut app).unwrap(); - let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); - crate::dialogs::confirm(&mut app, dialog).unwrap(); - let st = app.session.active().unwrap(); - assert!(st.doc.work_path.is_some() && st.doc.selection.is_some()); - // The active (Work) path again, with no pen path in progress. - app.run("select.deselect", json!({})).unwrap(); - make_selection(&mut app).unwrap(); - let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); - crate::dialogs::confirm(&mut app, dialog).unwrap(); - assert!(app.session.active().unwrap().doc.selection.is_some()); - // Drawn with a saved path selected, the path is added to that one (#4721): the dialog is - // for it, not for a Work Path. - app.run("path.rename", json!({"name": "work", "to": "Cutout"})).unwrap(); - app.ui.selected_path = Some("Cutout".into()); - for (x, y) in [(4.0, 24.0), (12.0, 24.0), (12.0, 30.0)] { - crate::vector_ui::pen_down(&mut app, x, y, false); - crate::vector_ui::pen_up(&mut app); - } - make_selection(&mut app).unwrap(); - assert_eq!(app.ui.dialogs.last().and_then(|d| d.fields.get("name")), Some(&json!("Cutout"))); - } - - /// #1056: the Path Selection and Direct Selection tools' right-click opens the path menu for - /// the selected path, as the Pen's does, instead of nothing. - #[test] - fn path_selection_tools_open_the_path_menu() { - for tool in [Tool::PathSelection, Tool::DirectSelection] { - let mut app = app(); - app.ui.tool = Tool::Pen; - for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { - crate::vector_ui::pen_down(&mut app, x, y, false); - crate::vector_ui::pen_up(&mut app); - } - crate::vector_ui::pen_commit(&mut app, false); - assert!(app.session.active().unwrap().doc.work_path.is_some()); - app.ui.tool = tool; - assert!(applies(tool)); - assert!(open(&mut app, &Context::default(), tool, [10.0, 10.0]), "{tool:?}"); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - assert_eq!(rows(&menu), PEN_MENU, "{tool:?}"); - assert!(menu.has_path && entry_enabled(&app, &menu, "path.toSelection"), "{tool:?}"); - choose(&mut app, &Context::default(), "path.toSelection"); - let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); - crate::dialogs::confirm(&mut app, dialog).unwrap(); - assert!(app.session.active().unwrap().doc.selection.is_some(), "{tool:?}: Make Selection made one"); - } - } - - #[test] - fn pen_menu_has_all_reference_rows_in_order_and_guards_unavailable_actions() { - let labels: Vec<_> = PEN_MENU.iter().map(|row| row.map(|(label, _)| label)).collect(); - assert_eq!( - labels, - vec![ - Some("Create Vector Mask"), - Some("Delete Path"), - None, - Some("Define Custom Shape…"), - None, - Some("Make Selection…"), - Some("New Guides From Shape"), - Some("Fill Path…"), - Some("Stroke Path…"), - None, - Some("Clipping Path…"), - None, - Some("Free Transform Path"), - None, - Some("Unite Shapes"), - Some("Subtract Front Shape"), - Some("Unite Shapes at Overlap"), - Some("Subtract Shapes at Overlap"), - None, - Some("Copy Fill"), - Some("Copy Complete Stroke"), - None, - Some("Paste Fill"), - Some("Paste Complete Stroke"), - None, - Some("Isolate Layers"), - None, - Some("Make Symmetry Path"), - Some("Disable Symmetry Path"), - ] - ); - let mut app = app(); - app.ui.tool = Tool::Pen; - assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); - assert!(!entry_enabled(&app, menu, "path.toSelection")); - let before = app.session.journal.len(); - choose(&mut app, &Context::default(), "path.toSelection"); - assert_eq!(app.session.journal.len(), before); - assert!(app.ui.dialogs.is_empty()); - } - - #[test] - fn pen_menu_creates_mask_deletes_path_and_opens_named_path_dialogs() { - let mut app = app(); - app.ui.tool = Tool::Pen; - work_path(&mut app); - choose_open(&mut app, "layer.vectorMask.fromPath"); - let st = app.session.active().unwrap(); - assert!(st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.vector_mask.is_some())); - // The new vector mask's path becomes the active one (#4728); pick the Work Path again. - assert_eq!(app.ui.selected_path.as_deref(), Some("layer")); - app.ui.selected_path = Some("work".into()); - choose_open(&mut app, "edit.defineCustomShape"); - let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); - let fields = &app.ui.dialogs.last().unwrap().fields; - assert_eq!(fields.get("path"), Some(&json!("work"))); - app.ui.dialog_mut(id).unwrap().fields.insert("name".into(), json!("Menu Shape")); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert!(app.session.edit_state.custom_shapes.iter().any(|s| s.name == "Menu Shape")); - choose_open(&mut app, "path.fill"); - let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); - assert_eq!(app.ui.dialogs.last().unwrap().fields.get("name"), Some(&json!("work"))); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("path.fill")); - choose_open(&mut app, "path.delete"); - assert!(app.session.active().unwrap().doc.work_path.is_none()); - } - - #[test] - fn pen_menu_saved_path_clipping_and_numeric_transform() { - let mut app = app(); - app.ui.tool = Tool::Pen; - work_path(&mut app); - app.run("path.rename", json!({"name": "work", "to": "Cutout"})).unwrap(); - app.ui.selected_path = Some("Cutout".into()); - assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); - assert!(entry_enabled(&app, app.ui.canvas_tool_menu.as_ref().unwrap(), "path.clippingPath.set")); - choose(&mut app, &Context::default(), "path.clippingPath.set"); - let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); - app.ui.dialog_mut(id).unwrap().fields.insert("flatness".into(), json!(2.0)); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(app.session.active().unwrap().doc.clipping_path.as_ref().map(|p| p.name.as_str()), Some("Cutout")); - choose_open(&mut app, "path.transform"); - let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); - app.ui.dialog_mut(id).unwrap().fields.insert("translateX".into(), json!(5.0)); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("path.transform")); - } - - #[test] - fn pen_shape_menu_enables_shape_ops_and_style_copy_only_when_applicable() { - let mut app = app(); - app.ui.tool = Tool::Pen; - app.run( - "shape.create", - json!({"kind":"path", "path":{"subpaths":[ - {"closed":true,"knots":[[2,2],[20,2],[20,20]]}, - {"closed":true,"knots":[[5,5],[10,5],[10,10]]} - ]}, "fill":"#ff0000", "stroke":{"width":2,"color":"#000000"}}), - ) - .unwrap(); - assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); - assert!(entry_enabled(&app, menu, "layer.combineShapes.unite")); - assert!(entry_enabled(&app, menu, "path.style.copyFill")); - assert!(!entry_enabled(&app, menu, "path.style.pasteFill")); - assert!(!entry_enabled(&app, menu, "path.fill")); - choose(&mut app, &Context::default(), "path.style.copyFill"); - assert!(app.session.path_fill_clipboard.is_some()); - assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); - assert!(entry_enabled(&app, app.ui.canvas_tool_menu.as_ref().unwrap(), "path.style.pasteFill")); - } - - #[test] - fn unfinished_shape_path_disables_actions_that_would_target_the_previous_layer() { - let mut app = app(); - app.ui.tool = Tool::Pen; - app.ui.tool_options.vector_mode = "shape".into(); - for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { - crate::vector_ui::pen_down(&mut app, x, y, false); - crate::vector_ui::pen_up(&mut app); - } - assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); - for id in ["layer.vectorMask.fromPath", "path.delete", "path.fill", "path.stroke", "path.clippingPath.set", "view.newGuidesFromShape"] { - assert!(!entry_enabled(&app, menu, id), "{id} must not act on the layer replaced by the pending shape"); - } - assert!(entry_enabled(&app, menu, "path.toSelection")); - } - - /// A 32 × 32 document with the Crop tool picked (Classic Mode, so the view stays put) and its - /// untouched default frame. - fn crop_app() -> PhotocraftApp { - let mut app = app(); - app.ui.tool = Tool::Crop; - app.ui.tool_options.crop_shield.classic_mode = true; - app.ui.extras.snap = false; - crate::crop_ui::ensure_frame(&mut app); - app - } - - /// Draws a crop frame from (4, 4) to (28, 28): a pending crop. Returns the frame. - fn draw_crop(app: &mut PhotocraftApp) -> [f64; 4] { - use crate::canvas::{ToolEvent, tool_event}; - tool_event(app, ToolEvent::Down { x: 4.0, y: 4.0, pressure: 1.0 }, Modifiers::NONE); - tool_event(app, ToolEvent::Move { x: 16.0, y: 16.0, pressure: 1.0 }, Modifiers::NONE); - tool_event(app, ToolEvent::Move { x: 28.0, y: 28.0, pressure: 1.0 }, Modifiers::NONE); - tool_event(app, ToolEvent::Up { x: 28.0, y: 28.0 }, Modifiers::NONE); - assert!(crate::crop_ui::pending(app), "the drag draws a pending frame"); - app.ui.crop_rect.unwrap() - } - - fn aspect(r: [f64; 4]) -> f64 { - (r[2] - r[0]) / (r[3] - r[1]) - } - - /// #6561: right-click on a pending crop opens its menu without touching the frame, and a ratio - /// row refits the frame as the options bar's dropdown does. - #[test] - fn right_click_on_a_pending_crop_opens_the_crop_menu_and_a_ratio_refits_the_frame() { - let mut app = crop_app(); - let frame = draw_crop(&mut app); - let mut h = harness(app); - let center = h.state().last_canvas_rect.center(); - right_click(&mut h, center, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().expect("right-click on a pending crop opens a menu"); - assert_eq!(h.state().ui.crop_rect, Some(frame), "the right-click leaves the frame alone"); - assert!(available(h.state(), &menu, "crop.ratio.16:9"), "the menu lists the options bar's ratios"); - let ctx = h.ctx.clone(); - choose(h.state_mut(), &ctx, "crop.ratio.16:9"); - assert_eq!(h.state().ui.tool_options.crop_ratio, "16:9"); - let r = h.state().ui.crop_rect.unwrap(); - assert!((aspect(r) - 16.0 / 9.0).abs() < 1e-9, "the frame is 16 : 9 now: {r:?}"); - assert!(r[0] >= frame[0] && r[1] >= frame[1] && r[2] <= frame[2] && r[3] <= frame[3], "fitted inside the old frame: {r:?}"); - assert!(h.state().ui.canvas_tool_menu.is_none()); - } - - #[test] - fn untouched_crop_frame_has_no_menu_and_a_pending_one_wins_over_the_pasteboard() { - let mut h = harness(crop_app()); - let rect = h.state().last_canvas_rect; - let outside = rect.min + vec2(5.0, 5.0); - right_click(&mut h, rect.center(), Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.is_none(), "the tool's untouched frame is no crop in progress"); - right_click(&mut h, outside, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "outside: the pasteboard menu, as before"); - h.state_mut().ui.canvas_tool_menu = None; - draw_crop(h.state_mut()); - h.run_steps(2); - right_click(&mut h, outside, Modifiers::NONE); - let menu = h.state().ui.canvas_tool_menu.clone().unwrap(); - assert!(menu.crop.is_some() && !menu.pasteboard, "with a crop pending, its menu also outside the image"); - } - - /// A harness in the app's order: shortcuts (the crop's Esc and ↵ among them), then the canvas. - fn shortcut_harness(mut app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { - app.sync_views(); - 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 - } - - #[test] - fn esc_closes_only_the_crop_menu() { - let mut app = crop_app(); - let frame = draw_crop(&mut app); - let mut h = shortcut_harness(app); - let center = h.state().last_canvas_rect.center(); - right_click(&mut h, center, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some())); - h.key_press(egui::Key::Escape); - h.run_steps(2); - assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu"); - assert_eq!(h.state().ui.crop_rect, Some(frame), "and only the menu: the crop is not cancelled"); - assert!(crate::crop_ui::pending(h.state())); - } - - /// ↵ under the open crop menu doesn't commit the crop beneath it. - #[test] - fn enter_under_the_crop_menu_does_not_crop() { - let mut app = crop_app(); - let frame = draw_crop(&mut app); - let mut h = shortcut_harness(app); - let size = h.state().session.active().map(|s| s.doc.size); - let center = h.state().last_canvas_rect.center(); - right_click(&mut h, center, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some())); - h.key_press(egui::Key::Enter); - h.run_steps(2); - assert_eq!(h.state().session.active().map(|s| s.doc.size), size, "↵ under the menu doesn't crop"); - assert_eq!(h.state().ui.crop_rect, Some(frame)); - assert!(crate::crop_ui::pending(h.state())); - } - - /// A right-click while the left button drags the crop frame opens no menu over the drag, on - /// the image or outside it (no pasteboard menu either), and the menu opens again once the left - /// button is up, though egui ended that drag without a release of its own. - #[test] - fn no_crop_menu_while_the_left_button_drags_the_frame() { - let mut app = crop_app(); - draw_crop(&mut app); - let mut h = harness(app); - let rect = h.state().last_canvas_rect; - let (center, outside) = (rect.center(), rect.min + vec2(5.0, 5.0)); - let left = |pos, pressed| egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; - h.event(egui::Event::PointerMoved(center)); - h.run_steps(1); - h.event(left(center, true)); - h.run_steps(1); - for k in 1..=4 { - h.event(egui::Event::PointerMoved(center + vec2(8.0 * k as f32, 0.0))); - h.run_steps(1); - } - assert!(h.state().crop.drag.is_some(), "the left button drags the frame"); - let held = center + vec2(32.0, 0.0); - right_click(&mut h, held, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.is_none(), "no crop menu over the drag"); - right_click(&mut h, outside, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.is_none(), "nor the pasteboard menu outside the image"); - h.event(egui::Event::PointerMoved(held)); - h.event(left(held, false)); - h.run_steps(2); - right_click(&mut h, center, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some()), "with the button up the menu opens"); - } - - /// The left button down with no crop gesture under way (a press egui doesn't take for a drag - /// yet, or one whose release was lost to an Alt+Tab or a cancelled touch) doesn't keep the - /// crop menu shut. - #[test] - fn a_left_button_down_without_a_crop_drag_keeps_the_crop_menu() { - let mut app = crop_app(); - draw_crop(&mut app); - let mut h = harness(app); - let center = h.state().last_canvas_rect.center(); - h.event(egui::Event::PointerMoved(center)); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: center, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - assert!(h.ctx.input(|i| i.pointer.primary_down()) && h.state().crop.drag.is_none(), "down, dragging nothing"); - right_click(&mut h, center, Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some()), "the crop menu opens"); - } - - /// Nor does a right-click open a menu over a Straighten line the left button still draws. - #[test] - fn no_crop_menu_while_the_left_button_draws_a_straighten_line() { - let mut app = crop_app(); - draw_crop(&mut app); - crate::crop_straighten::toggle(&mut app); - let mut h = harness(app); - let center = h.state().last_canvas_rect.center(); - let left = |pos, pressed| egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; - h.event(egui::Event::PointerMoved(center)); - h.run_steps(1); - h.event(left(center, true)); - h.run_steps(1); - for k in 1..=4 { - h.event(egui::Event::PointerMoved(center + vec2(8.0 * k as f32, 4.0))); - h.run_steps(1); - } - assert!(h.state().crop.straighten.line.is_some() && h.state().crop.drag.is_none(), "the left button draws a Straighten line"); - right_click(&mut h, center + vec2(32.0, 4.0), Modifiers::NONE); - assert!(h.state().ui.canvas_tool_menu.is_none(), "no menu over the line"); - } - - /// A finger held still on a pending crop (a touch screen's press-and-hold right-click) opens - /// the crop menu, though the touch counts as the primary button down. - #[test] - fn a_finger_held_on_a_pending_crop_opens_the_crop_menu() { - let mut app = crop_app(); - let frame = draw_crop(&mut app); - let mut h = harness(app); - let at = h.state().last_canvas_rect.center(); - let touch = |phase| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(1), phase, pos: at, force: None }; - let button = |pressed| egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; - h.input_mut().events.extend([egui::Event::PointerMoved(at), touch(egui::TouchPhase::Start), button(true)]); - h.step(); - // Held past egui's max_click_duration (0.8 s) without moving. - for _ in 0..120 { - if h.state().ui.canvas_tool_menu.is_some() { - break; - } - h.step(); - } - assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some()), "the held finger opens the crop menu"); - h.input_mut().events.extend([touch(egui::TouchPhase::End), button(false)]); - h.run_steps(2); - assert_eq!(h.state().ui.crop_rect, Some(frame), "the hold leaves the frame alone"); - } - - #[test] - fn crop_menu_rows_act_like_the_options_bar() { - use crate::crop_overlay::{CropOverlay, OverlayShow}; - let ctx = Context::default(); - let mut app = crop_app(); - draw_crop(&mut app); - // Space's Hand held over the Crop tool keeps its own right-click. - assert!(!open_crop(&mut app, &ctx, Tool::Hand, [10.0, 10.0])); - let reopen = |app: &mut PhotocraftApp| { - assert!(open_crop(app, &Context::default(), Tool::Crop, [10.0, 10.0])); - app.ui.canvas_tool_menu.clone().unwrap() - }; - // Nothing to save with a free ratio, nothing to delete without saved presets. - let menu = reopen(&mut app); - assert!(!entry_enabled(&app, &menu, CROP_NEW) && !entry_enabled(&app, &menu, CROP_DELETE)); - assert!(mode_checked(&app, &menu, "crop.ratio."), "free Ratio is checked, as in the dropdown"); - // A size preset fills W x H x Resolution, which the menu checks, as the dropdown does. - choose(&mut app, &ctx, "crop.ratio.preset:4x5in"); - let menu = reopen(&mut app); - assert!(mode_checked(&app, &menu, "crop.ratio.whr") && !mode_checked(&app, &menu, "crop.ratio.preset:4x5in")); - assert!((aspect(app.ui.crop_rect.unwrap()) - 0.8).abs() < 1e-9); - assert!(entry_enabled(&app, &menu, CROP_NEW)); - // Clear empties W x H x Resolution, as the bar's Clear. - choose(&mut app, &ctx, CROP_CLEAR); - assert_eq!(app.ui.tool_options.crop_width, ""); - // Overlays: another overlay starts at its first orientation; when it shows. - app.ui.tool_options.crop_overlay = CropOverlay::GoldenSpiral; - app.ui.tool_options.crop_overlay_orientation = 2; - reopen(&mut app); - choose(&mut app, &ctx, "crop.overlay.triangle"); - assert_eq!((app.ui.tool_options.crop_overlay, app.ui.tool_options.crop_overlay_orientation), (CropOverlay::Triangle, 0)); - reopen(&mut app); - choose(&mut app, &ctx, "crop.overlayShow.never"); - assert_eq!(app.ui.tool_options.crop_overlay_show, OverlayShow::Never); - let menu = reopen(&mut app); - assert!(mode_checked(&app, &menu, "crop.overlay.triangle") && mode_checked(&app, &menu, "crop.overlayShow.never")); - // A saved preset is listed by name; picking it refits the frame to its W x H, though the - // ratio key is "whr" before and after. - app.ui.canvas_tool_menu = None; - app.ui.tool_options.crop_ratio = crate::crop_size::WHR.into(); - let saved = json!({"crop_ratio": "whr", "crop_width": "300 px", "crop_height": "100 px", "crop_resolution": "72", "crop_resolution_unit": "px/in"}); - app.run("tool.presets.new", json!({"name": "Banner", "tool": "crop", "options": {"toolOptions": saved}})).unwrap(); - let menu = reopen(&mut app); - let banner = crop_rows(&menu).into_iter().flatten().find(|(l, _)| l == "Banner").expect("the saved preset is a row").1; - assert!(entry_enabled(&app, &menu, CROP_DELETE)); - choose(&mut app, &ctx, &banner); - assert_eq!(app.ui.tool_options.crop_width, "300 px"); - assert!((aspect(app.ui.crop_rect.unwrap()) - 3.0).abs() < 1e-9, "the frame follows the preset: {:?}", app.ui.crop_rect); - let menu = reopen(&mut app); - assert!(mode_checked(&app, &menu, &banner)); - // Crop commits as ↵ does: the preset's size. - choose(&mut app, &ctx, CROP_COMMIT); - let size = app.session.active().unwrap().doc.size; - assert_eq!((size.width, size.height), (300, 100)); - // Cancel drops a pending crop. - draw_crop(&mut app); - reopen(&mut app); - choose(&mut app, &ctx, CROP_CANCEL); - assert!(!crate::crop_ui::pending(&app)); - } -} +mod tests; diff --git a/crates/ui-egui/src/canvas_tool_menu/tests.rs b/crates/ui-egui/src/canvas_tool_menu/tests.rs new file mode 100644 index 0000000000..5980e4e28c --- /dev/null +++ b/crates/ui-egui/src/canvas_tool_menu/tests.rs @@ -0,0 +1,1207 @@ +use super::*; +use egui::{Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::{Harness, kittest::Queryable}; + +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(); + app +} + +fn work_path(app: &mut PhotocraftApp) { + app.run( + "path.set", + json!({"name": "work", "path": {"subpaths": [{"closed": true, "knots": [ + {"anchor": [2, 2], "in": [2, 2], "out": [2, 2]}, + {"anchor": [20, 2], "in": [20, 2], "out": [20, 2]}, + {"anchor": [20, 20], "in": [20, 20], "out": [20, 20]} + ]}]}}), + ) + .unwrap(); +} + +fn choose_open(app: &mut PhotocraftApp, command: &str) { + assert!(open(app, &Context::default(), Tool::Pen, [10.0, 10.0])); + choose(app, &Context::default(), command); +} + +fn harness(mut app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + app.sync_views(); + 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; + } + 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 +} + +fn right_click(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, modifiers: Modifiers) { + h.event(egui::Event::ModifiersChanged(modifiers)); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers }); + h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); +} + +#[test] +fn canvas_gesture_preserves_selection_and_command_override() { + let mut app = app(); + app.ui.tool = Tool::Lasso; + app.run("select.rect", json!({"x": 1, "y": 1, "width": 8, "height": 8})).unwrap(); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + let revision = h.state().session.active().unwrap().revision; + right_click(&mut h, center, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_some()); + assert_eq!(h.state().session.active().unwrap().revision, revision, "right-click cannot alter selection"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none()); + right_click(&mut h, center, Modifiers::COMMAND); + assert!(h.state().ui.canvas_tool_menu.is_none(), "command right-click belongs to layer picker"); +} + +/// A type layer reading "Hello", being edited with every character selected. +fn editing_type(app: &mut PhotocraftApp) -> u64 { + app.ui.tool = Tool::Type; + let id = app.run("type.create", json!({"text": "Hello", "size": 12, "x": 4, "y": 20})).unwrap()["layer"].as_u64().unwrap(); + crate::menus::invoke(app, &Context::default(), "type.editText", json!({})).unwrap(); + id +} + +fn text_of(app: &PhotocraftApp, id: u64) -> Option { + match &app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content { + LayerContent::Text(t) => Some(t.clone()), + _ => None, + } +} + +#[test] +fn right_click_while_typing_opens_the_type_edit_menu_and_esc_keeps_the_edit() { + let mut app = app(); + editing_type(&mut app); + app.sync_views(); + 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; + } + // The app's order: shortcuts (inline type's keys among them), then the canvas. + 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); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().expect("right-click in a type edit opens a menu"); + assert!(menu.text && !menu.pasteboard && !menu.transform); + assert_eq!(rows(&menu), TYPE_EDIT_MENU); + let edit = h.state().ui.text_edit.clone().expect("the edit goes on under the menu"); + assert_eq!((edit.anchor, edit.caret), (0, 5), "the right-click keeps the selection for Cut and Copy"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu"); + assert!(h.state().ui.text_edit.is_some(), "and only the menu: the edit isn't committed"); +} + +#[test] +fn type_edit_menu_rows_act_on_the_text_and_the_layer() { + let mut app = app(); + let id = editing_type(&mut app); + let ctx = Context::default(); + let reopen = |app: &mut PhotocraftApp| assert!(open(app, &Context::default(), Tool::Type, [10.0, 10.0])); + // Faux Bold toggles the style of the selected characters, and shows checked. + reopen(&mut app); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(!mode_checked(&app, &menu, FAUX_BOLD) && mode_checked(&app, &menu, "type.antiAlias.smooth")); + choose(&mut app, &ctx, FAUX_BOLD); + assert!(text_of(&app, id).unwrap().char_runs().iter().all(|r| r.style.faux_bold)); + assert!(mode_checked(&app, &menu, FAUX_BOLD)); + // Cut takes the selection out of the text; with nothing selected Copy and Cut grey out. + reopen(&mut app); + choose(&mut app, &ctx, "edit.cut"); + assert_eq!(text_of(&app, id).unwrap().text, ""); + reopen(&mut app); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(!entry_enabled(&app, &menu, "edit.copy") && !entry_enabled(&app, &menu, "edit.cut")); + app.ui.canvas_tool_menu = None; + crate::menus::invoke(&mut app, &ctx, "edit.undo", json!({})).unwrap(); + assert_eq!(text_of(&app, id).unwrap().text, "Hello"); + // Select All selects every character, not the canvas. + reopen(&mut app); + choose(&mut app, &ctx, "select.all"); + let edit = app.ui.text_edit.clone().unwrap(); + assert_eq!((edit.anchor, edit.caret), (0, 5)); + assert!(app.session.active().unwrap().doc.selection.is_none()); + // Warp Text… opens its dialog; Rasterize Type ends the edit and rasterizes the layer. + reopen(&mut app); + choose(&mut app, &ctx, "type.warpText"); + assert!(!app.ui.dialogs.is_empty(), "Warp Text… asks for its settings"); + app.ui.dialogs.clear(); + reopen(&mut app); + choose(&mut app, &ctx, "type.rasterizeTypeLayer"); + assert!(app.ui.text_edit.is_none() && text_of(&app, id).is_none(), "the type layer is pixels now"); +} + +/// A committed type layer reading "Hello" over the middle of the canvas, no edit running. +fn committed_type(app: &mut PhotocraftApp) -> u64 { + app.ui.tool = Tool::Type; + let id = app.run("type.create", json!({"text": "Hello", "size": 14, "x": 1, "y": 22})).unwrap()["layer"].as_u64().unwrap(); + assert!(app.ui.text_edit.is_none()); + id +} + +#[test] +fn right_click_on_committed_type_opens_the_type_layer_menu() { + use photocraft_doc::text::Orientation; + let mut app = app(); + let id = committed_type(&mut app); + assert_eq!(crate::type_tool::hit_layer(&mut app, 16.0, 16.0).map(|l| l.0), Some(id), "the canvas centre is on the type"); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().expect("right-click on committed type opens a menu (#7324)"); + assert!(menu.type_layer && !menu.text && !menu.pasteboard); + assert_eq!(rows(&menu), TYPE_LAYER_MENU); + assert!(h.state().ui.text_edit.is_none(), "the right-click doesn't start an edit"); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_some(), "the menu stays open without an edit"); + // An edit started some other way (here, as an agent's Type › Edit Text would) closes the + // menu, which has no text edit rows. + crate::menus::invoke(h.state_mut(), &Context::default(), "type.editText", json!({})).unwrap(); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none(), "an edit closes the type layer menu"); + crate::type_tool::commit(h.state_mut()); + right_click(&mut h, center, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().expect("committed again, the menu opens again"); + assert!(menu.type_layer && mode_checked(h.state(), &menu, "type.orientation.horizontal")); + choose(h.state_mut(), &Context::default(), "type.orientation.vertical"); + assert_eq!(text_of(h.state(), id).unwrap().orientation, Orientation::Vertical); +} + +#[test] +fn type_layer_menu_targets_the_type_under_the_pointer() { + let mut app = app(); + let id = committed_type(&mut app); + app.run("layer.new.layer", json!({})).unwrap(); + let ctx = Context::default(); + let active = |app: &PhotocraftApp| app.session.active().unwrap().active_layer.map(|l| l.0); + assert_ne!(active(&app), Some(id)); + // Away from the type, or with a Type Mask tool, nothing opens and nothing is selected. + assert!(!open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([30.0, 2.0]))); + assert!(!open_at(&mut app, &ctx, Tool::HorizontalTypeMask, [10.0, 10.0], Some([16.0, 16.0]))); + assert!(!open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([f64::NAN, 16.0]))); + assert_ne!(active(&app), Some(id)); + // Over the type: its layer becomes the target, and the menu has no text edit rows. + assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([16.0, 16.0]))); + assert_eq!(active(&app), Some(id)); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + for edit_row in ["edit.undo", "edit.cut", "edit.copy", "edit.paste", "select.all", FAUX_BOLD, FAUX_ITALIC] { + assert!(!available(&app, &menu, edit_row), "{edit_row} belongs to the edit menu only"); + } + assert!(entry_enabled(&app, &menu, "type.convertToParagraphText") && !entry_enabled(&app, &menu, "type.convertToPointText")); + choose(&mut app, &ctx, "type.rasterizeTypeLayer"); + assert!(text_of(&app, id).is_none(), "the type layer is pixels now"); + assert!(app.ui.text_edit.is_none()); +} + +/// Two selected type layers: the one right-clicked becomes active, and the selection stays. +#[test] +fn type_layer_menu_in_a_multiselection_acts_on_the_clicked_type() { + 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::Type; + let top = app.run("type.create", json!({"text": "Top", "size": 30, "x": 10, "y": 40})).unwrap()["layer"].as_u64().unwrap(); + let bottom = app.run("type.create", json!({"text": "Low", "size": 30, "x": 10, "y": 90})).unwrap()["layer"].as_u64().unwrap(); + app.run("layer.select", json!({"layer": bottom})).unwrap(); + app.run("layer.select", json!({"layer": top, "mode": "add"})).unwrap(); + let at = [25.0, 80.0]; + assert_eq!(crate::type_tool::hit_layer(&mut app, at[0], at[1]).map(|l| l.0), Some(bottom)); + assert_eq!(app.session.active().unwrap().active_layer.map(|l| l.0), Some(top)); + let ctx = Context::default(); + assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some(at))); + let st = app.session.active().unwrap(); + assert_eq!(st.active_layer.map(|l| l.0), Some(bottom), "the clicked type is the target"); + assert_eq!(st.selected_layers().len(), 2, "the multiselection stays"); + choose(&mut app, &ctx, "type.rasterizeTypeLayer"); + assert!(text_of(&app, bottom).is_none(), "the clicked type is rasterized"); + assert!(text_of(&app, top).is_some(), "not the other selected type"); +} + +#[test] +fn type_edit_menu_lists_spelling_suggestions_for_the_word_under_the_pointer() { + let mut app = app(); + app.ui.tool = Tool::Type; + let id = app.run("type.create", json!({"text": "Teh cat", "size": 12, "x": 4, "y": 20})).unwrap()["layer"].as_u64().unwrap(); + let ctx = Context::default(); + crate::menus::invoke(&mut app, &ctx, "type.editText", json!({})).unwrap(); + // Away from the misspelling (past the end of the line): no spelling rows. + assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([600.0, 15.0]))); + assert!(spelling_rows(app.ui.canvas_tool_menu.as_ref().unwrap()).is_empty()); + // Over "Teh": its suggestions head the menu, then Add to Dictionary. + assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([5.0, 15.0]))); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + let rows = spelling_rows(&menu); + assert!(rows.iter().any(|(l, _)| l == "The"), "{rows:?}"); + assert_eq!(rows.last().map(|(_, id)| id.as_str()), Some(SPELLING_ADD)); + assert!(rows.len() <= MAX_SUGGESTIONS + 1, "at most {MAX_SUGGESTIONS} suggestions and Add to Dictionary: {rows:?}"); + assert!(available(&app, &menu, &rows[0].1)); + let pick = rows.iter().find(|(l, _)| l == "The").unwrap().1.clone(); + choose(&mut app, &ctx, &pick); + assert_eq!(text_of(&app, id).unwrap().text, "The cat"); + assert_eq!(app.ui.text_edit.as_ref().map(|e| (e.caret, e.anchor)), Some((3, 3)), "the caret lands after the replacement"); + // Add to Dictionary stops flagging a word. + app.run("type.insertText", json!({"layer": id, "text": " Zqx"})).unwrap(); + assert!(open_at(&mut app, &ctx, Tool::Type, [10.0, 10.0], Some([600.0, 15.0]))); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(menu.spelling.as_ref().is_some_and(|s| s.word == "Zqx")); + choose(&mut app, &ctx, SPELLING_ADD); + assert!(app.session.prefs().user_dictionary.iter().any(|w| w == "Zqx")); +} + +#[test] +fn right_click_outside_the_image_picks_the_pasteboard_color() { + let mut app = app(); + app.ui.tool = Tool::RectMarquee; + let mut h = harness(app); + let rect = h.state().last_canvas_rect; + let outside = rect.min + vec2(5.0, 5.0); + right_click(&mut h, rect.center(), Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| !m.pasteboard), "inside: the tool's own menu"); + h.state_mut().ui.canvas_tool_menu = None; + right_click(&mut h, outside, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().unwrap(); + assert!(menu.pasteboard && rows(&menu) == PASTEBOARD_MENU, "outside: the pasteboard menu"); + let ctx = h.ctx.clone(); + choose(h.state_mut(), &ctx, "pasteboard.black"); + assert_eq!(crate::prefs_ui::pasteboard_color(h.state()), Some(egui::Color32::BLACK)); + // Select Custom Color… opens the Color Picker; OK makes its colour the custom pasteboard. + right_click(&mut h, outside, Modifiers::NONE); + choose(h.state_mut(), &ctx, PASTEBOARD_PICK); + let mut f = h.state().ui.dialogs.last().unwrap().fields.clone(); + f.insert("color".into(), json!("#123456")); + crate::color_picker_ui::confirm(h.state_mut(), &f).unwrap(); + assert_eq!(crate::prefs_ui::pasteboard_color(h.state()), Some(egui::Color32::from_rgb(0x12, 0x34, 0x56))); + // A painting tool keeps its Brush Preset picker there. + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(2); + right_click(&mut h, outside, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_none() && h.state().ui.brush_picker.is_some()); +} + +/// #2832: right-click over an open Free Transform box: Photoshop's transform menu. Skew +/// switches the box's mode; Rotate and Flip turn the box about its reference point without +/// committing it; Content-Aware Scale and Puppet Warp are greyed. +#[test] +fn right_click_during_free_transform_switches_modes_rotates_and_flips_the_box() { + let mut app = app(); + app.ui.tool = Tool::RectMarquee; + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 4, "y": 6, "width": 10, "height": 8})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let mut h = harness(app); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); + h.run_steps(2); + let center = h.state().last_canvas_rect.center(); + let (revision, journal) = (h.state().session.active().unwrap().revision, h.state().session.journal.len()); + right_click(&mut h, center, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().expect("the transform menu"); + assert!(menu.transform && rows(&menu) == TRANSFORM_MENU); + for (id, on) in + [("edit.contentAwareScale", false), ("edit.puppetWarp", false), ("edit.transform.rotate90Cw", true), ("edit.transform.flipVertical", true)] + { + assert_eq!(entry_enabled(h.state(), &menu, id), on, "{id}"); + } + choose(h.state_mut(), &ctx, "edit.transform.skew"); + assert_eq!(h.state().ui.transform.as_ref().unwrap().mode, crate::state::TransformMode::Skew); + let t = h.state().ui.transform.clone().unwrap(); + let (q0, c) = (t.quad, t.pivot); + right_click(&mut h, center, Modifiers::NONE); + choose(h.state_mut(), &ctx, "edit.transform.flipHorizontal"); + let q = h.state().ui.transform.as_ref().expect("the box stays open").quad; + for (a, b) in q.iter().zip(q0) { + assert!((a[0] - (2.0 * c[0] - b[0])).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9, "mirrored about the reference point: {q0:?} -> {q:?}"); + } + right_click(&mut h, center, Modifiers::NONE); + choose(h.state_mut(), &ctx, "edit.transform.rotate180"); + let q = h.state().ui.transform.as_ref().unwrap().quad; + for (a, b) in q.iter().zip(q0) { + assert!((a[1] - (2.0 * c[1] - b[1])).abs() < 1e-9 && (a[0] - b[0]).abs() < 1e-9, "flipped then turned 180°: {q0:?} -> {q:?}"); + } + let st = h.state().session.active().unwrap(); + assert_eq!((st.revision, h.state().session.journal.len()), (revision, journal), "nothing is committed"); +} + +#[test] +fn transform_menu_follows_photoshop_order() { + assert_eq!( + labels(TRANSFORM_MENU), + vec![ + Some("Free Transform"), + Some("Scale"), + Some("Rotate"), + Some("Skew"), + Some("Distort"), + Some("Perspective"), + Some("Warp"), + None, + Some("Content-Aware Scale"), + Some("Puppet Warp"), + None, + Some("Rotate 180°"), + Some("Rotate 90° Clockwise"), + Some("Rotate 90° Counter Clockwise"), + None, + Some("Flip Horizontal"), + Some("Flip Vertical"), + ] + ); + // Over a box on editable type, Distort and Perspective are greyed (#2630). + let mut app = app(); + app.run("type.create", json!({"x": 2, "y": 20, "text": "Hi", "size": 16})).unwrap(); + crate::transform_tool::begin(&mut app, &Context::default()).unwrap(); + assert!(open_transform(&mut app, &Context::default(), [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + for (id, on) in [("edit.transform.skew", true), ("edit.transform.distort", false), ("edit.transform.perspective", false)] { + assert_eq!(entry_enabled(&app, &menu, id), on, "{id}"); + } +} + +fn labels(rows: &[Row]) -> Vec> { + rows.iter().map(|row| row.map(|(label, _)| label)).collect() +} + +#[test] +fn selection_menus_follow_photoshop_order() { + assert_eq!( + labels(SELECTION_MENU), + vec![ + Some("Deselect"), + Some("Select Inverse"), + Some("Feather…"), + Some("Select and Mask…"), + None, + Some("Save Selection…"), + Some("Make Work Path…"), + None, + Some("Layer via Copy"), + Some("Layer via Cut"), + Some("New Layer…"), + None, + Some("Free Transform"), + Some("Transform Selection"), + Some("Distort"), + Some("Perspective"), + None, + Some("Delete and Fill Selection"), + Some("Fill…"), + Some("Stroke…"), + Some("Content-Aware Fill…"), + None, + Some("Last Filter"), + None, + Some("Fade…"), + ] + ); + assert_eq!(labels(NO_SELECTION_MENU), vec![Some("Select All"), Some("Reselect"), Some("Color Range…"), None, Some("Load Selection…")]); + // Every row runs a real command: one the menu bar has, or an engine command. + let app = app(); + let items = crate::menus::menu_items(&app); + for (label, id) in [SELECTION_MENU, NO_SELECTION_MENU, PEN_MENU, TRANSFORM_MENU].into_iter().flatten().flatten() { + assert!(items.iter().any(|i| i.id == *id) || photocraft_engine::commands::find(id).is_some(), "{label}: unknown command {id}"); + } +} + +#[test] +fn selection_menu_routes_actions_through_commands() { + let mut app = app(); + app.ui.tool = Tool::RectMarquee; + app.run("select.rect", json!({"x": 1, "y": 1, "width": 8, "height": 8})).unwrap(); + assert!(open(&mut app, &Context::default(), Tool::RectMarquee, [10.0, 10.0])); + assert_eq!(rows(app.ui.canvas_tool_menu.as_ref().unwrap()), SELECTION_MENU); + let before = app.session.journal.len(); + choose(&mut app, &Context::default(), "select.inverse"); + assert!(app.ui.canvas_tool_menu.is_none()); + assert!(app.session.journal[before..].iter().any(|(id, _)| id == "select.inverse")); + let before = app.session.journal.len(); + assert!(open(&mut app, &Context::default(), Tool::RectMarquee, [10.0, 10.0])); + choose(&mut app, &Context::default(), "select.deselect"); + assert!(app.session.active().unwrap().doc.selection.is_none()); + assert!(app.session.journal[before..].iter().any(|(id, _)| id == "select.deselect")); + // Nothing selected: the menu that makes a selection. + assert!(open(&mut app, &Context::default(), Tool::RectMarquee, [10.0, 10.0])); + assert_eq!(rows(app.ui.canvas_tool_menu.as_ref().unwrap()), NO_SELECTION_MENU); + choose(&mut app, &Context::default(), "select.reselect"); + assert!(app.session.active().unwrap().doc.selection.is_some()); + assert!(app.session.journal.iter().any(|(id, _)| id == "select.reselect")); + app.run("select.deselect", json!({})).unwrap(); + assert!(open(&mut app, &Context::default(), Tool::Lasso, [10.0, 10.0])); + choose(&mut app, &Context::default(), "select.all"); + assert!(app.session.active().unwrap().doc.selection.is_some()); +} + +#[test] +fn selection_menu_layer_and_path_actions() { + let mut app = app(); + app.ui.tool = Tool::EllipseMarquee; + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); + let layers = app.session.active().unwrap().doc.layers.len(); + assert!(open(&mut app, &Context::default(), Tool::EllipseMarquee, [10.0, 10.0])); + choose(&mut app, &Context::default(), "layer.new.layerViaCopy"); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1, "Layer via Copy adds a layer"); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("layer.new.layerViaCopy")); + // Make Work Path… asks for the tolerance, then traces the selection. + app.run("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); + assert!(open(&mut app, &Context::default(), Tool::EllipseMarquee, [10.0, 10.0])); + choose(&mut app, &Context::default(), "select.toWorkPath"); + let dialog = app.ui.dialogs.last().map(|d| d.id).expect("tolerance dialog"); + assert!(app.session.active().unwrap().doc.work_path.is_none(), "nothing happens before OK"); + crate::dialogs::confirm(&mut app, dialog).unwrap(); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("select.toWorkPath")); +} + +#[test] +fn disabled_selection_rows_do_nothing() { + let mut app = app(); + app.ui.tool = Tool::MagicWand; + app.run("select.rect", json!({"x": 1, "y": 1, "width": 8, "height": 8})).unwrap(); + assert!(open(&mut app, &Context::default(), Tool::MagicWand, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + // No filter has run and nothing can be faded yet. + for id in ["filter.lastFilter", "edit.fade"] { + assert!(!entry_enabled(&app, &menu, id), "{id} is greyed out"); + } + let before = app.session.journal.len(); + choose(&mut app, &Context::default(), "edit.fade"); + assert_eq!(app.session.journal.len(), before); + assert!(app.ui.dialogs.is_empty()); + // Rows of the other variant are not part of this menu. + assert!(open(&mut app, &Context::default(), Tool::MagicWand, [10.0, 10.0])); + choose(&mut app, &Context::default(), "select.all"); + assert_eq!(app.session.journal.len(), before); +} + +/// Photoshop's Zoom tool menu is Fit on Screen, 100%, 200%, Print Size, then Zoom In and Zoom +/// Out after a separator (#6005); Fill Screen (the Hand tool's) keeps its place by Fit on Screen. +#[test] +fn view_menu_follows_photoshop_order() { + assert_eq!( + labels(VIEW_MENU), + vec![Some("Fit on Screen"), Some("Fill Screen"), Some("100%"), Some("200%"), Some("Print Size"), None, Some("Zoom In"), Some("Zoom Out")] + ); + // Every row but Fill Screen (the Hand tool's options-bar button) is a View menu command. + let app = app(); + let items = crate::menus::menu_items(&app); + for (label, id) in VIEW_MENU.iter().flatten().filter(|(_, id)| *id != FILL_SCREEN) { + assert!(items.iter().any(|i| i.id == *id), "{label}: unknown command {id}"); + } +} + +fn zoom_app(w: u32, h: u32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": w, "height": h})).unwrap(); + app +} + +fn screen_of(app: &PhotocraftApp, doc: [f32; 2]) -> Pos2 { + crate::canvas::ViewXform::active(app).unwrap().to_screen(doc[0], doc[1]) +} + +#[test] +fn zoom_and_hand_right_click_opens_the_view_menu() { + for tool in [Tool::Zoom, Tool::Hand] { + let mut app = zoom_app(400, 300); + app.ui.tool = tool; + let mut h = harness(app); + let zoom = h.state().ui.views[0].zoom; + 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"); + 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. + h.state_mut().ui.canvas_tool_menu = None; + let outside = h.state().last_canvas_rect.min + vec2(5.0, 5.0); + right_click(&mut h, outside, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "{tool:?}: pasteboard menu outside"); + } +} + +#[test] +fn view_menu_zoom_in_keeps_the_clicked_point_under_the_pointer() { + 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 doc = [300.0, 100.0]; + let p = screen_of(h.state(), doc); + right_click(&mut h, p, Modifiers::NONE); + // Chosen in the menu itself: the canvas frame that draws the menu must keep the new view. + h.get_by_label("Zoom In").click(); + h.run_steps(3); + 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().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); + h.get_by_label("Zoom Out").click(); + h.run_steps(3); + assert_eq!(h.state().ui.views[0].zoom, zoom); + assert!((screen_of(h.state(), doc) - p).length() < 1.0); +} + +#[test] +fn animated_zoom_off_view_menu_keeps_the_anchor_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 doc = [300.0, 100.0]; + let p = screen_of(h.state(), doc); + right_click(&mut h, p, Modifiers::NONE); + let ctx = h.ctx.clone(); + choose(h.state_mut(), &ctx, command); + assert!(!h.state().ui.views[0].zoom_animating, "{command}"); + h.step(); + let v = &h.state().ui.views[0]; + let xf = crate::canvas::ViewXform::active(h.state()).unwrap(); + 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"); + } + } +} + +#[test] +fn view_menu_zoom_keeps_its_anchor_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 doc = [300.0, 100.0]; + let p = screen_of(h.state(), doc); + right_click(&mut h, p, Modifiers::NONE); + let ctx = h.ctx.clone(); + // Choose without the widget click helper, which runs repaint frames until settled. + choose(h.state_mut(), &ctx, "view.zoomIn"); + h.step(); + h.input_mut().time = Some(ctx.input(|i| i.time) + 0.11); + 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); + h.input_mut().time = Some(ctx.input(|i| i.time) + 0.3); + h.step(); + assert!(!h.state().ui.views[0].zoom_animating); +} + +#[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; + app.run("prefs.set", json!({"path": "tools.zoomClickedPointToCenter", "value": true})).unwrap(); + let mut h = harness(app); + let doc = [300.0, 100.0]; + let p = screen_of(h.state(), doc); + right_click(&mut h, p, Modifiers::NONE); + h.get_by_label("Zoom In").click(); + h.run_steps(3); + assert_eq!(h.state().ui.views[0].center, doc); +} + +#[test] +fn view_menu_fits_fills_and_sets_fixed_zooms() { + let mut app = zoom_app(400, 300); + app.ui.tool = Tool::Zoom; + let mut h = harness(app); + let p = screen_of(h.state(), [200.0, 150.0]); + let area = crate::rulers::content_rect(h.state(), h.state().last_canvas_rect).size(); + let ppp = h.state().canvas_ppp(); + let pick = |h: &mut Harness<'static, PhotocraftApp>, label: &str| { + right_click(h, p, Modifiers::NONE); + h.get_by_label(label).click(); + h.run_steps(3); + h.state().ui.views[0].zoom + }; + assert_eq!(pick(&mut h, "200%"), 2.0); + // Fill Screen: the image covers the whole canvas (one axis can overflow). + let fill = pick(&mut h, "Fill Screen") / ppp; + assert!(400.0 * fill >= area.x - 1.0 && 300.0 * fill >= area.y - 1.0, "fill {fill} for {area:?}"); + assert!(400.0 * fill <= area.x + 1.0 || 300.0 * fill <= area.y + 1.0, "fill {fill} for {area:?}"); + assert_eq!(h.state().ui.views[0].center, [200.0, 150.0]); + // Fit on Screen: back to the whole image (capped at 100%, as on open). + let fit = pick(&mut h, "Fit on Screen") / ppp; + assert!(400.0 * fit <= area.x && 300.0 * fit <= area.y && fit < fill, "fit {fit} fill {fill}"); +} + +#[test] +fn view_menu_needs_finite_points_and_a_view_tool() { + let mut app = app(); + assert!(!open_view(&mut app, &Context::default(), Tool::Brush, [1.0, 1.0], [1.0, 1.0])); + assert!(!open_view(&mut app, &Context::default(), Tool::Zoom, [f32::NAN, 1.0], [1.0, 1.0])); + assert!(!open_view(&mut app, &Context::default(), Tool::Zoom, [1.0, 1.0], [f64::INFINITY, 1.0])); + assert!(app.ui.canvas_tool_menu.is_none()); + assert!(open_view(&mut app, &Context::default(), Tool::Zoom, [1.0, 1.0], [1.0, 1.0])); + let before = app.session.journal.len(); + choose(&mut app, &Context::default(), "select.all"); + assert_eq!(app.session.journal.len(), before, "the view menu cannot run another menu's row"); + // With no document every row is greyed out and choosing one does nothing. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + assert!(open_view(&mut app, &Context::default(), Tool::Hand, [1.0, 1.0], [1.0, 1.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + for (_, id) in VIEW_MENU.iter().flatten() { + assert!(!entry_enabled(&app, &menu, id), "{id} is greyed out with no document"); + } + choose(&mut app, &Context::default(), FILL_SCREEN); + choose(&mut app, &Context::default(), "view.zoomIn"); +} + +#[test] +fn unsupported_tools_and_nonfinite_positions_do_not_open_menu() { + let mut app = app(); + assert!(!open(&mut app, &Context::default(), Tool::Brush, [1.0, 1.0])); + assert!(!open(&mut app, &Context::default(), Tool::Lasso, [f32::NAN, 1.0])); + assert!(app.ui.canvas_tool_menu.is_none()); + assert!(open(&mut app, &Context::default(), Tool::MagicWand, [1.0, 1.0])); + let before = app.session.journal.len(); + choose(&mut app, &Context::default(), "file.new"); + assert_eq!(app.session.journal.len(), before, "context menu cannot invoke an unrelated command"); +} + +#[test] +fn completed_pen_path_right_click_makes_selection() { + let mut app = app(); + app.ui.tool = Tool::Pen; + for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + crate::vector_ui::pen_commit(&mut app, true); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.tool == Tool::Pen && m.has_path)); + let ctx = h.ctx.clone(); + choose(h.state_mut(), &ctx, "path.toSelection"); + let dialog = h.state().ui.dialogs.last().map(|d| d.id).unwrap(); + crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + assert!(h.state().session.active().unwrap().doc.selection.is_some()); + assert_eq!(h.state().session.journal.last().map(|(id, _)| id.as_str()), Some("path.toSelection")); +} + +#[test] +fn pen_menu_finishes_in_progress_path_before_selection() { + let mut app = app(); + app.ui.tool = Tool::Pen; + for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + assert!(app.session.active().unwrap().doc.work_path.is_none()); + assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); + assert!(entry_enabled(&app, menu, "path.toSelection")); + choose(&mut app, &Context::default(), "path.toSelection"); + let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); + crate::dialogs::confirm(&mut app, dialog).unwrap(); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + assert!(app.session.active().unwrap().doc.selection.is_some()); +} + +/// #5703: the Pen options bar's Make Selection (Path mode) opens the same dialog for the path +/// being drawn (finished into the Work Path first), and OK selects inside it; with no path at +/// all it reports that instead. +#[test] +fn pen_options_bar_makes_a_selection_from_the_path() { + let mut app = app(); + app.ui.tool = Tool::Pen; + assert!(make_selection(&mut app).is_err(), "no path yet"); + assert!(app.ui.dialogs.is_empty()); + for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + make_selection(&mut app).unwrap(); + let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); + crate::dialogs::confirm(&mut app, dialog).unwrap(); + let st = app.session.active().unwrap(); + assert!(st.doc.work_path.is_some() && st.doc.selection.is_some()); + // The active (Work) path again, with no pen path in progress. + app.run("select.deselect", json!({})).unwrap(); + make_selection(&mut app).unwrap(); + let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); + crate::dialogs::confirm(&mut app, dialog).unwrap(); + assert!(app.session.active().unwrap().doc.selection.is_some()); + // Drawn with a saved path selected, the path is added to that one (#4721): the dialog is + // for it, not for a Work Path. + app.run("path.rename", json!({"name": "work", "to": "Cutout"})).unwrap(); + app.ui.selected_path = Some("Cutout".into()); + for (x, y) in [(4.0, 24.0), (12.0, 24.0), (12.0, 30.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + make_selection(&mut app).unwrap(); + assert_eq!(app.ui.dialogs.last().and_then(|d| d.fields.get("name")), Some(&json!("Cutout"))); +} + +/// #1056: the Path Selection and Direct Selection tools' right-click opens the path menu for +/// the selected path, as the Pen's does, instead of nothing. +#[test] +fn path_selection_tools_open_the_path_menu() { + for tool in [Tool::PathSelection, Tool::DirectSelection] { + let mut app = app(); + app.ui.tool = Tool::Pen; + for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + crate::vector_ui::pen_commit(&mut app, false); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + app.ui.tool = tool; + assert!(applies(tool)); + assert!(open(&mut app, &Context::default(), tool, [10.0, 10.0]), "{tool:?}"); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert_eq!(rows(&menu), PEN_MENU, "{tool:?}"); + assert!(menu.has_path && entry_enabled(&app, &menu, "path.toSelection"), "{tool:?}"); + choose(&mut app, &Context::default(), "path.toSelection"); + let dialog = app.ui.dialogs.last().map(|d| d.id).unwrap(); + crate::dialogs::confirm(&mut app, dialog).unwrap(); + assert!(app.session.active().unwrap().doc.selection.is_some(), "{tool:?}: Make Selection made one"); + } +} + +#[test] +fn pen_menu_has_all_reference_rows_in_order_and_guards_unavailable_actions() { + let labels: Vec<_> = PEN_MENU.iter().map(|row| row.map(|(label, _)| label)).collect(); + assert_eq!( + labels, + vec![ + Some("Create Vector Mask"), + Some("Delete Path"), + None, + Some("Define Custom Shape…"), + None, + Some("Make Selection…"), + Some("New Guides From Shape"), + Some("Fill Path…"), + Some("Stroke Path…"), + None, + Some("Clipping Path…"), + None, + Some("Free Transform Path"), + None, + Some("Unite Shapes"), + Some("Subtract Front Shape"), + Some("Unite Shapes at Overlap"), + Some("Subtract Shapes at Overlap"), + None, + Some("Copy Fill"), + Some("Copy Complete Stroke"), + None, + Some("Paste Fill"), + Some("Paste Complete Stroke"), + None, + Some("Isolate Layers"), + None, + Some("Make Symmetry Path"), + Some("Disable Symmetry Path"), + ] + ); + let mut app = app(); + app.ui.tool = Tool::Pen; + assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); + assert!(!entry_enabled(&app, menu, "path.toSelection")); + let before = app.session.journal.len(); + choose(&mut app, &Context::default(), "path.toSelection"); + assert_eq!(app.session.journal.len(), before); + assert!(app.ui.dialogs.is_empty()); +} + +#[test] +fn pen_menu_creates_mask_deletes_path_and_opens_named_path_dialogs() { + let mut app = app(); + app.ui.tool = Tool::Pen; + work_path(&mut app); + choose_open(&mut app, "layer.vectorMask.fromPath"); + let st = app.session.active().unwrap(); + assert!(st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.vector_mask.is_some())); + // The new vector mask's path becomes the active one (#4728); pick the Work Path again. + assert_eq!(app.ui.selected_path.as_deref(), Some("layer")); + app.ui.selected_path = Some("work".into()); + choose_open(&mut app, "edit.defineCustomShape"); + let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); + let fields = &app.ui.dialogs.last().unwrap().fields; + assert_eq!(fields.get("path"), Some(&json!("work"))); + app.ui.dialog_mut(id).unwrap().fields.insert("name".into(), json!("Menu Shape")); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert!(app.session.edit_state.custom_shapes.iter().any(|s| s.name == "Menu Shape")); + choose_open(&mut app, "path.fill"); + let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); + assert_eq!(app.ui.dialogs.last().unwrap().fields.get("name"), Some(&json!("work"))); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("path.fill")); + choose_open(&mut app, "path.delete"); + assert!(app.session.active().unwrap().doc.work_path.is_none()); +} + +#[test] +fn pen_menu_saved_path_clipping_and_numeric_transform() { + let mut app = app(); + app.ui.tool = Tool::Pen; + work_path(&mut app); + app.run("path.rename", json!({"name": "work", "to": "Cutout"})).unwrap(); + app.ui.selected_path = Some("Cutout".into()); + assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); + assert!(entry_enabled(&app, app.ui.canvas_tool_menu.as_ref().unwrap(), "path.clippingPath.set")); + choose(&mut app, &Context::default(), "path.clippingPath.set"); + let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); + app.ui.dialog_mut(id).unwrap().fields.insert("flatness".into(), json!(2.0)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.active().unwrap().doc.clipping_path.as_ref().map(|p| p.name.as_str()), Some("Cutout")); + choose_open(&mut app, "path.transform"); + let id = app.ui.dialogs.last().map(|d| d.id).unwrap(); + app.ui.dialog_mut(id).unwrap().fields.insert("translateX".into(), json!(5.0)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("path.transform")); +} + +#[test] +fn pen_shape_menu_enables_shape_ops_and_style_copy_only_when_applicable() { + let mut app = app(); + app.ui.tool = Tool::Pen; + app.run( + "shape.create", + json!({"kind":"path", "path":{"subpaths":[ + {"closed":true,"knots":[[2,2],[20,2],[20,20]]}, + {"closed":true,"knots":[[5,5],[10,5],[10,10]]} + ]}, "fill":"#ff0000", "stroke":{"width":2,"color":"#000000"}}), + ) + .unwrap(); + assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); + assert!(entry_enabled(&app, menu, "layer.combineShapes.unite")); + assert!(entry_enabled(&app, menu, "path.style.copyFill")); + assert!(!entry_enabled(&app, menu, "path.style.pasteFill")); + assert!(!entry_enabled(&app, menu, "path.fill")); + choose(&mut app, &Context::default(), "path.style.copyFill"); + assert!(app.session.path_fill_clipboard.is_some()); + assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); + assert!(entry_enabled(&app, app.ui.canvas_tool_menu.as_ref().unwrap(), "path.style.pasteFill")); +} + +#[test] +fn unfinished_shape_path_disables_actions_that_would_target_the_previous_layer() { + let mut app = app(); + app.ui.tool = Tool::Pen; + app.ui.tool_options.vector_mode = "shape".into(); + for (x, y) in [(2.0, 2.0), (20.0, 2.0), (20.0, 20.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + assert!(open(&mut app, &Context::default(), Tool::Pen, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.as_ref().unwrap(); + for id in ["layer.vectorMask.fromPath", "path.delete", "path.fill", "path.stroke", "path.clippingPath.set", "view.newGuidesFromShape"] { + assert!(!entry_enabled(&app, menu, id), "{id} must not act on the layer replaced by the pending shape"); + } + assert!(entry_enabled(&app, menu, "path.toSelection")); +} + +/// A 32 × 32 document with the Crop tool picked (Classic Mode, so the view stays put) and its +/// untouched default frame. +fn crop_app() -> PhotocraftApp { + let mut app = app(); + app.ui.tool = Tool::Crop; + app.ui.tool_options.crop_shield.classic_mode = true; + app.ui.extras.snap = false; + crate::crop_ui::ensure_frame(&mut app); + app +} + +/// Draws a crop frame from (4, 4) to (28, 28): a pending crop. Returns the frame. +fn draw_crop(app: &mut PhotocraftApp) -> [f64; 4] { + use crate::canvas::{ToolEvent, tool_event}; + tool_event(app, ToolEvent::Down { x: 4.0, y: 4.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: 16.0, y: 16.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: 28.0, y: 28.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: 28.0, y: 28.0 }, Modifiers::NONE); + assert!(crate::crop_ui::pending(app), "the drag draws a pending frame"); + app.ui.crop_rect.unwrap() +} + +fn aspect(r: [f64; 4]) -> f64 { + (r[2] - r[0]) / (r[3] - r[1]) +} + +/// #6561: right-click on a pending crop opens its menu without touching the frame, and a ratio +/// row refits the frame as the options bar's dropdown does. +#[test] +fn right_click_on_a_pending_crop_opens_the_crop_menu_and_a_ratio_refits_the_frame() { + let mut app = crop_app(); + let frame = draw_crop(&mut app); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().expect("right-click on a pending crop opens a menu"); + assert_eq!(h.state().ui.crop_rect, Some(frame), "the right-click leaves the frame alone"); + assert!(available(h.state(), &menu, "crop.ratio.16:9"), "the menu lists the options bar's ratios"); + let ctx = h.ctx.clone(); + choose(h.state_mut(), &ctx, "crop.ratio.16:9"); + assert_eq!(h.state().ui.tool_options.crop_ratio, "16:9"); + let r = h.state().ui.crop_rect.unwrap(); + assert!((aspect(r) - 16.0 / 9.0).abs() < 1e-9, "the frame is 16 : 9 now: {r:?}"); + assert!(r[0] >= frame[0] && r[1] >= frame[1] && r[2] <= frame[2] && r[3] <= frame[3], "fitted inside the old frame: {r:?}"); + assert!(h.state().ui.canvas_tool_menu.is_none()); +} + +#[test] +fn untouched_crop_frame_has_no_menu_and_a_pending_one_wins_over_the_pasteboard() { + let mut h = harness(crop_app()); + let rect = h.state().last_canvas_rect; + let outside = rect.min + vec2(5.0, 5.0); + right_click(&mut h, rect.center(), Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_none(), "the tool's untouched frame is no crop in progress"); + right_click(&mut h, outside, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "outside: the pasteboard menu, as before"); + h.state_mut().ui.canvas_tool_menu = None; + draw_crop(h.state_mut()); + h.run_steps(2); + right_click(&mut h, outside, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().unwrap(); + assert!(menu.crop.is_some() && !menu.pasteboard, "with a crop pending, its menu also outside the image"); +} + +/// A harness in the app's order: shortcuts (the crop's Esc and ↵ among them), then the canvas. +fn shortcut_harness(mut app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + app.sync_views(); + 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 +} + +#[test] +fn esc_closes_only_the_crop_menu() { + let mut app = crop_app(); + let frame = draw_crop(&mut app); + let mut h = shortcut_harness(app); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some())); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu"); + assert_eq!(h.state().ui.crop_rect, Some(frame), "and only the menu: the crop is not cancelled"); + assert!(crate::crop_ui::pending(h.state())); +} + +/// ↵ under the open crop menu doesn't commit the crop beneath it. +#[test] +fn enter_under_the_crop_menu_does_not_crop() { + let mut app = crop_app(); + let frame = draw_crop(&mut app); + let mut h = shortcut_harness(app); + let size = h.state().session.active().map(|s| s.doc.size); + let center = h.state().last_canvas_rect.center(); + right_click(&mut h, center, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some())); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(h.state().session.active().map(|s| s.doc.size), size, "↵ under the menu doesn't crop"); + assert_eq!(h.state().ui.crop_rect, Some(frame)); + assert!(crate::crop_ui::pending(h.state())); +} + +/// A right-click while the left button drags the crop frame opens no menu over the drag, on +/// the image or outside it (no pasteboard menu either), and the menu opens again once the left +/// button is up, though egui ended that drag without a release of its own. +#[test] +fn no_crop_menu_while_the_left_button_drags_the_frame() { + let mut app = crop_app(); + draw_crop(&mut app); + let mut h = harness(app); + let rect = h.state().last_canvas_rect; + let (center, outside) = (rect.center(), rect.min + vec2(5.0, 5.0)); + let left = |pos, pressed| egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + h.event(egui::Event::PointerMoved(center)); + h.run_steps(1); + h.event(left(center, true)); + h.run_steps(1); + for k in 1..=4 { + h.event(egui::Event::PointerMoved(center + vec2(8.0 * k as f32, 0.0))); + h.run_steps(1); + } + assert!(h.state().crop.drag.is_some(), "the left button drags the frame"); + let held = center + vec2(32.0, 0.0); + right_click(&mut h, held, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_none(), "no crop menu over the drag"); + right_click(&mut h, outside, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_none(), "nor the pasteboard menu outside the image"); + h.event(egui::Event::PointerMoved(held)); + h.event(left(held, false)); + h.run_steps(2); + right_click(&mut h, center, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some()), "with the button up the menu opens"); +} + +/// The left button down with no crop gesture under way (a press egui doesn't take for a drag +/// yet, or one whose release was lost to an Alt+Tab or a cancelled touch) doesn't keep the +/// crop menu shut. +#[test] +fn a_left_button_down_without_a_crop_drag_keeps_the_crop_menu() { + let mut app = crop_app(); + draw_crop(&mut app); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(center)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: center, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert!(h.ctx.input(|i| i.pointer.primary_down()) && h.state().crop.drag.is_none(), "down, dragging nothing"); + right_click(&mut h, center, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some()), "the crop menu opens"); +} + +/// Nor does a right-click open a menu over a Straighten line the left button still draws. +#[test] +fn no_crop_menu_while_the_left_button_draws_a_straighten_line() { + let mut app = crop_app(); + draw_crop(&mut app); + crate::crop_straighten::toggle(&mut app); + let mut h = harness(app); + let center = h.state().last_canvas_rect.center(); + let left = |pos, pressed| egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + h.event(egui::Event::PointerMoved(center)); + h.run_steps(1); + h.event(left(center, true)); + h.run_steps(1); + for k in 1..=4 { + h.event(egui::Event::PointerMoved(center + vec2(8.0 * k as f32, 4.0))); + h.run_steps(1); + } + assert!(h.state().crop.straighten.line.is_some() && h.state().crop.drag.is_none(), "the left button draws a Straighten line"); + right_click(&mut h, center + vec2(32.0, 4.0), Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_none(), "no menu over the line"); +} + +/// A finger held still on a pending crop (a touch screen's press-and-hold right-click) opens +/// the crop menu, though the touch counts as the primary button down. +#[test] +fn a_finger_held_on_a_pending_crop_opens_the_crop_menu() { + let mut app = crop_app(); + let frame = draw_crop(&mut app); + let mut h = harness(app); + let at = h.state().last_canvas_rect.center(); + let touch = |phase| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(1), phase, pos: at, force: None }; + let button = |pressed| egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + h.input_mut().events.extend([egui::Event::PointerMoved(at), touch(egui::TouchPhase::Start), button(true)]); + h.step(); + // Held past egui's max_click_duration (0.8 s) without moving. + for _ in 0..120 { + if h.state().ui.canvas_tool_menu.is_some() { + break; + } + h.step(); + } + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some()), "the held finger opens the crop menu"); + h.input_mut().events.extend([touch(egui::TouchPhase::End), button(false)]); + h.run_steps(2); + assert_eq!(h.state().ui.crop_rect, Some(frame), "the hold leaves the frame alone"); +} + +#[test] +fn crop_menu_rows_act_like_the_options_bar() { + use crate::crop_overlay::{CropOverlay, OverlayShow}; + let ctx = Context::default(); + let mut app = crop_app(); + draw_crop(&mut app); + // Space's Hand held over the Crop tool keeps its own right-click. + assert!(!open_crop(&mut app, &ctx, Tool::Hand, [10.0, 10.0])); + let reopen = |app: &mut PhotocraftApp| { + assert!(open_crop(app, &Context::default(), Tool::Crop, [10.0, 10.0])); + app.ui.canvas_tool_menu.clone().unwrap() + }; + // Nothing to save with a free ratio, nothing to delete without saved presets. + let menu = reopen(&mut app); + assert!(!entry_enabled(&app, &menu, CROP_NEW) && !entry_enabled(&app, &menu, CROP_DELETE)); + assert!(mode_checked(&app, &menu, "crop.ratio."), "free Ratio is checked, as in the dropdown"); + // A size preset fills W x H x Resolution, which the menu checks, as the dropdown does. + choose(&mut app, &ctx, "crop.ratio.preset:4x5in"); + let menu = reopen(&mut app); + assert!(mode_checked(&app, &menu, "crop.ratio.whr") && !mode_checked(&app, &menu, "crop.ratio.preset:4x5in")); + assert!((aspect(app.ui.crop_rect.unwrap()) - 0.8).abs() < 1e-9); + assert!(entry_enabled(&app, &menu, CROP_NEW)); + // Clear empties W x H x Resolution, as the bar's Clear. + choose(&mut app, &ctx, CROP_CLEAR); + assert_eq!(app.ui.tool_options.crop_width, ""); + // Overlays: another overlay starts at its first orientation; when it shows. + app.ui.tool_options.crop_overlay = CropOverlay::GoldenSpiral; + app.ui.tool_options.crop_overlay_orientation = 2; + reopen(&mut app); + choose(&mut app, &ctx, "crop.overlay.triangle"); + assert_eq!((app.ui.tool_options.crop_overlay, app.ui.tool_options.crop_overlay_orientation), (CropOverlay::Triangle, 0)); + reopen(&mut app); + choose(&mut app, &ctx, "crop.overlayShow.never"); + assert_eq!(app.ui.tool_options.crop_overlay_show, OverlayShow::Never); + let menu = reopen(&mut app); + assert!(mode_checked(&app, &menu, "crop.overlay.triangle") && mode_checked(&app, &menu, "crop.overlayShow.never")); + // A saved preset is listed by name; picking it refits the frame to its W x H, though the + // ratio key is "whr" before and after. + app.ui.canvas_tool_menu = None; + app.ui.tool_options.crop_ratio = crate::crop_size::WHR.into(); + let saved = json!({"crop_ratio": "whr", "crop_width": "300 px", "crop_height": "100 px", "crop_resolution": "72", "crop_resolution_unit": "px/in"}); + app.run("tool.presets.new", json!({"name": "Banner", "tool": "crop", "options": {"toolOptions": saved}})).unwrap(); + let menu = reopen(&mut app); + let banner = crop_rows(&menu).into_iter().flatten().find(|(l, _)| l == "Banner").expect("the saved preset is a row").1; + assert!(entry_enabled(&app, &menu, CROP_DELETE)); + choose(&mut app, &ctx, &banner); + assert_eq!(app.ui.tool_options.crop_width, "300 px"); + assert!((aspect(app.ui.crop_rect.unwrap()) - 3.0).abs() < 1e-9, "the frame follows the preset: {:?}", app.ui.crop_rect); + let menu = reopen(&mut app); + assert!(mode_checked(&app, &menu, &banner)); + // Crop commits as ↵ does: the preset's size. + choose(&mut app, &ctx, CROP_COMMIT); + let size = app.session.active().unwrap().doc.size; + assert_eq!((size.width, size.height), (300, 100)); + // Cancel drops a pending crop. + draw_crop(&mut app); + reopen(&mut app); + choose(&mut app, &ctx, CROP_CANCEL); + assert!(!crate::crop_ui::pending(&app)); +} From 57dbc1cca791e86ad37a589df589cc0134f03331 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:50 +0000 Subject: [PATCH 067/259] refactor(ui-egui): move move_ui.rs tests to move_ui/tests.rs --- crates/ui-egui/src/move_ui.rs | 348 +--------------------------- crates/ui-egui/src/move_ui/tests.rs | 345 +++++++++++++++++++++++++++ 2 files changed, 346 insertions(+), 347 deletions(-) create mode 100644 crates/ui-egui/src/move_ui/tests.rs diff --git a/crates/ui-egui/src/move_ui.rs b/crates/ui-egui/src/move_ui.rs index 46fcfa56a7..29920474f7 100644 --- a/crates/ui-egui/src/move_ui.rs +++ b/crates/ui-egui/src/move_ui.rs @@ -298,350 +298,4 @@ pub(crate) fn finish(app: &mut PhotocraftApp, dx: f64, dy: f64) { } #[cfg(test)] -mod tests { - use photocraft_geom::Rect; - use serde_json::json; - - use crate::PhotocraftApp; - use crate::canvas::ToolEvent; - use crate::state::Tool; - - #[test] - fn dragging_a_layer_larger_than_the_canvas_redraws_what_comes_in_from_beyond_the_edge() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, a| { - doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(-32, -32, 96, 96), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - app.ui.tool = Tool::Move; - app.ui.extras.snap = false; - app.ui.view.show.smart_guides = false; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 32.0, y: 32.0, pressure: 1.0 }, m); - let mut keys = Vec::new(); - for x in [42.0, 52.0] { - crate::canvas::tool_event(&mut app, ToolEvent::Move { x, y: 32.0, pressure: 1.0 }, m); - keys.push(super::display_doc(&mut app, 0).unwrap().1); - } - let st = app.session.active().unwrap(); - // From +10 to +20 the strip x 0..10 shows pixels that were off the canvas a frame ago. - let r = super::damage(&app, st.doc.id, st.revision, keys[0], keys[1]).unwrap(); - assert_eq!(r, Rect::new(0, 0, 64, 64)); - } - - /// The Move tool shows how far it has moved the layer, ΔX/ΔY in whole pixels, as Photoshop - /// and Free Transform do (#5727): once the pointer moves, until the release. - #[test] - fn a_move_drag_reads_out_the_offset_it_will_commit() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, a| { - doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(16, 16, 32, 32), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - app.ui.tool = Tool::Move; - app.ui.extras.snap = false; - app.ui.view.show.smart_guides = false; - let m = egui::Modifiers::NONE; - assert_eq!(super::offset_readout(&app), None, "no drag"); - // Pressed on the red square (16..32): with Auto-Select (on by default) an empty spot would - // start the layer marquee instead of a move. - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 24.0, y: 24.0, pressure: 1.0 }, m); - assert_eq!(super::offset_readout(&app), None, "pressed, not moved yet"); - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 34.4, y: 20.8, pressure: 1.0 }, m); - assert_eq!(super::offset_readout(&app), Some(["10 px".to_string(), "-3 px".to_string()])); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 34.4, y: 20.8 }, m); - assert_eq!(super::offset_readout(&app), None, "released"); - } - - /// A release past the ±10,000,000 px the preview and the readout show commits the offset they - /// showed, not the raw pointer distance. - #[test] - fn a_release_commits_the_offset_the_readout_caps_at() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); - app.sync_views(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); - app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.session.execute("select.deselect", json!({})).unwrap(); - super::finish(&mut app, 2.5e7, -2.5e7); - let st = app.session.active().unwrap(); - let s = st.active_layer.and_then(|id| st.doc.layer(id)).and_then(|l| l.surface()).unwrap(); - assert!(s.pixel(16 + 10_000_000, 16 - 10_000_000)[3] > 0.5, "moved by the capped offset"); - } - - /// A shape reaching past the canvas edge renders cut at the canvas, but its path goes on: a - /// drag frame must redraw where the rest of it was, or the cut edge stays behind (#3946). - #[test] - fn dragging_a_shape_past_the_canvas_edge_leaves_no_trail() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); - app.sync_views(); - let id = app.session.execute("shape.create", json!({"kind": "rect", "rect": [40, 16, 50, 32], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap(); - let id = photocraft_doc::LayerId(id); - app.ui.tool = Tool::Move; - app.ui.extras.snap = false; - app.ui.view.show.smart_guides = false; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 32.0, pressure: 1.0 }, m); - let mut frames = Vec::new(); - for x in [40.0, 10.0] { - crate::canvas::tool_event(&mut app, ToolEvent::Move { x, y: 32.0, pressure: 1.0 }, m); - frames.push(super::display_doc(&mut app, 0).unwrap()); - } - let st = app.session.active().unwrap(); - let r = super::damage(&app, st.doc.id, st.revision, frames[0].1, frames[1].1).unwrap(); - let alpha = |d: &photocraft_doc::Document, x, y| d.layer(id).and_then(|l| l.surface()).map_or(0.0, |s| s.pixel(x, y)[3]); - for y in 0..64 { - for x in 0..64 { - if alpha(&frames[0].0, x, y) != alpha(&frames[1].0, x, y) { - assert!(r.contains(x, y), "({x}, {y}) changed outside the redrawn {r:?}"); - } - } - } - } - - /// 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] - fn dragging_with_an_unlinked_mask_targeted_moves_the_mask_alone() { - for (linked, mask_target) in [(false, true), (false, false), (true, true)] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); - app.sync_views(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); - app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.session.execute("select.deselect", json!({})).unwrap(); - app.session.execute("layer.layerMask.revealAll", json!({})).unwrap(); - app.session.execute("layer.layerMask.linked", json!({"linked": linked})).unwrap(); - app.ui.mask_target = mask_target; - app.ui.tool = Tool::Move; - app.ui.extras.snap = false; - app.ui.view.show.smart_guides = false; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 16.0, y: 16.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 36.0, y: 16.0, pressure: 1.0 }, m); - let shown = super::display_doc(&mut app, 0).unwrap().0; - let id = app.session.active().unwrap().active_layer.unwrap(); - let layer_moved = |d: &photocraft_doc::Document| d.layer(id).and_then(|l| l.surface()).is_some_and(|s| s.pixel(28, 16)[3] > 0.5); - let alone = !linked && mask_target; - assert_eq!(layer_moved(&shown), !alone, "preview, linked {linked} mask target {mask_target}"); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 36.0, y: 16.0 }, m); - let d = &app.session.active().unwrap().doc; - assert_eq!(layer_moved(d), !alone, "commit, linked {linked} mask target {mask_target}"); - } - } - - /// Mid-drag on a painted layer: is the layer shown at the pointer? - fn live(outline: bool) -> bool { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); - app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.session.execute("select.deselect", json!({})).unwrap(); - app.session.edit_prefs(|p| p.interface.show_bounding_box_when_dragging_layer = outline); - app.ui.tool = Tool::Move; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 16.0, y: 16.0, pressure: 1.0 }, m); - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 20.0, pressure: 1.0 }, m); - let shown = super::display_doc(&mut app, 0).is_some(); - assert_eq!(shown, super::showing(&app)); - shown - } - - #[test] - fn bounding_box_preference_turns_the_live_drag_off() { - assert!(live(false), "by default the layer follows the pointer"); - assert!(!live(true), "with the preference on, only the outline and arrow move"); - } - - /// A `depth`-bit transparent document whose layer holds a red square (8..24)² and a blue one - /// (40..56)×(8..24), the red one selected; the Move tool with Auto-Select on. - fn selected_pixels(depth: u32) -> (PhotocraftApp, photocraft_doc::LayerId) { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent", "depth": depth})).unwrap(); - app.sync_views(); - for (x, color) in [(40, "#0000ff"), (8, "#ff0000")] { - app.session.execute("select.rect", json!({"x": x, "y": 8, "width": 16, "height": 16})).unwrap(); - app.session.execute("edit.fill", json!({"color": color})).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 id = app.session.active().unwrap().active_layer.unwrap(); - (app, id) - } - - fn alpha(app: &PhotocraftApp, id: photocraft_doc::LayerId, x: i32, y: i32) -> f32 { - app.session.active().unwrap().doc.layer(id).unwrap().surface().unwrap().rgba(x, y)[3] - } - - fn offset(app: &PhotocraftApp) -> Option<(i32, i32)> { - photocraft_engine::float_cmds::floating(app.session.active().unwrap()).map(|f| f.offset) - } - - fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], m: egui::Modifiers) { - crate::canvas::tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, m); - crate::canvas::tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, m); - crate::canvas::tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, m); - } - - /// ↩ through the app's key handling. - fn enter(app: &mut PhotocraftApp) { - let ctx = egui::Context::default(); - let key = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - let input = egui::RawInput { events: vec![key], ..Default::default() }; - ctx.run_ui(input, |ui| crate::shortcuts::handle(app, ui.ctx())).textures_delta.clear(); - } - - /// #578: with a selection the Move tool drags the selected pixels (from anywhere, without an - /// Auto-Select pick), not the layer; ↩ drops them as one "Move" step that one undo takes back. - #[test] - fn with_a_selection_the_move_tool_moves_only_the_selected_pixels() { - for depth in [8, 16, 32] { - let (mut app, id) = selected_pixels(depth); - let steps = app.session.active().unwrap().history.past_len(); - drag(&mut app, [50.0, 40.0], [60.0, 45.0], egui::Modifiers::NONE); - assert_eq!(offset(&app), Some((10, 5)), "{depth}-bit: floating"); - let shown = super::display_doc(&mut app, 0).unwrap().0; - let shown_alpha = |x, y| shown.layer(id).unwrap().surface().unwrap().rgba(x, y)[3]; - assert!(shown_alpha(10, 10) == 0.0 && shown_alpha(30, 25) == 1.0, "{depth}-bit: shown moved"); - enter(&mut app); - assert_eq!(offset(&app), None, "{depth}-bit: ↩ dropped it"); - assert_eq!(alpha(&app, id, 10, 10), 0.0, "{depth}-bit: the hole is transparent"); - assert_eq!(alpha(&app, id, 30, 25), 1.0, "{depth}-bit: the red square moved"); - assert_eq!(alpha(&app, id, 48, 16), 1.0, "{depth}-bit: the unselected blue one stayed"); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), Rect::new(18, 13, 34, 29), "{depth}-bit"); - assert_eq!((st.history.past_len(), st.history.undo_label()), (steps + 1, Some("Move")), "{depth}-bit"); - assert!(app.session.undo()); - assert!(alpha(&app, id, 10, 10) == 1.0 && alpha(&app, id, 30, 25) == 0.0, "{depth}-bit: undone"); - } - } - - /// ⌥ copies the selected pixels (no layer copy), ⇧ locks the drag to multiples of 45°. - #[test] - fn alt_copies_and_shift_constrains_the_selected_pixels() { - for depth in [8, 16, 32] { - let (mut app, id) = selected_pixels(depth); - let layers = app.session.active().unwrap().doc.layers.len(); - drag(&mut app, [16.0, 16.0], [30.0, 28.0], egui::Modifiers::ALT | egui::Modifiers::SHIFT); - assert_eq!(offset(&app), Some((13, 13)), "{depth}-bit: 45°"); - app.run("select.drop", json!({})).unwrap(); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "{depth}-bit: no layer copy"); - assert!(alpha(&app, id, 10, 10) == 1.0 && alpha(&app, id, 35, 35) == 1.0, "{depth}-bit: original and copy"); - assert!(app.session.undo()); - assert_eq!(alpha(&app, id, 35, 35), 0.0, "{depth}-bit: undone"); - } - } - - /// #7538: a loose marquee round the red square shrinks to it as the drag starts: the canvas - /// outlines the moved pixels while they float, and the dropped selection is theirs. Alt-drag - /// (a copy) too. - #[test] - fn dragging_selected_pixels_shrinks_the_ants_to_them() { - for depth in [8, 16, 32] { - for m in [egui::Modifiers::NONE, egui::Modifiers::ALT] { - let (mut app, _) = selected_pixels(depth); - app.session.execute("select.rect", json!({"x": 2, "y": 2, "width": 30, "height": 30})).unwrap(); - drag(&mut app, [16.0, 16.0], [26.0, 21.0], m); - assert_eq!(offset(&app), Some((10, 5)), "{depth}-bit, {m:?}: floating"); - let ants = crate::canvas::floating_outline(&app, 0).map(|s| s.content_bounds()); - assert_eq!(ants, Some(Rect::new(8, 8, 24, 24)), "{depth}-bit, {m:?}: the ants hug the red square"); - assert!(crate::canvas::floating_outline(&app, 1).is_none(), "only the active document's"); - app.run("select.drop", json!({})).unwrap(); - let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds()); - assert_eq!(sel, Some(Rect::new(18, 13, 34, 29)), "{depth}-bit, {m:?}: dropped"); - assert!(crate::canvas::floating_outline(&app, 0).is_none(), "nothing floats"); - } - } - } - - /// ⌘-drag with a painting tool drags the selected pixels as the Move tool does, also when ⌘ - /// comes with the event (control channel, MCP) rather than as the held-key override. - #[test] - fn command_drag_with_a_painting_tool_moves_only_the_selected_pixels() { - let (mut app, id) = selected_pixels(8); - app.ui.tool = Tool::Brush; - app.ui.tool_options.move_auto_select = false; - let cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; - drag(&mut app, [50.0, 40.0], [60.0, 45.0], cmd); - assert_eq!(offset(&app), Some((10, 5)), "the selected pixels float"); - drag(&mut app, [50.0, 40.0], [60.0, 45.0], cmd); - assert_eq!(offset(&app), Some((20, 10)), "a second drag moves the same floating piece"); - app.run("select.drop", json!({})).unwrap(); - assert!(alpha(&app, id, 10, 10) == 0.0 && alpha(&app, id, 40, 30) == 1.0, "the red square moved"); - assert_eq!(alpha(&app, id, 48, 16), 1.0, "the unselected blue one stayed"); - } - - /// A click moves nothing and leaves nothing floating (Undo isn't spent putting it back). - #[test] - fn a_click_with_a_selection_moves_nothing() { - let (mut app, id) = selected_pixels(8); - let steps = app.session.active().unwrap().history.past_len(); - drag(&mut app, [16.0, 16.0], [16.0, 16.0], egui::Modifiers::NONE); - assert_eq!(offset(&app), None); - assert_eq!(app.session.active().unwrap().history.past_len(), steps); - assert!(alpha(&app, id, 10, 10) == 1.0 && alpha(&app, id, 48, 16) == 1.0); - } - - #[test] - fn arrow_keys_nudge_the_selected_pixels() { - let (mut app, id) = selected_pixels(16); - crate::move_mods::nudge(&mut app, 10.0, 0.0, false); - crate::move_mods::nudge(&mut app, 0.0, 1.0, false); - assert_eq!(offset(&app), Some((10, 1))); - // ⌥ leaves the piece where it is and nudges a copy of it. - crate::move_mods::nudge(&mut app, 1.0, 0.0, true); - assert_eq!(offset(&app), Some((1, 0))); - app.run("select.drop", json!({})).unwrap(); - assert!(alpha(&app, id, 10, 10) == 0.0 && alpha(&app, id, 18, 20) == 1.0 && alpha(&app, id, 34, 20) == 1.0); - assert_eq!(alpha(&app, id, 48, 16), 1.0, "the layer itself didn't move"); - } - - /// Without floatable pixels (a position-locked layer) the Move tool behaves as without a - /// selection: it moves the layer, which the lock refuses. - #[test] - fn a_layer_that_cannot_float_moves_whole_as_before() { - let (mut app, id) = selected_pixels(8); - app.session.execute("layer.lockLayers", json!({"position": true})).unwrap(); - drag(&mut app, [16.0, 16.0], [26.0, 16.0], egui::Modifiers::NONE); - assert_eq!(offset(&app), None); - assert!(alpha(&app, id, 10, 10) == 1.0 && alpha(&app, id, 30, 16) == 0.0, "nothing moved"); - // Without a selection the layer moves whole. - app.session.execute("layer.lockLayers", json!({"position": false})).unwrap(); - app.session.execute("select.deselect", json!({})).unwrap(); - drag(&mut app, [16.0, 16.0], [26.0, 16.0], egui::Modifiers::NONE); - assert!(alpha(&app, id, 10, 10) == 0.0 && alpha(&app, id, 58, 16) == 1.0, "the whole layer moved"); - } - - #[test] - fn floating_selection_does_not_snap_to_its_own_starting_outline_or_preview_at_zero() { - let (mut app, _id) = selected_pixels(8); - app.ui.extras.snap = true; - app.ui.view.snap_to.document_bounds = false; - let m = egui::Modifiers::NONE; - crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 16.0, y: 16.0, pressure: 1.0 }, m); - assert!(super::display_doc(&mut app, 0).is_none(), "no preview composite at offset (0, 0) before the pointer moves"); - // A small 2 px move within the snap radius must move immediately instead of snapping back to (0, 0). - crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 18.0, y: 17.0, pressure: 1.0 }, m); - assert_eq!(super::floating_offset(&app), Some((2, 1)), "small drag moves without snapping to own selection bounds"); - assert!(super::display_doc(&mut app, 0).is_some(), "preview is shown once offset is non-zero"); - crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 18.0, y: 17.0 }, m); - assert_eq!(offset(&app), Some((2, 1))); - } -} +mod tests; diff --git a/crates/ui-egui/src/move_ui/tests.rs b/crates/ui-egui/src/move_ui/tests.rs new file mode 100644 index 0000000000..80bea71dc2 --- /dev/null +++ b/crates/ui-egui/src/move_ui/tests.rs @@ -0,0 +1,345 @@ +use photocraft_geom::Rect; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::ToolEvent; +use crate::state::Tool; + +#[test] +fn dragging_a_layer_larger_than_the_canvas_redraws_what_comes_in_from_beyond_the_edge() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(-32, -32, 96, 96), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.ui.tool = Tool::Move; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 32.0, y: 32.0, pressure: 1.0 }, m); + let mut keys = Vec::new(); + for x in [42.0, 52.0] { + crate::canvas::tool_event(&mut app, ToolEvent::Move { x, y: 32.0, pressure: 1.0 }, m); + keys.push(super::display_doc(&mut app, 0).unwrap().1); + } + let st = app.session.active().unwrap(); + // From +10 to +20 the strip x 0..10 shows pixels that were off the canvas a frame ago. + let r = super::damage(&app, st.doc.id, st.revision, keys[0], keys[1]).unwrap(); + assert_eq!(r, Rect::new(0, 0, 64, 64)); +} + +/// The Move tool shows how far it has moved the layer, ΔX/ΔY in whole pixels, as Photoshop +/// and Free Transform do (#5727): once the pointer moves, until the release. +#[test] +fn a_move_drag_reads_out_the_offset_it_will_commit() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(16, 16, 32, 32), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.ui.tool = Tool::Move; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + let m = egui::Modifiers::NONE; + assert_eq!(super::offset_readout(&app), None, "no drag"); + // Pressed on the red square (16..32): with Auto-Select (on by default) an empty spot would + // start the layer marquee instead of a move. + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 24.0, y: 24.0, pressure: 1.0 }, m); + assert_eq!(super::offset_readout(&app), None, "pressed, not moved yet"); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 34.4, y: 20.8, pressure: 1.0 }, m); + assert_eq!(super::offset_readout(&app), Some(["10 px".to_string(), "-3 px".to_string()])); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 34.4, y: 20.8 }, m); + assert_eq!(super::offset_readout(&app), None, "released"); +} + +/// A release past the ±10,000,000 px the preview and the readout show commits the offset they +/// showed, not the raw pointer distance. +#[test] +fn a_release_commits_the_offset_the_readout_caps_at() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + super::finish(&mut app, 2.5e7, -2.5e7); + let st = app.session.active().unwrap(); + let s = st.active_layer.and_then(|id| st.doc.layer(id)).and_then(|l| l.surface()).unwrap(); + assert!(s.pixel(16 + 10_000_000, 16 - 10_000_000)[3] > 0.5, "moved by the capped offset"); +} + +/// A shape reaching past the canvas edge renders cut at the canvas, but its path goes on: a +/// drag frame must redraw where the rest of it was, or the cut edge stays behind (#3946). +#[test] +fn dragging_a_shape_past_the_canvas_edge_leaves_no_trail() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); + app.sync_views(); + let id = app.session.execute("shape.create", json!({"kind": "rect", "rect": [40, 16, 50, 32], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap(); + let id = photocraft_doc::LayerId(id); + app.ui.tool = Tool::Move; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 32.0, pressure: 1.0 }, m); + let mut frames = Vec::new(); + for x in [40.0, 10.0] { + crate::canvas::tool_event(&mut app, ToolEvent::Move { x, y: 32.0, pressure: 1.0 }, m); + frames.push(super::display_doc(&mut app, 0).unwrap()); + } + let st = app.session.active().unwrap(); + let r = super::damage(&app, st.doc.id, st.revision, frames[0].1, frames[1].1).unwrap(); + let alpha = |d: &photocraft_doc::Document, x, y| d.layer(id).and_then(|l| l.surface()).map_or(0.0, |s| s.pixel(x, y)[3]); + for y in 0..64 { + for x in 0..64 { + if alpha(&frames[0].0, x, y) != alpha(&frames[1].0, x, y) { + assert!(r.contains(x, y), "({x}, {y}) changed outside the redrawn {r:?}"); + } + } + } +} + +/// 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] +fn dragging_with_an_unlinked_mask_targeted_moves_the_mask_alone() { + for (linked, mask_target) in [(false, true), (false, false), (true, true)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + app.session.execute("layer.layerMask.revealAll", json!({})).unwrap(); + app.session.execute("layer.layerMask.linked", json!({"linked": linked})).unwrap(); + app.ui.mask_target = mask_target; + app.ui.tool = Tool::Move; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 16.0, y: 16.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 36.0, y: 16.0, pressure: 1.0 }, m); + let shown = super::display_doc(&mut app, 0).unwrap().0; + let id = app.session.active().unwrap().active_layer.unwrap(); + let layer_moved = |d: &photocraft_doc::Document| d.layer(id).and_then(|l| l.surface()).is_some_and(|s| s.pixel(28, 16)[3] > 0.5); + let alone = !linked && mask_target; + assert_eq!(layer_moved(&shown), !alone, "preview, linked {linked} mask target {mask_target}"); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 36.0, y: 16.0 }, m); + let d = &app.session.active().unwrap().doc; + assert_eq!(layer_moved(d), !alone, "commit, linked {linked} mask target {mask_target}"); + } +} + +/// Mid-drag on a painted layer: is the layer shown at the pointer? +fn live(outline: bool) -> bool { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + app.session.edit_prefs(|p| p.interface.show_bounding_box_when_dragging_layer = outline); + app.ui.tool = Tool::Move; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 16.0, y: 16.0, pressure: 1.0 }, m); + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 20.0, pressure: 1.0 }, m); + let shown = super::display_doc(&mut app, 0).is_some(); + assert_eq!(shown, super::showing(&app)); + shown +} + +#[test] +fn bounding_box_preference_turns_the_live_drag_off() { + assert!(live(false), "by default the layer follows the pointer"); + assert!(!live(true), "with the preference on, only the outline and arrow move"); +} + +/// A `depth`-bit transparent document whose layer holds a red square (8..24)² and a blue one +/// (40..56)×(8..24), the red one selected; the Move tool with Auto-Select on. +fn selected_pixels(depth: u32) -> (PhotocraftApp, photocraft_doc::LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64, "background": "transparent", "depth": depth})).unwrap(); + app.sync_views(); + for (x, color) in [(40, "#0000ff"), (8, "#ff0000")] { + app.session.execute("select.rect", json!({"x": x, "y": 8, "width": 16, "height": 16})).unwrap(); + app.session.execute("edit.fill", json!({"color": color})).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 id = app.session.active().unwrap().active_layer.unwrap(); + (app, id) +} + +fn alpha(app: &PhotocraftApp, id: photocraft_doc::LayerId, x: i32, y: i32) -> f32 { + app.session.active().unwrap().doc.layer(id).unwrap().surface().unwrap().rgba(x, y)[3] +} + +fn offset(app: &PhotocraftApp) -> Option<(i32, i32)> { + photocraft_engine::float_cmds::floating(app.session.active().unwrap()).map(|f| f.offset) +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], m: egui::Modifiers) { + crate::canvas::tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, m); + crate::canvas::tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, m); + crate::canvas::tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, m); +} + +/// ↩ through the app's key handling. +fn enter(app: &mut PhotocraftApp) { + let ctx = egui::Context::default(); + let key = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let input = egui::RawInput { events: vec![key], ..Default::default() }; + ctx.run_ui(input, |ui| crate::shortcuts::handle(app, ui.ctx())).textures_delta.clear(); +} + +/// #578: with a selection the Move tool drags the selected pixels (from anywhere, without an +/// Auto-Select pick), not the layer; ↩ drops them as one "Move" step that one undo takes back. +#[test] +fn with_a_selection_the_move_tool_moves_only_the_selected_pixels() { + for depth in [8, 16, 32] { + let (mut app, id) = selected_pixels(depth); + let steps = app.session.active().unwrap().history.past_len(); + drag(&mut app, [50.0, 40.0], [60.0, 45.0], egui::Modifiers::NONE); + assert_eq!(offset(&app), Some((10, 5)), "{depth}-bit: floating"); + let shown = super::display_doc(&mut app, 0).unwrap().0; + let shown_alpha = |x, y| shown.layer(id).unwrap().surface().unwrap().rgba(x, y)[3]; + assert!(shown_alpha(10, 10) == 0.0 && shown_alpha(30, 25) == 1.0, "{depth}-bit: shown moved"); + enter(&mut app); + assert_eq!(offset(&app), None, "{depth}-bit: ↩ dropped it"); + assert_eq!(alpha(&app, id, 10, 10), 0.0, "{depth}-bit: the hole is transparent"); + assert_eq!(alpha(&app, id, 30, 25), 1.0, "{depth}-bit: the red square moved"); + assert_eq!(alpha(&app, id, 48, 16), 1.0, "{depth}-bit: the unselected blue one stayed"); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), Rect::new(18, 13, 34, 29), "{depth}-bit"); + assert_eq!((st.history.past_len(), st.history.undo_label()), (steps + 1, Some("Move")), "{depth}-bit"); + assert!(app.session.undo()); + assert!(alpha(&app, id, 10, 10) == 1.0 && alpha(&app, id, 30, 25) == 0.0, "{depth}-bit: undone"); + } +} + +/// ⌥ copies the selected pixels (no layer copy), ⇧ locks the drag to multiples of 45°. +#[test] +fn alt_copies_and_shift_constrains_the_selected_pixels() { + for depth in [8, 16, 32] { + let (mut app, id) = selected_pixels(depth); + let layers = app.session.active().unwrap().doc.layers.len(); + drag(&mut app, [16.0, 16.0], [30.0, 28.0], egui::Modifiers::ALT | egui::Modifiers::SHIFT); + assert_eq!(offset(&app), Some((13, 13)), "{depth}-bit: 45°"); + app.run("select.drop", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "{depth}-bit: no layer copy"); + assert!(alpha(&app, id, 10, 10) == 1.0 && alpha(&app, id, 35, 35) == 1.0, "{depth}-bit: original and copy"); + assert!(app.session.undo()); + assert_eq!(alpha(&app, id, 35, 35), 0.0, "{depth}-bit: undone"); + } +} + +/// #7538: a loose marquee round the red square shrinks to it as the drag starts: the canvas +/// outlines the moved pixels while they float, and the dropped selection is theirs. Alt-drag +/// (a copy) too. +#[test] +fn dragging_selected_pixels_shrinks_the_ants_to_them() { + for depth in [8, 16, 32] { + for m in [egui::Modifiers::NONE, egui::Modifiers::ALT] { + let (mut app, _) = selected_pixels(depth); + app.session.execute("select.rect", json!({"x": 2, "y": 2, "width": 30, "height": 30})).unwrap(); + drag(&mut app, [16.0, 16.0], [26.0, 21.0], m); + assert_eq!(offset(&app), Some((10, 5)), "{depth}-bit, {m:?}: floating"); + let ants = crate::canvas::floating_outline(&app, 0).map(|s| s.content_bounds()); + assert_eq!(ants, Some(Rect::new(8, 8, 24, 24)), "{depth}-bit, {m:?}: the ants hug the red square"); + assert!(crate::canvas::floating_outline(&app, 1).is_none(), "only the active document's"); + app.run("select.drop", json!({})).unwrap(); + let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds()); + assert_eq!(sel, Some(Rect::new(18, 13, 34, 29)), "{depth}-bit, {m:?}: dropped"); + assert!(crate::canvas::floating_outline(&app, 0).is_none(), "nothing floats"); + } + } +} + +/// ⌘-drag with a painting tool drags the selected pixels as the Move tool does, also when ⌘ +/// comes with the event (control channel, MCP) rather than as the held-key override. +#[test] +fn command_drag_with_a_painting_tool_moves_only_the_selected_pixels() { + let (mut app, id) = selected_pixels(8); + app.ui.tool = Tool::Brush; + app.ui.tool_options.move_auto_select = false; + let cmd = egui::Modifiers { mac_cmd: true, command: true, ..Default::default() }; + drag(&mut app, [50.0, 40.0], [60.0, 45.0], cmd); + assert_eq!(offset(&app), Some((10, 5)), "the selected pixels float"); + drag(&mut app, [50.0, 40.0], [60.0, 45.0], cmd); + assert_eq!(offset(&app), Some((20, 10)), "a second drag moves the same floating piece"); + app.run("select.drop", json!({})).unwrap(); + assert!(alpha(&app, id, 10, 10) == 0.0 && alpha(&app, id, 40, 30) == 1.0, "the red square moved"); + assert_eq!(alpha(&app, id, 48, 16), 1.0, "the unselected blue one stayed"); +} + +/// A click moves nothing and leaves nothing floating (Undo isn't spent putting it back). +#[test] +fn a_click_with_a_selection_moves_nothing() { + let (mut app, id) = selected_pixels(8); + let steps = app.session.active().unwrap().history.past_len(); + drag(&mut app, [16.0, 16.0], [16.0, 16.0], egui::Modifiers::NONE); + assert_eq!(offset(&app), None); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + assert!(alpha(&app, id, 10, 10) == 1.0 && alpha(&app, id, 48, 16) == 1.0); +} + +#[test] +fn arrow_keys_nudge_the_selected_pixels() { + let (mut app, id) = selected_pixels(16); + crate::move_mods::nudge(&mut app, 10.0, 0.0, false); + crate::move_mods::nudge(&mut app, 0.0, 1.0, false); + assert_eq!(offset(&app), Some((10, 1))); + // ⌥ leaves the piece where it is and nudges a copy of it. + crate::move_mods::nudge(&mut app, 1.0, 0.0, true); + assert_eq!(offset(&app), Some((1, 0))); + app.run("select.drop", json!({})).unwrap(); + assert!(alpha(&app, id, 10, 10) == 0.0 && alpha(&app, id, 18, 20) == 1.0 && alpha(&app, id, 34, 20) == 1.0); + assert_eq!(alpha(&app, id, 48, 16), 1.0, "the layer itself didn't move"); +} + +/// Without floatable pixels (a position-locked layer) the Move tool behaves as without a +/// selection: it moves the layer, which the lock refuses. +#[test] +fn a_layer_that_cannot_float_moves_whole_as_before() { + let (mut app, id) = selected_pixels(8); + app.session.execute("layer.lockLayers", json!({"position": true})).unwrap(); + drag(&mut app, [16.0, 16.0], [26.0, 16.0], egui::Modifiers::NONE); + assert_eq!(offset(&app), None); + assert!(alpha(&app, id, 10, 10) == 1.0 && alpha(&app, id, 30, 16) == 0.0, "nothing moved"); + // Without a selection the layer moves whole. + app.session.execute("layer.lockLayers", json!({"position": false})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + drag(&mut app, [16.0, 16.0], [26.0, 16.0], egui::Modifiers::NONE); + assert!(alpha(&app, id, 10, 10) == 0.0 && alpha(&app, id, 58, 16) == 1.0, "the whole layer moved"); +} + +#[test] +fn floating_selection_does_not_snap_to_its_own_starting_outline_or_preview_at_zero() { + let (mut app, _id) = selected_pixels(8); + app.ui.extras.snap = true; + app.ui.view.snap_to.document_bounds = false; + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 16.0, y: 16.0, pressure: 1.0 }, m); + assert!(super::display_doc(&mut app, 0).is_none(), "no preview composite at offset (0, 0) before the pointer moves"); + // A small 2 px move within the snap radius must move immediately instead of snapping back to (0, 0). + crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 18.0, y: 17.0, pressure: 1.0 }, m); + assert_eq!(super::floating_offset(&app), Some((2, 1)), "small drag moves without snapping to own selection bounds"); + assert!(super::display_doc(&mut app, 0).is_some(), "preview is shown once offset is non-zero"); + crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 18.0, y: 17.0 }, m); + assert_eq!(offset(&app), Some((2, 1))); +} From 4db2c14464ec81be48e0433c626ff99f6e51b9cf Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:51 +0000 Subject: [PATCH 068/259] refactor(ui-egui): move menus.rs tests to menus/tests.rs --- crates/ui-egui/src/menus.rs | 539 +----------------------------- crates/ui-egui/src/menus/tests.rs | 530 +++++++++++++++++++++++++++++ 2 files changed, 531 insertions(+), 538 deletions(-) create mode 100644 crates/ui-egui/src/menus/tests.rs diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 07df45a66a..3179a81422 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1678,544 +1678,7 @@ pub fn apply_workspace(app: &mut PhotocraftApp) { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn showing_grid_restores_hidden_extras() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.ui.extras.grid = false; - app.ui.view.extras = false; - - assert_eq!(invoke(&mut app, &ctx, "view.show.grid", json!({})).unwrap(), json!(true)); - assert_eq!(checked(&app, "view.show.grid"), Some(true)); - assert!(app.ui.view.extras, "showing Grid must make the overlay visible when Extras was hidden"); - - assert_eq!(invoke(&mut app, &ctx, "view.show.grid", json!({})).unwrap(), json!(false)); - assert!(!app.ui.extras.grid); - assert!(app.ui.view.extras); - - app.ui.extras.grid = true; - app.ui.view.extras = false; - assert_eq!(invoke(&mut app, &ctx, "view.show.grid", json!({})).unwrap(), json!(false)); - assert!(!app.ui.view.extras, "hiding Grid must leave hidden Extras alone"); - } - - #[test] - fn sync_with_system_menu_keeps_saved_slots_and_its_checkmark_across_palettes() { - use photocraft_engine::prefs::{AppearanceMode, DarkTheme, LightTheme}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.services.system_theme = Some(Box::new(|_| Some(egui::Theme::Light))); - app.run("prefs.set", json!({"values": {"interface.darkTheme": "studio", "interface.lightTheme": "classic"}})).unwrap(); - invoke(&mut app, &ctx, "window.theme.system", json!({})).unwrap(); - assert_eq!(app.session.prefs().interface.appearance_mode, AppearanceMode::Auto); - assert_eq!(app.session.prefs().interface.dark_theme, DarkTheme::Studio); - assert_eq!(app.session.prefs().interface.light_theme, LightTheme::Classic); - assert_eq!(app.ui.theme, crate::theme::ThemeKind::Classic); - for appearance in [egui::Theme::Dark, egui::Theme::Light] { - app.services.system_theme = Some(Box::new(move |_| Some(appearance))); - crate::prefs_ui::tick(&mut app, &ctx); - let items = menu_items(&app); - let item = items.iter().find(|i| i.id == "window.theme.system").unwrap(); - assert_eq!(item.label, "Sync with system"); - assert_eq!(item.path, ["Window", "Theme"]); - assert!(item.enabled); - assert_eq!(item.checked, Some(true)); - for kind in crate::theme::ThemeKind::ALL { - assert_eq!(checked(&app, &format!("window.theme.{}", kind.id())), Some(false)); - } - } - invoke(&mut app, &ctx, "window.theme.studio", json!({})).unwrap(); - assert_eq!(app.session.prefs().interface.appearance_mode, AppearanceMode::Dark); - assert_eq!(checked(&app, "window.theme.system"), Some(false)); - assert_eq!(checked(&app, "window.theme.studio"), Some(true)); - } - - #[test] - fn submenu_header_is_disabled_when_every_item_is() { - let item = |label: &str, enabled: bool| MenuItem { - id: label.into(), - label: label.into(), - path: vec!["File".into(), "Export".into()], - shortcut: None, - enabled, - checked: None, - color: None, - }; - let (off, on, sep) = (item("Off", false), item("On", true), item("---", true)); - assert!(!submenu_enabled(&[])); - assert!(!submenu_enabled(&[&off, &sep])); - assert!(submenu_enabled(&[&off, &on])); - } - - #[test] - fn live_lookup_finds_engine_and_shell_commands() { - for command in photocraft_engine::commands::command_specs() { - assert!(is_live(command.id), "{}", command.id); - } - for &(id, ..) in UI_COMMANDS { - assert!(is_live(id), "{id}"); - } - for id in ["", "missing.command", "💾"] { - assert!(!is_live(id)); - } - } - - #[test] - fn select_menu_contains_every_selection_context_action_and_more() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.run("select.rect", json!({"x": 2, "y": 2, "width": 8, "height": 8})).unwrap(); - let items = menu_items(&app); - let top: Vec<_> = items.iter().filter(|i| i.path.len() == 1 && i.path.first().is_some_and(|p| p == "Select")).collect(); - // The context menus' Select actions live somewhere under Select (Feather stays in Select > - // Modify, as in the reference menus). Make Work Path is a Paths panel action. - let select: Vec<_> = items.iter().filter(|i| i.path.first().is_some_and(|p| p == "Select")).collect(); - let rows = crate::canvas_tool_menu::SELECTION_MENU.iter().chain(crate::canvas_tool_menu::NO_SELECTION_MENU).flatten(); - for &(label, id) in rows.filter(|(_, id)| id.starts_with("select.") && *id != "select.toWorkPath") { - assert!(select.iter().any(|i| i.id == id), "Select menu missing {label} ({id})"); - } - assert!(top.iter().any(|i| i.id == "select.all")); - assert!(top.iter().any(|i| i.id == "select.colorRange")); - assert!( - items.iter().any(|i| i.id == "select.modify.feather" && i.path.iter().map(String::as_str).eq(["Select", "Modify"])), - "keep the Photoshop Modify route" - ); - assert!(!top.iter().any(|i| i.id == "select.modify.feather"), "no extra top-level Feather"); - } - - /// Color to Alpha (#1576) has no Photoshop counterpart: it joins Photoshop's own Filter › - /// Other submenu (not a second "Other") right after Offset, enabled on a pixel layer. - #[test] - fn color_to_alpha_sits_in_filter_other_after_offset() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - let items = menu_items(&app); - let at = |id: &str| items.iter().position(|i| i.id == id).unwrap_or_else(|| panic!("{id} missing")); - let (offset, c2a) = (at("filter.other.offset"), at("filter.other.colorToAlpha")); - assert_eq!(c2a, offset + 1); - assert_eq!(items[c2a].path, items[offset].path); - assert_eq!(items[c2a].label, "Color to Alpha…"); - assert!(items[c2a].enabled, "the Background becomes a layer when the filter runs"); - let others: Vec<_> = items.iter().filter(|i| i.path.first().is_some_and(|p| p == "Filter") && i.path.len() == 2).map(|i| &i.path[1]).collect(); - assert!(!others.iter().any(|p| p.as_str() == "Other"), "no duplicate Other submenu: {others:?}"); - } - - #[test] - fn menu_bar_labels_have_horizontal_padding_and_open_menus() { - use egui_kittest::{Harness, kittest::Queryable}; - - for theme in crate::theme::ThemeKind::ALL { - for width in [640.0, 1440.0] { - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut harness = Harness::builder().with_size(egui::vec2(width, 200.0)).build_ui_state( - |ui, app| { - menu_bar(app, ui); - }, - app, - ); - PhotocraftApp::setup_context(&harness.ctx, theme); - harness.run_steps(3); - - let font = egui::TextStyle::Button.resolve(&harness.ctx.global_style()); - let mut right = 0.0; - for label in TOP_MENUS { - let rect = harness.get_by_label(label).rect(); - let text_width = harness.ctx.fonts_mut(|fonts| fonts.layout_no_wrap(label.into(), font.clone(), egui::Color32::WHITE).size().x); - assert!(rect.width() >= text_width + 11.5, "{theme:?}: {label} lacks horizontal padding"); - assert!(rect.left() >= right && rect.right() <= width, "{theme:?}: {label} overlaps or overflows at width {width}"); - right = rect.right(); - } - - harness.get_by_label("File").click(); - harness.run_steps(3); - assert!(harness.query_by_label_contains("Open…").is_some(), "{theme:?}: File menu did not open"); - } - } - } - - #[test] - fn overlapped_menu_title_does_not_receive_hover_switching() { - let ctx = egui::Context::default(); - let mut title: Option = None; - let p = egui::pos2(90.0, 12.0); - let mut reaches = true; - // The popup area becomes hit-testable once egui has laid it out, so draw a few frames. - for _ in 0..3 { - let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0))), ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| { - let ctx = &ui.ctx().clone(); - egui::CentralPanel::default().show(ui, |ui| { - let (rect, _) = ui.allocate_exact_size(egui::vec2(80.0, 24.0), egui::Sense::hover()); - let shifted = rect.translate(egui::vec2(p.x - rect.center().x, p.y - rect.center().y)); - let response = ui.interact(shifted, egui::Id::unique("menu-title-test"), egui::Sense::hover()); - title = Some(response); - }); - egui::Area::new(egui::Id::unique("overlapping-popup-test")).order(egui::Order::Foreground).fixed_pos(p - egui::vec2(10.0, 10.0)).show( - ctx, - |ui| { - ui.allocate_space(egui::vec2(20.0, 20.0)); - }, - ); - let response = title.as_ref().unwrap(); - reaches = pointer_reaches_title(ctx, response, p); - }); - out.textures_delta.clear(); - } - assert!(!reaches); - } - - /// #7702: a pointer at the very top edge of the screen (the window maximized) moving between - /// titles switches the open menu, as it does a little lower. - #[test] - fn hovering_a_title_at_the_screen_edge_switches_the_open_menu() { - use egui_kittest::{Harness, kittest::Queryable}; - - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut harness = Harness::builder().with_size(egui::vec2(1200.0, 700.0)).build_ui_state( - |ui, app| { - egui::Frame::NONE.inner_margin(egui::Margin { top: 4, ..Default::default() }).show(ui, |ui| { - menu_bar(app, ui); - }); - }, - app, - ); - PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); - harness.run_steps(3); - harness.get_by_label("File").click(); - harness.run_steps(3); - assert!(harness.query_by_label_contains("Open…").is_some()); - let image = harness.get_by_label("Image").rect(); - assert!(image.top() > 0.0, "the title sits below the screen edge"); - harness.hover_at(egui::pos2(image.center().x, 0.0)); - harness.run_steps(4); - assert!(harness.query_by_label_contains("Open…").is_none(), "File menu should close"); - assert!(harness.query_by_label_contains("Duplicate…").is_some(), "Image menu should open from the screen edge"); - } - - #[test] - fn hovering_another_title_switches_the_open_menu() { - use egui_kittest::{Harness, kittest::Queryable}; - - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut harness = Harness::builder().with_size(egui::vec2(1200.0, 700.0)).build_ui_state( - |ui, app| { - menu_bar(app, ui); - }, - app, - ); - PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); - harness.run_steps(3); - // Nothing open: hovering a title does not open it. - harness.get_by_label("Image").hover(); - harness.run_steps(3); - assert!(harness.query_by_label_contains("Open…").is_none() && harness.query_by_label_contains("Duplicate…").is_none()); - harness.get_by_label("File").click(); - harness.run_steps(3); - assert!(harness.query_by_label_contains("Open…").is_some()); - harness.get_by_label("Image").hover(); - harness.run_steps(4); - assert!(harness.query_by_label_contains("Open…").is_none(), "File menu should close"); - assert!(harness.query_by_label_contains("Duplicate…").is_some(), "Image menu should open on hover"); - } - - /// An open menu reuses its items between frames (building them costs far more than a frame on - /// a document with thousands of layers), rebuilds them when the state changes under it, and - /// keeps nothing once it closes. - #[test] - fn an_open_menu_reuses_its_items_until_the_state_changes() { - use egui_kittest::{Harness, kittest::Queryable}; - - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut harness = Harness::builder().with_size(egui::vec2(1200.0, 700.0)).build_ui_state( - |ui, app| { - menu_bar(app, ui); - }, - app, - ); - PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); - harness.run_steps(3); - assert!(harness.state().menu_cache.is_none(), "no menu open, nothing built"); - harness.get_by_label("File").click(); - harness.run_steps(3); - // The same allocation frame after frame: the items were not rebuilt. - let built = |app: &PhotocraftApp| app.menu_cache.as_ref().map(|c| c.items.as_ptr()); - let close = |app: &PhotocraftApp| app.menu_cache.as_ref().and_then(|c| c.items.iter().find(|i| i.id == "file.close")).map(|i| i.enabled); - let first = built(harness.state()); - assert!(first.is_some()); - assert_eq!(close(harness.state()), Some(false)); - harness.run_steps(3); - assert_eq!(built(harness.state()), first); - // A document opened under the open menu (a job ending, an agent): the items follow. - harness.state_mut().run("file.new", json!({"width": 8, "height": 8})).unwrap(); - harness.run_steps(1); - assert_eq!(close(harness.state()), Some(true)); - harness.key_press(egui::Key::Escape); - harness.run_steps(3); - assert!(harness.state().menu_cache.is_none(), "closed, nothing kept"); - } - - #[test] - fn help_search_finds_commands_by_any_word() { - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let items = menu_items(&app); - let ids = |q: &str| search_items(&items, q, crate::i18n::Lang::EN).iter().map(|i| i.id.clone()).collect::>(); - let di = ids("DI"); - assert!(di.contains(&"edit.transform.distort".to_string()), "{di:?}"); - assert!(di.len() <= HELP_SEARCH_MAX); - // A word inside the label matches too, and a label match outranks a path-only match. - assert!(ids("selection").contains(&"select.transformSelection".to_string())); - assert_eq!(search_rank("dis", "Distort", &[]), Some(0)); - assert_eq!(search_rank("sel", "Transform Selection", &[]), Some(1)); - assert_eq!(search_rank("orm", "Transform Selection", &[]), Some(2)); - assert_eq!(search_rank("trans", "Distort", &["Edit".into(), "Transform".into()]), Some(3)); - assert!(ids(" ").is_empty()); - assert!(ids("zzzzqqq").is_empty()); - } - - /// In another UI language both the translated and the English names match. - #[test] - fn help_search_matches_the_ui_language_and_english() { - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let items = menu_items(&app); - let Some(fr) = crate::i18n::Lang::from_code("fr") else { return }; - let ids = |q: &str| search_items(&items, q, fr).iter().map(|i| i.id.clone()).collect::>(); - assert!(!ids(&crate::i18n::tr(fr, "Layer").to_lowercase()).is_empty(), "French menu name"); - assert!(ids("distort").contains(&"edit.transform.distort".to_string()), "English still matches"); - assert!(ids("zzzzqqq").is_empty()); - } - - /// #1447, #1438: a click on Help leaves its search field focused, so typing searches at once, - /// and clicking into the field and typing keeps the menu open. Whole app, real clicks (press - /// and release in separate frames), with the custom title bar (Windows, Linux) and without. - #[test] - fn help_search_takes_typing_and_clicks_without_closing_the_menu() { - use egui::{Event, Modifiers, PointerButton}; - use egui_kittest::{Harness, kittest::Queryable}; - for (custom, doc, scale) in [(true, false, 1.0), (true, true, 1.25), (false, true, 1.5)] { - let what = format!("custom title bar {custom}, document {doc}, scale {scale}"); - let mut h = Harness::builder().with_size(egui::vec2(1200.0 / scale, 800.0 / scale)).with_pixels_per_point(scale).with_max_steps(64).build_eframe( - move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ALL[0]); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.custom_titlebar = custom; - if doc { - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - } - app - }, - ); - h.run_steps(4); - let click = |h: &mut Harness<'_, PhotocraftApp>, at: egui::Pos2| { - h.event(Event::PointerMoved(at)); - h.run_steps(1); - h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(3); - }; - let typing = |h: &mut Harness<'_, PhotocraftApp>, text: &str| { - for c in text.chars() { - h.event(Event::Text(c.to_string())); - h.run_steps(1); - } - h.run_steps(3); - }; - let open = |h: &Harness<'_, PhotocraftApp>| h.query_by_label_contains("About PhotoCraft").is_some(); - let field_id = egui::Id::unique("help-menu-search").with("field"); - let help = h.get_by_label("Help").rect().center(); - click(&mut h, help); - assert!(open(&h), "Help opened ({what})"); - assert_eq!(h.ctx.memory(|m| m.focused()), Some(field_id), "the click on Help leaves the search field focused ({what})"); - typing(&mut h, "lev"); - assert!(open(&h), "typing keeps Help open ({what})"); - assert!(h.query_all_by_label_contains("› Levels").next().is_some(), "typing right away searches ({what})"); - let field = h.query_all_by_role(egui::accesskit::Role::TextInput).find(|n| n.is_focused()).map(|n| n.rect().center()); - let field = field.unwrap_or_else(|| panic!("the search field is in the accessibility tree ({what})")); - click(&mut h, field); - assert!(open(&h), "clicking the search field keeps Help open ({what})"); - assert_eq!(h.ctx.memory(|m| m.focused()), Some(field_id), "and focused ({what})"); - typing(&mut h, "els"); - assert!(open(&h), "typing after the click keeps Help open ({what})"); - assert!(h.query_all_by_label_contains("› Levels").next().is_some(), "and lists the matches ({what})"); - } - } - - /// #5996: a real key press comes as a key and its text. A letter typed into Help › Search is - /// text for the field, not a mnemonic: "S" ran System Info and "A" the ArtCraft website. - #[test] - fn help_search_letters_are_not_mnemonics() { - use egui::{Event, Key, Modifiers, PointerButton}; - use egui_kittest::{Harness, kittest::Queryable}; - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(|cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ALL[0]); - PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()) - }); - h.run_steps(4); - let help = h.get_by_label("Help").rect().center(); - h.event(Event::PointerMoved(help)); - h.run_steps(1); - for pressed in [true, false] { - h.event(Event::PointerButton { pos: help, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); - h.run_steps(1); - } - h.run_steps(3); - assert!(h.query_by_label_contains("About PhotoCraft").is_some(), "Help opened"); - for c in "DeSelect all".chars() { - let key = Key::from_name(&c.to_ascii_uppercase().to_string()); - if let Some(key) = key { - h.event(Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }); - } - h.event(Event::Text(c.to_string())); - h.run_steps(1); - if let Some(key) = key { - h.event(Event::Key { key, physical_key: Some(key), pressed: false, repeat: false, modifiers: Modifiers::NONE }); - } - } - h.run_steps(3); - assert!(h.query_by_label_contains("About PhotoCraft").is_some(), "typing keeps Help open"); - let query: String = h.ctx.data(|d| d.get_temp(egui::Id::unique("help-menu-search"))).unwrap_or_default(); - assert_eq!(query, "DeSelect all", "every letter reached the field"); - assert!(h.state().ui.dialogs.is_empty(), "no menu command ran: {:?}", h.state().ui.dialogs); - } - - #[test] - fn dropdown_items_have_room() { - use egui_kittest::{Harness, kittest::Queryable}; - - for theme in crate::theme::ThemeKind::ALL { - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut harness = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( - |ui, app| { - menu_bar(app, ui); - }, - app, - ); - PhotocraftApp::setup_context(&harness.ctx, theme); - harness.run_steps(3); - harness.get_by_label("File").click(); - harness.run_steps(3); - let a = harness.get_by_label_contains("New…").rect(); - let b = harness.get_by_label_contains("Open…").rect(); - let font = egui::TextStyle::Button.resolve(&harness.ctx.global_style()).size; - assert!(a.height() >= font + 8.0, "{theme:?}: item height {} for a {font} pt font", a.height()); - assert!(b.top() - a.top() >= font + 10.0, "{theme:?}: rows {} apart", b.top() - a.top()); - // #402: rows touch (no dialog spacing between them), so long menus fit the window. - let next = harness.get_by_label_contains("New from Clipboard").rect(); - assert!((next.top() - a.bottom()).abs() < 0.5, "{theme:?}: {} pt between rows", next.top() - a.bottom()); - assert!(next.top() - a.top() <= 24.5, "{theme:?}: rows {} apart", next.top() - a.top()); - } - } - - #[test] - fn menu_level_height_is_bounded_by_viewport() { - use egui_kittest::Harness; - - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut harness = Harness::builder().with_size(egui::vec2(900.0, 240.0)).build_ui_state( - |ui, app| { - menu_bar(app, ui); - }, - app, - ); - PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); - harness.run_steps(3); - // Opening a top-level menu with many entries must not grow its popup past the viewport. - use egui_kittest::kittest::Queryable; - harness.get_by_label("Filter").click(); - harness.run_steps(3); - let viewport = harness.ctx.content_rect(); - let max_bottom = harness - .ctx - .memory(|m| m.areas().visible_layer_ids()) - .into_iter() - .filter_map(|layer| harness.ctx.memory(|m| m.area_rect(layer.id))) - .map(|r| r.bottom()) - .fold(viewport.top(), f32::max); - assert!(max_bottom <= viewport.bottom() + 1.0, "menu popup overflowed viewport: {max_bottom} > {}", viewport.bottom()); - } - - #[test] - fn tall_menu_scrolls_with_mouse_wheel_on_short_display() { - use egui_kittest::{Harness, kittest::Queryable}; - - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut harness = Harness::builder().with_size(egui::vec2(900.0, 220.0)).build_ui_state( - |ui, app| { - menu_bar(app, ui); - }, - app, - ); - PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); - harness.run_steps(3); - harness.get_by_label("Filter").click(); - harness.run_steps(3); - - let item = harness.get_by_label_contains("Filter Gallery…"); - let before = item.rect().top(); - harness.hover_at(item.rect().center()); - harness.event(egui::Event::MouseWheel { - source: egui::MouseWheelSource::Unknown, - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, -80.0), - phase: egui::TouchPhase::Move, - modifiers: egui::Modifiers::NONE, - }); - harness.run_steps(4); - - let after = harness.get_by_label_contains("Filter Gallery…").rect().top(); - assert!(after < before - 1.0, "mouse wheel should move tall menu content: {before} -> {after}"); - } - - #[test] - fn window_panel_and_workspace_ids_drive_the_shell() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - assert!(!app.ui.panels.history); - invoke(&mut app, &ctx, "window.panel.history", Value::Null).unwrap(); - assert!(app.ui.panels.history); - assert_eq!(checked(&app, "window.panel.history"), Some(true)); - invoke(&mut app, &ctx, "window.workspace.painting", Value::Null).unwrap(); - assert_eq!(app.ui.workspace, "Painting"); - assert!(!app.ui.panels.properties); - assert_eq!(checked(&app, "window.workspace.painting"), Some(true)); - invoke(&mut app, &ctx, "window.workspace.essentials", Value::Null).unwrap(); - assert!(app.ui.panels.properties); - // Live in the menu, and no duplicate "Layers" entry from the window.toggle.* commands. - let items = menu_items(&app); - assert!(items.iter().any(|i| i.id == "window.panel.layers" && i.enabled)); - assert_eq!(items.iter().filter(|i| i.path == ["Window"] && i.label == "Layers").count(), 1); - assert!(items.iter().any(|i| i.id == "edit.stroke")); - } - - #[test] - fn proof_setup_presets_and_checkmarks() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - app.sync_views(); - assert_eq!(checked(&app, "view.proofColors"), Some(false)); - invoke(&mut app, &ctx, "view.proofSetup.workingCmyk", Value::Null).unwrap(); - assert_eq!(checked(&app, "view.proofColors"), Some(true)); - invoke(&mut app, &ctx, "view.gamutWarning", json!({"on": true})).unwrap(); - assert_eq!(checked(&app, "view.gamutWarning"), Some(true)); - let doc = app.session.active().unwrap().doc.clone(); - let lut = app.session.color.canvas_lut(&doc, 9).unwrap().unwrap(); - assert_eq!(lut.len(), 9 * 9 * 9 * 4); - // Pure sRGB green is outside coated CMYK; mid grey is inside. - let at = |r: usize, g: usize, b: usize| lut[(r + g * 9 + b * 81) * 4 + 3]; - assert_eq!((at(0, 8, 0), at(4, 4, 4)), (255, 0)); - // Custom… opens the generated Proof Setup dialog with a profile choice. - assert!(invoke(&mut app, &ctx, "view.proofSetup.custom", Value::Null).unwrap()["dialog"].is_u64()); - let spec = photocraft_engine::commands::find("edit.convertToProfile").unwrap(); - let params = crate::filter_dialog::parse_spec(spec.params); - assert!( - matches!(¶ms[0].kind, crate::filter_dialog::Kind::Choice { options, .. } if options[0] == "srgb" && !options.iter().any(|v| v.contains('/'))) - ); - } -} +mod tests; #[cfg(test)] mod open_recent_tests { diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs new file mode 100644 index 0000000000..2527b0fc3f --- /dev/null +++ b/crates/ui-egui/src/menus/tests.rs @@ -0,0 +1,530 @@ +use super::*; + +#[test] +fn showing_grid_restores_hidden_extras() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.ui.extras.grid = false; + app.ui.view.extras = false; + + assert_eq!(invoke(&mut app, &ctx, "view.show.grid", json!({})).unwrap(), json!(true)); + assert_eq!(checked(&app, "view.show.grid"), Some(true)); + assert!(app.ui.view.extras, "showing Grid must make the overlay visible when Extras was hidden"); + + assert_eq!(invoke(&mut app, &ctx, "view.show.grid", json!({})).unwrap(), json!(false)); + assert!(!app.ui.extras.grid); + assert!(app.ui.view.extras); + + app.ui.extras.grid = true; + app.ui.view.extras = false; + assert_eq!(invoke(&mut app, &ctx, "view.show.grid", json!({})).unwrap(), json!(false)); + assert!(!app.ui.view.extras, "hiding Grid must leave hidden Extras alone"); +} + +#[test] +fn sync_with_system_menu_keeps_saved_slots_and_its_checkmark_across_palettes() { + use photocraft_engine::prefs::{AppearanceMode, DarkTheme, LightTheme}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.services.system_theme = Some(Box::new(|_| Some(egui::Theme::Light))); + app.run("prefs.set", json!({"values": {"interface.darkTheme": "studio", "interface.lightTheme": "classic"}})).unwrap(); + invoke(&mut app, &ctx, "window.theme.system", json!({})).unwrap(); + assert_eq!(app.session.prefs().interface.appearance_mode, AppearanceMode::Auto); + assert_eq!(app.session.prefs().interface.dark_theme, DarkTheme::Studio); + assert_eq!(app.session.prefs().interface.light_theme, LightTheme::Classic); + assert_eq!(app.ui.theme, crate::theme::ThemeKind::Classic); + for appearance in [egui::Theme::Dark, egui::Theme::Light] { + app.services.system_theme = Some(Box::new(move |_| Some(appearance))); + crate::prefs_ui::tick(&mut app, &ctx); + let items = menu_items(&app); + let item = items.iter().find(|i| i.id == "window.theme.system").unwrap(); + assert_eq!(item.label, "Sync with system"); + assert_eq!(item.path, ["Window", "Theme"]); + assert!(item.enabled); + assert_eq!(item.checked, Some(true)); + for kind in crate::theme::ThemeKind::ALL { + assert_eq!(checked(&app, &format!("window.theme.{}", kind.id())), Some(false)); + } + } + invoke(&mut app, &ctx, "window.theme.studio", json!({})).unwrap(); + assert_eq!(app.session.prefs().interface.appearance_mode, AppearanceMode::Dark); + assert_eq!(checked(&app, "window.theme.system"), Some(false)); + assert_eq!(checked(&app, "window.theme.studio"), Some(true)); +} + +#[test] +fn submenu_header_is_disabled_when_every_item_is() { + let item = |label: &str, enabled: bool| MenuItem { + id: label.into(), + label: label.into(), + path: vec!["File".into(), "Export".into()], + shortcut: None, + enabled, + checked: None, + color: None, + }; + let (off, on, sep) = (item("Off", false), item("On", true), item("---", true)); + assert!(!submenu_enabled(&[])); + assert!(!submenu_enabled(&[&off, &sep])); + assert!(submenu_enabled(&[&off, &on])); +} + +#[test] +fn live_lookup_finds_engine_and_shell_commands() { + for command in photocraft_engine::commands::command_specs() { + assert!(is_live(command.id), "{}", command.id); + } + for &(id, ..) in UI_COMMANDS { + assert!(is_live(id), "{id}"); + } + for id in ["", "missing.command", "💾"] { + assert!(!is_live(id)); + } +} + +#[test] +fn select_menu_contains_every_selection_context_action_and_more() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("select.rect", json!({"x": 2, "y": 2, "width": 8, "height": 8})).unwrap(); + let items = menu_items(&app); + let top: Vec<_> = items.iter().filter(|i| i.path.len() == 1 && i.path.first().is_some_and(|p| p == "Select")).collect(); + // The context menus' Select actions live somewhere under Select (Feather stays in Select > + // Modify, as in the reference menus). Make Work Path is a Paths panel action. + let select: Vec<_> = items.iter().filter(|i| i.path.first().is_some_and(|p| p == "Select")).collect(); + let rows = crate::canvas_tool_menu::SELECTION_MENU.iter().chain(crate::canvas_tool_menu::NO_SELECTION_MENU).flatten(); + for &(label, id) in rows.filter(|(_, id)| id.starts_with("select.") && *id != "select.toWorkPath") { + assert!(select.iter().any(|i| i.id == id), "Select menu missing {label} ({id})"); + } + assert!(top.iter().any(|i| i.id == "select.all")); + assert!(top.iter().any(|i| i.id == "select.colorRange")); + assert!( + items.iter().any(|i| i.id == "select.modify.feather" && i.path.iter().map(String::as_str).eq(["Select", "Modify"])), + "keep the Photoshop Modify route" + ); + assert!(!top.iter().any(|i| i.id == "select.modify.feather"), "no extra top-level Feather"); +} + +/// Color to Alpha (#1576) has no Photoshop counterpart: it joins Photoshop's own Filter › +/// Other submenu (not a second "Other") right after Offset, enabled on a pixel layer. +#[test] +fn color_to_alpha_sits_in_filter_other_after_offset() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + let items = menu_items(&app); + let at = |id: &str| items.iter().position(|i| i.id == id).unwrap_or_else(|| panic!("{id} missing")); + let (offset, c2a) = (at("filter.other.offset"), at("filter.other.colorToAlpha")); + assert_eq!(c2a, offset + 1); + assert_eq!(items[c2a].path, items[offset].path); + assert_eq!(items[c2a].label, "Color to Alpha…"); + assert!(items[c2a].enabled, "the Background becomes a layer when the filter runs"); + let others: Vec<_> = items.iter().filter(|i| i.path.first().is_some_and(|p| p == "Filter") && i.path.len() == 2).map(|i| &i.path[1]).collect(); + assert!(!others.iter().any(|p| p.as_str() == "Other"), "no duplicate Other submenu: {others:?}"); +} + +#[test] +fn menu_bar_labels_have_horizontal_padding_and_open_menus() { + use egui_kittest::{Harness, kittest::Queryable}; + + for theme in crate::theme::ThemeKind::ALL { + for width in [640.0, 1440.0] { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut harness = Harness::builder().with_size(egui::vec2(width, 200.0)).build_ui_state( + |ui, app| { + menu_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&harness.ctx, theme); + harness.run_steps(3); + + let font = egui::TextStyle::Button.resolve(&harness.ctx.global_style()); + let mut right = 0.0; + for label in TOP_MENUS { + let rect = harness.get_by_label(label).rect(); + let text_width = harness.ctx.fonts_mut(|fonts| fonts.layout_no_wrap(label.into(), font.clone(), egui::Color32::WHITE).size().x); + assert!(rect.width() >= text_width + 11.5, "{theme:?}: {label} lacks horizontal padding"); + assert!(rect.left() >= right && rect.right() <= width, "{theme:?}: {label} overlaps or overflows at width {width}"); + right = rect.right(); + } + + harness.get_by_label("File").click(); + harness.run_steps(3); + assert!(harness.query_by_label_contains("Open…").is_some(), "{theme:?}: File menu did not open"); + } + } +} + +#[test] +fn overlapped_menu_title_does_not_receive_hover_switching() { + let ctx = egui::Context::default(); + let mut title: Option = None; + let p = egui::pos2(90.0, 12.0); + let mut reaches = true; + // The popup area becomes hit-testable once egui has laid it out, so draw a few frames. + for _ in 0..3 { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + let ctx = &ui.ctx().clone(); + egui::CentralPanel::default().show(ui, |ui| { + let (rect, _) = ui.allocate_exact_size(egui::vec2(80.0, 24.0), egui::Sense::hover()); + let shifted = rect.translate(egui::vec2(p.x - rect.center().x, p.y - rect.center().y)); + let response = ui.interact(shifted, egui::Id::unique("menu-title-test"), egui::Sense::hover()); + title = Some(response); + }); + egui::Area::new(egui::Id::unique("overlapping-popup-test")).order(egui::Order::Foreground).fixed_pos(p - egui::vec2(10.0, 10.0)).show(ctx, |ui| { + ui.allocate_space(egui::vec2(20.0, 20.0)); + }); + let response = title.as_ref().unwrap(); + reaches = pointer_reaches_title(ctx, response, p); + }); + out.textures_delta.clear(); + } + assert!(!reaches); +} + +/// #7702: a pointer at the very top edge of the screen (the window maximized) moving between +/// titles switches the open menu, as it does a little lower. +#[test] +fn hovering_a_title_at_the_screen_edge_switches_the_open_menu() { + use egui_kittest::{Harness, kittest::Queryable}; + + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut harness = Harness::builder().with_size(egui::vec2(1200.0, 700.0)).build_ui_state( + |ui, app| { + egui::Frame::NONE.inner_margin(egui::Margin { top: 4, ..Default::default() }).show(ui, |ui| { + menu_bar(app, ui); + }); + }, + app, + ); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + harness.run_steps(3); + harness.get_by_label("File").click(); + harness.run_steps(3); + assert!(harness.query_by_label_contains("Open…").is_some()); + let image = harness.get_by_label("Image").rect(); + assert!(image.top() > 0.0, "the title sits below the screen edge"); + harness.hover_at(egui::pos2(image.center().x, 0.0)); + harness.run_steps(4); + assert!(harness.query_by_label_contains("Open…").is_none(), "File menu should close"); + assert!(harness.query_by_label_contains("Duplicate…").is_some(), "Image menu should open from the screen edge"); +} + +#[test] +fn hovering_another_title_switches_the_open_menu() { + use egui_kittest::{Harness, kittest::Queryable}; + + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut harness = Harness::builder().with_size(egui::vec2(1200.0, 700.0)).build_ui_state( + |ui, app| { + menu_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + harness.run_steps(3); + // Nothing open: hovering a title does not open it. + harness.get_by_label("Image").hover(); + harness.run_steps(3); + assert!(harness.query_by_label_contains("Open…").is_none() && harness.query_by_label_contains("Duplicate…").is_none()); + harness.get_by_label("File").click(); + harness.run_steps(3); + assert!(harness.query_by_label_contains("Open…").is_some()); + harness.get_by_label("Image").hover(); + harness.run_steps(4); + assert!(harness.query_by_label_contains("Open…").is_none(), "File menu should close"); + assert!(harness.query_by_label_contains("Duplicate…").is_some(), "Image menu should open on hover"); +} + +/// An open menu reuses its items between frames (building them costs far more than a frame on +/// a document with thousands of layers), rebuilds them when the state changes under it, and +/// keeps nothing once it closes. +#[test] +fn an_open_menu_reuses_its_items_until_the_state_changes() { + use egui_kittest::{Harness, kittest::Queryable}; + + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut harness = Harness::builder().with_size(egui::vec2(1200.0, 700.0)).build_ui_state( + |ui, app| { + menu_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + harness.run_steps(3); + assert!(harness.state().menu_cache.is_none(), "no menu open, nothing built"); + harness.get_by_label("File").click(); + harness.run_steps(3); + // The same allocation frame after frame: the items were not rebuilt. + let built = |app: &PhotocraftApp| app.menu_cache.as_ref().map(|c| c.items.as_ptr()); + let close = |app: &PhotocraftApp| app.menu_cache.as_ref().and_then(|c| c.items.iter().find(|i| i.id == "file.close")).map(|i| i.enabled); + let first = built(harness.state()); + assert!(first.is_some()); + assert_eq!(close(harness.state()), Some(false)); + harness.run_steps(3); + assert_eq!(built(harness.state()), first); + // A document opened under the open menu (a job ending, an agent): the items follow. + harness.state_mut().run("file.new", json!({"width": 8, "height": 8})).unwrap(); + harness.run_steps(1); + assert_eq!(close(harness.state()), Some(true)); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + assert!(harness.state().menu_cache.is_none(), "closed, nothing kept"); +} + +#[test] +fn help_search_finds_commands_by_any_word() { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let items = menu_items(&app); + let ids = |q: &str| search_items(&items, q, crate::i18n::Lang::EN).iter().map(|i| i.id.clone()).collect::>(); + let di = ids("DI"); + assert!(di.contains(&"edit.transform.distort".to_string()), "{di:?}"); + assert!(di.len() <= HELP_SEARCH_MAX); + // A word inside the label matches too, and a label match outranks a path-only match. + assert!(ids("selection").contains(&"select.transformSelection".to_string())); + assert_eq!(search_rank("dis", "Distort", &[]), Some(0)); + assert_eq!(search_rank("sel", "Transform Selection", &[]), Some(1)); + assert_eq!(search_rank("orm", "Transform Selection", &[]), Some(2)); + assert_eq!(search_rank("trans", "Distort", &["Edit".into(), "Transform".into()]), Some(3)); + assert!(ids(" ").is_empty()); + assert!(ids("zzzzqqq").is_empty()); +} + +/// In another UI language both the translated and the English names match. +#[test] +fn help_search_matches_the_ui_language_and_english() { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let items = menu_items(&app); + let Some(fr) = crate::i18n::Lang::from_code("fr") else { return }; + let ids = |q: &str| search_items(&items, q, fr).iter().map(|i| i.id.clone()).collect::>(); + assert!(!ids(&crate::i18n::tr(fr, "Layer").to_lowercase()).is_empty(), "French menu name"); + assert!(ids("distort").contains(&"edit.transform.distort".to_string()), "English still matches"); + assert!(ids("zzzzqqq").is_empty()); +} + +/// #1447, #1438: a click on Help leaves its search field focused, so typing searches at once, +/// and clicking into the field and typing keeps the menu open. Whole app, real clicks (press +/// and release in separate frames), with the custom title bar (Windows, Linux) and without. +#[test] +fn help_search_takes_typing_and_clicks_without_closing_the_menu() { + use egui::{Event, Modifiers, PointerButton}; + use egui_kittest::{Harness, kittest::Queryable}; + for (custom, doc, scale) in [(true, false, 1.0), (true, true, 1.25), (false, true, 1.5)] { + let what = format!("custom title bar {custom}, document {doc}, scale {scale}"); + let mut h = + Harness::builder().with_size(egui::vec2(1200.0 / scale, 800.0 / scale)).with_pixels_per_point(scale).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ALL[0]); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.custom_titlebar = custom; + if doc { + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + } + app + }); + h.run_steps(4); + let click = |h: &mut Harness<'_, PhotocraftApp>, at: egui::Pos2| { + h.event(Event::PointerMoved(at)); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + }; + let typing = |h: &mut Harness<'_, PhotocraftApp>, text: &str| { + for c in text.chars() { + h.event(Event::Text(c.to_string())); + h.run_steps(1); + } + h.run_steps(3); + }; + let open = |h: &Harness<'_, PhotocraftApp>| h.query_by_label_contains("About PhotoCraft").is_some(); + let field_id = egui::Id::unique("help-menu-search").with("field"); + let help = h.get_by_label("Help").rect().center(); + click(&mut h, help); + assert!(open(&h), "Help opened ({what})"); + assert_eq!(h.ctx.memory(|m| m.focused()), Some(field_id), "the click on Help leaves the search field focused ({what})"); + typing(&mut h, "lev"); + assert!(open(&h), "typing keeps Help open ({what})"); + assert!(h.query_all_by_label_contains("› Levels").next().is_some(), "typing right away searches ({what})"); + let field = h.query_all_by_role(egui::accesskit::Role::TextInput).find(|n| n.is_focused()).map(|n| n.rect().center()); + let field = field.unwrap_or_else(|| panic!("the search field is in the accessibility tree ({what})")); + click(&mut h, field); + assert!(open(&h), "clicking the search field keeps Help open ({what})"); + assert_eq!(h.ctx.memory(|m| m.focused()), Some(field_id), "and focused ({what})"); + typing(&mut h, "els"); + assert!(open(&h), "typing after the click keeps Help open ({what})"); + assert!(h.query_all_by_label_contains("› Levels").next().is_some(), "and lists the matches ({what})"); + } +} + +/// #5996: a real key press comes as a key and its text. A letter typed into Help › Search is +/// text for the field, not a mnemonic: "S" ran System Info and "A" the ArtCraft website. +#[test] +fn help_search_letters_are_not_mnemonics() { + use egui::{Event, Key, Modifiers, PointerButton}; + use egui_kittest::{Harness, kittest::Queryable}; + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ALL[0]); + PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()) + }); + h.run_steps(4); + let help = h.get_by_label("Help").rect().center(); + h.event(Event::PointerMoved(help)); + h.run_steps(1); + for pressed in [true, false] { + h.event(Event::PointerButton { pos: help, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(1); + } + h.run_steps(3); + assert!(h.query_by_label_contains("About PhotoCraft").is_some(), "Help opened"); + for c in "DeSelect all".chars() { + let key = Key::from_name(&c.to_ascii_uppercase().to_string()); + if let Some(key) = key { + h.event(Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: Modifiers::NONE }); + } + h.event(Event::Text(c.to_string())); + h.run_steps(1); + if let Some(key) = key { + h.event(Event::Key { key, physical_key: Some(key), pressed: false, repeat: false, modifiers: Modifiers::NONE }); + } + } + h.run_steps(3); + assert!(h.query_by_label_contains("About PhotoCraft").is_some(), "typing keeps Help open"); + let query: String = h.ctx.data(|d| d.get_temp(egui::Id::unique("help-menu-search"))).unwrap_or_default(); + assert_eq!(query, "DeSelect all", "every letter reached the field"); + assert!(h.state().ui.dialogs.is_empty(), "no menu command ran: {:?}", h.state().ui.dialogs); +} + +#[test] +fn dropdown_items_have_room() { + use egui_kittest::{Harness, kittest::Queryable}; + + for theme in crate::theme::ThemeKind::ALL { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut harness = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( + |ui, app| { + menu_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&harness.ctx, theme); + harness.run_steps(3); + harness.get_by_label("File").click(); + harness.run_steps(3); + let a = harness.get_by_label_contains("New…").rect(); + let b = harness.get_by_label_contains("Open…").rect(); + let font = egui::TextStyle::Button.resolve(&harness.ctx.global_style()).size; + assert!(a.height() >= font + 8.0, "{theme:?}: item height {} for a {font} pt font", a.height()); + assert!(b.top() - a.top() >= font + 10.0, "{theme:?}: rows {} apart", b.top() - a.top()); + // #402: rows touch (no dialog spacing between them), so long menus fit the window. + let next = harness.get_by_label_contains("New from Clipboard").rect(); + assert!((next.top() - a.bottom()).abs() < 0.5, "{theme:?}: {} pt between rows", next.top() - a.bottom()); + assert!(next.top() - a.top() <= 24.5, "{theme:?}: rows {} apart", next.top() - a.top()); + } +} + +#[test] +fn menu_level_height_is_bounded_by_viewport() { + use egui_kittest::Harness; + + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut harness = Harness::builder().with_size(egui::vec2(900.0, 240.0)).build_ui_state( + |ui, app| { + menu_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + harness.run_steps(3); + // Opening a top-level menu with many entries must not grow its popup past the viewport. + use egui_kittest::kittest::Queryable; + harness.get_by_label("Filter").click(); + harness.run_steps(3); + let viewport = harness.ctx.content_rect(); + let max_bottom = harness + .ctx + .memory(|m| m.areas().visible_layer_ids()) + .into_iter() + .filter_map(|layer| harness.ctx.memory(|m| m.area_rect(layer.id))) + .map(|r| r.bottom()) + .fold(viewport.top(), f32::max); + assert!(max_bottom <= viewport.bottom() + 1.0, "menu popup overflowed viewport: {max_bottom} > {}", viewport.bottom()); +} + +#[test] +fn tall_menu_scrolls_with_mouse_wheel_on_short_display() { + use egui_kittest::{Harness, kittest::Queryable}; + + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut harness = Harness::builder().with_size(egui::vec2(900.0, 220.0)).build_ui_state( + |ui, app| { + menu_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + harness.run_steps(3); + harness.get_by_label("Filter").click(); + harness.run_steps(3); + + let item = harness.get_by_label_contains("Filter Gallery…"); + let before = item.rect().top(); + harness.hover_at(item.rect().center()); + harness.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -80.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(4); + + let after = harness.get_by_label_contains("Filter Gallery…").rect().top(); + assert!(after < before - 1.0, "mouse wheel should move tall menu content: {before} -> {after}"); +} + +#[test] +fn window_panel_and_workspace_ids_drive_the_shell() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + assert!(!app.ui.panels.history); + invoke(&mut app, &ctx, "window.panel.history", Value::Null).unwrap(); + assert!(app.ui.panels.history); + assert_eq!(checked(&app, "window.panel.history"), Some(true)); + invoke(&mut app, &ctx, "window.workspace.painting", Value::Null).unwrap(); + assert_eq!(app.ui.workspace, "Painting"); + assert!(!app.ui.panels.properties); + assert_eq!(checked(&app, "window.workspace.painting"), Some(true)); + invoke(&mut app, &ctx, "window.workspace.essentials", Value::Null).unwrap(); + assert!(app.ui.panels.properties); + // Live in the menu, and no duplicate "Layers" entry from the window.toggle.* commands. + let items = menu_items(&app); + assert!(items.iter().any(|i| i.id == "window.panel.layers" && i.enabled)); + assert_eq!(items.iter().filter(|i| i.path == ["Window"] && i.label == "Layers").count(), 1); + assert!(items.iter().any(|i| i.id == "edit.stroke")); +} + +#[test] +fn proof_setup_presets_and_checkmarks() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.sync_views(); + assert_eq!(checked(&app, "view.proofColors"), Some(false)); + invoke(&mut app, &ctx, "view.proofSetup.workingCmyk", Value::Null).unwrap(); + assert_eq!(checked(&app, "view.proofColors"), Some(true)); + invoke(&mut app, &ctx, "view.gamutWarning", json!({"on": true})).unwrap(); + assert_eq!(checked(&app, "view.gamutWarning"), Some(true)); + let doc = app.session.active().unwrap().doc.clone(); + let lut = app.session.color.canvas_lut(&doc, 9).unwrap().unwrap(); + assert_eq!(lut.len(), 9 * 9 * 9 * 4); + // Pure sRGB green is outside coated CMYK; mid grey is inside. + let at = |r: usize, g: usize, b: usize| lut[(r + g * 9 + b * 81) * 4 + 3]; + assert_eq!((at(0, 8, 0), at(4, 4, 4)), (255, 0)); + // Custom… opens the generated Proof Setup dialog with a profile choice. + assert!(invoke(&mut app, &ctx, "view.proofSetup.custom", Value::Null).unwrap()["dialog"].is_u64()); + let spec = photocraft_engine::commands::find("edit.convertToProfile").unwrap(); + let params = crate::filter_dialog::parse_spec(spec.params); + assert!(matches!(¶ms[0].kind, crate::filter_dialog::Kind::Choice { options, .. } if options[0] == "srgb" && !options.iter().any(|v| v.contains('/')))); +} From 749a65e5637444b488108c506b90046937a7f9f8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:52 +0000 Subject: [PATCH 069/259] refactor(ui-egui): move zoom_tool.rs tests to zoom_tool/tests.rs --- crates/ui-egui/src/zoom_tool.rs | 424 +------------------------- crates/ui-egui/src/zoom_tool/tests.rs | 421 +++++++++++++++++++++++++ 2 files changed, 422 insertions(+), 423 deletions(-) create mode 100644 crates/ui-egui/src/zoom_tool/tests.rs diff --git a/crates/ui-egui/src/zoom_tool.rs b/crates/ui-egui/src/zoom_tool.rs index 0a96c76420..553e9ad781 100644 --- a/crates/ui-egui/src/zoom_tool.rs +++ b/crates/ui-egui/src/zoom_tool.rs @@ -111,426 +111,4 @@ pub fn draw(ctx: &egui::Context, painter: &egui::Painter) { } #[cfg(test)] -mod tests { - use super::*; - use egui::{Event, PointerButton}; - use egui_kittest::Harness; - use serde_json::json; - - #[test] - fn scrub_zoom_is_continuous_and_clamped() { - const DOC: [u32; 2] = [400, 300]; - assert_eq!(scrub_zoom(1.0, 0.0, DOC), 1.0); - assert!((scrub_zoom(1.0, DOUBLING, DOC) - 2.0).abs() < 1e-5); - assert!((scrub_zoom(1.0, -DOUBLING, DOC) - 0.5).abs() < 1e-5); - // Monotone: every point of drag to the right zooms in a little more. - let zs: Vec = (0..50).map(|i| scrub_zoom(0.7, i as f32 * 3.0, DOC)).collect(); - assert!(zs.windows(2).all(|w| w[1] > w[0])); - assert_eq!(scrub_zoom(1.0, 1e6, DOC), crate::zoom_levels::MAX); - assert_eq!(scrub_zoom(1.0, -1e6, DOC), crate::zoom_levels::min(DOC)); - assert_eq!(scrub_zoom(2.0, f32::NAN, DOC), 2.0); - } - - fn harness(scrubby: bool, ppp: 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 = crate::state::Tool::Zoom; - app.ui.tool_options.zoom_scrubby = scrubby; - let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).with_pixels_per_point(ppp).build_ui_state( - |ui, app: &mut PhotocraftApp| { - // Fonts set up after the first frame only apply from the next one. - 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::ALL[0]); - h.run_steps(4); - h - } - - fn view_xf(h: &Harness<'static, PhotocraftApp>) -> ViewXform { - ViewXform::active(h.state()).unwrap() - } - - // Pixel alignment derives a presentation camera within half a display pixel of the - // stored target; interrupting an animation must keep that same target and its zoom. - fn assert_camera_center(h: &Harness<'static, PhotocraftApp>, target: &View) { - let xf = view_xf(h); - let delta = (xf.to_screen(target.center[0], target.center[1]) - xf.rect.center()) * h.ctx.pixels_per_point(); - assert!(delta.x.abs() <= 0.501 && delta.y.abs() <= 0.501, "camera differs by {delta:?} display pixels"); - } - - fn press(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, pressed: bool) { - h.event(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }); - h.step(); - } - - #[test] - fn scrubby_zoom_drags_continuously_about_the_press_point() { - let mut h = harness(true, 1.0); - let r = h.state().last_canvas_rect; - let p0 = r.center() + vec2(-150.0, 60.0); - let doc0 = view_xf(&h).to_doc(p0); - let z0 = h.state().current_zoom(); - h.event(Event::PointerMoved(p0)); - h.step(); - press(&mut h, p0, true); - // Right: zooms in a little more each frame, the pressed document point stays put. - let mut last = z0; - for i in 1..=8 { - h.event(Event::PointerMoved(p0 + vec2(i as f32 * 15.0, (i % 3) as f32))); - h.step(); - let z = h.state().current_zoom(); - assert!(z > last, "frame {i}: {last} -> {z}"); - last = z; - let s = view_xf(&h).to_screen(doc0[0] as f32, doc0[1] as f32); - assert!(s.distance(p0) < 0.5, "anchor drifted to {s:?} (pressed at {p0:?})"); - } - // Back left past the press point: zooms out below the start. - h.event(Event::PointerMoved(p0 - vec2(60.0, 0.0))); - h.step(); - let z = h.state().current_zoom(); - assert!(z < z0 && (z - scrub_zoom(z0, -60.0, h.state().ui.views[0].doc_size)).abs() < 1e-4, "{z0} -> {z}"); - press(&mut h, p0 - vec2(60.0, 0.0), false); - h.run_steps(2); - // Release keeps the zoom; nothing was painted or recorded. - assert!((h.state().current_zoom() - z).abs() < 1e-5); - assert_eq!(h.state().session.documents()[0].history.past_len(), 0); - // A plain click still steps in. - let zc = h.state().current_zoom(); - h.event(Event::PointerMoved(p0)); - h.step(); - press(&mut h, p0, true); - press(&mut h, p0, false); - h.run_steps(2); - assert_eq!(h.state().current_zoom(), crate::zoom_levels::step(zc, 1, h.state().ui.views[0].doc_size)); - } - - #[test] - fn animated_zoom_off_click_jumps_to_the_anchored_target() { - let mut h = harness(true, 1.0); - h.state_mut() - .run("prefs.set", json!({"values": {"general.animatedZoom": false, "tools.zoomClickedPointToCenter": false, "tools.overscroll": true}})) - .unwrap(); - let pointer = h.state().last_canvas_rect.center() + vec2(90.0, -45.0); - let anchor = view_xf(&h).to_doc(pointer); - let start = h.state().current_zoom(); - h.event(Event::PointerMoved(pointer)); - h.step(); - press(&mut h, pointer, true); - press(&mut h, pointer, false); - let target = crate::zoom_levels::step(start, 1, [400, 300]); - let v = &h.state().ui.views[0]; - assert_eq!(v.zoom, target); - assert_eq!(view_xf(&h).zoom, target); - assert!(!v.zoom_animating && v.zoom_anchor.is_none() && v.zoom_transition.is_none()); - assert!(view_xf(&h).to_screen(anchor[0] as f32, anchor[1] as f32).distance(pointer) < 0.5); - } - - #[test] - fn animated_zoom_off_view_commands_show_the_target_on_the_first_frame() { - for command in - ["view.zoomIn", "view.zoomOut", "view.actualPixels", "view.fitOnScreen", "view.twoHundredPercent", "view.printSize", "view.fitLayersOnScreen"] - { - let mut h = harness(true, 1.0); - h.state_mut().run("prefs.set", json!({"values": {"general.animatedZoom": false}})).unwrap(); - if crate::view_cmds::handles(command) { - crate::view_cmds::invoke(h.state_mut(), &egui::Context::default(), command, &json!({})).unwrap().unwrap(); - } else { - h.state_mut().run(command, json!({})).unwrap(); - } - assert!(!h.state().ui.views[0].zoom_animating, "{command}"); - h.step(); - let v = &h.state().ui.views[0]; - let xf = view_xf(&h); - assert_eq!((xf.zoom, xf.center), (v.zoom, v.center), "{command}"); - assert!(v.zoom_anchor.is_none() && v.zoom_transition.is_none(), "{command}"); - } - } - - #[test] - fn disabling_animated_zoom_during_a_transition_snaps_and_does_not_resume() { - let mut h = harness(true, 1.0); - h.state_mut().run("view.zoomIn", json!({})).unwrap(); - h.step(); - let time = h.ctx.input(|i| i.time) + 0.11; - h.input_mut().time = Some(time); - h.step(); - assert!(h.state().ui.views[0].zoom_animating); - let target = (h.state().ui.views[0].zoom, h.state().ui.views[0].center); - assert_ne!(view_xf(&h).zoom, target.0); - h.state_mut().run("prefs.set", json!({"values": {"general.animatedZoom": false}})).unwrap(); - assert_eq!((view_xf(&h).zoom, view_xf(&h).center), target, "pointer mapping switches immediately"); - h.step(); - let v = &h.state().ui.views[0]; - assert!(!v.zoom_animating && v.zoom_anchor.is_none() && v.zoom_transition.is_none()); - assert_eq!((view_xf(&h).zoom, view_xf(&h).center), target); - h.state_mut().run("prefs.set", json!({"values": {"general.animatedZoom": true}})).unwrap(); - h.step(); - assert!(!h.state().ui.views[0].zoom_animating); - assert_eq!((view_xf(&h).zoom, view_xf(&h).center), target); - } - - #[test] - fn discrete_zoom_animates_and_keeps_its_document_anchor_fixed() { - let mut h = harness(true, 1.0); - let r = h.state().last_canvas_rect; - let pointer = r.center() + vec2(90.0, -45.0); - let anchor_doc = view_xf(&h).to_doc(pointer); - let anchor_screen = if h.state().session.prefs().tools.zoom_clicked_point_to_center { r.center() } else { pointer }; - let start = h.state().current_zoom(); - - h.event(Event::PointerMoved(pointer)); - h.step(); - press(&mut h, pointer, true); - press(&mut h, pointer, false); - - let target = crate::zoom_levels::step(start, 1, h.state().ui.views[0].doc_size); - assert_eq!(h.state().current_zoom(), target, "the model keeps the requested zoom as its target"); - assert!(h.state().ui.views[0].zoom_animating); - let mut time = h.ctx.input(|i| i.time) + 0.05; - for _ in 0..5 { - time += 0.01; - h.input_mut().time = Some(time); - h.step(); - } - let displayed_xf = view_xf(&h); - let displayed = displayed_xf.to_screen(anchor_doc[0] as f32, anchor_doc[1] as f32); - assert!(displayed.distance(anchor_screen) < 0.5, "anchor moved to {displayed:?}"); - let intermediate = displayed_xf.zoom; - assert!(intermediate > start && intermediate < target, "expected an intermediate zoom, got {intermediate}"); - - for _ in 0..30 { - time += 0.01; - h.input_mut().time = Some(time); - h.step(); - } - assert!(!h.state().ui.views[0].zoom_animating); - assert_eq!(view_xf(&h).zoom, target); - assert_eq!(h.state().current_zoom(), target); - } - - #[test] - fn gpu_zoom_animation_reuses_the_document_composite() { - let Ok(rs) = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) else { - eprintln!("skipping: no GPU adapter"); - return; - }; - let renderer = egui_kittest::wgpu::WgpuTestRenderer::from_render_state(rs); - let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).with_pixels_per_point(1.0).renderer(renderer).build_eframe(|cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ALL[0]); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.set_wgpu(cc.wgpu_render_state.clone().unwrap()); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - app.run("edit.fill", json!({"color": "#2060c0"})).unwrap(); - app - }); - h.run_steps(4); - h.state_mut().run("view.actualPixels", json!({})).unwrap(); - h.step(); - let time = h.ctx.input(|i| i.time) + 0.3; - h.input_mut().time = Some(time); - h.step(); - let id = h.state().session.documents()[0].doc.id; - assert!(h.state().canvases[&(id, crate::canvas::GPU_OUTPUT)].on_gpu); - let directory = std::env::var_os("CRAFT_UI_ZOOM_FIXTURES").map(std::path::PathBuf::from); - if let Some(directory) = &directory { - std::fs::create_dir_all(directory).unwrap(); - } - h.state_mut().run("view.zoomIn", json!({})).unwrap(); - let target = h.state().current_zoom(); - for (name, elapsed) in [("start", 0.0), ("midpoint", 0.11), ("finished", 0.23)] { - h.state_mut().perf.last_refresh = ""; - h.input_mut().time = Some(time + elapsed); - h.step(); - assert!(h.state().perf.gpu, "{name}: keep the GPU canvas"); - assert_eq!(h.state().perf.last_refresh, "", "{name}: reuse the composite"); - assert!(h.state().canvases.values().all(|cache| cache.texture.is_none()), "{name}: no CPU texture fallback"); - let xf = view_xf(&h); - if name == "midpoint" { - assert!(xf.zoom > 1.0 && xf.zoom < target); - } - let image = h.render().unwrap(); - let center = xf.to_screen(200.0, 150.0); - let pixel = image.get_pixel(center.x as u32, center.y as u32); - assert!(pixel[2] > pixel[0] * 2, "{name}: document remains visible: {pixel:?}"); - if let Some(directory) = &directory { - image.save(directory.join(format!("photocraft-zoom-{name}.png"))).unwrap(); - } - } - assert!(!h.state().ui.views[0].zoom_animating); - assert_eq!(view_xf(&h).zoom, target); - h.state_mut().run("prefs.set", json!({"values": {"general.animatedZoom": false}})).unwrap(); - h.state_mut().run("view.zoomIn", json!({})).unwrap(); - h.state_mut().perf.last_refresh = ""; - h.step(); - assert_eq!(view_xf(&h).zoom, h.state().current_zoom()); - assert!(!h.state().ui.views[0].zoom_animating); - assert!(h.state().perf.gpu); - assert_eq!(h.state().perf.last_refresh, "", "immediate zoom reuses the GPU composite"); - let image = h.render().unwrap(); - if let Some(directory) = &directory { - image.save(directory.join("photocraft-zoom-disabled.png")).unwrap(); - } - } - - #[test] - fn view_commands_retarget_a_zoom_click_without_retaining_its_anchor() { - for command in ["view.zoomIn", "view.actualPixels", "view.fitOnScreen"] { - let mut h = harness(true, 1.0); - let pointer = h.state().last_canvas_rect.center() + vec2(90.0, -45.0); - h.event(Event::PointerMoved(pointer)); - h.step(); - press(&mut h, pointer, true); - press(&mut h, pointer, false); - assert!(h.state().ui.views[0].zoom_anchor.is_some()); - h.step(); - h.state_mut().run(command, json!({})).unwrap(); - assert!(h.state().ui.views[0].zoom_anchor.is_none(), "{command}"); - h.step(); - let time = h.ctx.input(|i| i.time) + 0.3; - h.input_mut().time = Some(time); - h.step(); - let target = &h.state().ui.views[0]; - assert!(!target.zoom_animating, "{command}"); - assert_eq!(view_xf(&h).zoom, target.zoom); - assert_camera_center(&h, target); - } - } - - #[test] - fn wheel_pinch_pan_and_scrubby_zoom_interrupt_a_transition() { - for gesture in 0..5 { - let mut h = harness(true, 1.0); - let pointer = h.state().last_canvas_rect.center(); - h.event(Event::PointerMoved(pointer)); - h.step(); - h.state_mut().run("view.zoomIn", json!({})).unwrap(); - h.step(); - assert!(h.state().ui.views[0].zoom_animating); - match gesture { - 0 => h.event(Event::Zoom(1.25)), - 1 | 2 => h.event(Event::MouseWheel { - unit: egui::MouseWheelUnit::Line, - delta: vec2(0.0, 1.0), - phase: egui::TouchPhase::Move, - source: egui::MouseWheelSource::Unknown, - modifiers: egui::Modifiers { alt: gesture == 1, ..Default::default() }, - }), - _ => { - h.state_mut().ui.tool = if gesture == 3 { crate::state::Tool::Hand } else { crate::state::Tool::Zoom }; - press(&mut h, pointer, true); - h.event(Event::PointerMoved(pointer + vec2(120.0, 0.0))); - } - } - h.step(); - assert!(!h.state().ui.views[0].zoom_animating, "gesture {gesture}"); - h.step(); - let target = &h.state().ui.views[0]; - assert_eq!(view_xf(&h).zoom, target.zoom, "gesture {gesture}"); - assert_camera_center(&h, target); - } - } - - #[test] - fn a_scrub_release_keeps_a_view_centred_since_its_last_zoom() { - // Zoom Resizes Windows centres the image once its window wraps it (zoom_window_fit.rs): - // the release frame, at the same zoom, must not pull it back to the press point. - let mut h = harness(true, 1.0); - let p0 = h.state().last_canvas_rect.center() + vec2(-150.0, 60.0); - h.event(Event::PointerMoved(p0)); - h.step(); - press(&mut h, p0, true); - let end = p0 + vec2(90.0, 0.0); - h.event(Event::PointerMoved(end)); - h.step(); - let z = h.state().current_zoom(); - h.state_mut().ui.views[0].center = [200.0, 150.0]; - h.step(); - assert_eq!(h.state().ui.views[0].center, [200.0, 150.0], "a held, unmoved scrub keeps the view"); - press(&mut h, end, false); - h.run_steps(2); - assert_eq!(h.state().current_zoom(), z); - assert_eq!(h.state().ui.views[0].center, [200.0, 150.0], "the release keeps the view"); - } - - #[test] - fn zoom_drags_keep_the_press_point_in_rotated_and_flipped_views() { - for (scrubby, out, rotation, flip, ppp) in [ - (true, false, 30.0, false, 1.0), - (true, false, -45.0, true, 1.0), - (true, false, 90.0, false, 2.0), - (true, false, 30.0, true, 2.0), - (false, false, 30.0, false, 1.0), - (false, true, -45.0, true, 2.0), - ] { - let mut h = harness(scrubby, ppp); - let view = &mut h.state_mut().ui.views[0]; - view.zoom = 1.0; - view.center = [200.0, 150.0]; - view.rotation = rotation; - view.fit_pending = false; - view.fill_pending = false; - h.state_mut().ui.view.flip_horizontal = flip; - h.run_steps(2); - let anchor = view_xf(&h).to_screen(140.0, 110.0); - let modifiers = egui::Modifiers { alt: out, ..Default::default() }; - h.event(Event::ModifiersChanged(modifiers)); - h.event(Event::PointerMoved(anchor)); - h.step(); - h.event(Event::PointerButton { pos: anchor, button: PointerButton::Primary, pressed: true, modifiers }); - h.step(); - let steps: &[f32] = if scrubby { &[15.0, 50.0, 100.0, -40.0] } else { &[20.0] }; - let mut end = anchor; - for &dx in steps { - end = anchor + vec2(dx, if scrubby { 0.0 } else { 1.0 }); - h.event(Event::PointerMoved(end)); - h.step(); - let actual = view_xf(&h).to_screen(140.0, 110.0); - assert!(actual.distance(anchor) < 0.01, "rotation={rotation}, flip={flip}, ppp={ppp}: {anchor:?} -> {actual:?}"); - let expected = if scrubby { scrub_zoom(1.0, dx, [400, 300]) } else { 1.0 }; - assert!((h.state().current_zoom() - expected).abs() < 1e-5); - } - h.event(Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers }); - h.step(); - h.run_steps(2); - assert!(view_xf(&h).to_screen(140.0, 110.0).distance(anchor) < 0.01); - let expected = if scrubby { scrub_zoom(1.0, -40.0, [400, 300]) } else { crate::zoom_levels::step(1.0, if out { -1 } else { 1 }, [400, 300]) }; - assert!((h.state().current_zoom() - expected).abs() < 1e-5); - assert_eq!(h.state().ui.views[0].rotation, rotation); - assert_eq!(h.state().ui.view.flip_horizontal, flip); - assert_eq!(h.state().session.documents()[0].history.past_len(), 0); - } - } - - #[test] - fn zoom_rectangle_without_scrubby_zoom() { - let mut h = harness(false, 1.0); - let r = h.state().last_canvas_rect; - let z0 = h.state().current_zoom(); - let a = r.center() - vec2(60.0, 40.0); - let b = r.center() + vec2(60.0, 40.0); - let mid = view_xf(&h).to_doc(r.center()); - h.event(Event::PointerMoved(a)); - h.step(); - press(&mut h, a, true); - for t in [0.3, 0.7, 1.0] { - h.event(Event::PointerMoved(a + (b - a) * t)); - h.step(); - } - assert_eq!(h.state().current_zoom(), z0, "no zoom while the rectangle is drawn"); - press(&mut h, b, false); - h.run_steps(2); - let z = h.state().current_zoom(); - let k = (r.width() / 120.0).min(r.height() / 80.0); - assert!((z - z0 * k).abs() < z0 * k * 0.02, "{z0} * {k} vs {z}"); - // The rectangle's centre is now the view centre. - let c = h.state().ui.views[0].center; - assert!((c[0] as f64 - mid[0]).abs() < 1.0 && (c[1] as f64 - mid[1]).abs() < 1.0, "{c:?} vs {mid:?}"); - } -} +mod tests; diff --git a/crates/ui-egui/src/zoom_tool/tests.rs b/crates/ui-egui/src/zoom_tool/tests.rs new file mode 100644 index 0000000000..e2b557ac42 --- /dev/null +++ b/crates/ui-egui/src/zoom_tool/tests.rs @@ -0,0 +1,421 @@ +use super::*; +use egui::{Event, PointerButton}; +use egui_kittest::Harness; +use serde_json::json; + +#[test] +fn scrub_zoom_is_continuous_and_clamped() { + const DOC: [u32; 2] = [400, 300]; + assert_eq!(scrub_zoom(1.0, 0.0, DOC), 1.0); + assert!((scrub_zoom(1.0, DOUBLING, DOC) - 2.0).abs() < 1e-5); + assert!((scrub_zoom(1.0, -DOUBLING, DOC) - 0.5).abs() < 1e-5); + // Monotone: every point of drag to the right zooms in a little more. + let zs: Vec = (0..50).map(|i| scrub_zoom(0.7, i as f32 * 3.0, DOC)).collect(); + assert!(zs.windows(2).all(|w| w[1] > w[0])); + assert_eq!(scrub_zoom(1.0, 1e6, DOC), crate::zoom_levels::MAX); + assert_eq!(scrub_zoom(1.0, -1e6, DOC), crate::zoom_levels::min(DOC)); + assert_eq!(scrub_zoom(2.0, f32::NAN, DOC), 2.0); +} + +fn harness(scrubby: bool, ppp: 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 = crate::state::Tool::Zoom; + app.ui.tool_options.zoom_scrubby = scrubby; + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).with_pixels_per_point(ppp).build_ui_state( + |ui, app: &mut PhotocraftApp| { + // Fonts set up after the first frame only apply from the next one. + 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::ALL[0]); + h.run_steps(4); + h +} + +fn view_xf(h: &Harness<'static, PhotocraftApp>) -> ViewXform { + ViewXform::active(h.state()).unwrap() +} + +// Pixel alignment derives a presentation camera within half a display pixel of the +// stored target; interrupting an animation must keep that same target and its zoom. +fn assert_camera_center(h: &Harness<'static, PhotocraftApp>, target: &View) { + let xf = view_xf(h); + let delta = (xf.to_screen(target.center[0], target.center[1]) - xf.rect.center()) * h.ctx.pixels_per_point(); + assert!(delta.x.abs() <= 0.501 && delta.y.abs() <= 0.501, "camera differs by {delta:?} display pixels"); +} + +fn press(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, pressed: bool) { + h.event(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }); + h.step(); +} + +#[test] +fn scrubby_zoom_drags_continuously_about_the_press_point() { + let mut h = harness(true, 1.0); + let r = h.state().last_canvas_rect; + let p0 = r.center() + vec2(-150.0, 60.0); + let doc0 = view_xf(&h).to_doc(p0); + let z0 = h.state().current_zoom(); + h.event(Event::PointerMoved(p0)); + h.step(); + press(&mut h, p0, true); + // Right: zooms in a little more each frame, the pressed document point stays put. + let mut last = z0; + for i in 1..=8 { + h.event(Event::PointerMoved(p0 + vec2(i as f32 * 15.0, (i % 3) as f32))); + h.step(); + let z = h.state().current_zoom(); + assert!(z > last, "frame {i}: {last} -> {z}"); + last = z; + let s = view_xf(&h).to_screen(doc0[0] as f32, doc0[1] as f32); + assert!(s.distance(p0) < 0.5, "anchor drifted to {s:?} (pressed at {p0:?})"); + } + // Back left past the press point: zooms out below the start. + h.event(Event::PointerMoved(p0 - vec2(60.0, 0.0))); + h.step(); + let z = h.state().current_zoom(); + assert!(z < z0 && (z - scrub_zoom(z0, -60.0, h.state().ui.views[0].doc_size)).abs() < 1e-4, "{z0} -> {z}"); + press(&mut h, p0 - vec2(60.0, 0.0), false); + h.run_steps(2); + // Release keeps the zoom; nothing was painted or recorded. + assert!((h.state().current_zoom() - z).abs() < 1e-5); + assert_eq!(h.state().session.documents()[0].history.past_len(), 0); + // A plain click still steps in. + let zc = h.state().current_zoom(); + h.event(Event::PointerMoved(p0)); + h.step(); + press(&mut h, p0, true); + press(&mut h, p0, false); + h.run_steps(2); + assert_eq!(h.state().current_zoom(), crate::zoom_levels::step(zc, 1, h.state().ui.views[0].doc_size)); +} + +#[test] +fn animated_zoom_off_click_jumps_to_the_anchored_target() { + let mut h = harness(true, 1.0); + h.state_mut() + .run("prefs.set", json!({"values": {"general.animatedZoom": false, "tools.zoomClickedPointToCenter": false, "tools.overscroll": true}})) + .unwrap(); + let pointer = h.state().last_canvas_rect.center() + vec2(90.0, -45.0); + let anchor = view_xf(&h).to_doc(pointer); + let start = h.state().current_zoom(); + h.event(Event::PointerMoved(pointer)); + h.step(); + press(&mut h, pointer, true); + press(&mut h, pointer, false); + let target = crate::zoom_levels::step(start, 1, [400, 300]); + let v = &h.state().ui.views[0]; + assert_eq!(v.zoom, target); + assert_eq!(view_xf(&h).zoom, target); + assert!(!v.zoom_animating && v.zoom_anchor.is_none() && v.zoom_transition.is_none()); + assert!(view_xf(&h).to_screen(anchor[0] as f32, anchor[1] as f32).distance(pointer) < 0.5); +} + +#[test] +fn animated_zoom_off_view_commands_show_the_target_on_the_first_frame() { + for command in + ["view.zoomIn", "view.zoomOut", "view.actualPixels", "view.fitOnScreen", "view.twoHundredPercent", "view.printSize", "view.fitLayersOnScreen"] + { + let mut h = harness(true, 1.0); + h.state_mut().run("prefs.set", json!({"values": {"general.animatedZoom": false}})).unwrap(); + if crate::view_cmds::handles(command) { + crate::view_cmds::invoke(h.state_mut(), &egui::Context::default(), command, &json!({})).unwrap().unwrap(); + } else { + h.state_mut().run(command, json!({})).unwrap(); + } + assert!(!h.state().ui.views[0].zoom_animating, "{command}"); + h.step(); + let v = &h.state().ui.views[0]; + let xf = view_xf(&h); + assert_eq!((xf.zoom, xf.center), (v.zoom, v.center), "{command}"); + assert!(v.zoom_anchor.is_none() && v.zoom_transition.is_none(), "{command}"); + } +} + +#[test] +fn disabling_animated_zoom_during_a_transition_snaps_and_does_not_resume() { + let mut h = harness(true, 1.0); + h.state_mut().run("view.zoomIn", json!({})).unwrap(); + h.step(); + let time = h.ctx.input(|i| i.time) + 0.11; + h.input_mut().time = Some(time); + h.step(); + assert!(h.state().ui.views[0].zoom_animating); + let target = (h.state().ui.views[0].zoom, h.state().ui.views[0].center); + assert_ne!(view_xf(&h).zoom, target.0); + h.state_mut().run("prefs.set", json!({"values": {"general.animatedZoom": false}})).unwrap(); + assert_eq!((view_xf(&h).zoom, view_xf(&h).center), target, "pointer mapping switches immediately"); + h.step(); + let v = &h.state().ui.views[0]; + assert!(!v.zoom_animating && v.zoom_anchor.is_none() && v.zoom_transition.is_none()); + assert_eq!((view_xf(&h).zoom, view_xf(&h).center), target); + h.state_mut().run("prefs.set", json!({"values": {"general.animatedZoom": true}})).unwrap(); + h.step(); + assert!(!h.state().ui.views[0].zoom_animating); + assert_eq!((view_xf(&h).zoom, view_xf(&h).center), target); +} + +#[test] +fn discrete_zoom_animates_and_keeps_its_document_anchor_fixed() { + let mut h = harness(true, 1.0); + let r = h.state().last_canvas_rect; + let pointer = r.center() + vec2(90.0, -45.0); + let anchor_doc = view_xf(&h).to_doc(pointer); + let anchor_screen = if h.state().session.prefs().tools.zoom_clicked_point_to_center { r.center() } else { pointer }; + let start = h.state().current_zoom(); + + h.event(Event::PointerMoved(pointer)); + h.step(); + press(&mut h, pointer, true); + press(&mut h, pointer, false); + + let target = crate::zoom_levels::step(start, 1, h.state().ui.views[0].doc_size); + assert_eq!(h.state().current_zoom(), target, "the model keeps the requested zoom as its target"); + assert!(h.state().ui.views[0].zoom_animating); + let mut time = h.ctx.input(|i| i.time) + 0.05; + for _ in 0..5 { + time += 0.01; + h.input_mut().time = Some(time); + h.step(); + } + let displayed_xf = view_xf(&h); + let displayed = displayed_xf.to_screen(anchor_doc[0] as f32, anchor_doc[1] as f32); + assert!(displayed.distance(anchor_screen) < 0.5, "anchor moved to {displayed:?}"); + let intermediate = displayed_xf.zoom; + assert!(intermediate > start && intermediate < target, "expected an intermediate zoom, got {intermediate}"); + + for _ in 0..30 { + time += 0.01; + h.input_mut().time = Some(time); + h.step(); + } + assert!(!h.state().ui.views[0].zoom_animating); + assert_eq!(view_xf(&h).zoom, target); + assert_eq!(h.state().current_zoom(), target); +} + +#[test] +fn gpu_zoom_animation_reuses_the_document_composite() { + let Ok(rs) = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let renderer = egui_kittest::wgpu::WgpuTestRenderer::from_render_state(rs); + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).with_pixels_per_point(1.0).renderer(renderer).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, crate::theme::ThemeKind::ALL[0]); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.set_wgpu(cc.wgpu_render_state.clone().unwrap()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("edit.fill", json!({"color": "#2060c0"})).unwrap(); + app + }); + h.run_steps(4); + h.state_mut().run("view.actualPixels", json!({})).unwrap(); + h.step(); + let time = h.ctx.input(|i| i.time) + 0.3; + h.input_mut().time = Some(time); + h.step(); + let id = h.state().session.documents()[0].doc.id; + assert!(h.state().canvases[&(id, crate::canvas::GPU_OUTPUT)].on_gpu); + let directory = std::env::var_os("CRAFT_UI_ZOOM_FIXTURES").map(std::path::PathBuf::from); + if let Some(directory) = &directory { + std::fs::create_dir_all(directory).unwrap(); + } + h.state_mut().run("view.zoomIn", json!({})).unwrap(); + let target = h.state().current_zoom(); + for (name, elapsed) in [("start", 0.0), ("midpoint", 0.11), ("finished", 0.23)] { + h.state_mut().perf.last_refresh = ""; + h.input_mut().time = Some(time + elapsed); + h.step(); + assert!(h.state().perf.gpu, "{name}: keep the GPU canvas"); + assert_eq!(h.state().perf.last_refresh, "", "{name}: reuse the composite"); + assert!(h.state().canvases.values().all(|cache| cache.texture.is_none()), "{name}: no CPU texture fallback"); + let xf = view_xf(&h); + if name == "midpoint" { + assert!(xf.zoom > 1.0 && xf.zoom < target); + } + let image = h.render().unwrap(); + let center = xf.to_screen(200.0, 150.0); + let pixel = image.get_pixel(center.x as u32, center.y as u32); + assert!(pixel[2] > pixel[0] * 2, "{name}: document remains visible: {pixel:?}"); + if let Some(directory) = &directory { + image.save(directory.join(format!("photocraft-zoom-{name}.png"))).unwrap(); + } + } + assert!(!h.state().ui.views[0].zoom_animating); + assert_eq!(view_xf(&h).zoom, target); + h.state_mut().run("prefs.set", json!({"values": {"general.animatedZoom": false}})).unwrap(); + h.state_mut().run("view.zoomIn", json!({})).unwrap(); + h.state_mut().perf.last_refresh = ""; + h.step(); + assert_eq!(view_xf(&h).zoom, h.state().current_zoom()); + assert!(!h.state().ui.views[0].zoom_animating); + assert!(h.state().perf.gpu); + assert_eq!(h.state().perf.last_refresh, "", "immediate zoom reuses the GPU composite"); + let image = h.render().unwrap(); + if let Some(directory) = &directory { + image.save(directory.join("photocraft-zoom-disabled.png")).unwrap(); + } +} + +#[test] +fn view_commands_retarget_a_zoom_click_without_retaining_its_anchor() { + for command in ["view.zoomIn", "view.actualPixels", "view.fitOnScreen"] { + let mut h = harness(true, 1.0); + let pointer = h.state().last_canvas_rect.center() + vec2(90.0, -45.0); + h.event(Event::PointerMoved(pointer)); + h.step(); + press(&mut h, pointer, true); + press(&mut h, pointer, false); + assert!(h.state().ui.views[0].zoom_anchor.is_some()); + h.step(); + h.state_mut().run(command, json!({})).unwrap(); + assert!(h.state().ui.views[0].zoom_anchor.is_none(), "{command}"); + h.step(); + let time = h.ctx.input(|i| i.time) + 0.3; + h.input_mut().time = Some(time); + h.step(); + let target = &h.state().ui.views[0]; + assert!(!target.zoom_animating, "{command}"); + assert_eq!(view_xf(&h).zoom, target.zoom); + assert_camera_center(&h, target); + } +} + +#[test] +fn wheel_pinch_pan_and_scrubby_zoom_interrupt_a_transition() { + for gesture in 0..5 { + let mut h = harness(true, 1.0); + let pointer = h.state().last_canvas_rect.center(); + h.event(Event::PointerMoved(pointer)); + h.step(); + h.state_mut().run("view.zoomIn", json!({})).unwrap(); + h.step(); + assert!(h.state().ui.views[0].zoom_animating); + match gesture { + 0 => h.event(Event::Zoom(1.25)), + 1 | 2 => h.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers { alt: gesture == 1, ..Default::default() }, + }), + _ => { + h.state_mut().ui.tool = if gesture == 3 { crate::state::Tool::Hand } else { crate::state::Tool::Zoom }; + press(&mut h, pointer, true); + h.event(Event::PointerMoved(pointer + vec2(120.0, 0.0))); + } + } + h.step(); + assert!(!h.state().ui.views[0].zoom_animating, "gesture {gesture}"); + h.step(); + let target = &h.state().ui.views[0]; + assert_eq!(view_xf(&h).zoom, target.zoom, "gesture {gesture}"); + assert_camera_center(&h, target); + } +} + +#[test] +fn a_scrub_release_keeps_a_view_centred_since_its_last_zoom() { + // Zoom Resizes Windows centres the image once its window wraps it (zoom_window_fit.rs): + // the release frame, at the same zoom, must not pull it back to the press point. + let mut h = harness(true, 1.0); + let p0 = h.state().last_canvas_rect.center() + vec2(-150.0, 60.0); + h.event(Event::PointerMoved(p0)); + h.step(); + press(&mut h, p0, true); + let end = p0 + vec2(90.0, 0.0); + h.event(Event::PointerMoved(end)); + h.step(); + let z = h.state().current_zoom(); + h.state_mut().ui.views[0].center = [200.0, 150.0]; + h.step(); + assert_eq!(h.state().ui.views[0].center, [200.0, 150.0], "a held, unmoved scrub keeps the view"); + press(&mut h, end, false); + h.run_steps(2); + assert_eq!(h.state().current_zoom(), z); + assert_eq!(h.state().ui.views[0].center, [200.0, 150.0], "the release keeps the view"); +} + +#[test] +fn zoom_drags_keep_the_press_point_in_rotated_and_flipped_views() { + for (scrubby, out, rotation, flip, ppp) in [ + (true, false, 30.0, false, 1.0), + (true, false, -45.0, true, 1.0), + (true, false, 90.0, false, 2.0), + (true, false, 30.0, true, 2.0), + (false, false, 30.0, false, 1.0), + (false, true, -45.0, true, 2.0), + ] { + let mut h = harness(scrubby, ppp); + let view = &mut h.state_mut().ui.views[0]; + view.zoom = 1.0; + view.center = [200.0, 150.0]; + view.rotation = rotation; + view.fit_pending = false; + view.fill_pending = false; + h.state_mut().ui.view.flip_horizontal = flip; + h.run_steps(2); + let anchor = view_xf(&h).to_screen(140.0, 110.0); + let modifiers = egui::Modifiers { alt: out, ..Default::default() }; + h.event(Event::ModifiersChanged(modifiers)); + h.event(Event::PointerMoved(anchor)); + h.step(); + h.event(Event::PointerButton { pos: anchor, button: PointerButton::Primary, pressed: true, modifiers }); + h.step(); + let steps: &[f32] = if scrubby { &[15.0, 50.0, 100.0, -40.0] } else { &[20.0] }; + let mut end = anchor; + for &dx in steps { + end = anchor + vec2(dx, if scrubby { 0.0 } else { 1.0 }); + h.event(Event::PointerMoved(end)); + h.step(); + let actual = view_xf(&h).to_screen(140.0, 110.0); + assert!(actual.distance(anchor) < 0.01, "rotation={rotation}, flip={flip}, ppp={ppp}: {anchor:?} -> {actual:?}"); + let expected = if scrubby { scrub_zoom(1.0, dx, [400, 300]) } else { 1.0 }; + assert!((h.state().current_zoom() - expected).abs() < 1e-5); + } + h.event(Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers }); + h.step(); + h.run_steps(2); + assert!(view_xf(&h).to_screen(140.0, 110.0).distance(anchor) < 0.01); + let expected = if scrubby { scrub_zoom(1.0, -40.0, [400, 300]) } else { crate::zoom_levels::step(1.0, if out { -1 } else { 1 }, [400, 300]) }; + assert!((h.state().current_zoom() - expected).abs() < 1e-5); + assert_eq!(h.state().ui.views[0].rotation, rotation); + assert_eq!(h.state().ui.view.flip_horizontal, flip); + assert_eq!(h.state().session.documents()[0].history.past_len(), 0); + } +} + +#[test] +fn zoom_rectangle_without_scrubby_zoom() { + let mut h = harness(false, 1.0); + let r = h.state().last_canvas_rect; + let z0 = h.state().current_zoom(); + let a = r.center() - vec2(60.0, 40.0); + let b = r.center() + vec2(60.0, 40.0); + let mid = view_xf(&h).to_doc(r.center()); + h.event(Event::PointerMoved(a)); + h.step(); + press(&mut h, a, true); + for t in [0.3, 0.7, 1.0] { + h.event(Event::PointerMoved(a + (b - a) * t)); + h.step(); + } + assert_eq!(h.state().current_zoom(), z0, "no zoom while the rectangle is drawn"); + press(&mut h, b, false); + h.run_steps(2); + let z = h.state().current_zoom(); + let k = (r.width() / 120.0).min(r.height() / 80.0); + assert!((z - z0 * k).abs() < z0 * k * 0.02, "{z0} * {k} vs {z}"); + // The rectangle's centre is now the view centre. + let c = h.state().ui.views[0].center; + assert!((c[0] as f64 - mid[0]).abs() < 1.0 && (c[1] as f64 - mid[1]).abs() < 1.0, "{c:?} vs {mid:?}"); +} From 24111a1067dc2e337914a4664b342887c1f03676 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:53 +0000 Subject: [PATCH 070/259] refactor(ui-egui): move channels_panel.rs tests to channels_panel/tests.rs --- crates/ui-egui/src/channels_panel.rs | 317 +-------------------- crates/ui-egui/src/channels_panel/tests.rs | 314 ++++++++++++++++++++ 2 files changed, 315 insertions(+), 316 deletions(-) create mode 100644 crates/ui-egui/src/channels_panel/tests.rs diff --git a/crates/ui-egui/src/channels_panel.rs b/crates/ui-egui/src/channels_panel.rs index 5768ae0850..f073cf8f3c 100644 --- a/crates/ui-egui/src/channels_panel.rs +++ b/crates/ui-egui/src/channels_panel.rs @@ -501,319 +501,4 @@ fn overlay_colors(ui: &mut egui::Ui, actions: &mut Vec<(String, Value)>, channel } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn modifier_operations() { - let m = |shift, alt| egui::Modifiers { command: true, shift, alt, ..Default::default() }; - assert_eq!(load_operation(m(false, false)), "new"); - assert_eq!(load_operation(m(true, false)), "add"); - assert_eq!(load_operation(m(false, true)), "subtract"); - assert_eq!(load_operation(m(true, true)), "intersect"); - } - - #[test] - fn rename_field_interrupts_the_ime_only_when_it_takes_focus() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.run("channel.new", json!({})).unwrap(); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); - let doc = app.session.active().unwrap().doc.id.0; - let name = app.session.active().unwrap().doc.channels[0].name.clone(); - ctx.data_mut(|d| d.insert_temp(egui::Id::unique(("chan-rename", doc, format!("{:?}", Row::Alpha(0).reference()))), name)); - // The field takes focus on the first pass and owns the IME from the second on (#585). - let interrupts: Vec> = (0..4) - .map(|_| { - let mut out = ctx.run_ui(Default::default(), |ui| show(&mut app, ui)); - out.textures_delta.clear(); - out.platform_output.ime.map(|ime| ime.should_interrupt_composition) - }) - .collect(); - assert_eq!(interrupts, [None, Some(false), Some(false), Some(false)]); - } - - #[test] - fn channel_thumbs_honours_show_channels_in_color() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - let ctx = egui::Context::default(); - let thumbs_gray = app.channel_thumbs(&ctx); - assert!(!thumbs_gray.is_empty()); - - app.session.execute("prefs.set", json!({"values": {"interface.showChannelsInColor": true}})).unwrap(); - let thumbs_color = app.channel_thumbs(&ctx); - assert_eq!(thumbs_gray.len(), thumbs_color.len()); - } - - /// A selection-only step keeps the thumbnails; a pixel edit rebuilds them into the same - /// textures rather than new ones (#4518). - #[test] - fn channel_thumbs_skip_selection_steps_and_reuse_textures() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - let ctx = egui::Context::default(); - // Texture uploads one pass makes (new textures and updates both count). - let pass = |app: &mut PhotocraftApp| { - ctx.begin_pass(Default::default()); - let ids = app.channel_thumbs(&ctx); - let mut delta = ctx.end_pass().textures_delta; - let n = delta.set.len(); - delta.clear(); - (ids, n) - }; - let (first, uploads) = pass(&mut app); - assert!(uploads > 0); - app.run("select.rect", json!({"x": 4, "y": 4, "width": 20, "height": 20})).unwrap(); - assert_eq!(pass(&mut app), (first.clone(), 0), "a marquee changes no pixels"); - app.run("select.deselect", json!({})).unwrap(); - assert_eq!(pass(&mut app), (first.clone(), 0), "neither does Deselect"); - app.run("edit.fill", json!({"color": "#336699"})).unwrap(); - let (after, uploads) = pass(&mut app); - assert!(uploads > 0, "a fill rebuilds them"); - assert_eq!(after, first, "into the same textures"); - } - - /// The Channels tab (the Layers card's second tab) of a 64×48 white document with a layer - /// mask on "Masked" and one alpha channel. - fn channels_harness() -> (egui_kittest::Harness<'static, PhotocraftApp>, u64) { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); - let masked = s.execute("layer.new.layer", json!({"name": "Masked"})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.layerMask.revealAll", json!({"layer": masked})).unwrap(); - s.execute("channel.new", json!({})).unwrap(); - // 60 fps steps, so two clicks a frame apart count as a double-click. - let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 1000.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!({"dockWidth": 290.0, "dockTabs": {"layers": 1}, "dock": {"collapsed": ["color", "properties", "history", "navigator"]}}), - ); - crate::control::handle(h.state_mut(), &ctx, &req); - h.run_steps(8); - (h, masked) - } - - /// The centre of the row or button labelled `label` (not its tooltip, which a hover leaves open). - fn at(h: &egui_kittest::Harness<'_, PhotocraftApp>, label: &str) -> egui::Pos2 { - use egui::accesskit::Role; - use egui_kittest::kittest::{NodeT, Queryable}; - h.query_all_by_label(label) - .find(|n| matches!(n.accesskit_node().role(), Role::Button | Role::ListBoxOption | Role::Label) && n.rect().height() > 20.0) - .unwrap_or_else(|| panic!("no row or button {label}")) - .rect() - .center() - } - - /// A real press, drag and release. - fn drag(h: &mut egui_kittest::Harness<'_, PhotocraftApp>, from: egui::Pos2, to: egui::Pos2) { - use egui::{Modifiers, PointerButton}; - h.hover_at(from); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - for i in 1..=6 { - h.hover_at(from + (to - from) * (i as f32 / 6.0)); - h.run_steps(1); - } - h.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(3); - } - - /// Drags the row or button labelled `from` onto the one labelled `to`. - fn drag_to(h: &mut egui_kittest::Harness<'_, PhotocraftApp>, from: &str, to: &str) { - let (from, to) = (at(h, from), at(h, to)); - drag(h, from, to); - } - - fn alphas(h: &egui_kittest::Harness<'_, PhotocraftApp>) -> Vec { - h.state().session.active().unwrap().doc.channels.iter().map(|c| c.name.clone()).collect() - } - - /// #9163: alpha channels reorder by dragging, as in Photoshop: a drop in a row's upper half - /// lands above it, over the colour channels it lands first among the alphas, colour channels - /// don't move, and each reorder is one history step. - #[test] - fn alpha_channels_reorder_by_dragging() { - let (mut h, _) = channels_harness(); - h.state_mut().run("channel.new", json!({"name": "Alpha 2"})).unwrap(); - h.state_mut().run("channel.new", json!({"name": "Alpha 3"})).unwrap(); - h.run_steps(3); - assert_eq!(alphas(&h), ["Alpha 1", "Alpha 2", "Alpha 3"]); - let steps = h.state().session.active().unwrap().history.past_len(); - - let (from, onto) = (at(&h, "Alpha 3"), at(&h, "Alpha 1")); - drag(&mut h, from, onto - vec2(0.0, 8.0)); - assert_eq!(alphas(&h), ["Alpha 3", "Alpha 1", "Alpha 2"]); - assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "one history step"); - - // The lower half of a row: below it. - let (from, onto) = (at(&h, "Alpha 3"), at(&h, "Alpha 1")); - drag(&mut h, from, onto + vec2(0.0, 8.0)); - assert_eq!(alphas(&h), ["Alpha 1", "Alpha 3", "Alpha 2"]); - - // Dropped on a colour channel: first among the alphas. - drag_to(&mut h, "Alpha 2", "Red"); - assert_eq!(alphas(&h), ["Alpha 2", "Alpha 1", "Alpha 3"]); - - // A colour channel dragged onto the alphas stays where it is. - let before = h.state().session.active().unwrap().history.past_len(); - drag_to(&mut h, "Green", "Alpha 3"); - assert_eq!(alphas(&h), ["Alpha 2", "Alpha 1", "Alpha 3"]); - assert_eq!(h.state().session.active().unwrap().history.past_len(), before); - } - - /// #4689: as in Photoshop, a channel dropped on New is duplicated, on Delete deleted, and on - /// Load Channel as Selection loaded. - #[test] - fn rows_dropped_on_the_footer_duplicate_delete_and_load() { - let (mut h, _) = channels_harness(); - assert_eq!(alphas(&h), ["Alpha 1"]); - let steps = h.state().session.active().unwrap().history.past_len(); - - drag_to(&mut h, "Alpha 1", "Create new channel"); - assert_eq!(alphas(&h), ["Alpha 1", "Alpha 1 copy"]); - assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "one history step"); - drag_to(&mut h, "Red", "Create new channel"); - assert_eq!(alphas(&h), ["Alpha 1", "Alpha 1 copy", "Red copy"]); - drag_to(&mut h, "Masked Mask", "Create new channel"); - assert_eq!(alphas(&h), ["Alpha 1", "Alpha 1 copy", "Red copy", "Masked Mask copy"]); - - drag_to(&mut h, "Alpha 1 copy", "Delete current channel"); - assert_eq!(alphas(&h), ["Alpha 1", "Red copy", "Masked Mask copy"]); - // Colour channels stay: Photoshop would turn the image into Multichannel. - drag_to(&mut h, "Green", "Delete current channel"); - assert_eq!(alphas(&h), ["Alpha 1", "Red copy", "Masked Mask copy"]); - assert_eq!(h.state().session.active().unwrap().doc.mode, photocraft_doc::ColorMode::Rgb); - - assert!(h.state().session.active().unwrap().doc.selection.is_none()); - drag_to(&mut h, "Red copy", "Load channel as selection"); - assert!(h.state().session.active().unwrap().doc.selection.is_some(), "the white channel selects everything"); - } - - /// The footer follows the targeted row shown by the panel when mask painting is active, - /// even though the engine's channel-view target remains Composite. Other channel targets - /// continue to load their own values, and each load remains one undoable selection change. - #[test] - fn footer_loads_the_selected_layer_mask_and_preserves_color_alpha_targets() { - let (mut h, _) = channels_harness(); - h.state_mut().run("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 48})).unwrap(); - h.state_mut().run("layer.layerMask.hideAll", json!({})).unwrap(); - h.state_mut().run("layer.layerMask.revealSelection", json!({})).unwrap(); - h.state_mut().run("channel.target", json!({"channel": "composite"})).unwrap(); - h.state_mut().ui.mask_target = true; - h.run_steps(2); - - let click_load = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>| { - use egui::{Modifiers, PointerButton}; - let p = at(h, "Load channel as selection"); - h.hover_at(p); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); - }; - let sample = - |h: &egui_kittest::Harness<'_, PhotocraftApp>, x, y| h.state().session.active().unwrap().doc.selection.as_ref().unwrap().sample_channel(x, y, 0); - - assert_eq!(h.state().session.active().unwrap().channel_view.target, ChannelTarget::Composite); - click_load(&mut h); - assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0), "mask row selection wins over the Composite engine target"); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert!(h.state().session.active().unwrap().doc.selection.is_none()); - h.state_mut().run("edit.redo", json!({})).unwrap(); - assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0)); - - h.state_mut().ui.mask_target = false; - h.state_mut().run("channel.target", json!({"channel": "composite"})).unwrap(); - click_load(&mut h); - assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0), "composite luminosity remains available"); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0)); - h.state_mut().run("edit.redo", json!({})).unwrap(); - assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0)); - - h.state_mut().run("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 48})).unwrap(); - h.state_mut().run("channel.new", json!({"fill": "selection"})).unwrap(); - h.state_mut().run("select.deselect", json!({})).unwrap(); - h.state_mut().run("channel.target", json!({"channel": "red"})).unwrap(); - click_load(&mut h); - assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0), "color channel still loads its own plane"); - h.state_mut().run("edit.undo", json!({})).unwrap(); - h.state_mut().run("edit.redo", json!({})).unwrap(); - assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0)); - - h.state_mut().run("channel.target", json!({"channel": 1})).unwrap(); - click_load(&mut h); - assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0), "alpha channel still loads its own plane"); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0)); - h.state_mut().run("edit.redo", json!({})).unwrap(); - assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0)); - } - - /// A plain click on a row still targets it, and a drag released elsewhere does nothing. - #[test] - fn clicks_still_target_and_a_drop_elsewhere_does_nothing() { - let (mut h, _) = channels_harness(); - let p = at(&h, "Alpha 1"); - 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); - assert_eq!(h.state().session.active().unwrap().channel_view.target, ChannelTarget::Alpha(0)); - - let steps = h.state().session.active().unwrap().history.past_len(); - let (from, to) = (at(&h, "Alpha 1"), at(&h, "Blue")); - drag(&mut h, from, to); - drag_to(&mut h, "Alpha 1", "Save selection as channel"); - assert_eq!(alphas(&h), ["Alpha 1"]); - assert_eq!(h.state().session.active().unwrap().history.past_len(), steps, "nothing ran"); - assert!(h.ctx.data(|d| d.get_temp::<(Row, String)>(drag_id())).is_none(), "the drag ended"); - } - - /// Double-clicking the layer mask's row opens Layer Mask Display Options, as in Photoshop; OK - /// sets the rubylith's colour and opacity, a view setting rather than an undo step. - #[test] - fn double_clicking_the_layer_mask_row_opens_its_display_options() { - let (mut h, _) = channels_harness(); - let steps = h.state().session.active().unwrap().history.past_len(); - let p = at(&h, "Masked Mask"); - h.hover_at(p); - h.run_steps(30); - for pressed in [true, false, true, false] { - h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); - h.step(); - } - h.run_steps(3); - let d = h.state().ui.dialogs.last().expect("a dialog opens"); - assert!(crate::channel_options_ui::owns(&d.fields), "{:?}", d.fields); - assert_eq!((d.fields["channel"].clone(), d.fields["color"].clone(), d.fields["opacity"].clone()), (json!("mask"), json!("#ff0000"), json!(50.0))); - let id = d.id; - let d = h.state_mut().ui.dialog_mut(id).unwrap(); - d.fields.insert("color".into(), json!("#0000ff")); - d.fields.insert("opacity".into(), json!(80.0)); - crate::dialogs::confirm(h.state_mut(), id).unwrap(); - let o = &h.state().session.prefs().layer_mask_overlay; - assert_eq!((o.color.as_str(), o.opacity), ("#0000ff", 80.0)); - assert_eq!(h.state().session.active().unwrap().history.past_len(), steps, "no history step"); - } - - /// The layer mask's row asks "Apply mask to layer before removing?", like its Layers thumbnail. - #[test] - fn the_layer_mask_row_on_the_trash_asks_first() { - let (mut h, masked) = channels_harness(); - drag_to(&mut h, "Masked Mask", "Delete current channel"); - assert!(h.state().ui.dialogs.iter().any(|d| crate::mask_trash_prompt::owns(&d.fields)), "the prompt is open"); - let st = h.state().session.active().unwrap(); - assert!(st.doc.layer(photocraft_doc::LayerId(masked)).unwrap().mask.is_some(), "nothing deleted yet"); - } -} +mod tests; diff --git a/crates/ui-egui/src/channels_panel/tests.rs b/crates/ui-egui/src/channels_panel/tests.rs new file mode 100644 index 0000000000..428b9de1e7 --- /dev/null +++ b/crates/ui-egui/src/channels_panel/tests.rs @@ -0,0 +1,314 @@ +use super::*; + +#[test] +fn modifier_operations() { + let m = |shift, alt| egui::Modifiers { command: true, shift, alt, ..Default::default() }; + assert_eq!(load_operation(m(false, false)), "new"); + assert_eq!(load_operation(m(true, false)), "add"); + assert_eq!(load_operation(m(false, true)), "subtract"); + assert_eq!(load_operation(m(true, true)), "intersect"); +} + +#[test] +fn rename_field_interrupts_the_ime_only_when_it_takes_focus() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("channel.new", json!({})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); + let doc = app.session.active().unwrap().doc.id.0; + let name = app.session.active().unwrap().doc.channels[0].name.clone(); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique(("chan-rename", doc, format!("{:?}", Row::Alpha(0).reference()))), name)); + // The field takes focus on the first pass and owns the IME from the second on (#585). + let interrupts: Vec> = (0..4) + .map(|_| { + let mut out = ctx.run_ui(Default::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + out.platform_output.ime.map(|ime| ime.should_interrupt_composition) + }) + .collect(); + assert_eq!(interrupts, [None, Some(false), Some(false), Some(false)]); +} + +#[test] +fn channel_thumbs_honours_show_channels_in_color() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + let ctx = egui::Context::default(); + let thumbs_gray = app.channel_thumbs(&ctx); + assert!(!thumbs_gray.is_empty()); + + app.session.execute("prefs.set", json!({"values": {"interface.showChannelsInColor": true}})).unwrap(); + let thumbs_color = app.channel_thumbs(&ctx); + assert_eq!(thumbs_gray.len(), thumbs_color.len()); +} + +/// A selection-only step keeps the thumbnails; a pixel edit rebuilds them into the same +/// textures rather than new ones (#4518). +#[test] +fn channel_thumbs_skip_selection_steps_and_reuse_textures() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + let ctx = egui::Context::default(); + // Texture uploads one pass makes (new textures and updates both count). + let pass = |app: &mut PhotocraftApp| { + ctx.begin_pass(Default::default()); + let ids = app.channel_thumbs(&ctx); + let mut delta = ctx.end_pass().textures_delta; + let n = delta.set.len(); + delta.clear(); + (ids, n) + }; + let (first, uploads) = pass(&mut app); + assert!(uploads > 0); + app.run("select.rect", json!({"x": 4, "y": 4, "width": 20, "height": 20})).unwrap(); + assert_eq!(pass(&mut app), (first.clone(), 0), "a marquee changes no pixels"); + app.run("select.deselect", json!({})).unwrap(); + assert_eq!(pass(&mut app), (first.clone(), 0), "neither does Deselect"); + app.run("edit.fill", json!({"color": "#336699"})).unwrap(); + let (after, uploads) = pass(&mut app); + assert!(uploads > 0, "a fill rebuilds them"); + assert_eq!(after, first, "into the same textures"); +} + +/// The Channels tab (the Layers card's second tab) of a 64×48 white document with a layer +/// mask on "Masked" and one alpha channel. +fn channels_harness() -> (egui_kittest::Harness<'static, PhotocraftApp>, u64) { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + let masked = s.execute("layer.new.layer", json!({"name": "Masked"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.layerMask.revealAll", json!({"layer": masked})).unwrap(); + s.execute("channel.new", json!({})).unwrap(); + // 60 fps steps, so two clicks a frame apart count as a double-click. + let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 1000.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!({"dockWidth": 290.0, "dockTabs": {"layers": 1}, "dock": {"collapsed": ["color", "properties", "history", "navigator"]}}), + ); + crate::control::handle(h.state_mut(), &ctx, &req); + h.run_steps(8); + (h, masked) +} + +/// The centre of the row or button labelled `label` (not its tooltip, which a hover leaves open). +fn at(h: &egui_kittest::Harness<'_, PhotocraftApp>, label: &str) -> egui::Pos2 { + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; + h.query_all_by_label(label) + .find(|n| matches!(n.accesskit_node().role(), Role::Button | Role::ListBoxOption | Role::Label) && n.rect().height() > 20.0) + .unwrap_or_else(|| panic!("no row or button {label}")) + .rect() + .center() +} + +/// A real press, drag and release. +fn drag(h: &mut egui_kittest::Harness<'_, PhotocraftApp>, from: egui::Pos2, to: egui::Pos2) { + use egui::{Modifiers, PointerButton}; + h.hover_at(from); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + for i in 1..=6 { + h.hover_at(from + (to - from) * (i as f32 / 6.0)); + h.run_steps(1); + } + h.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); +} + +/// Drags the row or button labelled `from` onto the one labelled `to`. +fn drag_to(h: &mut egui_kittest::Harness<'_, PhotocraftApp>, from: &str, to: &str) { + let (from, to) = (at(h, from), at(h, to)); + drag(h, from, to); +} + +fn alphas(h: &egui_kittest::Harness<'_, PhotocraftApp>) -> Vec { + h.state().session.active().unwrap().doc.channels.iter().map(|c| c.name.clone()).collect() +} + +/// #9163: alpha channels reorder by dragging, as in Photoshop: a drop in a row's upper half +/// lands above it, over the colour channels it lands first among the alphas, colour channels +/// don't move, and each reorder is one history step. +#[test] +fn alpha_channels_reorder_by_dragging() { + let (mut h, _) = channels_harness(); + h.state_mut().run("channel.new", json!({"name": "Alpha 2"})).unwrap(); + h.state_mut().run("channel.new", json!({"name": "Alpha 3"})).unwrap(); + h.run_steps(3); + assert_eq!(alphas(&h), ["Alpha 1", "Alpha 2", "Alpha 3"]); + let steps = h.state().session.active().unwrap().history.past_len(); + + let (from, onto) = (at(&h, "Alpha 3"), at(&h, "Alpha 1")); + drag(&mut h, from, onto - vec2(0.0, 8.0)); + assert_eq!(alphas(&h), ["Alpha 3", "Alpha 1", "Alpha 2"]); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "one history step"); + + // The lower half of a row: below it. + let (from, onto) = (at(&h, "Alpha 3"), at(&h, "Alpha 1")); + drag(&mut h, from, onto + vec2(0.0, 8.0)); + assert_eq!(alphas(&h), ["Alpha 1", "Alpha 3", "Alpha 2"]); + + // Dropped on a colour channel: first among the alphas. + drag_to(&mut h, "Alpha 2", "Red"); + assert_eq!(alphas(&h), ["Alpha 2", "Alpha 1", "Alpha 3"]); + + // A colour channel dragged onto the alphas stays where it is. + let before = h.state().session.active().unwrap().history.past_len(); + drag_to(&mut h, "Green", "Alpha 3"); + assert_eq!(alphas(&h), ["Alpha 2", "Alpha 1", "Alpha 3"]); + assert_eq!(h.state().session.active().unwrap().history.past_len(), before); +} + +/// #4689: as in Photoshop, a channel dropped on New is duplicated, on Delete deleted, and on +/// Load Channel as Selection loaded. +#[test] +fn rows_dropped_on_the_footer_duplicate_delete_and_load() { + let (mut h, _) = channels_harness(); + assert_eq!(alphas(&h), ["Alpha 1"]); + let steps = h.state().session.active().unwrap().history.past_len(); + + drag_to(&mut h, "Alpha 1", "Create new channel"); + assert_eq!(alphas(&h), ["Alpha 1", "Alpha 1 copy"]); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "one history step"); + drag_to(&mut h, "Red", "Create new channel"); + assert_eq!(alphas(&h), ["Alpha 1", "Alpha 1 copy", "Red copy"]); + drag_to(&mut h, "Masked Mask", "Create new channel"); + assert_eq!(alphas(&h), ["Alpha 1", "Alpha 1 copy", "Red copy", "Masked Mask copy"]); + + drag_to(&mut h, "Alpha 1 copy", "Delete current channel"); + assert_eq!(alphas(&h), ["Alpha 1", "Red copy", "Masked Mask copy"]); + // Colour channels stay: Photoshop would turn the image into Multichannel. + drag_to(&mut h, "Green", "Delete current channel"); + assert_eq!(alphas(&h), ["Alpha 1", "Red copy", "Masked Mask copy"]); + assert_eq!(h.state().session.active().unwrap().doc.mode, photocraft_doc::ColorMode::Rgb); + + assert!(h.state().session.active().unwrap().doc.selection.is_none()); + drag_to(&mut h, "Red copy", "Load channel as selection"); + assert!(h.state().session.active().unwrap().doc.selection.is_some(), "the white channel selects everything"); +} + +/// The footer follows the targeted row shown by the panel when mask painting is active, +/// even though the engine's channel-view target remains Composite. Other channel targets +/// continue to load their own values, and each load remains one undoable selection change. +#[test] +fn footer_loads_the_selected_layer_mask_and_preserves_color_alpha_targets() { + let (mut h, _) = channels_harness(); + h.state_mut().run("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 48})).unwrap(); + h.state_mut().run("layer.layerMask.hideAll", json!({})).unwrap(); + h.state_mut().run("layer.layerMask.revealSelection", json!({})).unwrap(); + h.state_mut().run("channel.target", json!({"channel": "composite"})).unwrap(); + h.state_mut().ui.mask_target = true; + h.run_steps(2); + + let click_load = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>| { + use egui::{Modifiers, PointerButton}; + let p = at(h, "Load channel as selection"); + h.hover_at(p); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + }; + let sample = + |h: &egui_kittest::Harness<'_, PhotocraftApp>, x, y| h.state().session.active().unwrap().doc.selection.as_ref().unwrap().sample_channel(x, y, 0); + + assert_eq!(h.state().session.active().unwrap().channel_view.target, ChannelTarget::Composite); + click_load(&mut h); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0), "mask row selection wins over the Composite engine target"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert!(h.state().session.active().unwrap().doc.selection.is_none()); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0)); + + h.state_mut().ui.mask_target = false; + h.state_mut().run("channel.target", json!({"channel": "composite"})).unwrap(); + click_load(&mut h); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0), "composite luminosity remains available"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0)); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0)); + + h.state_mut().run("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 48})).unwrap(); + h.state_mut().run("channel.new", json!({"fill": "selection"})).unwrap(); + h.state_mut().run("select.deselect", json!({})).unwrap(); + h.state_mut().run("channel.target", json!({"channel": "red"})).unwrap(); + click_load(&mut h); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0), "color channel still loads its own plane"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0)); + + h.state_mut().run("channel.target", json!({"channel": 1})).unwrap(); + click_load(&mut h); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0), "alpha channel still loads its own plane"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 1.0)); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!((sample(&h, 8, 8), sample(&h, 48, 8)), (1.0, 0.0)); +} + +/// A plain click on a row still targets it, and a drag released elsewhere does nothing. +#[test] +fn clicks_still_target_and_a_drop_elsewhere_does_nothing() { + let (mut h, _) = channels_harness(); + let p = at(&h, "Alpha 1"); + 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); + assert_eq!(h.state().session.active().unwrap().channel_view.target, ChannelTarget::Alpha(0)); + + let steps = h.state().session.active().unwrap().history.past_len(); + let (from, to) = (at(&h, "Alpha 1"), at(&h, "Blue")); + drag(&mut h, from, to); + drag_to(&mut h, "Alpha 1", "Save selection as channel"); + assert_eq!(alphas(&h), ["Alpha 1"]); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps, "nothing ran"); + assert!(h.ctx.data(|d| d.get_temp::<(Row, String)>(drag_id())).is_none(), "the drag ended"); +} + +/// Double-clicking the layer mask's row opens Layer Mask Display Options, as in Photoshop; OK +/// sets the rubylith's colour and opacity, a view setting rather than an undo step. +#[test] +fn double_clicking_the_layer_mask_row_opens_its_display_options() { + let (mut h, _) = channels_harness(); + let steps = h.state().session.active().unwrap().history.past_len(); + let p = at(&h, "Masked Mask"); + h.hover_at(p); + h.run_steps(30); + for pressed in [true, false, true, false] { + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.step(); + } + h.run_steps(3); + let d = h.state().ui.dialogs.last().expect("a dialog opens"); + assert!(crate::channel_options_ui::owns(&d.fields), "{:?}", d.fields); + assert_eq!((d.fields["channel"].clone(), d.fields["color"].clone(), d.fields["opacity"].clone()), (json!("mask"), json!("#ff0000"), json!(50.0))); + let id = d.id; + let d = h.state_mut().ui.dialog_mut(id).unwrap(); + d.fields.insert("color".into(), json!("#0000ff")); + d.fields.insert("opacity".into(), json!(80.0)); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + let o = &h.state().session.prefs().layer_mask_overlay; + assert_eq!((o.color.as_str(), o.opacity), ("#0000ff", 80.0)); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps, "no history step"); +} + +/// The layer mask's row asks "Apply mask to layer before removing?", like its Layers thumbnail. +#[test] +fn the_layer_mask_row_on_the_trash_asks_first() { + let (mut h, masked) = channels_harness(); + drag_to(&mut h, "Masked Mask", "Delete current channel"); + assert!(h.state().ui.dialogs.iter().any(|d| crate::mask_trash_prompt::owns(&d.fields)), "the prompt is open"); + let st = h.state().session.active().unwrap(); + assert!(st.doc.layer(photocraft_doc::LayerId(masked)).unwrap().mask.is_some(), "nothing deleted yet"); +} From 3a39075d06f44b89cd28b45816e995d30ed088f1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:55 +0000 Subject: [PATCH 071/259] refactor(ui-egui): move actions.rs tests to actions/tests.rs --- crates/ui-egui/src/actions.rs | 1183 +-------------------------- crates/ui-egui/src/actions/tests.rs | 1180 ++++++++++++++++++++++++++ 2 files changed, 1181 insertions(+), 1182 deletions(-) create mode 100644 crates/ui-egui/src/actions/tests.rs diff --git a/crates/ui-egui/src/actions.rs b/crates/ui-egui/src/actions.rs index 2c5e423314..a4a5969544 100644 --- a/crates/ui-egui/src/actions.rs +++ b/crates/ui-egui/src/actions.rs @@ -1191,1185 +1191,4 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn panel_menu_lists_load_save_and_existing_action_commands() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut empty_app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - empty_app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - let mut empty = Harness::builder().with_size(vec2(240.0, 280.0)).build_ui_state(|ui, app| panel_menu(app, ui), empty_app); - empty.run_steps(2); - assert!(empty.query_all_by_label("Load Actions…").count() > 0); - assert!(empty.query_all_by_label("New Action…").count() > 0); - assert!(empty.query_all_by_label("Start Recording").count() > 0); - empty.get_by_label("New Action…").click(); - empty.run_steps(2); - assert_eq!(empty.state().session.actions.list.len(), 1); - - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - app.session.actions.list.push(Action::new("Make Layer", vec![("layer.new.layer".into(), json!({}))])); - app.ui.actions.selected = Some(0); - let mut h = Harness::builder().with_size(vec2(240.0, 320.0)).build_ui_state(|ui, app| panel_menu(app, ui), app); - h.run_steps(2); - for label in ["Load Actions…", "Save Actions…", "Insert Stop…", "Play", "Delete", "Start Recording"] { - assert!(h.query_all_by_label(label).count() > 0, "{label}"); - } - let layers = h.state().session.active().unwrap().doc.layers.len(); - h.get_by_label("Play").click(); - h.run_steps(3); - assert_eq!(h.state().session.active().unwrap().doc.layers.len(), layers + 1); - } - - #[test] - fn selected_layer_name_is_visible_during_recording_and_after_stop() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width":4,"height":4})).unwrap(); - app.run("layer.setProps", json!({"name":"Background"})).unwrap(); - let layer = app.session.active().unwrap().active_layer.unwrap(); - app.run("actions.record", json!({"name":"Select photo"})).unwrap(); - app.ui.actions.expanded = vec![true]; - app.run("layer.select", json!({"layer":layer.0})).unwrap(); - let mut h = Harness::builder().with_size(vec2(400.0, 260.0)).build_ui_state(|ui, app| panel(app, ui), app); - h.run_steps(4); - h.get_by_label("Select Layer (Background)"); - h.state_mut().run("actions.stop", json!({})).unwrap(); - h.run_steps(4); - h.get_by_label("Select Layer (Background)"); - assert_eq!(step_label("layer.select", &json!({"layer":26})), "Select Layer (ID 26)"); - assert_eq!(step_label("layer.select", &json!({"layer":"Background"})), "Select Layer (Background)"); - } - - #[test] - fn actions_list_grows_with_panel_and_keeps_footer_visible() { - use egui_kittest::{Harness, kittest::Queryable}; - let bottom = |height: f32| { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - for i in 0..50 { - app.session.actions.list.push(Action { name: format!("Action {i}"), steps: vec![], disabled: Default::default(), ..Default::default() }); - } - let mut h = Harness::builder().with_size(vec2(320.0, height)).build_ui_state(|ui, app| panel(app, ui), app); - h.run_steps(3); - let rect = h.get_by_label("Play selection").rect(); - assert!(rect.bottom() <= height, "footer must fit: {rect:?}"); - rect.top() - }; - assert!(bottom(700.0) - bottom(300.0) > 350.0, "list uses the additional panel height instead of stopping at 320 px"); - assert!(crate::dock::Group::History.scrolls_itself(1)); - } - - /// #7646: an action's function key can take Shift and Command, as in Photoshop's Action - /// Options, and only that combination plays it. - #[test] - fn a_function_key_with_shift_and_command_plays_its_action() { - use egui::{Event, Key, Modifiers}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.session.actions.list.push(Action { - name: "Action 1".into(), - steps: vec![("layer.new.layer".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - let key = photocraft_engine::atn_cmds::function_key_name(2, true, true); - assert_eq!(key, "Cmd+Shift+F2"); - assign_shortcut(&mut app, "Action 1", &key).unwrap(); - let ctx = egui::Context::default(); - let press = |app: &mut PhotocraftApp, modifiers| { - ctx.begin_pass(egui::RawInput { - events: vec![ - Event::ModifiersChanged(modifiers), - Event::Key { key: Key::F2, physical_key: None, pressed: true, repeat: false, modifiers }, - Event::Key { key: Key::F2, physical_key: None, pressed: false, repeat: false, modifiers }, - ], - ..Default::default() - }); - crate::shortcuts::handle(app, &ctx); - ctx.end_pass().textures_delta.clear(); - }; - let layers = |app: &PhotocraftApp| app.session.active().unwrap().doc.layers.len(); - let before = layers(&app); - press(&mut app, Modifiers::NONE); - press(&mut app, Modifiers::SHIFT); - assert_eq!(layers(&app), before, "F2 and Shift+F2 alone don't play it"); - press(&mut app, Modifiers::SHIFT | Modifiers::COMMAND); - assert_eq!(layers(&app), before + 1, "Cmd+Shift+F2 plays it"); - } - - #[test] - fn double_clicking_an_action_name_renames_it_in_place() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.session.actions.list.push(Action { - name: "Action 1".into(), - steps: vec![("layer.new.layer".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - let layers = app.session.active().unwrap().doc.layers.len(); - // 60 fps steps, so two clicks a frame apart count as a double-click. - let mut h = Harness::builder().with_size(vec2(320.0, 260.0)).with_step_dt(1.0 / 60.0).build_ui_state(|ui, app| panel(app, ui), app); - h.run_steps(3); - let rename = |h: &mut Harness<'_, PhotocraftApp>, text: &str| { - let name = h.get_by_label("Action 1").rect().left_center() + vec2(52.0, 0.0); - h.event(egui::Event::PointerMoved(name)); - // Wait out the double-click window of the previous attempt. - h.run_steps(30); - for pressed in [true, false, true, false] { - h.event(egui::Event::PointerButton { pos: name, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); - h.step(); - } - h.run_steps(3); - h.event(egui::Event::Text(text.into())); - h.run_steps(1); - h.key_press(egui::Key::Enter); - h.run_steps(3); - }; - // Whitespace keeps the old name and reports why. - rename(&mut h, " "); - assert_eq!(h.state().session.actions.list[0].name, "Action 1"); - assert!(h.state().ui.status_error); - rename(&mut h, "Sepia"); - assert_eq!(h.state().session.actions.list[0].name, "Sepia"); - assert_eq!(h.state().session.active().unwrap().doc.layers.len(), layers, "renaming must not play the action"); - } - - #[test] - fn play_button_targets_first_action_if_nothing_is_selected() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - assert_eq!(playback_selection(&app), None); - app.session.actions.list.push(Action { - name: "Make Layer".into(), - steps: vec![("layer.new.layer".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - app.session.actions.list.push(Action { - name: "Fit".into(), - steps: vec![("view.fitOnScreen".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - assert_eq!(playback_selection(&app), Some(0)); - app.ui.actions.selected = Some(1); - assert_eq!(playback_selection(&app), Some(1)); - app.ui.actions.selected = Some(999); - assert_eq!(playback_selection(&app), Some(0)); - - app.ui.actions.selected = None; - use egui_kittest::{Harness, kittest::Queryable}; - let mut h = Harness::builder().with_size(vec2(400.0, 320.0)).build_ui_state(|ui, app| panel(app, ui), app); - h.run_steps(3); - let before = h.state().session.active().unwrap().doc.layers.len(); - h.get_by_label("Play selection").click(); - h.run_steps(3); - assert_eq!(h.state().session.active().unwrap().doc.layers.len(), before + 1); - assert!(!h.state().ui.status_error); - } - - #[test] - fn step_check_box_excludes_the_step_from_playback_and_batch() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - let steps = ["A", "B", "C"].map(|n| ("layer.new.layer".to_string(), json!({"name": n}))); - app.session.actions.list.push(Action::new("Three", steps.to_vec())); - app.ui.actions.expanded = vec![true]; - let mut h = Harness::builder().with_size(vec2(320.0, 300.0)).build_ui_state(|ui, app| panel(app, ui), app); - h.run_steps(3); - let checks = h.query_all_by_role(egui::accesskit::Role::CheckBox).count(); - assert_eq!(checks, 3); - h.query_all_by_role(egui::accesskit::Role::CheckBox).nth(1).unwrap().click(); - h.run_steps(3); - let action = &h.state().session.actions.list[0]; - assert_eq!(action.disabled.iter().copied().collect::>(), [1]); - assert_eq!(action_steps(action).len(), 2, "Batch and droplets get only the checked steps"); - assert_eq!(step_count(3, action.disabled.len()), "2/3 steps"); - h.get_by_label("Play selection").click(); - h.run_steps(3); - let names: Vec<_> = h.state().session.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.clone()).collect(); - assert_eq!(names, ["A", "C"]); - } - - #[test] - fn playback_errors_are_visible_in_status_bar() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.session.actions.list.push(Action { - name: "Bad action".into(), - steps: vec![("not.a.command".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - let mut h = Harness::builder().with_size(vec2(400.0, 320.0)).build_ui_state(|ui, app| panel(app, ui), app); - h.run_steps(3); - h.get_by_label("Play selection").click(); - h.run_steps(3); - assert!(h.state().ui.status_error); - assert!(h.state().ui.status.contains("not.a.command") || h.state().ui.status.contains("unknown command")); - } - - #[test] - fn recording_reveals_new_action_and_latest_step_in_a_long_panel() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width":4,"height":4})).unwrap(); - for i in 0..30 { - app.session.actions.list.push(Action { name: format!("Existing {i}"), steps: vec![], disabled: Default::default(), ..Default::default() }); - } - let mut h = Harness::builder().with_size(vec2(320.0, 260.0)).build_ui_state(|ui, app| panel(app, ui), app); - h.run_steps(4); - begin_recording(h.state_mut(), false); - h.run_steps(20); - let rect = h.get_by_label("Action 31").rect(); - assert!(rect.top() >= 0.0 && rect.bottom() <= h.get_by_label("Play selection").rect().top(), "new action visible: {rect:?}"); - for _ in 0..20 { - h.state_mut().run("view.zoomOut", json!({})).unwrap(); - } - h.state_mut().run("view.fitOnScreen", json!({})).unwrap(); - h.run_steps(20); - let rect = h.get_by_label("Fit on Screen").rect(); - assert!(rect.top() >= 0.0 && rect.bottom() <= h.get_by_label("Play selection").rect().top(), "latest step visible: {rect:?}"); - } - - #[test] - fn drag_steps_and_action_headers_reorders_and_keeps_selection() { - use egui_kittest::{Harness, kittest::Queryable}; - 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!({}))], - disabled: Default::default(), - ..Default::default() - }); - app.session.actions.list.push(Action { name: "Second".into(), steps: vec![], disabled: Default::default(), ..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); - 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); - } - let from = h.get_by_label("Zoom Out").rect().center(); - let target = h.get_by_label("100%").rect(); - drag(&mut h, from, pos2(target.center().x, target.bottom() - 2.0)); - assert_eq!( - h.state().session.actions.list[0].steps.iter().map(|st| st.0.as_str()).collect::>(), - ["view.fitOnScreen", "view.actualPixels", "view.zoomOut"] - ); - assert_eq!(h.state().ui.actions.selected_step, Some(2)); - let from = h.get_by_label("Second").rect().center(); - let target = h.get_by_label("First").rect(); - drag(&mut h, from, pos2(target.center().x, target.top() + 2.0)); - assert_eq!(h.state().session.actions.list[0].name, "Second"); - assert_eq!(h.state().ui.actions.expanded, [false, true]); - assert_eq!(h.state().ui.actions.selected, Some(0)); - } - - #[test] - fn nested_shell_actions_include_view_steps_and_propagate_failures() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width":40,"height":40})).unwrap(); - app.session.actions.list.push(Action { - name: "Child".into(), - steps: vec![("layer.new.layer".into(), json!({})), ("view.fitOnScreen".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - app.run("actions.record", json!({"name":"Parent"})).unwrap(); - app.run("actions.play", json!({"action":"Child"})).unwrap(); - app.run("actions.stop", json!({})).unwrap(); - assert_eq!(app.session.actions.list[1].steps, [("actions.play".into(), json!({"action":"Child"}))]); - assert_eq!(step_label("actions.play", &json!({"action":"Child"})), "Play Action: Child"); - app.run("view.actualPixels", json!({})).unwrap(); - let r = app.run("actions.play", json!({"action":"Parent"})).unwrap(); - assert!(r.get("failed").is_none(), "{r}"); - assert!(app.ui.views[0].fit_pending); - app.session.authorize = - Some(|id, _| if id == "view.fitOnScreen" { Err(photocraft_engine::EngineError::Other("denied nested view".into())) } else { Ok(()) }); - let r = app.run("actions.play", json!({"action":"Parent"})).unwrap(); - assert!(r["failed"]["error"].as_str().unwrap().contains("denied nested view")); - assert!(app.session.actions.playback_stack.is_empty()); - assert_eq!(app.session.actions.playing, 0); - } - - #[test] - fn panel_shows_pending_steps_and_trash_deletes_only_the_clicked_step() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 40, "height": 40})).unwrap(); - begin_recording(&mut app, false); - app.run("view.fitOnScreen", json!({})).unwrap(); - app.run("view.zoomOut", json!({})).unwrap(); - let mut h = Harness::builder().with_size(vec2(320.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); - h.run_steps(2); - assert!(h.state().session.actions.recording.is_some()); - h.get_by_label("Fit on Screen"); - h.get_by_label("Zoom Out").click(); - h.run_steps(2); - assert_eq!(h.state().ui.actions.selected_step, Some(1)); - h.get_by_label("Delete").click(); - h.run_steps(2); - assert_eq!(visible_steps(h.state(), 0).iter().map(|(id, _)| id.as_str()).collect::>(), ["view.fitOnScreen"]); - assert_eq!(h.state().session.actions.list.len(), 1); - assert!(h.state().session.actions.recording.is_some()); - assert!(h.state().ui.actions.selected.is_none()); - delete_selection(h.state_mut()); - assert_eq!(h.state().session.actions.list.len(), 1, "repeated trash cannot delete the action"); - h.state_mut().run("view.zoomIn", json!({})).unwrap(); - h.run_steps(2); - h.get_by_label("Zoom In"); - h.state_mut().run("actions.stop", json!({})).unwrap(); - h.run_steps(2); - assert_eq!(visible_steps(h.state(), 0).iter().map(|(id, _)| id.as_str()).collect::>(), ["view.fitOnScreen", "view.zoomIn"]); - h.get_by_label("Zoom In").click(); - h.run_steps(2); - h.get_by_label("Delete").click(); - h.run_steps(2); - assert_eq!(visible_steps(h.state(), 0).iter().map(|(id, _)| id.as_str()).collect::>(), ["view.fitOnScreen"]); - } - - #[test] - fn view_menu_commands_record_append_and_replay_after_resize() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 160, "height": 100})).unwrap(); - begin_recording(&mut app, false); - app.run("image.canvasSize", json!({"width": 80, "height": 60})).unwrap(); - app.run("actions.stop", json!({})).unwrap(); - begin_recording(&mut app, true); - crate::menus::invoke(&mut app, &ctx, "view.fitOnScreen", json!({})).unwrap(); - app.run("actions.stop", json!({})).unwrap(); - assert_eq!(app.session.actions.list.len(), 1); - assert_eq!(app.session.actions.list[0].steps.iter().map(|s| s.0.as_str()).collect::>(), ["image.canvasSize", "view.fitOnScreen"]); - assert_eq!(label_of("view.fitOnScreen"), "Fit on Screen"); - // Persisted actions retain the menu step, and playback fits the new document. - let saved = serde_json::to_string(&app.session.actions.list).unwrap(); - app.session.actions.list = serde_json::from_str(&saved).unwrap(); - app.run("file.new", json!({"width": 200, "height": 140})).unwrap(); - app.run("view.actualPixels", json!({})).unwrap(); - let result = app.run("actions.play", json!({"action": 0})).unwrap(); - assert_eq!(result["ran"], 2); - assert!(result.get("failed").is_none(), "{result}"); - let idx = app.session.active_index().unwrap(); - assert!(app.ui.views[idx].fit_pending); - let doc = &app.session.active().unwrap().doc; - crate::canvas::fit_view(&mut app.ui.views[idx], doc, vec2(100.0, 100.0), 1.0, 1.0); - assert_eq!(app.ui.views[idx].zoom, 0.75); - assert_eq!(app.ui.views[idx].center, [40.0, 30.0]); - assert!(!app.ui.views[idx].fit_pending); - } - - #[test] - fn view_action_failure_resume_and_authorization() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.actions.list.push(Action { - name: "Fit".into(), - steps: vec![("view.fitOnScreen".into(), json!({})), ("view.actualPixels".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - let result = app.run("actions.play", json!({"action": "Fit"})).unwrap(); - assert_eq!(result["ran"], 0); - assert_eq!(result["failed"]["step"], 0); - assert_eq!(app.session.actions.playing, 0); - app.run("file.new", json!({"width": 40, "height": 40})).unwrap(); - app.session.authorize = - Some( - |id, _| { - if id == "view.fitOnScreen" { Err(photocraft_engine::EngineError::BadParams { cmd: id.into(), msg: "denied view".into() }) } else { Ok(()) } - }, - ); - let result = app.run("actions.play", json!({"action": 0})).unwrap(); - assert_eq!(result["ran"], 0); - assert!(result["failed"]["error"].as_str().unwrap().contains("denied view")); - let result = app.run("actions.play", json!({"action": 0, "from": 1})).unwrap(); - assert_eq!(result["ran"], 1); - assert!(!app.ui.views[0].fit_pending); - assert!(app.run("actions.play", json!({"action": 0, "from": -1})).is_err()); - app.session.actions.playing = 1; - assert!(app.run("actions.play", json!({"action": 0})).is_err()); - } - - #[test] - fn record_and_replay_on_another_document() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 40, "height": 40})).unwrap(); - app.sync_views(); - app.run("actions.record", json!({})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - let _ = app.run("document.pixel", json!({"x": 1, "y": 1})); - app.run("actions.stop", json!({})).unwrap(); - let a = &app.session.actions.list[0]; - assert_eq!(a.steps.iter().map(|s| s.0.as_str()).collect::>(), ["layer.new.layer", "select.rect", "edit.fill"]); - app.run("file.new", json!({"width": 40, "height": 40})).unwrap(); - app.sync_views(); - let played = app.run("actions.play", json!({"action": 0})).unwrap(); - assert_eq!(played["ran"], 3); - assert!(played.get("failed").is_none(), "{played}"); - let d = &app.session.active().unwrap().doc; - assert_eq!(d.layers.len(), 2); - assert_eq!(d.layers[1].surface().unwrap().pixel(5, 5), vec![1.0, 0.0, 0.0, 1.0]); - } - - #[test] - fn recorded_save_as_and_save_replay_and_write_the_file() { - let written = std::rc::Rc::new(std::cell::RefCell::new(Vec::::new())); - let log = written.clone(); - let services = crate::Services { - export: Some(Box::new(|doc, path, _| { - photocraft_io::export(doc, path, &Default::default()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()) - })), - write: Some(Box::new(move |path, _| { - log.borrow_mut().push(path.to_string()); - Ok(()) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - app.run("actions.record", json!({})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - crate::menus::invoke(&mut app, &ctx, "file.saveAs", json!({"path": "out/result.psd"})).unwrap(); - crate::menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap(); - app.run("actions.stop", json!({})).unwrap(); - let steps = &app.session.actions.list[0].steps; - assert_eq!(steps, &[("layer.new.layer".into(), json!({})), ("file.saveAs".into(), json!({"path": "out/result.psd"})), ("file.save".into(), json!({}))]); - written.borrow_mut().clear(); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - let played = app.run("actions.play", json!({"action": 0})).unwrap(); - assert!(played.get("failed").is_none(), "{played}"); - assert_eq!(*written.borrow(), ["out/result.psd", "out/result.psd"]); - assert_eq!(app.session.active().unwrap().path.as_deref(), Some("out/result.psd")); - } - - /// An app with the real importer/exporter and writer whose Save dialogs answer `answers`. - fn disk_app(answers: Vec>) -> PhotocraftApp { - let services = crate::Services { - import: Some(Box::new(|name, bytes, opts| { - photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()) - })), - export: Some(Box::new(|doc, path, _| { - photocraft_io::export(doc, path, &Default::default()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()) - })), - write: Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))), - file_dialog: Some(crate::file_dialog::fake(answers).0), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - app.background_jobs = false; - app - } - - /// Records Invert + File › Save on the file `a`, then plays it on the file `b` (given a - /// new layer first when `layered`). Returns the played result and whether `b` / `a` - /// changed on disk. - fn record_save_on_a_play_on_b(ext: &str, layered: bool) -> (Value, bool, bool) { - use crate::file_dialog::FileDialogAnswer::SaveTo; - let dir = std::env::temp_dir().join(format!("photocraft-rec-save-{ext}-{layered}-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = |n: &str| dir.join(format!("{n}.{ext}")).to_string_lossy().into_owned(); - let (a, b) = (path("a"), path("b")); - // The dialog confirms the suggested name, which is the document's own file. - let mut app = disk_app(vec![Some(SaveTo(a.clone())), Some(SaveTo(a.clone()))]); - let ctx = egui::Context::default(); - for p in [&a, &b] { - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - app.save_as(Some(p.clone())).unwrap(); - } - let (before_a, before_b) = (std::fs::read(&a).unwrap(), std::fs::read(&b).unwrap()); - app.open_path(&a).unwrap(); - app.run("actions.record", json!({})).unwrap(); - app.run("image.adjustments.invert", json!({})).unwrap(); - crate::menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap(); - app.poll_file_dialog(&ctx, None); - app.run("actions.stop", json!({})).unwrap(); - std::fs::write(&a, &before_a).unwrap(); - app.open_path(&b).unwrap(); - if layered { - app.run("layer.new.layer", json!({})).unwrap(); - } - let played = app.run("actions.play", json!({"action": 0})).unwrap(); - let r = (played, std::fs::read(&b).unwrap() != before_b, std::fs::read(&a).unwrap() != before_a); - let _ = std::fs::remove_dir_all(&dir); - r - } - - #[test] - fn recorded_save_overwrites_the_layered_file_the_action_is_played_on() { - let (played, b_changed, a_changed) = record_save_on_a_play_on_b("psd", false); - assert!(played.get("failed").is_none(), "{played}"); - assert!(b_changed && !a_changed); - } - - #[test] - fn recorded_save_overwrites_the_flat_file_the_action_is_played_on() { - let (played, b_changed, a_changed) = record_save_on_a_play_on_b("png", false); - assert!(played.get("failed").is_none(), "{played}"); - assert!(b_changed, "Save did not overwrite the file the action was played on"); - assert!(!a_changed, "Save wrote the file the action was recorded on"); - } - - #[test] - fn recorded_save_never_flattens_layers_over_a_flat_file() { - // The played-on document has layers its PNG can't keep: the step fails, nothing is written (#3806). - let (played, b_changed, a_changed) = record_save_on_a_play_on_b("png", true); - assert!(played.get("failed").is_some(), "{played}"); - assert!(!b_changed && !a_changed); - } - - /// Loads a Photoshop set holding Invert + a Save As into `dest` and plays it on a PSD. - /// Returns the played result, whether the PSD changed on disk and the files in `out`. - fn play_imported_save_as(dest: &str) -> (Value, bool, Vec) { - use photocraft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; - use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value as D}; - let dir = std::env::temp_dir().join(format!("photocraft-atn-save-as-{}-{}", dest.len(), std::process::id())); - let out = dir.join("out"); - std::fs::create_dir_all(&out).unwrap(); - let src = dir.join("src.psd").to_string_lossy().into_owned(); - let path = |text: &str| { - let units: Vec = text.encode_utf16().chain(std::iter::once(0)).collect(); - let mut b = b"txtu".to_vec(); - b.extend_from_slice(&((12 + units.len() * 2) as u32).to_le_bytes()); - b.extend_from_slice(&(units.len() as u32).to_le_bytes()); - units.iter().for_each(|u| b.extend_from_slice(&u.to_le_bytes())); - D::Path(b) - }; - let save = Descriptor::new("null") - .with("As ", D::Descriptor(Descriptor::new("PNGF"))) - .with("In ", path(&out.join(dest).to_string_lossy())) - .with("DocI", D::Integer(53)); - let item = |code: &[u8; 4], label: &str, d: Option| AtnItem { - event: AtnEvent::Code(*code), - dictionary: label.into(), - descriptor: d, - ..Default::default() - }; - let set = AtnFile { - name: UnicodeString::new_nul("Export"), - actions: vec![AtnAction { - name: UnicodeString::new_nul("Invert and save"), - items: vec![item(b"Invr", "Invert", None), item(b"save", "Save", Some(save))], - ..Default::default() - }], - ..Default::default() - }; - let mut app = disk_app(vec![]); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - app.save_as(Some(src.clone())).unwrap(); - let before = std::fs::read(&src).unwrap(); - app.run("actions.load", json!({"data": photocraft_engine::paint::tile::b64_encode(&photocraft_psd::atn::write(&set).unwrap())})).unwrap(); - app.open_path(&src).unwrap(); - let played = app.run("actions.play", json!({"action": 0})).unwrap(); - let mut written: Vec = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); - written.sort(); - let r = (played, std::fs::read(&src).unwrap() != before, written); - let _ = std::fs::remove_dir_all(&dir); - r - } - - #[test] - fn imported_save_as_writes_the_recorded_file_not_the_played_one() { - // #7102: the Save As imported as File › Save, which wrote over src.psd. - let (played, src_changed, written) = play_imported_save_as("result.png"); - assert!(played.get("failed").is_none(), "{played}"); - assert!(!src_changed, "the Save As wrote over the file the action was played on"); - assert_eq!(written, ["result.png"]); - } - - #[test] - fn imported_save_as_into_a_folder_stops_before_writing() { - // A folder destination isn't mapped yet (#5430): playback stops on it, nothing is saved. - let (played, src_changed, written) = play_imported_save_as("folder"); - assert!(played.get("failed").is_some(), "{played}"); - assert!(!src_changed); - assert!(written.is_empty(), "{written:?}"); - } - - #[test] - fn set_folders_group_actions_and_collapse() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut sharpen = Action::new("Sharpen", vec![("filter.sharpen.sharpen".into(), json!({}))]); - sharpen.set = Some("Retouch".into()); - let mut soften = Action::new("Soften", vec![("filter.blur.blur".into(), json!({}))]); - soften.set = Some("Retouch".into()); - app.session.actions.list.push(Action::new("Loose", vec![])); - app.session.actions.list.push(sharpen); - app.session.actions.list.push(Action::new("Also loose", vec![])); - app.session.actions.list.push(soften); - let mut h = Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); - h.run_steps(3); - // The folder row shows the set with its count; its actions sit under it, loose ones first. - let folder = h.get_by_label("Retouch").rect(); - assert!(h.get_by_label("Loose").rect().top() < folder.top()); - assert!(h.get_by_label("Also loose").rect().top() < folder.top()); - assert!(h.get_by_label("Sharpen").rect().top() > folder.top()); - assert!(h.get_by_label("Soften").rect().top() > h.get_by_label("Sharpen").rect().top()); - assert_eq!(display_order(&[]), Vec::::new()); - // Clicking the folder collapses it; its actions disappear and the state is remembered. - h.get_by_label("Retouch").click(); - h.run_steps(3); - assert_eq!(h.state().ui.actions.collapsed_sets, ["Retouch"]); - assert!(h.query_by_label("Sharpen").is_none()); - assert!(h.query_by_label("Loose").is_some()); - h.get_by_label("Retouch").click(); - h.run_steps(3); - assert!(h.state().ui.actions.collapsed_sets.is_empty()); - assert!(h.query_by_label("Sharpen").is_some()); - } - - #[test] - fn moving_an_action_next_to_another_set_joins_it() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut a = Action::new("A", vec![]); - a.set = Some("One".into()); - let mut b = Action::new("B", vec![]); - b.set = Some("Two".into()); - app.session.actions.list.push(a); - app.session.actions.list.push(b); - app.session.actions.list.push(Action::new("C", vec![])); - // C dropped below B: it joins B's set, "Two". - move_row(&mut app, DragRow { action: 2, step: None }, 2); - assert_eq!(app.session.actions.list[2].set.as_deref(), Some("Two")); - // B dropped to the top, above A: the row below decides when there is none above. - move_row(&mut app, DragRow { action: 1, step: None }, 0); - assert_eq!((app.session.actions.list[0].name.as_str(), app.session.actions.list[0].set.as_deref()), ("B", Some("One"))); - // C dropped between A (One) and nothing: the row above wins. - move_row(&mut app, DragRow { action: 2, step: None }, 2); - assert_eq!((app.session.actions.list[2].name.as_str(), app.session.actions.list[2].set.as_deref()), ("C", Some("One"))); - } - - #[test] - fn insert_stop_dialog_adds_a_stop_after_the_selected_step() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - app.session.actions.list.push(Action::new("A", vec![("select.all".into(), json!({})), ("select.inverse".into(), json!({}))])); - assert!(insert_stop_dialog(&mut app).is_err(), "needs a selected action"); - app.ui.actions.selected = Some(0); - app.ui.actions.selected_step = Some(0); - let id = insert_stop_dialog(&mut app).unwrap()["dialog"].as_u64().unwrap(); - let d = app.ui.dialog_mut(id).unwrap(); - assert!(owns_insert_stop(&d.fields)); - assert_eq!(d.fields["at"], 1); - d.fields.insert("message".into(), json!("Check the mask")); - d.fields.insert("allowContinue".into(), json!(true)); - crate::dialogs::confirm(&mut app, id).unwrap(); - let steps = &app.session.actions.list[0].steps; - assert_eq!(steps[1], (photocraft_engine::atn_cmds::STOP_MESSAGE.to_string(), json!({"message": "Check the mask", "allowContinue": true}))); - assert_eq!((app.ui.actions.selected, app.ui.actions.selected_step), (Some(0), Some(1))); - assert_eq!(step_label(&steps[1].0, &steps[1].1), "Stop: Check the mask"); - // Without a selected step the stop goes last; the panel's menu wiring is exercised by name. - app.ui.actions.selected_step = None; - let id = insert_stop_dialog(&mut app).unwrap()["dialog"].as_u64().unwrap(); - assert_eq!(app.ui.dialog_mut(id).unwrap().fields["at"], 3); - crate::dialogs::cancel(&mut app, id).unwrap(); - assert_eq!(app.session.actions.list[0].steps.len(), 3); - } - - #[test] - fn dialog_worker_failure_stops_action_before_following_steps() { - for (background, locked) in [(true, true), (false, true), (true, false)] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 6, "background": "#203040"})).unwrap(); - let mut action = Action::new( - "Worker Result", - vec![ - ("layer.setProps".into(), json!({"name": "Prefix", "locks": {"pixels": locked}})), - ("filter.blur.gaussianBlur".into(), json!({"radius": 1.5})), - ("layer.new.layer".into(), json!({"name": "Suffix"})), - ], - ); - action.dialogs.insert(1); - app.session.actions.list.push(action); - app.background_jobs = background; - let paused = play(&mut app, &json!({"action": "Worker Result"})).unwrap(); - let dialog = paused["paused"]["dialog"].as_u64().unwrap(); - let result = crate::dialogs::confirm(&mut app, dialog); - let suffix = app.session.active().unwrap().doc.walk().iter().any(|(_, _, layer)| layer.name == "Suffix"); - - assert_eq!(suffix, !locked, "background={background}, locked={locked}: {result:?}"); - if locked && background { - assert!(result.as_ref().is_err_and(|e| e.contains("locked")), "failed worker must fail the dialog confirmation: {result:?}"); - assert!(app.ui.status_error, "the action must report the worker failure"); - assert!(app.ui.status.contains("locked"), "{}", app.ui.status); - assert_eq!(app.session.jobs_with_recent()[0].state, "failed"); - } else if locked { - assert!(result.is_err(), "the foreground command rejects the locked layer"); - } else { - assert!(result.is_ok(), "the successful worker lets the action continue: {result:?}"); - } - assert_eq!(app.session.actions.playing, 0); - assert!(app.session.actions.playback_stack.is_empty()); - } - } - - #[test] - fn a_dialog_toggled_step_pauses_playback_and_resumes_on_ok() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - let mut a = Action::new( - "Blur", - vec![("layer.new.layer".into(), json!({})), ("filter.blur.gaussianBlur".into(), json!({"radius": 3})), ("select.all".into(), json!({}))], - ); - a.dialogs.insert(1); - app.session.actions.list.push(a); - let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); - assert_eq!(v["ran"], 1, "{v}"); - assert_eq!(v["paused"]["step"], 1); - let id = v["paused"]["dialog"].as_u64().unwrap(); - let d = app.ui.dialog_mut(id).unwrap(); - assert_eq!(d.fields["radius"], 3, "the dialog opens on the recorded values"); - assert!(d.fields[RESUME].is_u64(), "the dialog carries only the pause's token: {}", d.fields[RESUME]); - assert!(app.session.active().unwrap().doc.selection.is_none(), "nothing after the dialog ran yet"); - report_play(&mut app, &v); - assert!(app.ui.status.contains("dialog"), "{}", app.ui.status); - // OK runs the blur with the dialog's values and plays the rest. - app.ui.dialog_mut(id).unwrap().fields.insert("radius".into(), json!(5)); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert!(app.ui.dialogs.is_empty()); - assert!(app.session.active().unwrap().doc.selection.is_some(), "the step after the dialog ran"); - assert!(app.ui.status.starts_with("Played"), "{}", app.ui.status); - // Cancel stops the action there. - app.run("select.deselect", json!({})).unwrap(); - let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); - let id = v["paused"]["dialog"].as_u64().unwrap(); - crate::dialogs::cancel(&mut app, id).unwrap(); - assert!(app.session.active().unwrap().doc.selection.is_none()); - assert!(app.ui.status.contains("stopped"), "{}", app.ui.status); - // With background jobs (the desktop default) the resumed steps wait for the dialog's - // filter to land instead of meeting a locked document. - app.background_jobs = true; - let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); - let id = v["paused"]["dialog"].as_u64().unwrap(); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert!(app.session.active().unwrap().doc.selection.is_some(), "the step after the background blur ran"); - assert!(app.ui.status.starts_with("Played"), "{}", app.ui.status); - app.background_jobs = false; - // Agents play headlessly: no pause, the recorded values run. - app.automation_input = true; - let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); - assert_eq!(v["ran"], 3, "{v}"); - assert!(v.get("paused").is_none()); - } - - /// An 8×6 document, a Child action whose first step (a blur) shows its dialog and whose - /// second step adds a "Suffix" layer, and recording into Owner started. - fn recording_with_dialog_child() -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 6, "background": "#203040"})).unwrap(); - let mut child = - Action::new("Child", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1.5})), ("layer.new.layer".into(), json!({"name": "Suffix"}))]); - child.dialogs.insert(0); - app.session.actions.list.push(child); - app.run("actions.record", json!({"name": "Owner"})).unwrap(); - app - } - - fn suffixes(app: &PhotocraftApp) -> usize { - app.session.active().unwrap().doc.walk().iter().filter(|(_, _, l)| l.name == "Suffix").count() - } - - fn child_call() -> Vec<(String, Value)> { - vec![("actions.play".to_string(), json!({"action": "Child"}))] - } - - /// Play Child and return the id of its step dialog. - fn pause_child(app: &mut PhotocraftApp) -> u64 { - let v = play(app, &json!({"action": "Child"})).unwrap(); - v["paused"]["dialog"].as_u64().unwrap() - } - - #[test] - fn a_recorded_call_paused_by_a_dialog_records_one_call_and_replays_once() { - let mut app = recording_with_dialog_child(); - let refusal = crate::i18n::t("Confirm or cancel the open action step dialog first").to_string(); - - // Confirm: the dialog command and the resumed rest stay inside the one named call. - let live = app.session.journal.len(); - let id = pause_child(&mut app); - assert!(app.session.actions.recording.is_none(), "recording stays suspended while the step dialog is open"); - let names = |app: &PhotocraftApp| app.session.actions.list.iter().map(|a| a.name.clone()).collect::>(); - let before = names(&app); - assert_eq!(app.run("actions.record", json!({"name": "Intruder"})), Err(refusal.clone()), "no second recording while the call is suspended"); - assert_eq!(app.run("actions.delete", json!({"action": "Owner"})), Err(refusal.clone()), "the suspended owner can't be deleted"); - assert_eq!(app.run("actions.move", json!({"action": "Owner", "to": 0})), Err(refusal.clone()), "the suspended owner can't be moved"); - assert_eq!(names(&app), before, "the refused commands leave the list alone"); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert!(app.session.actions.recording.is_some(), "recording comes back when the call completes"); - app.run("actions.stop", json!({})).unwrap(); - assert_eq!(app.session.actions.list[1].steps, child_call()); - assert_eq!(suffixes(&app), 1); - - // Replaying the recording repeats the call once. - app.run("file.new", json!({"width": 8, "height": 6})).unwrap(); - let start = app.session.journal.len(); - app.automation_input = true; - let v = play(&mut app, &json!({"action": "Owner"})).unwrap(); - app.automation_input = false; - assert!(v.get("failed").is_none(), "{v}"); - assert_eq!(suffixes(&app), 1, "replay creates the suffix once"); - let edits = |from: usize| -> Vec<(String, Value)> { - app.session.journal[from..].iter().filter(|(id, _)| !id.starts_with("actions.") && id != "file.new").cloned().collect() - }; - let expected = vec![("filter.blur.gaussianBlur".to_string(), json!({"radius": 1.5})), ("layer.new.layer".to_string(), json!({"name": "Suffix"}))]; - assert_eq!(edits(start), expected, "replay journals the blur and the suffix once each, in order"); - assert_eq!(edits(live), expected[..].iter().chain(&expected).cloned().collect::>(), "live then replay"); - - // Cancel: the call ends at the dialog and is recorded once. - app.run("actions.record", json!({"name": "Cancelled"})).unwrap(); - let id = pause_child(&mut app); - crate::dialogs::cancel(&mut app, id).unwrap(); - assert!(app.session.actions.recording.is_some(), "cancel restores recording"); - app.run("actions.stop", json!({})).unwrap(); - assert_eq!(app.session.actions.list[2].steps, child_call()); - } - - #[test] - fn a_failing_step_dialog_command_ends_the_recorded_call_once() { - let mut app = recording_with_dialog_child(); - let id = pause_child(&mut app); - assert!(app.session.actions.recording.is_none(), "recording stays suspended while the step dialog is open"); - app.ui.dialog_mut(id).unwrap().fields.insert("radius".into(), json!("not a radius")); - assert!(crate::dialogs::confirm(&mut app, id).is_err(), "the dialog command fails"); - assert!(app.session.actions.recording.is_some(), "recording comes back when the dialog command fails"); - assert_eq!(suffixes(&app), 0, "the action stops at the failed step"); - app.run("actions.stop", json!({})).unwrap(); - assert_eq!(app.session.actions.list[1].steps, child_call()); - } - - #[test] - fn an_abandoned_step_dialog_leaves_no_paused_playback() { - let mut app = recording_with_dialog_child(); - let id = pause_child(&mut app); - app.ui.dialog_mut(id).unwrap().fields.insert("radius".into(), json!("not a radius")); - assert!(crate::dialogs::confirm(&mut app, id).is_err(), "the dialog command fails"); - assert!(app.paused_playbacks.paused.is_empty(), "the failed dialog ends its pause"); - app.run("actions.stop", json!({})).unwrap(); - assert_eq!(app.session.actions.list[1].steps, child_call(), "the call is recorded once"); - app.run("actions.record", json!({"name": "Next"})).unwrap(); - } - - #[test] - fn a_failing_resumed_playback_ends_the_recorded_call_once() { - let mut app = recording_with_dialog_child(); - let id = pause_child(&mut app); - // The rest of the call can't be found any more: resuming it fails. - app.session.actions.list[0].name = "Renamed".into(); - assert!(crate::dialogs::confirm(&mut app, id).is_err(), "the resumed playback fails"); - assert!(app.session.actions.recording.is_some(), "recording comes back when the resumed playback fails"); - app.run("actions.stop", json!({})).unwrap(); - assert_eq!(app.session.actions.list[1].steps, child_call()); - } - - #[test] - fn a_suspended_call_is_recorded_into_its_action_after_the_list_changes() { - let mut app = recording_with_dialog_child(); - let id = pause_child(&mut app); - // Something else puts an action where Owner was. - app.session.actions.list.insert(1, Action::new("Bystander", vec![])); - crate::dialogs::confirm(&mut app, id).unwrap(); - app.run("actions.stop", json!({})).unwrap(); - assert!(app.session.actions.list[1].steps.is_empty(), "the action now at the old index gets nothing"); - assert_eq!(app.session.actions.list[2].name, "Owner"); - assert_eq!(app.session.actions.list[2].steps, child_call()); - } - - #[test] - fn escape_on_a_step_dialog_ends_the_recorded_call_once() { - let app = recording_with_dialog_child(); - let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.run_steps(2); - pause_child(h.state_mut()); - h.run_steps(4); - assert!(h.state().session.actions.recording.is_none(), "recording stays suspended while the step dialog is open"); - h.key_press(egui::Key::Escape); - h.run_steps(2); - assert!(h.state().ui.dialogs.is_empty(), "Esc closes the step dialog"); - assert!(h.state().session.actions.recording.is_some(), "Esc restores recording"); - let app = h.state_mut(); - app.run("actions.stop", json!({})).unwrap(); - assert_eq!(app.session.actions.list[1].steps, child_call()); - } - - #[test] - fn a_step_dialog_keeps_its_continuation_token() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.background_jobs = false; - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - for (name, steps) in [ - ("First", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1}))]), - ("Second", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1})), ("select.all".into(), json!({}))]), - ] { - let mut action = Action::new(name, steps); - action.dialogs.insert(0); - app.session.actions.list.push(action); - } - let first = play(&mut app, &json!({"action": "First"})).unwrap()["paused"]["dialog"].as_u64().unwrap(); - let second = play(&mut app, &json!({"action": "Second"})).unwrap()["paused"]["dialog"].as_u64().unwrap(); - let first_token = app.ui.dialog_mut(first).unwrap().fields[RESUME].clone(); - let second_token = app.ui.dialog_mut(second).unwrap().fields[RESUME].clone(); - for token in [second_token.clone(), Value::Null, json!("invalid"), json!({"action": "Second", "from": 1})] { - let (request, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"dialog": first, "field": RESUME, "value": token})); - let response = crate::control::handle(&mut app, &egui::Context::default(), &request); - assert!(matches!(response, crate::control::Outcome::Done(ref v) if v["error"].as_str().is_some_and(|e| e.contains("read-only")))); - assert_eq!(app.ui.dialog_mut(first).unwrap().fields[RESUME], first_token); - assert_eq!(app.ui.dialog_mut(second).unwrap().fields[RESUME], second_token); - assert_eq!(app.paused_playbacks.paused.len(), 2); - } - crate::dialogs::confirm(&mut app, first).unwrap(); - assert!(app.session.active().unwrap().doc.selection.is_none(), "First must not run Second's remaining step"); - crate::dialogs::confirm(&mut app, second).unwrap(); - assert!(app.session.active().unwrap().doc.selection.is_some()); - assert!(app.paused_playbacks.paused.is_empty()); - } - - fn recording_with_displace_child() -> PhotocraftApp { - let mut app = recording_with_dialog_child(); - app.background_jobs = false; - app.session.actions.list[0].steps[0] = ("filter.distort.displace".into(), json!({})); - app - } - - fn assert_displace_call_finished(app: &mut PhotocraftApp, suffix_count: usize) { - assert!(!app.file_dialog_open()); - assert!(app.ui.dialogs.is_empty()); - assert!(app.paused_playbacks.paused.is_empty()); - assert!(app.session.actions.recording.is_some()); - assert_eq!(suffixes(app), suffix_count); - app.run("actions.stop", json!({})).unwrap(); - assert_eq!(app.session.actions.list[1].steps, child_call(), "record the child call exactly once"); - app.run("actions.record", json!({"name": "Next"})).unwrap(); - } - - #[test] - fn a_displace_step_restores_recording_when_the_map_picker_fails_or_is_cancelled() { - use crate::file_dialog::FileDialogAnswer; - let dir = tempfile::tempdir().unwrap(); - let missing = dir.path().join("missing.png").to_string_lossy().into_owned(); - for answer in [ - None, - Some(FileDialogAnswer::Unavailable("no picker available".into())), - Some(FileDialogAnswer::Paths(Vec::new())), - Some(FileDialogAnswer::Contents("map.png".into(), Vec::new())), - Some(FileDialogAnswer::Paths(vec![missing])), - ] { - let mut app = recording_with_displace_child(); - let (show, _) = crate::file_dialog::fake(vec![answer]); - app.services.file_dialog = Some(show); - let id = pause_child(&mut app); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert!(app.file_dialog_open()); - assert!(app.session.actions.recording.is_none()); - app.poll_file_dialog(&egui::Context::default(), None); - assert_displace_call_finished(&mut app, 0); - } - } - - #[test] - fn a_displace_step_restores_recording_when_the_map_picker_cannot_start() { - let mut app = recording_with_displace_child(); - let id = pause_child(&mut app); - assert!(crate::dialogs::confirm(&mut app, id).is_err()); - assert_displace_call_finished(&mut app, 0); - } - - #[test] - fn a_displace_step_resumes_and_records_its_call_once_after_choosing_a_map() { - let mut app = recording_with_displace_child(); - let dir = tempfile::tempdir().unwrap(); - let map = dir.path().join("map.png"); - let bytes = photocraft_io::export(&app.session.active().unwrap().doc, "png", &Default::default()).unwrap().bytes; - std::fs::write(&map, bytes).unwrap(); - let (show, _) = crate::file_dialog::fake(vec![Some(crate::file_dialog::FileDialogAnswer::Paths(vec![map.to_string_lossy().into_owned()]))]); - app.services.file_dialog = Some(show); - let id = pause_child(&mut app); - crate::dialogs::confirm(&mut app, id).unwrap(); - app.poll_file_dialog(&egui::Context::default(), None); - assert_displace_call_finished(&mut app, 1); - } - - #[test] - fn a_step_dialog_takes_only_the_steps_values() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - let mut a = Action::new("Blur", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 2, "__command": "select.all", "__label": "Other"}))]); - a.dialogs.insert(0); - app.session.actions.list.push(a); - let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); - let d = app.ui.dialog_mut(v["paused"]["dialog"].as_u64().unwrap()).unwrap(); - assert_eq!(d.fields["radius"], 2); - assert_eq!(d.fields["__command"], "filter.blur.gaussianBlur"); - assert_ne!(d.fields["__label"], "Other"); - } - - fn deny_blur(id: &str, _: &Value) -> photocraft_engine::Result<()> { - if id == "filter.blur.gaussianBlur" { Err(photocraft_engine::EngineError::Other("blur denied".into())) } else { Ok(()) } - } - - #[test] - fn a_step_the_gate_denies_opens_no_dialog() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - let mut a = Action::new("Blur", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1}))]); - a.dialogs.insert(0); - app.session.actions.list.push(a); - app.session.authorize = Some(deny_blur); - let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); - app.session.authorize = None; - assert!(v["failed"]["error"].as_str().is_some_and(|e| e.contains("blur denied")), "{v}"); - assert!(app.ui.dialogs.is_empty(), "no step dialog opened"); - assert!(app.paused_playbacks.paused.is_empty()); - } - - fn deny_select_all(id: &str, _: &Value) -> photocraft_engine::Result<()> { - if id == "select.all" { Err(photocraft_engine::EngineError::Other("select.all denied".into())) } else { Ok(()) } - } - - /// An action an automation client plays (`control::handle` installs the gate, then removes - /// it) pauses at a step dialog; confirming the dialog later, here with synthetic Enter or - /// OK, runs the remaining steps under the same gate. - #[test] - fn a_paused_playback_keeps_its_automation_gate_when_the_dialog_is_confirmed() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - let mut a = Action::new("Seeded", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1})), ("select.all".into(), json!({}))]); - a.dialogs.insert(0); - app.session.actions.list.push(a); - app.session.authorize = Some(deny_select_all); - let v = play(&mut app, &json!({"action": "Seeded"})).unwrap(); - app.session.authorize = None; - let id = v["paused"]["dialog"].as_u64().unwrap(); - app.automation_input = true; - let _ = crate::dialogs::confirm(&mut app, id); - app.automation_input = false; - assert!(app.session.active().unwrap().doc.selection.is_none(), "the denied step did not run"); - assert!(app.ui.status.contains("select.all denied"), "{}", app.ui.status); - } - - /// The dialog names only its pause: changing its fields can't resume another action. - #[test] - fn a_step_dialog_resumes_only_the_playback_that_paused_it() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - let mut a = Action::new("Blur", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1}))]); - a.dialogs.insert(0); - app.session.actions.list.push(a); - app.session.actions.list.push(Action::new("Seeded", vec![("select.all".into(), json!({}))])); - let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); - let id = v["paused"]["dialog"].as_u64().unwrap(); - app.ui.dialog_mut(id).unwrap().fields.insert(RESUME.into(), json!({"action": "Seeded", "from": 0})); - let r = crate::dialogs::confirm(&mut app, id); - assert!(app.session.active().unwrap().doc.selection.is_none(), "the other action did not play"); - assert!(r.is_err_and(|e| e.contains("paused action"))); - } - - #[test] - fn button_mode_plays_the_clicked_action_and_hides_its_steps() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - app.session.actions.list.push(Action::new("Print", vec![("layer.new.layer".into(), json!({}))])); - app.session.actions.list[0].color = "blue".into(); - app.ui.actions.expanded = vec![true]; - app.ui.actions.button_mode = true; - let mut h = Harness::builder().with_size(vec2(420.0, 280.0)).build_ui_state(|ui, app| panel(app, ui), app); - h.run_steps(3); - assert_eq!(h.query_all_by_role(egui::accesskit::Role::CheckBox).count(), 0, "button mode hides the step list"); - let before = h.state().session.active().unwrap().doc.layers.len(); - h.get_by_label("Print").click(); - h.run_steps(3); - assert_eq!(h.state().session.active().unwrap().doc.layers.len(), before + 1, "a click plays the action"); - h.get_by_label("Button Mode On").click(); - h.run_steps(2); - assert!(!h.state().ui.actions.button_mode); - assert!(h.query_by_label("Button Mode").is_some()); - assert_eq!(h.query_all_by_role(egui::accesskit::Role::CheckBox).count(), 1, "the step list returns when Button Mode is turned off"); - } - - /// An imported Close with Save: Yes plays as Save then Close. A Save Document script event - /// that closes the saved document stops playback, so the Close never reaches another dirty - /// document (#7367). - #[test] - fn save_hook_closing_the_target_stops_an_imported_close_with_save() { - use photocraft_psd::atn::{self, AtnEvent, AtnItem}; - use photocraft_psd::descriptor::{Descriptor, Id, Value as D}; - use std::{cell::RefCell, rc::Rc}; - // A one-step .atn: Close (`Cls `) with Save: Yes. - let seed = Action::new("Seed", vec![("layer.new.layer".into(), json!({}))]); - let (bytes, _) = photocraft_engine::atn_cmds::export("Set", &[&seed], &[], false).unwrap(); - let mut f = atn::parse(&bytes).unwrap(); - f.actions[0].items = vec![AtnItem { - event: AtnEvent::Code(*b"Cls "), - dictionary: "Close".into(), - descriptor: Some(Descriptor::new("null").with("Svng", D::Enumerated { type_id: Id::new("YsN "), value: Id::new("Ys ") })), - ..Default::default() - }]; - let imported = photocraft_engine::atn_cmds::import(&atn::write(&f).unwrap()).unwrap(); - let close_with_save = imported.actions[0].clone(); - assert_eq!(close_with_save.steps, [("file.save".into(), json!({})), ("file.close".into(), json!({}))]); - for hook in ["none", "activate", "close"] { - let writes = Rc::new(RefCell::new(Vec::::new())); - let w = writes.clone(); - let services = crate::Services { - export: Some(Box::new(|doc, _, _| Ok((doc.name.clone().into_bytes(), Vec::new())))), - write: Some(Box::new(move |path, _| { - w.borrow_mut().push(path.to_string()); - Ok(()) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - // B is dirty with an unsaved KeepB layer; A is active and has its own file. - for name in ["B", "A"] { - app.run("file.new", json!({"name": name, "width": 2, "height": 2})).unwrap(); - } - assert!(app.session.set_active(0)); - app.run("layer.new.layer", json!({"name": "KeepB"})).unwrap(); - assert!(app.session.set_active(1)); - app.session.active_mut().unwrap().path = Some("A.psd".into()); - app.session.actions.list.push(close_with_save.clone()); - let steps = match hook { - "activate" => json!([["document.activate", {"document": 0}]]), - "close" => json!([["file.close", {}]]), - _ => Value::Null, - }; - if !steps.is_null() { - app.run("file.scripts.scriptEventsManager", json!({"add": {"event": "saveDocument", "steps": steps}})).unwrap(); - } - let r = app.run("actions.play", json!({"action": 0})).unwrap(); - assert_eq!(*writes.borrow(), ["A.psd"], "hook={hook}: A is saved once"); - let names: Vec> = app.session.documents().iter().map(|d| d.doc.layers.iter().map(|l| l.name.clone()).collect()).collect(); - assert_eq!(app.session.documents().len(), 1, "hook={hook}: only A closes; result={r}"); - assert_eq!(app.session.active().unwrap().doc.name, "B", "hook={hook}"); - assert_eq!(names, [["Background", "KeepB"]], "hook={hook}: B stays open with its unsaved layer"); - if hook == "close" { - assert_eq!(r["failed"]["step"], 0, "{r}"); - assert_eq!(r["failed"]["id"], "file.save", "{r}"); - assert!(r["failed"]["error"].as_str().unwrap().contains("closed during the save"), "{r}"); - } else { - assert!(r.get("failed").is_none(), "hook={hook}: {r}"); - } - assert_eq!(app.session.actions.playing, 0); - assert!(app.session.actions.playback_stack.is_empty()); - } - } -} +mod tests; diff --git a/crates/ui-egui/src/actions/tests.rs b/crates/ui-egui/src/actions/tests.rs new file mode 100644 index 0000000000..3286a65e09 --- /dev/null +++ b/crates/ui-egui/src/actions/tests.rs @@ -0,0 +1,1180 @@ +use super::*; + +#[test] +fn panel_menu_lists_load_save_and_existing_action_commands() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut empty_app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + empty_app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut empty = Harness::builder().with_size(vec2(240.0, 280.0)).build_ui_state(|ui, app| panel_menu(app, ui), empty_app); + empty.run_steps(2); + assert!(empty.query_all_by_label("Load Actions…").count() > 0); + assert!(empty.query_all_by_label("New Action…").count() > 0); + assert!(empty.query_all_by_label("Start Recording").count() > 0); + empty.get_by_label("New Action…").click(); + empty.run_steps(2); + assert_eq!(empty.state().session.actions.list.len(), 1); + + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.session.actions.list.push(Action::new("Make Layer", vec![("layer.new.layer".into(), json!({}))])); + app.ui.actions.selected = Some(0); + let mut h = Harness::builder().with_size(vec2(240.0, 320.0)).build_ui_state(|ui, app| panel_menu(app, ui), app); + h.run_steps(2); + for label in ["Load Actions…", "Save Actions…", "Insert Stop…", "Play", "Delete", "Start Recording"] { + assert!(h.query_all_by_label(label).count() > 0, "{label}"); + } + let layers = h.state().session.active().unwrap().doc.layers.len(); + h.get_by_label("Play").click(); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), layers + 1); +} + +#[test] +fn selected_layer_name_is_visible_during_recording_and_after_stop() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width":4,"height":4})).unwrap(); + app.run("layer.setProps", json!({"name":"Background"})).unwrap(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.run("actions.record", json!({"name":"Select photo"})).unwrap(); + app.ui.actions.expanded = vec![true]; + app.run("layer.select", json!({"layer":layer.0})).unwrap(); + let mut h = Harness::builder().with_size(vec2(400.0, 260.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(4); + h.get_by_label("Select Layer (Background)"); + h.state_mut().run("actions.stop", json!({})).unwrap(); + h.run_steps(4); + h.get_by_label("Select Layer (Background)"); + assert_eq!(step_label("layer.select", &json!({"layer":26})), "Select Layer (ID 26)"); + assert_eq!(step_label("layer.select", &json!({"layer":"Background"})), "Select Layer (Background)"); +} + +#[test] +fn actions_list_grows_with_panel_and_keeps_footer_visible() { + use egui_kittest::{Harness, kittest::Queryable}; + let bottom = |height: f32| { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for i in 0..50 { + app.session.actions.list.push(Action { name: format!("Action {i}"), steps: vec![], disabled: Default::default(), ..Default::default() }); + } + let mut h = Harness::builder().with_size(vec2(320.0, height)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(3); + let rect = h.get_by_label("Play selection").rect(); + assert!(rect.bottom() <= height, "footer must fit: {rect:?}"); + rect.top() + }; + assert!(bottom(700.0) - bottom(300.0) > 350.0, "list uses the additional panel height instead of stopping at 320 px"); + assert!(crate::dock::Group::History.scrolls_itself(1)); +} + +/// #7646: an action's function key can take Shift and Command, as in Photoshop's Action +/// Options, and only that combination plays it. +#[test] +fn a_function_key_with_shift_and_command_plays_its_action() { + use egui::{Event, Key, Modifiers}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.session.actions.list.push(Action { + name: "Action 1".into(), + steps: vec![("layer.new.layer".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + let key = photocraft_engine::atn_cmds::function_key_name(2, true, true); + assert_eq!(key, "Cmd+Shift+F2"); + assign_shortcut(&mut app, "Action 1", &key).unwrap(); + let ctx = egui::Context::default(); + let press = |app: &mut PhotocraftApp, modifiers| { + ctx.begin_pass(egui::RawInput { + events: vec![ + Event::ModifiersChanged(modifiers), + Event::Key { key: Key::F2, physical_key: None, pressed: true, repeat: false, modifiers }, + Event::Key { key: Key::F2, physical_key: None, pressed: false, repeat: false, modifiers }, + ], + ..Default::default() + }); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); + }; + let layers = |app: &PhotocraftApp| app.session.active().unwrap().doc.layers.len(); + let before = layers(&app); + press(&mut app, Modifiers::NONE); + press(&mut app, Modifiers::SHIFT); + assert_eq!(layers(&app), before, "F2 and Shift+F2 alone don't play it"); + press(&mut app, Modifiers::SHIFT | Modifiers::COMMAND); + assert_eq!(layers(&app), before + 1, "Cmd+Shift+F2 plays it"); +} + +#[test] +fn double_clicking_an_action_name_renames_it_in_place() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.session.actions.list.push(Action { + name: "Action 1".into(), + steps: vec![("layer.new.layer".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + let layers = app.session.active().unwrap().doc.layers.len(); + // 60 fps steps, so two clicks a frame apart count as a double-click. + let mut h = Harness::builder().with_size(vec2(320.0, 260.0)).with_step_dt(1.0 / 60.0).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(3); + let rename = |h: &mut Harness<'_, PhotocraftApp>, text: &str| { + let name = h.get_by_label("Action 1").rect().left_center() + vec2(52.0, 0.0); + h.event(egui::Event::PointerMoved(name)); + // Wait out the double-click window of the previous attempt. + h.run_steps(30); + for pressed in [true, false, true, false] { + h.event(egui::Event::PointerButton { pos: name, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.step(); + } + h.run_steps(3); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(3); + }; + // Whitespace keeps the old name and reports why. + rename(&mut h, " "); + assert_eq!(h.state().session.actions.list[0].name, "Action 1"); + assert!(h.state().ui.status_error); + rename(&mut h, "Sepia"); + assert_eq!(h.state().session.actions.list[0].name, "Sepia"); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), layers, "renaming must not play the action"); +} + +#[test] +fn play_button_targets_first_action_if_nothing_is_selected() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + assert_eq!(playback_selection(&app), None); + app.session.actions.list.push(Action { + name: "Make Layer".into(), + steps: vec![("layer.new.layer".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + app.session.actions.list.push(Action { + name: "Fit".into(), + steps: vec![("view.fitOnScreen".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + assert_eq!(playback_selection(&app), Some(0)); + app.ui.actions.selected = Some(1); + assert_eq!(playback_selection(&app), Some(1)); + app.ui.actions.selected = Some(999); + assert_eq!(playback_selection(&app), Some(0)); + + app.ui.actions.selected = None; + use egui_kittest::{Harness, kittest::Queryable}; + let mut h = Harness::builder().with_size(vec2(400.0, 320.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(3); + let before = h.state().session.active().unwrap().doc.layers.len(); + h.get_by_label("Play selection").click(); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), before + 1); + assert!(!h.state().ui.status_error); +} + +#[test] +fn step_check_box_excludes_the_step_from_playback_and_batch() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + let steps = ["A", "B", "C"].map(|n| ("layer.new.layer".to_string(), json!({"name": n}))); + app.session.actions.list.push(Action::new("Three", steps.to_vec())); + app.ui.actions.expanded = vec![true]; + let mut h = Harness::builder().with_size(vec2(320.0, 300.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(3); + let checks = h.query_all_by_role(egui::accesskit::Role::CheckBox).count(); + assert_eq!(checks, 3); + h.query_all_by_role(egui::accesskit::Role::CheckBox).nth(1).unwrap().click(); + h.run_steps(3); + let action = &h.state().session.actions.list[0]; + assert_eq!(action.disabled.iter().copied().collect::>(), [1]); + assert_eq!(action_steps(action).len(), 2, "Batch and droplets get only the checked steps"); + assert_eq!(step_count(3, action.disabled.len()), "2/3 steps"); + h.get_by_label("Play selection").click(); + h.run_steps(3); + let names: Vec<_> = h.state().session.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.clone()).collect(); + assert_eq!(names, ["A", "C"]); +} + +#[test] +fn playback_errors_are_visible_in_status_bar() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.session.actions.list.push(Action { + name: "Bad action".into(), + steps: vec![("not.a.command".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + let mut h = Harness::builder().with_size(vec2(400.0, 320.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(3); + h.get_by_label("Play selection").click(); + h.run_steps(3); + assert!(h.state().ui.status_error); + assert!(h.state().ui.status.contains("not.a.command") || h.state().ui.status.contains("unknown command")); +} + +#[test] +fn recording_reveals_new_action_and_latest_step_in_a_long_panel() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width":4,"height":4})).unwrap(); + for i in 0..30 { + app.session.actions.list.push(Action { name: format!("Existing {i}"), steps: vec![], disabled: Default::default(), ..Default::default() }); + } + let mut h = Harness::builder().with_size(vec2(320.0, 260.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(4); + begin_recording(h.state_mut(), false); + h.run_steps(20); + let rect = h.get_by_label("Action 31").rect(); + assert!(rect.top() >= 0.0 && rect.bottom() <= h.get_by_label("Play selection").rect().top(), "new action visible: {rect:?}"); + for _ in 0..20 { + h.state_mut().run("view.zoomOut", json!({})).unwrap(); + } + h.state_mut().run("view.fitOnScreen", json!({})).unwrap(); + h.run_steps(20); + let rect = h.get_by_label("Fit on Screen").rect(); + assert!(rect.top() >= 0.0 && rect.bottom() <= h.get_by_label("Play selection").rect().top(), "latest step visible: {rect:?}"); +} + +#[test] +fn drag_steps_and_action_headers_reorders_and_keeps_selection() { + use egui_kittest::{Harness, kittest::Queryable}; + 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!({}))], + disabled: Default::default(), + ..Default::default() + }); + app.session.actions.list.push(Action { name: "Second".into(), steps: vec![], disabled: Default::default(), ..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); + 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); + } + let from = h.get_by_label("Zoom Out").rect().center(); + let target = h.get_by_label("100%").rect(); + drag(&mut h, from, pos2(target.center().x, target.bottom() - 2.0)); + assert_eq!( + h.state().session.actions.list[0].steps.iter().map(|st| st.0.as_str()).collect::>(), + ["view.fitOnScreen", "view.actualPixels", "view.zoomOut"] + ); + assert_eq!(h.state().ui.actions.selected_step, Some(2)); + let from = h.get_by_label("Second").rect().center(); + let target = h.get_by_label("First").rect(); + drag(&mut h, from, pos2(target.center().x, target.top() + 2.0)); + assert_eq!(h.state().session.actions.list[0].name, "Second"); + assert_eq!(h.state().ui.actions.expanded, [false, true]); + assert_eq!(h.state().ui.actions.selected, Some(0)); +} + +#[test] +fn nested_shell_actions_include_view_steps_and_propagate_failures() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width":40,"height":40})).unwrap(); + app.session.actions.list.push(Action { + name: "Child".into(), + steps: vec![("layer.new.layer".into(), json!({})), ("view.fitOnScreen".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + app.run("actions.record", json!({"name":"Parent"})).unwrap(); + app.run("actions.play", json!({"action":"Child"})).unwrap(); + app.run("actions.stop", json!({})).unwrap(); + assert_eq!(app.session.actions.list[1].steps, [("actions.play".into(), json!({"action":"Child"}))]); + assert_eq!(step_label("actions.play", &json!({"action":"Child"})), "Play Action: Child"); + app.run("view.actualPixels", json!({})).unwrap(); + let r = app.run("actions.play", json!({"action":"Parent"})).unwrap(); + assert!(r.get("failed").is_none(), "{r}"); + assert!(app.ui.views[0].fit_pending); + app.session.authorize = + Some(|id, _| if id == "view.fitOnScreen" { Err(photocraft_engine::EngineError::Other("denied nested view".into())) } else { Ok(()) }); + let r = app.run("actions.play", json!({"action":"Parent"})).unwrap(); + assert!(r["failed"]["error"].as_str().unwrap().contains("denied nested view")); + assert!(app.session.actions.playback_stack.is_empty()); + assert_eq!(app.session.actions.playing, 0); +} + +#[test] +fn panel_shows_pending_steps_and_trash_deletes_only_the_clicked_step() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 40, "height": 40})).unwrap(); + begin_recording(&mut app, false); + app.run("view.fitOnScreen", json!({})).unwrap(); + app.run("view.zoomOut", json!({})).unwrap(); + let mut h = Harness::builder().with_size(vec2(320.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(2); + assert!(h.state().session.actions.recording.is_some()); + h.get_by_label("Fit on Screen"); + h.get_by_label("Zoom Out").click(); + h.run_steps(2); + assert_eq!(h.state().ui.actions.selected_step, Some(1)); + h.get_by_label("Delete").click(); + h.run_steps(2); + assert_eq!(visible_steps(h.state(), 0).iter().map(|(id, _)| id.as_str()).collect::>(), ["view.fitOnScreen"]); + assert_eq!(h.state().session.actions.list.len(), 1); + assert!(h.state().session.actions.recording.is_some()); + assert!(h.state().ui.actions.selected.is_none()); + delete_selection(h.state_mut()); + assert_eq!(h.state().session.actions.list.len(), 1, "repeated trash cannot delete the action"); + h.state_mut().run("view.zoomIn", json!({})).unwrap(); + h.run_steps(2); + h.get_by_label("Zoom In"); + h.state_mut().run("actions.stop", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(visible_steps(h.state(), 0).iter().map(|(id, _)| id.as_str()).collect::>(), ["view.fitOnScreen", "view.zoomIn"]); + h.get_by_label("Zoom In").click(); + h.run_steps(2); + h.get_by_label("Delete").click(); + h.run_steps(2); + assert_eq!(visible_steps(h.state(), 0).iter().map(|(id, _)| id.as_str()).collect::>(), ["view.fitOnScreen"]); +} + +#[test] +fn view_menu_commands_record_append_and_replay_after_resize() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 160, "height": 100})).unwrap(); + begin_recording(&mut app, false); + app.run("image.canvasSize", json!({"width": 80, "height": 60})).unwrap(); + app.run("actions.stop", json!({})).unwrap(); + begin_recording(&mut app, true); + crate::menus::invoke(&mut app, &ctx, "view.fitOnScreen", json!({})).unwrap(); + app.run("actions.stop", json!({})).unwrap(); + assert_eq!(app.session.actions.list.len(), 1); + assert_eq!(app.session.actions.list[0].steps.iter().map(|s| s.0.as_str()).collect::>(), ["image.canvasSize", "view.fitOnScreen"]); + assert_eq!(label_of("view.fitOnScreen"), "Fit on Screen"); + // Persisted actions retain the menu step, and playback fits the new document. + let saved = serde_json::to_string(&app.session.actions.list).unwrap(); + app.session.actions.list = serde_json::from_str(&saved).unwrap(); + app.run("file.new", json!({"width": 200, "height": 140})).unwrap(); + app.run("view.actualPixels", json!({})).unwrap(); + let result = app.run("actions.play", json!({"action": 0})).unwrap(); + assert_eq!(result["ran"], 2); + assert!(result.get("failed").is_none(), "{result}"); + let idx = app.session.active_index().unwrap(); + assert!(app.ui.views[idx].fit_pending); + let doc = &app.session.active().unwrap().doc; + crate::canvas::fit_view(&mut app.ui.views[idx], doc, vec2(100.0, 100.0), 1.0, 1.0); + assert_eq!(app.ui.views[idx].zoom, 0.75); + assert_eq!(app.ui.views[idx].center, [40.0, 30.0]); + assert!(!app.ui.views[idx].fit_pending); +} + +#[test] +fn view_action_failure_resume_and_authorization() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.actions.list.push(Action { + name: "Fit".into(), + steps: vec![("view.fitOnScreen".into(), json!({})), ("view.actualPixels".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + let result = app.run("actions.play", json!({"action": "Fit"})).unwrap(); + assert_eq!(result["ran"], 0); + assert_eq!(result["failed"]["step"], 0); + assert_eq!(app.session.actions.playing, 0); + app.run("file.new", json!({"width": 40, "height": 40})).unwrap(); + app.session.authorize = + Some( + |id, _| { + if id == "view.fitOnScreen" { Err(photocraft_engine::EngineError::BadParams { cmd: id.into(), msg: "denied view".into() }) } else { Ok(()) } + }, + ); + let result = app.run("actions.play", json!({"action": 0})).unwrap(); + assert_eq!(result["ran"], 0); + assert!(result["failed"]["error"].as_str().unwrap().contains("denied view")); + let result = app.run("actions.play", json!({"action": 0, "from": 1})).unwrap(); + assert_eq!(result["ran"], 1); + assert!(!app.ui.views[0].fit_pending); + assert!(app.run("actions.play", json!({"action": 0, "from": -1})).is_err()); + app.session.actions.playing = 1; + assert!(app.run("actions.play", json!({"action": 0})).is_err()); +} + +#[test] +fn record_and_replay_on_another_document() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 40, "height": 40})).unwrap(); + app.sync_views(); + app.run("actions.record", json!({})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let _ = app.run("document.pixel", json!({"x": 1, "y": 1})); + app.run("actions.stop", json!({})).unwrap(); + let a = &app.session.actions.list[0]; + assert_eq!(a.steps.iter().map(|s| s.0.as_str()).collect::>(), ["layer.new.layer", "select.rect", "edit.fill"]); + app.run("file.new", json!({"width": 40, "height": 40})).unwrap(); + app.sync_views(); + let played = app.run("actions.play", json!({"action": 0})).unwrap(); + assert_eq!(played["ran"], 3); + assert!(played.get("failed").is_none(), "{played}"); + let d = &app.session.active().unwrap().doc; + assert_eq!(d.layers.len(), 2); + assert_eq!(d.layers[1].surface().unwrap().pixel(5, 5), vec![1.0, 0.0, 0.0, 1.0]); +} + +#[test] +fn recorded_save_as_and_save_replay_and_write_the_file() { + let written = std::rc::Rc::new(std::cell::RefCell::new(Vec::::new())); + let log = written.clone(); + let services = crate::Services { + export: Some(Box::new(|doc, path, _| { + photocraft_io::export(doc, path, &Default::default()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()) + })), + write: Some(Box::new(move |path, _| { + log.borrow_mut().push(path.to_string()); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + app.run("actions.record", json!({})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + crate::menus::invoke(&mut app, &ctx, "file.saveAs", json!({"path": "out/result.psd"})).unwrap(); + crate::menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap(); + app.run("actions.stop", json!({})).unwrap(); + let steps = &app.session.actions.list[0].steps; + assert_eq!(steps, &[("layer.new.layer".into(), json!({})), ("file.saveAs".into(), json!({"path": "out/result.psd"})), ("file.save".into(), json!({}))]); + written.borrow_mut().clear(); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + let played = app.run("actions.play", json!({"action": 0})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert_eq!(*written.borrow(), ["out/result.psd", "out/result.psd"]); + assert_eq!(app.session.active().unwrap().path.as_deref(), Some("out/result.psd")); +} + +/// An app with the real importer/exporter and writer whose Save dialogs answer `answers`. +fn disk_app(answers: Vec>) -> PhotocraftApp { + let services = crate::Services { + import: Some(Box::new(|name, bytes, opts| { + photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()) + })), + export: Some(Box::new(|doc, path, _| { + photocraft_io::export(doc, path, &Default::default()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()) + })), + write: Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))), + file_dialog: Some(crate::file_dialog::fake(answers).0), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.background_jobs = false; + app +} + +/// Records Invert + File › Save on the file `a`, then plays it on the file `b` (given a +/// new layer first when `layered`). Returns the played result and whether `b` / `a` +/// changed on disk. +fn record_save_on_a_play_on_b(ext: &str, layered: bool) -> (Value, bool, bool) { + use crate::file_dialog::FileDialogAnswer::SaveTo; + let dir = std::env::temp_dir().join(format!("photocraft-rec-save-{ext}-{layered}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = |n: &str| dir.join(format!("{n}.{ext}")).to_string_lossy().into_owned(); + let (a, b) = (path("a"), path("b")); + // The dialog confirms the suggested name, which is the document's own file. + let mut app = disk_app(vec![Some(SaveTo(a.clone())), Some(SaveTo(a.clone()))]); + let ctx = egui::Context::default(); + for p in [&a, &b] { + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + app.save_as(Some(p.clone())).unwrap(); + } + let (before_a, before_b) = (std::fs::read(&a).unwrap(), std::fs::read(&b).unwrap()); + app.open_path(&a).unwrap(); + app.run("actions.record", json!({})).unwrap(); + app.run("image.adjustments.invert", json!({})).unwrap(); + crate::menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap(); + app.poll_file_dialog(&ctx, None); + app.run("actions.stop", json!({})).unwrap(); + std::fs::write(&a, &before_a).unwrap(); + app.open_path(&b).unwrap(); + if layered { + app.run("layer.new.layer", json!({})).unwrap(); + } + let played = app.run("actions.play", json!({"action": 0})).unwrap(); + let r = (played, std::fs::read(&b).unwrap() != before_b, std::fs::read(&a).unwrap() != before_a); + let _ = std::fs::remove_dir_all(&dir); + r +} + +#[test] +fn recorded_save_overwrites_the_layered_file_the_action_is_played_on() { + let (played, b_changed, a_changed) = record_save_on_a_play_on_b("psd", false); + assert!(played.get("failed").is_none(), "{played}"); + assert!(b_changed && !a_changed); +} + +#[test] +fn recorded_save_overwrites_the_flat_file_the_action_is_played_on() { + let (played, b_changed, a_changed) = record_save_on_a_play_on_b("png", false); + assert!(played.get("failed").is_none(), "{played}"); + assert!(b_changed, "Save did not overwrite the file the action was played on"); + assert!(!a_changed, "Save wrote the file the action was recorded on"); +} + +#[test] +fn recorded_save_never_flattens_layers_over_a_flat_file() { + // The played-on document has layers its PNG can't keep: the step fails, nothing is written (#3806). + let (played, b_changed, a_changed) = record_save_on_a_play_on_b("png", true); + assert!(played.get("failed").is_some(), "{played}"); + assert!(!b_changed && !a_changed); +} + +/// Loads a Photoshop set holding Invert + a Save As into `dest` and plays it on a PSD. +/// Returns the played result, whether the PSD changed on disk and the files in `out`. +fn play_imported_save_as(dest: &str) -> (Value, bool, Vec) { + use photocraft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; + use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value as D}; + let dir = std::env::temp_dir().join(format!("photocraft-atn-save-as-{}-{}", dest.len(), std::process::id())); + let out = dir.join("out"); + std::fs::create_dir_all(&out).unwrap(); + let src = dir.join("src.psd").to_string_lossy().into_owned(); + let path = |text: &str| { + let units: Vec = text.encode_utf16().chain(std::iter::once(0)).collect(); + let mut b = b"txtu".to_vec(); + b.extend_from_slice(&((12 + units.len() * 2) as u32).to_le_bytes()); + b.extend_from_slice(&(units.len() as u32).to_le_bytes()); + units.iter().for_each(|u| b.extend_from_slice(&u.to_le_bytes())); + D::Path(b) + }; + let save = Descriptor::new("null") + .with("As ", D::Descriptor(Descriptor::new("PNGF"))) + .with("In ", path(&out.join(dest).to_string_lossy())) + .with("DocI", D::Integer(53)); + let item = |code: &[u8; 4], label: &str, d: Option| AtnItem { + event: AtnEvent::Code(*code), + dictionary: label.into(), + descriptor: d, + ..Default::default() + }; + let set = AtnFile { + name: UnicodeString::new_nul("Export"), + actions: vec![AtnAction { + name: UnicodeString::new_nul("Invert and save"), + items: vec![item(b"Invr", "Invert", None), item(b"save", "Save", Some(save))], + ..Default::default() + }], + ..Default::default() + }; + let mut app = disk_app(vec![]); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + app.save_as(Some(src.clone())).unwrap(); + let before = std::fs::read(&src).unwrap(); + app.run("actions.load", json!({"data": photocraft_engine::paint::tile::b64_encode(&photocraft_psd::atn::write(&set).unwrap())})).unwrap(); + app.open_path(&src).unwrap(); + let played = app.run("actions.play", json!({"action": 0})).unwrap(); + let mut written: Vec = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + written.sort(); + let r = (played, std::fs::read(&src).unwrap() != before, written); + let _ = std::fs::remove_dir_all(&dir); + r +} + +#[test] +fn imported_save_as_writes_the_recorded_file_not_the_played_one() { + // #7102: the Save As imported as File › Save, which wrote over src.psd. + let (played, src_changed, written) = play_imported_save_as("result.png"); + assert!(played.get("failed").is_none(), "{played}"); + assert!(!src_changed, "the Save As wrote over the file the action was played on"); + assert_eq!(written, ["result.png"]); +} + +#[test] +fn imported_save_as_into_a_folder_stops_before_writing() { + // A folder destination isn't mapped yet (#5430): playback stops on it, nothing is saved. + let (played, src_changed, written) = play_imported_save_as("folder"); + assert!(played.get("failed").is_some(), "{played}"); + assert!(!src_changed); + assert!(written.is_empty(), "{written:?}"); +} + +#[test] +fn set_folders_group_actions_and_collapse() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut sharpen = Action::new("Sharpen", vec![("filter.sharpen.sharpen".into(), json!({}))]); + sharpen.set = Some("Retouch".into()); + let mut soften = Action::new("Soften", vec![("filter.blur.blur".into(), json!({}))]); + soften.set = Some("Retouch".into()); + app.session.actions.list.push(Action::new("Loose", vec![])); + app.session.actions.list.push(sharpen); + app.session.actions.list.push(Action::new("Also loose", vec![])); + app.session.actions.list.push(soften); + let mut h = Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(3); + // The folder row shows the set with its count; its actions sit under it, loose ones first. + let folder = h.get_by_label("Retouch").rect(); + assert!(h.get_by_label("Loose").rect().top() < folder.top()); + assert!(h.get_by_label("Also loose").rect().top() < folder.top()); + assert!(h.get_by_label("Sharpen").rect().top() > folder.top()); + assert!(h.get_by_label("Soften").rect().top() > h.get_by_label("Sharpen").rect().top()); + assert_eq!(display_order(&[]), Vec::::new()); + // Clicking the folder collapses it; its actions disappear and the state is remembered. + h.get_by_label("Retouch").click(); + h.run_steps(3); + assert_eq!(h.state().ui.actions.collapsed_sets, ["Retouch"]); + assert!(h.query_by_label("Sharpen").is_none()); + assert!(h.query_by_label("Loose").is_some()); + h.get_by_label("Retouch").click(); + h.run_steps(3); + assert!(h.state().ui.actions.collapsed_sets.is_empty()); + assert!(h.query_by_label("Sharpen").is_some()); +} + +#[test] +fn moving_an_action_next_to_another_set_joins_it() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut a = Action::new("A", vec![]); + a.set = Some("One".into()); + let mut b = Action::new("B", vec![]); + b.set = Some("Two".into()); + app.session.actions.list.push(a); + app.session.actions.list.push(b); + app.session.actions.list.push(Action::new("C", vec![])); + // C dropped below B: it joins B's set, "Two". + move_row(&mut app, DragRow { action: 2, step: None }, 2); + assert_eq!(app.session.actions.list[2].set.as_deref(), Some("Two")); + // B dropped to the top, above A: the row below decides when there is none above. + move_row(&mut app, DragRow { action: 1, step: None }, 0); + assert_eq!((app.session.actions.list[0].name.as_str(), app.session.actions.list[0].set.as_deref()), ("B", Some("One"))); + // C dropped between A (One) and nothing: the row above wins. + move_row(&mut app, DragRow { action: 2, step: None }, 2); + assert_eq!((app.session.actions.list[2].name.as_str(), app.session.actions.list[2].set.as_deref()), ("C", Some("One"))); +} + +#[test] +fn insert_stop_dialog_adds_a_stop_after_the_selected_step() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.session.actions.list.push(Action::new("A", vec![("select.all".into(), json!({})), ("select.inverse".into(), json!({}))])); + assert!(insert_stop_dialog(&mut app).is_err(), "needs a selected action"); + app.ui.actions.selected = Some(0); + app.ui.actions.selected_step = Some(0); + let id = insert_stop_dialog(&mut app).unwrap()["dialog"].as_u64().unwrap(); + let d = app.ui.dialog_mut(id).unwrap(); + assert!(owns_insert_stop(&d.fields)); + assert_eq!(d.fields["at"], 1); + d.fields.insert("message".into(), json!("Check the mask")); + d.fields.insert("allowContinue".into(), json!(true)); + crate::dialogs::confirm(&mut app, id).unwrap(); + let steps = &app.session.actions.list[0].steps; + assert_eq!(steps[1], (photocraft_engine::atn_cmds::STOP_MESSAGE.to_string(), json!({"message": "Check the mask", "allowContinue": true}))); + assert_eq!((app.ui.actions.selected, app.ui.actions.selected_step), (Some(0), Some(1))); + assert_eq!(step_label(&steps[1].0, &steps[1].1), "Stop: Check the mask"); + // Without a selected step the stop goes last; the panel's menu wiring is exercised by name. + app.ui.actions.selected_step = None; + let id = insert_stop_dialog(&mut app).unwrap()["dialog"].as_u64().unwrap(); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["at"], 3); + crate::dialogs::cancel(&mut app, id).unwrap(); + assert_eq!(app.session.actions.list[0].steps.len(), 3); +} + +#[test] +fn dialog_worker_failure_stops_action_before_following_steps() { + for (background, locked) in [(true, true), (false, true), (true, false)] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 6, "background": "#203040"})).unwrap(); + let mut action = Action::new( + "Worker Result", + vec![ + ("layer.setProps".into(), json!({"name": "Prefix", "locks": {"pixels": locked}})), + ("filter.blur.gaussianBlur".into(), json!({"radius": 1.5})), + ("layer.new.layer".into(), json!({"name": "Suffix"})), + ], + ); + action.dialogs.insert(1); + app.session.actions.list.push(action); + app.background_jobs = background; + let paused = play(&mut app, &json!({"action": "Worker Result"})).unwrap(); + let dialog = paused["paused"]["dialog"].as_u64().unwrap(); + let result = crate::dialogs::confirm(&mut app, dialog); + let suffix = app.session.active().unwrap().doc.walk().iter().any(|(_, _, layer)| layer.name == "Suffix"); + + assert_eq!(suffix, !locked, "background={background}, locked={locked}: {result:?}"); + if locked && background { + assert!(result.as_ref().is_err_and(|e| e.contains("locked")), "failed worker must fail the dialog confirmation: {result:?}"); + assert!(app.ui.status_error, "the action must report the worker failure"); + assert!(app.ui.status.contains("locked"), "{}", app.ui.status); + assert_eq!(app.session.jobs_with_recent()[0].state, "failed"); + } else if locked { + assert!(result.is_err(), "the foreground command rejects the locked layer"); + } else { + assert!(result.is_ok(), "the successful worker lets the action continue: {result:?}"); + } + assert_eq!(app.session.actions.playing, 0); + assert!(app.session.actions.playback_stack.is_empty()); + } +} + +#[test] +fn a_dialog_toggled_step_pauses_playback_and_resumes_on_ok() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut a = Action::new( + "Blur", + vec![("layer.new.layer".into(), json!({})), ("filter.blur.gaussianBlur".into(), json!({"radius": 3})), ("select.all".into(), json!({}))], + ); + a.dialogs.insert(1); + app.session.actions.list.push(a); + let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); + assert_eq!(v["ran"], 1, "{v}"); + assert_eq!(v["paused"]["step"], 1); + let id = v["paused"]["dialog"].as_u64().unwrap(); + let d = app.ui.dialog_mut(id).unwrap(); + assert_eq!(d.fields["radius"], 3, "the dialog opens on the recorded values"); + assert!(d.fields[RESUME].is_u64(), "the dialog carries only the pause's token: {}", d.fields[RESUME]); + assert!(app.session.active().unwrap().doc.selection.is_none(), "nothing after the dialog ran yet"); + report_play(&mut app, &v); + assert!(app.ui.status.contains("dialog"), "{}", app.ui.status); + // OK runs the blur with the dialog's values and plays the rest. + app.ui.dialog_mut(id).unwrap().fields.insert("radius".into(), json!(5)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert!(app.ui.dialogs.is_empty()); + assert!(app.session.active().unwrap().doc.selection.is_some(), "the step after the dialog ran"); + assert!(app.ui.status.starts_with("Played"), "{}", app.ui.status); + // Cancel stops the action there. + app.run("select.deselect", json!({})).unwrap(); + let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); + let id = v["paused"]["dialog"].as_u64().unwrap(); + crate::dialogs::cancel(&mut app, id).unwrap(); + assert!(app.session.active().unwrap().doc.selection.is_none()); + assert!(app.ui.status.contains("stopped"), "{}", app.ui.status); + // With background jobs (the desktop default) the resumed steps wait for the dialog's + // filter to land instead of meeting a locked document. + app.background_jobs = true; + let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); + let id = v["paused"]["dialog"].as_u64().unwrap(); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert!(app.session.active().unwrap().doc.selection.is_some(), "the step after the background blur ran"); + assert!(app.ui.status.starts_with("Played"), "{}", app.ui.status); + app.background_jobs = false; + // Agents play headlessly: no pause, the recorded values run. + app.automation_input = true; + let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); + assert_eq!(v["ran"], 3, "{v}"); + assert!(v.get("paused").is_none()); +} + +/// An 8×6 document, a Child action whose first step (a blur) shows its dialog and whose +/// second step adds a "Suffix" layer, and recording into Owner started. +fn recording_with_dialog_child() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 6, "background": "#203040"})).unwrap(); + let mut child = + Action::new("Child", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1.5})), ("layer.new.layer".into(), json!({"name": "Suffix"}))]); + child.dialogs.insert(0); + app.session.actions.list.push(child); + app.run("actions.record", json!({"name": "Owner"})).unwrap(); + app +} + +fn suffixes(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.walk().iter().filter(|(_, _, l)| l.name == "Suffix").count() +} + +fn child_call() -> Vec<(String, Value)> { + vec![("actions.play".to_string(), json!({"action": "Child"}))] +} + +/// Play Child and return the id of its step dialog. +fn pause_child(app: &mut PhotocraftApp) -> u64 { + let v = play(app, &json!({"action": "Child"})).unwrap(); + v["paused"]["dialog"].as_u64().unwrap() +} + +#[test] +fn a_recorded_call_paused_by_a_dialog_records_one_call_and_replays_once() { + let mut app = recording_with_dialog_child(); + let refusal = crate::i18n::t("Confirm or cancel the open action step dialog first").to_string(); + + // Confirm: the dialog command and the resumed rest stay inside the one named call. + let live = app.session.journal.len(); + let id = pause_child(&mut app); + assert!(app.session.actions.recording.is_none(), "recording stays suspended while the step dialog is open"); + let names = |app: &PhotocraftApp| app.session.actions.list.iter().map(|a| a.name.clone()).collect::>(); + let before = names(&app); + assert_eq!(app.run("actions.record", json!({"name": "Intruder"})), Err(refusal.clone()), "no second recording while the call is suspended"); + assert_eq!(app.run("actions.delete", json!({"action": "Owner"})), Err(refusal.clone()), "the suspended owner can't be deleted"); + assert_eq!(app.run("actions.move", json!({"action": "Owner", "to": 0})), Err(refusal.clone()), "the suspended owner can't be moved"); + assert_eq!(names(&app), before, "the refused commands leave the list alone"); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert!(app.session.actions.recording.is_some(), "recording comes back when the call completes"); + app.run("actions.stop", json!({})).unwrap(); + assert_eq!(app.session.actions.list[1].steps, child_call()); + assert_eq!(suffixes(&app), 1); + + // Replaying the recording repeats the call once. + app.run("file.new", json!({"width": 8, "height": 6})).unwrap(); + let start = app.session.journal.len(); + app.automation_input = true; + let v = play(&mut app, &json!({"action": "Owner"})).unwrap(); + app.automation_input = false; + assert!(v.get("failed").is_none(), "{v}"); + assert_eq!(suffixes(&app), 1, "replay creates the suffix once"); + let edits = |from: usize| -> Vec<(String, Value)> { + app.session.journal[from..].iter().filter(|(id, _)| !id.starts_with("actions.") && id != "file.new").cloned().collect() + }; + let expected = vec![("filter.blur.gaussianBlur".to_string(), json!({"radius": 1.5})), ("layer.new.layer".to_string(), json!({"name": "Suffix"}))]; + assert_eq!(edits(start), expected, "replay journals the blur and the suffix once each, in order"); + assert_eq!(edits(live), expected[..].iter().chain(&expected).cloned().collect::>(), "live then replay"); + + // Cancel: the call ends at the dialog and is recorded once. + app.run("actions.record", json!({"name": "Cancelled"})).unwrap(); + let id = pause_child(&mut app); + crate::dialogs::cancel(&mut app, id).unwrap(); + assert!(app.session.actions.recording.is_some(), "cancel restores recording"); + app.run("actions.stop", json!({})).unwrap(); + assert_eq!(app.session.actions.list[2].steps, child_call()); +} + +#[test] +fn a_failing_step_dialog_command_ends_the_recorded_call_once() { + let mut app = recording_with_dialog_child(); + let id = pause_child(&mut app); + assert!(app.session.actions.recording.is_none(), "recording stays suspended while the step dialog is open"); + app.ui.dialog_mut(id).unwrap().fields.insert("radius".into(), json!("not a radius")); + assert!(crate::dialogs::confirm(&mut app, id).is_err(), "the dialog command fails"); + assert!(app.session.actions.recording.is_some(), "recording comes back when the dialog command fails"); + assert_eq!(suffixes(&app), 0, "the action stops at the failed step"); + app.run("actions.stop", json!({})).unwrap(); + assert_eq!(app.session.actions.list[1].steps, child_call()); +} + +#[test] +fn an_abandoned_step_dialog_leaves_no_paused_playback() { + let mut app = recording_with_dialog_child(); + let id = pause_child(&mut app); + app.ui.dialog_mut(id).unwrap().fields.insert("radius".into(), json!("not a radius")); + assert!(crate::dialogs::confirm(&mut app, id).is_err(), "the dialog command fails"); + assert!(app.paused_playbacks.paused.is_empty(), "the failed dialog ends its pause"); + app.run("actions.stop", json!({})).unwrap(); + assert_eq!(app.session.actions.list[1].steps, child_call(), "the call is recorded once"); + app.run("actions.record", json!({"name": "Next"})).unwrap(); +} + +#[test] +fn a_failing_resumed_playback_ends_the_recorded_call_once() { + let mut app = recording_with_dialog_child(); + let id = pause_child(&mut app); + // The rest of the call can't be found any more: resuming it fails. + app.session.actions.list[0].name = "Renamed".into(); + assert!(crate::dialogs::confirm(&mut app, id).is_err(), "the resumed playback fails"); + assert!(app.session.actions.recording.is_some(), "recording comes back when the resumed playback fails"); + app.run("actions.stop", json!({})).unwrap(); + assert_eq!(app.session.actions.list[1].steps, child_call()); +} + +#[test] +fn a_suspended_call_is_recorded_into_its_action_after_the_list_changes() { + let mut app = recording_with_dialog_child(); + let id = pause_child(&mut app); + // Something else puts an action where Owner was. + app.session.actions.list.insert(1, Action::new("Bystander", vec![])); + crate::dialogs::confirm(&mut app, id).unwrap(); + app.run("actions.stop", json!({})).unwrap(); + assert!(app.session.actions.list[1].steps.is_empty(), "the action now at the old index gets nothing"); + assert_eq!(app.session.actions.list[2].name, "Owner"); + assert_eq!(app.session.actions.list[2].steps, child_call()); +} + +#[test] +fn escape_on_a_step_dialog_ends_the_recorded_call_once() { + let app = recording_with_dialog_child(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(2); + pause_child(h.state_mut()); + h.run_steps(4); + assert!(h.state().session.actions.recording.is_none(), "recording stays suspended while the step dialog is open"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.dialogs.is_empty(), "Esc closes the step dialog"); + assert!(h.state().session.actions.recording.is_some(), "Esc restores recording"); + let app = h.state_mut(); + app.run("actions.stop", json!({})).unwrap(); + assert_eq!(app.session.actions.list[1].steps, child_call()); +} + +#[test] +fn a_step_dialog_keeps_its_continuation_token() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + for (name, steps) in [ + ("First", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1}))]), + ("Second", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1})), ("select.all".into(), json!({}))]), + ] { + let mut action = Action::new(name, steps); + action.dialogs.insert(0); + app.session.actions.list.push(action); + } + let first = play(&mut app, &json!({"action": "First"})).unwrap()["paused"]["dialog"].as_u64().unwrap(); + let second = play(&mut app, &json!({"action": "Second"})).unwrap()["paused"]["dialog"].as_u64().unwrap(); + let first_token = app.ui.dialog_mut(first).unwrap().fields[RESUME].clone(); + let second_token = app.ui.dialog_mut(second).unwrap().fields[RESUME].clone(); + for token in [second_token.clone(), Value::Null, json!("invalid"), json!({"action": "Second", "from": 1})] { + let (request, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"dialog": first, "field": RESUME, "value": token})); + let response = crate::control::handle(&mut app, &egui::Context::default(), &request); + assert!(matches!(response, crate::control::Outcome::Done(ref v) if v["error"].as_str().is_some_and(|e| e.contains("read-only")))); + assert_eq!(app.ui.dialog_mut(first).unwrap().fields[RESUME], first_token); + assert_eq!(app.ui.dialog_mut(second).unwrap().fields[RESUME], second_token); + assert_eq!(app.paused_playbacks.paused.len(), 2); + } + crate::dialogs::confirm(&mut app, first).unwrap(); + assert!(app.session.active().unwrap().doc.selection.is_none(), "First must not run Second's remaining step"); + crate::dialogs::confirm(&mut app, second).unwrap(); + assert!(app.session.active().unwrap().doc.selection.is_some()); + assert!(app.paused_playbacks.paused.is_empty()); +} + +fn recording_with_displace_child() -> PhotocraftApp { + let mut app = recording_with_dialog_child(); + app.background_jobs = false; + app.session.actions.list[0].steps[0] = ("filter.distort.displace".into(), json!({})); + app +} + +fn assert_displace_call_finished(app: &mut PhotocraftApp, suffix_count: usize) { + assert!(!app.file_dialog_open()); + assert!(app.ui.dialogs.is_empty()); + assert!(app.paused_playbacks.paused.is_empty()); + assert!(app.session.actions.recording.is_some()); + assert_eq!(suffixes(app), suffix_count); + app.run("actions.stop", json!({})).unwrap(); + assert_eq!(app.session.actions.list[1].steps, child_call(), "record the child call exactly once"); + app.run("actions.record", json!({"name": "Next"})).unwrap(); +} + +#[test] +fn a_displace_step_restores_recording_when_the_map_picker_fails_or_is_cancelled() { + use crate::file_dialog::FileDialogAnswer; + let dir = tempfile::tempdir().unwrap(); + let missing = dir.path().join("missing.png").to_string_lossy().into_owned(); + for answer in [ + None, + Some(FileDialogAnswer::Unavailable("no picker available".into())), + Some(FileDialogAnswer::Paths(Vec::new())), + Some(FileDialogAnswer::Contents("map.png".into(), Vec::new())), + Some(FileDialogAnswer::Paths(vec![missing])), + ] { + let mut app = recording_with_displace_child(); + let (show, _) = crate::file_dialog::fake(vec![answer]); + app.services.file_dialog = Some(show); + let id = pause_child(&mut app); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert!(app.file_dialog_open()); + assert!(app.session.actions.recording.is_none()); + app.poll_file_dialog(&egui::Context::default(), None); + assert_displace_call_finished(&mut app, 0); + } +} + +#[test] +fn a_displace_step_restores_recording_when_the_map_picker_cannot_start() { + let mut app = recording_with_displace_child(); + let id = pause_child(&mut app); + assert!(crate::dialogs::confirm(&mut app, id).is_err()); + assert_displace_call_finished(&mut app, 0); +} + +#[test] +fn a_displace_step_resumes_and_records_its_call_once_after_choosing_a_map() { + let mut app = recording_with_displace_child(); + let dir = tempfile::tempdir().unwrap(); + let map = dir.path().join("map.png"); + let bytes = photocraft_io::export(&app.session.active().unwrap().doc, "png", &Default::default()).unwrap().bytes; + std::fs::write(&map, bytes).unwrap(); + let (show, _) = crate::file_dialog::fake(vec![Some(crate::file_dialog::FileDialogAnswer::Paths(vec![map.to_string_lossy().into_owned()]))]); + app.services.file_dialog = Some(show); + let id = pause_child(&mut app); + crate::dialogs::confirm(&mut app, id).unwrap(); + app.poll_file_dialog(&egui::Context::default(), None); + assert_displace_call_finished(&mut app, 1); +} + +#[test] +fn a_step_dialog_takes_only_the_steps_values() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut a = Action::new("Blur", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 2, "__command": "select.all", "__label": "Other"}))]); + a.dialogs.insert(0); + app.session.actions.list.push(a); + let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); + let d = app.ui.dialog_mut(v["paused"]["dialog"].as_u64().unwrap()).unwrap(); + assert_eq!(d.fields["radius"], 2); + assert_eq!(d.fields["__command"], "filter.blur.gaussianBlur"); + assert_ne!(d.fields["__label"], "Other"); +} + +fn deny_blur(id: &str, _: &Value) -> photocraft_engine::Result<()> { + if id == "filter.blur.gaussianBlur" { Err(photocraft_engine::EngineError::Other("blur denied".into())) } else { Ok(()) } +} + +#[test] +fn a_step_the_gate_denies_opens_no_dialog() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut a = Action::new("Blur", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1}))]); + a.dialogs.insert(0); + app.session.actions.list.push(a); + app.session.authorize = Some(deny_blur); + let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); + app.session.authorize = None; + assert!(v["failed"]["error"].as_str().is_some_and(|e| e.contains("blur denied")), "{v}"); + assert!(app.ui.dialogs.is_empty(), "no step dialog opened"); + assert!(app.paused_playbacks.paused.is_empty()); +} + +fn deny_select_all(id: &str, _: &Value) -> photocraft_engine::Result<()> { + if id == "select.all" { Err(photocraft_engine::EngineError::Other("select.all denied".into())) } else { Ok(()) } +} + +/// An action an automation client plays (`control::handle` installs the gate, then removes +/// it) pauses at a step dialog; confirming the dialog later, here with synthetic Enter or +/// OK, runs the remaining steps under the same gate. +#[test] +fn a_paused_playback_keeps_its_automation_gate_when_the_dialog_is_confirmed() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut a = Action::new("Seeded", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1})), ("select.all".into(), json!({}))]); + a.dialogs.insert(0); + app.session.actions.list.push(a); + app.session.authorize = Some(deny_select_all); + let v = play(&mut app, &json!({"action": "Seeded"})).unwrap(); + app.session.authorize = None; + let id = v["paused"]["dialog"].as_u64().unwrap(); + app.automation_input = true; + let _ = crate::dialogs::confirm(&mut app, id); + app.automation_input = false; + assert!(app.session.active().unwrap().doc.selection.is_none(), "the denied step did not run"); + assert!(app.ui.status.contains("select.all denied"), "{}", app.ui.status); +} + +/// The dialog names only its pause: changing its fields can't resume another action. +#[test] +fn a_step_dialog_resumes_only_the_playback_that_paused_it() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut a = Action::new("Blur", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1}))]); + a.dialogs.insert(0); + app.session.actions.list.push(a); + app.session.actions.list.push(Action::new("Seeded", vec![("select.all".into(), json!({}))])); + let v = play(&mut app, &json!({"action": "Blur"})).unwrap(); + let id = v["paused"]["dialog"].as_u64().unwrap(); + app.ui.dialog_mut(id).unwrap().fields.insert(RESUME.into(), json!({"action": "Seeded", "from": 0})); + let r = crate::dialogs::confirm(&mut app, id); + assert!(app.session.active().unwrap().doc.selection.is_none(), "the other action did not play"); + assert!(r.is_err_and(|e| e.contains("paused action"))); +} + +#[test] +fn button_mode_plays_the_clicked_action_and_hides_its_steps() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + app.session.actions.list.push(Action::new("Print", vec![("layer.new.layer".into(), json!({}))])); + app.session.actions.list[0].color = "blue".into(); + app.ui.actions.expanded = vec![true]; + app.ui.actions.button_mode = true; + let mut h = Harness::builder().with_size(vec2(420.0, 280.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(3); + assert_eq!(h.query_all_by_role(egui::accesskit::Role::CheckBox).count(), 0, "button mode hides the step list"); + let before = h.state().session.active().unwrap().doc.layers.len(); + h.get_by_label("Print").click(); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().doc.layers.len(), before + 1, "a click plays the action"); + h.get_by_label("Button Mode On").click(); + h.run_steps(2); + assert!(!h.state().ui.actions.button_mode); + assert!(h.query_by_label("Button Mode").is_some()); + assert_eq!(h.query_all_by_role(egui::accesskit::Role::CheckBox).count(), 1, "the step list returns when Button Mode is turned off"); +} + +/// An imported Close with Save: Yes plays as Save then Close. A Save Document script event +/// that closes the saved document stops playback, so the Close never reaches another dirty +/// document (#7367). +#[test] +fn save_hook_closing_the_target_stops_an_imported_close_with_save() { + use photocraft_psd::atn::{self, AtnEvent, AtnItem}; + use photocraft_psd::descriptor::{Descriptor, Id, Value as D}; + use std::{cell::RefCell, rc::Rc}; + // A one-step .atn: Close (`Cls `) with Save: Yes. + let seed = Action::new("Seed", vec![("layer.new.layer".into(), json!({}))]); + let (bytes, _) = photocraft_engine::atn_cmds::export("Set", &[&seed], &[], false).unwrap(); + let mut f = atn::parse(&bytes).unwrap(); + f.actions[0].items = vec![AtnItem { + event: AtnEvent::Code(*b"Cls "), + dictionary: "Close".into(), + descriptor: Some(Descriptor::new("null").with("Svng", D::Enumerated { type_id: Id::new("YsN "), value: Id::new("Ys ") })), + ..Default::default() + }]; + let imported = photocraft_engine::atn_cmds::import(&atn::write(&f).unwrap()).unwrap(); + let close_with_save = imported.actions[0].clone(); + assert_eq!(close_with_save.steps, [("file.save".into(), json!({})), ("file.close".into(), json!({}))]); + for hook in ["none", "activate", "close"] { + let writes = Rc::new(RefCell::new(Vec::::new())); + let w = writes.clone(); + let services = crate::Services { + export: Some(Box::new(|doc, _, _| Ok((doc.name.clone().into_bytes(), Vec::new())))), + write: Some(Box::new(move |path, _| { + w.borrow_mut().push(path.to_string()); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + // B is dirty with an unsaved KeepB layer; A is active and has its own file. + for name in ["B", "A"] { + app.run("file.new", json!({"name": name, "width": 2, "height": 2})).unwrap(); + } + assert!(app.session.set_active(0)); + app.run("layer.new.layer", json!({"name": "KeepB"})).unwrap(); + assert!(app.session.set_active(1)); + app.session.active_mut().unwrap().path = Some("A.psd".into()); + app.session.actions.list.push(close_with_save.clone()); + let steps = match hook { + "activate" => json!([["document.activate", {"document": 0}]]), + "close" => json!([["file.close", {}]]), + _ => Value::Null, + }; + if !steps.is_null() { + app.run("file.scripts.scriptEventsManager", json!({"add": {"event": "saveDocument", "steps": steps}})).unwrap(); + } + let r = app.run("actions.play", json!({"action": 0})).unwrap(); + assert_eq!(*writes.borrow(), ["A.psd"], "hook={hook}: A is saved once"); + let names: Vec> = app.session.documents().iter().map(|d| d.doc.layers.iter().map(|l| l.name.clone()).collect()).collect(); + assert_eq!(app.session.documents().len(), 1, "hook={hook}: only A closes; result={r}"); + assert_eq!(app.session.active().unwrap().doc.name, "B", "hook={hook}"); + assert_eq!(names, [["Background", "KeepB"]], "hook={hook}: B stays open with its unsaved layer"); + if hook == "close" { + assert_eq!(r["failed"]["step"], 0, "{r}"); + assert_eq!(r["failed"]["id"], "file.save", "{r}"); + assert!(r["failed"]["error"].as_str().unwrap().contains("closed during the save"), "{r}"); + } else { + assert!(r.get("failed").is_none(), "hook={hook}: {r}"); + } + assert_eq!(app.session.actions.playing, 0); + assert!(app.session.actions.playback_stack.is_empty()); + } +} From e7514f07af071abf57471d565b4004fa38be4042 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:56 +0000 Subject: [PATCH 072/259] refactor(ui-egui): move camera_raw_ui.rs tests to camera_raw_ui/tests.rs --- crates/ui-egui/src/camera_raw_ui.rs | 1013 +-------------------- crates/ui-egui/src/camera_raw_ui/tests.rs | 1010 ++++++++++++++++++++ 2 files changed, 1011 insertions(+), 1012 deletions(-) create mode 100644 crates/ui-egui/src/camera_raw_ui/tests.rs diff --git a/crates/ui-egui/src/camera_raw_ui.rs b/crates/ui-egui/src/camera_raw_ui.rs index 1ff5fb4bd1..dc6693fca0 100644 --- a/crates/ui-egui/src/camera_raw_ui.rs +++ b/crates/ui-egui/src/camera_raw_ui.rs @@ -1861,1018 +1861,7 @@ fn draw(app: &mut PhotocraftApp, ctx: &egui::Context, own_window: bool) { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn preview_texture_uses_linear_document_display_encoding() { - let mut doc = photocraft_doc::Document::new("test", photocraft_geom::Size::new(1, 1), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::F32); - doc.icc_profile = Some(photocraft_cms::Builtin::LinearSrgb.profile().to_bytes()); - let mut color = photocraft_engine::color_cmds::ColorState::default(); - color.settings.monitor_profile = "srgb".into(); - let display = color.canvas_display(&doc).unwrap(); - let px = [[0.25, 0.25, 0.25, 1.0]]; - let preview = CameraRawDialog::image(&px, 1, 1, &display); - let expected = display.to_rgba8(&photocraft_compose::Buffer::filled(Rect::new(0, 0, 1, 1), px[0])); - assert_eq!(preview.pixels[0].to_array(), expected.pixels[..4]); - assert_ne!(preview.pixels[0].r(), 64, "linear light must be encoded before display"); - } - - #[test] - fn histogram_follows_preview_and_view_changes_do_not_render_or_edit() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"color": "#808080"})).unwrap(); - let steps = app.session.active().unwrap().history.past_len(); - let initial = menu(&mut app, &ctx, "filter.cameraRaw", &json!({})).unwrap().unwrap(); - assert_eq!(initial["histogram"]["samples"], 64 * 48); - assert_eq!(initial["histogram"]["red"][128], 64 * 48); - let updated = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0}}})).unwrap().unwrap(); - assert_ne!(updated["histogram"]["red"], initial["histogram"]["red"]); - let before = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"before": true}})).unwrap().unwrap(); - assert_eq!(before["histogram"]["source"], "before"); - assert_eq!(before["histogram"]["red"], initial["histogram"]["red"]); - assert_eq!(before["previewRevision"], updated["previewRevision"]); - let after = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"before": false, "set": {"exposure": 1}}})).unwrap().unwrap(); - assert_eq!(after["histogram"], updated["histogram"]); - assert_eq!(after["previewRevision"], updated["previewRevision"]); - assert_eq!(app.session.active().unwrap().history.past_len(), steps); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"cancel": true}})).unwrap().unwrap(); - assert_eq!(app.session.active().unwrap().history.past_len(), steps); - let pixel = app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(0, 0); - assert!((pixel[0] - 128.0 / 255.0).abs() < 0.0001); - } - - /// Closing Camera Raw's window is Cancel. Without a multi-window backend egui embeds the - /// "window" (`ViewportClass::EmbeddedWindow`), and the close request comes from the window - /// it is drawn in; the overlay fallback (`embed_viewports`) keeps the dialog open. - #[test] - fn closing_the_camera_raw_window_cancels() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::Pro); - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"color": "#808080"})).unwrap(); - let steps = app.session.active().unwrap().history.past_len(); - let frame = |app: &mut PhotocraftApp, close: bool| { - let mut input = egui::RawInput::default(); - if close { - let info = input.viewports.entry(egui::ViewportId::ROOT).or_default(); - info.events.push(egui::ViewportEvent::Close); - } - ctx.run_ui(input, |ui| show(app, ui.ctx())).textures_delta.clear(); - }; - open(&mut app, &ctx).unwrap(); - frame(&mut app, false); - assert!(app.camera_raw.is_some(), "drawn over the main window"); - ctx.set_embed_viewports(false); - frame(&mut app, false); - assert!(app.camera_raw.is_some(), "drawn in its window"); - frame(&mut app, true); - assert!(app.camera_raw.is_none(), "closing the window is Cancel"); - assert_eq!(app.session.active().unwrap().history.past_len(), steps); - } - - /// A layer with tonal variation, a selection over part of it and the dialog open on it. - fn worker_app() -> (PhotocraftApp, egui::Context) { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"color": "#406080"})).unwrap(); - app.run("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 30})).unwrap(); - open(&mut app, &ctx).unwrap(); - (app, ctx) - } - - fn finish_worker(d: &mut CameraRawDialog, ctx: &egui::Context) { - for _ in 0..2000 { - d.poll_render(ctx).unwrap(); - if !d.render_pending() { - return; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - panic!("the Camera Raw preview worker never finished"); - } - - /// The dialog's controls develop the proxy on a worker (#5964): the frame it shows is the one - /// the UI thread would have developed, and settings changed while it runs are developed next. - #[test] - fn worker_preview_matches_the_synchronous_render_and_ends_on_the_latest_settings() { - let (mut app, ctx) = worker_app(); - let d = app.camera_raw.as_mut().unwrap(); - assert!(d.selection.is_some()); - let revision = d.preview_revision; - d.params.exposure = 1.0; - d.dirty = true; - d.request_render(&ctx); - assert!(d.render_pending() && !d.dirty); - // A drag moves on while the first develop runs; the request waits for it. - d.params.highlights = -60.0; - d.params.shadows = 45.0; - d.dirty = true; - d.request_render(&ctx); - finish_worker(d, &ctx); - assert_eq!(d.preview_revision, revision + 1); - assert!(d.dirty, "the newer settings are still to be developed"); - d.request_render(&ctx); - finish_worker(d, &ctx); - assert_eq!(d.preview_revision, revision + 2); - let (from_worker, histogram) = (d.processed.clone(), d.after_histogram.channels); - d.render(&ctx); - assert_eq!(d.processed, from_worker, "the worker develops exactly what the UI thread does"); - assert_eq!(d.after_histogram.channels, histogram); - assert!(d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)["previewPending"] == false); - } - - /// The control channel renders on its own thread so its reply describes its settings; a worker - /// still running with older settings must not replace that frame afterwards. - #[test] - fn a_stale_worker_never_replaces_a_newer_synchronous_render() { - let (mut app, ctx) = worker_app(); - let d = app.camera_raw.as_mut().unwrap(); - d.params.highlights = -80.0; - d.dirty = true; - d.request_render(&ctx); - assert!(d.render_pending()); - let reply = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": 0, "exposure": -1.0}}})).unwrap().unwrap(); - assert_eq!(reply["previewPending"], false); - let d = app.camera_raw.as_mut().unwrap(); - let (revision, shown) = (d.preview_revision, d.processed.clone()); - std::thread::sleep(std::time::Duration::from_millis(200)); - d.poll_render(&ctx).unwrap(); - assert_eq!((d.preview_revision, &d.processed), (revision, &shown)); - d.render(&ctx); - assert_eq!(d.processed, shown, "the frame shown is the one for the control channel's settings"); - } - - /// Dragging a slider in the dialog itself never develops on the UI thread: the frame that - /// takes the change returns with the develop still running, and the preview catches up. - #[test] - fn a_dialog_edit_develops_off_the_ui_thread() { - let (mut app, ctx) = worker_app(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::Pro); - let frame = |app: &mut PhotocraftApp| { - ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui.ctx())).textures_delta.clear(); - }; - frame(&mut app); - let d = app.camera_raw.as_mut().unwrap(); - let revision = d.preview_revision; - d.params.highlights = -60.0; - d.dirty = true; - frame(&mut app); - let d = app.camera_raw.as_mut().unwrap(); - assert!(d.render_pending() && d.preview_revision == revision, "the frame returned before the develop finished"); - finish_worker(d, &ctx); - assert_eq!(d.preview_revision, revision + 1); - assert!(!d.dirty); - frame(&mut app); - assert!(!app.ui.status_error, "{}", app.ui.status); - } - - /// A failed worker develop shows its error until a later frame is published, and never takes - /// down an error something else reported meanwhile. - #[test] - fn a_worker_failure_is_reported_until_the_next_frame() { - let (mut app, ctx) = worker_app(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::Pro); - let frame = |app: &mut PhotocraftApp| { - ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui.ctx())).textures_delta.clear(); - }; - let fail = |app: &mut PhotocraftApp| { - let (tx, rx) = std::sync::mpsc::channel(); - tx.send(Err("Camera Raw preview failed".to_string())).unwrap(); - let d = app.camera_raw.as_mut().unwrap(); - d.pending = Some(rx); - d.dirty = false; - }; - let edit = |app: &mut PhotocraftApp, exposure: f32| { - let d = app.camera_raw.as_mut().unwrap(); - d.params.exposure = exposure; - d.dirty = true; - }; - frame(&mut app); - fail(&mut app); - frame(&mut app); - assert!(app.ui.status_error && app.ui.status == "Camera Raw preview failed", "{}", app.ui.status); - // No new frame yet: the error stays. - frame(&mut app); - assert!(app.ui.status_error); - edit(&mut app, 0.5); - frame(&mut app); - finish_worker(app.camera_raw.as_mut().unwrap(), &ctx); - frame(&mut app); - assert!(!app.ui.status_error && app.ui.status.is_empty(), "{}", app.ui.status); - - fail(&mut app); - frame(&mut app); - app.ui.status = "something else failed".into(); - edit(&mut app, 1.0); - frame(&mut app); - finish_worker(app.camera_raw.as_mut().unwrap(), &ctx); - frame(&mut app); - assert!(app.ui.status_error && app.ui.status == "something else failed", "{}", app.ui.status); - - // A control-channel edit renders on its own thread; the status is clear before any frame. - fail(&mut app); - frame(&mut app); - assert!(app.ui.status_error); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": -0.5}}})).unwrap().unwrap(); - assert!(!app.ui.status_error && app.ui.status.is_empty(), "{}", app.ui.status); - assert_eq!(crate::control::inspect(&app, &ctx)["statusError"], false); - } - - #[test] - fn smart_filter_double_click_edits_the_stored_camera_raw_filter_in_its_own_dialog() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"color": "#808080"})).unwrap(); - app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - // An older editor could save stacked curve inputs; the filter must stay editable. - let legacy = json!([[0.0, 0.0], [60.0, 40.0], [60.0, 200.0], [255.0, 255.0]]); - app.run("filter.cameraRaw", json!({"exposure": 1.0, "contrast": 20})).unwrap(); - app.run("layer.smartFilter.setParams", json!({"index": 0, "params": {"pointCurve": legacy}})).unwrap(); - let layer = app.session.active().unwrap().active_layer.unwrap(); - let smart = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(layer).unwrap().content { - photocraft_doc::LayerContent::Smart(sm) => sm.clone(), - _ => panic!("not a smart object"), - }; - let steps = app.session.active().unwrap().history.past_len(); - - let sm = smart(&app); - crate::smart_ui::open_editor(&mut app, &ctx, layer.0, &sm, 0); - assert!(app.ui.dialogs.is_empty(), "no generic parameter form"); - let opened = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {}})).unwrap().unwrap(); - assert_eq!(opened["smartFilter"], 0); - assert_eq!(opened["params"]["exposure"], 1.0); - assert_eq!(opened["params"]["pointCurve"], legacy); - // The preview starts from the pixels below the filter, not the filtered cache. - let before = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"before": true}})).unwrap().unwrap(); - assert_eq!(before["histogram"]["red"][128], 64 * 48); - - // Resetting a control to its default must overwrite the stored value. - let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 0.0}, "before": false, "commit": true}})).unwrap(); - assert!(r.is_ok(), "{r:?}"); - assert!(app.camera_raw.is_none()); - let sm = smart(&app); - assert_eq!(sm.smart_filters.len(), 1, "edited in place, not added"); - assert_eq!(sm.smart_filters[0].params["exposure"], 0.0); - assert_eq!(sm.smart_filters[0].params["contrast"], 20.0); - assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(smart(&app).smart_filters[0].params["exposure"], 1.0); - - // A broken new curve is still rejected; an unknown index is an error, not a panic. - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"smartFilter": {"layer": layer.0, "index": 0}})).unwrap().unwrap(); - assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"pointCurve": [[10, 10]]}}})).unwrap().is_err()); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"cancel": true}})).unwrap().unwrap(); - assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"smartFilter": {"layer": layer.0, "index": 7}})).unwrap().is_err()); - assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"smartFilter": {"layer": "x"}})).unwrap().is_err()); - } - - #[test] - fn distant_sparse_pixels_cannot_trigger_an_unbounded_proxy_scan() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width":64,"height":48})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - let layer = app.session.active().unwrap().active_layer.unwrap(); - let mut source = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); - source.write_region(Rect::new(30_000, 30_000, 30_001, 30_001), &[0.5, 0.5, 0.5, 1.0]); - let result = open_pixels(&mut app, &ctx, layer, source, CameraRaw::default(), Coverage::None, Target::NewFilter); - assert!(result.unwrap_err().contains("bounds are too large")); - assert!(app.camera_raw.is_none()); - } - - #[test] - fn dialog_drives_the_engine() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"color": "#808080"})).unwrap(); - let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({})).unwrap().unwrap(); - assert_eq!(r["proxy"], json!([64, 48])); - let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0, "vignetteAmount": -40}}})).unwrap().unwrap(); - assert_eq!(r["params"]["exposure"], 1.0); - assert_eq!(app.camera_raw.as_ref().unwrap().command_params(), json!({"exposure": 1.0, "vignetteAmount": -40.0})); - let before = app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(32, 24); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - assert!(app.camera_raw.is_none()); - let after = app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(32, 24); - assert!(after[0] > before[0] + 0.1, "{before:?} → {after:?}"); - // Cancel leaves the document alone. - menu(&mut app, &ctx, "filter.cameraRaw", &json!({})).unwrap().unwrap(); - let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"cancel": true}})).unwrap().unwrap(); - assert_eq!(r["cancelled"], true); - assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": "x"}}})).unwrap().is_err()); - } - - /// An app whose importer is the real one, opening a synthetic DNG. - fn raw_app() -> (PhotocraftApp, Vec) { - use photocraft_raw::testgen::{DngSpec, mosaic, scene}; - let services = crate::Services { - import: Some(Box::new(|name: &str, b: &[u8], opts: &photocraft_io::ImportOptions| { - photocraft_io::import_with_options(name, b, opts).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()) - })), - ..Default::default() - }; - let (w, h) = (48, 32); - let mut spec = DngSpec::cfa(w, h, mosaic(&scene(w, h), w, [0, 1, 1, 2], 0, 30000)); - spec.as_shot_neutral = Some([0.5, 1.0, 0.7]); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - // The pixel comparisons below read the developed ProPhoto values: no conversion on open - // (Camera Raw Defaults › Color space is Adobe RGB otherwise). - app.run("prefs.set", json!({"path": "rawDefaults.colorSpace", "value": "proPhoto"})).unwrap(); - (app, spec.build()) - } - - fn mean_red(app: &PhotocraftApp) -> f32 { - let st = app.session.active().unwrap(); - let s = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - (0..8).map(|i| s.rgba(4 + i * 4, 16)[0]).sum::() / 8.0 - } - - #[test] - fn raw_opens_in_camera_raw_and_open_redevelops() { - let (mut app, dng) = raw_app(); - let ctx = egui::Context::default(); - let warnings = app.open_bytes("IMG_0001.dng", &dng).unwrap(); - assert!(warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)), "{warnings:?}"); - // A raw has no embedded profile (ProPhoto RGB is the space it is developed into), so Ask - // When Opening (on by default) has nothing to ask about. - assert!(app.ui.dialogs.is_empty(), "no profile prompt for a raw"); - let raw = app.pending_raw_open.take().expect("a raw open queues the dialog"); - open_raw(&mut app, &ctx, raw).unwrap(); - let d = app.camera_raw.as_ref().unwrap(); - assert_eq!(d.target, Target::OpenRaw); - assert_eq!(d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)["openingRaw"]["name"], "IMG_0001.dng"); - let before = mean_red(&app); - 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!(app.camera_raw.is_none()); - assert_eq!(app.session.documents().len(), 1); - let st = app.session.active().unwrap(); - assert_eq!(st.saved_revision, st.revision, "Open leaves the document unmodified"); - assert_eq!(st.doc.depth, photocraft_color::SampleType::U16); - assert!(mean_red(&app) > before + 0.05, "{before} → {}", mean_red(&app)); - } - - fn pixels(app: &PhotocraftApp) -> Vec { - let st = app.session.active().unwrap(); - let s = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - (0..32).flat_map(|y| (0..48).map(move |x| (x, y))).flat_map(|(x, y)| s.rgba(x, y)).collect() - } - - #[test] - fn the_demosaic_method_is_chosen_at_open() { - let (mut app, dng) = raw_app(); - let ctx = egui::Context::default(); - app.open_bytes("IMG_0002.dng", &dng).unwrap(); - let ahd = pixels(&app); - let raw = app.pending_raw_open.take().unwrap(); - open_raw(&mut app, &ctx, raw).unwrap(); - let d = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"demosaic": "bilinear"}})).unwrap().unwrap(); - assert_eq!(d["openingRaw"]["demosaic"], "bilinear"); - assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"demosaic": "amaze"}})).unwrap().is_err()); - let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - assert_eq!(r["redeveloped"], true, "another method re-develops: {r}"); - assert!(r.get("filter").is_none(), "nothing else to apply: {r}"); - let bilinear = pixels(&app); - assert!(ahd.iter().zip(&bilinear).any(|(a, b)| (a - b).abs() > 1e-3), "bilinear differs from AHD"); - let st = app.session.active().unwrap(); - assert_eq!(st.saved_revision, st.revision); - - // The preference sets the method of the open itself; Open with it changes nothing. - app.run("prefs.set", json!({"path": "rawDefaults.demosaic", "value": "bilinear"})).unwrap(); - app.open_bytes("IMG_0003.dng", &dng).unwrap(); - assert_eq!(pixels(&app), bilinear, "developed with the preference's method"); - let raw = app.pending_raw_open.take().unwrap(); - open_raw(&mut app, &ctx, raw).unwrap(); - let d = app.camera_raw.as_ref().unwrap().describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview); - assert_eq!(d["openingRaw"]["demosaic"], "bilinear"); - let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - assert_eq!(r["redeveloped"], false, "{r}"); - - // Only the open-time dialog has the choice. - menu(&mut app, &ctx, "filter.cameraRaw", &json!({})).unwrap().unwrap(); - assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"demosaic": "ahd"}})).unwrap().is_err()); - - // The preference may change while a background open runs: the dialog starts from the - // method the open developed with (its note), not from the newer preference. - let warnings = app.open_bytes("IMG_0004.dng", &dng).unwrap(); - app.pending_raw_open.take(); - app.run("prefs.set", json!({"path": "rawDefaults.demosaic", "value": "ahd"})).unwrap(); - let document = app.session.active().unwrap().doc.id; - queue_open_dialog(&mut app, document, "IMG_0004.dng", None, Some(&dng), &warnings).unwrap(); - let raw = app.pending_raw_open.take().unwrap(); - use photocraft_io::raw::Demosaic; - assert_eq!((raw.developed_with, raw.demosaic), (Demosaic::Bilinear, Demosaic::Bilinear)); - } - - #[test] - fn shadows_of_a_raw_open_act_on_the_raw_data_and_the_preview_shows_it() { - let (mut app, dng) = raw_app(); - let ctx = egui::Context::default(); - app.open_bytes("IMG_0002.dng", &dng).unwrap(); - let raw = app.pending_raw_open.take().unwrap(); - open_raw(&mut app, &ctx, raw).unwrap(); - assert!(app.camera_raw.as_ref().unwrap().raw_curve.is_some(), "the preview knows how the raw was developed"); - let mean = |px: &[[f32; 4]]| px.iter().map(|p| p[0] + p[1] + p[2]).sum::() / px.len() as f32; - let preview_before = mean(&app.camera_raw.as_ref().unwrap().processed); - let before = mean_red(&app); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"shadows": 100}}})).unwrap().unwrap(); - let d = app.camera_raw.as_mut().unwrap(); - d.render(&ctx); - assert!(mean(&d.processed) > preview_before + 0.01, "{preview_before} → {}", mean(&d.processed)); - 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_none(), "Shadows acts while developing, not as a later filter step: {r}"); - assert!(mean_red(&app) > before + 0.01, "{before} → {}", mean_red(&app)); - } - - #[test] - fn clarity_texture_and_dehaze_of_a_raw_open_act_on_the_raw_data() { - let (mut app, dng) = raw_app(); - let ctx = egui::Context::default(); - app.open_bytes("IMG_0003.dng", &dng).unwrap(); - let raw = app.pending_raw_open.take().unwrap(); - open_raw(&mut app, &ctx, raw).unwrap(); - let before = mean_red(&app); - let preview_before = app.camera_raw.as_ref().unwrap().processed.clone(); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"clarity": 60, "texture": 40, "dehaze": 50}}})).unwrap().unwrap(); - let d = app.camera_raw.as_mut().unwrap(); - d.render(&ctx); - assert_ne!(d.processed, preview_before, "the preview shows the raw-stage change"); - 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_none(), "they act while developing, not as a later filter step: {r}"); - assert!(mean_red(&app) < before, "Dehaze darkens: {before} → {}", mean_red(&app)); - } - - #[test] - fn background_redevelop_keeps_the_tab_position_and_view() { - let (mut app, dng) = raw_app(); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 10, "height": 10})).unwrap(); - app.open_bytes("mid.dng", &dng).unwrap(); - app.run("file.new", json!({"width": 12, "height": 12})).unwrap(); - app.sync_views(); - let raw = app.pending_raw_open.take().unwrap(); - let old_id = raw.document; - assert_eq!(document_index(&app, old_id), Some(1)); - app.ui.views[1].zoom = 3.0; - open_raw(&mut app, &ctx, raw).unwrap(); - let before = mean_red(&app); - // The re-develop and the Camera Raw step run as jobs; the UI thread only polls. - app.background_jobs = true; - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0, "contrast": 20}}})).unwrap().unwrap(); - let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - assert_eq!(r["pending"], true, "{r}"); - assert!(app.camera_raw.is_none()); - for _ in 0..3000 { - crate::jobs_ui::tick(&mut app, &ctx); - if app.raw_redevelop.is_empty() && !app.session.has_jobs() { - break; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - assert!(app.raw_redevelop.is_empty() && !app.session.has_jobs(), "the jobs never finished"); - let docs = app.session.documents(); - assert_eq!(docs.len(), 3); - assert_eq!((docs[0].doc.size.width, docs[2].doc.size.width), (10, 12), "the other tabs keep their places"); - assert_ne!(docs[1].doc.id, old_id, "re-developed"); - assert_eq!(docs[1].doc.depth, photocraft_color::SampleType::U16); - assert_eq!(docs[1].saved_revision, docs[1].revision, "Open leaves the document unmodified"); - assert_eq!(app.session.active_index(), Some(1)); - assert_eq!(app.ui.views[1].zoom, 3.0, "the view carries over to the re-developed document"); - assert!(mean_red(&app) > before + 0.05, "{before} → {}", mean_red(&app)); - } - - /// #7789: Preferences › Raw Defaults › Resolution sets a raw's ppi when the app opens it - /// itself (no background job) and from automation, and a Camera Raw re-develop keeps it. - #[test] - fn a_raw_opens_and_redevelops_at_the_raw_defaults_resolution() { - let (mut app, dng) = raw_app(); - let ctx = egui::Context::default(); - app.run("prefs.set", json!({"path": "rawDefaults.resolution", "value": 240})).unwrap(); - app.open_bytes("IMG_0004.dng", &dng).unwrap(); - assert_eq!(app.session.active().unwrap().doc.resolution_dpi, 240.0); - let raw = app.pending_raw_open.take().unwrap(); - open_raw(&mut app, &ctx, raw).unwrap(); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0}}})).unwrap().unwrap(); - let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - assert_eq!(r["redeveloped"], true, "{r}"); - assert_eq!(app.session.active().unwrap().doc.resolution_dpi, 240.0, "kept by the re-develop"); - app.open_automation_bytes("IMG_0005.dng", &dng).unwrap(); - assert_eq!(app.session.active().unwrap().doc.resolution_dpi, 240.0, "automation open"); - } - - #[test] - fn cancel_closes_the_raw_and_the_preference_skips_the_dialog() { - let (mut app, dng) = raw_app(); - let ctx = egui::Context::default(); - app.open_bytes("a.dng", &dng).unwrap(); - let raw = app.pending_raw_open.take().unwrap(); - open_raw(&mut app, &ctx, raw).unwrap(); - let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"cancel": true}})).unwrap().unwrap(); - assert_eq!(r["cancelled"], true); - assert!(app.session.documents().is_empty(), "Cancel closes the raw being opened"); - // Unchanged settings: Open keeps the default develop and adds no step. - app.open_bytes("b.dng", &dng).unwrap(); - let raw = app.pending_raw_open.take().unwrap(); - 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}"); - // Preference off: raws open straight away. - app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap(); - app.open_bytes("c.dng", &dng).unwrap(); - assert!(app.pending_raw_open.is_none()); - // A non-raw never queues the dialog; a closed document is an error, not a panic. - assert!( - open_raw( - &mut app, - &ctx, - RawOpen { - document: photocraft_doc::DocId(u64::MAX), - name: "x".into(), - path: None, - bytes: None, - developed_with: Default::default(), - demosaic: Default::default() - } - ) - .is_err() - ); - } - - #[test] - fn calibration_changes_the_preview_and_round_trips_through_xmp() { - let (mut app, dng) = raw_app(); - let ctx = egui::Context::default(); - app.open_bytes("IMG_0005.dng", &dng).unwrap(); - let raw = app.pending_raw_open.take().unwrap(); - open_raw(&mut app, &ctx, raw).unwrap(); - let before = app.camera_raw.as_ref().unwrap().processed.clone(); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"shadowTint": 100, "calibrationHue": [100, 0, 0], "calibrationSat": [0, 0, -100]}}})) - .unwrap() - .unwrap(); - let d = app.camera_raw.as_mut().unwrap(); - d.render(&ctx); - assert!( - d.processed.iter().zip(&before).any(|(a, b)| (a[0] - b[0]).abs() > 0.01 || (a[1] - b[1]).abs() > 0.01), - "the Calibration panel changes the preview" - ); - let xmp = photocraft_io::camera_raw_xmp::save(&d.params); - assert!(xmp.contains("crs:ShadowTint=\"+100\"") && xmp.contains("crs:RedHue=\"+100\"") && xmp.contains("crs:BlueSaturation=\"-100\""), "{xmp}"); - let mut back = CameraRaw::default(); - photocraft_io::camera_raw_xmp::load(&mut back, xmp.as_bytes()).unwrap(); - assert_eq!((back.shadow_tint, back.calibration_hue, back.calibration_sat), (100.0, [100.0, 0.0, 0.0], [0.0, 0.0, -100.0])); - assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"auto": "yes"}})).unwrap().is_err(), "auto must be a boolean"); - } - - #[test] - fn auto_sets_the_light_sliders_from_the_image() { - let (mut app, dng) = raw_app(); - let ctx = egui::Context::default(); - app.open_bytes("IMG_0006.dng", &dng).unwrap(); - let raw = app.pending_raw_open.take().unwrap(); - open_raw(&mut app, &ctx, raw).unwrap(); - assert!(app.camera_raw.as_ref().unwrap().params.is_identity()); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"auto": true}})).unwrap().unwrap(); - let p = app.camera_raw.as_ref().unwrap().params.clone(); - assert!(!p.is_identity(), "Auto chose something: {p:?}"); - assert!(p.saturation == 0.0 && p.hsl_hue == [0.0; 8], "only the Light panel: {p:?}"); - // The preference does the same when a raw opens without a sidecar. - app.run("prefs.set", json!({"path": "rawDefaults.applyAutoTone", "value": true})).unwrap(); - app.open_bytes("IMG_0007.dng", &dng).unwrap(); - let raw = app.pending_raw_open.take().unwrap(); - open_raw(&mut app, &ctx, raw).unwrap(); - assert_eq!(app.camera_raw.as_ref().unwrap().params, p, "Apply auto tone opens the dialog with Auto's settings"); - } - - #[test] - fn a_sidecar_fills_the_dialog_and_open_writes_it_back() { - use std::sync::{Arc, Mutex}; - let (mut app, dng) = raw_app(); - let dir = std::env::temp_dir().join(format!("photocraft-sidecar-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let raw_path = dir.join("IMG_0008.cr2").to_string_lossy().into_owned(); - std::fs::write(&raw_path, &dng).unwrap(); - assert_eq!(sidecar_path(&raw_path), dir.join("IMG_0008.xmp").to_string_lossy()); - assert_eq!(sidecar_path("/a/b.c/noext"), "/a/b.c/noext.xmp"); - std::fs::write( - sidecar_path(&raw_path), - "", - ) - .unwrap(); - type Written = Arc)>>>; - let written: Written = Arc::default(); - let sink = written.clone(); - app.services.write = Some(Box::new(move |p: &str, b: &[u8]| { - sink.lock().unwrap().push((p.to_string(), b.to_vec())); - Ok(()) - })); - let ctx = egui::Context::default(); - app.open_bytes("IMG_0008.cr2", &dng).unwrap(); - let mut raw = app.pending_raw_open.take().unwrap(); - raw.path = Some(raw_path.clone()); - open_raw(&mut app, &ctx, raw).unwrap(); - let d = app.camera_raw.as_ref().unwrap(); - assert_eq!((d.params.exposure, d.params.shadow_tint), (1.5, 20.0), "the sidecar fills the dialog"); - assert!( - app.ui.status.contains("IMG_0008.xmp") && app.ui.status.contains("Temperature"), - "the absolute white balance is reported as not supported: {}", - app.ui.status - ); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 15}}})).unwrap().unwrap(); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - let w = written.lock().unwrap().clone(); - assert_eq!(w.len(), 1, "Open writes the sidecar once: {:?}", w.iter().map(|(p, _)| p).collect::>()); - assert_eq!(w[0].0, sidecar_path(&raw_path)); - let text = String::from_utf8(w[0].1.clone()).unwrap(); - assert!(text.contains("crs:Exposure2012=\"+1.50\"") && text.contains("crs:Contrast2012=\"+15\"") && text.contains("crs:ShadowTint=\"+20\""), "{text}"); - // A DNG keeps its settings inside: no sidecar beside it. And the preference turns writing off. - written.lock().unwrap().clear(); - let dng_path = dir.join("IMG_0009.dng").to_string_lossy().into_owned(); - std::fs::write(&dng_path, &dng).unwrap(); - app.open_bytes("IMG_0009.dng", &dng).unwrap(); - let mut raw = app.pending_raw_open.take().unwrap(); - raw.path = Some(dng_path); - open_raw(&mut app, &ctx, raw).unwrap(); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 15}, "commit": true}})).unwrap().unwrap(); - assert!(written.lock().unwrap().is_empty(), "no sidecar for a DNG"); - app.run("prefs.set", json!({"path": "rawDefaults.writeXmpSidecars", "value": false})).unwrap(); - app.open_bytes("IMG_0008.cr2", &dng).unwrap(); - let mut raw = app.pending_raw_open.take().unwrap(); - raw.path = Some(raw_path.clone()); - open_raw(&mut app, &ctx, raw).unwrap(); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 30}, "commit": true}})).unwrap().unwrap(); - assert!(written.lock().unwrap().is_empty(), "the preference stops the write"); - // Without the dialog, the sidecar still develops the file. - app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap(); - let before = app.session.documents().len(); - app.open_file(&raw_path, &dng).unwrap(); - assert!(app.pending_raw_open.is_none()); - assert_eq!(app.session.documents().len(), before + 1); - let st = app.session.active().unwrap(); - assert_eq!(st.saved_revision, st.revision, "opening with a sidecar leaves the document unmodified"); - assert!(mean_red(&app) > 0.0); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn camera_raw_defaults_apply_when_a_raw_opens() { - let (mut app, dng) = raw_app(); - app.run("prefs.set", json!({"values": {"rawDefaults.openInCameraRaw": false, "rawDefaults.colorSpace": "srgb", "rawDefaults.bitDepth": "8", "rawDefaults.resolution": 240.0, "rawDefaults.sharpenFor": "screen", "rawDefaults.openAsSmartObject": true}})).unwrap(); - app.open_bytes("IMG_0010.dng", &dng).unwrap(); - assert!(app.pending_raw_open.is_none()); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.depth, photocraft_color::SampleType::U8, "Bit depth 8"); - assert_eq!(st.doc.resolution_dpi, 240.0, "Resolution"); - let profile = st.doc.icc_profile.as_deref().and_then(|p| photocraft_cms::Profile::parse(p).ok()).map(|p| p.description).unwrap_or_default(); - assert!(profile.to_lowercase().contains("srgb"), "Color space: {profile}"); - let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); - assert!(matches!(layer.content, photocraft_doc::LayerContent::Smart(_)), "Open as Smart Object"); - assert_eq!(st.saved_revision, st.revision, "the defaults are part of opening: unmodified"); - // The dialog's Open applies them too, and reports what it applied. - app.run("prefs.set", json!({"values": {"rawDefaults.openInCameraRaw": true, "rawDefaults.openAsSmartObject": false, "rawDefaults.bitDepth": "16"}})) - .unwrap(); - let ctx = egui::Context::default(); - app.open_bytes("IMG_0011.dng", &dng).unwrap(); - let raw = app.pending_raw_open.take().unwrap(); - 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}"); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.depth, photocraft_color::SampleType::U16); - assert_eq!(st.saved_revision, st.revision); - } - - type Written = std::sync::Arc)>>>; - - /// A sidecar as Lightroom Classic leaves one beside a raw: its own toolkit, a crop, a rating - /// and a keyword next to the develop settings (values synthetic). - const LIGHTROOM_SIDECAR: &str = r#" - - - harbour - - - -"#; - - /// `raw_app` whose `write` service records what it is asked to write, and a raw file in a fresh - /// folder with `sidecar` beside it when given. Returns the app, the raw's bytes, the folder, - /// the raw's path and the recorded writes. - fn raw_with_sidecar(tag: &str, sidecar: Option<&str>) -> (PhotocraftApp, Vec, std::path::PathBuf, String, Written) { - let (mut app, dng) = raw_app(); - let dir = std::env::temp_dir().join(format!("photocraft-sidecar-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let raw_path = dir.join("IMG_0100.cr2").to_string_lossy().into_owned(); - std::fs::write(&raw_path, &dng).unwrap(); - if let Some(text) = sidecar { - std::fs::write(sidecar_path(&raw_path), text).unwrap(); - } - let written: Written = Default::default(); - let sink = written.clone(); - app.services.write = Some(Box::new(move |p: &str, b: &[u8]| { - sink.lock().unwrap().push((p.to_string(), b.to_vec())); - Ok(()) - })); - (app, dng, dir, raw_path, written) - } - - /// Opens the raw at `raw_path` in the open-time dialog, as File › Open does. - fn open_dialog_at(app: &mut PhotocraftApp, ctx: &egui::Context, dng: &[u8], raw_path: &str) { - app.open_bytes("IMG_0100.cr2", dng).unwrap(); - let mut raw = app.pending_raw_open.take().unwrap(); - raw.path = Some(raw_path.to_string()); - open_raw(app, ctx, raw).unwrap(); - } - - /// The notices about the sidecar (the open's own import notes aside). - fn notice_titles(app: &PhotocraftApp) -> Vec { - app.ui.notices.iter().map(|n| n.title.clone()).filter(|t| t.contains(".xmp")).collect() - } - - /// A Lightroom or Bridge sidecar holds settings PhotoCraft can't keep (crop, masks, rating, - /// keywords): Open uses its develop settings but never writes over it, and says so. - #[test] - fn a_foreign_sidecar_is_never_overwritten() { - let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("foreign", Some(LIGHTROOM_SIDECAR)); - let ctx = egui::Context::default(); - open_dialog_at(&mut app, &ctx, &dng, &raw_path); - assert_eq!(app.camera_raw.as_ref().unwrap().params.exposure, 1.0, "the sidecar's settings fill the dialog"); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 15}}})).unwrap().unwrap(); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - assert!(written.lock().unwrap().is_empty(), "nothing written over Lightroom's sidecar"); - assert_eq!(std::fs::read_to_string(sidecar_path(&raw_path)).unwrap(), LIGHTROOM_SIDECAR); - let titles = notice_titles(&app); - assert!(titles.iter().any(|t| t.contains("IMG_0100.xmp") && t.contains("another application")), "{titles:?}"); - let _ = std::fs::remove_dir_all(&dir); - } - - /// Bridge writes a sidecar with only a rating (no Camera Raw settings): it is not PhotoCraft's - /// to replace, with or without a change in the dialog. - #[test] - fn a_rating_only_sidecar_is_left_alone() { - let bridge = r#""#; - let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("rating", Some(bridge)); - let ctx = egui::Context::default(); - open_dialog_at(&mut app, &ctx, &dng, &raw_path); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - assert!(written.lock().unwrap().is_empty(), "Open with no change writes nothing"); - assert!(notice_titles(&app).is_empty(), "and has nothing to report: {:?}", notice_titles(&app)); - open_dialog_at(&mut app, &ctx, &dng, &raw_path); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 10}, "commit": true}})).unwrap().unwrap(); - assert!(written.lock().unwrap().is_empty(), "nor with a change"); - assert_eq!(std::fs::read_to_string(sidecar_path(&raw_path)).unwrap(), bridge); - 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] - fn opening_without_the_dialog_does_not_rewrite_the_sidecar() { - let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("nodialog", Some(LIGHTROOM_SIDECAR)); - app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap(); - app.open_file(&raw_path, &dng).unwrap(); - assert!(app.pending_raw_open.is_none()); - assert_eq!(app.session.documents().len(), 1); - assert!(written.lock().unwrap().is_empty(), "just opening never writes the sidecar"); - assert_eq!(std::fs::read_to_string(sidecar_path(&raw_path)).unwrap(), LIGHTROOM_SIDECAR); - assert!(notice_titles(&app).is_empty(), "{:?}", notice_titles(&app)); - let _ = std::fs::remove_dir_all(&dir); - } - - /// A control or MCP request has no authority to write beside the user's files: its commit - /// develops the raw but writes no sidecar. The same Open from the dialog does. - #[test] - fn a_control_request_never_writes_the_sidecar() { - fn allow(_: &str, _: &Value) -> photocraft_engine::Result<()> { - Ok(()) - } - let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("control", None); - app.services.automation_authorize = Some(allow); - let ctx = egui::Context::default(); - open_dialog_at(&mut app, &ctx, &dng, &raw_path); - let commit = json!({"id": "filter.cameraRaw", "params": {"ui": {"set": {"contrast": 15}, "commit": true}}}); - let (req, _rx) = crate::control::ControlRequest::new("ui.menu.invoke", commit); - let crate::control::Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &req) else { panic!("expected a reply") }; - assert_eq!(reply["ok"], true, "{reply}"); - assert!(app.camera_raw.is_none(), "committed"); - assert!(written.lock().unwrap().is_empty(), "no sidecar from a control request"); - 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!(written.lock().unwrap().len(), 1, "the user's own Open writes it"); - let _ = std::fs::remove_dir_all(&dir); - } - - /// A sidecar that can't be written is reported in a notice that outlasts the status line the - /// develop and the Camera Raw step write after it. - #[test] - fn a_sidecar_write_error_stays_reported() { - let (mut app, dng, dir, raw_path, _) = raw_with_sidecar("readonly", None); - app.services.write = Some(Box::new(|_: &str, _: &[u8]| Err("read-only volume".to_string()))); - let ctx = egui::Context::default(); - open_dialog_at(&mut app, &ctx, &dng, &raw_path); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 0.5, "contrast": 15}, "commit": true}})).unwrap().unwrap(); - let errors: Vec<_> = app.ui.notices.iter().filter(|n| n.error).map(|n| n.title.clone()).collect(); - assert!(errors.iter().any(|t| t.contains("IMG_0100.xmp") && t.contains("read-only volume")), "{errors:?}"); - let _ = std::fs::remove_dir_all(&dir); - } - - fn open_with_settings(app: &mut PhotocraftApp, ctx: &egui::Context, dng: &[u8], name: &str) { - app.open_bytes(name, dng).unwrap(); - let raw = app.pending_raw_open.take().unwrap(); - open_raw(app, ctx, raw).unwrap(); - menu(app, ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 0.5, "contrast": 60, "saturation": 40, "vibrance": 30}}})).unwrap().unwrap(); - } - - fn profile_name(app: &PhotocraftApp) -> String { - let st = app.session.active().unwrap(); - st.doc.icc_profile.as_deref().and_then(|p| photocraft_cms::Profile::parse(p).ok()).map(|p| p.description).unwrap_or_default() - } - - /// Camera Raw renders in its own space and converts to the workflow space last, so Open gives - /// what the dialog previewed on the developed ProPhoto pixels: with the default Adobe RGB the - /// result is the Camera Raw step on the ProPhoto develop, then the conversion. Inline and with - /// the re-develop as a background job. - #[test] - fn the_camera_raw_step_runs_before_the_workflow_conversion() { - let ctx = egui::Context::default(); - let (mut app, dng) = raw_app(); - open_with_settings(&mut app, &ctx, &dng, "a.dng"); - menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - app.run("edit.convertToProfile", json!({"profile": "adobe-rgb-compat", "intent": "relative"})).unwrap(); - let want = pixels(&app); - let close = |a: &[f32], b: &[f32]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5); - for background in [false, true] { - let (mut app, dng) = raw_app(); - app.run("prefs.set", json!({"path": "rawDefaults.colorSpace", "value": "adobeRgb"})).unwrap(); - open_with_settings(&mut app, &ctx, &dng, "b.dng"); - app.background_jobs = background; - let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - if background { - assert_eq!(r["pending"], true, "the re-develop runs as a job: {r}"); - } else { - assert_eq!(r["defaults"], json!(["colorSpace"]), "{r}"); - } - for _ in 0..3000 { - crate::jobs_ui::tick(&mut app, &ctx); - if app.raw_redevelop.is_empty() && !app.session.has_jobs() { - break; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - assert!(app.raw_redevelop.is_empty() && !app.session.has_jobs(), "the jobs never finished"); - assert!(profile_name(&app).to_lowercase().contains("adobe"), "background {background}: {}", profile_name(&app)); - assert!(close(&pixels(&app), &want), "background {background}: the step ran on other pixels than the preview"); - let st = app.session.active().unwrap(); - assert_eq!(st.saved_revision, st.revision, "background {background}: unmodified"); - } - } - - /// Two raws opened one after the other while the first one's re-develop still runs in the - /// background: each lands with its Camera Raw step and conversions and is left unmodified. - #[test] - fn two_raws_opened_back_to_back_both_finish_their_open() { - let ctx = egui::Context::default(); - let (mut app, dng) = raw_app(); - app.run("prefs.set", json!({"path": "rawDefaults.colorSpace", "value": "adobeRgb"})).unwrap(); - open_with_settings(&mut app, &ctx, &dng, "a.dng"); - app.background_jobs = true; - let a = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - assert_eq!(a["pending"], true, "the re-develop runs as a job: {a}"); - app.background_jobs = false; - open_with_settings(&mut app, &ctx, &dng, "b.dng"); - app.background_jobs = true; - let b = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - assert_eq!(b["pending"], true, "{b}"); - for _ in 0..3000 { - crate::jobs_ui::tick(&mut app, &ctx); - if app.raw_redevelop.is_empty() && !app.session.has_jobs() { - break; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - assert!(app.raw_redevelop.is_empty() && !app.session.has_jobs(), "the jobs never finished"); - assert_eq!(app.session.documents().len(), 2); - for i in 0..2 { - app.session.set_active(i); - assert!(profile_name(&app).to_lowercase().contains("adobe"), "document {i}: {}", profile_name(&app)); - let st = app.session.active().unwrap(); - assert_eq!(st.saved_revision, st.revision, "document {i} unmodified"); - } - } - - /// A sidecar is read only from a regular file of at most `MAX_XMP_BYTES`: a folder, or a file - /// one byte larger, is not read (a pipe or device named like one would never end). - #[test] - fn sidecars_are_read_from_small_regular_files_only() { - let dir = std::env::temp_dir().join(format!("photocraft-sidecar-bounded-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(dir.join("folder.xmp")).unwrap(); - let cap = photocraft_io::camera_raw_xmp::MAX_XMP_BYTES; - let (fits, larger) = (dir.join("fits.xmp"), dir.join("larger.xmp")); - std::fs::write(&fits, vec![b' '; cap]).unwrap(); - std::fs::write(&larger, vec![b' '; cap + 1]).unwrap(); - let s = |p: std::path::PathBuf| p.to_string_lossy().into_owned(); - assert_eq!(read_bounded(&s(fits)).map(|b| b.len()), Some(cap)); - assert_eq!(read_bounded(&s(larger.clone())), None); - assert_eq!(read_bounded(&s(dir.join("folder.xmp"))), None); - assert_eq!(read_bounded(&s(dir.join("missing.xmp"))), None); - assert_eq!(existing_sidecar_is_ours(&s(dir.join("folder.xmp"))), Some(false), "something is there: never written over"); - assert_eq!(existing_sidecar_is_ours(&s(larger)), Some(false)); - assert_eq!(existing_sidecar_is_ours(&s(dir.join("missing.xmp"))), None); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn save_and_load_settings_round_trip_through_xmp_files() { - use crate::file_dialog::FileDialogAnswer; - use std::sync::{Arc, Mutex}; - type Written = Arc)>>>; - let written: Written = Arc::default(); - let w = written.clone(); - let foreign = br#" - - "#; - let answers = vec![ - Some(FileDialogAnswer::SaveTo("/out/Look.xmp".into())), - Some(FileDialogAnswer::Contents("Look.xmp".into(), Vec::new())), - Some(FileDialogAnswer::Contents("Other.xmp".into(), foreign.to_vec())), - Some(FileDialogAnswer::Contents("Broken.xmp".into(), b" (PhotocraftApp, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#406080"})).unwrap(); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 30})).unwrap(); + open(&mut app, &ctx).unwrap(); + (app, ctx) +} + +fn finish_worker(d: &mut CameraRawDialog, ctx: &egui::Context) { + for _ in 0..2000 { + d.poll_render(ctx).unwrap(); + if !d.render_pending() { + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("the Camera Raw preview worker never finished"); +} + +/// The dialog's controls develop the proxy on a worker (#5964): the frame it shows is the one +/// the UI thread would have developed, and settings changed while it runs are developed next. +#[test] +fn worker_preview_matches_the_synchronous_render_and_ends_on_the_latest_settings() { + let (mut app, ctx) = worker_app(); + let d = app.camera_raw.as_mut().unwrap(); + assert!(d.selection.is_some()); + let revision = d.preview_revision; + d.params.exposure = 1.0; + d.dirty = true; + d.request_render(&ctx); + assert!(d.render_pending() && !d.dirty); + // A drag moves on while the first develop runs; the request waits for it. + d.params.highlights = -60.0; + d.params.shadows = 45.0; + d.dirty = true; + d.request_render(&ctx); + finish_worker(d, &ctx); + assert_eq!(d.preview_revision, revision + 1); + assert!(d.dirty, "the newer settings are still to be developed"); + d.request_render(&ctx); + finish_worker(d, &ctx); + assert_eq!(d.preview_revision, revision + 2); + let (from_worker, histogram) = (d.processed.clone(), d.after_histogram.channels); + d.render(&ctx); + assert_eq!(d.processed, from_worker, "the worker develops exactly what the UI thread does"); + assert_eq!(d.after_histogram.channels, histogram); + assert!(d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)["previewPending"] == false); +} + +/// The control channel renders on its own thread so its reply describes its settings; a worker +/// still running with older settings must not replace that frame afterwards. +#[test] +fn a_stale_worker_never_replaces_a_newer_synchronous_render() { + let (mut app, ctx) = worker_app(); + let d = app.camera_raw.as_mut().unwrap(); + d.params.highlights = -80.0; + d.dirty = true; + d.request_render(&ctx); + assert!(d.render_pending()); + let reply = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"highlights": 0, "exposure": -1.0}}})).unwrap().unwrap(); + assert_eq!(reply["previewPending"], false); + let d = app.camera_raw.as_mut().unwrap(); + let (revision, shown) = (d.preview_revision, d.processed.clone()); + std::thread::sleep(std::time::Duration::from_millis(200)); + d.poll_render(&ctx).unwrap(); + assert_eq!((d.preview_revision, &d.processed), (revision, &shown)); + d.render(&ctx); + assert_eq!(d.processed, shown, "the frame shown is the one for the control channel's settings"); +} + +/// Dragging a slider in the dialog itself never develops on the UI thread: the frame that +/// takes the change returns with the develop still running, and the preview catches up. +#[test] +fn a_dialog_edit_develops_off_the_ui_thread() { + let (mut app, ctx) = worker_app(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::Pro); + let frame = |app: &mut PhotocraftApp| { + ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui.ctx())).textures_delta.clear(); + }; + frame(&mut app); + let d = app.camera_raw.as_mut().unwrap(); + let revision = d.preview_revision; + d.params.highlights = -60.0; + d.dirty = true; + frame(&mut app); + let d = app.camera_raw.as_mut().unwrap(); + assert!(d.render_pending() && d.preview_revision == revision, "the frame returned before the develop finished"); + finish_worker(d, &ctx); + assert_eq!(d.preview_revision, revision + 1); + assert!(!d.dirty); + frame(&mut app); + assert!(!app.ui.status_error, "{}", app.ui.status); +} + +/// A failed worker develop shows its error until a later frame is published, and never takes +/// down an error something else reported meanwhile. +#[test] +fn a_worker_failure_is_reported_until_the_next_frame() { + let (mut app, ctx) = worker_app(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::Pro); + let frame = |app: &mut PhotocraftApp| { + ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui.ctx())).textures_delta.clear(); + }; + let fail = |app: &mut PhotocraftApp| { + let (tx, rx) = std::sync::mpsc::channel(); + tx.send(Err("Camera Raw preview failed".to_string())).unwrap(); + let d = app.camera_raw.as_mut().unwrap(); + d.pending = Some(rx); + d.dirty = false; + }; + let edit = |app: &mut PhotocraftApp, exposure: f32| { + let d = app.camera_raw.as_mut().unwrap(); + d.params.exposure = exposure; + d.dirty = true; + }; + frame(&mut app); + fail(&mut app); + frame(&mut app); + assert!(app.ui.status_error && app.ui.status == "Camera Raw preview failed", "{}", app.ui.status); + // No new frame yet: the error stays. + frame(&mut app); + assert!(app.ui.status_error); + edit(&mut app, 0.5); + frame(&mut app); + finish_worker(app.camera_raw.as_mut().unwrap(), &ctx); + frame(&mut app); + assert!(!app.ui.status_error && app.ui.status.is_empty(), "{}", app.ui.status); + + fail(&mut app); + frame(&mut app); + app.ui.status = "something else failed".into(); + edit(&mut app, 1.0); + frame(&mut app); + finish_worker(app.camera_raw.as_mut().unwrap(), &ctx); + frame(&mut app); + assert!(app.ui.status_error && app.ui.status == "something else failed", "{}", app.ui.status); + + // A control-channel edit renders on its own thread; the status is clear before any frame. + fail(&mut app); + frame(&mut app); + assert!(app.ui.status_error); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": -0.5}}})).unwrap().unwrap(); + assert!(!app.ui.status_error && app.ui.status.is_empty(), "{}", app.ui.status); + assert_eq!(crate::control::inspect(&app, &ctx)["statusError"], false); +} + +#[test] +fn smart_filter_double_click_edits_the_stored_camera_raw_filter_in_its_own_dialog() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#808080"})).unwrap(); + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + // An older editor could save stacked curve inputs; the filter must stay editable. + let legacy = json!([[0.0, 0.0], [60.0, 40.0], [60.0, 200.0], [255.0, 255.0]]); + app.run("filter.cameraRaw", json!({"exposure": 1.0, "contrast": 20})).unwrap(); + app.run("layer.smartFilter.setParams", json!({"index": 0, "params": {"pointCurve": legacy}})).unwrap(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + let smart = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(layer).unwrap().content { + photocraft_doc::LayerContent::Smart(sm) => sm.clone(), + _ => panic!("not a smart object"), + }; + let steps = app.session.active().unwrap().history.past_len(); + + let sm = smart(&app); + crate::smart_ui::open_editor(&mut app, &ctx, layer.0, &sm, 0); + assert!(app.ui.dialogs.is_empty(), "no generic parameter form"); + let opened = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {}})).unwrap().unwrap(); + assert_eq!(opened["smartFilter"], 0); + assert_eq!(opened["params"]["exposure"], 1.0); + assert_eq!(opened["params"]["pointCurve"], legacy); + // The preview starts from the pixels below the filter, not the filtered cache. + let before = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"before": true}})).unwrap().unwrap(); + assert_eq!(before["histogram"]["red"][128], 64 * 48); + + // Resetting a control to its default must overwrite the stored value. + let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 0.0}, "before": false, "commit": true}})).unwrap(); + assert!(r.is_ok(), "{r:?}"); + assert!(app.camera_raw.is_none()); + let sm = smart(&app); + assert_eq!(sm.smart_filters.len(), 1, "edited in place, not added"); + assert_eq!(sm.smart_filters[0].params["exposure"], 0.0); + assert_eq!(sm.smart_filters[0].params["contrast"], 20.0); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(smart(&app).smart_filters[0].params["exposure"], 1.0); + + // A broken new curve is still rejected; an unknown index is an error, not a panic. + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"smartFilter": {"layer": layer.0, "index": 0}})).unwrap().unwrap(); + assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"pointCurve": [[10, 10]]}}})).unwrap().is_err()); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"cancel": true}})).unwrap().unwrap(); + assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"smartFilter": {"layer": layer.0, "index": 7}})).unwrap().is_err()); + assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"smartFilter": {"layer": "x"}})).unwrap().is_err()); +} + +#[test] +fn distant_sparse_pixels_cannot_trigger_an_unbounded_proxy_scan() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width":64,"height":48})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + let mut source = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); + source.write_region(Rect::new(30_000, 30_000, 30_001, 30_001), &[0.5, 0.5, 0.5, 1.0]); + let result = open_pixels(&mut app, &ctx, layer, source, CameraRaw::default(), Coverage::None, Target::NewFilter); + assert!(result.unwrap_err().contains("bounds are too large")); + assert!(app.camera_raw.is_none()); +} + +#[test] +fn dialog_drives_the_engine() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#808080"})).unwrap(); + let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({})).unwrap().unwrap(); + assert_eq!(r["proxy"], json!([64, 48])); + let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0, "vignetteAmount": -40}}})).unwrap().unwrap(); + assert_eq!(r["params"]["exposure"], 1.0); + assert_eq!(app.camera_raw.as_ref().unwrap().command_params(), json!({"exposure": 1.0, "vignetteAmount": -40.0})); + let before = app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(32, 24); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert!(app.camera_raw.is_none()); + let after = app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(32, 24); + assert!(after[0] > before[0] + 0.1, "{before:?} → {after:?}"); + // Cancel leaves the document alone. + menu(&mut app, &ctx, "filter.cameraRaw", &json!({})).unwrap().unwrap(); + let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"cancel": true}})).unwrap().unwrap(); + assert_eq!(r["cancelled"], true); + assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": "x"}}})).unwrap().is_err()); +} + +/// An app whose importer is the real one, opening a synthetic DNG. +fn raw_app() -> (PhotocraftApp, Vec) { + use photocraft_raw::testgen::{DngSpec, mosaic, scene}; + let services = crate::Services { + import: Some(Box::new(|name: &str, b: &[u8], opts: &photocraft_io::ImportOptions| { + photocraft_io::import_with_options(name, b, opts).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()) + })), + ..Default::default() + }; + let (w, h) = (48, 32); + let mut spec = DngSpec::cfa(w, h, mosaic(&scene(w, h), w, [0, 1, 1, 2], 0, 30000)); + spec.as_shot_neutral = Some([0.5, 1.0, 0.7]); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + // The pixel comparisons below read the developed ProPhoto values: no conversion on open + // (Camera Raw Defaults › Color space is Adobe RGB otherwise). + app.run("prefs.set", json!({"path": "rawDefaults.colorSpace", "value": "proPhoto"})).unwrap(); + (app, spec.build()) +} + +fn mean_red(app: &PhotocraftApp) -> f32 { + let st = app.session.active().unwrap(); + let s = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + (0..8).map(|i| s.rgba(4 + i * 4, 16)[0]).sum::() / 8.0 +} + +#[test] +fn raw_opens_in_camera_raw_and_open_redevelops() { + let (mut app, dng) = raw_app(); + let ctx = egui::Context::default(); + let warnings = app.open_bytes("IMG_0001.dng", &dng).unwrap(); + assert!(warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)), "{warnings:?}"); + // A raw has no embedded profile (ProPhoto RGB is the space it is developed into), so Ask + // When Opening (on by default) has nothing to ask about. + assert!(app.ui.dialogs.is_empty(), "no profile prompt for a raw"); + let raw = app.pending_raw_open.take().expect("a raw open queues the dialog"); + open_raw(&mut app, &ctx, raw).unwrap(); + let d = app.camera_raw.as_ref().unwrap(); + assert_eq!(d.target, Target::OpenRaw); + assert_eq!(d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)["openingRaw"]["name"], "IMG_0001.dng"); + let before = mean_red(&app); + 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!(app.camera_raw.is_none()); + assert_eq!(app.session.documents().len(), 1); + let st = app.session.active().unwrap(); + assert_eq!(st.saved_revision, st.revision, "Open leaves the document unmodified"); + assert_eq!(st.doc.depth, photocraft_color::SampleType::U16); + assert!(mean_red(&app) > before + 0.05, "{before} → {}", mean_red(&app)); +} + +fn pixels(app: &PhotocraftApp) -> Vec { + let st = app.session.active().unwrap(); + let s = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + (0..32).flat_map(|y| (0..48).map(move |x| (x, y))).flat_map(|(x, y)| s.rgba(x, y)).collect() +} + +#[test] +fn the_demosaic_method_is_chosen_at_open() { + let (mut app, dng) = raw_app(); + let ctx = egui::Context::default(); + app.open_bytes("IMG_0002.dng", &dng).unwrap(); + let ahd = pixels(&app); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + let d = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"demosaic": "bilinear"}})).unwrap().unwrap(); + assert_eq!(d["openingRaw"]["demosaic"], "bilinear"); + assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"demosaic": "amaze"}})).unwrap().is_err()); + let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert_eq!(r["redeveloped"], true, "another method re-develops: {r}"); + assert!(r.get("filter").is_none(), "nothing else to apply: {r}"); + let bilinear = pixels(&app); + assert!(ahd.iter().zip(&bilinear).any(|(a, b)| (a - b).abs() > 1e-3), "bilinear differs from AHD"); + let st = app.session.active().unwrap(); + assert_eq!(st.saved_revision, st.revision); + + // The preference sets the method of the open itself; Open with it changes nothing. + app.run("prefs.set", json!({"path": "rawDefaults.demosaic", "value": "bilinear"})).unwrap(); + app.open_bytes("IMG_0003.dng", &dng).unwrap(); + assert_eq!(pixels(&app), bilinear, "developed with the preference's method"); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + let d = app.camera_raw.as_ref().unwrap().describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview); + assert_eq!(d["openingRaw"]["demosaic"], "bilinear"); + let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert_eq!(r["redeveloped"], false, "{r}"); + + // Only the open-time dialog has the choice. + menu(&mut app, &ctx, "filter.cameraRaw", &json!({})).unwrap().unwrap(); + assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"demosaic": "ahd"}})).unwrap().is_err()); + + // The preference may change while a background open runs: the dialog starts from the + // method the open developed with (its note), not from the newer preference. + let warnings = app.open_bytes("IMG_0004.dng", &dng).unwrap(); + app.pending_raw_open.take(); + app.run("prefs.set", json!({"path": "rawDefaults.demosaic", "value": "ahd"})).unwrap(); + let document = app.session.active().unwrap().doc.id; + queue_open_dialog(&mut app, document, "IMG_0004.dng", None, Some(&dng), &warnings).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + use photocraft_io::raw::Demosaic; + assert_eq!((raw.developed_with, raw.demosaic), (Demosaic::Bilinear, Demosaic::Bilinear)); +} + +#[test] +fn shadows_of_a_raw_open_act_on_the_raw_data_and_the_preview_shows_it() { + let (mut app, dng) = raw_app(); + let ctx = egui::Context::default(); + app.open_bytes("IMG_0002.dng", &dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + assert!(app.camera_raw.as_ref().unwrap().raw_curve.is_some(), "the preview knows how the raw was developed"); + let mean = |px: &[[f32; 4]]| px.iter().map(|p| p[0] + p[1] + p[2]).sum::() / px.len() as f32; + let preview_before = mean(&app.camera_raw.as_ref().unwrap().processed); + let before = mean_red(&app); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"shadows": 100}}})).unwrap().unwrap(); + let d = app.camera_raw.as_mut().unwrap(); + d.render(&ctx); + assert!(mean(&d.processed) > preview_before + 0.01, "{preview_before} → {}", mean(&d.processed)); + 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_none(), "Shadows acts while developing, not as a later filter step: {r}"); + assert!(mean_red(&app) > before + 0.01, "{before} → {}", mean_red(&app)); +} + +#[test] +fn clarity_texture_and_dehaze_of_a_raw_open_act_on_the_raw_data() { + let (mut app, dng) = raw_app(); + let ctx = egui::Context::default(); + app.open_bytes("IMG_0003.dng", &dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + let before = mean_red(&app); + let preview_before = app.camera_raw.as_ref().unwrap().processed.clone(); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"clarity": 60, "texture": 40, "dehaze": 50}}})).unwrap().unwrap(); + let d = app.camera_raw.as_mut().unwrap(); + d.render(&ctx); + assert_ne!(d.processed, preview_before, "the preview shows the raw-stage change"); + 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_none(), "they act while developing, not as a later filter step: {r}"); + assert!(mean_red(&app) < before, "Dehaze darkens: {before} → {}", mean_red(&app)); +} + +#[test] +fn background_redevelop_keeps_the_tab_position_and_view() { + let (mut app, dng) = raw_app(); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 10, "height": 10})).unwrap(); + app.open_bytes("mid.dng", &dng).unwrap(); + app.run("file.new", json!({"width": 12, "height": 12})).unwrap(); + app.sync_views(); + let raw = app.pending_raw_open.take().unwrap(); + let old_id = raw.document; + assert_eq!(document_index(&app, old_id), Some(1)); + app.ui.views[1].zoom = 3.0; + open_raw(&mut app, &ctx, raw).unwrap(); + let before = mean_red(&app); + // The re-develop and the Camera Raw step run as jobs; the UI thread only polls. + app.background_jobs = true; + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0, "contrast": 20}}})).unwrap().unwrap(); + let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert_eq!(r["pending"], true, "{r}"); + assert!(app.camera_raw.is_none()); + for _ in 0..3000 { + crate::jobs_ui::tick(&mut app, &ctx); + if app.raw_redevelop.is_empty() && !app.session.has_jobs() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(app.raw_redevelop.is_empty() && !app.session.has_jobs(), "the jobs never finished"); + let docs = app.session.documents(); + assert_eq!(docs.len(), 3); + assert_eq!((docs[0].doc.size.width, docs[2].doc.size.width), (10, 12), "the other tabs keep their places"); + assert_ne!(docs[1].doc.id, old_id, "re-developed"); + assert_eq!(docs[1].doc.depth, photocraft_color::SampleType::U16); + assert_eq!(docs[1].saved_revision, docs[1].revision, "Open leaves the document unmodified"); + assert_eq!(app.session.active_index(), Some(1)); + assert_eq!(app.ui.views[1].zoom, 3.0, "the view carries over to the re-developed document"); + assert!(mean_red(&app) > before + 0.05, "{before} → {}", mean_red(&app)); +} + +/// #7789: Preferences › Raw Defaults › Resolution sets a raw's ppi when the app opens it +/// itself (no background job) and from automation, and a Camera Raw re-develop keeps it. +#[test] +fn a_raw_opens_and_redevelops_at_the_raw_defaults_resolution() { + let (mut app, dng) = raw_app(); + let ctx = egui::Context::default(); + app.run("prefs.set", json!({"path": "rawDefaults.resolution", "value": 240})).unwrap(); + app.open_bytes("IMG_0004.dng", &dng).unwrap(); + assert_eq!(app.session.active().unwrap().doc.resolution_dpi, 240.0); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0}}})).unwrap().unwrap(); + let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert_eq!(r["redeveloped"], true, "{r}"); + assert_eq!(app.session.active().unwrap().doc.resolution_dpi, 240.0, "kept by the re-develop"); + app.open_automation_bytes("IMG_0005.dng", &dng).unwrap(); + assert_eq!(app.session.active().unwrap().doc.resolution_dpi, 240.0, "automation open"); +} + +#[test] +fn cancel_closes_the_raw_and_the_preference_skips_the_dialog() { + let (mut app, dng) = raw_app(); + let ctx = egui::Context::default(); + app.open_bytes("a.dng", &dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"cancel": true}})).unwrap().unwrap(); + assert_eq!(r["cancelled"], true); + assert!(app.session.documents().is_empty(), "Cancel closes the raw being opened"); + // Unchanged settings: Open keeps the default develop and adds no step. + app.open_bytes("b.dng", &dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + 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}"); + // Preference off: raws open straight away. + app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap(); + app.open_bytes("c.dng", &dng).unwrap(); + assert!(app.pending_raw_open.is_none()); + // A non-raw never queues the dialog; a closed document is an error, not a panic. + assert!( + open_raw( + &mut app, + &ctx, + RawOpen { + document: photocraft_doc::DocId(u64::MAX), + name: "x".into(), + path: None, + bytes: None, + developed_with: Default::default(), + demosaic: Default::default() + } + ) + .is_err() + ); +} + +#[test] +fn calibration_changes_the_preview_and_round_trips_through_xmp() { + let (mut app, dng) = raw_app(); + let ctx = egui::Context::default(); + app.open_bytes("IMG_0005.dng", &dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + let before = app.camera_raw.as_ref().unwrap().processed.clone(); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"shadowTint": 100, "calibrationHue": [100, 0, 0], "calibrationSat": [0, 0, -100]}}})) + .unwrap() + .unwrap(); + let d = app.camera_raw.as_mut().unwrap(); + d.render(&ctx); + assert!( + d.processed.iter().zip(&before).any(|(a, b)| (a[0] - b[0]).abs() > 0.01 || (a[1] - b[1]).abs() > 0.01), + "the Calibration panel changes the preview" + ); + let xmp = photocraft_io::camera_raw_xmp::save(&d.params); + assert!(xmp.contains("crs:ShadowTint=\"+100\"") && xmp.contains("crs:RedHue=\"+100\"") && xmp.contains("crs:BlueSaturation=\"-100\""), "{xmp}"); + let mut back = CameraRaw::default(); + photocraft_io::camera_raw_xmp::load(&mut back, xmp.as_bytes()).unwrap(); + assert_eq!((back.shadow_tint, back.calibration_hue, back.calibration_sat), (100.0, [100.0, 0.0, 0.0], [0.0, 0.0, -100.0])); + assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"auto": "yes"}})).unwrap().is_err(), "auto must be a boolean"); +} + +#[test] +fn auto_sets_the_light_sliders_from_the_image() { + let (mut app, dng) = raw_app(); + let ctx = egui::Context::default(); + app.open_bytes("IMG_0006.dng", &dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + assert!(app.camera_raw.as_ref().unwrap().params.is_identity()); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"auto": true}})).unwrap().unwrap(); + let p = app.camera_raw.as_ref().unwrap().params.clone(); + assert!(!p.is_identity(), "Auto chose something: {p:?}"); + assert!(p.saturation == 0.0 && p.hsl_hue == [0.0; 8], "only the Light panel: {p:?}"); + // The preference does the same when a raw opens without a sidecar. + app.run("prefs.set", json!({"path": "rawDefaults.applyAutoTone", "value": true})).unwrap(); + app.open_bytes("IMG_0007.dng", &dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + assert_eq!(app.camera_raw.as_ref().unwrap().params, p, "Apply auto tone opens the dialog with Auto's settings"); +} + +#[test] +fn a_sidecar_fills_the_dialog_and_open_writes_it_back() { + use std::sync::{Arc, Mutex}; + let (mut app, dng) = raw_app(); + let dir = std::env::temp_dir().join(format!("photocraft-sidecar-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let raw_path = dir.join("IMG_0008.cr2").to_string_lossy().into_owned(); + std::fs::write(&raw_path, &dng).unwrap(); + assert_eq!(sidecar_path(&raw_path), dir.join("IMG_0008.xmp").to_string_lossy()); + assert_eq!(sidecar_path("/a/b.c/noext"), "/a/b.c/noext.xmp"); + std::fs::write( + sidecar_path(&raw_path), + "", + ) + .unwrap(); + type Written = Arc)>>>; + let written: Written = Arc::default(); + let sink = written.clone(); + app.services.write = Some(Box::new(move |p: &str, b: &[u8]| { + sink.lock().unwrap().push((p.to_string(), b.to_vec())); + Ok(()) + })); + let ctx = egui::Context::default(); + app.open_bytes("IMG_0008.cr2", &dng).unwrap(); + let mut raw = app.pending_raw_open.take().unwrap(); + raw.path = Some(raw_path.clone()); + open_raw(&mut app, &ctx, raw).unwrap(); + let d = app.camera_raw.as_ref().unwrap(); + assert_eq!((d.params.exposure, d.params.shadow_tint), (1.5, 20.0), "the sidecar fills the dialog"); + assert!( + app.ui.status.contains("IMG_0008.xmp") && app.ui.status.contains("Temperature"), + "the absolute white balance is reported as not supported: {}", + app.ui.status + ); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 15}}})).unwrap().unwrap(); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + let w = written.lock().unwrap().clone(); + assert_eq!(w.len(), 1, "Open writes the sidecar once: {:?}", w.iter().map(|(p, _)| p).collect::>()); + assert_eq!(w[0].0, sidecar_path(&raw_path)); + let text = String::from_utf8(w[0].1.clone()).unwrap(); + assert!(text.contains("crs:Exposure2012=\"+1.50\"") && text.contains("crs:Contrast2012=\"+15\"") && text.contains("crs:ShadowTint=\"+20\""), "{text}"); + // A DNG keeps its settings inside: no sidecar beside it. And the preference turns writing off. + written.lock().unwrap().clear(); + let dng_path = dir.join("IMG_0009.dng").to_string_lossy().into_owned(); + std::fs::write(&dng_path, &dng).unwrap(); + app.open_bytes("IMG_0009.dng", &dng).unwrap(); + let mut raw = app.pending_raw_open.take().unwrap(); + raw.path = Some(dng_path); + open_raw(&mut app, &ctx, raw).unwrap(); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 15}, "commit": true}})).unwrap().unwrap(); + assert!(written.lock().unwrap().is_empty(), "no sidecar for a DNG"); + app.run("prefs.set", json!({"path": "rawDefaults.writeXmpSidecars", "value": false})).unwrap(); + app.open_bytes("IMG_0008.cr2", &dng).unwrap(); + let mut raw = app.pending_raw_open.take().unwrap(); + raw.path = Some(raw_path.clone()); + open_raw(&mut app, &ctx, raw).unwrap(); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 30}, "commit": true}})).unwrap().unwrap(); + assert!(written.lock().unwrap().is_empty(), "the preference stops the write"); + // Without the dialog, the sidecar still develops the file. + app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap(); + let before = app.session.documents().len(); + app.open_file(&raw_path, &dng).unwrap(); + assert!(app.pending_raw_open.is_none()); + assert_eq!(app.session.documents().len(), before + 1); + let st = app.session.active().unwrap(); + assert_eq!(st.saved_revision, st.revision, "opening with a sidecar leaves the document unmodified"); + assert!(mean_red(&app) > 0.0); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn camera_raw_defaults_apply_when_a_raw_opens() { + let (mut app, dng) = raw_app(); + app.run("prefs.set", json!({"values": {"rawDefaults.openInCameraRaw": false, "rawDefaults.colorSpace": "srgb", "rawDefaults.bitDepth": "8", "rawDefaults.resolution": 240.0, "rawDefaults.sharpenFor": "screen", "rawDefaults.openAsSmartObject": true}})).unwrap(); + app.open_bytes("IMG_0010.dng", &dng).unwrap(); + assert!(app.pending_raw_open.is_none()); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.depth, photocraft_color::SampleType::U8, "Bit depth 8"); + assert_eq!(st.doc.resolution_dpi, 240.0, "Resolution"); + let profile = st.doc.icc_profile.as_deref().and_then(|p| photocraft_cms::Profile::parse(p).ok()).map(|p| p.description).unwrap_or_default(); + assert!(profile.to_lowercase().contains("srgb"), "Color space: {profile}"); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert!(matches!(layer.content, photocraft_doc::LayerContent::Smart(_)), "Open as Smart Object"); + assert_eq!(st.saved_revision, st.revision, "the defaults are part of opening: unmodified"); + // The dialog's Open applies them too, and reports what it applied. + app.run("prefs.set", json!({"values": {"rawDefaults.openInCameraRaw": true, "rawDefaults.openAsSmartObject": false, "rawDefaults.bitDepth": "16"}})) + .unwrap(); + let ctx = egui::Context::default(); + app.open_bytes("IMG_0011.dng", &dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + 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}"); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.depth, photocraft_color::SampleType::U16); + assert_eq!(st.saved_revision, st.revision); +} + +type Written = std::sync::Arc)>>>; + +/// A sidecar as Lightroom Classic leaves one beside a raw: its own toolkit, a crop, a rating +/// and a keyword next to the develop settings (values synthetic). +const LIGHTROOM_SIDECAR: &str = r#" + + + harbour + + + +"#; + +/// `raw_app` whose `write` service records what it is asked to write, and a raw file in a fresh +/// folder with `sidecar` beside it when given. Returns the app, the raw's bytes, the folder, +/// the raw's path and the recorded writes. +fn raw_with_sidecar(tag: &str, sidecar: Option<&str>) -> (PhotocraftApp, Vec, std::path::PathBuf, String, Written) { + let (mut app, dng) = raw_app(); + let dir = std::env::temp_dir().join(format!("photocraft-sidecar-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let raw_path = dir.join("IMG_0100.cr2").to_string_lossy().into_owned(); + std::fs::write(&raw_path, &dng).unwrap(); + if let Some(text) = sidecar { + std::fs::write(sidecar_path(&raw_path), text).unwrap(); + } + let written: Written = Default::default(); + let sink = written.clone(); + app.services.write = Some(Box::new(move |p: &str, b: &[u8]| { + sink.lock().unwrap().push((p.to_string(), b.to_vec())); + Ok(()) + })); + (app, dng, dir, raw_path, written) +} + +/// Opens the raw at `raw_path` in the open-time dialog, as File › Open does. +fn open_dialog_at(app: &mut PhotocraftApp, ctx: &egui::Context, dng: &[u8], raw_path: &str) { + app.open_bytes("IMG_0100.cr2", dng).unwrap(); + let mut raw = app.pending_raw_open.take().unwrap(); + raw.path = Some(raw_path.to_string()); + open_raw(app, ctx, raw).unwrap(); +} + +/// The notices about the sidecar (the open's own import notes aside). +fn notice_titles(app: &PhotocraftApp) -> Vec { + app.ui.notices.iter().map(|n| n.title.clone()).filter(|t| t.contains(".xmp")).collect() +} + +/// A Lightroom or Bridge sidecar holds settings PhotoCraft can't keep (crop, masks, rating, +/// keywords): Open uses its develop settings but never writes over it, and says so. +#[test] +fn a_foreign_sidecar_is_never_overwritten() { + let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("foreign", Some(LIGHTROOM_SIDECAR)); + let ctx = egui::Context::default(); + open_dialog_at(&mut app, &ctx, &dng, &raw_path); + assert_eq!(app.camera_raw.as_ref().unwrap().params.exposure, 1.0, "the sidecar's settings fill the dialog"); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 15}}})).unwrap().unwrap(); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert!(written.lock().unwrap().is_empty(), "nothing written over Lightroom's sidecar"); + assert_eq!(std::fs::read_to_string(sidecar_path(&raw_path)).unwrap(), LIGHTROOM_SIDECAR); + let titles = notice_titles(&app); + assert!(titles.iter().any(|t| t.contains("IMG_0100.xmp") && t.contains("another application")), "{titles:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Bridge writes a sidecar with only a rating (no Camera Raw settings): it is not PhotoCraft's +/// to replace, with or without a change in the dialog. +#[test] +fn a_rating_only_sidecar_is_left_alone() { + let bridge = r#""#; + let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("rating", Some(bridge)); + let ctx = egui::Context::default(); + open_dialog_at(&mut app, &ctx, &dng, &raw_path); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert!(written.lock().unwrap().is_empty(), "Open with no change writes nothing"); + assert!(notice_titles(&app).is_empty(), "and has nothing to report: {:?}", notice_titles(&app)); + open_dialog_at(&mut app, &ctx, &dng, &raw_path); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 10}, "commit": true}})).unwrap().unwrap(); + assert!(written.lock().unwrap().is_empty(), "nor with a change"); + assert_eq!(std::fs::read_to_string(sidecar_path(&raw_path)).unwrap(), bridge); + 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] +fn opening_without_the_dialog_does_not_rewrite_the_sidecar() { + let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("nodialog", Some(LIGHTROOM_SIDECAR)); + app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap(); + app.open_file(&raw_path, &dng).unwrap(); + assert!(app.pending_raw_open.is_none()); + assert_eq!(app.session.documents().len(), 1); + assert!(written.lock().unwrap().is_empty(), "just opening never writes the sidecar"); + assert_eq!(std::fs::read_to_string(sidecar_path(&raw_path)).unwrap(), LIGHTROOM_SIDECAR); + assert!(notice_titles(&app).is_empty(), "{:?}", notice_titles(&app)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A control or MCP request has no authority to write beside the user's files: its commit +/// develops the raw but writes no sidecar. The same Open from the dialog does. +#[test] +fn a_control_request_never_writes_the_sidecar() { + fn allow(_: &str, _: &Value) -> photocraft_engine::Result<()> { + Ok(()) + } + let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("control", None); + app.services.automation_authorize = Some(allow); + let ctx = egui::Context::default(); + open_dialog_at(&mut app, &ctx, &dng, &raw_path); + let commit = json!({"id": "filter.cameraRaw", "params": {"ui": {"set": {"contrast": 15}, "commit": true}}}); + let (req, _rx) = crate::control::ControlRequest::new("ui.menu.invoke", commit); + let crate::control::Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &req) else { panic!("expected a reply") }; + assert_eq!(reply["ok"], true, "{reply}"); + assert!(app.camera_raw.is_none(), "committed"); + assert!(written.lock().unwrap().is_empty(), "no sidecar from a control request"); + 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!(written.lock().unwrap().len(), 1, "the user's own Open writes it"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A sidecar that can't be written is reported in a notice that outlasts the status line the +/// develop and the Camera Raw step write after it. +#[test] +fn a_sidecar_write_error_stays_reported() { + let (mut app, dng, dir, raw_path, _) = raw_with_sidecar("readonly", None); + app.services.write = Some(Box::new(|_: &str, _: &[u8]| Err("read-only volume".to_string()))); + let ctx = egui::Context::default(); + open_dialog_at(&mut app, &ctx, &dng, &raw_path); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 0.5, "contrast": 15}, "commit": true}})).unwrap().unwrap(); + let errors: Vec<_> = app.ui.notices.iter().filter(|n| n.error).map(|n| n.title.clone()).collect(); + assert!(errors.iter().any(|t| t.contains("IMG_0100.xmp") && t.contains("read-only volume")), "{errors:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +fn open_with_settings(app: &mut PhotocraftApp, ctx: &egui::Context, dng: &[u8], name: &str) { + app.open_bytes(name, dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(app, ctx, raw).unwrap(); + menu(app, ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 0.5, "contrast": 60, "saturation": 40, "vibrance": 30}}})).unwrap().unwrap(); +} + +fn profile_name(app: &PhotocraftApp) -> String { + let st = app.session.active().unwrap(); + st.doc.icc_profile.as_deref().and_then(|p| photocraft_cms::Profile::parse(p).ok()).map(|p| p.description).unwrap_or_default() +} + +/// Camera Raw renders in its own space and converts to the workflow space last, so Open gives +/// what the dialog previewed on the developed ProPhoto pixels: with the default Adobe RGB the +/// result is the Camera Raw step on the ProPhoto develop, then the conversion. Inline and with +/// the re-develop as a background job. +#[test] +fn the_camera_raw_step_runs_before_the_workflow_conversion() { + let ctx = egui::Context::default(); + let (mut app, dng) = raw_app(); + open_with_settings(&mut app, &ctx, &dng, "a.dng"); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + app.run("edit.convertToProfile", json!({"profile": "adobe-rgb-compat", "intent": "relative"})).unwrap(); + let want = pixels(&app); + let close = |a: &[f32], b: &[f32]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5); + for background in [false, true] { + let (mut app, dng) = raw_app(); + app.run("prefs.set", json!({"path": "rawDefaults.colorSpace", "value": "adobeRgb"})).unwrap(); + open_with_settings(&mut app, &ctx, &dng, "b.dng"); + app.background_jobs = background; + let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + if background { + assert_eq!(r["pending"], true, "the re-develop runs as a job: {r}"); + } else { + assert_eq!(r["defaults"], json!(["colorSpace"]), "{r}"); + } + for _ in 0..3000 { + crate::jobs_ui::tick(&mut app, &ctx); + if app.raw_redevelop.is_empty() && !app.session.has_jobs() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(app.raw_redevelop.is_empty() && !app.session.has_jobs(), "the jobs never finished"); + assert!(profile_name(&app).to_lowercase().contains("adobe"), "background {background}: {}", profile_name(&app)); + assert!(close(&pixels(&app), &want), "background {background}: the step ran on other pixels than the preview"); + let st = app.session.active().unwrap(); + assert_eq!(st.saved_revision, st.revision, "background {background}: unmodified"); + } +} + +/// Two raws opened one after the other while the first one's re-develop still runs in the +/// background: each lands with its Camera Raw step and conversions and is left unmodified. +#[test] +fn two_raws_opened_back_to_back_both_finish_their_open() { + let ctx = egui::Context::default(); + let (mut app, dng) = raw_app(); + app.run("prefs.set", json!({"path": "rawDefaults.colorSpace", "value": "adobeRgb"})).unwrap(); + open_with_settings(&mut app, &ctx, &dng, "a.dng"); + app.background_jobs = true; + let a = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert_eq!(a["pending"], true, "the re-develop runs as a job: {a}"); + app.background_jobs = false; + open_with_settings(&mut app, &ctx, &dng, "b.dng"); + app.background_jobs = true; + let b = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert_eq!(b["pending"], true, "{b}"); + for _ in 0..3000 { + crate::jobs_ui::tick(&mut app, &ctx); + if app.raw_redevelop.is_empty() && !app.session.has_jobs() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(app.raw_redevelop.is_empty() && !app.session.has_jobs(), "the jobs never finished"); + assert_eq!(app.session.documents().len(), 2); + for i in 0..2 { + app.session.set_active(i); + assert!(profile_name(&app).to_lowercase().contains("adobe"), "document {i}: {}", profile_name(&app)); + let st = app.session.active().unwrap(); + assert_eq!(st.saved_revision, st.revision, "document {i} unmodified"); + } +} + +/// A sidecar is read only from a regular file of at most `MAX_XMP_BYTES`: a folder, or a file +/// one byte larger, is not read (a pipe or device named like one would never end). +#[test] +fn sidecars_are_read_from_small_regular_files_only() { + let dir = std::env::temp_dir().join(format!("photocraft-sidecar-bounded-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("folder.xmp")).unwrap(); + let cap = photocraft_io::camera_raw_xmp::MAX_XMP_BYTES; + let (fits, larger) = (dir.join("fits.xmp"), dir.join("larger.xmp")); + std::fs::write(&fits, vec![b' '; cap]).unwrap(); + std::fs::write(&larger, vec![b' '; cap + 1]).unwrap(); + let s = |p: std::path::PathBuf| p.to_string_lossy().into_owned(); + assert_eq!(read_bounded(&s(fits)).map(|b| b.len()), Some(cap)); + assert_eq!(read_bounded(&s(larger.clone())), None); + assert_eq!(read_bounded(&s(dir.join("folder.xmp"))), None); + assert_eq!(read_bounded(&s(dir.join("missing.xmp"))), None); + assert_eq!(existing_sidecar_is_ours(&s(dir.join("folder.xmp"))), Some(false), "something is there: never written over"); + assert_eq!(existing_sidecar_is_ours(&s(larger)), Some(false)); + assert_eq!(existing_sidecar_is_ours(&s(dir.join("missing.xmp"))), None); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn save_and_load_settings_round_trip_through_xmp_files() { + use crate::file_dialog::FileDialogAnswer; + use std::sync::{Arc, Mutex}; + type Written = Arc)>>>; + let written: Written = Arc::default(); + let w = written.clone(); + let foreign = br#" + + "#; + let answers = vec![ + Some(FileDialogAnswer::SaveTo("/out/Look.xmp".into())), + Some(FileDialogAnswer::Contents("Look.xmp".into(), Vec::new())), + Some(FileDialogAnswer::Contents("Other.xmp".into(), foreign.to_vec())), + Some(FileDialogAnswer::Contents("Broken.xmp".into(), b" Date: Mon, 26 Oct 2026 18:16:58 +0000 Subject: [PATCH 073/259] refactor(ui-egui): move layer_style.rs tests to layer_style/tests.rs --- crates/ui-egui/src/layer_style.rs | 1027 +---------------------- crates/ui-egui/src/layer_style/tests.rs | 1024 ++++++++++++++++++++++ 2 files changed, 1025 insertions(+), 1026 deletions(-) create mode 100644 crates/ui-egui/src/layer_style/tests.rs diff --git a/crates/ui-egui/src/layer_style.rs b/crates/ui-egui/src/layer_style.rs index b8fb211ccf..2b63ee3379 100644 --- a/crates/ui-egui/src/layer_style.rs +++ b/crates/ui-egui/src/layer_style.rs @@ -1471,1029 +1471,4 @@ impl MaxAlpha for Color32 { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_doc::StrokeFx; - - /// #5701: with a shadow page selected, a drag on the image moves the shadow: its offset - /// follows the pointer, as whole degrees and pixels, the global light angle with it. - #[test] - fn dragging_on_the_image_moves_the_selected_shadow() { - let shadow = |id: &str, kind: &str, global: bool| json!({"id": id, "kind": kind, "on": true, "params": {"angle": 120.0, "distance": 10.0, "useGlobalLight": global}}); - let mut f = Map::new(); - f.insert("selected".into(), json!("fx1")); - f.insert("globalLight".into(), json!(120.0)); - f.insert("effects".into(), json!([shadow("fx1", "dropShadow", true), shadow("fx2", "innerShadow", true), shadow("fx3", "dropShadow", false)])); - assert!(drags_shadow(&f)); - let params = |f: &Map, id: &str| { - let p = &entry(f, id).unwrap()["params"]; - (p["angle"].as_f64().unwrap(), p["distance"].as_f64().unwrap()) - }; - // The press keeps the shadow where it is: (5, 8.66) px. - drag_shadow(&mut f, true, [0.0, 0.0]); - assert_eq!(params(&f, "fx1"), (120.0, 10.0)); - // Dragged to (15, 0): straight right of the layer, the light from the left (180°). - drag_shadow(&mut f, false, [10.0, -8.660_254]); - assert_eq!(params(&f, "fx1"), (180.0, 15.0)); - assert_eq!(params(&f, "fx2").0, 180.0, "the global light angle is shared"); - assert_eq!(params(&f, "fx3"), (120.0, 10.0), "an instance with its own angle is left alone"); - // Back onto the layer: no offset, and the angle the drag started with. - drag_shadow(&mut f, false, [-5.0, -8.660_254]); - assert_eq!(params(&f, "fx1"), (120.0, 0.0)); - // Not on a shadow page: nothing moves. - f.insert("selected".into(), json!(BLENDING)); - assert!(!drags_shadow(&f)); - drag_shadow(&mut f, true, [50.0, 50.0]); - assert_eq!(params(&f, "fx1"), (120.0, 0.0)); - } - - fn session() -> photocraft_engine::Session { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s - } - - fn strokes_of(s: &photocraft_engine::Session) -> Vec { - let d = s.active().unwrap(); - let id = d.active_layer.unwrap(); - d.doc - .layer(id) - .unwrap() - .effects - .items - .iter() - .filter_map(|e| match e { - Effect::Stroke(st) => Some(st.clone()), - _ => None, - }) - .collect() - } - - /// #1357: every effect row has its checkbox from the start, also for the effects not on the - /// layer yet (an empty box), not only after one was turned on and off again. - #[test] - fn every_effect_row_shows_a_checkbox() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - let l = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8); - let fields = initial_fields(&l, Some(BLENDING), 120.0); - let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state( - move |ui, app: &mut PhotocraftApp| { - if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - let mut f = fields.clone(); - body(app, ui, &mut f); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); - h.run_steps(3); - let boxes: Vec = h - .output() - .shapes - .iter() - .filter_map(|c| match &c.shape { - egui::Shape::Rect(r) if r.rect.size() == vec2(14.0, 14.0) && r.stroke.width > 0.0 => Some(r.rect), - _ => None, - }) - .collect(); - // The effect list is the leftmost column; the selected pane draws checkboxes of its own. - let column = boxes.iter().map(|r| r.min.x).fold(f32::INFINITY, f32::min); - let rows = boxes.iter().filter(|r| (r.min.x - column).abs() < 0.5).count(); - assert_eq!(rows, KINDS.len(), "one empty checkbox per effect row"); - } - - // Regression test for #2209: Make Default and Reset to Default sat in a non-wrapping row, so - // translated labels wider than the page column (Russian) pushed one button over the other - // and out of the column instead of wrapping to a second row. - #[test] - fn default_buttons_wrap_inside_the_page_column_with_long_labels() { - use egui_kittest::kittest::Queryable; - let ru = crate::i18n::Lang::from_code("ru").unwrap(); - crate::i18n::with_language(ru, || { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - let l = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8); - let fields = initial_fields(&l, Some("dropShadow"), 120.0); - let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state( - move |ui, app: &mut PhotocraftApp| { - if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - let mut f = fields.clone(); - body(app, ui, &mut f); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); - h.run_steps(3); - let reset = h.get_by_role_and_label(egui::accesskit::Role::Button, crate::i18n::tr(ru, "Reset to Default")).rect(); - let make = h.get_by_role_and_label(egui::accesskit::Role::Button, crate::i18n::tr(ru, "Make Default")).rect(); - // Together they are wider than the page column: the second wraps to a row below - // instead of sharing the row and running left over the effect list. - assert!(make.top() >= reset.bottom(), "the buttons share one row: {make:?} {reset:?}"); - assert_eq!(make.right(), reset.right(), "the wrapped row stays right-aligned"); - }); - } - - /// Double-clicking an effect row of a layer that isn't active selects that layer first, so - /// the dialog holds its effects (and OK edits it), not the active layer's. - #[test] - fn effect_row_of_another_layer_opens_that_layers_style() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - let with_fx = app.session.active().unwrap().active_layer.unwrap(); - app.run("layer.layerStyle.replace", json!({"layer": with_fx.0, "effects": [{"kind": "dropShadow", "params": defaults("dropShadow")}]})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - let plain = app.session.active().unwrap().active_layer.unwrap(); - assert_ne!(plain, with_fx); - assert!(app.session.active().unwrap().doc.layer(plain).unwrap().effects.items.is_empty()); - - let id = open_for_layer(&mut app, with_fx, Some("dropShadow")).unwrap(); - assert_eq!(app.session.active().unwrap().active_layer, Some(with_fx), "the row's layer becomes active"); - let d = app.ui.dialogs.iter().find(|d| d.id == id).unwrap(); - assert_eq!(d.fields["layer"], json!(with_fx.0)); - let fx = effects_of(&d.fields); - assert_eq!(fx.len(), 1); - assert_eq!(fx[0]["kind"], json!("dropShadow")); - assert!(fx[0]["fx"].is_object(), "the existing drop shadow, not a new instance"); - } - - #[test] - fn every_kind_has_spec_and_defaults() { - for &(kind, _) in KINDS { - assert!(!spec(kind).is_empty(), "{kind}"); - let d = defaults(kind); - for &(key, _, _) in spec(kind) { - assert!(d.get(key).is_some(), "{kind}.{key} has no default"); - } - } - } - - #[test] - fn adding_an_effect_after_maximum_instance_id_uses_an_unused_id() { - // Imported and scripted effects can provide arbitrary instance IDs. - let layer = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8); - let mut fields = initial_fields(&layer, None, 120.0); - fields.insert( - "effects".into(), - json!([ - {"id": "fx1", "kind": "stroke", "on": true, "params": {}}, - {"id": format!("fx{}", u64::MAX), "kind": "stroke", "on": false, "params": {}} - ]), - ); - add_instance(&mut fields, "stroke"); - - let ids: Vec<&str> = effects_of(&fields).iter().filter_map(|e| e.get("id").and_then(Value::as_str)).collect(); - assert_eq!(ids, ["fx1", "fx18446744073709551615", "fx2"]); - assert_eq!(fields["selected"], json!("fx2")); - } - - #[test] - fn initial_fields_lists_every_instance_and_selects() { - let l = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8); - let f = initial_fields(&l, Some("stroke"), 120.0); - assert_eq!(f["globalLight"], json!(120.0)); - // The kind isn't on the layer yet: selecting it creates the instance. - assert_eq!(f["effects"].as_array().unwrap().len(), 1); - assert_eq!(f["effects"][0]["kind"], json!("stroke")); - assert_eq!(f["effects"][0]["on"], json!(true)); - assert_eq!(f["selected"], json!("fx1")); - // Opening the blending page selects no instance. - let f = initial_fields(&l, Some(BLENDING), 120.0); - assert_eq!(f["selected"], json!(BLENDING)); - assert!(effects_of(&f).is_empty()); - } - - #[test] - fn open_and_confirm_preserves_two_strokes() { - // The manga/typesetting case: a 3 px black stroke under a 7 px white one. - let mut s = session(); - s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000"})).unwrap(); - s.execute("layer.layerStyle.stroke", json!({"size": 7, "color": "#ffffff", "add": true})).unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); - assert_eq!(effects_of(&f).len(), 2, "both instances load"); - // Confirm without touching anything: both strokes, same order and params. - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let strokes = strokes_of(&s); - assert_eq!(strokes.len(), 2); - assert_eq!((strokes[0].size, strokes[1].size), (3.0, 7.0)); - assert_eq!(strokes[0].paint, FxPaint::Color(photocraft_color::Color::BLACK)); - assert_eq!(strokes[1].paint, FxPaint::Color(photocraft_color::Color::WHITE)); - } - - #[test] - fn editing_one_instance_leaves_its_sibling_alone() { - let mut s = session(); - s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000"})).unwrap(); - s.execute("layer.layerStyle.stroke", json!({"size": 7, "color": "#ffffff", "add": true})).unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); - set_param(&mut f, "fx1", "size", json!(5)); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let strokes = strokes_of(&s); - assert_eq!(strokes.len(), 2); - assert_eq!(strokes[0].size, 5.0); - assert_eq!(strokes[1].size, 7.0, "the second stroke is untouched"); - assert_eq!(strokes[1].paint, FxPaint::Color(photocraft_color::Color::WHITE)); - } - - #[test] - fn add_and_remove_instances() { - let mut s = session(); - s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000"})).unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); - add_instance(&mut f, "stroke"); - add_instance(&mut f, "stroke"); - assert_eq!(effects_of(&f).len(), 3); - assert_eq!(f["selected"], json!("fx3")); - remove_instance(&mut f, "fx2"); - assert_eq!(effects_of(&f).len(), 2); - assert_eq!(f["selected"], json!("fx3"), "selection moves to a sibling"); - remove_instance(&mut f, "fx3"); - assert_eq!(f["selected"], json!("fx1"), "the last sibling takes over"); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let strokes = strokes_of(&s); - assert_eq!(strokes.len(), 1); - assert_eq!(strokes[0].size, 3.0); - } - - #[test] - fn disabled_instances_are_kept() { - let mut s = session(); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); - if let Some(e) = entry_mut(&mut f, "fx1") { - e["on"] = json!(false); - } - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let d = s.active().unwrap(); - let items = &d.doc.layer(id).unwrap().effects.items; - assert_eq!(items.len(), 1, "configured but switched off stays"); - assert!(!items[0].enabled()); - } - - #[test] - fn baked_gradient_overlay_keeps_endpoint_colours_on_reopen() { - let mut s = session(); - s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#ff0000", "to": "#0000ff", "method": "classic"})).unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let layer = st.doc.layer(id).unwrap(); - let Effect::GradientOverlay { gradient, .. } = &layer.effects.items[0] else { panic!() }; - assert!(gradient.stops.len() > 2, "classic bakes intermediate stops"); - let f = initial_fields(layer, Some("gradientOverlay"), st.doc.global_light.angle); - let params = &effects_of(&f)[0]["params"]; - assert_eq!(params["from"], json!("#ff0000")); - assert_eq!(params["to"], json!("#0000ff")); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let Effect::GradientOverlay { gradient, .. } = &s.active().unwrap().doc.layer(id).unwrap().effects.items[0] else { panic!() }; - assert!(gradient.stops.len() > 2); - assert_eq!(gradient.stops.first().unwrap().1, photocraft_color::Color::rgb(1.0, 0.0, 0.0)); - assert_eq!(gradient.stops.last().unwrap().1, photocraft_color::Color::rgb(0.0, 0.0, 1.0)); - } - - #[test] - fn gradient_strokes_survive_the_dialog() { - let mut s = session(); - s.execute("layer.layerStyle.stroke", json!({"size": 4, "from": "#ff0000", "to": "#0000ff"})).unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); - // The dialog doesn't model the gradient, so no colour key is stored for it. - assert!(effects_of(&f)[0]["params"].get("color").is_none()); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let strokes = strokes_of(&s); - assert_eq!(strokes.len(), 1); - assert!( - matches!(&strokes[0].paint, FxPaint::Gradient(g) if g.stops.len() == 2 - && g.stops[0].1 == photocraft_color::Color::rgb(1.0, 0.0, 0.0) - && g.stops[1].1 == photocraft_color::Color::rgb(0.0, 0.0, 1.0)), - "the gradient is carried, not reset", - ); - } - - #[test] - fn bevel_gloss_anti_alias_survives_the_dialog() { - let mut s = session(); - s.execute("layer.layerStyle.bevelEmboss", json!({"glossContour": "Ring - Double", "glossAntiAlias": true})).unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); - assert_eq!(effects_of(&f)[0]["params"]["glossAntiAlias"], json!(true)); - // Editing another setting keeps the gloss contour's Anti-aliased. - set_param(&mut f, "fx1", "size", json!(12)); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let st = s.active().unwrap(); - let items = &st.doc.layer(id).unwrap().effects.items; - let Some(photocraft_doc::Effect::BevelEmboss(b)) = items.first() else { panic!("{items:?}") }; - assert_eq!(b.size, 12.0); - assert!(b.gloss_anti_alias); - } - - #[test] - fn stroke_overprint_survives_the_dialog() { - let mut s = session(); - s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000", "overprint": true})).unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); - assert_eq!(effects_of(&f)[0]["params"]["overprint"], json!(true)); - // Editing another setting keeps Overprint. - set_param(&mut f, "fx1", "size", json!(5)); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let strokes = strokes_of(&s); - assert_eq!(strokes[0].size, 5.0); - assert!(strokes[0].overprint); - } - - #[test] - fn preview_applies_the_style_without_touching_the_document() { - let s = session(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("colorOverlay"), st.doc.global_light.angle); - add_instance(&mut f, "stroke"); - let h = preview_hash(&f); - f.insert("selected".into(), json!("fx2")); - assert_eq!(preview_hash(&f), h, "switching pages doesn't re-render"); - set_param(&mut f, "fx2", "size", json!(5)); - assert_ne!(preview_hash(&f), h); - let shown = preview_document(&st.doc, &s.patterns, &f).unwrap(); - let fx = |doc: &photocraft_doc::Document| doc.layer(id).unwrap().effects.items.len(); - assert_eq!((fx(&shown), fx(&st.doc)), (2, 0)); - } - - #[test] - fn preview_rejects_non_object_effect_params() { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - let st = s.active().unwrap(); - let mut f = initial_fields(st.doc.layer(st.active_layer.unwrap()).unwrap(), Some("colorOverlay"), st.doc.global_light.angle); - let id = f["selected"].as_str().unwrap().to_string(); - entry_mut(&mut f, &id).unwrap()["params"] = json!("invalid"); - - assert!(preview_document(&st.doc, &s.patterns, &f).is_err()); - } - - #[test] - fn apply_rejects_non_object_params_before_running_commands() { - let mut f = Map::new(); - f.insert("effects".into(), json!([{"id": "fx1", "kind": "stroke", "on": true, "params": [1, 2]}])); - let mut calls = 0; - - let result = apply(&f, |_, _| { - calls += 1; - Ok(Value::Null) - }); - - assert!(result.is_err()); - assert_eq!(calls, 0, "invalid params must not partially apply the style"); - } - - #[test] - fn body_keeps_invalid_params_and_renders_without_panicking() { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - for bad in [json!(7), json!(null), json!("x")] { - let mut fields = Map::new(); - fields.insert("selected".into(), json!("fx1")); - fields.insert("effects".into(), json!([{"id": "fx1", "kind": "dropShadow", "on": true, "params": bad.clone()}])); - - let mut out = ctx.run_ui(Default::default(), |ui| body(&mut app, ui, &mut fields)); - out.textures_delta.clear(); - - assert_eq!(entry(&fields, "fx1").unwrap()["params"], bad); - } - for bad in [json!(7), json!([1])] { - let mut fields = Map::new(); - fields.insert("selected".into(), json!(BLENDING)); - fields.insert("p:blendingOptions".into(), bad.clone()); - fields.insert("effects".into(), bad.clone()); - let mut out = ctx.run_ui(Default::default(), |ui| body(&mut app, ui, &mut fields)); - out.textures_delta.clear(); - assert_eq!(fields.get("p:blendingOptions"), Some(&bad)); - } - } - - /// #2288: the selected effect row must dim again when its checkbox is cleared. - #[test] - fn disabled_effect_row_uses_muted_text_even_when_selected() { - for theme in crate::theme::ThemeKind::ALL { - let tokens = Tokens::for_kind(theme); - assert_eq!(fx_label_color(true, &tokens), tokens.text, "{theme:?}: checked"); - assert_eq!(fx_label_color(false, &tokens), tokens.text_dim, "{theme:?}: unchecked"); - } - } - - #[test] - fn blending_page_renders_for_every_mode_and_odd_fields() { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let mut layer = photocraft_doc::Layer::new("L", photocraft_doc::LayerContent::Adjustment(photocraft_doc::Adjustment::Invert)); - layer.advanced.knockout = photocraft_doc::Knockout::Deep; - for mode in - [photocraft_color::ColorMode::Rgb, photocraft_color::ColorMode::Cmyk, photocraft_color::ColorMode::Lab, photocraft_color::ColorMode::Grayscale] - { - let mut f = initial_fields(&layer, Some(BLENDING), 120.0); - set_blending_fields(&mut f, &layer, mode); - let mut out = ctx.run_ui(Default::default(), |ui| body(&mut app, ui, &mut f)); - out.textures_delta.clear(); - assert_eq!(f["p:blendingOptions"]["knockout"], "deep", "{mode:?}"); - // Hostile dialog state (only reachable through `ui.dialog.set`) still renders. - let bo = f.get_mut("p:blendingOptions").unwrap(); - bo["blendIfChannel"] = json!(99); - bo["channels"] = json!("x"); - bo["blendIf"] = json!([{"thisLayer": [300, -5, "a"]}]); - f.insert("channelNames".into(), json!([])); - let mut out = ctx.run_ui(Default::default(), |ui| body(&mut app, ui, &mut f)); - out.textures_delta.clear(); - } - } - - #[test] - fn confirm_rejects_invalid_params_and_applies_valid_effects() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - let layer = app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().clone(); - let mut invalid = initial_fields(&layer, Some("colorOverlay"), 0.0); - let id = invalid["selected"].as_str().unwrap().to_string(); - entry_mut(&mut invalid, &id).unwrap()["params"] = json!(null); - assert!(confirm(&mut app, &invalid).is_err()); - assert!(app.session.active().unwrap().doc.layer(layer.id).unwrap().effects.items.is_empty()); - - let valid = initial_fields(&layer, Some("colorOverlay"), 0.0); - confirm(&mut app, &valid).unwrap(); - assert_eq!(app.session.active().unwrap().doc.layer(layer.id).unwrap().effects.items.len(), 1); - } - - #[test] - fn blending_page_round_trips_advanced_blending_and_blend_if() { - use photocraft_doc::{BlendRange, Knockout}; - for mode in ["rgb", "cmyk", "grayscale"] { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "mode": mode})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let mut l = st.doc.layer(id).unwrap().clone(); - l.advanced.knockout = Knockout::Shallow; - l.advanced.blend_clipped = false; - l.excluded_channels = 0b1; - let gray = if st.doc.mode.color_channels() == 1 { 1 } else { 0 }; - l.blend_if.set(gray, [BlendRange { black: [10, 30], white: [255, 255] }, BlendRange::FULL]); - let mut f = initial_fields(&l, None, 120.0); - set_blending_fields(&mut f, &l, st.doc.mode); - let names = channel_names(st.doc.mode); - assert_eq!(f["channelNames"], json!(names), "{mode}"); - let p = &f[&format!("p:{BLENDING}")]; - assert_eq!(p["knockout"], "shallow"); - assert_eq!(p["blendClippedLayersAsGroup"], false); - assert_eq!(p["transparencyShapesLayer"], true); - assert_eq!(p["channels"].as_array().unwrap().len(), names.len()); - assert_eq!(p["channels"][0], false); - assert_eq!(p["blendIf"][0]["thisLayer"], json!([10, 30, 255, 255]), "{mode}"); - // Applying the page sets every switch through the engine command. - let mut f2 = f.clone(); - let bo = f2.get_mut(&format!("p:{BLENDING}")).unwrap(); - bo["knockout"] = json!("deep"); - bo["vectorMaskHidesEffects"] = json!(true); - bo["blendIfChannel"] = json!(names.len().min(1)); - let shown = preview_document(&st.doc, &s.patterns, &f2).unwrap(); - let got = shown.layer(id).unwrap(); - assert_eq!(got.advanced.knockout, Knockout::Deep, "{mode}"); - assert!(got.advanced.vector_mask_hides_effects); - assert!(!got.advanced.blend_clipped); - assert_eq!(got.excluded_channels, 0b1); - assert_eq!(got.blend_if.get(gray)[0], BlendRange { black: [10, 30], white: [255, 255] }, "{mode}"); - } - } - - #[test] - fn blend_if_values_stay_ordered() { - assert_eq!(blend_quad(Some(&json!([200, 10, 5, 300]))), [200, 200, 200, 255]); - assert_eq!(blend_quad(None), [0, 0, 255, 255]); - assert_eq!(blend_quad(Some(&json!(["x", null]))), [0, 0, 255, 255]); - } - - #[test] - fn contour_picker_and_editor_edit_the_effect_curve() { - let mut s = session(); - s.execute("layer.layerStyle.dropShadow", json!({})).unwrap(); - let shadow = |s: &photocraft_engine::Session| { - let d = s.active().unwrap(); - match &d.doc.layer(d.active_layer.unwrap()).unwrap().effects.items[0] { - Effect::DropShadow(sh) => sh.contour.clone(), - e => panic!("{e:?}"), - } - }; - let st = s.active().unwrap(); - let mut f = initial_fields(st.doc.layer(st.active_layer.unwrap()).unwrap(), None, 120.0); - // The picker: Cone. - contour::pick(&mut f, "fx1", "contour", "Cone"); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - assert_eq!(shadow(&s), photocraft_engine::layer_style::builtin_contour("Cone").unwrap()); - - // The Contour Editor: drag the second point to 10 % / 30 % (between its neighbours on - // the measured Cone), make the first point a corner. - contour::open_editor(&mut f, "fx1", "contour"); - assert!(contour::set_point(&mut f, 1, 10.0, 30.0)); - assert!(contour::set_corner(&mut f, 0, true)); - assert!(!contour::set_point(&mut f, 99, 10.0, 10.0), "no such point"); - contour::close_editor(&mut f, true); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let photocraft_doc::Contour::Custom { name, points, corners } = shadow(&s) else { panic!() }; - assert_eq!(name, "Custom", "an edited preset is no longer called Cone"); - assert!((points[1].input - 0.1).abs() < 3e-3 && (points[1].output - 0.3).abs() < 3e-3, "{points:?}"); - assert_eq!(corners.len(), points.len()); - assert!(corners[0] && corners[1] && !corners[corners.len() - 1], "{corners:?}"); - - // Cancel restores the curve the editor opened with. - let before = f.clone(); - contour::open_editor(&mut f, "fx1", "contour"); - contour::set_point(&mut f, 1, 10.0, 10.0); - contour::close_editor(&mut f, false); - assert_eq!(f, before); - } - - #[test] - fn percent_fields_round_trip_through_the_engine() { - let mut s = session(); - s.execute("layer.layerStyle.outerGlow", json!({"spread": 6, "range": 40})).unwrap(); - s.execute("layer.layerStyle.dropShadow", json!({"spread": 12, "add": true})).unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); - let fx = effects_of(&f); - assert_eq!(fx.len(), 2); - assert_eq!(fx[0]["params"]["spread"], json!(6.0)); - assert_eq!(fx[0]["params"]["range"], json!(40.0)); - assert_eq!(fx[1]["params"]["spread"], json!(12.0)); - } - - /// OK with no edits used to turn a Center-source Inner Glow into an Edge one: the dialog never - /// loaded the source, so it showed the default and applied it. - #[test] - fn inner_glow_center_source_survives_ok() { - let mut s = session(); - s.execute("layer.layerStyle.innerGlow", json!({"source": "center"})).unwrap(); - let source = |s: &photocraft_engine::Session| { - let d = s.active().unwrap(); - let id = d.active_layer.unwrap(); - d.doc.layer(id).unwrap().effects.items.iter().find_map(|e| match e { - Effect::InnerGlow(g) => Some(g.source), - _ => None, - }) - }; - assert_eq!(source(&s), Some(GlowSource::Center)); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); - let glow = effects_of(&f).iter().find(|e| e["kind"] == json!("innerGlow")).unwrap(); - assert_eq!(glow["params"]["source"], json!("center"), "the dialog shows the effect's source"); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - assert_eq!(source(&s), Some(GlowSource::Center), "OK keeps the source"); - } - - /// #6698: Inner Glow lacked Photoshop's Technique and Range, Outer Glow its Technique. They - /// show in Photoshop's order, the dialog loads them, and OK keeps them. - #[test] - fn glows_show_and_keep_technique_and_range() { - let keys = |kind: &str| spec(kind).iter().map(|(k, _, _)| *k).collect::>(); - assert_eq!(keys("innerGlow"), ["blend", "opacity", "color", "technique", "source", "choke", "size", "contour", "range", "noise"]); - assert_eq!(keys("outerGlow"), ["blend", "opacity", "color", "technique", "spread", "size", "contour", "range", "noise"]); - let mut s = session(); - s.execute("layer.layerStyle.innerGlow", json!({"technique": "precise", "range": 30})).unwrap(); - s.execute("layer.layerStyle.outerGlow", json!({"technique": "precise"})).unwrap(); - let glows = |s: &photocraft_engine::Session| { - let d = s.active().unwrap(); - let id = d.active_layer.unwrap(); - d.doc - .layer(id) - .unwrap() - .effects - .items - .iter() - .filter_map(|e| match e { - Effect::InnerGlow(g) | Effect::OuterGlow(g) => Some((kind_of(e), g.technique, (g.range * 100.0).round())), - _ => None, - }) - .collect::>() - }; - let expected = [("outerGlow", GlowTechnique::Precise, 50.0), ("innerGlow", GlowTechnique::Precise, 30.0)]; - let mut have = glows(&s); - have.sort_by_key(|g| g.0); - let mut want = expected.to_vec(); - want.sort_by_key(|g| g.0); - assert_eq!(have, want); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); - let inner = effects_of(&f).iter().find(|e| e["kind"] == json!("innerGlow")).unwrap().clone(); - assert_eq!((&inner["params"]["technique"], &inner["params"]["range"]), (&json!("precise"), &json!(30.0)), "the dialog shows them"); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let mut have = glows(&s); - have.sort_by_key(|g| g.0); - assert_eq!(have, want, "OK keeps them"); - } - - #[test] - fn drop_shadow_angle_reaches_the_effect() { - // #350: the Angle slider was dead — the dialog never sent `useGlobalLight`, so the engine - // defaulted it to true and the compositor used the fixed global light angle, ignoring the slider. - let mut s = session(); - let shadow = |s: &photocraft_engine::Session| { - let d = s.active().unwrap(); - let id = d.active_layer.unwrap(); - d.doc.layer(id).unwrap().effects.items.iter().find_map(|e| match e { - Effect::DropShadow(sh) => Some(sh.clone()), - _ => None, - }) - }; - - // Use Global Light off: the per-effect angle is stored and used. - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("dropShadow"), st.doc.global_light.angle); - set_param(&mut f, "fx1", "angle", json!(45.0)); - set_param(&mut f, "fx1", "useGlobalLight", json!(false)); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let eff = shadow(&s).unwrap(); - assert!(!eff.use_global_light, "Use Global Light off keeps the per-effect angle"); - assert_eq!(eff.angle, 45.0); - - // Use Global Light on: the Angle slider drives the document's shared light angle. - let st = s.active().unwrap(); - let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("dropShadow"), st.doc.global_light.angle); - set_param(&mut f, "fx1", "useGlobalLight", json!(true)); - set_param(&mut f, "fx1", "angle", json!(30.0)); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - assert_eq!(s.active().unwrap().doc.global_light.angle, 30.0, "the Angle slider moves the shared light"); - assert!(shadow(&s).unwrap().use_global_light); - - // Reopening the dialog shows the effective angle and the checkbox state. - let st = s.active().unwrap(); - let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); - let fx = effects_of(&f); - let shadow_entry = fx.iter().find(|e| e["kind"] == json!("dropShadow")).unwrap(); - assert_eq!(shadow_entry["params"]["useGlobalLight"], json!(true)); - assert_eq!(shadow_entry["params"]["angle"], json!(30.0)); - } - - #[test] - fn bevel_angle_change_is_not_overridden_by_unchanged_drop_shadow_angle() { - let mut s = session(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); - add_instance(&mut f, "bevelEmboss"); - set_param(&mut f, "fx1", "angle", json!(45.0)); - add_instance(&mut f, "dropShadow"); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - assert_eq!(s.active().unwrap().doc.global_light.angle, 45.0); - let d = s.active().unwrap(); - assert_eq!(d.doc.layer(id).unwrap().effects.items.len(), 2); - } - - #[test] - fn bevel_technique_is_selectable_and_round_trips() { - let Some((_, _, P::Choice(options))) = spec("bevelEmboss").iter().find(|(k, _, _)| *k == "technique") else { - panic!("Bevel & Emboss has no Technique dropdown"); - }; - let values: Vec<&str> = options.iter().map(|(v, _)| *v).collect(); - assert_eq!(values, ["smooth", "chiselHard", "chiselSoft"]); - - let mut s = session(); - s.execute("layer.layerStyle.bevelEmboss", json!({"technique": "chiselSoft"})).unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("bevelEmboss"), st.doc.global_light.angle); - assert_eq!(entry(&f, "fx1").unwrap()["params"]["technique"], json!("chiselSoft")); - set_param(&mut f, "fx1", "technique", json!("chiselHard")); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let Effect::BevelEmboss(b) = &s.active().unwrap().doc.layer(id).unwrap().effects.items[0] else { panic!("expected bevel") }; - assert_eq!(b.technique, photocraft_doc::effects::BevelTechnique::ChiselHard); - } - - #[test] - fn unchanged_global_light_angle_is_not_applied() { - let layer = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8); - let mut f = initial_fields(&layer, None, 47.5); - add_instance(&mut f, "bevelEmboss"); - assert_eq!(effects_of(&f)[0]["params"]["angle"].as_f64(), Some(47.5), "a fresh effect starts from the shared light",); - let mut commands = Vec::new(); - apply(&f, |cmd, _| { - commands.push(cmd.to_string()); - Ok(Value::Null) - }) - .unwrap(); - assert!(!commands.iter().any(|cmd| cmd == "layer.layerStyle.globalLight")); - } - - #[test] - fn last_angle_edit_wins_across_global_light_instances_and_preview() { - let mut s = session(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let original = st.doc.clone(); - let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("dropShadow"), st.doc.global_light.angle); - add_instance(&mut f, "innerShadow"); - add_instance(&mut f, "bevelEmboss"); - set_param(&mut f, "fx2", "angle", json!(30.0)); - set_param(&mut f, "fx1", "angle", json!(-90.0)); - let preview = preview_document(&original, &s.patterns, &f).unwrap(); - assert_eq!(preview.global_light.angle, -90.0, "a later instance must not override the edited shadow"); - for e in effects_of(&f) { - assert_eq!(e["params"]["angle"], json!(-90.0)); - } - assert_eq!(s.active().unwrap().doc.global_light.angle, original.global_light.angle, "preview does not mutate the document"); - // Adding an effect and disabling the edited effect must preserve the pending light. - add_instance(&mut f, "dropShadow"); - assert_eq!(effects_of(&f)[3]["params"]["angle"], json!(-90.0)); - entry_mut(&mut f, "fx1").unwrap()["on"] = json!(false); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - assert_eq!(s.active().unwrap().doc.global_light.angle, -90.0); - // Moving back to the opening angle also refreshes the preview. - let before = preview_hash(&f); - set_param(&mut f, "fx2", "angle", json!(original.global_light.angle)); - assert_ne!(preview_hash(&f), before); - assert_eq!(preview_document(&original, &s.patterns, &f).unwrap().global_light.angle, original.global_light.angle); - } - - #[test] - fn local_angles_stay_independent_and_enabling_global_light_uses_shared_angle() { - let layer = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8); - let mut f = initial_fields(&layer, Some("dropShadow"), 120.0); - add_instance(&mut f, "innerShadow"); - set_param(&mut f, "fx2", "useGlobalLight", json!(false)); - set_param(&mut f, "fx2", "angle", json!(45.0)); - set_param(&mut f, "fx1", "angle", json!(60.0)); - assert_eq!(entry(&f, "fx2").unwrap()["params"]["angle"], json!(45.0)); - set_param(&mut f, "fx2", "useGlobalLight", json!(true)); - assert_eq!(entry(&f, "fx2").unwrap()["params"]["angle"], json!(60.0)); - } - - #[test] - fn preview_moves_shadow_pixels_when_shared_angle_changes() { - let mut s = session(); - s.execute("select.rect", json!({"x": 20, "y": 20, "width": 16, "height": 16})).unwrap(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - let st = s.active().unwrap(); - let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); - let mut f = initial_fields(layer, Some("dropShadow"), st.doc.global_light.angle); - set_param(&mut f, "fx1", "distance", json!(8.0)); - set_param(&mut f, "fx1", "size", json!(0.0)); - set_param(&mut f, "fx1", "opacity", json!(100.0)); - let pixel = |f: &Map, x, y| { - let preview = preview_document(&st.doc, &s.patterns, f).unwrap(); - photocraft_compose::flatten(&preview).get(x, y) - }; - set_param(&mut f, "fx1", "angle", json!(0.0)); - assert!(pixel(&f, 14, 28)[0] < 0.01, "light from right casts shadow left"); - set_param(&mut f, "fx1", "angle", json!(90.0)); - assert!(pixel(&f, 14, 28)[0] > 0.99, "the old shadow disappears"); - assert!(pixel(&f, 28, 40)[0] < 0.01, "light from above casts shadow below"); - } - - #[test] - fn angle_dial_clicks_follow_light_direction() { - use egui_kittest::kittest::Queryable; - let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 100.0)).build_ui_state( - |ui, angle| { - widgets::angle_dial_row(ui, "Angle", angle, -180.0..=180.0); - }, - 120.0_f32, - ); - h.run(); - let dial = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Angle"); - let rect = dial.rect(); - for (delta, expected) in [(vec2(15.0, 0.0), 0.0), (vec2(0.0, -15.0), 90.0), (vec2(0.0, 15.0), -90.0)] { - let pos = rect.center() + delta; - h.event(egui::Event::PointerMoved(pos)); - h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); - h.step(); - h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); - h.run(); - assert_eq!(*h.state(), expected); - } - } - - #[test] - fn unedited_bevel_shading_keeps_imported_precision() { - for size in [None, Some(12.0)] { - let mut s = session(); - s.execute("layer.layerStyle.bevelEmboss", json!({})).unwrap(); - s.edit("imported shading", |doc, active| { - let Effect::BevelEmboss(b) = &mut doc.layer_mut(active.unwrap()).unwrap().effects.items[0] else { panic!("bevel") }; - b.highlight_color = photocraft_color::Color::rgb(0.12345, 0.45678, 0.78901); - b.shadow_color = photocraft_color::Color::rgb(0.98765, 0.54321, 0.13579); - b.highlight.opacity = 0.3525; - b.shadow.opacity = 0.6175; - Ok(()) - }) - .unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let original = st.doc.layer(id).unwrap().effects.items[0].clone(); - let mut fields = initial_fields(st.doc.layer(id).unwrap(), Some("bevelEmboss"), st.doc.global_light.angle); - if let Some(size) = size { - set_param(&mut fields, "fx1", "size", json!(size)); - } - apply(&fields, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let Effect::BevelEmboss(before) = original else { panic!("bevel") }; - let Effect::BevelEmboss(after) = &s.active().unwrap().doc.layer(id).unwrap().effects.items[0] else { panic!("bevel") }; - assert_eq!(after.highlight, before.highlight); - assert_eq!(after.shadow, before.shadow); - assert_eq!(after.highlight_color, before.highlight_color); - assert_eq!(after.shadow_color, before.shadow_color); - if let Some(size) = size { - assert_eq!(after.size, size, "the unrelated edit still applies"); - } - } - } - - #[test] - fn bevel_shading_round_trips_through_dialog_preview_and_confirm() { - let mut s = session(); - s.execute( - "layer.layerStyle.bevelEmboss", - json!({ - "highlightBlend": "Normal", "highlightColor": "#e08020", "highlightOpacity": 25, - "shadowBlend": "Multiply", "shadowColor": "#204080", "shadowOpacity": 40 - }), - ) - .unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let mut fields = initial_fields(st.doc.layer(id).unwrap(), Some("bevelEmboss"), st.doc.global_light.angle); - let values = &entry(&fields, "fx1").unwrap()["params"]; - assert_eq!(values["highlightColor"], "#e08020"); - assert_eq!(values["highlightOpacity"], 25.0); - assert_eq!(values["shadowColor"], "#204080"); - assert_eq!(values["shadowOpacity"], 40.0); - - set_param(&mut fields, "fx1", "highlightBlend", json!("Screen")); - set_param(&mut fields, "fx1", "highlightOpacity", json!(80.0)); - set_param(&mut fields, "fx1", "shadowColor", json!("#ff0000")); - assert!(preview_document(&st.doc, &s.patterns, &fields).is_ok()); - apply(&fields, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let effect = &s.active().unwrap().doc.layer(id).unwrap().effects.items[0]; - let Effect::BevelEmboss(bevel) = effect else { panic!("expected bevel") }; - assert_eq!(bevel.highlight.blend, photocraft_doc::BlendMode::Screen); - assert!((bevel.highlight.opacity - 0.8).abs() < 0.001); - assert_eq!(hex(&bevel.shadow_color), "#ff0000"); - assert_eq!(hex(&bevel.highlight_color), "#e08020"); - } - - #[test] - fn preview_off_shows_the_original_until_reenabled() { - let mut s = session(); - s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("colorOverlay"), st.doc.global_light.angle); - // Preview off is the dialog default's complement; edits still change the state. - f.insert("preview".into(), json!(false)); - let h_off = preview_hash(&f); - set_param(&mut f, "fx1", "color", json!("#00ff00")); - assert_ne!(preview_hash(&f), h_off, "editing while preview is off still updates the dialog state"); - // Re-enabling preview applies the pending state (the canvas reads `preview`; the - // scratch-session apply is the same one the checkbox-on path uses). - f.insert("preview".into(), json!(true)); - let shown = preview_document(&st.doc, &s.patterns, &f).unwrap(); - let d = s.active().unwrap(); - let color = |doc: &photocraft_doc::Document| match &doc.layer(id).unwrap().effects.items[0] { - Effect::ColorOverlay { color, .. } => *color, - other => panic!("{other:?}"), - }; - assert_eq!(color(&shown), photocraft_color::Color::rgb(0.0, 1.0, 0.0)); - assert_ne!(color(&d.doc), color(&shown), "the document itself is untouched until OK"); - // OK commits regardless of the checkbox. - f.insert("preview".into(), json!(false)); - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let d = s.active().unwrap(); - assert_eq!(color(&d.doc), photocraft_color::Color::rgb(0.0, 1.0, 0.0), "OK commits with Preview off"); - } - - /// #3648's steps in one dialog session: disable the stroke row, add a Color Overlay, - /// untick Preview. Preview off shows the document as saved — the stroke was never - /// disabled in it, so it keeps rendering until OK, exactly like Photoshop's preview - /// semantics; nothing disabled resurrects, and OK applies the dialog's state. - #[test] - fn issue_steps_disable_stroke_add_overlay_untick_preview() { - let mut s = session(); - s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); - // Steps 1-3: a stroke is enabled and OK'd; reopening the dialog loads it enabled. - s.execute("layer.layerStyle.stroke", json!({"size": 40, "position": "inside", "color": "#00ff00"})).unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); - let rows = f["effects"].as_array().unwrap(); - assert_eq!(rows.len(), 1, "the saved stroke is the only row"); - assert_eq!((rows[0]["kind"].as_str(), rows[0]["on"].as_bool()), (Some("stroke"), Some(true))); - // Step 4: disable the stroke row — a pending edit, the document is untouched. - f["effects"][0]["on"] = json!(false); - // Step 5: add a Color Overlay (a new instance: no fx snapshot, factory defaults). - f["effects"].as_array_mut().unwrap().push(json!({ - "id": "fx2", - "kind": "colorOverlay", - "on": true, - "params": {"color": "#0000ff"}, - })); - // While Preview is on, the live preview honours the in-dialog disable: the stroke - // is disabled in the scratch document, the overlay renders. - let shown = preview_document(&st.doc, &s.patterns, &f).unwrap(); - let mut shown_effects = shown.layer(id).unwrap().effects.items.iter(); - assert!(!shown_effects.find(|e| kind_of(e) == "stroke").is_none_or(|e| e.enabled()), "the preview leaves the stroke off"); - assert!(shown_effects.find(|e| kind_of(e) == "colorOverlay").is_some_and(|e| e.enabled()), "the preview shows the overlay"); - // Step 6: untick Preview — the canvas shows the real document, whose stroke is - // still enabled (the disable is an unapplied edit). This is the state the issue - // reports; it is the saved state, not a resurrected effect. - f.insert("preview".into(), json!(false)); - let green: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 32, "y": 32})).unwrap()).unwrap(); - assert!(green[1] > 0.9 && green[0] < 0.1, "preview off shows the saved stroke: {green:?}"); - // OK (with Preview off) applies the dialog state: the stroke is now disabled in the - // document too, the overlay shows, and the dialog — which never models the list's - // master switch — leaves it at its default. - apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); - let d = s.active().unwrap(); - let effects = &d.doc.layer(id).unwrap().effects; - assert!(!effects.items.iter().find(|e| kind_of(e) == "stroke").is_none_or(|e| e.enabled()), "OK disables the stroke"); - assert!(effects.items.iter().find(|e| kind_of(e) == "colorOverlay").is_some_and(|e| e.enabled()), "OK keeps the overlay on"); - assert!(effects.enabled, "the list's master switch keeps its value"); - let blue: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 32, "y": 32})).unwrap()).unwrap(); - assert!(blue[2] > 0.9 && blue[1] < 0.1, "after OK only the overlay renders: {blue:?}"); - } - - #[test] - fn new_style_saves_pending_state_and_a_swatch_apply_restores_it() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - let id = app.session.active().unwrap().active_layer.unwrap(); - let mut f = initial_fields(app.session.active().unwrap().doc.layer(id).unwrap(), Some("stroke"), 120.0); - set_param(&mut f, "fx1", "size", json!(9)); - set_param(&mut f, BLENDING, "opacity", json!(40)); - save_new_style(&mut app, &f); - let preset = app.session.presets.styles.iter().flat_map(|g| g.items.iter()).find(|st| st.name == "Style").expect("the preset is created"); - assert_eq!(preset.effects.len(), 1, "only the enabled instance is saved"); - assert_eq!(preset.opacity, Some(0.4), "the pending opacity is saved, not the layer's"); - // A second layer gets the pending style back through the swatch path. - app.run("layer.new.layer", json!({})).unwrap(); - let mut f2 = initial_fields(app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap(), None, 120.0); - f2.insert("layer".into(), json!(app.session.active().unwrap().active_layer.unwrap().0)); - apply_style_preset(&app, &mut f2, "Style"); - // Swatch clicks update the dialog fields only; document is untouched until confirm. - assert_eq!(effects_of(&f2).len(), 1); - assert_eq!(effects_of(&f2)[0]["params"]["size"], json!(9.0)); - assert_eq!(f2["p:blendingOptions"]["opacity"], json!(40.0), "the swatch brings the style's opacity"); - // Confirming applies the style to the layer. - confirm(&mut app, &f2).unwrap(); - let st = app.session.active().unwrap(); - let strokes: Vec = st - .doc - .layer(app.session.active().unwrap().active_layer.unwrap()) - .unwrap() - .effects - .items - .iter() - .filter_map(|e| match e { - Effect::Stroke(s) => Some(s.size), - _ => None, - }) - .collect(); - assert_eq!(strokes, vec![9.0], "confirming commits the style preset to the layer"); - } - - #[test] - fn style_click_does_not_mutate_document_until_confirm() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - let id = app.session.active().unwrap().active_layer.unwrap(); - let mut f = initial_fields(app.session.active().unwrap().doc.layer(id).unwrap(), Some(STYLES_PAGE), 120.0); - apply_style_preset(&app, &mut f, "Black Stroke"); - // Document itself still has 0 effects. - assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().effects.items.len(), 0); - // Dialog fields now have the preset loaded. - assert_eq!(effects_of(&f).len(), 1); - // Cancel discards dialog; document remains with 0 effects. - // Confirm commits the style. - confirm(&mut app, &f).unwrap(); - assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().effects.items.len(), 1); - } -} +mod tests; diff --git a/crates/ui-egui/src/layer_style/tests.rs b/crates/ui-egui/src/layer_style/tests.rs new file mode 100644 index 0000000000..ebfb894081 --- /dev/null +++ b/crates/ui-egui/src/layer_style/tests.rs @@ -0,0 +1,1024 @@ +use super::*; +use photocraft_doc::StrokeFx; + +/// #5701: with a shadow page selected, a drag on the image moves the shadow: its offset +/// follows the pointer, as whole degrees and pixels, the global light angle with it. +#[test] +fn dragging_on_the_image_moves_the_selected_shadow() { + let shadow = |id: &str, kind: &str, global: bool| json!({"id": id, "kind": kind, "on": true, "params": {"angle": 120.0, "distance": 10.0, "useGlobalLight": global}}); + let mut f = Map::new(); + f.insert("selected".into(), json!("fx1")); + f.insert("globalLight".into(), json!(120.0)); + f.insert("effects".into(), json!([shadow("fx1", "dropShadow", true), shadow("fx2", "innerShadow", true), shadow("fx3", "dropShadow", false)])); + assert!(drags_shadow(&f)); + let params = |f: &Map, id: &str| { + let p = &entry(f, id).unwrap()["params"]; + (p["angle"].as_f64().unwrap(), p["distance"].as_f64().unwrap()) + }; + // The press keeps the shadow where it is: (5, 8.66) px. + drag_shadow(&mut f, true, [0.0, 0.0]); + assert_eq!(params(&f, "fx1"), (120.0, 10.0)); + // Dragged to (15, 0): straight right of the layer, the light from the left (180°). + drag_shadow(&mut f, false, [10.0, -8.660_254]); + assert_eq!(params(&f, "fx1"), (180.0, 15.0)); + assert_eq!(params(&f, "fx2").0, 180.0, "the global light angle is shared"); + assert_eq!(params(&f, "fx3"), (120.0, 10.0), "an instance with its own angle is left alone"); + // Back onto the layer: no offset, and the angle the drag started with. + drag_shadow(&mut f, false, [-5.0, -8.660_254]); + assert_eq!(params(&f, "fx1"), (120.0, 0.0)); + // Not on a shadow page: nothing moves. + f.insert("selected".into(), json!(BLENDING)); + assert!(!drags_shadow(&f)); + drag_shadow(&mut f, true, [50.0, 50.0]); + assert_eq!(params(&f, "fx1"), (120.0, 0.0)); +} + +fn session() -> photocraft_engine::Session { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +fn strokes_of(s: &photocraft_engine::Session) -> Vec { + let d = s.active().unwrap(); + let id = d.active_layer.unwrap(); + d.doc + .layer(id) + .unwrap() + .effects + .items + .iter() + .filter_map(|e| match e { + Effect::Stroke(st) => Some(st.clone()), + _ => None, + }) + .collect() +} + +/// #1357: every effect row has its checkbox from the start, also for the effects not on the +/// layer yet (an empty box), not only after one was turned on and off again. +#[test] +fn every_effect_row_shows_a_checkbox() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + let l = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8); + let fields = initial_fields(&l, Some(BLENDING), 120.0); + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + let mut f = fields.clone(); + body(app, ui, &mut f); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run_steps(3); + let boxes: Vec = h + .output() + .shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Rect(r) if r.rect.size() == vec2(14.0, 14.0) && r.stroke.width > 0.0 => Some(r.rect), + _ => None, + }) + .collect(); + // The effect list is the leftmost column; the selected pane draws checkboxes of its own. + let column = boxes.iter().map(|r| r.min.x).fold(f32::INFINITY, f32::min); + let rows = boxes.iter().filter(|r| (r.min.x - column).abs() < 0.5).count(); + assert_eq!(rows, KINDS.len(), "one empty checkbox per effect row"); +} + +// Regression test for #2209: Make Default and Reset to Default sat in a non-wrapping row, so +// translated labels wider than the page column (Russian) pushed one button over the other +// and out of the column instead of wrapping to a second row. +#[test] +fn default_buttons_wrap_inside_the_page_column_with_long_labels() { + use egui_kittest::kittest::Queryable; + let ru = crate::i18n::Lang::from_code("ru").unwrap(); + crate::i18n::with_language(ru, || { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + let l = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8); + let fields = initial_fields(&l, Some("dropShadow"), 120.0); + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + let mut f = fields.clone(); + body(app, ui, &mut f); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run_steps(3); + let reset = h.get_by_role_and_label(egui::accesskit::Role::Button, crate::i18n::tr(ru, "Reset to Default")).rect(); + let make = h.get_by_role_and_label(egui::accesskit::Role::Button, crate::i18n::tr(ru, "Make Default")).rect(); + // Together they are wider than the page column: the second wraps to a row below + // instead of sharing the row and running left over the effect list. + assert!(make.top() >= reset.bottom(), "the buttons share one row: {make:?} {reset:?}"); + assert_eq!(make.right(), reset.right(), "the wrapped row stays right-aligned"); + }); +} + +/// Double-clicking an effect row of a layer that isn't active selects that layer first, so +/// the dialog holds its effects (and OK edits it), not the active layer's. +#[test] +fn effect_row_of_another_layer_opens_that_layers_style() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let with_fx = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.layerStyle.replace", json!({"layer": with_fx.0, "effects": [{"kind": "dropShadow", "params": defaults("dropShadow")}]})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let plain = app.session.active().unwrap().active_layer.unwrap(); + assert_ne!(plain, with_fx); + assert!(app.session.active().unwrap().doc.layer(plain).unwrap().effects.items.is_empty()); + + let id = open_for_layer(&mut app, with_fx, Some("dropShadow")).unwrap(); + assert_eq!(app.session.active().unwrap().active_layer, Some(with_fx), "the row's layer becomes active"); + let d = app.ui.dialogs.iter().find(|d| d.id == id).unwrap(); + assert_eq!(d.fields["layer"], json!(with_fx.0)); + let fx = effects_of(&d.fields); + assert_eq!(fx.len(), 1); + assert_eq!(fx[0]["kind"], json!("dropShadow")); + assert!(fx[0]["fx"].is_object(), "the existing drop shadow, not a new instance"); +} + +#[test] +fn every_kind_has_spec_and_defaults() { + for &(kind, _) in KINDS { + assert!(!spec(kind).is_empty(), "{kind}"); + let d = defaults(kind); + for &(key, _, _) in spec(kind) { + assert!(d.get(key).is_some(), "{kind}.{key} has no default"); + } + } +} + +#[test] +fn adding_an_effect_after_maximum_instance_id_uses_an_unused_id() { + // Imported and scripted effects can provide arbitrary instance IDs. + let layer = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8); + let mut fields = initial_fields(&layer, None, 120.0); + fields.insert( + "effects".into(), + json!([ + {"id": "fx1", "kind": "stroke", "on": true, "params": {}}, + {"id": format!("fx{}", u64::MAX), "kind": "stroke", "on": false, "params": {}} + ]), + ); + add_instance(&mut fields, "stroke"); + + let ids: Vec<&str> = effects_of(&fields).iter().filter_map(|e| e.get("id").and_then(Value::as_str)).collect(); + assert_eq!(ids, ["fx1", "fx18446744073709551615", "fx2"]); + assert_eq!(fields["selected"], json!("fx2")); +} + +#[test] +fn initial_fields_lists_every_instance_and_selects() { + let l = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8); + let f = initial_fields(&l, Some("stroke"), 120.0); + assert_eq!(f["globalLight"], json!(120.0)); + // The kind isn't on the layer yet: selecting it creates the instance. + assert_eq!(f["effects"].as_array().unwrap().len(), 1); + assert_eq!(f["effects"][0]["kind"], json!("stroke")); + assert_eq!(f["effects"][0]["on"], json!(true)); + assert_eq!(f["selected"], json!("fx1")); + // Opening the blending page selects no instance. + let f = initial_fields(&l, Some(BLENDING), 120.0); + assert_eq!(f["selected"], json!(BLENDING)); + assert!(effects_of(&f).is_empty()); +} + +#[test] +fn open_and_confirm_preserves_two_strokes() { + // The manga/typesetting case: a 3 px black stroke under a 7 px white one. + let mut s = session(); + s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000"})).unwrap(); + s.execute("layer.layerStyle.stroke", json!({"size": 7, "color": "#ffffff", "add": true})).unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); + assert_eq!(effects_of(&f).len(), 2, "both instances load"); + // Confirm without touching anything: both strokes, same order and params. + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let strokes = strokes_of(&s); + assert_eq!(strokes.len(), 2); + assert_eq!((strokes[0].size, strokes[1].size), (3.0, 7.0)); + assert_eq!(strokes[0].paint, FxPaint::Color(photocraft_color::Color::BLACK)); + assert_eq!(strokes[1].paint, FxPaint::Color(photocraft_color::Color::WHITE)); +} + +#[test] +fn editing_one_instance_leaves_its_sibling_alone() { + let mut s = session(); + s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000"})).unwrap(); + s.execute("layer.layerStyle.stroke", json!({"size": 7, "color": "#ffffff", "add": true})).unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); + set_param(&mut f, "fx1", "size", json!(5)); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let strokes = strokes_of(&s); + assert_eq!(strokes.len(), 2); + assert_eq!(strokes[0].size, 5.0); + assert_eq!(strokes[1].size, 7.0, "the second stroke is untouched"); + assert_eq!(strokes[1].paint, FxPaint::Color(photocraft_color::Color::WHITE)); +} + +#[test] +fn add_and_remove_instances() { + let mut s = session(); + s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000"})).unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); + add_instance(&mut f, "stroke"); + add_instance(&mut f, "stroke"); + assert_eq!(effects_of(&f).len(), 3); + assert_eq!(f["selected"], json!("fx3")); + remove_instance(&mut f, "fx2"); + assert_eq!(effects_of(&f).len(), 2); + assert_eq!(f["selected"], json!("fx3"), "selection moves to a sibling"); + remove_instance(&mut f, "fx3"); + assert_eq!(f["selected"], json!("fx1"), "the last sibling takes over"); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let strokes = strokes_of(&s); + assert_eq!(strokes.len(), 1); + assert_eq!(strokes[0].size, 3.0); +} + +#[test] +fn disabled_instances_are_kept() { + let mut s = session(); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); + if let Some(e) = entry_mut(&mut f, "fx1") { + e["on"] = json!(false); + } + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let d = s.active().unwrap(); + let items = &d.doc.layer(id).unwrap().effects.items; + assert_eq!(items.len(), 1, "configured but switched off stays"); + assert!(!items[0].enabled()); +} + +#[test] +fn baked_gradient_overlay_keeps_endpoint_colours_on_reopen() { + let mut s = session(); + s.execute("layer.layerStyle.gradientOverlay", json!({"from": "#ff0000", "to": "#0000ff", "method": "classic"})).unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let layer = st.doc.layer(id).unwrap(); + let Effect::GradientOverlay { gradient, .. } = &layer.effects.items[0] else { panic!() }; + assert!(gradient.stops.len() > 2, "classic bakes intermediate stops"); + let f = initial_fields(layer, Some("gradientOverlay"), st.doc.global_light.angle); + let params = &effects_of(&f)[0]["params"]; + assert_eq!(params["from"], json!("#ff0000")); + assert_eq!(params["to"], json!("#0000ff")); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let Effect::GradientOverlay { gradient, .. } = &s.active().unwrap().doc.layer(id).unwrap().effects.items[0] else { panic!() }; + assert!(gradient.stops.len() > 2); + assert_eq!(gradient.stops.first().unwrap().1, photocraft_color::Color::rgb(1.0, 0.0, 0.0)); + assert_eq!(gradient.stops.last().unwrap().1, photocraft_color::Color::rgb(0.0, 0.0, 1.0)); +} + +#[test] +fn gradient_strokes_survive_the_dialog() { + let mut s = session(); + s.execute("layer.layerStyle.stroke", json!({"size": 4, "from": "#ff0000", "to": "#0000ff"})).unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); + // The dialog doesn't model the gradient, so no colour key is stored for it. + assert!(effects_of(&f)[0]["params"].get("color").is_none()); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let strokes = strokes_of(&s); + assert_eq!(strokes.len(), 1); + assert!( + matches!(&strokes[0].paint, FxPaint::Gradient(g) if g.stops.len() == 2 + && g.stops[0].1 == photocraft_color::Color::rgb(1.0, 0.0, 0.0) + && g.stops[1].1 == photocraft_color::Color::rgb(0.0, 0.0, 1.0)), + "the gradient is carried, not reset", + ); +} + +#[test] +fn bevel_gloss_anti_alias_survives_the_dialog() { + let mut s = session(); + s.execute("layer.layerStyle.bevelEmboss", json!({"glossContour": "Ring - Double", "glossAntiAlias": true})).unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); + assert_eq!(effects_of(&f)[0]["params"]["glossAntiAlias"], json!(true)); + // Editing another setting keeps the gloss contour's Anti-aliased. + set_param(&mut f, "fx1", "size", json!(12)); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.layer(id).unwrap().effects.items; + let Some(photocraft_doc::Effect::BevelEmboss(b)) = items.first() else { panic!("{items:?}") }; + assert_eq!(b.size, 12.0); + assert!(b.gloss_anti_alias); +} + +#[test] +fn stroke_overprint_survives_the_dialog() { + let mut s = session(); + s.execute("layer.layerStyle.stroke", json!({"size": 3, "color": "#000000", "overprint": true})).unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); + assert_eq!(effects_of(&f)[0]["params"]["overprint"], json!(true)); + // Editing another setting keeps Overprint. + set_param(&mut f, "fx1", "size", json!(5)); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let strokes = strokes_of(&s); + assert_eq!(strokes[0].size, 5.0); + assert!(strokes[0].overprint); +} + +#[test] +fn preview_applies_the_style_without_touching_the_document() { + let s = session(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("colorOverlay"), st.doc.global_light.angle); + add_instance(&mut f, "stroke"); + let h = preview_hash(&f); + f.insert("selected".into(), json!("fx2")); + assert_eq!(preview_hash(&f), h, "switching pages doesn't re-render"); + set_param(&mut f, "fx2", "size", json!(5)); + assert_ne!(preview_hash(&f), h); + let shown = preview_document(&st.doc, &s.patterns, &f).unwrap(); + let fx = |doc: &photocraft_doc::Document| doc.layer(id).unwrap().effects.items.len(); + assert_eq!((fx(&shown), fx(&st.doc)), (2, 0)); +} + +#[test] +fn preview_rejects_non_object_effect_params() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let st = s.active().unwrap(); + let mut f = initial_fields(st.doc.layer(st.active_layer.unwrap()).unwrap(), Some("colorOverlay"), st.doc.global_light.angle); + let id = f["selected"].as_str().unwrap().to_string(); + entry_mut(&mut f, &id).unwrap()["params"] = json!("invalid"); + + assert!(preview_document(&st.doc, &s.patterns, &f).is_err()); +} + +#[test] +fn apply_rejects_non_object_params_before_running_commands() { + let mut f = Map::new(); + f.insert("effects".into(), json!([{"id": "fx1", "kind": "stroke", "on": true, "params": [1, 2]}])); + let mut calls = 0; + + let result = apply(&f, |_, _| { + calls += 1; + Ok(Value::Null) + }); + + assert!(result.is_err()); + assert_eq!(calls, 0, "invalid params must not partially apply the style"); +} + +#[test] +fn body_keeps_invalid_params_and_renders_without_panicking() { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + for bad in [json!(7), json!(null), json!("x")] { + let mut fields = Map::new(); + fields.insert("selected".into(), json!("fx1")); + fields.insert("effects".into(), json!([{"id": "fx1", "kind": "dropShadow", "on": true, "params": bad.clone()}])); + + let mut out = ctx.run_ui(Default::default(), |ui| body(&mut app, ui, &mut fields)); + out.textures_delta.clear(); + + assert_eq!(entry(&fields, "fx1").unwrap()["params"], bad); + } + for bad in [json!(7), json!([1])] { + let mut fields = Map::new(); + fields.insert("selected".into(), json!(BLENDING)); + fields.insert("p:blendingOptions".into(), bad.clone()); + fields.insert("effects".into(), bad.clone()); + let mut out = ctx.run_ui(Default::default(), |ui| body(&mut app, ui, &mut fields)); + out.textures_delta.clear(); + assert_eq!(fields.get("p:blendingOptions"), Some(&bad)); + } +} + +/// #2288: the selected effect row must dim again when its checkbox is cleared. +#[test] +fn disabled_effect_row_uses_muted_text_even_when_selected() { + for theme in crate::theme::ThemeKind::ALL { + let tokens = Tokens::for_kind(theme); + assert_eq!(fx_label_color(true, &tokens), tokens.text, "{theme:?}: checked"); + assert_eq!(fx_label_color(false, &tokens), tokens.text_dim, "{theme:?}: unchecked"); + } +} + +#[test] +fn blending_page_renders_for_every_mode_and_odd_fields() { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let mut layer = photocraft_doc::Layer::new("L", photocraft_doc::LayerContent::Adjustment(photocraft_doc::Adjustment::Invert)); + layer.advanced.knockout = photocraft_doc::Knockout::Deep; + for mode in + [photocraft_color::ColorMode::Rgb, photocraft_color::ColorMode::Cmyk, photocraft_color::ColorMode::Lab, photocraft_color::ColorMode::Grayscale] + { + let mut f = initial_fields(&layer, Some(BLENDING), 120.0); + set_blending_fields(&mut f, &layer, mode); + let mut out = ctx.run_ui(Default::default(), |ui| body(&mut app, ui, &mut f)); + out.textures_delta.clear(); + assert_eq!(f["p:blendingOptions"]["knockout"], "deep", "{mode:?}"); + // Hostile dialog state (only reachable through `ui.dialog.set`) still renders. + let bo = f.get_mut("p:blendingOptions").unwrap(); + bo["blendIfChannel"] = json!(99); + bo["channels"] = json!("x"); + bo["blendIf"] = json!([{"thisLayer": [300, -5, "a"]}]); + f.insert("channelNames".into(), json!([])); + let mut out = ctx.run_ui(Default::default(), |ui| body(&mut app, ui, &mut f)); + out.textures_delta.clear(); + } +} + +#[test] +fn confirm_rejects_invalid_params_and_applies_valid_effects() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let layer = app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().clone(); + let mut invalid = initial_fields(&layer, Some("colorOverlay"), 0.0); + let id = invalid["selected"].as_str().unwrap().to_string(); + entry_mut(&mut invalid, &id).unwrap()["params"] = json!(null); + assert!(confirm(&mut app, &invalid).is_err()); + assert!(app.session.active().unwrap().doc.layer(layer.id).unwrap().effects.items.is_empty()); + + let valid = initial_fields(&layer, Some("colorOverlay"), 0.0); + confirm(&mut app, &valid).unwrap(); + assert_eq!(app.session.active().unwrap().doc.layer(layer.id).unwrap().effects.items.len(), 1); +} + +#[test] +fn blending_page_round_trips_advanced_blending_and_blend_if() { + use photocraft_doc::{BlendRange, Knockout}; + for mode in ["rgb", "cmyk", "grayscale"] { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "mode": mode})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let mut l = st.doc.layer(id).unwrap().clone(); + l.advanced.knockout = Knockout::Shallow; + l.advanced.blend_clipped = false; + l.excluded_channels = 0b1; + let gray = if st.doc.mode.color_channels() == 1 { 1 } else { 0 }; + l.blend_if.set(gray, [BlendRange { black: [10, 30], white: [255, 255] }, BlendRange::FULL]); + let mut f = initial_fields(&l, None, 120.0); + set_blending_fields(&mut f, &l, st.doc.mode); + let names = channel_names(st.doc.mode); + assert_eq!(f["channelNames"], json!(names), "{mode}"); + let p = &f[&format!("p:{BLENDING}")]; + assert_eq!(p["knockout"], "shallow"); + assert_eq!(p["blendClippedLayersAsGroup"], false); + assert_eq!(p["transparencyShapesLayer"], true); + assert_eq!(p["channels"].as_array().unwrap().len(), names.len()); + assert_eq!(p["channels"][0], false); + assert_eq!(p["blendIf"][0]["thisLayer"], json!([10, 30, 255, 255]), "{mode}"); + // Applying the page sets every switch through the engine command. + let mut f2 = f.clone(); + let bo = f2.get_mut(&format!("p:{BLENDING}")).unwrap(); + bo["knockout"] = json!("deep"); + bo["vectorMaskHidesEffects"] = json!(true); + bo["blendIfChannel"] = json!(names.len().min(1)); + let shown = preview_document(&st.doc, &s.patterns, &f2).unwrap(); + let got = shown.layer(id).unwrap(); + assert_eq!(got.advanced.knockout, Knockout::Deep, "{mode}"); + assert!(got.advanced.vector_mask_hides_effects); + assert!(!got.advanced.blend_clipped); + assert_eq!(got.excluded_channels, 0b1); + assert_eq!(got.blend_if.get(gray)[0], BlendRange { black: [10, 30], white: [255, 255] }, "{mode}"); + } +} + +#[test] +fn blend_if_values_stay_ordered() { + assert_eq!(blend_quad(Some(&json!([200, 10, 5, 300]))), [200, 200, 200, 255]); + assert_eq!(blend_quad(None), [0, 0, 255, 255]); + assert_eq!(blend_quad(Some(&json!(["x", null]))), [0, 0, 255, 255]); +} + +#[test] +fn contour_picker_and_editor_edit_the_effect_curve() { + let mut s = session(); + s.execute("layer.layerStyle.dropShadow", json!({})).unwrap(); + let shadow = |s: &photocraft_engine::Session| { + let d = s.active().unwrap(); + match &d.doc.layer(d.active_layer.unwrap()).unwrap().effects.items[0] { + Effect::DropShadow(sh) => sh.contour.clone(), + e => panic!("{e:?}"), + } + }; + let st = s.active().unwrap(); + let mut f = initial_fields(st.doc.layer(st.active_layer.unwrap()).unwrap(), None, 120.0); + // The picker: Cone. + contour::pick(&mut f, "fx1", "contour", "Cone"); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + assert_eq!(shadow(&s), photocraft_engine::layer_style::builtin_contour("Cone").unwrap()); + + // The Contour Editor: drag the second point to 10 % / 30 % (between its neighbours on + // the measured Cone), make the first point a corner. + contour::open_editor(&mut f, "fx1", "contour"); + assert!(contour::set_point(&mut f, 1, 10.0, 30.0)); + assert!(contour::set_corner(&mut f, 0, true)); + assert!(!contour::set_point(&mut f, 99, 10.0, 10.0), "no such point"); + contour::close_editor(&mut f, true); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let photocraft_doc::Contour::Custom { name, points, corners } = shadow(&s) else { panic!() }; + assert_eq!(name, "Custom", "an edited preset is no longer called Cone"); + assert!((points[1].input - 0.1).abs() < 3e-3 && (points[1].output - 0.3).abs() < 3e-3, "{points:?}"); + assert_eq!(corners.len(), points.len()); + assert!(corners[0] && corners[1] && !corners[corners.len() - 1], "{corners:?}"); + + // Cancel restores the curve the editor opened with. + let before = f.clone(); + contour::open_editor(&mut f, "fx1", "contour"); + contour::set_point(&mut f, 1, 10.0, 10.0); + contour::close_editor(&mut f, false); + assert_eq!(f, before); +} + +#[test] +fn percent_fields_round_trip_through_the_engine() { + let mut s = session(); + s.execute("layer.layerStyle.outerGlow", json!({"spread": 6, "range": 40})).unwrap(); + s.execute("layer.layerStyle.dropShadow", json!({"spread": 12, "add": true})).unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); + let fx = effects_of(&f); + assert_eq!(fx.len(), 2); + assert_eq!(fx[0]["params"]["spread"], json!(6.0)); + assert_eq!(fx[0]["params"]["range"], json!(40.0)); + assert_eq!(fx[1]["params"]["spread"], json!(12.0)); +} + +/// OK with no edits used to turn a Center-source Inner Glow into an Edge one: the dialog never +/// loaded the source, so it showed the default and applied it. +#[test] +fn inner_glow_center_source_survives_ok() { + let mut s = session(); + s.execute("layer.layerStyle.innerGlow", json!({"source": "center"})).unwrap(); + let source = |s: &photocraft_engine::Session| { + let d = s.active().unwrap(); + let id = d.active_layer.unwrap(); + d.doc.layer(id).unwrap().effects.items.iter().find_map(|e| match e { + Effect::InnerGlow(g) => Some(g.source), + _ => None, + }) + }; + assert_eq!(source(&s), Some(GlowSource::Center)); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); + let glow = effects_of(&f).iter().find(|e| e["kind"] == json!("innerGlow")).unwrap(); + assert_eq!(glow["params"]["source"], json!("center"), "the dialog shows the effect's source"); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + assert_eq!(source(&s), Some(GlowSource::Center), "OK keeps the source"); +} + +/// #6698: Inner Glow lacked Photoshop's Technique and Range, Outer Glow its Technique. They +/// show in Photoshop's order, the dialog loads them, and OK keeps them. +#[test] +fn glows_show_and_keep_technique_and_range() { + let keys = |kind: &str| spec(kind).iter().map(|(k, _, _)| *k).collect::>(); + assert_eq!(keys("innerGlow"), ["blend", "opacity", "color", "technique", "source", "choke", "size", "contour", "range", "noise"]); + assert_eq!(keys("outerGlow"), ["blend", "opacity", "color", "technique", "spread", "size", "contour", "range", "noise"]); + let mut s = session(); + s.execute("layer.layerStyle.innerGlow", json!({"technique": "precise", "range": 30})).unwrap(); + s.execute("layer.layerStyle.outerGlow", json!({"technique": "precise"})).unwrap(); + let glows = |s: &photocraft_engine::Session| { + let d = s.active().unwrap(); + let id = d.active_layer.unwrap(); + d.doc + .layer(id) + .unwrap() + .effects + .items + .iter() + .filter_map(|e| match e { + Effect::InnerGlow(g) | Effect::OuterGlow(g) => Some((kind_of(e), g.technique, (g.range * 100.0).round())), + _ => None, + }) + .collect::>() + }; + let expected = [("outerGlow", GlowTechnique::Precise, 50.0), ("innerGlow", GlowTechnique::Precise, 30.0)]; + let mut have = glows(&s); + have.sort_by_key(|g| g.0); + let mut want = expected.to_vec(); + want.sort_by_key(|g| g.0); + assert_eq!(have, want); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); + let inner = effects_of(&f).iter().find(|e| e["kind"] == json!("innerGlow")).unwrap().clone(); + assert_eq!((&inner["params"]["technique"], &inner["params"]["range"]), (&json!("precise"), &json!(30.0)), "the dialog shows them"); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let mut have = glows(&s); + have.sort_by_key(|g| g.0); + assert_eq!(have, want, "OK keeps them"); +} + +#[test] +fn drop_shadow_angle_reaches_the_effect() { + // #350: the Angle slider was dead — the dialog never sent `useGlobalLight`, so the engine + // defaulted it to true and the compositor used the fixed global light angle, ignoring the slider. + let mut s = session(); + let shadow = |s: &photocraft_engine::Session| { + let d = s.active().unwrap(); + let id = d.active_layer.unwrap(); + d.doc.layer(id).unwrap().effects.items.iter().find_map(|e| match e { + Effect::DropShadow(sh) => Some(sh.clone()), + _ => None, + }) + }; + + // Use Global Light off: the per-effect angle is stored and used. + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("dropShadow"), st.doc.global_light.angle); + set_param(&mut f, "fx1", "angle", json!(45.0)); + set_param(&mut f, "fx1", "useGlobalLight", json!(false)); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let eff = shadow(&s).unwrap(); + assert!(!eff.use_global_light, "Use Global Light off keeps the per-effect angle"); + assert_eq!(eff.angle, 45.0); + + // Use Global Light on: the Angle slider drives the document's shared light angle. + let st = s.active().unwrap(); + let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("dropShadow"), st.doc.global_light.angle); + set_param(&mut f, "fx1", "useGlobalLight", json!(true)); + set_param(&mut f, "fx1", "angle", json!(30.0)); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + assert_eq!(s.active().unwrap().doc.global_light.angle, 30.0, "the Angle slider moves the shared light"); + assert!(shadow(&s).unwrap().use_global_light); + + // Reopening the dialog shows the effective angle and the checkbox state. + let st = s.active().unwrap(); + let f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); + let fx = effects_of(&f); + let shadow_entry = fx.iter().find(|e| e["kind"] == json!("dropShadow")).unwrap(); + assert_eq!(shadow_entry["params"]["useGlobalLight"], json!(true)); + assert_eq!(shadow_entry["params"]["angle"], json!(30.0)); +} + +#[test] +fn bevel_angle_change_is_not_overridden_by_unchanged_drop_shadow_angle() { + let mut s = session(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); + add_instance(&mut f, "bevelEmboss"); + set_param(&mut f, "fx1", "angle", json!(45.0)); + add_instance(&mut f, "dropShadow"); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + assert_eq!(s.active().unwrap().doc.global_light.angle, 45.0); + let d = s.active().unwrap(); + assert_eq!(d.doc.layer(id).unwrap().effects.items.len(), 2); +} + +#[test] +fn bevel_technique_is_selectable_and_round_trips() { + let Some((_, _, P::Choice(options))) = spec("bevelEmboss").iter().find(|(k, _, _)| *k == "technique") else { + panic!("Bevel & Emboss has no Technique dropdown"); + }; + let values: Vec<&str> = options.iter().map(|(v, _)| *v).collect(); + assert_eq!(values, ["smooth", "chiselHard", "chiselSoft"]); + + let mut s = session(); + s.execute("layer.layerStyle.bevelEmboss", json!({"technique": "chiselSoft"})).unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("bevelEmboss"), st.doc.global_light.angle); + assert_eq!(entry(&f, "fx1").unwrap()["params"]["technique"], json!("chiselSoft")); + set_param(&mut f, "fx1", "technique", json!("chiselHard")); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let Effect::BevelEmboss(b) = &s.active().unwrap().doc.layer(id).unwrap().effects.items[0] else { panic!("expected bevel") }; + assert_eq!(b.technique, photocraft_doc::effects::BevelTechnique::ChiselHard); +} + +#[test] +fn unchanged_global_light_angle_is_not_applied() { + let layer = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8); + let mut f = initial_fields(&layer, None, 47.5); + add_instance(&mut f, "bevelEmboss"); + assert_eq!(effects_of(&f)[0]["params"]["angle"].as_f64(), Some(47.5), "a fresh effect starts from the shared light",); + let mut commands = Vec::new(); + apply(&f, |cmd, _| { + commands.push(cmd.to_string()); + Ok(Value::Null) + }) + .unwrap(); + assert!(!commands.iter().any(|cmd| cmd == "layer.layerStyle.globalLight")); +} + +#[test] +fn last_angle_edit_wins_across_global_light_instances_and_preview() { + let mut s = session(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let original = st.doc.clone(); + let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("dropShadow"), st.doc.global_light.angle); + add_instance(&mut f, "innerShadow"); + add_instance(&mut f, "bevelEmboss"); + set_param(&mut f, "fx2", "angle", json!(30.0)); + set_param(&mut f, "fx1", "angle", json!(-90.0)); + let preview = preview_document(&original, &s.patterns, &f).unwrap(); + assert_eq!(preview.global_light.angle, -90.0, "a later instance must not override the edited shadow"); + for e in effects_of(&f) { + assert_eq!(e["params"]["angle"], json!(-90.0)); + } + assert_eq!(s.active().unwrap().doc.global_light.angle, original.global_light.angle, "preview does not mutate the document"); + // Adding an effect and disabling the edited effect must preserve the pending light. + add_instance(&mut f, "dropShadow"); + assert_eq!(effects_of(&f)[3]["params"]["angle"], json!(-90.0)); + entry_mut(&mut f, "fx1").unwrap()["on"] = json!(false); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + assert_eq!(s.active().unwrap().doc.global_light.angle, -90.0); + // Moving back to the opening angle also refreshes the preview. + let before = preview_hash(&f); + set_param(&mut f, "fx2", "angle", json!(original.global_light.angle)); + assert_ne!(preview_hash(&f), before); + assert_eq!(preview_document(&original, &s.patterns, &f).unwrap().global_light.angle, original.global_light.angle); +} + +#[test] +fn local_angles_stay_independent_and_enabling_global_light_uses_shared_angle() { + let layer = Layer::raster("x", photocraft_doc::PixelFormat::RGBA8); + let mut f = initial_fields(&layer, Some("dropShadow"), 120.0); + add_instance(&mut f, "innerShadow"); + set_param(&mut f, "fx2", "useGlobalLight", json!(false)); + set_param(&mut f, "fx2", "angle", json!(45.0)); + set_param(&mut f, "fx1", "angle", json!(60.0)); + assert_eq!(entry(&f, "fx2").unwrap()["params"]["angle"], json!(45.0)); + set_param(&mut f, "fx2", "useGlobalLight", json!(true)); + assert_eq!(entry(&f, "fx2").unwrap()["params"]["angle"], json!(60.0)); +} + +#[test] +fn preview_moves_shadow_pixels_when_shared_angle_changes() { + let mut s = session(); + s.execute("select.rect", json!({"x": 20, "y": 20, "width": 16, "height": 16})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let st = s.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + let mut f = initial_fields(layer, Some("dropShadow"), st.doc.global_light.angle); + set_param(&mut f, "fx1", "distance", json!(8.0)); + set_param(&mut f, "fx1", "size", json!(0.0)); + set_param(&mut f, "fx1", "opacity", json!(100.0)); + let pixel = |f: &Map, x, y| { + let preview = preview_document(&st.doc, &s.patterns, f).unwrap(); + photocraft_compose::flatten(&preview).get(x, y) + }; + set_param(&mut f, "fx1", "angle", json!(0.0)); + assert!(pixel(&f, 14, 28)[0] < 0.01, "light from right casts shadow left"); + set_param(&mut f, "fx1", "angle", json!(90.0)); + assert!(pixel(&f, 14, 28)[0] > 0.99, "the old shadow disappears"); + assert!(pixel(&f, 28, 40)[0] < 0.01, "light from above casts shadow below"); +} + +#[test] +fn angle_dial_clicks_follow_light_direction() { + use egui_kittest::kittest::Queryable; + let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 100.0)).build_ui_state( + |ui, angle| { + widgets::angle_dial_row(ui, "Angle", angle, -180.0..=180.0); + }, + 120.0_f32, + ); + h.run(); + let dial = h.get_by_role_and_label(egui::accesskit::Role::Slider, "Angle"); + let rect = dial.rect(); + for (delta, expected) in [(vec2(15.0, 0.0), 0.0), (vec2(0.0, -15.0), 90.0), (vec2(0.0, 15.0), -90.0)] { + let pos = rect.center() + delta; + h.event(egui::Event::PointerMoved(pos)); + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.step(); + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run(); + assert_eq!(*h.state(), expected); + } +} + +#[test] +fn unedited_bevel_shading_keeps_imported_precision() { + for size in [None, Some(12.0)] { + let mut s = session(); + s.execute("layer.layerStyle.bevelEmboss", json!({})).unwrap(); + s.edit("imported shading", |doc, active| { + let Effect::BevelEmboss(b) = &mut doc.layer_mut(active.unwrap()).unwrap().effects.items[0] else { panic!("bevel") }; + b.highlight_color = photocraft_color::Color::rgb(0.12345, 0.45678, 0.78901); + b.shadow_color = photocraft_color::Color::rgb(0.98765, 0.54321, 0.13579); + b.highlight.opacity = 0.3525; + b.shadow.opacity = 0.6175; + Ok(()) + }) + .unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let original = st.doc.layer(id).unwrap().effects.items[0].clone(); + let mut fields = initial_fields(st.doc.layer(id).unwrap(), Some("bevelEmboss"), st.doc.global_light.angle); + if let Some(size) = size { + set_param(&mut fields, "fx1", "size", json!(size)); + } + apply(&fields, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let Effect::BevelEmboss(before) = original else { panic!("bevel") }; + let Effect::BevelEmboss(after) = &s.active().unwrap().doc.layer(id).unwrap().effects.items[0] else { panic!("bevel") }; + assert_eq!(after.highlight, before.highlight); + assert_eq!(after.shadow, before.shadow); + assert_eq!(after.highlight_color, before.highlight_color); + assert_eq!(after.shadow_color, before.shadow_color); + if let Some(size) = size { + assert_eq!(after.size, size, "the unrelated edit still applies"); + } + } +} + +#[test] +fn bevel_shading_round_trips_through_dialog_preview_and_confirm() { + let mut s = session(); + s.execute( + "layer.layerStyle.bevelEmboss", + json!({ + "highlightBlend": "Normal", "highlightColor": "#e08020", "highlightOpacity": 25, + "shadowBlend": "Multiply", "shadowColor": "#204080", "shadowOpacity": 40 + }), + ) + .unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let mut fields = initial_fields(st.doc.layer(id).unwrap(), Some("bevelEmboss"), st.doc.global_light.angle); + let values = &entry(&fields, "fx1").unwrap()["params"]; + assert_eq!(values["highlightColor"], "#e08020"); + assert_eq!(values["highlightOpacity"], 25.0); + assert_eq!(values["shadowColor"], "#204080"); + assert_eq!(values["shadowOpacity"], 40.0); + + set_param(&mut fields, "fx1", "highlightBlend", json!("Screen")); + set_param(&mut fields, "fx1", "highlightOpacity", json!(80.0)); + set_param(&mut fields, "fx1", "shadowColor", json!("#ff0000")); + assert!(preview_document(&st.doc, &s.patterns, &fields).is_ok()); + apply(&fields, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let effect = &s.active().unwrap().doc.layer(id).unwrap().effects.items[0]; + let Effect::BevelEmboss(bevel) = effect else { panic!("expected bevel") }; + assert_eq!(bevel.highlight.blend, photocraft_doc::BlendMode::Screen); + assert!((bevel.highlight.opacity - 0.8).abs() < 0.001); + assert_eq!(hex(&bevel.shadow_color), "#ff0000"); + assert_eq!(hex(&bevel.highlight_color), "#e08020"); +} + +#[test] +fn preview_off_shows_the_original_until_reenabled() { + let mut s = session(); + s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let mut f = initial_fields(st.doc.layer(id).unwrap(), Some("colorOverlay"), st.doc.global_light.angle); + // Preview off is the dialog default's complement; edits still change the state. + f.insert("preview".into(), json!(false)); + let h_off = preview_hash(&f); + set_param(&mut f, "fx1", "color", json!("#00ff00")); + assert_ne!(preview_hash(&f), h_off, "editing while preview is off still updates the dialog state"); + // Re-enabling preview applies the pending state (the canvas reads `preview`; the + // scratch-session apply is the same one the checkbox-on path uses). + f.insert("preview".into(), json!(true)); + let shown = preview_document(&st.doc, &s.patterns, &f).unwrap(); + let d = s.active().unwrap(); + let color = |doc: &photocraft_doc::Document| match &doc.layer(id).unwrap().effects.items[0] { + Effect::ColorOverlay { color, .. } => *color, + other => panic!("{other:?}"), + }; + assert_eq!(color(&shown), photocraft_color::Color::rgb(0.0, 1.0, 0.0)); + assert_ne!(color(&d.doc), color(&shown), "the document itself is untouched until OK"); + // OK commits regardless of the checkbox. + f.insert("preview".into(), json!(false)); + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let d = s.active().unwrap(); + assert_eq!(color(&d.doc), photocraft_color::Color::rgb(0.0, 1.0, 0.0), "OK commits with Preview off"); +} + +/// #3648's steps in one dialog session: disable the stroke row, add a Color Overlay, +/// untick Preview. Preview off shows the document as saved — the stroke was never +/// disabled in it, so it keeps rendering until OK, exactly like Photoshop's preview +/// semantics; nothing disabled resurrects, and OK applies the dialog's state. +#[test] +fn issue_steps_disable_stroke_add_overlay_untick_preview() { + let mut s = session(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + // Steps 1-3: a stroke is enabled and OK'd; reopening the dialog loads it enabled. + s.execute("layer.layerStyle.stroke", json!({"size": 40, "position": "inside", "color": "#00ff00"})).unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let mut f = initial_fields(st.doc.layer(id).unwrap(), None, st.doc.global_light.angle); + let rows = f["effects"].as_array().unwrap(); + assert_eq!(rows.len(), 1, "the saved stroke is the only row"); + assert_eq!((rows[0]["kind"].as_str(), rows[0]["on"].as_bool()), (Some("stroke"), Some(true))); + // Step 4: disable the stroke row — a pending edit, the document is untouched. + f["effects"][0]["on"] = json!(false); + // Step 5: add a Color Overlay (a new instance: no fx snapshot, factory defaults). + f["effects"].as_array_mut().unwrap().push(json!({ + "id": "fx2", + "kind": "colorOverlay", + "on": true, + "params": {"color": "#0000ff"}, + })); + // While Preview is on, the live preview honours the in-dialog disable: the stroke + // is disabled in the scratch document, the overlay renders. + let shown = preview_document(&st.doc, &s.patterns, &f).unwrap(); + let mut shown_effects = shown.layer(id).unwrap().effects.items.iter(); + assert!(!shown_effects.find(|e| kind_of(e) == "stroke").is_none_or(|e| e.enabled()), "the preview leaves the stroke off"); + assert!(shown_effects.find(|e| kind_of(e) == "colorOverlay").is_some_and(|e| e.enabled()), "the preview shows the overlay"); + // Step 6: untick Preview — the canvas shows the real document, whose stroke is + // still enabled (the disable is an unapplied edit). This is the state the issue + // reports; it is the saved state, not a resurrected effect. + f.insert("preview".into(), json!(false)); + let green: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 32, "y": 32})).unwrap()).unwrap(); + assert!(green[1] > 0.9 && green[0] < 0.1, "preview off shows the saved stroke: {green:?}"); + // OK (with Preview off) applies the dialog state: the stroke is now disabled in the + // document too, the overlay shows, and the dialog — which never models the list's + // master switch — leaves it at its default. + apply(&f, |cmd, p| s.execute(cmd, p).map_err(|e| e.to_string())).unwrap(); + let d = s.active().unwrap(); + let effects = &d.doc.layer(id).unwrap().effects; + assert!(!effects.items.iter().find(|e| kind_of(e) == "stroke").is_none_or(|e| e.enabled()), "OK disables the stroke"); + assert!(effects.items.iter().find(|e| kind_of(e) == "colorOverlay").is_some_and(|e| e.enabled()), "OK keeps the overlay on"); + assert!(effects.enabled, "the list's master switch keeps its value"); + let blue: Vec = serde_json::from_value(s.execute("document.pixel", json!({"x": 32, "y": 32})).unwrap()).unwrap(); + assert!(blue[2] > 0.9 && blue[1] < 0.1, "after OK only the overlay renders: {blue:?}"); +} + +#[test] +fn new_style_saves_pending_state_and_a_swatch_apply_restores_it() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let id = app.session.active().unwrap().active_layer.unwrap(); + let mut f = initial_fields(app.session.active().unwrap().doc.layer(id).unwrap(), Some("stroke"), 120.0); + set_param(&mut f, "fx1", "size", json!(9)); + set_param(&mut f, BLENDING, "opacity", json!(40)); + save_new_style(&mut app, &f); + let preset = app.session.presets.styles.iter().flat_map(|g| g.items.iter()).find(|st| st.name == "Style").expect("the preset is created"); + assert_eq!(preset.effects.len(), 1, "only the enabled instance is saved"); + assert_eq!(preset.opacity, Some(0.4), "the pending opacity is saved, not the layer's"); + // A second layer gets the pending style back through the swatch path. + app.run("layer.new.layer", json!({})).unwrap(); + let mut f2 = initial_fields(app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap(), None, 120.0); + f2.insert("layer".into(), json!(app.session.active().unwrap().active_layer.unwrap().0)); + apply_style_preset(&app, &mut f2, "Style"); + // Swatch clicks update the dialog fields only; document is untouched until confirm. + assert_eq!(effects_of(&f2).len(), 1); + assert_eq!(effects_of(&f2)[0]["params"]["size"], json!(9.0)); + assert_eq!(f2["p:blendingOptions"]["opacity"], json!(40.0), "the swatch brings the style's opacity"); + // Confirming applies the style to the layer. + confirm(&mut app, &f2).unwrap(); + let st = app.session.active().unwrap(); + let strokes: Vec = st + .doc + .layer(app.session.active().unwrap().active_layer.unwrap()) + .unwrap() + .effects + .items + .iter() + .filter_map(|e| match e { + Effect::Stroke(s) => Some(s.size), + _ => None, + }) + .collect(); + assert_eq!(strokes, vec![9.0], "confirming commits the style preset to the layer"); +} + +#[test] +fn style_click_does_not_mutate_document_until_confirm() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let id = app.session.active().unwrap().active_layer.unwrap(); + let mut f = initial_fields(app.session.active().unwrap().doc.layer(id).unwrap(), Some(STYLES_PAGE), 120.0); + apply_style_preset(&app, &mut f, "Black Stroke"); + // Document itself still has 0 effects. + assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().effects.items.len(), 0); + // Dialog fields now have the preset loaded. + assert_eq!(effects_of(&f).len(), 1); + // Cancel discards dialog; document remains with 0 effects. + // Confirm commits the style. + confirm(&mut app, &f).unwrap(); + assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().effects.items.len(), 1); +} From 78f2f17bd0fc6891b6c1701fc28bf00bd64cae90 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:16:59 +0000 Subject: [PATCH 074/259] refactor(ui-egui): move discard_ui.rs tests to discard_ui/tests.rs --- crates/ui-egui/src/discard_ui.rs | 702 +------------------------ crates/ui-egui/src/discard_ui/tests.rs | 699 ++++++++++++++++++++++++ 2 files changed, 700 insertions(+), 701 deletions(-) create mode 100644 crates/ui-egui/src/discard_ui/tests.rs diff --git a/crates/ui-egui/src/discard_ui.rs b/crates/ui-egui/src/discard_ui.rs index 2570e9041c..41ca4e4acb 100644 --- a/crates/ui-egui/src/discard_ui.rs +++ b/crates/ui-egui/src/discard_ui.rs @@ -433,704 +433,4 @@ fn button_labels(mac: bool, buttons: &[(&str, Option)]) -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - fn app_with_docs(n: usize) -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - for _ in 0..n { - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - } - app.sync_views(); - app - } - - fn make_dirty(app: &mut PhotocraftApp, doc: usize) { - app.session.set_active(doc); - app.run("layer.new.layer", json!({})).unwrap(); - } - - fn doc_id(app: &PhotocraftApp, i: usize) -> DocId { - app.session.documents()[i].doc.id - } - - #[test] - fn a_save_document_script_that_edits_the_document_keeps_the_prompt_up() { - use photocraft_engine::automate_cmds::ScriptBinding; - let mut app = app_with_docs(1); - let ctx = egui::Context::default(); - make_dirty(&mut app, 0); - app.session.active_mut().unwrap().path = Some("/pics/kept.psd".into()); - app.services.export = Some(Box::new(|_: &photocraft_doc::Document, _: &str, _: &crate::ExportSettings| Ok((b"out".to_vec(), Vec::new())))); - app.services.write = Some(Box::new(|_: &str, _: &[u8]| Ok(()))); - app.session.edit_prefs(|prefs| { - prefs.script_events.enabled = true; - prefs.script_events.bindings = vec![ScriptBinding { - event: "saveDocument".into(), - script: None, - steps: Some(json!([["layer.new.layer", {"name": "From the script"}]])), - name: "Binding".into(), - }]; - }); - let doc = doc_id(&app, 0); - assert!(!save(&mut app, &ctx, doc), "the script's layer was never written"); - assert!(app.session.documents()[0].is_dirty()); - // Without the script the same save releases the prompt. - app.session.edit_prefs(|prefs| prefs.script_events.enabled = false); - assert!(save(&mut app, &ctx, doc)); - } - - #[test] - fn clean_documents_close_without_asking() { - let mut app = app_with_docs(2); - let ctx = egui::Context::default(); - crate::menus::invoke(&mut app, &ctx, "file.close", json!({})).unwrap(); - assert!(app.discard.is_none()); - assert_eq!(app.session.documents().len(), 1); - } - - #[test] - fn closing_a_dirty_document_waits_for_an_answer() { - let mut app = app_with_docs(2); - let ctx = egui::Context::default(); - make_dirty(&mut app, 1); - crate::menus::invoke(&mut app, &ctx, "file.close", json!({"document": 1})).unwrap(); - assert_eq!(app.session.documents().len(), 2, "nothing closes before the user answers"); - assert!(app.discard.is_some()); - advance(&mut app, &ctx); - assert!(app.discard.is_none()); - assert_eq!(app.session.documents().len(), 1); - } - - #[test] - fn only_documents_that_would_be_discarded_are_asked_about() { - let mut app = app_with_docs(3); - make_dirty(&mut app, 0); - make_dirty(&mut app, 2); - let ids = [doc_id(&app, 0), doc_id(&app, 2)]; - assert_eq!(discarded(&app, "file.closeOthers", &json!({"document": 0})), (Some(ids[0]), vec![ids[1]])); - assert_eq!(discarded(&app, "file.closeAll", &json!({})).1, ids); - assert_eq!(discarded(&app, EXIT, &json!({})).1, ids); - assert!(discarded(&app, "view.zoomIn", &json!({})).1.is_empty()); - } - - #[test] - fn close_all_asks_per_dirty_document_then_runs() { - let mut app = app_with_docs(3); - let ctx = egui::Context::default(); - make_dirty(&mut app, 0); - make_dirty(&mut app, 2); - crate::menus::invoke(&mut app, &ctx, "file.closeAll", json!({})).unwrap(); - advance(&mut app, &ctx); - assert_eq!(app.session.documents().len(), 2, "the answered document closes; still waiting on the second"); - advance(&mut app, &ctx); - assert!(app.session.documents().is_empty()); - } - - /// A document that became dirty while the prompt was up is asked about before the final close (#4954). - #[test] - fn a_document_dirtied_during_the_prompt_is_asked_about_before_the_final_close() { - for command in ["file.closeAll", EXIT] { - let mut app = app_with_docs(2); - let ctx = egui::Context::default(); - make_dirty(&mut app, 0); - let late = doc_id(&app, 1); - crate::menus::invoke(&mut app, &ctx, command, json!({})).unwrap(); - make_dirty(&mut app, 1); - advance(&mut app, &ctx); - assert_eq!(app.discard.as_ref().map(|p| p.docs.clone()), Some(vec![late]), "{command}: asks about the newly dirty document"); - assert!(!app.allow_close, "{command}"); - assert_eq!(app.session.documents().len(), 1, "{command}: it is not discarded unasked"); - advance(&mut app, &ctx); - assert!(app.discard.is_none(), "{command}"); - } - // Close Others asks about the others too, but still not about the document it keeps. - let mut app = app_with_docs(3); - let ctx = egui::Context::default(); - make_dirty(&mut app, 0); - let (late, kept) = (doc_id(&app, 1), doc_id(&app, 2)); - crate::menus::invoke(&mut app, &ctx, "file.closeOthers", json!({"document": 2})).unwrap(); - make_dirty(&mut app, 1); - make_dirty(&mut app, 2); - advance(&mut app, &ctx); - assert_eq!(app.discard.as_ref().map(|p| p.docs.clone()), Some(vec![late]), "file.closeOthers: asks about the newly dirty other document"); - advance(&mut app, &ctx); - assert!(app.discard.is_none()); - assert_eq!(app.session.documents().iter().map(|d| d.doc.id).collect::>(), [kept]); - } - - #[test] - fn close_others_closes_each_answered_document_and_keeps_its_target() { - let mut app = app_with_docs(3); - let ctx = egui::Context::default(); - (0..3).for_each(|i| make_dirty(&mut app, i)); - let kept = doc_id(&app, 1); - crate::menus::invoke(&mut app, &ctx, "file.closeOthers", json!({"document": 1})).unwrap(); - assert_eq!(app.session.active_index(), Some(0), "the first one asked about is shown"); - advance(&mut app, &ctx); - assert_eq!(app.session.documents().len(), 2); - assert_eq!(app.session.active().map(|d| d.doc.id), Some(doc_id(&app, 1)), "the next one asked about is shown"); - advance(&mut app, &ctx); - assert!(app.discard.is_none()); - assert_eq!(app.session.documents().iter().map(|d| d.doc.id).collect::>(), [kept]); - } - - #[test] - fn the_parked_close_still_hits_its_document_after_tabs_move() { - let mut app = app_with_docs(3); - let ctx = egui::Context::default(); - make_dirty(&mut app, 2); - let doomed = doc_id(&app, 2); - crate::menus::invoke(&mut app, &ctx, "file.close", json!({"document": 2})).unwrap(); - // Another document closes while the prompt is up, shifting the tab to index 1. - app.run("file.close", json!({"document": 0})).unwrap(); - advance(&mut app, &ctx); - assert_eq!(app.session.documents().len(), 1); - assert!(index_of(&app, doomed).is_none()); - } - - #[test] - fn quitting_replaces_a_pending_close_but_other_requests_are_refused() { - let mut app = app_with_docs(2); - make_dirty(&mut app, 0); - make_dirty(&mut app, 1); - assert!(intercept(&mut app, "file.close", &json!({"document": 0}))); - assert!(intercept(&mut app, "file.closeAll", &Value::Null)); - assert_eq!(app.discard.as_ref().map(|p| (p.id.as_str(), p.docs.len())), Some(("file.close", 1))); - assert!(app.ui.status_error); - assert!(intercept(&mut app, EXIT, &Value::Null)); - assert_eq!(app.discard.as_ref().map(|p| (p.id.as_str(), p.docs.len())), Some((EXIT, 2))); - // Pressing the window's X again must not restart the questions. - app.discard.as_mut().unwrap().docs.remove(0); - assert!(intercept(&mut app, EXIT, &Value::Null)); - assert_eq!(app.discard.as_ref().unwrap().docs.len(), 1); - } - - #[test] - fn exit_is_held_back_until_confirmed() { - let mut app = app_with_docs(1); - let ctx = egui::Context::default(); - make_dirty(&mut app, 0); - assert!(intercept(&mut app, EXIT, &Value::Null)); - assert!(!app.allow_close); - advance(&mut app, &ctx); - assert!(app.allow_close); - } - - #[test] - fn mnemonic_labels_bracket_the_key() { - assert_eq!(button_label(false, "Don't Save", Some(Key::D)), "(D)on't Save"); - assert_eq!(button_label(false, "Guardar", Some(Key::S)), "Guardar (S)"); - assert_eq!(button_label(false, "保存", Some(Key::S)), "保存 (S)"); - } - - type Prompted = egui_kittest::Harness<'static, PhotocraftApp>; - - /// The unsaved-changes prompt for `command` over `app`'s dirty documents, as `os` draws it (with - /// the file dialogs shown and answered at the end of each frame, as the app does). - fn prompt_for(app: PhotocraftApp, command: &str, os: egui::os::OperatingSystem) -> Prompted { - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state( - |ui, app| { - show(app, ui.ctx()); - app.poll_file_dialog(ui.ctx(), None); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.ctx.set_os(os); - assert!(intercept(h.state_mut(), command, &Value::Null)); - h.run_steps(2); - h - } - - /// The unsaved-changes prompt for Close All over two dirty documents, as `os` draws it. - fn prompt_on(os: egui::os::OperatingSystem) -> Prompted { - let mut app = app_with_docs(2); - make_dirty(&mut app, 0); - make_dirty(&mut app, 1); - prompt_for(app, "file.closeAll", os) - } - - /// The buttons named `labels`, sorted by where they are drawn, left to right. - fn drawn_order<'a>(h: &Prompted, labels: [&'a str; 3]) -> Vec<&'a str> { - use egui_kittest::kittest::Queryable; - let mut v = labels.map(|l| (h.get_by_label(l).rect().left(), l)).to_vec(); - v.sort_by(|a, b| a.0.total_cmp(&b.0)); - v.into_iter().map(|(_, l)| l).collect() - } - - /// Tab walks `labels` left to right from the focused default answer, `labels[default]`, and - /// wraps; Shift+Tab steps back. - fn tab_walks(h: &mut Prompted, labels: [&str; 3], default: usize) { - assert_eq!(focused(h, &labels), Some(labels[default])); - for step in 1..=3 { - h.key_press(Key::Tab); - h.run_steps(2); - assert_eq!(focused(h, &labels), Some(labels[(default + step) % 3])); - } - h.key_press_modifiers(egui::Modifiers::SHIFT, Key::Tab); - h.run_steps(2); - assert_eq!(focused(h, &labels), Some(labels[(default + 2) % 3])); - } - - fn docs_left(h: &Prompted) -> Option { - h.state().discard.as_ref().map(|p| p.docs.len()) - } - - /// Which of `labels` has keyboard focus. - fn focused<'a>(h: &Prompted, labels: &[&'a str]) -> Option<&'a str> { - use egui_kittest::kittest::Queryable; - labels.iter().copied().find(|l| h.get_by_label(l).is_focused()) - } - - /// The default answer has keyboard focus as each question comes up, so the arrow keys move - /// between the answers and Enter presses the one they reached, as in Photoshop (#6441). - #[test] - fn each_question_comes_up_with_the_default_answer_focused() { - let mut h = prompt_on(egui::os::OperatingSystem::Windows); - let labels = ["(Y)es", "(N)o", "(C)ancel"]; - assert_eq!(focused(&h, &labels), Some("(Y)es")); - h.key_press(Key::ArrowRight); - h.run_steps(2); - assert_eq!(focused(&h, &labels), Some("(N)o")); - h.key_press(Key::Enter); - h.run_steps(2); - assert_eq!(docs_left(&h), Some(1), "Enter pressed No"); - assert_eq!(focused(&h, &labels), Some("(Y)es"), "the next question starts on the default again"); - - let mut h = prompt_on(egui::os::OperatingSystem::Mac); - let labels = ["Don't Save", "Cancel", "Save"]; - assert_eq!(focused(&h, &labels), Some("Save")); - h.key_press(Key::ArrowLeft); - h.run_steps(2); - assert_eq!(focused(&h, &labels), Some("Cancel")); - } - - #[test] - fn windows_and_linux_ask_yes_no_cancel_with_the_default_first() { - for os in [egui::os::OperatingSystem::Windows, egui::os::OperatingSystem::Nix] { - let mut h = prompt_on(os); - let labels = ["(Y)es", "(N)o", "(C)ancel"]; - assert_eq!(drawn_order(&h, labels), labels, "{os:?}"); - tab_walks(&mut h, labels, 0); - h.key_press(Key::N); - h.run_steps(2); - assert_eq!(docs_left(&h), Some(1), "N answered the first document"); - h.key_press(Key::C); - h.run_steps(2); - assert!(h.state().discard.is_none()); - assert_eq!(h.state().session.documents().len(), 1, "Cancel keeps the unanswered document"); - } - } - - /// Whether the prompt is asking about the document called `name`. - fn asks_about(h: &Prompted, name: &str) -> bool { - use egui_kittest::kittest::Queryable; - h.query_by_label_contains(&format!("“{name}”")).is_some() - } - - /// No on one of several documents closes it and asks about the next one (#2547). - #[test] - fn answering_no_closes_that_document_and_asks_about_the_next() { - for command in [EXIT, "file.closeAll"] { - let mut app = app_with_docs(2); - make_dirty(&mut app, 0); - make_dirty(&mut app, 1); - let names: Vec = app.session.documents().iter().map(|d| d.doc.name.clone()).collect(); - let second = doc_id(&app, 1); - let first = doc_id(&app, 0); - assert_eq!(app.session.active_index(), Some(1), "the last new document is active"); - let mut h = prompt_for(app, command, egui::os::OperatingSystem::Windows); - assert!(asks_about(&h, &names[0]), "{command}"); - assert_eq!(h.state().session.active().map(|d| d.doc.id), Some(first), "{command}: the first tab asked about is shown"); - h.key_press(Key::N); - h.run_steps(2); - assert_eq!(h.state().session.documents().len(), 1, "{command}: No closed the first document"); - assert_eq!(doc_id(h.state(), 0), second); - assert_eq!(h.state().session.active_index(), Some(0), "{command}: the tab asked about is shown"); - assert!(asks_about(&h, &names[1]), "{command}: then about the second"); - assert!(!h.state().allow_close); - h.key_press(Key::N); - h.run_steps(2); - assert!(h.state().discard.is_none()); - if command == EXIT { - assert!(h.state().allow_close, "answering the last document lets the app quit"); - } else { - assert!(h.state().session.documents().is_empty()); - } - } - } - - #[test] - fn cancel_after_no_keeps_the_unanswered_documents_and_the_app_open() { - let mut app = app_with_docs(2); - make_dirty(&mut app, 0); - make_dirty(&mut app, 1); - let second = doc_id(&app, 1); - let mut h = prompt_for(app, EXIT, egui::os::OperatingSystem::Windows); - h.key_press(Key::N); - h.run_steps(2); - h.key_press(Key::Escape); - h.run_steps(2); - assert!(h.state().discard.is_none()); - assert!(!h.state().allow_close, "Cancel aborts the quit"); - assert_eq!(h.state().session.documents().len(), 1); - assert_eq!(doc_id(h.state(), 0), second); - assert!(h.state().session.documents()[0].is_dirty(), "the unanswered document keeps its changes"); - } - - #[test] - fn macos_hides_mnemonics_but_other_platforms_keep_them() { - assert_eq!(button_label(true, "Don't Save", Some(Key::D)), tl!("Don't Save")); - assert_eq!(button_label(true, "Cancel", Some(Key::C)), tl!("Cancel")); - assert_eq!(button_label(false, "Don't Save", Some(Key::D)), "(D)on't Save"); - assert_eq!(button_label(false, "Cancel", Some(Key::C)), "(C)ancel"); - } - - /// German "Ja" doesn't start with Y, so every button appends its key rather than mixing - /// "Ja (Y)" with "(N)ein" (#5564). - #[test] - fn one_dialog_shows_every_key_in_the_same_style() { - let buttons = [("Yes", Some(Key::Y)), ("No", Some(Key::N)), ("Cancel", Some(Key::C))]; - assert_eq!(button_labels(false, &buttons), ["(Y)es", "(N)o", "(C)ancel"]); - let german = crate::i18n::Lang::from_code("de").unwrap(); - crate::i18n::with_language(german, || { - let shown: Vec<&str> = buttons.iter().map(|(label, _)| crate::i18n::tr(german, label)).collect(); - assert_eq!(button_labels(true, &buttons), shown); - let labels = button_labels(false, &buttons); - let appended: Vec = shown.iter().zip(&buttons).map(|(text, (_, key))| format!("{text} ({})", key.map_or("", |k| k.name()))).collect(); - assert!(labels.iter().all(|label| label.starts_with('(')) || labels == appended, "{labels:?}"); - }); - } - - #[test] - fn macos_asks_dont_save_cancel_save_with_the_default_last() { - let mut h = prompt_on(egui::os::OperatingSystem::Mac); - let labels = ["Don't Save", "Cancel", "Save"]; - assert_eq!(drawn_order(&h, labels), labels); - tab_walks(&mut h, labels, 2); - h.key_press(Key::D); - h.run_steps(2); - assert_eq!(docs_left(&h), Some(1), "D answered the first document"); - h.key_press(Key::C); - h.run_steps(2); - assert!(h.state().discard.is_none()); - assert_eq!(h.state().session.documents().len(), 1, "Cancel keeps the unanswered document"); - } - - #[test] - fn macos_plain_labels_keep_save_and_escape_shortcuts() { - for key in [Key::S, Key::Enter] { - let mut h = prompt_on(egui::os::OperatingSystem::Mac); - let (show, asked) = crate::file_dialog::fake(vec![None]); - h.state_mut().services.file_dialog = Some(show); - h.key_press(key); - h.run_steps(2); - assert_eq!(asked.borrow().len(), 1, "{key:?} opens the save dialog"); - assert_eq!(docs_left(&h), Some(2), "cancelling the save dialog keeps the prompt"); - h.key_press(Key::Escape); - h.run_steps(2); - assert!(h.state().discard.is_none()); - assert_eq!(h.state().session.documents().len(), 2, "Escape closed nothing"); - } - } - - #[test] - fn enter_takes_the_default_answer_or_the_focused_button() { - let mut h = prompt_on(egui::os::OperatingSystem::Windows); - // Backing out of the save dialog keeps the prompt. - let (show, asked) = crate::file_dialog::fake(vec![None]); - h.state_mut().services.file_dialog = Some(show); - h.key_press(Key::Enter); - h.run_steps(2); - assert_eq!(asked.borrow().len(), 1, "Enter answered Yes, which saves"); - assert_eq!(docs_left(&h), Some(2)); - // Tab from the focused Yes to No: Enter now presses it. - h.key_press(Key::Tab); - h.run_steps(2); - h.key_press(Key::Enter); - h.run_steps(2); - assert_eq!(asked.borrow().len(), 1, "no second dialog"); - assert_eq!(docs_left(&h), Some(1), "Enter pressed the focused No"); - } - - #[test] - fn saving_from_the_prompt_waits_for_the_save_dialog_then_closes() { - use crate::{FileDialogAnswer, FileDialogReply}; - use egui_kittest::kittest::Queryable; - use std::{cell::RefCell, rc::Rc}; - let written: Rc>> = Rc::default(); - let (w, waiting): (_, Rc>>) = (written.clone(), Rc::default()); - let held = waiting.clone(); - let mut app = app_with_docs(1); - make_dirty(&mut app, 0); - app.services.export = Some(Box::new(|_: &photocraft_doc::Document, _: &str, _: &crate::ExportSettings| Ok((b"out".to_vec(), Vec::new())))); - app.services.write = Some(Box::new(move |p: &str, _: &[u8]| { - w.borrow_mut().push(p.to_string()); - Ok(()) - })); - // A dialog the user takes their time with. - app.services.file_dialog = Some(Box::new(move |_, _, reply| *held.borrow_mut() = Some(reply))); - let mut h = prompt_for(app, "file.close", egui::os::OperatingSystem::Windows); - let answer = |h: &mut Prompted, a: Option| { - waiting.borrow_mut().take().expect("the save dialog is open").send(a); - h.run_steps(2); - }; - // Cancelling the save dialog brings the prompt back. - h.key_press(Key::Y); - h.run_steps(3); - assert!(h.state().file_dialog_open()); - assert!(h.query_by_label("(Y)es").is_none(), "the prompt waits behind the dialog"); - answer(&mut h, None); - assert_eq!(docs_left(&h), Some(1)); - assert_eq!(focused(&h, &["(Y)es", "(N)o", "(C)ancel"]), Some("(Y)es"), "the prompt comes back with Yes focused"); - // Saving closes the document. - h.key_press(Key::Y); - h.run_steps(3); - assert_eq!(h.state().session.documents().len(), 1, "still open while the dialog is"); - answer(&mut h, Some(FileDialogAnswer::SaveTo("/pics/kept.psd".into()))); - assert_eq!(*written.borrow(), ["/pics/kept.psd"]); - assert!(h.state().discard.is_none()); - assert!(h.state().session.documents().is_empty()); - } - - /// Save on closing an untitled document, answered with `kept` while `kept.psd` exists: the - /// prompt waits for the question whether to replace it. Cancel brings the prompt back with - /// nothing written; Replace saves and closes the document. - #[test] - fn saving_from_the_prompt_waits_for_the_question_whether_to_replace() { - use crate::{FileDialogAnswer, FileDialogReply}; - use egui_kittest::kittest::Queryable; - use std::{cell::RefCell, rc::Rc}; - let written: Rc>> = Rc::default(); - let (w, waiting): (_, Rc>>) = (written.clone(), Rc::default()); - let held = waiting.clone(); - let mut app = app_with_docs(1); - make_dirty(&mut app, 0); - app.services.export = Some(Box::new(|_: &photocraft_doc::Document, _: &str, _: &crate::ExportSettings| Ok((b"out".to_vec(), Vec::new())))); - app.services.write = Some(Box::new(move |p: &str, _: &[u8]| { - w.borrow_mut().push(p.to_string()); - Ok(()) - })); - app.services.file_stamp = Some(Box::new(|p: &str| (p == "/pics/kept.psd").then_some(crate::FileStamp { len: 1, modified: None }))); - app.services.file_dialog = Some(Box::new(move |_, _, reply| *held.borrow_mut() = Some(reply))); - let mut h = prompt_for(app, "file.close", egui::os::OperatingSystem::Windows); - let save = |h: &mut Prompted| { - h.key_press(Key::Y); - h.run_steps(3); - waiting.borrow_mut().take().expect("the save dialog is open").send(Some(FileDialogAnswer::SaveTo("/pics/kept".into()))); - h.run_steps(2); - h.state().ui.dialogs.iter().find(|d| crate::replace_prompt::owns(&d.fields)).map(|d| d.id).expect("the save asks first") - }; - let id = save(&mut h); - assert!(h.state().file_dialog_open()); - assert!(h.query_by_label("(Y)es").is_none(), "the prompt waits behind the question"); - assert!(written.borrow().is_empty()); - - crate::dialogs::cancel(h.state_mut(), id).unwrap(); - h.run_steps(2); - assert!(written.borrow().is_empty(), "Cancel writes nothing"); - assert_eq!(docs_left(&h), Some(1)); - assert_eq!(focused(&h, &["(Y)es", "(N)o", "(C)ancel"]), Some("(Y)es"), "the prompt comes back"); - - let id = save(&mut h); - crate::dialogs::confirm(h.state_mut(), id).unwrap(); - h.run_steps(2); - assert_eq!(*written.borrow(), ["/pics/kept.psd"]); - assert!(h.state().discard.is_none()); - assert!(h.state().session.documents().is_empty()); - } - - #[test] - fn saving_from_the_prompt_waits_for_a_background_save_then_closes() { - use egui_kittest::kittest::Queryable; - use std::sync::atomic::{AtomicBool, Ordering}; - use std::sync::{Arc, Mutex}; - let (gate, written) = (Arc::new(AtomicBool::new(false)), Arc::new(Mutex::new(Vec::::new()))); - let mut app = app_with_docs(1); - make_dirty(&mut app, 0); - app.session.active_mut().unwrap().path = Some("/pics/big.psd".into()); - app.background_jobs = true; - let (g, w) = (gate.clone(), written.clone()); - app.services.save_file = Some(Arc::new(move |_, path, _, ctx| { - while !g.load(Ordering::Relaxed) { - ctx.check().map_err(|e| e.to_string())?; - std::thread::sleep(std::time::Duration::from_millis(1)); - } - w.lock().unwrap().push(path.to_string()); - Ok(Vec::new()) - })); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state( - |ui, app| { - crate::jobs_ui::tick(app, ui.ctx()); - show(app, ui.ctx()); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.ctx.set_os(egui::os::OperatingSystem::Windows); - assert!(intercept(h.state_mut(), "file.close", &Value::Null)); - h.run_steps(2); - h.key_press(Key::Y); - h.run_steps(3); - assert!(h.state().saving()); - assert!(h.query_by_label("(Y)es").is_none(), "the prompt waits for the save"); - assert_eq!(h.state().session.documents().len(), 1, "still open while saving"); - gate.store(true, Ordering::Relaxed); - let t = std::time::Instant::now(); - while h.state().saving() && t.elapsed() < std::time::Duration::from_secs(30) { - h.step(); - } - h.run_steps(2); - assert_eq!(*written.lock().unwrap(), ["/pics/big.psd"]); - assert!(h.state().discard.is_none()); - assert!(h.state().session.documents().is_empty(), "closed once saved"); - } - - /// #6414: on the web a save stays dirty (the download isn't confirmed), and answering Save - /// still closes the tab after one write. - #[test] - fn saving_from_the_prompt_closes_after_an_unconfirmed_write() { - use std::{cell::RefCell, rc::Rc}; - let written: Rc>> = Rc::default(); - let w = written.clone(); - let mut app = app_with_docs(1); - make_dirty(&mut app, 0); - app.session.active_mut().unwrap().path = Some("/pics/kept.psd".into()); - app.services.write_unconfirmed = true; - app.services.export = Some(Box::new(|_: &photocraft_doc::Document, _: &str, _: &crate::ExportSettings| Ok((b"out".to_vec(), Vec::new())))); - app.services.write = Some(Box::new(move |p: &str, _: &[u8]| { - w.borrow_mut().push(p.to_string()); - Ok(()) - })); - let mut h = prompt_for(app, "file.close", egui::os::OperatingSystem::Windows); - h.key_press(Key::Y); - h.run_steps(3); - assert_eq!(*written.borrow(), ["/pics/kept.psd"]); - assert!(h.state().discard.is_none()); - assert!(h.state().session.documents().is_empty(), "closed after one write"); - } - - #[path = "tiff_tests.rs"] - mod tiff_tests; - - #[path = "targa_tests.rs"] - mod targa_tests; - - #[path = "dds_tests.rs"] - mod dds_tests; - - #[path = "jpeg_tests.rs"] - mod jpeg_tests; - - /// One frame with the window's close button pressed; the commands the guard sent. - fn window_close_commands(app: &mut PhotocraftApp) -> Vec { - let mut info = egui::ViewportInfo::default(); - info.events.push(egui::ViewportEvent::Close); - let mut input = egui::RawInput::default(); - input.viewports.insert(egui::ViewportId::ROOT, info); - let mut out = egui::Context::default().run_ui(input, |ui| guard_window_close(app, ui.ctx())); - out.textures_delta.clear(); - out.viewport_output.remove(&egui::ViewportId::ROOT).map(|o| o.commands).unwrap_or_default() - } - - /// One frame with the window's close button pressed; whether the guard cancelled the close. - fn press_window_close(app: &mut PhotocraftApp) -> bool { - let commands = &window_close_commands(app); - let cancelled = commands.iter().any(|c| matches!(c, egui::ViewportCommand::CancelClose)); - assert_eq!(commands.iter().any(|c| matches!(c, egui::ViewportCommand::Focus)), cancelled); - cancelled - } - - #[test] - fn window_close_is_cancelled_while_work_is_unsaved() { - let mut app = app_with_docs(1); - make_dirty(&mut app, 0); - assert!(press_window_close(&mut app)); - assert!(app.discard.is_some()); - } - - /// After the window's GPU device is lost nothing can be drawn, so a prompt could never be seen - /// or answered. While unsaved work can't be written for recovery (the save keeps retrying), the - /// close button must still quit, instead of opening a prompt that never shows. - #[test] - fn window_close_goes_through_once_the_window_device_is_lost() { - let mut app = app_with_docs(1); - make_dirty(&mut app, 0); - app.window_lost = true; - assert!(!press_window_close(&mut app), "the close isn't cancelled"); - assert!(app.discard.is_none(), "no prompt opened"); - } - - /// The title bar's close button and File › Exit run `file.exit` through `menus::invoke`, which - /// parks it behind the prompt before any close request is made: once the window's device is - /// lost they must close instead. - #[test] - fn file_exit_quits_without_a_prompt_once_the_window_device_is_lost() { - let exit = |app: &mut PhotocraftApp| { - let mut out = egui::Context::default().run_ui(egui::RawInput::default(), |ui| { - let _ = crate::menus::invoke(app, ui.ctx(), EXIT, json!({})); - }); - out.textures_delta.clear(); - let commands = out.viewport_output.remove(&egui::ViewportId::ROOT).map(|o| o.commands).unwrap_or_default(); - commands.iter().any(|c| matches!(c, egui::ViewportCommand::Close)) - }; - let mut app = app_with_docs(1); - make_dirty(&mut app, 0); - assert!(!exit(&mut app), "a window that can draw asks first"); - assert!(app.discard.is_some()); - app.discard = None; - app.window_lost = true; - assert!(exit(&mut app), "the window is asked to close"); - assert!(app.discard.is_none(), "no prompt opened"); - } - - #[test] - fn unsaved_work_is_any_dirty_document_until_closing_is_confirmed() { - let mut app = app_with_docs(2); - assert!(!app.has_unsaved_work()); - make_dirty(&mut app, 1); - assert!(app.has_unsaved_work(), "a dirty document that isn't the active one counts"); - app.allow_close = true; - assert!(!app.has_unsaved_work()); - } - - #[test] - fn window_close_goes_through_when_nothing_is_unsaved_or_it_was_confirmed() { - let mut app = app_with_docs(1); - assert!(!press_window_close(&mut app)); - make_dirty(&mut app, 0); - app.allow_close = true; - assert!(!press_window_close(&mut app)); - assert!(app.discard.is_none()); - } - - /// With a platform quit (macOS), leaving runs it and keeps the window open for it to close; - /// unsaved work still asks first. - #[test] - fn leaving_runs_the_platform_quit_instead_of_closing_the_window() { - use std::{cell::Cell, rc::Rc}; - let quits = Rc::new(Cell::new(0)); - let mut app = app_with_docs(1); - let counted = quits.clone(); - app.services.quit = Some(Box::new(move || counted.set(counted.get() + 1))); - // The close is cancelled for the quit to do it, with no prompt brought forward. - let cancels_only = |c: &[egui::ViewportCommand]| { - c.iter().any(|c| matches!(c, egui::ViewportCommand::CancelClose)) && !c.iter().any(|c| matches!(c, egui::ViewportCommand::Focus)) - }; - - assert!(cancels_only(&window_close_commands(&mut app)), "the window stays for the quit to close"); - assert_eq!(quits.get(), 1); - - make_dirty(&mut app, 0); - assert!(press_window_close(&mut app), "unsaved work asks first"); - assert_eq!(quits.get(), 1, "no quit while the prompt is up"); - assert!(app.discard.is_some()); - - // Don't Save: the prompt confirms, and the close it sends quits. - app.discard = None; - app.allow_close = true; - assert!(cancels_only(&window_close_commands(&mut app))); - assert_eq!(quits.get(), 2); - } -} +mod tests; diff --git a/crates/ui-egui/src/discard_ui/tests.rs b/crates/ui-egui/src/discard_ui/tests.rs new file mode 100644 index 0000000000..5866a5ae12 --- /dev/null +++ b/crates/ui-egui/src/discard_ui/tests.rs @@ -0,0 +1,699 @@ +use super::*; + +fn app_with_docs(n: usize) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for _ in 0..n { + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + } + app.sync_views(); + app +} + +fn make_dirty(app: &mut PhotocraftApp, doc: usize) { + app.session.set_active(doc); + app.run("layer.new.layer", json!({})).unwrap(); +} + +fn doc_id(app: &PhotocraftApp, i: usize) -> DocId { + app.session.documents()[i].doc.id +} + +#[test] +fn a_save_document_script_that_edits_the_document_keeps_the_prompt_up() { + use photocraft_engine::automate_cmds::ScriptBinding; + let mut app = app_with_docs(1); + let ctx = egui::Context::default(); + make_dirty(&mut app, 0); + app.session.active_mut().unwrap().path = Some("/pics/kept.psd".into()); + app.services.export = Some(Box::new(|_: &photocraft_doc::Document, _: &str, _: &crate::ExportSettings| Ok((b"out".to_vec(), Vec::new())))); + app.services.write = Some(Box::new(|_: &str, _: &[u8]| Ok(()))); + app.session.edit_prefs(|prefs| { + prefs.script_events.enabled = true; + prefs.script_events.bindings = vec![ScriptBinding { + event: "saveDocument".into(), + script: None, + steps: Some(json!([["layer.new.layer", {"name": "From the script"}]])), + name: "Binding".into(), + }]; + }); + let doc = doc_id(&app, 0); + assert!(!save(&mut app, &ctx, doc), "the script's layer was never written"); + assert!(app.session.documents()[0].is_dirty()); + // Without the script the same save releases the prompt. + app.session.edit_prefs(|prefs| prefs.script_events.enabled = false); + assert!(save(&mut app, &ctx, doc)); +} + +#[test] +fn clean_documents_close_without_asking() { + let mut app = app_with_docs(2); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "file.close", json!({})).unwrap(); + assert!(app.discard.is_none()); + assert_eq!(app.session.documents().len(), 1); +} + +#[test] +fn closing_a_dirty_document_waits_for_an_answer() { + let mut app = app_with_docs(2); + let ctx = egui::Context::default(); + make_dirty(&mut app, 1); + crate::menus::invoke(&mut app, &ctx, "file.close", json!({"document": 1})).unwrap(); + assert_eq!(app.session.documents().len(), 2, "nothing closes before the user answers"); + assert!(app.discard.is_some()); + advance(&mut app, &ctx); + assert!(app.discard.is_none()); + assert_eq!(app.session.documents().len(), 1); +} + +#[test] +fn only_documents_that_would_be_discarded_are_asked_about() { + let mut app = app_with_docs(3); + make_dirty(&mut app, 0); + make_dirty(&mut app, 2); + let ids = [doc_id(&app, 0), doc_id(&app, 2)]; + assert_eq!(discarded(&app, "file.closeOthers", &json!({"document": 0})), (Some(ids[0]), vec![ids[1]])); + assert_eq!(discarded(&app, "file.closeAll", &json!({})).1, ids); + assert_eq!(discarded(&app, EXIT, &json!({})).1, ids); + assert!(discarded(&app, "view.zoomIn", &json!({})).1.is_empty()); +} + +#[test] +fn close_all_asks_per_dirty_document_then_runs() { + let mut app = app_with_docs(3); + let ctx = egui::Context::default(); + make_dirty(&mut app, 0); + make_dirty(&mut app, 2); + crate::menus::invoke(&mut app, &ctx, "file.closeAll", json!({})).unwrap(); + advance(&mut app, &ctx); + assert_eq!(app.session.documents().len(), 2, "the answered document closes; still waiting on the second"); + advance(&mut app, &ctx); + assert!(app.session.documents().is_empty()); +} + +/// A document that became dirty while the prompt was up is asked about before the final close (#4954). +#[test] +fn a_document_dirtied_during_the_prompt_is_asked_about_before_the_final_close() { + for command in ["file.closeAll", EXIT] { + let mut app = app_with_docs(2); + let ctx = egui::Context::default(); + make_dirty(&mut app, 0); + let late = doc_id(&app, 1); + crate::menus::invoke(&mut app, &ctx, command, json!({})).unwrap(); + make_dirty(&mut app, 1); + advance(&mut app, &ctx); + assert_eq!(app.discard.as_ref().map(|p| p.docs.clone()), Some(vec![late]), "{command}: asks about the newly dirty document"); + assert!(!app.allow_close, "{command}"); + assert_eq!(app.session.documents().len(), 1, "{command}: it is not discarded unasked"); + advance(&mut app, &ctx); + assert!(app.discard.is_none(), "{command}"); + } + // Close Others asks about the others too, but still not about the document it keeps. + let mut app = app_with_docs(3); + let ctx = egui::Context::default(); + make_dirty(&mut app, 0); + let (late, kept) = (doc_id(&app, 1), doc_id(&app, 2)); + crate::menus::invoke(&mut app, &ctx, "file.closeOthers", json!({"document": 2})).unwrap(); + make_dirty(&mut app, 1); + make_dirty(&mut app, 2); + advance(&mut app, &ctx); + assert_eq!(app.discard.as_ref().map(|p| p.docs.clone()), Some(vec![late]), "file.closeOthers: asks about the newly dirty other document"); + advance(&mut app, &ctx); + assert!(app.discard.is_none()); + assert_eq!(app.session.documents().iter().map(|d| d.doc.id).collect::>(), [kept]); +} + +#[test] +fn close_others_closes_each_answered_document_and_keeps_its_target() { + let mut app = app_with_docs(3); + let ctx = egui::Context::default(); + (0..3).for_each(|i| make_dirty(&mut app, i)); + let kept = doc_id(&app, 1); + crate::menus::invoke(&mut app, &ctx, "file.closeOthers", json!({"document": 1})).unwrap(); + assert_eq!(app.session.active_index(), Some(0), "the first one asked about is shown"); + advance(&mut app, &ctx); + assert_eq!(app.session.documents().len(), 2); + assert_eq!(app.session.active().map(|d| d.doc.id), Some(doc_id(&app, 1)), "the next one asked about is shown"); + advance(&mut app, &ctx); + assert!(app.discard.is_none()); + assert_eq!(app.session.documents().iter().map(|d| d.doc.id).collect::>(), [kept]); +} + +#[test] +fn the_parked_close_still_hits_its_document_after_tabs_move() { + let mut app = app_with_docs(3); + let ctx = egui::Context::default(); + make_dirty(&mut app, 2); + let doomed = doc_id(&app, 2); + crate::menus::invoke(&mut app, &ctx, "file.close", json!({"document": 2})).unwrap(); + // Another document closes while the prompt is up, shifting the tab to index 1. + app.run("file.close", json!({"document": 0})).unwrap(); + advance(&mut app, &ctx); + assert_eq!(app.session.documents().len(), 1); + assert!(index_of(&app, doomed).is_none()); +} + +#[test] +fn quitting_replaces_a_pending_close_but_other_requests_are_refused() { + let mut app = app_with_docs(2); + make_dirty(&mut app, 0); + make_dirty(&mut app, 1); + assert!(intercept(&mut app, "file.close", &json!({"document": 0}))); + assert!(intercept(&mut app, "file.closeAll", &Value::Null)); + assert_eq!(app.discard.as_ref().map(|p| (p.id.as_str(), p.docs.len())), Some(("file.close", 1))); + assert!(app.ui.status_error); + assert!(intercept(&mut app, EXIT, &Value::Null)); + assert_eq!(app.discard.as_ref().map(|p| (p.id.as_str(), p.docs.len())), Some((EXIT, 2))); + // Pressing the window's X again must not restart the questions. + app.discard.as_mut().unwrap().docs.remove(0); + assert!(intercept(&mut app, EXIT, &Value::Null)); + assert_eq!(app.discard.as_ref().unwrap().docs.len(), 1); +} + +#[test] +fn exit_is_held_back_until_confirmed() { + let mut app = app_with_docs(1); + let ctx = egui::Context::default(); + make_dirty(&mut app, 0); + assert!(intercept(&mut app, EXIT, &Value::Null)); + assert!(!app.allow_close); + advance(&mut app, &ctx); + assert!(app.allow_close); +} + +#[test] +fn mnemonic_labels_bracket_the_key() { + assert_eq!(button_label(false, "Don't Save", Some(Key::D)), "(D)on't Save"); + assert_eq!(button_label(false, "Guardar", Some(Key::S)), "Guardar (S)"); + assert_eq!(button_label(false, "保存", Some(Key::S)), "保存 (S)"); +} + +type Prompted = egui_kittest::Harness<'static, PhotocraftApp>; + +/// The unsaved-changes prompt for `command` over `app`'s dirty documents, as `os` draws it (with +/// the file dialogs shown and answered at the end of each frame, as the app does). +fn prompt_for(app: PhotocraftApp, command: &str, os: egui::os::OperatingSystem) -> Prompted { + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state( + |ui, app| { + show(app, ui.ctx()); + app.poll_file_dialog(ui.ctx(), None); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.ctx.set_os(os); + assert!(intercept(h.state_mut(), command, &Value::Null)); + h.run_steps(2); + h +} + +/// The unsaved-changes prompt for Close All over two dirty documents, as `os` draws it. +fn prompt_on(os: egui::os::OperatingSystem) -> Prompted { + let mut app = app_with_docs(2); + make_dirty(&mut app, 0); + make_dirty(&mut app, 1); + prompt_for(app, "file.closeAll", os) +} + +/// The buttons named `labels`, sorted by where they are drawn, left to right. +fn drawn_order<'a>(h: &Prompted, labels: [&'a str; 3]) -> Vec<&'a str> { + use egui_kittest::kittest::Queryable; + let mut v = labels.map(|l| (h.get_by_label(l).rect().left(), l)).to_vec(); + v.sort_by(|a, b| a.0.total_cmp(&b.0)); + v.into_iter().map(|(_, l)| l).collect() +} + +/// Tab walks `labels` left to right from the focused default answer, `labels[default]`, and +/// wraps; Shift+Tab steps back. +fn tab_walks(h: &mut Prompted, labels: [&str; 3], default: usize) { + assert_eq!(focused(h, &labels), Some(labels[default])); + for step in 1..=3 { + h.key_press(Key::Tab); + h.run_steps(2); + assert_eq!(focused(h, &labels), Some(labels[(default + step) % 3])); + } + h.key_press_modifiers(egui::Modifiers::SHIFT, Key::Tab); + h.run_steps(2); + assert_eq!(focused(h, &labels), Some(labels[(default + 2) % 3])); +} + +fn docs_left(h: &Prompted) -> Option { + h.state().discard.as_ref().map(|p| p.docs.len()) +} + +/// Which of `labels` has keyboard focus. +fn focused<'a>(h: &Prompted, labels: &[&'a str]) -> Option<&'a str> { + use egui_kittest::kittest::Queryable; + labels.iter().copied().find(|l| h.get_by_label(l).is_focused()) +} + +/// The default answer has keyboard focus as each question comes up, so the arrow keys move +/// between the answers and Enter presses the one they reached, as in Photoshop (#6441). +#[test] +fn each_question_comes_up_with_the_default_answer_focused() { + let mut h = prompt_on(egui::os::OperatingSystem::Windows); + let labels = ["(Y)es", "(N)o", "(C)ancel"]; + assert_eq!(focused(&h, &labels), Some("(Y)es")); + h.key_press(Key::ArrowRight); + h.run_steps(2); + assert_eq!(focused(&h, &labels), Some("(N)o")); + h.key_press(Key::Enter); + h.run_steps(2); + assert_eq!(docs_left(&h), Some(1), "Enter pressed No"); + assert_eq!(focused(&h, &labels), Some("(Y)es"), "the next question starts on the default again"); + + let mut h = prompt_on(egui::os::OperatingSystem::Mac); + let labels = ["Don't Save", "Cancel", "Save"]; + assert_eq!(focused(&h, &labels), Some("Save")); + h.key_press(Key::ArrowLeft); + h.run_steps(2); + assert_eq!(focused(&h, &labels), Some("Cancel")); +} + +#[test] +fn windows_and_linux_ask_yes_no_cancel_with_the_default_first() { + for os in [egui::os::OperatingSystem::Windows, egui::os::OperatingSystem::Nix] { + let mut h = prompt_on(os); + let labels = ["(Y)es", "(N)o", "(C)ancel"]; + assert_eq!(drawn_order(&h, labels), labels, "{os:?}"); + tab_walks(&mut h, labels, 0); + h.key_press(Key::N); + h.run_steps(2); + assert_eq!(docs_left(&h), Some(1), "N answered the first document"); + h.key_press(Key::C); + h.run_steps(2); + assert!(h.state().discard.is_none()); + assert_eq!(h.state().session.documents().len(), 1, "Cancel keeps the unanswered document"); + } +} + +/// Whether the prompt is asking about the document called `name`. +fn asks_about(h: &Prompted, name: &str) -> bool { + use egui_kittest::kittest::Queryable; + h.query_by_label_contains(&format!("“{name}”")).is_some() +} + +/// No on one of several documents closes it and asks about the next one (#2547). +#[test] +fn answering_no_closes_that_document_and_asks_about_the_next() { + for command in [EXIT, "file.closeAll"] { + let mut app = app_with_docs(2); + make_dirty(&mut app, 0); + make_dirty(&mut app, 1); + let names: Vec = app.session.documents().iter().map(|d| d.doc.name.clone()).collect(); + let second = doc_id(&app, 1); + let first = doc_id(&app, 0); + assert_eq!(app.session.active_index(), Some(1), "the last new document is active"); + let mut h = prompt_for(app, command, egui::os::OperatingSystem::Windows); + assert!(asks_about(&h, &names[0]), "{command}"); + assert_eq!(h.state().session.active().map(|d| d.doc.id), Some(first), "{command}: the first tab asked about is shown"); + h.key_press(Key::N); + h.run_steps(2); + assert_eq!(h.state().session.documents().len(), 1, "{command}: No closed the first document"); + assert_eq!(doc_id(h.state(), 0), second); + assert_eq!(h.state().session.active_index(), Some(0), "{command}: the tab asked about is shown"); + assert!(asks_about(&h, &names[1]), "{command}: then about the second"); + assert!(!h.state().allow_close); + h.key_press(Key::N); + h.run_steps(2); + assert!(h.state().discard.is_none()); + if command == EXIT { + assert!(h.state().allow_close, "answering the last document lets the app quit"); + } else { + assert!(h.state().session.documents().is_empty()); + } + } +} + +#[test] +fn cancel_after_no_keeps_the_unanswered_documents_and_the_app_open() { + let mut app = app_with_docs(2); + make_dirty(&mut app, 0); + make_dirty(&mut app, 1); + let second = doc_id(&app, 1); + let mut h = prompt_for(app, EXIT, egui::os::OperatingSystem::Windows); + h.key_press(Key::N); + h.run_steps(2); + h.key_press(Key::Escape); + h.run_steps(2); + assert!(h.state().discard.is_none()); + assert!(!h.state().allow_close, "Cancel aborts the quit"); + assert_eq!(h.state().session.documents().len(), 1); + assert_eq!(doc_id(h.state(), 0), second); + assert!(h.state().session.documents()[0].is_dirty(), "the unanswered document keeps its changes"); +} + +#[test] +fn macos_hides_mnemonics_but_other_platforms_keep_them() { + assert_eq!(button_label(true, "Don't Save", Some(Key::D)), tl!("Don't Save")); + assert_eq!(button_label(true, "Cancel", Some(Key::C)), tl!("Cancel")); + assert_eq!(button_label(false, "Don't Save", Some(Key::D)), "(D)on't Save"); + assert_eq!(button_label(false, "Cancel", Some(Key::C)), "(C)ancel"); +} + +/// German "Ja" doesn't start with Y, so every button appends its key rather than mixing +/// "Ja (Y)" with "(N)ein" (#5564). +#[test] +fn one_dialog_shows_every_key_in_the_same_style() { + let buttons = [("Yes", Some(Key::Y)), ("No", Some(Key::N)), ("Cancel", Some(Key::C))]; + assert_eq!(button_labels(false, &buttons), ["(Y)es", "(N)o", "(C)ancel"]); + let german = crate::i18n::Lang::from_code("de").unwrap(); + crate::i18n::with_language(german, || { + let shown: Vec<&str> = buttons.iter().map(|(label, _)| crate::i18n::tr(german, label)).collect(); + assert_eq!(button_labels(true, &buttons), shown); + let labels = button_labels(false, &buttons); + let appended: Vec = shown.iter().zip(&buttons).map(|(text, (_, key))| format!("{text} ({})", key.map_or("", |k| k.name()))).collect(); + assert!(labels.iter().all(|label| label.starts_with('(')) || labels == appended, "{labels:?}"); + }); +} + +#[test] +fn macos_asks_dont_save_cancel_save_with_the_default_last() { + let mut h = prompt_on(egui::os::OperatingSystem::Mac); + let labels = ["Don't Save", "Cancel", "Save"]; + assert_eq!(drawn_order(&h, labels), labels); + tab_walks(&mut h, labels, 2); + h.key_press(Key::D); + h.run_steps(2); + assert_eq!(docs_left(&h), Some(1), "D answered the first document"); + h.key_press(Key::C); + h.run_steps(2); + assert!(h.state().discard.is_none()); + assert_eq!(h.state().session.documents().len(), 1, "Cancel keeps the unanswered document"); +} + +#[test] +fn macos_plain_labels_keep_save_and_escape_shortcuts() { + for key in [Key::S, Key::Enter] { + let mut h = prompt_on(egui::os::OperatingSystem::Mac); + let (show, asked) = crate::file_dialog::fake(vec![None]); + h.state_mut().services.file_dialog = Some(show); + h.key_press(key); + h.run_steps(2); + assert_eq!(asked.borrow().len(), 1, "{key:?} opens the save dialog"); + assert_eq!(docs_left(&h), Some(2), "cancelling the save dialog keeps the prompt"); + h.key_press(Key::Escape); + h.run_steps(2); + assert!(h.state().discard.is_none()); + assert_eq!(h.state().session.documents().len(), 2, "Escape closed nothing"); + } +} + +#[test] +fn enter_takes_the_default_answer_or_the_focused_button() { + let mut h = prompt_on(egui::os::OperatingSystem::Windows); + // Backing out of the save dialog keeps the prompt. + let (show, asked) = crate::file_dialog::fake(vec![None]); + h.state_mut().services.file_dialog = Some(show); + h.key_press(Key::Enter); + h.run_steps(2); + assert_eq!(asked.borrow().len(), 1, "Enter answered Yes, which saves"); + assert_eq!(docs_left(&h), Some(2)); + // Tab from the focused Yes to No: Enter now presses it. + h.key_press(Key::Tab); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(2); + assert_eq!(asked.borrow().len(), 1, "no second dialog"); + assert_eq!(docs_left(&h), Some(1), "Enter pressed the focused No"); +} + +#[test] +fn saving_from_the_prompt_waits_for_the_save_dialog_then_closes() { + use crate::{FileDialogAnswer, FileDialogReply}; + use egui_kittest::kittest::Queryable; + use std::{cell::RefCell, rc::Rc}; + let written: Rc>> = Rc::default(); + let (w, waiting): (_, Rc>>) = (written.clone(), Rc::default()); + let held = waiting.clone(); + let mut app = app_with_docs(1); + make_dirty(&mut app, 0); + app.services.export = Some(Box::new(|_: &photocraft_doc::Document, _: &str, _: &crate::ExportSettings| Ok((b"out".to_vec(), Vec::new())))); + app.services.write = Some(Box::new(move |p: &str, _: &[u8]| { + w.borrow_mut().push(p.to_string()); + Ok(()) + })); + // A dialog the user takes their time with. + app.services.file_dialog = Some(Box::new(move |_, _, reply| *held.borrow_mut() = Some(reply))); + let mut h = prompt_for(app, "file.close", egui::os::OperatingSystem::Windows); + let answer = |h: &mut Prompted, a: Option| { + waiting.borrow_mut().take().expect("the save dialog is open").send(a); + h.run_steps(2); + }; + // Cancelling the save dialog brings the prompt back. + h.key_press(Key::Y); + h.run_steps(3); + assert!(h.state().file_dialog_open()); + assert!(h.query_by_label("(Y)es").is_none(), "the prompt waits behind the dialog"); + answer(&mut h, None); + assert_eq!(docs_left(&h), Some(1)); + assert_eq!(focused(&h, &["(Y)es", "(N)o", "(C)ancel"]), Some("(Y)es"), "the prompt comes back with Yes focused"); + // Saving closes the document. + h.key_press(Key::Y); + h.run_steps(3); + assert_eq!(h.state().session.documents().len(), 1, "still open while the dialog is"); + answer(&mut h, Some(FileDialogAnswer::SaveTo("/pics/kept.psd".into()))); + assert_eq!(*written.borrow(), ["/pics/kept.psd"]); + assert!(h.state().discard.is_none()); + assert!(h.state().session.documents().is_empty()); +} + +/// Save on closing an untitled document, answered with `kept` while `kept.psd` exists: the +/// prompt waits for the question whether to replace it. Cancel brings the prompt back with +/// nothing written; Replace saves and closes the document. +#[test] +fn saving_from_the_prompt_waits_for_the_question_whether_to_replace() { + use crate::{FileDialogAnswer, FileDialogReply}; + use egui_kittest::kittest::Queryable; + use std::{cell::RefCell, rc::Rc}; + let written: Rc>> = Rc::default(); + let (w, waiting): (_, Rc>>) = (written.clone(), Rc::default()); + let held = waiting.clone(); + let mut app = app_with_docs(1); + make_dirty(&mut app, 0); + app.services.export = Some(Box::new(|_: &photocraft_doc::Document, _: &str, _: &crate::ExportSettings| Ok((b"out".to_vec(), Vec::new())))); + app.services.write = Some(Box::new(move |p: &str, _: &[u8]| { + w.borrow_mut().push(p.to_string()); + Ok(()) + })); + app.services.file_stamp = Some(Box::new(|p: &str| (p == "/pics/kept.psd").then_some(crate::FileStamp { len: 1, modified: None }))); + app.services.file_dialog = Some(Box::new(move |_, _, reply| *held.borrow_mut() = Some(reply))); + let mut h = prompt_for(app, "file.close", egui::os::OperatingSystem::Windows); + let save = |h: &mut Prompted| { + h.key_press(Key::Y); + h.run_steps(3); + waiting.borrow_mut().take().expect("the save dialog is open").send(Some(FileDialogAnswer::SaveTo("/pics/kept".into()))); + h.run_steps(2); + h.state().ui.dialogs.iter().find(|d| crate::replace_prompt::owns(&d.fields)).map(|d| d.id).expect("the save asks first") + }; + let id = save(&mut h); + assert!(h.state().file_dialog_open()); + assert!(h.query_by_label("(Y)es").is_none(), "the prompt waits behind the question"); + assert!(written.borrow().is_empty()); + + crate::dialogs::cancel(h.state_mut(), id).unwrap(); + h.run_steps(2); + assert!(written.borrow().is_empty(), "Cancel writes nothing"); + assert_eq!(docs_left(&h), Some(1)); + assert_eq!(focused(&h, &["(Y)es", "(N)o", "(C)ancel"]), Some("(Y)es"), "the prompt comes back"); + + let id = save(&mut h); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + h.run_steps(2); + assert_eq!(*written.borrow(), ["/pics/kept.psd"]); + assert!(h.state().discard.is_none()); + assert!(h.state().session.documents().is_empty()); +} + +#[test] +fn saving_from_the_prompt_waits_for_a_background_save_then_closes() { + use egui_kittest::kittest::Queryable; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, Mutex}; + let (gate, written) = (Arc::new(AtomicBool::new(false)), Arc::new(Mutex::new(Vec::::new()))); + let mut app = app_with_docs(1); + make_dirty(&mut app, 0); + app.session.active_mut().unwrap().path = Some("/pics/big.psd".into()); + app.background_jobs = true; + let (g, w) = (gate.clone(), written.clone()); + app.services.save_file = Some(Arc::new(move |_, path, _, ctx| { + while !g.load(Ordering::Relaxed) { + ctx.check().map_err(|e| e.to_string())?; + std::thread::sleep(std::time::Duration::from_millis(1)); + } + w.lock().unwrap().push(path.to_string()); + Ok(Vec::new()) + })); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state( + |ui, app| { + crate::jobs_ui::tick(app, ui.ctx()); + show(app, ui.ctx()); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.ctx.set_os(egui::os::OperatingSystem::Windows); + assert!(intercept(h.state_mut(), "file.close", &Value::Null)); + h.run_steps(2); + h.key_press(Key::Y); + h.run_steps(3); + assert!(h.state().saving()); + assert!(h.query_by_label("(Y)es").is_none(), "the prompt waits for the save"); + assert_eq!(h.state().session.documents().len(), 1, "still open while saving"); + gate.store(true, Ordering::Relaxed); + let t = std::time::Instant::now(); + while h.state().saving() && t.elapsed() < std::time::Duration::from_secs(30) { + h.step(); + } + h.run_steps(2); + assert_eq!(*written.lock().unwrap(), ["/pics/big.psd"]); + assert!(h.state().discard.is_none()); + assert!(h.state().session.documents().is_empty(), "closed once saved"); +} + +/// #6414: on the web a save stays dirty (the download isn't confirmed), and answering Save +/// still closes the tab after one write. +#[test] +fn saving_from_the_prompt_closes_after_an_unconfirmed_write() { + use std::{cell::RefCell, rc::Rc}; + let written: Rc>> = Rc::default(); + let w = written.clone(); + let mut app = app_with_docs(1); + make_dirty(&mut app, 0); + app.session.active_mut().unwrap().path = Some("/pics/kept.psd".into()); + app.services.write_unconfirmed = true; + app.services.export = Some(Box::new(|_: &photocraft_doc::Document, _: &str, _: &crate::ExportSettings| Ok((b"out".to_vec(), Vec::new())))); + app.services.write = Some(Box::new(move |p: &str, _: &[u8]| { + w.borrow_mut().push(p.to_string()); + Ok(()) + })); + let mut h = prompt_for(app, "file.close", egui::os::OperatingSystem::Windows); + h.key_press(Key::Y); + h.run_steps(3); + assert_eq!(*written.borrow(), ["/pics/kept.psd"]); + assert!(h.state().discard.is_none()); + assert!(h.state().session.documents().is_empty(), "closed after one write"); +} + +#[path = "tests/tiff_tests.rs"] +mod tiff_tests; + +#[path = "tests/targa_tests.rs"] +mod targa_tests; + +#[path = "tests/dds_tests.rs"] +mod dds_tests; + +#[path = "tests/jpeg_tests.rs"] +mod jpeg_tests; + +/// One frame with the window's close button pressed; the commands the guard sent. +fn window_close_commands(app: &mut PhotocraftApp) -> Vec { + let mut info = egui::ViewportInfo::default(); + info.events.push(egui::ViewportEvent::Close); + let mut input = egui::RawInput::default(); + input.viewports.insert(egui::ViewportId::ROOT, info); + let mut out = egui::Context::default().run_ui(input, |ui| guard_window_close(app, ui.ctx())); + out.textures_delta.clear(); + out.viewport_output.remove(&egui::ViewportId::ROOT).map(|o| o.commands).unwrap_or_default() +} + +/// One frame with the window's close button pressed; whether the guard cancelled the close. +fn press_window_close(app: &mut PhotocraftApp) -> bool { + let commands = &window_close_commands(app); + let cancelled = commands.iter().any(|c| matches!(c, egui::ViewportCommand::CancelClose)); + assert_eq!(commands.iter().any(|c| matches!(c, egui::ViewportCommand::Focus)), cancelled); + cancelled +} + +#[test] +fn window_close_is_cancelled_while_work_is_unsaved() { + let mut app = app_with_docs(1); + make_dirty(&mut app, 0); + assert!(press_window_close(&mut app)); + assert!(app.discard.is_some()); +} + +/// After the window's GPU device is lost nothing can be drawn, so a prompt could never be seen +/// or answered. While unsaved work can't be written for recovery (the save keeps retrying), the +/// close button must still quit, instead of opening a prompt that never shows. +#[test] +fn window_close_goes_through_once_the_window_device_is_lost() { + let mut app = app_with_docs(1); + make_dirty(&mut app, 0); + app.window_lost = true; + assert!(!press_window_close(&mut app), "the close isn't cancelled"); + assert!(app.discard.is_none(), "no prompt opened"); +} + +/// The title bar's close button and File › Exit run `file.exit` through `menus::invoke`, which +/// parks it behind the prompt before any close request is made: once the window's device is +/// lost they must close instead. +#[test] +fn file_exit_quits_without_a_prompt_once_the_window_device_is_lost() { + let exit = |app: &mut PhotocraftApp| { + let mut out = egui::Context::default().run_ui(egui::RawInput::default(), |ui| { + let _ = crate::menus::invoke(app, ui.ctx(), EXIT, json!({})); + }); + out.textures_delta.clear(); + let commands = out.viewport_output.remove(&egui::ViewportId::ROOT).map(|o| o.commands).unwrap_or_default(); + commands.iter().any(|c| matches!(c, egui::ViewportCommand::Close)) + }; + let mut app = app_with_docs(1); + make_dirty(&mut app, 0); + assert!(!exit(&mut app), "a window that can draw asks first"); + assert!(app.discard.is_some()); + app.discard = None; + app.window_lost = true; + assert!(exit(&mut app), "the window is asked to close"); + assert!(app.discard.is_none(), "no prompt opened"); +} + +#[test] +fn unsaved_work_is_any_dirty_document_until_closing_is_confirmed() { + let mut app = app_with_docs(2); + assert!(!app.has_unsaved_work()); + make_dirty(&mut app, 1); + assert!(app.has_unsaved_work(), "a dirty document that isn't the active one counts"); + app.allow_close = true; + assert!(!app.has_unsaved_work()); +} + +#[test] +fn window_close_goes_through_when_nothing_is_unsaved_or_it_was_confirmed() { + let mut app = app_with_docs(1); + assert!(!press_window_close(&mut app)); + make_dirty(&mut app, 0); + app.allow_close = true; + assert!(!press_window_close(&mut app)); + assert!(app.discard.is_none()); +} + +/// With a platform quit (macOS), leaving runs it and keeps the window open for it to close; +/// unsaved work still asks first. +#[test] +fn leaving_runs_the_platform_quit_instead_of_closing_the_window() { + use std::{cell::Cell, rc::Rc}; + let quits = Rc::new(Cell::new(0)); + let mut app = app_with_docs(1); + let counted = quits.clone(); + app.services.quit = Some(Box::new(move || counted.set(counted.get() + 1))); + // The close is cancelled for the quit to do it, with no prompt brought forward. + let cancels_only = |c: &[egui::ViewportCommand]| { + c.iter().any(|c| matches!(c, egui::ViewportCommand::CancelClose)) && !c.iter().any(|c| matches!(c, egui::ViewportCommand::Focus)) + }; + + assert!(cancels_only(&window_close_commands(&mut app)), "the window stays for the quit to close"); + assert_eq!(quits.get(), 1); + + make_dirty(&mut app, 0); + assert!(press_window_close(&mut app), "unsaved work asks first"); + assert_eq!(quits.get(), 1, "no quit while the prompt is up"); + assert!(app.discard.is_some()); + + // Don't Save: the prompt confirms, and the close it sends quits. + app.discard = None; + app.allow_close = true; + assert!(cancels_only(&window_close_commands(&mut app))); + assert_eq!(quits.get(), 2); +} From 6831de943bdb7941c267360e5e54d2da733073d4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:00 +0000 Subject: [PATCH 075/259] refactor(ui-egui): move gpu_canvas.rs tests to gpu_canvas/tests.rs --- crates/ui-egui/src/gpu_canvas.rs | 322 +------------------------ crates/ui-egui/src/gpu_canvas/tests.rs | 319 ++++++++++++++++++++++++ 2 files changed, 320 insertions(+), 321 deletions(-) create mode 100644 crates/ui-egui/src/gpu_canvas/tests.rs diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rs index 5af1f71cef..7c50c3a924 100644 --- a/crates/ui-egui/src/gpu_canvas.rs +++ b/crates/ui-egui/src/gpu_canvas.rs @@ -2669,324 +2669,4 @@ fn fs(in: V) -> @location(0) vec4 { mod mip_tests; #[cfg(test)] -mod tests { - use super::*; - - /// A GPU measurement arrives a frame or two after its refresh, so most GPU refreshes carry - /// none; the last one reported must stand until a newer one lands. A CPU refresh is - /// different: there is no GPU time at all then, and keeping the old number would show it as - /// this refresh's. Runs anywhere — the GPU timing tests need hardware and CI has none. - #[test] - fn a_gpu_measurement_stands_until_replaced_and_a_cpu_refresh_clears_it() { - let timing = |ms, px| photocraft_gpu::GpuTiming { ms, px, spans: 1 }; - let refresh = |kind, gpu| Refresh { kind, gpu, ..Default::default() }; - let mut perf = Perf::default(); - assert_eq!(perf.gpu_ms, None, "nothing is reported before a measurement"); - - perf.record_refresh(&refresh("gpu-full", Some(timing(83.9, 24_000_000)))); - assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(83.9), 24_000_000)); - - // The common case: a GPU refresh whose own measurement has not come back yet. - perf.record_refresh(&refresh("gpu-rect", None)); - assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(83.9), 24_000_000), "the last measurement stands"); - - perf.record_refresh(&refresh("gpu-rect", Some(timing(11.2, 1_098_640)))); - assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(11.2), 1_098_640), "a newer measurement replaces it"); - - // The CPU compositor did this one: the GPU number belongs to no refresh on screen. - perf.record_refresh(&refresh("full", None)); - assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (None, 0), "a CPU refresh clears it rather than showing a stale one"); - - // And it comes back on the next GPU refresh that carries one. - perf.record_refresh(&refresh("gpu-full", Some(timing(42.0, 6_000_000)))); - assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(42.0), 6_000_000)); - } - - #[test] - fn device_limits_support_v3d_shader_variable_limit() { - let supported = wgpu::Limits { max_texture_dimension_2d: 7680, max_inter_stage_shader_variables: 15, ..wgpu::Limits::default() }; - let requested = device_limits_for(wgpu::Backend::Vulkan, supported.clone()); - assert_eq!(requested.max_inter_stage_shader_variables, 15); - assert!(requested.check_limits(&supported)); - assert_eq!(requested.max_texture_dimension_2d, 7680); - assert_eq!(requested.max_buffer_size, supported.max_buffer_size); - } - - #[test] - fn device_limits_support_weaker_gl_adapters() { - let supported = wgpu::Limits { - max_texture_dimension_2d: 1024, - max_texture_dimension_3d: 128, - max_bind_groups: 2, - max_buffer_size: 128 << 20, - ..wgpu::Limits::downlevel_webgl2_defaults() - }; - let requested = device_limits_for(wgpu::Backend::Gl, supported.clone()); - assert!(requested.check_limits(&supported)); - assert_eq!(requested, supported); - } - - #[test] - fn device_limits_preserve_backend_defaults_on_capable_adapters() { - let supported = wgpu::Limits { - max_texture_dimension_2d: 16_384, - max_buffer_size: 1 << 30, - max_bind_groups: 8, - max_inter_stage_shader_variables: 32, - min_uniform_buffer_offset_alignment: 64, - min_storage_buffer_offset_alignment: 64, - ..wgpu::Limits::default() - }; - for (backend, base) in [ - (wgpu::Backend::Vulkan, wgpu::Limits::default()), - (wgpu::Backend::Dx12, wgpu::Limits::default()), - (wgpu::Backend::Metal, wgpu::Limits::default()), - (wgpu::Backend::Gl, wgpu::Limits::downlevel_webgl2_defaults()), - ] { - let requested = device_limits_for(backend, supported.clone()); - assert!(requested.check_limits(&supported)); - assert_eq!(requested, wgpu::Limits { max_texture_dimension_2d: 16_384, max_buffer_size: 1 << 30, ..base }, "{backend:?}"); - } - } - - #[test] - fn device_limits_support_larger_minimum_alignments() { - let supported = wgpu::Limits { min_uniform_buffer_offset_alignment: 512, min_storage_buffer_offset_alignment: 1024, ..wgpu::Limits::default() }; - for backend in [wgpu::Backend::Vulkan, wgpu::Backend::Gl] { - let requested = device_limits_for(backend, supported.clone()); - assert!(requested.check_limits(&supported)); - assert_eq!(requested.min_uniform_buffer_offset_alignment, 512); - assert_eq!(requested.min_storage_buffer_offset_alignment, 1024); - } - } - - /// The scratch-texture workaround is for Intel's DX12 drivers (#892); other DX12 adapters - /// render straight into the level like every other backend (#4515). - #[test] - fn separate_mip_targets_only_for_intel_on_dx12() { - use wgpu::Backend::{Dx12, Metal, Vulkan}; - let (intel, nvidia, amd) = (0x8086, 0x10de, 0x1002); - assert!(separate_mip_targets(Dx12, intel, None)); - assert!(!separate_mip_targets(Dx12, nvidia, None)); - assert!(!separate_mip_targets(Dx12, amd, None)); - assert!(!separate_mip_targets(Vulkan, intel, None)); - assert!(!separate_mip_targets(Metal, 0, None)); - // PHOTOCRAFT_SEPARATE_MIPS forces either way; anything else leaves the default. - assert!(separate_mip_targets(Dx12, nvidia, Some("1"))); - assert!(!separate_mip_targets(Dx12, intel, Some(" 0 "))); - assert!(separate_mip_targets(Dx12, intel, Some("yes"))); - } - - /// #6418: levels of at most WHOLE_MIP_SIDE are redrawn whole; larger ones keep the damage. - #[test] - fn small_mip_levels_are_redrawn_whole() { - // A 3 × 3 dab at (800, 500) of a 1791 × 1083 tile, at mip 1 (895 × 541): halved and padded. - assert_eq!(mip_damage([800, 500, 803, 503], 895, 541), [399, 249, 403, 253]); - // At most 128 px on either side: the whole level, wherever the damage is. - assert_eq!(mip_damage([100, 60, 102, 63], 111, 67), [0, 0, 111, 67]); - assert_eq!(mip_damage([0, 0, 1, 1], 128, 2), [0, 0, 128, 2]); - assert_eq!(mip_damage([0, 0, 1, 1], 129, 2), [0, 0, 2, 2]); - } - - #[test] - fn gpu_budget_follows_memory_usage_and_ram() { - const G: u64 = 1 << 30; - // Card memory unknown (integrated, software, or unreadable): what Memory Usage leaves - // after the document, within a quarter of RAM. - assert_eq!(memory_budget(8 * G, 3 * G, Some(48 * G), None, 0), 5 * G); - assert_eq!(memory_budget(8 * G, 3 * G, Some(16 * G), None, 0), 4 * G); - assert_eq!(memory_budget(64 * G, 3 * G, Some(16 * G), None, 0), 4 * G); - // Never below the floor, even with nothing left; 16 GB assumed when RAM is unknown. - assert_eq!(memory_budget(8 * G, 10 * G, Some(48 * G), None, 0), MIN_GPU_BUDGET); - assert_eq!(memory_budget(64 * G, 0, None, None, 0), 4 * G); - // A card's own memory, known, doesn't hold the document's pixels: 10 GB of layers no - // longer squeeze the budget, which stays within 3/8 of the card (#4536). - assert_eq!(memory_budget(8 * G, 10 * G, Some(32 * G), Some(32 * G), 0), 8 * G); - assert_eq!(memory_budget(8 * G, 10 * G, Some(32 * G), Some(16 * G), 0), 6 * G); - assert_eq!(memory_budget(8 * G, 10 * G, Some(16 * G), Some(32 * G), 0), 4 * G); - // GPU Memory set: that much, within the card's share, above the floor. - assert_eq!(memory_budget(8 * G, 10 * G, Some(16 * G), None, 12 * G), 12 * G); - assert_eq!(memory_budget(8 * G, 10 * G, Some(16 * G), Some(16 * G), 12 * G), 6 * G); - assert_eq!(memory_budget(8 * G, 0, None, Some(32 * G), 1 << 20), MIN_GPU_BUDGET); - assert!(physical_memory().is_none_or(|b| b >= 256 << 20)); - } - - /// An 8 GB card in a 64 GB machine: both budgets used to plan for 16 GB, twice the card (#4536). - #[test] - fn gpu_budgets_fit_a_discrete_gpus_own_memory() { - const G: u64 = 1 << 30; - let (ram, vram) = (Some(64 * G), Some(8 * G)); - assert_eq!(memory_budget(64 * G, 3 * G, ram, vram, 0), 3 * G); - assert_eq!(canvas_budget(ram, vram), 3 * G); - assert!(memory_budget(64 * G, 0, ram, vram, 0) + canvas_budget(ram, vram) <= 6 * G, "a quarter of the card stays free"); - // A card larger than a quarter of RAM caps nothing (its own memory isn't charged for the - // document's 3 GB); a tiny one keeps the floor. - assert_eq!(memory_budget(8 * G, 3 * G, Some(48 * G), Some(24 * G), 0), 8 * G); - assert_eq!(canvas_budget(Some(16 * G), Some(24 * G)), 4 * G); - assert_eq!(memory_budget(64 * G, 0, ram, Some(G), 0), MIN_GPU_BUDGET); - assert_eq!(canvas_budget(ram, Some(G)), MIN_GPU_BUDGET); - } - - /// DXGI reports each adapter's dedicated memory, found by the vendor and device ids wgpu gives. - #[cfg(windows)] - #[test] - fn windows_reports_the_adapters_own_memory() { - use winsafe::prelude::*; - let descs: Vec<_> = winsafe::CreateDXGIFactory1().unwrap().EnumAdapters1().map(|a| a.unwrap().GetDesc1().unwrap()).collect(); - assert!(!descs.is_empty(), "DXGI lists at least its software adapter"); - for d in descs.iter().filter(|d| d.DedicatedVideoMemory > 0) { - // The first adapter with these ids is the one matched. - let first = descs.iter().find(|e| e.VendorId == d.VendorId && e.DeviceId == d.DeviceId).unwrap(); - assert_eq!(detect_video_memory(d.VendorId, d.DeviceId), Some(first.DedicatedVideoMemory as u64)); - } - assert_eq!(detect_video_memory(0xdead, 0xbeef), None, "no such adapter"); - } - - /// System Info names the card's own memory, after the driver, when the card reports one; an - /// integrated GPU or an unknown card shows no such line. - #[test] - fn system_info_shows_the_cards_memory() { - let info = GpuInfo { adapter: "Card".into(), driver: "Driver 1".into(), video_memory_mb: Some(8192), ..Default::default() }; - let lines = info.lines(); - assert_eq!(lines.get(2).map(String::as_str), Some("Driver: Driver 1")); - assert_eq!(lines.get(3).map(String::as_str), Some("Graphics memory: 8.0G")); - let none = GpuInfo { video_memory_mb: None, ..info }.lines(); - assert!(none.iter().all(|l| !l.starts_with("Graphics memory")), "{none:?}"); - assert_eq!(none.len() + 1, lines.len()); - } - - /// The Linux reader finds the card by its PCI ids in a `/sys/class/drm`-shaped folder and reads - /// amdgpu's VRAM size; a card without one, unreadable ids or a malformed size give nothing. - #[test] - fn drm_video_memory_reads_the_matching_cards_vram() { - let drm = std::env::temp_dir().join(format!("pc-drm-{}", std::process::id())); - let card = |name: &str, vendor: &str, device: &str, vram: Option<&str>| { - let dev = drm.join(name).join("device"); - std::fs::create_dir_all(&dev).unwrap(); - std::fs::write(dev.join("vendor"), vendor).unwrap(); - std::fs::write(dev.join("device"), device).unwrap(); - if let Some(v) = vram { - std::fs::write(dev.join("mem_info_vram_total"), v).unwrap(); - } - }; - // An Intel iGPU (no VRAM file), an AMD card, and an entry with garbage ids. - card("card0", "0x8086\n", "0x9a49\n", None); - card("card1", "0x1002\n", "0x73bf\n", Some("17163091968\n")); - card("card2", "not hex\n", "0x73bf\n", Some("1\n")); - card("card3", "0x10de\n", "0x2684\n", Some("lots\n")); - assert_eq!(drm_video_memory(&drm, 0x1002, 0x73bf), Some(17_163_091_968)); - assert_eq!(drm_video_memory(&drm, 0x8086, 0x9a49), None, "no amdgpu VRAM file"); - assert_eq!(drm_video_memory(&drm, 0x10de, 0x2684), None, "a malformed size"); - assert_eq!(drm_video_memory(&drm, 0xdead, 0xbeef), None, "no such card"); - assert_eq!(drm_video_memory(&drm.join("missing"), 0x1002, 0x73bf), None, "no drm folder"); - std::fs::remove_dir_all(&drm).unwrap(); - } - - /// Windows used to report no RAM at all, so the budget assumed 16 GB on every machine. - #[cfg(windows)] - #[test] - fn windows_reports_installed_ram() { - let ram = detect_physical_memory().unwrap_or(0); - assert!(ram >= 256 << 20, "{ram} bytes"); - assert!(ram < 1 << 50, "{ram} bytes"); - } - - #[test] - fn canvas_texture_bytes_price_every_tile_and_mip_level() { - // The same sum DocTextures builds tile by tile (and texture_info reports). - let brute = |size: [u32; 2], tile: u32, bpp: u64| -> u64 { - let mut total = 0; - for ty in (0..size[1]).step_by(tile as usize) { - for tx in (0..size[0]).step_by(tile as usize) { - let (w, h) = (tile.min(size[0] - tx), tile.min(size[1] - ty)); - total += (0..mip_count(w, h)).map(|l| u64::from((w >> l).max(1)) * u64::from((h >> l).max(1)) * bpp).sum::(); - } - } - total - }; - for (size, tile) in [([1, 1], 64), ([300, 200], 64), ([128, 64], 64), ([1000, 7], 256), ([8192, 8193], 8192), ([20_000, 9_000], 8192)] { - for bpp in [4, 8] { - assert_eq!(canvas_texture_bytes(size, tile, bpp), brute(size, tile, bpp), "{size:?} tile {tile}"); - } - } - assert_eq!(canvas_texture_bytes([0, 500], 64, 4), 0); - // A canvas declared in a few bytes of a file is priced without building (or looping over) it. - let huge = canvas_texture_bytes([300_000, 300_000], 8192, 4); - assert!(huge > 300_000u64 * 300_000 * 4 && huge > canvas_budget(Some(1 << 40), None)); - assert_eq!(canvas_texture_bytes([u32::MAX, u32::MAX], 64, 8), u64::MAX, "saturates"); - // A quarter of RAM (16 GB assumed), never below the compositor's floor. - assert_eq!(canvas_budget(None, None), 4 << 30); - assert_eq!(canvas_budget(Some(1 << 30), None), MIN_GPU_BUDGET); - assert!(canvas_texture_bytes([12_000, 8_000], DEFAULT_TILE, 8) < canvas_budget(None, None), "a 96 MP 16-bit canvas stays on the GPU"); - } - - #[test] - fn view_uniform_packs_rotation() { - assert_eq!(VIEW_FLOATS, 32); - assert_eq!(VIEW_UNIFORM_SIZE, 128); - assert_eq!(VIEW_FLOATS * 4, VIEW_UNIFORM_SIZE as usize); - assert!(gpu_view_ok(false, 0.0, 1.0)); - assert!(gpu_view_ok(false, 45.0_f32.to_radians(), 1.0)); - assert!(!gpu_view_ok(true, 45.0_f32.to_radians(), 1.0)); - assert!(!gpu_view_ok(false, 0.0, 2.0), "pixel aspect correction draws on the CPU"); - // Identity packing: rotation 0 matches the unrotated origin + scale map. - let origin = [10.0, 20.0]; - let (scale, center) = (2.0, [40.0, 8.0]); - let a = map_doc_px(origin, scale, center, 1.0, 0.0, 5.0, 9.0); - assert!((a[0] - (origin[0] + 5.0 * scale)).abs() < 1e-4); - assert!((a[1] - (origin[1] + 9.0 * scale)).abs() < 1e-4); - let (x0, y0, x1, y1) = tile_screen_aabb(origin, scale, center, 1.0, 0.0, [0.0, 0.0, 10.0, 4.0]); - assert!((x0 - origin[0]).abs() < 1e-4 && (y0 - origin[1]).abs() < 1e-4); - assert!((x1 - (origin[0] + 20.0)).abs() < 1e-4 && (y1 - (origin[1] + 8.0)).abs() < 1e-4); - } - - #[test] - fn filter_modes() { - assert_eq!(filter_mode(0.25), (0.0, 2.0)); - assert_eq!(filter_mode(1.0).0, 2.0); - assert_eq!(filter_mode(1.5).0, 1.0); - assert_eq!(filter_mode(3.3).0, 2.0); - } - - #[test] - fn mips_and_premultiply() { - assert_eq!(mip_count(1, 1), 1); - assert_eq!(mip_count(4096, 100), 13); - assert_eq!(mip_count(5, 3), 3); - assert_eq!(premultiply_rgba8(&[[1.0, 0.5, 0.0, 0.5]]), vec![128, 64, 0, 128]); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn half_floats() { - // Every finite half survives the round trip; ties round to even; overflow saturates. - for h in 0..=u16::MAX { - if h & 0x7c00 != 0x7c00 && h != 0x8000 { - assert_eq!(f32_to_f16(f16_to_f32(h)), h, "{h:#06x}"); - } - } - assert_eq!(f32_to_f16(1.0), 0x3c00); - assert_eq!(f32_to_f16(1.0 + 2f32.powi(-11)), 0x3c00); - assert_eq!(f32_to_f16(1.0 + 3.0 * 2f32.powi(-11)), 0x3c02); - assert_eq!(f32_to_f16(2f32.powi(-24)), 1); - assert_eq!(f32_to_f16(2f32.powi(-26)), 0); - assert_eq!(f32_to_f16(65504.0), 0x7bff); - assert_eq!(f32_to_f16(1e9), 0x7bff); - assert_eq!(f32_to_f16(f32::INFINITY), 0x7bff); - assert_eq!(f32_to_f16(f32::NAN), 0); - assert_eq!(f32_to_f16(-2.0), 0xc000); - assert_eq!(premultiply_rgba16f(&[[2.0, -1.0, f32::NAN, 0.5]]), [0x00, 0x3c, 0, 0, 0, 0, 0x00, 0x38]); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn shaders_validate() { - use wgpu::naga; - for (name, src) in [("canvas", CANVAS_WGSL), ("mip", MIP_WGSL), ("encode", ENCODE_WGSL)] { - let module = naga::front::wgsl::parse_str(src).unwrap_or_else(|e| panic!("{name}: {}", e.emit_to_string(src))); - naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()) - .validate(&module) - .unwrap_or_else(|e| panic!("{name}: {e:?}")); - } - } -} +mod tests; diff --git a/crates/ui-egui/src/gpu_canvas/tests.rs b/crates/ui-egui/src/gpu_canvas/tests.rs new file mode 100644 index 0000000000..7402f5026f --- /dev/null +++ b/crates/ui-egui/src/gpu_canvas/tests.rs @@ -0,0 +1,319 @@ +use super::*; + +/// A GPU measurement arrives a frame or two after its refresh, so most GPU refreshes carry +/// none; the last one reported must stand until a newer one lands. A CPU refresh is +/// different: there is no GPU time at all then, and keeping the old number would show it as +/// this refresh's. Runs anywhere — the GPU timing tests need hardware and CI has none. +#[test] +fn a_gpu_measurement_stands_until_replaced_and_a_cpu_refresh_clears_it() { + let timing = |ms, px| photocraft_gpu::GpuTiming { ms, px, spans: 1 }; + let refresh = |kind, gpu| Refresh { kind, gpu, ..Default::default() }; + let mut perf = Perf::default(); + assert_eq!(perf.gpu_ms, None, "nothing is reported before a measurement"); + + perf.record_refresh(&refresh("gpu-full", Some(timing(83.9, 24_000_000)))); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(83.9), 24_000_000)); + + // The common case: a GPU refresh whose own measurement has not come back yet. + perf.record_refresh(&refresh("gpu-rect", None)); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(83.9), 24_000_000), "the last measurement stands"); + + perf.record_refresh(&refresh("gpu-rect", Some(timing(11.2, 1_098_640)))); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(11.2), 1_098_640), "a newer measurement replaces it"); + + // The CPU compositor did this one: the GPU number belongs to no refresh on screen. + perf.record_refresh(&refresh("full", None)); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (None, 0), "a CPU refresh clears it rather than showing a stale one"); + + // And it comes back on the next GPU refresh that carries one. + perf.record_refresh(&refresh("gpu-full", Some(timing(42.0, 6_000_000)))); + assert_eq!((perf.gpu_ms, perf.gpu_ms_px), (Some(42.0), 6_000_000)); +} + +#[test] +fn device_limits_support_v3d_shader_variable_limit() { + let supported = wgpu::Limits { max_texture_dimension_2d: 7680, max_inter_stage_shader_variables: 15, ..wgpu::Limits::default() }; + let requested = device_limits_for(wgpu::Backend::Vulkan, supported.clone()); + assert_eq!(requested.max_inter_stage_shader_variables, 15); + assert!(requested.check_limits(&supported)); + assert_eq!(requested.max_texture_dimension_2d, 7680); + assert_eq!(requested.max_buffer_size, supported.max_buffer_size); +} + +#[test] +fn device_limits_support_weaker_gl_adapters() { + let supported = wgpu::Limits { + max_texture_dimension_2d: 1024, + max_texture_dimension_3d: 128, + max_bind_groups: 2, + max_buffer_size: 128 << 20, + ..wgpu::Limits::downlevel_webgl2_defaults() + }; + let requested = device_limits_for(wgpu::Backend::Gl, supported.clone()); + assert!(requested.check_limits(&supported)); + assert_eq!(requested, supported); +} + +#[test] +fn device_limits_preserve_backend_defaults_on_capable_adapters() { + let supported = wgpu::Limits { + max_texture_dimension_2d: 16_384, + max_buffer_size: 1 << 30, + max_bind_groups: 8, + max_inter_stage_shader_variables: 32, + min_uniform_buffer_offset_alignment: 64, + min_storage_buffer_offset_alignment: 64, + ..wgpu::Limits::default() + }; + for (backend, base) in [ + (wgpu::Backend::Vulkan, wgpu::Limits::default()), + (wgpu::Backend::Dx12, wgpu::Limits::default()), + (wgpu::Backend::Metal, wgpu::Limits::default()), + (wgpu::Backend::Gl, wgpu::Limits::downlevel_webgl2_defaults()), + ] { + let requested = device_limits_for(backend, supported.clone()); + assert!(requested.check_limits(&supported)); + assert_eq!(requested, wgpu::Limits { max_texture_dimension_2d: 16_384, max_buffer_size: 1 << 30, ..base }, "{backend:?}"); + } +} + +#[test] +fn device_limits_support_larger_minimum_alignments() { + let supported = wgpu::Limits { min_uniform_buffer_offset_alignment: 512, min_storage_buffer_offset_alignment: 1024, ..wgpu::Limits::default() }; + for backend in [wgpu::Backend::Vulkan, wgpu::Backend::Gl] { + let requested = device_limits_for(backend, supported.clone()); + assert!(requested.check_limits(&supported)); + assert_eq!(requested.min_uniform_buffer_offset_alignment, 512); + assert_eq!(requested.min_storage_buffer_offset_alignment, 1024); + } +} + +/// The scratch-texture workaround is for Intel's DX12 drivers (#892); other DX12 adapters +/// render straight into the level like every other backend (#4515). +#[test] +fn separate_mip_targets_only_for_intel_on_dx12() { + use wgpu::Backend::{Dx12, Metal, Vulkan}; + let (intel, nvidia, amd) = (0x8086, 0x10de, 0x1002); + assert!(separate_mip_targets(Dx12, intel, None)); + assert!(!separate_mip_targets(Dx12, nvidia, None)); + assert!(!separate_mip_targets(Dx12, amd, None)); + assert!(!separate_mip_targets(Vulkan, intel, None)); + assert!(!separate_mip_targets(Metal, 0, None)); + // PHOTOCRAFT_SEPARATE_MIPS forces either way; anything else leaves the default. + assert!(separate_mip_targets(Dx12, nvidia, Some("1"))); + assert!(!separate_mip_targets(Dx12, intel, Some(" 0 "))); + assert!(separate_mip_targets(Dx12, intel, Some("yes"))); +} + +/// #6418: levels of at most WHOLE_MIP_SIDE are redrawn whole; larger ones keep the damage. +#[test] +fn small_mip_levels_are_redrawn_whole() { + // A 3 × 3 dab at (800, 500) of a 1791 × 1083 tile, at mip 1 (895 × 541): halved and padded. + assert_eq!(mip_damage([800, 500, 803, 503], 895, 541), [399, 249, 403, 253]); + // At most 128 px on either side: the whole level, wherever the damage is. + assert_eq!(mip_damage([100, 60, 102, 63], 111, 67), [0, 0, 111, 67]); + assert_eq!(mip_damage([0, 0, 1, 1], 128, 2), [0, 0, 128, 2]); + assert_eq!(mip_damage([0, 0, 1, 1], 129, 2), [0, 0, 2, 2]); +} + +#[test] +fn gpu_budget_follows_memory_usage_and_ram() { + const G: u64 = 1 << 30; + // Card memory unknown (integrated, software, or unreadable): what Memory Usage leaves + // after the document, within a quarter of RAM. + assert_eq!(memory_budget(8 * G, 3 * G, Some(48 * G), None, 0), 5 * G); + assert_eq!(memory_budget(8 * G, 3 * G, Some(16 * G), None, 0), 4 * G); + assert_eq!(memory_budget(64 * G, 3 * G, Some(16 * G), None, 0), 4 * G); + // Never below the floor, even with nothing left; 16 GB assumed when RAM is unknown. + assert_eq!(memory_budget(8 * G, 10 * G, Some(48 * G), None, 0), MIN_GPU_BUDGET); + assert_eq!(memory_budget(64 * G, 0, None, None, 0), 4 * G); + // A card's own memory, known, doesn't hold the document's pixels: 10 GB of layers no + // longer squeeze the budget, which stays within 3/8 of the card (#4536). + assert_eq!(memory_budget(8 * G, 10 * G, Some(32 * G), Some(32 * G), 0), 8 * G); + assert_eq!(memory_budget(8 * G, 10 * G, Some(32 * G), Some(16 * G), 0), 6 * G); + assert_eq!(memory_budget(8 * G, 10 * G, Some(16 * G), Some(32 * G), 0), 4 * G); + // GPU Memory set: that much, within the card's share, above the floor. + assert_eq!(memory_budget(8 * G, 10 * G, Some(16 * G), None, 12 * G), 12 * G); + assert_eq!(memory_budget(8 * G, 10 * G, Some(16 * G), Some(16 * G), 12 * G), 6 * G); + assert_eq!(memory_budget(8 * G, 0, None, Some(32 * G), 1 << 20), MIN_GPU_BUDGET); + assert!(physical_memory().is_none_or(|b| b >= 256 << 20)); +} + +/// An 8 GB card in a 64 GB machine: both budgets used to plan for 16 GB, twice the card (#4536). +#[test] +fn gpu_budgets_fit_a_discrete_gpus_own_memory() { + const G: u64 = 1 << 30; + let (ram, vram) = (Some(64 * G), Some(8 * G)); + assert_eq!(memory_budget(64 * G, 3 * G, ram, vram, 0), 3 * G); + assert_eq!(canvas_budget(ram, vram), 3 * G); + assert!(memory_budget(64 * G, 0, ram, vram, 0) + canvas_budget(ram, vram) <= 6 * G, "a quarter of the card stays free"); + // A card larger than a quarter of RAM caps nothing (its own memory isn't charged for the + // document's 3 GB); a tiny one keeps the floor. + assert_eq!(memory_budget(8 * G, 3 * G, Some(48 * G), Some(24 * G), 0), 8 * G); + assert_eq!(canvas_budget(Some(16 * G), Some(24 * G)), 4 * G); + assert_eq!(memory_budget(64 * G, 0, ram, Some(G), 0), MIN_GPU_BUDGET); + assert_eq!(canvas_budget(ram, Some(G)), MIN_GPU_BUDGET); +} + +/// DXGI reports each adapter's dedicated memory, found by the vendor and device ids wgpu gives. +#[cfg(windows)] +#[test] +fn windows_reports_the_adapters_own_memory() { + use winsafe::prelude::*; + let descs: Vec<_> = winsafe::CreateDXGIFactory1().unwrap().EnumAdapters1().map(|a| a.unwrap().GetDesc1().unwrap()).collect(); + assert!(!descs.is_empty(), "DXGI lists at least its software adapter"); + for d in descs.iter().filter(|d| d.DedicatedVideoMemory > 0) { + // The first adapter with these ids is the one matched. + let first = descs.iter().find(|e| e.VendorId == d.VendorId && e.DeviceId == d.DeviceId).unwrap(); + assert_eq!(detect_video_memory(d.VendorId, d.DeviceId), Some(first.DedicatedVideoMemory as u64)); + } + assert_eq!(detect_video_memory(0xdead, 0xbeef), None, "no such adapter"); +} + +/// System Info names the card's own memory, after the driver, when the card reports one; an +/// integrated GPU or an unknown card shows no such line. +#[test] +fn system_info_shows_the_cards_memory() { + let info = GpuInfo { adapter: "Card".into(), driver: "Driver 1".into(), video_memory_mb: Some(8192), ..Default::default() }; + let lines = info.lines(); + assert_eq!(lines.get(2).map(String::as_str), Some("Driver: Driver 1")); + assert_eq!(lines.get(3).map(String::as_str), Some("Graphics memory: 8.0G")); + let none = GpuInfo { video_memory_mb: None, ..info }.lines(); + assert!(none.iter().all(|l| !l.starts_with("Graphics memory")), "{none:?}"); + assert_eq!(none.len() + 1, lines.len()); +} + +/// The Linux reader finds the card by its PCI ids in a `/sys/class/drm`-shaped folder and reads +/// amdgpu's VRAM size; a card without one, unreadable ids or a malformed size give nothing. +#[test] +fn drm_video_memory_reads_the_matching_cards_vram() { + let drm = std::env::temp_dir().join(format!("pc-drm-{}", std::process::id())); + let card = |name: &str, vendor: &str, device: &str, vram: Option<&str>| { + let dev = drm.join(name).join("device"); + std::fs::create_dir_all(&dev).unwrap(); + std::fs::write(dev.join("vendor"), vendor).unwrap(); + std::fs::write(dev.join("device"), device).unwrap(); + if let Some(v) = vram { + std::fs::write(dev.join("mem_info_vram_total"), v).unwrap(); + } + }; + // An Intel iGPU (no VRAM file), an AMD card, and an entry with garbage ids. + card("card0", "0x8086\n", "0x9a49\n", None); + card("card1", "0x1002\n", "0x73bf\n", Some("17163091968\n")); + card("card2", "not hex\n", "0x73bf\n", Some("1\n")); + card("card3", "0x10de\n", "0x2684\n", Some("lots\n")); + assert_eq!(drm_video_memory(&drm, 0x1002, 0x73bf), Some(17_163_091_968)); + assert_eq!(drm_video_memory(&drm, 0x8086, 0x9a49), None, "no amdgpu VRAM file"); + assert_eq!(drm_video_memory(&drm, 0x10de, 0x2684), None, "a malformed size"); + assert_eq!(drm_video_memory(&drm, 0xdead, 0xbeef), None, "no such card"); + assert_eq!(drm_video_memory(&drm.join("missing"), 0x1002, 0x73bf), None, "no drm folder"); + std::fs::remove_dir_all(&drm).unwrap(); +} + +/// Windows used to report no RAM at all, so the budget assumed 16 GB on every machine. +#[cfg(windows)] +#[test] +fn windows_reports_installed_ram() { + let ram = detect_physical_memory().unwrap_or(0); + assert!(ram >= 256 << 20, "{ram} bytes"); + assert!(ram < 1 << 50, "{ram} bytes"); +} + +#[test] +fn canvas_texture_bytes_price_every_tile_and_mip_level() { + // The same sum DocTextures builds tile by tile (and texture_info reports). + let brute = |size: [u32; 2], tile: u32, bpp: u64| -> u64 { + let mut total = 0; + for ty in (0..size[1]).step_by(tile as usize) { + for tx in (0..size[0]).step_by(tile as usize) { + let (w, h) = (tile.min(size[0] - tx), tile.min(size[1] - ty)); + total += (0..mip_count(w, h)).map(|l| u64::from((w >> l).max(1)) * u64::from((h >> l).max(1)) * bpp).sum::(); + } + } + total + }; + for (size, tile) in [([1, 1], 64), ([300, 200], 64), ([128, 64], 64), ([1000, 7], 256), ([8192, 8193], 8192), ([20_000, 9_000], 8192)] { + for bpp in [4, 8] { + assert_eq!(canvas_texture_bytes(size, tile, bpp), brute(size, tile, bpp), "{size:?} tile {tile}"); + } + } + assert_eq!(canvas_texture_bytes([0, 500], 64, 4), 0); + // A canvas declared in a few bytes of a file is priced without building (or looping over) it. + let huge = canvas_texture_bytes([300_000, 300_000], 8192, 4); + assert!(huge > 300_000u64 * 300_000 * 4 && huge > canvas_budget(Some(1 << 40), None)); + assert_eq!(canvas_texture_bytes([u32::MAX, u32::MAX], 64, 8), u64::MAX, "saturates"); + // A quarter of RAM (16 GB assumed), never below the compositor's floor. + assert_eq!(canvas_budget(None, None), 4 << 30); + assert_eq!(canvas_budget(Some(1 << 30), None), MIN_GPU_BUDGET); + assert!(canvas_texture_bytes([12_000, 8_000], DEFAULT_TILE, 8) < canvas_budget(None, None), "a 96 MP 16-bit canvas stays on the GPU"); +} + +#[test] +fn view_uniform_packs_rotation() { + assert_eq!(VIEW_FLOATS, 32); + assert_eq!(VIEW_UNIFORM_SIZE, 128); + assert_eq!(VIEW_FLOATS * 4, VIEW_UNIFORM_SIZE as usize); + assert!(gpu_view_ok(false, 0.0, 1.0)); + assert!(gpu_view_ok(false, 45.0_f32.to_radians(), 1.0)); + assert!(!gpu_view_ok(true, 45.0_f32.to_radians(), 1.0)); + assert!(!gpu_view_ok(false, 0.0, 2.0), "pixel aspect correction draws on the CPU"); + // Identity packing: rotation 0 matches the unrotated origin + scale map. + let origin = [10.0, 20.0]; + let (scale, center) = (2.0, [40.0, 8.0]); + let a = map_doc_px(origin, scale, center, 1.0, 0.0, 5.0, 9.0); + assert!((a[0] - (origin[0] + 5.0 * scale)).abs() < 1e-4); + assert!((a[1] - (origin[1] + 9.0 * scale)).abs() < 1e-4); + let (x0, y0, x1, y1) = tile_screen_aabb(origin, scale, center, 1.0, 0.0, [0.0, 0.0, 10.0, 4.0]); + assert!((x0 - origin[0]).abs() < 1e-4 && (y0 - origin[1]).abs() < 1e-4); + assert!((x1 - (origin[0] + 20.0)).abs() < 1e-4 && (y1 - (origin[1] + 8.0)).abs() < 1e-4); +} + +#[test] +fn filter_modes() { + assert_eq!(filter_mode(0.25), (0.0, 2.0)); + assert_eq!(filter_mode(1.0).0, 2.0); + assert_eq!(filter_mode(1.5).0, 1.0); + assert_eq!(filter_mode(3.3).0, 2.0); +} + +#[test] +fn mips_and_premultiply() { + assert_eq!(mip_count(1, 1), 1); + assert_eq!(mip_count(4096, 100), 13); + assert_eq!(mip_count(5, 3), 3); + assert_eq!(premultiply_rgba8(&[[1.0, 0.5, 0.0, 0.5]]), vec![128, 64, 0, 128]); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn half_floats() { + // Every finite half survives the round trip; ties round to even; overflow saturates. + for h in 0..=u16::MAX { + if h & 0x7c00 != 0x7c00 && h != 0x8000 { + assert_eq!(f32_to_f16(f16_to_f32(h)), h, "{h:#06x}"); + } + } + assert_eq!(f32_to_f16(1.0), 0x3c00); + assert_eq!(f32_to_f16(1.0 + 2f32.powi(-11)), 0x3c00); + assert_eq!(f32_to_f16(1.0 + 3.0 * 2f32.powi(-11)), 0x3c02); + assert_eq!(f32_to_f16(2f32.powi(-24)), 1); + assert_eq!(f32_to_f16(2f32.powi(-26)), 0); + assert_eq!(f32_to_f16(65504.0), 0x7bff); + assert_eq!(f32_to_f16(1e9), 0x7bff); + assert_eq!(f32_to_f16(f32::INFINITY), 0x7bff); + assert_eq!(f32_to_f16(f32::NAN), 0); + assert_eq!(f32_to_f16(-2.0), 0xc000); + assert_eq!(premultiply_rgba16f(&[[2.0, -1.0, f32::NAN, 0.5]]), [0x00, 0x3c, 0, 0, 0, 0, 0x00, 0x38]); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn shaders_validate() { + use wgpu::naga; + for (name, src) in [("canvas", CANVAS_WGSL), ("mip", MIP_WGSL), ("encode", ENCODE_WGSL)] { + let module = naga::front::wgsl::parse_str(src).unwrap_or_else(|e| panic!("{name}: {}", e.emit_to_string(src))); + naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()) + .validate(&module) + .unwrap_or_else(|e| panic!("{name}: {e:?}")); + } +} From ea5a7cfc8535e7f4995b487e7f0c43ccdc1d05bd Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:00 +0000 Subject: [PATCH 076/259] refactor(ui-egui): move puppet_ui.rs tests to puppet_ui/tests.rs --- crates/ui-egui/src/puppet_ui.rs | 431 +------------------------- crates/ui-egui/src/puppet_ui/tests.rs | 428 +++++++++++++++++++++++++ 2 files changed, 429 insertions(+), 430 deletions(-) create mode 100644 crates/ui-egui/src/puppet_ui/tests.rs diff --git a/crates/ui-egui/src/puppet_ui.rs b/crates/ui-egui/src/puppet_ui.rs index cb390f77ad..bf905c4c29 100644 --- a/crates/ui-egui/src/puppet_ui.rs +++ b/crates/ui-egui/src/puppet_ui.rs @@ -484,433 +484,4 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } #[cfg(test)] -mod tests { - use super::*; - - fn puppet_app(ctx: &egui::Context) -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(20, 30, 80, 50), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - app.sync_views(); - begin(&mut app, ctx, "edit.puppetWarp").unwrap(); - app - } - - fn gesture(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { - pointer(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, egui::Modifiers::NONE); - pointer(app, ToolEvent::Up { x: to[0], y: to[1] }, egui::Modifiers::NONE); - } - - fn press(app: &mut PhotocraftApp, ctx: &egui::Context, key: egui::Key, modifiers: egui::Modifiers) { - let events = [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }).to_vec(); - let input = egui::RawInput { events, ..Default::default() }; - ctx.run_ui(input, |ui| crate::shortcuts::handle(app, ui.ctx())).textures_delta.clear(); - } - - #[test] - fn delete_keys_remove_selected_pin_and_restore_its_deformation_on_undo() { - for key in [egui::Key::Delete, egui::Key::Backspace] { - let ctx = egui::Context::default(); - let mut app = puppet_app(&ctx); - gesture(&mut app, [25.0, 40.0], [25.0, 40.0]); - gesture(&mut app, [75.0, 40.0], [75.0, 40.0]); - gesture(&mut app, [75.0, 40.0], [75.0, 30.0]); - gesture(&mut app, [25.0, 40.0], [25.0, 20.0]); - let s = app.distort.puppet.as_mut().unwrap(); - // Rotation/depth are part of a deleted pin's state, not just its position. - let before = s.warp.pins.clone(); - s.warp.pins[0].rotate = Some(15.0); - s.warp.pins[0].depth = 2; - s.rebind(); - s.record(before); - let pins = s.warp.pins.clone(); - let deformed = s.deformed.clone(); - let order = s.order.clone(); - let edits = s.undo.len(); - let survivor = &pins[1]; - let solver = PuppetSolver::new(s.mesh.clone(), &[survivor.src], &[survivor.rotate.is_some()]); - let expected = solver.solve(&[survivor.dst], &[survivor.rotate], s.warp.mode, ITERATIONS, None).0; - let past = app.session.active().unwrap().history.past_len(); - - press(&mut app, &ctx, key, egui::Modifiers::NONE); - let s = app.distort.puppet.as_ref().unwrap(); - assert_eq!(s.warp.pins, pins[1..], "{key:?}: delete the selected first pin, not the last"); - assert_eq!(s.selected, None); - assert_eq!(s.deformed, expected, "solve from rest without the deleted constraint"); - assert_eq!(s.order, solver.draw_order(&[survivor.depth], &[survivor.src])); - assert_eq!(s.undo.len(), edits + 1); - press(&mut app, &ctx, key, egui::Modifiers::NONE); - assert_eq!(app.distort.puppet.as_ref().unwrap().undo.len(), edits + 1, "no selection: no edit"); - - press(&mut app, &ctx, egui::Key::Z, egui::Modifiers::COMMAND); - let s = app.distort.puppet.as_ref().unwrap(); - assert_eq!(s.warp.pins, pins); - assert_eq!(s.deformed, deformed); - assert_eq!(s.order, order); - press(&mut app, &ctx, egui::Key::Z, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT); - assert_eq!(app.distort.puppet.as_ref().unwrap().deformed, expected); - assert_eq!(app.session.active().unwrap().history.past_len(), past, "pin edits stay in the open session"); - - let original = app.session.active().unwrap().doc.clone(); - commit(&mut app); - assert_eq!(app.session.active().unwrap().history.past_len(), past + 1); - let committed = app.session.active().unwrap().doc.clone(); - assert_ne!(committed, original); - app.session.execute("edit.undo", json!({})).unwrap(); - assert_eq!(app.session.active().unwrap().doc, original); - app.session.execute("edit.redo", json!({})).unwrap(); - assert_eq!(app.session.active().unwrap().doc, committed); - } - } - - #[test] - fn deleting_during_a_drag_settles_history_and_cannot_move_the_next_pin() { - let ctx = egui::Context::default(); - let mut app = puppet_app(&ctx); - gesture(&mut app, [25.0, 40.0], [25.0, 40.0]); - gesture(&mut app, [75.0, 40.0], [75.0, 40.0]); - let original = app.distort.puppet.as_ref().unwrap().warp.pins.clone(); - pointer(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE); - pointer(&mut app, ToolEvent::Move { x: 25.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); - let moved = app.distort.puppet.as_ref().unwrap().warp.pins.clone(); - press(&mut app, &ctx, egui::Key::Delete, egui::Modifiers::NONE); - pointer(&mut app, ToolEvent::Move { x: 5.0, y: 5.0, pressure: 1.0 }, egui::Modifiers::NONE); - pointer(&mut app, ToolEvent::Up { x: 5.0, y: 5.0 }, egui::Modifiers::NONE); - let s = app.distort.puppet.as_mut().unwrap(); - assert_eq!(s.warp.pins, original[1..]); - assert!(s.drag.is_none() && s.drag_from.is_none()); - assert!(s.undo()); - assert_eq!(s.warp.pins, moved, "first undo restores the deleted pin at its moved position"); - assert!(s.undo()); - assert_eq!(s.warp.pins, original, "second undo reverts the preceding drag"); - assert!(s.redo()); - s.selected = Some(0); - control(&mut app, &json!({"deleteSelectedPin": true})).unwrap(); - assert!(!app.distort.puppet.as_mut().unwrap().redo(), "a new deletion discards the redo branch"); - } - - #[test] - fn deleting_last_pin_restores_rest_mesh_and_empty_commit_is_not_an_edit() { - let ctx = egui::Context::default(); - let mut app = puppet_app(&ctx); - gesture(&mut app, [25.0, 40.0], [25.0, 20.0]); - let past = app.session.active().unwrap().history.past_len(); - let s = app.distort.puppet.as_mut().unwrap(); - let pins = s.warp.pins.clone(); - s.selected = Some(usize::MAX); - press(&mut app, &ctx, egui::Key::Delete, egui::Modifiers::NONE); - assert_eq!(app.distort.puppet.as_ref().unwrap().warp.pins, pins, "stale selection is harmless"); - app.distort.puppet.as_mut().unwrap().selected = Some(0); - press(&mut app, &ctx, egui::Key::Backspace, egui::Modifiers::NONE); - let s = app.distort.puppet.as_ref().unwrap(); - assert!(s.warp.pins.is_empty()); - assert_eq!(s.deformed.len(), s.mesh.verts.len()); - for (deformed, rest) in s.deformed.iter().zip(&s.mesh.verts) { - assert!(dist(*deformed, *rest) < 1e-8, "no constraints: the mesh returns to rest"); - } - commit(&mut app); - assert!(app.distort.puppet.is_none()); - assert_eq!(app.session.active().unwrap().history.past_len(), past); - } - - #[test] - fn delete_keys_in_a_text_field_do_not_remove_pins() { - for key in [egui::Key::Delete, egui::Key::Backspace] { - let ctx = egui::Context::default(); - let mut app = puppet_app(&ctx); - gesture(&mut app, [25.0, 40.0], [25.0, 20.0]); - let mut text = "123".to_string(); - ctx.run_ui(Default::default(), |ui| { - ui.text_edit_singleline(&mut text).request_focus(); - }) - .textures_delta - .clear(); - let pins = app.distort.puppet.as_ref().unwrap().warp.pins.clone(); - let input = egui::RawInput { - events: vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], - ..Default::default() - }; - ctx.run_ui(input, |ui| { - assert!(ui.ctx().text_edit_focused()); - crate::shortcuts::handle(&mut app, ui.ctx()); - ui.text_edit_singleline(&mut text); - }) - .textures_delta - .clear(); - assert_eq!(app.distort.puppet.as_ref().unwrap().warp.pins, pins); - assert_eq!(app.distort.puppet.as_ref().unwrap().undo.len(), 1); - } - } - - fn long_puppet(ctx: &egui::Context, mode: PuppetMode, density: PuppetDensity) -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", json!({"width": 1000, "height": 300, "depth": 8})).unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(40, 180, 960, 220), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - app.sync_views(); - begin(&mut app, ctx, "edit.puppetWarp").unwrap(); - for x in [70.0, 160.0, 930.0] { - pointer(&mut app, ToolEvent::Down { x, y: 200.0, pressure: 1.0 }, egui::Modifiers::NONE); - pointer(&mut app, ToolEvent::Up { x, y: 200.0 }, egui::Modifiers::NONE); - } - let s = app.distort.puppet.as_mut().unwrap(); - s.warp.mode = mode; - s.warp.density = density; - s.rebuild_mesh(); - app - } - - fn assert_same_mesh(a: &[[f64; 2]], b: &[[f64; 2]]) { - assert_eq!(a.len(), b.len()); - let offset = a.iter().zip(b).map(|(a, b)| dist(*a, *b)).fold(0.0, f64::max); - assert!(offset < 1e-8, "mesh moved by {offset} px with unchanged pins"); - } - - #[test] - fn drag_preview_matches_release_history_and_committed_geometry() { - use photocraft_algo::puppet::{deform, render}; - for mode in [PuppetMode::Rigid, PuppetMode::Normal, PuppetMode::Distort] { - for density in [PuppetDensity::Fewer, PuppetDensity::Normal, PuppetDensity::More] { - let ctx = egui::Context::default(); - let mut app = long_puppet(&ctx, mode, density); - let rest = app.distort.puppet.as_ref().unwrap().deformed.clone(); - let past = app.session.active().unwrap().history.past_len(); - pointer(&mut app, ToolEvent::Down { x: 930.0, y: 200.0, pressure: 1.0 }, egui::Modifiers::NONE); - for step in 1..=12 { - let x = 930.0 - f64::from(step) * 20.0; - let y = 200.0 - f64::from(step) * 10.0; - pointer(&mut app, ToolEvent::Move { x, y, pressure: 1.0 }, egui::Modifiers::NONE); - } - let s = app.distort.puppet.as_ref().unwrap(); - let preview = s.deformed.clone(); - let order = s.order.clone(); - pointer(&mut app, ToolEvent::Up { x: 690.0, y: 80.0 }, egui::Modifiers::NONE); - let s = app.distort.puppet.as_mut().unwrap(); - assert_same_mesh(&preview, &s.deformed); - assert_eq!(order, s.order); - let (_, canonical, _) = deform(&s.surface, s.bounds, &s.warp, ITERATIONS); - assert_same_mesh(&preview, &canonical); - assert!(s.undo()); - assert_same_mesh(&rest, &s.deformed); - assert!(s.redo()); - assert_same_mesh(&preview, &s.deformed); - // Use the engine's interpolation to isolate geometry from GPU texture sampling. - let expected = render(&s.surface, s.bounds, &s.mesh, &preview, &order, photocraft_algo::transform::Interp::Bicubic); - let layer = s.layer; - assert_eq!(app.session.active().unwrap().history.past_len(), past); - commit(&mut app); - let st = app.session.active().unwrap(); - assert_eq!(st.history.past_len(), past + 1); - assert_eq!(st.doc.layer(layer).unwrap().surface().unwrap(), &expected); - } - } - } - - #[test] - fn drag_preview_is_independent_of_pointer_path_and_honors_release_coordinates() { - let ctx = egui::Context::default(); - let mut app = long_puppet(&ctx, PuppetMode::Normal, PuppetDensity::More); - let s = app.distort.puppet.as_mut().unwrap(); - s.warp.pins[0].rotate = Some(25.0); - s.rebind(); - let pins = s.warp.pins.clone(); - let paths = [ - vec![[690.0, 80.0]], - vec![[870.0, 170.0], [810.0, 140.0], [750.0, 110.0], [690.0, 80.0]], - vec![[500.0, 30.0], [930.0, 200.0], [1000.0, 270.0], [690.0, 80.0]], - ]; - let mut expected = None; - for path in paths { - app.distort.puppet.as_mut().unwrap().restore(pins.clone()); - pointer(&mut app, ToolEvent::Down { x: 930.0, y: 200.0, pressure: 1.0 }, egui::Modifiers::NONE); - for [x, y] in path { - pointer(&mut app, ToolEvent::Move { x, y, pressure: 1.0 }, egui::Modifiers::NONE); - } - let preview = &app.distort.puppet.as_ref().unwrap().deformed; - assert_same_mesh(expected.get_or_insert_with(|| preview.clone()), preview); - // The last pointer-up may carry a new position without a preceding move event. - pointer(&mut app, ToolEvent::Up { x: 720.0, y: 90.0 }, egui::Modifiers::NONE); - let s = app.distort.puppet.as_ref().unwrap(); - assert_eq!(s.warp.pins[2].dst, [720.0, 90.0]); - let (_, canonical, _) = photocraft_algo::puppet::deform(&s.surface, s.bounds, &s.warp, ITERATIONS); - assert_same_mesh(&s.deformed, &canonical); - } - } - - /// #5092: a Puppet Warp session left open does not follow the user to a new document. - #[test] - fn session_is_dropped_when_another_document_becomes_active() { - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(20, 30, 80, 50), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - app.sync_views(); - crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); - crate::distort_ui::drop_foreign(&mut app); - assert!(app.distort.puppet.is_some()); - app.session.execute("file.new", json!({"width": 32, "height": 32, "depth": 8})).unwrap(); - let active = app.session.active_index().unwrap(); - // The session stays until drop_foreign; the preview must not follow this document (#5115). - assert!(app.distort.puppet.is_some()); - assert!(crate::distort_ui::display_doc(&app, active).is_none()); - crate::distort_ui::drop_foreign(&mut app); - assert!(app.distort.puppet.is_none()); - assert!(crate::distort_ui::display_doc(&app, active).is_none()); - // Closing the document it was started on drops it too. - assert!(app.session.set_active(0)); - crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); - crate::distort_ui::drop_foreign(&mut app); - assert!(app.distort.puppet.is_some()); - assert!(app.session.close(0).is_some()); - crate::distort_ui::drop_foreign(&mut app); - assert!(app.distort.puppet.is_none()); - } - - /// #4440: ⌘Z / ⌘⇧Z undo and redo pin edits while Puppet Warp is open: placing a pin, - /// dragging one and removing one are a step each; a click that moves nothing isn't one. - #[test] - fn pin_edits_undo_and_redo_inside_the_session() { - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(20, 30, 80, 50), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - app.sync_views(); - crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); - let ev = |app: &mut PhotocraftApp, e| crate::distort_ui::pointer(app, e, egui::Modifiers::NONE); - let pins = |app: &PhotocraftApp| app.distort.puppet.as_ref().unwrap().warp.pins.iter().map(|p| p.dst).collect::>(); - ev(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Up { x: 25.0, y: 40.0 }); - ev(&mut app, ToolEvent::Down { x: 75.0, y: 40.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Up { x: 75.0, y: 40.0 }); - // Drag the second pin up; then a click on it that moves nothing. - ev(&mut app, ToolEvent::Down { x: 75.0, y: 40.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Move { x: 75.0, y: 30.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Up { x: 75.0, y: 20.0 }); - ev(&mut app, ToolEvent::Down { x: 75.0, y: 20.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Up { x: 75.0, y: 20.0 }); - crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }, egui::Modifiers { alt: true, ..Default::default() }); - assert_eq!(pins(&app), [[75.0, 20.0]]); - // ⌘Z, through the keyboard: the removed pin comes back, then the drag is undone. - let press = |app: &mut PhotocraftApp, modifiers: egui::Modifiers| { - let ev = egui::Event::Key { key: egui::Key::Z, physical_key: None, pressed: true, repeat: false, modifiers }; - let input = egui::RawInput { events: vec![ev], ..Default::default() }; - ctx.run_ui(input, |ui| assert!(crate::distort_ui::keys(app, ui.ctx()))).textures_delta.clear(); - }; - press(&mut app, egui::Modifiers::COMMAND); - assert_eq!(pins(&app), [[25.0, 40.0], [75.0, 20.0]]); - press(&mut app, egui::Modifiers::COMMAND); - assert_eq!(pins(&app), [[25.0, 40.0], [75.0, 40.0]], "the drag, not the click after it"); - // ⌘⇧Z redoes it; a new edit after an undo drops what was undone. - press(&mut app, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT); - assert_eq!(pins(&app), [[25.0, 40.0], [75.0, 20.0]]); - control(&mut app, &json!({"undo": true})).unwrap(); - control(&mut app, &json!({"undo": true})).unwrap(); - assert_eq!(pins(&app), [[25.0, 40.0]]); - ev(&mut app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Up { x: 50.0, y: 40.0 }); - control(&mut app, &json!({"redo": true})).unwrap(); - assert_eq!(pins(&app), [[25.0, 40.0], [50.0, 40.0]], "nothing left to redo"); - // Undo past the first pin stops there, and the document's History is untouched. - let past = app.session.active().unwrap().history.past_len(); - for _ in 0..5 { - control(&mut app, &json!({"undo": true})).unwrap(); - } - assert!(pins(&app).is_empty()); - assert_eq!(app.session.active().unwrap().history.past_len(), past); - } - - #[test] - fn pins_drag_and_commit_through_the_engine() { - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(20, 30, 80, 50), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - app.sync_views(); - crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); - let ev = |app: &mut PhotocraftApp, e| crate::distort_ui::pointer(app, e, egui::Modifiers::NONE); - // Two pins: hold the left end, drag the right end up. - ev(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Up { x: 25.0, y: 40.0 }); - ev(&mut app, ToolEvent::Down { x: 75.0, y: 40.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Move { x: 75.0, y: 30.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Up { x: 75.0, y: 20.0 }); - let s = app.distort.puppet.as_ref().unwrap(); - assert_eq!(s.warp.pins.len(), 2); - assert_eq!(s.warp.pins[1].dst, [75.0, 20.0]); - // ⌥-click removes; clicking off the mesh adds nothing. - ev(&mut app, ToolEvent::Down { x: 5.0, y: 5.0, pressure: 1.0 }); - assert_eq!(app.distort.puppet.as_ref().unwrap().warp.pins.len(), 2); - crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }, egui::Modifiers { alt: true, ..Default::default() }); - assert_eq!(app.distort.puppet.as_ref().unwrap().warp.pins.len(), 1); - ev(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Up { x: 25.0, y: 40.0 }); - control(&mut app, &json!({"mode": "rigid", "density": "more"})).unwrap(); - let expected = app.distort.puppet.as_ref().unwrap().deformed.clone(); - assert!(!expected.is_empty()); - let before = app.session.active().unwrap().history.past_len(); - crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({"ui": {"commit": true}})).unwrap().unwrap(); - assert!(app.distort.puppet.is_none()); - assert_eq!(app.session.active().unwrap().history.past_len(), before + 1); - let st = app.session.active().unwrap(); - let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); - assert!(b.y0 < 25, "the right end went up: {b:?}"); - } - - #[test] - fn an_expansion_that_empties_the_mesh_is_refused() { - // #951: remeshing to no vertices rebound the pins to a vertex that doesn't exist and - // panicked. -50 is the options bar's minimum and also empties this 20 px tall bar. - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(20, 30, 80, 50), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - app.sync_views(); - crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); - crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE); - crate::distort_ui::pointer(&mut app, ToolEvent::Up { x: 50.0, y: 40.0 }, egui::Modifiers::NONE); - let before = app.distort.puppet.as_ref().unwrap().describe(); - for e in [-200, -50] { - assert!(control(&mut app, &json!({"expansion": e})).is_err(), "{e}"); - assert_eq!(app.distort.puppet.as_ref().unwrap().describe(), before, "{e}: the previous settings and mesh stay"); - } - // A smaller shrink still remeshes. - let v = control(&mut app, &json!({"expansion": -2})).unwrap(); - assert_eq!(v["expansion"], -2.0); - assert!(v["triangles"].as_u64().unwrap() > 0); - } -} +mod tests; diff --git a/crates/ui-egui/src/puppet_ui/tests.rs b/crates/ui-egui/src/puppet_ui/tests.rs new file mode 100644 index 0000000000..60b7fe96b0 --- /dev/null +++ b/crates/ui-egui/src/puppet_ui/tests.rs @@ -0,0 +1,428 @@ +use super::*; + +fn puppet_app(ctx: &egui::Context) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(20, 30, 80, 50), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.sync_views(); + begin(&mut app, ctx, "edit.puppetWarp").unwrap(); + app +} + +fn gesture(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + pointer(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, egui::Modifiers::NONE); + pointer(app, ToolEvent::Up { x: to[0], y: to[1] }, egui::Modifiers::NONE); +} + +fn press(app: &mut PhotocraftApp, ctx: &egui::Context, key: egui::Key, modifiers: egui::Modifiers) { + let events = [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }).to_vec(); + let input = egui::RawInput { events, ..Default::default() }; + ctx.run_ui(input, |ui| crate::shortcuts::handle(app, ui.ctx())).textures_delta.clear(); +} + +#[test] +fn delete_keys_remove_selected_pin_and_restore_its_deformation_on_undo() { + for key in [egui::Key::Delete, egui::Key::Backspace] { + let ctx = egui::Context::default(); + let mut app = puppet_app(&ctx); + gesture(&mut app, [25.0, 40.0], [25.0, 40.0]); + gesture(&mut app, [75.0, 40.0], [75.0, 40.0]); + gesture(&mut app, [75.0, 40.0], [75.0, 30.0]); + gesture(&mut app, [25.0, 40.0], [25.0, 20.0]); + let s = app.distort.puppet.as_mut().unwrap(); + // Rotation/depth are part of a deleted pin's state, not just its position. + let before = s.warp.pins.clone(); + s.warp.pins[0].rotate = Some(15.0); + s.warp.pins[0].depth = 2; + s.rebind(); + s.record(before); + let pins = s.warp.pins.clone(); + let deformed = s.deformed.clone(); + let order = s.order.clone(); + let edits = s.undo.len(); + let survivor = &pins[1]; + let solver = PuppetSolver::new(s.mesh.clone(), &[survivor.src], &[survivor.rotate.is_some()]); + let expected = solver.solve(&[survivor.dst], &[survivor.rotate], s.warp.mode, ITERATIONS, None).0; + let past = app.session.active().unwrap().history.past_len(); + + press(&mut app, &ctx, key, egui::Modifiers::NONE); + let s = app.distort.puppet.as_ref().unwrap(); + assert_eq!(s.warp.pins, pins[1..], "{key:?}: delete the selected first pin, not the last"); + assert_eq!(s.selected, None); + assert_eq!(s.deformed, expected, "solve from rest without the deleted constraint"); + assert_eq!(s.order, solver.draw_order(&[survivor.depth], &[survivor.src])); + assert_eq!(s.undo.len(), edits + 1); + press(&mut app, &ctx, key, egui::Modifiers::NONE); + assert_eq!(app.distort.puppet.as_ref().unwrap().undo.len(), edits + 1, "no selection: no edit"); + + press(&mut app, &ctx, egui::Key::Z, egui::Modifiers::COMMAND); + let s = app.distort.puppet.as_ref().unwrap(); + assert_eq!(s.warp.pins, pins); + assert_eq!(s.deformed, deformed); + assert_eq!(s.order, order); + press(&mut app, &ctx, egui::Key::Z, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT); + assert_eq!(app.distort.puppet.as_ref().unwrap().deformed, expected); + assert_eq!(app.session.active().unwrap().history.past_len(), past, "pin edits stay in the open session"); + + let original = app.session.active().unwrap().doc.clone(); + commit(&mut app); + assert_eq!(app.session.active().unwrap().history.past_len(), past + 1); + let committed = app.session.active().unwrap().doc.clone(); + assert_ne!(committed, original); + app.session.execute("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc, original); + app.session.execute("edit.redo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc, committed); + } +} + +#[test] +fn deleting_during_a_drag_settles_history_and_cannot_move_the_next_pin() { + let ctx = egui::Context::default(); + let mut app = puppet_app(&ctx); + gesture(&mut app, [25.0, 40.0], [25.0, 40.0]); + gesture(&mut app, [75.0, 40.0], [75.0, 40.0]); + let original = app.distort.puppet.as_ref().unwrap().warp.pins.clone(); + pointer(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE); + pointer(&mut app, ToolEvent::Move { x: 25.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); + let moved = app.distort.puppet.as_ref().unwrap().warp.pins.clone(); + press(&mut app, &ctx, egui::Key::Delete, egui::Modifiers::NONE); + pointer(&mut app, ToolEvent::Move { x: 5.0, y: 5.0, pressure: 1.0 }, egui::Modifiers::NONE); + pointer(&mut app, ToolEvent::Up { x: 5.0, y: 5.0 }, egui::Modifiers::NONE); + let s = app.distort.puppet.as_mut().unwrap(); + assert_eq!(s.warp.pins, original[1..]); + assert!(s.drag.is_none() && s.drag_from.is_none()); + assert!(s.undo()); + assert_eq!(s.warp.pins, moved, "first undo restores the deleted pin at its moved position"); + assert!(s.undo()); + assert_eq!(s.warp.pins, original, "second undo reverts the preceding drag"); + assert!(s.redo()); + s.selected = Some(0); + control(&mut app, &json!({"deleteSelectedPin": true})).unwrap(); + assert!(!app.distort.puppet.as_mut().unwrap().redo(), "a new deletion discards the redo branch"); +} + +#[test] +fn deleting_last_pin_restores_rest_mesh_and_empty_commit_is_not_an_edit() { + let ctx = egui::Context::default(); + let mut app = puppet_app(&ctx); + gesture(&mut app, [25.0, 40.0], [25.0, 20.0]); + let past = app.session.active().unwrap().history.past_len(); + let s = app.distort.puppet.as_mut().unwrap(); + let pins = s.warp.pins.clone(); + s.selected = Some(usize::MAX); + press(&mut app, &ctx, egui::Key::Delete, egui::Modifiers::NONE); + assert_eq!(app.distort.puppet.as_ref().unwrap().warp.pins, pins, "stale selection is harmless"); + app.distort.puppet.as_mut().unwrap().selected = Some(0); + press(&mut app, &ctx, egui::Key::Backspace, egui::Modifiers::NONE); + let s = app.distort.puppet.as_ref().unwrap(); + assert!(s.warp.pins.is_empty()); + assert_eq!(s.deformed.len(), s.mesh.verts.len()); + for (deformed, rest) in s.deformed.iter().zip(&s.mesh.verts) { + assert!(dist(*deformed, *rest) < 1e-8, "no constraints: the mesh returns to rest"); + } + commit(&mut app); + assert!(app.distort.puppet.is_none()); + assert_eq!(app.session.active().unwrap().history.past_len(), past); +} + +#[test] +fn delete_keys_in_a_text_field_do_not_remove_pins() { + for key in [egui::Key::Delete, egui::Key::Backspace] { + let ctx = egui::Context::default(); + let mut app = puppet_app(&ctx); + gesture(&mut app, [25.0, 40.0], [25.0, 20.0]); + let mut text = "123".to_string(); + ctx.run_ui(Default::default(), |ui| { + ui.text_edit_singleline(&mut text).request_focus(); + }) + .textures_delta + .clear(); + let pins = app.distort.puppet.as_ref().unwrap().warp.pins.clone(); + let input = egui::RawInput { + events: vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ..Default::default() + }; + ctx.run_ui(input, |ui| { + assert!(ui.ctx().text_edit_focused()); + crate::shortcuts::handle(&mut app, ui.ctx()); + ui.text_edit_singleline(&mut text); + }) + .textures_delta + .clear(); + assert_eq!(app.distort.puppet.as_ref().unwrap().warp.pins, pins); + assert_eq!(app.distort.puppet.as_ref().unwrap().undo.len(), 1); + } +} + +fn long_puppet(ctx: &egui::Context, mode: PuppetMode, density: PuppetDensity) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 1000, "height": 300, "depth": 8})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(40, 180, 960, 220), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.sync_views(); + begin(&mut app, ctx, "edit.puppetWarp").unwrap(); + for x in [70.0, 160.0, 930.0] { + pointer(&mut app, ToolEvent::Down { x, y: 200.0, pressure: 1.0 }, egui::Modifiers::NONE); + pointer(&mut app, ToolEvent::Up { x, y: 200.0 }, egui::Modifiers::NONE); + } + let s = app.distort.puppet.as_mut().unwrap(); + s.warp.mode = mode; + s.warp.density = density; + s.rebuild_mesh(); + app +} + +fn assert_same_mesh(a: &[[f64; 2]], b: &[[f64; 2]]) { + assert_eq!(a.len(), b.len()); + let offset = a.iter().zip(b).map(|(a, b)| dist(*a, *b)).fold(0.0, f64::max); + assert!(offset < 1e-8, "mesh moved by {offset} px with unchanged pins"); +} + +#[test] +fn drag_preview_matches_release_history_and_committed_geometry() { + use photocraft_algo::puppet::{deform, render}; + for mode in [PuppetMode::Rigid, PuppetMode::Normal, PuppetMode::Distort] { + for density in [PuppetDensity::Fewer, PuppetDensity::Normal, PuppetDensity::More] { + let ctx = egui::Context::default(); + let mut app = long_puppet(&ctx, mode, density); + let rest = app.distort.puppet.as_ref().unwrap().deformed.clone(); + let past = app.session.active().unwrap().history.past_len(); + pointer(&mut app, ToolEvent::Down { x: 930.0, y: 200.0, pressure: 1.0 }, egui::Modifiers::NONE); + for step in 1..=12 { + let x = 930.0 - f64::from(step) * 20.0; + let y = 200.0 - f64::from(step) * 10.0; + pointer(&mut app, ToolEvent::Move { x, y, pressure: 1.0 }, egui::Modifiers::NONE); + } + let s = app.distort.puppet.as_ref().unwrap(); + let preview = s.deformed.clone(); + let order = s.order.clone(); + pointer(&mut app, ToolEvent::Up { x: 690.0, y: 80.0 }, egui::Modifiers::NONE); + let s = app.distort.puppet.as_mut().unwrap(); + assert_same_mesh(&preview, &s.deformed); + assert_eq!(order, s.order); + let (_, canonical, _) = deform(&s.surface, s.bounds, &s.warp, ITERATIONS); + assert_same_mesh(&preview, &canonical); + assert!(s.undo()); + assert_same_mesh(&rest, &s.deformed); + assert!(s.redo()); + assert_same_mesh(&preview, &s.deformed); + // Use the engine's interpolation to isolate geometry from GPU texture sampling. + let expected = render(&s.surface, s.bounds, &s.mesh, &preview, &order, photocraft_algo::transform::Interp::Bicubic); + let layer = s.layer; + assert_eq!(app.session.active().unwrap().history.past_len(), past); + commit(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), past + 1); + assert_eq!(st.doc.layer(layer).unwrap().surface().unwrap(), &expected); + } + } +} + +#[test] +fn drag_preview_is_independent_of_pointer_path_and_honors_release_coordinates() { + let ctx = egui::Context::default(); + let mut app = long_puppet(&ctx, PuppetMode::Normal, PuppetDensity::More); + let s = app.distort.puppet.as_mut().unwrap(); + s.warp.pins[0].rotate = Some(25.0); + s.rebind(); + let pins = s.warp.pins.clone(); + let paths = [ + vec![[690.0, 80.0]], + vec![[870.0, 170.0], [810.0, 140.0], [750.0, 110.0], [690.0, 80.0]], + vec![[500.0, 30.0], [930.0, 200.0], [1000.0, 270.0], [690.0, 80.0]], + ]; + let mut expected = None; + for path in paths { + app.distort.puppet.as_mut().unwrap().restore(pins.clone()); + pointer(&mut app, ToolEvent::Down { x: 930.0, y: 200.0, pressure: 1.0 }, egui::Modifiers::NONE); + for [x, y] in path { + pointer(&mut app, ToolEvent::Move { x, y, pressure: 1.0 }, egui::Modifiers::NONE); + } + let preview = &app.distort.puppet.as_ref().unwrap().deformed; + assert_same_mesh(expected.get_or_insert_with(|| preview.clone()), preview); + // The last pointer-up may carry a new position without a preceding move event. + pointer(&mut app, ToolEvent::Up { x: 720.0, y: 90.0 }, egui::Modifiers::NONE); + let s = app.distort.puppet.as_ref().unwrap(); + assert_eq!(s.warp.pins[2].dst, [720.0, 90.0]); + let (_, canonical, _) = photocraft_algo::puppet::deform(&s.surface, s.bounds, &s.warp, ITERATIONS); + assert_same_mesh(&s.deformed, &canonical); + } +} + +/// #5092: a Puppet Warp session left open does not follow the user to a new document. +#[test] +fn session_is_dropped_when_another_document_becomes_active() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(20, 30, 80, 50), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.sync_views(); + crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); + crate::distort_ui::drop_foreign(&mut app); + assert!(app.distort.puppet.is_some()); + app.session.execute("file.new", json!({"width": 32, "height": 32, "depth": 8})).unwrap(); + let active = app.session.active_index().unwrap(); + // The session stays until drop_foreign; the preview must not follow this document (#5115). + assert!(app.distort.puppet.is_some()); + assert!(crate::distort_ui::display_doc(&app, active).is_none()); + crate::distort_ui::drop_foreign(&mut app); + assert!(app.distort.puppet.is_none()); + assert!(crate::distort_ui::display_doc(&app, active).is_none()); + // Closing the document it was started on drops it too. + assert!(app.session.set_active(0)); + crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); + crate::distort_ui::drop_foreign(&mut app); + assert!(app.distort.puppet.is_some()); + assert!(app.session.close(0).is_some()); + crate::distort_ui::drop_foreign(&mut app); + assert!(app.distort.puppet.is_none()); +} + +/// #4440: ⌘Z / ⌘⇧Z undo and redo pin edits while Puppet Warp is open: placing a pin, +/// dragging one and removing one are a step each; a click that moves nothing isn't one. +#[test] +fn pin_edits_undo_and_redo_inside_the_session() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(20, 30, 80, 50), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.sync_views(); + crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); + let ev = |app: &mut PhotocraftApp, e| crate::distort_ui::pointer(app, e, egui::Modifiers::NONE); + let pins = |app: &PhotocraftApp| app.distort.puppet.as_ref().unwrap().warp.pins.iter().map(|p| p.dst).collect::>(); + ev(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Up { x: 25.0, y: 40.0 }); + ev(&mut app, ToolEvent::Down { x: 75.0, y: 40.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Up { x: 75.0, y: 40.0 }); + // Drag the second pin up; then a click on it that moves nothing. + ev(&mut app, ToolEvent::Down { x: 75.0, y: 40.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 75.0, y: 30.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Up { x: 75.0, y: 20.0 }); + ev(&mut app, ToolEvent::Down { x: 75.0, y: 20.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Up { x: 75.0, y: 20.0 }); + crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }, egui::Modifiers { alt: true, ..Default::default() }); + assert_eq!(pins(&app), [[75.0, 20.0]]); + // ⌘Z, through the keyboard: the removed pin comes back, then the drag is undone. + let press = |app: &mut PhotocraftApp, modifiers: egui::Modifiers| { + let ev = egui::Event::Key { key: egui::Key::Z, physical_key: None, pressed: true, repeat: false, modifiers }; + let input = egui::RawInput { events: vec![ev], ..Default::default() }; + ctx.run_ui(input, |ui| assert!(crate::distort_ui::keys(app, ui.ctx()))).textures_delta.clear(); + }; + press(&mut app, egui::Modifiers::COMMAND); + assert_eq!(pins(&app), [[25.0, 40.0], [75.0, 20.0]]); + press(&mut app, egui::Modifiers::COMMAND); + assert_eq!(pins(&app), [[25.0, 40.0], [75.0, 40.0]], "the drag, not the click after it"); + // ⌘⇧Z redoes it; a new edit after an undo drops what was undone. + press(&mut app, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT); + assert_eq!(pins(&app), [[25.0, 40.0], [75.0, 20.0]]); + control(&mut app, &json!({"undo": true})).unwrap(); + control(&mut app, &json!({"undo": true})).unwrap(); + assert_eq!(pins(&app), [[25.0, 40.0]]); + ev(&mut app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Up { x: 50.0, y: 40.0 }); + control(&mut app, &json!({"redo": true})).unwrap(); + assert_eq!(pins(&app), [[25.0, 40.0], [50.0, 40.0]], "nothing left to redo"); + // Undo past the first pin stops there, and the document's History is untouched. + let past = app.session.active().unwrap().history.past_len(); + for _ in 0..5 { + control(&mut app, &json!({"undo": true})).unwrap(); + } + assert!(pins(&app).is_empty()); + assert_eq!(app.session.active().unwrap().history.past_len(), past); +} + +#[test] +fn pins_drag_and_commit_through_the_engine() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(20, 30, 80, 50), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.sync_views(); + crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); + let ev = |app: &mut PhotocraftApp, e| crate::distort_ui::pointer(app, e, egui::Modifiers::NONE); + // Two pins: hold the left end, drag the right end up. + ev(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Up { x: 25.0, y: 40.0 }); + ev(&mut app, ToolEvent::Down { x: 75.0, y: 40.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 75.0, y: 30.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Up { x: 75.0, y: 20.0 }); + let s = app.distort.puppet.as_ref().unwrap(); + assert_eq!(s.warp.pins.len(), 2); + assert_eq!(s.warp.pins[1].dst, [75.0, 20.0]); + // ⌥-click removes; clicking off the mesh adds nothing. + ev(&mut app, ToolEvent::Down { x: 5.0, y: 5.0, pressure: 1.0 }); + assert_eq!(app.distort.puppet.as_ref().unwrap().warp.pins.len(), 2); + crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }, egui::Modifiers { alt: true, ..Default::default() }); + assert_eq!(app.distort.puppet.as_ref().unwrap().warp.pins.len(), 1); + ev(&mut app, ToolEvent::Down { x: 25.0, y: 40.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Up { x: 25.0, y: 40.0 }); + control(&mut app, &json!({"mode": "rigid", "density": "more"})).unwrap(); + let expected = app.distort.puppet.as_ref().unwrap().deformed.clone(); + assert!(!expected.is_empty()); + let before = app.session.active().unwrap().history.past_len(); + crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert!(app.distort.puppet.is_none()); + assert_eq!(app.session.active().unwrap().history.past_len(), before + 1); + let st = app.session.active().unwrap(); + let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); + assert!(b.y0 < 25, "the right end went up: {b:?}"); +} + +#[test] +fn an_expansion_that_empties_the_mesh_is_refused() { + // #951: remeshing to no vertices rebound the pins to a vertex that doesn't exist and + // panicked. -50 is the options bar's minimum and also empties this 20 px tall bar. + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(20, 30, 80, 50), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.sync_views(); + crate::distort_ui::menu(&mut app, &ctx, "edit.puppetWarp", &json!({})).unwrap().unwrap(); + crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE); + crate::distort_ui::pointer(&mut app, ToolEvent::Up { x: 50.0, y: 40.0 }, egui::Modifiers::NONE); + let before = app.distort.puppet.as_ref().unwrap().describe(); + for e in [-200, -50] { + assert!(control(&mut app, &json!({"expansion": e})).is_err(), "{e}"); + assert_eq!(app.distort.puppet.as_ref().unwrap().describe(), before, "{e}: the previous settings and mesh stay"); + } + // A smaller shrink still remeshes. + let v = control(&mut app, &json!({"expansion": -2})).unwrap(); + assert_eq!(v["expansion"], -2.0); + assert!(v["triangles"].as_u64().unwrap() > 0); +} From 7d64a30876c2a164d29fade59721d95f4a70d520 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:01 +0000 Subject: [PATCH 077/259] refactor(ui-egui): move brush_sections.rs tests to brush_sections/tests.rs --- crates/ui-egui/src/brush_sections.rs | 340 +-------------------- crates/ui-egui/src/brush_sections/tests.rs | 337 ++++++++++++++++++++ 2 files changed, 338 insertions(+), 339 deletions(-) create mode 100644 crates/ui-egui/src/brush_sections/tests.rs diff --git a/crates/ui-egui/src/brush_sections.rs b/crates/ui-egui/src/brush_sections.rs index d75a4daad1..da96b7474a 100644 --- a/crates/ui-egui/src/brush_sections.rs +++ b/crates/ui-egui/src/brush_sections.rs @@ -643,342 +643,4 @@ pub fn section_body(ui: &mut egui::Ui, b: &mut BrushSettings, i: usize, presets: } #[cfg(test)] -mod tests { - use super::*; - use egui::accesskit::Role; - use egui_kittest::{ - Harness, - kittest::{NodeT, Queryable}, - }; - - /// The slider row's visible caption, not the field or slider it names. - fn caption_rect(h: &Harness<'_, T>, text: &str) -> egui::Rect { - h.query_all(egui_kittest::kittest::by().label(text).include_labels()) - .find(|n| n.accesskit_node().role() == Role::Label) - .unwrap_or_else(|| panic!("the `{text}` caption")) - .rect() - } - - fn minimum_brush() -> BrushSettings { - let mut b = BrushSettings::default(); - b.shape_dynamics.size.minimum = 0.2; - b.shape_dynamics.roundness.minimum = 0.35; - b.transfer.opacity.minimum = 0.4; - b.transfer.flow.minimum = 0.55; - b.transfer.wetness.minimum = 0.6; - b.transfer.mix.minimum = 0.75; - b - } - - fn section_harness(section: usize, b: BrushSettings) -> Harness<'static, BrushSettings> { - let mut ready = false; - let mut h = Harness::builder().with_size(vec2(340.0, 1100.0)).build_ui_state( - move |ui, b: &mut BrushSettings| { - if !ready { - crate::PhotocraftApp::setup_context(ui.ctx(), theme::ThemeKind::ProMedium); - ready = true; - return; - } - section_body(ui, b, section, &[], None, Tool::MixerBrush); - }, - b, - ); - h.run_steps(3); - h - } - - #[test] - fn pose_axes_controls_are_independent_and_below_each_tilt_in_all_themes() { - use egui::accesskit::Toggled; - for kind in theme::ThemeKind::ALL { - let b: BrushSettings = serde_json::from_value(serde_json::json!({"pose": { - "enabled": true, "tiltX": 45.0, "tiltY": -18.0, - "overrideTiltX": true, "overrideTiltY": false, - "pressure": 0.71, "rotation": 67.0 - }})) - .unwrap(); - let mut h = section_harness(7, b.clone()); - crate::PhotocraftApp::setup_context(&h.ctx, kind); - h.run_steps(3); - let x = h.get_by_role_and_label(Role::CheckBox, "Override Tilt X"); - let y = h.get_by_role_and_label(Role::CheckBox, "Override Tilt Y"); - assert_eq!(x.accesskit_node().toggled(), Some(Toggled::True)); - assert_eq!(y.accesskit_node().toggled(), Some(Toggled::False)); - assert!(caption_rect(&h, "Tilt X").bottom() < x.rect().top() && x.rect().bottom() < caption_rect(&h, "Tilt Y").top()); - assert!(caption_rect(&h, "Tilt Y").bottom() < y.rect().top() && y.rect().bottom() < caption_rect(&h, "Rotation").top()); - assert_eq!(h.state(), &b, "drawing preserves pose degrees and flags"); - y.focus(); - h.run_steps(1); - h.key_press(egui::Key::Space); - h.run_steps(2); - let wire = serde_json::to_value(h.state()).unwrap(); - assert_eq!(wire["pose"]["overrideTiltX"], true); - assert_eq!(wire["pose"]["overrideTiltY"], true); - let mut expected = serde_json::to_value(b).unwrap(); - expected["pose"]["overrideTiltY"] = serde_json::json!(true); - expected["pose"]["overrideTilt"] = serde_json::json!(true); - assert_eq!(wire, expected, "Space changes only Y, plus the derived legacy readback"); - } - } - - /// #3825: jitter is an amount, not a hue selector; it uses the themed amount track. - #[test] - fn hue_jitter_paints_an_amount_track_in_every_theme() { - for kind in theme::ThemeKind::ALL { - let mut b = BrushSettings::default(); - b.color_dynamics.hue_jitter = 0.37; - let mut h = section_harness(5, b.clone()); - crate::PhotocraftApp::setup_context(&h.ctx, kind); - h.run_steps(3); - let label = caption_rect(&h, "Hue Jitter"); - let t = Tokens::get(&h.ctx); - assert!( - h.output().shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Rect(r) - if r.rect.width() > 150.0 && (r.rect.height() - 3.0).abs() < 0.1 - && r.rect.top() > label.bottom() && r.rect.bottom() < label.bottom() + 30.0 - && r.fill == t.field_border)), - "{kind:?}: Hue Jitter paints the same neutral track as other percentage amounts" - ); - assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.accesskit_node().numeric_value() == Some(37.0))); - assert_eq!(h.state(), &b, "rendering does not change saved brush settings"); - } - } - - struct TransferState { - brush: BrushSettings, - tool: Tool, - } - - fn transfer_mixer_brush() -> BrushSettings { - let mut b = BrushSettings::default(); - b.transfer.enabled = true; - for (dynamic, jitter, minimum, fade_steps) in [ - (&mut b.transfer.opacity, 0.13, 0.17, 119), - (&mut b.transfer.flow, 0.27, 0.29, 229), - (&mut b.transfer.wetness, 0.41, 0.43, 339), - (&mut b.transfer.mix, 0.63, 0.67, 449), - ] { - *dynamic = Dynamic { control: Control::Fade, jitter, minimum, fade_steps, ..Default::default() }; - } - b - } - - fn transfer_mixer_harness(kind: theme::ThemeKind, tool: Tool) -> Harness<'static, TransferState> { - let mut ready = false; - let mut h = Harness::builder().with_size(vec2(340.0, 1400.0)).build_ui_state( - move |ui, state: &mut TransferState| { - if !ready { - crate::PhotocraftApp::setup_context(ui.ctx(), kind); - ready = true; - return; - } - ui.add_enabled_ui(state.brush.transfer.enabled, |ui| section_body(ui, &mut state.brush, 6, &[], None, state.tool)); - }, - TransferState { brush: transfer_mixer_brush(), tool }, - ); - h.run_steps(3); - h - } - - /// #3825: Mixer-only blocks follow the tool, including sliders, minimums and Fade steps. - #[test] - fn transfer_mixer_controls_follow_the_tool_and_section_in_every_theme() { - for kind in theme::ThemeKind::ALL { - let mut h = transfer_mixer_harness(kind, Tool::Brush); - let before = h.state().brush.clone(); - for tool in Tool::ALL { - h.state_mut().tool = tool; - h.run_steps(2); - for (mixer_only, values) in [(false, [13.0, 17.0, 119.0, 27.0, 29.0, 229.0]), (true, [41.0, 43.0, 339.0, 63.0, 67.0, 449.0])] { - for value in values { - let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(value)).unwrap(); - assert_eq!(field.accesskit_node().is_disabled(), mixer_only && tool != Tool::MixerBrush, "{kind:?}, {tool:?}, {value}"); - } - } - for (index, node) in h.query_all_by_role(Role::ComboBox).enumerate() { - assert_eq!(node.accesskit_node().is_disabled(), index >= 2 && tool != Tool::MixerBrush, "{kind:?}, {tool:?}: controller {index}"); - } - assert_eq!(h.state().brush, before, "changing tool context only changes availability"); - } - h.state_mut().tool = Tool::MixerBrush; - h.state_mut().brush.transfer.enabled = false; - h.run_steps(2); - assert!(h.query_all_by_role(Role::SpinButton).all(|node| node.accesskit_node().is_disabled()), "section Off still disables every field"); - assert!(h.query_all_by_role(Role::ComboBox).all(|node| node.accesskit_node().is_disabled())); - h.state_mut().brush.transfer.enabled = true; - h.state_mut().brush.transfer.wetness.control = Control::Off; - h.run_steps(2); - let minimum = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(43.0)).unwrap(); - assert!(minimum.accesskit_node().is_disabled(), "Control Off still disables the applicable minimum"); - } - } - - #[test] - fn transfer_mixer_controls_ignore_disabled_edits_and_keep_values_on_reactivation() { - let mut h = transfer_mixer_harness(theme::ThemeKind::ProMedium, Tool::Brush); - let before = h.state().brush.clone(); - for value in [41.0, 43.0, 339.0, 63.0, 67.0, 449.0] { - let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(value)).unwrap(); - let at = field.rect().center(); - 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); - h.hover_at(at); - h.drag_at(at); - h.run_steps(1); - h.drop_at(at + vec2(60.0, 0.0)); - h.run_steps(2); - assert_eq!(h.state().brush, before, "inactive field {value} ignores keyboard and pointer input"); - } - for label in ["Wetness Jitter", "Mix Jitter"] { - let row = caption_rect(&h, label); - let from = pos2(row.left() + 120.0, row.bottom() + 16.0); - h.hover_at(from); - h.drag_at(from); - h.run_steps(1); - h.hover_at(from + vec2(150.0, 0.0)); - h.run_steps(1); - h.drop_at(from + vec2(150.0, 0.0)); - h.run_steps(2); - assert_eq!(h.state().brush, before, "the inactive {label} track ignores a drag"); - } - h.state_mut().tool = Tool::MixerBrush; - h.run_steps(2); - let row = caption_rect(&h, "Wetness Jitter"); - let from = pos2(row.left() + 120.0, row.bottom() + 16.0); - h.hover_at(from); - h.drag_at(from); - h.run_steps(1); - h.hover_at(from + vec2(150.0, 0.0)); - h.run_steps(1); - h.drop_at(from + vec2(150.0, 0.0)); - h.run_steps(2); - assert!(h.state().brush.transfer.wetness.jitter > 0.6, "the same track accepts a drag when applicable"); - h.state_mut().brush.transfer.wetness.jitter = 0.41; - h.run_steps(2); - let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(41.0)).unwrap(); - field.click(); - h.key_press(egui::Key::ArrowUp); - h.run_steps(2); - assert!((h.state().brush.transfer.wetness.jitter - 0.42).abs() < 1e-6); - let after = h.state().brush.clone(); - h.state_mut().tool = Tool::Brush; - h.run_steps(2); - h.state_mut().tool = Tool::MixerBrush; - h.run_steps(2); - assert_eq!(h.state().brush, after); - assert!(h.query_all_by_role(Role::SpinButton).any(|node| node.accesskit_node().numeric_value() == Some(42.0) && !node.accesskit_node().is_disabled())); - } - - fn set_controls(b: &mut BrushSettings, control: Control) { - for d in [ - &mut b.shape_dynamics.size, - &mut b.shape_dynamics.roundness, - &mut b.transfer.opacity, - &mut b.transfer.flow, - &mut b.transfer.wetness, - &mut b.transfer.mix, - ] { - d.control = control; - } - } - - /// #3825: all six minimum fields follow their own Control; jitter remains editable. - #[test] - fn minimum_fields_are_disabled_only_when_their_control_is_off() { - for (section, values) in [(1, vec![20.0, 35.0]), (6, vec![40.0, 55.0, 60.0, 75.0])] { - let mut h = section_harness(section, minimum_brush()); - for (control, _) in CONTROLS { - set_controls(h.state_mut(), control); - h.run_steps(2); - for value in &values { - let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().numeric_value() == Some(*value)).expect("minimum input"); - assert_eq!(field.accesskit_node().is_disabled(), control == Control::Off, "section {section}, minimum {value}, {control:?}"); - } - assert!( - h.query_all_by_role(Role::SpinButton).any(|n| n.accesskit_node().numeric_value() == Some(0.0) && !n.accesskit_node().is_disabled()), - "jitter stays editable" - ); - } - set_controls(h.state_mut(), Control::PenPressure); - if section == 1 { - h.state_mut().shape_dynamics.size.control = Control::Off; - } else { - h.state_mut().transfer.opacity.control = Control::Off; - } - h.run_steps(2); - for (index, value) in values.iter().enumerate() { - let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().numeric_value() == Some(*value)).unwrap(); - assert_eq!(field.accesskit_node().is_disabled(), index == 0, "each minimum follows its own control"); - } - } - } - - fn drag(h: &mut Harness<'static, BrushSettings>, 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(to)); - h.run_steps(1); - h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); - h.run_steps(2); - } - - #[test] - fn disabled_minimum_ignores_input_and_keeps_its_value_for_reactivation() { - let mut h = section_harness(1, minimum_brush()); - let before = h.state().clone(); - let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().numeric_value() == Some(20.0)).unwrap(); - let center = field.rect().center(); - field.click(); - h.key_press(egui::Key::ArrowUp); - h.event(egui::Event::Text("99".into())); - h.key_press(egui::Key::Enter); - // The slider below the number and its scrubby label are disabled too. - let track = pos2(300.0, center.y + 24.0); - drag(&mut h, track, track); - let label = caption_rect(&h, "Minimum Diameter").center(); - drag(&mut h, label, label + vec2(60.0, 0.0)); - assert_eq!(h.state(), &before, "disabled interactions never rewrite brush settings"); - - h.state_mut().shape_dynamics.size.control = Control::PenPressure; - h.run_steps(2); - let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().numeric_value() == Some(20.0)).unwrap(); - assert!(!field.accesskit_node().is_disabled()); - field.click(); - h.key_press(egui::Key::ArrowUp); - h.run_steps(2); - assert_eq!(h.state().shape_dynamics.size.minimum, 0.21, "active minimum is editable"); - drag(&mut h, track, track); - let minimum = h.state().shape_dynamics.size.minimum; - assert!(minimum > 0.8, "the active slider accepts the same pointer position: {minimum}"); - h.state_mut().shape_dynamics.size.control = Control::Off; - h.run_steps(2); - assert_eq!(h.state().shape_dynamics.size.minimum, minimum, "Off keeps the saved minimum"); - } - - #[test] - fn ellipse_widget_drags_angle_and_roundness() { - // Pointing straight up is 90° (counter-clockwise from +x; screen y is down). - assert_eq!(ellipse_drag(EllipseGrab::Angle, vec2(0.0, -20.0), 0.0, 1.0), (90.0, 1.0)); - assert_eq!(ellipse_drag(EllipseGrab::Angle, vec2(-20.0, 0.0), 0.0, 1.0).0.abs(), 180.0); - // The centre itself doesn't change the angle. - assert_eq!(ellipse_drag(EllipseGrab::Angle, vec2(0.2, 0.1), 30.0, 0.5), (30.0, 0.5)); - // At angle 0 the minor axis is vertical: half the radius up is 50 % roundness. - let (_, r) = ellipse_drag(EllipseGrab::Roundness, vec2(0.0, -ELLIPSE_R / 2.0), 0.0, 1.0); - assert!((r - 0.5).abs() < 1e-4); - // Handles sit on the minor axis and are what a press there grabs. - let [h, _] = roundness_handles(0.0, 0.5); - assert!((h - vec2(0.0, -ELLIPSE_R / 2.0)).length() < 1e-4); - assert_eq!(ellipse_grab(h, 0.0, 0.5), EllipseGrab::Roundness); - assert_eq!(ellipse_grab(vec2(ELLIPSE_R, 0.0), 0.0, 0.5), EllipseGrab::Angle); - // Rotated 90°: the minor axis is horizontal. - let [h, _] = roundness_handles(90.0, 1.0); - assert!((h.x.abs() - ELLIPSE_R).abs() < 1e-3 && h.y.abs() < 1e-3, "{h:?}"); - let (_, r) = ellipse_drag(EllipseGrab::Roundness, vec2(500.0, 0.0), 90.0, 0.2); - assert_eq!(r, 1.0); - } -} +mod tests; diff --git a/crates/ui-egui/src/brush_sections/tests.rs b/crates/ui-egui/src/brush_sections/tests.rs new file mode 100644 index 0000000000..b9a221f04e --- /dev/null +++ b/crates/ui-egui/src/brush_sections/tests.rs @@ -0,0 +1,337 @@ +use super::*; +use egui::accesskit::Role; +use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, +}; + +/// The slider row's visible caption, not the field or slider it names. +fn caption_rect(h: &Harness<'_, T>, text: &str) -> egui::Rect { + h.query_all(egui_kittest::kittest::by().label(text).include_labels()) + .find(|n| n.accesskit_node().role() == Role::Label) + .unwrap_or_else(|| panic!("the `{text}` caption")) + .rect() +} + +fn minimum_brush() -> BrushSettings { + let mut b = BrushSettings::default(); + b.shape_dynamics.size.minimum = 0.2; + b.shape_dynamics.roundness.minimum = 0.35; + b.transfer.opacity.minimum = 0.4; + b.transfer.flow.minimum = 0.55; + b.transfer.wetness.minimum = 0.6; + b.transfer.mix.minimum = 0.75; + b +} + +fn section_harness(section: usize, b: BrushSettings) -> Harness<'static, BrushSettings> { + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(340.0, 1100.0)).build_ui_state( + move |ui, b: &mut BrushSettings| { + if !ready { + crate::PhotocraftApp::setup_context(ui.ctx(), theme::ThemeKind::ProMedium); + ready = true; + return; + } + section_body(ui, b, section, &[], None, Tool::MixerBrush); + }, + b, + ); + h.run_steps(3); + h +} + +#[test] +fn pose_axes_controls_are_independent_and_below_each_tilt_in_all_themes() { + use egui::accesskit::Toggled; + for kind in theme::ThemeKind::ALL { + let b: BrushSettings = serde_json::from_value(serde_json::json!({"pose": { + "enabled": true, "tiltX": 45.0, "tiltY": -18.0, + "overrideTiltX": true, "overrideTiltY": false, + "pressure": 0.71, "rotation": 67.0 + }})) + .unwrap(); + let mut h = section_harness(7, b.clone()); + crate::PhotocraftApp::setup_context(&h.ctx, kind); + h.run_steps(3); + let x = h.get_by_role_and_label(Role::CheckBox, "Override Tilt X"); + let y = h.get_by_role_and_label(Role::CheckBox, "Override Tilt Y"); + assert_eq!(x.accesskit_node().toggled(), Some(Toggled::True)); + assert_eq!(y.accesskit_node().toggled(), Some(Toggled::False)); + assert!(caption_rect(&h, "Tilt X").bottom() < x.rect().top() && x.rect().bottom() < caption_rect(&h, "Tilt Y").top()); + assert!(caption_rect(&h, "Tilt Y").bottom() < y.rect().top() && y.rect().bottom() < caption_rect(&h, "Rotation").top()); + assert_eq!(h.state(), &b, "drawing preserves pose degrees and flags"); + y.focus(); + h.run_steps(1); + h.key_press(egui::Key::Space); + h.run_steps(2); + let wire = serde_json::to_value(h.state()).unwrap(); + assert_eq!(wire["pose"]["overrideTiltX"], true); + assert_eq!(wire["pose"]["overrideTiltY"], true); + let mut expected = serde_json::to_value(b).unwrap(); + expected["pose"]["overrideTiltY"] = serde_json::json!(true); + expected["pose"]["overrideTilt"] = serde_json::json!(true); + assert_eq!(wire, expected, "Space changes only Y, plus the derived legacy readback"); + } +} + +/// #3825: jitter is an amount, not a hue selector; it uses the themed amount track. +#[test] +fn hue_jitter_paints_an_amount_track_in_every_theme() { + for kind in theme::ThemeKind::ALL { + let mut b = BrushSettings::default(); + b.color_dynamics.hue_jitter = 0.37; + let mut h = section_harness(5, b.clone()); + crate::PhotocraftApp::setup_context(&h.ctx, kind); + h.run_steps(3); + let label = caption_rect(&h, "Hue Jitter"); + let t = Tokens::get(&h.ctx); + assert!( + h.output().shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Rect(r) + if r.rect.width() > 150.0 && (r.rect.height() - 3.0).abs() < 0.1 + && r.rect.top() > label.bottom() && r.rect.bottom() < label.bottom() + 30.0 + && r.fill == t.field_border)), + "{kind:?}: Hue Jitter paints the same neutral track as other percentage amounts" + ); + assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.accesskit_node().numeric_value() == Some(37.0))); + assert_eq!(h.state(), &b, "rendering does not change saved brush settings"); + } +} + +struct TransferState { + brush: BrushSettings, + tool: Tool, +} + +fn transfer_mixer_brush() -> BrushSettings { + let mut b = BrushSettings::default(); + b.transfer.enabled = true; + for (dynamic, jitter, minimum, fade_steps) in [ + (&mut b.transfer.opacity, 0.13, 0.17, 119), + (&mut b.transfer.flow, 0.27, 0.29, 229), + (&mut b.transfer.wetness, 0.41, 0.43, 339), + (&mut b.transfer.mix, 0.63, 0.67, 449), + ] { + *dynamic = Dynamic { control: Control::Fade, jitter, minimum, fade_steps, ..Default::default() }; + } + b +} + +fn transfer_mixer_harness(kind: theme::ThemeKind, tool: Tool) -> Harness<'static, TransferState> { + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(340.0, 1400.0)).build_ui_state( + move |ui, state: &mut TransferState| { + if !ready { + crate::PhotocraftApp::setup_context(ui.ctx(), kind); + ready = true; + return; + } + ui.add_enabled_ui(state.brush.transfer.enabled, |ui| section_body(ui, &mut state.brush, 6, &[], None, state.tool)); + }, + TransferState { brush: transfer_mixer_brush(), tool }, + ); + h.run_steps(3); + h +} + +/// #3825: Mixer-only blocks follow the tool, including sliders, minimums and Fade steps. +#[test] +fn transfer_mixer_controls_follow_the_tool_and_section_in_every_theme() { + for kind in theme::ThemeKind::ALL { + let mut h = transfer_mixer_harness(kind, Tool::Brush); + let before = h.state().brush.clone(); + for tool in Tool::ALL { + h.state_mut().tool = tool; + h.run_steps(2); + for (mixer_only, values) in [(false, [13.0, 17.0, 119.0, 27.0, 29.0, 229.0]), (true, [41.0, 43.0, 339.0, 63.0, 67.0, 449.0])] { + for value in values { + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(value)).unwrap(); + assert_eq!(field.accesskit_node().is_disabled(), mixer_only && tool != Tool::MixerBrush, "{kind:?}, {tool:?}, {value}"); + } + } + for (index, node) in h.query_all_by_role(Role::ComboBox).enumerate() { + assert_eq!(node.accesskit_node().is_disabled(), index >= 2 && tool != Tool::MixerBrush, "{kind:?}, {tool:?}: controller {index}"); + } + assert_eq!(h.state().brush, before, "changing tool context only changes availability"); + } + h.state_mut().tool = Tool::MixerBrush; + h.state_mut().brush.transfer.enabled = false; + h.run_steps(2); + assert!(h.query_all_by_role(Role::SpinButton).all(|node| node.accesskit_node().is_disabled()), "section Off still disables every field"); + assert!(h.query_all_by_role(Role::ComboBox).all(|node| node.accesskit_node().is_disabled())); + h.state_mut().brush.transfer.enabled = true; + h.state_mut().brush.transfer.wetness.control = Control::Off; + h.run_steps(2); + let minimum = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(43.0)).unwrap(); + assert!(minimum.accesskit_node().is_disabled(), "Control Off still disables the applicable minimum"); + } +} + +#[test] +fn transfer_mixer_controls_ignore_disabled_edits_and_keep_values_on_reactivation() { + let mut h = transfer_mixer_harness(theme::ThemeKind::ProMedium, Tool::Brush); + let before = h.state().brush.clone(); + for value in [41.0, 43.0, 339.0, 63.0, 67.0, 449.0] { + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(value)).unwrap(); + let at = field.rect().center(); + 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); + h.hover_at(at); + h.drag_at(at); + h.run_steps(1); + h.drop_at(at + vec2(60.0, 0.0)); + h.run_steps(2); + assert_eq!(h.state().brush, before, "inactive field {value} ignores keyboard and pointer input"); + } + for label in ["Wetness Jitter", "Mix Jitter"] { + let row = caption_rect(&h, label); + let from = pos2(row.left() + 120.0, row.bottom() + 16.0); + h.hover_at(from); + h.drag_at(from); + h.run_steps(1); + h.hover_at(from + vec2(150.0, 0.0)); + h.run_steps(1); + h.drop_at(from + vec2(150.0, 0.0)); + h.run_steps(2); + assert_eq!(h.state().brush, before, "the inactive {label} track ignores a drag"); + } + h.state_mut().tool = Tool::MixerBrush; + h.run_steps(2); + let row = caption_rect(&h, "Wetness Jitter"); + let from = pos2(row.left() + 120.0, row.bottom() + 16.0); + h.hover_at(from); + h.drag_at(from); + h.run_steps(1); + h.hover_at(from + vec2(150.0, 0.0)); + h.run_steps(1); + h.drop_at(from + vec2(150.0, 0.0)); + h.run_steps(2); + assert!(h.state().brush.transfer.wetness.jitter > 0.6, "the same track accepts a drag when applicable"); + h.state_mut().brush.transfer.wetness.jitter = 0.41; + h.run_steps(2); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(41.0)).unwrap(); + field.click(); + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + assert!((h.state().brush.transfer.wetness.jitter - 0.42).abs() < 1e-6); + let after = h.state().brush.clone(); + h.state_mut().tool = Tool::Brush; + h.run_steps(2); + h.state_mut().tool = Tool::MixerBrush; + h.run_steps(2); + assert_eq!(h.state().brush, after); + assert!(h.query_all_by_role(Role::SpinButton).any(|node| node.accesskit_node().numeric_value() == Some(42.0) && !node.accesskit_node().is_disabled())); +} + +fn set_controls(b: &mut BrushSettings, control: Control) { + for d in [ + &mut b.shape_dynamics.size, + &mut b.shape_dynamics.roundness, + &mut b.transfer.opacity, + &mut b.transfer.flow, + &mut b.transfer.wetness, + &mut b.transfer.mix, + ] { + d.control = control; + } +} + +/// #3825: all six minimum fields follow their own Control; jitter remains editable. +#[test] +fn minimum_fields_are_disabled_only_when_their_control_is_off() { + for (section, values) in [(1, vec![20.0, 35.0]), (6, vec![40.0, 55.0, 60.0, 75.0])] { + let mut h = section_harness(section, minimum_brush()); + for (control, _) in CONTROLS { + set_controls(h.state_mut(), control); + h.run_steps(2); + for value in &values { + let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().numeric_value() == Some(*value)).expect("minimum input"); + assert_eq!(field.accesskit_node().is_disabled(), control == Control::Off, "section {section}, minimum {value}, {control:?}"); + } + assert!( + h.query_all_by_role(Role::SpinButton).any(|n| n.accesskit_node().numeric_value() == Some(0.0) && !n.accesskit_node().is_disabled()), + "jitter stays editable" + ); + } + set_controls(h.state_mut(), Control::PenPressure); + if section == 1 { + h.state_mut().shape_dynamics.size.control = Control::Off; + } else { + h.state_mut().transfer.opacity.control = Control::Off; + } + h.run_steps(2); + for (index, value) in values.iter().enumerate() { + let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().numeric_value() == Some(*value)).unwrap(); + assert_eq!(field.accesskit_node().is_disabled(), index == 0, "each minimum follows its own control"); + } + } +} + +fn drag(h: &mut Harness<'static, BrushSettings>, 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(to)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(2); +} + +#[test] +fn disabled_minimum_ignores_input_and_keeps_its_value_for_reactivation() { + let mut h = section_harness(1, minimum_brush()); + let before = h.state().clone(); + let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().numeric_value() == Some(20.0)).unwrap(); + let center = field.rect().center(); + field.click(); + h.key_press(egui::Key::ArrowUp); + h.event(egui::Event::Text("99".into())); + h.key_press(egui::Key::Enter); + // The slider below the number and its scrubby label are disabled too. + let track = pos2(300.0, center.y + 24.0); + drag(&mut h, track, track); + let label = caption_rect(&h, "Minimum Diameter").center(); + drag(&mut h, label, label + vec2(60.0, 0.0)); + assert_eq!(h.state(), &before, "disabled interactions never rewrite brush settings"); + + h.state_mut().shape_dynamics.size.control = Control::PenPressure; + h.run_steps(2); + let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().numeric_value() == Some(20.0)).unwrap(); + assert!(!field.accesskit_node().is_disabled()); + field.click(); + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + assert_eq!(h.state().shape_dynamics.size.minimum, 0.21, "active minimum is editable"); + drag(&mut h, track, track); + let minimum = h.state().shape_dynamics.size.minimum; + assert!(minimum > 0.8, "the active slider accepts the same pointer position: {minimum}"); + h.state_mut().shape_dynamics.size.control = Control::Off; + h.run_steps(2); + assert_eq!(h.state().shape_dynamics.size.minimum, minimum, "Off keeps the saved minimum"); +} + +#[test] +fn ellipse_widget_drags_angle_and_roundness() { + // Pointing straight up is 90° (counter-clockwise from +x; screen y is down). + assert_eq!(ellipse_drag(EllipseGrab::Angle, vec2(0.0, -20.0), 0.0, 1.0), (90.0, 1.0)); + assert_eq!(ellipse_drag(EllipseGrab::Angle, vec2(-20.0, 0.0), 0.0, 1.0).0.abs(), 180.0); + // The centre itself doesn't change the angle. + assert_eq!(ellipse_drag(EllipseGrab::Angle, vec2(0.2, 0.1), 30.0, 0.5), (30.0, 0.5)); + // At angle 0 the minor axis is vertical: half the radius up is 50 % roundness. + let (_, r) = ellipse_drag(EllipseGrab::Roundness, vec2(0.0, -ELLIPSE_R / 2.0), 0.0, 1.0); + assert!((r - 0.5).abs() < 1e-4); + // Handles sit on the minor axis and are what a press there grabs. + let [h, _] = roundness_handles(0.0, 0.5); + assert!((h - vec2(0.0, -ELLIPSE_R / 2.0)).length() < 1e-4); + assert_eq!(ellipse_grab(h, 0.0, 0.5), EllipseGrab::Roundness); + assert_eq!(ellipse_grab(vec2(ELLIPSE_R, 0.0), 0.0, 0.5), EllipseGrab::Angle); + // Rotated 90°: the minor axis is horizontal. + let [h, _] = roundness_handles(90.0, 1.0); + assert!((h.x.abs() - ELLIPSE_R).abs() < 1e-3 && h.y.abs() < 1e-3, "{h:?}"); + let (_, r) = ellipse_drag(EllipseGrab::Roundness, vec2(500.0, 0.0), 90.0, 0.2); + assert_eq!(r, 1.0); +} From cd56583a03440854f198a3f3d4284bdac7cd068c Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:02 +0000 Subject: [PATCH 078/259] refactor(ui-egui): move retouch_ui.rs tests to retouch_ui/tests.rs --- crates/ui-egui/src/retouch_ui.rs | 787 +------------------------ crates/ui-egui/src/retouch_ui/tests.rs | 784 ++++++++++++++++++++++++ 2 files changed, 785 insertions(+), 786 deletions(-) create mode 100644 crates/ui-egui/src/retouch_ui/tests.rs diff --git a/crates/ui-egui/src/retouch_ui.rs b/crates/ui-egui/src/retouch_ui.rs index db8bde9240..78fb6c3548 100644 --- a/crates/ui-egui/src/retouch_ui.rs +++ b/crates/ui-egui/src/retouch_ui.rs @@ -739,789 +739,4 @@ fn pattern_stamp_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } #[cfg(test)] -mod tests { - use super::*; - use crate::canvas::{ToolEvent, tool_event}; - - 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("tools.setBrush", json!({"brush": {"size": 16, "hardness": 1.0}})).unwrap(); - app - } - - fn drag(app: &mut PhotocraftApp, tool: Tool) { - app.ui.tool = tool; - let m = egui::Modifiers::NONE; - tool_event(app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, m); - tool_event(app, ToolEvent::Move { x: 50.0, y: 30.0, pressure: 1.0 }, m); - tool_event(app, ToolEvent::Up { x: 50.0, y: 30.0 }, m); - assert!(!app.ui.status_error, "{tool:?}: {}", app.ui.status); - } - - fn active(app: &PhotocraftApp) -> &photocraft_doc::Layer { - let st = app.session.active().unwrap(); - st.active_layer.and_then(|id| st.doc.layer(id)).unwrap() - } - - fn stripes(app: &mut PhotocraftApp, step: usize, target: &str) { - for x in (0..100).step_by(step) { - app.run("paint.pencil", json!({"points": [[x, 0], [x, 60]], "size": 2, "color": "#606060", "target": target})).unwrap(); - } - } - - #[test] - fn clone_stamp_in_pattern_preview_wraps_a_dab_across_the_right_edge() { - for pattern_preview in [false, true] { - let mut app = app(); - app.run("paint.pencil", json!({"points": [[10, 10]], "size": 24, "color": "#ff0000"})).unwrap(); - app.ui.tool = Tool::CloneStamp; - app.ui.clone_source = Some([10.0, 10.0]); - app.ui.view.pattern_preview = pattern_preview; - let modifiers = egui::Modifiers::NONE; - tool_event(&mut app, ToolEvent::Down { x: 98.0, y: 30.0, pressure: 1.0 }, modifiers); - tool_event(&mut app, ToolEvent::Up { x: 98.0, y: 30.0 }, modifiers); - assert!(!app.ui.status_error, "{}", app.ui.status); - let surface = active(&app).surface().unwrap(); - let center = surface.rgba(98, 30); - assert!(center[0] > 0.9 && center[1] < 0.1, "clone center: {center:?}"); - let opposite = surface.rgba(1, 30); - if pattern_preview { - assert!(opposite[0] > 0.9 && opposite[1] < 0.1, "Pattern Preview must wrap the clone footprint: {opposite:?}"); - } else { - assert!(opposite[0] > 0.9 && opposite[1] > 0.9, "ordinary cloning must not wrap: {opposite:?}"); - } - } - } - - #[test] - fn alt_flips_dodge_burn_and_blur_sharpen() { - for (tool, flipped) in [(Tool::Dodge, Tool::Burn), (Tool::Burn, Tool::Dodge), (Tool::Blur, Tool::Sharpen), (Tool::Sharpen, Tool::Blur)] { - assert_eq!(alt_flipped(tool, true), flipped); - assert_eq!(alt_flipped(tool, false), tool); - } - for tool in [Tool::Sponge, Tool::Smudge, Tool::Brush] { - assert_eq!(alt_flipped(tool, true), tool, "{tool:?} has no ⌥ counterpart"); - } - } - - #[test] - fn alt_stroke_runs_the_opposite_tool() { - // ⌥ held as the stroke starts: Dodge burns, Burn dodges, Blur sharpens, Sharpen blurs. - for (tool, cmd) in [(Tool::Dodge, "paint.burn"), (Tool::Burn, "paint.dodge"), (Tool::Blur, "paint.sharpen"), (Tool::Sharpen, "paint.blur")] { - let mut app = app(); - app.ui.tool = tool; - let m = egui::Modifiers::ALT; - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 30.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 30.0 }, m); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some(cmd), "{tool:?} with ⌥"); - assert_eq!(app.ui.tool, tool, "the selected tool stays {tool:?}"); - } - } - - #[test] - fn clone_stamp_brush_opacity_and_flow_reach_the_painted_pixels() { - let mut app = app(); - app.run("paint.pencil", json!({"points": [[10, 10]], "size": 16, "color": "#ff0000"})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.ui.tool = Tool::CloneStamp; - app.ui.clone_source = Some([10.0, 10.0]); - app.ui.tool_options.clone_sample = "all".into(); - app.run("tools.setBrush", json!({"brush": {"opacity": 0.5, "flow": 0.5}})).unwrap(); - assert!(finish_stroke(&mut app, Tool::CloneStamp, &[[50.0, 30.0, 1.0]], egui::Modifiers::NONE)); - assert!(!app.ui.status_error, "{}", app.ui.status); - let pixel = active(&app).surface().unwrap().rgba(50, 30); - assert!(pixel[0] > 0.9 && pixel[3] > 0.0 && pixel[3] < 0.5, "partial-opacity, partial-flow red stamp: {pixel:?}"); - let (id, params) = app.session.journal.last().unwrap(); - assert_eq!(id, "paint.cloneStamp"); - assert_eq!(params["opacity"], 50.0); - assert_eq!(params["flow"], 50.0); - } - - /// A Healing Brush whose brush holds a mode outside its menu (Overlay, restored with the tool - /// active, so no tool switch sees it) heals in Normal; the Clone Stamp keeps Overlay. - #[test] - fn healing_brush_heals_in_normal_with_a_mode_outside_its_menu() { - for (tool, want) in [(Tool::Healing, "Normal"), (Tool::CloneStamp, "Overlay")] { - let mut app = app(); - app.ui.tool = tool; - crate::paint_mouse::sync_tool_brush(&mut app); - app.session.tools.brush.mode = photocraft_color::BlendMode::Overlay; - app.ui.clone_source = Some([10.0, 10.0]); - drag(&mut app, tool); - let (_, params) = app.session.journal.last().unwrap(); - assert_eq!(params["mode"], want, "{tool:?}"); - } - } - - /// The options bar's Mode (each tool's own brush's) reaches the stamps', the History Brush's - /// and the Healing Brush's strokes, live and committed. - #[test] - fn retouch_mode_reaches_the_command() { - for (tool, cmd, mode) in [ - (Tool::CloneStamp, "paint.cloneStamp", "Multiply"), - (Tool::Healing, "paint.healingBrush", "Luminosity"), - (Tool::HistoryBrush, "paint.historyBrush", "Screen"), - (Tool::PatternStamp, "paint.patternStamp", "Overlay"), - ] { - let mut app = app(); - app.ui.tool = tool; - crate::paint_mouse::sync_tool_brush(&mut app); - app.run("tools.setBrush", json!({"brush": {"mode": mode}})).unwrap(); - app.ui.clone_source = Some([10.0, 10.0]); - drag(&mut app, tool); - let (id, params) = app.session.journal.last().unwrap(); - assert_eq!((id.as_str(), params["mode"].as_str()), (cmd, Some(mode)), "{tool:?}"); - } - } - - /// The Paint Bucket's Mode reaches the fill: Multiply darkens, Clear erases. - #[test] - fn paint_bucket_mode_reaches_the_fill() { - let mut app = app(); - app.run("layer.new.layer", json!({})).unwrap(); - app.ui.tool = Tool::PaintBucket; - app.session.tools.foreground = [0.5, 0.5, 0.5, 1.0]; - let click = |app: &mut PhotocraftApp| { - let m = egui::Modifiers::NONE; - tool_event(app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m); - tool_event(app, ToolEvent::Up { x: 20.0, y: 20.0 }, m); - }; - click(&mut app); - app.session.tools.foreground = [1.0, 0.0, 0.0, 1.0]; - app.ui.tool_options.bucket_blend_mode = photocraft_color::BlendMode::Multiply; - click(&mut app); - let px = active(&app).surface().unwrap().rgba(20, 20); - assert!((px[0] - 0.5).abs() < 0.02 && px[1] < 0.02, "multiplied: {px:?}"); - app.ui.tool_options.bucket_clear = true; - click(&mut app); - assert_eq!(app.session.journal.last().unwrap().1["mode"], "clear"); - assert!(active(&app).surface().unwrap().rgba(20, 20)[3] < 0.01, "cleared"); - } - - #[test] - fn clone_without_a_source_names_the_platform_modifier() { - // Option-click on the Mac, Alt-click elsewhere (#251). - for tool in [Tool::CloneStamp, Tool::Healing] { - let mut app = app(); - app.ui.tool = tool; - assert!(finish_stroke(&mut app, tool, &[[10.0, 30.0, 1.0], [50.0, 30.0, 1.0]], egui::Modifiers::NONE)); - assert!(app.ui.status_error, "{tool:?}"); - let want = if cfg!(target_os = "macos") { "Option-click" } else { "Alt-click" }; - assert!(app.ui.status.starts_with(want), "{tool:?}: {}", app.ui.status); - } - } - - #[test] - fn retouch_strokes_paint_the_targeted_mask() { - // #207: with the mask targeted, retouching changes the mask, never the pixels. - for tool in [Tool::Blur, Tool::Sharpen, Tool::Smudge, Tool::Dodge, Tool::Burn] { - let mut app = app(); - app.run("layer.new.layer", json!({})).unwrap(); - stripes(&mut app, 4, "pixels"); - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - stripes(&mut app, 6, "mask"); - app.ui.mask_target = true; - app.ui.tool_options.protect_detail = false; - let b = app.session.active().unwrap().doc.bounds(); - let px0 = active(&app).surface().unwrap().read_region(b); - let mask0 = active(&app).mask.as_ref().unwrap().surface.read_region(b); - drag(&mut app, tool); - assert_eq!(active(&app).surface().unwrap().read_region(b), px0, "{tool:?}: pixels untouched"); - assert_ne!(active(&app).mask.as_ref().unwrap().surface.read_region(b), mask0, "{tool:?}: mask changed"); - } - } - - #[test] - fn sample_all_layers_reaches_the_command() { - // #207, #731: the options-bar checkbox reaches the command. - for tool in [Tool::SpotHealing, Tool::Remove, Tool::Blur, Tool::Sharpen, Tool::Smudge] { - for all in [false, true] { - let mut app = app(); - stripes(&mut app, 4, "pixels"); - app.run("layer.new.layer", json!({})).unwrap(); - *app.ui.tool_options.sample_all.slot(tool).unwrap() = all; - drag(&mut app, tool); - let a = active(&app).surface().unwrap().rgba(30, 30)[3]; - assert_eq!(a > 0.0, all, "{tool:?} sampleAllLayers={all}: alpha {a}"); - } - } - } - - #[test] - fn sample_all_layers_is_each_tools_own() { - // #5524: Sample All Layers turned on for another tool (the Magic Wand, say) left Blur and - // Smudge copying the composite onto an annotation layer, freezing a sharp patch above the - // picture. Photoshop keeps the option per tool, so those strokes leave the empty layer empty. - for tool in [Tool::Blur, Tool::Sharpen, Tool::Smudge] { - let mut app = app(); - stripes(&mut app, 4, "pixels"); - app.run("layer.new.layer", json!({})).unwrap(); - let mut others = crate::state::SampleAllLayers::default(); - for t in [ - Tool::MagicWand, - Tool::QuickSelection, - Tool::ObjectSelection, - Tool::PaintBucket, - Tool::MagicEraser, - Tool::SpotHealing, - Tool::Patch, - Tool::ContentAwareMove, - Tool::Remove, - Tool::Blur, - Tool::Sharpen, - Tool::Smudge, - ] { - if let Some(v) = others.slot(t).filter(|_| t != tool) { - *v = true; - } - } - app.ui.tool_options.sample_all = others; - assert!(!app.ui.tool_options.sample_all.get(tool)); - drag(&mut app, tool); - let a = active(&app).surface().unwrap().rgba(30, 30)[3]; - assert_eq!(a, 0.0, "{tool:?} sampled all layers through another tool's option"); - } - } - - #[test] - fn object_selection_click_falls_back_to_quick_selection() { - // A click cannot be a rectangle: it selects at the cursor instead of looking dead. - let mut app = app(); - app.ui.tool = Tool::ObjectSelection; - app.ui.tool_options.object_finder = false; - let m = egui::Modifiers::NONE; - tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 30.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 30.0 }, m); - assert!(!app.ui.status_error, "{}", app.ui.status); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("select.quick")); - } - - #[test] - fn object_selection_rect_runs_object_selection_and_reports() { - let mut app = app(); - app.run("paint.pencil", json!({"points": [[20, 10], [20, 50]], "size": 8, "color": "#ff0000"})).unwrap(); - app.ui.tool = Tool::ObjectSelection; - let m = egui::Modifiers::NONE; - tool_event(&mut app, ToolEvent::Down { x: 5.0, y: 5.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Move { x: 60.0, y: 55.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 55.0 }, m); - assert!(!app.ui.status_error, "{}", app.ui.status); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("select.object")); - } - - #[test] - fn empty_smart_result_is_reported_without_error() { - // An empty smart selection (Select Subject missing on a busy photo) is an info, not - // an error and not silence: the button must visibly answer. - let mut app = app(); - report_smart_result(&mut app, Ok(json!({"selected": false, "changed": false})), "nothing there"); - assert_eq!(app.ui.status.as_str(), "nothing there"); - assert!(!app.ui.status_error); - app.ui.status.clear(); - report_smart_result(&mut app, Ok(json!({"selected": true, "changed": true})), "nothing there"); - assert!(app.ui.status.is_empty()); - } - - #[test] - fn mixer_brush_is_selectable_and_paints_only_inside_the_selection_via_control() { - use crate::control::{ControlRequest, Outcome, handle}; - - let mut app = app(); - app.run("paint.pencil", json!({"points": [[50, 30]], "size": 200, "color": "#204080"})).unwrap(); - app.run("tools.setColors", json!({"foreground": "#f02010"})).unwrap(); - app.run( - "tools.setBrush", - json!({ - "pressureSize": false, - "size": 12, - "mixer": {"wet": 0.0, "load": 1.0, "mix": 0.0, "flow": 1.0} - }), - ) - .unwrap(); - app.run("select.rect", json!({"x": 35, "y": 20, "width": 30, "height": 20})).unwrap(); - let before = { - let surface = active(&app).surface().unwrap(); - [surface.rgba(20, 30), surface.rgba(50, 30), surface.rgba(80, 30)] - }; - - let ctx = egui::Context::default(); - let (req, _rx) = ControlRequest::new( - "ui.pointer", - json!({ - "tool": "mixerBrush", - "events": [ - {"kind": "down", "x": 8, "y": 30}, - {"kind": "move", "x": 92, "y": 30}, - {"kind": "up", "x": 92, "y": 30} - ] - }), - ); - assert!(matches!(handle(&mut app, &ctx, &req), Outcome::Done(_))); - assert_eq!(app.ui.tool, Tool::MixerBrush); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.mixerBrush")); - - let surface = active(&app).surface().unwrap(); - assert_ne!(surface.rgba(50, 30), before[1], "the selected pixels are mixed"); - assert_eq!(surface.rgba(20, 30), before[0], "outside the selection is unchanged"); - assert_eq!(surface.rgba(80, 30), before[2], "the far side outside the selection is unchanged"); - } - - #[test] - fn patch_tool_lassoes_then_drags_the_patch() { - let mut app = app(); - app.run("paint.pencil", json!({"points": [[68, 30], [74, 30]], "size": 6, "color": "#ff0000"})).unwrap(); - let red = |app: &PhotocraftApp| active(app).surface().unwrap().rgba(71, 30)[1] < 0.5; - assert!(red(&app)); - app.ui.tool = Tool::Patch; - let m = egui::Modifiers::NONE; - // Outside any selection the drag is a lasso. - tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 20.0, pressure: 1.0 }, m); - for [x, y] in [[84.0, 20.0], [84.0, 40.0], [60.0, 40.0]] { - tool_event(&mut app, ToolEvent::Move { x, y, pressure: 1.0 }, m); - } - tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 40.0 }, m); - assert!(app.session.active().unwrap().doc.selection.is_some(), "lasso made a selection"); - assert!(red(&app), "the lasso alone changes no pixels"); - // ⇧-drag inside the selection adds to it rather than patching. - assert!(!patch_drags_selection(&app, [70.0, 30.0], egui::Modifiers::SHIFT)); - // Dragging inside it patches from where it is dropped; the offset is limited to the canvas. - assert!(patch_drags_selection(&app, [70.0, 30.0], m)); - assert_eq!(patch_offset(&mut app, [70.0, 30.0], [-200.0, 30.0]), [-60, 0]); - tool_event(&mut app, ToolEvent::Down { x: 70.0, y: 30.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 31.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }, m); - assert!(!app.ui.status_error, "{}", app.ui.status); - let px = active(&app).surface().unwrap().rgba(71, 30); - assert!(px[0] > 0.95 && px[1] > 0.95 && px[2] > 0.95, "blemish patched with the white background: {px:?}"); - } - - #[test] - fn patch_tool_content_aware_fills_from_where_it_is_dropped() { - let mut app = app(); - app.run("paint.pencil", json!({"points": [[68, 30], [74, 30]], "size": 6, "color": "#ff0000"})).unwrap(); - app.run("select.rect", json!({"x": 60, "y": 20, "width": 24, "height": 20})).unwrap(); - app.ui.tool = Tool::Patch; - app.ui.tool_options.patch_content_aware = true; - app.ui.tool_options.patch_structure = 5.0; - app.ui.tool_options.patch_color = 3.0; - let m = egui::Modifiers::NONE; - tool_event(&mut app, ToolEvent::Down { x: 70.0, y: 30.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 31.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }, m); - assert!(!app.ui.status_error, "{}", app.ui.status); - let (id, p) = app.session.journal.last().cloned().unwrap(); - assert_eq!(id, "paint.patch"); - assert_eq!((p["contentAware"].as_bool(), p["structure"].as_f64(), p["color"].as_f64()), (Some(true), Some(5.0), Some(3.0))); - let px = active(&app).surface().unwrap().rgba(71, 30); - assert!(px[0] > 0.95 && px[1] > 0.95 && px[2] > 0.95, "blemish filled from the white background: {px:?}"); - } - - #[test] - fn content_aware_move_tool_lassoes_then_moves_or_extends() { - for (mode, keeps) in [("move", false), ("extend", true)] { - let mut app = app(); - 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_mode = mode.into(); - app.ui.tool_options.cam_structure = 7.0; - let m = egui::Modifiers::NONE; - tool_event(&mut app, ToolEvent::Down { x: 12.0, y: 20.0, pressure: 1.0 }, m); - for [x, y] in [[32.0, 20.0], [32.0, 40.0], [12.0, 40.0]] { - tool_event(&mut app, ToolEvent::Move { x, y, pressure: 1.0 }, m); - } - tool_event(&mut app, ToolEvent::Up { x: 12.0, y: 40.0 }, m); - assert!(app.session.active().unwrap().doc.selection.is_some(), "lasso made a selection"); - assert!(blue(&app, 22), "the lasso alone changes no pixels"); - tool_event(&mut app, ToolEvent::Down { x: 22.0, y: 30.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 31.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x: 72.0, y: 30.0 }, m); - assert!(!app.ui.status_error, "{mode}: {}", app.ui.status); - assert!(blue(&app, 72), "{mode}: the content lands where it was dropped"); - assert_eq!(blue(&app, 22), keeps, "{mode}: the original place"); - assert_eq!(app.session.journal.last().map(|(id, p)| (id.as_str(), p["mode"].as_str())), Some(("paint.contentAwareMove", Some(mode)))); - let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap(); - assert!(sel.sample_channel(72, 30, 0) > 0.0 && sel.sample_channel(22, 30, 0) == 0.0, "{mode}: the selection follows"); - } - } - - #[test] - fn content_aware_move_transform_on_drop_turns_the_patch_on_enter() { - let mut app = app(); - app.run("paint.pencil", json!({"points": [[16, 30], [28, 30]], "size": 4, "color": "#0000ff"})).unwrap(); - let blue = |app: &PhotocraftApp, x: i32, y: i32| active(app).surface().unwrap().rgba(x, y)[0] < 0.5; - app.ui.tool = Tool::ContentAwareMove; - app.ui.tool_options.cam_transform_on_drop = true; - app.ui.tool_options.cam_structure = 7.0; - let m = egui::Modifiers::NONE; - let drag = |app: &mut PhotocraftApp, path: &[[f64; 2]]| { - let ([x, y], rest) = (path[0], &path[1..]); - tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, m); - for &[x, y] in rest { - tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, m); - } - let [x, y] = path[path.len() - 1]; - tool_event(app, ToolEvent::Up { x, y }, m); - }; - drag(&mut app, &[[6.0, 14.0], [38.0, 14.0], [38.0, 46.0], [6.0, 46.0]]); - let steps = app.session.active().unwrap().history.past_len(); - // The drop puts a box on the patch; nothing is computed yet. - drag(&mut app, &[[22.0, 30.0], [50.0, 30.0], [72.0, 30.0]]); - assert!(crate::cam_transform::active(&app), "{}", app.ui.status); - assert!(blue(&app, 22, 30) && !blue(&app, 72, 30), "the document waits for the commit"); - assert_eq!(app.session.active().unwrap().history.past_len(), steps); - // Dragging outside the box turns it 90° about its centre (72, 30). - drag(&mut app, &[[98.0, 55.0], [60.0, 58.0], [47.0, 56.0]]); - let place = crate::cam_transform::placement(app.ui.cam_transform.as_ref().unwrap()).unwrap(); - assert_eq!((place.offset, place.scale), ([50, 0], [100.0, 100.0])); - assert!((place.rotate - 90.0).abs() < 1e-3, "{place:?}"); - crate::cam_transform::commit(&mut app); - assert!(!crate::cam_transform::active(&app) && !app.ui.status_error, "{}", app.ui.status); - let (id, p) = app.session.journal.last().unwrap(); - assert_eq!((id.as_str(), &p["offset"]), ("paint.contentAwareMove", &json!([50, 0]))); - assert!((p["rotate"].as_f64().unwrap() - 90.0).abs() < 1e-3, "{p}"); - // The horizontal line lands upright, in one History step. - assert!(blue(&app, 72, 26) && blue(&app, 72, 34), "the turned line"); - assert!(!blue(&app, 66, 30) && !blue(&app, 78, 30), "no unturned line"); - assert!(!blue(&app, 22, 30), "the old place is filled"); - assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); - } - - #[test] - fn red_eye_click_corrects_a_pupil_and_errors_on_a_miss() { - let mut app = app(); - app.run("paint.pencil", json!({"points": [[50, 30]], "size": 18, "hardness": 100, "color": "#f21818"})).unwrap(); - let before = active(&app).surface().unwrap().rgba(50, 30); - assert!(before[0] > before[1] + 0.4, "{before:?}"); - app.ui.tool = Tool::RedEye; - // Pupil Size 15 → search radius 22 px, so a click at (8,8) cannot reach the blob at (50,30). - app.ui.tool_options.red_eye_pupil_size = 15.0; - tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); - tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 30.0 }, egui::Modifiers::NONE); - assert!(!app.ui.status_error, "{}", app.ui.status); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.redEye")); - let after = active(&app).surface().unwrap().rgba(50, 30); - assert!(after[0] < before[0] - 0.15, "before {before:?} after {after:?}"); - tool_event(&mut app, ToolEvent::Down { x: 8.0, y: 8.0, pressure: 1.0 }, egui::Modifiers::NONE); - tool_event(&mut app, ToolEvent::Up { x: 8.0, y: 8.0 }, egui::Modifiers::NONE); - assert!(app.ui.status_error); - assert!(app.ui.status.contains("no red-eye pixels"), "{}", app.ui.status); - } - - #[test] - fn red_eye_options_bar_shows_pupil_size_and_darken() { - use crate::theme::ThemeKind; - use egui::vec2; - use egui_kittest::kittest::Queryable; - let mut app = app(); - app.ui.tool = Tool::RedEye; - let mut h = egui_kittest::Harness::builder().with_size(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, ThemeKind::Studio); - h.run_steps(4); - h.get_by_label("Pupil Size"); - h.get_by_label("Darken Amount"); - assert_eq!(h.state().ui.tool_options.red_eye_pupil_size, 50.0); - assert_eq!(h.state().ui.tool_options.red_eye_darken, 50.0); - } - - #[test] - fn patch_tool_says_to_drag_the_selection_after_the_lasso_and_after_a_click() { - let hint = tl!("Now drag the selection onto another area"); - let m = egui::Modifiers::NONE; - let mut app = app(); - app.ui.tool = Tool::Patch; - app.ui.status.clear(); - // No selection yet: the drag is a lasso, which outlines the patch and says what comes next. - tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 10.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Move { x: 40.0, y: 10.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Move { x: 40.0, y: 30.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x: 20.0, y: 30.0 }, m); - assert!(app.session.active().is_some_and(|st| st.doc.selection.is_some()), "the lasso made a selection"); - assert_eq!((app.ui.status.as_str(), app.ui.status_error), (hint, false)); - // A press and release inside the selection moves nothing: it says so instead of staying silent. - app.ui.status.clear(); - tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 20.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 20.0 }, m); - assert_eq!((app.ui.status.as_str(), app.ui.status_error), (hint, false)); - assert!(app.session.active().is_some_and(|st| st.doc.selection.is_some()), "the selection stays"); - } - - #[test] - fn remove_tool_stroke_removes_what_it_covers() { - let mut app = app(); - app.run("paint.pencil", json!({"points": [[0, 30], [100, 30]], "size": 200, "color": "#808080"})).unwrap(); - app.run("paint.pencil", json!({"points": [[30, 20], [30, 40]], "size": 4, "color": "#000000"})).unwrap(); - let bg = active(&app).surface().unwrap().rgba(70, 30); - app.ui.tool = Tool::Remove; - let m = egui::Modifiers::NONE; - tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 18.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 42.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 42.0 }, m); - assert!(!app.ui.status_error, "{}", app.ui.status); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.remove")); - let px = active(&app).surface().unwrap().rgba(30, 30); - assert!(px.iter().zip(bg).all(|(a, b)| (a - b).abs() < 0.02), "{px:?} vs {bg:?}"); - } - - #[test] - fn remove_after_each_stroke_off_collects_strokes_until_enter_or_escape() { - let mut app = app(); - app.run("paint.pencil", json!({"points": [[0, 30], [100, 30]], "size": 200, "color": "#808080"})).unwrap(); - app.run("paint.pencil", json!({"points": [[30, 20], [30, 40]], "size": 4, "color": "#000000"})).unwrap(); - app.ui.tool = Tool::Remove; - app.ui.tool_options.remove_after_each_stroke = false; - let m = egui::Modifiers::NONE; - let journal = app.session.journal.len(); - for x in [28.0, 32.0] { - tool_event(&mut app, ToolEvent::Down { x, y: 18.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Move { x, y: 42.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x, y: 42.0 }, m); - } - // Nothing ran yet: the strokes wait, tinted, and the status says so. - assert_eq!(app.session.journal.len(), journal, "no command before Enter"); - assert_eq!(app.remove_pending.len(), 2); - assert!(app.remove_trail.is_some()); - assert!(app.ui.status.contains("2") && !app.ui.status_error, "{}", app.ui.status); - // Esc drops them. - assert!(remove_pending_cancel(&mut app)); - assert!(app.remove_pending.is_empty() && app.remove_trail.is_none()); - assert!(!remove_pending_cancel(&mut app)); - // Collected again, Enter applies them as one `paint.remove` with both strokes. - for x in [28.0, 32.0] { - tool_event(&mut app, ToolEvent::Down { x, y: 18.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x, y: 42.0 }, m); - } - let bg = active(&app).surface().unwrap().rgba(70, 30); - assert!(remove_pending_commit(&mut app)); - assert!(!app.ui.status_error, "{}", app.ui.status); - let (id, p) = app.session.journal.last().cloned().expect("a journaled command"); - assert_eq!(id, "paint.remove"); - assert_eq!(p["strokes"].as_array().map(Vec::len), Some(2)); - assert!(p.get("points").is_none()); - assert!(app.remove_pending.is_empty()); - let px = active(&app).surface().unwrap().rgba(30, 30); - assert!(px.iter().zip(bg).all(|(a, b)| (a - b).abs() < 0.02), "{px:?} vs {bg:?}"); - assert!(!remove_pending_commit(&mut app), "nothing left to apply"); - } - - #[test] - fn every_waiting_remove_stroke_is_tinted_in_full() { - // #6555: each stroke used to be stamped only past the previous stroke's point count. - let mut app = app(); - app.ui.tool = Tool::Remove; - app.ui.tool_options.remove_after_each_stroke = false; - let strokes: [&[[f64; 3]]; 3] = [ - &[[10.0, 10.0, 1.0], [40.0, 10.0, 1.0], [70.0, 10.0, 1.0]], - &[[10.0, 30.0, 1.0], [40.0, 30.0, 1.0]], - &[[10.0, 50.0, 1.0], [20.0, 50.0, 1.0], [30.0, 50.0, 1.0], [50.0, 50.0, 1.0], [90.0, 50.0, 1.0]], - ]; - for s in strokes { - remove_pending_add(&mut app, s); - } - assert_eq!(app.remove_pending.len(), 3); - let t = app.remove_trail.as_ref().expect("the waiting strokes are tinted"); - let k = f64::from(t.scale()); - for s in strokes { - for w in s.windows(2) { - for i in 0..=8 { - let f = f64::from(i) / 8.0; - let (x, y) = (w[0][0] + (w[1][0] - w[0][0]) * f, w[0][1] + (w[1][1] - w[0][1]) * f); - assert_eq!(t.coverage((x / k) as usize, (y / k) as usize), 255, "({x}, {y}) on a waiting stroke is tinted"); - } - } - } - // Enter, Esc, another tool and another document all drop the tint with the strokes. - assert!(remove_pending_commit(&mut app)); - assert!(app.remove_trail.is_none()); - remove_pending_add(&mut app, strokes[0]); - assert!(remove_pending_cancel(&mut app) && app.remove_trail.is_none()); - remove_pending_add(&mut app, strokes[1]); - app.ui.tool = Tool::SpotHealing; - assert!(!remove_pending_live(&mut app) && app.remove_trail.is_none()); - app.ui.tool = Tool::Remove; - remove_pending_add(&mut app, strokes[2]); - app.run("file.new", json!({"width": 100, "height": 60})).unwrap(); - assert!(!remove_pending_live(&mut app) && app.remove_trail.is_none()); - } - - #[test] - fn queued_remove_cannot_commit_after_layer_or_channel_target_changes() { - for change in ["layer", "color", "mask"] { - let mut app = app(); - app.run("layer.new.layer", json!({"name": "Original"})).unwrap(); - if change == "color" { - app.run("channel.target", json!({"channel": "red"})).unwrap(); - } - app.ui.tool = Tool::Remove; - app.ui.tool_options.remove_after_each_stroke = false; - remove_pending_add(&mut app, &[[12.0, 10.0, 1.0], [16.0, 12.0, 1.0]]); - assert_eq!(app.remove_pending.len(), 1); - assert!(remove_pending_live(&mut app)); - - match change { - "layer" => { - app.run("layer.new.layer", json!({"name": "Other"})).unwrap(); - } - "color" => { - app.run("channel.target", json!({"channel": "blue"})).unwrap(); - } - _ => { - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - app.ui.mask_target = true; - } - } - - let journal = app.session.journal.len(); - assert!(!remove_pending_commit(&mut app), "{change}: Enter must not retarget a queued stroke"); - assert_eq!(app.session.journal.len(), journal, "{change}: no Remove command ran"); - assert!(app.remove_pending.is_empty() && app.remove_trail.is_none(), "{change}: queue cleared"); - assert!(app.remove_pending_target.is_none()); - } - } - - #[test] - fn queued_remove_starts_a_new_queue_after_target_switch() { - let mut app = app(); - app.run("layer.new.layer", json!({"name": "Original"})).unwrap(); - app.ui.tool = Tool::Remove; - app.ui.tool_options.remove_after_each_stroke = false; - remove_pending_add(&mut app, &[[12.0, 10.0, 1.0], [16.0, 12.0, 1.0]]); - app.run("layer.new.layer", json!({"name": "Other"})).unwrap(); - remove_pending_add(&mut app, &[[40.0, 10.0, 1.0], [44.0, 12.0, 1.0]]); - assert_eq!(app.remove_pending.len(), 1, "strokes from different layers must not be combined"); - assert_eq!(app.remove_pending[0][0][0], 40.0); - assert!(remove_pending_live(&mut app)); - } - - #[test] - fn remove_strokes_waiting_are_dropped_when_the_tool_changes() { - let mut app = app(); - app.ui.tool = Tool::Remove; - app.ui.tool_options.remove_after_each_stroke = false; - remove_pending_add(&mut app, &[[10.0, 10.0, 1.0], [20.0, 10.0, 1.0]]); - assert_eq!(app.remove_pending.len(), 1); - assert!(remove_pending_live(&mut app)); - app.ui.tool = Tool::SpotHealing; - assert!(!remove_pending_live(&mut app)); - assert!(app.remove_pending.is_empty(), "the strokes belong to the Remove tool"); - } - - #[test] - fn create_a_new_layer_sends_new_layer_to_the_command() { - let mut app = app(); - app.run("paint.pencil", json!({"points": [[0, 30], [100, 30]], "size": 200, "color": "#808080"})).unwrap(); - app.ui.tool = Tool::Remove; - app.ui.tool_options.remove_new_layer = true; - let layers = app.session.active().unwrap().doc.walk().len(); - let m = egui::Modifiers::NONE; - tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 18.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 42.0 }, m); - assert!(!app.ui.status_error, "{}", app.ui.status); - let (id, p) = app.session.journal.last().cloned().unwrap(); - assert_eq!((id.as_str(), p["newLayer"].as_bool()), ("paint.remove", Some(true))); - assert_eq!(app.session.active().unwrap().doc.walk().len(), layers + 1, "the fill went to a new layer"); - } - - #[test] - fn red_eye_is_in_the_j_flyout() { - let j = [Tool::Remove, Tool::SpotHealing, Tool::Healing, Tool::Patch, Tool::ContentAwareMove, Tool::RedEye]; - assert!(j.contains(&Tool::RedEye)); - assert!(j.iter().all(|t| t.key() == 'J')); - } - - #[test] - fn j_cycles_from_remove() { - // J from another group picks the first J tool, and repeated J goes on in this order. - let group: Vec = Tool::ALL.iter().copied().filter(|t| t.key() == 'J').collect(); - assert_eq!(group, [Tool::Remove, Tool::SpotHealing, Tool::Healing, Tool::Patch, Tool::ContentAwareMove, Tool::RedEye]); - } - - #[test] - fn s_group_is_clone_stamp_then_pattern_stamp() { - assert_eq!(Tool::CloneStamp.key(), 'S'); - assert_eq!(Tool::PatternStamp.key(), 'S'); - let group: Vec = Tool::ALL.iter().copied().filter(|t| t.key() == 'S').collect(); - assert_eq!(group, vec![Tool::CloneStamp, Tool::PatternStamp]); - assert_eq!(Tool::from_name("patternStamp"), Some(Tool::PatternStamp)); - } - - #[test] - fn pattern_stamp_stroke_paints_pixels_and_keeps_phase_when_aligned() { - let mut app = app(); - assert!(finish_stroke(&mut app, Tool::PatternStamp, &[[20.0, 30.0, 1.0], [50.0, 30.0, 1.0]], egui::Modifiers::NONE)); - assert!(!app.ui.status_error, "{}", app.ui.status); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.patternStamp")); - assert!(app.ui.pattern_stamp_phase.is_some()); - let px = active(&app).surface().unwrap().rgba(30, 30); - assert!(px[3] > 0.5, "the stamp paints through the brush: {px:?}"); - app.ui.tool_options.pattern_stamp_aligned = false; - app.ui.pattern_stamp_phase = None; - assert!(finish_stroke(&mut app, Tool::PatternStamp, &[[70.0, 30.0, 1.0]], egui::Modifiers::NONE)); - assert!(app.ui.pattern_stamp_phase.is_none(), "unaligned strokes do not keep phase"); - } - - #[test] - fn pattern_stamp_does_not_require_a_clone_source() { - let mut app = app(); - assert!(app.ui.clone_source.is_none()); - assert!(finish_stroke(&mut app, Tool::PatternStamp, &[[12.0, 30.0, 1.0]], egui::Modifiers::NONE)); - assert!(!app.ui.status_error, "{}", app.ui.status); - assert!(app.ui.clone_source.is_none()); - } - - #[test] - fn art_history_is_in_the_y_flyout() { - let y = [Tool::HistoryBrush, Tool::ArtHistoryBrush]; - assert_eq!(y[0], Tool::HistoryBrush); - assert_eq!(y[1], Tool::ArtHistoryBrush); - assert!(y.iter().all(|t| t.key() == 'Y')); - assert!(Tool::ArtHistoryBrush.is_brushlike()); - } - - #[test] - fn art_history_options_bar_defaults() { - use crate::theme::ThemeKind; - use egui::vec2; - use egui_kittest::kittest::Queryable; - let mut app = app(); - app.ui.tool = Tool::ArtHistoryBrush; - let mut h = egui_kittest::Harness::builder().with_size(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, ThemeKind::Studio); - h.run_steps(4); - h.get_by_label("Style"); - h.get_by_label("Area"); - h.get_by_label("Tolerance"); - assert_eq!(h.state().ui.tool_options.art_history_style, "tightMedium"); - assert_eq!(h.state().ui.tool_options.art_history_area, 50.0); - assert_eq!(h.state().ui.tool_options.art_history_tolerance, 0.0); - } - - #[test] - fn art_history_stroke_runs_the_command() { - let mut app = app(); - app.run("paint.pencil", json!({"points": [[0, 30], [100, 30]], "size": 20, "color": "#3060c0"})).unwrap(); - app.ui.tool = Tool::ArtHistoryBrush; - app.ui.tool_options.art_history_style = "tightMedium".into(); - app.ui.tool_options.art_history_tolerance = 0.0; - drag(&mut app, Tool::ArtHistoryBrush); - assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.artHistoryBrush")); - } -} +mod tests; diff --git a/crates/ui-egui/src/retouch_ui/tests.rs b/crates/ui-egui/src/retouch_ui/tests.rs new file mode 100644 index 0000000000..d7d07d6e9f --- /dev/null +++ b/crates/ui-egui/src/retouch_ui/tests.rs @@ -0,0 +1,784 @@ +use super::*; +use crate::canvas::{ToolEvent, tool_event}; + +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("tools.setBrush", json!({"brush": {"size": 16, "hardness": 1.0}})).unwrap(); + app +} + +fn drag(app: &mut PhotocraftApp, tool: Tool) { + app.ui.tool = tool; + let m = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Move { x: 50.0, y: 30.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x: 50.0, y: 30.0 }, m); + assert!(!app.ui.status_error, "{tool:?}: {}", app.ui.status); +} + +fn active(app: &PhotocraftApp) -> &photocraft_doc::Layer { + let st = app.session.active().unwrap(); + st.active_layer.and_then(|id| st.doc.layer(id)).unwrap() +} + +fn stripes(app: &mut PhotocraftApp, step: usize, target: &str) { + for x in (0..100).step_by(step) { + app.run("paint.pencil", json!({"points": [[x, 0], [x, 60]], "size": 2, "color": "#606060", "target": target})).unwrap(); + } +} + +#[test] +fn clone_stamp_in_pattern_preview_wraps_a_dab_across_the_right_edge() { + for pattern_preview in [false, true] { + let mut app = app(); + app.run("paint.pencil", json!({"points": [[10, 10]], "size": 24, "color": "#ff0000"})).unwrap(); + app.ui.tool = Tool::CloneStamp; + app.ui.clone_source = Some([10.0, 10.0]); + app.ui.view.pattern_preview = pattern_preview; + let modifiers = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 98.0, y: 30.0, pressure: 1.0 }, modifiers); + tool_event(&mut app, ToolEvent::Up { x: 98.0, y: 30.0 }, modifiers); + assert!(!app.ui.status_error, "{}", app.ui.status); + let surface = active(&app).surface().unwrap(); + let center = surface.rgba(98, 30); + assert!(center[0] > 0.9 && center[1] < 0.1, "clone center: {center:?}"); + let opposite = surface.rgba(1, 30); + if pattern_preview { + assert!(opposite[0] > 0.9 && opposite[1] < 0.1, "Pattern Preview must wrap the clone footprint: {opposite:?}"); + } else { + assert!(opposite[0] > 0.9 && opposite[1] > 0.9, "ordinary cloning must not wrap: {opposite:?}"); + } + } +} + +#[test] +fn alt_flips_dodge_burn_and_blur_sharpen() { + for (tool, flipped) in [(Tool::Dodge, Tool::Burn), (Tool::Burn, Tool::Dodge), (Tool::Blur, Tool::Sharpen), (Tool::Sharpen, Tool::Blur)] { + assert_eq!(alt_flipped(tool, true), flipped); + assert_eq!(alt_flipped(tool, false), tool); + } + for tool in [Tool::Sponge, Tool::Smudge, Tool::Brush] { + assert_eq!(alt_flipped(tool, true), tool, "{tool:?} has no ⌥ counterpart"); + } +} + +#[test] +fn alt_stroke_runs_the_opposite_tool() { + // ⌥ held as the stroke starts: Dodge burns, Burn dodges, Blur sharpens, Sharpen blurs. + for (tool, cmd) in [(Tool::Dodge, "paint.burn"), (Tool::Burn, "paint.dodge"), (Tool::Blur, "paint.sharpen"), (Tool::Sharpen, "paint.blur")] { + let mut app = app(); + app.ui.tool = tool; + let m = egui::Modifiers::ALT; + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 30.0 }, m); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some(cmd), "{tool:?} with ⌥"); + assert_eq!(app.ui.tool, tool, "the selected tool stays {tool:?}"); + } +} + +#[test] +fn clone_stamp_brush_opacity_and_flow_reach_the_painted_pixels() { + let mut app = app(); + app.run("paint.pencil", json!({"points": [[10, 10]], "size": 16, "color": "#ff0000"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = Tool::CloneStamp; + app.ui.clone_source = Some([10.0, 10.0]); + app.ui.tool_options.clone_sample = "all".into(); + app.run("tools.setBrush", json!({"brush": {"opacity": 0.5, "flow": 0.5}})).unwrap(); + assert!(finish_stroke(&mut app, Tool::CloneStamp, &[[50.0, 30.0, 1.0]], egui::Modifiers::NONE)); + assert!(!app.ui.status_error, "{}", app.ui.status); + let pixel = active(&app).surface().unwrap().rgba(50, 30); + assert!(pixel[0] > 0.9 && pixel[3] > 0.0 && pixel[3] < 0.5, "partial-opacity, partial-flow red stamp: {pixel:?}"); + let (id, params) = app.session.journal.last().unwrap(); + assert_eq!(id, "paint.cloneStamp"); + assert_eq!(params["opacity"], 50.0); + assert_eq!(params["flow"], 50.0); +} + +/// A Healing Brush whose brush holds a mode outside its menu (Overlay, restored with the tool +/// active, so no tool switch sees it) heals in Normal; the Clone Stamp keeps Overlay. +#[test] +fn healing_brush_heals_in_normal_with_a_mode_outside_its_menu() { + for (tool, want) in [(Tool::Healing, "Normal"), (Tool::CloneStamp, "Overlay")] { + let mut app = app(); + app.ui.tool = tool; + crate::paint_mouse::sync_tool_brush(&mut app); + app.session.tools.brush.mode = photocraft_color::BlendMode::Overlay; + app.ui.clone_source = Some([10.0, 10.0]); + drag(&mut app, tool); + let (_, params) = app.session.journal.last().unwrap(); + assert_eq!(params["mode"], want, "{tool:?}"); + } +} + +/// The options bar's Mode (each tool's own brush's) reaches the stamps', the History Brush's +/// and the Healing Brush's strokes, live and committed. +#[test] +fn retouch_mode_reaches_the_command() { + for (tool, cmd, mode) in [ + (Tool::CloneStamp, "paint.cloneStamp", "Multiply"), + (Tool::Healing, "paint.healingBrush", "Luminosity"), + (Tool::HistoryBrush, "paint.historyBrush", "Screen"), + (Tool::PatternStamp, "paint.patternStamp", "Overlay"), + ] { + let mut app = app(); + app.ui.tool = tool; + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": {"mode": mode}})).unwrap(); + app.ui.clone_source = Some([10.0, 10.0]); + drag(&mut app, tool); + let (id, params) = app.session.journal.last().unwrap(); + assert_eq!((id.as_str(), params["mode"].as_str()), (cmd, Some(mode)), "{tool:?}"); + } +} + +/// The Paint Bucket's Mode reaches the fill: Multiply darkens, Clear erases. +#[test] +fn paint_bucket_mode_reaches_the_fill() { + let mut app = app(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = Tool::PaintBucket; + app.session.tools.foreground = [0.5, 0.5, 0.5, 1.0]; + let click = |app: &mut PhotocraftApp| { + let m = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x: 20.0, y: 20.0 }, m); + }; + click(&mut app); + app.session.tools.foreground = [1.0, 0.0, 0.0, 1.0]; + app.ui.tool_options.bucket_blend_mode = photocraft_color::BlendMode::Multiply; + click(&mut app); + let px = active(&app).surface().unwrap().rgba(20, 20); + assert!((px[0] - 0.5).abs() < 0.02 && px[1] < 0.02, "multiplied: {px:?}"); + app.ui.tool_options.bucket_clear = true; + click(&mut app); + assert_eq!(app.session.journal.last().unwrap().1["mode"], "clear"); + assert!(active(&app).surface().unwrap().rgba(20, 20)[3] < 0.01, "cleared"); +} + +#[test] +fn clone_without_a_source_names_the_platform_modifier() { + // Option-click on the Mac, Alt-click elsewhere (#251). + for tool in [Tool::CloneStamp, Tool::Healing] { + let mut app = app(); + app.ui.tool = tool; + assert!(finish_stroke(&mut app, tool, &[[10.0, 30.0, 1.0], [50.0, 30.0, 1.0]], egui::Modifiers::NONE)); + assert!(app.ui.status_error, "{tool:?}"); + let want = if cfg!(target_os = "macos") { "Option-click" } else { "Alt-click" }; + assert!(app.ui.status.starts_with(want), "{tool:?}: {}", app.ui.status); + } +} + +#[test] +fn retouch_strokes_paint_the_targeted_mask() { + // #207: with the mask targeted, retouching changes the mask, never the pixels. + for tool in [Tool::Blur, Tool::Sharpen, Tool::Smudge, Tool::Dodge, Tool::Burn] { + let mut app = app(); + app.run("layer.new.layer", json!({})).unwrap(); + stripes(&mut app, 4, "pixels"); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + stripes(&mut app, 6, "mask"); + app.ui.mask_target = true; + app.ui.tool_options.protect_detail = false; + let b = app.session.active().unwrap().doc.bounds(); + let px0 = active(&app).surface().unwrap().read_region(b); + let mask0 = active(&app).mask.as_ref().unwrap().surface.read_region(b); + drag(&mut app, tool); + assert_eq!(active(&app).surface().unwrap().read_region(b), px0, "{tool:?}: pixels untouched"); + assert_ne!(active(&app).mask.as_ref().unwrap().surface.read_region(b), mask0, "{tool:?}: mask changed"); + } +} + +#[test] +fn sample_all_layers_reaches_the_command() { + // #207, #731: the options-bar checkbox reaches the command. + for tool in [Tool::SpotHealing, Tool::Remove, Tool::Blur, Tool::Sharpen, Tool::Smudge] { + for all in [false, true] { + let mut app = app(); + stripes(&mut app, 4, "pixels"); + app.run("layer.new.layer", json!({})).unwrap(); + *app.ui.tool_options.sample_all.slot(tool).unwrap() = all; + drag(&mut app, tool); + let a = active(&app).surface().unwrap().rgba(30, 30)[3]; + assert_eq!(a > 0.0, all, "{tool:?} sampleAllLayers={all}: alpha {a}"); + } + } +} + +#[test] +fn sample_all_layers_is_each_tools_own() { + // #5524: Sample All Layers turned on for another tool (the Magic Wand, say) left Blur and + // Smudge copying the composite onto an annotation layer, freezing a sharp patch above the + // picture. Photoshop keeps the option per tool, so those strokes leave the empty layer empty. + for tool in [Tool::Blur, Tool::Sharpen, Tool::Smudge] { + let mut app = app(); + stripes(&mut app, 4, "pixels"); + app.run("layer.new.layer", json!({})).unwrap(); + let mut others = crate::state::SampleAllLayers::default(); + for t in [ + Tool::MagicWand, + Tool::QuickSelection, + Tool::ObjectSelection, + Tool::PaintBucket, + Tool::MagicEraser, + Tool::SpotHealing, + Tool::Patch, + Tool::ContentAwareMove, + Tool::Remove, + Tool::Blur, + Tool::Sharpen, + Tool::Smudge, + ] { + if let Some(v) = others.slot(t).filter(|_| t != tool) { + *v = true; + } + } + app.ui.tool_options.sample_all = others; + assert!(!app.ui.tool_options.sample_all.get(tool)); + drag(&mut app, tool); + let a = active(&app).surface().unwrap().rgba(30, 30)[3]; + assert_eq!(a, 0.0, "{tool:?} sampled all layers through another tool's option"); + } +} + +#[test] +fn object_selection_click_falls_back_to_quick_selection() { + // A click cannot be a rectangle: it selects at the cursor instead of looking dead. + let mut app = app(); + app.ui.tool = Tool::ObjectSelection; + app.ui.tool_options.object_finder = false; + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 30.0 }, m); + assert!(!app.ui.status_error, "{}", app.ui.status); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("select.quick")); +} + +#[test] +fn object_selection_rect_runs_object_selection_and_reports() { + let mut app = app(); + app.run("paint.pencil", json!({"points": [[20, 10], [20, 50]], "size": 8, "color": "#ff0000"})).unwrap(); + app.ui.tool = Tool::ObjectSelection; + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 5.0, y: 5.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 60.0, y: 55.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 55.0 }, m); + assert!(!app.ui.status_error, "{}", app.ui.status); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("select.object")); +} + +#[test] +fn empty_smart_result_is_reported_without_error() { + // An empty smart selection (Select Subject missing on a busy photo) is an info, not + // an error and not silence: the button must visibly answer. + let mut app = app(); + report_smart_result(&mut app, Ok(json!({"selected": false, "changed": false})), "nothing there"); + assert_eq!(app.ui.status.as_str(), "nothing there"); + assert!(!app.ui.status_error); + app.ui.status.clear(); + report_smart_result(&mut app, Ok(json!({"selected": true, "changed": true})), "nothing there"); + assert!(app.ui.status.is_empty()); +} + +#[test] +fn mixer_brush_is_selectable_and_paints_only_inside_the_selection_via_control() { + use crate::control::{ControlRequest, Outcome, handle}; + + let mut app = app(); + app.run("paint.pencil", json!({"points": [[50, 30]], "size": 200, "color": "#204080"})).unwrap(); + app.run("tools.setColors", json!({"foreground": "#f02010"})).unwrap(); + app.run( + "tools.setBrush", + json!({ + "pressureSize": false, + "size": 12, + "mixer": {"wet": 0.0, "load": 1.0, "mix": 0.0, "flow": 1.0} + }), + ) + .unwrap(); + app.run("select.rect", json!({"x": 35, "y": 20, "width": 30, "height": 20})).unwrap(); + let before = { + let surface = active(&app).surface().unwrap(); + [surface.rgba(20, 30), surface.rgba(50, 30), surface.rgba(80, 30)] + }; + + let ctx = egui::Context::default(); + let (req, _rx) = ControlRequest::new( + "ui.pointer", + json!({ + "tool": "mixerBrush", + "events": [ + {"kind": "down", "x": 8, "y": 30}, + {"kind": "move", "x": 92, "y": 30}, + {"kind": "up", "x": 92, "y": 30} + ] + }), + ); + assert!(matches!(handle(&mut app, &ctx, &req), Outcome::Done(_))); + assert_eq!(app.ui.tool, Tool::MixerBrush); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.mixerBrush")); + + let surface = active(&app).surface().unwrap(); + assert_ne!(surface.rgba(50, 30), before[1], "the selected pixels are mixed"); + assert_eq!(surface.rgba(20, 30), before[0], "outside the selection is unchanged"); + assert_eq!(surface.rgba(80, 30), before[2], "the far side outside the selection is unchanged"); +} + +#[test] +fn patch_tool_lassoes_then_drags_the_patch() { + let mut app = app(); + app.run("paint.pencil", json!({"points": [[68, 30], [74, 30]], "size": 6, "color": "#ff0000"})).unwrap(); + let red = |app: &PhotocraftApp| active(app).surface().unwrap().rgba(71, 30)[1] < 0.5; + assert!(red(&app)); + app.ui.tool = Tool::Patch; + let m = egui::Modifiers::NONE; + // Outside any selection the drag is a lasso. + tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 20.0, pressure: 1.0 }, m); + for [x, y] in [[84.0, 20.0], [84.0, 40.0], [60.0, 40.0]] { + tool_event(&mut app, ToolEvent::Move { x, y, pressure: 1.0 }, m); + } + tool_event(&mut app, ToolEvent::Up { x: 60.0, y: 40.0 }, m); + assert!(app.session.active().unwrap().doc.selection.is_some(), "lasso made a selection"); + assert!(red(&app), "the lasso alone changes no pixels"); + // ⇧-drag inside the selection adds to it rather than patching. + assert!(!patch_drags_selection(&app, [70.0, 30.0], egui::Modifiers::SHIFT)); + // Dragging inside it patches from where it is dropped; the offset is limited to the canvas. + assert!(patch_drags_selection(&app, [70.0, 30.0], m)); + assert_eq!(patch_offset(&mut app, [70.0, 30.0], [-200.0, 30.0]), [-60, 0]); + tool_event(&mut app, ToolEvent::Down { x: 70.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 31.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }, m); + assert!(!app.ui.status_error, "{}", app.ui.status); + let px = active(&app).surface().unwrap().rgba(71, 30); + assert!(px[0] > 0.95 && px[1] > 0.95 && px[2] > 0.95, "blemish patched with the white background: {px:?}"); +} + +#[test] +fn patch_tool_content_aware_fills_from_where_it_is_dropped() { + let mut app = app(); + app.run("paint.pencil", json!({"points": [[68, 30], [74, 30]], "size": 6, "color": "#ff0000"})).unwrap(); + app.run("select.rect", json!({"x": 60, "y": 20, "width": 24, "height": 20})).unwrap(); + app.ui.tool = Tool::Patch; + app.ui.tool_options.patch_content_aware = true; + app.ui.tool_options.patch_structure = 5.0; + app.ui.tool_options.patch_color = 3.0; + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 70.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 31.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }, m); + assert!(!app.ui.status_error, "{}", app.ui.status); + let (id, p) = app.session.journal.last().cloned().unwrap(); + assert_eq!(id, "paint.patch"); + assert_eq!((p["contentAware"].as_bool(), p["structure"].as_f64(), p["color"].as_f64()), (Some(true), Some(5.0), Some(3.0))); + let px = active(&app).surface().unwrap().rgba(71, 30); + assert!(px[0] > 0.95 && px[1] > 0.95 && px[2] > 0.95, "blemish filled from the white background: {px:?}"); +} + +#[test] +fn content_aware_move_tool_lassoes_then_moves_or_extends() { + for (mode, keeps) in [("move", false), ("extend", true)] { + let mut app = app(); + 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_mode = mode.into(); + app.ui.tool_options.cam_structure = 7.0; + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 12.0, y: 20.0, pressure: 1.0 }, m); + for [x, y] in [[32.0, 20.0], [32.0, 40.0], [12.0, 40.0]] { + tool_event(&mut app, ToolEvent::Move { x, y, pressure: 1.0 }, m); + } + tool_event(&mut app, ToolEvent::Up { x: 12.0, y: 40.0 }, m); + assert!(app.session.active().unwrap().doc.selection.is_some(), "lasso made a selection"); + assert!(blue(&app, 22), "the lasso alone changes no pixels"); + tool_event(&mut app, ToolEvent::Down { x: 22.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 31.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 72.0, y: 30.0 }, m); + assert!(!app.ui.status_error, "{mode}: {}", app.ui.status); + assert!(blue(&app, 72), "{mode}: the content lands where it was dropped"); + assert_eq!(blue(&app, 22), keeps, "{mode}: the original place"); + assert_eq!(app.session.journal.last().map(|(id, p)| (id.as_str(), p["mode"].as_str())), Some(("paint.contentAwareMove", Some(mode)))); + let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap(); + assert!(sel.sample_channel(72, 30, 0) > 0.0 && sel.sample_channel(22, 30, 0) == 0.0, "{mode}: the selection follows"); + } +} + +#[test] +fn content_aware_move_transform_on_drop_turns_the_patch_on_enter() { + let mut app = app(); + app.run("paint.pencil", json!({"points": [[16, 30], [28, 30]], "size": 4, "color": "#0000ff"})).unwrap(); + let blue = |app: &PhotocraftApp, x: i32, y: i32| active(app).surface().unwrap().rgba(x, y)[0] < 0.5; + app.ui.tool = Tool::ContentAwareMove; + app.ui.tool_options.cam_transform_on_drop = true; + app.ui.tool_options.cam_structure = 7.0; + let m = egui::Modifiers::NONE; + let drag = |app: &mut PhotocraftApp, path: &[[f64; 2]]| { + let ([x, y], rest) = (path[0], &path[1..]); + tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, m); + for &[x, y] in rest { + tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, m); + } + let [x, y] = path[path.len() - 1]; + tool_event(app, ToolEvent::Up { x, y }, m); + }; + drag(&mut app, &[[6.0, 14.0], [38.0, 14.0], [38.0, 46.0], [6.0, 46.0]]); + let steps = app.session.active().unwrap().history.past_len(); + // The drop puts a box on the patch; nothing is computed yet. + drag(&mut app, &[[22.0, 30.0], [50.0, 30.0], [72.0, 30.0]]); + assert!(crate::cam_transform::active(&app), "{}", app.ui.status); + assert!(blue(&app, 22, 30) && !blue(&app, 72, 30), "the document waits for the commit"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + // Dragging outside the box turns it 90° about its centre (72, 30). + drag(&mut app, &[[98.0, 55.0], [60.0, 58.0], [47.0, 56.0]]); + let place = crate::cam_transform::placement(app.ui.cam_transform.as_ref().unwrap()).unwrap(); + assert_eq!((place.offset, place.scale), ([50, 0], [100.0, 100.0])); + assert!((place.rotate - 90.0).abs() < 1e-3, "{place:?}"); + crate::cam_transform::commit(&mut app); + assert!(!crate::cam_transform::active(&app) && !app.ui.status_error, "{}", app.ui.status); + let (id, p) = app.session.journal.last().unwrap(); + assert_eq!((id.as_str(), &p["offset"]), ("paint.contentAwareMove", &json!([50, 0]))); + assert!((p["rotate"].as_f64().unwrap() - 90.0).abs() < 1e-3, "{p}"); + // The horizontal line lands upright, in one History step. + assert!(blue(&app, 72, 26) && blue(&app, 72, 34), "the turned line"); + assert!(!blue(&app, 66, 30) && !blue(&app, 78, 30), "no unturned line"); + assert!(!blue(&app, 22, 30), "the old place is filled"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); +} + +#[test] +fn red_eye_click_corrects_a_pupil_and_errors_on_a_miss() { + let mut app = app(); + app.run("paint.pencil", json!({"points": [[50, 30]], "size": 18, "hardness": 100, "color": "#f21818"})).unwrap(); + let before = active(&app).surface().unwrap().rgba(50, 30); + assert!(before[0] > before[1] + 0.4, "{before:?}"); + app.ui.tool = Tool::RedEye; + // Pupil Size 15 → search radius 22 px, so a click at (8,8) cannot reach the blob at (50,30). + app.ui.tool_options.red_eye_pupil_size = 15.0; + tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 30.0 }, egui::Modifiers::NONE); + assert!(!app.ui.status_error, "{}", app.ui.status); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.redEye")); + let after = active(&app).surface().unwrap().rgba(50, 30); + assert!(after[0] < before[0] - 0.15, "before {before:?} after {after:?}"); + tool_event(&mut app, ToolEvent::Down { x: 8.0, y: 8.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 8.0, y: 8.0 }, egui::Modifiers::NONE); + assert!(app.ui.status_error); + assert!(app.ui.status.contains("no red-eye pixels"), "{}", app.ui.status); +} + +#[test] +fn red_eye_options_bar_shows_pupil_size_and_darken() { + use crate::theme::ThemeKind; + use egui::vec2; + use egui_kittest::kittest::Queryable; + let mut app = app(); + app.ui.tool = Tool::RedEye; + let mut h = egui_kittest::Harness::builder().with_size(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, ThemeKind::Studio); + h.run_steps(4); + h.get_by_label("Pupil Size"); + h.get_by_label("Darken Amount"); + assert_eq!(h.state().ui.tool_options.red_eye_pupil_size, 50.0); + assert_eq!(h.state().ui.tool_options.red_eye_darken, 50.0); +} + +#[test] +fn patch_tool_says_to_drag_the_selection_after_the_lasso_and_after_a_click() { + let hint = tl!("Now drag the selection onto another area"); + let m = egui::Modifiers::NONE; + let mut app = app(); + app.ui.tool = Tool::Patch; + app.ui.status.clear(); + // No selection yet: the drag is a lasso, which outlines the patch and says what comes next. + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 10.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 40.0, y: 10.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 40.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 20.0, y: 30.0 }, m); + assert!(app.session.active().is_some_and(|st| st.doc.selection.is_some()), "the lasso made a selection"); + assert_eq!((app.ui.status.as_str(), app.ui.status_error), (hint, false)); + // A press and release inside the selection moves nothing: it says so instead of staying silent. + app.ui.status.clear(); + tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 20.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 20.0 }, m); + assert_eq!((app.ui.status.as_str(), app.ui.status_error), (hint, false)); + assert!(app.session.active().is_some_and(|st| st.doc.selection.is_some()), "the selection stays"); +} + +#[test] +fn remove_tool_stroke_removes_what_it_covers() { + let mut app = app(); + app.run("paint.pencil", json!({"points": [[0, 30], [100, 30]], "size": 200, "color": "#808080"})).unwrap(); + app.run("paint.pencil", json!({"points": [[30, 20], [30, 40]], "size": 4, "color": "#000000"})).unwrap(); + let bg = active(&app).surface().unwrap().rgba(70, 30); + app.ui.tool = Tool::Remove; + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 18.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 30.0, y: 42.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 42.0 }, m); + assert!(!app.ui.status_error, "{}", app.ui.status); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.remove")); + let px = active(&app).surface().unwrap().rgba(30, 30); + assert!(px.iter().zip(bg).all(|(a, b)| (a - b).abs() < 0.02), "{px:?} vs {bg:?}"); +} + +#[test] +fn remove_after_each_stroke_off_collects_strokes_until_enter_or_escape() { + let mut app = app(); + app.run("paint.pencil", json!({"points": [[0, 30], [100, 30]], "size": 200, "color": "#808080"})).unwrap(); + app.run("paint.pencil", json!({"points": [[30, 20], [30, 40]], "size": 4, "color": "#000000"})).unwrap(); + app.ui.tool = Tool::Remove; + app.ui.tool_options.remove_after_each_stroke = false; + let m = egui::Modifiers::NONE; + let journal = app.session.journal.len(); + for x in [28.0, 32.0] { + tool_event(&mut app, ToolEvent::Down { x, y: 18.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x, y: 42.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x, y: 42.0 }, m); + } + // Nothing ran yet: the strokes wait, tinted, and the status says so. + assert_eq!(app.session.journal.len(), journal, "no command before Enter"); + assert_eq!(app.remove_pending.len(), 2); + assert!(app.remove_trail.is_some()); + assert!(app.ui.status.contains("2") && !app.ui.status_error, "{}", app.ui.status); + // Esc drops them. + assert!(remove_pending_cancel(&mut app)); + assert!(app.remove_pending.is_empty() && app.remove_trail.is_none()); + assert!(!remove_pending_cancel(&mut app)); + // Collected again, Enter applies them as one `paint.remove` with both strokes. + for x in [28.0, 32.0] { + tool_event(&mut app, ToolEvent::Down { x, y: 18.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x, y: 42.0 }, m); + } + let bg = active(&app).surface().unwrap().rgba(70, 30); + assert!(remove_pending_commit(&mut app)); + assert!(!app.ui.status_error, "{}", app.ui.status); + let (id, p) = app.session.journal.last().cloned().expect("a journaled command"); + assert_eq!(id, "paint.remove"); + assert_eq!(p["strokes"].as_array().map(Vec::len), Some(2)); + assert!(p.get("points").is_none()); + assert!(app.remove_pending.is_empty()); + let px = active(&app).surface().unwrap().rgba(30, 30); + assert!(px.iter().zip(bg).all(|(a, b)| (a - b).abs() < 0.02), "{px:?} vs {bg:?}"); + assert!(!remove_pending_commit(&mut app), "nothing left to apply"); +} + +#[test] +fn every_waiting_remove_stroke_is_tinted_in_full() { + // #6555: each stroke used to be stamped only past the previous stroke's point count. + let mut app = app(); + app.ui.tool = Tool::Remove; + app.ui.tool_options.remove_after_each_stroke = false; + let strokes: [&[[f64; 3]]; 3] = [ + &[[10.0, 10.0, 1.0], [40.0, 10.0, 1.0], [70.0, 10.0, 1.0]], + &[[10.0, 30.0, 1.0], [40.0, 30.0, 1.0]], + &[[10.0, 50.0, 1.0], [20.0, 50.0, 1.0], [30.0, 50.0, 1.0], [50.0, 50.0, 1.0], [90.0, 50.0, 1.0]], + ]; + for s in strokes { + remove_pending_add(&mut app, s); + } + assert_eq!(app.remove_pending.len(), 3); + let t = app.remove_trail.as_ref().expect("the waiting strokes are tinted"); + let k = f64::from(t.scale()); + for s in strokes { + for w in s.windows(2) { + for i in 0..=8 { + let f = f64::from(i) / 8.0; + let (x, y) = (w[0][0] + (w[1][0] - w[0][0]) * f, w[0][1] + (w[1][1] - w[0][1]) * f); + assert_eq!(t.coverage((x / k) as usize, (y / k) as usize), 255, "({x}, {y}) on a waiting stroke is tinted"); + } + } + } + // Enter, Esc, another tool and another document all drop the tint with the strokes. + assert!(remove_pending_commit(&mut app)); + assert!(app.remove_trail.is_none()); + remove_pending_add(&mut app, strokes[0]); + assert!(remove_pending_cancel(&mut app) && app.remove_trail.is_none()); + remove_pending_add(&mut app, strokes[1]); + app.ui.tool = Tool::SpotHealing; + assert!(!remove_pending_live(&mut app) && app.remove_trail.is_none()); + app.ui.tool = Tool::Remove; + remove_pending_add(&mut app, strokes[2]); + app.run("file.new", json!({"width": 100, "height": 60})).unwrap(); + assert!(!remove_pending_live(&mut app) && app.remove_trail.is_none()); +} + +#[test] +fn queued_remove_cannot_commit_after_layer_or_channel_target_changes() { + for change in ["layer", "color", "mask"] { + let mut app = app(); + app.run("layer.new.layer", json!({"name": "Original"})).unwrap(); + if change == "color" { + app.run("channel.target", json!({"channel": "red"})).unwrap(); + } + app.ui.tool = Tool::Remove; + app.ui.tool_options.remove_after_each_stroke = false; + remove_pending_add(&mut app, &[[12.0, 10.0, 1.0], [16.0, 12.0, 1.0]]); + assert_eq!(app.remove_pending.len(), 1); + assert!(remove_pending_live(&mut app)); + + match change { + "layer" => { + app.run("layer.new.layer", json!({"name": "Other"})).unwrap(); + } + "color" => { + app.run("channel.target", json!({"channel": "blue"})).unwrap(); + } + _ => { + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.ui.mask_target = true; + } + } + + let journal = app.session.journal.len(); + assert!(!remove_pending_commit(&mut app), "{change}: Enter must not retarget a queued stroke"); + assert_eq!(app.session.journal.len(), journal, "{change}: no Remove command ran"); + assert!(app.remove_pending.is_empty() && app.remove_trail.is_none(), "{change}: queue cleared"); + assert!(app.remove_pending_target.is_none()); + } +} + +#[test] +fn queued_remove_starts_a_new_queue_after_target_switch() { + let mut app = app(); + app.run("layer.new.layer", json!({"name": "Original"})).unwrap(); + app.ui.tool = Tool::Remove; + app.ui.tool_options.remove_after_each_stroke = false; + remove_pending_add(&mut app, &[[12.0, 10.0, 1.0], [16.0, 12.0, 1.0]]); + app.run("layer.new.layer", json!({"name": "Other"})).unwrap(); + remove_pending_add(&mut app, &[[40.0, 10.0, 1.0], [44.0, 12.0, 1.0]]); + assert_eq!(app.remove_pending.len(), 1, "strokes from different layers must not be combined"); + assert_eq!(app.remove_pending[0][0][0], 40.0); + assert!(remove_pending_live(&mut app)); +} + +#[test] +fn remove_strokes_waiting_are_dropped_when_the_tool_changes() { + let mut app = app(); + app.ui.tool = Tool::Remove; + app.ui.tool_options.remove_after_each_stroke = false; + remove_pending_add(&mut app, &[[10.0, 10.0, 1.0], [20.0, 10.0, 1.0]]); + assert_eq!(app.remove_pending.len(), 1); + assert!(remove_pending_live(&mut app)); + app.ui.tool = Tool::SpotHealing; + assert!(!remove_pending_live(&mut app)); + assert!(app.remove_pending.is_empty(), "the strokes belong to the Remove tool"); +} + +#[test] +fn create_a_new_layer_sends_new_layer_to_the_command() { + let mut app = app(); + app.run("paint.pencil", json!({"points": [[0, 30], [100, 30]], "size": 200, "color": "#808080"})).unwrap(); + app.ui.tool = Tool::Remove; + app.ui.tool_options.remove_new_layer = true; + let layers = app.session.active().unwrap().doc.walk().len(); + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 18.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 42.0 }, m); + assert!(!app.ui.status_error, "{}", app.ui.status); + let (id, p) = app.session.journal.last().cloned().unwrap(); + assert_eq!((id.as_str(), p["newLayer"].as_bool()), ("paint.remove", Some(true))); + assert_eq!(app.session.active().unwrap().doc.walk().len(), layers + 1, "the fill went to a new layer"); +} + +#[test] +fn red_eye_is_in_the_j_flyout() { + let j = [Tool::Remove, Tool::SpotHealing, Tool::Healing, Tool::Patch, Tool::ContentAwareMove, Tool::RedEye]; + assert!(j.contains(&Tool::RedEye)); + assert!(j.iter().all(|t| t.key() == 'J')); +} + +#[test] +fn j_cycles_from_remove() { + // J from another group picks the first J tool, and repeated J goes on in this order. + let group: Vec = Tool::ALL.iter().copied().filter(|t| t.key() == 'J').collect(); + assert_eq!(group, [Tool::Remove, Tool::SpotHealing, Tool::Healing, Tool::Patch, Tool::ContentAwareMove, Tool::RedEye]); +} + +#[test] +fn s_group_is_clone_stamp_then_pattern_stamp() { + assert_eq!(Tool::CloneStamp.key(), 'S'); + assert_eq!(Tool::PatternStamp.key(), 'S'); + let group: Vec = Tool::ALL.iter().copied().filter(|t| t.key() == 'S').collect(); + assert_eq!(group, vec![Tool::CloneStamp, Tool::PatternStamp]); + assert_eq!(Tool::from_name("patternStamp"), Some(Tool::PatternStamp)); +} + +#[test] +fn pattern_stamp_stroke_paints_pixels_and_keeps_phase_when_aligned() { + let mut app = app(); + assert!(finish_stroke(&mut app, Tool::PatternStamp, &[[20.0, 30.0, 1.0], [50.0, 30.0, 1.0]], egui::Modifiers::NONE)); + assert!(!app.ui.status_error, "{}", app.ui.status); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.patternStamp")); + assert!(app.ui.pattern_stamp_phase.is_some()); + let px = active(&app).surface().unwrap().rgba(30, 30); + assert!(px[3] > 0.5, "the stamp paints through the brush: {px:?}"); + app.ui.tool_options.pattern_stamp_aligned = false; + app.ui.pattern_stamp_phase = None; + assert!(finish_stroke(&mut app, Tool::PatternStamp, &[[70.0, 30.0, 1.0]], egui::Modifiers::NONE)); + assert!(app.ui.pattern_stamp_phase.is_none(), "unaligned strokes do not keep phase"); +} + +#[test] +fn pattern_stamp_does_not_require_a_clone_source() { + let mut app = app(); + assert!(app.ui.clone_source.is_none()); + assert!(finish_stroke(&mut app, Tool::PatternStamp, &[[12.0, 30.0, 1.0]], egui::Modifiers::NONE)); + assert!(!app.ui.status_error, "{}", app.ui.status); + assert!(app.ui.clone_source.is_none()); +} + +#[test] +fn art_history_is_in_the_y_flyout() { + let y = [Tool::HistoryBrush, Tool::ArtHistoryBrush]; + assert_eq!(y[0], Tool::HistoryBrush); + assert_eq!(y[1], Tool::ArtHistoryBrush); + assert!(y.iter().all(|t| t.key() == 'Y')); + assert!(Tool::ArtHistoryBrush.is_brushlike()); +} + +#[test] +fn art_history_options_bar_defaults() { + use crate::theme::ThemeKind; + use egui::vec2; + use egui_kittest::kittest::Queryable; + let mut app = app(); + app.ui.tool = Tool::ArtHistoryBrush; + let mut h = egui_kittest::Harness::builder().with_size(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, ThemeKind::Studio); + h.run_steps(4); + h.get_by_label("Style"); + h.get_by_label("Area"); + h.get_by_label("Tolerance"); + assert_eq!(h.state().ui.tool_options.art_history_style, "tightMedium"); + assert_eq!(h.state().ui.tool_options.art_history_area, 50.0); + assert_eq!(h.state().ui.tool_options.art_history_tolerance, 0.0); +} + +#[test] +fn art_history_stroke_runs_the_command() { + let mut app = app(); + app.run("paint.pencil", json!({"points": [[0, 30], [100, 30]], "size": 20, "color": "#3060c0"})).unwrap(); + app.ui.tool = Tool::ArtHistoryBrush; + app.ui.tool_options.art_history_style = "tightMedium".into(); + app.ui.tool_options.art_history_tolerance = 0.0; + drag(&mut app, Tool::ArtHistoryBrush); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.artHistoryBrush")); +} From e7c635e022e5d75350852959ecfcee42a94247b0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:03 +0000 Subject: [PATCH 079/259] refactor(ui-egui): move adjust_dialog.rs tests to adjust_dialog/tests.rs --- crates/ui-egui/src/adjust_dialog.rs | 865 +--------------------- crates/ui-egui/src/adjust_dialog/tests.rs | 862 +++++++++++++++++++++ 2 files changed, 863 insertions(+), 864 deletions(-) create mode 100644 crates/ui-egui/src/adjust_dialog/tests.rs diff --git a/crates/ui-egui/src/adjust_dialog.rs b/crates/ui-egui/src/adjust_dialog.rs index 18e32e486a..e1d61ab659 100644 --- a/crates/ui-egui/src/adjust_dialog.rs +++ b/crates/ui-egui/src/adjust_dialog.rs @@ -389,867 +389,4 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map PhotocraftApp { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 48})).unwrap(); - s.execute("edit.fill", json!({"color": "#b04020"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - PhotocraftApp::new(s, crate::Services::default()) - } - - fn app_in_mode(mode: &str) -> PhotocraftApp { - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width": 32, "height": 24, "mode": mode})).unwrap(); - PhotocraftApp::new(session, crate::Services::default()) - } - - fn arm(app: &mut PhotocraftApp, id: u64, picker: &str) { - let base = app.ui.dialog_mut(id).map(|dialog| crate::filter_dialog::params_of(&dialog.fields)).unwrap(); - let dialog = app.ui.dialog_mut(id).unwrap(); - dialog.fields.insert(CURVE_PICKER.into(), json!(picker)); - dialog.fields.insert(CURVE_PICKER_BASE.into(), base); - } - - fn channel_points(app: &PhotocraftApp, key: &str) -> Vec<[f64; 2]> { - app.ui - .dialogs - .last() - .and_then(|dialog| dialog.fields.get(key)) - .and_then(Value::as_array) - .map(|points| { - points - .iter() - .filter_map(|point| { - let point = point.as_array()?; - Some([point.first()?.as_f64()?, point.get(1)?.as_f64()?]) - }) - .collect() - }) - .unwrap_or_default() - } - - #[test] - fn every_adjustment_with_an_editor_has_a_dialog() { - for kind in adjust_editors::KINDS { - assert!(has_dialog(&format!("image.adjustments.{kind}")), "{kind}"); - } - for id in ["image.adjustments.invert", "image.adjustments.selectiveColor", "image.adjustments.desaturate", "filter.blur.gaussianBlur"] { - assert!(!has_dialog(id), "{id}"); - } - } - - /// Opens each dialog, renders it, changes a value, then cancels (document untouched) or - /// confirms (one history step). - #[test] - fn dialogs_preview_cancel_and_commit() { - for kind in adjust_editors::KINDS { - let cmd = format!("image.adjustments.{kind}"); - let mut harness = - Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); - PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); - let id = open(harness.state_mut(), &cmd).unwrap(); - harness.run_steps(3); - let before = harness.state().session.active().unwrap().revision; - let steps = harness.state().session.active().unwrap().history.past_len(); - // Change the settings the way automation does. - let sample = photocraft_engine::adjust_params::to_params( - &photocraft_engine::adjust_params::from_params(kind, &sample_params(kind), None, photocraft_doc::ColorMode::Rgb).unwrap(), - ); - let d = harness.state_mut().ui.dialog_mut(id).unwrap(); - if let Value::Object(p) = sample { - d.fields.extend(p); - } - harness.run_steps(2); - // The preview runs the real command on the proxy. - let fields = harness.state().ui.dialogs[0].fields.clone(); - let doc = harness.state().session.active().unwrap().doc.clone(); - let prev = crate::filter_dialog::preview_document( - &doc, - harness.state().session.active().unwrap().active_layer, - &cmd, - &crate::filter_dialog::params_of(&fields), - 1, - ); - assert!(prev.is_some(), "{kind}: preview"); - assert_eq!(harness.state().session.active().unwrap().revision, before, "{kind}: previewing leaves the document alone"); - let r = crate::dialogs::confirm(harness.state_mut(), id); - assert!(r.is_ok(), "{kind}: {r:?}"); - assert_eq!(harness.state().session.active().unwrap().history.past_len(), steps + 1, "{kind}: one history step"); - } - } - - fn color_balance_dialog() -> (Harness<'static, PhotocraftApp>, u64) { - // Real frame times: a double-click's two clicks must land within the double-click time. - let mut h = Harness::builder() - .with_size(egui::vec2(1200.0, 900.0)) - .with_step_dt(1.0 / 60.0) - .build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - let id = open(h.state_mut(), "image.adjustments.colorBalance").unwrap(); - let d = h.state_mut().ui.dialog_mut(id).unwrap(); - for (k, v) in - [("shadows", json!([10, 0, 0])), ("midtones", json!([40, -30, 20])), ("highlights", json!([0, 0, -15])), ("preserveLuminosity", json!(false))] - { - d.fields.insert(k.into(), v); - } - h.run_steps(3); - (h, id) - } - - fn field(h: &Harness<'static, PhotocraftApp>, id: u64, key: &str) -> Value { - h.state().ui.dialogs.iter().find(|d| d.id == id).map(|d| d.fields.get(key).cloned().unwrap_or(Value::Null)).unwrap_or(Value::Null) - } - - fn input(h: &mut Harness<'static, PhotocraftApp>, mods: egui::Modifiers, events: &[egui::Event]) { - h.event(egui::Event::ModifiersChanged(mods)); - h.run_steps(1); - for e in events { - h.event(e.clone()); - h.run_steps(1); - } - h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); - h.run_steps(3); - } - - /// Photoshop 25.4's Color Balance dialog (measured with the real application): a double-click - /// on a slider zeroes it whatever the modifiers; the wheel over a slider steps it by 1, with - /// Shift by 10 (Ctrl/Alt: 1); holding Alt turns Cancel into Reset, which zeroes every tone, - /// shows Midtones, keeps Preserve Luminosity and leaves the dialog open. - #[test] - fn color_balance_dialog_gestures_match_photoshop() { - use egui_kittest::kittest::{NodeT, Queryable}; - let (mut h, id) = color_balance_dialog(); - // The slider row's caption, not the field or slider it names. - let label = h - .query_all(egui_kittest::kittest::by().label("Cyan · Red").include_labels()) - .find(|n| n.accesskit_node().role() == egui::accesskit::Role::Label) - .map(|n| n.rect()) - .expect("Cyan · Red row"); - let at = egui::pos2(label.left() + 60.0, label.bottom() + 14.0); - let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; - input(&mut h, egui::Modifiers::ALT, &[egui::Event::PointerMoved(at), press(true), press(false), press(true), press(false)]); - assert_eq!(field(&h, id, "midtones"), json!([0.0, -30.0, 20.0]), "Alt+double-click zeroes the slider"); - assert_eq!(field(&h, id, "shadows"), json!([10, 0, 0]), "other tones untouched"); - let wheel = |n: f32, m| egui::Event::MouseWheel { - source: egui::MouseWheelSource::Unknown, - unit: egui::MouseWheelUnit::Line, - delta: egui::vec2(0.0, n), - phase: egui::TouchPhase::Move, - modifiers: m, - }; - input(&mut h, egui::Modifiers::NONE, &[egui::Event::PointerMoved(at), wheel(3.0, egui::Modifiers::NONE)]); - assert_eq!(field(&h, id, "midtones")[0], json!(3.0), "3 notches up"); - input(&mut h, egui::Modifiers::SHIFT, &[egui::Event::PointerMoved(at), wheel(2.0, egui::Modifiers::SHIFT)]); - assert_eq!(field(&h, id, "midtones")[0], json!(23.0), "Shift: 10 per notch"); - input(&mut h, egui::Modifiers::CTRL, &[egui::Event::PointerMoved(at), wheel(-1.0, egui::Modifiers::CTRL)]); - assert_eq!(field(&h, id, "midtones")[0], json!(22.0), "Ctrl: 1 per notch, down"); - // Alt turns Cancel into Reset. - assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Reset").is_none()); - h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("highlights".into(), json!([5, 5, 5])); - let tone = egui::Id::unique(("adjust-dialog", "colorBalance")).with("cb-tone"); - h.ctx.data_mut(|d| d.insert_temp(tone, 2usize)); - h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); - h.run_steps(2); - let reset = h.get_by_label("Reset").rect(); - assert!(h.query_by_label("Cancel").is_none()); - let click = - |pressed| egui::Event::PointerButton { pos: reset.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; - input(&mut h, egui::Modifiers::ALT, &[egui::Event::PointerMoved(reset.center()), click(true), click(false)]); - assert!(h.state().ui.dialogs.iter().any(|d| d.id == id), "Reset keeps the dialog open"); - for k in ["shadows", "midtones", "highlights"] { - assert_eq!(field(&h, id, k), json!([0.0, 0.0, 0.0]), "{k}"); - } - assert_eq!(field(&h, id, "preserveLuminosity"), json!(false), "Reset keeps Preserve Luminosity"); - assert_eq!(h.ctx.data(|d| d.get_temp::(tone)), Some(1), "Reset shows Midtones"); - // Without Alt it is Cancel again, and it closes. - let cancel = h.get_by_label("Cancel").rect(); - let click = - |pressed| egui::Event::PointerButton { pos: cancel.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; - input(&mut h, egui::Modifiers::NONE, &[egui::Event::PointerMoved(cancel.center()), click(true), click(false)]); - assert!(h.state().ui.dialogs.is_empty(), "Cancel closes"); - } - - /// Every adjustment kind opts into Alt+Reset; Levels restores engine defaults and stays open. - #[test] - fn levels_alt_reset_restores_defaults() { - use egui_kittest::kittest::Queryable; - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - let id = open(h.state_mut(), "image.adjustments.levels").unwrap(); - h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("inBlack".into(), json!(30)); - h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("gamma".into(), json!(1.3)); - h.run_steps(2); - assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Reset").is_none()); - h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); - h.run_steps(2); - let reset = h.get_by_label("Reset").rect(); - assert!(h.query_by_label("Cancel").is_none()); - let click = - |pressed| egui::Event::PointerButton { pos: reset.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; - input(&mut h, egui::Modifiers::ALT, &[egui::Event::PointerMoved(reset.center()), click(true), click(false)]); - assert!(h.state().ui.dialogs.iter().any(|d| d.id == id), "Reset keeps the dialog open"); - let defaults = - photocraft_engine::adjust_params::to_params(&photocraft_engine::adjust_params::default_for("levels", photocraft_doc::ColorMode::Rgb).unwrap()); - assert_eq!(field(&h, id, "inBlack"), defaults["inBlack"]); - assert_eq!(field(&h, id, "gamma"), defaults["gamma"]); - } - - fn sample_params(kind: &str) -> Value { - match kind { - "brightnessContrast" => json!({"brightness": 40}), - "levels" => json!({"inBlack": 30, "gamma": 1.3}), - "curves" => json!({"points": [[0, 0], [100, 150], [255, 255]]}), - "exposure" => json!({"exposure": 1}), - "vibrance" => json!({"vibrance": 50}), - "hueSaturation" => json!({"reds": {"hue": 40}}), - "colorBalance" => json!({"midtones": [40, 0, -20]}), - "blackWhite" => json!({"reds": 150, "tint": true}), - "photoFilter" => json!({"filter": "cooling80", "density": 60}), - "channelMixer" => json!({"red": [50, 50, 0, 0]}), - "posterize" => json!({"levels": 3}), - "threshold" => json!({"level": 90}), - "gradientMap" => json!({"stops": [[0, "#200040"], [1, "#ffd080"]]}), - _ => json!({}), - } - } - - /// #5113: the dialog should fit its curve graph instead of reserving a blank right column. - #[test] - fn curves_dialog_fits_its_graph_and_controls() { - for language in ["en", "ru"] { - let _language = crate::i18n::language_scope(crate::i18n::Lang::from_code(language).unwrap()); - for theme in crate::theme::ThemeKind::ALL { - for size in [egui::vec2(1280.0, 900.0), egui::vec2(900.0, 720.0)] { - let mut h = Harness::builder().with_size(size).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); - PhotocraftApp::setup_context(&h.ctx, theme); - let id = open(h.state_mut(), "image.adjustments.curves").unwrap(); - h.run_steps(4); - let window = h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", id)))).unwrap(); - let graph = h.ctx.data(|d| d.get_temp::(dialog_mem("curves").with("curves-graph"))).unwrap(); - assert!(window.right() - graph.right() < 40.0, "blank right column: window {window:?}, graph {graph:?}"); - assert!(graph.width() > 270.0, "keep the graph usable: {graph:?}"); - assert!(window.contains_rect(graph)); - for label in ["Channel:", "Input:", "Output:", "Preview", "OK", "Cancel"] { - // A caption and the field it names share the label; any of them is the control. - let node = h.query_all_by_label(crate::i18n::t(label)).next().unwrap_or_else(|| panic!("{label} in the dialog")); - assert!(window.contains_rect(node.rect()), "{label} inside the window"); - } - } - } - } - } - - /// #8984: the Curves dialog has a resize grip; its graph grows with the dialog, the controls - /// stay inside it, and it reopens at the size it was left at. - #[test] - fn curves_dialog_resizes_with_its_graph_and_reopens_at_that_size() { - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); - PhotocraftApp::setup_context(&h.ctx, Default::default()); - let graph = |h: &Harness<'_, PhotocraftApp>| h.ctx.data(|d| d.get_temp::(dialog_mem("curves").with("curves-graph"))).unwrap(); - let window = |h: &Harness<'_, PhotocraftApp>, id: u64| h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", id)))).unwrap(); - let id = open(h.state_mut(), "image.adjustments.curves").unwrap(); - h.run_steps(4); - let (opened, small) = (window(&h, id), graph(&h)); - assert!(small.width() > 270.0 && small.width() < 300.0, "opens at the 300-point graph: {small:?}"); - // Drag the grip (bottom-right corner) 300 points right and 200 down. - let corner = opened.max - egui::vec2(12.0, 12.0); - let by = egui::vec2(300.0, 200.0); - h.event(egui::Event::PointerMoved(corner)); - h.step(); - h.event(egui::Event::PointerButton { pos: corner, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); - h.step(); - for i in 1..=4 { - h.event(egui::Event::PointerMoved(corner + by * (i as f32 / 4.0))); - h.step(); - } - h.event(egui::Event::PointerButton { pos: corner + by, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); - h.run_steps(6); - let (wide, big) = (window(&h, id), graph(&h)); - assert!(big.width() > small.width() + 250.0, "the graph follows the dialog: {small:?} → {big:?}"); - assert!((big.width() - big.height()).abs() < 1.0, "still square: {big:?}"); - assert!(wide.contains_rect(big) && wide.right() - big.right() < 40.0, "no blank column: window {wide:?}, graph {big:?}"); - for label in ["Channel:", "Input:", "Output:", "Preview", "OK", "Cancel"] { - for node in h.get_all_by_label(crate::i18n::t(label)) { - assert!(wide.contains_rect(node.rect()), "{label} label and control stay inside the window"); - } - } - // Cancel, open again: the size it was left at. - h.get_by_label("Cancel").click(); - h.run_steps(3); - assert!(h.state().ui.dialogs.is_empty()); - let again = open(h.state_mut(), "image.adjustments.curves").unwrap(); - h.run_steps(4); - assert!((graph(&h).width() - big.width()).abs() < 2.0, "reopened at {:?}, left at {big:?}", graph(&h)); - assert!((window(&h, again).width() - wide.width()).abs() < 2.0); - } - - /// #8984: however tall the graph's width would make it, the dialog still fits the window. - #[test] - fn curves_graph_never_pushes_the_dialog_off_a_short_window() { - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 700.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); - PhotocraftApp::setup_context(&h.ctx, Default::default()); - h.ctx.data_mut(|m| m.insert_persisted(egui::Id::unique(("dialog-place", "image.adjustments.curves")).with("size"), egui::vec2(1200.0, 1200.0))); - let id = open(h.state_mut(), "image.adjustments.curves").unwrap(); - h.run_steps(5); - let graph = h.ctx.data(|d| d.get_temp::(dialog_mem("curves").with("curves-graph"))).unwrap(); - let window = h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", id)))).unwrap(); - assert!(graph.height() <= 700.0 - 360.0, "{graph:?}"); - assert!(window.height() <= 700.0, "{window:?}"); - assert!(window.contains_rect(h.get_by_label("OK").rect())); - // The size the window squeezed it to is not remembered: a larger window gets 1200 again. - let kept = h.ctx.data_mut(|m| m.get_persisted::(egui::Id::unique(("dialog-place", "image.adjustments.curves")).with("size"))); - assert_eq!(kept, Some(egui::vec2(1200.0, 1200.0))); - // Dragged far wider, the dialog stops where the graph stops: no blank column. - let corner = window.max - egui::vec2(12.0, 12.0); - h.event(egui::Event::PointerMoved(corner)); - h.step(); - h.event(egui::Event::PointerButton { pos: corner, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); - h.step(); - h.event(egui::Event::PointerMoved(corner + egui::vec2(600.0, 0.0))); - h.step(); - h.event(egui::Event::PointerButton { - pos: corner + egui::vec2(600.0, 0.0), - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }); - h.run_steps(5); - let graph = h.ctx.data(|d| d.get_temp::(dialog_mem("curves").with("curves-graph"))).unwrap(); - let window = h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", id)))).unwrap(); - assert!(window.right() - graph.right() < 40.0, "no blank column: window {window:?}, graph {graph:?}"); - } - - #[test] - fn cancel_leaves_the_document_untouched() { - let mut harness = - Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); - PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); - let id = open(harness.state_mut(), "image.adjustments.curves").unwrap(); - harness.run_steps(2); - harness.state_mut().ui.dialog_mut(id).unwrap().fields.insert("points".into(), json!([[0, 255], [255, 0]])); - harness.run_steps(2); - let before = harness.state().session.active().unwrap().doc.clone(); - harness.state_mut().ui.close_dialog(id); - harness.run_steps(2); - let after = harness.state().session.active().unwrap().doc.clone(); - assert!(std::sync::Arc::ptr_eq(&before, &after)); - assert!(harness.state().ui.dialogs.is_empty()); - } - - #[test] - fn gradient_map_dialog_handles_preview_without_committing_until_ok() { - use egui_kittest::kittest::Queryable; - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); - PhotocraftApp::setup_context(&h.ctx, Default::default()); - let id = open(h.state_mut(), "image.adjustments.gradientMap").unwrap(); - h.run_steps(4); - let doc = h.state().session.active().unwrap().doc.clone(); - let steps = h.state().session.active().unwrap().history.past_len(); - let strip = h.get_by_label("Gradient stops").rect(); - let start = egui::pos2(strip.left() + 8.0, strip.top() + 36.0); - let to = start + egui::vec2((strip.width() - 16.0) * 0.3, 0.0); - h.hover_at(start); - h.run_steps(1); - h.drag_at(start); - h.run_steps(1); - h.hover_at(to); - h.run_steps(1); - h.drop_at(to); - h.run_steps(3); - let stops = h.state().ui.dialogs[0].fields["stops"].as_array().unwrap(); - assert!((stops[0][0].as_f64().unwrap() - 0.3).abs() < 0.001); - assert!(std::sync::Arc::ptr_eq(&doc, &h.state().session.active().unwrap().doc), "dialog edits are previews"); - assert_eq!(h.state().session.active().unwrap().history.past_len(), steps); - crate::dialogs::confirm(h.state_mut(), id).unwrap(); - h.run_steps(2); - assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_eq!(*h.state().session.active().unwrap().doc, *doc); - } - #[test] - fn curves_pencil_drag_draws_the_map_and_confirm_applies_it() { - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - let steps = h.state().session.active().unwrap().history.past_len(); - let id = open(h.state_mut(), "image.adjustments.curves").unwrap(); - let fields = &mut h.state_mut().ui.dialog_mut(id).unwrap().fields; - fields.insert("pencil".into(), json!(true)); - fields.insert("points".into(), json!((0..256).collect::>())); - h.run_steps(4); - let graph = h.ctx.data(|d| d.get_temp::(egui::Id::unique(("adjust-dialog", "curves")).with("curves-graph"))).unwrap(); - let at = |i: f32, o: f32| egui::pos2(graph.left() + i / 255.0 * graph.width(), graph.bottom() - o / 255.0 * graph.height()); - h.hover_at(at(64.0, 200.0)); - h.run_steps(1); - h.drag_at(at(64.0, 200.0)); - h.run_steps(1); - for i in [100.0, 150.0, 192.0] { - h.hover_at(at(i, 200.0)); - h.run_steps(1); - } - h.drop_at(at(192.0, 200.0)); - h.run_steps(3); - let map = h.state().ui.dialogs[0].fields["points"].as_array().unwrap().clone(); - assert_eq!(map.len(), 256); - assert!((70..185).all(|k| (map[k].as_f64().unwrap() - 200.0).abs() < 3.0), "{map:?}"); - assert_eq!(map[20].as_f64(), Some(20.0), "outside the stroke the map is untouched"); - crate::dialogs::confirm(h.state_mut(), id).unwrap(); - assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1); - } - - #[test] - fn curves_pointer_drag_previews_until_confirm_and_cancel_preserves_document() { - for confirm in [false, true] { - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - let original = h.state().session.active().unwrap().doc.clone(); - let steps = h.state().session.active().unwrap().history.past_len(); - let id = open(h.state_mut(), "image.adjustments.curves").unwrap(); - h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("points".into(), json!([[0, 0], [128, 128], [255, 255]])); - h.run_steps(4); - let graph = h.ctx.data(|d| d.get_temp::(egui::Id::unique(("adjust-dialog", "curves")).with("curves-graph"))).unwrap(); - let a = egui::pos2(graph.left() + 128.0 / 255.0 * graph.width(), graph.bottom() - 128.0 / 255.0 * graph.height()); - h.hover_at(a); - h.run_steps(1); - h.drag_at(a); - h.run_steps(1); - h.hover_at(a + egui::vec2(40.0, -32.0)); - h.run_steps(1); - h.drop_at(a + egui::vec2(40.0, -32.0)); - h.run_steps(3); - let points = &h.state().ui.dialogs[0].fields["points"]; - assert_eq!(points.as_array().unwrap().len(), 3); - assert!(points[1][0].as_f64().unwrap() > 150.0 && points[1][1].as_f64().unwrap() > 150.0, "{points}"); - assert!(std::sync::Arc::ptr_eq(&original, &h.state().session.active().unwrap().doc)); - assert_eq!(h.state().session.active().unwrap().history.past_len(), steps); - if confirm { - crate::dialogs::confirm(h.state_mut(), id).unwrap(); - assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert!(std::sync::Arc::ptr_eq(&original, &h.state().session.active().unwrap().doc)); - } else { - h.state_mut().ui.close_dialog(id); - h.run_steps(2); - assert!(std::sync::Arc::ptr_eq(&original, &h.state().session.active().unwrap().doc)); - } - } - } - - #[test] - fn curves_eyedroppers_sample_repeatedly_without_editing_the_document() { - let mut app = app_with_image(); - let original = app.session.active().unwrap().doc.clone(); - let revision = app.session.active().unwrap().revision; - let steps = app.session.active().unwrap().history.past_len(); - let id = open(&mut app, "image.adjustments.curves").unwrap(); - arm(&mut app, id, "black"); - assert!(picker_armed(&app)); - assert!(sample_at(&mut app, 8.0, 8.0)); - let first = channel_points(&app, "red"); - assert!((first[0][0] - 176.0).abs() < 0.6 && first[0][1] == 0.0, "{first:?}"); - assert!(sample_at(&mut app, 8.0, 8.0)); - assert_eq!(channel_points(&app, "red"), first, "the same repeated sample is deterministic"); - assert!(sample_at(&mut app, 48.0, 8.0)); - assert_ne!(channel_points(&app, "red"), first); - assert!(sample_at(&mut app, 8.0, 8.0)); - assert_eq!(channel_points(&app, "red"), first, "repeated samples resolve from the armed baseline"); - let st = app.session.active().unwrap(); - assert!(std::sync::Arc::ptr_eq(&st.doc, &original)); - assert_eq!(st.revision, revision); - assert_eq!(st.history.past_len(), steps); - } - - /// #3116: the Levels dialog's Set White Point moves each channel's input white to the sample - /// (#b04020) and leaves the document alone until OK. - #[test] - fn levels_white_point_eyedropper_sets_the_channel_input_whites() { - let mut app = app_with_image(); - let original = app.session.active().unwrap().doc.clone(); - let id = open(&mut app, "image.adjustments.levels").unwrap(); - arm(&mut app, id, "white"); - assert!(picker_armed(&app)); - assert!(sample_at(&mut app, 8.0, 8.0)); - let in_white = |key: &str| app.ui.dialogs.last().and_then(|d| d.fields.get(key)).and_then(|c| c.get("inWhite")).and_then(Value::as_f64); - assert_eq!([in_white("red"), in_white("green"), in_white("blue")], [Some(176.0), Some(64.0), Some(32.0)]); - assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original)); - } - - #[test] - fn curves_picker_controls_arm_and_disable_by_document_mode() { - let harness = |app| { - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - open(h.state_mut(), "image.adjustments.curves").unwrap(); - h.run_steps(3); - h - }; - let mut rgb = harness(app_in_mode("rgb")); - for label in ["Set Black Point", "Set Neutral Gray Point", "Set White Point"] { - assert!(!rgb.get_by_label(label).accesskit_node().is_disabled(), "{label}"); - } - rgb.get_by_label("Set Black Point").click(); - rgb.run_steps(2); - assert!(picker_armed(rgb.state())); - assert_eq!(rgb.state().ui.dialogs.last().and_then(|d| d.fields.get(CURVE_PICKER)).and_then(Value::as_str), Some("black")); - - let gray = harness(app_in_mode("gray")); - assert!(!gray.get_by_label("Set Black Point").accesskit_node().is_disabled()); - assert!(gray.get_by_label("Set Neutral Gray Point").accesskit_node().is_disabled()); - assert!(!gray.get_by_label("Set White Point").accesskit_node().is_disabled()); - - for mode in ["cmyk", "lab"] { - let h = harness(app_in_mode(mode)); - for label in ["Set Black Point", "Set Neutral Gray Point", "Set White Point"] { - assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{mode}: {label}"); - } - } - } - - #[test] - fn curves_picker_rejects_outside_and_transparent_samples() { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 32, "height": 24, "background": "transparent"})).unwrap(); - let mut app = PhotocraftApp::new(s, crate::Services::default()); - let id = open(&mut app, "image.adjustments.curves").unwrap(); - arm(&mut app, id, "white"); - let before = crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields); - assert!(sample_at(&mut app, -1.0, 4.0)); - assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields), before); - assert!(sample_at(&mut app, 4.0, 4.0)); - assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields), before); - assert!(picker_armed(&app), "an invalid sample does not disarm the picker"); - } - - #[test] - fn curves_picker_cancel_and_confirm_keep_one_transaction() { - for confirm in [false, true] { - let mut app = app_with_image(); - let original = app.session.active().unwrap().doc.clone(); - let steps = app.session.active().unwrap().history.past_len(); - let id = open(&mut app, "image.adjustments.curves").unwrap(); - arm(&mut app, id, "white"); - assert!(sample_at(&mut app, 8.0, 8.0)); - assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original)); - assert_eq!(app.session.active().unwrap().history.past_len(), steps); - if confirm { - crate::dialogs::confirm(&mut app, id).unwrap(); - let committed = app.session.active().unwrap().doc.clone(); - assert!(!std::sync::Arc::ptr_eq(&committed, &original)); - assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); - app.run("edit.undo", json!({})).unwrap(); - assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original)); - app.run("edit.redo", json!({})).unwrap(); - assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &committed)); - } else { - app.ui.close_dialog(id); - assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original)); - assert_eq!(app.session.active().unwrap().history.past_len(), steps); - } - } - } - - #[test] - fn curves_picker_modes_and_depths_are_explicit() { - use photocraft_engine::adjust_params::CurvesEyedropper; - assert!(picker_supported(photocraft_doc::ColorMode::Rgb, CurvesEyedropper::NeutralGray)); - assert!(picker_supported(photocraft_doc::ColorMode::Grayscale, CurvesEyedropper::Black)); - assert!(picker_supported(photocraft_doc::ColorMode::Grayscale, CurvesEyedropper::White)); - assert!(!picker_supported(photocraft_doc::ColorMode::Grayscale, CurvesEyedropper::NeutralGray)); - assert!(!picker_supported(photocraft_doc::ColorMode::Cmyk, CurvesEyedropper::Black)); - assert!(!picker_supported(photocraft_doc::ColorMode::Lab, CurvesEyedropper::White)); - - for depth in [8, 16, 32] { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap(); - s.execute("edit.fill", json!({"color": [0.3142, 0.4821, 0.7137]})).unwrap(); - let mut app = PhotocraftApp::new(s, crate::Services::default()); - let sampled = crate::canvas::composite_color(&mut app, 4.0, 4.0).unwrap(); - let id = open(&mut app, "image.adjustments.curves").unwrap(); - arm(&mut app, id, "gray"); - assert!(sample_at(&mut app, 4.0, 4.0), "RGB @{depth}"); - let red = channel_points(&app, "red"); - let target_level = (f64::from(sampled[0]) * 0.2126 + f64::from(sampled[1]) * 0.7152 + f64::from(sampled[2]) * 0.0722) * 255.0; - let sample_level = f64::from(sampled[0]) * 255.0; - let serialized_sample_level = (sample_level * 100.0).round() / 100.0; - let neutral_anchor = red.iter().find(|point| (point[0] - serialized_sample_level).abs() < 1e-5).unwrap(); - let serialized_target_level = (target_level * 100.0).round() / 100.0; - assert!((neutral_anchor[1] - serialized_target_level).abs() < 1e-5, "depth={depth} anchor={neutral_anchor:?} sampled={sampled:?}"); - assert!((neutral_anchor[0] - sample_level).abs() <= 0.0051, "depth={depth} anchor={neutral_anchor:?} sampled={}", sampled[0]); - if depth == 16 || depth == 32 { - assert!( - (sampled[0] * 255.0 - (sampled[0] * 255.0).round()).abs() > 0.01, - "depth={depth} sample was quantized to an 8-bit level: {}", - sampled[0] - ); - } - } - } - - fn pointer_down(app: &mut PhotocraftApp, ctx: &egui::Context, x: f64, y: f64, modifiers: Value) { - let (request, _receiver) = - crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "down", "x": x, "y": y}], "modifiers": modifiers})); - let _ = crate::control::handle(app, ctx, &request); - } - - /// The Curves curve `pts` (0-255 levels) as a 256-entry 0-255 map. - fn curve_levels(pts: &[[f64; 2]]) -> Vec { - let cp: Vec<_> = pts.iter().map(|q| photocraft_doc::adjust::CurvePoint { input: q[0] as f32 / 255.0, output: q[1] as f32 / 255.0 }).collect(); - let lut = photocraft_compose::adjust::curve_lut(&cp); - (0..256).map(|k| lut[(k as f32 / 255.0 * (lut.len() - 1) as f32).round() as usize] * 255.0).collect() - } - - /// #7325: ⌘/Ctrl-click on the image puts a point on the shown curve at the pixel's tone - /// (#b04020: Rec. 709 luma 85.5 → level 86) and at the curve's own output there, so the - /// image does not change; the new point is the selected one, and the document waits for OK. - #[test] - fn command_click_on_the_image_adds_a_point_on_the_composite_curve() { - let mut app = app_with_image(); - let original = app.session.active().unwrap().doc.clone(); - let steps = app.session.active().unwrap().history.past_len(); - let id = open(&mut app, "image.adjustments.curves").unwrap(); - let base = [[0.0, 0.0], [128.0, 200.0], [255.0, 255.0]]; - app.ui.dialog_mut(id).unwrap().fields.insert("points".into(), json!(base)); - let ctx = egui::Context::default(); - let sample = crate::canvas::composite_color(&mut app, 8.0, 8.0).unwrap(); - let level = ((sample[0] * 0.2126 + sample[1] * 0.7152 + sample[2] * 0.0722) * 255.0).round(); - assert_eq!(level, 86.0); - let output = f64::from(curve_levels(&base)[86].round()); - assert_ne!(output, 86.0, "the base curve is not the identity at the sampled level"); - - pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true})); - let points = channel_points(&app, "points"); - assert_eq!(points, vec![base[0], [86.0, output], base[1], base[2]]); - let (before, after) = (curve_levels(&base), curve_levels(&points)); - assert!(before.iter().zip(&after).all(|(a, b)| (a - b).abs() <= 0.5), "the curve keeps its shape:\n{before:?}\n{after:?}"); - let st: crate::state::CurvesEditorState = ctx.data(|d| d.get_temp(dialog_mem("curves").with("curves"))).unwrap(); - assert_eq!((st.channel, st.gesture.selected), (0, Some(1)), "the new point is selected"); - for key in ["red", "green", "blue"] { - assert_eq!(channel_points(&app, key), vec![[0.0, 0.0], [255.0, 255.0]], "{key} untouched"); - } - assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original)); - assert_eq!(app.session.active().unwrap().history.past_len(), steps); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); - } - - /// #7325: Shift+⌘-click puts a point on each colour channel at that channel's own value - /// (176, 64, 32), and leaves the composite curve alone. - #[test] - fn shift_command_click_adds_a_point_on_each_colour_channel() { - let mut app = app_with_image(); - open(&mut app, "image.adjustments.curves").unwrap(); - let ctx = egui::Context::default(); - let composite = channel_points(&app, "points"); - pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true, "shift": true})); - for (key, level) in [("red", 176.0), ("green", 64.0), ("blue", 32.0)] { - assert_eq!(channel_points(&app, key), vec![[0.0, 0.0], [level, level], [255.0, 255.0]], "{key}"); - } - assert_eq!(channel_points(&app, "points"), composite); - } - - /// #7325: with Red shown in the Channel popup the point goes on the red curve, at red's value. - #[test] - fn command_click_adds_the_point_on_the_channel_shown_in_the_dialog() { - let mut app = app_with_image(); - open(&mut app, "image.adjustments.curves").unwrap(); - let ctx = egui::Context::default(); - ctx.data_mut(|d| d.insert_temp(dialog_mem("curves").with("curves-ch"), 1usize)); - let composite = channel_points(&app, "points"); - pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true})); - assert_eq!(channel_points(&app, "red"), vec![[0.0, 0.0], [176.0, 176.0], [255.0, 255.0]]); - for key in ["green", "blue"] { - assert_eq!(channel_points(&app, key), vec![[0.0, 0.0], [255.0, 255.0]], "{key} untouched"); - } - assert_eq!(channel_points(&app, "points"), composite); - let st: crate::state::CurvesEditorState = ctx.data(|d| d.get_temp(dialog_mem("curves").with("curves"))).unwrap(); - assert_eq!((st.channel, st.gesture.selected), (1, Some(1))); - } - - /// #7325: a plain click, a full curve and an armed eyedropper add nothing. - #[test] - fn command_click_adds_nothing_without_the_modifier_on_a_full_curve_or_with_an_eyedropper() { - let mut app = app_with_image(); - let id = open(&mut app, "image.adjustments.curves").unwrap(); - let ctx = egui::Context::default(); - let before = crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields); - pointer_down(&mut app, &ctx, 8.0, 8.0, json!({})); - assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields), before, "no modifier, no point"); - // Space and the middle button pan, as with the mouse. - for extra in [json!({"modifiers": {"command": true, "space": true}}), json!({"command": true, "button": "middle"})] { - let mut params = json!({"events": [{"kind": "down", "x": 8, "y": 8}]}); - params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); - let (request, _receiver) = crate::control::ControlRequest::new("ui.pointer", params); - let _ = crate::control::handle(&mut app, &ctx, &request); - assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields), before, "{extra}"); - } - - // Sixteen points (the most a curve holds), none within reach of level 86. - let full: Vec<[f64; 2]> = - [0, 10, 20, 30, 40, 50, 60, 70, 80, 100, 120, 140, 160, 180, 200, 255].iter().map(|&i| [f64::from(i), f64::from(i)]).collect(); - app.ui.dialog_mut(id).unwrap().fields.insert("points".into(), json!(full)); - pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true})); - assert_eq!(channel_points(&app, "points"), full, "a full curve takes no more points and moves none"); - - let mut app = app_with_image(); - let id = open(&mut app, "image.adjustments.curves").unwrap(); - arm(&mut app, id, "black"); - pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true})); - assert_eq!(channel_points(&app, "points").len(), 2, "the armed eyedropper samples instead"); - assert_eq!(channel_points(&app, "red")[0], [176.0, 0.0]); - } - - /// #7325: Lab and CMYK curves and a targeted mask are left to a later change: nothing is added. - #[test] - fn command_click_adds_nothing_in_lab_or_on_a_targeted_mask() { - let ctx = egui::Context::default(); - let mut lab = app_in_mode("lab"); - lab.run("edit.fill", json!({"color": "#b04020"})).unwrap(); - let id = open(&mut lab, "image.adjustments.curves").unwrap(); - let before = crate::filter_dialog::params_of(&lab.ui.dialog_mut(id).unwrap().fields); - assert!(add_point_at(&mut lab, &ctx, 4.0, 4.0, false)); - assert_eq!(crate::filter_dialog::params_of(&lab.ui.dialog_mut(id).unwrap().fields), before); - - let mut masked = app_with_image(); - masked.run("layer.layerMask.revealAll", json!({})).unwrap(); - masked.run("channel.target", json!({"channel": "mask"})).unwrap(); - let id = open(&mut masked, "image.adjustments.curves").unwrap(); - let before = crate::filter_dialog::params_of(&masked.ui.dialog_mut(id).unwrap().fields); - assert!(add_point_at(&mut masked, &ctx, 8.0, 8.0, false)); - assert_eq!(crate::filter_dialog::params_of(&masked.ui.dialog_mut(id).unwrap().fields), before); - } - - #[test] - fn ui_pointer_drives_an_armed_curves_picker() { - let mut app = app_with_image(); - let id = open(&mut app, "image.adjustments.curves").unwrap(); - arm(&mut app, id, "black"); - let context = egui::Context::default(); - let before = channel_points(&app, "red"); - let (request, _receiver) = crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "move", "x": 48, "y": 8}]})); - let _ = crate::control::handle(&mut app, &context, &request); - assert_eq!(channel_points(&app, "red"), before, "pointer move does not sample"); - - let (request, _receiver) = crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "down", "x": 8, "y": 8}]})); - let _ = crate::control::handle(&mut app, &context, &request); - let red = channel_points(&app, "red"); - assert!((red[0][0] - 176.0).abs() < 0.6 && red[0][1] == 0.0, "{red:?}"); - assert_ne!(red, before, "pointer down samples"); - - let (request, _receiver) = crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "up", "x": 48, "y": 8}]})); - let _ = crate::control::handle(&mut app, &context, &request); - assert_eq!(channel_points(&app, "red"), red, "pointer up does not sample again"); - assert!(picker_armed(&app)); - } - - /// #5335: a targeted mask, saved channel or colour component is the only Channel popup entry. - #[test] - fn curves_channel_popup_lists_only_the_targeted_channel() { - let mut app = app_with_image(); - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - app.run("channel.target", json!({"channel": "mask"})).unwrap(); - let mut h = curves_harness(app); - let names = popup_channels(&mut h); - assert!(names.iter().any(|n| n.contains("Mask")), "{names:?}"); - assert!(!names.iter().any(|n| n == "RGB" || n == "Red" || n == "Green" || n == "Blue"), "{names:?}"); - } - - /// #5335: selecting the mask in the Layers panel gives the same Curves dropdown as selecting - /// it in the Channels panel. - #[test] - fn curves_channel_popup_lists_only_the_mask_selected_in_the_layers_panel() { - let mut app = app_with_image(); - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - app.ui.mask_target = true; // clicking the mask thumbnail in the Layers panel - assert!(app.layer_mask_targeted(), "the Layers panel mask thumbnail is targeted"); - let mut h = curves_harness(app); - let names = popup_channels(&mut h); - assert_eq!(names.len(), 1, "only the mask: {names:?}"); - assert!(names[0].contains("Mask"), "{names:?}"); - } - - /// #5335: in a Lab document, Curves over a gray target keeps neutral fields: no Lab records - /// to overwrite the mask's own curve or pick the wrong tone space. - #[test] - fn curves_on_a_gray_target_seeds_neutral_fields_in_a_lab_document() { - for via_layers_panel in [false, true] { - let mut app = app_in_mode("lab"); - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - if via_layers_panel { - app.ui.mask_target = true; - } else { - app.run("channel.target", json!({"channel": "mask"})).unwrap(); - } - let id = open(&mut app, "image.adjustments.curves").expect("opens"); - let values = crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields.clone()); - assert!(values.get("points").is_some(), "{values:?}"); - for key in ["lightness", "a", "b", "cyan", "magenta", "yellow", "black"] { - assert!(values.get(key).is_none(), "{key} in a gray target's curves: {values:?}"); - } - } - } - - /// #5335: in Italian the built-in labels translate, but a channel the user named "Green" - /// stays exactly "Green". - #[test] - fn curves_channel_popup_keeps_custom_names_verbatim_in_italian() { - let it = crate::i18n::Lang::from_code("it").expect("it registered"); - let green = crate::i18n::tr(it, "Green"); - let _lang = crate::i18n::language_scope(it); - let mut app = app_with_image(); - app.run("channel.new", json!({"name": "Green", "fill": "white"})).unwrap(); - app.run("channel.target", json!({"channel": 0})).unwrap(); - let mut h = curves_harness(app); - let names = popup_channels(&mut h); - assert!(names.iter().any(|n| n == "Green"), "custom names stay as entered: {names:?}"); - assert!(green == "Green" || !names.iter().any(|n| n == green), "not translated: {names:?}"); - // A targeted colour component keeps its translated built-in label. - let mut colour = app_with_image(); - colour.run("channel.target", json!({"channel": {"color": 1}})).unwrap(); - let mut h = curves_harness(colour); - let names = popup_channels(&mut h); - assert!(names.iter().any(|n| n == green), "built-in labels follow the language: {names:?}"); - } - - /// Curves open in a harness over `app`. - fn curves_harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, Default::default()); - open(h.state_mut(), "image.adjustments.curves").unwrap(); - h.run_steps(4); - h - } - - /// The Channel popup's selected value (its option labels are what it shows). - fn popup_channels(h: &mut Harness<'static, PhotocraftApp>) -> Vec { - h.query_all_by_role(egui::accesskit::Role::ComboBox).filter_map(|n| n.value().map(|s| s.to_string())).collect() - } - - /// FILE-215-3: Curves on a targeted filter mask edits a gray plane, and its histogram is the - /// filter mask's, not the smart object's colours. - #[test] - fn curves_on_a_targeted_filter_mask_is_a_gray_plane() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); - app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - app.run("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); - let id = app.session.active().unwrap().active_layer.unwrap(); - app.select_filter_mask_target(Some(id.0)); - assert!(app.filter_mask_targeted()); - let c = isolated(&app).expect("a gray target"); - assert_eq!(c.gray, Some(photocraft_engine::channel_cmds::GraySurface::FilterMask)); - // Its histogram counts the filter mask's levels: half black after a stroke. - app.run("paint.stroke", json!({"points": [[8, 0], [8, 31]], "size": 16, "hardness": 1, "color": "#000000", "target": "filterMask"})).unwrap(); - let surface = photocraft_engine::channel_cmds::GraySurface::FilterMask; - let st = app.session.active().unwrap(); - let h = tone::compute_histograms(&st.doc, HistSource::Channel { layer: id, surface }, photocraft_doc::adjust::ToneSpace::Rgb); - assert!(h.ch[0][0] > 0 && h.ch[0][255] > 0, "black and white levels"); - assert_eq!(curve_mode(&app, "curves"), photocraft_doc::ColorMode::Grayscale); - } -} +mod tests; diff --git a/crates/ui-egui/src/adjust_dialog/tests.rs b/crates/ui-egui/src/adjust_dialog/tests.rs new file mode 100644 index 0000000000..e8bee2b4c7 --- /dev/null +++ b/crates/ui-egui/src/adjust_dialog/tests.rs @@ -0,0 +1,862 @@ +use super::*; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; + +fn app_with_image() -> PhotocraftApp { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 48})).unwrap(); + s.execute("edit.fill", json!({"color": "#b04020"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + PhotocraftApp::new(s, crate::Services::default()) +} + +fn app_in_mode(mode: &str) -> PhotocraftApp { + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 32, "height": 24, "mode": mode})).unwrap(); + PhotocraftApp::new(session, crate::Services::default()) +} + +fn arm(app: &mut PhotocraftApp, id: u64, picker: &str) { + let base = app.ui.dialog_mut(id).map(|dialog| crate::filter_dialog::params_of(&dialog.fields)).unwrap(); + let dialog = app.ui.dialog_mut(id).unwrap(); + dialog.fields.insert(CURVE_PICKER.into(), json!(picker)); + dialog.fields.insert(CURVE_PICKER_BASE.into(), base); +} + +fn channel_points(app: &PhotocraftApp, key: &str) -> Vec<[f64; 2]> { + app.ui + .dialogs + .last() + .and_then(|dialog| dialog.fields.get(key)) + .and_then(Value::as_array) + .map(|points| { + points + .iter() + .filter_map(|point| { + let point = point.as_array()?; + Some([point.first()?.as_f64()?, point.get(1)?.as_f64()?]) + }) + .collect() + }) + .unwrap_or_default() +} + +#[test] +fn every_adjustment_with_an_editor_has_a_dialog() { + for kind in adjust_editors::KINDS { + assert!(has_dialog(&format!("image.adjustments.{kind}")), "{kind}"); + } + for id in ["image.adjustments.invert", "image.adjustments.selectiveColor", "image.adjustments.desaturate", "filter.blur.gaussianBlur"] { + assert!(!has_dialog(id), "{id}"); + } +} + +/// Opens each dialog, renders it, changes a value, then cancels (document untouched) or +/// confirms (one history step). +#[test] +fn dialogs_preview_cancel_and_commit() { + for kind in adjust_editors::KINDS { + let cmd = format!("image.adjustments.{kind}"); + let mut harness = + Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(harness.state_mut(), &cmd).unwrap(); + harness.run_steps(3); + let before = harness.state().session.active().unwrap().revision; + let steps = harness.state().session.active().unwrap().history.past_len(); + // Change the settings the way automation does. + let sample = photocraft_engine::adjust_params::to_params( + &photocraft_engine::adjust_params::from_params(kind, &sample_params(kind), None, photocraft_doc::ColorMode::Rgb).unwrap(), + ); + let d = harness.state_mut().ui.dialog_mut(id).unwrap(); + if let Value::Object(p) = sample { + d.fields.extend(p); + } + harness.run_steps(2); + // The preview runs the real command on the proxy. + let fields = harness.state().ui.dialogs[0].fields.clone(); + let doc = harness.state().session.active().unwrap().doc.clone(); + let prev = crate::filter_dialog::preview_document( + &doc, + harness.state().session.active().unwrap().active_layer, + &cmd, + &crate::filter_dialog::params_of(&fields), + 1, + ); + assert!(prev.is_some(), "{kind}: preview"); + assert_eq!(harness.state().session.active().unwrap().revision, before, "{kind}: previewing leaves the document alone"); + let r = crate::dialogs::confirm(harness.state_mut(), id); + assert!(r.is_ok(), "{kind}: {r:?}"); + assert_eq!(harness.state().session.active().unwrap().history.past_len(), steps + 1, "{kind}: one history step"); + } +} + +fn color_balance_dialog() -> (Harness<'static, PhotocraftApp>, u64) { + // Real frame times: a double-click's two clicks must land within the double-click time. + let mut h = Harness::builder() + .with_size(egui::vec2(1200.0, 900.0)) + .with_step_dt(1.0 / 60.0) + .build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(h.state_mut(), "image.adjustments.colorBalance").unwrap(); + let d = h.state_mut().ui.dialog_mut(id).unwrap(); + for (k, v) in + [("shadows", json!([10, 0, 0])), ("midtones", json!([40, -30, 20])), ("highlights", json!([0, 0, -15])), ("preserveLuminosity", json!(false))] + { + d.fields.insert(k.into(), v); + } + h.run_steps(3); + (h, id) +} + +fn field(h: &Harness<'static, PhotocraftApp>, id: u64, key: &str) -> Value { + h.state().ui.dialogs.iter().find(|d| d.id == id).map(|d| d.fields.get(key).cloned().unwrap_or(Value::Null)).unwrap_or(Value::Null) +} + +fn input(h: &mut Harness<'static, PhotocraftApp>, mods: egui::Modifiers, events: &[egui::Event]) { + h.event(egui::Event::ModifiersChanged(mods)); + h.run_steps(1); + for e in events { + h.event(e.clone()); + h.run_steps(1); + } + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(3); +} + +/// Photoshop 25.4's Color Balance dialog (measured with the real application): a double-click +/// on a slider zeroes it whatever the modifiers; the wheel over a slider steps it by 1, with +/// Shift by 10 (Ctrl/Alt: 1); holding Alt turns Cancel into Reset, which zeroes every tone, +/// shows Midtones, keeps Preserve Luminosity and leaves the dialog open. +#[test] +fn color_balance_dialog_gestures_match_photoshop() { + use egui_kittest::kittest::{NodeT, Queryable}; + let (mut h, id) = color_balance_dialog(); + // The slider row's caption, not the field or slider it names. + let label = h + .query_all(egui_kittest::kittest::by().label("Cyan · Red").include_labels()) + .find(|n| n.accesskit_node().role() == egui::accesskit::Role::Label) + .map(|n| n.rect()) + .expect("Cyan · Red row"); + let at = egui::pos2(label.left() + 60.0, label.bottom() + 14.0); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; + input(&mut h, egui::Modifiers::ALT, &[egui::Event::PointerMoved(at), press(true), press(false), press(true), press(false)]); + assert_eq!(field(&h, id, "midtones"), json!([0.0, -30.0, 20.0]), "Alt+double-click zeroes the slider"); + assert_eq!(field(&h, id, "shadows"), json!([10, 0, 0]), "other tones untouched"); + let wheel = |n: f32, m| egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, n), + phase: egui::TouchPhase::Move, + modifiers: m, + }; + input(&mut h, egui::Modifiers::NONE, &[egui::Event::PointerMoved(at), wheel(3.0, egui::Modifiers::NONE)]); + assert_eq!(field(&h, id, "midtones")[0], json!(3.0), "3 notches up"); + input(&mut h, egui::Modifiers::SHIFT, &[egui::Event::PointerMoved(at), wheel(2.0, egui::Modifiers::SHIFT)]); + assert_eq!(field(&h, id, "midtones")[0], json!(23.0), "Shift: 10 per notch"); + input(&mut h, egui::Modifiers::CTRL, &[egui::Event::PointerMoved(at), wheel(-1.0, egui::Modifiers::CTRL)]); + assert_eq!(field(&h, id, "midtones")[0], json!(22.0), "Ctrl: 1 per notch, down"); + // Alt turns Cancel into Reset. + assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Reset").is_none()); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("highlights".into(), json!([5, 5, 5])); + let tone = egui::Id::unique(("adjust-dialog", "colorBalance")).with("cb-tone"); + h.ctx.data_mut(|d| d.insert_temp(tone, 2usize)); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); + h.run_steps(2); + let reset = h.get_by_label("Reset").rect(); + assert!(h.query_by_label("Cancel").is_none()); + let click = + |pressed| egui::Event::PointerButton { pos: reset.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; + input(&mut h, egui::Modifiers::ALT, &[egui::Event::PointerMoved(reset.center()), click(true), click(false)]); + assert!(h.state().ui.dialogs.iter().any(|d| d.id == id), "Reset keeps the dialog open"); + for k in ["shadows", "midtones", "highlights"] { + assert_eq!(field(&h, id, k), json!([0.0, 0.0, 0.0]), "{k}"); + } + assert_eq!(field(&h, id, "preserveLuminosity"), json!(false), "Reset keeps Preserve Luminosity"); + assert_eq!(h.ctx.data(|d| d.get_temp::(tone)), Some(1), "Reset shows Midtones"); + // Without Alt it is Cancel again, and it closes. + let cancel = h.get_by_label("Cancel").rect(); + let click = + |pressed| egui::Event::PointerButton { pos: cancel.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + input(&mut h, egui::Modifiers::NONE, &[egui::Event::PointerMoved(cancel.center()), click(true), click(false)]); + assert!(h.state().ui.dialogs.is_empty(), "Cancel closes"); +} + +/// Every adjustment kind opts into Alt+Reset; Levels restores engine defaults and stays open. +#[test] +fn levels_alt_reset_restores_defaults() { + use egui_kittest::kittest::Queryable; + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(h.state_mut(), "image.adjustments.levels").unwrap(); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("inBlack".into(), json!(30)); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("gamma".into(), json!(1.3)); + h.run_steps(2); + assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Reset").is_none()); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); + h.run_steps(2); + let reset = h.get_by_label("Reset").rect(); + assert!(h.query_by_label("Cancel").is_none()); + let click = + |pressed| egui::Event::PointerButton { pos: reset.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; + input(&mut h, egui::Modifiers::ALT, &[egui::Event::PointerMoved(reset.center()), click(true), click(false)]); + assert!(h.state().ui.dialogs.iter().any(|d| d.id == id), "Reset keeps the dialog open"); + let defaults = + photocraft_engine::adjust_params::to_params(&photocraft_engine::adjust_params::default_for("levels", photocraft_doc::ColorMode::Rgb).unwrap()); + assert_eq!(field(&h, id, "inBlack"), defaults["inBlack"]); + assert_eq!(field(&h, id, "gamma"), defaults["gamma"]); +} + +fn sample_params(kind: &str) -> Value { + match kind { + "brightnessContrast" => json!({"brightness": 40}), + "levels" => json!({"inBlack": 30, "gamma": 1.3}), + "curves" => json!({"points": [[0, 0], [100, 150], [255, 255]]}), + "exposure" => json!({"exposure": 1}), + "vibrance" => json!({"vibrance": 50}), + "hueSaturation" => json!({"reds": {"hue": 40}}), + "colorBalance" => json!({"midtones": [40, 0, -20]}), + "blackWhite" => json!({"reds": 150, "tint": true}), + "photoFilter" => json!({"filter": "cooling80", "density": 60}), + "channelMixer" => json!({"red": [50, 50, 0, 0]}), + "posterize" => json!({"levels": 3}), + "threshold" => json!({"level": 90}), + "gradientMap" => json!({"stops": [[0, "#200040"], [1, "#ffd080"]]}), + _ => json!({}), + } +} + +/// #5113: the dialog should fit its curve graph instead of reserving a blank right column. +#[test] +fn curves_dialog_fits_its_graph_and_controls() { + for language in ["en", "ru"] { + let _language = crate::i18n::language_scope(crate::i18n::Lang::from_code(language).unwrap()); + for theme in crate::theme::ThemeKind::ALL { + for size in [egui::vec2(1280.0, 900.0), egui::vec2(900.0, 720.0)] { + let mut h = Harness::builder().with_size(size).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + PhotocraftApp::setup_context(&h.ctx, theme); + let id = open(h.state_mut(), "image.adjustments.curves").unwrap(); + h.run_steps(4); + let window = h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", id)))).unwrap(); + let graph = h.ctx.data(|d| d.get_temp::(dialog_mem("curves").with("curves-graph"))).unwrap(); + assert!(window.right() - graph.right() < 40.0, "blank right column: window {window:?}, graph {graph:?}"); + assert!(graph.width() > 270.0, "keep the graph usable: {graph:?}"); + assert!(window.contains_rect(graph)); + for label in ["Channel:", "Input:", "Output:", "Preview", "OK", "Cancel"] { + // A caption and the field it names share the label; any of them is the control. + let node = h.query_all_by_label(crate::i18n::t(label)).next().unwrap_or_else(|| panic!("{label} in the dialog")); + assert!(window.contains_rect(node.rect()), "{label} inside the window"); + } + } + } + } +} + +/// #8984: the Curves dialog has a resize grip; its graph grows with the dialog, the controls +/// stay inside it, and it reopens at the size it was left at. +#[test] +fn curves_dialog_resizes_with_its_graph_and_reopens_at_that_size() { + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + let graph = |h: &Harness<'_, PhotocraftApp>| h.ctx.data(|d| d.get_temp::(dialog_mem("curves").with("curves-graph"))).unwrap(); + let window = |h: &Harness<'_, PhotocraftApp>, id: u64| h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", id)))).unwrap(); + let id = open(h.state_mut(), "image.adjustments.curves").unwrap(); + h.run_steps(4); + let (opened, small) = (window(&h, id), graph(&h)); + assert!(small.width() > 270.0 && small.width() < 300.0, "opens at the 300-point graph: {small:?}"); + // Drag the grip (bottom-right corner) 300 points right and 200 down. + let corner = opened.max - egui::vec2(12.0, 12.0); + let by = egui::vec2(300.0, 200.0); + h.event(egui::Event::PointerMoved(corner)); + h.step(); + h.event(egui::Event::PointerButton { pos: corner, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.step(); + for i in 1..=4 { + h.event(egui::Event::PointerMoved(corner + by * (i as f32 / 4.0))); + h.step(); + } + h.event(egui::Event::PointerButton { pos: corner + by, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(6); + let (wide, big) = (window(&h, id), graph(&h)); + assert!(big.width() > small.width() + 250.0, "the graph follows the dialog: {small:?} → {big:?}"); + assert!((big.width() - big.height()).abs() < 1.0, "still square: {big:?}"); + assert!(wide.contains_rect(big) && wide.right() - big.right() < 40.0, "no blank column: window {wide:?}, graph {big:?}"); + for label in ["Channel:", "Input:", "Output:", "Preview", "OK", "Cancel"] { + for node in h.get_all_by_label(crate::i18n::t(label)) { + assert!(wide.contains_rect(node.rect()), "{label} label and control stay inside the window"); + } + } + // Cancel, open again: the size it was left at. + h.get_by_label("Cancel").click(); + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty()); + let again = open(h.state_mut(), "image.adjustments.curves").unwrap(); + h.run_steps(4); + assert!((graph(&h).width() - big.width()).abs() < 2.0, "reopened at {:?}, left at {big:?}", graph(&h)); + assert!((window(&h, again).width() - wide.width()).abs() < 2.0); +} + +/// #8984: however tall the graph's width would make it, the dialog still fits the window. +#[test] +fn curves_graph_never_pushes_the_dialog_off_a_short_window() { + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 700.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.ctx.data_mut(|m| m.insert_persisted(egui::Id::unique(("dialog-place", "image.adjustments.curves")).with("size"), egui::vec2(1200.0, 1200.0))); + let id = open(h.state_mut(), "image.adjustments.curves").unwrap(); + h.run_steps(5); + let graph = h.ctx.data(|d| d.get_temp::(dialog_mem("curves").with("curves-graph"))).unwrap(); + let window = h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", id)))).unwrap(); + assert!(graph.height() <= 700.0 - 360.0, "{graph:?}"); + assert!(window.height() <= 700.0, "{window:?}"); + assert!(window.contains_rect(h.get_by_label("OK").rect())); + // The size the window squeezed it to is not remembered: a larger window gets 1200 again. + let kept = h.ctx.data_mut(|m| m.get_persisted::(egui::Id::unique(("dialog-place", "image.adjustments.curves")).with("size"))); + assert_eq!(kept, Some(egui::vec2(1200.0, 1200.0))); + // Dragged far wider, the dialog stops where the graph stops: no blank column. + let corner = window.max - egui::vec2(12.0, 12.0); + h.event(egui::Event::PointerMoved(corner)); + h.step(); + h.event(egui::Event::PointerButton { pos: corner, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.step(); + h.event(egui::Event::PointerMoved(corner + egui::vec2(600.0, 0.0))); + h.step(); + h.event(egui::Event::PointerButton { + pos: corner + egui::vec2(600.0, 0.0), + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(5); + let graph = h.ctx.data(|d| d.get_temp::(dialog_mem("curves").with("curves-graph"))).unwrap(); + let window = h.ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", id)))).unwrap(); + assert!(window.right() - graph.right() < 40.0, "no blank column: window {window:?}, graph {graph:?}"); +} + +#[test] +fn cancel_leaves_the_document_untouched() { + let mut harness = + Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(harness.state_mut(), "image.adjustments.curves").unwrap(); + harness.run_steps(2); + harness.state_mut().ui.dialog_mut(id).unwrap().fields.insert("points".into(), json!([[0, 255], [255, 0]])); + harness.run_steps(2); + let before = harness.state().session.active().unwrap().doc.clone(); + harness.state_mut().ui.close_dialog(id); + harness.run_steps(2); + let after = harness.state().session.active().unwrap().doc.clone(); + assert!(std::sync::Arc::ptr_eq(&before, &after)); + assert!(harness.state().ui.dialogs.is_empty()); +} + +#[test] +fn gradient_map_dialog_handles_preview_without_committing_until_ok() { + use egui_kittest::kittest::Queryable; + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + let id = open(h.state_mut(), "image.adjustments.gradientMap").unwrap(); + h.run_steps(4); + let doc = h.state().session.active().unwrap().doc.clone(); + let steps = h.state().session.active().unwrap().history.past_len(); + let strip = h.get_by_label("Gradient stops").rect(); + let start = egui::pos2(strip.left() + 8.0, strip.top() + 36.0); + let to = start + egui::vec2((strip.width() - 16.0) * 0.3, 0.0); + h.hover_at(start); + h.run_steps(1); + h.drag_at(start); + h.run_steps(1); + h.hover_at(to); + h.run_steps(1); + h.drop_at(to); + h.run_steps(3); + let stops = h.state().ui.dialogs[0].fields["stops"].as_array().unwrap(); + assert!((stops[0][0].as_f64().unwrap() - 0.3).abs() < 0.001); + assert!(std::sync::Arc::ptr_eq(&doc, &h.state().session.active().unwrap().doc), "dialog edits are previews"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + h.run_steps(2); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(*h.state().session.active().unwrap().doc, *doc); +} +#[test] +fn curves_pencil_drag_draws_the_map_and_confirm_applies_it() { + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let steps = h.state().session.active().unwrap().history.past_len(); + let id = open(h.state_mut(), "image.adjustments.curves").unwrap(); + let fields = &mut h.state_mut().ui.dialog_mut(id).unwrap().fields; + fields.insert("pencil".into(), json!(true)); + fields.insert("points".into(), json!((0..256).collect::>())); + h.run_steps(4); + let graph = h.ctx.data(|d| d.get_temp::(egui::Id::unique(("adjust-dialog", "curves")).with("curves-graph"))).unwrap(); + let at = |i: f32, o: f32| egui::pos2(graph.left() + i / 255.0 * graph.width(), graph.bottom() - o / 255.0 * graph.height()); + h.hover_at(at(64.0, 200.0)); + h.run_steps(1); + h.drag_at(at(64.0, 200.0)); + h.run_steps(1); + for i in [100.0, 150.0, 192.0] { + h.hover_at(at(i, 200.0)); + h.run_steps(1); + } + h.drop_at(at(192.0, 200.0)); + h.run_steps(3); + let map = h.state().ui.dialogs[0].fields["points"].as_array().unwrap().clone(); + assert_eq!(map.len(), 256); + assert!((70..185).all(|k| (map[k].as_f64().unwrap() - 200.0).abs() < 3.0), "{map:?}"); + assert_eq!(map[20].as_f64(), Some(20.0), "outside the stroke the map is untouched"); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1); +} + +#[test] +fn curves_pointer_drag_previews_until_confirm_and_cancel_preserves_document() { + for confirm in [false, true] { + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let original = h.state().session.active().unwrap().doc.clone(); + let steps = h.state().session.active().unwrap().history.past_len(); + let id = open(h.state_mut(), "image.adjustments.curves").unwrap(); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("points".into(), json!([[0, 0], [128, 128], [255, 255]])); + h.run_steps(4); + let graph = h.ctx.data(|d| d.get_temp::(egui::Id::unique(("adjust-dialog", "curves")).with("curves-graph"))).unwrap(); + let a = egui::pos2(graph.left() + 128.0 / 255.0 * graph.width(), graph.bottom() - 128.0 / 255.0 * graph.height()); + h.hover_at(a); + h.run_steps(1); + h.drag_at(a); + h.run_steps(1); + h.hover_at(a + egui::vec2(40.0, -32.0)); + h.run_steps(1); + h.drop_at(a + egui::vec2(40.0, -32.0)); + h.run_steps(3); + let points = &h.state().ui.dialogs[0].fields["points"]; + assert_eq!(points.as_array().unwrap().len(), 3); + assert!(points[1][0].as_f64().unwrap() > 150.0 && points[1][1].as_f64().unwrap() > 150.0, "{points}"); + assert!(std::sync::Arc::ptr_eq(&original, &h.state().session.active().unwrap().doc)); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps); + if confirm { + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&original, &h.state().session.active().unwrap().doc)); + } else { + h.state_mut().ui.close_dialog(id); + h.run_steps(2); + assert!(std::sync::Arc::ptr_eq(&original, &h.state().session.active().unwrap().doc)); + } + } +} + +#[test] +fn curves_eyedroppers_sample_repeatedly_without_editing_the_document() { + let mut app = app_with_image(); + let original = app.session.active().unwrap().doc.clone(); + let revision = app.session.active().unwrap().revision; + let steps = app.session.active().unwrap().history.past_len(); + let id = open(&mut app, "image.adjustments.curves").unwrap(); + arm(&mut app, id, "black"); + assert!(picker_armed(&app)); + assert!(sample_at(&mut app, 8.0, 8.0)); + let first = channel_points(&app, "red"); + assert!((first[0][0] - 176.0).abs() < 0.6 && first[0][1] == 0.0, "{first:?}"); + assert!(sample_at(&mut app, 8.0, 8.0)); + assert_eq!(channel_points(&app, "red"), first, "the same repeated sample is deterministic"); + assert!(sample_at(&mut app, 48.0, 8.0)); + assert_ne!(channel_points(&app, "red"), first); + assert!(sample_at(&mut app, 8.0, 8.0)); + assert_eq!(channel_points(&app, "red"), first, "repeated samples resolve from the armed baseline"); + let st = app.session.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &original)); + assert_eq!(st.revision, revision); + assert_eq!(st.history.past_len(), steps); +} + +/// #3116: the Levels dialog's Set White Point moves each channel's input white to the sample +/// (#b04020) and leaves the document alone until OK. +#[test] +fn levels_white_point_eyedropper_sets_the_channel_input_whites() { + let mut app = app_with_image(); + let original = app.session.active().unwrap().doc.clone(); + let id = open(&mut app, "image.adjustments.levels").unwrap(); + arm(&mut app, id, "white"); + assert!(picker_armed(&app)); + assert!(sample_at(&mut app, 8.0, 8.0)); + let in_white = |key: &str| app.ui.dialogs.last().and_then(|d| d.fields.get(key)).and_then(|c| c.get("inWhite")).and_then(Value::as_f64); + assert_eq!([in_white("red"), in_white("green"), in_white("blue")], [Some(176.0), Some(64.0), Some(32.0)]); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original)); +} + +#[test] +fn curves_picker_controls_arm_and_disable_by_document_mode() { + let harness = |app| { + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut(), "image.adjustments.curves").unwrap(); + h.run_steps(3); + h + }; + let mut rgb = harness(app_in_mode("rgb")); + for label in ["Set Black Point", "Set Neutral Gray Point", "Set White Point"] { + assert!(!rgb.get_by_label(label).accesskit_node().is_disabled(), "{label}"); + } + rgb.get_by_label("Set Black Point").click(); + rgb.run_steps(2); + assert!(picker_armed(rgb.state())); + assert_eq!(rgb.state().ui.dialogs.last().and_then(|d| d.fields.get(CURVE_PICKER)).and_then(Value::as_str), Some("black")); + + let gray = harness(app_in_mode("gray")); + assert!(!gray.get_by_label("Set Black Point").accesskit_node().is_disabled()); + assert!(gray.get_by_label("Set Neutral Gray Point").accesskit_node().is_disabled()); + assert!(!gray.get_by_label("Set White Point").accesskit_node().is_disabled()); + + for mode in ["cmyk", "lab"] { + let h = harness(app_in_mode(mode)); + for label in ["Set Black Point", "Set Neutral Gray Point", "Set White Point"] { + assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{mode}: {label}"); + } + } +} + +#[test] +fn curves_picker_rejects_outside_and_transparent_samples() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 32, "height": 24, "background": "transparent"})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + let id = open(&mut app, "image.adjustments.curves").unwrap(); + arm(&mut app, id, "white"); + let before = crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields); + assert!(sample_at(&mut app, -1.0, 4.0)); + assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields), before); + assert!(sample_at(&mut app, 4.0, 4.0)); + assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields), before); + assert!(picker_armed(&app), "an invalid sample does not disarm the picker"); +} + +#[test] +fn curves_picker_cancel_and_confirm_keep_one_transaction() { + for confirm in [false, true] { + let mut app = app_with_image(); + let original = app.session.active().unwrap().doc.clone(); + let steps = app.session.active().unwrap().history.past_len(); + let id = open(&mut app, "image.adjustments.curves").unwrap(); + arm(&mut app, id, "white"); + assert!(sample_at(&mut app, 8.0, 8.0)); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original)); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + if confirm { + crate::dialogs::confirm(&mut app, id).unwrap(); + let committed = app.session.active().unwrap().doc.clone(); + assert!(!std::sync::Arc::ptr_eq(&committed, &original)); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); + app.run("edit.undo", json!({})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original)); + app.run("edit.redo", json!({})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &committed)); + } else { + app.ui.close_dialog(id); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original)); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + } + } +} + +#[test] +fn curves_picker_modes_and_depths_are_explicit() { + use photocraft_engine::adjust_params::CurvesEyedropper; + assert!(picker_supported(photocraft_doc::ColorMode::Rgb, CurvesEyedropper::NeutralGray)); + assert!(picker_supported(photocraft_doc::ColorMode::Grayscale, CurvesEyedropper::Black)); + assert!(picker_supported(photocraft_doc::ColorMode::Grayscale, CurvesEyedropper::White)); + assert!(!picker_supported(photocraft_doc::ColorMode::Grayscale, CurvesEyedropper::NeutralGray)); + assert!(!picker_supported(photocraft_doc::ColorMode::Cmyk, CurvesEyedropper::Black)); + assert!(!picker_supported(photocraft_doc::ColorMode::Lab, CurvesEyedropper::White)); + + for depth in [8, 16, 32] { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap(); + s.execute("edit.fill", json!({"color": [0.3142, 0.4821, 0.7137]})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + let sampled = crate::canvas::composite_color(&mut app, 4.0, 4.0).unwrap(); + let id = open(&mut app, "image.adjustments.curves").unwrap(); + arm(&mut app, id, "gray"); + assert!(sample_at(&mut app, 4.0, 4.0), "RGB @{depth}"); + let red = channel_points(&app, "red"); + let target_level = (f64::from(sampled[0]) * 0.2126 + f64::from(sampled[1]) * 0.7152 + f64::from(sampled[2]) * 0.0722) * 255.0; + let sample_level = f64::from(sampled[0]) * 255.0; + let serialized_sample_level = (sample_level * 100.0).round() / 100.0; + let neutral_anchor = red.iter().find(|point| (point[0] - serialized_sample_level).abs() < 1e-5).unwrap(); + let serialized_target_level = (target_level * 100.0).round() / 100.0; + assert!((neutral_anchor[1] - serialized_target_level).abs() < 1e-5, "depth={depth} anchor={neutral_anchor:?} sampled={sampled:?}"); + assert!((neutral_anchor[0] - sample_level).abs() <= 0.0051, "depth={depth} anchor={neutral_anchor:?} sampled={}", sampled[0]); + if depth == 16 || depth == 32 { + assert!( + (sampled[0] * 255.0 - (sampled[0] * 255.0).round()).abs() > 0.01, + "depth={depth} sample was quantized to an 8-bit level: {}", + sampled[0] + ); + } + } +} + +fn pointer_down(app: &mut PhotocraftApp, ctx: &egui::Context, x: f64, y: f64, modifiers: Value) { + let (request, _receiver) = + crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "down", "x": x, "y": y}], "modifiers": modifiers})); + let _ = crate::control::handle(app, ctx, &request); +} + +/// The Curves curve `pts` (0-255 levels) as a 256-entry 0-255 map. +fn curve_levels(pts: &[[f64; 2]]) -> Vec { + let cp: Vec<_> = pts.iter().map(|q| photocraft_doc::adjust::CurvePoint { input: q[0] as f32 / 255.0, output: q[1] as f32 / 255.0 }).collect(); + let lut = photocraft_compose::adjust::curve_lut(&cp); + (0..256).map(|k| lut[(k as f32 / 255.0 * (lut.len() - 1) as f32).round() as usize] * 255.0).collect() +} + +/// #7325: ⌘/Ctrl-click on the image puts a point on the shown curve at the pixel's tone +/// (#b04020: Rec. 709 luma 85.5 → level 86) and at the curve's own output there, so the +/// image does not change; the new point is the selected one, and the document waits for OK. +#[test] +fn command_click_on_the_image_adds_a_point_on_the_composite_curve() { + let mut app = app_with_image(); + let original = app.session.active().unwrap().doc.clone(); + let steps = app.session.active().unwrap().history.past_len(); + let id = open(&mut app, "image.adjustments.curves").unwrap(); + let base = [[0.0, 0.0], [128.0, 200.0], [255.0, 255.0]]; + app.ui.dialog_mut(id).unwrap().fields.insert("points".into(), json!(base)); + let ctx = egui::Context::default(); + let sample = crate::canvas::composite_color(&mut app, 8.0, 8.0).unwrap(); + let level = ((sample[0] * 0.2126 + sample[1] * 0.7152 + sample[2] * 0.0722) * 255.0).round(); + assert_eq!(level, 86.0); + let output = f64::from(curve_levels(&base)[86].round()); + assert_ne!(output, 86.0, "the base curve is not the identity at the sampled level"); + + pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true})); + let points = channel_points(&app, "points"); + assert_eq!(points, vec![base[0], [86.0, output], base[1], base[2]]); + let (before, after) = (curve_levels(&base), curve_levels(&points)); + assert!(before.iter().zip(&after).all(|(a, b)| (a - b).abs() <= 0.5), "the curve keeps its shape:\n{before:?}\n{after:?}"); + let st: crate::state::CurvesEditorState = ctx.data(|d| d.get_temp(dialog_mem("curves").with("curves"))).unwrap(); + assert_eq!((st.channel, st.gesture.selected), (0, Some(1)), "the new point is selected"); + for key in ["red", "green", "blue"] { + assert_eq!(channel_points(&app, key), vec![[0.0, 0.0], [255.0, 255.0]], "{key} untouched"); + } + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original)); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); +} + +/// #7325: Shift+⌘-click puts a point on each colour channel at that channel's own value +/// (176, 64, 32), and leaves the composite curve alone. +#[test] +fn shift_command_click_adds_a_point_on_each_colour_channel() { + let mut app = app_with_image(); + open(&mut app, "image.adjustments.curves").unwrap(); + let ctx = egui::Context::default(); + let composite = channel_points(&app, "points"); + pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true, "shift": true})); + for (key, level) in [("red", 176.0), ("green", 64.0), ("blue", 32.0)] { + assert_eq!(channel_points(&app, key), vec![[0.0, 0.0], [level, level], [255.0, 255.0]], "{key}"); + } + assert_eq!(channel_points(&app, "points"), composite); +} + +/// #7325: with Red shown in the Channel popup the point goes on the red curve, at red's value. +#[test] +fn command_click_adds_the_point_on_the_channel_shown_in_the_dialog() { + let mut app = app_with_image(); + open(&mut app, "image.adjustments.curves").unwrap(); + let ctx = egui::Context::default(); + ctx.data_mut(|d| d.insert_temp(dialog_mem("curves").with("curves-ch"), 1usize)); + let composite = channel_points(&app, "points"); + pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true})); + assert_eq!(channel_points(&app, "red"), vec![[0.0, 0.0], [176.0, 176.0], [255.0, 255.0]]); + for key in ["green", "blue"] { + assert_eq!(channel_points(&app, key), vec![[0.0, 0.0], [255.0, 255.0]], "{key} untouched"); + } + assert_eq!(channel_points(&app, "points"), composite); + let st: crate::state::CurvesEditorState = ctx.data(|d| d.get_temp(dialog_mem("curves").with("curves"))).unwrap(); + assert_eq!((st.channel, st.gesture.selected), (1, Some(1))); +} + +/// #7325: a plain click, a full curve and an armed eyedropper add nothing. +#[test] +fn command_click_adds_nothing_without_the_modifier_on_a_full_curve_or_with_an_eyedropper() { + let mut app = app_with_image(); + let id = open(&mut app, "image.adjustments.curves").unwrap(); + let ctx = egui::Context::default(); + let before = crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields); + pointer_down(&mut app, &ctx, 8.0, 8.0, json!({})); + assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields), before, "no modifier, no point"); + // Space and the middle button pan, as with the mouse. + for extra in [json!({"modifiers": {"command": true, "space": true}}), json!({"command": true, "button": "middle"})] { + let mut params = json!({"events": [{"kind": "down", "x": 8, "y": 8}]}); + params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let (request, _receiver) = crate::control::ControlRequest::new("ui.pointer", params); + let _ = crate::control::handle(&mut app, &ctx, &request); + assert_eq!(crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields), before, "{extra}"); + } + + // Sixteen points (the most a curve holds), none within reach of level 86. + let full: Vec<[f64; 2]> = + [0, 10, 20, 30, 40, 50, 60, 70, 80, 100, 120, 140, 160, 180, 200, 255].iter().map(|&i| [f64::from(i), f64::from(i)]).collect(); + app.ui.dialog_mut(id).unwrap().fields.insert("points".into(), json!(full)); + pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true})); + assert_eq!(channel_points(&app, "points"), full, "a full curve takes no more points and moves none"); + + let mut app = app_with_image(); + let id = open(&mut app, "image.adjustments.curves").unwrap(); + arm(&mut app, id, "black"); + pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true})); + assert_eq!(channel_points(&app, "points").len(), 2, "the armed eyedropper samples instead"); + assert_eq!(channel_points(&app, "red")[0], [176.0, 0.0]); +} + +/// #7325: Lab and CMYK curves and a targeted mask are left to a later change: nothing is added. +#[test] +fn command_click_adds_nothing_in_lab_or_on_a_targeted_mask() { + let ctx = egui::Context::default(); + let mut lab = app_in_mode("lab"); + lab.run("edit.fill", json!({"color": "#b04020"})).unwrap(); + let id = open(&mut lab, "image.adjustments.curves").unwrap(); + let before = crate::filter_dialog::params_of(&lab.ui.dialog_mut(id).unwrap().fields); + assert!(add_point_at(&mut lab, &ctx, 4.0, 4.0, false)); + assert_eq!(crate::filter_dialog::params_of(&lab.ui.dialog_mut(id).unwrap().fields), before); + + let mut masked = app_with_image(); + masked.run("layer.layerMask.revealAll", json!({})).unwrap(); + masked.run("channel.target", json!({"channel": "mask"})).unwrap(); + let id = open(&mut masked, "image.adjustments.curves").unwrap(); + let before = crate::filter_dialog::params_of(&masked.ui.dialog_mut(id).unwrap().fields); + assert!(add_point_at(&mut masked, &ctx, 8.0, 8.0, false)); + assert_eq!(crate::filter_dialog::params_of(&masked.ui.dialog_mut(id).unwrap().fields), before); +} + +#[test] +fn ui_pointer_drives_an_armed_curves_picker() { + let mut app = app_with_image(); + let id = open(&mut app, "image.adjustments.curves").unwrap(); + arm(&mut app, id, "black"); + let context = egui::Context::default(); + let before = channel_points(&app, "red"); + let (request, _receiver) = crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "move", "x": 48, "y": 8}]})); + let _ = crate::control::handle(&mut app, &context, &request); + assert_eq!(channel_points(&app, "red"), before, "pointer move does not sample"); + + let (request, _receiver) = crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "down", "x": 8, "y": 8}]})); + let _ = crate::control::handle(&mut app, &context, &request); + let red = channel_points(&app, "red"); + assert!((red[0][0] - 176.0).abs() < 0.6 && red[0][1] == 0.0, "{red:?}"); + assert_ne!(red, before, "pointer down samples"); + + let (request, _receiver) = crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "up", "x": 48, "y": 8}]})); + let _ = crate::control::handle(&mut app, &context, &request); + assert_eq!(channel_points(&app, "red"), red, "pointer up does not sample again"); + assert!(picker_armed(&app)); +} + +/// #5335: a targeted mask, saved channel or colour component is the only Channel popup entry. +#[test] +fn curves_channel_popup_lists_only_the_targeted_channel() { + let mut app = app_with_image(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.run("channel.target", json!({"channel": "mask"})).unwrap(); + let mut h = curves_harness(app); + let names = popup_channels(&mut h); + assert!(names.iter().any(|n| n.contains("Mask")), "{names:?}"); + assert!(!names.iter().any(|n| n == "RGB" || n == "Red" || n == "Green" || n == "Blue"), "{names:?}"); +} + +/// #5335: selecting the mask in the Layers panel gives the same Curves dropdown as selecting +/// it in the Channels panel. +#[test] +fn curves_channel_popup_lists_only_the_mask_selected_in_the_layers_panel() { + let mut app = app_with_image(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.ui.mask_target = true; // clicking the mask thumbnail in the Layers panel + assert!(app.layer_mask_targeted(), "the Layers panel mask thumbnail is targeted"); + let mut h = curves_harness(app); + let names = popup_channels(&mut h); + assert_eq!(names.len(), 1, "only the mask: {names:?}"); + assert!(names[0].contains("Mask"), "{names:?}"); +} + +/// #5335: in a Lab document, Curves over a gray target keeps neutral fields: no Lab records +/// to overwrite the mask's own curve or pick the wrong tone space. +#[test] +fn curves_on_a_gray_target_seeds_neutral_fields_in_a_lab_document() { + for via_layers_panel in [false, true] { + let mut app = app_in_mode("lab"); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + if via_layers_panel { + app.ui.mask_target = true; + } else { + app.run("channel.target", json!({"channel": "mask"})).unwrap(); + } + let id = open(&mut app, "image.adjustments.curves").expect("opens"); + let values = crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields.clone()); + assert!(values.get("points").is_some(), "{values:?}"); + for key in ["lightness", "a", "b", "cyan", "magenta", "yellow", "black"] { + assert!(values.get(key).is_none(), "{key} in a gray target's curves: {values:?}"); + } + } +} + +/// #5335: in Italian the built-in labels translate, but a channel the user named "Green" +/// stays exactly "Green". +#[test] +fn curves_channel_popup_keeps_custom_names_verbatim_in_italian() { + let it = crate::i18n::Lang::from_code("it").expect("it registered"); + let green = crate::i18n::tr(it, "Green"); + let _lang = crate::i18n::language_scope(it); + let mut app = app_with_image(); + app.run("channel.new", json!({"name": "Green", "fill": "white"})).unwrap(); + app.run("channel.target", json!({"channel": 0})).unwrap(); + let mut h = curves_harness(app); + let names = popup_channels(&mut h); + assert!(names.iter().any(|n| n == "Green"), "custom names stay as entered: {names:?}"); + assert!(green == "Green" || !names.iter().any(|n| n == green), "not translated: {names:?}"); + // A targeted colour component keeps its translated built-in label. + let mut colour = app_with_image(); + colour.run("channel.target", json!({"channel": {"color": 1}})).unwrap(); + let mut h = curves_harness(colour); + let names = popup_channels(&mut h); + assert!(names.iter().any(|n| n == green), "built-in labels follow the language: {names:?}"); +} + +/// Curves open in a harness over `app`. +fn curves_harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + open(h.state_mut(), "image.adjustments.curves").unwrap(); + h.run_steps(4); + h +} + +/// The Channel popup's selected value (its option labels are what it shows). +fn popup_channels(h: &mut Harness<'static, PhotocraftApp>) -> Vec { + h.query_all_by_role(egui::accesskit::Role::ComboBox).filter_map(|n| n.value().map(|s| s.to_string())).collect() +} + +/// FILE-215-3: Curves on a targeted filter mask edits a gray plane, and its histogram is the +/// filter mask's, not the smart object's colours. +#[test] +fn curves_on_a_targeted_filter_mask_is_a_gray_plane() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + app.run("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); + let id = app.session.active().unwrap().active_layer.unwrap(); + app.select_filter_mask_target(Some(id.0)); + assert!(app.filter_mask_targeted()); + let c = isolated(&app).expect("a gray target"); + assert_eq!(c.gray, Some(photocraft_engine::channel_cmds::GraySurface::FilterMask)); + // Its histogram counts the filter mask's levels: half black after a stroke. + app.run("paint.stroke", json!({"points": [[8, 0], [8, 31]], "size": 16, "hardness": 1, "color": "#000000", "target": "filterMask"})).unwrap(); + let surface = photocraft_engine::channel_cmds::GraySurface::FilterMask; + let st = app.session.active().unwrap(); + let h = tone::compute_histograms(&st.doc, HistSource::Channel { layer: id, surface }, photocraft_doc::adjust::ToneSpace::Rgb); + assert!(h.ch[0][0] > 0 && h.ch[0][255] > 0, "black and white levels"); + assert_eq!(curve_mode(&app, "curves"), photocraft_doc::ColorMode::Grayscale); +} From 1a12f7202730aef1e2b2b728f9ad413bd6404be2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:03 +0000 Subject: [PATCH 080/259] refactor(ui-egui): move rotate_view.rs tests to rotate_view/tests.rs --- crates/ui-egui/src/rotate_view.rs | 372 +----------------------- crates/ui-egui/src/rotate_view/tests.rs | 369 +++++++++++++++++++++++ 2 files changed, 370 insertions(+), 371 deletions(-) create mode 100644 crates/ui-egui/src/rotate_view/tests.rs diff --git a/crates/ui-egui/src/rotate_view.rs b/crates/ui-egui/src/rotate_view.rs index ddfabb1261..8b6706327f 100644 --- a/crates/ui-egui/src/rotate_view.rs +++ b/crates/ui-egui/src/rotate_view.rs @@ -270,374 +270,4 @@ pub fn cursor(dragged: bool) -> egui::CursorIcon { } #[cfg(test)] -mod tests { - use super::*; - use egui::{Event, PointerButton, pos2}; - use egui_kittest::Harness; - use serde_json::json; - - #[test] - fn wrap_deg_folds_huge_and_hostile_angles() { - assert_eq!(wrap_deg(0.0), 0.0); - assert_eq!(wrap_deg(180.0), 180.0); - assert_eq!(wrap_deg(-180.0), 180.0); - assert!((wrap_deg(190.0) + 170.0).abs() < 1e-4); - assert!((wrap_deg(-190.0) - 170.0).abs() < 1e-4); - assert!((wrap_deg(360.0)).abs() < 1e-4); - assert!((wrap_deg(1.0e10)).abs() <= 180.0); - assert_eq!(wrap_deg(f32::NAN), 0.0); - assert_eq!(wrap_deg(f32::INFINITY), 0.0); - assert_eq!(wrap_deg(f32::NEG_INFINITY), 0.0); - } - - #[test] - fn snap_deg_lands_on_fifteens() { - assert_eq!(snap_deg(0.0, SNAP_DEG), 0.0); - assert_eq!(snap_deg(7.0, SNAP_DEG), 0.0); - assert_eq!(snap_deg(8.0, SNAP_DEG), 15.0); - assert_eq!(snap_deg(-7.0, SNAP_DEG), 0.0); - assert_eq!(snap_deg(-8.0, SNAP_DEG), -15.0); - assert_eq!(snap_deg(40.0, SNAP_DEG), 45.0); - assert_eq!(snap_deg(f32::NAN, SNAP_DEG), 0.0); - assert_eq!(snap_deg(40.0, 0.0), wrap_deg(40.0)); - assert_eq!(snap_deg(40.0, f32::NAN), wrap_deg(40.0)); - } - - #[test] - fn apply_params_sets_adds_resets_and_rejects() { - assert_eq!(apply_params(0.0, &json!({"angle": 30.0})).unwrap(), 30.0); - assert_eq!(apply_params(30.0, &json!({"delta": 15.0})).unwrap(), 45.0); - assert_eq!(apply_params(45.0, &json!({"reset": true})).unwrap(), 0.0); - assert_eq!(apply_params(170.0, &json!({"delta": 20.0})).unwrap(), -170.0); - assert!(apply_params(0.0, &json!({})).is_err()); - assert!(apply_params(0.0, &Value::Null).is_err()); - assert!(apply_params(0.0, &json!("30")).is_err()); - assert!(apply_params(0.0, &json!({"angle": f64::NAN})).is_err()); - assert!(apply_params(0.0, &json!({"angle": f64::INFINITY})).is_err()); - assert!(apply_params(0.0, &json!({"delta": f64::INFINITY})).is_err()); - // JSON can contain finite f64 values whose f32 conversion overflows to infinity. - // Silently wrapping infinity to 0 would reset a rotated view. - assert!(apply_params(32.0, &json!({"angle": 1.0e100})).is_err()); - assert!(apply_params(32.0, &json!({"delta": -1.0e100})).is_err()); - assert!(apply_params(0.0, &json!({"reset": "yes"})).is_err()); - assert!(apply_params(0.0, &json!({"zoom": 1})).is_err()); - let huge = apply_params(0.0, &json!({"angle": 1.0e20})).unwrap(); - assert!(huge.is_finite() && huge.abs() <= 180.0); - } - - #[test] - fn native_rotate_event_reaches_canvas_when_trackpad_rotation_is_enabled() { - let ctx = egui::Context::default(); - let mut enabled = None; - let mut disabled = None; - let raw = egui::RawInput { events: vec![Event::Rotate(std::f32::consts::FRAC_PI_6)], ..Default::default() }; - let mut output = ctx.run_ui(raw, |ui| { - enabled = trackpad_delta(ui.ctx(), true, true); - disabled = trackpad_delta(ui.ctx(), false, true); - }); - output.textures_delta.clear(); - - assert!(enabled.is_some_and(|degrees| (degrees - 30.0).abs() < 1e-3), "{enabled:?}"); - assert_eq!(disabled, None); - } - - /// Preferences › Enhanced Controls › Enable Gestures (#204): off, a two-finger twist on a - /// touch screen doesn't turn the view; the trackpad's `Rotate` event still does. - #[test] - fn enable_gestures_switches_touch_screen_rotation() { - use egui::TouchPhase::{Move, Start}; - let touch = |id: u64, phase, pos| Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(id), phase, pos, force: None }; - let twist = |touch_gestures: bool, extra: Vec| { - let ctx = egui::Context::default(); - let frames = [ - // egui only starts a multi-touch gesture once it knows where the pointer is. - vec![Event::PointerMoved(pos2(50.0, 50.0))], - vec![touch(1, Start, pos2(40.0, 50.0)), touch(2, Start, pos2(60.0, 50.0))], - // A quarter turn about the centre between the fingers. - [vec![touch(1, Move, pos2(50.0, 40.0)), touch(2, Move, pos2(50.0, 60.0))], extra].concat(), - ]; - let mut last = None; - for (n, events) in (0u32..).zip(frames) { - let raw = egui::RawInput { time: Some(f64::from(n) / 60.0), events, ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| last = trackpad_delta(ui.ctx(), true, touch_gestures)); - out.textures_delta.clear(); - } - last - }; - let on = twist(true, Vec::new()); - assert!(on.is_some_and(|d| (d.abs() - 90.0).abs() < 1e-3), "on: the fingers turn the view: {on:?}"); - assert_eq!(twist(false, Vec::new()), None, "off: the fingers don't"); - let trackpad = twist(false, vec![Event::Rotate(std::f32::consts::FRAC_PI_6)]); - assert!(trackpad.is_some_and(|d| (d - 30.0).abs() < 1e-3), "off: a trackpad rotate still turns: {trackpad:?}"); - } - - #[test] - fn trackpad_pref_gates_rotation() { - assert_eq!(apply_trackpad(10.0, false, 0.5), None); - assert_eq!(apply_trackpad(10.0, true, 0.0), None); - assert_eq!(apply_trackpad(10.0, true, f32::NAN), None); - assert_eq!(apply_trackpad(10.0, true, f32::INFINITY), None); - let a = apply_trackpad(10.0, true, std::f32::consts::FRAC_PI_2).expect("finite delta"); - assert!((a - 100.0).abs() < 0.05, "{a}"); - } - - #[test] - fn view_xform_identity_matches_unrotated_mapping() { - for zoom in [0.5, 1.0, 2.5] { - for center in [[0.0, 0.0], [320.0, 240.0], [10.0, -4.0]] { - for flip in [false, true] { - let rect = Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0)); - let a = ViewXform { rect, zoom, center, flip, rotation: 0.0, aspect: 1.0 }; - let sx = if flip { -1.0 } else { 1.0 }; - let want = rect.center() + vec2((10.0 - center[0]) * zoom * sx, (20.0 - center[1]) * zoom); - let got = a.to_screen(10.0, 20.0); - assert!((got.x - want.x).abs() < 1e-4 && (got.y - want.y).abs() < 1e-4, "{got:?} vs {want:?}"); - } - } - } - } - - #[test] - fn view_xform_roundtrip_and_ninety_degrees() { - let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)); - for rot in [15.0, 90.0, -45.0, 180.0] { - for flip in [false, true] { - let xf = ViewXform { rect, zoom: 2.0, center: [80.0, 40.0], flip, rotation: rot, aspect: 1.0 }; - let s = xf.to_screen(10.0, 20.0); - let d = xf.to_doc(s); - assert!((d[0] - 10.0).abs() < 1e-3 && (d[1] - 20.0).abs() < 1e-3, "rot={rot} flip={flip} {d:?}"); - } - } - // 90°: a point on +X in document space lands on +Y on screen (Y-down = clockwise). - let xf = ViewXform { rect, zoom: 1.0, center: [0.0, 0.0], flip: false, rotation: 90.0, aspect: 1.0 }; - let s = xf.to_screen(1.0, 0.0); - let c = rect.center(); - assert!((s.x - c.x).abs() < 1e-3 && (s.y - (c.y + 1.0)).abs() < 1e-3, "{s:?} vs {c:?}"); - // Flip after rotate: 0° +X goes left. - let xf = ViewXform { rect, zoom: 1.0, center: [0.0, 0.0], flip: true, rotation: 0.0, aspect: 1.0 }; - assert!(xf.to_screen(1.0, 0.0).x < rect.center().x); - let xf = ViewXform { rect, zoom: 1.0, center: [0.0, 0.0], flip: true, rotation: 90.0, aspect: 1.0 }; - let s = xf.to_screen(1.0, 0.0); - assert!((s.x - c.x).abs() < 1e-3 && (s.y - (c.y + 1.0)).abs() < 1e-3, "flip then rotate {s:?}"); - } - - /// Screen angle, about the canvas centre, of the document point that was under `p0` at the press. - fn followed_angle(h: &Harness<'static, PhotocraftApp>, p0: Pos2, start_rotation: f32) -> f32 { - let st = h.state(); - let (rect, v, flip) = (st.last_canvas_rect, &st.ui.views[0], st.ui.view.flip_horizontal); - let before = ViewXform { rect, zoom: 1.0, center: v.center, flip, rotation: start_rotation, aspect: 1.0 }; - let d = before.to_doc(p0); - let after = ViewXform { rotation: v.rotation, ..before }; - let s = after.to_screen(d[0] as f32, d[1] as f32) - rect.center(); - wrap_deg(s.y.atan2(s.x).to_degrees() - pointer_deg(p0, rect.center())) - } - - #[test] - fn drag_follows_the_pointer_in_a_flipped_view() { - for flip in [false, true] { - let mut h = harness(); - h.state_mut().ui.view.flip_horizontal = flip; - h.run_steps(2); - let c = h.state().last_canvas_rect.center(); - let p0 = c + vec2(120.0, 0.0); - h.event(Event::PointerMoved(p0)); - h.step(); - press(&mut h, p0, true, false); - // 30° clockwise about the pivot: the image turns 30° clockwise on screen. - let p1 = c + vec2(120.0 * 30f32.to_radians().cos(), 120.0 * 30f32.to_radians().sin()); - h.event(Event::PointerMoved(p1)); - h.step(); - let got = followed_angle(&h, p0, 0.0); - assert!((got - 30.0).abs() < 0.75, "flip={flip}: the image turned {got}°, the pointer 30°"); - press(&mut h, p1, false, false); - } - } - - #[test] - fn screen_delta_mirrors_only_in_a_flipped_view() { - assert_eq!(screen_delta(12.5, false), 12.5); - assert_eq!(screen_delta(12.5, true), -12.5); - assert_eq!(screen_delta(-180.0, true), 180.0); - assert_eq!(screen_delta(f32::NAN, true), 0.0); - assert_eq!(screen_delta(f32::INFINITY, false), 0.0); - // A flipped view still lands on the snapped angle with Shift. - assert_eq!(snap_deg(0.0 + screen_delta(-40.0, true), SNAP_DEG), 45.0); - } - - fn app_docs(n: usize) -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - for i in 0..n { - app.run("file.new", json!({"width": 200 + i as u32 * 10, "height": 100})).unwrap(); - } - app.sync_views(); - app - } - - #[test] - fn commands_rotate_reset_and_reject_without_a_document() { - let ctx = egui::Context::default(); - let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - assert_eq!(crate::menus::invoke(&mut empty, &ctx, "view.rotateView", json!({"angle": 30})).unwrap_err(), "no document open"); - assert_eq!(crate::menus::invoke(&mut empty, &ctx, "view.resetView", json!({})).unwrap_err(), "no document open"); - - let mut app = app_docs(1); - let r = crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"angle": 30})).unwrap(); - assert_eq!(r["rotation"], 30.0); - assert_eq!(app.ui.views[0].rotation, 30.0); - let r = crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"delta": 15})).unwrap(); - assert_eq!(r["rotation"], 45.0); - let z = app.ui.views[0].zoom; - let c = app.ui.views[0].center; - let r = crate::menus::invoke(&mut app, &ctx, "view.resetView", json!({})).unwrap(); - assert_eq!(r["rotation"], 0.0); - assert_eq!(app.ui.views[0].rotation, 0.0); - assert_eq!(app.ui.views[0].zoom, z); - assert_eq!(app.ui.views[0].center, c); - assert!(crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({})).is_err()); - assert!(crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"angle": f64::NAN})).is_err()); - assert_eq!(app.ui.views[0].rotation, 0.0); - assert_eq!(app.session.documents()[0].history.past_len(), 0); - } - - #[test] - fn ui_set_selects_the_tool_and_sets_rotation() { - let ctx = egui::Context::default(); - let mut app = app_docs(1); - let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"tool": "RotateView", "rotation": 30})); - let out = crate::control::handle(&mut app, &ctx, &req); - let crate::control::Outcome::Done(v) = out else { panic!("done") }; - assert_eq!(v["ok"], true, "{v}"); - assert_eq!(app.ui.tool, crate::state::Tool::RotateView); - assert_eq!(app.ui.views[0].rotation, 30.0); - let (req, _) = crate::control::ControlRequest::new("ui.inspect", json!({})); - let crate::control::Outcome::Done(ins) = crate::control::handle(&mut app, &ctx, &req) else { panic!("inspect") }; - assert_eq!(ins["result"]["tool"], "RotateView"); - assert_eq!(ins["result"]["views"][0]["rotation"], 30.0); - let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"rotation": f64::NAN})); - let crate::control::Outcome::Done(bad) = crate::control::handle(&mut app, &ctx, &req) else { panic!("nan") }; - assert_eq!(bad["ok"], false); - assert_eq!(app.ui.views[0].rotation, 30.0); - let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"tool": "RotateView"})); - let crate::control::Outcome::Done(ok) = crate::control::handle(&mut empty, &ctx, &req) else { panic!("tool") }; - assert_eq!(ok["ok"], true, "{ok}"); - assert_eq!(empty.ui.tool, crate::state::Tool::RotateView); - let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"rotation": 15})); - let crate::control::Outcome::Done(err) = crate::control::handle(&mut empty, &ctx, &req) else { panic!("no doc") }; - assert_eq!(err["ok"], false); - assert!(err["error"].as_str().unwrap().contains("no document open"), "{err}"); - } - - #[test] - fn match_rotation_copies_the_angle_and_needs_two_documents() { - let ctx = egui::Context::default(); - let one = app_docs(1); - assert_eq!(crate::view_cmds::is_enabled(&one, "window.arrange.matchRotation"), Some(false)); - let mut app = app_docs(2); - assert_eq!(crate::view_cmds::is_enabled(&app, "window.arrange.matchRotation"), Some(true)); - app.ui.views[1].rotation = 30.0; - let r = crate::menus::invoke(&mut app, &ctx, "window.arrange.matchRotation", json!({})).unwrap(); - assert_eq!(r["rotation"], 30.0); - assert!(app.ui.views.iter().all(|v| (v.rotation - 30.0).abs() < 1e-4)); - app.ui.views[1].rotation = 12.0; - app.ui.views[1].zoom = 2.0; - crate::menus::invoke(&mut app, &ctx, "window.arrange.matchAll", json!({})).unwrap(); - assert!(app.ui.views.iter().all(|v| (v.rotation - 12.0).abs() < 1e-4 && (v.zoom - 2.0).abs() < 1e-4)); - } - - 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.sync_views(); - app.ui.extras.rulers = false; - app.ui.tool = crate::state::Tool::RotateView; - let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).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::ALL[0]); - h.run_steps(4); - h - } - - fn press(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, pressed: bool, shift: bool) { - let modifiers = egui::Modifiers { shift, ..Default::default() }; - h.event(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers }); - h.step(); - } - - #[test] - fn shift_drag_snaps_to_fifteen_degrees() { - let mut h = harness(); - let r = h.state().last_canvas_rect; - let c = r.center(); - let p0 = c + vec2(120.0, 0.0); - h.event(Event::PointerMoved(p0)); - h.step(); - h.event(Event::ModifiersChanged(egui::Modifiers::SHIFT)); - h.step(); - press(&mut h, p0, true, true); - // ~40° clockwise: Shift rounds to 45°. - let p1 = c + vec2(120.0 * 40f32.to_radians().cos(), 120.0 * 40f32.to_radians().sin()); - h.event(Event::PointerMoved(p1)); - h.step(); - let rot = h.state().ui.views[0].rotation; - assert!((rot - 45.0).abs() < 0.75, "{rot}"); - press(&mut h, p1, false, true); - h.run_steps(2); - assert_eq!(h.state().session.documents()[0].history.past_len(), 0); - assert_eq!(crate::state::Tool::from_name("RotateView"), Some(crate::state::Tool::RotateView)); - assert_eq!(crate::state::Tool::RotateView.key(), 'R'); - } - - #[test] - fn escape_and_reset_zero_the_angle_without_history() { - let ctx = egui::Context::default(); - let mut app = app_docs(1); - crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"angle": 33})).unwrap(); - assert_eq!(app.session.documents()[0].history.past_len(), 0); - crate::menus::invoke(&mut app, &ctx, "view.resetView", json!({})).unwrap(); - assert_eq!(app.ui.views[0].rotation, 0.0); - assert_eq!(app.session.documents()[0].history.past_len(), 0); - - let mut h = harness(); - h.state_mut().ui.views[0].rotation = 40.0; - h.event(Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }); - h.step(); - h.run_steps(2); - assert!((h.state().ui.views[0].rotation).abs() < 0.05, "{}", h.state().ui.views[0].rotation); - assert_eq!(h.state().session.documents()[0].history.past_len(), 0); - } - - #[test] - fn rotated_view_keeps_engine_selection_in_document_space() { - let mut app = app_docs(1); - app.ui.views[0].rotation = 30.0; - app.run("select.rect", json!({"x": 10, "y": 20, "width": 40, "height": 10})).unwrap(); - let st = app.session.active().unwrap(); - let b = st.doc.selection.as_ref().and_then(|s| photocraft_compose::bounds::content_bounds(s).into()).expect("selection"); - // Axis-aligned in the file: the outline is drawn rotated via ViewXform. - assert!(b.width() >= 40 && b.height() >= 10, "{b:?}"); - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), zoom: 1.0, center: [100.0, 50.0], flip: false, rotation: 30.0, aspect: 1.0 }; - let a = xf.to_screen(10.0, 20.0); - let c = xf.to_screen(50.0, 20.0); - let v = c - a; - let ang = v.y.atan2(v.x).to_degrees(); - assert!((wrap_deg(ang) - 30.0).abs() < 0.5, "{ang}"); - assert_eq!(st.history.past_len(), 1, "only the selection is a history step"); - } - - #[test] - fn gpu_path_stays_on_with_rotation() { - // Flip is the only CPU-blit fallback; rotation is a shader uniform. - assert!(crate::gpu_canvas::gpu_view_ok(false, 45.0, 1.0)); - assert!(!crate::gpu_canvas::gpu_view_ok(true, 45.0, 1.0)); - assert!(crate::gpu_canvas::gpu_view_ok(false, 0.0, 1.0)); - } -} +mod tests; diff --git a/crates/ui-egui/src/rotate_view/tests.rs b/crates/ui-egui/src/rotate_view/tests.rs new file mode 100644 index 0000000000..2705c28ac9 --- /dev/null +++ b/crates/ui-egui/src/rotate_view/tests.rs @@ -0,0 +1,369 @@ +use super::*; +use egui::{Event, PointerButton, pos2}; +use egui_kittest::Harness; +use serde_json::json; + +#[test] +fn wrap_deg_folds_huge_and_hostile_angles() { + assert_eq!(wrap_deg(0.0), 0.0); + assert_eq!(wrap_deg(180.0), 180.0); + assert_eq!(wrap_deg(-180.0), 180.0); + assert!((wrap_deg(190.0) + 170.0).abs() < 1e-4); + assert!((wrap_deg(-190.0) - 170.0).abs() < 1e-4); + assert!((wrap_deg(360.0)).abs() < 1e-4); + assert!((wrap_deg(1.0e10)).abs() <= 180.0); + assert_eq!(wrap_deg(f32::NAN), 0.0); + assert_eq!(wrap_deg(f32::INFINITY), 0.0); + assert_eq!(wrap_deg(f32::NEG_INFINITY), 0.0); +} + +#[test] +fn snap_deg_lands_on_fifteens() { + assert_eq!(snap_deg(0.0, SNAP_DEG), 0.0); + assert_eq!(snap_deg(7.0, SNAP_DEG), 0.0); + assert_eq!(snap_deg(8.0, SNAP_DEG), 15.0); + assert_eq!(snap_deg(-7.0, SNAP_DEG), 0.0); + assert_eq!(snap_deg(-8.0, SNAP_DEG), -15.0); + assert_eq!(snap_deg(40.0, SNAP_DEG), 45.0); + assert_eq!(snap_deg(f32::NAN, SNAP_DEG), 0.0); + assert_eq!(snap_deg(40.0, 0.0), wrap_deg(40.0)); + assert_eq!(snap_deg(40.0, f32::NAN), wrap_deg(40.0)); +} + +#[test] +fn apply_params_sets_adds_resets_and_rejects() { + assert_eq!(apply_params(0.0, &json!({"angle": 30.0})).unwrap(), 30.0); + assert_eq!(apply_params(30.0, &json!({"delta": 15.0})).unwrap(), 45.0); + assert_eq!(apply_params(45.0, &json!({"reset": true})).unwrap(), 0.0); + assert_eq!(apply_params(170.0, &json!({"delta": 20.0})).unwrap(), -170.0); + assert!(apply_params(0.0, &json!({})).is_err()); + assert!(apply_params(0.0, &Value::Null).is_err()); + assert!(apply_params(0.0, &json!("30")).is_err()); + assert!(apply_params(0.0, &json!({"angle": f64::NAN})).is_err()); + assert!(apply_params(0.0, &json!({"angle": f64::INFINITY})).is_err()); + assert!(apply_params(0.0, &json!({"delta": f64::INFINITY})).is_err()); + // JSON can contain finite f64 values whose f32 conversion overflows to infinity. + // Silently wrapping infinity to 0 would reset a rotated view. + assert!(apply_params(32.0, &json!({"angle": 1.0e100})).is_err()); + assert!(apply_params(32.0, &json!({"delta": -1.0e100})).is_err()); + assert!(apply_params(0.0, &json!({"reset": "yes"})).is_err()); + assert!(apply_params(0.0, &json!({"zoom": 1})).is_err()); + let huge = apply_params(0.0, &json!({"angle": 1.0e20})).unwrap(); + assert!(huge.is_finite() && huge.abs() <= 180.0); +} + +#[test] +fn native_rotate_event_reaches_canvas_when_trackpad_rotation_is_enabled() { + let ctx = egui::Context::default(); + let mut enabled = None; + let mut disabled = None; + let raw = egui::RawInput { events: vec![Event::Rotate(std::f32::consts::FRAC_PI_6)], ..Default::default() }; + let mut output = ctx.run_ui(raw, |ui| { + enabled = trackpad_delta(ui.ctx(), true, true); + disabled = trackpad_delta(ui.ctx(), false, true); + }); + output.textures_delta.clear(); + + assert!(enabled.is_some_and(|degrees| (degrees - 30.0).abs() < 1e-3), "{enabled:?}"); + assert_eq!(disabled, None); +} + +/// Preferences › Enhanced Controls › Enable Gestures (#204): off, a two-finger twist on a +/// touch screen doesn't turn the view; the trackpad's `Rotate` event still does. +#[test] +fn enable_gestures_switches_touch_screen_rotation() { + use egui::TouchPhase::{Move, Start}; + let touch = |id: u64, phase, pos| Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(id), phase, pos, force: None }; + let twist = |touch_gestures: bool, extra: Vec| { + let ctx = egui::Context::default(); + let frames = [ + // egui only starts a multi-touch gesture once it knows where the pointer is. + vec![Event::PointerMoved(pos2(50.0, 50.0))], + vec![touch(1, Start, pos2(40.0, 50.0)), touch(2, Start, pos2(60.0, 50.0))], + // A quarter turn about the centre between the fingers. + [vec![touch(1, Move, pos2(50.0, 40.0)), touch(2, Move, pos2(50.0, 60.0))], extra].concat(), + ]; + let mut last = None; + for (n, events) in (0u32..).zip(frames) { + let raw = egui::RawInput { time: Some(f64::from(n) / 60.0), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| last = trackpad_delta(ui.ctx(), true, touch_gestures)); + out.textures_delta.clear(); + } + last + }; + let on = twist(true, Vec::new()); + assert!(on.is_some_and(|d| (d.abs() - 90.0).abs() < 1e-3), "on: the fingers turn the view: {on:?}"); + assert_eq!(twist(false, Vec::new()), None, "off: the fingers don't"); + let trackpad = twist(false, vec![Event::Rotate(std::f32::consts::FRAC_PI_6)]); + assert!(trackpad.is_some_and(|d| (d - 30.0).abs() < 1e-3), "off: a trackpad rotate still turns: {trackpad:?}"); +} + +#[test] +fn trackpad_pref_gates_rotation() { + assert_eq!(apply_trackpad(10.0, false, 0.5), None); + assert_eq!(apply_trackpad(10.0, true, 0.0), None); + assert_eq!(apply_trackpad(10.0, true, f32::NAN), None); + assert_eq!(apply_trackpad(10.0, true, f32::INFINITY), None); + let a = apply_trackpad(10.0, true, std::f32::consts::FRAC_PI_2).expect("finite delta"); + assert!((a - 100.0).abs() < 0.05, "{a}"); +} + +#[test] +fn view_xform_identity_matches_unrotated_mapping() { + for zoom in [0.5, 1.0, 2.5] { + for center in [[0.0, 0.0], [320.0, 240.0], [10.0, -4.0]] { + for flip in [false, true] { + let rect = Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0)); + let a = ViewXform { rect, zoom, center, flip, rotation: 0.0, aspect: 1.0 }; + let sx = if flip { -1.0 } else { 1.0 }; + let want = rect.center() + vec2((10.0 - center[0]) * zoom * sx, (20.0 - center[1]) * zoom); + let got = a.to_screen(10.0, 20.0); + assert!((got.x - want.x).abs() < 1e-4 && (got.y - want.y).abs() < 1e-4, "{got:?} vs {want:?}"); + } + } + } +} + +#[test] +fn view_xform_roundtrip_and_ninety_degrees() { + let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)); + for rot in [15.0, 90.0, -45.0, 180.0] { + for flip in [false, true] { + let xf = ViewXform { rect, zoom: 2.0, center: [80.0, 40.0], flip, rotation: rot, aspect: 1.0 }; + let s = xf.to_screen(10.0, 20.0); + let d = xf.to_doc(s); + assert!((d[0] - 10.0).abs() < 1e-3 && (d[1] - 20.0).abs() < 1e-3, "rot={rot} flip={flip} {d:?}"); + } + } + // 90°: a point on +X in document space lands on +Y on screen (Y-down = clockwise). + let xf = ViewXform { rect, zoom: 1.0, center: [0.0, 0.0], flip: false, rotation: 90.0, aspect: 1.0 }; + let s = xf.to_screen(1.0, 0.0); + let c = rect.center(); + assert!((s.x - c.x).abs() < 1e-3 && (s.y - (c.y + 1.0)).abs() < 1e-3, "{s:?} vs {c:?}"); + // Flip after rotate: 0° +X goes left. + let xf = ViewXform { rect, zoom: 1.0, center: [0.0, 0.0], flip: true, rotation: 0.0, aspect: 1.0 }; + assert!(xf.to_screen(1.0, 0.0).x < rect.center().x); + let xf = ViewXform { rect, zoom: 1.0, center: [0.0, 0.0], flip: true, rotation: 90.0, aspect: 1.0 }; + let s = xf.to_screen(1.0, 0.0); + assert!((s.x - c.x).abs() < 1e-3 && (s.y - (c.y + 1.0)).abs() < 1e-3, "flip then rotate {s:?}"); +} + +/// Screen angle, about the canvas centre, of the document point that was under `p0` at the press. +fn followed_angle(h: &Harness<'static, PhotocraftApp>, p0: Pos2, start_rotation: f32) -> f32 { + let st = h.state(); + let (rect, v, flip) = (st.last_canvas_rect, &st.ui.views[0], st.ui.view.flip_horizontal); + let before = ViewXform { rect, zoom: 1.0, center: v.center, flip, rotation: start_rotation, aspect: 1.0 }; + let d = before.to_doc(p0); + let after = ViewXform { rotation: v.rotation, ..before }; + let s = after.to_screen(d[0] as f32, d[1] as f32) - rect.center(); + wrap_deg(s.y.atan2(s.x).to_degrees() - pointer_deg(p0, rect.center())) +} + +#[test] +fn drag_follows_the_pointer_in_a_flipped_view() { + for flip in [false, true] { + let mut h = harness(); + h.state_mut().ui.view.flip_horizontal = flip; + h.run_steps(2); + let c = h.state().last_canvas_rect.center(); + let p0 = c + vec2(120.0, 0.0); + h.event(Event::PointerMoved(p0)); + h.step(); + press(&mut h, p0, true, false); + // 30° clockwise about the pivot: the image turns 30° clockwise on screen. + let p1 = c + vec2(120.0 * 30f32.to_radians().cos(), 120.0 * 30f32.to_radians().sin()); + h.event(Event::PointerMoved(p1)); + h.step(); + let got = followed_angle(&h, p0, 0.0); + assert!((got - 30.0).abs() < 0.75, "flip={flip}: the image turned {got}°, the pointer 30°"); + press(&mut h, p1, false, false); + } +} + +#[test] +fn screen_delta_mirrors_only_in_a_flipped_view() { + assert_eq!(screen_delta(12.5, false), 12.5); + assert_eq!(screen_delta(12.5, true), -12.5); + assert_eq!(screen_delta(-180.0, true), 180.0); + assert_eq!(screen_delta(f32::NAN, true), 0.0); + assert_eq!(screen_delta(f32::INFINITY, false), 0.0); + // A flipped view still lands on the snapped angle with Shift. + assert_eq!(snap_deg(0.0 + screen_delta(-40.0, true), SNAP_DEG), 45.0); +} + +fn app_docs(n: usize) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for i in 0..n { + app.run("file.new", json!({"width": 200 + i as u32 * 10, "height": 100})).unwrap(); + } + app.sync_views(); + app +} + +#[test] +fn commands_rotate_reset_and_reject_without_a_document() { + let ctx = egui::Context::default(); + let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + assert_eq!(crate::menus::invoke(&mut empty, &ctx, "view.rotateView", json!({"angle": 30})).unwrap_err(), "no document open"); + assert_eq!(crate::menus::invoke(&mut empty, &ctx, "view.resetView", json!({})).unwrap_err(), "no document open"); + + let mut app = app_docs(1); + let r = crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"angle": 30})).unwrap(); + assert_eq!(r["rotation"], 30.0); + assert_eq!(app.ui.views[0].rotation, 30.0); + let r = crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"delta": 15})).unwrap(); + assert_eq!(r["rotation"], 45.0); + let z = app.ui.views[0].zoom; + let c = app.ui.views[0].center; + let r = crate::menus::invoke(&mut app, &ctx, "view.resetView", json!({})).unwrap(); + assert_eq!(r["rotation"], 0.0); + assert_eq!(app.ui.views[0].rotation, 0.0); + assert_eq!(app.ui.views[0].zoom, z); + assert_eq!(app.ui.views[0].center, c); + assert!(crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({})).is_err()); + assert!(crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"angle": f64::NAN})).is_err()); + assert_eq!(app.ui.views[0].rotation, 0.0); + assert_eq!(app.session.documents()[0].history.past_len(), 0); +} + +#[test] +fn ui_set_selects_the_tool_and_sets_rotation() { + let ctx = egui::Context::default(); + let mut app = app_docs(1); + let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"tool": "RotateView", "rotation": 30})); + let out = crate::control::handle(&mut app, &ctx, &req); + let crate::control::Outcome::Done(v) = out else { panic!("done") }; + assert_eq!(v["ok"], true, "{v}"); + assert_eq!(app.ui.tool, crate::state::Tool::RotateView); + assert_eq!(app.ui.views[0].rotation, 30.0); + let (req, _) = crate::control::ControlRequest::new("ui.inspect", json!({})); + let crate::control::Outcome::Done(ins) = crate::control::handle(&mut app, &ctx, &req) else { panic!("inspect") }; + assert_eq!(ins["result"]["tool"], "RotateView"); + assert_eq!(ins["result"]["views"][0]["rotation"], 30.0); + let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"rotation": f64::NAN})); + let crate::control::Outcome::Done(bad) = crate::control::handle(&mut app, &ctx, &req) else { panic!("nan") }; + assert_eq!(bad["ok"], false); + assert_eq!(app.ui.views[0].rotation, 30.0); + let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"tool": "RotateView"})); + let crate::control::Outcome::Done(ok) = crate::control::handle(&mut empty, &ctx, &req) else { panic!("tool") }; + assert_eq!(ok["ok"], true, "{ok}"); + assert_eq!(empty.ui.tool, crate::state::Tool::RotateView); + let (req, _) = crate::control::ControlRequest::new("ui.set", json!({"rotation": 15})); + let crate::control::Outcome::Done(err) = crate::control::handle(&mut empty, &ctx, &req) else { panic!("no doc") }; + assert_eq!(err["ok"], false); + assert!(err["error"].as_str().unwrap().contains("no document open"), "{err}"); +} + +#[test] +fn match_rotation_copies_the_angle_and_needs_two_documents() { + let ctx = egui::Context::default(); + let one = app_docs(1); + assert_eq!(crate::view_cmds::is_enabled(&one, "window.arrange.matchRotation"), Some(false)); + let mut app = app_docs(2); + assert_eq!(crate::view_cmds::is_enabled(&app, "window.arrange.matchRotation"), Some(true)); + app.ui.views[1].rotation = 30.0; + let r = crate::menus::invoke(&mut app, &ctx, "window.arrange.matchRotation", json!({})).unwrap(); + assert_eq!(r["rotation"], 30.0); + assert!(app.ui.views.iter().all(|v| (v.rotation - 30.0).abs() < 1e-4)); + app.ui.views[1].rotation = 12.0; + app.ui.views[1].zoom = 2.0; + crate::menus::invoke(&mut app, &ctx, "window.arrange.matchAll", json!({})).unwrap(); + assert!(app.ui.views.iter().all(|v| (v.rotation - 12.0).abs() < 1e-4 && (v.zoom - 2.0).abs() < 1e-4)); +} + +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.sync_views(); + app.ui.extras.rulers = false; + app.ui.tool = crate::state::Tool::RotateView; + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).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::ALL[0]); + h.run_steps(4); + h +} + +fn press(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, pressed: bool, shift: bool) { + let modifiers = egui::Modifiers { shift, ..Default::default() }; + h.event(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers }); + h.step(); +} + +#[test] +fn shift_drag_snaps_to_fifteen_degrees() { + let mut h = harness(); + let r = h.state().last_canvas_rect; + let c = r.center(); + let p0 = c + vec2(120.0, 0.0); + h.event(Event::PointerMoved(p0)); + h.step(); + h.event(Event::ModifiersChanged(egui::Modifiers::SHIFT)); + h.step(); + press(&mut h, p0, true, true); + // ~40° clockwise: Shift rounds to 45°. + let p1 = c + vec2(120.0 * 40f32.to_radians().cos(), 120.0 * 40f32.to_radians().sin()); + h.event(Event::PointerMoved(p1)); + h.step(); + let rot = h.state().ui.views[0].rotation; + assert!((rot - 45.0).abs() < 0.75, "{rot}"); + press(&mut h, p1, false, true); + h.run_steps(2); + assert_eq!(h.state().session.documents()[0].history.past_len(), 0); + assert_eq!(crate::state::Tool::from_name("RotateView"), Some(crate::state::Tool::RotateView)); + assert_eq!(crate::state::Tool::RotateView.key(), 'R'); +} + +#[test] +fn escape_and_reset_zero_the_angle_without_history() { + let ctx = egui::Context::default(); + let mut app = app_docs(1); + crate::menus::invoke(&mut app, &ctx, "view.rotateView", json!({"angle": 33})).unwrap(); + assert_eq!(app.session.documents()[0].history.past_len(), 0); + crate::menus::invoke(&mut app, &ctx, "view.resetView", json!({})).unwrap(); + assert_eq!(app.ui.views[0].rotation, 0.0); + assert_eq!(app.session.documents()[0].history.past_len(), 0); + + let mut h = harness(); + h.state_mut().ui.views[0].rotation = 40.0; + h.event(Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }); + h.step(); + h.run_steps(2); + assert!((h.state().ui.views[0].rotation).abs() < 0.05, "{}", h.state().ui.views[0].rotation); + assert_eq!(h.state().session.documents()[0].history.past_len(), 0); +} + +#[test] +fn rotated_view_keeps_engine_selection_in_document_space() { + let mut app = app_docs(1); + app.ui.views[0].rotation = 30.0; + app.run("select.rect", json!({"x": 10, "y": 20, "width": 40, "height": 10})).unwrap(); + let st = app.session.active().unwrap(); + let b = st.doc.selection.as_ref().and_then(|s| photocraft_compose::bounds::content_bounds(s).into()).expect("selection"); + // Axis-aligned in the file: the outline is drawn rotated via ViewXform. + assert!(b.width() >= 40 && b.height() >= 10, "{b:?}"); + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)), zoom: 1.0, center: [100.0, 50.0], flip: false, rotation: 30.0, aspect: 1.0 }; + let a = xf.to_screen(10.0, 20.0); + let c = xf.to_screen(50.0, 20.0); + let v = c - a; + let ang = v.y.atan2(v.x).to_degrees(); + assert!((wrap_deg(ang) - 30.0).abs() < 0.5, "{ang}"); + assert_eq!(st.history.past_len(), 1, "only the selection is a history step"); +} + +#[test] +fn gpu_path_stays_on_with_rotation() { + // Flip is the only CPU-blit fallback; rotation is a shader uniform. + assert!(crate::gpu_canvas::gpu_view_ok(false, 45.0, 1.0)); + assert!(!crate::gpu_canvas::gpu_view_ok(true, 45.0, 1.0)); + assert!(crate::gpu_canvas::gpu_view_ok(false, 0.0, 1.0)); +} From 5f55d7c93aaa7de5b82410b192cb17471c45a74a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:04 +0000 Subject: [PATCH 081/259] refactor(ui-egui): move file_ui.rs tests to file_ui/tests.rs --- crates/ui-egui/src/file_ui.rs | 569 +--------------------------- crates/ui-egui/src/file_ui/tests.rs | 566 +++++++++++++++++++++++++++ 2 files changed, 567 insertions(+), 568 deletions(-) create mode 100644 crates/ui-egui/src/file_ui/tests.rs diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index 39b0278b31..f79de746d3 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -1427,574 +1427,7 @@ pub(crate) fn print_status(app: &mut PhotocraftApp, r: &Value) { } #[cfg(test)] -mod tests { - use super::*; - - /// Checks no-jump centering and nonaccumulating screen displacement against shared layout - /// across fit, percentage scaling, orientation and mirroring combinations. - #[test] - fn print_drag_uses_the_resolved_layout_and_screen_points_without_accumulation() { - let (app, _) = app(); - let doc = &app.session.active().unwrap().doc; - for fit in [false, true] { - for mirror in [false, true] { - for orientation in ["portrait", "landscape"] { - let mut f = json!({"center": true, "scale": 175, "scaleToFit": fit, - "emulsionDown": mirror, "orientation": orientation}) - .as_object() - .unwrap() - .clone(); - let start = photocraft_engine::print_cmds::layout(doc, &Value::Object(f.clone()), "file.print").unwrap(); - let page = egui::Rect::from_min_size(egui::pos2(20.0, 30.0), egui::vec2(start.paper.0 as f32, start.paper.1 as f32)); - assert!(drag_print_position(&mut f, start, egui::Vec2::ZERO, 1.0)); - let manual = photocraft_engine::print_cmds::layout(doc, &Value::Object(f.clone()), "file.print").unwrap(); - assert!((manual.rect.0 - start.rect.0).abs() < 1e-9); - assert!((manual.rect.1 - start.rect.1).abs() < 1e-9); - assert_eq!(manual.scale, start.scale); - for k in [0.25, 0.5, 1.0, 2.0] { - let delta = egui::vec2(-90.0, 45.0) * k; - assert!(drag_print_position(&mut f, start, delta, k)); - let moved = photocraft_engine::print_cmds::layout(doc, &Value::Object(f.clone()), "file.print").unwrap(); - let old_img = print_preview_image(start, page, k); - let new_img = print_preview_image(moved, page, k); - assert!((new_img.min - old_img.min - delta).length() < 0.001); - assert_eq!((moved.rect.2, moved.rect.3, moved.scale), (start.rect.2, start.rect.3, start.scale)); - let once = f.clone(); - assert!(drag_print_position(&mut f, start, delta, k)); - assert_eq!(f, once, "total drag displacement must not accumulate"); - } - } - } - } - } - - /// Checks rejected pointer geometry leaves fields untouched and extreme finite drags - /// clamp both inch offsets to the same safety limits as numeric positioning. - #[test] - fn print_drag_rejects_nonfinite_input_and_bounds_offsets() { - let (app, _) = app(); - let doc = &app.session.active().unwrap().doc; - let start = photocraft_engine::print_cmds::layout(doc, &json!({}), "file.print").unwrap(); - let mut f = Map::new(); - for k in [0.0, -1.0, f32::NAN, f32::INFINITY] { - assert!(!drag_print_position(&mut f, start, egui::vec2(10.0, 10.0), k)); - assert!(f.is_empty()); - } - assert!(!drag_print_position(&mut f, start, egui::vec2(f32::NAN, 0.0), 1.0)); - assert!(f.is_empty()); - assert!(drag_print_position(&mut f, start, egui::vec2(-f32::MAX, f32::MAX), 1.0)); - assert_eq!(f["left"], -photocraft_engine::print_cmds::MAX_POSITION_INCHES); - assert_eq!(f["top"], photocraft_engine::print_cmds::MAX_POSITION_INCHES); - } - - fn app() -> (PhotocraftApp, egui::Context) { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 120, "height": 80, "name": "web"})).unwrap(); - (app, egui::Context::default()) - } - - #[test] - fn droplet_folder_follows_the_document_or_uses_a_safe_fallback() { - let (mut app, _) = app(); - let fallback = droplet_default_dir(&app); - #[cfg(target_os = "macos")] - if std::env::var_os("HOME").is_some() { - assert!(std::path::Path::new(&fallback).is_absolute()); - } - #[cfg(not(target_os = "macos"))] - assert_eq!(fallback, "."); - app.session.active_mut().unwrap().path = Some("/tmp/photocraft/drawing.pcraft".into()); - assert_eq!(droplet_default_dir(&app), "/tmp/photocraft"); - } - - #[test] - fn save_for_web_dialog_runs_the_command() { - let (mut app, ctx) = app(); - let r = crate::menus::invoke(&mut app, &ctx, "file.export.saveForWebLegacy", json!({})).unwrap(); - let id = r["dialog"].as_u64().unwrap(); - let dir = std::env::temp_dir().join(format!("pc-webui-{}", std::process::id())); - let path = dir.join("web.gif").to_string_lossy().into_owned(); - let d = app.ui.dialog_mut(id).unwrap(); - d.fields.insert("format".into(), json!("gif")); - d.fields.insert("path".into(), json!(path)); - let r = crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(r["files"][0], json!(path)); - assert!(std::fs::read(&path).unwrap().starts_with(b"GIF89a")); - // The next dialog starts from those settings. - let r = crate::menus::invoke(&mut app, &ctx, "file.export.saveForWebLegacy", json!({})).unwrap(); - let d = app.ui.dialog_mut(r["dialog"].as_u64().unwrap()).unwrap(); - assert_eq!(d.fields["format"], "gif"); - assert!(!d.fields.contains_key("path")); - } - - /// A fresh session's dialog seeds from the preferences: the last export before a restart is - /// remembered there (`web_cmds::remember_web_settings`), as `file_menu` is not saved. - #[test] - fn the_save_for_web_dialog_seeds_from_the_remembered_preferences() { - let (mut app, _) = app(); - app.session.prefs.edit(|p| { - p.dialogs.insert(WEB_COMMAND.into(), json!({"format": "png8", "colors": 64})); - }); - let id = open_web(&mut app); - let f = &app.ui.dialog_mut(id).unwrap().fields; - assert_eq!(f["format"], "png8"); - assert_eq!(f["colors"], 64); - } - - #[test] - fn save_for_web_starts_at_the_current_document_size() { - let (mut app, _) = app(); - let path = std::env::temp_dir().join(format!("pc-webui-size-{}.png", std::process::id())).to_string_lossy().into_owned(); - app.run("file.export.saveForWebLegacy", json!({"path": path, "format": "png24", "width": 60, "height": 40, "percent": 50})).unwrap(); - app.run("file.new", json!({"width": 240, "height": 160, "name": "next"})).unwrap(); - let id = open_web(&mut app); - let f = &app.ui.dialog_mut(id).unwrap().fields; - assert_eq!(f["format"], "png24"); - assert_eq!(f["percent"], 100.0); - assert!(!f.contains_key("width")); - assert!(!f.contains_key("height")); - } - - /// Save for Web's Image Size on a 120 x 80 document, as a PNG-24 (no other number fields). - fn web_size_dialog(app: PhotocraftApp) -> (egui_kittest::Harness<'static, PhotocraftApp>, u64) { - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("semibold".into()))) { - crate::dialogs::show(app, ui.ctx()); - } - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, Default::default()); - let id = open_web(h.state_mut()); - h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("format".into(), json!("png24")); - h.run_steps(5); - (h, id) - } - - /// Types `text` into the number field now showing `value`, and leaves it with Tab. - fn type_into_field(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, value: f64, text: &str) { - use egui_kittest::kittest::{NodeT, Queryable}; - let field = h - .query_all_by_role(egui::accesskit::Role::SpinButton) - .find(|n| n.accesskit_node().numeric_value() == Some(value)) - .map(|n| n.rect()) - .expect("a field showing the value"); - h.hover_at(field.center()); - h.run_steps(1); - h.drag_at(field.center()); - h.run_steps(1); - h.drop_at(field.center()); - h.run_steps(2); - 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); - } - - /// #6388: Save for Web's Image Size has Width and Height linked in proportion, as in - /// Photoshop. A typed width sets the height, the file comes out at that size, and the - /// document itself is never resized. - #[test] - fn save_for_web_width_keeps_proportions_and_sizes_the_file() { - let (app, _) = app(); - let (mut h, id) = web_size_dialog(app); - let revision = h.state().session.active().unwrap().revision; - type_into_field(&mut h, 120.0, "60"); - let f = h.state().ui.dialogs[0].fields.clone(); - assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(60.0), Some(40.0)), "{f:?}"); - // Unlinked, the height changes alone; linked again, it follows the width. - { - use egui_kittest::kittest::Queryable; - h.get_by_label("Constrain proportions").click(); - h.run_steps(3); - type_into_field(&mut h, 40.0, "50"); - let f = h.state().ui.dialogs[0].fields.clone(); - assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(60.0), Some(50.0)), "{f:?}"); - h.get_by_label("Constrain proportions").click(); - h.run_steps(3); - } - let f = h.state().ui.dialogs[0].fields.clone(); - assert_eq!((f["width"].as_f64(), f["height"].as_f64(), f.get("__constrain")), (Some(60.0), Some(40.0), Some(&json!(true))), "{f:?}"); - let path = std::env::temp_dir().join(format!("pc-webui-wh-{}.png", std::process::id())).to_string_lossy().into_owned(); - h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("path".into(), json!(path)); - let r = crate::dialogs::confirm(h.state_mut(), id).unwrap(); - assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(60), Some(40)), "{r}"); - let st = h.state().session.active().unwrap(); - assert_eq!((st.revision, st.doc.size), (revision, photocraft_doc::Size::new(120, 80))); - } - - /// Reopened on another document, Save for Web starts at that document's full size again - /// (#1857) but keeps the resampling method, like the other encoding choices. - #[test] - fn save_for_web_reopens_at_full_size_with_the_resample_method() { - let (app, _) = app(); - let (mut h, id) = web_size_dialog(app); - type_into_field(&mut h, 120.0, "60"); - let path = std::env::temp_dir().join(format!("pc-webui-reopen-{}.png", std::process::id())).to_string_lossy().into_owned(); - let d = h.state_mut().ui.dialog_mut(id).unwrap(); - d.fields.insert("resample".into(), json!("nearest")); - d.fields.insert("path".into(), json!(path)); - crate::dialogs::confirm(h.state_mut(), id).unwrap(); - h.state_mut().run("file.new", json!({"width": 240, "height": 160, "name": "next"})).unwrap(); - let id = open_web(h.state_mut()); - h.run_steps(3); - let f = h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone(); - assert_eq!(f["resample"], "nearest"); - assert!(!f.contains_key("width") && !f.contains_key("height"), "{f:?}"); - let p = web_preview::dimensions(&h.state().session.active().unwrap().doc, ¶ms(&f)).unwrap(); - assert_eq!(p, (240.0, 160.0)); - } - - #[test] - fn save_for_web_downloads_images_and_html_through_the_platform_writer() { - let (mut app, _) = app(); - let downloads = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); - let captured = downloads.clone(); - app.services.write = Some(Box::new(move |path, bytes| { - captured.borrow_mut().push((path.to_string(), bytes.to_vec())); - Ok(()) - })); - download_for_web(&mut app, json!({"path": "web.png", "format": "png24"})).unwrap(); - assert_eq!(downloads.borrow()[0].0, "web.png"); - assert!(downloads.borrow()[0].1.starts_with(b"\x89PNG\r\n\x1a\n")); - downloads.borrow_mut().clear(); - - app.run("slice.new", json!({"rect": [0, 0, 60, 80], "name": "left"})).unwrap(); - download_for_web(&mut app, json!({"dir": ".", "format": "png24", "html": true, "imagesFolder": "images"})).unwrap(); - let files = downloads.borrow(); - let html = std::str::from_utf8(&files.iter().find(|(path, _)| path.ends_with(".html")).unwrap().1).unwrap(); - assert!(!html.contains("images/"), "downloaded files are siblings, not an images directory"); - for (path, bytes) in files.iter().filter(|(path, _)| !path.ends_with(".html")) { - let name = std::path::Path::new(path).file_name().unwrap().to_str().unwrap(); - assert!(html.contains(&format!("src=\"{name}\"")), "missing downloaded image {name}"); - assert!(!bytes.is_empty()); - } - assert!(files.iter().any(|(path, _)| path.ends_with("spacer.gif"))); - drop(files); - - app.services.write = Some(Box::new(|_, _| Err("download failed".into()))); - assert_eq!(download_for_web(&mut app, json!({"path": "fail.png", "format": "png24"})).unwrap_err(), "download failed"); - app.services.write = None; - assert_eq!(download_for_web(&mut app, json!({"path": "missing.png"})).unwrap_err(), "no download service"); - } - - #[test] - fn save_for_web_authorizes_before_opening_a_picker() { - fn deny(_: &str, _: &Value) -> photocraft_engine::Result<()> { - Err(photocraft_engine::EngineError::Other("export denied".into())) - } - for explicit_path in [false, true] { - for synthetic_input in [false, true] { - let (mut app, ctx) = app(); - let id = open_web(&mut app); - if explicit_path { - app.ui.dialog_mut(id).unwrap().fields.insert("path".into(), json!("denied.png")); - } - app.services.automation_authorize = Some(deny); - app.services.file_dialog = Some(Box::new(|_, _, _| panic!("denied export must not show a picker"))); - app.services.write = Some(Box::new(|_, _| panic!("denied export must not write"))); - let error = if synthetic_input { - app.automation_input = true; - crate::dialogs::confirm(&mut app, id).unwrap_err() - } else { - let (request, _) = crate::control::ControlRequest::new("ui.dialog.confirm", json!({"dialog": id})); - let crate::control::Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &request) else { panic!("expected immediate denial") }; - assert_eq!(reply["ok"], false); - reply["error"].as_str().unwrap().to_string() - }; - assert_eq!(error, "export denied"); - assert!(!app.file_dialog_open()); - } - } - } - - #[test] - fn save_for_web_authorizes_generated_palette_before_opening_a_picker() { - fn deny_palette(_: &str, p: &Value) -> photocraft_engine::Result<()> { - if p.get("colorTable").is_some() { Err(photocraft_engine::EngineError::Other("palette denied".into())) } else { Ok(()) } - } - for synthetic_input in [false, true] { - let (mut app, _) = app(); - let id = open_web(&mut app); - let fields = &mut app.ui.dialog_mut(id).unwrap().fields; - fields.insert("format".into(), json!("gif")); - assert!(!fields.contains_key("colorTable")); - if synthetic_input { - app.automation_input = true; - app.services.automation_command = Some(Box::new(|cmd, p| deny_palette(cmd, p).map_err(|e| e.to_string()))); - } else { - app.session.authorize = Some(deny_palette); - } - app.services.file_dialog = Some(Box::new(|_, _, _| panic!("denied palette must not show a picker"))); - app.services.write = Some(Box::new(|_, _| panic!("denied palette must not write"))); - assert_eq!(crate::dialogs::confirm(&mut app, id).unwrap_err(), "palette denied"); - assert!(!app.file_dialog_open()); - } - } - - #[test] - fn web_preview_grows_with_resize_and_accepts_zoom_and_pan() { - let (mut app, _) = app(); - let id = open_web(&mut app); - let revision = app.session.active().unwrap().revision; - app.ui.dialog_mut(id).unwrap().fields.insert("__view".into(), json!("optimized")); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).build_ui_state( - |ui, app| { - if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("semibold".into()))) { - crate::dialogs::show(app, ui.ctx()); - } - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, Default::default()); - h.run_steps(5); - let pane = |h: &egui_kittest::Harness<'_, PhotocraftApp>| { - let r = &h.state().ui.dialogs[0].fields["__previewRects"][0]; - egui::Rect::from_min_max( - egui::pos2(r[0].as_f64().unwrap() as f32, r[1].as_f64().unwrap() as f32), - egui::pos2(r[2].as_f64().unwrap() as f32, r[3].as_f64().unwrap() as f32), - ) - }; - let before = pane(&h); - let rects: Vec = h.ctx.data(|m| m.get_temp(egui::Id::unique("pc-dialog-rects"))).unwrap(); - let corner = rects[0].max - egui::vec2(14.0, 14.0); - h.event(egui::Event::PointerMoved(corner)); - h.step(); - h.event(egui::Event::PointerButton { pos: corner, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); - h.step(); - let end = corner + egui::vec2(180.0, 100.0); - h.event(egui::Event::PointerMoved(end)); - h.step(); - h.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); - h.run_steps(4); - let after = pane(&h); - assert!(after.width() > before.width() + 100.0, "before {before:?}, after {after:?}, corner {corner:?}"); - assert!(after.height() > before.height() + 50.0); - // Zoom in enough that the small fixture can pan, then drag the real pane. - h.state_mut().ui.dialogs[0].fields.insert("__zoom".into(), json!(16.0)); - h.run_steps(3); - let at = pane(&h).center(); - h.event(egui::Event::PointerMoved(at)); - h.step(); - h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); - h.step(); - let end = at + egui::vec2(35.0, 20.0); - h.event(egui::Event::PointerMoved(end)); - h.step(); - h.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); - h.run_steps(3); - assert_ne!(h.state().ui.dialogs[0].fields["__center"], json!([0.5, 0.5])); - assert_eq!(h.state().session.active().unwrap().revision, revision); - // Enter while editing a swatch must not export and close the parent dialog. - h.state_mut().ui.dialogs[0].fields.insert("format".into(), json!("gif")); - h.run_steps(4); - use egui_kittest::kittest::Queryable; - h.get_by_role(egui::accesskit::Role::ColorWell).click(); - h.run_steps(3); - assert!(egui::Popup::is_any_open(&h.ctx)); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(h.state().ui.dialogs.len(), 1); - } - - #[test] - fn palette_draft_survives_navigation_and_resets_when_colors_change() { - let (app, _) = app(); - let mut f = serde_json::from_value::>(json!({"format": "gif", "colors": 16})).unwrap(); - web_preview::prepare_table(&app, &mut f).unwrap(); - let table = f["colorTable"].clone(); - f.insert("colorTableEdits".into(), json!({"0": "#12ab34"})); - f.insert("__zoom".into(), json!(2.0)); - f.insert("__center".into(), json!([0.25, 0.75])); - web_preview::prepare_table(&app, &mut f).unwrap(); - assert_eq!(f["colorTable"], table); - assert_eq!(f["colorTableEdits"]["0"], "#12ab34"); - f.insert("metadata".into(), json!("none")); - f.insert("interlaced".into(), json!(true)); - f.insert("dither".into(), json!("pattern")); - web_preview::prepare_table(&app, &mut f).unwrap(); - assert_eq!(f["colorTableEdits"]["0"], "#12ab34", "non-palette settings must retain edits"); - f.insert("colors".into(), json!(8)); - web_preview::prepare_table(&app, &mut f).unwrap(); - assert!(!f.contains_key("colorTableEdits")); - assert!(f["colorTable"].as_array().unwrap().len() <= 8); - } - - #[test] - fn print_dialog_and_toggles() { - let (mut app, ctx) = app(); - let r = crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap(); - let id = r["dialog"].as_u64().unwrap(); - let out = std::env::temp_dir().join(format!("pc-printui-{}.pdf", std::process::id())).to_string_lossy().into_owned(); - app.ui.dialog_mut(id).unwrap().fields.insert("output".into(), json!(out)); - let r = crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(r["sent"], false); - assert!(std::fs::read(&out).unwrap().starts_with(b"%PDF")); - assert_eq!(checked(&app, "view.lockSlices"), Some(false)); - crate::menus::invoke(&mut app, &ctx, "view.lockSlices", json!({})).unwrap(); - assert_eq!(checked(&app, "view.lockSlices"), Some(true)); - // Generator is opt-in (Preferences ▸ Plug-ins), as in Photoshop: the menu item is - // unavailable until it is enabled. - assert!(crate::menus::invoke(&mut app, &ctx, "file.generate.imageAssets", json!({})).is_err()); - app.run("prefs.set", json!({"path": "plugIns.generatorEnabled", "value": true})).unwrap(); - crate::menus::invoke(&mut app, &ctx, "file.generate.imageAssets", json!({})).unwrap(); - assert_eq!(checked(&app, "file.generate.imageAssets"), Some(true)); - // Form dialogs open for the rest. - for id in ["file.automate.contactSheetII", "file.scripts.statistics", "file.scripts.scriptEventsManager", "file.package"] { - let r = crate::menus::invoke(&mut app, &ctx, id, json!({})).unwrap(); - assert!(r["dialog"].is_u64(), "{id}"); - } - } - - #[test] - fn printer_menu_lists_the_spooler_printers_after_the_default() { - let list = json!([{"name": "HP_OfficeJet_3830_series", "default": true}, {"name": "DNP_DP_DS620", "default": false}]); - let o = printer_options(Some(&list), ""); - let keys: Vec<&str> = o.iter().map(|p| p.0.as_str()).collect(); - assert_eq!(keys, ["", "HP_OfficeJet_3830_series", "DNP_DP_DS620"]); - assert!(o[0].1.ends_with("(HP OfficeJet 3830 series)"), "{}", o[0].1); - assert_eq!(o[2].1, "DNP DP DS620"); - // A remembered printer that's gone stays selectable; no list still offers the default. - let o = printer_options(Some(&list), "Old_Queue"); - assert_eq!(o.last().unwrap().0, "Old_Queue"); - assert_eq!(printer_options(None, "").len(), 1); - // The dialog asks the engine, and the list never reaches file.print's params. - let (mut app, ctx) = app(); - let id = crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap()["dialog"].as_u64().unwrap(); - let f = &app.ui.dialog_mut(id).unwrap().fields; - assert!(f.get("__systemPrinters").is_some_and(Value::is_array)); - assert!(params(f).get("__systemPrinters").is_none()); - assert!(params(f).get("__printers").is_none()); - } - - /// An output path or a preview typed and confirmed in one frame doesn't take the driver's area. - #[test] - fn the_printable_area_goes_only_with_a_print_to_the_printer() { - let area = json!([0.0, 0.0, 842.29, 1191.14]); - let mut f = Map::new(); - f.insert("printable".into(), area.clone()); - assert_eq!(print_params(&f)["printable"], area); - f.insert("output".into(), json!("/tmp/out.pdf")); - assert!(print_params(&f).get("printable").is_none()); - f.insert("output".into(), json!("")); - f.insert("dryRun".into(), json!(true)); - assert!(print_params(&f).get("printable").is_none()); - } - - /// #7410: File › Print opens with the settings of the last print, also those remembered from - /// an earlier session (the preferences), before anything was printed in this one. - #[test] - fn print_dialog_opens_with_the_settings_remembered_from_an_earlier_session() { - let (mut app, _) = app(); - app.session.prefs.edit(|p| { - p.dialogs.insert( - photocraft_engine::print_cmds::REMEMBERED.into(), - json!({"paper": "a5", "scale": 50, "orientation": "landscape", "intent": "perceptual"}), - ); - }); - let id = open_print(&mut app); - let f = &app.ui.dialog_mut(id).unwrap().fields; - assert_eq!((&f["paper"], &f["scale"], &f["orientation"], &f["intent"]), (&json!("a5"), &json!(50), &json!("landscape"), &json!("perceptual"))); - assert_eq!(f["copies"], 1, "what wasn't remembered keeps its default"); - } - - /// #5328: Save as PDF has Browse…, which fills the field from a Save dialog (suggesting the - /// document's name as a PDF) rather than needing a typed path. - #[test] - fn save_as_pdf_browse_fills_the_output_from_a_save_dialog() { - use crate::file_dialog::{FileDialogAnswer, FileDialogRequest}; - use egui_kittest::{Harness, kittest::Queryable}; - let out = std::env::temp_dir().join(format!("pc-printui-browse-{}", std::process::id())).to_string_lossy().into_owned(); - let (show, asked) = crate::file_dialog::fake(vec![Some(FileDialogAnswer::SaveTo(out.clone()))]); - let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { file_dialog: Some(show), ..Default::default() }) - }); - h.state_mut().run("file.new", json!({"width": 120, "height": 80, "name": "poster"})).unwrap(); - let id = open_print(h.state_mut()); - h.run_steps(3); - h.get_by_label("Browse…").click(); - h.run_steps(4); - assert!(matches!(asked.borrow().as_slice(), [FileDialogRequest::Save { suggested }] if suggested.ends_with("poster.pdf")), "{:?}", asked.borrow()); - // A name chosen without an extension gets the suggested one. - assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields["output"], json!(format!("{out}.pdf"))); - } - - #[test] - fn print_dialog_does_not_inherit_scripted_send_override() { - for send in [false, true] { - let (mut app, ctx) = app(); - let out = std::env::temp_dir().join(format!("pc-printui-state-{}-{send}.pdf", std::process::id())).to_string_lossy().into_owned(); - app.session.execute("file.print", json!({"output": out, "send": send, "dryRun": true})).unwrap(); - assert!(app.session.file_menu.last_print.as_ref().unwrap().get("send").is_none()); - let r = crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap(); - let id = r["dialog"].as_u64().unwrap(); - assert!(app.ui.dialog_mut(id).unwrap().fields.get("send").is_none()); - std::fs::remove_file(out).unwrap(); - } - } - - /// The Orientation buttons show the driver paper's shape: landscape when it is wider than tall. - #[test] - fn orientation_follows_the_driver_paper() { - let with = |paper: Value| { - let mut f = Map::new(); - f.insert("paper".into(), paper); - f - }; - assert!(driver_paper_is_wide(&with(json!([1191.14, 842.29])))); - assert!(!driver_paper_is_wide(&with(json!([842.29, 1191.14])))); - assert!(!driver_paper_is_wide(&with(json!("a3"))), "a named paper is not a driver page"); - assert!(!driver_paper_is_wide(&Map::new())); - } - - /// Turning a printer whose driver can't be asked keeps its settings and says why on the dialog. - #[test] - fn turning_without_a_driver_keeps_the_settings_and_shows_the_error() { - // Valid driver settings (a minimal DEVMODEW: 220 bytes, no private part), so the command - // gets past reading them and fails where it asks the (missing) printer for its page. - let mut dm = vec![0u8; 220]; - dm[68..70].copy_from_slice(&220u16.to_le_bytes()); - let hex: String = dm.iter().map(|b| format!("{b:02x}")).collect(); - assert!(craft_print::rgb::DevMode::from_hex(&hex).is_ok()); - let (mut app, _) = app(); - let mut f = Map::new(); - f.insert("printer".into(), json!("photocraft-no-such-printer")); - f.insert("printerSettings".into(), json!(hex)); - f.insert("paper".into(), json!([595.28, 841.89])); - turn_driver(&mut app, &mut f, true); - assert_eq!(f.get("printerSettings"), Some(&json!(hex))); - assert_eq!(f.get("paper"), Some(&json!([595.28, 841.89]))); - let error = f.get("__pageError").and_then(Value::as_str).unwrap_or_default(); - // Reading bad settings fails with "printer settings are too short / damaged"; this must not. - assert!(!error.is_empty() && !error.contains("printer settings are"), "failed at the printer, not at reading the settings: {error}"); - } - - /// A turn takes the settings and the paper from the same answer, never one without the other. - #[test] - fn a_turn_takes_settings_and_paper_together() { - let fields = || { - let mut f = Map::new(); - f.insert("printerSettings".into(), json!("old")); - f.insert("paper".into(), json!([595.28, 841.89])); - f.insert("__pageError".into(), json!("earlier")); - f - }; - let mut f = fields(); - take_turned_page(&mut f, &json!({"printerSettings": "new", "paper": [841.89, 595.28]})); - assert_eq!((f.get("printerSettings"), f.get("paper")), (Some(&json!("new")), Some(&json!([841.89, 595.28])))); - assert_eq!(f.get("orientation"), Some(&json!("portrait")), "the driver paper is already turned"); - assert!(f.get("__pageError").is_none()); - for partial in [json!({"printerSettings": "new"}), json!({"paper": [841.89, 595.28]}), json!({"printerSettings": "new", "paper": [841.89]})] { - let mut f = fields(); - take_turned_page(&mut f, &partial); - assert_eq!((f.get("printerSettings"), f.get("paper")), (Some(&json!("old")), Some(&json!([595.28, 841.89]))), "{partial}"); - assert!(f.get("__pageError").is_some(), "{partial}"); - } - } -} +mod tests; #[cfg(test)] mod web_playback_tests { diff --git a/crates/ui-egui/src/file_ui/tests.rs b/crates/ui-egui/src/file_ui/tests.rs new file mode 100644 index 0000000000..1a6a882456 --- /dev/null +++ b/crates/ui-egui/src/file_ui/tests.rs @@ -0,0 +1,566 @@ +use super::*; + +/// Checks no-jump centering and nonaccumulating screen displacement against shared layout +/// across fit, percentage scaling, orientation and mirroring combinations. +#[test] +fn print_drag_uses_the_resolved_layout_and_screen_points_without_accumulation() { + let (app, _) = app(); + let doc = &app.session.active().unwrap().doc; + for fit in [false, true] { + for mirror in [false, true] { + for orientation in ["portrait", "landscape"] { + let mut f = json!({"center": true, "scale": 175, "scaleToFit": fit, + "emulsionDown": mirror, "orientation": orientation}) + .as_object() + .unwrap() + .clone(); + let start = photocraft_engine::print_cmds::layout(doc, &Value::Object(f.clone()), "file.print").unwrap(); + let page = egui::Rect::from_min_size(egui::pos2(20.0, 30.0), egui::vec2(start.paper.0 as f32, start.paper.1 as f32)); + assert!(drag_print_position(&mut f, start, egui::Vec2::ZERO, 1.0)); + let manual = photocraft_engine::print_cmds::layout(doc, &Value::Object(f.clone()), "file.print").unwrap(); + assert!((manual.rect.0 - start.rect.0).abs() < 1e-9); + assert!((manual.rect.1 - start.rect.1).abs() < 1e-9); + assert_eq!(manual.scale, start.scale); + for k in [0.25, 0.5, 1.0, 2.0] { + let delta = egui::vec2(-90.0, 45.0) * k; + assert!(drag_print_position(&mut f, start, delta, k)); + let moved = photocraft_engine::print_cmds::layout(doc, &Value::Object(f.clone()), "file.print").unwrap(); + let old_img = print_preview_image(start, page, k); + let new_img = print_preview_image(moved, page, k); + assert!((new_img.min - old_img.min - delta).length() < 0.001); + assert_eq!((moved.rect.2, moved.rect.3, moved.scale), (start.rect.2, start.rect.3, start.scale)); + let once = f.clone(); + assert!(drag_print_position(&mut f, start, delta, k)); + assert_eq!(f, once, "total drag displacement must not accumulate"); + } + } + } + } +} + +/// Checks rejected pointer geometry leaves fields untouched and extreme finite drags +/// clamp both inch offsets to the same safety limits as numeric positioning. +#[test] +fn print_drag_rejects_nonfinite_input_and_bounds_offsets() { + let (app, _) = app(); + let doc = &app.session.active().unwrap().doc; + let start = photocraft_engine::print_cmds::layout(doc, &json!({}), "file.print").unwrap(); + let mut f = Map::new(); + for k in [0.0, -1.0, f32::NAN, f32::INFINITY] { + assert!(!drag_print_position(&mut f, start, egui::vec2(10.0, 10.0), k)); + assert!(f.is_empty()); + } + assert!(!drag_print_position(&mut f, start, egui::vec2(f32::NAN, 0.0), 1.0)); + assert!(f.is_empty()); + assert!(drag_print_position(&mut f, start, egui::vec2(-f32::MAX, f32::MAX), 1.0)); + assert_eq!(f["left"], -photocraft_engine::print_cmds::MAX_POSITION_INCHES); + assert_eq!(f["top"], photocraft_engine::print_cmds::MAX_POSITION_INCHES); +} + +fn app() -> (PhotocraftApp, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 120, "height": 80, "name": "web"})).unwrap(); + (app, egui::Context::default()) +} + +#[test] +fn droplet_folder_follows_the_document_or_uses_a_safe_fallback() { + let (mut app, _) = app(); + let fallback = droplet_default_dir(&app); + #[cfg(target_os = "macos")] + if std::env::var_os("HOME").is_some() { + assert!(std::path::Path::new(&fallback).is_absolute()); + } + #[cfg(not(target_os = "macos"))] + assert_eq!(fallback, "."); + app.session.active_mut().unwrap().path = Some("/tmp/photocraft/drawing.pcraft".into()); + assert_eq!(droplet_default_dir(&app), "/tmp/photocraft"); +} + +#[test] +fn save_for_web_dialog_runs_the_command() { + let (mut app, ctx) = app(); + let r = crate::menus::invoke(&mut app, &ctx, "file.export.saveForWebLegacy", json!({})).unwrap(); + let id = r["dialog"].as_u64().unwrap(); + let dir = std::env::temp_dir().join(format!("pc-webui-{}", std::process::id())); + let path = dir.join("web.gif").to_string_lossy().into_owned(); + let d = app.ui.dialog_mut(id).unwrap(); + d.fields.insert("format".into(), json!("gif")); + d.fields.insert("path".into(), json!(path)); + let r = crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(r["files"][0], json!(path)); + assert!(std::fs::read(&path).unwrap().starts_with(b"GIF89a")); + // The next dialog starts from those settings. + let r = crate::menus::invoke(&mut app, &ctx, "file.export.saveForWebLegacy", json!({})).unwrap(); + let d = app.ui.dialog_mut(r["dialog"].as_u64().unwrap()).unwrap(); + assert_eq!(d.fields["format"], "gif"); + assert!(!d.fields.contains_key("path")); +} + +/// A fresh session's dialog seeds from the preferences: the last export before a restart is +/// remembered there (`web_cmds::remember_web_settings`), as `file_menu` is not saved. +#[test] +fn the_save_for_web_dialog_seeds_from_the_remembered_preferences() { + let (mut app, _) = app(); + app.session.prefs.edit(|p| { + p.dialogs.insert(WEB_COMMAND.into(), json!({"format": "png8", "colors": 64})); + }); + let id = open_web(&mut app); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!(f["format"], "png8"); + assert_eq!(f["colors"], 64); +} + +#[test] +fn save_for_web_starts_at_the_current_document_size() { + let (mut app, _) = app(); + let path = std::env::temp_dir().join(format!("pc-webui-size-{}.png", std::process::id())).to_string_lossy().into_owned(); + app.run("file.export.saveForWebLegacy", json!({"path": path, "format": "png24", "width": 60, "height": 40, "percent": 50})).unwrap(); + app.run("file.new", json!({"width": 240, "height": 160, "name": "next"})).unwrap(); + let id = open_web(&mut app); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!(f["format"], "png24"); + assert_eq!(f["percent"], 100.0); + assert!(!f.contains_key("width")); + assert!(!f.contains_key("height")); +} + +/// Save for Web's Image Size on a 120 x 80 document, as a PNG-24 (no other number fields). +fn web_size_dialog(app: PhotocraftApp) -> (egui_kittest::Harness<'static, PhotocraftApp>, u64) { + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("semibold".into()))) { + crate::dialogs::show(app, ui.ctx()); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + let id = open_web(h.state_mut()); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("format".into(), json!("png24")); + h.run_steps(5); + (h, id) +} + +/// Types `text` into the number field now showing `value`, and leaves it with Tab. +fn type_into_field(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, value: f64, text: &str) { + use egui_kittest::kittest::{NodeT, Queryable}; + let field = h + .query_all_by_role(egui::accesskit::Role::SpinButton) + .find(|n| n.accesskit_node().numeric_value() == Some(value)) + .map(|n| n.rect()) + .expect("a field showing the value"); + h.hover_at(field.center()); + h.run_steps(1); + h.drag_at(field.center()); + h.run_steps(1); + h.drop_at(field.center()); + h.run_steps(2); + 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); +} + +/// #6388: Save for Web's Image Size has Width and Height linked in proportion, as in +/// Photoshop. A typed width sets the height, the file comes out at that size, and the +/// document itself is never resized. +#[test] +fn save_for_web_width_keeps_proportions_and_sizes_the_file() { + let (app, _) = app(); + let (mut h, id) = web_size_dialog(app); + let revision = h.state().session.active().unwrap().revision; + type_into_field(&mut h, 120.0, "60"); + let f = h.state().ui.dialogs[0].fields.clone(); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(60.0), Some(40.0)), "{f:?}"); + // Unlinked, the height changes alone; linked again, it follows the width. + { + use egui_kittest::kittest::Queryable; + h.get_by_label("Constrain proportions").click(); + h.run_steps(3); + type_into_field(&mut h, 40.0, "50"); + let f = h.state().ui.dialogs[0].fields.clone(); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(60.0), Some(50.0)), "{f:?}"); + h.get_by_label("Constrain proportions").click(); + h.run_steps(3); + } + let f = h.state().ui.dialogs[0].fields.clone(); + assert_eq!((f["width"].as_f64(), f["height"].as_f64(), f.get("__constrain")), (Some(60.0), Some(40.0), Some(&json!(true))), "{f:?}"); + let path = std::env::temp_dir().join(format!("pc-webui-wh-{}.png", std::process::id())).to_string_lossy().into_owned(); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("path".into(), json!(path)); + let r = crate::dialogs::confirm(h.state_mut(), id).unwrap(); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(60), Some(40)), "{r}"); + let st = h.state().session.active().unwrap(); + assert_eq!((st.revision, st.doc.size), (revision, photocraft_doc::Size::new(120, 80))); +} + +/// Reopened on another document, Save for Web starts at that document's full size again +/// (#1857) but keeps the resampling method, like the other encoding choices. +#[test] +fn save_for_web_reopens_at_full_size_with_the_resample_method() { + let (app, _) = app(); + let (mut h, id) = web_size_dialog(app); + type_into_field(&mut h, 120.0, "60"); + let path = std::env::temp_dir().join(format!("pc-webui-reopen-{}.png", std::process::id())).to_string_lossy().into_owned(); + let d = h.state_mut().ui.dialog_mut(id).unwrap(); + d.fields.insert("resample".into(), json!("nearest")); + d.fields.insert("path".into(), json!(path)); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + h.state_mut().run("file.new", json!({"width": 240, "height": 160, "name": "next"})).unwrap(); + let id = open_web(h.state_mut()); + h.run_steps(3); + let f = h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone(); + assert_eq!(f["resample"], "nearest"); + assert!(!f.contains_key("width") && !f.contains_key("height"), "{f:?}"); + let p = web_preview::dimensions(&h.state().session.active().unwrap().doc, ¶ms(&f)).unwrap(); + assert_eq!(p, (240.0, 160.0)); +} + +#[test] +fn save_for_web_downloads_images_and_html_through_the_platform_writer() { + let (mut app, _) = app(); + let downloads = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let captured = downloads.clone(); + app.services.write = Some(Box::new(move |path, bytes| { + captured.borrow_mut().push((path.to_string(), bytes.to_vec())); + Ok(()) + })); + download_for_web(&mut app, json!({"path": "web.png", "format": "png24"})).unwrap(); + assert_eq!(downloads.borrow()[0].0, "web.png"); + assert!(downloads.borrow()[0].1.starts_with(b"\x89PNG\r\n\x1a\n")); + downloads.borrow_mut().clear(); + + app.run("slice.new", json!({"rect": [0, 0, 60, 80], "name": "left"})).unwrap(); + download_for_web(&mut app, json!({"dir": ".", "format": "png24", "html": true, "imagesFolder": "images"})).unwrap(); + let files = downloads.borrow(); + let html = std::str::from_utf8(&files.iter().find(|(path, _)| path.ends_with(".html")).unwrap().1).unwrap(); + assert!(!html.contains("images/"), "downloaded files are siblings, not an images directory"); + for (path, bytes) in files.iter().filter(|(path, _)| !path.ends_with(".html")) { + let name = std::path::Path::new(path).file_name().unwrap().to_str().unwrap(); + assert!(html.contains(&format!("src=\"{name}\"")), "missing downloaded image {name}"); + assert!(!bytes.is_empty()); + } + assert!(files.iter().any(|(path, _)| path.ends_with("spacer.gif"))); + drop(files); + + app.services.write = Some(Box::new(|_, _| Err("download failed".into()))); + assert_eq!(download_for_web(&mut app, json!({"path": "fail.png", "format": "png24"})).unwrap_err(), "download failed"); + app.services.write = None; + assert_eq!(download_for_web(&mut app, json!({"path": "missing.png"})).unwrap_err(), "no download service"); +} + +#[test] +fn save_for_web_authorizes_before_opening_a_picker() { + fn deny(_: &str, _: &Value) -> photocraft_engine::Result<()> { + Err(photocraft_engine::EngineError::Other("export denied".into())) + } + for explicit_path in [false, true] { + for synthetic_input in [false, true] { + let (mut app, ctx) = app(); + let id = open_web(&mut app); + if explicit_path { + app.ui.dialog_mut(id).unwrap().fields.insert("path".into(), json!("denied.png")); + } + app.services.automation_authorize = Some(deny); + app.services.file_dialog = Some(Box::new(|_, _, _| panic!("denied export must not show a picker"))); + app.services.write = Some(Box::new(|_, _| panic!("denied export must not write"))); + let error = if synthetic_input { + app.automation_input = true; + crate::dialogs::confirm(&mut app, id).unwrap_err() + } else { + let (request, _) = crate::control::ControlRequest::new("ui.dialog.confirm", json!({"dialog": id})); + let crate::control::Outcome::Done(reply) = crate::control::handle(&mut app, &ctx, &request) else { panic!("expected immediate denial") }; + assert_eq!(reply["ok"], false); + reply["error"].as_str().unwrap().to_string() + }; + assert_eq!(error, "export denied"); + assert!(!app.file_dialog_open()); + } + } +} + +#[test] +fn save_for_web_authorizes_generated_palette_before_opening_a_picker() { + fn deny_palette(_: &str, p: &Value) -> photocraft_engine::Result<()> { + if p.get("colorTable").is_some() { Err(photocraft_engine::EngineError::Other("palette denied".into())) } else { Ok(()) } + } + for synthetic_input in [false, true] { + let (mut app, _) = app(); + let id = open_web(&mut app); + let fields = &mut app.ui.dialog_mut(id).unwrap().fields; + fields.insert("format".into(), json!("gif")); + assert!(!fields.contains_key("colorTable")); + if synthetic_input { + app.automation_input = true; + app.services.automation_command = Some(Box::new(|cmd, p| deny_palette(cmd, p).map_err(|e| e.to_string()))); + } else { + app.session.authorize = Some(deny_palette); + } + app.services.file_dialog = Some(Box::new(|_, _, _| panic!("denied palette must not show a picker"))); + app.services.write = Some(Box::new(|_, _| panic!("denied palette must not write"))); + assert_eq!(crate::dialogs::confirm(&mut app, id).unwrap_err(), "palette denied"); + assert!(!app.file_dialog_open()); + } +} + +#[test] +fn web_preview_grows_with_resize_and_accepts_zoom_and_pan() { + let (mut app, _) = app(); + let id = open_web(&mut app); + let revision = app.session.active().unwrap().revision; + app.ui.dialog_mut(id).unwrap().fields.insert("__view".into(), json!("optimized")); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).build_ui_state( + |ui, app| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("semibold".into()))) { + crate::dialogs::show(app, ui.ctx()); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(5); + let pane = |h: &egui_kittest::Harness<'_, PhotocraftApp>| { + let r = &h.state().ui.dialogs[0].fields["__previewRects"][0]; + egui::Rect::from_min_max( + egui::pos2(r[0].as_f64().unwrap() as f32, r[1].as_f64().unwrap() as f32), + egui::pos2(r[2].as_f64().unwrap() as f32, r[3].as_f64().unwrap() as f32), + ) + }; + let before = pane(&h); + let rects: Vec = h.ctx.data(|m| m.get_temp(egui::Id::unique("pc-dialog-rects"))).unwrap(); + let corner = rects[0].max - egui::vec2(14.0, 14.0); + h.event(egui::Event::PointerMoved(corner)); + h.step(); + h.event(egui::Event::PointerButton { pos: corner, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.step(); + let end = corner + egui::vec2(180.0, 100.0); + h.event(egui::Event::PointerMoved(end)); + h.step(); + h.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(4); + let after = pane(&h); + assert!(after.width() > before.width() + 100.0, "before {before:?}, after {after:?}, corner {corner:?}"); + assert!(after.height() > before.height() + 50.0); + // Zoom in enough that the small fixture can pan, then drag the real pane. + h.state_mut().ui.dialogs[0].fields.insert("__zoom".into(), json!(16.0)); + h.run_steps(3); + let at = pane(&h).center(); + h.event(egui::Event::PointerMoved(at)); + h.step(); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.step(); + let end = at + egui::vec2(35.0, 20.0); + h.event(egui::Event::PointerMoved(end)); + h.step(); + h.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); + assert_ne!(h.state().ui.dialogs[0].fields["__center"], json!([0.5, 0.5])); + assert_eq!(h.state().session.active().unwrap().revision, revision); + // Enter while editing a swatch must not export and close the parent dialog. + h.state_mut().ui.dialogs[0].fields.insert("format".into(), json!("gif")); + h.run_steps(4); + use egui_kittest::kittest::Queryable; + h.get_by_role(egui::accesskit::Role::ColorWell).click(); + h.run_steps(3); + assert!(egui::Popup::is_any_open(&h.ctx)); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(h.state().ui.dialogs.len(), 1); +} + +#[test] +fn palette_draft_survives_navigation_and_resets_when_colors_change() { + let (app, _) = app(); + let mut f = serde_json::from_value::>(json!({"format": "gif", "colors": 16})).unwrap(); + web_preview::prepare_table(&app, &mut f).unwrap(); + let table = f["colorTable"].clone(); + f.insert("colorTableEdits".into(), json!({"0": "#12ab34"})); + f.insert("__zoom".into(), json!(2.0)); + f.insert("__center".into(), json!([0.25, 0.75])); + web_preview::prepare_table(&app, &mut f).unwrap(); + assert_eq!(f["colorTable"], table); + assert_eq!(f["colorTableEdits"]["0"], "#12ab34"); + f.insert("metadata".into(), json!("none")); + f.insert("interlaced".into(), json!(true)); + f.insert("dither".into(), json!("pattern")); + web_preview::prepare_table(&app, &mut f).unwrap(); + assert_eq!(f["colorTableEdits"]["0"], "#12ab34", "non-palette settings must retain edits"); + f.insert("colors".into(), json!(8)); + web_preview::prepare_table(&app, &mut f).unwrap(); + assert!(!f.contains_key("colorTableEdits")); + assert!(f["colorTable"].as_array().unwrap().len() <= 8); +} + +#[test] +fn print_dialog_and_toggles() { + let (mut app, ctx) = app(); + let r = crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap(); + let id = r["dialog"].as_u64().unwrap(); + let out = std::env::temp_dir().join(format!("pc-printui-{}.pdf", std::process::id())).to_string_lossy().into_owned(); + app.ui.dialog_mut(id).unwrap().fields.insert("output".into(), json!(out)); + let r = crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(r["sent"], false); + assert!(std::fs::read(&out).unwrap().starts_with(b"%PDF")); + assert_eq!(checked(&app, "view.lockSlices"), Some(false)); + crate::menus::invoke(&mut app, &ctx, "view.lockSlices", json!({})).unwrap(); + assert_eq!(checked(&app, "view.lockSlices"), Some(true)); + // Generator is opt-in (Preferences ▸ Plug-ins), as in Photoshop: the menu item is + // unavailable until it is enabled. + assert!(crate::menus::invoke(&mut app, &ctx, "file.generate.imageAssets", json!({})).is_err()); + app.run("prefs.set", json!({"path": "plugIns.generatorEnabled", "value": true})).unwrap(); + crate::menus::invoke(&mut app, &ctx, "file.generate.imageAssets", json!({})).unwrap(); + assert_eq!(checked(&app, "file.generate.imageAssets"), Some(true)); + // Form dialogs open for the rest. + for id in ["file.automate.contactSheetII", "file.scripts.statistics", "file.scripts.scriptEventsManager", "file.package"] { + let r = crate::menus::invoke(&mut app, &ctx, id, json!({})).unwrap(); + assert!(r["dialog"].is_u64(), "{id}"); + } +} + +#[test] +fn printer_menu_lists_the_spooler_printers_after_the_default() { + let list = json!([{"name": "HP_OfficeJet_3830_series", "default": true}, {"name": "DNP_DP_DS620", "default": false}]); + let o = printer_options(Some(&list), ""); + let keys: Vec<&str> = o.iter().map(|p| p.0.as_str()).collect(); + assert_eq!(keys, ["", "HP_OfficeJet_3830_series", "DNP_DP_DS620"]); + assert!(o[0].1.ends_with("(HP OfficeJet 3830 series)"), "{}", o[0].1); + assert_eq!(o[2].1, "DNP DP DS620"); + // A remembered printer that's gone stays selectable; no list still offers the default. + let o = printer_options(Some(&list), "Old_Queue"); + assert_eq!(o.last().unwrap().0, "Old_Queue"); + assert_eq!(printer_options(None, "").len(), 1); + // The dialog asks the engine, and the list never reaches file.print's params. + let (mut app, ctx) = app(); + let id = crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap()["dialog"].as_u64().unwrap(); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert!(f.get("__systemPrinters").is_some_and(Value::is_array)); + assert!(params(f).get("__systemPrinters").is_none()); + assert!(params(f).get("__printers").is_none()); +} + +/// An output path or a preview typed and confirmed in one frame doesn't take the driver's area. +#[test] +fn the_printable_area_goes_only_with_a_print_to_the_printer() { + let area = json!([0.0, 0.0, 842.29, 1191.14]); + let mut f = Map::new(); + f.insert("printable".into(), area.clone()); + assert_eq!(print_params(&f)["printable"], area); + f.insert("output".into(), json!("/tmp/out.pdf")); + assert!(print_params(&f).get("printable").is_none()); + f.insert("output".into(), json!("")); + f.insert("dryRun".into(), json!(true)); + assert!(print_params(&f).get("printable").is_none()); +} + +/// #7410: File › Print opens with the settings of the last print, also those remembered from +/// an earlier session (the preferences), before anything was printed in this one. +#[test] +fn print_dialog_opens_with_the_settings_remembered_from_an_earlier_session() { + let (mut app, _) = app(); + app.session.prefs.edit(|p| { + p.dialogs.insert( + photocraft_engine::print_cmds::REMEMBERED.into(), + json!({"paper": "a5", "scale": 50, "orientation": "landscape", "intent": "perceptual"}), + ); + }); + let id = open_print(&mut app); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!((&f["paper"], &f["scale"], &f["orientation"], &f["intent"]), (&json!("a5"), &json!(50), &json!("landscape"), &json!("perceptual"))); + assert_eq!(f["copies"], 1, "what wasn't remembered keeps its default"); +} + +/// #5328: Save as PDF has Browse…, which fills the field from a Save dialog (suggesting the +/// document's name as a PDF) rather than needing a typed path. +#[test] +fn save_as_pdf_browse_fills_the_output_from_a_save_dialog() { + use crate::file_dialog::{FileDialogAnswer, FileDialogRequest}; + use egui_kittest::{Harness, kittest::Queryable}; + let out = std::env::temp_dir().join(format!("pc-printui-browse-{}", std::process::id())).to_string_lossy().into_owned(); + let (show, asked) = crate::file_dialog::fake(vec![Some(FileDialogAnswer::SaveTo(out.clone()))]); + let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { file_dialog: Some(show), ..Default::default() }) + }); + h.state_mut().run("file.new", json!({"width": 120, "height": 80, "name": "poster"})).unwrap(); + let id = open_print(h.state_mut()); + h.run_steps(3); + h.get_by_label("Browse…").click(); + h.run_steps(4); + assert!(matches!(asked.borrow().as_slice(), [FileDialogRequest::Save { suggested }] if suggested.ends_with("poster.pdf")), "{:?}", asked.borrow()); + // A name chosen without an extension gets the suggested one. + assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields["output"], json!(format!("{out}.pdf"))); +} + +#[test] +fn print_dialog_does_not_inherit_scripted_send_override() { + for send in [false, true] { + let (mut app, ctx) = app(); + let out = std::env::temp_dir().join(format!("pc-printui-state-{}-{send}.pdf", std::process::id())).to_string_lossy().into_owned(); + app.session.execute("file.print", json!({"output": out, "send": send, "dryRun": true})).unwrap(); + assert!(app.session.file_menu.last_print.as_ref().unwrap().get("send").is_none()); + let r = crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap(); + let id = r["dialog"].as_u64().unwrap(); + assert!(app.ui.dialog_mut(id).unwrap().fields.get("send").is_none()); + std::fs::remove_file(out).unwrap(); + } +} + +/// The Orientation buttons show the driver paper's shape: landscape when it is wider than tall. +#[test] +fn orientation_follows_the_driver_paper() { + let with = |paper: Value| { + let mut f = Map::new(); + f.insert("paper".into(), paper); + f + }; + assert!(driver_paper_is_wide(&with(json!([1191.14, 842.29])))); + assert!(!driver_paper_is_wide(&with(json!([842.29, 1191.14])))); + assert!(!driver_paper_is_wide(&with(json!("a3"))), "a named paper is not a driver page"); + assert!(!driver_paper_is_wide(&Map::new())); +} + +/// Turning a printer whose driver can't be asked keeps its settings and says why on the dialog. +#[test] +fn turning_without_a_driver_keeps_the_settings_and_shows_the_error() { + // Valid driver settings (a minimal DEVMODEW: 220 bytes, no private part), so the command + // gets past reading them and fails where it asks the (missing) printer for its page. + let mut dm = vec![0u8; 220]; + dm[68..70].copy_from_slice(&220u16.to_le_bytes()); + let hex: String = dm.iter().map(|b| format!("{b:02x}")).collect(); + assert!(craft_print::rgb::DevMode::from_hex(&hex).is_ok()); + let (mut app, _) = app(); + let mut f = Map::new(); + f.insert("printer".into(), json!("photocraft-no-such-printer")); + f.insert("printerSettings".into(), json!(hex)); + f.insert("paper".into(), json!([595.28, 841.89])); + turn_driver(&mut app, &mut f, true); + assert_eq!(f.get("printerSettings"), Some(&json!(hex))); + assert_eq!(f.get("paper"), Some(&json!([595.28, 841.89]))); + let error = f.get("__pageError").and_then(Value::as_str).unwrap_or_default(); + // Reading bad settings fails with "printer settings are too short / damaged"; this must not. + assert!(!error.is_empty() && !error.contains("printer settings are"), "failed at the printer, not at reading the settings: {error}"); +} + +/// A turn takes the settings and the paper from the same answer, never one without the other. +#[test] +fn a_turn_takes_settings_and_paper_together() { + let fields = || { + let mut f = Map::new(); + f.insert("printerSettings".into(), json!("old")); + f.insert("paper".into(), json!([595.28, 841.89])); + f.insert("__pageError".into(), json!("earlier")); + f + }; + let mut f = fields(); + take_turned_page(&mut f, &json!({"printerSettings": "new", "paper": [841.89, 595.28]})); + assert_eq!((f.get("printerSettings"), f.get("paper")), (Some(&json!("new")), Some(&json!([841.89, 595.28])))); + assert_eq!(f.get("orientation"), Some(&json!("portrait")), "the driver paper is already turned"); + assert!(f.get("__pageError").is_none()); + for partial in [json!({"printerSettings": "new"}), json!({"paper": [841.89, 595.28]}), json!({"printerSettings": "new", "paper": [841.89]})] { + let mut f = fields(); + take_turned_page(&mut f, &partial); + assert_eq!((f.get("printerSettings"), f.get("paper")), (Some(&json!("old")), Some(&json!([595.28, 841.89]))), "{partial}"); + assert!(f.get("__pageError").is_some(), "{partial}"); + } +} From 86cb5ee5ca8cdce660a8eb8afe3233bc3f750f3d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:05 +0000 Subject: [PATCH 082/259] refactor(ui-egui): move analysis_ui.rs tests to analysis_ui/tests.rs --- crates/ui-egui/src/analysis_ui.rs | 301 +----------------------- crates/ui-egui/src/analysis_ui/tests.rs | 298 +++++++++++++++++++++++ 2 files changed, 299 insertions(+), 300 deletions(-) create mode 100644 crates/ui-egui/src/analysis_ui/tests.rs diff --git a/crates/ui-egui/src/analysis_ui.rs b/crates/ui-egui/src/analysis_ui.rs index f3c1594b7b..6cad2b2158 100644 --- a/crates/ui-egui/src/analysis_ui.rs +++ b/crates/ui-egui/src/analysis_ui.rs @@ -987,303 +987,4 @@ fn dialog(app: &mut PhotocraftApp, ctx: &egui::Context) { } #[cfg(test)] -pub(crate) mod tests { - use super::*; - - fn app() -> (PhotocraftApp, egui::Context) { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); - (app, egui::Context::default()) - } - - /// Draw `f` for a few frames (fonts load on the first). - pub(crate) fn render(app: &mut PhotocraftApp, ctx: &egui::Context, f: fn(&mut PhotocraftApp, &egui::Context)) { - PhotocraftApp::setup_context(ctx, Default::default()); - for _ in 0..3 { - let mut o = ctx.run_ui(Default::default(), |ui| f(app, ui.ctx())); - o.textures_delta.clear(); - } - } - - fn down(app: &mut PhotocraftApp, x: f64, y: f64, m: egui::Modifiers) { - crate::canvas::tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, m); - } - fn mv(app: &mut PhotocraftApp, x: f64, y: f64, m: egui::Modifiers) { - crate::canvas::tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, m); - } - fn up(app: &mut PhotocraftApp, x: f64, y: f64) { - crate::canvas::tool_event(app, ToolEvent::Up { x, y }, egui::Modifiers::NONE); - } - - fn ruler(app: &PhotocraftApp) -> Option { - app.session.active().unwrap().doc.measurement.ruler - } - - #[test] - fn menu_selects_tools_and_toggles_panels() { - let (mut app, ctx) = app(); - crate::menus::invoke(&mut app, &ctx, "image.analysis.rulerTool", json!({})).unwrap(); - assert_eq!(app.ui.tool, Tool::Ruler); - assert_eq!(checked(&app, "image.analysis.rulerTool"), Some(true)); - crate::menus::invoke(&mut app, &ctx, "image.analysis.countTool", json!({})).unwrap(); - assert_eq!(app.ui.tool, Tool::Count); - crate::menus::invoke(&mut app, &ctx, "window.panel.measurementLog", json!({})).unwrap(); - assert!(app.ui.analysis.measurement_log); - crate::menus::invoke(&mut app, &ctx, "window.panel.notes", json!({"show": true})).unwrap(); - assert!(app.ui.analysis.notes); - let items = crate::menus::menu_items(&app); - for id in [ - "window.panel.measurementLog", - "window.panel.notes", - "image.analysis.setMeasurementScale", - "image.analysis.placeScaleMarker", - "file.import.notes", - "view.proofSetup.workingCyanPlate", - ] { - assert!(items.iter().any(|i| i.id == id && i.enabled), "{id} live"); - } - } - - #[test] - fn arbitrary_rotation_starts_at_the_ruler_angle() { - let (mut app, ctx) = app(); - let open = |app: &mut PhotocraftApp| { - let r = crate::menus::invoke(app, &ctx, "image.rotation.arbitrary", json!({})).unwrap(); - let f = &app.ui.dialog_mut(r["dialog"].as_u64().unwrap()).unwrap().fields; - (f["angle"].as_f64().unwrap(), f["direction"].clone()) - }; - assert_eq!(open(&mut app), (0.0, json!("cw"))); - // A line falling to the right straightens counter-clockwise, a near-vertical one to the y axis. - for (end, dir) in [([150, 60], "ccw"), ([150, 40], "cw"), ([60, -50], "ccw")] { - app.run("image.analysis.rulerTool", json!({"start": [50, 50], "end": end})).unwrap(); - let (a, d) = open(&mut app); - assert!((a - 5.7106).abs() < 1e-3 && d == json!(dir), "{end:?}: {a} {d}"); - } - } - - #[test] - fn ruler_drag_protractor_and_clear() { - let (mut app, _) = app(); - app.ui.tool = Tool::Ruler; - let none = egui::Modifiers::NONE; - down(&mut app, 10.0, 10.0, none); - mv(&mut app, 60.0, 10.0, none); - up(&mut app, 60.0, 10.0); - assert_eq!(ruler(&app).map(|r| r.end), Some([60.0, 10.0])); - // Drag the end point with ⇧: constrained to 45°. - down(&mut app, 60.0, 10.0, none); - mv(&mut app, 12.0, 52.0, egui::Modifiers::SHIFT); - up(&mut app, 12.0, 52.0); - let r = ruler(&app).unwrap(); - assert!((r.end[0] - 10.0).abs() < 1e-6, "vertical: {r:?}"); - // ⌥-drag from the start point: protractor arm. - down(&mut app, 10.0, 10.0, egui::Modifiers::ALT); - mv(&mut app, 60.0, 10.0, none); - up(&mut app, 60.0, 10.0); - let info = photocraft_engine::analysis_cmds::ruler_info(&ruler(&app).unwrap(), &Default::default()); - assert!((info["angle"].as_f64().unwrap() - 90.0).abs() < 1e-6, "{info}"); - // A click without a drag far away starts a new line and clears it. - down(&mut app, 150.0, 80.0, none); - up(&mut app, 150.0, 80.0); - assert!(ruler(&app).is_none()); - assert_eq!(app.session.active().unwrap().history.past_len(), 0, "the ruler adds no history"); - } - - #[test] - fn count_tool_add_move_remove() { - let (mut app, _) = app(); - app.ui.tool = Tool::Count; - down(&mut app, 20.0, 20.0, egui::Modifiers::NONE); - up(&mut app, 20.0, 20.0); - down(&mut app, 50.0, 50.0, egui::Modifiers::NONE); - up(&mut app, 50.0, 50.0); - let pts = |app: &PhotocraftApp| app.session.active().unwrap().doc.measurement.count_groups[0].points.clone(); - assert_eq!(pts(&app).len(), 2); - // Drag marker 1. - down(&mut app, 20.5, 20.5, egui::Modifiers::NONE); - up(&mut app, 30.0, 25.0); - assert_eq!(pts(&app)[0], [30.0, 25.0]); - // ⌥-click removes. - down(&mut app, 50.0, 50.0, egui::Modifiers::ALT); - up(&mut app, 50.0, 50.0); - assert_eq!(pts(&app).len(), 1); - } - - #[test] - fn note_tool_and_panel_state() { - let (mut app, ctx) = app(); - app.ui.tool = Tool::Note; - app.ui.analysis.note_author = "QA".into(); - down(&mut app, 30.0, 40.0, egui::Modifiers::NONE); - up(&mut app, 30.0, 40.0); - let n = app.session.active().unwrap().doc.notes.clone(); - assert_eq!(n.len(), 1); - assert_eq!(n[0].author, "QA"); - assert!(app.ui.analysis.notes && app.ui.analysis.note_selected == Some(0)); - // Drag the icon. - down(&mut app, 32.0, 42.0, egui::Modifiers::NONE); - up(&mut app, 62.0, 52.0); - assert_eq!(app.session.active().unwrap().doc.notes[0].position, [60.0, 50.0]); - // The panel renders without panicking. - render(&mut app, &ctx, windows); - } - - /// Clicking a note with the Note tool shows its author and colour in the options bar (#7940), - /// so a note from a PSD reads as itself, not as the next note's defaults. - #[test] - fn clicking_a_note_shows_its_author_and_color() { - let (mut app, _ctx) = app(); - app.run("notes.add", json!({"x": 20, "y": 20, "author": "Ann", "color": [1.0, 0.5, 0.75]})).unwrap(); - app.run("notes.add", json!({"x": 120, "y": 80, "author": "Bob", "color": [0.25, 0.5, 1.0]})).unwrap(); - app.ui.tool = Tool::Note; - app.ui.analysis.note_author = "Me".into(); - app.ui.analysis.note_color = [1.0, 1.0, 0.51]; - down(&mut app, 22.0, 22.0, egui::Modifiers::NONE); - up(&mut app, 22.0, 22.0); - assert_eq!(app.ui.analysis.note_selected, Some(0)); - assert_eq!((app.ui.analysis.note_author.as_str(), app.ui.analysis.note_color), ("Ann", [1.0, 0.5, 0.75])); - down(&mut app, 122.0, 82.0, egui::Modifiers::NONE); - up(&mut app, 122.0, 82.0); - assert_eq!((app.ui.analysis.note_author.as_str(), app.ui.analysis.note_color), ("Bob", [0.25, 0.5, 1.0])); - // A click off the notes adds one with what the bar now shows, and leaves the notes as they were. - down(&mut app, 170.0, 40.0, egui::Modifiers::NONE); - up(&mut app, 170.0, 40.0); - let notes = app.session.active().unwrap().doc.notes.clone(); - assert_eq!(notes.iter().map(|n| n.author.as_str()).collect::>(), ["Ann", "Bob", "Bob"]); - } - - #[test] - fn dialogs_open_and_run_their_commands() { - let (mut app, ctx) = app(); - let r = crate::menus::invoke(&mut app, &ctx, "image.analysis.setMeasurementScale", json!({})).unwrap(); - assert_eq!(r["dialog"], "scale"); - let (kind, mut f) = app.ui.analysis.dialog.clone().unwrap(); - f.insert("preset".into(), json!("custom")); - f.insert("pixelLength".into(), json!(40)); - f.insert("logicalLength".into(), json!(1)); - f.insert("units".into(), json!("cm")); - let (id, p) = dialog_command(&kind, &f).unwrap(); - app.run(id, p).unwrap(); - assert_eq!(app.session.active().unwrap().doc.measurement.scale.units, "cm"); - crate::menus::invoke(&mut app, &ctx, "image.analysis.placeScaleMarker", json!({})).unwrap(); - let (kind, f) = app.ui.analysis.dialog.clone().unwrap(); - assert_eq!(f["length"], 1.0); - let (id, p) = dialog_command(&kind, &f).unwrap(); - app.run(id, p).unwrap(); - crate::menus::invoke(&mut app, &ctx, "image.analysis.selectDataPoints", json!({})).unwrap(); - let (kind, mut f) = app.ui.analysis.dialog.clone().unwrap(); - f.insert("ruler".into(), json!(["label", "length"])); - let (id, p) = dialog_command(&kind, &f).unwrap(); - app.run(id, p).unwrap(); - assert_eq!(app.session.analysis.data_points.ruler, ["label", "length"]); - // Record from the Count tool records counts and opens the log. - app.ui.tool = Tool::Count; - crate::menus::invoke(&mut app, &ctx, "image.analysis.recordMeasurements", json!({})).unwrap(); - assert!(app.ui.analysis.measurement_log); - assert_eq!(app.session.analysis.log.last().unwrap().values["source"], "Count Tool"); - render(&mut app, &ctx, windows); - } - - #[test] - fn color_sampler_tool_places_moves_and_removes_points() { - let (mut app, ctx) = app(); - app.ui.tool = Tool::ColorSampler; - let pts = |app: &PhotocraftApp| app.session.active().unwrap().color_samplers.clone(); - down(&mut app, 20.0, 20.0, egui::Modifiers::NONE); - up(&mut app, 20.0, 20.0); - down(&mut app, 60.0, 40.0, egui::Modifiers::NONE); - up(&mut app, 60.0, 40.0); - assert_eq!(pts(&app), vec![[20.0, 20.0], [60.0, 40.0]]); - // Drag the first point to a new pixel (committed on release). - down(&mut app, 20.0, 20.0, egui::Modifiers::NONE); - mv(&mut app, 30.0, 25.0, egui::Modifiers::NONE); - up(&mut app, 30.0, 25.0); - assert_eq!(pts(&app)[0], [30.0, 25.0]); - // A click on a point, with no drag, leaves it where it is. - down(&mut app, 30.0, 25.0, egui::Modifiers::NONE); - up(&mut app, 30.0, 25.0); - assert_eq!(pts(&app)[0], [30.0, 25.0]); - // ⌥-click removes that one point. - down(&mut app, 60.0, 40.0, egui::Modifiers::ALT); - up(&mut app, 60.0, 40.0); - assert_eq!(pts(&app).len(), 1); - // Dragging a point off the canvas removes it. - down(&mut app, 30.0, 25.0, egui::Modifiers::NONE); - mv(&mut app, -50.0, 25.0, egui::Modifiers::NONE); - up(&mut app, -50.0, 25.0); - assert!(pts(&app).is_empty()); - assert_eq!(app.session.active().unwrap().history.past_len(), 0, "sampling adds no history"); - // The overlay and the options bar render without panicking. - down(&mut app, 10.0, 10.0, egui::Modifiers::NONE); - up(&mut app, 10.0, 10.0); - render(&mut app, &ctx, windows); - let xf = ViewXform { - rect: egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(200.0, 100.0)), - zoom: 1.0, - center: [100.0, 50.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(); - } - - #[test] - fn color_sampler_readout_and_crop_removal_report() { - let (mut app, _) = app(); - app.ui.tool = Tool::ColorSampler; - down(&mut app, 5.0, 5.0, egui::Modifiers::NONE); - up(&mut app, 5.0, 5.0); - down(&mut app, 150.0, 90.0, egui::Modifiers::NONE); - up(&mut app, 150.0, 90.0); - // The list reports both, numbered, with their position and RGB/CMYK readout. - let l = app.run("view.colorSamplers.list", json!({})).unwrap(); - assert_eq!(l["samplers"].as_array().unwrap().len(), 2); - assert_eq!(l["samplers"][0]["number"], 1); - assert_eq!(l["samplers"][1]["position"], json!([150.0, 90.0])); - assert!(l["samplers"][0]["rgb"].as_array().is_some_and(|a| a.len() == 3)); - // Cropping to the top-left drops the outside point and reports how many went. - app.run("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); - assert_eq!(app.session.active().unwrap().color_samplers, vec![[5.0, 5.0]]); - assert!(app.ui.status.contains("removed"), "{}", app.ui.status); - assert!(!app.ui.status_error); - } - - #[test] - fn color_sampler_is_per_document_and_inert_without_one() { - let (mut app, _) = app(); - app.ui.tool = Tool::ColorSampler; - down(&mut app, 10.0, 10.0, egui::Modifiers::NONE); - up(&mut app, 10.0, 10.0); - // A second document starts empty; the first keeps its own point. - app.run("file.new", json!({"width": 50, "height": 50})).unwrap(); - assert!(app.session.active().unwrap().color_samplers.is_empty()); - down(&mut app, 20.0, 20.0, egui::Modifiers::NONE); - up(&mut app, 20.0, 20.0); - assert_eq!(app.session.active().unwrap().color_samplers, vec![[20.0, 20.0]]); - app.run("document.activate", json!({"document": 0})).unwrap(); - assert_eq!(app.session.active().unwrap().color_samplers, vec![[10.0, 10.0]]); - // With no document the tool says so (no dialog, no panic) and the commands error. - let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - empty.ui.tool = Tool::ColorSampler; - down(&mut empty, 5.0, 5.0, egui::Modifiers::NONE); - assert_eq!(empty.ui.status, "No document open"); - assert!(!empty.ui.status_error); - assert!(empty.run("view.colorSamplers.add", json!({"x": 1, "y": 1})).is_err()); - assert!(empty.run("view.colorSamplers.list", json!({})).is_err()); - } - - #[test] - fn count_size_fields_send_whole_numbers_the_engine_applies() { - let p = count_size_params(7.6, 20.0); - assert_eq!(p, json!({"markerSize": 8, "labelSize": 20})); - assert!(p["markerSize"].is_u64() && p["labelSize"].is_u64()); - assert_eq!(count_size_params(f32::NAN, 500.0), json!({"markerSize": 1, "labelSize": 72})); - let (mut app, _ctx) = app(); - app.run("count.add", json!({"x": 10, "y": 10})).unwrap(); - app.run("count.setGroup", count_size_params(8.0, 20.0)).unwrap(); - let g = &app.session.active().unwrap().doc.measurement.count_groups[0]; - assert_eq!((g.marker_size, g.label_size), (8, 20)); - } -} +pub(crate) mod tests; diff --git a/crates/ui-egui/src/analysis_ui/tests.rs b/crates/ui-egui/src/analysis_ui/tests.rs new file mode 100644 index 0000000000..3ed65a3ffd --- /dev/null +++ b/crates/ui-egui/src/analysis_ui/tests.rs @@ -0,0 +1,298 @@ +use super::*; + +fn app() -> (PhotocraftApp, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + (app, egui::Context::default()) +} + +/// Draw `f` for a few frames (fonts load on the first). +pub(crate) fn render(app: &mut PhotocraftApp, ctx: &egui::Context, f: fn(&mut PhotocraftApp, &egui::Context)) { + PhotocraftApp::setup_context(ctx, Default::default()); + for _ in 0..3 { + let mut o = ctx.run_ui(Default::default(), |ui| f(app, ui.ctx())); + o.textures_delta.clear(); + } +} + +fn down(app: &mut PhotocraftApp, x: f64, y: f64, m: egui::Modifiers) { + crate::canvas::tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, m); +} +fn mv(app: &mut PhotocraftApp, x: f64, y: f64, m: egui::Modifiers) { + crate::canvas::tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, m); +} +fn up(app: &mut PhotocraftApp, x: f64, y: f64) { + crate::canvas::tool_event(app, ToolEvent::Up { x, y }, egui::Modifiers::NONE); +} + +fn ruler(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().doc.measurement.ruler +} + +#[test] +fn menu_selects_tools_and_toggles_panels() { + let (mut app, ctx) = app(); + crate::menus::invoke(&mut app, &ctx, "image.analysis.rulerTool", json!({})).unwrap(); + assert_eq!(app.ui.tool, Tool::Ruler); + assert_eq!(checked(&app, "image.analysis.rulerTool"), Some(true)); + crate::menus::invoke(&mut app, &ctx, "image.analysis.countTool", json!({})).unwrap(); + assert_eq!(app.ui.tool, Tool::Count); + crate::menus::invoke(&mut app, &ctx, "window.panel.measurementLog", json!({})).unwrap(); + assert!(app.ui.analysis.measurement_log); + crate::menus::invoke(&mut app, &ctx, "window.panel.notes", json!({"show": true})).unwrap(); + assert!(app.ui.analysis.notes); + let items = crate::menus::menu_items(&app); + for id in [ + "window.panel.measurementLog", + "window.panel.notes", + "image.analysis.setMeasurementScale", + "image.analysis.placeScaleMarker", + "file.import.notes", + "view.proofSetup.workingCyanPlate", + ] { + assert!(items.iter().any(|i| i.id == id && i.enabled), "{id} live"); + } +} + +#[test] +fn arbitrary_rotation_starts_at_the_ruler_angle() { + let (mut app, ctx) = app(); + let open = |app: &mut PhotocraftApp| { + let r = crate::menus::invoke(app, &ctx, "image.rotation.arbitrary", json!({})).unwrap(); + let f = &app.ui.dialog_mut(r["dialog"].as_u64().unwrap()).unwrap().fields; + (f["angle"].as_f64().unwrap(), f["direction"].clone()) + }; + assert_eq!(open(&mut app), (0.0, json!("cw"))); + // A line falling to the right straightens counter-clockwise, a near-vertical one to the y axis. + for (end, dir) in [([150, 60], "ccw"), ([150, 40], "cw"), ([60, -50], "ccw")] { + app.run("image.analysis.rulerTool", json!({"start": [50, 50], "end": end})).unwrap(); + let (a, d) = open(&mut app); + assert!((a - 5.7106).abs() < 1e-3 && d == json!(dir), "{end:?}: {a} {d}"); + } +} + +#[test] +fn ruler_drag_protractor_and_clear() { + let (mut app, _) = app(); + app.ui.tool = Tool::Ruler; + let none = egui::Modifiers::NONE; + down(&mut app, 10.0, 10.0, none); + mv(&mut app, 60.0, 10.0, none); + up(&mut app, 60.0, 10.0); + assert_eq!(ruler(&app).map(|r| r.end), Some([60.0, 10.0])); + // Drag the end point with ⇧: constrained to 45°. + down(&mut app, 60.0, 10.0, none); + mv(&mut app, 12.0, 52.0, egui::Modifiers::SHIFT); + up(&mut app, 12.0, 52.0); + let r = ruler(&app).unwrap(); + assert!((r.end[0] - 10.0).abs() < 1e-6, "vertical: {r:?}"); + // ⌥-drag from the start point: protractor arm. + down(&mut app, 10.0, 10.0, egui::Modifiers::ALT); + mv(&mut app, 60.0, 10.0, none); + up(&mut app, 60.0, 10.0); + let info = photocraft_engine::analysis_cmds::ruler_info(&ruler(&app).unwrap(), &Default::default()); + assert!((info["angle"].as_f64().unwrap() - 90.0).abs() < 1e-6, "{info}"); + // A click without a drag far away starts a new line and clears it. + down(&mut app, 150.0, 80.0, none); + up(&mut app, 150.0, 80.0); + assert!(ruler(&app).is_none()); + assert_eq!(app.session.active().unwrap().history.past_len(), 0, "the ruler adds no history"); +} + +#[test] +fn count_tool_add_move_remove() { + let (mut app, _) = app(); + app.ui.tool = Tool::Count; + down(&mut app, 20.0, 20.0, egui::Modifiers::NONE); + up(&mut app, 20.0, 20.0); + down(&mut app, 50.0, 50.0, egui::Modifiers::NONE); + up(&mut app, 50.0, 50.0); + let pts = |app: &PhotocraftApp| app.session.active().unwrap().doc.measurement.count_groups[0].points.clone(); + assert_eq!(pts(&app).len(), 2); + // Drag marker 1. + down(&mut app, 20.5, 20.5, egui::Modifiers::NONE); + up(&mut app, 30.0, 25.0); + assert_eq!(pts(&app)[0], [30.0, 25.0]); + // ⌥-click removes. + down(&mut app, 50.0, 50.0, egui::Modifiers::ALT); + up(&mut app, 50.0, 50.0); + assert_eq!(pts(&app).len(), 1); +} + +#[test] +fn note_tool_and_panel_state() { + let (mut app, ctx) = app(); + app.ui.tool = Tool::Note; + app.ui.analysis.note_author = "QA".into(); + down(&mut app, 30.0, 40.0, egui::Modifiers::NONE); + up(&mut app, 30.0, 40.0); + let n = app.session.active().unwrap().doc.notes.clone(); + assert_eq!(n.len(), 1); + assert_eq!(n[0].author, "QA"); + assert!(app.ui.analysis.notes && app.ui.analysis.note_selected == Some(0)); + // Drag the icon. + down(&mut app, 32.0, 42.0, egui::Modifiers::NONE); + up(&mut app, 62.0, 52.0); + assert_eq!(app.session.active().unwrap().doc.notes[0].position, [60.0, 50.0]); + // The panel renders without panicking. + render(&mut app, &ctx, windows); +} + +/// Clicking a note with the Note tool shows its author and colour in the options bar (#7940), +/// so a note from a PSD reads as itself, not as the next note's defaults. +#[test] +fn clicking_a_note_shows_its_author_and_color() { + let (mut app, _ctx) = app(); + app.run("notes.add", json!({"x": 20, "y": 20, "author": "Ann", "color": [1.0, 0.5, 0.75]})).unwrap(); + app.run("notes.add", json!({"x": 120, "y": 80, "author": "Bob", "color": [0.25, 0.5, 1.0]})).unwrap(); + app.ui.tool = Tool::Note; + app.ui.analysis.note_author = "Me".into(); + app.ui.analysis.note_color = [1.0, 1.0, 0.51]; + down(&mut app, 22.0, 22.0, egui::Modifiers::NONE); + up(&mut app, 22.0, 22.0); + assert_eq!(app.ui.analysis.note_selected, Some(0)); + assert_eq!((app.ui.analysis.note_author.as_str(), app.ui.analysis.note_color), ("Ann", [1.0, 0.5, 0.75])); + down(&mut app, 122.0, 82.0, egui::Modifiers::NONE); + up(&mut app, 122.0, 82.0); + assert_eq!((app.ui.analysis.note_author.as_str(), app.ui.analysis.note_color), ("Bob", [0.25, 0.5, 1.0])); + // A click off the notes adds one with what the bar now shows, and leaves the notes as they were. + down(&mut app, 170.0, 40.0, egui::Modifiers::NONE); + up(&mut app, 170.0, 40.0); + let notes = app.session.active().unwrap().doc.notes.clone(); + assert_eq!(notes.iter().map(|n| n.author.as_str()).collect::>(), ["Ann", "Bob", "Bob"]); +} + +#[test] +fn dialogs_open_and_run_their_commands() { + let (mut app, ctx) = app(); + let r = crate::menus::invoke(&mut app, &ctx, "image.analysis.setMeasurementScale", json!({})).unwrap(); + assert_eq!(r["dialog"], "scale"); + let (kind, mut f) = app.ui.analysis.dialog.clone().unwrap(); + f.insert("preset".into(), json!("custom")); + f.insert("pixelLength".into(), json!(40)); + f.insert("logicalLength".into(), json!(1)); + f.insert("units".into(), json!("cm")); + let (id, p) = dialog_command(&kind, &f).unwrap(); + app.run(id, p).unwrap(); + assert_eq!(app.session.active().unwrap().doc.measurement.scale.units, "cm"); + crate::menus::invoke(&mut app, &ctx, "image.analysis.placeScaleMarker", json!({})).unwrap(); + let (kind, f) = app.ui.analysis.dialog.clone().unwrap(); + assert_eq!(f["length"], 1.0); + let (id, p) = dialog_command(&kind, &f).unwrap(); + app.run(id, p).unwrap(); + crate::menus::invoke(&mut app, &ctx, "image.analysis.selectDataPoints", json!({})).unwrap(); + let (kind, mut f) = app.ui.analysis.dialog.clone().unwrap(); + f.insert("ruler".into(), json!(["label", "length"])); + let (id, p) = dialog_command(&kind, &f).unwrap(); + app.run(id, p).unwrap(); + assert_eq!(app.session.analysis.data_points.ruler, ["label", "length"]); + // Record from the Count tool records counts and opens the log. + app.ui.tool = Tool::Count; + crate::menus::invoke(&mut app, &ctx, "image.analysis.recordMeasurements", json!({})).unwrap(); + assert!(app.ui.analysis.measurement_log); + assert_eq!(app.session.analysis.log.last().unwrap().values["source"], "Count Tool"); + render(&mut app, &ctx, windows); +} + +#[test] +fn color_sampler_tool_places_moves_and_removes_points() { + let (mut app, ctx) = app(); + app.ui.tool = Tool::ColorSampler; + let pts = |app: &PhotocraftApp| app.session.active().unwrap().color_samplers.clone(); + down(&mut app, 20.0, 20.0, egui::Modifiers::NONE); + up(&mut app, 20.0, 20.0); + down(&mut app, 60.0, 40.0, egui::Modifiers::NONE); + up(&mut app, 60.0, 40.0); + assert_eq!(pts(&app), vec![[20.0, 20.0], [60.0, 40.0]]); + // Drag the first point to a new pixel (committed on release). + down(&mut app, 20.0, 20.0, egui::Modifiers::NONE); + mv(&mut app, 30.0, 25.0, egui::Modifiers::NONE); + up(&mut app, 30.0, 25.0); + assert_eq!(pts(&app)[0], [30.0, 25.0]); + // A click on a point, with no drag, leaves it where it is. + down(&mut app, 30.0, 25.0, egui::Modifiers::NONE); + up(&mut app, 30.0, 25.0); + assert_eq!(pts(&app)[0], [30.0, 25.0]); + // ⌥-click removes that one point. + down(&mut app, 60.0, 40.0, egui::Modifiers::ALT); + up(&mut app, 60.0, 40.0); + assert_eq!(pts(&app).len(), 1); + // Dragging a point off the canvas removes it. + down(&mut app, 30.0, 25.0, egui::Modifiers::NONE); + mv(&mut app, -50.0, 25.0, egui::Modifiers::NONE); + up(&mut app, -50.0, 25.0); + assert!(pts(&app).is_empty()); + assert_eq!(app.session.active().unwrap().history.past_len(), 0, "sampling adds no history"); + // The overlay and the options bar render without panicking. + down(&mut app, 10.0, 10.0, egui::Modifiers::NONE); + up(&mut app, 10.0, 10.0); + render(&mut app, &ctx, windows); + let xf = ViewXform { + rect: egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(200.0, 100.0)), + zoom: 1.0, + center: [100.0, 50.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(); +} + +#[test] +fn color_sampler_readout_and_crop_removal_report() { + let (mut app, _) = app(); + app.ui.tool = Tool::ColorSampler; + down(&mut app, 5.0, 5.0, egui::Modifiers::NONE); + up(&mut app, 5.0, 5.0); + down(&mut app, 150.0, 90.0, egui::Modifiers::NONE); + up(&mut app, 150.0, 90.0); + // The list reports both, numbered, with their position and RGB/CMYK readout. + let l = app.run("view.colorSamplers.list", json!({})).unwrap(); + assert_eq!(l["samplers"].as_array().unwrap().len(), 2); + assert_eq!(l["samplers"][0]["number"], 1); + assert_eq!(l["samplers"][1]["position"], json!([150.0, 90.0])); + assert!(l["samplers"][0]["rgb"].as_array().is_some_and(|a| a.len() == 3)); + // Cropping to the top-left drops the outside point and reports how many went. + app.run("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + assert_eq!(app.session.active().unwrap().color_samplers, vec![[5.0, 5.0]]); + assert!(app.ui.status.contains("removed"), "{}", app.ui.status); + assert!(!app.ui.status_error); +} + +#[test] +fn color_sampler_is_per_document_and_inert_without_one() { + let (mut app, _) = app(); + app.ui.tool = Tool::ColorSampler; + down(&mut app, 10.0, 10.0, egui::Modifiers::NONE); + up(&mut app, 10.0, 10.0); + // A second document starts empty; the first keeps its own point. + app.run("file.new", json!({"width": 50, "height": 50})).unwrap(); + assert!(app.session.active().unwrap().color_samplers.is_empty()); + down(&mut app, 20.0, 20.0, egui::Modifiers::NONE); + up(&mut app, 20.0, 20.0); + assert_eq!(app.session.active().unwrap().color_samplers, vec![[20.0, 20.0]]); + app.run("document.activate", json!({"document": 0})).unwrap(); + assert_eq!(app.session.active().unwrap().color_samplers, vec![[10.0, 10.0]]); + // With no document the tool says so (no dialog, no panic) and the commands error. + let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + empty.ui.tool = Tool::ColorSampler; + down(&mut empty, 5.0, 5.0, egui::Modifiers::NONE); + assert_eq!(empty.ui.status, "No document open"); + assert!(!empty.ui.status_error); + assert!(empty.run("view.colorSamplers.add", json!({"x": 1, "y": 1})).is_err()); + assert!(empty.run("view.colorSamplers.list", json!({})).is_err()); +} + +#[test] +fn count_size_fields_send_whole_numbers_the_engine_applies() { + let p = count_size_params(7.6, 20.0); + assert_eq!(p, json!({"markerSize": 8, "labelSize": 20})); + assert!(p["markerSize"].is_u64() && p["labelSize"].is_u64()); + assert_eq!(count_size_params(f32::NAN, 500.0), json!({"markerSize": 1, "labelSize": 72})); + let (mut app, _ctx) = app(); + app.run("count.add", json!({"x": 10, "y": 10})).unwrap(); + app.run("count.setGroup", count_size_params(8.0, 20.0)).unwrap(); + let g = &app.session.active().unwrap().doc.measurement.count_groups[0]; + assert_eq!((g.marker_size, g.label_size), (8, 20)); +} From b03238b22e349cc0a21a978de7e2137b6d593d34 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:05 +0000 Subject: [PATCH 083/259] refactor(ui-egui): move cjk_fonts.rs tests to cjk_fonts/tests.rs --- crates/ui-egui/src/cjk_fonts.rs | 1929 +------------------------ crates/ui-egui/src/cjk_fonts/tests.rs | 1917 ++++++++++++++++++++++++ 2 files changed, 1918 insertions(+), 1928 deletions(-) create mode 100644 crates/ui-egui/src/cjk_fonts/tests.rs diff --git a/crates/ui-egui/src/cjk_fonts.rs b/crates/ui-egui/src/cjk_fonts.rs index 7dfefbb640..674ae6948e 100644 --- a/crates/ui-egui/src/cjk_fonts.rs +++ b/crates/ui-egui/src/cjk_fonts.rs @@ -1014,1931 +1014,4 @@ pub(crate) fn set_craft_font_scale(ctx: &egui::Context, scale: f32) { } #[cfg(test)] #[cfg(not(target_arch = "wasm32"))] -mod tests { - use super::*; - use egui::FontProvider; - use std::sync::Mutex; - - #[test] - fn lazy_fallbacks_follow_ui_font_size_and_survive_size_changes() { - use photocraft_engine::prefs::UiFontSize; - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); - crate::theme::set_ui_font_size(&ctx, UiFontSize::Large); - let name = "test-lazy-fallback".to_string(); - add_to_all_families(&ctx, name.clone(), FontData::from_static(photocraft_text::fonts::INTER_REGULAR.as_slice())); - for (size, scale) in [(UiFontSize::Large, 16.0 / 12.0), (UiFontSize::Tiny, 10.0 / 12.0), (UiFontSize::Small, 1.0)] { - crate::theme::set_ui_font_size(&ctx, size); - for _ in 0..2 { - ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); - } - let fonts = ctx.fonts(|f| f.definitions().clone()); - let fallback = fonts.font_data.get(&name).unwrap(); - assert_eq!(fallback.tweak.scale, scale); - assert_eq!(fallback.tweak.y_offset_factor, 0.0, "same face as Inter keeps its baseline"); - for stack in fonts.families.values() { - assert_eq!(stack.iter().filter(|n| *n == &name).count(), 1); - assert_eq!(stack.last(), Some(&name), "fallback stays at the lowest priority"); - } - } - } - - /// A face discovered by [`CraftFontProvider`] during a pass that also changes Interface > UI - /// Font Size must use the scale of the definitions active in that pass. The size plugin moves - /// the provider to the new scale only after `ctx.set_fonts` queued the rescaled definitions; - /// updating the provider in `set_ui_font_size` would put the new scale on a face laid out - /// with the old stack. - #[test] - fn discovered_faces_use_the_scale_of_the_definitions_they_were_laid_out_with() { - use photocraft_engine::prefs::UiFontSize; - fn thai_reader(_: &std::path::Path) -> Option> { - Some(synthetic_font(&[(0x0E01, 0x0E5B)])) - } - let ctx = egui::Context::default(); - crate::theme::install_fonts_with(&ctx, craft_only(|| None)); - ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); - let mut provider = CraftFontProvider::new( - &Sources { - locale: || Some("en".into()), - files: no_files, - last_resort: Vec::new, - pending: || false, - scripts: |script| if script == Script::Thai { vec![PathBuf::from("synthetic-thai.ttf")] } else { Vec::new() }, - covers: scripts::covering_face, - embedded: no_embedded, - eager_craft_fonts: false, - }, - 1.0, - ); - provider.reader = thai_reader; - let provider = std::sync::Arc::new(provider); - ctx.data_mut(|d| d.insert_temp(craft_provider_id(), provider.clone())); - let as_provider: std::sync::Arc = provider.clone(); - ctx.set_font_providers(vec![as_provider]); - - // The scale of the configured Inter face (part of `FontDefinitions`) and of the face the - // provider discovered for Thai. - let inter_scale = |ctx: &egui::Context| -> Option { ctx.fonts(|f| f.definitions().font_data.get("Inter").map(|data| data.tweak.scale)) }; - let thai_scale = |ctx: &egui::Context| -> Option { - ctx.fonts(|f| f.discovered_fonts().iter().find(|insert| insert.name.starts_with("craft-system-")).map(|insert| insert.data.tweak.scale)) - }; - // A frame that checks the state during the change pass, before laying out Thai (the - // character that makes the provider discover a face). - let frame = |check: &dyn Fn(&egui::Context)| { - ctx.run_ui(Default::default(), |ui| { - check(&ctx); - ui.label("ก"); - }) - .textures_delta - .clear(); - }; - // Small (the install default) is active. Walk Small -> Large -> Small, repeat Large - // (the same size must leave both the definitions and the provider alone, not accumulate) - // and back to Small. - assert_eq!(provider.scale(), 1.0); - for (size, want, same_size) in [ - (UiFontSize::Large, 16.0 / 12.0, false), - (UiFontSize::Small, 1.0, false), - (UiFontSize::Large, 16.0 / 12.0, false), - (UiFontSize::Large, 16.0 / 12.0, true), - (UiFontSize::Small, 1.0, false), - ] { - let old = provider.scale(); - let inter_before = inter_scale(&ctx); - crate::theme::set_ui_font_size(&ctx, size); - assert_eq!(provider.scale(), old, "the provider follows the definitions still active in this pass"); - frame(&|ctx: &egui::Context| { - assert_eq!(inter_scale(ctx), inter_before, "the configured Inter keeps its old scale during the change pass"); - assert_eq!(provider.scale(), old, "the provider does not move before the pass ends"); - }); - assert_eq!(provider.scale(), want, "the provider follows the rescaled definitions"); - if same_size { - assert_eq!(inter_scale(&ctx), inter_before, "a same-size request leaves the stack alone"); - } - assert_eq!(thai_scale(&ctx), Some(old), "the pass laid the discovered face out with the old definitions"); - // The queued definitions with the new scale are active now, and a new pass drops the - // discovered face and rediscovers it at the provider's new scale. - frame(&|ctx: &egui::Context| { - assert_eq!(inter_scale(ctx), Some(want), "the rescaled stack is active in the next pass"); - assert_eq!(provider.scale(), want); - }); - assert_eq!(thai_scale(&ctx), Some(want), "the next pass rediscovers the face at the provider's scale"); - } - } - - /// A font holding only an `fvar` table with the given axes (tag, min, default, max), as a - /// single face or as face 1 of a two-face collection. - fn fvar_font(axes: &[(&[u8; 4], f32, f32, f32)], collection: bool) -> Vec { - let fixed = |v: f32| ((v * 65536.0) as i32).to_be_bytes(); - let mut fvar = Vec::new(); - for x in [1u16, 0, 16, 2, axes.len() as u16, 20, 0, 0] { - fvar.extend(x.to_be_bytes()); - } - for (tag, min, def, max) in axes { - fvar.extend(*tag); - for v in [*min, *def, *max] { - fvar.extend(fixed(v)); - } - fvar.extend([0, 0, 1, 0]); - } - let face = |at: u32| { - let mut d = vec![0, 1, 0, 0, 0, 1, 0, 16, 0, 0, 0, 0]; - d.extend(b"fvar"); - d.extend([0; 4]); - d.extend(at.to_be_bytes()); - d.extend((fvar.len() as u32).to_be_bytes()); - d - }; - if !collection { - let mut f = face(28); - f.extend(&fvar); - return f; - } - // ttcf header (12 + 2×4), two 28-byte directories, then the shared table. - let mut f = b"ttcf".to_vec(); - f.extend([0, 1, 0, 0, 0, 0, 0, 2]); - f.extend(20u32.to_be_bytes()); - f.extend(48u32.to_be_bytes()); - f.extend(face(76)); - f.extend(face(76)); - f.extend(&fvar); - f - } - - /// #4820: Noto Sans CJK's variable collection defaults to Thin; the fallback asks for Regular. - #[test] - fn variable_fallbacks_are_drawn_at_regular_weight() { - let thin = fvar_font(&[(b"wght", 100.0, 100.0, 900.0)], true); - assert_eq!(regular_weight(&thin, 1), Some(400.0), "Noto Sans CJK VF, face 1 of a collection"); - assert_eq!(regular_weight(&fvar_font(&[(b"wdth", 75.0, 100.0, 100.0), (b"wght", 100.0, 100.0, 900.0)], false), 0), Some(400.0)); - assert_eq!(regular_weight(&fvar_font(&[(b"wght", 500.0, 600.0, 900.0)], false), 0), Some(500.0), "Regular clamped into the axis"); - assert_eq!(regular_weight(&fvar_font(&[(b"wght", 100.0, 400.0, 900.0)], false), 0), None, "already Regular"); - assert_eq!(regular_weight(&fvar_font(&[(b"wdth", 75.0, 100.0, 100.0)], false), 0), None, "no weight axis"); - assert_eq!(regular_weight(photocraft_text::fonts::INTER_REGULAR.as_slice(), 0), None, "static font"); - for bad in [&thin[..thin.len() - 9], &thin[..30], &b"ttcf"[..], &[][..]] { - assert_eq!(regular_weight(bad, 1), None); - } - // Registered as a fallback, a static face keeps the default (no variation) coordinates. - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); - add_to_all_families(&ctx, "test-static".into(), FontData::from_static(photocraft_text::fonts::INTER_REGULAR.as_slice())); - ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); - let fonts = ctx.fonts(|f| f.definitions().clone()); - assert_eq!(fonts.font_data.get("test-static").map(|d| d.tweak.coords.clone()), Some(Default::default())); - } - - /// A corrupt or non-font blob has no `hhea`, `head` or `fvar` table: the fallback tweaks - /// must leave it untouched rather than deriving a baseline or weight from garbage. - #[test] - fn font_tweaks_ignore_bytes_without_metrics_or_weight_axes() { - let mut data = FontData::from_static(b""); - apply_font_tweaks(&mut data); - assert_eq!(data.tweak.y_offset_factor, 0.0); - assert_eq!(data.tweak.coords, Default::default()); - } - - static DIR: Mutex> = Mutex::new(None); - - #[test] - fn changing_language_resets_the_loader_once_and_reorders_scripts() { - crate::i18n::with_language(crate::i18n::Lang::EN, || { - let ctx = egui::Context::default(); - crate::i18n::sync_context(&ctx, "ja"); - ctx.with_plugin::(|plugin| { - assert_eq!(plugin.0.order()[0], CjkScript::Japanese); - plugin.0.tried = plugin.0.order().to_vec(); - plugin.0.last_resort_tried = true; - }) - .expect("font plugin"); - crate::i18n::sync_context(&ctx, "ja"); - assert!(ctx.with_plugin::(|plugin| plugin.0.exhausted()).expect("font plugin"), "idle frames must not reload fonts"); - crate::i18n::sync_context(&ctx, "ko"); - ctx.with_plugin::(|plugin| { - assert!(!plugin.0.exhausted()); - assert_eq!(plugin.0.order()[0], CjkScript::Korean); - }) - .expect("font plugin"); - }); - } - - fn fake_dir() -> PathBuf { - let mut g = DIR.lock().unwrap(); - g.get_or_insert_with(|| { - let dir = std::env::temp_dir().join(format!("photocraft-cjk-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("font.ttf"), include_bytes!("../../../assets/fonts/Inter-Regular.ttf")).unwrap(); - std::fs::write(dir.join("empty.ttf"), b"").unwrap(); - std::fs::write(dir.join("thai.ttf"), synthetic_font(&[(0x0E01, 0x0E5B)])).unwrap(); - std::fs::write(dir.join("arabic.ttf"), synthetic_font(&[(0x0600, 0x06FF)])).unwrap(); - std::fs::write(dir.join("devanagari.ttf"), synthetic_font(&[(0x0900, 0x097F)])).unwrap(); - std::fs::write(dir.join("korean.ttf"), synthetic_font(&[(0xCE74, 0xCE74)])).unwrap(); - std::fs::write(dir.join("tamil.ttf"), synthetic_font(&[(0x0B80, 0x0BFF)])).unwrap(); - std::fs::write(dir.join("ethiopic.ttf"), synthetic_font(&[(0x1200, 0x137F)])).unwrap(); - std::fs::write(dir.join("hant.ttf"), synthetic_font(&[(0x9F8D, 0x9F8D)])).unwrap(); - std::fs::write( - dir.join("families.ttc"), - two_face_ttc(include_bytes!("../../../assets/fonts/Inter-Regular.ttf"), include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf")), - ) - .unwrap(); - dir - }) - .clone() - } - - fn fake(name: &str) -> FontFile { - FontFile { path: fake_dir().join(name), family: String::new() } - } - - #[test] - fn font_reads_skip_missing_empty_oversized_and_non_file_candidates() { - let dir = fake_dir(); - assert!(read_font(&dir.join("missing-read-test.ttf")).is_none(), "a missing path is skipped"); - assert!(read_font(&dir).is_none(), "a directory is not a font file"); - assert!(read_font(&dir.join("empty.ttf")).is_none(), "an empty file is skipped"); - - let oversized = dir.join("oversized-read-test.ttf"); - let file = std::fs::File::create(&oversized).expect("create a sparse oversized test file"); - file.set_len(MAX_FONT_BYTES + 1).expect("set the sparse file size"); - drop(file); - assert!(read_font(&oversized).is_none(), "an oversized file is not read"); - std::fs::remove_file(&oversized).expect("remove the sparse test file"); - - let valid = dir.join("font.ttf"); - assert_eq!(read_font(&valid).expect("the valid font is read").as_slice(), std::fs::read(&valid).expect("test font bytes").as_slice()); - } - - fn provider_corrupt_thai_candidates(script: Script) -> Vec { - if script == Script::Thai { - vec![ - fake_dir().join("provider-missing-thai.ttf"), - fake_dir().join("provider-corrupt-thai.ttf"), - fake_dir().join("provider-corrupt-selected-thai.ttc"), - fake_dir().join("font.ttf"), - fake_dir().join("thai.ttf"), - ] - } else { - Vec::new() - } - } - - fn provider_missing_thai_candidate(script: Script) -> Vec { - if script == Script::Thai { vec![fake_dir().join("provider-only-missing-thai.ttf")] } else { Vec::new() } - } - - /// The provider's non-CJK script route must reject a structurally invalid file, a readable - /// collection whose selected covering face is unreadable, and a missing file, then use the - /// next real candidate. The rejected and missing paths stay negative-cached. - #[test] - fn provider_skips_missing_and_corrupt_script_candidates_before_registering() { - let malformed = fake_dir().join("provider-corrupt-thai.ttf"); - let collection = fake_dir().join("provider-corrupt-selected-thai.ttc"); - std::fs::write(&malformed, font_with_out_of_bounds_table()).expect("write the malformed test font"); - std::fs::write(&collection, two_face_ttc(include_bytes!("../../../assets/fonts/Inter-Regular.ttf"), &font_with_out_of_bounds_table())) - .expect("write the malformed selected-face collection"); - - let sources = Sources { - locale: || Some("en".into()), - files: no_files, - last_resort: Vec::new, - pending: || false, - scripts: provider_corrupt_thai_candidates, - covers: scripts::covering_face, - embedded: no_embedded, - eager_craft_fonts: false, - }; - let provider = CraftFontProvider::new(&sources, 1.0); - let insert = provided_insert(&provider, 'ก').expect("the valid Thai candidate is reached"); - assert_eq!(insert.data.index, 0); - assert_eq!(insert.data.bytes(), std::fs::read(fake_dir().join("thai.ttf")).expect("Thai test font").as_slice()); - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert!(cache.failed_reads.contains(&fake_dir().join("provider-missing-thai.ttf")), "the missing file is remembered"); - assert!(cache.invalid_fonts.contains(&malformed), "the readable non-font is remembered as invalid"); - assert!(cache.files.iter().any(|file| file.path == collection), "the readable collection is retained for its other faces"); - drop(cache); - - let missing_only = Sources { scripts: provider_missing_thai_candidate, ..sources }; - let provider = CraftFontProvider::new(&missing_only, 1.0); - assert!(provided(&provider, 'ก').is_none(), "no readable script candidate leaves the character missing"); - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert_eq!(cache.failed_reads.len(), 1); - assert_eq!(cache.reads, 0); - } - - fn fake_sources(locale: fn() -> Option) -> Sources { - Sources { - locale, - // Korean has a readable Hangul font, Japanese only broken files, Chinese none. - files: |s| match s { - CjkScript::Korean => vec![fake("missing.ttc"), fake("empty.ttf"), fake("korean.ttf")], - CjkScript::Japanese => vec![fake("empty.ttf")], - _ => vec![], - }, - last_resort: || vec![fake("font.ttf")], - pending: || false, - scripts: |_| Vec::new(), - covers: scripts::covering_face, - embedded: no_embedded, - eager_craft_fonts: false, - } - } - - #[test] - fn picks_preferred_script_skips_unreadable_and_exhausts() { - let mut fb = CjkFallback::new(fake_sources(|| Some("en_US".into()))); - assert!(!fb.exhausted()); - // Hangul: Korean first; missing and empty files are skipped. - let (name, data) = fb.next_font('카', CjkChar::Hangul).expect("korean font"); - assert!(name.starts_with(FONT_PREFIX)); - assert_eq!(data.index, 0); - assert_eq!(fb.tried, vec![CjkScript::Korean]); - // Han on an English locale: system fallback keeps the locale order (SC first); the - // Japanese-first craft-manifest baseline is a separate provider/lazy-craft path. - // SC, TC, JA have nothing readable here, and the last-resort file was already loaded, - // so nothing new; everything is now tried. - assert!(fb.next_font('日', CjkChar::Han).is_none()); - assert!(fb.exhausted()); - assert_eq!(fb.tried, vec![CjkScript::Korean, CjkScript::SimplifiedChinese, CjkScript::TraditionalChinese, CjkScript::Japanese]); - assert_eq!(fb.registered.len(), 1, "a file is read at most once"); - assert!(fb.next_font('あ', CjkChar::Kana).is_none()); - } - - #[test] - fn han_follows_locale() { - for (loc, first) in [ - ("ja_JP.UTF-8", CjkScript::Japanese), - ("zh-Hans-CN", CjkScript::SimplifiedChinese), - ("zh-Hant-TW", CjkScript::TraditionalChinese), - ("ko_KR", CjkScript::Korean), - ] { - let mut fb = CjkFallback::new(Sources { - locale: || None, - files: |_| vec![], - last_resort: Vec::new, - pending: || false, - scripts: |_| Vec::new(), - covers: scripts::covering_face, - embedded: no_embedded, - eager_craft_fonts: false, - }); - fb.order = Some(cjk::script_order(Some(loc))); - assert!(fb.next_font('日', CjkChar::Han).is_none()); - assert_eq!(fb.tried[0], first, "{loc}"); - } - } - - /// Runs frames showing `text` until fonts settle; returns whether every glyph is covered. - fn render(ctx: &egui::Context, text: &str) -> bool { - for _ in 0..12 { - let mut out = ctx.run_ui(Default::default(), |ui| { - ui.label(text); - }); - out.textures_delta.clear(); - } - ctx.fonts_mut(|f| f.has_glyphs(&FontId::proportional(12.0), &text.replace(' ', ""))) - } - - /// A two-face TrueType collection built at runtime from the repository's OFL-licensed - /// Inter and JetBrains Mono files. Each face directory is rewritten with offsets relative to - /// the collection, so no font fixture is committed. - fn two_face_ttc(first: &[u8], second: &[u8]) -> Vec { - let font_count = 2usize; - let tables = |font: &[u8]| u16::from_be_bytes([font[4], font[5]]) as usize; - let dir_lengths = [12 + 16 * tables(first), 12 + 16 * tables(second)]; - let mut dir_offsets = Vec::with_capacity(font_count); - let mut cursor = 12 + 4 * font_count; - for length in dir_lengths { - dir_offsets.push(cursor); - cursor += length; - } - let data_start = cursor.next_multiple_of(4); - let mut bases = Vec::with_capacity(font_count); - let mut total = data_start; - for font in [first, second] { - bases.push(total); - total += font.len().next_multiple_of(4); - } - let mut out = vec![0u8; total]; - out[..4].copy_from_slice(b"ttcf"); - out[4..8].copy_from_slice(&0x0001_0000u32.to_be_bytes()); - out[8..12].copy_from_slice(&u32::try_from(font_count).expect("two faces").to_be_bytes()); - for (i, offset) in dir_offsets.iter().enumerate() { - let at = 12 + i * 4; - out[at..at + 4].copy_from_slice(&u32::try_from(*offset).expect("collection fits").to_be_bytes()); - } - for (i, font) in [first, second].into_iter().enumerate() { - let dir = dir_offsets[i]; - let base = bases[i]; - out[dir..dir + 12].copy_from_slice(&font[..12]); - for record in 0..tables(font) { - let src = 12 + 16 * record; - let dst = dir + 12 + 16 * record; - out[dst..dst + 8].copy_from_slice(&font[src..src + 8]); - let table_offset = u32::from_be_bytes(font[src + 8..src + 12].try_into().expect("four bytes")); - let collection_offset = u32::try_from(base).expect("collection fits") + table_offset; - out[dst + 8..dst + 12].copy_from_slice(&collection_offset.to_be_bytes()); - out[dst + 12..dst + 16].copy_from_slice(&font[src + 12..src + 16]); - } - out[base..base + font.len()].copy_from_slice(font); - } - out - } - - /// A minimal TrueType font mapping the `ranges` (inclusive) to box glyphs, so tests have a - /// font for a script without committing font files. - fn synthetic_font(ranges: &[(u32, u32)]) -> Vec { - let be16 = |v: &mut Vec, x: i32| v.extend((x as u16).to_be_bytes()); - let be32 = |v: &mut Vec, x: u32| v.extend(x.to_be_bytes()); - let chars: u32 = ranges.iter().map(|(a, b)| b - a + 1).sum(); - let glyphs = chars as i32 + 1; - // One 500x700 box (contour of four on-curve points); glyph 0 (.notdef) is empty. - let mut boxed = Vec::new(); - for x in [1, 50, 0, 550, 700, 3, 0] { - be16(&mut boxed, x); - } - boxed.extend([1u8; 4]); - for x in [50, 0, 500, 0, 0, 700, 0, -700] { - be16(&mut boxed, x); - } - boxed.extend([0, 0]); - let glyf: Vec = boxed.repeat(chars as usize); - let mut loca = Vec::new(); - be32(&mut loca, 0); - for i in 0..chars { - be32(&mut loca, i * boxed.len() as u32); - } - be32(&mut loca, chars * boxed.len() as u32); - let mut head = Vec::new(); - for x in [0x0001_0000, 0x0001_0000, 0, 0x5F0F_3CF5] { - be32(&mut head, x); - } - for x in [0x000B, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, -200, 600, 800, 0, 8, 2, 1, 0] { - be16(&mut head, x); - } - let mut hhea = Vec::new(); - be32(&mut hhea, 0x0001_0000); - for x in [800, -200, 0, 600, 0, 0, 550, 1, 0, 0, 0, 0, 0, 0, 0, glyphs] { - be16(&mut hhea, x); - } - let mut maxp = Vec::new(); - be32(&mut maxp, 0x0001_0000); - for x in [glyphs, 4, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0] { - be16(&mut maxp, x); - } - let mut hmtx = Vec::new(); - for _ in 0..glyphs { - be16(&mut hmtx, 600); - be16(&mut hmtx, 50); - } - let mut cmap = Vec::new(); - for x in [0, 1, 3, 10] { - be16(&mut cmap, x); - } - be32(&mut cmap, 12); - be16(&mut cmap, 12); - be16(&mut cmap, 0); - be32(&mut cmap, 16 + 12 * ranges.len() as u32); - be32(&mut cmap, 0); - be32(&mut cmap, ranges.len() as u32); - let mut gid = 1; - for (a, b) in ranges { - for x in [*a, *b, gid] { - be32(&mut cmap, x); - } - gid += b - a + 1; - } - let tables: [(&[u8; 4], Vec); 7] = - [(b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)]; - let mut font = Vec::new(); - be32(&mut font, 0x0001_0000); - for x in [7, 64, 2, 48] { - be16(&mut font, x); - } - let mut offset = 12 + 16 * tables.len() as u32; - for (tag, data) in &tables { - font.extend(*tag); - be32(&mut font, 0); - be32(&mut font, offset); - be32(&mut font, data.len() as u32); - offset += (data.len() as u32).next_multiple_of(4); - } - for (_, data) in &tables { - font.extend(data); - font.resize(font.len().next_multiple_of(4), 0); - } - font - } - - /// Thai, Arabic and Devanagari each have a synthetic font; Thai's list starts with unreadable - /// files and Inter, which doesn't map Thai. No other script has a font. - fn script_sources() -> Sources { - Sources { - locale: || Some("en".into()), - files: |_| vec![], - last_resort: Vec::new, - pending: || false, - scripts: |s| { - let f = |name: &str| fake_dir().join(name); - match s { - Script::Thai => vec![f("missing.ttf"), f("empty.ttf"), f("font.ttf"), f("thai.ttf")], - Script::Arabic => vec![f("arabic.ttf")], - Script::Devanagari => vec![f("devanagari.ttf")], - _ => vec![], - } - }, - covers: scripts::covering_face, - embedded: no_embedded, - eager_craft_fonts: false, - } - } - - fn fallback_files(ctx: &egui::Context) -> Vec { - ctx.with_plugin::(|p| p.0.registered.iter().map(|(_, path, _)| path.file_name().unwrap().to_string_lossy().into_owned()).collect()) - .unwrap() - } - - #[test] - fn layer_names_in_other_scripts_load_a_covering_font_once() { - let ctx = egui::Context::default(); - for _ in 0..2 { - crate::theme::install_fonts_with(&ctx, script_sources()); - assert!(render(&ctx, "Layer 1 – café")); - ctx.with_plugin::(|p| assert!(p.0.scripts_tried.is_empty(), "Latin text reads no font")).unwrap(); - assert!(fallback_files(&ctx).is_empty()); - // A Thai type layer's name (#2275), Arabic (#1693) and Devanagari: no missing glyphs. - for text in ["สวัสดี", "ภาพถ่าย/วันหยุดพักผ่อน", "مرحبا بالعالم", "नमस्ते दुनिया"] - { - assert!(render(&ctx, text), "tofu in {text}"); - } - assert_eq!(fallback_files(&ctx), ["thai.ttf", "arabic.ttf", "devanagari.ttf"], "the first file that maps the character, never Inter"); - // Hebrew has no font here: tried once, then left alone (no reload or repaint loop). - assert!(!render(&ctx, "שלום")); - assert!(!render(&ctx, "שלום")); - ctx.with_plugin::(|p| { - assert!(p.0.scripts_tried.contains(&Script::Hebrew)); - assert_eq!(p.0.registered.len(), 3); - }) - .unwrap(); - let fonts = ctx.fonts(|f| f.definitions().clone()); - assert_eq!(fonts.families[&FontFamily::Proportional].first().map(String::as_str), Some("Inter")); - for stack in fonts.families.values() { - assert_eq!(stack.iter().filter(|n| n.starts_with(FONT_PREFIX)).count(), 3); - assert_eq!(stack.last().map(String::as_str), Some("system-cjk-2"), "appended last so Latin keeps Inter"); - } - } - } - - #[test] - fn a_missing_cjk_font_does_not_block_other_scripts_and_vice_versa() { - let ctx = egui::Context::default(); - crate::theme::install_fonts_with(&ctx, script_sources()); - assert!(!render(&ctx, "日本語/ภาพถ่าย/วันหยุดพักผ่อน.png")); - assert!(render(&ctx, "ภาพถ่าย/วันหยุดพักผ่อน.png")); - ctx.with_plugin::(|p| assert!(p.0.exhausted())).unwrap(); - assert_eq!(fallback_files(&ctx), ["thai.ttf"]); - // A script with no font leaves CJK available. - let mut fallback = CjkFallback::new(fake_sources(|| Some("ko".into()))); - assert!(fallback.next_script_font('ส').is_none()); - assert!(fallback.next_script_font('ส').is_none()); - assert!(fallback.next_script_font('A').is_none(), "Latin is never a fallback script"); - assert_eq!(fallback.scripts_tried, [Script::Thai]); - assert!(fallback.next_font('카', CjkChar::Hangul).is_some()); - } - - #[test] - fn script_candidates_are_read_a_bounded_number_of_times() { - static CHECKED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - let mut fallback = CjkFallback::new(Sources { - scripts: |_| (0..20).map(|i| fake_dir().join(if i % 2 == 0 { "font.ttf" } else { "thai.ttf" })).collect(), - covers: |_, _| { - CHECKED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - None - }, - ..script_sources() - }); - assert!(fallback.next_script_font('ش').is_none()); - assert!(fallback.next_script_font('ش').is_none()); - assert_eq!(CHECKED.load(std::sync::atomic::Ordering::Relaxed), MAX_SCRIPT_READS, "one bounded pass per script"); - assert!(fallback.registered.is_empty()); - assert!(!fallback.scripts_exhausted()); - } - - #[test] - fn system_fonts_cover_other_script_samples() { - // Like the CJK system-font test, run per script when this machine has a font for it. - // The deterministic tests above do not need installed fonts. - let samples = [("ภาพถ่าย/วันหยุดพักผ่อน", 'ภ'), ("مرحبا", 'م'), ("שלום", 'ש'), ("नमस्ते", 'न')]; - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - for (text, c) in samples { - let Some(script) = scripts::classify(c) else { continue }; - if !scripts::system_candidates(script).iter().any(|p| read_font(p).and_then(|b| scripts::covering_face(&b, c)).is_some()) { - eprintln!("skipping {text}: no {script:?} system font"); - continue; - } - assert!(render(&ctx, text), "{text} still has missing glyphs"); - } - } - - #[test] - fn vertical_metrics_parse_and_reject_garbage() { - let (asc, desc, gap) = vertical_metrics(include_bytes!("../../../assets/fonts/Inter-Regular.ttf"), 0).unwrap(); - assert!((asc - 1984.0 / 2048.0).abs() < 1e-4 && (desc + 494.0 / 2048.0).abs() < 1e-4 && gap == 0.0); - for bad in [&b""[..], b"ttcf", b"ttcf\0\0\0\0\0\0\0\0\xff\xff\xff\xff", b"\0\x01\0\0\0\xff\0\0\0\0\0\0"] { - assert!(vertical_metrics(bad, 0).is_none()); - assert!(vertical_metrics(bad, u32::MAX).is_none()); - } - } - - #[test] - fn a_face_with_a_big_line_gap_is_shifted_down_onto_the_primary_baseline() { - let inter = (1984.0 / 2048.0, -494.0 / 2048.0, 0.0); - let hiragino = (0.88, -0.12, 0.5); - assert!((baseline_offset(hiragino, inter) - 0.2338).abs() < 1e-3); - assert_eq!(baseline_offset(inter, inter), 0.0); - assert_eq!(baseline_offset((f32::NAN, 0.0, 0.0), inter), 0.0); - let jb = (1.02, -0.3, 0.0); - assert!((baseline_offset(hiragino, jb) - baseline_offset(hiragino, inter)).abs() < 0.005, "one offset serves the monospace family too"); - } - - #[test] - fn lazy_registration_triggers_only_for_supported_scripts() { - let ctx = egui::Context::default(); - install_with(&ctx, fake_sources(|| Some("ko".into()))); - let _ = render(&ctx, "Layer 1 – café"); - let n = ctx.fonts(|f| f.definitions().font_data.keys().filter(|k| k.starts_with(FONT_PREFIX)).count()); - assert_eq!(n, 0, "Latin text loads nothing"); - // The Korean candidate covers the first missing Hangul character and is registered. - let _ = render(&ctx, "카드 배경"); - let fonts = ctx.fonts(|f| f.definitions().clone()); - let name = format!("{FONT_PREFIX}-0"); - assert!(fonts.font_data.contains_key(&name)); - for (fam, stack) in &fonts.families { - assert_eq!(stack.last(), Some(&name), "{fam:?}: appended last so Latin keeps Inter"); - } - } - - /// Craft fonts available through the first-frame provider, as the desktop shell does. - fn eager_sources(locale: fn() -> Option) -> Sources { - Sources { - locale, - files: |_| vec![], - last_resort: Vec::new, - pending: || false, - scripts: |_| Vec::new(), - covers: scripts::covering_face, - embedded: craft_embedded_iso, - eager_craft_fonts: true, - } - } - - /// No system fonts at all: craft-fonts alone draws CJK through the lazy loader. - fn craft_only(locale: fn() -> Option) -> Sources { - Sources { - locale, - files: |_| vec![], - last_resort: Vec::new, - pending: || false, - scripts: |_| Vec::new(), - covers: scripts::covering_face, - embedded: craft_embedded_iso, - eager_craft_fonts: false, - } - } - - /// The migration baseline's first craft face covering `c`: the first non-empty face in - /// manifest order (what the old family stack appended first), not the UI-first sort. - fn baseline_face(c: char) -> Option<&'static CraftFont> { - craft_fonts::CRAFT_FONTS.iter().find(|f| !f.bytes.is_empty() && scripts::face_covers(f.bytes, 0, c)) - } - - /// A test-only craft face backed by a collection built with [`two_face_ttc`]: face 0 maps - /// Thai only, face 1 maps 龍. `craft_insert` would install face 0, so the craft coverage - /// helpers must not accept it for 龍 even though a later face covers the character. - fn ttc_craft_face() -> &'static CraftFont { - static FACE: std::sync::OnceLock = std::sync::OnceLock::new(); - FACE.get_or_init(|| { - let bytes: &'static [u8] = Box::leak(two_face_ttc(&synthetic_font(&[(0x0E01, 0x0E5B)]), &synthetic_font(&[(0x9F8D, 0x9F8D)])).into_boxed_slice()); - CraftFont { family: "Synthetic Collection", style: "Regular", scripts: &["Hans"], bytes } - }) - } - - /// The craft helpers must test face 0, the face `FontData::from_static` installs. The old - /// any-face coverage check returned the face for a character only a later collection face - /// maps, which then drew tofu in the installed face 0. - #[test] - fn craft_face_coverage_matches_the_face_craft_insert_installs() { - let face = ttc_craft_face(); - // Precondition: an any-face check really accepts 龍 (face 1), so this regression would - // fail if the helpers went back to `scripts::covering_face`. - assert_eq!(scripts::covering_face(face.bytes, '龍'), Some(1), "face 1 maps 龍"); - assert!(!scripts::face_covers(face.bytes, 0, '龍'), "the installed face 0 does not map 龍"); - assert!(!craft_face_installs_coverage(face, '龍'), "face 0 lacks the glyph; craft_insert installs face 0"); - assert!(craft_face_installs_coverage(face, 'ก'), "face 0 maps Thai"); - } - - static EMPTY_CRAFT_FACE: CraftFont = CraftFont { family: "Empty", style: "Regular", scripts: &["Zsym"], bytes: &[] }; - - fn only_empty_craft_face(_: &'static str) -> Vec<&'static CraftFont> { - vec![&EMPTY_CRAFT_FACE] - } - - /// A craft entry without bytes, or a face injected only by a test that is absent from the - /// global manifest, has no installable face index: selection must return `None`, not a face - /// name egui cannot resolve. - #[test] - fn craft_face_selection_ignores_empty_and_unindexed_faces() { - assert!(!craft_face_installs_coverage(&EMPTY_CRAFT_FACE, '☃')); - assert!(craft_face_for(only_empty_craft_face, "Zsym", '☃').is_none()); - assert!(craft_face_manifest(only_empty_craft_face, "Zsym", '☃').is_none()); - } - - /// Every script the lazy fallback can see has a valid ISO 15924 tag, so its injected craft - /// faces and the CJK scripts are selected by the same tags the manifest declares. - #[test] - fn fallback_scripts_map_to_iso_15924_tags() { - assert_eq!(cjk_iso(CjkScript::Japanese), "Jpan"); - assert_eq!(cjk_iso(CjkScript::SimplifiedChinese), "Hans"); - assert_eq!(cjk_iso(CjkScript::TraditionalChinese), "Hant"); - assert_eq!(cjk_iso(CjkScript::Korean), "Kore"); - let expected = [ - (Script::Thai, "Thai"), - (Script::Lao, "Laoo"), - (Script::Khmer, "Khmr"), - (Script::Myanmar, "Mymr"), - (Script::Tibetan, "Tibt"), - (Script::Arabic, "Arab"), - (Script::Hebrew, "Hebr"), - (Script::Armenian, "Armn"), - (Script::Georgian, "Geor"), - (Script::Ethiopic, "Ethi"), - (Script::Devanagari, "Deva"), - (Script::Bengali, "Beng"), - (Script::Gurmukhi, "Guru"), - (Script::Gujarati, "Gujr"), - (Script::Oriya, "Orya"), - (Script::Tamil, "Taml"), - (Script::Telugu, "Telu"), - (Script::Kannada, "Knda"), - (Script::Malayalam, "Mlym"), - (Script::Sinhala, "Sinh"), - ]; - assert_eq!(expected.len(), Script::ALL.len(), "the test lists every fallback script"); - for (script, iso) in expected { - assert_eq!(script_iso(script), iso, "{script:?}"); - } - assert_eq!(craft_embedded(CjkScript::Japanese).len(), craft_embedded_iso("Jpan").len()); - } - - /// No system fonts at all: craft-fonts alone draws CJK, in the locale's script order. - #[test] - fn craft_fonts_render_cjk_without_system_fonts() { - let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { - eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); - return; - }; - let Some(chinese) = craft_fonts::CRAFT_FONTS.iter().find(|f| f.family == "Noto Sans CJK SC" && f.style == "Regular") else { - eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); - return; - }; - // The craft manifest's Japanese faces come before Noto Sans CJK SC and the baseline - // appended them in manifest order, so a non-CJK/unknown effective locale keeps Shippori - // Mincho (the first covering face). An explicit locale keeps its own UI-first script face. - let Some(baseline) = baseline_face('日') else { - eprintln!("skipping: the craft-fonts manifest has no face covering 日"); - return; - }; - for (locale, expected) in [ - ((|| Some("en_US".into())) as fn() -> Option, baseline), - ((|| Some("ja_JP".into())) as fn() -> Option, ui_font), - ((|| Some("zh-CN".into())) as fn() -> Option, chinese), - ((|| None) as fn() -> Option, baseline), - ] { - let ctx = egui::Context::default(); - crate::theme::install_fonts_with(&ctx, craft_only(locale)); - assert!(render(&ctx, "日本語の文字"), "tofu in 日本語の文字"); - assert!(render(&ctx, "レイヤー 1"), "tofu in kana"); - let fonts = ctx.fonts(|f| f.definitions().clone()); - let name = format!("{FONT_PREFIX}-0"); - assert!( - fonts.font_data.get(&name).is_some_and(|d| std::ptr::eq(d.bytes().as_ptr(), expected.bytes.as_ptr())), - "{} first by locale: {name}", - expected.family - ); - for (fam, stack) in &fonts.families { - assert_eq!(stack.last(), Some(&name), "{fam:?}: appended last so Latin keeps Inter"); - assert!(stack.first().is_some_and(|f| f != &name), "{fam:?}"); - } - } - } - - fn provided_insert(provider: &CraftFontProvider, c: char) -> Option { - let mut buf = [0u8; 4]; - let cluster = c.encode_utf8(&mut buf); - provider.font_for(&FallbackRequest { cluster, family: &FontFamily::Proportional }) - } - - fn provided(provider: &CraftFontProvider, c: char) -> Option { - provided_insert(provider, c).map(|insert| insert.name) - } - - fn test_sources(locale: fn() -> Option) -> Sources { - Sources { - locale, - files: no_files, - last_resort: Vec::new, - pending: || false, - scripts: no_script_files, - covers: scripts::covering_face, - embedded: craft_embedded_iso, - eager_craft_fonts: false, - } - } - - fn test_provider(locale: fn() -> Option) -> CraftFontProvider { - CraftFontProvider::new(&test_sources(locale), 1.0) - } - - #[test] - fn effective_locale_prefers_the_translated_ui_then_the_os_locale() { - assert_eq!(effective_locale("ja", Some("en_US.UTF-8")), Some("ja".into())); - assert_eq!(effective_locale("zh-hant", Some("ja_JP.UTF-8")), Some("zh-hant".into())); - assert_eq!(effective_locale("en", Some("ja_JP.UTF-8")), Some("ja_JP.UTF-8".into()), "English UI on a Japanese OS uses the OS locale"); - assert_eq!(effective_locale("de", Some("ko_KR")), Some("ko_KR".into())); - assert_eq!(effective_locale("en", None), None, "no UI preference and no OS locale stays unknown"); - } - - fn no_script_files(_: Script) -> Vec { - Vec::new() - } - - fn no_files(_: CjkScript) -> Vec { - Vec::new() - } - - /// A stand-in system Traditional Chinese file, so the system-before-SC-craft ordering is - /// testable without depending on the host's fonts. Its content is the SC craft face (which - /// covers the sample Han character). - fn hant_system_file() -> Option { - static FILE: std::sync::OnceLock> = std::sync::OnceLock::new(); - let face = craft_fonts::CRAFT_FONTS.iter().find(|f| f.family == "Noto Sans CJK SC" && !f.bytes.is_empty())?; - FILE.get_or_init(|| { - let path = std::env::temp_dir().join(format!("photocraft-hant-{}.otf", std::process::id())); - std::fs::write(&path, face.bytes).ok().map(|()| path) - }) - .clone() - } - - fn hant_files(script: CjkScript) -> Vec { - if script == CjkScript::TraditionalChinese { - hant_system_file().map(|path| vec![FontFile { path, family: String::new() }]).unwrap_or_default() - } else { - Vec::new() - } - } - - #[test] - fn craft_font_provider_keeps_the_baseline_face_for_unknown_locales() { - let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { - eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); - return; - }; - let Some(ui_index) = craft_index(ui_font) else { return }; - let Some((sc_index, sc)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans CJK SC") else { - eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); - return; - }; - let Some((korean_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "NanumGothic") else { - eprintln!("skipping: the craft-fonts manifest has no Korean face"); - return; - }; - let Some((arabic_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans Arabic") else { - eprintln!("skipping: the craft-fonts manifest has no Arabic face"); - return; - }; - let Some((devanagari_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans Devanagari") else { - eprintln!("skipping: the craft-fonts manifest has no Devanagari face"); - return; - }; - let Some(baseline_han) = baseline_face('日') else { - eprintln!("skipping: the craft-fonts manifest has no face covering 日"); - return; - }; - let Some(baseline_kana) = baseline_face('あ') else { - eprintln!("skipping: the craft-fonts manifest has no face covering あ"); - return; - }; - let baseline_han_index = craft_index(baseline_han).expect("a manifest face has an index"); - let baseline_kana_index = craft_index(baseline_kana).expect("a manifest face has an index"); - let baseline_han_name = format!("craft-font-{baseline_han_index}"); - let baseline_kana_name = format!("craft-font-{baseline_kana_index}"); - let ui_name = format!("craft-font-{ui_index}"); - let sc_name = format!("craft-font-{sc_index}"); - let korean_name = format!("craft-font-{korean_index}"); - let arabic_name = format!("craft-font-{arabic_index}"); - let devanagari_name = format!("craft-font-{devanagari_index}"); - - let ja = test_provider((|| Some("ja_JP".into())) as fn() -> Option); - assert_eq!(provided(&ja, 'あ').as_deref(), Some(ui_name.as_str()), "explicit ja keeps the Japanese UI face"); - assert_eq!(provided(&ja, '日').as_deref(), Some(ui_name.as_str()), "Han follows an explicit Japanese locale"); - - let en = test_provider((|| Some("en_US".into())) as fn() -> Option); - assert_eq!( - provided(&en, 'あ').as_deref(), - Some(baseline_kana_name.as_str()), - "kana in a non-CJK effective locale keeps the manifest's first covering face" - ); - assert_eq!(provided(&en, '한').as_deref(), Some(korean_name.as_str()), "Hangul in a non-CJK effective locale stays on the Korean face"); - assert_eq!( - provided(&en, '日').as_deref(), - Some(baseline_han_name.as_str()), - "Han in a non-CJK effective locale keeps the manifest's first covering face" - ); - let unknown = test_provider((|| None) as fn() -> Option); - assert_eq!(provided(&unknown, '日').as_deref(), Some(baseline_han_name.as_str()), "an unknown effective locale has the same baseline face"); - let english_on_japanese_os = test_provider((|| effective_locale("en", Some("ja_JP"))) as fn() -> Option); - assert_eq!( - provided(&english_on_japanese_os, '日').as_deref(), - Some(ui_name.as_str()), - "English UI on a Japanese OS follows the OS locale; the manifest baseline is not universal for English UI" - ); - assert_eq!(provided(&en, 'م').as_deref(), Some(arabic_name.as_str()), "Arabic uses its own craft face"); - assert_eq!(provided(&en, 'न').as_deref(), Some(devanagari_name.as_str()), "Devanagari uses its own craft face"); - - let hans = test_provider((|| Some("zh-CN".into())) as fn() -> Option); - assert_eq!(provided(&hans, '日').as_deref(), Some(sc_name.as_str())); - assert_eq!(provided(&hans, 'あ').as_deref(), Some(ui_name.as_str()), "kana in a Chinese UI keeps the Japanese face"); - - let hant = test_provider((|| Some("zh-Hant-TW".into())) as fn() -> Option); - assert_eq!(provided(&hant, '龍').as_deref(), Some(sc_name.as_str()), "with no system Hant face, the locale order falls through to SC"); - assert_eq!(provided(&hant, '\u{3105}').as_deref(), Some(sc_name.as_str()), "Bopomofo follows the same locale-order fallback"); - assert_eq!(provided(&hant, 'あ').as_deref(), Some(ui_name.as_str()), "kana in a Hant UI keeps the Japanese face"); - - // A system Hant file, when present, is read before the Simplified Chinese craft fallback. - if hant_system_file().is_some() { - let sources = Sources { - locale: (|| Some("zh-Hant-TW".into())) as fn() -> Option, - files: hant_files, - last_resort: Vec::new, - pending: || false, - scripts: no_script_files, - covers: scripts::covering_face, - embedded: craft_embedded_iso, - eager_craft_fonts: false, - }; - let hant = CraftFontProvider::new(&sources, 1.0); - let got = provided(&hant, '龍').expect("the system Hant face"); - assert!(got.starts_with("craft-system-"), "the system Hant face comes before the SC craft fallback: {got}"); - assert_ne!(got, sc_name, "the SC craft face must not pre-empt a system Hant face"); - } - - let ko = test_provider((|| Some("ko_KR".into())) as fn() -> Option); - assert_eq!(provided(&ko, '한').as_deref(), Some(korean_name.as_str())); - assert_eq!(provided(&ko, 'あ').as_deref(), Some(ui_name.as_str()), "kana in a Korean UI keeps the Japanese face"); - assert_ne!(sc.family, ui_font.family); - } - - static PENDING_LAST_RESORT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - static PENDING_CRAFT_SC: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - static PENDING_READY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - static STRICT_PENDING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); - - fn pending_last_resort() -> bool { - PENDING_LAST_RESORT.load(std::sync::atomic::Ordering::Relaxed) - } - - fn pending_craft_sc() -> bool { - PENDING_CRAFT_SC.load(std::sync::atomic::Ordering::Relaxed) - } - - fn pending_ready() -> bool { - !PENDING_READY.load(std::sync::atomic::Ordering::Relaxed) - } - - fn strict_pending() -> bool { - STRICT_PENDING.load(std::sync::atomic::Ordering::Relaxed) - } - - fn ready_files(script: CjkScript) -> Vec { - if script == CjkScript::TraditionalChinese && PENDING_READY.load(std::sync::atomic::Ordering::Relaxed) { vec![fake("hant.ttf")] } else { Vec::new() } - } - - fn ready_hant_files(script: CjkScript) -> Vec { - if script == CjkScript::TraditionalChinese { vec![fake("hant.ttf")] } else { Vec::new() } - } - - #[test] - fn provider_uses_the_requested_collection_family_and_its_exact_coverage() { - let path = fake_dir().join("families.ttc"); - let provider = CraftFontProvider::new(&test_sources(|| Some("en".into())), 1.0); - let file = |family: &str| vec![FontFile { path: path.clone(), family: family.into() }]; - - let insert = provider.system_insert_files(file("JetBrains Mono"), 'A').expect("face 1 covers A"); - assert_eq!(insert.data.index, 1, "the requested family selects face 1, not the first covering face 0"); - assert!( - provider.system_insert_files(file("JetBrains Mono"), 'ƀ').is_none(), - "JetBrains Mono does not cover the character; face 0 of Inter must not be used" - ); - - let empty_family = vec![FontFile { path: path.clone(), family: String::new() }]; - let insert = provider.system_insert_files(empty_family, 'ƀ').expect("an empty family is face 0"); - assert_eq!(insert.data.index, 0); - } - - #[test] - fn cached_system_face_returns_the_current_scale() { - let path = fake_dir().join("families.ttc"); - let provider = CraftFontProvider::new(&test_sources(|| Some("en".into())), 1.0); - let file = || vec![FontFile { path: path.clone(), family: "JetBrains Mono".into() }]; - - let first = provider.system_insert_files(file(), 'A').expect("face 1 covers A"); - assert_eq!(first.data.index, 1); - assert_eq!(first.data.tweak.scale, 1.0); - provider.set_scale(4.0 / 3.0); - let second = provider.system_insert_files(file(), 'A').expect("cached face"); - assert_eq!(second.data.index, 1); - assert_eq!(second.data.tweak.scale, 4.0 / 3.0, "a cached face must not bake in the old UI scale"); - } - - #[test] - fn provider_honours_the_injected_embedded_faces() { - let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { - eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); - return; - }; - if craft_index(ui_font).is_none() { - return; - } - let Some(baseline) = baseline_face('あ') else { return }; - let baseline_name = format!("craft-font-{}", craft_index(baseline).expect("a manifest face has an index")); - let with_craft = test_provider((|| Some("en_US".into())) as fn() -> Option); - assert_eq!(provided(&with_craft, 'あ').as_deref(), Some(baseline_name.as_str())); - - let no_craft = Sources { embedded: no_embedded, ..test_sources((|| Some("en_US".into())) as fn() -> Option) }; - let provider = CraftFontProvider::new(&no_craft, 1.0); - assert!(provided(&provider, 'あ').is_none(), "the provider must use Sources::embedded, not the global craft table"); - } - - #[test] - fn provider_reaches_a_fontconfig_match_after_six_missing_candidates() { - let mut files: Vec = - (0..MAX_SCRIPT_READS).map(|i| FontFile { path: fake_dir().join(format!("missing-{i}.ttf")), family: String::new() }).collect(); - files.push(fake("hant.ttf")); - let provider = CraftFontProvider::new(&test_sources((|| Some("zh-Hant-TW".into())) as fn() -> Option), 1.0); - let insert = provider.system_insert_files(files, '龍').expect("the seventh (Fontconfig) candidate must be reachable"); - assert!(insert.name.starts_with("craft-system-")); - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert_eq!(cache.reads, 1, "only the real file counts as a read; absent paths do not"); - assert_eq!(cache.failed_reads.len(), MAX_SCRIPT_READS); - } - - #[test] - fn provider_caches_failed_reads_and_face_lookups_across_characters() { - let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); - let missing = fake("missing-cache.ttf"); - assert!(provider.system_insert_files(vec![missing.clone()], '日').is_none()); - assert!(provider.system_insert_files(vec![missing.clone()], '本').is_none()); - { - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert_eq!(cache.failed_reads.len(), 1, "a missing path is remembered"); - assert_eq!(cache.reads, 0, "a missing path performs no font read"); - } - - // Inter is readable but does not cover either Han character: its bytes are read once. - let inter = fake("font.ttf"); - assert!(provider.system_insert_files(vec![inter.clone()], '日').is_none()); - assert!(provider.system_insert_files(vec![inter.clone()], '本').is_none()); - { - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert_eq!(cache.reads, 1, "the second character reuses the cached bytes"); - assert_eq!(cache.files.len(), 1); - } - - // A collection's family lookup is parsed once even when it misses every character. - let path = fake_dir().join("families.ttc"); - let file = vec![FontFile { path, family: "Noto Sans CJK TC".into() }]; - assert!(provider.system_insert_files(file.clone(), '日').is_none()); - assert!(provider.system_insert_files(file, '本').is_none()); - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert_eq!(cache.family_indices.len(), 1, "a family miss is cached"); - assert_eq!(cache.family_indices[0].2, None); - } - - static TTC_READS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - - fn counted_ttc_read(path: &std::path::Path) -> Option> { - TTC_READS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - std::fs::read(path).ok() - } - - /// A collection's two faces share one blob: selecting both faces reads the file once and - /// charges its bytes once, not once per face. - #[test] - fn provider_charges_a_ttc_blob_once_for_multiple_selected_faces() { - let path = fake_dir().join("families.ttc"); - let size = std::fs::metadata(&path).expect("test collection").len() as usize; - let mut provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); - provider.reader = counted_ttc_read; - TTC_READS.store(0, std::sync::atomic::Ordering::Relaxed); - let first = provider.system_insert_files(vec![FontFile { path: path.clone(), family: "Inter".into() }], 'A').expect("face 0 covers A"); - let second = provider.system_insert_files(vec![FontFile { path: path.clone(), family: "JetBrains Mono".into() }], 'A').expect("face 1 covers A"); - assert_eq!((first.data.index, second.data.index), (0, 1)); - assert!(std::sync::Arc::ptr_eq(&first.data.font, &second.data.font), "both faces share the collection's blob"); - assert_eq!(TTC_READS.load(std::sync::atomic::Ordering::Relaxed), 1, "the collection is read once"); - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert_eq!(cache.files.len(), 1, "one retained blob serves both faces"); - assert_eq!(cache.retained_bytes, size, "the TTC blob is charged once"); - assert_eq!(cache.faces.len(), 2, "both selected faces keep their own name"); - } - - /// Selecting a second face under a one-blob budget evicts the earlier blob from the - /// provider, but the earlier `FontInsert` remains valid because it owns its shared blob. - #[test] - fn provider_evicts_an_earlier_selected_blob_under_budget_pressure() { - let first_path = fake("font.ttf").path; - let bytes = std::fs::read(&first_path).expect("test font"); - let size = bytes.len(); - let second_path = fake_dir().join("budget-selected-second.ttf"); - std::fs::write(&second_path, &bytes).expect("write a second test font"); - let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); - { - let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - cache.max_bytes = size; - } - let first = provider.system_insert_files(vec![FontFile { path: first_path.clone(), family: String::new() }], 'A').expect("the first selected face"); - let second = provider.system_insert_files(vec![FontFile { path: second_path.clone(), family: String::new() }], 'A').expect("the second selected face"); - assert_ne!(first.name, second.name); - assert_eq!(first.data.bytes(), bytes.as_slice(), "evicting the provider's blob does not invalidate egui's copy"); - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert_eq!(cache.files.len(), 1, "only one blob fits"); - assert_eq!(cache.files[0].path, second_path, "the newest selected blob is retained"); - assert_eq!(cache.retained_bytes, size, "the provider cache stays within its one-blob budget"); - assert_eq!(cache.faces.len(), 2, "the earlier face name remains reusable metadata, not bytes"); - } - - /// A selected face whose blob does not fit the budget is still returned complete for this - /// request. egui may keep it, but the provider retains neither its bytes nor a second copy. - #[test] - fn provider_returns_a_transient_valid_face_when_the_blob_cannot_be_retained() { - let path = fake("font.ttf").path; - let size = std::fs::metadata(&path).expect("test font").len() as usize; - let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); - { - let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - cache.max_bytes = size.saturating_sub(1); - } - let insert = provider - .system_insert_files(vec![FontFile { path: path.clone(), family: String::new() }], 'A') - .expect("the over-budget face is returned transiently"); - assert_eq!(insert.data.index, 0); - assert_eq!(insert.data.bytes().len(), size, "the transient face carries the whole valid font"); - assert_eq!(insert.data.bytes(), std::fs::read(&path).expect("test font bytes").as_slice()); - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert_eq!(cache.retained_bytes, 0, "an over-budget face retains no provider bytes"); - assert!(cache.files.is_empty(), "the over-budget blob is not retained"); - assert!(cache.retained_bytes <= cache.max_bytes, "the provider cache stays within its budget"); - assert_eq!(cache.reads, 1); - } - - /// A valid font file whose character map does not include the requested character is still a - /// valid font: its bytes are cached within the budget and it is not marked invalid. - #[test] - fn provider_cache_evicts_retained_bytes_within_the_budget() { - let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); - let bytes = synthetic_font(&[(0x0E01, 0x0E5B)]); - let size = bytes.len(); - assert!(size > 0); - { - let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - cache.max_bytes = size.saturating_mul(2); - } - let mut paths = Vec::new(); - for i in 0..5 { - let path = fake_dir().join(format!("budget-{i}.ttf")); - std::fs::write(&path, &bytes).expect("write a synthetic test font"); - paths.push(path); - } - for path in &paths { - let file = vec![FontFile { path: path.clone(), family: String::new() }]; - assert!(provider.system_insert_files(file, '日').is_none(), "the Thai-only face does not cover 日"); - } - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert!(cache.retained_bytes <= cache.max_bytes, "retained {} > budget {}", cache.retained_bytes, cache.max_bytes); - assert!(cache.files.len() <= 2, "only two files fit the budget"); - assert!(cache.files.iter().any(|file| file.path == paths[4]), "the newest retained file stays"); - assert!(!cache.files.iter().any(|file| file.path == paths[0]), "the oldest retained file was evicted"); - assert_eq!(cache.reads, 5, "each distinct file was read once"); - assert!(cache.invalid_fonts.is_empty(), "a non-covering face is not an invalid font"); - } - - /// A later covering candidate (such as the Fontconfig match appended last) is reached even - /// when a tiny budget evicts every retained candidate before it. - #[test] - fn provider_reaches_a_later_covering_candidate_under_budget_pressure() { - let provider = CraftFontProvider::new(&test_sources((|| Some("zh-Hant-TW".into())) as fn() -> Option), 1.0); - let bytes = synthetic_font(&[(0x0E01, 0x0E5B)]); - { - let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - cache.max_bytes = bytes.len(); - } - let mut files = Vec::new(); - for i in 0..12 { - let path = fake_dir().join(format!("budget-later-{i}.ttf")); - std::fs::write(&path, &bytes).expect("write a synthetic test font"); - files.push(FontFile { path, family: String::new() }); - } - let covering = fake("hant.ttf").path; - files.push(FontFile { path: covering.clone(), family: String::new() }); - let insert = provider.system_insert_files(files, '龍').expect("the later covering candidate must be reached"); - assert!(insert.name.starts_with("craft-system-"), "{insert:?}"); - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert!(cache.faces.iter().any(|face| face.path == covering), "the covering file became a selected face"); - assert!(cache.reads >= 13, "all retained candidates plus the matching file were read"); - } - - /// The old lifetime read cap could exhaust before a Fontconfig match appended after many - /// earlier characters. Reads are no longer globally capped; only retained bytes are bounded. - #[test] - fn provider_has_no_lifetime_read_cap_for_the_final_fontconfig_candidate() { - let provider = CraftFontProvider::new(&test_sources((|| Some("zh-Hant-TW".into())) as fn() -> Option), 1.0); - let bytes = synthetic_font(&[(0x0E01, 0x0E5B)]); - { - let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - cache.max_bytes = bytes.len(); - } - for i in 0..130 { - let path = fake_dir().join(format!("lifetime-{i}.ttf")); - std::fs::write(&path, &bytes).expect("write a synthetic test font"); - let file = vec![FontFile { path, family: String::new() }]; - assert!(provider.system_insert_files(file, '日').is_none()); - } - let covering = fake("hant.ttf").path; - let insert = provider - .system_insert_files(vec![FontFile { path: covering, family: String::new() }], '龍') - .expect("the final candidate must still be read after 130 successful reads"); - assert!(insert.name.starts_with("craft-system-"), "{insert:?}"); - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert_eq!(cache.reads, 131, "130 non-covering reads plus the final candidate"); - } - - static CONCURRENT_READS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - - fn counted_slow_read(path: &std::path::Path) -> Option> { - CONCURRENT_READS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - std::thread::sleep(std::time::Duration::from_millis(20)); - std::fs::read(path).ok() - } - - /// Layout may ask the provider from several threads. The check/read/insert is serialised, so - /// the same path is read once and every caller sees the same success. - #[test] - fn provider_serialises_concurrent_reads_of_the_same_path() { - let path = fake("font.ttf").path; - let mut provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); - provider.reader = counted_slow_read; - CONCURRENT_READS.store(0, std::sync::atomic::Ordering::Relaxed); - let provider = std::sync::Arc::new(provider); - let mut handles = Vec::new(); - for _ in 0..8 { - let provider = std::sync::Arc::clone(&provider); - let path = path.clone(); - handles.push(std::thread::spawn(move || { - let file = vec![FontFile { path, family: String::new() }]; - provider.system_insert_files(file, 'A').is_some() - })); - } - for handle in handles { - assert!(handle.join().expect("layout thread"), "every caller must get the Inter face"); - } - assert_eq!(CONCURRENT_READS.load(std::sync::atomic::Ordering::Relaxed), 1, "one read per path even under concurrency"); - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert_eq!(cache.faces.len(), 1, "one selected face is shared"); - } - - /// A readable non-font is negative-cached as invalid (read/parsed once) and never conflated - /// with a valid font that simply does not cover the requested character. - #[test] - fn provider_negative_caches_invalid_fonts_separately_from_noncovering_faces() { - let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); - let invalid = fake("not-a-font-cache.ttf").path; - std::fs::write(&invalid, b"this is not a font").expect("write invalid bytes"); - let truncated = fake("truncated-font-cache.ttf").path; - std::fs::write(&truncated, &include_bytes!("../../../assets/fonts/Inter-Regular.ttf")[..20]).expect("write truncated font"); - for path in [&invalid, &truncated] { - for c in ['日', '本'] { - let file = vec![FontFile { path: path.clone(), family: String::new() }]; - assert!(provider.system_insert_files(file, c).is_none()); - } - } - { - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert_eq!(cache.invalid_fonts.len(), 2, "both invalid paths are remembered"); - assert_eq!(cache.reads, 2, "invalid bytes are read and examined once each"); - assert!(cache.files.is_empty(), "invalid bytes are never retained as a font"); - assert!(cache.failed_reads.is_empty(), "an invalid font is not an I/O failure"); - } - let inter = fake("font.ttf").path; - let file = vec![FontFile { path: inter.clone(), family: String::new() }]; - assert!(provider.system_insert_files(file, '日').is_none(), "Inter does not cover 日"); - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert!(cache.files.iter().any(|file| file.path == inter), "a valid non-covering font is cached"); - assert!(!cache.invalid_fonts.contains(&inter), "a non-covering face is not an invalid font"); - drop(cache); - let file = vec![FontFile { path: inter, family: String::new() }]; - let insert = provider.system_insert_files(file, 'A').expect("the cached valid font still covers A"); - assert!(insert.name.starts_with("craft-system-"), "{insert:?}"); - } - - #[test] - fn pending_scan_recovers_through_real_layout_and_the_lazy_reload() { - PENDING_READY.store(false, std::sync::atomic::Ordering::Relaxed); - let ctx = egui::Context::default(); - let sources = Sources { - locale: (|| Some("zh-Hant-TW".into())) as fn() -> Option, - files: ready_files, - last_resort: Vec::new, - pending: pending_ready, - scripts: no_script_files, - covers: scripts::covering_face, - embedded: no_embedded, - eager_craft_fonts: true, - }; - crate::theme::install_fonts_with(&ctx, sources); - let frame = |ctx: &egui::Context| { - ctx.run_ui(Default::default(), |ui| { - ui.label("龍"); - }) - .textures_delta - .clear(); - }; - frame(&ctx); - assert!(!ctx.fonts_mut(|f| f.has_glyph(&FontId::proportional(12.0), '龍')), "the pending first frame has no Hant face"); - - PENDING_READY.store(true, std::sync::atomic::Ordering::Relaxed); - for _ in 0..4 { - frame(&ctx); - } - assert!(ctx.fonts_mut(|f| f.has_glyph(&FontId::proportional(12.0), '龍')), "the lazy loader's add_font reload recovers after the scan"); - let registered = ctx.fonts(|f| f.definitions().font_data.keys().filter(|name| name.starts_with(FONT_PREFIX)).count()); - assert_eq!(registered, 1, "exactly the Hant file was installed"); - PENDING_READY.store(false, std::sync::atomic::Ordering::Relaxed); - } - - #[test] - fn strict_policy_first_frame_after_the_scan_is_accepted() { - if craft_fonts::CRAFT_FONTS.is_empty() { - eprintln!("skipping: the eager provider is only installed with craft-fonts"); - return; - } - let ctx = egui::Context::default(); - ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Panic); - let sources = Sources { - locale: (|| Some("zh-Hant-TW".into())) as fn() -> Option, - files: ready_hant_files, - last_resort: Vec::new, - pending: || false, - scripts: no_script_files, - covers: scripts::covering_face, - embedded: no_embedded, - eager_craft_fonts: true, - }; - crate::theme::install_fonts_with(&ctx, sources); - ctx.run_ui(Default::default(), |ui| { - ui.label("龍"); - }) - .textures_delta - .clear(); - assert!(ctx.fonts_mut(|f| f.has_glyph(&FontId::proportional(12.0), '龍'))); - } - - /// A strict first frame while Fontconfig is still pending cannot be recovered by the lazy - /// loader: epaint panics during layout before `output_hook` can call `add_font`. The real app - /// uses `MissingGlyphPolicy::Tofu` (brief tofu, then the reload above); strict integration - /// tests such as `camera_raw_localization` must wait for the scan first. This test records - /// that limitation instead of claiming a pending strict startup is accepted. - #[test] - #[should_panic(expected = "No glyph for")] - fn pending_strict_policy_startup_is_not_fake_acceptance() { - let ctx = egui::Context::default(); - ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Panic); - let sources = Sources { - locale: (|| Some("zh-Hant-TW".into())) as fn() -> Option, - files: no_files, - last_resort: Vec::new, - pending: strict_pending, - scripts: no_script_files, - covers: scripts::covering_face, - embedded: no_embedded, - eager_craft_fonts: true, - }; - crate::theme::install_fonts_with(&ctx, sources); - let _ = ctx.run_ui(Default::default(), |ui| { - ui.label("龍"); - }); - } - - #[test] - fn language_change_reloads_eager_faces_through_the_app_context() { - let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { - eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); - return; - }; - let Some(ui_index) = craft_index(ui_font) else { return }; - let Some((sc_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans CJK SC") else { - eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); - return; - }; - let ui_name = format!("craft-font-{ui_index}"); - let sc_name = format!("craft-font-{sc_index}"); - crate::i18n::with_language(crate::i18n::Lang::EN, || { - let ctx = egui::Context::default(); - crate::i18n::sync_context(&ctx, "ja"); - for _ in 0..2 { - ctx.run_ui(Default::default(), |ui| { - ui.label("日"); - }) - .textures_delta - .clear(); - } - let discovered = ctx.fonts(|f| f.discovered_fonts().to_vec()); - assert!(discovered.iter().any(|insert| insert.name == ui_name), "ja discovers {ui_name}: {discovered:?}"); - - crate::i18n::sync_context(&ctx, "zh-hans"); - for _ in 0..2 { - ctx.run_ui(Default::default(), |ui| { - ui.label("日"); - }) - .textures_delta - .clear(); - } - let discovered = ctx.fonts(|f| f.discovered_fonts().to_vec()); - assert!(discovered.iter().any(|insert| insert.name == sc_name), "zh-hans discovers {sc_name}: {discovered:?}"); - assert!(!discovered.iter().any(|insert| insert.name == ui_name), "the language reload clears the old Japanese face: {discovered:?}"); - }); - } - - /// A valid synthetic font whose `glyf` table record extends past the end of the file. Its - /// `cmap` still parses and maps Thai, so a coverage-only check accepts it, but the text - /// engine cannot read every declared table. - fn font_with_out_of_bounds_table() -> Vec { - let mut font = synthetic_font(&[(0x0E01, 0x0E5B)]); - let tables = u16::from_be_bytes([font[4], font[5]]) as usize; - for i in 0..tables { - let rec = 12 + 16 * i; - if font.get(rec..rec + 4) == Some(&b"glyf"[..]) { - font[rec + 12..rec + 16].copy_from_slice(&u32::MAX.to_be_bytes()); - return font; - } - } - panic!("synthetic font has no glyf table"); - } - - /// A readable collection whose selected family face has an out-of-bounds `glyf` table. Face 0 - /// stays readable, and face 1's `cmap`/`name` still work, so a file-level check plus coverage - /// accepts it even though the face cannot be installed safely. - fn collection_with_out_of_bounds_selected_face() -> Vec { - let inter = include_bytes!("../../../assets/fonts/Inter-Regular.ttf"); - let mut jetbrains = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec(); - let tables = u16::from_be_bytes([jetbrains[4], jetbrains[5]]) as usize; - let glyf = (0..tables).map(|i| 12 + 16 * i).find(|&rec| jetbrains.get(rec..rec + 4) == Some(&b"glyf"[..])).expect("JetBrains Mono has a glyf table"); - jetbrains[glyf + 12..glyf + 16].copy_from_slice(&u32::MAX.to_be_bytes()); - two_face_ttc(inter, &jetbrains) - } - - /// A truncated/out-of-bounds table can keep a valid `cmap`, so `load_first` must validate - /// the file before registering it, and must still reach the next, valid candidate. - #[test] - fn lazy_loader_rejects_a_font_with_an_out_of_bounds_table_and_uses_the_next_candidate() { - let malformed = fake_dir().join("out-of-bounds-thai.ttf"); - std::fs::write(&malformed, font_with_out_of_bounds_table()).unwrap(); - let valid = fake_dir().join("thai.ttf"); - let files = vec![FontFile { path: malformed.clone(), family: String::new() }, FontFile { path: valid.clone(), family: String::new() }]; - let bytes = std::fs::read(&malformed).unwrap(); - assert!(scripts::face_covers(&bytes, 0, 'ก'), "the malformed file's cmap still maps the character"); - assert!(!cjk::font_file_is_readable(&bytes), "an out-of-bounds table makes the file unreadable"); - - let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); - let (_, data) = fallback.load_first(&files, 'ก').expect("the valid fallback is reached"); - assert_eq!(fallback.registered.len(), 1); - assert_eq!(fallback.registered[0].1, valid, "the malformed file is skipped, not registered"); - assert_eq!(data.index, 0); - assert_eq!(data.bytes(), std::fs::read(&valid).unwrap().as_slice()); - - // The non-CJK script route must enforce the same validation before registration. - let mut sources = test_sources(|| Some("en".into())); - sources.scripts = |_| vec![fake_dir().join("out-of-bounds-thai.ttf"), fake_dir().join("thai.ttf")]; - let mut fallback = CjkFallback::new(sources); - let (_, data) = fallback.next_script_font('ก').expect("the valid script fallback is reached"); - assert_eq!(fallback.registered.len(), 1); - assert_eq!(fallback.registered[0].1, valid, "the script route also skips the malformed file"); - assert_eq!(data.bytes(), std::fs::read(&valid).unwrap().as_slice()); - - // A readable collection with an unreadable covering face must also skip that face: the - // coverage route selects face 1 by its valid cmap, not the readable face 0. - let collection = fake_dir().join("out-of-bounds-thai.ttc"); - let inter = include_bytes!("../../../assets/fonts/Inter-Regular.ttf"); - let collection_bytes = two_face_ttc(inter, &font_with_out_of_bounds_table()); - std::fs::write(&collection, &collection_bytes).unwrap(); - assert!(cjk::font_file_is_readable(&collection_bytes), "face 0 keeps the collection readable"); - assert_eq!(scripts::covering_face(&collection_bytes, 'ก'), Some(1), "coverage selects the malformed face"); - assert!(!cjk::font_face_is_readable(&collection_bytes, 1)); - let mut sources = test_sources(|| Some("en".into())); - sources.scripts = |_| vec![fake_dir().join("out-of-bounds-thai.ttc"), fake_dir().join("thai.ttf")]; - let mut fallback = CjkFallback::new(sources); - let (_, data) = fallback.next_script_font('ก').expect("the valid script fallback is reached"); - assert_eq!(fallback.registered.len(), 1); - assert_eq!(fallback.registered[0].1, valid, "the coverage route skips the malformed selected face"); - assert_eq!(data.bytes(), std::fs::read(&valid).unwrap().as_slice()); - } - - /// A readable collection may contain one bad face. The selected face (by family name) can - /// keep a valid `cmap` and `name` while another table points outside the file, so checking the - /// file or coverage alone would register a face epaint cannot safely install. Both the lazy - /// loader and the eager provider must skip that face and continue to the valid candidate. - #[test] - fn malformed_selected_collection_face_falls_back_before_lazy_and_provider_registration() { - let path = fake_dir().join("out-of-bounds-selected.ttc"); - let bytes = collection_with_out_of_bounds_selected_face(); - std::fs::write(&path, &bytes).expect("write the synthetic collection"); - assert!(cjk::font_file_is_readable(&bytes), "face 0 keeps the collection readable"); - assert_eq!(cjk::face_index_for_family_checked(&bytes, "JetBrains Mono"), Some(1), "the selected face's name resolves"); - assert!(scripts::face_covers(&bytes, 1, 'A'), "the selected face's cmap covers the character"); - assert!(!cjk::font_face_is_readable(&bytes, 1), "the selected face's glyf table is out of bounds"); - - let valid = fake("font.ttf"); - let candidates = vec![FontFile { path: path.clone(), family: "JetBrains Mono".into() }, FontFile { path: valid.path.clone(), family: String::new() }]; - let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); - let (name, data) = fallback.load_first(&candidates, 'A').expect("the valid alternative is reached"); - assert_eq!(data.index, 0, "the lazy loader registers the valid face 0, not the malformed selected face"); - assert_eq!(fallback.registered.len(), 1); - assert_eq!(fallback.registered[0].1, valid.path, "the malformed collection is not registered"); - - let provider = CraftFontProvider::new(&test_sources(|| Some("en".into())), 1.0); - let insert = provider.system_insert_files(candidates, 'A').expect("the provider reaches the valid alternative"); - assert_eq!(insert.data.index, 0, "the provider does not hand the malformed selected face to epaint"); - assert!(insert.name.starts_with("craft-system-"), "{insert:?}"); - - // Installing the selected font under the strict policy must not panic: only the valid - // fallback reaches egui's family builder. - let ctx = egui::Context::default(); - ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Panic); - crate::theme::install_fonts(&ctx); - // The lazy loader runs after a frame; initialize the font view before matching that path. - ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); - add_to_all_families(&ctx, name, data); - ctx.run_ui(Default::default(), |ui| { - ui.label("A"); - }) - .textures_delta - .clear(); - } - - #[test] - fn lazy_loader_uses_the_requested_collection_family_and_checks_coverage() { - let path = fake_dir().join("families.ttc"); - let file = |family: &str| vec![FontFile { path: path.clone(), family: family.into() }]; - - let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); - let (_, data) = fallback.load_first(&file("JetBrains Mono"), 'A').expect("face 1 covers A"); - assert_eq!(data.index, 1); - - let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); - assert!(fallback.load_first(&file("JetBrains Mono"), 'ƀ').is_none(), "coverage is checked on the requested face"); - - let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); - let empty_family = vec![FontFile { path: path.clone(), family: String::new() }]; - let (_, data) = fallback.load_first(&empty_family, 'ƀ').expect("empty family is face 0"); - assert_eq!(data.index, 0); - } - - fn always_thai_candidate(_: Script) -> Vec { - vec![fake_dir().join("thai.ttf")] - } - - /// A path already registered through either route is not read or registered a second time. - #[test] - fn lazy_loader_registers_each_loaded_font_once() { - let valid = fake("font.ttf"); - let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); - let files = vec![valid.clone()]; - fallback.load_first(&files, 'A').expect("the font covers Latin A"); - assert!(fallback.load_first(&files, 'A').is_none(), "a second request for the loaded file registers nothing"); - assert_eq!(fallback.registered.len(), 1); - - let sources = Sources { scripts: always_thai_candidate, ..test_sources(|| Some("en".into())) }; - let mut fallback = CjkFallback::new(sources); - fallback.loaded.push(fake_dir().join("thai.ttf")); - assert!(fallback.next_script_font('ก').is_none(), "the script route skips a file the other route already loaded"); - assert!(fallback.registered.is_empty()); - assert_eq!(fallback.scripts_tried, vec![Script::Thai], "the script is still marked tried only once"); - } - - /// A craft face is registered once: a later request for the same embedded file must not add - /// another font with a new name and a duplicate blob. - #[test] - fn lazy_loader_registers_an_embedded_craft_face_once() { - if baseline_face('あ').is_none() { - eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); - return; - } - let mut fallback = CjkFallback::new(craft_only(|| Some("en".into()))); - fallback.load_embedded(CjkScript::Japanese, 'あ').expect("the manifest covers kana"); - assert!(fallback.load_embedded(CjkScript::Japanese, 'あ').is_none(), "the same embedded face is not registered twice"); - assert_eq!(fallback.registered.len(), 1); - assert_eq!(fallback.loaded.len(), 1); - } - - #[test] - fn provider_uses_system_script_candidates_and_last_resort_for_non_cjk() { - let sources = Sources { - locale: || Some("en".into()), - files: no_files, - last_resort: || vec![FontFile { path: fake_dir().join("ethiopic.ttf"), family: String::new() }], - pending: || false, - scripts: |s| match s { - Script::Tamil => vec![fake_dir().join("tamil.ttf")], - _ => Vec::new(), - }, - covers: scripts::covering_face, - embedded: no_embedded, - eager_craft_fonts: false, - }; - let provider = CraftFontProvider::new(&sources, 1.0); - let tamil = provided(&provider, 'த').expect("Tamil system candidate"); - assert!(tamil.starts_with("craft-system-"), "{tamil}"); - let ethiopic = provided(&provider, 'ሀ').expect("last-resort face"); - assert!(ethiopic.starts_with("craft-system-"), "{ethiopic}"); - } - - static PROVIDER_SCRIPT_CALLS: Mutex> = Mutex::new(Vec::new()); - - fn recorded_provider_files(script: CjkScript) -> Vec { - PROVIDER_SCRIPT_CALLS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(script); - Vec::new() - } - - /// A Hangul character's preferred script is the locale order's first script, so the provider - /// builds a list with Korean twice. It must still ask for Korean's files once, then try each - /// remaining script once, not restart the preferred script after a miss. - #[test] - fn provider_tries_each_script_once_when_the_preferred_script_repeats_the_order() { - PROVIDER_SCRIPT_CALLS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clear(); - let sources = Sources { - locale: || Some("ko_KR".into()), - files: recorded_provider_files, - last_resort: Vec::new, - pending: || false, - scripts: no_script_files, - covers: scripts::covering_face, - embedded: no_embedded, - eager_craft_fonts: false, - }; - let provider = CraftFontProvider::new(&sources, 1.0); - assert!(provided(&provider, '한').is_none(), "the test source has no Hangul face"); - let calls = PROVIDER_SCRIPT_CALLS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); - assert_eq!(calls, vec![CjkScript::Korean, CjkScript::TraditionalChinese, CjkScript::SimplifiedChinese, CjkScript::Japanese]); - } - - /// An unclassified symbol (not CJK, not one of the non-CJK scripts) only has the optional - /// craft `Zsym` face. Without one the provider must return missing rather than read unrelated - /// system fonts, and an empty cluster is likewise no request at all. - #[test] - fn provider_missing_symbol_and_empty_cluster_do_not_touch_system_fonts() { - let sources = Sources { embedded: no_embedded, ..test_sources(|| Some("en".into())) }; - let provider = CraftFontProvider::new(&sources, 1.0); - assert!(provider.font_for(&FallbackRequest { cluster: "", family: &FontFamily::Proportional }).is_none()); - assert!(provided(&provider, '☃').is_none(), "no injected Zsym craft face covers the symbol"); - let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - assert_eq!(cache.reads, 0, "a symbol is not a CJK or script fallback request"); - assert!(cache.failed_reads.is_empty() && cache.invalid_fonts.is_empty()); - } - - #[test] - fn provider_applies_the_current_scale_to_craft_faces() { - if baseline_face('あ').is_none() { - eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); - return; - } - let provider = test_provider(|| Some("en".into())); - let first = provided_insert(&provider, 'あ').expect("the craft manifest covers kana"); - assert_eq!(first.data.tweak.scale, 1.0); - assert!(first.families.iter().any(|f| f.family == FontFamily::Proportional)); - assert!(first.families.iter().any(|f| f.family == FontFamily::Monospace)); - provider.set_scale(4.0 / 3.0); - let second = provided_insert(&provider, 'あ').expect("the craft face is resolved again at the current scale"); - assert_eq!(second.data.tweak.scale, 4.0 / 3.0, "a craft face must not bake in the scale of an earlier pass"); - } - - /// Face-name metadata is capped independently of the retained-blob budget: forgetting the - /// oldest name only makes egui install that face under a later name, it never drops bytes - /// from a file that still fits. - #[test] - fn system_face_names_are_bounded_independently_of_font_blobs() { - let mut cache = SystemCache::default(); - for i in 0..MAX_SYSTEM_FACE_NAMES + 4 { - cache.remember_face(PathBuf::from(format!("face-{i}.ttf")), i as u32, format!("craft-system-{i}")); - } - assert_eq!(cache.faces.len(), MAX_SYSTEM_FACE_NAMES); - assert_eq!(cache.faces.first().map(|face| face.name.as_str()), Some("craft-system-4"), "the oldest names are evicted first"); - assert_eq!(cache.faces.last().map(|face| face.name.as_str()), Some("craft-system-1027")); - assert!(cache.files.is_empty() && cache.retained_bytes == 0, "face names do not retain or charge font bytes"); - } - - #[test] - fn pending_fontconfig_defers_the_last_resort_instead_of_returning_none_forever() { - PENDING_LAST_RESORT.store(true, std::sync::atomic::Ordering::Relaxed); - let sources = Sources { - locale: || Some("zh-Hant-TW".into()), - files: no_files, - last_resort: || vec![FontFile { path: fake_dir().join("hant.ttf"), family: String::new() }], - pending: pending_last_resort, - scripts: no_script_files, - covers: scripts::covering_face, - embedded: no_embedded, - eager_craft_fonts: false, - }; - let provider = CraftFontProvider::new(&sources, 1.0); - assert!(provided(&provider, '龍').is_none(), "pending Hant scan must not fall through to a last resort"); - PENDING_LAST_RESORT.store(false, std::sync::atomic::Ordering::Relaxed); - let got = provided(&provider, '龍').expect("after the scan the last resort is usable"); - assert!(got.starts_with("craft-system-"), "{got}"); - } - - #[test] - fn pending_fontconfig_does_not_cache_the_lower_priority_sc_craft_face_for_hant() { - let Some((sc_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans CJK SC") else { - eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); - return; - }; - PENDING_CRAFT_SC.store(true, std::sync::atomic::Ordering::Relaxed); - let sources = Sources { - locale: || Some("zh-Hant-TW".into()), - files: no_files, - last_resort: Vec::new, - pending: pending_craft_sc, - scripts: no_script_files, - covers: scripts::covering_face, - embedded: craft_embedded_iso, - eager_craft_fonts: false, - }; - let provider = CraftFontProvider::new(&sources, 1.0); - assert!(provided(&provider, '龍').is_none(), "a pending Hant scan must not return (and cache) the lower-priority SC craft face"); - PENDING_CRAFT_SC.store(false, std::sync::atomic::Ordering::Relaxed); - let expected = format!("craft-font-{sc_index}"); - assert_eq!(provided(&provider, '龍').as_deref(), Some(expected.as_str())); - } - - #[test] - fn every_craft_face_is_available_to_both_ui_families() { - let mut checked = 0; - for (i, face) in craft_fonts::CRAFT_FONTS.iter().enumerate() { - if face.bytes.is_empty() { - continue; - } - let insert = craft_insert(i, face, 1.0); - assert_eq!(insert.name, format!("craft-font-{i}")); - assert!(insert.families.iter().any(|f| f.family == FontFamily::Proportional), "{} is missing from Proportional", face.family); - assert!(insert.families.iter().any(|f| f.family == FontFamily::Monospace), "{} is missing from Monospace", face.family); - checked += 1; - } - if checked == 0 { - eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); - } - } - - #[test] - fn the_craft_provider_shapes_the_first_headless_frame_in_both_families() { - let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { - eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); - return; - }; - let Some(ui_index) = craft_index(ui_font) else { return }; - let Some((sc_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans CJK SC") else { - eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); - return; - }; - let Some((korean_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "NanumGothic") else { - eprintln!("skipping: the craft-fonts manifest has no Korean face"); - return; - }; - let Some((arabic_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans Arabic") else { - eprintln!("skipping: the craft-fonts manifest has no Arabic face"); - return; - }; - let Some((devanagari_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans Devanagari") else { - eprintln!("skipping: the craft-fonts manifest has no Devanagari face"); - return; - }; - let Some(baseline_kana) = baseline_face('か') else { return }; - let Some(baseline_han) = baseline_face('日') else { return }; - let baseline_kana_index = craft_index(baseline_kana).expect("a manifest face has an index"); - let baseline_han_index = craft_index(baseline_han).expect("a manifest face has an index"); - for (locale, text, expected) in [ - ((|| Some("ja_JP".into())) as fn() -> Option, "かな", ui_index), - ((|| Some("en_US".into())) as fn() -> Option, "かな", baseline_kana_index), - ((|| Some("en_US".into())) as fn() -> Option, "日本", baseline_han_index), - ((|| None) as fn() -> Option, "日本", baseline_han_index), - ((|| Some("en_US".into())) as fn() -> Option, "한", korean_index), - ((|| Some("en_US".into())) as fn() -> Option, "مرحبا", arabic_index), - ((|| Some("en_US".into())) as fn() -> Option, "नमस्ते", devanagari_index), - ((|| Some("zh-Hant-TW".into())) as fn() -> Option, "かな", ui_index), - ((|| Some("zh-Hant-TW".into())) as fn() -> Option, "龍", sc_index), - ((|| Some("zh-CN".into())) as fn() -> Option, "中文", sc_index), - ] { - let ctx = egui::Context::default(); - crate::theme::install_fonts_with(&ctx, eager_sources(locale)); - ctx.run_ui(Default::default(), |ui| { - ui.label(text); - ui.label(egui::RichText::new(text).monospace()); - }) - .textures_delta - .clear(); - assert!(ctx.fonts_mut(|f| f.has_glyphs(&FontId::monospace(12.0), text)), "{text} is missing from Monospace"); - let discovered = ctx.fonts(|f| f.discovered_fonts().to_vec()); - assert!( - discovered.iter().any(|insert| insert.name == format!("craft-font-{expected}")), - "{text}: expected craft-font-{expected}, discovered {discovered:?}" - ); - for insert in &discovered { - assert!(insert.families.iter().any(|f| f.family == FontFamily::Proportional), "{insert:?}"); - assert!(insert.families.iter().any(|f| f.family == FontFamily::Monospace), "{insert:?}"); - } - } - // A Traditional Chinese locale has no Hant craft face. A system Hant file, when present, - // must be read before the Simplified Chinese craft fallback. - if hant_system_file().is_some() { - let mut sources = eager_sources((|| Some("zh-Hant-TW".into())) as fn() -> Option); - sources.files = hant_files; - let ctx = egui::Context::default(); - crate::theme::install_fonts_with(&ctx, sources); - ctx.run_ui(Default::default(), |ui| { - ui.label("龍"); - }) - .textures_delta - .clear(); - let discovered = ctx.fonts(|f| f.discovered_fonts().to_vec()); - assert!(discovered.iter().any(|insert| insert.name.starts_with("craft-system-")), "the system Hant face draws the first frame: {discovered:?}"); - assert!( - !discovered.iter().any(|insert| insert.name == format!("craft-font-{sc_index}")), - "the Simplified Chinese face must not pre-empt the Hant system font: {discovered:?}" - ); - } - } - - #[test] - fn ui_works_without_craft_fonts() { - // The pre-craft-fonts behaviour: no embedded fonts, no system fonts. Latin renders, - // Japanese is tried (and stays missing) without panicking, and the loader exhausts. - let ctx = egui::Context::default(); - crate::theme::install_fonts_with( - &ctx, - Sources { - locale: || None, - files: |_| vec![], - last_resort: Vec::new, - pending: || false, - scripts: |_| Vec::new(), - covers: scripts::covering_face, - embedded: no_embedded, - eager_craft_fonts: false, - }, - ); - assert!(render(&ctx, "Layer 1 – café")); - assert!(!render(&ctx, "日本語の文字")); - let n = ctx.fonts(|f| f.definitions().font_data.keys().filter(|k| k.starts_with(FONT_PREFIX)).count()); - assert_eq!(n, 0); - if craft_fonts::CRAFT_FONTS.is_empty() { - assert!(craft_embedded(CjkScript::Japanese).is_empty()); - } - } - - /// With the real system fonts, every CJK sample renders (skipped per script when the - /// machine has no font for it, e.g. CI Linux without Noto CJK). - #[test] - fn system_fonts_cover_cjk_samples() { - #[cfg(target_os = "linux")] - assert!(wait_for_fontconfig_cjk_scan(), "Fontconfig CJK lookup did not finish within 10 seconds"); - let available = |s: CjkScript| cjk::font_files(s).iter().any(|f| f.path.is_file()); - let samples = [ - ("图层", CjkScript::SimplifiedChinese), - ("圖層", CjkScript::TraditionalChinese), - ("카드 배경", CjkScript::Korean), - ("レイヤー", CjkScript::Japanese), - ]; - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - for (text, script) in samples { - if !available(script) { - eprintln!("skipping {text}: no {script:?} system font"); - continue; - } - assert!(render(&ctx, text), "{text} still has missing glyphs"); - } - // All at once in a fresh context too (several scripts in one frame). - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let all: String = samples.iter().filter(|(_, s)| available(*s)).map(|(t, _)| *t).collect::>().join(" "); - assert!(render(&ctx, &all), "{all}"); - } -} +mod tests; diff --git a/crates/ui-egui/src/cjk_fonts/tests.rs b/crates/ui-egui/src/cjk_fonts/tests.rs new file mode 100644 index 0000000000..863b465453 --- /dev/null +++ b/crates/ui-egui/src/cjk_fonts/tests.rs @@ -0,0 +1,1917 @@ +use super::*; +use egui::FontProvider; +use std::sync::Mutex; + +#[test] +fn lazy_fallbacks_follow_ui_font_size_and_survive_size_changes() { + use photocraft_engine::prefs::UiFontSize; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); + crate::theme::set_ui_font_size(&ctx, UiFontSize::Large); + let name = "test-lazy-fallback".to_string(); + add_to_all_families(&ctx, name.clone(), FontData::from_static(photocraft_text::fonts::INTER_REGULAR.as_slice())); + for (size, scale) in [(UiFontSize::Large, 16.0 / 12.0), (UiFontSize::Tiny, 10.0 / 12.0), (UiFontSize::Small, 1.0)] { + crate::theme::set_ui_font_size(&ctx, size); + for _ in 0..2 { + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); + } + let fonts = ctx.fonts(|f| f.definitions().clone()); + let fallback = fonts.font_data.get(&name).unwrap(); + assert_eq!(fallback.tweak.scale, scale); + assert_eq!(fallback.tweak.y_offset_factor, 0.0, "same face as Inter keeps its baseline"); + for stack in fonts.families.values() { + assert_eq!(stack.iter().filter(|n| *n == &name).count(), 1); + assert_eq!(stack.last(), Some(&name), "fallback stays at the lowest priority"); + } + } +} + +/// A face discovered by [`CraftFontProvider`] during a pass that also changes Interface > UI +/// Font Size must use the scale of the definitions active in that pass. The size plugin moves +/// the provider to the new scale only after `ctx.set_fonts` queued the rescaled definitions; +/// updating the provider in `set_ui_font_size` would put the new scale on a face laid out +/// with the old stack. +#[test] +fn discovered_faces_use_the_scale_of_the_definitions_they_were_laid_out_with() { + use photocraft_engine::prefs::UiFontSize; + fn thai_reader(_: &std::path::Path) -> Option> { + Some(synthetic_font(&[(0x0E01, 0x0E5B)])) + } + let ctx = egui::Context::default(); + crate::theme::install_fonts_with(&ctx, craft_only(|| None)); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); + let mut provider = CraftFontProvider::new( + &Sources { + locale: || Some("en".into()), + files: no_files, + last_resort: Vec::new, + pending: || false, + scripts: |script| if script == Script::Thai { vec![PathBuf::from("synthetic-thai.ttf")] } else { Vec::new() }, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: false, + }, + 1.0, + ); + provider.reader = thai_reader; + let provider = std::sync::Arc::new(provider); + ctx.data_mut(|d| d.insert_temp(craft_provider_id(), provider.clone())); + let as_provider: std::sync::Arc = provider.clone(); + ctx.set_font_providers(vec![as_provider]); + + // The scale of the configured Inter face (part of `FontDefinitions`) and of the face the + // provider discovered for Thai. + let inter_scale = |ctx: &egui::Context| -> Option { ctx.fonts(|f| f.definitions().font_data.get("Inter").map(|data| data.tweak.scale)) }; + let thai_scale = |ctx: &egui::Context| -> Option { + ctx.fonts(|f| f.discovered_fonts().iter().find(|insert| insert.name.starts_with("craft-system-")).map(|insert| insert.data.tweak.scale)) + }; + // A frame that checks the state during the change pass, before laying out Thai (the + // character that makes the provider discover a face). + let frame = |check: &dyn Fn(&egui::Context)| { + ctx.run_ui(Default::default(), |ui| { + check(&ctx); + ui.label("ก"); + }) + .textures_delta + .clear(); + }; + // Small (the install default) is active. Walk Small -> Large -> Small, repeat Large + // (the same size must leave both the definitions and the provider alone, not accumulate) + // and back to Small. + assert_eq!(provider.scale(), 1.0); + for (size, want, same_size) in [ + (UiFontSize::Large, 16.0 / 12.0, false), + (UiFontSize::Small, 1.0, false), + (UiFontSize::Large, 16.0 / 12.0, false), + (UiFontSize::Large, 16.0 / 12.0, true), + (UiFontSize::Small, 1.0, false), + ] { + let old = provider.scale(); + let inter_before = inter_scale(&ctx); + crate::theme::set_ui_font_size(&ctx, size); + assert_eq!(provider.scale(), old, "the provider follows the definitions still active in this pass"); + frame(&|ctx: &egui::Context| { + assert_eq!(inter_scale(ctx), inter_before, "the configured Inter keeps its old scale during the change pass"); + assert_eq!(provider.scale(), old, "the provider does not move before the pass ends"); + }); + assert_eq!(provider.scale(), want, "the provider follows the rescaled definitions"); + if same_size { + assert_eq!(inter_scale(&ctx), inter_before, "a same-size request leaves the stack alone"); + } + assert_eq!(thai_scale(&ctx), Some(old), "the pass laid the discovered face out with the old definitions"); + // The queued definitions with the new scale are active now, and a new pass drops the + // discovered face and rediscovers it at the provider's new scale. + frame(&|ctx: &egui::Context| { + assert_eq!(inter_scale(ctx), Some(want), "the rescaled stack is active in the next pass"); + assert_eq!(provider.scale(), want); + }); + assert_eq!(thai_scale(&ctx), Some(want), "the next pass rediscovers the face at the provider's scale"); + } +} + +/// A font holding only an `fvar` table with the given axes (tag, min, default, max), as a +/// single face or as face 1 of a two-face collection. +fn fvar_font(axes: &[(&[u8; 4], f32, f32, f32)], collection: bool) -> Vec { + let fixed = |v: f32| ((v * 65536.0) as i32).to_be_bytes(); + let mut fvar = Vec::new(); + for x in [1u16, 0, 16, 2, axes.len() as u16, 20, 0, 0] { + fvar.extend(x.to_be_bytes()); + } + for (tag, min, def, max) in axes { + fvar.extend(*tag); + for v in [*min, *def, *max] { + fvar.extend(fixed(v)); + } + fvar.extend([0, 0, 1, 0]); + } + let face = |at: u32| { + let mut d = vec![0, 1, 0, 0, 0, 1, 0, 16, 0, 0, 0, 0]; + d.extend(b"fvar"); + d.extend([0; 4]); + d.extend(at.to_be_bytes()); + d.extend((fvar.len() as u32).to_be_bytes()); + d + }; + if !collection { + let mut f = face(28); + f.extend(&fvar); + return f; + } + // ttcf header (12 + 2×4), two 28-byte directories, then the shared table. + let mut f = b"ttcf".to_vec(); + f.extend([0, 1, 0, 0, 0, 0, 0, 2]); + f.extend(20u32.to_be_bytes()); + f.extend(48u32.to_be_bytes()); + f.extend(face(76)); + f.extend(face(76)); + f.extend(&fvar); + f +} + +/// #4820: Noto Sans CJK's variable collection defaults to Thin; the fallback asks for Regular. +#[test] +fn variable_fallbacks_are_drawn_at_regular_weight() { + let thin = fvar_font(&[(b"wght", 100.0, 100.0, 900.0)], true); + assert_eq!(regular_weight(&thin, 1), Some(400.0), "Noto Sans CJK VF, face 1 of a collection"); + assert_eq!(regular_weight(&fvar_font(&[(b"wdth", 75.0, 100.0, 100.0), (b"wght", 100.0, 100.0, 900.0)], false), 0), Some(400.0)); + assert_eq!(regular_weight(&fvar_font(&[(b"wght", 500.0, 600.0, 900.0)], false), 0), Some(500.0), "Regular clamped into the axis"); + assert_eq!(regular_weight(&fvar_font(&[(b"wght", 100.0, 400.0, 900.0)], false), 0), None, "already Regular"); + assert_eq!(regular_weight(&fvar_font(&[(b"wdth", 75.0, 100.0, 100.0)], false), 0), None, "no weight axis"); + assert_eq!(regular_weight(photocraft_text::fonts::INTER_REGULAR.as_slice(), 0), None, "static font"); + for bad in [&thin[..thin.len() - 9], &thin[..30], &b"ttcf"[..], &[][..]] { + assert_eq!(regular_weight(bad, 1), None); + } + // Registered as a fallback, a static face keeps the default (no variation) coordinates. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); + add_to_all_families(&ctx, "test-static".into(), FontData::from_static(photocraft_text::fonts::INTER_REGULAR.as_slice())); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); + let fonts = ctx.fonts(|f| f.definitions().clone()); + assert_eq!(fonts.font_data.get("test-static").map(|d| d.tweak.coords.clone()), Some(Default::default())); +} + +/// A corrupt or non-font blob has no `hhea`, `head` or `fvar` table: the fallback tweaks +/// must leave it untouched rather than deriving a baseline or weight from garbage. +#[test] +fn font_tweaks_ignore_bytes_without_metrics_or_weight_axes() { + let mut data = FontData::from_static(b""); + apply_font_tweaks(&mut data); + assert_eq!(data.tweak.y_offset_factor, 0.0); + assert_eq!(data.tweak.coords, Default::default()); +} + +static DIR: Mutex> = Mutex::new(None); + +#[test] +fn changing_language_resets_the_loader_once_and_reorders_scripts() { + crate::i18n::with_language(crate::i18n::Lang::EN, || { + let ctx = egui::Context::default(); + crate::i18n::sync_context(&ctx, "ja"); + ctx.with_plugin::(|plugin| { + assert_eq!(plugin.0.order()[0], CjkScript::Japanese); + plugin.0.tried = plugin.0.order().to_vec(); + plugin.0.last_resort_tried = true; + }) + .expect("font plugin"); + crate::i18n::sync_context(&ctx, "ja"); + assert!(ctx.with_plugin::(|plugin| plugin.0.exhausted()).expect("font plugin"), "idle frames must not reload fonts"); + crate::i18n::sync_context(&ctx, "ko"); + ctx.with_plugin::(|plugin| { + assert!(!plugin.0.exhausted()); + assert_eq!(plugin.0.order()[0], CjkScript::Korean); + }) + .expect("font plugin"); + }); +} + +fn fake_dir() -> PathBuf { + let mut g = DIR.lock().unwrap(); + g.get_or_insert_with(|| { + let dir = std::env::temp_dir().join(format!("photocraft-cjk-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("font.ttf"), include_bytes!("../../../../assets/fonts/Inter-Regular.ttf")).unwrap(); + std::fs::write(dir.join("empty.ttf"), b"").unwrap(); + std::fs::write(dir.join("thai.ttf"), synthetic_font(&[(0x0E01, 0x0E5B)])).unwrap(); + std::fs::write(dir.join("arabic.ttf"), synthetic_font(&[(0x0600, 0x06FF)])).unwrap(); + std::fs::write(dir.join("devanagari.ttf"), synthetic_font(&[(0x0900, 0x097F)])).unwrap(); + std::fs::write(dir.join("korean.ttf"), synthetic_font(&[(0xCE74, 0xCE74)])).unwrap(); + std::fs::write(dir.join("tamil.ttf"), synthetic_font(&[(0x0B80, 0x0BFF)])).unwrap(); + std::fs::write(dir.join("ethiopic.ttf"), synthetic_font(&[(0x1200, 0x137F)])).unwrap(); + std::fs::write(dir.join("hant.ttf"), synthetic_font(&[(0x9F8D, 0x9F8D)])).unwrap(); + std::fs::write( + dir.join("families.ttc"), + two_face_ttc(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"), include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf")), + ) + .unwrap(); + dir + }) + .clone() +} + +fn fake(name: &str) -> FontFile { + FontFile { path: fake_dir().join(name), family: String::new() } +} + +#[test] +fn font_reads_skip_missing_empty_oversized_and_non_file_candidates() { + let dir = fake_dir(); + assert!(read_font(&dir.join("missing-read-test.ttf")).is_none(), "a missing path is skipped"); + assert!(read_font(&dir).is_none(), "a directory is not a font file"); + assert!(read_font(&dir.join("empty.ttf")).is_none(), "an empty file is skipped"); + + let oversized = dir.join("oversized-read-test.ttf"); + let file = std::fs::File::create(&oversized).expect("create a sparse oversized test file"); + file.set_len(MAX_FONT_BYTES + 1).expect("set the sparse file size"); + drop(file); + assert!(read_font(&oversized).is_none(), "an oversized file is not read"); + std::fs::remove_file(&oversized).expect("remove the sparse test file"); + + let valid = dir.join("font.ttf"); + assert_eq!(read_font(&valid).expect("the valid font is read").as_slice(), std::fs::read(&valid).expect("test font bytes").as_slice()); +} + +fn provider_corrupt_thai_candidates(script: Script) -> Vec { + if script == Script::Thai { + vec![ + fake_dir().join("provider-missing-thai.ttf"), + fake_dir().join("provider-corrupt-thai.ttf"), + fake_dir().join("provider-corrupt-selected-thai.ttc"), + fake_dir().join("font.ttf"), + fake_dir().join("thai.ttf"), + ] + } else { + Vec::new() + } +} + +fn provider_missing_thai_candidate(script: Script) -> Vec { + if script == Script::Thai { vec![fake_dir().join("provider-only-missing-thai.ttf")] } else { Vec::new() } +} + +/// The provider's non-CJK script route must reject a structurally invalid file, a readable +/// collection whose selected covering face is unreadable, and a missing file, then use the +/// next real candidate. The rejected and missing paths stay negative-cached. +#[test] +fn provider_skips_missing_and_corrupt_script_candidates_before_registering() { + let malformed = fake_dir().join("provider-corrupt-thai.ttf"); + let collection = fake_dir().join("provider-corrupt-selected-thai.ttc"); + std::fs::write(&malformed, font_with_out_of_bounds_table()).expect("write the malformed test font"); + std::fs::write(&collection, two_face_ttc(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"), &font_with_out_of_bounds_table())) + .expect("write the malformed selected-face collection"); + + let sources = Sources { + locale: || Some("en".into()), + files: no_files, + last_resort: Vec::new, + pending: || false, + scripts: provider_corrupt_thai_candidates, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: false, + }; + let provider = CraftFontProvider::new(&sources, 1.0); + let insert = provided_insert(&provider, 'ก').expect("the valid Thai candidate is reached"); + assert_eq!(insert.data.index, 0); + assert_eq!(insert.data.bytes(), std::fs::read(fake_dir().join("thai.ttf")).expect("Thai test font").as_slice()); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert!(cache.failed_reads.contains(&fake_dir().join("provider-missing-thai.ttf")), "the missing file is remembered"); + assert!(cache.invalid_fonts.contains(&malformed), "the readable non-font is remembered as invalid"); + assert!(cache.files.iter().any(|file| file.path == collection), "the readable collection is retained for its other faces"); + drop(cache); + + let missing_only = Sources { scripts: provider_missing_thai_candidate, ..sources }; + let provider = CraftFontProvider::new(&missing_only, 1.0); + assert!(provided(&provider, 'ก').is_none(), "no readable script candidate leaves the character missing"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.failed_reads.len(), 1); + assert_eq!(cache.reads, 0); +} + +fn fake_sources(locale: fn() -> Option) -> Sources { + Sources { + locale, + // Korean has a readable Hangul font, Japanese only broken files, Chinese none. + files: |s| match s { + CjkScript::Korean => vec![fake("missing.ttc"), fake("empty.ttf"), fake("korean.ttf")], + CjkScript::Japanese => vec![fake("empty.ttf")], + _ => vec![], + }, + last_resort: || vec![fake("font.ttf")], + pending: || false, + scripts: |_| Vec::new(), + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: false, + } +} + +#[test] +fn picks_preferred_script_skips_unreadable_and_exhausts() { + let mut fb = CjkFallback::new(fake_sources(|| Some("en_US".into()))); + assert!(!fb.exhausted()); + // Hangul: Korean first; missing and empty files are skipped. + let (name, data) = fb.next_font('카', CjkChar::Hangul).expect("korean font"); + assert!(name.starts_with(FONT_PREFIX)); + assert_eq!(data.index, 0); + assert_eq!(fb.tried, vec![CjkScript::Korean]); + // Han on an English locale: system fallback keeps the locale order (SC first); the + // Japanese-first craft-manifest baseline is a separate provider/lazy-craft path. + // SC, TC, JA have nothing readable here, and the last-resort file was already loaded, + // so nothing new; everything is now tried. + assert!(fb.next_font('日', CjkChar::Han).is_none()); + assert!(fb.exhausted()); + assert_eq!(fb.tried, vec![CjkScript::Korean, CjkScript::SimplifiedChinese, CjkScript::TraditionalChinese, CjkScript::Japanese]); + assert_eq!(fb.registered.len(), 1, "a file is read at most once"); + assert!(fb.next_font('あ', CjkChar::Kana).is_none()); +} + +#[test] +fn han_follows_locale() { + for (loc, first) in [ + ("ja_JP.UTF-8", CjkScript::Japanese), + ("zh-Hans-CN", CjkScript::SimplifiedChinese), + ("zh-Hant-TW", CjkScript::TraditionalChinese), + ("ko_KR", CjkScript::Korean), + ] { + let mut fb = CjkFallback::new(Sources { + locale: || None, + files: |_| vec![], + last_resort: Vec::new, + pending: || false, + scripts: |_| Vec::new(), + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: false, + }); + fb.order = Some(cjk::script_order(Some(loc))); + assert!(fb.next_font('日', CjkChar::Han).is_none()); + assert_eq!(fb.tried[0], first, "{loc}"); + } +} + +/// Runs frames showing `text` until fonts settle; returns whether every glyph is covered. +fn render(ctx: &egui::Context, text: &str) -> bool { + for _ in 0..12 { + let mut out = ctx.run_ui(Default::default(), |ui| { + ui.label(text); + }); + out.textures_delta.clear(); + } + ctx.fonts_mut(|f| f.has_glyphs(&FontId::proportional(12.0), &text.replace(' ', ""))) +} + +/// A two-face TrueType collection built at runtime from the repository's OFL-licensed +/// Inter and JetBrains Mono files. Each face directory is rewritten with offsets relative to +/// the collection, so no font fixture is committed. +fn two_face_ttc(first: &[u8], second: &[u8]) -> Vec { + let font_count = 2usize; + let tables = |font: &[u8]| u16::from_be_bytes([font[4], font[5]]) as usize; + let dir_lengths = [12 + 16 * tables(first), 12 + 16 * tables(second)]; + let mut dir_offsets = Vec::with_capacity(font_count); + let mut cursor = 12 + 4 * font_count; + for length in dir_lengths { + dir_offsets.push(cursor); + cursor += length; + } + let data_start = cursor.next_multiple_of(4); + let mut bases = Vec::with_capacity(font_count); + let mut total = data_start; + for font in [first, second] { + bases.push(total); + total += font.len().next_multiple_of(4); + } + let mut out = vec![0u8; total]; + out[..4].copy_from_slice(b"ttcf"); + out[4..8].copy_from_slice(&0x0001_0000u32.to_be_bytes()); + out[8..12].copy_from_slice(&u32::try_from(font_count).expect("two faces").to_be_bytes()); + for (i, offset) in dir_offsets.iter().enumerate() { + let at = 12 + i * 4; + out[at..at + 4].copy_from_slice(&u32::try_from(*offset).expect("collection fits").to_be_bytes()); + } + for (i, font) in [first, second].into_iter().enumerate() { + let dir = dir_offsets[i]; + let base = bases[i]; + out[dir..dir + 12].copy_from_slice(&font[..12]); + for record in 0..tables(font) { + let src = 12 + 16 * record; + let dst = dir + 12 + 16 * record; + out[dst..dst + 8].copy_from_slice(&font[src..src + 8]); + let table_offset = u32::from_be_bytes(font[src + 8..src + 12].try_into().expect("four bytes")); + let collection_offset = u32::try_from(base).expect("collection fits") + table_offset; + out[dst + 8..dst + 12].copy_from_slice(&collection_offset.to_be_bytes()); + out[dst + 12..dst + 16].copy_from_slice(&font[src + 12..src + 16]); + } + out[base..base + font.len()].copy_from_slice(font); + } + out +} + +/// A minimal TrueType font mapping the `ranges` (inclusive) to box glyphs, so tests have a +/// font for a script without committing font files. +fn synthetic_font(ranges: &[(u32, u32)]) -> Vec { + let be16 = |v: &mut Vec, x: i32| v.extend((x as u16).to_be_bytes()); + let be32 = |v: &mut Vec, x: u32| v.extend(x.to_be_bytes()); + let chars: u32 = ranges.iter().map(|(a, b)| b - a + 1).sum(); + let glyphs = chars as i32 + 1; + // One 500x700 box (contour of four on-curve points); glyph 0 (.notdef) is empty. + let mut boxed = Vec::new(); + for x in [1, 50, 0, 550, 700, 3, 0] { + be16(&mut boxed, x); + } + boxed.extend([1u8; 4]); + for x in [50, 0, 500, 0, 0, 700, 0, -700] { + be16(&mut boxed, x); + } + boxed.extend([0, 0]); + let glyf: Vec = boxed.repeat(chars as usize); + let mut loca = Vec::new(); + be32(&mut loca, 0); + for i in 0..chars { + be32(&mut loca, i * boxed.len() as u32); + } + be32(&mut loca, chars * boxed.len() as u32); + let mut head = Vec::new(); + for x in [0x0001_0000, 0x0001_0000, 0, 0x5F0F_3CF5] { + be32(&mut head, x); + } + for x in [0x000B, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, -200, 600, 800, 0, 8, 2, 1, 0] { + be16(&mut head, x); + } + let mut hhea = Vec::new(); + be32(&mut hhea, 0x0001_0000); + for x in [800, -200, 0, 600, 0, 0, 550, 1, 0, 0, 0, 0, 0, 0, 0, glyphs] { + be16(&mut hhea, x); + } + let mut maxp = Vec::new(); + be32(&mut maxp, 0x0001_0000); + for x in [glyphs, 4, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0] { + be16(&mut maxp, x); + } + let mut hmtx = Vec::new(); + for _ in 0..glyphs { + be16(&mut hmtx, 600); + be16(&mut hmtx, 50); + } + let mut cmap = Vec::new(); + for x in [0, 1, 3, 10] { + be16(&mut cmap, x); + } + be32(&mut cmap, 12); + be16(&mut cmap, 12); + be16(&mut cmap, 0); + be32(&mut cmap, 16 + 12 * ranges.len() as u32); + be32(&mut cmap, 0); + be32(&mut cmap, ranges.len() as u32); + let mut gid = 1; + for (a, b) in ranges { + for x in [*a, *b, gid] { + be32(&mut cmap, x); + } + gid += b - a + 1; + } + let tables: [(&[u8; 4], Vec); 7] = + [(b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)]; + let mut font = Vec::new(); + be32(&mut font, 0x0001_0000); + for x in [7, 64, 2, 48] { + be16(&mut font, x); + } + let mut offset = 12 + 16 * tables.len() as u32; + for (tag, data) in &tables { + font.extend(*tag); + be32(&mut font, 0); + be32(&mut font, offset); + be32(&mut font, data.len() as u32); + offset += (data.len() as u32).next_multiple_of(4); + } + for (_, data) in &tables { + font.extend(data); + font.resize(font.len().next_multiple_of(4), 0); + } + font +} + +/// Thai, Arabic and Devanagari each have a synthetic font; Thai's list starts with unreadable +/// files and Inter, which doesn't map Thai. No other script has a font. +fn script_sources() -> Sources { + Sources { + locale: || Some("en".into()), + files: |_| vec![], + last_resort: Vec::new, + pending: || false, + scripts: |s| { + let f = |name: &str| fake_dir().join(name); + match s { + Script::Thai => vec![f("missing.ttf"), f("empty.ttf"), f("font.ttf"), f("thai.ttf")], + Script::Arabic => vec![f("arabic.ttf")], + Script::Devanagari => vec![f("devanagari.ttf")], + _ => vec![], + } + }, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: false, + } +} + +fn fallback_files(ctx: &egui::Context) -> Vec { + ctx.with_plugin::(|p| p.0.registered.iter().map(|(_, path, _)| path.file_name().unwrap().to_string_lossy().into_owned()).collect()) + .unwrap() +} + +#[test] +fn layer_names_in_other_scripts_load_a_covering_font_once() { + let ctx = egui::Context::default(); + for _ in 0..2 { + crate::theme::install_fonts_with(&ctx, script_sources()); + assert!(render(&ctx, "Layer 1 – café")); + ctx.with_plugin::(|p| assert!(p.0.scripts_tried.is_empty(), "Latin text reads no font")).unwrap(); + assert!(fallback_files(&ctx).is_empty()); + // A Thai type layer's name (#2275), Arabic (#1693) and Devanagari: no missing glyphs. + for text in ["สวัสดี", "ภาพถ่าย/วันหยุดพักผ่อน", "مرحبا بالعالم", "नमस्ते दुनिया"] + { + assert!(render(&ctx, text), "tofu in {text}"); + } + assert_eq!(fallback_files(&ctx), ["thai.ttf", "arabic.ttf", "devanagari.ttf"], "the first file that maps the character, never Inter"); + // Hebrew has no font here: tried once, then left alone (no reload or repaint loop). + assert!(!render(&ctx, "שלום")); + assert!(!render(&ctx, "שלום")); + ctx.with_plugin::(|p| { + assert!(p.0.scripts_tried.contains(&Script::Hebrew)); + assert_eq!(p.0.registered.len(), 3); + }) + .unwrap(); + let fonts = ctx.fonts(|f| f.definitions().clone()); + assert_eq!(fonts.families[&FontFamily::Proportional].first().map(String::as_str), Some("Inter")); + for stack in fonts.families.values() { + assert_eq!(stack.iter().filter(|n| n.starts_with(FONT_PREFIX)).count(), 3); + assert_eq!(stack.last().map(String::as_str), Some("system-cjk-2"), "appended last so Latin keeps Inter"); + } + } +} + +#[test] +fn a_missing_cjk_font_does_not_block_other_scripts_and_vice_versa() { + let ctx = egui::Context::default(); + crate::theme::install_fonts_with(&ctx, script_sources()); + assert!(!render(&ctx, "日本語/ภาพถ่าย/วันหยุดพักผ่อน.png")); + assert!(render(&ctx, "ภาพถ่าย/วันหยุดพักผ่อน.png")); + ctx.with_plugin::(|p| assert!(p.0.exhausted())).unwrap(); + assert_eq!(fallback_files(&ctx), ["thai.ttf"]); + // A script with no font leaves CJK available. + let mut fallback = CjkFallback::new(fake_sources(|| Some("ko".into()))); + assert!(fallback.next_script_font('ส').is_none()); + assert!(fallback.next_script_font('ส').is_none()); + assert!(fallback.next_script_font('A').is_none(), "Latin is never a fallback script"); + assert_eq!(fallback.scripts_tried, [Script::Thai]); + assert!(fallback.next_font('카', CjkChar::Hangul).is_some()); +} + +#[test] +fn script_candidates_are_read_a_bounded_number_of_times() { + static CHECKED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let mut fallback = CjkFallback::new(Sources { + scripts: |_| (0..20).map(|i| fake_dir().join(if i % 2 == 0 { "font.ttf" } else { "thai.ttf" })).collect(), + covers: |_, _| { + CHECKED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + None + }, + ..script_sources() + }); + assert!(fallback.next_script_font('ش').is_none()); + assert!(fallback.next_script_font('ش').is_none()); + assert_eq!(CHECKED.load(std::sync::atomic::Ordering::Relaxed), MAX_SCRIPT_READS, "one bounded pass per script"); + assert!(fallback.registered.is_empty()); + assert!(!fallback.scripts_exhausted()); +} + +#[test] +fn system_fonts_cover_other_script_samples() { + // Like the CJK system-font test, run per script when this machine has a font for it. + // The deterministic tests above do not need installed fonts. + let samples = [("ภาพถ่าย/วันหยุดพักผ่อน", 'ภ'), ("مرحبا", 'م'), ("שלום", 'ש'), ("नमस्ते", 'न')]; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + for (text, c) in samples { + let Some(script) = scripts::classify(c) else { continue }; + if !scripts::system_candidates(script).iter().any(|p| read_font(p).and_then(|b| scripts::covering_face(&b, c)).is_some()) { + eprintln!("skipping {text}: no {script:?} system font"); + continue; + } + assert!(render(&ctx, text), "{text} still has missing glyphs"); + } +} + +#[test] +fn vertical_metrics_parse_and_reject_garbage() { + let (asc, desc, gap) = vertical_metrics(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"), 0).unwrap(); + assert!((asc - 1984.0 / 2048.0).abs() < 1e-4 && (desc + 494.0 / 2048.0).abs() < 1e-4 && gap == 0.0); + for bad in [&b""[..], b"ttcf", b"ttcf\0\0\0\0\0\0\0\0\xff\xff\xff\xff", b"\0\x01\0\0\0\xff\0\0\0\0\0\0"] { + assert!(vertical_metrics(bad, 0).is_none()); + assert!(vertical_metrics(bad, u32::MAX).is_none()); + } +} + +#[test] +fn a_face_with_a_big_line_gap_is_shifted_down_onto_the_primary_baseline() { + let inter = (1984.0 / 2048.0, -494.0 / 2048.0, 0.0); + let hiragino = (0.88, -0.12, 0.5); + assert!((baseline_offset(hiragino, inter) - 0.2338).abs() < 1e-3); + assert_eq!(baseline_offset(inter, inter), 0.0); + assert_eq!(baseline_offset((f32::NAN, 0.0, 0.0), inter), 0.0); + let jb = (1.02, -0.3, 0.0); + assert!((baseline_offset(hiragino, jb) - baseline_offset(hiragino, inter)).abs() < 0.005, "one offset serves the monospace family too"); +} + +#[test] +fn lazy_registration_triggers_only_for_supported_scripts() { + let ctx = egui::Context::default(); + install_with(&ctx, fake_sources(|| Some("ko".into()))); + let _ = render(&ctx, "Layer 1 – café"); + let n = ctx.fonts(|f| f.definitions().font_data.keys().filter(|k| k.starts_with(FONT_PREFIX)).count()); + assert_eq!(n, 0, "Latin text loads nothing"); + // The Korean candidate covers the first missing Hangul character and is registered. + let _ = render(&ctx, "카드 배경"); + let fonts = ctx.fonts(|f| f.definitions().clone()); + let name = format!("{FONT_PREFIX}-0"); + assert!(fonts.font_data.contains_key(&name)); + for (fam, stack) in &fonts.families { + assert_eq!(stack.last(), Some(&name), "{fam:?}: appended last so Latin keeps Inter"); + } +} + +/// Craft fonts available through the first-frame provider, as the desktop shell does. +fn eager_sources(locale: fn() -> Option) -> Sources { + Sources { + locale, + files: |_| vec![], + last_resort: Vec::new, + pending: || false, + scripts: |_| Vec::new(), + covers: scripts::covering_face, + embedded: craft_embedded_iso, + eager_craft_fonts: true, + } +} + +/// No system fonts at all: craft-fonts alone draws CJK through the lazy loader. +fn craft_only(locale: fn() -> Option) -> Sources { + Sources { + locale, + files: |_| vec![], + last_resort: Vec::new, + pending: || false, + scripts: |_| Vec::new(), + covers: scripts::covering_face, + embedded: craft_embedded_iso, + eager_craft_fonts: false, + } +} + +/// The migration baseline's first craft face covering `c`: the first non-empty face in +/// manifest order (what the old family stack appended first), not the UI-first sort. +fn baseline_face(c: char) -> Option<&'static CraftFont> { + craft_fonts::CRAFT_FONTS.iter().find(|f| !f.bytes.is_empty() && scripts::face_covers(f.bytes, 0, c)) +} + +/// A test-only craft face backed by a collection built with [`two_face_ttc`]: face 0 maps +/// Thai only, face 1 maps 龍. `craft_insert` would install face 0, so the craft coverage +/// helpers must not accept it for 龍 even though a later face covers the character. +fn ttc_craft_face() -> &'static CraftFont { + static FACE: std::sync::OnceLock = std::sync::OnceLock::new(); + FACE.get_or_init(|| { + let bytes: &'static [u8] = Box::leak(two_face_ttc(&synthetic_font(&[(0x0E01, 0x0E5B)]), &synthetic_font(&[(0x9F8D, 0x9F8D)])).into_boxed_slice()); + CraftFont { family: "Synthetic Collection", style: "Regular", scripts: &["Hans"], bytes } + }) +} + +/// The craft helpers must test face 0, the face `FontData::from_static` installs. The old +/// any-face coverage check returned the face for a character only a later collection face +/// maps, which then drew tofu in the installed face 0. +#[test] +fn craft_face_coverage_matches_the_face_craft_insert_installs() { + let face = ttc_craft_face(); + // Precondition: an any-face check really accepts 龍 (face 1), so this regression would + // fail if the helpers went back to `scripts::covering_face`. + assert_eq!(scripts::covering_face(face.bytes, '龍'), Some(1), "face 1 maps 龍"); + assert!(!scripts::face_covers(face.bytes, 0, '龍'), "the installed face 0 does not map 龍"); + assert!(!craft_face_installs_coverage(face, '龍'), "face 0 lacks the glyph; craft_insert installs face 0"); + assert!(craft_face_installs_coverage(face, 'ก'), "face 0 maps Thai"); +} + +static EMPTY_CRAFT_FACE: CraftFont = CraftFont { family: "Empty", style: "Regular", scripts: &["Zsym"], bytes: &[] }; + +fn only_empty_craft_face(_: &'static str) -> Vec<&'static CraftFont> { + vec![&EMPTY_CRAFT_FACE] +} + +/// A craft entry without bytes, or a face injected only by a test that is absent from the +/// global manifest, has no installable face index: selection must return `None`, not a face +/// name egui cannot resolve. +#[test] +fn craft_face_selection_ignores_empty_and_unindexed_faces() { + assert!(!craft_face_installs_coverage(&EMPTY_CRAFT_FACE, '☃')); + assert!(craft_face_for(only_empty_craft_face, "Zsym", '☃').is_none()); + assert!(craft_face_manifest(only_empty_craft_face, "Zsym", '☃').is_none()); +} + +/// Every script the lazy fallback can see has a valid ISO 15924 tag, so its injected craft +/// faces and the CJK scripts are selected by the same tags the manifest declares. +#[test] +fn fallback_scripts_map_to_iso_15924_tags() { + assert_eq!(cjk_iso(CjkScript::Japanese), "Jpan"); + assert_eq!(cjk_iso(CjkScript::SimplifiedChinese), "Hans"); + assert_eq!(cjk_iso(CjkScript::TraditionalChinese), "Hant"); + assert_eq!(cjk_iso(CjkScript::Korean), "Kore"); + let expected = [ + (Script::Thai, "Thai"), + (Script::Lao, "Laoo"), + (Script::Khmer, "Khmr"), + (Script::Myanmar, "Mymr"), + (Script::Tibetan, "Tibt"), + (Script::Arabic, "Arab"), + (Script::Hebrew, "Hebr"), + (Script::Armenian, "Armn"), + (Script::Georgian, "Geor"), + (Script::Ethiopic, "Ethi"), + (Script::Devanagari, "Deva"), + (Script::Bengali, "Beng"), + (Script::Gurmukhi, "Guru"), + (Script::Gujarati, "Gujr"), + (Script::Oriya, "Orya"), + (Script::Tamil, "Taml"), + (Script::Telugu, "Telu"), + (Script::Kannada, "Knda"), + (Script::Malayalam, "Mlym"), + (Script::Sinhala, "Sinh"), + ]; + assert_eq!(expected.len(), Script::ALL.len(), "the test lists every fallback script"); + for (script, iso) in expected { + assert_eq!(script_iso(script), iso, "{script:?}"); + } + assert_eq!(craft_embedded(CjkScript::Japanese).len(), craft_embedded_iso("Jpan").len()); +} + +/// No system fonts at all: craft-fonts alone draws CJK, in the locale's script order. +#[test] +fn craft_fonts_render_cjk_without_system_fonts() { + let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + return; + }; + let Some(chinese) = craft_fonts::CRAFT_FONTS.iter().find(|f| f.family == "Noto Sans CJK SC" && f.style == "Regular") else { + eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); + return; + }; + // The craft manifest's Japanese faces come before Noto Sans CJK SC and the baseline + // appended them in manifest order, so a non-CJK/unknown effective locale keeps Shippori + // Mincho (the first covering face). An explicit locale keeps its own UI-first script face. + let Some(baseline) = baseline_face('日') else { + eprintln!("skipping: the craft-fonts manifest has no face covering 日"); + return; + }; + for (locale, expected) in [ + ((|| Some("en_US".into())) as fn() -> Option, baseline), + ((|| Some("ja_JP".into())) as fn() -> Option, ui_font), + ((|| Some("zh-CN".into())) as fn() -> Option, chinese), + ((|| None) as fn() -> Option, baseline), + ] { + let ctx = egui::Context::default(); + crate::theme::install_fonts_with(&ctx, craft_only(locale)); + assert!(render(&ctx, "日本語の文字"), "tofu in 日本語の文字"); + assert!(render(&ctx, "レイヤー 1"), "tofu in kana"); + let fonts = ctx.fonts(|f| f.definitions().clone()); + let name = format!("{FONT_PREFIX}-0"); + assert!( + fonts.font_data.get(&name).is_some_and(|d| std::ptr::eq(d.bytes().as_ptr(), expected.bytes.as_ptr())), + "{} first by locale: {name}", + expected.family + ); + for (fam, stack) in &fonts.families { + assert_eq!(stack.last(), Some(&name), "{fam:?}: appended last so Latin keeps Inter"); + assert!(stack.first().is_some_and(|f| f != &name), "{fam:?}"); + } + } +} + +fn provided_insert(provider: &CraftFontProvider, c: char) -> Option { + let mut buf = [0u8; 4]; + let cluster = c.encode_utf8(&mut buf); + provider.font_for(&FallbackRequest { cluster, family: &FontFamily::Proportional }) +} + +fn provided(provider: &CraftFontProvider, c: char) -> Option { + provided_insert(provider, c).map(|insert| insert.name) +} + +fn test_sources(locale: fn() -> Option) -> Sources { + Sources { + locale, + files: no_files, + last_resort: Vec::new, + pending: || false, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: craft_embedded_iso, + eager_craft_fonts: false, + } +} + +fn test_provider(locale: fn() -> Option) -> CraftFontProvider { + CraftFontProvider::new(&test_sources(locale), 1.0) +} + +#[test] +fn effective_locale_prefers_the_translated_ui_then_the_os_locale() { + assert_eq!(effective_locale("ja", Some("en_US.UTF-8")), Some("ja".into())); + assert_eq!(effective_locale("zh-hant", Some("ja_JP.UTF-8")), Some("zh-hant".into())); + assert_eq!(effective_locale("en", Some("ja_JP.UTF-8")), Some("ja_JP.UTF-8".into()), "English UI on a Japanese OS uses the OS locale"); + assert_eq!(effective_locale("de", Some("ko_KR")), Some("ko_KR".into())); + assert_eq!(effective_locale("en", None), None, "no UI preference and no OS locale stays unknown"); +} + +fn no_script_files(_: Script) -> Vec { + Vec::new() +} + +fn no_files(_: CjkScript) -> Vec { + Vec::new() +} + +/// A stand-in system Traditional Chinese file, so the system-before-SC-craft ordering is +/// testable without depending on the host's fonts. Its content is the SC craft face (which +/// covers the sample Han character). +fn hant_system_file() -> Option { + static FILE: std::sync::OnceLock> = std::sync::OnceLock::new(); + let face = craft_fonts::CRAFT_FONTS.iter().find(|f| f.family == "Noto Sans CJK SC" && !f.bytes.is_empty())?; + FILE.get_or_init(|| { + let path = std::env::temp_dir().join(format!("photocraft-hant-{}.otf", std::process::id())); + std::fs::write(&path, face.bytes).ok().map(|()| path) + }) + .clone() +} + +fn hant_files(script: CjkScript) -> Vec { + if script == CjkScript::TraditionalChinese { + hant_system_file().map(|path| vec![FontFile { path, family: String::new() }]).unwrap_or_default() + } else { + Vec::new() + } +} + +#[test] +fn craft_font_provider_keeps_the_baseline_face_for_unknown_locales() { + let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + return; + }; + let Some(ui_index) = craft_index(ui_font) else { return }; + let Some((sc_index, sc)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans CJK SC") else { + eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); + return; + }; + let Some((korean_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "NanumGothic") else { + eprintln!("skipping: the craft-fonts manifest has no Korean face"); + return; + }; + let Some((arabic_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans Arabic") else { + eprintln!("skipping: the craft-fonts manifest has no Arabic face"); + return; + }; + let Some((devanagari_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans Devanagari") else { + eprintln!("skipping: the craft-fonts manifest has no Devanagari face"); + return; + }; + let Some(baseline_han) = baseline_face('日') else { + eprintln!("skipping: the craft-fonts manifest has no face covering 日"); + return; + }; + let Some(baseline_kana) = baseline_face('あ') else { + eprintln!("skipping: the craft-fonts manifest has no face covering あ"); + return; + }; + let baseline_han_index = craft_index(baseline_han).expect("a manifest face has an index"); + let baseline_kana_index = craft_index(baseline_kana).expect("a manifest face has an index"); + let baseline_han_name = format!("craft-font-{baseline_han_index}"); + let baseline_kana_name = format!("craft-font-{baseline_kana_index}"); + let ui_name = format!("craft-font-{ui_index}"); + let sc_name = format!("craft-font-{sc_index}"); + let korean_name = format!("craft-font-{korean_index}"); + let arabic_name = format!("craft-font-{arabic_index}"); + let devanagari_name = format!("craft-font-{devanagari_index}"); + + let ja = test_provider((|| Some("ja_JP".into())) as fn() -> Option); + assert_eq!(provided(&ja, 'あ').as_deref(), Some(ui_name.as_str()), "explicit ja keeps the Japanese UI face"); + assert_eq!(provided(&ja, '日').as_deref(), Some(ui_name.as_str()), "Han follows an explicit Japanese locale"); + + let en = test_provider((|| Some("en_US".into())) as fn() -> Option); + assert_eq!( + provided(&en, 'あ').as_deref(), + Some(baseline_kana_name.as_str()), + "kana in a non-CJK effective locale keeps the manifest's first covering face" + ); + assert_eq!(provided(&en, '한').as_deref(), Some(korean_name.as_str()), "Hangul in a non-CJK effective locale stays on the Korean face"); + assert_eq!(provided(&en, '日').as_deref(), Some(baseline_han_name.as_str()), "Han in a non-CJK effective locale keeps the manifest's first covering face"); + let unknown = test_provider((|| None) as fn() -> Option); + assert_eq!(provided(&unknown, '日').as_deref(), Some(baseline_han_name.as_str()), "an unknown effective locale has the same baseline face"); + let english_on_japanese_os = test_provider((|| effective_locale("en", Some("ja_JP"))) as fn() -> Option); + assert_eq!( + provided(&english_on_japanese_os, '日').as_deref(), + Some(ui_name.as_str()), + "English UI on a Japanese OS follows the OS locale; the manifest baseline is not universal for English UI" + ); + assert_eq!(provided(&en, 'م').as_deref(), Some(arabic_name.as_str()), "Arabic uses its own craft face"); + assert_eq!(provided(&en, 'न').as_deref(), Some(devanagari_name.as_str()), "Devanagari uses its own craft face"); + + let hans = test_provider((|| Some("zh-CN".into())) as fn() -> Option); + assert_eq!(provided(&hans, '日').as_deref(), Some(sc_name.as_str())); + assert_eq!(provided(&hans, 'あ').as_deref(), Some(ui_name.as_str()), "kana in a Chinese UI keeps the Japanese face"); + + let hant = test_provider((|| Some("zh-Hant-TW".into())) as fn() -> Option); + assert_eq!(provided(&hant, '龍').as_deref(), Some(sc_name.as_str()), "with no system Hant face, the locale order falls through to SC"); + assert_eq!(provided(&hant, '\u{3105}').as_deref(), Some(sc_name.as_str()), "Bopomofo follows the same locale-order fallback"); + assert_eq!(provided(&hant, 'あ').as_deref(), Some(ui_name.as_str()), "kana in a Hant UI keeps the Japanese face"); + + // A system Hant file, when present, is read before the Simplified Chinese craft fallback. + if hant_system_file().is_some() { + let sources = Sources { + locale: (|| Some("zh-Hant-TW".into())) as fn() -> Option, + files: hant_files, + last_resort: Vec::new, + pending: || false, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: craft_embedded_iso, + eager_craft_fonts: false, + }; + let hant = CraftFontProvider::new(&sources, 1.0); + let got = provided(&hant, '龍').expect("the system Hant face"); + assert!(got.starts_with("craft-system-"), "the system Hant face comes before the SC craft fallback: {got}"); + assert_ne!(got, sc_name, "the SC craft face must not pre-empt a system Hant face"); + } + + let ko = test_provider((|| Some("ko_KR".into())) as fn() -> Option); + assert_eq!(provided(&ko, '한').as_deref(), Some(korean_name.as_str())); + assert_eq!(provided(&ko, 'あ').as_deref(), Some(ui_name.as_str()), "kana in a Korean UI keeps the Japanese face"); + assert_ne!(sc.family, ui_font.family); +} + +static PENDING_LAST_RESORT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static PENDING_CRAFT_SC: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static PENDING_READY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static STRICT_PENDING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + +fn pending_last_resort() -> bool { + PENDING_LAST_RESORT.load(std::sync::atomic::Ordering::Relaxed) +} + +fn pending_craft_sc() -> bool { + PENDING_CRAFT_SC.load(std::sync::atomic::Ordering::Relaxed) +} + +fn pending_ready() -> bool { + !PENDING_READY.load(std::sync::atomic::Ordering::Relaxed) +} + +fn strict_pending() -> bool { + STRICT_PENDING.load(std::sync::atomic::Ordering::Relaxed) +} + +fn ready_files(script: CjkScript) -> Vec { + if script == CjkScript::TraditionalChinese && PENDING_READY.load(std::sync::atomic::Ordering::Relaxed) { vec![fake("hant.ttf")] } else { Vec::new() } +} + +fn ready_hant_files(script: CjkScript) -> Vec { + if script == CjkScript::TraditionalChinese { vec![fake("hant.ttf")] } else { Vec::new() } +} + +#[test] +fn provider_uses_the_requested_collection_family_and_its_exact_coverage() { + let path = fake_dir().join("families.ttc"); + let provider = CraftFontProvider::new(&test_sources(|| Some("en".into())), 1.0); + let file = |family: &str| vec![FontFile { path: path.clone(), family: family.into() }]; + + let insert = provider.system_insert_files(file("JetBrains Mono"), 'A').expect("face 1 covers A"); + assert_eq!(insert.data.index, 1, "the requested family selects face 1, not the first covering face 0"); + assert!( + provider.system_insert_files(file("JetBrains Mono"), 'ƀ').is_none(), + "JetBrains Mono does not cover the character; face 0 of Inter must not be used" + ); + + let empty_family = vec![FontFile { path: path.clone(), family: String::new() }]; + let insert = provider.system_insert_files(empty_family, 'ƀ').expect("an empty family is face 0"); + assert_eq!(insert.data.index, 0); +} + +#[test] +fn cached_system_face_returns_the_current_scale() { + let path = fake_dir().join("families.ttc"); + let provider = CraftFontProvider::new(&test_sources(|| Some("en".into())), 1.0); + let file = || vec![FontFile { path: path.clone(), family: "JetBrains Mono".into() }]; + + let first = provider.system_insert_files(file(), 'A').expect("face 1 covers A"); + assert_eq!(first.data.index, 1); + assert_eq!(first.data.tweak.scale, 1.0); + provider.set_scale(4.0 / 3.0); + let second = provider.system_insert_files(file(), 'A').expect("cached face"); + assert_eq!(second.data.index, 1); + assert_eq!(second.data.tweak.scale, 4.0 / 3.0, "a cached face must not bake in the old UI scale"); +} + +#[test] +fn provider_honours_the_injected_embedded_faces() { + let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + return; + }; + if craft_index(ui_font).is_none() { + return; + } + let Some(baseline) = baseline_face('あ') else { return }; + let baseline_name = format!("craft-font-{}", craft_index(baseline).expect("a manifest face has an index")); + let with_craft = test_provider((|| Some("en_US".into())) as fn() -> Option); + assert_eq!(provided(&with_craft, 'あ').as_deref(), Some(baseline_name.as_str())); + + let no_craft = Sources { embedded: no_embedded, ..test_sources((|| Some("en_US".into())) as fn() -> Option) }; + let provider = CraftFontProvider::new(&no_craft, 1.0); + assert!(provided(&provider, 'あ').is_none(), "the provider must use Sources::embedded, not the global craft table"); +} + +#[test] +fn provider_reaches_a_fontconfig_match_after_six_missing_candidates() { + let mut files: Vec = + (0..MAX_SCRIPT_READS).map(|i| FontFile { path: fake_dir().join(format!("missing-{i}.ttf")), family: String::new() }).collect(); + files.push(fake("hant.ttf")); + let provider = CraftFontProvider::new(&test_sources((|| Some("zh-Hant-TW".into())) as fn() -> Option), 1.0); + let insert = provider.system_insert_files(files, '龍').expect("the seventh (Fontconfig) candidate must be reachable"); + assert!(insert.name.starts_with("craft-system-")); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.reads, 1, "only the real file counts as a read; absent paths do not"); + assert_eq!(cache.failed_reads.len(), MAX_SCRIPT_READS); +} + +#[test] +fn provider_caches_failed_reads_and_face_lookups_across_characters() { + let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); + let missing = fake("missing-cache.ttf"); + assert!(provider.system_insert_files(vec![missing.clone()], '日').is_none()); + assert!(provider.system_insert_files(vec![missing.clone()], '本').is_none()); + { + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.failed_reads.len(), 1, "a missing path is remembered"); + assert_eq!(cache.reads, 0, "a missing path performs no font read"); + } + + // Inter is readable but does not cover either Han character: its bytes are read once. + let inter = fake("font.ttf"); + assert!(provider.system_insert_files(vec![inter.clone()], '日').is_none()); + assert!(provider.system_insert_files(vec![inter.clone()], '本').is_none()); + { + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.reads, 1, "the second character reuses the cached bytes"); + assert_eq!(cache.files.len(), 1); + } + + // A collection's family lookup is parsed once even when it misses every character. + let path = fake_dir().join("families.ttc"); + let file = vec![FontFile { path, family: "Noto Sans CJK TC".into() }]; + assert!(provider.system_insert_files(file.clone(), '日').is_none()); + assert!(provider.system_insert_files(file, '本').is_none()); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.family_indices.len(), 1, "a family miss is cached"); + assert_eq!(cache.family_indices[0].2, None); +} + +static TTC_READS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +fn counted_ttc_read(path: &std::path::Path) -> Option> { + TTC_READS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + std::fs::read(path).ok() +} + +/// A collection's two faces share one blob: selecting both faces reads the file once and +/// charges its bytes once, not once per face. +#[test] +fn provider_charges_a_ttc_blob_once_for_multiple_selected_faces() { + let path = fake_dir().join("families.ttc"); + let size = std::fs::metadata(&path).expect("test collection").len() as usize; + let mut provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); + provider.reader = counted_ttc_read; + TTC_READS.store(0, std::sync::atomic::Ordering::Relaxed); + let first = provider.system_insert_files(vec![FontFile { path: path.clone(), family: "Inter".into() }], 'A').expect("face 0 covers A"); + let second = provider.system_insert_files(vec![FontFile { path: path.clone(), family: "JetBrains Mono".into() }], 'A').expect("face 1 covers A"); + assert_eq!((first.data.index, second.data.index), (0, 1)); + assert!(std::sync::Arc::ptr_eq(&first.data.font, &second.data.font), "both faces share the collection's blob"); + assert_eq!(TTC_READS.load(std::sync::atomic::Ordering::Relaxed), 1, "the collection is read once"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.files.len(), 1, "one retained blob serves both faces"); + assert_eq!(cache.retained_bytes, size, "the TTC blob is charged once"); + assert_eq!(cache.faces.len(), 2, "both selected faces keep their own name"); +} + +/// Selecting a second face under a one-blob budget evicts the earlier blob from the +/// provider, but the earlier `FontInsert` remains valid because it owns its shared blob. +#[test] +fn provider_evicts_an_earlier_selected_blob_under_budget_pressure() { + let first_path = fake("font.ttf").path; + let bytes = std::fs::read(&first_path).expect("test font"); + let size = bytes.len(); + let second_path = fake_dir().join("budget-selected-second.ttf"); + std::fs::write(&second_path, &bytes).expect("write a second test font"); + let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); + { + let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + cache.max_bytes = size; + } + let first = provider.system_insert_files(vec![FontFile { path: first_path.clone(), family: String::new() }], 'A').expect("the first selected face"); + let second = provider.system_insert_files(vec![FontFile { path: second_path.clone(), family: String::new() }], 'A').expect("the second selected face"); + assert_ne!(first.name, second.name); + assert_eq!(first.data.bytes(), bytes.as_slice(), "evicting the provider's blob does not invalidate egui's copy"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.files.len(), 1, "only one blob fits"); + assert_eq!(cache.files[0].path, second_path, "the newest selected blob is retained"); + assert_eq!(cache.retained_bytes, size, "the provider cache stays within its one-blob budget"); + assert_eq!(cache.faces.len(), 2, "the earlier face name remains reusable metadata, not bytes"); +} + +/// A selected face whose blob does not fit the budget is still returned complete for this +/// request. egui may keep it, but the provider retains neither its bytes nor a second copy. +#[test] +fn provider_returns_a_transient_valid_face_when_the_blob_cannot_be_retained() { + let path = fake("font.ttf").path; + let size = std::fs::metadata(&path).expect("test font").len() as usize; + let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); + { + let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + cache.max_bytes = size.saturating_sub(1); + } + let insert = + provider.system_insert_files(vec![FontFile { path: path.clone(), family: String::new() }], 'A').expect("the over-budget face is returned transiently"); + assert_eq!(insert.data.index, 0); + assert_eq!(insert.data.bytes().len(), size, "the transient face carries the whole valid font"); + assert_eq!(insert.data.bytes(), std::fs::read(&path).expect("test font bytes").as_slice()); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.retained_bytes, 0, "an over-budget face retains no provider bytes"); + assert!(cache.files.is_empty(), "the over-budget blob is not retained"); + assert!(cache.retained_bytes <= cache.max_bytes, "the provider cache stays within its budget"); + assert_eq!(cache.reads, 1); +} + +/// A valid font file whose character map does not include the requested character is still a +/// valid font: its bytes are cached within the budget and it is not marked invalid. +#[test] +fn provider_cache_evicts_retained_bytes_within_the_budget() { + let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); + let bytes = synthetic_font(&[(0x0E01, 0x0E5B)]); + let size = bytes.len(); + assert!(size > 0); + { + let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + cache.max_bytes = size.saturating_mul(2); + } + let mut paths = Vec::new(); + for i in 0..5 { + let path = fake_dir().join(format!("budget-{i}.ttf")); + std::fs::write(&path, &bytes).expect("write a synthetic test font"); + paths.push(path); + } + for path in &paths { + let file = vec![FontFile { path: path.clone(), family: String::new() }]; + assert!(provider.system_insert_files(file, '日').is_none(), "the Thai-only face does not cover 日"); + } + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert!(cache.retained_bytes <= cache.max_bytes, "retained {} > budget {}", cache.retained_bytes, cache.max_bytes); + assert!(cache.files.len() <= 2, "only two files fit the budget"); + assert!(cache.files.iter().any(|file| file.path == paths[4]), "the newest retained file stays"); + assert!(!cache.files.iter().any(|file| file.path == paths[0]), "the oldest retained file was evicted"); + assert_eq!(cache.reads, 5, "each distinct file was read once"); + assert!(cache.invalid_fonts.is_empty(), "a non-covering face is not an invalid font"); +} + +/// A later covering candidate (such as the Fontconfig match appended last) is reached even +/// when a tiny budget evicts every retained candidate before it. +#[test] +fn provider_reaches_a_later_covering_candidate_under_budget_pressure() { + let provider = CraftFontProvider::new(&test_sources((|| Some("zh-Hant-TW".into())) as fn() -> Option), 1.0); + let bytes = synthetic_font(&[(0x0E01, 0x0E5B)]); + { + let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + cache.max_bytes = bytes.len(); + } + let mut files = Vec::new(); + for i in 0..12 { + let path = fake_dir().join(format!("budget-later-{i}.ttf")); + std::fs::write(&path, &bytes).expect("write a synthetic test font"); + files.push(FontFile { path, family: String::new() }); + } + let covering = fake("hant.ttf").path; + files.push(FontFile { path: covering.clone(), family: String::new() }); + let insert = provider.system_insert_files(files, '龍').expect("the later covering candidate must be reached"); + assert!(insert.name.starts_with("craft-system-"), "{insert:?}"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert!(cache.faces.iter().any(|face| face.path == covering), "the covering file became a selected face"); + assert!(cache.reads >= 13, "all retained candidates plus the matching file were read"); +} + +/// The old lifetime read cap could exhaust before a Fontconfig match appended after many +/// earlier characters. Reads are no longer globally capped; only retained bytes are bounded. +#[test] +fn provider_has_no_lifetime_read_cap_for_the_final_fontconfig_candidate() { + let provider = CraftFontProvider::new(&test_sources((|| Some("zh-Hant-TW".into())) as fn() -> Option), 1.0); + let bytes = synthetic_font(&[(0x0E01, 0x0E5B)]); + { + let mut cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + cache.max_bytes = bytes.len(); + } + for i in 0..130 { + let path = fake_dir().join(format!("lifetime-{i}.ttf")); + std::fs::write(&path, &bytes).expect("write a synthetic test font"); + let file = vec![FontFile { path, family: String::new() }]; + assert!(provider.system_insert_files(file, '日').is_none()); + } + let covering = fake("hant.ttf").path; + let insert = provider + .system_insert_files(vec![FontFile { path: covering, family: String::new() }], '龍') + .expect("the final candidate must still be read after 130 successful reads"); + assert!(insert.name.starts_with("craft-system-"), "{insert:?}"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.reads, 131, "130 non-covering reads plus the final candidate"); +} + +static CONCURRENT_READS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +fn counted_slow_read(path: &std::path::Path) -> Option> { + CONCURRENT_READS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + std::thread::sleep(std::time::Duration::from_millis(20)); + std::fs::read(path).ok() +} + +/// Layout may ask the provider from several threads. The check/read/insert is serialised, so +/// the same path is read once and every caller sees the same success. +#[test] +fn provider_serialises_concurrent_reads_of_the_same_path() { + let path = fake("font.ttf").path; + let mut provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); + provider.reader = counted_slow_read; + CONCURRENT_READS.store(0, std::sync::atomic::Ordering::Relaxed); + let provider = std::sync::Arc::new(provider); + let mut handles = Vec::new(); + for _ in 0..8 { + let provider = std::sync::Arc::clone(&provider); + let path = path.clone(); + handles.push(std::thread::spawn(move || { + let file = vec![FontFile { path, family: String::new() }]; + provider.system_insert_files(file, 'A').is_some() + })); + } + for handle in handles { + assert!(handle.join().expect("layout thread"), "every caller must get the Inter face"); + } + assert_eq!(CONCURRENT_READS.load(std::sync::atomic::Ordering::Relaxed), 1, "one read per path even under concurrency"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.faces.len(), 1, "one selected face is shared"); +} + +/// A readable non-font is negative-cached as invalid (read/parsed once) and never conflated +/// with a valid font that simply does not cover the requested character. +#[test] +fn provider_negative_caches_invalid_fonts_separately_from_noncovering_faces() { + let provider = CraftFontProvider::new(&test_sources((|| Some("en".into())) as fn() -> Option), 1.0); + let invalid = fake("not-a-font-cache.ttf").path; + std::fs::write(&invalid, b"this is not a font").expect("write invalid bytes"); + let truncated = fake("truncated-font-cache.ttf").path; + std::fs::write(&truncated, &include_bytes!("../../../../assets/fonts/Inter-Regular.ttf")[..20]).expect("write truncated font"); + for path in [&invalid, &truncated] { + for c in ['日', '本'] { + let file = vec![FontFile { path: path.clone(), family: String::new() }]; + assert!(provider.system_insert_files(file, c).is_none()); + } + } + { + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.invalid_fonts.len(), 2, "both invalid paths are remembered"); + assert_eq!(cache.reads, 2, "invalid bytes are read and examined once each"); + assert!(cache.files.is_empty(), "invalid bytes are never retained as a font"); + assert!(cache.failed_reads.is_empty(), "an invalid font is not an I/O failure"); + } + let inter = fake("font.ttf").path; + let file = vec![FontFile { path: inter.clone(), family: String::new() }]; + assert!(provider.system_insert_files(file, '日').is_none(), "Inter does not cover 日"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert!(cache.files.iter().any(|file| file.path == inter), "a valid non-covering font is cached"); + assert!(!cache.invalid_fonts.contains(&inter), "a non-covering face is not an invalid font"); + drop(cache); + let file = vec![FontFile { path: inter, family: String::new() }]; + let insert = provider.system_insert_files(file, 'A').expect("the cached valid font still covers A"); + assert!(insert.name.starts_with("craft-system-"), "{insert:?}"); +} + +#[test] +fn pending_scan_recovers_through_real_layout_and_the_lazy_reload() { + PENDING_READY.store(false, std::sync::atomic::Ordering::Relaxed); + let ctx = egui::Context::default(); + let sources = Sources { + locale: (|| Some("zh-Hant-TW".into())) as fn() -> Option, + files: ready_files, + last_resort: Vec::new, + pending: pending_ready, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: true, + }; + crate::theme::install_fonts_with(&ctx, sources); + let frame = |ctx: &egui::Context| { + ctx.run_ui(Default::default(), |ui| { + ui.label("龍"); + }) + .textures_delta + .clear(); + }; + frame(&ctx); + assert!(!ctx.fonts_mut(|f| f.has_glyph(&FontId::proportional(12.0), '龍')), "the pending first frame has no Hant face"); + + PENDING_READY.store(true, std::sync::atomic::Ordering::Relaxed); + for _ in 0..4 { + frame(&ctx); + } + assert!(ctx.fonts_mut(|f| f.has_glyph(&FontId::proportional(12.0), '龍')), "the lazy loader's add_font reload recovers after the scan"); + let registered = ctx.fonts(|f| f.definitions().font_data.keys().filter(|name| name.starts_with(FONT_PREFIX)).count()); + assert_eq!(registered, 1, "exactly the Hant file was installed"); + PENDING_READY.store(false, std::sync::atomic::Ordering::Relaxed); +} + +#[test] +fn strict_policy_first_frame_after_the_scan_is_accepted() { + if craft_fonts::CRAFT_FONTS.is_empty() { + eprintln!("skipping: the eager provider is only installed with craft-fonts"); + return; + } + let ctx = egui::Context::default(); + ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Panic); + let sources = Sources { + locale: (|| Some("zh-Hant-TW".into())) as fn() -> Option, + files: ready_hant_files, + last_resort: Vec::new, + pending: || false, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: true, + }; + crate::theme::install_fonts_with(&ctx, sources); + ctx.run_ui(Default::default(), |ui| { + ui.label("龍"); + }) + .textures_delta + .clear(); + assert!(ctx.fonts_mut(|f| f.has_glyph(&FontId::proportional(12.0), '龍'))); +} + +/// A strict first frame while Fontconfig is still pending cannot be recovered by the lazy +/// loader: epaint panics during layout before `output_hook` can call `add_font`. The real app +/// uses `MissingGlyphPolicy::Tofu` (brief tofu, then the reload above); strict integration +/// tests such as `camera_raw_localization` must wait for the scan first. This test records +/// that limitation instead of claiming a pending strict startup is accepted. +#[test] +#[should_panic(expected = "No glyph for")] +fn pending_strict_policy_startup_is_not_fake_acceptance() { + let ctx = egui::Context::default(); + ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Panic); + let sources = Sources { + locale: (|| Some("zh-Hant-TW".into())) as fn() -> Option, + files: no_files, + last_resort: Vec::new, + pending: strict_pending, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: true, + }; + crate::theme::install_fonts_with(&ctx, sources); + let _ = ctx.run_ui(Default::default(), |ui| { + ui.label("龍"); + }); +} + +#[test] +fn language_change_reloads_eager_faces_through_the_app_context() { + let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + return; + }; + let Some(ui_index) = craft_index(ui_font) else { return }; + let Some((sc_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans CJK SC") else { + eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); + return; + }; + let ui_name = format!("craft-font-{ui_index}"); + let sc_name = format!("craft-font-{sc_index}"); + crate::i18n::with_language(crate::i18n::Lang::EN, || { + let ctx = egui::Context::default(); + crate::i18n::sync_context(&ctx, "ja"); + for _ in 0..2 { + ctx.run_ui(Default::default(), |ui| { + ui.label("日"); + }) + .textures_delta + .clear(); + } + let discovered = ctx.fonts(|f| f.discovered_fonts().to_vec()); + assert!(discovered.iter().any(|insert| insert.name == ui_name), "ja discovers {ui_name}: {discovered:?}"); + + crate::i18n::sync_context(&ctx, "zh-hans"); + for _ in 0..2 { + ctx.run_ui(Default::default(), |ui| { + ui.label("日"); + }) + .textures_delta + .clear(); + } + let discovered = ctx.fonts(|f| f.discovered_fonts().to_vec()); + assert!(discovered.iter().any(|insert| insert.name == sc_name), "zh-hans discovers {sc_name}: {discovered:?}"); + assert!(!discovered.iter().any(|insert| insert.name == ui_name), "the language reload clears the old Japanese face: {discovered:?}"); + }); +} + +/// A valid synthetic font whose `glyf` table record extends past the end of the file. Its +/// `cmap` still parses and maps Thai, so a coverage-only check accepts it, but the text +/// engine cannot read every declared table. +fn font_with_out_of_bounds_table() -> Vec { + let mut font = synthetic_font(&[(0x0E01, 0x0E5B)]); + let tables = u16::from_be_bytes([font[4], font[5]]) as usize; + for i in 0..tables { + let rec = 12 + 16 * i; + if font.get(rec..rec + 4) == Some(&b"glyf"[..]) { + font[rec + 12..rec + 16].copy_from_slice(&u32::MAX.to_be_bytes()); + return font; + } + } + panic!("synthetic font has no glyf table"); +} + +/// A readable collection whose selected family face has an out-of-bounds `glyf` table. Face 0 +/// stays readable, and face 1's `cmap`/`name` still work, so a file-level check plus coverage +/// accepts it even though the face cannot be installed safely. +fn collection_with_out_of_bounds_selected_face() -> Vec { + let inter = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"); + let mut jetbrains = include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec(); + let tables = u16::from_be_bytes([jetbrains[4], jetbrains[5]]) as usize; + let glyf = (0..tables).map(|i| 12 + 16 * i).find(|&rec| jetbrains.get(rec..rec + 4) == Some(&b"glyf"[..])).expect("JetBrains Mono has a glyf table"); + jetbrains[glyf + 12..glyf + 16].copy_from_slice(&u32::MAX.to_be_bytes()); + two_face_ttc(inter, &jetbrains) +} + +/// A truncated/out-of-bounds table can keep a valid `cmap`, so `load_first` must validate +/// the file before registering it, and must still reach the next, valid candidate. +#[test] +fn lazy_loader_rejects_a_font_with_an_out_of_bounds_table_and_uses_the_next_candidate() { + let malformed = fake_dir().join("out-of-bounds-thai.ttf"); + std::fs::write(&malformed, font_with_out_of_bounds_table()).unwrap(); + let valid = fake_dir().join("thai.ttf"); + let files = vec![FontFile { path: malformed.clone(), family: String::new() }, FontFile { path: valid.clone(), family: String::new() }]; + let bytes = std::fs::read(&malformed).unwrap(); + assert!(scripts::face_covers(&bytes, 0, 'ก'), "the malformed file's cmap still maps the character"); + assert!(!cjk::font_file_is_readable(&bytes), "an out-of-bounds table makes the file unreadable"); + + let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); + let (_, data) = fallback.load_first(&files, 'ก').expect("the valid fallback is reached"); + assert_eq!(fallback.registered.len(), 1); + assert_eq!(fallback.registered[0].1, valid, "the malformed file is skipped, not registered"); + assert_eq!(data.index, 0); + assert_eq!(data.bytes(), std::fs::read(&valid).unwrap().as_slice()); + + // The non-CJK script route must enforce the same validation before registration. + let mut sources = test_sources(|| Some("en".into())); + sources.scripts = |_| vec![fake_dir().join("out-of-bounds-thai.ttf"), fake_dir().join("thai.ttf")]; + let mut fallback = CjkFallback::new(sources); + let (_, data) = fallback.next_script_font('ก').expect("the valid script fallback is reached"); + assert_eq!(fallback.registered.len(), 1); + assert_eq!(fallback.registered[0].1, valid, "the script route also skips the malformed file"); + assert_eq!(data.bytes(), std::fs::read(&valid).unwrap().as_slice()); + + // A readable collection with an unreadable covering face must also skip that face: the + // coverage route selects face 1 by its valid cmap, not the readable face 0. + let collection = fake_dir().join("out-of-bounds-thai.ttc"); + let inter = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"); + let collection_bytes = two_face_ttc(inter, &font_with_out_of_bounds_table()); + std::fs::write(&collection, &collection_bytes).unwrap(); + assert!(cjk::font_file_is_readable(&collection_bytes), "face 0 keeps the collection readable"); + assert_eq!(scripts::covering_face(&collection_bytes, 'ก'), Some(1), "coverage selects the malformed face"); + assert!(!cjk::font_face_is_readable(&collection_bytes, 1)); + let mut sources = test_sources(|| Some("en".into())); + sources.scripts = |_| vec![fake_dir().join("out-of-bounds-thai.ttc"), fake_dir().join("thai.ttf")]; + let mut fallback = CjkFallback::new(sources); + let (_, data) = fallback.next_script_font('ก').expect("the valid script fallback is reached"); + assert_eq!(fallback.registered.len(), 1); + assert_eq!(fallback.registered[0].1, valid, "the coverage route skips the malformed selected face"); + assert_eq!(data.bytes(), std::fs::read(&valid).unwrap().as_slice()); +} + +/// A readable collection may contain one bad face. The selected face (by family name) can +/// keep a valid `cmap` and `name` while another table points outside the file, so checking the +/// file or coverage alone would register a face epaint cannot safely install. Both the lazy +/// loader and the eager provider must skip that face and continue to the valid candidate. +#[test] +fn malformed_selected_collection_face_falls_back_before_lazy_and_provider_registration() { + let path = fake_dir().join("out-of-bounds-selected.ttc"); + let bytes = collection_with_out_of_bounds_selected_face(); + std::fs::write(&path, &bytes).expect("write the synthetic collection"); + assert!(cjk::font_file_is_readable(&bytes), "face 0 keeps the collection readable"); + assert_eq!(cjk::face_index_for_family_checked(&bytes, "JetBrains Mono"), Some(1), "the selected face's name resolves"); + assert!(scripts::face_covers(&bytes, 1, 'A'), "the selected face's cmap covers the character"); + assert!(!cjk::font_face_is_readable(&bytes, 1), "the selected face's glyf table is out of bounds"); + + let valid = fake("font.ttf"); + let candidates = vec![FontFile { path: path.clone(), family: "JetBrains Mono".into() }, FontFile { path: valid.path.clone(), family: String::new() }]; + let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); + let (name, data) = fallback.load_first(&candidates, 'A').expect("the valid alternative is reached"); + assert_eq!(data.index, 0, "the lazy loader registers the valid face 0, not the malformed selected face"); + assert_eq!(fallback.registered.len(), 1); + assert_eq!(fallback.registered[0].1, valid.path, "the malformed collection is not registered"); + + let provider = CraftFontProvider::new(&test_sources(|| Some("en".into())), 1.0); + let insert = provider.system_insert_files(candidates, 'A').expect("the provider reaches the valid alternative"); + assert_eq!(insert.data.index, 0, "the provider does not hand the malformed selected face to epaint"); + assert!(insert.name.starts_with("craft-system-"), "{insert:?}"); + + // Installing the selected font under the strict policy must not panic: only the valid + // fallback reaches egui's family builder. + let ctx = egui::Context::default(); + ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Panic); + crate::theme::install_fonts(&ctx); + // The lazy loader runs after a frame; initialize the font view before matching that path. + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); + add_to_all_families(&ctx, name, data); + ctx.run_ui(Default::default(), |ui| { + ui.label("A"); + }) + .textures_delta + .clear(); +} + +#[test] +fn lazy_loader_uses_the_requested_collection_family_and_checks_coverage() { + let path = fake_dir().join("families.ttc"); + let file = |family: &str| vec![FontFile { path: path.clone(), family: family.into() }]; + + let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); + let (_, data) = fallback.load_first(&file("JetBrains Mono"), 'A').expect("face 1 covers A"); + assert_eq!(data.index, 1); + + let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); + assert!(fallback.load_first(&file("JetBrains Mono"), 'ƀ').is_none(), "coverage is checked on the requested face"); + + let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); + let empty_family = vec![FontFile { path: path.clone(), family: String::new() }]; + let (_, data) = fallback.load_first(&empty_family, 'ƀ').expect("empty family is face 0"); + assert_eq!(data.index, 0); +} + +fn always_thai_candidate(_: Script) -> Vec { + vec![fake_dir().join("thai.ttf")] +} + +/// A path already registered through either route is not read or registered a second time. +#[test] +fn lazy_loader_registers_each_loaded_font_once() { + let valid = fake("font.ttf"); + let mut fallback = CjkFallback::new(test_sources(|| Some("en".into()))); + let files = vec![valid.clone()]; + fallback.load_first(&files, 'A').expect("the font covers Latin A"); + assert!(fallback.load_first(&files, 'A').is_none(), "a second request for the loaded file registers nothing"); + assert_eq!(fallback.registered.len(), 1); + + let sources = Sources { scripts: always_thai_candidate, ..test_sources(|| Some("en".into())) }; + let mut fallback = CjkFallback::new(sources); + fallback.loaded.push(fake_dir().join("thai.ttf")); + assert!(fallback.next_script_font('ก').is_none(), "the script route skips a file the other route already loaded"); + assert!(fallback.registered.is_empty()); + assert_eq!(fallback.scripts_tried, vec![Script::Thai], "the script is still marked tried only once"); +} + +/// A craft face is registered once: a later request for the same embedded file must not add +/// another font with a new name and a duplicate blob. +#[test] +fn lazy_loader_registers_an_embedded_craft_face_once() { + if baseline_face('あ').is_none() { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + return; + } + let mut fallback = CjkFallback::new(craft_only(|| Some("en".into()))); + fallback.load_embedded(CjkScript::Japanese, 'あ').expect("the manifest covers kana"); + assert!(fallback.load_embedded(CjkScript::Japanese, 'あ').is_none(), "the same embedded face is not registered twice"); + assert_eq!(fallback.registered.len(), 1); + assert_eq!(fallback.loaded.len(), 1); +} + +#[test] +fn provider_uses_system_script_candidates_and_last_resort_for_non_cjk() { + let sources = Sources { + locale: || Some("en".into()), + files: no_files, + last_resort: || vec![FontFile { path: fake_dir().join("ethiopic.ttf"), family: String::new() }], + pending: || false, + scripts: |s| match s { + Script::Tamil => vec![fake_dir().join("tamil.ttf")], + _ => Vec::new(), + }, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: false, + }; + let provider = CraftFontProvider::new(&sources, 1.0); + let tamil = provided(&provider, 'த').expect("Tamil system candidate"); + assert!(tamil.starts_with("craft-system-"), "{tamil}"); + let ethiopic = provided(&provider, 'ሀ').expect("last-resort face"); + assert!(ethiopic.starts_with("craft-system-"), "{ethiopic}"); +} + +static PROVIDER_SCRIPT_CALLS: Mutex> = Mutex::new(Vec::new()); + +fn recorded_provider_files(script: CjkScript) -> Vec { + PROVIDER_SCRIPT_CALLS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(script); + Vec::new() +} + +/// A Hangul character's preferred script is the locale order's first script, so the provider +/// builds a list with Korean twice. It must still ask for Korean's files once, then try each +/// remaining script once, not restart the preferred script after a miss. +#[test] +fn provider_tries_each_script_once_when_the_preferred_script_repeats_the_order() { + PROVIDER_SCRIPT_CALLS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clear(); + let sources = Sources { + locale: || Some("ko_KR".into()), + files: recorded_provider_files, + last_resort: Vec::new, + pending: || false, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: false, + }; + let provider = CraftFontProvider::new(&sources, 1.0); + assert!(provided(&provider, '한').is_none(), "the test source has no Hangul face"); + let calls = PROVIDER_SCRIPT_CALLS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); + assert_eq!(calls, vec![CjkScript::Korean, CjkScript::TraditionalChinese, CjkScript::SimplifiedChinese, CjkScript::Japanese]); +} + +/// An unclassified symbol (not CJK, not one of the non-CJK scripts) only has the optional +/// craft `Zsym` face. Without one the provider must return missing rather than read unrelated +/// system fonts, and an empty cluster is likewise no request at all. +#[test] +fn provider_missing_symbol_and_empty_cluster_do_not_touch_system_fonts() { + let sources = Sources { embedded: no_embedded, ..test_sources(|| Some("en".into())) }; + let provider = CraftFontProvider::new(&sources, 1.0); + assert!(provider.font_for(&FallbackRequest { cluster: "", family: &FontFamily::Proportional }).is_none()); + assert!(provided(&provider, '☃').is_none(), "no injected Zsym craft face covers the symbol"); + let cache = provider.system.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert_eq!(cache.reads, 0, "a symbol is not a CJK or script fallback request"); + assert!(cache.failed_reads.is_empty() && cache.invalid_fonts.is_empty()); +} + +#[test] +fn provider_applies_the_current_scale_to_craft_faces() { + if baseline_face('あ').is_none() { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + return; + } + let provider = test_provider(|| Some("en".into())); + let first = provided_insert(&provider, 'あ').expect("the craft manifest covers kana"); + assert_eq!(first.data.tweak.scale, 1.0); + assert!(first.families.iter().any(|f| f.family == FontFamily::Proportional)); + assert!(first.families.iter().any(|f| f.family == FontFamily::Monospace)); + provider.set_scale(4.0 / 3.0); + let second = provided_insert(&provider, 'あ').expect("the craft face is resolved again at the current scale"); + assert_eq!(second.data.tweak.scale, 4.0 / 3.0, "a craft face must not bake in the scale of an earlier pass"); +} + +/// Face-name metadata is capped independently of the retained-blob budget: forgetting the +/// oldest name only makes egui install that face under a later name, it never drops bytes +/// from a file that still fits. +#[test] +fn system_face_names_are_bounded_independently_of_font_blobs() { + let mut cache = SystemCache::default(); + for i in 0..MAX_SYSTEM_FACE_NAMES + 4 { + cache.remember_face(PathBuf::from(format!("face-{i}.ttf")), i as u32, format!("craft-system-{i}")); + } + assert_eq!(cache.faces.len(), MAX_SYSTEM_FACE_NAMES); + assert_eq!(cache.faces.first().map(|face| face.name.as_str()), Some("craft-system-4"), "the oldest names are evicted first"); + assert_eq!(cache.faces.last().map(|face| face.name.as_str()), Some("craft-system-1027")); + assert!(cache.files.is_empty() && cache.retained_bytes == 0, "face names do not retain or charge font bytes"); +} + +#[test] +fn pending_fontconfig_defers_the_last_resort_instead_of_returning_none_forever() { + PENDING_LAST_RESORT.store(true, std::sync::atomic::Ordering::Relaxed); + let sources = Sources { + locale: || Some("zh-Hant-TW".into()), + files: no_files, + last_resort: || vec![FontFile { path: fake_dir().join("hant.ttf"), family: String::new() }], + pending: pending_last_resort, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: false, + }; + let provider = CraftFontProvider::new(&sources, 1.0); + assert!(provided(&provider, '龍').is_none(), "pending Hant scan must not fall through to a last resort"); + PENDING_LAST_RESORT.store(false, std::sync::atomic::Ordering::Relaxed); + let got = provided(&provider, '龍').expect("after the scan the last resort is usable"); + assert!(got.starts_with("craft-system-"), "{got}"); +} + +#[test] +fn pending_fontconfig_does_not_cache_the_lower_priority_sc_craft_face_for_hant() { + let Some((sc_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans CJK SC") else { + eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); + return; + }; + PENDING_CRAFT_SC.store(true, std::sync::atomic::Ordering::Relaxed); + let sources = Sources { + locale: || Some("zh-Hant-TW".into()), + files: no_files, + last_resort: Vec::new, + pending: pending_craft_sc, + scripts: no_script_files, + covers: scripts::covering_face, + embedded: craft_embedded_iso, + eager_craft_fonts: false, + }; + let provider = CraftFontProvider::new(&sources, 1.0); + assert!(provided(&provider, '龍').is_none(), "a pending Hant scan must not return (and cache) the lower-priority SC craft face"); + PENDING_CRAFT_SC.store(false, std::sync::atomic::Ordering::Relaxed); + let expected = format!("craft-font-{sc_index}"); + assert_eq!(provided(&provider, '龍').as_deref(), Some(expected.as_str())); +} + +#[test] +fn every_craft_face_is_available_to_both_ui_families() { + let mut checked = 0; + for (i, face) in craft_fonts::CRAFT_FONTS.iter().enumerate() { + if face.bytes.is_empty() { + continue; + } + let insert = craft_insert(i, face, 1.0); + assert_eq!(insert.name, format!("craft-font-{i}")); + assert!(insert.families.iter().any(|f| f.family == FontFamily::Proportional), "{} is missing from Proportional", face.family); + assert!(insert.families.iter().any(|f| f.family == FontFamily::Monospace), "{} is missing from Monospace", face.family); + checked += 1; + } + if checked == 0 { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + } +} + +#[test] +fn the_craft_provider_shapes_the_first_headless_frame_in_both_families() { + let Some(ui_font) = craft_fonts::japanese_for_ui().first().copied() else { + eprintln!("skipping: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout)"); + return; + }; + let Some(ui_index) = craft_index(ui_font) else { return }; + let Some((sc_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans CJK SC") else { + eprintln!("skipping: the craft-fonts manifest has no Simplified Chinese face"); + return; + }; + let Some((korean_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "NanumGothic") else { + eprintln!("skipping: the craft-fonts manifest has no Korean face"); + return; + }; + let Some((arabic_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans Arabic") else { + eprintln!("skipping: the craft-fonts manifest has no Arabic face"); + return; + }; + let Some((devanagari_index, _)) = craft_fonts::CRAFT_FONTS.iter().enumerate().find(|(_, f)| f.family == "Noto Sans Devanagari") else { + eprintln!("skipping: the craft-fonts manifest has no Devanagari face"); + return; + }; + let Some(baseline_kana) = baseline_face('か') else { return }; + let Some(baseline_han) = baseline_face('日') else { return }; + let baseline_kana_index = craft_index(baseline_kana).expect("a manifest face has an index"); + let baseline_han_index = craft_index(baseline_han).expect("a manifest face has an index"); + for (locale, text, expected) in [ + ((|| Some("ja_JP".into())) as fn() -> Option, "かな", ui_index), + ((|| Some("en_US".into())) as fn() -> Option, "かな", baseline_kana_index), + ((|| Some("en_US".into())) as fn() -> Option, "日本", baseline_han_index), + ((|| None) as fn() -> Option, "日本", baseline_han_index), + ((|| Some("en_US".into())) as fn() -> Option, "한", korean_index), + ((|| Some("en_US".into())) as fn() -> Option, "مرحبا", arabic_index), + ((|| Some("en_US".into())) as fn() -> Option, "नमस्ते", devanagari_index), + ((|| Some("zh-Hant-TW".into())) as fn() -> Option, "かな", ui_index), + ((|| Some("zh-Hant-TW".into())) as fn() -> Option, "龍", sc_index), + ((|| Some("zh-CN".into())) as fn() -> Option, "中文", sc_index), + ] { + let ctx = egui::Context::default(); + crate::theme::install_fonts_with(&ctx, eager_sources(locale)); + ctx.run_ui(Default::default(), |ui| { + ui.label(text); + ui.label(egui::RichText::new(text).monospace()); + }) + .textures_delta + .clear(); + assert!(ctx.fonts_mut(|f| f.has_glyphs(&FontId::monospace(12.0), text)), "{text} is missing from Monospace"); + let discovered = ctx.fonts(|f| f.discovered_fonts().to_vec()); + assert!( + discovered.iter().any(|insert| insert.name == format!("craft-font-{expected}")), + "{text}: expected craft-font-{expected}, discovered {discovered:?}" + ); + for insert in &discovered { + assert!(insert.families.iter().any(|f| f.family == FontFamily::Proportional), "{insert:?}"); + assert!(insert.families.iter().any(|f| f.family == FontFamily::Monospace), "{insert:?}"); + } + } + // A Traditional Chinese locale has no Hant craft face. A system Hant file, when present, + // must be read before the Simplified Chinese craft fallback. + if hant_system_file().is_some() { + let mut sources = eager_sources((|| Some("zh-Hant-TW".into())) as fn() -> Option); + sources.files = hant_files; + let ctx = egui::Context::default(); + crate::theme::install_fonts_with(&ctx, sources); + ctx.run_ui(Default::default(), |ui| { + ui.label("龍"); + }) + .textures_delta + .clear(); + let discovered = ctx.fonts(|f| f.discovered_fonts().to_vec()); + assert!(discovered.iter().any(|insert| insert.name.starts_with("craft-system-")), "the system Hant face draws the first frame: {discovered:?}"); + assert!( + !discovered.iter().any(|insert| insert.name == format!("craft-font-{sc_index}")), + "the Simplified Chinese face must not pre-empt the Hant system font: {discovered:?}" + ); + } +} + +#[test] +fn ui_works_without_craft_fonts() { + // The pre-craft-fonts behaviour: no embedded fonts, no system fonts. Latin renders, + // Japanese is tried (and stays missing) without panicking, and the loader exhausts. + let ctx = egui::Context::default(); + crate::theme::install_fonts_with( + &ctx, + Sources { + locale: || None, + files: |_| vec![], + last_resort: Vec::new, + pending: || false, + scripts: |_| Vec::new(), + covers: scripts::covering_face, + embedded: no_embedded, + eager_craft_fonts: false, + }, + ); + assert!(render(&ctx, "Layer 1 – café")); + assert!(!render(&ctx, "日本語の文字")); + let n = ctx.fonts(|f| f.definitions().font_data.keys().filter(|k| k.starts_with(FONT_PREFIX)).count()); + assert_eq!(n, 0); + if craft_fonts::CRAFT_FONTS.is_empty() { + assert!(craft_embedded(CjkScript::Japanese).is_empty()); + } +} + +/// With the real system fonts, every CJK sample renders (skipped per script when the +/// machine has no font for it, e.g. CI Linux without Noto CJK). +#[test] +fn system_fonts_cover_cjk_samples() { + #[cfg(target_os = "linux")] + assert!(wait_for_fontconfig_cjk_scan(), "Fontconfig CJK lookup did not finish within 10 seconds"); + let available = |s: CjkScript| cjk::font_files(s).iter().any(|f| f.path.is_file()); + let samples = + [("图层", CjkScript::SimplifiedChinese), ("圖層", CjkScript::TraditionalChinese), ("카드 배경", CjkScript::Korean), ("レイヤー", CjkScript::Japanese)]; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + for (text, script) in samples { + if !available(script) { + eprintln!("skipping {text}: no {script:?} system font"); + continue; + } + assert!(render(&ctx, text), "{text} still has missing glyphs"); + } + // All at once in a fresh context too (several scripts in one frame). + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let all: String = samples.iter().filter(|(_, s)| available(*s)).map(|(t, _)| *t).collect::>().join(" "); + assert!(render(&ctx, &all), "{all}"); +} From 595662913883b6d20a25e3d930ca7662379c22e8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:05 +0000 Subject: [PATCH 084/259] refactor(ui-egui): move gallery_ui.rs tests to gallery_ui/tests.rs --- crates/ui-egui/src/gallery_ui.rs | 369 +------------------------ crates/ui-egui/src/gallery_ui/tests.rs | 366 ++++++++++++++++++++++++ 2 files changed, 367 insertions(+), 368 deletions(-) create mode 100644 crates/ui-egui/src/gallery_ui/tests.rs diff --git a/crates/ui-egui/src/gallery_ui.rs b/crates/ui-egui/src/gallery_ui.rs index aade41f2e9..d37eec865d 100644 --- a/crates/ui-egui/src/gallery_ui.rs +++ b/crates/ui-egui/src/gallery_ui.rs @@ -891,371 +891,4 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { } #[cfg(test)] -mod tests { - use super::*; - - fn app() -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", json!({"width": 90, "height": 60, "depth": 16})).unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, active| { - let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in 0..60 { - for x in 0..90 { - let v = ((x / 6 + y / 6) % 2) as f32; - s.write_pixel(x, y, &[v, 0.4, 1.0 - v, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - app.sync_views(); - app - } - - /// ⌘+ / ⌘− step the preview along the canvas's zoom ladder as Liquify's do, from the zoom Fit - /// in View shows; ⌘0 fits it and ⌘1 is 100 %, through the canvas's own shortcuts; the canvas - /// behind keeps its zoom. - #[test] - fn zoom_shortcuts_zoom_the_preview_not_the_canvas() { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - // Large enough that Fit in View is well under 100 % in a 1000 × 700 window. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", json!({"width": 3000, "height": 2000})).unwrap(); - app.sync_views(); - open(&mut app).unwrap(); - let canvas_zoom = app.ui.views.first().map(|v| v.zoom); - let mut run = |key: Option| { - let events = key - .map(|key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }) - .into_iter() - .collect(); - let screen = ERect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 700.0)); - let raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| { - crate::shortcuts::handle(&mut app, ui.ctx()); - show(&mut app, ui.ctx()); - }); - out.textures_delta.clear(); - let d = app.distort.gallery.as_ref().unwrap(); - (d.zoom, d.fit) - }; - let (zoom, fit) = run(None); - assert_eq!(zoom, 0.0, "opens at Fit in View"); - assert!(fit > 0.0 && fit < 0.5, "fits a 3000 px image well under 100 %: {fit}"); - let step = |z, dir| crate::zoom_levels::step_in_range(z, dir, ZOOM_MIN, ZOOM_MAX); - let (zoom, _) = run(Some(egui::Key::Equals)); - assert_eq!(zoom, step(fit, 1), "⌘= steps up from the fitted zoom, not from the menu's first entry"); - assert!(zoom > fit); - assert_eq!(run(Some(egui::Key::Plus)).0, step(step(fit, 1), 1), "⌘+ typed as Plus too"); - assert_eq!(run(Some(egui::Key::Num0)).0, 0.0, "Fit in View"); - assert!(run(Some(egui::Key::Minus)).0 < fit, "⌘− steps down from the fitted zoom"); - assert_eq!(run(Some(egui::Key::Num1)).0, 1.0); - assert_eq!(run(Some(egui::Key::Equals)).0, 2.0); - assert_eq!(run(Some(egui::Key::Equals)).0, 3.0, "past the menu's steps, on the canvas's ladder"); - assert_eq!(run(Some(egui::Key::Minus)).0, 2.0); - assert!(app.distort.gallery.is_some(), "the dialog stays open"); - assert_eq!(app.ui.views.first().map(|v| v.zoom), canvas_zoom, "the canvas behind keeps its zoom"); - } - - /// A huge image can fit below the 1 % minimum: Zoom Out keeps Fit in View rather than - /// enlarging it to 1 %, and Zoom In still steps up from there. - #[test] - fn zoom_out_from_a_fit_below_the_minimum_stays_at_fit() { - let mut app = app(); - open(&mut app).unwrap(); - let d = app.distort.gallery.as_mut().unwrap(); - d.zoom = 0.0; - d.fit = 0.005; - assert_eq!(step_zoom(d, -1), 0.0, "no smaller zoom than Fit: stays at Fit in View"); - assert!(step_zoom(d, 1) > d.fit); - d.fit = 0.05; - assert!(step_zoom(d, -1) > 0.0 && step_zoom(d, -1) < 0.05, "a Fit above the minimum still steps down"); - } - - #[test] - fn stack_editing_and_commit_match_the_engine() { - let ctx = egui::Context::default(); - let mut app = app(); - let r = crate::distort_ui::menu(&mut app, &ctx, "filter.filterGallery", &json!({})).unwrap().unwrap(); - assert_eq!(r["gallery"]["effects"].as_array().unwrap().len(), 1); - control(&mut app, &json!({"filter": "cutout", "params": {"numberOfLevels": 3}})).unwrap(); - control(&mut app, &json!({"add": true})).unwrap(); - control(&mut app, &json!({"filter": "texturizer", "params": {"texture": "brick", "relief": 20}})).unwrap(); - control(&mut app, &json!({"add": true})).unwrap(); - control(&mut app, &json!({"filter": "glowingEdges"})).unwrap(); - control(&mut app, &json!({"toggle": 2})).unwrap(); - let d = control(&mut app, &json!({"move": {"from": 1, "to": 0}})).unwrap(); - let keys: Vec<&str> = d["effects"].as_array().unwrap().iter().map(|e| e["filter"].as_str().unwrap()).collect(); - assert_eq!(keys, ["texturizer", "cutout", "glowingEdges"]); - assert_eq!(d["effects"][2]["visible"], json!(false)); - // Preview pixels = engine result on the same pixels. - let params = app.distort.gallery.as_ref().unwrap().params(); - let before = app.session.active().unwrap().history.past_len(); - control(&mut app, &json!({"commit": true})).unwrap(); - assert!(app.distort.gallery.is_none()); - assert_eq!(app.session.active().unwrap().history.past_len(), before + 1); - let (id, p) = app.session.journal.last().cloned().unwrap(); - assert_eq!(id, "filter.filterGallery"); - assert_eq!(p["effects"], params["effects"]); - // Re-opening starts from the last stack. - crate::distort_ui::menu(&mut app, &ctx, "filter.filterGallery", &json!({})).unwrap().unwrap(); - assert_eq!(app.distort.gallery.as_ref().unwrap().effects.len(), 3); - control(&mut app, &json!({"delete": true})).unwrap(); - assert_eq!(app.distort.gallery.as_ref().unwrap().effects.len(), 2); - control(&mut app, &json!({"cancel": true})).unwrap(); - assert_eq!(app.session.active().unwrap().history.past_len(), before + 1, "cancel records nothing"); - } - - #[test] - fn smart_filter_double_click_edits_the_stored_gallery_stack() { - let ctx = egui::Context::default(); - let mut app = app(); - app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let stack = json!({"effects": [{"filter": "chrome", "params": {"detail": 2, "smoothness": 9}, "visible": true}], "foreground": [1.0, 0.0, 0.0, 1.0], "background": [0.0, 0.0, 1.0, 1.0]}); - app.run("filter.filterGallery", stack).unwrap(); - app.run("filter.blur.gaussianBlur", json!({"radius": 2.0})).unwrap(); - let layer = app.session.active().unwrap().active_layer.unwrap(); - let smart = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(layer).unwrap().content { - photocraft_doc::LayerContent::Smart(sm) => sm.clone(), - _ => panic!("not a smart object"), - }; - let steps = app.session.active().unwrap().history.past_len(); - - let sm = smart(&app); - crate::smart_ui::open_editor(&mut app, &ctx, layer.0, &sm, 0); - assert!(app.ui.dialogs.is_empty(), "no generic parameter form"); - let d = app.distort.gallery.as_ref().expect("the gallery dialog opens"); - assert_eq!((d.smart_filter, d.foreground, d.background), (Some(0), [1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0])); - assert_eq!(d.effects.len(), 1); - assert_eq!((d.effects[0].filter, &d.effects[0].params["detail"]), (GalleryFilter::Chrome, &json!(2))); - // The preview starts from the pixels below the filter (no blur, no chrome). - let below = photocraft_engine::smart_cmds::render_below_filter(&app.session.active().unwrap().doc, &sm, 0).unwrap().unwrap(); - let d = app.distort.gallery.as_ref().unwrap(); - assert_eq!(d.src.read_region(d.canvas), below.read_region(d.canvas)); - - control(&mut app, &json!({"params": {"detail": 7}})).unwrap(); - control(&mut app, &json!({"commit": true})).unwrap(); - assert!(app.distort.gallery.is_none()); - let sm = smart(&app); - assert_eq!(sm.smart_filters.len(), 2, "edited in place, not added"); - assert_eq!(sm.smart_filters[0].command, "filter.filterGallery"); - assert_eq!(sm.smart_filters[0].params["effects"][0]["params"]["detail"], json!(7)); - assert_eq!(sm.smart_filters[0].params["foreground"], json!([1.0, 0.0, 0.0, 1.0])); - assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(smart(&app).smart_filters[0].params["effects"][0]["params"]["detail"], json!(2)); - - // Not a gallery filter / no such filter: an error, no dialog. - assert!(open_smart_filter(&mut app, layer, 1).is_err()); - assert!(open_smart_filter(&mut app, layer, 9).is_err()); - assert!(app.distort.gallery.is_none()); - } - - #[test] - fn preview_and_thumbnails_render() { - let ctx = egui::Context::default(); - let mut app = app(); - open(&mut app).unwrap(); - let d = app.distort.gallery.as_mut().unwrap(); - update_preview(d, &ctx, ERect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)), false); - assert!(d.tex.is_some() && d.shown.is_some()); - d.open = [true; 6]; - update_thumbs(d, &ctx, 100); - assert!(d.thumbs.iter().all(Option::is_some)); - // Preview equals the engine's algorithm on the sampled pixels. - let src = sample(&d.src, d.canvas, 1); - let a = render(&src, &d.params()); - let mut s2 = photocraft_engine::Session::new(); - s2.add_document(app.session.active().unwrap().doc.as_ref().clone(), None); - s2.select_layer(d.layer).unwrap(); - s2.execute("filter.filterGallery", d.params()).unwrap(); - let st = s2.active().unwrap(); - let b = st.doc.layer(d.layer).unwrap().surface().unwrap().read_region(d.canvas); - let worst = a.read_region(d.canvas).iter().zip(&b).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max); - assert!(worst < 2e-3, "preview differs from the result by {worst}"); - } - - /// A 240×160 layer with gradients, edges and fine detail, so every gallery filter has - /// something to draw. - fn photo_app() -> PhotocraftApp { - let (w, h) = (240, 160); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", json!({"width": w, "height": h, "depth": 16})).unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, active| { - let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in 0..h { - for x in 0..w { - let (u, v) = (x as f32 / w as f32, y as f32 / h as f32); - let disc = (((x - 150) * (x - 150) + (y - 70) * (y - 70)) < 45 * 45) as i32 as f32; - let stripes = ((x + y) / 11 % 2) as f32; - s.write_pixel(x, y, &[u * 0.8 + disc * 0.2, 0.25 + 0.5 * stripes * (1.0 - disc), v * (1.0 - disc) + disc * 0.9, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - app.sync_views(); - app - } - - /// What OK applies: `filter.filterGallery` with the dialog's stack on a copy of the document. - fn applied(app: &PhotocraftApp, d: &GalleryDialog) -> Surface { - let mut s2 = photocraft_engine::Session::new(); - s2.add_document(app.session.active().unwrap().doc.as_ref().clone(), None); - s2.select_layer(d.layer).unwrap(); - s2.execute("filter.filterGallery", d.params()).unwrap(); - s2.active().unwrap().doc.layer(d.layer).unwrap().surface().unwrap().clone() - } - - /// Mean of `k`×`k` blocks (opaque layers), written independently of [`reduce`]. - fn box_mean(surf: &Surface, r: Rect, k: i32) -> Vec { - let mut out = Vec::new(); - let mut px = [0.0f32; 4]; - for by in (r.y0..r.y1).step_by(k as usize) { - for bx in (r.x0..r.x1).step_by(k as usize) { - let mut sum = [0.0f32; 4]; - let mut n = 0.0; - for y in by..(by + k).min(r.y1) { - for x in bx..(bx + k).min(r.x1) { - surf.read_pixel(x, y, &mut px); - sum.iter_mut().zip(px).for_each(|(s, v)| *s += v); - n += 1.0; - } - } - out.extend(sum.map(|s| s / n)); - } - } - out - } - - /// Mean absolute RGB difference. - fn mean_diff(a: &[f32], b: &[f32]) -> f32 { - assert_eq!(a.len(), b.len()); - let (sum, n) = a.chunks(4).zip(b.chunks(4)).fold((0.0, 0.0), |(s, n), (p, q)| (s + (0..3).map(|c| (p[c] - q[c]).abs()).sum::(), n + 3.0)); - sum / n - } - - #[test] - fn zoomed_out_preview_matches_the_applied_result_scaled_down() { - // #2502: below 100 % the preview filtered every k-th pixel with the same params, so - // strokes, grain and textures showed several times too large. - let ctx = egui::Context::default(); - let mut app = photo_app(); - open(&mut app).unwrap(); - let area = ERect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)); - for f in ["graphicPen", "charcoal", "reticulation", "stainedGlass", "spatter", "chalkCharcoal"] { - control(&mut app, &json!({"filter": f, "zoom": 0.25})).unwrap(); - let reference = { - let d = app.distort.gallery.as_ref().unwrap(); - box_mean(&applied(&app, d), d.canvas, 4) - }; - let d = app.distort.gallery.as_mut().unwrap(); - let (_, vis, k) = view(d, area); - assert_eq!((vis, k), (d.canvas, 4), "{f}: at 25 % the whole layer shows, averaged 4×4"); - assert!(update_preview(d, &ctx, area, false).is_some()); - let shown = preview_pixels(&d.src, d.canvas, &d.params(), vis, k, &Interrupt::NONE).unwrap(); - let (w, h) = (reduced(vis.width(), k) as i32, reduced(vis.height(), k) as i32); - let diff = mean_diff(&shown.read_region(Rect::new(0, 0, w, h)), &reference); - // The old preview (every 4th pixel, filtered at that size) for comparison. - let old = mean_diff(&render(&sample(&d.src, vis, k), &d.params()).read_region(Rect::new(0, 0, w, h)), &reference); - assert!(diff < 1e-3, "{f}: preview differs from the applied result by {diff}"); - assert!(old > 20.0 * diff.max(1e-3), "{f}: the old preview differed by only {old}"); - } - } - - #[test] - fn a_region_renders_the_same_pixels_as_the_full_result() { - // Zoomed in, only the visible part renders: noise, cells and textures are seeded by - // document position, and the filters read their reach around the region. - let mut app = photo_app(); - open(&mut app).unwrap(); - let region = Rect::new(37, 21, 151, 117); - for f in GalleryFilter::ALL { - control(&mut app, &json!({"filter": f.key()})).unwrap(); - let d = app.distort.gallery.as_ref().unwrap(); - let full = applied(&app, d).read_region(region); - let part = preview_pixels(&d.src, d.canvas, &d.params(), region, 1, &Interrupt::NONE).unwrap(); - let part = part.read_region(Rect::new(0, 0, region.width() as i32, region.height() as i32)); - let worst = full.iter().zip(&part).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); - assert!(worst < 1e-3, "{}: region differs from the full result by {worst}", f.key()); - } - } - - #[test] - fn reduce_averages_blocks_weighted_by_alpha() { - let mut s = Surface::new(photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::F32, true)); - s.write_pixel(0, 0, &[1.0, 0.0, 0.0, 1.0]); - s.write_pixel(1, 0, &[0.0, 1.0, 0.0, 0.0]); // transparent: its colour doesn't count - s.write_pixel(2, 0, &[0.2, 0.4, 0.6, 1.0]); // a partial block at the edge - let r = reduce(&s, Rect::new(0, 0, 3, 2), 2).read_region(Rect::new(0, 0, 2, 1)); - assert_eq!(r, [1.0, 0.0, 0.0, 0.25, 0.2, 0.4, 0.6, 0.5]); - assert_eq!(reduce(&s, Rect::EMPTY, 2).content_bounds(), Rect::EMPTY); - } - - #[test] - fn background_preview_renders_off_the_ui_thread() { - let ctx = egui::Context::default(); - let mut app = photo_app(); - open(&mut app).unwrap(); - control(&mut app, &json!({"filter": "graphicPen"})).unwrap(); - let d = app.distort.gallery.as_mut().unwrap(); - let area = ERect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)); - assert!(update_preview(d, &ctx, area, true).is_none(), "nothing to show until the first render is done"); - assert!(d.describe()["rendering"].as_bool().unwrap()); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - while d.rendering().is_some() { - assert!(std::time::Instant::now() < deadline, "the preview never finished"); - std::thread::sleep(std::time::Duration::from_millis(5)); - update_preview(d, &ctx, area, true); - } - assert!(d.tex.is_some() && update_preview(d, &ctx, area, true).is_some()); - // A new setting starts a new render; the last preview stays up meanwhile. - let before = d.cur().params.get("strokeLength").cloned().unwrap(); - d.cur().params.insert("strokeLength".into(), json!(5)); - assert!(update_preview(d, &ctx, area, true).is_some()); - assert!(d.rendering().is_some()); - // Back to the settings on screen: that render is dropped (and cancelled). - d.cur().params.insert("strokeLength".into(), before); - assert!(update_preview(d, &ctx, area, true).is_some()); - assert!(d.rendering().is_none()); - d.cur().params.insert("strokeLength".into(), json!(5)); - update_preview(d, &ctx, area, true); - // Closing the dialog cancels it. - app.distort.gallery = None; - } - - /// Preview cost on 24 MP: `cargo test -p photocraft-ui-egui --lib bench_gallery_preview -- --ignored --nocapture`. - #[test] - #[ignore] - fn bench_gallery_preview() { - let (w, h) = (6000, 4000); - let canvas = Rect::new(0, 0, w, h); - let mut s = Surface::new(photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, true)); - s.fill_rect(canvas, &[0.5, 0.4, 0.3, 1.0]); - for y in (0..h).step_by(9) { - s.fill_rect(Rect::new(0, y, w, y + 3), &[0.9, 0.8, 0.2, 1.0]); - } - let ms = |t: std::time::Instant| t.elapsed().as_secs_f64() * 1000.0; - let t = std::time::Instant::now(); - std::hint::black_box(reduce(&s, canvas, 8)); - println!("{:>14}: {:>7.0} ms", "reduce 1/8", ms(t)); - for f in ["graphicPen", "charcoal", "reticulation", "stainedGlass", "spatter", "roughPastels"] { - let p = json!({"effects": [{"filter": f}]}); - let t = std::time::Instant::now(); - std::hint::black_box(render(&sample(&s, canvas, 8), &p)); - let old = ms(t); - let t = std::time::Instant::now(); - std::hint::black_box(preview_pixels(&s, canvas, &p, canvas, 8, &Interrupt::NONE)); - let fit = ms(t); - let t = std::time::Instant::now(); - std::hint::black_box(preview_pixels(&s, canvas, &p, Rect::new(2400, 1600, 3500, 2400), 1, &Interrupt::NONE)); - let screen = ms(t); - println!("{f:>14}: old fit {old:>5.0} ms, new fit {fit:>6.0} ms, new 100 % (1100x800) {screen:>5.0} ms"); - } - } -} +mod tests; diff --git a/crates/ui-egui/src/gallery_ui/tests.rs b/crates/ui-egui/src/gallery_ui/tests.rs new file mode 100644 index 0000000000..456be95588 --- /dev/null +++ b/crates/ui-egui/src/gallery_ui/tests.rs @@ -0,0 +1,366 @@ +use super::*; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 90, "height": 60, "depth": 16})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, active| { + let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..60 { + for x in 0..90 { + let v = ((x / 6 + y / 6) % 2) as f32; + s.write_pixel(x, y, &[v, 0.4, 1.0 - v, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + app.sync_views(); + app +} + +/// ⌘+ / ⌘− step the preview along the canvas's zoom ladder as Liquify's do, from the zoom Fit +/// in View shows; ⌘0 fits it and ⌘1 is 100 %, through the canvas's own shortcuts; the canvas +/// behind keeps its zoom. +#[test] +fn zoom_shortcuts_zoom_the_preview_not_the_canvas() { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + // Large enough that Fit in View is well under 100 % in a 1000 × 700 window. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 3000, "height": 2000})).unwrap(); + app.sync_views(); + open(&mut app).unwrap(); + let canvas_zoom = app.ui.views.first().map(|v| v.zoom); + let mut run = |key: Option| { + let events = key + .map(|key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }) + .into_iter() + .collect(); + let screen = ERect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 700.0)); + let raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + show(&mut app, ui.ctx()); + }); + out.textures_delta.clear(); + let d = app.distort.gallery.as_ref().unwrap(); + (d.zoom, d.fit) + }; + let (zoom, fit) = run(None); + assert_eq!(zoom, 0.0, "opens at Fit in View"); + assert!(fit > 0.0 && fit < 0.5, "fits a 3000 px image well under 100 %: {fit}"); + let step = |z, dir| crate::zoom_levels::step_in_range(z, dir, ZOOM_MIN, ZOOM_MAX); + let (zoom, _) = run(Some(egui::Key::Equals)); + assert_eq!(zoom, step(fit, 1), "⌘= steps up from the fitted zoom, not from the menu's first entry"); + assert!(zoom > fit); + assert_eq!(run(Some(egui::Key::Plus)).0, step(step(fit, 1), 1), "⌘+ typed as Plus too"); + assert_eq!(run(Some(egui::Key::Num0)).0, 0.0, "Fit in View"); + assert!(run(Some(egui::Key::Minus)).0 < fit, "⌘− steps down from the fitted zoom"); + assert_eq!(run(Some(egui::Key::Num1)).0, 1.0); + assert_eq!(run(Some(egui::Key::Equals)).0, 2.0); + assert_eq!(run(Some(egui::Key::Equals)).0, 3.0, "past the menu's steps, on the canvas's ladder"); + assert_eq!(run(Some(egui::Key::Minus)).0, 2.0); + assert!(app.distort.gallery.is_some(), "the dialog stays open"); + assert_eq!(app.ui.views.first().map(|v| v.zoom), canvas_zoom, "the canvas behind keeps its zoom"); +} + +/// A huge image can fit below the 1 % minimum: Zoom Out keeps Fit in View rather than +/// enlarging it to 1 %, and Zoom In still steps up from there. +#[test] +fn zoom_out_from_a_fit_below_the_minimum_stays_at_fit() { + let mut app = app(); + open(&mut app).unwrap(); + let d = app.distort.gallery.as_mut().unwrap(); + d.zoom = 0.0; + d.fit = 0.005; + assert_eq!(step_zoom(d, -1), 0.0, "no smaller zoom than Fit: stays at Fit in View"); + assert!(step_zoom(d, 1) > d.fit); + d.fit = 0.05; + assert!(step_zoom(d, -1) > 0.0 && step_zoom(d, -1) < 0.05, "a Fit above the minimum still steps down"); +} + +#[test] +fn stack_editing_and_commit_match_the_engine() { + let ctx = egui::Context::default(); + let mut app = app(); + let r = crate::distort_ui::menu(&mut app, &ctx, "filter.filterGallery", &json!({})).unwrap().unwrap(); + assert_eq!(r["gallery"]["effects"].as_array().unwrap().len(), 1); + control(&mut app, &json!({"filter": "cutout", "params": {"numberOfLevels": 3}})).unwrap(); + control(&mut app, &json!({"add": true})).unwrap(); + control(&mut app, &json!({"filter": "texturizer", "params": {"texture": "brick", "relief": 20}})).unwrap(); + control(&mut app, &json!({"add": true})).unwrap(); + control(&mut app, &json!({"filter": "glowingEdges"})).unwrap(); + control(&mut app, &json!({"toggle": 2})).unwrap(); + let d = control(&mut app, &json!({"move": {"from": 1, "to": 0}})).unwrap(); + let keys: Vec<&str> = d["effects"].as_array().unwrap().iter().map(|e| e["filter"].as_str().unwrap()).collect(); + assert_eq!(keys, ["texturizer", "cutout", "glowingEdges"]); + assert_eq!(d["effects"][2]["visible"], json!(false)); + // Preview pixels = engine result on the same pixels. + let params = app.distort.gallery.as_ref().unwrap().params(); + let before = app.session.active().unwrap().history.past_len(); + control(&mut app, &json!({"commit": true})).unwrap(); + assert!(app.distort.gallery.is_none()); + assert_eq!(app.session.active().unwrap().history.past_len(), before + 1); + let (id, p) = app.session.journal.last().cloned().unwrap(); + assert_eq!(id, "filter.filterGallery"); + assert_eq!(p["effects"], params["effects"]); + // Re-opening starts from the last stack. + crate::distort_ui::menu(&mut app, &ctx, "filter.filterGallery", &json!({})).unwrap().unwrap(); + assert_eq!(app.distort.gallery.as_ref().unwrap().effects.len(), 3); + control(&mut app, &json!({"delete": true})).unwrap(); + assert_eq!(app.distort.gallery.as_ref().unwrap().effects.len(), 2); + control(&mut app, &json!({"cancel": true})).unwrap(); + assert_eq!(app.session.active().unwrap().history.past_len(), before + 1, "cancel records nothing"); +} + +#[test] +fn smart_filter_double_click_edits_the_stored_gallery_stack() { + let ctx = egui::Context::default(); + let mut app = app(); + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let stack = json!({"effects": [{"filter": "chrome", "params": {"detail": 2, "smoothness": 9}, "visible": true}], "foreground": [1.0, 0.0, 0.0, 1.0], "background": [0.0, 0.0, 1.0, 1.0]}); + app.run("filter.filterGallery", stack).unwrap(); + app.run("filter.blur.gaussianBlur", json!({"radius": 2.0})).unwrap(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + let smart = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(layer).unwrap().content { + photocraft_doc::LayerContent::Smart(sm) => sm.clone(), + _ => panic!("not a smart object"), + }; + let steps = app.session.active().unwrap().history.past_len(); + + let sm = smart(&app); + crate::smart_ui::open_editor(&mut app, &ctx, layer.0, &sm, 0); + assert!(app.ui.dialogs.is_empty(), "no generic parameter form"); + let d = app.distort.gallery.as_ref().expect("the gallery dialog opens"); + assert_eq!((d.smart_filter, d.foreground, d.background), (Some(0), [1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0])); + assert_eq!(d.effects.len(), 1); + assert_eq!((d.effects[0].filter, &d.effects[0].params["detail"]), (GalleryFilter::Chrome, &json!(2))); + // The preview starts from the pixels below the filter (no blur, no chrome). + let below = photocraft_engine::smart_cmds::render_below_filter(&app.session.active().unwrap().doc, &sm, 0).unwrap().unwrap(); + let d = app.distort.gallery.as_ref().unwrap(); + assert_eq!(d.src.read_region(d.canvas), below.read_region(d.canvas)); + + control(&mut app, &json!({"params": {"detail": 7}})).unwrap(); + control(&mut app, &json!({"commit": true})).unwrap(); + assert!(app.distort.gallery.is_none()); + let sm = smart(&app); + assert_eq!(sm.smart_filters.len(), 2, "edited in place, not added"); + assert_eq!(sm.smart_filters[0].command, "filter.filterGallery"); + assert_eq!(sm.smart_filters[0].params["effects"][0]["params"]["detail"], json!(7)); + assert_eq!(sm.smart_filters[0].params["foreground"], json!([1.0, 0.0, 0.0, 1.0])); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(smart(&app).smart_filters[0].params["effects"][0]["params"]["detail"], json!(2)); + + // Not a gallery filter / no such filter: an error, no dialog. + assert!(open_smart_filter(&mut app, layer, 1).is_err()); + assert!(open_smart_filter(&mut app, layer, 9).is_err()); + assert!(app.distort.gallery.is_none()); +} + +#[test] +fn preview_and_thumbnails_render() { + let ctx = egui::Context::default(); + let mut app = app(); + open(&mut app).unwrap(); + let d = app.distort.gallery.as_mut().unwrap(); + update_preview(d, &ctx, ERect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)), false); + assert!(d.tex.is_some() && d.shown.is_some()); + d.open = [true; 6]; + update_thumbs(d, &ctx, 100); + assert!(d.thumbs.iter().all(Option::is_some)); + // Preview equals the engine's algorithm on the sampled pixels. + let src = sample(&d.src, d.canvas, 1); + let a = render(&src, &d.params()); + let mut s2 = photocraft_engine::Session::new(); + s2.add_document(app.session.active().unwrap().doc.as_ref().clone(), None); + s2.select_layer(d.layer).unwrap(); + s2.execute("filter.filterGallery", d.params()).unwrap(); + let st = s2.active().unwrap(); + let b = st.doc.layer(d.layer).unwrap().surface().unwrap().read_region(d.canvas); + let worst = a.read_region(d.canvas).iter().zip(&b).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max); + assert!(worst < 2e-3, "preview differs from the result by {worst}"); +} + +/// A 240×160 layer with gradients, edges and fine detail, so every gallery filter has +/// something to draw. +fn photo_app() -> PhotocraftApp { + let (w, h) = (240, 160); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": w, "height": h, "depth": 16})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, active| { + let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..h { + for x in 0..w { + let (u, v) = (x as f32 / w as f32, y as f32 / h as f32); + let disc = (((x - 150) * (x - 150) + (y - 70) * (y - 70)) < 45 * 45) as i32 as f32; + let stripes = ((x + y) / 11 % 2) as f32; + s.write_pixel(x, y, &[u * 0.8 + disc * 0.2, 0.25 + 0.5 * stripes * (1.0 - disc), v * (1.0 - disc) + disc * 0.9, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + app.sync_views(); + app +} + +/// What OK applies: `filter.filterGallery` with the dialog's stack on a copy of the document. +fn applied(app: &PhotocraftApp, d: &GalleryDialog) -> Surface { + let mut s2 = photocraft_engine::Session::new(); + s2.add_document(app.session.active().unwrap().doc.as_ref().clone(), None); + s2.select_layer(d.layer).unwrap(); + s2.execute("filter.filterGallery", d.params()).unwrap(); + s2.active().unwrap().doc.layer(d.layer).unwrap().surface().unwrap().clone() +} + +/// Mean of `k`×`k` blocks (opaque layers), written independently of [`reduce`]. +fn box_mean(surf: &Surface, r: Rect, k: i32) -> Vec { + let mut out = Vec::new(); + let mut px = [0.0f32; 4]; + for by in (r.y0..r.y1).step_by(k as usize) { + for bx in (r.x0..r.x1).step_by(k as usize) { + let mut sum = [0.0f32; 4]; + let mut n = 0.0; + for y in by..(by + k).min(r.y1) { + for x in bx..(bx + k).min(r.x1) { + surf.read_pixel(x, y, &mut px); + sum.iter_mut().zip(px).for_each(|(s, v)| *s += v); + n += 1.0; + } + } + out.extend(sum.map(|s| s / n)); + } + } + out +} + +/// Mean absolute RGB difference. +fn mean_diff(a: &[f32], b: &[f32]) -> f32 { + assert_eq!(a.len(), b.len()); + let (sum, n) = a.chunks(4).zip(b.chunks(4)).fold((0.0, 0.0), |(s, n), (p, q)| (s + (0..3).map(|c| (p[c] - q[c]).abs()).sum::(), n + 3.0)); + sum / n +} + +#[test] +fn zoomed_out_preview_matches_the_applied_result_scaled_down() { + // #2502: below 100 % the preview filtered every k-th pixel with the same params, so + // strokes, grain and textures showed several times too large. + let ctx = egui::Context::default(); + let mut app = photo_app(); + open(&mut app).unwrap(); + let area = ERect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)); + for f in ["graphicPen", "charcoal", "reticulation", "stainedGlass", "spatter", "chalkCharcoal"] { + control(&mut app, &json!({"filter": f, "zoom": 0.25})).unwrap(); + let reference = { + let d = app.distort.gallery.as_ref().unwrap(); + box_mean(&applied(&app, d), d.canvas, 4) + }; + let d = app.distort.gallery.as_mut().unwrap(); + let (_, vis, k) = view(d, area); + assert_eq!((vis, k), (d.canvas, 4), "{f}: at 25 % the whole layer shows, averaged 4×4"); + assert!(update_preview(d, &ctx, area, false).is_some()); + let shown = preview_pixels(&d.src, d.canvas, &d.params(), vis, k, &Interrupt::NONE).unwrap(); + let (w, h) = (reduced(vis.width(), k) as i32, reduced(vis.height(), k) as i32); + let diff = mean_diff(&shown.read_region(Rect::new(0, 0, w, h)), &reference); + // The old preview (every 4th pixel, filtered at that size) for comparison. + let old = mean_diff(&render(&sample(&d.src, vis, k), &d.params()).read_region(Rect::new(0, 0, w, h)), &reference); + assert!(diff < 1e-3, "{f}: preview differs from the applied result by {diff}"); + assert!(old > 20.0 * diff.max(1e-3), "{f}: the old preview differed by only {old}"); + } +} + +#[test] +fn a_region_renders_the_same_pixels_as_the_full_result() { + // Zoomed in, only the visible part renders: noise, cells and textures are seeded by + // document position, and the filters read their reach around the region. + let mut app = photo_app(); + open(&mut app).unwrap(); + let region = Rect::new(37, 21, 151, 117); + for f in GalleryFilter::ALL { + control(&mut app, &json!({"filter": f.key()})).unwrap(); + let d = app.distort.gallery.as_ref().unwrap(); + let full = applied(&app, d).read_region(region); + let part = preview_pixels(&d.src, d.canvas, &d.params(), region, 1, &Interrupt::NONE).unwrap(); + let part = part.read_region(Rect::new(0, 0, region.width() as i32, region.height() as i32)); + let worst = full.iter().zip(&part).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(worst < 1e-3, "{}: region differs from the full result by {worst}", f.key()); + } +} + +#[test] +fn reduce_averages_blocks_weighted_by_alpha() { + let mut s = Surface::new(photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::F32, true)); + s.write_pixel(0, 0, &[1.0, 0.0, 0.0, 1.0]); + s.write_pixel(1, 0, &[0.0, 1.0, 0.0, 0.0]); // transparent: its colour doesn't count + s.write_pixel(2, 0, &[0.2, 0.4, 0.6, 1.0]); // a partial block at the edge + let r = reduce(&s, Rect::new(0, 0, 3, 2), 2).read_region(Rect::new(0, 0, 2, 1)); + assert_eq!(r, [1.0, 0.0, 0.0, 0.25, 0.2, 0.4, 0.6, 0.5]); + assert_eq!(reduce(&s, Rect::EMPTY, 2).content_bounds(), Rect::EMPTY); +} + +#[test] +fn background_preview_renders_off_the_ui_thread() { + let ctx = egui::Context::default(); + let mut app = photo_app(); + open(&mut app).unwrap(); + control(&mut app, &json!({"filter": "graphicPen"})).unwrap(); + let d = app.distort.gallery.as_mut().unwrap(); + let area = ERect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)); + assert!(update_preview(d, &ctx, area, true).is_none(), "nothing to show until the first render is done"); + assert!(d.describe()["rendering"].as_bool().unwrap()); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while d.rendering().is_some() { + assert!(std::time::Instant::now() < deadline, "the preview never finished"); + std::thread::sleep(std::time::Duration::from_millis(5)); + update_preview(d, &ctx, area, true); + } + assert!(d.tex.is_some() && update_preview(d, &ctx, area, true).is_some()); + // A new setting starts a new render; the last preview stays up meanwhile. + let before = d.cur().params.get("strokeLength").cloned().unwrap(); + d.cur().params.insert("strokeLength".into(), json!(5)); + assert!(update_preview(d, &ctx, area, true).is_some()); + assert!(d.rendering().is_some()); + // Back to the settings on screen: that render is dropped (and cancelled). + d.cur().params.insert("strokeLength".into(), before); + assert!(update_preview(d, &ctx, area, true).is_some()); + assert!(d.rendering().is_none()); + d.cur().params.insert("strokeLength".into(), json!(5)); + update_preview(d, &ctx, area, true); + // Closing the dialog cancels it. + app.distort.gallery = None; +} + +/// Preview cost on 24 MP: `cargo test -p photocraft-ui-egui --lib bench_gallery_preview -- --ignored --nocapture`. +#[test] +#[ignore] +fn bench_gallery_preview() { + let (w, h) = (6000, 4000); + let canvas = Rect::new(0, 0, w, h); + let mut s = Surface::new(photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, true)); + s.fill_rect(canvas, &[0.5, 0.4, 0.3, 1.0]); + for y in (0..h).step_by(9) { + s.fill_rect(Rect::new(0, y, w, y + 3), &[0.9, 0.8, 0.2, 1.0]); + } + let ms = |t: std::time::Instant| t.elapsed().as_secs_f64() * 1000.0; + let t = std::time::Instant::now(); + std::hint::black_box(reduce(&s, canvas, 8)); + println!("{:>14}: {:>7.0} ms", "reduce 1/8", ms(t)); + for f in ["graphicPen", "charcoal", "reticulation", "stainedGlass", "spatter", "roughPastels"] { + let p = json!({"effects": [{"filter": f}]}); + let t = std::time::Instant::now(); + std::hint::black_box(render(&sample(&s, canvas, 8), &p)); + let old = ms(t); + let t = std::time::Instant::now(); + std::hint::black_box(preview_pixels(&s, canvas, &p, canvas, 8, &Interrupt::NONE)); + let fit = ms(t); + let t = std::time::Instant::now(); + std::hint::black_box(preview_pixels(&s, canvas, &p, Rect::new(2400, 1600, 3500, 2400), 1, &Interrupt::NONE)); + let screen = ms(t); + println!("{f:>14}: old fit {old:>5.0} ms, new fit {fit:>6.0} ms, new 100 % (1100x800) {screen:>5.0} ms"); + } +} From c019d24203870385c18517b1b4f45a2cb1f0450c Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:06 +0000 Subject: [PATCH 085/259] refactor(ui-egui): move native_menu.rs tests to native_menu/tests.rs --- crates/ui-egui/src/native_menu.rs | 506 +----------------------- crates/ui-egui/src/native_menu/tests.rs | 503 +++++++++++++++++++++++ 2 files changed, 504 insertions(+), 505 deletions(-) create mode 100644 crates/ui-egui/src/native_menu/tests.rs diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index 6a1426f39b..4dad63c448 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -767,508 +767,4 @@ pub(crate) fn state_hash(app: &PhotocraftApp, input: Option) -> u64 { } #[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn app(doc: bool) -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - if doc { - app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); - app.sync_views(); - } - app - } - - fn layout(doc: bool) -> Layout { - photocraft_layout(&crate::menus::menu_items(&app(doc)), Lang::EN, "auto") - } - - fn ids(nodes: &[Node]) -> Vec { - nodes - .iter() - .map(|n| match n { - Node::Item(it) => it.id.clone(), - Node::Separator => "---".into(), - Node::Submenu { label, .. } => format!("[{label}]"), - Node::Standard(s) => format!("<{s:?}>"), - }) - .collect() - } - - #[test] - fn photocraft_gets_a_mac_app_menu() { - let l = layout(true); - let app = &l.bar.menus[0]; - assert_eq!((app.title.as_str(), app.role), ("PhotoCraft", MenuRole::App)); - assert_eq!( - ids(&app.children), - [ - "help.about", - "---", - "[Settings]", - "[Language]", - "[Appearance]", - "---", - "", - "---", - HIDE, - "", - "", - "---", - "file.exit" - ] - ); - let quit = l.bar.find("file.exit").unwrap(); - assert_eq!((quit.label.as_str(), quit.shortcut.as_deref()), ("Quit PhotoCraft", Some("Cmd+Q"))); - assert_eq!(l.bar.find("help.about").unwrap().label, "About PhotoCraft"); - } - - #[test] - fn moved_items_leave_their_old_menus() { - let l = layout(true); - let by = |t: &str| l.bar.menus.iter().find(|m| m.title == t).unwrap(); - assert!(!ids(&by("File").children).contains(&"file.exit".to_string())); - assert!(!ids(&by("Help").children).contains(&"help.about".to_string())); - assert!(!ids(&by("Edit").children).contains(&"[Preferences]".to_string())); - let titles: Vec<&str> = l.bar.menus.iter().map(|m| m.title.as_str()).collect(); - assert_eq!(titles, ["PhotoCraft", "File", "Edit", "Image", "Layer", "Type", "Select", "Filter", "View", "Window", "Help"]); - } - - /// PhotoCraft keeps Photoshop's ⌘H, ⌘M, ⌘W and ⌘, (Hide Layers): the system items give way. - #[test] - fn clashes_are_resolved_in_photocrafts_favour() { - let l = layout(true); - let clash = |sc: &str| l.clashes.iter().find(|c| c.shortcut == sc).map(|c| c.command.as_str()); - assert_eq!(clash("Cmd+H"), Some("view.extras")); - assert_eq!(clash("Cmd+M"), Some("image.adjustments.curves")); - assert_eq!(clash("Cmd+W"), Some("file.close")); - assert_eq!(clash("Cmd+,"), Some("layer.hideLayers")); - assert_eq!(l.bar.find(HIDE).unwrap().shortcut.as_deref(), Some("Ctrl+Cmd+H"), "as in Photoshop"); - assert_eq!(l.bar.find(MINIMIZE).unwrap().shortcut.as_deref(), Some("Ctrl+Cmd+M")); - let window = l.bar.menu(MenuRole::Window).unwrap(); - assert_eq!(ids(&window.children)[..3], [MINIMIZE.to_string(), "".into(), "---".into()]); - assert!(ids(&window.children).ends_with(&["".into(), "---".into(), "window.document.0".into()])); - let file = l.bar.menus.iter().find(|m| m.title == "File").unwrap(); - assert!(!file.children.contains(&Node::Standard(Standard::CloseWindow)), "⌘W stays File › Close"); - } - - /// Themes and the appearance-mode cycle move from Window to the app menu's Appearance. - #[test] - fn themes_move_to_the_app_menus_appearance() { - let mut a = app(false); - a.ui.theme = crate::theme::ThemeKind::Classic; - let l = photocraft_layout(&crate::menus::menu_items(&a), Lang::EN, "auto"); - let app_menu = l.bar.menu(MenuRole::App).unwrap(); - let Some(Node::Submenu { children, .. }) = app_menu.children.iter().find(|n| matches!(n, Node::Submenu { label, .. } if label == "Appearance")) else { - panic!("an Appearance submenu"); - }; - let themes = ids(children); - assert_eq!(themes.last().map(String::as_str), Some("window.theme.toggle")); - assert!(themes.contains(&"[Dark Theme]".to_string()) && themes.contains(&"[Light Theme]".to_string())); - assert_eq!(l.bar.find("window.theme.classic").unwrap().checked, Some(true)); - assert_eq!(l.bar.find("window.theme.pro").unwrap().checked, Some(false)); - assert_eq!(l.bar.find("window.theme.toggle").unwrap().label, "Next Appearance Mode"); - assert_eq!(l.bar.find("window.theme.system").unwrap().label, "Sync with system"); - assert_eq!(l.bar.find("window.theme.system").unwrap().checked, Some(false)); - let window = ids(&l.bar.menu(MenuRole::Window).unwrap().children); - assert!(!window.iter().any(|id| id.starts_with("window.theme.") || id == "[Theme]"), "{window:?}"); - a.session.prefs.edit(|p| p.interface.appearance_mode = photocraft_engine::prefs::AppearanceMode::Auto); - for palette in [crate::theme::ThemeKind::Classic, crate::theme::ThemeKind::ProMedium] { - a.ui.theme = palette; - let automatic = photocraft_layout(&crate::menus::menu_items(&a), Lang::EN, "auto"); - assert_eq!(automatic.bar.find("window.theme.system").unwrap().checked, Some(true)); - for kind in crate::theme::ThemeKind::ALL { - assert_eq!(automatic.bar.find(&format!("window.theme.{}", kind.id())).unwrap().checked, Some(false)); - } - } - } - - /// Language follows Settings in the app menu: Auto and every UI language in its own name, - /// the preference checked; choosing one sets `interface.language`. - #[test] - fn the_app_menu_switches_the_ui_language() { - let l = photocraft_layout(&crate::menus::menu_items(&app(false)), Lang::EN, "ja"); - let app_menu = l.bar.menu(MenuRole::App).unwrap(); - let Some(Node::Submenu { children, .. }) = app_menu.children.iter().find(|n| matches!(n, Node::Submenu { label, .. } if label == "Language")) else { - panic!("a Language submenu"); - }; - assert_eq!(children.iter().filter(|n| matches!(n, Node::Item(_))).count(), Lang::all().count() + 1); - assert_eq!(l.bar.find("app.language.ja").map(|it| (it.label.as_str(), it.checked)), Some(("日本語", Some(true)))); - assert_eq!(l.bar.find("app.language.auto").and_then(|it| it.checked), Some(false)); - // Native names stay native in another UI language. - let de = photocraft_layout(&crate::menus::menu_items(&app(false)), Lang::from_pref("de"), "de"); - assert_eq!(de.bar.find("app.language.ja").map(|it| it.label.as_str()), Some("日本語")); - let mut a = app(false); - let ctx = egui::Context::default(); - crate::menus::invoke(&mut a, &ctx, "app.language.fr", json!({})).unwrap(); - assert_eq!(a.session.prefs().interface.language, "fr"); - crate::menus::invoke(&mut a, &ctx, "app.language.auto", json!({})).unwrap(); - assert_eq!(a.session.prefs().interface.language, "auto"); - assert!(crate::menus::invoke(&mut a, &ctx, "app.language.xx-nope", json!({})).is_err(), "an unknown code is an error"); - } - - /// The menus show the shortcut that runs each command (Undo ⌘Z, Copy ⌘C were blank). - #[test] - fn menu_rows_show_the_shortcut_that_runs_them() { - let l = layout(true); - let sc = |id: &str| l.bar.find(id).and_then(|it| it.shortcut.clone()); - assert_eq!(sc("edit.undo").as_deref(), Some("Cmd+Z")); - assert_eq!(sc("edit.copy").as_deref(), Some("Cmd+C")); - assert_eq!(sc("edit.paste").as_deref(), Some("Cmd+V")); - assert_eq!(sc("layer.hideLayers").as_deref(), Some("Cmd+,")); - let app = app(true); - let bindings = crate::shortcut_dispatch::bindings(&app); - for it in crate::menus::menu_items(&app).iter().filter(|it| it.enabled) { - let Some(shown) = it.shortcut.as_deref().and_then(crate::shortcuts::parse) else { continue }; - let runs = bindings.iter().find(|(_, b)| *b == shown).map(|(id, _)| id.as_str()); - assert!(runs.is_some(), "{} shows {:?}, which runs nothing", it.id, it.shortcut); - } - } - - /// A native menu can't turn a plain item into a check item in place: opening the first - /// document must not change any item's kind, or the whole menu is rebuilt. Window's list of - /// documents gains a row, which rebuilds only the Window menu. - #[test] - fn opening_a_document_changes_state_not_structure() { - let (a, b) = (crate::menus::menu_items(&app(false)), crate::menus::menu_items(&app(true))); - let kind = |items: &[MenuItem]| items.iter().map(|i| (i.id.clone(), i.checked.is_some())).collect::>(); - let (ka, kb) = (kind(&a), kind(&b)); - let flips: Vec<&String> = ka.iter().filter(|(id, k)| kb.get(*id).is_some_and(|o| o != *k)).map(|(id, _)| id).collect(); - assert!(flips.is_empty(), "items that change kind: {flips:?}"); - let (no_doc, one_doc) = (layout(false).bar, layout(true).bar); - assert_eq!(structure_key(&no_doc), structure_key(&one_doc)); - assert_ne!(window_key(&no_doc), window_key(&one_doc), "the Window menu is rebuilt for its new row"); - } - - /// #2991: the open documents follow Bring All to Front, where a Mac app lists its windows, - /// the active one checked. Switching documents moves the check without a rebuild. - #[test] - fn the_documents_follow_bring_all_to_front() { - let none = ids(&layout(false).bar.menu(MenuRole::Window).unwrap().children); - assert_eq!(none.last().map(String::as_str), Some("")); - - let mut a = app(true); - a.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - a.sync_views(); - let bar = photocraft_layout(&crate::menus::menu_items(&a), Lang::EN, "auto").bar; - let window = ids(&bar.menu(MenuRole::Window).unwrap().children); - assert_eq!(window[window.len() - 4..], ["", "---", "window.document.0", "window.document.1"]); - assert_eq!(bar.find("window.document.1").and_then(|i| i.checked), Some(true)); - assert_eq!(bar.find("window.document.0").and_then(|i| i.checked), Some(false)); - - a.session.set_active(0); - let switched = photocraft_layout(&crate::menus::menu_items(&a), Lang::EN, "auto").bar; - assert_eq!(switched.find("window.document.0").and_then(|i| i.checked), Some(true)); - assert_eq!((structure_key(&switched), window_key(&switched)), (structure_key(&bar), window_key(&bar)), "a check moves in place"); - } - - #[test] - fn native_key_equivalents_are_command_and_function_keys_only() { - assert!(Chord::parse("Cmd+B").unwrap().native_ok()); - assert!(Chord::parse("F5").unwrap().native_ok()); - assert!(!Chord::parse("B").unwrap().native_ok()); - assert!(!Chord::parse("Alt+F").unwrap().native_ok()); - assert!(!Chord::parse("Shift+X").unwrap().native_ok()); - assert_eq!(Chord::parse("Ctrl+Cmd+M").unwrap().portable(), "Ctrl+Cmd+M"); - assert_eq!(Chord::parse("Cmd++").unwrap().key, "+"); - } - - /// Every menu shortcut is written so it parses and turns back into the key press egui gets. - #[test] - fn every_shortcut_becomes_a_key_press() { - for it in layout(true).bar.items() { - let Some(sc) = &it.shortcut else { continue }; - let c = Chord::parse(sc).unwrap_or_else(|| panic!("{sc} on {} doesn't parse", it.id)); - assert_eq!(&c.portable(), sc, "{} writes its modifiers in another order", it.id); - let Some(egui::Event::Key { key, modifiers, .. }) = c.key_event(true) else { panic!("{sc} on {} has no egui key", it.id) }; - let parsed = crate::shortcuts::parse(sc).unwrap(); - assert!(crate::shortcuts::key_matches(&parsed, key, modifiers), "{sc} on {} doesn't match its own key press", it.id); - } - } - - fn frame(ctx: &egui::Context, raw: egui::RawInput, f: impl FnMut(&mut egui::Ui)) { - let mut out = ctx.run_ui(raw, f); - out.textures_delta.clear(); - } - - struct Fake { - synced: std::rc::Rc>>, - events: Vec, - } - - impl Backend for Fake { - fn sync(&mut self, bar: &MenuBar) { - self.synced.borrow_mut().push(bar.clone()); - } - fn drain(&mut self) -> Vec { - std::mem::take(&mut self.events) - } - } - - /// A key equivalent reaches PhotoCraft's own key handling as the key press it was, so the - /// shortcut runs once, through the same rules as without a native menu. - #[test] - fn key_equivalents_run_through_the_normal_shortcut_path() { - let synced = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); - let mut app = app(true); - let ctx = egui::Context::default(); - let rulers = Chord::parse("Cmd+R").unwrap(); - app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: synced.clone(), events: vec![Event::Key(rulers)] }))); - let before = app.ui.extras.rulers; - let mut raw = egui::RawInput::default(); - if let Some(m) = app.services.native_menu.as_mut() { - m.raw_input(&mut raw); - } - assert_eq!(raw.events.len(), 1, "the press: winit delivers the release"); - frame(&ctx, raw, |ui| { - run(&mut app, ui.ctx()); - crate::shortcuts::handle(&mut app, ui.ctx()); - sync(&mut app, ui.ctx()); - }); - assert_eq!(app.ui.extras.rulers, !before, "⌘R toggled View › Rulers once"); - assert_eq!(synced.borrow().len(), 1, "the menu was built"); - // Nothing changed: no rebuild of the rows on the next frame. - frame(&ctx, egui::RawInput::default(), |ui| sync(&mut app, ui.ctx())); - assert_eq!(synced.borrow().len(), 1); - } - - /// #1638: ⌘V through the Mac menu pasted three layers. AppKit takes the key-down for Edit › - /// Paste's key equivalent, but winit still delivers the key-up (it forwards key-ups while ⌘ is - /// held). The menu's press plus that real release must paste once, whether the release - /// arrives in a later frame or already sits in the same input as the menu event. - #[test] - fn a_paste_key_equivalent_pastes_once() { - let release = || egui::Event::Key { key: Key::V, physical_key: Some(Key::V), pressed: false, repeat: false, modifiers: Modifiers::COMMAND }; - for same_frame in [false, true] { - let mut app = app(true); - let ctx = egui::Context::default(); - app.run("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 4})).unwrap(); - app.run("edit.copy", json!({})).unwrap(); - let layers = |app: &PhotocraftApp| app.session.active().unwrap().doc.layer_count(); - let before = layers(&app); - let paste = Chord::parse("Cmd+V").unwrap(); - app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: Default::default(), events: vec![Event::Key(paste)] }))); - let step = |app: &mut PhotocraftApp, events: Vec| { - let mut raw = egui::RawInput { events, ..Default::default() }; - eframe::App::raw_input_hook(app, &ctx, &mut raw); - frame(&ctx, raw, |ui| { - run(app, ui.ctx()); - crate::shortcuts::handle(app, ui.ctx()); - }); - }; - if same_frame { - // A quick tap: the real key-up is already queued when the menu event is drained. - step(&mut app, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND), release()]); - } else { - step(&mut app, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND)]); - step(&mut app, vec![release()]); - } - step(&mut app, vec![egui::Event::ModifiersChanged(Modifiers::NONE)]); - assert_eq!(layers(&app), before + 1, "one ⌘V pastes one layer (key-up in the same frame: {same_frame})"); - } - } - - #[test] - fn clicks_run_the_command_and_resync() { - let synced = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); - let mut app = app(true); - let ctx = egui::Context::default(); - app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: synced.clone(), events: vec![Event::Click("window.panel.layers".into())] }))); - let before = app.ui.panels.layers; - let mut raw = egui::RawInput::default(); - if let Some(m) = app.services.native_menu.as_mut() { - m.raw_input(&mut raw); - } - frame(&ctx, raw, |ui| { - run(&mut app, ui.ctx()); - sync(&mut app, ui.ctx()); - }); - assert_eq!(app.ui.panels.layers, !before); - let bar = synced.borrow().last().cloned().unwrap(); - assert_eq!(bar.find("window.panel.layers").unwrap().checked, Some(!before)); - } - - /// #1354: a dialog is modal for the menu bar too. Its rows are disabled (view navigation - /// aside), and a click that arrives anyway doesn't run under the dialog. - #[test] - fn an_open_dialog_blocks_menu_clicks_except_view_navigation() { - let synced = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); - let mut app = app(true); - let ctx = egui::Context::default(); - crate::menus::invoke(&mut app, &ctx, "image.imageSize", json!({})).unwrap(); - assert!(!app.ui.dialogs.is_empty(), "Image Size opened its dialog"); - let size = |app: &PhotocraftApp| app.session.active().map(|d| (d.doc.size.width, d.doc.size.height)); - let zoom = app.ui.views[0].zoom; - let events = vec![Event::Click("image.imageRotation.90cw".into()), Event::Click("view.zoomIn".into())]; - app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: synced.clone(), events }))); - let mut raw = egui::RawInput::default(); - if let Some(m) = app.services.native_menu.as_mut() { - m.raw_input(&mut raw); - } - frame(&ctx, raw, |ui| { - run(&mut app, ui.ctx()); - sync(&mut app, ui.ctx()); - }); - assert_eq!(size(&app), Some((64, 48)), "the rotation didn't run under the dialog"); - assert!(app.ui.views[0].zoom > zoom, "Zoom In still works under a dialog"); - let bar = synced.borrow().last().cloned().unwrap(); - assert!(!bar.find("image.imageRotation.90cw").unwrap().enabled); - assert!(bar.find("view.zoomIn").unwrap().enabled); - // With the dialog closed the rows come back and a click runs. - app.ui.dialogs.clear(); - frame(&ctx, egui::RawInput::default(), |ui| sync(&mut app, ui.ctx())); - assert!(synced.borrow().last().unwrap().find("image.imageRotation.90cw").unwrap().enabled); - } - - /// Edit > Cut uses the type editor's selection, like the clipboard Cut event (#1355). - #[test] - fn cut_selected_type_from_native_menu_matches_keyboard_cut() { - for native_click in [true, false] { - let synced = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); - let mut app = app(true); - let ctx = egui::Context::default(); - let id = photocraft_doc::LayerId(app.run("type.create", json!({"text": "Hello", "size": 12, "x": 4, "y": 24})).unwrap()["layer"].as_u64().unwrap()); - crate::menus::invoke(&mut app, &ctx, "type.editText", json!({})).unwrap(); - let edit = app.ui.text_edit.as_ref().unwrap(); - assert_eq!((edit.anchor, edit.caret), (0, 5)); - let events = if native_click { vec![Event::Click("edit.cut".into())] } else { Vec::new() }; - app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: synced.clone(), events }))); - frame(&ctx, egui::RawInput::default(), |ui| sync(&mut app, ui.ctx())); - assert!(synced.borrow().last().unwrap().find("edit.cut").unwrap().enabled, "Cut must be enabled for selected characters"); - - let mut raw = egui::RawInput::default(); - app.services.native_menu.as_mut().unwrap().raw_input(&mut raw); - if !native_click { - raw.events.push(egui::Event::Cut); - } - let mut out = ctx.run_ui(raw, |ui| { - run(&mut app, ui.ctx()); - crate::shortcuts::handle(&mut app, ui.ctx()); - sync(&mut app, ui.ctx()); - }); - out.textures_delta.clear(); - assert_eq!(out.platform_output.commands, [egui::OutputCommand::CopyText("Hello".into())]); - let photocraft_doc::LayerContent::Text(text) = &app.session.active().unwrap().doc.layer(id).unwrap().content else { - panic!("type layer changed kind") - }; - assert!(text.text.is_empty()); - let edit = app.ui.text_edit.as_ref().unwrap(); - assert_eq!((edit.anchor, edit.caret), (0, 0)); - assert!(!synced.borrow().last().unwrap().find("edit.cut").unwrap().enabled, "Cut must be disabled at an empty caret"); - assert!(app.session.clipboard.is_none(), "text Cut must not copy rendered pixels"); - } - } - - /// Select > All, Edit > Copy and Edit > Paste work on the text being typed, not on pixels (#2893). - #[test] - fn copy_and_paste_type_from_native_menu() { - let synced = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); - let mut app = app(true); - let ctx = egui::Context::default(); - let id = photocraft_doc::LayerId(app.run("type.create", json!({"text": "Hello", "size": 12, "x": 4, "y": 24})).unwrap()["layer"].as_u64().unwrap()); - crate::menus::invoke(&mut app, &ctx, "type.editText", json!({})).unwrap(); - if let Some(e) = app.ui.text_edit.as_mut() { - (e.anchor, e.caret) = (5, 5); - } - let layers = app.session.active().unwrap().doc.layers.len(); - let click = |app: &mut PhotocraftApp, id: &str| { - app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: synced.clone(), events: vec![Event::Click(id.into())] }))); - let mut raw = egui::RawInput::default(); - app.services.native_menu.as_mut().unwrap().raw_input(&mut raw); - let mut out = ctx.run_ui(raw, |ui| { - run(app, ui.ctx()); - sync(app, ui.ctx()); - }); - out.textures_delta.clear(); - out - }; - let text = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(id).unwrap().content { - photocraft_doc::LayerContent::Text(t) => t.text.clone(), - _ => panic!("type layer changed kind"), - }; - - click(&mut app, "select.all"); - let edit = app.ui.text_edit.as_ref().unwrap(); - assert_eq!((edit.anchor, edit.caret), (0, 5), "Select > All selects the characters"); - let bar = synced.borrow().last().cloned().unwrap(); - assert!(bar.find("edit.copy").unwrap().enabled, "Copy is enabled for selected characters"); - assert!(bar.find("edit.paste").unwrap().enabled, "Paste is enabled while typing"); - - let out = click(&mut app, "edit.copy"); - assert_eq!(out.platform_output.commands, [egui::OutputCommand::CopyText("Hello".into())]); - assert!(app.session.clipboard.is_none(), "text Copy must not copy rendered pixels"); - - let out = click(&mut app, "edit.paste"); - let asked = out.viewport_output.values().any(|v| v.commands.contains(&egui::ViewportCommand::RequestPaste)); - assert!(asked, "Edit > Paste asks the window for the clipboard text"); - // The text arrives as a Paste event next frame and replaces the selection. - let raw = egui::RawInput { events: vec![egui::Event::Paste("World".into())], ..Default::default() }; - frame(&ctx, raw, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); - assert_eq!(text(&app), "World"); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "no pixel layer was pasted"); - assert!(!app.ui.status_error, "{}", app.ui.status); - } - - #[test] - fn native_cut_without_type_edit_keeps_pixel_clipboard_behavior() { - let synced = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); - let mut app = app(false); - app.run("file.new", json!({"width": 4, "height": 4, "background": "transparent"})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - assert_eq!(app.run("document.pixel", json!({"x": 1, "y": 1})).unwrap(), json!([1.0, 0.0, 0.0, 1.0])); - let ctx = egui::Context::default(); - app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: synced.clone(), events: vec![Event::Click("edit.cut".into())] }))); - frame(&ctx, egui::RawInput::default(), |ui| sync(&mut app, ui.ctx())); - assert_eq!(synced.borrow().last().unwrap().find("edit.cut").unwrap().enabled, app.session.is_enabled("edit.cut")); - assert!(app.session.is_enabled("edit.cut")); - let mut raw = egui::RawInput::default(); - app.services.native_menu.as_mut().unwrap().raw_input(&mut raw); - frame(&ctx, raw, |ui| { - run(&mut app, ui.ctx()); - sync(&mut app, ui.ctx()); - }); - assert_eq!(app.run("document.pixel", json!({"x": 1, "y": 1})).unwrap(), json!([0.0, 0.0, 0.0, 0.0])); - let clip = app.session.clipboard.as_ref().unwrap(); - assert_eq!((clip.bounds.width(), clip.bounds.height()), (4, 4)); - let mut px = vec![[0u8; 4]; 16]; - clip.surface.read_rgba8_into(clip.bounds, &mut px); - assert_eq!(px, vec![[255u8, 0, 0, 255]; 16]); - assert!(app.ui.text_edit.is_none()); - } - - /// With the Mac menu bar the title bar draws no menu titles: each title shows once fewer. - #[test] - fn the_title_bar_hides_its_menus_with_the_mac_menu_bar() { - use egui_kittest::{Harness, kittest::Queryable}; - let counts = |native: bool| -> Vec { - let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - let mut app = app(true); - if native { - app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: Default::default(), events: Vec::new() }))); - } - app - }); - h.run_steps(4); - crate::menus::TOP_MENUS.iter().map(|t| h.query_all_by_label(t).count()).collect() - }; - let (in_window, native) = (counts(false), counts(true)); - for (i, title) in crate::menus::TOP_MENUS.iter().enumerate() { - assert_eq!(native[i] + 1, in_window[i], "{title}: {} in-window, {} with the Mac menu bar", in_window[i], native[i]); - } - } - - #[test] - fn opening_or_closing_a_workspace_without_input_rebuilds_the_menus() { - let mut app = app(true); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"color": "#808080"})).unwrap(); - let closed = state_hash(&app, None); - crate::gallery_ui::open(&mut app).unwrap(); - let open = state_hash(&app, None); - assert_ne!(open, closed, "the menus grey out when an agent opens Filter Gallery"); - app.distort.gallery = None; - assert_eq!(state_hash(&app, None), closed, "and come back when it is cancelled"); - } -} +mod tests; diff --git a/crates/ui-egui/src/native_menu/tests.rs b/crates/ui-egui/src/native_menu/tests.rs new file mode 100644 index 0000000000..648fd04287 --- /dev/null +++ b/crates/ui-egui/src/native_menu/tests.rs @@ -0,0 +1,503 @@ +use super::*; +use serde_json::json; + +fn app(doc: bool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + if doc { + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.sync_views(); + } + app +} + +fn layout(doc: bool) -> Layout { + photocraft_layout(&crate::menus::menu_items(&app(doc)), Lang::EN, "auto") +} + +fn ids(nodes: &[Node]) -> Vec { + nodes + .iter() + .map(|n| match n { + Node::Item(it) => it.id.clone(), + Node::Separator => "---".into(), + Node::Submenu { label, .. } => format!("[{label}]"), + Node::Standard(s) => format!("<{s:?}>"), + }) + .collect() +} + +#[test] +fn photocraft_gets_a_mac_app_menu() { + let l = layout(true); + let app = &l.bar.menus[0]; + assert_eq!((app.title.as_str(), app.role), ("PhotoCraft", MenuRole::App)); + assert_eq!( + ids(&app.children), + [ + "help.about", + "---", + "[Settings]", + "[Language]", + "[Appearance]", + "---", + "", + "---", + HIDE, + "", + "", + "---", + "file.exit" + ] + ); + let quit = l.bar.find("file.exit").unwrap(); + assert_eq!((quit.label.as_str(), quit.shortcut.as_deref()), ("Quit PhotoCraft", Some("Cmd+Q"))); + assert_eq!(l.bar.find("help.about").unwrap().label, "About PhotoCraft"); +} + +#[test] +fn moved_items_leave_their_old_menus() { + let l = layout(true); + let by = |t: &str| l.bar.menus.iter().find(|m| m.title == t).unwrap(); + assert!(!ids(&by("File").children).contains(&"file.exit".to_string())); + assert!(!ids(&by("Help").children).contains(&"help.about".to_string())); + assert!(!ids(&by("Edit").children).contains(&"[Preferences]".to_string())); + let titles: Vec<&str> = l.bar.menus.iter().map(|m| m.title.as_str()).collect(); + assert_eq!(titles, ["PhotoCraft", "File", "Edit", "Image", "Layer", "Type", "Select", "Filter", "View", "Window", "Help"]); +} + +/// PhotoCraft keeps Photoshop's ⌘H, ⌘M, ⌘W and ⌘, (Hide Layers): the system items give way. +#[test] +fn clashes_are_resolved_in_photocrafts_favour() { + let l = layout(true); + let clash = |sc: &str| l.clashes.iter().find(|c| c.shortcut == sc).map(|c| c.command.as_str()); + assert_eq!(clash("Cmd+H"), Some("view.extras")); + assert_eq!(clash("Cmd+M"), Some("image.adjustments.curves")); + assert_eq!(clash("Cmd+W"), Some("file.close")); + assert_eq!(clash("Cmd+,"), Some("layer.hideLayers")); + assert_eq!(l.bar.find(HIDE).unwrap().shortcut.as_deref(), Some("Ctrl+Cmd+H"), "as in Photoshop"); + assert_eq!(l.bar.find(MINIMIZE).unwrap().shortcut.as_deref(), Some("Ctrl+Cmd+M")); + let window = l.bar.menu(MenuRole::Window).unwrap(); + assert_eq!(ids(&window.children)[..3], [MINIMIZE.to_string(), "".into(), "---".into()]); + assert!(ids(&window.children).ends_with(&["".into(), "---".into(), "window.document.0".into()])); + let file = l.bar.menus.iter().find(|m| m.title == "File").unwrap(); + assert!(!file.children.contains(&Node::Standard(Standard::CloseWindow)), "⌘W stays File › Close"); +} + +/// Themes and the appearance-mode cycle move from Window to the app menu's Appearance. +#[test] +fn themes_move_to_the_app_menus_appearance() { + let mut a = app(false); + a.ui.theme = crate::theme::ThemeKind::Classic; + let l = photocraft_layout(&crate::menus::menu_items(&a), Lang::EN, "auto"); + let app_menu = l.bar.menu(MenuRole::App).unwrap(); + let Some(Node::Submenu { children, .. }) = app_menu.children.iter().find(|n| matches!(n, Node::Submenu { label, .. } if label == "Appearance")) else { + panic!("an Appearance submenu"); + }; + let themes = ids(children); + assert_eq!(themes.last().map(String::as_str), Some("window.theme.toggle")); + assert!(themes.contains(&"[Dark Theme]".to_string()) && themes.contains(&"[Light Theme]".to_string())); + assert_eq!(l.bar.find("window.theme.classic").unwrap().checked, Some(true)); + assert_eq!(l.bar.find("window.theme.pro").unwrap().checked, Some(false)); + assert_eq!(l.bar.find("window.theme.toggle").unwrap().label, "Next Appearance Mode"); + assert_eq!(l.bar.find("window.theme.system").unwrap().label, "Sync with system"); + assert_eq!(l.bar.find("window.theme.system").unwrap().checked, Some(false)); + let window = ids(&l.bar.menu(MenuRole::Window).unwrap().children); + assert!(!window.iter().any(|id| id.starts_with("window.theme.") || id == "[Theme]"), "{window:?}"); + a.session.prefs.edit(|p| p.interface.appearance_mode = photocraft_engine::prefs::AppearanceMode::Auto); + for palette in [crate::theme::ThemeKind::Classic, crate::theme::ThemeKind::ProMedium] { + a.ui.theme = palette; + let automatic = photocraft_layout(&crate::menus::menu_items(&a), Lang::EN, "auto"); + assert_eq!(automatic.bar.find("window.theme.system").unwrap().checked, Some(true)); + for kind in crate::theme::ThemeKind::ALL { + assert_eq!(automatic.bar.find(&format!("window.theme.{}", kind.id())).unwrap().checked, Some(false)); + } + } +} + +/// Language follows Settings in the app menu: Auto and every UI language in its own name, +/// the preference checked; choosing one sets `interface.language`. +#[test] +fn the_app_menu_switches_the_ui_language() { + let l = photocraft_layout(&crate::menus::menu_items(&app(false)), Lang::EN, "ja"); + let app_menu = l.bar.menu(MenuRole::App).unwrap(); + let Some(Node::Submenu { children, .. }) = app_menu.children.iter().find(|n| matches!(n, Node::Submenu { label, .. } if label == "Language")) else { + panic!("a Language submenu"); + }; + assert_eq!(children.iter().filter(|n| matches!(n, Node::Item(_))).count(), Lang::all().count() + 1); + assert_eq!(l.bar.find("app.language.ja").map(|it| (it.label.as_str(), it.checked)), Some(("日本語", Some(true)))); + assert_eq!(l.bar.find("app.language.auto").and_then(|it| it.checked), Some(false)); + // Native names stay native in another UI language. + let de = photocraft_layout(&crate::menus::menu_items(&app(false)), Lang::from_pref("de"), "de"); + assert_eq!(de.bar.find("app.language.ja").map(|it| it.label.as_str()), Some("日本語")); + let mut a = app(false); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut a, &ctx, "app.language.fr", json!({})).unwrap(); + assert_eq!(a.session.prefs().interface.language, "fr"); + crate::menus::invoke(&mut a, &ctx, "app.language.auto", json!({})).unwrap(); + assert_eq!(a.session.prefs().interface.language, "auto"); + assert!(crate::menus::invoke(&mut a, &ctx, "app.language.xx-nope", json!({})).is_err(), "an unknown code is an error"); +} + +/// The menus show the shortcut that runs each command (Undo ⌘Z, Copy ⌘C were blank). +#[test] +fn menu_rows_show_the_shortcut_that_runs_them() { + let l = layout(true); + let sc = |id: &str| l.bar.find(id).and_then(|it| it.shortcut.clone()); + assert_eq!(sc("edit.undo").as_deref(), Some("Cmd+Z")); + assert_eq!(sc("edit.copy").as_deref(), Some("Cmd+C")); + assert_eq!(sc("edit.paste").as_deref(), Some("Cmd+V")); + assert_eq!(sc("layer.hideLayers").as_deref(), Some("Cmd+,")); + let app = app(true); + let bindings = crate::shortcut_dispatch::bindings(&app); + for it in crate::menus::menu_items(&app).iter().filter(|it| it.enabled) { + let Some(shown) = it.shortcut.as_deref().and_then(crate::shortcuts::parse) else { continue }; + let runs = bindings.iter().find(|(_, b)| *b == shown).map(|(id, _)| id.as_str()); + assert!(runs.is_some(), "{} shows {:?}, which runs nothing", it.id, it.shortcut); + } +} + +/// A native menu can't turn a plain item into a check item in place: opening the first +/// document must not change any item's kind, or the whole menu is rebuilt. Window's list of +/// documents gains a row, which rebuilds only the Window menu. +#[test] +fn opening_a_document_changes_state_not_structure() { + let (a, b) = (crate::menus::menu_items(&app(false)), crate::menus::menu_items(&app(true))); + let kind = |items: &[MenuItem]| items.iter().map(|i| (i.id.clone(), i.checked.is_some())).collect::>(); + let (ka, kb) = (kind(&a), kind(&b)); + let flips: Vec<&String> = ka.iter().filter(|(id, k)| kb.get(*id).is_some_and(|o| o != *k)).map(|(id, _)| id).collect(); + assert!(flips.is_empty(), "items that change kind: {flips:?}"); + let (no_doc, one_doc) = (layout(false).bar, layout(true).bar); + assert_eq!(structure_key(&no_doc), structure_key(&one_doc)); + assert_ne!(window_key(&no_doc), window_key(&one_doc), "the Window menu is rebuilt for its new row"); +} + +/// #2991: the open documents follow Bring All to Front, where a Mac app lists its windows, +/// the active one checked. Switching documents moves the check without a rebuild. +#[test] +fn the_documents_follow_bring_all_to_front() { + let none = ids(&layout(false).bar.menu(MenuRole::Window).unwrap().children); + assert_eq!(none.last().map(String::as_str), Some("")); + + let mut a = app(true); + a.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + a.sync_views(); + let bar = photocraft_layout(&crate::menus::menu_items(&a), Lang::EN, "auto").bar; + let window = ids(&bar.menu(MenuRole::Window).unwrap().children); + assert_eq!(window[window.len() - 4..], ["", "---", "window.document.0", "window.document.1"]); + assert_eq!(bar.find("window.document.1").and_then(|i| i.checked), Some(true)); + assert_eq!(bar.find("window.document.0").and_then(|i| i.checked), Some(false)); + + a.session.set_active(0); + let switched = photocraft_layout(&crate::menus::menu_items(&a), Lang::EN, "auto").bar; + assert_eq!(switched.find("window.document.0").and_then(|i| i.checked), Some(true)); + assert_eq!((structure_key(&switched), window_key(&switched)), (structure_key(&bar), window_key(&bar)), "a check moves in place"); +} + +#[test] +fn native_key_equivalents_are_command_and_function_keys_only() { + assert!(Chord::parse("Cmd+B").unwrap().native_ok()); + assert!(Chord::parse("F5").unwrap().native_ok()); + assert!(!Chord::parse("B").unwrap().native_ok()); + assert!(!Chord::parse("Alt+F").unwrap().native_ok()); + assert!(!Chord::parse("Shift+X").unwrap().native_ok()); + assert_eq!(Chord::parse("Ctrl+Cmd+M").unwrap().portable(), "Ctrl+Cmd+M"); + assert_eq!(Chord::parse("Cmd++").unwrap().key, "+"); +} + +/// Every menu shortcut is written so it parses and turns back into the key press egui gets. +#[test] +fn every_shortcut_becomes_a_key_press() { + for it in layout(true).bar.items() { + let Some(sc) = &it.shortcut else { continue }; + let c = Chord::parse(sc).unwrap_or_else(|| panic!("{sc} on {} doesn't parse", it.id)); + assert_eq!(&c.portable(), sc, "{} writes its modifiers in another order", it.id); + let Some(egui::Event::Key { key, modifiers, .. }) = c.key_event(true) else { panic!("{sc} on {} has no egui key", it.id) }; + let parsed = crate::shortcuts::parse(sc).unwrap(); + assert!(crate::shortcuts::key_matches(&parsed, key, modifiers), "{sc} on {} doesn't match its own key press", it.id); + } +} + +fn frame(ctx: &egui::Context, raw: egui::RawInput, f: impl FnMut(&mut egui::Ui)) { + let mut out = ctx.run_ui(raw, f); + out.textures_delta.clear(); +} + +struct Fake { + synced: std::rc::Rc>>, + events: Vec, +} + +impl Backend for Fake { + fn sync(&mut self, bar: &MenuBar) { + self.synced.borrow_mut().push(bar.clone()); + } + fn drain(&mut self) -> Vec { + std::mem::take(&mut self.events) + } +} + +/// A key equivalent reaches PhotoCraft's own key handling as the key press it was, so the +/// shortcut runs once, through the same rules as without a native menu. +#[test] +fn key_equivalents_run_through_the_normal_shortcut_path() { + let synced = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let mut app = app(true); + let ctx = egui::Context::default(); + let rulers = Chord::parse("Cmd+R").unwrap(); + app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: synced.clone(), events: vec![Event::Key(rulers)] }))); + let before = app.ui.extras.rulers; + let mut raw = egui::RawInput::default(); + if let Some(m) = app.services.native_menu.as_mut() { + m.raw_input(&mut raw); + } + assert_eq!(raw.events.len(), 1, "the press: winit delivers the release"); + frame(&ctx, raw, |ui| { + run(&mut app, ui.ctx()); + crate::shortcuts::handle(&mut app, ui.ctx()); + sync(&mut app, ui.ctx()); + }); + assert_eq!(app.ui.extras.rulers, !before, "⌘R toggled View › Rulers once"); + assert_eq!(synced.borrow().len(), 1, "the menu was built"); + // Nothing changed: no rebuild of the rows on the next frame. + frame(&ctx, egui::RawInput::default(), |ui| sync(&mut app, ui.ctx())); + assert_eq!(synced.borrow().len(), 1); +} + +/// #1638: ⌘V through the Mac menu pasted three layers. AppKit takes the key-down for Edit › +/// Paste's key equivalent, but winit still delivers the key-up (it forwards key-ups while ⌘ is +/// held). The menu's press plus that real release must paste once, whether the release +/// arrives in a later frame or already sits in the same input as the menu event. +#[test] +fn a_paste_key_equivalent_pastes_once() { + let release = || egui::Event::Key { key: Key::V, physical_key: Some(Key::V), pressed: false, repeat: false, modifiers: Modifiers::COMMAND }; + for same_frame in [false, true] { + let mut app = app(true); + let ctx = egui::Context::default(); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 4})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + let layers = |app: &PhotocraftApp| app.session.active().unwrap().doc.layer_count(); + let before = layers(&app); + let paste = Chord::parse("Cmd+V").unwrap(); + app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: Default::default(), events: vec![Event::Key(paste)] }))); + let step = |app: &mut PhotocraftApp, events: Vec| { + let mut raw = egui::RawInput { events, ..Default::default() }; + eframe::App::raw_input_hook(app, &ctx, &mut raw); + frame(&ctx, raw, |ui| { + run(app, ui.ctx()); + crate::shortcuts::handle(app, ui.ctx()); + }); + }; + if same_frame { + // A quick tap: the real key-up is already queued when the menu event is drained. + step(&mut app, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND), release()]); + } else { + step(&mut app, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND)]); + step(&mut app, vec![release()]); + } + step(&mut app, vec![egui::Event::ModifiersChanged(Modifiers::NONE)]); + assert_eq!(layers(&app), before + 1, "one ⌘V pastes one layer (key-up in the same frame: {same_frame})"); + } +} + +#[test] +fn clicks_run_the_command_and_resync() { + let synced = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let mut app = app(true); + let ctx = egui::Context::default(); + app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: synced.clone(), events: vec![Event::Click("window.panel.layers".into())] }))); + let before = app.ui.panels.layers; + let mut raw = egui::RawInput::default(); + if let Some(m) = app.services.native_menu.as_mut() { + m.raw_input(&mut raw); + } + frame(&ctx, raw, |ui| { + run(&mut app, ui.ctx()); + sync(&mut app, ui.ctx()); + }); + assert_eq!(app.ui.panels.layers, !before); + let bar = synced.borrow().last().cloned().unwrap(); + assert_eq!(bar.find("window.panel.layers").unwrap().checked, Some(!before)); +} + +/// #1354: a dialog is modal for the menu bar too. Its rows are disabled (view navigation +/// aside), and a click that arrives anyway doesn't run under the dialog. +#[test] +fn an_open_dialog_blocks_menu_clicks_except_view_navigation() { + let synced = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let mut app = app(true); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "image.imageSize", json!({})).unwrap(); + assert!(!app.ui.dialogs.is_empty(), "Image Size opened its dialog"); + let size = |app: &PhotocraftApp| app.session.active().map(|d| (d.doc.size.width, d.doc.size.height)); + let zoom = app.ui.views[0].zoom; + let events = vec![Event::Click("image.imageRotation.90cw".into()), Event::Click("view.zoomIn".into())]; + app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: synced.clone(), events }))); + let mut raw = egui::RawInput::default(); + if let Some(m) = app.services.native_menu.as_mut() { + m.raw_input(&mut raw); + } + frame(&ctx, raw, |ui| { + run(&mut app, ui.ctx()); + sync(&mut app, ui.ctx()); + }); + assert_eq!(size(&app), Some((64, 48)), "the rotation didn't run under the dialog"); + assert!(app.ui.views[0].zoom > zoom, "Zoom In still works under a dialog"); + let bar = synced.borrow().last().cloned().unwrap(); + assert!(!bar.find("image.imageRotation.90cw").unwrap().enabled); + assert!(bar.find("view.zoomIn").unwrap().enabled); + // With the dialog closed the rows come back and a click runs. + app.ui.dialogs.clear(); + frame(&ctx, egui::RawInput::default(), |ui| sync(&mut app, ui.ctx())); + assert!(synced.borrow().last().unwrap().find("image.imageRotation.90cw").unwrap().enabled); +} + +/// Edit > Cut uses the type editor's selection, like the clipboard Cut event (#1355). +#[test] +fn cut_selected_type_from_native_menu_matches_keyboard_cut() { + for native_click in [true, false] { + let synced = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let mut app = app(true); + let ctx = egui::Context::default(); + let id = photocraft_doc::LayerId(app.run("type.create", json!({"text": "Hello", "size": 12, "x": 4, "y": 24})).unwrap()["layer"].as_u64().unwrap()); + crate::menus::invoke(&mut app, &ctx, "type.editText", json!({})).unwrap(); + let edit = app.ui.text_edit.as_ref().unwrap(); + assert_eq!((edit.anchor, edit.caret), (0, 5)); + let events = if native_click { vec![Event::Click("edit.cut".into())] } else { Vec::new() }; + app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: synced.clone(), events }))); + frame(&ctx, egui::RawInput::default(), |ui| sync(&mut app, ui.ctx())); + assert!(synced.borrow().last().unwrap().find("edit.cut").unwrap().enabled, "Cut must be enabled for selected characters"); + + let mut raw = egui::RawInput::default(); + app.services.native_menu.as_mut().unwrap().raw_input(&mut raw); + if !native_click { + raw.events.push(egui::Event::Cut); + } + let mut out = ctx.run_ui(raw, |ui| { + run(&mut app, ui.ctx()); + crate::shortcuts::handle(&mut app, ui.ctx()); + sync(&mut app, ui.ctx()); + }); + out.textures_delta.clear(); + assert_eq!(out.platform_output.commands, [egui::OutputCommand::CopyText("Hello".into())]); + let photocraft_doc::LayerContent::Text(text) = &app.session.active().unwrap().doc.layer(id).unwrap().content else { + panic!("type layer changed kind") + }; + assert!(text.text.is_empty()); + let edit = app.ui.text_edit.as_ref().unwrap(); + assert_eq!((edit.anchor, edit.caret), (0, 0)); + assert!(!synced.borrow().last().unwrap().find("edit.cut").unwrap().enabled, "Cut must be disabled at an empty caret"); + assert!(app.session.clipboard.is_none(), "text Cut must not copy rendered pixels"); + } +} + +/// Select > All, Edit > Copy and Edit > Paste work on the text being typed, not on pixels (#2893). +#[test] +fn copy_and_paste_type_from_native_menu() { + let synced = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let mut app = app(true); + let ctx = egui::Context::default(); + let id = photocraft_doc::LayerId(app.run("type.create", json!({"text": "Hello", "size": 12, "x": 4, "y": 24})).unwrap()["layer"].as_u64().unwrap()); + crate::menus::invoke(&mut app, &ctx, "type.editText", json!({})).unwrap(); + if let Some(e) = app.ui.text_edit.as_mut() { + (e.anchor, e.caret) = (5, 5); + } + let layers = app.session.active().unwrap().doc.layers.len(); + let click = |app: &mut PhotocraftApp, id: &str| { + app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: synced.clone(), events: vec![Event::Click(id.into())] }))); + let mut raw = egui::RawInput::default(); + app.services.native_menu.as_mut().unwrap().raw_input(&mut raw); + let mut out = ctx.run_ui(raw, |ui| { + run(app, ui.ctx()); + sync(app, ui.ctx()); + }); + out.textures_delta.clear(); + out + }; + let text = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(id).unwrap().content { + photocraft_doc::LayerContent::Text(t) => t.text.clone(), + _ => panic!("type layer changed kind"), + }; + + click(&mut app, "select.all"); + let edit = app.ui.text_edit.as_ref().unwrap(); + assert_eq!((edit.anchor, edit.caret), (0, 5), "Select > All selects the characters"); + let bar = synced.borrow().last().cloned().unwrap(); + assert!(bar.find("edit.copy").unwrap().enabled, "Copy is enabled for selected characters"); + assert!(bar.find("edit.paste").unwrap().enabled, "Paste is enabled while typing"); + + let out = click(&mut app, "edit.copy"); + assert_eq!(out.platform_output.commands, [egui::OutputCommand::CopyText("Hello".into())]); + assert!(app.session.clipboard.is_none(), "text Copy must not copy rendered pixels"); + + let out = click(&mut app, "edit.paste"); + let asked = out.viewport_output.values().any(|v| v.commands.contains(&egui::ViewportCommand::RequestPaste)); + assert!(asked, "Edit > Paste asks the window for the clipboard text"); + // The text arrives as a Paste event next frame and replaces the selection. + let raw = egui::RawInput { events: vec![egui::Event::Paste("World".into())], ..Default::default() }; + frame(&ctx, raw, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + assert_eq!(text(&app), "World"); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "no pixel layer was pasted"); + assert!(!app.ui.status_error, "{}", app.ui.status); +} + +#[test] +fn native_cut_without_type_edit_keeps_pixel_clipboard_behavior() { + let synced = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let mut app = app(false); + app.run("file.new", json!({"width": 4, "height": 4, "background": "transparent"})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + assert_eq!(app.run("document.pixel", json!({"x": 1, "y": 1})).unwrap(), json!([1.0, 0.0, 0.0, 1.0])); + let ctx = egui::Context::default(); + app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: synced.clone(), events: vec![Event::Click("edit.cut".into())] }))); + frame(&ctx, egui::RawInput::default(), |ui| sync(&mut app, ui.ctx())); + assert_eq!(synced.borrow().last().unwrap().find("edit.cut").unwrap().enabled, app.session.is_enabled("edit.cut")); + assert!(app.session.is_enabled("edit.cut")); + let mut raw = egui::RawInput::default(); + app.services.native_menu.as_mut().unwrap().raw_input(&mut raw); + frame(&ctx, raw, |ui| { + run(&mut app, ui.ctx()); + sync(&mut app, ui.ctx()); + }); + assert_eq!(app.run("document.pixel", json!({"x": 1, "y": 1})).unwrap(), json!([0.0, 0.0, 0.0, 0.0])); + let clip = app.session.clipboard.as_ref().unwrap(); + assert_eq!((clip.bounds.width(), clip.bounds.height()), (4, 4)); + let mut px = vec![[0u8; 4]; 16]; + clip.surface.read_rgba8_into(clip.bounds, &mut px); + assert_eq!(px, vec![[255u8, 0, 0, 255]; 16]); + assert!(app.ui.text_edit.is_none()); +} + +/// With the Mac menu bar the title bar draws no menu titles: each title shows once fewer. +#[test] +fn the_title_bar_hides_its_menus_with_the_mac_menu_bar() { + use egui_kittest::{Harness, kittest::Queryable}; + let counts = |native: bool| -> Vec { + let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = app(true); + if native { + app.services.native_menu = Some(NativeMenu::new(Box::new(Fake { synced: Default::default(), events: Vec::new() }))); + } + app + }); + h.run_steps(4); + crate::menus::TOP_MENUS.iter().map(|t| h.query_all_by_label(t).count()).collect() + }; + let (in_window, native) = (counts(false), counts(true)); + for (i, title) in crate::menus::TOP_MENUS.iter().enumerate() { + assert_eq!(native[i] + 1, in_window[i], "{title}: {} in-window, {} with the Mac menu bar", in_window[i], native[i]); + } +} + +#[test] +fn opening_or_closing_a_workspace_without_input_rebuilds_the_menus() { + let mut app = app(true); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#808080"})).unwrap(); + let closed = state_hash(&app, None); + crate::gallery_ui::open(&mut app).unwrap(); + let open = state_hash(&app, None); + assert_ne!(open, closed, "the menus grey out when an agent opens Filter Gallery"); + app.distort.gallery = None; + assert_eq!(state_hash(&app, None), closed, "and come back when it is cancelled"); +} From 2a3caab14c18ba2fae927e2426e50f5df95ba3c6 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:09 +0000 Subject: [PATCH 086/259] refactor(ui-egui): move panels.rs color_tests to panels/color_tests.rs --- crates/ui-egui/src/panels.rs | 617 +---------------------- crates/ui-egui/src/panels/color_tests.rs | 614 ++++++++++++++++++++++ 2 files changed, 615 insertions(+), 616 deletions(-) create mode 100644 crates/ui-egui/src/panels/color_tests.rs diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index b86d7b2af9..678f38bc4f 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -4972,622 +4972,7 @@ mod symmetry_theme_tests { } #[cfg(test)] -mod color_tests { - use super::*; - - #[test] - /// #3323: the Color panel's HSB is Photoshop's (and the Color Picker's), on sRGB values, not - /// egui's linear-light HSV: a 50% grey has Brightness 50%, and the field's left edge halfway - /// down is that grey (128), not 188. - fn color_panel_hsb_is_srgb_like_photoshop() { - let grey = srgb_hsva([128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]); - assert!((grey.v - 128.0 / 255.0).abs() < 1e-3 && grey.s < 1e-3, "{grey:?}"); - let mid = hsva_srgb(egui::ecolor::Hsva::new(0.3, 0.0, 0.5, 1.0)); - assert!(mid[..3].iter().all(|v| (v - 0.5).abs() <= 1.0 / 255.0), "{mid:?}"); - // What the field paints there. - assert_eq!(hsva_color32(egui::ecolor::Hsva::new(0.3, 0.0, 0.5, 1.0)), Color32::from_gray(128)); - // The same numbers as the Color Picker dialog for a saturated colour. - let c = [0.847, 0.271, 0.180]; - let (ours, dialog) = (srgb_hsva([c[0], c[1], c[2], 1.0]), photocraft_color::convert::rgb_to_hsb(c)); - assert!((ours.h * 360.0 - dialog[0]).abs() < 0.5 && (ours.s - dialog[1]).abs() < 1e-3 && (ours.v - dialog[2]).abs() < 1e-3, "{ours:?} vs {dialog:?}"); - } - - #[test] - fn srgb_hsva_roundtrip() { - for c in [[0.847, 0.271, 0.180, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.2, 0.6, 0.4, 1.0]] { - let back = hsva_srgb(srgb_hsva(c)); - for i in 0..3 { - assert!((back[i] - c[i]).abs() <= 1.0 / 255.0, "{c:?} -> {back:?}"); - } - } - } - - /// #7793: the Color panel's field and hue strip pick on the frame the button goes down (no - /// release, no time passing) and follow moves smaller than egui's 6-point click threshold. - #[test] - fn color_panel_field_and_hue_strip_pick_on_press() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.tools.foreground = [0.2, 0.4, 0.6, 1.0]; - let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 300.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - let at = (ui.cursor().min, ui.available_width()); - ui.data_mut(|d| d.insert_temp(egui::Id::unique("test-origin"), at)); - color_field(app, ui); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run_steps(2); - let (o, w) = h.ctx.data(|d| d.get_temp::<(Pos2, f32)>(egui::Id::unique("test-origin"))).unwrap(); - let field_w = w - 38.0 - 14.0 - 16.0; - let press = |h: &mut egui_kittest::Harness<'static, PhotocraftApp>, at: Pos2, pressed: bool| { - h.event(egui::Event::PointerMoved(at)); - h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); - h.run_steps(1); - }; - let at = o + vec2(38.0 + 8.0 + field_w * 0.5, 60.0); - press(&mut h, at, true); - let picked = h.state().session.tools.foreground; - assert_ne!(picked, [0.2, 0.4, 0.6, 1.0], "the press itself picks"); - let hsva = srgb_hsva(picked); - assert!((hsva.s - 0.5).abs() < 0.03 && (hsva.v - 0.5).abs() < 0.03, "{hsva:?}"); - h.event(egui::Event::PointerMoved(at + vec2(3.0, 0.0))); - h.run_steps(1); - assert_ne!(h.state().session.tools.foreground, picked, "a small drag adjusts the pick"); - press(&mut h, at + vec2(3.0, 0.0), false); - h.run_steps(1); - // Hue strip: a press a third of the way down is a hue of about 240° at once. - let before = h.state().session.tools.foreground; - press(&mut h, o + vec2(38.0 + 8.0 + field_w + 8.0 + 7.0, 40.0), true); - let now = h.state().session.tools.foreground; - assert_ne!(now, before, "the strip picks on press"); - assert!((srgb_hsva(now).h * 360.0 - 240.0).abs() < 8.0, "{:?}", srgb_hsva(now)); - } - - /// Only the primary button picks: a right or middle press (and its release) on the field or - /// the hue strip leaves the foreground colour alone. - #[test] - fn color_panel_ignores_secondary_and_middle_presses() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.tools.foreground = [0.2, 0.4, 0.6, 1.0]; - let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 300.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - let at = (ui.cursor().min, ui.available_width()); - ui.data_mut(|d| d.insert_temp(egui::Id::unique("test-origin"), at)); - color_field(app, ui); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run_steps(2); - let (o, w) = h.ctx.data(|d| d.get_temp::<(Pos2, f32)>(egui::Id::unique("test-origin"))).unwrap(); - let field_w = w - 38.0 - 14.0 - 16.0; - let field = o + vec2(38.0 + 8.0 + field_w * 0.5, 60.0); - let strip = o + vec2(38.0 + 8.0 + field_w + 8.0 + 7.0, 40.0); - for at in [field, strip] { - for button in [egui::PointerButton::Secondary, egui::PointerButton::Middle] { - for pressed in [true, false] { - h.event(egui::Event::PointerMoved(at)); - h.event(egui::Event::PointerButton { pos: at, button, pressed, modifiers: egui::Modifiers::NONE }); - h.run_steps(1); - assert_eq!(h.state().session.tools.foreground, [0.2, 0.4, 0.6, 1.0], "{button:?} pressed={pressed} at {at:?}"); - } - } - } - } - - /// Click the hex field, select its text and type `text` one key per frame. - fn type_hex(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, text: &str) { - use egui_kittest::kittest::Queryable; - h.get_by_role(egui::accesskit::Role::TextInput).click(); - h.run_steps(1); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.run_steps(1); - for ch in text.chars() { - h.event(egui::Event::Text(ch.to_string())); - h.run_steps(1); - } - } - - /// The Color panel's hex readout is editable, with or without the leading `#`. - #[test] - fn color_panel_hex_field_takes_a_typed_hex() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.tools.foreground = [1.0, 1.0, 1.0, 1.0]; - let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 300.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - color_field(app, ui); - } - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run_steps(2); - type_hex(&mut h, "003300"); - assert_eq!(srgb_bytes(h.state().session.tools.foreground), [0x00, 0x33, 0x00]); - // A leading '#' is accepted too. - type_hex(&mut h, "#ff8000"); - assert_eq!(srgb_bytes(h.state().session.tools.foreground), [0xff, 0x80, 0x00]); - } - - /// Themes with `round_chips` (Studio) draw round chips, stacked or side by side in two tool - /// columns, with Switch Colors right under them and Default Colors at the top-right corner - /// (stacked) or the left edge (side by side); both buttons work in either layout. - #[test] - fn studio_color_chips_keep_default_and_swap_buttons_below() { - use egui_kittest::kittest::Queryable; - for (kind, two_columns) in [ - (crate::theme::ThemeKind::Studio, false), - (crate::theme::ThemeKind::StudioLight, false), - (crate::theme::ThemeKind::Studio, true), - (crate::theme::ThemeKind::StudioLight, true), - ] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.tools.foreground = [1.0, 0.0, 0.0, 1.0]; - app.session.tools.background = [0.0, 0.0, 1.0, 1.0]; - let mut h = egui_kittest::Harness::builder().with_size(vec2(80.0, 120.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - let w = ui.available_width(); - color_chips(app, ui, two_columns, w) - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, kind); - h.run_steps(2); - h.get_by_label("Swap colours (X)").click(); - h.run_steps(2); - assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 1.0, 1.0], "{kind:?}"); - assert_eq!(h.state().session.tools.background, [1.0, 0.0, 0.0, 1.0], "{kind:?}"); - h.get_by_label("Default colours (D)").click(); - h.run_steps(2); - assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 0.0, 1.0], "{kind:?}"); - assert_eq!(h.state().session.tools.background, [1.0, 1.0, 1.0, 1.0], "{kind:?}"); - } - } - - /// While characters are highlighted in a type layer being edited, the Switch Colors and - /// Default Colors buttons recolour them with the new foreground (#5690); without a selection - /// they only change the tool colours, as before. - #[test] - fn swap_and_default_colors_recolour_selected_type() { - use egui_kittest::kittest::Queryable; - use photocraft_doc::LayerId; - let rgb = |app: &PhotocraftApp, id: LayerId, ci: usize| { - let doc = &app.session.active().unwrap().doc; - let photocraft_doc::LayerContent::Text(t) = &doc.layer(id).unwrap().content else { panic!("not a type layer") }; - let b = t.text.char_indices().nth(ci).map_or(t.text.len(), |(b, _)| b); - let mut at = 0; - for r in t.char_runs() { - if b < at + r.len { - return r.style.color.to_rgba8(); - } - at += r.len; - } - [0; 4] - }; - for selected in [true, false] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let made = app.run("type.create", json!({"text": "Hello world", "size": 40, "x": 50, "y": 150, "color": "#000000"})).unwrap(); - let id = LayerId(made["layer"].as_u64().unwrap()); - app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); - let anchor = if selected { 6 } else { 11 }; - app.ui.text_edit = Some(crate::state::TextEdit { - layer: id.0, - document: None, - caret: 11, - anchor, - session: "s".into(), - created: false, - mask: false, - dragging: false, - resize: None, - preedit: None, - }); - let mut h = egui_kittest::Harness::builder().with_size(vec2(80.0, 120.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - let w = ui.available_width(); - color_chips(app, ui, false, w) - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run_steps(2); - h.get_by_label("Swap colours (X)").click(); - h.run_steps(2); - assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 1.0, 1.0]); - assert_eq!(h.state().session.tools.background, [1.0, 0.0, 0.0, 1.0]); - let blue = if selected { [0, 0, 255, 255] } else { [0, 0, 0, 255] }; - assert_eq!(rgb(h.state(), id, 0), [0, 0, 0, 255], "unselected characters keep their colour"); - assert_eq!((rgb(h.state(), id, 6), rgb(h.state(), id, 10)), (blue, blue), "selected: {selected}"); - // Default Colors: the selection takes black, the new foreground. - h.state_mut().run("tools.setColors", json!({"foreground": "#00ff00"})).unwrap(); - h.get_by_label("Default colours (D)").click(); - h.run_steps(2); - assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 0.0, 1.0]); - assert_eq!(rgb(h.state(), id, 6), [0, 0, 0, 255], "selected: {selected}"); - } - } - - /// The Studio layout (chips stacked, icons below) fits the height the toolbar reserves for - /// the chips, so the two-column check does not change with the theme. - #[test] - fn studio_color_chips_fit_the_reserved_height() { - // Chips, then the row holding the Switch Colors curve. - assert!(STUDIO_CHIP.0 + STUDIO_CHIP.1 + 8.0 + 4.0 <= chips_height(false, true, false)); - // Side by side: the chips plus the same row, and shorter than stacked. - assert!(STUDIO_CHIP.0 + 8.0 + 4.0 <= chips_height(false, true, true)); - assert!(chips_height(false, true, true) < chips_height(false, true, false)); - // The Studio block is taller than Photoshop's, and the two-column check knows it. - assert!(chips_height(false, true, false) > chips_height(false, false, false)); - } - - /// An incomplete entry never changes the colour and the field snaps back when focus leaves. - #[test] - fn color_panel_hex_field_ignores_partial_input() { - use egui_kittest::kittest::Queryable; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.tools.foreground = [0.2, 0.4, 0.6, 1.0]; - let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 300.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - color_field(app, ui); - } - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run_steps(2); - let fg = h.state().session.tools.foreground; - h.get_by_role(egui::accesskit::Role::TextInput).click(); - h.run_steps(1); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.run_steps(1); - for ch in "12zz".chars() { - h.event(egui::Event::Text(ch.to_string())); - h.run_steps(1); - } - assert_eq!(h.state().session.tools.foreground, fg, "invalid input changes nothing"); - h.key_press(egui::Key::Tab); - h.run_steps(2); - assert_eq!(h.get_by_role(egui::accesskit::Role::TextInput).value().as_deref(), Some("336699"), "snaps back to the colour"); - } - - /// The R, G and B fields next to the hex are editable, like the hex field. - #[test] - fn color_readout_rgb_fields_take_values() { - use egui_kittest::kittest::Queryable; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.tools.foreground = [0.0, 0.0, 0.0, 1.0]; - let mut h = field_harness(app); - // The only spin buttons are R, G and B, in that order. - h.query_all_by_role(egui::accesskit::Role::SpinButton).nth(1).unwrap().click(); - h.run_steps(1); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.run_steps(1); - for ch in "128".chars() { - h.event(egui::Event::Text(ch.to_string())); - h.run_steps(1); - } - h.key_press(egui::Key::Tab); - h.run_steps(2); - assert_eq!(srgb_bytes(h.state().session.tools.foreground), [0x00, 0x80, 0x00]); - } - - /// Typing a value into the R, G or B field recolours a selected shape as one undo step per - /// field, not one per keystroke. - #[test] - fn typing_an_rgb_value_recolours_the_selected_shape_in_one_step() { - use egui_kittest::kittest::Queryable; - use photocraft_doc::{Fill, LayerContent, LayerId}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); - let id = LayerId(app.run("shape.create", json!({"rect": [8, 8, 40, 30], "fill": "#000000"})).unwrap()["layer"].as_u64().unwrap()); - app.ui.tool = crate::state::Tool::Rectangle; - app.session.tools.foreground = [0.0, 0.0, 0.0, 1.0]; - let mut h = field_harness(app); - let fill = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(id).unwrap().content { - LayerContent::Shape(sh) => match &sh.fill { - Some(Fill::Solid(c)) => srgb_bytes([c.c[0], c.c[1], c.c[2], 1.0]), - _ => panic!("a solid fill"), - }, - _ => panic!("not a shape layer"), - }; - let steps = |app: &PhotocraftApp| app.session.active().unwrap().history.entries().len(); - let before = steps(h.state()); - // The only spin buttons are R, G and B, in that order. - for (field, text, steps_after, want) in [(1, "128", 1, [0x00, 0x80, 0x00]), (2, "64", 2, [0x00, 0x80, 0x40])] { - h.query_all_by_role(egui::accesskit::Role::SpinButton).nth(field).unwrap().click(); - h.run_steps(1); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.run_steps(1); - for ch in text.chars() { - h.event(egui::Event::Text(ch.to_string())); - h.run_steps(1); - } - h.key_press(egui::Key::Tab); - h.run_steps(2); - assert_eq!(fill(h.state()), want, "{text}"); - assert_eq!(steps(h.state()), before + steps_after, "{text}: one step for the typed value"); - } - // Typing into B again and clicking the field while B still has the focus: two steps, the - // click is not part of the typed value. - h.query_all_by_role(egui::accesskit::Role::SpinButton).nth(2).unwrap().click(); - h.run_steps(1); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.run_steps(1); - h.event(egui::Event::Text("9".into())); - h.run_steps(1); - assert_eq!(fill(h.state()), [0x00, 0x80, 0x09]); - assert_eq!(steps(h.state()), before + 3, "the typed 9"); - let min = h.ctx.input(|i| i.viewport_rect()).min; - click(&mut h, min + vec2(60.0, 10.0)); - assert_eq!(steps(h.state()), before + 4, "the click after typing"); - // A sum applies when Enter commits it, after the field let go of the focus: still the - // step of the "2" typed before it. - h.query_all_by_role(egui::accesskit::Role::SpinButton).next().unwrap().click(); - h.run_steps(1); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.run_steps(1); - for ch in "2*64".chars() { - h.event(egui::Event::Text(ch.to_string())); - h.run_steps(1); - } - h.key_press(egui::Key::Enter); - h.run_steps(2); - assert_eq!(fill(h.state())[0], 0x80, "2*64"); - assert_eq!(steps(h.state()), before + 5, "2*64 is one step"); - } - - /// The pro Color panel's hex readout edits the foreground too. - #[test] - fn color_field_hex_field_takes_a_typed_hex() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.tools.foreground = [1.0, 1.0, 1.0, 1.0]; - let mut h = field_harness(app); - type_hex(&mut h, "003300"); - assert_eq!(srgb_bytes(h.state().session.tools.foreground), [0x00, 0x33, 0x00]); - } - - /// The Color field fills the dock group, shrinks to leave room for the readout in a short group, and ignores a bad height. - #[test] - fn color_field_height_fills_the_group() { - assert_eq!(color_field_height(None, 300.0), 120.0); - assert_eq!(color_field_height(Some(500.0), 300.0), 468.0); - assert_eq!(color_field_height(Some(500.0), 200.0), 442.0); - assert_eq!(color_field_height(Some(60.0), 300.0), 28.0); - assert_eq!(color_field_height(Some(f32::NAN), 300.0), 120.0); - assert_eq!(color_field_height(Some(1.0e9), 300.0), 2000.0); - } - - /// A squeezed Color group still shows the hex/RGB readout, not only the spectrum field (#6885). - #[test] - fn docked_color_field_keeps_rgb_readout_at_compact_height() { - use egui_kittest::kittest::Queryable; - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - // Body height after tab strip and margins in a Color group at `compact_height` (130 pt). - let inner = 86.0; - let mut h = egui_kittest::Harness::builder().with_size(vec2(240.0, inner)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - ui.set_height(inner); - ui.data_mut(|d| d.insert_temp(color_field_fill_id(), inner)); - color_field(app, ui); - } - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); - h.run_steps(2); - assert!(h.query_by_label("R").is_some(), "RGB readout stays visible when the group is short"); - assert!(h.query_by_role(egui::accesskit::Role::TextInput).is_some(), "hex field stays visible"); - } - - fn field_harness(app: PhotocraftApp) -> egui_kittest::Harness<'static, PhotocraftApp> { - // 60 fps steps, so two clicks a frame apart are a double-click. - let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 200.0)).with_step_dt(1.0 / 60.0).build_ui_state( - |ui, app: &mut PhotocraftApp| { - if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - color_field(app, ui); - } - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run_steps(2); - h - } - - fn click(h: &mut egui_kittest::Harness<'_, PhotocraftApp>, p: egui::Pos2) { - h.hover_at(p); - h.run_steps(1); - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); - h.run_steps(1); - } - } - - /// A click on the background chip makes the field edit the background, not the foreground. - #[test] - fn background_chip_retargets_the_color_field() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.tools.foreground = [0.2, 0.4, 0.6, 1.0]; - app.session.tools.background = [0.0, 0.0, 0.0, 1.0]; - let mut h = field_harness(app); - let min = h.ctx.input(|i| i.viewport_rect()).min; - // The background chip's corner that the foreground chip doesn't cover. - click(&mut h, min + vec2(40.0, 40.0)); - // The field's top-left: no saturation, full brightness. - click(&mut h, min + vec2(60.0, 10.0)); - assert!(h.state().ui.color_panel.background); - let tools = &h.state().session.tools; - assert_eq!(tools.foreground, [0.2, 0.4, 0.6, 1.0]); - assert!(tools.background[..3].iter().all(|&v| v > 0.9), "{:?}", tools.background); - } - - #[test] - fn double_clicking_a_chip_opens_its_color_picker() { - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut h = field_harness(app); - let min = h.ctx.input(|i| i.viewport_rect()).min; - // The foreground point is where the chips overlap: the foreground is on top there. - for (p, target) in [(vec2(40.0, 40.0), "background"), (vec2(30.0, 30.0), "foreground")] { - h.state_mut().ui.dialogs.clear(); - // Past the last double-click, so this one isn't counted as a triple-click. - h.run_steps(40); - click(&mut h, min + p); - assert!(h.state().ui.dialogs.is_empty(), "a single click only picks the chip"); - click(&mut h, min + p); - let [d] = h.state().ui.dialogs.as_slice() else { panic!("one Color Picker") }; - assert_eq!(d.fields.get("__colorPicker").and_then(Value::as_str), Some(target)); - } - } - - /// With a shape tool and a shape layer selected, the field recolours its fill, and each - /// gesture is its own undo step: a click, every drag, and a swatch followed by a drag. A drag - /// only reaches the field after its press frame, so it must not join the step before it. - #[test] - fn color_panel_gestures_recolour_the_selected_shape_in_separate_steps() { - use photocraft_doc::{Fill, LayerContent, LayerId}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); - let id = LayerId(app.run("shape.create", json!({"rect": [8, 8, 40, 30], "fill": "#000000"})).unwrap()["layer"].as_u64().unwrap()); - app.ui.tool = crate::state::Tool::Rectangle; - let mut h = field_harness(app); - let is_foreground = |app: &PhotocraftApp| { - let fg = app.session.tools.foreground; - match &app.session.active().unwrap().doc.layer(id).unwrap().content { - LayerContent::Shape(sh) => matches!(&sh.fill, Some(Fill::Solid(c)) if (0..3).all(|i| (c.c[i] - fg[i]).abs() < 0.01)), - _ => panic!("not a shape layer"), - } - }; - let steps = |app: &PhotocraftApp| app.session.active().unwrap().history.entries().len(); - let before = steps(h.state()); - let min = h.ctx.input(|i| i.viewport_rect()).min; - click(&mut h, min + vec2(60.0, 10.0)); - assert!(is_foreground(h.state())); - assert_eq!(steps(h.state()), before + 1, "the click"); - drag(&mut h, min + vec2(120.0, 40.0), min + vec2(250.0, 120.0)); - assert!(is_foreground(h.state())); - assert_eq!(steps(h.state()), before + 2, "the drag is one more step"); - drag(&mut h, min + vec2(200.0, 60.0), min + vec2(100.0, 150.0)); - assert_eq!(steps(h.state()), before + 3, "the next drag another"); - // The drag ended on black, the first swatch: picking the shape's own colour changes - // nothing and adds no step (#5568), so take the second swatch. - let fg = h.state().session.tools.foreground; - let name = h.state_mut().run("swatches.list", json!({})).unwrap()["groups"][0]["swatches"][1]["name"].as_str().unwrap().to_string(); - crate::swatches_ui::use_swatch(h.state_mut(), &name, false); - assert_ne!(h.state().session.tools.foreground, fg, "{name} is another colour"); - assert_eq!(steps(h.state()), before + 4, "the swatch"); - drag(&mut h, min + vec2(150.0, 30.0), min + vec2(220.0, 100.0)); - assert!(is_foreground(h.state())); - assert_eq!(steps(h.state()), before + 5, "a drag after a swatch is a step of its own"); - } - - /// #5568: with a shape tool and a shape layer selected, the Color panel recolours its fill (keeping the fill's - /// opacity): a click is one undo step and a whole drag across the field is one more. - #[test] - fn color_panel_recolours_the_selected_shape_fill() { - use photocraft_doc::{Fill, LayerContent, LayerId}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); - let id = LayerId(app.run("shape.create", json!({"rect": [8, 8, 40, 30], "fill": [0.2, 0.4, 0.6, 0.5]})).unwrap()["layer"].as_u64().unwrap()); - app.ui.tool = crate::state::Tool::Rectangle; - let mut h = field_harness(app); - let fill = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(id).unwrap().content { - LayerContent::Shape(sh) => sh.fill.clone(), - _ => panic!("not a shape layer"), - }; - let steps = |app: &PhotocraftApp| app.session.active().unwrap().history.entries().len(); - let before = steps(h.state()); - let min = h.ctx.input(|i| i.viewport_rect()).min; - // The field's top-left: no saturation, full brightness. - click(&mut h, min + vec2(60.0, 10.0)); - let fg = h.state().session.tools.foreground; - assert_eq!(fill(h.state()), Some(Fill::Solid(photocraft_doc::Color::rgba(fg[0], fg[1], fg[2], 0.5)))); - assert_eq!(steps(h.state()), before + 1); - drag(&mut h, min + vec2(120.0, 40.0), min + vec2(250.0, 120.0)); - let fg = h.state().session.tools.foreground; - assert_eq!(fill(h.state()), Some(Fill::Solid(photocraft_doc::Color::rgba(fg[0], fg[1], fg[2], 0.5)))); - assert_eq!(steps(h.state()), before + 2, "the whole drag is one undo step"); - } - - /// Press at `from`, move to `to` in six steps and release, as egui sees a drag. - fn drag(h: &mut egui_kittest::Harness<'_, PhotocraftApp>, from: egui::Pos2, to: egui::Pos2) { - h.hover_at(from); - h.run_steps(1); - h.drag_at(from); - h.run_steps(1); - for i in 1..=6 { - h.hover_at(from + (to - from) * (i as f32 / 6.0)); - h.run_steps(1); - } - h.drop_at(to); - h.run_steps(3); - } - - /// Black carries neither hue nor saturation, a grey only the saturation it really has, and any - /// other colour nothing at all: the knob keeps where it was dragged instead of round-tripping - /// through RGB to the left edge (#3228). - #[test] - fn field_hsva_keeps_black_where_it_was_and_leaves_a_real_colour_alone() { - // Read back from black, as every frame does: nothing of the drag survives the RGB trip. - let black = field_hsva(egui::ecolor::Hsva::new(0.0, 0.0, 0.0, 1.0), (0.6, 1.0)); - assert_eq!((black.h, black.s), (0.6, 1.0), "the corner the drag ended in"); - // A grey: the saturation is genuinely zero — that is where the knob belongs — only the - // hue was undefined. - let grey = field_hsva(egui::ecolor::Hsva::new(0.0, 0.0, 0.5, 1.0), (0.6, 1.0)); - assert_eq!((grey.h, grey.s), (0.6, 0.0), "the grey stays on the left edge"); - // An ordinary colour is left as it is. - let red = field_hsva(egui::ecolor::Hsva::new(0.1, 0.8, 0.9, 1.0), (0.6, 1.0)); - assert_eq!((red.h, red.s), (0.1, 0.8)); - } - - /// Dragging the selector into the bottom-right corner picks black there and leaves the knob - /// in that corner: black has no saturation of its own, so it used to be read back as `s = 0` - /// and drawn at the bottom-left instead, one frame after the drag that put it on the right - /// (#3228). - #[test] - fn dragging_to_the_bottom_right_keeps_the_knob_there() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.tools.foreground = [1.0, 1.0, 1.0, 1.0]; - let mut h = field_harness(app); - let min = h.ctx.input(|i| i.viewport_rect()).min; - // Into the far bottom-right corner of the SV field: full saturation, no value. The end - // point lies past the corner on purpose — a real drag goes there too, and the widget - // clamps it to the field. - drag(&mut h, min + vec2(200.0, 60.0), min + vec2(280.0, 170.0)); - assert_eq!(srgb_bytes(h.state().session.tools.foreground), [0, 0, 0], "both corners are black"); - // What the knob is drawn from on the very next frame: the field kept the saturation the - // drag ended at (not the zero black reads back as), together with the hue. - let remembered: (f32, f32) = h.ctx.data(|d| d.get_temp(egui::Id::unique(("color-field-hue", false)))).expect("the field remembers what it showed"); - assert!(remembered.1 > 0.9, "the saturation the corner was dragged to: {remembered:?}"); - let shown = field_hsva(egui::ecolor::Hsva::new(0.0, 0.0, 0.0, 1.0), remembered); - assert!(shown.s > 0.9, "the knob stays at the right edge, not the left: {remembered:?}"); - assert!(shown.v < 0.01, "still black: {shown:?}"); - } - - /// Black has no hue of its own, so each chip remembers the hue last picked for it. - #[test] - fn each_chip_keeps_its_own_hue_on_black() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.tools.foreground = [0.0, 0.0, 0.0, 1.0]; - app.session.tools.background = [0.0, 0.0, 0.0, 1.0]; - let mut h = field_harness(app); - let min = h.ctx.input(|i| i.viewport_rect()).min; - // The hue strip runs from red at the top through blue (a third down) and green (two thirds). - let (strip_x, green, blue) = (285.0, 88.0, 48.0); - click(&mut h, min + vec2(strip_x, green)); - click(&mut h, min + vec2(40.0, 40.0)); - click(&mut h, min + vec2(strip_x, blue)); - click(&mut h, min + vec2(16.0, 16.0)); - // Near the field's top-right: high saturation and brightness. - click(&mut h, min + vec2(265.0, 10.0)); - let [r, g, b] = srgb_bytes(h.state().session.tools.foreground); - assert!(g > 200 && r < 64 && b < 64, "the foreground's green, not the background's blue: {:?}", [r, g, b]); - } -} +mod color_tests; #[cfg(test)] mod info_panel_sampler_tests { diff --git a/crates/ui-egui/src/panels/color_tests.rs b/crates/ui-egui/src/panels/color_tests.rs new file mode 100644 index 0000000000..8abdec859a --- /dev/null +++ b/crates/ui-egui/src/panels/color_tests.rs @@ -0,0 +1,614 @@ +use super::*; + +#[test] +/// #3323: the Color panel's HSB is Photoshop's (and the Color Picker's), on sRGB values, not +/// egui's linear-light HSV: a 50% grey has Brightness 50%, and the field's left edge halfway +/// down is that grey (128), not 188. +fn color_panel_hsb_is_srgb_like_photoshop() { + let grey = srgb_hsva([128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]); + assert!((grey.v - 128.0 / 255.0).abs() < 1e-3 && grey.s < 1e-3, "{grey:?}"); + let mid = hsva_srgb(egui::ecolor::Hsva::new(0.3, 0.0, 0.5, 1.0)); + assert!(mid[..3].iter().all(|v| (v - 0.5).abs() <= 1.0 / 255.0), "{mid:?}"); + // What the field paints there. + assert_eq!(hsva_color32(egui::ecolor::Hsva::new(0.3, 0.0, 0.5, 1.0)), Color32::from_gray(128)); + // The same numbers as the Color Picker dialog for a saturated colour. + let c = [0.847, 0.271, 0.180]; + let (ours, dialog) = (srgb_hsva([c[0], c[1], c[2], 1.0]), photocraft_color::convert::rgb_to_hsb(c)); + assert!((ours.h * 360.0 - dialog[0]).abs() < 0.5 && (ours.s - dialog[1]).abs() < 1e-3 && (ours.v - dialog[2]).abs() < 1e-3, "{ours:?} vs {dialog:?}"); +} + +#[test] +fn srgb_hsva_roundtrip() { + for c in [[0.847, 0.271, 0.180, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.2, 0.6, 0.4, 1.0]] { + let back = hsva_srgb(srgb_hsva(c)); + for i in 0..3 { + assert!((back[i] - c[i]).abs() <= 1.0 / 255.0, "{c:?} -> {back:?}"); + } + } +} + +/// #7793: the Color panel's field and hue strip pick on the frame the button goes down (no +/// release, no time passing) and follow moves smaller than egui's 6-point click threshold. +#[test] +fn color_panel_field_and_hue_strip_pick_on_press() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.tools.foreground = [0.2, 0.4, 0.6, 1.0]; + let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 300.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let at = (ui.cursor().min, ui.available_width()); + ui.data_mut(|d| d.insert_temp(egui::Id::unique("test-origin"), at)); + color_field(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(2); + let (o, w) = h.ctx.data(|d| d.get_temp::<(Pos2, f32)>(egui::Id::unique("test-origin"))).unwrap(); + let field_w = w - 38.0 - 14.0 - 16.0; + let press = |h: &mut egui_kittest::Harness<'static, PhotocraftApp>, at: Pos2, pressed: bool| { + h.event(egui::Event::PointerMoved(at)); + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + }; + let at = o + vec2(38.0 + 8.0 + field_w * 0.5, 60.0); + press(&mut h, at, true); + let picked = h.state().session.tools.foreground; + assert_ne!(picked, [0.2, 0.4, 0.6, 1.0], "the press itself picks"); + let hsva = srgb_hsva(picked); + assert!((hsva.s - 0.5).abs() < 0.03 && (hsva.v - 0.5).abs() < 0.03, "{hsva:?}"); + h.event(egui::Event::PointerMoved(at + vec2(3.0, 0.0))); + h.run_steps(1); + assert_ne!(h.state().session.tools.foreground, picked, "a small drag adjusts the pick"); + press(&mut h, at + vec2(3.0, 0.0), false); + h.run_steps(1); + // Hue strip: a press a third of the way down is a hue of about 240° at once. + let before = h.state().session.tools.foreground; + press(&mut h, o + vec2(38.0 + 8.0 + field_w + 8.0 + 7.0, 40.0), true); + let now = h.state().session.tools.foreground; + assert_ne!(now, before, "the strip picks on press"); + assert!((srgb_hsva(now).h * 360.0 - 240.0).abs() < 8.0, "{:?}", srgb_hsva(now)); +} + +/// Only the primary button picks: a right or middle press (and its release) on the field or +/// the hue strip leaves the foreground colour alone. +#[test] +fn color_panel_ignores_secondary_and_middle_presses() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.tools.foreground = [0.2, 0.4, 0.6, 1.0]; + let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 300.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let at = (ui.cursor().min, ui.available_width()); + ui.data_mut(|d| d.insert_temp(egui::Id::unique("test-origin"), at)); + color_field(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(2); + let (o, w) = h.ctx.data(|d| d.get_temp::<(Pos2, f32)>(egui::Id::unique("test-origin"))).unwrap(); + let field_w = w - 38.0 - 14.0 - 16.0; + let field = o + vec2(38.0 + 8.0 + field_w * 0.5, 60.0); + let strip = o + vec2(38.0 + 8.0 + field_w + 8.0 + 7.0, 40.0); + for at in [field, strip] { + for button in [egui::PointerButton::Secondary, egui::PointerButton::Middle] { + for pressed in [true, false] { + h.event(egui::Event::PointerMoved(at)); + h.event(egui::Event::PointerButton { pos: at, button, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + assert_eq!(h.state().session.tools.foreground, [0.2, 0.4, 0.6, 1.0], "{button:?} pressed={pressed} at {at:?}"); + } + } + } +} + +/// Click the hex field, select its text and type `text` one key per frame. +fn type_hex(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, text: &str) { + use egui_kittest::kittest::Queryable; + h.get_by_role(egui::accesskit::Role::TextInput).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + for ch in text.chars() { + h.event(egui::Event::Text(ch.to_string())); + h.run_steps(1); + } +} + +/// The Color panel's hex readout is editable, with or without the leading `#`. +#[test] +fn color_panel_hex_field_takes_a_typed_hex() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.tools.foreground = [1.0, 1.0, 1.0, 1.0]; + let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 300.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + color_field(app, ui); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(2); + type_hex(&mut h, "003300"); + assert_eq!(srgb_bytes(h.state().session.tools.foreground), [0x00, 0x33, 0x00]); + // A leading '#' is accepted too. + type_hex(&mut h, "#ff8000"); + assert_eq!(srgb_bytes(h.state().session.tools.foreground), [0xff, 0x80, 0x00]); +} + +/// Themes with `round_chips` (Studio) draw round chips, stacked or side by side in two tool +/// columns, with Switch Colors right under them and Default Colors at the top-right corner +/// (stacked) or the left edge (side by side); both buttons work in either layout. +#[test] +fn studio_color_chips_keep_default_and_swap_buttons_below() { + use egui_kittest::kittest::Queryable; + for (kind, two_columns) in [ + (crate::theme::ThemeKind::Studio, false), + (crate::theme::ThemeKind::StudioLight, false), + (crate::theme::ThemeKind::Studio, true), + (crate::theme::ThemeKind::StudioLight, true), + ] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.tools.foreground = [1.0, 0.0, 0.0, 1.0]; + app.session.tools.background = [0.0, 0.0, 1.0, 1.0]; + let mut h = egui_kittest::Harness::builder().with_size(vec2(80.0, 120.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let w = ui.available_width(); + color_chips(app, ui, two_columns, w) + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, kind); + h.run_steps(2); + h.get_by_label("Swap colours (X)").click(); + h.run_steps(2); + assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 1.0, 1.0], "{kind:?}"); + assert_eq!(h.state().session.tools.background, [1.0, 0.0, 0.0, 1.0], "{kind:?}"); + h.get_by_label("Default colours (D)").click(); + h.run_steps(2); + assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 0.0, 1.0], "{kind:?}"); + assert_eq!(h.state().session.tools.background, [1.0, 1.0, 1.0, 1.0], "{kind:?}"); + } +} + +/// While characters are highlighted in a type layer being edited, the Switch Colors and +/// Default Colors buttons recolour them with the new foreground (#5690); without a selection +/// they only change the tool colours, as before. +#[test] +fn swap_and_default_colors_recolour_selected_type() { + use egui_kittest::kittest::Queryable; + use photocraft_doc::LayerId; + let rgb = |app: &PhotocraftApp, id: LayerId, ci: usize| { + let doc = &app.session.active().unwrap().doc; + let photocraft_doc::LayerContent::Text(t) = &doc.layer(id).unwrap().content else { panic!("not a type layer") }; + let b = t.text.char_indices().nth(ci).map_or(t.text.len(), |(b, _)| b); + let mut at = 0; + for r in t.char_runs() { + if b < at + r.len { + return r.style.color.to_rgba8(); + } + at += r.len; + } + [0; 4] + }; + for selected in [true, false] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let made = app.run("type.create", json!({"text": "Hello world", "size": 40, "x": 50, "y": 150, "color": "#000000"})).unwrap(); + let id = LayerId(made["layer"].as_u64().unwrap()); + app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); + let anchor = if selected { 6 } else { 11 }; + app.ui.text_edit = Some(crate::state::TextEdit { + layer: id.0, + document: None, + caret: 11, + anchor, + session: "s".into(), + created: false, + mask: false, + dragging: false, + resize: None, + preedit: None, + }); + let mut h = egui_kittest::Harness::builder().with_size(vec2(80.0, 120.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let w = ui.available_width(); + color_chips(app, ui, false, w) + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(2); + h.get_by_label("Swap colours (X)").click(); + h.run_steps(2); + assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 1.0, 1.0]); + assert_eq!(h.state().session.tools.background, [1.0, 0.0, 0.0, 1.0]); + let blue = if selected { [0, 0, 255, 255] } else { [0, 0, 0, 255] }; + assert_eq!(rgb(h.state(), id, 0), [0, 0, 0, 255], "unselected characters keep their colour"); + assert_eq!((rgb(h.state(), id, 6), rgb(h.state(), id, 10)), (blue, blue), "selected: {selected}"); + // Default Colors: the selection takes black, the new foreground. + h.state_mut().run("tools.setColors", json!({"foreground": "#00ff00"})).unwrap(); + h.get_by_label("Default colours (D)").click(); + h.run_steps(2); + assert_eq!(h.state().session.tools.foreground, [0.0, 0.0, 0.0, 1.0]); + assert_eq!(rgb(h.state(), id, 6), [0, 0, 0, 255], "selected: {selected}"); + } +} + +/// The Studio layout (chips stacked, icons below) fits the height the toolbar reserves for +/// the chips, so the two-column check does not change with the theme. +#[test] +fn studio_color_chips_fit_the_reserved_height() { + // Chips, then the row holding the Switch Colors curve. + assert!(STUDIO_CHIP.0 + STUDIO_CHIP.1 + 8.0 + 4.0 <= chips_height(false, true, false)); + // Side by side: the chips plus the same row, and shorter than stacked. + assert!(STUDIO_CHIP.0 + 8.0 + 4.0 <= chips_height(false, true, true)); + assert!(chips_height(false, true, true) < chips_height(false, true, false)); + // The Studio block is taller than Photoshop's, and the two-column check knows it. + assert!(chips_height(false, true, false) > chips_height(false, false, false)); +} + +/// An incomplete entry never changes the colour and the field snaps back when focus leaves. +#[test] +fn color_panel_hex_field_ignores_partial_input() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.tools.foreground = [0.2, 0.4, 0.6, 1.0]; + let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 300.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + color_field(app, ui); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(2); + let fg = h.state().session.tools.foreground; + h.get_by_role(egui::accesskit::Role::TextInput).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + for ch in "12zz".chars() { + h.event(egui::Event::Text(ch.to_string())); + h.run_steps(1); + } + assert_eq!(h.state().session.tools.foreground, fg, "invalid input changes nothing"); + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert_eq!(h.get_by_role(egui::accesskit::Role::TextInput).value().as_deref(), Some("336699"), "snaps back to the colour"); +} + +/// The R, G and B fields next to the hex are editable, like the hex field. +#[test] +fn color_readout_rgb_fields_take_values() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.tools.foreground = [0.0, 0.0, 0.0, 1.0]; + let mut h = field_harness(app); + // The only spin buttons are R, G and B, in that order. + h.query_all_by_role(egui::accesskit::Role::SpinButton).nth(1).unwrap().click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + for ch in "128".chars() { + h.event(egui::Event::Text(ch.to_string())); + h.run_steps(1); + } + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert_eq!(srgb_bytes(h.state().session.tools.foreground), [0x00, 0x80, 0x00]); +} + +/// Typing a value into the R, G or B field recolours a selected shape as one undo step per +/// field, not one per keystroke. +#[test] +fn typing_an_rgb_value_recolours_the_selected_shape_in_one_step() { + use egui_kittest::kittest::Queryable; + use photocraft_doc::{Fill, LayerContent, LayerId}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + let id = LayerId(app.run("shape.create", json!({"rect": [8, 8, 40, 30], "fill": "#000000"})).unwrap()["layer"].as_u64().unwrap()); + app.ui.tool = crate::state::Tool::Rectangle; + app.session.tools.foreground = [0.0, 0.0, 0.0, 1.0]; + let mut h = field_harness(app); + let fill = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(id).unwrap().content { + LayerContent::Shape(sh) => match &sh.fill { + Some(Fill::Solid(c)) => srgb_bytes([c.c[0], c.c[1], c.c[2], 1.0]), + _ => panic!("a solid fill"), + }, + _ => panic!("not a shape layer"), + }; + let steps = |app: &PhotocraftApp| app.session.active().unwrap().history.entries().len(); + let before = steps(h.state()); + // The only spin buttons are R, G and B, in that order. + for (field, text, steps_after, want) in [(1, "128", 1, [0x00, 0x80, 0x00]), (2, "64", 2, [0x00, 0x80, 0x40])] { + h.query_all_by_role(egui::accesskit::Role::SpinButton).nth(field).unwrap().click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + for ch in text.chars() { + h.event(egui::Event::Text(ch.to_string())); + h.run_steps(1); + } + h.key_press(egui::Key::Tab); + h.run_steps(2); + assert_eq!(fill(h.state()), want, "{text}"); + assert_eq!(steps(h.state()), before + steps_after, "{text}: one step for the typed value"); + } + // Typing into B again and clicking the field while B still has the focus: two steps, the + // click is not part of the typed value. + h.query_all_by_role(egui::accesskit::Role::SpinButton).nth(2).unwrap().click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.event(egui::Event::Text("9".into())); + h.run_steps(1); + assert_eq!(fill(h.state()), [0x00, 0x80, 0x09]); + assert_eq!(steps(h.state()), before + 3, "the typed 9"); + let min = h.ctx.input(|i| i.viewport_rect()).min; + click(&mut h, min + vec2(60.0, 10.0)); + assert_eq!(steps(h.state()), before + 4, "the click after typing"); + // A sum applies when Enter commits it, after the field let go of the focus: still the + // step of the "2" typed before it. + h.query_all_by_role(egui::accesskit::Role::SpinButton).next().unwrap().click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + for ch in "2*64".chars() { + h.event(egui::Event::Text(ch.to_string())); + h.run_steps(1); + } + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(fill(h.state())[0], 0x80, "2*64"); + assert_eq!(steps(h.state()), before + 5, "2*64 is one step"); +} + +/// The pro Color panel's hex readout edits the foreground too. +#[test] +fn color_field_hex_field_takes_a_typed_hex() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.tools.foreground = [1.0, 1.0, 1.0, 1.0]; + let mut h = field_harness(app); + type_hex(&mut h, "003300"); + assert_eq!(srgb_bytes(h.state().session.tools.foreground), [0x00, 0x33, 0x00]); +} + +/// The Color field fills the dock group, shrinks to leave room for the readout in a short group, and ignores a bad height. +#[test] +fn color_field_height_fills_the_group() { + assert_eq!(color_field_height(None, 300.0), 120.0); + assert_eq!(color_field_height(Some(500.0), 300.0), 468.0); + assert_eq!(color_field_height(Some(500.0), 200.0), 442.0); + assert_eq!(color_field_height(Some(60.0), 300.0), 28.0); + assert_eq!(color_field_height(Some(f32::NAN), 300.0), 120.0); + assert_eq!(color_field_height(Some(1.0e9), 300.0), 2000.0); +} + +/// A squeezed Color group still shows the hex/RGB readout, not only the spectrum field (#6885). +#[test] +fn docked_color_field_keeps_rgb_readout_at_compact_height() { + use egui_kittest::kittest::Queryable; + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + // Body height after tab strip and margins in a Color group at `compact_height` (130 pt). + let inner = 86.0; + let mut h = egui_kittest::Harness::builder().with_size(vec2(240.0, inner)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + ui.set_height(inner); + ui.data_mut(|d| d.insert_temp(color_field_fill_id(), inner)); + color_field(app, ui); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); + h.run_steps(2); + assert!(h.query_by_label("R").is_some(), "RGB readout stays visible when the group is short"); + assert!(h.query_by_role(egui::accesskit::Role::TextInput).is_some(), "hex field stays visible"); +} + +fn field_harness(app: PhotocraftApp) -> egui_kittest::Harness<'static, PhotocraftApp> { + // 60 fps steps, so two clicks a frame apart are a double-click. + let mut h = egui_kittest::Harness::builder().with_size(vec2(300.0, 200.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + color_field(app, ui); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(2); + h +} + +fn click(h: &mut egui_kittest::Harness<'_, PhotocraftApp>, p: egui::Pos2) { + h.hover_at(p); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + } +} + +/// A click on the background chip makes the field edit the background, not the foreground. +#[test] +fn background_chip_retargets_the_color_field() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.tools.foreground = [0.2, 0.4, 0.6, 1.0]; + app.session.tools.background = [0.0, 0.0, 0.0, 1.0]; + let mut h = field_harness(app); + let min = h.ctx.input(|i| i.viewport_rect()).min; + // The background chip's corner that the foreground chip doesn't cover. + click(&mut h, min + vec2(40.0, 40.0)); + // The field's top-left: no saturation, full brightness. + click(&mut h, min + vec2(60.0, 10.0)); + assert!(h.state().ui.color_panel.background); + let tools = &h.state().session.tools; + assert_eq!(tools.foreground, [0.2, 0.4, 0.6, 1.0]); + assert!(tools.background[..3].iter().all(|&v| v > 0.9), "{:?}", tools.background); +} + +#[test] +fn double_clicking_a_chip_opens_its_color_picker() { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut h = field_harness(app); + let min = h.ctx.input(|i| i.viewport_rect()).min; + // The foreground point is where the chips overlap: the foreground is on top there. + for (p, target) in [(vec2(40.0, 40.0), "background"), (vec2(30.0, 30.0), "foreground")] { + h.state_mut().ui.dialogs.clear(); + // Past the last double-click, so this one isn't counted as a triple-click. + h.run_steps(40); + click(&mut h, min + p); + assert!(h.state().ui.dialogs.is_empty(), "a single click only picks the chip"); + click(&mut h, min + p); + let [d] = h.state().ui.dialogs.as_slice() else { panic!("one Color Picker") }; + assert_eq!(d.fields.get("__colorPicker").and_then(Value::as_str), Some(target)); + } +} + +/// With a shape tool and a shape layer selected, the field recolours its fill, and each +/// gesture is its own undo step: a click, every drag, and a swatch followed by a drag. A drag +/// only reaches the field after its press frame, so it must not join the step before it. +#[test] +fn color_panel_gestures_recolour_the_selected_shape_in_separate_steps() { + use photocraft_doc::{Fill, LayerContent, LayerId}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + let id = LayerId(app.run("shape.create", json!({"rect": [8, 8, 40, 30], "fill": "#000000"})).unwrap()["layer"].as_u64().unwrap()); + app.ui.tool = crate::state::Tool::Rectangle; + let mut h = field_harness(app); + let is_foreground = |app: &PhotocraftApp| { + let fg = app.session.tools.foreground; + match &app.session.active().unwrap().doc.layer(id).unwrap().content { + LayerContent::Shape(sh) => matches!(&sh.fill, Some(Fill::Solid(c)) if (0..3).all(|i| (c.c[i] - fg[i]).abs() < 0.01)), + _ => panic!("not a shape layer"), + } + }; + let steps = |app: &PhotocraftApp| app.session.active().unwrap().history.entries().len(); + let before = steps(h.state()); + let min = h.ctx.input(|i| i.viewport_rect()).min; + click(&mut h, min + vec2(60.0, 10.0)); + assert!(is_foreground(h.state())); + assert_eq!(steps(h.state()), before + 1, "the click"); + drag(&mut h, min + vec2(120.0, 40.0), min + vec2(250.0, 120.0)); + assert!(is_foreground(h.state())); + assert_eq!(steps(h.state()), before + 2, "the drag is one more step"); + drag(&mut h, min + vec2(200.0, 60.0), min + vec2(100.0, 150.0)); + assert_eq!(steps(h.state()), before + 3, "the next drag another"); + // The drag ended on black, the first swatch: picking the shape's own colour changes + // nothing and adds no step (#5568), so take the second swatch. + let fg = h.state().session.tools.foreground; + let name = h.state_mut().run("swatches.list", json!({})).unwrap()["groups"][0]["swatches"][1]["name"].as_str().unwrap().to_string(); + crate::swatches_ui::use_swatch(h.state_mut(), &name, false); + assert_ne!(h.state().session.tools.foreground, fg, "{name} is another colour"); + assert_eq!(steps(h.state()), before + 4, "the swatch"); + drag(&mut h, min + vec2(150.0, 30.0), min + vec2(220.0, 100.0)); + assert!(is_foreground(h.state())); + assert_eq!(steps(h.state()), before + 5, "a drag after a swatch is a step of its own"); +} + +/// #5568: with a shape tool and a shape layer selected, the Color panel recolours its fill (keeping the fill's +/// opacity): a click is one undo step and a whole drag across the field is one more. +#[test] +fn color_panel_recolours_the_selected_shape_fill() { + use photocraft_doc::{Fill, LayerContent, LayerId}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + let id = LayerId(app.run("shape.create", json!({"rect": [8, 8, 40, 30], "fill": [0.2, 0.4, 0.6, 0.5]})).unwrap()["layer"].as_u64().unwrap()); + app.ui.tool = crate::state::Tool::Rectangle; + let mut h = field_harness(app); + let fill = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(id).unwrap().content { + LayerContent::Shape(sh) => sh.fill.clone(), + _ => panic!("not a shape layer"), + }; + let steps = |app: &PhotocraftApp| app.session.active().unwrap().history.entries().len(); + let before = steps(h.state()); + let min = h.ctx.input(|i| i.viewport_rect()).min; + // The field's top-left: no saturation, full brightness. + click(&mut h, min + vec2(60.0, 10.0)); + let fg = h.state().session.tools.foreground; + assert_eq!(fill(h.state()), Some(Fill::Solid(photocraft_doc::Color::rgba(fg[0], fg[1], fg[2], 0.5)))); + assert_eq!(steps(h.state()), before + 1); + drag(&mut h, min + vec2(120.0, 40.0), min + vec2(250.0, 120.0)); + let fg = h.state().session.tools.foreground; + assert_eq!(fill(h.state()), Some(Fill::Solid(photocraft_doc::Color::rgba(fg[0], fg[1], fg[2], 0.5)))); + assert_eq!(steps(h.state()), before + 2, "the whole drag is one undo step"); +} + +/// Press at `from`, move to `to` in six steps and release, as egui sees a drag. +fn drag(h: &mut egui_kittest::Harness<'_, PhotocraftApp>, from: egui::Pos2, to: egui::Pos2) { + h.hover_at(from); + h.run_steps(1); + h.drag_at(from); + h.run_steps(1); + for i in 1..=6 { + h.hover_at(from + (to - from) * (i as f32 / 6.0)); + h.run_steps(1); + } + h.drop_at(to); + h.run_steps(3); +} + +/// Black carries neither hue nor saturation, a grey only the saturation it really has, and any +/// other colour nothing at all: the knob keeps where it was dragged instead of round-tripping +/// through RGB to the left edge (#3228). +#[test] +fn field_hsva_keeps_black_where_it_was_and_leaves_a_real_colour_alone() { + // Read back from black, as every frame does: nothing of the drag survives the RGB trip. + let black = field_hsva(egui::ecolor::Hsva::new(0.0, 0.0, 0.0, 1.0), (0.6, 1.0)); + assert_eq!((black.h, black.s), (0.6, 1.0), "the corner the drag ended in"); + // A grey: the saturation is genuinely zero — that is where the knob belongs — only the + // hue was undefined. + let grey = field_hsva(egui::ecolor::Hsva::new(0.0, 0.0, 0.5, 1.0), (0.6, 1.0)); + assert_eq!((grey.h, grey.s), (0.6, 0.0), "the grey stays on the left edge"); + // An ordinary colour is left as it is. + let red = field_hsva(egui::ecolor::Hsva::new(0.1, 0.8, 0.9, 1.0), (0.6, 1.0)); + assert_eq!((red.h, red.s), (0.1, 0.8)); +} + +/// Dragging the selector into the bottom-right corner picks black there and leaves the knob +/// in that corner: black has no saturation of its own, so it used to be read back as `s = 0` +/// and drawn at the bottom-left instead, one frame after the drag that put it on the right +/// (#3228). +#[test] +fn dragging_to_the_bottom_right_keeps_the_knob_there() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.tools.foreground = [1.0, 1.0, 1.0, 1.0]; + let mut h = field_harness(app); + let min = h.ctx.input(|i| i.viewport_rect()).min; + // Into the far bottom-right corner of the SV field: full saturation, no value. The end + // point lies past the corner on purpose — a real drag goes there too, and the widget + // clamps it to the field. + drag(&mut h, min + vec2(200.0, 60.0), min + vec2(280.0, 170.0)); + assert_eq!(srgb_bytes(h.state().session.tools.foreground), [0, 0, 0], "both corners are black"); + // What the knob is drawn from on the very next frame: the field kept the saturation the + // drag ended at (not the zero black reads back as), together with the hue. + let remembered: (f32, f32) = h.ctx.data(|d| d.get_temp(egui::Id::unique(("color-field-hue", false)))).expect("the field remembers what it showed"); + assert!(remembered.1 > 0.9, "the saturation the corner was dragged to: {remembered:?}"); + let shown = field_hsva(egui::ecolor::Hsva::new(0.0, 0.0, 0.0, 1.0), remembered); + assert!(shown.s > 0.9, "the knob stays at the right edge, not the left: {remembered:?}"); + assert!(shown.v < 0.01, "still black: {shown:?}"); +} + +/// Black has no hue of its own, so each chip remembers the hue last picked for it. +#[test] +fn each_chip_keeps_its_own_hue_on_black() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.tools.foreground = [0.0, 0.0, 0.0, 1.0]; + app.session.tools.background = [0.0, 0.0, 0.0, 1.0]; + let mut h = field_harness(app); + let min = h.ctx.input(|i| i.viewport_rect()).min; + // The hue strip runs from red at the top through blue (a third down) and green (two thirds). + let (strip_x, green, blue) = (285.0, 88.0, 48.0); + click(&mut h, min + vec2(strip_x, green)); + click(&mut h, min + vec2(40.0, 40.0)); + click(&mut h, min + vec2(strip_x, blue)); + click(&mut h, min + vec2(16.0, 16.0)); + // Near the field's top-right: high saturation and brightness. + click(&mut h, min + vec2(265.0, 10.0)); + let [r, g, b] = srgb_bytes(h.state().session.tools.foreground); + assert!(g > 200 && r < 64 && b < 64, "the foreground's green, not the background's blue: {:?}", [r, g, b]); +} From e0fe2f2d7ab1c1289ca85eb2bf5cfba6747d9718 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:11 +0000 Subject: [PATCH 087/259] refactor(ui-egui): move panels.rs type_flyout_tests to panels/type_flyout_tests.rs --- crates/ui-egui/src/panels.rs | 397 +----------------- .../ui-egui/src/panels/type_flyout_tests.rs | 385 +++++++++++++++++ 2 files changed, 386 insertions(+), 396 deletions(-) create mode 100644 crates/ui-egui/src/panels/type_flyout_tests.rs diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 678f38bc4f..85912c23c7 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -5606,402 +5606,7 @@ mod tool_flyout_drag_tests { } #[cfg(test)] -mod type_flyout_tests { - use super::*; - - fn frame(app: &mut PhotocraftApp, ctx: &egui::Context, time: f64, events: Vec) { - let mut out = ctx.run_ui( - egui::RawInput { time: Some(time), events, screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1200.0, 1800.0))), ..Default::default() }, - |ui| toolbar(app, ui), - ); - out.textures_delta.clear(); - } - - #[test] - fn long_press_type_button_selects_type_then_vertical_from_the_flyout() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - assert_ne!(app.ui.tool, Tool::Type); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - frame(&mut app, &ctx, 0.0, vec![]); - frame(&mut app, &ctx, 0.1, vec![]); - let index = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&Tool::Type)).unwrap(); - let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; - let mut buttons: Vec = ctx.viewport(|v| { - v.prev_pass - .widgets - .layers() - .flat_map(|(_, w)| w.iter()) - .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) - .map(|w| w.rect) - .collect() - }); - buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); - let at = buttons[index].center(); - let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(at), pointer(at, true)]); - frame(&mut app, &ctx, 1.36, vec![]); - assert_eq!( - ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::unique("tool-flyout"))).map(|(id, _)| id), - Some(egui::Id::unique(("tool-slot", index))) - ); - frame(&mut app, &ctx, 1.4, vec![pointer(at, false)]); - frame(&mut app, &ctx, 1.45, vec![]); - // The held button's tool is selected, as Photoshop does (#4453). - assert_eq!(app.ui.tool, Tool::Type); - let key = egui::Id::unique(("tool-slot", index)); - let menu = ctx.memory(|m| m.area_rect(key.with("flyout"))).unwrap(); - let row = egui::pos2(menu.left() + 65.0, menu.top() + 39.0 + 8.0); - frame(&mut app, &ctx, 2.0, vec![egui::Event::PointerMoved(row), pointer(row, true)]); - frame(&mut app, &ctx, 2.05, vec![pointer(row, false)]); - assert_eq!(app.ui.tool, Tool::VerticalType); - assert!(ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::unique("tool-flyout"))).is_none()); - } - - /// #4444: click and hold on Change Screen Mode opens its list like the tool flyouts, without - /// cycling the mode on release; a plain click still cycles, and right-click still opens it. - #[test] - fn long_press_screen_mode_opens_the_modes_without_cycling() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - frame(&mut app, &ctx, 0.0, vec![]); - frame(&mut app, &ctx, 0.1, vec![]); - let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; - // The toolbar's last button: Change Screen Mode, after Quick Mask. - let at = ctx - .viewport(|v| { - v.prev_pass - .widgets - .layers() - .flat_map(|(_, w)| w.iter()) - .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) - .map(|w| w.rect) - .max_by(|a, b| a.top().total_cmp(&b.top()).then(a.left().total_cmp(&b.left()))) - }) - .unwrap() - .center(); - let standard = |app: &PhotocraftApp| crate::view_cmds::checked(app, "view.screenMode.standard") == Some(true); - let menu_open = |ctx: &egui::Context| egui::Popup::is_any_open(ctx); - let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - assert!(standard(&app)); - // Hold, then release: the list opens and stays open, and the mode is unchanged. - frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(at), pointer(at, true)]); - frame(&mut app, &ctx, 1.2, vec![]); - assert!(!menu_open(&ctx), "not before the hold time"); - frame(&mut app, &ctx, 1.4, vec![]); - assert!(menu_open(&ctx), "open while still held"); - frame(&mut app, &ctx, 1.5, vec![pointer(at, false)]); - frame(&mut app, &ctx, 1.55, vec![]); - assert!(menu_open(&ctx), "the release keeps it open"); - assert!(standard(&app), "the release doesn't cycle the mode"); - // Escape closes it; a plain click cycles the mode and opens nothing. - frame( - &mut app, - &ctx, - 2.0, - vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], - ); - frame(&mut app, &ctx, 2.05, vec![]); - assert!(!menu_open(&ctx)); - frame(&mut app, &ctx, 3.0, vec![egui::Event::PointerMoved(at), pointer(at, true)]); - frame(&mut app, &ctx, 3.1, vec![pointer(at, false)]); - frame(&mut app, &ctx, 3.15, vec![]); - assert!(!standard(&app), "a click cycles"); - assert!(!menu_open(&ctx)); - // Right-click opens it too. - let secondary = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }; - frame(&mut app, &ctx, 4.0, vec![secondary(true)]); - frame(&mut app, &ctx, 4.05, vec![secondary(false)]); - frame(&mut app, &ctx, 4.1, vec![]); - assert!(menu_open(&ctx)); - } - - /// Every text drawn in one toolbar frame. - fn frame_texts(app: &mut PhotocraftApp, ctx: &egui::Context, time: f64, events: Vec) -> Vec { - fn collect(shape: &egui::Shape, out: &mut Vec) { - match shape { - egui::Shape::Text(t) => out.push(t.galley.text().to_string()), - egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)), - _ => {} - } - } - let mut out = ctx.run_ui( - egui::RawInput { time: Some(time), events, screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1200.0, 1800.0))), ..Default::default() }, - |ui| toolbar(app, ui), - ); - out.textures_delta.clear(); - let mut texts = Vec::new(); - out.shapes.iter().for_each(|c| collect(&c.shape, &mut texts)); - texts - } - - /// #4450: no tool tooltip while a flyout is open or a tool button is held to open one, for the - /// held tool or any other; a plain hover still shows its tooltip. - #[test] - fn no_tooltips_over_an_open_tool_flyout() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - frame(&mut app, &ctx, 0.0, vec![]); - frame(&mut app, &ctx, 0.1, vec![]); - let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; - let mut buttons: Vec = ctx.viewport(|v| { - v.prev_pass - .widgets - .layers() - .flat_map(|(_, w)| w.iter()) - .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) - .map(|w| w.rect) - .collect() - }); - buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); - let slot_of = |tool: Tool| TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&tool)).unwrap(); - let (eyedropper, brush) = (buttons[slot_of(Tool::Eyedropper)].center(), buttons[slot_of(Tool::Brush)].center()); - let tip = |tool: Tool| format!("{} ({})", tl!(tool.label()), tool.key()); - let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - // A plain hover shows the tooltip. - frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(brush)]); - let mut texts = Vec::new(); - for k in 1..=10 { - texts = frame_texts(&mut app, &ctx, 1.0 + 0.1 * f64::from(k), vec![]); - } - assert!(texts.contains(&tip(Tool::Brush)), "hovered long enough: {texts:?}"); - // Held on the Eyedropper: no tooltip before or after its flyout opens. - frame(&mut app, &ctx, 3.0, vec![egui::Event::PointerMoved(eyedropper), pointer(eyedropper, true)]); - for k in 1..=10 { - let texts = frame_texts(&mut app, &ctx, 3.0 + 0.1 * f64::from(k), vec![]); - assert!(!texts.contains(&tip(Tool::Eyedropper)), "held {k}: {texts:?}"); - } - assert!(ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::unique("tool-flyout"))).is_some(), "the flyout is open"); - // Released, with the flyout still open: none for the held tool or another one. - frame(&mut app, &ctx, 4.1, vec![pointer(eyedropper, false)]); - for (start, at, tool) in [(4.5, eyedropper, Tool::Eyedropper), (6.0, brush, Tool::Brush)] { - frame(&mut app, &ctx, start, vec![egui::Event::PointerMoved(at)]); - for k in 1..=10 { - let texts = frame_texts(&mut app, &ctx, start + 0.1 * f64::from(k), vec![]); - assert!(!texts.contains(&tip(tool)), "{tool:?} under the flyout: {texts:?}"); - } - } - } - - /// #4460: a press outside an open flyout closes it, even when it becomes a drag (cropping or - /// painting on the canvas) rather than a click; a press on the flyout keeps it for its pick. - /// #4932: so does a click on its own tool button. - #[test] - fn a_drag_outside_closes_the_tool_flyout() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - frame(&mut app, &ctx, 0.0, vec![]); - frame(&mut app, &ctx, 0.1, vec![]); - let index = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&Tool::Brush)).unwrap(); - let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; - let mut buttons: Vec = ctx.viewport(|v| { - v.prev_pass - .widgets - .layers() - .flat_map(|(_, w)| w.iter()) - .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) - .map(|w| w.rect) - .collect() - }); - buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); - let at = buttons[index].center(); - let flyout = |ctx: &egui::Context| ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::unique("tool-flyout"))).is_some(); - let secondary = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }; - let primary = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - // A right-click on the button of an open flyout closes it (#4932), so open only a closed one. - let open = |app: &mut PhotocraftApp, t: f64| { - if !flyout(&ctx) { - frame(app, &ctx, t, vec![egui::Event::PointerMoved(at), secondary(true)]); - frame(app, &ctx, t + 0.05, vec![secondary(false)]); - frame(app, &ctx, t + 0.1, vec![]); - } - assert!(flyout(&ctx), "right-click opens it"); - }; - // A press on the flyout itself keeps it open (the row picks on release). - open(&mut app, 1.0); - let menu = ctx.memory(|m| m.area_rect(egui::Id::unique(("tool-slot", index)).with("flyout"))).unwrap(); - frame(&mut app, &ctx, 1.5, vec![egui::Event::PointerMoved(menu.center()), primary(menu.center(), true)]); - assert!(flyout(&ctx), "a press on the flyout keeps it"); - frame(&mut app, &ctx, 1.55, vec![primary(menu.center(), false)]); - // A drag far from the toolbar (the canvas) closes it as soon as it starts. - open(&mut app, 2.0); - let canvas = egui::pos2(900.0, 900.0); - frame(&mut app, &ctx, 2.5, vec![egui::Event::PointerMoved(canvas), primary(canvas, true)]); - frame(&mut app, &ctx, 2.55, vec![egui::Event::PointerMoved(canvas + vec2(80.0, 60.0))]); - assert!(!flyout(&ctx), "a press outside closes it, even one that becomes a drag"); - frame(&mut app, &ctx, 2.6, vec![primary(canvas + vec2(80.0, 60.0), false)]); - assert!(!flyout(&ctx)); - // #4932: clicking its own tool button again closes it, with either button. - open(&mut app, 3.0); - frame(&mut app, &ctx, 3.5, vec![egui::Event::PointerMoved(at), secondary(true)]); - frame(&mut app, &ctx, 3.55, vec![secondary(false)]); - frame(&mut app, &ctx, 3.6, vec![]); - assert!(!flyout(&ctx), "a second right-click on the button closes it"); - open(&mut app, 4.0); - app.ui.tool = Tool::Move; - frame(&mut app, &ctx, 4.5, vec![egui::Event::PointerMoved(at), primary(at, true)]); - frame(&mut app, &ctx, 4.55, vec![primary(at, false)]); - frame(&mut app, &ctx, 4.6, vec![]); - assert!(!flyout(&ctx), "a click on the button closes it"); - assert_eq!(app.ui.tool, Tool::Brush, "and picks the tool, as any click on it does"); - // The release that ends a long press keeps the flyout it opened. - frame(&mut app, &ctx, 5.0, vec![egui::Event::PointerMoved(at), primary(at, true)]); - frame(&mut app, &ctx, 5.2, vec![]); - frame(&mut app, &ctx, 5.5, vec![]); - assert!(flyout(&ctx), "a long press opens it"); - frame(&mut app, &ctx, 5.55, vec![primary(at, false)]); - frame(&mut app, &ctx, 5.6, vec![]); - assert!(flyout(&ctx), "releasing the long press keeps it open"); - } - - #[test] - fn red_eye_is_in_the_j_flyout() { - let j = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).find(|slot| slot.contains(&Tool::SpotHealing)).expect("J group"); - assert!(j.contains(&Tool::RedEye), "{j:?}"); - assert_eq!(j.last(), Some(&Tool::RedEye)); - // Remove leads the flyout, so the slot shows it until another J tool is picked. - assert_eq!(j.first(), Some(&Tool::Remove)); - } - - #[test] - fn art_history_is_in_the_y_flyout() { - let y = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).find(|slot| slot.contains(&Tool::HistoryBrush)).expect("Y group"); - assert_eq!(*y, [Tool::HistoryBrush, Tool::ArtHistoryBrush]); - } - - #[test] - fn long_press_clone_stamp_selects_pattern_stamp() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - frame(&mut app, &ctx, 0.0, vec![]); - frame(&mut app, &ctx, 0.1, vec![]); - let index = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&Tool::CloneStamp)).unwrap(); - let slot = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).nth(index).copied().unwrap(); - assert_eq!(slot, &[Tool::CloneStamp, Tool::PatternStamp]); - let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; - let mut buttons: Vec = ctx.viewport(|v| { - v.prev_pass - .widgets - .layers() - .flat_map(|(_, w)| w.iter()) - .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) - .map(|w| w.rect) - .collect() - }); - buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); - let at = buttons[index].center(); - let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(at), pointer(at, true)]); - frame(&mut app, &ctx, 1.36, vec![]); - assert_eq!( - ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::unique("tool-flyout"))).map(|(id, _)| id), - Some(egui::Id::unique(("tool-slot", index))) - ); - frame(&mut app, &ctx, 1.4, vec![pointer(at, false)]); - frame(&mut app, &ctx, 1.45, vec![]); - let key = egui::Id::unique(("tool-slot", index)); - let menu = ctx.memory(|m| m.area_rect(key.with("flyout"))).unwrap(); - let row = egui::pos2(menu.left() + 65.0, menu.top() + 39.0 + 8.0); - frame(&mut app, &ctx, 2.0, vec![egui::Event::PointerMoved(row), pointer(row, true)]); - frame(&mut app, &ctx, 2.05, vec![pointer(row, false)]); - assert_eq!(app.ui.tool, Tool::PatternStamp); - } - - #[test] - fn long_press_brush_selects_color_replacement() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - frame(&mut app, &ctx, 0.0, vec![]); - frame(&mut app, &ctx, 0.1, vec![]); - let index = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&Tool::Brush)).unwrap(); - let slot = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).nth(index).copied().unwrap(); - // Photoshop's Brush group, Color Replacement after the Mixer Brush. - assert_eq!(slot, &[Tool::Brush, Tool::Pencil, Tool::MixerBrush, Tool::ColorReplacement]); - let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; - let mut buttons: Vec = ctx.viewport(|v| { - v.prev_pass - .widgets - .layers() - .flat_map(|(_, w)| w.iter()) - .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) - .map(|w| w.rect) - .collect() - }); - buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); - let at = buttons[index].center(); - let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(at), pointer(at, true)]); - frame(&mut app, &ctx, 1.36, vec![]); - frame(&mut app, &ctx, 1.4, vec![pointer(at, false)]); - frame(&mut app, &ctx, 1.45, vec![]); - let key = egui::Id::unique(("tool-slot", index)); - let menu = ctx.memory(|m| m.area_rect(key.with("flyout"))).unwrap(); - // The last of the four 26-point rows. - let row = egui::pos2(menu.left() + 65.0, menu.bottom() - 20.0); - frame(&mut app, &ctx, 2.0, vec![egui::Event::PointerMoved(row), pointer(row, true)]); - frame(&mut app, &ctx, 2.05, vec![pointer(row, false)]); - assert_eq!(app.ui.tool, Tool::ColorReplacement); - assert_eq!(crate::icons::tool_icon(Tool::ColorReplacement), "brush-replace"); - } - - #[test] - fn rotate_view_is_in_the_hand_flyout() { - let hand = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).find(|slot| slot.contains(&Tool::Hand)).expect("Hand group"); - assert_eq!(*hand, [Tool::Hand, Tool::RotateView]); - assert_eq!(Tool::RotateView.key(), 'R'); - } - - #[test] - fn pro_toolbar_glyphs_fill_two_thirds_of_the_button() { - // #2665: Photoshop-style themes draw tool glyphs larger than other icon buttons. - assert_eq!(toolbar_icon_size(30.0, true), 20.0); - assert_eq!(toolbar_icon_size(36.0, false), (36.0f32 * 0.52).round(), "other themes keep the icon-button size"); - // The glyph stays inside the button with room for the flyout triangle's corner. - assert!(toolbar_icon_size(30.0, true) <= 30.0 - 2.0 * 4.0); - } - - #[test] - fn long_press_y_button_selects_art_history() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - frame(&mut app, &ctx, 0.0, vec![]); - frame(&mut app, &ctx, 0.1, vec![]); - let index = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&Tool::HistoryBrush)).unwrap(); - let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; - let mut buttons: Vec = ctx.viewport(|v| { - v.prev_pass - .widgets - .layers() - .flat_map(|(_, w)| w.iter()) - .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) - .map(|w| w.rect) - .collect() - }); - buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); - let at = buttons[index].center(); - let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(at), pointer(at, true)]); - frame(&mut app, &ctx, 1.36, vec![]); - assert_eq!( - ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::unique("tool-flyout"))).map(|(id, _)| id), - Some(egui::Id::unique(("tool-slot", index))) - ); - frame(&mut app, &ctx, 1.4, vec![pointer(at, false)]); - frame(&mut app, &ctx, 1.45, vec![]); - let key = egui::Id::unique(("tool-slot", index)); - let menu = ctx.memory(|m| m.area_rect(key.with("flyout"))).unwrap(); - let row = egui::pos2(menu.left() + 65.0, menu.top() + 39.0 + 8.0); - frame(&mut app, &ctx, 2.0, vec![egui::Event::PointerMoved(row), pointer(row, true)]); - frame(&mut app, &ctx, 2.05, vec![pointer(row, false)]); - assert_eq!(app.ui.tool, Tool::ArtHistoryBrush); - } -} +mod type_flyout_tests; #[cfg(test)] mod toolbar_hidden_tests { diff --git a/crates/ui-egui/src/panels/type_flyout_tests.rs b/crates/ui-egui/src/panels/type_flyout_tests.rs new file mode 100644 index 0000000000..27659cf8b5 --- /dev/null +++ b/crates/ui-egui/src/panels/type_flyout_tests.rs @@ -0,0 +1,385 @@ +use super::*; + +fn frame(app: &mut PhotocraftApp, ctx: &egui::Context, time: f64, events: Vec) { + let mut out = ctx.run_ui( + egui::RawInput { time: Some(time), events, screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1200.0, 1800.0))), ..Default::default() }, + |ui| toolbar(app, ui), + ); + out.textures_delta.clear(); +} + +#[test] +fn long_press_type_button_selects_type_then_vertical_from_the_flyout() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + assert_ne!(app.ui.tool, Tool::Type); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + let index = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&Tool::Type)).unwrap(); + let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; + let mut buttons: Vec = ctx.viewport(|v| { + v.prev_pass + .widgets + .layers() + .flat_map(|(_, w)| w.iter()) + .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) + .map(|w| w.rect) + .collect() + }); + buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); + let at = buttons[index].center(); + let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(at), pointer(at, true)]); + frame(&mut app, &ctx, 1.36, vec![]); + assert_eq!(ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::unique("tool-flyout"))).map(|(id, _)| id), Some(egui::Id::unique(("tool-slot", index)))); + frame(&mut app, &ctx, 1.4, vec![pointer(at, false)]); + frame(&mut app, &ctx, 1.45, vec![]); + // The held button's tool is selected, as Photoshop does (#4453). + assert_eq!(app.ui.tool, Tool::Type); + let key = egui::Id::unique(("tool-slot", index)); + let menu = ctx.memory(|m| m.area_rect(key.with("flyout"))).unwrap(); + let row = egui::pos2(menu.left() + 65.0, menu.top() + 39.0 + 8.0); + frame(&mut app, &ctx, 2.0, vec![egui::Event::PointerMoved(row), pointer(row, true)]); + frame(&mut app, &ctx, 2.05, vec![pointer(row, false)]); + assert_eq!(app.ui.tool, Tool::VerticalType); + assert!(ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::unique("tool-flyout"))).is_none()); +} + +/// #4444: click and hold on Change Screen Mode opens its list like the tool flyouts, without +/// cycling the mode on release; a plain click still cycles, and right-click still opens it. +#[test] +fn long_press_screen_mode_opens_the_modes_without_cycling() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; + // The toolbar's last button: Change Screen Mode, after Quick Mask. + let at = ctx + .viewport(|v| { + v.prev_pass + .widgets + .layers() + .flat_map(|(_, w)| w.iter()) + .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) + .map(|w| w.rect) + .max_by(|a, b| a.top().total_cmp(&b.top()).then(a.left().total_cmp(&b.left()))) + }) + .unwrap() + .center(); + let standard = |app: &PhotocraftApp| crate::view_cmds::checked(app, "view.screenMode.standard") == Some(true); + let menu_open = |ctx: &egui::Context| egui::Popup::is_any_open(ctx); + let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + assert!(standard(&app)); + // Hold, then release: the list opens and stays open, and the mode is unchanged. + frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(at), pointer(at, true)]); + frame(&mut app, &ctx, 1.2, vec![]); + assert!(!menu_open(&ctx), "not before the hold time"); + frame(&mut app, &ctx, 1.4, vec![]); + assert!(menu_open(&ctx), "open while still held"); + frame(&mut app, &ctx, 1.5, vec![pointer(at, false)]); + frame(&mut app, &ctx, 1.55, vec![]); + assert!(menu_open(&ctx), "the release keeps it open"); + assert!(standard(&app), "the release doesn't cycle the mode"); + // Escape closes it; a plain click cycles the mode and opens nothing. + frame( + &mut app, + &ctx, + 2.0, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], + ); + frame(&mut app, &ctx, 2.05, vec![]); + assert!(!menu_open(&ctx)); + frame(&mut app, &ctx, 3.0, vec![egui::Event::PointerMoved(at), pointer(at, true)]); + frame(&mut app, &ctx, 3.1, vec![pointer(at, false)]); + frame(&mut app, &ctx, 3.15, vec![]); + assert!(!standard(&app), "a click cycles"); + assert!(!menu_open(&ctx)); + // Right-click opens it too. + let secondary = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, 4.0, vec![secondary(true)]); + frame(&mut app, &ctx, 4.05, vec![secondary(false)]); + frame(&mut app, &ctx, 4.1, vec![]); + assert!(menu_open(&ctx)); +} + +/// Every text drawn in one toolbar frame. +fn frame_texts(app: &mut PhotocraftApp, ctx: &egui::Context, time: f64, events: Vec) -> Vec { + fn collect(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)), + _ => {} + } + } + let mut out = ctx.run_ui( + egui::RawInput { time: Some(time), events, screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1200.0, 1800.0))), ..Default::default() }, + |ui| toolbar(app, ui), + ); + out.textures_delta.clear(); + let mut texts = Vec::new(); + out.shapes.iter().for_each(|c| collect(&c.shape, &mut texts)); + texts +} + +/// #4450: no tool tooltip while a flyout is open or a tool button is held to open one, for the +/// held tool or any other; a plain hover still shows its tooltip. +#[test] +fn no_tooltips_over_an_open_tool_flyout() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; + let mut buttons: Vec = ctx.viewport(|v| { + v.prev_pass + .widgets + .layers() + .flat_map(|(_, w)| w.iter()) + .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) + .map(|w| w.rect) + .collect() + }); + buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); + let slot_of = |tool: Tool| TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&tool)).unwrap(); + let (eyedropper, brush) = (buttons[slot_of(Tool::Eyedropper)].center(), buttons[slot_of(Tool::Brush)].center()); + let tip = |tool: Tool| format!("{} ({})", tl!(tool.label()), tool.key()); + let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + // A plain hover shows the tooltip. + frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(brush)]); + let mut texts = Vec::new(); + for k in 1..=10 { + texts = frame_texts(&mut app, &ctx, 1.0 + 0.1 * f64::from(k), vec![]); + } + assert!(texts.contains(&tip(Tool::Brush)), "hovered long enough: {texts:?}"); + // Held on the Eyedropper: no tooltip before or after its flyout opens. + frame(&mut app, &ctx, 3.0, vec![egui::Event::PointerMoved(eyedropper), pointer(eyedropper, true)]); + for k in 1..=10 { + let texts = frame_texts(&mut app, &ctx, 3.0 + 0.1 * f64::from(k), vec![]); + assert!(!texts.contains(&tip(Tool::Eyedropper)), "held {k}: {texts:?}"); + } + assert!(ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::unique("tool-flyout"))).is_some(), "the flyout is open"); + // Released, with the flyout still open: none for the held tool or another one. + frame(&mut app, &ctx, 4.1, vec![pointer(eyedropper, false)]); + for (start, at, tool) in [(4.5, eyedropper, Tool::Eyedropper), (6.0, brush, Tool::Brush)] { + frame(&mut app, &ctx, start, vec![egui::Event::PointerMoved(at)]); + for k in 1..=10 { + let texts = frame_texts(&mut app, &ctx, start + 0.1 * f64::from(k), vec![]); + assert!(!texts.contains(&tip(tool)), "{tool:?} under the flyout: {texts:?}"); + } + } +} + +/// #4460: a press outside an open flyout closes it, even when it becomes a drag (cropping or +/// painting on the canvas) rather than a click; a press on the flyout keeps it for its pick. +/// #4932: so does a click on its own tool button. +#[test] +fn a_drag_outside_closes_the_tool_flyout() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + let index = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&Tool::Brush)).unwrap(); + let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; + let mut buttons: Vec = ctx.viewport(|v| { + v.prev_pass + .widgets + .layers() + .flat_map(|(_, w)| w.iter()) + .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) + .map(|w| w.rect) + .collect() + }); + buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); + let at = buttons[index].center(); + let flyout = |ctx: &egui::Context| ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::unique("tool-flyout"))).is_some(); + let secondary = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }; + let primary = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + // A right-click on the button of an open flyout closes it (#4932), so open only a closed one. + let open = |app: &mut PhotocraftApp, t: f64| { + if !flyout(&ctx) { + frame(app, &ctx, t, vec![egui::Event::PointerMoved(at), secondary(true)]); + frame(app, &ctx, t + 0.05, vec![secondary(false)]); + frame(app, &ctx, t + 0.1, vec![]); + } + assert!(flyout(&ctx), "right-click opens it"); + }; + // A press on the flyout itself keeps it open (the row picks on release). + open(&mut app, 1.0); + let menu = ctx.memory(|m| m.area_rect(egui::Id::unique(("tool-slot", index)).with("flyout"))).unwrap(); + frame(&mut app, &ctx, 1.5, vec![egui::Event::PointerMoved(menu.center()), primary(menu.center(), true)]); + assert!(flyout(&ctx), "a press on the flyout keeps it"); + frame(&mut app, &ctx, 1.55, vec![primary(menu.center(), false)]); + // A drag far from the toolbar (the canvas) closes it as soon as it starts. + open(&mut app, 2.0); + let canvas = egui::pos2(900.0, 900.0); + frame(&mut app, &ctx, 2.5, vec![egui::Event::PointerMoved(canvas), primary(canvas, true)]); + frame(&mut app, &ctx, 2.55, vec![egui::Event::PointerMoved(canvas + vec2(80.0, 60.0))]); + assert!(!flyout(&ctx), "a press outside closes it, even one that becomes a drag"); + frame(&mut app, &ctx, 2.6, vec![primary(canvas + vec2(80.0, 60.0), false)]); + assert!(!flyout(&ctx)); + // #4932: clicking its own tool button again closes it, with either button. + open(&mut app, 3.0); + frame(&mut app, &ctx, 3.5, vec![egui::Event::PointerMoved(at), secondary(true)]); + frame(&mut app, &ctx, 3.55, vec![secondary(false)]); + frame(&mut app, &ctx, 3.6, vec![]); + assert!(!flyout(&ctx), "a second right-click on the button closes it"); + open(&mut app, 4.0); + app.ui.tool = Tool::Move; + frame(&mut app, &ctx, 4.5, vec![egui::Event::PointerMoved(at), primary(at, true)]); + frame(&mut app, &ctx, 4.55, vec![primary(at, false)]); + frame(&mut app, &ctx, 4.6, vec![]); + assert!(!flyout(&ctx), "a click on the button closes it"); + assert_eq!(app.ui.tool, Tool::Brush, "and picks the tool, as any click on it does"); + // The release that ends a long press keeps the flyout it opened. + frame(&mut app, &ctx, 5.0, vec![egui::Event::PointerMoved(at), primary(at, true)]); + frame(&mut app, &ctx, 5.2, vec![]); + frame(&mut app, &ctx, 5.5, vec![]); + assert!(flyout(&ctx), "a long press opens it"); + frame(&mut app, &ctx, 5.55, vec![primary(at, false)]); + frame(&mut app, &ctx, 5.6, vec![]); + assert!(flyout(&ctx), "releasing the long press keeps it open"); +} + +#[test] +fn red_eye_is_in_the_j_flyout() { + let j = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).find(|slot| slot.contains(&Tool::SpotHealing)).expect("J group"); + assert!(j.contains(&Tool::RedEye), "{j:?}"); + assert_eq!(j.last(), Some(&Tool::RedEye)); + // Remove leads the flyout, so the slot shows it until another J tool is picked. + assert_eq!(j.first(), Some(&Tool::Remove)); +} + +#[test] +fn art_history_is_in_the_y_flyout() { + let y = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).find(|slot| slot.contains(&Tool::HistoryBrush)).expect("Y group"); + assert_eq!(*y, [Tool::HistoryBrush, Tool::ArtHistoryBrush]); +} + +#[test] +fn long_press_clone_stamp_selects_pattern_stamp() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + let index = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&Tool::CloneStamp)).unwrap(); + let slot = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).nth(index).copied().unwrap(); + assert_eq!(slot, &[Tool::CloneStamp, Tool::PatternStamp]); + let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; + let mut buttons: Vec = ctx.viewport(|v| { + v.prev_pass + .widgets + .layers() + .flat_map(|(_, w)| w.iter()) + .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) + .map(|w| w.rect) + .collect() + }); + buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); + let at = buttons[index].center(); + let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(at), pointer(at, true)]); + frame(&mut app, &ctx, 1.36, vec![]); + assert_eq!(ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::unique("tool-flyout"))).map(|(id, _)| id), Some(egui::Id::unique(("tool-slot", index)))); + frame(&mut app, &ctx, 1.4, vec![pointer(at, false)]); + frame(&mut app, &ctx, 1.45, vec![]); + let key = egui::Id::unique(("tool-slot", index)); + let menu = ctx.memory(|m| m.area_rect(key.with("flyout"))).unwrap(); + let row = egui::pos2(menu.left() + 65.0, menu.top() + 39.0 + 8.0); + frame(&mut app, &ctx, 2.0, vec![egui::Event::PointerMoved(row), pointer(row, true)]); + frame(&mut app, &ctx, 2.05, vec![pointer(row, false)]); + assert_eq!(app.ui.tool, Tool::PatternStamp); +} + +#[test] +fn long_press_brush_selects_color_replacement() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + let index = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&Tool::Brush)).unwrap(); + let slot = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).nth(index).copied().unwrap(); + // Photoshop's Brush group, Color Replacement after the Mixer Brush. + assert_eq!(slot, &[Tool::Brush, Tool::Pencil, Tool::MixerBrush, Tool::ColorReplacement]); + let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; + let mut buttons: Vec = ctx.viewport(|v| { + v.prev_pass + .widgets + .layers() + .flat_map(|(_, w)| w.iter()) + .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) + .map(|w| w.rect) + .collect() + }); + buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); + let at = buttons[index].center(); + let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(at), pointer(at, true)]); + frame(&mut app, &ctx, 1.36, vec![]); + frame(&mut app, &ctx, 1.4, vec![pointer(at, false)]); + frame(&mut app, &ctx, 1.45, vec![]); + let key = egui::Id::unique(("tool-slot", index)); + let menu = ctx.memory(|m| m.area_rect(key.with("flyout"))).unwrap(); + // The last of the four 26-point rows. + let row = egui::pos2(menu.left() + 65.0, menu.bottom() - 20.0); + frame(&mut app, &ctx, 2.0, vec![egui::Event::PointerMoved(row), pointer(row, true)]); + frame(&mut app, &ctx, 2.05, vec![pointer(row, false)]); + assert_eq!(app.ui.tool, Tool::ColorReplacement); + assert_eq!(crate::icons::tool_icon(Tool::ColorReplacement), "brush-replace"); +} + +#[test] +fn rotate_view_is_in_the_hand_flyout() { + let hand = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).find(|slot| slot.contains(&Tool::Hand)).expect("Hand group"); + assert_eq!(*hand, [Tool::Hand, Tool::RotateView]); + assert_eq!(Tool::RotateView.key(), 'R'); +} + +#[test] +fn pro_toolbar_glyphs_fill_two_thirds_of_the_button() { + // #2665: Photoshop-style themes draw tool glyphs larger than other icon buttons. + assert_eq!(toolbar_icon_size(30.0, true), 20.0); + assert_eq!(toolbar_icon_size(36.0, false), (36.0f32 * 0.52).round(), "other themes keep the icon-button size"); + // The glyph stays inside the button with room for the flyout triangle's corner. + assert!(toolbar_icon_size(30.0, true) <= 30.0 - 2.0 * 4.0); +} + +#[test] +fn long_press_y_button_selects_art_history() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + let index = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&Tool::HistoryBrush)).unwrap(); + let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 }; + let mut buttons: Vec = ctx.viewport(|v| { + v.prev_pass + .widgets + .layers() + .flat_map(|(_, w)| w.iter()) + .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click()) + .map(|w| w.rect) + .collect() + }); + buttons.sort_by(|a, b| a.top().total_cmp(&b.top())); + let at = buttons[index].center(); + let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(at), pointer(at, true)]); + frame(&mut app, &ctx, 1.36, vec![]); + assert_eq!(ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::unique("tool-flyout"))).map(|(id, _)| id), Some(egui::Id::unique(("tool-slot", index)))); + frame(&mut app, &ctx, 1.4, vec![pointer(at, false)]); + frame(&mut app, &ctx, 1.45, vec![]); + let key = egui::Id::unique(("tool-slot", index)); + let menu = ctx.memory(|m| m.area_rect(key.with("flyout"))).unwrap(); + let row = egui::pos2(menu.left() + 65.0, menu.top() + 39.0 + 8.0); + frame(&mut app, &ctx, 2.0, vec![egui::Event::PointerMoved(row), pointer(row, true)]); + frame(&mut app, &ctx, 2.05, vec![pointer(row, false)]); + assert_eq!(app.ui.tool, Tool::ArtHistoryBrush); +} From f994c77edcc881fe6bd20475b1c8141526105b51 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:14 +0000 Subject: [PATCH 088/259] refactor(ui-egui): move panels.rs compact_visual_regressions to panels/compact_visual_regressions.rs --- crates/ui-egui/src/panels.rs | 522 +----------------- .../src/panels/compact_visual_regressions.rs | 519 +++++++++++++++++ 2 files changed, 520 insertions(+), 521 deletions(-) create mode 100644 crates/ui-egui/src/panels/compact_visual_regressions.rs diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 85912c23c7..72e443906e 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -6148,527 +6148,7 @@ mod clipping_indicator_tests; mod mask_properties_tests; #[cfg(test)] -mod compact_visual_regressions { - use super::*; - use egui_kittest::kittest::Queryable; - - fn input_at_scale(screen: Rect, scale: f32) -> egui::RawInput { - let mut input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; - input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(scale); - input - } - - fn toolbar_harness(kind: theme::ThemeKind, scale: f32) -> egui_kittest::Harness<'static, PhotocraftApp> { - toolbar_harness_sized(kind, scale, 360.0) - } - - fn toolbar_harness_sized(kind: theme::ThemeKind, scale: f32, height: f32) -> egui_kittest::Harness<'static, PhotocraftApp> { - let mut ready = false; - let mut harness = egui_kittest::Harness::builder().with_size(vec2(400.0, height)).with_pixels_per_point(scale).build_ui_state( - move |ui, app: &mut PhotocraftApp| { - if !ready { - egui_extras::install_image_loaders(ui.ctx()); - theme::install_fonts(ui.ctx()); - theme::apply(ui.ctx(), kind); - app.session.prefs.edit(|prefs| prefs.shortcuts.insert("window.togglePanels".into(), String::new())); - ready = true; - return; - } - crate::shortcuts::handle(app, ui.ctx()); - toolbar(app, ui); - }, - PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()), - ); - harness.run_steps(4); - harness - } - - #[test] - fn compact_toolbar_scrolls_to_and_activates_the_last_tool() { - for kind in theme::ThemeKind::ALL { - for scale in [1.0, 1.5, 2.0] { - let mut harness = toolbar_harness(kind, scale); - harness.event(egui::Event::PointerMoved(pos2(25.0, 100.0))); - harness.event(egui::Event::MouseWheel { - source: egui::MouseWheelSource::Unknown, - unit: egui::MouseWheelUnit::Point, - delta: vec2(0.0, -1500.0), - modifiers: egui::Modifiers::NONE, - phase: egui::TouchPhase::Move, - }); - harness.run_steps(30); - // Off the toolbar, so a tooltip of the tool scrolled under the pointer isn't a - // second "Zoom Tool" node. - harness.event(egui::Event::PointerMoved(pos2(300.0, 100.0))); - harness.run_steps(2); - let node = harness.get_by_label("Zoom Tool (Z)"); - let rect = node.rect(); - assert!(rect.top() >= 0.0 && rect.bottom() <= 360.0, "{kind:?} at {scale}x: last tool remains outside the toolbar: {rect:?}"); - node.click(); - harness.run_steps(3); - assert_eq!(harness.state().ui.tool, Tool::Zoom, "the scrolled button must select its real tool"); - } - } - } - - #[test] - fn compact_toolbar_tab_reveals_and_activates_the_last_tool() { - for kind in theme::ThemeKind::ALL { - for scale in [1.0, 1.5, 2.0] { - let mut harness = toolbar_harness(kind, scale); - // The supported shortcut preference clears the canvas Tab binding. From no - // focus, every step below is a real Tab processed by the app's dispatcher. - let mut reached = false; - for _ in 0..80 { - harness.key_press(egui::Key::Tab); - harness.run_steps(3); - reached = harness.get_by_label("Zoom Tool (Z)").is_focused(); - if reached { - break; - } - } - assert!(reached, "{kind:?} at {scale}x: Tab must reach the last tool"); - harness.run_steps(20); - let rect = harness.get_by_label("Zoom Tool (Z)").rect(); - assert!(rect.top() >= 0.0 && rect.bottom() <= 360.0, "{kind:?} at {scale}x: focused tool remains clipped: {rect:?}"); - harness.key_press(egui::Key::Space); - harness.run_steps(3); - assert_eq!(harness.state().ui.tool, Tool::Zoom, "Space must select the revealed tool"); - } - } - } - - /// A window taller than the tools keeps the colour chips right under the tool column (its - /// last row is Edit Toolbar), as Photoshop does, instead of at the bottom of the toolbar. - #[test] - fn tall_toolbar_keeps_the_colour_chips_under_the_tools() { - for kind in theme::ThemeKind::ALL { - let harness = toolbar_harness_sized(kind, 1.0, 1600.0); - let last = harness.get_by_label("Edit Toolbar…").rect(); - let swap = harness.get_by_label("Swap colours (X)").rect(); - assert!(swap.top() - last.bottom() < 80.0, "{kind:?}: the chips {swap:?} sit far below the last tool {last:?}"); - } - } - - #[test] - fn capture_compact_visual_fixtures() { - let _gpu = photocraft_testkit::gpu_lock(); - let Some(directory) = std::env::var_os("CRAFT_UI_VISUAL_FIXTURES").map(std::path::PathBuf::from) else { return }; - std::fs::create_dir_all(&directory).unwrap(); - for kind in crate::theme::ThemeKind::ALL { - for (width, height) in [(800.0, 480.0), (1280.0, 720.0)] { - for scale in [1.0, 1.5, 2.0] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.tools.foreground = [1.0, 0.0, 1.0, 1.0]; - app.session.tools.background = [0.0, 1.0, 0.0, 1.0]; - let mut ready = false; - let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, height)).with_pixels_per_point(scale).wgpu().build_ui_state( - move |ui, app: &mut PhotocraftApp| { - if !ready { - egui_extras::install_image_loaders(ui.ctx()); - crate::theme::install_fonts(ui.ctx()); - crate::theme::apply(ui.ctx(), kind); - ready = true; - return; - } - app.ui.tool = if Tokens::get(ui.ctx()).pro { Tool::Pencil } else { Tool::Brush }; - options_bar(app, ui); - toolbar(app, ui); - }, - app, - ); - harness.input_mut().max_texture_side = Some(8192); - harness.run_steps(4); - let stem = format!("photocraft-compact-{}-{width}-{height}-{scale}x", kind.id()); - harness.render().unwrap().save(directory.join(format!("{stem}.png"))).unwrap(); - let mut regions = serde_json::Map::new(); - for id in ["options_bar", "toolbar"] { - let r = egui::containers::panel::PanelState::load(&harness.ctx, panel_state_id(&harness.ctx, id)).unwrap().outer_rect; - regions.insert(id.into(), json!([r.left(), r.top(), r.width(), r.height()])); - } - let metadata = json!({"screen": [width, height], "scale": scale, "regions": regions}); - std::fs::write(directory.join(format!("{stem}.json")), serde_json::to_vec_pretty(&metadata).unwrap()).unwrap(); - for _ in 0..6 { - harness.input_mut().events.extend([ - egui::Event::PointerMoved(pos2(width * 0.5, 20.0)), - egui::Event::MouseWheel { - source: egui::MouseWheelSource::Unknown, - unit: egui::MouseWheelUnit::Point, - delta: vec2(-1500.0, 0.0), - modifiers: egui::Modifiers::NONE, - phase: egui::TouchPhase::Move, - }, - ]); - harness.run_steps(1); - } - harness.render().unwrap().save(directory.join(format!("{stem}-scrolled.png"))).unwrap(); - std::fs::write(directory.join(format!("{stem}-scrolled.json")), serde_json::to_vec_pretty(&metadata).unwrap()).unwrap(); - } - } - } - } - - /// #7316: a window too short for the tools scrolls them, and the scroll bar widened the UI - /// the colour chips were centred in, so they (and Switch Colors with them) sat a bar's width - /// right of the tools. They stay where they are in a window tall enough not to scroll. - #[test] - fn color_chips_stay_centred_when_the_tools_scroll() { - let chips = |kind: crate::theme::ThemeKind, double: bool, height: f32, scale: f32| { - let ctx = egui::Context::default(); - egui_extras::install_image_loaders(&ctx); - crate::theme::install_fonts(&ctx); - crate::theme::apply(&ctx, kind); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.tools.foreground = [1.0, 0.0, 1.0, 1.0]; - app.session.tools.background = [0.0, 1.0, 0.0, 1.0]; - app.ui.panels.toolbar_double = double; - let input = || input_at_scale(Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, height)), scale); - // The scroll bar shows from the frame after the one that measured the tools. - let mut output = ctx.run_ui(input(), |ui| toolbar(&mut app, ui)); - for _ in 0..2 { - output.textures_delta.clear(); - output = ctx.run_ui(input(), |ui| toolbar(&mut app, ui)); - } - output.textures_delta.clear(); - [Color32::from_rgb(255, 0, 255), Color32::GREEN].map(|color| { - output - .shapes - .iter() - .find_map(|shape| match &shape.shape { - egui::Shape::Rect(rect) if rect.fill == color => Some(rect.rect.center()), - egui::Shape::Circle(circle) if circle.fill == color => Some(circle.center), - _ => None, - }) - .unwrap_or_else(|| panic!("{kind:?}: both color chips are painted")) - .x - }) - }; - for kind in crate::theme::ThemeKind::ALL { - for double in [false, true] { - for scale in [1.0, 2.0] { - let (short, tall) = (chips(kind, double, 420.0, scale), chips(kind, double, 1400.0, scale)); - assert_eq!(short, tall, "{kind:?}, two columns {double}, scale {scale}: the chips don't move when the tools scroll"); - } - } - } - } - - #[test] - fn compact_toolbar_keeps_both_color_chips_visible() { - for kind in crate::theme::ThemeKind::ALL { - for height in [480.0, 720.0] { - for scale in [1.0, 1.5, 2.0] { - let ctx = egui::Context::default(); - egui_extras::install_image_loaders(&ctx); - crate::theme::install_fonts(&ctx); - crate::theme::apply(&ctx, kind); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.tools.foreground = [1.0, 0.0, 1.0, 1.0]; - app.session.tools.background = [0.0, 1.0, 0.0, 1.0]; - let mut output = ctx.run_ui(input_at_scale(Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, height)), scale), |ui| toolbar(&mut app, ui)); - output.textures_delta.clear(); - for color in [Color32::from_rgb(255, 0, 255), Color32::GREEN] { - let (clip, chip) = output - .shapes - .iter() - .find_map(|shape| match &shape.shape { - egui::Shape::Rect(rect) if rect.fill == color => Some((shape.clip_rect, rect.rect)), - egui::Shape::Circle(circle) if circle.fill == color => { - Some((shape.clip_rect, Rect::from_center_size(circle.center, vec2(circle.radius * 2.0, circle.radius * 2.0)))) - } - _ => None, - }) - .unwrap_or_else(|| panic!("{kind:?} at {height}/{scale}: both color chips are painted")); - assert!(clip.contains_rect(chip) && chip.bottom() <= height, "{kind:?} at {height}: color chip {chip:?} clipped by {clip:?}"); - } - } - } - } - } - - #[test] - fn tab_focus_reveals_the_final_narrow_tool_option() { - for kind in theme::ThemeKind::ALL { - for scale in [1.0, 1.5, 2.0] { - let mut ready = false; - let mut harness = egui_kittest::Harness::builder().with_size(vec2(360.0, 120.0)).with_pixels_per_point(scale).build_ui_state( - move |ui, app: &mut PhotocraftApp| { - if !ready { - egui_extras::install_image_loaders(ui.ctx()); - theme::install_fonts(ui.ctx()); - theme::apply(ui.ctx(), kind); - app.ui.tool = if Tokens::get(ui.ctx()).pro { Tool::Pencil } else { Tool::Brush }; - app.session.prefs.edit(|prefs| prefs.shortcuts.insert("window.togglePanels".into(), String::new())); - ready = true; - return; - } - crate::shortcuts::handle(app, ui.ctx()); - options_bar(app, ui); - }, - PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()), - ); - harness.run_steps(4); - let pro = Tokens::get(&harness.ctx).pro; - let last_label = if pro { "Auto Erase" } else { "Pressure for Opacity" }; - // Only the canvas Tab shortcut is cleared, using its public preference; - // no response is assigned focus programmatically. - let mut reached = false; - for _ in 0..80 { - harness.key_press(egui::Key::Tab); - harness.run_steps(3); - let label = harness.output().shapes.iter().find_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.job.text.contains(last_label) => Some(text.visual_bounding_rect()), - _ => None, - }); - reached = label.is_some_and(|label| { - harness.ctx.memory(|memory| memory.focused()).and_then(|id| harness.ctx.read_response(id)).is_some_and(|response| { - response.rect.intersects(label) - || ((label.left() - response.rect.right()).abs() <= 12.0 - && response.rect.top() < label.bottom() - && response.rect.bottom() > label.top()) - }) - }); - if reached { - break; - } - } - assert!(reached, "{kind:?} at {scale}x: Tab must reach the final tool option"); - harness.run_steps(20); - let (clip, label) = harness - .output() - .shapes - .iter() - .find_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.job.text.contains(last_label) => Some((shape.clip_rect, text.visual_bounding_rect())), - _ => None, - }) - .expect("the final option remains painted"); - assert!(clip.contains_rect(label), "{kind:?} at {scale}x: Tab leaves the focused final option outside {clip:?}: {label:?}"); - let previous = if pro { harness.state().ui.tool_options.pencil_auto_erase } else { harness.state().session.tools.brush.pressure_opacity }; - harness.key_press(egui::Key::Space); - harness.run_steps(3); - let current = if pro { harness.state().ui.tool_options.pencil_auto_erase } else { harness.state().session.tools.brush.pressure_opacity }; - assert_ne!(current, previous, "{kind:?} at {scale}x: Space must activate the revealed option"); - assert!(harness.state().ui.panels.options_bar, "widget traversal must preserve the options bar"); - } - } - } - - #[test] - fn a_wide_crop_options_bar_does_not_scroll() { - for kind in crate::theme::ThemeKind::ALL { - for scale in [1.0, 1.5, 2.0] { - for mode in ["", crate::crop_size::WHR] { - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - crate::theme::apply(&ctx, kind); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - if !Tokens::get(&ctx).pro { - continue; - } - app.ui.tool = Tool::Crop; - app.ui.tool_options.crop_ratio = mode.into(); - let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 120.0)); - let clear_x = |output: &egui::FullOutput| { - output - .shapes - .iter() - .find_map(|s| match &s.shape { - egui::Shape::Text(t) if t.galley.job.text == "Clear" => Some(t.pos.x), - _ => None, - }) - .unwrap() - }; - let mut before = ctx.run_ui(input_at_scale(screen, scale), |ui| options_bar(&mut app, ui)); - before.textures_delta.clear(); - for _ in 0..3 { - before = ctx.run_ui(input_at_scale(screen, scale), |ui| options_bar(&mut app, ui)); - before.textures_delta.clear(); - } - let mut after = before.clone(); - for _ in 0..6 { - after = ctx.run_ui( - egui::RawInput { - events: vec![ - egui::Event::PointerMoved(pos2(800.0, 20.0)), - egui::Event::MouseWheel { - source: egui::MouseWheelSource::Unknown, - unit: egui::MouseWheelUnit::Point, - delta: vec2(-100.0, 0.0), - modifiers: egui::Modifiers::NONE, - phase: egui::TouchPhase::Move, - }, - ], - ..input_at_scale(screen, scale) - }, - |ui| options_bar(&mut app, ui), - ); - after.textures_delta.clear(); - } - assert_eq!(clear_x(&before), clear_x(&after), "a roomy bar must not have horizontal overflow"); - } - } - } - } - - #[test] - fn the_crop_ratio_fields_show_three_decimals() { - // #6487: a 1.414 : 1 ratio reads 1.414 in the bar, not 1.4. - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let Some(kind) = crate::theme::ThemeKind::ALL.into_iter().find(|k| { - crate::theme::apply(&ctx, *k); - Tokens::get(&ctx).pro - }) else { - return; - }; - crate::theme::apply(&ctx, kind); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.ui.tool = Tool::Crop; - app.ui.tool_options.crop_ratio = "1.414:1".into(); - let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 120.0)); - let mut out = ctx.run_ui(input_at_scale(screen, 1.0), |ui| options_bar(&mut app, ui)); - for _ in 0..3 { - out.textures_delta.clear(); - out = ctx.run_ui(input_at_scale(screen, 1.0), |ui| options_bar(&mut app, ui)); - } - out.textures_delta.clear(); - let texts: Vec<&str> = out - .shapes - .iter() - .filter_map(|s| match &s.shape { - egui::Shape::Text(t) => Some(t.galley.job.text.as_str()), - _ => None, - }) - .collect(); - assert!(texts.contains(&"1.414"), "{texts:?}"); - assert_eq!(app.ui.tool_options.crop_ratio, "1.414:1", "showing the ratio leaves it alone"); - } - - #[test] - fn a_typed_crop_ratio_fits_from_the_frame_the_edit_started_with() { - // #7752: typing 16 over 4 gave 1:3, then 16:3 inside that 100 x 300 frame (100 x 18.75). - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let Some(kind) = crate::theme::ThemeKind::ALL.into_iter().find(|k| { - crate::theme::apply(&ctx, *k); - Tokens::get(&ctx).pro - }) else { - return; - }; - crate::theme::apply(&ctx, kind); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - app.ui.tool = Tool::Crop; - app.ui.tool_options.crop_shield.classic_mode = true; - app.ui.tool_options.crop_ratio = "4:3".into(); - app.ui.crop_rect = Some([0.0, 0.0, 400.0, 300.0]); - let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 120.0)); - let step = |app: &mut PhotocraftApp, events: Vec| { - let mut input = input_at_scale(screen, 1.0); - input.events = events; - ctx.run_ui(input, |ui| options_bar(app, ui)).textures_delta.clear(); - }; - for _ in 0..3 { - step(&mut app, vec![]); - } - // The ratio's W field is the bar's first number field; focusing it selects its text. - widgets::focus_first_field(&ctx, true); - step(&mut app, vec![]); - step(&mut app, vec![egui::Event::Text("1".into())]); - assert_eq!(app.ui.tool_options.crop_ratio, "1:3"); - step(&mut app, vec![egui::Event::Text("6".into())]); - step(&mut app, vec![]); - assert_eq!(app.ui.tool_options.crop_ratio, "16:3"); - let r = app.ui.crop_rect.unwrap(); - let want = [0.0, 112.5, 400.0, 187.5]; - assert!(r.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "16:3 fitted once in 400 x 300: {r:?}"); - } - - #[test] - fn the_narrow_options_bar_preference_shortens_the_bar() { - assert_eq!(options_bar_height(true, false), 36.0); - assert_eq!(options_bar_height(true, true), 30.0); - assert_eq!(options_bar_height(false, false), 42.0); - assert_eq!(options_bar_height(false, true), 34.0); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - crate::theme::apply(&ctx, crate::theme::ThemeKind::ALL[0]); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 900.0)); - let run = |app: &mut PhotocraftApp| { - let mut top = 0.0; - let mut out = ctx.run_ui(input_at_scale(screen, 1.0), |ui| { - options_bar(app, ui); - top = ui.available_rect_before_wrap().top(); - }); - out.textures_delta.clear(); - top - }; - let normal = run(&mut app); - assert_eq!(normal, options_bar_height(Tokens::get(&ctx).pro, false)); - app.session.execute("prefs.set", json!({"path": "workspace.enableNarrowOptionsBar", "value": true})).unwrap(); - let narrow = run(&mut app); - assert_eq!(narrow, options_bar_height(Tokens::get(&ctx).pro, true)); - assert!(narrow < normal, "narrow {narrow} must trim the bar under {normal}"); - } - - #[test] - fn narrow_tool_options_can_scroll_to_the_last_control() { - for kind in crate::theme::ThemeKind::ALL { - for width in [360.0, 800.0, 1280.0] { - for scale in [1.0, 1.5, 2.0] { - let ctx = egui::Context::default(); - egui_extras::install_image_loaders(&ctx); - crate::theme::install_fonts(&ctx); - crate::theme::apply(&ctx, kind); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let (tool, last_label) = if Tokens::get(&ctx).pro { (Tool::Pencil, "Auto Erase") } else { (Tool::Brush, "Pressure for Opacity") }; - app.ui.tool = tool; - let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 120.0)); - let mut output = ctx.run_ui(input_at_scale(screen, scale), |ui| options_bar(&mut app, ui)); - output.textures_delta.clear(); - for frame in 1..=6 { - output = ctx.run_ui( - egui::RawInput { - time: Some(f64::from(frame) * 0.1), - events: vec![ - // Studio: above the controls, clear of the Brush's Mode dropdown, which takes the wheel - // to step through blend modes (#4512). - egui::Event::PointerMoved(if Tokens::get(&ctx).pro { pos2(width * 0.5, 20.0) } else { pos2(width * 0.5, 2.0) }), - egui::Event::MouseWheel { - source: egui::MouseWheelSource::Unknown, - unit: egui::MouseWheelUnit::Point, - delta: vec2(-1500.0, 0.0), - modifiers: egui::Modifiers::NONE, - phase: egui::TouchPhase::Move, - }, - ], - ..input_at_scale(screen, scale) - }, - |ui| options_bar(&mut app, ui), - ); - output.textures_delta.clear(); - } - let (clip, label) = output - .shapes - .iter() - .find_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.job.text.contains(last_label) => Some((shape.clip_rect, text)), - _ => None, - }) - .expect("scrolling reaches the final tool control"); - assert!( - clip.contains_rect(label.visual_bounding_rect()), - "{kind:?} at {width}: final control is clipped: {:?} / {clip:?}", - label.visual_bounding_rect() - ); - assert!(label.visual_bounding_rect().right() <= width, "the final option stays inside the window"); - } - } - } - } -} +mod compact_visual_regressions; #[cfg(test)] mod properties_target_regressions { diff --git a/crates/ui-egui/src/panels/compact_visual_regressions.rs b/crates/ui-egui/src/panels/compact_visual_regressions.rs new file mode 100644 index 0000000000..c4fdf59abc --- /dev/null +++ b/crates/ui-egui/src/panels/compact_visual_regressions.rs @@ -0,0 +1,519 @@ +use super::*; +use egui_kittest::kittest::Queryable; + +fn input_at_scale(screen: Rect, scale: f32) -> egui::RawInput { + let mut input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(scale); + input +} + +fn toolbar_harness(kind: theme::ThemeKind, scale: f32) -> egui_kittest::Harness<'static, PhotocraftApp> { + toolbar_harness_sized(kind, scale, 360.0) +} + +fn toolbar_harness_sized(kind: theme::ThemeKind, scale: f32, height: f32) -> egui_kittest::Harness<'static, PhotocraftApp> { + let mut ready = false; + let mut harness = egui_kittest::Harness::builder().with_size(vec2(400.0, height)).with_pixels_per_point(scale).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + egui_extras::install_image_loaders(ui.ctx()); + theme::install_fonts(ui.ctx()); + theme::apply(ui.ctx(), kind); + app.session.prefs.edit(|prefs| prefs.shortcuts.insert("window.togglePanels".into(), String::new())); + ready = true; + return; + } + crate::shortcuts::handle(app, ui.ctx()); + toolbar(app, ui); + }, + PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()), + ); + harness.run_steps(4); + harness +} + +#[test] +fn compact_toolbar_scrolls_to_and_activates_the_last_tool() { + for kind in theme::ThemeKind::ALL { + for scale in [1.0, 1.5, 2.0] { + let mut harness = toolbar_harness(kind, scale); + harness.event(egui::Event::PointerMoved(pos2(25.0, 100.0))); + harness.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -1500.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }); + harness.run_steps(30); + // Off the toolbar, so a tooltip of the tool scrolled under the pointer isn't a + // second "Zoom Tool" node. + harness.event(egui::Event::PointerMoved(pos2(300.0, 100.0))); + harness.run_steps(2); + let node = harness.get_by_label("Zoom Tool (Z)"); + let rect = node.rect(); + assert!(rect.top() >= 0.0 && rect.bottom() <= 360.0, "{kind:?} at {scale}x: last tool remains outside the toolbar: {rect:?}"); + node.click(); + harness.run_steps(3); + assert_eq!(harness.state().ui.tool, Tool::Zoom, "the scrolled button must select its real tool"); + } + } +} + +#[test] +fn compact_toolbar_tab_reveals_and_activates_the_last_tool() { + for kind in theme::ThemeKind::ALL { + for scale in [1.0, 1.5, 2.0] { + let mut harness = toolbar_harness(kind, scale); + // The supported shortcut preference clears the canvas Tab binding. From no + // focus, every step below is a real Tab processed by the app's dispatcher. + let mut reached = false; + for _ in 0..80 { + harness.key_press(egui::Key::Tab); + harness.run_steps(3); + reached = harness.get_by_label("Zoom Tool (Z)").is_focused(); + if reached { + break; + } + } + assert!(reached, "{kind:?} at {scale}x: Tab must reach the last tool"); + harness.run_steps(20); + let rect = harness.get_by_label("Zoom Tool (Z)").rect(); + assert!(rect.top() >= 0.0 && rect.bottom() <= 360.0, "{kind:?} at {scale}x: focused tool remains clipped: {rect:?}"); + harness.key_press(egui::Key::Space); + harness.run_steps(3); + assert_eq!(harness.state().ui.tool, Tool::Zoom, "Space must select the revealed tool"); + } + } +} + +/// A window taller than the tools keeps the colour chips right under the tool column (its +/// last row is Edit Toolbar), as Photoshop does, instead of at the bottom of the toolbar. +#[test] +fn tall_toolbar_keeps_the_colour_chips_under_the_tools() { + for kind in theme::ThemeKind::ALL { + let harness = toolbar_harness_sized(kind, 1.0, 1600.0); + let last = harness.get_by_label("Edit Toolbar…").rect(); + let swap = harness.get_by_label("Swap colours (X)").rect(); + assert!(swap.top() - last.bottom() < 80.0, "{kind:?}: the chips {swap:?} sit far below the last tool {last:?}"); + } +} + +#[test] +fn capture_compact_visual_fixtures() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(directory) = std::env::var_os("CRAFT_UI_VISUAL_FIXTURES").map(std::path::PathBuf::from) else { return }; + std::fs::create_dir_all(&directory).unwrap(); + for kind in crate::theme::ThemeKind::ALL { + for (width, height) in [(800.0, 480.0), (1280.0, 720.0)] { + for scale in [1.0, 1.5, 2.0] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.tools.foreground = [1.0, 0.0, 1.0, 1.0]; + app.session.tools.background = [0.0, 1.0, 0.0, 1.0]; + let mut ready = false; + let mut harness = egui_kittest::Harness::builder().with_size(vec2(width, height)).with_pixels_per_point(scale).wgpu().build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + egui_extras::install_image_loaders(ui.ctx()); + crate::theme::install_fonts(ui.ctx()); + crate::theme::apply(ui.ctx(), kind); + ready = true; + return; + } + app.ui.tool = if Tokens::get(ui.ctx()).pro { Tool::Pencil } else { Tool::Brush }; + options_bar(app, ui); + toolbar(app, ui); + }, + app, + ); + harness.input_mut().max_texture_side = Some(8192); + harness.run_steps(4); + let stem = format!("photocraft-compact-{}-{width}-{height}-{scale}x", kind.id()); + harness.render().unwrap().save(directory.join(format!("{stem}.png"))).unwrap(); + let mut regions = serde_json::Map::new(); + for id in ["options_bar", "toolbar"] { + let r = egui::containers::panel::PanelState::load(&harness.ctx, panel_state_id(&harness.ctx, id)).unwrap().outer_rect; + regions.insert(id.into(), json!([r.left(), r.top(), r.width(), r.height()])); + } + let metadata = json!({"screen": [width, height], "scale": scale, "regions": regions}); + std::fs::write(directory.join(format!("{stem}.json")), serde_json::to_vec_pretty(&metadata).unwrap()).unwrap(); + for _ in 0..6 { + harness.input_mut().events.extend([ + egui::Event::PointerMoved(pos2(width * 0.5, 20.0)), + egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Point, + delta: vec2(-1500.0, 0.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }, + ]); + harness.run_steps(1); + } + harness.render().unwrap().save(directory.join(format!("{stem}-scrolled.png"))).unwrap(); + std::fs::write(directory.join(format!("{stem}-scrolled.json")), serde_json::to_vec_pretty(&metadata).unwrap()).unwrap(); + } + } + } +} + +/// #7316: a window too short for the tools scrolls them, and the scroll bar widened the UI +/// the colour chips were centred in, so they (and Switch Colors with them) sat a bar's width +/// right of the tools. They stay where they are in a window tall enough not to scroll. +#[test] +fn color_chips_stay_centred_when_the_tools_scroll() { + let chips = |kind: crate::theme::ThemeKind, double: bool, height: f32, scale: f32| { + let ctx = egui::Context::default(); + egui_extras::install_image_loaders(&ctx); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, kind); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.tools.foreground = [1.0, 0.0, 1.0, 1.0]; + app.session.tools.background = [0.0, 1.0, 0.0, 1.0]; + app.ui.panels.toolbar_double = double; + let input = || input_at_scale(Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, height)), scale); + // The scroll bar shows from the frame after the one that measured the tools. + let mut output = ctx.run_ui(input(), |ui| toolbar(&mut app, ui)); + for _ in 0..2 { + output.textures_delta.clear(); + output = ctx.run_ui(input(), |ui| toolbar(&mut app, ui)); + } + output.textures_delta.clear(); + [Color32::from_rgb(255, 0, 255), Color32::GREEN].map(|color| { + output + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Rect(rect) if rect.fill == color => Some(rect.rect.center()), + egui::Shape::Circle(circle) if circle.fill == color => Some(circle.center), + _ => None, + }) + .unwrap_or_else(|| panic!("{kind:?}: both color chips are painted")) + .x + }) + }; + for kind in crate::theme::ThemeKind::ALL { + for double in [false, true] { + for scale in [1.0, 2.0] { + let (short, tall) = (chips(kind, double, 420.0, scale), chips(kind, double, 1400.0, scale)); + assert_eq!(short, tall, "{kind:?}, two columns {double}, scale {scale}: the chips don't move when the tools scroll"); + } + } + } +} + +#[test] +fn compact_toolbar_keeps_both_color_chips_visible() { + for kind in crate::theme::ThemeKind::ALL { + for height in [480.0, 720.0] { + for scale in [1.0, 1.5, 2.0] { + let ctx = egui::Context::default(); + egui_extras::install_image_loaders(&ctx); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, kind); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.tools.foreground = [1.0, 0.0, 1.0, 1.0]; + app.session.tools.background = [0.0, 1.0, 0.0, 1.0]; + let mut output = ctx.run_ui(input_at_scale(Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, height)), scale), |ui| toolbar(&mut app, ui)); + output.textures_delta.clear(); + for color in [Color32::from_rgb(255, 0, 255), Color32::GREEN] { + let (clip, chip) = output + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Rect(rect) if rect.fill == color => Some((shape.clip_rect, rect.rect)), + egui::Shape::Circle(circle) if circle.fill == color => { + Some((shape.clip_rect, Rect::from_center_size(circle.center, vec2(circle.radius * 2.0, circle.radius * 2.0)))) + } + _ => None, + }) + .unwrap_or_else(|| panic!("{kind:?} at {height}/{scale}: both color chips are painted")); + assert!(clip.contains_rect(chip) && chip.bottom() <= height, "{kind:?} at {height}: color chip {chip:?} clipped by {clip:?}"); + } + } + } + } +} + +#[test] +fn tab_focus_reveals_the_final_narrow_tool_option() { + for kind in theme::ThemeKind::ALL { + for scale in [1.0, 1.5, 2.0] { + let mut ready = false; + let mut harness = egui_kittest::Harness::builder().with_size(vec2(360.0, 120.0)).with_pixels_per_point(scale).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + egui_extras::install_image_loaders(ui.ctx()); + theme::install_fonts(ui.ctx()); + theme::apply(ui.ctx(), kind); + app.ui.tool = if Tokens::get(ui.ctx()).pro { Tool::Pencil } else { Tool::Brush }; + app.session.prefs.edit(|prefs| prefs.shortcuts.insert("window.togglePanels".into(), String::new())); + ready = true; + return; + } + crate::shortcuts::handle(app, ui.ctx()); + options_bar(app, ui); + }, + PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()), + ); + harness.run_steps(4); + let pro = Tokens::get(&harness.ctx).pro; + let last_label = if pro { "Auto Erase" } else { "Pressure for Opacity" }; + // Only the canvas Tab shortcut is cleared, using its public preference; + // no response is assigned focus programmatically. + let mut reached = false; + for _ in 0..80 { + harness.key_press(egui::Key::Tab); + harness.run_steps(3); + let label = harness.output().shapes.iter().find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.job.text.contains(last_label) => Some(text.visual_bounding_rect()), + _ => None, + }); + reached = label.is_some_and(|label| { + harness.ctx.memory(|memory| memory.focused()).and_then(|id| harness.ctx.read_response(id)).is_some_and(|response| { + response.rect.intersects(label) + || ((label.left() - response.rect.right()).abs() <= 12.0 + && response.rect.top() < label.bottom() + && response.rect.bottom() > label.top()) + }) + }); + if reached { + break; + } + } + assert!(reached, "{kind:?} at {scale}x: Tab must reach the final tool option"); + harness.run_steps(20); + let (clip, label) = harness + .output() + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.job.text.contains(last_label) => Some((shape.clip_rect, text.visual_bounding_rect())), + _ => None, + }) + .expect("the final option remains painted"); + assert!(clip.contains_rect(label), "{kind:?} at {scale}x: Tab leaves the focused final option outside {clip:?}: {label:?}"); + let previous = if pro { harness.state().ui.tool_options.pencil_auto_erase } else { harness.state().session.tools.brush.pressure_opacity }; + harness.key_press(egui::Key::Space); + harness.run_steps(3); + let current = if pro { harness.state().ui.tool_options.pencil_auto_erase } else { harness.state().session.tools.brush.pressure_opacity }; + assert_ne!(current, previous, "{kind:?} at {scale}x: Space must activate the revealed option"); + assert!(harness.state().ui.panels.options_bar, "widget traversal must preserve the options bar"); + } + } +} + +#[test] +fn a_wide_crop_options_bar_does_not_scroll() { + for kind in crate::theme::ThemeKind::ALL { + for scale in [1.0, 1.5, 2.0] { + for mode in ["", crate::crop_size::WHR] { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, kind); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + if !Tokens::get(&ctx).pro { + continue; + } + app.ui.tool = Tool::Crop; + app.ui.tool_options.crop_ratio = mode.into(); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 120.0)); + let clear_x = |output: &egui::FullOutput| { + output + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Text(t) if t.galley.job.text == "Clear" => Some(t.pos.x), + _ => None, + }) + .unwrap() + }; + let mut before = ctx.run_ui(input_at_scale(screen, scale), |ui| options_bar(&mut app, ui)); + before.textures_delta.clear(); + for _ in 0..3 { + before = ctx.run_ui(input_at_scale(screen, scale), |ui| options_bar(&mut app, ui)); + before.textures_delta.clear(); + } + let mut after = before.clone(); + for _ in 0..6 { + after = ctx.run_ui( + egui::RawInput { + events: vec![ + egui::Event::PointerMoved(pos2(800.0, 20.0)), + egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Point, + delta: vec2(-100.0, 0.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }, + ], + ..input_at_scale(screen, scale) + }, + |ui| options_bar(&mut app, ui), + ); + after.textures_delta.clear(); + } + assert_eq!(clear_x(&before), clear_x(&after), "a roomy bar must not have horizontal overflow"); + } + } + } +} + +#[test] +fn the_crop_ratio_fields_show_three_decimals() { + // #6487: a 1.414 : 1 ratio reads 1.414 in the bar, not 1.4. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let Some(kind) = crate::theme::ThemeKind::ALL.into_iter().find(|k| { + crate::theme::apply(&ctx, *k); + Tokens::get(&ctx).pro + }) else { + return; + }; + crate::theme::apply(&ctx, kind); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.ui.tool = Tool::Crop; + app.ui.tool_options.crop_ratio = "1.414:1".into(); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 120.0)); + let mut out = ctx.run_ui(input_at_scale(screen, 1.0), |ui| options_bar(&mut app, ui)); + for _ in 0..3 { + out.textures_delta.clear(); + out = ctx.run_ui(input_at_scale(screen, 1.0), |ui| options_bar(&mut app, ui)); + } + out.textures_delta.clear(); + let texts: Vec<&str> = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Text(t) => Some(t.galley.job.text.as_str()), + _ => None, + }) + .collect(); + assert!(texts.contains(&"1.414"), "{texts:?}"); + assert_eq!(app.ui.tool_options.crop_ratio, "1.414:1", "showing the ratio leaves it alone"); +} + +#[test] +fn a_typed_crop_ratio_fits_from_the_frame_the_edit_started_with() { + // #7752: typing 16 over 4 gave 1:3, then 16:3 inside that 100 x 300 frame (100 x 18.75). + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let Some(kind) = crate::theme::ThemeKind::ALL.into_iter().find(|k| { + crate::theme::apply(&ctx, *k); + Tokens::get(&ctx).pro + }) else { + return; + }; + crate::theme::apply(&ctx, kind); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.tool = Tool::Crop; + app.ui.tool_options.crop_shield.classic_mode = true; + app.ui.tool_options.crop_ratio = "4:3".into(); + app.ui.crop_rect = Some([0.0, 0.0, 400.0, 300.0]); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 120.0)); + let step = |app: &mut PhotocraftApp, events: Vec| { + let mut input = input_at_scale(screen, 1.0); + input.events = events; + ctx.run_ui(input, |ui| options_bar(app, ui)).textures_delta.clear(); + }; + for _ in 0..3 { + step(&mut app, vec![]); + } + // The ratio's W field is the bar's first number field; focusing it selects its text. + widgets::focus_first_field(&ctx, true); + step(&mut app, vec![]); + step(&mut app, vec![egui::Event::Text("1".into())]); + assert_eq!(app.ui.tool_options.crop_ratio, "1:3"); + step(&mut app, vec![egui::Event::Text("6".into())]); + step(&mut app, vec![]); + assert_eq!(app.ui.tool_options.crop_ratio, "16:3"); + let r = app.ui.crop_rect.unwrap(); + let want = [0.0, 112.5, 400.0, 187.5]; + assert!(r.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "16:3 fitted once in 400 x 300: {r:?}"); +} + +#[test] +fn the_narrow_options_bar_preference_shortens_the_bar() { + assert_eq!(options_bar_height(true, false), 36.0); + assert_eq!(options_bar_height(true, true), 30.0); + assert_eq!(options_bar_height(false, false), 42.0); + assert_eq!(options_bar_height(false, true), 34.0); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, crate::theme::ThemeKind::ALL[0]); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 900.0)); + let run = |app: &mut PhotocraftApp| { + let mut top = 0.0; + let mut out = ctx.run_ui(input_at_scale(screen, 1.0), |ui| { + options_bar(app, ui); + top = ui.available_rect_before_wrap().top(); + }); + out.textures_delta.clear(); + top + }; + let normal = run(&mut app); + assert_eq!(normal, options_bar_height(Tokens::get(&ctx).pro, false)); + app.session.execute("prefs.set", json!({"path": "workspace.enableNarrowOptionsBar", "value": true})).unwrap(); + let narrow = run(&mut app); + assert_eq!(narrow, options_bar_height(Tokens::get(&ctx).pro, true)); + assert!(narrow < normal, "narrow {narrow} must trim the bar under {normal}"); +} + +#[test] +fn narrow_tool_options_can_scroll_to_the_last_control() { + for kind in crate::theme::ThemeKind::ALL { + for width in [360.0, 800.0, 1280.0] { + for scale in [1.0, 1.5, 2.0] { + let ctx = egui::Context::default(); + egui_extras::install_image_loaders(&ctx); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, kind); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let (tool, last_label) = if Tokens::get(&ctx).pro { (Tool::Pencil, "Auto Erase") } else { (Tool::Brush, "Pressure for Opacity") }; + app.ui.tool = tool; + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 120.0)); + let mut output = ctx.run_ui(input_at_scale(screen, scale), |ui| options_bar(&mut app, ui)); + output.textures_delta.clear(); + for frame in 1..=6 { + output = ctx.run_ui( + egui::RawInput { + time: Some(f64::from(frame) * 0.1), + events: vec![ + // Studio: above the controls, clear of the Brush's Mode dropdown, which takes the wheel + // to step through blend modes (#4512). + egui::Event::PointerMoved(if Tokens::get(&ctx).pro { pos2(width * 0.5, 20.0) } else { pos2(width * 0.5, 2.0) }), + egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Point, + delta: vec2(-1500.0, 0.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }, + ], + ..input_at_scale(screen, scale) + }, + |ui| options_bar(&mut app, ui), + ); + output.textures_delta.clear(); + } + let (clip, label) = output + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.job.text.contains(last_label) => Some((shape.clip_rect, text)), + _ => None, + }) + .expect("scrolling reaches the final tool control"); + assert!( + clip.contains_rect(label.visual_bounding_rect()), + "{kind:?} at {width}: final control is clipped: {:?} / {clip:?}", + label.visual_bounding_rect() + ); + assert!(label.visual_bounding_rect().right() <= width, "the final option stays inside the window"); + } + } + } +} From b181da10910deaf929ace3500d8ae46f45928f36 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:15 +0000 Subject: [PATCH 089/259] refactor(ui-egui): move filter_dialog.rs tests to filter_dialog/tests.rs --- crates/ui-egui/src/filter_dialog.rs | 1554 +-------------------- crates/ui-egui/src/filter_dialog/tests.rs | 1551 ++++++++++++++++++++ 2 files changed, 1552 insertions(+), 1553 deletions(-) create mode 100644 crates/ui-egui/src/filter_dialog/tests.rs diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs index 7f0ae8e998..24b9609b20 100644 --- a/crates/ui-egui/src/filter_dialog.rs +++ b/crates/ui-egui/src/filter_dialog.rs @@ -1316,1556 +1316,4 @@ impl FilterPreviewKey { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_unit_after_a_range_bound_does_not_reset_the_range_to_its_fallback() { - // #7598: `0.5..5000 px?` fell back to a maximum of 100, so the Mixer Brush's Size slider - // (and every range documented with a px or % suffix) topped out at 100. - let range = |spec: &str| match parse_spec(spec).into_iter().next().map(|p| p.kind) { - Some(Kind::Range { min, max, default }) => (min, max, default), - other => panic!("{spec}: {other:?}"), - }; - assert_eq!(range(r#"{"size":0.5..5000 px?}"#), (0.5, 5000.0, 0.5)); - assert_eq!(range(r#"{"scale":1..1000 %=100}"#), (1.0, 1000.0, 100.0)); - assert_eq!(range(r#"{"tolerance":0.5..10 px=2}"#), (0.5, 10.0, 2.0)); - assert_eq!(range(r#"{"angle":-180..180}"#), (-180.0, 180.0, -180.0)); - assert_eq!(range(r#"{"radius":0.1..1000=1}"#), (0.1, 1000.0, 1.0)); - assert_eq!(range(r#"{"gain":1e-3..2e2}"#), (0.001, 200.0, 0.001)); - // A bound that is no number at all still takes the old fallback rather than failing. - assert_eq!(range(r#"{"x":0..many}"#), (0.0, 100.0, 0.0)); - // The documented specs of the real commands read their full ranges. - let spec = photocraft_engine::commands::find("paint.pencil").expect("paint.pencil is registered"); - let size = parse_spec(spec.params).into_iter().find(|p| p.key == "size"); - assert!(matches!(size.map(|p| p.kind), Some(Kind::Range { max, .. }) if max == 5000.0)); - } - - #[test] - fn color_settings_working_spaces_list_installed_profiles_of_their_space() { - // #6323: a press condition installed in the system can be the CMYK working space, as in - // Photoshop's Color Settings; each working-space menu lists only profiles of its space. - use photocraft_cms::{ColorSpace, ProfileClass}; - let p = |path: &str, class, color_space| InstalledProfile { path: path.into(), description: path.to_uppercase(), class, color_space }; - let installed = [ - p("gracol.icc", ProfileClass::Output, ColorSpace::Cmyk), - p("monitor.icc", ProfileClass::Display, ColorSpace::Rgb), - p("printer-rgb.icc", ProfileClass::Output, ColorSpace::Rgb), - p("scanner.icc", ProfileClass::Input, ColorSpace::Rgb), - p("gray.icc", ProfileClass::Output, ColorSpace::Gray), - p("link.icc", ProfileClass::DeviceLink, ColorSpace::Cmyk), - ]; - let paths = |key: &str| installed_choices("edit.colorSettings", key, &installed).into_iter().map(|(path, _)| path).collect::>(); - assert_eq!(paths("workingCmyk"), ["gracol.icc"]); - assert_eq!(paths("workingRgb"), ["monitor.icc"]); - assert_eq!(paths("workingGray"), ["gray.icc"]); - assert!(paths("policyCmyk").is_empty() && paths("intent").is_empty()); - assert_eq!(installed_choices("edit.colorSettings", "workingCmyk", &installed)[0].1, "GRACOL.ICC", "listed by description"); - // The profile dialogs keep listing every destination profile. - assert_eq!(installed_choices("edit.convertToProfile", "profile", &installed).len(), 5); - assert!(installed_choices("filter.blur.gaussianBlur", "profile", &installed).is_empty()); - } - - /// #5710: the seed field's Random button always gives a different seed the field can hold. - #[test] - fn random_seeds_stay_in_range_and_change() { - let mut seen = std::collections::HashSet::new(); - for i in 0..200u64 { - let s = random_seed(i, 7); - assert!((0..=30_000).contains(&s), "{s}"); - assert_ne!(s, 7, "a click always changes the seed"); - seen.insert(s); - } - assert!(seen.len() > 100, "seeds spread out: {}", seen.len()); - assert_ne!(random_seed(1, 30_000), 30_000); - // Every seed dialog shows the button: Clouds, Add Noise and the like carry a `seed` param. - let specs = photocraft_engine::command_specs(); - assert!( - specs - .iter() - .filter(|c| c.id.starts_with("filter.")) - .any(|c| parse_spec(c.params).iter().any(|p| p.key == "seed" && matches!(p.kind, Kind::Int { .. }))) - ); - } - - /// Preset names such as "iPhone 14 Pro Max" (the artboard dialog's choices) are text, not - /// camelCase keys: they used to read "I Phone 14 Pro Max". - #[test] - fn display_names_are_not_split_like_camel_case_keys() { - assert_eq!(source_label("iPhone 14 Pro Max"), "iPhone 14 Pro Max"); - assert_eq!(source_label("Web 1920"), "Web 1920"); - assert_eq!(source_label("centerX"), "Center X"); - } - - /// Convert to Profile's and Proof Setup's `bpc` read "Bpc": spelled out. - #[test] - fn black_point_compensation_is_spelled_out() { - assert_eq!(source_label("bpc"), "Black Point Compensation"); - } - - fn key() -> FilterPreviewKey { - FilterPreviewKey { - doc: photocraft_doc::DocId(7), - revision: 11, - dialog: 3, - active: Some(photocraft_doc::LayerId(2)), - target: Default::default(), - command: "filter.blur.gaussianBlur".into(), - params: json!({"radius": 4.0}), - k: 1, - } - } - - #[test] - fn same_target_ignores_parameters_but_nothing_else() { - // A drag only changes the parameters, and that must not hide the finished frame. - let base = key(); - let mut moved = base.clone(); - moved.params = json!({"radius": 40.0}); - assert!(base.same_target(&moved)); - assert!(moved.same_target(&base)); - - // Anything else names a different preview and must not be shown. - for break_it in [ - |k: &mut FilterPreviewKey| k.doc = photocraft_doc::DocId(8), - |k: &mut FilterPreviewKey| k.revision = 12, - |k: &mut FilterPreviewKey| k.dialog = 4, - |k: &mut FilterPreviewKey| k.active = Some(photocraft_doc::LayerId(5)), - |k: &mut FilterPreviewKey| k.active = None, - |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, - ] { - let mut other = base.clone(); - break_it(&mut other); - assert!(!other.same_target(&base), "{other:?} must not pass as {base:?}"); - assert!(!base.same_target(&other)); - } - } - - #[test] - fn only_direction_angles_get_the_dial() { - // Every listed command still has a degree `angle` range, so the list cannot go stale. - for cmd in ANGLE_DIAL { - let spec = photocraft_engine::commands::find(cmd).unwrap_or_else(|| panic!("{cmd} is not a command")).params; - assert!( - parse_spec(spec).iter().any(|p| p.key == "angle" && matches!(p.kind, Kind::Range { min, max, .. } if min >= -360.0 && max <= 360.0)), - "{cmd} has no angle range" - ); - assert!(uses_angle_dial(cmd, "angle")); - assert!(!uses_angle_dial(cmd, "distance")); - } - // Rotation amounts and angles with another zero keep their slider. - for cmd in - ["filter.distort.twirl", "image.rotation.arbitrary", "image.crop", "filter.blurGallery.tiltShift", "filter.lensCorrection", "filter.render.flame"] - { - assert!(!uses_angle_dial(cmd, "angle"), "{cmd}"); - } - } - - #[test] - fn restores_only_valid_previous_filter_choices() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.prefs.edit(|prefs| { - prefs.dialogs.insert("filter.blur.gaussianBlur".into(), json!({"radius": 11.0, "bogus": 42})); - }); - open(&mut app, "filter.blur.gaussianBlur").unwrap(); - let fields = &app.ui.dialogs.last().unwrap().fields; - assert_eq!(fields["radius"], json!(11.0)); - assert!(!fields.contains_key("bogus")); - - // A changed registry range, corrupt preference or stale path is never restored. - let mut fields = Map::new(); - fields.insert("radius".into(), json!(2.0)); - restore_remembered(&app, "filter.blur.gaussianBlur", r#"{"radius":0.1..5=1}"#, &mut fields); - assert_eq!(fields["radius"], json!(2.0)); - } - - #[test] - fn alt_reset_restores_schema_defaults_not_remembered() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.prefs.edit(|prefs| { - prefs.dialogs.insert("filter.blur.gaussianBlur".into(), json!({"radius": 11.0})); - }); - let id = open(&mut app, "filter.blur.gaussianBlur").unwrap(); - assert_eq!(app.ui.dialog_mut(id).unwrap().fields["radius"], json!(11.0)); - let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone(); - reset_fields(&app, &mut fields); - app.ui.dialog_mut(id).unwrap().fields = fields; - let f = &app.ui.dialog_mut(id).unwrap().fields; - // Registry default for gaussian blur radius is 1. - assert_eq!(f["radius"], json!(1.0)); - assert!(f.contains_key("__filter")); - assert!(app.ui.dialogs.iter().any(|d| d.id == id)); - } - - /// #5806: OK in Displace with no map asks for the map file, as Photoshop does, and displaces - /// with the chosen file; Cancel in the picker applies nothing; a map already given runs at once. - #[test] - fn displace_asks_for_its_map_after_ok() { - let dir = std::env::temp_dir().join(format!("photocraft-displace-map-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let map = dir.join("map.png"); - let mut m = photocraft_engine::Session::new(); - m.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); - std::fs::write(&map, photocraft_io::export(&m.active().unwrap().doc, "map.png", &Default::default()).unwrap().bytes).unwrap(); - let answers = vec![Some(crate::file_dialog::FileDialogAnswer::Paths(vec![map.to_string_lossy().into_owned()])), None]; - let (show, asked) = crate::file_dialog::fake(answers); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { file_dialog: Some(show), ..Default::default() }); - app.run("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); - app.run("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap(); - app.run("edit.fill", json!({"color": "#000000"})).unwrap(); - app.run("select.deselect", json!({})).unwrap(); - let steps = app.session.active().unwrap().history.past_len(); - let ctx = egui::Context::default(); - let id = open(&mut app, "filter.distort.displace").unwrap(); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert!(app.file_dialog_open(), "OK leaves the map picker pending"); - // Another document activated while the picker is open is left alone. - app.run("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); - let other_steps = app.session.documents()[1].history.past_len(); - // The frame shows the picker (the service is asked then) and acts on its answer. - app.poll_file_dialog(&ctx, None); - assert_eq!(asked.borrow().len(), 1, "OK asks for the map"); - assert_eq!(app.session.active_index(), Some(0), "the document that asked is shown"); - assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1, "Displace ran with the chosen map"); - assert_eq!(app.session.documents()[1].history.past_len(), other_steps, "not on the other document"); - // Cancelled: nothing is applied. - let id = open(&mut app, "filter.distort.displace").unwrap(); - crate::dialogs::confirm(&mut app, id).unwrap(); - app.poll_file_dialog(&ctx, None); - assert_eq!(asked.borrow().len(), 2); - assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); - // A map given in the dialog runs without asking. - assert!(!needs_displace_map("filter.distort.displace", &json!({"mapPath": "/maps/x.psd"}))); - assert!(!needs_displace_map("filter.distort.displace", &json!({"mapDocument": 0}))); - assert!(needs_displace_map("filter.distort.displace", &json!({"mapDocument": -1, "mapPath": " "}))); - assert!(!needs_displace_map("filter.blur.gaussianBlur", &json!({}))); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn remembering_dialogs_never_persists_paths_or_document_indices() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let mut fields = Map::new(); - fields.insert("__filter".into(), json!(true)); - fields.insert("radius".into(), json!(7.0)); - fields.insert("mapPath".into(), json!("/private/file")); - fields.insert("document".into(), json!(5)); - remember(&mut app, "filter.blur.gaussianBlur", &fields); - let saved = &app.session.prefs().dialogs["filter.blur.gaussianBlur"]; - assert_eq!(saved["radius"], json!(7.0)); - assert!(saved.get("mapPath").is_none()); - assert!(saved.get("document").is_none()); - } - - #[test] - fn parses_registry_notation() { - let p = parse_spec(r#"{"radius":0.1..1000=1,"method":"spin|zoom","monochromatic":bool,"seed":u32=0,"horizontal":px=0}"#); - assert_eq!(p[0], Param { key: "radius".into(), kind: Kind::Range { min: 0.1, max: 1000.0, default: 1.0 } }); - assert_eq!(p[1].kind, Kind::Choice { options: vec!["spin".into(), "zoom".into()], default: None }); - assert_eq!(p[2].kind, Kind::Bool(false)); - assert_eq!(p[3].kind, Kind::Int { default: 0 }); - assert_eq!(p[4].kind, Kind::Int { default: 0 }); - assert!(parse_spec("{}").is_empty()); - let p_choice = parse_spec(r#"{"quality":"draft|good|best"="good"}"#); - assert_eq!(p_choice[0].kind, Kind::Choice { options: vec!["draft".into(), "good".into(), "best".into()], default: Some("good".into()) }); - let p = parse_spec(r#"{"lighting":bool=true,"kernel":int[25],"pins":json,"points":[[0,0],[1,0]],"mapPath":text,"mapDocument":doc,"scale":1..9999=1}"#); - let kinds: Vec<&Kind> = p.iter().map(|p| &p.kind).collect(); - assert_eq!( - kinds, - [&Kind::Bool(true), &Kind::Grid(25), &Kind::Json, &Kind::Json, &Kind::Text, &Kind::Document, &Kind::Range { min: 1.0, max: 9999.0, default: 1.0 }] - ); - } - - /// A layer-id param has no number field: drawing the Auto-Align dialog used to write - /// `reference: 0` back, which the engine rejects as not a selected layer (#674). - #[test] - fn layer_id_params_stay_out_of_the_dialog() { - let mut f = Map::new(); - f.insert("__command".into(), json!("edit.autoAlignLayers")); - egui::Context::default().run_ui(Default::default(), |ui| body(ui, &mut f)).textures_delta.clear(); - assert!(!params_of(&f).as_object().unwrap().contains_key("reference"), "{f:?}"); - } - - /// Layer › Layer Style › Global Light (#3054): Global Light dialog opens with the active - /// document's current shared lighting, preserving it on unchanged OK, ignoring stale - /// remembered dialog values, tracking document switching, applying edits, and leaving the - /// document unchanged on Cancel. - #[test] - fn global_light_dialog_reflects_active_document_light() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - let doc1_id = app.session.active().unwrap().doc.id; - - // 0. Default-document control: fresh document starts at angle 120 and altitude 30. - let d_default = crate::menus::invoke(&mut app, &ctx, "layer.layerStyle.globalLight", Value::Null).unwrap()["dialog"].as_u64().unwrap(); - assert_eq!(app.ui.dialog_mut(d_default).unwrap().fields["angle"], json!(120.0)); - assert_eq!(app.ui.dialog_mut(d_default).unwrap().fields["altitude"], json!(30.0)); - crate::dialogs::confirm(&mut app, d_default).unwrap(); - assert_eq!(app.session.active().unwrap().doc.global_light.angle, 120.0); - assert_eq!(app.session.active().unwrap().doc.global_light.altitude, 30.0); - - // 1. Change document's global light to 30 degrees angle and 45 degrees altitude. - app.run("layer.layerStyle.globalLight", json!({"angle": 30.0, "altitude": 45.0})).unwrap(); - assert_eq!(app.session.active().unwrap().doc.global_light.angle, 30.0); - assert_eq!(app.session.active().unwrap().doc.global_light.altitude, 45.0); - - // 2. Open Global Light dialog: opens with the active document's light (30 / 45). - let d_id = crate::menus::invoke(&mut app, &ctx, "layer.layerStyle.globalLight", Value::Null).unwrap()["dialog"].as_u64().unwrap(); - let fields = &app.ui.dialog_mut(d_id).unwrap().fields; - assert_eq!(fields["angle"], json!(30.0)); - assert_eq!(fields["altitude"], json!(45.0)); - - // 3. Unchanged OK preserves the document's light. - crate::dialogs::confirm(&mut app, d_id).unwrap(); - let gl = app.session.active().unwrap().doc.global_light; - assert_eq!(gl.angle, 30.0); - assert_eq!(gl.altitude, 45.0); - - // 4. Stale remembered values do not override the active document. - app.session.prefs.edit(|prefs| { - prefs.dialogs.insert( - "layer.layerStyle.globalLight".into(), - json!({ - "angle": 75.0, - "altitude": 60.0, - }), - ); - }); - let d_id = open(&mut app, "layer.layerStyle.globalLight").unwrap(); - let fields = &app.ui.dialog_mut(d_id).unwrap().fields; - assert_eq!(fields["angle"], json!(30.0), "reads active document, not remembered"); - assert_eq!(fields["altitude"], json!(45.0)); - - // 5. Cancel preserves the document's light. - app.ui.close_dialog(d_id); - let gl = app.session.active().unwrap().doc.global_light; - assert_eq!(gl.angle, 30.0); - assert_eq!(gl.altitude, 45.0); - - // 6. Multiple documents: each document initializes the dialog to its own light. - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - let doc2_id = app.session.active().unwrap().doc.id; - assert_ne!(doc1_id, doc2_id); - app.run("layer.layerStyle.globalLight", json!({"angle": -45.0, "altitude": 15.0})).unwrap(); - assert_eq!(app.session.active().unwrap().doc.global_light.angle, -45.0); - assert_eq!(app.session.active().unwrap().doc.global_light.altitude, 15.0); - - let d_id2 = open(&mut app, "layer.layerStyle.globalLight").unwrap(); - let fields2 = &app.ui.dialog_mut(d_id2).unwrap().fields; - assert_eq!(fields2["angle"], json!(-45.0)); - assert_eq!(fields2["altitude"], json!(15.0)); - app.ui.close_dialog(d_id2); - - // Switch back to doc1: dialog still reflects doc1's light (30 / 45). - assert!(app.session.set_active(0)); - let d_id1 = open(&mut app, "layer.layerStyle.globalLight").unwrap(); - assert_eq!(app.ui.dialog_mut(d_id1).unwrap().fields["angle"], json!(30.0)); - assert_eq!(app.ui.dialog_mut(d_id1).unwrap().fields["altitude"], json!(45.0)); - - // 7. Modifying the dialog updates the active document. - app.ui.dialog_mut(d_id1).unwrap().fields.insert("angle".into(), json!(-60.0)); - app.ui.dialog_mut(d_id1).unwrap().fields.insert("altitude".into(), json!(20.0)); - crate::dialogs::confirm(&mut app, d_id1).unwrap(); - assert_eq!(app.session.active().unwrap().doc.global_light.angle, -60.0); - assert_eq!(app.session.active().unwrap().doc.global_light.altitude, 20.0); - - // Switch to doc2: doc2 is untouched (-45 / 15). - assert!(app.session.set_active(1)); - assert_eq!(app.session.active().unwrap().doc.global_light.angle, -45.0); - assert_eq!(app.session.active().unwrap().doc.global_light.altitude, 15.0); - } - - /// View › Proof Setup (#3055): Custom Proof Setup opens with the active document's current - /// proof condition, preserving it on unchanged OK, ignoring stale remembered dialog values, - /// tracking document switching, applying edits, and leaving the document unchanged on Cancel. - #[test] - fn proof_setup_dialog_reflects_active_document_proof_condition() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - let doc1_id = app.session.active().unwrap().doc.id; - - // 0. A fresh document defaults to working-cmyk. - let d_fresh = crate::menus::invoke(&mut app, &ctx, "view.proofSetup.custom", Value::Null).unwrap()["dialog"].as_u64().unwrap(); - assert_eq!(app.ui.dialog_mut(d_fresh).unwrap().fields["profile"], json!("working-cmyk")); - crate::dialogs::confirm(&mut app, d_fresh).unwrap(); - assert_eq!(app.session.color.proof(doc1_id).setup.name, "working-cmyk"); - - // 1. Preset sets sRGB and turns Proof Colors on. - crate::menus::invoke(&mut app, &ctx, "view.proofSetup.internetStandardRgb", Value::Null).unwrap(); - assert_eq!(app.session.color.proof(doc1_id).setup.name, "srgb"); - assert!(app.session.color.proof(doc1_id).enabled); - - // 2. Open Custom Proof Setup: starts with the active document's condition (sRGB). - let d_id = crate::menus::invoke(&mut app, &ctx, "view.proofSetup.custom", Value::Null).unwrap()["dialog"].as_u64().unwrap(); - let fields = &app.ui.dialog_mut(d_id).unwrap().fields; - assert_eq!(fields["profile"], json!("srgb")); - assert_eq!(fields["intent"], json!("relative")); - assert_eq!(fields["bpc"], json!(true)); - assert_eq!(fields["simulatePaper"], json!(false)); - - // 3. Unchanged OK preserves the document's condition and leaves Proof Colors enabled. - crate::dialogs::confirm(&mut app, d_id).unwrap(); - let pv = app.session.color.proof(doc1_id); - assert_eq!(pv.setup.name, "srgb"); - assert!(pv.enabled); - - // 4. Stale remembered values do not override the active document. - app.session.prefs.edit(|prefs| { - prefs.dialogs.insert( - "view.proofSetup".into(), - json!({ - "profile": "display-p3", - "intent": "perceptual", - "bpc": false, - "simulatePaper": true, - }), - ); - }); - let d_id = open(&mut app, "view.proofSetup").unwrap(); - let fields = &app.ui.dialog_mut(d_id).unwrap().fields; - assert_eq!(fields["profile"], json!("srgb"), "reads active document, not remembered"); - assert_eq!(fields["intent"], json!("relative")); - assert_eq!(fields["bpc"], json!(true)); - assert_eq!(fields["simulatePaper"], json!(false)); - - // 5. Cancel preserves the document. - app.ui.close_dialog(d_id); - assert_eq!(app.session.color.proof(doc1_id).setup.name, "srgb"); - - // 6. Multiple documents: each document initializes the dialog to its own condition. - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - let doc2_id = app.session.active().unwrap().doc.id; - assert_ne!(doc1_id, doc2_id); - app.run("view.proofSetup", json!({"profile": "display-p3", "intent": "perceptual", "bpc": false, "simulatePaper": true})).unwrap(); - assert_eq!(app.session.color.proof(doc2_id).setup.name, "display-p3"); - - let d_id2 = open(&mut app, "view.proofSetup").unwrap(); - let fields2 = &app.ui.dialog_mut(d_id2).unwrap().fields; - assert_eq!(fields2["profile"], json!("display-p3")); - assert_eq!(fields2["intent"], json!("perceptual")); - assert_eq!(fields2["bpc"], json!(false)); - assert_eq!(fields2["simulatePaper"], json!(true)); - app.ui.close_dialog(d_id2); - - // Switch back to doc1: dialog still reflects doc1's sRGB. - assert!(app.session.set_active(0)); - let d_id1 = open(&mut app, "view.proofSetup").unwrap(); - assert_eq!(app.ui.dialog_mut(d_id1).unwrap().fields["profile"], json!("srgb")); - - // 7. Modifying the dialog updates the active document. - app.ui.dialog_mut(d_id1).unwrap().fields.insert("profile".into(), json!("adobe-rgb-compat")); - crate::dialogs::confirm(&mut app, d_id1).unwrap(); - assert_eq!(app.session.color.proof(doc1_id).setup.name, "adobe-rgb-compat"); - // doc2 is untouched - assert_eq!(app.session.color.proof(doc2_id).setup.name, "display-p3"); - } - - #[test] - fn indexed_counts_are_integer_json_while_dither_amounts_keep_their_decimals() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - open(&mut app, "image.mode.indexedColor").unwrap(); - let mut defaults = app.ui.dialogs.first().unwrap().fields.clone(); - let before = params_of(&defaults)["colors"].clone(); - egui::Context::default().run_ui(Default::default(), |ui| body(ui, &mut defaults)).textures_delta.clear(); - assert_eq!(before.as_u64(), Some(256)); - assert_eq!(params_of(&defaults)["colors"], before, "opening a preview must not schedule a second job just to normalize its count"); - let mut fields = Map::new(); - fields.insert("__command".into(), json!("image.mode.indexedColor")); - fields.insert("colors".into(), json!(17)); - fields.insert("amount".into(), json!(37.5)); - egui::Context::default().run_ui(Default::default(), |ui| body(ui, &mut fields)).textures_delta.clear(); - let params = params_of(&fields); - assert_eq!(params["colors"].as_u64(), Some(17)); - assert_eq!(params["amount"].as_f64(), Some(37.5)); - } - - /// #7400: Lens Blur's Source lists the document's alpha channels, by name, each choosable even - /// when two share a name; `depthChannel` is set through that menu, not shown as a field, and - /// like the other references it isn't remembered, so a remembered `channel` source opens as None. - #[test] - fn lens_blur_source_lists_the_alpha_channels() { - let spec = photocraft_engine::commands::find(LENS_BLUR).unwrap().params; - let params = parse_spec(spec); - assert!(params.iter().any(|p| p.key == "depthChannel" && p.kind == Kind::Json), "depthChannel is no dialog field"); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 20, "height": 10})).unwrap(); - app.run("channel.new", json!({"name": "Depth Map", "fill": "white"})).unwrap(); - let id = open(&mut app, LENS_BLUR).unwrap(); - assert_eq!(app.ui.dialog_mut(id).unwrap().fields["__channels"], json!(["Depth Map"])); - // The menu's values are channel indices, so two channels with one name are both choosable. - app.run("channel.new", json!({"name": "Depth Map", "fill": "black"})).unwrap(); - let id = open(&mut app, LENS_BLUR).unwrap(); - let names: Vec = serde_json::from_value(app.ui.dialog_mut(id).unwrap().fields["__channels"].clone()).unwrap(); - assert_eq!(names, ["Depth Map", "Depth Map"]); - assert_eq!((channel_choice(0), channel_choice(1)), ("channel:0".to_string(), "channel:1".to_string())); - assert_eq!(channel_index(&json!(1), &names), Some(1), "the second one by its index"); - assert_eq!(channel_index(&json!("Depth Map"), &names), Some(0), "a name is the first so named, as the engine reads it"); - assert_eq!(channel_index(&json!(2), &names), None); - - app.session.prefs.edit(|p| { - p.dialogs.insert(LENS_BLUR.into(), json!({"depthMap": "channel", "depthChannel": "Depth Map"})); - }); - let id = open(&mut app, LENS_BLUR).unwrap(); - let f = &app.ui.dialog_mut(id).unwrap().fields; - assert_eq!(f["depthMap"], "none", "no channel was remembered with it"); - assert!(f.get("depthChannel").is_none()); - } - - #[test] - fn wide_positive_ranges_use_the_logarithmic_slider_path() { - assert!(uses_logarithmic_slider(0.1, 1000.0), "Gaussian Blur radius"); - assert!(uses_logarithmic_slider(1.0, 9999.0)); - assert!(!uses_logarithmic_slider(1.0, 500.0)); - assert!(!uses_logarithmic_slider(0.0, 1000.0)); - } - - #[test] - fn new_filters_have_dialogs_or_run_directly() { - for id in [ - "filter.stylize.oilPaint", - "filter.blur.lensBlur", - "filter.blurGallery.irisBlur", - "filter.other.custom", - "filter.distort.displace", - "filter.pixelate.mezzotint", - "filter.render.lightingEffects", - "filter.render.relight", - "filter.other.colorToAlpha", - ] { - assert!(has_dialog(id), "{id}"); - } - for id in ["filter.pixelate.facet", "filter.pixelate.fragment", "filter.video.ntscColors"] { - assert!(!has_dialog(id), "{id}"); - } - } - - #[test] - fn every_filter_command_spec_parses() { - for c in photocraft_engine::command_specs().iter().filter(|c| c.id.starts_with("filter.")) { - let _ = parse_spec(c.params); - } - assert!(has_dialog("filter.blur.gaussianBlur")); - assert!(!has_dialog("filter.stylize.findEdges")); - } - - /// Select and Mask's Output To lists all six output targets. - #[test] - fn select_and_mask_output_lists_all_six_targets() { - let spec = photocraft_engine::commands::find("select.refineEdge").unwrap().params; - let p = parse_spec(spec).into_iter().find(|p| p.key == "output").unwrap(); - let Kind::Choice { options: choices, .. } = p.kind else { panic!("output is not a choice") }; - let labels: Vec = choices.iter().map(|c| source_label(c)).collect(); - assert_eq!(labels, ["Selection", "Layer Mask", "New Layer", "New Layer With Mask", "New Document", "New Document With Mask"]); - } - - #[test] - fn preview_runs_engine_command_on_proxy() { - let mut doc = Document::with_background( - "p", - photocraft_doc::Size::new(64, 64), - photocraft_doc::ColorMode::Rgb, - photocraft_doc::SampleType::U8, - photocraft_doc::Color::WHITE, - ); - let bg = doc.layers[0].id; - doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 32, 64), &[0.0, 0.0, 0.0, 1.0]); - let out = preview_document(&doc, Some(bg), "filter.blur.gaussianBlur", &json!({"radius": 4.0}), 1).unwrap(); - let p = out.layers[0].surface().unwrap().pixel(32, 32); - assert!(p[0] > 0.2 && p[0] < 0.8, "edge blurred: {p:?}"); - assert_eq!(label("wavelengthMin"), "Wavelength Min"); - } - - /// #7423 (review on #7799): re-editing a Displace smart filter and picking another open - /// document as its map previews with that document, as OK applies it. The preview session held - /// only the edited document, and the map's `mapDocument` sits inside the filter's `params`. - #[test] - fn smart_displace_preview_uses_the_map_document() { - let mut s = photocraft_engine::Session::new(); - // Documents 0 and 1: a white and a black map, opened before the edited one. - s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); - s.execute("file.new", json!({"width": 8, "height": 8, "background": "black"})).unwrap(); - s.execute("file.new", json!({"width": 48, "height": 32, "background": "transparent"})).unwrap(); - s.edit("square", |doc, active| { - let fmt = doc.pixel_format(); - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - surf.fill_rect(photocraft_geom::Rect::new(10, 10, 20, 12), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); - Ok(()) - }) - .unwrap(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("filter.distort.displace", json!({"horizontal": 10, "vertical": 0, "mapDocument": 0})).unwrap(); - let doc = s.active().unwrap().doc.clone(); - let layer = s.active().unwrap().active_layer; - let documents: Vec<_> = s.documents().iter().map(|d| d.doc.clone()).collect(); - for map in [1, 0] { - let p = json!({"index": 0, "params": {"mapDocument": map}}); - let mut applied = photocraft_engine::Session::new(); - for d in &documents { - applied.add_document((**d).clone(), None); - } - applied.execute(SMART_FILTER_SET_PARAMS, p.clone()).unwrap(); - let want = photocraft_compose::render(&applied.active().unwrap().doc, doc.bounds()).px; - let preview = preview_document_for_target( - &doc, - layer, - SMART_FILTER_SET_PARAMS, - &p, - 1, - None, - photocraft_engine::channel_cmds::ChannelTarget::Composite, - &documents, - &ColorSettings::default(), - ) - .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"); - } - } - - /// Match Color's preview reads the Source document from the open documents, as OK does: the - /// preview session held only the edited document, so a Source showed no change (#4851). - #[test] - fn match_color_preview_uses_the_source_document() { - use photocraft_doc::{Color, ColorMode, SampleType, Size}; - let solid = |name: &str, c: [f32; 4]| { - let mut d = Document::with_background(name, Size::new(32, 32), ColorMode::Rgb, SampleType::U8, Color::WHITE); - d.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 32, 32), &c); - d.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 16, 32), &[c[0] * 0.5, c[1] * 0.5, c[2] * 0.5, 1.0]); - d - }; - // The source document is open before the edited one, so indices differ between sessions. - let mut s = photocraft_engine::Session::new(); - s.add_document(solid("reference", [0.1, 0.3, 0.9, 1.0]), None); - s.add_document(solid("texture", [0.9, 0.5, 0.2, 1.0]), None); - let doc = s.active().unwrap().doc.clone(); - let layer = doc.layers[0].id; - let documents: Vec<_> = s.documents().iter().map(|d| d.doc.clone()).collect(); - for (source, label) in [(0, "another document"), (1, "the edited document itself")] { - let p = json!({"source": source}); - let mut applied = photocraft_engine::Session::new(); - for d in &documents { - applied.add_document((**d).clone(), None); - } - applied.execute("image.adjustments.matchColor", p.clone()).unwrap(); - let want = applied.active().unwrap().doc.layers[0].surface().unwrap().pixel(24, 16); - let preview = preview_document_for_target( - &doc, - Some(layer), - "image.adjustments.matchColor", - &p, - 1, - None, - photocraft_engine::channel_cmds::ChannelTarget::Composite, - &documents, - &ColorSettings::default(), - ) - .unwrap_or_else(|| panic!("{label}: no preview")); - let got = preview.layers[0].surface().unwrap().pixel(24, 16); - assert!((0..3).all(|c| (got[c] - want[c]).abs() < 1.0 / 255.0 + 1e-4), "{label}: preview {got:?}, OK gives {want:?}"); - } - // The preview is of the matched image: the orange texture took the reference's blue. - let preview = preview_document_for_target( - &doc, - Some(layer), - "image.adjustments.matchColor", - &json!({"source": 0}), - 2, - None, - photocraft_engine::channel_cmds::ChannelTarget::Composite, - &documents, - &ColorSettings::default(), - ) - .unwrap(); - let px = preview.layers[0].surface().unwrap().pixel(12, 8); - assert!(px[2] > px[0], "proxy preview matched to the reference: {px:?}"); - } - - #[test] - fn core_filter_previews_keep_minimum_settings_after_downsampling() { - use photocraft_doc::{Color, ColorMode, SampleType, Size}; - use photocraft_geom::Rect; - - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - let mut doc = Document::with_background("preview", Size::new(32, 32), ColorMode::Rgb, depth, Color::WHITE); - let layer = doc.layers[0].id; - doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 16, 32), &[0.0, 0.0, 0.0, 1.0]); - for (suffix, params) in [ - ("blur.boxBlur", json!({"radius":1})), - ("blur.motionBlur", json!({"distance":1})), - ("blur.surfaceBlur", json!({"radius":1})), - ("noise.median", json!({"radius":1})), - ("noise.dustAndScratches", json!({"radius":1})), - ("pixelate.mosaic", json!({"cellSize":2})), - ("stylize.emboss", json!({"height":1})), - ("other.minimum", json!({"radius":0.2})), - ("other.maximum", json!({"radius":0.2})), - ("distort.wave", json!({"wavelengthMin":1,"wavelengthMax":2,"amplitudeMin":1,"amplitudeMax":1})), - ] { - let command = format!("filter.{suffix}"); - for k in [2, 4] { - let proxy = crate::proxy::proxy_document(&doc, k); - let expected = preview_document(&proxy, Some(layer), &command, ¶ms, 1).unwrap(); - let out = preview_document(&doc, Some(layer), &command, ¶ms, k).unwrap_or_else(|| panic!("{command}: {depth:?}, proxy factor {k}")); - assert_eq!( - out.layers[0].surface().unwrap().read_region(proxy.bounds()), - expected.layers[0].surface().unwrap().read_region(proxy.bounds()), - "{command}: {depth:?}, proxy factor {k}" - ); - } - } - } - } - - /// A serde type error from numbers the dialog sends as JSON floats (`1.0`) for an integer - /// field ("invalid type: floating point `1.0`, expected u32"), as opposed to a legitimate - /// refusal such as "no selection" or "needs a map". - fn float_type_error(e: &str) -> bool { - e.contains("invalid type: floating point") - } - - /// #2501: every schema dialog, opened with its default fields and drawn once, runs its command - /// (OK) and its live preview without a type error from integer fields sent as floats. - #[test] - fn every_dialog_default_runs_without_float_type_errors() { - let ids: Vec<&str> = photocraft_engine::command_specs().iter().map(|c| c.id).filter(|id| has_dialog(id)).collect(); - assert!(ids.len() > 100, "{} dialogs", ids.len()); - let mut failures = Vec::new(); - for id in ids { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 24, "height": 24})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - let Some(dialog) = open(&mut app, id) else { continue }; - let mut f = app.ui.dialogs.iter().find(|d| d.id == dialog).unwrap().fields.clone(); - egui::Context::default().run_ui(Default::default(), |ui| body(ui, &mut f)).textures_delta.clear(); - let params = params_of(&f); - let st = app.session.active().unwrap(); - let (doc, active) = ((*st.doc).clone(), st.active_layer); - if let Err(e) = app.session.execute(id, params.clone()) { - let e = e.to_string(); - if float_type_error(&e) { - failures.push(format!("{id} OK {params}: {e}")); - } - } - // The preview swallows the error; rerun its params at full size to see it. - if preview_document(&doc, active, id, ¶ms, 1).is_none() { - let mut s = photocraft_engine::Session::new(); - s.add_document(doc, None); - if let Some(a) = active { - s.select_layer(a).unwrap(); - } - if let Err(e) = s.execute(id, params.clone()).map_err(|e| e.to_string()) - && float_type_error(&e) - { - failures.push(format!("{id} preview {params}: {e}")); - } - } - } - assert!(failures.is_empty(), "{failures:#?}"); - } - - #[test] - fn colour_params_parse_with_and_without_a_default() { - let p = parse_spec(r##"{"color":color=#ffffff,"vineColor":color,"bad":color=#zz}"##); - assert_eq!(p[0].kind, Kind::Color(Some([1.0, 1.0, 1.0]))); - assert_eq!(p[1].kind, Kind::Color(None)); - assert_eq!(p[2].kind, Kind::Color(None)); - } - - /// Color to Alpha (#1576): the dialog starts at white and the GIMP-style thresholds, drawing it - /// keeps those params, and its live preview makes the white of a Background transparent. - #[test] - fn color_to_alpha_dialog_defaults_draw_and_preview() { - const ID: &str = "filter.other.colorToAlpha"; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - let id = open(&mut app, ID).unwrap(); - let mut f = app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone(); - assert_eq!(f.get("__preview"), Some(&json!(true))); - let want = json!({"color": "#ffffff", "transparencyThreshold": 0.0, "opacityThreshold": 1.0}); - assert_eq!(params_of(&f), want); - egui::Context::default().run_ui(Default::default(), |ui| body(ui, &mut f)).textures_delta.clear(); - assert_eq!(params_of(&f), want, "drawing the dialog keeps its params"); - - let mut doc = Document::with_background( - "p", - photocraft_doc::Size::new(32, 32), - photocraft_doc::ColorMode::Rgb, - photocraft_doc::SampleType::U16, - photocraft_doc::Color::WHITE, - ); - let bg = doc.layers[0].id; - doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 8, 32), &[0.0, 0.0, 0.0, 1.0]); - for k in [1, 2] { - let out = preview_document(&doc, Some(bg), ID, &want, k).unwrap(); - let s = out.layers[0].surface().unwrap(); - assert_eq!(out.layers[0].name, "Layer 0", "k={k}"); - assert!(s.pixel(24 / k as i32, 4)[3] < 1e-3, "k={k}: white removed"); - assert_eq!(s.pixel(1, 4)[3], 1.0, "k={k}: black kept"); - } - } - - #[test] - fn preview_stays_inside_the_selection_at_every_proxy_factor() { - use photocraft_doc::SampleType; - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - let mut doc = - Document::with_background("p", photocraft_doc::Size::new(64, 64), photocraft_doc::ColorMode::Rgb, depth, photocraft_doc::Color::gray(0.5)); - let bg = doc.layers[0].id; - let mut sel = photocraft_raster::Surface::new(photocraft_doc::PixelFormat::GRAY8); - sel.fill_rect(photocraft_geom::Rect::new(0, 0, 32, 64), &[1.0]); - doc.selection = Some(sel); - for k in [1, 2, 4] { - let out = preview_document(&doc, Some(bg), "filter.noise.addNoise", &json!({"amount": 100.0}), k).unwrap(); - let s = out.layers[0].surface().unwrap(); - let half = 32 / k as i32; - let changed = |x0: i32, x1: i32| (0..64 / k as i32).any(|y| (x0..x1).any(|x| s.pixel(x, y) != doc.layers[0].surface().unwrap().pixel(0, 0))); - assert!(changed(0, half), "{depth:?} k={k}: noise inside the selection"); - assert!(!changed(half, 64 / k as i32), "{depth:?} k={k}: nothing outside the selection"); - } - } - } - - #[test] - fn define_pattern_asks_for_a_name() { - // Edit › Define Pattern… named the pattern after the document without asking ("ask", then - // "ask 2"). Photoshop's Pattern Name dialog starts from that name and lets you change it. - let spec = photocraft_engine::commands::find("edit.definePattern").unwrap(); - assert_eq!(parse_spec(spec.params), vec![Param { key: "name".into(), kind: Kind::Text }, Param { key: "rect".into(), kind: Kind::Json }]); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 8, "name": "ask.jpg"})).unwrap(); - let ctx = egui::Context::default(); - let define = |app: &mut PhotocraftApp, name: Option<&str>| { - crate::menus::invoke(app, &ctx, "edit.definePattern", Value::Null).unwrap(); - let d = app.ui.dialogs.last().expect("Define Pattern opens a dialog").clone(); - let shown = d.fields["name"].as_str().unwrap().to_string(); - if let Some(n) = name { - app.ui.dialog_mut(d.id).unwrap().fields.insert("name".into(), json!(n)); - } - crate::dialogs::confirm(app, d.id).unwrap(); - shown - }; - assert_eq!(define(&mut app, Some("Bricks")), "ask", "prefilled with the document's name"); - assert_eq!(define(&mut app, None), "ask", "Bricks didn't take it"); - assert_eq!(define(&mut app, None), "ask 2", "numbered past the library"); - let names: Vec<&str> = app.session.patterns.items.iter().map(|p| p.name.as_str()).collect(); - for n in ["Bricks", "ask", "ask 2"] { - assert!(names.contains(&n), "{n} in {names:?}"); - } - } - - #[test] - fn notes_after_a_spec_are_not_parameters() { - // A note after the object, like Selective Color's "(per-range [c,m,y,k] arrays: …)", was - // parsed as parameters: its commas split off junk fields and it glued itself onto the last - // one, so "reds":json became a number field the dialog showed and sent. - let p = parse_spec(r#"{"a":0..10=1,"b":json} (notes [x,y,z] here, and more) → {"c":id}"#); - assert_eq!(p, vec![Param { key: "a".into(), kind: Kind::Range { min: 0.0, max: 10.0, default: 1.0 } }, Param { key: "b".into(), kind: Kind::Json }]); - // Every command with a schema dialog has plain parameter keys. - for c in photocraft_engine::command_specs().iter().filter(|c| has_dialog(c.id)) { - for p in parse_spec(c.params) { - assert!(p.key.chars().all(|ch| ch.is_ascii_alphanumeric() || ch == '_'), "{}: junk parameter {:?}", c.id, p.key); - } - } - } - - #[test] - fn selective_color_dialog_ok_applies() { - // With the junk `reds: 0` the dialog's OK failed (`reds` must be an array of 4 numbers). - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - let id = open(&mut app, "image.adjustments.selectiveColor").unwrap(); - let fields = app.ui.dialogs.last().unwrap().fields.clone(); - assert!(fields.keys().all(|k| k.starts_with("__") || k.chars().all(|ch| ch.is_ascii_alphanumeric())), "{fields:?}"); - assert!(!fields.contains_key("reds"), "the per-range arrays are not dialog fields"); - app.ui.dialog_mut(id).unwrap().fields.insert("black".into(), json!(40.0)); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(app.session.journal.last().map(|j| j.0.as_str()), Some("image.adjustments.selectiveColor")); - } - - /// A filtered test image with structure at every scale (low-frequency waves plus a ramp). - fn waves(n: u32) -> Document { - let mut doc = Document::with_background( - "w", - photocraft_doc::Size::new(n, n), - photocraft_doc::ColorMode::Rgb, - photocraft_doc::SampleType::U8, - photocraft_doc::Color::WHITE, - ); - let s = doc.layers[0].surface_mut().unwrap(); - for y in 0..n as i32 { - for x in 0..n as i32 { - let v = 0.5 + 0.4 * (x as f32 / 23.0).sin() * (y as f32 / 31.0).cos(); - s.fill_rect(photocraft_geom::Rect::new(x, y, x + 1, y + 1), &[v, 1.0 - v, x as f32 / n as f32, 1.0]); - } - } - doc - } - - /// Mean absolute RGB difference of two documents, compared at 1/4 scale. - fn diff_at_quarter(a: &Document, b: &Document) -> f32 { - let quarter = |d: &Document| photocraft_compose::flatten(&crate::proxy::proxy_document(d, (d.size.width / 64).max(1))); - let (a, b) = (quarter(a), quarter(b)); - assert_eq!(a.px.len(), b.px.len()); - a.px.iter().zip(&b.px).map(|(p, q)| (0..3).map(|c| (p[c] - q[c]).abs()).sum::() / 3.0).sum::() / a.px.len() as f32 - } - - /// #2063: these filters drew their features in proxy pixels (noise, dots, dither, strokes, - /// kernels, scan lines, contour lines, streaks, depths, a tree's segments), so a 1/4 preview - /// showed them 4x larger than OK applied them. Their preview now runs at full resolution and - /// matches the applied result. Dust & Scratches (#3265) is the mirror image of those: a proxy - /// averages away the very specks the filter exists to remove, so its preview showed an - /// untouched image at a blocky scale. - #[test] - fn fixed_size_filters_preview_at_the_scale_they_apply() { - let doc = sharp(256); - let gray = grayscale(&doc); - let edge = json!([0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 4, -1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0]); - for (cmd, p) in [ - ("filter.distort.ripple", json!({"amount": 300.0, "size": "large"})), - ("filter.stylize.diffuse", json!({"mode": "normal"})), - ("filter.stylize.oilPaint", json!({})), - ("filter.render.flame", json!({})), - ("filter.render.fibers", json!({})), - ("filter.pixelate.mezzotint", json!({"type": "mediumDots"})), - ("filter.noise.addNoise", json!({"amount": 12.5})), - ("filter.noise.dustAndScratches", json!({"radius": 4.0, "threshold": 0.0})), - ("filter.noise.reduceNoise", json!({})), - ("filter.other.custom", json!({"kernel": edge})), - ("filter.video.deInterlace", json!({})), - ("filter.stylize.traceContour", json!({})), - ("filter.stylize.wind", json!({"method": "blast"})), - ("filter.stylize.extrude", json!({})), - ("filter.render.tree", json!({"baseTreeType": 1})), - ("filter.sharpen.sharpen", json!({})), - ("filter.sharpen.sharpenMore", json!({})), - ("filter.sharpen.sharpenEdges", json!({})), - ("filter.stylize.findEdges", json!({})), - ("filter.stylize.emboss", json!({})), - ("filter.noise.despeckle", json!({})), - ("filter.gallery.graphicPen", json!({})), - ("filter.gallery.stainedGlass", json!({"cellSize": 10})), - ("image.mode.indexedColor", json!({"colors": 16})), - ("image.mode.bitmap", json!({"method": "diffusion"})), - ] { - let doc = if cmd == "image.mode.bitmap" { &gray } else { &doc }; - let bg = doc.layers[0].id; - let applied = preview_document(doc, Some(bg), cmd, &p, 1).unwrap(); - let old = preview_document(doc, Some(bg), cmd, &p, 4).unwrap(); - assert!(diff_at_quarter(&applied, &old) > 0.005, "{cmd}: a 1/4 proxy differs from the result"); - let k = preview_factor(cmd, &p, 4); - assert_eq!(k, 1, "{cmd}"); - let shown = preview_document(doc, Some(bg), cmd, &p, k).unwrap(); - assert!(diff_at_quarter(&applied, &shown) < 1e-4, "{cmd}: the preview is what OK applies"); - } - // Without dithering, the colour-mode conversions keep the proxy. - assert_eq!(preview_factor("image.mode.indexedColor", &json!({"dither": "none"}), 4), 4); - assert_eq!(preview_factor("image.mode.bitmap", &json!({"method": "threshold"}), 4), 4); - } - - /// #6530: the Content-Aware Fill preview runs at full resolution, for every Sampling choice, - /// because its patch search finds different matches on a reduced copy. - #[test] - fn content_aware_fill_previews_at_full_resolution() { - for params in [json!({}), json!({"sampling": "auto"}), json!({"sampling": "rectangular"})] { - assert_eq!(preview_factor("edit.contentAwareFill", ¶ms, 4), 1, "{params}"); - } - } - - /// #2063: proxy previews scaled what isn't a length (Tree's canvas fraction, Lens Correction's - /// perspective), clamped negative lengths to +0.1 (Offset left/up), left Shadows/Highlights' - /// radii in document pixels and rounded Mosaic's 10 px cells to 3 proxy px (12 px). - #[test] - fn proxy_previews_scale_only_lengths() { - let doc = waves(256); - let bg = doc.layers[0].id; - let error = |cmd: &str, p: Value| { - let k = preview_factor(cmd, &p, 4); - let applied = preview_document(&doc, Some(bg), cmd, &p, 1).unwrap(); - let shown = preview_document(&doc, Some(bg), cmd, &p, k).unwrap(); - (k, mean_abs(&every_kth(&applied, k), &every_kth(&shown, 1))) - }; - for (cmd, p) in [ - ("filter.lensCorrection", json!({"vertical": -100.0, "horizontal": 60.0})), - ("filter.other.offset", json!({"horizontal": -40, "vertical": -24, "undefinedAreas": "wrap"})), - ( - "image.adjustments.shadowsHighlights", - json!({"shadowAmount": 50.0, "shadowRadius": 30.0, "highlightAmount": 50.0, "highlightRadius": 30.0, "blackClip": 0.0, "whiteClip": 0.0}), - ), - ] { - let (k, diff) = error(cmd, p); - assert_eq!(k, 4, "{cmd} keeps the proxy"); - assert!(diff < 0.01, "{cmd}: the preview shows what OK applies ({diff})"); - } - // Mosaic's cells divide evenly: 10 px at k = 2 is 5 proxy px; 40 px keeps k = 4. - assert_eq!(preview_factor("filter.pixelate.mosaic", &json!({"cellSize": 10.0}), 4), 2); - assert_eq!(preview_factor("filter.pixelate.mosaic", &json!({"cellSize": 40.0}), 4), 4); - assert_eq!(preview_factor("filter.pixelate.mosaic", &json!({"cellSize": 7.0}), 4), 1); - assert_eq!(preview_factor("filter.pixelate.mosaic", &json!({"cellSize": "x"}), 4), 4); - let (k, diff) = error("filter.pixelate.mosaic", json!({"cellSize": 10.0})); - assert!(k == 2 && diff < 0.01, "Mosaic: {diff}"); - // Tree's and Picture Frame's sizes are relative, not pixels (and not shown as "px"). - assert!(!is_pixel_param_of("filter.render.tree", "size") && !is_pixel_param_of("filter.render.pictureFrame", "size")); - assert!(is_pixel_param_of("filter.stylize.extrude", "size")); - } - - /// #218: Warp Text renders the type again from the layer model, which a reduced proxy doesn't - /// scale: the preview showed the text k times too large. It is the full-size result, reduced. - #[test] - fn warp_text_preview_matches_the_full_size_result_on_a_reduced_proxy() { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 4000, "height": 3000})).unwrap(); - s.execute("type.create", json!({"x": 300, "y": 1600, "text": "Warp", "size": 400})).unwrap(); - let st = s.active().unwrap(); - let (doc, layer) = ((*st.doc).clone(), st.active_layer.unwrap()); - let p = json!({"style": "arc", "bend": 40.0}); - let k = preview_factor("type.warpText", &p, crate::proxy::preview_factor(&doc, true)); - assert!(k > 1, "the preview runs on a reduced proxy"); - let cache = |d: &Document| match &d.layer(layer).unwrap().content { - photocraft_doc::LayerContent::Text(t) => t.cache.clone().unwrap(), - _ => panic!("a type layer"), - }; - let full = crate::proxy::proxy_document(&preview_document(&doc, Some(layer), "type.warpText", &p, 1).unwrap(), k); - let shown = preview_document(&doc, Some(layer), "type.warpText", &p, k).unwrap(); - assert_eq!(shown.size, full.size); - assert_eq!(cache(&shown).content_bounds(), cache(&full).content_bounds()); - assert_eq!(photocraft_compose::flatten(&shown).px, photocraft_compose::flatten(&full).px); - } - - /// #5766: Curves on a smart object adds a smart filter, which re-renders the source through - /// the object's placement. On a reduced proxy that placement stayed in full-size document - /// coordinates, so the preview showed the object `k` times too large until OK. - #[test] - fn smart_object_curves_preview_keeps_its_size_on_a_reduced_proxy() { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 16, "y": 16, "width": 16, "height": 16})).unwrap(); - s.execute("edit.fill", json!({"contents": "black"})).unwrap(); - s.execute("select.deselect", json!({})).unwrap(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let st = s.active().unwrap(); - let (doc, layer) = ((*st.doc).clone(), st.active_layer.unwrap()); - let alpha = |d: &Document, x: i32, y: i32| match &d.layer(layer).unwrap().content { - photocraft_doc::LayerContent::Smart(sm) => sm.cache.as_ref().unwrap().pixel(x, y).last().copied().unwrap(), - _ => panic!("a smart object"), - }; - let k = 4; - let params = json!({"points": [[0, 20], [90, 150], [255, 230]]}); - let shown = preview_document(&doc, Some(layer), "image.adjustments.curves", ¶ms, k).unwrap(); - let full = preview_document(&doc, Some(layer), "image.adjustments.curves", ¶ms, 1).unwrap(); - let photocraft_doc::LayerContent::Smart(full_sm) = &full.layer(layer).unwrap().content else { panic!("a smart object") }; - let reference = photocraft_algo::resample::resize_surface(full_sm.cache.as_ref().unwrap(), 0.25, 0.25, photocraft_algo::resample::Resample::Bicubic); - let photocraft_doc::LayerContent::Smart(sm) = &shown.layer(layer).unwrap().content else { panic!("a smart object") }; - assert_eq!(sm.smart_filters.len(), 1, "the preview adds the Curves smart filter"); - assert_eq!(shown.size, crate::proxy::proxy_document(&doc, k).size); - // The 16 px square at (16, 16) is a 4 px square at (4, 4) on the proxy, not 16 px at (16, 16). - // Bicubic reduction blends the square's boundary with transparency; compare all alpha - // values with a reduced full-size result, and require opacity only in the interior. - for y in 0..shown.size.height as i32 { - for x in 0..shown.size.width as i32 { - let expected = reference.pixel(x, y).last().copied().unwrap(); - let actual = alpha(&shown, x, y); - assert!((actual - expected).abs() <= 1.0 / 255.0, "({x}, {y}): alpha {actual}, expected {expected}"); - } - } - for (x, y) in [(5, 5), (5, 6), (6, 6)] { - assert!(alpha(&shown, x, y) > 0.99, "({x}, {y}) is inside the reduced square"); - } - for (x, y) in [(4, 4), (7, 7)] { - assert!(alpha(&shown, x, y) > 0.5, "({x}, {y}) is a corner of the reduced square"); - } - for (x, y) in [(2, 2), (9, 9), (12, 12), (15, 15)] { - assert!(alpha(&shown, x, y) < 0.01, "({x}, {y}) is outside the reduced square"); - } - } - - /// #2063: a pixel-sized parameter divided by the proxy factor was clamped to the command's - /// minimum (Pointillize's 5 px cells became 3 px proxy cells = 12 px), so the preview factor - /// drops until every pixel-sized value fits its range. - #[test] - fn proxy_previews_never_clamp_pixel_sized_params() { - let pointillize = |c: f64| preview_factor("filter.pixelate.pointillize", &json!({"cellSize": c}), 4); - assert_eq!((pointillize(5.0), pointillize(7.0), pointillize(12.0), pointillize(300.0)), (1, 2, 4, 4)); - assert_eq!(preview_factor("filter.pixelate.crystallize", &json!({"cellSize": 10.0}), 4), 3); - assert_eq!(preview_factor("filter.pixelate.colorHalftone", &json!({"maxRadius": 8.0}), 4), 2); - assert_eq!(preview_factor("filter.blur.gaussianBlur", &json!({"radius": 8.0}), 4), 4, "unclamped filters keep the proxy"); - // Hostile params never panic and leave the factor alone; a full-size document stays at 1. - assert_eq!(preview_factor("filter.pixelate.pointillize", &json!({"cellSize": "x"}), 4), 4); - assert_eq!(preview_factor("filter.pixelate.pointillize", &json!(null), 4), 4); - assert_eq!(preview_factor("no.such.command", &json!({"cellSize": 1.0}), 4), 4); - assert_eq!(preview_factor("filter.pixelate.pointillize", &json!({"cellSize": 5.0}), 0), 1); - // Every previewed command, at each pixel-sized param's minimum, default and in between. - let previewed = photocraft_engine::command_specs().iter().filter(|c| has_dialog(c.id) && (c.id.starts_with("filter.") || PREVIEWED.contains(&c.id))); - for c in previewed { - for p in parse_spec(c.params) { - let Kind::Range { min, default, .. } = p.kind else { continue }; - if min <= 0.0 || !is_pixel_param_of(c.id, &p.key) { - continue; - } - for v in [f64::from(min), f64::from(default), f64::from(min) * 2.5] { - let k = preview_factor(c.id, &json!({ p.key.clone(): v }), 4); - assert!(v / f64::from(k) >= f64::from(min) - 1e-9, "{} {}={v}: k={k} clamps to {min}", c.id, p.key); - } - } - } - } - - /// Sharp structure at every scale: [`waves`] with hard squares from 2 to 32 px, a fine - /// per-pixel texture and an interlaced band (odd rows inverted) at the bottom. - fn sharp(n: u32) -> Document { - let mut doc = waves(n); - let s = doc.layers[0].surface_mut().unwrap(); - let mut x0 = 4; - for (i, size) in [2, 3, 4, 6, 8, 12, 16, 24, 32].into_iter().enumerate() { - for y0 in (4..n as i32 * 3 / 4 - size).step_by((size * 3) as usize) { - let v = if (i + y0 as usize / 7).is_multiple_of(2) { 0.05 } else { 0.95 }; - s.fill_rect(photocraft_geom::Rect::new(x0, y0, x0 + size, y0 + size), &[v, v * 0.8, 1.0 - v, 1.0]); - } - x0 += size + 6; - } - for y in 0..n as i32 { - for x in 0..n as i32 { - let mut px = s.pixel(x, y); - if (x * 7 + y * 13) % 5 == 0 { - px.iter_mut().take(3).for_each(|c| *c = (*c + 0.08).min(1.0)); - } - if y >= n as i32 * 3 / 4 && y % 2 == 1 { - px[0] = 1.0 - px[0]; - } - s.fill_rect(photocraft_geom::Rect::new(x, y, x + 1, y + 1), &px); - } - } - doc - } - - /// [`waves`] with strong per-pixel noise, the input of noise reduction. - fn noisy(n: u32) -> Document { - let mut doc = waves(n); - let s = doc.layers[0].surface_mut().unwrap(); - let hash = |x: i32, y: i32| ((x as u32).wrapping_mul(73_856_093) ^ (y as u32).wrapping_mul(19_349_663)).wrapping_mul(2_654_435_761) >> 8; - for y in 0..n as i32 { - for x in 0..n as i32 { - let mut px = s.pixel(x, y); - for (c, v) in px.iter_mut().take(3).enumerate() { - *v = (*v + (hash(x * 3 + c as i32, y) as f32 / (1u32 << 24) as f32 - 0.5) * 0.3).clamp(0.0, 1.0); - } - s.fill_rect(photocraft_geom::Rect::new(x, y, x + 1, y + 1), &px); - } - } - doc - } - - /// How a preview at factor `k` compares with what OK applies (factor 1) on a document. - #[derive(Debug)] - struct PreviewError { - /// Mean absolute RGB difference at the pixels the proxy samples. - diff: f32, - /// Feature scale of the preview shown at document size, relative to the result: 1 when - /// the features match, 1/k when the preview draws them k times too large. - scale: f32, - /// How much the preview changes the image relative to how much OK does (sampled); NaN - /// when OK barely changes it. - change: f32, - } - - /// Mean absolute difference of neighbouring pixels at the document's own resolution. - fn detail(d: &Document) -> f32 { - let b = photocraft_compose::flatten(d); - let w = b.rect.width() as usize; - let mut sum = 0.0; - for (i, p) in b.px.iter().enumerate() { - for q in [b.px.get(i + 1).filter(|_| (i + 1) % w != 0), b.px.get(i + w)].into_iter().flatten() { - sum += (0..3).map(|c| (p[c] - q[c]).abs()).sum::() / 3.0; - } - } - sum / b.px.len().max(1) as f32 - } - - /// Pixels of `d` at every `k`-th row and column: the document pixels a factor-`k` proxy - /// samples, so a preview at `k` compares with them one to one. - fn every_kth(d: &Document, k: u32) -> Vec<[f32; 4]> { - let b = photocraft_compose::flatten(d); - let w = b.rect.width() as usize; - let k = k as usize; - let h = b.px.len() / w.max(1); - (0..h.div_ceil(k)) - .flat_map(|y| (0..w.div_ceil(k)).map(move |x| (x * k, y * k))) - .map(|(x, y)| b.px.get(y * w + x).copied().unwrap_or([f32::NAN; 4])) - .collect() - } - - fn mean_abs(a: &[[f32; 4]], b: &[[f32; 4]]) -> f32 { - a.iter().zip(b).map(|(p, q)| (0..3).map(|c| (p[c] - q[c]).abs()).sum::() / 3.0).sum::() / a.len().max(1) as f32 - } - - /// `None` when the command can't run on `doc` at all (e.g. Displace without a map). - fn preview_error(doc: &Document, command: &str, p: &Value, k: u32) -> Option { - let bg = doc.layers[0].id; - let applied = preview_document(doc, Some(bg), command, p, 1)?; - let shown = preview_document(doc, Some(bg), command, p, k).unwrap_or_else(|| panic!("{command} {p}: the k = {k} preview failed")); - let (a, s) = (every_kth(&applied, k), every_kth(&shown, 1)); - let (src, src_k) = (every_kth(doc, k), every_kth(&crate::proxy::proxy_document(doc, k), 1)); - let applied_change = mean_abs(&a, &src); - Some(PreviewError { - diff: mean_abs(&a, &s), - scale: detail(&shown) / k as f32 / detail(&applied).max(1e-5), - change: if applied_change > 0.01 { mean_abs(&s, &src_k) / applied_change } else { f32::NAN }, - }) - } - - /// The parameter sets to preview `command` with: the dialog's defaults, and each pixel-sized - /// value at its minimum and at a large value (whole numbers as integers: Tree and Picture - /// Frame read some ranges as `u32`). - fn sweep_params(app: &mut PhotocraftApp, command: &str) -> Vec<(String, Value)> { - let Some(id) = open(app, command) else { return Vec::new() }; - let base = params_of(&app.ui.dialog_mut(id).unwrap().fields); - let mut out = vec![("default".to_string(), base.clone())]; - for p in parse_spec(photocraft_engine::commands::find(command).unwrap().params) { - if !is_pixel_param_of(command, &p.key) { - continue; - } - let values = match p.kind { - Kind::Int { .. } => vec![-40.0, 40.0], - Kind::Range { min, max, default } => [min, (default * 4.0).clamp(min, max.min(64.0))].into_iter().filter(|v| *v != default).collect(), - _ => continue, - }; - for v in values { - let mut q = base.clone(); - q[p.key.as_str()] = json!(v); - out.push((format!("{}={v}", p.key), q)); - } - } - for (_, p) in &mut out { - for v in p.as_object_mut().into_iter().flat_map(|o| o.values_mut()) { - if let Some(x) = v.as_f64().filter(|x| x.fract() == 0.0 && x.abs() < 1e9) { - *v = json!(x as i64); - } - } - } - out - } - - /// Every previewed command with its parameter sets. - fn previewed_cases() -> Vec<(&'static str, String, Value)> { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ids: Vec<&'static str> = photocraft_engine::command_specs() - .iter() - .map(|c| c.id) - .filter(|id| has_dialog(id) && (id.starts_with("filter.") || PREVIEWED.contains(id))) - .collect(); - ids.into_iter().flat_map(|id| sweep_params(&mut app, id).into_iter().map(move |(label, p)| (id, label, p))).collect() - } - - fn grayscale(d: &Document) -> Document { - let mut s = photocraft_engine::Session::new(); - s.add_document(d.clone(), None); - s.execute("image.mode.grayscale", json!({})).unwrap(); - s.active().map(|d| (*d.doc).clone()).unwrap() - } - - /// Smooth, sharp and noisy test images, each in RGB and grayscale (for the modes that need it). - fn test_images(n: u32) -> [(&'static str, Document, Document); 3] { - let with_gray = |d: Document| (grayscale(&d), d); - let ((ws, w), (ss, s), (ns, no)) = (with_gray(waves(n)), with_gray(sharp(n)), with_gray(noisy(n))); - [("smooth", w, ws), ("sharp", s, ss), ("noisy", no, ns)] - } - - fn image_for<'a>(command: &str, rgb: &'a Document, gray: &'a Document) -> &'a Document { - if command == "image.mode.bitmap" || command == "image.mode.duotone" { gray } else { rgb } - } - - /// Previews that only approximate the result at a proxy although their features have the - /// right size: dots and cells placed on the proxy's pixel grid (Color Halftone, Pointillize) - /// and tile edges resampled (Tiles). Two more only differ on a proxy as small as this test's - /// (64 x 64 px): Picture Frame's minimum line widths, and Shadows/Highlights' 0.01 % black and - /// white clips, which pick single pixels out of 4096 (its radii are checked in - /// `proxy_previews_scale_only_lengths`). - const APPROXIMATE_AT_PROXY: &[&str] = &[ - "filter.pixelate.colorHalftone", - "filter.pixelate.pointillize", - "filter.stylize.tiles", - "filter.render.pictureFrame", - "image.adjustments.shadowsHighlights", - ]; - - /// Why a preview doesn't show what OK applies, if it doesn't: a clearly different result or - /// features at another size on the smooth image, or (on the sharp and noisy images, where a - /// sub-pixel radius can't show on a proxy) a filter that acts more strongly in the preview, - /// i.e. over a k times larger area. - fn mismatch(image: &str, e: &PreviewError) -> Option { - let off = if image == "smooth" { e.diff > 0.03 || (!(0.6..=1.6).contains(&e.scale) && e.diff > 0.002) } else { e.change > 1.25 }; - off.then(|| format!("{e:?}")) - } - - /// #2063, every previewed command: the live preview at the factor [`preview_factor`] picks - /// for a 1/4 proxy shows what OK applies: the same features at the same size, on smooth, - /// sharp and noisy images, at the defaults and at small and large pixel sizes. - #[test] - fn every_preview_shows_what_ok_applies() { - let cases: Vec<_> = previewed_cases().into_iter().filter(|(id, _, p)| preview_factor(id, p, 4) > 1 && !APPROXIMATE_AT_PROXY.contains(id)).collect(); - // One thread per test image: about 270 filter runs at 256 x 256. - let bad: Vec = std::thread::scope(|scope| { - let runs: Vec<_> = test_images(256) - .into_iter() - .map(|(image, rgb, gray)| { - let cases = &cases; - scope.spawn(move || { - let mut bad = Vec::new(); - for (id, label, p) in cases { - let k = preview_factor(id, p, 4); - if let Some(why) = preview_error(image_for(id, &rgb, &gray), id, p, k).and_then(|e| mismatch(image, &e)) { - bad.push(format!("{id} ({label}) at k = {k} on the {image} image: {why}")); - } - } - bad - }) - }) - .collect(); - runs.into_iter().flat_map(|r| r.join().unwrap()).collect() - }); - assert!(bad.is_empty(), "previews that differ from the result:\n{}", bad.join("\n")); - } - - /// The table behind [`every_preview_shows_what_ok_applies`]: every previewed command at a - /// plain 1/4 proxy and at its chosen factor, on each test image. - /// `cargo test -p photocraft-ui-egui --lib filter_dialog::tests::sweep_all_previews -- --ignored --nocapture` - #[test] - #[ignore] - fn sweep_all_previews() { - let images = test_images(256); - println!("command | params | image | k | diff k=4 | scale k=4 | change k=4 | diff k | scale k | change k"); - for (id, label, p) in previewed_cases() { - let k = preview_factor(id, &p, 4); - for (image, rgb, gray) in &images { - let doc = image_for(id, rgb, gray); - match (preview_error(doc, id, &p, 4), preview_error(doc, id, &p, k)) { - (Some(a), Some(b)) => println!( - "{id} | {label} | {image} | {k} | {:.4} | {:.2} | {:.2} | {:.4} | {:.2} | {:.2}", - a.diff, a.scale, a.change, b.diff, b.scale, b.change - ), - _ => println!("{id} | {label} | {image} | {k} | fails"), - } - } - } - } - - /// The profiles Assign Profile offers for a new document converted with `mode` (if any), - /// and which of the command's built-in profiles the command itself accepts for it. - fn assign_profile_offers(mode: Option<&str>) -> (Vec, Vec) { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - if let Some(mode) = mode { - app.run(mode, json!({})).unwrap(); - } - open(&mut app, "edit.assignProfile").unwrap(); - let offered: Vec = - app.ui.dialogs.last().unwrap().fields["__profiles"].as_array().unwrap().iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(); - let spec = photocraft_engine::commands::find("edit.assignProfile").unwrap(); - let builtin = parse_spec(spec.params).into_iter().find(|p| p.key == "profile").unwrap(); - let Kind::Choice { options, .. } = builtin.kind else { panic!("profile is a menu") }; - let accepted = options.into_iter().filter(|name| app.session.execute("edit.assignProfile", json!({"profile": name})).is_ok()).collect(); - (offered, accepted) - } - - /// #4951: Assign Profile lists the profiles the command accepts for the document's colour - /// mode, and none of the others. - #[test] - fn assign_profile_offers_only_profiles_of_the_documents_colour_mode() { - for mode in [None, Some("image.mode.cmyk"), Some("image.mode.grayscale")] { - let (offered, accepted) = assign_profile_offers(mode); - for name in &accepted { - assert!(offered.contains(name), "{mode:?}: {name} can be assigned, so it is offered"); - } - for name in ["srgb", "coated-cmyk", "sgray"] { - assert_eq!(offered.iter().any(|o| o == name), accepted.iter().any(|a| a == name), "{mode:?}: {name}"); - } - assert!(offered.iter().any(|o| o == "working") && offered.iter().any(|o| o == "none"), "{mode:?}: working space and none always fit"); - } - let (rgb, _) = assign_profile_offers(None); - assert!(rgb.iter().any(|o| o == "srgb") && !rgb.iter().any(|o| o == "coated-cmyk"), "an RGB document gets RGB profiles"); - let (cmyk, _) = assign_profile_offers(Some("image.mode.cmyk")); - assert!(cmyk.iter().any(|o| o == "coated-cmyk") && !cmyk.iter().any(|o| o == "srgb"), "a CMYK document gets CMYK profiles"); - } - - /// #4951: a profile remembered from a document of another colour mode isn't preselected. - #[test] - fn assign_profile_drops_a_remembered_profile_that_does_not_fit() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - app.session.prefs.edit(|prefs| { - prefs.dialogs.insert("edit.assignProfile".into(), json!({"profile": "coated-cmyk"})); - }); - open(&mut app, "edit.assignProfile").unwrap(); - assert_eq!(app.ui.dialogs.last().unwrap().fields["profile"], json!("working")); - app.session.prefs.edit(|prefs| { - prefs.dialogs.insert("edit.assignProfile".into(), json!({"profile": "display-p3"})); - }); - open(&mut app, "edit.assignProfile").unwrap(); - assert_eq!(app.ui.dialogs.last().unwrap().fields["profile"], json!("display-p3"), "one that fits is kept"); - } - - #[test] - fn schema_dialogs_respect_explicit_dropdown_defaults() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - - // 1. Radial Blur has explicit default "good", not the first option ("draft"). - open(&mut app, "filter.blur.radialBlur").unwrap(); - let fields = &app.ui.dialogs.last().unwrap().fields; - assert_eq!(fields["quality"], json!("good"), "Radial Blur must select explicit default 'good'"); - assert_eq!(fields["method"], json!("spin"), "Radial Blur method has no explicit default, retains first option"); - let params = params_of(fields); - assert_eq!(params["quality"], json!("good")); - - // 2. Convert to Profile has explicit default "relative", not first option ("perceptual"). - open(&mut app, "edit.convertToProfile").unwrap(); - let fields = &app.ui.dialogs.last().unwrap().fields; - assert_eq!(fields["intent"], json!("relative"), "Convert to Profile must select explicit default 'relative'"); - let params = params_of(fields); - assert_eq!(params["intent"], json!("relative")); - - // 3. Proof Setup has explicit default "relative". - open(&mut app, "view.proofSetup").unwrap(); - let fields = &app.ui.dialogs.last().unwrap().fields; - assert_eq!(fields["intent"], json!("relative"), "Proof Setup must select explicit default 'relative'"); - let params = params_of(fields); - assert_eq!(params["intent"], json!("relative")); - - // 4. Remembered values still override initial defaults. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.prefs.edit(|prefs| { - prefs.dialogs.insert("filter.blur.radialBlur".into(), json!({"quality": "best"})); - }); - open(&mut app, "filter.blur.radialBlur").unwrap(); - let fields = &app.ui.dialogs.last().unwrap().fields; - assert_eq!(fields["quality"], json!("best"), "Remembered choice must override explicit default"); - - // 5. Explicit default that is the first option (e.g. "cw" in arbitrary rotation). - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - open(&mut app, "image.rotation.arbitrary").unwrap(); - let fields = &app.ui.dialogs.last().unwrap().fields; - assert_eq!(fields["direction"], json!("cw"), "Explicit default matching first option is preserved"); - } - - /// #4143: Replace Color shows the From colour (defaulting to the foreground) and its canvas - /// eyedropper samples the merged image into the dialog. - #[test] - fn replace_color_eyedropper_samples_the_image() { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16, "background": "#00ff00"})).unwrap(); - let mut app = PhotocraftApp::new(s, crate::Services::default()); - app.run("tools.setColors", json!({"foreground": "#ff0000"})).unwrap(); - let id = open(&mut app, REPLACE_COLOR).unwrap(); - assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#ff0000"), "the dialog starts from the foreground colour"); - // #6279: armed as it opens, so the first click on the image samples. - assert!(color_eyedropper_armed(&app)); - assert!(color_eyedropper_sample(&mut app, 4.0, 4.0)); - assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#00ff00")); - // #4457: where it was picked, for Localized Color Clusters. - assert_eq!(app.ui.dialogs.last().unwrap().fields["points"], json!([[4.0, 4.0]])); - // Off-image: the click is consumed, nothing changes and the eyedropper stays armed. - assert!(color_eyedropper_sample(&mut app, -1.0, 4.0)); - assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#00ff00")); - assert!(color_eyedropper_armed(&app)); - // Disarmed, the dialog never claims the click. - app.ui.dialog_mut(id).unwrap().fields.insert(COLOR_EYEDROPPER.into(), json!(false)); - assert!(!color_eyedropper_armed(&app)); - assert!(!color_eyedropper_sample(&mut app, 4.0, 4.0)); - } - - /// #4143: the eyedropper button disarms and re-arms the canvas picker (#6279: it opens armed). - #[test] - fn replace_color_dialog_arms_the_eyedropper_button() { - use egui_kittest::Harness; - use egui_kittest::kittest::Queryable; - - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); - let mut app = PhotocraftApp::new(s, crate::Services::default()); - let mut h = Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - open(h.state_mut(), REPLACE_COLOR).unwrap(); - h.run_steps(3); - assert!(color_eyedropper_armed(h.state()), "armed as the dialog opens"); - h.get_by_label("Pick Color From Image").click(); - h.run_steps(2); - assert!(!color_eyedropper_armed(h.state())); - h.get_by_label("Pick Color From Image").click(); - h.run_steps(2); - assert!(color_eyedropper_armed(h.state())); - } - - /// #6278: the Result swatch shows the sampled colour after the shift, and a colour picked for - /// it sets Hue, Saturation and Lightness so the sampled colour becomes it. - #[test] - fn replace_color_result_swatch_sets_the_sliders() { - use egui_kittest::Harness; - use egui_kittest::kittest::Queryable; - - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); - let mut app = PhotocraftApp::new(s, crate::Services::default()); - app.run("tools.setColors", json!({"foreground": "#cc3333"})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(900.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - let id = open(h.state_mut(), REPLACE_COLOR).unwrap(); - h.run_steps(3); - // No shift yet: the Result is the sampled colour. - assert_eq!(h.get_all_by_label("#cc3333").count(), 2, "the sampled colour and the Result both read #cc3333"); - h.get_by_role_and_label(egui::accesskit::Role::ColorWell, "Result").click(); - h.run_steps(3); - let picker = h.state().ui.dialogs.last().unwrap(); - assert_ne!(picker.id, id, "the Color Picker opened over the dialog"); - assert_eq!(picker.fields["color"], json!("#cc3333"), "on the current Result"); - let picker = picker.id; - h.state_mut().ui.dialog_mut(picker).unwrap().fields.insert("color".into(), json!("#3355cc")); - crate::dialogs::confirm(h.state_mut(), picker).unwrap(); - h.state_mut().ui.dialogs.retain(|d| d.id != picker); - h.run_steps(3); - let f = h.state_mut().ui.dialog_mut(id).unwrap().fields.clone(); - let n = |k: &str| f[k].as_f64().unwrap() as f32; - let got = photocraft_algo::tone::replace_color_result([0.8, 0.2, 0.2], n("hue"), n("saturation"), n("lightness")); - let want = crate::color_picker_ui::parse_hex("#3355cc").unwrap(); - assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.02), "the sliders turn the sampled colour into the pick: {got:?}"); - assert!(n("hue") != 0.0, "the hue moved"); - // Moving a slider afterwards is not mistaken for another pick. - h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("lightness".into(), json!(10.0)); - h.run_steps(2); - assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields["lightness"], json!(10.0)); - } - - /// #4457: Localized Color Clusters and its Range, as in Photoshop's dialog; the sampled point - /// and both settings reach the command. - #[test] - fn replace_color_localized_color_clusters() { - use egui_kittest::Harness; - use egui_kittest::kittest::Queryable; - - // Left half red, right half red too: localized on the left point, the right half stays. - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 40, "height": 10, "background": "#ff0000"})).unwrap(); - let mut app = PhotocraftApp::new(s, crate::Services::default()); - let mut h = Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - let id = open(h.state_mut(), REPLACE_COLOR).unwrap(); - h.run_steps(3); - let _ = h.get_by_label("Localized Color Clusters"); - h.state_mut().ui.dialog_mut(id).unwrap().fields.insert(COLOR_EYEDROPPER.into(), json!(true)); - assert!(color_eyedropper_sample(h.state_mut(), 2.0, 5.0)); - h.get_by_label("Localized Color Clusters").click(); - h.run_steps(2); - let f = h.state().ui.dialogs.last().unwrap().fields.clone(); - assert_eq!((f["localized"].clone(), f["points"].clone()), (json!(true), json!([[2.0, 5.0]]))); - // The command with the dialog's fields, small range and a hue shift: only near (2, 5). - let mut p: Map = f.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); - p.insert("range".into(), json!(10)); - p.insert("hue".into(), json!(120)); - h.state_mut().run(REPLACE_COLOR, Value::Object(p)).unwrap(); - let doc = &h.state().session.active().unwrap().doc; - let px = |x: i32| doc.layers[0].surface().unwrap().read_region(photocraft_geom::Rect::new(x, 5, x + 1, 6)); - 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)); - } -} +mod tests; diff --git a/crates/ui-egui/src/filter_dialog/tests.rs b/crates/ui-egui/src/filter_dialog/tests.rs new file mode 100644 index 0000000000..ce2f77025d --- /dev/null +++ b/crates/ui-egui/src/filter_dialog/tests.rs @@ -0,0 +1,1551 @@ +use super::*; + +#[test] +fn a_unit_after_a_range_bound_does_not_reset_the_range_to_its_fallback() { + // #7598: `0.5..5000 px?` fell back to a maximum of 100, so the Mixer Brush's Size slider + // (and every range documented with a px or % suffix) topped out at 100. + let range = |spec: &str| match parse_spec(spec).into_iter().next().map(|p| p.kind) { + Some(Kind::Range { min, max, default }) => (min, max, default), + other => panic!("{spec}: {other:?}"), + }; + assert_eq!(range(r#"{"size":0.5..5000 px?}"#), (0.5, 5000.0, 0.5)); + assert_eq!(range(r#"{"scale":1..1000 %=100}"#), (1.0, 1000.0, 100.0)); + assert_eq!(range(r#"{"tolerance":0.5..10 px=2}"#), (0.5, 10.0, 2.0)); + assert_eq!(range(r#"{"angle":-180..180}"#), (-180.0, 180.0, -180.0)); + assert_eq!(range(r#"{"radius":0.1..1000=1}"#), (0.1, 1000.0, 1.0)); + assert_eq!(range(r#"{"gain":1e-3..2e2}"#), (0.001, 200.0, 0.001)); + // A bound that is no number at all still takes the old fallback rather than failing. + assert_eq!(range(r#"{"x":0..many}"#), (0.0, 100.0, 0.0)); + // The documented specs of the real commands read their full ranges. + let spec = photocraft_engine::commands::find("paint.pencil").expect("paint.pencil is registered"); + let size = parse_spec(spec.params).into_iter().find(|p| p.key == "size"); + assert!(matches!(size.map(|p| p.kind), Some(Kind::Range { max, .. }) if max == 5000.0)); +} + +#[test] +fn color_settings_working_spaces_list_installed_profiles_of_their_space() { + // #6323: a press condition installed in the system can be the CMYK working space, as in + // Photoshop's Color Settings; each working-space menu lists only profiles of its space. + use photocraft_cms::{ColorSpace, ProfileClass}; + let p = |path: &str, class, color_space| InstalledProfile { path: path.into(), description: path.to_uppercase(), class, color_space }; + let installed = [ + p("gracol.icc", ProfileClass::Output, ColorSpace::Cmyk), + p("monitor.icc", ProfileClass::Display, ColorSpace::Rgb), + p("printer-rgb.icc", ProfileClass::Output, ColorSpace::Rgb), + p("scanner.icc", ProfileClass::Input, ColorSpace::Rgb), + p("gray.icc", ProfileClass::Output, ColorSpace::Gray), + p("link.icc", ProfileClass::DeviceLink, ColorSpace::Cmyk), + ]; + let paths = |key: &str| installed_choices("edit.colorSettings", key, &installed).into_iter().map(|(path, _)| path).collect::>(); + assert_eq!(paths("workingCmyk"), ["gracol.icc"]); + assert_eq!(paths("workingRgb"), ["monitor.icc"]); + assert_eq!(paths("workingGray"), ["gray.icc"]); + assert!(paths("policyCmyk").is_empty() && paths("intent").is_empty()); + assert_eq!(installed_choices("edit.colorSettings", "workingCmyk", &installed)[0].1, "GRACOL.ICC", "listed by description"); + // The profile dialogs keep listing every destination profile. + assert_eq!(installed_choices("edit.convertToProfile", "profile", &installed).len(), 5); + assert!(installed_choices("filter.blur.gaussianBlur", "profile", &installed).is_empty()); +} + +/// #5710: the seed field's Random button always gives a different seed the field can hold. +#[test] +fn random_seeds_stay_in_range_and_change() { + let mut seen = std::collections::HashSet::new(); + for i in 0..200u64 { + let s = random_seed(i, 7); + assert!((0..=30_000).contains(&s), "{s}"); + assert_ne!(s, 7, "a click always changes the seed"); + seen.insert(s); + } + assert!(seen.len() > 100, "seeds spread out: {}", seen.len()); + assert_ne!(random_seed(1, 30_000), 30_000); + // Every seed dialog shows the button: Clouds, Add Noise and the like carry a `seed` param. + let specs = photocraft_engine::command_specs(); + assert!( + specs + .iter() + .filter(|c| c.id.starts_with("filter.")) + .any(|c| parse_spec(c.params).iter().any(|p| p.key == "seed" && matches!(p.kind, Kind::Int { .. }))) + ); +} + +/// Preset names such as "iPhone 14 Pro Max" (the artboard dialog's choices) are text, not +/// camelCase keys: they used to read "I Phone 14 Pro Max". +#[test] +fn display_names_are_not_split_like_camel_case_keys() { + assert_eq!(source_label("iPhone 14 Pro Max"), "iPhone 14 Pro Max"); + assert_eq!(source_label("Web 1920"), "Web 1920"); + assert_eq!(source_label("centerX"), "Center X"); +} + +/// Convert to Profile's and Proof Setup's `bpc` read "Bpc": spelled out. +#[test] +fn black_point_compensation_is_spelled_out() { + assert_eq!(source_label("bpc"), "Black Point Compensation"); +} + +fn key() -> FilterPreviewKey { + FilterPreviewKey { + doc: photocraft_doc::DocId(7), + revision: 11, + dialog: 3, + active: Some(photocraft_doc::LayerId(2)), + target: Default::default(), + command: "filter.blur.gaussianBlur".into(), + params: json!({"radius": 4.0}), + k: 1, + } +} + +#[test] +fn same_target_ignores_parameters_but_nothing_else() { + // A drag only changes the parameters, and that must not hide the finished frame. + let base = key(); + let mut moved = base.clone(); + moved.params = json!({"radius": 40.0}); + assert!(base.same_target(&moved)); + assert!(moved.same_target(&base)); + + // Anything else names a different preview and must not be shown. + for break_it in [ + |k: &mut FilterPreviewKey| k.doc = photocraft_doc::DocId(8), + |k: &mut FilterPreviewKey| k.revision = 12, + |k: &mut FilterPreviewKey| k.dialog = 4, + |k: &mut FilterPreviewKey| k.active = Some(photocraft_doc::LayerId(5)), + |k: &mut FilterPreviewKey| k.active = None, + |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, + ] { + let mut other = base.clone(); + break_it(&mut other); + assert!(!other.same_target(&base), "{other:?} must not pass as {base:?}"); + assert!(!base.same_target(&other)); + } +} + +#[test] +fn only_direction_angles_get_the_dial() { + // Every listed command still has a degree `angle` range, so the list cannot go stale. + for cmd in ANGLE_DIAL { + let spec = photocraft_engine::commands::find(cmd).unwrap_or_else(|| panic!("{cmd} is not a command")).params; + assert!( + parse_spec(spec).iter().any(|p| p.key == "angle" && matches!(p.kind, Kind::Range { min, max, .. } if min >= -360.0 && max <= 360.0)), + "{cmd} has no angle range" + ); + assert!(uses_angle_dial(cmd, "angle")); + assert!(!uses_angle_dial(cmd, "distance")); + } + // Rotation amounts and angles with another zero keep their slider. + for cmd in + ["filter.distort.twirl", "image.rotation.arbitrary", "image.crop", "filter.blurGallery.tiltShift", "filter.lensCorrection", "filter.render.flame"] + { + assert!(!uses_angle_dial(cmd, "angle"), "{cmd}"); + } +} + +#[test] +fn restores_only_valid_previous_filter_choices() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.prefs.edit(|prefs| { + prefs.dialogs.insert("filter.blur.gaussianBlur".into(), json!({"radius": 11.0, "bogus": 42})); + }); + open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let fields = &app.ui.dialogs.last().unwrap().fields; + assert_eq!(fields["radius"], json!(11.0)); + assert!(!fields.contains_key("bogus")); + + // A changed registry range, corrupt preference or stale path is never restored. + let mut fields = Map::new(); + fields.insert("radius".into(), json!(2.0)); + restore_remembered(&app, "filter.blur.gaussianBlur", r#"{"radius":0.1..5=1}"#, &mut fields); + assert_eq!(fields["radius"], json!(2.0)); +} + +#[test] +fn alt_reset_restores_schema_defaults_not_remembered() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.prefs.edit(|prefs| { + prefs.dialogs.insert("filter.blur.gaussianBlur".into(), json!({"radius": 11.0})); + }); + let id = open(&mut app, "filter.blur.gaussianBlur").unwrap(); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["radius"], json!(11.0)); + let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone(); + reset_fields(&app, &mut fields); + app.ui.dialog_mut(id).unwrap().fields = fields; + let f = &app.ui.dialog_mut(id).unwrap().fields; + // Registry default for gaussian blur radius is 1. + assert_eq!(f["radius"], json!(1.0)); + assert!(f.contains_key("__filter")); + assert!(app.ui.dialogs.iter().any(|d| d.id == id)); +} + +/// #5806: OK in Displace with no map asks for the map file, as Photoshop does, and displaces +/// with the chosen file; Cancel in the picker applies nothing; a map already given runs at once. +#[test] +fn displace_asks_for_its_map_after_ok() { + let dir = std::env::temp_dir().join(format!("photocraft-displace-map-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let map = dir.join("map.png"); + let mut m = photocraft_engine::Session::new(); + m.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); + std::fs::write(&map, photocraft_io::export(&m.active().unwrap().doc, "map.png", &Default::default()).unwrap().bytes).unwrap(); + let answers = vec![Some(crate::file_dialog::FileDialogAnswer::Paths(vec![map.to_string_lossy().into_owned()])), None]; + let (show, asked) = crate::file_dialog::fake(answers); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { file_dialog: Some(show), ..Default::default() }); + app.run("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 16})).unwrap(); + app.run("edit.fill", json!({"color": "#000000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let steps = app.session.active().unwrap().history.past_len(); + let ctx = egui::Context::default(); + let id = open(&mut app, "filter.distort.displace").unwrap(); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert!(app.file_dialog_open(), "OK leaves the map picker pending"); + // Another document activated while the picker is open is left alone. + app.run("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); + let other_steps = app.session.documents()[1].history.past_len(); + // The frame shows the picker (the service is asked then) and acts on its answer. + app.poll_file_dialog(&ctx, None); + assert_eq!(asked.borrow().len(), 1, "OK asks for the map"); + assert_eq!(app.session.active_index(), Some(0), "the document that asked is shown"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1, "Displace ran with the chosen map"); + assert_eq!(app.session.documents()[1].history.past_len(), other_steps, "not on the other document"); + // Cancelled: nothing is applied. + let id = open(&mut app, "filter.distort.displace").unwrap(); + crate::dialogs::confirm(&mut app, id).unwrap(); + app.poll_file_dialog(&ctx, None); + assert_eq!(asked.borrow().len(), 2); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); + // A map given in the dialog runs without asking. + assert!(!needs_displace_map("filter.distort.displace", &json!({"mapPath": "/maps/x.psd"}))); + assert!(!needs_displace_map("filter.distort.displace", &json!({"mapDocument": 0}))); + assert!(needs_displace_map("filter.distort.displace", &json!({"mapDocument": -1, "mapPath": " "}))); + assert!(!needs_displace_map("filter.blur.gaussianBlur", &json!({}))); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn remembering_dialogs_never_persists_paths_or_document_indices() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let mut fields = Map::new(); + fields.insert("__filter".into(), json!(true)); + fields.insert("radius".into(), json!(7.0)); + fields.insert("mapPath".into(), json!("/private/file")); + fields.insert("document".into(), json!(5)); + remember(&mut app, "filter.blur.gaussianBlur", &fields); + let saved = &app.session.prefs().dialogs["filter.blur.gaussianBlur"]; + assert_eq!(saved["radius"], json!(7.0)); + assert!(saved.get("mapPath").is_none()); + assert!(saved.get("document").is_none()); +} + +#[test] +fn parses_registry_notation() { + let p = parse_spec(r#"{"radius":0.1..1000=1,"method":"spin|zoom","monochromatic":bool,"seed":u32=0,"horizontal":px=0}"#); + assert_eq!(p[0], Param { key: "radius".into(), kind: Kind::Range { min: 0.1, max: 1000.0, default: 1.0 } }); + assert_eq!(p[1].kind, Kind::Choice { options: vec!["spin".into(), "zoom".into()], default: None }); + assert_eq!(p[2].kind, Kind::Bool(false)); + assert_eq!(p[3].kind, Kind::Int { default: 0 }); + assert_eq!(p[4].kind, Kind::Int { default: 0 }); + assert!(parse_spec("{}").is_empty()); + let p_choice = parse_spec(r#"{"quality":"draft|good|best"="good"}"#); + assert_eq!(p_choice[0].kind, Kind::Choice { options: vec!["draft".into(), "good".into(), "best".into()], default: Some("good".into()) }); + let p = parse_spec(r#"{"lighting":bool=true,"kernel":int[25],"pins":json,"points":[[0,0],[1,0]],"mapPath":text,"mapDocument":doc,"scale":1..9999=1}"#); + let kinds: Vec<&Kind> = p.iter().map(|p| &p.kind).collect(); + assert_eq!( + kinds, + [&Kind::Bool(true), &Kind::Grid(25), &Kind::Json, &Kind::Json, &Kind::Text, &Kind::Document, &Kind::Range { min: 1.0, max: 9999.0, default: 1.0 }] + ); +} + +/// A layer-id param has no number field: drawing the Auto-Align dialog used to write +/// `reference: 0` back, which the engine rejects as not a selected layer (#674). +#[test] +fn layer_id_params_stay_out_of_the_dialog() { + let mut f = Map::new(); + f.insert("__command".into(), json!("edit.autoAlignLayers")); + egui::Context::default().run_ui(Default::default(), |ui| body(ui, &mut f)).textures_delta.clear(); + assert!(!params_of(&f).as_object().unwrap().contains_key("reference"), "{f:?}"); +} + +/// Layer › Layer Style › Global Light (#3054): Global Light dialog opens with the active +/// document's current shared lighting, preserving it on unchanged OK, ignoring stale +/// remembered dialog values, tracking document switching, applying edits, and leaving the +/// document unchanged on Cancel. +#[test] +fn global_light_dialog_reflects_active_document_light() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let doc1_id = app.session.active().unwrap().doc.id; + + // 0. Default-document control: fresh document starts at angle 120 and altitude 30. + let d_default = crate::menus::invoke(&mut app, &ctx, "layer.layerStyle.globalLight", Value::Null).unwrap()["dialog"].as_u64().unwrap(); + assert_eq!(app.ui.dialog_mut(d_default).unwrap().fields["angle"], json!(120.0)); + assert_eq!(app.ui.dialog_mut(d_default).unwrap().fields["altitude"], json!(30.0)); + crate::dialogs::confirm(&mut app, d_default).unwrap(); + assert_eq!(app.session.active().unwrap().doc.global_light.angle, 120.0); + assert_eq!(app.session.active().unwrap().doc.global_light.altitude, 30.0); + + // 1. Change document's global light to 30 degrees angle and 45 degrees altitude. + app.run("layer.layerStyle.globalLight", json!({"angle": 30.0, "altitude": 45.0})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.global_light.angle, 30.0); + assert_eq!(app.session.active().unwrap().doc.global_light.altitude, 45.0); + + // 2. Open Global Light dialog: opens with the active document's light (30 / 45). + let d_id = crate::menus::invoke(&mut app, &ctx, "layer.layerStyle.globalLight", Value::Null).unwrap()["dialog"].as_u64().unwrap(); + let fields = &app.ui.dialog_mut(d_id).unwrap().fields; + assert_eq!(fields["angle"], json!(30.0)); + assert_eq!(fields["altitude"], json!(45.0)); + + // 3. Unchanged OK preserves the document's light. + crate::dialogs::confirm(&mut app, d_id).unwrap(); + let gl = app.session.active().unwrap().doc.global_light; + assert_eq!(gl.angle, 30.0); + assert_eq!(gl.altitude, 45.0); + + // 4. Stale remembered values do not override the active document. + app.session.prefs.edit(|prefs| { + prefs.dialogs.insert( + "layer.layerStyle.globalLight".into(), + json!({ + "angle": 75.0, + "altitude": 60.0, + }), + ); + }); + let d_id = open(&mut app, "layer.layerStyle.globalLight").unwrap(); + let fields = &app.ui.dialog_mut(d_id).unwrap().fields; + assert_eq!(fields["angle"], json!(30.0), "reads active document, not remembered"); + assert_eq!(fields["altitude"], json!(45.0)); + + // 5. Cancel preserves the document's light. + app.ui.close_dialog(d_id); + let gl = app.session.active().unwrap().doc.global_light; + assert_eq!(gl.angle, 30.0); + assert_eq!(gl.altitude, 45.0); + + // 6. Multiple documents: each document initializes the dialog to its own light. + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let doc2_id = app.session.active().unwrap().doc.id; + assert_ne!(doc1_id, doc2_id); + app.run("layer.layerStyle.globalLight", json!({"angle": -45.0, "altitude": 15.0})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.global_light.angle, -45.0); + assert_eq!(app.session.active().unwrap().doc.global_light.altitude, 15.0); + + let d_id2 = open(&mut app, "layer.layerStyle.globalLight").unwrap(); + let fields2 = &app.ui.dialog_mut(d_id2).unwrap().fields; + assert_eq!(fields2["angle"], json!(-45.0)); + assert_eq!(fields2["altitude"], json!(15.0)); + app.ui.close_dialog(d_id2); + + // Switch back to doc1: dialog still reflects doc1's light (30 / 45). + assert!(app.session.set_active(0)); + let d_id1 = open(&mut app, "layer.layerStyle.globalLight").unwrap(); + assert_eq!(app.ui.dialog_mut(d_id1).unwrap().fields["angle"], json!(30.0)); + assert_eq!(app.ui.dialog_mut(d_id1).unwrap().fields["altitude"], json!(45.0)); + + // 7. Modifying the dialog updates the active document. + app.ui.dialog_mut(d_id1).unwrap().fields.insert("angle".into(), json!(-60.0)); + app.ui.dialog_mut(d_id1).unwrap().fields.insert("altitude".into(), json!(20.0)); + crate::dialogs::confirm(&mut app, d_id1).unwrap(); + assert_eq!(app.session.active().unwrap().doc.global_light.angle, -60.0); + assert_eq!(app.session.active().unwrap().doc.global_light.altitude, 20.0); + + // Switch to doc2: doc2 is untouched (-45 / 15). + assert!(app.session.set_active(1)); + assert_eq!(app.session.active().unwrap().doc.global_light.angle, -45.0); + assert_eq!(app.session.active().unwrap().doc.global_light.altitude, 15.0); +} + +/// View › Proof Setup (#3055): Custom Proof Setup opens with the active document's current +/// proof condition, preserving it on unchanged OK, ignoring stale remembered dialog values, +/// tracking document switching, applying edits, and leaving the document unchanged on Cancel. +#[test] +fn proof_setup_dialog_reflects_active_document_proof_condition() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let doc1_id = app.session.active().unwrap().doc.id; + + // 0. A fresh document defaults to working-cmyk. + let d_fresh = crate::menus::invoke(&mut app, &ctx, "view.proofSetup.custom", Value::Null).unwrap()["dialog"].as_u64().unwrap(); + assert_eq!(app.ui.dialog_mut(d_fresh).unwrap().fields["profile"], json!("working-cmyk")); + crate::dialogs::confirm(&mut app, d_fresh).unwrap(); + assert_eq!(app.session.color.proof(doc1_id).setup.name, "working-cmyk"); + + // 1. Preset sets sRGB and turns Proof Colors on. + crate::menus::invoke(&mut app, &ctx, "view.proofSetup.internetStandardRgb", Value::Null).unwrap(); + assert_eq!(app.session.color.proof(doc1_id).setup.name, "srgb"); + assert!(app.session.color.proof(doc1_id).enabled); + + // 2. Open Custom Proof Setup: starts with the active document's condition (sRGB). + let d_id = crate::menus::invoke(&mut app, &ctx, "view.proofSetup.custom", Value::Null).unwrap()["dialog"].as_u64().unwrap(); + let fields = &app.ui.dialog_mut(d_id).unwrap().fields; + assert_eq!(fields["profile"], json!("srgb")); + assert_eq!(fields["intent"], json!("relative")); + assert_eq!(fields["bpc"], json!(true)); + assert_eq!(fields["simulatePaper"], json!(false)); + + // 3. Unchanged OK preserves the document's condition and leaves Proof Colors enabled. + crate::dialogs::confirm(&mut app, d_id).unwrap(); + let pv = app.session.color.proof(doc1_id); + assert_eq!(pv.setup.name, "srgb"); + assert!(pv.enabled); + + // 4. Stale remembered values do not override the active document. + app.session.prefs.edit(|prefs| { + prefs.dialogs.insert( + "view.proofSetup".into(), + json!({ + "profile": "display-p3", + "intent": "perceptual", + "bpc": false, + "simulatePaper": true, + }), + ); + }); + let d_id = open(&mut app, "view.proofSetup").unwrap(); + let fields = &app.ui.dialog_mut(d_id).unwrap().fields; + assert_eq!(fields["profile"], json!("srgb"), "reads active document, not remembered"); + assert_eq!(fields["intent"], json!("relative")); + assert_eq!(fields["bpc"], json!(true)); + assert_eq!(fields["simulatePaper"], json!(false)); + + // 5. Cancel preserves the document. + app.ui.close_dialog(d_id); + assert_eq!(app.session.color.proof(doc1_id).setup.name, "srgb"); + + // 6. Multiple documents: each document initializes the dialog to its own condition. + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let doc2_id = app.session.active().unwrap().doc.id; + assert_ne!(doc1_id, doc2_id); + app.run("view.proofSetup", json!({"profile": "display-p3", "intent": "perceptual", "bpc": false, "simulatePaper": true})).unwrap(); + assert_eq!(app.session.color.proof(doc2_id).setup.name, "display-p3"); + + let d_id2 = open(&mut app, "view.proofSetup").unwrap(); + let fields2 = &app.ui.dialog_mut(d_id2).unwrap().fields; + assert_eq!(fields2["profile"], json!("display-p3")); + assert_eq!(fields2["intent"], json!("perceptual")); + assert_eq!(fields2["bpc"], json!(false)); + assert_eq!(fields2["simulatePaper"], json!(true)); + app.ui.close_dialog(d_id2); + + // Switch back to doc1: dialog still reflects doc1's sRGB. + assert!(app.session.set_active(0)); + let d_id1 = open(&mut app, "view.proofSetup").unwrap(); + assert_eq!(app.ui.dialog_mut(d_id1).unwrap().fields["profile"], json!("srgb")); + + // 7. Modifying the dialog updates the active document. + app.ui.dialog_mut(d_id1).unwrap().fields.insert("profile".into(), json!("adobe-rgb-compat")); + crate::dialogs::confirm(&mut app, d_id1).unwrap(); + assert_eq!(app.session.color.proof(doc1_id).setup.name, "adobe-rgb-compat"); + // doc2 is untouched + assert_eq!(app.session.color.proof(doc2_id).setup.name, "display-p3"); +} + +#[test] +fn indexed_counts_are_integer_json_while_dither_amounts_keep_their_decimals() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + open(&mut app, "image.mode.indexedColor").unwrap(); + let mut defaults = app.ui.dialogs.first().unwrap().fields.clone(); + let before = params_of(&defaults)["colors"].clone(); + egui::Context::default().run_ui(Default::default(), |ui| body(ui, &mut defaults)).textures_delta.clear(); + assert_eq!(before.as_u64(), Some(256)); + assert_eq!(params_of(&defaults)["colors"], before, "opening a preview must not schedule a second job just to normalize its count"); + let mut fields = Map::new(); + fields.insert("__command".into(), json!("image.mode.indexedColor")); + fields.insert("colors".into(), json!(17)); + fields.insert("amount".into(), json!(37.5)); + egui::Context::default().run_ui(Default::default(), |ui| body(ui, &mut fields)).textures_delta.clear(); + let params = params_of(&fields); + assert_eq!(params["colors"].as_u64(), Some(17)); + assert_eq!(params["amount"].as_f64(), Some(37.5)); +} + +/// #7400: Lens Blur's Source lists the document's alpha channels, by name, each choosable even +/// when two share a name; `depthChannel` is set through that menu, not shown as a field, and +/// like the other references it isn't remembered, so a remembered `channel` source opens as None. +#[test] +fn lens_blur_source_lists_the_alpha_channels() { + let spec = photocraft_engine::commands::find(LENS_BLUR).unwrap().params; + let params = parse_spec(spec); + assert!(params.iter().any(|p| p.key == "depthChannel" && p.kind == Kind::Json), "depthChannel is no dialog field"); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 20, "height": 10})).unwrap(); + app.run("channel.new", json!({"name": "Depth Map", "fill": "white"})).unwrap(); + let id = open(&mut app, LENS_BLUR).unwrap(); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["__channels"], json!(["Depth Map"])); + // The menu's values are channel indices, so two channels with one name are both choosable. + app.run("channel.new", json!({"name": "Depth Map", "fill": "black"})).unwrap(); + let id = open(&mut app, LENS_BLUR).unwrap(); + let names: Vec = serde_json::from_value(app.ui.dialog_mut(id).unwrap().fields["__channels"].clone()).unwrap(); + assert_eq!(names, ["Depth Map", "Depth Map"]); + assert_eq!((channel_choice(0), channel_choice(1)), ("channel:0".to_string(), "channel:1".to_string())); + assert_eq!(channel_index(&json!(1), &names), Some(1), "the second one by its index"); + assert_eq!(channel_index(&json!("Depth Map"), &names), Some(0), "a name is the first so named, as the engine reads it"); + assert_eq!(channel_index(&json!(2), &names), None); + + app.session.prefs.edit(|p| { + p.dialogs.insert(LENS_BLUR.into(), json!({"depthMap": "channel", "depthChannel": "Depth Map"})); + }); + let id = open(&mut app, LENS_BLUR).unwrap(); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!(f["depthMap"], "none", "no channel was remembered with it"); + assert!(f.get("depthChannel").is_none()); +} + +#[test] +fn wide_positive_ranges_use_the_logarithmic_slider_path() { + assert!(uses_logarithmic_slider(0.1, 1000.0), "Gaussian Blur radius"); + assert!(uses_logarithmic_slider(1.0, 9999.0)); + assert!(!uses_logarithmic_slider(1.0, 500.0)); + assert!(!uses_logarithmic_slider(0.0, 1000.0)); +} + +#[test] +fn new_filters_have_dialogs_or_run_directly() { + for id in [ + "filter.stylize.oilPaint", + "filter.blur.lensBlur", + "filter.blurGallery.irisBlur", + "filter.other.custom", + "filter.distort.displace", + "filter.pixelate.mezzotint", + "filter.render.lightingEffects", + "filter.render.relight", + "filter.other.colorToAlpha", + ] { + assert!(has_dialog(id), "{id}"); + } + for id in ["filter.pixelate.facet", "filter.pixelate.fragment", "filter.video.ntscColors"] { + assert!(!has_dialog(id), "{id}"); + } +} + +#[test] +fn every_filter_command_spec_parses() { + for c in photocraft_engine::command_specs().iter().filter(|c| c.id.starts_with("filter.")) { + let _ = parse_spec(c.params); + } + assert!(has_dialog("filter.blur.gaussianBlur")); + assert!(!has_dialog("filter.stylize.findEdges")); +} + +/// Select and Mask's Output To lists all six output targets. +#[test] +fn select_and_mask_output_lists_all_six_targets() { + let spec = photocraft_engine::commands::find("select.refineEdge").unwrap().params; + let p = parse_spec(spec).into_iter().find(|p| p.key == "output").unwrap(); + let Kind::Choice { options: choices, .. } = p.kind else { panic!("output is not a choice") }; + let labels: Vec = choices.iter().map(|c| source_label(c)).collect(); + assert_eq!(labels, ["Selection", "Layer Mask", "New Layer", "New Layer With Mask", "New Document", "New Document With Mask"]); +} + +#[test] +fn preview_runs_engine_command_on_proxy() { + let mut doc = Document::with_background( + "p", + photocraft_doc::Size::new(64, 64), + photocraft_doc::ColorMode::Rgb, + photocraft_doc::SampleType::U8, + photocraft_doc::Color::WHITE, + ); + let bg = doc.layers[0].id; + doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 32, 64), &[0.0, 0.0, 0.0, 1.0]); + let out = preview_document(&doc, Some(bg), "filter.blur.gaussianBlur", &json!({"radius": 4.0}), 1).unwrap(); + let p = out.layers[0].surface().unwrap().pixel(32, 32); + assert!(p[0] > 0.2 && p[0] < 0.8, "edge blurred: {p:?}"); + assert_eq!(label("wavelengthMin"), "Wavelength Min"); +} + +/// #7423 (review on #7799): re-editing a Displace smart filter and picking another open +/// document as its map previews with that document, as OK applies it. The preview session held +/// only the edited document, and the map's `mapDocument` sits inside the filter's `params`. +#[test] +fn smart_displace_preview_uses_the_map_document() { + let mut s = photocraft_engine::Session::new(); + // Documents 0 and 1: a white and a black map, opened before the edited one. + s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "black"})).unwrap(); + s.execute("file.new", json!({"width": 48, "height": 32, "background": "transparent"})).unwrap(); + s.edit("square", |doc, active| { + let fmt = doc.pixel_format(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(photocraft_geom::Rect::new(10, 10, 20, 12), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + Ok(()) + }) + .unwrap(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("filter.distort.displace", json!({"horizontal": 10, "vertical": 0, "mapDocument": 0})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let layer = s.active().unwrap().active_layer; + let documents: Vec<_> = s.documents().iter().map(|d| d.doc.clone()).collect(); + for map in [1, 0] { + let p = json!({"index": 0, "params": {"mapDocument": map}}); + let mut applied = photocraft_engine::Session::new(); + for d in &documents { + applied.add_document((**d).clone(), None); + } + applied.execute(SMART_FILTER_SET_PARAMS, p.clone()).unwrap(); + let want = photocraft_compose::render(&applied.active().unwrap().doc, doc.bounds()).px; + let preview = preview_document_for_target( + &doc, + layer, + SMART_FILTER_SET_PARAMS, + &p, + 1, + None, + photocraft_engine::channel_cmds::ChannelTarget::Composite, + &documents, + &ColorSettings::default(), + ) + .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"); + } +} + +/// Match Color's preview reads the Source document from the open documents, as OK does: the +/// preview session held only the edited document, so a Source showed no change (#4851). +#[test] +fn match_color_preview_uses_the_source_document() { + use photocraft_doc::{Color, ColorMode, SampleType, Size}; + let solid = |name: &str, c: [f32; 4]| { + let mut d = Document::with_background(name, Size::new(32, 32), ColorMode::Rgb, SampleType::U8, Color::WHITE); + d.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 32, 32), &c); + d.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 16, 32), &[c[0] * 0.5, c[1] * 0.5, c[2] * 0.5, 1.0]); + d + }; + // The source document is open before the edited one, so indices differ between sessions. + let mut s = photocraft_engine::Session::new(); + s.add_document(solid("reference", [0.1, 0.3, 0.9, 1.0]), None); + s.add_document(solid("texture", [0.9, 0.5, 0.2, 1.0]), None); + let doc = s.active().unwrap().doc.clone(); + let layer = doc.layers[0].id; + let documents: Vec<_> = s.documents().iter().map(|d| d.doc.clone()).collect(); + for (source, label) in [(0, "another document"), (1, "the edited document itself")] { + let p = json!({"source": source}); + let mut applied = photocraft_engine::Session::new(); + for d in &documents { + applied.add_document((**d).clone(), None); + } + applied.execute("image.adjustments.matchColor", p.clone()).unwrap(); + let want = applied.active().unwrap().doc.layers[0].surface().unwrap().pixel(24, 16); + let preview = preview_document_for_target( + &doc, + Some(layer), + "image.adjustments.matchColor", + &p, + 1, + None, + photocraft_engine::channel_cmds::ChannelTarget::Composite, + &documents, + &ColorSettings::default(), + ) + .unwrap_or_else(|| panic!("{label}: no preview")); + let got = preview.layers[0].surface().unwrap().pixel(24, 16); + assert!((0..3).all(|c| (got[c] - want[c]).abs() < 1.0 / 255.0 + 1e-4), "{label}: preview {got:?}, OK gives {want:?}"); + } + // The preview is of the matched image: the orange texture took the reference's blue. + let preview = preview_document_for_target( + &doc, + Some(layer), + "image.adjustments.matchColor", + &json!({"source": 0}), + 2, + None, + photocraft_engine::channel_cmds::ChannelTarget::Composite, + &documents, + &ColorSettings::default(), + ) + .unwrap(); + let px = preview.layers[0].surface().unwrap().pixel(12, 8); + assert!(px[2] > px[0], "proxy preview matched to the reference: {px:?}"); +} + +#[test] +fn core_filter_previews_keep_minimum_settings_after_downsampling() { + use photocraft_doc::{Color, ColorMode, SampleType, Size}; + use photocraft_geom::Rect; + + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut doc = Document::with_background("preview", Size::new(32, 32), ColorMode::Rgb, depth, Color::WHITE); + let layer = doc.layers[0].id; + doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 16, 32), &[0.0, 0.0, 0.0, 1.0]); + for (suffix, params) in [ + ("blur.boxBlur", json!({"radius":1})), + ("blur.motionBlur", json!({"distance":1})), + ("blur.surfaceBlur", json!({"radius":1})), + ("noise.median", json!({"radius":1})), + ("noise.dustAndScratches", json!({"radius":1})), + ("pixelate.mosaic", json!({"cellSize":2})), + ("stylize.emboss", json!({"height":1})), + ("other.minimum", json!({"radius":0.2})), + ("other.maximum", json!({"radius":0.2})), + ("distort.wave", json!({"wavelengthMin":1,"wavelengthMax":2,"amplitudeMin":1,"amplitudeMax":1})), + ] { + let command = format!("filter.{suffix}"); + for k in [2, 4] { + let proxy = crate::proxy::proxy_document(&doc, k); + let expected = preview_document(&proxy, Some(layer), &command, ¶ms, 1).unwrap(); + let out = preview_document(&doc, Some(layer), &command, ¶ms, k).unwrap_or_else(|| panic!("{command}: {depth:?}, proxy factor {k}")); + assert_eq!( + out.layers[0].surface().unwrap().read_region(proxy.bounds()), + expected.layers[0].surface().unwrap().read_region(proxy.bounds()), + "{command}: {depth:?}, proxy factor {k}" + ); + } + } + } +} + +/// A serde type error from numbers the dialog sends as JSON floats (`1.0`) for an integer +/// field ("invalid type: floating point `1.0`, expected u32"), as opposed to a legitimate +/// refusal such as "no selection" or "needs a map". +fn float_type_error(e: &str) -> bool { + e.contains("invalid type: floating point") +} + +/// #2501: every schema dialog, opened with its default fields and drawn once, runs its command +/// (OK) and its live preview without a type error from integer fields sent as floats. +#[test] +fn every_dialog_default_runs_without_float_type_errors() { + let ids: Vec<&str> = photocraft_engine::command_specs().iter().map(|c| c.id).filter(|id| has_dialog(id)).collect(); + assert!(ids.len() > 100, "{} dialogs", ids.len()); + let mut failures = Vec::new(); + for id in ids { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 24, "height": 24})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let Some(dialog) = open(&mut app, id) else { continue }; + let mut f = app.ui.dialogs.iter().find(|d| d.id == dialog).unwrap().fields.clone(); + egui::Context::default().run_ui(Default::default(), |ui| body(ui, &mut f)).textures_delta.clear(); + let params = params_of(&f); + let st = app.session.active().unwrap(); + let (doc, active) = ((*st.doc).clone(), st.active_layer); + if let Err(e) = app.session.execute(id, params.clone()) { + let e = e.to_string(); + if float_type_error(&e) { + failures.push(format!("{id} OK {params}: {e}")); + } + } + // The preview swallows the error; rerun its params at full size to see it. + if preview_document(&doc, active, id, ¶ms, 1).is_none() { + let mut s = photocraft_engine::Session::new(); + s.add_document(doc, None); + if let Some(a) = active { + s.select_layer(a).unwrap(); + } + if let Err(e) = s.execute(id, params.clone()).map_err(|e| e.to_string()) + && float_type_error(&e) + { + failures.push(format!("{id} preview {params}: {e}")); + } + } + } + assert!(failures.is_empty(), "{failures:#?}"); +} + +#[test] +fn colour_params_parse_with_and_without_a_default() { + let p = parse_spec(r##"{"color":color=#ffffff,"vineColor":color,"bad":color=#zz}"##); + assert_eq!(p[0].kind, Kind::Color(Some([1.0, 1.0, 1.0]))); + assert_eq!(p[1].kind, Kind::Color(None)); + assert_eq!(p[2].kind, Kind::Color(None)); +} + +/// Color to Alpha (#1576): the dialog starts at white and the GIMP-style thresholds, drawing it +/// keeps those params, and its live preview makes the white of a Background transparent. +#[test] +fn color_to_alpha_dialog_defaults_draw_and_preview() { + const ID: &str = "filter.other.colorToAlpha"; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + let id = open(&mut app, ID).unwrap(); + let mut f = app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone(); + assert_eq!(f.get("__preview"), Some(&json!(true))); + let want = json!({"color": "#ffffff", "transparencyThreshold": 0.0, "opacityThreshold": 1.0}); + assert_eq!(params_of(&f), want); + egui::Context::default().run_ui(Default::default(), |ui| body(ui, &mut f)).textures_delta.clear(); + assert_eq!(params_of(&f), want, "drawing the dialog keeps its params"); + + let mut doc = Document::with_background( + "p", + photocraft_doc::Size::new(32, 32), + photocraft_doc::ColorMode::Rgb, + photocraft_doc::SampleType::U16, + photocraft_doc::Color::WHITE, + ); + let bg = doc.layers[0].id; + doc.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 8, 32), &[0.0, 0.0, 0.0, 1.0]); + for k in [1, 2] { + let out = preview_document(&doc, Some(bg), ID, &want, k).unwrap(); + let s = out.layers[0].surface().unwrap(); + assert_eq!(out.layers[0].name, "Layer 0", "k={k}"); + assert!(s.pixel(24 / k as i32, 4)[3] < 1e-3, "k={k}: white removed"); + assert_eq!(s.pixel(1, 4)[3], 1.0, "k={k}: black kept"); + } +} + +#[test] +fn preview_stays_inside_the_selection_at_every_proxy_factor() { + use photocraft_doc::SampleType; + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut doc = + Document::with_background("p", photocraft_doc::Size::new(64, 64), photocraft_doc::ColorMode::Rgb, depth, photocraft_doc::Color::gray(0.5)); + let bg = doc.layers[0].id; + let mut sel = photocraft_raster::Surface::new(photocraft_doc::PixelFormat::GRAY8); + sel.fill_rect(photocraft_geom::Rect::new(0, 0, 32, 64), &[1.0]); + doc.selection = Some(sel); + for k in [1, 2, 4] { + let out = preview_document(&doc, Some(bg), "filter.noise.addNoise", &json!({"amount": 100.0}), k).unwrap(); + let s = out.layers[0].surface().unwrap(); + let half = 32 / k as i32; + let changed = |x0: i32, x1: i32| (0..64 / k as i32).any(|y| (x0..x1).any(|x| s.pixel(x, y) != doc.layers[0].surface().unwrap().pixel(0, 0))); + assert!(changed(0, half), "{depth:?} k={k}: noise inside the selection"); + assert!(!changed(half, 64 / k as i32), "{depth:?} k={k}: nothing outside the selection"); + } + } +} + +#[test] +fn define_pattern_asks_for_a_name() { + // Edit › Define Pattern… named the pattern after the document without asking ("ask", then + // "ask 2"). Photoshop's Pattern Name dialog starts from that name and lets you change it. + let spec = photocraft_engine::commands::find("edit.definePattern").unwrap(); + assert_eq!(parse_spec(spec.params), vec![Param { key: "name".into(), kind: Kind::Text }, Param { key: "rect".into(), kind: Kind::Json }]); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8, "name": "ask.jpg"})).unwrap(); + let ctx = egui::Context::default(); + let define = |app: &mut PhotocraftApp, name: Option<&str>| { + crate::menus::invoke(app, &ctx, "edit.definePattern", Value::Null).unwrap(); + let d = app.ui.dialogs.last().expect("Define Pattern opens a dialog").clone(); + let shown = d.fields["name"].as_str().unwrap().to_string(); + if let Some(n) = name { + app.ui.dialog_mut(d.id).unwrap().fields.insert("name".into(), json!(n)); + } + crate::dialogs::confirm(app, d.id).unwrap(); + shown + }; + assert_eq!(define(&mut app, Some("Bricks")), "ask", "prefilled with the document's name"); + assert_eq!(define(&mut app, None), "ask", "Bricks didn't take it"); + assert_eq!(define(&mut app, None), "ask 2", "numbered past the library"); + let names: Vec<&str> = app.session.patterns.items.iter().map(|p| p.name.as_str()).collect(); + for n in ["Bricks", "ask", "ask 2"] { + assert!(names.contains(&n), "{n} in {names:?}"); + } +} + +#[test] +fn notes_after_a_spec_are_not_parameters() { + // A note after the object, like Selective Color's "(per-range [c,m,y,k] arrays: …)", was + // parsed as parameters: its commas split off junk fields and it glued itself onto the last + // one, so "reds":json became a number field the dialog showed and sent. + let p = parse_spec(r#"{"a":0..10=1,"b":json} (notes [x,y,z] here, and more) → {"c":id}"#); + assert_eq!(p, vec![Param { key: "a".into(), kind: Kind::Range { min: 0.0, max: 10.0, default: 1.0 } }, Param { key: "b".into(), kind: Kind::Json }]); + // Every command with a schema dialog has plain parameter keys. + for c in photocraft_engine::command_specs().iter().filter(|c| has_dialog(c.id)) { + for p in parse_spec(c.params) { + assert!(p.key.chars().all(|ch| ch.is_ascii_alphanumeric() || ch == '_'), "{}: junk parameter {:?}", c.id, p.key); + } + } +} + +#[test] +fn selective_color_dialog_ok_applies() { + // With the junk `reds: 0` the dialog's OK failed (`reds` must be an array of 4 numbers). + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let id = open(&mut app, "image.adjustments.selectiveColor").unwrap(); + let fields = app.ui.dialogs.last().unwrap().fields.clone(); + assert!(fields.keys().all(|k| k.starts_with("__") || k.chars().all(|ch| ch.is_ascii_alphanumeric())), "{fields:?}"); + assert!(!fields.contains_key("reds"), "the per-range arrays are not dialog fields"); + app.ui.dialog_mut(id).unwrap().fields.insert("black".into(), json!(40.0)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.journal.last().map(|j| j.0.as_str()), Some("image.adjustments.selectiveColor")); +} + +/// A filtered test image with structure at every scale (low-frequency waves plus a ramp). +fn waves(n: u32) -> Document { + let mut doc = Document::with_background( + "w", + photocraft_doc::Size::new(n, n), + photocraft_doc::ColorMode::Rgb, + photocraft_doc::SampleType::U8, + photocraft_doc::Color::WHITE, + ); + let s = doc.layers[0].surface_mut().unwrap(); + for y in 0..n as i32 { + for x in 0..n as i32 { + let v = 0.5 + 0.4 * (x as f32 / 23.0).sin() * (y as f32 / 31.0).cos(); + s.fill_rect(photocraft_geom::Rect::new(x, y, x + 1, y + 1), &[v, 1.0 - v, x as f32 / n as f32, 1.0]); + } + } + doc +} + +/// Mean absolute RGB difference of two documents, compared at 1/4 scale. +fn diff_at_quarter(a: &Document, b: &Document) -> f32 { + let quarter = |d: &Document| photocraft_compose::flatten(&crate::proxy::proxy_document(d, (d.size.width / 64).max(1))); + let (a, b) = (quarter(a), quarter(b)); + assert_eq!(a.px.len(), b.px.len()); + a.px.iter().zip(&b.px).map(|(p, q)| (0..3).map(|c| (p[c] - q[c]).abs()).sum::() / 3.0).sum::() / a.px.len() as f32 +} + +/// #2063: these filters drew their features in proxy pixels (noise, dots, dither, strokes, +/// kernels, scan lines, contour lines, streaks, depths, a tree's segments), so a 1/4 preview +/// showed them 4x larger than OK applied them. Their preview now runs at full resolution and +/// matches the applied result. Dust & Scratches (#3265) is the mirror image of those: a proxy +/// averages away the very specks the filter exists to remove, so its preview showed an +/// untouched image at a blocky scale. +#[test] +fn fixed_size_filters_preview_at_the_scale_they_apply() { + let doc = sharp(256); + let gray = grayscale(&doc); + let edge = json!([0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, 4, -1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0]); + for (cmd, p) in [ + ("filter.distort.ripple", json!({"amount": 300.0, "size": "large"})), + ("filter.stylize.diffuse", json!({"mode": "normal"})), + ("filter.stylize.oilPaint", json!({})), + ("filter.render.flame", json!({})), + ("filter.render.fibers", json!({})), + ("filter.pixelate.mezzotint", json!({"type": "mediumDots"})), + ("filter.noise.addNoise", json!({"amount": 12.5})), + ("filter.noise.dustAndScratches", json!({"radius": 4.0, "threshold": 0.0})), + ("filter.noise.reduceNoise", json!({})), + ("filter.other.custom", json!({"kernel": edge})), + ("filter.video.deInterlace", json!({})), + ("filter.stylize.traceContour", json!({})), + ("filter.stylize.wind", json!({"method": "blast"})), + ("filter.stylize.extrude", json!({})), + ("filter.render.tree", json!({"baseTreeType": 1})), + ("filter.sharpen.sharpen", json!({})), + ("filter.sharpen.sharpenMore", json!({})), + ("filter.sharpen.sharpenEdges", json!({})), + ("filter.stylize.findEdges", json!({})), + ("filter.stylize.emboss", json!({})), + ("filter.noise.despeckle", json!({})), + ("filter.gallery.graphicPen", json!({})), + ("filter.gallery.stainedGlass", json!({"cellSize": 10})), + ("image.mode.indexedColor", json!({"colors": 16})), + ("image.mode.bitmap", json!({"method": "diffusion"})), + ] { + let doc = if cmd == "image.mode.bitmap" { &gray } else { &doc }; + let bg = doc.layers[0].id; + let applied = preview_document(doc, Some(bg), cmd, &p, 1).unwrap(); + let old = preview_document(doc, Some(bg), cmd, &p, 4).unwrap(); + assert!(diff_at_quarter(&applied, &old) > 0.005, "{cmd}: a 1/4 proxy differs from the result"); + let k = preview_factor(cmd, &p, 4); + assert_eq!(k, 1, "{cmd}"); + let shown = preview_document(doc, Some(bg), cmd, &p, k).unwrap(); + assert!(diff_at_quarter(&applied, &shown) < 1e-4, "{cmd}: the preview is what OK applies"); + } + // Without dithering, the colour-mode conversions keep the proxy. + assert_eq!(preview_factor("image.mode.indexedColor", &json!({"dither": "none"}), 4), 4); + assert_eq!(preview_factor("image.mode.bitmap", &json!({"method": "threshold"}), 4), 4); +} + +/// #6530: the Content-Aware Fill preview runs at full resolution, for every Sampling choice, +/// because its patch search finds different matches on a reduced copy. +#[test] +fn content_aware_fill_previews_at_full_resolution() { + for params in [json!({}), json!({"sampling": "auto"}), json!({"sampling": "rectangular"})] { + assert_eq!(preview_factor("edit.contentAwareFill", ¶ms, 4), 1, "{params}"); + } +} + +/// #2063: proxy previews scaled what isn't a length (Tree's canvas fraction, Lens Correction's +/// perspective), clamped negative lengths to +0.1 (Offset left/up), left Shadows/Highlights' +/// radii in document pixels and rounded Mosaic's 10 px cells to 3 proxy px (12 px). +#[test] +fn proxy_previews_scale_only_lengths() { + let doc = waves(256); + let bg = doc.layers[0].id; + let error = |cmd: &str, p: Value| { + let k = preview_factor(cmd, &p, 4); + let applied = preview_document(&doc, Some(bg), cmd, &p, 1).unwrap(); + let shown = preview_document(&doc, Some(bg), cmd, &p, k).unwrap(); + (k, mean_abs(&every_kth(&applied, k), &every_kth(&shown, 1))) + }; + for (cmd, p) in [ + ("filter.lensCorrection", json!({"vertical": -100.0, "horizontal": 60.0})), + ("filter.other.offset", json!({"horizontal": -40, "vertical": -24, "undefinedAreas": "wrap"})), + ( + "image.adjustments.shadowsHighlights", + json!({"shadowAmount": 50.0, "shadowRadius": 30.0, "highlightAmount": 50.0, "highlightRadius": 30.0, "blackClip": 0.0, "whiteClip": 0.0}), + ), + ] { + let (k, diff) = error(cmd, p); + assert_eq!(k, 4, "{cmd} keeps the proxy"); + assert!(diff < 0.01, "{cmd}: the preview shows what OK applies ({diff})"); + } + // Mosaic's cells divide evenly: 10 px at k = 2 is 5 proxy px; 40 px keeps k = 4. + assert_eq!(preview_factor("filter.pixelate.mosaic", &json!({"cellSize": 10.0}), 4), 2); + assert_eq!(preview_factor("filter.pixelate.mosaic", &json!({"cellSize": 40.0}), 4), 4); + assert_eq!(preview_factor("filter.pixelate.mosaic", &json!({"cellSize": 7.0}), 4), 1); + assert_eq!(preview_factor("filter.pixelate.mosaic", &json!({"cellSize": "x"}), 4), 4); + let (k, diff) = error("filter.pixelate.mosaic", json!({"cellSize": 10.0})); + assert!(k == 2 && diff < 0.01, "Mosaic: {diff}"); + // Tree's and Picture Frame's sizes are relative, not pixels (and not shown as "px"). + assert!(!is_pixel_param_of("filter.render.tree", "size") && !is_pixel_param_of("filter.render.pictureFrame", "size")); + assert!(is_pixel_param_of("filter.stylize.extrude", "size")); +} + +/// #218: Warp Text renders the type again from the layer model, which a reduced proxy doesn't +/// scale: the preview showed the text k times too large. It is the full-size result, reduced. +#[test] +fn warp_text_preview_matches_the_full_size_result_on_a_reduced_proxy() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 4000, "height": 3000})).unwrap(); + s.execute("type.create", json!({"x": 300, "y": 1600, "text": "Warp", "size": 400})).unwrap(); + let st = s.active().unwrap(); + let (doc, layer) = ((*st.doc).clone(), st.active_layer.unwrap()); + let p = json!({"style": "arc", "bend": 40.0}); + let k = preview_factor("type.warpText", &p, crate::proxy::preview_factor(&doc, true)); + assert!(k > 1, "the preview runs on a reduced proxy"); + let cache = |d: &Document| match &d.layer(layer).unwrap().content { + photocraft_doc::LayerContent::Text(t) => t.cache.clone().unwrap(), + _ => panic!("a type layer"), + }; + let full = crate::proxy::proxy_document(&preview_document(&doc, Some(layer), "type.warpText", &p, 1).unwrap(), k); + let shown = preview_document(&doc, Some(layer), "type.warpText", &p, k).unwrap(); + assert_eq!(shown.size, full.size); + assert_eq!(cache(&shown).content_bounds(), cache(&full).content_bounds()); + assert_eq!(photocraft_compose::flatten(&shown).px, photocraft_compose::flatten(&full).px); +} + +/// #5766: Curves on a smart object adds a smart filter, which re-renders the source through +/// the object's placement. On a reduced proxy that placement stayed in full-size document +/// coordinates, so the preview showed the object `k` times too large until OK. +#[test] +fn smart_object_curves_preview_keeps_its_size_on_a_reduced_proxy() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 16, "y": 16, "width": 16, "height": 16})).unwrap(); + s.execute("edit.fill", json!({"contents": "black"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let st = s.active().unwrap(); + let (doc, layer) = ((*st.doc).clone(), st.active_layer.unwrap()); + let alpha = |d: &Document, x: i32, y: i32| match &d.layer(layer).unwrap().content { + photocraft_doc::LayerContent::Smart(sm) => sm.cache.as_ref().unwrap().pixel(x, y).last().copied().unwrap(), + _ => panic!("a smart object"), + }; + let k = 4; + let params = json!({"points": [[0, 20], [90, 150], [255, 230]]}); + let shown = preview_document(&doc, Some(layer), "image.adjustments.curves", ¶ms, k).unwrap(); + let full = preview_document(&doc, Some(layer), "image.adjustments.curves", ¶ms, 1).unwrap(); + let photocraft_doc::LayerContent::Smart(full_sm) = &full.layer(layer).unwrap().content else { panic!("a smart object") }; + let reference = photocraft_algo::resample::resize_surface(full_sm.cache.as_ref().unwrap(), 0.25, 0.25, photocraft_algo::resample::Resample::Bicubic); + let photocraft_doc::LayerContent::Smart(sm) = &shown.layer(layer).unwrap().content else { panic!("a smart object") }; + assert_eq!(sm.smart_filters.len(), 1, "the preview adds the Curves smart filter"); + assert_eq!(shown.size, crate::proxy::proxy_document(&doc, k).size); + // The 16 px square at (16, 16) is a 4 px square at (4, 4) on the proxy, not 16 px at (16, 16). + // Bicubic reduction blends the square's boundary with transparency; compare all alpha + // values with a reduced full-size result, and require opacity only in the interior. + for y in 0..shown.size.height as i32 { + for x in 0..shown.size.width as i32 { + let expected = reference.pixel(x, y).last().copied().unwrap(); + let actual = alpha(&shown, x, y); + assert!((actual - expected).abs() <= 1.0 / 255.0, "({x}, {y}): alpha {actual}, expected {expected}"); + } + } + for (x, y) in [(5, 5), (5, 6), (6, 6)] { + assert!(alpha(&shown, x, y) > 0.99, "({x}, {y}) is inside the reduced square"); + } + for (x, y) in [(4, 4), (7, 7)] { + assert!(alpha(&shown, x, y) > 0.5, "({x}, {y}) is a corner of the reduced square"); + } + for (x, y) in [(2, 2), (9, 9), (12, 12), (15, 15)] { + assert!(alpha(&shown, x, y) < 0.01, "({x}, {y}) is outside the reduced square"); + } +} + +/// #2063: a pixel-sized parameter divided by the proxy factor was clamped to the command's +/// minimum (Pointillize's 5 px cells became 3 px proxy cells = 12 px), so the preview factor +/// drops until every pixel-sized value fits its range. +#[test] +fn proxy_previews_never_clamp_pixel_sized_params() { + let pointillize = |c: f64| preview_factor("filter.pixelate.pointillize", &json!({"cellSize": c}), 4); + assert_eq!((pointillize(5.0), pointillize(7.0), pointillize(12.0), pointillize(300.0)), (1, 2, 4, 4)); + assert_eq!(preview_factor("filter.pixelate.crystallize", &json!({"cellSize": 10.0}), 4), 3); + assert_eq!(preview_factor("filter.pixelate.colorHalftone", &json!({"maxRadius": 8.0}), 4), 2); + assert_eq!(preview_factor("filter.blur.gaussianBlur", &json!({"radius": 8.0}), 4), 4, "unclamped filters keep the proxy"); + // Hostile params never panic and leave the factor alone; a full-size document stays at 1. + assert_eq!(preview_factor("filter.pixelate.pointillize", &json!({"cellSize": "x"}), 4), 4); + assert_eq!(preview_factor("filter.pixelate.pointillize", &json!(null), 4), 4); + assert_eq!(preview_factor("no.such.command", &json!({"cellSize": 1.0}), 4), 4); + assert_eq!(preview_factor("filter.pixelate.pointillize", &json!({"cellSize": 5.0}), 0), 1); + // Every previewed command, at each pixel-sized param's minimum, default and in between. + let previewed = photocraft_engine::command_specs().iter().filter(|c| has_dialog(c.id) && (c.id.starts_with("filter.") || PREVIEWED.contains(&c.id))); + for c in previewed { + for p in parse_spec(c.params) { + let Kind::Range { min, default, .. } = p.kind else { continue }; + if min <= 0.0 || !is_pixel_param_of(c.id, &p.key) { + continue; + } + for v in [f64::from(min), f64::from(default), f64::from(min) * 2.5] { + let k = preview_factor(c.id, &json!({ p.key.clone(): v }), 4); + assert!(v / f64::from(k) >= f64::from(min) - 1e-9, "{} {}={v}: k={k} clamps to {min}", c.id, p.key); + } + } + } +} + +/// Sharp structure at every scale: [`waves`] with hard squares from 2 to 32 px, a fine +/// per-pixel texture and an interlaced band (odd rows inverted) at the bottom. +fn sharp(n: u32) -> Document { + let mut doc = waves(n); + let s = doc.layers[0].surface_mut().unwrap(); + let mut x0 = 4; + for (i, size) in [2, 3, 4, 6, 8, 12, 16, 24, 32].into_iter().enumerate() { + for y0 in (4..n as i32 * 3 / 4 - size).step_by((size * 3) as usize) { + let v = if (i + y0 as usize / 7).is_multiple_of(2) { 0.05 } else { 0.95 }; + s.fill_rect(photocraft_geom::Rect::new(x0, y0, x0 + size, y0 + size), &[v, v * 0.8, 1.0 - v, 1.0]); + } + x0 += size + 6; + } + for y in 0..n as i32 { + for x in 0..n as i32 { + let mut px = s.pixel(x, y); + if (x * 7 + y * 13) % 5 == 0 { + px.iter_mut().take(3).for_each(|c| *c = (*c + 0.08).min(1.0)); + } + if y >= n as i32 * 3 / 4 && y % 2 == 1 { + px[0] = 1.0 - px[0]; + } + s.fill_rect(photocraft_geom::Rect::new(x, y, x + 1, y + 1), &px); + } + } + doc +} + +/// [`waves`] with strong per-pixel noise, the input of noise reduction. +fn noisy(n: u32) -> Document { + let mut doc = waves(n); + let s = doc.layers[0].surface_mut().unwrap(); + let hash = |x: i32, y: i32| ((x as u32).wrapping_mul(73_856_093) ^ (y as u32).wrapping_mul(19_349_663)).wrapping_mul(2_654_435_761) >> 8; + for y in 0..n as i32 { + for x in 0..n as i32 { + let mut px = s.pixel(x, y); + for (c, v) in px.iter_mut().take(3).enumerate() { + *v = (*v + (hash(x * 3 + c as i32, y) as f32 / (1u32 << 24) as f32 - 0.5) * 0.3).clamp(0.0, 1.0); + } + s.fill_rect(photocraft_geom::Rect::new(x, y, x + 1, y + 1), &px); + } + } + doc +} + +/// How a preview at factor `k` compares with what OK applies (factor 1) on a document. +#[derive(Debug)] +struct PreviewError { + /// Mean absolute RGB difference at the pixels the proxy samples. + diff: f32, + /// Feature scale of the preview shown at document size, relative to the result: 1 when + /// the features match, 1/k when the preview draws them k times too large. + scale: f32, + /// How much the preview changes the image relative to how much OK does (sampled); NaN + /// when OK barely changes it. + change: f32, +} + +/// Mean absolute difference of neighbouring pixels at the document's own resolution. +fn detail(d: &Document) -> f32 { + let b = photocraft_compose::flatten(d); + let w = b.rect.width() as usize; + let mut sum = 0.0; + for (i, p) in b.px.iter().enumerate() { + for q in [b.px.get(i + 1).filter(|_| (i + 1) % w != 0), b.px.get(i + w)].into_iter().flatten() { + sum += (0..3).map(|c| (p[c] - q[c]).abs()).sum::() / 3.0; + } + } + sum / b.px.len().max(1) as f32 +} + +/// Pixels of `d` at every `k`-th row and column: the document pixels a factor-`k` proxy +/// samples, so a preview at `k` compares with them one to one. +fn every_kth(d: &Document, k: u32) -> Vec<[f32; 4]> { + let b = photocraft_compose::flatten(d); + let w = b.rect.width() as usize; + let k = k as usize; + let h = b.px.len() / w.max(1); + (0..h.div_ceil(k)) + .flat_map(|y| (0..w.div_ceil(k)).map(move |x| (x * k, y * k))) + .map(|(x, y)| b.px.get(y * w + x).copied().unwrap_or([f32::NAN; 4])) + .collect() +} + +fn mean_abs(a: &[[f32; 4]], b: &[[f32; 4]]) -> f32 { + a.iter().zip(b).map(|(p, q)| (0..3).map(|c| (p[c] - q[c]).abs()).sum::() / 3.0).sum::() / a.len().max(1) as f32 +} + +/// `None` when the command can't run on `doc` at all (e.g. Displace without a map). +fn preview_error(doc: &Document, command: &str, p: &Value, k: u32) -> Option { + let bg = doc.layers[0].id; + let applied = preview_document(doc, Some(bg), command, p, 1)?; + let shown = preview_document(doc, Some(bg), command, p, k).unwrap_or_else(|| panic!("{command} {p}: the k = {k} preview failed")); + let (a, s) = (every_kth(&applied, k), every_kth(&shown, 1)); + let (src, src_k) = (every_kth(doc, k), every_kth(&crate::proxy::proxy_document(doc, k), 1)); + let applied_change = mean_abs(&a, &src); + Some(PreviewError { + diff: mean_abs(&a, &s), + scale: detail(&shown) / k as f32 / detail(&applied).max(1e-5), + change: if applied_change > 0.01 { mean_abs(&s, &src_k) / applied_change } else { f32::NAN }, + }) +} + +/// The parameter sets to preview `command` with: the dialog's defaults, and each pixel-sized +/// value at its minimum and at a large value (whole numbers as integers: Tree and Picture +/// Frame read some ranges as `u32`). +fn sweep_params(app: &mut PhotocraftApp, command: &str) -> Vec<(String, Value)> { + let Some(id) = open(app, command) else { return Vec::new() }; + let base = params_of(&app.ui.dialog_mut(id).unwrap().fields); + let mut out = vec![("default".to_string(), base.clone())]; + for p in parse_spec(photocraft_engine::commands::find(command).unwrap().params) { + if !is_pixel_param_of(command, &p.key) { + continue; + } + let values = match p.kind { + Kind::Int { .. } => vec![-40.0, 40.0], + Kind::Range { min, max, default } => [min, (default * 4.0).clamp(min, max.min(64.0))].into_iter().filter(|v| *v != default).collect(), + _ => continue, + }; + for v in values { + let mut q = base.clone(); + q[p.key.as_str()] = json!(v); + out.push((format!("{}={v}", p.key), q)); + } + } + for (_, p) in &mut out { + for v in p.as_object_mut().into_iter().flat_map(|o| o.values_mut()) { + if let Some(x) = v.as_f64().filter(|x| x.fract() == 0.0 && x.abs() < 1e9) { + *v = json!(x as i64); + } + } + } + out +} + +/// Every previewed command with its parameter sets. +fn previewed_cases() -> Vec<(&'static str, String, Value)> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ids: Vec<&'static str> = photocraft_engine::command_specs() + .iter() + .map(|c| c.id) + .filter(|id| has_dialog(id) && (id.starts_with("filter.") || PREVIEWED.contains(id))) + .collect(); + ids.into_iter().flat_map(|id| sweep_params(&mut app, id).into_iter().map(move |(label, p)| (id, label, p))).collect() +} + +fn grayscale(d: &Document) -> Document { + let mut s = photocraft_engine::Session::new(); + s.add_document(d.clone(), None); + s.execute("image.mode.grayscale", json!({})).unwrap(); + s.active().map(|d| (*d.doc).clone()).unwrap() +} + +/// Smooth, sharp and noisy test images, each in RGB and grayscale (for the modes that need it). +fn test_images(n: u32) -> [(&'static str, Document, Document); 3] { + let with_gray = |d: Document| (grayscale(&d), d); + let ((ws, w), (ss, s), (ns, no)) = (with_gray(waves(n)), with_gray(sharp(n)), with_gray(noisy(n))); + [("smooth", w, ws), ("sharp", s, ss), ("noisy", no, ns)] +} + +fn image_for<'a>(command: &str, rgb: &'a Document, gray: &'a Document) -> &'a Document { + if command == "image.mode.bitmap" || command == "image.mode.duotone" { gray } else { rgb } +} + +/// Previews that only approximate the result at a proxy although their features have the +/// right size: dots and cells placed on the proxy's pixel grid (Color Halftone, Pointillize) +/// and tile edges resampled (Tiles). Two more only differ on a proxy as small as this test's +/// (64 x 64 px): Picture Frame's minimum line widths, and Shadows/Highlights' 0.01 % black and +/// white clips, which pick single pixels out of 4096 (its radii are checked in +/// `proxy_previews_scale_only_lengths`). +const APPROXIMATE_AT_PROXY: &[&str] = &[ + "filter.pixelate.colorHalftone", + "filter.pixelate.pointillize", + "filter.stylize.tiles", + "filter.render.pictureFrame", + "image.adjustments.shadowsHighlights", +]; + +/// Why a preview doesn't show what OK applies, if it doesn't: a clearly different result or +/// features at another size on the smooth image, or (on the sharp and noisy images, where a +/// sub-pixel radius can't show on a proxy) a filter that acts more strongly in the preview, +/// i.e. over a k times larger area. +fn mismatch(image: &str, e: &PreviewError) -> Option { + let off = if image == "smooth" { e.diff > 0.03 || (!(0.6..=1.6).contains(&e.scale) && e.diff > 0.002) } else { e.change > 1.25 }; + off.then(|| format!("{e:?}")) +} + +/// #2063, every previewed command: the live preview at the factor [`preview_factor`] picks +/// for a 1/4 proxy shows what OK applies: the same features at the same size, on smooth, +/// sharp and noisy images, at the defaults and at small and large pixel sizes. +#[test] +fn every_preview_shows_what_ok_applies() { + let cases: Vec<_> = previewed_cases().into_iter().filter(|(id, _, p)| preview_factor(id, p, 4) > 1 && !APPROXIMATE_AT_PROXY.contains(id)).collect(); + // One thread per test image: about 270 filter runs at 256 x 256. + let bad: Vec = std::thread::scope(|scope| { + let runs: Vec<_> = test_images(256) + .into_iter() + .map(|(image, rgb, gray)| { + let cases = &cases; + scope.spawn(move || { + let mut bad = Vec::new(); + for (id, label, p) in cases { + let k = preview_factor(id, p, 4); + if let Some(why) = preview_error(image_for(id, &rgb, &gray), id, p, k).and_then(|e| mismatch(image, &e)) { + bad.push(format!("{id} ({label}) at k = {k} on the {image} image: {why}")); + } + } + bad + }) + }) + .collect(); + runs.into_iter().flat_map(|r| r.join().unwrap()).collect() + }); + assert!(bad.is_empty(), "previews that differ from the result:\n{}", bad.join("\n")); +} + +/// The table behind [`every_preview_shows_what_ok_applies`]: every previewed command at a +/// plain 1/4 proxy and at its chosen factor, on each test image. +/// `cargo test -p photocraft-ui-egui --lib filter_dialog::tests::sweep_all_previews -- --ignored --nocapture` +#[test] +#[ignore] +fn sweep_all_previews() { + let images = test_images(256); + println!("command | params | image | k | diff k=4 | scale k=4 | change k=4 | diff k | scale k | change k"); + for (id, label, p) in previewed_cases() { + let k = preview_factor(id, &p, 4); + for (image, rgb, gray) in &images { + let doc = image_for(id, rgb, gray); + match (preview_error(doc, id, &p, 4), preview_error(doc, id, &p, k)) { + (Some(a), Some(b)) => println!( + "{id} | {label} | {image} | {k} | {:.4} | {:.2} | {:.2} | {:.4} | {:.2} | {:.2}", + a.diff, a.scale, a.change, b.diff, b.scale, b.change + ), + _ => println!("{id} | {label} | {image} | {k} | fails"), + } + } + } +} + +/// The profiles Assign Profile offers for a new document converted with `mode` (if any), +/// and which of the command's built-in profiles the command itself accepts for it. +fn assign_profile_offers(mode: Option<&str>) -> (Vec, Vec) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + if let Some(mode) = mode { + app.run(mode, json!({})).unwrap(); + } + open(&mut app, "edit.assignProfile").unwrap(); + let offered: Vec = + app.ui.dialogs.last().unwrap().fields["__profiles"].as_array().unwrap().iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(); + let spec = photocraft_engine::commands::find("edit.assignProfile").unwrap(); + let builtin = parse_spec(spec.params).into_iter().find(|p| p.key == "profile").unwrap(); + let Kind::Choice { options, .. } = builtin.kind else { panic!("profile is a menu") }; + let accepted = options.into_iter().filter(|name| app.session.execute("edit.assignProfile", json!({"profile": name})).is_ok()).collect(); + (offered, accepted) +} + +/// #4951: Assign Profile lists the profiles the command accepts for the document's colour +/// mode, and none of the others. +#[test] +fn assign_profile_offers_only_profiles_of_the_documents_colour_mode() { + for mode in [None, Some("image.mode.cmyk"), Some("image.mode.grayscale")] { + let (offered, accepted) = assign_profile_offers(mode); + for name in &accepted { + assert!(offered.contains(name), "{mode:?}: {name} can be assigned, so it is offered"); + } + for name in ["srgb", "coated-cmyk", "sgray"] { + assert_eq!(offered.iter().any(|o| o == name), accepted.iter().any(|a| a == name), "{mode:?}: {name}"); + } + assert!(offered.iter().any(|o| o == "working") && offered.iter().any(|o| o == "none"), "{mode:?}: working space and none always fit"); + } + let (rgb, _) = assign_profile_offers(None); + assert!(rgb.iter().any(|o| o == "srgb") && !rgb.iter().any(|o| o == "coated-cmyk"), "an RGB document gets RGB profiles"); + let (cmyk, _) = assign_profile_offers(Some("image.mode.cmyk")); + assert!(cmyk.iter().any(|o| o == "coated-cmyk") && !cmyk.iter().any(|o| o == "srgb"), "a CMYK document gets CMYK profiles"); +} + +/// #4951: a profile remembered from a document of another colour mode isn't preselected. +#[test] +fn assign_profile_drops_a_remembered_profile_that_does_not_fit() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.session.prefs.edit(|prefs| { + prefs.dialogs.insert("edit.assignProfile".into(), json!({"profile": "coated-cmyk"})); + }); + open(&mut app, "edit.assignProfile").unwrap(); + assert_eq!(app.ui.dialogs.last().unwrap().fields["profile"], json!("working")); + app.session.prefs.edit(|prefs| { + prefs.dialogs.insert("edit.assignProfile".into(), json!({"profile": "display-p3"})); + }); + open(&mut app, "edit.assignProfile").unwrap(); + assert_eq!(app.ui.dialogs.last().unwrap().fields["profile"], json!("display-p3"), "one that fits is kept"); +} + +#[test] +fn schema_dialogs_respect_explicit_dropdown_defaults() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + + // 1. Radial Blur has explicit default "good", not the first option ("draft"). + open(&mut app, "filter.blur.radialBlur").unwrap(); + let fields = &app.ui.dialogs.last().unwrap().fields; + assert_eq!(fields["quality"], json!("good"), "Radial Blur must select explicit default 'good'"); + assert_eq!(fields["method"], json!("spin"), "Radial Blur method has no explicit default, retains first option"); + let params = params_of(fields); + assert_eq!(params["quality"], json!("good")); + + // 2. Convert to Profile has explicit default "relative", not first option ("perceptual"). + open(&mut app, "edit.convertToProfile").unwrap(); + let fields = &app.ui.dialogs.last().unwrap().fields; + assert_eq!(fields["intent"], json!("relative"), "Convert to Profile must select explicit default 'relative'"); + let params = params_of(fields); + assert_eq!(params["intent"], json!("relative")); + + // 3. Proof Setup has explicit default "relative". + open(&mut app, "view.proofSetup").unwrap(); + let fields = &app.ui.dialogs.last().unwrap().fields; + assert_eq!(fields["intent"], json!("relative"), "Proof Setup must select explicit default 'relative'"); + let params = params_of(fields); + assert_eq!(params["intent"], json!("relative")); + + // 4. Remembered values still override initial defaults. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.prefs.edit(|prefs| { + prefs.dialogs.insert("filter.blur.radialBlur".into(), json!({"quality": "best"})); + }); + open(&mut app, "filter.blur.radialBlur").unwrap(); + let fields = &app.ui.dialogs.last().unwrap().fields; + assert_eq!(fields["quality"], json!("best"), "Remembered choice must override explicit default"); + + // 5. Explicit default that is the first option (e.g. "cw" in arbitrary rotation). + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + open(&mut app, "image.rotation.arbitrary").unwrap(); + let fields = &app.ui.dialogs.last().unwrap().fields; + assert_eq!(fields["direction"], json!("cw"), "Explicit default matching first option is preserved"); +} + +/// #4143: Replace Color shows the From colour (defaulting to the foreground) and its canvas +/// eyedropper samples the merged image into the dialog. +#[test] +fn replace_color_eyedropper_samples_the_image() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#00ff00"})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.run("tools.setColors", json!({"foreground": "#ff0000"})).unwrap(); + let id = open(&mut app, REPLACE_COLOR).unwrap(); + assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#ff0000"), "the dialog starts from the foreground colour"); + // #6279: armed as it opens, so the first click on the image samples. + assert!(color_eyedropper_armed(&app)); + assert!(color_eyedropper_sample(&mut app, 4.0, 4.0)); + assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#00ff00")); + // #4457: where it was picked, for Localized Color Clusters. + assert_eq!(app.ui.dialogs.last().unwrap().fields["points"], json!([[4.0, 4.0]])); + // Off-image: the click is consumed, nothing changes and the eyedropper stays armed. + assert!(color_eyedropper_sample(&mut app, -1.0, 4.0)); + assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#00ff00")); + assert!(color_eyedropper_armed(&app)); + // Disarmed, the dialog never claims the click. + app.ui.dialog_mut(id).unwrap().fields.insert(COLOR_EYEDROPPER.into(), json!(false)); + assert!(!color_eyedropper_armed(&app)); + assert!(!color_eyedropper_sample(&mut app, 4.0, 4.0)); +} + +/// #4143: the eyedropper button disarms and re-arms the canvas picker (#6279: it opens armed). +#[test] +fn replace_color_dialog_arms_the_eyedropper_button() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + let mut h = Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut(), REPLACE_COLOR).unwrap(); + h.run_steps(3); + assert!(color_eyedropper_armed(h.state()), "armed as the dialog opens"); + h.get_by_label("Pick Color From Image").click(); + h.run_steps(2); + assert!(!color_eyedropper_armed(h.state())); + h.get_by_label("Pick Color From Image").click(); + h.run_steps(2); + assert!(color_eyedropper_armed(h.state())); +} + +/// #6278: the Result swatch shows the sampled colour after the shift, and a colour picked for +/// it sets Hue, Saturation and Lightness so the sampled colour becomes it. +#[test] +fn replace_color_result_swatch_sets_the_sliders() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.run("tools.setColors", json!({"foreground": "#cc3333"})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(900.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(h.state_mut(), REPLACE_COLOR).unwrap(); + h.run_steps(3); + // No shift yet: the Result is the sampled colour. + assert_eq!(h.get_all_by_label("#cc3333").count(), 2, "the sampled colour and the Result both read #cc3333"); + h.get_by_role_and_label(egui::accesskit::Role::ColorWell, "Result").click(); + h.run_steps(3); + let picker = h.state().ui.dialogs.last().unwrap(); + assert_ne!(picker.id, id, "the Color Picker opened over the dialog"); + assert_eq!(picker.fields["color"], json!("#cc3333"), "on the current Result"); + let picker = picker.id; + h.state_mut().ui.dialog_mut(picker).unwrap().fields.insert("color".into(), json!("#3355cc")); + crate::dialogs::confirm(h.state_mut(), picker).unwrap(); + h.state_mut().ui.dialogs.retain(|d| d.id != picker); + h.run_steps(3); + let f = h.state_mut().ui.dialog_mut(id).unwrap().fields.clone(); + let n = |k: &str| f[k].as_f64().unwrap() as f32; + let got = photocraft_algo::tone::replace_color_result([0.8, 0.2, 0.2], n("hue"), n("saturation"), n("lightness")); + let want = crate::color_picker_ui::parse_hex("#3355cc").unwrap(); + assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.02), "the sliders turn the sampled colour into the pick: {got:?}"); + assert!(n("hue") != 0.0, "the hue moved"); + // Moving a slider afterwards is not mistaken for another pick. + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("lightness".into(), json!(10.0)); + h.run_steps(2); + assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields["lightness"], json!(10.0)); +} + +/// #4457: Localized Color Clusters and its Range, as in Photoshop's dialog; the sampled point +/// and both settings reach the command. +#[test] +fn replace_color_localized_color_clusters() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + + // Left half red, right half red too: localized on the left point, the right half stays. + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 40, "height": 10, "background": "#ff0000"})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + let mut h = Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(h.state_mut(), REPLACE_COLOR).unwrap(); + h.run_steps(3); + let _ = h.get_by_label("Localized Color Clusters"); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert(COLOR_EYEDROPPER.into(), json!(true)); + assert!(color_eyedropper_sample(h.state_mut(), 2.0, 5.0)); + h.get_by_label("Localized Color Clusters").click(); + h.run_steps(2); + let f = h.state().ui.dialogs.last().unwrap().fields.clone(); + assert_eq!((f["localized"].clone(), f["points"].clone()), (json!(true), json!([[2.0, 5.0]]))); + // The command with the dialog's fields, small range and a hue shift: only near (2, 5). + let mut p: Map = f.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); + p.insert("range".into(), json!(10)); + p.insert("hue".into(), json!(120)); + h.state_mut().run(REPLACE_COLOR, Value::Object(p)).unwrap(); + let doc = &h.state().session.active().unwrap().doc; + let px = |x: i32| doc.layers[0].surface().unwrap().read_region(photocraft_geom::Rect::new(x, 5, x + 1, 6)); + 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)); +} From 1328817710eb8976aae0b3a7a23a17715811e8d1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:16 +0000 Subject: [PATCH 090/259] refactor(ui-egui): move channel_view.rs tests to channel_view/tests.rs --- crates/ui-egui/src/channel_view.rs | 357 +---------------------- crates/ui-egui/src/channel_view/tests.rs | 354 ++++++++++++++++++++++ 2 files changed, 355 insertions(+), 356 deletions(-) create mode 100644 crates/ui-egui/src/channel_view/tests.rs diff --git a/crates/ui-egui/src/channel_view.rs b/crates/ui-egui/src/channel_view.rs index 0a5e1958a3..4d7602e4a1 100644 --- a/crates/ui-egui/src/channel_view.rs +++ b/crates/ui-egui/src/channel_view.rs @@ -387,359 +387,4 @@ pub fn ensure(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize) -> Optio } #[cfg(test)] -mod tests { - use super::*; - use photocraft_engine::Session; - use photocraft_engine::channel_cmds::ChannelTarget; - use serde_json::json; - - fn session() -> Session { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 8, "height": 4})).unwrap(); - s - } - - #[test] - fn composite_bands_keep_the_downsample_grid() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 41, "height": 700})).unwrap(); - s.execute("edit.fill", json!({"color": "#398db2"})).unwrap(); - let doc = &s.active().unwrap().doc; - let rect = doc.bounds(); - let full = photocraft_compose::render(doc, rect); - let full_ref = &full; - for factor in [1, 2, 3, 5] { - let expected: Vec<_> = (0..rect.height()) - .step_by(factor as usize) - .flat_map(|y| { - (0..rect.width()).step_by(factor as usize).map(move |x| { - let p = full_ref.get(rect.x0 + x as i32, rect.y0 + y as i32); - let a = p[3].clamp(0.0, 1.0); - [p[0] * a + 1.0 - a, p[1] * a + 1.0 - a, p[2] * a + 1.0 - a, 1.0] - }) - }) - .collect(); - assert_eq!(composite(doc, rect, factor), expected, "factor {factor}"); - } - } - - #[test] - fn channel_eyes_reuse_composite_until_pixels_change() { - let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 64, "height": 32})).unwrap(); - app.run("edit.fill", json!({"color": "#4080c0"})).unwrap(); - app.sync_views(); - let ctx = egui::Context::default(); - app.run("channel.setVisible", json!({"channel": "red", "visible": false})).unwrap(); - assert!(ensure(&mut app, &ctx, 0).is_some()); - let id = app.session.active().unwrap().doc.id.0; - let first = app.channel_views.get_mut(&id).unwrap().source.as_mut().unwrap(); - let original_sample = first.pixels[0]; - // Mark the cache: a recomposite overwrites it, while a freed buffer's address can come back. - first.pixels[0] = [0.0, 1.0, 0.0, 1.0]; - - app.run("channel.setVisible", json!({"channel": "green", "visible": false})).unwrap(); - assert!(ensure(&mut app, &ctx, 0).is_some()); - let reused = app.channel_views.get(&id).unwrap().source.as_ref().unwrap(); - assert_eq!(reused.pixels[0], [0.0, 1.0, 0.0, 1.0], "visibility does not recompose the pixels"); - - app.run("edit.fill", json!({"color": "#e02010"})).unwrap(); - assert!(ensure(&mut app, &ctx, 0).is_some()); - // A partial damage upload discards the source; a full redraw may replace it. - // In either case, cached samples must never refer to the pre-edit pixels. - if let Some(source) = app.channel_views.get(&id).unwrap().source.as_ref() { - assert_ne!(source.pixels[0], original_sample, "a full redraw replaces stale pixels"); - } - app.run("channel.setVisible", json!({"channel": "red", "visible": true})).unwrap(); - assert!(ensure(&mut app, &ctx, 0).is_some()); - let refreshed = app.channel_views.get(&id).unwrap().source.as_ref().unwrap(); - let st = app.session.active().unwrap(); - assert_eq!(refreshed.revision, st.revision); - assert_ne!(refreshed.pixels[0], original_sample, "new pixels must be recomposited"); - let expected = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - let mut unused = None; - let actual = render_with_source( - &st.doc, - &st.channel_view, - st.doc.bounds(), - 1, - Look::default(), - st.active_layer, - CompositeSource { cached: Some(&refreshed.pixels), fresh: &mut unused }, - ) - .unwrap(); - assert_eq!(actual, expected, "reused pixels must preserve channel colours"); - assert!(unused.is_none(), "reuse must not create a second composite"); - } - - #[test] - fn plain_composite_draws_nothing() { - let s = session(); - let st = s.active().unwrap(); - assert!(render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).is_none()); - } - - #[test] - fn quick_mask_overlay_is_red_over_masked_areas() { - let mut s = session(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap(); - s.execute("select.editInQuickMaskMode", json!({})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert_eq!(px[0], Color32::TRANSPARENT, "selected: no overlay"); - assert_eq!(px[6], Color32::from_rgba_premultiplied(128, 0, 0, 128), "masked: 50% red"); - } - - #[test] - fn quick_mask_without_selection_shows_no_overlay_in_either_mode() { - // #2743: nothing selected is a colourless mask, whichever way the colour reads. - for (before, after) in [(None, Some("selected")), (Some("selected"), None), (Some("selected"), Some("masked"))] { - let mut s = session(); - if let Some(i) = before { - s.execute("channel.options", json!({"channel": "quickMask", "indicates": i})).unwrap(); - } - s.execute("select.editInQuickMaskMode", json!({})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert!(px.iter().all(|p| *p == Color32::TRANSPARENT), "{before:?}"); - if let Some(i) = after { - s.execute("channel.options", json!({"channel": "quickMask", "indicates": i})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert!(px.iter().all(|p| *p == Color32::TRANSPARENT), "{before:?} → {i}"); - } - } - // Selected Areas with Select All: the whole canvas is coloured. - let mut s = session(); - s.execute("channel.options", json!({"channel": "quickMask", "indicates": "selected"})).unwrap(); - s.execute("select.all", json!({})).unwrap(); - s.execute("select.editInQuickMaskMode", json!({})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert!(px.iter().all(|p| *p == Color32::from_rgba_premultiplied(128, 0, 0, 128))); - } - - #[test] - fn layer_mask_views_and_damage_on_the_downsampled_grid() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 37, "height": 21})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [37, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap(); - s.execute("view.layerMask", json!({"mode": "gray"})).unwrap(); - let st = s.active().unwrap(); - let b = st.doc.bounds(); - let full = render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap(); - assert!(full[0].r() < 10 && full[36].r() > 245 && full[0].a() == 255, "opaque grayscale ramp"); - // A sub-rect starting on the factor grid matches the same pixels of the full render. - for f in [1u32, 2, 3] { - let all = render(&st.doc, &st.channel_view, b, f, Look::default(), st.active_layer).unwrap(); - let w = b.width().div_ceil(f) as usize; - let r = Rect::new(3 * f as i32, 2 * f as i32, 30, 19); - let part = render(&st.doc, &st.channel_view, r, f, Look::default(), st.active_layer).unwrap(); - let pw = r.width().div_ceil(f) as usize; - for (i, p) in part.iter().enumerate() { - assert_eq!(*p, all[(i / pw + 2) * w + i % pw + 3], "factor {f}, pixel {i}"); - } - } - s.execute("view.layerMask", json!({"mode": "overlay"})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap(); - assert!(px[0].r() >= 124 && px[0].g() == 0 && px[0].a() >= 124, "about 50% red over the hidden end: {:?}", px[0]); - assert!(px[36].a() <= 4, "next to nothing over the revealed end: {:?}", px[36]); - } - - #[test] - fn layer_mask_views_show_the_feathered_mask() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 37, "height": 21})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [37, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap(); - s.execute("layer.layerMask.edit", json!({"feather": 4})).unwrap(); - s.execute("view.layerMask", json!({"mode": "gray"})).unwrap(); - - let st = s.active().unwrap(); - let bounds = st.doc.bounds(); - let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); - let raw = layer.mask.as_ref().unwrap().surface.sample_channel(0, 0, 0); - let effective = photocraft_compose::masks::combined_mask(layer, bounds).unwrap(); - let softened = effective.sample_channel(0, 0, 0); - assert!((softened - raw).abs() > 0.01, "the fixture has a visible feather at its edge"); - - let gray = render(&st.doc, &st.channel_view, bounds, 1, Look::default(), st.active_layer).unwrap(); - assert_eq!(gray[0], Color32::from_gray(q(softened)), "gray view uses the compositor's feathered mask"); - - s.execute("view.layerMask", json!({"mode": "overlay"})).unwrap(); - let st = s.active().unwrap(); - let overlay = render(&st.doc, &st.channel_view, bounds, 1, Look::default(), st.active_layer).unwrap(); - let alpha = 0.5 * (1.0 - softened); - let red = AlphaChannel::DEFAULT_COLOR.to_rgb(); - assert_eq!(overlay[0], Color32::from_rgba_premultiplied(q(red[0] * alpha), q(red[1] * alpha), q(red[2] * alpha), q(alpha))); - } - - /// Layer Mask Display Options: the rubylith takes their colour and opacity, alone over the - /// composite and with a colour channel hidden. - #[test] - fn layer_mask_overlay_takes_its_display_options() { - let mut s = session(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - s.execute("layer.layerMask.hideAll", json!({})).unwrap(); - s.execute("view.layerMask", json!({"mode": "overlay"})).unwrap(); - let green = Look { mask_rgb: [0.0, 1.0, 0.0], mask_opacity: 0.25, ..Look::default() }; - let st = s.active().unwrap(); - let b = st.doc.bounds(); - assert_eq!(render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap()[0], Color32::from_rgba_premultiplied(128, 0, 0, 128)); - assert_eq!(render(&st.doc, &st.channel_view, b, 1, green, st.active_layer).unwrap()[0], Color32::from_rgba_premultiplied(0, 64, 0, 64)); - // Red hidden: the white picture shows cyan, then green at 25 % over it. - s.execute("channel.setVisible", json!({"channel": "red", "visible": false})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(render(&st.doc, &st.channel_view, b, 1, green, st.active_layer).unwrap()[0], Color32::from_rgb(0, 255, 191)); - } - - /// `cargo test --release -p photocraft-ui-egui --lib mask_view_switch_24mp -- --ignored --nocapture` - #[test] - #[ignore = "benchmark"] - fn mask_view_switch_24mp() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 6000, "height": 4000})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("edit.fill", json!({"color": "#d0402b"})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [6000, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap(); - let factor = 6000u32.div_ceil(MAX_SIDE); - for mode in ["gray", "overlay"] { - s.execute("view.layerMask", json!({"mode": mode})).unwrap(); - let st = s.active().unwrap(); - let mut best = f64::MAX; - for _ in 0..8 { - let t = std::time::Instant::now(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), factor, Look::default(), st.active_layer).unwrap(); - let img = egui::ColorImage::new([3000, 2000], px); - std::hint::black_box(img); - best = best.min(t.elapsed().as_secs_f64() * 1000.0); - } - println!("24 MP mask view {mode}: {best:.1} ms (render at 1/{factor})"); - } - } - - /// Interface ▸ Show Channels in Color (#2385): a solo RGB / CMYK channel tints the canvas - /// instead of staying gray, like the panel thumbnails wired in #1986. - #[test] - fn show_channels_in_color_tints_the_canvas() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb"})).unwrap(); - s.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); - s.execute("channel.target", json!({"channel": "green"})).unwrap(); - let st = s.active().unwrap(); - let b = st.doc.bounds(); - assert_eq!(render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap()[0], Color32::from_gray(128)); - assert_eq!( - render(&st.doc, &st.channel_view, b, 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0], - Color32::from_rgb(0, 128, 0) - ); - - let mut s = Session::new(); - s.execute("file.new", json!({"width": 4, "height": 4, "mode": "cmyk"})).unwrap(); - s.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); - s.execute("channel.target", json!({"channel": "cyan"})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0]; - assert!(px.r() < 100 && px.g() > 150 && px.b() > 150, "cyan ink, not gray: {px:?}"); - let gray = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap()[0]; - assert_eq!(gray.r(), gray.g(), "off stays grayscale"); - } - - /// Lab: a and b tint over a neutral Lightness; Lightness itself stays gray (Adobe's exception). - #[test] - fn show_channels_in_color_lab_lightness_stays_gray() { - let mut s = Session::new(); - s.execute("file.new", json!({"width": 4, "height": 4, "mode": "lab"})).unwrap(); - s.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); - let b = s.active().unwrap().doc.bounds(); - s.execute("channel.target", json!({"channel": {"color": 0}})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, b, 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0]; - let spread = px.r().max(px.g().max(px.b())) as i32 - px.r().min(px.g().min(px.b())) as i32; - assert!(spread <= 3, "Lightness stays gray: {px:?}"); - s.execute("channel.target", json!({"channel": {"color": 1}})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, b, 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0]; - assert!(px.r() != px.g() || px.g() != px.b(), "a channel is tinted, not gray: {px:?}"); - } - - /// The canvas texture cache is keyed by the preference, so toggling it rebuilds the view. - #[test] - fn ensure_honours_show_channels_in_color() { - let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - app.sync_views(); - app.run("channel.target", json!({"channel": "green"})).unwrap(); - let ctx = egui::Context::default(); - assert!(ensure(&mut app, &ctx, 0).is_some()); - let key_off = app.channel_views.values().next().unwrap().key; - app.session.execute("prefs.set", json!({"values": {"interface.showChannelsInColor": true}})).unwrap(); - assert!(ensure(&mut app, &ctx, 0).is_some()); - let key_on = app.channel_views.values().next().unwrap().key; - assert_ne!(key_off, key_on, "the preference changes the cached view key"); - // So do the Layer Mask Display Options. - app.session.execute("channel.options", json!({"channel": "mask", "color": "#00ff00", "opacity": 70})).unwrap(); - assert!(ensure(&mut app, &ctx, 0).is_some()); - assert_ne!(app.channel_views.values().next().unwrap().key, key_on, "the overlay options change the cached view key"); - } - - #[test] - fn solo_alpha_is_grayscale_and_colour_channels_split() { - let mut s = session(); - s.execute("edit.fill", json!({"color": "#ff8000"})).unwrap(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 2, "height": 4})).unwrap(); - s.execute("channel.new", json!({"fill": "selection"})).unwrap(); - let st = s.active().unwrap(); - assert_eq!(st.channel_view.target, ChannelTarget::Alpha(0)); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert_eq!((px[0], px[5]), (Color32::WHITE, Color32::BLACK)); - // Green alone: grayscale of the green channel; with blue hidden only. - s.execute("channel.target", json!({"channel": "green"})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert_eq!(px[0], Color32::from_gray(128)); - s.execute("channel.target", json!({"channel": "composite"})).unwrap(); - s.execute("channel.setVisible", json!({"channel": "red", "visible": false})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 2, Look::default(), st.active_layer).unwrap(); - assert_eq!(px.len(), 4 * 2); - assert_eq!(px[0], Color32::from_rgb(0, 128, 0)); - } - - #[test] - fn rgb_off_shows_alpha_quick_mask_or_the_layer_mask() { - let mut s = session(); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - s.execute("channel.new", json!({"fill": "white"})).unwrap(); - s.execute("channel.setVisible", json!({"channel": "composite", "visible": true})).unwrap(); - s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); - let st = s.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert_eq!(px[0], Color32::WHITE, "Alpha alone is the channel, not the red image"); - - let mut q = session(); - q.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - q.execute("select.editInQuickMaskMode", json!({})).unwrap(); - q.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); - let st = q.active().unwrap(); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert_eq!(px[0], Color32::WHITE, "Quick Mask alone is grayscale, not the red composite"); - - let mut m = session(); - m.execute("layer.new.layer", json!({})).unwrap(); - m.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - m.execute("layer.layerMask.hideAll", json!({})).unwrap(); - m.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); - let st = m.active().unwrap(); - assert_eq!(st.channel_view.visible_colors(3), 0); - let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); - assert_eq!(px[0], Color32::BLACK, "the hidden mask reads black, not the red layer"); - } -} +mod tests; diff --git a/crates/ui-egui/src/channel_view/tests.rs b/crates/ui-egui/src/channel_view/tests.rs new file mode 100644 index 0000000000..99def559a2 --- /dev/null +++ b/crates/ui-egui/src/channel_view/tests.rs @@ -0,0 +1,354 @@ +use super::*; +use photocraft_engine::Session; +use photocraft_engine::channel_cmds::ChannelTarget; +use serde_json::json; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 4})).unwrap(); + s +} + +#[test] +fn composite_bands_keep_the_downsample_grid() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 41, "height": 700})).unwrap(); + s.execute("edit.fill", json!({"color": "#398db2"})).unwrap(); + let doc = &s.active().unwrap().doc; + let rect = doc.bounds(); + let full = photocraft_compose::render(doc, rect); + let full_ref = &full; + for factor in [1, 2, 3, 5] { + let expected: Vec<_> = (0..rect.height()) + .step_by(factor as usize) + .flat_map(|y| { + (0..rect.width()).step_by(factor as usize).map(move |x| { + let p = full_ref.get(rect.x0 + x as i32, rect.y0 + y as i32); + let a = p[3].clamp(0.0, 1.0); + [p[0] * a + 1.0 - a, p[1] * a + 1.0 - a, p[2] * a + 1.0 - a, 1.0] + }) + }) + .collect(); + assert_eq!(composite(doc, rect, factor), expected, "factor {factor}"); + } +} + +#[test] +fn channel_eyes_reuse_composite_until_pixels_change() { + let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 32})).unwrap(); + app.run("edit.fill", json!({"color": "#4080c0"})).unwrap(); + app.sync_views(); + let ctx = egui::Context::default(); + app.run("channel.setVisible", json!({"channel": "red", "visible": false})).unwrap(); + assert!(ensure(&mut app, &ctx, 0).is_some()); + let id = app.session.active().unwrap().doc.id.0; + let first = app.channel_views.get_mut(&id).unwrap().source.as_mut().unwrap(); + let original_sample = first.pixels[0]; + // Mark the cache: a recomposite overwrites it, while a freed buffer's address can come back. + first.pixels[0] = [0.0, 1.0, 0.0, 1.0]; + + app.run("channel.setVisible", json!({"channel": "green", "visible": false})).unwrap(); + assert!(ensure(&mut app, &ctx, 0).is_some()); + let reused = app.channel_views.get(&id).unwrap().source.as_ref().unwrap(); + assert_eq!(reused.pixels[0], [0.0, 1.0, 0.0, 1.0], "visibility does not recompose the pixels"); + + app.run("edit.fill", json!({"color": "#e02010"})).unwrap(); + assert!(ensure(&mut app, &ctx, 0).is_some()); + // A partial damage upload discards the source; a full redraw may replace it. + // In either case, cached samples must never refer to the pre-edit pixels. + if let Some(source) = app.channel_views.get(&id).unwrap().source.as_ref() { + assert_ne!(source.pixels[0], original_sample, "a full redraw replaces stale pixels"); + } + app.run("channel.setVisible", json!({"channel": "red", "visible": true})).unwrap(); + assert!(ensure(&mut app, &ctx, 0).is_some()); + let refreshed = app.channel_views.get(&id).unwrap().source.as_ref().unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(refreshed.revision, st.revision); + assert_ne!(refreshed.pixels[0], original_sample, "new pixels must be recomposited"); + let expected = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + let mut unused = None; + let actual = render_with_source( + &st.doc, + &st.channel_view, + st.doc.bounds(), + 1, + Look::default(), + st.active_layer, + CompositeSource { cached: Some(&refreshed.pixels), fresh: &mut unused }, + ) + .unwrap(); + assert_eq!(actual, expected, "reused pixels must preserve channel colours"); + assert!(unused.is_none(), "reuse must not create a second composite"); +} + +#[test] +fn plain_composite_draws_nothing() { + let s = session(); + let st = s.active().unwrap(); + assert!(render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).is_none()); +} + +#[test] +fn quick_mask_overlay_is_red_over_masked_areas() { + let mut s = session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap(); + s.execute("select.editInQuickMaskMode", json!({})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert_eq!(px[0], Color32::TRANSPARENT, "selected: no overlay"); + assert_eq!(px[6], Color32::from_rgba_premultiplied(128, 0, 0, 128), "masked: 50% red"); +} + +#[test] +fn quick_mask_without_selection_shows_no_overlay_in_either_mode() { + // #2743: nothing selected is a colourless mask, whichever way the colour reads. + for (before, after) in [(None, Some("selected")), (Some("selected"), None), (Some("selected"), Some("masked"))] { + let mut s = session(); + if let Some(i) = before { + s.execute("channel.options", json!({"channel": "quickMask", "indicates": i})).unwrap(); + } + s.execute("select.editInQuickMaskMode", json!({})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert!(px.iter().all(|p| *p == Color32::TRANSPARENT), "{before:?}"); + if let Some(i) = after { + s.execute("channel.options", json!({"channel": "quickMask", "indicates": i})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert!(px.iter().all(|p| *p == Color32::TRANSPARENT), "{before:?} → {i}"); + } + } + // Selected Areas with Select All: the whole canvas is coloured. + let mut s = session(); + s.execute("channel.options", json!({"channel": "quickMask", "indicates": "selected"})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + s.execute("select.editInQuickMaskMode", json!({})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert!(px.iter().all(|p| *p == Color32::from_rgba_premultiplied(128, 0, 0, 128))); +} + +#[test] +fn layer_mask_views_and_damage_on_the_downsampled_grid() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 37, "height": 21})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [37, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap(); + s.execute("view.layerMask", json!({"mode": "gray"})).unwrap(); + let st = s.active().unwrap(); + let b = st.doc.bounds(); + let full = render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap(); + assert!(full[0].r() < 10 && full[36].r() > 245 && full[0].a() == 255, "opaque grayscale ramp"); + // A sub-rect starting on the factor grid matches the same pixels of the full render. + for f in [1u32, 2, 3] { + let all = render(&st.doc, &st.channel_view, b, f, Look::default(), st.active_layer).unwrap(); + let w = b.width().div_ceil(f) as usize; + let r = Rect::new(3 * f as i32, 2 * f as i32, 30, 19); + let part = render(&st.doc, &st.channel_view, r, f, Look::default(), st.active_layer).unwrap(); + let pw = r.width().div_ceil(f) as usize; + for (i, p) in part.iter().enumerate() { + assert_eq!(*p, all[(i / pw + 2) * w + i % pw + 3], "factor {f}, pixel {i}"); + } + } + s.execute("view.layerMask", json!({"mode": "overlay"})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap(); + assert!(px[0].r() >= 124 && px[0].g() == 0 && px[0].a() >= 124, "about 50% red over the hidden end: {:?}", px[0]); + assert!(px[36].a() <= 4, "next to nothing over the revealed end: {:?}", px[36]); +} + +#[test] +fn layer_mask_views_show_the_feathered_mask() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 37, "height": 21})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [37, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap(); + s.execute("layer.layerMask.edit", json!({"feather": 4})).unwrap(); + s.execute("view.layerMask", json!({"mode": "gray"})).unwrap(); + + let st = s.active().unwrap(); + let bounds = st.doc.bounds(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + let raw = layer.mask.as_ref().unwrap().surface.sample_channel(0, 0, 0); + let effective = photocraft_compose::masks::combined_mask(layer, bounds).unwrap(); + let softened = effective.sample_channel(0, 0, 0); + assert!((softened - raw).abs() > 0.01, "the fixture has a visible feather at its edge"); + + let gray = render(&st.doc, &st.channel_view, bounds, 1, Look::default(), st.active_layer).unwrap(); + assert_eq!(gray[0], Color32::from_gray(q(softened)), "gray view uses the compositor's feathered mask"); + + s.execute("view.layerMask", json!({"mode": "overlay"})).unwrap(); + let st = s.active().unwrap(); + let overlay = render(&st.doc, &st.channel_view, bounds, 1, Look::default(), st.active_layer).unwrap(); + let alpha = 0.5 * (1.0 - softened); + let red = AlphaChannel::DEFAULT_COLOR.to_rgb(); + assert_eq!(overlay[0], Color32::from_rgba_premultiplied(q(red[0] * alpha), q(red[1] * alpha), q(red[2] * alpha), q(alpha))); +} + +/// Layer Mask Display Options: the rubylith takes their colour and opacity, alone over the +/// composite and with a colour channel hidden. +#[test] +fn layer_mask_overlay_takes_its_display_options() { + let mut s = session(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s.execute("layer.layerMask.hideAll", json!({})).unwrap(); + s.execute("view.layerMask", json!({"mode": "overlay"})).unwrap(); + let green = Look { mask_rgb: [0.0, 1.0, 0.0], mask_opacity: 0.25, ..Look::default() }; + let st = s.active().unwrap(); + let b = st.doc.bounds(); + assert_eq!(render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap()[0], Color32::from_rgba_premultiplied(128, 0, 0, 128)); + assert_eq!(render(&st.doc, &st.channel_view, b, 1, green, st.active_layer).unwrap()[0], Color32::from_rgba_premultiplied(0, 64, 0, 64)); + // Red hidden: the white picture shows cyan, then green at 25 % over it. + s.execute("channel.setVisible", json!({"channel": "red", "visible": false})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(render(&st.doc, &st.channel_view, b, 1, green, st.active_layer).unwrap()[0], Color32::from_rgb(0, 255, 191)); +} + +/// `cargo test --release -p photocraft-ui-egui --lib mask_view_switch_24mp -- --ignored --nocapture` +#[test] +#[ignore = "benchmark"] +fn mask_view_switch_24mp() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 6000, "height": 4000})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#d0402b"})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [6000, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap(); + let factor = 6000u32.div_ceil(MAX_SIDE); + for mode in ["gray", "overlay"] { + s.execute("view.layerMask", json!({"mode": mode})).unwrap(); + let st = s.active().unwrap(); + let mut best = f64::MAX; + for _ in 0..8 { + let t = std::time::Instant::now(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), factor, Look::default(), st.active_layer).unwrap(); + let img = egui::ColorImage::new([3000, 2000], px); + std::hint::black_box(img); + best = best.min(t.elapsed().as_secs_f64() * 1000.0); + } + println!("24 MP mask view {mode}: {best:.1} ms (render at 1/{factor})"); + } +} + +/// Interface ▸ Show Channels in Color (#2385): a solo RGB / CMYK channel tints the canvas +/// instead of staying gray, like the panel thumbnails wired in #1986. +#[test] +fn show_channels_in_color_tints_the_canvas() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb"})).unwrap(); + s.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); + s.execute("channel.target", json!({"channel": "green"})).unwrap(); + let st = s.active().unwrap(); + let b = st.doc.bounds(); + assert_eq!(render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap()[0], Color32::from_gray(128)); + assert_eq!( + render(&st.doc, &st.channel_view, b, 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0], + Color32::from_rgb(0, 128, 0) + ); + + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4, "mode": "cmyk"})).unwrap(); + s.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); + s.execute("channel.target", json!({"channel": "cyan"})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0]; + assert!(px.r() < 100 && px.g() > 150 && px.b() > 150, "cyan ink, not gray: {px:?}"); + let gray = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap()[0]; + assert_eq!(gray.r(), gray.g(), "off stays grayscale"); +} + +/// Lab: a and b tint over a neutral Lightness; Lightness itself stays gray (Adobe's exception). +#[test] +fn show_channels_in_color_lab_lightness_stays_gray() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4, "mode": "lab"})).unwrap(); + s.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); + let b = s.active().unwrap().doc.bounds(); + s.execute("channel.target", json!({"channel": {"color": 0}})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, b, 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0]; + let spread = px.r().max(px.g().max(px.b())) as i32 - px.r().min(px.g().min(px.b())) as i32; + assert!(spread <= 3, "Lightness stays gray: {px:?}"); + s.execute("channel.target", json!({"channel": {"color": 1}})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, b, 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0]; + assert!(px.r() != px.g() || px.g() != px.b(), "a channel is tinted, not gray: {px:?}"); +} + +/// The canvas texture cache is keyed by the preference, so toggling it rebuilds the view. +#[test] +fn ensure_honours_show_channels_in_color() { + let mut app = PhotocraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.sync_views(); + app.run("channel.target", json!({"channel": "green"})).unwrap(); + let ctx = egui::Context::default(); + assert!(ensure(&mut app, &ctx, 0).is_some()); + let key_off = app.channel_views.values().next().unwrap().key; + app.session.execute("prefs.set", json!({"values": {"interface.showChannelsInColor": true}})).unwrap(); + assert!(ensure(&mut app, &ctx, 0).is_some()); + let key_on = app.channel_views.values().next().unwrap().key; + assert_ne!(key_off, key_on, "the preference changes the cached view key"); + // So do the Layer Mask Display Options. + app.session.execute("channel.options", json!({"channel": "mask", "color": "#00ff00", "opacity": 70})).unwrap(); + assert!(ensure(&mut app, &ctx, 0).is_some()); + assert_ne!(app.channel_views.values().next().unwrap().key, key_on, "the overlay options change the cached view key"); +} + +#[test] +fn solo_alpha_is_grayscale_and_colour_channels_split() { + let mut s = session(); + s.execute("edit.fill", json!({"color": "#ff8000"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 2, "height": 4})).unwrap(); + s.execute("channel.new", json!({"fill": "selection"})).unwrap(); + let st = s.active().unwrap(); + assert_eq!(st.channel_view.target, ChannelTarget::Alpha(0)); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert_eq!((px[0], px[5]), (Color32::WHITE, Color32::BLACK)); + // Green alone: grayscale of the green channel; with blue hidden only. + s.execute("channel.target", json!({"channel": "green"})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert_eq!(px[0], Color32::from_gray(128)); + s.execute("channel.target", json!({"channel": "composite"})).unwrap(); + s.execute("channel.setVisible", json!({"channel": "red", "visible": false})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 2, Look::default(), st.active_layer).unwrap(); + assert_eq!(px.len(), 4 * 2); + assert_eq!(px[0], Color32::from_rgb(0, 128, 0)); +} + +#[test] +fn rgb_off_shows_alpha_quick_mask_or_the_layer_mask() { + let mut s = session(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + s.execute("channel.setVisible", json!({"channel": "composite", "visible": true})).unwrap(); + s.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); + let st = s.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert_eq!(px[0], Color32::WHITE, "Alpha alone is the channel, not the red image"); + + let mut q = session(); + q.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + q.execute("select.editInQuickMaskMode", json!({})).unwrap(); + q.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); + let st = q.active().unwrap(); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert_eq!(px[0], Color32::WHITE, "Quick Mask alone is grayscale, not the red composite"); + + let mut m = session(); + m.execute("layer.new.layer", json!({})).unwrap(); + m.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + m.execute("layer.layerMask.hideAll", json!({})).unwrap(); + m.execute("channel.setVisible", json!({"channel": "composite", "visible": false})).unwrap(); + let st = m.active().unwrap(); + assert_eq!(st.channel_view.visible_colors(3), 0); + let px = render(&st.doc, &st.channel_view, st.doc.bounds(), 1, Look::default(), st.active_layer).unwrap(); + assert_eq!(px[0], Color32::BLACK, "the hidden mask reads black, not the red layer"); +} From 0b5b0faf2eb2385e4d518cfc40a6fd5552aa5e94 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:17 +0000 Subject: [PATCH 091/259] refactor(ui-egui): move vp_ui.rs tests to vp_ui/tests.rs --- crates/ui-egui/src/vp_ui.rs | 417 +----------------------------- crates/ui-egui/src/vp_ui/tests.rs | 414 +++++++++++++++++++++++++++++ 2 files changed, 415 insertions(+), 416 deletions(-) create mode 100644 crates/ui-egui/src/vp_ui/tests.rs diff --git a/crates/ui-egui/src/vp_ui.rs b/crates/ui-egui/src/vp_ui.rs index e1e1f8e449..f057fd2bcf 100644 --- a/crates/ui-egui/src/vp_ui.rs +++ b/crates/ui-egui/src/vp_ui.rs @@ -1296,419 +1296,4 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } #[cfg(test)] -mod tests { - use super::*; - - fn app_with_layer() -> (egui::Context, PhotocraftApp) { - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", json!({"width": 240, "height": 160, "depth": 16})).unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); - app.sync_views(); - (ctx, app) - } - - #[test] - fn four_clicks_make_a_plane_and_ok_pastes_in_one_step() { - let (ctx, mut app) = app_with_layer(); - // Something to paste: a red square on the clipboard. - app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); - app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.session.execute("edit.copy", json!({})).unwrap(); - app.session.execute("select.deselect", json!({})).unwrap(); - crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); - let click = |app: &mut PhotocraftApp, x: f64, y: f64| { - crate::distort_ui::pointer(app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE); - crate::distort_ui::pointer(app, ToolEvent::Up { x, y }, egui::Modifiers::NONE); - }; - // A floor receding to the top, clicked counter-clockwise from the bottom-left. - for (x, y) in [(20.0, 150.0), (220.0, 150.0), (170.0, 60.0), (70.0, 60.0)] { - click(&mut app, x, y); - } - let s = app.distort.vanishing.as_ref().unwrap(); - assert_eq!(s.planes.len(), 1); - assert_eq!(s.planes[0].corners, [[70.0, 60.0], [170.0, 60.0], [220.0, 150.0], [20.0, 150.0]], "clockwise from the top-left"); - assert_eq!(s.tool, VpTool::EditPlane); - assert_eq!(s.describe()["planes"][0]["check"], "valid"); - // Edit Plane: drag the top edge node up; the edge slides along the perspective. - let top = s.edge_nodes(0).unwrap()[0]; - crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: top[0], y: top[1], pressure: 1.0 }, egui::Modifiers::NONE); - crate::distort_ui::pointer(&mut app, ToolEvent::Up { x: top[0], y: top[1] - 15.0 }, egui::Modifiers::NONE); - let c = app.distort.vanishing.as_ref().unwrap().planes[0].corners; - assert!(c[0][1] < 60.0 && c[1][1] < 60.0 && c[1][0] - c[0][0] < 100.0, "taller and narrower at the far edge: {c:?}"); - assert_eq!(c[2], [220.0, 150.0]); - let before = app.session.active().unwrap().history.past_len(); - commit(&mut app).unwrap(); - assert!(app.distort.vanishing.is_none()); - assert_eq!(app.session.active().unwrap().history.past_len(), before + 1); - // The paste landed on the plane: red at its middle, blue outside it. - let st = app.session.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - let h = VpPlane { corners: c }.homography().unwrap(); - let (x, y) = h.apply(0.5, 0.35); - assert!(l.rgba(x as i32, y as i32)[0] > 0.9, "{:?}", l.rgba(x as i32, y as i32)); - assert!(l.rgba(230, 20)[0] < 0.5, "outside the plane"); - } - - #[test] - fn ctrl_drag_tears_off_a_wall_and_the_stamp_clones_in_one_step() { - let (ctx, mut app) = app_with_layer(); - // A green mark near the floor's front edge to clone. - app.session.execute("select.rect", json!({"x": 100, "y": 135, "width": 40, "height": 8})).unwrap(); - app.session.execute("edit.fill", json!({"color": "#00ff00"})).unwrap(); - app.session.execute("select.deselect", json!({})).unwrap(); - crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); - control(&mut app, &json!({"planes": [{"corners": [[70, 60], [170, 60], [220, 150], [20, 150]]}]})).unwrap(); - let ev = |app: &mut PhotocraftApp, e: ToolEvent, m: egui::Modifiers| crate::distort_ui::pointer(app, e, m); - let drag = |app: &mut PhotocraftApp, a: [f64; 2], b: [f64; 2], m: egui::Modifiers| { - ev(app, ToolEvent::Down { x: a[0], y: a[1], pressure: 1.0 }, m); - ev(app, ToolEvent::Move { x: (a[0] + b[0]) / 2.0, y: (a[1] + b[1]) / 2.0, pressure: 1.0 }, m); - ev(app, ToolEvent::Up { x: b[0], y: b[1] }, m); - }; - fn vp(app: &PhotocraftApp) -> &VpSession { - app.distort.vanishing.as_ref().unwrap() - } - - // Ctrl/Cmd-drag the top edge node up: a wall torn off the floor's far edge, 90° to it. - let top = vp(&app).edge_nodes(0).unwrap()[0]; - drag(&mut app, top, [top[0], top[1] - 35.0], egui::Modifiers::COMMAND); - let s = vp(&app); - assert_eq!(s.planes.len(), 2); - let t = s.torn[1].unwrap(); - assert_eq!((t.from, t.edge, t.angle), (0, Edge::Top, 90.0)); - let c = s.planes[1].corners; - assert!((c[0][1] + c[1][1]) / 2.0 < 40.0, "the far edge followed the pointer up: {c:?}"); - assert_ne!(s.describe()["planes"][1]["check"], "invalid"); - assert_eq!(s.params()["planes"][1], json!({"from": 0, "edge": "top", "angle": 90.0, "depth": t.depth})); - // Alt-dragging its far edge node turns it; editing the floor carries it along. - let far = s.edge_nodes(1).unwrap()[0]; - drag(&mut app, far, [far[0], far[1] + 12.0], egui::Modifiers::ALT); - assert_ne!(vp(&app).torn[1].unwrap().angle, 90.0); - let before = vp(&app).planes[1].corners; - drag(&mut app, [220.0, 150.0], [228.0, 150.0], egui::Modifiers::NONE); - assert_ne!(vp(&app).planes[1].corners, before); - assert!(vp(&app).torn[1].is_some()); - - // Stamp: painting needs a source first; Alt-click sets it on the floor's green mark. - control(&mut app, &json!({"tool": "stamp", "stamp": {"diameter": 12, "hardness": 80}})).unwrap(); - drag(&mut app, [120.0, 100.0], [120.0, 100.0], egui::Modifiers::NONE); - assert!(vp(&app).strokes.is_empty() && app.ui.status.contains("Alt-click"), "{}", app.ui.status); - drag(&mut app, [120.0, 139.0], [120.0, 139.0], egui::Modifiers::ALT); - assert_eq!(vp(&app).source, Some([120.0, 139.0])); - drag(&mut app, [118.0, 100.0], [126.0, 100.0], egui::Modifiers::NONE); - assert_eq!(vp(&app).strokes.len(), 1); - assert!(vp(&app).strokes[0].points.len() >= 3, "dabs along the drag"); - // The canvas shows the stroke; the document is untouched until OK. - let layer = app.session.active().unwrap().active_layer.unwrap(); - let green = |d: &Document| d.layer(layer).unwrap().surface().unwrap().rgba(122, 100)[1]; - let (shown, key) = crate::distort_ui::display_doc(&app, 0).expect("a stamp preview"); - assert!(green(&shown) > 0.8, "{}", green(&shown)); - let st = app.session.active().unwrap(); - assert!(green(&st.doc) < 0.6); - let area = damage(&app, st.doc.id, st.revision, 0, key).unwrap(); - assert!(area.contains(122, 100) && !area.contains(20, 20), "only the stroke recomposites: {area:?}"); - - let before = app.session.active().unwrap().history.past_len(); - let r = commit(&mut app).unwrap(); - assert_eq!(r["committed"], true, "{r}"); - let st = app.session.active().unwrap(); - assert_eq!(st.history.past_len(), before + 1, "one history step for the whole session"); - assert!(green(&st.doc) > 0.8, "{}", green(&st.doc)); - } - - #[test] - fn undo_steps_back_through_clone_strokes_and_tear_offs() { - let (ctx, mut app) = app_with_layer(); - crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); - control(&mut app, &json!({"planes": [{"corners": [[70, 60], [170, 60], [220, 150], [20, 150]]}]})).unwrap(); - let drag = |app: &mut PhotocraftApp, a: [f64; 2], b: [f64; 2], m: egui::Modifiers| { - crate::distort_ui::pointer(app, ToolEvent::Down { x: a[0], y: a[1], pressure: 1.0 }, m); - crate::distort_ui::pointer(app, ToolEvent::Move { x: b[0], y: b[1], pressure: 1.0 }, m); - crate::distort_ui::pointer(app, ToolEvent::Up { x: b[0], y: b[1] }, m); - }; - let step = |app: &mut PhotocraftApp, st: Step| { - app.distort.vanishing.as_mut().unwrap().step(st); - sync_preview(app); - }; - let top = app.distort.vanishing.as_ref().unwrap().edge_nodes(0).unwrap()[0]; - drag(&mut app, top, [top[0], top[1] - 35.0], egui::Modifiers::COMMAND); - control(&mut app, &json!({"tool": "stamp", "source": [120, 139]})).unwrap(); - drag(&mut app, [118.0, 100.0], [126.0, 100.0], egui::Modifiers::NONE); - assert_eq!(app.distort.vanishing.as_ref().unwrap().strokes.len(), 1); - assert!(crate::distort_ui::display_doc(&app, 0).is_some()); - - // ⌘Z takes the stroke back (and its preview), then the source, then the torn-off wall. - step(&mut app, Step::Undo); - assert!(app.distort.vanishing.as_ref().unwrap().strokes.is_empty()); - assert!(crate::distort_ui::display_doc(&app, 0).is_none(), "no stamp preview left"); - step(&mut app, Step::Undo); - assert_eq!(app.distort.vanishing.as_ref().unwrap().source, None); - step(&mut app, Step::Undo); - let s = app.distort.vanishing.as_ref().unwrap(); - assert_eq!((s.planes.len(), s.torn.len()), (1, 1)); - // ⇧⌘Z brings them back. - for _ in 0..3 { - step(&mut app, Step::Redo); - } - let s = app.distort.vanishing.as_ref().unwrap(); - assert_eq!((s.planes.len(), s.strokes.len()), (2, 1)); - assert!(s.torn[1].is_some()); - assert!(crate::distort_ui::display_doc(&app, 0).is_some(), "the stroke shows again"); - } - #[test] - fn overlapping_stamp_preview_matches_commit_across_batches() { - for new_layer in [false, true] { - let (ctx, mut app) = app_with_layer(); - app.session - .edit("pattern", |doc, active| { - let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for x in 0..240 { - surf.fill_rect(Rect::new(x, 0, x + 1, 160), &[x as f32 / 240.0, (x % 7) as f32 / 6.0, 0.3, 1.0]); - } - Ok(()) - }) - .unwrap(); - crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); - control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}]})).unwrap(); - let points = [[80.0, 80.0], [84.0, 80.0], [88.0, 80.0], [92.0, 80.0]]; - let s = app.distort.vanishing.as_mut().unwrap(); - s.new_layer = new_layer; - s.strokes.push(CloneSpec { source: [76.0, 80.0], points: points[..2].to_vec(), size: 12.0, hardness: 0.8, opacity: 1.0 }); - assert!(s.paint_preview(|| 1)); - s.strokes[0].points.extend_from_slice(&points[2..]); - assert!(s.paint_preview(|| 2)); - let (shown, _) = s.shown().unwrap(); - let expected = photocraft_compose::flatten(&shown).px; - assert_ne!(expected, photocraft_compose::flatten(&app.session.active().unwrap().doc).px); - commit(&mut app).unwrap(); - assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected, "newLayer={new_layer}"); - } - } - - /// A red square on the clipboard (copied from the layer's top-left corner). - fn copy_red_square(app: &mut PhotocraftApp) { - app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap(); - app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.session.execute("edit.copy", json!({})).unwrap(); - app.session.execute("select.deselect", json!({})).unwrap(); - } - - #[test] - fn stamp_preview_paints_over_the_paste_like_ok() { - for new_layer in [false, true] { - let (ctx, mut app) = app_with_layer(); - copy_red_square(&mut app); - crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); - control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}], "newLayer": new_layer})).unwrap(); - let s = app.distort.vanishing.as_ref().unwrap(); - assert!(s.paste && s.paste_plane() == Some(0), "the clipboard pastes by default"); - // The paste covers x 65..175 from y 45 down. One stroke clones it onto the base - // layer, the other paints across its right edge. - control( - &mut app, - &json!({"clone": [ - {"source": [100, 60], "points": [[40, 120], [48, 120], [56, 120]], "size": 16, "hardness": 80}, - {"source": [40, 130], "points": [[150, 60], [170, 60], [190, 60]], "size": 16, "hardness": 80}, - ]}), - ) - .unwrap(); - let s = app.distort.vanishing.as_ref().unwrap(); - assert!(s.preview_has_paste(), "the preview shows the paste, so the overlay isn't drawn over the strokes"); - let (shown, _) = s.shown().unwrap(); - let expected = photocraft_compose::flatten(&shown).px; - commit(&mut app).unwrap(); - assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected, "newLayer={new_layer}"); - } - } - - #[test] - fn moving_the_paste_repaints_the_stamp_preview() { - let (ctx, mut app) = app_with_layer(); - copy_red_square(&mut app); - crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); - control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}]})).unwrap(); - control(&mut app, &json!({"clone": [{"source": [200, 130], "points": [[30, 130]], "size": 8}]})).unwrap(); - let red = |app: &PhotocraftApp, x: i32, y: i32| { - let (shown, _) = app.distort.vanishing.as_ref().unwrap().shown().unwrap(); - let l = app.session.active().unwrap().active_layer.unwrap(); - shown.layer(l).unwrap().surface().unwrap().rgba(x, y)[0] - }; - assert!(red(&app, 100, 60) > 0.9); - control(&mut app, &json!({"pasteAt": [0.0, 0.5]})).unwrap(); - assert!(red(&app, 100, 60) < 0.5, "the paste left its old place"); - assert!(red(&app, 30, 100) > 0.9, "and shows at the new one"); - control(&mut app, &json!({"paste": false})).unwrap(); - assert!(red(&app, 30, 100) < 0.5, "paste off: gone from the preview"); - assert!(!app.distort.vanishing.as_ref().unwrap().preview_has_paste()); - } - - #[test] - fn dragging_the_paste_shows_it_once() { - let (ctx, mut app) = app_with_layer(); - copy_red_square(&mut app); - crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); - control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}], "tool": "edit"})).unwrap(); - control(&mut app, &json!({"clone": [{"source": [200, 130], "points": [[30, 130]], "size": 8}]})).unwrap(); - let layer = app.session.active().unwrap().active_layer.unwrap(); - let red = |app: &PhotocraftApp, x: i32, y: i32| { - let (shown, _) = crate::distort_ui::display_doc(app, 0)?; - Some(shown.layer(layer).unwrap().surface().unwrap().rgba(x, y)[0]) - }; - assert!(red(&app, 100, 60).unwrap() > 0.9, "the paste is in the preview"); - let ev = |app: &mut PhotocraftApp, e: ToolEvent| crate::distort_ui::pointer(app, e, egui::Modifiers::NONE); - ev(&mut app, ToolEvent::Down { x: 100.0, y: 60.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Move { x: 60.0, y: 100.0, pressure: 1.0 }); - // Mid-drag: no copy left behind at the old place, only the overlay at the pointer. - assert!(red(&app, 100, 60).is_none_or(|r| r < 0.5), "{:?}", red(&app, 100, 60)); - assert!(app.distort.vanishing.as_ref().unwrap().paste_overlay(), "the overlay draws the moving paste"); - ev(&mut app, ToolEvent::Up { x: 60.0, y: 100.0 }); - assert!(red(&app, 100, 60).unwrap() < 0.5); - assert!(red(&app, 60, 100).unwrap() > 0.9, "released: the preview pastes at the new place"); - assert!(!app.distort.vanishing.as_ref().unwrap().paste_overlay()); - // A plane corner drag freezes the preview, paste included, until release: one copy. - ev(&mut app, ToolEvent::Down { x: 230.0, y: 150.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Move { x: 236.0, y: 156.0, pressure: 1.0 }); - let s = app.distort.vanishing.as_ref().unwrap(); - assert!(matches!(s.drag, Some(Drag::Corner { .. }))); - assert!(red(&app, 60, 100).unwrap() > 0.9 && !s.paste_overlay(), "frozen preview, no overlay on top"); - ev(&mut app, ToolEvent::Up { x: 236.0, y: 156.0 }); - let s = app.distort.vanishing.as_ref().unwrap(); - assert!(s.preview_has_paste() && !s.paste_overlay()); - } - - #[test] - fn new_layer_stamp_preview_stays_on_the_canvas() { - let (ctx, mut app) = app_with_layer(); - // A red stripe where the first dab samples, so cloning it changes pixels. - app.session.execute("select.rect", json!({"x": 130, "y": 70, "width": 20, "height": 20})).unwrap(); - app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - app.session.execute("select.deselect", json!({})).unwrap(); - crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); - control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}], "newLayer": true})).unwrap(); - // The second dab lies left of the canvas and samples the canvas 100 px to its right. - control(&mut app, &json!({"clone": [{"source": [140, 80], "points": [[40, 80], [-30, 80]], "size": 16}]})).unwrap(); - let s = app.distort.vanishing.as_ref().unwrap(); - let out = s.preview.as_ref().unwrap().out.content_bounds(); - assert!(!out.is_empty() && s.canvas.contains_rect(&out), "{out:?}"); - let st = app.session.active().unwrap(); - let area = damage(&app, st.doc.id, st.revision, 0, s.shown().unwrap().1).unwrap(); - assert!(s.canvas.contains_rect(&area), "{area:?}"); - } - - #[test] - fn deleting_the_last_plane_drops_the_stamp_preview() { - let (ctx, mut app) = app_with_layer(); - crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); - control(&mut app, &json!({"planes": [{"corners": [[70, 60], [170, 60], [220, 150], [20, 150]]}]})).unwrap(); - control(&mut app, &json!({"clone": [{"source": [120, 139], "points": [[118, 100], [126, 100]], "size": 12}]})).unwrap(); - assert!(crate::distort_ui::display_doc(&app, 0).is_some()); - let s = app.distort.vanishing.as_mut().unwrap(); - s.selected = Some(0); - s.delete_selected(); - sync_preview(&mut app); - assert!(app.distort.vanishing.as_ref().unwrap().planes.is_empty()); - assert!(crate::distort_ui::display_doc(&app, 0).is_none(), "no strokes shown without a plane"); - } - - /// Opens the mode on the active layer of `app_with_layer` and stamps one stroke. - fn stamp_a_stroke(app: &mut PhotocraftApp, ctx: &egui::Context) { - crate::distort_ui::menu(app, ctx, VP, &json!({})).unwrap().unwrap(); - control(app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}]})).unwrap(); - control(app, &json!({"clone": [{"source": [60, 80], "points": [[120, 80], [126, 80]], "size": 12}]})).unwrap(); - } - - #[test] - fn stamp_preview_is_not_shown_on_another_document() { - let (ctx, mut app) = app_with_layer(); - stamp_a_stroke(&mut app, &ctx); - assert!(crate::distort_ui::display_doc(&app, 0).is_some()); - app.session.execute("file.new", json!({"width": 32, "height": 32, "depth": 8})).unwrap(); - let active = app.session.active_index().unwrap(); - // The session stays until drop_foreign; the preview must not follow this document (#5115). - assert!(app.distort.vanishing.is_some()); - assert!(crate::distort_ui::display_doc(&app, active).is_none()); - } - - #[test] - fn ok_paints_the_layer_the_mode_was_opened_on() { - for new_layer in [false, true] { - let (ctx, mut app) = app_with_layer(); - let layer = app.session.active().unwrap().active_layer.unwrap(); - app.session - .edit("stripe", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(50, 70, 70, 90), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - stamp_a_stroke(&mut app, &ctx); - app.distort.vanishing.as_mut().unwrap().new_layer = new_layer; - sync_preview(&mut app); - // Another layer is picked while the mode is open (it isn't modal). - app.session.execute("layer.new.layer", json!({"name": "other"})).unwrap(); - let other = app.session.active().unwrap().active_layer.unwrap(); - sync_preview(&mut app); - let expected = photocraft_compose::flatten(&crate::distort_ui::display_doc(&app, 0).unwrap().0).px; - commit(&mut app).unwrap(); - let d = &app.session.active().unwrap().doc; - assert!(d.layer(other).unwrap().surface().unwrap().content_bounds().is_empty(), "newLayer={new_layer}"); - if !new_layer { - assert!(d.layer(layer).unwrap().surface().unwrap().rgba(120, 80)[0] > 0.9, "the stroke lands on the session's layer"); - // And it becomes active, so Fade and a colour-channel target follow it. - assert_eq!(app.session.active().unwrap().active_layer, Some(layer)); - } - assert_eq!(photocraft_compose::flatten(d).px, expected, "newLayer={new_layer}"); - } - } - - #[test] - fn an_edit_under_the_mode_shows_on_the_canvas() { - let (ctx, mut app) = app_with_layer(); - app.session - .edit("stripe", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(50, 70, 70, 90), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - stamp_a_stroke(&mut app, &ctx); - let before = crate::distort_ui::display_doc(&app, 0).unwrap(); - app.session - .edit("edit", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(200, 20, 220, 40), &[0.0, 1.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - // Not the stale preview, even before the mode catches up. - assert!(crate::distort_ui::display_doc(&app, 0).is_none_or(|(d, _)| !Arc::ptr_eq(&d, &before.0))); - // The canvas catches up before it draws: the strokes over the edit, no frame without them. - let (shown, key) = crate::canvas::display_doc(&mut app, 0); - assert_ne!(key, before.1); - let st = app.session.active().unwrap(); - let layer = st.active_layer.unwrap(); - let px = shown.layer(layer).unwrap().surface().unwrap(); - assert!(px.rgba(210, 30)[1] > 0.9, "the edit shows: {:?}", px.rgba(210, 30)); - assert!(px.rgba(120, 80) != st.doc.layer(layer).unwrap().surface().unwrap().rgba(120, 80), "and so does the stroke"); - let expected = photocraft_compose::flatten(&shown).px; - commit(&mut app).unwrap(); - assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected); - } - - #[test] - fn selecting_another_layer_keeps_the_stamp_preview() { - let (ctx, mut app) = app_with_layer(); - let layer = app.session.active().unwrap().active_layer.unwrap(); - app.session.execute("layer.new.layer", json!({"name": "other"})).unwrap(); - app.session.execute("layer.select", json!({"layer": layer.0})).unwrap(); - app.sync_views(); - stamp_a_stroke(&mut app, &ctx); - let before = crate::canvas::display_doc(&mut app, 0); - let (doc, revision) = app.session.active().map(|st| (st.doc.clone(), st.revision)).unwrap(); - app.session.execute("layer.select", json!({"layer": "other"})).unwrap(); - let st = app.session.active().unwrap(); - assert!(st.revision != revision && Arc::ptr_eq(&st.doc, &doc), "a selection change leaves the pixels alone"); - // Same preview, same key: nothing to repaint or recomposite. - let after = crate::canvas::display_doc(&mut app, 0); - assert!(Arc::ptr_eq(&after.0, &before.0)); - assert_eq!(after.1, before.1); - } -} +mod tests; diff --git a/crates/ui-egui/src/vp_ui/tests.rs b/crates/ui-egui/src/vp_ui/tests.rs new file mode 100644 index 0000000000..19f7786e33 --- /dev/null +++ b/crates/ui-egui/src/vp_ui/tests.rs @@ -0,0 +1,414 @@ +use super::*; + +fn app_with_layer() -> (egui::Context, PhotocraftApp) { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 240, "height": 160, "depth": 16})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); + app.sync_views(); + (ctx, app) +} + +#[test] +fn four_clicks_make_a_plane_and_ok_pastes_in_one_step() { + let (ctx, mut app) = app_with_layer(); + // Something to paste: a red square on the clipboard. + app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("edit.copy", json!({})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + let click = |app: &mut PhotocraftApp, x: f64, y: f64| { + crate::distort_ui::pointer(app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE); + crate::distort_ui::pointer(app, ToolEvent::Up { x, y }, egui::Modifiers::NONE); + }; + // A floor receding to the top, clicked counter-clockwise from the bottom-left. + for (x, y) in [(20.0, 150.0), (220.0, 150.0), (170.0, 60.0), (70.0, 60.0)] { + click(&mut app, x, y); + } + let s = app.distort.vanishing.as_ref().unwrap(); + assert_eq!(s.planes.len(), 1); + assert_eq!(s.planes[0].corners, [[70.0, 60.0], [170.0, 60.0], [220.0, 150.0], [20.0, 150.0]], "clockwise from the top-left"); + assert_eq!(s.tool, VpTool::EditPlane); + assert_eq!(s.describe()["planes"][0]["check"], "valid"); + // Edit Plane: drag the top edge node up; the edge slides along the perspective. + let top = s.edge_nodes(0).unwrap()[0]; + crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: top[0], y: top[1], pressure: 1.0 }, egui::Modifiers::NONE); + crate::distort_ui::pointer(&mut app, ToolEvent::Up { x: top[0], y: top[1] - 15.0 }, egui::Modifiers::NONE); + let c = app.distort.vanishing.as_ref().unwrap().planes[0].corners; + assert!(c[0][1] < 60.0 && c[1][1] < 60.0 && c[1][0] - c[0][0] < 100.0, "taller and narrower at the far edge: {c:?}"); + assert_eq!(c[2], [220.0, 150.0]); + let before = app.session.active().unwrap().history.past_len(); + commit(&mut app).unwrap(); + assert!(app.distort.vanishing.is_none()); + assert_eq!(app.session.active().unwrap().history.past_len(), before + 1); + // The paste landed on the plane: red at its middle, blue outside it. + let st = app.session.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + let h = VpPlane { corners: c }.homography().unwrap(); + let (x, y) = h.apply(0.5, 0.35); + assert!(l.rgba(x as i32, y as i32)[0] > 0.9, "{:?}", l.rgba(x as i32, y as i32)); + assert!(l.rgba(230, 20)[0] < 0.5, "outside the plane"); +} + +#[test] +fn ctrl_drag_tears_off_a_wall_and_the_stamp_clones_in_one_step() { + let (ctx, mut app) = app_with_layer(); + // A green mark near the floor's front edge to clone. + app.session.execute("select.rect", json!({"x": 100, "y": 135, "width": 40, "height": 8})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#00ff00"})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[70, 60], [170, 60], [220, 150], [20, 150]]}]})).unwrap(); + let ev = |app: &mut PhotocraftApp, e: ToolEvent, m: egui::Modifiers| crate::distort_ui::pointer(app, e, m); + let drag = |app: &mut PhotocraftApp, a: [f64; 2], b: [f64; 2], m: egui::Modifiers| { + ev(app, ToolEvent::Down { x: a[0], y: a[1], pressure: 1.0 }, m); + ev(app, ToolEvent::Move { x: (a[0] + b[0]) / 2.0, y: (a[1] + b[1]) / 2.0, pressure: 1.0 }, m); + ev(app, ToolEvent::Up { x: b[0], y: b[1] }, m); + }; + fn vp(app: &PhotocraftApp) -> &VpSession { + app.distort.vanishing.as_ref().unwrap() + } + + // Ctrl/Cmd-drag the top edge node up: a wall torn off the floor's far edge, 90° to it. + let top = vp(&app).edge_nodes(0).unwrap()[0]; + drag(&mut app, top, [top[0], top[1] - 35.0], egui::Modifiers::COMMAND); + let s = vp(&app); + assert_eq!(s.planes.len(), 2); + let t = s.torn[1].unwrap(); + assert_eq!((t.from, t.edge, t.angle), (0, Edge::Top, 90.0)); + let c = s.planes[1].corners; + assert!((c[0][1] + c[1][1]) / 2.0 < 40.0, "the far edge followed the pointer up: {c:?}"); + assert_ne!(s.describe()["planes"][1]["check"], "invalid"); + assert_eq!(s.params()["planes"][1], json!({"from": 0, "edge": "top", "angle": 90.0, "depth": t.depth})); + // Alt-dragging its far edge node turns it; editing the floor carries it along. + let far = s.edge_nodes(1).unwrap()[0]; + drag(&mut app, far, [far[0], far[1] + 12.0], egui::Modifiers::ALT); + assert_ne!(vp(&app).torn[1].unwrap().angle, 90.0); + let before = vp(&app).planes[1].corners; + drag(&mut app, [220.0, 150.0], [228.0, 150.0], egui::Modifiers::NONE); + assert_ne!(vp(&app).planes[1].corners, before); + assert!(vp(&app).torn[1].is_some()); + + // Stamp: painting needs a source first; Alt-click sets it on the floor's green mark. + control(&mut app, &json!({"tool": "stamp", "stamp": {"diameter": 12, "hardness": 80}})).unwrap(); + drag(&mut app, [120.0, 100.0], [120.0, 100.0], egui::Modifiers::NONE); + assert!(vp(&app).strokes.is_empty() && app.ui.status.contains("Alt-click"), "{}", app.ui.status); + drag(&mut app, [120.0, 139.0], [120.0, 139.0], egui::Modifiers::ALT); + assert_eq!(vp(&app).source, Some([120.0, 139.0])); + drag(&mut app, [118.0, 100.0], [126.0, 100.0], egui::Modifiers::NONE); + assert_eq!(vp(&app).strokes.len(), 1); + assert!(vp(&app).strokes[0].points.len() >= 3, "dabs along the drag"); + // The canvas shows the stroke; the document is untouched until OK. + let layer = app.session.active().unwrap().active_layer.unwrap(); + let green = |d: &Document| d.layer(layer).unwrap().surface().unwrap().rgba(122, 100)[1]; + let (shown, key) = crate::distort_ui::display_doc(&app, 0).expect("a stamp preview"); + assert!(green(&shown) > 0.8, "{}", green(&shown)); + let st = app.session.active().unwrap(); + assert!(green(&st.doc) < 0.6); + let area = damage(&app, st.doc.id, st.revision, 0, key).unwrap(); + assert!(area.contains(122, 100) && !area.contains(20, 20), "only the stroke recomposites: {area:?}"); + + let before = app.session.active().unwrap().history.past_len(); + let r = commit(&mut app).unwrap(); + assert_eq!(r["committed"], true, "{r}"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), before + 1, "one history step for the whole session"); + assert!(green(&st.doc) > 0.8, "{}", green(&st.doc)); +} + +#[test] +fn undo_steps_back_through_clone_strokes_and_tear_offs() { + let (ctx, mut app) = app_with_layer(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[70, 60], [170, 60], [220, 150], [20, 150]]}]})).unwrap(); + let drag = |app: &mut PhotocraftApp, a: [f64; 2], b: [f64; 2], m: egui::Modifiers| { + crate::distort_ui::pointer(app, ToolEvent::Down { x: a[0], y: a[1], pressure: 1.0 }, m); + crate::distort_ui::pointer(app, ToolEvent::Move { x: b[0], y: b[1], pressure: 1.0 }, m); + crate::distort_ui::pointer(app, ToolEvent::Up { x: b[0], y: b[1] }, m); + }; + let step = |app: &mut PhotocraftApp, st: Step| { + app.distort.vanishing.as_mut().unwrap().step(st); + sync_preview(app); + }; + let top = app.distort.vanishing.as_ref().unwrap().edge_nodes(0).unwrap()[0]; + drag(&mut app, top, [top[0], top[1] - 35.0], egui::Modifiers::COMMAND); + control(&mut app, &json!({"tool": "stamp", "source": [120, 139]})).unwrap(); + drag(&mut app, [118.0, 100.0], [126.0, 100.0], egui::Modifiers::NONE); + assert_eq!(app.distort.vanishing.as_ref().unwrap().strokes.len(), 1); + assert!(crate::distort_ui::display_doc(&app, 0).is_some()); + + // ⌘Z takes the stroke back (and its preview), then the source, then the torn-off wall. + step(&mut app, Step::Undo); + assert!(app.distort.vanishing.as_ref().unwrap().strokes.is_empty()); + assert!(crate::distort_ui::display_doc(&app, 0).is_none(), "no stamp preview left"); + step(&mut app, Step::Undo); + assert_eq!(app.distort.vanishing.as_ref().unwrap().source, None); + step(&mut app, Step::Undo); + let s = app.distort.vanishing.as_ref().unwrap(); + assert_eq!((s.planes.len(), s.torn.len()), (1, 1)); + // ⇧⌘Z brings them back. + for _ in 0..3 { + step(&mut app, Step::Redo); + } + let s = app.distort.vanishing.as_ref().unwrap(); + assert_eq!((s.planes.len(), s.strokes.len()), (2, 1)); + assert!(s.torn[1].is_some()); + assert!(crate::distort_ui::display_doc(&app, 0).is_some(), "the stroke shows again"); +} +#[test] +fn overlapping_stamp_preview_matches_commit_across_batches() { + for new_layer in [false, true] { + let (ctx, mut app) = app_with_layer(); + app.session + .edit("pattern", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for x in 0..240 { + surf.fill_rect(Rect::new(x, 0, x + 1, 160), &[x as f32 / 240.0, (x % 7) as f32 / 6.0, 0.3, 1.0]); + } + Ok(()) + }) + .unwrap(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}]})).unwrap(); + let points = [[80.0, 80.0], [84.0, 80.0], [88.0, 80.0], [92.0, 80.0]]; + let s = app.distort.vanishing.as_mut().unwrap(); + s.new_layer = new_layer; + s.strokes.push(CloneSpec { source: [76.0, 80.0], points: points[..2].to_vec(), size: 12.0, hardness: 0.8, opacity: 1.0 }); + assert!(s.paint_preview(|| 1)); + s.strokes[0].points.extend_from_slice(&points[2..]); + assert!(s.paint_preview(|| 2)); + let (shown, _) = s.shown().unwrap(); + let expected = photocraft_compose::flatten(&shown).px; + assert_ne!(expected, photocraft_compose::flatten(&app.session.active().unwrap().doc).px); + commit(&mut app).unwrap(); + assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected, "newLayer={new_layer}"); + } +} + +/// A red square on the clipboard (copied from the layer's top-left corner). +fn copy_red_square(app: &mut PhotocraftApp) { + app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("edit.copy", json!({})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); +} + +#[test] +fn stamp_preview_paints_over_the_paste_like_ok() { + for new_layer in [false, true] { + let (ctx, mut app) = app_with_layer(); + copy_red_square(&mut app); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}], "newLayer": new_layer})).unwrap(); + let s = app.distort.vanishing.as_ref().unwrap(); + assert!(s.paste && s.paste_plane() == Some(0), "the clipboard pastes by default"); + // The paste covers x 65..175 from y 45 down. One stroke clones it onto the base + // layer, the other paints across its right edge. + control( + &mut app, + &json!({"clone": [ + {"source": [100, 60], "points": [[40, 120], [48, 120], [56, 120]], "size": 16, "hardness": 80}, + {"source": [40, 130], "points": [[150, 60], [170, 60], [190, 60]], "size": 16, "hardness": 80}, + ]}), + ) + .unwrap(); + let s = app.distort.vanishing.as_ref().unwrap(); + assert!(s.preview_has_paste(), "the preview shows the paste, so the overlay isn't drawn over the strokes"); + let (shown, _) = s.shown().unwrap(); + let expected = photocraft_compose::flatten(&shown).px; + commit(&mut app).unwrap(); + assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected, "newLayer={new_layer}"); + } +} + +#[test] +fn moving_the_paste_repaints_the_stamp_preview() { + let (ctx, mut app) = app_with_layer(); + copy_red_square(&mut app); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}]})).unwrap(); + control(&mut app, &json!({"clone": [{"source": [200, 130], "points": [[30, 130]], "size": 8}]})).unwrap(); + let red = |app: &PhotocraftApp, x: i32, y: i32| { + let (shown, _) = app.distort.vanishing.as_ref().unwrap().shown().unwrap(); + let l = app.session.active().unwrap().active_layer.unwrap(); + shown.layer(l).unwrap().surface().unwrap().rgba(x, y)[0] + }; + assert!(red(&app, 100, 60) > 0.9); + control(&mut app, &json!({"pasteAt": [0.0, 0.5]})).unwrap(); + assert!(red(&app, 100, 60) < 0.5, "the paste left its old place"); + assert!(red(&app, 30, 100) > 0.9, "and shows at the new one"); + control(&mut app, &json!({"paste": false})).unwrap(); + assert!(red(&app, 30, 100) < 0.5, "paste off: gone from the preview"); + assert!(!app.distort.vanishing.as_ref().unwrap().preview_has_paste()); +} + +#[test] +fn dragging_the_paste_shows_it_once() { + let (ctx, mut app) = app_with_layer(); + copy_red_square(&mut app); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}], "tool": "edit"})).unwrap(); + control(&mut app, &json!({"clone": [{"source": [200, 130], "points": [[30, 130]], "size": 8}]})).unwrap(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + let red = |app: &PhotocraftApp, x: i32, y: i32| { + let (shown, _) = crate::distort_ui::display_doc(app, 0)?; + Some(shown.layer(layer).unwrap().surface().unwrap().rgba(x, y)[0]) + }; + assert!(red(&app, 100, 60).unwrap() > 0.9, "the paste is in the preview"); + let ev = |app: &mut PhotocraftApp, e: ToolEvent| crate::distort_ui::pointer(app, e, egui::Modifiers::NONE); + ev(&mut app, ToolEvent::Down { x: 100.0, y: 60.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 60.0, y: 100.0, pressure: 1.0 }); + // Mid-drag: no copy left behind at the old place, only the overlay at the pointer. + assert!(red(&app, 100, 60).is_none_or(|r| r < 0.5), "{:?}", red(&app, 100, 60)); + assert!(app.distort.vanishing.as_ref().unwrap().paste_overlay(), "the overlay draws the moving paste"); + ev(&mut app, ToolEvent::Up { x: 60.0, y: 100.0 }); + assert!(red(&app, 100, 60).unwrap() < 0.5); + assert!(red(&app, 60, 100).unwrap() > 0.9, "released: the preview pastes at the new place"); + assert!(!app.distort.vanishing.as_ref().unwrap().paste_overlay()); + // A plane corner drag freezes the preview, paste included, until release: one copy. + ev(&mut app, ToolEvent::Down { x: 230.0, y: 150.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 236.0, y: 156.0, pressure: 1.0 }); + let s = app.distort.vanishing.as_ref().unwrap(); + assert!(matches!(s.drag, Some(Drag::Corner { .. }))); + assert!(red(&app, 60, 100).unwrap() > 0.9 && !s.paste_overlay(), "frozen preview, no overlay on top"); + ev(&mut app, ToolEvent::Up { x: 236.0, y: 156.0 }); + let s = app.distort.vanishing.as_ref().unwrap(); + assert!(s.preview_has_paste() && !s.paste_overlay()); +} + +#[test] +fn new_layer_stamp_preview_stays_on_the_canvas() { + let (ctx, mut app) = app_with_layer(); + // A red stripe where the first dab samples, so cloning it changes pixels. + app.session.execute("select.rect", json!({"x": 130, "y": 70, "width": 20, "height": 20})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}], "newLayer": true})).unwrap(); + // The second dab lies left of the canvas and samples the canvas 100 px to its right. + control(&mut app, &json!({"clone": [{"source": [140, 80], "points": [[40, 80], [-30, 80]], "size": 16}]})).unwrap(); + let s = app.distort.vanishing.as_ref().unwrap(); + let out = s.preview.as_ref().unwrap().out.content_bounds(); + assert!(!out.is_empty() && s.canvas.contains_rect(&out), "{out:?}"); + let st = app.session.active().unwrap(); + let area = damage(&app, st.doc.id, st.revision, 0, s.shown().unwrap().1).unwrap(); + assert!(s.canvas.contains_rect(&area), "{area:?}"); +} + +#[test] +fn deleting_the_last_plane_drops_the_stamp_preview() { + let (ctx, mut app) = app_with_layer(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[70, 60], [170, 60], [220, 150], [20, 150]]}]})).unwrap(); + control(&mut app, &json!({"clone": [{"source": [120, 139], "points": [[118, 100], [126, 100]], "size": 12}]})).unwrap(); + assert!(crate::distort_ui::display_doc(&app, 0).is_some()); + let s = app.distort.vanishing.as_mut().unwrap(); + s.selected = Some(0); + s.delete_selected(); + sync_preview(&mut app); + assert!(app.distort.vanishing.as_ref().unwrap().planes.is_empty()); + assert!(crate::distort_ui::display_doc(&app, 0).is_none(), "no strokes shown without a plane"); +} + +/// Opens the mode on the active layer of `app_with_layer` and stamps one stroke. +fn stamp_a_stroke(app: &mut PhotocraftApp, ctx: &egui::Context) { + crate::distort_ui::menu(app, ctx, VP, &json!({})).unwrap().unwrap(); + control(app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}]})).unwrap(); + control(app, &json!({"clone": [{"source": [60, 80], "points": [[120, 80], [126, 80]], "size": 12}]})).unwrap(); +} + +#[test] +fn stamp_preview_is_not_shown_on_another_document() { + let (ctx, mut app) = app_with_layer(); + stamp_a_stroke(&mut app, &ctx); + assert!(crate::distort_ui::display_doc(&app, 0).is_some()); + app.session.execute("file.new", json!({"width": 32, "height": 32, "depth": 8})).unwrap(); + let active = app.session.active_index().unwrap(); + // The session stays until drop_foreign; the preview must not follow this document (#5115). + assert!(app.distort.vanishing.is_some()); + assert!(crate::distort_ui::display_doc(&app, active).is_none()); +} + +#[test] +fn ok_paints_the_layer_the_mode_was_opened_on() { + for new_layer in [false, true] { + let (ctx, mut app) = app_with_layer(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.session + .edit("stripe", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(50, 70, 70, 90), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + stamp_a_stroke(&mut app, &ctx); + app.distort.vanishing.as_mut().unwrap().new_layer = new_layer; + sync_preview(&mut app); + // Another layer is picked while the mode is open (it isn't modal). + app.session.execute("layer.new.layer", json!({"name": "other"})).unwrap(); + let other = app.session.active().unwrap().active_layer.unwrap(); + sync_preview(&mut app); + let expected = photocraft_compose::flatten(&crate::distort_ui::display_doc(&app, 0).unwrap().0).px; + commit(&mut app).unwrap(); + let d = &app.session.active().unwrap().doc; + assert!(d.layer(other).unwrap().surface().unwrap().content_bounds().is_empty(), "newLayer={new_layer}"); + if !new_layer { + assert!(d.layer(layer).unwrap().surface().unwrap().rgba(120, 80)[0] > 0.9, "the stroke lands on the session's layer"); + // And it becomes active, so Fade and a colour-channel target follow it. + assert_eq!(app.session.active().unwrap().active_layer, Some(layer)); + } + assert_eq!(photocraft_compose::flatten(d).px, expected, "newLayer={new_layer}"); + } +} + +#[test] +fn an_edit_under_the_mode_shows_on_the_canvas() { + let (ctx, mut app) = app_with_layer(); + app.session + .edit("stripe", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(50, 70, 70, 90), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + stamp_a_stroke(&mut app, &ctx); + let before = crate::distort_ui::display_doc(&app, 0).unwrap(); + app.session + .edit("edit", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(200, 20, 220, 40), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + // Not the stale preview, even before the mode catches up. + assert!(crate::distort_ui::display_doc(&app, 0).is_none_or(|(d, _)| !Arc::ptr_eq(&d, &before.0))); + // The canvas catches up before it draws: the strokes over the edit, no frame without them. + let (shown, key) = crate::canvas::display_doc(&mut app, 0); + assert_ne!(key, before.1); + let st = app.session.active().unwrap(); + let layer = st.active_layer.unwrap(); + let px = shown.layer(layer).unwrap().surface().unwrap(); + assert!(px.rgba(210, 30)[1] > 0.9, "the edit shows: {:?}", px.rgba(210, 30)); + assert!(px.rgba(120, 80) != st.doc.layer(layer).unwrap().surface().unwrap().rgba(120, 80), "and so does the stroke"); + let expected = photocraft_compose::flatten(&shown).px; + commit(&mut app).unwrap(); + assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected); +} + +#[test] +fn selecting_another_layer_keeps_the_stamp_preview() { + let (ctx, mut app) = app_with_layer(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("layer.new.layer", json!({"name": "other"})).unwrap(); + app.session.execute("layer.select", json!({"layer": layer.0})).unwrap(); + app.sync_views(); + stamp_a_stroke(&mut app, &ctx); + let before = crate::canvas::display_doc(&mut app, 0); + let (doc, revision) = app.session.active().map(|st| (st.doc.clone(), st.revision)).unwrap(); + app.session.execute("layer.select", json!({"layer": "other"})).unwrap(); + let st = app.session.active().unwrap(); + assert!(st.revision != revision && Arc::ptr_eq(&st.doc, &doc), "a selection change leaves the pixels alone"); + // Same preview, same key: nothing to repaint or recomposite. + let after = crate::canvas::display_doc(&mut app, 0); + assert!(Arc::ptr_eq(&after.0, &before.0)); + assert_eq!(after.1, before.1); +} From 668009e152beca79317fd2949bb5b0e88e5828ee Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:19 +0000 Subject: [PATCH 092/259] refactor(ui-egui): move type_tool.rs tests to type_tool/tests.rs --- crates/ui-egui/src/type_tool.rs | 455 +------------------------- crates/ui-egui/src/type_tool/tests.rs | 452 +++++++++++++++++++++++++ 2 files changed, 453 insertions(+), 454 deletions(-) create mode 100644 crates/ui-egui/src/type_tool/tests.rs diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index 2f15e94723..78f78731ba 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -4112,460 +4112,7 @@ mod canvas_tests; mod font_picker_tests; #[cfg(test)] -mod tests { - use super::*; - - fn app() -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); - app.sync_views(); - app.ui.tool = crate::state::Tool::Type; - app - } - - /// Preferences ▸ Type ▸ Recent Fonts caps the recorded list; a re-pick moves to the front and - /// 0 keeps no list. - #[test] - fn note_recent_font_caps_and_de_duplicates() { - let mut app = app(); - for f in ["A", "B", "C"] { - app.note_recent_font(f); - } - assert_eq!(app.ui.recent_fonts, ["C", "B", "A"]); - app.run("prefs.set", json!({"path": "type.recentFonts", "value": 2})).unwrap(); - app.note_recent_font("D"); - assert_eq!(app.ui.recent_fonts, ["D", "C"], "the cap trims the tail"); - app.note_recent_font("C"); - assert_eq!(app.ui.recent_fonts, ["C", "D"], "a re-pick moves to the front"); - app.run("prefs.set", json!({"path": "type.recentFonts", "value": 0})).unwrap(); - app.note_recent_font("E"); - assert!(app.ui.recent_fonts.is_empty(), "0 keeps no list"); - } - - /// A smaller Recent Fonts cap (or 0) applies to the existing list at once, without waiting - /// for the next pick (CodeRabbit review of #3559). - #[test] - fn lowering_the_recent_fonts_cap_applies_at_once() { - let mut app = app(); - for f in ["A", "B", "C"] { - app.note_recent_font(f); - } - app.run("prefs.set", json!({"path": "type.recentFonts", "value": 2})).unwrap(); - app.sync_recent_fonts(); - assert_eq!(app.ui.recent_fonts, ["C", "B"], "the smaller cap trims the tail without a pick"); - app.run("prefs.set", json!({"path": "type.recentFonts", "value": 0})).unwrap(); - app.sync_recent_fonts(); - assert!(app.ui.recent_fonts.is_empty(), "0 clears the list"); - } - - fn layer_text(app: &PhotocraftApp) -> String { - let ed = app.ui.text_edit.as_ref().unwrap(); - current_text(app, LayerId(ed.layer)).unwrap() - } - - /// A committed type layer reading `s` at the same spot as the others (stacked variants, #4320). - fn stacked_variant(app: &mut PhotocraftApp, s: &str) -> LayerId { - app.ui.text_edit = None; - pointer_up(app, [50.0, 100.0], [50.0, 100.0]); - insert(app, s); - commit(app); - app.session.active().unwrap().active_layer.unwrap() - } - - fn hide(app: &mut PhotocraftApp, id: LayerId) { - app.run("layer.setProps", json!({"layer": id.0, "visible": false})).unwrap(); - } - - /// Wraps `id` in a new group and returns the group. - fn group_of(app: &mut PhotocraftApp, id: LayerId) -> LayerId { - app.run("layer.select", json!({"layer": id.0, "mode": "replace"})).unwrap(); - app.run("layer.groupLayers", json!({})).unwrap(); - let doc = &app.session.active().unwrap().doc; - let path = doc.path_of(id).unwrap(); - doc.layer_at(&path[..path.len() - 1]).unwrap().id - } - - /// Three type variants at one spot, bottom to top: A, B, C. - fn variants() -> (PhotocraftApp, [LayerId; 3]) { - let mut app = app(); - let ids = ["Variant A", "Variant B", "Variant C"].map(|s| stacked_variant(&mut app, s)); - (app, ids) - } - - const ON_TEXT: (f64, f64) = (60.0, 95.0); - - /// #4320: variants hidden through their groups above the shown one are not picked. - #[test] - fn type_click_skips_text_in_hidden_groups_above_the_shown_variant() { - let (mut app, [a, b, c]) = variants(); - for id in [b, c] { - let g = group_of(&mut app, id); - hide(&mut app, g); - } - assert_eq!(hit_layer(&mut app, ON_TEXT.0, ON_TEXT.1), Some(a)); - assert!(pointer_down(&mut app, ON_TEXT.0, ON_TEXT.1, egui::Modifiers::NONE)); - assert_eq!(app.ui.text_edit.as_ref().map(|e| e.layer), Some(a.0), "the click edits the shown variant"); - } - - #[test] - fn type_click_skips_text_in_a_nested_hidden_group() { - let (mut app, [a, b, c]) = variants(); - hide(&mut app, b); - let inner = group_of(&mut app, c); - let outer = group_of(&mut app, inner); - hide(&mut app, outer); - assert!(app.session.active().unwrap().doc.layer(c).unwrap().visible, "only the outer group is hidden"); - assert_eq!(hit_layer(&mut app, ON_TEXT.0, ON_TEXT.1), Some(a)); - } - - #[test] - fn type_click_skips_own_hidden_variants_above_and_below() { - let (mut app, [a, b, c]) = variants(); - hide(&mut app, b); - hide(&mut app, c); - assert_eq!(hit_layer(&mut app, ON_TEXT.0, ON_TEXT.1), Some(a), "hidden variants above"); - let (mut app, [a, b, c]) = variants(); - hide(&mut app, a); - hide(&mut app, b); - assert_eq!(hit_layer(&mut app, ON_TEXT.0, ON_TEXT.1), Some(c), "hidden variants below"); - } - - /// The Move tool's double-click on type (#1132) shares the pick. - #[test] - fn move_double_click_edits_the_shown_variant_not_one_in_a_hidden_group() { - let (mut app, [a, b, c]) = variants(); - for id in [b, c] { - let g = group_of(&mut app, id); - hide(&mut app, g); - } - app.ui.tool = crate::state::Tool::Move; - assert!(edit_at(&mut app, ON_TEXT.0, ON_TEXT.1)); - assert_eq!(app.ui.text_edit.as_ref().map(|e| e.layer), Some(a.0)); - } - - /// Photoshop: a click on existing type edits it; a ⇧-click there starts a new type layer. - #[test] - fn shift_click_on_existing_type_starts_new_text() { - let mut app = app(); - pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); - insert(&mut app, "Existing words"); - commit(&mut app); - let existing = app.session.active().unwrap().doc.layers.last().unwrap().id; - let (x, y) = (60.0, 95.0); - assert_eq!(hit_layer(&mut app, x, y), Some(existing), "the click lands on the existing text"); - assert!(!pointer_down(&mut app, x, y, egui::Modifiers::SHIFT), "⇧: not consumed, so a new type layer starts"); - assert!(app.ui.text_edit.is_none()); - assert!(pointer_down(&mut app, x, y, egui::Modifiers::NONE), "a plain click edits the existing text"); - assert_eq!(app.ui.text_edit.as_ref().map(|e| e.layer), Some(existing.0)); - } - - #[test] - fn click_creates_placeholder_selected_and_typing_replaces_it() { - let mut app = app(); - assert!(!pointer_down(&mut app, 50.0, 100.0, egui::Modifiers::NONE)); - pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); - let ed = app.ui.text_edit.clone().unwrap(); - assert_eq!((ed.anchor, ed.caret), (0, PLACEHOLDER.chars().count())); - insert(&mut app, "Héllo"); - insert(&mut app, " world"); - assert_eq!(layer_text(&app), "Héllo world"); - // Creating and typing share the session key: one step after the initial snapshot. - let steps = app.session.active().unwrap().history.entries(); - assert_eq!(steps, ["Open", "New Type Layer"]); - commit(&mut app); - let doc = &app.session.active().unwrap().doc; - assert_eq!(doc.layers.last().unwrap().name, "Héllo world"); - assert!(app.ui.text_edit.is_none()); - } - - /// TYPE-218-1: a Type tool click on the work path starts type on the path from the point - /// clicked, in one history step with the placeholder selected; a click off it is point text. - #[test] - fn click_on_a_path_starts_type_on_the_path() { - use photocraft_doc::text::TextShape; - let mut app = app(); - app.session - .edit("path", |doc, _| { - doc.work_path = Some(photocraft_doc::vector::Path::new(vec![photocraft_doc::vector::Subpath::polyline(&[(20.0, 100.0), (380.0, 100.0)])])); - Ok(()) - }) - .unwrap(); - assert!(matches!(path_target(&app, 200.0, 101.0), Some(PathClick::OnPath { .. }))); - assert!(path_target(&app, 200.0, 160.0).is_none(), "off the path"); - let before = app.session.active().unwrap().history.entries().len(); - assert!(!pointer_down(&mut app, 200.0, 101.0, egui::Modifiers::NONE)); - pointer_up(&mut app, [200.0, 101.0], [200.0, 101.0]); - let ed = app.ui.text_edit.clone().unwrap(); - assert_eq!((ed.anchor, ed.caret), (0, PLACEHOLDER.chars().count()), "the placeholder is selected"); - let shape = text_layer(&app.session.active().unwrap().doc, LayerId(ed.layer)).unwrap().shape.clone(); - assert!(matches!(shape, TextShape::Path { start, flip: false, .. } if (start - 180.0).abs() < 0.5), "{shape:?}"); - assert_eq!(app.session.active().unwrap().history.entries().len(), before + 1, "one step for the click"); - insert(&mut app, "On the line"); - assert_eq!(layer_text(&app), "On the line"); - commit(&mut app); - // With the vertical tool a click does not start path type. - app.ui.tool = crate::state::Tool::VerticalType; - assert!(!matches!(path_target(&app, 200.0, 101.0), Some(PathClick::OnPath { .. }))); - app.ui.tool = crate::state::Tool::Type; - pointer_up(&mut app, [200.0, 160.0], [200.0, 160.0]); - let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer); - assert_eq!(text_layer(&app.session.active().unwrap().doc, id).unwrap().shape, TextShape::Point); - } - - /// A click in type on a path puts the caret at the glyph there along the curve, not where the - /// straight line would have it. - #[test] - fn caret_hits_type_on_a_path_along_the_curve() { - let mut app = app(); - app.session - .edit("path", |doc, _| { - doc.work_path = Some(photocraft_doc::vector::Path::new(vec![photocraft_doc::vector::Subpath::polyline(&[(300.0, 10.0), (300.0, 195.0)])])); - Ok(()) - }) - .unwrap(); - pointer_up(&mut app, [300.0, 20.0], [300.0, 20.0]); - insert(&mut app, "ABCDEFGH"); - let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer); - assert!(matches!(text_layer(&app.session.active().unwrap().doc, id).unwrap().shape, photocraft_doc::text::TextShape::Path { .. })); - // The type runs down the path: near its start the caret is at the beginning, far down at the end. - assert_eq!(offset_at(&mut app, id, 300.0, 18.0), 0); - // (The straight line would put both of these at the start: they are left of its first glyph.) - let (mid, far) = (offset_at(&mut app, id, 296.0, 60.0), offset_at(&mut app, id, 296.0, 190.0)); - assert!(0 < mid && mid < far, "{mid} {far}"); - } - - /// Preferences ▸ Units & Rulers ▸ Type switches the display unit of type metrics: points by - /// default, pixels by the document's resolution, or millimetres. - #[test] - fn type_unit_follows_the_units_and_rulers_preference() { - let mut app = app(); - assert_eq!(type_unit(&app), (1.0, "pt")); - app.run("prefs.set", json!({"path": "unitsAndRulers.typeUnits", "value": "pixels"})).unwrap(); - assert_eq!(type_unit(&app), (1.0, "px"), "a 72 ppi document: 1 pt is 1 px"); - app.run("image.imageSize", json!({"resolution": 144, "resample": "none"})).unwrap(); - assert_eq!(type_unit(&app), (2.0, "px"), "144 ppi: a point is two pixels"); - app.run("prefs.set", json!({"path": "unitsAndRulers.typeUnits", "value": "mm"})).unwrap(); - assert!((type_unit(&app).0 - 25.4 / 72.0).abs() < 1e-6, "millimetres ignore the resolution"); - } - - /// Preferences ▸ Type ▸ Fill new type layers with placeholder text: off, a click creates an - /// empty layer (nothing selected) and committing without typing removes it again. - #[test] - fn placeholder_preference_controls_new_type_layer_text() { - let mut app = app(); - app.run("prefs.set", json!({"path": "type.fillNewTypeLayersWithPlaceholder", "value": false})).unwrap(); - pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); - let ed = app.ui.text_edit.clone().unwrap(); - assert_eq!((ed.anchor, ed.caret), (0, 0), "nothing to select"); - assert_eq!(layer_text(&app), ""); - assert_eq!(app.session.active().unwrap().doc.layers.len(), 2, "the layer was created"); - commit(&mut app); - assert_eq!(app.session.active().unwrap().doc.layers.len(), 1, "an empty type layer is removed on commit"); - assert!(app.ui.text_edit.is_none()); - } - - /// Pure smart-quote mapping: opening after whitespace, a bracket or a dash, closing next to a - /// letter or another quote. - #[test] - fn smart_quotes_are_typographic() { - assert_eq!(smart_quotes("\"Hello\"", None), "\u{201c}Hello\u{201d}"); - assert_eq!(smart_quotes("don't", None), "don\u{2019}t"); - assert_eq!(smart_quotes("(\"x\")", None), "(\u{201c}x\u{201d})"); - assert_eq!(smart_quotes("--'x'", None), "--\u{2018}x\u{2019}", "a dash stays a dash, the quote opens after it"); - assert_eq!(smart_quotes("\"\"", None), "\u{201c}\u{201d}"); - } - - /// Preferences ▸ Type ▸ Use Smart Quotes switches typed quotes (typed text only, not paste). - #[test] - fn smart_quotes_preference_controls_typed_quotes() { - for (smart, expected) in [(true, "hi \u{201c}you\u{201d}"), (false, "hi \"you\"")] { - let mut app = app(); - app.run("prefs.set", json!({"path": "type.smartQuotes", "value": smart})).unwrap(); - pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); - insert_typed(&mut app, "hi \"you\""); - assert_eq!(layer_text(&app), expected, "smartQuotes={smart}"); - } - } - - #[test] - fn a_name_from_text_after_blank_lines_keeps_following_the_text() { - let mut app = app(); - pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); - insert(&mut app, "\n\nTitle"); - let id = app.ui.text_edit.as_ref().unwrap().layer; - commit(&mut app); - let name = |app: &PhotocraftApp| app.session.active().unwrap().doc.layers.last().unwrap().name.clone(); - assert_eq!(name(&app), "Title"); - // Edited later, outside the session that created it (#483). - app.run("type.edit", json!({"layer": id, "text": "\nSubtitle"})).unwrap(); - assert_eq!(name(&app), "Subtitle"); - } - - #[test] - fn dragging_a_box_handle_resizes_the_paragraph_box() { - let mut app = app(); - pointer_up(&mut app, [10.0, 10.0], [110.0, 60.0]); - let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer); - let steps = app.session.active().unwrap().history.entries().len(); - // Top-left corner: the box keeps its bottom-right corner. - assert!(pointer_down(&mut app, 10.0, 10.0, egui::Modifiers::NONE)); - assert_eq!(app.ui.text_edit.as_ref().unwrap().resize.map(|r| r.handle), Some(0)); - pointer_move(&mut app, 20.0, 25.0, egui::Modifiers::NONE); - pointer_move(&mut app, 30.0, 30.0, egui::Modifiers::NONE); - pointer_up(&mut app, [10.0, 10.0], [30.0, 30.0]); - assert_eq!(box_shape(&app, id), Some((0.0, 0.0, 80.0, 30.0))); - let aff = layout(&mut app, id).unwrap().1; - assert_eq!((aff.m[4], aff.m[5]), (30.0, 30.0)); - // The whole drag is one history step, and the edit session survives it. - assert_eq!(app.session.active().unwrap().history.entries().len(), steps); - assert!(app.ui.text_edit.is_some()); - // Right edge: only the width changes, and never below the minimum. - assert!(pointer_down(&mut app, 110.0, 45.0, egui::Modifiers::NONE)); - pointer_move(&mut app, 0.0, 99.0, egui::Modifiers::NONE); - pointer_up(&mut app, [110.0, 45.0], [0.0, 99.0]); - assert_eq!(box_shape(&app, id), Some((0.0, 0.0, MIN_BOX, 30.0))); - // ⌥ mirrors the drag about the centre: the left edge follows the right one out. - assert!(pointer_down(&mut app, 34.0, 45.0, egui::Modifiers::ALT)); - pointer_move(&mut app, 70.0, 45.0, egui::Modifiers::ALT); - pointer_up(&mut app, [34.0, 45.0], [70.0, 45.0]); - assert_eq!(box_shape(&app, id), Some((0.0, 0.0, MIN_BOX + 72.0, 30.0))); - let aff = layout(&mut app, id).unwrap().1; - // Text space −36..40 (centre 2) through the translation: the doc centre stays at 32. - assert_eq!((aff.m[4], aff.m[5]), (-6.0, 30.0)); - } - - #[test] - fn ime_preedit_is_replaced_by_each_update_and_commit_finalises() { - let mut app = app(); - pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); - // Each preedit update replaces the previous one (and the placeholder selection first). - ime_update(&mut app, "に", false); - assert_eq!(layer_text(&app), "に"); - ime_update(&mut app, "にほん", false); - ime_update(&mut app, "にほんご", false); - assert_eq!(layer_text(&app), "にほんご"); - assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, Some((0, 4))); - ime_update(&mut app, "日本語", true); - assert_eq!(layer_text(&app), "日本語"); - let ed = app.ui.text_edit.clone().unwrap(); - assert_eq!((ed.caret, ed.anchor, ed.preedit), (3, 3, None)); - // The next composition starts after the committed text; cancelling removes it again. - ime_update(&mut app, "あ", false); - assert_eq!(layer_text(&app), "日本語あ"); - ime_update(&mut app, "", false); - assert_eq!(layer_text(&app), "日本語"); - assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, None); - // A stale preedit range (text shortened by undo) must not replace committed text; the - // composition is invalidated and its pending commit is dropped. - app.ui.text_edit.as_mut().unwrap().preedit = Some((10, 5)); - ime_update(&mut app, "x", true); - assert_eq!(layer_text(&app), "日本語"); - assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, None); - } - - #[test] - fn empty_new_layer_is_deleted_on_commit() { - let mut app = app(); - pointer_up(&mut app, [10.0, 50.0], [10.0, 50.0]); - let n = app.session.active().unwrap().doc.layers.len(); - insert(&mut app, ""); - if let Some(e) = app.ui.text_edit.as_mut() { - e.anchor = 0; - } - insert(&mut app, ""); - commit(&mut app); - assert_eq!(app.session.active().unwrap().doc.layers.len(), n - 1); - } - - #[test] - fn word_boundaries() { - assert_eq!(word_boundary("hello big world", 0, true), 5); - assert_eq!(word_boundary("hello big world", 7, false), 6); - assert_eq!(word_boundary("hello big world", 15, false), 10); - } - #[test] - fn arrow_keys_reset_caret_blink_phase() { - let mut app = app(); - pointer_up(&mut app, [10.0, 50.0], [10.0, 50.0]); - insert(&mut app, "Hello"); - app.ui.caret_blink_time = 0.0; - let ctx = egui::Context::default(); - - let has_caret = |app: &mut PhotocraftApp, ctx: &egui::Context, time: f64| -> bool { - let mut out = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { - let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 400.0)); - let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); - let xf = ViewXform { rect, zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; - draw_overlay(app, &painter, &xf); - }); - out.textures_delta.clear(); - out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::LineSegment { stroke, .. } if CARET_STROKES.contains(stroke))) - }; - - // Before resetting, the caret is in the off phase at t = 10.5 s (10500 / 530 = 19, odd phase) - assert!(!has_caret(&mut app, &ctx, 10.5), "caret should be off at t = 10.5 with phase 0.0"); - - ctx.begin_pass(egui::RawInput { - time: Some(10.5), - events: vec![egui::Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], - ..Default::default() - }); - handle_keys(&mut app, &ctx); - assert_eq!(app.ui.caret_blink_time, 10.5); - - // draw_overlay paints the solid caret in the new phase - assert!(has_caret(&mut app, &ctx, 10.5), "caret should be painted right after arrow key"); - } - - #[test] - fn pointer_up_click_resets_caret_blink_phase() { - let mut app = app(); - pointer_up(&mut app, [10.0, 50.0], [10.0, 50.0]); - insert(&mut app, "Hello"); - app.ui.caret_blink_time = 0.0; - app.last_frame_time = 12.3; - pointer_up(&mut app, [10.0, 50.0], [10.0, 50.0]); - assert_eq!(app.ui.caret_blink_time, 12.3); - } - - #[test] - fn double_click_from_move_tool_restores_move_tool_on_commit_and_cancel() { - let (mut app, _) = variants(); - app.ui.tool = crate::state::Tool::Move; - assert!(edit_at(&mut app, ON_TEXT.0, ON_TEXT.1)); - assert_eq!(app.ui.tool, crate::state::Tool::Type); - assert_eq!(app.ui.text_edit_return_tool, Some(crate::state::Tool::Move)); - commit(&mut app); - assert_eq!(app.ui.tool, crate::state::Tool::Move, "commit restores the Move tool"); - assert_eq!(app.ui.text_edit_return_tool, None); - - // Also test cancel - app.ui.tool = crate::state::Tool::Move; - assert!(edit_at(&mut app, ON_TEXT.0, ON_TEXT.1)); - assert_eq!(app.ui.tool, crate::state::Tool::Type); - cancel(&mut app); - assert_eq!(app.ui.tool, crate::state::Tool::Move, "cancel restores the Move tool"); - assert_eq!(app.ui.text_edit_return_tool, None); - - // Switching tools mid-edit commits without overriding the newly chosen tool - app.ui.tool = crate::state::Tool::Move; - assert!(edit_at(&mut app, ON_TEXT.0, ON_TEXT.1)); - assert_eq!(app.ui.tool, crate::state::Tool::Type); - assert_eq!(app.ui.text_edit_return_tool, Some(crate::state::Tool::Move)); - app.ui.tool = crate::state::Tool::Brush; - commit(&mut app); - assert_eq!(app.ui.tool, crate::state::Tool::Brush, "switching tools keeps the chosen tool"); - assert_eq!(app.ui.text_edit_return_tool, None); - - // Layers-thumbnail edit stays on Type tool (matches Photoshop) - app.ui.tool = crate::state::Tool::Move; - edit_active(&mut app).unwrap(); - assert_eq!(app.ui.tool, crate::state::Tool::Type); - assert_eq!(app.ui.text_edit_return_tool, None); - commit(&mut app); - assert_eq!(app.ui.tool, crate::state::Tool::Type, "Layers-thumbnail edit stays on Type tool"); - } -} +mod tests; #[cfg(test)] #[path = "type_commit_tests.rs"] diff --git a/crates/ui-egui/src/type_tool/tests.rs b/crates/ui-egui/src/type_tool/tests.rs new file mode 100644 index 0000000000..77c3db56c2 --- /dev/null +++ b/crates/ui-egui/src/type_tool/tests.rs @@ -0,0 +1,452 @@ +use super::*; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.sync_views(); + app.ui.tool = crate::state::Tool::Type; + app +} + +/// Preferences ▸ Type ▸ Recent Fonts caps the recorded list; a re-pick moves to the front and +/// 0 keeps no list. +#[test] +fn note_recent_font_caps_and_de_duplicates() { + let mut app = app(); + for f in ["A", "B", "C"] { + app.note_recent_font(f); + } + assert_eq!(app.ui.recent_fonts, ["C", "B", "A"]); + app.run("prefs.set", json!({"path": "type.recentFonts", "value": 2})).unwrap(); + app.note_recent_font("D"); + assert_eq!(app.ui.recent_fonts, ["D", "C"], "the cap trims the tail"); + app.note_recent_font("C"); + assert_eq!(app.ui.recent_fonts, ["C", "D"], "a re-pick moves to the front"); + app.run("prefs.set", json!({"path": "type.recentFonts", "value": 0})).unwrap(); + app.note_recent_font("E"); + assert!(app.ui.recent_fonts.is_empty(), "0 keeps no list"); +} + +/// A smaller Recent Fonts cap (or 0) applies to the existing list at once, without waiting +/// for the next pick (CodeRabbit review of #3559). +#[test] +fn lowering_the_recent_fonts_cap_applies_at_once() { + let mut app = app(); + for f in ["A", "B", "C"] { + app.note_recent_font(f); + } + app.run("prefs.set", json!({"path": "type.recentFonts", "value": 2})).unwrap(); + app.sync_recent_fonts(); + assert_eq!(app.ui.recent_fonts, ["C", "B"], "the smaller cap trims the tail without a pick"); + app.run("prefs.set", json!({"path": "type.recentFonts", "value": 0})).unwrap(); + app.sync_recent_fonts(); + assert!(app.ui.recent_fonts.is_empty(), "0 clears the list"); +} + +fn layer_text(app: &PhotocraftApp) -> String { + let ed = app.ui.text_edit.as_ref().unwrap(); + current_text(app, LayerId(ed.layer)).unwrap() +} + +/// A committed type layer reading `s` at the same spot as the others (stacked variants, #4320). +fn stacked_variant(app: &mut PhotocraftApp, s: &str) -> LayerId { + app.ui.text_edit = None; + pointer_up(app, [50.0, 100.0], [50.0, 100.0]); + insert(app, s); + commit(app); + app.session.active().unwrap().active_layer.unwrap() +} + +fn hide(app: &mut PhotocraftApp, id: LayerId) { + app.run("layer.setProps", json!({"layer": id.0, "visible": false})).unwrap(); +} + +/// Wraps `id` in a new group and returns the group. +fn group_of(app: &mut PhotocraftApp, id: LayerId) -> LayerId { + app.run("layer.select", json!({"layer": id.0, "mode": "replace"})).unwrap(); + app.run("layer.groupLayers", json!({})).unwrap(); + let doc = &app.session.active().unwrap().doc; + let path = doc.path_of(id).unwrap(); + doc.layer_at(&path[..path.len() - 1]).unwrap().id +} + +/// Three type variants at one spot, bottom to top: A, B, C. +fn variants() -> (PhotocraftApp, [LayerId; 3]) { + let mut app = app(); + let ids = ["Variant A", "Variant B", "Variant C"].map(|s| stacked_variant(&mut app, s)); + (app, ids) +} + +const ON_TEXT: (f64, f64) = (60.0, 95.0); + +/// #4320: variants hidden through their groups above the shown one are not picked. +#[test] +fn type_click_skips_text_in_hidden_groups_above_the_shown_variant() { + let (mut app, [a, b, c]) = variants(); + for id in [b, c] { + let g = group_of(&mut app, id); + hide(&mut app, g); + } + assert_eq!(hit_layer(&mut app, ON_TEXT.0, ON_TEXT.1), Some(a)); + assert!(pointer_down(&mut app, ON_TEXT.0, ON_TEXT.1, egui::Modifiers::NONE)); + assert_eq!(app.ui.text_edit.as_ref().map(|e| e.layer), Some(a.0), "the click edits the shown variant"); +} + +#[test] +fn type_click_skips_text_in_a_nested_hidden_group() { + let (mut app, [a, b, c]) = variants(); + hide(&mut app, b); + let inner = group_of(&mut app, c); + let outer = group_of(&mut app, inner); + hide(&mut app, outer); + assert!(app.session.active().unwrap().doc.layer(c).unwrap().visible, "only the outer group is hidden"); + assert_eq!(hit_layer(&mut app, ON_TEXT.0, ON_TEXT.1), Some(a)); +} + +#[test] +fn type_click_skips_own_hidden_variants_above_and_below() { + let (mut app, [a, b, c]) = variants(); + hide(&mut app, b); + hide(&mut app, c); + assert_eq!(hit_layer(&mut app, ON_TEXT.0, ON_TEXT.1), Some(a), "hidden variants above"); + let (mut app, [a, b, c]) = variants(); + hide(&mut app, a); + hide(&mut app, b); + assert_eq!(hit_layer(&mut app, ON_TEXT.0, ON_TEXT.1), Some(c), "hidden variants below"); +} + +/// The Move tool's double-click on type (#1132) shares the pick. +#[test] +fn move_double_click_edits_the_shown_variant_not_one_in_a_hidden_group() { + let (mut app, [a, b, c]) = variants(); + for id in [b, c] { + let g = group_of(&mut app, id); + hide(&mut app, g); + } + app.ui.tool = crate::state::Tool::Move; + assert!(edit_at(&mut app, ON_TEXT.0, ON_TEXT.1)); + assert_eq!(app.ui.text_edit.as_ref().map(|e| e.layer), Some(a.0)); +} + +/// Photoshop: a click on existing type edits it; a ⇧-click there starts a new type layer. +#[test] +fn shift_click_on_existing_type_starts_new_text() { + let mut app = app(); + pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); + insert(&mut app, "Existing words"); + commit(&mut app); + let existing = app.session.active().unwrap().doc.layers.last().unwrap().id; + let (x, y) = (60.0, 95.0); + assert_eq!(hit_layer(&mut app, x, y), Some(existing), "the click lands on the existing text"); + assert!(!pointer_down(&mut app, x, y, egui::Modifiers::SHIFT), "⇧: not consumed, so a new type layer starts"); + assert!(app.ui.text_edit.is_none()); + assert!(pointer_down(&mut app, x, y, egui::Modifiers::NONE), "a plain click edits the existing text"); + assert_eq!(app.ui.text_edit.as_ref().map(|e| e.layer), Some(existing.0)); +} + +#[test] +fn click_creates_placeholder_selected_and_typing_replaces_it() { + let mut app = app(); + assert!(!pointer_down(&mut app, 50.0, 100.0, egui::Modifiers::NONE)); + pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); + let ed = app.ui.text_edit.clone().unwrap(); + assert_eq!((ed.anchor, ed.caret), (0, PLACEHOLDER.chars().count())); + insert(&mut app, "Héllo"); + insert(&mut app, " world"); + assert_eq!(layer_text(&app), "Héllo world"); + // Creating and typing share the session key: one step after the initial snapshot. + let steps = app.session.active().unwrap().history.entries(); + assert_eq!(steps, ["Open", "New Type Layer"]); + commit(&mut app); + let doc = &app.session.active().unwrap().doc; + assert_eq!(doc.layers.last().unwrap().name, "Héllo world"); + assert!(app.ui.text_edit.is_none()); +} + +/// TYPE-218-1: a Type tool click on the work path starts type on the path from the point +/// clicked, in one history step with the placeholder selected; a click off it is point text. +#[test] +fn click_on_a_path_starts_type_on_the_path() { + use photocraft_doc::text::TextShape; + let mut app = app(); + app.session + .edit("path", |doc, _| { + doc.work_path = Some(photocraft_doc::vector::Path::new(vec![photocraft_doc::vector::Subpath::polyline(&[(20.0, 100.0), (380.0, 100.0)])])); + Ok(()) + }) + .unwrap(); + assert!(matches!(path_target(&app, 200.0, 101.0), Some(PathClick::OnPath { .. }))); + assert!(path_target(&app, 200.0, 160.0).is_none(), "off the path"); + let before = app.session.active().unwrap().history.entries().len(); + assert!(!pointer_down(&mut app, 200.0, 101.0, egui::Modifiers::NONE)); + pointer_up(&mut app, [200.0, 101.0], [200.0, 101.0]); + let ed = app.ui.text_edit.clone().unwrap(); + assert_eq!((ed.anchor, ed.caret), (0, PLACEHOLDER.chars().count()), "the placeholder is selected"); + let shape = text_layer(&app.session.active().unwrap().doc, LayerId(ed.layer)).unwrap().shape.clone(); + assert!(matches!(shape, TextShape::Path { start, flip: false, .. } if (start - 180.0).abs() < 0.5), "{shape:?}"); + assert_eq!(app.session.active().unwrap().history.entries().len(), before + 1, "one step for the click"); + insert(&mut app, "On the line"); + assert_eq!(layer_text(&app), "On the line"); + commit(&mut app); + // With the vertical tool a click does not start path type. + app.ui.tool = crate::state::Tool::VerticalType; + assert!(!matches!(path_target(&app, 200.0, 101.0), Some(PathClick::OnPath { .. }))); + app.ui.tool = crate::state::Tool::Type; + pointer_up(&mut app, [200.0, 160.0], [200.0, 160.0]); + let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer); + assert_eq!(text_layer(&app.session.active().unwrap().doc, id).unwrap().shape, TextShape::Point); +} + +/// A click in type on a path puts the caret at the glyph there along the curve, not where the +/// straight line would have it. +#[test] +fn caret_hits_type_on_a_path_along_the_curve() { + let mut app = app(); + app.session + .edit("path", |doc, _| { + doc.work_path = Some(photocraft_doc::vector::Path::new(vec![photocraft_doc::vector::Subpath::polyline(&[(300.0, 10.0), (300.0, 195.0)])])); + Ok(()) + }) + .unwrap(); + pointer_up(&mut app, [300.0, 20.0], [300.0, 20.0]); + insert(&mut app, "ABCDEFGH"); + let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer); + assert!(matches!(text_layer(&app.session.active().unwrap().doc, id).unwrap().shape, photocraft_doc::text::TextShape::Path { .. })); + // The type runs down the path: near its start the caret is at the beginning, far down at the end. + assert_eq!(offset_at(&mut app, id, 300.0, 18.0), 0); + // (The straight line would put both of these at the start: they are left of its first glyph.) + let (mid, far) = (offset_at(&mut app, id, 296.0, 60.0), offset_at(&mut app, id, 296.0, 190.0)); + assert!(0 < mid && mid < far, "{mid} {far}"); +} + +/// Preferences ▸ Units & Rulers ▸ Type switches the display unit of type metrics: points by +/// default, pixels by the document's resolution, or millimetres. +#[test] +fn type_unit_follows_the_units_and_rulers_preference() { + let mut app = app(); + assert_eq!(type_unit(&app), (1.0, "pt")); + app.run("prefs.set", json!({"path": "unitsAndRulers.typeUnits", "value": "pixels"})).unwrap(); + assert_eq!(type_unit(&app), (1.0, "px"), "a 72 ppi document: 1 pt is 1 px"); + app.run("image.imageSize", json!({"resolution": 144, "resample": "none"})).unwrap(); + assert_eq!(type_unit(&app), (2.0, "px"), "144 ppi: a point is two pixels"); + app.run("prefs.set", json!({"path": "unitsAndRulers.typeUnits", "value": "mm"})).unwrap(); + assert!((type_unit(&app).0 - 25.4 / 72.0).abs() < 1e-6, "millimetres ignore the resolution"); +} + +/// Preferences ▸ Type ▸ Fill new type layers with placeholder text: off, a click creates an +/// empty layer (nothing selected) and committing without typing removes it again. +#[test] +fn placeholder_preference_controls_new_type_layer_text() { + let mut app = app(); + app.run("prefs.set", json!({"path": "type.fillNewTypeLayersWithPlaceholder", "value": false})).unwrap(); + pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); + let ed = app.ui.text_edit.clone().unwrap(); + assert_eq!((ed.anchor, ed.caret), (0, 0), "nothing to select"); + assert_eq!(layer_text(&app), ""); + assert_eq!(app.session.active().unwrap().doc.layers.len(), 2, "the layer was created"); + commit(&mut app); + assert_eq!(app.session.active().unwrap().doc.layers.len(), 1, "an empty type layer is removed on commit"); + assert!(app.ui.text_edit.is_none()); +} + +/// Pure smart-quote mapping: opening after whitespace, a bracket or a dash, closing next to a +/// letter or another quote. +#[test] +fn smart_quotes_are_typographic() { + assert_eq!(smart_quotes("\"Hello\"", None), "\u{201c}Hello\u{201d}"); + assert_eq!(smart_quotes("don't", None), "don\u{2019}t"); + assert_eq!(smart_quotes("(\"x\")", None), "(\u{201c}x\u{201d})"); + assert_eq!(smart_quotes("--'x'", None), "--\u{2018}x\u{2019}", "a dash stays a dash, the quote opens after it"); + assert_eq!(smart_quotes("\"\"", None), "\u{201c}\u{201d}"); +} + +/// Preferences ▸ Type ▸ Use Smart Quotes switches typed quotes (typed text only, not paste). +#[test] +fn smart_quotes_preference_controls_typed_quotes() { + for (smart, expected) in [(true, "hi \u{201c}you\u{201d}"), (false, "hi \"you\"")] { + let mut app = app(); + app.run("prefs.set", json!({"path": "type.smartQuotes", "value": smart})).unwrap(); + pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); + insert_typed(&mut app, "hi \"you\""); + assert_eq!(layer_text(&app), expected, "smartQuotes={smart}"); + } +} + +#[test] +fn a_name_from_text_after_blank_lines_keeps_following_the_text() { + let mut app = app(); + pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); + insert(&mut app, "\n\nTitle"); + let id = app.ui.text_edit.as_ref().unwrap().layer; + commit(&mut app); + let name = |app: &PhotocraftApp| app.session.active().unwrap().doc.layers.last().unwrap().name.clone(); + assert_eq!(name(&app), "Title"); + // Edited later, outside the session that created it (#483). + app.run("type.edit", json!({"layer": id, "text": "\nSubtitle"})).unwrap(); + assert_eq!(name(&app), "Subtitle"); +} + +#[test] +fn dragging_a_box_handle_resizes_the_paragraph_box() { + let mut app = app(); + pointer_up(&mut app, [10.0, 10.0], [110.0, 60.0]); + let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer); + let steps = app.session.active().unwrap().history.entries().len(); + // Top-left corner: the box keeps its bottom-right corner. + assert!(pointer_down(&mut app, 10.0, 10.0, egui::Modifiers::NONE)); + assert_eq!(app.ui.text_edit.as_ref().unwrap().resize.map(|r| r.handle), Some(0)); + pointer_move(&mut app, 20.0, 25.0, egui::Modifiers::NONE); + pointer_move(&mut app, 30.0, 30.0, egui::Modifiers::NONE); + pointer_up(&mut app, [10.0, 10.0], [30.0, 30.0]); + assert_eq!(box_shape(&app, id), Some((0.0, 0.0, 80.0, 30.0))); + let aff = layout(&mut app, id).unwrap().1; + assert_eq!((aff.m[4], aff.m[5]), (30.0, 30.0)); + // The whole drag is one history step, and the edit session survives it. + assert_eq!(app.session.active().unwrap().history.entries().len(), steps); + assert!(app.ui.text_edit.is_some()); + // Right edge: only the width changes, and never below the minimum. + assert!(pointer_down(&mut app, 110.0, 45.0, egui::Modifiers::NONE)); + pointer_move(&mut app, 0.0, 99.0, egui::Modifiers::NONE); + pointer_up(&mut app, [110.0, 45.0], [0.0, 99.0]); + assert_eq!(box_shape(&app, id), Some((0.0, 0.0, MIN_BOX, 30.0))); + // ⌥ mirrors the drag about the centre: the left edge follows the right one out. + assert!(pointer_down(&mut app, 34.0, 45.0, egui::Modifiers::ALT)); + pointer_move(&mut app, 70.0, 45.0, egui::Modifiers::ALT); + pointer_up(&mut app, [34.0, 45.0], [70.0, 45.0]); + assert_eq!(box_shape(&app, id), Some((0.0, 0.0, MIN_BOX + 72.0, 30.0))); + let aff = layout(&mut app, id).unwrap().1; + // Text space −36..40 (centre 2) through the translation: the doc centre stays at 32. + assert_eq!((aff.m[4], aff.m[5]), (-6.0, 30.0)); +} + +#[test] +fn ime_preedit_is_replaced_by_each_update_and_commit_finalises() { + let mut app = app(); + pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); + // Each preedit update replaces the previous one (and the placeholder selection first). + ime_update(&mut app, "に", false); + assert_eq!(layer_text(&app), "に"); + ime_update(&mut app, "にほん", false); + ime_update(&mut app, "にほんご", false); + assert_eq!(layer_text(&app), "にほんご"); + assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, Some((0, 4))); + ime_update(&mut app, "日本語", true); + assert_eq!(layer_text(&app), "日本語"); + let ed = app.ui.text_edit.clone().unwrap(); + assert_eq!((ed.caret, ed.anchor, ed.preedit), (3, 3, None)); + // The next composition starts after the committed text; cancelling removes it again. + ime_update(&mut app, "あ", false); + assert_eq!(layer_text(&app), "日本語あ"); + ime_update(&mut app, "", false); + assert_eq!(layer_text(&app), "日本語"); + assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, None); + // A stale preedit range (text shortened by undo) must not replace committed text; the + // composition is invalidated and its pending commit is dropped. + app.ui.text_edit.as_mut().unwrap().preedit = Some((10, 5)); + ime_update(&mut app, "x", true); + assert_eq!(layer_text(&app), "日本語"); + assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, None); +} + +#[test] +fn empty_new_layer_is_deleted_on_commit() { + let mut app = app(); + pointer_up(&mut app, [10.0, 50.0], [10.0, 50.0]); + let n = app.session.active().unwrap().doc.layers.len(); + insert(&mut app, ""); + if let Some(e) = app.ui.text_edit.as_mut() { + e.anchor = 0; + } + insert(&mut app, ""); + commit(&mut app); + assert_eq!(app.session.active().unwrap().doc.layers.len(), n - 1); +} + +#[test] +fn word_boundaries() { + assert_eq!(word_boundary("hello big world", 0, true), 5); + assert_eq!(word_boundary("hello big world", 7, false), 6); + assert_eq!(word_boundary("hello big world", 15, false), 10); +} +#[test] +fn arrow_keys_reset_caret_blink_phase() { + let mut app = app(); + pointer_up(&mut app, [10.0, 50.0], [10.0, 50.0]); + insert(&mut app, "Hello"); + app.ui.caret_blink_time = 0.0; + let ctx = egui::Context::default(); + + let has_caret = |app: &mut PhotocraftApp, ctx: &egui::Context, time: f64| -> bool { + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 400.0)); + let painter = ui.ctx().layer_painter(egui::LayerId::background()).with_clip_rect(rect); + let xf = ViewXform { rect, zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + draw_overlay(app, &painter, &xf); + }); + out.textures_delta.clear(); + out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::LineSegment { stroke, .. } if CARET_STROKES.contains(stroke))) + }; + + // Before resetting, the caret is in the off phase at t = 10.5 s (10500 / 530 = 19, odd phase) + assert!(!has_caret(&mut app, &ctx, 10.5), "caret should be off at t = 10.5 with phase 0.0"); + + ctx.begin_pass(egui::RawInput { + time: Some(10.5), + events: vec![egui::Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ..Default::default() + }); + handle_keys(&mut app, &ctx); + assert_eq!(app.ui.caret_blink_time, 10.5); + + // draw_overlay paints the solid caret in the new phase + assert!(has_caret(&mut app, &ctx, 10.5), "caret should be painted right after arrow key"); +} + +#[test] +fn pointer_up_click_resets_caret_blink_phase() { + let mut app = app(); + pointer_up(&mut app, [10.0, 50.0], [10.0, 50.0]); + insert(&mut app, "Hello"); + app.ui.caret_blink_time = 0.0; + app.last_frame_time = 12.3; + pointer_up(&mut app, [10.0, 50.0], [10.0, 50.0]); + assert_eq!(app.ui.caret_blink_time, 12.3); +} + +#[test] +fn double_click_from_move_tool_restores_move_tool_on_commit_and_cancel() { + let (mut app, _) = variants(); + app.ui.tool = crate::state::Tool::Move; + assert!(edit_at(&mut app, ON_TEXT.0, ON_TEXT.1)); + assert_eq!(app.ui.tool, crate::state::Tool::Type); + assert_eq!(app.ui.text_edit_return_tool, Some(crate::state::Tool::Move)); + commit(&mut app); + assert_eq!(app.ui.tool, crate::state::Tool::Move, "commit restores the Move tool"); + assert_eq!(app.ui.text_edit_return_tool, None); + + // Also test cancel + app.ui.tool = crate::state::Tool::Move; + assert!(edit_at(&mut app, ON_TEXT.0, ON_TEXT.1)); + assert_eq!(app.ui.tool, crate::state::Tool::Type); + cancel(&mut app); + assert_eq!(app.ui.tool, crate::state::Tool::Move, "cancel restores the Move tool"); + assert_eq!(app.ui.text_edit_return_tool, None); + + // Switching tools mid-edit commits without overriding the newly chosen tool + app.ui.tool = crate::state::Tool::Move; + assert!(edit_at(&mut app, ON_TEXT.0, ON_TEXT.1)); + assert_eq!(app.ui.tool, crate::state::Tool::Type); + assert_eq!(app.ui.text_edit_return_tool, Some(crate::state::Tool::Move)); + app.ui.tool = crate::state::Tool::Brush; + commit(&mut app); + assert_eq!(app.ui.tool, crate::state::Tool::Brush, "switching tools keeps the chosen tool"); + assert_eq!(app.ui.text_edit_return_tool, None); + + // Layers-thumbnail edit stays on Type tool (matches Photoshop) + app.ui.tool = crate::state::Tool::Move; + edit_active(&mut app).unwrap(); + assert_eq!(app.ui.tool, crate::state::Tool::Type); + assert_eq!(app.ui.text_edit_return_tool, None); + commit(&mut app); + assert_eq!(app.ui.tool, crate::state::Tool::Type, "Layers-thumbnail edit stays on Type tool"); +} From 523cbe4f6fe021a6ac0819914f80dd3c8e9fd94f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:21 +0000 Subject: [PATCH 093/259] refactor(ui-egui): move type_tool.rs ime_tests to type_tool/ime_tests.rs --- crates/ui-egui/src/type_tool.rs | 1346 +-------------------- crates/ui-egui/src/type_tool/ime_tests.rs | 1343 ++++++++++++++++++++ 2 files changed, 1344 insertions(+), 1345 deletions(-) create mode 100644 crates/ui-egui/src/type_tool/ime_tests.rs diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index 78f78731ba..cc8f252efa 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -4119,1348 +4119,4 @@ mod tests; mod commit_tests; #[cfg(test)] -mod ime_tests { - use super::*; - use egui::output::{IMEOutput, ImeChangeCause}; - - fn context() -> egui::Context { - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - install_reset_hooks(&ctx); - ctx - } - - fn app() -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); - app.sync_views(); - app.ui.tool = crate::state::Tool::Type; - pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); - insert(&mut app, "abc"); - app - } - - fn run(app: &mut PhotocraftApp, ctx: &egui::Context, events: Vec) -> Option { - let raw = egui::RawInput { focused: true, events, ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| { - let rect = egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400.0, 300.0)); - let xf = ViewXform { rect, zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; - handle_keys(app, ui.ctx()); - draw_overlay(app, ui.painter(), &xf); - sync_ime(app, ui.ctx()); - finish_reset_pass(app, ui.ctx()); - }); - out.textures_delta.clear(); // This protocol harness does not paint. - out.platform_output.ime - } - - fn layer_text(app: &PhotocraftApp) -> String { - let ed = app.ui.text_edit.as_ref().expect("editing"); - current_text(app, LayerId(ed.layer)).expect("text layer") - } - - fn completed(request_id: egui::ImeResetId) -> egui::Event { - egui::Event::ImeResetCompleted { request_id } - } - - fn payload(ime: &IMEOutput) -> &egui::output::IMESurroundingTextPayload { - ime.surrounding_text.available().expect("a bounded committed snapshot") - } - - fn preedit(text: &str) -> egui::Event { - egui::Event::Ime(egui::ImeEvent::Preedit { text: text.to_owned(), active_range_chars: None }) - } - - #[test] - fn successive_ime_commits_are_input_method_and_keep_directional_offsets() { - let ctx = context(); - let mut app = app(); - let baseline = run(&mut app, &ctx, Vec::new()).expect("a focused editor descriptor"); - assert_eq!(payload(&baseline).text, "abc"); - assert_eq!(baseline.change_cause, ImeChangeCause::Other); - - // The pre-edit is laid out in the layer but is not committed surrounding text. - let composing = run(&mut app, &ctx, vec![preedit("に")]).expect("descriptor while composing"); - assert_eq!(payload(&composing).text, "abc"); - assert_eq!((payload(&composing).cursor, payload(&composing).anchor), (3, 3)); - - let first = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日本".into()))]).expect("commit descriptor"); - assert_eq!(first.change_cause, ImeChangeCause::InputMethod); - assert_eq!(payload(&first).text, "abc日本"); - - let composing = run(&mut app, &ctx, vec![preedit("ご")]).expect("second composition"); - assert_eq!(payload(&composing).text, "abc日本"); - let second = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("語".into()))]).expect("second commit"); - assert_eq!(second.change_cause, ImeChangeCause::InputMethod); - assert_eq!(payload(&second).text, "abc日本語"); - assert_eq!(payload(&second).cursor, payload(&second).text.len()); - } - - #[test] - fn reversed_selection_keeps_its_direction_in_byte_offsets() { - let ctx = context(); - let mut app = app(); - if let Some(ed) = app.ui.text_edit.as_mut() { - ed.caret = 1; - ed.anchor = 3; - } - let selected = run(&mut app, &ctx, Vec::new()).expect("descriptor"); - assert_eq!(payload(&selected).text, "abc"); - assert_eq!((payload(&selected).cursor, payload(&selected).anchor), (1, 3)); - } - - #[test] - fn mixed_application_and_ime_edits_in_one_frame_are_other() { - let ctx = context(); - let mut app = app(); - run(&mut app, &ctx, Vec::new()); - - // An IME commit followed by ordinary typing in the same pass: the application change - // dominates even though the commit itself was accepted. - let mixed = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("い".into())), egui::Event::Text("x".into())]).expect("mixed descriptor"); - assert_eq!(payload(&mixed).text, "abcいx"); - assert_eq!(mixed.change_cause, ImeChangeCause::Other); - - // The observed mixed state is the next baseline, so a later clean IME commit is once - // again an InputMethod change. - let next = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("う".into()))]).expect("next commit"); - assert_eq!(next.change_cause, ImeChangeCause::InputMethod); - assert_eq!(payload(&next).text, "abcいxう"); - - // Application text before the commit in the same frame must also prevent InputMethod. - let mut app = self::app(); - run(&mut app, &ctx, Vec::new()); - let mixed = run(&mut app, &ctx, vec![egui::Event::Text("x".into()), egui::Event::Ime(egui::ImeEvent::Commit("い".into()))]).expect("mixed descriptor"); - assert_eq!(mixed.change_cause, ImeChangeCause::Other); - assert_eq!(payload(&mixed).text, "abcxい"); - } - - #[test] - fn replaced_layer_or_session_bumps_generation_without_changing_owner() { - let ctx = context(); - let mut app = app(); - let first = run(&mut app, &ctx, Vec::new()).expect("descriptor"); - let owner = first.owner; - let generation = first.context_generation; - - // Same document and layer id, a new edit session: the replacement epoch changes, so the - // stale generation cannot be reused by a native IME bridge. - app.ui.text_edit.as_mut().unwrap().session = "type-replaced".into(); - let replaced = run(&mut app, &ctx, Vec::new()).expect("replaced descriptor"); - assert_eq!(replaced.owner, owner, "the layer identity is immutable"); - assert_ne!(replaced.context_generation, generation); - assert_eq!(replaced.change_cause, ImeChangeCause::Other); - - // Ending the editor ends the context; no descriptor is emitted for an absent owner. - app.ui.text_edit = None; - assert!(run(&mut app, &ctx, Vec::new()).is_none()); - } - - #[test] - fn unavailable_editor_state_still_carries_owner_and_generation() { - let ctx = context(); - let mut app = app(); - // A stale composition range cannot be mapped onto the layer: do not silently publish - // the composition as committed text. - app.ui.text_edit.as_mut().unwrap().preedit = Some((10, 5)); - let unavailable = run(&mut app, &ctx, Vec::new()).expect("descriptor with an owner"); - assert!(unavailable.surrounding_text.available().is_none()); - assert!(unavailable.context_generation > 0); - assert_eq!(unavailable.purpose, egui::IMEPurpose::Normal); - } - - #[test] - fn delete_surrounding_bytes_with_preedit_excludes_the_composition() { - let ctx = context(); - let mut app = app(); - run(&mut app, &ctx, Vec::new()); - run(&mut app, &ctx, vec![preedit("x")]); - assert_eq!(layer_text(&app), "abcx"); - assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, Some((3, 1))); - - // `c` is the byte immediately before the pre-edit; deleting it must not delete or - // report the composing `x`. - let deleted = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 })]) - .expect("deletion descriptor"); - assert_eq!(deleted.change_cause, ImeChangeCause::InputMethod); - assert_eq!(payload(&deleted).text, "ab"); - assert_eq!((payload(&deleted).cursor, payload(&deleted).anchor), (2, 2)); - assert_eq!(layer_text(&app), "abx"); - assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, Some((2, 1))); - } - - #[test] - fn external_edit_invalidates_the_preedit_and_rejects_its_late_commit() { - for bytes in [false, true] { - for split in [false, true] { - for discard in [false, true] { - let ctx = context(); - let mut app = app(); - run(&mut app, &ctx, Vec::new()); - // Compose in the middle of committed text, so an application edit before it - // moves a still-in-range (but wrong) character range. - insert(&mut app, "def"); - if let Some(ed) = app.ui.text_edit.as_mut() { - ed.caret = 3; - ed.anchor = 3; - } - let composing = run(&mut app, &ctx, vec![preedit("に")]).expect("composing descriptor"); - assert_eq!(layer_text(&app), "abcにdef"); - assert_eq!(payload(&composing).text, "abcdef", "the preview is not committed text"); - let layer = app.ui.text_edit.as_ref().unwrap().layer; - let session = app.ui.text_edit.as_ref().unwrap().session.clone(); - // The control channel edits the same layer without passing through `insert`. - app.run("type.edit", json!({"layer": layer, "replace": {"start": 0, "end": 1, "text": ""}, "coalesce": session})).unwrap(); - assert_eq!(layer_text(&app), "bcにdef"); - let revision = app.session.active().unwrap().revision; - let history = app.session.active().unwrap().history.entries(); - let selection = app.ui.text_edit.as_ref().map(|ed| (ed.anchor, ed.caret)); - let unchanged = |app: &PhotocraftApp| { - assert_eq!(layer_text(app), "bcにdef"); - assert_eq!(app.session.active().unwrap().revision, revision); - assert_eq!(app.session.active().unwrap().history.entries(), history); - assert_eq!(app.ui.text_edit.as_ref().map(|ed| (ed.anchor, ed.caret)), selection); - }; - - // The old range (3,1) now covers `d`: report unavailable, cancel the - // composition and do not present `d` as the composition. A discarded pass - // must retain both latches until a descriptor is actually delivered. - let invalidated = if discard { - ctx.options_mut(|o| o.max_passes = std::num::NonZeroUsize::new(4).expect("four passes")); - let mut passes = Vec::new(); - let mut out = ctx.run_ui(egui::RawInput { focused: true, ..Default::default() }, |ui| { - handle_keys(&mut app, ui.ctx()); - let rect = egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400.0, 300.0)); - let xf = ViewXform { rect, zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; - draw_overlay(&mut app, ui.painter(), &xf); - if passes.is_empty() { - ui.ctx().request_discard("invalidated preedit descriptor regression"); - } - let discarded = ui.ctx().will_discard(); - let before = (app.type_ime.stale, app.type_ime.interrupt); - sync_ime(&mut app, ui.ctx()); - finish_reset_pass(&mut app, ui.ctx()); - let unavailable = ui.ctx().output(|out| out.ime.as_ref().expect("pass descriptor").surrounding_text.available().is_none()); - passes.push((discarded, before, (app.type_ime.stale, app.type_ime.interrupt), unavailable)); - }); - out.textures_delta.clear(); - assert_eq!(passes.first(), Some(&(true, (true, true), (true, true), true)), "discard cannot consume invalidation"); - assert_eq!(passes.last(), Some(&(false, (true, true), (false, false), true)), "the accepted pass delivers it once"); - out.platform_output.ime.expect("descriptor") - } else { - run(&mut app, &ctx, Vec::new()).expect("descriptor") - }; - assert!(invalidated.surrounding_text.available().is_none()); - assert!(invalidated.should_interrupt_composition); - assert_eq!( - (invalidated.owner, invalidated.context_generation, invalidated.purpose), - (composing.owner, composing.context_generation, composing.purpose) - ); - assert_eq!(invalidated.change_cause, ImeChangeCause::Other); - assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, None); - assert!(app.type_ime.preedit.is_none()); - unchanged(&app); - - let recovered = run(&mut app, &ctx, Vec::new()).expect("idle descriptor"); - assert_eq!(payload(&recovered).text, "bcにdef"); - assert_eq!((payload(&recovered).cursor, payload(&recovered).anchor), (6, 6)); - assert!(!recovered.should_interrupt_composition, "a delivered reset is not replayed"); - assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale)), "idle availability does not accept an old terminal"); - unchanged(&app); - - // The pending deletion and commit belonged to the cancelled composition: - // neither combined nor split delivery may replace `d` or grow undo history. - let mut events = vec![terminal_delete(bytes)]; - if split { - run(&mut app, &ctx, events).expect("rejected deletion descriptor"); - unchanged(&app); - for _ in 0..3 { - run(&mut app, &ctx, Vec::new()); - } - assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale))); - events = Vec::new(); - } - events.push(egui::Event::Ime(egui::ImeEvent::Commit("に".into()))); - let late = run(&mut app, &ctx, events).expect("descriptor"); - assert_eq!(layer_text(&app), "bcにdef"); - assert_eq!(late.change_cause, ImeChangeCause::Other); - assert_eq!(payload(&late).text, "bcにdef"); - unchanged(&app); - assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale)), "terminal input cannot acknowledge cancellation"); - - let fresh = run(&mut app, &ctx, vec![completed(invalidated.reset_request.expect("reset request")), preedit("Q")]) - .expect("fresh preview descriptor"); - assert_eq!(layer_text(&app), "bcにdQef"); - assert_eq!(payload(&fresh).text, "bcにdef", "fresh preview is excluded from committed text"); - assert!(!fresh.should_interrupt_composition); - let committed = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("Q".into()))]).expect("fresh commit descriptor"); - assert_eq!(layer_text(&app), "bcにdQef"); - assert_eq!(payload(&committed).text, "bcにdQef"); - assert_eq!(committed.change_cause, ImeChangeCause::InputMethod); - let direct = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("R".into()))]).expect("direct commit descriptor"); - assert_eq!(layer_text(&app), "bcにdQRef"); - assert_eq!(payload(&direct).text, "bcにdQRef"); - assert_eq!(direct.change_cause, ImeChangeCause::InputMethod); - } - } - } - } - - #[test] - fn target_change_interrupts_and_rejects_the_late_commit() { - let ctx = context(); - let mut app = app(); - run(&mut app, &ctx, Vec::new()); - run(&mut app, &ctx, vec![preedit("に")]); - assert_eq!(layer_text(&app), "abcに"); - - let created = app.run("type.create", json!({"text": "two", "x": 150, "y": 60})).unwrap(); - let second = created.get("layer").and_then(serde_json::Value::as_u64).expect("new layer"); - app.session.select_layer(LayerId(second)).expect("select the second type layer"); - app.ui.text_edit = Some(TextEdit { - layer: second, - document: active_doc_id(&app), - caret: 3, - anchor: 3, - session: "type-second".into(), - created: false, - mask: false, - dragging: false, - resize: None, - preedit: None, - }); - // The platform only cancels composition on this flag (X11, macOS, Windows and the web). - let switched = run(&mut app, &ctx, Vec::new()).expect("transition descriptor"); - assert!(switched.should_interrupt_composition); - - let late = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日本".into()))]).expect("descriptor"); - assert_eq!(current_text(&app, LayerId(second)).unwrap(), "two"); - assert_eq!(late.change_cause, ImeChangeCause::Other); - run(&mut app, &ctx, vec![completed(switched.reset_request.expect("replacement layer reset")), preedit("が")]); - assert_eq!(layer_text(&app), "twoが"); - } - - #[test] - fn type_mask_session_has_a_distinct_owner() { - let ctx = context(); - let mut app = app(); - let normal = run(&mut app, &ctx, Vec::new()).expect("descriptor"); - app.ui.text_edit.as_mut().unwrap().mask = true; - let masked = run(&mut app, &ctx, Vec::new()).expect("mask descriptor"); - assert_ne!(masked.owner, normal.owner, "the Type Mask session is its own owner"); - assert_ne!(masked.context_generation, normal.context_generation); - } - - #[test] - fn reentering_the_same_session_cancels_the_preedit() { - let ctx = context(); - let mut app = app(); - run(&mut app, &ctx, vec![preedit("に")]); - assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, Some((3, 1))); - edit_active(&mut app).unwrap(); - assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, None); - assert!(app.type_ime.interrupt, "the native composition is cancelled"); - assert!(app.type_ime.preedit.is_none()); - } - - #[test] - fn a_discarded_transition_pass_still_interrupts_the_next_descriptor() { - let ctx = context(); - ctx.options_mut(|o| o.max_passes = std::num::NonZeroUsize::new(4).expect("four passes")); - let mut app = app(); - run(&mut app, &ctx, Vec::new()).expect("baseline descriptor"); - app.ui.text_edit.as_mut().unwrap().session = "type-discarded".into(); - let mut passes = Vec::new(); - let mut out = ctx.run_ui(egui::RawInput { focused: true, ..Default::default() }, |ui| { - handle_keys(&mut app, ui.ctx()); - let rect = egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400.0, 300.0)); - let xf = ViewXform { rect, zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; - draw_overlay(&mut app, ui.painter(), &xf); - if passes.is_empty() { - ui.ctx().request_discard("IME transition regression"); - } - let discarded = ui.ctx().will_discard(); - let pending_before = app.type_ime.interrupt; - sync_ime(&mut app, ui.ctx()); - finish_reset_pass(&mut app, ui.ctx()); - passes.push((discarded, pending_before, app.type_ime.interrupt)); - }); - out.textures_delta.clear(); - assert_eq!(passes.first(), Some(&(true, true, true)), "discard retains the interrupt latch"); - assert_eq!(passes.last(), Some(&(false, true, false)), "the accepted pass delivers it once"); - assert!(out.platform_output.ime.expect("final descriptor").should_interrupt_composition); - let next = run(&mut app, &ctx, Vec::new()).expect("next descriptor"); - assert!(!next.should_interrupt_composition, "a delivered interrupt is not replayed"); - } - - #[test] - fn delete_surrounding_characters_is_one_undo_step() { - let ctx = context(); - let mut app = app(); - commit(&mut app); - edit_active(&mut app).unwrap(); - if let Some(ed) = app.ui.text_edit.as_mut() { - ed.caret = 3; - ed.anchor = 3; - } - run(&mut app, &ctx, Vec::new()).expect("baseline descriptor"); - let deleted = - run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 })]).expect("deletion descriptor"); - assert_eq!(deleted.change_cause, ImeChangeCause::InputMethod); - assert_eq!(layer_text(&app), "ab"); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(layer_text(&app), "abc", "the delete and its session coalesce into one step"); - } - - #[test] - fn an_empty_point_text_reports_an_available_empty_snapshot() { - let ctx = context(); - let mut app = app(); - if let Some(ed) = app.ui.text_edit.as_mut() { - ed.anchor = 0; - ed.caret = 3; - } - insert(&mut app, ""); - assert_eq!(layer_text(&app), ""); - let empty = run(&mut app, &ctx, Vec::new()).expect("descriptor"); - let available = payload(&empty); - assert_eq!(available.text, ""); - assert_eq!((available.cursor, available.anchor), (0, 0)); - } - - #[test] - fn a_long_line_reports_a_bounded_snapshot() { - let ctx = context(); - let mut app = app(); - if let Some(ed) = app.ui.text_edit.as_mut() { - ed.anchor = 0; - ed.caret = 3; - } - insert(&mut app, &"a".repeat(4500)); - let long = run(&mut app, &ctx, Vec::new()).expect("descriptor"); - let available = payload(&long); - assert!(available.text.len() <= egui::output::MAX_IME_SURROUNDING_TEXT_BYTES); - assert!(available.text.is_char_boundary(available.cursor)); - assert!(available.text.is_char_boundary(available.anchor)); - } - - #[test] - fn the_real_app_logic_and_ui_publish_the_descriptor() { - use eframe::App as _; - let ctx = context(); - let mut app = app(); - let mut frame = eframe::Frame::_new_kittest(); - let mut descriptors = Vec::new(); - // The first pass registers fonts; the next passes run the real logic → ui orchestration - // (where `handle_keys` and the final `sync_ime` live). - for _ in 0..3 { - let raw = - egui::RawInput { focused: true, screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, 800.0))), ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| { - app.logic(ui.ctx(), &mut frame); - app.ui(ui, &mut frame); - }); - out.textures_delta.clear(); // No renderer consumes this harness output. - descriptors.push(out.platform_output.ime); - } - let ime = descriptors.iter().flatten().last().expect("a descriptor from App::ui"); - assert!(ime.surrounding_text.available().is_some()); - assert!(ime.context_generation > 0); - } - - fn terminal_delete(bytes: bool) -> egui::Event { - egui::Event::Ime(if bytes { - egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 } - } else { - egui::ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 } - }) - } - - fn raw_key(key: egui::Key, command: bool, shift: bool) -> egui::Event { - egui::Event::Key { - key, - physical_key: Some(key), - pressed: true, - repeat: false, - modifiers: egui::Modifiers { - command, - ctrl: command && !cfg!(target_os = "macos"), - mac_cmd: command && cfg!(target_os = "macos"), - shift, - ..Default::default() - }, - } - } - - #[test] - fn stale_owner_terminal_survives_idle_and_split_delete_commit_but_fresh_input_works() { - for empty in [false, true] { - for bytes in [false, true] { - let ctx = context(); - let mut app = app(); - run(&mut app, &ctx, vec![]); - run(&mut app, &ctx, vec![preedit("P")]); - if empty { - run(&mut app, &ctx, vec![preedit("")]); - } - let old_layer = app.ui.text_edit.as_ref().unwrap().layer; - let created = app.run("type.create", json!({"text": "two", "x": 150, "y": 60})).unwrap(); - let second = created["layer"].as_u64().unwrap(); - app.session.select_layer(LayerId(second)).unwrap(); - edit_active(&mut app).unwrap(); - let transition = run(&mut app, &ctx, vec![]).unwrap(); - assert!(transition.should_interrupt_composition); - for _ in 0..5 { - run(&mut app, &ctx, vec![]); - } - let revision = app.session.active().unwrap().revision; - let undo = app.session.active().unwrap().history.entries().len(); - let before = layer_text(&app); - run(&mut app, &ctx, vec![terminal_delete(bytes)]); - for _ in 0..3 { - run(&mut app, &ctx, vec![]); - } - run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("X".into()))]); - assert_eq!(layer_text(&app), before, "an old split terminal cannot edit a replacement owner"); - assert_eq!(app.session.active().unwrap().revision, revision); - assert_eq!(app.session.active().unwrap().history.entries().len(), undo); - assert_eq!(current_text(&app, LayerId(old_layer)).unwrap(), if empty { "abc" } else { "abcP" }); - let selection = app.ui.text_edit.as_ref().unwrap().clone(); - let (a, b) = (selection.anchor.min(selection.caret), selection.anchor.max(selection.caret)); - let expected = before.chars().take(a).chain("Q".chars()).chain(before.chars().skip(b)).collect::(); - run( - &mut app, - &ctx, - vec![completed(transition.reset_request.expect("reset request")), preedit("Q"), egui::Event::Ime(egui::ImeEvent::Commit("Q".into()))], - ); - assert_eq!(layer_text(&app), expected, "the exact completion permits fresh input"); - run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("R".into()))]); - assert!(layer_text(&app).contains("QR"), "a later direct commit remains valid"); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(current_text(&app, LayerId(second)).unwrap(), before, "the new session is undoable"); - } - } - } - - #[test] - fn raw_application_selection_changes_reject_old_terminal_input_and_allow_later_fresh_input() { - for empty in [false, true] { - for bytes in [false, true] { - for (key, command, shift) in [(egui::Key::A, true, false), (egui::Key::ArrowLeft, false, false), (egui::Key::Home, false, true)] { - let ctx = context(); - let mut app = app(); - run(&mut app, &ctx, vec![]); - run(&mut app, &ctx, vec![preedit("P")]); - if empty { - run(&mut app, &ctx, vec![preedit("")]); - } - let before = layer_text(&app); - let revision = app.session.active().unwrap().revision; - let transition = run(&mut app, &ctx, vec![raw_key(key, command, shift)]).expect("selection reset"); - let selected = app.ui.text_edit.as_ref().unwrap().clone(); - assert!( - (selected.anchor, selected.caret) != (before.chars().count(), before.chars().count()), - "actual raw selection key changed the caret" - ); - for _ in 0..3 { - run(&mut app, &ctx, vec![]); - } - let undo = app.session.active().unwrap().history.entries().len(); - run(&mut app, &ctx, vec![terminal_delete(bytes), egui::Event::Ime(egui::ImeEvent::Commit("X".into()))]); - assert_eq!(layer_text(&app), before); - assert_eq!(app.session.active().unwrap().revision, revision); - assert_eq!(app.session.active().unwrap().history.entries().len(), undo); - assert_eq!(app.ui.text_edit.as_ref().map(|e| (e.anchor, e.caret)), Some((selected.anchor, selected.caret))); - let (a, b) = (selected.anchor.min(selected.caret), selected.anchor.max(selected.caret)); - let expected = before.chars().take(a).chain("Q".chars()).chain(before.chars().skip(b)).collect::(); - // The completion opens admission at its exact position in the batch. - run( - &mut app, - &ctx, - vec![completed(transition.reset_request.expect("reset request")), preedit("Q"), egui::Event::Ime(egui::ImeEvent::Commit("Q".into()))], - ); - assert_eq!(layer_text(&app), expected); - } - } - } - } - - #[test] - fn uninterrupted_live_and_empty_preedit_delete_commit_and_direct_commit_stay_valid() { - for empty in [false, true] { - for bytes in [false, true] { - let ctx = context(); - let mut app = app(); - run(&mut app, &ctx, vec![]); - run(&mut app, &ctx, vec![preedit("P")]); - if empty { - run(&mut app, &ctx, vec![preedit("")]); - } - run(&mut app, &ctx, vec![terminal_delete(bytes)]); - for _ in 0..3 { - run(&mut app, &ctx, vec![]); - } - run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("X".into()))]); - assert_eq!(layer_text(&app), "abX", "accepted deletion refreshes its composing caret"); - } - } - let ctx = context(); - let mut app = app(); - run(&mut app, &ctx, vec![]); - run(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false), egui::Event::Ime(egui::ImeEvent::Commit("D".into()))]); - assert_eq!(layer_text(&app), "D", "without known preedit the direct commit replaces the selection"); - } - - fn actual_app_frame(app: &mut PhotocraftApp, ctx: &egui::Context, events: Vec) -> egui::FullOutput { - use eframe::App as _; - let mut frame = eframe::Frame::_new_kittest(); - let mut raw = - egui::RawInput { focused: true, events, screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, 800.0))), ..Default::default() }; - app.raw_input_hook(ctx, &mut raw); - let mut output = ctx.run_ui(raw, |ui| { - app.logic(ui.ctx(), &mut frame); - app.ui(ui, &mut frame); - }); - output.textures_delta.clear(); - output - } - - #[test] - fn the_real_app_pointer_interruption_rejects_idle_delayed_terminal_then_accepts_fresh_input() { - for empty in [false, true] { - for bytes in [false, true] { - let ctx = context(); - let mut app = app(); - for _ in 0..4 { - actual_app_frame(&mut app, &ctx, vec![]); - } - app.ui.text_edit.as_mut().unwrap().caret = 1; - app.ui.text_edit.as_mut().unwrap().anchor = 1; - let point = actual_app_frame(&mut app, &ctx, vec![]).platform_output.ime.expect("real caret1 descriptor").cursor_rect.center(); - app.ui.text_edit.as_mut().unwrap().caret = 3; - app.ui.text_edit.as_mut().unwrap().anchor = 3; - actual_app_frame(&mut app, &ctx, vec![]); - actual_app_frame(&mut app, &ctx, vec![preedit("P")]); - if empty { - actual_app_frame(&mut app, &ctx, vec![preedit("")]); - } - let before = layer_text(&app); - let button = |pressed| egui::Event::PointerButton { pos: point, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - let press = - actual_app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(point), button(true)]).platform_output.ime.expect("press descriptor"); - let release = actual_app_frame(&mut app, &ctx, vec![button(false)]).platform_output.ime.expect("release descriptor"); - let request = release.reset_request.or(press.reset_request).expect("pointer reset"); - assert_eq!(app.ui.text_edit.as_ref().unwrap().caret, 1, "actual canvas pointer moved the caret"); - for _ in 0..4 { - actual_app_frame(&mut app, &ctx, vec![]); - } - let revision = app.session.active().unwrap().revision; - actual_app_frame(&mut app, &ctx, vec![terminal_delete(bytes), egui::Event::Ime(egui::ImeEvent::Commit("X".into()))]); - assert_eq!(layer_text(&app), before); - assert_eq!(app.session.active().unwrap().revision, revision); - actual_app_frame(&mut app, &ctx, vec![completed(request), preedit("Q"), egui::Event::Ime(egui::ImeEvent::Commit("Q".into()))]); - let expected = before.chars().take(1).chain("Q".chars()).chain(before.chars().skip(1)).collect::(); - assert_eq!(layer_text(&app), expected); - } - } - } - - #[test] - fn only_a_matching_completion_allows_a_new_composition_in_the_same_raw_batch() { - for bytes in [false, true] { - let ctx = context(); - let mut app = app(); - run(&mut app, &ctx, vec![]); - run(&mut app, &ctx, vec![preedit("P")]); - let transition = run(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false)]).expect("selection reset"); - run( - &mut app, - &ctx, - vec![ - terminal_delete(bytes), - egui::Event::Ime(egui::ImeEvent::Commit("old".into())), - completed(transition.reset_request.expect("reset request")), - preedit("Q"), - egui::Event::Ime(egui::ImeEvent::Commit("Q".into())), - ], - ); - assert_eq!(layer_text(&app), "Q", "the old terminal is rejected before the completion opens admission"); - } - } - - #[test] - fn an_actual_same_batch_selection_requires_completion_before_the_new_live_preedit() { - for empty in [false, true] { - for bytes in [false, true] { - for terminal in [false, true] { - let ctx = context(); - let mut app = app(); - for _ in 0..4 { - actual_app_frame(&mut app, &ctx, vec![]); - } - actual_app_frame(&mut app, &ctx, vec![preedit("P")]); - if empty { - actual_app_frame(&mut app, &ctx, vec![preedit("")]); - } - let before = layer_text(&app); - let revision = app.session.active().unwrap().revision; - let mut events = vec![raw_key(egui::Key::A, true, false), terminal_delete(bytes)]; - if terminal { - events.push(egui::Event::Ime(egui::ImeEvent::Commit("old".into()))); - } - events.push(preedit("Q")); - let out = actual_app_frame(&mut app, &ctx, events); - assert_eq!(layer_text(&app), before, "all unacknowledged payloads remain stale, even after Commit"); - assert_eq!(app.session.active().unwrap().revision, revision); - assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale))); - let selected = app.ui.text_edit.as_ref().unwrap(); - assert_eq!((selected.anchor, selected.caret), (0, before.chars().count()), "the actual selection key ran"); - let request = out.platform_output.ime.expect("interrupted descriptor").reset_request.expect("reset request"); - actual_app_frame(&mut app, &ctx, vec![completed(request), preedit("Q")]); - assert_eq!(layer_text(&app), "Q", "only the new preedit replaced the selected text"); - assert_eq!(app.session.active().unwrap().revision, revision + 1, "neither old deletion nor old commit mutated the document"); - let editing = app.ui.text_edit.as_ref().unwrap(); - assert_eq!((editing.anchor, editing.caret, editing.preedit), (1, 1, Some((0, 1)))); - assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Active(_)))); - // Keep Q live across a real idle pass before its separately delivered commit. - let idle = actual_app_frame(&mut app, &ctx, vec![]); - assert!(!idle.platform_output.ime.expect("the live preview keeps its descriptor").should_interrupt_composition); - actual_app_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("Q".into()))]); - assert_eq!(layer_text(&app), "Q"); - assert!(app.ui.text_edit.as_ref().unwrap().preedit.is_none()); - assert!(app.type_ime.incoming.is_none()); - } - } - } - } - - fn pending(app: &PhotocraftApp) -> Option { - match app.type_ime.resets.get(&egui::ViewportId::ROOT) { - Some(ResetPhase::Awaiting { id, .. }) => Some(*id), - _ => None, - } - } - - fn interrupt_with_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> egui::ImeResetId { - run(app, ctx, vec![preedit("P")]); - run(app, ctx, vec![raw_key(egui::Key::A, true, false)]).expect("custom output").reset_request.expect("published reset") - } - - #[test] - fn newest_published_request_alone_opens_the_ordered_suffix() { - let ctx = context(); - let mut app = app(); - let first = interrupt_with_selection(&mut app, &ctx); - let second = run(&mut app, &ctx, vec![raw_key(egui::Key::ArrowLeft, false, false), completed(first), preedit("old")]) - .expect("moved selection") - .reset_request - .expect("replacement request"); - assert_ne!(first, second); - let before = layer_text(&app); - let revision = app.session.active().unwrap().revision; - let history = app.session.active().unwrap().history.entries().len(); - run(&mut app, &ctx, vec![terminal_delete(true), completed(first), egui::Event::Ime(egui::ImeEvent::Commit("old".into()))]); - assert_eq!(layer_text(&app), before); - assert_eq!(app.session.active().unwrap().revision, revision); - assert_eq!(app.session.active().unwrap().history.entries().len(), history); - assert_eq!(pending(&app), Some(second)); - let selection = app.ui.text_edit.as_ref().map(|e| (e.anchor, e.caret)); - run(&mut app, &ctx, vec![completed(second), completed(second)]); - assert_eq!(layer_text(&app), before, "controls alone never edit text"); - assert_eq!(app.ui.text_edit.as_ref().map(|e| (e.anchor, e.caret)), selection); - assert_eq!(app.session.active().unwrap().revision, revision); - assert_eq!(app.session.active().unwrap().history.entries().len(), history); - assert_eq!(pending(&app), None); - run(&mut app, &ctx, vec![preedit("が"), egui::Event::Ime(egui::ImeEvent::Commit("が".into()))]); - assert!(layer_text(&app).starts_with("が")); - } - - #[test] - fn foreign_viewport_and_context_completions_cannot_release_root() { - let ctx = context(); - let mut app = app(); - let root = interrupt_with_selection(&mut app, &ctx); - let other = context(); - let viewport = egui::ViewportId::from_hash_of("photo-reset-foreign"); - let foreign_input = || { - let rect = egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400.0, 300.0)); - let mut raw = egui::RawInput { viewport_id: viewport, screen_rect: Some(rect), focused: true, ..Default::default() }; - raw.viewports.insert( - viewport, - egui::ViewportInfo { inner_rect: Some(rect), native_pixels_per_point: Some(1.0), minimized: Some(false), ..Default::default() }, - ); - raw - }; - let mut text = String::new(); - let mut output = other.run_ui(foreign_input(), |ui| { - ui.add(egui::TextEdit::singleline(&mut text)).request_focus(); - let _ = ui.ctx().request_ime_reset(viewport); - }); - output.textures_delta.clear(); - // Draw once more if egui has not yet reported the newly focused stock editor. - if output.platform_output.ime.is_none() { - output = other.run_ui(foreign_input(), |ui| { - ui.add(egui::TextEdit::singleline(&mut text)); - }); - output.textures_delta.clear(); - } - let foreign = output.platform_output.ime.expect("foreign stock output").reset_request.expect("foreign published request"); - assert_ne!(foreign.viewport_id(), root.viewport_id()); - let before = layer_text(&app); - run(&mut app, &ctx, vec![completed(foreign), preedit("bad"), completed(root), preedit("が")]); - assert_eq!(layer_text(&app), "が", "foreign marker cannot open admission before the root marker"); - assert_ne!(layer_text(&app), before); - } - - #[test] - fn standalone_logic_suspends_once_without_replaying_input_and_return_rearms_once() { - use eframe::App as _; - let ctx = context(); - let mut app = app(); - for _ in 0..4 { - actual_app_frame(&mut app, &ctx, vec![]); - } - actual_app_frame(&mut app, &ctx, vec![preedit("P")]); - let first = actual_app_frame(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false)]) - .platform_output - .ime - .expect("custom output") - .reset_request - .expect("first request"); - let before = layer_text(&app); - for _ in 0..3 { - let mut frame = eframe::Frame::_new_kittest(); - let _ = ctx.run_logic(&egui::RawInput { focused: true, ..Default::default() }, |ctx| app.logic(ctx, &mut frame)); - assert_eq!(layer_text(&app), before, "hidden logic does not replay the previous raw selection batch"); - assert_eq!(pending(&app), None); - assert!(matches!(app.type_ime.resets.get(&egui::ViewportId::ROOT), Some(ResetPhase::Suspended))); - } - let second = actual_app_frame(&mut app, &ctx, vec![completed(first), preedit("bad")]) - .platform_output - .ime - .expect("returned custom output") - .reset_request - .expect("fresh request after hidden logic"); - assert_ne!(first, second); - assert_eq!(layer_text(&app), before); - for _ in 0..3 { - let idle = actual_app_frame(&mut app, &ctx, vec![]).platform_output.ime.expect("idle custom output"); - assert_eq!(idle.reset_request, None, "logic inside a full UI pass cannot suspend and rearm the stable guard"); - assert_eq!(pending(&app), Some(second)); - } - actual_app_frame(&mut app, &ctx, vec![completed(second), preedit("が"), egui::Event::Ime(egui::ImeEvent::Commit("が".into()))]); - assert_eq!(layer_text(&app), "が"); - } - - #[test] - fn standalone_logic_does_not_guard_an_uninterrupted_terminal_pending_composition() { - use eframe::App as _; - let ctx = context(); - let mut app = app(); - for _ in 0..4 { - actual_app_frame(&mut app, &ctx, vec![]); - } - actual_app_frame(&mut app, &ctx, vec![preedit("P"), preedit("")]); - let mut frame = eframe::Frame::_new_kittest(); - let _ = ctx.run_logic(&egui::RawInput { focused: true, ..Default::default() }, |ctx| app.logic(ctx, &mut frame)); - assert!(app.type_ime.resets.is_empty()); - assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::TerminalPending(_)))); - actual_app_frame(&mut app, &ctx, vec![terminal_delete(false), egui::Event::Ime(egui::ImeEvent::Commit("X".into()))]); - assert_eq!(layer_text(&app), "abX"); - } - - #[test] - fn fonts_not_ready_and_no_editor_early_returns_retire_the_old_request() { - use eframe::App as _; - for no_editor in [false, true] { - let ctx = context(); - let mut app = app(); - for _ in 0..4 { - actual_app_frame(&mut app, &ctx, vec![]); - } - actual_app_frame(&mut app, &ctx, vec![preedit("P")]); - let first = actual_app_frame(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false)]) - .platform_output - .ime - .expect("custom output") - .reset_request - .expect("first request"); - let editor = app.ui.text_edit.clone(); - let before = layer_text(&app); - let mut frame = eframe::Frame::_new_kittest(); - let mut output = ctx.run_ui(egui::RawInput { focused: true, events: vec![completed(first), preedit("bad")], ..Default::default() }, |ui| { - if no_editor { - app.ui.text_edit = None; - } else { - app.fonts_ready = false; - } - app.ui(ui, &mut frame); - }); - output.textures_delta.clear(); - assert!(output.platform_output.ime.is_none()); - assert_eq!(pending(&app), None); - app.ui.text_edit = editor; - app.fonts_ready = true; - let second = actual_app_frame(&mut app, &ctx, vec![completed(first), preedit("bad")]) - .platform_output - .ime - .expect("same editor returned") - .reset_request - .expect("rearmed request"); - assert_ne!(first, second); - assert_eq!(layer_text(&app), before); - actual_app_frame(&mut app, &ctx, vec![completed(second), preedit("が")]); - assert_eq!(layer_text(&app), "が"); - } - } - - #[test] - fn pointer_deferred_suffix_cannot_edit_the_old_caret_or_complete_its_old_request() { - let ctx = context(); - let mut app = app(); - for _ in 0..4 { - actual_app_frame(&mut app, &ctx, vec![]); - } - app.ui.text_edit.as_mut().unwrap().caret = 1; - app.ui.text_edit.as_mut().unwrap().anchor = 1; - let point = actual_app_frame(&mut app, &ctx, vec![]).platform_output.ime.expect("caret geometry").cursor_rect.center(); - app.ui.text_edit.as_mut().unwrap().caret = 3; - app.ui.text_edit.as_mut().unwrap().anchor = 3; - actual_app_frame(&mut app, &ctx, vec![preedit("P")]); - let first = actual_app_frame(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false)]) - .platform_output - .ime - .expect("selection output") - .reset_request - .expect("first request"); - let before = layer_text(&app); - let revision = app.session.active().unwrap().revision; - let event = |pressed| egui::Event::PointerButton { pos: point, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - let out = actual_app_frame( - &mut app, - &ctx, - vec![ - egui::Event::PointerMoved(point), - event(true), - completed(first), - egui::Event::Text("bad".into()), - egui::Event::Paste("bad".into()), - egui::Event::Cut, - preedit("bad"), - ], - ); - let first_after_pointer = out.platform_output.ime.expect("pointer output").reset_request; - let out = actual_app_frame(&mut app, &ctx, vec![event(false)]); - let second = out.platform_output.ime.expect("release output").reset_request.or(first_after_pointer).expect("actual pointer destination reset"); - assert_ne!(first, second); - assert_eq!(layer_text(&app), before); - assert_eq!(app.session.active().unwrap().revision, revision); - assert_eq!(app.ui.text_edit.as_ref().unwrap().caret, 1); - actual_app_frame(&mut app, &ctx, vec![completed(second), preedit("が")]); - assert!(layer_text(&app).contains("が")); - } - - #[test] - fn completion_without_current_geometry_is_suspended_before_the_following_preedit() { - let ctx = context(); - let mut app = app(); - let first = interrupt_with_selection(&mut app, &ctx); - let before = layer_text(&app); - // No canvas view for this input batch: the completion cannot be attributed to a visible - // custom descriptor yet. This is the pre-descriptor check, not a wait on final output. - app.type_ime.view = None; - let output = run(&mut app, &ctx, vec![completed(first), preedit("bad")]).expect("custom output"); - let second = output.reset_request.expect("the final custom output rearms"); - assert_ne!(first, second); - assert_eq!(layer_text(&app), before, "the preedit after a geometry-less completion stays blocked"); - assert!(matches!(app.type_ime.resets.get(&egui::ViewportId::ROOT), Some(ResetPhase::Awaiting { id, .. }) if *id == second)); - run(&mut app, &ctx, vec![completed(second), preedit("が")]); - assert_eq!(layer_text(&app), "が"); - } - - #[test] - fn pointer_press_without_a_guard_defers_the_same_batch_custom_suffix() { - let ctx = context(); - let mut app = app(); - let before = layer_text(&app); - let revision = app.session.active().unwrap().revision; - let selection = app.ui.text_edit.as_ref().map(|ed| (ed.anchor, ed.caret)); - let press = - egui::Event::PointerButton { pos: Pos2::new(20.0, 20.0), button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }; - let output = run( - &mut app, - &ctx, - vec![ - egui::Event::PointerMoved(Pos2::new(20.0, 20.0)), - press, - egui::Event::Text("bad".into()), - egui::Event::Paste("bad".into()), - egui::Event::Cut, - preedit("bad"), - ], - ) - .expect("descriptor"); - assert_eq!(layer_text(&app), before, "the deferred canvas handler never lets a suffix edit the old caret"); - assert_eq!(app.session.active().unwrap().revision, revision); - assert_eq!(app.ui.text_edit.as_ref().map(|ed| (ed.anchor, ed.caret)), selection); - assert_eq!(output.reset_request, None, "no prior guard means no speculative reset yet"); - } - - #[test] - fn synchronous_select_all_accepts_fresh_text_but_still_blocks_stale_ime() { - let ctx = context(); - // With no guard, the synchronously selected destination is a real destination: Text is - // an application edit, not an old IME suffix. - let mut app = app(); - run(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false), egui::Event::Text("x".into())]); - assert_eq!(layer_text(&app), "x"); - - // The same holds when Cmd+A interrupted a known composition: Text is still fresh input. - let mut app = self::app(); - run(&mut app, &ctx, vec![preedit("P")]); - let out = run(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false), egui::Event::Text("x".into())]).expect("custom output"); - assert_eq!(layer_text(&app), "x"); - assert!(out.reset_request.is_some(), "the stale composition still needs its ordered reset"); - - // An IME payload in that same batch is not fresh Text: it remains blocked until its - // replacement request is actually completed. - let mut app = self::app(); - run(&mut app, &ctx, vec![preedit("P")]); - let before = layer_text(&app); - let out = run(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false), preedit("bad")]).expect("custom output"); - assert_eq!(layer_text(&app), before); - let request = out.reset_request.expect("selection reset request"); - run(&mut app, &ctx, vec![completed(request), preedit("が")]); - assert_eq!(layer_text(&app), "が"); - } - - struct ResetHarness { - app: PhotocraftApp, - stock: bool, - picker_button: bool, - search: String, - search_input: Option, - search_focused: bool, - search_height: Option, - } - - fn reset_harness(app: PhotocraftApp) -> egui_kittest::Harness<'static, ResetHarness> { - let mut h = egui_kittest::Harness::builder() - .with_size(egui::vec2(1200.0, 800.0)) - .with_context_setup(|ctx| { - install_reset_hooks(ctx); - crate::theme::install_fonts(ctx); - }) - .build_ui_state( - |ui, state: &mut ResetHarness| { - let mut frame = eframe::Frame::_new_kittest(); - state.app.logic_frame(ui.ctx(), &mut frame); - state.app.ui_frame(ui, &mut frame); - if state.stock { - egui::Window::new("Reset font fixture").show(ui.ctx(), |ui| { - let button = ui.make_persistent_id(egui::IdSalt::new("reset-font")); - egui::Popup::open_id(ui.ctx(), button.with("popup")); - let mut current = "Family 00".to_owned(); - family_picker_in( - ui, - "reset-font", - &mut current, - 170.0, - &["Family 00".into(), "Family 01".into()], - photocraft_engine::prefs::FontPreview::Medium, - &[], - ); - let search = ui.scope_id().with(("font-search", "reset-font")); - state.search = ui.data(|d| d.get_temp::(search)).unwrap_or_default(); - let input = search.with("input"); - state.search_input = Some(input); - state.search_focused = ui.memory(|m| m.has_focus(input)); - state.search_height = ui.data(|d| d.get_temp::(search.with("height"))); - }); - } - if state.picker_button { - egui::Window::new("Reset screen fixture").show(ui.ctx(), |ui| { - crate::screen_picker::button(ui, egui::Id::unique("reset-screen")); - }); - } - state.app.finish_type_reset_pass(ui.ctx()); - }, - ResetHarness { app, stock: false, picker_button: false, search: String::new(), search_input: None, search_focused: false, search_height: None }, - ); - h.run_steps(4); - h - } - - fn harness_request(h: &egui_kittest::Harness<'_, ResetHarness>) -> egui::ImeResetId { - h.output().platform_output.ime.as_ref().expect("actual harness output").reset_request.expect("published harness reset") - } - - #[test] - fn actual_font_search_owns_stock_input_without_a_speculative_custom_request() { - let mut h = reset_harness(app()); - h.event(preedit("P")); - h.step(); - h.event(raw_key(egui::Key::A, true, false)); - h.step(); - let first = harness_request(&h); - let before = layer_text(&h.state().app); - let custom_owner = h.output().platform_output.ime.as_ref().unwrap().owner; - h.state_mut().stock = true; - h.run_steps(3); - let stock_owner = h.output().platform_output.ime.as_ref().expect("real font search descriptor").owner; - assert_ne!(stock_owner, custom_owner); - let search_input = h.state().search_input.expect("font search field id"); - assert!(h.state().search_focused, "the real font search field, not another stock field, owns focus"); - assert_eq!(h.ctx.memory(|m| m.focused()), Some(search_input), "the stock IME owner is the focused font search input"); - assert!( - h.state().search_height.is_some_and(|height| height > 0.0 && height <= FONT_MENU_HEIGHT), - "the real font list measured within its bounded popup height" - ); - h.input_mut().events = vec![completed(first), egui::Event::Text("Family".into())]; - h.step(); - assert_eq!(h.state().search, "Family", "the actual font picker keeps its text event"); - assert_eq!(layer_text(&h.state().app), before); - assert_eq!(pending(&h.state().app), None); - let stock = h.output().platform_output.ime.as_ref().expect("stock output survives finalization"); - assert_eq!(stock.owner, stock_owner); - assert_eq!(stock.reset_request, None, "an already-ineligible route cannot allocate a custom request"); - h.state_mut().stock = false; - egui::Popup::close_all(&h.ctx); - h.ctx.memory_mut(|m| m.stop_text_input()); - h.input_mut().events = vec![completed(first), preedit("bad")]; - h.step(); - let second = harness_request(&h); - assert_ne!(first, second); - assert_eq!(layer_text(&h.state().app), before); - h.step(); - assert_eq!(h.output().platform_output.ime.as_ref().unwrap().reset_request, None); - h.input_mut().events = vec![completed(second), preedit("が")]; - h.step(); - assert_eq!(layer_text(&h.state().app), "が"); - } - - type ImmediateViewportRecord = (egui::ViewportId, egui::ViewportId, Option, Option); - - fn record_immediate_viewports() -> Arc>> { - let seen = Arc::new(std::sync::Mutex::new(Vec::new())); - let recorded = seen.clone(); - egui::Context::set_immediate_viewport_renderer(move |ctx, immediate| { - let ids = immediate.ids; - if let Ok(mut seen) = recorded.lock() { - seen.push((ids.this, ids.parent, immediate.builder.inner_size, immediate.builder.visible)); - } - let mut callback = immediate.viewport_ui_cb; - let mut output = ctx.run_ui( - egui::RawInput { - viewport_id: ids.this, - viewports: std::iter::once((ids.this, egui::ViewportInfo::default())).collect(), - screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(2.0, 2.0))), - ..Default::default() - }, - |ui| callback(ui), - ); - output.textures_delta.clear(); - }); - seen - } - - #[test] - fn actual_screen_picker_modal_retires_the_type_fence_and_return_rearms_it() { - use egui_kittest::kittest::Queryable as _; - let mut app = app(); - app.services.screen_pick = Some(Box::new(|_| { - let (sender, receiver) = std::sync::mpsc::channel(); - sender - .send(Ok(crate::screen_picker::Capture::Images(vec![crate::screen_picker::ScreenImage { - monitor: None, - position: Pos2::ZERO, - size: egui::vec2(2.0, 2.0), - width: 2, - height: 2, - rgba: vec![0; 16], - profile: None, - }]))) - .unwrap(); - crate::screen_picker::Pending { receiver, cancelled: Arc::new(std::sync::atomic::AtomicBool::new(false)) } - })); - let mut h = reset_harness(app); - h.event(preedit("P")); - h.step(); - h.event(raw_key(egui::Key::A, true, false)); - h.step(); - let first = harness_request(&h); - let before = layer_text(&h.state().app); - let immediate = record_immediate_viewports(); - h.ctx.set_embed_viewports(false); - h.state_mut().picker_button = true; - h.run_steps(2); - h.get_by_label("Pick screen color").click(); - h.run_steps(3); - assert!(crate::screen_picker::busy(&h.ctx)); - assert!(crate::screen_picker::showing(&h.ctx), "the actual UI takes its screen-picker modal early return"); - let seen = immediate.lock().expect("recorded viewports"); - assert!(!seen.is_empty(), "the native immediate-viewport renderer received the picker"); - assert!( - seen.iter().all(|(child, parent, size, visible)| *child != egui::ViewportId::ROOT - && *parent == egui::ViewportId::ROOT - && *size == Some(egui::vec2(2.0, 2.0)) - && *visible == Some(false)), - "each picker viewport is a hidden 2x2 child of the root" - ); - drop(seen); - h.input_mut().events = vec![completed(first), preedit("bad")]; - h.step(); - assert!(h.output().platform_output.ime.is_none()); - assert_eq!(pending(&h.state().app), None); - assert_eq!(layer_text(&h.state().app), before); - crate::screen_picker::cancel(&h.ctx); - h.state_mut().picker_button = false; - h.ctx.memory_mut(|m| m.stop_text_input()); - h.input_mut().events = vec![completed(first), preedit("bad")]; - h.step(); - let second = harness_request(&h); - assert_ne!(first, second); - assert_eq!(layer_text(&h.state().app), before); - h.input_mut().events = vec![completed(second), preedit("が")]; - h.step(); - assert_eq!(layer_text(&h.state().app), "が"); - } - - #[test] - fn a_discarded_custom_output_allocates_no_new_id_and_final_absence_retires_then_rearms() { - let ctx = context(); - ctx.options_mut(|o| o.max_passes = std::num::NonZeroUsize::new(4).unwrap()); - let mut app = app(); - // A prior queued R1 is deliberately present: the discard must preserve it, not allocate - // a speculative replacement for output egui will throw away. - let first = interrupt_with_selection(&mut app, &ctx); - let mut passes = 0; - let mut discarded_pending = None; - let mut output = ctx.run_ui(egui::RawInput { focused: true, ..Default::default() }, |ui| { - handle_keys(&mut app, ui.ctx()); - if passes == 0 { - let xf = ViewXform { - rect: egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400.0, 300.0)), - zoom: 1.0, - center: [100.0, 100.0], - flip: false, - rotation: 0.0, - aspect: 1.0, - }; - draw_overlay(&mut app, ui.painter(), &xf); - ui.ctx().request_discard("reset custom output disappears on final pass"); - } - sync_ime(&mut app, ui.ctx()); - finish_reset_pass(&mut app, ui.ctx()); - if passes == 0 { - discarded_pending = pending(&app); - } - passes += 1; - }); - output.textures_delta.clear(); - assert!(passes > 1); - assert!(output.platform_output.ime.is_none()); - assert_eq!(discarded_pending, Some(first), "discard keeps the queued R1 and allocates no NEW id"); - assert_eq!(pending(&app), None, "the final ineligible pass retires the prior R1"); - let before = layer_text(&app); - let returned = run(&mut app, &ctx, vec![completed(first), preedit("bad")]).expect("same model returns"); - let second = returned.reset_request.expect("new published request"); - assert_ne!(first, second); - assert_eq!(layer_text(&app), before); - run(&mut app, &ctx, vec![completed(second), preedit("が")]); - assert_eq!(layer_text(&app), "が"); - } - - #[test] - fn a_recreated_context_installed_before_run_ui_rejects_the_old_completion_and_rearms() { - use eframe::App as _; - let old = context(); - let mut app = app(); - for _ in 0..4 { - actual_app_frame(&mut app, &old, vec![]); - } - let first = interrupt_with_selection(&mut app, &old); - let before = layer_text(&app); - // The host replaces its Context and must run the same supported setup before `run_ui`; - // a begin-pass hook registered later could not mark the first pass. - let next = egui::Context::default(); - PhotocraftApp::setup_context(&next, app.ui.theme); - let mut frame = eframe::Frame::_new_kittest(); - let mut saw_ui_pass = false; - let mut output = next.run_ui( - egui::RawInput { - focused: true, - events: vec![completed(first), preedit("bad")], - screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, 800.0))), - ..Default::default() - }, - |ui| { - app.logic(ui.ctx(), &mut frame); - saw_ui_pass = in_ui_pass(ui.ctx()); - app.ui(ui, &mut frame); - }, - ); - output.textures_delta.clear(); - assert!(saw_ui_pass, "the supported creator setup marks the first replacement Context pass"); - let second = output.platform_output.ime.expect("replacement Context custom output").reset_request.expect("replacement Context request"); - assert_ne!(first, second); - assert_eq!(layer_text(&app), before); - run(&mut app, &next, vec![completed(second), preedit("が")]); - assert_eq!(layer_text(&app), "が"); - } - - #[test] - fn type_mask_and_same_owner_session_replacement_supersede_the_full_request() { - for mask in [false, true] { - let ctx = context(); - let mut app = app(); - let first = interrupt_with_selection(&mut app, &ctx); - let original = run(&mut app, &ctx, vec![]).expect("original context"); - if mask { - app.ui.text_edit.as_mut().unwrap().mask = true; - } else { - app.ui.text_edit.as_mut().unwrap().session = "replacement-reset-session".into(); - } - let before = layer_text(&app); - let changed = run(&mut app, &ctx, vec![completed(first), preedit("bad")]).expect("replacement output"); - let second = changed.reset_request.expect("replacement request"); - assert_ne!(first, second); - if mask { - assert_ne!(changed.owner, original.owner); - } else { - assert_eq!(changed.owner, original.owner); - } - assert_ne!(changed.context_generation, original.context_generation); - assert_eq!(layer_text(&app), before); - run(&mut app, &ctx, vec![completed(first), terminal_delete(false), egui::Event::Ime(egui::ImeEvent::Commit("bad".into()))]); - assert_eq!(layer_text(&app), before); - run(&mut app, &ctx, vec![completed(second), preedit("が")]); - assert_eq!(layer_text(&app), "が"); - } - } - - #[test] - fn document_replacement_cannot_reuse_the_previous_documents_reset() { - let ctx = context(); - let mut app = app(); - let first = interrupt_with_selection(&mut app, &ctx); - let old_document = active_doc_id(&app); - app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); - app.sync_views(); - // The host runs this before handling input: a new active document ends the old edit in - // its own document, so the next canvas click starts an editor for the new one. - end_if_left(&mut app); - assert!(app.ui.text_edit.is_none(), "the new document starts without the previous edit target"); - app.ui.tool = crate::state::Tool::Type; - pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); - insert(&mut app, "new"); - assert_ne!(active_doc_id(&app), old_document); - let before = layer_text(&app); - let changed = run(&mut app, &ctx, vec![completed(first), preedit("bad")]).expect("new document output"); - let second = changed.reset_request.expect("new document reset"); - assert_ne!(first, second); - assert_eq!(layer_text(&app), before); - run(&mut app, &ctx, vec![completed(second), preedit("が")]); - assert!(layer_text(&app).contains("が")); - } -} +mod ime_tests; diff --git a/crates/ui-egui/src/type_tool/ime_tests.rs b/crates/ui-egui/src/type_tool/ime_tests.rs new file mode 100644 index 0000000000..48e08f533e --- /dev/null +++ b/crates/ui-egui/src/type_tool/ime_tests.rs @@ -0,0 +1,1343 @@ +use super::*; +use egui::output::{IMEOutput, ImeChangeCause}; + +fn context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + install_reset_hooks(&ctx); + ctx +} + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.sync_views(); + app.ui.tool = crate::state::Tool::Type; + pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); + insert(&mut app, "abc"); + app +} + +fn run(app: &mut PhotocraftApp, ctx: &egui::Context, events: Vec) -> Option { + let raw = egui::RawInput { focused: true, events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + let rect = egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400.0, 300.0)); + let xf = ViewXform { rect, zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + handle_keys(app, ui.ctx()); + draw_overlay(app, ui.painter(), &xf); + sync_ime(app, ui.ctx()); + finish_reset_pass(app, ui.ctx()); + }); + out.textures_delta.clear(); // This protocol harness does not paint. + out.platform_output.ime +} + +fn layer_text(app: &PhotocraftApp) -> String { + let ed = app.ui.text_edit.as_ref().expect("editing"); + current_text(app, LayerId(ed.layer)).expect("text layer") +} + +fn completed(request_id: egui::ImeResetId) -> egui::Event { + egui::Event::ImeResetCompleted { request_id } +} + +fn payload(ime: &IMEOutput) -> &egui::output::IMESurroundingTextPayload { + ime.surrounding_text.available().expect("a bounded committed snapshot") +} + +fn preedit(text: &str) -> egui::Event { + egui::Event::Ime(egui::ImeEvent::Preedit { text: text.to_owned(), active_range_chars: None }) +} + +#[test] +fn successive_ime_commits_are_input_method_and_keep_directional_offsets() { + let ctx = context(); + let mut app = app(); + let baseline = run(&mut app, &ctx, Vec::new()).expect("a focused editor descriptor"); + assert_eq!(payload(&baseline).text, "abc"); + assert_eq!(baseline.change_cause, ImeChangeCause::Other); + + // The pre-edit is laid out in the layer but is not committed surrounding text. + let composing = run(&mut app, &ctx, vec![preedit("に")]).expect("descriptor while composing"); + assert_eq!(payload(&composing).text, "abc"); + assert_eq!((payload(&composing).cursor, payload(&composing).anchor), (3, 3)); + + let first = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日本".into()))]).expect("commit descriptor"); + assert_eq!(first.change_cause, ImeChangeCause::InputMethod); + assert_eq!(payload(&first).text, "abc日本"); + + let composing = run(&mut app, &ctx, vec![preedit("ご")]).expect("second composition"); + assert_eq!(payload(&composing).text, "abc日本"); + let second = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("語".into()))]).expect("second commit"); + assert_eq!(second.change_cause, ImeChangeCause::InputMethod); + assert_eq!(payload(&second).text, "abc日本語"); + assert_eq!(payload(&second).cursor, payload(&second).text.len()); +} + +#[test] +fn reversed_selection_keeps_its_direction_in_byte_offsets() { + let ctx = context(); + let mut app = app(); + if let Some(ed) = app.ui.text_edit.as_mut() { + ed.caret = 1; + ed.anchor = 3; + } + let selected = run(&mut app, &ctx, Vec::new()).expect("descriptor"); + assert_eq!(payload(&selected).text, "abc"); + assert_eq!((payload(&selected).cursor, payload(&selected).anchor), (1, 3)); +} + +#[test] +fn mixed_application_and_ime_edits_in_one_frame_are_other() { + let ctx = context(); + let mut app = app(); + run(&mut app, &ctx, Vec::new()); + + // An IME commit followed by ordinary typing in the same pass: the application change + // dominates even though the commit itself was accepted. + let mixed = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("い".into())), egui::Event::Text("x".into())]).expect("mixed descriptor"); + assert_eq!(payload(&mixed).text, "abcいx"); + assert_eq!(mixed.change_cause, ImeChangeCause::Other); + + // The observed mixed state is the next baseline, so a later clean IME commit is once + // again an InputMethod change. + let next = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("う".into()))]).expect("next commit"); + assert_eq!(next.change_cause, ImeChangeCause::InputMethod); + assert_eq!(payload(&next).text, "abcいxう"); + + // Application text before the commit in the same frame must also prevent InputMethod. + let mut app = self::app(); + run(&mut app, &ctx, Vec::new()); + let mixed = run(&mut app, &ctx, vec![egui::Event::Text("x".into()), egui::Event::Ime(egui::ImeEvent::Commit("い".into()))]).expect("mixed descriptor"); + assert_eq!(mixed.change_cause, ImeChangeCause::Other); + assert_eq!(payload(&mixed).text, "abcxい"); +} + +#[test] +fn replaced_layer_or_session_bumps_generation_without_changing_owner() { + let ctx = context(); + let mut app = app(); + let first = run(&mut app, &ctx, Vec::new()).expect("descriptor"); + let owner = first.owner; + let generation = first.context_generation; + + // Same document and layer id, a new edit session: the replacement epoch changes, so the + // stale generation cannot be reused by a native IME bridge. + app.ui.text_edit.as_mut().unwrap().session = "type-replaced".into(); + let replaced = run(&mut app, &ctx, Vec::new()).expect("replaced descriptor"); + assert_eq!(replaced.owner, owner, "the layer identity is immutable"); + assert_ne!(replaced.context_generation, generation); + assert_eq!(replaced.change_cause, ImeChangeCause::Other); + + // Ending the editor ends the context; no descriptor is emitted for an absent owner. + app.ui.text_edit = None; + assert!(run(&mut app, &ctx, Vec::new()).is_none()); +} + +#[test] +fn unavailable_editor_state_still_carries_owner_and_generation() { + let ctx = context(); + let mut app = app(); + // A stale composition range cannot be mapped onto the layer: do not silently publish + // the composition as committed text. + app.ui.text_edit.as_mut().unwrap().preedit = Some((10, 5)); + let unavailable = run(&mut app, &ctx, Vec::new()).expect("descriptor with an owner"); + assert!(unavailable.surrounding_text.available().is_none()); + assert!(unavailable.context_generation > 0); + assert_eq!(unavailable.purpose, egui::IMEPurpose::Normal); +} + +#[test] +fn delete_surrounding_bytes_with_preedit_excludes_the_composition() { + let ctx = context(); + let mut app = app(); + run(&mut app, &ctx, Vec::new()); + run(&mut app, &ctx, vec![preedit("x")]); + assert_eq!(layer_text(&app), "abcx"); + assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, Some((3, 1))); + + // `c` is the byte immediately before the pre-edit; deleting it must not delete or + // report the composing `x`. + let deleted = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 })]) + .expect("deletion descriptor"); + assert_eq!(deleted.change_cause, ImeChangeCause::InputMethod); + assert_eq!(payload(&deleted).text, "ab"); + assert_eq!((payload(&deleted).cursor, payload(&deleted).anchor), (2, 2)); + assert_eq!(layer_text(&app), "abx"); + assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, Some((2, 1))); +} + +#[test] +fn external_edit_invalidates_the_preedit_and_rejects_its_late_commit() { + for bytes in [false, true] { + for split in [false, true] { + for discard in [false, true] { + let ctx = context(); + let mut app = app(); + run(&mut app, &ctx, Vec::new()); + // Compose in the middle of committed text, so an application edit before it + // moves a still-in-range (but wrong) character range. + insert(&mut app, "def"); + if let Some(ed) = app.ui.text_edit.as_mut() { + ed.caret = 3; + ed.anchor = 3; + } + let composing = run(&mut app, &ctx, vec![preedit("に")]).expect("composing descriptor"); + assert_eq!(layer_text(&app), "abcにdef"); + assert_eq!(payload(&composing).text, "abcdef", "the preview is not committed text"); + let layer = app.ui.text_edit.as_ref().unwrap().layer; + let session = app.ui.text_edit.as_ref().unwrap().session.clone(); + // The control channel edits the same layer without passing through `insert`. + app.run("type.edit", json!({"layer": layer, "replace": {"start": 0, "end": 1, "text": ""}, "coalesce": session})).unwrap(); + assert_eq!(layer_text(&app), "bcにdef"); + let revision = app.session.active().unwrap().revision; + let history = app.session.active().unwrap().history.entries(); + let selection = app.ui.text_edit.as_ref().map(|ed| (ed.anchor, ed.caret)); + let unchanged = |app: &PhotocraftApp| { + assert_eq!(layer_text(app), "bcにdef"); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(app.session.active().unwrap().history.entries(), history); + assert_eq!(app.ui.text_edit.as_ref().map(|ed| (ed.anchor, ed.caret)), selection); + }; + + // The old range (3,1) now covers `d`: report unavailable, cancel the + // composition and do not present `d` as the composition. A discarded pass + // must retain both latches until a descriptor is actually delivered. + let invalidated = if discard { + ctx.options_mut(|o| o.max_passes = std::num::NonZeroUsize::new(4).expect("four passes")); + let mut passes = Vec::new(); + let mut out = ctx.run_ui(egui::RawInput { focused: true, ..Default::default() }, |ui| { + handle_keys(&mut app, ui.ctx()); + let rect = egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400.0, 300.0)); + let xf = ViewXform { rect, zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + draw_overlay(&mut app, ui.painter(), &xf); + if passes.is_empty() { + ui.ctx().request_discard("invalidated preedit descriptor regression"); + } + let discarded = ui.ctx().will_discard(); + let before = (app.type_ime.stale, app.type_ime.interrupt); + sync_ime(&mut app, ui.ctx()); + finish_reset_pass(&mut app, ui.ctx()); + let unavailable = ui.ctx().output(|out| out.ime.as_ref().expect("pass descriptor").surrounding_text.available().is_none()); + passes.push((discarded, before, (app.type_ime.stale, app.type_ime.interrupt), unavailable)); + }); + out.textures_delta.clear(); + assert_eq!(passes.first(), Some(&(true, (true, true), (true, true), true)), "discard cannot consume invalidation"); + assert_eq!(passes.last(), Some(&(false, (true, true), (false, false), true)), "the accepted pass delivers it once"); + out.platform_output.ime.expect("descriptor") + } else { + run(&mut app, &ctx, Vec::new()).expect("descriptor") + }; + assert!(invalidated.surrounding_text.available().is_none()); + assert!(invalidated.should_interrupt_composition); + assert_eq!( + (invalidated.owner, invalidated.context_generation, invalidated.purpose), + (composing.owner, composing.context_generation, composing.purpose) + ); + assert_eq!(invalidated.change_cause, ImeChangeCause::Other); + assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, None); + assert!(app.type_ime.preedit.is_none()); + unchanged(&app); + + let recovered = run(&mut app, &ctx, Vec::new()).expect("idle descriptor"); + assert_eq!(payload(&recovered).text, "bcにdef"); + assert_eq!((payload(&recovered).cursor, payload(&recovered).anchor), (6, 6)); + assert!(!recovered.should_interrupt_composition, "a delivered reset is not replayed"); + assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale)), "idle availability does not accept an old terminal"); + unchanged(&app); + + // The pending deletion and commit belonged to the cancelled composition: + // neither combined nor split delivery may replace `d` or grow undo history. + let mut events = vec![terminal_delete(bytes)]; + if split { + run(&mut app, &ctx, events).expect("rejected deletion descriptor"); + unchanged(&app); + for _ in 0..3 { + run(&mut app, &ctx, Vec::new()); + } + assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale))); + events = Vec::new(); + } + events.push(egui::Event::Ime(egui::ImeEvent::Commit("に".into()))); + let late = run(&mut app, &ctx, events).expect("descriptor"); + assert_eq!(layer_text(&app), "bcにdef"); + assert_eq!(late.change_cause, ImeChangeCause::Other); + assert_eq!(payload(&late).text, "bcにdef"); + unchanged(&app); + assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale)), "terminal input cannot acknowledge cancellation"); + + let fresh = run(&mut app, &ctx, vec![completed(invalidated.reset_request.expect("reset request")), preedit("Q")]) + .expect("fresh preview descriptor"); + assert_eq!(layer_text(&app), "bcにdQef"); + assert_eq!(payload(&fresh).text, "bcにdef", "fresh preview is excluded from committed text"); + assert!(!fresh.should_interrupt_composition); + let committed = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("Q".into()))]).expect("fresh commit descriptor"); + assert_eq!(layer_text(&app), "bcにdQef"); + assert_eq!(payload(&committed).text, "bcにdQef"); + assert_eq!(committed.change_cause, ImeChangeCause::InputMethod); + let direct = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("R".into()))]).expect("direct commit descriptor"); + assert_eq!(layer_text(&app), "bcにdQRef"); + assert_eq!(payload(&direct).text, "bcにdQRef"); + assert_eq!(direct.change_cause, ImeChangeCause::InputMethod); + } + } + } +} + +#[test] +fn target_change_interrupts_and_rejects_the_late_commit() { + let ctx = context(); + let mut app = app(); + run(&mut app, &ctx, Vec::new()); + run(&mut app, &ctx, vec![preedit("に")]); + assert_eq!(layer_text(&app), "abcに"); + + let created = app.run("type.create", json!({"text": "two", "x": 150, "y": 60})).unwrap(); + let second = created.get("layer").and_then(serde_json::Value::as_u64).expect("new layer"); + app.session.select_layer(LayerId(second)).expect("select the second type layer"); + app.ui.text_edit = Some(TextEdit { + layer: second, + document: active_doc_id(&app), + caret: 3, + anchor: 3, + session: "type-second".into(), + created: false, + mask: false, + dragging: false, + resize: None, + preedit: None, + }); + // The platform only cancels composition on this flag (X11, macOS, Windows and the web). + let switched = run(&mut app, &ctx, Vec::new()).expect("transition descriptor"); + assert!(switched.should_interrupt_composition); + + let late = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日本".into()))]).expect("descriptor"); + assert_eq!(current_text(&app, LayerId(second)).unwrap(), "two"); + assert_eq!(late.change_cause, ImeChangeCause::Other); + run(&mut app, &ctx, vec![completed(switched.reset_request.expect("replacement layer reset")), preedit("が")]); + assert_eq!(layer_text(&app), "twoが"); +} + +#[test] +fn type_mask_session_has_a_distinct_owner() { + let ctx = context(); + let mut app = app(); + let normal = run(&mut app, &ctx, Vec::new()).expect("descriptor"); + app.ui.text_edit.as_mut().unwrap().mask = true; + let masked = run(&mut app, &ctx, Vec::new()).expect("mask descriptor"); + assert_ne!(masked.owner, normal.owner, "the Type Mask session is its own owner"); + assert_ne!(masked.context_generation, normal.context_generation); +} + +#[test] +fn reentering_the_same_session_cancels_the_preedit() { + let ctx = context(); + let mut app = app(); + run(&mut app, &ctx, vec![preedit("に")]); + assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, Some((3, 1))); + edit_active(&mut app).unwrap(); + assert_eq!(app.ui.text_edit.as_ref().unwrap().preedit, None); + assert!(app.type_ime.interrupt, "the native composition is cancelled"); + assert!(app.type_ime.preedit.is_none()); +} + +#[test] +fn a_discarded_transition_pass_still_interrupts_the_next_descriptor() { + let ctx = context(); + ctx.options_mut(|o| o.max_passes = std::num::NonZeroUsize::new(4).expect("four passes")); + let mut app = app(); + run(&mut app, &ctx, Vec::new()).expect("baseline descriptor"); + app.ui.text_edit.as_mut().unwrap().session = "type-discarded".into(); + let mut passes = Vec::new(); + let mut out = ctx.run_ui(egui::RawInput { focused: true, ..Default::default() }, |ui| { + handle_keys(&mut app, ui.ctx()); + let rect = egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400.0, 300.0)); + let xf = ViewXform { rect, zoom: 1.0, center: [100.0, 100.0], flip: false, rotation: 0.0, aspect: 1.0 }; + draw_overlay(&mut app, ui.painter(), &xf); + if passes.is_empty() { + ui.ctx().request_discard("IME transition regression"); + } + let discarded = ui.ctx().will_discard(); + let pending_before = app.type_ime.interrupt; + sync_ime(&mut app, ui.ctx()); + finish_reset_pass(&mut app, ui.ctx()); + passes.push((discarded, pending_before, app.type_ime.interrupt)); + }); + out.textures_delta.clear(); + assert_eq!(passes.first(), Some(&(true, true, true)), "discard retains the interrupt latch"); + assert_eq!(passes.last(), Some(&(false, true, false)), "the accepted pass delivers it once"); + assert!(out.platform_output.ime.expect("final descriptor").should_interrupt_composition); + let next = run(&mut app, &ctx, Vec::new()).expect("next descriptor"); + assert!(!next.should_interrupt_composition, "a delivered interrupt is not replayed"); +} + +#[test] +fn delete_surrounding_characters_is_one_undo_step() { + let ctx = context(); + let mut app = app(); + commit(&mut app); + edit_active(&mut app).unwrap(); + if let Some(ed) = app.ui.text_edit.as_mut() { + ed.caret = 3; + ed.anchor = 3; + } + run(&mut app, &ctx, Vec::new()).expect("baseline descriptor"); + let deleted = + run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 })]).expect("deletion descriptor"); + assert_eq!(deleted.change_cause, ImeChangeCause::InputMethod); + assert_eq!(layer_text(&app), "ab"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(layer_text(&app), "abc", "the delete and its session coalesce into one step"); +} + +#[test] +fn an_empty_point_text_reports_an_available_empty_snapshot() { + let ctx = context(); + let mut app = app(); + if let Some(ed) = app.ui.text_edit.as_mut() { + ed.anchor = 0; + ed.caret = 3; + } + insert(&mut app, ""); + assert_eq!(layer_text(&app), ""); + let empty = run(&mut app, &ctx, Vec::new()).expect("descriptor"); + let available = payload(&empty); + assert_eq!(available.text, ""); + assert_eq!((available.cursor, available.anchor), (0, 0)); +} + +#[test] +fn a_long_line_reports_a_bounded_snapshot() { + let ctx = context(); + let mut app = app(); + if let Some(ed) = app.ui.text_edit.as_mut() { + ed.anchor = 0; + ed.caret = 3; + } + insert(&mut app, &"a".repeat(4500)); + let long = run(&mut app, &ctx, Vec::new()).expect("descriptor"); + let available = payload(&long); + assert!(available.text.len() <= egui::output::MAX_IME_SURROUNDING_TEXT_BYTES); + assert!(available.text.is_char_boundary(available.cursor)); + assert!(available.text.is_char_boundary(available.anchor)); +} + +#[test] +fn the_real_app_logic_and_ui_publish_the_descriptor() { + use eframe::App as _; + let ctx = context(); + let mut app = app(); + let mut frame = eframe::Frame::_new_kittest(); + let mut descriptors = Vec::new(); + // The first pass registers fonts; the next passes run the real logic → ui orchestration + // (where `handle_keys` and the final `sync_ime` live). + for _ in 0..3 { + let raw = + egui::RawInput { focused: true, screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, 800.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + app.logic(ui.ctx(), &mut frame); + app.ui(ui, &mut frame); + }); + out.textures_delta.clear(); // No renderer consumes this harness output. + descriptors.push(out.platform_output.ime); + } + let ime = descriptors.iter().flatten().last().expect("a descriptor from App::ui"); + assert!(ime.surrounding_text.available().is_some()); + assert!(ime.context_generation > 0); +} + +fn terminal_delete(bytes: bool) -> egui::Event { + egui::Event::Ime(if bytes { + egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 } + } else { + egui::ImeEvent::DeleteSurrounding { before_chars: 1, after_chars: 0 } + }) +} + +fn raw_key(key: egui::Key, command: bool, shift: bool) -> egui::Event { + egui::Event::Key { + key, + physical_key: Some(key), + pressed: true, + repeat: false, + modifiers: egui::Modifiers { + command, + ctrl: command && !cfg!(target_os = "macos"), + mac_cmd: command && cfg!(target_os = "macos"), + shift, + ..Default::default() + }, + } +} + +#[test] +fn stale_owner_terminal_survives_idle_and_split_delete_commit_but_fresh_input_works() { + for empty in [false, true] { + for bytes in [false, true] { + let ctx = context(); + let mut app = app(); + run(&mut app, &ctx, vec![]); + run(&mut app, &ctx, vec![preedit("P")]); + if empty { + run(&mut app, &ctx, vec![preedit("")]); + } + let old_layer = app.ui.text_edit.as_ref().unwrap().layer; + let created = app.run("type.create", json!({"text": "two", "x": 150, "y": 60})).unwrap(); + let second = created["layer"].as_u64().unwrap(); + app.session.select_layer(LayerId(second)).unwrap(); + edit_active(&mut app).unwrap(); + let transition = run(&mut app, &ctx, vec![]).unwrap(); + assert!(transition.should_interrupt_composition); + for _ in 0..5 { + run(&mut app, &ctx, vec![]); + } + let revision = app.session.active().unwrap().revision; + let undo = app.session.active().unwrap().history.entries().len(); + let before = layer_text(&app); + run(&mut app, &ctx, vec![terminal_delete(bytes)]); + for _ in 0..3 { + run(&mut app, &ctx, vec![]); + } + run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("X".into()))]); + assert_eq!(layer_text(&app), before, "an old split terminal cannot edit a replacement owner"); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(app.session.active().unwrap().history.entries().len(), undo); + assert_eq!(current_text(&app, LayerId(old_layer)).unwrap(), if empty { "abc" } else { "abcP" }); + let selection = app.ui.text_edit.as_ref().unwrap().clone(); + let (a, b) = (selection.anchor.min(selection.caret), selection.anchor.max(selection.caret)); + let expected = before.chars().take(a).chain("Q".chars()).chain(before.chars().skip(b)).collect::(); + run( + &mut app, + &ctx, + vec![completed(transition.reset_request.expect("reset request")), preedit("Q"), egui::Event::Ime(egui::ImeEvent::Commit("Q".into()))], + ); + assert_eq!(layer_text(&app), expected, "the exact completion permits fresh input"); + run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("R".into()))]); + assert!(layer_text(&app).contains("QR"), "a later direct commit remains valid"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(current_text(&app, LayerId(second)).unwrap(), before, "the new session is undoable"); + } + } +} + +#[test] +fn raw_application_selection_changes_reject_old_terminal_input_and_allow_later_fresh_input() { + for empty in [false, true] { + for bytes in [false, true] { + for (key, command, shift) in [(egui::Key::A, true, false), (egui::Key::ArrowLeft, false, false), (egui::Key::Home, false, true)] { + let ctx = context(); + let mut app = app(); + run(&mut app, &ctx, vec![]); + run(&mut app, &ctx, vec![preedit("P")]); + if empty { + run(&mut app, &ctx, vec![preedit("")]); + } + let before = layer_text(&app); + let revision = app.session.active().unwrap().revision; + let transition = run(&mut app, &ctx, vec![raw_key(key, command, shift)]).expect("selection reset"); + let selected = app.ui.text_edit.as_ref().unwrap().clone(); + assert!( + (selected.anchor, selected.caret) != (before.chars().count(), before.chars().count()), + "actual raw selection key changed the caret" + ); + for _ in 0..3 { + run(&mut app, &ctx, vec![]); + } + let undo = app.session.active().unwrap().history.entries().len(); + run(&mut app, &ctx, vec![terminal_delete(bytes), egui::Event::Ime(egui::ImeEvent::Commit("X".into()))]); + assert_eq!(layer_text(&app), before); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(app.session.active().unwrap().history.entries().len(), undo); + assert_eq!(app.ui.text_edit.as_ref().map(|e| (e.anchor, e.caret)), Some((selected.anchor, selected.caret))); + let (a, b) = (selected.anchor.min(selected.caret), selected.anchor.max(selected.caret)); + let expected = before.chars().take(a).chain("Q".chars()).chain(before.chars().skip(b)).collect::(); + // The completion opens admission at its exact position in the batch. + run( + &mut app, + &ctx, + vec![completed(transition.reset_request.expect("reset request")), preedit("Q"), egui::Event::Ime(egui::ImeEvent::Commit("Q".into()))], + ); + assert_eq!(layer_text(&app), expected); + } + } + } +} + +#[test] +fn uninterrupted_live_and_empty_preedit_delete_commit_and_direct_commit_stay_valid() { + for empty in [false, true] { + for bytes in [false, true] { + let ctx = context(); + let mut app = app(); + run(&mut app, &ctx, vec![]); + run(&mut app, &ctx, vec![preedit("P")]); + if empty { + run(&mut app, &ctx, vec![preedit("")]); + } + run(&mut app, &ctx, vec![terminal_delete(bytes)]); + for _ in 0..3 { + run(&mut app, &ctx, vec![]); + } + run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("X".into()))]); + assert_eq!(layer_text(&app), "abX", "accepted deletion refreshes its composing caret"); + } + } + let ctx = context(); + let mut app = app(); + run(&mut app, &ctx, vec![]); + run(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false), egui::Event::Ime(egui::ImeEvent::Commit("D".into()))]); + assert_eq!(layer_text(&app), "D", "without known preedit the direct commit replaces the selection"); +} + +fn actual_app_frame(app: &mut PhotocraftApp, ctx: &egui::Context, events: Vec) -> egui::FullOutput { + use eframe::App as _; + let mut frame = eframe::Frame::_new_kittest(); + let mut raw = + egui::RawInput { focused: true, events, screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, 800.0))), ..Default::default() }; + app.raw_input_hook(ctx, &mut raw); + let mut output = ctx.run_ui(raw, |ui| { + app.logic(ui.ctx(), &mut frame); + app.ui(ui, &mut frame); + }); + output.textures_delta.clear(); + output +} + +#[test] +fn the_real_app_pointer_interruption_rejects_idle_delayed_terminal_then_accepts_fresh_input() { + for empty in [false, true] { + for bytes in [false, true] { + let ctx = context(); + let mut app = app(); + for _ in 0..4 { + actual_app_frame(&mut app, &ctx, vec![]); + } + app.ui.text_edit.as_mut().unwrap().caret = 1; + app.ui.text_edit.as_mut().unwrap().anchor = 1; + let point = actual_app_frame(&mut app, &ctx, vec![]).platform_output.ime.expect("real caret1 descriptor").cursor_rect.center(); + app.ui.text_edit.as_mut().unwrap().caret = 3; + app.ui.text_edit.as_mut().unwrap().anchor = 3; + actual_app_frame(&mut app, &ctx, vec![]); + actual_app_frame(&mut app, &ctx, vec![preedit("P")]); + if empty { + actual_app_frame(&mut app, &ctx, vec![preedit("")]); + } + let before = layer_text(&app); + let button = |pressed| egui::Event::PointerButton { pos: point, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let press = + actual_app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(point), button(true)]).platform_output.ime.expect("press descriptor"); + let release = actual_app_frame(&mut app, &ctx, vec![button(false)]).platform_output.ime.expect("release descriptor"); + let request = release.reset_request.or(press.reset_request).expect("pointer reset"); + assert_eq!(app.ui.text_edit.as_ref().unwrap().caret, 1, "actual canvas pointer moved the caret"); + for _ in 0..4 { + actual_app_frame(&mut app, &ctx, vec![]); + } + let revision = app.session.active().unwrap().revision; + actual_app_frame(&mut app, &ctx, vec![terminal_delete(bytes), egui::Event::Ime(egui::ImeEvent::Commit("X".into()))]); + assert_eq!(layer_text(&app), before); + assert_eq!(app.session.active().unwrap().revision, revision); + actual_app_frame(&mut app, &ctx, vec![completed(request), preedit("Q"), egui::Event::Ime(egui::ImeEvent::Commit("Q".into()))]); + let expected = before.chars().take(1).chain("Q".chars()).chain(before.chars().skip(1)).collect::(); + assert_eq!(layer_text(&app), expected); + } + } +} + +#[test] +fn only_a_matching_completion_allows_a_new_composition_in_the_same_raw_batch() { + for bytes in [false, true] { + let ctx = context(); + let mut app = app(); + run(&mut app, &ctx, vec![]); + run(&mut app, &ctx, vec![preedit("P")]); + let transition = run(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false)]).expect("selection reset"); + run( + &mut app, + &ctx, + vec![ + terminal_delete(bytes), + egui::Event::Ime(egui::ImeEvent::Commit("old".into())), + completed(transition.reset_request.expect("reset request")), + preedit("Q"), + egui::Event::Ime(egui::ImeEvent::Commit("Q".into())), + ], + ); + assert_eq!(layer_text(&app), "Q", "the old terminal is rejected before the completion opens admission"); + } +} + +#[test] +fn an_actual_same_batch_selection_requires_completion_before_the_new_live_preedit() { + for empty in [false, true] { + for bytes in [false, true] { + for terminal in [false, true] { + let ctx = context(); + let mut app = app(); + for _ in 0..4 { + actual_app_frame(&mut app, &ctx, vec![]); + } + actual_app_frame(&mut app, &ctx, vec![preedit("P")]); + if empty { + actual_app_frame(&mut app, &ctx, vec![preedit("")]); + } + let before = layer_text(&app); + let revision = app.session.active().unwrap().revision; + let mut events = vec![raw_key(egui::Key::A, true, false), terminal_delete(bytes)]; + if terminal { + events.push(egui::Event::Ime(egui::ImeEvent::Commit("old".into()))); + } + events.push(preedit("Q")); + let out = actual_app_frame(&mut app, &ctx, events); + assert_eq!(layer_text(&app), before, "all unacknowledged payloads remain stale, even after Commit"); + assert_eq!(app.session.active().unwrap().revision, revision); + assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale))); + let selected = app.ui.text_edit.as_ref().unwrap(); + assert_eq!((selected.anchor, selected.caret), (0, before.chars().count()), "the actual selection key ran"); + let request = out.platform_output.ime.expect("interrupted descriptor").reset_request.expect("reset request"); + actual_app_frame(&mut app, &ctx, vec![completed(request), preedit("Q")]); + assert_eq!(layer_text(&app), "Q", "only the new preedit replaced the selected text"); + assert_eq!(app.session.active().unwrap().revision, revision + 1, "neither old deletion nor old commit mutated the document"); + let editing = app.ui.text_edit.as_ref().unwrap(); + assert_eq!((editing.anchor, editing.caret, editing.preedit), (1, 1, Some((0, 1)))); + assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Active(_)))); + // Keep Q live across a real idle pass before its separately delivered commit. + let idle = actual_app_frame(&mut app, &ctx, vec![]); + assert!(!idle.platform_output.ime.expect("the live preview keeps its descriptor").should_interrupt_composition); + actual_app_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("Q".into()))]); + assert_eq!(layer_text(&app), "Q"); + assert!(app.ui.text_edit.as_ref().unwrap().preedit.is_none()); + assert!(app.type_ime.incoming.is_none()); + } + } + } +} + +fn pending(app: &PhotocraftApp) -> Option { + match app.type_ime.resets.get(&egui::ViewportId::ROOT) { + Some(ResetPhase::Awaiting { id, .. }) => Some(*id), + _ => None, + } +} + +fn interrupt_with_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> egui::ImeResetId { + run(app, ctx, vec![preedit("P")]); + run(app, ctx, vec![raw_key(egui::Key::A, true, false)]).expect("custom output").reset_request.expect("published reset") +} + +#[test] +fn newest_published_request_alone_opens_the_ordered_suffix() { + let ctx = context(); + let mut app = app(); + let first = interrupt_with_selection(&mut app, &ctx); + let second = run(&mut app, &ctx, vec![raw_key(egui::Key::ArrowLeft, false, false), completed(first), preedit("old")]) + .expect("moved selection") + .reset_request + .expect("replacement request"); + assert_ne!(first, second); + let before = layer_text(&app); + let revision = app.session.active().unwrap().revision; + let history = app.session.active().unwrap().history.entries().len(); + run(&mut app, &ctx, vec![terminal_delete(true), completed(first), egui::Event::Ime(egui::ImeEvent::Commit("old".into()))]); + assert_eq!(layer_text(&app), before); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(app.session.active().unwrap().history.entries().len(), history); + assert_eq!(pending(&app), Some(second)); + let selection = app.ui.text_edit.as_ref().map(|e| (e.anchor, e.caret)); + run(&mut app, &ctx, vec![completed(second), completed(second)]); + assert_eq!(layer_text(&app), before, "controls alone never edit text"); + assert_eq!(app.ui.text_edit.as_ref().map(|e| (e.anchor, e.caret)), selection); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(app.session.active().unwrap().history.entries().len(), history); + assert_eq!(pending(&app), None); + run(&mut app, &ctx, vec![preedit("が"), egui::Event::Ime(egui::ImeEvent::Commit("が".into()))]); + assert!(layer_text(&app).starts_with("が")); +} + +#[test] +fn foreign_viewport_and_context_completions_cannot_release_root() { + let ctx = context(); + let mut app = app(); + let root = interrupt_with_selection(&mut app, &ctx); + let other = context(); + let viewport = egui::ViewportId::from_hash_of("photo-reset-foreign"); + let foreign_input = || { + let rect = egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400.0, 300.0)); + let mut raw = egui::RawInput { viewport_id: viewport, screen_rect: Some(rect), focused: true, ..Default::default() }; + raw.viewports.insert( + viewport, + egui::ViewportInfo { inner_rect: Some(rect), native_pixels_per_point: Some(1.0), minimized: Some(false), ..Default::default() }, + ); + raw + }; + let mut text = String::new(); + let mut output = other.run_ui(foreign_input(), |ui| { + ui.add(egui::TextEdit::singleline(&mut text)).request_focus(); + let _ = ui.ctx().request_ime_reset(viewport); + }); + output.textures_delta.clear(); + // Draw once more if egui has not yet reported the newly focused stock editor. + if output.platform_output.ime.is_none() { + output = other.run_ui(foreign_input(), |ui| { + ui.add(egui::TextEdit::singleline(&mut text)); + }); + output.textures_delta.clear(); + } + let foreign = output.platform_output.ime.expect("foreign stock output").reset_request.expect("foreign published request"); + assert_ne!(foreign.viewport_id(), root.viewport_id()); + let before = layer_text(&app); + run(&mut app, &ctx, vec![completed(foreign), preedit("bad"), completed(root), preedit("が")]); + assert_eq!(layer_text(&app), "が", "foreign marker cannot open admission before the root marker"); + assert_ne!(layer_text(&app), before); +} + +#[test] +fn standalone_logic_suspends_once_without_replaying_input_and_return_rearms_once() { + use eframe::App as _; + let ctx = context(); + let mut app = app(); + for _ in 0..4 { + actual_app_frame(&mut app, &ctx, vec![]); + } + actual_app_frame(&mut app, &ctx, vec![preedit("P")]); + let first = actual_app_frame(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false)]) + .platform_output + .ime + .expect("custom output") + .reset_request + .expect("first request"); + let before = layer_text(&app); + for _ in 0..3 { + let mut frame = eframe::Frame::_new_kittest(); + let _ = ctx.run_logic(&egui::RawInput { focused: true, ..Default::default() }, |ctx| app.logic(ctx, &mut frame)); + assert_eq!(layer_text(&app), before, "hidden logic does not replay the previous raw selection batch"); + assert_eq!(pending(&app), None); + assert!(matches!(app.type_ime.resets.get(&egui::ViewportId::ROOT), Some(ResetPhase::Suspended))); + } + let second = actual_app_frame(&mut app, &ctx, vec![completed(first), preedit("bad")]) + .platform_output + .ime + .expect("returned custom output") + .reset_request + .expect("fresh request after hidden logic"); + assert_ne!(first, second); + assert_eq!(layer_text(&app), before); + for _ in 0..3 { + let idle = actual_app_frame(&mut app, &ctx, vec![]).platform_output.ime.expect("idle custom output"); + assert_eq!(idle.reset_request, None, "logic inside a full UI pass cannot suspend and rearm the stable guard"); + assert_eq!(pending(&app), Some(second)); + } + actual_app_frame(&mut app, &ctx, vec![completed(second), preedit("が"), egui::Event::Ime(egui::ImeEvent::Commit("が".into()))]); + assert_eq!(layer_text(&app), "が"); +} + +#[test] +fn standalone_logic_does_not_guard_an_uninterrupted_terminal_pending_composition() { + use eframe::App as _; + let ctx = context(); + let mut app = app(); + for _ in 0..4 { + actual_app_frame(&mut app, &ctx, vec![]); + } + actual_app_frame(&mut app, &ctx, vec![preedit("P"), preedit("")]); + let mut frame = eframe::Frame::_new_kittest(); + let _ = ctx.run_logic(&egui::RawInput { focused: true, ..Default::default() }, |ctx| app.logic(ctx, &mut frame)); + assert!(app.type_ime.resets.is_empty()); + assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::TerminalPending(_)))); + actual_app_frame(&mut app, &ctx, vec![terminal_delete(false), egui::Event::Ime(egui::ImeEvent::Commit("X".into()))]); + assert_eq!(layer_text(&app), "abX"); +} + +#[test] +fn fonts_not_ready_and_no_editor_early_returns_retire_the_old_request() { + use eframe::App as _; + for no_editor in [false, true] { + let ctx = context(); + let mut app = app(); + for _ in 0..4 { + actual_app_frame(&mut app, &ctx, vec![]); + } + actual_app_frame(&mut app, &ctx, vec![preedit("P")]); + let first = actual_app_frame(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false)]) + .platform_output + .ime + .expect("custom output") + .reset_request + .expect("first request"); + let editor = app.ui.text_edit.clone(); + let before = layer_text(&app); + let mut frame = eframe::Frame::_new_kittest(); + let mut output = ctx.run_ui(egui::RawInput { focused: true, events: vec![completed(first), preedit("bad")], ..Default::default() }, |ui| { + if no_editor { + app.ui.text_edit = None; + } else { + app.fonts_ready = false; + } + app.ui(ui, &mut frame); + }); + output.textures_delta.clear(); + assert!(output.platform_output.ime.is_none()); + assert_eq!(pending(&app), None); + app.ui.text_edit = editor; + app.fonts_ready = true; + let second = actual_app_frame(&mut app, &ctx, vec![completed(first), preedit("bad")]) + .platform_output + .ime + .expect("same editor returned") + .reset_request + .expect("rearmed request"); + assert_ne!(first, second); + assert_eq!(layer_text(&app), before); + actual_app_frame(&mut app, &ctx, vec![completed(second), preedit("が")]); + assert_eq!(layer_text(&app), "が"); + } +} + +#[test] +fn pointer_deferred_suffix_cannot_edit_the_old_caret_or_complete_its_old_request() { + let ctx = context(); + let mut app = app(); + for _ in 0..4 { + actual_app_frame(&mut app, &ctx, vec![]); + } + app.ui.text_edit.as_mut().unwrap().caret = 1; + app.ui.text_edit.as_mut().unwrap().anchor = 1; + let point = actual_app_frame(&mut app, &ctx, vec![]).platform_output.ime.expect("caret geometry").cursor_rect.center(); + app.ui.text_edit.as_mut().unwrap().caret = 3; + app.ui.text_edit.as_mut().unwrap().anchor = 3; + actual_app_frame(&mut app, &ctx, vec![preedit("P")]); + let first = actual_app_frame(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false)]) + .platform_output + .ime + .expect("selection output") + .reset_request + .expect("first request"); + let before = layer_text(&app); + let revision = app.session.active().unwrap().revision; + let event = |pressed| egui::Event::PointerButton { pos: point, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let out = actual_app_frame( + &mut app, + &ctx, + vec![ + egui::Event::PointerMoved(point), + event(true), + completed(first), + egui::Event::Text("bad".into()), + egui::Event::Paste("bad".into()), + egui::Event::Cut, + preedit("bad"), + ], + ); + let first_after_pointer = out.platform_output.ime.expect("pointer output").reset_request; + let out = actual_app_frame(&mut app, &ctx, vec![event(false)]); + let second = out.platform_output.ime.expect("release output").reset_request.or(first_after_pointer).expect("actual pointer destination reset"); + assert_ne!(first, second); + assert_eq!(layer_text(&app), before); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(app.ui.text_edit.as_ref().unwrap().caret, 1); + actual_app_frame(&mut app, &ctx, vec![completed(second), preedit("が")]); + assert!(layer_text(&app).contains("が")); +} + +#[test] +fn completion_without_current_geometry_is_suspended_before_the_following_preedit() { + let ctx = context(); + let mut app = app(); + let first = interrupt_with_selection(&mut app, &ctx); + let before = layer_text(&app); + // No canvas view for this input batch: the completion cannot be attributed to a visible + // custom descriptor yet. This is the pre-descriptor check, not a wait on final output. + app.type_ime.view = None; + let output = run(&mut app, &ctx, vec![completed(first), preedit("bad")]).expect("custom output"); + let second = output.reset_request.expect("the final custom output rearms"); + assert_ne!(first, second); + assert_eq!(layer_text(&app), before, "the preedit after a geometry-less completion stays blocked"); + assert!(matches!(app.type_ime.resets.get(&egui::ViewportId::ROOT), Some(ResetPhase::Awaiting { id, .. }) if *id == second)); + run(&mut app, &ctx, vec![completed(second), preedit("が")]); + assert_eq!(layer_text(&app), "が"); +} + +#[test] +fn pointer_press_without_a_guard_defers_the_same_batch_custom_suffix() { + let ctx = context(); + let mut app = app(); + let before = layer_text(&app); + let revision = app.session.active().unwrap().revision; + let selection = app.ui.text_edit.as_ref().map(|ed| (ed.anchor, ed.caret)); + let press = + egui::Event::PointerButton { pos: Pos2::new(20.0, 20.0), button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }; + let output = run( + &mut app, + &ctx, + vec![ + egui::Event::PointerMoved(Pos2::new(20.0, 20.0)), + press, + egui::Event::Text("bad".into()), + egui::Event::Paste("bad".into()), + egui::Event::Cut, + preedit("bad"), + ], + ) + .expect("descriptor"); + assert_eq!(layer_text(&app), before, "the deferred canvas handler never lets a suffix edit the old caret"); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(app.ui.text_edit.as_ref().map(|ed| (ed.anchor, ed.caret)), selection); + assert_eq!(output.reset_request, None, "no prior guard means no speculative reset yet"); +} + +#[test] +fn synchronous_select_all_accepts_fresh_text_but_still_blocks_stale_ime() { + let ctx = context(); + // With no guard, the synchronously selected destination is a real destination: Text is + // an application edit, not an old IME suffix. + let mut app = app(); + run(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false), egui::Event::Text("x".into())]); + assert_eq!(layer_text(&app), "x"); + + // The same holds when Cmd+A interrupted a known composition: Text is still fresh input. + let mut app = self::app(); + run(&mut app, &ctx, vec![preedit("P")]); + let out = run(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false), egui::Event::Text("x".into())]).expect("custom output"); + assert_eq!(layer_text(&app), "x"); + assert!(out.reset_request.is_some(), "the stale composition still needs its ordered reset"); + + // An IME payload in that same batch is not fresh Text: it remains blocked until its + // replacement request is actually completed. + let mut app = self::app(); + run(&mut app, &ctx, vec![preedit("P")]); + let before = layer_text(&app); + let out = run(&mut app, &ctx, vec![raw_key(egui::Key::A, true, false), preedit("bad")]).expect("custom output"); + assert_eq!(layer_text(&app), before); + let request = out.reset_request.expect("selection reset request"); + run(&mut app, &ctx, vec![completed(request), preedit("が")]); + assert_eq!(layer_text(&app), "が"); +} + +struct ResetHarness { + app: PhotocraftApp, + stock: bool, + picker_button: bool, + search: String, + search_input: Option, + search_focused: bool, + search_height: Option, +} + +fn reset_harness(app: PhotocraftApp) -> egui_kittest::Harness<'static, ResetHarness> { + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(1200.0, 800.0)) + .with_context_setup(|ctx| { + install_reset_hooks(ctx); + crate::theme::install_fonts(ctx); + }) + .build_ui_state( + |ui, state: &mut ResetHarness| { + let mut frame = eframe::Frame::_new_kittest(); + state.app.logic_frame(ui.ctx(), &mut frame); + state.app.ui_frame(ui, &mut frame); + if state.stock { + egui::Window::new("Reset font fixture").show(ui.ctx(), |ui| { + let button = ui.make_persistent_id(egui::IdSalt::new("reset-font")); + egui::Popup::open_id(ui.ctx(), button.with("popup")); + let mut current = "Family 00".to_owned(); + family_picker_in( + ui, + "reset-font", + &mut current, + 170.0, + &["Family 00".into(), "Family 01".into()], + photocraft_engine::prefs::FontPreview::Medium, + &[], + ); + let search = ui.scope_id().with(("font-search", "reset-font")); + state.search = ui.data(|d| d.get_temp::(search)).unwrap_or_default(); + let input = search.with("input"); + state.search_input = Some(input); + state.search_focused = ui.memory(|m| m.has_focus(input)); + state.search_height = ui.data(|d| d.get_temp::(search.with("height"))); + }); + } + if state.picker_button { + egui::Window::new("Reset screen fixture").show(ui.ctx(), |ui| { + crate::screen_picker::button(ui, egui::Id::unique("reset-screen")); + }); + } + state.app.finish_type_reset_pass(ui.ctx()); + }, + ResetHarness { app, stock: false, picker_button: false, search: String::new(), search_input: None, search_focused: false, search_height: None }, + ); + h.run_steps(4); + h +} + +fn harness_request(h: &egui_kittest::Harness<'_, ResetHarness>) -> egui::ImeResetId { + h.output().platform_output.ime.as_ref().expect("actual harness output").reset_request.expect("published harness reset") +} + +#[test] +fn actual_font_search_owns_stock_input_without_a_speculative_custom_request() { + let mut h = reset_harness(app()); + h.event(preedit("P")); + h.step(); + h.event(raw_key(egui::Key::A, true, false)); + h.step(); + let first = harness_request(&h); + let before = layer_text(&h.state().app); + let custom_owner = h.output().platform_output.ime.as_ref().unwrap().owner; + h.state_mut().stock = true; + h.run_steps(3); + let stock_owner = h.output().platform_output.ime.as_ref().expect("real font search descriptor").owner; + assert_ne!(stock_owner, custom_owner); + let search_input = h.state().search_input.expect("font search field id"); + assert!(h.state().search_focused, "the real font search field, not another stock field, owns focus"); + assert_eq!(h.ctx.memory(|m| m.focused()), Some(search_input), "the stock IME owner is the focused font search input"); + assert!( + h.state().search_height.is_some_and(|height| height > 0.0 && height <= FONT_MENU_HEIGHT), + "the real font list measured within its bounded popup height" + ); + h.input_mut().events = vec![completed(first), egui::Event::Text("Family".into())]; + h.step(); + assert_eq!(h.state().search, "Family", "the actual font picker keeps its text event"); + assert_eq!(layer_text(&h.state().app), before); + assert_eq!(pending(&h.state().app), None); + let stock = h.output().platform_output.ime.as_ref().expect("stock output survives finalization"); + assert_eq!(stock.owner, stock_owner); + assert_eq!(stock.reset_request, None, "an already-ineligible route cannot allocate a custom request"); + h.state_mut().stock = false; + egui::Popup::close_all(&h.ctx); + h.ctx.memory_mut(|m| m.stop_text_input()); + h.input_mut().events = vec![completed(first), preedit("bad")]; + h.step(); + let second = harness_request(&h); + assert_ne!(first, second); + assert_eq!(layer_text(&h.state().app), before); + h.step(); + assert_eq!(h.output().platform_output.ime.as_ref().unwrap().reset_request, None); + h.input_mut().events = vec![completed(second), preedit("が")]; + h.step(); + assert_eq!(layer_text(&h.state().app), "が"); +} + +type ImmediateViewportRecord = (egui::ViewportId, egui::ViewportId, Option, Option); + +fn record_immediate_viewports() -> Arc>> { + let seen = Arc::new(std::sync::Mutex::new(Vec::new())); + let recorded = seen.clone(); + egui::Context::set_immediate_viewport_renderer(move |ctx, immediate| { + let ids = immediate.ids; + if let Ok(mut seen) = recorded.lock() { + seen.push((ids.this, ids.parent, immediate.builder.inner_size, immediate.builder.visible)); + } + let mut callback = immediate.viewport_ui_cb; + let mut output = ctx.run_ui( + egui::RawInput { + viewport_id: ids.this, + viewports: std::iter::once((ids.this, egui::ViewportInfo::default())).collect(), + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(2.0, 2.0))), + ..Default::default() + }, + |ui| callback(ui), + ); + output.textures_delta.clear(); + }); + seen +} + +#[test] +fn actual_screen_picker_modal_retires_the_type_fence_and_return_rearms_it() { + use egui_kittest::kittest::Queryable as _; + let mut app = app(); + app.services.screen_pick = Some(Box::new(|_| { + let (sender, receiver) = std::sync::mpsc::channel(); + sender + .send(Ok(crate::screen_picker::Capture::Images(vec![crate::screen_picker::ScreenImage { + monitor: None, + position: Pos2::ZERO, + size: egui::vec2(2.0, 2.0), + width: 2, + height: 2, + rgba: vec![0; 16], + profile: None, + }]))) + .unwrap(); + crate::screen_picker::Pending { receiver, cancelled: Arc::new(std::sync::atomic::AtomicBool::new(false)) } + })); + let mut h = reset_harness(app); + h.event(preedit("P")); + h.step(); + h.event(raw_key(egui::Key::A, true, false)); + h.step(); + let first = harness_request(&h); + let before = layer_text(&h.state().app); + let immediate = record_immediate_viewports(); + h.ctx.set_embed_viewports(false); + h.state_mut().picker_button = true; + h.run_steps(2); + h.get_by_label("Pick screen color").click(); + h.run_steps(3); + assert!(crate::screen_picker::busy(&h.ctx)); + assert!(crate::screen_picker::showing(&h.ctx), "the actual UI takes its screen-picker modal early return"); + let seen = immediate.lock().expect("recorded viewports"); + assert!(!seen.is_empty(), "the native immediate-viewport renderer received the picker"); + assert!( + seen.iter().all(|(child, parent, size, visible)| *child != egui::ViewportId::ROOT + && *parent == egui::ViewportId::ROOT + && *size == Some(egui::vec2(2.0, 2.0)) + && *visible == Some(false)), + "each picker viewport is a hidden 2x2 child of the root" + ); + drop(seen); + h.input_mut().events = vec![completed(first), preedit("bad")]; + h.step(); + assert!(h.output().platform_output.ime.is_none()); + assert_eq!(pending(&h.state().app), None); + assert_eq!(layer_text(&h.state().app), before); + crate::screen_picker::cancel(&h.ctx); + h.state_mut().picker_button = false; + h.ctx.memory_mut(|m| m.stop_text_input()); + h.input_mut().events = vec![completed(first), preedit("bad")]; + h.step(); + let second = harness_request(&h); + assert_ne!(first, second); + assert_eq!(layer_text(&h.state().app), before); + h.input_mut().events = vec![completed(second), preedit("が")]; + h.step(); + assert_eq!(layer_text(&h.state().app), "が"); +} + +#[test] +fn a_discarded_custom_output_allocates_no_new_id_and_final_absence_retires_then_rearms() { + let ctx = context(); + ctx.options_mut(|o| o.max_passes = std::num::NonZeroUsize::new(4).unwrap()); + let mut app = app(); + // A prior queued R1 is deliberately present: the discard must preserve it, not allocate + // a speculative replacement for output egui will throw away. + let first = interrupt_with_selection(&mut app, &ctx); + let mut passes = 0; + let mut discarded_pending = None; + let mut output = ctx.run_ui(egui::RawInput { focused: true, ..Default::default() }, |ui| { + handle_keys(&mut app, ui.ctx()); + if passes == 0 { + let xf = ViewXform { + rect: egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400.0, 300.0)), + zoom: 1.0, + center: [100.0, 100.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + }; + draw_overlay(&mut app, ui.painter(), &xf); + ui.ctx().request_discard("reset custom output disappears on final pass"); + } + sync_ime(&mut app, ui.ctx()); + finish_reset_pass(&mut app, ui.ctx()); + if passes == 0 { + discarded_pending = pending(&app); + } + passes += 1; + }); + output.textures_delta.clear(); + assert!(passes > 1); + assert!(output.platform_output.ime.is_none()); + assert_eq!(discarded_pending, Some(first), "discard keeps the queued R1 and allocates no NEW id"); + assert_eq!(pending(&app), None, "the final ineligible pass retires the prior R1"); + let before = layer_text(&app); + let returned = run(&mut app, &ctx, vec![completed(first), preedit("bad")]).expect("same model returns"); + let second = returned.reset_request.expect("new published request"); + assert_ne!(first, second); + assert_eq!(layer_text(&app), before); + run(&mut app, &ctx, vec![completed(second), preedit("が")]); + assert_eq!(layer_text(&app), "が"); +} + +#[test] +fn a_recreated_context_installed_before_run_ui_rejects_the_old_completion_and_rearms() { + use eframe::App as _; + let old = context(); + let mut app = app(); + for _ in 0..4 { + actual_app_frame(&mut app, &old, vec![]); + } + let first = interrupt_with_selection(&mut app, &old); + let before = layer_text(&app); + // The host replaces its Context and must run the same supported setup before `run_ui`; + // a begin-pass hook registered later could not mark the first pass. + let next = egui::Context::default(); + PhotocraftApp::setup_context(&next, app.ui.theme); + let mut frame = eframe::Frame::_new_kittest(); + let mut saw_ui_pass = false; + let mut output = next.run_ui( + egui::RawInput { + focused: true, + events: vec![completed(first), preedit("bad")], + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, 800.0))), + ..Default::default() + }, + |ui| { + app.logic(ui.ctx(), &mut frame); + saw_ui_pass = in_ui_pass(ui.ctx()); + app.ui(ui, &mut frame); + }, + ); + output.textures_delta.clear(); + assert!(saw_ui_pass, "the supported creator setup marks the first replacement Context pass"); + let second = output.platform_output.ime.expect("replacement Context custom output").reset_request.expect("replacement Context request"); + assert_ne!(first, second); + assert_eq!(layer_text(&app), before); + run(&mut app, &next, vec![completed(second), preedit("が")]); + assert_eq!(layer_text(&app), "が"); +} + +#[test] +fn type_mask_and_same_owner_session_replacement_supersede_the_full_request() { + for mask in [false, true] { + let ctx = context(); + let mut app = app(); + let first = interrupt_with_selection(&mut app, &ctx); + let original = run(&mut app, &ctx, vec![]).expect("original context"); + if mask { + app.ui.text_edit.as_mut().unwrap().mask = true; + } else { + app.ui.text_edit.as_mut().unwrap().session = "replacement-reset-session".into(); + } + let before = layer_text(&app); + let changed = run(&mut app, &ctx, vec![completed(first), preedit("bad")]).expect("replacement output"); + let second = changed.reset_request.expect("replacement request"); + assert_ne!(first, second); + if mask { + assert_ne!(changed.owner, original.owner); + } else { + assert_eq!(changed.owner, original.owner); + } + assert_ne!(changed.context_generation, original.context_generation); + assert_eq!(layer_text(&app), before); + run(&mut app, &ctx, vec![completed(first), terminal_delete(false), egui::Event::Ime(egui::ImeEvent::Commit("bad".into()))]); + assert_eq!(layer_text(&app), before); + run(&mut app, &ctx, vec![completed(second), preedit("が")]); + assert_eq!(layer_text(&app), "が"); + } +} + +#[test] +fn document_replacement_cannot_reuse_the_previous_documents_reset() { + let ctx = context(); + let mut app = app(); + let first = interrupt_with_selection(&mut app, &ctx); + let old_document = active_doc_id(&app); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.sync_views(); + // The host runs this before handling input: a new active document ends the old edit in + // its own document, so the next canvas click starts an editor for the new one. + end_if_left(&mut app); + assert!(app.ui.text_edit.is_none(), "the new document starts without the previous edit target"); + app.ui.tool = crate::state::Tool::Type; + pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); + insert(&mut app, "new"); + assert_ne!(active_doc_id(&app), old_document); + let before = layer_text(&app); + let changed = run(&mut app, &ctx, vec![completed(first), preedit("bad")]).expect("new document output"); + let second = changed.reset_request.expect("new document reset"); + assert_ne!(first, second); + assert_eq!(layer_text(&app), before); + run(&mut app, &ctx, vec![completed(second), preedit("が")]); + assert!(layer_text(&app).contains("が")); +} From 75bc44467926d72d9287fec3cbac032666245a70 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:23 +0000 Subject: [PATCH 094/259] refactor(ui-egui): move control.rs tests to control/tests.rs --- crates/ui-egui/src/control.rs | 2074 +-------------------------- crates/ui-egui/src/control/tests.rs | 2054 ++++++++++++++++++++++++++ 2 files changed, 2055 insertions(+), 2073 deletions(-) create mode 100644 crates/ui-egui/src/control/tests.rs diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 550c121827..e5efe9af0a 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1525,2076 +1525,4 @@ pub fn save_screenshot_rgba(app: &mut PhotocraftApp, w: usize, h: usize, rgba: & } #[cfg(test)] -mod tests { - use super::*; - - fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { - let (req, _rx) = ControlRequest::new(method, params); - match handle(app, ctx, &req) { - Outcome::Done(v) => v, - _ => panic!("{method}: expected an immediate reply"), - } - } - - #[test] - fn ui_set_turns_the_stroke_trace_on_and_off_at_runtime() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - assert!(!app.stroke_trace.enabled()); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"strokeTrace": true}))["ok"], true); - assert!(app.stroke_trace.enabled()); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"strokeTrace": "off"}))["ok"], true); - assert!(!app.stroke_trace.enabled()); - let bad = call(&mut app, &ctx, "ui.set", json!({"strokeTrace": 3, "tool": "Pencil"})); - assert_eq!(bad["ok"], false); - // A file path isn't accepted over the channel (it would write outside the automation - // write root); nothing is created. - let path = std::env::temp_dir().join(format!("photocraft-trace-{}.csv", std::process::id())); - let bad = call(&mut app, &ctx, "ui.set", json!({"strokeTrace": path.to_str().unwrap(), "tool": "Pencil"})); - assert_eq!(bad["ok"], false); - assert!(!path.exists()); - assert!(!app.stroke_trace.enabled() && app.ui.tool != crate::state::Tool::Pencil, "a rejected call applies nothing"); - } - - #[test] - fn camera_raw_control_updates_and_commits_or_cancels_an_open_raw() { - use photocraft_raw::testgen::{DngSpec, mosaic, scene}; - let (w, h) = (48, 32); - let mut spec = DngSpec::cfa(w, h, mosaic(&scene(w, h), w, [0, 1, 1, 2], 0, 30000)); - spec.as_shot_neutral = Some([0.5, 1.0, 0.7]); - let dng = spec.build(); - for finish in ["commit", "cancel"] { - let services = crate::Services { - import: Some(Box::new(|name, bytes, opts| { - photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, Default::default()); - app.open_bytes("control.dng", &dng).unwrap(); - ctx.run_ui(Default::default(), |ui| crate::camera_raw_ui::show(&mut app, ui.ctx())).textures_delta.clear(); - assert!(app.camera_raw.is_some()); - // A developed raw has no embedded profile to ask about (`open_prompt`), so no profile - // prompt stands between the open and the Camera Raw dialog. - assert!(app.ui.dialogs.is_empty()); - let update = json!({"id":"filter.cameraRaw","params":{"ui":{"set":{"exposure":0.5}}}}); - let original = app.session.active().unwrap().doc.clone(); - let changed = call(&mut app, &ctx, "ui.menu.invoke", update.clone()); - let undone = call(&mut app, &ctx, "ui.menu.invoke", json!({"id":"filter.cameraRaw","params":{"ui":{"undo":true}}})); - assert_eq!(undone["result"]["params"]["exposure"], 0.0, "{undone}"); - let redone = call(&mut app, &ctx, "ui.menu.invoke", json!({"id":"filter.cameraRaw","params":{"ui":{"redo":true}}})); - assert_eq!(redone["result"]["params"]["exposure"], 0.5, "{redone}"); - assert_eq!(changed["ok"], true, "{changed}"); - assert_eq!(changed["result"]["params"]["exposure"], 0.5); - assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original), "a preview must not commit"); - assert!(!crate::menus::modal_allows(&app, "filter.cameraRaw"), "native menu clicks stay blocked"); - let finished = call(&mut app, &ctx, "ui.menu.invoke", json!({"id":"filter.cameraRaw","params":{"ui":{finish:true}}})); - assert_eq!(finished["ok"], true, "{finished}"); - assert!(app.camera_raw.is_none()); - if finish == "commit" { - assert_eq!(finished["result"]["redeveloped"], true, "{finished}"); - assert_eq!(app.session.documents().len(), 1); - let st = app.session.active().unwrap(); - assert_ne!(st.doc.id, original.id); - assert_eq!(st.doc.depth, photocraft_color::SampleType::U16); - assert_eq!(st.saved_revision, st.revision); - } else { - assert_eq!(finished["result"]["cancelled"], true); - assert!(app.session.documents().is_empty()); - } - } - } - - #[test] - fn camera_raw_control_continuation_does_not_bypass_other_modal_or_command_gates() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width":16,"height":16})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"color":"#808080"})).unwrap(); - let opened = call(&mut app, &ctx, "ui.menu.invoke", json!({"id":"filter.cameraRaw"})); - assert_eq!(opened["ok"], true, "{opened}"); - let original = app.session.active().unwrap().doc.clone(); - let cancel = json!({"id":"filter.cameraRaw","params":{"ui":{"cancel":true}}}); - for request in [ - json!({"id":"file.new"}), - json!({"id":"view.zoomIn"}), - json!({"id":"filter.cameraRaw"}), - json!({"id":"filter.cameraRaw","params":{"exposure":1}}), - json!({"id":"filter.cameraRaw","params":{"ui":null}}), - json!({"id":"filter.cameraRaw","params":{"ui":{},"smartFilter":{"layer":1,"index":0}}}), - ] { - let blocked = call(&mut app, &ctx, "ui.menu.invoke", request); - assert_eq!(blocked["ok"], false, "{blocked}"); - } - app.ui.open_dialog(DialogKind::About, Default::default()); - assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", cancel.clone())["ok"], false); - app.ui.dialogs.clear(); - assert!(crate::discard_ui::intercept(&mut app, "file.close", &json!({}))); - assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", cancel.clone())["ok"], false); - app.discard = None; - app.ui.tool = Tool::Crop; - app.ui.crop_rect = Some([1.0, 1.0, 10.0, 10.0]); - assert!(crate::crop_ui::blocks(&app, "filter.cameraRaw")); - assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", cancel.clone())["ok"], false); - app.ui.crop_rect = None; - app.services.automation_command = Some(Box::new(|id, _| if id == "filter.cameraRaw" { Err("Camera Raw denied".into()) } else { Ok(()) })); - for ui in [json!({"set":{"exposure":1}}), json!({"commit":true}), json!({"cancel":true})] { - let denied = call(&mut app, &ctx, "ui.menu.invoke", json!({"id":"filter.cameraRaw","params":{"ui":ui}})); - assert_eq!(denied["ok"], false, "{denied}"); - assert_eq!(denied["error"], "Camera Raw denied"); - } - assert_eq!(app.camera_raw.as_ref().unwrap().params.exposure, 0.0); - assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original)); - app.services.automation_command = None; - assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", cancel)["ok"], true); - assert!(app.camera_raw.is_none()); - } - - #[test] - fn full_window_workspaces_are_modal_for_menu_invocations() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width":32,"height":32})).unwrap(); - app.run("file.new", json!({"width":32,"height":32})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"color":"#808080"})).unwrap(); - app.run("select.rect", json!({"x":8,"y":8,"width":8,"height":8})).unwrap(); - for workspace in ["filter.liquify", "edit.contentAwareFill", "filter.filterGallery", "filter.adaptiveWideAngle"] { - let opened = call(&mut app, &ctx, "ui.menu.invoke", json!({"id":workspace})); - assert_eq!(opened["ok"], true, "{workspace}: {opened}"); - assert_eq!(crate::distort_ui::modal_workspace(&app), Some(workspace)); - let doc = app.session.active().unwrap().doc.id; - for request in [ - json!({"id":"window.document.0"}), - json!({"id":"select.all"}), - json!({"id":"view.zoomIn"}), - json!({"id":"filter.cameraRaw"}), - json!({"id":workspace,"params":{"ui":null}}), - ] { - let blocked = call(&mut app, &ctx, "ui.menu.invoke", request.clone()); - assert_eq!(blocked["ok"], false, "{workspace}: {request} → {blocked}"); - assert!(!crate::menus::modal_allows(&app, request["id"].as_str().unwrap()), "{workspace}: native menu greys {request}"); - } - let listed = call(&mut app, &ctx, "ui.menu.list", json!({})); - let enabled = |id: &str| listed["result"].as_array().unwrap().iter().find(|it| it["id"] == id).map(|it| it["enabled"].clone()); - assert_eq!(enabled("select.all"), Some(json!(false)), "{workspace}: ui.menu.list greys what invoke refuses"); - assert_eq!(crate::distort_ui::modal_workspace(&app), Some(workspace), "{workspace} stays open with its work"); - assert_eq!(app.session.active().unwrap().doc.id, doc); - // An open dialog still takes precedence over the workspace's own requests. - app.ui.open_dialog(DialogKind::About, Default::default()); - let cancel = json!({"id":workspace,"params":{"ui":{"cancel":true}}}); - assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", cancel.clone())["ok"], false); - app.ui.dialogs.clear(); - let cancelled = call(&mut app, &ctx, "ui.menu.invoke", cancel); - assert_eq!(cancelled["ok"], true, "{workspace}: {cancelled}"); - assert_eq!(crate::distort_ui::modal_workspace(&app), None); - assert!(crate::menus::modal_allows(&app, "select.all"), "{workspace}: menus are free again"); - let listed = call(&mut app, &ctx, "ui.menu.list", json!({})); - assert!( - listed["result"].as_array().unwrap().iter().any(|it| it["id"] == "select.all" && it["enabled"] == true), - "{workspace}: listed as enabled again" - ); - } - // engine.execute stays programmatic: it is not a menu click. - assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id":"filter.liquify"}))["ok"], true); - let executed = call(&mut app, &ctx, "engine.execute", json!({"command":"select.all"})); - assert_eq!(executed["ok"], true, "{executed}"); - } - - #[test] - fn layer_style_picker_control_binds_previews_confirms_and_cancels() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width":16,"height":16})).unwrap(); - let parent = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"layerStyle","effect":"gradientOverlay"}))["result"]["dialog"].as_u64(); - let parent = parent.unwrap(); - let before = app.ui.dialogs[0].fields.clone(); - for field in ["from", "to"] { - let reply = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","parent":parent,"effect":"fx1","field":field})); - assert_eq!(reply["ok"], true, "{reply}"); - let picker = app.ui.dialogs.last().unwrap().id; - let inspected = call(&mut app, &ctx, "ui.inspect", json!({})); - assert!(inspected.to_string().contains("__layerStyleColor")); - assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog":parent}))["ok"], false); - assert_eq!(call(&mut app, &ctx, "ui.dialog.set", json!({"dialog":picker,"field":"color","value":"#123456"}))["ok"], true); - assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog":picker}))["ok"], true); - assert_eq!(app.ui.dialogs[0].fields["effects"][0]["params"][field], "#123456"); - } - assert_ne!(app.ui.dialogs[0].fields, before); - call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","parent":parent,"effect":"fx1","field":"to"})); - assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog":parent}))["ok"], true); - assert!(app.ui.dialogs.is_empty()); - } - - #[test] - fn text_style_picker_control_uses_bound_target_and_rejects_invalid_requests_atomically() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width":32,"height":32})).unwrap(); - let id = app.run("type.characterStyle.new", json!({"fromSelection":false,"attrs":{"color":"#123456"}})).unwrap()["id"].as_u64().unwrap(); - for style in [ - Value::Null, - json!({"kind":"wrong","id":id}), - json!({"kind":"character","id":"bad"}), - json!({"kind":"paragraph","id":u64::MAX}), - json!({"kind":"character","id":0}), - json!({"kind":"character","id":id,"extra":1}), - ] { - let panels = app.ui.type_panels.clone(); - assert_eq!(call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","textStyle":style}))["ok"], false); - assert_eq!(app.ui.type_panels, panels); - assert!(app.ui.dialogs.is_empty()); - } - assert_eq!(call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","textStyle":{"kind":"character","id":id},"parent":1}))["ok"], false); - let doc = app.session.active().unwrap().doc.clone(); - let r = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","textStyle":{"kind":"character","id":id}})); - assert_eq!(r["ok"], true); - let picker = r["result"]["dialog"].as_u64().unwrap(); - assert_eq!(app.ui.dialogs[0].fields["__textStyleColor"]["id"], id); - assert_eq!(call(&mut app, &ctx, "ui.dialog.set", json!({"dialog":picker,"field":"color","value":"#00ff00"}))["ok"], true); - assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog":picker}))["ok"], true); - assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &doc)); - let r = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","textStyle":{"kind":"character","id":id}})); - let picker = r["result"]["dialog"].as_u64().unwrap(); - call(&mut app, &ctx, "ui.dialog.set", json!({"dialog":picker,"field":"color","value":"#00ff00"})); - assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog":picker}))["ok"], true); - assert_ne!(app.session.active().unwrap().doc.text_styles, doc.text_styles); - } - - #[test] - fn layer_style_picker_control_rejects_bad_targets_without_opening_tool_picker() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width":16,"height":16})).unwrap(); - let parent = crate::layer_style::open(&mut app, Some("colorOverlay")).unwrap(); - for params in [ - json!({"kind":"colorPicker","parent":null,"effect":"fx1","field":"color"}), - json!({"kind":"colorPicker","parent":"bad","effect":"fx1","field":"color"}), - json!({"kind":"colorPicker","parent":parent,"effect":3,"field":"color"}), - json!({"kind":"colorPicker","parent":parent,"effect":"missing","field":"color"}), - json!({"kind":"colorPicker","parent":parent,"effect":"fx1","field":"opacity"}), - json!({"kind":"colorPicker","parent":parent,"effect":"fx1","field":"to"}), - json!({"kind":"colorPicker","effect":"fx1","field":"color"}), - ] { - let before = app.ui.dialogs.clone(); - assert_eq!(call(&mut app, &ctx, "ui.dialog.open", params)["ok"], false); - assert_eq!(app.ui.dialogs, before); - } - } - - #[test] - fn shape_stroke_defaults_are_drivable_and_validate_atomically() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let result = call( - &mut app, - &ctx, - "ui.set", - json!({"tool":"Triangle", "shapeStroke":{"width":5,"cap":"round","join":"bevel","dashes":[0,2,4,1],"dashOffset":-0.5}}), - ); - assert_eq!(result["ok"], true); - assert_eq!(app.ui.tool_options.stroke_width, 5.0); - assert_eq!(app.ui.tool_options.shape_stroke.dashes, [0.0, 2.0, 4.0, 1.0]); - let before = app.ui.clone(); - let bad = call(&mut app, &ctx, "ui.set", json!({"tool":"Rectangle","shapeStroke":{"dashes":[0,0]}})); - assert_eq!(bad["ok"], false); - assert_eq!(app.ui, before); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"shapeStroke":{"colour":"#ff0000"}}))["ok"], false); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"shapeStroke":null}))["ok"], true); - assert_eq!(app.ui.tool_options.stroke_width, 0.0); - } - - #[test] - fn the_unsaved_changes_prompt_is_listed_and_answered_through_ui_dialog() { - // #4920: the prompt shown on quit or close with unsaved changes wasn't in ui.inspect, and a - // control client couldn't answer it. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - for _ in 0..2 { - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - } - let prompt = |app: &mut PhotocraftApp| { - let v = call(app, &ctx, "ui.inspect", json!({})); - v["result"]["dialogs"].as_array().unwrap().iter().find(|d| d["id"] == "discard").cloned() - }; - assert!(prompt(&mut app).is_none()); - // Closing a dirty document: listed with its choices; a bad choice and Cancel keep the document. - crate::menus::invoke(&mut app, &ctx, "file.close", json!({})).unwrap(); - let d = prompt(&mut app).expect("the prompt is listed"); - assert_eq!(d["fields"]["command"], "file.close"); - assert_eq!(d["fields"]["choices"], json!(["save", "dontSave", "cancel"])); - assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "maybe"}))["ok"], false); - assert_eq!(call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": "discard", "field": "x", "value": 1}))["ok"], false); - assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"}))["ok"], true); - assert!(prompt(&mut app).is_none() && app.session.documents().len() == 2); - assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"}))["ok"], false, "nothing left to answer"); - // Don't Save closes it. - crate::menus::invoke(&mut app, &ctx, "file.close", json!({})).unwrap(); - assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "dontSave"}))["ok"], true); - assert_eq!(app.session.documents().len(), 1); - // Quitting asks about each dirty document, then lets the window close. - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - assert!(crate::discard_ui::intercept(&mut app, "file.exit", &Value::Null)); - let d = prompt(&mut app).expect("the quit prompt is listed"); - assert_eq!((d["fields"]["command"].as_str(), d["fields"]["remaining"].as_u64()), (Some("file.exit"), Some(2))); - assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "dontSave"}))["result"]["open"], true); - assert_eq!(prompt(&mut app).unwrap()["fields"]["remaining"], 1); - assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "dontSave"}))["result"]["open"], false); - assert!(app.allow_close && app.session.documents().is_empty()); - } - - #[test] - fn shell_dialogs_are_listed_and_driven_through_ui_dialog() { - // #1004: Window › Workspace and View dialogs live in `ui.shell.dialog`, and ui.inspect and - // ui.dialog.* only knew `ui.dialogs`. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let shell = |app: &mut PhotocraftApp| { - let v = call(app, &ctx, "ui.inspect", json!({})); - v["result"]["dialogs"].as_array().unwrap().iter().find(|d| d["id"] == "shell").cloned() - }; - // Listed, then cancelled. - crate::menus::invoke(&mut app, &ctx, "window.workspace.newWorkspace", json!({})).unwrap(); - let d = shell(&mut app).expect("the open shell dialog is listed"); - assert_eq!((d["kind"].as_str(), d["title"].as_str()), (Some("newWorkspace"), Some("New Workspace"))); - assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "shell"}))["ok"], true); - assert!(app.ui.shell.dialog.is_none() && shell(&mut app).is_none()); - assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "shell"}))["ok"], false, "nothing left to cancel"); - // A field set over control reaches OK. - crate::menus::invoke(&mut app, &ctx, "view.show.showExtrasOptions", json!({})).unwrap(); - assert!(app.ui.view.show.notes); - assert_eq!(call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": "shell", "field": "notes", "value": false}))["ok"], true); - assert_eq!(shell(&mut app).unwrap()["fields"]["notes"], false); - assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "shell"}))["ok"], true); - assert!(!app.ui.view.show.notes && app.ui.shell.dialog.is_none()); - // An OK that fails keeps the dialog open and says why. - crate::menus::invoke(&mut app, &ctx, "view.show.showExtrasOptions", json!({})).unwrap(); - call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": "shell", "field": "bogus", "value": true})); - let r = call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "shell"})); - assert_eq!(r["ok"], false); - assert!(r["error"].as_str().unwrap_or("").contains("bogus"), "{r}"); - assert!(app.ui.shell.dialog.is_some()); - // Apply is Preferences-only; numeric ids still address ordinary dialogs only. - assert_eq!(call(&mut app, &ctx, "ui.dialog.apply", json!({"dialog": "shell"}))["ok"], false); - assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": 0}))["ok"], false); - assert!(app.ui.shell.dialog.is_some()); - } - - #[test] - fn opening_new_document_through_control_matches_clipboard_image_size() { - // #2034: every way of opening New Document uses the clipboard-aware initial fields. - let clipboard = std::sync::Arc::new(std::sync::Mutex::new(Some((100, 200, vec![255; 100 * 200 * 4])))); - let image = clipboard.clone(); - let mut app = PhotocraftApp::new( - photocraft_engine::Session::new(), - crate::Services { clipboard_get_image: Some(Box::new(move || Ok(image.lock().unwrap().clone()))), ..Default::default() }, - ); - let ctx = egui::Context::default(); - let opened = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"newDocument"})); - assert_eq!(opened["ok"], true); - let id = opened["result"]["dialog"].as_u64().expect("dialog id is returned"); - let fields = &app.ui.dialog_mut(id).expect("dialog was opened").fields; - assert_eq!((fields["width"].as_u64(), fields["height"].as_u64()), (Some(100), Some(200))); - assert_eq!(fields["__preset"], "Clipboard"); - } - - #[test] - fn expired_queued_edit_does_not_run_and_a_live_retry_runs_once() { - use std::time::{Duration, Instant}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - let before = app.session.active().unwrap(); - let layers = before.doc.layers.len(); - let steps = before.history.past_len(); - let (tx, rx) = std::sync::mpsc::channel(); - app = app.with_control(rx); - let (mut expired, expired_reply) = ControlRequest::new("engine.execute", json!({"command": "layer.new.layer"})); - expired.deadline = Some(Instant::now() - Duration::from_secs(1)); - tx.send(expired).unwrap(); - let (mut retry, retry_reply) = ControlRequest::new("engine.execute", json!({"command": "layer.new.layer"})); - retry.deadline = Some(Instant::now() + Duration::from_secs(60)); - tx.send(retry).unwrap(); - app.drain_control(&egui::Context::default()); - let expired_error = expired_reply.try_recv().unwrap()["error"].as_str().unwrap().to_string(); - assert_eq!(retry_reply.try_recv().unwrap()["ok"], true); - let after = app.session.active().unwrap(); - assert_eq!(after.doc.layers.len(), layers + 1, "only the live retry adds a layer"); - assert_eq!(after.history.past_len(), steps + 1, "the expired edit adds no undo step"); - // #3662: a caller must be able to tell this reply, safe to re-send, from the - // transport's, sent while the command may still apply. - assert!(expired_error.starts_with("timeout"), "machines match on the prefix: {expired_error}"); - assert!(expired_error.contains("not run"), "the expired request says it never ran: {expired_error}"); - let transport_error = super::timeout_error(); - assert!(!transport_error.contains("not run"), "the transport can't know it didn't run: {transport_error}"); - assert!(transport_error.contains("may still apply"), "the transport warns against a blind re-send: {transport_error}"); - } - - #[test] - fn a_transport_that_gives_up_learns_whether_the_command_can_still_run() { - // #3662: the transport's clock runs out no later than the UI thread's, so it is the - // one that answers; it must still tell a request that will never run from one that may. - use std::time::{Duration, Instant}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - let layers = app.session.active().unwrap().doc.layers.len(); - let (tx, rx) = std::sync::mpsc::channel(); - app = app.with_control(rx); - let ctx = egui::Context::default(); - let request = |deadline: Instant| { - let (mut req, reply) = ControlRequest::new("engine.execute", json!({"command": "layer.new.layer"})); - req.deadline = Some(deadline); - (req.dispatch.clone(), req, reply) - }; - - let (dispatch, queued, _) = request(Instant::now() + Duration::from_secs(60)); - tx.send(queued).unwrap(); - assert_eq!(dispatch.give_up(), super::expired_error(), "still queued: it will not run"); - app.drain_control(&ctx); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "a request given up on never runs"); - - let (dispatch, expired, _) = request(Instant::now() - Duration::from_secs(1)); - tx.send(expired).unwrap(); - app.drain_control(&ctx); - assert_eq!(dispatch.give_up(), super::expired_error(), "rejected by the UI thread: it did not run"); - - let (dispatch, live, reply) = request(Instant::now() + Duration::from_secs(60)); - tx.send(live).unwrap(); - app.drain_control(&ctx); - assert_eq!(reply.try_recv().unwrap()["ok"], true); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1); - assert_eq!(dispatch.give_up(), super::timeout_error(), "dispatched: it may still apply"); - } - - #[test] - fn timeout_errors_name_the_likely_causes() { - // #2489: the reply must tell "wait" from "check the machine", and its number - // must come from the deadline it reports. - let error = super::timeout_error(); - assert!(error.starts_with("timeout"), "machines match on the prefix"); - assert!(error.contains(&format!("{}s", super::REPLY_DEADLINE.as_secs())), "the text matches the deadline: {error}"); - assert!(error.contains("may still be running"), "the wait-it-out cause"); - assert!(error.contains("display asleep"), "the check-the-display cause"); - assert!(error.contains("frame"), "the frame-loop cause"); - } - - #[test] - fn deadline_free_requests_run_even_after_the_receiver_is_dropped() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - let layers = app.session.active().unwrap().doc.layers.len(); - let (tx, rx) = std::sync::mpsc::channel(); - app = app.with_control(rx); - let (req, reply) = ControlRequest::new("engine.execute", json!({"command": "layer.new.layer"})); - assert!(req.deadline.is_none()); - drop(reply); - tx.send(req).unwrap(); - app.drain_control(&egui::Context::default()); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1); - } - - #[test] - fn right_pointer_opens_agent_visible_selection_menu() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.run("select.rect", json!({"x": 1, "y": 1, "width": 8, "height": 8})).unwrap(); - let result = call( - &mut app, - &ctx, - "ui.pointer", - json!({ - "tool": "RectMarquee", "button": "secondary", - "events": [{"kind": "down", "x": 4, "y": 4}, {"kind": "up", "x": 4, "y": 4}] - }), - ); - assert_eq!(result.get("ok"), Some(&Value::Bool(true))); - let inspected = call(&mut app, &ctx, "ui.inspect", json!({})); - let entries = inspected.pointer("/result/canvasToolMenu/entries").and_then(Value::as_array).unwrap(); - assert!(entries.iter().any(|entry| entry.get("id") == Some(&json!("select.inverse")) && entry.get("enabled") == Some(&json!(true)))); - assert!(app.session.active().unwrap().doc.selection.is_some(), "right-click must not edit selection"); - } - - #[test] - fn agent_right_click_with_the_zoom_tool_opens_and_runs_the_view_menu() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.sync_views(); - let result = call( - &mut app, - &ctx, - "ui.pointer", - json!({"tool": "Zoom", "button": "secondary", "events": [{"kind":"down","x":8,"y":8},{"kind":"up","x":8,"y":8}]}), - ); - assert_eq!(result["ok"], true); - assert_eq!(app.ui.canvas_tool_menu.as_ref().and_then(|m| m.anchor), Some([8.0, 8.0])); - let inspected = call(&mut app, &ctx, "ui.inspect", json!({})); - let entries = inspected.pointer("/result/canvasToolMenu/entries").and_then(Value::as_array).unwrap(); - let ids: Vec<_> = entries.iter().filter_map(|row| row.get("id").and_then(Value::as_str)).collect(); - assert_eq!( - ids, - ["view.fitOnScreen", "view.fillScreen", "view.actualPixels", "view.twoHundredPercent", "view.printSize", "view.zoomIn", "view.zoomOut"] - ); - assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id":"select.all"}))["ok"], false); - assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id":"view.twoHundredPercent"}))["ok"], true); - assert_eq!(app.ui.views[0].zoom, 2.0); - assert!(app.ui.canvas_tool_menu.is_none()); - } - - /// #6561: an agent's right-click on a pending crop opens the crop menu, as on the canvas. - #[test] - fn agent_right_click_on_a_pending_crop_opens_and_runs_the_crop_menu() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.sync_views(); - app.ui.tool = crate::state::Tool::Crop; - app.ui.tool_options.crop_shield.classic_mode = true; - app.ui.extras.snap = false; - crate::crop_ui::ensure_frame(&mut app); - tool_event(&mut app, ToolEvent::Down { x: 4.0, y: 4.0, pressure: 1.0 }, egui::Modifiers::NONE); - tool_event(&mut app, ToolEvent::Move { x: 16.0, y: 12.0, pressure: 1.0 }, egui::Modifiers::NONE); - tool_event(&mut app, ToolEvent::Move { x: 28.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); - tool_event(&mut app, ToolEvent::Up { x: 28.0, y: 20.0 }, egui::Modifiers::NONE); - let frame = app.ui.crop_rect.unwrap(); - let result = call( - &mut app, - &ctx, - "ui.pointer", - json!({"tool": "Crop", "button": "secondary", "events": [{"kind":"down","x":16,"y":12},{"kind":"up","x":16,"y":12}]}), - ); - assert_eq!(result["ok"], true); - let inspected = call(&mut app, &ctx, "ui.inspect", json!({})); - assert_eq!(inspected.pointer("/result/canvasToolMenu/crop"), Some(&json!(true))); - let entries = inspected.pointer("/result/canvasToolMenu/entries").and_then(Value::as_array).unwrap(); - assert!(entries.iter().any(|row| row.get("id") == Some(&json!("crop.commit")) && row.get("enabled") == Some(&json!(true)))); - assert_eq!(app.ui.crop_rect, Some(frame), "the right-click leaves the frame alone"); - assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id":"crop.commit"}))["ok"], true); - let size = app.session.active().unwrap().doc.size; - assert_eq!([f64::from(size.width), f64::from(size.height)], [frame[2] - frame[0], frame[3] - frame[1]], "cropped to the frame"); - } - - /// An agent's right-click while its own crop frame drag is still down opens no menu over it; - /// after the drag's release it does. - #[test] - fn agent_right_click_during_its_crop_drag_opens_no_menu() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.sync_views(); - app.ui.tool = crate::state::Tool::Crop; - app.ui.tool_options.crop_shield.classic_mode = true; - app.ui.extras.snap = false; - crate::crop_ui::ensure_frame(&mut app); - let pointer = |app: &mut PhotocraftApp, button: &str, events: Value| { - assert_eq!(call(app, &ctx, "ui.pointer", json!({"tool": "Crop", "button": button, "events": events}))["ok"], true); - }; - // The first drag on the default frame (nothing pending yet): no pasteboard menu outside the image. - pointer(&mut app, "left", json!([{"kind":"down","x":4,"y":4},{"kind":"move","x":16,"y":12},{"kind":"move","x":28,"y":20}])); - assert!(app.crop.drag.is_some() && !crate::crop_ui::pending(&app), "the first frame is still being drawn"); - pointer(&mut app, "secondary", json!([{"kind":"down","x":-8,"y":-8},{"kind":"up","x":-8,"y":-8}])); - assert!(app.ui.canvas_tool_menu.is_none(), "no pasteboard menu over the first drag"); - pointer(&mut app, "left", json!([{"kind":"up","x":28,"y":20}])); - // A second drag, on the drawn frame, still down. - pointer(&mut app, "left", json!([{"kind":"down","x":16,"y":12},{"kind":"move","x":18,"y":14}])); - assert!(app.crop.drag.is_some() && crate::crop_ui::pending(&app), "the frame drag is still down"); - let right_click = json!([{"kind":"down","x":16,"y":12},{"kind":"up","x":16,"y":12}]); - pointer(&mut app, "secondary", right_click.clone()); - assert!(app.ui.canvas_tool_menu.is_none(), "no menu over the drag"); - pointer(&mut app, "left", json!([{"kind":"up","x":18,"y":14}])); - pointer(&mut app, "secondary", right_click.clone()); - assert!(app.ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some()), "after the release it opens"); - // Nor over a Straighten line still being drawn. - app.ui.canvas_tool_menu = None; - crate::crop_straighten::toggle(&mut app); - pointer(&mut app, "left", json!([{"kind":"down","x":6,"y":6},{"kind":"move","x":20,"y":8}])); - assert!(app.crop.straighten.line.is_some(), "the Straighten line is still down"); - pointer(&mut app, "secondary", right_click); - assert!(app.ui.canvas_tool_menu.is_none(), "no menu over the Straighten line"); - } - - #[test] - fn agent_can_inspect_and_choose_pen_make_selection_from_full_context_menu() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.run("path.set", json!({"name":"work","path":{"subpaths":[{"closed":true,"knots":[[2,2],[20,2],[20,20]]}]}})).unwrap(); - let expected_pos = screen_point(&app, 8.0, 8.0); - let result = call( - &mut app, - &ctx, - "ui.pointer", - json!({ - "tool": "Pen", "button": "secondary", "events": [{"kind":"down","x":8,"y":8},{"kind":"up","x":8,"y":8}] - }), - ); - assert_eq!(result["ok"], true); - let inspected = call(&mut app, &ctx, "ui.inspect", json!({})); - assert_eq!(app.ui.canvas_tool_menu.as_ref().unwrap().pos, expected_pos); - let entries = inspected.pointer("/result/canvasToolMenu/entries").and_then(Value::as_array).unwrap(); - assert_eq!(entries.iter().filter(|row| row.get("separator") == Some(&json!(true))).count(), 9); - assert!(entries.iter().any(|row| row.get("id") == Some(&json!("path.toSelection")) && row.get("enabled") == Some(&json!(true)))); - assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id":"file.new"}))["ok"], false); - let chosen = call(&mut app, &ctx, "ui.context.choose", json!({"id":"path.toSelection"})); - assert_eq!(chosen["ok"], true); - let dialog = chosen["result"]["dialog"].as_u64().unwrap(); - assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog":dialog}))["ok"], true); - assert!(app.session.active().unwrap().doc.selection.is_some()); - } - - #[test] - fn ui_inspect_reports_the_view_preferences() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let before = call(&mut app, &ctx, "ui.inspect", json!({})); - assert_eq!(before.pointer("/result/view/show/selection_edges"), Some(&json!(true))); - assert_eq!(before.pointer("/result/view/screen_mode"), Some(&json!("standard"))); - assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "view.show.selectionEdges"}))["ok"], true); - let after = call(&mut app, &ctx, "ui.inspect", json!({})); - assert_eq!(after.pointer("/result/view/show/selection_edges"), Some(&json!(false))); - assert_eq!(after["result"]["view"], json!(app.ui.view)); - } - - #[test] - fn engine_execute_runs_with_defaults_but_menu_invoke_opens_the_dialog() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.run("edit.fill", json!({"color": "#808080"})).unwrap(); - let rev = app.session.active().unwrap().revision; - let r = call(&mut app, &ctx, "engine.execute", json!({"command": "filter.blur.gaussianBlur"})); - assert!(!r.to_string().contains("\"dialog\""), "engine.execute opened a dialog: {r}"); - assert!(app.session.active().unwrap().revision > rev, "engine.execute didn't run the filter"); - let rev = app.session.active().unwrap().revision; - let r = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "filter.blur.gaussianBlur"})); - assert!(r.to_string().contains("dialog"), "ui.menu.invoke should open the dialog: {r}"); - assert_eq!(app.session.active().unwrap().revision, rev, "opening a dialog must not edit the document"); - } - - #[test] - fn menu_invoke_cannot_edit_document_behind_an_open_dialog() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - - let opened = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "image.imageSize"})); - assert_eq!(opened["ok"], true, "{opened}"); - let dialog = opened["result"]["dialog"].as_u64().unwrap(); - let revision = app.session.active().unwrap().revision; - let before = call(&mut app, &ctx, "ui.inspect", json!({})); - let fields = before["result"]["dialogs"][0]["fields"].clone(); - - for params in [json!({"id": "image.imageRotation.90cw"}), json!({"id": "image.imageRotation.90cw", "params": {}})] { - let blocked = call(&mut app, &ctx, "ui.menu.invoke", params); - assert_eq!(blocked["ok"], false, "{blocked}"); - assert_eq!(app.session.active().unwrap().revision, revision); - let snapshot = call(&mut app, &ctx, "ui.inspect", json!({})); - assert_eq!(snapshot["result"]["dialogs"][0]["id"], dialog); - assert_eq!(snapshot["result"]["dialogs"][0]["fields"], fields); - } - - // View navigation stays permitted by the same policy as native menus and shortcuts. - assert!(crate::menus::modal_allows(&app, "view.zoomIn")); - assert!(!crate::menus::modal_allows(&app, "image.imageRotation.90cw")); - - assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": dialog}))["ok"], true); - let rotated = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "image.imageRotation.90cw"})); - assert_eq!(rotated["ok"], true, "{rotated}"); - assert!(app.session.active().unwrap().revision > revision); - } - - #[test] - fn ui_set_rejects_unknown_fields_before_changing_anything() { - use crate::theme::ThemeKind; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.set_theme(&ctx, ThemeKind::StudioLight); - // `dark` was advertised to MCP clients but never read; a typo looked like success too. - for params in [json!({"dark": true}), json!({"thme": "classic"}), json!({"tool": "move", "dark": true})] { - let r = call(&mut app, &ctx, "ui.set", params.clone()); - assert_eq!(r["ok"], false, "{params}: {r}"); - assert!(r["error"].as_str().unwrap().contains("unknown field"), "{r}"); - } - assert_eq!(app.ui.theme, ThemeKind::StudioLight); - assert_eq!(app.ui.tool, Tool::Brush, "a rejected call applies none of its fields"); - // Every field the method reads gets past the check (a bad value is its own error). - for field in UI_SET_FIELDS { - let r = call(&mut app, &ctx, "ui.set", json!({ field: null })); - assert!(!r.to_string().contains("unknown field"), "{field}: {r}"); - } - assert_eq!(call(&mut app, &ctx, "ui.set", Value::Null)["ok"], true); - } - - #[test] - fn ui_set_gradient_blend_mode_validates_and_updates_options() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let good = call(&mut app, &ctx, "ui.set", json!({"tool": "gradient", "gradientBlendMode": "Difference", "gradientClassic": true})); - assert_eq!(good["ok"], true, "{good}"); - assert_eq!(app.ui.tool_options.gradient_blend_mode, photocraft_color::BlendMode::Difference); - assert!(app.ui.tool_options.gradient_classic); - let bad = call(&mut app, &ctx, "ui.set", json!({"gradientBlendMode": "nonsense", "gradientClassic": false})); - assert_eq!(bad["ok"], false, "{bad}"); - assert!(app.ui.tool_options.gradient_classic, "invalid mode must not change options"); - } - - /// #5048: the Layers panel filter is drivable; a bad field changes nothing. - #[test] - fn ui_set_drives_the_layers_panel_filter() { - use crate::layer_filter_ui::FilterBy; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let ok = call(&mut app, &ctx, "ui.set", json!({"layerFilter": {"by": "name", "name": "ink"}})); - assert_eq!(ok["ok"], true, "{ok}"); - assert_eq!((app.ui.layer_filter_by, app.ui.layer_filter_name.as_str()), (FilterBy::Name, "ink")); - let ok = call(&mut app, &ctx, "ui.set", json!({"layerFilter": {"by": "mode", "mode": "Pass Through", "kinds": ["type", "pixel", "type"]}})); - assert_eq!(ok["ok"], true, "{ok}"); - assert_eq!((app.ui.layer_filter_by, app.ui.layer_filter_mode), (FilterBy::Mode, photocraft_color::BlendMode::PassThrough)); - assert_eq!(app.ui.layer_filter, ["type", "pixel"], "kinds are kept once each"); - assert_eq!(app.ui.layer_filter_name, "ink", "fields left out keep their value"); - for bad in [ - json!({"layerFilter": "name"}), - json!({"layerFilter": {"by": "colour"}}), - json!({"layerFilter": {"kinds": ["pixels"]}}), - json!({"layerFilter": {"kinds": "pixel"}}), - json!({"layerFilter": {"name": 3}}), - json!({"layerFilter": {"mode": "Nonsense"}}), - json!({"layerFilter": {"by": "kind", "extra": true}}), - json!({"layerFilter": {"by": "kind"}, "tileGrid": "yes"}), - ] { - let r = call(&mut app, &ctx, "ui.set", bad.clone()); - assert_eq!(r["ok"], false, "{bad} → {r}"); - assert_eq!(app.ui.layer_filter_by, FilterBy::Mode, "{bad} changed nothing"); - } - } - - #[test] - fn ui_set_toggles_the_developer_tile_grid() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - assert!(!app.ui.view.tile_grid, "off by default"); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"tileGrid": true}))["ok"], true); - assert!(app.ui.view.tile_grid); - assert_eq!(call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["view"]["tile_grid"], true); - // Not a View › Show item: Extras doesn't hide it, and Show Extras Options doesn't list it. - crate::menus::invoke(&mut app, &ctx, "view.extras", json!({})).unwrap(); - assert!(!app.ui.view.extras && app.ui.view.tile_grid); - assert!(serde_json::to_value(app.ui.view.show).unwrap().get("tile_grid").is_none()); - let bad = call(&mut app, &ctx, "ui.set", json!({"tileGrid": "yes"})); - assert_eq!(bad["ok"], false, "{bad}"); - assert!(app.ui.view.tile_grid, "a rejected value changes nothing"); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"tileGrid": false}))["ok"], true); - assert!(!app.ui.view.tile_grid); - } - - #[test] - fn ui_set_drives_the_eyedropper_options() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let good = call( - &mut app, - &ctx, - "ui.set", - json!({"tool": "eyedropper", "eyedropperSampleSize": 11, "eyedropperSample": "currentAndBelow", "eyedropperRing": false}), - ); - assert_eq!(good["ok"], true, "{good}"); - let o = &app.ui.tool_options; - assert_eq!((o.eyedropper_size, o.eyedropper_sample.as_str(), o.eyedropper_ring), (11, "currentAndBelow", false)); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"eyedropperSampleSize": "point"}))["ok"], true); - assert_eq!(app.ui.tool_options.eyedropper_size, 1); - for bad in [ - json!({"eyedropperSampleSize": 4}), - json!({"eyedropperSampleSize": "big"}), - json!({"eyedropperSample": "below"}), - json!({"eyedropperSample": 2}), - json!({"eyedropperRing": "yes"}), - ] { - let r = call(&mut app, &ctx, "ui.set", bad.clone()); - assert_eq!(r["ok"], false, "{bad}: {r}"); - } - // A rejected call applies none of its fields. - let r = call(&mut app, &ctx, "ui.set", json!({"eyedropperSampleSize": 101, "eyedropperSample": "nope"})); - assert_eq!(r["ok"], false, "{r}"); - assert_eq!(app.ui.tool_options.eyedropper_size, 1); - } - - /// #1046: the Color Sampler tool is selectable over the control channel and reported as active. - #[test] - fn ui_set_selects_the_color_sampler_tool() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"tool": "colorSampler"}))["ok"], true); - assert_eq!(app.ui.tool, Tool::ColorSampler); - assert_eq!(call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["tool"], "ColorSampler"); - // The `I` key group cycles through the eyedropper tools, so the sampler is on the same key. - assert_eq!(Tool::ColorSampler.key(), 'I'); - } - - /// #3823: the Crop tool's Fill over the control channel, reported by `ui.inspect`. - #[test] - fn ui_set_drives_the_crop_fill() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"tool": "crop", "cropFill": "contentAware"}))["ok"], true); - assert!(app.ui.tool_options.crop_content_aware); - assert_eq!(call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["toolOptions"]["crop_content_aware"], true); - for bad in [json!("generativeExpand"), json!(true), json!(1)] { - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"cropFill": bad}))["ok"], false, "{bad}"); - assert!(app.ui.tool_options.crop_content_aware, "{bad}: unchanged"); - } - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"cropFill": "background"}))["ok"], true); - assert!(!app.ui.tool_options.crop_content_aware); - } - - /// #1919: the Crop tool's overlay menu over the control channel, reported by `ui.inspect`. - #[test] - fn ui_set_drives_the_crop_overlay_options() { - use crate::crop_overlay::{CropOverlay, OverlayShow}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let good = - call(&mut app, &ctx, "ui.set", json!({"tool": "crop", "cropOverlay": "goldenSpiral", "cropOverlayShow": "always", "cropOverlayOrientation": 2})); - assert_eq!(good["ok"], true, "{good}"); - let o = &app.ui.tool_options; - assert_eq!((o.crop_overlay, o.crop_overlay_show, o.crop_overlay_orientation), (CropOverlay::GoldenSpiral, OverlayShow::Always, 2)); - let seen = call(&mut app, &ctx, "ui.inspect", json!({})); - let t = &seen["result"]["toolOptions"]; - assert_eq!( - (t["crop_overlay"].as_str(), t["crop_overlay_show"].as_str(), t["crop_overlay_orientation"].as_u64()), - (Some("goldenSpiral"), Some("always"), Some(2)) - ); - for bad in [ - json!({"cropOverlay": "spiral"}), - json!({"cropOverlay": 1}), - json!({"cropOverlayShow": "sometimes"}), - json!({"cropOverlayOrientation": 4}), - json!({"cropOverlayOrientation": -1}), - json!({"cropOverlayOrientation": "1"}), - json!({"cropOverlay": "grid", "cropOverlayShow": "nope"}), - ] { - let r = call(&mut app, &ctx, "ui.set", bad.clone()); - assert_eq!(r["ok"], false, "{bad}: {r}"); - } - assert_eq!(app.ui.tool_options.crop_overlay, CropOverlay::GoldenSpiral, "a rejected call applies none of its fields"); - } - - /// #1919: the Crop tool's gear menu (Show Cropped Area, crop shield) over the control channel. - #[test] - fn ui_set_drives_the_crop_shield_options() { - use crate::crop_shield::{CropShield, ShieldColor}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let good = call(&mut app, &ctx, "ui.set", json!({"cropShield": {"color": "custom", "custom_color": [255, 0, 0], "opacity": 40}})); - assert_eq!(good["ok"], true, "{good}"); - let want = CropShield { color: ShieldColor::Custom, custom_color: [255, 0, 0], opacity: 40.0, ..Default::default() }; - assert_eq!(app.ui.tool_options.crop_shield, want); - // A patch: the other fields stay. - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"cropShield": {"show_cropped_area": false}}))["ok"], true); - assert_eq!(app.ui.tool_options.crop_shield, CropShield { show_cropped_area: false, ..want.clone() }); - let t = &call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["toolOptions"]["crop_shield"]; - assert_eq!((t["color"].as_str(), t["opacity"].as_f64(), t["show_cropped_area"].as_bool()), (Some("custom"), Some(40.0), Some(false))); - for bad in [ - json!({"cropShield": true}), - json!({"cropShield": {"opacity": 101}}), - json!({"cropShield": {"opacity": -1}}), - json!({"cropShield": {"opacity": "50"}}), - json!({"cropShield": {"color": "red"}}), - json!({"cropShield": {"custom_color": [256, 0, 0]}}), - json!({"cropShield": {"shield": true}}), - json!({"cropShield": {"enabled": false}, "cropOverlay": "nope"}), - ] { - let r = call(&mut app, &ctx, "ui.set", bad.clone()); - assert_eq!(r["ok"], false, "{bad}: {r}"); - } - assert_eq!(app.ui.tool_options.crop_shield, CropShield { show_cropped_area: false, ..want }, "a rejected call applies none of its fields"); - } - - #[test] - 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"); - 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])); - assert!(!app.ui.brush_picker_list.show_stroke); - for bad in [ - json!({"brushPicker": [1]}), - json!({"brushPicker": "here"}), - json!({"brushPickerStroke": "nope"}), - json!({"brushPickerName": false, "brushPickerStroke": false, "brushPickerTip": false}), - ] { - assert_eq!(call(&mut app, &ctx, "ui.set", bad.clone())["ok"], false, "{bad}"); - } - assert_eq!(app.ui.brush_picker, Some([120.0, 80.0]), "a bad value leaves the picker alone"); - assert!(app.ui.brush_picker_list.show_name, "a rejected call leaves the card parts alone"); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"brushPicker": null}))["ok"], true); - assert_eq!(app.ui.brush_picker, None); - } - - #[test] - fn ui_inspect_tracks_brush_picker_open_and_closed() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 128, "height": 128})).unwrap(); - - let closed = call(&mut app, &ctx, "ui.inspect", json!({})); - assert!(closed["result"]["brushPicker"].is_null()); - - // A right-click on the canvas with Brush opens the same picker as the options bar. - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"tool": "brush"}))["ok"], true); - let click = call( - &mut app, - &ctx, - "ui.pointer", - json!({ - "button": "right", - "events": [{"kind": "down", "x": 64, "y": 64}, {"kind": "up", "x": 64, "y": 64}] - }), - ); - assert_eq!(click["ok"], true, "{click}"); - let open = call(&mut app, &ctx, "ui.inspect", json!({})); - 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!(call(&mut app, &ctx, "ui.set", json!({"brushPickerTip": false}))["ok"], true); - let changed = call(&mut app, &ctx, "ui.inspect", json!({})); - assert_eq!(changed["result"]["brushPicker"]["list"]["showTip"], false); - - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"brushPicker": null}))["ok"], true); - let closed_again = call(&mut app, &ctx, "ui.inspect", json!({})); - assert!(closed_again["result"]["brushPicker"].is_null()); - } - - #[test] - fn ui_set_applies_all_fields_or_none() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let before = app.ui.tool; - let panels_before = serde_json::to_value(&app.ui.panels).unwrap_or_default(); - // A late invalid field must not leave the earlier valid one applied - including the - // journaled brush command, which is validated up front for exactly this reason. - for params in - [json!({"tool": "move", "theme": "nope"}), json!({"tool": "move", "brushSize": 1e300}), json!({"tool": "move", "colorPanel": {"nope": true}})] - { - let r = call(&mut app, &ctx, "ui.set", params.clone()); - assert_eq!(r["ok"], false, "{params}: {r}"); - assert_eq!(app.ui.tool, before, "{params}: a rejected call applies none of its fields"); - } - // Wrong types and unknown nested keys are errors, not silent no-ops with ok:true. - for params in [ - json!({"panels": "x"}), - json!({"panels": {"nope": true}}), - json!({"dockTabs": {"nope": 1}}), - json!({"dock": {"nope": 1}}), - json!({"center": [1]}), - json!({"center": [1, 2, 3]}), - json!({"center": "here"}), - json!({"colorPanel": "x"}), - json!({"selectionMode": "add"}), - ] { - let r = call(&mut app, &ctx, "ui.set", params.clone()); - assert_eq!(r["ok"], false, "{params}: {r}"); - } - assert_eq!(serde_json::to_value(&app.ui.panels).unwrap_or_default(), panels_before, "nothing was applied"); - // Non-numeric brushSize keeps the API's historical silent no-op (see the dispatch test). - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"brushSize": "large"}))["ok"], true); - } - - #[test] - fn ui_set_rejects_view_numbers_beyond_f32_range() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.sync_views(); - let r = call(&mut app, &ctx, "ui.set", json!({"rotation": 30, "zoom": 2, "center": [3, 4], "dockWidth": 300})); - assert_eq!(r["ok"], true, "{r}"); - let dock = |ctx: &egui::Context| ctx.data(|d| d.get_temp::(crate::panels::dock_width_id())); - let (rotation, zoom, center) = (app.ui.views[0].rotation, app.ui.views[0].zoom, app.ui.views[0].center); - // Finite in f64 but infinite as f32: an error, not a silent reset to 0°, 100% or the minimum dock width. - for params in - [json!({"rotation": 1e39}), json!({"zoom": 1e39}), json!({"center": [1e39, 0]}), json!({"center": [0, -1e39]}), json!({"dockWidth": 1e39})] - { - let r = call(&mut app, &ctx, "ui.set", params.clone()); - assert_eq!(r["ok"], false, "{params}: {r}"); - assert_eq!(app.ui.views[0].rotation, rotation, "{params}"); - assert_eq!(app.ui.views[0].zoom, zoom, "{params}"); - assert_eq!(app.ui.views[0].center, center, "{params}"); - assert_eq!(dock(&ctx), Some(300.0), "{params}"); - } - // Huge but representable still clamps to the top zoom level. - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"zoom": 1e38}))["ok"], true); - assert!(app.ui.views[0].zoom.is_finite() && app.ui.views[0].zoom > zoom, "{}", app.ui.views[0].zoom); - } - - #[test] - fn ui_set_theme_keeps_explicit_dock_tab_indices() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - for theme in ["adwaitaDark", "pro"] { - let r = call(&mut app, &ctx, "ui.set", json!({"theme": theme, "dockTabs": {"color": 0}})); - assert_eq!(r["ok"], true, "{r}"); - assert_eq!(app.ui.dock_tabs.color, 0, "{theme}: explicit tab index changed"); - } - } - - #[test] - fn ui_set_color_panel_picks_the_edited_chip() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"colorPanel": {"background": true}}))["ok"], true); - assert!(app.ui.color_panel.background); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"colorPanel": {"background": "yes"}}))["ok"], false); - assert!(app.ui.color_panel.background, "a bad value changes nothing"); - } - - #[test] - fn ui_set_color_panel_mode() { - use crate::state::ColorPanelMode; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - assert_eq!(app.ui.color_panel.mode, ColorPanelMode::HueCube); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"colorPanel": {"mode": "rgbSliders"}}))["ok"], true); - assert_eq!(app.ui.color_panel.mode, ColorPanelMode::RgbSliders); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"colorPanel": {"mode": "hsbSliders"}}))["ok"], true); - assert_eq!(app.ui.color_panel.mode, ColorPanelMode::HsbSliders); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"colorPanel": {"mode": "nope"}}))["ok"], false); - assert_eq!(app.ui.color_panel.mode, ColorPanelMode::HsbSliders); - } - - #[test] - fn ui_set_unknown_theme_error_names_every_theme_and_each_name_works() { - use crate::theme::ThemeKind; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let r = call(&mut app, &ctx, "ui.set", json!({"theme": "nope"})); - assert_eq!(r["ok"], false); - let error = r["error"].as_str().unwrap(); - for kind in ThemeKind::ALL { - assert!(error.contains(kind.id()), "{error} lacks {}", kind.id()); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"theme": kind.id()}))["ok"], true); - assert_eq!(app.ui.theme, kind); - assert_eq!(ThemeKind::from_name(kind.id()), Some(kind)); - } - } - - #[test] - fn ui_window_open_rejects_an_unknown_document_index() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - // An out-of-range index must error instead of silently switching the active document - // and opening the window for whatever is active now. - let before = app.session.active_index(); - let r = call(&mut app, &ctx, "ui.window.open", json!({"document": 99})); - assert_eq!(r["ok"], false, "{r}"); - assert!(r["error"].as_str().unwrap().contains("no document 99"), "{r}"); - assert_eq!(app.session.active_index(), before, "the active document is untouched"); - // A valid index still opens the window. - assert_eq!(call(&mut app, &ctx, "ui.window.open", json!({"document": 0}))["ok"], true); - } - - #[test] - fn ui_set_brush_size_dispatches_a_journaled_brush_command() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - - let r = call(&mut app, &ctx, "ui.set", json!({"brushSize": 42.5})); - assert_eq!(r["ok"], true, "{r}"); - assert_eq!(app.session.tools.brush.size, 42.5); - let (id, params) = app.session.journal.last().cloned().expect("brush change is journaled"); - assert_eq!(id, "tools.setBrush"); - assert_eq!(params, json!({"brush": {"size": 42.5}})); - - // The control API has historically ignored non-numeric optional values. - for params in [json!({}), json!({"brushSize": null}), json!({"brushSize": "large"}), json!({"brushSize": true})] { - let journal_len = app.session.journal.len(); - let r = call(&mut app, &ctx, "ui.set", params); - assert_eq!(r["ok"], true, "{r}"); - assert_eq!(app.session.tools.brush.size, 42.5); - assert_eq!(app.session.journal.len(), journal_len); - } - - // Each tool keeps its own brush (#218), so `tool` + `brushSize` in one call sets the new - // tool's size rather than the one it was carrying. - call(&mut app, &ctx, "ui.set", json!({"tool": "eraser", "brushSize": 12.0})); - assert_eq!(app.session.tools.brush.size, 12.0, "the Eraser's own size"); - call(&mut app, &ctx, "ui.set", json!({"tool": "brush"})); - assert_eq!(app.session.tools.brush.size, 42.5, "the Brush gets its own back"); - call(&mut app, &ctx, "ui.set", json!({"tool": "eraser"})); - assert_eq!(app.session.tools.brush.size, 12.0); - call(&mut app, &ctx, "ui.set", json!({"tool": "brush", "brushSize": 42.5})); - - // Values that cannot be represented by BrushSettings must report the command error and - // leave both the brush and journal unchanged instead of mutating tool state directly. - let journal_len = app.session.journal.len(); - let r = call(&mut app, &ctx, "ui.set", json!({"brushSize": f64::MAX})); - assert_eq!(r["ok"], false, "{r}"); - assert!(r["error"].as_str().is_some(), "{r}"); - assert_eq!(app.session.tools.brush.size, 42.5); - assert_eq!(app.session.journal.len(), journal_len); - } - - #[test] - fn preferences_apply_is_available_over_control_without_closing() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let r = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "edit.preferences.interface"})); - let id = r["result"]["dialog"].as_u64().unwrap(); - let mut values = app.ui.dialog_mut(id).unwrap().fields["values"].clone(); - values["interface"]["uiScale"] = json!("200"); - assert_eq!(call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": id, "field": "values", "value": values}))["ok"], true); - assert_eq!(call(&mut app, &ctx, "ui.dialog.apply", json!({"dialog": id}))["ok"], true); - assert_eq!(app.session.prefs().interface.ui_scale, photocraft_engine::prefs::UiScale::P200); - assert!(app.ui.dialog_mut(id).is_some()); - assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id}))["ok"], true); - assert_eq!(app.session.prefs().interface.ui_scale, photocraft_engine::prefs::UiScale::P200); - for params in [json!({}), json!({"dialog": "invalid"}), json!({"dialog": u64::MAX})] { - assert_eq!(call(&mut app, &ctx, "ui.dialog.apply", params)["ok"], false); - } - } - - #[test] - fn preferences_apply_respects_the_automation_command_policy() { - let services = crate::Services { - automation_command: Some(Box::new(|id, _| if id == "prefs.set" { Err("preference changes denied".into()) } else { Ok(()) })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - let ctx = egui::Context::default(); - let before = app.session.prefs().to_json(); - let id = crate::prefs_ui::open_preferences(&mut app, "interface"); - app.ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap()["interface"]["uiScale"] = json!("200"); - let r = call(&mut app, &ctx, "ui.dialog.apply", json!({"dialog": id})); - assert_eq!(r["ok"], false); - assert_eq!(r["error"], "preference changes denied"); - assert_eq!(app.session.prefs().to_json(), before); - assert!(app.ui.dialog_mut(id).is_some()); - } - - #[test] - fn synthetic_shortcuts_use_the_automation_command_policy() { - let services = crate::Services { - automation_command: Some(Box::new(|id, _| if id.starts_with("file.") { Err("filesystem command denied".into()) } else { Ok(()) })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - let ctx = egui::Context::default(); - app.automation_input = true; - let error = crate::menus::invoke(&mut app, &ctx, "file.open", json!({})).unwrap_err(); - assert_eq!(error, "filesystem command denied"); - } - - /// `app.save` takes the Targa bits per pixel (`tgaBits`) and never stops at Targa Options. - #[test] - fn automation_save_passes_targa_bits_without_asking() { - use std::cell::RefCell; - use std::rc::Rc; - // The bits each export was asked for, and each path written. - let asked: Rc>>> = Rc::default(); - let written: Rc>> = Rc::default(); - let (a, w) = (asked.clone(), written.clone()); - let services = crate::Services { - export: Some(Box::new(move |_d: &photocraft_doc::Document, _p: &str, s: &crate::ExportSettings| { - a.borrow_mut().push(s.tga_bits.map(photocraft_io::TgaBits::bits)); - Ok((b"out".to_vec(), Vec::new())) - })), - automation_write: Some(Box::new(move |path: &str, _b: &[u8]| { - w.borrow_mut().push(path.to_string()); - Ok(()) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - for params in [json!({"path": "a.tga"}), json!({"path": "b.tga", "tgaBits": 24}), json!({"path": "c.tga", "tgaBits": 32})] { - let r = call(&mut app, &ctx, "app.save", params.clone()); - assert_eq!(r["result"]["path"], params["path"], "{r}"); - assert!(app.targa_options.is_none(), "automation saves never prompt"); - } - assert_eq!(*asked.borrow(), [None, Some(24), Some(32)]); - assert_eq!(*written.borrow(), ["a.tga", "b.tga", "c.tga"]); - let r = call(&mut app, &ctx, "app.save", json!({"path": "d.tga", "tgaBits": 16})); - assert!(r["error"].as_str().unwrap().contains("tgaBits"), "{r}"); - assert_eq!(written.borrow().len(), 3, "a bad tgaBits writes nothing"); - } - - /// `app.save` takes JPEG Options (`quality` 0–12, `jpegFormat`) and never stops at the prompt; - /// a value it can't read is an error that writes nothing. - #[test] - fn automation_save_passes_jpeg_options_without_asking() { - use photocraft_codecs::JpegFormat; - use std::cell::RefCell; - use std::rc::Rc; - // The JPEG quality (1–100) and format each export was asked for. - type Asked = Rc, JpegFormat)>>>; - let asked: Asked = Rc::default(); - let written: Rc>> = Rc::default(); - let (a, w) = (asked.clone(), written.clone()); - let services = crate::Services { - export: Some(Box::new(move |_d: &photocraft_doc::Document, _p: &str, s: &crate::ExportSettings| { - a.borrow_mut().push((s.jpeg_quality, s.jpeg_format)); - Ok((b"out".to_vec(), Vec::new())) - })), - automation_write: Some(Box::new(move |path: &str, _b: &[u8]| { - w.borrow_mut().push(path.to_string()); - Ok(()) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - for params in [ - json!({"path": "a.jpg"}), - json!({"path": "b.jpg", "quality": 12, "jpegFormat": "progressive"}), - json!({"path": "c.jpg", "jpegFormat": "optimized"}), - ] { - let r = call(&mut app, &ctx, "app.save", params.clone()); - assert_eq!(r["result"]["path"], params["path"], "{r}"); - assert!(app.jpeg_options.is_none(), "automation saves never prompt"); - } - assert_eq!(*asked.borrow(), [(None, JpegFormat::Baseline), (Some(100), JpegFormat::Progressive), (None, JpegFormat::Optimized)]); - for bad in [ - json!({"path": "d.jpg", "quality": 13}), - json!({"path": "d.jpg", "quality": "high"}), - json!({"path": "d.jpg", "jpegFormat": "fast"}), - json!({"path": "d.jpg", "jpegFormat": 2}), - ] { - let r = call(&mut app, &ctx, "app.save", bad.clone()); - assert!(r["error"].is_string(), "{bad}: {r}"); - } - assert_eq!(written.borrow().len(), 3, "a bad JPEG option writes nothing"); - } - - /// `app.save` takes the DDS options (`ddsCompression`, `ddsMipmaps`) and never stops at DDS - /// Options. - #[test] - fn automation_save_passes_dds_options_without_asking() { - use photocraft_io::{DdsCompression, DdsOptions}; - use std::cell::RefCell; - use std::rc::Rc; - let asked: Rc>> = Rc::default(); - let a = asked.clone(); - let services = crate::Services { - export: Some(Box::new(move |_d: &photocraft_doc::Document, _p: &str, s: &crate::ExportSettings| { - a.borrow_mut().push(s.dds); - Ok((b"out".to_vec(), Vec::new())) - })), - automation_write: Some(Box::new(|_: &str, _: &[u8]| Ok(()))), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - for params in [json!({"path": "a.dds"}), json!({"path": "b.dds", "ddsCompression": "bc1", "ddsMipmaps": true})] { - let r = call(&mut app, &ctx, "app.save", params.clone()); - assert_eq!(r["result"]["path"], params["path"], "{r}"); - assert!(app.dds_options.is_none(), "automation saves never prompt"); - } - assert_eq!(*asked.borrow(), [DdsOptions::default(), DdsOptions { compression: DdsCompression::Bc1, mipmaps: true }]); - let r = call(&mut app, &ctx, "app.save", json!({"path": "c.dds", "ddsCompression": "bc9"})); - assert!(r["error"].as_str().unwrap().contains("ddsCompression"), "{r}"); - assert_eq!(asked.borrow().len(), 2, "a bad ddsCompression writes nothing"); - } - - #[test] - fn automation_open_and_save_use_the_roots_and_reply_with_warnings() { - use photocraft_color::{ColorMode, SampleType}; - use photocraft_doc::Document; - use photocraft_geom::Size; - use std::cell::RefCell; - use std::rc::Rc; - - // Without granted roots both fail closed, even with an exporter and an ambient writer. - let services = crate::Services { - export: Some(Box::new(|_d: &Document, _p: &str, _s: &crate::ExportSettings| Ok((b"out".to_vec(), Vec::new())))), - write: Some(Box::new(|_p: &str, _b: &[u8]| Err("ambient writer used".into()))), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - let ctx = egui::Context::default(); - let r = call(&mut app, &ctx, "app.open", json!({"path": "in/warn.psd"})); - assert!(r.to_string().contains("automation read authority is not configured"), "{r}"); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - let r = call(&mut app, &ctx, "app.save", json!({"path": "out.png"})); - assert!(r.to_string().contains("automation write authority is not configured"), "{r}"); - - let written: Rc>> = Rc::default(); - let w = written.clone(); - let services = crate::Services { - import: Some(Box::new(|name: &str, _b: &[u8], _opts: &photocraft_io::ImportOptions| { - Ok((Document::new(name, Size::new(4, 4), ColorMode::Rgb, SampleType::U8), vec!["Adjustment layer flattened".to_string()])) - })), - export: Some(Box::new(|_d: &Document, _p: &str, _s: &crate::ExportSettings| Ok((b"out".to_vec(), vec!["Layers were flattened".to_string()])))), - automation_read: Some(Box::new(|path: &str| Ok((path.rsplit('/').next().unwrap_or(path).to_string(), b"x".to_vec())))), - automation_write: Some(Box::new(move |path: &str, _b: &[u8]| { - w.borrow_mut().push(path.to_string()); - Ok(()) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - let r = call(&mut app, &ctx, "app.open", json!({"path": "in/warn.psd"})); - assert_eq!(r["result"]["warnings"], json!(["Adjustment layer flattened"]), "{r}"); - assert_eq!(r["result"]["name"], "warn.psd"); - assert_eq!(app.session.active().unwrap().path.as_deref(), Some("in/warn.psd")); - assert_eq!(app.ui.recent_files, vec!["in/warn.psd".to_string()]); - let r = call(&mut app, &ctx, "app.save", json!({"path": "out.png"})); - assert_eq!(r["result"], json!({"path": "out.png", "warnings": ["Layers were flattened"]}), "{r}"); - assert_eq!(*written.borrow(), vec!["out.png".to_string()]); - // A flat export is a copy: the document keeps its name and file (#2579). - let st = app.session.active().unwrap(); - assert_eq!((st.doc.name.as_str(), st.path.as_deref()), ("warn.psd", Some("in/warn.psd"))); - // Without `path`, only a layered file is written back, like File › Save (#416). - call(&mut app, &ctx, "app.open", json!({"path": "in/flat.jpg"})); - let r = call(&mut app, &ctx, "app.save", json!({})); - assert!(r["error"].as_str().unwrap().contains("pass `path`"), "{r}"); - assert_eq!(written.borrow().len(), 1, "nothing written over the JPEG"); - call(&mut app, &ctx, "app.open", json!({"path": "in/layered.psd"})); - let r = call(&mut app, &ctx, "app.save", json!({})); - assert_eq!(r["result"]["path"], "in/layered.psd", "{r}"); - assert_eq!(written.borrow().last().map(String::as_str), Some("in/layered.psd")); - // A template opens untitled, so a save without `path` never writes over it. - let r = call(&mut app, &ctx, "app.open", json!({"path": "in/card.psdt"})); - assert_eq!(r["result"]["name"], "Untitled-1", "{r}"); - assert_eq!(app.session.active().unwrap().path, None); - let r = call(&mut app, &ctx, "app.save", json!({})); - assert!(r["error"].as_str().unwrap().contains("pass `path`"), "{r}"); - } - - fn deny_ambient_file(id: &str, _: &serde_json::Value) -> photocraft_engine::Result<()> { - if id.starts_with("file.") && id != "file.new" { - Err(photocraft_engine::EngineError::Other(format!("automation command `{id}` is disabled"))) - } else { - Ok(()) - } - } - - /// An app whose automation gates refuse file commands, with a document open, and the paths - /// its writer was asked to write. - fn gated_app_recording_writes() -> (PhotocraftApp, egui::Context, std::rc::Rc>>, u64) { - let written: std::rc::Rc>> = std::rc::Rc::default(); - let w = written.clone(); - let services = crate::Services { - automation_authorize: Some(deny_ambient_file), - automation_command: Some(Box::new(|id, params| deny_ambient_file(id, params).map_err(|e| e.to_string()))), - export: Some(Box::new(|_: &photocraft_doc::Document, _: &str, _: &crate::ExportSettings| Ok((b"out".to_vec(), Vec::new())))), - write: Some(Box::new(move |path: &str, _: &[u8]| { - w.borrow_mut().push(path.to_string()); - Ok(()) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - app.background_jobs = false; - app.session.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); - let doc = app.session.active().unwrap().doc.id.0; - (app, egui::Context::default(), written, doc) - } - - fn outside_target() -> String { - std::env::temp_dir().join("outside").join("x.png").to_string_lossy().into_owned() - } - - /// `ui.dialog.set` and `ui.dialog.open` never add a marker that picks a dialog's OK handler: - /// a View › Zoom In dialog can't be made to confirm as the disk-change prompt's save. - #[test] - fn automation_cannot_add_a_marker_that_reroutes_a_dialog() { - let (mut app, ctx, written, doc) = gated_app_recording_writes(); - let target = outside_target(); - let r = call(&mut app, &ctx, "ui.dialog.open", json!({"kind": "command", "command": "view.zoomIn"})); - let dialog = r["result"]["dialog"].clone(); - for (field, value) in [("document", json!(doc)), ("path", json!(target)), ("flat", json!(false))] { - let r = call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": dialog, "field": field, "value": value})); - assert!(r.get("error").is_none(), "{r}"); - } - let injected = call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": dialog, "field": "__diskChanged", "value": true})); - let replace = call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": dialog, "field": "__replaceSaved", "value": true})); - assert!(replace["error"].as_str().is_some_and(|e| e.contains("set only by the dialog")), "{replace}"); - call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": dialog})); - assert!(written.borrow().is_empty(), "nothing is written: {:?}", written.borrow()); - assert!(injected["error"].as_str().is_some_and(|e| e.contains("set only by the dialog")), "{injected}"); - let r = call(&mut app, &ctx, "ui.dialog.open", json!({"kind": "about", "fields": {"__export": true}})); - assert!(r["error"].as_str().is_some_and(|e| e.contains("set only by the dialog")), "{r}"); - } - - /// A handler that writes files itself (the disk-change prompt's save) is judged as the file - /// command it stands for, through a control request or synthetic input alike. - #[test] - fn automation_confirming_a_file_writing_dialog_is_judged_as_its_file_command() { - let (mut app, ctx, written, doc) = gated_app_recording_writes(); - let target = outside_target(); - // A real disk-change prompt keeps its own fields settable, but its save is a file command. - let fields = json!({"__diskChanged": true, "__label": "Save", "message": "", "document": doc, "path": target, "flat": false}); - let prompt = app.ui.open_dialog(DialogKind::Command, fields.as_object().cloned().unwrap()); - let r = call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": prompt, "field": "__diskChanged", "value": true})); - assert!(r.get("error").is_none(), "{r}"); - let r = call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": prompt})); - assert!(written.borrow().is_empty(), "nothing is written: {:?}", written.borrow()); - assert!(r["error"].as_str().is_some_and(|e| e.contains("file.save")), "{r}"); - // Synthetic input (Enter or OK) reaches the same handler without the control pre-check. - let synthetic = app.ui.open_dialog(DialogKind::Command, fields.as_object().cloned().unwrap()); - app.automation_input = true; - let r = crate::dialogs::confirm(&mut app, synthetic); - app.automation_input = false; - assert!(written.borrow().is_empty(), "nothing is written: {:?}", written.borrow()); - assert!(r.is_err_and(|e| e.contains("file.save"))); - } - - #[test] - fn app_open_opens_a_directory_pcraft_and_falls_back_for_the_zip_form() { - use photocraft_doc::Document; - use serde_json::json; - let services = crate::Services { - automation_open_pcraft: Some(Box::new(|path: &str| { - if path == "native.pcraft" { - let name = path.rsplit('/').next().unwrap_or(path).to_string(); - let doc = Document::new("Native", photocraft_doc::Size::new(16, 12), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); - Ok(Some((name, doc))) - } else if path == "zipped.pcraft" { - Ok(None) // a regular file: the bytes path reads the zip form - } else { - Err(format!("corrupt bundle: {path}")) - } - })), - import: Some(Box::new(|name: &str, _b: &[u8], _opts: &photocraft_io::ImportOptions| { - Ok((Document::new(name, photocraft_doc::Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8), Vec::new())) - })), - automation_read: Some(Box::new(|path: &str| { - if path == "zipped.pcraft" { - Ok((path.rsplit('/').next().unwrap_or(path).to_string(), b"zip-bytes".to_vec())) - } else { - Err(format!("no such path: {path}")) - } - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - let ctx = egui::Context::default(); - - let r = call(&mut app, &ctx, "app.open", json!({"path": "native.pcraft"})); - assert_eq!(r["result"], json!({"path": "native.pcraft", "name": "native.pcraft", "warnings": []}), "{r}"); - assert_eq!(app.session.active().unwrap().doc.name, "Native"); - assert_eq!(app.ui.recent_files, vec!["native.pcraft".to_string()], "the open is recorded in recent files"); - assert_eq!(app.session.active().unwrap().path, None, "no save-back target: the automation writer replaces files, never directories"); - let r = call(&mut app, &ctx, "app.save", json!({})); - assert!(r["error"].as_str().unwrap().contains("pass `path`"), "an in-place save is refused up front: {r}"); - - // The single-file form takes the bytes path through the same `.pcraft` extension. - let r = call(&mut app, &ctx, "app.open", json!({"path": "zipped.pcraft"})); - assert_eq!(r["result"]["name"], "zipped.pcraft", "{r}"); - assert_eq!(app.session.active().unwrap().doc.name, "zipped.pcraft", "the import served the zip form"); - - // A real opener error propagates instead of being masked by the fallback. - let r = call(&mut app, &ctx, "app.open", json!({"path": "gone.pcraft"})); - assert!(r["error"].as_str().unwrap().contains("corrupt bundle"), "{r}"); - } - - #[test] - fn app_save_runs_as_a_background_job_and_the_final_reply_carries_the_path() { - use photocraft_engine::automate_cmds::ScriptBinding; - use serde_json::json; - let saved: std::sync::Arc>> = Default::default(); - let record = saved.clone(); - let services = crate::Services { - automation_save: Some(std::sync::Arc::new(move |_doc, path: &str, _settings, _ctl| { - record.lock().unwrap().push(path.to_string()); - Ok(vec!["Layers were flattened".to_string()]) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - app.background_jobs = true; - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - // A "Save Document" binding that would leave a trace: automation saves never fire it. - app.session.edit_prefs(|prefs| { - prefs.script_events.enabled = true; - prefs.script_events.bindings = vec![ScriptBinding { - event: "saveDocument".into(), - script: None, - steps: Some(json!([["layer.new.layer", {"name": "From the binding"}]])), - name: "Binding".into(), - }]; - }); - let ctx = egui::Context::default(); - let (tx, rx) = std::sync::mpsc::channel(); - let app = app.with_control(rx); - let mut app = app; - - let (mut req, reply) = ControlRequest::new("app.save", json!({"path": "out.psd"})); - req.deadline = None; - tx.send(req).unwrap(); - app.drain_control(&ctx); - // Started in the background: no reply yet, the job is on the document. - assert!(reply.try_recv().is_err(), "the reply waits for the save job"); - assert!(app.saving(), "the save runs as a background job"); - for _ in 0..100 { - crate::jobs_ui::tick(&mut app, &ctx); - if !app.saving() { - break; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - assert!(!app.saving(), "the save finished"); - assert_eq!(*saved.lock().unwrap(), vec!["out.psd".to_string()]); - assert_eq!(app.session.active().unwrap().path.as_deref(), Some("out.psd"), "the save was recorded"); - assert_eq!(app.session.active().unwrap().doc.layer_count(), 1, "the saveDocument binding did not run for an automation save"); - let r = reply.recv().unwrap(); - assert_eq!(r["result"], json!({"path": "out.psd", "warnings": ["Layers were flattened"]}), "{r}"); - - // An interactive save (File › Save's worker) still fires the binding. - let save = std::sync::Arc::new(|_doc: &photocraft_doc::Document, path: &str, _settings: &crate::ExportSettings, _ctl: &crate::jobs_ui::SaveCtl| { - let _ = path; - Ok(Vec::new()) - }) as crate::SaveFileFn; - crate::jobs_ui::start_save(&mut app, "user.psd".into(), crate::ExportSettings::default(), false, save, false).unwrap(); - for _ in 0..100 { - crate::jobs_ui::tick(&mut app, &ctx); - if !app.saving() { - break; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - assert!(!app.saving(), "the interactive save finished"); - assert_eq!(app.session.active().unwrap().doc.layer_count(), 2, "the binding runs for an interactive save"); - } - - #[test] - fn ui_inspect_replies_while_a_save_job_encodes() { - // #2488: the control channel must keep answering while a large save runs. - use serde_json::json; - let gate = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let wait_for_gate = gate.clone(); - let saved: std::sync::Arc>> = Default::default(); - let record = saved.clone(); - let services = crate::Services { - automation_save: Some(std::sync::Arc::new(move |_doc, path: &str, _settings, ctl| { - while !wait_for_gate.load(std::sync::atomic::Ordering::Acquire) { - ctl.check()?; - std::thread::sleep(std::time::Duration::from_millis(2)); - } - record.lock().unwrap().push(path.to_string()); - Ok(Vec::new()) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - app.background_jobs = true; - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - let ctx = egui::Context::default(); - let (tx, rx) = std::sync::mpsc::channel(); - let app = app.with_control(rx); - let mut app = app; - - let (mut save_req, save_reply) = ControlRequest::new("app.save", json!({"path": "out.png", "wait": false})); - save_req.deadline = None; - tx.send(save_req).unwrap(); - let (mut inspect_req, inspect_reply) = ControlRequest::new("ui.inspect", json!({})); - inspect_req.deadline = None; - tx.send(inspect_req).unwrap(); - app.drain_control(&ctx); - - let pending = save_reply.recv_timeout(std::time::Duration::from_secs(5)).expect("the unwaited save replies at once"); - assert_eq!(pending["result"]["pending"], true, "{pending}"); - assert_eq!(pending["result"]["path"], "out.png", "{pending}"); - assert!(pending["result"]["job"].is_u64(), "the caller can poll or wait: {pending}"); - // While the save is still encoding, the channel answers other requests. - assert!(saved.lock().unwrap().is_empty(), "the save is still encoding"); - let inspected = inspect_reply.recv_timeout(std::time::Duration::from_secs(5)).expect("ui.inspect is not blocked by the save"); - assert_eq!(inspected["ok"], true, "{inspected}"); - - gate.store(true, std::sync::atomic::Ordering::Release); - for _ in 0..500 { - crate::jobs_ui::tick(&mut app, &ctx); - if !app.saving() { - break; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - assert_eq!(*saved.lock().unwrap(), vec!["out.png".to_string()], "the save completed after the gate opened"); - } - - fn deny_smart_object_paths(id: &str, params: &Value) -> photocraft_engine::Result<()> { - // The production policy lives in the automation crate. This gate exercises the control - // session's state-derived path check without adding that dependency to the UI crate. - if matches!(id, "layer.smartObjects.editContents" | "layer.smartObjects.convertToLayers" | "layer.smartObjects.saveContents") - && params.get("path").and_then(Value::as_str).is_some() - { - Err(photocraft_engine::EngineError::Other("ambient smart-object path denied".into())) - } else { - Ok(()) - } - } - - fn smart_control_app() -> (PhotocraftApp, egui::Context, photocraft_doc::LayerId) { - let services = crate::Services { - automation_authorize: Some(deny_smart_object_paths), - automation_command: Some(Box::new(|id, params| deny_smart_object_paths(id, params).map_err(|e| e.to_string()))), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - app.run("file.new", json!({"width": 8, "height": 6, "background": "transparent"})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - let id = app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap(); - (app, egui::Context::default(), photocraft_doc::LayerId(id)) - } - - #[test] - fn control_edits_nested_embedded_smart_objects_and_converts_an_explicit_target() { - use photocraft_doc::{LayerContent, SmartSource}; - use std::cell::RefCell; - use std::rc::Rc; - use std::sync::Arc; - - let (mut app, ctx, smart) = smart_control_app(); - // Embed this one-smart-layer document inside the outer object: two Edit Contents - // requests must reach the raster layer, as in a nested product-photo template. - let nested = photocraft_engine::smart_cmds::encode_source(&app.session.active().unwrap().doc).unwrap(); - app.session - .edit("Nested fixture", |doc, _| { - let LayerContent::Smart(sm) = &mut doc.layer_mut(smart).unwrap().content else { panic!("smart fixture") }; - sm.source = SmartSource::Embedded { file_name: "product.pcraft".into(), bytes: Arc::new(nested) }; - Ok(()) - }) - .unwrap(); - let other = app.run("layer.new.layer", json!({"name": "Unrelated"})).unwrap()["layer"].as_u64().unwrap(); - assert_ne!(app.session.active().unwrap().active_layer, Some(smart)); - for expected_document in [1, 2] { - let r = call(&mut app, &ctx, "engine.execute", json!({"command": "layer.smartObjects.editContents", "params": {"layer": smart.0}})); - assert_eq!(r["ok"], true, "{r}"); - assert_eq!(r["result"]["document"], expected_document, "{r}"); - assert!(app.session.active().unwrap().path.is_none(), "contents open in memory"); - assert!(app.session.authorize.is_none(), "the request gate must not remain installed"); - } - let r = call(&mut app, &ctx, "engine.execute", json!({"command": "edit.fill", "params": {"color": "#0000ff"}})); - assert_eq!(r["ok"], true, "{r}"); - for expected_documents in [2, 1] { - let r = call(&mut app, &ctx, "engine.execute", json!({"command": "layer.smartObjects.saveContents"})); - assert_eq!(r["ok"], true, "{r}"); - let r = call(&mut app, &ctx, "engine.execute", json!({"command": "file.close"})); - assert_eq!(r["ok"], true, "{r}"); - assert_eq!(app.session.documents().len(), expected_documents); - } - assert_eq!(app.session.active().unwrap().active_layer, Some(photocraft_doc::LayerId(other))); - assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px[0], [0.0, 0.0, 1.0, 1.0]); - let r = call(&mut app, &ctx, "engine.execute", json!({"command": "layer.smartObjects.convertToLayers", "params": {"layer": smart.0}})); - assert_eq!(r["ok"], true, "{r}"); - assert!(app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(other)).is_some(), "the unrelated active layer remains"); - assert!(app.session.authorize.is_none()); - - let written = Rc::new(RefCell::new(Vec::new())); - let output = written.clone(); - app.services.export = - Some(Box::new(|doc, _, _| photocraft_engine::smart_cmds::encode_source(doc).map(|bytes| (bytes, Vec::new())).map_err(|e| e.to_string()))); - app.services.automation_write = Some(Box::new(move |path, bytes| { - output.borrow_mut().push((path.to_string(), bytes.to_vec())); - Ok(()) - })); - app.services.write = Some(Box::new(|_, _| Err("ambient writer used".into()))); - let r = call(&mut app, &ctx, "app.save", json!({"path": "out/template.pcraft"})); - assert_eq!(r["ok"], true, "{r}"); - let written = written.borrow(); - assert_eq!(written.len(), 1); - assert_eq!(written[0].0, "out/template.pcraft"); - let saved = photocraft_engine::smart_cmds::decode_source(&written[0].0, &written[0].1).unwrap(); - assert_eq!(photocraft_compose::flatten(&saved).px[0], [0.0, 0.0, 1.0, 1.0]); - } - - #[test] - fn control_refuses_linked_smart_objects_in_commands_and_actions_but_local_editing_still_works() { - use photocraft_doc::{LayerContent, SmartSource}; - use std::sync::Arc; - - let (mut app, ctx, smart) = smart_control_app(); - let path = std::env::temp_dir().join(format!("pc-control-smart-linked-{}.pcraft", std::process::id())); - let st = app.session.active().unwrap(); - let LayerContent::Smart(sm) = &st.doc.layer(smart).unwrap().content else { panic!("smart fixture") }; - let SmartSource::Embedded { bytes, .. } = &sm.source else { panic!("embedded fixture") }; - std::fs::write(&path, bytes.as_slice()).unwrap(); - app.session - .edit("Linked fixture", |doc, _| { - let LayerContent::Smart(sm) = &mut doc.layer_mut(smart).unwrap().content else { panic!("smart fixture") }; - sm.source = SmartSource::Linked { path: path.to_string_lossy().into_owned() }; - Ok(()) - }) - .unwrap(); - app.run("layer.new.layer", json!({"name": "Unrelated"})).unwrap(); - let before = app.session.active().unwrap().doc.clone(); - let active = app.session.active().unwrap().active_layer; - for command in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers"] { - let r = call(&mut app, &ctx, "engine.execute", json!({"command": command, "params": {"layer": smart.0}})); - assert_eq!(r["ok"], false, "{r}"); - assert!(r["error"].as_str().unwrap().contains("ambient smart-object path denied"), "{r}"); - app.session.actions.list = vec![photocraft_engine::actions_cmds::Action { - name: "Linked contents".into(), - steps: vec![(command.into(), json!({"layer": smart.0}))], - disabled: Default::default(), - ..Default::default() - }]; - let r = call(&mut app, &ctx, "engine.execute", json!({"command": "actions.play", "params": {"action": "Linked contents"}})); - assert_eq!(r["ok"], true, "{r}"); - assert_eq!(r["result"]["ran"], 0, "{r}"); - assert_eq!(r["result"]["failed"]["id"], command, "{r}"); - assert_eq!(app.session.documents().len(), 1); - assert!(Arc::ptr_eq(&app.session.active().unwrap().doc, &before), "a refused operation must not edit the document"); - assert_eq!(app.session.active().unwrap().active_layer, active); - assert!(app.session.authorize.is_none(), "a refused request must restore the local session"); - } - // A synthetic thumbnail action uses the same temporary authorization as control calls. - app.automation_input = true; - let error = crate::menus::invoke(&mut app, &ctx, "layer.smartObjects.editContents", json!({"layer": smart.0})).unwrap_err(); - assert!(error.contains("ambient smart-object path denied"), "{error}"); - assert!(app.session.authorize.is_none()); - app.automation_input = false; - app.run("layer.smartObjects.editContents", json!({"layer": smart.0})).unwrap(); - assert_eq!(app.session.documents().len(), 2, "a human can still open the existing linked file"); - assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px[0], [1.0, 0.0, 0.0, 1.0]); - std::fs::remove_file(path).unwrap(); - } - - #[test] - fn actions_play_checks_each_step_over_control() { - let services = crate::Services { automation_authorize: Some(deny_ambient_file), ..Default::default() }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - app.session.actions.list.push(photocraft_engine::actions_cmds::Action { - name: "Open".into(), - steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - let ctx = egui::Context::default(); - let r = call(&mut app, &ctx, "engine.execute", json!({"command": "actions.play", "params": {"action": "Open"}})); - assert_eq!(r["ok"], true, "{r}"); - assert_eq!(r["result"]["ran"], 0, "{r}"); - assert_eq!(r["result"]["failed"]["id"], "file.open", "{r}"); - assert!(r["result"]["failed"]["error"].as_str().unwrap_or("").contains("disabled"), "{r}"); - assert!(app.session.documents().is_empty()); - assert!(app.session.authorize.is_none(), "the per-step gate is only installed for the request"); - } - - #[test] - fn actions_play_checks_each_step_for_synthetic_input() { - let services = crate::Services { automation_authorize: Some(deny_ambient_file), ..Default::default() }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - app.session.actions.list.push(photocraft_engine::actions_cmds::Action { - name: "Open".into(), - steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))], - disabled: Default::default(), - ..Default::default() - }); - app.automation_input = true; - let r = app.run("actions.play", json!({"action": "Open"})).unwrap(); - assert_eq!(r["ran"], 0, "{r}"); - assert_eq!(r["failed"]["id"], "file.open", "{r}"); - assert!(app.session.authorize.is_none(), "the per-step gate is only installed for the command"); - - // A local play (no automation input) still runs recorded steps. - app.automation_input = false; - app.session.actions.list[0].steps.remove(0); - app.session.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); - let r = app.run("actions.play", json!({"action": "Open"})).unwrap(); - assert_eq!(r["ran"], 1, "{r}"); - } - - #[test] - fn huge_click_count_is_rejected() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - // #982: a huge count used to queue a press and a release per click before replying. - for count in [json!(MAX_CLICKS + 1), json!(1_000_000_000u64), json!(u64::MAX)] { - let r = call(&mut app, &ctx, "ui.click", json!({"x": 10, "y": 10, "count": count})); - assert_eq!(r["ok"], false, "{r}"); - assert!(r["error"].as_str().unwrap().contains("`count` must be at most 256"), "{r}"); - assert!(app.synthetic.is_empty(), "a rejected click queues nothing"); - } - // Single, double and the largest allowed clicks still queue a move plus a press and a release each. - for (count, events) in [(None, 3), (Some(2), 5), (Some(MAX_CLICKS), 2 * MAX_CLICKS as usize + 1)] { - let params = match count { - Some(n) => json!({"x": 10, "y": 10, "count": n}), - None => json!({"x": 10, "y": 10}), - }; - let (req, _rx) = ControlRequest::new("ui.click", params); - assert!(matches!(handle(&mut app, &ctx, &req), Outcome::AfterInput)); - assert_eq!(app.synthetic.len(), events); - app.synthetic.clear(); - } - } - - /// #2449: the error of a rejected synthetic input call, after checking it changed nothing. - fn rejected(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value, names: &str) -> String { - let (tool, revision) = (app.ui.tool, app.session.active().map(|d| d.revision)); - let r = call(app, ctx, method, params.clone()); - assert_eq!(r["ok"], false, "{method} {params}: {r}"); - let error = r["error"].as_str().unwrap().to_string(); - assert!(error.contains(names), "{method} {params}: `{error}` should name `{names}`"); - assert!(app.synthetic.is_empty(), "{method} {params}: a rejected call queues nothing"); - assert_eq!(app.ui.tool, tool, "{method} {params}: a rejected call keeps the tool"); - assert_eq!(app.session.active().map(|d| d.revision), revision, "{method} {params}: a rejected call edits nothing"); - error - } - - #[test] - fn ui_pointer_rejects_bad_params_before_acting() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); - let stroke = json!([{"kind": "down", "x": 5, "y": 5}, {"kind": "move", "x": 30, "y": 30}, {"kind": "up", "x": 30, "y": 30}]); - // The same unknown tool is the same error as `ui.set`'s. - let set = call(&mut app, &ctx, "ui.set", json!({"tool": "noSuchTool"})); - let error = rejected(&mut app, &ctx, "ui.pointer", json!({"tool": "noSuchTool", "events": stroke}), "noSuchTool"); - assert_eq!(json!(error), set["error"]); - let event = |extra: Value| { - let mut e = json!({"kind": "down", "x": 5, "y": 5}); - e.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); - // A valid stroke first: a later bad event must not let the earlier ones run. - json!({"tool": "move", "events": [stroke[0], stroke[1], stroke[2], e]}) - }; - let cases = [ - // Unknown fields, top-level, under `modifiers` and in an event. - (json!({"tol": "move", "events": stroke}), "tol"), - (json!({"modifiers": {"shfit": true}, "events": stroke}), "shfit"), - (event(json!({"presure": 0.5})), "presure"), - // Wrong JSON types. - (json!({"tool": 3, "events": stroke}), "tool"), - (json!({"events": "down"}), "events"), - (json!({}), "events"), - (json!({"events": [5]}), "events[0]"), - (event(json!({"x": "abc"})), "x"), - (event(json!({"y": true})), "y"), - (event(json!({"kind": 1})), "kind"), - (json!({"shift": "yes", "events": stroke}), "shift"), - (json!({"modifiers": {"alt": 1}, "events": stroke}), "alt"), - (json!({"modifiers": true, "events": stroke}), "modifiers"), - (json!({"button": 2, "events": stroke}), "button"), - (json!([1, 2]), "params"), - // Values outside the accepted set. - (json!({"button": "ritgh", "events": stroke}), "button"), - (event(json!({"kind": "dwon"})), "kind"), - // Numbers outside their documented range. - (event(json!({"pressure": 99})), "pressure"), - (event(json!({"pressure": -0.1})), "pressure"), - (event(json!({"tiltX": 91})), "tiltX"), - (event(json!({"tiltY": -90.5})), "tiltY"), - (event(json!({"rotation": 361})), "rotation"), - (event(json!({"rotation": -1})), "rotation"), - ]; - for (params, names) in cases { - rejected(&mut app, &ctx, "ui.pointer", params, names); - } - let error = rejected(&mut app, &ctx, "ui.pointer", json!({"button": "ritgh", "events": stroke}), "button"); - assert!(error.contains("right") && error.contains("secondary"), "the error lists the buttons: {error}"); - let error = rejected(&mut app, &ctx, "ui.pointer", event(json!({"kind": "dwon"})), "kind"); - assert!(error.contains("down") && error.contains("move") && error.contains("up"), "the error lists the kinds: {error}"); - - // Valid calls still run: an omitted kind is a move, null is an omitted field, and the - // documented range ends are accepted. - let before = app.session.active().unwrap().revision; - let pen = json!({"kind": "down", "x": 5, "y": 5, "pressure": 0, "tiltX": -90, "tiltY": 90, "rotation": 360}); - let valid = json!({"tool": "brush", "button": null, "modifiers": {"shift": false}, "events": [pen, {"x": 20, "y": 20, "pressure": 1}, {"kind": "up", "x": 20, "y": 20}]}); - let r = call(&mut app, &ctx, "ui.pointer", valid); - assert_eq!(r["ok"], true, "{r}"); - assert_eq!(app.ui.tool, Tool::Brush); - assert!(app.session.active().unwrap().revision > before, "the stroke painted"); - for button in ["left", "middle", "right", "secondary"] { - let r = call( - &mut app, - &ctx, - "ui.pointer", - json!({"tool": "move", "button": button, "events": [{"kind": "down", "x": 5, "y": 5}, {"kind": "up", "x": 5, "y": 5}]}), - ); - assert_eq!(r["ok"], true, "{button}: {r}"); - } - assert!(app.ui.layer_menu.is_some(), "a right click with Move still opens the layer menu"); - } - - #[test] - fn ui_click_and_move_reject_bad_params_before_queueing_input() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let cases = [ - ("ui.click", json!({"x": 10, "y": 10, "buton": "right"}), "buton"), - ("ui.move", json!({"x": 10, "y": 10, "count": 2}), "count"), - ("ui.click", json!({"x": "abc", "y": 10}), "x"), - ("ui.move", json!({"x": 10, "y": [10]}), "y"), - ("ui.click", json!({"x": 10, "y": 10, "count": "dos"}), "count"), - ("ui.click", json!({"x": 10, "y": 10, "count": 1.5}), "count"), - ("ui.click", json!({"x": 10, "y": 10, "count": -1}), "count"), - ("ui.click", json!({"x": 10, "y": 10, "button": true}), "button"), - ("ui.click", json!({"x": 10, "y": 10, "button": "ritgh"}), "button"), - ("ui.click", json!({"x": 10, "y": 10, "count": MAX_CLICKS + 1}), "count"), - ("ui.click", json!("click"), "params"), - ]; - for (method, params, names) in cases { - rejected(&mut app, &ctx, method, params, names); - } - let error = rejected(&mut app, &ctx, "ui.click", json!({"x": 10, "y": 10, "button": "ritgh"}), "button"); - assert!(error.contains("left") && error.contains("right") && error.contains("middle"), "the error lists the buttons: {error}"); - // Valid calls queue what they did before; an omitted button is a left click. - for (method, params, button, events) in [ - ("ui.click", json!({"x": 10, "y": 10}), egui::PointerButton::Primary, 3), - ("ui.click", json!({"x": 10, "y": 10, "button": "right", "count": 2}), egui::PointerButton::Secondary, 5), - ("ui.click", json!({"x": 10, "y": 10, "button": "secondary"}), egui::PointerButton::Secondary, 3), - ("ui.click", json!({"x": 10.5, "y": 10, "button": "middle", "count": null}), egui::PointerButton::Middle, 3), - ("ui.move", json!({"x": 10, "y": 10}), egui::PointerButton::Primary, 1), - ] { - let (req, _rx) = ControlRequest::new(method, params.clone()); - assert!(matches!(handle(&mut app, &ctx, &req), Outcome::AfterInput), "{method} {params}"); - assert_eq!(app.synthetic.len(), events, "{method} {params}"); - if let Some(egui::Event::PointerButton { button: queued, .. }) = app.synthetic.get(1) { - assert_eq!(*queued, button, "{method} {params}"); - } - app.synthetic.clear(); - } - } - - #[test] - fn ui_key_rejects_bad_params_before_queueing_input() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let cases = [ - (json!({"key": "N", "ctl": true}), "ctl"), - (json!({"key": "N", "modifiers": {"space": true}}), "space"), - (json!({"key": "N", "ctrl": "yes"}), "ctrl"), - (json!({"key": "N", "modifiers": {"shift": 1}}), "shift"), - (json!({"key": "N", "modifiers": "ctrl"}), "modifiers"), - (json!({"key": 5}), "key"), - (json!({}), "key"), - (json!({"key": "NoSuchKey"}), "NoSuchKey"), - ]; - for (params, names) in cases { - rejected(&mut app, &ctx, "ui.key", params, names); - } - for params in [json!({"key": "N", "ctrl": true}), json!({"key": "N", "shift": false, "modifiers": {"ctrl": true}})] { - let (req, _rx) = ControlRequest::new("ui.key", params.clone()); - assert!(matches!(handle(&mut app, &ctx, &req), Outcome::AfterInput), "{params}"); - assert!(matches!(app.synthetic.first(), Some(egui::Event::Key { key: egui::Key::N, modifiers, .. }) if modifiers.ctrl), "{params}"); - app.synthetic.clear(); - } - } - - #[test] - fn ui_screenshot_rejects_bad_params_before_capturing() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - for (params, names) in [(json!({"focus": "yes"}), "focus"), (json!({"path": 5}), "path"), (json!({"pth": "shot.png"}), "pth")] { - rejected(&mut app, &ctx, "ui.screenshot", params, names); - } - for (params, path) in [(json!({}), None), (Value::Null, None), (json!({"path": "shot.png", "focus": false}), Some("shot.png"))] { - let (req, _rx) = ControlRequest::new("ui.screenshot", params.clone()); - let Outcome::Screenshot { path: queued, .. } = handle(&mut app, &ctx, &req) else { panic!("{params}: expected a capture") }; - assert_eq!(queued.as_deref(), path, "{params}"); - } - } - - /// A key event's modifiers, as `ui.key` queued them. - fn key_modifiers(app: &mut PhotocraftApp, ctx: &egui::Context, params: Value) -> egui::Modifiers { - app.synthetic.clear(); - let (req, _rx) = ControlRequest::new("ui.key", params.clone()); - assert!(matches!(handle(app, ctx, &req), Outcome::AfterInput), "{params}"); - match app.synthetic.first() { - Some(egui::Event::Key { modifiers, .. }) => *modifiers, - other => panic!("{params}: expected a key event, got {other:?}"), - } - } - - #[test] - fn ui_key_ctrl_reaches_shortcuts_like_a_real_ctrl_press() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let ctrl = key_modifiers(&mut app, &ctx, json!({"key":"N","ctrl":true})); - let command = key_modifiers(&mut app, &ctx, json!({"key":"N","command":true})); - let grouped = key_modifiers(&mut app, &ctx, json!({"key":"N","modifiers":{"ctrl":true}})); - assert_eq!(ctrl, grouped, "a grouped flag must match the top-level one"); - if cfg!(target_os = "macos") { - // Two different keys: Control is not ⌘, and only ⌘ matches a shortcut. - assert!(ctrl.ctrl && !ctrl.command && !ctrl.mac_cmd, "{ctrl:?}"); - assert!(command.command && command.mac_cmd && !command.ctrl, "{command:?}"); - } else { - // One key under two names, and shortcuts are matched on `command`, so asking for - // either must reach them: Ctrl+N has to open New Document, not do nothing. - assert_eq!(ctrl, command, "ctrl and command are the same key off the Mac"); - assert!(ctrl.command && ctrl.ctrl && !ctrl.mac_cmd, "{ctrl:?}"); - } - let plain = key_modifiers(&mut app, &ctx, json!({"key":"N"})); - assert_eq!(plain, egui::Modifiers::default(), "{plain:?}"); - let shift_alt = key_modifiers(&mut app, &ctx, json!({"key":"N","shift":true,"alt":true})); - assert!(shift_alt.shift && shift_alt.alt && !shift_alt.command && !shift_alt.ctrl, "{shift_alt:?}"); - } - - /// FILE-215-3: `filterMaskTarget` on a layer without a filter mask is refused before anything - /// changes, so the layer mask stays targeted. - #[test] - fn ui_set_filter_mask_target_needs_a_smart_object_with_filters() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"maskTarget": true}))["ok"], true); - let bad = call(&mut app, &ctx, "ui.set", json!({"filterMaskTarget": true})); - assert_eq!(bad["ok"], false, "{bad}"); - assert!(app.ui.mask_target, "the layer mask stays targeted"); - assert_eq!(app.ui.filter_mask_target, None); - // A smart object with smart filters takes it. - app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - app.run("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); - // Not while a single colour channel is targeted: nothing would end up targeted. - app.session.active_mut().unwrap().channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Color(0); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"filterMaskTarget": true}))["ok"], false); - app.session.active_mut().unwrap().channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Composite; - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"filterMaskTarget": true}))["ok"], true); - assert!(app.filter_mask_targeted()); - // Untargeting it ends its view, which would otherwise keep it targeted. - app.run("paint.stroke", json!({"points": [[4, 4]], "size": 4, "hardness": 1, "color": "#000000", "target": "filterMask"})).unwrap(); - app.run("view.layerMask", json!({"mode": "gray", "mask": "filter"})).unwrap(); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"filterMaskTarget": false}))["ok"], true); - assert!(!app.filter_mask_targeted()); - assert!(photocraft_engine::mask_view_cmds::current(app.session.active().unwrap()).is_none()); - // Targeting the pixels untargets it too. - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"filterMaskTarget": true}))["ok"], true); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"maskTarget": false}))["ok"], true); - assert!(!app.filter_mask_targeted()); - assert_eq!(crate::canvas::paint_target(&app), json!("pixels")); - } - - /// FILE-215-3: with the filter mask shown (⌥-click its thumbnail), targeting the layer mask - /// ends that view, and the brush paints the layer mask. - #[test] - fn ui_set_mask_target_ends_a_filter_mask_view() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); - app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - app.run("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - app.run("paint.stroke", json!({"points": [[4, 4]], "size": 4, "hardness": 1, "color": "#000000", "target": "filterMask"})).unwrap(); - app.run("view.layerMask", json!({"mode": "gray", "mask": "filter"})).unwrap(); - app.sync_mask_targets(); - assert!(app.filter_mask_targeted()); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"maskTarget": true}))["ok"], true); - assert!(photocraft_engine::mask_view_cmds::current(app.session.active().unwrap()).is_none(), "the filter mask view ends"); - assert!(app.layer_mask_targeted()); - assert!(!app.filter_mask_targeted()); - assert_eq!(crate::canvas::paint_target(&app), json!("mask")); - let target = crate::canvas::paint_target(&app); - app.run("paint.stroke", json!({"points": [[20, 20]], "size": 4, "hardness": 1, "color": "#000000", "target": target})).unwrap(); - let st = app.session.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); - assert_eq!(l.mask.as_ref().unwrap().value(20, 20), 0.0, "the stroke went into the layer mask"); - let photocraft_doc::LayerContent::Smart(sm) = &l.content else { panic!("smart object") }; - assert_eq!(sm.filter_mask.as_ref().unwrap().value(20, 20), 1.0, "not into the filter mask"); - } -} +mod tests; diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs new file mode 100644 index 0000000000..c7b9896e2f --- /dev/null +++ b/crates/ui-egui/src/control/tests.rs @@ -0,0 +1,2054 @@ +use super::*; + +fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { + let (req, _rx) = ControlRequest::new(method, params); + match handle(app, ctx, &req) { + Outcome::Done(v) => v, + _ => panic!("{method}: expected an immediate reply"), + } +} + +#[test] +fn ui_set_turns_the_stroke_trace_on_and_off_at_runtime() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + assert!(!app.stroke_trace.enabled()); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"strokeTrace": true}))["ok"], true); + assert!(app.stroke_trace.enabled()); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"strokeTrace": "off"}))["ok"], true); + assert!(!app.stroke_trace.enabled()); + let bad = call(&mut app, &ctx, "ui.set", json!({"strokeTrace": 3, "tool": "Pencil"})); + assert_eq!(bad["ok"], false); + // A file path isn't accepted over the channel (it would write outside the automation + // write root); nothing is created. + let path = std::env::temp_dir().join(format!("photocraft-trace-{}.csv", std::process::id())); + let bad = call(&mut app, &ctx, "ui.set", json!({"strokeTrace": path.to_str().unwrap(), "tool": "Pencil"})); + assert_eq!(bad["ok"], false); + assert!(!path.exists()); + assert!(!app.stroke_trace.enabled() && app.ui.tool != crate::state::Tool::Pencil, "a rejected call applies nothing"); +} + +#[test] +fn camera_raw_control_updates_and_commits_or_cancels_an_open_raw() { + use photocraft_raw::testgen::{DngSpec, mosaic, scene}; + let (w, h) = (48, 32); + let mut spec = DngSpec::cfa(w, h, mosaic(&scene(w, h), w, [0, 1, 1, 2], 0, 30000)); + spec.as_shot_neutral = Some([0.5, 1.0, 0.7]); + let dng = spec.build(); + for finish in ["commit", "cancel"] { + let services = crate::Services { + import: Some(Box::new(|name, bytes, opts| { + photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, Default::default()); + app.open_bytes("control.dng", &dng).unwrap(); + ctx.run_ui(Default::default(), |ui| crate::camera_raw_ui::show(&mut app, ui.ctx())).textures_delta.clear(); + assert!(app.camera_raw.is_some()); + // A developed raw has no embedded profile to ask about (`open_prompt`), so no profile + // prompt stands between the open and the Camera Raw dialog. + assert!(app.ui.dialogs.is_empty()); + let update = json!({"id":"filter.cameraRaw","params":{"ui":{"set":{"exposure":0.5}}}}); + let original = app.session.active().unwrap().doc.clone(); + let changed = call(&mut app, &ctx, "ui.menu.invoke", update.clone()); + let undone = call(&mut app, &ctx, "ui.menu.invoke", json!({"id":"filter.cameraRaw","params":{"ui":{"undo":true}}})); + assert_eq!(undone["result"]["params"]["exposure"], 0.0, "{undone}"); + let redone = call(&mut app, &ctx, "ui.menu.invoke", json!({"id":"filter.cameraRaw","params":{"ui":{"redo":true}}})); + assert_eq!(redone["result"]["params"]["exposure"], 0.5, "{redone}"); + assert_eq!(changed["ok"], true, "{changed}"); + assert_eq!(changed["result"]["params"]["exposure"], 0.5); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original), "a preview must not commit"); + assert!(!crate::menus::modal_allows(&app, "filter.cameraRaw"), "native menu clicks stay blocked"); + let finished = call(&mut app, &ctx, "ui.menu.invoke", json!({"id":"filter.cameraRaw","params":{"ui":{finish:true}}})); + assert_eq!(finished["ok"], true, "{finished}"); + assert!(app.camera_raw.is_none()); + if finish == "commit" { + assert_eq!(finished["result"]["redeveloped"], true, "{finished}"); + assert_eq!(app.session.documents().len(), 1); + let st = app.session.active().unwrap(); + assert_ne!(st.doc.id, original.id); + assert_eq!(st.doc.depth, photocraft_color::SampleType::U16); + assert_eq!(st.saved_revision, st.revision); + } else { + assert_eq!(finished["result"]["cancelled"], true); + assert!(app.session.documents().is_empty()); + } + } +} + +#[test] +fn camera_raw_control_continuation_does_not_bypass_other_modal_or_command_gates() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width":16,"height":16})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color":"#808080"})).unwrap(); + let opened = call(&mut app, &ctx, "ui.menu.invoke", json!({"id":"filter.cameraRaw"})); + assert_eq!(opened["ok"], true, "{opened}"); + let original = app.session.active().unwrap().doc.clone(); + let cancel = json!({"id":"filter.cameraRaw","params":{"ui":{"cancel":true}}}); + for request in [ + json!({"id":"file.new"}), + json!({"id":"view.zoomIn"}), + json!({"id":"filter.cameraRaw"}), + json!({"id":"filter.cameraRaw","params":{"exposure":1}}), + json!({"id":"filter.cameraRaw","params":{"ui":null}}), + json!({"id":"filter.cameraRaw","params":{"ui":{},"smartFilter":{"layer":1,"index":0}}}), + ] { + let blocked = call(&mut app, &ctx, "ui.menu.invoke", request); + assert_eq!(blocked["ok"], false, "{blocked}"); + } + app.ui.open_dialog(DialogKind::About, Default::default()); + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", cancel.clone())["ok"], false); + app.ui.dialogs.clear(); + assert!(crate::discard_ui::intercept(&mut app, "file.close", &json!({}))); + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", cancel.clone())["ok"], false); + app.discard = None; + app.ui.tool = Tool::Crop; + app.ui.crop_rect = Some([1.0, 1.0, 10.0, 10.0]); + assert!(crate::crop_ui::blocks(&app, "filter.cameraRaw")); + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", cancel.clone())["ok"], false); + app.ui.crop_rect = None; + app.services.automation_command = Some(Box::new(|id, _| if id == "filter.cameraRaw" { Err("Camera Raw denied".into()) } else { Ok(()) })); + for ui in [json!({"set":{"exposure":1}}), json!({"commit":true}), json!({"cancel":true})] { + let denied = call(&mut app, &ctx, "ui.menu.invoke", json!({"id":"filter.cameraRaw","params":{"ui":ui}})); + assert_eq!(denied["ok"], false, "{denied}"); + assert_eq!(denied["error"], "Camera Raw denied"); + } + assert_eq!(app.camera_raw.as_ref().unwrap().params.exposure, 0.0); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &original)); + app.services.automation_command = None; + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", cancel)["ok"], true); + assert!(app.camera_raw.is_none()); +} + +#[test] +fn full_window_workspaces_are_modal_for_menu_invocations() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width":32,"height":32})).unwrap(); + app.run("file.new", json!({"width":32,"height":32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color":"#808080"})).unwrap(); + app.run("select.rect", json!({"x":8,"y":8,"width":8,"height":8})).unwrap(); + for workspace in ["filter.liquify", "edit.contentAwareFill", "filter.filterGallery", "filter.adaptiveWideAngle"] { + let opened = call(&mut app, &ctx, "ui.menu.invoke", json!({"id":workspace})); + assert_eq!(opened["ok"], true, "{workspace}: {opened}"); + assert_eq!(crate::distort_ui::modal_workspace(&app), Some(workspace)); + let doc = app.session.active().unwrap().doc.id; + for request in [ + json!({"id":"window.document.0"}), + json!({"id":"select.all"}), + json!({"id":"view.zoomIn"}), + json!({"id":"filter.cameraRaw"}), + json!({"id":workspace,"params":{"ui":null}}), + ] { + let blocked = call(&mut app, &ctx, "ui.menu.invoke", request.clone()); + assert_eq!(blocked["ok"], false, "{workspace}: {request} → {blocked}"); + assert!(!crate::menus::modal_allows(&app, request["id"].as_str().unwrap()), "{workspace}: native menu greys {request}"); + } + let listed = call(&mut app, &ctx, "ui.menu.list", json!({})); + let enabled = |id: &str| listed["result"].as_array().unwrap().iter().find(|it| it["id"] == id).map(|it| it["enabled"].clone()); + assert_eq!(enabled("select.all"), Some(json!(false)), "{workspace}: ui.menu.list greys what invoke refuses"); + assert_eq!(crate::distort_ui::modal_workspace(&app), Some(workspace), "{workspace} stays open with its work"); + assert_eq!(app.session.active().unwrap().doc.id, doc); + // An open dialog still takes precedence over the workspace's own requests. + app.ui.open_dialog(DialogKind::About, Default::default()); + let cancel = json!({"id":workspace,"params":{"ui":{"cancel":true}}}); + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", cancel.clone())["ok"], false); + app.ui.dialogs.clear(); + let cancelled = call(&mut app, &ctx, "ui.menu.invoke", cancel); + assert_eq!(cancelled["ok"], true, "{workspace}: {cancelled}"); + assert_eq!(crate::distort_ui::modal_workspace(&app), None); + assert!(crate::menus::modal_allows(&app, "select.all"), "{workspace}: menus are free again"); + let listed = call(&mut app, &ctx, "ui.menu.list", json!({})); + assert!( + listed["result"].as_array().unwrap().iter().any(|it| it["id"] == "select.all" && it["enabled"] == true), + "{workspace}: listed as enabled again" + ); + } + // engine.execute stays programmatic: it is not a menu click. + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id":"filter.liquify"}))["ok"], true); + let executed = call(&mut app, &ctx, "engine.execute", json!({"command":"select.all"})); + assert_eq!(executed["ok"], true, "{executed}"); +} + +#[test] +fn layer_style_picker_control_binds_previews_confirms_and_cancels() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width":16,"height":16})).unwrap(); + let parent = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"layerStyle","effect":"gradientOverlay"}))["result"]["dialog"].as_u64(); + let parent = parent.unwrap(); + let before = app.ui.dialogs[0].fields.clone(); + for field in ["from", "to"] { + let reply = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","parent":parent,"effect":"fx1","field":field})); + assert_eq!(reply["ok"], true, "{reply}"); + let picker = app.ui.dialogs.last().unwrap().id; + let inspected = call(&mut app, &ctx, "ui.inspect", json!({})); + assert!(inspected.to_string().contains("__layerStyleColor")); + assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog":parent}))["ok"], false); + assert_eq!(call(&mut app, &ctx, "ui.dialog.set", json!({"dialog":picker,"field":"color","value":"#123456"}))["ok"], true); + assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog":picker}))["ok"], true); + assert_eq!(app.ui.dialogs[0].fields["effects"][0]["params"][field], "#123456"); + } + assert_ne!(app.ui.dialogs[0].fields, before); + call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","parent":parent,"effect":"fx1","field":"to"})); + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog":parent}))["ok"], true); + assert!(app.ui.dialogs.is_empty()); +} + +#[test] +fn text_style_picker_control_uses_bound_target_and_rejects_invalid_requests_atomically() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width":32,"height":32})).unwrap(); + let id = app.run("type.characterStyle.new", json!({"fromSelection":false,"attrs":{"color":"#123456"}})).unwrap()["id"].as_u64().unwrap(); + for style in [ + Value::Null, + json!({"kind":"wrong","id":id}), + json!({"kind":"character","id":"bad"}), + json!({"kind":"paragraph","id":u64::MAX}), + json!({"kind":"character","id":0}), + json!({"kind":"character","id":id,"extra":1}), + ] { + let panels = app.ui.type_panels.clone(); + assert_eq!(call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","textStyle":style}))["ok"], false); + assert_eq!(app.ui.type_panels, panels); + assert!(app.ui.dialogs.is_empty()); + } + assert_eq!(call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","textStyle":{"kind":"character","id":id},"parent":1}))["ok"], false); + let doc = app.session.active().unwrap().doc.clone(); + let r = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","textStyle":{"kind":"character","id":id}})); + assert_eq!(r["ok"], true); + let picker = r["result"]["dialog"].as_u64().unwrap(); + assert_eq!(app.ui.dialogs[0].fields["__textStyleColor"]["id"], id); + assert_eq!(call(&mut app, &ctx, "ui.dialog.set", json!({"dialog":picker,"field":"color","value":"#00ff00"}))["ok"], true); + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog":picker}))["ok"], true); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &doc)); + let r = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"colorPicker","textStyle":{"kind":"character","id":id}})); + let picker = r["result"]["dialog"].as_u64().unwrap(); + call(&mut app, &ctx, "ui.dialog.set", json!({"dialog":picker,"field":"color","value":"#00ff00"})); + assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog":picker}))["ok"], true); + assert_ne!(app.session.active().unwrap().doc.text_styles, doc.text_styles); +} + +#[test] +fn layer_style_picker_control_rejects_bad_targets_without_opening_tool_picker() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width":16,"height":16})).unwrap(); + let parent = crate::layer_style::open(&mut app, Some("colorOverlay")).unwrap(); + for params in [ + json!({"kind":"colorPicker","parent":null,"effect":"fx1","field":"color"}), + json!({"kind":"colorPicker","parent":"bad","effect":"fx1","field":"color"}), + json!({"kind":"colorPicker","parent":parent,"effect":3,"field":"color"}), + json!({"kind":"colorPicker","parent":parent,"effect":"missing","field":"color"}), + json!({"kind":"colorPicker","parent":parent,"effect":"fx1","field":"opacity"}), + json!({"kind":"colorPicker","parent":parent,"effect":"fx1","field":"to"}), + json!({"kind":"colorPicker","effect":"fx1","field":"color"}), + ] { + let before = app.ui.dialogs.clone(); + assert_eq!(call(&mut app, &ctx, "ui.dialog.open", params)["ok"], false); + assert_eq!(app.ui.dialogs, before); + } +} + +#[test] +fn shape_stroke_defaults_are_drivable_and_validate_atomically() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let result = + call(&mut app, &ctx, "ui.set", json!({"tool":"Triangle", "shapeStroke":{"width":5,"cap":"round","join":"bevel","dashes":[0,2,4,1],"dashOffset":-0.5}})); + assert_eq!(result["ok"], true); + assert_eq!(app.ui.tool_options.stroke_width, 5.0); + assert_eq!(app.ui.tool_options.shape_stroke.dashes, [0.0, 2.0, 4.0, 1.0]); + let before = app.ui.clone(); + let bad = call(&mut app, &ctx, "ui.set", json!({"tool":"Rectangle","shapeStroke":{"dashes":[0,0]}})); + assert_eq!(bad["ok"], false); + assert_eq!(app.ui, before); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"shapeStroke":{"colour":"#ff0000"}}))["ok"], false); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"shapeStroke":null}))["ok"], true); + assert_eq!(app.ui.tool_options.stroke_width, 0.0); +} + +#[test] +fn the_unsaved_changes_prompt_is_listed_and_answered_through_ui_dialog() { + // #4920: the prompt shown on quit or close with unsaved changes wasn't in ui.inspect, and a + // control client couldn't answer it. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + for _ in 0..2 { + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + } + let prompt = |app: &mut PhotocraftApp| { + let v = call(app, &ctx, "ui.inspect", json!({})); + v["result"]["dialogs"].as_array().unwrap().iter().find(|d| d["id"] == "discard").cloned() + }; + assert!(prompt(&mut app).is_none()); + // Closing a dirty document: listed with its choices; a bad choice and Cancel keep the document. + crate::menus::invoke(&mut app, &ctx, "file.close", json!({})).unwrap(); + let d = prompt(&mut app).expect("the prompt is listed"); + assert_eq!(d["fields"]["command"], "file.close"); + assert_eq!(d["fields"]["choices"], json!(["save", "dontSave", "cancel"])); + assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "maybe"}))["ok"], false); + assert_eq!(call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": "discard", "field": "x", "value": 1}))["ok"], false); + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"}))["ok"], true); + assert!(prompt(&mut app).is_none() && app.session.documents().len() == 2); + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"}))["ok"], false, "nothing left to answer"); + // Don't Save closes it. + crate::menus::invoke(&mut app, &ctx, "file.close", json!({})).unwrap(); + assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "dontSave"}))["ok"], true); + assert_eq!(app.session.documents().len(), 1); + // Quitting asks about each dirty document, then lets the window close. + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + assert!(crate::discard_ui::intercept(&mut app, "file.exit", &Value::Null)); + let d = prompt(&mut app).expect("the quit prompt is listed"); + assert_eq!((d["fields"]["command"].as_str(), d["fields"]["remaining"].as_u64()), (Some("file.exit"), Some(2))); + assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "dontSave"}))["result"]["open"], true); + assert_eq!(prompt(&mut app).unwrap()["fields"]["remaining"], 1); + assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "dontSave"}))["result"]["open"], false); + assert!(app.allow_close && app.session.documents().is_empty()); +} + +#[test] +fn shell_dialogs_are_listed_and_driven_through_ui_dialog() { + // #1004: Window › Workspace and View dialogs live in `ui.shell.dialog`, and ui.inspect and + // ui.dialog.* only knew `ui.dialogs`. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let shell = |app: &mut PhotocraftApp| { + let v = call(app, &ctx, "ui.inspect", json!({})); + v["result"]["dialogs"].as_array().unwrap().iter().find(|d| d["id"] == "shell").cloned() + }; + // Listed, then cancelled. + crate::menus::invoke(&mut app, &ctx, "window.workspace.newWorkspace", json!({})).unwrap(); + let d = shell(&mut app).expect("the open shell dialog is listed"); + assert_eq!((d["kind"].as_str(), d["title"].as_str()), (Some("newWorkspace"), Some("New Workspace"))); + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "shell"}))["ok"], true); + assert!(app.ui.shell.dialog.is_none() && shell(&mut app).is_none()); + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "shell"}))["ok"], false, "nothing left to cancel"); + // A field set over control reaches OK. + crate::menus::invoke(&mut app, &ctx, "view.show.showExtrasOptions", json!({})).unwrap(); + assert!(app.ui.view.show.notes); + assert_eq!(call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": "shell", "field": "notes", "value": false}))["ok"], true); + assert_eq!(shell(&mut app).unwrap()["fields"]["notes"], false); + assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "shell"}))["ok"], true); + assert!(!app.ui.view.show.notes && app.ui.shell.dialog.is_none()); + // An OK that fails keeps the dialog open and says why. + crate::menus::invoke(&mut app, &ctx, "view.show.showExtrasOptions", json!({})).unwrap(); + call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": "shell", "field": "bogus", "value": true})); + let r = call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "shell"})); + assert_eq!(r["ok"], false); + assert!(r["error"].as_str().unwrap_or("").contains("bogus"), "{r}"); + assert!(app.ui.shell.dialog.is_some()); + // Apply is Preferences-only; numeric ids still address ordinary dialogs only. + assert_eq!(call(&mut app, &ctx, "ui.dialog.apply", json!({"dialog": "shell"}))["ok"], false); + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": 0}))["ok"], false); + assert!(app.ui.shell.dialog.is_some()); +} + +#[test] +fn opening_new_document_through_control_matches_clipboard_image_size() { + // #2034: every way of opening New Document uses the clipboard-aware initial fields. + let clipboard = std::sync::Arc::new(std::sync::Mutex::new(Some((100, 200, vec![255; 100 * 200 * 4])))); + let image = clipboard.clone(); + let mut app = PhotocraftApp::new( + photocraft_engine::Session::new(), + crate::Services { clipboard_get_image: Some(Box::new(move || Ok(image.lock().unwrap().clone()))), ..Default::default() }, + ); + let ctx = egui::Context::default(); + let opened = call(&mut app, &ctx, "ui.dialog.open", json!({"kind":"newDocument"})); + assert_eq!(opened["ok"], true); + let id = opened["result"]["dialog"].as_u64().expect("dialog id is returned"); + let fields = &app.ui.dialog_mut(id).expect("dialog was opened").fields; + assert_eq!((fields["width"].as_u64(), fields["height"].as_u64()), (Some(100), Some(200))); + assert_eq!(fields["__preset"], "Clipboard"); +} + +#[test] +fn expired_queued_edit_does_not_run_and_a_live_retry_runs_once() { + use std::time::{Duration, Instant}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let before = app.session.active().unwrap(); + let layers = before.doc.layers.len(); + let steps = before.history.past_len(); + let (tx, rx) = std::sync::mpsc::channel(); + app = app.with_control(rx); + let (mut expired, expired_reply) = ControlRequest::new("engine.execute", json!({"command": "layer.new.layer"})); + expired.deadline = Some(Instant::now() - Duration::from_secs(1)); + tx.send(expired).unwrap(); + let (mut retry, retry_reply) = ControlRequest::new("engine.execute", json!({"command": "layer.new.layer"})); + retry.deadline = Some(Instant::now() + Duration::from_secs(60)); + tx.send(retry).unwrap(); + app.drain_control(&egui::Context::default()); + let expired_error = expired_reply.try_recv().unwrap()["error"].as_str().unwrap().to_string(); + assert_eq!(retry_reply.try_recv().unwrap()["ok"], true); + let after = app.session.active().unwrap(); + assert_eq!(after.doc.layers.len(), layers + 1, "only the live retry adds a layer"); + assert_eq!(after.history.past_len(), steps + 1, "the expired edit adds no undo step"); + // #3662: a caller must be able to tell this reply, safe to re-send, from the + // transport's, sent while the command may still apply. + assert!(expired_error.starts_with("timeout"), "machines match on the prefix: {expired_error}"); + assert!(expired_error.contains("not run"), "the expired request says it never ran: {expired_error}"); + let transport_error = super::timeout_error(); + assert!(!transport_error.contains("not run"), "the transport can't know it didn't run: {transport_error}"); + assert!(transport_error.contains("may still apply"), "the transport warns against a blind re-send: {transport_error}"); +} + +#[test] +fn a_transport_that_gives_up_learns_whether_the_command_can_still_run() { + // #3662: the transport's clock runs out no later than the UI thread's, so it is the + // one that answers; it must still tell a request that will never run from one that may. + use std::time::{Duration, Instant}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let layers = app.session.active().unwrap().doc.layers.len(); + let (tx, rx) = std::sync::mpsc::channel(); + app = app.with_control(rx); + let ctx = egui::Context::default(); + let request = |deadline: Instant| { + let (mut req, reply) = ControlRequest::new("engine.execute", json!({"command": "layer.new.layer"})); + req.deadline = Some(deadline); + (req.dispatch.clone(), req, reply) + }; + + let (dispatch, queued, _) = request(Instant::now() + Duration::from_secs(60)); + tx.send(queued).unwrap(); + assert_eq!(dispatch.give_up(), super::expired_error(), "still queued: it will not run"); + app.drain_control(&ctx); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "a request given up on never runs"); + + let (dispatch, expired, _) = request(Instant::now() - Duration::from_secs(1)); + tx.send(expired).unwrap(); + app.drain_control(&ctx); + assert_eq!(dispatch.give_up(), super::expired_error(), "rejected by the UI thread: it did not run"); + + let (dispatch, live, reply) = request(Instant::now() + Duration::from_secs(60)); + tx.send(live).unwrap(); + app.drain_control(&ctx); + assert_eq!(reply.try_recv().unwrap()["ok"], true); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1); + assert_eq!(dispatch.give_up(), super::timeout_error(), "dispatched: it may still apply"); +} + +#[test] +fn timeout_errors_name_the_likely_causes() { + // #2489: the reply must tell "wait" from "check the machine", and its number + // must come from the deadline it reports. + let error = super::timeout_error(); + assert!(error.starts_with("timeout"), "machines match on the prefix"); + assert!(error.contains(&format!("{}s", super::REPLY_DEADLINE.as_secs())), "the text matches the deadline: {error}"); + assert!(error.contains("may still be running"), "the wait-it-out cause"); + assert!(error.contains("display asleep"), "the check-the-display cause"); + assert!(error.contains("frame"), "the frame-loop cause"); +} + +#[test] +fn deadline_free_requests_run_even_after_the_receiver_is_dropped() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let layers = app.session.active().unwrap().doc.layers.len(); + let (tx, rx) = std::sync::mpsc::channel(); + app = app.with_control(rx); + let (req, reply) = ControlRequest::new("engine.execute", json!({"command": "layer.new.layer"})); + assert!(req.deadline.is_none()); + drop(reply); + tx.send(req).unwrap(); + app.drain_control(&egui::Context::default()); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1); +} + +#[test] +fn right_pointer_opens_agent_visible_selection_menu() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("select.rect", json!({"x": 1, "y": 1, "width": 8, "height": 8})).unwrap(); + let result = call( + &mut app, + &ctx, + "ui.pointer", + json!({ + "tool": "RectMarquee", "button": "secondary", + "events": [{"kind": "down", "x": 4, "y": 4}, {"kind": "up", "x": 4, "y": 4}] + }), + ); + assert_eq!(result.get("ok"), Some(&Value::Bool(true))); + let inspected = call(&mut app, &ctx, "ui.inspect", json!({})); + let entries = inspected.pointer("/result/canvasToolMenu/entries").and_then(Value::as_array).unwrap(); + assert!(entries.iter().any(|entry| entry.get("id") == Some(&json!("select.inverse")) && entry.get("enabled") == Some(&json!(true)))); + assert!(app.session.active().unwrap().doc.selection.is_some(), "right-click must not edit selection"); +} + +#[test] +fn agent_right_click_with_the_zoom_tool_opens_and_runs_the_view_menu() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.sync_views(); + let result = + call(&mut app, &ctx, "ui.pointer", json!({"tool": "Zoom", "button": "secondary", "events": [{"kind":"down","x":8,"y":8},{"kind":"up","x":8,"y":8}]})); + assert_eq!(result["ok"], true); + assert_eq!(app.ui.canvas_tool_menu.as_ref().and_then(|m| m.anchor), Some([8.0, 8.0])); + let inspected = call(&mut app, &ctx, "ui.inspect", json!({})); + let entries = inspected.pointer("/result/canvasToolMenu/entries").and_then(Value::as_array).unwrap(); + let ids: Vec<_> = entries.iter().filter_map(|row| row.get("id").and_then(Value::as_str)).collect(); + assert_eq!(ids, ["view.fitOnScreen", "view.fillScreen", "view.actualPixels", "view.twoHundredPercent", "view.printSize", "view.zoomIn", "view.zoomOut"]); + assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id":"select.all"}))["ok"], false); + assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id":"view.twoHundredPercent"}))["ok"], true); + assert_eq!(app.ui.views[0].zoom, 2.0); + assert!(app.ui.canvas_tool_menu.is_none()); +} + +/// #6561: an agent's right-click on a pending crop opens the crop menu, as on the canvas. +#[test] +fn agent_right_click_on_a_pending_crop_opens_and_runs_the_crop_menu() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.sync_views(); + app.ui.tool = crate::state::Tool::Crop; + app.ui.tool_options.crop_shield.classic_mode = true; + app.ui.extras.snap = false; + crate::crop_ui::ensure_frame(&mut app); + tool_event(&mut app, ToolEvent::Down { x: 4.0, y: 4.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 16.0, y: 12.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 28.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 28.0, y: 20.0 }, egui::Modifiers::NONE); + let frame = app.ui.crop_rect.unwrap(); + let result = call( + &mut app, + &ctx, + "ui.pointer", + json!({"tool": "Crop", "button": "secondary", "events": [{"kind":"down","x":16,"y":12},{"kind":"up","x":16,"y":12}]}), + ); + assert_eq!(result["ok"], true); + let inspected = call(&mut app, &ctx, "ui.inspect", json!({})); + assert_eq!(inspected.pointer("/result/canvasToolMenu/crop"), Some(&json!(true))); + let entries = inspected.pointer("/result/canvasToolMenu/entries").and_then(Value::as_array).unwrap(); + assert!(entries.iter().any(|row| row.get("id") == Some(&json!("crop.commit")) && row.get("enabled") == Some(&json!(true)))); + assert_eq!(app.ui.crop_rect, Some(frame), "the right-click leaves the frame alone"); + assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id":"crop.commit"}))["ok"], true); + let size = app.session.active().unwrap().doc.size; + assert_eq!([f64::from(size.width), f64::from(size.height)], [frame[2] - frame[0], frame[3] - frame[1]], "cropped to the frame"); +} + +/// An agent's right-click while its own crop frame drag is still down opens no menu over it; +/// after the drag's release it does. +#[test] +fn agent_right_click_during_its_crop_drag_opens_no_menu() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.sync_views(); + app.ui.tool = crate::state::Tool::Crop; + app.ui.tool_options.crop_shield.classic_mode = true; + app.ui.extras.snap = false; + crate::crop_ui::ensure_frame(&mut app); + let pointer = |app: &mut PhotocraftApp, button: &str, events: Value| { + assert_eq!(call(app, &ctx, "ui.pointer", json!({"tool": "Crop", "button": button, "events": events}))["ok"], true); + }; + // The first drag on the default frame (nothing pending yet): no pasteboard menu outside the image. + pointer(&mut app, "left", json!([{"kind":"down","x":4,"y":4},{"kind":"move","x":16,"y":12},{"kind":"move","x":28,"y":20}])); + assert!(app.crop.drag.is_some() && !crate::crop_ui::pending(&app), "the first frame is still being drawn"); + pointer(&mut app, "secondary", json!([{"kind":"down","x":-8,"y":-8},{"kind":"up","x":-8,"y":-8}])); + assert!(app.ui.canvas_tool_menu.is_none(), "no pasteboard menu over the first drag"); + pointer(&mut app, "left", json!([{"kind":"up","x":28,"y":20}])); + // A second drag, on the drawn frame, still down. + pointer(&mut app, "left", json!([{"kind":"down","x":16,"y":12},{"kind":"move","x":18,"y":14}])); + assert!(app.crop.drag.is_some() && crate::crop_ui::pending(&app), "the frame drag is still down"); + let right_click = json!([{"kind":"down","x":16,"y":12},{"kind":"up","x":16,"y":12}]); + pointer(&mut app, "secondary", right_click.clone()); + assert!(app.ui.canvas_tool_menu.is_none(), "no menu over the drag"); + pointer(&mut app, "left", json!([{"kind":"up","x":18,"y":14}])); + pointer(&mut app, "secondary", right_click.clone()); + assert!(app.ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_some()), "after the release it opens"); + // Nor over a Straighten line still being drawn. + app.ui.canvas_tool_menu = None; + crate::crop_straighten::toggle(&mut app); + pointer(&mut app, "left", json!([{"kind":"down","x":6,"y":6},{"kind":"move","x":20,"y":8}])); + assert!(app.crop.straighten.line.is_some(), "the Straighten line is still down"); + pointer(&mut app, "secondary", right_click); + assert!(app.ui.canvas_tool_menu.is_none(), "no menu over the Straighten line"); +} + +#[test] +fn agent_can_inspect_and_choose_pen_make_selection_from_full_context_menu() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("path.set", json!({"name":"work","path":{"subpaths":[{"closed":true,"knots":[[2,2],[20,2],[20,20]]}]}})).unwrap(); + let expected_pos = screen_point(&app, 8.0, 8.0); + let result = call( + &mut app, + &ctx, + "ui.pointer", + json!({ + "tool": "Pen", "button": "secondary", "events": [{"kind":"down","x":8,"y":8},{"kind":"up","x":8,"y":8}] + }), + ); + assert_eq!(result["ok"], true); + let inspected = call(&mut app, &ctx, "ui.inspect", json!({})); + assert_eq!(app.ui.canvas_tool_menu.as_ref().unwrap().pos, expected_pos); + let entries = inspected.pointer("/result/canvasToolMenu/entries").and_then(Value::as_array).unwrap(); + assert_eq!(entries.iter().filter(|row| row.get("separator") == Some(&json!(true))).count(), 9); + assert!(entries.iter().any(|row| row.get("id") == Some(&json!("path.toSelection")) && row.get("enabled") == Some(&json!(true)))); + assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id":"file.new"}))["ok"], false); + let chosen = call(&mut app, &ctx, "ui.context.choose", json!({"id":"path.toSelection"})); + assert_eq!(chosen["ok"], true); + let dialog = chosen["result"]["dialog"].as_u64().unwrap(); + assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog":dialog}))["ok"], true); + assert!(app.session.active().unwrap().doc.selection.is_some()); +} + +#[test] +fn ui_inspect_reports_the_view_preferences() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let before = call(&mut app, &ctx, "ui.inspect", json!({})); + assert_eq!(before.pointer("/result/view/show/selection_edges"), Some(&json!(true))); + assert_eq!(before.pointer("/result/view/screen_mode"), Some(&json!("standard"))); + assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "view.show.selectionEdges"}))["ok"], true); + let after = call(&mut app, &ctx, "ui.inspect", json!({})); + assert_eq!(after.pointer("/result/view/show/selection_edges"), Some(&json!(false))); + assert_eq!(after["result"]["view"], json!(app.ui.view)); +} + +#[test] +fn engine_execute_runs_with_defaults_but_menu_invoke_opens_the_dialog() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("edit.fill", json!({"color": "#808080"})).unwrap(); + let rev = app.session.active().unwrap().revision; + let r = call(&mut app, &ctx, "engine.execute", json!({"command": "filter.blur.gaussianBlur"})); + assert!(!r.to_string().contains("\"dialog\""), "engine.execute opened a dialog: {r}"); + assert!(app.session.active().unwrap().revision > rev, "engine.execute didn't run the filter"); + let rev = app.session.active().unwrap().revision; + let r = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "filter.blur.gaussianBlur"})); + assert!(r.to_string().contains("dialog"), "ui.menu.invoke should open the dialog: {r}"); + assert_eq!(app.session.active().unwrap().revision, rev, "opening a dialog must not edit the document"); +} + +#[test] +fn menu_invoke_cannot_edit_document_behind_an_open_dialog() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + + let opened = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "image.imageSize"})); + assert_eq!(opened["ok"], true, "{opened}"); + let dialog = opened["result"]["dialog"].as_u64().unwrap(); + let revision = app.session.active().unwrap().revision; + let before = call(&mut app, &ctx, "ui.inspect", json!({})); + let fields = before["result"]["dialogs"][0]["fields"].clone(); + + for params in [json!({"id": "image.imageRotation.90cw"}), json!({"id": "image.imageRotation.90cw", "params": {}})] { + let blocked = call(&mut app, &ctx, "ui.menu.invoke", params); + assert_eq!(blocked["ok"], false, "{blocked}"); + assert_eq!(app.session.active().unwrap().revision, revision); + let snapshot = call(&mut app, &ctx, "ui.inspect", json!({})); + assert_eq!(snapshot["result"]["dialogs"][0]["id"], dialog); + assert_eq!(snapshot["result"]["dialogs"][0]["fields"], fields); + } + + // View navigation stays permitted by the same policy as native menus and shortcuts. + assert!(crate::menus::modal_allows(&app, "view.zoomIn")); + assert!(!crate::menus::modal_allows(&app, "image.imageRotation.90cw")); + + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": dialog}))["ok"], true); + let rotated = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "image.imageRotation.90cw"})); + assert_eq!(rotated["ok"], true, "{rotated}"); + assert!(app.session.active().unwrap().revision > revision); +} + +#[test] +fn ui_set_rejects_unknown_fields_before_changing_anything() { + use crate::theme::ThemeKind; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.set_theme(&ctx, ThemeKind::StudioLight); + // `dark` was advertised to MCP clients but never read; a typo looked like success too. + for params in [json!({"dark": true}), json!({"thme": "classic"}), json!({"tool": "move", "dark": true})] { + let r = call(&mut app, &ctx, "ui.set", params.clone()); + assert_eq!(r["ok"], false, "{params}: {r}"); + assert!(r["error"].as_str().unwrap().contains("unknown field"), "{r}"); + } + assert_eq!(app.ui.theme, ThemeKind::StudioLight); + assert_eq!(app.ui.tool, Tool::Brush, "a rejected call applies none of its fields"); + // Every field the method reads gets past the check (a bad value is its own error). + for field in UI_SET_FIELDS { + let r = call(&mut app, &ctx, "ui.set", json!({ field: null })); + assert!(!r.to_string().contains("unknown field"), "{field}: {r}"); + } + assert_eq!(call(&mut app, &ctx, "ui.set", Value::Null)["ok"], true); +} + +#[test] +fn ui_set_gradient_blend_mode_validates_and_updates_options() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let good = call(&mut app, &ctx, "ui.set", json!({"tool": "gradient", "gradientBlendMode": "Difference", "gradientClassic": true})); + assert_eq!(good["ok"], true, "{good}"); + assert_eq!(app.ui.tool_options.gradient_blend_mode, photocraft_color::BlendMode::Difference); + assert!(app.ui.tool_options.gradient_classic); + let bad = call(&mut app, &ctx, "ui.set", json!({"gradientBlendMode": "nonsense", "gradientClassic": false})); + assert_eq!(bad["ok"], false, "{bad}"); + assert!(app.ui.tool_options.gradient_classic, "invalid mode must not change options"); +} + +/// #5048: the Layers panel filter is drivable; a bad field changes nothing. +#[test] +fn ui_set_drives_the_layers_panel_filter() { + use crate::layer_filter_ui::FilterBy; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let ok = call(&mut app, &ctx, "ui.set", json!({"layerFilter": {"by": "name", "name": "ink"}})); + assert_eq!(ok["ok"], true, "{ok}"); + assert_eq!((app.ui.layer_filter_by, app.ui.layer_filter_name.as_str()), (FilterBy::Name, "ink")); + let ok = call(&mut app, &ctx, "ui.set", json!({"layerFilter": {"by": "mode", "mode": "Pass Through", "kinds": ["type", "pixel", "type"]}})); + assert_eq!(ok["ok"], true, "{ok}"); + assert_eq!((app.ui.layer_filter_by, app.ui.layer_filter_mode), (FilterBy::Mode, photocraft_color::BlendMode::PassThrough)); + assert_eq!(app.ui.layer_filter, ["type", "pixel"], "kinds are kept once each"); + assert_eq!(app.ui.layer_filter_name, "ink", "fields left out keep their value"); + for bad in [ + json!({"layerFilter": "name"}), + json!({"layerFilter": {"by": "colour"}}), + json!({"layerFilter": {"kinds": ["pixels"]}}), + json!({"layerFilter": {"kinds": "pixel"}}), + json!({"layerFilter": {"name": 3}}), + json!({"layerFilter": {"mode": "Nonsense"}}), + json!({"layerFilter": {"by": "kind", "extra": true}}), + json!({"layerFilter": {"by": "kind"}, "tileGrid": "yes"}), + ] { + let r = call(&mut app, &ctx, "ui.set", bad.clone()); + assert_eq!(r["ok"], false, "{bad} → {r}"); + assert_eq!(app.ui.layer_filter_by, FilterBy::Mode, "{bad} changed nothing"); + } +} + +#[test] +fn ui_set_toggles_the_developer_tile_grid() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + assert!(!app.ui.view.tile_grid, "off by default"); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"tileGrid": true}))["ok"], true); + assert!(app.ui.view.tile_grid); + assert_eq!(call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["view"]["tile_grid"], true); + // Not a View › Show item: Extras doesn't hide it, and Show Extras Options doesn't list it. + crate::menus::invoke(&mut app, &ctx, "view.extras", json!({})).unwrap(); + assert!(!app.ui.view.extras && app.ui.view.tile_grid); + assert!(serde_json::to_value(app.ui.view.show).unwrap().get("tile_grid").is_none()); + let bad = call(&mut app, &ctx, "ui.set", json!({"tileGrid": "yes"})); + assert_eq!(bad["ok"], false, "{bad}"); + assert!(app.ui.view.tile_grid, "a rejected value changes nothing"); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"tileGrid": false}))["ok"], true); + assert!(!app.ui.view.tile_grid); +} + +#[test] +fn ui_set_drives_the_eyedropper_options() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let good = call( + &mut app, + &ctx, + "ui.set", + json!({"tool": "eyedropper", "eyedropperSampleSize": 11, "eyedropperSample": "currentAndBelow", "eyedropperRing": false}), + ); + assert_eq!(good["ok"], true, "{good}"); + let o = &app.ui.tool_options; + assert_eq!((o.eyedropper_size, o.eyedropper_sample.as_str(), o.eyedropper_ring), (11, "currentAndBelow", false)); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"eyedropperSampleSize": "point"}))["ok"], true); + assert_eq!(app.ui.tool_options.eyedropper_size, 1); + for bad in [ + json!({"eyedropperSampleSize": 4}), + json!({"eyedropperSampleSize": "big"}), + json!({"eyedropperSample": "below"}), + json!({"eyedropperSample": 2}), + json!({"eyedropperRing": "yes"}), + ] { + let r = call(&mut app, &ctx, "ui.set", bad.clone()); + assert_eq!(r["ok"], false, "{bad}: {r}"); + } + // A rejected call applies none of its fields. + let r = call(&mut app, &ctx, "ui.set", json!({"eyedropperSampleSize": 101, "eyedropperSample": "nope"})); + assert_eq!(r["ok"], false, "{r}"); + assert_eq!(app.ui.tool_options.eyedropper_size, 1); +} + +/// #1046: the Color Sampler tool is selectable over the control channel and reported as active. +#[test] +fn ui_set_selects_the_color_sampler_tool() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"tool": "colorSampler"}))["ok"], true); + assert_eq!(app.ui.tool, Tool::ColorSampler); + assert_eq!(call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["tool"], "ColorSampler"); + // The `I` key group cycles through the eyedropper tools, so the sampler is on the same key. + assert_eq!(Tool::ColorSampler.key(), 'I'); +} + +/// #3823: the Crop tool's Fill over the control channel, reported by `ui.inspect`. +#[test] +fn ui_set_drives_the_crop_fill() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"tool": "crop", "cropFill": "contentAware"}))["ok"], true); + assert!(app.ui.tool_options.crop_content_aware); + assert_eq!(call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["toolOptions"]["crop_content_aware"], true); + for bad in [json!("generativeExpand"), json!(true), json!(1)] { + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"cropFill": bad}))["ok"], false, "{bad}"); + assert!(app.ui.tool_options.crop_content_aware, "{bad}: unchanged"); + } + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"cropFill": "background"}))["ok"], true); + assert!(!app.ui.tool_options.crop_content_aware); +} + +/// #1919: the Crop tool's overlay menu over the control channel, reported by `ui.inspect`. +#[test] +fn ui_set_drives_the_crop_overlay_options() { + use crate::crop_overlay::{CropOverlay, OverlayShow}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let good = call(&mut app, &ctx, "ui.set", json!({"tool": "crop", "cropOverlay": "goldenSpiral", "cropOverlayShow": "always", "cropOverlayOrientation": 2})); + assert_eq!(good["ok"], true, "{good}"); + let o = &app.ui.tool_options; + assert_eq!((o.crop_overlay, o.crop_overlay_show, o.crop_overlay_orientation), (CropOverlay::GoldenSpiral, OverlayShow::Always, 2)); + let seen = call(&mut app, &ctx, "ui.inspect", json!({})); + let t = &seen["result"]["toolOptions"]; + assert_eq!( + (t["crop_overlay"].as_str(), t["crop_overlay_show"].as_str(), t["crop_overlay_orientation"].as_u64()), + (Some("goldenSpiral"), Some("always"), Some(2)) + ); + for bad in [ + json!({"cropOverlay": "spiral"}), + json!({"cropOverlay": 1}), + json!({"cropOverlayShow": "sometimes"}), + json!({"cropOverlayOrientation": 4}), + json!({"cropOverlayOrientation": -1}), + json!({"cropOverlayOrientation": "1"}), + json!({"cropOverlay": "grid", "cropOverlayShow": "nope"}), + ] { + let r = call(&mut app, &ctx, "ui.set", bad.clone()); + assert_eq!(r["ok"], false, "{bad}: {r}"); + } + assert_eq!(app.ui.tool_options.crop_overlay, CropOverlay::GoldenSpiral, "a rejected call applies none of its fields"); +} + +/// #1919: the Crop tool's gear menu (Show Cropped Area, crop shield) over the control channel. +#[test] +fn ui_set_drives_the_crop_shield_options() { + use crate::crop_shield::{CropShield, ShieldColor}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let good = call(&mut app, &ctx, "ui.set", json!({"cropShield": {"color": "custom", "custom_color": [255, 0, 0], "opacity": 40}})); + assert_eq!(good["ok"], true, "{good}"); + let want = CropShield { color: ShieldColor::Custom, custom_color: [255, 0, 0], opacity: 40.0, ..Default::default() }; + assert_eq!(app.ui.tool_options.crop_shield, want); + // A patch: the other fields stay. + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"cropShield": {"show_cropped_area": false}}))["ok"], true); + assert_eq!(app.ui.tool_options.crop_shield, CropShield { show_cropped_area: false, ..want.clone() }); + let t = &call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["toolOptions"]["crop_shield"]; + assert_eq!((t["color"].as_str(), t["opacity"].as_f64(), t["show_cropped_area"].as_bool()), (Some("custom"), Some(40.0), Some(false))); + for bad in [ + json!({"cropShield": true}), + json!({"cropShield": {"opacity": 101}}), + json!({"cropShield": {"opacity": -1}}), + json!({"cropShield": {"opacity": "50"}}), + json!({"cropShield": {"color": "red"}}), + json!({"cropShield": {"custom_color": [256, 0, 0]}}), + json!({"cropShield": {"shield": true}}), + json!({"cropShield": {"enabled": false}, "cropOverlay": "nope"}), + ] { + let r = call(&mut app, &ctx, "ui.set", bad.clone()); + assert_eq!(r["ok"], false, "{bad}: {r}"); + } + assert_eq!(app.ui.tool_options.crop_shield, CropShield { show_cropped_area: false, ..want }, "a rejected call applies none of its fields"); +} + +#[test] +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"); + 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])); + assert!(!app.ui.brush_picker_list.show_stroke); + for bad in [ + json!({"brushPicker": [1]}), + json!({"brushPicker": "here"}), + json!({"brushPickerStroke": "nope"}), + json!({"brushPickerName": false, "brushPickerStroke": false, "brushPickerTip": false}), + ] { + assert_eq!(call(&mut app, &ctx, "ui.set", bad.clone())["ok"], false, "{bad}"); + } + assert_eq!(app.ui.brush_picker, Some([120.0, 80.0]), "a bad value leaves the picker alone"); + assert!(app.ui.brush_picker_list.show_name, "a rejected call leaves the card parts alone"); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"brushPicker": null}))["ok"], true); + assert_eq!(app.ui.brush_picker, None); +} + +#[test] +fn ui_inspect_tracks_brush_picker_open_and_closed() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 128, "height": 128})).unwrap(); + + let closed = call(&mut app, &ctx, "ui.inspect", json!({})); + assert!(closed["result"]["brushPicker"].is_null()); + + // A right-click on the canvas with Brush opens the same picker as the options bar. + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"tool": "brush"}))["ok"], true); + let click = call( + &mut app, + &ctx, + "ui.pointer", + json!({ + "button": "right", + "events": [{"kind": "down", "x": 64, "y": 64}, {"kind": "up", "x": 64, "y": 64}] + }), + ); + assert_eq!(click["ok"], true, "{click}"); + let open = call(&mut app, &ctx, "ui.inspect", json!({})); + 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!(call(&mut app, &ctx, "ui.set", json!({"brushPickerTip": false}))["ok"], true); + let changed = call(&mut app, &ctx, "ui.inspect", json!({})); + assert_eq!(changed["result"]["brushPicker"]["list"]["showTip"], false); + + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"brushPicker": null}))["ok"], true); + let closed_again = call(&mut app, &ctx, "ui.inspect", json!({})); + assert!(closed_again["result"]["brushPicker"].is_null()); +} + +#[test] +fn ui_set_applies_all_fields_or_none() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let before = app.ui.tool; + let panels_before = serde_json::to_value(&app.ui.panels).unwrap_or_default(); + // A late invalid field must not leave the earlier valid one applied - including the + // journaled brush command, which is validated up front for exactly this reason. + for params in [json!({"tool": "move", "theme": "nope"}), json!({"tool": "move", "brushSize": 1e300}), json!({"tool": "move", "colorPanel": {"nope": true}})] + { + let r = call(&mut app, &ctx, "ui.set", params.clone()); + assert_eq!(r["ok"], false, "{params}: {r}"); + assert_eq!(app.ui.tool, before, "{params}: a rejected call applies none of its fields"); + } + // Wrong types and unknown nested keys are errors, not silent no-ops with ok:true. + for params in [ + json!({"panels": "x"}), + json!({"panels": {"nope": true}}), + json!({"dockTabs": {"nope": 1}}), + json!({"dock": {"nope": 1}}), + json!({"center": [1]}), + json!({"center": [1, 2, 3]}), + json!({"center": "here"}), + json!({"colorPanel": "x"}), + json!({"selectionMode": "add"}), + ] { + let r = call(&mut app, &ctx, "ui.set", params.clone()); + assert_eq!(r["ok"], false, "{params}: {r}"); + } + assert_eq!(serde_json::to_value(&app.ui.panels).unwrap_or_default(), panels_before, "nothing was applied"); + // Non-numeric brushSize keeps the API's historical silent no-op (see the dispatch test). + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"brushSize": "large"}))["ok"], true); +} + +#[test] +fn ui_set_rejects_view_numbers_beyond_f32_range() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.sync_views(); + let r = call(&mut app, &ctx, "ui.set", json!({"rotation": 30, "zoom": 2, "center": [3, 4], "dockWidth": 300})); + assert_eq!(r["ok"], true, "{r}"); + let dock = |ctx: &egui::Context| ctx.data(|d| d.get_temp::(crate::panels::dock_width_id())); + let (rotation, zoom, center) = (app.ui.views[0].rotation, app.ui.views[0].zoom, app.ui.views[0].center); + // Finite in f64 but infinite as f32: an error, not a silent reset to 0°, 100% or the minimum dock width. + for params in [json!({"rotation": 1e39}), json!({"zoom": 1e39}), json!({"center": [1e39, 0]}), json!({"center": [0, -1e39]}), json!({"dockWidth": 1e39})] { + let r = call(&mut app, &ctx, "ui.set", params.clone()); + assert_eq!(r["ok"], false, "{params}: {r}"); + assert_eq!(app.ui.views[0].rotation, rotation, "{params}"); + assert_eq!(app.ui.views[0].zoom, zoom, "{params}"); + assert_eq!(app.ui.views[0].center, center, "{params}"); + assert_eq!(dock(&ctx), Some(300.0), "{params}"); + } + // Huge but representable still clamps to the top zoom level. + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"zoom": 1e38}))["ok"], true); + assert!(app.ui.views[0].zoom.is_finite() && app.ui.views[0].zoom > zoom, "{}", app.ui.views[0].zoom); +} + +#[test] +fn ui_set_theme_keeps_explicit_dock_tab_indices() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + for theme in ["adwaitaDark", "pro"] { + let r = call(&mut app, &ctx, "ui.set", json!({"theme": theme, "dockTabs": {"color": 0}})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(app.ui.dock_tabs.color, 0, "{theme}: explicit tab index changed"); + } +} + +#[test] +fn ui_set_color_panel_picks_the_edited_chip() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"colorPanel": {"background": true}}))["ok"], true); + assert!(app.ui.color_panel.background); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"colorPanel": {"background": "yes"}}))["ok"], false); + assert!(app.ui.color_panel.background, "a bad value changes nothing"); +} + +#[test] +fn ui_set_color_panel_mode() { + use crate::state::ColorPanelMode; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + assert_eq!(app.ui.color_panel.mode, ColorPanelMode::HueCube); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"colorPanel": {"mode": "rgbSliders"}}))["ok"], true); + assert_eq!(app.ui.color_panel.mode, ColorPanelMode::RgbSliders); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"colorPanel": {"mode": "hsbSliders"}}))["ok"], true); + assert_eq!(app.ui.color_panel.mode, ColorPanelMode::HsbSliders); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"colorPanel": {"mode": "nope"}}))["ok"], false); + assert_eq!(app.ui.color_panel.mode, ColorPanelMode::HsbSliders); +} + +#[test] +fn ui_set_unknown_theme_error_names_every_theme_and_each_name_works() { + use crate::theme::ThemeKind; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let r = call(&mut app, &ctx, "ui.set", json!({"theme": "nope"})); + assert_eq!(r["ok"], false); + let error = r["error"].as_str().unwrap(); + for kind in ThemeKind::ALL { + assert!(error.contains(kind.id()), "{error} lacks {}", kind.id()); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"theme": kind.id()}))["ok"], true); + assert_eq!(app.ui.theme, kind); + assert_eq!(ThemeKind::from_name(kind.id()), Some(kind)); + } +} + +#[test] +fn ui_window_open_rejects_an_unknown_document_index() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + // An out-of-range index must error instead of silently switching the active document + // and opening the window for whatever is active now. + let before = app.session.active_index(); + let r = call(&mut app, &ctx, "ui.window.open", json!({"document": 99})); + assert_eq!(r["ok"], false, "{r}"); + assert!(r["error"].as_str().unwrap().contains("no document 99"), "{r}"); + assert_eq!(app.session.active_index(), before, "the active document is untouched"); + // A valid index still opens the window. + assert_eq!(call(&mut app, &ctx, "ui.window.open", json!({"document": 0}))["ok"], true); +} + +#[test] +fn ui_set_brush_size_dispatches_a_journaled_brush_command() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + + let r = call(&mut app, &ctx, "ui.set", json!({"brushSize": 42.5})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(app.session.tools.brush.size, 42.5); + let (id, params) = app.session.journal.last().cloned().expect("brush change is journaled"); + assert_eq!(id, "tools.setBrush"); + assert_eq!(params, json!({"brush": {"size": 42.5}})); + + // The control API has historically ignored non-numeric optional values. + for params in [json!({}), json!({"brushSize": null}), json!({"brushSize": "large"}), json!({"brushSize": true})] { + let journal_len = app.session.journal.len(); + let r = call(&mut app, &ctx, "ui.set", params); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(app.session.tools.brush.size, 42.5); + assert_eq!(app.session.journal.len(), journal_len); + } + + // Each tool keeps its own brush (#218), so `tool` + `brushSize` in one call sets the new + // tool's size rather than the one it was carrying. + call(&mut app, &ctx, "ui.set", json!({"tool": "eraser", "brushSize": 12.0})); + assert_eq!(app.session.tools.brush.size, 12.0, "the Eraser's own size"); + call(&mut app, &ctx, "ui.set", json!({"tool": "brush"})); + assert_eq!(app.session.tools.brush.size, 42.5, "the Brush gets its own back"); + call(&mut app, &ctx, "ui.set", json!({"tool": "eraser"})); + assert_eq!(app.session.tools.brush.size, 12.0); + call(&mut app, &ctx, "ui.set", json!({"tool": "brush", "brushSize": 42.5})); + + // Values that cannot be represented by BrushSettings must report the command error and + // leave both the brush and journal unchanged instead of mutating tool state directly. + let journal_len = app.session.journal.len(); + let r = call(&mut app, &ctx, "ui.set", json!({"brushSize": f64::MAX})); + assert_eq!(r["ok"], false, "{r}"); + assert!(r["error"].as_str().is_some(), "{r}"); + assert_eq!(app.session.tools.brush.size, 42.5); + assert_eq!(app.session.journal.len(), journal_len); +} + +#[test] +fn preferences_apply_is_available_over_control_without_closing() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let r = call(&mut app, &ctx, "ui.menu.invoke", json!({"id": "edit.preferences.interface"})); + let id = r["result"]["dialog"].as_u64().unwrap(); + let mut values = app.ui.dialog_mut(id).unwrap().fields["values"].clone(); + values["interface"]["uiScale"] = json!("200"); + assert_eq!(call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": id, "field": "values", "value": values}))["ok"], true); + assert_eq!(call(&mut app, &ctx, "ui.dialog.apply", json!({"dialog": id}))["ok"], true); + assert_eq!(app.session.prefs().interface.ui_scale, photocraft_engine::prefs::UiScale::P200); + assert!(app.ui.dialog_mut(id).is_some()); + assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": id}))["ok"], true); + assert_eq!(app.session.prefs().interface.ui_scale, photocraft_engine::prefs::UiScale::P200); + for params in [json!({}), json!({"dialog": "invalid"}), json!({"dialog": u64::MAX})] { + assert_eq!(call(&mut app, &ctx, "ui.dialog.apply", params)["ok"], false); + } +} + +#[test] +fn preferences_apply_respects_the_automation_command_policy() { + let services = crate::Services { + automation_command: Some(Box::new(|id, _| if id == "prefs.set" { Err("preference changes denied".into()) } else { Ok(()) })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = egui::Context::default(); + let before = app.session.prefs().to_json(); + let id = crate::prefs_ui::open_preferences(&mut app, "interface"); + app.ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap()["interface"]["uiScale"] = json!("200"); + let r = call(&mut app, &ctx, "ui.dialog.apply", json!({"dialog": id})); + assert_eq!(r["ok"], false); + assert_eq!(r["error"], "preference changes denied"); + assert_eq!(app.session.prefs().to_json(), before); + assert!(app.ui.dialog_mut(id).is_some()); +} + +#[test] +fn synthetic_shortcuts_use_the_automation_command_policy() { + let services = crate::Services { + automation_command: Some(Box::new(|id, _| if id.starts_with("file.") { Err("filesystem command denied".into()) } else { Ok(()) })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = egui::Context::default(); + app.automation_input = true; + let error = crate::menus::invoke(&mut app, &ctx, "file.open", json!({})).unwrap_err(); + assert_eq!(error, "filesystem command denied"); +} + +/// `app.save` takes the Targa bits per pixel (`tgaBits`) and never stops at Targa Options. +#[test] +fn automation_save_passes_targa_bits_without_asking() { + use std::cell::RefCell; + use std::rc::Rc; + // The bits each export was asked for, and each path written. + let asked: Rc>>> = Rc::default(); + let written: Rc>> = Rc::default(); + let (a, w) = (asked.clone(), written.clone()); + let services = crate::Services { + export: Some(Box::new(move |_d: &photocraft_doc::Document, _p: &str, s: &crate::ExportSettings| { + a.borrow_mut().push(s.tga_bits.map(photocraft_io::TgaBits::bits)); + Ok((b"out".to_vec(), Vec::new())) + })), + automation_write: Some(Box::new(move |path: &str, _b: &[u8]| { + w.borrow_mut().push(path.to_string()); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + for params in [json!({"path": "a.tga"}), json!({"path": "b.tga", "tgaBits": 24}), json!({"path": "c.tga", "tgaBits": 32})] { + let r = call(&mut app, &ctx, "app.save", params.clone()); + assert_eq!(r["result"]["path"], params["path"], "{r}"); + assert!(app.targa_options.is_none(), "automation saves never prompt"); + } + assert_eq!(*asked.borrow(), [None, Some(24), Some(32)]); + assert_eq!(*written.borrow(), ["a.tga", "b.tga", "c.tga"]); + let r = call(&mut app, &ctx, "app.save", json!({"path": "d.tga", "tgaBits": 16})); + assert!(r["error"].as_str().unwrap().contains("tgaBits"), "{r}"); + assert_eq!(written.borrow().len(), 3, "a bad tgaBits writes nothing"); +} + +/// `app.save` takes JPEG Options (`quality` 0–12, `jpegFormat`) and never stops at the prompt; +/// a value it can't read is an error that writes nothing. +#[test] +fn automation_save_passes_jpeg_options_without_asking() { + use photocraft_codecs::JpegFormat; + use std::cell::RefCell; + use std::rc::Rc; + // The JPEG quality (1–100) and format each export was asked for. + type Asked = Rc, JpegFormat)>>>; + let asked: Asked = Rc::default(); + let written: Rc>> = Rc::default(); + let (a, w) = (asked.clone(), written.clone()); + let services = crate::Services { + export: Some(Box::new(move |_d: &photocraft_doc::Document, _p: &str, s: &crate::ExportSettings| { + a.borrow_mut().push((s.jpeg_quality, s.jpeg_format)); + Ok((b"out".to_vec(), Vec::new())) + })), + automation_write: Some(Box::new(move |path: &str, _b: &[u8]| { + w.borrow_mut().push(path.to_string()); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + for params in + [json!({"path": "a.jpg"}), json!({"path": "b.jpg", "quality": 12, "jpegFormat": "progressive"}), json!({"path": "c.jpg", "jpegFormat": "optimized"})] + { + let r = call(&mut app, &ctx, "app.save", params.clone()); + assert_eq!(r["result"]["path"], params["path"], "{r}"); + assert!(app.jpeg_options.is_none(), "automation saves never prompt"); + } + assert_eq!(*asked.borrow(), [(None, JpegFormat::Baseline), (Some(100), JpegFormat::Progressive), (None, JpegFormat::Optimized)]); + for bad in [ + json!({"path": "d.jpg", "quality": 13}), + json!({"path": "d.jpg", "quality": "high"}), + json!({"path": "d.jpg", "jpegFormat": "fast"}), + json!({"path": "d.jpg", "jpegFormat": 2}), + ] { + let r = call(&mut app, &ctx, "app.save", bad.clone()); + assert!(r["error"].is_string(), "{bad}: {r}"); + } + assert_eq!(written.borrow().len(), 3, "a bad JPEG option writes nothing"); +} + +/// `app.save` takes the DDS options (`ddsCompression`, `ddsMipmaps`) and never stops at DDS +/// Options. +#[test] +fn automation_save_passes_dds_options_without_asking() { + use photocraft_io::{DdsCompression, DdsOptions}; + use std::cell::RefCell; + use std::rc::Rc; + let asked: Rc>> = Rc::default(); + let a = asked.clone(); + let services = crate::Services { + export: Some(Box::new(move |_d: &photocraft_doc::Document, _p: &str, s: &crate::ExportSettings| { + a.borrow_mut().push(s.dds); + Ok((b"out".to_vec(), Vec::new())) + })), + automation_write: Some(Box::new(|_: &str, _: &[u8]| Ok(()))), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + for params in [json!({"path": "a.dds"}), json!({"path": "b.dds", "ddsCompression": "bc1", "ddsMipmaps": true})] { + let r = call(&mut app, &ctx, "app.save", params.clone()); + assert_eq!(r["result"]["path"], params["path"], "{r}"); + assert!(app.dds_options.is_none(), "automation saves never prompt"); + } + assert_eq!(*asked.borrow(), [DdsOptions::default(), DdsOptions { compression: DdsCompression::Bc1, mipmaps: true }]); + let r = call(&mut app, &ctx, "app.save", json!({"path": "c.dds", "ddsCompression": "bc9"})); + assert!(r["error"].as_str().unwrap().contains("ddsCompression"), "{r}"); + assert_eq!(asked.borrow().len(), 2, "a bad ddsCompression writes nothing"); +} + +#[test] +fn automation_open_and_save_use_the_roots_and_reply_with_warnings() { + use photocraft_color::{ColorMode, SampleType}; + use photocraft_doc::Document; + use photocraft_geom::Size; + use std::cell::RefCell; + use std::rc::Rc; + + // Without granted roots both fail closed, even with an exporter and an ambient writer. + let services = crate::Services { + export: Some(Box::new(|_d: &Document, _p: &str, _s: &crate::ExportSettings| Ok((b"out".to_vec(), Vec::new())))), + write: Some(Box::new(|_p: &str, _b: &[u8]| Err("ambient writer used".into()))), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = egui::Context::default(); + let r = call(&mut app, &ctx, "app.open", json!({"path": "in/warn.psd"})); + assert!(r.to_string().contains("automation read authority is not configured"), "{r}"); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let r = call(&mut app, &ctx, "app.save", json!({"path": "out.png"})); + assert!(r.to_string().contains("automation write authority is not configured"), "{r}"); + + let written: Rc>> = Rc::default(); + let w = written.clone(); + let services = crate::Services { + import: Some(Box::new(|name: &str, _b: &[u8], _opts: &photocraft_io::ImportOptions| { + Ok((Document::new(name, Size::new(4, 4), ColorMode::Rgb, SampleType::U8), vec!["Adjustment layer flattened".to_string()])) + })), + export: Some(Box::new(|_d: &Document, _p: &str, _s: &crate::ExportSettings| Ok((b"out".to_vec(), vec!["Layers were flattened".to_string()])))), + automation_read: Some(Box::new(|path: &str| Ok((path.rsplit('/').next().unwrap_or(path).to_string(), b"x".to_vec())))), + automation_write: Some(Box::new(move |path: &str, _b: &[u8]| { + w.borrow_mut().push(path.to_string()); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let r = call(&mut app, &ctx, "app.open", json!({"path": "in/warn.psd"})); + assert_eq!(r["result"]["warnings"], json!(["Adjustment layer flattened"]), "{r}"); + assert_eq!(r["result"]["name"], "warn.psd"); + assert_eq!(app.session.active().unwrap().path.as_deref(), Some("in/warn.psd")); + assert_eq!(app.ui.recent_files, vec!["in/warn.psd".to_string()]); + let r = call(&mut app, &ctx, "app.save", json!({"path": "out.png"})); + assert_eq!(r["result"], json!({"path": "out.png", "warnings": ["Layers were flattened"]}), "{r}"); + assert_eq!(*written.borrow(), vec!["out.png".to_string()]); + // A flat export is a copy: the document keeps its name and file (#2579). + let st = app.session.active().unwrap(); + assert_eq!((st.doc.name.as_str(), st.path.as_deref()), ("warn.psd", Some("in/warn.psd"))); + // Without `path`, only a layered file is written back, like File › Save (#416). + call(&mut app, &ctx, "app.open", json!({"path": "in/flat.jpg"})); + let r = call(&mut app, &ctx, "app.save", json!({})); + assert!(r["error"].as_str().unwrap().contains("pass `path`"), "{r}"); + assert_eq!(written.borrow().len(), 1, "nothing written over the JPEG"); + call(&mut app, &ctx, "app.open", json!({"path": "in/layered.psd"})); + let r = call(&mut app, &ctx, "app.save", json!({})); + assert_eq!(r["result"]["path"], "in/layered.psd", "{r}"); + assert_eq!(written.borrow().last().map(String::as_str), Some("in/layered.psd")); + // A template opens untitled, so a save without `path` never writes over it. + let r = call(&mut app, &ctx, "app.open", json!({"path": "in/card.psdt"})); + assert_eq!(r["result"]["name"], "Untitled-1", "{r}"); + assert_eq!(app.session.active().unwrap().path, None); + let r = call(&mut app, &ctx, "app.save", json!({})); + assert!(r["error"].as_str().unwrap().contains("pass `path`"), "{r}"); +} + +fn deny_ambient_file(id: &str, _: &serde_json::Value) -> photocraft_engine::Result<()> { + if id.starts_with("file.") && id != "file.new" { + Err(photocraft_engine::EngineError::Other(format!("automation command `{id}` is disabled"))) + } else { + Ok(()) + } +} + +/// An app whose automation gates refuse file commands, with a document open, and the paths +/// its writer was asked to write. +fn gated_app_recording_writes() -> (PhotocraftApp, egui::Context, std::rc::Rc>>, u64) { + let written: std::rc::Rc>> = std::rc::Rc::default(); + let w = written.clone(); + let services = crate::Services { + automation_authorize: Some(deny_ambient_file), + automation_command: Some(Box::new(|id, params| deny_ambient_file(id, params).map_err(|e| e.to_string()))), + export: Some(Box::new(|_: &photocraft_doc::Document, _: &str, _: &crate::ExportSettings| Ok((b"out".to_vec(), Vec::new())))), + write: Some(Box::new(move |path: &str, _: &[u8]| { + w.borrow_mut().push(path.to_string()); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.background_jobs = false; + app.session.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + let doc = app.session.active().unwrap().doc.id.0; + (app, egui::Context::default(), written, doc) +} + +fn outside_target() -> String { + std::env::temp_dir().join("outside").join("x.png").to_string_lossy().into_owned() +} + +/// `ui.dialog.set` and `ui.dialog.open` never add a marker that picks a dialog's OK handler: +/// a View › Zoom In dialog can't be made to confirm as the disk-change prompt's save. +#[test] +fn automation_cannot_add_a_marker_that_reroutes_a_dialog() { + let (mut app, ctx, written, doc) = gated_app_recording_writes(); + let target = outside_target(); + let r = call(&mut app, &ctx, "ui.dialog.open", json!({"kind": "command", "command": "view.zoomIn"})); + let dialog = r["result"]["dialog"].clone(); + for (field, value) in [("document", json!(doc)), ("path", json!(target)), ("flat", json!(false))] { + let r = call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": dialog, "field": field, "value": value})); + assert!(r.get("error").is_none(), "{r}"); + } + let injected = call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": dialog, "field": "__diskChanged", "value": true})); + let replace = call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": dialog, "field": "__replaceSaved", "value": true})); + assert!(replace["error"].as_str().is_some_and(|e| e.contains("set only by the dialog")), "{replace}"); + call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": dialog})); + assert!(written.borrow().is_empty(), "nothing is written: {:?}", written.borrow()); + assert!(injected["error"].as_str().is_some_and(|e| e.contains("set only by the dialog")), "{injected}"); + let r = call(&mut app, &ctx, "ui.dialog.open", json!({"kind": "about", "fields": {"__export": true}})); + assert!(r["error"].as_str().is_some_and(|e| e.contains("set only by the dialog")), "{r}"); +} + +/// A handler that writes files itself (the disk-change prompt's save) is judged as the file +/// command it stands for, through a control request or synthetic input alike. +#[test] +fn automation_confirming_a_file_writing_dialog_is_judged_as_its_file_command() { + let (mut app, ctx, written, doc) = gated_app_recording_writes(); + let target = outside_target(); + // A real disk-change prompt keeps its own fields settable, but its save is a file command. + let fields = json!({"__diskChanged": true, "__label": "Save", "message": "", "document": doc, "path": target, "flat": false}); + let prompt = app.ui.open_dialog(DialogKind::Command, fields.as_object().cloned().unwrap()); + let r = call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": prompt, "field": "__diskChanged", "value": true})); + assert!(r.get("error").is_none(), "{r}"); + let r = call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": prompt})); + assert!(written.borrow().is_empty(), "nothing is written: {:?}", written.borrow()); + assert!(r["error"].as_str().is_some_and(|e| e.contains("file.save")), "{r}"); + // Synthetic input (Enter or OK) reaches the same handler without the control pre-check. + let synthetic = app.ui.open_dialog(DialogKind::Command, fields.as_object().cloned().unwrap()); + app.automation_input = true; + let r = crate::dialogs::confirm(&mut app, synthetic); + app.automation_input = false; + assert!(written.borrow().is_empty(), "nothing is written: {:?}", written.borrow()); + assert!(r.is_err_and(|e| e.contains("file.save"))); +} + +#[test] +fn app_open_opens_a_directory_pcraft_and_falls_back_for_the_zip_form() { + use photocraft_doc::Document; + use serde_json::json; + let services = crate::Services { + automation_open_pcraft: Some(Box::new(|path: &str| { + if path == "native.pcraft" { + let name = path.rsplit('/').next().unwrap_or(path).to_string(); + let doc = Document::new("Native", photocraft_doc::Size::new(16, 12), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); + Ok(Some((name, doc))) + } else if path == "zipped.pcraft" { + Ok(None) // a regular file: the bytes path reads the zip form + } else { + Err(format!("corrupt bundle: {path}")) + } + })), + import: Some(Box::new(|name: &str, _b: &[u8], _opts: &photocraft_io::ImportOptions| { + Ok((Document::new(name, photocraft_doc::Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8), Vec::new())) + })), + automation_read: Some(Box::new(|path: &str| { + if path == "zipped.pcraft" { + Ok((path.rsplit('/').next().unwrap_or(path).to_string(), b"zip-bytes".to_vec())) + } else { + Err(format!("no such path: {path}")) + } + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = egui::Context::default(); + + let r = call(&mut app, &ctx, "app.open", json!({"path": "native.pcraft"})); + assert_eq!(r["result"], json!({"path": "native.pcraft", "name": "native.pcraft", "warnings": []}), "{r}"); + assert_eq!(app.session.active().unwrap().doc.name, "Native"); + assert_eq!(app.ui.recent_files, vec!["native.pcraft".to_string()], "the open is recorded in recent files"); + assert_eq!(app.session.active().unwrap().path, None, "no save-back target: the automation writer replaces files, never directories"); + let r = call(&mut app, &ctx, "app.save", json!({})); + assert!(r["error"].as_str().unwrap().contains("pass `path`"), "an in-place save is refused up front: {r}"); + + // The single-file form takes the bytes path through the same `.pcraft` extension. + let r = call(&mut app, &ctx, "app.open", json!({"path": "zipped.pcraft"})); + assert_eq!(r["result"]["name"], "zipped.pcraft", "{r}"); + assert_eq!(app.session.active().unwrap().doc.name, "zipped.pcraft", "the import served the zip form"); + + // A real opener error propagates instead of being masked by the fallback. + let r = call(&mut app, &ctx, "app.open", json!({"path": "gone.pcraft"})); + assert!(r["error"].as_str().unwrap().contains("corrupt bundle"), "{r}"); +} + +#[test] +fn app_save_runs_as_a_background_job_and_the_final_reply_carries_the_path() { + use photocraft_engine::automate_cmds::ScriptBinding; + use serde_json::json; + let saved: std::sync::Arc>> = Default::default(); + let record = saved.clone(); + let services = crate::Services { + automation_save: Some(std::sync::Arc::new(move |_doc, path: &str, _settings, _ctl| { + record.lock().unwrap().push(path.to_string()); + Ok(vec!["Layers were flattened".to_string()]) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.background_jobs = true; + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + // A "Save Document" binding that would leave a trace: automation saves never fire it. + app.session.edit_prefs(|prefs| { + prefs.script_events.enabled = true; + prefs.script_events.bindings = vec![ScriptBinding { + event: "saveDocument".into(), + script: None, + steps: Some(json!([["layer.new.layer", {"name": "From the binding"}]])), + name: "Binding".into(), + }]; + }); + let ctx = egui::Context::default(); + let (tx, rx) = std::sync::mpsc::channel(); + let app = app.with_control(rx); + let mut app = app; + + let (mut req, reply) = ControlRequest::new("app.save", json!({"path": "out.psd"})); + req.deadline = None; + tx.send(req).unwrap(); + app.drain_control(&ctx); + // Started in the background: no reply yet, the job is on the document. + assert!(reply.try_recv().is_err(), "the reply waits for the save job"); + assert!(app.saving(), "the save runs as a background job"); + for _ in 0..100 { + crate::jobs_ui::tick(&mut app, &ctx); + if !app.saving() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(!app.saving(), "the save finished"); + assert_eq!(*saved.lock().unwrap(), vec!["out.psd".to_string()]); + assert_eq!(app.session.active().unwrap().path.as_deref(), Some("out.psd"), "the save was recorded"); + assert_eq!(app.session.active().unwrap().doc.layer_count(), 1, "the saveDocument binding did not run for an automation save"); + let r = reply.recv().unwrap(); + assert_eq!(r["result"], json!({"path": "out.psd", "warnings": ["Layers were flattened"]}), "{r}"); + + // An interactive save (File › Save's worker) still fires the binding. + let save = std::sync::Arc::new(|_doc: &photocraft_doc::Document, path: &str, _settings: &crate::ExportSettings, _ctl: &crate::jobs_ui::SaveCtl| { + let _ = path; + Ok(Vec::new()) + }) as crate::SaveFileFn; + crate::jobs_ui::start_save(&mut app, "user.psd".into(), crate::ExportSettings::default(), false, save, false).unwrap(); + for _ in 0..100 { + crate::jobs_ui::tick(&mut app, &ctx); + if !app.saving() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(!app.saving(), "the interactive save finished"); + assert_eq!(app.session.active().unwrap().doc.layer_count(), 2, "the binding runs for an interactive save"); +} + +#[test] +fn ui_inspect_replies_while_a_save_job_encodes() { + // #2488: the control channel must keep answering while a large save runs. + use serde_json::json; + let gate = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let wait_for_gate = gate.clone(); + let saved: std::sync::Arc>> = Default::default(); + let record = saved.clone(); + let services = crate::Services { + automation_save: Some(std::sync::Arc::new(move |_doc, path: &str, _settings, ctl| { + while !wait_for_gate.load(std::sync::atomic::Ordering::Acquire) { + ctl.check()?; + std::thread::sleep(std::time::Duration::from_millis(2)); + } + record.lock().unwrap().push(path.to_string()); + Ok(Vec::new()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.background_jobs = true; + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let ctx = egui::Context::default(); + let (tx, rx) = std::sync::mpsc::channel(); + let app = app.with_control(rx); + let mut app = app; + + let (mut save_req, save_reply) = ControlRequest::new("app.save", json!({"path": "out.png", "wait": false})); + save_req.deadline = None; + tx.send(save_req).unwrap(); + let (mut inspect_req, inspect_reply) = ControlRequest::new("ui.inspect", json!({})); + inspect_req.deadline = None; + tx.send(inspect_req).unwrap(); + app.drain_control(&ctx); + + let pending = save_reply.recv_timeout(std::time::Duration::from_secs(5)).expect("the unwaited save replies at once"); + assert_eq!(pending["result"]["pending"], true, "{pending}"); + assert_eq!(pending["result"]["path"], "out.png", "{pending}"); + assert!(pending["result"]["job"].is_u64(), "the caller can poll or wait: {pending}"); + // While the save is still encoding, the channel answers other requests. + assert!(saved.lock().unwrap().is_empty(), "the save is still encoding"); + let inspected = inspect_reply.recv_timeout(std::time::Duration::from_secs(5)).expect("ui.inspect is not blocked by the save"); + assert_eq!(inspected["ok"], true, "{inspected}"); + + gate.store(true, std::sync::atomic::Ordering::Release); + for _ in 0..500 { + crate::jobs_ui::tick(&mut app, &ctx); + if !app.saving() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(*saved.lock().unwrap(), vec!["out.png".to_string()], "the save completed after the gate opened"); +} + +fn deny_smart_object_paths(id: &str, params: &Value) -> photocraft_engine::Result<()> { + // The production policy lives in the automation crate. This gate exercises the control + // session's state-derived path check without adding that dependency to the UI crate. + if matches!(id, "layer.smartObjects.editContents" | "layer.smartObjects.convertToLayers" | "layer.smartObjects.saveContents") + && params.get("path").and_then(Value::as_str).is_some() + { + Err(photocraft_engine::EngineError::Other("ambient smart-object path denied".into())) + } else { + Ok(()) + } +} + +fn smart_control_app() -> (PhotocraftApp, egui::Context, photocraft_doc::LayerId) { + let services = crate::Services { + automation_authorize: Some(deny_smart_object_paths), + automation_command: Some(Box::new(|id, params| deny_smart_object_paths(id, params).map_err(|e| e.to_string()))), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", json!({"width": 8, "height": 6, "background": "transparent"})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let id = app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap(); + (app, egui::Context::default(), photocraft_doc::LayerId(id)) +} + +#[test] +fn control_edits_nested_embedded_smart_objects_and_converts_an_explicit_target() { + use photocraft_doc::{LayerContent, SmartSource}; + use std::cell::RefCell; + use std::rc::Rc; + use std::sync::Arc; + + let (mut app, ctx, smart) = smart_control_app(); + // Embed this one-smart-layer document inside the outer object: two Edit Contents + // requests must reach the raster layer, as in a nested product-photo template. + let nested = photocraft_engine::smart_cmds::encode_source(&app.session.active().unwrap().doc).unwrap(); + app.session + .edit("Nested fixture", |doc, _| { + let LayerContent::Smart(sm) = &mut doc.layer_mut(smart).unwrap().content else { panic!("smart fixture") }; + sm.source = SmartSource::Embedded { file_name: "product.pcraft".into(), bytes: Arc::new(nested) }; + Ok(()) + }) + .unwrap(); + let other = app.run("layer.new.layer", json!({"name": "Unrelated"})).unwrap()["layer"].as_u64().unwrap(); + assert_ne!(app.session.active().unwrap().active_layer, Some(smart)); + for expected_document in [1, 2] { + let r = call(&mut app, &ctx, "engine.execute", json!({"command": "layer.smartObjects.editContents", "params": {"layer": smart.0}})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(r["result"]["document"], expected_document, "{r}"); + assert!(app.session.active().unwrap().path.is_none(), "contents open in memory"); + assert!(app.session.authorize.is_none(), "the request gate must not remain installed"); + } + let r = call(&mut app, &ctx, "engine.execute", json!({"command": "edit.fill", "params": {"color": "#0000ff"}})); + assert_eq!(r["ok"], true, "{r}"); + for expected_documents in [2, 1] { + let r = call(&mut app, &ctx, "engine.execute", json!({"command": "layer.smartObjects.saveContents"})); + assert_eq!(r["ok"], true, "{r}"); + let r = call(&mut app, &ctx, "engine.execute", json!({"command": "file.close"})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(app.session.documents().len(), expected_documents); + } + assert_eq!(app.session.active().unwrap().active_layer, Some(photocraft_doc::LayerId(other))); + assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px[0], [0.0, 0.0, 1.0, 1.0]); + let r = call(&mut app, &ctx, "engine.execute", json!({"command": "layer.smartObjects.convertToLayers", "params": {"layer": smart.0}})); + assert_eq!(r["ok"], true, "{r}"); + assert!(app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(other)).is_some(), "the unrelated active layer remains"); + assert!(app.session.authorize.is_none()); + + let written = Rc::new(RefCell::new(Vec::new())); + let output = written.clone(); + app.services.export = + Some(Box::new(|doc, _, _| photocraft_engine::smart_cmds::encode_source(doc).map(|bytes| (bytes, Vec::new())).map_err(|e| e.to_string()))); + app.services.automation_write = Some(Box::new(move |path, bytes| { + output.borrow_mut().push((path.to_string(), bytes.to_vec())); + Ok(()) + })); + app.services.write = Some(Box::new(|_, _| Err("ambient writer used".into()))); + let r = call(&mut app, &ctx, "app.save", json!({"path": "out/template.pcraft"})); + assert_eq!(r["ok"], true, "{r}"); + let written = written.borrow(); + assert_eq!(written.len(), 1); + assert_eq!(written[0].0, "out/template.pcraft"); + let saved = photocraft_engine::smart_cmds::decode_source(&written[0].0, &written[0].1).unwrap(); + assert_eq!(photocraft_compose::flatten(&saved).px[0], [0.0, 0.0, 1.0, 1.0]); +} + +#[test] +fn control_refuses_linked_smart_objects_in_commands_and_actions_but_local_editing_still_works() { + use photocraft_doc::{LayerContent, SmartSource}; + use std::sync::Arc; + + let (mut app, ctx, smart) = smart_control_app(); + let path = std::env::temp_dir().join(format!("pc-control-smart-linked-{}.pcraft", std::process::id())); + let st = app.session.active().unwrap(); + let LayerContent::Smart(sm) = &st.doc.layer(smart).unwrap().content else { panic!("smart fixture") }; + let SmartSource::Embedded { bytes, .. } = &sm.source else { panic!("embedded fixture") }; + std::fs::write(&path, bytes.as_slice()).unwrap(); + app.session + .edit("Linked fixture", |doc, _| { + let LayerContent::Smart(sm) = &mut doc.layer_mut(smart).unwrap().content else { panic!("smart fixture") }; + sm.source = SmartSource::Linked { path: path.to_string_lossy().into_owned() }; + Ok(()) + }) + .unwrap(); + app.run("layer.new.layer", json!({"name": "Unrelated"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let active = app.session.active().unwrap().active_layer; + for command in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers"] { + let r = call(&mut app, &ctx, "engine.execute", json!({"command": command, "params": {"layer": smart.0}})); + assert_eq!(r["ok"], false, "{r}"); + assert!(r["error"].as_str().unwrap().contains("ambient smart-object path denied"), "{r}"); + app.session.actions.list = vec![photocraft_engine::actions_cmds::Action { + name: "Linked contents".into(), + steps: vec![(command.into(), json!({"layer": smart.0}))], + disabled: Default::default(), + ..Default::default() + }]; + let r = call(&mut app, &ctx, "engine.execute", json!({"command": "actions.play", "params": {"action": "Linked contents"}})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(r["result"]["ran"], 0, "{r}"); + assert_eq!(r["result"]["failed"]["id"], command, "{r}"); + assert_eq!(app.session.documents().len(), 1); + assert!(Arc::ptr_eq(&app.session.active().unwrap().doc, &before), "a refused operation must not edit the document"); + assert_eq!(app.session.active().unwrap().active_layer, active); + assert!(app.session.authorize.is_none(), "a refused request must restore the local session"); + } + // A synthetic thumbnail action uses the same temporary authorization as control calls. + app.automation_input = true; + let error = crate::menus::invoke(&mut app, &ctx, "layer.smartObjects.editContents", json!({"layer": smart.0})).unwrap_err(); + assert!(error.contains("ambient smart-object path denied"), "{error}"); + assert!(app.session.authorize.is_none()); + app.automation_input = false; + app.run("layer.smartObjects.editContents", json!({"layer": smart.0})).unwrap(); + assert_eq!(app.session.documents().len(), 2, "a human can still open the existing linked file"); + assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px[0], [1.0, 0.0, 0.0, 1.0]); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn actions_play_checks_each_step_over_control() { + let services = crate::Services { automation_authorize: Some(deny_ambient_file), ..Default::default() }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.session.actions.list.push(photocraft_engine::actions_cmds::Action { + name: "Open".into(), + steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + let ctx = egui::Context::default(); + let r = call(&mut app, &ctx, "engine.execute", json!({"command": "actions.play", "params": {"action": "Open"}})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(r["result"]["ran"], 0, "{r}"); + assert_eq!(r["result"]["failed"]["id"], "file.open", "{r}"); + assert!(r["result"]["failed"]["error"].as_str().unwrap_or("").contains("disabled"), "{r}"); + assert!(app.session.documents().is_empty()); + assert!(app.session.authorize.is_none(), "the per-step gate is only installed for the request"); +} + +#[test] +fn actions_play_checks_each_step_for_synthetic_input() { + let services = crate::Services { automation_authorize: Some(deny_ambient_file), ..Default::default() }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.session.actions.list.push(photocraft_engine::actions_cmds::Action { + name: "Open".into(), + steps: vec![("file.open".into(), json!({"path": "/etc/passwd"})), ("layer.new.layer".into(), json!({}))], + disabled: Default::default(), + ..Default::default() + }); + app.automation_input = true; + let r = app.run("actions.play", json!({"action": "Open"})).unwrap(); + assert_eq!(r["ran"], 0, "{r}"); + assert_eq!(r["failed"]["id"], "file.open", "{r}"); + assert!(app.session.authorize.is_none(), "the per-step gate is only installed for the command"); + + // A local play (no automation input) still runs recorded steps. + app.automation_input = false; + app.session.actions.list[0].steps.remove(0); + app.session.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + let r = app.run("actions.play", json!({"action": "Open"})).unwrap(); + assert_eq!(r["ran"], 1, "{r}"); +} + +#[test] +fn huge_click_count_is_rejected() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + // #982: a huge count used to queue a press and a release per click before replying. + for count in [json!(MAX_CLICKS + 1), json!(1_000_000_000u64), json!(u64::MAX)] { + let r = call(&mut app, &ctx, "ui.click", json!({"x": 10, "y": 10, "count": count})); + assert_eq!(r["ok"], false, "{r}"); + assert!(r["error"].as_str().unwrap().contains("`count` must be at most 256"), "{r}"); + assert!(app.synthetic.is_empty(), "a rejected click queues nothing"); + } + // Single, double and the largest allowed clicks still queue a move plus a press and a release each. + for (count, events) in [(None, 3), (Some(2), 5), (Some(MAX_CLICKS), 2 * MAX_CLICKS as usize + 1)] { + let params = match count { + Some(n) => json!({"x": 10, "y": 10, "count": n}), + None => json!({"x": 10, "y": 10}), + }; + let (req, _rx) = ControlRequest::new("ui.click", params); + assert!(matches!(handle(&mut app, &ctx, &req), Outcome::AfterInput)); + assert_eq!(app.synthetic.len(), events); + app.synthetic.clear(); + } +} + +/// #2449: the error of a rejected synthetic input call, after checking it changed nothing. +fn rejected(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value, names: &str) -> String { + let (tool, revision) = (app.ui.tool, app.session.active().map(|d| d.revision)); + let r = call(app, ctx, method, params.clone()); + assert_eq!(r["ok"], false, "{method} {params}: {r}"); + let error = r["error"].as_str().unwrap().to_string(); + assert!(error.contains(names), "{method} {params}: `{error}` should name `{names}`"); + assert!(app.synthetic.is_empty(), "{method} {params}: a rejected call queues nothing"); + assert_eq!(app.ui.tool, tool, "{method} {params}: a rejected call keeps the tool"); + assert_eq!(app.session.active().map(|d| d.revision), revision, "{method} {params}: a rejected call edits nothing"); + error +} + +#[test] +fn ui_pointer_rejects_bad_params_before_acting() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + let stroke = json!([{"kind": "down", "x": 5, "y": 5}, {"kind": "move", "x": 30, "y": 30}, {"kind": "up", "x": 30, "y": 30}]); + // The same unknown tool is the same error as `ui.set`'s. + let set = call(&mut app, &ctx, "ui.set", json!({"tool": "noSuchTool"})); + let error = rejected(&mut app, &ctx, "ui.pointer", json!({"tool": "noSuchTool", "events": stroke}), "noSuchTool"); + assert_eq!(json!(error), set["error"]); + let event = |extra: Value| { + let mut e = json!({"kind": "down", "x": 5, "y": 5}); + e.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + // A valid stroke first: a later bad event must not let the earlier ones run. + json!({"tool": "move", "events": [stroke[0], stroke[1], stroke[2], e]}) + }; + let cases = [ + // Unknown fields, top-level, under `modifiers` and in an event. + (json!({"tol": "move", "events": stroke}), "tol"), + (json!({"modifiers": {"shfit": true}, "events": stroke}), "shfit"), + (event(json!({"presure": 0.5})), "presure"), + // Wrong JSON types. + (json!({"tool": 3, "events": stroke}), "tool"), + (json!({"events": "down"}), "events"), + (json!({}), "events"), + (json!({"events": [5]}), "events[0]"), + (event(json!({"x": "abc"})), "x"), + (event(json!({"y": true})), "y"), + (event(json!({"kind": 1})), "kind"), + (json!({"shift": "yes", "events": stroke}), "shift"), + (json!({"modifiers": {"alt": 1}, "events": stroke}), "alt"), + (json!({"modifiers": true, "events": stroke}), "modifiers"), + (json!({"button": 2, "events": stroke}), "button"), + (json!([1, 2]), "params"), + // Values outside the accepted set. + (json!({"button": "ritgh", "events": stroke}), "button"), + (event(json!({"kind": "dwon"})), "kind"), + // Numbers outside their documented range. + (event(json!({"pressure": 99})), "pressure"), + (event(json!({"pressure": -0.1})), "pressure"), + (event(json!({"tiltX": 91})), "tiltX"), + (event(json!({"tiltY": -90.5})), "tiltY"), + (event(json!({"rotation": 361})), "rotation"), + (event(json!({"rotation": -1})), "rotation"), + ]; + for (params, names) in cases { + rejected(&mut app, &ctx, "ui.pointer", params, names); + } + let error = rejected(&mut app, &ctx, "ui.pointer", json!({"button": "ritgh", "events": stroke}), "button"); + assert!(error.contains("right") && error.contains("secondary"), "the error lists the buttons: {error}"); + let error = rejected(&mut app, &ctx, "ui.pointer", event(json!({"kind": "dwon"})), "kind"); + assert!(error.contains("down") && error.contains("move") && error.contains("up"), "the error lists the kinds: {error}"); + + // Valid calls still run: an omitted kind is a move, null is an omitted field, and the + // documented range ends are accepted. + let before = app.session.active().unwrap().revision; + let pen = json!({"kind": "down", "x": 5, "y": 5, "pressure": 0, "tiltX": -90, "tiltY": 90, "rotation": 360}); + let valid = json!({"tool": "brush", "button": null, "modifiers": {"shift": false}, "events": [pen, {"x": 20, "y": 20, "pressure": 1}, {"kind": "up", "x": 20, "y": 20}]}); + let r = call(&mut app, &ctx, "ui.pointer", valid); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(app.ui.tool, Tool::Brush); + assert!(app.session.active().unwrap().revision > before, "the stroke painted"); + for button in ["left", "middle", "right", "secondary"] { + let r = call( + &mut app, + &ctx, + "ui.pointer", + json!({"tool": "move", "button": button, "events": [{"kind": "down", "x": 5, "y": 5}, {"kind": "up", "x": 5, "y": 5}]}), + ); + assert_eq!(r["ok"], true, "{button}: {r}"); + } + assert!(app.ui.layer_menu.is_some(), "a right click with Move still opens the layer menu"); +} + +#[test] +fn ui_click_and_move_reject_bad_params_before_queueing_input() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let cases = [ + ("ui.click", json!({"x": 10, "y": 10, "buton": "right"}), "buton"), + ("ui.move", json!({"x": 10, "y": 10, "count": 2}), "count"), + ("ui.click", json!({"x": "abc", "y": 10}), "x"), + ("ui.move", json!({"x": 10, "y": [10]}), "y"), + ("ui.click", json!({"x": 10, "y": 10, "count": "dos"}), "count"), + ("ui.click", json!({"x": 10, "y": 10, "count": 1.5}), "count"), + ("ui.click", json!({"x": 10, "y": 10, "count": -1}), "count"), + ("ui.click", json!({"x": 10, "y": 10, "button": true}), "button"), + ("ui.click", json!({"x": 10, "y": 10, "button": "ritgh"}), "button"), + ("ui.click", json!({"x": 10, "y": 10, "count": MAX_CLICKS + 1}), "count"), + ("ui.click", json!("click"), "params"), + ]; + for (method, params, names) in cases { + rejected(&mut app, &ctx, method, params, names); + } + let error = rejected(&mut app, &ctx, "ui.click", json!({"x": 10, "y": 10, "button": "ritgh"}), "button"); + assert!(error.contains("left") && error.contains("right") && error.contains("middle"), "the error lists the buttons: {error}"); + // Valid calls queue what they did before; an omitted button is a left click. + for (method, params, button, events) in [ + ("ui.click", json!({"x": 10, "y": 10}), egui::PointerButton::Primary, 3), + ("ui.click", json!({"x": 10, "y": 10, "button": "right", "count": 2}), egui::PointerButton::Secondary, 5), + ("ui.click", json!({"x": 10, "y": 10, "button": "secondary"}), egui::PointerButton::Secondary, 3), + ("ui.click", json!({"x": 10.5, "y": 10, "button": "middle", "count": null}), egui::PointerButton::Middle, 3), + ("ui.move", json!({"x": 10, "y": 10}), egui::PointerButton::Primary, 1), + ] { + let (req, _rx) = ControlRequest::new(method, params.clone()); + assert!(matches!(handle(&mut app, &ctx, &req), Outcome::AfterInput), "{method} {params}"); + assert_eq!(app.synthetic.len(), events, "{method} {params}"); + if let Some(egui::Event::PointerButton { button: queued, .. }) = app.synthetic.get(1) { + assert_eq!(*queued, button, "{method} {params}"); + } + app.synthetic.clear(); + } +} + +#[test] +fn ui_key_rejects_bad_params_before_queueing_input() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let cases = [ + (json!({"key": "N", "ctl": true}), "ctl"), + (json!({"key": "N", "modifiers": {"space": true}}), "space"), + (json!({"key": "N", "ctrl": "yes"}), "ctrl"), + (json!({"key": "N", "modifiers": {"shift": 1}}), "shift"), + (json!({"key": "N", "modifiers": "ctrl"}), "modifiers"), + (json!({"key": 5}), "key"), + (json!({}), "key"), + (json!({"key": "NoSuchKey"}), "NoSuchKey"), + ]; + for (params, names) in cases { + rejected(&mut app, &ctx, "ui.key", params, names); + } + for params in [json!({"key": "N", "ctrl": true}), json!({"key": "N", "shift": false, "modifiers": {"ctrl": true}})] { + let (req, _rx) = ControlRequest::new("ui.key", params.clone()); + assert!(matches!(handle(&mut app, &ctx, &req), Outcome::AfterInput), "{params}"); + assert!(matches!(app.synthetic.first(), Some(egui::Event::Key { key: egui::Key::N, modifiers, .. }) if modifiers.ctrl), "{params}"); + app.synthetic.clear(); + } +} + +#[test] +fn ui_screenshot_rejects_bad_params_before_capturing() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + for (params, names) in [(json!({"focus": "yes"}), "focus"), (json!({"path": 5}), "path"), (json!({"pth": "shot.png"}), "pth")] { + rejected(&mut app, &ctx, "ui.screenshot", params, names); + } + for (params, path) in [(json!({}), None), (Value::Null, None), (json!({"path": "shot.png", "focus": false}), Some("shot.png"))] { + let (req, _rx) = ControlRequest::new("ui.screenshot", params.clone()); + let Outcome::Screenshot { path: queued, .. } = handle(&mut app, &ctx, &req) else { panic!("{params}: expected a capture") }; + assert_eq!(queued.as_deref(), path, "{params}"); + } +} + +/// A key event's modifiers, as `ui.key` queued them. +fn key_modifiers(app: &mut PhotocraftApp, ctx: &egui::Context, params: Value) -> egui::Modifiers { + app.synthetic.clear(); + let (req, _rx) = ControlRequest::new("ui.key", params.clone()); + assert!(matches!(handle(app, ctx, &req), Outcome::AfterInput), "{params}"); + match app.synthetic.first() { + Some(egui::Event::Key { modifiers, .. }) => *modifiers, + other => panic!("{params}: expected a key event, got {other:?}"), + } +} + +#[test] +fn ui_key_ctrl_reaches_shortcuts_like_a_real_ctrl_press() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let ctrl = key_modifiers(&mut app, &ctx, json!({"key":"N","ctrl":true})); + let command = key_modifiers(&mut app, &ctx, json!({"key":"N","command":true})); + let grouped = key_modifiers(&mut app, &ctx, json!({"key":"N","modifiers":{"ctrl":true}})); + assert_eq!(ctrl, grouped, "a grouped flag must match the top-level one"); + if cfg!(target_os = "macos") { + // Two different keys: Control is not ⌘, and only ⌘ matches a shortcut. + assert!(ctrl.ctrl && !ctrl.command && !ctrl.mac_cmd, "{ctrl:?}"); + assert!(command.command && command.mac_cmd && !command.ctrl, "{command:?}"); + } else { + // One key under two names, and shortcuts are matched on `command`, so asking for + // either must reach them: Ctrl+N has to open New Document, not do nothing. + assert_eq!(ctrl, command, "ctrl and command are the same key off the Mac"); + assert!(ctrl.command && ctrl.ctrl && !ctrl.mac_cmd, "{ctrl:?}"); + } + let plain = key_modifiers(&mut app, &ctx, json!({"key":"N"})); + assert_eq!(plain, egui::Modifiers::default(), "{plain:?}"); + let shift_alt = key_modifiers(&mut app, &ctx, json!({"key":"N","shift":true,"alt":true})); + assert!(shift_alt.shift && shift_alt.alt && !shift_alt.command && !shift_alt.ctrl, "{shift_alt:?}"); +} + +/// FILE-215-3: `filterMaskTarget` on a layer without a filter mask is refused before anything +/// changes, so the layer mask stays targeted. +#[test] +fn ui_set_filter_mask_target_needs_a_smart_object_with_filters() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"maskTarget": true}))["ok"], true); + let bad = call(&mut app, &ctx, "ui.set", json!({"filterMaskTarget": true})); + assert_eq!(bad["ok"], false, "{bad}"); + assert!(app.ui.mask_target, "the layer mask stays targeted"); + assert_eq!(app.ui.filter_mask_target, None); + // A smart object with smart filters takes it. + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + app.run("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); + // Not while a single colour channel is targeted: nothing would end up targeted. + app.session.active_mut().unwrap().channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Color(0); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"filterMaskTarget": true}))["ok"], false); + app.session.active_mut().unwrap().channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Composite; + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"filterMaskTarget": true}))["ok"], true); + assert!(app.filter_mask_targeted()); + // Untargeting it ends its view, which would otherwise keep it targeted. + app.run("paint.stroke", json!({"points": [[4, 4]], "size": 4, "hardness": 1, "color": "#000000", "target": "filterMask"})).unwrap(); + app.run("view.layerMask", json!({"mode": "gray", "mask": "filter"})).unwrap(); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"filterMaskTarget": false}))["ok"], true); + assert!(!app.filter_mask_targeted()); + assert!(photocraft_engine::mask_view_cmds::current(app.session.active().unwrap()).is_none()); + // Targeting the pixels untargets it too. + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"filterMaskTarget": true}))["ok"], true); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"maskTarget": false}))["ok"], true); + assert!(!app.filter_mask_targeted()); + assert_eq!(crate::canvas::paint_target(&app), json!("pixels")); +} + +/// FILE-215-3: with the filter mask shown (⌥-click its thumbnail), targeting the layer mask +/// ends that view, and the brush paints the layer mask. +#[test] +fn ui_set_mask_target_ends_a_filter_mask_view() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + app.run("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.run("paint.stroke", json!({"points": [[4, 4]], "size": 4, "hardness": 1, "color": "#000000", "target": "filterMask"})).unwrap(); + app.run("view.layerMask", json!({"mode": "gray", "mask": "filter"})).unwrap(); + app.sync_mask_targets(); + assert!(app.filter_mask_targeted()); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"maskTarget": true}))["ok"], true); + assert!(photocraft_engine::mask_view_cmds::current(app.session.active().unwrap()).is_none(), "the filter mask view ends"); + assert!(app.layer_mask_targeted()); + assert!(!app.filter_mask_targeted()); + assert_eq!(crate::canvas::paint_target(&app), json!("mask")); + let target = crate::canvas::paint_target(&app); + app.run("paint.stroke", json!({"points": [[20, 20]], "size": 4, "hardness": 1, "color": "#000000", "target": target})).unwrap(); + let st = app.session.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert_eq!(l.mask.as_ref().unwrap().value(20, 20), 0.0, "the stroke went into the layer mask"); + let photocraft_doc::LayerContent::Smart(sm) = &l.content else { panic!("smart object") }; + assert_eq!(sm.filter_mask.as_ref().unwrap().value(20, 20), 1.0, "not into the filter mask"); +} From 9fbb2af45ff0db08e62e23d91690f0c804e37e18 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:27 +0000 Subject: [PATCH 095/259] refactor(ui-egui): move prefs_ui.rs tests to prefs_ui/tests.rs --- crates/ui-egui/src/prefs_ui.rs | 2011 +------------------------- crates/ui-egui/src/prefs_ui/tests.rs | 2001 +++++++++++++++++++++++++ 2 files changed, 2002 insertions(+), 2010 deletions(-) create mode 100644 crates/ui-egui/src/prefs_ui/tests.rs diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index 1c7fbddb1e..4d639fa00d 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -2746,2013 +2746,4 @@ mod shortcut_capture_tests; mod shortcut_set_tests; #[cfg(test)] -mod tests { - #[test] - fn memory_usage_has_a_dedicated_explanation_and_keeps_its_value() { - use egui_kittest::{Harness, kittest::Queryable}; - let values = json!({"memoryUsageMb":50000}).as_object().unwrap().clone(); - assert!(!field_visible("performance", &values, "memoryUsageMb", "")); - let mut h = Harness::builder() - .with_size(vec2(680.0, 350.0)) - .build_ui_state(|ui, values| section_fields(ui, "performance", values, &["memoryUsageMb".into()], crate::i18n::Lang::EN, None, ""), values); - h.run_steps(2); - h.get_by_label("Memory Usage"); - h.get_by_label("Per-document RAM limit (MB)"); - h.get_by_label("Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded."); - h.get_by_label("Applies immediately when saved. Memory is not reserved in advance."); - assert_eq!(h.state()["memoryUsageMb"], 50000); - } - - #[test] - fn graphics_dropdowns_are_named_for_their_settings() { - use egui::accesskit::Role; - use egui_kittest::Harness; - use egui_kittest::kittest::{NodeT, Queryable}; - - let obj = json!({"gpuBackend": "auto", "gpuAdapter": ""}).as_object().unwrap().clone(); - let mut h = Harness::builder() - .with_size(vec2(700.0, 500.0)) - .with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0])) - .build_ui_state(|ui, obj| gpu_status_rows(ui, None, None, obj), obj); - h.run_steps(2); - h.get_by_label("Advanced").click(); - h.run_steps(2); - let labels: Vec = h.query_all_by_role(Role::ComboBox).filter_map(|n| n.accesskit_node().label()).collect(); - assert!(labels.iter().any(|label| label == "GPU Backend"), "{labels:?}"); - if cfg!(target_os = "linux") { - assert!(labels.iter().any(|label| label == "GPU adapter"), "{labels:?}"); - } - assert!(!labels.iter().any(|label| label == "Graphics"), "the section title names neither control: {labels:?}"); - } - - #[test] - fn colour_preferences_take_a_typed_hex_value() { - // #668: the canvas colour (and every colour preference) showed its hex but couldn't take one. - use egui::accesskit::Role; - use egui_kittest::kittest::Queryable; - let mut h = egui_kittest::Harness::new_ui_state(|ui, rgb: &mut [u8; 3]| super::hex_field(ui, "interface.canvasCustomColor", rgb), [0x28, 0x28, 0x28]); - h.run(); - assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("#282828")); - h.get_by_role(Role::TextInput).click(); - h.run_steps(1); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.run_steps(1); - for ch in "#80".chars() { - h.event(egui::Event::Text(ch.to_string())); - h.run_steps(1); - } - // A partial value stays as typed and leaves the colour alone. - assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("#80")); - assert_eq!(*h.state(), [0x28, 0x28, 0x28]); - for ch in "8080".chars() { - h.event(egui::Event::Text(ch.to_string())); - h.run_steps(1); - } - assert_eq!(*h.state(), [0x80, 0x80, 0x80]); - } - - #[test] - fn quick_export_controls_match_selected_format() { - let mut obj = serde_json::to_value(photocraft_engine::prefs::Export::default()).unwrap().as_object().unwrap().clone(); - assert!(!export_field_visible(&obj, "jpegQuality")); - assert!(!export_field_visible(&obj, "webpLossless")); - assert!(!export_field_visible(&obj, "webpQuality")); - - obj.insert("quickExportFormat".into(), json!("jpg")); - assert!(export_field_visible(&obj, "jpegQuality")); - assert!(!export_field_visible(&obj, "webpLossless")); - assert!(!export_field_visible(&obj, "webpQuality")); - - obj.insert("quickExportFormat".into(), json!("webp")); - assert!(!export_field_visible(&obj, "jpegQuality")); - assert!(export_field_visible(&obj, "webpLossless")); - assert!(!export_field_visible(&obj, "webpQuality"), "lossless WebP does not have a quality setting"); - - obj.insert("webpLossless".into(), json!(false)); - assert!(export_field_visible(&obj, "webpQuality")); - assert_eq!(humanize("webpLossless"), "Lossless"); - assert_eq!(humanize("webpQuality"), "Quality"); - obj.insert("quickExportFormat".into(), json!("exr")); - for key in ["jpegQuality", "webpLossless", "webpQuality", "convertToSrgb", "metadata"] { - assert!(!export_field_visible(&obj, key), "EXR must not offer ignored web settings: {key}"); - } - } - - #[test] - fn the_nudge_pause_is_hidden_while_nudges_are_not_bundled() { - let mut tools = Map::new(); - tools.insert("bundleNudges".into(), json!(true)); - assert!(tools_field_visible(&tools, "nudgeBundlePauseMs")); - assert!(tools_field_visible(&tools, "bundleNudges")); - tools.insert("bundleNudges".into(), json!(false)); - assert!(!tools_field_visible(&tools, "nudgeBundlePauseMs")); - assert!(tools_field_visible(&tools, "bundleNudges") && tools_field_visible(&tools, "showTooltips")); - // A section without the flag (an older preferences object) shows the field. - assert!(tools_field_visible(&Map::new(), "nudgeBundlePauseMs")); - assert_eq!(humanize("bundleNudges"), "Bundle Arrow-Key Nudges"); - assert_eq!(humanize("nudgeBundlePauseMs"), "Nudge Bundle Pause (ms)"); - } - - #[test] - fn rendering_mode_display_respects_explicit_mode_and_legacy_disable() { - let legacy = serde_json::json!({"useGpu": false, "gpuBackend": "auto"}); - assert_eq!(super::rendering_mode_value(legacy.as_object().unwrap()), "cpu"); - let explicit = serde_json::json!({"renderingMode": "gpu", "useGpu": false, "gpuBackend": "cpu"}); - assert_eq!(super::rendering_mode_value(explicit.as_object().unwrap()), "gpu"); - let automatic = serde_json::json!({"renderingMode": null, "useGpu": true, "gpuBackend": "auto"}); - assert_eq!(super::rendering_mode_value(automatic.as_object().unwrap()), "auto"); - } - - #[test] - fn preferences_search_matches_editable_fields_across_sections() { - let values = prefs::Preferences::default().to_json(); - let contains = |needle: &str, section: &str| preference_sections(&values, needle).iter().any(|(id, _)| *id == section); - assert!(contains("UI Scale", "interface")); - assert!(contains("placeholder", "type")); - assert!(contains("performance", "performance")); - assert!(contains("interface.uiScale", "interface")); - assert!(preference_sections(&values, "this setting does not exist").is_empty()); - assert_eq!(preference_sections(&values, "").len(), SECTIONS.len()); - } - - #[test] - fn preferences_dialog_width_follows_its_resizable_area() { - let prefs = serde_json::json!({"__prefsui": "prefs"}); - let prefs = prefs.as_object().unwrap(); - assert_eq!(super::width(prefs, 200.0), Some(380.0)); - assert_eq!(super::width(prefs, 800.0), Some(800.0)); - // A dialog resized wider than it opens is filled, not left with empty space (#7420). - assert_eq!(super::width(prefs, 3000.0), Some(3000.0)); - let shortcuts = serde_json::json!({"__prefsui": "shortcuts"}); - assert_eq!(super::width(shortcuts.as_object().unwrap(), 3000.0), Some(720.0)); - } - - #[test] - fn preferences_settings_fill_the_dialog_down_to_the_buttons() { - // The settings area plus the button row (spacing, 8 pt gap, buttons) stays inside what the - // resizable area gives it, at any size: the area grows to fit its content, so asking for - // more would make the dialog grow every frame. The area follows the dialog's size (#7420). - for available in [300.0, 600.0, 1400.0] { - let h = super::settings_height(available, 4.0, 30.0); - assert!(h + 4.0 + 8.0 + 30.0 <= available, "{available}"); - assert!(h + 4.0 + 8.0 + 30.0 + 8.0 >= available, "{available}"); - } - assert_eq!(super::settings_height(1400.0, 4.0, 30.0) - super::settings_height(600.0, 4.0, 30.0), 800.0); - assert_eq!(super::settings_height(50.0, 4.0, 30.0), 160.0); - } - use super::*; - use std::sync::{Arc, Mutex}; - - #[test] - fn appearance_resolves_both_saved_themes_and_follows_system() { - let mut interface = prefs::Interface { appearance_mode: AppearanceMode::Auto, ..prefs::Interface::default() }; - assert_eq!(selected_theme(&interface, Some(egui::Theme::Dark)), ThemeKind::ProMedium); - assert_eq!(selected_theme(&interface, Some(egui::Theme::Light)), ThemeKind::ProLight); - interface.dark_theme = DarkTheme::Studio; - interface.light_theme = LightTheme::Classic; - assert_eq!(selected_theme(&interface, Some(egui::Theme::Dark)), ThemeKind::Studio); - assert_eq!(selected_theme(&interface, Some(egui::Theme::Light)), ThemeKind::Classic); - interface.appearance_mode = AppearanceMode::Dark; - assert_eq!(selected_theme(&interface, Some(egui::Theme::Light)), ThemeKind::Studio); - interface.appearance_mode = AppearanceMode::Light; - assert_eq!(selected_theme(&interface, Some(egui::Theme::Dark)), ThemeKind::Classic); - } - - #[test] - fn breeze_themes_are_chosen_by_preference_and_fix_the_matching_mode() { - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - for (id, kind, mode) in [ - ("breezeLight", ThemeKind::BreezeLight, AppearanceMode::Light), - ("breezeDark", ThemeKind::BreezeDark, AppearanceMode::Dark), - ("softLight", ThemeKind::SoftLight, AppearanceMode::Light), - ("softDark", ThemeKind::SoftDark, AppearanceMode::Dark), - ] { - app.run("prefs.set", json!({"path": "interface.theme", "value": id})).unwrap(); - tick(&mut app, &ctx); - let interface = app.session.prefs().interface.clone(); - assert_eq!(interface.appearance_mode, mode, "{id}"); - assert_eq!(selected_theme(&interface, None), kind, "{id}"); - assert_eq!(app.ui.theme, kind, "{id}"); - } - // The two slots are independent: choosing the dark one left the light choice alone. - assert_eq!(app.session.prefs().interface.light_theme, LightTheme::SoftLight); - assert_eq!(app.session.prefs().interface.dark_theme, DarkTheme::SoftDark); - } - - #[test] - fn auto_uses_native_system_theme_when_egui_does_not_report_one() { - let (mut app, _) = app_with_store(); - app.services.system_theme = Some(Box::new(|_| Some(egui::Theme::Light))); - app.run("prefs.set", json!({"path": "interface.appearanceMode", "value": "auto"})).unwrap(); - app.run("prefs.set", json!({"path": "interface.appearanceMode", "value": "auto"})).unwrap(); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - assert_eq!(app.ui.theme, ThemeKind::ProLight); - } - - #[test] - fn appearance_button_cycles_modes_without_losing_theme_choices() { - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("prefs.set", json!({"values": {"interface.darkTheme": "studio", "interface.lightTheme": "classic"}})).unwrap(); - for (mode, visible) in - [(AppearanceMode::Auto, ThemeKind::Studio), (AppearanceMode::Light, ThemeKind::Classic), (AppearanceMode::Dark, ThemeKind::Studio)] - { - cycle_appearance(&mut app, &ctx); - assert_eq!(app.session.prefs().interface.appearance_mode, mode); - assert_eq!(app.ui.theme, visible); - assert_eq!(app.session.prefs().interface.dark_theme, DarkTheme::Studio); - assert_eq!(app.session.prefs().interface.light_theme, LightTheme::Classic); - } - } - - #[test] - fn darken_and_lighten_interface_step_through_photoshops_brightnesses_and_stop_at_the_ends() { - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - sync_appearance(&mut app, &ctx); - assert_eq!(app.ui.theme, ThemeKind::ProMedium, "Photoshop's default brightness"); - let press = |app: &mut PhotocraftApp, id: &str| crate::menus::invoke(app, &ctx, id, json!({})).unwrap(); - for expected in [ThemeKind::ProLightGray, ThemeKind::ProLight, ThemeKind::ProLight] { - press(&mut app, "view.lightenInterface"); - assert_eq!(app.ui.theme, expected); - } - // Saved like a choice in Preferences › Interface: the light slot and the Light appearance. - let i = &app.session.prefs().interface; - assert_eq!((i.appearance_mode, i.light_theme), (AppearanceMode::Light, LightTheme::ProLight)); - for expected in [ThemeKind::ProLightGray, ThemeKind::ProMedium, ThemeKind::Pro, ThemeKind::Pro] { - press(&mut app, "view.darkenInterface"); - assert_eq!(app.ui.theme, expected); - } - let i = &app.session.prefs().interface; - assert_eq!((i.appearance_mode, i.dark_theme), (AppearanceMode::Dark, DarkTheme::Pro)); - // Another theme steps from the nearest brightness. - for (theme, id, expected) in [ - ("studio", "view.darkenInterface", ThemeKind::Pro), - ("studio", "view.lightenInterface", ThemeKind::ProLightGray), - ("classic", "view.darkenInterface", ThemeKind::ProMedium), - ("classic", "view.lightenInterface", ThemeKind::ProLight), - ] { - app.run("prefs.set", json!({"path": "interface.theme", "value": theme})).unwrap(); - sync_appearance(&mut app, &ctx); - press(&mut app, id); - assert_eq!(app.ui.theme, expected, "{theme} {id}"); - } - } - - #[test] - fn ctrl_shift_f1_and_f2_darken_and_lighten_the_interface() { - for (id, shortcut) in [("view.darkenInterface", "Cmd+Shift+F1"), ("view.lightenInterface", "Cmd+Shift+F2")] { - assert_eq!(crate::shortcuts::default_shortcut(id).as_deref(), Some(shortcut), "{id}"); - } - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - sync_appearance(&mut app, &ctx); - let press = |app: &mut PhotocraftApp, key| { - let modifiers = egui::Modifiers::COMMAND | egui::Modifiers::SHIFT; - 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(); - }; - press(&mut app, egui::Key::F1); - assert_eq!(app.ui.theme, ThemeKind::Pro); - press(&mut app, egui::Key::F2); - press(&mut app, egui::Key::F2); - assert_eq!(app.ui.theme, ThemeKind::ProLightGray); - } - - fn appearance_frame(app: &mut PhotocraftApp, ctx: &egui::Context, appearance: Option) { - ctx.run_ui(egui::RawInput { system_theme: appearance, ..Default::default() }, |ui| tick(app, ui.ctx())).textures_delta.clear(); - } - - fn assert_palette(ctx: &egui::Context, kind: ThemeKind) { - let t = Tokens::get(ctx); - assert_eq!(t.kind, kind); - for style in [ctx.global_style(), ctx.style_of(egui::Theme::Light), ctx.style_of(egui::Theme::Dark)] { - assert_eq!(style.visuals.panel_fill, t.chrome); - assert_eq!(style.visuals.window_fill, t.card); - assert_eq!(style.visuals.override_text_color, Some(t.text)); - assert_eq!(style.visuals.widgets.inactive.bg_fill, t.field); - assert_eq!(style.visuals.dark_mode, t.dark()); - assert_eq!(style.text_styles[&egui::TextStyle::Body].size, if t.pro { 12.0 } else { 12.5 }); - } - assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::System); - } - - #[test] - fn auto_appearance_follows_live_changes_without_saving_resolved_palettes() { - for (dark, light) in [(ThemeKind::ProMedium, ThemeKind::StudioLight), (ThemeKind::SolarizedDark, ThemeKind::Adwaita)] { - let (mut app, store) = app_with_store(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, Default::default()); - app.run("prefs.set", json!({"values": {"interface.appearanceMode": "auto", "interface.darkTheme": dark.id(), "interface.lightTheme": light.id()}})) - .unwrap(); - appearance_frame(&mut app, &ctx, Some(egui::Theme::Light)); - let revision = app.session.prefs.rev(); - let interface = app.session.prefs().interface.clone(); - let saved = store.lock().unwrap().clone().unwrap(); - assert_eq!(stored(&store)["interface"]["appearanceMode"], "auto"); - let gpu_style = canvas_style(&app); - for (appearance, expected) in [(Some(egui::Theme::Light), light), (Some(egui::Theme::Dark), dark), (Some(egui::Theme::Light), light), (None, dark)] - { - appearance_frame(&mut app, &ctx, appearance); - assert_palette(&ctx, expected); - assert_eq!(app.ui.theme, expected); - assert_eq!(app.session.prefs().interface, interface); - assert_eq!(app.session.prefs.rev(), revision); - assert_eq!(store.lock().unwrap().as_ref(), Some(&saved)); - assert_eq!(canvas_style(&app), gpu_style); - assert_eq!(pasteboard_color(&app), None); - } - // A fresh launch resolves its saved Auto choice against the new OS input. - for (appearance, expected) in [(Some(egui::Theme::Light), light), (Some(egui::Theme::Dark), dark), (None, dark)] { - let (mut restarted, store) = app_with_saved(Some(saved.clone())); - let fresh = egui::Context::default(); - PhotocraftApp::setup_context(&fresh, Default::default()); - appearance_frame(&mut restarted, &fresh, appearance); - assert_palette(&fresh, expected); - assert_eq!(restarted.ui.theme, expected); - assert_eq!(restarted.session.prefs().interface, interface); - assert_eq!(store.lock().unwrap().as_ref(), Some(&saved)); - } - app.run("prefs.set", json!({"values": {"interface.canvasColor": "custom", "interface.canvasCustomColor": "#123456"}})).unwrap(); - for appearance in [Some(egui::Theme::Light), Some(egui::Theme::Dark)] { - appearance_frame(&mut app, &ctx, appearance); - assert_eq!(pasteboard_color(&app), Some(Color32::from_rgb(0x12, 0x34, 0x56))); - assert_eq!(canvas_style(&app), gpu_style); - } - } - } - - #[test] - fn manual_theme_tokens_and_global_styles_stay_fixed_across_os_changes() { - let (mut app, store) = app_with_store(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, Default::default()); - for kind in ThemeKind::ALL { - app.run("prefs.set", json!({"path": "interface.theme", "value": kind.id()})).unwrap(); - appearance_frame(&mut app, &ctx, Some(egui::Theme::Dark)); - let interface = app.session.prefs().interface.clone(); - let revision = app.session.prefs.rev(); - let saved = store.lock().unwrap().clone().unwrap(); - assert_eq!(interface.appearance_mode, if Tokens::for_kind(kind).dark() { AppearanceMode::Dark } else { AppearanceMode::Light }); - for appearance in [Some(egui::Theme::Dark), Some(egui::Theme::Light), Some(egui::Theme::Dark), None] { - appearance_frame(&mut app, &ctx, appearance); - assert_palette(&ctx, kind); - assert_eq!(Tokens::get(&ctx), Tokens::for_kind(kind)); - assert_eq!(app.ui.theme, kind); - assert_eq!(app.session.prefs().interface, interface); - assert_eq!(app.session.prefs.rev(), revision); - assert_eq!(store.lock().unwrap().as_ref(), Some(&saved)); - } - } - } - - #[test] - fn auto_appearance_replaces_a_restored_egui_dark_pin() { - let (mut app, _) = app_with_saved(Some(json!({"interface": {"appearanceMode": "auto"}}).to_string())); - let ctx = egui::Context::default(); - ctx.set_theme(egui::ThemePreference::Dark); - assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::Dark); - appearance_frame(&mut app, &ctx, Some(egui::Theme::Light)); - assert_palette(&ctx, ThemeKind::ProLight); - assert_eq!(app.session.prefs().interface.appearance_mode, AppearanceMode::Auto); - // A restored pin must also clear when the concrete PhotoCraft palette stays the same. - ctx.set_theme(egui::ThemePreference::Dark); - appearance_frame(&mut app, &ctx, Some(egui::Theme::Light)); - assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::System); - assert_palette(&ctx, ThemeKind::ProLight); - appearance_frame(&mut app, &ctx, Some(egui::Theme::Dark)); - assert_palette(&ctx, ThemeKind::ProMedium); - assert_eq!(app.session.prefs().interface.appearance_mode, AppearanceMode::Auto); - } - - #[test] - fn system_theme_menu_choice_stays_checked_as_the_appearance_changes() { - let (mut app, store) = app_with_store(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, Default::default()); - app.run("prefs.set", json!({"values": {"interface.darkTheme": "solarizedDark", "interface.lightTheme": "adwaita"}})).unwrap(); - appearance_frame(&mut app, &ctx, Some(egui::Theme::Light)); - crate::menus::invoke(&mut app, &ctx, "window.theme.system", json!({})).unwrap(); - appearance_frame(&mut app, &ctx, Some(egui::Theme::Light)); - let interface = app.session.prefs().interface.clone(); - let saved = store.lock().unwrap().clone().unwrap(); - let revision = app.session.prefs.rev(); - for appearance in [Some(egui::Theme::Light), Some(egui::Theme::Dark), None] { - appearance_frame(&mut app, &ctx, appearance); - let items = crate::menus::menu_items(&app); - let item = |id: &str| items.iter().find(|i| i.id == id).unwrap(); - assert_eq!(item("window.theme.system").checked, Some(true)); - assert!(item("window.theme.system").enabled); - assert_eq!(item("window.theme.system").path, ["Window", "Theme"]); - for kind in ThemeKind::ALL { - assert_eq!(item(&format!("window.theme.{}", kind.id())).checked, Some(false)); - } - assert_eq!(app.session.prefs().interface.appearance_mode, AppearanceMode::Auto); - assert_eq!(app.session.prefs().interface, interface); - assert_eq!(app.session.prefs.rev(), revision); - assert_eq!(store.lock().unwrap().as_ref(), Some(&saved)); - } - crate::menus::invoke(&mut app, &ctx, "window.theme.solarizedDark", json!({})).unwrap(); - for appearance in [Some(egui::Theme::Light), Some(egui::Theme::Dark)] { - appearance_frame(&mut app, &ctx, appearance); - assert_palette(&ctx, ThemeKind::SolarizedDark); - let items = crate::menus::menu_items(&app); - let item = |id: &str| items.iter().find(|i| i.id == id).unwrap(); - assert_eq!(item("window.theme.solarizedDark").checked, Some(true)); - assert_eq!(item("window.theme.system").checked, Some(false)); - assert_eq!(stored(&store)["interface"]["appearanceMode"], "dark"); - assert_eq!(app.session.prefs().interface.light_theme, LightTheme::Adwaita); - } - } - - #[test] - fn preferences_interface_offers_and_applies_sync_with_system() { - use egui_kittest::{Harness, kittest::Queryable}; - let (mut app, store) = app_with_store(); - app.run("prefs.set", json!({"values": {"interface.language": "en", "interface.darkTheme": "solarizedDark", "interface.lightTheme": "adwaita"}})) - .unwrap(); - let interface = app.session.prefs().interface.clone(); - open_preferences(&mut app, "interface"); - let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); - h.input_mut().system_theme = Some(egui::Theme::Light); - h.run_steps(4); - for label in ["Adwaita", "Adwaita dark", "Solarized dark"] { - assert!(h.query_by_label(label).is_some(), "missing theme choice {label}"); - } - h.get_by_value("Dark").click(); - h.run_steps(2); - h.get_by_label("Sync with system").click(); - h.run_steps(2); - h.get_by_label("Apply").click(); - h.run_steps(4); - assert_eq!(h.state().session.prefs().interface.appearance_mode, AppearanceMode::Auto); - assert_eq!(h.state().session.prefs().interface.dark_theme, interface.dark_theme); - assert_eq!(h.state().session.prefs().interface.light_theme, interface.light_theme); - assert_eq!(h.state().session.prefs().interface.theme, interface.theme); - assert_palette(&h.ctx, ThemeKind::Adwaita); - assert_eq!(stored(&store)["interface"]["appearanceMode"], "auto"); - let saved = store.lock().unwrap().clone().unwrap(); - let (mut restarted, reloaded) = app_with_saved(Some(saved.clone())); - let fresh = egui::Context::default(); - PhotocraftApp::setup_context(&fresh, Default::default()); - appearance_frame(&mut restarted, &fresh, Some(egui::Theme::Dark)); - assert_palette(&fresh, ThemeKind::SolarizedDark); - assert_eq!(restarted.session.prefs().interface.appearance_mode, AppearanceMode::Auto); - assert_eq!(restarted.session.prefs().interface.dark_theme, interface.dark_theme); - assert_eq!(restarted.session.prefs().interface.light_theme, interface.light_theme); - assert_eq!(restarted.session.prefs().interface.theme, interface.theme); - assert_eq!(reloaded.lock().unwrap().as_ref(), Some(&saved)); - } - - #[test] - fn theme_star_saves_favorite_and_menu_groups_it() { - use egui_kittest::{Harness, kittest::Queryable}; - let (mut app, _) = app_with_store(); - open_preferences(&mut app, "interface"); - let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); - h.run_steps(4); - h.get_by_label("Classic").hover(); - h.run_steps(2); - h.get_by_label("Add to favorites: Classic").click(); - h.run_steps(2); - h.get_by_label("Apply").click(); - h.run_steps(2); - assert_eq!(h.state().session.prefs().interface.favorite_themes, vec![SavedTheme::Classic]); - assert!(h.query_by_label("Remove from favorites: Classic").is_some()); - let (light, dark) = favorite_theme_groups(&[SavedTheme::Studio, SavedTheme::Classic, SavedTheme::Adwaita]); - assert_eq!(light, vec![ThemeKind::Classic, ThemeKind::Adwaita]); - assert_eq!(dark, vec![ThemeKind::Studio]); - } - - /// The favourite star badge overhangs its swatch; showing it on hover must not move the swatches - /// after it, or the row would shift under the pointer. - #[test] - fn theme_star_badge_on_hover_does_not_move_the_next_swatch() { - use egui_kittest::{Harness, kittest::Queryable}; - let (mut app, _) = app_with_store(); - open_preferences(&mut app, "interface"); - let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); - h.run_steps(4); - let first = h.get_by_label("Classic").rect(); - let next = h.get_by_label("Adwaita").rect(); - h.hover_at(first.right_top() + vec2(-3.0, 3.0)); - h.run_steps(3); - assert!(h.query_by_label("Add to favorites: Classic").is_some(), "the badge shows while the swatch is hovered"); - assert_eq!(h.get_by_label("Classic").rect(), first); - assert_eq!(h.get_by_label("Adwaita").rect(), next); - } - - #[test] - fn preferences_interface_shows_language_without_scrolling() { - // #2532: in a small window the theme cards filled the page and Language sat out of view - // below them. Like Photoshop, Presentation follows Appearance and both fit. - use egui_kittest::{Harness, kittest::Queryable}; - let (mut app, _) = app_with_store(); - app.run("prefs.set", json!({"values": {"interface.language": "en"}})).unwrap(); - open_preferences(&mut app, "interface"); - let mut h = Harness::builder().with_size(vec2(1000.0, 750.0)).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); - h.run_steps(4); - let language = h.query_all_by_label("Language").next().expect("the Language row").rect(); - let dark = h.query_all_by_label("Dark Theme").next().expect("the dark theme row").rect(); - let ok = h.get_by_label("OK").rect(); - assert!(dark.bottom() < language.top(), "Presentation {language:?} follows the theme swatches {dark:?}"); - assert!(language.bottom() < ok.top() - 20.0, "Language {language:?} must show above the buttons {ok:?} without scrolling"); - // Every theme in the option lists gets a swatch, Breeze included. - for (id, _) in LIGHT_THEME_OPTIONS.iter().chain(DARK_THEME_OPTIONS) { - let label = choice_label(id); - assert!(h.query_by_label(&label).is_some(), "missing theme swatch {label}"); - } - assert!(h.query_by_label("Breeze light").is_some() && h.query_by_label("Breeze dark").is_some()); - } - - #[test] - fn preferences_interface_search_hides_rows_and_skips_empty_groups() { - use egui_kittest::{Harness, kittest::Queryable}; - let render = |search: &str| { - let (mut app, _) = app_with_store(); - app.run("prefs.set", json!({"values": {"interface.language": "en"}})).unwrap(); - let id = open_preferences(&mut app, "interface"); - app.ui.dialog_mut(id).unwrap().fields.insert("__search".into(), json!(search)); - let mut h = Harness::builder().with_size(vec2(1000.0, 750.0)).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); - h.run_steps(4); - h - }; - let shown = |h: &Harness<'_, PhotocraftApp>, label: &str| h.query_all_by_label(label).next().is_some(); - - let h = render("language"); - assert!(shown(&h, "Language") && shown(&h, "Presentation")); - for gone in ["Appearance", "Appearance Mode", "Dark Theme", "Options", "UI scale"] { - assert!(!shown(&h, gone), "\"language\" must not show {gone}"); - } - - let h = render("theme"); - assert!(shown(&h, "Appearance") && shown(&h, "Light Theme") && shown(&h, "Dark Theme") && shown(&h, "Breeze dark")); - for gone in ["Appearance Mode", "Presentation", "Language", "Options"] { - assert!(!shown(&h, gone), "\"theme\" must not show {gone}"); - } - - let h = render(""); - for group in ["Appearance", "Appearance Mode", "Presentation", "Options", "UI scale"] { - assert!(shown(&h, group), "an empty search shows {group}"); - } - } - - fn app_with_store() -> (PhotocraftApp, Arc>>) { - app_with_saved(None) - } - - fn app_with_saved(text: Option) -> (PhotocraftApp, Arc>>) { - let store: Arc>> = Arc::new(Mutex::new(text)); - (app_on(&store, Arc::default()), store) - } - - /// An app whose preferences live in `store`; writes fail while `fail` is set. - fn app_on(store: &Arc>>, fail: Arc) -> PhotocraftApp { - let (a, b) = (store.clone(), store.clone()); - let services = crate::Services { - load_prefs: Some(Box::new(move || a.lock().unwrap().clone())), - save_prefs: Some(Box::new(move |s: &str| { - if fail.load(std::sync::atomic::Ordering::Relaxed) { - return Err("storage is full".into()); - } - *b.lock().unwrap() = Some(s.to_string()); - Ok(()) - })), - ..Default::default() - }; - PhotocraftApp::new(photocraft_engine::Session::new(), services) - } - - fn stored(store: &Arc>>) -> Value { - serde_json::from_str(store.lock().unwrap().as_deref().unwrap_or("null")).unwrap() - } - - #[test] - fn a_wrongly_typed_value_resets_only_itself_and_is_repaired_on_disk() { - // #6611: one bad value used to reset every preference, on every launch. - let saved = json!({ - "fileHandling": {"recentFileCount": "ten", "autosaveMinutes": 5}, - "performance": {"historyStates": 12}, - "shortcuts": {"edit.fill": "Cmd+Shift+F", "file.open": 7}, - "futureSection": {"kept": true}, - }); - let (mut app, store) = app_with_saved(Some(saved.to_string())); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - let p = app.session.prefs(); - assert_eq!((p.file_handling.recent_file_count, p.file_handling.autosave_minutes, p.performance.history_states), (20, 5, 12)); - assert!(!app.ui.status.contains("reset"), "{}", app.ui.status); - let notice = app.ui.notices.iter().find(|n| n.title == "Some preferences were reset").expect("a notice names the bad values"); - let text = notice.text(¬ice.lines[0]); - assert!(text.contains("fileHandling.recentFileCount, shortcuts.file.open"), "{text}"); - // The file now holds the default in its place and keeps everything else. - let v = stored(&store); - assert_eq!(v["fileHandling"]["recentFileCount"], 20); - assert_eq!(v["fileHandling"]["autosaveMinutes"], 5); - assert_eq!(v["performance"]["historyStates"], 12); - assert_eq!(v["shortcuts"]["edit.fill"], "Cmd+Shift+F"); - assert!(v["shortcuts"].get("file.open").is_none()); - assert_eq!(v["futureSection"]["kept"], true, "keys this version doesn't know survive"); - // So the next launch loads cleanly. - let (mut next, _) = app_with_saved(store.lock().unwrap().clone()); - tick(&mut next, &ctx); - assert!(next.ui.notices.iter().all(|n| n.title != "Some preferences were reset")); - assert_eq!(next.session.prefs().file_handling.autosave_minutes, 5); - } - - #[test] - fn an_old_files_shift_tool_switch_migration_is_saved_with_the_new_version() { - // #5647: a file before version 2 loads with Use Shift Key for Tool Switch on. Saving - // writes that and the current version, so turning it off later isn't taken for the old - // default on the next launch. - let ctx = egui::Context::default(); - for saved in [ - json!({"version": 1, "tools": {"useShiftKeyForToolSwitch": false}, "futureSection": {"kept": true}}), - json!({"tools": {"useShiftKeyForToolSwitch": false}, "futureSection": {"kept": true}}), - ] { - let (mut app, store) = app_with_saved(Some(saved.to_string())); - tick(&mut app, &ctx); - assert!(app.session.prefs().tools.use_shift_key_for_tool_switch, "{saved}"); - app.run("prefs.set", json!({"values": {"performance.historyStates": 12}})).unwrap(); - tick(&mut app, &ctx); - let v = stored(&store); - assert_eq!(v["version"], json!(prefs::PREFS_VERSION), "{saved}"); - assert_eq!(v["tools"]["useShiftKeyForToolSwitch"], true, "{saved}"); - assert_eq!(v["futureSection"]["kept"], true, "keys this version doesn't know survive"); - app.run("prefs.set", json!({"values": {"tools.useShiftKeyForToolSwitch": false}})).unwrap(); - tick(&mut app, &ctx); - let (mut next, _) = app_with_saved(store.lock().unwrap().clone()); - tick(&mut next, &ctx); - assert!(!next.session.prefs().tools.use_shift_key_for_tool_switch, "{saved}: turned off, it stays off"); - } - } - - #[test] - fn an_old_sparse_file_keeps_another_instances_change() { - // Two instances on a version 1 file that lacks most keys: one changes a key the file - // doesn't have, the other then saves an unrelated change and must not write its default - // over it. - let saved = json!({"version": 1, "tools": {"useShiftKeyForToolSwitch": false}}); - let store = Arc::new(Mutex::new(Some(saved.to_string()))); - let ctx = egui::Context::default(); - let (mut a, mut b) = (app_on(&store, Arc::default()), app_on(&store, Arc::default())); - tick(&mut a, &ctx); - tick(&mut b, &ctx); - b.run("prefs.set", json!({"values": {"interface.theme": "studio"}})).unwrap(); - tick(&mut b, &ctx); - assert_eq!(stored(&store)["interface"]["theme"], "studio"); - a.run("prefs.set", json!({"values": {"performance.historyStates": 12}})).unwrap(); - tick(&mut a, &ctx); - let v = stored(&store); - assert_eq!((v["interface"]["theme"].as_str(), v["performance"]["historyStates"].as_u64()), (Some("studio"), Some(12))); - } - - #[test] - fn another_instances_shift_tool_switch_choice_beats_this_ones_migration() { - // Two instances migrate the same version 1 file. One turns the switch off and saves - // version 2; the other's unrelated save must not write its migrated "on" over that. - let saved = json!({"version": 1, "tools": {"useShiftKeyForToolSwitch": false}}); - let store = Arc::new(Mutex::new(Some(saved.to_string()))); - let ctx = egui::Context::default(); - let (mut a, mut b) = (app_on(&store, Arc::default()), app_on(&store, Arc::default())); - tick(&mut a, &ctx); - tick(&mut b, &ctx); - b.run("prefs.set", json!({"values": {"tools.useShiftKeyForToolSwitch": false}})).unwrap(); - tick(&mut b, &ctx); - assert_eq!(stored(&store)["tools"]["useShiftKeyForToolSwitch"], false); - a.run("prefs.set", json!({"values": {"performance.historyStates": 12}})).unwrap(); - tick(&mut a, &ctx); - let v = stored(&store); - assert_eq!((v["tools"]["useShiftKeyForToolSwitch"].as_bool(), v["performance"]["historyStates"].as_u64()), (Some(false), Some(12))); - assert_eq!(v["version"], json!(prefs::PREFS_VERSION)); - } - - #[test] - fn turning_the_shift_tool_switch_off_is_saved_over_another_instances_migration() { - // Two instances migrate the same version 1 file. B saves version 2 with the migrated "on"; - // the user then turns the switch off in A, which must be written. - let saved = json!({"version": 1, "tools": {"useShiftKeyForToolSwitch": false}}); - let store = Arc::new(Mutex::new(Some(saved.to_string()))); - let ctx = egui::Context::default(); - let (mut a, mut b) = (app_on(&store, Arc::default()), app_on(&store, Arc::default())); - tick(&mut a, &ctx); - tick(&mut b, &ctx); - b.run("prefs.set", json!({"values": {"performance.historyStates": 12}})).unwrap(); - tick(&mut b, &ctx); - assert_eq!(stored(&store)["tools"]["useShiftKeyForToolSwitch"], true); - a.run("prefs.set", json!({"values": {"tools.useShiftKeyForToolSwitch": false}})).unwrap(); - tick(&mut a, &ctx); - let v = stored(&store); - assert_eq!((v["tools"]["useShiftKeyForToolSwitch"].as_bool(), v["performance"]["historyStates"].as_u64()), (Some(false), Some(12))); - } - - #[test] - fn a_newer_files_version_is_kept_on_save() { - let saved = json!({"version": prefs::PREFS_VERSION + 1, "tools": {"useShiftKeyForToolSwitch": false}}); - let (mut app, store) = app_with_saved(Some(saved.to_string())); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - assert!(!app.session.prefs().tools.use_shift_key_for_tool_switch, "a newer file isn't migrated"); - app.run("prefs.set", json!({"values": {"performance.historyStates": 12}})).unwrap(); - tick(&mut app, &ctx); - let v = stored(&store); - assert_eq!(v["version"], json!(prefs::PREFS_VERSION + 1)); - assert_eq!(v["performance"]["historyStates"], 12); - } - - #[test] - fn merge_keeps_changes_made_elsewhere() { - let base = json!({"a": {"x": 1, "y": 1}, "list": [1], "gone": 1, "kept": 1}); - // Here: a.x changed, `gone` removed, `new` added. - let ours = json!({"a": {"x": 2, "y": 1}, "list": [1], "kept": 1, "new": 1}); - // There: a.y, `list` and `kept` changed, and a key this version doesn't know. - let mut theirs = json!({"a": {"x": 1, "y": 3}, "list": [1, 2], "gone": 1, "kept": 5, "future": true}); - merge_changes(&base, &ours, &mut theirs); - assert_eq!(theirs, json!({"a": {"x": 2, "y": 3}, "list": [1, 2], "kept": 5, "new": 1, "future": true})); - // Arrays are leaves: a list changed here replaces the stored one whole. - merge_changes(&json!({"list": [1]}), &json!({"list": [1, 3]}), &mut theirs); - assert_eq!(theirs["list"], json!([1, 3])); - // Nothing changed here: storage is left as it is, whatever it holds. - let mut odd = json!({"x": [7]}); - merge_changes(&ours, &ours, &mut odd); - assert_eq!(odd, json!({"x": [7]})); - // A value that changed type here replaces the stored one. - merge_changes(&json!({"a": 1}), &json!({"a": {"b": 2}}), &mut theirs); - assert_eq!(theirs["a"], json!({"b": 2})); - } - - #[test] - fn saving_keeps_preferences_another_instance_changed() { - let store = Arc::new(Mutex::new(None)); - let ctx = egui::Context::default(); - // Two browser tabs (or app windows) on the same storage. - let (mut a, mut b) = (app_on(&store, Arc::default()), app_on(&store, Arc::default())); - tick(&mut a, &ctx); - tick(&mut b, &ctx); - a.run("prefs.set", json!({"values": {"interface.theme": "studio"}})).unwrap(); - tick(&mut a, &ctx); - assert_eq!(stored(&store)["interface"]["theme"], "studio"); - // The other one, never reloaded, saves an unrelated change: the theme stays. - b.run("prefs.set", json!({"values": {"performance.historyStates": 12}})).unwrap(); - tick(&mut b, &ctx); - let v = stored(&store); - assert_eq!((v["interface"]["theme"].as_str(), v["performance"]["historyStates"].as_u64()), (Some("studio"), Some(12))); - // And the first one's next save keeps the second one's change. - a.run("prefs.set", json!({"values": {"interface.showTooltips": false}})).unwrap(); - tick(&mut a, &ctx); - let v = stored(&store); - assert_eq!(v["performance"]["historyStates"], 12); - assert_eq!(v["interface"]["showTooltips"], false); - // A value changed in both: the latest save wins. - b.run("prefs.set", json!({"values": {"interface.theme": "classic"}})).unwrap(); - tick(&mut b, &ctx); - assert_eq!(stored(&store)["interface"]["theme"], "classic"); - // Unreadable storage is overwritten with this instance's preferences. - *store.lock().unwrap() = Some("not json".into()); - a.run("prefs.set", json!({"values": {"performance.historyStates": 30}})).unwrap(); - tick(&mut a, &ctx); - let (mut c, _) = app_with_saved(store.lock().unwrap().clone()); - tick(&mut c, &ctx); - assert_eq!(c.session.prefs().performance.history_states, 30); - assert_eq!(c.session.prefs().interface.theme, Theme::Studio); - } - - #[test] - fn failed_preference_saves_are_retried() { - use std::sync::atomic::{AtomicBool, Ordering}; - let store = Arc::new(Mutex::new(None)); - let fail = Arc::new(AtomicBool::new(true)); - let mut app = app_on(&store, fail.clone()); - tick(&mut app, &egui::Context::default()); - app.run("prefs.set", json!({"values": {"interface.theme": "studio"}})).unwrap(); - // The write fails: reported, and retried after a backoff rather than marked saved. - assert_eq!(persist(&mut app, 100.0), Some(SAVE_RETRY_S)); - assert!(app.ui.status.starts_with("Couldn't save preferences: storage is full") && app.ui.status_error); - assert!(store.lock().unwrap().is_none()); - assert_eq!(persist(&mut app, 101.0), Some(1.0), "not due yet"); - // Storage works again: the pending change is written without another edit. - fail.store(false, Ordering::Relaxed); - assert_eq!(persist(&mut app, 102.0), None); - assert_eq!(stored(&store)["interface"]["theme"], "studio"); - assert_eq!(app.ui.status, "Preferences saved"); - assert_eq!(persist(&mut app, 103.0), None, "nothing left to save"); - - // A persistent failure backs off up to a cap and raises a notice once. - fail.store(true, Ordering::Relaxed); - app.run("prefs.set", json!({"values": {"interface.theme": "classic"}})).unwrap(); - let mut now = 200.0; - let mut delays = Vec::new(); - for _ in 0..6 { - let wait = persist(&mut app, now).unwrap(); - delays.push(wait); - now += wait; - } - assert_eq!(delays, [2.0, 4.0, 8.0, 16.0, SAVE_RETRY_MAX_S, SAVE_RETRY_MAX_S]); - assert_eq!(app.ui.notices.iter().filter(|n| n.error && n.title == "Preferences can't be saved").count(), 1); - // A newer change retries sooner than the backoff, but not on every frame. - app.run("prefs.set", json!({"values": {"interface.theme": "pro"}})).unwrap(); - assert_eq!(persist(&mut app, now - 29.0), Some(1.0)); - fail.store(false, Ordering::Relaxed); - assert_eq!(persist(&mut app, now - 28.0), None); - assert_eq!(stored(&store)["interface"]["theme"], "pro"); - assert!(app.ui.notices.is_empty(), "the notice goes once preferences are saved"); - } - - #[test] - fn auto_scale_preserves_system_scale() { - use prefs::UiScale::Auto; - // Whatever the monitor, 4K included: an unscaled desktop stays at 100% (#1278), and a - // fractional or below-100% system scale is the user's choice (#1072). - for dpi in [0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0] { - assert_eq!(display_scale(Auto, Some(dpi)), dpi); - } - assert_eq!(display_scale(Auto, None), 1.0); - assert_eq!(display_scale(Auto, Some(f32::NAN)), 1.0); - assert_eq!(display_scale(Auto, Some(-2.0)), 1.0); - } - - #[test] - fn scale_preferences_and_monitor_changes_apply_live() { - let (mut app, _) = app_with_store(); - let ctx = egui::Context::default(); - { - let mut step = |physical: egui::Vec2, native: f32, expected: f32| { - let mut input = egui::RawInput::default(); - let viewport = input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap(); - viewport.native_pixels_per_point = Some(native); - viewport.monitor_size = Some(physical / (native * ctx.zoom_factor())); - ctx.run_ui(input, |ui| tick(&mut app, ui.ctx())).textures_delta.clear(); - // Scale changes take effect on the following pass. - let mut input = egui::RawInput::default(); - let viewport = input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap(); - viewport.native_pixels_per_point = Some(native); - viewport.monitor_size = Some(physical / (native * ctx.zoom_factor())); - ctx.run_ui(input, |ui| tick(&mut app, ui.ctx())).textures_delta.clear(); - assert!((ctx.pixels_per_point() - expected).abs() < 1e-4); - }; - for _ in 0..4 { - step(vec2(3840.0, 2160.0), 1.0, 1.0); - } - step(vec2(1920.0, 1080.0), 1.0, 1.0); - step(vec2(3840.0, 2160.0), 1.5, 1.5); - step(vec2(3840.0, 2160.0), 1.25, 1.25); - step(vec2(2560.0, 1440.0), 1.75, 1.75); - step(vec2(3840.0, 2160.0), 1.0, 1.0); - } - for (pref, expected) in [ - ("200", 2.0), - ("125", 1.25), - ("150", 1.5), - ("100", 1.0), - ("105", 1.05), - ("110", 1.1), - ("115", 1.15), - ("120", 1.2), - ("95", 0.95), - ("90", 0.9), - ("85", 0.85), - ("80", 0.8), - ("auto", 1.5), - ] { - app.run("prefs.set", json!({"values": {"interface.uiScale": pref}})).unwrap(); - let mut input = egui::RawInput::default(); - input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().native_pixels_per_point = Some(1.5); - ctx.run_ui(input.clone(), |ui| tick(&mut app, ui.ctx())).textures_delta.clear(); - ctx.run_ui(input, |ui| tick(&mut app, ui.ctx())).textures_delta.clear(); - assert!((ctx.pixels_per_point() - expected).abs() < 1e-4); - } - } - - #[test] - fn intermediate_ui_scale_choices_can_be_applied_from_preferences() { - use egui_kittest::{Harness, kittest::Queryable}; - let (mut app, store) = app_with_store(); - app.run("prefs.set", json!({"path": "interface.uiScale", "value": "100"})).unwrap(); - open_preferences(&mut app, "interface"); - let mut h = Harness::builder().with_size(vec2(1400.0, 1100.0)).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); - h.run_steps(4); - let mut current = "100%"; - for (label, value) in [("105%", "105"), ("110%", "110"), ("115%", "115"), ("120%", "120")] { - h.get_by_value(current).click(); - h.run_steps(2); - h.get_by_label(label).click(); - h.run_steps(2); - h.get_by_label("Apply").click(); - h.run_steps(4); - assert_eq!(h.state().session.prefs().interface.ui_scale.name(), value); - assert_eq!(stored(&store)["interface"]["uiScale"], value); - current = label; - } - } - - #[test] - fn ui_font_size_commands_follow_themes_and_dpi_and_reset_live() { - let (mut app, _) = app_with_store(); - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, ThemeKind::Pro); - let mut input = egui::RawInput::default(); - input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().native_pixels_per_point = Some(1.5); - for (theme, scale, expected) in - [("pro", "100", 1.0), ("studio", "auto", 1.5), ("studioLight", "200", 2.0), ("proMedium", "100", 1.0), ("classic", "auto", 1.5)] - { - app.run("prefs.set", json!({"values": {"interface.uiFontSize": "large", "interface.theme": theme, "interface.uiScale": scale}})).unwrap(); - for _ in 0..3 { - ctx.run_ui(input.clone(), |ui| tick(&mut app, ui.ctx())).textures_delta.clear(); - } - assert!((ctx.pixels_per_point() - expected).abs() < 1e-4); - assert_eq!(ctx.fonts(|f| f.definitions().font_data["Inter"].tweak.scale), 16.0 / 12.0); - } - app.run("prefs.reset", json!({"path": "interface.uiFontSize"})).unwrap(); - for _ in 0..2 { - ctx.run_ui(input.clone(), |ui| tick(&mut app, ui.ctx())).textures_delta.clear(); - } - assert_eq!(ctx.fonts(|f| f.definitions().font_data["Inter"].tweak.scale), 1.0); - assert!((ctx.pixels_per_point() - 1.5).abs() < 1e-4, "resetting font size keeps UI Scale"); - } - - #[test] - fn recent_files_survive_a_restart_and_honour_the_count() { - let (mut app, store) = app_with_store(); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - app.push_recent("/work/a.psd"); - app.push_recent("/work/b.png"); - tick(&mut app, &ctx); - let saved = store.lock().unwrap().clone().unwrap(); - // A new app instance (a restart) gets the list back, newest first. - let (mut app2, _) = app_with_saved(Some(saved)); - tick(&mut app2, &ctx); - assert_eq!(app2.ui.recent_files, vec!["/work/b.png".to_string(), "/work/a.psd".to_string()]); - // Lowering "Recent File List Contains" shortens the menu at once; 0 turns it off. - app2.run("prefs.set", json!({"values": {"fileHandling.recentFileCount": 1}})).unwrap(); - tick(&mut app2, &ctx); - assert_eq!(app2.ui.recent_files, vec!["/work/b.png".to_string()]); - app2.push_recent("/work/c.tif"); - assert_eq!(app2.session.prefs().file_handling.recent_files, vec!["/work/c.tif".to_string()]); - app2.run("prefs.set", json!({"values": {"fileHandling.recentFileCount": 0}})).unwrap(); - tick(&mut app2, &ctx); - app2.push_recent("/work/d.tif"); - assert!(app2.ui.recent_files.is_empty()); - // Clearing the list in the Preferences dialog (or by an agent) reaches the menu. - app2.run("prefs.set", json!({"values": {"fileHandling.recentFileCount": 20, "fileHandling.recentFiles": ["/x.psd"]}})).unwrap(); - tick(&mut app2, &ctx); - assert_eq!(app2.ui.recent_files, vec!["/x.psd".to_string()]); - // A hostile count from a hand-edited preferences file is capped, not trusted. - app2.run("prefs.set", json!({"values": {"fileHandling.recentFileCount": 100}})).unwrap(); - app2.session.prefs.edit(|p| p.file_handling.recent_file_count = u32::MAX); - assert_eq!(app2.recent_cap(), 100); - } - - #[test] - fn brush_picker_view_survives_a_restart() { - let (mut app, store) = app_with_store(); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - app.ui.brush_picker_list.show_stroke = false; - app.ui.brush_picker_list.scale = 0.4; - crate::brush_picker::persist(&mut app, &ctx); - tick(&mut app, &ctx); - assert_eq!(stored(&store)["brushPicker"]["showStroke"], json!(false)); - // A restart gets the view back at startup, before the picker is ever opened. - let saved = store.lock().unwrap().clone().unwrap(); - 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.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. - 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); - } - - #[test] - fn selected_tool_survives_a_restart_without_option_changes() { - use crate::state::Tool; - let (mut app, store) = app_with_store(); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - assert_eq!(app.ui.tool, Tool::Brush); - // Every tool, including flyout-only tools, can be restored. Return to Brush last to - // prove selecting the default overwrites a previously remembered nondefault tool. - for tool in Tool::ALL.into_iter().chain([Tool::Brush]) { - app.ui.tool = tool; - crate::tool_memory::persist(&mut app, &ctx); - tick(&mut app, &ctx); - assert_eq!(stored(&store)["selectedTool"], serde_json::to_value(tool).unwrap()); - let (app2, _) = app_with_saved(store.lock().unwrap().clone()); - assert_eq!(app2.ui.tool, tool, "restored before the first frame"); - assert_eq!(app2.ui.group_tool(tool.key()), Some(tool)); - assert_eq!(app2.ui.tool_options, crate::state::ToolOptions::default()); - } - } - - #[test] - fn selected_tool_is_flushed_on_exit_without_another_frame() { - let (mut app, store) = app_with_store(); - app.ui.tool = crate::state::Tool::Move; - crate::tool_memory::save_on_exit(&mut app).unwrap(); - let (app2, _) = app_with_saved(store.lock().unwrap().clone()); - assert_eq!(app2.ui.tool, crate::state::Tool::Move); - } - - #[test] - fn selected_tool_explicit_eraser_survives_exit_during_temporary_switches() { - use crate::state::Tool; - for spring in [false, true] { - for menu in [false, true] { - let (mut app, store) = app_with_store(); - app.stylus.tool_before_eraser = Some(Tool::Zoom); - app.ui.tool = Tool::Eraser; - if spring { - crate::spring_tools::pressed(&mut app, 'E', Tool::Zoom, true, 0.0); - } - if menu { - crate::menus::invoke(&mut app, &egui::Context::default(), "tools.select.eraser", json!({})).unwrap(); - } else { - crate::tool_memory::select(&mut app, Tool::Eraser); - } - assert_eq!(app.stylus.tool_before_eraser, None); - assert!(app.ui.spring.is_none()); - crate::tool_memory::save_on_exit(&mut app).unwrap(); - let (restored, _) = app_with_saved(store.lock().unwrap().clone()); - assert_eq!(restored.ui.tool, Tool::Eraser); - } - } - } - - #[test] - fn invalid_selected_tool_preserves_other_preferences() { - for bad in [json!(null), json!("FutureTool"), json!(42), json!({}), json!([])] { - let (app, _) = app_with_saved(Some( - json!({ - "selectedTool": bad, "toolOptions": {"feather": 12.0} - }) - .to_string(), - )); - assert_eq!(app.ui.tool, crate::state::Tool::Brush, "{bad}"); - assert_eq!(app.ui.tool_options.feather, 12.0); - } - } - - #[test] - fn selected_tool_excludes_temporary_switches() { - use crate::state::Tool; - let (mut app, store) = app_with_store(); - let ctx = egui::Context::default(); - app.ui.tool = Tool::Move; - crate::tool_memory::persist(&mut app, &ctx); - tick(&mut app, &ctx); - app.tool_override = Some(Tool::Hand); - crate::tool_memory::persist(&mut app, &ctx); - tick(&mut app, &ctx); - assert_eq!(stored(&store)["selectedTool"], json!("Move")); - app.tool_override = None; - app.ui.tool = Tool::Zoom; - crate::spring_tools::pressed(&mut app, 'Z', Tool::Move, true, 0.0); - crate::tool_memory::persist(&mut app, &ctx); - tick(&mut app, &ctx); - assert_eq!(stored(&store)["selectedTool"], json!("Move")); - // A quick tap commits the choice after spring_tools clears the pending switch. - crate::spring_tools::tick(&mut app, &ctx); - crate::tool_memory::persist(&mut app, &ctx); - tick(&mut app, &ctx); - assert_eq!(stored(&store)["selectedTool"], json!("Zoom")); - app.stylus.tool_before_eraser = Some(Tool::Zoom); - app.ui.tool = Tool::Eraser; - crate::tool_memory::persist(&mut app, &ctx); - tick(&mut app, &ctx); - assert_eq!(stored(&store)["selectedTool"], json!("Zoom")); - // An explicit selection during a temporary switch takes precedence. - app.ui.tool = Tool::PolygonLasso; - crate::tool_memory::persist(&mut app, &ctx); - tick(&mut app, &ctx); - assert_eq!(stored(&store)["selectedTool"], json!("PolygonLasso")); - } - - #[test] - fn tool_options_survive_a_restart() { - let (mut app, store) = app_with_store(); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - app.ui.tool_options.move_auto_select = false; - app.ui.tool_options.feather = 12.0; - crate::tool_memory::persist(&mut app, &ctx); - tick(&mut app, &ctx); - // Only what differs from the defaults is stored. - assert_eq!(stored(&store)["toolOptions"], json!({"move_auto_select": false, "feather": 12.0})); - let saved = store.lock().unwrap().clone().unwrap(); - let (mut app2, _) = app_with_saved(Some(saved)); - tick(&mut app2, &ctx); - assert!(!app2.ui.tool_options.move_auto_select); - assert_eq!(app2.ui.tool_options.feather, 12.0); - assert_eq!(app2.ui.tool_options.tolerance, crate::state::ToolOptions::default().tolerance); - // A hand-edited file: unreadable fields keep their defaults, the good ones still load. - for bad in [json!("junk"), json!({"move_auto_select": "no", "feather": 1e300, "tolerance": 5.0, "unknown": 1})] { - let (mut app3, _) = app_with_saved(Some(json!({"toolOptions": bad}).to_string())); - tick(&mut app3, &ctx); - let o = &app3.ui.tool_options; - assert!(o.move_auto_select && o.feather == 0.0, "{bad}"); - assert_eq!(o.tolerance, if bad.is_object() { 5.0 } else { 32.0 }); - } - } - - /// #6212: a remembered value its options-bar field could never hold is clamped to the - /// field's range (or takes the default) rather than reaching the tool. - #[test] - fn remembered_tool_options_are_clamped_to_their_fields() { - let ctx = egui::Context::default(); - let hostile = json!({"toolOptions": { - "feather": 1e30, "tolerance": -5.0, "polygon_sides": 0, "eyedropper_size": 7, - "crop_overlay_orientation": 9, "fill_opacity": 0.0, "magnetic_width": 1e9, - "pattern_stamp_angle": -720.0, "marquee_width": 1e7, "shape_stroke": {"miter_limit": -1.0, "opacity": 5.0}, - }}); - let (mut app, _) = app_with_saved(Some(hostile.to_string())); - tick(&mut app, &ctx); - let o = &app.ui.tool_options; - let d = crate::state::ToolOptions::default(); - assert_eq!((o.feather, o.tolerance, o.polygon_sides, o.eyedropper_size), (1000.0, 0.0, 3, d.eyedropper_size)); - assert_eq!((o.crop_overlay_orientation, o.fill_opacity, o.magnetic_width), (d.crop_overlay_orientation, 1.0, 256.0)); - assert_eq!((o.pattern_stamp_angle, o.marquee_width), (-180.0, 999.0)); - assert_eq!(o.shape_stroke, d.shape_stroke, "an invalid stroke style takes the default"); - // A good value is left alone, and in-range defaults never change (nothing to save). - let (mut app2, _) = app_with_saved(Some(json!({"toolOptions": {"feather": 12.5}}).to_string())); - tick(&mut app2, &ctx); - assert_eq!(app2.ui.tool_options, crate::state::ToolOptions { feather: 12.5, ..d.clone() }); - let mut def = d.clone(); - crate::tool_memory::sanitize(&mut def); - assert_eq!(def, d); - } - - /// #6212: every painting tool keeps its own brush across a restart, and the session brush - /// comes back as the brush of the tool that had it. - #[test] - fn tool_brushes_survive_a_restart() { - use crate::state::Tool; - let (mut app, store) = app_with_store(); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - let set_size = |app: &mut PhotocraftApp, size: f32| { - app.session.tools.brush.size = size; - app.session.tools.brush.opacity = size / 100.0; - app.session.tools.brush_changed(); - }; - set_size(&mut app, 77.0); - app.ui.tool = Tool::Eraser; - crate::paint_mouse::sync_tool_brush(&mut app); - set_size(&mut app, 33.0); - app.ui.tool = Tool::CloneStamp; - crate::paint_mouse::sync_tool_brush(&mut app); - set_size(&mut app, 12.0); - app.ui.tool = Tool::Eraser; - crate::paint_mouse::sync_tool_brush(&mut app); - crate::last_brush::persist(&mut app, &ctx); - crate::tool_memory::persist(&mut app, &ctx); - tick(&mut app, &ctx); - let saved = stored(&store); - assert_eq!(saved["toolBrushes"]["owner"], json!("Eraser")); - assert_eq!(saved["toolBrushes"]["brushes"]["Brush"]["size"], json!(77.0)); - assert_eq!(saved["toolBrushes"]["brushes"]["CloneStamp"]["size"], json!(12.0)); - assert!(saved["toolBrushes"]["brushes"].get("Eraser").is_none(), "the owner's brush is the last brush"); - - let (mut app2, _) = app_with_saved(store.lock().unwrap().clone()); - tick(&mut app2, &ctx); - assert_eq!((app2.ui.tool, app2.ui.brush_tool), (Tool::Eraser, Tool::Eraser)); - assert_eq!(app2.session.tools.brush.size, 33.0, "the Eraser's brush is the session brush"); - for (tool, size) in [(Tool::Brush, 77.0), (Tool::CloneStamp, 12.0), (Tool::Eraser, 33.0)] { - app2.ui.tool = tool; - crate::paint_mouse::sync_tool_brush(&mut app2); - assert_eq!(app2.session.tools.brush.size, size, "{tool:?}"); - assert_eq!(app2.session.tools.brush.opacity, size / 100.0, "{tool:?}"); - } - } - - /// #6212: `toolBrushes.owner` names the tool whose brush `last_brush` holds. A brush that - /// can't be remembered yet (a sampled tip too big to embed) leaves `last_brush` at the old - /// owner's brush, so the old owner stays saved: the next launch gives that brush back to it, - /// not to the tool selected since. - #[test] - fn the_saved_brush_owner_follows_the_saved_last_brush() { - use crate::state::Tool; - use photocraft_engine::paint::{GrayTile, TipShape}; - let (mut app, store) = app_with_store(); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - app.session.tools.brush.size = 77.0; - app.session.tools.brush_changed(); - crate::last_brush::persist(&mut app, &ctx); - crate::tool_memory::persist(&mut app, &ctx); - // The Brush's tip becomes a big sampled one, then the Eraser takes over that brush. - app.session.tools.brush.tip = TipShape::Sampled(GrayTile::from_fn(400, 300, |x, y| ((x * y) % 7) as f32 / 7.0)); - app.session.tools.brush_changed(); - app.ui.tool = Tool::Eraser; - crate::paint_mouse::sync_tool_brush(&mut app); - crate::last_brush::persist(&mut app, &ctx); - crate::tool_memory::persist(&mut app, &ctx); - tick(&mut app, &ctx); - let saved = stored(&store); - assert_eq!(saved["lastBrush"]["brush"]["size"], json!(77.0), "the big tip is not remembered yet"); - assert_ne!(saved["toolBrushes"]["owner"], json!("Eraser"), "{saved}"); - let (mut app2, _) = app_with_saved(store.lock().unwrap().clone()); - tick(&mut app2, &ctx); - assert_eq!(app2.ui.brush_tool, Tool::Brush, "the 77 px brush is the Brush's"); - assert_eq!(app2.session.tools.brush.size, 77.0); - - // Once the Eraser's brush is saved, the Eraser owns it in the preferences too. - app.session.tools.brush.tip = TipShape::Round; - app.session.tools.brush.size = 33.0; - app.session.tools.brush_changed(); - crate::last_brush::persist(&mut app, &ctx); - crate::tool_memory::persist(&mut app, &ctx); - tick(&mut app, &ctx); - let saved = stored(&store); - assert_eq!(saved["toolBrushes"]["owner"], json!("Eraser"), "{saved}"); - assert_eq!(saved["lastBrush"]["brush"]["size"], json!(33.0)); - } - - /// #6212: a damaged or hand-edited `toolBrushes` never panics: what reads back loads (clamped - /// to the options bar's ranges), the rest is skipped and those tools start from the brush. - #[test] - fn remembered_tool_brushes_survive_damage() { - use crate::state::Tool; - let ctx = egui::Context::default(); - for bad in [json!("junk"), json!(42), json!({"owner": [1], "brushes": "x"}), json!({"brushes": {"Eraser": 5}})] { - let (mut app, _) = app_with_saved(Some(json!({"toolBrushes": bad}).to_string())); - tick(&mut app, &ctx); - assert_eq!(app.ui.brush_tool, Tool::Brush, "{bad}"); - assert!(app.ui.tool_brushes.is_empty(), "{bad}"); - } - let hostile = json!({"toolBrushes": {"owner": "Move", "brushes": { - "Eraser": {"size": 1e30}, "Bogus": {"size": 5.0}, "Move": {"size": 5.0}, - "Smudge": {"size": -3.0, "opacity": 50.0, "flow": -2.0, "hardness": 1e30}, - "Brush": {"size": 9.0}, - }}}); - let (mut app, _) = app_with_saved(Some(hostile.to_string())); - tick(&mut app, &ctx); - assert_eq!(app.ui.brush_tool, Tool::Brush, "the Move tool has no brush"); - let tools: Vec = app.ui.tool_brushes.iter().map(|(t, _)| *t).collect(); - assert_eq!(tools, vec![Tool::Smudge], "too large, unknown, brushless and the owner's own are skipped"); - let b = &app.ui.tool_brushes[0].1; - assert_eq!((b.size, b.opacity, b.flow, b.hardness), (1.0, 1.0, 0.0, 1.0)); - // A whole preferences file that isn't JSON: defaults, no panic. - let (mut app, _) = app_with_saved(Some("{not json".into())); - tick(&mut app, &ctx); - assert!(app.ui.tool_brushes.is_empty()); - assert_eq!(app.ui.tool_options, crate::state::ToolOptions::default()); - } - - /// #6212: Reset Tool forgets that tool's remembered options and brush; Reset All Tools - /// forgets every tool's. - #[test] - fn reset_tools_clear_the_remembered_options_and_brushes() { - use crate::state::Tool; - let (mut app, store) = app_with_store(); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - app.ui.tool_options.feather = 12.0; - app.ui.tool_options.strength = 80.0; - app.session.tools.brush.size = 77.0; - app.session.tools.brush_changed(); - for tool in [Tool::Eraser, Tool::Smudge, Tool::Brush] { - app.ui.tool = tool; - crate::paint_mouse::sync_tool_brush(&mut app); - } - app.ui.tool = Tool::Smudge; - crate::paint_mouse::sync_tool_brush(&mut app); - crate::last_brush::persist(&mut app, &ctx); - crate::tool_memory::persist(&mut app, &ctx); - tick(&mut app, &ctx); - let saved = stored(&store); - assert_eq!(saved["toolOptions"]["strength"], json!(80.0)); - assert!(saved["toolBrushes"]["brushes"].get("Eraser").is_some() && saved["toolBrushes"]["brushes"].get("Brush").is_some()); - - crate::menus::invoke(&mut app, &ctx, crate::tool_reset::RESET, json!({})).unwrap(); - crate::last_brush::persist(&mut app, &ctx); - crate::tool_memory::persist(&mut app, &ctx); - tick(&mut app, &ctx); - let saved = stored(&store); - assert!(saved["toolOptions"].get("strength").is_none(), "the Smudge's Strength is forgotten"); - assert_eq!(saved["toolOptions"]["feather"], json!(12.0), "the marquee's Feather is not the Smudge's"); - assert!(saved["toolBrushes"]["brushes"].get("Eraser").is_some()); - - crate::menus::invoke(&mut app, &ctx, crate::tool_reset::RESET_ALL, json!({"confirmed": true})).unwrap(); - crate::last_brush::persist(&mut app, &ctx); - crate::tool_memory::persist(&mut app, &ctx); - tick(&mut app, &ctx); - let saved = stored(&store); - assert!(saved["toolOptions"].is_null(), "{saved}"); - assert!(saved["toolBrushes"]["brushes"].as_object().is_none_or(|m| m.is_empty()), "{saved}"); - let (app2, _) = app_with_saved(store.lock().unwrap().clone()); - assert_eq!(app2.ui.tool_options, crate::state::ToolOptions::default()); - assert!(app2.ui.tool_brushes.is_empty()); - } - - #[test] - fn view_show_items_survive_a_restart() { - let (mut app, store) = app_with_store(); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - // Untouched: nothing is stored, so later default changes still reach the user. - crate::view_cmds::persist(&mut app, &ctx); - tick(&mut app, &ctx); - assert!(stored(&store).get("viewExtras").is_none_or(Value::is_null)); - // The menu commands, as a user toggles them (#3762: Pixel Grid off). - for id in ["view.show.pixelGrid", "view.show.grid", "view.snapTo.layers", "view.extras"] { - crate::menus::invoke(&mut app, &ctx, id, json!({})).unwrap(); - } - crate::view_cmds::persist(&mut app, &ctx); - tick(&mut app, &ctx); - assert_eq!(stored(&store)["viewExtras"], json!({"extras": false, "grid": true, "show": {"pixelGrid": false}, "snapTo": {"layers": false}})); - // A restart gets them back. - let saved = store.lock().unwrap().clone().unwrap(); - let (mut app2, _) = app_with_saved(Some(saved)); - tick(&mut app2, &ctx); - let v = &app2.ui.view; - assert!(!v.extras && !v.show.pixel_grid && !v.snap_to.layers && app2.ui.extras.grid); - assert!(v.show.selection_edges && v.snap_to.guides && app2.ui.extras.guides, "the rest keep their defaults"); - // A hand-edited file: unknown keys and non-booleans keep the defaults, good ones still load. - for bad in [json!("junk"), json!({"extras": 0, "show": {"pixelGrid": "no", "mesh": true, "bogus": true}, "snapTo": [1]})] { - let (mut app3, _) = app_with_saved(Some(json!({"viewExtras": bad}).to_string())); - tick(&mut app3, &ctx); - let v = &app3.ui.view; - assert!(v.extras && v.show.pixel_grid && v.snap_to.layers, "{bad}"); - assert_eq!(v.show.mesh, bad.is_object()); - } - } - - #[test] - fn view_snap_off_survives_a_restart() { - let (mut app, store) = app_with_store(); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - assert!(app.ui.extras.snap, "on by default"); - crate::menus::invoke(&mut app, &ctx, "view.snap", json!({})).unwrap(); - assert!(!app.ui.extras.snap); - crate::view_cmds::persist(&mut app, &ctx); - tick(&mut app, &ctx); - assert_eq!(stored(&store)["viewExtras"], json!({"snap": false})); - let saved = store.lock().unwrap().clone().unwrap(); - let (mut app2, _) = app_with_saved(Some(saved)); - tick(&mut app2, &ctx); - assert!(!app2.ui.extras.snap, "still off after a restart"); - crate::menus::invoke(&mut app2, &ctx, "view.snap", json!({})).unwrap(); - crate::view_cmds::persist(&mut app2, &ctx); - assert!(app2.session.prefs().view_extras.is_null()); - } - - #[test] - fn show_tooltips_preferences_turn_tooltips_off() { - let (mut app, _) = app_with_store(); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - assert_eq!(ctx.global_style().interaction.tooltip_delay, crate::theme::TOOLTIP_DELAY); - for path in ["interface.showTooltips", "tools.showTooltips"] { - app.run("prefs.set", json!({"values": {path: false}})).unwrap(); - tick(&mut app, &ctx); - assert!(ctx.global_style().interaction.tooltip_delay.is_infinite(), "{path} off hides tooltips"); - app.run("prefs.set", json!({"values": {path: true}})).unwrap(); - tick(&mut app, &ctx); - assert_eq!(ctx.global_style().interaction.tooltip_delay, crate::theme::TOOLTIP_DELAY); - } - } - - #[test] - fn enable_animations_off_stops_fades_and_scroll_glides_and_is_remembered() { - let on = egui::Style::default().animation_time; - let both = |ctx: &egui::Context| [egui::Theme::Dark, egui::Theme::Light].map(|t| ctx.style_of(t).animation_time); - // Saved off: the first frame after a restart applies it to both appearance styles. - let (mut app, _) = app_with_saved(Some(json!({"interface": {"enableAnimations": false}}).to_string())); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - assert_eq!(both(&ctx), [0.0, 0.0]); - assert_eq!(ctx.global_style().scroll_animation.duration.max, 0.0); - // A theme change rebuilds the style; the next frame turns animations off again. - app.apply_theme(&ctx, crate::theme::ThemeKind::StudioLight); - tick(&mut app, &ctx); - assert_eq!(both(&ctx), [0.0, 0.0]); - app.run("prefs.set", json!({"values": {"interface.enableAnimations": true}})).unwrap(); - tick(&mut app, &ctx); - assert_eq!(both(&ctx), [on, on]); - assert!(on > 0.0 && ctx.global_style().scroll_animation.duration.max > 0.0); - // A hand-edited value of the wrong type doesn't crash: the defaults (animations on) stay. - let (mut bad, _) = app_with_saved(Some(json!({"interface": {"enableAnimations": "nope"}}).to_string())); - let ctx2 = egui::Context::default(); - tick(&mut bad, &ctx2); - assert_eq!(both(&ctx2), [on, on]); - } - - #[test] - fn unimplemented_preferences_are_hidden_from_the_dialog() { - let values = prefs::Preferences::default().to_json(); - assert!(has_visible_fields(&values, "general")); - assert!(has_visible_fields(&values, "fileHandling")); - // Every setting of this section is still unimplemented. - assert!(!has_visible_fields(&values, "scratchDisks"), "scratchDisks"); - // Allow Agent Control and Control Port are read at launch (apps/photocraft main.rs). - assert!(has_visible_fields(&values, "integrations")); - assert!(!prefs::is_hidden("integrations.allowAgentControl")); - assert!(!prefs::is_hidden("integrations.controlPort")); - // "Fill new type layers with placeholder text" and "Use Escape to Commit" are live; other Type rows stay hidden. - assert!(has_visible_fields(&values, "type")); - assert!(!prefs::is_hidden("type.fillNewTypeLayersWithPlaceholder")); - assert!(!prefs::is_hidden("type.useEscToCommit")); - assert!(!prefs::is_hidden("type.smartQuotes")); - assert!(!prefs::is_hidden("type.showFontNamesInEnglish")); - // Rotate View with Trackpad, the pinch zoom and Enable Gestures are live; the other - // Enhanced Controls rows stay hidden. - assert!(has_visible_fields(&values, "enhancedControls")); - assert!(!prefs::is_hidden("enhancedControls.rotateViewWithTrackpad")); - assert!(!prefs::is_hidden("enhancedControls.zoomWithTrackpadPinch")); - assert!(!prefs::is_hidden("enhancedControls.touchGestures")); - assert!(prefs::is_hidden("enhancedControls.scrubbySliderAcceleration")); - // Camera Raw Defaults are all live: the dialog's Open applies them (camera_raw_ui). - assert!(has_visible_fields(&values, "rawDefaults")); - for k in ["openInCameraRaw", "demosaic", "applyAutoTone", "colorSpace", "bitDepth", "resolution", "sharpenFor", "openAsSmartObject", "writeXmpSidecars"] - { - assert!(!prefs::is_hidden(&format!("rawDefaults.{k}")), "{k}"); - } - assert!(!prefs::is_hidden("general.autoShowHomeScreen")); - assert!(!prefs::is_hidden("general.animatedZoom")); - assert!(!prefs::is_hidden("general.zoomResizesWindows")); - assert!(!prefs::is_hidden("interface.uiScale")); - assert!(!prefs::is_hidden("interface.uiFontSize")); - // Hidden values still round-trip through the dialog untouched. - let (mut app, _) = app_with_store(); - app.run("prefs.set", json!({"values": {"type.smartQuotes": false}})).unwrap(); - let id = open_preferences(&mut app, "type"); - let fields = app.ui.dialogs.iter().find(|d| d.id == id).map(|d| d.fields.clone()).unwrap(); - confirm(&mut app, &fields).unwrap(); - assert!(!app.session.prefs().type_.smart_quotes); - } - - #[test] - fn preferences_persist_through_services_and_theme_follows() { - let (mut app, store) = app_with_store(); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - app.run("prefs.set", json!({"values": {"interface.theme": "studioLight", "performance.historyStates": 12}})).unwrap(); - tick(&mut app, &ctx); - assert_eq!(app.ui.theme, ThemeKind::StudioLight); - let saved = store.lock().unwrap().clone().unwrap(); - assert!(saved.contains("\"historyStates\": 12")); - // A new app instance loads them. - let (mut app2, store2) = app_with_saved(Some(saved)); - tick(&mut app2, &ctx); - assert_eq!(app2.session.prefs().performance.history_states, 12); - assert_eq!(app2.ui.theme, ThemeKind::StudioLight); - // Picking a theme from the Window menu becomes the preference. - crate::menus::invoke(&mut app2, &ctx, "window.theme.classic", json!({})).unwrap(); - tick(&mut app2, &ctx); - assert_eq!(app2.session.prefs().interface.theme, Theme::Classic); - assert!(store2.lock().unwrap().as_ref().unwrap().contains("classic")); - } - - #[test] - fn preset_export_dialog_offers_tool_presets() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let opened = crate::menus::invoke(&mut app, &ctx, "edit.presets.exportImportPresets", json!({})).unwrap(); - let fields = app.ui.dialog_mut(opened["dialog"].as_u64().unwrap()).unwrap().fields.clone(); - assert_eq!(fields["tools"], true); - let mut h = Harness::builder().with_size(vec2(420.0, 260.0)).build_ui_state(presets_io_body, fields); - h.run_steps(2); - h.get_by_label("Tool Presets").click(); - h.run_steps(2); - assert_eq!(h.state()["tools"], false); - assert_eq!(h.state()["brushes"], true); - assert_eq!(h.state()["customShapes"], true); - } - - #[test] - fn brush_preset_store_attaches_when_loaded_and_persists() { - use photocraft_engine::preset_store::{MemBackend, open}; - let mem = MemBackend::default(); - let ctx = egui::Context::default(); - let (tx, rx) = std::sync::mpsc::channel(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { preset_store: Some(rx), ..Default::default() }); - // Still loading: presets made now are kept and written once the store arrives. - tick(&mut app, &ctx); - app.run("brush.presets.save", json!({"name": "Early"})).unwrap(); - assert!(mem.files.lock().unwrap().is_empty()); - tx.send(open(Box::new(mem.clone()))).unwrap(); - tick(&mut app, &ctx); - assert!(app.services.preset_store.is_none() && app.session.preset_store.is_some()); - app.run("brush.presets.save", json!({"name": "Late"})).unwrap(); - let mut s2 = photocraft_engine::Session::new(); - assert!(s2.attach_preset_store(open(Box::new(mem))).is_empty()); - for n in ["Early", "Late"] { - assert!(s2.tools.presets.iter().any(|p| p.name == n), "{n}"); - } - } - - #[test] - fn preferences_dialog_round_trip() { - let (mut app, _) = app_with_store(); - let ctx = egui::Context::default(); - let r = crate::menus::invoke(&mut app, &ctx, "edit.preferences.cursors", json!({})).unwrap(); - let id = r["dialog"].as_u64().unwrap(); - let d = app.ui.dialogs.iter().find(|d| d.id == id).unwrap().clone(); - assert_eq!(d.fields["section"], "cursors"); - let mut values = d.fields["values"].clone(); - values["cursors"]["painting"] = json!("fullSizeTip"); - values["unitsAndRulers"]["rulers"] = json!("inches"); - app.ui.dialog_mut(id).unwrap().fields.insert("values".into(), values); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(app.session.prefs().cursors.painting, prefs::PaintingCursor::FullSizeTip); - assert_eq!(app.session.prefs().units_and_rulers.rulers, prefs::Unit::Inches); - // Invalid values are rejected and nothing changes. - let id = open_preferences(&mut app, "performance"); - let mut values = app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["values"].clone(); - values["performance"]["historyStates"] = json!(0); - app.ui.dialog_mut(id).unwrap().fields.insert("values".into(), values); - assert!(crate::dialogs::confirm(&mut app, id).is_err()); - assert_eq!(app.session.prefs().performance.history_states, 50); - } - - #[test] - fn preferences_apply_button_saves_without_closing_and_cancel_keeps_applied_values() { - use egui_kittest::{ - Harness, - kittest::{NodeT, Queryable}, - }; - - let (mut app, store) = app_with_store(); - app.run("prefs.set", json!({"values": {"interface.language": "en", "type.smartQuotes": false}})).unwrap(); - let id = open_preferences(&mut app, "interface"); - let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); - h.run_steps(4); - assert!(h.get_by_label("Apply").accesskit_node().is_disabled()); - - let values = h.state_mut().ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap(); - values["interface"]["appearanceMode"] = json!("light"); - values["interface"]["lightTheme"] = json!("studioLight"); - values["interface"]["uiFontSize"] = json!("large"); - values["performance"]["historyStates"] = json!(12); - h.run_steps(2); - assert!(!h.get_by_label("Apply").accesskit_node().is_disabled()); - h.get_by_label("Apply").click(); - h.run_steps(4); - - assert_eq!(h.state().session.prefs().performance.history_states, 12); - assert_eq!(h.state().ui.theme, ThemeKind::StudioLight); - assert_eq!(h.ctx.fonts(|f| f.definitions().font_data["Inter"].tweak.scale), 16.0 / 12.0); - assert!(!h.state().session.prefs().type_.smart_quotes, "hidden settings round-trip unchanged"); - let d = h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap(); - assert_eq!(d.fields["section"], "interface"); - assert_eq!(d.fields["values"]["performance"]["historyStates"], 12); - assert!(h.get_by_label("Apply").accesskit_node().is_disabled()); - let saved: Value = serde_json::from_str(store.lock().unwrap().as_ref().unwrap()).unwrap(); - assert_eq!(saved["performance"]["historyStates"], 12); - assert_eq!(saved["interface"]["appearanceMode"], "light"); - assert_eq!(saved["interface"]["lightTheme"], "studioLight"); - assert_eq!(saved["interface"]["uiFontSize"], "large"); - - // Repeated Apply starts from the validated values, not the dialog's original snapshot. - h.state_mut().ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap()["performance"]["historyStates"] = json!(22); - h.run_steps(2); - h.get_by_label("Apply").click(); - h.run_steps(4); - assert_eq!(h.state().session.prefs().performance.history_states, 22); - h.state_mut().ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap()["performance"]["historyStates"] = json!(33); - h.state_mut().ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap()["interface"]["uiFontSize"] = json!("tiny"); - h.run_steps(2); - h.get_by_label("Cancel").click(); - h.run_steps(4); - assert!(h.state().ui.dialogs.iter().all(|d| d.id != id)); - assert_eq!(h.state().session.prefs().performance.history_states, 22); - assert_eq!(h.ctx.fonts(|f| f.definitions().font_data["Inter"].tweak.scale), 16.0 / 12.0); - let saved = store.lock().unwrap().clone().unwrap(); - let (mut restarted, _) = app_with_saved(Some(saved)); - tick(&mut restarted, &egui::Context::default()); - assert_eq!(restarted.session.prefs().performance.history_states, 22); - assert_eq!(restarted.ui.theme, ThemeKind::StudioLight); - assert_eq!(restarted.session.prefs().interface.ui_font_size, prefs::UiFontSize::Large); - } - - #[cfg(all(not(target_arch = "wasm32"), not(target_os = "macos")))] - #[test] - fn system_title_bar_explains_next_launch_and_preserves_apply_and_cancel() { - use egui_kittest::{Harness, kittest::Queryable}; - - let (mut app, store) = app_with_store(); - app.run("prefs.set", json!({"values": {"interface.language": "en"}})).unwrap(); - app.custom_titlebar = true; - let id = open_preferences(&mut app, "interface"); - let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); - h.run_steps(4); - h.get_by_label("System title bar").scroll_to_me(); - h.run_steps(4); - h.get_by_label("Applies at next launch."); - for desired in [true, false] { - h.get_by_label("System title bar").click(); - h.run_steps(4); - assert_eq!(h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["values"]["interface"]["systemTitleBar"], desired); - assert_eq!(h.state().session.prefs().interface.system_title_bar, !desired, "the draft is not applied yet"); - h.get_by_label("Applies at next launch."); - h.get_by_label("Apply").click(); - h.run_steps(4); - assert_eq!(h.state().session.prefs().interface.system_title_bar, desired); - assert_eq!(stored(&store)["interface"]["systemTitleBar"], desired); - assert!(h.state().custom_titlebar, "do not change the current window or restart it"); - let (reloaded, _) = app_with_saved(store.lock().unwrap().clone()); - assert_eq!(reloaded.session.prefs().interface.system_title_bar, desired); - h.get_by_label("Applies at next launch."); - } - h.get_by_label("System title bar").click(); - h.run_steps(4); - h.get_by_label("Cancel").click(); - h.run_steps(4); - assert!(h.state().ui.dialogs.iter().all(|d| d.id != id)); - assert!(!h.state().session.prefs().interface.system_title_bar); - assert_eq!(stored(&store)["interface"]["systemTitleBar"], false); - assert!(h.state().custom_titlebar); - } - - /// #7939: switching Rendering Mode waits for the next launch, and says so next to the setting. - #[test] - fn rendering_mode_explains_next_launch() { - use egui_kittest::{Harness, kittest::Queryable}; - let obj = json!({"renderingMode": "auto", "historyStates": 50}).as_object().unwrap().clone(); - let mut h = Harness::new_ui_state( - |ui, obj: &mut Map| section_fields(ui, "performance", obj, &[], crate::i18n::Lang::from_pref("en"), None, ""), - obj, - ); - h.run_steps(4); - assert!(h.query_all_by_label("Rendering Mode").next().is_some(), "the Rendering Mode setting"); - assert!(h.query_all_by_label("Applies at next launch.").next().is_some(), "its next-launch notice"); - // A search that leaves Rendering Mode out leaves its notice out too. - let obj = json!({"renderingMode": "auto", "historyStates": 50}).as_object().unwrap().clone(); - let mut h = Harness::new_ui_state( - |ui, obj: &mut Map| section_fields(ui, "performance", obj, &[], crate::i18n::Lang::from_pref("en"), None, "history"), - obj, - ); - h.run_steps(4); - assert!(h.query_by_label("Applies at next launch.").is_none()); - } - - /// #4097: Allow Agent Control and Control Port are read when the app starts, and say so. - #[test] - fn integrations_explain_next_launch() { - use egui_kittest::{Harness, kittest::Queryable}; - let obj = json!({"allowAgentControl": true, "controlPort": 0}).as_object().unwrap().clone(); - let mut h = Harness::new_ui_state( - |ui, obj: &mut Map| section_fields(ui, "integrations", obj, &[], crate::i18n::Lang::from_pref("en"), None, ""), - obj, - ); - h.run_steps(4); - h.get_by_label("Allow agent control"); - assert_eq!(h.query_all_by_label("Applies at next launch.").count(), 2, "one notice under each row"); - } - - #[test] - fn next_launch_notice_does_not_mark_unrelated_interface_preferences() { - use egui_kittest::{Harness, kittest::Queryable}; - let obj = json!({"showTooltips": true}).as_object().unwrap().clone(); - let mut h = Harness::new_ui_state( - |ui, obj: &mut Map| section_fields(ui, "interface", obj, &[], crate::i18n::Lang::from_pref("en"), None, ""), - obj, - ); - h.run_steps(4); - assert!(h.query_by_label("Applies at next launch.").is_none()); - h.get_by_label("Show tooltips").click(); - h.run_steps(4); - assert_eq!(h.state()["showTooltips"], false); - assert!(h.query_by_label("Applies at next launch.").is_none()); - } - - #[test] - fn preferences_confirm_after_apply_commits_later_edits() { - let (mut app, _) = app_with_store(); - let id = open_preferences(&mut app, "cursors"); - app.ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap()["cursors"]["painting"] = json!("fullSizeTip"); - apply(&mut app, id).unwrap(); - app.ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap()["unitsAndRulers"]["rulers"] = json!("inches"); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert!(app.ui.dialogs.iter().all(|d| d.id != id)); - assert_eq!(app.session.prefs().cursors.painting, prefs::PaintingCursor::FullSizeTip); - assert_eq!(app.session.prefs().units_and_rulers.rulers, prefs::Unit::Inches); - } - - #[test] - fn preferences_apply_rejects_invalid_drafts_and_keeps_them_open() { - let (mut app, _) = app_with_store(); - let before = app.session.prefs().to_json(); - for invalid in [json!(0), json!("invalid"), Value::Null] { - let id = open_preferences(&mut app, "performance"); - app.ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap()["performance"]["historyStates"] = invalid; - let draft = app.ui.dialog_mut(id).unwrap().fields.clone(); - assert!(apply(&mut app, id).is_err()); - assert_eq!(app.session.prefs().to_json(), before); - assert_eq!(app.ui.dialog_mut(id).unwrap().fields, draft); - app.ui.close_dialog(id); - } - let id = open_preferences(&mut app, "interface"); - app.ui.dialog_mut(id).unwrap().fields.remove("values"); - assert!(apply(&mut app, id).is_err()); - assert!(app.ui.dialog_mut(id).is_some()); - assert_eq!(app.session.prefs().to_json(), before); - } - - #[test] - fn apply_rejects_missing_and_non_preferences_dialogs() { - let (mut app, _) = app_with_store(); - let before = app.session.prefs().to_json(); - assert!(apply(&mut app, u64::MAX).is_err()); - let id = open_shortcuts(&mut app, 0); - assert!(apply(&mut app, id).is_err()); - assert!(app.ui.dialog_mut(id).is_some()); - let fields = json!({"__prefsui": "prefs", "values": preference_values(app.session.prefs())}).as_object().unwrap().clone(); - let id = app.ui.open_dialog(DialogKind::About, fields); - assert!(apply(&mut app, id).is_err()); - assert!(app.ui.dialog_mut(id).is_some()); - assert_eq!(app.session.prefs().to_json(), before); - } - - #[test] - fn shortcut_dialog_moves_shortcuts_and_shell_dispatch_follows() { - let (mut app, _) = app_with_store(); - let ctx = egui::Context::default(); - let id = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); - // ⌘O (File › Open, a shell command) given to Layer › New › Layer. - app.ui.dialog_mut(id).unwrap().fields.insert("overrides".into(), json!({"layer.new.layer": "Cmd+O"})); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(effective_shortcut(&app, "layer.new.layer", None).as_deref(), Some("Cmd+O")); - assert_eq!(effective_shortcut(&app, "file.open", Some("Cmd+O")), None, "taken from File › Open"); - // Menu items show the effective shortcut. - let items = crate::menus::menu_items(&app); - assert!(items.iter().any(|i| i.id == "layer.new.layer" && i.shortcut.as_deref() == Some("Cmd+O"))); - assert!(items.iter().any(|i| i.id == "file.open" && i.shortcut.is_none())); - assert_eq!(shortcut_text(egui::Key::K, egui::Modifiers { command: true, shift: true, ..Default::default() }).as_deref(), Some("Cmd+Shift+K")); - - // Re-assigning a shortcut already held by a custom override takes it from the override. - let id2 = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); - let mut cur_overrides = app.session.prefs().shortcuts.clone(); - cur_overrides.insert("layer.new.group".into(), "Cmd+O".into()); - app.ui.dialog_mut(id2).unwrap().fields.insert("overrides".into(), json!(cur_overrides)); - crate::dialogs::confirm(&mut app, id2).unwrap(); - assert_eq!(effective_shortcut(&app, "layer.new.group", None).as_deref(), Some("Cmd+O")); - assert_eq!(effective_shortcut(&app, "layer.new.layer", None), None, "taken from layer.new.layer override"); - - // OK with nothing changed keeps every shortcut where it is. - let id3 = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); - let unchanged = app.session.prefs().shortcuts.clone(); - app.ui.dialog_mut(id3).unwrap().fields.insert("overrides".into(), json!(unchanged)); - crate::dialogs::confirm(&mut app, id3).unwrap(); - assert_eq!(app.session.prefs().shortcuts, unchanged); - - // Giving the shortcut back to Layer › New › Layer takes it from the group override; a - // cleared override (empty) holds nothing and is left alone. - let id4 = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); - let mut ov = app.session.prefs().shortcuts.clone(); - ov.insert("layer.new.layer".into(), "Cmd+O".into()); - app.ui.dialog_mut(id4).unwrap().fields.insert("overrides".into(), json!(ov)); - crate::dialogs::confirm(&mut app, id4).unwrap(); - assert_eq!(effective_shortcut(&app, "layer.new.layer", None).as_deref(), Some("Cmd+O")); - assert_eq!(effective_shortcut(&app, "layer.new.group", None), None, "taken back from the group"); - assert_eq!(effective_shortcut(&app, "file.open", Some("Cmd+O")), None, "File › Open stays cleared"); - } - - /// #3665: the dialog keeps a command's further keys: they move like main keys, an override - /// of the main key leaves them, and menus show only the main key. - #[test] - fn shortcut_dialog_moves_and_keeps_alternate_keys() { - let (mut app, _) = app_with_store(); - let ctx = egui::Context::default(); - let open = |app: &mut PhotocraftApp| crate::menus::invoke(app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); - assert_eq!(crate::shortcuts::effective_alternates(&app, "edit.copy"), ["F3"]); - assert_eq!(crate::shortcuts::effective_alternates(&app, "view.zoomIn"), ["Cmd++"]); - // F2 (Cut's alternate) given to Rename Layer is taken from Cut, which keeps ⌘X. - let id = open(&mut app); - app.ui.dialog_mut(id).unwrap().fields.insert("overrides".into(), json!({"layer.renameLayer": "F2"})); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(effective_shortcut(&app, "layer.renameLayer", None).as_deref(), Some("F2")); - assert!(crate::shortcuts::effective_alternates(&app, "edit.cut").is_empty()); - assert_eq!(effective_shortcut(&app, "edit.cut", Some("Cmd+X")).as_deref(), Some("Cmd+X")); - // Copy's main key moved to ⌘K keeps F3; the menu shows ⌘K. - let id = open(&mut app); - let mut ov = app.session.prefs().shortcuts.clone(); - ov.insert("edit.copy".into(), "Cmd+K".into()); - app.ui.dialog_mut(id).unwrap().fields.insert("overrides".into(), json!(ov)); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(crate::shortcuts::effective_alternates(&app, "edit.copy"), ["F3"]); - assert!(crate::menus::menu_items(&app).iter().any(|i| i.id == "edit.copy" && i.shortcut.as_deref() == Some("Cmd+K"))); - // An added alternate takes its key from the main key that held it. - let id = open(&mut app); - app.ui.dialog_mut(id).unwrap().fields.insert("alternates".into(), json!({"edit.paste": ["F4", "Cmd+K"]})); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(crate::shortcuts::effective_alternates(&app, "edit.paste"), ["F4", "Cmd+K"]); - assert_eq!(effective_shortcut(&app, "edit.copy", Some("Cmd+C")), None, "taken from Copy"); - // Use Default for everything restores the defaults; a malformed list is an error. - let id = open(&mut app); - app.ui.dialog_mut(id).unwrap().fields.insert("alternates".into(), json!({"edit.paste": "F4"})); - assert!(crate::dialogs::confirm(&mut app, id).is_err()); - let id = open(&mut app); - app.ui.dialog_mut(id).unwrap().fields.insert("alternates".into(), json!({"edit.paste": ["Cmd+Shift"]})); - assert!(crate::dialogs::confirm(&mut app, id).is_err()); - assert_eq!(crate::shortcuts::effective_alternates(&app, "edit.paste"), ["F4", "Cmd+K"], "nothing changed"); - let id = open(&mut app); - app.ui.dialog_mut(id).unwrap().fields.insert("alternates".into(), json!({})); - app.ui.dialog_mut(id).unwrap().fields.insert("overrides".into(), json!({})); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert!(app.session.prefs().alternate_shortcuts.is_empty() && app.session.prefs().shortcuts.is_empty()); - assert_eq!(crate::shortcuts::effective_alternates(&app, "edit.cut"), ["F2"]); - } - - #[test] - fn shortcut_dialog_rejects_malformed_overrides() { - // #956: a non-map `overrides` was read as "no overrides" and wiped every custom shortcut. - let (mut app, _) = app_with_store(); - let ctx = egui::Context::default(); - app.run("edit.keyboardShortcuts", json!({"set": {"file.new": "Ctrl+Shift+N"}})).unwrap(); - let before = app.session.prefs().shortcuts.clone(); - assert!(!before.is_empty()); - for bad in [json!("bogus"), json!(["file.new"]), json!({"file.new": 5})] { - let id = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); - app.ui.dialog_mut(id).unwrap().fields.insert("overrides".into(), bad.clone()); - assert!(crate::dialogs::confirm(&mut app, id).is_err(), "{bad} accepted"); - assert_eq!(app.session.prefs().shortcuts, before, "{bad} changed the shortcuts"); - } - - // Drawing the open dialog keeps the malformed value for OK to reject, instead of - // replacing it with the empty map it shows. - let id = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); - app.ui.dialog_mut(id).unwrap().fields.insert("overrides".into(), json!("bogus")); - let mut h = egui_kittest::Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); - h.run_steps(4); - assert_eq!(h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["overrides"], json!("bogus")); - assert!(crate::dialogs::confirm(h.state_mut(), id).is_err()); - assert_eq!(h.state().session.prefs().shortcuts, before); - } - - #[test] - fn hidden_menu_items_disappear() { - let (mut app, _) = app_with_store(); - app.run("edit.menus", json!({"hide": ["edit.fade"]})).unwrap(); - assert!(!crate::menus::menu_items(&app).iter().any(|i| i.id == "edit.fade")); - } - - /// #5096: preferences that list Edit › Menus or File › Exit as hidden still show them. - #[test] - fn essential_menu_items_stay_visible() { - let (mut app, _) = app_with_store(); - app.run("prefs.set", json!({"values": {"menus": {"hidden": ["edit.menus", "file.exit", "edit.fade"], "colors": {}}}})).unwrap(); - let items = crate::menus::menu_items(&app); - assert!(items.iter().any(|i| i.id == "edit.menus") && items.iter().any(|i| i.id == "file.exit")); - assert!(!items.iter().any(|i| i.id == "edit.fade")); - } - - #[test] - fn autosave_runs_for_dirty_documents() { - type Saved = Arc>>; - let saved: Saved = Arc::default(); - let s2 = saved.clone(); - let services = crate::Services { - autosave: Some(Box::new(move |doc: &Arc, rev: u64, _path: Option<&str>| { - s2.lock().unwrap().push((doc.id.0, rev)); - Ok(()) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - tick(&mut app, &ctx); - autosave_now(&mut app); - tick(&mut app, &ctx); - assert!(saved.lock().unwrap().is_empty(), "clean documents are not autosaved"); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - autosave_now(&mut app); - tick(&mut app, &ctx); - assert_eq!(saved.lock().unwrap().len(), 1); - autosave_now(&mut app); - tick(&mut app, &ctx); - assert_eq!(saved.lock().unwrap().len(), 1, "unchanged since the last autosave"); - - // Loaded copies can have the same persisted identity and dirty revision. - let original = app.session.active().unwrap().doc.clone(); - let original_id = original.id; - app.session.add_document(original.as_ref().clone(), None); - app.run("edit.fill", json!({"color": "#0000ff"})).unwrap(); - autosave_now(&mut app); - tick(&mut app, &ctx); - { - let saved = saved.lock().unwrap(); - assert_eq!(saved.len(), 2, "both dirty copies need independent autosaves"); - assert_eq!(saved[0].0, original_id.0); - assert_ne!(saved[0].0, saved[1].0, "recovery ownership must be distinct"); - assert_eq!(saved[0].1, saved[1].1, "the revisions must match to reproduce suppression"); - } - app.run("prefs.set", json!({"path": "fileHandling.autosave", "value": false})).unwrap(); - app.run("edit.fill", json!({"color": "#00ff00"})).unwrap(); - autosave_now(&mut app); - tick(&mut app, &ctx); - assert_eq!(saved.lock().unwrap().len(), 2, "autosave off"); - } - - #[test] - fn recovered_documents_adopt_their_entries_until_saved_or_closed() { - type Log = Arc>>; - let log: Log = Arc::default(); - let (l1, l2, l3) = (log.clone(), log.clone(), log.clone()); - use photocraft_doc::{Color, ColorMode, Document, SampleType, Size}; - let doc = || Document::with_background("R", Size::new(4, 4), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let services = crate::Services { - autosave: Some(Box::new(move |d: &Arc, _: u64, _: Option<&str>| { - l1.lock().unwrap().push(format!("save {}", d.id.0)); - Ok(()) - })), - discard_autosave: Some(Box::new(move |id: u64| l2.lock().unwrap().push(format!("discard {id}")))), - recover: Some(Box::new(move || { - ["a", "b"].map(|key| crate::Recoverable { key: key.into(), name: "R".into(), path: None, load: Box::new(move || Ok(doc())) }).into() - })), - adopt_autosave: Some(Box::new(move |id: u64, key: &str| l3.lock().unwrap().push(format!("adopt {id} {key}")))), - ..Default::default() - }; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - let ctx = egui::Context::default(); - tick(&mut app, &ctx); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while app.session.has_jobs() && std::time::Instant::now() < deadline { - crate::jobs_ui::tick(&mut app, &ctx); - std::thread::sleep(std::time::Duration::from_millis(1)); - } - assert!(!app.session.has_jobs(), "recovery finished"); - let ids: Vec = app.session.documents().iter().map(|d| d.doc.id.0).collect(); - assert!(app.session.documents().iter().all(|d| d.is_dirty()), "recovered documents are unsaved"); - let take = || std::mem::take(&mut *log.lock().unwrap()); - assert_eq!(take(), [format!("adopt {} a", ids[0]), format!("adopt {} b", ids[1])]); - // Their entries are current: nothing to autosave until they change. - tick(&mut app, &ctx); - autosave_now(&mut app); - tick(&mut app, &ctx); - assert!(take().is_empty()); - // Closing one drops its entry; editing the other autosaves over its own. - app.run("file.close", json!({"document": 0})).unwrap(); - app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); - autosave_now(&mut app); - tick(&mut app, &ctx); - assert_eq!(take(), [format!("discard {}", ids[0]), format!("save {}", ids[1])]); - } - - #[test] - fn edit_dialogs_open() { - let (mut app, _) = app_with_store(); - let ctx = egui::Context::default(); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.sync_views(); - let d = crate::menus::invoke(&mut app, &ctx, "edit.colorSettings", json!({})).unwrap()["dialog"].as_u64().unwrap(); - assert_eq!(app.ui.dialogs.iter().find(|x| x.id == d).unwrap().fields["workingRgb"], "srgb"); - let note = app.ui.dialogs.iter().find(|x| x.id == d).unwrap().fields["__note"].as_str().unwrap().to_string(); - assert!(note.starts_with("Monitor profile in use: sRGB") && note.contains("fallback"), "{note}"); - assert!(crate::menus::invoke(&mut app, &ctx, "edit.fade", json!({})).is_err()); - app.run("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); - // Content-Aware Fill opens its workspace (caf_ui); OK fills. - let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({})).unwrap(); - assert!(r["contentAwareFill"]["window"].is_array(), "{r}"); - crate::caf_ui::commit(&mut app); - assert!(app.distort.caf.is_none()); - let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareScale", json!({})).unwrap(); - assert_eq!(r["transform"]["rect"], json!([4.0, 4.0, 12.0, 12.0])); - crate::transform_tool::cancel(&mut app); - let d = crate::menus::invoke(&mut app, &ctx, "edit.presets.presetManager", json!({})).unwrap()["dialog"].as_u64().unwrap(); - assert!(crate::dialogs::confirm(&mut app, d).is_ok()); - } -} +mod tests; diff --git a/crates/ui-egui/src/prefs_ui/tests.rs b/crates/ui-egui/src/prefs_ui/tests.rs new file mode 100644 index 0000000000..55e3c6b6e2 --- /dev/null +++ b/crates/ui-egui/src/prefs_ui/tests.rs @@ -0,0 +1,2001 @@ +#[test] +fn memory_usage_has_a_dedicated_explanation_and_keeps_its_value() { + use egui_kittest::{Harness, kittest::Queryable}; + let values = json!({"memoryUsageMb":50000}).as_object().unwrap().clone(); + assert!(!field_visible("performance", &values, "memoryUsageMb", "")); + let mut h = Harness::builder() + .with_size(vec2(680.0, 350.0)) + .build_ui_state(|ui, values| section_fields(ui, "performance", values, &["memoryUsageMb".into()], crate::i18n::Lang::EN, None, ""), values); + h.run_steps(2); + h.get_by_label("Memory Usage"); + h.get_by_label("Per-document RAM limit (MB)"); + h.get_by_label("Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded."); + h.get_by_label("Applies immediately when saved. Memory is not reserved in advance."); + assert_eq!(h.state()["memoryUsageMb"], 50000); +} + +#[test] +fn graphics_dropdowns_are_named_for_their_settings() { + use egui::accesskit::Role; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + let obj = json!({"gpuBackend": "auto", "gpuAdapter": ""}).as_object().unwrap().clone(); + let mut h = Harness::builder() + .with_size(vec2(700.0, 500.0)) + .with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0])) + .build_ui_state(|ui, obj| gpu_status_rows(ui, None, None, obj), obj); + h.run_steps(2); + h.get_by_label("Advanced").click(); + h.run_steps(2); + let labels: Vec = h.query_all_by_role(Role::ComboBox).filter_map(|n| n.accesskit_node().label()).collect(); + assert!(labels.iter().any(|label| label == "GPU Backend"), "{labels:?}"); + if cfg!(target_os = "linux") { + assert!(labels.iter().any(|label| label == "GPU adapter"), "{labels:?}"); + } + assert!(!labels.iter().any(|label| label == "Graphics"), "the section title names neither control: {labels:?}"); +} + +#[test] +fn colour_preferences_take_a_typed_hex_value() { + // #668: the canvas colour (and every colour preference) showed its hex but couldn't take one. + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut h = egui_kittest::Harness::new_ui_state(|ui, rgb: &mut [u8; 3]| super::hex_field(ui, "interface.canvasCustomColor", rgb), [0x28, 0x28, 0x28]); + h.run(); + assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("#282828")); + h.get_by_role(Role::TextInput).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + for ch in "#80".chars() { + h.event(egui::Event::Text(ch.to_string())); + h.run_steps(1); + } + // A partial value stays as typed and leaves the colour alone. + assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("#80")); + assert_eq!(*h.state(), [0x28, 0x28, 0x28]); + for ch in "8080".chars() { + h.event(egui::Event::Text(ch.to_string())); + h.run_steps(1); + } + assert_eq!(*h.state(), [0x80, 0x80, 0x80]); +} + +#[test] +fn quick_export_controls_match_selected_format() { + let mut obj = serde_json::to_value(photocraft_engine::prefs::Export::default()).unwrap().as_object().unwrap().clone(); + assert!(!export_field_visible(&obj, "jpegQuality")); + assert!(!export_field_visible(&obj, "webpLossless")); + assert!(!export_field_visible(&obj, "webpQuality")); + + obj.insert("quickExportFormat".into(), json!("jpg")); + assert!(export_field_visible(&obj, "jpegQuality")); + assert!(!export_field_visible(&obj, "webpLossless")); + assert!(!export_field_visible(&obj, "webpQuality")); + + obj.insert("quickExportFormat".into(), json!("webp")); + assert!(!export_field_visible(&obj, "jpegQuality")); + assert!(export_field_visible(&obj, "webpLossless")); + assert!(!export_field_visible(&obj, "webpQuality"), "lossless WebP does not have a quality setting"); + + obj.insert("webpLossless".into(), json!(false)); + assert!(export_field_visible(&obj, "webpQuality")); + assert_eq!(humanize("webpLossless"), "Lossless"); + assert_eq!(humanize("webpQuality"), "Quality"); + obj.insert("quickExportFormat".into(), json!("exr")); + for key in ["jpegQuality", "webpLossless", "webpQuality", "convertToSrgb", "metadata"] { + assert!(!export_field_visible(&obj, key), "EXR must not offer ignored web settings: {key}"); + } +} + +#[test] +fn the_nudge_pause_is_hidden_while_nudges_are_not_bundled() { + let mut tools = Map::new(); + tools.insert("bundleNudges".into(), json!(true)); + assert!(tools_field_visible(&tools, "nudgeBundlePauseMs")); + assert!(tools_field_visible(&tools, "bundleNudges")); + tools.insert("bundleNudges".into(), json!(false)); + assert!(!tools_field_visible(&tools, "nudgeBundlePauseMs")); + assert!(tools_field_visible(&tools, "bundleNudges") && tools_field_visible(&tools, "showTooltips")); + // A section without the flag (an older preferences object) shows the field. + assert!(tools_field_visible(&Map::new(), "nudgeBundlePauseMs")); + assert_eq!(humanize("bundleNudges"), "Bundle Arrow-Key Nudges"); + assert_eq!(humanize("nudgeBundlePauseMs"), "Nudge Bundle Pause (ms)"); +} + +#[test] +fn rendering_mode_display_respects_explicit_mode_and_legacy_disable() { + let legacy = serde_json::json!({"useGpu": false, "gpuBackend": "auto"}); + assert_eq!(super::rendering_mode_value(legacy.as_object().unwrap()), "cpu"); + let explicit = serde_json::json!({"renderingMode": "gpu", "useGpu": false, "gpuBackend": "cpu"}); + assert_eq!(super::rendering_mode_value(explicit.as_object().unwrap()), "gpu"); + let automatic = serde_json::json!({"renderingMode": null, "useGpu": true, "gpuBackend": "auto"}); + assert_eq!(super::rendering_mode_value(automatic.as_object().unwrap()), "auto"); +} + +#[test] +fn preferences_search_matches_editable_fields_across_sections() { + let values = prefs::Preferences::default().to_json(); + let contains = |needle: &str, section: &str| preference_sections(&values, needle).iter().any(|(id, _)| *id == section); + assert!(contains("UI Scale", "interface")); + assert!(contains("placeholder", "type")); + assert!(contains("performance", "performance")); + assert!(contains("interface.uiScale", "interface")); + assert!(preference_sections(&values, "this setting does not exist").is_empty()); + assert_eq!(preference_sections(&values, "").len(), SECTIONS.len()); +} + +#[test] +fn preferences_dialog_width_follows_its_resizable_area() { + let prefs = serde_json::json!({"__prefsui": "prefs"}); + let prefs = prefs.as_object().unwrap(); + assert_eq!(super::width(prefs, 200.0), Some(380.0)); + assert_eq!(super::width(prefs, 800.0), Some(800.0)); + // A dialog resized wider than it opens is filled, not left with empty space (#7420). + assert_eq!(super::width(prefs, 3000.0), Some(3000.0)); + let shortcuts = serde_json::json!({"__prefsui": "shortcuts"}); + assert_eq!(super::width(shortcuts.as_object().unwrap(), 3000.0), Some(720.0)); +} + +#[test] +fn preferences_settings_fill_the_dialog_down_to_the_buttons() { + // The settings area plus the button row (spacing, 8 pt gap, buttons) stays inside what the + // resizable area gives it, at any size: the area grows to fit its content, so asking for + // more would make the dialog grow every frame. The area follows the dialog's size (#7420). + for available in [300.0, 600.0, 1400.0] { + let h = super::settings_height(available, 4.0, 30.0); + assert!(h + 4.0 + 8.0 + 30.0 <= available, "{available}"); + assert!(h + 4.0 + 8.0 + 30.0 + 8.0 >= available, "{available}"); + } + assert_eq!(super::settings_height(1400.0, 4.0, 30.0) - super::settings_height(600.0, 4.0, 30.0), 800.0); + assert_eq!(super::settings_height(50.0, 4.0, 30.0), 160.0); +} +use super::*; +use std::sync::{Arc, Mutex}; + +#[test] +fn appearance_resolves_both_saved_themes_and_follows_system() { + let mut interface = prefs::Interface { appearance_mode: AppearanceMode::Auto, ..prefs::Interface::default() }; + assert_eq!(selected_theme(&interface, Some(egui::Theme::Dark)), ThemeKind::ProMedium); + assert_eq!(selected_theme(&interface, Some(egui::Theme::Light)), ThemeKind::ProLight); + interface.dark_theme = DarkTheme::Studio; + interface.light_theme = LightTheme::Classic; + assert_eq!(selected_theme(&interface, Some(egui::Theme::Dark)), ThemeKind::Studio); + assert_eq!(selected_theme(&interface, Some(egui::Theme::Light)), ThemeKind::Classic); + interface.appearance_mode = AppearanceMode::Dark; + assert_eq!(selected_theme(&interface, Some(egui::Theme::Light)), ThemeKind::Studio); + interface.appearance_mode = AppearanceMode::Light; + assert_eq!(selected_theme(&interface, Some(egui::Theme::Dark)), ThemeKind::Classic); +} + +#[test] +fn breeze_themes_are_chosen_by_preference_and_fix_the_matching_mode() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for (id, kind, mode) in [ + ("breezeLight", ThemeKind::BreezeLight, AppearanceMode::Light), + ("breezeDark", ThemeKind::BreezeDark, AppearanceMode::Dark), + ("softLight", ThemeKind::SoftLight, AppearanceMode::Light), + ("softDark", ThemeKind::SoftDark, AppearanceMode::Dark), + ] { + app.run("prefs.set", json!({"path": "interface.theme", "value": id})).unwrap(); + tick(&mut app, &ctx); + let interface = app.session.prefs().interface.clone(); + assert_eq!(interface.appearance_mode, mode, "{id}"); + assert_eq!(selected_theme(&interface, None), kind, "{id}"); + assert_eq!(app.ui.theme, kind, "{id}"); + } + // The two slots are independent: choosing the dark one left the light choice alone. + assert_eq!(app.session.prefs().interface.light_theme, LightTheme::SoftLight); + assert_eq!(app.session.prefs().interface.dark_theme, DarkTheme::SoftDark); +} + +#[test] +fn auto_uses_native_system_theme_when_egui_does_not_report_one() { + let (mut app, _) = app_with_store(); + app.services.system_theme = Some(Box::new(|_| Some(egui::Theme::Light))); + app.run("prefs.set", json!({"path": "interface.appearanceMode", "value": "auto"})).unwrap(); + app.run("prefs.set", json!({"path": "interface.appearanceMode", "value": "auto"})).unwrap(); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + assert_eq!(app.ui.theme, ThemeKind::ProLight); +} + +#[test] +fn appearance_button_cycles_modes_without_losing_theme_choices() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("prefs.set", json!({"values": {"interface.darkTheme": "studio", "interface.lightTheme": "classic"}})).unwrap(); + for (mode, visible) in [(AppearanceMode::Auto, ThemeKind::Studio), (AppearanceMode::Light, ThemeKind::Classic), (AppearanceMode::Dark, ThemeKind::Studio)] { + cycle_appearance(&mut app, &ctx); + assert_eq!(app.session.prefs().interface.appearance_mode, mode); + assert_eq!(app.ui.theme, visible); + assert_eq!(app.session.prefs().interface.dark_theme, DarkTheme::Studio); + assert_eq!(app.session.prefs().interface.light_theme, LightTheme::Classic); + } +} + +#[test] +fn darken_and_lighten_interface_step_through_photoshops_brightnesses_and_stop_at_the_ends() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + sync_appearance(&mut app, &ctx); + assert_eq!(app.ui.theme, ThemeKind::ProMedium, "Photoshop's default brightness"); + let press = |app: &mut PhotocraftApp, id: &str| crate::menus::invoke(app, &ctx, id, json!({})).unwrap(); + for expected in [ThemeKind::ProLightGray, ThemeKind::ProLight, ThemeKind::ProLight] { + press(&mut app, "view.lightenInterface"); + assert_eq!(app.ui.theme, expected); + } + // Saved like a choice in Preferences › Interface: the light slot and the Light appearance. + let i = &app.session.prefs().interface; + assert_eq!((i.appearance_mode, i.light_theme), (AppearanceMode::Light, LightTheme::ProLight)); + for expected in [ThemeKind::ProLightGray, ThemeKind::ProMedium, ThemeKind::Pro, ThemeKind::Pro] { + press(&mut app, "view.darkenInterface"); + assert_eq!(app.ui.theme, expected); + } + let i = &app.session.prefs().interface; + assert_eq!((i.appearance_mode, i.dark_theme), (AppearanceMode::Dark, DarkTheme::Pro)); + // Another theme steps from the nearest brightness. + for (theme, id, expected) in [ + ("studio", "view.darkenInterface", ThemeKind::Pro), + ("studio", "view.lightenInterface", ThemeKind::ProLightGray), + ("classic", "view.darkenInterface", ThemeKind::ProMedium), + ("classic", "view.lightenInterface", ThemeKind::ProLight), + ] { + app.run("prefs.set", json!({"path": "interface.theme", "value": theme})).unwrap(); + sync_appearance(&mut app, &ctx); + press(&mut app, id); + assert_eq!(app.ui.theme, expected, "{theme} {id}"); + } +} + +#[test] +fn ctrl_shift_f1_and_f2_darken_and_lighten_the_interface() { + for (id, shortcut) in [("view.darkenInterface", "Cmd+Shift+F1"), ("view.lightenInterface", "Cmd+Shift+F2")] { + assert_eq!(crate::shortcuts::default_shortcut(id).as_deref(), Some(shortcut), "{id}"); + } + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + sync_appearance(&mut app, &ctx); + let press = |app: &mut PhotocraftApp, key| { + let modifiers = egui::Modifiers::COMMAND | egui::Modifiers::SHIFT; + 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(); + }; + press(&mut app, egui::Key::F1); + assert_eq!(app.ui.theme, ThemeKind::Pro); + press(&mut app, egui::Key::F2); + press(&mut app, egui::Key::F2); + assert_eq!(app.ui.theme, ThemeKind::ProLightGray); +} + +fn appearance_frame(app: &mut PhotocraftApp, ctx: &egui::Context, appearance: Option) { + ctx.run_ui(egui::RawInput { system_theme: appearance, ..Default::default() }, |ui| tick(app, ui.ctx())).textures_delta.clear(); +} + +fn assert_palette(ctx: &egui::Context, kind: ThemeKind) { + let t = Tokens::get(ctx); + assert_eq!(t.kind, kind); + for style in [ctx.global_style(), ctx.style_of(egui::Theme::Light), ctx.style_of(egui::Theme::Dark)] { + assert_eq!(style.visuals.panel_fill, t.chrome); + assert_eq!(style.visuals.window_fill, t.card); + assert_eq!(style.visuals.override_text_color, Some(t.text)); + assert_eq!(style.visuals.widgets.inactive.bg_fill, t.field); + assert_eq!(style.visuals.dark_mode, t.dark()); + assert_eq!(style.text_styles[&egui::TextStyle::Body].size, if t.pro { 12.0 } else { 12.5 }); + } + assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::System); +} + +#[test] +fn auto_appearance_follows_live_changes_without_saving_resolved_palettes() { + for (dark, light) in [(ThemeKind::ProMedium, ThemeKind::StudioLight), (ThemeKind::SolarizedDark, ThemeKind::Adwaita)] { + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, Default::default()); + app.run("prefs.set", json!({"values": {"interface.appearanceMode": "auto", "interface.darkTheme": dark.id(), "interface.lightTheme": light.id()}})) + .unwrap(); + appearance_frame(&mut app, &ctx, Some(egui::Theme::Light)); + let revision = app.session.prefs.rev(); + let interface = app.session.prefs().interface.clone(); + let saved = store.lock().unwrap().clone().unwrap(); + assert_eq!(stored(&store)["interface"]["appearanceMode"], "auto"); + let gpu_style = canvas_style(&app); + for (appearance, expected) in [(Some(egui::Theme::Light), light), (Some(egui::Theme::Dark), dark), (Some(egui::Theme::Light), light), (None, dark)] { + appearance_frame(&mut app, &ctx, appearance); + assert_palette(&ctx, expected); + assert_eq!(app.ui.theme, expected); + assert_eq!(app.session.prefs().interface, interface); + assert_eq!(app.session.prefs.rev(), revision); + assert_eq!(store.lock().unwrap().as_ref(), Some(&saved)); + assert_eq!(canvas_style(&app), gpu_style); + assert_eq!(pasteboard_color(&app), None); + } + // A fresh launch resolves its saved Auto choice against the new OS input. + for (appearance, expected) in [(Some(egui::Theme::Light), light), (Some(egui::Theme::Dark), dark), (None, dark)] { + let (mut restarted, store) = app_with_saved(Some(saved.clone())); + let fresh = egui::Context::default(); + PhotocraftApp::setup_context(&fresh, Default::default()); + appearance_frame(&mut restarted, &fresh, appearance); + assert_palette(&fresh, expected); + assert_eq!(restarted.ui.theme, expected); + assert_eq!(restarted.session.prefs().interface, interface); + assert_eq!(store.lock().unwrap().as_ref(), Some(&saved)); + } + app.run("prefs.set", json!({"values": {"interface.canvasColor": "custom", "interface.canvasCustomColor": "#123456"}})).unwrap(); + for appearance in [Some(egui::Theme::Light), Some(egui::Theme::Dark)] { + appearance_frame(&mut app, &ctx, appearance); + assert_eq!(pasteboard_color(&app), Some(Color32::from_rgb(0x12, 0x34, 0x56))); + assert_eq!(canvas_style(&app), gpu_style); + } + } +} + +#[test] +fn manual_theme_tokens_and_global_styles_stay_fixed_across_os_changes() { + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, Default::default()); + for kind in ThemeKind::ALL { + app.run("prefs.set", json!({"path": "interface.theme", "value": kind.id()})).unwrap(); + appearance_frame(&mut app, &ctx, Some(egui::Theme::Dark)); + let interface = app.session.prefs().interface.clone(); + let revision = app.session.prefs.rev(); + let saved = store.lock().unwrap().clone().unwrap(); + assert_eq!(interface.appearance_mode, if Tokens::for_kind(kind).dark() { AppearanceMode::Dark } else { AppearanceMode::Light }); + for appearance in [Some(egui::Theme::Dark), Some(egui::Theme::Light), Some(egui::Theme::Dark), None] { + appearance_frame(&mut app, &ctx, appearance); + assert_palette(&ctx, kind); + assert_eq!(Tokens::get(&ctx), Tokens::for_kind(kind)); + assert_eq!(app.ui.theme, kind); + assert_eq!(app.session.prefs().interface, interface); + assert_eq!(app.session.prefs.rev(), revision); + assert_eq!(store.lock().unwrap().as_ref(), Some(&saved)); + } + } +} + +#[test] +fn auto_appearance_replaces_a_restored_egui_dark_pin() { + let (mut app, _) = app_with_saved(Some(json!({"interface": {"appearanceMode": "auto"}}).to_string())); + let ctx = egui::Context::default(); + ctx.set_theme(egui::ThemePreference::Dark); + assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::Dark); + appearance_frame(&mut app, &ctx, Some(egui::Theme::Light)); + assert_palette(&ctx, ThemeKind::ProLight); + assert_eq!(app.session.prefs().interface.appearance_mode, AppearanceMode::Auto); + // A restored pin must also clear when the concrete PhotoCraft palette stays the same. + ctx.set_theme(egui::ThemePreference::Dark); + appearance_frame(&mut app, &ctx, Some(egui::Theme::Light)); + assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::System); + assert_palette(&ctx, ThemeKind::ProLight); + appearance_frame(&mut app, &ctx, Some(egui::Theme::Dark)); + assert_palette(&ctx, ThemeKind::ProMedium); + assert_eq!(app.session.prefs().interface.appearance_mode, AppearanceMode::Auto); +} + +#[test] +fn system_theme_menu_choice_stays_checked_as_the_appearance_changes() { + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, Default::default()); + app.run("prefs.set", json!({"values": {"interface.darkTheme": "solarizedDark", "interface.lightTheme": "adwaita"}})).unwrap(); + appearance_frame(&mut app, &ctx, Some(egui::Theme::Light)); + crate::menus::invoke(&mut app, &ctx, "window.theme.system", json!({})).unwrap(); + appearance_frame(&mut app, &ctx, Some(egui::Theme::Light)); + let interface = app.session.prefs().interface.clone(); + let saved = store.lock().unwrap().clone().unwrap(); + let revision = app.session.prefs.rev(); + for appearance in [Some(egui::Theme::Light), Some(egui::Theme::Dark), None] { + appearance_frame(&mut app, &ctx, appearance); + let items = crate::menus::menu_items(&app); + let item = |id: &str| items.iter().find(|i| i.id == id).unwrap(); + assert_eq!(item("window.theme.system").checked, Some(true)); + assert!(item("window.theme.system").enabled); + assert_eq!(item("window.theme.system").path, ["Window", "Theme"]); + for kind in ThemeKind::ALL { + assert_eq!(item(&format!("window.theme.{}", kind.id())).checked, Some(false)); + } + assert_eq!(app.session.prefs().interface.appearance_mode, AppearanceMode::Auto); + assert_eq!(app.session.prefs().interface, interface); + assert_eq!(app.session.prefs.rev(), revision); + assert_eq!(store.lock().unwrap().as_ref(), Some(&saved)); + } + crate::menus::invoke(&mut app, &ctx, "window.theme.solarizedDark", json!({})).unwrap(); + for appearance in [Some(egui::Theme::Light), Some(egui::Theme::Dark)] { + appearance_frame(&mut app, &ctx, appearance); + assert_palette(&ctx, ThemeKind::SolarizedDark); + let items = crate::menus::menu_items(&app); + let item = |id: &str| items.iter().find(|i| i.id == id).unwrap(); + assert_eq!(item("window.theme.solarizedDark").checked, Some(true)); + assert_eq!(item("window.theme.system").checked, Some(false)); + assert_eq!(stored(&store)["interface"]["appearanceMode"], "dark"); + assert_eq!(app.session.prefs().interface.light_theme, LightTheme::Adwaita); + } +} + +#[test] +fn preferences_interface_offers_and_applies_sync_with_system() { + use egui_kittest::{Harness, kittest::Queryable}; + let (mut app, store) = app_with_store(); + app.run("prefs.set", json!({"values": {"interface.language": "en", "interface.darkTheme": "solarizedDark", "interface.lightTheme": "adwaita"}})).unwrap(); + let interface = app.session.prefs().interface.clone(); + open_preferences(&mut app, "interface"); + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.input_mut().system_theme = Some(egui::Theme::Light); + h.run_steps(4); + for label in ["Adwaita", "Adwaita dark", "Solarized dark"] { + assert!(h.query_by_label(label).is_some(), "missing theme choice {label}"); + } + h.get_by_value("Dark").click(); + h.run_steps(2); + h.get_by_label("Sync with system").click(); + h.run_steps(2); + h.get_by_label("Apply").click(); + h.run_steps(4); + assert_eq!(h.state().session.prefs().interface.appearance_mode, AppearanceMode::Auto); + assert_eq!(h.state().session.prefs().interface.dark_theme, interface.dark_theme); + assert_eq!(h.state().session.prefs().interface.light_theme, interface.light_theme); + assert_eq!(h.state().session.prefs().interface.theme, interface.theme); + assert_palette(&h.ctx, ThemeKind::Adwaita); + assert_eq!(stored(&store)["interface"]["appearanceMode"], "auto"); + let saved = store.lock().unwrap().clone().unwrap(); + let (mut restarted, reloaded) = app_with_saved(Some(saved.clone())); + let fresh = egui::Context::default(); + PhotocraftApp::setup_context(&fresh, Default::default()); + appearance_frame(&mut restarted, &fresh, Some(egui::Theme::Dark)); + assert_palette(&fresh, ThemeKind::SolarizedDark); + assert_eq!(restarted.session.prefs().interface.appearance_mode, AppearanceMode::Auto); + assert_eq!(restarted.session.prefs().interface.dark_theme, interface.dark_theme); + assert_eq!(restarted.session.prefs().interface.light_theme, interface.light_theme); + assert_eq!(restarted.session.prefs().interface.theme, interface.theme); + assert_eq!(reloaded.lock().unwrap().as_ref(), Some(&saved)); +} + +#[test] +fn theme_star_saves_favorite_and_menu_groups_it() { + use egui_kittest::{Harness, kittest::Queryable}; + let (mut app, _) = app_with_store(); + open_preferences(&mut app, "interface"); + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + h.get_by_label("Classic").hover(); + h.run_steps(2); + h.get_by_label("Add to favorites: Classic").click(); + h.run_steps(2); + h.get_by_label("Apply").click(); + h.run_steps(2); + assert_eq!(h.state().session.prefs().interface.favorite_themes, vec![SavedTheme::Classic]); + assert!(h.query_by_label("Remove from favorites: Classic").is_some()); + let (light, dark) = favorite_theme_groups(&[SavedTheme::Studio, SavedTheme::Classic, SavedTheme::Adwaita]); + assert_eq!(light, vec![ThemeKind::Classic, ThemeKind::Adwaita]); + assert_eq!(dark, vec![ThemeKind::Studio]); +} + +/// The favourite star badge overhangs its swatch; showing it on hover must not move the swatches +/// after it, or the row would shift under the pointer. +#[test] +fn theme_star_badge_on_hover_does_not_move_the_next_swatch() { + use egui_kittest::{Harness, kittest::Queryable}; + let (mut app, _) = app_with_store(); + open_preferences(&mut app, "interface"); + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + let first = h.get_by_label("Classic").rect(); + let next = h.get_by_label("Adwaita").rect(); + h.hover_at(first.right_top() + vec2(-3.0, 3.0)); + h.run_steps(3); + assert!(h.query_by_label("Add to favorites: Classic").is_some(), "the badge shows while the swatch is hovered"); + assert_eq!(h.get_by_label("Classic").rect(), first); + assert_eq!(h.get_by_label("Adwaita").rect(), next); +} + +#[test] +fn preferences_interface_shows_language_without_scrolling() { + // #2532: in a small window the theme cards filled the page and Language sat out of view + // below them. Like Photoshop, Presentation follows Appearance and both fit. + use egui_kittest::{Harness, kittest::Queryable}; + let (mut app, _) = app_with_store(); + app.run("prefs.set", json!({"values": {"interface.language": "en"}})).unwrap(); + open_preferences(&mut app, "interface"); + let mut h = Harness::builder().with_size(vec2(1000.0, 750.0)).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + let language = h.query_all_by_label("Language").next().expect("the Language row").rect(); + let dark = h.query_all_by_label("Dark Theme").next().expect("the dark theme row").rect(); + let ok = h.get_by_label("OK").rect(); + assert!(dark.bottom() < language.top(), "Presentation {language:?} follows the theme swatches {dark:?}"); + assert!(language.bottom() < ok.top() - 20.0, "Language {language:?} must show above the buttons {ok:?} without scrolling"); + // Every theme in the option lists gets a swatch, Breeze included. + for (id, _) in LIGHT_THEME_OPTIONS.iter().chain(DARK_THEME_OPTIONS) { + let label = choice_label(id); + assert!(h.query_by_label(&label).is_some(), "missing theme swatch {label}"); + } + assert!(h.query_by_label("Breeze light").is_some() && h.query_by_label("Breeze dark").is_some()); +} + +#[test] +fn preferences_interface_search_hides_rows_and_skips_empty_groups() { + use egui_kittest::{Harness, kittest::Queryable}; + let render = |search: &str| { + let (mut app, _) = app_with_store(); + app.run("prefs.set", json!({"values": {"interface.language": "en"}})).unwrap(); + let id = open_preferences(&mut app, "interface"); + app.ui.dialog_mut(id).unwrap().fields.insert("__search".into(), json!(search)); + let mut h = Harness::builder().with_size(vec2(1000.0, 750.0)).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + h + }; + let shown = |h: &Harness<'_, PhotocraftApp>, label: &str| h.query_all_by_label(label).next().is_some(); + + let h = render("language"); + assert!(shown(&h, "Language") && shown(&h, "Presentation")); + for gone in ["Appearance", "Appearance Mode", "Dark Theme", "Options", "UI scale"] { + assert!(!shown(&h, gone), "\"language\" must not show {gone}"); + } + + let h = render("theme"); + assert!(shown(&h, "Appearance") && shown(&h, "Light Theme") && shown(&h, "Dark Theme") && shown(&h, "Breeze dark")); + for gone in ["Appearance Mode", "Presentation", "Language", "Options"] { + assert!(!shown(&h, gone), "\"theme\" must not show {gone}"); + } + + let h = render(""); + for group in ["Appearance", "Appearance Mode", "Presentation", "Options", "UI scale"] { + assert!(shown(&h, group), "an empty search shows {group}"); + } +} + +fn app_with_store() -> (PhotocraftApp, Arc>>) { + app_with_saved(None) +} + +fn app_with_saved(text: Option) -> (PhotocraftApp, Arc>>) { + let store: Arc>> = Arc::new(Mutex::new(text)); + (app_on(&store, Arc::default()), store) +} + +/// An app whose preferences live in `store`; writes fail while `fail` is set. +fn app_on(store: &Arc>>, fail: Arc) -> PhotocraftApp { + let (a, b) = (store.clone(), store.clone()); + let services = crate::Services { + load_prefs: Some(Box::new(move || a.lock().unwrap().clone())), + save_prefs: Some(Box::new(move |s: &str| { + if fail.load(std::sync::atomic::Ordering::Relaxed) { + return Err("storage is full".into()); + } + *b.lock().unwrap() = Some(s.to_string()); + Ok(()) + })), + ..Default::default() + }; + PhotocraftApp::new(photocraft_engine::Session::new(), services) +} + +fn stored(store: &Arc>>) -> Value { + serde_json::from_str(store.lock().unwrap().as_deref().unwrap_or("null")).unwrap() +} + +#[test] +fn a_wrongly_typed_value_resets_only_itself_and_is_repaired_on_disk() { + // #6611: one bad value used to reset every preference, on every launch. + let saved = json!({ + "fileHandling": {"recentFileCount": "ten", "autosaveMinutes": 5}, + "performance": {"historyStates": 12}, + "shortcuts": {"edit.fill": "Cmd+Shift+F", "file.open": 7}, + "futureSection": {"kept": true}, + }); + let (mut app, store) = app_with_saved(Some(saved.to_string())); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + let p = app.session.prefs(); + assert_eq!((p.file_handling.recent_file_count, p.file_handling.autosave_minutes, p.performance.history_states), (20, 5, 12)); + assert!(!app.ui.status.contains("reset"), "{}", app.ui.status); + let notice = app.ui.notices.iter().find(|n| n.title == "Some preferences were reset").expect("a notice names the bad values"); + let text = notice.text(¬ice.lines[0]); + assert!(text.contains("fileHandling.recentFileCount, shortcuts.file.open"), "{text}"); + // The file now holds the default in its place and keeps everything else. + let v = stored(&store); + assert_eq!(v["fileHandling"]["recentFileCount"], 20); + assert_eq!(v["fileHandling"]["autosaveMinutes"], 5); + assert_eq!(v["performance"]["historyStates"], 12); + assert_eq!(v["shortcuts"]["edit.fill"], "Cmd+Shift+F"); + assert!(v["shortcuts"].get("file.open").is_none()); + assert_eq!(v["futureSection"]["kept"], true, "keys this version doesn't know survive"); + // So the next launch loads cleanly. + let (mut next, _) = app_with_saved(store.lock().unwrap().clone()); + tick(&mut next, &ctx); + assert!(next.ui.notices.iter().all(|n| n.title != "Some preferences were reset")); + assert_eq!(next.session.prefs().file_handling.autosave_minutes, 5); +} + +#[test] +fn an_old_files_shift_tool_switch_migration_is_saved_with_the_new_version() { + // #5647: a file before version 2 loads with Use Shift Key for Tool Switch on. Saving + // writes that and the current version, so turning it off later isn't taken for the old + // default on the next launch. + let ctx = egui::Context::default(); + for saved in [ + json!({"version": 1, "tools": {"useShiftKeyForToolSwitch": false}, "futureSection": {"kept": true}}), + json!({"tools": {"useShiftKeyForToolSwitch": false}, "futureSection": {"kept": true}}), + ] { + let (mut app, store) = app_with_saved(Some(saved.to_string())); + tick(&mut app, &ctx); + assert!(app.session.prefs().tools.use_shift_key_for_tool_switch, "{saved}"); + app.run("prefs.set", json!({"values": {"performance.historyStates": 12}})).unwrap(); + tick(&mut app, &ctx); + let v = stored(&store); + assert_eq!(v["version"], json!(prefs::PREFS_VERSION), "{saved}"); + assert_eq!(v["tools"]["useShiftKeyForToolSwitch"], true, "{saved}"); + assert_eq!(v["futureSection"]["kept"], true, "keys this version doesn't know survive"); + app.run("prefs.set", json!({"values": {"tools.useShiftKeyForToolSwitch": false}})).unwrap(); + tick(&mut app, &ctx); + let (mut next, _) = app_with_saved(store.lock().unwrap().clone()); + tick(&mut next, &ctx); + assert!(!next.session.prefs().tools.use_shift_key_for_tool_switch, "{saved}: turned off, it stays off"); + } +} + +#[test] +fn an_old_sparse_file_keeps_another_instances_change() { + // Two instances on a version 1 file that lacks most keys: one changes a key the file + // doesn't have, the other then saves an unrelated change and must not write its default + // over it. + let saved = json!({"version": 1, "tools": {"useShiftKeyForToolSwitch": false}}); + let store = Arc::new(Mutex::new(Some(saved.to_string()))); + let ctx = egui::Context::default(); + let (mut a, mut b) = (app_on(&store, Arc::default()), app_on(&store, Arc::default())); + tick(&mut a, &ctx); + tick(&mut b, &ctx); + b.run("prefs.set", json!({"values": {"interface.theme": "studio"}})).unwrap(); + tick(&mut b, &ctx); + assert_eq!(stored(&store)["interface"]["theme"], "studio"); + a.run("prefs.set", json!({"values": {"performance.historyStates": 12}})).unwrap(); + tick(&mut a, &ctx); + let v = stored(&store); + assert_eq!((v["interface"]["theme"].as_str(), v["performance"]["historyStates"].as_u64()), (Some("studio"), Some(12))); +} + +#[test] +fn another_instances_shift_tool_switch_choice_beats_this_ones_migration() { + // Two instances migrate the same version 1 file. One turns the switch off and saves + // version 2; the other's unrelated save must not write its migrated "on" over that. + let saved = json!({"version": 1, "tools": {"useShiftKeyForToolSwitch": false}}); + let store = Arc::new(Mutex::new(Some(saved.to_string()))); + let ctx = egui::Context::default(); + let (mut a, mut b) = (app_on(&store, Arc::default()), app_on(&store, Arc::default())); + tick(&mut a, &ctx); + tick(&mut b, &ctx); + b.run("prefs.set", json!({"values": {"tools.useShiftKeyForToolSwitch": false}})).unwrap(); + tick(&mut b, &ctx); + assert_eq!(stored(&store)["tools"]["useShiftKeyForToolSwitch"], false); + a.run("prefs.set", json!({"values": {"performance.historyStates": 12}})).unwrap(); + tick(&mut a, &ctx); + let v = stored(&store); + assert_eq!((v["tools"]["useShiftKeyForToolSwitch"].as_bool(), v["performance"]["historyStates"].as_u64()), (Some(false), Some(12))); + assert_eq!(v["version"], json!(prefs::PREFS_VERSION)); +} + +#[test] +fn turning_the_shift_tool_switch_off_is_saved_over_another_instances_migration() { + // Two instances migrate the same version 1 file. B saves version 2 with the migrated "on"; + // the user then turns the switch off in A, which must be written. + let saved = json!({"version": 1, "tools": {"useShiftKeyForToolSwitch": false}}); + let store = Arc::new(Mutex::new(Some(saved.to_string()))); + let ctx = egui::Context::default(); + let (mut a, mut b) = (app_on(&store, Arc::default()), app_on(&store, Arc::default())); + tick(&mut a, &ctx); + tick(&mut b, &ctx); + b.run("prefs.set", json!({"values": {"performance.historyStates": 12}})).unwrap(); + tick(&mut b, &ctx); + assert_eq!(stored(&store)["tools"]["useShiftKeyForToolSwitch"], true); + a.run("prefs.set", json!({"values": {"tools.useShiftKeyForToolSwitch": false}})).unwrap(); + tick(&mut a, &ctx); + let v = stored(&store); + assert_eq!((v["tools"]["useShiftKeyForToolSwitch"].as_bool(), v["performance"]["historyStates"].as_u64()), (Some(false), Some(12))); +} + +#[test] +fn a_newer_files_version_is_kept_on_save() { + let saved = json!({"version": prefs::PREFS_VERSION + 1, "tools": {"useShiftKeyForToolSwitch": false}}); + let (mut app, store) = app_with_saved(Some(saved.to_string())); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + assert!(!app.session.prefs().tools.use_shift_key_for_tool_switch, "a newer file isn't migrated"); + app.run("prefs.set", json!({"values": {"performance.historyStates": 12}})).unwrap(); + tick(&mut app, &ctx); + let v = stored(&store); + assert_eq!(v["version"], json!(prefs::PREFS_VERSION + 1)); + assert_eq!(v["performance"]["historyStates"], 12); +} + +#[test] +fn merge_keeps_changes_made_elsewhere() { + let base = json!({"a": {"x": 1, "y": 1}, "list": [1], "gone": 1, "kept": 1}); + // Here: a.x changed, `gone` removed, `new` added. + let ours = json!({"a": {"x": 2, "y": 1}, "list": [1], "kept": 1, "new": 1}); + // There: a.y, `list` and `kept` changed, and a key this version doesn't know. + let mut theirs = json!({"a": {"x": 1, "y": 3}, "list": [1, 2], "gone": 1, "kept": 5, "future": true}); + merge_changes(&base, &ours, &mut theirs); + assert_eq!(theirs, json!({"a": {"x": 2, "y": 3}, "list": [1, 2], "kept": 5, "new": 1, "future": true})); + // Arrays are leaves: a list changed here replaces the stored one whole. + merge_changes(&json!({"list": [1]}), &json!({"list": [1, 3]}), &mut theirs); + assert_eq!(theirs["list"], json!([1, 3])); + // Nothing changed here: storage is left as it is, whatever it holds. + let mut odd = json!({"x": [7]}); + merge_changes(&ours, &ours, &mut odd); + assert_eq!(odd, json!({"x": [7]})); + // A value that changed type here replaces the stored one. + merge_changes(&json!({"a": 1}), &json!({"a": {"b": 2}}), &mut theirs); + assert_eq!(theirs["a"], json!({"b": 2})); +} + +#[test] +fn saving_keeps_preferences_another_instance_changed() { + let store = Arc::new(Mutex::new(None)); + let ctx = egui::Context::default(); + // Two browser tabs (or app windows) on the same storage. + let (mut a, mut b) = (app_on(&store, Arc::default()), app_on(&store, Arc::default())); + tick(&mut a, &ctx); + tick(&mut b, &ctx); + a.run("prefs.set", json!({"values": {"interface.theme": "studio"}})).unwrap(); + tick(&mut a, &ctx); + assert_eq!(stored(&store)["interface"]["theme"], "studio"); + // The other one, never reloaded, saves an unrelated change: the theme stays. + b.run("prefs.set", json!({"values": {"performance.historyStates": 12}})).unwrap(); + tick(&mut b, &ctx); + let v = stored(&store); + assert_eq!((v["interface"]["theme"].as_str(), v["performance"]["historyStates"].as_u64()), (Some("studio"), Some(12))); + // And the first one's next save keeps the second one's change. + a.run("prefs.set", json!({"values": {"interface.showTooltips": false}})).unwrap(); + tick(&mut a, &ctx); + let v = stored(&store); + assert_eq!(v["performance"]["historyStates"], 12); + assert_eq!(v["interface"]["showTooltips"], false); + // A value changed in both: the latest save wins. + b.run("prefs.set", json!({"values": {"interface.theme": "classic"}})).unwrap(); + tick(&mut b, &ctx); + assert_eq!(stored(&store)["interface"]["theme"], "classic"); + // Unreadable storage is overwritten with this instance's preferences. + *store.lock().unwrap() = Some("not json".into()); + a.run("prefs.set", json!({"values": {"performance.historyStates": 30}})).unwrap(); + tick(&mut a, &ctx); + let (mut c, _) = app_with_saved(store.lock().unwrap().clone()); + tick(&mut c, &ctx); + assert_eq!(c.session.prefs().performance.history_states, 30); + assert_eq!(c.session.prefs().interface.theme, Theme::Studio); +} + +#[test] +fn failed_preference_saves_are_retried() { + use std::sync::atomic::{AtomicBool, Ordering}; + let store = Arc::new(Mutex::new(None)); + let fail = Arc::new(AtomicBool::new(true)); + let mut app = app_on(&store, fail.clone()); + tick(&mut app, &egui::Context::default()); + app.run("prefs.set", json!({"values": {"interface.theme": "studio"}})).unwrap(); + // The write fails: reported, and retried after a backoff rather than marked saved. + assert_eq!(persist(&mut app, 100.0), Some(SAVE_RETRY_S)); + assert!(app.ui.status.starts_with("Couldn't save preferences: storage is full") && app.ui.status_error); + assert!(store.lock().unwrap().is_none()); + assert_eq!(persist(&mut app, 101.0), Some(1.0), "not due yet"); + // Storage works again: the pending change is written without another edit. + fail.store(false, Ordering::Relaxed); + assert_eq!(persist(&mut app, 102.0), None); + assert_eq!(stored(&store)["interface"]["theme"], "studio"); + assert_eq!(app.ui.status, "Preferences saved"); + assert_eq!(persist(&mut app, 103.0), None, "nothing left to save"); + + // A persistent failure backs off up to a cap and raises a notice once. + fail.store(true, Ordering::Relaxed); + app.run("prefs.set", json!({"values": {"interface.theme": "classic"}})).unwrap(); + let mut now = 200.0; + let mut delays = Vec::new(); + for _ in 0..6 { + let wait = persist(&mut app, now).unwrap(); + delays.push(wait); + now += wait; + } + assert_eq!(delays, [2.0, 4.0, 8.0, 16.0, SAVE_RETRY_MAX_S, SAVE_RETRY_MAX_S]); + assert_eq!(app.ui.notices.iter().filter(|n| n.error && n.title == "Preferences can't be saved").count(), 1); + // A newer change retries sooner than the backoff, but not on every frame. + app.run("prefs.set", json!({"values": {"interface.theme": "pro"}})).unwrap(); + assert_eq!(persist(&mut app, now - 29.0), Some(1.0)); + fail.store(false, Ordering::Relaxed); + assert_eq!(persist(&mut app, now - 28.0), None); + assert_eq!(stored(&store)["interface"]["theme"], "pro"); + assert!(app.ui.notices.is_empty(), "the notice goes once preferences are saved"); +} + +#[test] +fn auto_scale_preserves_system_scale() { + use prefs::UiScale::Auto; + // Whatever the monitor, 4K included: an unscaled desktop stays at 100% (#1278), and a + // fractional or below-100% system scale is the user's choice (#1072). + for dpi in [0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0] { + assert_eq!(display_scale(Auto, Some(dpi)), dpi); + } + assert_eq!(display_scale(Auto, None), 1.0); + assert_eq!(display_scale(Auto, Some(f32::NAN)), 1.0); + assert_eq!(display_scale(Auto, Some(-2.0)), 1.0); +} + +#[test] +fn scale_preferences_and_monitor_changes_apply_live() { + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + { + let mut step = |physical: egui::Vec2, native: f32, expected: f32| { + let mut input = egui::RawInput::default(); + let viewport = input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap(); + viewport.native_pixels_per_point = Some(native); + viewport.monitor_size = Some(physical / (native * ctx.zoom_factor())); + ctx.run_ui(input, |ui| tick(&mut app, ui.ctx())).textures_delta.clear(); + // Scale changes take effect on the following pass. + let mut input = egui::RawInput::default(); + let viewport = input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap(); + viewport.native_pixels_per_point = Some(native); + viewport.monitor_size = Some(physical / (native * ctx.zoom_factor())); + ctx.run_ui(input, |ui| tick(&mut app, ui.ctx())).textures_delta.clear(); + assert!((ctx.pixels_per_point() - expected).abs() < 1e-4); + }; + for _ in 0..4 { + step(vec2(3840.0, 2160.0), 1.0, 1.0); + } + step(vec2(1920.0, 1080.0), 1.0, 1.0); + step(vec2(3840.0, 2160.0), 1.5, 1.5); + step(vec2(3840.0, 2160.0), 1.25, 1.25); + step(vec2(2560.0, 1440.0), 1.75, 1.75); + step(vec2(3840.0, 2160.0), 1.0, 1.0); + } + for (pref, expected) in [ + ("200", 2.0), + ("125", 1.25), + ("150", 1.5), + ("100", 1.0), + ("105", 1.05), + ("110", 1.1), + ("115", 1.15), + ("120", 1.2), + ("95", 0.95), + ("90", 0.9), + ("85", 0.85), + ("80", 0.8), + ("auto", 1.5), + ] { + app.run("prefs.set", json!({"values": {"interface.uiScale": pref}})).unwrap(); + let mut input = egui::RawInput::default(); + input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().native_pixels_per_point = Some(1.5); + ctx.run_ui(input.clone(), |ui| tick(&mut app, ui.ctx())).textures_delta.clear(); + ctx.run_ui(input, |ui| tick(&mut app, ui.ctx())).textures_delta.clear(); + assert!((ctx.pixels_per_point() - expected).abs() < 1e-4); + } +} + +#[test] +fn intermediate_ui_scale_choices_can_be_applied_from_preferences() { + use egui_kittest::{Harness, kittest::Queryable}; + let (mut app, store) = app_with_store(); + app.run("prefs.set", json!({"path": "interface.uiScale", "value": "100"})).unwrap(); + open_preferences(&mut app, "interface"); + let mut h = Harness::builder().with_size(vec2(1400.0, 1100.0)).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + let mut current = "100%"; + for (label, value) in [("105%", "105"), ("110%", "110"), ("115%", "115"), ("120%", "120")] { + h.get_by_value(current).click(); + h.run_steps(2); + h.get_by_label(label).click(); + h.run_steps(2); + h.get_by_label("Apply").click(); + h.run_steps(4); + assert_eq!(h.state().session.prefs().interface.ui_scale.name(), value); + assert_eq!(stored(&store)["interface"]["uiScale"], value); + current = label; + } +} + +#[test] +fn ui_font_size_commands_follow_themes_and_dpi_and_reset_live() { + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, ThemeKind::Pro); + let mut input = egui::RawInput::default(); + input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().native_pixels_per_point = Some(1.5); + for (theme, scale, expected) in + [("pro", "100", 1.0), ("studio", "auto", 1.5), ("studioLight", "200", 2.0), ("proMedium", "100", 1.0), ("classic", "auto", 1.5)] + { + app.run("prefs.set", json!({"values": {"interface.uiFontSize": "large", "interface.theme": theme, "interface.uiScale": scale}})).unwrap(); + for _ in 0..3 { + ctx.run_ui(input.clone(), |ui| tick(&mut app, ui.ctx())).textures_delta.clear(); + } + assert!((ctx.pixels_per_point() - expected).abs() < 1e-4); + assert_eq!(ctx.fonts(|f| f.definitions().font_data["Inter"].tweak.scale), 16.0 / 12.0); + } + app.run("prefs.reset", json!({"path": "interface.uiFontSize"})).unwrap(); + for _ in 0..2 { + ctx.run_ui(input.clone(), |ui| tick(&mut app, ui.ctx())).textures_delta.clear(); + } + assert_eq!(ctx.fonts(|f| f.definitions().font_data["Inter"].tweak.scale), 1.0); + assert!((ctx.pixels_per_point() - 1.5).abs() < 1e-4, "resetting font size keeps UI Scale"); +} + +#[test] +fn recent_files_survive_a_restart_and_honour_the_count() { + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + app.push_recent("/work/a.psd"); + app.push_recent("/work/b.png"); + tick(&mut app, &ctx); + let saved = store.lock().unwrap().clone().unwrap(); + // A new app instance (a restart) gets the list back, newest first. + let (mut app2, _) = app_with_saved(Some(saved)); + tick(&mut app2, &ctx); + assert_eq!(app2.ui.recent_files, vec!["/work/b.png".to_string(), "/work/a.psd".to_string()]); + // Lowering "Recent File List Contains" shortens the menu at once; 0 turns it off. + app2.run("prefs.set", json!({"values": {"fileHandling.recentFileCount": 1}})).unwrap(); + tick(&mut app2, &ctx); + assert_eq!(app2.ui.recent_files, vec!["/work/b.png".to_string()]); + app2.push_recent("/work/c.tif"); + assert_eq!(app2.session.prefs().file_handling.recent_files, vec!["/work/c.tif".to_string()]); + app2.run("prefs.set", json!({"values": {"fileHandling.recentFileCount": 0}})).unwrap(); + tick(&mut app2, &ctx); + app2.push_recent("/work/d.tif"); + assert!(app2.ui.recent_files.is_empty()); + // Clearing the list in the Preferences dialog (or by an agent) reaches the menu. + app2.run("prefs.set", json!({"values": {"fileHandling.recentFileCount": 20, "fileHandling.recentFiles": ["/x.psd"]}})).unwrap(); + tick(&mut app2, &ctx); + assert_eq!(app2.ui.recent_files, vec!["/x.psd".to_string()]); + // A hostile count from a hand-edited preferences file is capped, not trusted. + app2.run("prefs.set", json!({"values": {"fileHandling.recentFileCount": 100}})).unwrap(); + app2.session.prefs.edit(|p| p.file_handling.recent_file_count = u32::MAX); + assert_eq!(app2.recent_cap(), 100); +} + +#[test] +fn brush_picker_view_survives_a_restart() { + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + app.ui.brush_picker_list.show_stroke = false; + app.ui.brush_picker_list.scale = 0.4; + crate::brush_picker::persist(&mut app, &ctx); + tick(&mut app, &ctx); + assert_eq!(stored(&store)["brushPicker"]["showStroke"], json!(false)); + // A restart gets the view back at startup, before the picker is ever opened. + let saved = store.lock().unwrap().clone().unwrap(); + 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.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. + 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); +} + +#[test] +fn selected_tool_survives_a_restart_without_option_changes() { + use crate::state::Tool; + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + assert_eq!(app.ui.tool, Tool::Brush); + // Every tool, including flyout-only tools, can be restored. Return to Brush last to + // prove selecting the default overwrites a previously remembered nondefault tool. + for tool in Tool::ALL.into_iter().chain([Tool::Brush]) { + app.ui.tool = tool; + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + assert_eq!(stored(&store)["selectedTool"], serde_json::to_value(tool).unwrap()); + let (app2, _) = app_with_saved(store.lock().unwrap().clone()); + assert_eq!(app2.ui.tool, tool, "restored before the first frame"); + assert_eq!(app2.ui.group_tool(tool.key()), Some(tool)); + assert_eq!(app2.ui.tool_options, crate::state::ToolOptions::default()); + } +} + +#[test] +fn selected_tool_is_flushed_on_exit_without_another_frame() { + let (mut app, store) = app_with_store(); + app.ui.tool = crate::state::Tool::Move; + crate::tool_memory::save_on_exit(&mut app).unwrap(); + let (app2, _) = app_with_saved(store.lock().unwrap().clone()); + assert_eq!(app2.ui.tool, crate::state::Tool::Move); +} + +#[test] +fn selected_tool_explicit_eraser_survives_exit_during_temporary_switches() { + use crate::state::Tool; + for spring in [false, true] { + for menu in [false, true] { + let (mut app, store) = app_with_store(); + app.stylus.tool_before_eraser = Some(Tool::Zoom); + app.ui.tool = Tool::Eraser; + if spring { + crate::spring_tools::pressed(&mut app, 'E', Tool::Zoom, true, 0.0); + } + if menu { + crate::menus::invoke(&mut app, &egui::Context::default(), "tools.select.eraser", json!({})).unwrap(); + } else { + crate::tool_memory::select(&mut app, Tool::Eraser); + } + assert_eq!(app.stylus.tool_before_eraser, None); + assert!(app.ui.spring.is_none()); + crate::tool_memory::save_on_exit(&mut app).unwrap(); + let (restored, _) = app_with_saved(store.lock().unwrap().clone()); + assert_eq!(restored.ui.tool, Tool::Eraser); + } + } +} + +#[test] +fn invalid_selected_tool_preserves_other_preferences() { + for bad in [json!(null), json!("FutureTool"), json!(42), json!({}), json!([])] { + let (app, _) = app_with_saved(Some( + json!({ + "selectedTool": bad, "toolOptions": {"feather": 12.0} + }) + .to_string(), + )); + assert_eq!(app.ui.tool, crate::state::Tool::Brush, "{bad}"); + assert_eq!(app.ui.tool_options.feather, 12.0); + } +} + +#[test] +fn selected_tool_excludes_temporary_switches() { + use crate::state::Tool; + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + app.ui.tool = Tool::Move; + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + app.tool_override = Some(Tool::Hand); + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + assert_eq!(stored(&store)["selectedTool"], json!("Move")); + app.tool_override = None; + app.ui.tool = Tool::Zoom; + crate::spring_tools::pressed(&mut app, 'Z', Tool::Move, true, 0.0); + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + assert_eq!(stored(&store)["selectedTool"], json!("Move")); + // A quick tap commits the choice after spring_tools clears the pending switch. + crate::spring_tools::tick(&mut app, &ctx); + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + assert_eq!(stored(&store)["selectedTool"], json!("Zoom")); + app.stylus.tool_before_eraser = Some(Tool::Zoom); + app.ui.tool = Tool::Eraser; + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + assert_eq!(stored(&store)["selectedTool"], json!("Zoom")); + // An explicit selection during a temporary switch takes precedence. + app.ui.tool = Tool::PolygonLasso; + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + assert_eq!(stored(&store)["selectedTool"], json!("PolygonLasso")); +} + +#[test] +fn tool_options_survive_a_restart() { + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + app.ui.tool_options.move_auto_select = false; + app.ui.tool_options.feather = 12.0; + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + // Only what differs from the defaults is stored. + assert_eq!(stored(&store)["toolOptions"], json!({"move_auto_select": false, "feather": 12.0})); + let saved = store.lock().unwrap().clone().unwrap(); + let (mut app2, _) = app_with_saved(Some(saved)); + tick(&mut app2, &ctx); + assert!(!app2.ui.tool_options.move_auto_select); + assert_eq!(app2.ui.tool_options.feather, 12.0); + assert_eq!(app2.ui.tool_options.tolerance, crate::state::ToolOptions::default().tolerance); + // A hand-edited file: unreadable fields keep their defaults, the good ones still load. + for bad in [json!("junk"), json!({"move_auto_select": "no", "feather": 1e300, "tolerance": 5.0, "unknown": 1})] { + let (mut app3, _) = app_with_saved(Some(json!({"toolOptions": bad}).to_string())); + tick(&mut app3, &ctx); + let o = &app3.ui.tool_options; + assert!(o.move_auto_select && o.feather == 0.0, "{bad}"); + assert_eq!(o.tolerance, if bad.is_object() { 5.0 } else { 32.0 }); + } +} + +/// #6212: a remembered value its options-bar field could never hold is clamped to the +/// field's range (or takes the default) rather than reaching the tool. +#[test] +fn remembered_tool_options_are_clamped_to_their_fields() { + let ctx = egui::Context::default(); + let hostile = json!({"toolOptions": { + "feather": 1e30, "tolerance": -5.0, "polygon_sides": 0, "eyedropper_size": 7, + "crop_overlay_orientation": 9, "fill_opacity": 0.0, "magnetic_width": 1e9, + "pattern_stamp_angle": -720.0, "marquee_width": 1e7, "shape_stroke": {"miter_limit": -1.0, "opacity": 5.0}, + }}); + let (mut app, _) = app_with_saved(Some(hostile.to_string())); + tick(&mut app, &ctx); + let o = &app.ui.tool_options; + let d = crate::state::ToolOptions::default(); + assert_eq!((o.feather, o.tolerance, o.polygon_sides, o.eyedropper_size), (1000.0, 0.0, 3, d.eyedropper_size)); + assert_eq!((o.crop_overlay_orientation, o.fill_opacity, o.magnetic_width), (d.crop_overlay_orientation, 1.0, 256.0)); + assert_eq!((o.pattern_stamp_angle, o.marquee_width), (-180.0, 999.0)); + assert_eq!(o.shape_stroke, d.shape_stroke, "an invalid stroke style takes the default"); + // A good value is left alone, and in-range defaults never change (nothing to save). + let (mut app2, _) = app_with_saved(Some(json!({"toolOptions": {"feather": 12.5}}).to_string())); + tick(&mut app2, &ctx); + assert_eq!(app2.ui.tool_options, crate::state::ToolOptions { feather: 12.5, ..d.clone() }); + let mut def = d.clone(); + crate::tool_memory::sanitize(&mut def); + assert_eq!(def, d); +} + +/// #6212: every painting tool keeps its own brush across a restart, and the session brush +/// comes back as the brush of the tool that had it. +#[test] +fn tool_brushes_survive_a_restart() { + use crate::state::Tool; + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + let set_size = |app: &mut PhotocraftApp, size: f32| { + app.session.tools.brush.size = size; + app.session.tools.brush.opacity = size / 100.0; + app.session.tools.brush_changed(); + }; + set_size(&mut app, 77.0); + app.ui.tool = Tool::Eraser; + crate::paint_mouse::sync_tool_brush(&mut app); + set_size(&mut app, 33.0); + app.ui.tool = Tool::CloneStamp; + crate::paint_mouse::sync_tool_brush(&mut app); + set_size(&mut app, 12.0); + app.ui.tool = Tool::Eraser; + crate::paint_mouse::sync_tool_brush(&mut app); + crate::last_brush::persist(&mut app, &ctx); + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + let saved = stored(&store); + assert_eq!(saved["toolBrushes"]["owner"], json!("Eraser")); + assert_eq!(saved["toolBrushes"]["brushes"]["Brush"]["size"], json!(77.0)); + assert_eq!(saved["toolBrushes"]["brushes"]["CloneStamp"]["size"], json!(12.0)); + assert!(saved["toolBrushes"]["brushes"].get("Eraser").is_none(), "the owner's brush is the last brush"); + + let (mut app2, _) = app_with_saved(store.lock().unwrap().clone()); + tick(&mut app2, &ctx); + assert_eq!((app2.ui.tool, app2.ui.brush_tool), (Tool::Eraser, Tool::Eraser)); + assert_eq!(app2.session.tools.brush.size, 33.0, "the Eraser's brush is the session brush"); + for (tool, size) in [(Tool::Brush, 77.0), (Tool::CloneStamp, 12.0), (Tool::Eraser, 33.0)] { + app2.ui.tool = tool; + crate::paint_mouse::sync_tool_brush(&mut app2); + assert_eq!(app2.session.tools.brush.size, size, "{tool:?}"); + assert_eq!(app2.session.tools.brush.opacity, size / 100.0, "{tool:?}"); + } +} + +/// #6212: `toolBrushes.owner` names the tool whose brush `last_brush` holds. A brush that +/// can't be remembered yet (a sampled tip too big to embed) leaves `last_brush` at the old +/// owner's brush, so the old owner stays saved: the next launch gives that brush back to it, +/// not to the tool selected since. +#[test] +fn the_saved_brush_owner_follows_the_saved_last_brush() { + use crate::state::Tool; + use photocraft_engine::paint::{GrayTile, TipShape}; + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + app.session.tools.brush.size = 77.0; + app.session.tools.brush_changed(); + crate::last_brush::persist(&mut app, &ctx); + crate::tool_memory::persist(&mut app, &ctx); + // The Brush's tip becomes a big sampled one, then the Eraser takes over that brush. + app.session.tools.brush.tip = TipShape::Sampled(GrayTile::from_fn(400, 300, |x, y| ((x * y) % 7) as f32 / 7.0)); + app.session.tools.brush_changed(); + app.ui.tool = Tool::Eraser; + crate::paint_mouse::sync_tool_brush(&mut app); + crate::last_brush::persist(&mut app, &ctx); + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + let saved = stored(&store); + assert_eq!(saved["lastBrush"]["brush"]["size"], json!(77.0), "the big tip is not remembered yet"); + assert_ne!(saved["toolBrushes"]["owner"], json!("Eraser"), "{saved}"); + let (mut app2, _) = app_with_saved(store.lock().unwrap().clone()); + tick(&mut app2, &ctx); + assert_eq!(app2.ui.brush_tool, Tool::Brush, "the 77 px brush is the Brush's"); + assert_eq!(app2.session.tools.brush.size, 77.0); + + // Once the Eraser's brush is saved, the Eraser owns it in the preferences too. + app.session.tools.brush.tip = TipShape::Round; + app.session.tools.brush.size = 33.0; + app.session.tools.brush_changed(); + crate::last_brush::persist(&mut app, &ctx); + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + let saved = stored(&store); + assert_eq!(saved["toolBrushes"]["owner"], json!("Eraser"), "{saved}"); + assert_eq!(saved["lastBrush"]["brush"]["size"], json!(33.0)); +} + +/// #6212: a damaged or hand-edited `toolBrushes` never panics: what reads back loads (clamped +/// to the options bar's ranges), the rest is skipped and those tools start from the brush. +#[test] +fn remembered_tool_brushes_survive_damage() { + use crate::state::Tool; + let ctx = egui::Context::default(); + for bad in [json!("junk"), json!(42), json!({"owner": [1], "brushes": "x"}), json!({"brushes": {"Eraser": 5}})] { + let (mut app, _) = app_with_saved(Some(json!({"toolBrushes": bad}).to_string())); + tick(&mut app, &ctx); + assert_eq!(app.ui.brush_tool, Tool::Brush, "{bad}"); + assert!(app.ui.tool_brushes.is_empty(), "{bad}"); + } + let hostile = json!({"toolBrushes": {"owner": "Move", "brushes": { + "Eraser": {"size": 1e30}, "Bogus": {"size": 5.0}, "Move": {"size": 5.0}, + "Smudge": {"size": -3.0, "opacity": 50.0, "flow": -2.0, "hardness": 1e30}, + "Brush": {"size": 9.0}, + }}}); + let (mut app, _) = app_with_saved(Some(hostile.to_string())); + tick(&mut app, &ctx); + assert_eq!(app.ui.brush_tool, Tool::Brush, "the Move tool has no brush"); + let tools: Vec = app.ui.tool_brushes.iter().map(|(t, _)| *t).collect(); + assert_eq!(tools, vec![Tool::Smudge], "too large, unknown, brushless and the owner's own are skipped"); + let b = &app.ui.tool_brushes[0].1; + assert_eq!((b.size, b.opacity, b.flow, b.hardness), (1.0, 1.0, 0.0, 1.0)); + // A whole preferences file that isn't JSON: defaults, no panic. + let (mut app, _) = app_with_saved(Some("{not json".into())); + tick(&mut app, &ctx); + assert!(app.ui.tool_brushes.is_empty()); + assert_eq!(app.ui.tool_options, crate::state::ToolOptions::default()); +} + +/// #6212: Reset Tool forgets that tool's remembered options and brush; Reset All Tools +/// forgets every tool's. +#[test] +fn reset_tools_clear_the_remembered_options_and_brushes() { + use crate::state::Tool; + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + app.ui.tool_options.feather = 12.0; + app.ui.tool_options.strength = 80.0; + app.session.tools.brush.size = 77.0; + app.session.tools.brush_changed(); + for tool in [Tool::Eraser, Tool::Smudge, Tool::Brush] { + app.ui.tool = tool; + crate::paint_mouse::sync_tool_brush(&mut app); + } + app.ui.tool = Tool::Smudge; + crate::paint_mouse::sync_tool_brush(&mut app); + crate::last_brush::persist(&mut app, &ctx); + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + let saved = stored(&store); + assert_eq!(saved["toolOptions"]["strength"], json!(80.0)); + assert!(saved["toolBrushes"]["brushes"].get("Eraser").is_some() && saved["toolBrushes"]["brushes"].get("Brush").is_some()); + + crate::menus::invoke(&mut app, &ctx, crate::tool_reset::RESET, json!({})).unwrap(); + crate::last_brush::persist(&mut app, &ctx); + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + let saved = stored(&store); + assert!(saved["toolOptions"].get("strength").is_none(), "the Smudge's Strength is forgotten"); + assert_eq!(saved["toolOptions"]["feather"], json!(12.0), "the marquee's Feather is not the Smudge's"); + assert!(saved["toolBrushes"]["brushes"].get("Eraser").is_some()); + + crate::menus::invoke(&mut app, &ctx, crate::tool_reset::RESET_ALL, json!({"confirmed": true})).unwrap(); + crate::last_brush::persist(&mut app, &ctx); + crate::tool_memory::persist(&mut app, &ctx); + tick(&mut app, &ctx); + let saved = stored(&store); + assert!(saved["toolOptions"].is_null(), "{saved}"); + assert!(saved["toolBrushes"]["brushes"].as_object().is_none_or(|m| m.is_empty()), "{saved}"); + let (app2, _) = app_with_saved(store.lock().unwrap().clone()); + assert_eq!(app2.ui.tool_options, crate::state::ToolOptions::default()); + assert!(app2.ui.tool_brushes.is_empty()); +} + +#[test] +fn view_show_items_survive_a_restart() { + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + // Untouched: nothing is stored, so later default changes still reach the user. + crate::view_cmds::persist(&mut app, &ctx); + tick(&mut app, &ctx); + assert!(stored(&store).get("viewExtras").is_none_or(Value::is_null)); + // The menu commands, as a user toggles them (#3762: Pixel Grid off). + for id in ["view.show.pixelGrid", "view.show.grid", "view.snapTo.layers", "view.extras"] { + crate::menus::invoke(&mut app, &ctx, id, json!({})).unwrap(); + } + crate::view_cmds::persist(&mut app, &ctx); + tick(&mut app, &ctx); + assert_eq!(stored(&store)["viewExtras"], json!({"extras": false, "grid": true, "show": {"pixelGrid": false}, "snapTo": {"layers": false}})); + // A restart gets them back. + let saved = store.lock().unwrap().clone().unwrap(); + let (mut app2, _) = app_with_saved(Some(saved)); + tick(&mut app2, &ctx); + let v = &app2.ui.view; + assert!(!v.extras && !v.show.pixel_grid && !v.snap_to.layers && app2.ui.extras.grid); + assert!(v.show.selection_edges && v.snap_to.guides && app2.ui.extras.guides, "the rest keep their defaults"); + // A hand-edited file: unknown keys and non-booleans keep the defaults, good ones still load. + for bad in [json!("junk"), json!({"extras": 0, "show": {"pixelGrid": "no", "mesh": true, "bogus": true}, "snapTo": [1]})] { + let (mut app3, _) = app_with_saved(Some(json!({"viewExtras": bad}).to_string())); + tick(&mut app3, &ctx); + let v = &app3.ui.view; + assert!(v.extras && v.show.pixel_grid && v.snap_to.layers, "{bad}"); + assert_eq!(v.show.mesh, bad.is_object()); + } +} + +#[test] +fn view_snap_off_survives_a_restart() { + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + assert!(app.ui.extras.snap, "on by default"); + crate::menus::invoke(&mut app, &ctx, "view.snap", json!({})).unwrap(); + assert!(!app.ui.extras.snap); + crate::view_cmds::persist(&mut app, &ctx); + tick(&mut app, &ctx); + assert_eq!(stored(&store)["viewExtras"], json!({"snap": false})); + let saved = store.lock().unwrap().clone().unwrap(); + let (mut app2, _) = app_with_saved(Some(saved)); + tick(&mut app2, &ctx); + assert!(!app2.ui.extras.snap, "still off after a restart"); + crate::menus::invoke(&mut app2, &ctx, "view.snap", json!({})).unwrap(); + crate::view_cmds::persist(&mut app2, &ctx); + assert!(app2.session.prefs().view_extras.is_null()); +} + +#[test] +fn show_tooltips_preferences_turn_tooltips_off() { + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + assert_eq!(ctx.global_style().interaction.tooltip_delay, crate::theme::TOOLTIP_DELAY); + for path in ["interface.showTooltips", "tools.showTooltips"] { + app.run("prefs.set", json!({"values": {path: false}})).unwrap(); + tick(&mut app, &ctx); + assert!(ctx.global_style().interaction.tooltip_delay.is_infinite(), "{path} off hides tooltips"); + app.run("prefs.set", json!({"values": {path: true}})).unwrap(); + tick(&mut app, &ctx); + assert_eq!(ctx.global_style().interaction.tooltip_delay, crate::theme::TOOLTIP_DELAY); + } +} + +#[test] +fn enable_animations_off_stops_fades_and_scroll_glides_and_is_remembered() { + let on = egui::Style::default().animation_time; + let both = |ctx: &egui::Context| [egui::Theme::Dark, egui::Theme::Light].map(|t| ctx.style_of(t).animation_time); + // Saved off: the first frame after a restart applies it to both appearance styles. + let (mut app, _) = app_with_saved(Some(json!({"interface": {"enableAnimations": false}}).to_string())); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + assert_eq!(both(&ctx), [0.0, 0.0]); + assert_eq!(ctx.global_style().scroll_animation.duration.max, 0.0); + // A theme change rebuilds the style; the next frame turns animations off again. + app.apply_theme(&ctx, crate::theme::ThemeKind::StudioLight); + tick(&mut app, &ctx); + assert_eq!(both(&ctx), [0.0, 0.0]); + app.run("prefs.set", json!({"values": {"interface.enableAnimations": true}})).unwrap(); + tick(&mut app, &ctx); + assert_eq!(both(&ctx), [on, on]); + assert!(on > 0.0 && ctx.global_style().scroll_animation.duration.max > 0.0); + // A hand-edited value of the wrong type doesn't crash: the defaults (animations on) stay. + let (mut bad, _) = app_with_saved(Some(json!({"interface": {"enableAnimations": "nope"}}).to_string())); + let ctx2 = egui::Context::default(); + tick(&mut bad, &ctx2); + assert_eq!(both(&ctx2), [on, on]); +} + +#[test] +fn unimplemented_preferences_are_hidden_from_the_dialog() { + let values = prefs::Preferences::default().to_json(); + assert!(has_visible_fields(&values, "general")); + assert!(has_visible_fields(&values, "fileHandling")); + // Every setting of this section is still unimplemented. + assert!(!has_visible_fields(&values, "scratchDisks"), "scratchDisks"); + // Allow Agent Control and Control Port are read at launch (apps/photocraft main.rs). + assert!(has_visible_fields(&values, "integrations")); + assert!(!prefs::is_hidden("integrations.allowAgentControl")); + assert!(!prefs::is_hidden("integrations.controlPort")); + // "Fill new type layers with placeholder text" and "Use Escape to Commit" are live; other Type rows stay hidden. + assert!(has_visible_fields(&values, "type")); + assert!(!prefs::is_hidden("type.fillNewTypeLayersWithPlaceholder")); + assert!(!prefs::is_hidden("type.useEscToCommit")); + assert!(!prefs::is_hidden("type.smartQuotes")); + assert!(!prefs::is_hidden("type.showFontNamesInEnglish")); + // Rotate View with Trackpad, the pinch zoom and Enable Gestures are live; the other + // Enhanced Controls rows stay hidden. + assert!(has_visible_fields(&values, "enhancedControls")); + assert!(!prefs::is_hidden("enhancedControls.rotateViewWithTrackpad")); + assert!(!prefs::is_hidden("enhancedControls.zoomWithTrackpadPinch")); + assert!(!prefs::is_hidden("enhancedControls.touchGestures")); + assert!(prefs::is_hidden("enhancedControls.scrubbySliderAcceleration")); + // Camera Raw Defaults are all live: the dialog's Open applies them (camera_raw_ui). + assert!(has_visible_fields(&values, "rawDefaults")); + for k in ["openInCameraRaw", "demosaic", "applyAutoTone", "colorSpace", "bitDepth", "resolution", "sharpenFor", "openAsSmartObject", "writeXmpSidecars"] { + assert!(!prefs::is_hidden(&format!("rawDefaults.{k}")), "{k}"); + } + assert!(!prefs::is_hidden("general.autoShowHomeScreen")); + assert!(!prefs::is_hidden("general.animatedZoom")); + assert!(!prefs::is_hidden("general.zoomResizesWindows")); + assert!(!prefs::is_hidden("interface.uiScale")); + assert!(!prefs::is_hidden("interface.uiFontSize")); + // Hidden values still round-trip through the dialog untouched. + let (mut app, _) = app_with_store(); + app.run("prefs.set", json!({"values": {"type.smartQuotes": false}})).unwrap(); + let id = open_preferences(&mut app, "type"); + let fields = app.ui.dialogs.iter().find(|d| d.id == id).map(|d| d.fields.clone()).unwrap(); + confirm(&mut app, &fields).unwrap(); + assert!(!app.session.prefs().type_.smart_quotes); +} + +#[test] +fn preferences_persist_through_services_and_theme_follows() { + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + app.run("prefs.set", json!({"values": {"interface.theme": "studioLight", "performance.historyStates": 12}})).unwrap(); + tick(&mut app, &ctx); + assert_eq!(app.ui.theme, ThemeKind::StudioLight); + let saved = store.lock().unwrap().clone().unwrap(); + assert!(saved.contains("\"historyStates\": 12")); + // A new app instance loads them. + let (mut app2, store2) = app_with_saved(Some(saved)); + tick(&mut app2, &ctx); + assert_eq!(app2.session.prefs().performance.history_states, 12); + assert_eq!(app2.ui.theme, ThemeKind::StudioLight); + // Picking a theme from the Window menu becomes the preference. + crate::menus::invoke(&mut app2, &ctx, "window.theme.classic", json!({})).unwrap(); + tick(&mut app2, &ctx); + assert_eq!(app2.session.prefs().interface.theme, Theme::Classic); + assert!(store2.lock().unwrap().as_ref().unwrap().contains("classic")); +} + +#[test] +fn preset_export_dialog_offers_tool_presets() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let opened = crate::menus::invoke(&mut app, &ctx, "edit.presets.exportImportPresets", json!({})).unwrap(); + let fields = app.ui.dialog_mut(opened["dialog"].as_u64().unwrap()).unwrap().fields.clone(); + assert_eq!(fields["tools"], true); + let mut h = Harness::builder().with_size(vec2(420.0, 260.0)).build_ui_state(presets_io_body, fields); + h.run_steps(2); + h.get_by_label("Tool Presets").click(); + h.run_steps(2); + assert_eq!(h.state()["tools"], false); + assert_eq!(h.state()["brushes"], true); + assert_eq!(h.state()["customShapes"], true); +} + +#[test] +fn brush_preset_store_attaches_when_loaded_and_persists() { + use photocraft_engine::preset_store::{MemBackend, open}; + let mem = MemBackend::default(); + let ctx = egui::Context::default(); + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { preset_store: Some(rx), ..Default::default() }); + // Still loading: presets made now are kept and written once the store arrives. + tick(&mut app, &ctx); + app.run("brush.presets.save", json!({"name": "Early"})).unwrap(); + assert!(mem.files.lock().unwrap().is_empty()); + tx.send(open(Box::new(mem.clone()))).unwrap(); + tick(&mut app, &ctx); + assert!(app.services.preset_store.is_none() && app.session.preset_store.is_some()); + app.run("brush.presets.save", json!({"name": "Late"})).unwrap(); + let mut s2 = photocraft_engine::Session::new(); + assert!(s2.attach_preset_store(open(Box::new(mem))).is_empty()); + for n in ["Early", "Late"] { + assert!(s2.tools.presets.iter().any(|p| p.name == n), "{n}"); + } +} + +#[test] +fn preferences_dialog_round_trip() { + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + let r = crate::menus::invoke(&mut app, &ctx, "edit.preferences.cursors", json!({})).unwrap(); + let id = r["dialog"].as_u64().unwrap(); + let d = app.ui.dialogs.iter().find(|d| d.id == id).unwrap().clone(); + assert_eq!(d.fields["section"], "cursors"); + let mut values = d.fields["values"].clone(); + values["cursors"]["painting"] = json!("fullSizeTip"); + values["unitsAndRulers"]["rulers"] = json!("inches"); + app.ui.dialog_mut(id).unwrap().fields.insert("values".into(), values); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.prefs().cursors.painting, prefs::PaintingCursor::FullSizeTip); + assert_eq!(app.session.prefs().units_and_rulers.rulers, prefs::Unit::Inches); + // Invalid values are rejected and nothing changes. + let id = open_preferences(&mut app, "performance"); + let mut values = app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["values"].clone(); + values["performance"]["historyStates"] = json!(0); + app.ui.dialog_mut(id).unwrap().fields.insert("values".into(), values); + assert!(crate::dialogs::confirm(&mut app, id).is_err()); + assert_eq!(app.session.prefs().performance.history_states, 50); +} + +#[test] +fn preferences_apply_button_saves_without_closing_and_cancel_keeps_applied_values() { + use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, + }; + + let (mut app, store) = app_with_store(); + app.run("prefs.set", json!({"values": {"interface.language": "en", "type.smartQuotes": false}})).unwrap(); + let id = open_preferences(&mut app, "interface"); + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + assert!(h.get_by_label("Apply").accesskit_node().is_disabled()); + + let values = h.state_mut().ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap(); + values["interface"]["appearanceMode"] = json!("light"); + values["interface"]["lightTheme"] = json!("studioLight"); + values["interface"]["uiFontSize"] = json!("large"); + values["performance"]["historyStates"] = json!(12); + h.run_steps(2); + assert!(!h.get_by_label("Apply").accesskit_node().is_disabled()); + h.get_by_label("Apply").click(); + h.run_steps(4); + + assert_eq!(h.state().session.prefs().performance.history_states, 12); + assert_eq!(h.state().ui.theme, ThemeKind::StudioLight); + assert_eq!(h.ctx.fonts(|f| f.definitions().font_data["Inter"].tweak.scale), 16.0 / 12.0); + assert!(!h.state().session.prefs().type_.smart_quotes, "hidden settings round-trip unchanged"); + let d = h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap(); + assert_eq!(d.fields["section"], "interface"); + assert_eq!(d.fields["values"]["performance"]["historyStates"], 12); + assert!(h.get_by_label("Apply").accesskit_node().is_disabled()); + let saved: Value = serde_json::from_str(store.lock().unwrap().as_ref().unwrap()).unwrap(); + assert_eq!(saved["performance"]["historyStates"], 12); + assert_eq!(saved["interface"]["appearanceMode"], "light"); + assert_eq!(saved["interface"]["lightTheme"], "studioLight"); + assert_eq!(saved["interface"]["uiFontSize"], "large"); + + // Repeated Apply starts from the validated values, not the dialog's original snapshot. + h.state_mut().ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap()["performance"]["historyStates"] = json!(22); + h.run_steps(2); + h.get_by_label("Apply").click(); + h.run_steps(4); + assert_eq!(h.state().session.prefs().performance.history_states, 22); + h.state_mut().ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap()["performance"]["historyStates"] = json!(33); + h.state_mut().ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap()["interface"]["uiFontSize"] = json!("tiny"); + h.run_steps(2); + h.get_by_label("Cancel").click(); + h.run_steps(4); + assert!(h.state().ui.dialogs.iter().all(|d| d.id != id)); + assert_eq!(h.state().session.prefs().performance.history_states, 22); + assert_eq!(h.ctx.fonts(|f| f.definitions().font_data["Inter"].tweak.scale), 16.0 / 12.0); + let saved = store.lock().unwrap().clone().unwrap(); + let (mut restarted, _) = app_with_saved(Some(saved)); + tick(&mut restarted, &egui::Context::default()); + assert_eq!(restarted.session.prefs().performance.history_states, 22); + assert_eq!(restarted.ui.theme, ThemeKind::StudioLight); + assert_eq!(restarted.session.prefs().interface.ui_font_size, prefs::UiFontSize::Large); +} + +#[cfg(all(not(target_arch = "wasm32"), not(target_os = "macos")))] +#[test] +fn system_title_bar_explains_next_launch_and_preserves_apply_and_cancel() { + use egui_kittest::{Harness, kittest::Queryable}; + + let (mut app, store) = app_with_store(); + app.run("prefs.set", json!({"values": {"interface.language": "en"}})).unwrap(); + app.custom_titlebar = true; + let id = open_preferences(&mut app, "interface"); + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + h.get_by_label("System title bar").scroll_to_me(); + h.run_steps(4); + h.get_by_label("Applies at next launch."); + for desired in [true, false] { + h.get_by_label("System title bar").click(); + h.run_steps(4); + assert_eq!(h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["values"]["interface"]["systemTitleBar"], desired); + assert_eq!(h.state().session.prefs().interface.system_title_bar, !desired, "the draft is not applied yet"); + h.get_by_label("Applies at next launch."); + h.get_by_label("Apply").click(); + h.run_steps(4); + assert_eq!(h.state().session.prefs().interface.system_title_bar, desired); + assert_eq!(stored(&store)["interface"]["systemTitleBar"], desired); + assert!(h.state().custom_titlebar, "do not change the current window or restart it"); + let (reloaded, _) = app_with_saved(store.lock().unwrap().clone()); + assert_eq!(reloaded.session.prefs().interface.system_title_bar, desired); + h.get_by_label("Applies at next launch."); + } + h.get_by_label("System title bar").click(); + h.run_steps(4); + h.get_by_label("Cancel").click(); + h.run_steps(4); + assert!(h.state().ui.dialogs.iter().all(|d| d.id != id)); + assert!(!h.state().session.prefs().interface.system_title_bar); + assert_eq!(stored(&store)["interface"]["systemTitleBar"], false); + assert!(h.state().custom_titlebar); +} + +/// #7939: switching Rendering Mode waits for the next launch, and says so next to the setting. +#[test] +fn rendering_mode_explains_next_launch() { + use egui_kittest::{Harness, kittest::Queryable}; + let obj = json!({"renderingMode": "auto", "historyStates": 50}).as_object().unwrap().clone(); + let mut h = Harness::new_ui_state( + |ui, obj: &mut Map| section_fields(ui, "performance", obj, &[], crate::i18n::Lang::from_pref("en"), None, ""), + obj, + ); + h.run_steps(4); + assert!(h.query_all_by_label("Rendering Mode").next().is_some(), "the Rendering Mode setting"); + assert!(h.query_all_by_label("Applies at next launch.").next().is_some(), "its next-launch notice"); + // A search that leaves Rendering Mode out leaves its notice out too. + let obj = json!({"renderingMode": "auto", "historyStates": 50}).as_object().unwrap().clone(); + let mut h = Harness::new_ui_state( + |ui, obj: &mut Map| section_fields(ui, "performance", obj, &[], crate::i18n::Lang::from_pref("en"), None, "history"), + obj, + ); + h.run_steps(4); + assert!(h.query_by_label("Applies at next launch.").is_none()); +} + +/// #4097: Allow Agent Control and Control Port are read when the app starts, and say so. +#[test] +fn integrations_explain_next_launch() { + use egui_kittest::{Harness, kittest::Queryable}; + let obj = json!({"allowAgentControl": true, "controlPort": 0}).as_object().unwrap().clone(); + let mut h = Harness::new_ui_state( + |ui, obj: &mut Map| section_fields(ui, "integrations", obj, &[], crate::i18n::Lang::from_pref("en"), None, ""), + obj, + ); + h.run_steps(4); + h.get_by_label("Allow agent control"); + assert_eq!(h.query_all_by_label("Applies at next launch.").count(), 2, "one notice under each row"); +} + +#[test] +fn next_launch_notice_does_not_mark_unrelated_interface_preferences() { + use egui_kittest::{Harness, kittest::Queryable}; + let obj = json!({"showTooltips": true}).as_object().unwrap().clone(); + let mut h = + Harness::new_ui_state(|ui, obj: &mut Map| section_fields(ui, "interface", obj, &[], crate::i18n::Lang::from_pref("en"), None, ""), obj); + h.run_steps(4); + assert!(h.query_by_label("Applies at next launch.").is_none()); + h.get_by_label("Show tooltips").click(); + h.run_steps(4); + assert_eq!(h.state()["showTooltips"], false); + assert!(h.query_by_label("Applies at next launch.").is_none()); +} + +#[test] +fn preferences_confirm_after_apply_commits_later_edits() { + let (mut app, _) = app_with_store(); + let id = open_preferences(&mut app, "cursors"); + app.ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap()["cursors"]["painting"] = json!("fullSizeTip"); + apply(&mut app, id).unwrap(); + app.ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap()["unitsAndRulers"]["rulers"] = json!("inches"); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert!(app.ui.dialogs.iter().all(|d| d.id != id)); + assert_eq!(app.session.prefs().cursors.painting, prefs::PaintingCursor::FullSizeTip); + assert_eq!(app.session.prefs().units_and_rulers.rulers, prefs::Unit::Inches); +} + +#[test] +fn preferences_apply_rejects_invalid_drafts_and_keeps_them_open() { + let (mut app, _) = app_with_store(); + let before = app.session.prefs().to_json(); + for invalid in [json!(0), json!("invalid"), Value::Null] { + let id = open_preferences(&mut app, "performance"); + app.ui.dialog_mut(id).unwrap().fields.get_mut("values").unwrap()["performance"]["historyStates"] = invalid; + let draft = app.ui.dialog_mut(id).unwrap().fields.clone(); + assert!(apply(&mut app, id).is_err()); + assert_eq!(app.session.prefs().to_json(), before); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields, draft); + app.ui.close_dialog(id); + } + let id = open_preferences(&mut app, "interface"); + app.ui.dialog_mut(id).unwrap().fields.remove("values"); + assert!(apply(&mut app, id).is_err()); + assert!(app.ui.dialog_mut(id).is_some()); + assert_eq!(app.session.prefs().to_json(), before); +} + +#[test] +fn apply_rejects_missing_and_non_preferences_dialogs() { + let (mut app, _) = app_with_store(); + let before = app.session.prefs().to_json(); + assert!(apply(&mut app, u64::MAX).is_err()); + let id = open_shortcuts(&mut app, 0); + assert!(apply(&mut app, id).is_err()); + assert!(app.ui.dialog_mut(id).is_some()); + let fields = json!({"__prefsui": "prefs", "values": preference_values(app.session.prefs())}).as_object().unwrap().clone(); + let id = app.ui.open_dialog(DialogKind::About, fields); + assert!(apply(&mut app, id).is_err()); + assert!(app.ui.dialog_mut(id).is_some()); + assert_eq!(app.session.prefs().to_json(), before); +} + +#[test] +fn shortcut_dialog_moves_shortcuts_and_shell_dispatch_follows() { + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + let id = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); + // ⌘O (File › Open, a shell command) given to Layer › New › Layer. + app.ui.dialog_mut(id).unwrap().fields.insert("overrides".into(), json!({"layer.new.layer": "Cmd+O"})); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(effective_shortcut(&app, "layer.new.layer", None).as_deref(), Some("Cmd+O")); + assert_eq!(effective_shortcut(&app, "file.open", Some("Cmd+O")), None, "taken from File › Open"); + // Menu items show the effective shortcut. + let items = crate::menus::menu_items(&app); + assert!(items.iter().any(|i| i.id == "layer.new.layer" && i.shortcut.as_deref() == Some("Cmd+O"))); + assert!(items.iter().any(|i| i.id == "file.open" && i.shortcut.is_none())); + assert_eq!(shortcut_text(egui::Key::K, egui::Modifiers { command: true, shift: true, ..Default::default() }).as_deref(), Some("Cmd+Shift+K")); + + // Re-assigning a shortcut already held by a custom override takes it from the override. + let id2 = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); + let mut cur_overrides = app.session.prefs().shortcuts.clone(); + cur_overrides.insert("layer.new.group".into(), "Cmd+O".into()); + app.ui.dialog_mut(id2).unwrap().fields.insert("overrides".into(), json!(cur_overrides)); + crate::dialogs::confirm(&mut app, id2).unwrap(); + assert_eq!(effective_shortcut(&app, "layer.new.group", None).as_deref(), Some("Cmd+O")); + assert_eq!(effective_shortcut(&app, "layer.new.layer", None), None, "taken from layer.new.layer override"); + + // OK with nothing changed keeps every shortcut where it is. + let id3 = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); + let unchanged = app.session.prefs().shortcuts.clone(); + app.ui.dialog_mut(id3).unwrap().fields.insert("overrides".into(), json!(unchanged)); + crate::dialogs::confirm(&mut app, id3).unwrap(); + assert_eq!(app.session.prefs().shortcuts, unchanged); + + // Giving the shortcut back to Layer › New › Layer takes it from the group override; a + // cleared override (empty) holds nothing and is left alone. + let id4 = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); + let mut ov = app.session.prefs().shortcuts.clone(); + ov.insert("layer.new.layer".into(), "Cmd+O".into()); + app.ui.dialog_mut(id4).unwrap().fields.insert("overrides".into(), json!(ov)); + crate::dialogs::confirm(&mut app, id4).unwrap(); + assert_eq!(effective_shortcut(&app, "layer.new.layer", None).as_deref(), Some("Cmd+O")); + assert_eq!(effective_shortcut(&app, "layer.new.group", None), None, "taken back from the group"); + assert_eq!(effective_shortcut(&app, "file.open", Some("Cmd+O")), None, "File › Open stays cleared"); +} + +/// #3665: the dialog keeps a command's further keys: they move like main keys, an override +/// of the main key leaves them, and menus show only the main key. +#[test] +fn shortcut_dialog_moves_and_keeps_alternate_keys() { + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + let open = |app: &mut PhotocraftApp| crate::menus::invoke(app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); + assert_eq!(crate::shortcuts::effective_alternates(&app, "edit.copy"), ["F3"]); + assert_eq!(crate::shortcuts::effective_alternates(&app, "view.zoomIn"), ["Cmd++"]); + // F2 (Cut's alternate) given to Rename Layer is taken from Cut, which keeps ⌘X. + let id = open(&mut app); + app.ui.dialog_mut(id).unwrap().fields.insert("overrides".into(), json!({"layer.renameLayer": "F2"})); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(effective_shortcut(&app, "layer.renameLayer", None).as_deref(), Some("F2")); + assert!(crate::shortcuts::effective_alternates(&app, "edit.cut").is_empty()); + assert_eq!(effective_shortcut(&app, "edit.cut", Some("Cmd+X")).as_deref(), Some("Cmd+X")); + // Copy's main key moved to ⌘K keeps F3; the menu shows ⌘K. + let id = open(&mut app); + let mut ov = app.session.prefs().shortcuts.clone(); + ov.insert("edit.copy".into(), "Cmd+K".into()); + app.ui.dialog_mut(id).unwrap().fields.insert("overrides".into(), json!(ov)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(crate::shortcuts::effective_alternates(&app, "edit.copy"), ["F3"]); + assert!(crate::menus::menu_items(&app).iter().any(|i| i.id == "edit.copy" && i.shortcut.as_deref() == Some("Cmd+K"))); + // An added alternate takes its key from the main key that held it. + let id = open(&mut app); + app.ui.dialog_mut(id).unwrap().fields.insert("alternates".into(), json!({"edit.paste": ["F4", "Cmd+K"]})); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(crate::shortcuts::effective_alternates(&app, "edit.paste"), ["F4", "Cmd+K"]); + assert_eq!(effective_shortcut(&app, "edit.copy", Some("Cmd+C")), None, "taken from Copy"); + // Use Default for everything restores the defaults; a malformed list is an error. + let id = open(&mut app); + app.ui.dialog_mut(id).unwrap().fields.insert("alternates".into(), json!({"edit.paste": "F4"})); + assert!(crate::dialogs::confirm(&mut app, id).is_err()); + let id = open(&mut app); + app.ui.dialog_mut(id).unwrap().fields.insert("alternates".into(), json!({"edit.paste": ["Cmd+Shift"]})); + assert!(crate::dialogs::confirm(&mut app, id).is_err()); + assert_eq!(crate::shortcuts::effective_alternates(&app, "edit.paste"), ["F4", "Cmd+K"], "nothing changed"); + let id = open(&mut app); + app.ui.dialog_mut(id).unwrap().fields.insert("alternates".into(), json!({})); + app.ui.dialog_mut(id).unwrap().fields.insert("overrides".into(), json!({})); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert!(app.session.prefs().alternate_shortcuts.is_empty() && app.session.prefs().shortcuts.is_empty()); + assert_eq!(crate::shortcuts::effective_alternates(&app, "edit.cut"), ["F2"]); +} + +#[test] +fn shortcut_dialog_rejects_malformed_overrides() { + // #956: a non-map `overrides` was read as "no overrides" and wiped every custom shortcut. + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + app.run("edit.keyboardShortcuts", json!({"set": {"file.new": "Ctrl+Shift+N"}})).unwrap(); + let before = app.session.prefs().shortcuts.clone(); + assert!(!before.is_empty()); + for bad in [json!("bogus"), json!(["file.new"]), json!({"file.new": 5})] { + let id = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); + app.ui.dialog_mut(id).unwrap().fields.insert("overrides".into(), bad.clone()); + assert!(crate::dialogs::confirm(&mut app, id).is_err(), "{bad} accepted"); + assert_eq!(app.session.prefs().shortcuts, before, "{bad} changed the shortcuts"); + } + + // Drawing the open dialog keeps the malformed value for OK to reject, instead of + // replacing it with the empty map it shows. + let id = crate::menus::invoke(&mut app, &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); + app.ui.dialog_mut(id).unwrap().fields.insert("overrides".into(), json!("bogus")); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + assert_eq!(h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["overrides"], json!("bogus")); + assert!(crate::dialogs::confirm(h.state_mut(), id).is_err()); + assert_eq!(h.state().session.prefs().shortcuts, before); +} + +#[test] +fn hidden_menu_items_disappear() { + let (mut app, _) = app_with_store(); + app.run("edit.menus", json!({"hide": ["edit.fade"]})).unwrap(); + assert!(!crate::menus::menu_items(&app).iter().any(|i| i.id == "edit.fade")); +} + +/// #5096: preferences that list Edit › Menus or File › Exit as hidden still show them. +#[test] +fn essential_menu_items_stay_visible() { + let (mut app, _) = app_with_store(); + app.run("prefs.set", json!({"values": {"menus": {"hidden": ["edit.menus", "file.exit", "edit.fade"], "colors": {}}}})).unwrap(); + let items = crate::menus::menu_items(&app); + assert!(items.iter().any(|i| i.id == "edit.menus") && items.iter().any(|i| i.id == "file.exit")); + assert!(!items.iter().any(|i| i.id == "edit.fade")); +} + +#[test] +fn autosave_runs_for_dirty_documents() { + type Saved = Arc>>; + let saved: Saved = Arc::default(); + let s2 = saved.clone(); + let services = crate::Services { + autosave: Some(Box::new(move |doc: &Arc, rev: u64, _path: Option<&str>| { + s2.lock().unwrap().push((doc.id.0, rev)); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + tick(&mut app, &ctx); + autosave_now(&mut app); + tick(&mut app, &ctx); + assert!(saved.lock().unwrap().is_empty(), "clean documents are not autosaved"); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + autosave_now(&mut app); + tick(&mut app, &ctx); + assert_eq!(saved.lock().unwrap().len(), 1); + autosave_now(&mut app); + tick(&mut app, &ctx); + assert_eq!(saved.lock().unwrap().len(), 1, "unchanged since the last autosave"); + + // Loaded copies can have the same persisted identity and dirty revision. + let original = app.session.active().unwrap().doc.clone(); + let original_id = original.id; + app.session.add_document(original.as_ref().clone(), None); + app.run("edit.fill", json!({"color": "#0000ff"})).unwrap(); + autosave_now(&mut app); + tick(&mut app, &ctx); + { + let saved = saved.lock().unwrap(); + assert_eq!(saved.len(), 2, "both dirty copies need independent autosaves"); + assert_eq!(saved[0].0, original_id.0); + assert_ne!(saved[0].0, saved[1].0, "recovery ownership must be distinct"); + assert_eq!(saved[0].1, saved[1].1, "the revisions must match to reproduce suppression"); + } + app.run("prefs.set", json!({"path": "fileHandling.autosave", "value": false})).unwrap(); + app.run("edit.fill", json!({"color": "#00ff00"})).unwrap(); + autosave_now(&mut app); + tick(&mut app, &ctx); + assert_eq!(saved.lock().unwrap().len(), 2, "autosave off"); +} + +#[test] +fn recovered_documents_adopt_their_entries_until_saved_or_closed() { + type Log = Arc>>; + let log: Log = Arc::default(); + let (l1, l2, l3) = (log.clone(), log.clone(), log.clone()); + use photocraft_doc::{Color, ColorMode, Document, SampleType, Size}; + let doc = || Document::with_background("R", Size::new(4, 4), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let services = crate::Services { + autosave: Some(Box::new(move |d: &Arc, _: u64, _: Option<&str>| { + l1.lock().unwrap().push(format!("save {}", d.id.0)); + Ok(()) + })), + discard_autosave: Some(Box::new(move |id: u64| l2.lock().unwrap().push(format!("discard {id}")))), + recover: Some(Box::new(move || { + ["a", "b"].map(|key| crate::Recoverable { key: key.into(), name: "R".into(), path: None, load: Box::new(move || Ok(doc())) }).into() + })), + adopt_autosave: Some(Box::new(move |id: u64, key: &str| l3.lock().unwrap().push(format!("adopt {id} {key}")))), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while app.session.has_jobs() && std::time::Instant::now() < deadline { + crate::jobs_ui::tick(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(!app.session.has_jobs(), "recovery finished"); + let ids: Vec = app.session.documents().iter().map(|d| d.doc.id.0).collect(); + assert!(app.session.documents().iter().all(|d| d.is_dirty()), "recovered documents are unsaved"); + let take = || std::mem::take(&mut *log.lock().unwrap()); + assert_eq!(take(), [format!("adopt {} a", ids[0]), format!("adopt {} b", ids[1])]); + // Their entries are current: nothing to autosave until they change. + tick(&mut app, &ctx); + autosave_now(&mut app); + tick(&mut app, &ctx); + assert!(take().is_empty()); + // Closing one drops its entry; editing the other autosaves over its own. + app.run("file.close", json!({"document": 0})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + autosave_now(&mut app); + tick(&mut app, &ctx); + assert_eq!(take(), [format!("discard {}", ids[0]), format!("save {}", ids[1])]); +} + +#[test] +fn edit_dialogs_open() { + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.sync_views(); + let d = crate::menus::invoke(&mut app, &ctx, "edit.colorSettings", json!({})).unwrap()["dialog"].as_u64().unwrap(); + assert_eq!(app.ui.dialogs.iter().find(|x| x.id == d).unwrap().fields["workingRgb"], "srgb"); + let note = app.ui.dialogs.iter().find(|x| x.id == d).unwrap().fields["__note"].as_str().unwrap().to_string(); + assert!(note.starts_with("Monitor profile in use: sRGB") && note.contains("fallback"), "{note}"); + assert!(crate::menus::invoke(&mut app, &ctx, "edit.fade", json!({})).is_err()); + app.run("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); + // Content-Aware Fill opens its workspace (caf_ui); OK fills. + let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({})).unwrap(); + assert!(r["contentAwareFill"]["window"].is_array(), "{r}"); + crate::caf_ui::commit(&mut app); + assert!(app.distort.caf.is_none()); + let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareScale", json!({})).unwrap(); + assert_eq!(r["transform"]["rect"], json!([4.0, 4.0, 12.0, 12.0])); + crate::transform_tool::cancel(&mut app); + let d = crate::menus::invoke(&mut app, &ctx, "edit.presets.presetManager", json!({})).unwrap()["dialog"].as_u64().unwrap(); + assert!(crate::dialogs::confirm(&mut app, d).is_ok()); +} From 3a94656b16f22a1eb71102806d5241f3e25c2593 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:28 +0000 Subject: [PATCH 096/259] refactor(ui-egui): move new_doc_ui.rs tests to new_doc_ui/tests.rs --- crates/ui-egui/src/new_doc_ui.rs | 913 +------------------------ crates/ui-egui/src/new_doc_ui/tests.rs | 910 ++++++++++++++++++++++++ 2 files changed, 911 insertions(+), 912 deletions(-) create mode 100644 crates/ui-egui/src/new_doc_ui/tests.rs diff --git a/crates/ui-egui/src/new_doc_ui.rs b/crates/ui-egui/src/new_doc_ui.rs index 7174fd0d43..f662842e1e 100644 --- a/crates/ui-egui/src/new_doc_ui.rs +++ b/crates/ui-egui/src/new_doc_ui.rs @@ -843,915 +843,4 @@ pub fn body(app: &mut crate::PhotocraftApp, ui: &mut egui::Ui, f: &mut Map>() - }; - let rgb = values("rgb"); - assert_eq!(rgb[0], "working"); - assert!(rgb.contains(&Builtin::AdobeRgbCompat.id().to_string()) && rgb.contains(&"panel.icc".to_string())); - assert!(!rgb.contains(&Builtin::CoatedCmyk.id().to_string()) && !rgb.contains(&"press.icc".to_string())); - let cmyk = values("cmyk"); - assert!(cmyk.contains(&"press.icc".to_string()) && !cmyk.contains(&Builtin::Srgb.id().to_string())); - assert!(profile_options(None, "sRGB", &installed).len() == 1, "an unknown mode offers only the working space"); - // Every entry is one `file.new` takes for that mode. - for mode in ["rgb", "gray", "cmyk", "lab"] { - for v in values(mode).into_iter().filter(|v| !v.ends_with(".icc")) { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 2, "height": 2, "mode": mode, "profile": v})).unwrap_or_else(|e| panic!("{mode} {v}: {e}")); - } - } - } - - /// A saved preset replaces the Color Profile picked before: its own, or the working space. - #[test] - fn applying_a_preset_replaces_the_picked_profile() { - let mut s = photocraft_engine::Session::new(); - let base = json!({"width": 8, "height": 8, "mode": "cmyk", "unit": "px"}); - s.execute("document.presets.save", json!({"name": "Plain", "settings": base})).unwrap(); - let mut press = base.clone(); - press["profile"] = json!("coated-cmyk"); - s.execute("document.presets.save", json!({"name": "Press", "settings": press})).unwrap(); - let mut f = Map::new(); - f.insert("profile".into(), json!(photocraft_cms::Builtin::AdobeRgbCompat.id())); - apply_saved_preset(&mut f, &s.presets.documents[0]); - assert!(!f.contains_key("profile"), "{f:?}"); - assert!(s.execute("file.new", command_params(&f)).is_ok()); - apply_saved_preset(&mut f, &s.presets.documents[1]); - assert_eq!(f["profile"], "coated-cmyk"); - } - - /// #9086: the Artboards checkbox's field reaches `file.new`, which starts the document as one - /// artboard; the dialog's own `__` keys don't. - #[test] - fn the_artboards_box_creates_an_artboard_document() { - let mut s = photocraft_engine::Session::new(); - let mut f = Map::new(); - for (k, v) in [("width", json!(64)), ("height", json!(48)), ("artboard", json!(true)), ("__orientation", json!("landscape"))] { - f.insert(k.into(), v); - } - s.execute("file.new", command_params(&f)).unwrap(); - let doc = &s.active().unwrap().doc; - assert_eq!(doc.artboards().len(), 1); - assert_eq!(doc.artboards()[0].2.rect, doc.bounds()); - } - - #[test] - fn units_round_trip_through_pixels() { - assert_eq!(to_unit(2100.0, "in", 300.0), 7.0); - assert_eq!(from_unit(7.0, "in", 300.0), 2100.0); - assert_eq!(from_unit(2.54, "cm", 300.0), 300.0); - assert_eq!(to_unit(640.0, "px", 72.0), 640.0); - } - - /// #1147: 5 mm at 72 ppi is 14 px, which is 4.94 mm. The field must keep showing the typed 5. - #[test] - fn typed_size_in_a_physical_unit_shows_as_typed() { - let mut f = crate::state::UiState::new_document_fields(); - set_size(&mut f, "height", 5.0, "mm", 72.0); - assert_eq!(command_params(&f)["height"], json!(14)); - assert_eq!(shown_size(&f, "height", 1080.0, "mm", 72.0), 5.0); - // Another unit, or pixels changed elsewhere (a preset, the orientation swap): converted. - assert_eq!(shown_size(&f, "height", 1080.0, "cm", 72.0), to_unit(14.0, "cm", 72.0)); - f.insert("height".into(), json!(1080)); - assert_eq!(shown_size(&f, "height", 1080.0, "mm", 72.0), to_unit(1080.0, "mm", 72.0)); - // Pixels show whole pixels. - set_size(&mut f, "width", 512.4, "px", 72.0); - assert_eq!(shown_size(&f, "width", 1920.0, "px", 72.0), 512.0); - // Over the 300000 px limit the field shows the limit. - set_size(&mut f, "width", 300_000.0, "mm", 72.0); - assert_eq!(command_params(&f)["width"], json!(300_000)); - assert_eq!(shown_size(&f, "width", 1920.0, "mm", 72.0), to_unit(300_000.0, "mm", 72.0)); - } - - /// #5661: 1 px at 300 ppi is 0.0033 in. Showing it in inches clamped the field to 0.01 in and - /// turned the width into 3 px without an edit. - #[test] - fn tiny_size_in_inches_is_not_changed_by_showing_it() { - use egui_kittest::Harness; - let app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut f = crate::state::UiState::new_document_fields(); - for (k, v) in [("width", json!(1)), ("height", json!(1)), ("resolution", json!(300.0)), ("__unit", json!("in"))] { - f.insert(k.into(), v); - } - let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state( - |ui, (app, f): &mut (crate::PhotocraftApp, Map)| { - if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - body(app, ui, f); - } - }, - (app, f), - ); - crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.run_steps(3); - let p = command_params(&h.state().1); - assert_eq!((p["width"].as_u64(), p["height"].as_u64()), (Some(1), Some(1))); - } - - /// #1147: the Orientation buttons swap the typed values too: 841 x 1189 mm becomes 1189 x 841. - #[test] - fn orientation_swap_keeps_the_typed_values() { - let mut f = crate::state::UiState::new_document_fields(); - set_size(&mut f, "width", 841.0, "mm", 72.0); - set_size(&mut f, "height", 1189.0, "mm", 72.0); - swap_size(&mut f); - let p = command_params(&f); - assert_eq!((p["width"].clone(), p["height"].clone()), (json!(3370), json!(2384))); - assert_eq!((shown_size(&f, "width", 1920.0, "mm", 72.0), shown_size(&f, "height", 1080.0, "mm", 72.0)), (1189.0, 841.0)); - } - - #[test] - fn resolution_keeps_physical_size_in_physical_units_and_pixels_in_px() { - let a4 = CATEGORIES.iter().find(|c| c.0 == "Print").unwrap().1.iter().find(|p| p.0 == "A4").unwrap(); - let mut f = crate::state::UiState::new_document_fields(); - apply_preset(&mut f, a4, &Default::default()); - f.insert("__unit".into(), json!("in")); - set_resolution(&mut f, 150.0); - let p = command_params(&f); - assert_eq!((p["width"].clone(), p["height"].clone(), p["resolution"].clone()), (json!(1240), json!(1754), json!(150.0))); - assert!(!f.contains_key("__preset")); - - let mut f = crate::state::UiState::new_document_fields(); - apply_preset(&mut f, a4, &Default::default()); - f.insert("__unit".into(), json!("px")); - set_resolution(&mut f, 150.0); - let p = command_params(&f); - assert_eq!((p["width"].clone(), p["height"].clone(), p["resolution"].clone()), (json!(2480), json!(3508), json!(150.0))); - } - - /// Units & Rulers › New Document Preset Resolutions: print presets keep their inches at the - /// Print Resolution, screen presets keep their pixels at the Screen Resolution. - #[test] - fn iso_b_paper_presets_use_correct_dimensions_and_selected_units() { - let presets = CATEGORIES.iter().find(|c| c.0 == "Print").unwrap().1; - let mut f = crate::state::UiState::new_document_fields(); - f.insert("__unit".into(), json!("mm")); - for (name, w, h) in [("B3", 4169, 5906), ("B4", 2953, 4169)] { - let preset = presets.iter().find(|p| p.0 == name).unwrap(); - assert_eq!((preset.1, preset.2, preset.3), (w, h, 300.0)); - assert_eq!(preset_unit(preset, &f), "mm"); - apply_preset(&mut f, preset, &Default::default()); - let params = command_params(&f); - assert_eq!((params["width"].as_u64(), params["height"].as_u64()), (Some(u64::from(w)), Some(u64::from(h)))); - assert_eq!(params["resolution"], 300.0); - } - } - - #[test] - fn presets_follow_the_preset_resolution_preferences() { - let find = |cat: &str, name: &str| *CATEGORIES.iter().find(|c| c.0 == cat).unwrap().1.iter().find(|p| p.0 == name).unwrap(); - let (letter, web) = (find("Print", "Letter"), find("Web", "Web Minimum")); - let stock = UnitsAndRulers::default(); - assert_eq!(at_pref_resolutions(&letter, &stock), letter, "the defaults are the listed sizes"); - assert_eq!(at_pref_resolutions(&web, &stock), web); - - let units = UnitsAndRulers { print_resolution: 200.0, screen_resolution: 96.0, ..stock.clone() }; - assert_eq!(at_pref_resolutions(&letter, &units), ("Letter", 1700, 2200, 200.0), "8.5 x 11 in at 200 ppi"); - assert_eq!(at_pref_resolutions(&find("Print", "A4"), &units), ("A4", 1653, 2339, 200.0)); - assert_eq!(at_pref_resolutions(&web, &units), ("Web Minimum", 1024, 768, 96.0), "pixels kept"); - let clipboard = (CLIPBOARD, 123, 45, 72.0); - assert_eq!(at_pref_resolutions(&clipboard, &units), clipboard, "the copied pixels keep their resolution"); - - let mut f = crate::state::UiState::new_document_fields(); - apply_preset(&mut f, &letter, &units); - assert_eq!((f["width"].as_u64(), f["height"].as_u64(), f["resolution"].as_f64()), (Some(1700), Some(2200), Some(200.0))); - assert_eq!((f["__preset"].as_str(), f["__unit"].as_str()), (Some("Letter"), Some("in")), "still a print preset below 300 ppi"); - apply_preset(&mut f, &web, &units); - assert_eq!((f["width"].as_u64(), f["resolution"].as_f64(), f["__unit"].as_str()), (Some(1024), Some(96.0), Some("px"))); - - // Out-of-range values (a hand-edited preferences file) never make an unusable size. - for bad in [0.0, -5.0, f64::NAN, f64::INFINITY] { - let units = UnitsAndRulers { print_resolution: bad, screen_resolution: bad, ..stock.clone() }; - assert_eq!(at_pref_resolutions(&letter, &units), letter, "{bad}"); - assert_eq!(at_pref_resolutions(&web, &units), web, "{bad}"); - } - let huge = UnitsAndRulers { print_resolution: 1e9, ..stock }; - let (_, w, h, _) = at_pref_resolutions(&find("Art & Illustration", "Poster"), &huge); - assert_eq!((w, h), (300_000, 300_000), "clamped to the file.new limit"); - } - - #[test] - fn preset_card_titles_fit_the_card_in_every_language() { - let ctx = egui::Context::default(); - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { - for lang in crate::i18n::Lang::all() { - for p in CATEGORIES.iter().flat_map(|c| c.1.iter()) { - let title = crate::i18n::tr(lang, p.0); - let g = card_title(ui.painter(), title, 152.0, egui::Color32::WHITE); - assert!(g.size().x <= 152.0 && g.rows.len() <= 2 && !g.elided, "{}: {title}", lang.code()); - } - } - }); - out.textures_delta.clear(); - } - - #[test] - fn recent_category_lists_clipboard_then_created_documents_then_uncovered_defaults() { - let settings = |w, h, ppi| DocumentSettings { - width: w, - height: h, - resolution: ppi, - mode: "rgb".into(), - depth: 8, - background: "white".into(), - background_color: None, - profile: None, - unit: "px".into(), - resolution_unit: "in".into(), - }; - let mut f = Map::new(); - set_clipboard(&mut f, 20, 30); - let cards = recent_cards(&f, &[settings(800, 600, 72.0), settings(1920, 1080, 72.0)], &UnitsAndRulers::default()); - let titles: Vec<(&str, String)> = cards.iter().map(|c| (c.title(), c.size_line(&UnitsAndRulers::default(), &f))).collect(); - assert_eq!( - titles, - [ - (CLIPBOARD, "20 x 30 px @ 72 ppi".to_string()), - ("Custom", "800 x 600 px @ 72 ppi".to_string()), - ("HDTV 1080p", "1920 x 1080 px @ 72 ppi".to_string()), - ("Default PhotoCraft Size", "7 x 5 in @ 300 ppi".to_string()), - ] - ); - assert!(holds(&f, &settings(20, 30, 72.0)) && !holds(&f, &settings(800, 600, 72.0))); - } - - #[test] - fn clipboard_preset_comes_first_and_is_selected() { - // Nothing on the clipboard: the dialog opens as before. - let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let f = app.new_document_fields(); - assert_eq!(f, crate::state::UiState::new_document_fields()); - assert!(clipboard_preset(&f).is_none()); - // Pixels copied in the app: the Clipboard preset takes their size, at 72 ppi, selected. - app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); - app.run("select.rect", json!({"x": 10, "y": 20, "width": 123, "height": 45})).unwrap(); - app.run("edit.copy", json!({})).unwrap(); - let f = app.new_document_fields(); - assert_eq!(clipboard_preset(&f), Some((CLIPBOARD, 123, 45, 72.0))); - assert_eq!((f["width"].as_u64(), f["height"].as_u64(), f["__preset"].as_str()), (Some(123), Some(45), Some(CLIPBOARD))); - let p = command_params(&f); - assert!(p.get("__clipboard").is_none(), "file.new never sees the dialog's keys"); - assert_eq!((p["width"].as_u64(), p["height"].as_u64(), p["resolution"].as_f64()), (Some(123), Some(45), Some(72.0))); - } - - #[test] - fn preset_sets_size_resolution_and_create_params_drop_ui_keys() { - let mut f = crate::state::UiState::new_document_fields(); - let a4 = CATEGORIES.iter().find(|c| c.0 == "Print").unwrap().1.iter().find(|p| p.0 == "A4").unwrap(); - apply_preset(&mut f, a4, &Default::default()); - let p = command_params(&f); - assert_eq!(p["width"], 2480); - assert_eq!(p["height"], 3508); - assert_eq!(p["resolution"], 300.0); - assert!(p.get("__preset").is_none() && p.get("__unit").is_none()); - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", p).unwrap(); - let d = &s.active().unwrap().doc; - assert_eq!((d.size.width, d.size.height, d.resolution_dpi), (2480, 3508, 300.0)); - } - - #[test] - fn saved_selection_restores_all_settings_but_keeps_the_document_name() { - let mut session = photocraft_engine::Session::new(); - session - .execute( - "document.presets.save", - json!({"name":"Print proof","settings":{ - "width":1600,"height":800,"resolution":254.0,"mode":"cmyk","depth":16, - "background":"backgroundColor","backgroundColor":[0.2,0.3,0.4],"unit":"mm","resolutionUnit":"cm" - }}), - ) - .unwrap(); - let preset = session.presets.documents[0].clone(); - let mut f = crate::state::UiState::new_document_fields(); - set_clipboard(&mut f, 20, 30); - f.insert("name".into(), json!("Catalog cover")); - apply_saved_preset(&mut f, &preset); - assert_eq!(f["name"], "Catalog cover"); - assert_eq!(f["__unit"], "mm"); - assert_eq!(f["__resUnit"], "cm"); - assert_eq!(f["__savedPreset"], "Print proof"); - assert!(f.get("__preset").is_none()); - assert_eq!(clipboard_preset(&f), Some((CLIPBOARD, 20, 30, 72.0))); - let mut expected = preset.settings.command_params(); - expected["name"] = json!("Catalog cover"); - assert_eq!(command_params(&f), expected); - f.insert("width".into(), json!(42)); - assert_eq!(session.presets.documents[0], preset, "editing the form does not edit the snapshot"); - apply_preset(&mut f, &(CLIPBOARD, 20, 30, 72.0), &Default::default()); - assert!(f.get("__savedPreset").is_none()); - assert_eq!((f["width"].as_u64(), f["height"].as_u64()), (Some(20), Some(30))); - } - /// The real dialog (#254): a typed size must reach `file.new`, however it is confirmed. - mod dialog { - use super::super::{CATEGORIES, apply_preset}; - use crate::PhotocraftApp; - use crate::state::{DialogKind, UiState}; - use egui::accesskit::Role; - use egui_kittest::{Harness, kittest::Queryable}; - use std::sync::{Arc, Mutex}; - - /// The real preference services, backed by an in-memory store shared across app restarts. - fn harness_with_store(store: &Arc>>) -> Harness<'static, PhotocraftApp> { - let (read, write) = (store.clone(), store.clone()); - let services = crate::Services { - load_prefs: Some(Box::new(move || read.lock().unwrap().clone())), - save_prefs: Some(Box::new(move |text| { - *write.lock().unwrap() = Some(text.to_string()); - Ok(()) - })), - ..Default::default() - }; - let app = PhotocraftApp::new(photocraft_engine::Session::new(), services); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state( - |ui, app| { - crate::prefs_ui::tick(app, ui.ctx()); - crate::dialogs::show(app, ui.ctx()); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.state_mut().ui.open_dialog(DialogKind::NewDocument, UiState::new_document_fields()); - h.run_steps(3); - h - } - - /// #4789: the swatch beside Background Contents (and Custom…) opens the Color Picker; its - /// colour becomes the new document's background (kept as its "#rrggbb"). - #[test] - fn a_custom_background_color_is_picked_and_used() { - let mut h = harness_with_store(&Arc::new(Mutex::new(None))); - let nd = h.state().ui.dialogs[0].id; - assert!(h.query_by_label("Custom background color").is_some()); - h.get_by_label("Custom background color").click(); - h.run_steps(3); - let picker = h - .state() - .ui - .dialogs - .iter() - .find(|d| d.fields.get("__dialog").and_then(serde_json::Value::as_u64) == Some(nd)) - .map(|d| d.id) - .expect("the Color Picker opens over the dialog"); - h.state_mut().ui.dialog_mut(picker).unwrap().fields.insert("color".into(), serde_json::json!("#336699")); - crate::dialogs::confirm(h.state_mut(), picker).unwrap(); - h.run_steps(3); - let bg = h.state().ui.dialogs.iter().find(|d| d.id == nd).unwrap().fields["background"].clone(); - assert_eq!(bg, "#336699"); - crate::dialogs::confirm(h.state_mut(), nd).unwrap(); - let doc = &h.state().session.active().unwrap().doc; - let px = photocraft_compose::flatten(doc).px[0]; - assert!((px[0] * 255.0 - 51.0).abs() < 1.0 && (px[1] * 255.0 - 102.0).abs() < 1.0 && (px[2] * 255.0 - 153.0).abs() < 1.0, "{px:?}"); - } - - /// #4789: the swatch shows what each Background Contents choice paints, Background Color included. - #[test] - fn the_swatch_shows_each_background_choice() { - let mut h = harness_with_store(&Arc::new(Mutex::new(None))); - h.state_mut().run("tools.setColors", serde_json::json!({"foreground": "#000000", "background": "#336699"})).unwrap(); - let rgb = |bg: &str| super::super::background_rgb(h.state(), serde_json::json!({ "background": bg }).as_object().unwrap()); - assert_eq!(rgb("white"), Some([1.0; 3])); - assert_eq!(rgb("black"), Some([0.0; 3])); - assert_eq!(rgb("transparent"), None); - assert_eq!(rgb("#ff0000"), Some([1.0, 0.0, 0.0])); - let c = rgb("backgroundColor").expect("Background Color shows the toolbox colour"); - assert!((c[0] * 255.0 - 51.0).abs() < 1.0 && (c[1] * 255.0 - 102.0).abs() < 1.0 && (c[2] * 255.0 - 153.0).abs() < 1.0, "{c:?}"); - } - - fn name_preset(h: &mut Harness<'static, PhotocraftApp>, name: &str) { - h.get_by_label("Save Preset…").click(); - h.run_steps(2); - h.get_by_role_and_label(Role::TextInput, "Preset Name").click(); - h.run_steps(1); - h.event(egui::Event::Text(name.into())); - h.run_steps(1); - } - - #[test] - fn save_restart_select_create_and_delete_through_the_dialog() { - let store = Arc::new(Mutex::new(None)); - let mut h = harness_with_store(&store); - type_into(&mut h, 0, "1600"); - type_into(&mut h, 1, "1600"); - let mut f = fields(&h); - f.insert("background".into(), serde_json::json!("transparent")); - set_fields(&mut h, f); - name_preset(&mut h, " Product square "); - h.get_by_label("Save").click(); - h.run_steps(3); - assert!(h.state().session.documents().is_empty(), "saving does not create a document"); - assert_eq!(h.state().session.presets.documents[0].name, "Product square"); - type_into(&mut h, 0, "32"); - assert_eq!(h.state().session.presets.documents[0].settings.width, 1600); - drop(h); - - let mut h = harness_with_store(&store); - h.get_by_label("Saved").click(); - h.run_steps(2); - h.get_by_label("Product square").click(); - h.run_steps(2); - assert!(h.state().session.documents().is_empty(), "selection only populates the form"); - assert_eq!(fields(&h)["name"], "Untitled-1"); - assert_eq!(fields(&h)["background"], "transparent"); - h.get_by_label("Create").click(); - h.run_steps(3); - assert_eq!(created(&h), (1600, 1600, 72.0)); - let pixel = h.state_mut().session.execute("document.pixel", serde_json::json!({"x":0,"y":0})).unwrap(); - assert_eq!(pixel[3], 0.0); - - h.state_mut().ui.open_dialog(DialogKind::NewDocument, UiState::new_document_fields()); - h.run_steps(2); - h.get_by_label("Saved").click(); - h.run_steps(2); - h.get_by_label("Delete").click(); - h.run_steps(3); - drop(h); - let mut h = harness_with_store(&store); - h.get_by_label("Saved").click(); - h.run_steps(2); - assert!(h.state().session.presets.documents.is_empty()); - assert!(h.query_by_label("No saved presets yet.").is_some()); - } - - #[test] - fn enter_saves_the_preset_and_bad_names_leave_the_form_open() { - let mut h = harness(); - name_preset(&mut h, "Enter test"); - enter(&mut h); - assert_eq!(h.state().session.presets.documents.len(), 1); - assert!(h.state().session.documents().is_empty(), "Enter must not also press Create"); - assert_eq!(h.state().ui.dialogs.len(), 1); - name_preset(&mut h, " ENTER TEST "); - h.get_by_label("Save").click(); - h.run_steps(2); - assert!(fields(&h).get("__presetError").is_some()); - assert_eq!(h.state().session.presets.documents.len(), 1); - assert!(h.state().session.documents().is_empty()); - h.get_by_label("Cancel").click(); - h.run_steps(2); - name_preset(&mut h, ""); - // Cancel keeps the entered name; clear it as an automation edit, then use the button. - h.state_mut().ui.dialogs[0].fields.insert("__presetName".into(), serde_json::json!(" ")); - h.run_steps(2); - h.get_by_label("Save").click(); - h.run_steps(2); - assert!(fields(&h).get("__presetError").is_some()); - assert_eq!(h.state().session.presets.documents.len(), 1); - } - - fn harness() -> Harness<'static, PhotocraftApp> { - let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut h = Harness::builder() - .with_size(egui::vec2(1400.0, 900.0)) - .with_step_dt(1.0 / 60.0) - .build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.state_mut().ui.open_dialog(DialogKind::NewDocument, UiState::new_document_fields()); - h.run_steps(3); - h - } - - fn click_at(h: &mut Harness<'static, PhotocraftApp>, at: egui::Pos2) { - h.hover_at(at); - h.run_steps(1); - h.drag_at(at); - h.run_steps(1); - h.drop_at(at); - h.run_steps(2); - } - - /// A finger tap at `at`. Events for one phase share a frame (`input_mut`), because `Harness::step` would otherwise run one frame per queued event and drop Touch before the click release (so `second_click` would not see touch). - fn touch_tap_at(h: &mut Harness<'static, PhotocraftApp>, at: egui::Pos2) { - let touch = |phase| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(1), phase, pos: at, force: None }; - let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; - h.input_mut().events.extend([egui::Event::PointerMoved(at), touch(egui::TouchPhase::Start), button(true)]); - h.step(); - h.input_mut().events.extend([touch(egui::TouchPhase::End), button(false)]); - h.step(); - h.run_steps(1); - } - - /// The Width (0), Height (1) and Resolution (2) fields. - fn field(h: &Harness<'static, PhotocraftApp>, i: usize) -> egui::Rect { - h.query_all_by_role(Role::SpinButton).nth(i).map(|n| n.rect()).expect("a size field") - } - - /// Click into field `i` (which selects its text) and type `text`, as a user does. - fn type_into(h: &mut Harness<'static, PhotocraftApp>, i: usize, text: &str) { - let r = field(h, i); - click_at(h, r.center()); - for c in text.chars() { - h.event(egui::Event::Text(c.to_string())); - h.run_steps(1); - } - } - - fn fields(h: &Harness<'static, PhotocraftApp>) -> serde_json::Map { - h.state().ui.dialogs.first().map(|d| d.fields.clone()).expect("the dialog is open") - } - - fn set_fields(h: &mut Harness<'static, PhotocraftApp>, f: serde_json::Map) { - h.state_mut().ui.dialogs[0].fields = f; - h.run_steps(2); - } - - fn enter(h: &mut Harness<'static, PhotocraftApp>) { - h.key_press(egui::Key::Enter); - h.run_steps(3); - } - - fn created(h: &Harness<'static, PhotocraftApp>) -> (u32, u32, f32) { - assert!(h.state().ui.dialogs.is_empty(), "the dialog closed"); - let d = &h.state().session.active().expect("a new document").doc; - (d.size.width, d.size.height, d.resolution_dpi) - } - - /// Preset cards paint their titles directly, without an accessibility label. - fn preset_title_at(h: &Harness<'static, PhotocraftApp>, title: &str) -> egui::Pos2 { - fn find(shape: &egui::Shape, title: &str) -> Option { - match shape { - egui::Shape::Text(text) if text.galley.job.text == title => Some(text.visual_bounding_rect().center()), - egui::Shape::Vec(shapes) => shapes.iter().find_map(|shape| find(shape, title)), - _ => None, - } - } - h.output().shapes.iter().find_map(|shape| find(&shape.shape, title)).expect("visible preset title") - } - - fn second_click_creates_once(h: &mut Harness<'static, PhotocraftApp>, at: egui::Pos2) { - assert!(h.state().session.documents().is_empty(), "the first click only selects the preset"); - assert_eq!(h.state().ui.dialogs.len(), 1); - // Two real pointer press/release pairs within egui's double-click interval. - click_at(h, at); - h.run_steps(3); - assert_eq!(h.state().session.documents().len(), 1, "the second click creates exactly one document"); - assert!(h.state().ui.dialogs.is_empty(), "double-click closes the New Document dialog"); - assert!(h.state().ui.views[0].fit_pending, "the normal Create path fits the new document"); - } - - fn assert_pixel(h: &mut Harness<'static, PhotocraftApp>, expected: [f64; 4]) { - let pixel = h.state_mut().session.execute("document.pixel", serde_json::json!({"x":0,"y":0})).unwrap(); - for (actual, expected) in pixel.as_array().unwrap().iter().zip(expected) { - assert!((actual.as_f64().unwrap() - expected).abs() < 0.001, "background pixel: {pixel}"); - } - } - - fn cursor_over(h: &mut Harness<'static, PhotocraftApp>, at: egui::Pos2) -> egui::CursorIcon { - h.hover_at(at); - h.run_steps(2); - h.output().platform_output.cursor_icon - } - - /// #8331: headings and field labels keep the arrow; only the text fields show the I-beam. - #[test] - fn labels_show_the_arrow_and_only_text_fields_the_text_cursor() { - use egui_kittest::kittest::NodeT; - let mut h = harness(); - let label_at = |h: &Harness<'static, PhotocraftApp>, text: &str| { - h.query_all_by_label(text) - .find(|n| n.accesskit_node().role() == Role::Label) - .map(|n| n.rect().center()) - .unwrap_or_else(|| panic!("a {text:?} label")) - }; - for text in ["PRESET DETAILS", "Width", "Height", "Resolution", "Color Mode", "Background Contents"] { - let at = label_at(&h, text); - assert_eq!(cursor_over(&mut h, at), egui::CursorIcon::Default, "over {text:?}"); - } - // The name field still shows the text cursor, so the check above can tell them apart. - let name = h.query_all_by_role(Role::TextInput).next().map(|n| n.rect().center()).expect("the name field"); - assert_eq!(cursor_over(&mut h, name), egui::CursorIcon::Text, "over the name field"); - // The Saved tab's labels too. - h.get_by_label("Saved").click(); - h.run_steps(2); - let at = label_at(&h, "No saved presets yet."); - assert_eq!(cursor_over(&mut h, at), egui::CursorIcon::Default, "over the empty Saved list"); - } - - #[test] - fn double_click_builtin_preset_creates_its_size_and_current_details() { - let mut h = harness(); - let mut f = fields(&h); - f.extend(serde_json::json!({"name":"Portrait proof","mode":"cmyk","depth":16,"background":"transparent"}).as_object().unwrap().clone()); - set_fields(&mut h, f); - h.get_by_label("Photo").click(); - h.run_steps(2); - let at = preset_title_at(&h, "Portrait, 4 x 6"); - click_at(&mut h, at); - assert_eq!(fields(&h)["__preset"], "Portrait, 4 x 6"); - assert_eq!( - super::super::command_params(&fields(&h)), - serde_json::json!({"name":"Portrait proof","width":1200,"height":1800,"resolution":300.0, - "mode":"cmyk","depth":16,"background":"transparent"}) - ); - second_click_creates_once(&mut h, at); - assert_eq!(created(&h), (1200, 1800, 300.0)); - let doc = &h.state().session.active().unwrap().doc; - assert_eq!(doc.name, "Portrait proof"); - assert_eq!((doc.mode, doc.depth), (photocraft_doc::ColorMode::Cmyk, photocraft_doc::SampleType::U16)); - assert_pixel(&mut h, [0.0; 4]); - } - - /// Framework-style touch: the second tap lands ~48 px off (past egui's 6 px and the old 32 px touch slop) and still creates. - #[test] - fn touch_double_tap_with_jitter_creates_from_builtin_preset() { - let mut h = harness(); - h.get_by_label("Photo").click(); - h.run_steps(2); - let at = preset_title_at(&h, "Portrait, 4 x 6"); - touch_tap_at(&mut h, at); - assert_eq!(fields(&h)["__preset"], "Portrait, 4 x 6"); - assert!(h.state().session.documents().is_empty(), "first tap only selects"); - touch_tap_at(&mut h, egui::pos2(at.x + 48.0, at.y)); - assert_eq!(created(&h), (1200, 1800, 300.0)); - } - - /// Mouse keeps egui's tight distance: 20 px between clicks is two singles, not a create. - #[test] - fn mouse_double_click_with_large_jitter_does_not_create() { - let mut h = harness(); - h.get_by_label("Photo").click(); - h.run_steps(2); - let at = preset_title_at(&h, "Portrait, 4 x 6"); - click_at(&mut h, at); - click_at(&mut h, at + egui::vec2(20.0, 0.0)); - assert!(h.state().session.documents().is_empty()); - assert_eq!(h.state().ui.dialogs.len(), 1, "dialog stays open"); - } - - #[test] - fn double_click_clipboard_preset_creates_its_size_and_current_details() { - let mut h = harness(); - let mut f = fields(&h); - super::super::set_clipboard(&mut f, 37, 23); - apply_preset(&mut f, &("Other size", 100, 200, 300.0), &Default::default()); - f.extend(serde_json::json!({"mode":"gray","depth":8,"background":"white"}).as_object().unwrap().clone()); - set_fields(&mut h, f); - let at = preset_title_at(&h, super::super::CLIPBOARD); - click_at(&mut h, at); - assert_eq!(fields(&h)["__preset"], super::super::CLIPBOARD); - assert_eq!( - super::super::command_params(&fields(&h)), - serde_json::json!({"name":"Untitled-1","width":37,"height":23,"resolution":72.0, - "mode":"gray","depth":8,"background":"white"}) - ); - second_click_creates_once(&mut h, at); - assert_eq!(created(&h), (37, 23, 72.0)); - let doc = &h.state().session.active().unwrap().doc; - assert_eq!((doc.mode, doc.depth), (photocraft_doc::ColorMode::Grayscale, photocraft_doc::SampleType::U8)); - assert_pixel(&mut h, [1.0; 4]); - } - - #[test] - fn double_click_saved_preset_restores_all_settings_and_captured_background() { - let mut h = harness(); - h.state_mut() - .run( - "document.presets.save", - serde_json::json!({"name":"Saved proof","settings":{ - "width":48,"height":32,"resolution":254.0,"mode":"rgb","depth":32, - "background":"backgroundColor","backgroundColor":[0.125,0.375,0.625],"unit":"mm","resolutionUnit":"cm" - }}), - ) - .unwrap(); - h.state_mut().session.tools.background = [1.0, 0.0, 1.0, 1.0]; - let mut f = fields(&h); - f.insert("name".into(), serde_json::json!("Current document name")); - set_fields(&mut h, f); - h.get_by_label("Saved").click(); - h.run_steps(2); - let at = h.get_by_label("Saved proof").rect().center(); - click_at(&mut h, at); - assert_eq!(fields(&h)["__savedPreset"], "Saved proof"); - assert_eq!(fields(&h)["__unit"], "mm"); - assert_eq!(fields(&h)["__resUnit"], "cm"); - second_click_creates_once(&mut h, at); - assert_eq!(created(&h), (48, 32, 254.0)); - let doc = &h.state().session.active().unwrap().doc; - assert_eq!(doc.name, "Current document name"); - assert_eq!((doc.mode, doc.depth), (photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::F32)); - assert_pixel(&mut h, [0.125, 0.375, 0.625, 1.0]); - } - - #[test] - fn preset_cards_use_the_preset_resolution_preferences() { - let mut h = harness(); - h.state_mut().run("prefs.set", serde_json::json!({"path": "unitsAndRulers.printResolution", "value": 150.0})).unwrap(); - h.state_mut().run("prefs.set", serde_json::json!({"path": "unitsAndRulers.screenResolution", "value": 96.0})).unwrap(); - h.get_by_label("Photo").click(); - h.run_steps(2); - let at = preset_title_at(&h, "Landscape, 6 x 4"); - click_at(&mut h, at); - assert_eq!(fields(&h)["__unit"], "in"); - second_click_creates_once(&mut h, at); - assert_eq!(created(&h), (900, 600, 150.0), "6 x 4 in at 150 ppi"); - - h.state_mut().ui.open_dialog(DialogKind::NewDocument, UiState::new_document_fields()); - h.run_steps(2); - h.get_by_label("Web").click(); - h.run_steps(2); - let at = preset_title_at(&h, "Web Minimum"); - click_at(&mut h, at); - enter(&mut h); - assert_eq!(created(&h), (1024, 768, 96.0)); - } - - #[test] - fn arithmetic_dimensions_create_the_evaluated_size() { - let mut h = harness(); - type_into(&mut h, 0, "1920/2"); - type_into(&mut h, 1, "(100+50)*2"); - enter(&mut h); - assert_eq!(created(&h), (960, 300, 72.0)); - } - - #[test] - fn typed_size_then_enter_creates_that_size() { - let mut h = harness(); - type_into(&mut h, 0, "512"); - type_into(&mut h, 1, "512"); - let f = fields(&h); - assert_eq!((f["width"].as_u64(), f["height"].as_u64()), (Some(512), Some(512)), "whole pixels: {f:?}"); - enter(&mut h); - assert_eq!(created(&h), (512, 512, 72.0)); - } - - #[test] - fn typed_size_then_create_without_leaving_the_field_creates_that_size() { - let mut h = harness(); - type_into(&mut h, 0, "512"); - type_into(&mut h, 1, "300"); - // Still editing Height: click Create straight away. - let create = h.get_by_label("Create").rect(); - click_at(&mut h, create.center()); - assert_eq!(created(&h), (512, 300, 72.0)); - } - - #[test] - fn typing_over_a_preset_wins() { - let mut h = harness(); - let mut f = fields(&h); - let web = CATEGORIES.iter().find(|c| c.0 == "Web").unwrap().1.iter().find(|p| p.0 == "Web Minimum").unwrap(); - apply_preset(&mut f, web, &Default::default()); - set_fields(&mut h, f); - type_into(&mut h, 0, "512"); - type_into(&mut h, 1, "512"); - assert!(fields(&h).get("__preset").is_none(), "typing deselects the preset"); - enter(&mut h); - assert_eq!(created(&h), (512, 512, 72.0)); - } - - #[test] - fn the_clipboard_card_is_first_and_creates_the_clipboard_size() { - let mut h = harness(); - let mut f = fields(&h); - super::super::set_clipboard(&mut f, 640, 360); - set_fields(&mut h, f); - // Recent lists the Clipboard card first: three presets instead of two. - assert!(h.query_by_label_contains("BLANK DOCUMENT PRESETS (3)").is_some()); - let heading = h.get_by_label_contains("BLANK DOCUMENT PRESETS").rect(); - // Pick the second card, then the first (Clipboard) again. - click_at(&mut h, heading.left_bottom() + egui::vec2(80.0 + 172.0, 60.0)); - assert_eq!(fields(&h).get("__preset").and_then(|v| v.as_str()), Some("Default PhotoCraft Size")); - click_at(&mut h, heading.left_bottom() + egui::vec2(80.0, 60.0)); - assert_eq!(fields(&h).get("__preset").and_then(|v| v.as_str()), Some(super::super::CLIPBOARD)); - enter(&mut h); - assert_eq!(created(&h), (640, 360, 72.0)); - } - - #[test] - fn clicking_a_preset_card_after_typing_sets_its_size() { - let mut h = harness(); - type_into(&mut h, 0, "512"); - h.get_by_label("Photo").click(); - h.run_steps(2); - // The first card ("Landscape, 6 x 4") sits under the presets heading. - let heading = h.get_by_label_contains("BLANK DOCUMENT PRESETS").rect(); - click_at(&mut h, heading.left_bottom() + egui::vec2(80.0, 60.0)); - assert_eq!(fields(&h).get("__preset").and_then(|v| v.as_str()), Some("Landscape, 6 x 4")); - enter(&mut h); - assert_eq!(created(&h), (1800, 1200, 300.0)); - } - - #[test] - fn typed_size_in_inches_converts_at_the_resolution() { - let mut h = harness(); - type_into(&mut h, 2, "300"); - let mut f = fields(&h); - f.insert("__unit".into(), serde_json::json!("in")); - set_fields(&mut h, f); - type_into(&mut h, 0, "2"); - type_into(&mut h, 1, "1.5"); - enter(&mut h); - assert_eq!(created(&h), (600, 450, 300.0)); - } - - /// #1147: typed digit by digit, millimetres used to be rewritten after each keystroke - /// (`8` became `8.1`), so 841 never arrived. - #[test] - fn typed_size_in_millimetres_keeps_every_digit() { - let mut h = harness(); - let mut f = fields(&h); - f.insert("__unit".into(), serde_json::json!("mm")); - set_fields(&mut h, f); - type_into(&mut h, 0, "841"); - type_into(&mut h, 1, "1189"); - enter(&mut h); - assert_eq!(created(&h), (2384, 3370, 72.0)); - } - - #[test] - fn changing_units_keeps_the_typed_pixel_size() { - let mut h = harness(); - type_into(&mut h, 0, "512"); - type_into(&mut h, 1, "512"); - for unit in ["in", "cm", "mm", "pt", "pica", "px"] { - let mut f = fields(&h); - f.insert("__unit".into(), serde_json::json!(unit)); - set_fields(&mut h, f); - } - enter(&mut h); - assert_eq!(created(&h), (512, 512, 72.0)); - } - - #[test] - fn orientation_swap_keeps_whole_pixels() { - let mut h = harness(); - type_into(&mut h, 0, "512"); - type_into(&mut h, 1, "256"); - // The Portrait icon button follows the "Orientation" label (icons have tooltips only). - let label = h.get_by_label("Orientation").rect(); - let gap = h.ctx.global_style().spacing.item_spacing.x; - click_at(&mut h, egui::pos2(label.right() + gap + 12.0, label.center().y)); - enter(&mut h); - assert_eq!(created(&h), (256, 512, 72.0)); - } - - /// #4668: once an orientation is picked, the presets turn to it, on the cards and when applied. - #[test] - fn picked_orientation_turns_the_presets() { - let mut h = harness(); - h.get_by_label("Print").click(); - h.run_steps(2); - // The default 1920 x 1080 is already landscape: Landscape swaps nothing, but is picked. - let label = h.get_by_label("Orientation").rect(); - let gap = h.ctx.global_style().spacing.item_spacing.x; - click_at(&mut h, egui::pos2(label.right() + gap + 24.0 + gap + 12.0, label.center().y)); - assert_eq!((fields(&h)["width"].as_u64(), fields(&h)["height"].as_u64()), (Some(1920), Some(1080))); - let _ = preset_title_at(&h, "11.7 x 8.3 in @ 300 ppi"); - let at = preset_title_at(&h, "A4"); - click_at(&mut h, at); - enter(&mut h); - assert_eq!(created(&h), (3508, 2480, 300.0)); - } - - /// #4668: a physical unit picked for Width/Height is the one print presets show and keep. - #[test] - fn picked_physical_unit_is_the_print_presets_unit() { - let mut h = harness(); - let mut f = fields(&h); - f.insert("__unit".into(), serde_json::json!("mm")); - set_fields(&mut h, f); - h.get_by_label("Print").click(); - h.run_steps(2); - let _ = preset_title_at(&h, "210 x 297 mm @ 300 ppi"); - let at = preset_title_at(&h, "A4"); - click_at(&mut h, at); - assert_eq!(fields(&h)["__unit"], "mm"); - // Screen presets stay in pixels. - h.get_by_label("Web").click(); - h.run_steps(2); - let _ = preset_title_at(&h, "1024 x 768 px @ 72 ppi"); - enter(&mut h); - assert_eq!(created(&h), (2480, 3508, 300.0)); - } - - #[test] - fn hovering_preset_tabs_shows_pointing_hand_not_text_cursor() { - let mut h = harness(); - for tab in ["Recent", "Saved", "Photo", "Print", "Art & Illustration", "Web", "Mobile", "Film & Video"] { - let rect = h.get_by_label(tab).rect(); - h.hover_at(rect.center()); - h.run_steps(2); - assert_eq!( - h.output().platform_output.cursor_icon, - egui::CursorIcon::PointingHand, - "hovering preset tab {tab:?} must show PointingHand instead of text caret" - ); - } - } - } -} +mod tests; diff --git a/crates/ui-egui/src/new_doc_ui/tests.rs b/crates/ui-egui/src/new_doc_ui/tests.rs new file mode 100644 index 0000000000..e4461f7d85 --- /dev/null +++ b/crates/ui-egui/src/new_doc_ui/tests.rs @@ -0,0 +1,910 @@ +use super::*; + +/// #321: New Document offers the working space and the other profiles of the mode's space. +#[test] +fn color_profile_menu_lists_the_profiles_of_the_modes_space() { + use photocraft_cms::{Builtin, ColorSpace, ProfileClass}; + use photocraft_engine::installed_profiles::InstalledProfile; + let installed = [ + InstalledProfile { path: "press.icc".into(), description: "Press".into(), class: ProfileClass::Output, color_space: ColorSpace::Cmyk }, + InstalledProfile { path: "panel.icc".into(), description: "Panel".into(), class: ProfileClass::Display, color_space: ColorSpace::Rgb }, + ]; + let values = |mode: &str| { + profile_options(color_mode_of(mode).map(photocraft_engine::color_cmds::mode_space), "sRGB", &installed) + .into_iter() + .map(|(v, _)| v) + .collect::>() + }; + let rgb = values("rgb"); + assert_eq!(rgb[0], "working"); + assert!(rgb.contains(&Builtin::AdobeRgbCompat.id().to_string()) && rgb.contains(&"panel.icc".to_string())); + assert!(!rgb.contains(&Builtin::CoatedCmyk.id().to_string()) && !rgb.contains(&"press.icc".to_string())); + let cmyk = values("cmyk"); + assert!(cmyk.contains(&"press.icc".to_string()) && !cmyk.contains(&Builtin::Srgb.id().to_string())); + assert!(profile_options(None, "sRGB", &installed).len() == 1, "an unknown mode offers only the working space"); + // Every entry is one `file.new` takes for that mode. + for mode in ["rgb", "gray", "cmyk", "lab"] { + for v in values(mode).into_iter().filter(|v| !v.ends_with(".icc")) { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 2, "height": 2, "mode": mode, "profile": v})).unwrap_or_else(|e| panic!("{mode} {v}: {e}")); + } + } +} + +/// A saved preset replaces the Color Profile picked before: its own, or the working space. +#[test] +fn applying_a_preset_replaces_the_picked_profile() { + let mut s = photocraft_engine::Session::new(); + let base = json!({"width": 8, "height": 8, "mode": "cmyk", "unit": "px"}); + s.execute("document.presets.save", json!({"name": "Plain", "settings": base})).unwrap(); + let mut press = base.clone(); + press["profile"] = json!("coated-cmyk"); + s.execute("document.presets.save", json!({"name": "Press", "settings": press})).unwrap(); + let mut f = Map::new(); + f.insert("profile".into(), json!(photocraft_cms::Builtin::AdobeRgbCompat.id())); + apply_saved_preset(&mut f, &s.presets.documents[0]); + assert!(!f.contains_key("profile"), "{f:?}"); + assert!(s.execute("file.new", command_params(&f)).is_ok()); + apply_saved_preset(&mut f, &s.presets.documents[1]); + assert_eq!(f["profile"], "coated-cmyk"); +} + +/// #9086: the Artboards checkbox's field reaches `file.new`, which starts the document as one +/// artboard; the dialog's own `__` keys don't. +#[test] +fn the_artboards_box_creates_an_artboard_document() { + let mut s = photocraft_engine::Session::new(); + let mut f = Map::new(); + for (k, v) in [("width", json!(64)), ("height", json!(48)), ("artboard", json!(true)), ("__orientation", json!("landscape"))] { + f.insert(k.into(), v); + } + s.execute("file.new", command_params(&f)).unwrap(); + let doc = &s.active().unwrap().doc; + assert_eq!(doc.artboards().len(), 1); + assert_eq!(doc.artboards()[0].2.rect, doc.bounds()); +} + +#[test] +fn units_round_trip_through_pixels() { + assert_eq!(to_unit(2100.0, "in", 300.0), 7.0); + assert_eq!(from_unit(7.0, "in", 300.0), 2100.0); + assert_eq!(from_unit(2.54, "cm", 300.0), 300.0); + assert_eq!(to_unit(640.0, "px", 72.0), 640.0); +} + +/// #1147: 5 mm at 72 ppi is 14 px, which is 4.94 mm. The field must keep showing the typed 5. +#[test] +fn typed_size_in_a_physical_unit_shows_as_typed() { + let mut f = crate::state::UiState::new_document_fields(); + set_size(&mut f, "height", 5.0, "mm", 72.0); + assert_eq!(command_params(&f)["height"], json!(14)); + assert_eq!(shown_size(&f, "height", 1080.0, "mm", 72.0), 5.0); + // Another unit, or pixels changed elsewhere (a preset, the orientation swap): converted. + assert_eq!(shown_size(&f, "height", 1080.0, "cm", 72.0), to_unit(14.0, "cm", 72.0)); + f.insert("height".into(), json!(1080)); + assert_eq!(shown_size(&f, "height", 1080.0, "mm", 72.0), to_unit(1080.0, "mm", 72.0)); + // Pixels show whole pixels. + set_size(&mut f, "width", 512.4, "px", 72.0); + assert_eq!(shown_size(&f, "width", 1920.0, "px", 72.0), 512.0); + // Over the 300000 px limit the field shows the limit. + set_size(&mut f, "width", 300_000.0, "mm", 72.0); + assert_eq!(command_params(&f)["width"], json!(300_000)); + assert_eq!(shown_size(&f, "width", 1920.0, "mm", 72.0), to_unit(300_000.0, "mm", 72.0)); +} + +/// #5661: 1 px at 300 ppi is 0.0033 in. Showing it in inches clamped the field to 0.01 in and +/// turned the width into 3 px without an edit. +#[test] +fn tiny_size_in_inches_is_not_changed_by_showing_it() { + use egui_kittest::Harness; + let app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut f = crate::state::UiState::new_document_fields(); + for (k, v) in [("width", json!(1)), ("height", json!(1)), ("resolution", json!(300.0)), ("__unit", json!("in"))] { + f.insert(k.into(), v); + } + let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state( + |ui, (app, f): &mut (crate::PhotocraftApp, Map)| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + body(app, ui, f); + } + }, + (app, f), + ); + crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(3); + let p = command_params(&h.state().1); + assert_eq!((p["width"].as_u64(), p["height"].as_u64()), (Some(1), Some(1))); +} + +/// #1147: the Orientation buttons swap the typed values too: 841 x 1189 mm becomes 1189 x 841. +#[test] +fn orientation_swap_keeps_the_typed_values() { + let mut f = crate::state::UiState::new_document_fields(); + set_size(&mut f, "width", 841.0, "mm", 72.0); + set_size(&mut f, "height", 1189.0, "mm", 72.0); + swap_size(&mut f); + let p = command_params(&f); + assert_eq!((p["width"].clone(), p["height"].clone()), (json!(3370), json!(2384))); + assert_eq!((shown_size(&f, "width", 1920.0, "mm", 72.0), shown_size(&f, "height", 1080.0, "mm", 72.0)), (1189.0, 841.0)); +} + +#[test] +fn resolution_keeps_physical_size_in_physical_units_and_pixels_in_px() { + let a4 = CATEGORIES.iter().find(|c| c.0 == "Print").unwrap().1.iter().find(|p| p.0 == "A4").unwrap(); + let mut f = crate::state::UiState::new_document_fields(); + apply_preset(&mut f, a4, &Default::default()); + f.insert("__unit".into(), json!("in")); + set_resolution(&mut f, 150.0); + let p = command_params(&f); + assert_eq!((p["width"].clone(), p["height"].clone(), p["resolution"].clone()), (json!(1240), json!(1754), json!(150.0))); + assert!(!f.contains_key("__preset")); + + let mut f = crate::state::UiState::new_document_fields(); + apply_preset(&mut f, a4, &Default::default()); + f.insert("__unit".into(), json!("px")); + set_resolution(&mut f, 150.0); + let p = command_params(&f); + assert_eq!((p["width"].clone(), p["height"].clone(), p["resolution"].clone()), (json!(2480), json!(3508), json!(150.0))); +} + +/// Units & Rulers › New Document Preset Resolutions: print presets keep their inches at the +/// Print Resolution, screen presets keep their pixels at the Screen Resolution. +#[test] +fn iso_b_paper_presets_use_correct_dimensions_and_selected_units() { + let presets = CATEGORIES.iter().find(|c| c.0 == "Print").unwrap().1; + let mut f = crate::state::UiState::new_document_fields(); + f.insert("__unit".into(), json!("mm")); + for (name, w, h) in [("B3", 4169, 5906), ("B4", 2953, 4169)] { + let preset = presets.iter().find(|p| p.0 == name).unwrap(); + assert_eq!((preset.1, preset.2, preset.3), (w, h, 300.0)); + assert_eq!(preset_unit(preset, &f), "mm"); + apply_preset(&mut f, preset, &Default::default()); + let params = command_params(&f); + assert_eq!((params["width"].as_u64(), params["height"].as_u64()), (Some(u64::from(w)), Some(u64::from(h)))); + assert_eq!(params["resolution"], 300.0); + } +} + +#[test] +fn presets_follow_the_preset_resolution_preferences() { + let find = |cat: &str, name: &str| *CATEGORIES.iter().find(|c| c.0 == cat).unwrap().1.iter().find(|p| p.0 == name).unwrap(); + let (letter, web) = (find("Print", "Letter"), find("Web", "Web Minimum")); + let stock = UnitsAndRulers::default(); + assert_eq!(at_pref_resolutions(&letter, &stock), letter, "the defaults are the listed sizes"); + assert_eq!(at_pref_resolutions(&web, &stock), web); + + let units = UnitsAndRulers { print_resolution: 200.0, screen_resolution: 96.0, ..stock.clone() }; + assert_eq!(at_pref_resolutions(&letter, &units), ("Letter", 1700, 2200, 200.0), "8.5 x 11 in at 200 ppi"); + assert_eq!(at_pref_resolutions(&find("Print", "A4"), &units), ("A4", 1653, 2339, 200.0)); + assert_eq!(at_pref_resolutions(&web, &units), ("Web Minimum", 1024, 768, 96.0), "pixels kept"); + let clipboard = (CLIPBOARD, 123, 45, 72.0); + assert_eq!(at_pref_resolutions(&clipboard, &units), clipboard, "the copied pixels keep their resolution"); + + let mut f = crate::state::UiState::new_document_fields(); + apply_preset(&mut f, &letter, &units); + assert_eq!((f["width"].as_u64(), f["height"].as_u64(), f["resolution"].as_f64()), (Some(1700), Some(2200), Some(200.0))); + assert_eq!((f["__preset"].as_str(), f["__unit"].as_str()), (Some("Letter"), Some("in")), "still a print preset below 300 ppi"); + apply_preset(&mut f, &web, &units); + assert_eq!((f["width"].as_u64(), f["resolution"].as_f64(), f["__unit"].as_str()), (Some(1024), Some(96.0), Some("px"))); + + // Out-of-range values (a hand-edited preferences file) never make an unusable size. + for bad in [0.0, -5.0, f64::NAN, f64::INFINITY] { + let units = UnitsAndRulers { print_resolution: bad, screen_resolution: bad, ..stock.clone() }; + assert_eq!(at_pref_resolutions(&letter, &units), letter, "{bad}"); + assert_eq!(at_pref_resolutions(&web, &units), web, "{bad}"); + } + let huge = UnitsAndRulers { print_resolution: 1e9, ..stock }; + let (_, w, h, _) = at_pref_resolutions(&find("Art & Illustration", "Poster"), &huge); + assert_eq!((w, h), (300_000, 300_000), "clamped to the file.new limit"); +} + +#[test] +fn preset_card_titles_fit_the_card_in_every_language() { + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + for lang in crate::i18n::Lang::all() { + for p in CATEGORIES.iter().flat_map(|c| c.1.iter()) { + let title = crate::i18n::tr(lang, p.0); + let g = card_title(ui.painter(), title, 152.0, egui::Color32::WHITE); + assert!(g.size().x <= 152.0 && g.rows.len() <= 2 && !g.elided, "{}: {title}", lang.code()); + } + } + }); + out.textures_delta.clear(); +} + +#[test] +fn recent_category_lists_clipboard_then_created_documents_then_uncovered_defaults() { + let settings = |w, h, ppi| DocumentSettings { + width: w, + height: h, + resolution: ppi, + mode: "rgb".into(), + depth: 8, + background: "white".into(), + background_color: None, + profile: None, + unit: "px".into(), + resolution_unit: "in".into(), + }; + let mut f = Map::new(); + set_clipboard(&mut f, 20, 30); + let cards = recent_cards(&f, &[settings(800, 600, 72.0), settings(1920, 1080, 72.0)], &UnitsAndRulers::default()); + let titles: Vec<(&str, String)> = cards.iter().map(|c| (c.title(), c.size_line(&UnitsAndRulers::default(), &f))).collect(); + assert_eq!( + titles, + [ + (CLIPBOARD, "20 x 30 px @ 72 ppi".to_string()), + ("Custom", "800 x 600 px @ 72 ppi".to_string()), + ("HDTV 1080p", "1920 x 1080 px @ 72 ppi".to_string()), + ("Default PhotoCraft Size", "7 x 5 in @ 300 ppi".to_string()), + ] + ); + assert!(holds(&f, &settings(20, 30, 72.0)) && !holds(&f, &settings(800, 600, 72.0))); +} + +#[test] +fn clipboard_preset_comes_first_and_is_selected() { + // Nothing on the clipboard: the dialog opens as before. + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let f = app.new_document_fields(); + assert_eq!(f, crate::state::UiState::new_document_fields()); + assert!(clipboard_preset(&f).is_none()); + // Pixels copied in the app: the Clipboard preset takes their size, at 72 ppi, selected. + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("select.rect", json!({"x": 10, "y": 20, "width": 123, "height": 45})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + let f = app.new_document_fields(); + assert_eq!(clipboard_preset(&f), Some((CLIPBOARD, 123, 45, 72.0))); + assert_eq!((f["width"].as_u64(), f["height"].as_u64(), f["__preset"].as_str()), (Some(123), Some(45), Some(CLIPBOARD))); + let p = command_params(&f); + assert!(p.get("__clipboard").is_none(), "file.new never sees the dialog's keys"); + assert_eq!((p["width"].as_u64(), p["height"].as_u64(), p["resolution"].as_f64()), (Some(123), Some(45), Some(72.0))); +} + +#[test] +fn preset_sets_size_resolution_and_create_params_drop_ui_keys() { + let mut f = crate::state::UiState::new_document_fields(); + let a4 = CATEGORIES.iter().find(|c| c.0 == "Print").unwrap().1.iter().find(|p| p.0 == "A4").unwrap(); + apply_preset(&mut f, a4, &Default::default()); + let p = command_params(&f); + assert_eq!(p["width"], 2480); + assert_eq!(p["height"], 3508); + assert_eq!(p["resolution"], 300.0); + assert!(p.get("__preset").is_none() && p.get("__unit").is_none()); + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", p).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!((d.size.width, d.size.height, d.resolution_dpi), (2480, 3508, 300.0)); +} + +#[test] +fn saved_selection_restores_all_settings_but_keeps_the_document_name() { + let mut session = photocraft_engine::Session::new(); + session + .execute( + "document.presets.save", + json!({"name":"Print proof","settings":{ + "width":1600,"height":800,"resolution":254.0,"mode":"cmyk","depth":16, + "background":"backgroundColor","backgroundColor":[0.2,0.3,0.4],"unit":"mm","resolutionUnit":"cm" + }}), + ) + .unwrap(); + let preset = session.presets.documents[0].clone(); + let mut f = crate::state::UiState::new_document_fields(); + set_clipboard(&mut f, 20, 30); + f.insert("name".into(), json!("Catalog cover")); + apply_saved_preset(&mut f, &preset); + assert_eq!(f["name"], "Catalog cover"); + assert_eq!(f["__unit"], "mm"); + assert_eq!(f["__resUnit"], "cm"); + assert_eq!(f["__savedPreset"], "Print proof"); + assert!(f.get("__preset").is_none()); + assert_eq!(clipboard_preset(&f), Some((CLIPBOARD, 20, 30, 72.0))); + let mut expected = preset.settings.command_params(); + expected["name"] = json!("Catalog cover"); + assert_eq!(command_params(&f), expected); + f.insert("width".into(), json!(42)); + assert_eq!(session.presets.documents[0], preset, "editing the form does not edit the snapshot"); + apply_preset(&mut f, &(CLIPBOARD, 20, 30, 72.0), &Default::default()); + assert!(f.get("__savedPreset").is_none()); + assert_eq!((f["width"].as_u64(), f["height"].as_u64()), (Some(20), Some(30))); +} +/// The real dialog (#254): a typed size must reach `file.new`, however it is confirmed. +mod dialog { + use super::super::{CATEGORIES, apply_preset}; + use crate::PhotocraftApp; + use crate::state::{DialogKind, UiState}; + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + use std::sync::{Arc, Mutex}; + + /// The real preference services, backed by an in-memory store shared across app restarts. + fn harness_with_store(store: &Arc>>) -> Harness<'static, PhotocraftApp> { + let (read, write) = (store.clone(), store.clone()); + let services = crate::Services { + load_prefs: Some(Box::new(move || read.lock().unwrap().clone())), + save_prefs: Some(Box::new(move |text| { + *write.lock().unwrap() = Some(text.to_string()); + Ok(()) + })), + ..Default::default() + }; + let app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state( + |ui, app| { + crate::prefs_ui::tick(app, ui.ctx()); + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.state_mut().ui.open_dialog(DialogKind::NewDocument, UiState::new_document_fields()); + h.run_steps(3); + h + } + + /// #4789: the swatch beside Background Contents (and Custom…) opens the Color Picker; its + /// colour becomes the new document's background (kept as its "#rrggbb"). + #[test] + fn a_custom_background_color_is_picked_and_used() { + let mut h = harness_with_store(&Arc::new(Mutex::new(None))); + let nd = h.state().ui.dialogs[0].id; + assert!(h.query_by_label("Custom background color").is_some()); + h.get_by_label("Custom background color").click(); + h.run_steps(3); + let picker = h + .state() + .ui + .dialogs + .iter() + .find(|d| d.fields.get("__dialog").and_then(serde_json::Value::as_u64) == Some(nd)) + .map(|d| d.id) + .expect("the Color Picker opens over the dialog"); + h.state_mut().ui.dialog_mut(picker).unwrap().fields.insert("color".into(), serde_json::json!("#336699")); + crate::dialogs::confirm(h.state_mut(), picker).unwrap(); + h.run_steps(3); + let bg = h.state().ui.dialogs.iter().find(|d| d.id == nd).unwrap().fields["background"].clone(); + assert_eq!(bg, "#336699"); + crate::dialogs::confirm(h.state_mut(), nd).unwrap(); + let doc = &h.state().session.active().unwrap().doc; + let px = photocraft_compose::flatten(doc).px[0]; + assert!((px[0] * 255.0 - 51.0).abs() < 1.0 && (px[1] * 255.0 - 102.0).abs() < 1.0 && (px[2] * 255.0 - 153.0).abs() < 1.0, "{px:?}"); + } + + /// #4789: the swatch shows what each Background Contents choice paints, Background Color included. + #[test] + fn the_swatch_shows_each_background_choice() { + let mut h = harness_with_store(&Arc::new(Mutex::new(None))); + h.state_mut().run("tools.setColors", serde_json::json!({"foreground": "#000000", "background": "#336699"})).unwrap(); + let rgb = |bg: &str| super::super::background_rgb(h.state(), serde_json::json!({ "background": bg }).as_object().unwrap()); + assert_eq!(rgb("white"), Some([1.0; 3])); + assert_eq!(rgb("black"), Some([0.0; 3])); + assert_eq!(rgb("transparent"), None); + assert_eq!(rgb("#ff0000"), Some([1.0, 0.0, 0.0])); + let c = rgb("backgroundColor").expect("Background Color shows the toolbox colour"); + assert!((c[0] * 255.0 - 51.0).abs() < 1.0 && (c[1] * 255.0 - 102.0).abs() < 1.0 && (c[2] * 255.0 - 153.0).abs() < 1.0, "{c:?}"); + } + + fn name_preset(h: &mut Harness<'static, PhotocraftApp>, name: &str) { + h.get_by_label("Save Preset…").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, "Preset Name").click(); + h.run_steps(1); + h.event(egui::Event::Text(name.into())); + h.run_steps(1); + } + + #[test] + fn save_restart_select_create_and_delete_through_the_dialog() { + let store = Arc::new(Mutex::new(None)); + let mut h = harness_with_store(&store); + type_into(&mut h, 0, "1600"); + type_into(&mut h, 1, "1600"); + let mut f = fields(&h); + f.insert("background".into(), serde_json::json!("transparent")); + set_fields(&mut h, f); + name_preset(&mut h, " Product square "); + h.get_by_label("Save").click(); + h.run_steps(3); + assert!(h.state().session.documents().is_empty(), "saving does not create a document"); + assert_eq!(h.state().session.presets.documents[0].name, "Product square"); + type_into(&mut h, 0, "32"); + assert_eq!(h.state().session.presets.documents[0].settings.width, 1600); + drop(h); + + let mut h = harness_with_store(&store); + h.get_by_label("Saved").click(); + h.run_steps(2); + h.get_by_label("Product square").click(); + h.run_steps(2); + assert!(h.state().session.documents().is_empty(), "selection only populates the form"); + assert_eq!(fields(&h)["name"], "Untitled-1"); + assert_eq!(fields(&h)["background"], "transparent"); + h.get_by_label("Create").click(); + h.run_steps(3); + assert_eq!(created(&h), (1600, 1600, 72.0)); + let pixel = h.state_mut().session.execute("document.pixel", serde_json::json!({"x":0,"y":0})).unwrap(); + assert_eq!(pixel[3], 0.0); + + h.state_mut().ui.open_dialog(DialogKind::NewDocument, UiState::new_document_fields()); + h.run_steps(2); + h.get_by_label("Saved").click(); + h.run_steps(2); + h.get_by_label("Delete").click(); + h.run_steps(3); + drop(h); + let mut h = harness_with_store(&store); + h.get_by_label("Saved").click(); + h.run_steps(2); + assert!(h.state().session.presets.documents.is_empty()); + assert!(h.query_by_label("No saved presets yet.").is_some()); + } + + #[test] + fn enter_saves_the_preset_and_bad_names_leave_the_form_open() { + let mut h = harness(); + name_preset(&mut h, "Enter test"); + enter(&mut h); + assert_eq!(h.state().session.presets.documents.len(), 1); + assert!(h.state().session.documents().is_empty(), "Enter must not also press Create"); + assert_eq!(h.state().ui.dialogs.len(), 1); + name_preset(&mut h, " ENTER TEST "); + h.get_by_label("Save").click(); + h.run_steps(2); + assert!(fields(&h).get("__presetError").is_some()); + assert_eq!(h.state().session.presets.documents.len(), 1); + assert!(h.state().session.documents().is_empty()); + h.get_by_label("Cancel").click(); + h.run_steps(2); + name_preset(&mut h, ""); + // Cancel keeps the entered name; clear it as an automation edit, then use the button. + h.state_mut().ui.dialogs[0].fields.insert("__presetName".into(), serde_json::json!(" ")); + h.run_steps(2); + h.get_by_label("Save").click(); + h.run_steps(2); + assert!(fields(&h).get("__presetError").is_some()); + assert_eq!(h.state().session.presets.documents.len(), 1); + } + + fn harness() -> Harness<'static, PhotocraftApp> { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut h = Harness::builder() + .with_size(egui::vec2(1400.0, 900.0)) + .with_step_dt(1.0 / 60.0) + .build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.state_mut().ui.open_dialog(DialogKind::NewDocument, UiState::new_document_fields()); + h.run_steps(3); + h + } + + fn click_at(h: &mut Harness<'static, PhotocraftApp>, at: egui::Pos2) { + h.hover_at(at); + h.run_steps(1); + h.drag_at(at); + h.run_steps(1); + h.drop_at(at); + h.run_steps(2); + } + + /// A finger tap at `at`. Events for one phase share a frame (`input_mut`), because `Harness::step` would otherwise run one frame per queued event and drop Touch before the click release (so `second_click` would not see touch). + fn touch_tap_at(h: &mut Harness<'static, PhotocraftApp>, at: egui::Pos2) { + let touch = |phase| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(1), phase, pos: at, force: None }; + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.input_mut().events.extend([egui::Event::PointerMoved(at), touch(egui::TouchPhase::Start), button(true)]); + h.step(); + h.input_mut().events.extend([touch(egui::TouchPhase::End), button(false)]); + h.step(); + h.run_steps(1); + } + + /// The Width (0), Height (1) and Resolution (2) fields. + fn field(h: &Harness<'static, PhotocraftApp>, i: usize) -> egui::Rect { + h.query_all_by_role(Role::SpinButton).nth(i).map(|n| n.rect()).expect("a size field") + } + + /// Click into field `i` (which selects its text) and type `text`, as a user does. + fn type_into(h: &mut Harness<'static, PhotocraftApp>, i: usize, text: &str) { + let r = field(h, i); + click_at(h, r.center()); + for c in text.chars() { + h.event(egui::Event::Text(c.to_string())); + h.run_steps(1); + } + } + + fn fields(h: &Harness<'static, PhotocraftApp>) -> serde_json::Map { + h.state().ui.dialogs.first().map(|d| d.fields.clone()).expect("the dialog is open") + } + + fn set_fields(h: &mut Harness<'static, PhotocraftApp>, f: serde_json::Map) { + h.state_mut().ui.dialogs[0].fields = f; + h.run_steps(2); + } + + fn enter(h: &mut Harness<'static, PhotocraftApp>) { + h.key_press(egui::Key::Enter); + h.run_steps(3); + } + + fn created(h: &Harness<'static, PhotocraftApp>) -> (u32, u32, f32) { + assert!(h.state().ui.dialogs.is_empty(), "the dialog closed"); + let d = &h.state().session.active().expect("a new document").doc; + (d.size.width, d.size.height, d.resolution_dpi) + } + + /// Preset cards paint their titles directly, without an accessibility label. + fn preset_title_at(h: &Harness<'static, PhotocraftApp>, title: &str) -> egui::Pos2 { + fn find(shape: &egui::Shape, title: &str) -> Option { + match shape { + egui::Shape::Text(text) if text.galley.job.text == title => Some(text.visual_bounding_rect().center()), + egui::Shape::Vec(shapes) => shapes.iter().find_map(|shape| find(shape, title)), + _ => None, + } + } + h.output().shapes.iter().find_map(|shape| find(&shape.shape, title)).expect("visible preset title") + } + + fn second_click_creates_once(h: &mut Harness<'static, PhotocraftApp>, at: egui::Pos2) { + assert!(h.state().session.documents().is_empty(), "the first click only selects the preset"); + assert_eq!(h.state().ui.dialogs.len(), 1); + // Two real pointer press/release pairs within egui's double-click interval. + click_at(h, at); + h.run_steps(3); + assert_eq!(h.state().session.documents().len(), 1, "the second click creates exactly one document"); + assert!(h.state().ui.dialogs.is_empty(), "double-click closes the New Document dialog"); + assert!(h.state().ui.views[0].fit_pending, "the normal Create path fits the new document"); + } + + fn assert_pixel(h: &mut Harness<'static, PhotocraftApp>, expected: [f64; 4]) { + let pixel = h.state_mut().session.execute("document.pixel", serde_json::json!({"x":0,"y":0})).unwrap(); + for (actual, expected) in pixel.as_array().unwrap().iter().zip(expected) { + assert!((actual.as_f64().unwrap() - expected).abs() < 0.001, "background pixel: {pixel}"); + } + } + + fn cursor_over(h: &mut Harness<'static, PhotocraftApp>, at: egui::Pos2) -> egui::CursorIcon { + h.hover_at(at); + h.run_steps(2); + h.output().platform_output.cursor_icon + } + + /// #8331: headings and field labels keep the arrow; only the text fields show the I-beam. + #[test] + fn labels_show_the_arrow_and_only_text_fields_the_text_cursor() { + use egui_kittest::kittest::NodeT; + let mut h = harness(); + let label_at = |h: &Harness<'static, PhotocraftApp>, text: &str| { + h.query_all_by_label(text) + .find(|n| n.accesskit_node().role() == Role::Label) + .map(|n| n.rect().center()) + .unwrap_or_else(|| panic!("a {text:?} label")) + }; + for text in ["PRESET DETAILS", "Width", "Height", "Resolution", "Color Mode", "Background Contents"] { + let at = label_at(&h, text); + assert_eq!(cursor_over(&mut h, at), egui::CursorIcon::Default, "over {text:?}"); + } + // The name field still shows the text cursor, so the check above can tell them apart. + let name = h.query_all_by_role(Role::TextInput).next().map(|n| n.rect().center()).expect("the name field"); + assert_eq!(cursor_over(&mut h, name), egui::CursorIcon::Text, "over the name field"); + // The Saved tab's labels too. + h.get_by_label("Saved").click(); + h.run_steps(2); + let at = label_at(&h, "No saved presets yet."); + assert_eq!(cursor_over(&mut h, at), egui::CursorIcon::Default, "over the empty Saved list"); + } + + #[test] + fn double_click_builtin_preset_creates_its_size_and_current_details() { + let mut h = harness(); + let mut f = fields(&h); + f.extend(serde_json::json!({"name":"Portrait proof","mode":"cmyk","depth":16,"background":"transparent"}).as_object().unwrap().clone()); + set_fields(&mut h, f); + h.get_by_label("Photo").click(); + h.run_steps(2); + let at = preset_title_at(&h, "Portrait, 4 x 6"); + click_at(&mut h, at); + assert_eq!(fields(&h)["__preset"], "Portrait, 4 x 6"); + assert_eq!( + super::super::command_params(&fields(&h)), + serde_json::json!({"name":"Portrait proof","width":1200,"height":1800,"resolution":300.0, + "mode":"cmyk","depth":16,"background":"transparent"}) + ); + second_click_creates_once(&mut h, at); + assert_eq!(created(&h), (1200, 1800, 300.0)); + let doc = &h.state().session.active().unwrap().doc; + assert_eq!(doc.name, "Portrait proof"); + assert_eq!((doc.mode, doc.depth), (photocraft_doc::ColorMode::Cmyk, photocraft_doc::SampleType::U16)); + assert_pixel(&mut h, [0.0; 4]); + } + + /// Framework-style touch: the second tap lands ~48 px off (past egui's 6 px and the old 32 px touch slop) and still creates. + #[test] + fn touch_double_tap_with_jitter_creates_from_builtin_preset() { + let mut h = harness(); + h.get_by_label("Photo").click(); + h.run_steps(2); + let at = preset_title_at(&h, "Portrait, 4 x 6"); + touch_tap_at(&mut h, at); + assert_eq!(fields(&h)["__preset"], "Portrait, 4 x 6"); + assert!(h.state().session.documents().is_empty(), "first tap only selects"); + touch_tap_at(&mut h, egui::pos2(at.x + 48.0, at.y)); + assert_eq!(created(&h), (1200, 1800, 300.0)); + } + + /// Mouse keeps egui's tight distance: 20 px between clicks is two singles, not a create. + #[test] + fn mouse_double_click_with_large_jitter_does_not_create() { + let mut h = harness(); + h.get_by_label("Photo").click(); + h.run_steps(2); + let at = preset_title_at(&h, "Portrait, 4 x 6"); + click_at(&mut h, at); + click_at(&mut h, at + egui::vec2(20.0, 0.0)); + assert!(h.state().session.documents().is_empty()); + assert_eq!(h.state().ui.dialogs.len(), 1, "dialog stays open"); + } + + #[test] + fn double_click_clipboard_preset_creates_its_size_and_current_details() { + let mut h = harness(); + let mut f = fields(&h); + super::super::set_clipboard(&mut f, 37, 23); + apply_preset(&mut f, &("Other size", 100, 200, 300.0), &Default::default()); + f.extend(serde_json::json!({"mode":"gray","depth":8,"background":"white"}).as_object().unwrap().clone()); + set_fields(&mut h, f); + let at = preset_title_at(&h, super::super::CLIPBOARD); + click_at(&mut h, at); + assert_eq!(fields(&h)["__preset"], super::super::CLIPBOARD); + assert_eq!( + super::super::command_params(&fields(&h)), + serde_json::json!({"name":"Untitled-1","width":37,"height":23,"resolution":72.0, + "mode":"gray","depth":8,"background":"white"}) + ); + second_click_creates_once(&mut h, at); + assert_eq!(created(&h), (37, 23, 72.0)); + let doc = &h.state().session.active().unwrap().doc; + assert_eq!((doc.mode, doc.depth), (photocraft_doc::ColorMode::Grayscale, photocraft_doc::SampleType::U8)); + assert_pixel(&mut h, [1.0; 4]); + } + + #[test] + fn double_click_saved_preset_restores_all_settings_and_captured_background() { + let mut h = harness(); + h.state_mut() + .run( + "document.presets.save", + serde_json::json!({"name":"Saved proof","settings":{ + "width":48,"height":32,"resolution":254.0,"mode":"rgb","depth":32, + "background":"backgroundColor","backgroundColor":[0.125,0.375,0.625],"unit":"mm","resolutionUnit":"cm" + }}), + ) + .unwrap(); + h.state_mut().session.tools.background = [1.0, 0.0, 1.0, 1.0]; + let mut f = fields(&h); + f.insert("name".into(), serde_json::json!("Current document name")); + set_fields(&mut h, f); + h.get_by_label("Saved").click(); + h.run_steps(2); + let at = h.get_by_label("Saved proof").rect().center(); + click_at(&mut h, at); + assert_eq!(fields(&h)["__savedPreset"], "Saved proof"); + assert_eq!(fields(&h)["__unit"], "mm"); + assert_eq!(fields(&h)["__resUnit"], "cm"); + second_click_creates_once(&mut h, at); + assert_eq!(created(&h), (48, 32, 254.0)); + let doc = &h.state().session.active().unwrap().doc; + assert_eq!(doc.name, "Current document name"); + assert_eq!((doc.mode, doc.depth), (photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::F32)); + assert_pixel(&mut h, [0.125, 0.375, 0.625, 1.0]); + } + + #[test] + fn preset_cards_use_the_preset_resolution_preferences() { + let mut h = harness(); + h.state_mut().run("prefs.set", serde_json::json!({"path": "unitsAndRulers.printResolution", "value": 150.0})).unwrap(); + h.state_mut().run("prefs.set", serde_json::json!({"path": "unitsAndRulers.screenResolution", "value": 96.0})).unwrap(); + h.get_by_label("Photo").click(); + h.run_steps(2); + let at = preset_title_at(&h, "Landscape, 6 x 4"); + click_at(&mut h, at); + assert_eq!(fields(&h)["__unit"], "in"); + second_click_creates_once(&mut h, at); + assert_eq!(created(&h), (900, 600, 150.0), "6 x 4 in at 150 ppi"); + + h.state_mut().ui.open_dialog(DialogKind::NewDocument, UiState::new_document_fields()); + h.run_steps(2); + h.get_by_label("Web").click(); + h.run_steps(2); + let at = preset_title_at(&h, "Web Minimum"); + click_at(&mut h, at); + enter(&mut h); + assert_eq!(created(&h), (1024, 768, 96.0)); + } + + #[test] + fn arithmetic_dimensions_create_the_evaluated_size() { + let mut h = harness(); + type_into(&mut h, 0, "1920/2"); + type_into(&mut h, 1, "(100+50)*2"); + enter(&mut h); + assert_eq!(created(&h), (960, 300, 72.0)); + } + + #[test] + fn typed_size_then_enter_creates_that_size() { + let mut h = harness(); + type_into(&mut h, 0, "512"); + type_into(&mut h, 1, "512"); + let f = fields(&h); + assert_eq!((f["width"].as_u64(), f["height"].as_u64()), (Some(512), Some(512)), "whole pixels: {f:?}"); + enter(&mut h); + assert_eq!(created(&h), (512, 512, 72.0)); + } + + #[test] + fn typed_size_then_create_without_leaving_the_field_creates_that_size() { + let mut h = harness(); + type_into(&mut h, 0, "512"); + type_into(&mut h, 1, "300"); + // Still editing Height: click Create straight away. + let create = h.get_by_label("Create").rect(); + click_at(&mut h, create.center()); + assert_eq!(created(&h), (512, 300, 72.0)); + } + + #[test] + fn typing_over_a_preset_wins() { + let mut h = harness(); + let mut f = fields(&h); + let web = CATEGORIES.iter().find(|c| c.0 == "Web").unwrap().1.iter().find(|p| p.0 == "Web Minimum").unwrap(); + apply_preset(&mut f, web, &Default::default()); + set_fields(&mut h, f); + type_into(&mut h, 0, "512"); + type_into(&mut h, 1, "512"); + assert!(fields(&h).get("__preset").is_none(), "typing deselects the preset"); + enter(&mut h); + assert_eq!(created(&h), (512, 512, 72.0)); + } + + #[test] + fn the_clipboard_card_is_first_and_creates_the_clipboard_size() { + let mut h = harness(); + let mut f = fields(&h); + super::super::set_clipboard(&mut f, 640, 360); + set_fields(&mut h, f); + // Recent lists the Clipboard card first: three presets instead of two. + assert!(h.query_by_label_contains("BLANK DOCUMENT PRESETS (3)").is_some()); + let heading = h.get_by_label_contains("BLANK DOCUMENT PRESETS").rect(); + // Pick the second card, then the first (Clipboard) again. + click_at(&mut h, heading.left_bottom() + egui::vec2(80.0 + 172.0, 60.0)); + assert_eq!(fields(&h).get("__preset").and_then(|v| v.as_str()), Some("Default PhotoCraft Size")); + click_at(&mut h, heading.left_bottom() + egui::vec2(80.0, 60.0)); + assert_eq!(fields(&h).get("__preset").and_then(|v| v.as_str()), Some(super::super::CLIPBOARD)); + enter(&mut h); + assert_eq!(created(&h), (640, 360, 72.0)); + } + + #[test] + fn clicking_a_preset_card_after_typing_sets_its_size() { + let mut h = harness(); + type_into(&mut h, 0, "512"); + h.get_by_label("Photo").click(); + h.run_steps(2); + // The first card ("Landscape, 6 x 4") sits under the presets heading. + let heading = h.get_by_label_contains("BLANK DOCUMENT PRESETS").rect(); + click_at(&mut h, heading.left_bottom() + egui::vec2(80.0, 60.0)); + assert_eq!(fields(&h).get("__preset").and_then(|v| v.as_str()), Some("Landscape, 6 x 4")); + enter(&mut h); + assert_eq!(created(&h), (1800, 1200, 300.0)); + } + + #[test] + fn typed_size_in_inches_converts_at_the_resolution() { + let mut h = harness(); + type_into(&mut h, 2, "300"); + let mut f = fields(&h); + f.insert("__unit".into(), serde_json::json!("in")); + set_fields(&mut h, f); + type_into(&mut h, 0, "2"); + type_into(&mut h, 1, "1.5"); + enter(&mut h); + assert_eq!(created(&h), (600, 450, 300.0)); + } + + /// #1147: typed digit by digit, millimetres used to be rewritten after each keystroke + /// (`8` became `8.1`), so 841 never arrived. + #[test] + fn typed_size_in_millimetres_keeps_every_digit() { + let mut h = harness(); + let mut f = fields(&h); + f.insert("__unit".into(), serde_json::json!("mm")); + set_fields(&mut h, f); + type_into(&mut h, 0, "841"); + type_into(&mut h, 1, "1189"); + enter(&mut h); + assert_eq!(created(&h), (2384, 3370, 72.0)); + } + + #[test] + fn changing_units_keeps_the_typed_pixel_size() { + let mut h = harness(); + type_into(&mut h, 0, "512"); + type_into(&mut h, 1, "512"); + for unit in ["in", "cm", "mm", "pt", "pica", "px"] { + let mut f = fields(&h); + f.insert("__unit".into(), serde_json::json!(unit)); + set_fields(&mut h, f); + } + enter(&mut h); + assert_eq!(created(&h), (512, 512, 72.0)); + } + + #[test] + fn orientation_swap_keeps_whole_pixels() { + let mut h = harness(); + type_into(&mut h, 0, "512"); + type_into(&mut h, 1, "256"); + // The Portrait icon button follows the "Orientation" label (icons have tooltips only). + let label = h.get_by_label("Orientation").rect(); + let gap = h.ctx.global_style().spacing.item_spacing.x; + click_at(&mut h, egui::pos2(label.right() + gap + 12.0, label.center().y)); + enter(&mut h); + assert_eq!(created(&h), (256, 512, 72.0)); + } + + /// #4668: once an orientation is picked, the presets turn to it, on the cards and when applied. + #[test] + fn picked_orientation_turns_the_presets() { + let mut h = harness(); + h.get_by_label("Print").click(); + h.run_steps(2); + // The default 1920 x 1080 is already landscape: Landscape swaps nothing, but is picked. + let label = h.get_by_label("Orientation").rect(); + let gap = h.ctx.global_style().spacing.item_spacing.x; + click_at(&mut h, egui::pos2(label.right() + gap + 24.0 + gap + 12.0, label.center().y)); + assert_eq!((fields(&h)["width"].as_u64(), fields(&h)["height"].as_u64()), (Some(1920), Some(1080))); + let _ = preset_title_at(&h, "11.7 x 8.3 in @ 300 ppi"); + let at = preset_title_at(&h, "A4"); + click_at(&mut h, at); + enter(&mut h); + assert_eq!(created(&h), (3508, 2480, 300.0)); + } + + /// #4668: a physical unit picked for Width/Height is the one print presets show and keep. + #[test] + fn picked_physical_unit_is_the_print_presets_unit() { + let mut h = harness(); + let mut f = fields(&h); + f.insert("__unit".into(), serde_json::json!("mm")); + set_fields(&mut h, f); + h.get_by_label("Print").click(); + h.run_steps(2); + let _ = preset_title_at(&h, "210 x 297 mm @ 300 ppi"); + let at = preset_title_at(&h, "A4"); + click_at(&mut h, at); + assert_eq!(fields(&h)["__unit"], "mm"); + // Screen presets stay in pixels. + h.get_by_label("Web").click(); + h.run_steps(2); + let _ = preset_title_at(&h, "1024 x 768 px @ 72 ppi"); + enter(&mut h); + assert_eq!(created(&h), (2480, 3508, 300.0)); + } + + #[test] + fn hovering_preset_tabs_shows_pointing_hand_not_text_cursor() { + let mut h = harness(); + for tab in ["Recent", "Saved", "Photo", "Print", "Art & Illustration", "Web", "Mobile", "Film & Video"] { + let rect = h.get_by_label(tab).rect(); + h.hover_at(rect.center()); + h.run_steps(2); + assert_eq!( + h.output().platform_output.cursor_icon, + egui::CursorIcon::PointingHand, + "hovering preset tab {tab:?} must show PointingHand instead of text caret" + ); + } + } +} From 91af26f868f96bc3b4910e90c78f3f419b013866 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:29 +0000 Subject: [PATCH 097/259] refactor(ui-egui): move layer_menu_ui.rs tests to layer_menu_ui/tests.rs --- crates/ui-egui/src/layer_menu_ui.rs | 559 +--------------------- crates/ui-egui/src/layer_menu_ui/tests.rs | 556 +++++++++++++++++++++ 2 files changed, 557 insertions(+), 558 deletions(-) create mode 100644 crates/ui-egui/src/layer_menu_ui/tests.rs diff --git a/crates/ui-egui/src/layer_menu_ui.rs b/crates/ui-egui/src/layer_menu_ui.rs index 0ea4db41ea..7ad844027a 100644 --- a/crates/ui-egui/src/layer_menu_ui.rs +++ b/crates/ui-egui/src/layer_menu_ui.rs @@ -317,561 +317,4 @@ fn color_button(ui: &mut egui::Ui, color: LabelColor, checked: bool) -> egui::Re mod color_tests; #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn mask_toggle_label_follows_history_and_selected_layer() { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - let mut app = crate::PhotocraftApp::new(s, Default::default()); - let toggle = "layer.layerMask.enabled"; - let check = |app: &crate::PhotocraftApp, label: Option<&str>| { - let st = app.session.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); - let entry = entries(l, false, st.doc.selection.is_some()).into_iter().flatten().find(|e| e.1 == toggle); - assert_eq!(entry.map(|e| e.0), label); - // A selection has no single mask to toggle: its menu never offers the item. - assert!(entries(l, true, st.doc.selection.is_some()).into_iter().flatten().all(|e| e.1 != toggle)); - let item = crate::menus::menu_items(app).into_iter().find(|i| i.id == toggle).unwrap(); - assert_eq!(item.enabled, label.is_some()); - assert_eq!(item.label, label.unwrap_or("Enable Layer Mask")); - for lang in [crate::i18n::Lang::EN, crate::i18n::Lang::from_pref("fr")] { - let layout = crate::native_menu::photocraft_layout(&crate::menus::menu_items(app), lang, lang.code()); - let native = layout.bar.find(toggle).unwrap(); - assert_eq!(native.label, crate::i18n::tr(lang, &item.label)); - assert_eq!(native.enabled, item.enabled); - } - }; - check(&app, None); - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - let masked = app.session.active().unwrap().active_layer.unwrap(); - check(&app, Some("Disable Layer Mask")); - app.run(toggle, json!({})).unwrap(); - check(&app, Some("Enable Layer Mask")); - app.run("edit.undo", json!({})).unwrap(); - check(&app, Some("Disable Layer Mask")); - app.run("edit.redo", json!({})).unwrap(); - check(&app, Some("Enable Layer Mask")); - app.run("layer.new.layer", json!({})).unwrap(); - check(&app, None); - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - check(&app, Some("Disable Layer Mask")); - app.run("layer.select", json!({"layer": masked.0, "mode": "add"})).unwrap(); - check(&app, Some("Enable Layer Mask")); - app.run("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap(); - check(&app, Some("Enable Layer Mask")); - app.session.active_mut().unwrap().active_layer = None; - assert!(!crate::menus::is_enabled(&app, toggle)); - let empty = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - assert!(!crate::menus::is_enabled(&empty, toggle)); - } - - #[test] - fn mask_toggle_context_menu_follows_the_clicked_layer_and_existing_translations() { - use egui_kittest::{Harness, kittest::Queryable}; - - for language in ["en", "fr"] { - let lang = crate::i18n::Lang::from_pref(language); - let _language = crate::i18n::language_scope(lang); - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - let clicked = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - let other = s.active().unwrap().active_layer.unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("layer.layerMask.enabled", json!({})).unwrap(); - let app = crate::PhotocraftApp::new(s, Default::default()); - // `other` stays the active layer with its mask disabled; the menu is opened over `clicked`, - // whose mask is enabled, and selects it first (a single-layer menu). - let mut h = Harness::builder().with_size(egui::vec2(400.0, 900.0)).build_ui_state( - move |ui, app| { - let st = app.session.active().unwrap(); - let l = st.doc.layer(clicked).unwrap().clone(); - let mut actions = Vec::new(); - show(app, ui, &l, false, &mut actions); - for (id, params) in actions { - crate::menus::invoke(app, ui.ctx(), &id, params).unwrap(); - } - }, - app, - ); - h.run_steps(3); - let enabled_label = crate::i18n::tr(lang, "Enable Layer Mask"); - let disabled_label = crate::i18n::tr(lang, "Disable Layer Mask"); - // The label follows the mask of the clicked layer, not of the active one. - assert!(h.query_by_label(enabled_label).is_none()); - h.get_by_label(disabled_label).click(); - h.run_steps(3); - assert_eq!(h.state().session.active().unwrap().active_layer, Some(clicked)); - assert!(!h.state().session.active().unwrap().doc.layer(clicked).unwrap().mask.as_ref().unwrap().enabled); - assert!(!h.state().session.active().unwrap().doc.layer(other).unwrap().mask.as_ref().unwrap().enabled); - h.get_by_label(enabled_label); - } - } - - /// With several layers selected there is no single mask to toggle, apply or delete: the menu - /// offers Add Layer Mask only, whatever the clicked layer has, and does not hit the active layer. - #[test] - fn multi_selection_menu_has_no_per_layer_mask_items() { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - let st = s.active().unwrap(); - let masked = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); - let ids = entries(&masked, true, false).into_iter().flatten().map(|e| e.1).collect::>(); - assert!(ids.contains(&"layer.layerMask.revealAll")); - for single in ["layer.layerMask.enabled", "layer.layerMask.apply", "layer.layerMask.delete"] { - assert!(!ids.contains(&single), "{single} acts on one layer, not on a selection"); - } - } - - #[test] - fn smart_object_context_menu_edits_the_clicked_layer() { - use crate::PhotocraftApp; - use egui::{Event, Modifiers, PointerButton, Pos2, 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); - } - - for ppp in [1.0, 2.0] { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 640, "height": 480})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Smart source"})).unwrap(); - s.execute("paint.stroke", json!({"points": [[100, 100]], "size": 20})).unwrap(); - let smart = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.new.layer", json!({"name": "Other active layer"})).unwrap(); - let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_pixels_per_point(ppp).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 row = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == smart).expect("layer row drawn").row; - // Top-level Pro row: 6 pt padding, 28 pt eye column, 24 pt layer thumbnail. - let at = pos2(row.left() + 6.0 + 28.0 + 12.0, row.center().y); - click(&mut h, at, PointerButton::Secondary); - let at = h.get_by_label("Edit Contents").rect().center(); - click(&mut h, at, PointerButton::Primary); - assert_eq!(h.state().session.active_index(), Some(1), "@{ppp}x: contents tab opens"); - assert!(h.state().session.is_enabled("layer.smartObjects.saveContents")); - assert!(h.state().session.active().unwrap().doc.walk().iter().any(|(_, _, l)| l.name == "Smart source")); - h.state_mut().session.set_active(0); - assert_eq!(h.state().session.active().unwrap().active_layer, Some(photocraft_doc::LayerId(smart))); - } - } - - /// #4575: right-clicking a layer-mask thumbnail opens Photoshop's mask menu, not the layer - /// menu, and its selection items load the clicked layer's mask (not the active layer's). - #[test] - fn mask_thumbnail_context_menu_acts_on_the_clicked_mask() { - 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(); - s.execute("layer.new.layer", json!({"name": "Masked"})).unwrap(); - s.execute("select.rect", json!({"x": 60, "y": 0, "width": 40, "height": 60})).unwrap(); - s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); - let masked = s.active().unwrap().active_layer.unwrap(); - // Another layer is active, and the selection doesn't overlap the mask. - 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 (thumbs, _) = crate::mask_thumbs_ui::recorded(&h.ctx, masked.0).expect("mask thumbnail drawn"); - let at = thumbs.iter().find(|(k, _)| *k == crate::mask_thumbs_ui::MaskKind::Pixel).unwrap().1.center(); - click(&mut h, at, PointerButton::Secondary); - assert!(h.query_by_label("Blending Options…").is_none(), "the mask menu, not the layer menu"); - for item in - ["Disable Layer Mask", "Delete Layer Mask", "Apply Layer Mask", "Subtract Mask from Selection", "Intersect Mask with Selection", "Select and Mask…"] - { - h.get_by_label(item); - } - let at = h.get_by_label("Add Mask to Selection").rect().center(); - click(&mut h, at, PointerButton::Primary); - let st = h.state().session.active().unwrap(); - assert_eq!(st.active_layer, Some(masked)); - let sel = st.doc.selection.as_ref().expect("a selection"); - assert!(sel.sample_channel(10, 30, 0) > 0.99, "the selection is kept"); - assert!(sel.sample_channel(80, 30, 0) > 0.99, "the clicked layer's mask is added"); - assert!(sel.sample_channel(40, 30, 0) < 0.01, "nothing else is selected"); - // Mask Options…: Layer Mask Display Options (the rubylith's colour and opacity). - let (thumbs, _) = crate::mask_thumbs_ui::recorded(&h.ctx, masked.0).expect("mask thumbnail drawn"); - let at = thumbs.iter().find(|(k, _)| *k == crate::mask_thumbs_ui::MaskKind::Pixel).unwrap().1.center(); - click(&mut h, at, PointerButton::Secondary); - let at = h.get_by_label("Mask Options…").rect().center(); - click(&mut h, at, PointerButton::Primary); - let d = h.state().ui.dialogs.last().expect("Mask Options… opens a dialog"); - assert!(crate::channel_options_ui::owns(&d.fields) && d.fields["channel"] == json!("mask"), "{:?}", d.fields); - assert_eq!(d.fields["__label"], json!("Layer Mask Display Options…")); - } - - #[test] - fn a_long_layer_menu_stays_inside_a_short_window_and_scrolls() { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 32, "height": 24})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap(); - let app = crate::PhotocraftApp::new(s, crate::Services::default()); - let layer = { - let st = app.session.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().clone() - }; - let ctx = egui::Context::default(); - crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 300.0)); - let id = egui::Id::unique("layer-menu-probe"); - let mut content = 0.0; - for _ in 0..4 { - let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| { - // Opened low in the window, like a right-click on a bottom Layers row. - egui::Area::new(id).order(egui::Order::Foreground).default_pos(egui::pos2(300.0, 250.0)).show(ui.ctx(), |ui| { - egui::Frame::menu(ui.style()).show(ui, |ui| { - let start = ui.next_widget_position().y; - show(&app, ui, &layer, false, &mut Vec::new()); - content = ui.min_rect().bottom() - start; - }); - }); - }); - out.textures_delta.clear(); - } - let rect = ctx.memory(|m| m.area_rect(id)).expect("the menu was shown"); - assert!(screen.contains_rect(rect), "the menu moves up and stays inside the window: {rect:?}"); - assert!(rect.height() < screen.height(), "{rect:?}"); - let rows = entries(&layer, false, false).iter().flatten().count(); - assert!(rows >= 15, "Photoshop's layer menu is long: {rows} rows"); - assert!(content < rect.height() + 1.0, "the rows scroll inside the menu instead of running off the window"); - } - - #[test] - fn edit_contents_is_available_only_for_smart_objects() { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 32, "height": 24})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Source"})).unwrap(); - let layer = |s: &photocraft_engine::Session| { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().clone() - }; - assert!(!entries(&layer(&s), false, false).iter().flatten().any(|e| e.1 == "layer.smartObjects.editContents")); - s.execute("paint.stroke", json!({"points": [[12, 12]], "size": 8})).unwrap(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let ids: Vec<_> = entries(&layer(&s), false, false).into_iter().flatten().map(|e| e.1).collect(); - let edit = ids.iter().position(|id| *id == "layer.smartObjects.editContents").expect("Edit Contents entry"); - assert_eq!( - ids[edit + 1..edit + 5], - ["layer.smartObjects.replaceContents", "layer.smartObjects.relinkToFile", "layer.smartObjects.convertToLayers", "layer.rasterize.smartObject"] - ); - } - - /// Right-clicking inside a multi-layer selection offers one Rasterize item for the whole - /// selection, whatever kind the clicked layer is, and no single-layer Smart Object items. - #[test] - fn multi_selection_menu_rasterizes_the_selection() { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 32, "height": 24})).unwrap(); - s.execute("layer.new.layer", json!({"name": "Source"})).unwrap(); - s.execute("paint.stroke", json!({"points": [[12, 12]], "size": 8})).unwrap(); - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let st = s.active().unwrap(); - let smart = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); - let ids = |multi| entries(&smart, multi, false).into_iter().flatten().map(|e| e.1).collect::>(); - assert!(ids(false).contains(&"layer.smartObjects.editContents"), "a single smart object keeps its items"); - let multi = ids(true); - assert!(multi.contains(&"layer.rasterize.layer")); - for single in [ - "layer.rasterize.smartObject", - "layer.rasterize.shape", - "layer.smartObjects.editContents", - "layer.smartObjects.replaceContents", - "layer.smartObjects.relinkToFile", - "layer.smartObjects.convertToLayers", - ] { - assert!(!multi.contains(&single), "{single} acts on one layer, not on a selection"); - } - let label = entries(&smart, true, false).into_iter().flatten().find(|e| e.1 == "layer.rasterize.layer").unwrap().0; - assert_eq!(label, "Rasterize Layers"); - } - - fn click(h: &mut egui_kittest::Harness<'_, crate::PhotocraftApp>, at: egui::Pos2, button: egui::PointerButton) { - h.hover_at(at); - h.step(); - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: at, button, pressed, modifiers: egui::Modifiers::NONE }); - h.step(); - } - h.run_steps(3); - } - - /// A type layer, an ellipse and a rectangle; the type layer and the ellipse are selected (the - /// ellipse active), the rectangle stays out. The Layers menu is opened by right-clicking the - /// type row, which is selected but not the active layer. Returns `[type, ellipse, rectangle]`. - fn open_multi_selection_menu() -> (egui_kittest::Harness<'static, crate::PhotocraftApp>, [u64; 3]) { - use crate::PhotocraftApp; - use egui::{PointerButton, pos2, vec2}; - - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 640, "height": 480})).unwrap(); - let text = s.execute("type.create", json!({"text": "Hi", "size": 24, "x": 20, "y": 60})).unwrap()["layer"].as_u64().unwrap(); - let shape = s.execute("shape.create", json!({"kind": "ellipse", "rect": [100, 100, 200, 160]})).unwrap()["layer"].as_u64().unwrap(); - let other = s.execute("shape.create", json!({"kind": "rect", "rect": [300, 100, 380, 160]})).unwrap()["layer"].as_u64().unwrap(); - s.execute("layer.select", json!({"layer": text})).unwrap(); - s.execute("layer.select", json!({"layer": shape, "mode": "add"})).unwrap(); - let mut h = egui_kittest::Harness::builder() - .with_size(vec2(1440.0, 900.0)) - .with_pixels_per_point(1.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 row = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == text).expect("layer row drawn").row; - click(&mut h, pos2(row.left() + 6.0 + 28.0 + 12.0, row.center().y), PointerButton::Secondary); - (h, [text, shape, other]) - } - - /// The reported bug: right-click a layer inside a multi-layer selection, choose Rasterize, and - /// only the clicked (or active) layer was converted. - #[test] - fn rasterize_from_the_menu_converts_every_selected_layer() { - use egui_kittest::kittest::Queryable; - let (mut h, [text, shape, other]) = open_multi_selection_menu(); - let at = h.get_by_label("Rasterize Layers").rect().center(); - click(&mut h, at, egui::PointerButton::Primary); - let doc = &h.state().session.active().unwrap().doc; - let raster = |id: u64| matches!(doc.layer(photocraft_doc::LayerId(id)).unwrap().content, photocraft_doc::LayerContent::Raster(_)); - assert!(raster(text) && raster(shape), "both selected layers are rasterized"); - assert!(!raster(other), "an unselected layer is left alone"); - assert_eq!(h.state().session.active().unwrap().selected_layers().len(), 2, "the selection survives"); - } - - /// Items with no single target are greyed for a multi-layer selection (they used to run on - /// whichever layer happened to be active, not the one right-clicked); the ones that act on the - /// whole selection, including adding a mask, stay available. - #[test] - fn multi_selection_menu_greys_what_acts_on_one_layer() { - use egui_kittest::kittest::{NodeT, Queryable}; - let (h, _) = open_multi_selection_menu(); - for label in ["Blending Options…", "Copy Layer Style"] { - assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label} works on one layer only"); - } - for label in [ - "Quick Export As PNG", - "Export As…", - "Add Layer Mask", - "Duplicate Layers…", - "Delete Layers", - "Convert to Smart Object", - "Rasterize Layers", - "Link Layers", - "Merge Layers", - ] { - assert!(!h.get_by_label(label).accesskit_node().is_disabled(), "{label} acts on the selection"); - } - // Greyed here only for lack of something to act on: no style on the clipboard, no style to clear. - for label in ["Paste Layer Style", "Clear Layer Style"] { - assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label} has nothing to do here"); - } - // Whatever the clicked layer is, the menu has the same shape: no per-layer mask or Smart Object items. - for label in ["Disable Layer Mask", "Apply Layer Mask", "Delete Layer Mask", "Edit Contents", "Convert to Layers"] { - assert!(h.query_by_label(label).is_none(), "{label} is not offered for several layers"); - } - } - - /// Every entry of the multi-layer menu is either known to act on the selection or greyed by - /// [`single_layer_only`]; a new single-layer command added to the menu must be classified. - #[test] - fn single_layer_only_covers_the_per_layer_commands() { - for id in [ - "layer.layerStyle.blendingOptions", - "layer.layerStyle.copyLayerStyle", - "layer.layerMask.enabled", - "layer.layerMask.apply", - "layer.layerMask.delete", - ] { - assert!(single_layer_only(id), "{id}"); - } - for id in [ - "layer.quickExportAsPng", - "layer.exportAs", - "layer.duplicate", - "layer.delete", - "layer.rasterize.layer", - "layer.smartObjects.convertToSmartObject", - "layer.createClippingMask", - "layer.linkLayers", - "layer.mergeLayers", - "layer.layerMask.revealAll", - "layer.layerMask.hideSelection", - "layer.layerStyle.pasteLayerStyle", - "layer.layerStyle.clear", - ] { - assert!(!single_layer_only(id), "{id}"); - } - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - let st = s.active().unwrap(); - let masked = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); - let ids: Vec<_> = entries(&masked, true, false).into_iter().flatten().map(|e| e.1).collect(); - assert!(ids.contains(&"layer.layerMask.revealAll") && !ids.contains(&"layer.layerMask.apply"), "one stable mask item for several layers"); - } - - #[test] - fn entries_follow_layer_state() { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - let st = s.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); - let ids: Vec<&str> = entries(&l, false, false).into_iter().flatten().map(|e| e.1).collect(); - assert_eq!(ids.first(), Some(&"layer.layerStyle.blendingOptions")); - assert!(ids.contains(&"layer.mergeDown") && !ids.contains(&"layer.mergeLayers")); - assert!(ids.contains(&"layer.layerMask.revealAll")); - let ids: Vec<&str> = entries(&l, false, true).into_iter().flatten().map(|e| e.1).collect(); - assert!(ids.contains(&"layer.layerMask.revealSelection") && !ids.contains(&"layer.layerMask.revealAll")); - let ids: Vec<&str> = entries(&l, true, false).into_iter().flatten().map(|e| e.1).collect(); - assert!(ids.contains(&"layer.mergeLayers")); - } - - /// #3832: a group's right-click menu and the Layer menu offer Photoshop's Merge Group, which - /// merges the group itself (not into the layer below), and it is enabled. - #[test] - fn a_group_offers_merge_group() { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("layer.groupLayers", json!({"name": "G"})).unwrap(); - let st = s.active().unwrap(); - let g = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); - let e: Vec<(&str, &str)> = entries(&g, false, false).into_iter().flatten().collect(); - assert!(e.contains(&("Merge Group", "layer.mergeGroup")), "{e:?}"); - assert!(!e.iter().any(|x| x.0 == "Merge Down")); - let mut app = crate::PhotocraftApp::new(s, Default::default()); - app.sync_views(); - let items = crate::menus::menu_items(&app); - let item = items.iter().find(|i| i.id == "layer.mergeLayers").unwrap(); - assert_eq!(item.label, "Merge Group"); - assert!(item.enabled, "Merge Group runs on a group"); - // A plain layer keeps Merge Layers. - app.run("layer.new.layer", json!({})).unwrap(); - let items = crate::menus::menu_items(&app); - assert_eq!(items.iter().find(|i| i.id == "layer.mergeLayers").unwrap().label, "Merge Layers"); - } - - #[test] - fn add_mask_uses_the_selection() { - assert_eq!(add_mask_command(false, false), "layer.layerMask.revealAll"); - assert_eq!(add_mask_command(false, true), "layer.layerMask.hideAll"); - assert_eq!(add_mask_command(true, true), "layer.layerMask.hideSelection"); - // With a selection the new mask is the selection: inside revealed, outside hidden. - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 10})).unwrap(); - s.execute(add_mask_command(true, false), json!({})).unwrap(); - let st = s.active().unwrap(); - let mask = &st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface; - assert!(mask.pixel(1, 5)[0] > 0.99 && mask.pixel(8, 5)[0] < 0.01); - } - - /// #2075: clicking the mask button again (with or without ⌥) used to replace the layer's - /// mask, discarding what was painted into it. Like Photoshop, it now adds a vector mask, and - /// does nothing once the layer has both. - #[test] - fn mask_button_never_replaces_a_mask() { - for alt in [false, true] { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); - s.execute("layer.new.layer", json!({})).unwrap(); - let layer = |s: &photocraft_engine::Session| { - let st = s.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().clone() - }; - let first = mask_button_command(Some(&layer(&s)), false, alt).unwrap(); - assert_eq!(first, if alt { "layer.layerMask.hideAll" } else { "layer.layerMask.revealAll" }); - s.execute(first, json!({})).unwrap(); - // Paint a stroke into the mask. - s.edit("paint mask", |doc, active| { - let id = (*active).ok_or(photocraft_engine::EngineError::NoDocument)?; - let m = doc.layer_mut(id).and_then(|l| l.mask.as_mut()).ok_or(photocraft_engine::EngineError::NoDocument)?; - m.surface.fill_rect(photocraft_geom::Rect::new(2, 2, 5, 5), &[0.5]); - Ok(()) - }) - .unwrap(); - let painted = layer(&s).mask.unwrap().surface.pixel(3, 3)[0]; - assert!((painted - 0.5).abs() < 0.01); - // Second click: a vector mask (⌥ hides all), the layer mask is untouched. - let second = mask_button_command(Some(&layer(&s)), false, alt).unwrap(); - assert_eq!(second, if alt { "layer.vectorMask.hideAll" } else { "layer.vectorMask.revealAll" }); - s.execute(second, json!({})).unwrap(); - let l = layer(&s); - assert!(l.vector_mask.is_some(), "alt={alt}"); - let mask = l.mask.as_ref().unwrap(); - assert!((mask.surface.pixel(3, 3)[0] - painted).abs() < 1e-6, "alt={alt}: the painted mask was replaced"); - // Third click: nothing left to add. - assert_eq!(mask_button_command(Some(&l), false, alt), None); - assert_eq!(mask_button_command(Some(&l), true, alt), None); - } - // No layer: nothing to do. - assert_eq!(mask_button_command(None, false, false), None); - // A shape layer's path is already its vector mask: after the layer mask, nothing more. - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); - s.execute("shape.create", json!({"kind": "rect", "rect": [0, 0, 5, 5]})).unwrap(); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - let st = s.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); - assert_eq!(mask_button_command(Some(l), false, false), None); - } - - #[test] - fn every_entry_is_a_known_command() { - let mut s = photocraft_engine::Session::new(); - s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); - let l = s.active().unwrap().doc.layers[0].clone(); - for (_, id) in entries(&l, false, true).into_iter().chain(entries(&l, false, false)).chain(entries(&l, true, false)).chain(effects_entries()).flatten() - { - assert!(crate::menu_catalog::CATALOG.iter().any(|m| m.3 == id) || photocraft_engine::commands::find(id).is_some(), "{id}"); - } - } -} +mod tests; diff --git a/crates/ui-egui/src/layer_menu_ui/tests.rs b/crates/ui-egui/src/layer_menu_ui/tests.rs new file mode 100644 index 0000000000..948a4a373f --- /dev/null +++ b/crates/ui-egui/src/layer_menu_ui/tests.rs @@ -0,0 +1,556 @@ +use super::*; + +#[test] +fn mask_toggle_label_follows_history_and_selected_layer() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let mut app = crate::PhotocraftApp::new(s, Default::default()); + let toggle = "layer.layerMask.enabled"; + let check = |app: &crate::PhotocraftApp, label: Option<&str>| { + let st = app.session.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + let entry = entries(l, false, st.doc.selection.is_some()).into_iter().flatten().find(|e| e.1 == toggle); + assert_eq!(entry.map(|e| e.0), label); + // A selection has no single mask to toggle: its menu never offers the item. + assert!(entries(l, true, st.doc.selection.is_some()).into_iter().flatten().all(|e| e.1 != toggle)); + let item = crate::menus::menu_items(app).into_iter().find(|i| i.id == toggle).unwrap(); + assert_eq!(item.enabled, label.is_some()); + assert_eq!(item.label, label.unwrap_or("Enable Layer Mask")); + for lang in [crate::i18n::Lang::EN, crate::i18n::Lang::from_pref("fr")] { + let layout = crate::native_menu::photocraft_layout(&crate::menus::menu_items(app), lang, lang.code()); + let native = layout.bar.find(toggle).unwrap(); + assert_eq!(native.label, crate::i18n::tr(lang, &item.label)); + assert_eq!(native.enabled, item.enabled); + } + }; + check(&app, None); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + let masked = app.session.active().unwrap().active_layer.unwrap(); + check(&app, Some("Disable Layer Mask")); + app.run(toggle, json!({})).unwrap(); + check(&app, Some("Enable Layer Mask")); + app.run("edit.undo", json!({})).unwrap(); + check(&app, Some("Disable Layer Mask")); + app.run("edit.redo", json!({})).unwrap(); + check(&app, Some("Enable Layer Mask")); + app.run("layer.new.layer", json!({})).unwrap(); + check(&app, None); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + check(&app, Some("Disable Layer Mask")); + app.run("layer.select", json!({"layer": masked.0, "mode": "add"})).unwrap(); + check(&app, Some("Enable Layer Mask")); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap(); + check(&app, Some("Enable Layer Mask")); + app.session.active_mut().unwrap().active_layer = None; + assert!(!crate::menus::is_enabled(&app, toggle)); + let empty = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + assert!(!crate::menus::is_enabled(&empty, toggle)); +} + +#[test] +fn mask_toggle_context_menu_follows_the_clicked_layer_and_existing_translations() { + use egui_kittest::{Harness, kittest::Queryable}; + + for language in ["en", "fr"] { + let lang = crate::i18n::Lang::from_pref(language); + let _language = crate::i18n::language_scope(lang); + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + let clicked = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let other = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("layer.layerMask.enabled", json!({})).unwrap(); + let app = crate::PhotocraftApp::new(s, Default::default()); + // `other` stays the active layer with its mask disabled; the menu is opened over `clicked`, + // whose mask is enabled, and selects it first (a single-layer menu). + let mut h = Harness::builder().with_size(egui::vec2(400.0, 900.0)).build_ui_state( + move |ui, app| { + let st = app.session.active().unwrap(); + let l = st.doc.layer(clicked).unwrap().clone(); + let mut actions = Vec::new(); + show(app, ui, &l, false, &mut actions); + for (id, params) in actions { + crate::menus::invoke(app, ui.ctx(), &id, params).unwrap(); + } + }, + app, + ); + h.run_steps(3); + let enabled_label = crate::i18n::tr(lang, "Enable Layer Mask"); + let disabled_label = crate::i18n::tr(lang, "Disable Layer Mask"); + // The label follows the mask of the clicked layer, not of the active one. + assert!(h.query_by_label(enabled_label).is_none()); + h.get_by_label(disabled_label).click(); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().active_layer, Some(clicked)); + assert!(!h.state().session.active().unwrap().doc.layer(clicked).unwrap().mask.as_ref().unwrap().enabled); + assert!(!h.state().session.active().unwrap().doc.layer(other).unwrap().mask.as_ref().unwrap().enabled); + h.get_by_label(enabled_label); + } +} + +/// With several layers selected there is no single mask to toggle, apply or delete: the menu +/// offers Add Layer Mask only, whatever the clicked layer has, and does not hit the active layer. +#[test] +fn multi_selection_menu_has_no_per_layer_mask_items() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + let st = s.active().unwrap(); + let masked = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + let ids = entries(&masked, true, false).into_iter().flatten().map(|e| e.1).collect::>(); + assert!(ids.contains(&"layer.layerMask.revealAll")); + for single in ["layer.layerMask.enabled", "layer.layerMask.apply", "layer.layerMask.delete"] { + assert!(!ids.contains(&single), "{single} acts on one layer, not on a selection"); + } +} + +#[test] +fn smart_object_context_menu_edits_the_clicked_layer() { + use crate::PhotocraftApp; + use egui::{Event, Modifiers, PointerButton, Pos2, 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); + } + + for ppp in [1.0, 2.0] { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 640, "height": 480})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Smart source"})).unwrap(); + s.execute("paint.stroke", json!({"points": [[100, 100]], "size": 20})).unwrap(); + let smart = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.new.layer", json!({"name": "Other active layer"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_pixels_per_point(ppp).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 row = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == smart).expect("layer row drawn").row; + // Top-level Pro row: 6 pt padding, 28 pt eye column, 24 pt layer thumbnail. + let at = pos2(row.left() + 6.0 + 28.0 + 12.0, row.center().y); + click(&mut h, at, PointerButton::Secondary); + let at = h.get_by_label("Edit Contents").rect().center(); + click(&mut h, at, PointerButton::Primary); + assert_eq!(h.state().session.active_index(), Some(1), "@{ppp}x: contents tab opens"); + assert!(h.state().session.is_enabled("layer.smartObjects.saveContents")); + assert!(h.state().session.active().unwrap().doc.walk().iter().any(|(_, _, l)| l.name == "Smart source")); + h.state_mut().session.set_active(0); + assert_eq!(h.state().session.active().unwrap().active_layer, Some(photocraft_doc::LayerId(smart))); + } +} + +/// #4575: right-clicking a layer-mask thumbnail opens Photoshop's mask menu, not the layer +/// menu, and its selection items load the clicked layer's mask (not the active layer's). +#[test] +fn mask_thumbnail_context_menu_acts_on_the_clicked_mask() { + 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(); + s.execute("layer.new.layer", json!({"name": "Masked"})).unwrap(); + s.execute("select.rect", json!({"x": 60, "y": 0, "width": 40, "height": 60})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + let masked = s.active().unwrap().active_layer.unwrap(); + // Another layer is active, and the selection doesn't overlap the mask. + 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 (thumbs, _) = crate::mask_thumbs_ui::recorded(&h.ctx, masked.0).expect("mask thumbnail drawn"); + let at = thumbs.iter().find(|(k, _)| *k == crate::mask_thumbs_ui::MaskKind::Pixel).unwrap().1.center(); + click(&mut h, at, PointerButton::Secondary); + assert!(h.query_by_label("Blending Options…").is_none(), "the mask menu, not the layer menu"); + for item in + ["Disable Layer Mask", "Delete Layer Mask", "Apply Layer Mask", "Subtract Mask from Selection", "Intersect Mask with Selection", "Select and Mask…"] + { + h.get_by_label(item); + } + let at = h.get_by_label("Add Mask to Selection").rect().center(); + click(&mut h, at, PointerButton::Primary); + let st = h.state().session.active().unwrap(); + assert_eq!(st.active_layer, Some(masked)); + let sel = st.doc.selection.as_ref().expect("a selection"); + assert!(sel.sample_channel(10, 30, 0) > 0.99, "the selection is kept"); + assert!(sel.sample_channel(80, 30, 0) > 0.99, "the clicked layer's mask is added"); + assert!(sel.sample_channel(40, 30, 0) < 0.01, "nothing else is selected"); + // Mask Options…: Layer Mask Display Options (the rubylith's colour and opacity). + let (thumbs, _) = crate::mask_thumbs_ui::recorded(&h.ctx, masked.0).expect("mask thumbnail drawn"); + let at = thumbs.iter().find(|(k, _)| *k == crate::mask_thumbs_ui::MaskKind::Pixel).unwrap().1.center(); + click(&mut h, at, PointerButton::Secondary); + let at = h.get_by_label("Mask Options…").rect().center(); + click(&mut h, at, PointerButton::Primary); + let d = h.state().ui.dialogs.last().expect("Mask Options… opens a dialog"); + assert!(crate::channel_options_ui::owns(&d.fields) && d.fields["channel"] == json!("mask"), "{:?}", d.fields); + assert_eq!(d.fields["__label"], json!("Layer Mask Display Options…")); +} + +#[test] +fn a_long_layer_menu_stays_inside_a_short_window_and_scrolls() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 32, "height": 24})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap(); + let app = crate::PhotocraftApp::new(s, crate::Services::default()); + let layer = { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().clone() + }; + let ctx = egui::Context::default(); + crate::PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 300.0)); + let id = egui::Id::unique("layer-menu-probe"); + let mut content = 0.0; + for _ in 0..4 { + let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + // Opened low in the window, like a right-click on a bottom Layers row. + egui::Area::new(id).order(egui::Order::Foreground).default_pos(egui::pos2(300.0, 250.0)).show(ui.ctx(), |ui| { + egui::Frame::menu(ui.style()).show(ui, |ui| { + let start = ui.next_widget_position().y; + show(&app, ui, &layer, false, &mut Vec::new()); + content = ui.min_rect().bottom() - start; + }); + }); + }); + out.textures_delta.clear(); + } + let rect = ctx.memory(|m| m.area_rect(id)).expect("the menu was shown"); + assert!(screen.contains_rect(rect), "the menu moves up and stays inside the window: {rect:?}"); + assert!(rect.height() < screen.height(), "{rect:?}"); + let rows = entries(&layer, false, false).iter().flatten().count(); + assert!(rows >= 15, "Photoshop's layer menu is long: {rows} rows"); + assert!(content < rect.height() + 1.0, "the rows scroll inside the menu instead of running off the window"); +} + +#[test] +fn edit_contents_is_available_only_for_smart_objects() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 32, "height": 24})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Source"})).unwrap(); + let layer = |s: &photocraft_engine::Session| { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().clone() + }; + assert!(!entries(&layer(&s), false, false).iter().flatten().any(|e| e.1 == "layer.smartObjects.editContents")); + s.execute("paint.stroke", json!({"points": [[12, 12]], "size": 8})).unwrap(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let ids: Vec<_> = entries(&layer(&s), false, false).into_iter().flatten().map(|e| e.1).collect(); + let edit = ids.iter().position(|id| *id == "layer.smartObjects.editContents").expect("Edit Contents entry"); + assert_eq!( + ids[edit + 1..edit + 5], + ["layer.smartObjects.replaceContents", "layer.smartObjects.relinkToFile", "layer.smartObjects.convertToLayers", "layer.rasterize.smartObject"] + ); +} + +/// Right-clicking inside a multi-layer selection offers one Rasterize item for the whole +/// selection, whatever kind the clicked layer is, and no single-layer Smart Object items. +#[test] +fn multi_selection_menu_rasterizes_the_selection() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 32, "height": 24})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Source"})).unwrap(); + s.execute("paint.stroke", json!({"points": [[12, 12]], "size": 8})).unwrap(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let st = s.active().unwrap(); + let smart = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + let ids = |multi| entries(&smart, multi, false).into_iter().flatten().map(|e| e.1).collect::>(); + assert!(ids(false).contains(&"layer.smartObjects.editContents"), "a single smart object keeps its items"); + let multi = ids(true); + assert!(multi.contains(&"layer.rasterize.layer")); + for single in [ + "layer.rasterize.smartObject", + "layer.rasterize.shape", + "layer.smartObjects.editContents", + "layer.smartObjects.replaceContents", + "layer.smartObjects.relinkToFile", + "layer.smartObjects.convertToLayers", + ] { + assert!(!multi.contains(&single), "{single} acts on one layer, not on a selection"); + } + let label = entries(&smart, true, false).into_iter().flatten().find(|e| e.1 == "layer.rasterize.layer").unwrap().0; + assert_eq!(label, "Rasterize Layers"); +} + +fn click(h: &mut egui_kittest::Harness<'_, crate::PhotocraftApp>, at: egui::Pos2, button: egui::PointerButton) { + h.hover_at(at); + h.step(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button, pressed, modifiers: egui::Modifiers::NONE }); + h.step(); + } + h.run_steps(3); +} + +/// A type layer, an ellipse and a rectangle; the type layer and the ellipse are selected (the +/// ellipse active), the rectangle stays out. The Layers menu is opened by right-clicking the +/// type row, which is selected but not the active layer. Returns `[type, ellipse, rectangle]`. +fn open_multi_selection_menu() -> (egui_kittest::Harness<'static, crate::PhotocraftApp>, [u64; 3]) { + use crate::PhotocraftApp; + use egui::{PointerButton, pos2, vec2}; + + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 640, "height": 480})).unwrap(); + let text = s.execute("type.create", json!({"text": "Hi", "size": 24, "x": 20, "y": 60})).unwrap()["layer"].as_u64().unwrap(); + let shape = s.execute("shape.create", json!({"kind": "ellipse", "rect": [100, 100, 200, 160]})).unwrap()["layer"].as_u64().unwrap(); + let other = s.execute("shape.create", json!({"kind": "rect", "rect": [300, 100, 380, 160]})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.select", json!({"layer": text})).unwrap(); + s.execute("layer.select", json!({"layer": shape, "mode": "add"})).unwrap(); + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(1440.0, 900.0)) + .with_pixels_per_point(1.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 row = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == text).expect("layer row drawn").row; + click(&mut h, pos2(row.left() + 6.0 + 28.0 + 12.0, row.center().y), PointerButton::Secondary); + (h, [text, shape, other]) +} + +/// The reported bug: right-click a layer inside a multi-layer selection, choose Rasterize, and +/// only the clicked (or active) layer was converted. +#[test] +fn rasterize_from_the_menu_converts_every_selected_layer() { + use egui_kittest::kittest::Queryable; + let (mut h, [text, shape, other]) = open_multi_selection_menu(); + let at = h.get_by_label("Rasterize Layers").rect().center(); + click(&mut h, at, egui::PointerButton::Primary); + let doc = &h.state().session.active().unwrap().doc; + let raster = |id: u64| matches!(doc.layer(photocraft_doc::LayerId(id)).unwrap().content, photocraft_doc::LayerContent::Raster(_)); + assert!(raster(text) && raster(shape), "both selected layers are rasterized"); + assert!(!raster(other), "an unselected layer is left alone"); + assert_eq!(h.state().session.active().unwrap().selected_layers().len(), 2, "the selection survives"); +} + +/// Items with no single target are greyed for a multi-layer selection (they used to run on +/// whichever layer happened to be active, not the one right-clicked); the ones that act on the +/// whole selection, including adding a mask, stay available. +#[test] +fn multi_selection_menu_greys_what_acts_on_one_layer() { + use egui_kittest::kittest::{NodeT, Queryable}; + let (h, _) = open_multi_selection_menu(); + for label in ["Blending Options…", "Copy Layer Style"] { + assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label} works on one layer only"); + } + for label in [ + "Quick Export As PNG", + "Export As…", + "Add Layer Mask", + "Duplicate Layers…", + "Delete Layers", + "Convert to Smart Object", + "Rasterize Layers", + "Link Layers", + "Merge Layers", + ] { + assert!(!h.get_by_label(label).accesskit_node().is_disabled(), "{label} acts on the selection"); + } + // Greyed here only for lack of something to act on: no style on the clipboard, no style to clear. + for label in ["Paste Layer Style", "Clear Layer Style"] { + assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label} has nothing to do here"); + } + // Whatever the clicked layer is, the menu has the same shape: no per-layer mask or Smart Object items. + for label in ["Disable Layer Mask", "Apply Layer Mask", "Delete Layer Mask", "Edit Contents", "Convert to Layers"] { + assert!(h.query_by_label(label).is_none(), "{label} is not offered for several layers"); + } +} + +/// Every entry of the multi-layer menu is either known to act on the selection or greyed by +/// [`single_layer_only`]; a new single-layer command added to the menu must be classified. +#[test] +fn single_layer_only_covers_the_per_layer_commands() { + for id in [ + "layer.layerStyle.blendingOptions", + "layer.layerStyle.copyLayerStyle", + "layer.layerMask.enabled", + "layer.layerMask.apply", + "layer.layerMask.delete", + ] { + assert!(single_layer_only(id), "{id}"); + } + for id in [ + "layer.quickExportAsPng", + "layer.exportAs", + "layer.duplicate", + "layer.delete", + "layer.rasterize.layer", + "layer.smartObjects.convertToSmartObject", + "layer.createClippingMask", + "layer.linkLayers", + "layer.mergeLayers", + "layer.layerMask.revealAll", + "layer.layerMask.hideSelection", + "layer.layerStyle.pasteLayerStyle", + "layer.layerStyle.clear", + ] { + assert!(!single_layer_only(id), "{id}"); + } + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + let st = s.active().unwrap(); + let masked = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + let ids: Vec<_> = entries(&masked, true, false).into_iter().flatten().map(|e| e.1).collect(); + assert!(ids.contains(&"layer.layerMask.revealAll") && !ids.contains(&"layer.layerMask.apply"), "one stable mask item for several layers"); +} + +#[test] +fn entries_follow_layer_state() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let st = s.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + let ids: Vec<&str> = entries(&l, false, false).into_iter().flatten().map(|e| e.1).collect(); + assert_eq!(ids.first(), Some(&"layer.layerStyle.blendingOptions")); + assert!(ids.contains(&"layer.mergeDown") && !ids.contains(&"layer.mergeLayers")); + assert!(ids.contains(&"layer.layerMask.revealAll")); + let ids: Vec<&str> = entries(&l, false, true).into_iter().flatten().map(|e| e.1).collect(); + assert!(ids.contains(&"layer.layerMask.revealSelection") && !ids.contains(&"layer.layerMask.revealAll")); + let ids: Vec<&str> = entries(&l, true, false).into_iter().flatten().map(|e| e.1).collect(); + assert!(ids.contains(&"layer.mergeLayers")); +} + +/// #3832: a group's right-click menu and the Layer menu offer Photoshop's Merge Group, which +/// merges the group itself (not into the layer below), and it is enabled. +#[test] +fn a_group_offers_merge_group() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.groupLayers", json!({"name": "G"})).unwrap(); + let st = s.active().unwrap(); + let g = st.doc.layer(st.active_layer.unwrap()).unwrap().clone(); + let e: Vec<(&str, &str)> = entries(&g, false, false).into_iter().flatten().collect(); + assert!(e.contains(&("Merge Group", "layer.mergeGroup")), "{e:?}"); + assert!(!e.iter().any(|x| x.0 == "Merge Down")); + let mut app = crate::PhotocraftApp::new(s, Default::default()); + app.sync_views(); + let items = crate::menus::menu_items(&app); + let item = items.iter().find(|i| i.id == "layer.mergeLayers").unwrap(); + assert_eq!(item.label, "Merge Group"); + assert!(item.enabled, "Merge Group runs on a group"); + // A plain layer keeps Merge Layers. + app.run("layer.new.layer", json!({})).unwrap(); + let items = crate::menus::menu_items(&app); + assert_eq!(items.iter().find(|i| i.id == "layer.mergeLayers").unwrap().label, "Merge Layers"); +} + +#[test] +fn add_mask_uses_the_selection() { + assert_eq!(add_mask_command(false, false), "layer.layerMask.revealAll"); + assert_eq!(add_mask_command(false, true), "layer.layerMask.hideAll"); + assert_eq!(add_mask_command(true, true), "layer.layerMask.hideSelection"); + // With a selection the new mask is the selection: inside revealed, outside hidden. + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 10})).unwrap(); + s.execute(add_mask_command(true, false), json!({})).unwrap(); + let st = s.active().unwrap(); + let mask = &st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface; + assert!(mask.pixel(1, 5)[0] > 0.99 && mask.pixel(8, 5)[0] < 0.01); +} + +/// #2075: clicking the mask button again (with or without ⌥) used to replace the layer's +/// mask, discarding what was painted into it. Like Photoshop, it now adds a vector mask, and +/// does nothing once the layer has both. +#[test] +fn mask_button_never_replaces_a_mask() { + for alt in [false, true] { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let layer = |s: &photocraft_engine::Session| { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().clone() + }; + let first = mask_button_command(Some(&layer(&s)), false, alt).unwrap(); + assert_eq!(first, if alt { "layer.layerMask.hideAll" } else { "layer.layerMask.revealAll" }); + s.execute(first, json!({})).unwrap(); + // Paint a stroke into the mask. + s.edit("paint mask", |doc, active| { + let id = (*active).ok_or(photocraft_engine::EngineError::NoDocument)?; + let m = doc.layer_mut(id).and_then(|l| l.mask.as_mut()).ok_or(photocraft_engine::EngineError::NoDocument)?; + m.surface.fill_rect(photocraft_geom::Rect::new(2, 2, 5, 5), &[0.5]); + Ok(()) + }) + .unwrap(); + let painted = layer(&s).mask.unwrap().surface.pixel(3, 3)[0]; + assert!((painted - 0.5).abs() < 0.01); + // Second click: a vector mask (⌥ hides all), the layer mask is untouched. + let second = mask_button_command(Some(&layer(&s)), false, alt).unwrap(); + assert_eq!(second, if alt { "layer.vectorMask.hideAll" } else { "layer.vectorMask.revealAll" }); + s.execute(second, json!({})).unwrap(); + let l = layer(&s); + assert!(l.vector_mask.is_some(), "alt={alt}"); + let mask = l.mask.as_ref().unwrap(); + assert!((mask.surface.pixel(3, 3)[0] - painted).abs() < 1e-6, "alt={alt}: the painted mask was replaced"); + // Third click: nothing left to add. + assert_eq!(mask_button_command(Some(&l), false, alt), None); + assert_eq!(mask_button_command(Some(&l), true, alt), None); + } + // No layer: nothing to do. + assert_eq!(mask_button_command(None, false, false), None); + // A shape layer's path is already its vector mask: after the layer mask, nothing more. + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); + s.execute("shape.create", json!({"kind": "rect", "rect": [0, 0, 5, 5]})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + let st = s.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert_eq!(mask_button_command(Some(l), false, false), None); +} + +#[test] +fn every_entry_is_a_known_command() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); + let l = s.active().unwrap().doc.layers[0].clone(); + for (_, id) in entries(&l, false, true).into_iter().chain(entries(&l, false, false)).chain(entries(&l, true, false)).chain(effects_entries()).flatten() + { + assert!(crate::menu_catalog::CATALOG.iter().any(|m| m.3 == id) || photocraft_engine::commands::find(id).is_some(), "{id}"); + } +} From 30dfa32cf5eb84d3119d3d753dcd05befd5ae073 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:30 +0000 Subject: [PATCH 098/259] refactor(ui-egui): move paint_mouse.rs tests to paint_mouse/tests.rs --- crates/ui-egui/src/paint_mouse.rs | 484 +----------------------- crates/ui-egui/src/paint_mouse/tests.rs | 481 +++++++++++++++++++++++ 2 files changed, 482 insertions(+), 483 deletions(-) create mode 100644 crates/ui-egui/src/paint_mouse/tests.rs diff --git a/crates/ui-egui/src/paint_mouse.rs b/crates/ui-egui/src/paint_mouse.rs index 33ff242b57..dc64d34312 100644 --- a/crates/ui-egui/src/paint_mouse.rs +++ b/crates/ui-egui/src/paint_mouse.rs @@ -236,486 +236,4 @@ pub fn show_picker(app: &mut PhotocraftApp, ctx: &egui::Context) { } #[cfg(test)] -mod tests { - use egui::{Modifiers, PointerButton, Pos2, vec2}; - use egui_kittest::Harness; - use serde_json::json; - - use super::*; - use crate::canvas::{ToolEvent, tool_event}; - - fn harness(prefs: Option<&str>) -> 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.setColors", json!({"foreground": "#0000ff"})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 1.0}})).unwrap(); - if let Some(v) = prefs { - app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": v})).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); - h - } - - fn press(h: &mut Harness<'static, PhotocraftApp>, pos: Pos2, button: PointerButton, pressed: bool) { - h.event(egui::Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE }); - h.run_steps(2); - } - - /// Drag across the canvas centre with `button`; returns the document points it covered. - fn drag(h: &mut Harness<'static, PhotocraftApp>, button: PointerButton) -> (Pos2, Pos2) { - let c = h.state().last_canvas_rect.center(); - let (a, b) = (c - vec2(80.0, 0.0), c + vec2(80.0, 0.0)); - h.event(egui::Event::PointerMoved(a)); - h.run_steps(1); - press(h, a, button, true); - for i in 1..=8 { - h.event(egui::Event::PointerMoved(a + (b - a) * (i as f32 / 8.0))); - h.run_steps(1); - } - press(h, b, button, false); - (a, b) - } - - fn alpha_at(h: &Harness<'static, PhotocraftApp>, screen: Pos2) -> f32 { - let app = h.state(); - let v = app.ui.views[0].clone(); - let r = app.last_canvas_rect; - let d = (screen - r.center()) / v.zoom; - let (x, y) = ((d.x + v.center[0]) as i32, (d.y + v.center[1]) as i32); - let st = app.session.active().unwrap(); - st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)[3] - } - - fn strokes(h: &Harness<'static, PhotocraftApp>) -> Vec { - h.state().session.journal.iter().filter(|(id, _)| id == "paint.stroke").map(|(_, p)| p.clone()).collect() - } - - #[test] - fn left_drag_paints() { - let mut h = harness(None); - let (a, b) = drag(&mut h, PointerButton::Primary); - assert_eq!(strokes(&h).len(), 1); - assert!(alpha_at(&h, a + (b - a) * 0.5) > 0.9); - } - - #[test] - fn shift_click_connects_to_the_previous_brush_stroke() { - use egui::{Event, Modifiers}; - - let mut h = harness(None); - let (_, end) = drag(&mut h, PointerButton::Primary); - let previous = h - .state() - .session - .journal - .iter() - .rev() - .find(|(id, _)| id == "paint.stroke") - .map(|(_, p)| p["points"].as_array().unwrap().last().unwrap().clone()) - .unwrap(); - let target = end + vec2(120.0, 80.0); - h.event(Event::PointerMoved(target)); - h.run_steps(1); - for pressed in [true, false] { - h.event(Event::PointerButton { pos: target, button: PointerButton::Primary, pressed, modifiers: Modifiers::SHIFT }); - h.run_steps(2); - } - - let strokes = strokes(&h); - assert_eq!(strokes.len(), 2, "a Shift-click commits one connected stroke"); - let points = strokes[1]["points"].as_array().unwrap(); - // The previous endpoint, then the clicked one. While the button is held, smoothing that is - // still catching up repeats the clicked point with later times. - assert_eq!(points[0][0], previous[0]); - assert_eq!(points[0][1], previous[1]); - let clicked = &points[1]; - assert!(points[1..].iter().all(|p| p[0] == clicked[0] && p[1] == clicked[1]), "{points:?}"); - assert!(alpha_at(&h, end + vec2(60.0, 40.0)) > 0.9, "the segment between the strokes is painted"); - } - - #[test] - fn right_click_opens_the_brush_picker_and_never_paints() { - let mut h = harness(None); - let undo = 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); - press(&mut h, c, PointerButton::Secondary, true); - press(&mut h, c, PointerButton::Secondary, false); - assert_eq!(h.state().ui.brush_picker, Some([c.x, c.y]), "opened at the pointer"); - assert!(strokes(&h).is_empty()); - // The picker shows over the canvas at the pointer, moved up just enough to stay on screen. - h.run_steps(2); - let shown = h.ctx.memory(|m| m.area_rect(egui::Id::unique("canvas-brush-picker"))).expect("picker shown"); - let screen = h.ctx.content_rect(); - assert!((shown.min.x - c.x).abs() < 1.0 && shown.min.y <= c.y + 1.0, "{shown:?}"); - assert!(screen.contains_rect(shown.shrink(0.5)) && shown.width() > 250.0 && shown.height() > 150.0, "{shown:?}"); - // It is the real preset library, not a fixed set of round tips (#258). - let names: Vec = h.state().session.tools.presets.iter().take(3).map(|p| p.name.clone()).collect(); - { - use egui_kittest::kittest::Queryable; - for n in &names { - assert!(h.query_by_label(n).is_some(), "{n} listed"); - } - } - // A right drag doesn't paint either. - drag(&mut h, PointerButton::Secondary); - assert!(strokes(&h).is_empty(), "right-drag never paints with the brush picker preference"); - assert_eq!(h.state().session.active().unwrap().history.past_len(), undo, "no edit"); - // Escape closes it. - h.state_mut().ui.brush_picker = Some([c.x, c.y]); - h.run_steps(1); - h.key_press(egui::Key::Escape); - h.run_steps(2); - assert_eq!(h.state().ui.brush_picker, None); - } - - #[test] - fn click_outside_closes_the_picker() { - let mut h = harness(None); - let c = h.state().last_canvas_rect.center(); - h.state_mut().ui.brush_picker = Some([c.x, c.y]); - h.run_steps(2); - let far = c - vec2(300.0, 200.0); - h.event(egui::Event::PointerMoved(far)); - press(&mut h, far, PointerButton::Primary, true); - press(&mut h, far, PointerButton::Primary, false); - assert_eq!(h.state().ui.brush_picker, None); - } - - /// #1031: the right-click picker picks brushes, not just the size. A click picks a preset and - /// keeps the picker open, a double-click picks one and closes it, and Enter applies a typed - /// size before it closes the picker. - #[test] - fn picker_click_picks_a_preset_and_double_click_closes_it() { - use egui_kittest::kittest::Queryable; - let mut h = harness(None); - let c = h.state().last_canvas_rect.center(); - h.event(egui::Event::PointerMoved(c)); - h.run_steps(1); - press(&mut h, c, PointerButton::Secondary, true); - press(&mut h, c, PointerButton::Secondary, false); - h.run_steps(2); - let names: Vec = h.state().session.tools.presets.iter().skip(1).take(2).map(|p| p.name.clone()).collect(); - let picks = |h: &Harness<'static, PhotocraftApp>, name: &str| { - h.state().session.journal.iter().filter(|(id, p)| id == "tools.setBrush" && *p == json!({ "preset": name })).count() - }; - h.get_by_label(&names[0]).click(); - h.run_steps(3); - assert_eq!(picks(&h, &names[0]), 1); - assert!(h.state().ui.brush_picker.is_some(), "a click keeps the picker open"); - let at = h.get_by_label(&names[1]).rect().center(); - h.event(egui::Event::PointerMoved(at)); - h.run_steps(1); - // Two clicks 2 frames apart; well after the first click, so not a triple click. - h.run_steps(40); - for pressed in [true, false, true, false] { - h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); - h.step(); - } - h.run_steps(2); - assert_eq!(picks(&h, &names[1]), 1, "picked once: the second click only closes"); - assert_eq!(h.state().ui.brush_picker, None, "a double-click closes the picker"); - assert!(strokes(&h).is_empty(), "nothing painted under the picker"); - // Enter applies the typed size, then closes the picker. - h.state_mut().ui.brush_picker = Some([c.x, c.y]); - h.run_steps(2); - h.get_all_by_role(egui::accesskit::Role::SpinButton).next().expect("the Size field").click(); - h.run_steps(1); - h.event(egui::Event::Text("30*2".into())); - h.run_steps(1); - h.key_press(egui::Key::Enter); - h.run_steps(2); - assert_eq!((h.state().session.tools.brush.size, h.state().ui.brush_picker), (60.0, None)); - } - - /// A sampled tip has no hardness: the picker shows only its size (Photoshop). - #[test] - fn picker_shows_hardness_only_for_round_tips() { - use egui_kittest::kittest::Queryable; - let mut h = harness(None); - let c = h.state().last_canvas_rect.center(); - h.state_mut().ui.brush_picker = Some([c.x, c.y]); - h.run_steps(2); - assert!(h.query_all_by_label("Hardness").next().is_some()); - let sampled = h.state().session.tools.presets.iter().find(|p| p.brush.tip != photocraft_engine::paint::TipShape::Round).map(|p| p.name.clone()); - h.state_mut().run("tools.setBrush", json!({ "preset": sampled.expect("a sampled preset") })).unwrap(); - h.run_steps(2); - assert!(h.query_all_by_label("Hardness").next().is_none()); - assert!(h.state().ui.brush_picker.is_some()); - } - - /// The gear menu's New Brush Preset… opens the New Brush Preset dialog (#4490), which saves - /// the preset under the typed name on OK. - #[test] - fn picker_gear_menu_saves_and_names_a_new_preset() { - use egui_kittest::kittest::Queryable; - let mut h = harness(None); - let c = h.state().last_canvas_rect.center(); - h.state_mut().ui.brush_picker = Some([c.x, c.y]); - h.run_steps(2); - h.get_by_label("Brush Preset Options").click(); - h.run_steps(2); - let before = h.state().session.tools.presets.len(); - h.get_by_label("New Brush Preset…").click(); - h.run_steps(3); - let dialog = h.state().ui.dialogs.iter().find(|d| crate::brush_preset_dialog::owns(&d.fields)).map(|d| d.id).expect("the dialog asks for a name"); - assert_eq!(h.state().session.tools.presets.len(), before, "nothing is saved before OK"); - assert!(h.state().ui.brush_picker.is_none(), "the dialog takes the picker's place"); - // This harness draws the canvas only: OK as automation does (the dialog's own tests type). - h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("name".into(), json!("Inky")); - crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); - h.run_steps(2); - assert!(h.state().session.tools.presets.iter().any(|p| p.name == "Inky"), "saved under the typed name"); - 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. - 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 Stroke").click(); - h.run_steps(2); - h.get_by_label("Brush Name").click(); - h.run_steps(2); - assert!(h.state().ui.brush_picker_list.show_name, "the last part on stays on"); - assert!(!h.state().ui.brush_picker_list.show_stroke && !h.state().ui.brush_picker_list.show_tip); - assert!(h.state().ui.brush_picker.is_some()); - // A rename left open goes with the picker. - h.state_mut().ui.brush_picker_list.renaming = - Some(crate::brush_panel::Renaming { group: false, name: "Inky".into(), folder: Vec::new(), text: String::new() }); - h.run_steps(2); - let far = c - vec2(300.0, 200.0); - h.event(egui::Event::PointerMoved(far)); - press(&mut h, far, PointerButton::Primary, true); - press(&mut h, far, PointerButton::Primary, false); - assert!(h.state().ui.brush_picker.is_none() && h.state().ui.brush_picker_list.renaming.is_none()); - } - - #[test] - fn right_drag_erases_with_the_erase_preference() { - let mut h = harness(Some("erase")); - let (a, b) = drag(&mut h, PointerButton::Primary); - let mid = a + (b - a) * 0.5; - assert!(alpha_at(&h, mid) > 0.9); - let undo = h.state().session.active().unwrap().history.past_len(); - drag(&mut h, PointerButton::Secondary); - let s = strokes(&h); - assert_eq!(s.len(), 2); - assert_eq!(s[1]["erase"], json!(true), "the right stroke erases"); - assert_eq!(alpha_at(&h, mid), 0.0, "erased to transparency"); - assert_eq!(h.state().session.active().unwrap().history.past_len(), undo + 1, "one undo step"); - assert_eq!(h.state().ui.brush_picker, None, "no picker in erase mode"); - // The next left stroke paints again. - drag(&mut h, PointerButton::Primary); - assert_eq!(strokes(&h)[2]["erase"], json!(false)); - assert!(alpha_at(&h, mid) > 0.9); - } - - #[test] - fn right_stroke_erases_with_pen_pressure_through_the_control_channel_path() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 120, "height": 80})).unwrap(); - app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": "erase"})).unwrap(); - app.ui.tool = Tool::Brush; - let m = Modifiers::NONE; - assert!(pointer_secondary(&mut app, &egui::Context::default(), true, egui::Modifiers::NONE, [0.0, 0.0])); - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 0.4 }, m); - assert!(!app.secondary_erase, "armed for one stroke only"); - tool_event(&mut app, ToolEvent::Move { x: 100.0, y: 40.0, pressure: 0.8 }, m); - tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 40.0 }, m); - let p = app.session.journal.iter().rev().find(|(id, _)| id == "paint.stroke").map(|(_, p)| p.clone()).unwrap(); - assert_eq!(p["erase"], json!(true)); - assert_eq!(p["points"][0], json!([10.0, 40.0, 0.4f32 as f64]), "pressure reaches the erasing stroke"); - // On the Background the erasing stroke paints the background colour (#76). - let st = app.session.active().unwrap(); - assert_eq!(st.doc.layers[0].surface().unwrap().rgba(50, 40), [1.0, 1.0, 1.0, 1.0]); - // With the default preference the right button opens the picker and nothing paints. - app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": "brushPicker"})).unwrap(); - assert!(!pointer_secondary(&mut app, &egui::Context::default(), true, egui::Modifiers::NONE, [0.0, 0.0])); - assert!(app.ui.brush_picker.is_some() && !app.secondary_erase); - } - - #[test] - fn the_brush_is_a_per_tool_option_that_presets_keep() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); - let amount = |app: &PhotocraftApp| app.session.tools.brush.smoothing.amount; - app.ui.tool = Tool::Brush; - sync_tool_brush(&mut app); - assert_eq!(amount(&app), 0.1, "Photoshop's default"); - // Picking a preset (whose own smoothing is 0) keeps the tool's smoothing. - let preset = app.session.tools.presets.iter().find(|p| p.brush.smoothing.amount == 0.0).map(|p| p.name.clone()).unwrap(); - app.run("tools.setBrush", json!({"preset": preset})).unwrap(); - assert_eq!(amount(&app), 0.1); - // A user value (the options-bar field) survives a preset too, mode included. - app.session.tools.brush.smoothing.amount = 0.42; - app.session.tools.brush.smoothing.pulled_string = true; - app.run("tools.setBrush", json!({"preset": preset})).unwrap(); - assert_eq!((amount(&app), app.session.tools.brush.smoothing.pulled_string), (0.42, true)); - // The Eraser has its own (10 % at first); switching back restores the Brush's. - app.ui.tool = Tool::Eraser; - sync_tool_brush(&mut app); - assert_eq!(amount(&app), 0.1); - app.session.tools.brush.smoothing.amount = 0.0; - app.ui.tool = Tool::Brush; - sync_tool_brush(&mut app); - assert_eq!((amount(&app), app.session.tools.brush.smoothing.pulled_string), (0.42, true)); - // Other tools leave it alone; the Eraser kept its 0 %. - app.ui.tool = Tool::Move; - sync_tool_brush(&mut app); - assert_eq!(amount(&app), 0.42); - app.ui.tool = Tool::Eraser; - // A stroke picks up the tool's brush even without a frame in between. - tool_event(&mut app, ToolEvent::Down { x: 5.0, y: 5.0, pressure: 1.0 }, Modifiers::NONE); - assert_eq!(amount(&app), 0.0); - tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 5.0 }, Modifiers::NONE); - } - - /// #218: Photoshop keeps a brush per painting tool, so the size, hardness, mode, opacity and - /// dynamics of one tool never leak into another's, and each tool gets its own back. - #[test] - fn each_tool_keeps_its_own_brush() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); - let brush = |app: &PhotocraftApp| app.session.tools.brush.clone(); - let size = |b: &BrushSettings| b.size; - let hardness = |b: &BrushSettings| b.hardness; - let opacity = |b: &BrushSettings| b.opacity; - let mode = |b: &BrushSettings| b.mode; - - app.ui.tool = Tool::Brush; - sync_tool_brush(&mut app); - app.run("tools.setBrush", json!({"brush": {"size": 40, "hardness": 0.2, "opacity": 0.7, "mode": "Multiply"}})).unwrap(); - assert_eq!(size(&brush(&app)), 40.0); - - // A tool seen for the first time starts from the brush the old tool left (Photoshop's - // 10 % smoothing), so nothing is lost by switching. - app.ui.tool = Tool::Eraser; - sync_tool_brush(&mut app); - assert_eq!(size(&brush(&app)), 40.0, "a new tool inherits the current brush"); - - // The Eraser edits its own size; the Brush keeps 40 px. - app.run("tools.setBrush", json!({"brush": {"size": 8, "hardness": 1.0}})).unwrap(); - app.ui.tool = Tool::Brush; - sync_tool_brush(&mut app); - assert_eq!(size(&brush(&app)), 40.0, "the Brush keeps its own size"); - assert_eq!(hardness(&brush(&app)), 0.2, "and its hardness"); - app.ui.tool = Tool::Eraser; - sync_tool_brush(&mut app); - assert_eq!(size(&brush(&app)), 8.0, "the Eraser keeps its own size"); - assert_eq!(hardness(&brush(&app)), 1.0, "and its hardness"); - - // Mode, opacity, flow and the dynamics sections are per tool too. - app.ui.tool = Tool::CloneStamp; - sync_tool_brush(&mut app); - assert_eq!(mode(&brush(&app)), photocraft_color::BlendMode::Normal, "a new tool starts in Normal, not the Brush's Multiply"); - app.run("tools.setBrush", json!({"brush": {"mode": "Screen", "opacity": 0.3}})).unwrap(); - app.ui.tool = Tool::Brush; - sync_tool_brush(&mut app); - assert_eq!((mode(&brush(&app)), opacity(&brush(&app))), (photocraft_color::BlendMode::Multiply, 0.7), "the Brush's own mode and opacity"); - app.ui.tool = Tool::CloneStamp; - sync_tool_brush(&mut app); - assert_eq!((mode(&brush(&app)), opacity(&brush(&app))), (photocraft_color::BlendMode::Screen, 0.3), "the Clone Stamp keeps its own"); - - // The colours, the erase flag and the seed belong to the session, so a swap keeps what is - // live now instead of restoring another tool's copy (a picked colour reaches every tool). - app.run("tools.setBrush", json!({"brush": {"color": [0.0, 1.0, 0.0, 1.0], "background": [1.0, 0.0, 1.0, 1.0], "erase": true, "seed": 42}})).unwrap(); - app.ui.tool = Tool::Brush; - sync_tool_brush(&mut app); - let b = brush(&app); - assert_eq!( - (b.color, b.background, b.erase, b.seed), - ([0.0, 1.0, 0.0, 1.0], [1.0, 0.0, 1.0, 1.0], true, 42), - "the session's own brush fields survive the swap" - ); - - // Tools with no brush of their own (the Move) leave the brush alone. - let before = brush(&app); - app.ui.tool = Tool::Move; - sync_tool_brush(&mut app); - assert_eq!(brush(&app), before); - } - - #[test] - fn eraser_tool_on_the_background_paints_the_background_colour() { - // #76: the Eraser on the Background (locked transparency) paints the background colour. - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({"width": 120, "height": 80})).unwrap(); - app.run("tools.setColors", json!({"background": "#ff0000"})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 12, "hardness": 1.0}})).unwrap(); - app.ui.tool = Tool::Eraser; - let m = Modifiers::NONE; - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Move { x: 100.0, y: 40.0, pressure: 1.0 }, m); - tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 40.0 }, m); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.layers[0].name, "Background"); - assert_eq!(st.doc.layers[0].surface().unwrap().rgba(50, 40), [1.0, 0.0, 0.0, 1.0]); - assert_eq!(st.history.undo_label(), Some("Eraser")); - assert!(!app.ui.status_error, "{}", app.ui.status); - } - - /// Assert the one committed stroke contains a point at each queued screen position. - fn assert_committed_points(h: &Harness<'static, PhotocraftApp>, queued: &[Pos2]) { - let s = strokes(h); - assert_eq!(s.len(), 1); - let points = s[0]["points"].as_array().unwrap(); - let app = h.state(); - let v = app.ui.views[0].clone(); - let r = app.last_canvas_rect; - for p in queued { - let d = (*p - r.center()) / v.zoom; - let want = [d.x as f64 + v.center[0] as f64, d.y as f64 + v.center[1] as f64]; - assert!( - points.iter().any(|q| { - let q = q.as_array().unwrap(); - (q[0].as_f64().unwrap() - want[0]).abs() < 1.0 && (q[1].as_f64().unwrap() - want[1]).abs() < 1.0 - }), - "queued move {want:?} missing from {points:?}" - ); - } - } - - #[test] - fn one_frame_feeds_every_pointer_move_not_just_the_latest() { - // Fast strokes used to lose the moves between two frames: the canvas read only - // `interact_pointer_pos()` once per frame, so the stroke was a coarse polyline. Every - // `PointerMoved` egui-winit delivered in one frame must now reach the stroke. - let mut h = harness(None); - let c = h.state().last_canvas_rect.center(); - let a = c - vec2(90.0, 0.0); - h.event(egui::Event::PointerMoved(a)); - h.run_steps(1); - press(&mut h, a, PointerButton::Primary, true); - // Cross egui's drag threshold on its own frame. - h.event(egui::Event::PointerMoved(a + vec2(20.0, 0.0))); - h.run_steps(1); - // Several moves in ONE frame: `Harness::event` would make one frame per event, so push - // them straight into the next frame's input. All of them must reach the committed stroke. - let queued: Vec = (1..=6).map(|i| a + vec2(20.0 + i as f32 * 8.0, 0.0)).collect(); - for p in &queued { - h.input_mut().events.push(egui::Event::PointerMoved(*p)); - } - h.run_steps(1); - let end = *queued.last().unwrap(); - press(&mut h, end, PointerButton::Primary, false); - assert_committed_points(&h, &queued); - } -} +mod tests; diff --git a/crates/ui-egui/src/paint_mouse/tests.rs b/crates/ui-egui/src/paint_mouse/tests.rs new file mode 100644 index 0000000000..4b54a1ce98 --- /dev/null +++ b/crates/ui-egui/src/paint_mouse/tests.rs @@ -0,0 +1,481 @@ +use egui::{Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use super::*; +use crate::canvas::{ToolEvent, tool_event}; + +fn harness(prefs: Option<&str>) -> 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.setColors", json!({"foreground": "#0000ff"})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 1.0}})).unwrap(); + if let Some(v) = prefs { + app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": v})).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); + h +} + +fn press(h: &mut Harness<'static, PhotocraftApp>, pos: Pos2, button: PointerButton, pressed: bool) { + h.event(egui::Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// Drag across the canvas centre with `button`; returns the document points it covered. +fn drag(h: &mut Harness<'static, PhotocraftApp>, button: PointerButton) -> (Pos2, Pos2) { + let c = h.state().last_canvas_rect.center(); + let (a, b) = (c - vec2(80.0, 0.0), c + vec2(80.0, 0.0)); + h.event(egui::Event::PointerMoved(a)); + h.run_steps(1); + press(h, a, button, true); + for i in 1..=8 { + h.event(egui::Event::PointerMoved(a + (b - a) * (i as f32 / 8.0))); + h.run_steps(1); + } + press(h, b, button, false); + (a, b) +} + +fn alpha_at(h: &Harness<'static, PhotocraftApp>, screen: Pos2) -> f32 { + let app = h.state(); + let v = app.ui.views[0].clone(); + let r = app.last_canvas_rect; + let d = (screen - r.center()) / v.zoom; + let (x, y) = ((d.x + v.center[0]) as i32, (d.y + v.center[1]) as i32); + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)[3] +} + +fn strokes(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.state().session.journal.iter().filter(|(id, _)| id == "paint.stroke").map(|(_, p)| p.clone()).collect() +} + +#[test] +fn left_drag_paints() { + let mut h = harness(None); + let (a, b) = drag(&mut h, PointerButton::Primary); + assert_eq!(strokes(&h).len(), 1); + assert!(alpha_at(&h, a + (b - a) * 0.5) > 0.9); +} + +#[test] +fn shift_click_connects_to_the_previous_brush_stroke() { + use egui::{Event, Modifiers}; + + let mut h = harness(None); + let (_, end) = drag(&mut h, PointerButton::Primary); + let previous = h + .state() + .session + .journal + .iter() + .rev() + .find(|(id, _)| id == "paint.stroke") + .map(|(_, p)| p["points"].as_array().unwrap().last().unwrap().clone()) + .unwrap(); + let target = end + vec2(120.0, 80.0); + h.event(Event::PointerMoved(target)); + h.run_steps(1); + for pressed in [true, false] { + h.event(Event::PointerButton { pos: target, button: PointerButton::Primary, pressed, modifiers: Modifiers::SHIFT }); + h.run_steps(2); + } + + let strokes = strokes(&h); + assert_eq!(strokes.len(), 2, "a Shift-click commits one connected stroke"); + let points = strokes[1]["points"].as_array().unwrap(); + // The previous endpoint, then the clicked one. While the button is held, smoothing that is + // still catching up repeats the clicked point with later times. + assert_eq!(points[0][0], previous[0]); + assert_eq!(points[0][1], previous[1]); + let clicked = &points[1]; + assert!(points[1..].iter().all(|p| p[0] == clicked[0] && p[1] == clicked[1]), "{points:?}"); + assert!(alpha_at(&h, end + vec2(60.0, 40.0)) > 0.9, "the segment between the strokes is painted"); +} + +#[test] +fn right_click_opens_the_brush_picker_and_never_paints() { + let mut h = harness(None); + let undo = 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); + press(&mut h, c, PointerButton::Secondary, true); + press(&mut h, c, PointerButton::Secondary, false); + assert_eq!(h.state().ui.brush_picker, Some([c.x, c.y]), "opened at the pointer"); + assert!(strokes(&h).is_empty()); + // The picker shows over the canvas at the pointer, moved up just enough to stay on screen. + h.run_steps(2); + let shown = h.ctx.memory(|m| m.area_rect(egui::Id::unique("canvas-brush-picker"))).expect("picker shown"); + let screen = h.ctx.content_rect(); + assert!((shown.min.x - c.x).abs() < 1.0 && shown.min.y <= c.y + 1.0, "{shown:?}"); + assert!(screen.contains_rect(shown.shrink(0.5)) && shown.width() > 250.0 && shown.height() > 150.0, "{shown:?}"); + // It is the real preset library, not a fixed set of round tips (#258). + let names: Vec = h.state().session.tools.presets.iter().take(3).map(|p| p.name.clone()).collect(); + { + use egui_kittest::kittest::Queryable; + for n in &names { + assert!(h.query_by_label(n).is_some(), "{n} listed"); + } + } + // A right drag doesn't paint either. + drag(&mut h, PointerButton::Secondary); + assert!(strokes(&h).is_empty(), "right-drag never paints with the brush picker preference"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), undo, "no edit"); + // Escape closes it. + h.state_mut().ui.brush_picker = Some([c.x, c.y]); + h.run_steps(1); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert_eq!(h.state().ui.brush_picker, None); +} + +#[test] +fn click_outside_closes_the_picker() { + let mut h = harness(None); + let c = h.state().last_canvas_rect.center(); + h.state_mut().ui.brush_picker = Some([c.x, c.y]); + h.run_steps(2); + let far = c - vec2(300.0, 200.0); + h.event(egui::Event::PointerMoved(far)); + press(&mut h, far, PointerButton::Primary, true); + press(&mut h, far, PointerButton::Primary, false); + assert_eq!(h.state().ui.brush_picker, None); +} + +/// #1031: the right-click picker picks brushes, not just the size. A click picks a preset and +/// keeps the picker open, a double-click picks one and closes it, and Enter applies a typed +/// size before it closes the picker. +#[test] +fn picker_click_picks_a_preset_and_double_click_closes_it() { + use egui_kittest::kittest::Queryable; + let mut h = harness(None); + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + press(&mut h, c, PointerButton::Secondary, true); + press(&mut h, c, PointerButton::Secondary, false); + h.run_steps(2); + let names: Vec = h.state().session.tools.presets.iter().skip(1).take(2).map(|p| p.name.clone()).collect(); + let picks = |h: &Harness<'static, PhotocraftApp>, name: &str| { + h.state().session.journal.iter().filter(|(id, p)| id == "tools.setBrush" && *p == json!({ "preset": name })).count() + }; + h.get_by_label(&names[0]).click(); + h.run_steps(3); + assert_eq!(picks(&h, &names[0]), 1); + assert!(h.state().ui.brush_picker.is_some(), "a click keeps the picker open"); + let at = h.get_by_label(&names[1]).rect().center(); + h.event(egui::Event::PointerMoved(at)); + h.run_steps(1); + // Two clicks 2 frames apart; well after the first click, so not a triple click. + h.run_steps(40); + for pressed in [true, false, true, false] { + h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(2); + assert_eq!(picks(&h, &names[1]), 1, "picked once: the second click only closes"); + assert_eq!(h.state().ui.brush_picker, None, "a double-click closes the picker"); + assert!(strokes(&h).is_empty(), "nothing painted under the picker"); + // Enter applies the typed size, then closes the picker. + h.state_mut().ui.brush_picker = Some([c.x, c.y]); + h.run_steps(2); + h.get_all_by_role(egui::accesskit::Role::SpinButton).next().expect("the Size field").click(); + h.run_steps(1); + h.event(egui::Event::Text("30*2".into())); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!((h.state().session.tools.brush.size, h.state().ui.brush_picker), (60.0, None)); +} + +/// A sampled tip has no hardness: the picker shows only its size (Photoshop). +#[test] +fn picker_shows_hardness_only_for_round_tips() { + use egui_kittest::kittest::Queryable; + let mut h = harness(None); + let c = h.state().last_canvas_rect.center(); + h.state_mut().ui.brush_picker = Some([c.x, c.y]); + h.run_steps(2); + assert!(h.query_all_by_label("Hardness").next().is_some()); + let sampled = h.state().session.tools.presets.iter().find(|p| p.brush.tip != photocraft_engine::paint::TipShape::Round).map(|p| p.name.clone()); + h.state_mut().run("tools.setBrush", json!({ "preset": sampled.expect("a sampled preset") })).unwrap(); + h.run_steps(2); + assert!(h.query_all_by_label("Hardness").next().is_none()); + assert!(h.state().ui.brush_picker.is_some()); +} + +/// The gear menu's New Brush Preset… opens the New Brush Preset dialog (#4490), which saves +/// the preset under the typed name on OK. +#[test] +fn picker_gear_menu_saves_and_names_a_new_preset() { + use egui_kittest::kittest::Queryable; + let mut h = harness(None); + let c = h.state().last_canvas_rect.center(); + h.state_mut().ui.brush_picker = Some([c.x, c.y]); + h.run_steps(2); + h.get_by_label("Brush Preset Options").click(); + h.run_steps(2); + let before = h.state().session.tools.presets.len(); + h.get_by_label("New Brush Preset…").click(); + h.run_steps(3); + let dialog = h.state().ui.dialogs.iter().find(|d| crate::brush_preset_dialog::owns(&d.fields)).map(|d| d.id).expect("the dialog asks for a name"); + assert_eq!(h.state().session.tools.presets.len(), before, "nothing is saved before OK"); + assert!(h.state().ui.brush_picker.is_none(), "the dialog takes the picker's place"); + // This harness draws the canvas only: OK as automation does (the dialog's own tests type). + h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("name".into(), json!("Inky")); + crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + h.run_steps(2); + assert!(h.state().session.tools.presets.iter().any(|p| p.name == "Inky"), "saved under the typed name"); + 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. + 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 Stroke").click(); + h.run_steps(2); + h.get_by_label("Brush Name").click(); + h.run_steps(2); + assert!(h.state().ui.brush_picker_list.show_name, "the last part on stays on"); + assert!(!h.state().ui.brush_picker_list.show_stroke && !h.state().ui.brush_picker_list.show_tip); + assert!(h.state().ui.brush_picker.is_some()); + // A rename left open goes with the picker. + h.state_mut().ui.brush_picker_list.renaming = + Some(crate::brush_panel::Renaming { group: false, name: "Inky".into(), folder: Vec::new(), text: String::new() }); + h.run_steps(2); + let far = c - vec2(300.0, 200.0); + h.event(egui::Event::PointerMoved(far)); + press(&mut h, far, PointerButton::Primary, true); + press(&mut h, far, PointerButton::Primary, false); + assert!(h.state().ui.brush_picker.is_none() && h.state().ui.brush_picker_list.renaming.is_none()); +} + +#[test] +fn right_drag_erases_with_the_erase_preference() { + let mut h = harness(Some("erase")); + let (a, b) = drag(&mut h, PointerButton::Primary); + let mid = a + (b - a) * 0.5; + assert!(alpha_at(&h, mid) > 0.9); + let undo = h.state().session.active().unwrap().history.past_len(); + drag(&mut h, PointerButton::Secondary); + let s = strokes(&h); + assert_eq!(s.len(), 2); + assert_eq!(s[1]["erase"], json!(true), "the right stroke erases"); + assert_eq!(alpha_at(&h, mid), 0.0, "erased to transparency"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), undo + 1, "one undo step"); + assert_eq!(h.state().ui.brush_picker, None, "no picker in erase mode"); + // The next left stroke paints again. + drag(&mut h, PointerButton::Primary); + assert_eq!(strokes(&h)[2]["erase"], json!(false)); + assert!(alpha_at(&h, mid) > 0.9); +} + +#[test] +fn right_stroke_erases_with_pen_pressure_through_the_control_channel_path() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 120, "height": 80})).unwrap(); + app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": "erase"})).unwrap(); + app.ui.tool = Tool::Brush; + let m = Modifiers::NONE; + assert!(pointer_secondary(&mut app, &egui::Context::default(), true, egui::Modifiers::NONE, [0.0, 0.0])); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 0.4 }, m); + assert!(!app.secondary_erase, "armed for one stroke only"); + tool_event(&mut app, ToolEvent::Move { x: 100.0, y: 40.0, pressure: 0.8 }, m); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 40.0 }, m); + let p = app.session.journal.iter().rev().find(|(id, _)| id == "paint.stroke").map(|(_, p)| p.clone()).unwrap(); + assert_eq!(p["erase"], json!(true)); + assert_eq!(p["points"][0], json!([10.0, 40.0, 0.4f32 as f64]), "pressure reaches the erasing stroke"); + // On the Background the erasing stroke paints the background colour (#76). + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers[0].surface().unwrap().rgba(50, 40), [1.0, 1.0, 1.0, 1.0]); + // With the default preference the right button opens the picker and nothing paints. + app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": "brushPicker"})).unwrap(); + assert!(!pointer_secondary(&mut app, &egui::Context::default(), true, egui::Modifiers::NONE, [0.0, 0.0])); + assert!(app.ui.brush_picker.is_some() && !app.secondary_erase); +} + +#[test] +fn the_brush_is_a_per_tool_option_that_presets_keep() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + let amount = |app: &PhotocraftApp| app.session.tools.brush.smoothing.amount; + app.ui.tool = Tool::Brush; + sync_tool_brush(&mut app); + assert_eq!(amount(&app), 0.1, "Photoshop's default"); + // Picking a preset (whose own smoothing is 0) keeps the tool's smoothing. + let preset = app.session.tools.presets.iter().find(|p| p.brush.smoothing.amount == 0.0).map(|p| p.name.clone()).unwrap(); + app.run("tools.setBrush", json!({"preset": preset})).unwrap(); + assert_eq!(amount(&app), 0.1); + // A user value (the options-bar field) survives a preset too, mode included. + app.session.tools.brush.smoothing.amount = 0.42; + app.session.tools.brush.smoothing.pulled_string = true; + app.run("tools.setBrush", json!({"preset": preset})).unwrap(); + assert_eq!((amount(&app), app.session.tools.brush.smoothing.pulled_string), (0.42, true)); + // The Eraser has its own (10 % at first); switching back restores the Brush's. + app.ui.tool = Tool::Eraser; + sync_tool_brush(&mut app); + assert_eq!(amount(&app), 0.1); + app.session.tools.brush.smoothing.amount = 0.0; + app.ui.tool = Tool::Brush; + sync_tool_brush(&mut app); + assert_eq!((amount(&app), app.session.tools.brush.smoothing.pulled_string), (0.42, true)); + // Other tools leave it alone; the Eraser kept its 0 %. + app.ui.tool = Tool::Move; + sync_tool_brush(&mut app); + assert_eq!(amount(&app), 0.42); + app.ui.tool = Tool::Eraser; + // A stroke picks up the tool's brush even without a frame in between. + tool_event(&mut app, ToolEvent::Down { x: 5.0, y: 5.0, pressure: 1.0 }, Modifiers::NONE); + assert_eq!(amount(&app), 0.0); + tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 5.0 }, Modifiers::NONE); +} + +/// #218: Photoshop keeps a brush per painting tool, so the size, hardness, mode, opacity and +/// dynamics of one tool never leak into another's, and each tool gets its own back. +#[test] +fn each_tool_keeps_its_own_brush() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + let brush = |app: &PhotocraftApp| app.session.tools.brush.clone(); + let size = |b: &BrushSettings| b.size; + let hardness = |b: &BrushSettings| b.hardness; + let opacity = |b: &BrushSettings| b.opacity; + let mode = |b: &BrushSettings| b.mode; + + app.ui.tool = Tool::Brush; + sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": {"size": 40, "hardness": 0.2, "opacity": 0.7, "mode": "Multiply"}})).unwrap(); + assert_eq!(size(&brush(&app)), 40.0); + + // A tool seen for the first time starts from the brush the old tool left (Photoshop's + // 10 % smoothing), so nothing is lost by switching. + app.ui.tool = Tool::Eraser; + sync_tool_brush(&mut app); + assert_eq!(size(&brush(&app)), 40.0, "a new tool inherits the current brush"); + + // The Eraser edits its own size; the Brush keeps 40 px. + app.run("tools.setBrush", json!({"brush": {"size": 8, "hardness": 1.0}})).unwrap(); + app.ui.tool = Tool::Brush; + sync_tool_brush(&mut app); + assert_eq!(size(&brush(&app)), 40.0, "the Brush keeps its own size"); + assert_eq!(hardness(&brush(&app)), 0.2, "and its hardness"); + app.ui.tool = Tool::Eraser; + sync_tool_brush(&mut app); + assert_eq!(size(&brush(&app)), 8.0, "the Eraser keeps its own size"); + assert_eq!(hardness(&brush(&app)), 1.0, "and its hardness"); + + // Mode, opacity, flow and the dynamics sections are per tool too. + app.ui.tool = Tool::CloneStamp; + sync_tool_brush(&mut app); + assert_eq!(mode(&brush(&app)), photocraft_color::BlendMode::Normal, "a new tool starts in Normal, not the Brush's Multiply"); + app.run("tools.setBrush", json!({"brush": {"mode": "Screen", "opacity": 0.3}})).unwrap(); + app.ui.tool = Tool::Brush; + sync_tool_brush(&mut app); + assert_eq!((mode(&brush(&app)), opacity(&brush(&app))), (photocraft_color::BlendMode::Multiply, 0.7), "the Brush's own mode and opacity"); + app.ui.tool = Tool::CloneStamp; + sync_tool_brush(&mut app); + assert_eq!((mode(&brush(&app)), opacity(&brush(&app))), (photocraft_color::BlendMode::Screen, 0.3), "the Clone Stamp keeps its own"); + + // The colours, the erase flag and the seed belong to the session, so a swap keeps what is + // live now instead of restoring another tool's copy (a picked colour reaches every tool). + app.run("tools.setBrush", json!({"brush": {"color": [0.0, 1.0, 0.0, 1.0], "background": [1.0, 0.0, 1.0, 1.0], "erase": true, "seed": 42}})).unwrap(); + app.ui.tool = Tool::Brush; + sync_tool_brush(&mut app); + let b = brush(&app); + assert_eq!( + (b.color, b.background, b.erase, b.seed), + ([0.0, 1.0, 0.0, 1.0], [1.0, 0.0, 1.0, 1.0], true, 42), + "the session's own brush fields survive the swap" + ); + + // Tools with no brush of their own (the Move) leave the brush alone. + let before = brush(&app); + app.ui.tool = Tool::Move; + sync_tool_brush(&mut app); + assert_eq!(brush(&app), before); +} + +#[test] +fn eraser_tool_on_the_background_paints_the_background_colour() { + // #76: the Eraser on the Background (locked transparency) paints the background colour. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 120, "height": 80})).unwrap(); + app.run("tools.setColors", json!({"background": "#ff0000"})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 12, "hardness": 1.0}})).unwrap(); + app.ui.tool = Tool::Eraser; + let m = Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 100.0, y: 40.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 40.0 }, m); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers[0].name, "Background"); + assert_eq!(st.doc.layers[0].surface().unwrap().rgba(50, 40), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(st.history.undo_label(), Some("Eraser")); + assert!(!app.ui.status_error, "{}", app.ui.status); +} + +/// Assert the one committed stroke contains a point at each queued screen position. +fn assert_committed_points(h: &Harness<'static, PhotocraftApp>, queued: &[Pos2]) { + let s = strokes(h); + assert_eq!(s.len(), 1); + let points = s[0]["points"].as_array().unwrap(); + let app = h.state(); + let v = app.ui.views[0].clone(); + let r = app.last_canvas_rect; + for p in queued { + let d = (*p - r.center()) / v.zoom; + let want = [d.x as f64 + v.center[0] as f64, d.y as f64 + v.center[1] as f64]; + assert!( + points.iter().any(|q| { + let q = q.as_array().unwrap(); + (q[0].as_f64().unwrap() - want[0]).abs() < 1.0 && (q[1].as_f64().unwrap() - want[1]).abs() < 1.0 + }), + "queued move {want:?} missing from {points:?}" + ); + } +} + +#[test] +fn one_frame_feeds_every_pointer_move_not_just_the_latest() { + // Fast strokes used to lose the moves between two frames: the canvas read only + // `interact_pointer_pos()` once per frame, so the stroke was a coarse polyline. Every + // `PointerMoved` egui-winit delivered in one frame must now reach the stroke. + let mut h = harness(None); + let c = h.state().last_canvas_rect.center(); + let a = c - vec2(90.0, 0.0); + h.event(egui::Event::PointerMoved(a)); + h.run_steps(1); + press(&mut h, a, PointerButton::Primary, true); + // Cross egui's drag threshold on its own frame. + h.event(egui::Event::PointerMoved(a + vec2(20.0, 0.0))); + h.run_steps(1); + // Several moves in ONE frame: `Harness::event` would make one frame per event, so push + // them straight into the next frame's input. All of them must reach the committed stroke. + let queued: Vec = (1..=6).map(|i| a + vec2(20.0 + i as f32 * 8.0, 0.0)).collect(); + for p in &queued { + h.input_mut().events.push(egui::Event::PointerMoved(*p)); + } + h.run_steps(1); + let end = *queued.last().unwrap(); + press(&mut h, end, PointerButton::Primary, false); + assert_committed_points(&h, &queued); +} From efe997d40e81cf17ea477c10533fc6bbd385a7ad Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:31 +0000 Subject: [PATCH 099/259] refactor(ui-egui): move brush_resize.rs tests to brush_resize/tests.rs --- crates/ui-egui/src/brush_resize.rs | 388 +---------------------- crates/ui-egui/src/brush_resize/tests.rs | 385 ++++++++++++++++++++++ 2 files changed, 386 insertions(+), 387 deletions(-) create mode 100644 crates/ui-egui/src/brush_resize/tests.rs diff --git a/crates/ui-egui/src/brush_resize.rs b/crates/ui-egui/src/brush_resize.rs index 5ff7beb9c9..1afba1bd1c 100644 --- a/crates/ui-egui/src/brush_resize.rs +++ b/crates/ui-egui/src/brush_resize.rs @@ -199,390 +199,4 @@ fn tip_preview(painter: &egui::Painter, c: Pos2, radius: f32, hardness: f32, col } #[cfg(test)] -mod tests { - use egui::{Modifiers, PointerButton, Pos2, vec2}; - use egui_kittest::Harness; - use serde_json::json; - - use super::*; - use crate::canvas::tool_event; - - const CTRL_ALT: Modifiers = Modifiers { alt: true, ctrl: true, shift: false, mac_cmd: false, command: false }; - - fn app(tool: Tool) -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 300, "height": 200, "background": "transparent"})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 40, "hardness": 0.2}})).unwrap(); - app.ui.tool = tool; - app - } - - fn history(app: &PhotocraftApp) -> usize { - app.session.active().unwrap().history.past_len() - } - - #[test] - fn mapping_is_bounded() { - assert_eq!(resized((40.0, 0.5), 10.0, 0.0, 1.0), (60.0, 0.5), "the edge follows the pointer"); - assert_eq!(resized((40.0, 0.5), 0.0, 50.0, 2.0), (40.0, 1.0), "down is harder, in screen points"); - assert_eq!(resized((40.0, 0.5), -1e9, -1e9, 1.0), (1.0, 0.0)); - assert_eq!(resized((40.0, 0.5), 1e9, 1e9, 1.0), (MAX_BRUSH_SIZE, 1.0)); - assert_eq!(resized((40.0, 0.5), f64::NAN, f64::INFINITY, f32::NAN), (40.0, 0.5)); - assert!(is_gesture(CTRL_ALT) && !is_gesture(Modifiers::ALT) && !is_gesture(Modifiers::CTRL) && !is_gesture(Modifiers::SHIFT)); - } - - #[test] - fn ctrl_alt_drag_resizes_every_brush_tool_without_painting_or_history() { - let tools: Vec = Tool::ALL.into_iter().filter(|t| applies(*t)).collect(); - assert!(tools.len() > 10 && tools.contains(&Tool::Brush) && tools.contains(&Tool::Eraser) && tools.contains(&Tool::CloneStamp)); - for tool in tools { - let mut app = app(tool); - let (h0, j0) = (history(&app), app.session.journal.len()); - tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, CTRL_ALT); - assert!(app.brush_resize.is_some() && app.drag.is_none(), "{tool:?}"); - // Right grows the size. - tool_event(&mut app, ToolEvent::Move { x: 130.0, y: 100.0, pressure: 1.0 }, CTRL_ALT); - assert_eq!(app.session.tools.brush.size, 100.0, "{tool:?}"); - // Down raises the hardness (at 100 %, 200 points take it from 0 to 100 %). - tool_event(&mut app, ToolEvent::Move { x: 130.0, y: 160.0, pressure: 1.0 }, CTRL_ALT); - assert_eq!(app.session.tools.brush.hardness, 0.5, "{tool:?}"); - // Letting go of the keys mid-drag keeps resizing until the button is released. - tool_event(&mut app, ToolEvent::Up { x: 120.0, y: 180.0 }, Modifiers::NONE); - let b = &app.session.tools.brush; - assert_eq!((b.size, b.hardness), (80.0, 0.6), "{tool:?}"); - assert!(app.brush_resize.is_none() && app.drag.is_none()); - // No history step, no paint: one coalesced tools.setBrush in the journal. - assert_eq!(history(&app), h0, "{tool:?}"); - let new: Vec<&str> = app.session.journal[j0..].iter().map(|(id, _)| id.as_str()).collect(); - assert_eq!(new, ["tools.setBrush"], "{tool:?}"); - assert_eq!(app.session.journal.last().unwrap().1["brush"], json!({"size": 80.0f32, "hardness": 0.6f32})); - } - } - - #[test] - fn other_tools_and_strokes_in_progress_are_untouched() { - let mut a = app(Tool::Move); - tool_event(&mut a, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, CTRL_ALT); - assert!(a.brush_resize.is_none()); - tool_event(&mut a, ToolEvent::Up { x: 10.0, y: 10.0 }, CTRL_ALT); - let mut a = app(Tool::Brush); - tool_event(&mut a, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, Modifiers::NONE); - tool_event(&mut a, ToolEvent::Move { x: 50.0, y: 10.0, pressure: 1.0 }, CTRL_ALT); - assert!(a.brush_resize.is_none(), "a stroke in progress isn't taken over"); - tool_event(&mut a, ToolEvent::Up { x: 50.0, y: 10.0 }, CTRL_ALT); - assert!(a.session.journal.iter().any(|(id, _)| id == "paint.stroke")); - assert_eq!(a.session.tools.brush.size, 40.0); - } - - #[test] - fn canvas_drag_shows_the_circle_and_readout() { - let mut a = app(Tool::Brush); - a.sync_views(); - 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; - } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); - }, - a, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); - h.run_steps(4); - let c = h.state().last_canvas_rect.center(); - let press = |h: &mut Harness<'static, PhotocraftApp>, pos: Pos2, pressed: bool| { - h.event(egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: CTRL_ALT }); - h.run(); - }; - h.event(egui::Event::ModifiersChanged(CTRL_ALT)); - h.event(egui::Event::PointerMoved(c)); - h.run(); - press(&mut h, c, true); - let size0 = h.state().session.tools.brush.size; - let undo0 = history(h.state()); - for k in 1..=6 { - h.event(egui::Event::PointerMoved(c + vec2(10.0 * k as f32, 8.0 * k as f32))); - h.run(); - } - assert!(h.state().brush_resize.is_some()); - assert!(h.state().session.tools.brush.size > size0, "dragging right grew the brush"); - assert!(h.state().session.tools.brush.hardness > 0.2, "dragging down hardened it"); - assert!(h.ctx.memory(|m| m.area_rect(egui::Id::unique("brush-resize-readout"))).is_some(), "the readout shows mid-drag"); - assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::None, "the pointer hides"); - press(&mut h, c + vec2(60.0, 48.0), false); - h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); - h.run_steps(2); - assert!(h.state().brush_resize.is_none()); - assert!(!h.state().session.journal.iter().any(|(id, _)| id == "paint.stroke"), "nothing painted"); - assert_eq!(history(h.state()), undo0, "no undo step"); - } - - fn canvas(a: PhotocraftApp) -> Harness<'static, PhotocraftApp> { - 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; - } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); - }, - a, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); - h.run_steps(4); - h - } - - fn button(h: &mut Harness<'static, PhotocraftApp>, pos: Pos2, button: PointerButton, pressed: bool, modifiers: Modifiers) { - h.event(egui::Event::PointerButton { pos, button, pressed, modifiers }); - h.run_steps(2); - } - - /// Alt+right-drag from the canvas centre, six steps of `step` screen points. - fn alt_right_drag(h: &mut Harness<'static, PhotocraftApp>, step: egui::Vec2) -> Pos2 { - let c = h.state().last_canvas_rect.center(); - h.event(egui::Event::ModifiersChanged(Modifiers::ALT)); - h.event(egui::Event::PointerMoved(c)); - h.run_steps(1); - button(h, c, PointerButton::Secondary, true, Modifiers::ALT); - let mut p = c; - for _ in 0..6 { - p += step; - h.event(egui::Event::PointerMoved(p)); - h.run_steps(1); - } - p - } - - #[test] - fn alt_right_drag_resizes_with_the_readout_and_never_paints() { - for erase_pref in [false, true] { - let mut a = app(Tool::Brush); - if erase_pref { - a.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": "erase"})).unwrap(); - } - a.sync_views(); - let mut h = canvas(a); - let (undo0, size0) = (history(h.state()), h.state().session.tools.brush.size); - let end = alt_right_drag(&mut h, vec2(10.0, 8.0)); - let r = h.state().brush_resize.expect("resizing"); - assert!(r.secondary); - assert!(h.state().session.tools.brush.size > size0, "right grows the brush"); - assert!(h.state().session.tools.brush.hardness > 0.2, "down hardens it"); - assert!(h.ctx.memory(|m| m.area_rect(egui::Id::unique("brush-resize-readout"))).is_some(), "the readout shows"); - assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::None); - button(&mut h, end, PointerButton::Secondary, false, Modifiers::ALT); - h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); - h.run_steps(2); - let app = h.state(); - assert!(app.brush_resize.is_none() && !app.brush_resize_armed && app.ui.brush_picker.is_none()); - assert!(!app.session.journal.iter().any(|(id, _)| id == "paint.stroke"), "nothing painted or erased (erase pref {erase_pref})"); - assert_eq!(history(app), undo0, "no undo step"); - let sets = app.session.journal.iter().filter(|(id, _)| id == "tools.setBrush").count(); - assert_eq!(sets, 2, "the setup call plus one coalesced resize"); - } - } - - /// Alt-right dragging changes tip size without loading paint or touching document history. - #[test] - fn mixer_alt_right_drag_resizes_without_sampling_or_painting() { - let mut a = app(Tool::MixerBrush); - let before = a.session.tools.mixer.clone(); - a.sync_views(); - let mut h = canvas(a); - let (undo0, size0) = (history(h.state()), h.state().session.tools.brush.size); - let end = alt_right_drag(&mut h, vec2(10.0, 8.0)); - assert!(h.state().brush_resize.is_some_and(|resize| resize.secondary)); - assert!(h.state().session.tools.brush.size > size0); - button(&mut h, end, PointerButton::Secondary, false, Modifiers::ALT); - h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); - h.run_steps(2); - let a = h.state(); - assert!(a.brush_resize.is_none() && !a.brush_resize_armed); - assert_eq!(a.session.tools.mixer, before); - assert_eq!(history(a), undo0); - assert!(!a.session.journal.iter().any(|(id, _)| id == "brush.mixer.sample" || id == "paint.mixerBrush")); - } - - #[test] - fn plain_right_click_still_opens_the_picker() { - let mut a = app(Tool::Brush); - a.sync_views(); - let mut h = canvas(a); - let c = h.state().last_canvas_rect.center(); - h.event(egui::Event::PointerMoved(c)); - h.run_steps(1); - button(&mut h, c, PointerButton::Secondary, true, Modifiers::NONE); - button(&mut h, c, PointerButton::Secondary, false, Modifiers::NONE); - assert!(h.state().ui.brush_picker.is_some() && h.state().brush_resize.is_none()); - // ⌥ alone on the left button stays the eyedropper, not a resize. - assert!(!is_gesture(Modifiers::ALT) && is_right_gesture(Modifiers::ALT)); - } - - #[test] - fn a_missed_release_never_leaves_the_resize_stuck() { - let mut a = app(Tool::Brush); - a.sync_views(); - let mut h = canvas(a); - // An Alt+right resize whose button-up never reached the canvas (released over another - // window, focus lost): the next canvas frame sees the right button up and ends it. - h.state_mut().brush_resize_armed = true; - tool_event(h.state_mut(), ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, Modifiers::NONE); - assert!(h.state().brush_resize.is_some_and(|r| r.secondary)); - h.run_steps(2); - assert!(h.state().brush_resize.is_none(), "released when the right button is up"); - // A plain left drag paints again. - let c = h.state().last_canvas_rect.center(); - h.event(egui::Event::WindowFocused(true)); - h.event(egui::Event::PointerMoved(c)); - h.run_steps(1); - button(&mut h, c, PointerButton::Primary, true, Modifiers::NONE); - for k in 1..=5 { - h.event(egui::Event::PointerMoved(c + vec2(12.0 * k as f32, 0.0))); - h.run_steps(1); - } - button(&mut h, c + vec2(60.0, 0.0), PointerButton::Primary, false, Modifiers::NONE); - assert!(h.state().session.journal.iter().any(|(id, _)| id == "paint.stroke"), "the stroke paints"); - } - - #[test] - fn an_armed_press_consumed_by_another_handler_disarms() { - // Free Transform is active: it takes every press, including an armed Alt+right one. - let mut a = app(Tool::Brush); - a.run("layer.new.layer", json!({})).unwrap(); - a.run("edit.fill", json!({"color": [1.0, 0.0, 0.0, 1.0]})).unwrap(); - let ctx = egui::Context::default(); - crate::transform_tool::begin(&mut a, &ctx).unwrap(); - assert!(a.ui.transform.is_some()); - a.brush_resize_armed = true; - tool_event(&mut a, ToolEvent::Down { x: 50.0, y: 50.0, pressure: 1.0 }, Modifiers::ALT); - tool_event(&mut a, ToolEvent::Up { x: 50.0, y: 50.0 }, Modifiers::ALT); - assert!(!a.brush_resize_armed, "the armed flag never outlives its press"); - assert!(a.brush_resize.is_none()); - crate::transform_tool::cancel(&mut a); - assert!(a.ui.transform.is_none()); - // The next plain press paints rather than resizing. - tool_event(&mut a, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, Modifiers::NONE); - assert!(a.brush_resize.is_none()); - tool_event(&mut a, ToolEvent::Move { x: 60.0, y: 20.0, pressure: 1.0 }, Modifiers::NONE); - tool_event(&mut a, ToolEvent::Up { x: 60.0, y: 20.0 }, Modifiers::NONE); - assert!(a.session.journal.iter().any(|(id, _)| id == "paint.stroke")); - } - - #[test] - fn agents_resize_with_an_alt_right_pointer_drag() { - let mut a = app(Tool::Brush); - let ctx = egui::Context::default(); - let events = json!([{"kind": "down", "x": 100, "y": 100}, {"kind": "move", "x": 120, "y": 100}, {"kind": "up", "x": 130, "y": 100}]); - let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"button": "right", "alt": true, "events": events})); - let _ = crate::control::handle(&mut a, &ctx, &req); - assert_eq!(a.session.tools.brush.size, 100.0, "40 px + 2 × 30"); - assert!(a.brush_resize.is_none() && !a.brush_resize_armed); - assert!(!a.session.journal.iter().any(|(id, _)| id == "paint.stroke")); - // Without Alt, a right press with the Brush opens the picker and paints nothing. - let events = json!([{"kind": "down", "x": 10, "y": 10}, {"kind": "up", "x": 10, "y": 10}]); - let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"button": "right", "events": events})); - let _ = crate::control::handle(&mut a, &ctx, &req); - assert_eq!(a.session.tools.brush.size, 100.0); - assert!(a.ui.brush_picker.is_some()); - } - - /// Preferences ▸ Tools ▸ Vary Round Brush Hardness on HUD (on by default): off, the HUD's - /// vertical movement takes the brush opacity instead of its hardness. - #[test] - fn vary_round_brush_hardness_on_hud_switches_the_vertical_target() { - for vary in [true, false] { - let mut app = app(Tool::Brush); - app.run("tools.setBrush", json!({"brush": {"opacity": 0.5}})).unwrap(); - if !vary { - app.run("prefs.set", json!({"path": "tools.varyRoundBrushHardnessOnHud", "value": false})).unwrap(); - } - let (h0, o0) = (app.session.tools.brush.hardness, app.session.tools.brush.opacity); - tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, CTRL_ALT); - tool_event(&mut app, ToolEvent::Move { x: 100.0, y: 140.0, pressure: 1.0 }, CTRL_ALT); - tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 140.0 }, CTRL_ALT); - let b = &app.session.tools.brush; - if vary { - assert_eq!((b.hardness, b.opacity), (h0 + 0.2, o0), "hardness moves with the drag"); - assert_eq!(app.session.journal.last().unwrap().1["brush"], json!({"size": 40.0f32, "hardness": 0.4f32})); - } else { - assert_eq!((b.hardness, b.opacity), (h0, o0 + 0.2), "opacity moves instead"); - assert_eq!(app.session.journal.last().unwrap().1["brush"], json!({"size": 40.0f32, "opacity": 0.7f32})); - } - } - } - - /// One Control+Alt drag by `(dx, dy)` document pixels from (100, 100) in a view turned by - /// `rotation` degrees (flipped with `flip`): the resulting (size, hardness). - fn drag_in_view(rotation: f32, flip: bool, dx: f64, dy: f64) -> (f32, f32) { - let mut app = app(Tool::Brush); - app.sync_views(); - app.ui.views[0].rotation = rotation; - app.ui.view.flip_horizontal = flip; - tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, CTRL_ALT); - tool_event(&mut app, ToolEvent::Up { x: 100.0 + dx, y: 100.0 + dy }, CTRL_ALT); - let b = &app.session.tools.brush; - (b.size, b.hardness) - } - - /// #4228: the HUD is screen-relative, as in Photoshop: horizontal on screen is the size and - /// vertical the hardness however the view is rotated or flipped. - #[test] - fn a_rotated_view_keeps_horizontal_for_size_and_vertical_for_hardness() { - // Unrotated, with and without View › Flip Horizontal: unchanged. - assert_eq!(drag_in_view(0.0, false, 30.0, 0.0), (100.0, 0.2), "right grows"); - assert_eq!(drag_in_view(0.0, false, 0.0, 40.0), (40.0, 0.4), "down hardens"); - assert_eq!(drag_in_view(0.0, true, -30.0, 0.0), (100.0, 0.2), "flipped: screen right grows"); - assert_eq!(drag_in_view(0.0, true, 0.0, 40.0), (40.0, 0.4), "flipped: down hardens"); - // 90° clockwise: document +y points screen-left and document +x screen-down. - assert_eq!(drag_in_view(90.0, false, 0.0, 10.0), (20.0, 0.2), "screen-left shrinks, the hardness stays"); - assert_eq!(drag_in_view(90.0, false, 0.0, -30.0), (100.0, 0.2), "screen-right grows"); - assert_eq!(drag_in_view(90.0, false, 40.0, 0.0), (40.0, 0.4), "screen-down hardens, the size stays"); - // 180°: document -x is screen right. - assert_eq!(drag_in_view(180.0, false, -30.0, 0.0), (100.0, 0.2), "screen right still grows"); - assert_eq!(drag_in_view(180.0, false, 0.0, -40.0), (40.0, 0.4), "screen down still hardens"); - // 90° and flipped: document +y points screen-right. - assert_eq!(drag_in_view(90.0, true, 0.0, 30.0), (100.0, 0.2), "rotated and flipped: screen right grows"); - } - - /// Preferences ▸ Cursors ▸ Brush Preview colour tints the HUD's tip preview (red by default). - #[test] - fn the_tip_preview_uses_the_brush_preview_colour() { - let mut app = app(Tool::Brush); - assert_eq!(preview_tint(&app), Color32::from_rgba_unmultiplied(255, 0, 0, 110)); - app.run("prefs.set", json!({"path": "cursors.brushPreviewColor", "value": "#00ff80"})).unwrap(); - assert_eq!(preview_tint(&app), Color32::from_rgba_unmultiplied(0, 255, 128, 110)); - app.session.prefs.edit(|p| p.cursors.brush_preview_color = "nonsense".into()); - assert_eq!(preview_tint(&app), Color32::from_rgba_unmultiplied(255, 0, 0, 110), "unreadable values keep the red"); - } - - #[test] - fn stylus_barrel_button_resizes_with_alt_and_never_samples_color() { - let mut a = app(Tool::Brush); - a.services.right_button_down = Some(Box::new(|| true)); - a.sync_views(); - let mut h = canvas(a); - let size0 = h.state().session.tools.brush.size; - let c = h.state().last_canvas_rect.center(); - h.event(egui::Event::ModifiersChanged(Modifiers::ALT)); - h.event(egui::Event::PointerMoved(c)); - h.run_steps(1); - button(&mut h, c, PointerButton::Primary, true, Modifiers::ALT); - let mut p = c; - for _ in 0..6 { - p += vec2(10.0, 8.0); - h.event(egui::Event::PointerMoved(p)); - h.run_steps(1); - } - let r = h.state().brush_resize.expect("resizing via stylus barrel button"); - assert!(r.secondary); - assert!(h.state().session.tools.brush.size > size0, "right grows the brush"); - assert!(h.state().session.tools.brush.hardness > 0.2, "down hardens the brush"); - assert!(!h.state().alt_sampling, "eyedropper never triggered"); - assert!(!h.state().session.journal.iter().any(|(id, _)| id == "paint.stroke"), "nothing painted"); - button(&mut h, p, PointerButton::Primary, false, Modifiers::ALT); - h.run_steps(2); - assert!(h.state().brush_resize.is_none()); - } -} +mod tests; diff --git a/crates/ui-egui/src/brush_resize/tests.rs b/crates/ui-egui/src/brush_resize/tests.rs new file mode 100644 index 0000000000..6967c7bb9a --- /dev/null +++ b/crates/ui-egui/src/brush_resize/tests.rs @@ -0,0 +1,385 @@ +use egui::{Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use super::*; +use crate::canvas::tool_event; + +const CTRL_ALT: Modifiers = Modifiers { alt: true, ctrl: true, shift: false, mac_cmd: false, command: false }; + +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200, "background": "transparent"})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 40, "hardness": 0.2}})).unwrap(); + app.ui.tool = tool; + app +} + +fn history(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +#[test] +fn mapping_is_bounded() { + assert_eq!(resized((40.0, 0.5), 10.0, 0.0, 1.0), (60.0, 0.5), "the edge follows the pointer"); + assert_eq!(resized((40.0, 0.5), 0.0, 50.0, 2.0), (40.0, 1.0), "down is harder, in screen points"); + assert_eq!(resized((40.0, 0.5), -1e9, -1e9, 1.0), (1.0, 0.0)); + assert_eq!(resized((40.0, 0.5), 1e9, 1e9, 1.0), (MAX_BRUSH_SIZE, 1.0)); + assert_eq!(resized((40.0, 0.5), f64::NAN, f64::INFINITY, f32::NAN), (40.0, 0.5)); + assert!(is_gesture(CTRL_ALT) && !is_gesture(Modifiers::ALT) && !is_gesture(Modifiers::CTRL) && !is_gesture(Modifiers::SHIFT)); +} + +#[test] +fn ctrl_alt_drag_resizes_every_brush_tool_without_painting_or_history() { + let tools: Vec = Tool::ALL.into_iter().filter(|t| applies(*t)).collect(); + assert!(tools.len() > 10 && tools.contains(&Tool::Brush) && tools.contains(&Tool::Eraser) && tools.contains(&Tool::CloneStamp)); + for tool in tools { + let mut app = app(tool); + let (h0, j0) = (history(&app), app.session.journal.len()); + tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, CTRL_ALT); + assert!(app.brush_resize.is_some() && app.drag.is_none(), "{tool:?}"); + // Right grows the size. + tool_event(&mut app, ToolEvent::Move { x: 130.0, y: 100.0, pressure: 1.0 }, CTRL_ALT); + assert_eq!(app.session.tools.brush.size, 100.0, "{tool:?}"); + // Down raises the hardness (at 100 %, 200 points take it from 0 to 100 %). + tool_event(&mut app, ToolEvent::Move { x: 130.0, y: 160.0, pressure: 1.0 }, CTRL_ALT); + assert_eq!(app.session.tools.brush.hardness, 0.5, "{tool:?}"); + // Letting go of the keys mid-drag keeps resizing until the button is released. + tool_event(&mut app, ToolEvent::Up { x: 120.0, y: 180.0 }, Modifiers::NONE); + let b = &app.session.tools.brush; + assert_eq!((b.size, b.hardness), (80.0, 0.6), "{tool:?}"); + assert!(app.brush_resize.is_none() && app.drag.is_none()); + // No history step, no paint: one coalesced tools.setBrush in the journal. + assert_eq!(history(&app), h0, "{tool:?}"); + let new: Vec<&str> = app.session.journal[j0..].iter().map(|(id, _)| id.as_str()).collect(); + assert_eq!(new, ["tools.setBrush"], "{tool:?}"); + assert_eq!(app.session.journal.last().unwrap().1["brush"], json!({"size": 80.0f32, "hardness": 0.6f32})); + } +} + +#[test] +fn other_tools_and_strokes_in_progress_are_untouched() { + let mut a = app(Tool::Move); + tool_event(&mut a, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, CTRL_ALT); + assert!(a.brush_resize.is_none()); + tool_event(&mut a, ToolEvent::Up { x: 10.0, y: 10.0 }, CTRL_ALT); + let mut a = app(Tool::Brush); + tool_event(&mut a, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut a, ToolEvent::Move { x: 50.0, y: 10.0, pressure: 1.0 }, CTRL_ALT); + assert!(a.brush_resize.is_none(), "a stroke in progress isn't taken over"); + tool_event(&mut a, ToolEvent::Up { x: 50.0, y: 10.0 }, CTRL_ALT); + assert!(a.session.journal.iter().any(|(id, _)| id == "paint.stroke")); + assert_eq!(a.session.tools.brush.size, 40.0); +} + +#[test] +fn canvas_drag_shows_the_circle_and_readout() { + let mut a = app(Tool::Brush); + a.sync_views(); + 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; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + a, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.run_steps(4); + let c = h.state().last_canvas_rect.center(); + let press = |h: &mut Harness<'static, PhotocraftApp>, pos: Pos2, pressed: bool| { + h.event(egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: CTRL_ALT }); + h.run(); + }; + h.event(egui::Event::ModifiersChanged(CTRL_ALT)); + h.event(egui::Event::PointerMoved(c)); + h.run(); + press(&mut h, c, true); + let size0 = h.state().session.tools.brush.size; + let undo0 = history(h.state()); + for k in 1..=6 { + h.event(egui::Event::PointerMoved(c + vec2(10.0 * k as f32, 8.0 * k as f32))); + h.run(); + } + assert!(h.state().brush_resize.is_some()); + assert!(h.state().session.tools.brush.size > size0, "dragging right grew the brush"); + assert!(h.state().session.tools.brush.hardness > 0.2, "dragging down hardened it"); + assert!(h.ctx.memory(|m| m.area_rect(egui::Id::unique("brush-resize-readout"))).is_some(), "the readout shows mid-drag"); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::None, "the pointer hides"); + press(&mut h, c + vec2(60.0, 48.0), false); + h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + assert!(h.state().brush_resize.is_none()); + assert!(!h.state().session.journal.iter().any(|(id, _)| id == "paint.stroke"), "nothing painted"); + assert_eq!(history(h.state()), undo0, "no undo step"); +} + +fn canvas(a: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + 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; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + a, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.run_steps(4); + h +} + +fn button(h: &mut Harness<'static, PhotocraftApp>, pos: Pos2, button: PointerButton, pressed: bool, modifiers: Modifiers) { + h.event(egui::Event::PointerButton { pos, button, pressed, modifiers }); + h.run_steps(2); +} + +/// Alt+right-drag from the canvas centre, six steps of `step` screen points. +fn alt_right_drag(h: &mut Harness<'static, PhotocraftApp>, step: egui::Vec2) -> Pos2 { + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::ModifiersChanged(Modifiers::ALT)); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + button(h, c, PointerButton::Secondary, true, Modifiers::ALT); + let mut p = c; + for _ in 0..6 { + p += step; + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + } + p +} + +#[test] +fn alt_right_drag_resizes_with_the_readout_and_never_paints() { + for erase_pref in [false, true] { + let mut a = app(Tool::Brush); + if erase_pref { + a.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": "erase"})).unwrap(); + } + a.sync_views(); + let mut h = canvas(a); + let (undo0, size0) = (history(h.state()), h.state().session.tools.brush.size); + let end = alt_right_drag(&mut h, vec2(10.0, 8.0)); + let r = h.state().brush_resize.expect("resizing"); + assert!(r.secondary); + assert!(h.state().session.tools.brush.size > size0, "right grows the brush"); + assert!(h.state().session.tools.brush.hardness > 0.2, "down hardens it"); + assert!(h.ctx.memory(|m| m.area_rect(egui::Id::unique("brush-resize-readout"))).is_some(), "the readout shows"); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::None); + button(&mut h, end, PointerButton::Secondary, false, Modifiers::ALT); + h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + let app = h.state(); + assert!(app.brush_resize.is_none() && !app.brush_resize_armed && app.ui.brush_picker.is_none()); + assert!(!app.session.journal.iter().any(|(id, _)| id == "paint.stroke"), "nothing painted or erased (erase pref {erase_pref})"); + assert_eq!(history(app), undo0, "no undo step"); + let sets = app.session.journal.iter().filter(|(id, _)| id == "tools.setBrush").count(); + assert_eq!(sets, 2, "the setup call plus one coalesced resize"); + } +} + +/// Alt-right dragging changes tip size without loading paint or touching document history. +#[test] +fn mixer_alt_right_drag_resizes_without_sampling_or_painting() { + let mut a = app(Tool::MixerBrush); + let before = a.session.tools.mixer.clone(); + a.sync_views(); + let mut h = canvas(a); + let (undo0, size0) = (history(h.state()), h.state().session.tools.brush.size); + let end = alt_right_drag(&mut h, vec2(10.0, 8.0)); + assert!(h.state().brush_resize.is_some_and(|resize| resize.secondary)); + assert!(h.state().session.tools.brush.size > size0); + button(&mut h, end, PointerButton::Secondary, false, Modifiers::ALT); + h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + let a = h.state(); + assert!(a.brush_resize.is_none() && !a.brush_resize_armed); + assert_eq!(a.session.tools.mixer, before); + assert_eq!(history(a), undo0); + assert!(!a.session.journal.iter().any(|(id, _)| id == "brush.mixer.sample" || id == "paint.mixerBrush")); +} + +#[test] +fn plain_right_click_still_opens_the_picker() { + let mut a = app(Tool::Brush); + a.sync_views(); + let mut h = canvas(a); + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + button(&mut h, c, PointerButton::Secondary, true, Modifiers::NONE); + button(&mut h, c, PointerButton::Secondary, false, Modifiers::NONE); + assert!(h.state().ui.brush_picker.is_some() && h.state().brush_resize.is_none()); + // ⌥ alone on the left button stays the eyedropper, not a resize. + assert!(!is_gesture(Modifiers::ALT) && is_right_gesture(Modifiers::ALT)); +} + +#[test] +fn a_missed_release_never_leaves_the_resize_stuck() { + let mut a = app(Tool::Brush); + a.sync_views(); + let mut h = canvas(a); + // An Alt+right resize whose button-up never reached the canvas (released over another + // window, focus lost): the next canvas frame sees the right button up and ends it. + h.state_mut().brush_resize_armed = true; + tool_event(h.state_mut(), ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, Modifiers::NONE); + assert!(h.state().brush_resize.is_some_and(|r| r.secondary)); + h.run_steps(2); + assert!(h.state().brush_resize.is_none(), "released when the right button is up"); + // A plain left drag paints again. + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::WindowFocused(true)); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + button(&mut h, c, PointerButton::Primary, true, Modifiers::NONE); + for k in 1..=5 { + h.event(egui::Event::PointerMoved(c + vec2(12.0 * k as f32, 0.0))); + h.run_steps(1); + } + button(&mut h, c + vec2(60.0, 0.0), PointerButton::Primary, false, Modifiers::NONE); + assert!(h.state().session.journal.iter().any(|(id, _)| id == "paint.stroke"), "the stroke paints"); +} + +#[test] +fn an_armed_press_consumed_by_another_handler_disarms() { + // Free Transform is active: it takes every press, including an armed Alt+right one. + let mut a = app(Tool::Brush); + a.run("layer.new.layer", json!({})).unwrap(); + a.run("edit.fill", json!({"color": [1.0, 0.0, 0.0, 1.0]})).unwrap(); + let ctx = egui::Context::default(); + crate::transform_tool::begin(&mut a, &ctx).unwrap(); + assert!(a.ui.transform.is_some()); + a.brush_resize_armed = true; + tool_event(&mut a, ToolEvent::Down { x: 50.0, y: 50.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut a, ToolEvent::Up { x: 50.0, y: 50.0 }, Modifiers::ALT); + assert!(!a.brush_resize_armed, "the armed flag never outlives its press"); + assert!(a.brush_resize.is_none()); + crate::transform_tool::cancel(&mut a); + assert!(a.ui.transform.is_none()); + // The next plain press paints rather than resizing. + tool_event(&mut a, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, Modifiers::NONE); + assert!(a.brush_resize.is_none()); + tool_event(&mut a, ToolEvent::Move { x: 60.0, y: 20.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut a, ToolEvent::Up { x: 60.0, y: 20.0 }, Modifiers::NONE); + assert!(a.session.journal.iter().any(|(id, _)| id == "paint.stroke")); +} + +#[test] +fn agents_resize_with_an_alt_right_pointer_drag() { + let mut a = app(Tool::Brush); + let ctx = egui::Context::default(); + let events = json!([{"kind": "down", "x": 100, "y": 100}, {"kind": "move", "x": 120, "y": 100}, {"kind": "up", "x": 130, "y": 100}]); + let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"button": "right", "alt": true, "events": events})); + let _ = crate::control::handle(&mut a, &ctx, &req); + assert_eq!(a.session.tools.brush.size, 100.0, "40 px + 2 × 30"); + assert!(a.brush_resize.is_none() && !a.brush_resize_armed); + assert!(!a.session.journal.iter().any(|(id, _)| id == "paint.stroke")); + // Without Alt, a right press with the Brush opens the picker and paints nothing. + let events = json!([{"kind": "down", "x": 10, "y": 10}, {"kind": "up", "x": 10, "y": 10}]); + let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"button": "right", "events": events})); + let _ = crate::control::handle(&mut a, &ctx, &req); + assert_eq!(a.session.tools.brush.size, 100.0); + assert!(a.ui.brush_picker.is_some()); +} + +/// Preferences ▸ Tools ▸ Vary Round Brush Hardness on HUD (on by default): off, the HUD's +/// vertical movement takes the brush opacity instead of its hardness. +#[test] +fn vary_round_brush_hardness_on_hud_switches_the_vertical_target() { + for vary in [true, false] { + let mut app = app(Tool::Brush); + app.run("tools.setBrush", json!({"brush": {"opacity": 0.5}})).unwrap(); + if !vary { + app.run("prefs.set", json!({"path": "tools.varyRoundBrushHardnessOnHud", "value": false})).unwrap(); + } + let (h0, o0) = (app.session.tools.brush.hardness, app.session.tools.brush.opacity); + tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, CTRL_ALT); + tool_event(&mut app, ToolEvent::Move { x: 100.0, y: 140.0, pressure: 1.0 }, CTRL_ALT); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 140.0 }, CTRL_ALT); + let b = &app.session.tools.brush; + if vary { + assert_eq!((b.hardness, b.opacity), (h0 + 0.2, o0), "hardness moves with the drag"); + assert_eq!(app.session.journal.last().unwrap().1["brush"], json!({"size": 40.0f32, "hardness": 0.4f32})); + } else { + assert_eq!((b.hardness, b.opacity), (h0, o0 + 0.2), "opacity moves instead"); + assert_eq!(app.session.journal.last().unwrap().1["brush"], json!({"size": 40.0f32, "opacity": 0.7f32})); + } + } +} + +/// One Control+Alt drag by `(dx, dy)` document pixels from (100, 100) in a view turned by +/// `rotation` degrees (flipped with `flip`): the resulting (size, hardness). +fn drag_in_view(rotation: f32, flip: bool, dx: f64, dy: f64) -> (f32, f32) { + let mut app = app(Tool::Brush); + app.sync_views(); + app.ui.views[0].rotation = rotation; + app.ui.view.flip_horizontal = flip; + tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, CTRL_ALT); + tool_event(&mut app, ToolEvent::Up { x: 100.0 + dx, y: 100.0 + dy }, CTRL_ALT); + let b = &app.session.tools.brush; + (b.size, b.hardness) +} + +/// #4228: the HUD is screen-relative, as in Photoshop: horizontal on screen is the size and +/// vertical the hardness however the view is rotated or flipped. +#[test] +fn a_rotated_view_keeps_horizontal_for_size_and_vertical_for_hardness() { + // Unrotated, with and without View › Flip Horizontal: unchanged. + assert_eq!(drag_in_view(0.0, false, 30.0, 0.0), (100.0, 0.2), "right grows"); + assert_eq!(drag_in_view(0.0, false, 0.0, 40.0), (40.0, 0.4), "down hardens"); + assert_eq!(drag_in_view(0.0, true, -30.0, 0.0), (100.0, 0.2), "flipped: screen right grows"); + assert_eq!(drag_in_view(0.0, true, 0.0, 40.0), (40.0, 0.4), "flipped: down hardens"); + // 90° clockwise: document +y points screen-left and document +x screen-down. + assert_eq!(drag_in_view(90.0, false, 0.0, 10.0), (20.0, 0.2), "screen-left shrinks, the hardness stays"); + assert_eq!(drag_in_view(90.0, false, 0.0, -30.0), (100.0, 0.2), "screen-right grows"); + assert_eq!(drag_in_view(90.0, false, 40.0, 0.0), (40.0, 0.4), "screen-down hardens, the size stays"); + // 180°: document -x is screen right. + assert_eq!(drag_in_view(180.0, false, -30.0, 0.0), (100.0, 0.2), "screen right still grows"); + assert_eq!(drag_in_view(180.0, false, 0.0, -40.0), (40.0, 0.4), "screen down still hardens"); + // 90° and flipped: document +y points screen-right. + assert_eq!(drag_in_view(90.0, true, 0.0, 30.0), (100.0, 0.2), "rotated and flipped: screen right grows"); +} + +/// Preferences ▸ Cursors ▸ Brush Preview colour tints the HUD's tip preview (red by default). +#[test] +fn the_tip_preview_uses_the_brush_preview_colour() { + let mut app = app(Tool::Brush); + assert_eq!(preview_tint(&app), Color32::from_rgba_unmultiplied(255, 0, 0, 110)); + app.run("prefs.set", json!({"path": "cursors.brushPreviewColor", "value": "#00ff80"})).unwrap(); + assert_eq!(preview_tint(&app), Color32::from_rgba_unmultiplied(0, 255, 128, 110)); + app.session.prefs.edit(|p| p.cursors.brush_preview_color = "nonsense".into()); + assert_eq!(preview_tint(&app), Color32::from_rgba_unmultiplied(255, 0, 0, 110), "unreadable values keep the red"); +} + +#[test] +fn stylus_barrel_button_resizes_with_alt_and_never_samples_color() { + let mut a = app(Tool::Brush); + a.services.right_button_down = Some(Box::new(|| true)); + a.sync_views(); + let mut h = canvas(a); + let size0 = h.state().session.tools.brush.size; + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::ModifiersChanged(Modifiers::ALT)); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + button(&mut h, c, PointerButton::Primary, true, Modifiers::ALT); + let mut p = c; + for _ in 0..6 { + p += vec2(10.0, 8.0); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + } + let r = h.state().brush_resize.expect("resizing via stylus barrel button"); + assert!(r.secondary); + assert!(h.state().session.tools.brush.size > size0, "right grows the brush"); + assert!(h.state().session.tools.brush.hardness > 0.2, "down hardens the brush"); + assert!(!h.state().alt_sampling, "eyedropper never triggered"); + assert!(!h.state().session.journal.iter().any(|(id, _)| id == "paint.stroke"), "nothing painted"); + button(&mut h, p, PointerButton::Primary, false, Modifiers::ALT); + h.run_steps(2); + assert!(h.state().brush_resize.is_none()); +} From 5c9367bc87ab2e8596769df14665cc0afc1f485a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:31 +0000 Subject: [PATCH 100/259] refactor(ui-egui): move caf_ui.rs tests to caf_ui/tests.rs --- crates/ui-egui/src/caf_ui.rs | 480 +---------------------------- crates/ui-egui/src/caf_ui/tests.rs | 474 ++++++++++++++++++++++++++++ 2 files changed, 475 insertions(+), 479 deletions(-) create mode 100644 crates/ui-egui/src/caf_ui/tests.rs diff --git a/crates/ui-egui/src/caf_ui.rs b/crates/ui-egui/src/caf_ui.rs index aaa7978e23..f0f6f8cb1e 100644 --- a/crates/ui-egui/src/caf_ui.rs +++ b/crates/ui-egui/src/caf_ui.rs @@ -1608,482 +1608,4 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { } #[cfg(test)] -mod tests { - use super::*; - - /// A textured layer (a checker of two colours over a gradient) with a 20 px square selected. - fn app_with_selection() -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", json!({"width": 200, "height": 160, "depth": 8})).unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, active| { - let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in 0..160 { - for x in 0..200 { - let v = ((x / 6 + y / 6) % 2) as f32 * 0.5 + x as f32 / 400.0; - s.write_pixel(x, y, &[v, 0.3, 1.0 - v, 1.0]); - } - } - // A red blemish to remove. - for y in 72..88 { - for x in 92..108 { - s.write_pixel(x, y, &[1.0, 0.0, 0.0, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - app.session.execute("select.rect", json!({"x": 90, "y": 70, "width": 20, "height": 20})).unwrap(); - app.sync_views(); - app - } - - fn px(app: &PhotocraftApp, layer: LayerId, x: i32, y: i32) -> Vec { - app.session.active().unwrap().doc.layer(layer).unwrap().surface().unwrap().pixel(x, y) - } - - fn ws(app: &PhotocraftApp) -> &CafWorkspace { - app.distort.caf.as_ref().unwrap() - } - - #[test] - fn settings_dropdowns_are_named_for_their_visible_labels() { - use egui::accesskit::Role; - use egui_kittest::Harness; - use egui_kittest::kittest::{NodeT, Queryable}; - - let mut app = app_with_selection(); - open(&mut app).unwrap(); - let mut h = Harness::builder() - .with_size(egui::vec2(1000.0, 900.0)) - .with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0])) - .build_ui_state(|ui, app: &mut PhotocraftApp| show(app, ui.ctx()), app); - h.run_steps(2); - // The Indicates dropdown lives inside a collapsed "Sampling Area Overlay" header. - h.get_by_role_and_label(Role::DisclosureTriangle, "Sampling Area Overlay").click(); - h.run_steps(3); - let labels: Vec = h.query_all_by_role(Role::ComboBox).filter_map(|n| n.accesskit_node().label()).collect(); - for label in ["Indicates", "Color Adaptation", "Rotation Adaptation", "Output To"] { - assert!(labels.iter().any(|have| have == label), "{label} names its dropdown: {labels:?}"); - } - for wrong in ["Contents:", "Color", "Rotation", "Source"] { - assert!(!labels.iter().any(|have| have == wrong), "{wrong} names no control here: {labels:?}"); - } - } - - /// Photoshop opens the workspace with the Sampling Brush subtracting at a tenth of the - /// window's side, Auto sampling, output to a new layer. - #[test] - fn opens_like_photoshop() { - let mut app = app_with_selection(); - app.session.prefs.edit(|p| { - p.dialogs.remove(REMEMBERED); - }); - open(&mut app).unwrap(); - let d = ws(&app).describe(); - assert_eq!(d["window"], json!([0, 0, 200, 160]), "a 200 px window, clipped to the 200 × 160 canvas"); - assert_eq!((d["tool"].as_str(), d["brushMode"].as_str(), d["brushSize"].as_f64()), (Some("brush"), Some("subtract"), Some(20.0))); - assert_eq!((d["settings"]["sampling"].as_str(), d["settings"]["output"].as_str()), (Some("auto"), Some("new"))); - assert_eq!(d["fillArea"], json!(400)); - assert!(d["sampledProxyPixels"].as_u64().unwrap() > 1000); - } - - #[test] - fn brush_strokes_change_the_sampling_area_and_undo() { - let mut app = app_with_selection(); - open(&mut app).unwrap(); - control(&mut app, &json!({"sampling": "rectangular"})).unwrap(); - let all = ws(&app).describe()["sampledProxyPixels"].as_u64().unwrap(); - assert_eq!(all, 200 * 160 - 400, "Rectangular: the whole window but the fill area"); - // Subtracting (the default): a 10 px stroke takes about 10 × 60 px away. - let d = control(&mut app, &json!({"stroke": {"points": [[20.0, 20.0], [80.0, 20.0]], "size": 10}})).unwrap(); - let less = d["sampledProxyPixels"].as_u64().unwrap(); - assert!((all - less).abs_diff(10 * 60 + 79) < 120, "{all} → {less}"); - // Undo brings it back; redo takes it again. - assert_eq!(control(&mut app, &json!({"undo": true})).unwrap()["sampledProxyPixels"].as_u64(), Some(all)); - assert_eq!(control(&mut app, &json!({"redo": true})).unwrap()["sampledProxyPixels"].as_u64(), Some(less)); - // Custom starts empty and the brush adds; Alt reverses it. - let d = control(&mut app, &json!({"sampling": "custom"})).unwrap(); - assert_eq!((d["sampledProxyPixels"].as_u64(), d["brushMode"].as_str(), d["strokes"].as_u64()), (Some(0), Some("add"), Some(0))); - let d = control(&mut app, &json!({"stroke": {"points": [[20.0, 120.0], [60.0, 120.0]], "size": 8}})).unwrap(); - assert!(d["sampledProxyPixels"].as_u64().unwrap() > 300); - let d = control(&mut app, &json!({"stroke": {"points": [[20.0, 120.0], [60.0, 120.0]], "size": 8, "alt": true}})).unwrap(); - assert_eq!(d["sampledProxyPixels"].as_u64(), Some(0)); - // Undoing the change of option restores Rectangular with its stroke. - control(&mut app, &json!({"undo": true})).unwrap(); - control(&mut app, &json!({"undo": true})).unwrap(); - let d = control(&mut app, &json!({"undo": true})).unwrap(); - assert_eq!((d["settings"]["sampling"].as_str(), d["strokes"].as_u64(), d["brushMode"].as_str()), (Some("rectangular"), Some(1), Some("subtract"))); - } - - #[test] - fn the_lasso_edits_the_fill_area_and_the_window_follows() { - let mut app = app_with_selection(); - open(&mut app).unwrap(); - let d = control(&mut app, &json!({"lasso": {"op": "add", "points": [[130.0, 70.0], [150.0, 70.0], [150.0, 90.0], [130.0, 90.0]]}})).unwrap(); - assert_eq!(d["fillArea"], json!(800)); - let d = control(&mut app, &json!({"expand": 2})).unwrap(); - assert!(d["fillArea"].as_u64().unwrap() > 900); - let d = control(&mut app, &json!({"undo": true, "lassoMode": "subtract"})).unwrap(); - assert_eq!((d["fillArea"].as_u64(), d["lassoMode"].as_str()), (Some(800), Some("subtract"))); - // Subtracting everything is refused: the fill area can't be empty. - let d = control(&mut app, &json!({"lasso": {"points": [[0.0, 0.0], [200.0, 0.0], [200.0, 160.0], [0.0, 160.0]]}})).unwrap(); - assert_eq!(d["fillArea"], json!(800)); - assert!(d["error"].as_str().is_some_and(|e| e.contains("empty")), "{d}"); - // The reset button goes back to the selection. - let d = control(&mut app, &json!({"reset": "lasso"})).unwrap(); - assert_eq!(d["fillArea"], json!(400)); - } - - /// A sampling area the Sampling Brush erased entirely previews as an error naming the - /// problem, not as the black fill it would make; undoing the stroke brings the preview back. - #[test] - fn an_erased_sampling_area_previews_as_an_error() { - let mut app = app_with_selection(); - open(&mut app).unwrap(); - control(&mut app, &json!({"sampling": "rectangular", "waitPreview": true})).unwrap(); - assert!(ws(&app).describe()["previewError"].is_null()); - // Subtracting (the default) with a brush wider than the 200 × 160 window. - let e = control(&mut app, &json!({"stroke": {"points": [[100.0, 80.0]], "size": 600}, "waitPreview": true})).unwrap_err(); - assert!(e.contains("nothing to sample from"), "{e}"); - let d = ws(&app).describe(); - assert_eq!(d["sampledProxyPixels"].as_u64(), Some(0), "{d}"); - assert!(d["previewError"].as_str().is_some_and(|e| e.contains("nothing to sample from")), "{d}"); - let d = control(&mut app, &json!({"undo": true, "waitPreview": true})).unwrap(); - assert!(d["previewError"].is_null(), "{d}"); - } - - /// OK whose fill fails keeps the workspace open with the error in its panel, from the button - /// and from the control channel, so the work isn't thrown away; once the fill can run, OK - /// fills and closes. - #[test] - fn a_failed_ok_keeps_the_workspace_open() { - let mut app = app_with_selection(); - open(&mut app).unwrap(); - let steps = app.session.active().unwrap().history.past_len(); - app.session.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap(); - commit(&mut app); - assert!(app.distort.caf.is_some(), "OK keeps the workspace open when the fill fails"); - assert!(ws(&app).error.as_deref().is_some_and(|e| e.contains("locked")), "{:?}", ws(&app).error); - assert!(app.ui.status_error); - assert!(control(&mut app, &json!({"commit": true})).unwrap_err().contains("locked")); - assert!(app.distort.caf.is_some(), "the control channel's OK too"); - app.session.execute("layer.setProps", json!({"locks": {"pixels": false}})).unwrap(); - let steps = app.session.active().unwrap().history.past_len().max(steps); - commit(&mut app); - assert!(app.distort.caf.is_none(), "OK closes once the fill runs"); - assert!(app.session.active().unwrap().history.past_len() > steps, "and fills"); - } - - /// Undo or Redo of a sampling stroke changes what OK would fill, so it clears the error a - /// failed OK left in the panel, as a new stroke does; otherwise the stale error would stay - /// drawn over the recovered preview. - #[test] - fn undo_and_redo_of_a_stroke_clear_a_failed_oks_error() { - let mut app = app_with_selection(); - open(&mut app).unwrap(); - control(&mut app, &json!({"stroke": {"points": [[20.0, 20.0], [60.0, 20.0]], "size": 10}})).unwrap(); - app.session.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap(); - commit(&mut app); - assert!(ws(&app).error.is_some(), "the failed OK reports in the panel"); - control(&mut app, &json!({"undo": true})).unwrap(); - assert!(ws(&app).error.is_none(), "Undo of the stroke clears it"); - commit(&mut app); - assert!(ws(&app).error.is_some()); - control(&mut app, &json!({"redo": true})).unwrap(); - assert!(ws(&app).error.is_none(), "Redo of the stroke clears it too"); - } - - #[test] - fn apply_fills_and_stays_open_ok_closes_cancel_keeps_what_was_applied() { - let mut app = app_with_selection(); - let layer = app.session.active().unwrap().active_layer.unwrap(); - open(&mut app).unwrap(); - // The preview is what Apply writes. - control(&mut app, &json!({"output": "current", "colorAdaptation": "none", "waitPreview": true})).unwrap(); - let (rect, img) = ws(&app).preview.pending_image.clone().unwrap(); - control(&mut app, &json!({"apply": true})).unwrap(); - assert!(app.distort.caf.is_some(), "Apply keeps the workspace open"); - let after = px(&app, layer, 100, 80); - assert!(after[0] < 0.9 || after[1] > 0.1, "the blemish is filled: {after:?}"); - let i = ((80 - rect.y0) * rect.width() as i32 + (100 - rect.x0)) as usize; - let shown = img.pixels[i]; - assert!( - (f32::from(shown.r()) / 255.0 - after[0]).abs() < 0.01 && (f32::from(shown.b()) / 255.0 - after[2]).abs() < 0.01, - "preview {shown:?} vs {after:?}" - ); - let steps = app.session.active().unwrap().history.past_len(); - cancel(&mut app); - assert!(app.distort.caf.is_none()); - assert_eq!(app.session.active().unwrap().history.past_len(), steps, "Cancel keeps the applied fill"); - // OK with New Layer: a new layer holds the fill; the original stays. - app.session.execute("edit.undo", json!({})).unwrap(); - open(&mut app).unwrap(); - control(&mut app, &json!({"output": "new", "commit": true})).unwrap(); - assert!(app.distort.caf.is_none()); - assert_eq!(px(&app, layer, 100, 80)[0], 1.0, "the original layer keeps its blemish"); - let top = app.session.active().unwrap().active_layer.unwrap(); - assert_ne!(top, layer); - assert!(px(&app, top, 100, 80)[3] > 0.99, "the new layer holds the fill"); - } - - /// #5092: the workspace left open does not follow the user to another document, and closing - /// the document it was opened on closes it. - #[test] - fn the_workspace_is_dropped_when_another_document_becomes_active() { - let mut app = app_with_selection(); - open(&mut app).unwrap(); - crate::distort_ui::drop_foreign(&mut app); - assert!(app.distort.caf.is_some()); - app.session.execute("file.new", json!({"width": 32, "height": 32, "depth": 8})).unwrap(); - crate::distort_ui::drop_foreign(&mut app); - assert!(app.distort.caf.is_none()); - assert!(app.session.set_active(0)); - open(&mut app).unwrap(); - crate::distort_ui::drop_foreign(&mut app); - assert!(app.distort.caf.is_some()); - assert!(app.session.close(0).is_some()); - crate::distort_ui::drop_foreign(&mut app); - assert!(app.distort.caf.is_none()); - } - - #[test] - fn settings_are_remembered_and_the_menu_opens_the_workspace() { - let ctx = egui::Context::default(); - let mut app = app_with_selection(); - let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({})).unwrap(); - assert!(r["contentAwareFill"]["window"].is_array(), "{r}"); - let set = json!({"opacity": 30, "color": [200, 40, 40], "excluded": true, "colorAdaptation": "high", "rotationAdaptation": "low", "mirror": true, "output": "duplicate"}); - crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({"ui": set})).unwrap(); - crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({"ui": {"cancel": true}})).unwrap(); - open(&mut app).unwrap(); - let mut want = CafOpts::default(); - want.apply(&set).unwrap(); - assert_eq!(ws(&app).opts, want); - // Bad values are errors; the engine command with params still runs directly. - assert!(control(&mut app, &json!({"sampling": "everywhere"})).is_err()); - assert!(control(&mut app, &json!({"tool": "pencil"})).is_err()); - cancel(&mut app); - let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({"colorAdaptation": "none"})).unwrap(); - assert_eq!(r["filled"], json!(400)); - assert!(app.distort.caf.is_none()); - } - - /// The engine's sampling area over the plan's rectangle (what the fill samples) and its fill - /// area. - fn engine_source(app: &PhotocraftApp) -> (Rect, Vec, Vec) { - let w = ws(app); - let st = app.session.active().unwrap(); - let plan = photocraft_engine::edit_menu_cmds::content_aware_plan(&st.doc, w.layer, &plan_params(w, true), CMD).unwrap(); - (plan.rect, plan.source, plan.hole) - } - - /// Each stroke is painted into the proxy once, over its own pixels: 400 strokes of 50 points - /// and the undo and redo that rebuild the proxy stay cheap (they used to test every proxy - /// pixel against every segment), and the overlay is exactly what the engine samples (at one - /// proxy px per document px). - #[test] - fn strokes_are_painted_once_and_the_overlay_is_the_engines_sampling_area() { - let mut app = app_with_selection(); - open(&mut app).unwrap(); - control(&mut app, &json!({"sampling": "rectangular"})).unwrap(); - let start = std::time::Instant::now(); - for i in 0..400u32 { - // Lines across the document, most subtracting, every fifth adding (Alt). - let y = 2.0 + f64::from(i % 40) * 4.0; - let pts: Vec<[f64; 2]> = (0..50).map(|j| [f64::from(j) * 4.0 + f64::from(i % 3), y + f64::from(j % 2)]).collect(); - control(&mut app, &json!({"stroke": {"points": pts, "size": 6 + (i % 4) * 3, "alt": i % 5 == 0}})).unwrap(); - } - let painted = start.elapsed(); - let start = std::time::Instant::now(); - control(&mut app, &json!({"undo": true})).unwrap(); - control(&mut app, &json!({"redo": true})).unwrap(); - let rebuilt = start.elapsed(); - assert!(painted.as_secs_f64() < 10.0 && rebuilt.as_secs_f64() < 10.0, "400 strokes {painted:?}, undo + redo {rebuilt:?}"); - let w = ws(&app); - assert_eq!((w.k, w.strokes.len()), (1, 400)); - let (rect, source, hole) = engine_source(&app); - assert_eq!(rect, w.canvas, "Rectangular's window is the whole 200 × 160 canvas"); - let differ = (0..source.len()).filter(|&i| (w.mask[i] && !w.hole_px[i]) != (source[i] && !hole[i])).count(); - assert_eq!(differ, 0, "proxy pixels that differ from the engine's sampling area"); - assert!(w.describe()["sampledProxyPixels"].as_u64().unwrap() > 1000); - } - - /// `edit.contentAwareFill {"ui": …}` addresses the workspace: with it closed that is an - /// error, not a fill with the default settings (an agent polling the state after an Esc - /// used to add a fill per poll). - #[test] - fn ui_params_with_the_workspace_closed_are_an_error_not_a_fill() { - let ctx = egui::Context::default(); - let mut app = app_with_selection(); - let steps = app.session.active().unwrap().history.past_len(); - for ui in [json!({}), json!({"cancel": true}), json!({"sampling": "rectangular"})] { - let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({"ui": ui})); - assert!(r.as_ref().is_err_and(|e| e.contains("not open")), "{r:?}"); - } - assert_eq!(app.session.active().unwrap().history.past_len(), steps, "nothing was filled"); - assert!(app.distort.caf.is_none()); - } - - /// The press is the first point of a stroke (and of a lasso), and the pointer's moves before - /// egui's drag threshold are its next ones: the drag, which starts a few pixels later, goes - /// on with the same stroke rather than beginning another over it. - #[test] - fn a_stroke_keeps_its_points_from_before_the_drag_threshold() { - use egui::{Modifiers, PointerButton}; - for tool in ["brush", "lasso"] { - let mut app = app_with_selection(); - open(&mut app).unwrap(); - control(&mut app, &json!({"tool": tool, "sampling": "rectangular"})).unwrap(); - let mut h = egui_kittest::Harness::builder().with_size(vec2(1600.0, 1000.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; - } - show(app, &ctx); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.run_steps(4); - // The document view sits between the tool strip and the Preview panel, under the - // title and the options bar; its centre shows the document's centre. - let view = ERect::from_min_max(pos2(LEFT_W, 30.0 + BAR_H), pos2(1600.0 - PANEL_W - PREVIEW_W, 1000.0)); - let c = view.center(); - let at = |dx: f32, dy: f32| pos2(c.x + dx, c.y + dy); - let press = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>, down: bool, p: Pos2| { - h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: Modifiers::NONE }); - h.run_steps(1); - }; - h.event(egui::Event::PointerMoved(at(0.0, 0.0))); - h.run_steps(1); - press(&mut h, true, at(0.0, 0.0)); - // Within egui's click distance (6 px): no drag yet, but these are the stroke's points. - // Then past it: the drag starts. (Not collinear: the lasso's polygon needs an area.) - for (dx, dy) in [(2.0, 1.0), (4.0, 2.0), (30.0, 20.0), (60.0, -10.0), (90.0, 40.0)] { - h.event(egui::Event::PointerMoved(at(dx, dy))); - h.run_steps(1); - } - press(&mut h, false, at(90.0, 40.0)); - h.run_steps(2); - let w = h.state().distort.caf.as_ref().unwrap(); - let points: Vec<[f64; 2]> = match tool { - "brush" => { - assert_eq!(w.strokes.len(), 1, "one stroke"); - w.strokes[0].points.clone() - } - _ => { - assert_eq!(w.fill_edits.len(), 1, "one lasso edit"); - serde_json::from_value(w.fill_edits[0]["points"].clone()).unwrap() - } - }; - let centre = [f64::from(w.canvas.x0 + w.canvas.x1) / 2.0, f64::from(w.canvas.y0 + w.canvas.y1) / 2.0]; - assert_eq!(points.len(), 6, "{tool}: the press and every move are points: {points:?}"); - let d = ((points[0][0] - centre[0]).powi(2) + (points[0][1] - centre[1]).powi(2)).sqrt(); - assert!(d < 1.0, "{tool}: the first point is the press ({:?} vs {centre:?})", points[0]); - assert!(w.cur.is_none() && w.lasso.is_none() && !w.pressed, "{tool}: the release ended it"); - } - } - - /// The preview texture fits the device: a plan rectangle wider than the texture limit is - /// box-averaged to fit, and is still drawn over the plan's rectangle. - #[test] - fn the_preview_texture_respects_the_device_limit() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", json!({"width": 2200, "height": 40, "depth": 8})).unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, active| { - let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - s.fill_rect(Rect::new(0, 0, 2200, 40), &[0.2, 0.6, 0.4, 1.0]); - s.fill_rect(Rect::new(1090, 10, 1110, 30), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - app.session.execute("select.rect", json!({"x": 1090, "y": 10, "width": 20, "height": 20})).unwrap(); - app.sync_views(); - open(&mut app).unwrap(); - // Custom sampling with a stroke across the whole width: the plan's rectangle is 2200 px wide. - control(&mut app, &json!({"sampling": "custom", "stroke": {"points": [[0.0, 5.0], [2200.0, 5.0]], "size": 8}})).unwrap(); - for (limit, want) in [(2048usize, 1100usize), (4096, 2200)] { - let w = app.distort.caf.as_mut().unwrap(); - w.texture_limit = limit; - w.stale(); - control(&mut app, &json!({"waitPreview": true})).unwrap(); - let (rect, img) = ws(&app).preview.pending_image.clone().unwrap(); - assert_eq!((rect.width(), img.size[0]), (2200, want), "limit {limit}"); - assert!(img.size.iter().all(|s| *s <= limit), "limit {limit}: {:?}", img.size); - let (sum, n) = img.pixels.iter().fold((0u32, 0u32), |(s, n), p| (s + u32::from(p.g()), n + 1)); - assert!(sum / n > 100, "limit {limit}: the reduced preview keeps the image ({})", sum / n); - } - } - - /// A preview that fails stands for that state: nothing is shown, the error is reported, and - /// the same preview is not started again on every frame. - #[test] - fn a_failing_preview_is_reported_once_not_restarted() { - let mut app = app_with_selection(); - open(&mut app).unwrap(); - control(&mut app, &json!({"waitPreview": true})).unwrap(); - assert!(ws(&app).preview.pending_image.is_some()); - // The selection goes away under the workspace: there is nothing to fill. - app.session.execute("select.deselect", json!({})).unwrap(); - app.distort.caf.as_mut().unwrap().stale(); - assert!(control(&mut app, &json!({"waitPreview": true})).is_err()); - let pv = &ws(&app).preview; - assert_eq!(pv.shown, pv.want, "the failed state counts as shown: no retry"); - assert!(pv.pending_image.is_none() && pv.tex.is_none()); - let d = ws(&app).describe(); - assert_eq!(d["previewReady"], json!(false)); - assert!(d["previewError"].as_str().is_some_and(|e| e.contains("selection")), "{d}"); - } - - /// The view shows the document, not the layer alone: after Apply to a new layer the fill - /// (on that layer) covers the blemish. - #[test] - fn the_view_shows_the_document_after_an_apply_to_a_new_layer() { - let mut app = app_with_selection(); - open(&mut app).unwrap(); - let red = |img: &egui::ColorImage| { - let p = img.pixels[80 * img.size[0] + 100]; - p.r() > 200 && p.g() < 60 - }; - let before = view_image(&app).unwrap(); - assert_eq!(before.size, [200, 160]); - assert!(red(&before), "the blemish shows before the fill"); - control(&mut app, &json!({"output": "new", "colorAdaptation": "none", "apply": true})).unwrap(); - assert!(!red(&view_image(&app).unwrap()), "the fill on the new layer shows"); - } - - /// The engine's limits (MAX_CAF_EDITS strokes or lasso edits, MAX_CAF_POINTS points in all) - /// hold at the brush: a stroke past them is refused with a message, so Apply and the - /// preview never fail on what was painted. - #[test] - fn strokes_past_the_engines_limits_are_refused_at_the_brush() { - let mut app = app_with_selection(); - open(&mut app).unwrap(); - control(&mut app, &json!({"sampling": "rectangular"})).unwrap(); - for i in 0..MAX_CAF_EDITS { - let x = (i % 190) as f64; - control(&mut app, &json!({"stroke": {"points": [[x, 5.0], [x + 3.0, 5.0]], "size": 2}})).unwrap(); - } - let d = control(&mut app, &json!({"stroke": {"points": [[10.0, 50.0], [20.0, 50.0]], "size": 2}})).unwrap(); - assert_eq!(d["strokes"], json!(MAX_CAF_EDITS)); - assert!(d["error"].as_str().is_some_and(|e| e.contains("at most")), "{d}"); - control(&mut app, &json!({"waitPreview": true})).unwrap(); - // The points budget: a long stroke stops at it. - let mut app = app_with_selection(); - open(&mut app).unwrap(); - let pts: Vec<[f64; 2]> = (0..MAX_CAF_POINTS + 100).map(|i| [10.0 + i as f64 * 0.0005, 5.0]).collect(); - let d = control(&mut app, &json!({"stroke": {"points": pts, "size": 2}})).unwrap(); - assert_eq!(ws(&app).points_used(), MAX_CAF_POINTS); - assert!(d["error"].as_str().is_some_and(|e| e.contains("at most")), "{d}"); - control(&mut app, &json!({"waitPreview": true})).unwrap(); - // A lasso edit past the points budget is refused too. - let d = control(&mut app, &json!({"lasso": {"op": "add", "points": [[130.0, 70.0], [150.0, 70.0], [150.0, 90.0]]}})).unwrap(); - assert_eq!(d["fillEdits"], json!(0)); - assert!(d["error"].as_str().is_some_and(|e| e.contains("at most")), "{d}"); - } -} +mod tests; diff --git a/crates/ui-egui/src/caf_ui/tests.rs b/crates/ui-egui/src/caf_ui/tests.rs new file mode 100644 index 0000000000..84071e3856 --- /dev/null +++ b/crates/ui-egui/src/caf_ui/tests.rs @@ -0,0 +1,474 @@ +use super::*; + +/// A textured layer (a checker of two colours over a gradient) with a 20 px square selected. +fn app_with_selection() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 200, "height": 160, "depth": 8})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, active| { + let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..160 { + for x in 0..200 { + let v = ((x / 6 + y / 6) % 2) as f32 * 0.5 + x as f32 / 400.0; + s.write_pixel(x, y, &[v, 0.3, 1.0 - v, 1.0]); + } + } + // A red blemish to remove. + for y in 72..88 { + for x in 92..108 { + s.write_pixel(x, y, &[1.0, 0.0, 0.0, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + app.session.execute("select.rect", json!({"x": 90, "y": 70, "width": 20, "height": 20})).unwrap(); + app.sync_views(); + app +} + +fn px(app: &PhotocraftApp, layer: LayerId, x: i32, y: i32) -> Vec { + app.session.active().unwrap().doc.layer(layer).unwrap().surface().unwrap().pixel(x, y) +} + +fn ws(app: &PhotocraftApp) -> &CafWorkspace { + app.distort.caf.as_ref().unwrap() +} + +#[test] +fn settings_dropdowns_are_named_for_their_visible_labels() { + use egui::accesskit::Role; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let mut h = Harness::builder() + .with_size(egui::vec2(1000.0, 900.0)) + .with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0])) + .build_ui_state(|ui, app: &mut PhotocraftApp| show(app, ui.ctx()), app); + h.run_steps(2); + // The Indicates dropdown lives inside a collapsed "Sampling Area Overlay" header. + h.get_by_role_and_label(Role::DisclosureTriangle, "Sampling Area Overlay").click(); + h.run_steps(3); + let labels: Vec = h.query_all_by_role(Role::ComboBox).filter_map(|n| n.accesskit_node().label()).collect(); + for label in ["Indicates", "Color Adaptation", "Rotation Adaptation", "Output To"] { + assert!(labels.iter().any(|have| have == label), "{label} names its dropdown: {labels:?}"); + } + for wrong in ["Contents:", "Color", "Rotation", "Source"] { + assert!(!labels.iter().any(|have| have == wrong), "{wrong} names no control here: {labels:?}"); + } +} + +/// Photoshop opens the workspace with the Sampling Brush subtracting at a tenth of the +/// window's side, Auto sampling, output to a new layer. +#[test] +fn opens_like_photoshop() { + let mut app = app_with_selection(); + app.session.prefs.edit(|p| { + p.dialogs.remove(REMEMBERED); + }); + open(&mut app).unwrap(); + let d = ws(&app).describe(); + assert_eq!(d["window"], json!([0, 0, 200, 160]), "a 200 px window, clipped to the 200 × 160 canvas"); + assert_eq!((d["tool"].as_str(), d["brushMode"].as_str(), d["brushSize"].as_f64()), (Some("brush"), Some("subtract"), Some(20.0))); + assert_eq!((d["settings"]["sampling"].as_str(), d["settings"]["output"].as_str()), (Some("auto"), Some("new"))); + assert_eq!(d["fillArea"], json!(400)); + assert!(d["sampledProxyPixels"].as_u64().unwrap() > 1000); +} + +#[test] +fn brush_strokes_change_the_sampling_area_and_undo() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + control(&mut app, &json!({"sampling": "rectangular"})).unwrap(); + let all = ws(&app).describe()["sampledProxyPixels"].as_u64().unwrap(); + assert_eq!(all, 200 * 160 - 400, "Rectangular: the whole window but the fill area"); + // Subtracting (the default): a 10 px stroke takes about 10 × 60 px away. + let d = control(&mut app, &json!({"stroke": {"points": [[20.0, 20.0], [80.0, 20.0]], "size": 10}})).unwrap(); + let less = d["sampledProxyPixels"].as_u64().unwrap(); + assert!((all - less).abs_diff(10 * 60 + 79) < 120, "{all} → {less}"); + // Undo brings it back; redo takes it again. + assert_eq!(control(&mut app, &json!({"undo": true})).unwrap()["sampledProxyPixels"].as_u64(), Some(all)); + assert_eq!(control(&mut app, &json!({"redo": true})).unwrap()["sampledProxyPixels"].as_u64(), Some(less)); + // Custom starts empty and the brush adds; Alt reverses it. + let d = control(&mut app, &json!({"sampling": "custom"})).unwrap(); + assert_eq!((d["sampledProxyPixels"].as_u64(), d["brushMode"].as_str(), d["strokes"].as_u64()), (Some(0), Some("add"), Some(0))); + let d = control(&mut app, &json!({"stroke": {"points": [[20.0, 120.0], [60.0, 120.0]], "size": 8}})).unwrap(); + assert!(d["sampledProxyPixels"].as_u64().unwrap() > 300); + let d = control(&mut app, &json!({"stroke": {"points": [[20.0, 120.0], [60.0, 120.0]], "size": 8, "alt": true}})).unwrap(); + assert_eq!(d["sampledProxyPixels"].as_u64(), Some(0)); + // Undoing the change of option restores Rectangular with its stroke. + control(&mut app, &json!({"undo": true})).unwrap(); + control(&mut app, &json!({"undo": true})).unwrap(); + let d = control(&mut app, &json!({"undo": true})).unwrap(); + assert_eq!((d["settings"]["sampling"].as_str(), d["strokes"].as_u64(), d["brushMode"].as_str()), (Some("rectangular"), Some(1), Some("subtract"))); +} + +#[test] +fn the_lasso_edits_the_fill_area_and_the_window_follows() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let d = control(&mut app, &json!({"lasso": {"op": "add", "points": [[130.0, 70.0], [150.0, 70.0], [150.0, 90.0], [130.0, 90.0]]}})).unwrap(); + assert_eq!(d["fillArea"], json!(800)); + let d = control(&mut app, &json!({"expand": 2})).unwrap(); + assert!(d["fillArea"].as_u64().unwrap() > 900); + let d = control(&mut app, &json!({"undo": true, "lassoMode": "subtract"})).unwrap(); + assert_eq!((d["fillArea"].as_u64(), d["lassoMode"].as_str()), (Some(800), Some("subtract"))); + // Subtracting everything is refused: the fill area can't be empty. + let d = control(&mut app, &json!({"lasso": {"points": [[0.0, 0.0], [200.0, 0.0], [200.0, 160.0], [0.0, 160.0]]}})).unwrap(); + assert_eq!(d["fillArea"], json!(800)); + assert!(d["error"].as_str().is_some_and(|e| e.contains("empty")), "{d}"); + // The reset button goes back to the selection. + let d = control(&mut app, &json!({"reset": "lasso"})).unwrap(); + assert_eq!(d["fillArea"], json!(400)); +} + +/// A sampling area the Sampling Brush erased entirely previews as an error naming the +/// problem, not as the black fill it would make; undoing the stroke brings the preview back. +#[test] +fn an_erased_sampling_area_previews_as_an_error() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + control(&mut app, &json!({"sampling": "rectangular", "waitPreview": true})).unwrap(); + assert!(ws(&app).describe()["previewError"].is_null()); + // Subtracting (the default) with a brush wider than the 200 × 160 window. + let e = control(&mut app, &json!({"stroke": {"points": [[100.0, 80.0]], "size": 600}, "waitPreview": true})).unwrap_err(); + assert!(e.contains("nothing to sample from"), "{e}"); + let d = ws(&app).describe(); + assert_eq!(d["sampledProxyPixels"].as_u64(), Some(0), "{d}"); + assert!(d["previewError"].as_str().is_some_and(|e| e.contains("nothing to sample from")), "{d}"); + let d = control(&mut app, &json!({"undo": true, "waitPreview": true})).unwrap(); + assert!(d["previewError"].is_null(), "{d}"); +} + +/// OK whose fill fails keeps the workspace open with the error in its panel, from the button +/// and from the control channel, so the work isn't thrown away; once the fill can run, OK +/// fills and closes. +#[test] +fn a_failed_ok_keeps_the_workspace_open() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let steps = app.session.active().unwrap().history.past_len(); + app.session.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap(); + commit(&mut app); + assert!(app.distort.caf.is_some(), "OK keeps the workspace open when the fill fails"); + assert!(ws(&app).error.as_deref().is_some_and(|e| e.contains("locked")), "{:?}", ws(&app).error); + assert!(app.ui.status_error); + assert!(control(&mut app, &json!({"commit": true})).unwrap_err().contains("locked")); + assert!(app.distort.caf.is_some(), "the control channel's OK too"); + app.session.execute("layer.setProps", json!({"locks": {"pixels": false}})).unwrap(); + let steps = app.session.active().unwrap().history.past_len().max(steps); + commit(&mut app); + assert!(app.distort.caf.is_none(), "OK closes once the fill runs"); + assert!(app.session.active().unwrap().history.past_len() > steps, "and fills"); +} + +/// Undo or Redo of a sampling stroke changes what OK would fill, so it clears the error a +/// failed OK left in the panel, as a new stroke does; otherwise the stale error would stay +/// drawn over the recovered preview. +#[test] +fn undo_and_redo_of_a_stroke_clear_a_failed_oks_error() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + control(&mut app, &json!({"stroke": {"points": [[20.0, 20.0], [60.0, 20.0]], "size": 10}})).unwrap(); + app.session.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap(); + commit(&mut app); + assert!(ws(&app).error.is_some(), "the failed OK reports in the panel"); + control(&mut app, &json!({"undo": true})).unwrap(); + assert!(ws(&app).error.is_none(), "Undo of the stroke clears it"); + commit(&mut app); + assert!(ws(&app).error.is_some()); + control(&mut app, &json!({"redo": true})).unwrap(); + assert!(ws(&app).error.is_none(), "Redo of the stroke clears it too"); +} + +#[test] +fn apply_fills_and_stays_open_ok_closes_cancel_keeps_what_was_applied() { + let mut app = app_with_selection(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + open(&mut app).unwrap(); + // The preview is what Apply writes. + control(&mut app, &json!({"output": "current", "colorAdaptation": "none", "waitPreview": true})).unwrap(); + let (rect, img) = ws(&app).preview.pending_image.clone().unwrap(); + control(&mut app, &json!({"apply": true})).unwrap(); + assert!(app.distort.caf.is_some(), "Apply keeps the workspace open"); + let after = px(&app, layer, 100, 80); + assert!(after[0] < 0.9 || after[1] > 0.1, "the blemish is filled: {after:?}"); + let i = ((80 - rect.y0) * rect.width() as i32 + (100 - rect.x0)) as usize; + let shown = img.pixels[i]; + assert!((f32::from(shown.r()) / 255.0 - after[0]).abs() < 0.01 && (f32::from(shown.b()) / 255.0 - after[2]).abs() < 0.01, "preview {shown:?} vs {after:?}"); + let steps = app.session.active().unwrap().history.past_len(); + cancel(&mut app); + assert!(app.distort.caf.is_none()); + assert_eq!(app.session.active().unwrap().history.past_len(), steps, "Cancel keeps the applied fill"); + // OK with New Layer: a new layer holds the fill; the original stays. + app.session.execute("edit.undo", json!({})).unwrap(); + open(&mut app).unwrap(); + control(&mut app, &json!({"output": "new", "commit": true})).unwrap(); + assert!(app.distort.caf.is_none()); + assert_eq!(px(&app, layer, 100, 80)[0], 1.0, "the original layer keeps its blemish"); + let top = app.session.active().unwrap().active_layer.unwrap(); + assert_ne!(top, layer); + assert!(px(&app, top, 100, 80)[3] > 0.99, "the new layer holds the fill"); +} + +/// #5092: the workspace left open does not follow the user to another document, and closing +/// the document it was opened on closes it. +#[test] +fn the_workspace_is_dropped_when_another_document_becomes_active() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + crate::distort_ui::drop_foreign(&mut app); + assert!(app.distort.caf.is_some()); + app.session.execute("file.new", json!({"width": 32, "height": 32, "depth": 8})).unwrap(); + crate::distort_ui::drop_foreign(&mut app); + assert!(app.distort.caf.is_none()); + assert!(app.session.set_active(0)); + open(&mut app).unwrap(); + crate::distort_ui::drop_foreign(&mut app); + assert!(app.distort.caf.is_some()); + assert!(app.session.close(0).is_some()); + crate::distort_ui::drop_foreign(&mut app); + assert!(app.distort.caf.is_none()); +} + +#[test] +fn settings_are_remembered_and_the_menu_opens_the_workspace() { + let ctx = egui::Context::default(); + let mut app = app_with_selection(); + let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({})).unwrap(); + assert!(r["contentAwareFill"]["window"].is_array(), "{r}"); + let set = json!({"opacity": 30, "color": [200, 40, 40], "excluded": true, "colorAdaptation": "high", "rotationAdaptation": "low", "mirror": true, "output": "duplicate"}); + crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({"ui": set})).unwrap(); + crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({"ui": {"cancel": true}})).unwrap(); + open(&mut app).unwrap(); + let mut want = CafOpts::default(); + want.apply(&set).unwrap(); + assert_eq!(ws(&app).opts, want); + // Bad values are errors; the engine command with params still runs directly. + assert!(control(&mut app, &json!({"sampling": "everywhere"})).is_err()); + assert!(control(&mut app, &json!({"tool": "pencil"})).is_err()); + cancel(&mut app); + let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({"colorAdaptation": "none"})).unwrap(); + assert_eq!(r["filled"], json!(400)); + assert!(app.distort.caf.is_none()); +} + +/// The engine's sampling area over the plan's rectangle (what the fill samples) and its fill +/// area. +fn engine_source(app: &PhotocraftApp) -> (Rect, Vec, Vec) { + let w = ws(app); + let st = app.session.active().unwrap(); + let plan = photocraft_engine::edit_menu_cmds::content_aware_plan(&st.doc, w.layer, &plan_params(w, true), CMD).unwrap(); + (plan.rect, plan.source, plan.hole) +} + +/// Each stroke is painted into the proxy once, over its own pixels: 400 strokes of 50 points +/// and the undo and redo that rebuild the proxy stay cheap (they used to test every proxy +/// pixel against every segment), and the overlay is exactly what the engine samples (at one +/// proxy px per document px). +#[test] +fn strokes_are_painted_once_and_the_overlay_is_the_engines_sampling_area() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + control(&mut app, &json!({"sampling": "rectangular"})).unwrap(); + let start = std::time::Instant::now(); + for i in 0..400u32 { + // Lines across the document, most subtracting, every fifth adding (Alt). + let y = 2.0 + f64::from(i % 40) * 4.0; + let pts: Vec<[f64; 2]> = (0..50).map(|j| [f64::from(j) * 4.0 + f64::from(i % 3), y + f64::from(j % 2)]).collect(); + control(&mut app, &json!({"stroke": {"points": pts, "size": 6 + (i % 4) * 3, "alt": i % 5 == 0}})).unwrap(); + } + let painted = start.elapsed(); + let start = std::time::Instant::now(); + control(&mut app, &json!({"undo": true})).unwrap(); + control(&mut app, &json!({"redo": true})).unwrap(); + let rebuilt = start.elapsed(); + assert!(painted.as_secs_f64() < 10.0 && rebuilt.as_secs_f64() < 10.0, "400 strokes {painted:?}, undo + redo {rebuilt:?}"); + let w = ws(&app); + assert_eq!((w.k, w.strokes.len()), (1, 400)); + let (rect, source, hole) = engine_source(&app); + assert_eq!(rect, w.canvas, "Rectangular's window is the whole 200 × 160 canvas"); + let differ = (0..source.len()).filter(|&i| (w.mask[i] && !w.hole_px[i]) != (source[i] && !hole[i])).count(); + assert_eq!(differ, 0, "proxy pixels that differ from the engine's sampling area"); + assert!(w.describe()["sampledProxyPixels"].as_u64().unwrap() > 1000); +} + +/// `edit.contentAwareFill {"ui": …}` addresses the workspace: with it closed that is an +/// error, not a fill with the default settings (an agent polling the state after an Esc +/// used to add a fill per poll). +#[test] +fn ui_params_with_the_workspace_closed_are_an_error_not_a_fill() { + let ctx = egui::Context::default(); + let mut app = app_with_selection(); + let steps = app.session.active().unwrap().history.past_len(); + for ui in [json!({}), json!({"cancel": true}), json!({"sampling": "rectangular"})] { + let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({"ui": ui})); + assert!(r.as_ref().is_err_and(|e| e.contains("not open")), "{r:?}"); + } + assert_eq!(app.session.active().unwrap().history.past_len(), steps, "nothing was filled"); + assert!(app.distort.caf.is_none()); +} + +/// The press is the first point of a stroke (and of a lasso), and the pointer's moves before +/// egui's drag threshold are its next ones: the drag, which starts a few pixels later, goes +/// on with the same stroke rather than beginning another over it. +#[test] +fn a_stroke_keeps_its_points_from_before_the_drag_threshold() { + use egui::{Modifiers, PointerButton}; + for tool in ["brush", "lasso"] { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + control(&mut app, &json!({"tool": tool, "sampling": "rectangular"})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1600.0, 1000.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; + } + show(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + // The document view sits between the tool strip and the Preview panel, under the + // title and the options bar; its centre shows the document's centre. + let view = ERect::from_min_max(pos2(LEFT_W, 30.0 + BAR_H), pos2(1600.0 - PANEL_W - PREVIEW_W, 1000.0)); + let c = view.center(); + let at = |dx: f32, dy: f32| pos2(c.x + dx, c.y + dy); + let press = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>, down: bool, p: Pos2| { + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: Modifiers::NONE }); + h.run_steps(1); + }; + h.event(egui::Event::PointerMoved(at(0.0, 0.0))); + h.run_steps(1); + press(&mut h, true, at(0.0, 0.0)); + // Within egui's click distance (6 px): no drag yet, but these are the stroke's points. + // Then past it: the drag starts. (Not collinear: the lasso's polygon needs an area.) + for (dx, dy) in [(2.0, 1.0), (4.0, 2.0), (30.0, 20.0), (60.0, -10.0), (90.0, 40.0)] { + h.event(egui::Event::PointerMoved(at(dx, dy))); + h.run_steps(1); + } + press(&mut h, false, at(90.0, 40.0)); + h.run_steps(2); + let w = h.state().distort.caf.as_ref().unwrap(); + let points: Vec<[f64; 2]> = match tool { + "brush" => { + assert_eq!(w.strokes.len(), 1, "one stroke"); + w.strokes[0].points.clone() + } + _ => { + assert_eq!(w.fill_edits.len(), 1, "one lasso edit"); + serde_json::from_value(w.fill_edits[0]["points"].clone()).unwrap() + } + }; + let centre = [f64::from(w.canvas.x0 + w.canvas.x1) / 2.0, f64::from(w.canvas.y0 + w.canvas.y1) / 2.0]; + assert_eq!(points.len(), 6, "{tool}: the press and every move are points: {points:?}"); + let d = ((points[0][0] - centre[0]).powi(2) + (points[0][1] - centre[1]).powi(2)).sqrt(); + assert!(d < 1.0, "{tool}: the first point is the press ({:?} vs {centre:?})", points[0]); + assert!(w.cur.is_none() && w.lasso.is_none() && !w.pressed, "{tool}: the release ended it"); + } +} + +/// The preview texture fits the device: a plan rectangle wider than the texture limit is +/// box-averaged to fit, and is still drawn over the plan's rectangle. +#[test] +fn the_preview_texture_respects_the_device_limit() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 2200, "height": 40, "depth": 8})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, active| { + let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + s.fill_rect(Rect::new(0, 0, 2200, 40), &[0.2, 0.6, 0.4, 1.0]); + s.fill_rect(Rect::new(1090, 10, 1110, 30), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.session.execute("select.rect", json!({"x": 1090, "y": 10, "width": 20, "height": 20})).unwrap(); + app.sync_views(); + open(&mut app).unwrap(); + // Custom sampling with a stroke across the whole width: the plan's rectangle is 2200 px wide. + control(&mut app, &json!({"sampling": "custom", "stroke": {"points": [[0.0, 5.0], [2200.0, 5.0]], "size": 8}})).unwrap(); + for (limit, want) in [(2048usize, 1100usize), (4096, 2200)] { + let w = app.distort.caf.as_mut().unwrap(); + w.texture_limit = limit; + w.stale(); + control(&mut app, &json!({"waitPreview": true})).unwrap(); + let (rect, img) = ws(&app).preview.pending_image.clone().unwrap(); + assert_eq!((rect.width(), img.size[0]), (2200, want), "limit {limit}"); + assert!(img.size.iter().all(|s| *s <= limit), "limit {limit}: {:?}", img.size); + let (sum, n) = img.pixels.iter().fold((0u32, 0u32), |(s, n), p| (s + u32::from(p.g()), n + 1)); + assert!(sum / n > 100, "limit {limit}: the reduced preview keeps the image ({})", sum / n); + } +} + +/// A preview that fails stands for that state: nothing is shown, the error is reported, and +/// the same preview is not started again on every frame. +#[test] +fn a_failing_preview_is_reported_once_not_restarted() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + control(&mut app, &json!({"waitPreview": true})).unwrap(); + assert!(ws(&app).preview.pending_image.is_some()); + // The selection goes away under the workspace: there is nothing to fill. + app.session.execute("select.deselect", json!({})).unwrap(); + app.distort.caf.as_mut().unwrap().stale(); + assert!(control(&mut app, &json!({"waitPreview": true})).is_err()); + let pv = &ws(&app).preview; + assert_eq!(pv.shown, pv.want, "the failed state counts as shown: no retry"); + assert!(pv.pending_image.is_none() && pv.tex.is_none()); + let d = ws(&app).describe(); + assert_eq!(d["previewReady"], json!(false)); + assert!(d["previewError"].as_str().is_some_and(|e| e.contains("selection")), "{d}"); +} + +/// The view shows the document, not the layer alone: after Apply to a new layer the fill +/// (on that layer) covers the blemish. +#[test] +fn the_view_shows_the_document_after_an_apply_to_a_new_layer() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let red = |img: &egui::ColorImage| { + let p = img.pixels[80 * img.size[0] + 100]; + p.r() > 200 && p.g() < 60 + }; + let before = view_image(&app).unwrap(); + assert_eq!(before.size, [200, 160]); + assert!(red(&before), "the blemish shows before the fill"); + control(&mut app, &json!({"output": "new", "colorAdaptation": "none", "apply": true})).unwrap(); + assert!(!red(&view_image(&app).unwrap()), "the fill on the new layer shows"); +} + +/// The engine's limits (MAX_CAF_EDITS strokes or lasso edits, MAX_CAF_POINTS points in all) +/// hold at the brush: a stroke past them is refused with a message, so Apply and the +/// preview never fail on what was painted. +#[test] +fn strokes_past_the_engines_limits_are_refused_at_the_brush() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + control(&mut app, &json!({"sampling": "rectangular"})).unwrap(); + for i in 0..MAX_CAF_EDITS { + let x = (i % 190) as f64; + control(&mut app, &json!({"stroke": {"points": [[x, 5.0], [x + 3.0, 5.0]], "size": 2}})).unwrap(); + } + let d = control(&mut app, &json!({"stroke": {"points": [[10.0, 50.0], [20.0, 50.0]], "size": 2}})).unwrap(); + assert_eq!(d["strokes"], json!(MAX_CAF_EDITS)); + assert!(d["error"].as_str().is_some_and(|e| e.contains("at most")), "{d}"); + control(&mut app, &json!({"waitPreview": true})).unwrap(); + // The points budget: a long stroke stops at it. + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let pts: Vec<[f64; 2]> = (0..MAX_CAF_POINTS + 100).map(|i| [10.0 + i as f64 * 0.0005, 5.0]).collect(); + let d = control(&mut app, &json!({"stroke": {"points": pts, "size": 2}})).unwrap(); + assert_eq!(ws(&app).points_used(), MAX_CAF_POINTS); + assert!(d["error"].as_str().is_some_and(|e| e.contains("at most")), "{d}"); + control(&mut app, &json!({"waitPreview": true})).unwrap(); + // A lasso edit past the points budget is refused too. + let d = control(&mut app, &json!({"lasso": {"op": "add", "points": [[130.0, 70.0], [150.0, 70.0], [150.0, 90.0]]}})).unwrap(); + assert_eq!(d["fillEdits"], json!(0)); + assert!(d["error"].as_str().is_some_and(|e| e.contains("at most")), "{d}"); +} From 072b010f11a09c64a0c09442120d6cd026bdd25f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:32 +0000 Subject: [PATCH 101/259] refactor(ui-egui): move stylus.rs tests to stylus/tests.rs --- crates/ui-egui/src/stylus.rs | 363 +---------------------------- crates/ui-egui/src/stylus/tests.rs | 360 ++++++++++++++++++++++++++++ 2 files changed, 361 insertions(+), 362 deletions(-) create mode 100644 crates/ui-egui/src/stylus/tests.rs diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs index 8460c31ea2..73191e4ebd 100644 --- a/crates/ui-egui/src/stylus.rs +++ b/crates/ui-egui/src/stylus.rs @@ -482,365 +482,4 @@ pub(crate) fn pen_hold_is_no_right_click(ctx: &egui::Context, pen_down: bool) { } #[cfg(test)] -mod tests { - use super::*; - - /// Hold a touch contact still for 1.2 s over a click-sensing area, with the press-and-hold - /// handling the app does in `raw_input_hook`. Did the area see a secondary click? - fn held_contact_right_clicks(hover_first: bool, force: Option) -> bool { - let ctx = egui::Context::default(); - let mut contacts = PenContacts::default(); - let mut right_clicked = false; - let ev = |phase, force| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(3), phase, pos: egui::pos2(50.0, 50.0), force }; - // A first frame lays the area out, so the press hits it. - let mut frames = vec![(0.0, vec![])]; - if hover_first { - frames.push((0.05, vec![ev(egui::TouchPhase::Move, None), egui::Event::PointerMoved(egui::pos2(50.0, 50.0))])); - } - frames.push(( - 0.1, - vec![ - ev(egui::TouchPhase::Start, force), - egui::Event::PointerMoved(egui::pos2(50.0, 50.0)), - egui::Event::PointerButton { - pos: egui::pos2(50.0, 50.0), - button: egui::PointerButton::Primary, - pressed: true, - modifiers: egui::Modifiers::NONE, - }, - ], - )); - for t in [0.4, 0.7, 1.0, 1.3] { - frames.push((t, vec![])); - } - for (time, mut events) in frames { - // egui-winit emits the touch and its emulated pointer events together. - let mut raw = egui::RawInput { - time: Some(time), - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(200.0, 200.0))), - ..Default::default() - }; - raw.events.append(&mut events); - let pen = contacts.observe(&raw.events); - pen_hold_is_no_right_click(&ctx, pen); - let mut out = ctx.run_ui(raw, |ui| { - let r = ui.allocate_rect(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(200.0, 200.0)), egui::Sense::click_and_drag()); - right_clicked |= r.secondary_clicked(); - }); - out.textures_delta.clear(); - } - right_clicked - } - - #[test] - fn a_held_pen_is_not_a_right_click_but_a_held_finger_still_is() { - assert!(held_contact_right_clicks(false, None), "a finger's press-and-hold is egui's context menu"); - assert!(!held_contact_right_clicks(true, None), "a pen that hovered first"); - assert!(!held_contact_right_clicks(false, Some(0.4)), "a contact that reports pressure"); - } - - #[test] - fn pen_contacts_follow_hover_force_and_lift() { - use egui::TouchPhase::{Cancel, End, Move, Start}; - let t = |id, phase, force| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(id), phase, pos: egui::pos2(1.0, 1.0), force }; - let mut c = PenContacts::default(); - assert!(!c.observe(&[t(1, Move, None)]), "hovering is no contact"); - assert!(c.observe(&[t(1, Start, None)])); - assert!(c.observe(&[]), "still down"); - assert!(c.observe(&[t(1, End, None)]), "the lift frame still counts"); - assert!(!c.observe(&[])); - // A finger, until it reports a force. - assert!(!c.observe(&[t(9, Start, None), t(9, Move, None)])); - assert!(c.observe(&[t(9, Move, Some(0.5))])); - assert!(c.observe(&[t(9, Cancel, None)])); - assert!(!c.observe(&[])); - } - - fn touch(phase: egui::TouchPhase, force: Option) -> egui::Event { - egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(0), phase, pos: egui::pos2(1.0, 1.0), force } - } - - fn pen(pressure: f32) -> PenSample { - PenSample { pressure, ..Default::default() } - } - - #[test] - fn the_feed_queues_every_sample_in_order_and_keeps_the_latest() { - let feed = StylusFeed::default(); - for p in [0.1, 0.2, 0.3] { - feed.set(Some(pen(p))); - } - assert_eq!(feed.get().map(|s| s.pressure), Some(0.3)); - assert_eq!(feed.drain().iter().map(|s| s.pressure).collect::>(), vec![0.1, 0.2, 0.3]); - assert!(feed.drain().is_empty(), "drained once"); - feed.set(None); - assert_eq!(feed.get(), None, "a lifted pen is not queued"); - assert!(feed.drain().is_empty()); - // A UI that stops draining keeps only the newest samples. - for i in 0..FEED_QUEUE + 10 { - feed.set(Some(pen((i % 100) as f32 / 100.0))); - } - assert_eq!(feed.drain().len(), FEED_QUEUE); - } - - #[test] - fn each_move_takes_its_share_of_the_frames_pen_samples() { - let mut s = Stylus::default(); - s.feed.set(Some(pen(0.2))); - s.update(&[]); - s.begin_stroke(); - // Next frame: the pen reported 0.4, 0.6 and 0.8 while six pointer moves arrived. - for p in [0.4, 0.6, 0.8] { - s.feed.set(Some(pen(p))); - } - s.update(&[]); - let got: Vec = (0..6) - .map(|k| { - s.select(k, 6); - s.pressure() - }) - .collect(); - let want = [0.3, 0.4, 0.5, 0.6, 0.7, 0.8]; - assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6), "{got:?}"); - s.clear_selection(); - assert_eq!(s.pressure(), 0.8, "back to the current sample"); - } - - #[test] - fn the_pressure_curve_reshapes_pen_pressure_but_not_the_mouse() { - let mut s = Stylus::default(); - s.set_pressure_curve(&[[0.0, 0.0], [0.3, 0.6], [1.0, 1.0]]); - s.feed.set(Some(pen(0.3))); - s.update(&[]); - assert!((s.pressure() - 0.6).abs() < 1e-5, "{}", s.pressure()); - s.set_pressure_curve(&[[0.0, 0.0], [1.0, 1.0]]); - assert!((s.pressure() - 0.3).abs() < 1e-6, "linear again"); - // A mouse is full pressure whatever the curve. - let mut m = Stylus::default(); - m.set_pressure_curve(&[[0.0, 0.0], [1.0, 0.2]]); - m.update(&[egui::Event::PointerMoved(egui::pos2(1.0, 1.0))]); - assert_eq!(m.pressure(), 1.0); - } - - #[test] - fn a_second_update_in_the_same_frame_keeps_its_samples() { - // The canvas runs once per view, and egui may run a frame in several passes. - let mut s = Stylus::default(); - s.feed.set(Some(pen(0.4))); - s.feed.set(Some(pen(0.8))); - s.update_for_frame(7, &[]); - s.update_for_frame(7, &[]); - s.select(0, 2); - assert!((s.pressure() - 0.4).abs() < 1e-6, "{}", s.pressure()); - } - - #[test] - fn a_new_stroke_never_starts_from_an_old_strokes_pressure() { - let mut s = Stylus::default(); - s.feed.set(Some(pen(0.9))); - s.update(&[]); - s.feed.set(Some(pen(0.1))); - s.update(&[]); - s.begin_stroke(); - s.select(0, 2); - assert!((s.pressure() - 0.1).abs() < 1e-6, "{}", s.pressure()); - } - - #[test] - fn a_mouse_or_use_pressure_off_paints_at_full_pressure() { - let mut s = Stylus::default(); - s.update(&[egui::Event::PointerMoved(egui::pos2(1.0, 1.0))]); - s.select(0, 1); - assert_eq!(s.pressure(), 1.0); - s.feed.set(Some(pen(0.3))); - s.use_pressure = false; - s.update(&[]); - s.select(0, 1); - assert_eq!(s.pressure(), 1.0); - } - - #[test] - fn rotation_between_samples_takes_the_short_way_round() { - let mut s = Stylus::default(); - s.feed.set(Some(PenSample { rotation: 350.0, ..pen(1.0) })); - s.update(&[]); - s.feed.set(Some(PenSample { rotation: 10.0, ..pen(1.0) })); - s.update(&[]); - s.select(0, 2); - let r = s.sample().map_or(-1.0, |p| p.rotation); - assert!(r.abs() < 1e-3 || (r - 360.0).abs() < 1e-3, "halfway from 350° to 10° is 0°, got {r}"); - } - - #[test] - fn mouse_is_full_pressure() { - let mut s = Stylus::default(); - s.update(&[egui::Event::PointerMoved(egui::pos2(3.0, 4.0))]); - assert_eq!(s.pressure(), 1.0); - assert_eq!(s.sample(), None); - } - - #[test] - fn touch_force_drives_pressure_until_lift() { - let mut s = Stylus::default(); - s.update(&[touch(egui::TouchPhase::Start, Some(0.25))]); - assert_eq!(s.pressure(), 0.25); - s.update(&[touch(egui::TouchPhase::Move, Some(0.8)), touch(egui::TouchPhase::Move, Some(1.7))]); - assert_eq!(s.pressure(), 1.0, "clamped"); - s.update(&[touch(egui::TouchPhase::Move, Some(f32::NAN))]); - assert_eq!(s.pressure(), 1.0); - s.update(&[touch(egui::TouchPhase::Move, Some(0.4))]); - assert_eq!(s.pressure(), 0.4); - // The lift frame still paints at the last force; the next frame is back to the mouse. - s.update(&[touch(egui::TouchPhase::End, None)]); - assert_eq!(s.pressure(), 0.4); - s.update(&[]); - assert_eq!(s.pressure(), 1.0); - } - - fn touch_id(id: u64, phase: egui::TouchPhase, force: Option) -> egui::Event { - egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(id), phase, pos: egui::pos2(1.0, 1.0), force } - } - - #[test] - fn a_light_windows_pen_tap_is_not_full_pressure() { - use egui::TouchPhase::{End, Move, Start}; - // winit on Windows reports a pen pressed below its first pressure level with no force - // (pressure 0 maps to `None`). The pen hovered first, so the tap is pressure 0, not a - // mouse click's 1. - let mut s = Stylus::default(); - s.update(&[touch_id(5, Move, None)]); - assert_eq!(s.pressure(), 1.0, "hovering is no contact"); - s.update(&[touch_id(5, Start, None), touch_id(5, End, None)]); - assert_eq!(s.pressure(), 0.0); - assert_eq!(s.tap_pressure(), 0.0); - s.update(&[]); - assert_eq!(s.pressure(), 1.0, "lifted"); - // A pen known from an earlier force: a stroke pressed before its first level starts at 0 - // and then follows the pen. - let mut s = Stylus::default(); - s.update(&[touch_id(7, Start, Some(0.5)), touch_id(7, End, None)]); - s.update(&[]); - s.update(&[touch_id(8, Start, None)]); - assert_eq!(s.pressure(), 0.0); - s.update(&[touch_id(8, Move, Some(0.3))]); - assert_eq!(s.pressure(), 0.3); - // A force-less move mid-stroke keeps the last force. - s.update(&[touch_id(8, Move, None)]); - assert_eq!(s.pressure(), 0.3); - } - - #[test] - fn a_finger_without_force_still_paints_at_full_pressure() { - use egui::TouchPhase::{End, Move, Start}; - let mut s = Stylus::default(); - s.update(&[touch_id(1, Start, None), touch_id(1, Move, None)]); - assert_eq!(s.pressure(), 1.0); - s.update(&[touch_id(1, End, None)]); - s.update(&[]); - assert_eq!(s.pressure(), 1.0); - } - - #[test] - fn a_new_tap_in_the_frame_an_old_one_lifted_keeps_its_force() { - use egui::TouchPhase::{End, Start}; - let mut s = Stylus::default(); - s.update(&[touch_id(1, Start, Some(0.6)), touch_id(1, End, None), touch_id(2, Start, Some(0.2))]); - assert_eq!(s.pressure(), 0.2); - s.update(&[]); - assert_eq!(s.pressure(), 0.2, "the second contact is still down"); - } - - #[test] - fn feed_wins_and_is_sanitized() { - let mut s = Stylus::default(); - s.update(&[touch(egui::TouchPhase::Start, Some(0.3))]); - s.feed.set(Some(PenSample { pressure: 0.6, tilt_x: 120.0, tilt_y: -30.0, rotation: -90.0, eraser: false })); - assert_eq!(s.sample(), Some(PenSample { pressure: 0.6, tilt_x: 90.0, tilt_y: -30.0, rotation: 270.0, eraser: false })); - s.feed.set(None); - assert_eq!(s.pressure(), 0.3); - } - - #[test] - fn pen_samples_reach_the_brush_stroke() { - use crate::canvas::{ToolEvent, tool_event}; - use serde_json::json; - let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", json!({"width": 120, "height": 80})).unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.ui.tool = crate::state::Tool::Brush; - let m = egui::Modifiers::NONE; - app.stylus.feed.set(Some(PenSample { pressure: 0.2, tilt_x: 40.0, tilt_y: 0.0, rotation: 30.0, eraser: false })); - let pr = app.stylus.pressure(); - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: pr }, m); - app.stylus.feed.set(Some(PenSample { pressure: 0.9, tilt_x: 10.0, tilt_y: -5.0, rotation: 60.0, eraser: false })); - let pr = app.stylus.pressure(); - tool_event(&mut app, ToolEvent::Move { x: 100.0, y: 40.0, pressure: pr }, m); - tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 40.0 }, m); - let (id, p) = app.session.journal.iter().rev().find(|(id, _)| id == "paint.stroke").cloned().unwrap(); - assert_eq!(id, "paint.stroke"); - assert_eq!(p["points"][0], json!([10.0, 40.0, 0.2f32 as f64, 40.0, 0.0, 30.0])); - assert_eq!(p["points"][1], json!([100.0, 40.0, 0.9f32 as f64, 10.0, -5.0, 60.0])); - // A mouse stroke stays at full pressure with plain [x, y, p] points. - app.stylus.feed.set(None); - let pr = app.stylus.pressure(); - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 60.0, pressure: pr }, m); - tool_event(&mut app, ToolEvent::Up { x: 90.0, y: 60.0 }, m); - let (_, p) = app.session.journal.iter().rev().find(|(id, _)| id == "paint.stroke").cloned().unwrap(); - assert_eq!(p["points"][0], json!([10.0, 60.0, 1.0])); - } - - #[test] - fn stroke_points_carry_tilt_only_when_present() { - let mut s = Stylus::default(); - let pts = [[0.0, 0.0, 0.5], [10.0, 0.0, 0.7], [20.0, 0.0, 0.7]]; - s.begin_stroke(); - s.record_point(); - assert_eq!(s.stroke_points(&pts)[1], vec![10.0, 0.0, 0.7]); - s.feed.set(Some(PenSample { pressure: 0.7, tilt_x: 30.0, tilt_y: 10.0, rotation: 45.0, eraser: false })); - s.record_point(); - let out = s.stroke_points(&pts); - assert_eq!(out[0], vec![0.0, 0.0, 0.5, 0.0, 0.0, 0.0]); - assert_eq!(out[2], vec![20.0, 0.0, 0.7, 30.0, 10.0, 45.0]); - } - - #[test] - fn use_pressure_off_ignores_pen_and_touch() { - let mut s = Stylus { use_pressure: false, ..Default::default() }; - s.update(&[touch(egui::TouchPhase::Start, Some(0.3))]); - s.feed.set(Some(PenSample { pressure: 0.2, tilt_x: 40.0, ..Default::default() })); - assert_eq!((s.sample(), s.pressure()), (None, 1.0)); - s.begin_stroke(); - assert_eq!(s.stroke_points(&[[1.0, 2.0, 1.0]]), vec![vec![1.0, 2.0, 1.0]], "no tilt either"); - } - - #[test] - fn eraser_end_switches_tools_once_and_never_mid_drag() { - use crate::canvas::{ToolEvent, tool_event}; - use crate::state::Tool; - let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", serde_json::json!({"width": 60, "height": 60})).unwrap(); - app.ui.tool = Tool::Brush; - let pen = |eraser| Some(PenSample { pressure: 0.5, eraser, ..Default::default() }); - // A mouse never switches. - assert!(!Stylus::sync_eraser_tool(&mut app)); - app.stylus.feed.set(pen(true)); - assert!(Stylus::sync_eraser_tool(&mut app)); - assert_eq!(app.ui.tool, Tool::Eraser); - assert!(!Stylus::sync_eraser_tool(&mut app), "reported once"); - // Flipping back during a drag waits for the drag to end. - tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 0.5 }, egui::Modifiers::NONE); - app.stylus.feed.set(pen(false)); - assert!(!Stylus::sync_eraser_tool(&mut app)); - assert_eq!(app.ui.tool, Tool::Eraser); - tool_event(&mut app, ToolEvent::Up { x: 20.0, y: 10.0 }, egui::Modifiers::NONE); - assert!(Stylus::sync_eraser_tool(&mut app)); - assert_eq!(app.ui.tool, Tool::Brush, "the tip restores the previous tool"); - // The eraser end while the Eraser is already chosen remembers nothing to restore. - app.ui.tool = Tool::Eraser; - app.stylus.feed.set(pen(true)); - assert!(!Stylus::sync_eraser_tool(&mut app)); - app.stylus.feed.set(pen(false)); - assert!(!Stylus::sync_eraser_tool(&mut app)); - assert_eq!(app.ui.tool, Tool::Eraser); - } -} +mod tests; diff --git a/crates/ui-egui/src/stylus/tests.rs b/crates/ui-egui/src/stylus/tests.rs new file mode 100644 index 0000000000..4dcd15ee63 --- /dev/null +++ b/crates/ui-egui/src/stylus/tests.rs @@ -0,0 +1,360 @@ +use super::*; + +/// Hold a touch contact still for 1.2 s over a click-sensing area, with the press-and-hold +/// handling the app does in `raw_input_hook`. Did the area see a secondary click? +fn held_contact_right_clicks(hover_first: bool, force: Option) -> bool { + let ctx = egui::Context::default(); + let mut contacts = PenContacts::default(); + let mut right_clicked = false; + let ev = |phase, force| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(3), phase, pos: egui::pos2(50.0, 50.0), force }; + // A first frame lays the area out, so the press hits it. + let mut frames = vec![(0.0, vec![])]; + if hover_first { + frames.push((0.05, vec![ev(egui::TouchPhase::Move, None), egui::Event::PointerMoved(egui::pos2(50.0, 50.0))])); + } + frames.push(( + 0.1, + vec![ + ev(egui::TouchPhase::Start, force), + egui::Event::PointerMoved(egui::pos2(50.0, 50.0)), + egui::Event::PointerButton { + pos: egui::pos2(50.0, 50.0), + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }, + ], + )); + for t in [0.4, 0.7, 1.0, 1.3] { + frames.push((t, vec![])); + } + for (time, mut events) in frames { + // egui-winit emits the touch and its emulated pointer events together. + let mut raw = egui::RawInput { + time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(200.0, 200.0))), + ..Default::default() + }; + raw.events.append(&mut events); + let pen = contacts.observe(&raw.events); + pen_hold_is_no_right_click(&ctx, pen); + let mut out = ctx.run_ui(raw, |ui| { + let r = ui.allocate_rect(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(200.0, 200.0)), egui::Sense::click_and_drag()); + right_clicked |= r.secondary_clicked(); + }); + out.textures_delta.clear(); + } + right_clicked +} + +#[test] +fn a_held_pen_is_not_a_right_click_but_a_held_finger_still_is() { + assert!(held_contact_right_clicks(false, None), "a finger's press-and-hold is egui's context menu"); + assert!(!held_contact_right_clicks(true, None), "a pen that hovered first"); + assert!(!held_contact_right_clicks(false, Some(0.4)), "a contact that reports pressure"); +} + +#[test] +fn pen_contacts_follow_hover_force_and_lift() { + use egui::TouchPhase::{Cancel, End, Move, Start}; + let t = |id, phase, force| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(id), phase, pos: egui::pos2(1.0, 1.0), force }; + let mut c = PenContacts::default(); + assert!(!c.observe(&[t(1, Move, None)]), "hovering is no contact"); + assert!(c.observe(&[t(1, Start, None)])); + assert!(c.observe(&[]), "still down"); + assert!(c.observe(&[t(1, End, None)]), "the lift frame still counts"); + assert!(!c.observe(&[])); + // A finger, until it reports a force. + assert!(!c.observe(&[t(9, Start, None), t(9, Move, None)])); + assert!(c.observe(&[t(9, Move, Some(0.5))])); + assert!(c.observe(&[t(9, Cancel, None)])); + assert!(!c.observe(&[])); +} + +fn touch(phase: egui::TouchPhase, force: Option) -> egui::Event { + egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(0), phase, pos: egui::pos2(1.0, 1.0), force } +} + +fn pen(pressure: f32) -> PenSample { + PenSample { pressure, ..Default::default() } +} + +#[test] +fn the_feed_queues_every_sample_in_order_and_keeps_the_latest() { + let feed = StylusFeed::default(); + for p in [0.1, 0.2, 0.3] { + feed.set(Some(pen(p))); + } + assert_eq!(feed.get().map(|s| s.pressure), Some(0.3)); + assert_eq!(feed.drain().iter().map(|s| s.pressure).collect::>(), vec![0.1, 0.2, 0.3]); + assert!(feed.drain().is_empty(), "drained once"); + feed.set(None); + assert_eq!(feed.get(), None, "a lifted pen is not queued"); + assert!(feed.drain().is_empty()); + // A UI that stops draining keeps only the newest samples. + for i in 0..FEED_QUEUE + 10 { + feed.set(Some(pen((i % 100) as f32 / 100.0))); + } + assert_eq!(feed.drain().len(), FEED_QUEUE); +} + +#[test] +fn each_move_takes_its_share_of_the_frames_pen_samples() { + let mut s = Stylus::default(); + s.feed.set(Some(pen(0.2))); + s.update(&[]); + s.begin_stroke(); + // Next frame: the pen reported 0.4, 0.6 and 0.8 while six pointer moves arrived. + for p in [0.4, 0.6, 0.8] { + s.feed.set(Some(pen(p))); + } + s.update(&[]); + let got: Vec = (0..6) + .map(|k| { + s.select(k, 6); + s.pressure() + }) + .collect(); + let want = [0.3, 0.4, 0.5, 0.6, 0.7, 0.8]; + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6), "{got:?}"); + s.clear_selection(); + assert_eq!(s.pressure(), 0.8, "back to the current sample"); +} + +#[test] +fn the_pressure_curve_reshapes_pen_pressure_but_not_the_mouse() { + let mut s = Stylus::default(); + s.set_pressure_curve(&[[0.0, 0.0], [0.3, 0.6], [1.0, 1.0]]); + s.feed.set(Some(pen(0.3))); + s.update(&[]); + assert!((s.pressure() - 0.6).abs() < 1e-5, "{}", s.pressure()); + s.set_pressure_curve(&[[0.0, 0.0], [1.0, 1.0]]); + assert!((s.pressure() - 0.3).abs() < 1e-6, "linear again"); + // A mouse is full pressure whatever the curve. + let mut m = Stylus::default(); + m.set_pressure_curve(&[[0.0, 0.0], [1.0, 0.2]]); + m.update(&[egui::Event::PointerMoved(egui::pos2(1.0, 1.0))]); + assert_eq!(m.pressure(), 1.0); +} + +#[test] +fn a_second_update_in_the_same_frame_keeps_its_samples() { + // The canvas runs once per view, and egui may run a frame in several passes. + let mut s = Stylus::default(); + s.feed.set(Some(pen(0.4))); + s.feed.set(Some(pen(0.8))); + s.update_for_frame(7, &[]); + s.update_for_frame(7, &[]); + s.select(0, 2); + assert!((s.pressure() - 0.4).abs() < 1e-6, "{}", s.pressure()); +} + +#[test] +fn a_new_stroke_never_starts_from_an_old_strokes_pressure() { + let mut s = Stylus::default(); + s.feed.set(Some(pen(0.9))); + s.update(&[]); + s.feed.set(Some(pen(0.1))); + s.update(&[]); + s.begin_stroke(); + s.select(0, 2); + assert!((s.pressure() - 0.1).abs() < 1e-6, "{}", s.pressure()); +} + +#[test] +fn a_mouse_or_use_pressure_off_paints_at_full_pressure() { + let mut s = Stylus::default(); + s.update(&[egui::Event::PointerMoved(egui::pos2(1.0, 1.0))]); + s.select(0, 1); + assert_eq!(s.pressure(), 1.0); + s.feed.set(Some(pen(0.3))); + s.use_pressure = false; + s.update(&[]); + s.select(0, 1); + assert_eq!(s.pressure(), 1.0); +} + +#[test] +fn rotation_between_samples_takes_the_short_way_round() { + let mut s = Stylus::default(); + s.feed.set(Some(PenSample { rotation: 350.0, ..pen(1.0) })); + s.update(&[]); + s.feed.set(Some(PenSample { rotation: 10.0, ..pen(1.0) })); + s.update(&[]); + s.select(0, 2); + let r = s.sample().map_or(-1.0, |p| p.rotation); + assert!(r.abs() < 1e-3 || (r - 360.0).abs() < 1e-3, "halfway from 350° to 10° is 0°, got {r}"); +} + +#[test] +fn mouse_is_full_pressure() { + let mut s = Stylus::default(); + s.update(&[egui::Event::PointerMoved(egui::pos2(3.0, 4.0))]); + assert_eq!(s.pressure(), 1.0); + assert_eq!(s.sample(), None); +} + +#[test] +fn touch_force_drives_pressure_until_lift() { + let mut s = Stylus::default(); + s.update(&[touch(egui::TouchPhase::Start, Some(0.25))]); + assert_eq!(s.pressure(), 0.25); + s.update(&[touch(egui::TouchPhase::Move, Some(0.8)), touch(egui::TouchPhase::Move, Some(1.7))]); + assert_eq!(s.pressure(), 1.0, "clamped"); + s.update(&[touch(egui::TouchPhase::Move, Some(f32::NAN))]); + assert_eq!(s.pressure(), 1.0); + s.update(&[touch(egui::TouchPhase::Move, Some(0.4))]); + assert_eq!(s.pressure(), 0.4); + // The lift frame still paints at the last force; the next frame is back to the mouse. + s.update(&[touch(egui::TouchPhase::End, None)]); + assert_eq!(s.pressure(), 0.4); + s.update(&[]); + assert_eq!(s.pressure(), 1.0); +} + +fn touch_id(id: u64, phase: egui::TouchPhase, force: Option) -> egui::Event { + egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(id), phase, pos: egui::pos2(1.0, 1.0), force } +} + +#[test] +fn a_light_windows_pen_tap_is_not_full_pressure() { + use egui::TouchPhase::{End, Move, Start}; + // winit on Windows reports a pen pressed below its first pressure level with no force + // (pressure 0 maps to `None`). The pen hovered first, so the tap is pressure 0, not a + // mouse click's 1. + let mut s = Stylus::default(); + s.update(&[touch_id(5, Move, None)]); + assert_eq!(s.pressure(), 1.0, "hovering is no contact"); + s.update(&[touch_id(5, Start, None), touch_id(5, End, None)]); + assert_eq!(s.pressure(), 0.0); + assert_eq!(s.tap_pressure(), 0.0); + s.update(&[]); + assert_eq!(s.pressure(), 1.0, "lifted"); + // A pen known from an earlier force: a stroke pressed before its first level starts at 0 + // and then follows the pen. + let mut s = Stylus::default(); + s.update(&[touch_id(7, Start, Some(0.5)), touch_id(7, End, None)]); + s.update(&[]); + s.update(&[touch_id(8, Start, None)]); + assert_eq!(s.pressure(), 0.0); + s.update(&[touch_id(8, Move, Some(0.3))]); + assert_eq!(s.pressure(), 0.3); + // A force-less move mid-stroke keeps the last force. + s.update(&[touch_id(8, Move, None)]); + assert_eq!(s.pressure(), 0.3); +} + +#[test] +fn a_finger_without_force_still_paints_at_full_pressure() { + use egui::TouchPhase::{End, Move, Start}; + let mut s = Stylus::default(); + s.update(&[touch_id(1, Start, None), touch_id(1, Move, None)]); + assert_eq!(s.pressure(), 1.0); + s.update(&[touch_id(1, End, None)]); + s.update(&[]); + assert_eq!(s.pressure(), 1.0); +} + +#[test] +fn a_new_tap_in_the_frame_an_old_one_lifted_keeps_its_force() { + use egui::TouchPhase::{End, Start}; + let mut s = Stylus::default(); + s.update(&[touch_id(1, Start, Some(0.6)), touch_id(1, End, None), touch_id(2, Start, Some(0.2))]); + assert_eq!(s.pressure(), 0.2); + s.update(&[]); + assert_eq!(s.pressure(), 0.2, "the second contact is still down"); +} + +#[test] +fn feed_wins_and_is_sanitized() { + let mut s = Stylus::default(); + s.update(&[touch(egui::TouchPhase::Start, Some(0.3))]); + s.feed.set(Some(PenSample { pressure: 0.6, tilt_x: 120.0, tilt_y: -30.0, rotation: -90.0, eraser: false })); + assert_eq!(s.sample(), Some(PenSample { pressure: 0.6, tilt_x: 90.0, tilt_y: -30.0, rotation: 270.0, eraser: false })); + s.feed.set(None); + assert_eq!(s.pressure(), 0.3); +} + +#[test] +fn pen_samples_reach_the_brush_stroke() { + use crate::canvas::{ToolEvent, tool_event}; + use serde_json::json; + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 120, "height": 80})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.ui.tool = crate::state::Tool::Brush; + let m = egui::Modifiers::NONE; + app.stylus.feed.set(Some(PenSample { pressure: 0.2, tilt_x: 40.0, tilt_y: 0.0, rotation: 30.0, eraser: false })); + let pr = app.stylus.pressure(); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 40.0, pressure: pr }, m); + app.stylus.feed.set(Some(PenSample { pressure: 0.9, tilt_x: 10.0, tilt_y: -5.0, rotation: 60.0, eraser: false })); + let pr = app.stylus.pressure(); + tool_event(&mut app, ToolEvent::Move { x: 100.0, y: 40.0, pressure: pr }, m); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 40.0 }, m); + let (id, p) = app.session.journal.iter().rev().find(|(id, _)| id == "paint.stroke").cloned().unwrap(); + assert_eq!(id, "paint.stroke"); + assert_eq!(p["points"][0], json!([10.0, 40.0, 0.2f32 as f64, 40.0, 0.0, 30.0])); + assert_eq!(p["points"][1], json!([100.0, 40.0, 0.9f32 as f64, 10.0, -5.0, 60.0])); + // A mouse stroke stays at full pressure with plain [x, y, p] points. + app.stylus.feed.set(None); + let pr = app.stylus.pressure(); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 60.0, pressure: pr }, m); + tool_event(&mut app, ToolEvent::Up { x: 90.0, y: 60.0 }, m); + let (_, p) = app.session.journal.iter().rev().find(|(id, _)| id == "paint.stroke").cloned().unwrap(); + assert_eq!(p["points"][0], json!([10.0, 60.0, 1.0])); +} + +#[test] +fn stroke_points_carry_tilt_only_when_present() { + let mut s = Stylus::default(); + let pts = [[0.0, 0.0, 0.5], [10.0, 0.0, 0.7], [20.0, 0.0, 0.7]]; + s.begin_stroke(); + s.record_point(); + assert_eq!(s.stroke_points(&pts)[1], vec![10.0, 0.0, 0.7]); + s.feed.set(Some(PenSample { pressure: 0.7, tilt_x: 30.0, tilt_y: 10.0, rotation: 45.0, eraser: false })); + s.record_point(); + let out = s.stroke_points(&pts); + assert_eq!(out[0], vec![0.0, 0.0, 0.5, 0.0, 0.0, 0.0]); + assert_eq!(out[2], vec![20.0, 0.0, 0.7, 30.0, 10.0, 45.0]); +} + +#[test] +fn use_pressure_off_ignores_pen_and_touch() { + let mut s = Stylus { use_pressure: false, ..Default::default() }; + s.update(&[touch(egui::TouchPhase::Start, Some(0.3))]); + s.feed.set(Some(PenSample { pressure: 0.2, tilt_x: 40.0, ..Default::default() })); + assert_eq!((s.sample(), s.pressure()), (None, 1.0)); + s.begin_stroke(); + assert_eq!(s.stroke_points(&[[1.0, 2.0, 1.0]]), vec![vec![1.0, 2.0, 1.0]], "no tilt either"); +} + +#[test] +fn eraser_end_switches_tools_once_and_never_mid_drag() { + use crate::canvas::{ToolEvent, tool_event}; + use crate::state::Tool; + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", serde_json::json!({"width": 60, "height": 60})).unwrap(); + app.ui.tool = Tool::Brush; + let pen = |eraser| Some(PenSample { pressure: 0.5, eraser, ..Default::default() }); + // A mouse never switches. + assert!(!Stylus::sync_eraser_tool(&mut app)); + app.stylus.feed.set(pen(true)); + assert!(Stylus::sync_eraser_tool(&mut app)); + assert_eq!(app.ui.tool, Tool::Eraser); + assert!(!Stylus::sync_eraser_tool(&mut app), "reported once"); + // Flipping back during a drag waits for the drag to end. + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 0.5 }, egui::Modifiers::NONE); + app.stylus.feed.set(pen(false)); + assert!(!Stylus::sync_eraser_tool(&mut app)); + assert_eq!(app.ui.tool, Tool::Eraser); + tool_event(&mut app, ToolEvent::Up { x: 20.0, y: 10.0 }, egui::Modifiers::NONE); + assert!(Stylus::sync_eraser_tool(&mut app)); + assert_eq!(app.ui.tool, Tool::Brush, "the tip restores the previous tool"); + // The eraser end while the Eraser is already chosen remembers nothing to restore. + app.ui.tool = Tool::Eraser; + app.stylus.feed.set(pen(true)); + assert!(!Stylus::sync_eraser_tool(&mut app)); + app.stylus.feed.set(pen(false)); + assert!(!Stylus::sync_eraser_tool(&mut app)); + assert_eq!(app.ui.tool, Tool::Eraser); +} From 98046d89727e34af6f407b46e279ab873bc4f428 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:34 +0000 Subject: [PATCH 102/259] refactor(ui-egui): move widgets.rs tests to widgets/tests.rs --- crates/ui-egui/src/widgets.rs | 1021 +-------------------------- crates/ui-egui/src/widgets/tests.rs | 1018 ++++++++++++++++++++++++++ 2 files changed, 1019 insertions(+), 1020 deletions(-) create mode 100644 crates/ui-egui/src/widgets/tests.rs diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 9becc29532..24e0713e2f 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -1955,1026 +1955,7 @@ fn clean(text: &str) -> String { } #[cfg(test)] -mod tests { - use super::{hue_color, hue_stops}; - use egui::{Color32, Key, Modifiers}; - - #[test] - fn hue_stops_are_pure_and_evenly_spaced() { - let c = |r, g, b| Color32::from_rgb(r, g, b); - let want = [c(255, 0, 0), c(255, 255, 0), c(0, 255, 0), c(0, 255, 255), c(0, 0, 255), c(255, 0, 255), c(255, 0, 0)]; - let stops = hue_stops(); - assert_eq!(stops.len(), 13); - for (k, w) in want.iter().enumerate() { - assert_eq!(stops[k * 2], *w, "stop at {} degrees", k * 60); - assert_eq!(hue_color(k as f32 * 60.0), *w); - } - } - - /// A light theme rings the slider knob with its outline token; a dark Studio-layout one draws - /// the plain knob (#7927). - #[test] - fn light_themes_draw_the_slider_knob_outline() { - use crate::theme::{ThemeKind, Tokens}; - fn rings(shape: &egui::Shape, out: &mut Vec) { - match shape { - egui::Shape::Vec(v) => v.iter().for_each(|s| rings(s, out)), - egui::Shape::Circle(c) if c.radius == 7.0 && c.stroke.width == 1.0 => out.push(c.stroke.color), - _ => {} - } - } - for kind in [ThemeKind::StudioLight, ThemeKind::Adwaita, ThemeKind::BreezeLight, ThemeKind::SoftLight, ThemeKind::Studio] { - let ctx = egui::Context::default(); - crate::theme::apply(&ctx, kind); - let mut v = 50.0; - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { - super::slider(ui, &mut v, 0.0..=100.0, None); - }); - out.textures_delta.clear(); - let mut found = Vec::new(); - out.shapes.iter().for_each(|c| rings(&c.shape, &mut found)); - let want: Vec<_> = Tokens::for_kind(kind).knob_outline().into_iter().collect(); - assert_eq!(found, want, "{kind:?}"); - } - } - - #[test] - fn checkbox_label_is_a_button_target_not_selectable_text() { - use egui::CursorIcon; - use egui_kittest::{ - Harness, - kittest::{NodeT, Queryable}, - }; - - let mut h = Harness::builder().with_size(egui::vec2(300.0, 80.0)).build_ui_state( - |ui, on: &mut bool| { - super::checkbox(ui, on, "Show Transform Controls"); - }, - false, - ); - h.run_steps(2); - let label = h.get_by_label("Show Transform Controls").rect(); - h.hover_at(label.center()); - h.run_steps(2); - assert_eq!(h.output().platform_output.cursor_icon, CursorIcon::PointingHand); - h.get_by_label("Show Transform Controls").click(); - h.run_steps(2); - assert!(*h.state()); - let checkbox = h.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Show Transform Controls"); - assert_eq!(checkbox.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True)); - checkbox.focus(); - h.run_steps(1); - h.key_press(egui::Key::Space); - h.run_steps(2); - assert!(!*h.state(), "the same named checkbox supports Space"); - } - - /// #3208: a rounded swatch's checker is one shared, repeating, unblurred two-by-two tile on - /// the rounded rect, scaled so a cell stays `cell` points, so nothing shows past the corners. - #[test] - fn rounded_swatches_clip_their_checker_to_the_corners() { - use egui::{Pos2, Rect, pos2, vec2}; - let mut h = egui_kittest::Harness::builder().with_size(vec2(200.0, 100.0)).build_ui(|ui| { - super::color_swatch(ui, egui::Color32::RED); - super::color_swatch_button(ui, egui::Color32::from_rgba_unmultiplied(0, 0, 255, 128), "Blue"); - }); - crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run_steps(2); - let tile = h.ctx.data(|d| d.get_temp::(super::checker_tile_id())).expect("the tile is loaded once"); - let manager = h.ctx.tex_manager(); - let manager = manager.read(); - let meta = manager.meta(tile.id()).expect("the tile is in the texture manager"); - assert_eq!(meta.size, [2, 2]); - assert_eq!(meta.options.wrap_mode, egui::TextureWrapMode::Repeat); - assert_eq!(meta.options.magnification, egui::TextureFilter::Nearest); - assert_eq!(super::checker_uv(Rect::from_min_size(Pos2::ZERO, vec2(40.0, 18.0)), 4.0), Rect::from_min_max(Pos2::ZERO, pos2(5.0, 2.25))); - assert_eq!( - super::checker_uv(Rect::from_min_size(Pos2::ZERO, vec2(8.0, 8.0)), 0.0), - Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), - "a bad cell falls back to 4 pt" - ); - } - - /// #3580: the shared eliding label never lays out wider than the room it is given, so a longer - /// translation shrinks with '…' instead of overrunning its row; a short label is untouched. - #[test] - fn elided_label_never_exceeds_its_room() { - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(240.0, 60.0)).build_ui(|ui| { - let long = super::elided_label(ui, "Preenchimento:", 24.0); // pt-br Fill:, the longest catalog - assert!(long.rect.width() <= 25.0, "elided to the room, got {}", long.rect.width()); - let short = super::elided_label(ui, "Fill", 200.0); - assert!(short.rect.width() < 60.0, "a short label is not padded: {}", short.rect.width()); - }); - crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run_steps(2); - } - - #[test] - fn spectrum_popup_style_matches_main_menu_and_preserves_studio() { - for kind in [crate::theme::ThemeKind::Pro, crate::theme::ThemeKind::ProMedium, crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::StudioLight] { - let ctx = egui::Context::default(); - crate::theme::apply(&ctx, kind); - let tokens = crate::theme::Tokens::for_kind(kind); - let mut out = ctx.run_ui(Default::default(), |ui| { - let original_padding = ui.spacing().button_padding; - let original_hover = ui.visuals().widgets.hovered.fg_stroke; - super::style_spectrum_popup_menu(ui); - assert_eq!(ui.spacing().item_spacing.y, 0.0, "{kind:?}: menu rows meet so the gap is selectable"); - if tokens.pro { - assert_eq!(ui.spacing().button_padding, egui::vec2(10.0, 4.0)); - assert_eq!(ui.visuals().widgets.hovered.bg_fill, tokens.accent); - assert_eq!(ui.visuals().widgets.hovered.fg_stroke.color, egui::Color32::WHITE); - } else { - assert_eq!(ui.spacing().button_padding, original_padding); - assert_eq!(ui.visuals().widgets.hovered.fg_stroke, original_hover); - } - }); - out.textures_delta.clear(); - } - } - - /// One primary press+release at `pos`. When `touch`, emit Touch Start/End with the pointer events (as egui-winit does) so [`super::second_click`] uses the touch distance. - fn pointer_click(ctx: &egui::Context, time: f64, pos: egui::Pos2, touch: bool) -> bool { - let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(200.0, 200.0)); - let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; - let touch_ev = |phase| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(1), phase, pos, force: None }; - let mut saw = false; - for (t, mut events) in [ - (time, { - let mut v = vec![egui::Event::PointerMoved(pos), button(true)]; - if touch { - v.insert(0, touch_ev(egui::TouchPhase::Start)); - } - v - }), - (time + 0.02, { - let mut v = vec![button(false)]; - if touch { - v.insert(0, touch_ev(egui::TouchPhase::End)); - } - v - }), - ] { - let mut raw = egui::RawInput { time: Some(t), screen_rect: Some(area), ..Default::default() }; - raw.events.append(&mut events); - let mut out = ctx.run_ui(raw, |ui| { - let r = ui.allocate_rect(area, egui::Sense::click()); - saw |= super::second_click(ui, &r); - }); - out.textures_delta.clear(); - } - saw - } - - /// #2274 touch: taps past egui's 6 px mouse limit (and past the old 32 px touch slop) within 0.5 s still count as a double; the same mouse path does not. - #[test] - fn second_click_tolerates_touch_jitter_but_keeps_mouse_tight() { - let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(200.0, 200.0)); - let a = egui::pos2(50.0, 50.0); - let mild = egui::pos2(70.0, 50.0); // 20 px — past mouse max_click_dist (6) - let wide = egui::pos2(50.0 + 48.0, 50.0); // past the old 32 px slop, inside TOUCH_MAX_CLICK_DIST (64) - for touch in [false, true] { - let ctx = egui::Context::default(); - let mut out = ctx.run_ui(egui::RawInput { time: Some(0.0), screen_rect: Some(area), ..Default::default() }, |ui| { - ui.allocate_rect(area, egui::Sense::click()); - }); - out.textures_delta.clear(); - assert!(!pointer_click(&ctx, 0.1, a, touch), "first click only arms the pair"); - let second = pointer_click(&ctx, 0.25, mild, touch); - assert_eq!(second, touch, "touch={touch}: 20 px jitter is a double only for touch"); - } - // Touch-only: casual Framework-style drift beyond the previous 32 px budget. - let ctx = egui::Context::default(); - let mut out = ctx.run_ui(egui::RawInput { time: Some(0.0), screen_rect: Some(area), ..Default::default() }, |ui| { - ui.allocate_rect(area, egui::Sense::click()); - }); - out.textures_delta.clear(); - assert!(!pointer_click(&ctx, 0.1, a, true)); - assert!(pointer_click(&ctx, 0.25, wide, true), "48 px touch jitter is still a double"); - } - - /// A mouse double past the time window is not a double, even at the same pixel. - #[test] - fn second_click_respects_the_half_second_window() { - let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(200.0, 200.0)); - let p = egui::pos2(40.0, 40.0); - let ctx = egui::Context::default(); - let mut out = ctx.run_ui(egui::RawInput { time: Some(0.0), screen_rect: Some(area), ..Default::default() }, |ui| { - ui.allocate_rect(area, egui::Sense::click()); - }); - out.textures_delta.clear(); - assert!(!pointer_click(&ctx, 0.1, p, false)); - assert!(!pointer_click(&ctx, 0.1 + super::DOUBLE_CLICK_S + 0.05, p, false), "past Windows' 0.5 s window"); - } - - use egui_kittest::{Harness, kittest::Queryable}; - - /// A panel footer's buttons are drawn whole. The bar runs on over the body's bottom margin, so a - /// body that clips where its content ends (as the panels do) cut the bottom off every button: - /// the hover highlight of a 26 px button was about 21 px tall in the Paths, Layers and Channels - /// panels (#6238). - #[test] - fn panel_footer_buttons_are_not_clipped_by_the_body() { - let mut h = Harness::new_ui_state( - |ui, s: &mut Option<(egui::Rect, egui::Rect, egui::Rect)>| { - // A body exactly as tall as the footer takes, clipped there. - let body = egui::Rect::from_min_size(ui.max_rect().min, egui::vec2(220.0, super::footer_height(ui))); - let mut body_ui = ui.new_child(egui::UiBuilder::new().max_rect(body)); - body_ui.set_clip_rect(body); - super::panel_footer(&mut body_ui, |bar| { - let b = crate::icons::button(bar, "square", 26.0, false, "Button"); - *s = Some((b.rect, bar.clip_rect(), body)); - }); - }, - None, - ); - crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run(); - let (button, clip, body) = h.state().expect("the footer drew its button"); - assert!(button.bottom() > body.bottom(), "the bar really overruns the body, or this test proves nothing: {button:?} vs {body:?}"); - assert!(clip.contains_rect(button), "the whole button is inside the clip: {button:?} not in {clip:?}"); - } - - /// #3789: a plain text field is one boxed, outline-free input whose text-selection colour stays - /// local, so it isn't recoloured for the rest of the frame (selected rows, slider trails). - #[test] - fn text_field_is_a_boxed_input_whose_selection_colour_stays_local() { - use egui::accesskit::Role; - let mut h = Harness::new_ui_state( - |ui, s: &mut (String, egui::Color32, egui::Color32)| { - s.1 = ui.visuals().selection.bg_fill; - super::text_field(ui, egui::Id::unique("tf"), &mut s.0, "hint", 140.0, false); - s.2 = ui.visuals().selection.bg_fill; - }, - (String::new(), egui::Color32::WHITE, egui::Color32::BLACK), - ); - crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run(); - assert_eq!(h.state().1, h.state().2, "the field's selection colour does not leak into its parent"); - h.get_by_role(Role::TextInput).click(); - h.run_steps(1); - for ch in "abc".chars() { - h.event(egui::Event::Text(ch.to_string())); - h.run_steps(1); - } - assert_eq!(h.state().0, "abc", "typing reaches the bound string"); - } - - /// #2150: a huge paste into a plain text field stops at its limit instead of growing the - /// string (and its laid-out text) without bound. - #[test] - fn text_field_caps_a_huge_paste() { - use egui::accesskit::Role; - let mut h = Harness::new_ui_state(|ui, s: &mut String| drop(super::text_field(ui, egui::Id::unique("tf"), s, "Value", 140.0, false)), String::new()); - crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run(); - h.get_by_role(Role::TextInput).click(); - h.run_steps(1); - h.event(egui::Event::Paste("9".repeat(200_000))); - h.run_steps(1); - assert_eq!(h.state().chars().count(), super::TEXT_FIELD_LIMIT); - // A second paste adds nothing past the limit. - h.event(egui::Event::Paste("9".repeat(10))); - h.run_steps(1); - assert_eq!(h.state().chars().count(), super::TEXT_FIELD_LIMIT); - } - - /// #2150: a value already past the limit is laid out only up to it, and stays the caller's - /// until the field is edited, which keeps the bounded copy. - #[test] - fn text_field_bounds_an_oversized_existing_value() { - use egui::accesskit::Role; - let long = "9".repeat(super::TEXT_FIELD_LIMIT * 4); - let mut h = Harness::new_ui_state(|ui, s: &mut String| drop(super::text_field(ui, egui::Id::unique("tf"), s, "Value", 140.0, false)), long.clone()); - crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run(); - assert_eq!(*h.state(), long, "drawing alone leaves the caller's value alone"); - assert_eq!(h.get_by_role(Role::TextInput).value().map(|v| v.chars().count()), Some(super::TEXT_FIELD_LIMIT)); - h.get_by_role(Role::TextInput).click(); - h.run_steps(1); - h.event(egui::Event::Key { key: egui::Key::Backspace, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); - h.run_steps(1); - assert!(h.state().chars().count() < super::TEXT_FIELD_LIMIT, "an edit keeps the bounded copy"); - } - - /// #2150: text queued by the control channel (`ui.type`) joins the input in `raw_input_hook` - /// and is cut like the OS's, so the cap must run after it is appended. - #[test] - fn raw_input_hook_caps_synthetic_text() { - use eframe::App as _; - let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.synthetic.push(egui::Event::Text("x".repeat(super::INPUT_EVENT_LIMIT + 10))); - let ctx = egui::Context::default(); - let mut raw = egui::RawInput::default(); - app.raw_input_hook(&ctx, &mut raw); - let texts: Vec = raw.events.iter().filter_map(|e| if let egui::Event::Text(t) = e { Some(t.chars().count()) } else { None }).collect(); - assert_eq!(texts, [super::INPUT_EVENT_LIMIT]); - } - - /// #2150: every text-carrying event is cut to the app-wide limit at a character boundary - /// before any widget sees it; other events and short text pass untouched. - #[test] - fn oversized_text_events_are_cut_before_widgets_see_them() { - let long = "é".repeat(super::INPUT_EVENT_LIMIT + 5); - let mut events = vec![ - egui::Event::Paste(long.clone()), - egui::Event::Text(long.clone()), - egui::Event::Ime(egui::ImeEvent::Commit(long.clone())), - egui::Event::Ime(egui::ImeEvent::Preedit { text: long, active_range_chars: Some(0..super::INPUT_EVENT_LIMIT + 2) }), - egui::Event::Text("ok".into()), - egui::Event::Copy, - ]; - super::cap_text_events(&mut events); - for e in &events[..4] { - let (egui::Event::Paste(t) - | egui::Event::Text(t) - | egui::Event::Ime(egui::ImeEvent::Commit(t)) - | egui::Event::Ime(egui::ImeEvent::Preedit { text: t, .. })) = e - else { - panic!("{e:?}") - }; - assert_eq!(t.chars().count(), super::INPUT_EVENT_LIMIT); - } - assert!(matches!(&events[3], egui::Event::Ime(egui::ImeEvent::Preedit { active_range_chars: None, .. })), "the range past the cut is dropped"); - assert_eq!(events[4], egui::Event::Text("ok".into())); - assert_eq!(events[5], egui::Event::Copy); - } - - /// A row's visible caption names both its number and its slider; a dropdown is named by its - /// own caption, or by the scrubby caption drawn just before it. - #[test] - fn labelled_rows_and_dropdowns_have_semantic_accessible_names() { - use egui_kittest::{Harness, kittest::Queryable}; - - #[derive(Default)] - struct State { - value: f32, - fill: f32, - blend: usize, - mode: usize, - } - - let mut h = Harness::builder().with_size(egui::vec2(360.0, 240.0)).build_ui_state( - |ui, s: &mut State| { - super::slider_row(ui, "Opacity", &mut s.value, 0.0..=100.0, "%", None); - super::popup_value_field(ui, "Fill", &mut s.fill, 0.0..=100.0, "%", 74.0); - let opts = [(0usize, "Normal"), (1, "Multiply")]; - super::dropdown(ui, "blend", "Blend Mode", &mut s.blend, &opts, 120.0); - ui.horizontal(|ui| { - let caption = ui.label("Mode"); - super::scrub_option_label(ui, &caption); - super::dropdown(ui, "mode", "Not this name", &mut s.mode, &opts, 120.0); - }); - }, - State::default(), - ); - crate::PhotocraftApp::setup_context(&h.ctx, Default::default()); - h.run(); - - // The row's caption is the accessible name of the value field and of the slider. - h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Opacity"); - h.get_by_role_and_label(egui::accesskit::Role::Slider, "Opacity"); - // A popup value field names both its number and the arrow that opens its slider. - h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Fill"); - h.get_by_role_and_label(egui::accesskit::Role::Button, "Fill"); - // A dropdown requires a real name; a preceding scrubby caption is used when present. - h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Blend Mode"); - h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Mode"); - } - - /// Sets up a test with one value field. Its state is its value and how many times it changed. - fn field(value: f32, range: std::ops::RangeInclusive) -> Harness<'static, (f32, u32)> { - let mut h = Harness::new_ui_state( - move |ui, s: &mut (f32, u32)| { - if super::value_field(ui, &mut s.0, range.clone(), "px", 80.0).accessible_name("Test number").changed() { - s.1 += 1; - } - }, - (value, 0), - ); - h.run(); - h - } - - fn press(h: &mut Harness<'static, (f32, u32)>, mods: Modifiers, key: Key) -> f32 { - h.key_press_modifiers(mods, key); - h.run(); - h.state().0 - } - - fn focused(value: f32, range: std::ops::RangeInclusive) -> Harness<'static, (f32, u32)> { - let mut h = field(value, range); - h.get_by_role(egui::accesskit::Role::SpinButton).click(); - h.run(); - h - } - - /// The number's slot (and its focus outline) is centred in the box (#5150). - #[test] - fn value_field_number_slot_is_centred_in_its_box() { - let mut h = Harness::new_ui_state( - |ui, s: &mut (f32, egui::Rect)| { - let field = super::value_field_in(ui, &mut s.0, 0.0..=100.0, "px", 80.0, 0.0, super::FieldOpts::default(), None); - s.1 = field.1; - field.0.accessible_name("Value"); - }, - (50.0, egui::Rect::NOTHING), - ); - h.run(); - let number = h.get_by_role(egui::accesskit::Role::SpinButton).rect(); - let field = h.state().1; - assert!((field.center().y - number.center().y).abs() < 0.01, "field {field:?}, number {number:?}"); - } - - /// The digits' ink, not just their slot, is centred in the box, and starts level with the - /// `%`'s, so the number lines up with the box and its unit (#5150). - #[test] - fn value_field_digits_ink_is_centred_and_level_with_the_unit() { - let _gpu = photocraft_testkit::gpu_lock(); - let scale = 4.0; - for kind in [crate::theme::ThemeKind::Pro, crate::theme::ThemeKind::Studio] { - let mut h = Harness::builder().with_size(egui::vec2(100.0, 40.0)).with_pixels_per_point(scale).wgpu().build_ui_state( - |ui, s: &mut (f32, egui::Rect)| { - let field = super::value_field_in(ui, &mut s.0, 0.0..=100.0, "%", 80.0, 0.0, super::FieldOpts::default(), None); - s.1 = field.1; - field.0.accessible_name("Value"); - }, - (100.0, egui::Rect::NOTHING), - ); - crate::PhotocraftApp::setup_context(&h.ctx, kind); - h.run_steps(3); - let image = h.render().expect("render value field"); - let (field, suffix_left) = (h.state().1, h.state().1.right() - 14.0); - let px = |v: f32| (v * scale) as u32; - let bg = image.get_pixel(px(field.left() + 2.0), px(field.center().y)).0; - let lum = |p: [u8; 4]| u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2]); - // Top and bottom of the ink (pt) between x0 and x1. - let ink = |x0: f32, x1: f32| { - let rows: Vec = (px(field.top() + 2.0)..px(field.bottom() - 2.0)) - .filter(|&y| (px(x0)..px(x1)).any(|x| lum(image.get_pixel(x, y).0) > lum(bg) + 150)) - .collect(); - let (top, bottom) = (rows.first().copied().unwrap_or(0), rows.last().copied().unwrap_or(0) + 1); - (top as f32 / scale, bottom as f32 / scale) - }; - let digits = ink(field.left() + 4.0, suffix_left - 2.0); - let unit = ink(suffix_left, field.right() - 2.0); - let what = format!("{kind:?}: field {field:?}, digits {digits:?}, unit {unit:?}"); - assert!(((digits.0 + digits.1) / 2.0 - field.center().y).abs() <= 0.25, "{what}"); - assert!((digits.0 - unit.0).abs() <= 0.25, "{what}"); - } - } - - /// With the app's theme (its 24 pt interact height and 4 pt button padding), in a full-size - /// box and a slim status-bar box alike, the number stays inside the box, centred in it, - /// and a long number doesn't spill out of the box's left edge (#2823). - #[test] - fn themed_value_field_number_sits_inside_its_box_in_every_size() { - for kind in crate::theme::ThemeKind::ALL { - for (w, h, v) in [(80.0, super::VALUE_FIELD_H, 50.0), (64.0, 18.0, 1600.5), (78.0, 22.0, 100.6)] { - let mut harness = Harness::new_ui_state( - move |ui, s: &mut (f32, egui::Rect)| { - let before = ui.cursor().min; - super::compact_value_field(ui, &mut s.0, 0.0..=3200.0, "%", w, h).accessible_name("Zoom"); - s.1 = egui::Rect::from_min_size(before, egui::vec2(w, h)); - }, - (v, egui::Rect::NOTHING), - ); - crate::PhotocraftApp::setup_context(&harness.ctx, kind); - harness.run(); - let number = harness.get_by_role(egui::accesskit::Role::SpinButton).rect(); - let field = harness.state().1; - let what = format!("{kind:?} {w}x{h}: field {field:?}, number {number:?}"); - assert!(field.contains_rect(number), "{what}"); - assert!((field.center().y - number.center().y).abs() < 0.51, "{what}"); - } - } - } - - /// The number's slot ends just left of its unit, by the unit's measured width: a one-character - /// `%` (the status bar zoom) leaves the number more room than the old fixed 16 pt, and a longer - /// unit never sits under the number (#3040). - #[test] - fn value_field_number_slot_stops_at_its_measured_suffix() { - for suffix in ["%", "px", "°", "×"] { - let mut h = Harness::new_ui_state( - move |ui, s: &mut (f32, egui::Rect, f32)| { - let before = ui.cursor().min; - super::compact_value_field(ui, &mut s.0, 0.0..=3200.0, suffix, 64.0, 18.0).accessible_name("Zoom"); - s.1 = egui::Rect::from_min_size(before, egui::vec2(64.0, 18.0)); - s.2 = ui.painter().layout_no_wrap(suffix.to_owned(), crate::theme::mono(11.0), egui::Color32::WHITE).size().x; - }, - (33.33, egui::Rect::NOTHING, 0.0), - ); - h.run(); - let number = h.get_by_role(egui::accesskit::Role::SpinButton).rect(); - let (_, field, suffix_w) = *h.state(); - let suffix_left = field.right() - 6.0 - suffix_w; - assert!(number.right() <= suffix_left, "{suffix}: number {number:?} runs under the suffix at {suffix_left}"); - assert!(suffix_left - number.right() <= 1.5, "{suffix}: {:.1} pt wasted before the suffix", suffix_left - number.right()); - } - } - - #[test] - fn arrow_keys_step_a_focused_field_by_one_and_shift_by_ten() { - let mut h = focused(100.0, 0.0..=1000.0); - assert_eq!(press(&mut h, Modifiers::NONE, Key::ArrowUp), 101.0); - assert_eq!(press(&mut h, Modifiers::SHIFT, Key::ArrowUp), 111.0); - assert_eq!(press(&mut h, Modifiers::NONE, Key::ArrowDown), 110.0); - assert_eq!(press(&mut h, Modifiers::SHIFT, Key::ArrowDown), 100.0); - assert_eq!(press(&mut h, Modifiers::COMMAND, Key::ArrowUp), 100.1); - assert_eq!(press(&mut h, Modifiers::COMMAND | Modifiers::SHIFT, Key::ArrowDown), 100.0); - assert_eq!(h.state().1, 6, "every step reports a change, so callers apply it"); - } - - #[test] - fn arrow_keys_on_a_field_with_a_reversed_range_do_not_panic() { - // The empty range is the case under test — arrow keys must not panic on it. - let mut h = focused(5.0, 10.0..=0.0); // NOSONAR - let _ = press(&mut h, Modifiers::NONE, Key::ArrowUp); - let mut h = focused(5.0, f32::NAN..=10.0); - let _ = press(&mut h, Modifiers::NONE, Key::ArrowDown); - } - - /// #5914: Exposure's ±20 stops keep 0.01 arrow steps when the field shows two decimals. - #[test] - fn arrow_keys_step_fractional_stops_when_decimals_are_set() { - let mut h = Harness::new_ui_state( - |ui, v: &mut f32| { - super::slider_row_prec(ui, "Exposure", v, -20.0..=20.0, "", None, super::RowGestures::default(), Some(2)); - }, - 0.0, - ); - h.run(); - h.get_by_role(egui::accesskit::Role::SpinButton).click(); - h.run(); - h.key_press_modifiers(Modifiers::NONE, Key::ArrowUp); - h.run(); - assert!((*h.state() - 0.01).abs() < 1e-6); - h.key_press_modifiers(Modifiers::NONE, Key::ArrowUp); - h.run(); - assert!((*h.state() - 0.02).abs() < 1e-6); - h.key_press_modifiers(Modifiers::SHIFT, Key::ArrowUp); - h.run(); - assert!((*h.state() - 0.12).abs() < 1e-6); - } - - #[test] - fn arrow_keys_round_decimals_step_fine_fields_and_clamp() { - for (start, mods, key, want) in [ - (55.4, Modifiers::NONE, Key::ArrowUp, 56.0), - (55.6, Modifiers::NONE, Key::ArrowUp, 57.0), - (55.4, Modifiers::NONE, Key::ArrowDown, 54.0), - (55.5, Modifiers::NONE, Key::ArrowUp, 57.0), - (55.5, Modifiers::NONE, Key::ArrowDown, 55.0), - (55.4, Modifiers::SHIFT, Key::ArrowUp, 65.0), - (55.47, Modifiers::COMMAND, Key::ArrowUp, 55.6), - ] { - assert_eq!(press(&mut focused(start, 0.0..=1000.0), mods, key), want, "{start} {mods:?} {key:?}"); - } - let mut h = focused(0.5, 0.0..=1.0); - assert_eq!(press(&mut h, Modifiers::NONE, Key::ArrowUp), 0.51); - assert_eq!(press(&mut h, Modifiers::SHIFT, Key::ArrowUp), 0.61); - assert_eq!(press(&mut h, Modifiers::COMMAND, Key::ArrowUp), 0.62); - let mut h = focused(995.0, 0.0..=1000.0); - assert_eq!(press(&mut h, Modifiers::SHIFT, Key::ArrowUp), 1000.0); - } - - /// #6545: a curved track (the mask Feather) has fine steps at the left and coarse ones toward - /// the right end, and the knob drawn for a value lands where that value is picked. - #[test] - fn curved_track_maps_ends_middle_and_round_trips() { - use super::{curve_fraction, curve_value}; - for (f, want) in [(0.0, 0.0), (0.1, 1.0), (0.2, 8.0), (0.5, 125.0), (1.0, 1000.0)] { - assert!((curve_value(f, 0.0, 1000.0, Some(3.0)) - want).abs() < 1e-3, "{f}: {}", curve_value(f, 0.0, 1000.0, Some(3.0))); - } - assert_eq!(curve_value(0.25, 0.0, 1000.0, None), 250.0, "no curve is the linear track"); - assert_eq!(curve_value(0.5, 10.0, 20.0, Some(3.0)), 11.25, "the curve starts at the range's low end"); - for i in 0..=100 { - let f = i as f32 / 100.0; - let back = curve_fraction(curve_value(f, 0.0, 1000.0, Some(3.0)), 0.0, 1000.0, Some(3.0)); - assert!((back - f).abs() < 1e-4, "{f} -> {back}"); - let v = i as f32 * 10.0; - let again = curve_value(curve_fraction(v, 0.0, 1000.0, Some(3.0)), 0.0, 1000.0, Some(3.0)); - assert!((again - v).abs() < 1e-3, "{v} -> {again}"); - } - assert_eq!(curve_fraction(-5.0, 0.0, 1000.0, Some(3.0)), 0.0); - assert_eq!(curve_fraction(f32::NAN, 0.0, 1000.0, Some(3.0)), 0.0); - } - - #[test] - fn arrow_keys_work_out_a_typed_sum_then_step_it() { - let mut h = focused(100.0, 0.0..=1000.0); - h.key_press_modifiers(Modifiers::COMMAND, Key::A); - h.event(egui::Event::Text("5+5".into())); - h.run(); - assert_eq!(press(&mut h, Modifiers::NONE, Key::ArrowUp), 11.0); - assert_eq!(press(&mut h, Modifiers::NONE, Key::ArrowDown), 10.0, "the field keeps focus"); - } - - /// #5474: a held arrow repeats on consecutive frames; every repeat steps the focused field - /// and none of them moves focus to the field above. - #[test] - fn held_arrow_keeps_stepping_the_focused_field() { - let mut h = Harness::new_ui_state( - |ui, s: &mut (f32, f32)| { - super::value_field(ui, &mut s.0, 0.0..=1000.0, "", 80.0).accessible_name("Left"); - super::value_field(ui, &mut s.1, 0.0..=1000.0, "", 80.0).accessible_name("Right"); - }, - (10.0, 59.0), - ); - h.run(); - h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(1).expect("second field").click(); - h.run(); - // Held down: key-down repeats on consecutive frames, no key-up in between. - for repeat in [false, true, true, true, true, true] { - h.event(egui::Event::Key { key: Key::ArrowUp, physical_key: None, pressed: true, repeat, modifiers: Modifiers::NONE }); - h.step(); - } - h.event(egui::Event::Key { key: Key::ArrowUp, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }); - h.run(); - assert_eq!(*h.state(), (10.0, 65.0)); - } - - #[test] - fn arrow_keys_leave_an_unfocused_field_alone() { - let mut h = field(100.0, 0.0..=1000.0); - assert_eq!(press(&mut h, Modifiers::NONE, Key::ArrowUp), 100.0); - assert_eq!(h.state().1, 0); - } - - /// Photoshop: a unit typed into a px field converts at the document resolution on Enter, and - /// an expression that can't convert (or divides by zero) keeps the value. - #[test] - fn enter_commits_a_typed_unit_expression_at_the_document_resolution() { - let mut h = field(100.0, 0.0..=10_000.0); - super::set_field_resolution(&h.ctx, 300.0, 72.0); - for (text, want) in [("1in+10", 310.0), ("2.54 cm * 2", 600.0), ("50%", 600.0), ("1in/0", 600.0), ("10px", 10.0)] { - h.get_by_role(egui::accesskit::Role::SpinButton).click(); - h.run(); - h.key_press_modifiers(Modifiers::COMMAND, Key::A); - h.event(egui::Event::Text(text.into())); - h.run(); - h.key_press(Key::Enter); - h.run(); - assert_eq!(h.state().0, want, "{text}"); - } - } - - /// Photoshop's scrubby labels: dragging the label right before a field moves its value, a - /// step a point (Shift ×10); a label with no field right after it moves nothing. - #[test] - fn dragging_a_label_scrubs_the_field_right_after_it() { - let mut h = Harness::new_ui_state( - |ui, s: &mut (f32, f32)| { - ui.horizontal(|ui| { - let l = ui.label("Size:"); - super::scrub_label(ui, &l); - super::value_field(ui, &mut s.0, 0.0..=1000.0, "px", 80.0).accessible_name("Start"); - }); - ui.horizontal(|ui| { - let l = ui.label("Mode:"); - super::scrub_label(ui, &l); - ui.add_space(60.0); - super::value_field(ui, &mut s.1, 0.0..=1000.0, "px", 80.0).accessible_name("End"); - }); - }, - (100.0, 100.0), - ); - h.run(); - let drag = |h: &mut Harness<'static, (f32, f32)>, label: &str, dx: f32, mods: Modifiers| { - let at = h.get_by_label(label).rect().center(); - h.hover_at(at); - h.run(); - h.drag_at(at); - h.run(); - for i in 1..=4 { - h.event(egui::Event::PointerMoved(at + egui::vec2(dx * i as f32 / 4.0, 0.0))); - h.event(egui::Event::ModifiersChanged(mods)); - h.run(); - } - h.drop_at(at + egui::vec2(dx, 0.0)); - h.run(); - }; - drag(&mut h, "Size:", 20.0, Modifiers::NONE); - assert_eq!(h.state().0, 120.0); - drag(&mut h, "Size:", -3.0, Modifiers::SHIFT); - assert_eq!(h.state().0, 90.0); - drag(&mut h, "Mode:", 20.0, Modifiers::NONE); - assert_eq!(h.state().1, 100.0, "the field isn't right after the label"); - } - - /// A right-aligned OK / Cancel / Apply row as `os` draws it: labels left to right, and the - /// row's right edge with the window's. - fn button_row(os: egui::os::OperatingSystem) -> (Vec, f32, f32) { - use super::{ButtonRole, DialogButton}; - use egui_kittest::{Harness, kittest::Queryable}; - // Drawn from the second frame, once the theme's fonts are bound. - let mut h = Harness::builder().with_size(egui::vec2(500.0, 80.0)).build_ui_state( - |ui, ready: &mut bool| { - if *ready { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| { - let row = [ - DialogButton::new(ButtonRole::Default, "OK", 84.0), - DialogButton::new(ButtonRole::Cancel, "Cancel", 84.0), - DialogButton::new(ButtonRole::Apply, "Apply", 84.0), - ]; - super::dialog_buttons(ui, &row); - }); - } - }, - false, - ); - crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.ctx.set_os(os); - *h.state_mut() = true; - h.run(); - let mut drawn: Vec<(f32, f32, String)> = - ["OK", "Cancel", "Apply"].iter().map(|l| (h.get_by_label(l).rect().left(), h.get_by_label(l).rect().right(), l.to_string())).collect(); - drawn.sort_by(|a, b| a.0.total_cmp(&b.0)); - let right = drawn.last().map_or(0.0, |d| d.1); - (drawn.into_iter().map(|d| d.2).collect(), right, h.ctx.content_rect().right()) - } - - #[test] - fn dialog_buttons_follow_the_platform_order() { - use egui::os::OperatingSystem as Os; - for (os, want) in [(Os::Windows, ["OK", "Cancel", "Apply"]), (Os::Nix, ["OK", "Cancel", "Apply"]), (Os::Mac, ["Cancel", "Apply", "OK"])] { - let (order, right, edge) = button_row(os); - assert_eq!(order, want, "{os:?}"); - assert!(edge - right < 20.0, "{os:?}: the row hugs the right edge ({right} of {edge})"); - } - } - - #[test] - fn two_decimal_numbers_trim_zeros() { - assert_eq!(super::fmt_num2(1.05), "1.05"); - assert_eq!(super::fmt_num2(0.78), "0.78"); - assert_eq!(super::fmt_num2(0.5), "0.5"); - assert_eq!(super::fmt_num2(2.0), "2"); - } - - #[test] - fn typed_arithmetic_evaluates() { - use super::parse_num; - for (text, want) in [ - ("1280*2", 2560.0), - ("658 * 1.5", 987.0), - ("48/3", 16.0), - ("20*2+5-2", 43.0), - ("2+3*4", 14.0), - ("10/4*2", 5.0), - ("-5+3", -2.0), - ("5--3", 8.0), - ("2*-3+1", -5.0), - ("−4", -4.0), - ("1 234", 1234.0), - ("1e3/2", 500.0), - ("(2+3)*4", 20.0), - ("2^3", 8.0), - ("10%3", 1.0), - ] { - assert_eq!(parse_num(text), Some(want), "{text}"); - } - for text in ["", "abc", "5+", "*2", "4/0", "0/0", "1+*2", "(2+3", "1e400"] { - assert_eq!(parse_num(text), None, "{text}"); - } - } - - /// Types `text` into a value field holding `start`, then presses `key`. Returns the value an OK - /// button that also fires on Enter saw, as dialogs read it, else the field's value. `round` - /// makes the caller round the value every frame, as pixel fields do. - fn type_and_press(start: f32, text: &str, key: egui::Key, round: bool) -> f32 { - use egui_kittest::{Harness, kittest::Queryable}; - let mut h = Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state( - move |ui, (v, ok): &mut (f32, Option)| { - super::value_field(ui, v, 0.0..=300000.0, "px", 90.0).accessible_name("Size"); - if round { - *v = v.round(); - } - if ui.button(tl!("OK")).clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) { - *ok = Some(*v); - } - }, - (start, None), - ); - h.get_by_role(egui::accesskit::Role::SpinButton).click(); - h.run(); - for c in text.chars() { - h.event(egui::Event::Text(c.to_string())); - h.run(); - } - h.key_press(key); - h.run(); - let (v, ok) = *h.state(); - ok.unwrap_or(v) - } - - /// Plain digits apply as they're typed; arithmetic doesn't report a change until it's committed. - #[test] - fn value_field_holds_arithmetic_until_committed() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut h = Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state( - |ui, (v, changes): &mut (f32, u32)| { - if super::value_field(ui, v, 0.0..=100.0, "%", 90.0).accessible_name("Opacity").changed() { - *changes += 1; - } - }, - (100.0, 0), - ); - h.get_by_role(egui::accesskit::Role::SpinButton).click(); - h.run(); - for (c, want) in [('5', (5.0, 1)), ('0', (50.0, 2)), ('/', (50.0, 2)), ('2', (50.0, 2))] { - h.event(egui::Event::Text(c.to_string())); - h.run(); - assert_eq!(*h.state(), want, "after {c}"); - } - h.key_press(egui::Key::Enter); - h.run(); - assert_eq!(*h.state(), (25.0, 3)); - } - - /// #5717: a value past the range shows as it is without reporting a change; an edit is clamped. - #[test] - fn value_field_keeps_a_shown_value_past_its_range_and_clamps_edits() { - use egui_kittest::{Harness, kittest::Queryable}; - let mut h = Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state( - |ui, (v, changes): &mut (f32, u32)| { - if super::value_field(ui, v, 0.1..=1296.0, "pt", 90.0).accessible_name("Font size").changed() { - *changes += 1; - } - }, - (2400.0, 0), - ); - h.run_steps(3); - assert_eq!(*h.state(), (2400.0, 0), "showing it changes nothing"); - h.get_by_role(egui::accesskit::Role::SpinButton).click(); - h.run(); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - h.event(egui::Event::Text("5000".into())); - h.key_press(egui::Key::Enter); - h.run(); - assert_eq!(h.state().0, 1296.0, "a typed value is clamped"); - } - - #[test] - fn value_field_applies_typed_arithmetic() { - use egui::Key::{Enter, Tab}; - assert_eq!(type_and_press(500.0, "1280*2", Tab, false), 2560.0); - assert_eq!(type_and_press(500.0, "1280*2", Enter, false), 2560.0); - // `5/2` alone would round to 3 under the caller; the whole expression still applies. - assert_eq!(type_and_press(1.0, "5/2*2", Tab, true), 5.0); - assert_eq!(type_and_press(1.0, "1280/3*2", Enter, true), 853.0); - } - - #[test] - fn numbers_drop_trailing_zero() { - // #2434: the unit keys map to Photoshop's places, and the shared formatter trims zeros. - assert_eq!(super::unit_decimals("px"), 0); - assert_eq!(super::unit_decimals("pt"), 1); - assert_eq!(super::unit_decimals("mm"), 2); - assert_eq!(super::unit_decimals("cm"), 2); - assert_eq!(super::unit_decimals("pica"), 2); - assert_eq!(super::unit_decimals("in"), 3); - assert_eq!(super::unit_decimals("nonsense"), 0); - assert_eq!(super::fmt_num_prec(0.7995, 3), "0.8"); - assert_eq!(super::fmt_num_prec(2.5, 0), "3"); - assert_eq!(super::fmt_num(100.0), "100"); - assert_eq!(super::fmt_num(12.46), "12.5"); - assert_eq!(super::fmt_num(-3.0), "-3"); - } - - #[test] - fn dropdown_opens_with_focus_and_arrow_keys_change_the_value() { - use egui::accesskit::Role; - use egui_kittest::{Harness, kittest::Queryable}; - - let mut h = Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state( - |ui, selected: &mut usize| { - let options = [(0, "Normal"), (1, "Multiply"), (2, "Screen")]; - super::dropdown(ui, "blend-mode", tl!("Blend Mode"), selected, &options, 120.0); - }, - 0, - ); - h.get_by_role(Role::ComboBox).click(); - h.run(); - h.key_press(egui::Key::ArrowDown); - h.run(); - assert_eq!(*h.state(), 1); - h.key_press(egui::Key::ArrowUp); - h.run(); - assert_eq!(*h.state(), 0); - } - - /// Scrolling rows under the pointer doesn't widen the list: it is as wide as the widest - /// option hovered from the start (#2607). - #[test] - fn dropdown_list_keeps_its_width_while_scrolling() { - use photocraft_color::BlendMode; - let mut h = Harness::builder().with_size(egui::vec2(400.0, 700.0)).build_ui_state( - |ui, mode: &mut BlendMode| { - let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); - super::dropdown(ui, "brush-mode", tl!("Mode"), mode, &opts, 96.0); - }, - BlendMode::Normal, - ); - // The app's theme strokes plain rows, which is what made hovered rows wider. - crate::theme::apply(&h.ctx, crate::theme::ThemeKind::ProMedium); - h.run(); - h.get_by_role(egui::accesskit::Role::ComboBox).click(); - h.run(); - let list = |h: &Harness<'_, BlendMode>| h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))); - let Some(open) = list(&h) else { panic!("the list is open") }; - for _ in 0..30 { - h.hover_at(open.center()); - 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(); - assert_eq!(list(&h).map(|r| r.width()), Some(open.width())); - } - } - - 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. - fn mode_dropdown(wheel: bool) -> Harness<'static, usize> { - Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state( - move |ui, selected: &mut usize| { - if wheel { - super::dropdown_wheel_hovered(ui, "blend-mode", tl!("Blend Mode"), selected, &MODES, 120.0); - } else { - super::dropdown(ui, "blend-mode", tl!("Blend Mode"), selected, &MODES, 120.0); - } - }, - 0, - ) - } - - /// One wheel event over the dropdown: negative `delta.y` is down. - fn wheel(h: &mut Harness<'_, T>, unit: egui::MouseWheelUnit, delta: egui::Vec2, modifiers: Modifiers) { - let at = h.get_by_role(egui::accesskit::Role::ComboBox).rect().center(); - h.event(egui::Event::ModifiersChanged(modifiers)); - h.hover_at(at); - h.run(); - h.event(egui::Event::MouseWheel { source: egui::MouseWheelSource::Unknown, unit, delta, phase: egui::TouchPhase::Move, modifiers }); - h.run(); - h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); - h.run(); - } - - #[test] - fn shift_wheel_steps_one_mode_per_notch() { - let mut h = mode_dropdown(true); - wheel(&mut h, egui::MouseWheelUnit::Line, egui::vec2(0.0, -1.0), Modifiers::SHIFT); - assert_eq!(*h.state(), 1, "not ten like a slider"); - // Some systems turn Shift+wheel into a horizontal scroll. - wheel(&mut h, egui::MouseWheelUnit::Line, egui::vec2(-1.0, 0.0), Modifiers::SHIFT); - assert_eq!(*h.state(), 2); - } - - #[test] - fn fractional_wheel_deltas_add_up_to_whole_mode_steps() { - let mut h = mode_dropdown(true); - wheel(&mut h, egui::MouseWheelUnit::Line, egui::vec2(0.0, -0.5), Modifiers::NONE); - assert_eq!(*h.state(), 0, "half a notch"); - wheel(&mut h, egui::MouseWheelUnit::Line, egui::vec2(0.0, -0.5), Modifiers::NONE); - assert_eq!(*h.state(), 1); - let per_line = h.ctx.options(|o| o.input_options.line_scroll_speed); - wheel(&mut h, egui::MouseWheelUnit::Point, egui::vec2(0.0, -per_line), Modifiers::NONE); - assert_eq!(*h.state(), 2, "a line's worth of points is a notch"); - } - - #[test] - fn the_wheel_over_a_wheel_dropdown_does_not_scroll_its_container() { - let mut h = Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state( - |ui, selected: &mut usize| { - egui::ScrollArea::vertical().max_height(80.0).show(ui, |ui| { - super::dropdown_wheel_hovered(ui, "blend-mode", tl!("Blend Mode"), selected, &MODES, 120.0); - ui.add_space(400.0); - }); - }, - 0, - ); - let top = h.get_by_role(egui::accesskit::Role::ComboBox).rect().top(); - wheel(&mut h, egui::MouseWheelUnit::Line, egui::vec2(0.0, -1.0), Modifiers::NONE); - for _ in 0..10 { - h.run(); - } - assert_eq!(*h.state(), 1); - assert_eq!(h.get_by_role(egui::accesskit::Role::ComboBox).rect().top(), top, "the container didn't scroll"); - } - - #[test] - fn the_wheel_leaves_a_plain_dropdown_alone() { - let mut h = mode_dropdown(false); - wheel(&mut h, egui::MouseWheelUnit::Line, egui::vec2(0.0, -1.0), Modifiers::NONE); - assert_eq!(*h.state(), 0); - } -} +mod tests; /// A compact colour popup with the shared desktop eyedropper. Keep egui's colour cache so hue /// survives black/white and alpha edits, and keep linear and encoded call sites distinct. diff --git a/crates/ui-egui/src/widgets/tests.rs b/crates/ui-egui/src/widgets/tests.rs new file mode 100644 index 0000000000..dd5a5da53f --- /dev/null +++ b/crates/ui-egui/src/widgets/tests.rs @@ -0,0 +1,1018 @@ +use super::{hue_color, hue_stops}; +use egui::{Color32, Key, Modifiers}; + +#[test] +fn hue_stops_are_pure_and_evenly_spaced() { + let c = |r, g, b| Color32::from_rgb(r, g, b); + let want = [c(255, 0, 0), c(255, 255, 0), c(0, 255, 0), c(0, 255, 255), c(0, 0, 255), c(255, 0, 255), c(255, 0, 0)]; + let stops = hue_stops(); + assert_eq!(stops.len(), 13); + for (k, w) in want.iter().enumerate() { + assert_eq!(stops[k * 2], *w, "stop at {} degrees", k * 60); + assert_eq!(hue_color(k as f32 * 60.0), *w); + } +} + +/// A light theme rings the slider knob with its outline token; a dark Studio-layout one draws +/// the plain knob (#7927). +#[test] +fn light_themes_draw_the_slider_knob_outline() { + use crate::theme::{ThemeKind, Tokens}; + fn rings(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Vec(v) => v.iter().for_each(|s| rings(s, out)), + egui::Shape::Circle(c) if c.radius == 7.0 && c.stroke.width == 1.0 => out.push(c.stroke.color), + _ => {} + } + } + for kind in [ThemeKind::StudioLight, ThemeKind::Adwaita, ThemeKind::BreezeLight, ThemeKind::SoftLight, ThemeKind::Studio] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, kind); + let mut v = 50.0; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + super::slider(ui, &mut v, 0.0..=100.0, None); + }); + out.textures_delta.clear(); + let mut found = Vec::new(); + out.shapes.iter().for_each(|c| rings(&c.shape, &mut found)); + let want: Vec<_> = Tokens::for_kind(kind).knob_outline().into_iter().collect(); + assert_eq!(found, want, "{kind:?}"); + } +} + +#[test] +fn checkbox_label_is_a_button_target_not_selectable_text() { + use egui::CursorIcon; + use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, + }; + + let mut h = Harness::builder().with_size(egui::vec2(300.0, 80.0)).build_ui_state( + |ui, on: &mut bool| { + super::checkbox(ui, on, "Show Transform Controls"); + }, + false, + ); + h.run_steps(2); + let label = h.get_by_label("Show Transform Controls").rect(); + h.hover_at(label.center()); + h.run_steps(2); + assert_eq!(h.output().platform_output.cursor_icon, CursorIcon::PointingHand); + h.get_by_label("Show Transform Controls").click(); + h.run_steps(2); + assert!(*h.state()); + let checkbox = h.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Show Transform Controls"); + assert_eq!(checkbox.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True)); + checkbox.focus(); + h.run_steps(1); + h.key_press(egui::Key::Space); + h.run_steps(2); + assert!(!*h.state(), "the same named checkbox supports Space"); +} + +/// #3208: a rounded swatch's checker is one shared, repeating, unblurred two-by-two tile on +/// the rounded rect, scaled so a cell stays `cell` points, so nothing shows past the corners. +#[test] +fn rounded_swatches_clip_their_checker_to_the_corners() { + use egui::{Pos2, Rect, pos2, vec2}; + let mut h = egui_kittest::Harness::builder().with_size(vec2(200.0, 100.0)).build_ui(|ui| { + super::color_swatch(ui, egui::Color32::RED); + super::color_swatch_button(ui, egui::Color32::from_rgba_unmultiplied(0, 0, 255, 128), "Blue"); + }); + crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(2); + let tile = h.ctx.data(|d| d.get_temp::(super::checker_tile_id())).expect("the tile is loaded once"); + let manager = h.ctx.tex_manager(); + let manager = manager.read(); + let meta = manager.meta(tile.id()).expect("the tile is in the texture manager"); + assert_eq!(meta.size, [2, 2]); + assert_eq!(meta.options.wrap_mode, egui::TextureWrapMode::Repeat); + assert_eq!(meta.options.magnification, egui::TextureFilter::Nearest); + assert_eq!(super::checker_uv(Rect::from_min_size(Pos2::ZERO, vec2(40.0, 18.0)), 4.0), Rect::from_min_max(Pos2::ZERO, pos2(5.0, 2.25))); + assert_eq!( + super::checker_uv(Rect::from_min_size(Pos2::ZERO, vec2(8.0, 8.0)), 0.0), + Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), + "a bad cell falls back to 4 pt" + ); +} + +/// #3580: the shared eliding label never lays out wider than the room it is given, so a longer +/// translation shrinks with '…' instead of overrunning its row; a short label is untouched. +#[test] +fn elided_label_never_exceeds_its_room() { + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(240.0, 60.0)).build_ui(|ui| { + let long = super::elided_label(ui, "Preenchimento:", 24.0); // pt-br Fill:, the longest catalog + assert!(long.rect.width() <= 25.0, "elided to the room, got {}", long.rect.width()); + let short = super::elided_label(ui, "Fill", 200.0); + assert!(short.rect.width() < 60.0, "a short label is not padded: {}", short.rect.width()); + }); + crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(2); +} + +#[test] +fn spectrum_popup_style_matches_main_menu_and_preserves_studio() { + for kind in [crate::theme::ThemeKind::Pro, crate::theme::ThemeKind::ProMedium, crate::theme::ThemeKind::Studio, crate::theme::ThemeKind::StudioLight] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, kind); + let tokens = crate::theme::Tokens::for_kind(kind); + let mut out = ctx.run_ui(Default::default(), |ui| { + let original_padding = ui.spacing().button_padding; + let original_hover = ui.visuals().widgets.hovered.fg_stroke; + super::style_spectrum_popup_menu(ui); + assert_eq!(ui.spacing().item_spacing.y, 0.0, "{kind:?}: menu rows meet so the gap is selectable"); + if tokens.pro { + assert_eq!(ui.spacing().button_padding, egui::vec2(10.0, 4.0)); + assert_eq!(ui.visuals().widgets.hovered.bg_fill, tokens.accent); + assert_eq!(ui.visuals().widgets.hovered.fg_stroke.color, egui::Color32::WHITE); + } else { + assert_eq!(ui.spacing().button_padding, original_padding); + assert_eq!(ui.visuals().widgets.hovered.fg_stroke, original_hover); + } + }); + out.textures_delta.clear(); + } +} + +/// One primary press+release at `pos`. When `touch`, emit Touch Start/End with the pointer events (as egui-winit does) so [`super::second_click`] uses the touch distance. +fn pointer_click(ctx: &egui::Context, time: f64, pos: egui::Pos2, touch: bool) -> bool { + let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(200.0, 200.0)); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let touch_ev = |phase| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(1), phase, pos, force: None }; + let mut saw = false; + for (t, mut events) in [ + (time, { + let mut v = vec![egui::Event::PointerMoved(pos), button(true)]; + if touch { + v.insert(0, touch_ev(egui::TouchPhase::Start)); + } + v + }), + (time + 0.02, { + let mut v = vec![button(false)]; + if touch { + v.insert(0, touch_ev(egui::TouchPhase::End)); + } + v + }), + ] { + let mut raw = egui::RawInput { time: Some(t), screen_rect: Some(area), ..Default::default() }; + raw.events.append(&mut events); + let mut out = ctx.run_ui(raw, |ui| { + let r = ui.allocate_rect(area, egui::Sense::click()); + saw |= super::second_click(ui, &r); + }); + out.textures_delta.clear(); + } + saw +} + +/// #2274 touch: taps past egui's 6 px mouse limit (and past the old 32 px touch slop) within 0.5 s still count as a double; the same mouse path does not. +#[test] +fn second_click_tolerates_touch_jitter_but_keeps_mouse_tight() { + let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(200.0, 200.0)); + let a = egui::pos2(50.0, 50.0); + let mild = egui::pos2(70.0, 50.0); // 20 px — past mouse max_click_dist (6) + let wide = egui::pos2(50.0 + 48.0, 50.0); // past the old 32 px slop, inside TOUCH_MAX_CLICK_DIST (64) + for touch in [false, true] { + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput { time: Some(0.0), screen_rect: Some(area), ..Default::default() }, |ui| { + ui.allocate_rect(area, egui::Sense::click()); + }); + out.textures_delta.clear(); + assert!(!pointer_click(&ctx, 0.1, a, touch), "first click only arms the pair"); + let second = pointer_click(&ctx, 0.25, mild, touch); + assert_eq!(second, touch, "touch={touch}: 20 px jitter is a double only for touch"); + } + // Touch-only: casual Framework-style drift beyond the previous 32 px budget. + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput { time: Some(0.0), screen_rect: Some(area), ..Default::default() }, |ui| { + ui.allocate_rect(area, egui::Sense::click()); + }); + out.textures_delta.clear(); + assert!(!pointer_click(&ctx, 0.1, a, true)); + assert!(pointer_click(&ctx, 0.25, wide, true), "48 px touch jitter is still a double"); +} + +/// A mouse double past the time window is not a double, even at the same pixel. +#[test] +fn second_click_respects_the_half_second_window() { + let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(200.0, 200.0)); + let p = egui::pos2(40.0, 40.0); + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput { time: Some(0.0), screen_rect: Some(area), ..Default::default() }, |ui| { + ui.allocate_rect(area, egui::Sense::click()); + }); + out.textures_delta.clear(); + assert!(!pointer_click(&ctx, 0.1, p, false)); + assert!(!pointer_click(&ctx, 0.1 + super::DOUBLE_CLICK_S + 0.05, p, false), "past Windows' 0.5 s window"); +} + +use egui_kittest::{Harness, kittest::Queryable}; + +/// A panel footer's buttons are drawn whole. The bar runs on over the body's bottom margin, so a +/// body that clips where its content ends (as the panels do) cut the bottom off every button: +/// the hover highlight of a 26 px button was about 21 px tall in the Paths, Layers and Channels +/// panels (#6238). +#[test] +fn panel_footer_buttons_are_not_clipped_by_the_body() { + let mut h = Harness::new_ui_state( + |ui, s: &mut Option<(egui::Rect, egui::Rect, egui::Rect)>| { + // A body exactly as tall as the footer takes, clipped there. + let body = egui::Rect::from_min_size(ui.max_rect().min, egui::vec2(220.0, super::footer_height(ui))); + let mut body_ui = ui.new_child(egui::UiBuilder::new().max_rect(body)); + body_ui.set_clip_rect(body); + super::panel_footer(&mut body_ui, |bar| { + let b = crate::icons::button(bar, "square", 26.0, false, "Button"); + *s = Some((b.rect, bar.clip_rect(), body)); + }); + }, + None, + ); + crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run(); + let (button, clip, body) = h.state().expect("the footer drew its button"); + assert!(button.bottom() > body.bottom(), "the bar really overruns the body, or this test proves nothing: {button:?} vs {body:?}"); + assert!(clip.contains_rect(button), "the whole button is inside the clip: {button:?} not in {clip:?}"); +} + +/// #3789: a plain text field is one boxed, outline-free input whose text-selection colour stays +/// local, so it isn't recoloured for the rest of the frame (selected rows, slider trails). +#[test] +fn text_field_is_a_boxed_input_whose_selection_colour_stays_local() { + use egui::accesskit::Role; + let mut h = Harness::new_ui_state( + |ui, s: &mut (String, egui::Color32, egui::Color32)| { + s.1 = ui.visuals().selection.bg_fill; + super::text_field(ui, egui::Id::unique("tf"), &mut s.0, "hint", 140.0, false); + s.2 = ui.visuals().selection.bg_fill; + }, + (String::new(), egui::Color32::WHITE, egui::Color32::BLACK), + ); + crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run(); + assert_eq!(h.state().1, h.state().2, "the field's selection colour does not leak into its parent"); + h.get_by_role(Role::TextInput).click(); + h.run_steps(1); + for ch in "abc".chars() { + h.event(egui::Event::Text(ch.to_string())); + h.run_steps(1); + } + assert_eq!(h.state().0, "abc", "typing reaches the bound string"); +} + +/// #2150: a huge paste into a plain text field stops at its limit instead of growing the +/// string (and its laid-out text) without bound. +#[test] +fn text_field_caps_a_huge_paste() { + use egui::accesskit::Role; + let mut h = Harness::new_ui_state(|ui, s: &mut String| drop(super::text_field(ui, egui::Id::unique("tf"), s, "Value", 140.0, false)), String::new()); + crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run(); + h.get_by_role(Role::TextInput).click(); + h.run_steps(1); + h.event(egui::Event::Paste("9".repeat(200_000))); + h.run_steps(1); + assert_eq!(h.state().chars().count(), super::TEXT_FIELD_LIMIT); + // A second paste adds nothing past the limit. + h.event(egui::Event::Paste("9".repeat(10))); + h.run_steps(1); + assert_eq!(h.state().chars().count(), super::TEXT_FIELD_LIMIT); +} + +/// #2150: a value already past the limit is laid out only up to it, and stays the caller's +/// until the field is edited, which keeps the bounded copy. +#[test] +fn text_field_bounds_an_oversized_existing_value() { + use egui::accesskit::Role; + let long = "9".repeat(super::TEXT_FIELD_LIMIT * 4); + let mut h = Harness::new_ui_state(|ui, s: &mut String| drop(super::text_field(ui, egui::Id::unique("tf"), s, "Value", 140.0, false)), long.clone()); + crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run(); + assert_eq!(*h.state(), long, "drawing alone leaves the caller's value alone"); + assert_eq!(h.get_by_role(Role::TextInput).value().map(|v| v.chars().count()), Some(super::TEXT_FIELD_LIMIT)); + h.get_by_role(Role::TextInput).click(); + h.run_steps(1); + h.event(egui::Event::Key { key: egui::Key::Backspace, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + assert!(h.state().chars().count() < super::TEXT_FIELD_LIMIT, "an edit keeps the bounded copy"); +} + +/// #2150: text queued by the control channel (`ui.type`) joins the input in `raw_input_hook` +/// and is cut like the OS's, so the cap must run after it is appended. +#[test] +fn raw_input_hook_caps_synthetic_text() { + use eframe::App as _; + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.synthetic.push(egui::Event::Text("x".repeat(super::INPUT_EVENT_LIMIT + 10))); + let ctx = egui::Context::default(); + let mut raw = egui::RawInput::default(); + app.raw_input_hook(&ctx, &mut raw); + let texts: Vec = raw.events.iter().filter_map(|e| if let egui::Event::Text(t) = e { Some(t.chars().count()) } else { None }).collect(); + assert_eq!(texts, [super::INPUT_EVENT_LIMIT]); +} + +/// #2150: every text-carrying event is cut to the app-wide limit at a character boundary +/// before any widget sees it; other events and short text pass untouched. +#[test] +fn oversized_text_events_are_cut_before_widgets_see_them() { + let long = "é".repeat(super::INPUT_EVENT_LIMIT + 5); + let mut events = vec![ + egui::Event::Paste(long.clone()), + egui::Event::Text(long.clone()), + egui::Event::Ime(egui::ImeEvent::Commit(long.clone())), + egui::Event::Ime(egui::ImeEvent::Preedit { text: long, active_range_chars: Some(0..super::INPUT_EVENT_LIMIT + 2) }), + egui::Event::Text("ok".into()), + egui::Event::Copy, + ]; + super::cap_text_events(&mut events); + for e in &events[..4] { + let (egui::Event::Paste(t) + | egui::Event::Text(t) + | egui::Event::Ime(egui::ImeEvent::Commit(t)) + | egui::Event::Ime(egui::ImeEvent::Preedit { text: t, .. })) = e + else { + panic!("{e:?}") + }; + assert_eq!(t.chars().count(), super::INPUT_EVENT_LIMIT); + } + assert!(matches!(&events[3], egui::Event::Ime(egui::ImeEvent::Preedit { active_range_chars: None, .. })), "the range past the cut is dropped"); + assert_eq!(events[4], egui::Event::Text("ok".into())); + assert_eq!(events[5], egui::Event::Copy); +} + +/// A row's visible caption names both its number and its slider; a dropdown is named by its +/// own caption, or by the scrubby caption drawn just before it. +#[test] +fn labelled_rows_and_dropdowns_have_semantic_accessible_names() { + use egui_kittest::{Harness, kittest::Queryable}; + + #[derive(Default)] + struct State { + value: f32, + fill: f32, + blend: usize, + mode: usize, + } + + let mut h = Harness::builder().with_size(egui::vec2(360.0, 240.0)).build_ui_state( + |ui, s: &mut State| { + super::slider_row(ui, "Opacity", &mut s.value, 0.0..=100.0, "%", None); + super::popup_value_field(ui, "Fill", &mut s.fill, 0.0..=100.0, "%", 74.0); + let opts = [(0usize, "Normal"), (1, "Multiply")]; + super::dropdown(ui, "blend", "Blend Mode", &mut s.blend, &opts, 120.0); + ui.horizontal(|ui| { + let caption = ui.label("Mode"); + super::scrub_option_label(ui, &caption); + super::dropdown(ui, "mode", "Not this name", &mut s.mode, &opts, 120.0); + }); + }, + State::default(), + ); + crate::PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run(); + + // The row's caption is the accessible name of the value field and of the slider. + h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Opacity"); + h.get_by_role_and_label(egui::accesskit::Role::Slider, "Opacity"); + // A popup value field names both its number and the arrow that opens its slider. + h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Fill"); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Fill"); + // A dropdown requires a real name; a preceding scrubby caption is used when present. + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Blend Mode"); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Mode"); +} + +/// Sets up a test with one value field. Its state is its value and how many times it changed. +fn field(value: f32, range: std::ops::RangeInclusive) -> Harness<'static, (f32, u32)> { + let mut h = Harness::new_ui_state( + move |ui, s: &mut (f32, u32)| { + if super::value_field(ui, &mut s.0, range.clone(), "px", 80.0).accessible_name("Test number").changed() { + s.1 += 1; + } + }, + (value, 0), + ); + h.run(); + h +} + +fn press(h: &mut Harness<'static, (f32, u32)>, mods: Modifiers, key: Key) -> f32 { + h.key_press_modifiers(mods, key); + h.run(); + h.state().0 +} + +fn focused(value: f32, range: std::ops::RangeInclusive) -> Harness<'static, (f32, u32)> { + let mut h = field(value, range); + h.get_by_role(egui::accesskit::Role::SpinButton).click(); + h.run(); + h +} + +/// The number's slot (and its focus outline) is centred in the box (#5150). +#[test] +fn value_field_number_slot_is_centred_in_its_box() { + let mut h = Harness::new_ui_state( + |ui, s: &mut (f32, egui::Rect)| { + let field = super::value_field_in(ui, &mut s.0, 0.0..=100.0, "px", 80.0, 0.0, super::FieldOpts::default(), None); + s.1 = field.1; + field.0.accessible_name("Value"); + }, + (50.0, egui::Rect::NOTHING), + ); + h.run(); + let number = h.get_by_role(egui::accesskit::Role::SpinButton).rect(); + let field = h.state().1; + assert!((field.center().y - number.center().y).abs() < 0.01, "field {field:?}, number {number:?}"); +} + +/// The digits' ink, not just their slot, is centred in the box, and starts level with the +/// `%`'s, so the number lines up with the box and its unit (#5150). +#[test] +fn value_field_digits_ink_is_centred_and_level_with_the_unit() { + let _gpu = photocraft_testkit::gpu_lock(); + let scale = 4.0; + for kind in [crate::theme::ThemeKind::Pro, crate::theme::ThemeKind::Studio] { + let mut h = Harness::builder().with_size(egui::vec2(100.0, 40.0)).with_pixels_per_point(scale).wgpu().build_ui_state( + |ui, s: &mut (f32, egui::Rect)| { + let field = super::value_field_in(ui, &mut s.0, 0.0..=100.0, "%", 80.0, 0.0, super::FieldOpts::default(), None); + s.1 = field.1; + field.0.accessible_name("Value"); + }, + (100.0, egui::Rect::NOTHING), + ); + crate::PhotocraftApp::setup_context(&h.ctx, kind); + h.run_steps(3); + let image = h.render().expect("render value field"); + let (field, suffix_left) = (h.state().1, h.state().1.right() - 14.0); + let px = |v: f32| (v * scale) as u32; + let bg = image.get_pixel(px(field.left() + 2.0), px(field.center().y)).0; + let lum = |p: [u8; 4]| u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2]); + // Top and bottom of the ink (pt) between x0 and x1. + let ink = |x0: f32, x1: f32| { + let rows: Vec = (px(field.top() + 2.0)..px(field.bottom() - 2.0)) + .filter(|&y| (px(x0)..px(x1)).any(|x| lum(image.get_pixel(x, y).0) > lum(bg) + 150)) + .collect(); + let (top, bottom) = (rows.first().copied().unwrap_or(0), rows.last().copied().unwrap_or(0) + 1); + (top as f32 / scale, bottom as f32 / scale) + }; + let digits = ink(field.left() + 4.0, suffix_left - 2.0); + let unit = ink(suffix_left, field.right() - 2.0); + let what = format!("{kind:?}: field {field:?}, digits {digits:?}, unit {unit:?}"); + assert!(((digits.0 + digits.1) / 2.0 - field.center().y).abs() <= 0.25, "{what}"); + assert!((digits.0 - unit.0).abs() <= 0.25, "{what}"); + } +} + +/// With the app's theme (its 24 pt interact height and 4 pt button padding), in a full-size +/// box and a slim status-bar box alike, the number stays inside the box, centred in it, +/// and a long number doesn't spill out of the box's left edge (#2823). +#[test] +fn themed_value_field_number_sits_inside_its_box_in_every_size() { + for kind in crate::theme::ThemeKind::ALL { + for (w, h, v) in [(80.0, super::VALUE_FIELD_H, 50.0), (64.0, 18.0, 1600.5), (78.0, 22.0, 100.6)] { + let mut harness = Harness::new_ui_state( + move |ui, s: &mut (f32, egui::Rect)| { + let before = ui.cursor().min; + super::compact_value_field(ui, &mut s.0, 0.0..=3200.0, "%", w, h).accessible_name("Zoom"); + s.1 = egui::Rect::from_min_size(before, egui::vec2(w, h)); + }, + (v, egui::Rect::NOTHING), + ); + crate::PhotocraftApp::setup_context(&harness.ctx, kind); + harness.run(); + let number = harness.get_by_role(egui::accesskit::Role::SpinButton).rect(); + let field = harness.state().1; + let what = format!("{kind:?} {w}x{h}: field {field:?}, number {number:?}"); + assert!(field.contains_rect(number), "{what}"); + assert!((field.center().y - number.center().y).abs() < 0.51, "{what}"); + } + } +} + +/// The number's slot ends just left of its unit, by the unit's measured width: a one-character +/// `%` (the status bar zoom) leaves the number more room than the old fixed 16 pt, and a longer +/// unit never sits under the number (#3040). +#[test] +fn value_field_number_slot_stops_at_its_measured_suffix() { + for suffix in ["%", "px", "°", "×"] { + let mut h = Harness::new_ui_state( + move |ui, s: &mut (f32, egui::Rect, f32)| { + let before = ui.cursor().min; + super::compact_value_field(ui, &mut s.0, 0.0..=3200.0, suffix, 64.0, 18.0).accessible_name("Zoom"); + s.1 = egui::Rect::from_min_size(before, egui::vec2(64.0, 18.0)); + s.2 = ui.painter().layout_no_wrap(suffix.to_owned(), crate::theme::mono(11.0), egui::Color32::WHITE).size().x; + }, + (33.33, egui::Rect::NOTHING, 0.0), + ); + h.run(); + let number = h.get_by_role(egui::accesskit::Role::SpinButton).rect(); + let (_, field, suffix_w) = *h.state(); + let suffix_left = field.right() - 6.0 - suffix_w; + assert!(number.right() <= suffix_left, "{suffix}: number {number:?} runs under the suffix at {suffix_left}"); + assert!(suffix_left - number.right() <= 1.5, "{suffix}: {:.1} pt wasted before the suffix", suffix_left - number.right()); + } +} + +#[test] +fn arrow_keys_step_a_focused_field_by_one_and_shift_by_ten() { + let mut h = focused(100.0, 0.0..=1000.0); + assert_eq!(press(&mut h, Modifiers::NONE, Key::ArrowUp), 101.0); + assert_eq!(press(&mut h, Modifiers::SHIFT, Key::ArrowUp), 111.0); + assert_eq!(press(&mut h, Modifiers::NONE, Key::ArrowDown), 110.0); + assert_eq!(press(&mut h, Modifiers::SHIFT, Key::ArrowDown), 100.0); + assert_eq!(press(&mut h, Modifiers::COMMAND, Key::ArrowUp), 100.1); + assert_eq!(press(&mut h, Modifiers::COMMAND | Modifiers::SHIFT, Key::ArrowDown), 100.0); + assert_eq!(h.state().1, 6, "every step reports a change, so callers apply it"); +} + +#[test] +fn arrow_keys_on_a_field_with_a_reversed_range_do_not_panic() { + // The empty range is the case under test — arrow keys must not panic on it. + let mut h = focused(5.0, 10.0..=0.0); // NOSONAR + let _ = press(&mut h, Modifiers::NONE, Key::ArrowUp); + let mut h = focused(5.0, f32::NAN..=10.0); + let _ = press(&mut h, Modifiers::NONE, Key::ArrowDown); +} + +/// #5914: Exposure's ±20 stops keep 0.01 arrow steps when the field shows two decimals. +#[test] +fn arrow_keys_step_fractional_stops_when_decimals_are_set() { + let mut h = Harness::new_ui_state( + |ui, v: &mut f32| { + super::slider_row_prec(ui, "Exposure", v, -20.0..=20.0, "", None, super::RowGestures::default(), Some(2)); + }, + 0.0, + ); + h.run(); + h.get_by_role(egui::accesskit::Role::SpinButton).click(); + h.run(); + h.key_press_modifiers(Modifiers::NONE, Key::ArrowUp); + h.run(); + assert!((*h.state() - 0.01).abs() < 1e-6); + h.key_press_modifiers(Modifiers::NONE, Key::ArrowUp); + h.run(); + assert!((*h.state() - 0.02).abs() < 1e-6); + h.key_press_modifiers(Modifiers::SHIFT, Key::ArrowUp); + h.run(); + assert!((*h.state() - 0.12).abs() < 1e-6); +} + +#[test] +fn arrow_keys_round_decimals_step_fine_fields_and_clamp() { + for (start, mods, key, want) in [ + (55.4, Modifiers::NONE, Key::ArrowUp, 56.0), + (55.6, Modifiers::NONE, Key::ArrowUp, 57.0), + (55.4, Modifiers::NONE, Key::ArrowDown, 54.0), + (55.5, Modifiers::NONE, Key::ArrowUp, 57.0), + (55.5, Modifiers::NONE, Key::ArrowDown, 55.0), + (55.4, Modifiers::SHIFT, Key::ArrowUp, 65.0), + (55.47, Modifiers::COMMAND, Key::ArrowUp, 55.6), + ] { + assert_eq!(press(&mut focused(start, 0.0..=1000.0), mods, key), want, "{start} {mods:?} {key:?}"); + } + let mut h = focused(0.5, 0.0..=1.0); + assert_eq!(press(&mut h, Modifiers::NONE, Key::ArrowUp), 0.51); + assert_eq!(press(&mut h, Modifiers::SHIFT, Key::ArrowUp), 0.61); + assert_eq!(press(&mut h, Modifiers::COMMAND, Key::ArrowUp), 0.62); + let mut h = focused(995.0, 0.0..=1000.0); + assert_eq!(press(&mut h, Modifiers::SHIFT, Key::ArrowUp), 1000.0); +} + +/// #6545: a curved track (the mask Feather) has fine steps at the left and coarse ones toward +/// the right end, and the knob drawn for a value lands where that value is picked. +#[test] +fn curved_track_maps_ends_middle_and_round_trips() { + use super::{curve_fraction, curve_value}; + for (f, want) in [(0.0, 0.0), (0.1, 1.0), (0.2, 8.0), (0.5, 125.0), (1.0, 1000.0)] { + assert!((curve_value(f, 0.0, 1000.0, Some(3.0)) - want).abs() < 1e-3, "{f}: {}", curve_value(f, 0.0, 1000.0, Some(3.0))); + } + assert_eq!(curve_value(0.25, 0.0, 1000.0, None), 250.0, "no curve is the linear track"); + assert_eq!(curve_value(0.5, 10.0, 20.0, Some(3.0)), 11.25, "the curve starts at the range's low end"); + for i in 0..=100 { + let f = i as f32 / 100.0; + let back = curve_fraction(curve_value(f, 0.0, 1000.0, Some(3.0)), 0.0, 1000.0, Some(3.0)); + assert!((back - f).abs() < 1e-4, "{f} -> {back}"); + let v = i as f32 * 10.0; + let again = curve_value(curve_fraction(v, 0.0, 1000.0, Some(3.0)), 0.0, 1000.0, Some(3.0)); + assert!((again - v).abs() < 1e-3, "{v} -> {again}"); + } + assert_eq!(curve_fraction(-5.0, 0.0, 1000.0, Some(3.0)), 0.0); + assert_eq!(curve_fraction(f32::NAN, 0.0, 1000.0, Some(3.0)), 0.0); +} + +#[test] +fn arrow_keys_work_out_a_typed_sum_then_step_it() { + let mut h = focused(100.0, 0.0..=1000.0); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.event(egui::Event::Text("5+5".into())); + h.run(); + assert_eq!(press(&mut h, Modifiers::NONE, Key::ArrowUp), 11.0); + assert_eq!(press(&mut h, Modifiers::NONE, Key::ArrowDown), 10.0, "the field keeps focus"); +} + +/// #5474: a held arrow repeats on consecutive frames; every repeat steps the focused field +/// and none of them moves focus to the field above. +#[test] +fn held_arrow_keeps_stepping_the_focused_field() { + let mut h = Harness::new_ui_state( + |ui, s: &mut (f32, f32)| { + super::value_field(ui, &mut s.0, 0.0..=1000.0, "", 80.0).accessible_name("Left"); + super::value_field(ui, &mut s.1, 0.0..=1000.0, "", 80.0).accessible_name("Right"); + }, + (10.0, 59.0), + ); + h.run(); + h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(1).expect("second field").click(); + h.run(); + // Held down: key-down repeats on consecutive frames, no key-up in between. + for repeat in [false, true, true, true, true, true] { + h.event(egui::Event::Key { key: Key::ArrowUp, physical_key: None, pressed: true, repeat, modifiers: Modifiers::NONE }); + h.step(); + } + h.event(egui::Event::Key { key: Key::ArrowUp, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }); + h.run(); + assert_eq!(*h.state(), (10.0, 65.0)); +} + +#[test] +fn arrow_keys_leave_an_unfocused_field_alone() { + let mut h = field(100.0, 0.0..=1000.0); + assert_eq!(press(&mut h, Modifiers::NONE, Key::ArrowUp), 100.0); + assert_eq!(h.state().1, 0); +} + +/// Photoshop: a unit typed into a px field converts at the document resolution on Enter, and +/// an expression that can't convert (or divides by zero) keeps the value. +#[test] +fn enter_commits_a_typed_unit_expression_at_the_document_resolution() { + let mut h = field(100.0, 0.0..=10_000.0); + super::set_field_resolution(&h.ctx, 300.0, 72.0); + for (text, want) in [("1in+10", 310.0), ("2.54 cm * 2", 600.0), ("50%", 600.0), ("1in/0", 600.0), ("10px", 10.0)] { + h.get_by_role(egui::accesskit::Role::SpinButton).click(); + h.run(); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.event(egui::Event::Text(text.into())); + h.run(); + h.key_press(Key::Enter); + h.run(); + assert_eq!(h.state().0, want, "{text}"); + } +} + +/// Photoshop's scrubby labels: dragging the label right before a field moves its value, a +/// step a point (Shift ×10); a label with no field right after it moves nothing. +#[test] +fn dragging_a_label_scrubs_the_field_right_after_it() { + let mut h = Harness::new_ui_state( + |ui, s: &mut (f32, f32)| { + ui.horizontal(|ui| { + let l = ui.label("Size:"); + super::scrub_label(ui, &l); + super::value_field(ui, &mut s.0, 0.0..=1000.0, "px", 80.0).accessible_name("Start"); + }); + ui.horizontal(|ui| { + let l = ui.label("Mode:"); + super::scrub_label(ui, &l); + ui.add_space(60.0); + super::value_field(ui, &mut s.1, 0.0..=1000.0, "px", 80.0).accessible_name("End"); + }); + }, + (100.0, 100.0), + ); + h.run(); + let drag = |h: &mut Harness<'static, (f32, f32)>, label: &str, dx: f32, mods: Modifiers| { + let at = h.get_by_label(label).rect().center(); + h.hover_at(at); + h.run(); + h.drag_at(at); + h.run(); + for i in 1..=4 { + h.event(egui::Event::PointerMoved(at + egui::vec2(dx * i as f32 / 4.0, 0.0))); + h.event(egui::Event::ModifiersChanged(mods)); + h.run(); + } + h.drop_at(at + egui::vec2(dx, 0.0)); + h.run(); + }; + drag(&mut h, "Size:", 20.0, Modifiers::NONE); + assert_eq!(h.state().0, 120.0); + drag(&mut h, "Size:", -3.0, Modifiers::SHIFT); + assert_eq!(h.state().0, 90.0); + drag(&mut h, "Mode:", 20.0, Modifiers::NONE); + assert_eq!(h.state().1, 100.0, "the field isn't right after the label"); +} + +/// A right-aligned OK / Cancel / Apply row as `os` draws it: labels left to right, and the +/// row's right edge with the window's. +fn button_row(os: egui::os::OperatingSystem) -> (Vec, f32, f32) { + use super::{ButtonRole, DialogButton}; + use egui_kittest::{Harness, kittest::Queryable}; + // Drawn from the second frame, once the theme's fonts are bound. + let mut h = Harness::builder().with_size(egui::vec2(500.0, 80.0)).build_ui_state( + |ui, ready: &mut bool| { + if *ready { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| { + let row = [ + DialogButton::new(ButtonRole::Default, "OK", 84.0), + DialogButton::new(ButtonRole::Cancel, "Cancel", 84.0), + DialogButton::new(ButtonRole::Apply, "Apply", 84.0), + ]; + super::dialog_buttons(ui, &row); + }); + } + }, + false, + ); + crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.ctx.set_os(os); + *h.state_mut() = true; + h.run(); + let mut drawn: Vec<(f32, f32, String)> = + ["OK", "Cancel", "Apply"].iter().map(|l| (h.get_by_label(l).rect().left(), h.get_by_label(l).rect().right(), l.to_string())).collect(); + drawn.sort_by(|a, b| a.0.total_cmp(&b.0)); + let right = drawn.last().map_or(0.0, |d| d.1); + (drawn.into_iter().map(|d| d.2).collect(), right, h.ctx.content_rect().right()) +} + +#[test] +fn dialog_buttons_follow_the_platform_order() { + use egui::os::OperatingSystem as Os; + for (os, want) in [(Os::Windows, ["OK", "Cancel", "Apply"]), (Os::Nix, ["OK", "Cancel", "Apply"]), (Os::Mac, ["Cancel", "Apply", "OK"])] { + let (order, right, edge) = button_row(os); + assert_eq!(order, want, "{os:?}"); + assert!(edge - right < 20.0, "{os:?}: the row hugs the right edge ({right} of {edge})"); + } +} + +#[test] +fn two_decimal_numbers_trim_zeros() { + assert_eq!(super::fmt_num2(1.05), "1.05"); + assert_eq!(super::fmt_num2(0.78), "0.78"); + assert_eq!(super::fmt_num2(0.5), "0.5"); + assert_eq!(super::fmt_num2(2.0), "2"); +} + +#[test] +fn typed_arithmetic_evaluates() { + use super::parse_num; + for (text, want) in [ + ("1280*2", 2560.0), + ("658 * 1.5", 987.0), + ("48/3", 16.0), + ("20*2+5-2", 43.0), + ("2+3*4", 14.0), + ("10/4*2", 5.0), + ("-5+3", -2.0), + ("5--3", 8.0), + ("2*-3+1", -5.0), + ("−4", -4.0), + ("1 234", 1234.0), + ("1e3/2", 500.0), + ("(2+3)*4", 20.0), + ("2^3", 8.0), + ("10%3", 1.0), + ] { + assert_eq!(parse_num(text), Some(want), "{text}"); + } + for text in ["", "abc", "5+", "*2", "4/0", "0/0", "1+*2", "(2+3", "1e400"] { + assert_eq!(parse_num(text), None, "{text}"); + } +} + +/// Types `text` into a value field holding `start`, then presses `key`. Returns the value an OK +/// button that also fires on Enter saw, as dialogs read it, else the field's value. `round` +/// makes the caller round the value every frame, as pixel fields do. +fn type_and_press(start: f32, text: &str, key: egui::Key, round: bool) -> f32 { + use egui_kittest::{Harness, kittest::Queryable}; + let mut h = Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state( + move |ui, (v, ok): &mut (f32, Option)| { + super::value_field(ui, v, 0.0..=300000.0, "px", 90.0).accessible_name("Size"); + if round { + *v = v.round(); + } + if ui.button(tl!("OK")).clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) { + *ok = Some(*v); + } + }, + (start, None), + ); + h.get_by_role(egui::accesskit::Role::SpinButton).click(); + h.run(); + for c in text.chars() { + h.event(egui::Event::Text(c.to_string())); + h.run(); + } + h.key_press(key); + h.run(); + let (v, ok) = *h.state(); + ok.unwrap_or(v) +} + +/// Plain digits apply as they're typed; arithmetic doesn't report a change until it's committed. +#[test] +fn value_field_holds_arithmetic_until_committed() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut h = Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state( + |ui, (v, changes): &mut (f32, u32)| { + if super::value_field(ui, v, 0.0..=100.0, "%", 90.0).accessible_name("Opacity").changed() { + *changes += 1; + } + }, + (100.0, 0), + ); + h.get_by_role(egui::accesskit::Role::SpinButton).click(); + h.run(); + for (c, want) in [('5', (5.0, 1)), ('0', (50.0, 2)), ('/', (50.0, 2)), ('2', (50.0, 2))] { + h.event(egui::Event::Text(c.to_string())); + h.run(); + assert_eq!(*h.state(), want, "after {c}"); + } + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(*h.state(), (25.0, 3)); +} + +/// #5717: a value past the range shows as it is without reporting a change; an edit is clamped. +#[test] +fn value_field_keeps_a_shown_value_past_its_range_and_clamps_edits() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut h = Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state( + |ui, (v, changes): &mut (f32, u32)| { + if super::value_field(ui, v, 0.1..=1296.0, "pt", 90.0).accessible_name("Font size").changed() { + *changes += 1; + } + }, + (2400.0, 0), + ); + h.run_steps(3); + assert_eq!(*h.state(), (2400.0, 0), "showing it changes nothing"); + h.get_by_role(egui::accesskit::Role::SpinButton).click(); + h.run(); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("5000".into())); + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(h.state().0, 1296.0, "a typed value is clamped"); +} + +#[test] +fn value_field_applies_typed_arithmetic() { + use egui::Key::{Enter, Tab}; + assert_eq!(type_and_press(500.0, "1280*2", Tab, false), 2560.0); + assert_eq!(type_and_press(500.0, "1280*2", Enter, false), 2560.0); + // `5/2` alone would round to 3 under the caller; the whole expression still applies. + assert_eq!(type_and_press(1.0, "5/2*2", Tab, true), 5.0); + assert_eq!(type_and_press(1.0, "1280/3*2", Enter, true), 853.0); +} + +#[test] +fn numbers_drop_trailing_zero() { + // #2434: the unit keys map to Photoshop's places, and the shared formatter trims zeros. + assert_eq!(super::unit_decimals("px"), 0); + assert_eq!(super::unit_decimals("pt"), 1); + assert_eq!(super::unit_decimals("mm"), 2); + assert_eq!(super::unit_decimals("cm"), 2); + assert_eq!(super::unit_decimals("pica"), 2); + assert_eq!(super::unit_decimals("in"), 3); + assert_eq!(super::unit_decimals("nonsense"), 0); + assert_eq!(super::fmt_num_prec(0.7995, 3), "0.8"); + assert_eq!(super::fmt_num_prec(2.5, 0), "3"); + assert_eq!(super::fmt_num(100.0), "100"); + assert_eq!(super::fmt_num(12.46), "12.5"); + assert_eq!(super::fmt_num(-3.0), "-3"); +} + +#[test] +fn dropdown_opens_with_focus_and_arrow_keys_change_the_value() { + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + + let mut h = Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state( + |ui, selected: &mut usize| { + let options = [(0, "Normal"), (1, "Multiply"), (2, "Screen")]; + super::dropdown(ui, "blend-mode", tl!("Blend Mode"), selected, &options, 120.0); + }, + 0, + ); + h.get_by_role(Role::ComboBox).click(); + h.run(); + h.key_press(egui::Key::ArrowDown); + h.run(); + assert_eq!(*h.state(), 1); + h.key_press(egui::Key::ArrowUp); + h.run(); + assert_eq!(*h.state(), 0); +} + +/// Scrolling rows under the pointer doesn't widen the list: it is as wide as the widest +/// option hovered from the start (#2607). +#[test] +fn dropdown_list_keeps_its_width_while_scrolling() { + use photocraft_color::BlendMode; + let mut h = Harness::builder().with_size(egui::vec2(400.0, 700.0)).build_ui_state( + |ui, mode: &mut BlendMode| { + let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); + super::dropdown(ui, "brush-mode", tl!("Mode"), mode, &opts, 96.0); + }, + BlendMode::Normal, + ); + // The app's theme strokes plain rows, which is what made hovered rows wider. + crate::theme::apply(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run(); + h.get_by_role(egui::accesskit::Role::ComboBox).click(); + h.run(); + let list = |h: &Harness<'_, BlendMode>| h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))); + let Some(open) = list(&h) else { panic!("the list is open") }; + for _ in 0..30 { + h.hover_at(open.center()); + 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(); + assert_eq!(list(&h).map(|r| r.width()), Some(open.width())); + } +} + +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. +fn mode_dropdown(wheel: bool) -> Harness<'static, usize> { + Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state( + move |ui, selected: &mut usize| { + if wheel { + super::dropdown_wheel_hovered(ui, "blend-mode", tl!("Blend Mode"), selected, &MODES, 120.0); + } else { + super::dropdown(ui, "blend-mode", tl!("Blend Mode"), selected, &MODES, 120.0); + } + }, + 0, + ) +} + +/// One wheel event over the dropdown: negative `delta.y` is down. +fn wheel(h: &mut Harness<'_, T>, unit: egui::MouseWheelUnit, delta: egui::Vec2, modifiers: Modifiers) { + let at = h.get_by_role(egui::accesskit::Role::ComboBox).rect().center(); + h.event(egui::Event::ModifiersChanged(modifiers)); + h.hover_at(at); + h.run(); + h.event(egui::Event::MouseWheel { source: egui::MouseWheelSource::Unknown, unit, delta, phase: egui::TouchPhase::Move, modifiers }); + h.run(); + h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + h.run(); +} + +#[test] +fn shift_wheel_steps_one_mode_per_notch() { + let mut h = mode_dropdown(true); + wheel(&mut h, egui::MouseWheelUnit::Line, egui::vec2(0.0, -1.0), Modifiers::SHIFT); + assert_eq!(*h.state(), 1, "not ten like a slider"); + // Some systems turn Shift+wheel into a horizontal scroll. + wheel(&mut h, egui::MouseWheelUnit::Line, egui::vec2(-1.0, 0.0), Modifiers::SHIFT); + assert_eq!(*h.state(), 2); +} + +#[test] +fn fractional_wheel_deltas_add_up_to_whole_mode_steps() { + let mut h = mode_dropdown(true); + wheel(&mut h, egui::MouseWheelUnit::Line, egui::vec2(0.0, -0.5), Modifiers::NONE); + assert_eq!(*h.state(), 0, "half a notch"); + wheel(&mut h, egui::MouseWheelUnit::Line, egui::vec2(0.0, -0.5), Modifiers::NONE); + assert_eq!(*h.state(), 1); + let per_line = h.ctx.options(|o| o.input_options.line_scroll_speed); + wheel(&mut h, egui::MouseWheelUnit::Point, egui::vec2(0.0, -per_line), Modifiers::NONE); + assert_eq!(*h.state(), 2, "a line's worth of points is a notch"); +} + +#[test] +fn the_wheel_over_a_wheel_dropdown_does_not_scroll_its_container() { + let mut h = Harness::builder().with_size(egui::vec2(300.0, 100.0)).build_ui_state( + |ui, selected: &mut usize| { + egui::ScrollArea::vertical().max_height(80.0).show(ui, |ui| { + super::dropdown_wheel_hovered(ui, "blend-mode", tl!("Blend Mode"), selected, &MODES, 120.0); + ui.add_space(400.0); + }); + }, + 0, + ); + let top = h.get_by_role(egui::accesskit::Role::ComboBox).rect().top(); + wheel(&mut h, egui::MouseWheelUnit::Line, egui::vec2(0.0, -1.0), Modifiers::NONE); + for _ in 0..10 { + h.run(); + } + assert_eq!(*h.state(), 1); + assert_eq!(h.get_by_role(egui::accesskit::Role::ComboBox).rect().top(), top, "the container didn't scroll"); +} + +#[test] +fn the_wheel_leaves_a_plain_dropdown_alone() { + let mut h = mode_dropdown(false); + wheel(&mut h, egui::MouseWheelUnit::Line, egui::vec2(0.0, -1.0), Modifiers::NONE); + assert_eq!(*h.state(), 0); +} From 4d5b427795144bf323f3f541cebfb972e433b53f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:34 +0000 Subject: [PATCH 103/259] refactor(ui-egui): move wheel_nav.rs tests to wheel_nav/tests.rs --- crates/ui-egui/src/wheel_nav.rs | 1035 +------------------------ crates/ui-egui/src/wheel_nav/tests.rs | 1032 ++++++++++++++++++++++++ 2 files changed, 1033 insertions(+), 1034 deletions(-) create mode 100644 crates/ui-egui/src/wheel_nav/tests.rs diff --git a/crates/ui-egui/src/wheel_nav.rs b/crates/ui-egui/src/wheel_nav.rs index 51a5b1ec64..0d190a0633 100644 --- a/crates/ui-egui/src/wheel_nav.rs +++ b/crates/ui-egui/src/wheel_nav.rs @@ -539,1037 +539,4 @@ pub fn pinch_factor(i: &InputState, touch_gestures: bool) -> f32 { } #[cfg(test)] -mod tests { - use egui::TouchPhase; - - use super::*; - - fn input(scroll: Vec2, alt: bool) -> Input { - Input { scroll, raw: scroll, zoom_delta: 1.0, alt, shift: false, zoom_with_wheel: false, pinch_zooms: true, animated_zoom: true, notch: 40.0 } - } - - fn wheel(delta: Vec2, modifiers: Modifiers) -> Event { - Event::MouseWheel { source: egui::MouseWheelSource::Unknown, unit: MouseWheelUnit::Line, delta, phase: TouchPhase::Move, modifiers } - } - - const CTRL: Modifiers = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; - const CMD: Modifiers = Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE }; - - /// Feed `events` through an egui context set up like the app's (`legacy`: the Windows pinch - /// fold on) and add up what the wheel did to the view over the following second. - /// - /// `gesture` runs with Animated Zoom off (a notch is one instant step); see [`gesture_with`]. - fn gesture(frames: Vec>, zoom_with_wheel: bool, legacy: bool) -> (Vec2, f32, i32) { - gesture_with(frames, zoom_with_wheel, legacy, false) - } - - fn gesture_with(frames: Vec>, zoom_with_wheel: bool, legacy: bool, animated_zoom: bool) -> (Vec2, f32, i32) { - let owner = Id::unique("test-gesture"); - let ctx = Context::default(); - configure(&ctx); - let (mut pan, mut zoom, mut snaps) = (Vec2::ZERO, 1.0, 0i32); - let mut frames = frames.into_iter(); - for n in 0..60 { - let mut raw = - RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events: frames.next().unwrap_or_default(), ..Default::default() }; - if legacy { - fold_legacy_pinch(&ctx, &mut raw); - } - let mut out = ctx.run_ui(raw, |ui| match read(ui.ctx(), zoom_with_wheel, true, animated_zoom, owner, true) { - Some(Wheel::Pan(d)) => pan += d, - Some(Wheel::Zoom(f)) => zoom *= f, - Some(Wheel::SnapZoom(n)) => snaps += n, - None => {} - }); - out.textures_delta.clear(); - } - (pan, zoom, snaps) - } - - fn wheel_point(delta: Vec2, modifiers: Modifiers) -> Event { - Event::MouseWheel { source: egui::MouseWheelSource::Unknown, unit: MouseWheelUnit::Point, delta, phase: TouchPhase::Move, modifiers } - } - - fn near(a: Vec2, b: Vec2) -> bool { - (a - b).length() < 0.01 - } - - /// #5721: with smoothing off a wheel notch pans the whole notch in the frame it arrives and - /// nothing after; smoothed (the default) it glides, reaching the same total over later frames. - #[test] - fn unsmoothed_wheel_pans_at_once_without_a_glide() { - let pans = |smooth: bool| -> Vec { - let owner = Id::unique("test-unsmoothed"); - let ctx = Context::default(); - configure(&ctx); - (0..30) - .map(|n| { - let events = if n == 0 { vec![wheel(Vec2::new(0.0, -1.0), Modifiers::NONE)] } else { Vec::new() }; - let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; - let mut pan = Vec2::ZERO; - let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::Pan(d)) = read_with(ui.ctx(), false, true, true, owner, true, smooth, true) { - pan = d; - } - }); - out.textures_delta.clear(); - pan - }) - .collect() - }; - let notch = { - let ctx = Context::default(); - configure(&ctx); - ctx.options(|o| o.input_options.line_scroll_speed) - }; - let direct = pans(false); - assert!(near(direct[0], Vec2::new(0.0, -notch)), "the whole notch at once: {:?}", direct[0]); - assert!(direct[1..].iter().all(|p| *p == Vec2::ZERO), "no glide after it"); - let smooth = pans(true); - assert!(smooth[0].y.abs() < notch - 0.5, "smoothed, the first frame moves only part of it: {:?}", smooth[0]); - assert!(smooth[1..].iter().any(|p| p.y != 0.0), "and the rest follows"); - } - - /// Interface › Enable Animations off only stops the *pan* gliding. A plain wheel that zooms - /// (Zoom with Scroll Wheel) with Animated Zoom on must still ease over the frames of a notch, - /// exactly as it does with the pan smoothing on. - #[test] - fn animated_wheel_zoom_keeps_its_eased_tail_when_pan_smoothing_is_off() { - let frames = |smooth: bool| -> Vec { - let owner = Id::unique("test-animated-zoom-unsmoothed-pan"); - let ctx = Context::default(); - configure(&ctx); - (0..60) - .map(|n| { - let events = if n == 0 { vec![wheel(Vec2::new(0.0, 1.0), Modifiers::NONE)] } else { Vec::new() }; - let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; - let mut factor = 1.0; - let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::Zoom(f)) = read_with(ui.ctx(), true, true, true, owner, true, smooth, true) { - factor = f; - } - }); - out.textures_delta.clear(); - factor - }) - .collect() - }; - let unsmoothed = frames(false); - assert!(unsmoothed[0] > 1.0 && unsmoothed[0] < NOTCH - 1e-3, "the first frame carries only part of it: {:?}", &unsmoothed[..4]); - assert!(unsmoothed[1..].iter().any(|f| *f > 1.0), "and the rest follows: {unsmoothed:?}"); - let product: f32 = unsmoothed.iter().product(); - assert!((product - NOTCH).abs() < 1e-4, "still x1.1 in total: {product}"); - let smoothed = frames(true); - assert!(unsmoothed.iter().zip(&smoothed).all(|(a, b)| (a - b).abs() < 1e-6), "same pacing as with pan smoothing on"); - } - - #[test] - fn plain_scroll_pans() { - assert_eq!(classify(input(Vec2::new(3.0, -40.0), false)), Some(Wheel::Pan(Vec2::new(3.0, -40.0)))); - assert_eq!(classify(input(Vec2::ZERO, false)), None); - } - - #[test] - fn alt_scroll_zooms_ten_percent_per_notch() { - let Some(Wheel::Zoom(f)) = classify(input(Vec2::new(0.0, 40.0), true)) else { panic!("zoom") }; - assert!((f - 1.1).abs() < 1e-5, "{f}"); - let Some(Wheel::Zoom(f)) = classify(input(Vec2::new(0.0, -40.0), true)) else { panic!("zoom") }; - assert!((f - 1.0 / 1.1).abs() < 1e-5, "{f}"); - // Two notches in one frame are two steps, x1.1 each. - let Some(Wheel::Zoom(f)) = classify(input(Vec2::new(0.0, 80.0), true)) else { panic!("zoom") }; - assert!((f - 1.21).abs() < 1e-4, "{f}"); - } - - /// Animated Zoom off: a notch is one instant step, and egui's smoothed tail does nothing. - #[test] - fn a_notch_zooms_the_frame_it_arrives_and_its_smoothed_tail_does_nothing() { - // egui keeps feeding a smoothed delta for several frames after the wheel event. Zooming - // must not follow it (that would ease the zoom), nor turn it into a pan. - let off = |i: Input| Input { animated_zoom: false, ..i }; - let tail = off(Input { raw: Vec2::ZERO, ..input(Vec2::new(0.0, 12.0), true) }); - assert_eq!(classify(tail), None); - let tail = off(Input { raw: Vec2::ZERO, zoom_with_wheel: true, ..input(Vec2::new(0.0, 12.0), false) }); - assert_eq!(classify(tail), None); - // The frame the notch arrives carries it whole, whatever the smoothed delta is. - let arrival = off(Input { scroll: Vec2::new(0.0, 12.0), raw: Vec2::new(0.0, 40.0), ..input(Vec2::ZERO, true) }); - assert!(matches!(classify(arrival), Some(Wheel::Zoom(f)) if (f - 1.1).abs() < 1e-5)); - // Plain scrolling without the preference still pans from the smoothed delta. - let pan = off(Input { raw: Vec2::ZERO, ..input(Vec2::new(0.0, 12.0), false) }); - assert_eq!(classify(pan), Some(Wheel::Pan(Vec2::new(0.0, 12.0)))); - } - - /// Animated Zoom on: the zoom follows egui's smoothed delta over the frames of a notch, and - /// never turns that tail into a pan. - #[test] - fn animated_zoom_follows_the_smoothed_tail_of_a_notch() { - let tail = Input { raw: Vec2::ZERO, ..input(Vec2::new(0.0, 12.0), true) }; - assert!(matches!(classify(tail), Some(Wheel::Zoom(f)) if f > 1.0)); - let tail = Input { raw: Vec2::ZERO, zoom_with_wheel: true, ..input(Vec2::new(0.0, 12.0), false) }; - assert!(matches!(classify(tail), Some(Wheel::Zoom(f)) if f > 1.0)); - // The size of the step comes from the smoothed delta, not the raw one. - let part = Input { scroll: Vec2::new(0.0, 20.0), raw: Vec2::new(0.0, 40.0), ..input(Vec2::ZERO, true) }; - assert!(matches!(classify(part), Some(Wheel::Zoom(f)) if (f - 1.1f32.powf(0.5)).abs() < 1e-5)); - // Plain scrolling without the preference still pans from the smoothed delta. - let pan = Input { raw: Vec2::ZERO, ..input(Vec2::new(0.0, 12.0), false) }; - assert_eq!(classify(pan), Some(Wheel::Pan(Vec2::new(0.0, 12.0)))); - // ⇧ + snap zoom stays on the wheel events and instant, in both modes. - for animated_zoom in [false, true] { - let tail = Input { shift: true, zoom_with_wheel: true, raw: Vec2::ZERO, animated_zoom, ..input(Vec2::new(12.0, 0.0), false) }; - assert_eq!(classify(tail), None, "animated_zoom {animated_zoom}"); - let snap = Input { shift: true, zoom_with_wheel: true, raw: Vec2::new(0.0, 40.0), animated_zoom, ..input(Vec2::new(0.0, 12.0), false) }; - assert_eq!(classify(snap), Some(Wheel::SnapZoom(1)), "animated_zoom {animated_zoom}"); - } - } - - /// The factor of every frame of one notch, through a real egui context (60 frames at 60 fps). - fn zoom_frames(modifiers: Modifiers, zoom_with_wheel: bool, animated_zoom: bool) -> Vec { - let owner = Id::unique("test-zoom-frames"); - let ctx = Context::default(); - configure(&ctx); - (0..60) - .map(|n| { - let events = if n == 0 { vec![wheel(Vec2::new(0.0, 1.0), modifiers)] } else { Vec::new() }; - let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; - let mut factor = 1.0; - let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::Zoom(f)) = read(ui.ctx(), zoom_with_wheel, true, animated_zoom, owner, true) { - factor = f; - } - }); - out.textures_delta.clear(); - factor - }) - .collect() - } - - /// The property the eased zoom relies on: however egui spreads a notch over frames, the - /// factors of those frames multiply to exactly ×1.1 (and ×1/1.1 for a notch the other way). - #[test] - fn the_eased_frames_of_one_notch_multiply_to_ten_percent() { - for (modifiers, zoom_with_wheel) in [(Modifiers::ALT, false), (Modifiers::NONE, true)] { - let frames = zoom_frames(modifiers, zoom_with_wheel, true); - assert!(frames.iter().all(|f| f.is_finite() && *f >= 1.0), "{frames:?}"); - assert!(frames.iter().filter(|f| **f != 1.0).count() > 1, "eased over several frames: {frames:?}"); - let product: f32 = frames.iter().product(); - assert!((product - NOTCH).abs() < 1e-4, "{modifiers:?} zoom_with_wheel {zoom_with_wheel}: {product} from {frames:?}"); - } - // The other way round: ×1/1.1. - let owner = Id::unique("test-zoom-frames-out"); - let ctx = Context::default(); - configure(&ctx); - let mut product = 1.0f32; - for n in 0..60 { - let events = if n == 0 { vec![wheel(Vec2::new(0.0, -1.0), Modifiers::ALT)] } else { Vec::new() }; - let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::Zoom(f)) = read(ui.ctx(), false, true, true, owner, true) { - product *= f; - } - }); - out.textures_delta.clear(); - } - assert!((product - 1.0 / NOTCH).abs() < 1e-4, "{product}"); - } - - /// Animated Zoom changes the pacing of a notch, never its size: off, the whole ×1.1 lands in - /// the frame the notch arrives and nothing follows; on, that frame carries only part of it. - #[test] - fn animated_zoom_changes_the_pacing_of_a_notch_not_its_size() { - for (modifiers, zoom_with_wheel) in [(Modifiers::ALT, false), (Modifiers::NONE, true)] { - let instant = zoom_frames(modifiers, zoom_with_wheel, false); - assert!((instant[0] - NOTCH).abs() < 1e-5, "the whole notch at once: {:?}", &instant[..4]); - assert!(instant[1..].iter().all(|f| *f == 1.0), "no tail after it: {instant:?}"); - let eased = zoom_frames(modifiers, zoom_with_wheel, true); - assert!(eased[0] > 1.0 && eased[0] < NOTCH - 1e-3, "the first frame carries only part of it: {:?}", &eased[..4]); - assert!(eased[1..].iter().any(|f| *f > 1.0), "and the rest follows"); - } - } - - /// Animated Zoom is only about the wheel zoom: ⇧ snap zoom and plain scrolling are the same - /// in both modes. - #[test] - fn animated_zoom_leaves_snap_zoom_and_panning_alone() { - let notch = Vec2::new(0.0, 1.0); - let shift_alt = Modifiers { shift: true, alt: true, ..Modifiers::NONE }; - for animated_zoom in [false, true] { - let (pan, zoom, snaps) = gesture_with(vec![vec![wheel(notch, shift_alt)]], false, false, animated_zoom); - assert!(pan == Vec2::ZERO && zoom == 1.0 && snaps == 1, "⇧ + ⌥: {pan:?} {zoom} {snaps}"); - let (pan, zoom, snaps) = gesture_with(vec![vec![wheel(notch, Modifiers::NONE)]], false, false, animated_zoom); - assert!(near(pan, Vec2::new(0.0, 40.0)) && zoom == 1.0 && snaps == 0, "plain wheel pans: {pan:?} {zoom} {snaps}"); - // A notch zooms ×1.1 in total in either mode. - let (pan, zoom, _) = gesture_with(vec![vec![wheel(notch, Modifiers::ALT)]], false, false, animated_zoom); - assert!(pan == Vec2::ZERO && (zoom - NOTCH).abs() < 1e-4, "animated_zoom {animated_zoom}: {pan:?} {zoom}"); - } - } - - /// A pan notch still gliding when an ⌥ notch arrives (and the same the other way round with - /// Zoom with Scroll Wheel): the zoom is that one notch's ×1.1, not the sum of both tails. - #[test] - fn a_pan_tail_does_not_leak_into_the_animated_zoom() { - let notch = Vec2::new(0.0, 1.0); - // Wheel pans, ⌥ zooms: plain notch, then ⌥ notch one frame later. - let frames = vec![vec![wheel(notch, Modifiers::NONE)], vec![wheel(notch, Modifiers::ALT)]]; - let (pan, zoom, snaps) = gesture_with(frames, false, false, true); - assert!((zoom - NOTCH).abs() < 1e-4, "only the ⌥ notch zooms: {zoom}"); - assert!(pan.y > 0.0 && pan.y < 40.0 && snaps == 0, "the plain notch only panned its first frame: {pan:?} {snaps}"); - // Wheel zooms, ⌥ pans: ⌥ notch, then plain notch. - let frames = vec![vec![wheel(notch, Modifiers::ALT)], vec![wheel(notch, Modifiers::NONE)]]; - let (_, zoom, snaps) = gesture_with(frames, true, false, true); - assert!((zoom - NOTCH).abs() < 1e-4, "only the plain notch zooms: {zoom}"); - assert_eq!(snaps, 0); - } - - /// The zoom factor of each of `frames` frames with Animated Zoom on and ⌥ zooming. `time` gives a - /// frame's timestamp and `hovered` whether the owner is hovered in it. - fn run_zoom(frames: u32, events: impl Fn(u32) -> Vec, time: impl Fn(u32) -> f64, hovered: impl Fn(u32) -> bool) -> Vec { - let owner = Id::unique("test-run-zoom"); - let ctx = Context::default(); - configure(&ctx); - (0..frames) - .map(|n| { - let raw = RawInput { time: Some(time(n)), predicted_dt: 1.0 / 60.0, events: events(n), ..Default::default() }; - let mut factor = 1.0; - let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::Zoom(f)) = read(ui.ctx(), false, true, true, owner, hovered(n)) { - factor = f; - } - }); - out.textures_delta.clear(); - factor - }) - .collect() - } - - /// A slow frame in the middle of an eased notch (a big image redrawing) must not drop what is - /// left of it: the notch still adds up to exactly ×1.1. - #[test] - fn a_slow_frame_does_not_cut_an_eased_notch_short() { - let notch = Vec2::new(0.0, 1.0); - let time = |n: u32| if n == 0 { 0.0 } else { 0.7 + f64::from(n - 1) / 60.0 }; - let frames = run_zoom(60, |n| if n == 0 { vec![wheel(notch, Modifiers::ALT)] } else { Vec::new() }, time, |_| true); - let product: f32 = frames.iter().product(); - assert!((product - NOTCH).abs() < 1e-4, "still x1.1 in total: {product} from {frames:?}"); - } - - /// What is left of an eased notch when the pointer leaves the viewport is dropped: a notch - /// made after it comes back is ×1.1 on its own, not ×1.1 plus the old remainder. - #[test] - fn an_unfinished_notch_is_not_carried_into_a_notch_after_the_pointer_left() { - let notch = Vec2::new(0.0, 1.0); - let events = |n: u32| if n == 0 || n == 40 { vec![wheel(notch, Modifiers::ALT)] } else { Vec::new() }; - let frames = run_zoom(100, events, |n| f64::from(n) / 60.0, |n| !(1..30).contains(&n)); - let first: f32 = frames[..40].iter().product(); - assert!(first > 1.0 && first < NOTCH - 1e-3, "the first notch was left unfinished: {first}"); - let second: f32 = frames[40..].iter().product(); - assert!((second - NOTCH).abs() < 1e-4, "the second notch is ×1.1 on its own: {second}"); - } - - /// Zoom with Scroll Wheel + Animated Zoom (the defaults of both): ⌘/Ctrl + wheel still scrolls - /// sideways, as it does with Animated Zoom off. - #[test] - fn animated_zoom_keeps_ctrl_wheel_sideways_scroll_with_zoom_with_wheel() { - let (pan, zoom, snaps) = gesture_with(vec![vec![wheel(Vec2::new(0.0, 1.0), CTRL)]], true, false, true); - assert!(near(pan, Vec2::new(40.0, 0.0)) && zoom == 1.0 && snaps == 0, "{pan:?} {zoom} {snaps}"); - } - - /// Shift snap zoom interrupting an unfinished animated notch drops that notch's residual: a - /// continuous zoom started right after Shift is released is its own ×1.1 and nothing more. - #[test] - fn shift_snap_zoom_drops_the_unfinished_eased_notch() { - let notch = Vec2::new(0.0, 1.0); - let shift_alt = Modifiers { shift: true, ..Modifiers::ALT }; - let owner = Id::unique("test-snap-interrupts-ease"); - let ctx = Context::default(); - configure(&ctx); - let (mut zoom, mut zoom_after_first, mut snaps) = (1.0f32, 1.0f32, 0i32); - for n in 0..60u32 { - // ⌥ notch (eases), ⇧⌥ notch (snap zoom takes over), then ⌥ notch again within 0.5 s. - let events = match n { - 0 | 2 => vec![wheel(notch, Modifiers::ALT)], - 1 => vec![wheel(notch, shift_alt)], - _ => Vec::new(), - }; - let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| match read(ui.ctx(), false, true, true, owner, true) { - Some(Wheel::Zoom(f)) => zoom *= f, - Some(Wheel::SnapZoom(s)) => snaps += s, - _ => {} - }); - out.textures_delta.clear(); - if n == 0 { - zoom_after_first = zoom; - } - } - assert_eq!(snaps, 1); - let second = zoom / zoom_after_first; - assert!((second - NOTCH).abs() < 1e-4, "the second ⌥ notch zooms ×1.1 on its own: {second}"); - } - - /// A trackpad's ⌥ + two-finger scroll comes in points and is already smooth: egui leaves it - /// unsmoothed because smoothing adds latency, so Animated Zoom must not ease it either. Each - /// frame zooms by its own events, at once. - #[test] - fn animated_zoom_does_not_ease_a_trackpad() { - let frames = - run_zoom(30, |n| if n == 0 { vec![wheel_point(Vec2::new(0.0, 4.0), Modifiers::ALT)] } else { Vec::new() }, |n| f64::from(n) / 60.0, |_| true); - assert!((frames[0] - NOTCH.powf(0.1)).abs() < 1e-6, "all of it in the frame it arrives: {:?}", &frames[..4]); - assert!(frames[1..].iter().all(|f| *f == 1.0), "no tail after it: {frames:?}"); - } - - /// Zoom with Scroll Wheel + Animated Zoom with Enable Animations off: the wheel zooms eased, but - /// a sideways wheel still pans without a glide (#5721), all of it in the frame it turns. - #[test] - fn animated_zoom_keeps_the_sideways_wheel_unsmoothed_with_animations_off() { - let owner = Id::unique("test-sideways-unsmoothed"); - let ctx = Context::default(); - configure(&ctx); - let pans: Vec = (0..30) - .map(|n| { - let events = if n == 0 { vec![wheel(Vec2::new(1.0, 0.0), Modifiers::NONE)] } else { Vec::new() }; - let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; - let mut pan = Vec2::ZERO; - let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::Pan(d)) = read_with(ui.ctx(), true, true, true, owner, true, false, true) { - pan = d; - } - }); - out.textures_delta.clear(); - pan - }) - .collect(); - assert!(near(pans[0], Vec2::new(40.0, 0.0)), "the whole notch at once: {:?}", &pans[..4]); - assert!(pans[1..].iter().all(|p| *p == Vec2::ZERO), "no glide after it: {pans:?}"); - } - - /// A diagonal point step with ⌥ is measured as egui measures it, folded onto one axis: (5, 5) - /// is a 10-point step, which egui smooths, so Animated Zoom eases it. - #[test] - fn a_diagonal_alt_point_step_is_measured_like_egui() { - let frames = - run_zoom(60, |n| if n == 0 { vec![wheel_point(Vec2::new(5.0, 5.0), Modifiers::ALT)] } else { Vec::new() }, |n| f64::from(n) / 60.0, |_| true); - assert!(frames[0] < NOTCH.powf(0.25) - 1e-4 && frames[1] > 1.0, "eased: {:?}", &frames[..4]); - } - - /// A touch whose end nobody read (no canvas in that pass, e.g. the last document closed - /// during a trackpad scroll) must not leave later mouse notches un-eased. - #[test] - fn a_touch_end_nobody_read_does_not_stick() { - let owner = Id::unique("test-touch-unread-end"); - let ctx = Context::default(); - configure(&ctx); - let point = |phase: TouchPhase| Event::MouseWheel { - source: egui::MouseWheelSource::Unknown, - unit: MouseWheelUnit::Point, - delta: Vec2::ZERO, - phase, - modifiers: Modifiers::ALT, - }; - let mut first = 1.0; - for n in 0..10u32 { - let events = match n { - 0 => vec![point(TouchPhase::Start)], - 2 => vec![point(TouchPhase::End)], - 5 => vec![wheel(Vec2::new(0.0, 1.0), Modifiers::ALT)], - _ => Vec::new(), - }; - let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| { - // Frames 2-3: nothing reads the wheel. - if !(2..4).contains(&n) - && let Some(Wheel::Zoom(f)) = read(ui.ctx(), false, true, true, owner, true) - && n == 5 - { - first = f; - } - }); - out.textures_delta.clear(); - } - assert!(first > 1.0 && first < NOTCH - 1e-3, "the notch is eased: {first}"); - } - - /// Quick back-and-forth wheeling still lands on whole ×1.1 steps: three notches in and one - /// out a frame later is ×1.1², whatever was still easing. - #[test] - fn a_quick_notch_back_nets_out() { - for back_at in [1, 3] { - let events = |n: u32| match n { - 0 => vec![wheel(Vec2::new(0.0, 3.0), Modifiers::ALT)], - n if n == back_at => vec![wheel(Vec2::new(0.0, -1.0), Modifiers::ALT)], - _ => Vec::new(), - }; - let total: f32 = run_zoom(60, events, |n| f64::from(n) / 60.0, |_| true).iter().product(); - assert!((total - NOTCH * NOTCH).abs() < 1e-4, "back at frame {back_at}: {total}"); - } - } - - /// A browser reports a mouse notch as a big pixel step (about 100 points in Chrome), which - /// egui smooths like a notch: Animated Zoom eases it too. Within a trackpad touch (egui's - /// `InTouch`) even big point steps zoom at once. - #[test] - fn animated_zoom_eases_big_pixel_steps_but_not_a_touch() { - let point = |dy: f32, phase: TouchPhase| Event::MouseWheel { - source: egui::MouseWheelSource::Unknown, - unit: MouseWheelUnit::Point, - delta: Vec2::new(0.0, dy), - phase, - modifiers: Modifiers::ALT, - }; - let browser = run_zoom(60, |n| if n == 0 { vec![point(100.0, TouchPhase::Move)] } else { Vec::new() }, |n| f64::from(n) / 60.0, |_| true); - assert!(browser[0] > 1.0 && browser[0] < NOTCH.powf(2.5) - 1e-3, "eased: {:?}", &browser[..4]); - let total: f32 = browser.iter().product(); - assert!((total - NOTCH.powf(2.5)).abs() < 1e-3, "{total}"); - let events = |n: u32| match n { - 0 => vec![point(0.0, TouchPhase::Start)], - 1 => vec![point(20.0, TouchPhase::Move)], - _ => Vec::new(), - }; - let touch = run_zoom(30, events, |n| f64::from(n) / 60.0, |_| true); - assert!((touch[1] - NOTCH.powf(0.5)).abs() < 1e-5, "at once: {:?}", &touch[..4]); - assert!(touch[2..].iter().all(|f| *f == 1.0), "no tail: {touch:?}"); - } - - #[test] - fn pinch_zooms() { - let i = Input { zoom_delta: 1.2, ..input(Vec2::ZERO, false) }; - assert_eq!(classify(i), Some(Wheel::Zoom(1.2))); - // The pinch wins over Alt. - let i = Input { zoom_delta: 0.8, ..input(Vec2::new(0.0, 40.0), true) }; - assert_eq!(classify(i), Some(Wheel::Zoom(0.8))); - } - - /// Preferences › Enhanced Controls › Zoom with Trackpad Pinch off: the pinch is ignored, and - /// a scroll in the same frame pans as it would without a pinch. - #[test] - fn the_pinch_preference_switches_pinch_zooming() { - let i = Input { zoom_delta: 1.2, pinch_zooms: false, ..input(Vec2::ZERO, false) }; - assert_eq!(classify(i), None); - let i = Input { zoom_delta: 1.2, pinch_zooms: false, ..input(Vec2::new(0.0, 12.0), false) }; - assert_eq!(classify(i), Some(Wheel::Pan(Vec2::new(0.0, 12.0)))); - // On (the default) the pinch still zooms. - let i = Input { zoom_delta: 1.2, pinch_zooms: true, ..input(Vec2::ZERO, false) }; - assert_eq!(classify(i), Some(Wheel::Zoom(1.2))); - } - - /// The Windows pinch fold follows the preference too: off, the Ctrl + wheel fractions stay - /// wheel events (which egui folds into a sideways scroll). - #[test] - fn the_windows_pinch_fold_follows_the_preference() { - use eframe::App as _; - if !cfg!(target_os = "windows") { - return; - } - let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let ctx = Context::default(); - let event = || Event::MouseWheel { - unit: MouseWheelUnit::Line, - delta: egui::vec2(0.0, 0.25), - phase: egui::TouchPhase::Move, - source: egui::MouseWheelSource::Unknown, - modifiers: Modifiers { ctrl: true, command: true, ..Modifiers::NONE }, - }; - let mut raw = RawInput { time: Some(1.0), events: vec![event()], ..Default::default() }; - app.raw_input_hook(&ctx, &mut raw); - assert!(matches!(raw.events[0], Event::Zoom(_)), "the fraction is a pinch: {:?}", raw.events[0]); - app.run("prefs.set", serde_json::json!({"path": "enhancedControls.zoomWithTrackpadPinch", "value": false})).unwrap(); - let mut raw = RawInput { time: Some(2.0), events: vec![event()], ..Default::default() }; - app.raw_input_hook(&ctx, &mut raw); - assert!(matches!(raw.events[0], Event::MouseWheel { .. }), "off: it stays a wheel event: {:?}", raw.events[0]); - } - - #[test] - fn zoom_with_scroll_wheel_preference_swaps_wheel_and_alt_wheel() { - let pref = |scroll, alt| Input { zoom_with_wheel: true, ..input(scroll, alt) }; - let Some(Wheel::Zoom(f)) = classify(pref(Vec2::new(0.0, 40.0), false)) else { panic!("zoom") }; - assert!((f - 1.1).abs() < 1e-5, "{f}"); - assert_eq!(classify(pref(Vec2::new(0.0, 40.0), true)), Some(Wheel::Pan(Vec2::new(0.0, 40.0))), "⌥ + wheel scrolls"); - assert_eq!(classify(pref(Vec2::new(40.0, 0.0), false)), Some(Wheel::Pan(Vec2::new(40.0, 0.0))), "sideways still scrolls"); - } - - #[test] - fn shift_scroll_snaps_to_zoom_ladder_with_preference() { - let snap = |dy: f32| Input { shift: true, zoom_with_wheel: true, ..input(Vec2::new(0.0, dy), false) }; - assert_eq!(classify(snap(40.0)), Some(Wheel::SnapZoom(1)), "one notch up → +1 step"); - assert_eq!(classify(snap(-40.0)), Some(Wheel::SnapZoom(-1)), "one notch down → −1 step"); - assert_eq!(classify(snap(80.0)), Some(Wheel::SnapZoom(2)), "two notches → +2 steps"); - assert_eq!(classify(snap(0.0)), None, "no scroll → nothing"); - // Some systems deliver Shift+wheel as horizontal (delta in x, y = 0). - let snap_h = |dx: f32| Input { shift: true, zoom_with_wheel: true, raw: Vec2::new(dx, 0.0), ..input(Vec2::new(dx, 0.0), false) }; - assert_eq!(classify(snap_h(40.0)), Some(Wheel::SnapZoom(1)), "horizontal notch → +1 step"); - assert_eq!(classify(snap_h(-40.0)), Some(Wheel::SnapZoom(-1)), "horizontal notch down → −1 step"); - } - - #[test] - fn shift_scroll_tail_does_not_snap_or_pan() { - let tail = Input { shift: true, zoom_with_wheel: true, raw: Vec2::ZERO, ..input(Vec2::new(12.0, 0.0), false) }; - assert_eq!(classify(tail), None, "smoothed tail of ⇧ + scroll produces nothing"); - } - - #[test] - fn shift_alt_scroll_snaps_without_preference() { - let snap = |dy: f32| Input { shift: true, ..input(Vec2::new(0.0, dy), true) }; - assert_eq!(classify(snap(40.0)), Some(Wheel::SnapZoom(1)), "⇧ + ⌥ + notch up → +1 step"); - assert_eq!(classify(snap(-40.0)), Some(Wheel::SnapZoom(-1)), "⇧ + ⌥ + notch down → −1 step"); - assert_eq!(classify(snap(0.0)), None, "no scroll → nothing"); - } - - #[test] - fn shift_only_without_zoom_with_wheel_does_not_snap() { - let i = Input { shift: true, zoom_with_wheel: false, ..input(Vec2::new(0.0, 40.0), false) }; - assert_eq!(classify(i), Some(Wheel::Pan(Vec2::new(0.0, 40.0))), "⇧ alone without the preference: no zoom"); - } - - #[test] - fn shift_scroll_snaps_through_egui_context() { - let notch = Vec2::new(0.0, 1.0); - // Shift + wheel with zoom_with_wheel on. - let (pan, zoom, snaps) = gesture(vec![vec![wheel(notch, Modifiers::SHIFT)]], true, false); - assert_eq!(snaps, 1, "⇧ + wheel with zoom_with_wheel → snap"); - assert!(pan == Vec2::ZERO, "no pan: {pan:?}"); - assert_eq!(zoom, 1.0, "no continuous zoom: {zoom}"); - let (_, _, snaps) = gesture(vec![vec![wheel(-notch, Modifiers::SHIFT)]], true, false); - assert_eq!(snaps, -1, "⇧ + wheel down → snap out"); - // Some systems deliver Shift+wheel as horizontal (delta in x, y = 0). - let h_notch = Vec2::new(1.0, 0.0); - let (pan, zoom, snaps) = gesture(vec![vec![wheel(h_notch, Modifiers::SHIFT)]], true, false); - assert_eq!(snaps, 1, "⇧ + horizontal wheel with zoom_with_wheel → snap"); - assert!(pan == Vec2::ZERO, "no pan: {pan:?}"); - assert_eq!(zoom, 1.0, "no continuous zoom: {zoom}"); - // Shift + Alt + wheel without the preference. - let shift_alt = Modifiers { shift: true, alt: true, ..Modifiers::NONE }; - let (pan, zoom, snaps) = gesture(vec![vec![wheel(notch, shift_alt)]], false, false); - assert_eq!(snaps, 1, "⇧ + ⌥ + wheel → snap"); - assert!(pan == Vec2::ZERO, "no pan: {pan:?}"); - assert_eq!(zoom, 1.0, "no continuous zoom: {zoom}"); - } - - #[test] - fn each_modifier_maps_like_photoshop() { - let notch = Vec2::new(0.0, 1.0); - let one = |m: Modifiers| gesture(vec![vec![wheel(notch, m)]], false, false); - let (pan, zoom, _) = one(Modifiers::NONE); - assert!(near(pan, Vec2::new(0.0, 40.0)) && zoom == 1.0, "wheel scrolls vertically: {pan:?} {zoom}"); - for m in [Modifiers::SHIFT, CTRL, CMD, Modifiers::CTRL] { - let (pan, zoom, _) = one(m); - assert!(near(pan, Vec2::new(40.0, 0.0)) && zoom == 1.0, "{m:?} + wheel scrolls sideways: {pan:?} {zoom}"); - } - let (pan, zoom, _) = one(Modifiers::ALT); - assert!(pan == Vec2::ZERO && (zoom - 1.1).abs() < 1e-4, "⌥ + wheel zooms 10%, at once: {pan:?} {zoom}"); - // Zoom with Scroll Wheel on: swapped. - let (pan, zoom, _) = gesture(vec![vec![wheel(notch, Modifiers::ALT)]], true, false); - assert!(near(pan, Vec2::new(0.0, 40.0)) && zoom == 1.0, "{pan:?} {zoom}"); - let (pan, zoom, _) = gesture(vec![vec![wheel(notch, Modifiers::NONE)]], true, false); - assert!(pan == Vec2::ZERO && (zoom - 1.1).abs() < 1e-4, "{pan:?} {zoom}"); - let (pan, zoom, _) = gesture(vec![vec![wheel(notch, CTRL)]], true, false); - assert!(near(pan, Vec2::new(40.0, 0.0)) && zoom == 1.0, "⌘/Ctrl + wheel still scrolls sideways: {pan:?} {zoom}"); - } - - #[test] - fn pinch_zooms_and_ctrl_wheel_pans() { - // macOS trackpad and browsers: the pinch is its own event. - let (pan, zoom, _) = gesture(vec![vec![Event::Zoom(1.1)], vec![Event::Zoom(1.1)]], false, false); - assert!(pan == Vec2::ZERO && (zoom - 1.21).abs() < 1e-4, "{pan:?} {zoom}"); - // Windows: a touchpad pinch is Ctrl + wheel in fractions of a notch, a mouse wheel whole notches. - let (pan, zoom, _) = gesture(vec![vec![wheel(Vec2::new(0.0, 0.25), CTRL)], vec![wheel(Vec2::new(0.0, 0.5), CTRL)]], false, true); - let speed = egui::InputOptions::default().scroll_zoom_speed; - assert!(pan == Vec2::ZERO && (zoom - (speed * 40.0 * 0.75).exp()).abs() < 1e-4, "the pinch zooms: {pan:?} {zoom}"); - let (pan, zoom, _) = gesture(vec![vec![wheel(Vec2::new(0.0, 1.0), CTRL)]], false, true); - assert!(near(pan, Vec2::new(40.0, 0.0)) && zoom == 1.0, "Ctrl + mouse wheel scrolls sideways: {pan:?} {zoom}"); - } - - #[test] - fn linux_wayland_point_unit_pinch_keeps_mouse_notches_for_sideways_scroll() { - // Some Wayland compositors report fractional Ctrl-wheel pinch steps in points - // rather than line units. The delta must not be multiplied by notch twice. - let mut point = [Event::MouseWheel { - source: egui::MouseWheelSource::Unknown, - unit: MouseWheelUnit::Point, - delta: Vec2::new(0.0, 8.0), - phase: TouchPhase::Move, - modifiers: CTRL, - }]; - assert_eq!(legacy_pinch_to_zoom(&mut point, 1.0, None, 40.0, 0.005), Some(1.0)); - assert!(matches!(point[0], Event::Zoom(f) if (f - (8.0f32 * 0.005).exp()).abs() < 1e-5)); - let mut wheel_only = [wheel(Vec2::new(0.0, 1.0), CTRL)]; - assert_eq!(legacy_pinch_to_zoom(&mut wheel_only, 2.0, Some(1.0), 40.0, 0.005), Some(1.0)); - assert!(matches!(wheel_only[0], Event::MouseWheel { .. }), "whole mouse notch is not a pinch"); - } - - #[test] - fn native_pinch_is_not_zoomed_twice_when_ctrl_wheel_arrives_in_the_same_frame() { - let (_, zoom, _) = gesture(vec![vec![Event::Zoom(1.2), wheel(Vec2::new(0.0, 0.25), CTRL)]], false, true); - assert!((zoom - 1.2).abs() < 1e-4, "native zoom must win over fallback: {zoom}"); - } - - #[test] - fn native_pinch_resets_legacy_gesture_continuation() { - let ctx = Context::default(); - let mut legacy = RawInput { time: Some(1.0), events: vec![wheel(Vec2::new(0.0, 0.25), CTRL)], ..Default::default() }; - fold_legacy_pinch(&ctx, &mut legacy); - assert!(matches!(legacy.events[0], Event::Zoom(_))); - - // Native magnification takes over before the synthetic gesture times out. - let mut native = RawInput { time: Some(1.1), events: vec![Event::Zoom(1.1), wheel(Vec2::new(0.0, 0.25), CTRL)], ..Default::default() }; - fold_legacy_pinch(&ctx, &mut native); - assert!(matches!(native.events[0], Event::Zoom(f) if (f - 1.1).abs() < 1e-5)); - assert!(matches!(native.events[1], Event::MouseWheel { .. })); - - // A notched mouse scroll must no longer inherit the previous pinch. - let mut notch = RawInput { time: Some(1.12), events: vec![wheel(Vec2::new(0.0, 1.0), CTRL)], ..Default::default() }; - fold_legacy_pinch(&ctx, &mut notch); - assert!(matches!(notch.events[0], Event::MouseWheel { .. })); - } - - #[test] - fn a_whole_notch_inside_a_pinch_stays_a_pinch() { - let mut ev = [wheel(Vec2::new(0.0, 0.5), CTRL)]; - let t = legacy_pinch_to_zoom(&mut ev, 1.0, None, 40.0, 0.005); - assert_eq!(t, Some(1.0)); - assert!(matches!(ev[0], Event::Zoom(f) if (f - 0.1f32.exp()).abs() < 1e-5), "{ev:?}"); - // The next step lands on a whole notch: still the pinch. - let mut ev = [wheel(Vec2::new(0.0, -1.0), CTRL)]; - assert_eq!(legacy_pinch_to_zoom(&mut ev, 1.1, t, 40.0, 0.005), Some(1.1)); - assert!(matches!(ev[0], Event::Zoom(f) if f < 1.0), "{ev:?}"); - // Long after: a mouse wheel notch, untouched. - let mut ev = [wheel(Vec2::new(0.0, -1.0), CTRL)]; - assert_eq!(legacy_pinch_to_zoom(&mut ev, 2.0, Some(1.1), 40.0, 0.005), Some(1.1)); - assert!(matches!(ev[0], Event::MouseWheel { .. })); - // Without Ctrl nothing is a pinch. - let mut ev = [wheel(Vec2::new(0.0, 0.5), Modifiers::NONE)]; - assert_eq!(legacy_pinch_to_zoom(&mut ev, 2.0, None, 40.0, 0.005), None); - assert!(matches!(ev[0], Event::MouseWheel { .. })); - } - - #[test] - fn hostile_numbers_never_produce_a_bad_zoom() { - for s in [f32::NAN, f32::INFINITY, -f32::INFINITY, 1e30, -1e30] { - for alt in [false, true] { - for notch in [0.0, -1.0, f32::NAN, 40.0] { - for (zd, animated_zoom) in [f32::NAN, 0.0, -1.0, f32::INFINITY, 1.0].into_iter().flat_map(|zd| [(zd, false), (zd, true)]) { - let i = Input { - scroll: Vec2::new(0.0, s), - raw: Vec2::new(0.0, s), - zoom_delta: zd, - alt, - shift: false, - zoom_with_wheel: !alt, - pinch_zooms: true, - animated_zoom, - notch, - }; - if let Some(Wheel::Zoom(f)) = classify(i) { - assert!(f.is_finite() && f > 0.0, "{f} from {i:?}"); - } - let si = Input { - shift: true, - zoom_with_wheel: true, - ..Input { - scroll: Vec2::new(0.0, s), - raw: Vec2::new(0.0, s), - zoom_delta: zd, - alt: false, - shift: false, - zoom_with_wheel: true, - pinch_zooms: true, - animated_zoom, - notch, - } - }; - if let Some(Wheel::SnapZoom(n)) = classify(si) { - assert!(n.abs() <= 10, "snap steps clamped: {n} from {si:?}"); - } - } - let mut ev = [wheel(Vec2::new(s, 0.5), CTRL)]; - let _ = legacy_pinch_to_zoom(&mut ev, f64::NAN, Some(f64::NAN), notch, 0.005); - let _ = legacy_pinch_to_zoom(&mut ev, 0.0, None, notch, f32::NAN); - if let Event::Zoom(f) = ev[0] { - assert!(f.is_finite() && f > 0.0, "{f}"); - } - } - } - } - } - - /// A gesture helper that runs each frame at 1/60 s spacing with Point-unit events, - /// collecting snaps, and using a specific owner ID. - fn snap_gesture(frames: Vec>, zoom_with_wheel: bool, owner: Id) -> i32 { - let ctx = Context::default(); - configure(&ctx); - let mut snaps = 0i32; - let mut frames = frames.into_iter(); - for n in 0..60 { - let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events: frames.next().unwrap_or_default(), ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), zoom_with_wheel, true, true, owner, true) { - snaps += s; - } - }); - out.textures_delta.clear(); - } - snaps - } - - #[test] - fn fractional_point_events_accumulate_across_frames() { - let quarter = Vec2::new(0.0, 10.0); - let batched = snap_gesture(vec![vec![wheel_point(Vec2::new(0.0, 40.0), Modifiers::SHIFT)]], true, Id::unique("accum-batched")); - let split = snap_gesture( - vec![ - vec![wheel_point(quarter, Modifiers::SHIFT)], - vec![wheel_point(quarter, Modifiers::SHIFT)], - vec![wheel_point(quarter, Modifiers::SHIFT)], - vec![wheel_point(quarter, Modifiers::SHIFT)], - ], - true, - Id::unique("accum-split"), - ); - assert_eq!(batched, 1, "40 points batched → 1 step"); - assert_eq!(split, 1, "4 × 10 points split → 1 step"); - } - - #[test] - fn fractional_accumulation_negative_and_horizontal() { - let neg_quarter = Vec2::new(0.0, -10.0); - let neg_split = snap_gesture( - vec![ - vec![wheel_point(neg_quarter, Modifiers::SHIFT)], - vec![wheel_point(neg_quarter, Modifiers::SHIFT)], - vec![wheel_point(neg_quarter, Modifiers::SHIFT)], - vec![wheel_point(neg_quarter, Modifiers::SHIFT)], - ], - true, - Id::unique("accum-neg"), - ); - assert_eq!(neg_split, -1, "4 × −10 points → −1 step"); - let h_quarter = Vec2::new(10.0, 0.0); - let h_split = snap_gesture( - vec![ - vec![wheel_point(h_quarter, Modifiers::SHIFT)], - vec![wheel_point(h_quarter, Modifiers::SHIFT)], - vec![wheel_point(h_quarter, Modifiers::SHIFT)], - vec![wheel_point(h_quarter, Modifiers::SHIFT)], - ], - true, - Id::unique("accum-horiz"), - ); - assert_eq!(h_split, 1, "horizontal 4 × 10 → 1 step"); - } - - #[test] - fn accumulation_handles_empty_frames_and_direction_reversal() { - let snaps = snap_gesture( - vec![ - vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], - vec![], // empty frame - vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], - vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], - vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], - ], - true, - Id::unique("accum-empty"), - ); - assert_eq!(snaps, 1, "empty frame preserves residual"); - let reversal = snap_gesture( - vec![vec![wheel_point(Vec2::new(0.0, 30.0), Modifiers::SHIFT)], vec![wheel_point(Vec2::new(0.0, -15.0), Modifiers::SHIFT)]], - true, - Id::unique("accum-reversal"), - ); - assert_eq!(reversal, 0, "30 − 15 = 15 points, below 1 notch → 0 steps"); - } - - #[test] - fn accumulation_shift_alt_without_preference() { - let shift_alt = Modifiers { shift: true, alt: true, ..Modifiers::NONE }; - let split = snap_gesture( - vec![ - vec![wheel_point(Vec2::new(0.0, 10.0), shift_alt)], - vec![wheel_point(Vec2::new(0.0, 10.0), shift_alt)], - vec![wheel_point(Vec2::new(0.0, 10.0), shift_alt)], - vec![wheel_point(Vec2::new(0.0, 10.0), shift_alt)], - ], - false, - Id::unique("accum-shift-alt"), - ); - assert_eq!(split, 1, "Shift+Alt 4 × 10 → 1 step without preference"); - } - - #[test] - fn cross_viewport_does_not_leak_residual() { - let owner_a = Id::unique("owner-a"); - let owner_b = Id::unique("owner-b"); - let ctx = Context::default(); - configure(&ctx); - let mut snaps_a = 0i32; - let mut snaps_b = 0i32; - // Frame 0: 30 points over A (hovered), B not hovered. - let raw = - RawInput { time: Some(0.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 30.0), Modifiers::SHIFT)], ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_a, true) { - snaps_a += s; - } - if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_b, false) { - snaps_b += s; - } - }); - out.textures_delta.clear(); - assert_eq!(snaps_a, 0, "A: 30 points, below 1 notch"); - assert_eq!(snaps_b, 0, "B: not hovered, nothing"); - // Frame 1: 10 points, pointer moved to B (B hovered, A not). - let raw = RawInput { - time: Some(1.0 / 60.0), - predicted_dt: 1.0 / 60.0, - events: vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], - ..Default::default() - }; - let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_a, false) { - snaps_a += s; - } - if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_b, true) { - snaps_b += s; - } - }); - out.textures_delta.clear(); - assert_eq!(snaps_b, 0, "B: only 10 points of its own, no snap"); - // Frame 2–4: 30 more points over B. - for n in 2..5 { - let raw = RawInput { - time: Some(f64::from(n) / 60.0), - predicted_dt: 1.0 / 60.0, - events: vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], - ..Default::default() - }; - let mut out = ctx.run_ui(raw, |ui| { - let _ = read(ui.ctx(), true, true, true, owner_a, false); - if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_b, true) { - snaps_b += s; - } - }); - out.textures_delta.clear(); - } - assert_eq!(snaps_b, 1, "B: 10+10+10+10 = 40 → 1 step"); - // Frame 5: switch back to A — A's residual was cleared on the viewport switch. - let raw = RawInput { - time: Some(5.0 / 60.0), - predicted_dt: 1.0 / 60.0, - events: vec![wheel_point(Vec2::new(0.0, 30.0), Modifiers::SHIFT)], - ..Default::default() - }; - let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_a, true) { - snaps_a += s; - } - let _ = read(ui.ctx(), true, true, true, owner_b, false); - }); - out.textures_delta.clear(); - assert_eq!(snaps_a, 0, "A: fresh start after switch, 30 points, no snap yet"); - } - - #[test] - fn two_reads_same_owner_same_frame_do_not_double_count() { - let owner = Id::unique("same-owner"); - let ctx = Context::default(); - configure(&ctx); - let mut total_snaps = 0i32; - let raw = - RawInput { time: Some(0.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 20.0), Modifiers::SHIFT)], ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner, true) { - total_snaps += s; - } - if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner, true) { - total_snaps += s; - } - }); - out.textures_delta.clear(); - assert_eq!(total_snaps, 0, "20 points read twice must not become 40"); - // Now add another 20 in the next frame — should snap since accumulated 20+20=40. - let raw = RawInput { - time: Some(1.0 / 60.0), - predicted_dt: 1.0 / 60.0, - events: vec![wheel_point(Vec2::new(0.0, 20.0), Modifiers::SHIFT)], - ..Default::default() - }; - let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner, true) { - total_snaps += s; - } - }); - out.textures_delta.clear(); - assert_eq!(total_snaps, 1, "20 + 20 across two frames → 1 step"); - } - - #[test] - fn accumulation_hostile_numbers() { - for dy in [1e30, -1e30, 1e-10, -1e-10] { - let snaps = snap_gesture(vec![vec![wheel_point(Vec2::new(0.0, dy), Modifiers::SHIFT)]], true, Id::unique("accum-hostile")); - assert!(snaps.abs() <= 10, "hostile {dy} clamped: {snaps}"); - } - } - - #[test] - fn line_unit_snap_still_works_with_accumulation() { - let (_, _, snaps) = gesture(vec![vec![wheel(Vec2::new(0.0, 1.0), Modifiers::SHIFT)]], true, false); - assert_eq!(snaps, 1, "Line-unit notch produces 1 step"); - let (_, _, snaps) = gesture(vec![vec![wheel(Vec2::new(0.0, -1.0), Modifiers::SHIFT)]], true, false); - assert_eq!(snaps, -1, "Line-unit notch down produces −1 step"); - } - - /// Two fingers on a touch screen: down 20 points apart, spread to 40 (a ×2 pinch), lifted. - fn touch_pinch_frames() -> Vec> { - let touch = |id: u64, phase: TouchPhase, x: f32| Event::Touch { - device_id: egui::TouchDeviceId(1), - id: egui::TouchId(id), - phase, - pos: egui::pos2(x, 50.0), - force: None, - }; - vec![ - // egui only starts a multi-touch gesture once it knows where the pointer is. - vec![Event::PointerMoved(egui::pos2(40.0, 50.0))], - vec![touch(1, TouchPhase::Start, 40.0), touch(2, TouchPhase::Start, 60.0)], - vec![touch(1, TouchPhase::Move, 30.0), touch(2, TouchPhase::Move, 70.0)], - vec![touch(1, TouchPhase::End, 30.0), touch(2, TouchPhase::End, 70.0)], - ] - } - - /// The total zoom [`read_with`] reports over `frames`, Enable Gestures set to `touch_gestures`. - fn touch_zoom(frames: Vec>, touch_gestures: bool) -> f32 { - let owner = Id::unique("test-touch"); - let ctx = Context::default(); - configure(&ctx); - let mut zoom = 1.0; - for (n, events) in (0u32..).zip(frames) { - let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::Zoom(f)) = read_with(ui.ctx(), false, true, true, owner, true, true, touch_gestures) { - zoom *= f; - } - }); - out.textures_delta.clear(); - } - zoom - } - - /// Preferences › Enhanced Controls › Enable Gestures (#204): on (the default) a two-finger - /// pinch on a touch screen zooms; off, it leaves the view alone. - #[test] - fn enable_gestures_switches_touch_screen_pinch_zoom() { - let on = touch_zoom(touch_pinch_frames(), true); - assert!((on - 2.0).abs() < 1e-4, "on: the fingers zoom ×2: {on}"); - let off = touch_zoom(touch_pinch_frames(), false); - assert_eq!(off, 1.0, "off: the fingers don't zoom"); - } - - /// Enable Gestures off only silences the touch screen: a trackpad pinch still zooms, also in a - /// frame where two fingers rest on the screen (egui's `zoom_delta` would report theirs instead). - #[test] - fn enable_gestures_off_keeps_the_trackpad_pinch() { - let zoom = touch_zoom(vec![vec![Event::Zoom(1.25)]], false); - assert!((zoom - 1.25).abs() < 1e-4, "no fingers down: {zoom}"); - let mut frames = touch_pinch_frames(); - frames[2] = vec![Event::Zoom(1.25)]; - let zoom = touch_zoom(frames, false); - assert!((zoom - 1.25).abs() < 1e-4, "fingers resting: {zoom}"); - } -} +mod tests; diff --git a/crates/ui-egui/src/wheel_nav/tests.rs b/crates/ui-egui/src/wheel_nav/tests.rs new file mode 100644 index 0000000000..2a727d2dcf --- /dev/null +++ b/crates/ui-egui/src/wheel_nav/tests.rs @@ -0,0 +1,1032 @@ +use egui::TouchPhase; + +use super::*; + +fn input(scroll: Vec2, alt: bool) -> Input { + Input { scroll, raw: scroll, zoom_delta: 1.0, alt, shift: false, zoom_with_wheel: false, pinch_zooms: true, animated_zoom: true, notch: 40.0 } +} + +fn wheel(delta: Vec2, modifiers: Modifiers) -> Event { + Event::MouseWheel { source: egui::MouseWheelSource::Unknown, unit: MouseWheelUnit::Line, delta, phase: TouchPhase::Move, modifiers } +} + +const CTRL: Modifiers = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; +const CMD: Modifiers = Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE }; + +/// Feed `events` through an egui context set up like the app's (`legacy`: the Windows pinch +/// fold on) and add up what the wheel did to the view over the following second. +/// +/// `gesture` runs with Animated Zoom off (a notch is one instant step); see [`gesture_with`]. +fn gesture(frames: Vec>, zoom_with_wheel: bool, legacy: bool) -> (Vec2, f32, i32) { + gesture_with(frames, zoom_with_wheel, legacy, false) +} + +fn gesture_with(frames: Vec>, zoom_with_wheel: bool, legacy: bool, animated_zoom: bool) -> (Vec2, f32, i32) { + let owner = Id::unique("test-gesture"); + let ctx = Context::default(); + configure(&ctx); + let (mut pan, mut zoom, mut snaps) = (Vec2::ZERO, 1.0, 0i32); + let mut frames = frames.into_iter(); + for n in 0..60 { + let mut raw = + RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events: frames.next().unwrap_or_default(), ..Default::default() }; + if legacy { + fold_legacy_pinch(&ctx, &mut raw); + } + let mut out = ctx.run_ui(raw, |ui| match read(ui.ctx(), zoom_with_wheel, true, animated_zoom, owner, true) { + Some(Wheel::Pan(d)) => pan += d, + Some(Wheel::Zoom(f)) => zoom *= f, + Some(Wheel::SnapZoom(n)) => snaps += n, + None => {} + }); + out.textures_delta.clear(); + } + (pan, zoom, snaps) +} + +fn wheel_point(delta: Vec2, modifiers: Modifiers) -> Event { + Event::MouseWheel { source: egui::MouseWheelSource::Unknown, unit: MouseWheelUnit::Point, delta, phase: TouchPhase::Move, modifiers } +} + +fn near(a: Vec2, b: Vec2) -> bool { + (a - b).length() < 0.01 +} + +/// #5721: with smoothing off a wheel notch pans the whole notch in the frame it arrives and +/// nothing after; smoothed (the default) it glides, reaching the same total over later frames. +#[test] +fn unsmoothed_wheel_pans_at_once_without_a_glide() { + let pans = |smooth: bool| -> Vec { + let owner = Id::unique("test-unsmoothed"); + let ctx = Context::default(); + configure(&ctx); + (0..30) + .map(|n| { + let events = if n == 0 { vec![wheel(Vec2::new(0.0, -1.0), Modifiers::NONE)] } else { Vec::new() }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut pan = Vec2::ZERO; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Pan(d)) = read_with(ui.ctx(), false, true, true, owner, true, smooth, true) { + pan = d; + } + }); + out.textures_delta.clear(); + pan + }) + .collect() + }; + let notch = { + let ctx = Context::default(); + configure(&ctx); + ctx.options(|o| o.input_options.line_scroll_speed) + }; + let direct = pans(false); + assert!(near(direct[0], Vec2::new(0.0, -notch)), "the whole notch at once: {:?}", direct[0]); + assert!(direct[1..].iter().all(|p| *p == Vec2::ZERO), "no glide after it"); + let smooth = pans(true); + assert!(smooth[0].y.abs() < notch - 0.5, "smoothed, the first frame moves only part of it: {:?}", smooth[0]); + assert!(smooth[1..].iter().any(|p| p.y != 0.0), "and the rest follows"); +} + +/// Interface › Enable Animations off only stops the *pan* gliding. A plain wheel that zooms +/// (Zoom with Scroll Wheel) with Animated Zoom on must still ease over the frames of a notch, +/// exactly as it does with the pan smoothing on. +#[test] +fn animated_wheel_zoom_keeps_its_eased_tail_when_pan_smoothing_is_off() { + let frames = |smooth: bool| -> Vec { + let owner = Id::unique("test-animated-zoom-unsmoothed-pan"); + let ctx = Context::default(); + configure(&ctx); + (0..60) + .map(|n| { + let events = if n == 0 { vec![wheel(Vec2::new(0.0, 1.0), Modifiers::NONE)] } else { Vec::new() }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut factor = 1.0; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Zoom(f)) = read_with(ui.ctx(), true, true, true, owner, true, smooth, true) { + factor = f; + } + }); + out.textures_delta.clear(); + factor + }) + .collect() + }; + let unsmoothed = frames(false); + assert!(unsmoothed[0] > 1.0 && unsmoothed[0] < NOTCH - 1e-3, "the first frame carries only part of it: {:?}", &unsmoothed[..4]); + assert!(unsmoothed[1..].iter().any(|f| *f > 1.0), "and the rest follows: {unsmoothed:?}"); + let product: f32 = unsmoothed.iter().product(); + assert!((product - NOTCH).abs() < 1e-4, "still x1.1 in total: {product}"); + let smoothed = frames(true); + assert!(unsmoothed.iter().zip(&smoothed).all(|(a, b)| (a - b).abs() < 1e-6), "same pacing as with pan smoothing on"); +} + +#[test] +fn plain_scroll_pans() { + assert_eq!(classify(input(Vec2::new(3.0, -40.0), false)), Some(Wheel::Pan(Vec2::new(3.0, -40.0)))); + assert_eq!(classify(input(Vec2::ZERO, false)), None); +} + +#[test] +fn alt_scroll_zooms_ten_percent_per_notch() { + let Some(Wheel::Zoom(f)) = classify(input(Vec2::new(0.0, 40.0), true)) else { panic!("zoom") }; + assert!((f - 1.1).abs() < 1e-5, "{f}"); + let Some(Wheel::Zoom(f)) = classify(input(Vec2::new(0.0, -40.0), true)) else { panic!("zoom") }; + assert!((f - 1.0 / 1.1).abs() < 1e-5, "{f}"); + // Two notches in one frame are two steps, x1.1 each. + let Some(Wheel::Zoom(f)) = classify(input(Vec2::new(0.0, 80.0), true)) else { panic!("zoom") }; + assert!((f - 1.21).abs() < 1e-4, "{f}"); +} + +/// Animated Zoom off: a notch is one instant step, and egui's smoothed tail does nothing. +#[test] +fn a_notch_zooms_the_frame_it_arrives_and_its_smoothed_tail_does_nothing() { + // egui keeps feeding a smoothed delta for several frames after the wheel event. Zooming + // must not follow it (that would ease the zoom), nor turn it into a pan. + let off = |i: Input| Input { animated_zoom: false, ..i }; + let tail = off(Input { raw: Vec2::ZERO, ..input(Vec2::new(0.0, 12.0), true) }); + assert_eq!(classify(tail), None); + let tail = off(Input { raw: Vec2::ZERO, zoom_with_wheel: true, ..input(Vec2::new(0.0, 12.0), false) }); + assert_eq!(classify(tail), None); + // The frame the notch arrives carries it whole, whatever the smoothed delta is. + let arrival = off(Input { scroll: Vec2::new(0.0, 12.0), raw: Vec2::new(0.0, 40.0), ..input(Vec2::ZERO, true) }); + assert!(matches!(classify(arrival), Some(Wheel::Zoom(f)) if (f - 1.1).abs() < 1e-5)); + // Plain scrolling without the preference still pans from the smoothed delta. + let pan = off(Input { raw: Vec2::ZERO, ..input(Vec2::new(0.0, 12.0), false) }); + assert_eq!(classify(pan), Some(Wheel::Pan(Vec2::new(0.0, 12.0)))); +} + +/// Animated Zoom on: the zoom follows egui's smoothed delta over the frames of a notch, and +/// never turns that tail into a pan. +#[test] +fn animated_zoom_follows_the_smoothed_tail_of_a_notch() { + let tail = Input { raw: Vec2::ZERO, ..input(Vec2::new(0.0, 12.0), true) }; + assert!(matches!(classify(tail), Some(Wheel::Zoom(f)) if f > 1.0)); + let tail = Input { raw: Vec2::ZERO, zoom_with_wheel: true, ..input(Vec2::new(0.0, 12.0), false) }; + assert!(matches!(classify(tail), Some(Wheel::Zoom(f)) if f > 1.0)); + // The size of the step comes from the smoothed delta, not the raw one. + let part = Input { scroll: Vec2::new(0.0, 20.0), raw: Vec2::new(0.0, 40.0), ..input(Vec2::ZERO, true) }; + assert!(matches!(classify(part), Some(Wheel::Zoom(f)) if (f - 1.1f32.powf(0.5)).abs() < 1e-5)); + // Plain scrolling without the preference still pans from the smoothed delta. + let pan = Input { raw: Vec2::ZERO, ..input(Vec2::new(0.0, 12.0), false) }; + assert_eq!(classify(pan), Some(Wheel::Pan(Vec2::new(0.0, 12.0)))); + // ⇧ + snap zoom stays on the wheel events and instant, in both modes. + for animated_zoom in [false, true] { + let tail = Input { shift: true, zoom_with_wheel: true, raw: Vec2::ZERO, animated_zoom, ..input(Vec2::new(12.0, 0.0), false) }; + assert_eq!(classify(tail), None, "animated_zoom {animated_zoom}"); + let snap = Input { shift: true, zoom_with_wheel: true, raw: Vec2::new(0.0, 40.0), animated_zoom, ..input(Vec2::new(0.0, 12.0), false) }; + assert_eq!(classify(snap), Some(Wheel::SnapZoom(1)), "animated_zoom {animated_zoom}"); + } +} + +/// The factor of every frame of one notch, through a real egui context (60 frames at 60 fps). +fn zoom_frames(modifiers: Modifiers, zoom_with_wheel: bool, animated_zoom: bool) -> Vec { + let owner = Id::unique("test-zoom-frames"); + let ctx = Context::default(); + configure(&ctx); + (0..60) + .map(|n| { + let events = if n == 0 { vec![wheel(Vec2::new(0.0, 1.0), modifiers)] } else { Vec::new() }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut factor = 1.0; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Zoom(f)) = read(ui.ctx(), zoom_with_wheel, true, animated_zoom, owner, true) { + factor = f; + } + }); + out.textures_delta.clear(); + factor + }) + .collect() +} + +/// The property the eased zoom relies on: however egui spreads a notch over frames, the +/// factors of those frames multiply to exactly ×1.1 (and ×1/1.1 for a notch the other way). +#[test] +fn the_eased_frames_of_one_notch_multiply_to_ten_percent() { + for (modifiers, zoom_with_wheel) in [(Modifiers::ALT, false), (Modifiers::NONE, true)] { + let frames = zoom_frames(modifiers, zoom_with_wheel, true); + assert!(frames.iter().all(|f| f.is_finite() && *f >= 1.0), "{frames:?}"); + assert!(frames.iter().filter(|f| **f != 1.0).count() > 1, "eased over several frames: {frames:?}"); + let product: f32 = frames.iter().product(); + assert!((product - NOTCH).abs() < 1e-4, "{modifiers:?} zoom_with_wheel {zoom_with_wheel}: {product} from {frames:?}"); + } + // The other way round: ×1/1.1. + let owner = Id::unique("test-zoom-frames-out"); + let ctx = Context::default(); + configure(&ctx); + let mut product = 1.0f32; + for n in 0..60 { + let events = if n == 0 { vec![wheel(Vec2::new(0.0, -1.0), Modifiers::ALT)] } else { Vec::new() }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Zoom(f)) = read(ui.ctx(), false, true, true, owner, true) { + product *= f; + } + }); + out.textures_delta.clear(); + } + assert!((product - 1.0 / NOTCH).abs() < 1e-4, "{product}"); +} + +/// Animated Zoom changes the pacing of a notch, never its size: off, the whole ×1.1 lands in +/// the frame the notch arrives and nothing follows; on, that frame carries only part of it. +#[test] +fn animated_zoom_changes_the_pacing_of_a_notch_not_its_size() { + for (modifiers, zoom_with_wheel) in [(Modifiers::ALT, false), (Modifiers::NONE, true)] { + let instant = zoom_frames(modifiers, zoom_with_wheel, false); + assert!((instant[0] - NOTCH).abs() < 1e-5, "the whole notch at once: {:?}", &instant[..4]); + assert!(instant[1..].iter().all(|f| *f == 1.0), "no tail after it: {instant:?}"); + let eased = zoom_frames(modifiers, zoom_with_wheel, true); + assert!(eased[0] > 1.0 && eased[0] < NOTCH - 1e-3, "the first frame carries only part of it: {:?}", &eased[..4]); + assert!(eased[1..].iter().any(|f| *f > 1.0), "and the rest follows"); + } +} + +/// Animated Zoom is only about the wheel zoom: ⇧ snap zoom and plain scrolling are the same +/// in both modes. +#[test] +fn animated_zoom_leaves_snap_zoom_and_panning_alone() { + let notch = Vec2::new(0.0, 1.0); + let shift_alt = Modifiers { shift: true, alt: true, ..Modifiers::NONE }; + for animated_zoom in [false, true] { + let (pan, zoom, snaps) = gesture_with(vec![vec![wheel(notch, shift_alt)]], false, false, animated_zoom); + assert!(pan == Vec2::ZERO && zoom == 1.0 && snaps == 1, "⇧ + ⌥: {pan:?} {zoom} {snaps}"); + let (pan, zoom, snaps) = gesture_with(vec![vec![wheel(notch, Modifiers::NONE)]], false, false, animated_zoom); + assert!(near(pan, Vec2::new(0.0, 40.0)) && zoom == 1.0 && snaps == 0, "plain wheel pans: {pan:?} {zoom} {snaps}"); + // A notch zooms ×1.1 in total in either mode. + let (pan, zoom, _) = gesture_with(vec![vec![wheel(notch, Modifiers::ALT)]], false, false, animated_zoom); + assert!(pan == Vec2::ZERO && (zoom - NOTCH).abs() < 1e-4, "animated_zoom {animated_zoom}: {pan:?} {zoom}"); + } +} + +/// A pan notch still gliding when an ⌥ notch arrives (and the same the other way round with +/// Zoom with Scroll Wheel): the zoom is that one notch's ×1.1, not the sum of both tails. +#[test] +fn a_pan_tail_does_not_leak_into_the_animated_zoom() { + let notch = Vec2::new(0.0, 1.0); + // Wheel pans, ⌥ zooms: plain notch, then ⌥ notch one frame later. + let frames = vec![vec![wheel(notch, Modifiers::NONE)], vec![wheel(notch, Modifiers::ALT)]]; + let (pan, zoom, snaps) = gesture_with(frames, false, false, true); + assert!((zoom - NOTCH).abs() < 1e-4, "only the ⌥ notch zooms: {zoom}"); + assert!(pan.y > 0.0 && pan.y < 40.0 && snaps == 0, "the plain notch only panned its first frame: {pan:?} {snaps}"); + // Wheel zooms, ⌥ pans: ⌥ notch, then plain notch. + let frames = vec![vec![wheel(notch, Modifiers::ALT)], vec![wheel(notch, Modifiers::NONE)]]; + let (_, zoom, snaps) = gesture_with(frames, true, false, true); + assert!((zoom - NOTCH).abs() < 1e-4, "only the plain notch zooms: {zoom}"); + assert_eq!(snaps, 0); +} + +/// The zoom factor of each of `frames` frames with Animated Zoom on and ⌥ zooming. `time` gives a +/// frame's timestamp and `hovered` whether the owner is hovered in it. +fn run_zoom(frames: u32, events: impl Fn(u32) -> Vec, time: impl Fn(u32) -> f64, hovered: impl Fn(u32) -> bool) -> Vec { + let owner = Id::unique("test-run-zoom"); + let ctx = Context::default(); + configure(&ctx); + (0..frames) + .map(|n| { + let raw = RawInput { time: Some(time(n)), predicted_dt: 1.0 / 60.0, events: events(n), ..Default::default() }; + let mut factor = 1.0; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Zoom(f)) = read(ui.ctx(), false, true, true, owner, hovered(n)) { + factor = f; + } + }); + out.textures_delta.clear(); + factor + }) + .collect() +} + +/// A slow frame in the middle of an eased notch (a big image redrawing) must not drop what is +/// left of it: the notch still adds up to exactly ×1.1. +#[test] +fn a_slow_frame_does_not_cut_an_eased_notch_short() { + let notch = Vec2::new(0.0, 1.0); + let time = |n: u32| if n == 0 { 0.0 } else { 0.7 + f64::from(n - 1) / 60.0 }; + let frames = run_zoom(60, |n| if n == 0 { vec![wheel(notch, Modifiers::ALT)] } else { Vec::new() }, time, |_| true); + let product: f32 = frames.iter().product(); + assert!((product - NOTCH).abs() < 1e-4, "still x1.1 in total: {product} from {frames:?}"); +} + +/// What is left of an eased notch when the pointer leaves the viewport is dropped: a notch +/// made after it comes back is ×1.1 on its own, not ×1.1 plus the old remainder. +#[test] +fn an_unfinished_notch_is_not_carried_into_a_notch_after_the_pointer_left() { + let notch = Vec2::new(0.0, 1.0); + let events = |n: u32| if n == 0 || n == 40 { vec![wheel(notch, Modifiers::ALT)] } else { Vec::new() }; + let frames = run_zoom(100, events, |n| f64::from(n) / 60.0, |n| !(1..30).contains(&n)); + let first: f32 = frames[..40].iter().product(); + assert!(first > 1.0 && first < NOTCH - 1e-3, "the first notch was left unfinished: {first}"); + let second: f32 = frames[40..].iter().product(); + assert!((second - NOTCH).abs() < 1e-4, "the second notch is ×1.1 on its own: {second}"); +} + +/// Zoom with Scroll Wheel + Animated Zoom (the defaults of both): ⌘/Ctrl + wheel still scrolls +/// sideways, as it does with Animated Zoom off. +#[test] +fn animated_zoom_keeps_ctrl_wheel_sideways_scroll_with_zoom_with_wheel() { + let (pan, zoom, snaps) = gesture_with(vec![vec![wheel(Vec2::new(0.0, 1.0), CTRL)]], true, false, true); + assert!(near(pan, Vec2::new(40.0, 0.0)) && zoom == 1.0 && snaps == 0, "{pan:?} {zoom} {snaps}"); +} + +/// Shift snap zoom interrupting an unfinished animated notch drops that notch's residual: a +/// continuous zoom started right after Shift is released is its own ×1.1 and nothing more. +#[test] +fn shift_snap_zoom_drops_the_unfinished_eased_notch() { + let notch = Vec2::new(0.0, 1.0); + let shift_alt = Modifiers { shift: true, ..Modifiers::ALT }; + let owner = Id::unique("test-snap-interrupts-ease"); + let ctx = Context::default(); + configure(&ctx); + let (mut zoom, mut zoom_after_first, mut snaps) = (1.0f32, 1.0f32, 0i32); + for n in 0..60u32 { + // ⌥ notch (eases), ⇧⌥ notch (snap zoom takes over), then ⌥ notch again within 0.5 s. + let events = match n { + 0 | 2 => vec![wheel(notch, Modifiers::ALT)], + 1 => vec![wheel(notch, shift_alt)], + _ => Vec::new(), + }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| match read(ui.ctx(), false, true, true, owner, true) { + Some(Wheel::Zoom(f)) => zoom *= f, + Some(Wheel::SnapZoom(s)) => snaps += s, + _ => {} + }); + out.textures_delta.clear(); + if n == 0 { + zoom_after_first = zoom; + } + } + assert_eq!(snaps, 1); + let second = zoom / zoom_after_first; + assert!((second - NOTCH).abs() < 1e-4, "the second ⌥ notch zooms ×1.1 on its own: {second}"); +} + +/// A trackpad's ⌥ + two-finger scroll comes in points and is already smooth: egui leaves it +/// unsmoothed because smoothing adds latency, so Animated Zoom must not ease it either. Each +/// frame zooms by its own events, at once. +#[test] +fn animated_zoom_does_not_ease_a_trackpad() { + let frames = + run_zoom(30, |n| if n == 0 { vec![wheel_point(Vec2::new(0.0, 4.0), Modifiers::ALT)] } else { Vec::new() }, |n| f64::from(n) / 60.0, |_| true); + assert!((frames[0] - NOTCH.powf(0.1)).abs() < 1e-6, "all of it in the frame it arrives: {:?}", &frames[..4]); + assert!(frames[1..].iter().all(|f| *f == 1.0), "no tail after it: {frames:?}"); +} + +/// Zoom with Scroll Wheel + Animated Zoom with Enable Animations off: the wheel zooms eased, but +/// a sideways wheel still pans without a glide (#5721), all of it in the frame it turns. +#[test] +fn animated_zoom_keeps_the_sideways_wheel_unsmoothed_with_animations_off() { + let owner = Id::unique("test-sideways-unsmoothed"); + let ctx = Context::default(); + configure(&ctx); + let pans: Vec = (0..30) + .map(|n| { + let events = if n == 0 { vec![wheel(Vec2::new(1.0, 0.0), Modifiers::NONE)] } else { Vec::new() }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut pan = Vec2::ZERO; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Pan(d)) = read_with(ui.ctx(), true, true, true, owner, true, false, true) { + pan = d; + } + }); + out.textures_delta.clear(); + pan + }) + .collect(); + assert!(near(pans[0], Vec2::new(40.0, 0.0)), "the whole notch at once: {:?}", &pans[..4]); + assert!(pans[1..].iter().all(|p| *p == Vec2::ZERO), "no glide after it: {pans:?}"); +} + +/// A diagonal point step with ⌥ is measured as egui measures it, folded onto one axis: (5, 5) +/// is a 10-point step, which egui smooths, so Animated Zoom eases it. +#[test] +fn a_diagonal_alt_point_step_is_measured_like_egui() { + let frames = + run_zoom(60, |n| if n == 0 { vec![wheel_point(Vec2::new(5.0, 5.0), Modifiers::ALT)] } else { Vec::new() }, |n| f64::from(n) / 60.0, |_| true); + assert!(frames[0] < NOTCH.powf(0.25) - 1e-4 && frames[1] > 1.0, "eased: {:?}", &frames[..4]); +} + +/// A touch whose end nobody read (no canvas in that pass, e.g. the last document closed +/// during a trackpad scroll) must not leave later mouse notches un-eased. +#[test] +fn a_touch_end_nobody_read_does_not_stick() { + let owner = Id::unique("test-touch-unread-end"); + let ctx = Context::default(); + configure(&ctx); + let point = |phase: TouchPhase| Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: MouseWheelUnit::Point, + delta: Vec2::ZERO, + phase, + modifiers: Modifiers::ALT, + }; + let mut first = 1.0; + for n in 0..10u32 { + let events = match n { + 0 => vec![point(TouchPhase::Start)], + 2 => vec![point(TouchPhase::End)], + 5 => vec![wheel(Vec2::new(0.0, 1.0), Modifiers::ALT)], + _ => Vec::new(), + }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + // Frames 2-3: nothing reads the wheel. + if !(2..4).contains(&n) + && let Some(Wheel::Zoom(f)) = read(ui.ctx(), false, true, true, owner, true) + && n == 5 + { + first = f; + } + }); + out.textures_delta.clear(); + } + assert!(first > 1.0 && first < NOTCH - 1e-3, "the notch is eased: {first}"); +} + +/// Quick back-and-forth wheeling still lands on whole ×1.1 steps: three notches in and one +/// out a frame later is ×1.1², whatever was still easing. +#[test] +fn a_quick_notch_back_nets_out() { + for back_at in [1, 3] { + let events = |n: u32| match n { + 0 => vec![wheel(Vec2::new(0.0, 3.0), Modifiers::ALT)], + n if n == back_at => vec![wheel(Vec2::new(0.0, -1.0), Modifiers::ALT)], + _ => Vec::new(), + }; + let total: f32 = run_zoom(60, events, |n| f64::from(n) / 60.0, |_| true).iter().product(); + assert!((total - NOTCH * NOTCH).abs() < 1e-4, "back at frame {back_at}: {total}"); + } +} + +/// A browser reports a mouse notch as a big pixel step (about 100 points in Chrome), which +/// egui smooths like a notch: Animated Zoom eases it too. Within a trackpad touch (egui's +/// `InTouch`) even big point steps zoom at once. +#[test] +fn animated_zoom_eases_big_pixel_steps_but_not_a_touch() { + let point = |dy: f32, phase: TouchPhase| Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: MouseWheelUnit::Point, + delta: Vec2::new(0.0, dy), + phase, + modifiers: Modifiers::ALT, + }; + let browser = run_zoom(60, |n| if n == 0 { vec![point(100.0, TouchPhase::Move)] } else { Vec::new() }, |n| f64::from(n) / 60.0, |_| true); + assert!(browser[0] > 1.0 && browser[0] < NOTCH.powf(2.5) - 1e-3, "eased: {:?}", &browser[..4]); + let total: f32 = browser.iter().product(); + assert!((total - NOTCH.powf(2.5)).abs() < 1e-3, "{total}"); + let events = |n: u32| match n { + 0 => vec![point(0.0, TouchPhase::Start)], + 1 => vec![point(20.0, TouchPhase::Move)], + _ => Vec::new(), + }; + let touch = run_zoom(30, events, |n| f64::from(n) / 60.0, |_| true); + assert!((touch[1] - NOTCH.powf(0.5)).abs() < 1e-5, "at once: {:?}", &touch[..4]); + assert!(touch[2..].iter().all(|f| *f == 1.0), "no tail: {touch:?}"); +} + +#[test] +fn pinch_zooms() { + let i = Input { zoom_delta: 1.2, ..input(Vec2::ZERO, false) }; + assert_eq!(classify(i), Some(Wheel::Zoom(1.2))); + // The pinch wins over Alt. + let i = Input { zoom_delta: 0.8, ..input(Vec2::new(0.0, 40.0), true) }; + assert_eq!(classify(i), Some(Wheel::Zoom(0.8))); +} + +/// Preferences › Enhanced Controls › Zoom with Trackpad Pinch off: the pinch is ignored, and +/// a scroll in the same frame pans as it would without a pinch. +#[test] +fn the_pinch_preference_switches_pinch_zooming() { + let i = Input { zoom_delta: 1.2, pinch_zooms: false, ..input(Vec2::ZERO, false) }; + assert_eq!(classify(i), None); + let i = Input { zoom_delta: 1.2, pinch_zooms: false, ..input(Vec2::new(0.0, 12.0), false) }; + assert_eq!(classify(i), Some(Wheel::Pan(Vec2::new(0.0, 12.0)))); + // On (the default) the pinch still zooms. + let i = Input { zoom_delta: 1.2, pinch_zooms: true, ..input(Vec2::ZERO, false) }; + assert_eq!(classify(i), Some(Wheel::Zoom(1.2))); +} + +/// The Windows pinch fold follows the preference too: off, the Ctrl + wheel fractions stay +/// wheel events (which egui folds into a sideways scroll). +#[test] +fn the_windows_pinch_fold_follows_the_preference() { + use eframe::App as _; + if !cfg!(target_os = "windows") { + return; + } + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = Context::default(); + let event = || Event::MouseWheel { + unit: MouseWheelUnit::Line, + delta: egui::vec2(0.0, 0.25), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: Modifiers { ctrl: true, command: true, ..Modifiers::NONE }, + }; + let mut raw = RawInput { time: Some(1.0), events: vec![event()], ..Default::default() }; + app.raw_input_hook(&ctx, &mut raw); + assert!(matches!(raw.events[0], Event::Zoom(_)), "the fraction is a pinch: {:?}", raw.events[0]); + app.run("prefs.set", serde_json::json!({"path": "enhancedControls.zoomWithTrackpadPinch", "value": false})).unwrap(); + let mut raw = RawInput { time: Some(2.0), events: vec![event()], ..Default::default() }; + app.raw_input_hook(&ctx, &mut raw); + assert!(matches!(raw.events[0], Event::MouseWheel { .. }), "off: it stays a wheel event: {:?}", raw.events[0]); +} + +#[test] +fn zoom_with_scroll_wheel_preference_swaps_wheel_and_alt_wheel() { + let pref = |scroll, alt| Input { zoom_with_wheel: true, ..input(scroll, alt) }; + let Some(Wheel::Zoom(f)) = classify(pref(Vec2::new(0.0, 40.0), false)) else { panic!("zoom") }; + assert!((f - 1.1).abs() < 1e-5, "{f}"); + assert_eq!(classify(pref(Vec2::new(0.0, 40.0), true)), Some(Wheel::Pan(Vec2::new(0.0, 40.0))), "⌥ + wheel scrolls"); + assert_eq!(classify(pref(Vec2::new(40.0, 0.0), false)), Some(Wheel::Pan(Vec2::new(40.0, 0.0))), "sideways still scrolls"); +} + +#[test] +fn shift_scroll_snaps_to_zoom_ladder_with_preference() { + let snap = |dy: f32| Input { shift: true, zoom_with_wheel: true, ..input(Vec2::new(0.0, dy), false) }; + assert_eq!(classify(snap(40.0)), Some(Wheel::SnapZoom(1)), "one notch up → +1 step"); + assert_eq!(classify(snap(-40.0)), Some(Wheel::SnapZoom(-1)), "one notch down → −1 step"); + assert_eq!(classify(snap(80.0)), Some(Wheel::SnapZoom(2)), "two notches → +2 steps"); + assert_eq!(classify(snap(0.0)), None, "no scroll → nothing"); + // Some systems deliver Shift+wheel as horizontal (delta in x, y = 0). + let snap_h = |dx: f32| Input { shift: true, zoom_with_wheel: true, raw: Vec2::new(dx, 0.0), ..input(Vec2::new(dx, 0.0), false) }; + assert_eq!(classify(snap_h(40.0)), Some(Wheel::SnapZoom(1)), "horizontal notch → +1 step"); + assert_eq!(classify(snap_h(-40.0)), Some(Wheel::SnapZoom(-1)), "horizontal notch down → −1 step"); +} + +#[test] +fn shift_scroll_tail_does_not_snap_or_pan() { + let tail = Input { shift: true, zoom_with_wheel: true, raw: Vec2::ZERO, ..input(Vec2::new(12.0, 0.0), false) }; + assert_eq!(classify(tail), None, "smoothed tail of ⇧ + scroll produces nothing"); +} + +#[test] +fn shift_alt_scroll_snaps_without_preference() { + let snap = |dy: f32| Input { shift: true, ..input(Vec2::new(0.0, dy), true) }; + assert_eq!(classify(snap(40.0)), Some(Wheel::SnapZoom(1)), "⇧ + ⌥ + notch up → +1 step"); + assert_eq!(classify(snap(-40.0)), Some(Wheel::SnapZoom(-1)), "⇧ + ⌥ + notch down → −1 step"); + assert_eq!(classify(snap(0.0)), None, "no scroll → nothing"); +} + +#[test] +fn shift_only_without_zoom_with_wheel_does_not_snap() { + let i = Input { shift: true, zoom_with_wheel: false, ..input(Vec2::new(0.0, 40.0), false) }; + assert_eq!(classify(i), Some(Wheel::Pan(Vec2::new(0.0, 40.0))), "⇧ alone without the preference: no zoom"); +} + +#[test] +fn shift_scroll_snaps_through_egui_context() { + let notch = Vec2::new(0.0, 1.0); + // Shift + wheel with zoom_with_wheel on. + let (pan, zoom, snaps) = gesture(vec![vec![wheel(notch, Modifiers::SHIFT)]], true, false); + assert_eq!(snaps, 1, "⇧ + wheel with zoom_with_wheel → snap"); + assert!(pan == Vec2::ZERO, "no pan: {pan:?}"); + assert_eq!(zoom, 1.0, "no continuous zoom: {zoom}"); + let (_, _, snaps) = gesture(vec![vec![wheel(-notch, Modifiers::SHIFT)]], true, false); + assert_eq!(snaps, -1, "⇧ + wheel down → snap out"); + // Some systems deliver Shift+wheel as horizontal (delta in x, y = 0). + let h_notch = Vec2::new(1.0, 0.0); + let (pan, zoom, snaps) = gesture(vec![vec![wheel(h_notch, Modifiers::SHIFT)]], true, false); + assert_eq!(snaps, 1, "⇧ + horizontal wheel with zoom_with_wheel → snap"); + assert!(pan == Vec2::ZERO, "no pan: {pan:?}"); + assert_eq!(zoom, 1.0, "no continuous zoom: {zoom}"); + // Shift + Alt + wheel without the preference. + let shift_alt = Modifiers { shift: true, alt: true, ..Modifiers::NONE }; + let (pan, zoom, snaps) = gesture(vec![vec![wheel(notch, shift_alt)]], false, false); + assert_eq!(snaps, 1, "⇧ + ⌥ + wheel → snap"); + assert!(pan == Vec2::ZERO, "no pan: {pan:?}"); + assert_eq!(zoom, 1.0, "no continuous zoom: {zoom}"); +} + +#[test] +fn each_modifier_maps_like_photoshop() { + let notch = Vec2::new(0.0, 1.0); + let one = |m: Modifiers| gesture(vec![vec![wheel(notch, m)]], false, false); + let (pan, zoom, _) = one(Modifiers::NONE); + assert!(near(pan, Vec2::new(0.0, 40.0)) && zoom == 1.0, "wheel scrolls vertically: {pan:?} {zoom}"); + for m in [Modifiers::SHIFT, CTRL, CMD, Modifiers::CTRL] { + let (pan, zoom, _) = one(m); + assert!(near(pan, Vec2::new(40.0, 0.0)) && zoom == 1.0, "{m:?} + wheel scrolls sideways: {pan:?} {zoom}"); + } + let (pan, zoom, _) = one(Modifiers::ALT); + assert!(pan == Vec2::ZERO && (zoom - 1.1).abs() < 1e-4, "⌥ + wheel zooms 10%, at once: {pan:?} {zoom}"); + // Zoom with Scroll Wheel on: swapped. + let (pan, zoom, _) = gesture(vec![vec![wheel(notch, Modifiers::ALT)]], true, false); + assert!(near(pan, Vec2::new(0.0, 40.0)) && zoom == 1.0, "{pan:?} {zoom}"); + let (pan, zoom, _) = gesture(vec![vec![wheel(notch, Modifiers::NONE)]], true, false); + assert!(pan == Vec2::ZERO && (zoom - 1.1).abs() < 1e-4, "{pan:?} {zoom}"); + let (pan, zoom, _) = gesture(vec![vec![wheel(notch, CTRL)]], true, false); + assert!(near(pan, Vec2::new(40.0, 0.0)) && zoom == 1.0, "⌘/Ctrl + wheel still scrolls sideways: {pan:?} {zoom}"); +} + +#[test] +fn pinch_zooms_and_ctrl_wheel_pans() { + // macOS trackpad and browsers: the pinch is its own event. + let (pan, zoom, _) = gesture(vec![vec![Event::Zoom(1.1)], vec![Event::Zoom(1.1)]], false, false); + assert!(pan == Vec2::ZERO && (zoom - 1.21).abs() < 1e-4, "{pan:?} {zoom}"); + // Windows: a touchpad pinch is Ctrl + wheel in fractions of a notch, a mouse wheel whole notches. + let (pan, zoom, _) = gesture(vec![vec![wheel(Vec2::new(0.0, 0.25), CTRL)], vec![wheel(Vec2::new(0.0, 0.5), CTRL)]], false, true); + let speed = egui::InputOptions::default().scroll_zoom_speed; + assert!(pan == Vec2::ZERO && (zoom - (speed * 40.0 * 0.75).exp()).abs() < 1e-4, "the pinch zooms: {pan:?} {zoom}"); + let (pan, zoom, _) = gesture(vec![vec![wheel(Vec2::new(0.0, 1.0), CTRL)]], false, true); + assert!(near(pan, Vec2::new(40.0, 0.0)) && zoom == 1.0, "Ctrl + mouse wheel scrolls sideways: {pan:?} {zoom}"); +} + +#[test] +fn linux_wayland_point_unit_pinch_keeps_mouse_notches_for_sideways_scroll() { + // Some Wayland compositors report fractional Ctrl-wheel pinch steps in points + // rather than line units. The delta must not be multiplied by notch twice. + let mut point = [Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: MouseWheelUnit::Point, + delta: Vec2::new(0.0, 8.0), + phase: TouchPhase::Move, + modifiers: CTRL, + }]; + assert_eq!(legacy_pinch_to_zoom(&mut point, 1.0, None, 40.0, 0.005), Some(1.0)); + assert!(matches!(point[0], Event::Zoom(f) if (f - (8.0f32 * 0.005).exp()).abs() < 1e-5)); + let mut wheel_only = [wheel(Vec2::new(0.0, 1.0), CTRL)]; + assert_eq!(legacy_pinch_to_zoom(&mut wheel_only, 2.0, Some(1.0), 40.0, 0.005), Some(1.0)); + assert!(matches!(wheel_only[0], Event::MouseWheel { .. }), "whole mouse notch is not a pinch"); +} + +#[test] +fn native_pinch_is_not_zoomed_twice_when_ctrl_wheel_arrives_in_the_same_frame() { + let (_, zoom, _) = gesture(vec![vec![Event::Zoom(1.2), wheel(Vec2::new(0.0, 0.25), CTRL)]], false, true); + assert!((zoom - 1.2).abs() < 1e-4, "native zoom must win over fallback: {zoom}"); +} + +#[test] +fn native_pinch_resets_legacy_gesture_continuation() { + let ctx = Context::default(); + let mut legacy = RawInput { time: Some(1.0), events: vec![wheel(Vec2::new(0.0, 0.25), CTRL)], ..Default::default() }; + fold_legacy_pinch(&ctx, &mut legacy); + assert!(matches!(legacy.events[0], Event::Zoom(_))); + + // Native magnification takes over before the synthetic gesture times out. + let mut native = RawInput { time: Some(1.1), events: vec![Event::Zoom(1.1), wheel(Vec2::new(0.0, 0.25), CTRL)], ..Default::default() }; + fold_legacy_pinch(&ctx, &mut native); + assert!(matches!(native.events[0], Event::Zoom(f) if (f - 1.1).abs() < 1e-5)); + assert!(matches!(native.events[1], Event::MouseWheel { .. })); + + // A notched mouse scroll must no longer inherit the previous pinch. + let mut notch = RawInput { time: Some(1.12), events: vec![wheel(Vec2::new(0.0, 1.0), CTRL)], ..Default::default() }; + fold_legacy_pinch(&ctx, &mut notch); + assert!(matches!(notch.events[0], Event::MouseWheel { .. })); +} + +#[test] +fn a_whole_notch_inside_a_pinch_stays_a_pinch() { + let mut ev = [wheel(Vec2::new(0.0, 0.5), CTRL)]; + let t = legacy_pinch_to_zoom(&mut ev, 1.0, None, 40.0, 0.005); + assert_eq!(t, Some(1.0)); + assert!(matches!(ev[0], Event::Zoom(f) if (f - 0.1f32.exp()).abs() < 1e-5), "{ev:?}"); + // The next step lands on a whole notch: still the pinch. + let mut ev = [wheel(Vec2::new(0.0, -1.0), CTRL)]; + assert_eq!(legacy_pinch_to_zoom(&mut ev, 1.1, t, 40.0, 0.005), Some(1.1)); + assert!(matches!(ev[0], Event::Zoom(f) if f < 1.0), "{ev:?}"); + // Long after: a mouse wheel notch, untouched. + let mut ev = [wheel(Vec2::new(0.0, -1.0), CTRL)]; + assert_eq!(legacy_pinch_to_zoom(&mut ev, 2.0, Some(1.1), 40.0, 0.005), Some(1.1)); + assert!(matches!(ev[0], Event::MouseWheel { .. })); + // Without Ctrl nothing is a pinch. + let mut ev = [wheel(Vec2::new(0.0, 0.5), Modifiers::NONE)]; + assert_eq!(legacy_pinch_to_zoom(&mut ev, 2.0, None, 40.0, 0.005), None); + assert!(matches!(ev[0], Event::MouseWheel { .. })); +} + +#[test] +fn hostile_numbers_never_produce_a_bad_zoom() { + for s in [f32::NAN, f32::INFINITY, -f32::INFINITY, 1e30, -1e30] { + for alt in [false, true] { + for notch in [0.0, -1.0, f32::NAN, 40.0] { + for (zd, animated_zoom) in [f32::NAN, 0.0, -1.0, f32::INFINITY, 1.0].into_iter().flat_map(|zd| [(zd, false), (zd, true)]) { + let i = Input { + scroll: Vec2::new(0.0, s), + raw: Vec2::new(0.0, s), + zoom_delta: zd, + alt, + shift: false, + zoom_with_wheel: !alt, + pinch_zooms: true, + animated_zoom, + notch, + }; + if let Some(Wheel::Zoom(f)) = classify(i) { + assert!(f.is_finite() && f > 0.0, "{f} from {i:?}"); + } + let si = Input { + shift: true, + zoom_with_wheel: true, + ..Input { + scroll: Vec2::new(0.0, s), + raw: Vec2::new(0.0, s), + zoom_delta: zd, + alt: false, + shift: false, + zoom_with_wheel: true, + pinch_zooms: true, + animated_zoom, + notch, + } + }; + if let Some(Wheel::SnapZoom(n)) = classify(si) { + assert!(n.abs() <= 10, "snap steps clamped: {n} from {si:?}"); + } + } + let mut ev = [wheel(Vec2::new(s, 0.5), CTRL)]; + let _ = legacy_pinch_to_zoom(&mut ev, f64::NAN, Some(f64::NAN), notch, 0.005); + let _ = legacy_pinch_to_zoom(&mut ev, 0.0, None, notch, f32::NAN); + if let Event::Zoom(f) = ev[0] { + assert!(f.is_finite() && f > 0.0, "{f}"); + } + } + } + } +} + +/// A gesture helper that runs each frame at 1/60 s spacing with Point-unit events, +/// collecting snaps, and using a specific owner ID. +fn snap_gesture(frames: Vec>, zoom_with_wheel: bool, owner: Id) -> i32 { + let ctx = Context::default(); + configure(&ctx); + let mut snaps = 0i32; + let mut frames = frames.into_iter(); + for n in 0..60 { + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events: frames.next().unwrap_or_default(), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), zoom_with_wheel, true, true, owner, true) { + snaps += s; + } + }); + out.textures_delta.clear(); + } + snaps +} + +#[test] +fn fractional_point_events_accumulate_across_frames() { + let quarter = Vec2::new(0.0, 10.0); + let batched = snap_gesture(vec![vec![wheel_point(Vec2::new(0.0, 40.0), Modifiers::SHIFT)]], true, Id::unique("accum-batched")); + let split = snap_gesture( + vec![ + vec![wheel_point(quarter, Modifiers::SHIFT)], + vec![wheel_point(quarter, Modifiers::SHIFT)], + vec![wheel_point(quarter, Modifiers::SHIFT)], + vec![wheel_point(quarter, Modifiers::SHIFT)], + ], + true, + Id::unique("accum-split"), + ); + assert_eq!(batched, 1, "40 points batched → 1 step"); + assert_eq!(split, 1, "4 × 10 points split → 1 step"); +} + +#[test] +fn fractional_accumulation_negative_and_horizontal() { + let neg_quarter = Vec2::new(0.0, -10.0); + let neg_split = snap_gesture( + vec![ + vec![wheel_point(neg_quarter, Modifiers::SHIFT)], + vec![wheel_point(neg_quarter, Modifiers::SHIFT)], + vec![wheel_point(neg_quarter, Modifiers::SHIFT)], + vec![wheel_point(neg_quarter, Modifiers::SHIFT)], + ], + true, + Id::unique("accum-neg"), + ); + assert_eq!(neg_split, -1, "4 × −10 points → −1 step"); + let h_quarter = Vec2::new(10.0, 0.0); + let h_split = snap_gesture( + vec![ + vec![wheel_point(h_quarter, Modifiers::SHIFT)], + vec![wheel_point(h_quarter, Modifiers::SHIFT)], + vec![wheel_point(h_quarter, Modifiers::SHIFT)], + vec![wheel_point(h_quarter, Modifiers::SHIFT)], + ], + true, + Id::unique("accum-horiz"), + ); + assert_eq!(h_split, 1, "horizontal 4 × 10 → 1 step"); +} + +#[test] +fn accumulation_handles_empty_frames_and_direction_reversal() { + let snaps = snap_gesture( + vec![ + vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], + vec![], // empty frame + vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], + vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], + vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], + ], + true, + Id::unique("accum-empty"), + ); + assert_eq!(snaps, 1, "empty frame preserves residual"); + let reversal = snap_gesture( + vec![vec![wheel_point(Vec2::new(0.0, 30.0), Modifiers::SHIFT)], vec![wheel_point(Vec2::new(0.0, -15.0), Modifiers::SHIFT)]], + true, + Id::unique("accum-reversal"), + ); + assert_eq!(reversal, 0, "30 − 15 = 15 points, below 1 notch → 0 steps"); +} + +#[test] +fn accumulation_shift_alt_without_preference() { + let shift_alt = Modifiers { shift: true, alt: true, ..Modifiers::NONE }; + let split = snap_gesture( + vec![ + vec![wheel_point(Vec2::new(0.0, 10.0), shift_alt)], + vec![wheel_point(Vec2::new(0.0, 10.0), shift_alt)], + vec![wheel_point(Vec2::new(0.0, 10.0), shift_alt)], + vec![wheel_point(Vec2::new(0.0, 10.0), shift_alt)], + ], + false, + Id::unique("accum-shift-alt"), + ); + assert_eq!(split, 1, "Shift+Alt 4 × 10 → 1 step without preference"); +} + +#[test] +fn cross_viewport_does_not_leak_residual() { + let owner_a = Id::unique("owner-a"); + let owner_b = Id::unique("owner-b"); + let ctx = Context::default(); + configure(&ctx); + let mut snaps_a = 0i32; + let mut snaps_b = 0i32; + // Frame 0: 30 points over A (hovered), B not hovered. + let raw = + RawInput { time: Some(0.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 30.0), Modifiers::SHIFT)], ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_a, true) { + snaps_a += s; + } + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_b, false) { + snaps_b += s; + } + }); + out.textures_delta.clear(); + assert_eq!(snaps_a, 0, "A: 30 points, below 1 notch"); + assert_eq!(snaps_b, 0, "B: not hovered, nothing"); + // Frame 1: 10 points, pointer moved to B (B hovered, A not). + let raw = RawInput { + time: Some(1.0 / 60.0), + predicted_dt: 1.0 / 60.0, + events: vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_a, false) { + snaps_a += s; + } + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_b, true) { + snaps_b += s; + } + }); + out.textures_delta.clear(); + assert_eq!(snaps_b, 0, "B: only 10 points of its own, no snap"); + // Frame 2–4: 30 more points over B. + for n in 2..5 { + let raw = RawInput { + time: Some(f64::from(n) / 60.0), + predicted_dt: 1.0 / 60.0, + events: vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + let _ = read(ui.ctx(), true, true, true, owner_a, false); + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_b, true) { + snaps_b += s; + } + }); + out.textures_delta.clear(); + } + assert_eq!(snaps_b, 1, "B: 10+10+10+10 = 40 → 1 step"); + // Frame 5: switch back to A — A's residual was cleared on the viewport switch. + let raw = RawInput { + time: Some(5.0 / 60.0), + predicted_dt: 1.0 / 60.0, + events: vec![wheel_point(Vec2::new(0.0, 30.0), Modifiers::SHIFT)], + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_a, true) { + snaps_a += s; + } + let _ = read(ui.ctx(), true, true, true, owner_b, false); + }); + out.textures_delta.clear(); + assert_eq!(snaps_a, 0, "A: fresh start after switch, 30 points, no snap yet"); +} + +#[test] +fn two_reads_same_owner_same_frame_do_not_double_count() { + let owner = Id::unique("same-owner"); + let ctx = Context::default(); + configure(&ctx); + let mut total_snaps = 0i32; + let raw = + RawInput { time: Some(0.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 20.0), Modifiers::SHIFT)], ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner, true) { + total_snaps += s; + } + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner, true) { + total_snaps += s; + } + }); + out.textures_delta.clear(); + assert_eq!(total_snaps, 0, "20 points read twice must not become 40"); + // Now add another 20 in the next frame — should snap since accumulated 20+20=40. + let raw = RawInput { + time: Some(1.0 / 60.0), + predicted_dt: 1.0 / 60.0, + events: vec![wheel_point(Vec2::new(0.0, 20.0), Modifiers::SHIFT)], + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner, true) { + total_snaps += s; + } + }); + out.textures_delta.clear(); + assert_eq!(total_snaps, 1, "20 + 20 across two frames → 1 step"); +} + +#[test] +fn accumulation_hostile_numbers() { + for dy in [1e30, -1e30, 1e-10, -1e-10] { + let snaps = snap_gesture(vec![vec![wheel_point(Vec2::new(0.0, dy), Modifiers::SHIFT)]], true, Id::unique("accum-hostile")); + assert!(snaps.abs() <= 10, "hostile {dy} clamped: {snaps}"); + } +} + +#[test] +fn line_unit_snap_still_works_with_accumulation() { + let (_, _, snaps) = gesture(vec![vec![wheel(Vec2::new(0.0, 1.0), Modifiers::SHIFT)]], true, false); + assert_eq!(snaps, 1, "Line-unit notch produces 1 step"); + let (_, _, snaps) = gesture(vec![vec![wheel(Vec2::new(0.0, -1.0), Modifiers::SHIFT)]], true, false); + assert_eq!(snaps, -1, "Line-unit notch down produces −1 step"); +} + +/// Two fingers on a touch screen: down 20 points apart, spread to 40 (a ×2 pinch), lifted. +fn touch_pinch_frames() -> Vec> { + let touch = |id: u64, phase: TouchPhase, x: f32| Event::Touch { + device_id: egui::TouchDeviceId(1), + id: egui::TouchId(id), + phase, + pos: egui::pos2(x, 50.0), + force: None, + }; + vec![ + // egui only starts a multi-touch gesture once it knows where the pointer is. + vec![Event::PointerMoved(egui::pos2(40.0, 50.0))], + vec![touch(1, TouchPhase::Start, 40.0), touch(2, TouchPhase::Start, 60.0)], + vec![touch(1, TouchPhase::Move, 30.0), touch(2, TouchPhase::Move, 70.0)], + vec![touch(1, TouchPhase::End, 30.0), touch(2, TouchPhase::End, 70.0)], + ] +} + +/// The total zoom [`read_with`] reports over `frames`, Enable Gestures set to `touch_gestures`. +fn touch_zoom(frames: Vec>, touch_gestures: bool) -> f32 { + let owner = Id::unique("test-touch"); + let ctx = Context::default(); + configure(&ctx); + let mut zoom = 1.0; + for (n, events) in (0u32..).zip(frames) { + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Zoom(f)) = read_with(ui.ctx(), false, true, true, owner, true, true, touch_gestures) { + zoom *= f; + } + }); + out.textures_delta.clear(); + } + zoom +} + +/// Preferences › Enhanced Controls › Enable Gestures (#204): on (the default) a two-finger +/// pinch on a touch screen zooms; off, it leaves the view alone. +#[test] +fn enable_gestures_switches_touch_screen_pinch_zoom() { + let on = touch_zoom(touch_pinch_frames(), true); + assert!((on - 2.0).abs() < 1e-4, "on: the fingers zoom ×2: {on}"); + let off = touch_zoom(touch_pinch_frames(), false); + assert_eq!(off, 1.0, "off: the fingers don't zoom"); +} + +/// Enable Gestures off only silences the touch screen: a trackpad pinch still zooms, also in a +/// frame where two fingers rest on the screen (egui's `zoom_delta` would report theirs instead). +#[test] +fn enable_gestures_off_keeps_the_trackpad_pinch() { + let zoom = touch_zoom(vec![vec![Event::Zoom(1.25)]], false); + assert!((zoom - 1.25).abs() < 1e-4, "no fingers down: {zoom}"); + let mut frames = touch_pinch_frames(); + frames[2] = vec![Event::Zoom(1.25)]; + let zoom = touch_zoom(frames, false); + assert!((zoom - 1.25).abs() < 1e-4, "fingers resting: {zoom}"); +} From 6a2bc15544d912801f67a3a6444f65bb798d6322 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:35 +0000 Subject: [PATCH 104/259] refactor(ui-egui): move liquify_ui.rs tests to liquify_ui/tests.rs --- crates/ui-egui/src/liquify_ui.rs | 846 +------------------------ crates/ui-egui/src/liquify_ui/tests.rs | 843 ++++++++++++++++++++++++ 2 files changed, 844 insertions(+), 845 deletions(-) create mode 100644 crates/ui-egui/src/liquify_ui/tests.rs diff --git a/crates/ui-egui/src/liquify_ui.rs b/crates/ui-egui/src/liquify_ui.rs index 52a16f6223..5d4da05bff 100644 --- a/crates/ui-egui/src/liquify_ui.rs +++ b/crates/ui-egui/src/liquify_ui.rs @@ -1275,848 +1275,4 @@ fn draw_mesh(d: &LiquifyDialog, painter: &egui::Painter, area: ERect) { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_brush_outline_follows_the_pointer_except_while_resizing() { - let (hover, anchor) = (pos2(30.0, 40.0), pos2(10.0, 20.0)); - assert_eq!(brush_circle_at(None, Some(hover)), Some(hover)); - assert_eq!(brush_circle_at(Some((anchor, 40.0, 50.0)), Some(hover)), Some(anchor)); - assert_eq!(brush_circle_at(Some((anchor, 40.0, 50.0)), None), Some(anchor)); - assert_eq!(brush_circle_at(None, None), None); - } - - #[test] - fn alt_right_drag_resizes_the_liquify_brush_and_does_not_paint() { - assert!(brush_resize_gesture(egui::Modifiers::ALT, true)); - assert!(brush_resize_gesture(egui::Modifiers::CTRL | egui::Modifiers::ALT, false)); - assert!(!brush_resize_gesture(egui::Modifiers::ALT, false), "Alt+left stays the tool's opposite"); - assert!(!brush_resize_gesture(egui::Modifiers::NONE, true)); - let (size, density) = resized_brush(40.0, 50.0, 25.0, crate::brush_resize::HARDNESS_TRAVEL); - assert_eq!((size, density), (65.0, 100.0)); - let (size, density) = resized_brush(40.0, 50.0, -100.0, 0.0); - assert_eq!((size, density), (1.0, 50.0)); - } - - fn app_with_layer() -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.session.execute("file.new", json!({"width": 120, "height": 80, "depth": 8})).unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, active| { - let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for y in 10..70 { - for x in 10..110 { - let v = ((x / 5 + y / 5) % 2) as f32; - s.write_pixel(x, y, &[v, 0.3, 1.0 - v, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - app.sync_views(); - app - } - - #[test] - fn zoomed_liquify_preview_uses_only_the_visible_full_resolution_crop() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - let d = app.distort.liquify.as_mut().unwrap(); - d.zoom = 2.0; - d.center = [60.0, 40.0]; - d.update_view_preview(&ctx, ERect::from_min_size(pos2(0.0, 0.0), vec2(60.0, 40.0))); - assert_eq!(d.view_bounds, Some(Rect::new(45, 30, 75, 50))); - assert_eq!(d.view_out.len(), 30 * 20, "one preview texel per document pixel"); - assert!(d.view_tex.is_some()); - - let before = d.view_out.clone(); - let mut stroke = LiquifyStroke::new(LiquifyTool::ForwardWarp, 24.0); - stroke.points = vec![vec![50.0, 40.0, 1.0], vec![58.0, 40.0, 1.0]]; - let dirty = d.field.stroke_segment(&stroke, [50.0, 40.0, 1.0], [58.0, 40.0, 1.0]); - d.mark(dirty, false); - d.render_dirty(); - d.update_view_preview(&ctx, ERect::from_min_size(pos2(0.0, 0.0), vec2(60.0, 40.0))); - assert_ne!(d.view_out, before, "a brush update refreshes the visible source-resolution crop"); - assert!(d.preview_ms.is_finite()); - } - - /// #7609: Show Backdrop › Use and Mode, as in Photoshop: the settings, how each mode layers the - /// backdrop and the image, and what each Use shows. - #[test] - fn backdrop_use_and_mode() { - let mut o = LiquifyOpts::default(); - assert_eq!((o.backdrop_layer, o.backdrop_mode), (None, BackdropMode::InFront), "All Layers, In Front"); - o.apply(&json!({"backdropUse": 3, "backdropMode": "behind"})).unwrap(); - assert_eq!((o.backdrop_layer, o.backdrop_mode), (Some(3), BackdropMode::Behind)); - assert_eq!((&o.to_json()["backdropUse"], &o.to_json()["backdropMode"]), (&json!(3), &json!("behind"))); - o.apply(&json!({"backdropUse": "all", "backdropMode": "nope"})).unwrap(); - assert_eq!((o.backdrop_layer, o.backdrop_mode), (None, BackdropMode::Behind), "a bad mode is ignored"); - let (w, a) = (Color32::WHITE, |x: f32| Color32::from_white_alpha((x * 255.0).round() as u8)); - let l = |image, behind, front| Layering { image, behind, front }; - assert_eq!(backdrop_layering(Some(1), BackdropMode::InFront, 0.25), l(w, None, Some((1, a(0.25)))), "backdrop over the image"); - assert_eq!(backdrop_layering(Some(1), BackdropMode::Behind, 0.25), l(a(0.25), Some((1, w)), None), "image over the backdrop"); - assert_eq!(backdrop_layering(Some(1), BackdropMode::Blend, 0.25), l(a(0.75), None, Some((1, a(0.25)))), "faded together"); - assert_eq!(backdrop_layering::(None, BackdropMode::Blend, 0.25), l(w, None, None), "no backdrop: the image as is"); - // All Layers is the document with the liquified layer in it; one layer is that layer alone. - let app = app_with_layer(); - let st = app.session.active().unwrap(); - let (layer, background) = (st.active_layer.unwrap(), st.doc.layers[0].id); - let at = |doc: &Document| photocraft_compose::render(doc, Rect::new(10, 10, 11, 11)).px[0]; - let own = at(&st.doc); - assert_eq!(at(&backdrop_doc(&st.doc, None)), own, "All Layers"); - assert_eq!(at(&backdrop_doc(&st.doc, Some(layer.0))), own, "the liquified layer alone"); - assert_ne!(at(&backdrop_doc(&st.doc, Some(background.0))), own, "the Background alone"); - assert_eq!(at(&backdrop_doc(&st.doc, Some(9999))), own, "a layer that's gone: All Layers"); - // A hidden layer shows when it is the one used. - let mut hidden = (*st.doc).clone(); - hidden.layer_mut(layer).unwrap().visible = false; - assert_eq!(at(&backdrop_doc(&hidden, Some(layer.0))), own, "the hidden liquified layer, alone"); - // A remembered Use is a layer of another document: Liquify opens on All Layers. - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - app.session.prefs.edit(|p| p.dialogs.insert(REMEMBERED.into(), json!({"backdropUse": 42, "backdropMode": "blend"}))); - open(&mut app, &ctx).unwrap(); - let o = &app.distort.liquify.as_ref().unwrap().opts; - assert_eq!((o.backdrop_layer, o.backdrop_mode), (None, BackdropMode::Blend), "the mode is kept, the layer is not"); - // Over the control channel, a layer of the document is kept and one that isn't is All Layers. - let layer = app.session.active().unwrap().active_layer.unwrap().0; - control(&mut app, &json!({"backdropUse": layer})).unwrap(); - assert_eq!(app.distort.liquify.as_ref().unwrap().opts.backdrop_layer, Some(layer)); - control(&mut app, &json!({"backdropUse": 4242})).unwrap(); - assert_eq!(app.distort.liquify.as_ref().unwrap().opts.backdrop_layer, None, "no such layer: All Layers"); - control(&mut app, &json!({"backdropUse": layer})).unwrap(); - assert!(control(&mut app, &json!({"backdropUse": 4242, "tool": "nope"})).is_err()); - assert_eq!(app.distort.liquify.as_ref().unwrap().opts.backdrop_layer, None, "also when another setting fails"); - } - - /// #418: the brush settings survive Cancel, OK and Esc, and come back the next time Liquify - /// opens (also after a restart: they live in the preferences). - #[test] - fn brush_settings_are_remembered_between_uses() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - let fresh = app.distort.liquify.as_ref().unwrap().opts.clone(); - assert_eq!((fresh.density, fresh.tool), (50.0, LiquifyTool::ForwardWarp), "first use: the defaults"); - let set = json!({"tool": "twirlCw", "size": 37, "density": 85, "pressure": 60, "rate": 30, "showMesh": true, "meshSize": "large", "showBackdrop": true, "backdropOpacity": 25}); - control(&mut app, &set).unwrap(); - control(&mut app, &json!({"cancel": true})).unwrap(); - assert!(app.distort.liquify.is_none()); - open(&mut app, &ctx).unwrap(); - assert_eq!(app.distort.liquify.as_ref().unwrap().opts.to_json(), { - let mut o = LiquifyOpts::default(); - o.apply(&set).unwrap(); - o.to_json() - }); - // OK and Esc keep the latest settings too. - control(&mut app, &json!({"density": 90})).unwrap(); - commit(&mut app).unwrap(); - open(&mut app, &ctx).unwrap(); - assert_eq!(app.distort.liquify.as_ref().unwrap().opts.density, 90.0); - control(&mut app, &json!({"density": 70})).unwrap(); - cancel(&mut app); - assert_eq!(app.session.prefs().dialogs[REMEMBERED]["density"], json!(70.0)); - // A damaged preference keeps what it can and never fails to open. - app.session.prefs.edit(|p| p.dialogs.insert(REMEMBERED.into(), json!({"tool": "nope", "density": "lots", "size": 1e12, "rate": 20}))); - open(&mut app, &ctx).unwrap(); - let o = &app.distort.liquify.as_ref().unwrap().opts; - assert_eq!((o.tool, o.density, o.size, o.rate), (LiquifyTool::ForwardWarp, 50.0, 15000.0, 20.0)); - app.session.prefs.edit(|p| p.dialogs.insert(REMEMBERED.into(), json!("not an object"))); - cancel(&mut app); - assert!(open(&mut app, &ctx).is_ok()); - } - - /// Follow-up to #1494 / #1484: Alt is captured at stroke-down and stays recorded - /// through undo, redo and deterministic Liquify field reconstruction. - #[test] - fn alt_reversed_twirl_survives_replay_undo_and_redo() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - control(&mut app, &json!({"tool": "twirlCw", "size": 36, "rate": 80})).unwrap(); - - // Releasing Alt while dragging must not change the tool recorded at pointer-down. - pointer(&mut app, ToolEvent::Down { x: 53.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::ALT); - pointer(&mut app, ToolEvent::Move { x: 58.0, y: 41.0, pressure: 1.0 }, egui::Modifiers::NONE); - pointer(&mut app, ToolEvent::Up { x: 58.0, y: 41.0 }, egui::Modifiers::NONE); - let d = app.distort.liquify.as_ref().unwrap(); - assert_eq!(d.opts.tool, LiquifyTool::TwirlCw, "Alt must not change the selected tool"); - assert_eq!(d.strokes.len(), 1); - assert_eq!(d.strokes[0].tool, LiquifyTool::TwirlCcw); - assert_eq!(LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes), d.field); - - // A following stroke without Alt records the original tool. - pointer(&mut app, ToolEvent::Down { x: 70.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE); - pointer(&mut app, ToolEvent::Move { x: 75.0, y: 42.0, pressure: 1.0 }, egui::Modifiers::ALT); - pointer(&mut app, ToolEvent::Up { x: 75.0, y: 42.0 }, egui::Modifiers::ALT); - let d = app.distort.liquify.as_ref().unwrap(); - assert_eq!(d.strokes.len(), 2); - assert_eq!(d.strokes[1].tool, LiquifyTool::TwirlCw); - assert_eq!(LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes), d.field); - - control(&mut app, &json!({"undo": true})).unwrap(); - let d = app.distort.liquify.as_ref().unwrap(); - assert_eq!(d.strokes.len(), 1); - assert_eq!(d.strokes[0].tool, LiquifyTool::TwirlCcw); - assert_eq!(d.redo[0].tool, LiquifyTool::TwirlCw); - assert_eq!(LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes), d.field); - - control(&mut app, &json!({"redo": true})).unwrap(); - let d = app.distort.liquify.as_ref().unwrap(); - assert_eq!(d.strokes.len(), 2); - assert!(d.redo.is_empty()); - assert_eq!(d.strokes[0].tool, LiquifyTool::TwirlCcw); - assert_eq!(d.strokes[1].tool, LiquifyTool::TwirlCw); - assert_eq!(LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes), d.field); - } - - #[test] - fn dialog_strokes_match_the_engine_and_commit_once() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - control(&mut app, &json!({"tool": "forwardWarp", "size": 40})).unwrap(); - for ev in [ - ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, - ToolEvent::Move { x: 48.0, y: 41.0, pressure: 1.0 }, - ToolEvent::Move { x: 56.0, y: 40.0, pressure: 1.0 }, - ToolEvent::Up { x: 56.0, y: 40.0 }, - ] { - pointer(&mut app, ev, egui::Modifiers::NONE); - } - control(&mut app, &json!({"tool": "bloat"})).unwrap(); - for ev in [ToolEvent::Down { x: 80.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 80.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 80.0, y: 40.0 }] - { - pointer(&mut app, ev, egui::Modifiers::NONE); - } - let d = app.distort.liquify.as_ref().unwrap(); - assert_eq!(d.strokes.len(), 2); - assert_eq!(d.redo.len(), 0); - // Replaying the recorded strokes gives exactly the interactive field. - let replay = LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes); - assert_eq!(replay, d.field); - assert!(d.field.max_displacement() > 3.0); - // Undo inside the dialog drops the last stroke. - control(&mut app, &json!({"undo": true})).unwrap(); - assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 1); - assert_eq!(app.distort.liquify.as_ref().unwrap().redo.len(), 1); - control(&mut app, &json!({"redo": true})).unwrap(); - assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 2); - assert_eq!(app.distort.liquify.as_ref().unwrap().redo.len(), 0); - control(&mut app, &json!({"undo": true})).unwrap(); - let before = app.session.active().unwrap().history.past_len(); - control(&mut app, &json!({"commit": true})).unwrap(); - assert!(app.distort.liquify.is_none()); - assert_eq!(app.session.active().unwrap().history.past_len(), before + 1); - } - - #[test] - fn undo_rerenders_the_proxy_before_the_next_texture_upload() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - control(&mut app, &json!({"tool": "forwardWarp", "size": 40})).unwrap(); - for ev in [ - ToolEvent::Down { x: 35.0, y: 40.0, pressure: 1.0 }, - ToolEvent::Move { x: 55.0, y: 40.0, pressure: 1.0 }, - ToolEvent::Up { x: 55.0, y: 40.0 }, - ToolEvent::Down { x: 70.0, y: 40.0, pressure: 1.0 }, - ToolEvent::Move { x: 90.0, y: 40.0, pressure: 1.0 }, - ToolEvent::Up { x: 90.0, y: 40.0 }, - ] { - pointer(&mut app, ev, egui::Modifiers::NONE); - } - - let before = app.distort.liquify.as_ref().unwrap().out.clone(); - control(&mut app, &json!({"undo": true})).unwrap(); - let d = app.distort.liquify.as_ref().unwrap(); - assert_eq!(d.strokes.len(), 1); - assert_ne!(d.out, before, "undo must update the pixels shown by the existing texture"); - - let mut expected = vec![[0u8; 4]; d.proxy.w * d.proxy.h]; - d.proxy.render(&d.field, [0, 0, d.proxy.w, d.proxy.h], &mut expected); - assert_eq!(d.out, expected, "dirty upload source must match the rebuilt field"); - } - - #[test] - fn undo_dirties_the_zoomed_preview() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - control(&mut app, &json!({"tool": "forwardWarp", "size": 40})).unwrap(); - for ev in [ToolEvent::Down { x: 35.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 55.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 55.0, y: 40.0 }] - { - pointer(&mut app, ev, egui::Modifiers::NONE); - } - { - let d = app.distort.liquify.as_mut().unwrap(); - d.zoom = 2.0; - d.view_bounds = Some(Rect::new(0, 0, 20, 20)); - d.view_dirty = None; - } - control(&mut app, &json!({"undo": true})).unwrap(); - let d = app.distort.liquify.as_ref().unwrap(); - assert_eq!(d.view_dirty, d.view_bounds); - } - - #[test] - fn liquify_redo_restores_undone_stroke_and_a_new_stroke_clears_redo() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - control(&mut app, &json!({"tool": "forwardWarp", "size": 40})).unwrap(); - let draw = |app: &mut PhotocraftApp, x: f64| { - for ev in - [ToolEvent::Down { x, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: x + 14.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: x + 14.0, y: 40.0 }] - { - pointer(app, ev, egui::Modifiers::NONE); - } - }; - - draw(&mut app, 30.0); - draw(&mut app, 70.0); - control(&mut app, &json!({"undo": true})).unwrap(); - let d = app.distort.liquify.as_ref().unwrap(); - assert_eq!((d.strokes.len(), d.redo.len()), (1, 1)); - - control(&mut app, &json!({"redo": true})).unwrap(); - let d = app.distort.liquify.as_ref().unwrap(); - assert_eq!((d.strokes.len(), d.redo.len()), (2, 0)); - assert_eq!(LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes), d.field); - - control(&mut app, &json!({"undo": true})).unwrap(); - draw(&mut app, 50.0); - let d = app.distort.liquify.as_ref().unwrap(); - assert_eq!((d.strokes.len(), d.redo.len()), (2, 0)); - control(&mut app, &json!({"redo": true})).unwrap(); - assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 2, "redo after a new stroke is a no-op"); - } - - /// The Freeze Lasso freezes the dragged polygon (⌥ thaws it) as one recorded stroke, and a - /// new lasso clears Redo like any other stroke. - #[test] - fn freeze_lasso_records_a_stroke_and_clears_redo() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - control(&mut app, &json!({"tool": "lassoMask"})).unwrap(); - let lasso = |app: &mut PhotocraftApp, m: egui::Modifiers, r: [f64; 4]| { - pointer(app, ToolEvent::Down { x: r[0], y: r[1], pressure: 1.0 }, m); - for (x, y) in [(r[2], r[1]), (r[2], r[3]), (r[0], r[3])] { - pointer(app, ToolEvent::Move { x, y, pressure: 1.0 }, m); - } - pointer(app, ToolEvent::Up { x: r[0], y: r[3] }, m); - }; - lasso(&mut app, egui::Modifiers::NONE, [20.0, 20.0, 80.0, 60.0]); - let d = app.distort.liquify.as_ref().unwrap(); - assert_eq!(d.strokes.len(), 1); - assert_eq!(d.field.freeze_at(50.0, 40.0), 1.0, "frozen inside"); - assert_eq!(d.field.freeze_at(5.0, 5.0), 0.0, "not outside"); - lasso(&mut app, egui::Modifiers::ALT, [40.0, 30.0, 60.0, 50.0]); - let d = app.distort.liquify.as_ref().unwrap(); - assert_eq!(d.field.freeze_at(50.0, 40.0), 0.0, "⌥ thaws"); - assert_eq!(d.field.freeze_at(25.0, 25.0), 1.0); - control(&mut app, &json!({"undo": true})).unwrap(); - assert_eq!(app.distort.liquify.as_ref().unwrap().field.freeze_at(50.0, 40.0), 1.0, "undo replays the first lasso"); - assert_eq!(app.distort.liquify.as_ref().unwrap().redo.len(), 1); - lasso(&mut app, egui::Modifiers::NONE, [0.0, 0.0, 10.0, 10.0]); - assert_eq!(app.distort.liquify.as_ref().unwrap().redo.len(), 0, "a new lasso clears redo"); - } - - #[test] - fn alt_reverses_twirl_and_swaps_pucker_and_bloat() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - let dab = |app: &mut PhotocraftApp, m: egui::Modifiers| { - pointer(app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }, m); - pointer(app, ToolEvent::Up { x: 50.0, y: 40.0 }, m); - app.distort.liquify.as_ref().unwrap().strokes.last().unwrap().tool - }; - for (tool, plain, alt) in [ - ("twirlCw", LiquifyTool::TwirlCw, LiquifyTool::TwirlCcw), - ("twirlCcw", LiquifyTool::TwirlCcw, LiquifyTool::TwirlCw), - ("pucker", LiquifyTool::Pucker, LiquifyTool::Bloat), - ("bloat", LiquifyTool::Bloat, LiquifyTool::Pucker), - ("forwardWarp", LiquifyTool::ForwardWarp, LiquifyTool::ForwardWarp), - ] { - control(&mut app, &json!({"tool": tool})).unwrap(); - assert_eq!(dab(&mut app, egui::Modifiers::NONE), plain, "{tool}"); - assert_eq!(dab(&mut app, egui::Modifiers::ALT), alt, "⌥ {tool}"); - assert_eq!(app.distort.liquify.as_ref().unwrap().opts.tool, plain, "⌥ leaves the selected tool alone"); - } - } - - #[test] - fn liquify_redo_stack_is_bounded() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - let d = app.distort.liquify.as_mut().unwrap(); - d.strokes = (0..=REDO_STACK_LIMIT).map(|_| LiquifyStroke::new(LiquifyTool::ForwardWarp, 1.0)).collect(); - for _ in 0..=REDO_STACK_LIMIT { - d.undo(); - } - assert_eq!(d.redo.len(), REDO_STACK_LIMIT); - } - - /// #7884: Alt+right-dragging the brush size in the Liquify dialog keeps the brush where the - /// drag started (its outline and the point it would work at) and only changes its size, as the - /// brush tools' Alt-drag does outside Liquify. - #[test] - fn alt_drag_resize_keeps_the_brush_where_it_started() { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, Default::default()); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - let screen = ERect::from_min_size(pos2(0.0, 0.0), vec2(1400.0, 900.0)); - let frame = |app: &mut PhotocraftApp, events: Vec, mods: egui::Modifiers| { - let events = std::iter::once(egui::Event::ModifiersChanged(mods)).chain(events).collect(); - let raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; - ctx.run_ui(raw, |ui| show(app, ui.ctx())).textures_delta.clear(); - }; - let alt = egui::Modifiers::ALT; - let none = egui::Modifiers::NONE; - frame(&mut app, vec![], none); - // A point over the image in the dialog's canvas (120 × 80): the first one on a grid. - let p = (1..22) - .flat_map(|j| (1..34).map(move |i| pos2(40.0 * i as f32, 40.0 * j as f32))) - .find(|&q| { - frame(&mut app, vec![egui::Event::PointerMoved(q)], none); - let h = app.distort.liquify.as_ref().and_then(|d| d.hover); - h.is_some_and(|h| (10.0..60.0).contains(&h[0]) && (20.0..60.0).contains(&h[1])) - }) - .expect("the dialog shows the image"); - frame(&mut app, vec![egui::Event::PointerMoved(p)], none); - let d = app.distort.liquify.as_ref().unwrap(); - let (start, size0) = (d.hover.expect("the pointer is over the canvas"), d.opts.size); - let button = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Secondary, pressed, modifiers: alt }; - frame(&mut app, vec![button(true)], alt); - for k in 1..=6 { - frame(&mut app, vec![egui::Event::PointerMoved(p + vec2(10.0 * k as f32, 0.0))], alt); - } - let d = app.distort.liquify.as_ref().unwrap(); - assert!(d.opts.size > size0, "the drag resized the brush: {} -> {}", size0, d.opts.size); - assert_eq!(d.hover, Some(start), "the brush stayed where the drag started"); - assert!(d.strokes.is_empty(), "and nothing was painted"); - } - - #[test] - fn shortcut_handler_undoes_liquify_even_when_egui_owns_keyboard_focus() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - for ev in [ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 52.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 52.0, y: 40.0 }] - { - pointer(&mut app, ev, egui::Modifiers::NONE); - } - assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 1); - - let raw = egui::RawInput { - events: vec![egui::Event::Key { key: egui::Key::Z, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }], - ..Default::default() - }; - let mut out = ctx.run_ui(raw, |ui| { - let ctx = ui.ctx(); - ctx.memory_mut(|m| m.request_focus(egui::Id::unique("liquify-slider-focus"))); - assert!(ctx.egui_wants_keyboard_input()); - crate::shortcuts::handle(&mut app, ctx); - }); - out.textures_delta.clear(); - assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 0); - let raw = egui::RawInput { - events: vec![egui::Event::Key { - key: egui::Key::Z, - physical_key: None, - pressed: true, - repeat: false, - modifiers: egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, - }], - ..Default::default() - }; - let _ = ctx.run_ui(raw, |ui| { - crate::shortcuts::handle(&mut app, ui.ctx()); - }); - assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 1, "Cmd+Shift+Z redoes the last stroke"); - } - - // Regression test for #4134: Cmd+Z and Cmd+Shift+Z were ignored in Liquify while a numeric - // field's text edit (Size, Pressure, ...) had keyboard focus, so a stroke could not be undone. - #[test] - fn liquify_undo_and_redo_work_while_a_numeric_field_is_focused() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - for ev in [ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 52.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 52.0, y: 40.0 }] - { - pointer(&mut app, ev, egui::Modifiers::NONE); - } - let strokes = |app: &PhotocraftApp| app.distort.liquify.as_ref().unwrap().strokes.len(); - assert_eq!(strokes(&app), 1); - - // One frame of the real shortcut handler, then a focused single-line text edit (the - // numeric fields are text edits), as the app orders them. - let mut text = String::from("100"); - let field = egui::Id::unique("liquify-size-field"); - let mut frame = |app: &mut PhotocraftApp, events: Vec| { - let raw = egui::RawInput { events, ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| { - crate::shortcuts::handle(app, ui.ctx()); - let edit = ui.add(egui::TextEdit::singleline(&mut text).id(field)); - edit.request_focus(); - }); - out.textures_delta.clear(); - }; - frame(&mut app, Vec::new()); - assert!(ctx.text_edit_focused(), "the numeric field is a focused text edit"); - - let z = |modifiers| egui::Event::Key { key: egui::Key::Z, physical_key: None, pressed: true, repeat: false, modifiers }; - frame(&mut app, vec![z(egui::Modifiers::COMMAND)]); - assert_eq!(strokes(&app), 0, "Cmd+Z undoes the stroke with the field focused"); - frame(&mut app, vec![z(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT)]); - assert_eq!(strokes(&app), 1, "Cmd+Shift+Z redoes it"); - } - - // Regression test for #4134: other Liquify keys must not steal characters from a focused - // numeric field, and the bracket keys step the brush by at least one pixel. - #[test] - fn liquify_tool_keys_leave_a_focused_field_alone_and_brackets_reach_one_pixel() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - app.distort.liquify.as_mut().unwrap().opts.size = 2.0; - let size = |app: &PhotocraftApp| app.distort.liquify.as_ref().unwrap().opts.size; - let press = |app: &mut PhotocraftApp, key: egui::Key| { - let ev = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - let mut out = ctx.run_ui(egui::RawInput { events: vec![ev], ..Default::default() }, |ui| crate::shortcuts::handle(app, ui.ctx())); - out.textures_delta.clear(); - }; - // 2 px * 0.9 used to round back to 2, so `[` never reached 1 px; `]` steps up from 1. - press(&mut app, egui::Key::OpenBracket); - assert_eq!(size(&app), 1.0, "`[` steps a 2 px brush down to 1 px"); - press(&mut app, egui::Key::CloseBracket); - assert_eq!(size(&app), 2.0, "`]` steps it back up"); - - // With a text edit focused, `[` belongs to the field. - let mut text = String::new(); - let field = egui::Id::unique("liquify-size-field"); - let focused_frame = |app: &mut PhotocraftApp, text: &mut String, events: Vec| { - let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { - crate::shortcuts::handle(app, ui.ctx()); - ui.add(egui::TextEdit::singleline(text).id(field)).request_focus(); - }); - out.textures_delta.clear(); - }; - focused_frame(&mut app, &mut text, Vec::new()); - assert!(ctx.text_edit_focused()); - let bracket = egui::Event::Key { key: egui::Key::OpenBracket, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; - focused_frame(&mut app, &mut text, vec![bracket]); - assert_eq!(size(&app), 2.0, "the focused field keeps its keys"); - } - - fn key(key: egui::Key) -> egui::Event { - egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND } - } - - /// A frame of the open dialog in a 1000 × 700 window with `events`; returns the preview's - /// centre (between the tool strip and the options panel, under the title strip). - fn frame(app: &mut PhotocraftApp, ctx: &egui::Context, events: Vec) -> Pos2 { - let screen = ERect::from_min_size(Pos2::ZERO, vec2(1000.0, 700.0)); - let raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| show(app, ui.ctx())); - out.textures_delta.clear(); - pos2((LEFT_W + screen.width() - RIGHT_W) / 2.0, (30.0 + screen.height()) / 2.0) - } - - /// #7210: ⌘+ / ⌘− step Liquify's preview along the zoom ladder, ⌘0 fits it and ⌘1 is the - /// dialog's 100 %, through the canvas's own shortcuts; the canvas behind keeps its zoom. - #[test] - fn zoom_shortcuts_zoom_the_preview_not_the_canvas() { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - frame(&mut app, &ctx, Vec::new()); - let fitted = app.distort.liquify.as_ref().unwrap().zoom; - assert!(fitted > 0.0, "the preview fits on its first frame"); - let canvas_zoom = app.ui.views.first().map(|v| v.zoom); - let mut press = |k: egui::Key| { - let raw = egui::RawInput { events: vec![key(k)], ..Default::default() }; - let _ = ctx.run_ui(raw, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); - app.distort.liquify.as_ref().unwrap().zoom - }; - assert_eq!(press(egui::Key::Num1), 1.0); - assert_eq!(press(egui::Key::Equals), 2.0, "next step up the ladder"); - assert_eq!(press(egui::Key::Plus), 3.0, "⌘+ typed as Plus too"); - assert_eq!(press(egui::Key::Minus), 2.0); - assert_eq!(press(egui::Key::Num0), 0.0, "fit on the next frame"); - frame(&mut app, &ctx, Vec::new()); - assert_eq!(app.distort.liquify.as_ref().unwrap().zoom, fitted); - assert_eq!(app.ui.views.first().map(|v| v.zoom), canvas_zoom, "the canvas behind keeps its zoom"); - } - - /// #7210: a trackpad pinch over the preview zooms it about the pointer (macOS sends no wheel - /// for it), unless Preferences › Enhanced Controls › Zoom with Trackpad Pinch is off; a wheel - /// notch is one ×1.1 step. - #[test] - fn pinch_and_wheel_zoom_the_preview_about_the_pointer() { - let ctx = egui::Context::default(); - PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - let center = frame(&mut app, &ctx, Vec::new()); - let at = center + vec2(60.0, -40.0); - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); - let screen = ERect::from_min_size(Pos2::ZERO, vec2(1000.0, 700.0)); - let area = ERect::from_min_max(pos2(LEFT_W, 30.0), pos2(screen.width() - RIGHT_W, screen.height())); - let (z0, under) = { - let d = app.distort.liquify.as_ref().unwrap(); - (d.zoom, to_doc(d, area, at)) - }; - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), egui::Event::Zoom(2.0)]); - let d = app.distort.liquify.as_ref().unwrap(); - assert!((d.zoom - z0 * 2.0).abs() < 1e-4, "{} → {}", z0, d.zoom); - let still = to_doc(d, area, at); - assert!((still[0] - under[0]).abs() < 1e-3 && (still[1] - under[1]).abs() < 1e-3, "the point under the pointer stays: {under:?} → {still:?}"); - - // Animated Zoom off: a notch is one instant step, so one frame shows the whole ×1.1. - app.session.prefs.edit(|p| p.general.animated_zoom = false); - let notch = ctx.options(|o| o.input_options.line_scroll_speed); - let wheel = egui::Event::MouseWheel { - source: egui::MouseWheelSource::Unknown, - unit: egui::MouseWheelUnit::Line, - delta: vec2(0.0, 1.0), - modifiers: egui::Modifiers::NONE, - phase: egui::TouchPhase::Move, - }; - let z1 = app.distort.liquify.as_ref().unwrap().zoom; - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), wheel]); - let z2 = app.distort.liquify.as_ref().unwrap().zoom; - assert!(notch > 0.0 && (z2 / z1 - crate::wheel_nav::NOTCH).abs() < 1e-3, "one notch is ×1.1: {z1} → {z2}"); - - app.session.prefs.edit(|p| p.enhanced_controls.zoom_with_trackpad_pinch = false); - frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), egui::Event::Zoom(2.0)]); - assert_eq!(app.distort.liquify.as_ref().unwrap().zoom, z2, "a pinch does nothing with the preference off"); - } - - /// The proxy rendered from the recorded strokes, i.e. what undo/replay rebuilds. - fn replayed_out(d: &LiquifyDialog) -> Vec<[u8; 4]> { - let field = LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes); - let mut out = vec![[0u8; 4]; d.proxy.w * d.proxy.h]; - d.proxy.render(&field, [0, 0, d.proxy.w, d.proxy.h], &mut out); - out - } - - /// #8055: a second pointer-down while a stroke is open must not drop the dabs already applied. - #[test] - fn second_down_without_up_keeps_the_open_strokes_dabs_recorded() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - control(&mut app, &json!({"tool": "forwardWarp", "size": 30})).unwrap(); - for ev in [ - ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, - ToolEvent::Move { x: 46.0, y: 41.0, pressure: 1.0 }, - ToolEvent::Down { x: 46.0, y: 41.0, pressure: 1.0 }, - ToolEvent::Move { x: 55.0, y: 42.0, pressure: 1.0 }, - ToolEvent::Up { x: 55.0, y: 42.0 }, - ] { - pointer(&mut app, ev, egui::Modifiers::NONE); - } - let d = app.distort.liquify.as_ref().unwrap(); - assert!(d.out == replayed_out(d), "the live field must match the field rebuilt from the recorded strokes"); - } - - /// #8055: short strokes drawn with the mouse (moves inside egui's drag threshold first) are - /// recorded whole, as one stroke each, so undo removes only the last one. - #[test] - fn short_mouse_strokes_are_recorded_whole_and_undo_removes_only_the_last() { - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let mut app = app_with_layer(); - open(&mut app, &ctx).unwrap(); - control(&mut app, &json!({"tool": "forwardWarp", "size": 30})).unwrap(); - let screen = ERect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0)); - let frame = |app: &mut PhotocraftApp, events: Vec| { - let raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| show(app, ui.ctx())); - out.textures_delta.clear(); - }; - frame(&mut app, vec![]); - frame(&mut app, vec![]); - let mut before_last = Vec::new(); - let strokes = 6; - for i in 0..strokes { - let start = pos2(560.0 + i as f32 * 25.0, 380.0 + (i % 2) as f32 * 20.0); - before_last = app.distort.liquify.as_ref().unwrap().out.clone(); - frame(&mut app, vec![egui::Event::PointerMoved(start)]); - let press = egui::Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; - frame(&mut app, vec![press]); - let mut p = start; - for _ in 0..8 { - p += vec2(1.5, 1.0); - frame(&mut app, vec![egui::Event::PointerMoved(p)]); - } - let release = egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }; - frame(&mut app, vec![release]); - frame(&mut app, vec![]); - let d = app.distort.liquify.as_ref().unwrap(); - assert_eq!(d.strokes.len(), i + 1, "one recorded stroke per mouse stroke"); - assert!(d.out == replayed_out(d), "stroke {i}: the live field must match the recorded strokes"); - } - control(&mut app, &json!({"undo": true})).unwrap(); - let d = app.distort.liquify.as_ref().unwrap(); - assert_eq!(d.strokes.len(), strokes - 1); - let differ = d.out.iter().zip(&before_last).filter(|(a, b)| a != b).count(); - assert_eq!(differ, 0, "undo restores the pixels from before the last stroke"); - } - - #[test] - fn menu_opens_the_dialog_and_routes_pointer_events() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - let r = crate::distort_ui::menu(&mut app, &ctx, "filter.liquify", &json!({})).unwrap().unwrap(); - assert!(r["liquify"]["proxy"].is_array()); - assert!(crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE)); - crate::distort_ui::pointer(&mut app, ToolEvent::Up { x: 60.0, y: 40.0 }, egui::Modifiers::NONE); - assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 1); - control(&mut app, &json!({"cancel": true})).unwrap(); - assert!(app.distort.liquify.is_none()); - assert_eq!(app.session.active().unwrap().history.past_len(), 2, "cancel records nothing"); - } - - /// A smart object with a Liquify smart filter (one stroke, mesh size 3) and a Gaussian Blur - /// above it. - fn smart_liquify_app() -> (PhotocraftApp, LayerId) { - let mut app = app_with_layer(); - app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let stroke = json!({"tool": "forwardWarp", "size": 40, "points": [[40.0, 40.0, 1.0], [48.0, 41.0, 1.0], [56.0, 40.0, 1.0]]}); - app.run("filter.liquify", json!({"strokes": [stroke], "meshSize": 3.0})).unwrap(); - app.run("filter.blur.gaussianBlur", json!({"radius": 2.0})).unwrap(); - let layer = app.session.active().unwrap().active_layer.unwrap(); - (app, layer) - } - - fn smart(app: &PhotocraftApp, layer: LayerId) -> photocraft_doc::SmartObject { - match &app.session.active().unwrap().doc.layer(layer).unwrap().content { - photocraft_doc::LayerContent::Smart(sm) => sm.clone(), - _ => panic!("not a smart object"), - } - } - - fn drag(app: &mut PhotocraftApp, from: f64, to: f64) { - for ev in [ToolEvent::Down { x: from, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: to, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: to, y: 40.0 }] { - pointer(app, ev, egui::Modifiers::NONE); - } - } - - #[test] - fn smart_filter_double_click_edits_the_recorded_liquify() { - let ctx = egui::Context::default(); - let (mut app, layer) = smart_liquify_app(); - let steps = app.session.active().unwrap().history.past_len(); - let sm = smart(&app, layer); - let recorded: Vec = serde_json::from_value(sm.smart_filters[0].params["strokes"].clone()).unwrap(); - assert_eq!(recorded.len(), 1); - - crate::smart_ui::open_editor(&mut app, &ctx, layer.0, &sm, 0); - assert!(app.ui.dialogs.is_empty(), "no generic parameter form"); - let d = app.distort.liquify.as_ref().expect("the Liquify workspace opens"); - assert_eq!((d.smart_filter, d.cell), (Some(0), 3.0)); - assert_eq!(d.strokes, recorded); - assert_eq!(d.field, LiquifyField::from_strokes(d.canvas, 3.0, &recorded)); - // The preview starts from the pixels below the filter (no liquify, no blur). - let below = photocraft_engine::smart_cmds::render_below_filter(&app.session.active().unwrap().doc, &sm, 0).unwrap().unwrap(); - assert_eq!(d.source.read_region(d.canvas), below.read_region(d.canvas)); - - drag(&mut app, 70.0, 84.0); - control(&mut app, &json!({"commit": true})).unwrap(); - assert!(app.distort.liquify.is_none()); - let sm = smart(&app, layer); - assert_eq!(sm.smart_filters.len(), 2, "edited in place, not added"); - assert_eq!(sm.smart_filters[0].command, photocraft_engine::distort_cmds::LIQUIFY); - assert_eq!(sm.smart_filters[0].params["strokes"].as_array().map(Vec::len), Some(2)); - assert_eq!(sm.smart_filters[0].params["meshSize"], json!(3.0)); - assert_eq!(sm.smart_filters[1].command, "filter.blur.gaussianBlur"); - assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); - app.run("edit.undo", json!({})).unwrap(); - assert_eq!(smart(&app, layer).smart_filters[0].params["strokes"].as_array().map(Vec::len), Some(1)); - } - - #[test] - fn smart_filter_cancel_keeps_and_restore_all_clears_the_recorded_strokes() { - let ctx = egui::Context::default(); - let (mut app, layer) = smart_liquify_app(); - let steps = app.session.active().unwrap().history.past_len(); - let params = smart(&app, layer).smart_filters[0].params.clone(); - - open_smart_filter(&mut app, &ctx, layer, 0).unwrap(); - drag(&mut app, 70.0, 84.0); - control(&mut app, &json!({"cancel": true})).unwrap(); - assert_eq!(smart(&app, layer).smart_filters[0].params, params, "Cancel leaves the filter as it was"); - assert_eq!(app.session.active().unwrap().history.past_len(), steps); - - // OK after Restore All keeps the filter, with no strokes. - open_smart_filter(&mut app, &ctx, layer, 0).unwrap(); - control(&mut app, &json!({"restoreAll": true})).unwrap(); - control(&mut app, &json!({"commit": true})).unwrap(); - let sm = smart(&app, layer); - assert_eq!(sm.smart_filters.len(), 2); - assert_eq!(sm.smart_filters[0].params["strokes"], json!([])); - assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); - } - - #[test] - fn open_smart_filter_rejects_other_filters_and_layers() { - let ctx = egui::Context::default(); - let (mut app, layer) = smart_liquify_app(); - assert!(open_smart_filter(&mut app, &ctx, layer, 1).is_err(), "the Gaussian Blur"); - assert!(open_smart_filter(&mut app, &ctx, layer, 9).is_err(), "no such filter"); - let mut plain = app_with_layer(); - let pixels = plain.session.active().unwrap().active_layer.unwrap(); - assert!(open_smart_filter(&mut plain, &ctx, pixels, 0).is_err(), "not a smart object"); - assert!(app.distort.liquify.is_none() && plain.distort.liquify.is_none()); - } - - /// OK on a smart filter that is gone: the workspace closes, the status bar shows the error and - /// the control channel returns it. - #[test] - fn smart_filter_edit_that_cannot_be_applied_reports_the_error() { - let ctx = egui::Context::default(); - let (mut app, layer) = smart_liquify_app(); - open_smart_filter(&mut app, &ctx, layer, 0).unwrap(); - drag(&mut app, 70.0, 84.0); - app.session.execute("layer.smartFilter.clearSmartFilters", json!({"layer": layer.0})).unwrap(); - let steps = app.session.active().unwrap().history.past_len(); - let r = control(&mut app, &json!({"commit": true})); - assert!(app.distort.liquify.is_none()); - assert!(app.ui.status_error); - assert!(app.ui.status.contains("no smart filters"), "{}", app.ui.status); - assert!(smart(&app, layer).smart_filters.is_empty()); - assert_eq!(app.session.active().unwrap().history.past_len(), steps); - assert_eq!(r, Err(app.ui.status.clone())); - } - - /// OK after the layer was deleted: the dialog closes, the status bar shows the error and the - /// control channel returns it. - #[test] - fn liquify_that_cannot_be_applied_reports_the_error() { - let ctx = egui::Context::default(); - let mut app = app_with_layer(); - let layer = app.session.active().unwrap().active_layer.unwrap(); - open(&mut app, &ctx).unwrap(); - drag(&mut app, 40.0, 56.0); - assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 1); - app.session.execute("layer.delete", json!({"layer": layer.0})).unwrap(); - let steps = app.session.active().unwrap().history.past_len(); - let r = control(&mut app, &json!({"commit": true})); - assert!(app.distort.liquify.is_none()); - assert!(app.ui.status_error); - assert!(!app.ui.status.is_empty()); - assert_eq!(app.session.active().unwrap().history.past_len(), steps); - assert_eq!(r, Err(app.ui.status.clone())); - } -} +mod tests; diff --git a/crates/ui-egui/src/liquify_ui/tests.rs b/crates/ui-egui/src/liquify_ui/tests.rs new file mode 100644 index 0000000000..6a6796409e --- /dev/null +++ b/crates/ui-egui/src/liquify_ui/tests.rs @@ -0,0 +1,843 @@ +use super::*; + +#[test] +fn the_brush_outline_follows_the_pointer_except_while_resizing() { + let (hover, anchor) = (pos2(30.0, 40.0), pos2(10.0, 20.0)); + assert_eq!(brush_circle_at(None, Some(hover)), Some(hover)); + assert_eq!(brush_circle_at(Some((anchor, 40.0, 50.0)), Some(hover)), Some(anchor)); + assert_eq!(brush_circle_at(Some((anchor, 40.0, 50.0)), None), Some(anchor)); + assert_eq!(brush_circle_at(None, None), None); +} + +#[test] +fn alt_right_drag_resizes_the_liquify_brush_and_does_not_paint() { + assert!(brush_resize_gesture(egui::Modifiers::ALT, true)); + assert!(brush_resize_gesture(egui::Modifiers::CTRL | egui::Modifiers::ALT, false)); + assert!(!brush_resize_gesture(egui::Modifiers::ALT, false), "Alt+left stays the tool's opposite"); + assert!(!brush_resize_gesture(egui::Modifiers::NONE, true)); + let (size, density) = resized_brush(40.0, 50.0, 25.0, crate::brush_resize::HARDNESS_TRAVEL); + assert_eq!((size, density), (65.0, 100.0)); + let (size, density) = resized_brush(40.0, 50.0, -100.0, 0.0); + assert_eq!((size, density), (1.0, 50.0)); +} + +fn app_with_layer() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 120, "height": 80, "depth": 8})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, active| { + let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for y in 10..70 { + for x in 10..110 { + let v = ((x / 5 + y / 5) % 2) as f32; + s.write_pixel(x, y, &[v, 0.3, 1.0 - v, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + app.sync_views(); + app +} + +#[test] +fn zoomed_liquify_preview_uses_only_the_visible_full_resolution_crop() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + let d = app.distort.liquify.as_mut().unwrap(); + d.zoom = 2.0; + d.center = [60.0, 40.0]; + d.update_view_preview(&ctx, ERect::from_min_size(pos2(0.0, 0.0), vec2(60.0, 40.0))); + assert_eq!(d.view_bounds, Some(Rect::new(45, 30, 75, 50))); + assert_eq!(d.view_out.len(), 30 * 20, "one preview texel per document pixel"); + assert!(d.view_tex.is_some()); + + let before = d.view_out.clone(); + let mut stroke = LiquifyStroke::new(LiquifyTool::ForwardWarp, 24.0); + stroke.points = vec![vec![50.0, 40.0, 1.0], vec![58.0, 40.0, 1.0]]; + let dirty = d.field.stroke_segment(&stroke, [50.0, 40.0, 1.0], [58.0, 40.0, 1.0]); + d.mark(dirty, false); + d.render_dirty(); + d.update_view_preview(&ctx, ERect::from_min_size(pos2(0.0, 0.0), vec2(60.0, 40.0))); + assert_ne!(d.view_out, before, "a brush update refreshes the visible source-resolution crop"); + assert!(d.preview_ms.is_finite()); +} + +/// #7609: Show Backdrop › Use and Mode, as in Photoshop: the settings, how each mode layers the +/// backdrop and the image, and what each Use shows. +#[test] +fn backdrop_use_and_mode() { + let mut o = LiquifyOpts::default(); + assert_eq!((o.backdrop_layer, o.backdrop_mode), (None, BackdropMode::InFront), "All Layers, In Front"); + o.apply(&json!({"backdropUse": 3, "backdropMode": "behind"})).unwrap(); + assert_eq!((o.backdrop_layer, o.backdrop_mode), (Some(3), BackdropMode::Behind)); + assert_eq!((&o.to_json()["backdropUse"], &o.to_json()["backdropMode"]), (&json!(3), &json!("behind"))); + o.apply(&json!({"backdropUse": "all", "backdropMode": "nope"})).unwrap(); + assert_eq!((o.backdrop_layer, o.backdrop_mode), (None, BackdropMode::Behind), "a bad mode is ignored"); + let (w, a) = (Color32::WHITE, |x: f32| Color32::from_white_alpha((x * 255.0).round() as u8)); + let l = |image, behind, front| Layering { image, behind, front }; + assert_eq!(backdrop_layering(Some(1), BackdropMode::InFront, 0.25), l(w, None, Some((1, a(0.25)))), "backdrop over the image"); + assert_eq!(backdrop_layering(Some(1), BackdropMode::Behind, 0.25), l(a(0.25), Some((1, w)), None), "image over the backdrop"); + assert_eq!(backdrop_layering(Some(1), BackdropMode::Blend, 0.25), l(a(0.75), None, Some((1, a(0.25)))), "faded together"); + assert_eq!(backdrop_layering::(None, BackdropMode::Blend, 0.25), l(w, None, None), "no backdrop: the image as is"); + // All Layers is the document with the liquified layer in it; one layer is that layer alone. + let app = app_with_layer(); + let st = app.session.active().unwrap(); + let (layer, background) = (st.active_layer.unwrap(), st.doc.layers[0].id); + let at = |doc: &Document| photocraft_compose::render(doc, Rect::new(10, 10, 11, 11)).px[0]; + let own = at(&st.doc); + assert_eq!(at(&backdrop_doc(&st.doc, None)), own, "All Layers"); + assert_eq!(at(&backdrop_doc(&st.doc, Some(layer.0))), own, "the liquified layer alone"); + assert_ne!(at(&backdrop_doc(&st.doc, Some(background.0))), own, "the Background alone"); + assert_eq!(at(&backdrop_doc(&st.doc, Some(9999))), own, "a layer that's gone: All Layers"); + // A hidden layer shows when it is the one used. + let mut hidden = (*st.doc).clone(); + hidden.layer_mut(layer).unwrap().visible = false; + assert_eq!(at(&backdrop_doc(&hidden, Some(layer.0))), own, "the hidden liquified layer, alone"); + // A remembered Use is a layer of another document: Liquify opens on All Layers. + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + app.session.prefs.edit(|p| p.dialogs.insert(REMEMBERED.into(), json!({"backdropUse": 42, "backdropMode": "blend"}))); + open(&mut app, &ctx).unwrap(); + let o = &app.distort.liquify.as_ref().unwrap().opts; + assert_eq!((o.backdrop_layer, o.backdrop_mode), (None, BackdropMode::Blend), "the mode is kept, the layer is not"); + // Over the control channel, a layer of the document is kept and one that isn't is All Layers. + let layer = app.session.active().unwrap().active_layer.unwrap().0; + control(&mut app, &json!({"backdropUse": layer})).unwrap(); + assert_eq!(app.distort.liquify.as_ref().unwrap().opts.backdrop_layer, Some(layer)); + control(&mut app, &json!({"backdropUse": 4242})).unwrap(); + assert_eq!(app.distort.liquify.as_ref().unwrap().opts.backdrop_layer, None, "no such layer: All Layers"); + control(&mut app, &json!({"backdropUse": layer})).unwrap(); + assert!(control(&mut app, &json!({"backdropUse": 4242, "tool": "nope"})).is_err()); + assert_eq!(app.distort.liquify.as_ref().unwrap().opts.backdrop_layer, None, "also when another setting fails"); +} + +/// #418: the brush settings survive Cancel, OK and Esc, and come back the next time Liquify +/// opens (also after a restart: they live in the preferences). +#[test] +fn brush_settings_are_remembered_between_uses() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + let fresh = app.distort.liquify.as_ref().unwrap().opts.clone(); + assert_eq!((fresh.density, fresh.tool), (50.0, LiquifyTool::ForwardWarp), "first use: the defaults"); + let set = json!({"tool": "twirlCw", "size": 37, "density": 85, "pressure": 60, "rate": 30, "showMesh": true, "meshSize": "large", "showBackdrop": true, "backdropOpacity": 25}); + control(&mut app, &set).unwrap(); + control(&mut app, &json!({"cancel": true})).unwrap(); + assert!(app.distort.liquify.is_none()); + open(&mut app, &ctx).unwrap(); + assert_eq!(app.distort.liquify.as_ref().unwrap().opts.to_json(), { + let mut o = LiquifyOpts::default(); + o.apply(&set).unwrap(); + o.to_json() + }); + // OK and Esc keep the latest settings too. + control(&mut app, &json!({"density": 90})).unwrap(); + commit(&mut app).unwrap(); + open(&mut app, &ctx).unwrap(); + assert_eq!(app.distort.liquify.as_ref().unwrap().opts.density, 90.0); + control(&mut app, &json!({"density": 70})).unwrap(); + cancel(&mut app); + assert_eq!(app.session.prefs().dialogs[REMEMBERED]["density"], json!(70.0)); + // A damaged preference keeps what it can and never fails to open. + app.session.prefs.edit(|p| p.dialogs.insert(REMEMBERED.into(), json!({"tool": "nope", "density": "lots", "size": 1e12, "rate": 20}))); + open(&mut app, &ctx).unwrap(); + let o = &app.distort.liquify.as_ref().unwrap().opts; + assert_eq!((o.tool, o.density, o.size, o.rate), (LiquifyTool::ForwardWarp, 50.0, 15000.0, 20.0)); + app.session.prefs.edit(|p| p.dialogs.insert(REMEMBERED.into(), json!("not an object"))); + cancel(&mut app); + assert!(open(&mut app, &ctx).is_ok()); +} + +/// Follow-up to #1494 / #1484: Alt is captured at stroke-down and stays recorded +/// through undo, redo and deterministic Liquify field reconstruction. +#[test] +fn alt_reversed_twirl_survives_replay_undo_and_redo() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + control(&mut app, &json!({"tool": "twirlCw", "size": 36, "rate": 80})).unwrap(); + + // Releasing Alt while dragging must not change the tool recorded at pointer-down. + pointer(&mut app, ToolEvent::Down { x: 53.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::ALT); + pointer(&mut app, ToolEvent::Move { x: 58.0, y: 41.0, pressure: 1.0 }, egui::Modifiers::NONE); + pointer(&mut app, ToolEvent::Up { x: 58.0, y: 41.0 }, egui::Modifiers::NONE); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.opts.tool, LiquifyTool::TwirlCw, "Alt must not change the selected tool"); + assert_eq!(d.strokes.len(), 1); + assert_eq!(d.strokes[0].tool, LiquifyTool::TwirlCcw); + assert_eq!(LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes), d.field); + + // A following stroke without Alt records the original tool. + pointer(&mut app, ToolEvent::Down { x: 70.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE); + pointer(&mut app, ToolEvent::Move { x: 75.0, y: 42.0, pressure: 1.0 }, egui::Modifiers::ALT); + pointer(&mut app, ToolEvent::Up { x: 75.0, y: 42.0 }, egui::Modifiers::ALT); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.strokes.len(), 2); + assert_eq!(d.strokes[1].tool, LiquifyTool::TwirlCw); + assert_eq!(LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes), d.field); + + control(&mut app, &json!({"undo": true})).unwrap(); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.strokes.len(), 1); + assert_eq!(d.strokes[0].tool, LiquifyTool::TwirlCcw); + assert_eq!(d.redo[0].tool, LiquifyTool::TwirlCw); + assert_eq!(LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes), d.field); + + control(&mut app, &json!({"redo": true})).unwrap(); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.strokes.len(), 2); + assert!(d.redo.is_empty()); + assert_eq!(d.strokes[0].tool, LiquifyTool::TwirlCcw); + assert_eq!(d.strokes[1].tool, LiquifyTool::TwirlCw); + assert_eq!(LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes), d.field); +} + +#[test] +fn dialog_strokes_match_the_engine_and_commit_once() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + control(&mut app, &json!({"tool": "forwardWarp", "size": 40})).unwrap(); + for ev in [ + ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, + ToolEvent::Move { x: 48.0, y: 41.0, pressure: 1.0 }, + ToolEvent::Move { x: 56.0, y: 40.0, pressure: 1.0 }, + ToolEvent::Up { x: 56.0, y: 40.0 }, + ] { + pointer(&mut app, ev, egui::Modifiers::NONE); + } + control(&mut app, &json!({"tool": "bloat"})).unwrap(); + for ev in [ToolEvent::Down { x: 80.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 80.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 80.0, y: 40.0 }] + { + pointer(&mut app, ev, egui::Modifiers::NONE); + } + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.strokes.len(), 2); + assert_eq!(d.redo.len(), 0); + // Replaying the recorded strokes gives exactly the interactive field. + let replay = LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes); + assert_eq!(replay, d.field); + assert!(d.field.max_displacement() > 3.0); + // Undo inside the dialog drops the last stroke. + control(&mut app, &json!({"undo": true})).unwrap(); + assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 1); + assert_eq!(app.distort.liquify.as_ref().unwrap().redo.len(), 1); + control(&mut app, &json!({"redo": true})).unwrap(); + assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 2); + assert_eq!(app.distort.liquify.as_ref().unwrap().redo.len(), 0); + control(&mut app, &json!({"undo": true})).unwrap(); + let before = app.session.active().unwrap().history.past_len(); + control(&mut app, &json!({"commit": true})).unwrap(); + assert!(app.distort.liquify.is_none()); + assert_eq!(app.session.active().unwrap().history.past_len(), before + 1); +} + +#[test] +fn undo_rerenders_the_proxy_before_the_next_texture_upload() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + control(&mut app, &json!({"tool": "forwardWarp", "size": 40})).unwrap(); + for ev in [ + ToolEvent::Down { x: 35.0, y: 40.0, pressure: 1.0 }, + ToolEvent::Move { x: 55.0, y: 40.0, pressure: 1.0 }, + ToolEvent::Up { x: 55.0, y: 40.0 }, + ToolEvent::Down { x: 70.0, y: 40.0, pressure: 1.0 }, + ToolEvent::Move { x: 90.0, y: 40.0, pressure: 1.0 }, + ToolEvent::Up { x: 90.0, y: 40.0 }, + ] { + pointer(&mut app, ev, egui::Modifiers::NONE); + } + + let before = app.distort.liquify.as_ref().unwrap().out.clone(); + control(&mut app, &json!({"undo": true})).unwrap(); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.strokes.len(), 1); + assert_ne!(d.out, before, "undo must update the pixels shown by the existing texture"); + + let mut expected = vec![[0u8; 4]; d.proxy.w * d.proxy.h]; + d.proxy.render(&d.field, [0, 0, d.proxy.w, d.proxy.h], &mut expected); + assert_eq!(d.out, expected, "dirty upload source must match the rebuilt field"); +} + +#[test] +fn undo_dirties_the_zoomed_preview() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + control(&mut app, &json!({"tool": "forwardWarp", "size": 40})).unwrap(); + for ev in [ToolEvent::Down { x: 35.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 55.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 55.0, y: 40.0 }] + { + pointer(&mut app, ev, egui::Modifiers::NONE); + } + { + let d = app.distort.liquify.as_mut().unwrap(); + d.zoom = 2.0; + d.view_bounds = Some(Rect::new(0, 0, 20, 20)); + d.view_dirty = None; + } + control(&mut app, &json!({"undo": true})).unwrap(); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.view_dirty, d.view_bounds); +} + +#[test] +fn liquify_redo_restores_undone_stroke_and_a_new_stroke_clears_redo() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + control(&mut app, &json!({"tool": "forwardWarp", "size": 40})).unwrap(); + let draw = |app: &mut PhotocraftApp, x: f64| { + for ev in + [ToolEvent::Down { x, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: x + 14.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: x + 14.0, y: 40.0 }] + { + pointer(app, ev, egui::Modifiers::NONE); + } + }; + + draw(&mut app, 30.0); + draw(&mut app, 70.0); + control(&mut app, &json!({"undo": true})).unwrap(); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!((d.strokes.len(), d.redo.len()), (1, 1)); + + control(&mut app, &json!({"redo": true})).unwrap(); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!((d.strokes.len(), d.redo.len()), (2, 0)); + assert_eq!(LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes), d.field); + + control(&mut app, &json!({"undo": true})).unwrap(); + draw(&mut app, 50.0); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!((d.strokes.len(), d.redo.len()), (2, 0)); + control(&mut app, &json!({"redo": true})).unwrap(); + assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 2, "redo after a new stroke is a no-op"); +} + +/// The Freeze Lasso freezes the dragged polygon (⌥ thaws it) as one recorded stroke, and a +/// new lasso clears Redo like any other stroke. +#[test] +fn freeze_lasso_records_a_stroke_and_clears_redo() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + control(&mut app, &json!({"tool": "lassoMask"})).unwrap(); + let lasso = |app: &mut PhotocraftApp, m: egui::Modifiers, r: [f64; 4]| { + pointer(app, ToolEvent::Down { x: r[0], y: r[1], pressure: 1.0 }, m); + for (x, y) in [(r[2], r[1]), (r[2], r[3]), (r[0], r[3])] { + pointer(app, ToolEvent::Move { x, y, pressure: 1.0 }, m); + } + pointer(app, ToolEvent::Up { x: r[0], y: r[3] }, m); + }; + lasso(&mut app, egui::Modifiers::NONE, [20.0, 20.0, 80.0, 60.0]); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.strokes.len(), 1); + assert_eq!(d.field.freeze_at(50.0, 40.0), 1.0, "frozen inside"); + assert_eq!(d.field.freeze_at(5.0, 5.0), 0.0, "not outside"); + lasso(&mut app, egui::Modifiers::ALT, [40.0, 30.0, 60.0, 50.0]); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.field.freeze_at(50.0, 40.0), 0.0, "⌥ thaws"); + assert_eq!(d.field.freeze_at(25.0, 25.0), 1.0); + control(&mut app, &json!({"undo": true})).unwrap(); + assert_eq!(app.distort.liquify.as_ref().unwrap().field.freeze_at(50.0, 40.0), 1.0, "undo replays the first lasso"); + assert_eq!(app.distort.liquify.as_ref().unwrap().redo.len(), 1); + lasso(&mut app, egui::Modifiers::NONE, [0.0, 0.0, 10.0, 10.0]); + assert_eq!(app.distort.liquify.as_ref().unwrap().redo.len(), 0, "a new lasso clears redo"); +} + +#[test] +fn alt_reverses_twirl_and_swaps_pucker_and_bloat() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + let dab = |app: &mut PhotocraftApp, m: egui::Modifiers| { + pointer(app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }, m); + pointer(app, ToolEvent::Up { x: 50.0, y: 40.0 }, m); + app.distort.liquify.as_ref().unwrap().strokes.last().unwrap().tool + }; + for (tool, plain, alt) in [ + ("twirlCw", LiquifyTool::TwirlCw, LiquifyTool::TwirlCcw), + ("twirlCcw", LiquifyTool::TwirlCcw, LiquifyTool::TwirlCw), + ("pucker", LiquifyTool::Pucker, LiquifyTool::Bloat), + ("bloat", LiquifyTool::Bloat, LiquifyTool::Pucker), + ("forwardWarp", LiquifyTool::ForwardWarp, LiquifyTool::ForwardWarp), + ] { + control(&mut app, &json!({"tool": tool})).unwrap(); + assert_eq!(dab(&mut app, egui::Modifiers::NONE), plain, "{tool}"); + assert_eq!(dab(&mut app, egui::Modifiers::ALT), alt, "⌥ {tool}"); + assert_eq!(app.distort.liquify.as_ref().unwrap().opts.tool, plain, "⌥ leaves the selected tool alone"); + } +} + +#[test] +fn liquify_redo_stack_is_bounded() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + let d = app.distort.liquify.as_mut().unwrap(); + d.strokes = (0..=REDO_STACK_LIMIT).map(|_| LiquifyStroke::new(LiquifyTool::ForwardWarp, 1.0)).collect(); + for _ in 0..=REDO_STACK_LIMIT { + d.undo(); + } + assert_eq!(d.redo.len(), REDO_STACK_LIMIT); +} + +/// #7884: Alt+right-dragging the brush size in the Liquify dialog keeps the brush where the +/// drag started (its outline and the point it would work at) and only changes its size, as the +/// brush tools' Alt-drag does outside Liquify. +#[test] +fn alt_drag_resize_keeps_the_brush_where_it_started() { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, Default::default()); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + let screen = ERect::from_min_size(pos2(0.0, 0.0), vec2(1400.0, 900.0)); + let frame = |app: &mut PhotocraftApp, events: Vec, mods: egui::Modifiers| { + let events = std::iter::once(egui::Event::ModifiersChanged(mods)).chain(events).collect(); + let raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + ctx.run_ui(raw, |ui| show(app, ui.ctx())).textures_delta.clear(); + }; + let alt = egui::Modifiers::ALT; + let none = egui::Modifiers::NONE; + frame(&mut app, vec![], none); + // A point over the image in the dialog's canvas (120 × 80): the first one on a grid. + let p = (1..22) + .flat_map(|j| (1..34).map(move |i| pos2(40.0 * i as f32, 40.0 * j as f32))) + .find(|&q| { + frame(&mut app, vec![egui::Event::PointerMoved(q)], none); + let h = app.distort.liquify.as_ref().and_then(|d| d.hover); + h.is_some_and(|h| (10.0..60.0).contains(&h[0]) && (20.0..60.0).contains(&h[1])) + }) + .expect("the dialog shows the image"); + frame(&mut app, vec![egui::Event::PointerMoved(p)], none); + let d = app.distort.liquify.as_ref().unwrap(); + let (start, size0) = (d.hover.expect("the pointer is over the canvas"), d.opts.size); + let button = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Secondary, pressed, modifiers: alt }; + frame(&mut app, vec![button(true)], alt); + for k in 1..=6 { + frame(&mut app, vec![egui::Event::PointerMoved(p + vec2(10.0 * k as f32, 0.0))], alt); + } + let d = app.distort.liquify.as_ref().unwrap(); + assert!(d.opts.size > size0, "the drag resized the brush: {} -> {}", size0, d.opts.size); + assert_eq!(d.hover, Some(start), "the brush stayed where the drag started"); + assert!(d.strokes.is_empty(), "and nothing was painted"); +} + +#[test] +fn shortcut_handler_undoes_liquify_even_when_egui_owns_keyboard_focus() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + for ev in [ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 52.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 52.0, y: 40.0 }] + { + pointer(&mut app, ev, egui::Modifiers::NONE); + } + assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 1); + + let raw = egui::RawInput { + events: vec![egui::Event::Key { key: egui::Key::Z, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }], + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + let ctx = ui.ctx(); + ctx.memory_mut(|m| m.request_focus(egui::Id::unique("liquify-slider-focus"))); + assert!(ctx.egui_wants_keyboard_input()); + crate::shortcuts::handle(&mut app, ctx); + }); + out.textures_delta.clear(); + assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 0); + let raw = egui::RawInput { + events: vec![egui::Event::Key { + key: egui::Key::Z, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, + }], + ..Default::default() + }; + let _ = ctx.run_ui(raw, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + }); + assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 1, "Cmd+Shift+Z redoes the last stroke"); +} + +// Regression test for #4134: Cmd+Z and Cmd+Shift+Z were ignored in Liquify while a numeric +// field's text edit (Size, Pressure, ...) had keyboard focus, so a stroke could not be undone. +#[test] +fn liquify_undo_and_redo_work_while_a_numeric_field_is_focused() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + for ev in [ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 52.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 52.0, y: 40.0 }] + { + pointer(&mut app, ev, egui::Modifiers::NONE); + } + let strokes = |app: &PhotocraftApp| app.distort.liquify.as_ref().unwrap().strokes.len(); + assert_eq!(strokes(&app), 1); + + // One frame of the real shortcut handler, then a focused single-line text edit (the + // numeric fields are text edits), as the app orders them. + let mut text = String::from("100"); + let field = egui::Id::unique("liquify-size-field"); + let mut frame = |app: &mut PhotocraftApp, events: Vec| { + let raw = egui::RawInput { events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + crate::shortcuts::handle(app, ui.ctx()); + let edit = ui.add(egui::TextEdit::singleline(&mut text).id(field)); + edit.request_focus(); + }); + out.textures_delta.clear(); + }; + frame(&mut app, Vec::new()); + assert!(ctx.text_edit_focused(), "the numeric field is a focused text edit"); + + let z = |modifiers| egui::Event::Key { key: egui::Key::Z, physical_key: None, pressed: true, repeat: false, modifiers }; + frame(&mut app, vec![z(egui::Modifiers::COMMAND)]); + assert_eq!(strokes(&app), 0, "Cmd+Z undoes the stroke with the field focused"); + frame(&mut app, vec![z(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT)]); + assert_eq!(strokes(&app), 1, "Cmd+Shift+Z redoes it"); +} + +// Regression test for #4134: other Liquify keys must not steal characters from a focused +// numeric field, and the bracket keys step the brush by at least one pixel. +#[test] +fn liquify_tool_keys_leave_a_focused_field_alone_and_brackets_reach_one_pixel() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + app.distort.liquify.as_mut().unwrap().opts.size = 2.0; + let size = |app: &PhotocraftApp| app.distort.liquify.as_ref().unwrap().opts.size; + let press = |app: &mut PhotocraftApp, key: egui::Key| { + let ev = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let mut out = ctx.run_ui(egui::RawInput { events: vec![ev], ..Default::default() }, |ui| crate::shortcuts::handle(app, ui.ctx())); + out.textures_delta.clear(); + }; + // 2 px * 0.9 used to round back to 2, so `[` never reached 1 px; `]` steps up from 1. + press(&mut app, egui::Key::OpenBracket); + assert_eq!(size(&app), 1.0, "`[` steps a 2 px brush down to 1 px"); + press(&mut app, egui::Key::CloseBracket); + assert_eq!(size(&app), 2.0, "`]` steps it back up"); + + // With a text edit focused, `[` belongs to the field. + let mut text = String::new(); + let field = egui::Id::unique("liquify-size-field"); + let focused_frame = |app: &mut PhotocraftApp, text: &mut String, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + crate::shortcuts::handle(app, ui.ctx()); + ui.add(egui::TextEdit::singleline(text).id(field)).request_focus(); + }); + out.textures_delta.clear(); + }; + focused_frame(&mut app, &mut text, Vec::new()); + assert!(ctx.text_edit_focused()); + let bracket = egui::Event::Key { key: egui::Key::OpenBracket, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + focused_frame(&mut app, &mut text, vec![bracket]); + assert_eq!(size(&app), 2.0, "the focused field keeps its keys"); +} + +fn key(key: egui::Key) -> egui::Event { + egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND } +} + +/// A frame of the open dialog in a 1000 × 700 window with `events`; returns the preview's +/// centre (between the tool strip and the options panel, under the title strip). +fn frame(app: &mut PhotocraftApp, ctx: &egui::Context, events: Vec) -> Pos2 { + let screen = ERect::from_min_size(Pos2::ZERO, vec2(1000.0, 700.0)); + let raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + pos2((LEFT_W + screen.width() - RIGHT_W) / 2.0, (30.0 + screen.height()) / 2.0) +} + +/// #7210: ⌘+ / ⌘− step Liquify's preview along the zoom ladder, ⌘0 fits it and ⌘1 is the +/// dialog's 100 %, through the canvas's own shortcuts; the canvas behind keeps its zoom. +#[test] +fn zoom_shortcuts_zoom_the_preview_not_the_canvas() { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + frame(&mut app, &ctx, Vec::new()); + let fitted = app.distort.liquify.as_ref().unwrap().zoom; + assert!(fitted > 0.0, "the preview fits on its first frame"); + let canvas_zoom = app.ui.views.first().map(|v| v.zoom); + let mut press = |k: egui::Key| { + let raw = egui::RawInput { events: vec![key(k)], ..Default::default() }; + let _ = ctx.run_ui(raw, |ui| crate::shortcuts::handle(&mut app, ui.ctx())); + app.distort.liquify.as_ref().unwrap().zoom + }; + assert_eq!(press(egui::Key::Num1), 1.0); + assert_eq!(press(egui::Key::Equals), 2.0, "next step up the ladder"); + assert_eq!(press(egui::Key::Plus), 3.0, "⌘+ typed as Plus too"); + assert_eq!(press(egui::Key::Minus), 2.0); + assert_eq!(press(egui::Key::Num0), 0.0, "fit on the next frame"); + frame(&mut app, &ctx, Vec::new()); + assert_eq!(app.distort.liquify.as_ref().unwrap().zoom, fitted); + assert_eq!(app.ui.views.first().map(|v| v.zoom), canvas_zoom, "the canvas behind keeps its zoom"); +} + +/// #7210: a trackpad pinch over the preview zooms it about the pointer (macOS sends no wheel +/// for it), unless Preferences › Enhanced Controls › Zoom with Trackpad Pinch is off; a wheel +/// notch is one ×1.1 step. +#[test] +fn pinch_and_wheel_zoom_the_preview_about_the_pointer() { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + let center = frame(&mut app, &ctx, Vec::new()); + let at = center + vec2(60.0, -40.0); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + let screen = ERect::from_min_size(Pos2::ZERO, vec2(1000.0, 700.0)); + let area = ERect::from_min_max(pos2(LEFT_W, 30.0), pos2(screen.width() - RIGHT_W, screen.height())); + let (z0, under) = { + let d = app.distort.liquify.as_ref().unwrap(); + (d.zoom, to_doc(d, area, at)) + }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), egui::Event::Zoom(2.0)]); + let d = app.distort.liquify.as_ref().unwrap(); + assert!((d.zoom - z0 * 2.0).abs() < 1e-4, "{} → {}", z0, d.zoom); + let still = to_doc(d, area, at); + assert!((still[0] - under[0]).abs() < 1e-3 && (still[1] - under[1]).abs() < 1e-3, "the point under the pointer stays: {under:?} → {still:?}"); + + // Animated Zoom off: a notch is one instant step, so one frame shows the whole ×1.1. + app.session.prefs.edit(|p| p.general.animated_zoom = false); + let notch = ctx.options(|o| o.input_options.line_scroll_speed); + let wheel = egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }; + let z1 = app.distort.liquify.as_ref().unwrap().zoom; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), wheel]); + let z2 = app.distort.liquify.as_ref().unwrap().zoom; + assert!(notch > 0.0 && (z2 / z1 - crate::wheel_nav::NOTCH).abs() < 1e-3, "one notch is ×1.1: {z1} → {z2}"); + + app.session.prefs.edit(|p| p.enhanced_controls.zoom_with_trackpad_pinch = false); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), egui::Event::Zoom(2.0)]); + assert_eq!(app.distort.liquify.as_ref().unwrap().zoom, z2, "a pinch does nothing with the preference off"); +} + +/// The proxy rendered from the recorded strokes, i.e. what undo/replay rebuilds. +fn replayed_out(d: &LiquifyDialog) -> Vec<[u8; 4]> { + let field = LiquifyField::from_strokes(d.canvas, d.cell, &d.strokes); + let mut out = vec![[0u8; 4]; d.proxy.w * d.proxy.h]; + d.proxy.render(&field, [0, 0, d.proxy.w, d.proxy.h], &mut out); + out +} + +/// #8055: a second pointer-down while a stroke is open must not drop the dabs already applied. +#[test] +fn second_down_without_up_keeps_the_open_strokes_dabs_recorded() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + control(&mut app, &json!({"tool": "forwardWarp", "size": 30})).unwrap(); + for ev in [ + ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, + ToolEvent::Move { x: 46.0, y: 41.0, pressure: 1.0 }, + ToolEvent::Down { x: 46.0, y: 41.0, pressure: 1.0 }, + ToolEvent::Move { x: 55.0, y: 42.0, pressure: 1.0 }, + ToolEvent::Up { x: 55.0, y: 42.0 }, + ] { + pointer(&mut app, ev, egui::Modifiers::NONE); + } + let d = app.distort.liquify.as_ref().unwrap(); + assert!(d.out == replayed_out(d), "the live field must match the field rebuilt from the recorded strokes"); +} + +/// #8055: short strokes drawn with the mouse (moves inside egui's drag threshold first) are +/// recorded whole, as one stroke each, so undo removes only the last one. +#[test] +fn short_mouse_strokes_are_recorded_whole_and_undo_removes_only_the_last() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + control(&mut app, &json!({"tool": "forwardWarp", "size": 30})).unwrap(); + let screen = ERect::from_min_size(pos2(0.0, 0.0), vec2(1280.0, 800.0)); + let frame = |app: &mut PhotocraftApp, events: Vec| { + let raw = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + let mut before_last = Vec::new(); + let strokes = 6; + for i in 0..strokes { + let start = pos2(560.0 + i as f32 * 25.0, 380.0 + (i % 2) as f32 * 20.0); + before_last = app.distort.liquify.as_ref().unwrap().out.clone(); + frame(&mut app, vec![egui::Event::PointerMoved(start)]); + let press = egui::Event::PointerButton { pos: start, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + frame(&mut app, vec![press]); + let mut p = start; + for _ in 0..8 { + p += vec2(1.5, 1.0); + frame(&mut app, vec![egui::Event::PointerMoved(p)]); + } + let release = egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }; + frame(&mut app, vec![release]); + frame(&mut app, vec![]); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.strokes.len(), i + 1, "one recorded stroke per mouse stroke"); + assert!(d.out == replayed_out(d), "stroke {i}: the live field must match the recorded strokes"); + } + control(&mut app, &json!({"undo": true})).unwrap(); + let d = app.distort.liquify.as_ref().unwrap(); + assert_eq!(d.strokes.len(), strokes - 1); + let differ = d.out.iter().zip(&before_last).filter(|(a, b)| a != b).count(); + assert_eq!(differ, 0, "undo restores the pixels from before the last stroke"); +} + +#[test] +fn menu_opens_the_dialog_and_routes_pointer_events() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + let r = crate::distort_ui::menu(&mut app, &ctx, "filter.liquify", &json!({})).unwrap().unwrap(); + assert!(r["liquify"]["proxy"].is_array()); + assert!(crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: 50.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE)); + crate::distort_ui::pointer(&mut app, ToolEvent::Up { x: 60.0, y: 40.0 }, egui::Modifiers::NONE); + assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 1); + control(&mut app, &json!({"cancel": true})).unwrap(); + assert!(app.distort.liquify.is_none()); + assert_eq!(app.session.active().unwrap().history.past_len(), 2, "cancel records nothing"); +} + +/// A smart object with a Liquify smart filter (one stroke, mesh size 3) and a Gaussian Blur +/// above it. +fn smart_liquify_app() -> (PhotocraftApp, LayerId) { + let mut app = app_with_layer(); + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let stroke = json!({"tool": "forwardWarp", "size": 40, "points": [[40.0, 40.0, 1.0], [48.0, 41.0, 1.0], [56.0, 40.0, 1.0]]}); + app.run("filter.liquify", json!({"strokes": [stroke], "meshSize": 3.0})).unwrap(); + app.run("filter.blur.gaussianBlur", json!({"radius": 2.0})).unwrap(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + (app, layer) +} + +fn smart(app: &PhotocraftApp, layer: LayerId) -> photocraft_doc::SmartObject { + match &app.session.active().unwrap().doc.layer(layer).unwrap().content { + photocraft_doc::LayerContent::Smart(sm) => sm.clone(), + _ => panic!("not a smart object"), + } +} + +fn drag(app: &mut PhotocraftApp, from: f64, to: f64) { + for ev in [ToolEvent::Down { x: from, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: to, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: to, y: 40.0 }] { + pointer(app, ev, egui::Modifiers::NONE); + } +} + +#[test] +fn smart_filter_double_click_edits_the_recorded_liquify() { + let ctx = egui::Context::default(); + let (mut app, layer) = smart_liquify_app(); + let steps = app.session.active().unwrap().history.past_len(); + let sm = smart(&app, layer); + let recorded: Vec = serde_json::from_value(sm.smart_filters[0].params["strokes"].clone()).unwrap(); + assert_eq!(recorded.len(), 1); + + crate::smart_ui::open_editor(&mut app, &ctx, layer.0, &sm, 0); + assert!(app.ui.dialogs.is_empty(), "no generic parameter form"); + let d = app.distort.liquify.as_ref().expect("the Liquify workspace opens"); + assert_eq!((d.smart_filter, d.cell), (Some(0), 3.0)); + assert_eq!(d.strokes, recorded); + assert_eq!(d.field, LiquifyField::from_strokes(d.canvas, 3.0, &recorded)); + // The preview starts from the pixels below the filter (no liquify, no blur). + let below = photocraft_engine::smart_cmds::render_below_filter(&app.session.active().unwrap().doc, &sm, 0).unwrap().unwrap(); + assert_eq!(d.source.read_region(d.canvas), below.read_region(d.canvas)); + + drag(&mut app, 70.0, 84.0); + control(&mut app, &json!({"commit": true})).unwrap(); + assert!(app.distort.liquify.is_none()); + let sm = smart(&app, layer); + assert_eq!(sm.smart_filters.len(), 2, "edited in place, not added"); + assert_eq!(sm.smart_filters[0].command, photocraft_engine::distort_cmds::LIQUIFY); + assert_eq!(sm.smart_filters[0].params["strokes"].as_array().map(Vec::len), Some(2)); + assert_eq!(sm.smart_filters[0].params["meshSize"], json!(3.0)); + assert_eq!(sm.smart_filters[1].command, "filter.blur.gaussianBlur"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(smart(&app, layer).smart_filters[0].params["strokes"].as_array().map(Vec::len), Some(1)); +} + +#[test] +fn smart_filter_cancel_keeps_and_restore_all_clears_the_recorded_strokes() { + let ctx = egui::Context::default(); + let (mut app, layer) = smart_liquify_app(); + let steps = app.session.active().unwrap().history.past_len(); + let params = smart(&app, layer).smart_filters[0].params.clone(); + + open_smart_filter(&mut app, &ctx, layer, 0).unwrap(); + drag(&mut app, 70.0, 84.0); + control(&mut app, &json!({"cancel": true})).unwrap(); + assert_eq!(smart(&app, layer).smart_filters[0].params, params, "Cancel leaves the filter as it was"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + + // OK after Restore All keeps the filter, with no strokes. + open_smart_filter(&mut app, &ctx, layer, 0).unwrap(); + control(&mut app, &json!({"restoreAll": true})).unwrap(); + control(&mut app, &json!({"commit": true})).unwrap(); + let sm = smart(&app, layer); + assert_eq!(sm.smart_filters.len(), 2); + assert_eq!(sm.smart_filters[0].params["strokes"], json!([])); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); +} + +#[test] +fn open_smart_filter_rejects_other_filters_and_layers() { + let ctx = egui::Context::default(); + let (mut app, layer) = smart_liquify_app(); + assert!(open_smart_filter(&mut app, &ctx, layer, 1).is_err(), "the Gaussian Blur"); + assert!(open_smart_filter(&mut app, &ctx, layer, 9).is_err(), "no such filter"); + let mut plain = app_with_layer(); + let pixels = plain.session.active().unwrap().active_layer.unwrap(); + assert!(open_smart_filter(&mut plain, &ctx, pixels, 0).is_err(), "not a smart object"); + assert!(app.distort.liquify.is_none() && plain.distort.liquify.is_none()); +} + +/// OK on a smart filter that is gone: the workspace closes, the status bar shows the error and +/// the control channel returns it. +#[test] +fn smart_filter_edit_that_cannot_be_applied_reports_the_error() { + let ctx = egui::Context::default(); + let (mut app, layer) = smart_liquify_app(); + open_smart_filter(&mut app, &ctx, layer, 0).unwrap(); + drag(&mut app, 70.0, 84.0); + app.session.execute("layer.smartFilter.clearSmartFilters", json!({"layer": layer.0})).unwrap(); + let steps = app.session.active().unwrap().history.past_len(); + let r = control(&mut app, &json!({"commit": true})); + assert!(app.distort.liquify.is_none()); + assert!(app.ui.status_error); + assert!(app.ui.status.contains("no smart filters"), "{}", app.ui.status); + assert!(smart(&app, layer).smart_filters.is_empty()); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + assert_eq!(r, Err(app.ui.status.clone())); +} + +/// OK after the layer was deleted: the dialog closes, the status bar shows the error and the +/// control channel returns it. +#[test] +fn liquify_that_cannot_be_applied_reports_the_error() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + open(&mut app, &ctx).unwrap(); + drag(&mut app, 40.0, 56.0); + assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 1); + app.session.execute("layer.delete", json!({"layer": layer.0})).unwrap(); + let steps = app.session.active().unwrap().history.past_len(); + let r = control(&mut app, &json!({"commit": true})); + assert!(app.distort.liquify.is_none()); + assert!(app.ui.status_error); + assert!(!app.ui.status.is_empty()); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + assert_eq!(r, Err(app.ui.status.clone())); +} From 20dff60e0de87ed16e7209ccd6182c0fe5744cfc Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:36 +0000 Subject: [PATCH 105/259] refactor(ui-egui): move slice_ui.rs tests to slice_ui/tests.rs --- crates/ui-egui/src/slice_ui.rs | 331 +-------------------------- crates/ui-egui/src/slice_ui/tests.rs | 328 ++++++++++++++++++++++++++ 2 files changed, 329 insertions(+), 330 deletions(-) create mode 100644 crates/ui-egui/src/slice_ui/tests.rs diff --git a/crates/ui-egui/src/slice_ui.rs b/crates/ui-egui/src/slice_ui.rs index f812f94c14..f56e330f0a 100644 --- a/crates/ui-egui/src/slice_ui.rs +++ b/crates/ui-egui/src/slice_ui.rs @@ -470,333 +470,4 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo } #[cfg(test)] -mod tests { - use super::*; - - fn app() -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); - app - } - - #[test] - fn slice_tool_draws_and_select_tool_moves() { - let mut app = app(); - app.ui.tool = Tool::Slice; - let m = egui::Modifiers::NONE; - assert!(pointer(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m)); - pointer(&mut app, ToolEvent::Move { x: 40.0, y: 30.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 40.0, y: 30.0 }, m); - let doc = app.session.active().unwrap().doc.clone(); - assert_eq!(doc.slices.list.len(), 1); - assert_eq!(doc.slices.list[0].rect, photocraft_geom::Rect::new(10, 10, 40, 30)); - let n = app.ui.slices.selected.unwrap(); - // Slice Select: drag it by (5, 5). - app.ui.tool = Tool::SliceSelect; - pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m); - assert_eq!(app.ui.slices.selected, Some(n)); - pointer(&mut app, ToolEvent::Up { x: 25.0, y: 25.0 }, m); - let doc = app.session.active().unwrap().doc.clone(); - assert_eq!(doc.slices.list[0].rect, photocraft_geom::Rect::new(15, 15, 45, 35)); - // Clicking an auto slice selects it; Slice Options promotes it. - pointer(&mut app, ToolEvent::Down { x: 90.0, y: 75.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 90.0, y: 75.0 }, m); - let r = open_options(&mut app).unwrap(); - let id = r["dialog"].as_u64().unwrap(); - app.ui.dialog_mut(id).unwrap().fields.insert("name".into(), json!("footer")); - crate::dialogs::confirm(&mut app, id).unwrap(); - let doc = app.session.active().unwrap().doc.clone(); - assert!(doc.slices.list.iter().any(|s| s.name == "footer")); - } - - /// #7865: with View › Lock Slices on, Slice Select doesn't select (or move) a slice, and the - /// Slice tool doesn't start one; both say why, as Photoshop's error does. - #[test] - fn locked_slices_cannot_be_selected() { - let mut app = app(); - let m = egui::Modifiers::NONE; - app.ui.tool = Tool::Slice; - pointer(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 40.0, y: 30.0 }, m); - let rect = app.session.active().unwrap().doc.slices.list[0].rect; - app.ui.slices.selected = None; - app.run("view.lockSlices", json!({"on": true})).unwrap(); - app.ui.tool = Tool::SliceSelect; - pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Move { x: 30.0, y: 30.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }, m); - assert_eq!(app.ui.slices.selected, None, "not selected"); - assert_eq!(app.session.active().unwrap().doc.slices.list[0].rect, rect, "not moved"); - assert!(app.ui.status_error && app.ui.status.contains("locked"), "{}", app.ui.status); - // The Slice tool says so too. - app.ui.status_error = false; - app.ui.tool = Tool::Slice; - pointer(&mut app, ToolEvent::Down { x: 50.0, y: 50.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 80.0, y: 70.0 }, m); - assert_eq!(app.session.active().unwrap().doc.slices.list.len(), 1); - assert!(app.ui.status_error && app.ui.status.contains("locked"), "{}", app.ui.status); - // Unlocked again, Slice Select selects it. - app.run("view.lockSlices", json!({"on": false})).unwrap(); - app.ui.tool = Tool::SliceSelect; - pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 20.0, y: 20.0 }, m); - assert!(app.ui.slices.selected.is_some()); - } - - /// #8360: the Slice tool's Style, as the marquee's. Fixed Ratio keeps the drag's larger extent - /// and gives the other the ratio; Fixed Size draws a slice of that size where the drag starts, - /// towards the drag, also on a plain click. - #[test] - fn slice_style_fixes_the_ratio_or_the_size() { - let mut app = app(); - app.ui.tool = Tool::Slice; - let m = egui::Modifiers::NONE; - let draw = |app: &mut PhotocraftApp, a: [f64; 2], b: [f64; 2]| { - pointer(app, ToolEvent::Down { x: a[0], y: a[1], pressure: 1.0 }, m); - pointer(app, ToolEvent::Move { x: b[0], y: b[1], pressure: 1.0 }, m); - pointer(app, ToolEvent::Up { x: b[0], y: b[1] }, m); - app.session.active().unwrap().doc.slices.list.last().unwrap().rect - }; - let o = &mut app.ui.tool_options; - (o.slice_style, o.slice_width, o.slice_height) = ("fixedRatio".into(), 2.0, 1.0); - assert_eq!(draw(&mut app, [10.0, 10.0], [30.0, 40.0]), photocraft_geom::Rect::new(10, 10, 70, 40)); - let o = &mut app.ui.tool_options; - (o.slice_style, o.slice_width, o.slice_height) = ("fixedSize".into(), 24.0, 16.0); - assert_eq!(draw(&mut app, [5.0, 5.0], [5.0, 5.0]), photocraft_geom::Rect::new(5, 5, 29, 21), "a click"); - assert_eq!(draw(&mut app, [90.0, 70.0], [80.0, 60.0]), photocraft_geom::Rect::new(66, 54, 90, 70), "up and to the left"); - // The preview while dragging shows the same rectangle the slice gets. - pointer(&mut app, ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Move { x: 41.0, y: 41.0, pressure: 1.0 }, m); - let Some(SliceDrag::New { start, cur }) = app.ui.slices.drag.clone() else { panic!("drawing a slice") }; - assert_eq!(new_rect(&app, start, cur), photocraft_geom::Rect::new(40, 40, 64, 56)); - pointer(&mut app, ToolEvent::Up { x: 41.0, y: 41.0 }, m); - // A press inside a pixel starts the slice on that pixel, still 24 x 16 pixels. - assert_eq!(draw(&mut app, [10.25, 30.75], [12.5, 31.5]), photocraft_geom::Rect::new(10, 30, 34, 46), "a press inside a pixel"); - assert_eq!( - draw(&mut app, [70.5, 70.5], [60.25, 60.25]), - photocraft_geom::Rect::new(47, 55, 71, 71), - "and towards the upper left, holding the pressed pixel" - ); - // A short drag up and to the left inside the pressed pixel goes up and to the left. - assert_eq!(draw(&mut app, [50.75, 50.75], [50.25, 50.25]), photocraft_geom::Rect::new(27, 35, 51, 51), "up-left within the pixel"); - // A Fixed Size that isn't whole pixels (from a settings file) is rounded, not grown a pixel. - let o = &mut app.ui.tool_options; - (o.slice_width, o.slice_height) = (1.5, 2.4); - assert_eq!(draw(&mut app, [5.5, 5.5], [5.5, 5.5]), photocraft_geom::Rect::new(5, 5, 7, 7), "1.5 x 2.4 is 2 x 2"); - // A size of a pixel or two is made too, not taken for a click that selects. - let o = &mut app.ui.tool_options; - (o.slice_width, o.slice_height) = (1.0, 2.0); - assert_eq!(draw(&mut app, [3.0, 3.0], [3.0, 3.0]), photocraft_geom::Rect::new(3, 3, 4, 5), "a 1 x 2 slice"); - } - - /// #8360: Fixed Ratio's longer side follows a fractional drag to the pixel and the shorter takes - /// the ratio from it, as close as whole pixels allow. - #[test] - fn fixed_ratio_slices_keep_their_ratio_from_a_fractional_drag() { - let mut app = app(); - app.ui.tool = Tool::Slice; - let m = egui::Modifiers::NONE; - let mut draw = |w: f32, h: f32, a: [f64; 2], b: [f64; 2]| { - let o = &mut app.ui.tool_options; - (o.slice_style, o.slice_width, o.slice_height) = ("fixedRatio".into(), w, h); - pointer(&mut app, ToolEvent::Down { x: a[0], y: a[1], pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: b[0], y: b[1] }, m); - let r = app.session.active().unwrap().doc.slices.list.last().unwrap().rect; - (r.x0, r.y0, r.width(), r.height()) - }; - assert_eq!(draw(2.0, 1.0, [10.5, 10.5], [14.5, 11.0]), (10, 10, 4, 2), "not 5 x 2"); - assert_eq!(draw(2.0, 1.0, [10.5, 10.5], [31.3, 13.0]), (10, 10, 21, 11), "a 20.8 px drag: 21 px, and half of it as near as pixels allow"); - assert_eq!(draw(16.0, 9.0, [0.5, 0.5], [40.3, 10.0]), (0, 0, 40, 23), "a 39.8 px drag"); - assert_eq!(draw(1366.0, 768.0, [0.0, 0.0], [40.0, 1.0]), (0, 0, 40, 22), "not in steps of 683 px"); - assert_eq!(draw(9.0, 16.0, [0.0, 0.0], [1.0, 32.2]), (0, 0, 18, 32), "the longer side is the height"); - assert_eq!(draw(4.0, 2.0, [60.7, 60.7], [50.2, 58.0]), (50, 55, 11, 6), "towards the upper left, holding the pressed pixel"); - assert_eq!(draw(1.5, 1.0, [0.0, 40.0], [30.0, 41.0]), (0, 40, 30, 20), "a fractional ratio"); - // A click inside a pixel doesn't move the pointer: it selects, as with Normal, and makes no - // slice (the drag is measured from the press, not from the pixel's corner). - let n = app.session.active().unwrap().doc.slices.list.len(); - let o = &mut app.ui.tool_options; - (o.slice_width, o.slice_height) = (4.0, 1.0); - pointer(&mut app, ToolEvent::Down { x: 10.75, y: 10.75, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 10.75, y: 10.75 }, m); - assert_eq!(app.session.active().unwrap().doc.slices.list.len(), n, "a click makes no slice"); - } - - /// #8360: remembered Slice tool options are checked when loaded: an unknown Style is Normal - /// again, and Fixed Size is whole pixels. - #[test] - fn remembered_slice_options_are_checked() { - let mut o = crate::state::ToolOptions::default(); - (o.slice_style, o.slice_width, o.slice_height) = ("fixedsize".into(), 0.5, 2.0); - crate::tool_memory::sanitize(&mut o); - assert_eq!(o.slice_style, "normal"); - (o.slice_style, o.slice_width, o.slice_height) = ("fixedSize".into(), 1.5, 63.6); - crate::tool_memory::sanitize(&mut o); - assert_eq!((o.slice_width, o.slice_height), (2.0, 64.0)); - } - - /// #8360: the options bar's Style picks Fixed Size, which starts at 64 × 64 px, and the slice - /// drawn next has that size. - #[test] - fn options_bar_picks_the_slice_style() { - use egui::accesskit::Role; - use egui_kittest::Harness; - use egui_kittest::kittest::{NodeT, Queryable}; - - let mut app = app(); - app.sync_views(); - app.ui.tool = Tool::Slice; - let mut h = Harness::builder().with_size(vec2(1400.0, 200.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - crate::panels::options_bar(app, ui); - } - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); - h.run_steps(4); - let fields = |h: &Harness<'static, PhotocraftApp>| { - h.query_all_by_role(Role::SpinButton) - .filter(|n| !n.accesskit_node().is_disabled()) - .filter_map(|n| n.accesskit_node().numeric_value()) - .collect::>() - }; - assert!(fields(&h).is_empty(), "Normal has no Width or Height to set"); - h.get_all_by_role(Role::ComboBox).find(|n| n.accesskit_node().value().as_deref() == Some("Normal")).unwrap().click(); - h.run_steps(3); - h.get_by_label("Fixed Size").click(); - h.run_steps(4); - let o = &h.state().ui.tool_options; - assert_eq!((o.slice_style.as_str(), o.slice_width, o.slice_height), ("fixedSize", 64.0, 64.0)); - assert_eq!(fields(&h), [64.0, 64.0]); - let (app, m) = (h.state_mut(), egui::Modifiers::NONE); - pointer(app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m); - pointer(app, ToolEvent::Up { x: 10.0, y: 10.0 }, m); - assert_eq!(app.session.active().unwrap().doc.slices.list[0].rect, photocraft_geom::Rect::new(10, 10, 74, 74)); - } - - #[test] - fn dragging_a_piece_moves_the_whole_covered_slice() { - // #7770: the slice under a later one is drawn as pieces; dragging one moves all of it. - let mut app = app(); - app.run("slice.new", json!({"rect": [0, 0, 60, 60]})).unwrap(); - app.run("slice.new", json!({"rect": [40, 40, 20, 20]})).unwrap(); - app.ui.tool = Tool::SliceSelect; - let m = egui::Modifiers::NONE; - pointer(&mut app, ToolEvent::Down { x: 10.0, y: 50.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 15.0, y: 50.0 }, m); - let doc = app.session.active().unwrap().doc.clone(); - assert_eq!(doc.slices.list[0].rect, photocraft_geom::Rect::new(5, 0, 65, 60)); - } - - #[test] - fn handles_resize_the_edges_they_hang_off() { - let r = photocraft_geom::Rect::new(10, 10, 40, 30); - assert_eq!(handle_at(r, [10.5, 9.0], 2.0), Some([-1, -1])); - assert_eq!(handle_at(r, [25.0, 30.0], 2.0), Some([0, 1])); - assert_eq!(handle_at(r, [40.0, 20.0], 2.0), Some([1, 0])); - assert_eq!(handle_at(r, [25.0, 20.0], 2.0), None, "the middle is no handle"); - assert_eq!(resized(r, [1, 0], 5, 9), photocraft_geom::Rect::new(10, 10, 45, 30), "the right edge only"); - assert_eq!(resized(r, [-1, 1], -4, 6), photocraft_geom::Rect::new(6, 10, 40, 36)); - assert_eq!(resized(r, [-1, 0], 50, 0), photocraft_geom::Rect::new(40, 10, 60, 30), "dragged past the other edge"); - assert_eq!(resized(r, [1, 0], -30, 0), photocraft_geom::Rect::new(10, 10, 11, 30), "never empty"); - } - - /// #7863: with Slice Select, dragging a handle of the selected slice resizes it; the middle - /// still moves it, and locked slices keep their size. - #[test] - fn slice_select_handles_resize_the_slice() { - let mut app = app(); - let m = egui::Modifiers::NONE; - app.ui.tool = Tool::Slice; - pointer(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 40.0, y: 30.0 }, m); - app.ui.tool = Tool::SliceSelect; - let rect = |app: &PhotocraftApp| app.session.active().unwrap().doc.slices.list[0].rect; - // The bottom-right corner. - pointer(&mut app, ToolEvent::Down { x: 40.0, y: 30.0, pressure: 1.0 }, m); - assert!(matches!(app.ui.slices.drag, Some(SliceDrag::Resize { handle: [1, 1], .. }))); - pointer(&mut app, ToolEvent::Move { x: 50.0, y: 45.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 50.0, y: 45.0 }, m); - assert_eq!(rect(&app), photocraft_geom::Rect::new(10, 10, 50, 45)); - assert!(app.ui.slices.selected.is_some(), "still selected"); - // The left edge's middle. - pointer(&mut app, ToolEvent::Down { x: 10.0, y: 27.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 4.0, y: 60.0 }, m); - assert_eq!(rect(&app), photocraft_geom::Rect::new(4, 10, 50, 45), "only the left edge moves"); - // Inside, away from the handles, it still moves. - pointer(&mut app, ToolEvent::Down { x: 30.0, y: 20.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 32.0, y: 21.0 }, m); - assert_eq!(rect(&app), photocraft_geom::Rect::new(6, 11, 52, 46)); - // Locked: the handle doesn't resize. - app.run("view.lockSlices", json!({"on": true})).unwrap(); - pointer(&mut app, ToolEvent::Down { x: 52.0, y: 46.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 70.0, y: 70.0 }, m); - assert_eq!(rect(&app), photocraft_geom::Rect::new(6, 11, 52, 46)); - } - - /// Delete through the app's shortcut handling, as the canvas gets it. - fn press(app: &mut PhotocraftApp, key: egui::Key) { - let ctx = egui::Context::default(); - let m = egui::Modifiers::NONE; - let raw = egui::RawInput { - events: vec![egui::Event::ModifiersChanged(m), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: m }], - ..Default::default() - }; - ctx.begin_pass(raw); - crate::shortcuts::handle(app, &ctx); - ctx.end_pass().textures_delta.clear(); - } - - /// #7862: with Slice Select, Delete (or Backspace) deletes the selected slice, never the - /// layer: in a one-layer document that used to fail with "a document must keep at least one - /// layer". Locked slices refuse; an auto slice has nothing to delete. - #[test] - fn delete_deletes_the_selected_slice_not_the_layer() { - let m = egui::Modifiers::NONE; - for key in [egui::Key::Delete, egui::Key::Backspace] { - let mut app = app(); - let layers = app.session.active().unwrap().doc.layers.len(); - app.ui.tool = Tool::Slice; - pointer(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 40.0, y: 30.0 }, m); - app.ui.tool = Tool::SliceSelect; - pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 20.0, y: 20.0 }, m); - assert!(app.ui.slices.selected.is_some()); - - // Locked: the slice stays, and says why. - app.run("view.lockSlices", json!({"on": true})).unwrap(); - press(&mut app, key); - assert_eq!(app.session.active().unwrap().doc.slices.list.len(), 1, "{key:?}: locked"); - assert!(app.ui.status_error && app.ui.status.contains("locked"), "{key:?}: {}", app.ui.status); - app.run("view.lockSlices", json!({"on": false})).unwrap(); - app.ui.status_error = false; - - press(&mut app, key); - let doc = app.session.active().unwrap().doc.clone(); - assert!(doc.slices.list.is_empty(), "{key:?}: the slice is deleted"); - assert_eq!(doc.layers.len(), layers, "{key:?}: the layer stays"); - assert!(!app.ui.status_error, "{key:?}: {}", app.ui.status); - assert_eq!(app.ui.slices.selected, None); - - // An auto slice: nothing to delete, and still not the layer. - pointer(&mut app, ToolEvent::Down { x: 90.0, y: 75.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 90.0, y: 75.0 }, m); - press(&mut app, key); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "{key:?}: auto slice"); - assert!(!app.ui.status_error, "{key:?}: {}", app.ui.status); - } - } - - #[test] - fn locked_slices_ignore_gestures() { - let mut app = app(); - app.run("view.lockSlices", json!({"on": true})).unwrap(); - app.ui.tool = Tool::Slice; - let m = egui::Modifiers::NONE; - pointer(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m); - pointer(&mut app, ToolEvent::Up { x: 40.0, y: 30.0 }, m); - assert!(app.session.active().unwrap().doc.slices.is_empty()); - } -} +mod tests; diff --git a/crates/ui-egui/src/slice_ui/tests.rs b/crates/ui-egui/src/slice_ui/tests.rs new file mode 100644 index 0000000000..51c9b67e17 --- /dev/null +++ b/crates/ui-egui/src/slice_ui/tests.rs @@ -0,0 +1,328 @@ +use super::*; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); + app +} + +#[test] +fn slice_tool_draws_and_select_tool_moves() { + let mut app = app(); + app.ui.tool = Tool::Slice; + let m = egui::Modifiers::NONE; + assert!(pointer(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m)); + pointer(&mut app, ToolEvent::Move { x: 40.0, y: 30.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 40.0, y: 30.0 }, m); + let doc = app.session.active().unwrap().doc.clone(); + assert_eq!(doc.slices.list.len(), 1); + assert_eq!(doc.slices.list[0].rect, photocraft_geom::Rect::new(10, 10, 40, 30)); + let n = app.ui.slices.selected.unwrap(); + // Slice Select: drag it by (5, 5). + app.ui.tool = Tool::SliceSelect; + pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m); + assert_eq!(app.ui.slices.selected, Some(n)); + pointer(&mut app, ToolEvent::Up { x: 25.0, y: 25.0 }, m); + let doc = app.session.active().unwrap().doc.clone(); + assert_eq!(doc.slices.list[0].rect, photocraft_geom::Rect::new(15, 15, 45, 35)); + // Clicking an auto slice selects it; Slice Options promotes it. + pointer(&mut app, ToolEvent::Down { x: 90.0, y: 75.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 90.0, y: 75.0 }, m); + let r = open_options(&mut app).unwrap(); + let id = r["dialog"].as_u64().unwrap(); + app.ui.dialog_mut(id).unwrap().fields.insert("name".into(), json!("footer")); + crate::dialogs::confirm(&mut app, id).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + assert!(doc.slices.list.iter().any(|s| s.name == "footer")); +} + +/// #7865: with View › Lock Slices on, Slice Select doesn't select (or move) a slice, and the +/// Slice tool doesn't start one; both say why, as Photoshop's error does. +#[test] +fn locked_slices_cannot_be_selected() { + let mut app = app(); + let m = egui::Modifiers::NONE; + app.ui.tool = Tool::Slice; + pointer(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 40.0, y: 30.0 }, m); + let rect = app.session.active().unwrap().doc.slices.list[0].rect; + app.ui.slices.selected = None; + app.run("view.lockSlices", json!({"on": true})).unwrap(); + app.ui.tool = Tool::SliceSelect; + pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Move { x: 30.0, y: 30.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }, m); + assert_eq!(app.ui.slices.selected, None, "not selected"); + assert_eq!(app.session.active().unwrap().doc.slices.list[0].rect, rect, "not moved"); + assert!(app.ui.status_error && app.ui.status.contains("locked"), "{}", app.ui.status); + // The Slice tool says so too. + app.ui.status_error = false; + app.ui.tool = Tool::Slice; + pointer(&mut app, ToolEvent::Down { x: 50.0, y: 50.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 80.0, y: 70.0 }, m); + assert_eq!(app.session.active().unwrap().doc.slices.list.len(), 1); + assert!(app.ui.status_error && app.ui.status.contains("locked"), "{}", app.ui.status); + // Unlocked again, Slice Select selects it. + app.run("view.lockSlices", json!({"on": false})).unwrap(); + app.ui.tool = Tool::SliceSelect; + pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 20.0, y: 20.0 }, m); + assert!(app.ui.slices.selected.is_some()); +} + +/// #8360: the Slice tool's Style, as the marquee's. Fixed Ratio keeps the drag's larger extent +/// and gives the other the ratio; Fixed Size draws a slice of that size where the drag starts, +/// towards the drag, also on a plain click. +#[test] +fn slice_style_fixes_the_ratio_or_the_size() { + let mut app = app(); + app.ui.tool = Tool::Slice; + let m = egui::Modifiers::NONE; + let draw = |app: &mut PhotocraftApp, a: [f64; 2], b: [f64; 2]| { + pointer(app, ToolEvent::Down { x: a[0], y: a[1], pressure: 1.0 }, m); + pointer(app, ToolEvent::Move { x: b[0], y: b[1], pressure: 1.0 }, m); + pointer(app, ToolEvent::Up { x: b[0], y: b[1] }, m); + app.session.active().unwrap().doc.slices.list.last().unwrap().rect + }; + let o = &mut app.ui.tool_options; + (o.slice_style, o.slice_width, o.slice_height) = ("fixedRatio".into(), 2.0, 1.0); + assert_eq!(draw(&mut app, [10.0, 10.0], [30.0, 40.0]), photocraft_geom::Rect::new(10, 10, 70, 40)); + let o = &mut app.ui.tool_options; + (o.slice_style, o.slice_width, o.slice_height) = ("fixedSize".into(), 24.0, 16.0); + assert_eq!(draw(&mut app, [5.0, 5.0], [5.0, 5.0]), photocraft_geom::Rect::new(5, 5, 29, 21), "a click"); + assert_eq!(draw(&mut app, [90.0, 70.0], [80.0, 60.0]), photocraft_geom::Rect::new(66, 54, 90, 70), "up and to the left"); + // The preview while dragging shows the same rectangle the slice gets. + pointer(&mut app, ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Move { x: 41.0, y: 41.0, pressure: 1.0 }, m); + let Some(SliceDrag::New { start, cur }) = app.ui.slices.drag.clone() else { panic!("drawing a slice") }; + assert_eq!(new_rect(&app, start, cur), photocraft_geom::Rect::new(40, 40, 64, 56)); + pointer(&mut app, ToolEvent::Up { x: 41.0, y: 41.0 }, m); + // A press inside a pixel starts the slice on that pixel, still 24 x 16 pixels. + assert_eq!(draw(&mut app, [10.25, 30.75], [12.5, 31.5]), photocraft_geom::Rect::new(10, 30, 34, 46), "a press inside a pixel"); + assert_eq!( + draw(&mut app, [70.5, 70.5], [60.25, 60.25]), + photocraft_geom::Rect::new(47, 55, 71, 71), + "and towards the upper left, holding the pressed pixel" + ); + // A short drag up and to the left inside the pressed pixel goes up and to the left. + assert_eq!(draw(&mut app, [50.75, 50.75], [50.25, 50.25]), photocraft_geom::Rect::new(27, 35, 51, 51), "up-left within the pixel"); + // A Fixed Size that isn't whole pixels (from a settings file) is rounded, not grown a pixel. + let o = &mut app.ui.tool_options; + (o.slice_width, o.slice_height) = (1.5, 2.4); + assert_eq!(draw(&mut app, [5.5, 5.5], [5.5, 5.5]), photocraft_geom::Rect::new(5, 5, 7, 7), "1.5 x 2.4 is 2 x 2"); + // A size of a pixel or two is made too, not taken for a click that selects. + let o = &mut app.ui.tool_options; + (o.slice_width, o.slice_height) = (1.0, 2.0); + assert_eq!(draw(&mut app, [3.0, 3.0], [3.0, 3.0]), photocraft_geom::Rect::new(3, 3, 4, 5), "a 1 x 2 slice"); +} + +/// #8360: Fixed Ratio's longer side follows a fractional drag to the pixel and the shorter takes +/// the ratio from it, as close as whole pixels allow. +#[test] +fn fixed_ratio_slices_keep_their_ratio_from_a_fractional_drag() { + let mut app = app(); + app.ui.tool = Tool::Slice; + let m = egui::Modifiers::NONE; + let mut draw = |w: f32, h: f32, a: [f64; 2], b: [f64; 2]| { + let o = &mut app.ui.tool_options; + (o.slice_style, o.slice_width, o.slice_height) = ("fixedRatio".into(), w, h); + pointer(&mut app, ToolEvent::Down { x: a[0], y: a[1], pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: b[0], y: b[1] }, m); + let r = app.session.active().unwrap().doc.slices.list.last().unwrap().rect; + (r.x0, r.y0, r.width(), r.height()) + }; + assert_eq!(draw(2.0, 1.0, [10.5, 10.5], [14.5, 11.0]), (10, 10, 4, 2), "not 5 x 2"); + assert_eq!(draw(2.0, 1.0, [10.5, 10.5], [31.3, 13.0]), (10, 10, 21, 11), "a 20.8 px drag: 21 px, and half of it as near as pixels allow"); + assert_eq!(draw(16.0, 9.0, [0.5, 0.5], [40.3, 10.0]), (0, 0, 40, 23), "a 39.8 px drag"); + assert_eq!(draw(1366.0, 768.0, [0.0, 0.0], [40.0, 1.0]), (0, 0, 40, 22), "not in steps of 683 px"); + assert_eq!(draw(9.0, 16.0, [0.0, 0.0], [1.0, 32.2]), (0, 0, 18, 32), "the longer side is the height"); + assert_eq!(draw(4.0, 2.0, [60.7, 60.7], [50.2, 58.0]), (50, 55, 11, 6), "towards the upper left, holding the pressed pixel"); + assert_eq!(draw(1.5, 1.0, [0.0, 40.0], [30.0, 41.0]), (0, 40, 30, 20), "a fractional ratio"); + // A click inside a pixel doesn't move the pointer: it selects, as with Normal, and makes no + // slice (the drag is measured from the press, not from the pixel's corner). + let n = app.session.active().unwrap().doc.slices.list.len(); + let o = &mut app.ui.tool_options; + (o.slice_width, o.slice_height) = (4.0, 1.0); + pointer(&mut app, ToolEvent::Down { x: 10.75, y: 10.75, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 10.75, y: 10.75 }, m); + assert_eq!(app.session.active().unwrap().doc.slices.list.len(), n, "a click makes no slice"); +} + +/// #8360: remembered Slice tool options are checked when loaded: an unknown Style is Normal +/// again, and Fixed Size is whole pixels. +#[test] +fn remembered_slice_options_are_checked() { + let mut o = crate::state::ToolOptions::default(); + (o.slice_style, o.slice_width, o.slice_height) = ("fixedsize".into(), 0.5, 2.0); + crate::tool_memory::sanitize(&mut o); + assert_eq!(o.slice_style, "normal"); + (o.slice_style, o.slice_width, o.slice_height) = ("fixedSize".into(), 1.5, 63.6); + crate::tool_memory::sanitize(&mut o); + assert_eq!((o.slice_width, o.slice_height), (2.0, 64.0)); +} + +/// #8360: the options bar's Style picks Fixed Size, which starts at 64 × 64 px, and the slice +/// drawn next has that size. +#[test] +fn options_bar_picks_the_slice_style() { + use egui::accesskit::Role; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + let mut app = app(); + app.sync_views(); + app.ui.tool = Tool::Slice; + let mut h = Harness::builder().with_size(vec2(1400.0, 200.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + crate::panels::options_bar(app, ui); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); + h.run_steps(4); + let fields = |h: &Harness<'static, PhotocraftApp>| { + h.query_all_by_role(Role::SpinButton) + .filter(|n| !n.accesskit_node().is_disabled()) + .filter_map(|n| n.accesskit_node().numeric_value()) + .collect::>() + }; + assert!(fields(&h).is_empty(), "Normal has no Width or Height to set"); + h.get_all_by_role(Role::ComboBox).find(|n| n.accesskit_node().value().as_deref() == Some("Normal")).unwrap().click(); + h.run_steps(3); + h.get_by_label("Fixed Size").click(); + h.run_steps(4); + let o = &h.state().ui.tool_options; + assert_eq!((o.slice_style.as_str(), o.slice_width, o.slice_height), ("fixedSize", 64.0, 64.0)); + assert_eq!(fields(&h), [64.0, 64.0]); + let (app, m) = (h.state_mut(), egui::Modifiers::NONE); + pointer(app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m); + pointer(app, ToolEvent::Up { x: 10.0, y: 10.0 }, m); + assert_eq!(app.session.active().unwrap().doc.slices.list[0].rect, photocraft_geom::Rect::new(10, 10, 74, 74)); +} + +#[test] +fn dragging_a_piece_moves_the_whole_covered_slice() { + // #7770: the slice under a later one is drawn as pieces; dragging one moves all of it. + let mut app = app(); + app.run("slice.new", json!({"rect": [0, 0, 60, 60]})).unwrap(); + app.run("slice.new", json!({"rect": [40, 40, 20, 20]})).unwrap(); + app.ui.tool = Tool::SliceSelect; + let m = egui::Modifiers::NONE; + pointer(&mut app, ToolEvent::Down { x: 10.0, y: 50.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 15.0, y: 50.0 }, m); + let doc = app.session.active().unwrap().doc.clone(); + assert_eq!(doc.slices.list[0].rect, photocraft_geom::Rect::new(5, 0, 65, 60)); +} + +#[test] +fn handles_resize_the_edges_they_hang_off() { + let r = photocraft_geom::Rect::new(10, 10, 40, 30); + assert_eq!(handle_at(r, [10.5, 9.0], 2.0), Some([-1, -1])); + assert_eq!(handle_at(r, [25.0, 30.0], 2.0), Some([0, 1])); + assert_eq!(handle_at(r, [40.0, 20.0], 2.0), Some([1, 0])); + assert_eq!(handle_at(r, [25.0, 20.0], 2.0), None, "the middle is no handle"); + assert_eq!(resized(r, [1, 0], 5, 9), photocraft_geom::Rect::new(10, 10, 45, 30), "the right edge only"); + assert_eq!(resized(r, [-1, 1], -4, 6), photocraft_geom::Rect::new(6, 10, 40, 36)); + assert_eq!(resized(r, [-1, 0], 50, 0), photocraft_geom::Rect::new(40, 10, 60, 30), "dragged past the other edge"); + assert_eq!(resized(r, [1, 0], -30, 0), photocraft_geom::Rect::new(10, 10, 11, 30), "never empty"); +} + +/// #7863: with Slice Select, dragging a handle of the selected slice resizes it; the middle +/// still moves it, and locked slices keep their size. +#[test] +fn slice_select_handles_resize_the_slice() { + let mut app = app(); + let m = egui::Modifiers::NONE; + app.ui.tool = Tool::Slice; + pointer(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 40.0, y: 30.0 }, m); + app.ui.tool = Tool::SliceSelect; + let rect = |app: &PhotocraftApp| app.session.active().unwrap().doc.slices.list[0].rect; + // The bottom-right corner. + pointer(&mut app, ToolEvent::Down { x: 40.0, y: 30.0, pressure: 1.0 }, m); + assert!(matches!(app.ui.slices.drag, Some(SliceDrag::Resize { handle: [1, 1], .. }))); + pointer(&mut app, ToolEvent::Move { x: 50.0, y: 45.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 50.0, y: 45.0 }, m); + assert_eq!(rect(&app), photocraft_geom::Rect::new(10, 10, 50, 45)); + assert!(app.ui.slices.selected.is_some(), "still selected"); + // The left edge's middle. + pointer(&mut app, ToolEvent::Down { x: 10.0, y: 27.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 4.0, y: 60.0 }, m); + assert_eq!(rect(&app), photocraft_geom::Rect::new(4, 10, 50, 45), "only the left edge moves"); + // Inside, away from the handles, it still moves. + pointer(&mut app, ToolEvent::Down { x: 30.0, y: 20.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 32.0, y: 21.0 }, m); + assert_eq!(rect(&app), photocraft_geom::Rect::new(6, 11, 52, 46)); + // Locked: the handle doesn't resize. + app.run("view.lockSlices", json!({"on": true})).unwrap(); + pointer(&mut app, ToolEvent::Down { x: 52.0, y: 46.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 70.0, y: 70.0 }, m); + assert_eq!(rect(&app), photocraft_geom::Rect::new(6, 11, 52, 46)); +} + +/// Delete through the app's shortcut handling, as the canvas gets it. +fn press(app: &mut PhotocraftApp, key: egui::Key) { + let ctx = egui::Context::default(); + let m = egui::Modifiers::NONE; + let raw = egui::RawInput { + events: vec![egui::Event::ModifiersChanged(m), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: m }], + ..Default::default() + }; + ctx.begin_pass(raw); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +/// #7862: with Slice Select, Delete (or Backspace) deletes the selected slice, never the +/// layer: in a one-layer document that used to fail with "a document must keep at least one +/// layer". Locked slices refuse; an auto slice has nothing to delete. +#[test] +fn delete_deletes_the_selected_slice_not_the_layer() { + let m = egui::Modifiers::NONE; + for key in [egui::Key::Delete, egui::Key::Backspace] { + let mut app = app(); + let layers = app.session.active().unwrap().doc.layers.len(); + app.ui.tool = Tool::Slice; + pointer(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 40.0, y: 30.0 }, m); + app.ui.tool = Tool::SliceSelect; + pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 20.0, y: 20.0 }, m); + assert!(app.ui.slices.selected.is_some()); + + // Locked: the slice stays, and says why. + app.run("view.lockSlices", json!({"on": true})).unwrap(); + press(&mut app, key); + assert_eq!(app.session.active().unwrap().doc.slices.list.len(), 1, "{key:?}: locked"); + assert!(app.ui.status_error && app.ui.status.contains("locked"), "{key:?}: {}", app.ui.status); + app.run("view.lockSlices", json!({"on": false})).unwrap(); + app.ui.status_error = false; + + press(&mut app, key); + let doc = app.session.active().unwrap().doc.clone(); + assert!(doc.slices.list.is_empty(), "{key:?}: the slice is deleted"); + assert_eq!(doc.layers.len(), layers, "{key:?}: the layer stays"); + assert!(!app.ui.status_error, "{key:?}: {}", app.ui.status); + assert_eq!(app.ui.slices.selected, None); + + // An auto slice: nothing to delete, and still not the layer. + pointer(&mut app, ToolEvent::Down { x: 90.0, y: 75.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 90.0, y: 75.0 }, m); + press(&mut app, key); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "{key:?}: auto slice"); + assert!(!app.ui.status_error, "{key:?}: {}", app.ui.status); + } +} + +#[test] +fn locked_slices_ignore_gestures() { + let mut app = app(); + app.run("view.lockSlices", json!({"on": true})).unwrap(); + app.ui.tool = Tool::Slice; + let m = egui::Modifiers::NONE; + pointer(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m); + pointer(&mut app, ToolEvent::Up { x: 40.0, y: 30.0 }, m); + assert!(app.session.active().unwrap().doc.slices.is_empty()); +} From efae6f4f80fb4314cfb6d85b335860626545694b Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:37 +0000 Subject: [PATCH 106/259] refactor(ui-egui): move shortcuts.rs tests to shortcuts/tests.rs --- crates/ui-egui/src/shortcuts.rs | 486 +------------------------- crates/ui-egui/src/shortcuts/tests.rs | 483 +++++++++++++++++++++++++ 2 files changed, 484 insertions(+), 485 deletions(-) create mode 100644 crates/ui-egui/src/shortcuts/tests.rs diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 258b833819..807f748a49 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -856,488 +856,4 @@ fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn tool_key_brings_back_the_groups_last_used_tool() { - use crate::state::Tool; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - let press = |app: &mut PhotocraftApp, key, 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(); - }; - // Plain-key cycling (the pref is on by default, as in Photoshop). - app.session.edit_prefs(|p| p.tools.use_shift_key_for_tool_switch = false); - // Polygonal Lasso picked from the toolbar flyout, then the Brush (#2608). - app.ui.tool = Tool::PolygonLasso; - press(&mut app, Key::B, Modifiers::NONE); - assert_eq!(app.ui.tool, Tool::Brush); - press(&mut app, Key::L, Modifiers::NONE); - assert_eq!(app.ui.tool, Tool::PolygonLasso); - // Within the group, L still cycles; leaving and coming back keeps the new pick. - press(&mut app, Key::L, Modifiers::NONE); - assert_eq!(app.ui.tool, Tool::MagneticLasso); - press(&mut app, Key::M, Modifiers::NONE); - assert_eq!(app.ui.tool, Tool::RectMarquee); - press(&mut app, Key::L, Modifiers::NONE); - assert_eq!(app.ui.tool, Tool::MagneticLasso); - // Use Shift Key for Tool Switch: the plain key also returns to the last-used tool. - app.session.edit_prefs(|p| p.tools.use_shift_key_for_tool_switch = true); - press(&mut app, Key::B, Modifiers::NONE); - press(&mut app, Key::L, Modifiers::NONE); - assert_eq!(app.ui.tool, Tool::MagneticLasso); - } - - /// #3296: by default T keeps the current type tool and only Shift+T cycles, as in Photoshop. - #[test] - fn shift_key_tool_switch_is_the_default() { - use crate::state::Tool; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ctx = egui::Context::default(); - let press = |app: &mut PhotocraftApp, modifiers| { - let raw = egui::RawInput { - events: vec![ - egui::Event::ModifiersChanged(modifiers), - egui::Event::Key { key: Key::T, physical_key: None, pressed: true, repeat: false, modifiers }, - egui::Event::Key { key: Key::T, physical_key: None, pressed: false, repeat: false, modifiers }, - ], - ..Default::default() - }; - ctx.begin_pass(raw); - handle(app, &ctx); - ctx.end_pass().textures_delta.clear(); - }; - app.ui.tool = Tool::Type; - press(&mut app, Modifiers::NONE); - press(&mut app, Modifiers::NONE); - assert_eq!(app.ui.tool, Tool::Type); - press(&mut app, Modifiers::SHIFT); - assert_ne!(app.ui.tool, Tool::Type); - // A stored "off" restores plain-key cycling. - app.session.edit_prefs(|p| p.tools.use_shift_key_for_tool_switch = false); - app.ui.tool = Tool::Type; - press(&mut app, Modifiers::NONE); - assert_ne!(app.ui.tool, Tool::Type); - } - - /// #3109: on a German layout Ö / # (physical `;` / `\`) step the brush size and ⇧Ö / ⇧# - /// (⇧# types `'`) its hardness, as Photoshop's German shortcuts. - #[test] - fn german_o_umlaut_and_hash_are_the_brush_keys() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - app.ui.tool = Tool::Brush; - app.session.tools.brush.hardness = 0.5; - let ctx = egui::Context::default(); - let typed = |app: &mut PhotocraftApp, key, physical_key, text: &str, modifiers| { - let press = egui::Event::Key { key, physical_key: Some(physical_key), pressed: true, repeat: false, modifiers }; - let raw = egui::RawInput { events: vec![egui::Event::ModifiersChanged(modifiers), press, egui::Event::Text(text.into())], ..Default::default() }; - ctx.begin_pass(raw); - handle(app, &ctx); - ctx.end_pass().textures_delta.clear(); - }; - let size = app.session.tools.brush.size; - typed(&mut app, Key::Backslash, Key::Backslash, "#", Modifiers::NONE); - assert!(app.session.tools.brush.size > size, "# is ]"); - typed(&mut app, Key::Semicolon, Key::Semicolon, "ö", Modifiers::NONE); - assert_eq!(app.session.tools.brush.size, size, "ö is ["); - typed(&mut app, Key::Quote, Key::Backslash, "'", Modifiers::SHIFT); - assert!(app.session.tools.brush.hardness > 0.5, "⇧# is ⇧]"); - typed(&mut app, Key::Semicolon, Key::Semicolon, "Ö", Modifiers::SHIFT); - assert_eq!(app.session.tools.brush.hardness, 0.5, "⇧Ö is ⇧["); - } - - #[test] - fn pen_command_z_and_backspace_retract_points_before_document_undo() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", serde_json::json!({"width": 200, "height": 200})).unwrap(); - app.ui.tool = crate::state::Tool::Pen; - app.run("shape.create", serde_json::json!({"kind": "rect", "rect": [10, 10, 40, 40], "fill": "#ff0000"})).unwrap(); - let history = app.session.active().unwrap().history.past_len(); - for (x, y) in [(10.0, 10.0), (50.0, 10.0), (50.0, 50.0)] { - crate::vector_ui::pen_down(&mut app, x, y, false); - crate::vector_ui::pen_up(&mut app); - } - let ctx = egui::Context::default(); - let press = |app: &mut PhotocraftApp, key, 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); - handle(app, &ctx); - ctx.end_pass().textures_delta.clear(); - }; - - press(&mut app, Key::Z, Modifiers::COMMAND); - assert_eq!(app.ui.pen.as_ref().unwrap().knots.len(), 2); - assert_eq!(app.session.active().unwrap().history.past_len(), history); - press(&mut app, Key::Backspace, Modifiers::NONE); - assert_eq!(app.ui.pen.as_ref().unwrap().knots.len(), 1); - press(&mut app, Key::Delete, Modifiers::NONE); - assert!(app.ui.pen.is_none()); - assert_eq!(app.session.active().unwrap().history.past_len(), history); - // No unfinished Pen points remain, so regular Undo can now affect the document. - app.run("edit.undo", serde_json::json!({})).unwrap(); - assert_eq!(app.session.active().unwrap().history.past_len(), history - 1); - } - - #[test] - fn pen_custom_undo_binding_and_menu_retract_pending_points() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - app.run("file.new", serde_json::json!({"width": 200, "height": 200})).unwrap(); - app.ui.tool = crate::state::Tool::Pen; - for (x, y) in [(10.0, 10.0), (50.0, 10.0)] { - crate::vector_ui::pen_down(&mut app, x, y, false); - crate::vector_ui::pen_up(&mut app); - } - app.session.prefs.edit(|p| p.shortcuts.insert("edit.undo".into(), "Cmd+Shift+Y".into())); - let ctx = egui::Context::default(); - let press = |app: &mut PhotocraftApp, key: Key, modifiers: Modifiers| { - ctx.begin_pass(egui::RawInput { - events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], - ..Default::default() - }); - handle(app, &ctx); - ctx.end_pass().textures_delta.clear(); - }; - // Once rebound, the default key must no longer intercept pending points. - press(&mut app, Key::Z, Modifiers::COMMAND); - assert_eq!(app.ui.pen.as_ref().unwrap().knots.len(), 2); - press(&mut app, Key::Y, Modifiers::COMMAND | Modifiers::SHIFT); - assert_eq!(app.ui.pen.as_ref().unwrap().knots.len(), 1); - assert!(crate::menus::is_enabled(&app, "edit.undo")); - crate::menus::invoke(&mut app, &ctx, "edit.undo", serde_json::json!({})).unwrap(); - assert!(app.ui.pen.is_none()); - } - - #[test] - fn parses_registry_shortcuts() { - let sc = parse("Cmd+Shift+N").unwrap(); - assert_eq!(sc.logical_key, Key::N); - assert!(sc.modifiers.command && sc.modifiers.shift); - assert_eq!(parse("Cmd+]").unwrap().logical_key, Key::CloseBracket); - assert_eq!(parse("Cmd+=").unwrap().logical_key, Key::Equals); - assert_eq!(parse("F7").unwrap().logical_key, Key::F7); - assert!(parse("Cmd+Nonsense").is_none()); - } - - #[test] - fn malformed_bindings_do_not_silently_match_a_different_shortcut() { - for invalid in ["Cmd+Typo+Z", "Cmd+X+Z", "Cmd+Z+X", "Cmd+Z+", "Cmd+Cmd+Z", "Ctrl+Ctrl+Z", "Shift+Shift+Z", "Cmd+Shift+++"] { - assert!(parse(invalid).is_none(), "{invalid} must not bind a command"); - } - // '+' is a key name as well as a separator; keep existing shortcut spellings. - for plus in ["+", "Cmd+", "Cmd++", "Cmd+Shift++"] { - assert_eq!(parse(plus).unwrap().logical_key, Key::Plus, "{plus}"); - } - assert!(parse("Cmd+Shift+Z").is_some()); - assert_eq!(parse("Cmd+;").unwrap().logical_key, Key::Semicolon); - } - - #[test] - fn keys_match_like_photoshop() { - let cmd = Modifiers::COMMAND; - let zoom_in = parse("Cmd+=").unwrap(); - // ⌘= , ⌘+ typed with ⇧ (US), ⌘+ from the numpad or a Nordic/German `+` key. - assert!(key_matches(&zoom_in, Key::Equals, cmd)); - assert!(key_matches(&zoom_in, Key::Plus, cmd | Modifiers::SHIFT)); - assert!(key_matches(&zoom_in, Key::Plus, cmd)); - assert!(!key_matches(&zoom_in, Key::Plus, Modifiers::NONE)); - assert!(!key_matches(&zoom_in, Key::Equals, cmd | Modifiers::ALT)); - assert!(key_matches(&parse("Cmd+-").unwrap(), Key::Minus, cmd)); - assert!(key_matches(&parse("Cmd+0").unwrap(), Key::Num0, cmd)); - // Ctrl (Windows) is ⌘. - assert!(key_matches(&zoom_in, Key::Plus, Modifiers::CTRL | Modifiers { command: true, ..Default::default() })); - // Exact modifiers: ⌘⌥I is Image Size, never Invert (⌘I); ⇧⌘Z is not ⌘Z. - let invert = parse("Cmd+I").unwrap(); - assert!(key_matches(&invert, Key::I, cmd)); - assert!(!key_matches(&invert, Key::I, cmd | Modifiers::ALT)); - assert!(!key_matches(&parse("Cmd+Z").unwrap(), Key::Z, cmd | Modifiers::SHIFT)); - // ⇧ shortcuts on punctuation arrive as the shifted character. - assert!(key_matches(&parse("Cmd+Shift+;").unwrap(), Key::Colon, cmd | Modifiers::SHIFT)); - assert!(key_matches(&parse("Cmd+Shift+]").unwrap(), Key::CloseCurlyBracket, cmd | Modifiers::SHIFT)); - assert!(!key_matches(&parse("Cmd+;").unwrap(), Key::Colon, cmd | Modifiers::SHIFT)); - // Delete and the Mac's delete (Backspace) both clear. - let clear = parse("Delete").unwrap(); - assert!(key_matches(&clear, Key::Delete, Modifiers::NONE) && key_matches(&clear, Key::Backspace, Modifiers::NONE)); - assert!(!key_matches(&clear, Key::Backspace, cmd)); - } - - #[test] - fn pretty_uses_the_platform_notation() { - let mac = cfg!(target_os = "macos"); - assert_eq!(pretty("Cmd+Shift+N"), if mac { "⌘⇧N" } else { "Ctrl+Shift+N" }); - // Lone keys and inline-hint combos. - assert_eq!(pretty("Alt"), if mac { "⌥" } else { "Alt" }); - assert_eq!(pretty("Shift+Alt"), if mac { "⇧⌥" } else { "Shift+Alt" }); - assert_eq!(pretty("Enter"), if mac { "↩" } else { "Enter" }); - assert_eq!(pretty("Cmd+Enter"), if mac { "⌘↩" } else { "Ctrl+Enter" }); - } - - #[test] - fn labels_show_the_effective_shortcut_in_platform_notation() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let new = command_label(&app, "New document…", "file.new"); - if cfg!(target_os = "macos") { - assert_eq!(new, "New document… ⌘N"); - } else { - assert_eq!(new, "New document… Ctrl+N"); - } - assert_eq!(tip_label(&app, "Rulers", "view.rulers"), format!("Rulers ({})", pretty("Cmd+R"))); - // A user override is picked up… - app.session.prefs.edit(|p| p.shortcuts.insert("file.new".into(), "Cmd+Shift+N".into())); - assert_eq!(command_label(&app, "New document…", "file.new"), format!("New document… {}", pretty("Cmd+Shift+N"))); - // …and a removed binding hides the shortcut entirely. - app.session.prefs.edit(|p| p.shortcuts.insert("file.new".into(), String::new())); - assert_eq!(command_label(&app, "New document…", "file.new"), "New document…"); - } - - #[test] - fn clipboard_events_become_pixel_shortcuts_outside_text() { - let ctx = egui::Context::default(); - let raw = |mut events: Vec, modifiers| { - events.insert(0, egui::Event::ModifiersChanged(modifiers)); - egui::RawInput { events, ..Default::default() } - }; - let keys = |r: &egui::RawInput| -> Vec<(Key, bool, bool)> { - r.events - .iter() - .filter_map(|e| if let egui::Event::Key { key, pressed, modifiers, .. } = e { Some((*key, *pressed, modifiers.shift)) } else { None }) - .collect() - }; - let cmd_shift = Modifiers::COMMAND | Modifiers::SHIFT; - let mut r = raw(vec![egui::Event::Copy, egui::Event::Cut], cmd_shift); - clipboard_keys(&ctx, false, &mut r); - assert_eq!(keys(&r), vec![(Key::C, true, true), (Key::X, true, true)]); - // A text paste becomes ⌘V; its key release then adds nothing. - let up = egui::Event::Key { key: Key::V, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::COMMAND }; - let mut r = raw(vec![egui::Event::Paste("x".into()), up.clone()], Modifiers::COMMAND); - clipboard_keys(&ctx, false, &mut r); - assert_eq!(keys(&r), vec![(Key::V, true, false), (Key::V, false, false)]); - // An image on the clipboard: egui-winit sends only the release. It still pastes. - let mut r = raw(vec![up.clone()], Modifiers::COMMAND); - clipboard_keys(&ctx, false, &mut r); - assert_eq!(keys(&r), vec![(Key::V, true, false), (Key::V, false, false)]); - // In a text field the events stay text clipboard events. - let mut r = raw(vec![egui::Event::Paste("x".into())], Modifiers::COMMAND); - clipboard_keys(&ctx, true, &mut r); - assert!(matches!(r.events.as_slice(), [_, egui::Event::Paste(_)])); - } - - /// In a text field the Mac menu's ⌘C / ⌘X key equivalents become the field's Copy / Cut, and - /// its ⌘V asks the window for the clipboard text, which the field pastes. Other keys, and ⇧ / ⌥ - /// chords, pass through. - #[test] - fn menu_key_equivalents_reach_a_text_field_as_clipboard_events() { - let ctx = egui::Context::default(); - let key = |key, pressed, modifiers| egui::Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }; - let cmd = Modifiers::COMMAND; - let events = vec![ - key(Key::C, true, cmd), - key(Key::X, true, cmd), - key(Key::V, true, cmd), - key(Key::V, false, cmd), - key(Key::A, true, cmd), - key(Key::C, true, cmd | Modifiers::SHIFT), - ]; - let mut r = egui::RawInput { events: [vec![egui::Event::ModifiersChanged(cmd)], events].concat(), ..Default::default() }; - // In a frame, as the app calls it, so the request for the clipboard text is in its output. - ctx.begin_pass(egui::RawInput::default()); - clipboard_keys(&ctx, true, &mut r); - let mut out = ctx.end_pass(); - out.textures_delta.clear(); - assert!( - matches!( - &r.events[1..], - [ - egui::Event::Copy, - egui::Event::Cut, - egui::Event::Key { key: Key::V, pressed: false, .. }, - egui::Event::Key { key: Key::A, .. }, - egui::Event::Key { key: Key::C, .. } - ] - ), - "{:?}", - r.events - ); - // The ⌘V press became a request for the clipboard's text. - let asked = out.viewport_output.values().flat_map(|v| &v.commands).any(|c| matches!(c, egui::ViewportCommand::RequestPaste)); - assert!(asked, "the window is asked for the clipboard text"); - } - - /// #1638: every ⌘V is one press, however its key-down and key-up arrive. - #[test] - fn each_paste_key_is_one_press() { - let ctx = egui::Context::default(); - let key = |key, pressed, modifiers| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }; - let presses = |events: Vec| { - let mut r = egui::RawInput { events, ..Default::default() }; - clipboard_keys(&ctx, false, &mut r); - r.events.iter().filter(|e| matches!(e, egui::Event::Key { key: Key::V, pressed: true, .. })).count() - }; - // A ⌘V press that reached us (the Mac menu's key equivalent), then its release. - assert_eq!(presses(vec![key(Key::V, true, Modifiers::COMMAND)]), 1); - assert_eq!(presses(vec![key(Key::V, false, Modifiers::COMMAND)]), 0, "the release of a press doesn't paste again"); - // A text paste whose V is released after ⌘: the next image paste still pastes. - assert_eq!(presses(vec![egui::Event::Paste("x".into())]), 1); - assert_eq!(presses(vec![egui::Event::ModifiersChanged(Modifiers::NONE), key(Key::V, false, Modifiers::NONE)]), 0); - assert_eq!(presses(vec![egui::Event::ModifiersChanged(Modifiers::COMMAND), key(Key::V, false, Modifiers::COMMAND)]), 1, "image paste"); - } - - /// #6329: with an image on the clipboard egui-winit swallows the ⌘V press and sends only the V - /// release, which carries no ⌘ when ⌘ was let go first: that release still pastes, once. A V - /// pressed and released on its own (the Move tool) never pastes. - #[test] - fn an_image_paste_released_after_command_still_pastes() { - let key = |key, pressed, modifiers| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }; - let pastes = |ctx: &egui::Context, events: Vec| { - let mut r = egui::RawInput { events, ..Default::default() }; - clipboard_keys(ctx, false, &mut r); - r.events.iter().filter(|e| matches!(e, egui::Event::Key { key: Key::V, pressed: true, modifiers, .. } if modifiers.command)).count() - }; - let none = Modifiers::NONE; - // ⌘ down, (the swallowed V press,) ⌘ up, V up: in one frame or over several. - let ctx = egui::Context::default(); - assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND), egui::Event::ModifiersChanged(none), key(Key::V, false, none)]), 1); - assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND)]), 0); - assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(none)]), 0); - assert_eq!(pastes(&ctx, vec![key(Key::V, false, none)]), 1, "released after ⌘"); - // Once: another lone release without ⌘ held again doesn't paste again. - assert_eq!(pastes(&ctx, vec![key(Key::V, false, none)]), 0); - // A plain V tap after ⌘ was used is the Move tool, not a paste. - let ctx = egui::Context::default(); - assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND), egui::Event::ModifiersChanged(none)]), 0); - assert_eq!(pastes(&ctx, vec![key(Key::V, true, none), key(Key::V, false, none)]), 0); - // Without ⌘ at all, a lone V release is nothing. - let ctx = egui::Context::default(); - assert_eq!(pastes(&ctx, vec![key(Key::V, false, none)]), 0); - // Released with ⌘ still held it pastes as before. - assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND), key(Key::V, false, Modifiers::COMMAND)]), 1); - } - - /// #2638: on the web one ⌘V brings its key press and the browser's paste event; that is one paste. - #[test] - fn web_paste_key_and_paste_event_are_one_press() { - let ctx = egui::Context::default(); - let key = |key, pressed| egui::Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: Modifiers::COMMAND }; - let mut r = - egui::RawInput { events: vec![key(Key::V, true), egui::Event::Paste("x".into()), key(Key::X, true), egui::Event::Cut], ..Default::default() }; - clipboard_keys(&ctx, false, &mut r); - let presses = |k| r.events.iter().filter(|e| matches!(e, egui::Event::Key { key, pressed: true, .. } if *key == k)).count(); - assert_eq!((presses(Key::V), presses(Key::X)), (1, 1)); - let mut r = egui::RawInput { events: vec![key(Key::V, false)], ..Default::default() }; - clipboard_keys(&ctx, false, &mut r); - assert!(!r.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. })), "its release doesn't paste again"); - } - - /// #530: egui-winit sends Cut for Shift+Delete on Windows; on the canvas it opens Fill. - #[test] - fn windows_shift_delete_fills_instead_of_cutting() { - let shift = Modifiers::SHIFT; - let ctrl = Modifiers::CTRL | Modifiers::COMMAND; - let app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let bound = |held| { - let (key, mods) = clipboard_press(&egui::Event::Cut, held, true)?; - assert_eq!((key, mods), (Key::Delete, held)); - crate::shortcut_dispatch::bindings(&app).into_iter().find(|(_, sc)| key_matches(sc, key, mods)).map(|(id, _)| id) - }; - assert_eq!(bound(shift).as_deref(), Some("edit.fill")); - // ⇧⌥Delete keeps ⌥: fill with the foreground, keeping transparency. - assert_eq!(bound(shift | Modifiers::ALT).as_deref(), Some("edit.fillForegroundPreserve")); - // Ctrl+X (and Ctrl+Shift+X) still cut; elsewhere a Cut is always ⌘X. - assert_eq!(clipboard_press(&egui::Event::Cut, ctrl, true), Some((Key::X, ctrl))); - assert_eq!(clipboard_press(&egui::Event::Cut, ctrl | shift, true), Some((Key::X, ctrl | shift))); - assert_eq!(clipboard_press(&egui::Event::Cut, shift, false), Some((Key::X, Modifiers::COMMAND))); - // Shift+Insert pastes on Windows. - assert_eq!(clipboard_press(&egui::Event::Paste("x".into()), shift, true), Some((Key::V, Modifiers::COMMAND))); - // egui 0.37's image-only clipboard paste is the same ⌘V press; the command reads the - // clipboard itself, once, through the existing import path. - let image = std::sync::Arc::new(egui::ColorImage::filled([1, 1], egui::Color32::BLACK)); - assert_eq!(clipboard_press(&egui::Event::PasteImage(image), shift, true), Some((Key::V, Modifiers::COMMAND))); - // Through the raw-input hook on this platform; a text field keeps its Cut. - let ctx = egui::Context::default(); - let cut = || egui::RawInput { events: vec![egui::Event::ModifiersChanged(shift), egui::Event::Cut], ..Default::default() }; - let mut r = cut(); - clipboard_keys(&ctx, false, &mut r); - let want = if cfg!(target_os = "windows") { Key::Delete } else { Key::X }; - assert!(matches!(r.events.as_slice(), [_, egui::Event::Key { key, pressed: true, .. }] if *key == want), "{:?}", r.events); - let mut r = cut(); - clipboard_keys(&ctx, true, &mut r); - assert!(matches!(r.events.as_slice(), [_, egui::Event::Cut])); - } - - #[cfg(target_os = "linux")] - #[test] - fn ctrl_and_shift_insert_copy_and_paste_on_linux() { - let ctx = egui::Context::default(); - let insert = |modifiers| egui::RawInput { - events: vec![egui::Event::Key { key: Key::Insert, physical_key: None, pressed: true, repeat: false, modifiers }], - ..Default::default() - }; - let pressed = |r: &egui::RawInput| match r.events.as_slice() { - [egui::Event::Key { key, pressed: true, modifiers, .. }] if modifiers.command => Some(*key), - _ => None, - }; - // On the canvas they become the pixel commands' ⌘C / ⌘V. - let mut r = insert(Modifiers::CTRL); - clipboard_keys(&ctx, false, &mut r); - assert_eq!(pressed(&r), Some(Key::C)); - let mut r = insert(Modifiers::SHIFT); - clipboard_keys(&ctx, false, &mut r); - assert_eq!(pressed(&r), Some(Key::V)); - // In a text field Ctrl+Insert copies the text; Shift+Insert asks egui-winit for the text. - let mut r = insert(Modifiers::CTRL); - clipboard_keys(&ctx, true, &mut r); - assert!(matches!(r.events.as_slice(), [egui::Event::Copy])); - let mut r = insert(Modifiers::SHIFT); - clipboard_keys(&ctx, true, &mut r); - assert!(r.events.is_empty()); - // Plain Insert is left alone. - let mut r = insert(Modifiers::NONE); - clipboard_keys(&ctx, false, &mut r); - assert!(matches!(r.events.as_slice(), [egui::Event::Key { key: Key::Insert, .. }])); - } - - #[test] - fn every_registered_shortcut_parses() { - for c in photocraft_engine::command_specs() { - if let Some(sc) = c.shortcut { - assert!(parse(sc).is_some(), "{}: {sc}", c.id); - } - } - for (id, _, _, sc) in crate::menus::UI_COMMANDS { - if let Some(sc) = sc { - assert!(parse(sc).is_some(), "{id}: {sc}"); - } - } - } - - #[test] - fn no_duplicate_shortcuts() { - let mut seen = std::collections::HashMap::new(); - let all = photocraft_engine::command_specs() - .iter() - .filter_map(|c| c.shortcut.map(|s| (c.id, s))) - .chain(crate::menus::UI_COMMANDS.iter().filter_map(|(id, _, _, s)| s.map(|s| (*id, s)))) - // Photoshop's second keys (#3665) are taken by no other command either. - .chain(photocraft_engine::prefs::ALTERNATE_SHORTCUTS.iter().copied()); - for (id, s) in all { - assert!(parse(s).is_some(), "{id}: {s}"); - if let Some(prev) = seen.insert(s, id) { - panic!("shortcut {s} bound to both {prev} and {id}"); - } - } - } -} +mod tests; diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs new file mode 100644 index 0000000000..bb24e69fdc --- /dev/null +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -0,0 +1,483 @@ +use super::*; + +#[test] +fn tool_key_brings_back_the_groups_last_used_tool() { + use crate::state::Tool; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + let press = |app: &mut PhotocraftApp, key, 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(); + }; + // Plain-key cycling (the pref is on by default, as in Photoshop). + app.session.edit_prefs(|p| p.tools.use_shift_key_for_tool_switch = false); + // Polygonal Lasso picked from the toolbar flyout, then the Brush (#2608). + app.ui.tool = Tool::PolygonLasso; + press(&mut app, Key::B, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::Brush); + press(&mut app, Key::L, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::PolygonLasso); + // Within the group, L still cycles; leaving and coming back keeps the new pick. + press(&mut app, Key::L, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::MagneticLasso); + press(&mut app, Key::M, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::RectMarquee); + press(&mut app, Key::L, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::MagneticLasso); + // Use Shift Key for Tool Switch: the plain key also returns to the last-used tool. + app.session.edit_prefs(|p| p.tools.use_shift_key_for_tool_switch = true); + press(&mut app, Key::B, Modifiers::NONE); + press(&mut app, Key::L, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::MagneticLasso); +} + +/// #3296: by default T keeps the current type tool and only Shift+T cycles, as in Photoshop. +#[test] +fn shift_key_tool_switch_is_the_default() { + use crate::state::Tool; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + let press = |app: &mut PhotocraftApp, modifiers| { + let raw = egui::RawInput { + events: vec![ + egui::Event::ModifiersChanged(modifiers), + egui::Event::Key { key: Key::T, physical_key: None, pressed: true, repeat: false, modifiers }, + egui::Event::Key { key: Key::T, physical_key: None, pressed: false, repeat: false, modifiers }, + ], + ..Default::default() + }; + ctx.begin_pass(raw); + handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); + }; + app.ui.tool = Tool::Type; + press(&mut app, Modifiers::NONE); + press(&mut app, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::Type); + press(&mut app, Modifiers::SHIFT); + assert_ne!(app.ui.tool, Tool::Type); + // A stored "off" restores plain-key cycling. + app.session.edit_prefs(|p| p.tools.use_shift_key_for_tool_switch = false); + app.ui.tool = Tool::Type; + press(&mut app, Modifiers::NONE); + assert_ne!(app.ui.tool, Tool::Type); +} + +/// #3109: on a German layout Ö / # (physical `;` / `\`) step the brush size and ⇧Ö / ⇧# +/// (⇧# types `'`) its hardness, as Photoshop's German shortcuts. +#[test] +fn german_o_umlaut_and_hash_are_the_brush_keys() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.ui.tool = Tool::Brush; + app.session.tools.brush.hardness = 0.5; + let ctx = egui::Context::default(); + let typed = |app: &mut PhotocraftApp, key, physical_key, text: &str, modifiers| { + let press = egui::Event::Key { key, physical_key: Some(physical_key), pressed: true, repeat: false, modifiers }; + let raw = egui::RawInput { events: vec![egui::Event::ModifiersChanged(modifiers), press, egui::Event::Text(text.into())], ..Default::default() }; + ctx.begin_pass(raw); + handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); + }; + let size = app.session.tools.brush.size; + typed(&mut app, Key::Backslash, Key::Backslash, "#", Modifiers::NONE); + assert!(app.session.tools.brush.size > size, "# is ]"); + typed(&mut app, Key::Semicolon, Key::Semicolon, "ö", Modifiers::NONE); + assert_eq!(app.session.tools.brush.size, size, "ö is ["); + typed(&mut app, Key::Quote, Key::Backslash, "'", Modifiers::SHIFT); + assert!(app.session.tools.brush.hardness > 0.5, "⇧# is ⇧]"); + typed(&mut app, Key::Semicolon, Key::Semicolon, "Ö", Modifiers::SHIFT); + assert_eq!(app.session.tools.brush.hardness, 0.5, "⇧Ö is ⇧["); +} + +#[test] +fn pen_command_z_and_backspace_retract_points_before_document_undo() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 200, "height": 200})).unwrap(); + app.ui.tool = crate::state::Tool::Pen; + app.run("shape.create", serde_json::json!({"kind": "rect", "rect": [10, 10, 40, 40], "fill": "#ff0000"})).unwrap(); + let history = app.session.active().unwrap().history.past_len(); + for (x, y) in [(10.0, 10.0), (50.0, 10.0), (50.0, 50.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + let ctx = egui::Context::default(); + let press = |app: &mut PhotocraftApp, key, 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); + handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); + }; + + press(&mut app, Key::Z, Modifiers::COMMAND); + assert_eq!(app.ui.pen.as_ref().unwrap().knots.len(), 2); + assert_eq!(app.session.active().unwrap().history.past_len(), history); + press(&mut app, Key::Backspace, Modifiers::NONE); + assert_eq!(app.ui.pen.as_ref().unwrap().knots.len(), 1); + press(&mut app, Key::Delete, Modifiers::NONE); + assert!(app.ui.pen.is_none()); + assert_eq!(app.session.active().unwrap().history.past_len(), history); + // No unfinished Pen points remain, so regular Undo can now affect the document. + app.run("edit.undo", serde_json::json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().history.past_len(), history - 1); +} + +#[test] +fn pen_custom_undo_binding_and_menu_retract_pending_points() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 200, "height": 200})).unwrap(); + app.ui.tool = crate::state::Tool::Pen; + for (x, y) in [(10.0, 10.0), (50.0, 10.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + app.session.prefs.edit(|p| p.shortcuts.insert("edit.undo".into(), "Cmd+Shift+Y".into())); + let ctx = egui::Context::default(); + let press = |app: &mut PhotocraftApp, key: Key, modifiers: Modifiers| { + ctx.begin_pass(egui::RawInput { + events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], + ..Default::default() + }); + handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); + }; + // Once rebound, the default key must no longer intercept pending points. + press(&mut app, Key::Z, Modifiers::COMMAND); + assert_eq!(app.ui.pen.as_ref().unwrap().knots.len(), 2); + press(&mut app, Key::Y, Modifiers::COMMAND | Modifiers::SHIFT); + assert_eq!(app.ui.pen.as_ref().unwrap().knots.len(), 1); + assert!(crate::menus::is_enabled(&app, "edit.undo")); + crate::menus::invoke(&mut app, &ctx, "edit.undo", serde_json::json!({})).unwrap(); + assert!(app.ui.pen.is_none()); +} + +#[test] +fn parses_registry_shortcuts() { + let sc = parse("Cmd+Shift+N").unwrap(); + assert_eq!(sc.logical_key, Key::N); + assert!(sc.modifiers.command && sc.modifiers.shift); + assert_eq!(parse("Cmd+]").unwrap().logical_key, Key::CloseBracket); + assert_eq!(parse("Cmd+=").unwrap().logical_key, Key::Equals); + assert_eq!(parse("F7").unwrap().logical_key, Key::F7); + assert!(parse("Cmd+Nonsense").is_none()); +} + +#[test] +fn malformed_bindings_do_not_silently_match_a_different_shortcut() { + for invalid in ["Cmd+Typo+Z", "Cmd+X+Z", "Cmd+Z+X", "Cmd+Z+", "Cmd+Cmd+Z", "Ctrl+Ctrl+Z", "Shift+Shift+Z", "Cmd+Shift+++"] { + assert!(parse(invalid).is_none(), "{invalid} must not bind a command"); + } + // '+' is a key name as well as a separator; keep existing shortcut spellings. + for plus in ["+", "Cmd+", "Cmd++", "Cmd+Shift++"] { + assert_eq!(parse(plus).unwrap().logical_key, Key::Plus, "{plus}"); + } + assert!(parse("Cmd+Shift+Z").is_some()); + assert_eq!(parse("Cmd+;").unwrap().logical_key, Key::Semicolon); +} + +#[test] +fn keys_match_like_photoshop() { + let cmd = Modifiers::COMMAND; + let zoom_in = parse("Cmd+=").unwrap(); + // ⌘= , ⌘+ typed with ⇧ (US), ⌘+ from the numpad or a Nordic/German `+` key. + assert!(key_matches(&zoom_in, Key::Equals, cmd)); + assert!(key_matches(&zoom_in, Key::Plus, cmd | Modifiers::SHIFT)); + assert!(key_matches(&zoom_in, Key::Plus, cmd)); + assert!(!key_matches(&zoom_in, Key::Plus, Modifiers::NONE)); + assert!(!key_matches(&zoom_in, Key::Equals, cmd | Modifiers::ALT)); + assert!(key_matches(&parse("Cmd+-").unwrap(), Key::Minus, cmd)); + assert!(key_matches(&parse("Cmd+0").unwrap(), Key::Num0, cmd)); + // Ctrl (Windows) is ⌘. + assert!(key_matches(&zoom_in, Key::Plus, Modifiers::CTRL | Modifiers { command: true, ..Default::default() })); + // Exact modifiers: ⌘⌥I is Image Size, never Invert (⌘I); ⇧⌘Z is not ⌘Z. + let invert = parse("Cmd+I").unwrap(); + assert!(key_matches(&invert, Key::I, cmd)); + assert!(!key_matches(&invert, Key::I, cmd | Modifiers::ALT)); + assert!(!key_matches(&parse("Cmd+Z").unwrap(), Key::Z, cmd | Modifiers::SHIFT)); + // ⇧ shortcuts on punctuation arrive as the shifted character. + assert!(key_matches(&parse("Cmd+Shift+;").unwrap(), Key::Colon, cmd | Modifiers::SHIFT)); + assert!(key_matches(&parse("Cmd+Shift+]").unwrap(), Key::CloseCurlyBracket, cmd | Modifiers::SHIFT)); + assert!(!key_matches(&parse("Cmd+;").unwrap(), Key::Colon, cmd | Modifiers::SHIFT)); + // Delete and the Mac's delete (Backspace) both clear. + let clear = parse("Delete").unwrap(); + assert!(key_matches(&clear, Key::Delete, Modifiers::NONE) && key_matches(&clear, Key::Backspace, Modifiers::NONE)); + assert!(!key_matches(&clear, Key::Backspace, cmd)); +} + +#[test] +fn pretty_uses_the_platform_notation() { + let mac = cfg!(target_os = "macos"); + assert_eq!(pretty("Cmd+Shift+N"), if mac { "⌘⇧N" } else { "Ctrl+Shift+N" }); + // Lone keys and inline-hint combos. + assert_eq!(pretty("Alt"), if mac { "⌥" } else { "Alt" }); + assert_eq!(pretty("Shift+Alt"), if mac { "⇧⌥" } else { "Shift+Alt" }); + assert_eq!(pretty("Enter"), if mac { "↩" } else { "Enter" }); + assert_eq!(pretty("Cmd+Enter"), if mac { "⌘↩" } else { "Ctrl+Enter" }); +} + +#[test] +fn labels_show_the_effective_shortcut_in_platform_notation() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let new = command_label(&app, "New document…", "file.new"); + if cfg!(target_os = "macos") { + assert_eq!(new, "New document… ⌘N"); + } else { + assert_eq!(new, "New document… Ctrl+N"); + } + assert_eq!(tip_label(&app, "Rulers", "view.rulers"), format!("Rulers ({})", pretty("Cmd+R"))); + // A user override is picked up… + app.session.prefs.edit(|p| p.shortcuts.insert("file.new".into(), "Cmd+Shift+N".into())); + assert_eq!(command_label(&app, "New document…", "file.new"), format!("New document… {}", pretty("Cmd+Shift+N"))); + // …and a removed binding hides the shortcut entirely. + app.session.prefs.edit(|p| p.shortcuts.insert("file.new".into(), String::new())); + assert_eq!(command_label(&app, "New document…", "file.new"), "New document…"); +} + +#[test] +fn clipboard_events_become_pixel_shortcuts_outside_text() { + let ctx = egui::Context::default(); + let raw = |mut events: Vec, modifiers| { + events.insert(0, egui::Event::ModifiersChanged(modifiers)); + egui::RawInput { events, ..Default::default() } + }; + let keys = |r: &egui::RawInput| -> Vec<(Key, bool, bool)> { + r.events + .iter() + .filter_map(|e| if let egui::Event::Key { key, pressed, modifiers, .. } = e { Some((*key, *pressed, modifiers.shift)) } else { None }) + .collect() + }; + let cmd_shift = Modifiers::COMMAND | Modifiers::SHIFT; + let mut r = raw(vec![egui::Event::Copy, egui::Event::Cut], cmd_shift); + clipboard_keys(&ctx, false, &mut r); + assert_eq!(keys(&r), vec![(Key::C, true, true), (Key::X, true, true)]); + // A text paste becomes ⌘V; its key release then adds nothing. + let up = egui::Event::Key { key: Key::V, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::COMMAND }; + let mut r = raw(vec![egui::Event::Paste("x".into()), up.clone()], Modifiers::COMMAND); + clipboard_keys(&ctx, false, &mut r); + assert_eq!(keys(&r), vec![(Key::V, true, false), (Key::V, false, false)]); + // An image on the clipboard: egui-winit sends only the release. It still pastes. + let mut r = raw(vec![up.clone()], Modifiers::COMMAND); + clipboard_keys(&ctx, false, &mut r); + assert_eq!(keys(&r), vec![(Key::V, true, false), (Key::V, false, false)]); + // In a text field the events stay text clipboard events. + let mut r = raw(vec![egui::Event::Paste("x".into())], Modifiers::COMMAND); + clipboard_keys(&ctx, true, &mut r); + assert!(matches!(r.events.as_slice(), [_, egui::Event::Paste(_)])); +} + +/// In a text field the Mac menu's ⌘C / ⌘X key equivalents become the field's Copy / Cut, and +/// its ⌘V asks the window for the clipboard text, which the field pastes. Other keys, and ⇧ / ⌥ +/// chords, pass through. +#[test] +fn menu_key_equivalents_reach_a_text_field_as_clipboard_events() { + let ctx = egui::Context::default(); + let key = |key, pressed, modifiers| egui::Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }; + let cmd = Modifiers::COMMAND; + let events = vec![ + key(Key::C, true, cmd), + key(Key::X, true, cmd), + key(Key::V, true, cmd), + key(Key::V, false, cmd), + key(Key::A, true, cmd), + key(Key::C, true, cmd | Modifiers::SHIFT), + ]; + let mut r = egui::RawInput { events: [vec![egui::Event::ModifiersChanged(cmd)], events].concat(), ..Default::default() }; + // In a frame, as the app calls it, so the request for the clipboard text is in its output. + ctx.begin_pass(egui::RawInput::default()); + clipboard_keys(&ctx, true, &mut r); + let mut out = ctx.end_pass(); + out.textures_delta.clear(); + assert!( + matches!( + &r.events[1..], + [ + egui::Event::Copy, + egui::Event::Cut, + egui::Event::Key { key: Key::V, pressed: false, .. }, + egui::Event::Key { key: Key::A, .. }, + egui::Event::Key { key: Key::C, .. } + ] + ), + "{:?}", + r.events + ); + // The ⌘V press became a request for the clipboard's text. + let asked = out.viewport_output.values().flat_map(|v| &v.commands).any(|c| matches!(c, egui::ViewportCommand::RequestPaste)); + assert!(asked, "the window is asked for the clipboard text"); +} + +/// #1638: every ⌘V is one press, however its key-down and key-up arrive. +#[test] +fn each_paste_key_is_one_press() { + let ctx = egui::Context::default(); + let key = |key, pressed, modifiers| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }; + let presses = |events: Vec| { + let mut r = egui::RawInput { events, ..Default::default() }; + clipboard_keys(&ctx, false, &mut r); + r.events.iter().filter(|e| matches!(e, egui::Event::Key { key: Key::V, pressed: true, .. })).count() + }; + // A ⌘V press that reached us (the Mac menu's key equivalent), then its release. + assert_eq!(presses(vec![key(Key::V, true, Modifiers::COMMAND)]), 1); + assert_eq!(presses(vec![key(Key::V, false, Modifiers::COMMAND)]), 0, "the release of a press doesn't paste again"); + // A text paste whose V is released after ⌘: the next image paste still pastes. + assert_eq!(presses(vec![egui::Event::Paste("x".into())]), 1); + assert_eq!(presses(vec![egui::Event::ModifiersChanged(Modifiers::NONE), key(Key::V, false, Modifiers::NONE)]), 0); + assert_eq!(presses(vec![egui::Event::ModifiersChanged(Modifiers::COMMAND), key(Key::V, false, Modifiers::COMMAND)]), 1, "image paste"); +} + +/// #6329: with an image on the clipboard egui-winit swallows the ⌘V press and sends only the V +/// release, which carries no ⌘ when ⌘ was let go first: that release still pastes, once. A V +/// pressed and released on its own (the Move tool) never pastes. +#[test] +fn an_image_paste_released_after_command_still_pastes() { + let key = |key, pressed, modifiers| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }; + let pastes = |ctx: &egui::Context, events: Vec| { + let mut r = egui::RawInput { events, ..Default::default() }; + clipboard_keys(ctx, false, &mut r); + r.events.iter().filter(|e| matches!(e, egui::Event::Key { key: Key::V, pressed: true, modifiers, .. } if modifiers.command)).count() + }; + let none = Modifiers::NONE; + // ⌘ down, (the swallowed V press,) ⌘ up, V up: in one frame or over several. + let ctx = egui::Context::default(); + assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND), egui::Event::ModifiersChanged(none), key(Key::V, false, none)]), 1); + assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND)]), 0); + assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(none)]), 0); + assert_eq!(pastes(&ctx, vec![key(Key::V, false, none)]), 1, "released after ⌘"); + // Once: another lone release without ⌘ held again doesn't paste again. + assert_eq!(pastes(&ctx, vec![key(Key::V, false, none)]), 0); + // A plain V tap after ⌘ was used is the Move tool, not a paste. + let ctx = egui::Context::default(); + assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND), egui::Event::ModifiersChanged(none)]), 0); + assert_eq!(pastes(&ctx, vec![key(Key::V, true, none), key(Key::V, false, none)]), 0); + // Without ⌘ at all, a lone V release is nothing. + let ctx = egui::Context::default(); + assert_eq!(pastes(&ctx, vec![key(Key::V, false, none)]), 0); + // Released with ⌘ still held it pastes as before. + assert_eq!(pastes(&ctx, vec![egui::Event::ModifiersChanged(Modifiers::COMMAND), key(Key::V, false, Modifiers::COMMAND)]), 1); +} + +/// #2638: on the web one ⌘V brings its key press and the browser's paste event; that is one paste. +#[test] +fn web_paste_key_and_paste_event_are_one_press() { + let ctx = egui::Context::default(); + let key = |key, pressed| egui::Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: Modifiers::COMMAND }; + let mut r = + egui::RawInput { events: vec![key(Key::V, true), egui::Event::Paste("x".into()), key(Key::X, true), egui::Event::Cut], ..Default::default() }; + clipboard_keys(&ctx, false, &mut r); + let presses = |k| r.events.iter().filter(|e| matches!(e, egui::Event::Key { key, pressed: true, .. } if *key == k)).count(); + assert_eq!((presses(Key::V), presses(Key::X)), (1, 1)); + let mut r = egui::RawInput { events: vec![key(Key::V, false)], ..Default::default() }; + clipboard_keys(&ctx, false, &mut r); + assert!(!r.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. })), "its release doesn't paste again"); +} + +/// #530: egui-winit sends Cut for Shift+Delete on Windows; on the canvas it opens Fill. +#[test] +fn windows_shift_delete_fills_instead_of_cutting() { + let shift = Modifiers::SHIFT; + let ctrl = Modifiers::CTRL | Modifiers::COMMAND; + let app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let bound = |held| { + let (key, mods) = clipboard_press(&egui::Event::Cut, held, true)?; + assert_eq!((key, mods), (Key::Delete, held)); + crate::shortcut_dispatch::bindings(&app).into_iter().find(|(_, sc)| key_matches(sc, key, mods)).map(|(id, _)| id) + }; + assert_eq!(bound(shift).as_deref(), Some("edit.fill")); + // ⇧⌥Delete keeps ⌥: fill with the foreground, keeping transparency. + assert_eq!(bound(shift | Modifiers::ALT).as_deref(), Some("edit.fillForegroundPreserve")); + // Ctrl+X (and Ctrl+Shift+X) still cut; elsewhere a Cut is always ⌘X. + assert_eq!(clipboard_press(&egui::Event::Cut, ctrl, true), Some((Key::X, ctrl))); + assert_eq!(clipboard_press(&egui::Event::Cut, ctrl | shift, true), Some((Key::X, ctrl | shift))); + assert_eq!(clipboard_press(&egui::Event::Cut, shift, false), Some((Key::X, Modifiers::COMMAND))); + // Shift+Insert pastes on Windows. + assert_eq!(clipboard_press(&egui::Event::Paste("x".into()), shift, true), Some((Key::V, Modifiers::COMMAND))); + // egui 0.37's image-only clipboard paste is the same ⌘V press; the command reads the + // clipboard itself, once, through the existing import path. + let image = std::sync::Arc::new(egui::ColorImage::filled([1, 1], egui::Color32::BLACK)); + assert_eq!(clipboard_press(&egui::Event::PasteImage(image), shift, true), Some((Key::V, Modifiers::COMMAND))); + // Through the raw-input hook on this platform; a text field keeps its Cut. + let ctx = egui::Context::default(); + let cut = || egui::RawInput { events: vec![egui::Event::ModifiersChanged(shift), egui::Event::Cut], ..Default::default() }; + let mut r = cut(); + clipboard_keys(&ctx, false, &mut r); + let want = if cfg!(target_os = "windows") { Key::Delete } else { Key::X }; + assert!(matches!(r.events.as_slice(), [_, egui::Event::Key { key, pressed: true, .. }] if *key == want), "{:?}", r.events); + let mut r = cut(); + clipboard_keys(&ctx, true, &mut r); + assert!(matches!(r.events.as_slice(), [_, egui::Event::Cut])); +} + +#[cfg(target_os = "linux")] +#[test] +fn ctrl_and_shift_insert_copy_and_paste_on_linux() { + let ctx = egui::Context::default(); + let insert = |modifiers| egui::RawInput { + events: vec![egui::Event::Key { key: Key::Insert, physical_key: None, pressed: true, repeat: false, modifiers }], + ..Default::default() + }; + let pressed = |r: &egui::RawInput| match r.events.as_slice() { + [egui::Event::Key { key, pressed: true, modifiers, .. }] if modifiers.command => Some(*key), + _ => None, + }; + // On the canvas they become the pixel commands' ⌘C / ⌘V. + let mut r = insert(Modifiers::CTRL); + clipboard_keys(&ctx, false, &mut r); + assert_eq!(pressed(&r), Some(Key::C)); + let mut r = insert(Modifiers::SHIFT); + clipboard_keys(&ctx, false, &mut r); + assert_eq!(pressed(&r), Some(Key::V)); + // In a text field Ctrl+Insert copies the text; Shift+Insert asks egui-winit for the text. + let mut r = insert(Modifiers::CTRL); + clipboard_keys(&ctx, true, &mut r); + assert!(matches!(r.events.as_slice(), [egui::Event::Copy])); + let mut r = insert(Modifiers::SHIFT); + clipboard_keys(&ctx, true, &mut r); + assert!(r.events.is_empty()); + // Plain Insert is left alone. + let mut r = insert(Modifiers::NONE); + clipboard_keys(&ctx, false, &mut r); + assert!(matches!(r.events.as_slice(), [egui::Event::Key { key: Key::Insert, .. }])); +} + +#[test] +fn every_registered_shortcut_parses() { + for c in photocraft_engine::command_specs() { + if let Some(sc) = c.shortcut { + assert!(parse(sc).is_some(), "{}: {sc}", c.id); + } + } + for (id, _, _, sc) in crate::menus::UI_COMMANDS { + if let Some(sc) = sc { + assert!(parse(sc).is_some(), "{id}: {sc}"); + } + } +} + +#[test] +fn no_duplicate_shortcuts() { + let mut seen = std::collections::HashMap::new(); + let all = photocraft_engine::command_specs() + .iter() + .filter_map(|c| c.shortcut.map(|s| (c.id, s))) + .chain(crate::menus::UI_COMMANDS.iter().filter_map(|(id, _, _, s)| s.map(|s| (*id, s)))) + // Photoshop's second keys (#3665) are taken by no other command either. + .chain(photocraft_engine::prefs::ALTERNATE_SHORTCUTS.iter().copied()); + for (id, s) in all { + assert!(parse(s).is_some(), "{id}: {s}"); + if let Some(prev) = seen.insert(s, id) { + panic!("shortcut {s} bound to both {prev} and {id}"); + } + } +} From 100f7fd5dd1bc68962d319f6910095e2d76982b9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:37 +0000 Subject: [PATCH 107/259] refactor(ui-egui): move sizing.rs tests to sizing/tests.rs --- crates/ui-egui/src/sizing.rs | 341 +---------------------------- crates/ui-egui/src/sizing/tests.rs | 337 ++++++++++++++++++++++++++++ 2 files changed, 338 insertions(+), 340 deletions(-) create mode 100644 crates/ui-egui/src/sizing/tests.rs diff --git a/crates/ui-egui/src/sizing.rs b/crates/ui-egui/src/sizing.rs index a969dfcb7d..1437d80b64 100644 --- a/crates/ui-egui/src/sizing.rs +++ b/crates/ui-egui/src/sizing.rs @@ -467,343 +467,4 @@ fn anchor_grid(ui: &mut egui::Ui, current: &str, dw: f64, dh: f64) -> Option<&'s } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn unit_conversions_round_trip() { - for ppi in [72.0, 72.27] { - for unit in ["px", "percent", "in", "cm", "mm", "pt", "pica"] { - let v = to_unit(1500.0, unit, 3000.0, 300.0, ppi); - assert!((from_unit(v, unit, 3000.0, 300.0, ppi) - 1500.0).abs() < 1e-9, "{unit} at {ppi} pt/in"); - } - } - assert_eq!(to_unit(1500.0, "percent", 3000.0, 300.0, 72.0), 50.0); - assert_eq!(to_unit(600.0, "in", 3000.0, 300.0, 72.0), 2.0); - assert_eq!(human_bytes(6016.0 * 6016.0 * 4.0), "138.1M"); - } - - /// #5756: points and picas use the Point/Pica Size preference (Traditional is 72.27 pt/in), - /// and a dialog without the field (or with a bad one) falls back to PostScript's 72. - #[test] - fn points_and_picas_use_the_points_per_inch() { - assert!((to_unit(72.0, "pt", 72.0, 72.0, 72.27) - 72.27).abs() < 1e-9); - assert!((to_unit(72.0, "pica", 72.0, 72.0, 72.27) - 72.27 / 12.0).abs() < 1e-9); - assert_eq!(to_unit(72.0, "pt", 72.0, 72.0, 72.0), 72.0); - assert_eq!(to_unit(72.0, "pica", 72.0, 72.0, 72.0), 6.0); - assert!((from_unit(72.27, "pt", 72.0, 72.0, 72.27) - 72.0).abs() < 1e-9); - let mut f = Map::new(); - assert_eq!(pt_per_in(&f), 72.0); - for bad in [json!(0.0), json!(-3.0), json!("x")] { - f.insert("__ptPerIn".into(), bad); - assert_eq!(pt_per_in(&f), 72.0); - } - f.insert("__ptPerIn".into(), json!(72.27)); - assert_eq!(pt_per_in(&f), 72.27); - } - - #[test] - fn dialog_maps_to_engine_command() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); - let id = open(&mut app, "image.imageSize").unwrap(); - let d = app.ui.dialog_mut(id).unwrap(); - d.fields.insert("width".into(), json!(100)); - d.fields.insert("height".into(), json!(50)); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(100, 50)); - let id = open(&mut app, "image.canvasSize").unwrap(); - let d = app.ui.dialog_mut(id).unwrap(); - d.fields.insert("width".into(), json!(120)); - d.fields.insert("anchor".into(), json!("topLeft")); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(120, 50)); - } - - #[test] - fn alt_reset_restores_open_dimensions() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 100, "resolution": 72})).unwrap(); - let id = open(&mut app, "image.imageSize").unwrap(); - let d = app.ui.dialog_mut(id).unwrap(); - d.fields.insert("width".into(), json!(50)); - d.fields.insert("height".into(), json!(25)); - d.fields.insert("resolution".into(), json!(300)); - d.fields.insert("__constrain".into(), json!(false)); - reset(&mut d.fields); - assert_eq!((num(&d.fields, "width"), num(&d.fields, "height"), num(&d.fields, "resolution")), (200.0, 100.0, 72.0)); - assert_eq!(d.fields.get("__constrain"), Some(&json!(true))); - assert!(app.ui.dialogs.iter().any(|x| x.id == id), "reset leaves the dialog open"); - } - - #[test] - fn canvas_extension_dropdown_is_named_for_its_setting() { - use egui::accesskit::Role; - use egui_kittest::Harness; - use egui_kittest::kittest::{NodeT, Queryable}; - - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 100, "height": 50})).unwrap(); - let mut h = - Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app: &mut PhotocraftApp| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - open(h.state_mut(), "image.canvasSize").unwrap(); - h.run_steps(3); - let labels: Vec = h.query_all_by_role(Role::ComboBox).filter_map(|n| n.accesskit_node().label()).collect(); - assert!(labels.iter().any(|label| label == "Canvas extension color:"), "{labels:?}"); - assert!(!labels.iter().any(|label| label == "Size"), "the dialog's Size label names a different field: {labels:?}"); - } - - /// #6019: on an Indexed Color document the dialog opens on, and offers only, Automatic and Nearest Neighbor. - #[test] - fn indexed_color_resamples_with_nearest_neighbor_only() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); - app.session.execute("image.mode.indexedColor", json!({})).unwrap(); - for (pref, method) in [("bicubic", "nearest"), ("bicubicAutomatic", "automatic"), ("nearestNeighbor", "nearest")] { - app.session.execute("prefs.set", json!({"path": "general.imageInterpolation", "value": pref})).unwrap(); - let id = open(&mut app, "image.imageSize").unwrap(); - let f = &app.ui.dialog_mut(id).unwrap().fields; - assert_eq!(f.get("resample"), Some(&json!(method)), "{pref}"); - assert_eq!(f.get("__indexed"), Some(&json!(true))); - app.ui.close_dialog(id); - } - // The open list offers only Automatic and Nearest Neighbor. - use egui_kittest::{Harness, kittest::Queryable}; - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - open(h.state_mut(), "image.imageSize").unwrap(); - h.run_steps(3); - let combo = h.query_all_by_role(egui::accesskit::Role::ComboBox).find(|n| n.value().as_deref() == Some("Nearest Neighbor (hard edges)")); - combo.expect("the Resample list shows Nearest Neighbor").click(); - h.run_steps(3); - assert!(h.query_by_label_contains("Automatic").is_some(), "Automatic is offered"); - for gone in ["Bicubic", "Bilinear", "Lanczos", "Preserve Details"] { - assert!(h.query_by_label_contains(gone).is_none(), "{gone} is not offered for Indexed Color"); - } - } - - /// The dialog starts on Preferences › General › Image Interpolation: Bicubic Automatic opens - /// as Automatic and the others as themselves (Bicubic Sharper used to open as Lanczos). - #[test] - fn resample_follows_the_interpolation_preference() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); - for (pref, method) in - [("bicubicAutomatic", "automatic"), ("bicubicSharper", "bicubicSharper"), ("bicubicSmoother", "bicubicSmoother"), ("nearestNeighbor", "nearest")] - { - app.session.execute("prefs.set", json!({"path": "general.imageInterpolation", "value": pref})).unwrap(); - let id = open(&mut app, "image.imageSize").unwrap(); - let f = &app.ui.dialog_mut(id).unwrap().fields; - assert_eq!((f.get("resample"), f.get("__resample")), (Some(&json!(method)), Some(&json!(method))), "{pref}"); - app.ui.close_dialog(id); - } - let id = open(&mut app, "image.imageSize").unwrap(); - let d = app.ui.dialog_mut(id).unwrap(); - d.fields.insert("width".into(), json!(50)); - d.fields.insert("height".into(), json!(25)); - crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(50, 25)); - } - - /// #441: a typed zero width showed "0 px × 1 px" while OK resized to 1×1. - #[test] - fn typed_zero_width_shows_the_applied_size() { - use egui::accesskit::Role; - use egui_kittest::{Harness, kittest::Queryable}; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - let id = open(h.state_mut(), "image.imageSize").unwrap(); - h.run_steps(3); - // The dialog opens on Width, selected (#2329): the typed 0 replaces the 4. - assert!(h.query_all_by_role(Role::SpinButton).next().expect("the Width field").is_focused()); - h.event(egui::Event::Text("0".into())); - h.run_steps(1); - h.key_press(egui::Key::Tab); - h.run_steps(3); - let f = h.state().ui.dialogs.first().map(|d| d.fields.clone()).expect("the dialog is open"); - assert_eq!((num(&f, "width"), num(&f, "height")), (1.0, 1.0), "{f:?}"); - crate::dialogs::confirm(h.state_mut(), id).unwrap(); - assert_eq!(h.state().session.active().unwrap().doc.size, photocraft_doc::Size::new(1, 1)); - } - - /// An Image Size dialog for a 100 x 50 px, 72 ppi document with Resample off, shown in `unit`. - fn resample_off_dialog(unit: &str) -> (egui_kittest::Harness<'static, PhotocraftApp>, u64) { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 100, "height": 50, "resolution": 72})).unwrap(); - let mut h = egui_kittest::Harness::builder() - .with_size(egui::vec2(1400.0, 900.0)) - .build_ui_state(|ui, app: &mut PhotocraftApp| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - let id = open(h.state_mut(), "image.imageSize").unwrap(); - let d = h.state_mut().ui.dialog_mut(id).unwrap(); - d.fields.insert("resample".into(), json!("none")); - d.fields.insert("__unit".into(), json!(unit)); - h.run_steps(3); - (h, id) - } - - /// #5756: points and picas follow Preferences › Units & Rulers › Point/Pica Size. With - /// Traditional (72.27 pt/in) and Resample off, 100 px typed as 72.27 pt wide is 100 ppi. - #[test] - fn traditional_point_size_drives_points_and_picas() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 100, "height": 50, "resolution": 72})).unwrap(); - app.session.execute("prefs.set", json!({"path": "unitsAndRulers.pointSize", "value": "traditional"})).unwrap(); - for command in ["image.imageSize", "image.canvasSize"] { - let id = open(&mut app, command).unwrap(); - assert_eq!(app.ui.dialog_mut(id).unwrap().fields.get("__ptPerIn"), Some(&json!(72.27)), "{command}"); - app.ui.close_dialog(id); - } - let mut h = egui_kittest::Harness::builder() - .with_size(egui::vec2(1400.0, 900.0)) - .build_ui_state(|ui, app: &mut PhotocraftApp| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - let id = open(h.state_mut(), "image.imageSize").unwrap(); - let d = h.state_mut().ui.dialog_mut(id).unwrap(); - d.fields.insert("resample".into(), json!("none")); - d.fields.insert("__unit".into(), json!("pt")); - h.run_steps(3); - type_width(&mut h, "72.27"); - let f = fields(&h); - assert_eq!((num(&f, "width"), num(&f, "height")), (100.0, 50.0), "{f:?}"); - assert!((num(&f, "resolution") - 100.0).abs() < 1e-2, "{f:?}"); - } - - /// Types `text` into the Width field and leaves it with Tab. - fn type_width(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, text: &str) { - type_into(h, 0, text); - } - - /// Types `text` into the `n`th number field (Width, Height, Resolution) and leaves it with Tab. - fn type_into(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, n: usize, text: &str) { - use egui::accesskit::Role; - use egui_kittest::kittest::Queryable; - let width = h.query_all_by_role(Role::SpinButton).nth(n).map(|n| n.rect()).expect("the number field"); - h.hover_at(width.center()); - h.run_steps(1); - h.drag_at(width.center()); - h.run_steps(1); - h.drop_at(width.center()); - h.run_steps(2); - 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 fields(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> Map { - h.state().ui.dialogs.first().map(|d| d.fields.clone()).expect("the dialog is open") - } - - /// #2393: with Resample off, a pixel Width can't be edited and the readouts keep showing the - /// pixels OK keeps (they showed "200 px × 50 px" and "39K (was 20K)"). - #[test] - fn resample_off_keeps_pixel_dimensions_in_the_dialog() { - use egui_kittest::kittest::Queryable; - let (mut h, id) = resample_off_dialog("px"); - type_width(&mut h, "200"); - let f = fields(&h); - assert_eq!((num(&f, "width"), num(&f, "height"), num(&f, "resolution")), (100.0, 50.0, 72.0), "{f:?}"); - assert!(h.query_by_label("100 px × 50 px").is_some(), "the Dimensions line shows the kept pixels"); - assert!(h.query_by_label_contains("20K (was 20K)").is_some(), "the Image Size estimate is unchanged"); - crate::dialogs::confirm(h.state_mut(), id).unwrap(); - let doc = &h.state().session.active().unwrap().doc; - assert_eq!((doc.size, doc.resolution_dpi), (photocraft_doc::Size::new(100, 50), 72.0)); - } - - /// With Resample off, a physical Width changes the resolution and keeps the pixels (Photoshop): - /// 100 px at 72 ppi is 1.39 in; 2 in wide is 50 ppi. - #[test] - fn resample_off_physical_width_changes_the_resolution() { - let (mut h, id) = resample_off_dialog("in"); - type_width(&mut h, "2"); - let f = fields(&h); - assert_eq!((num(&f, "width"), num(&f, "height")), (100.0, 50.0), "{f:?}"); - assert!((num(&f, "resolution") - 50.0).abs() < 1e-3, "{f:?}"); - crate::dialogs::confirm(h.state_mut(), id).unwrap(); - let doc = &h.state().session.active().unwrap().doc; - assert_eq!(doc.size, photocraft_doc::Size::new(100, 50)); - assert!((doc.resolution_dpi - 50.0).abs() < 1e-3, "{}", doc.resolution_dpi); - } - - /// #6979: with Resample on, a new Resolution keeps the print size in a physical unit and - /// resamples the pixels (Photoshop): 720 x 576 px at 72 ppi is 10 x 8 in, so 300 ppi is - /// 3000 x 2400 px. In pixels the pixel count stays. - #[test] - fn resample_on_resolution_keeps_the_physical_size() { - for (unit, size) in [("in", (3000.0, 2400.0)), ("cm", (3000.0, 2400.0)), ("px", (720.0, 576.0))] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 720, "height": 576, "resolution": 72})).unwrap(); - let mut h = egui_kittest::Harness::builder() - .with_size(egui::vec2(1400.0, 900.0)) - .build_ui_state(|ui, app: &mut PhotocraftApp| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - let id = open(h.state_mut(), "image.imageSize").unwrap(); - let d = h.state_mut().ui.dialog_mut(id).unwrap(); - d.fields.insert("resample".into(), json!("bicubic")); - d.fields.insert("__unit".into(), json!(unit)); - h.run_steps(3); - type_into(&mut h, 2, "300"); - let f = fields(&h); - assert_eq!((num(&f, "width"), num(&f, "height"), num(&f, "resolution")), (size.0, size.1, 300.0), "{unit}: {f:?}"); - crate::dialogs::confirm(h.state_mut(), id).unwrap(); - let doc = &h.state().session.active().unwrap().doc; - assert_eq!((doc.size, doc.resolution_dpi), (photocraft_doc::Size::new(size.0 as u32, size.1 as u32), 300.0), "{unit}"); - } - } - - /// #4162: a document wider than 30000 units in a physical unit (40000 px at 72 ppi is 40000 pt) - /// kept its size in the fields and on OK; the fields clamped it to 30000 on open, so OK with - /// no edit resized (Image Size) or cropped (Canvas Size) it. - #[test] - fn large_documents_in_physical_units_open_unchanged() { - use egui_kittest::Harness; - let mut wrong = Vec::new(); - for command in ["image.imageSize", "image.canvasSize"] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 40000, "height": 4, "resolution": 72})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - let id = open(h.state_mut(), command).unwrap(); - h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("__unit".into(), json!("pt")); - h.run_steps(3); - let f = fields(&h); - let shown = (num(&f, "width"), num(&f, "height")); - crate::dialogs::confirm(h.state_mut(), id).unwrap(); - let size = h.state().session.active().unwrap().doc.size; - if shown != (40000.0, 4.0) || size != photocraft_doc::Size::new(40000, 4) { - wrong.push(format!("{command}: fields {shown:?}, document {size:?}")); - } - } - assert!(wrong.is_empty(), "{wrong:#?}"); - } - - /// #2329: Image Size and Canvas Size open on Width with its value selected, as in Photoshop: - /// typing replaces it and Enter applies it. - #[test] - fn sizing_dialogs_open_on_width_selected() { - use egui::accesskit::Role; - use egui_kittest::{Harness, kittest::Queryable}; - for command in ["image.imageSize", "image.canvasSize"] { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - open(h.state_mut(), command).unwrap(); - h.run_steps(3); - assert!(h.query_all_by_role(Role::SpinButton).next().expect("the Width field").is_focused(), "{command}: Width has focus"); - h.event(egui::Event::Text("50".into())); - h.run_steps(1); - let f = h.state().ui.dialogs.first().map(|d| d.fields.clone()).expect("the dialog is open"); - assert_eq!(num(&f, "width"), 50.0, "{command}: typing replaced the selected 200"); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert!(h.state().ui.dialogs.is_empty(), "{command}: Enter is OK"); - assert_eq!(h.state().session.active().unwrap().doc.size.width, 50, "{command}"); - } - } -} +mod tests; diff --git a/crates/ui-egui/src/sizing/tests.rs b/crates/ui-egui/src/sizing/tests.rs new file mode 100644 index 0000000000..a7e7c1dd20 --- /dev/null +++ b/crates/ui-egui/src/sizing/tests.rs @@ -0,0 +1,337 @@ +use super::*; + +#[test] +fn unit_conversions_round_trip() { + for ppi in [72.0, 72.27] { + for unit in ["px", "percent", "in", "cm", "mm", "pt", "pica"] { + let v = to_unit(1500.0, unit, 3000.0, 300.0, ppi); + assert!((from_unit(v, unit, 3000.0, 300.0, ppi) - 1500.0).abs() < 1e-9, "{unit} at {ppi} pt/in"); + } + } + assert_eq!(to_unit(1500.0, "percent", 3000.0, 300.0, 72.0), 50.0); + assert_eq!(to_unit(600.0, "in", 3000.0, 300.0, 72.0), 2.0); + assert_eq!(human_bytes(6016.0 * 6016.0 * 4.0), "138.1M"); +} + +/// #5756: points and picas use the Point/Pica Size preference (Traditional is 72.27 pt/in), +/// and a dialog without the field (or with a bad one) falls back to PostScript's 72. +#[test] +fn points_and_picas_use_the_points_per_inch() { + assert!((to_unit(72.0, "pt", 72.0, 72.0, 72.27) - 72.27).abs() < 1e-9); + assert!((to_unit(72.0, "pica", 72.0, 72.0, 72.27) - 72.27 / 12.0).abs() < 1e-9); + assert_eq!(to_unit(72.0, "pt", 72.0, 72.0, 72.0), 72.0); + assert_eq!(to_unit(72.0, "pica", 72.0, 72.0, 72.0), 6.0); + assert!((from_unit(72.27, "pt", 72.0, 72.0, 72.27) - 72.0).abs() < 1e-9); + let mut f = Map::new(); + assert_eq!(pt_per_in(&f), 72.0); + for bad in [json!(0.0), json!(-3.0), json!("x")] { + f.insert("__ptPerIn".into(), bad); + assert_eq!(pt_per_in(&f), 72.0); + } + f.insert("__ptPerIn".into(), json!(72.27)); + assert_eq!(pt_per_in(&f), 72.27); +} + +#[test] +fn dialog_maps_to_engine_command() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + let id = open(&mut app, "image.imageSize").unwrap(); + let d = app.ui.dialog_mut(id).unwrap(); + d.fields.insert("width".into(), json!(100)); + d.fields.insert("height".into(), json!(50)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(100, 50)); + let id = open(&mut app, "image.canvasSize").unwrap(); + let d = app.ui.dialog_mut(id).unwrap(); + d.fields.insert("width".into(), json!(120)); + d.fields.insert("anchor".into(), json!("topLeft")); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(120, 50)); +} + +#[test] +fn alt_reset_restores_open_dimensions() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100, "resolution": 72})).unwrap(); + let id = open(&mut app, "image.imageSize").unwrap(); + let d = app.ui.dialog_mut(id).unwrap(); + d.fields.insert("width".into(), json!(50)); + d.fields.insert("height".into(), json!(25)); + d.fields.insert("resolution".into(), json!(300)); + d.fields.insert("__constrain".into(), json!(false)); + reset(&mut d.fields); + assert_eq!((num(&d.fields, "width"), num(&d.fields, "height"), num(&d.fields, "resolution")), (200.0, 100.0, 72.0)); + assert_eq!(d.fields.get("__constrain"), Some(&json!(true))); + assert!(app.ui.dialogs.iter().any(|x| x.id == id), "reset leaves the dialog open"); +} + +#[test] +fn canvas_extension_dropdown_is_named_for_its_setting() { + use egui::accesskit::Role; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 100, "height": 50})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app: &mut PhotocraftApp| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut(), "image.canvasSize").unwrap(); + h.run_steps(3); + let labels: Vec = h.query_all_by_role(Role::ComboBox).filter_map(|n| n.accesskit_node().label()).collect(); + assert!(labels.iter().any(|label| label == "Canvas extension color:"), "{labels:?}"); + assert!(!labels.iter().any(|label| label == "Size"), "the dialog's Size label names a different field: {labels:?}"); +} + +/// #6019: on an Indexed Color document the dialog opens on, and offers only, Automatic and Nearest Neighbor. +#[test] +fn indexed_color_resamples_with_nearest_neighbor_only() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.session.execute("image.mode.indexedColor", json!({})).unwrap(); + for (pref, method) in [("bicubic", "nearest"), ("bicubicAutomatic", "automatic"), ("nearestNeighbor", "nearest")] { + app.session.execute("prefs.set", json!({"path": "general.imageInterpolation", "value": pref})).unwrap(); + let id = open(&mut app, "image.imageSize").unwrap(); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!(f.get("resample"), Some(&json!(method)), "{pref}"); + assert_eq!(f.get("__indexed"), Some(&json!(true))); + app.ui.close_dialog(id); + } + // The open list offers only Automatic and Nearest Neighbor. + use egui_kittest::{Harness, kittest::Queryable}; + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut(), "image.imageSize").unwrap(); + h.run_steps(3); + let combo = h.query_all_by_role(egui::accesskit::Role::ComboBox).find(|n| n.value().as_deref() == Some("Nearest Neighbor (hard edges)")); + combo.expect("the Resample list shows Nearest Neighbor").click(); + h.run_steps(3); + assert!(h.query_by_label_contains("Automatic").is_some(), "Automatic is offered"); + for gone in ["Bicubic", "Bilinear", "Lanczos", "Preserve Details"] { + assert!(h.query_by_label_contains(gone).is_none(), "{gone} is not offered for Indexed Color"); + } +} + +/// The dialog starts on Preferences › General › Image Interpolation: Bicubic Automatic opens +/// as Automatic and the others as themselves (Bicubic Sharper used to open as Lanczos). +#[test] +fn resample_follows_the_interpolation_preference() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + for (pref, method) in + [("bicubicAutomatic", "automatic"), ("bicubicSharper", "bicubicSharper"), ("bicubicSmoother", "bicubicSmoother"), ("nearestNeighbor", "nearest")] + { + app.session.execute("prefs.set", json!({"path": "general.imageInterpolation", "value": pref})).unwrap(); + let id = open(&mut app, "image.imageSize").unwrap(); + let f = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!((f.get("resample"), f.get("__resample")), (Some(&json!(method)), Some(&json!(method))), "{pref}"); + app.ui.close_dialog(id); + } + let id = open(&mut app, "image.imageSize").unwrap(); + let d = app.ui.dialog_mut(id).unwrap(); + d.fields.insert("width".into(), json!(50)); + d.fields.insert("height".into(), json!(25)); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.active().unwrap().doc.size, photocraft_doc::Size::new(50, 25)); +} + +/// #441: a typed zero width showed "0 px × 1 px" while OK resized to 1×1. +#[test] +fn typed_zero_width_shows_the_applied_size() { + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(h.state_mut(), "image.imageSize").unwrap(); + h.run_steps(3); + // The dialog opens on Width, selected (#2329): the typed 0 replaces the 4. + assert!(h.query_all_by_role(Role::SpinButton).next().expect("the Width field").is_focused()); + h.event(egui::Event::Text("0".into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); + let f = h.state().ui.dialogs.first().map(|d| d.fields.clone()).expect("the dialog is open"); + assert_eq!((num(&f, "width"), num(&f, "height")), (1.0, 1.0), "{f:?}"); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + assert_eq!(h.state().session.active().unwrap().doc.size, photocraft_doc::Size::new(1, 1)); +} + +/// An Image Size dialog for a 100 x 50 px, 72 ppi document with Resample off, shown in `unit`. +fn resample_off_dialog(unit: &str) -> (egui_kittest::Harness<'static, PhotocraftApp>, u64) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 100, "height": 50, "resolution": 72})).unwrap(); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(1400.0, 900.0)) + .build_ui_state(|ui, app: &mut PhotocraftApp| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(h.state_mut(), "image.imageSize").unwrap(); + let d = h.state_mut().ui.dialog_mut(id).unwrap(); + d.fields.insert("resample".into(), json!("none")); + d.fields.insert("__unit".into(), json!(unit)); + h.run_steps(3); + (h, id) +} + +/// #5756: points and picas follow Preferences › Units & Rulers › Point/Pica Size. With +/// Traditional (72.27 pt/in) and Resample off, 100 px typed as 72.27 pt wide is 100 ppi. +#[test] +fn traditional_point_size_drives_points_and_picas() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 100, "height": 50, "resolution": 72})).unwrap(); + app.session.execute("prefs.set", json!({"path": "unitsAndRulers.pointSize", "value": "traditional"})).unwrap(); + for command in ["image.imageSize", "image.canvasSize"] { + let id = open(&mut app, command).unwrap(); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields.get("__ptPerIn"), Some(&json!(72.27)), "{command}"); + app.ui.close_dialog(id); + } + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(1400.0, 900.0)) + .build_ui_state(|ui, app: &mut PhotocraftApp| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(h.state_mut(), "image.imageSize").unwrap(); + let d = h.state_mut().ui.dialog_mut(id).unwrap(); + d.fields.insert("resample".into(), json!("none")); + d.fields.insert("__unit".into(), json!("pt")); + h.run_steps(3); + type_width(&mut h, "72.27"); + let f = fields(&h); + assert_eq!((num(&f, "width"), num(&f, "height")), (100.0, 50.0), "{f:?}"); + assert!((num(&f, "resolution") - 100.0).abs() < 1e-2, "{f:?}"); +} + +/// Types `text` into the Width field and leaves it with Tab. +fn type_width(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, text: &str) { + type_into(h, 0, text); +} + +/// Types `text` into the `n`th number field (Width, Height, Resolution) and leaves it with Tab. +fn type_into(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, n: usize, text: &str) { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let width = h.query_all_by_role(Role::SpinButton).nth(n).map(|n| n.rect()).expect("the number field"); + h.hover_at(width.center()); + h.run_steps(1); + h.drag_at(width.center()); + h.run_steps(1); + h.drop_at(width.center()); + h.run_steps(2); + 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 fields(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> Map { + h.state().ui.dialogs.first().map(|d| d.fields.clone()).expect("the dialog is open") +} + +/// #2393: with Resample off, a pixel Width can't be edited and the readouts keep showing the +/// pixels OK keeps (they showed "200 px × 50 px" and "39K (was 20K)"). +#[test] +fn resample_off_keeps_pixel_dimensions_in_the_dialog() { + use egui_kittest::kittest::Queryable; + let (mut h, id) = resample_off_dialog("px"); + type_width(&mut h, "200"); + let f = fields(&h); + assert_eq!((num(&f, "width"), num(&f, "height"), num(&f, "resolution")), (100.0, 50.0, 72.0), "{f:?}"); + assert!(h.query_by_label("100 px × 50 px").is_some(), "the Dimensions line shows the kept pixels"); + assert!(h.query_by_label_contains("20K (was 20K)").is_some(), "the Image Size estimate is unchanged"); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + let doc = &h.state().session.active().unwrap().doc; + assert_eq!((doc.size, doc.resolution_dpi), (photocraft_doc::Size::new(100, 50), 72.0)); +} + +/// With Resample off, a physical Width changes the resolution and keeps the pixels (Photoshop): +/// 100 px at 72 ppi is 1.39 in; 2 in wide is 50 ppi. +#[test] +fn resample_off_physical_width_changes_the_resolution() { + let (mut h, id) = resample_off_dialog("in"); + type_width(&mut h, "2"); + let f = fields(&h); + assert_eq!((num(&f, "width"), num(&f, "height")), (100.0, 50.0), "{f:?}"); + assert!((num(&f, "resolution") - 50.0).abs() < 1e-3, "{f:?}"); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + let doc = &h.state().session.active().unwrap().doc; + assert_eq!(doc.size, photocraft_doc::Size::new(100, 50)); + assert!((doc.resolution_dpi - 50.0).abs() < 1e-3, "{}", doc.resolution_dpi); +} + +/// #6979: with Resample on, a new Resolution keeps the print size in a physical unit and +/// resamples the pixels (Photoshop): 720 x 576 px at 72 ppi is 10 x 8 in, so 300 ppi is +/// 3000 x 2400 px. In pixels the pixel count stays. +#[test] +fn resample_on_resolution_keeps_the_physical_size() { + for (unit, size) in [("in", (3000.0, 2400.0)), ("cm", (3000.0, 2400.0)), ("px", (720.0, 576.0))] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 720, "height": 576, "resolution": 72})).unwrap(); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(1400.0, 900.0)) + .build_ui_state(|ui, app: &mut PhotocraftApp| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(h.state_mut(), "image.imageSize").unwrap(); + let d = h.state_mut().ui.dialog_mut(id).unwrap(); + d.fields.insert("resample".into(), json!("bicubic")); + d.fields.insert("__unit".into(), json!(unit)); + h.run_steps(3); + type_into(&mut h, 2, "300"); + let f = fields(&h); + assert_eq!((num(&f, "width"), num(&f, "height"), num(&f, "resolution")), (size.0, size.1, 300.0), "{unit}: {f:?}"); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + let doc = &h.state().session.active().unwrap().doc; + assert_eq!((doc.size, doc.resolution_dpi), (photocraft_doc::Size::new(size.0 as u32, size.1 as u32), 300.0), "{unit}"); + } +} + +/// #4162: a document wider than 30000 units in a physical unit (40000 px at 72 ppi is 40000 pt) +/// kept its size in the fields and on OK; the fields clamped it to 30000 on open, so OK with +/// no edit resized (Image Size) or cropped (Canvas Size) it. +#[test] +fn large_documents_in_physical_units_open_unchanged() { + use egui_kittest::Harness; + let mut wrong = Vec::new(); + for command in ["image.imageSize", "image.canvasSize"] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 40000, "height": 4, "resolution": 72})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(h.state_mut(), command).unwrap(); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("__unit".into(), json!("pt")); + h.run_steps(3); + let f = fields(&h); + let shown = (num(&f, "width"), num(&f, "height")); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + let size = h.state().session.active().unwrap().doc.size; + if shown != (40000.0, 4.0) || size != photocraft_doc::Size::new(40000, 4) { + wrong.push(format!("{command}: fields {shown:?}, document {size:?}")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// #2329: Image Size and Canvas Size open on Width with its value selected, as in Photoshop: +/// typing replaces it and Enter applies it. +#[test] +fn sizing_dialogs_open_on_width_selected() { + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + for command in ["image.imageSize", "image.canvasSize"] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut(), command).unwrap(); + h.run_steps(3); + assert!(h.query_all_by_role(Role::SpinButton).next().expect("the Width field").is_focused(), "{command}: Width has focus"); + h.event(egui::Event::Text("50".into())); + h.run_steps(1); + let f = h.state().ui.dialogs.first().map(|d| d.fields.clone()).expect("the dialog is open"); + assert_eq!(num(&f, "width"), 50.0, "{command}: typing replaced the selected 200"); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty(), "{command}: Enter is OK"); + assert_eq!(h.state().session.active().unwrap().doc.size.width, 50, "{command}"); + } +} From 0a2c8f0b09b0b9abbfff048aa14e7a65fe144e32 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:40 +0000 Subject: [PATCH 108/259] refactor(ui-egui): move transform_tool.rs tests to transform_tool/tests.rs --- crates/ui-egui/src/transform_tool.rs | 3007 +------------------- crates/ui-egui/src/transform_tool/tests.rs | 3004 +++++++++++++++++++ 2 files changed, 3005 insertions(+), 3006 deletions(-) create mode 100644 crates/ui-egui/src/transform_tool/tests.rs diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index 9cd31d2e29..58e412d784 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -3278,3009 +3278,4 @@ fn rotate_about_pivot(app: &mut PhotocraftApp, da: f64) { } #[cfg(test)] -mod tests { - use super::*; - - fn session() -> TransformSession { - TransformSession { - session: 1, - layer: 1, - rect: [0.0, 0.0, 100.0, 50.0], - quad: corners([0.0, 0.0, 100.0, 50.0]), - pivot: [50.0, 25.0], - interpolation: "bicubic".into(), - warp: None, - selection: false, - target: None, - path: None, - made: None, - mode: Default::default(), - content_aware: None, - skew_v: 0.0, - } - } - - #[test] - fn a_plain_click_far_outside_accepts_transform_but_a_rotation_drag_does_not() { - let context = egui::Context::default(); - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - begin(&mut app, &context).unwrap(); - let before = app.session.active().unwrap().history.past_len(); - let t = app.ui.transform.as_mut().unwrap(); - t.quad = t.quad.map(|[x, y]| [x + 6.0, y]); - let outside = [44.0, 44.0]; - let none = egui::Modifiers::NONE; - assert!(pointer(&mut app, ToolEvent::Down { x: outside[0], y: outside[1], pressure: 1.0 }, none)); - assert!(app.ui.transform.is_some(), "press alone does not accept"); - assert!(pointer(&mut app, ToolEvent::Up { x: outside[0], y: outside[1] }, none)); - assert!(app.ui.transform.is_none(), "a release without a drag commits"); - assert_eq!(app.session.active().unwrap().history.past_len(), before + 1, "one undo step for the transform"); - let st = app.session.active().unwrap(); - let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); - assert_eq!(layer.surface().unwrap().content_bounds(), photocraft_geom::Rect::new(14, 8, 30, 24)); - - // An outside drag remains a rotation gesture; releasing it does not commit. - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - begin(&mut app, &context).unwrap(); - let start = [44.0, 44.0]; - let end = [44.0, 54.0]; - let original = app.ui.transform.as_ref().unwrap().quad; - pointer(&mut app, ToolEvent::Down { x: start[0], y: start[1], pressure: 1.0 }, none); - pointer(&mut app, ToolEvent::Move { x: end[0], y: end[1], pressure: 1.0 }, none); - pointer(&mut app, ToolEvent::Up { x: end[0], y: end[1] }, none); - assert!(app.ui.transform.is_some(), "rotation stays active after an outside drag"); - assert_ne!(app.ui.transform.as_ref().unwrap().quad, original); - } - - #[test] - fn a_click_near_rotation_handles_accepts_but_drags_and_option_pivot_do_not() { - let t = session(); - let tol = 12.0; - let near = Gesture { hit: Hit::Outside, start: [-18.0, -18.0], quad0: t.quad, pivot0: t.pivot }; - assert!(accepts_outside_click(near, near.start, tol), "a click in the rotation zone accepts; a drag still rotates"); - let far = Gesture { start: [500.0, 500.0], ..near }; - assert!(accepts_outside_click(far, far.start, tol)); - assert!(!accepts_outside_click(far, [512.0, 500.0], tol), "drag does not commit"); - let handle = Gesture { hit: Hit::Corner(0), ..near }; - assert!(!accepts_outside_click(handle, handle.start, tol), "resize handles stay interactive"); - - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - begin(&mut app, &egui::Context::default()).unwrap(); - let p = [44.0, 44.0]; - pointer(&mut app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, egui::Modifiers::ALT); - pointer(&mut app, ToolEvent::Up { x: p[0], y: p[1] }, egui::Modifiers::ALT); - assert!(app.ui.transform.is_some(), "Option-click moves the pivot, never accepts"); - assert_eq!(app.ui.transform.as_ref().unwrap().pivot, p); - } - - #[test] - fn rotate_feedback_only_appears_just_outside_corners() { - let mut t = session(); - assert!(near_rotate_corner(&t, [-18.0, -18.0], 12.0)); - assert!(!near_rotate_corner(&t, [50.0, 25.0], 12.0), "inside moves the box"); - assert!(!near_rotate_corner(&t, [500.0, 500.0], 12.0), "far outside stays generic"); - assert!(!near_rotate_corner(&t, [2.0, 2.0], 12.0), "corner handle resizes"); - t.mode = TransformMode::Distort; - assert!(!near_rotate_corner(&t, [-18.0, -18.0], 12.0)); - } - - #[test] - fn angle_readout_tracks_rotated_quad_and_handles_degenerate_edges() { - let mut t = session(); - assert_eq!(rotation_degrees(t.quad), 0.0); - let pivot = t.pivot; - t.quad = t.quad.map(|q| [pivot[0] - (q[1] - pivot[1]), pivot[1] + (q[0] - pivot[0])]); - assert!((rotation_degrees(t.quad) - 90.0).abs() < 1e-9); - t.quad[1] = t.quad[0]; - assert_eq!(rotation_degrees(t.quad), 0.0); - } - - #[test] - fn transform_bar_pins_warp_cancel_and_commit() { - use egui_kittest::Harness; - use egui_kittest::kittest::Queryable; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.ui.transform = Some(session()); - let width = 720.0; - let mut h = Harness::builder().with_size(vec2(width, 48.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - ui.horizontal_centered(|ui| options_bar(app, ui)); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run_steps(6); - let commit = h.get_by_label("Commit transform").rect(); - let cancel = h.get_by_label("Cancel transform").rect(); - let mode = h.get_by_label("Switch between free transform and warp modes").rect(); - assert!(commit.right() > width - 36.0, "commit sits on the right: {commit:?}"); - assert!(cancel.right() < commit.left() + 1.0, "cancel is left of commit"); - assert!(mode.right() < cancel.left() + 1.0, "warp switch is left of cancel"); - h.get_by_label("Switch between free transform and warp modes").click(); - h.run_steps(2); - assert!(h.state().ui.transform.as_ref().unwrap().warp.is_some()); - h.get_by_label("Switch between free transform and warp modes").click(); - h.run_steps(2); - assert!(h.state().ui.transform.as_ref().unwrap().warp.is_none()); - h.get_by_label("Cancel transform").click(); - h.run_steps(2); - assert!(h.state().ui.transform.is_none()); - } - - #[test] - fn free_transform_bar_buttons_follow_the_fields_on_a_wide_bar() { - use egui_kittest::Harness; - use egui_kittest::kittest::Queryable; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.ui.transform = Some(session()); - let width = 2400.0; - let mut h = Harness::builder().with_size(vec2(width, 48.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - ui.horizontal_centered(|ui| options_bar(app, ui)); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run_steps(6); - let commit = h.get_by_label("Commit transform").rect(); - assert!(commit.right() < width * 0.7, "commit sits next to the fields, not at the far right: {commit:?}"); - } - - #[test] - fn warp_bar_buttons_follow_the_fields_on_a_wide_bar() { - use egui_kittest::Harness; - use egui_kittest::kittest::Queryable; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.ui.transform = Some(session()); - let width = 2000.0; - let mut h = Harness::builder().with_size(vec2(width, 48.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - ui.horizontal_centered(|ui| options_bar(app, ui)); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run_steps(6); - h.get_by_label("Switch between free transform and warp modes").click(); - h.run_steps(4); - assert!(h.state().ui.transform.as_ref().unwrap().warp.is_some()); - let commit = h.get_by_label("Commit transform").rect(); - assert!(commit.right() < width / 2.0, "commit sits next to the fields, not at the far right: {commit:?}"); - let reset = h.get_by_label("Reset warp").rect(); - assert!(reset.right() < commit.left() + 1.0, "reset is left of commit"); - h.get_by_label("Reset warp").click(); - h.run_steps(2); - assert!(h.state().ui.transform.as_ref().unwrap().warp.as_ref().unwrap().is_identity()); - } - - fn eq6(a: f64, b: f64) -> bool { - (a - b).abs() < 1e-6 - } - - /// Scale, skew and rotation read back exactly from the box they make, flips included. - #[test] - fn parts_round_trip() { - for (sx, sy, angle, h, v) in [(1.0, 1.0, 0.0, 0.0, 0.0), (1.5, 0.5, 30.0, 20.0, 0.0), (0.8, -1.2, -120.0, -35.0, 15.0), (2.0, 1.0, 179.0, 0.0, -60.0)] { - let p = Parts { sx, sy, angle: f64::to_radians(angle), skew_h: f64::to_radians(h), skew_v: f64::to_radians(v) }; - let back = Parts::from_columns(p.columns_of(), p.skew_v); - for (a, b) in [(back.sx, p.sx), (back.sy, p.sy), (back.angle, p.angle), (back.skew_h, p.skew_h)] { - assert!(eq6(a, b), "{p:?} read back as {back:?}"); - } - } - } - - /// A box sheared sideways keeps W, H and the angle; only H skew moves (it used to read as a - /// taller box). - #[test] - fn a_sheared_box_reads_as_horizontal_skew() { - let mut t = session(); - // The 100×50 frame with its bottom slid 50·tan 20° to the left: a positive H skew. - let d = 50.0 * 20f64.to_radians().tan(); - t.quad = [[0.0, 0.0], [100.0, 0.0], [100.0 - d, 50.0], [-d, 50.0]]; - let (w, h, angle, skew) = readout(&t); - assert!(eq6(w, 100.0) && eq6(h, 100.0) && eq6(angle, 0.0), "{w} {h} {angle}"); - assert!(eq6(skew, 20.0), "{skew}"); - } - - /// The test box flipped horizontally and vertically, as Edit › Transform › Flip leaves it. - const FLIPPED_H: [[f64; 2]; 4] = [[100.0, 0.0], [0.0, 0.0], [0.0, 50.0], [100.0, 50.0]]; - const FLIPPED_V: [[f64; 2]; 4] = [[0.0, 50.0], [100.0, 50.0], [100.0, 0.0], [0.0, 0.0]]; - - /// Photoshop puts a flip's minus on the flipped axis and keeps the angle at 0: Flip Horizontal - /// reads W -100 %, Flip Vertical H -100 % (it read 180° and nothing at all). - #[test] - fn a_flipped_box_reads_as_a_negative_scale_on_that_axis() { - let mut t = session(); - for (quad, want) in [(FLIPPED_H, (-100.0, 100.0)), (FLIPPED_V, (100.0, -100.0))] { - t.quad = quad; - let (w, h, angle, skew) = readout(&t); - assert!(eq6(w, want.0) && eq6(h, want.1) && eq6(angle, 0.0) && eq6(skew, 0.0), "{quad:?}: {w} {h} {angle} {skew}"); - } - // Flipped both ways is a half turn, not a mirror. - t.quad = [[100.0, 50.0], [0.0, 50.0], [0.0, 0.0], [100.0, 0.0]]; - let (w, h, angle, _) = readout(&t); - assert!(eq6(w, 100.0) && eq6(h, 100.0) && eq6(angle.abs(), 180.0), "{w} {h} {angle}"); - } - - /// The bar's fields act on a flipped box without undoing the flip: angle 0 keeps it as it is, - /// and a typed W scales it and keeps it mirrored. - #[test] - fn bar_fields_keep_a_flipped_box_flipped() { - let flip_h = |app: &mut PhotocraftApp| app.ui.transform.as_mut().unwrap().quad = FLIPPED_H; - let t = type_into_bar_field_with(flip_h, 4, "0"); - assert!(t.quad.iter().flatten().zip(FLIPPED_H.iter().flatten()).all(|(a, b)| eq6(*a, *b)), "{:?}", t.quad); - let t = type_into_bar_field_with(flip_h, 2, "-50"); - let (w, h, angle, _) = readout(&t); - assert!(eq6(w, -50.0) && eq6(h, 50.0) && eq6(angle, 0.0), "{w} {h} {angle}"); - assert!(eq6(t.quad[0][0] - t.quad[1][0], 50.0), "50 px wide, still mirrored: {:?}", t.quad); - let flip_v = |app: &mut PhotocraftApp| app.ui.transform.as_mut().unwrap().quad = FLIPPED_V; - let t = type_into_bar_field_with(flip_v, 3, "-200"); - let (w, h, _, _) = readout(&t); - assert!(eq6(w, 200.0) && eq6(h, -200.0), "{w} {h}"); - } - - /// Typing H and V skews leans the box about the reference point; the angle, W and H fields keep - /// their values, and V stays as typed. - #[test] - fn skew_fields_lean_the_box_about_the_reference_point() { - let t = type_into_bar_field(5, "20"); - let (w, h, angle, skew) = readout(&t); - assert!(eq6(skew, 20.0) && eq6(angle, 0.0) && eq6(w, 100.0) && eq6(h, 100.0), "{w} {h} {angle} {skew}"); - // The pivot (50, 25) stays put: the top edge slid right, the bottom left, by the same amount. - let d = 25.0 * 20f64.to_radians().tan(); - assert!(eq6(t.quad[0][0], d) && eq6(t.quad[0][1], 0.0) && eq6(t.quad[3][0], -d) && eq6(t.quad[3][1], 50.0), "{:?}", t.quad); - - let t = type_into_bar_field(6, "-10"); - assert!(eq6(t.skew_v, -10.0)); - let (w, h, angle, skew) = readout(&t); - assert!(eq6(skew, 0.0) && eq6(angle, 0.0) && eq6(w, 100.0) && eq6(h, 100.0), "{w} {h} {angle} {skew}"); - // The right side rose: tan(−10°) per pixel across, about the pivot. - let d = 50.0 * (-10f64).to_radians().tan(); - assert!(eq6(t.quad[1][1], d) && eq6(t.quad[0][1], -d), "{:?}", t.quad); - // A skew past ±90° would flatten the box: the field stops at the limit. - let t = type_into_bar_field(5, "120"); - assert!(eq6(readout(&t).3, f64::from(SKEW_LIMIT_DEG)), "{}", readout(&t).3); - } - - /// Types `text` + Enter into the `n`th numeric field of the transform bar (X, Y, W, H, angle…). - fn type_into_bar_field(n: usize, text: &str) -> TransformSession { - type_into_bar_field_with(|_| {}, n, text) - } - - /// The transform bar over the test box, after `setup` (e.g. picking the W/H unit). Tall enough - /// for the fields' unit menu to open below the bar unscrolled. - fn bar_harness(setup: impl FnOnce(&mut PhotocraftApp)) -> egui_kittest::Harness<'static, PhotocraftApp> { - use egui_kittest::Harness; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.ui.transform = Some(session()); - setup(&mut app); - let mut h = Harness::builder().with_size(vec2(900.0, 360.0)).build_ui_state( - |ui, app: &mut PhotocraftApp| { - if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - ui.horizontal_centered(|ui| options_bar(app, ui)); - }, - app, - ); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); - h.run_steps(6); - h - } - - /// [`type_into_bar_field`] after `setup`. - fn type_into_bar_field_with(setup: impl FnOnce(&mut PhotocraftApp), n: usize, text: &str) -> TransformSession { - use egui_kittest::kittest::Queryable; - let mut h = bar_harness(setup); - h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(n).unwrap().click(); - h.run(); - for c in text.chars() { - h.event(egui::Event::Text(c.to_string())); - h.run(); - } - h.key_press(egui::Key::Enter); - h.run_steps(2); - h.state().ui.transform.clone().unwrap() - } - - /// The values the W and H fields show (the 3rd and 4th numeric fields). - fn shown_size(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> Vec { - use egui_kittest::kittest::{NodeT, Queryable}; - h.get_all_by_role(egui::accesskit::Role::SpinButton).skip(2).take(2).map(|n| n.accesskit_node().value().unwrap_or_default().to_string()).collect() - } - - #[test] - fn size_fields_convert_between_percent_and_lengths() { - use crate::layer_props_ui::LenUnit; - use photocraft_engine::prefs::Unit; - // A 300 px side at 300 ppi is one inch at 100 %. - let at = |unit| LenUnit { unit, dpi: 300.0, ppi: 72.0 }; - for (unit, at_100) in [ - (Unit::Percent, 100.0), - (Unit::Pixels, 300.0), - (Unit::Inches, 1.0), - (Unit::Centimeters, 2.54), - (Unit::Millimeters, 25.4), - (Unit::Points, 72.0), - (Unit::Picas, 6.0), - ] { - let u = at(unit); - let shown = size_shown(&u, 100.0, 300.0); - assert!((f64::from(shown) - at_100).abs() < 1e-3, "{unit:?}: {shown}"); - assert!((size_shown(&u, 150.0, 300.0) - shown * 1.5).abs() < 1e-3, "{unit:?} scales with the box"); - assert!((size_pct(&u, shown * 2.0, 300.0) - 200.0).abs() < 1e-3, "{unit:?}: twice the length is 200 %"); - assert!((size_pct(&u, -shown, 300.0) + 100.0).abs() < 1e-3, "{unit:?}: a negative length flips"); - } - // A degenerate side never divides by zero. - assert!(size_pct(&at(Unit::Inches), 1.0, 0.0).is_finite()); - } - - #[test] - fn w_and_h_take_lengths_in_the_unit_picked_for_them() { - use photocraft_engine::prefs::Unit; - // The test box is 100 × 50 px; with no document open, lengths convert at 72 ppi. - let cm = |app: &mut PhotocraftApp| set_size_unit(app, Unit::Centimeters.name()); - let h = bar_harness(cm); - assert_eq!(shown_size(&h), ["3.53", "1.76"], "the box's size in cm, not 100 %"); - // 7.06 cm is twice the width; linked, the height follows. - let t = type_into_bar_field_with(cm, 2, "7.06"); - let (sx, sy, _, _) = readout(&t); - assert!((sx - 200.0).abs() < 0.2 && (sy - 200.0).abs() < 0.2, "{sx} {sy}"); - // Pixels: an exact width. - let t = type_into_bar_field_with(|app| set_size_unit(app, Unit::Pixels.name()), 2, "250"); - assert!((t.quad[1][0] - t.quad[0][0] - 250.0).abs() < 0.01, "{:?}", t.quad); - // Percent is still the default. - assert_eq!(shown_size(&bar_harness(|_| {})), ["100", "100"]); - } - - /// Opens a document at `dpi` so the W/H fields convert typed lengths at its resolution. - fn at_dpi(app: &mut PhotocraftApp, dpi: f32) { - app.session.execute("file.new", json!({"width": 400, "height": 400})).unwrap(); - app.session - .edit("resolution", |doc, _| { - doc.resolution_dpi = dpi; - Ok(()) - }) - .unwrap(); - } - - /// The box's width and height in px after a W/H edit. - fn box_size(t: &TransformSession) -> (f64, f64) { - (t.quad[1][0] - t.quad[0][0], t.quad[3][1] - t.quad[0][1]) - } - - #[test] - fn w_and_h_in_percent_take_a_typed_length() { - use photocraft_engine::prefs::Unit; - let near = |a: f64, b: f64| (a - b).abs() < 0.01; - // The 100 × 50 px box with W/H showing percent (#6284): a typed length is the box's new side. - for (text, px) in - [("40px", 40.0), ("40 px", 40.0), ("2in", 600.0), ("2 in", 600.0), ("5cm", 5.0 / 2.54 * 300.0), ("25.4mm", 300.0), ("72pt", 300.0), ("1pica", 50.0)] - { - // Linked: the height follows the width. - let t = type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, text); - let (w, h) = box_size(&t); - assert!(near(w, px) && near(h, px / 2.0), "{text} linked: {w} × {h}"); - // Unlinked: only the width changes. - let t = type_into_bar_field_with( - |app| { - at_dpi(app, 300.0); - app.ui.transform_unlinked = true; - }, - 2, - text, - ); - let (w, h) = box_size(&t); - assert!(near(w, px) && near(h, 50.0), "{text} unlinked: {w} × {h}"); - } - // H takes a length too; linked, the width follows. - let t = type_into_bar_field_with(|app| at_dpi(app, 300.0), 3, "1in"); - let (w, h) = box_size(&t); - assert!(near(w, 600.0) && near(h, 300.0), "H 1in: {w} × {h}"); - // A plain number is still the percentage. - let (w, _) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "40")); - assert!(near(w, 40.0), "40 is 40 % of 100 px: {w}"); - // A percentage typed into a length field is that share of the box's original side. - let px = |app: &mut PhotocraftApp| { - at_dpi(app, 300.0); - set_size_unit(app, Unit::Pixels.name()); - }; - let (w, h) = box_size(&type_into_bar_field_with(px, 2, "50%")); - assert!(near(w, 50.0) && near(h, 25.0), "50% in px: {w} × {h}"); - let inches = |app: &mut PhotocraftApp| { - at_dpi(app, 300.0); - set_size_unit(app, Unit::Inches.name()); - }; - let (w, h) = box_size(&type_into_bar_field_with(inches, 3, "300%")); - assert!(near(w, 300.0) && near(h, 150.0), "300% in inches: {w} × {h}"); - } - - #[test] - fn w_and_h_reject_or_clamp_hostile_typed_lengths() { - let near = |a: f64, b: f64| (a - b).abs() < 0.01; - // Text that is no number leaves the box alone. - for text in ["px", "in", "NaN", "%"] { - let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, text)); - assert!(near(w, 100.0) && near(h, 50.0), "{text}: {w} × {h}"); - } - // Invalid text after a number keeps only what applied while typing (a plain number applies - // per keystroke), never a NaN or a box past the largest document. - for text in ["1in/0", "1e400px", "2 inches", "1e308in"] { - let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, text)); - assert!(w.is_finite() && h.is_finite() && w.abs() <= f64::from(POSITION_LIMIT_PX) + 0.01, "{text}: {w} × {h}"); - } - // A huge length stops at the field's limit: the box stays within the largest document. - let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "1e9in")); - assert!(w.is_finite() && w <= f64::from(POSITION_LIMIT_PX) + 0.01 && h <= f64::from(POSITION_LIMIT_PX), "{w} × {h}"); - // A negative length flips, as a negative percentage does. - let (w, _) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "-40px")); - assert!(near(w, -40.0), "{w}"); - // Zero collapses the side without dividing by zero. - let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "0px")); - assert!(w.is_finite() && h.is_finite(), "{w} × {h}"); - } - - #[test] - fn right_clicking_w_or_h_picks_their_unit_and_remembers_it() { - use egui_kittest::kittest::Queryable; - let mut h = bar_harness(|_| {}); - h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(2).unwrap().click_secondary(); - h.run_steps(2); - h.get_by_label("Inches").click(); - h.run_steps(3); - assert_eq!(size_unit(h.state()).unit, photocraft_engine::prefs::Unit::Inches); - assert_eq!(h.state().session.prefs().dialogs[SIZE_UNIT_KEY]["sizeUnit"], "inches"); - assert_eq!(shown_size(&h), ["1.389", "0.694"], "100 × 50 px at 72 ppi"); - // H opens the same menu, with the current unit checked. - h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(3).unwrap().click_secondary(); - h.run_steps(2); - assert!(h.query_by_label("✓ Inches").is_some(), "the current unit is checked"); - h.get_by_label("Percent").click(); - h.run_steps(3); - assert_eq!(shown_size(&h), ["100", "100"]); - // A hand-edited or stale preference falls back to Percent instead of failing. - h.state_mut().session.prefs.edit(|p| { - p.dialogs.insert(SIZE_UNIT_KEY.into(), json!({"sizeUnit": "furlongs"})); - }); - assert_eq!(size_unit(h.state()).unit, photocraft_engine::prefs::Unit::Percent); - h.state_mut().session.prefs.edit(|p| { - p.dialogs.insert(SIZE_UNIT_KEY.into(), json!("not an object")); - }); - assert_eq!(size_unit(h.state()).unit, photocraft_engine::prefs::Unit::Percent); - set_size_unit(h.state_mut(), "points"); - assert_eq!(size_unit(h.state()).unit, photocraft_engine::prefs::Unit::Points, "a bad entry is replaced, not kept"); - } - - #[test] - fn editing_the_contents_of_a_dropped_file_keeps_the_layer() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - - app.session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - app.sync_views(); - - app.session.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); - app.sync_views(); - - let parent_id = app.session.active().unwrap().doc.id; - let placed_layer = app.session.active().unwrap().active_layer.unwrap(); - - begin_placed(&mut app, &egui::Context::default()).unwrap(); - - app.session.execute("layer.smartObjects.editContents", json!({})).unwrap(); - - assert_ne!(app.session.active().unwrap().doc.id, parent_id, "Edit Contents should activate the child document"); - - end_if_left(&mut app); - - let parent = app.session.documents().iter().find(|st| st.doc.id == parent_id); - - assert!(parent.is_some_and(|st| st.doc.layer(placed_layer).is_some()), "the placed Smart Object must remain in the parent document"); - assert!(app.ui.transform.is_none(), "the transform session should end"); - assert!(app.transform_preview.is_none(), "the transform preview should end"); - } - - /// Polls the app's background jobs until they have all landed. - fn land_jobs(app: &mut PhotocraftApp) { - let ctx = egui::Context::default(); - for _ in 0..2000 { - crate::jobs_ui::tick(app, &ctx); - if !app.session.has_jobs() { - return; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - panic!("the background jobs never landed"); - } - - /// A smart object placed the way a dropped file is (the last step made it), in Free Transform - /// and moved 8 px right, with commits running in the background as in the desktop app: - /// (app, the placed layer, its frame before the move, history steps before the place). - fn moved_place() -> (PhotocraftApp, LayerId, photocraft_geom::Rect, usize) { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - app.session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let steps = app.session.active().unwrap().history.past_len(); - app.session.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); - app.sync_views(); - let st = app.session.active().unwrap(); - let placed = st.active_layer.unwrap(); - let frame = photocraft_engine::transform_cmds::transform_frame(&st.doc, st.doc.layer(placed).unwrap()); - begin_placed(&mut app, &egui::Context::default()).unwrap(); - let t = app.ui.transform.as_mut().unwrap(); - t.quad = t.quad.map(|[x, y]| [x + 8.0, y]); - app.background_jobs = true; - (app, placed, frame, steps) - } - - fn frame_of(app: &PhotocraftApp, layer: LayerId) -> Option { - let st = app.session.active()?; - Some(photocraft_engine::transform_cmds::transform_frame(&st.doc, st.doc.layer(layer)?)) - } - - /// #5665: picking another tool or selecting another layer while a dropped file is in Free - /// Transform applies the transform when the commit runs in the background too. Ending the - /// box used to cancel that commit, which took the dropped file back (or left a transformed - /// layer where it was). - #[test] - fn another_tool_or_layer_applies_a_transform_committed_in_the_background() { - for by_layer in [false, true] { - let (mut app, placed, frame, steps) = moved_place(); - if by_layer { - let below = app.session.active().unwrap().doc.layers.iter().map(|l| l.id).find(|id| *id != placed).unwrap(); - app.run("layer.select", json!({"layer": below.0})).unwrap(); - } else { - app.ui.tool = if app.ui.tool == Tool::Brush { Tool::Move } else { Tool::Brush }; - } - end_if_left(&mut app); - assert!(committing(&app).is_some(), "the commit runs in the background"); - land_jobs(&mut app); - assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "the box ended"); - assert_eq!(frame_of(&app, placed), Some(frame.translate(8, 0)), "the dropped file stays, moved (by layer: {by_layer})"); - let st = app.session.active().unwrap(); - assert_eq!(st.history.past_len(), steps + 1, "the place and its move are one step"); - assert_eq!(st.history.undo_label(), Some(photocraft_engine::file_cmds::PLACE_EMBEDDED)); - } - } - - /// #5667: New Layer while a dropped file is in Free Transform applies the transform first. When - /// the commit runs in the background the command is refused until it has landed, then runs: the - /// place (which takes the move into its step) and the new layer each stay their own step, in - /// that order. - #[test] - fn new_layer_applies_the_open_transform() { - let (mut app, placed, frame, steps) = moved_place(); - let layers = app.session.active().unwrap().doc.layers.len(); - let err = app.run("layer.new.layer", json!({})).unwrap_err(); - assert!(err.contains("Free Transform is still being applied"), "refused while the commit runs: {err}"); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "no layer yet"); - land_jobs(&mut app); - assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "the box ended"); - assert_eq!(frame_of(&app, placed), Some(frame.translate(8, 0)), "applied as it showed, not the original"); - app.run("layer.new.layer", json!({})).unwrap(); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.layers.len(), layers + 1); - assert_eq!(st.history.past_len(), steps + 2, "the place with its move, then New Layer"); - assert_eq!(st.history.undo_label(), Some("New Layer")); - app.session.undo(); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "one undo takes back the new layer"); - assert_eq!(frame_of(&app, placed), Some(frame.translate(8, 0)), "the transform stays"); - } - - /// #5665, the report's second case through the UI with background jobs on, as in the desktop - /// app: Free Transform on a layer, move it, then click another layer's row in the Layers panel. - #[test] - fn clicking_another_layer_row_applies_the_transform() { - use egui_kittest::kittest::{NodeT, Queryable}; - let app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let layer = app.session.active().unwrap().active_layer.unwrap(); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_max_steps(64).with_step_dt(1.0 / 60.0).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); - h.run_steps(4); - let before = frame_of(h.state(), layer).unwrap(); - let ctx = h.ctx.clone(); - crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); - let t = h.state_mut().ui.transform.as_mut().expect("in Free Transform"); - t.quad = t.quad.map(|[x, y]| [x + 8.0, y]); - h.state_mut().background_jobs = true; - h.run_steps(2); - let row = h - .query_all_by_label("Background") - .find(|n| n.accesskit_node().role() == egui::accesskit::Role::Button) - .expect("the Background row") - .rect() - .center(); - h.hover_at(row); - h.run_steps(1); - h.drag_at(row); - h.run_steps(1); - h.drop_at(row); - for _ in 0..400 { - h.run_steps(1); - if h.state().ui.transform.is_none() && !h.state().session.has_jobs() { - break; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - assert_ne!(h.state().session.active().unwrap().active_layer, Some(layer), "the click selected the Background"); - assert!(h.state().ui.transform.is_none(), "the box ended"); - assert_eq!(frame_of(h.state(), layer), Some(before.translate(8, 0)), "the move was applied"); - } - - /// Large documents need scales past 10000% and positions past 30000 px (#1267). - #[test] - fn transform_fields_reach_large_documents() { - let t = type_into_bar_field(2, "15000"); - let (sx, sy, _, _) = readout(&t); - assert!((sx - 15000.0).abs() < 0.5 && (sy - 15000.0).abs() < 0.5, "{sx} {sy}"); - assert!((t.quad[1][0] - t.quad[0][0] - 15_000.0).abs() < 1.0, "{:?}", t.quad); - let t = type_into_bar_field(0, "250000"); - assert!((t.pivot[0] - 250_000.0).abs() < 1.0, "{:?}", t.pivot); - } - - /// A typed scale stops where the box reaches the largest document side, not past what can be - /// allocated: the 100 × 50 px test box tops out at 300000 % wide. - #[test] - fn typed_scales_stay_within_the_largest_document() { - assert_eq!(scale_limit_pct(20.0), SCALE_LIMIT_PCT); - assert_eq!(scale_limit_pct(3000.0), 10_000.0); - assert_eq!(scale_limit_pct(1e9), 100.0); - assert_eq!(scale_limit_pct(0.0), SCALE_LIMIT_PCT); - assert_eq!(scale_limit_pct(f64::NAN), SCALE_LIMIT_PCT); - let t = type_into_bar_field(2, "99999999"); - let (sx, sy, _, _) = readout(&t); - let side = t.rect[2] - t.rect[0]; - assert!(sx <= f64::from(scale_limit_pct(side)) + 0.5 && sy <= f64::from(scale_limit_pct(t.rect[3] - t.rect[1])) + 0.5, "{sx} {sy}"); - } - - fn drag(s: &mut TransformSession, from: [f64; 2], to: [f64; 2], mods: egui::Modifiers) { - let g = Gesture { hit: hit(s, from, 8.0), start: from, quad0: s.quad, pivot0: s.pivot }; - apply_drag(s, g, to, mods); - } - - /// A handle drag in Edit › Transform `mode`, as the canvas applies it (on a pixel layer). - fn drag_in(mode: TransformMode, from: [f64; 2], to: [f64; 2], mods: egui::Modifiers) -> [[f64; 2]; 4] { - drag_on(mode, false, from, to, mods) - } - - fn drag_on(mode: TransformMode, type_layer: bool, from: [f64; 2], to: [f64; 2], mods: egui::Modifiers) -> [[f64; 2]; 4] { - let mut s = session(); - let g = Gesture { hit: hit(&s, from, 8.0), start: from, quad0: s.quad, pivot0: s.pivot }; - apply_mode_drag(&mut s, g, to, mode, type_layer, mods); - s.quad - } - - /// Skew on editable type, checked in Photoshop: a corner can't move alone (type stays a - /// parallelogram), so it slides its whole edge: the top or bottom edge for a mostly - /// horizontal drag, the left or right one for a mostly vertical drag. ⌥ moves the opposite - /// edge the other way. Side handles are as on any layer. - #[test] - fn skew_mode_on_type_slides_the_corners_edge() { - let (skew, none) = (TransformMode::Skew, egui::Modifiers::NONE); - assert_eq!(drag_on(skew, true, [100.0, 0.0], [110.0, 3.0], none), [[10.0, 0.0], [110.0, 0.0], [100.0, 50.0], [0.0, 50.0]]); - assert_eq!(drag_on(skew, true, [100.0, 0.0], [102.0, -9.0], none), [[0.0, 0.0], [100.0, -9.0], [100.0, 41.0], [0.0, 50.0]]); - assert_eq!(drag_on(skew, true, [100.0, 0.0], [110.0, 3.0], egui::Modifiers::ALT), [[10.0, 0.0], [110.0, 0.0], [90.0, 50.0], [-10.0, 50.0]]); - assert_eq!(drag_on(skew, true, [50.0, 0.0], [62.0, 7.0], none), [[12.0, 0.0], [112.0, 0.0], [100.0, 50.0], [0.0, 50.0]]); - } - - /// Edit › Transform › Skew, checked in Photoshop (#3437): a corner moves alone, horizontally or - /// vertically (whichever way the drag mostly goes); the top and bottom handles slide only - /// horizontally, the left and right ones only vertically; ⌥ moves the opposite corner or edge - /// the other way. Nothing scales. - #[test] - fn skew_mode_moves_a_corner_or_an_edge_along_one_axis() { - let skew = TransformMode::Skew; - let none = egui::Modifiers::NONE; - // Corner (top right), mostly horizontal, then mostly vertical: only that corner moves. - assert_eq!(drag_in(skew, [100.0, 0.0], [110.0, 3.0], none), [[0.0, 0.0], [110.0, 0.0], [100.0, 50.0], [0.0, 50.0]]); - assert_eq!(drag_in(skew, [100.0, 0.0], [102.0, -9.0], none), [[0.0, 0.0], [100.0, -9.0], [100.0, 50.0], [0.0, 50.0]]); - // Top edge: horizontal only, both its corners. - assert_eq!(drag_in(skew, [50.0, 0.0], [62.0, 7.0], none), [[12.0, 0.0], [112.0, 0.0], [100.0, 50.0], [0.0, 50.0]]); - // Left edge: vertical only. - assert_eq!(drag_in(skew, [0.0, 25.0], [6.0, 33.0], none), [[0.0, 8.0], [100.0, 0.0], [100.0, 50.0], [0.0, 58.0]]); - // ⌥: the opposite corner, and the opposite edge, go the other way. - let alt = egui::Modifiers::ALT; - assert_eq!(drag_in(skew, [100.0, 0.0], [110.0, 3.0], alt), [[0.0, 0.0], [110.0, 0.0], [100.0, 50.0], [-10.0, 50.0]]); - assert_eq!(drag_in(skew, [50.0, 0.0], [62.0, 7.0], alt), [[12.0, 0.0], [112.0, 0.0], [88.0, 50.0], [-12.0, 50.0]]); - // ⇧ changes nothing in Skew mode. - let shift = egui::Modifiers::SHIFT; - assert_eq!(drag_in(skew, [100.0, 0.0], [110.0, 3.0], shift), drag_in(skew, [100.0, 0.0], [110.0, 3.0], none)); - assert_eq!(drag_in(skew, [50.0, 0.0], [62.0, 7.0], shift), drag_in(skew, [50.0, 0.0], [62.0, 7.0], none)); - // A drag outside the box doesn't rotate it in Skew mode. - assert_eq!(drag_in(skew, [130.0, 25.0], [120.0, 60.0], none), corners([0.0, 0.0, 100.0, 50.0])); - // Free Transform is unchanged: a corner scales. - assert_ne!(drag_in(TransformMode::Free, [100.0, 0.0], [110.0, 3.0], none)[2], [100.0, 50.0]); - } - - fn close(a: [[f64; 2]; 4], b: [[f64; 2]; 4]) -> bool { - a.iter().flatten().zip(b.iter().flatten()).all(|(x, y)| (x - y).abs() < 1e-6) - } - - /// On a box smaller than the handles' grab areas the nearest handle wins, so the reference - /// point at the centre doesn't take presses on the corners and edges. - #[test] - fn the_nearest_handle_wins_on_a_small_box() { - let mut s = session(); - s.quad = corners([0.0, 0.0, 16.0, 16.0]); - s.pivot = [8.0, 8.0]; - assert_eq!(hit(&s, [0.0, 0.0], 12.0), Hit::Corner(0)); - assert_eq!(hit(&s, [16.0, 17.0], 12.0), Hit::Corner(2)); - assert_eq!(hit(&s, [8.0, -1.0], 12.0), Hit::Edge(0)); - assert_eq!(hit(&s, [8.0, 8.0], 12.0), Hit::Pivot); - assert_eq!(hit(&s, [40.0, 40.0], 12.0), Hit::Outside); - } - - #[test] - fn interior_patch_points_are_hidden_and_grid_anchors_stay() { - assert!(on_section_edge(0, 0) && on_section_edge(1, 0) && on_section_edge(0, 2)); - assert!(!on_section_edge(1, 1) && !on_section_edge(2, 2)); - let b = [0.0, 0.0, 30.0, 30.0]; - let w = Warp::custom(BezierMesh::identity(b, 1, 1), b); - assert!(warp_hit(&w, [10.0, 10.0], 4.0).is_none(), "the point inside the patch is not shown"); - assert_eq!(warp_hit(&w, [0.0, 0.0], 4.0), Some(0)); - let grid = Warp::custom(BezierMesh::identity(b, 3, 3), b); - assert_eq!(warp_hit(&grid, [10.0, 10.0], 4.0), Some(33), "a grid-corner anchor stays draggable"); - assert!(warp_hit(&grid, [30.0 / 9.0, 30.0 / 9.0], 2.0).is_none()); - } - - #[test] - fn grid_menu_reads_default_and_even_presets() { - let b = [0.0, 0.0, 100.0, 80.0]; - let plain = BezierMesh::identity(b, 1, 1); - assert_eq!(warp_grid_id(&plain), "default"); - assert_eq!(warp_grid_id(&BezierMesh::identity(b, 3, 3)), "3"); - assert_eq!(warp_grid_id(&BezierMesh::identity(b, 4, 4)), "4"); - assert_eq!(warp_grid_id(&BezierMesh::identity(b, 5, 5)), "5"); - assert_eq!(warp_grid_id(&BezierMesh::identity(b, 2, 2)), "custom"); - let mut split = plain.clone(); - assert!(split.split_u(0.5)); - assert_eq!(warp_grid_id(&split), "custom"); - assert!(single_patch(&plain)); - assert!(!single_patch(&BezierMesh::identity(b, 3, 3))); - } - - #[test] - fn split_tool_places_the_line_where_the_pointer_releases() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, a| { - doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 32, 32), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - begin_warp(&mut app, &egui::Context::default()).unwrap(); - app.transform_preview.as_mut().unwrap().split_tool = Some(SplitTool::Vertical); - let knots = |app: &PhotocraftApp| app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.as_ref().unwrap().us.clone(); - assert_eq!(knots(&app).len(), 2); - let mods = egui::Modifiers::NONE; - warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, mods); - warp_pointer(&mut app, ToolEvent::Move { x: 14.0, y: 20.0, pressure: 1.0 }, 2.0, mods); - assert_eq!(knots(&app).len(), 2, "the line is only a guide until release"); - warp_pointer(&mut app, ToolEvent::Up { x: 14.0, y: 20.0 }, 2.0, mods); - let us = knots(&app); - let has = |ks: &[f64], u: f64| ks.iter().any(|k| (k - u).abs() < 0.02); - // The default grid's thirds stay; the release cuts the section that contains it. - assert!(has(&us, 0.25) && has(&us, 1.0 / 3.0) && has(&us, 2.0 / 3.0), "{us:?}"); - let vs = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.as_ref().unwrap().vs.clone(); - assert!(has(&vs, 1.0 / 3.0) && has(&vs, 2.0 / 3.0), "horizontal sections stay: {vs:?}"); - assert!(app.transform_preview.as_ref().unwrap().split_tool.is_some(), "the tool stays armed"); - // Option-click in the open places both lines, without a button armed. - app.transform_preview.as_mut().unwrap().split_tool = None; - let alt = egui::Modifiers::ALT; - warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, alt); - warp_pointer(&mut app, ToolEvent::Up { x: 20.0, y: 20.0 }, 2.0, alt); - let m = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.as_ref().unwrap(); - assert!(m.us.len() == us.len() + 1 && has(&m.vs, 0.5), "crosswise cuts the open section: us {:?} vs {:?}", m.us, m.vs); - } - - #[test] - fn split_of_a_grid_cuts_one_section_and_keeps_the_rest() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, a| { - doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 32, 32), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - begin_warp(&mut app, &egui::Context::default()).unwrap(); - let rect = app.ui.transform.as_ref().unwrap().rect; - let before = BezierMesh::identity(rect, 3, 3); - app.ui.transform.as_mut().unwrap().warp = Some(Warp::custom(before.clone(), rect)); - // Middle of the centre column (s = 0.5), inside the top row of cells. - let x = rect[0] + 0.5 * (rect[2] - rect[0]); - let y = rect[1] + (1.0 / 6.0) * (rect[3] - rect[1]); - app.transform_preview.as_mut().unwrap().split_tool = Some(SplitTool::Vertical); - let mods = egui::Modifiers::NONE; - warp_pointer(&mut app, ToolEvent::Down { x, y, pressure: 1.0 }, 2.0, mods); - warp_pointer(&mut app, ToolEvent::Up { x, y }, 2.0, mods); - let m = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.as_ref().unwrap(); - assert_eq!(m.vs.len(), before.vs.len(), "horizontal sections are not rebuilt: {:?}", m.vs); - for (a, b) in m.vs.iter().zip(&before.vs) { - assert!((a - b).abs() < 1e-6, "{:?} vs {:?}", m.vs, before.vs); - } - assert_eq!(m.us.len(), before.us.len() + 1, "one cut: {:?}", m.us); - for u in [0.0, 1.0 / 3.0, 0.5, 2.0 / 3.0, 1.0] { - assert!(m.us.iter().any(|k| (k - u).abs() < 1e-3), "missing {u} in {:?}", m.us); - } - let (nx0, nx1) = (before.nx(), m.nx()); - for j in 0..before.ny() { - for i in 0..3 { - let a = before.points[j * nx0 + i]; - let b = m.points[j * nx1 + i]; - assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "left section moved"); - } - } - } - - #[test] - fn corner_drag_scales_proportionally_about_opposite_corner() { - let mut s = session(); - drag(&mut s, [100.0, 50.0], [200.0, 60.0], egui::Modifiers::NONE); - assert!(close(s.quad, corners([0.0, 0.0, 200.0, 100.0])), "{:?}", s.quad); - let mut s = session(); - drag(&mut s, [100.0, 50.0], [200.0, 60.0], egui::Modifiers::SHIFT); - assert!(close(s.quad, corners([0.0, 0.0, 200.0, 60.0])), "shift = free: {:?}", s.quad); - } - - /// Photoshop CC 2019 and later: an edge scales proportionally too, about the middle of the - /// opposite edge, and ⇧ stretches its one axis instead. - #[test] - fn edge_drag_scales_proportionally_about_the_opposite_edge() { - // Right edge: 100 × 50 → 150 × 75; the left edge's middle (0, 25) stays, and so does the - // reference point's place in the box (its centre). - let mut s = session(); - drag(&mut s, [100.0, 25.0], [150.0, 25.0], egui::Modifiers::NONE); - assert!(close(s.quad, corners([0.0, -12.5, 150.0, 62.5])), "{:?}", s.quad); - assert!(near(s.pivot, [75.0, 25.0]), "{:?}", s.pivot); - // Top edge to twice the height: twice the width, about x = 50. - let mut s = session(); - drag(&mut s, [50.0, 0.0], [50.0, -50.0], egui::Modifiers::NONE); - assert!(close(s.quad, corners([-50.0, -50.0, 150.0, 50.0])), "{:?}", s.quad); - // Past the opposite edge: the dragged axis flips, the other only shrinks. - let mut s = session(); - drag(&mut s, [100.0, 25.0], [-50.0, 25.0], egui::Modifiers::NONE); - assert!(close(s.quad, corners([0.0, 12.5, -50.0, 37.5])), "{:?}", s.quad); - // ⇧: one axis. - let mut s = session(); - drag(&mut s, [50.0, 50.0], [50.0, 80.0], egui::Modifiers::SHIFT); - assert!(close(s.quad, corners([0.0, 0.0, 100.0, 80.0])), "{:?}", s.quad); - } - - #[test] - fn alt_scales_edges_about_reference_point() { - let mut s = session(); - drag(&mut s, [100.0, 25.0], [150.0, 25.0], egui::Modifiers::ALT); - assert!(close(s.quad, corners([-50.0, -25.0, 150.0, 75.0])), "{:?}", s.quad); - // ⌥⇧: one axis, about the reference point. - let mut s = session(); - drag(&mut s, [100.0, 25.0], [150.0, 25.0], egui::Modifiers { alt: true, shift: true, ..Default::default() }); - assert!(close(s.quad, corners([-50.0, 0.0, 150.0, 50.0])), "{:?}", s.quad); - } - - /// A reference point moved off the centre (⌥-click) is the centre of ⌥-scaling too, not just - /// of rotation: it stays put and the box scales away from it. - #[test] - fn alt_scales_about_a_moved_reference_point() { - let alt = egui::Modifiers::ALT; - // Reference point on the top-left corner: the bottom-right corner to (200, 100) doubles - // the box, top-left fixed (not centred on the reference point). - let mut s = session(); - s.pivot = [0.0, 0.0]; - drag(&mut s, [100.0, 50.0], [200.0, 100.0], alt); - assert!(close(s.quad, corners([0.0, 0.0, 200.0, 100.0])), "{:?}", s.quad); - assert!(near(s.pivot, [0.0, 0.0]), "{:?}", s.pivot); - // Reference point at (25, 25): the right edge to x = 175 is 2× about x = 25, and - // proportionally 2× about y = 25 too. - let mut s = session(); - s.pivot = [25.0, 25.0]; - drag(&mut s, [100.0, 25.0], [175.0, 25.0], alt); - assert!(close(s.quad, corners([-25.0, -25.0, 175.0, 75.0])), "{:?}", s.quad); - // ⌥⇧: that edge's axis only. - let mut s = session(); - s.pivot = [25.0, 25.0]; - drag(&mut s, [100.0, 25.0], [175.0, 25.0], egui::Modifiers { alt: true, shift: true, ..Default::default() }); - assert!(close(s.quad, corners([-25.0, 0.0, 175.0, 50.0])), "{:?}", s.quad); - // Reference point in line with the dragged corner horizontally: that axis has nothing to - // scale against and stays, the other doubles about it. - let mut s = session(); - s.pivot = [100.0, 50.0]; - drag(&mut s, [100.0, 0.0], [150.0, -50.0], egui::Modifiers { alt: true, shift: true, ..Default::default() }); - assert!(close(s.quad, corners([0.0, -50.0, 100.0, 50.0])), "{:?}", s.quad); - } - - fn near(a: [f64; 2], b: [f64; 2]) -> bool { - (a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6 - } - - /// The reference point is attached to the box (#1329): scaling, skewing, distorting and - /// perspective carry it along to the same place within the box; ⌥-scaling about it and - /// rotating about it leave it put. - #[test] - fn the_reference_point_moves_with_the_box() { - // Corner scale down: the centre stays the centre. - let mut s = session(); - drag(&mut s, [100.0, 50.0], [50.0, 25.0], egui::Modifiers::NONE); - assert!(close(s.quad, corners([0.0, 0.0, 50.0, 25.0])), "{:?}", s.quad); - assert!(near(s.pivot, [25.0, 12.5]), "{:?}", s.pivot); - // A reference point set to a corner stays at that corner; an edge drag carries it too. - let mut s = session(); - s.pivot = [100.0, 0.0]; - drag(&mut s, [50.0, 50.0], [50.0, 80.0], egui::Modifiers::SHIFT); - assert!(near(s.pivot, [100.0, 0.0]), "{:?}", s.pivot); - drag(&mut s, [100.0, 40.0], [150.0, 40.0], egui::Modifiers::SHIFT); - assert!(near(s.pivot, s.quad[1]), "{:?} {:?}", s.pivot, s.quad); - drag(&mut s, [150.0, 40.0], [180.0, 40.0], egui::Modifiers::NONE); - assert!(near(s.pivot, s.quad[1]), "proportional edge drag: {:?} {:?}", s.pivot, s.quad); - // Skew: the centre follows the box's centre. - let mut s = session(); - drag(&mut s, [50.0, 0.0], [70.0, 0.0], egui::Modifiers::COMMAND); - assert!(near(s.pivot, [60.0, 25.0]), "{:?}", s.pivot); - // Distort: a corner reference point stays on its corner. - let mut s = session(); - s.pivot = [0.0, 50.0]; - drag(&mut s, [0.0, 50.0], [-20.0, 70.0], egui::Modifiers::COMMAND); - assert!(near(s.pivot, [-20.0, 70.0]), "{:?}", s.pivot); - // Perspective: the centre stays inside the box, on the box's own centre lines. - let mut s = session(); - drag(&mut s, [100.0, 0.0], [120.0, 0.0], egui::Modifiers { command: true, alt: true, shift: true, ..Default::default() }); - let h = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], s.quad).unwrap(); - let (x, y) = h.apply(0.5, 0.5); - assert!(near(s.pivot, [x, y]), "{:?} vs {:?}", s.pivot, [x, y]); - // ⌥ scales about the reference point: it stays where it is. - let mut s = session(); - drag(&mut s, [100.0, 50.0], [150.0, 75.0], egui::Modifiers::ALT); - assert!(near(s.pivot, [50.0, 25.0]), "{:?}", s.pivot); - // Rotation turns about it. - let mut s = session(); - drag(&mut s, [150.0, 25.0], [50.0, 125.0], egui::Modifiers::NONE); - assert!(near(s.pivot, [50.0, 25.0]), "{:?}", s.pivot); - // From a box collapsed to a point there is no place within it to keep: it stays put. - assert_eq!(carry_pivot([[0.0, 0.0]; 4], corners([0.0, 0.0, 10.0, 10.0]), [5.0, 5.0]), [5.0, 5.0]); - } - - #[test] - fn move_rotate_and_distort() { - let mut s = session(); - drag(&mut s, [40.0, 20.0], [50.0, 30.0], egui::Modifiers::NONE); - assert!(close(s.quad, corners([10.0, 10.0, 110.0, 60.0]))); - assert_eq!(s.pivot, [60.0, 35.0]); - // Rotate 90° about the centre (drag from right of the box to below it). - let mut s = session(); - drag(&mut s, [150.0, 25.0], [50.0, 125.0], egui::Modifiers::NONE); - let (_, _, angle, _) = readout(&s); - assert!((angle - 90.0).abs() < 1e-6, "{angle}"); - // ⇧ snaps: a 50° drag lands on 45°. - let mut s = session(); - let a = 50f64.to_radians(); - drag(&mut s, [150.0, 25.0], [50.0 + 100.0 * a.cos(), 25.0 + 100.0 * a.sin()], egui::Modifiers::SHIFT); - assert!((readout(&s).2 - 45.0).abs() < 1e-6); - // ⌘ corner = distort. - let mut s = session(); - drag(&mut s, [100.0, 0.0], [120.0, -10.0], egui::Modifiers::COMMAND); - assert_eq!(s.quad[1], [120.0, -10.0]); - assert_eq!(s.quad[0], [0.0, 0.0]); - } - - #[test] - fn begin_and_commit_through_the_engine() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, a| { - doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 24, 24), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - let ctx = egui::Context::default(); - begin(&mut app, &ctx).unwrap(); - assert_eq!(app.ui.transform.as_ref().unwrap().rect, [8.0, 8.0, 24.0, 24.0]); - scale_about_pivot(&mut app, 2.0, 2.0); - commit(&mut app); - let st = app.session.active().unwrap(); - let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); - assert!(b.width().abs_diff(32) <= 2 && b.x0.abs_diff(0) <= 1, "{b:?}"); - assert!(app.ui.transform.is_none() && app.transform_preview.is_none()); - } - - /// A commit the engine refuses (here a collapsed box; a result over the pixel budget, #3773, is - /// refused the same way) shows the reason and keeps the box open, unchanged; picking another - /// tool then ends it. - #[test] - fn a_refused_commit_keeps_the_box_open() { - let ctx = egui::Context::default(); - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let (revision, steps) = (app.session.active().unwrap().revision, app.session.active().unwrap().history.past_len()); - begin(&mut app, &ctx).unwrap(); - if let Some(t) = app.ui.transform.as_mut() { - t.quad = [[16.0, 16.0]; 4]; - } - commit(&mut app); - let t = app.ui.transform.as_ref().expect("the box stays open"); - assert_eq!(t.quad, [[16.0, 16.0]; 4], "as the user left it"); - assert!(app.transform_preview.is_some(), "with its preview"); - assert!(app.ui.status.contains("collapses"), "{}", app.ui.status); - let st = app.session.active().unwrap(); - assert_eq!((st.revision, st.history.past_len()), (revision, steps), "the document was not changed"); - app.ui.tool = if app.ui.tool == Tool::Brush { Tool::Move } else { Tool::Brush }; - end_if_left(&mut app); - assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "another tool ends it"); - } - - /// #6737: Save for Web exports the committed document, so it is off while a box is pending. - #[test] - fn save_for_web_is_off_under_a_pending_transform() { - let ctx = egui::Context::default(); - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - assert!(crate::menus::is_enabled(&app, SAVE_FOR_WEB), "enabled with no box"); - crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); - assert!(!crate::menus::is_enabled(&app, SAVE_FOR_WEB), "off under the box"); - assert!(crate::menus::invoke(&mut app, &ctx, SAVE_FOR_WEB, json!({})).is_err(), "the dialog doesn't open"); - let path = std::env::temp_dir().join(format!("pc-web6737-{}.png", std::process::id())).to_string_lossy().into_owned(); - let r = crate::menus::invoke(&mut app, &ctx, SAVE_FOR_WEB, json!({"path": path, "format": "png24"})); - assert!(r.is_err() && !std::path::Path::new(&path).exists(), "nor does the export run"); - assert!(app.ui.transform.is_some(), "the box stays open"); - cancel(&mut app); - assert!(crate::menus::is_enabled(&app, SAVE_FOR_WEB), "back after the box closes"); - } - - /// #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. - #[test] - fn free_transform_a_copy() { - let ctx = egui::Context::default(); - let bounds = |app: &PhotocraftApp, i: usize| app.session.active().unwrap().doc.layers[i].surface().unwrap().content_bounds(); - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let (layers, steps) = (app.session.active().unwrap().doc.layers.len(), app.session.active().unwrap().history.past_len()); - crate::menus::invoke(&mut app, &ctx, "edit.freeTransformCopy", json!({})).unwrap(); - assert_eq!(app.ui.transform.as_ref().unwrap().made, Some(MadeLayer::Copy)); - assert!(!crate::menus::is_enabled(&app, "edit.freeTransformCopy"), "one transform at a time"); - // Esc: the copy goes too. - cancel(&mut app); - let st = app.session.active().unwrap(); - assert_eq!((st.doc.layers.len(), st.history.past_len()), (layers, steps)); - assert!(!st.history.can_redo(), "nothing to redo"); - // OK: original in place, a moved copy, one step. - crate::menus::invoke(&mut app, &ctx, "edit.freeTransformCopy", json!({})).unwrap(); - if let Some(t) = app.ui.transform.as_mut() { - t.quad = t.quad.map(|[x, y]| [x + 20.0, y]); - } - commit(&mut app); - let st = app.session.active().unwrap(); - assert_eq!((st.doc.layers.len(), st.history.past_len()), (layers + 1, steps + 1)); - assert_eq!(bounds(&app, layers - 1), photocraft_geom::Rect::new(8, 8, 24, 24), "the original stays"); - assert_eq!(bounds(&app, layers), photocraft_geom::Rect::new(28, 8, 44, 24), "the copy moved"); - app.session.undo(); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "one undo removes copy and move"); - // With a selection: Layer via Copy, so only the selected pixels are copied. - app.run("select.rect", json!({"x": 8, "y": 8, "width": 8, "height": 16})).unwrap(); - crate::menus::invoke(&mut app, &ctx, "edit.freeTransformCopy", json!({})).unwrap(); - assert_eq!(app.ui.transform.as_ref().unwrap().rect, [8.0, 8.0, 16.0, 24.0]); - cancel(&mut app); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers); - } - - /// #4112: ⌥⌘T on a cylinder smart object, Warp mode, Enter with nothing touched: the copy - /// keeps the cylinder and stays its own step (no warp step to fold into), so one undo takes - /// back the copy and nothing before it. - #[test] - fn untouched_warp_of_a_cylinder_copy_keeps_its_own_step() { - let ctx = egui::Context::default(); - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - app.run("layer.smartObjects.warp", json!({"style": "cylinder", "values": [8, 24, 24, 8, 0.3, 0.3, 0.5], "rect": [8, 8, 24, 24]})).unwrap(); - let warp = |app: &PhotocraftApp, i: usize| match &app.session.active().unwrap().doc.layers[i].content { - photocraft_doc::LayerContent::Smart(sm) => sm.warp.as_ref().map(|w| w.style), - _ => None, - }; - let (layers, steps) = (app.session.active().unwrap().doc.layers.len(), app.session.active().unwrap().history.past_len()); - assert_eq!(warp(&app, layers - 1), Some(WarpStyle::Cylinder)); - crate::menus::invoke(&mut app, &ctx, "edit.freeTransformCopy", json!({})).unwrap(); - enter_warp(&mut app, &ctx); - assert!(app.ui.transform.as_ref().unwrap().warp.is_some(), "Warp mode shows the cylinder"); - commit(&mut app); - assert!(!app.ui.status_error, "{}", app.ui.status); - let st = app.session.active().unwrap(); - assert_eq!((st.doc.layers.len(), st.history.past_len()), (layers + 1, steps + 1)); - assert_eq!(warp(&app, layers), Some(WarpStyle::Cylinder), "the copy is still a cylinder"); - app.session.undo(); - let st = app.session.active().unwrap(); - assert_eq!((st.doc.layers.len(), st.history.past_len()), (layers, steps), "one undo takes back the copy only"); - assert_eq!(warp(&app, layers - 1), Some(WarpStyle::Cylinder)); - } - - /// #1099: cancel, frame cleanup and a commit before the next frame all belong to the - /// original document, including after tab reordering and with shared layer IDs. - #[test] - fn cancelling_a_copy_after_switching_documents_preserves_the_active_document() { - for reorder in [false, true] { - for finish in [cancel, end_if_left, commit] { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let original = app.session.active().unwrap().doc.clone(); - let steps = app.session.active().unwrap().history.past_len(); - begin_copy(&mut app, &egui::Context::default()).unwrap(); - app.ui.transform.as_mut().unwrap().quad = corners([12.0, 8.0, 28.0, 24.0]); - // Cloning a document deliberately shares layer IDs, but gets a fresh document ID. - let other = app.session.active().unwrap().doc.as_ref().clone(); - app.session.add_document(other, None); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - assert!(app.session.undo()); - let st = app.session.active().unwrap(); - let (doc, history, redo, revision, layer) = - (st.doc.clone(), st.history.entries(), st.history.redo_labels().map(str::to_owned).collect::>(), st.revision, st.active_layer); - if reorder { - app.session.move_document(0, 1); - } - finish(&mut app); - assert!(app.ui.transform.is_none() && app.transform_preview.is_none()); - let st = app.session.active().unwrap(); - assert!(Arc::ptr_eq(&st.doc, &doc), "the selected document's pixels are unchanged"); - assert_eq!((st.history.entries(), st.revision, st.active_layer), (history, revision, layer)); - assert_eq!(st.history.redo_labels().collect::>(), redo); - let origin = app.session.documents().iter().find(|st| st.doc.id == original.id).unwrap(); - assert!(Arc::ptr_eq(&origin.doc, &original), "only the originating copy is undone"); - assert_eq!(origin.history.past_len(), steps); - assert!(!origin.history.can_redo()); - } - } - } - - #[test] - fn cancelling_a_copy_after_its_document_closes_does_not_undo_another_document() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - begin_copy(&mut app, &egui::Context::default()).unwrap(); - app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - let doc = app.session.active().unwrap().doc.clone(); - let steps = app.session.active().unwrap().history.past_len(); - app.session.close(0); - end_if_left(&mut app); - let st = app.session.active().unwrap(); - assert!(Arc::ptr_eq(&st.doc, &doc)); - assert_eq!(st.history.past_len(), steps); - assert!(app.ui.transform.is_none() && app.transform_preview.is_none()); - } - - #[test] - fn cancelling_an_already_undone_copy_preserves_history_and_redo() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - begin_copy(&mut app, &egui::Context::default()).unwrap(); - assert!(app.session.undo()); - let st = app.session.active().unwrap(); - let (doc, history, redo) = (st.doc.clone(), st.history.entries(), st.history.redo_labels().map(str::to_owned).collect::>()); - end_if_left(&mut app); - let st = app.session.active().unwrap(); - assert!(Arc::ptr_eq(&st.doc, &doc)); - assert_eq!(st.history.entries(), history); - assert_eq!(st.history.redo_labels().collect::>(), redo); - assert!(app.ui.transform.is_none() && app.transform_preview.is_none()); - } - - #[test] - fn cancelling_a_copy_does_not_undo_a_later_edit() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - begin_copy(&mut app, &egui::Context::default()).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - let st = app.session.active().unwrap(); - let (doc, history) = (st.doc.clone(), st.history.entries()); - cancel(&mut app); - let st = app.session.active().unwrap(); - assert!(Arc::ptr_eq(&st.doc, &doc)); - assert_eq!(st.history.entries(), history); - } - - /// #1384: the Layers panel's opacity, fill, visibility and blend edits to the moving layer - /// and to the others show while the box is open, and survive the commit. - #[test] - fn edits_during_a_transform_show_in_the_preview() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - app.ui.tool = Tool::Move; - let bg = app.session.active().unwrap().doc.layers[0].id; - let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); - h.run_steps(4); - let ctx = h.ctx.clone(); - crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); - if let Some(t) = h.state_mut().ui.transform.as_mut() { - t.quad = t.quad.map(|[x, y]| [x + 20.0, y]); - } - h.run_steps(2); - let layer = h.state().ui.transform.as_ref().unwrap().layer; - assert_eq!(h.state().transform_preview.as_ref().unwrap().opacity, 1.0); - - h.state_mut().run("layer.setProps", json!({"layer": layer, "opacity": 0.5, "fill": 0.6, "blend": "Multiply"})).unwrap(); - h.state_mut().run("layer.setProps", json!({"layer": bg.0, "visible": false})).unwrap(); - h.run_steps(2); - let app = h.state(); - assert!(app.ui.transform.is_some(), "the edits leave the box open"); - let pv = app.transform_preview.as_ref().unwrap(); - assert!((pv.opacity - 0.3).abs() < 1e-6, "the moving pixels take the new opacity × fill: {}", pv.opacity); - assert!(!pv.doc.layer(bg).unwrap().visible, "the document under the box follows"); - let moving = pv.doc.layer(LayerId(layer)).unwrap(); - assert!(!moving.visible, "the moving layer stays out of the document under the box"); - assert_eq!(moving.blend, photocraft_color::BlendMode::Multiply); - - h.state_mut().run("layer.setProps", json!({"layer": layer, "visible": false})).unwrap(); - h.run_steps(2); - assert_eq!(h.state().transform_preview.as_ref().unwrap().opacity, 0.0, "hiding the layer hides the moving pixels"); - h.state_mut().run("layer.setProps", json!({"layer": layer, "visible": true})).unwrap(); - - commit(h.state_mut()); - let st = h.state().session.active().unwrap(); - let l = st.doc.layer(LayerId(layer)).unwrap(); - assert_eq!((l.opacity, l.fill_opacity, l.blend), (0.5, 0.6, photocraft_color::BlendMode::Multiply)); - assert_eq!(l.surface().unwrap().content_bounds(), photocraft_geom::Rect::new(28, 8, 44, 24)); - } - - /// #1384 with a selection: the pixels it leaves behind stay in the rebuilt preview without - /// the lifted ones, and take the layer's new properties. - #[test] - fn edits_during_a_selection_transform_keep_the_lifted_pixels_out() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - app.ui.tool = Tool::Move; - app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 8, "height": 16})).unwrap(); - let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); - h.run_steps(4); - let ctx = h.ctx.clone(); - crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); - h.run_steps(2); - let layer = LayerId(h.state().ui.transform.as_ref().unwrap().layer); - // Alpha in the preview's copy of the layer: in the lifted half (x 8..16) and the rest (16..24). - let left = |app: &PhotocraftApp| { - let s = app.transform_preview.as_ref().unwrap().doc.layer(layer).unwrap().surface().unwrap().clone(); - (s.sample_channel(10, 12, 3), s.sample_channel(20, 12, 3)) - }; - assert_eq!(left(h.state()), (0.0, 1.0), "the selected half is lifted out"); - - h.state_mut().run("layer.setProps", json!({"layer": layer.0, "opacity": 0.4})).unwrap(); - h.run_steps(2); - let app = h.state(); - assert_eq!(left(app), (0.0, 1.0), "still without the lifted pixels"); - let moving = app.transform_preview.as_ref().unwrap().doc.layer(layer).unwrap(); - assert!(moving.visible && (moving.opacity - 0.4).abs() < 1e-6, "what stays behind is drawn with the new opacity"); - assert!((app.transform_preview.as_ref().unwrap().opacity - 0.4).abs() < 1e-6); - } - - /// #670: picking another tool applies the open transform, as one history step. - #[test] - fn picking_another_tool_applies_the_transform() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - app.ui.tool = Tool::Move; - let steps = app.session.active().unwrap().history.past_len(); - let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); - h.run_steps(4); - let ctx = h.ctx.clone(); - crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); - if let Some(t) = h.state_mut().ui.transform.as_mut() { - t.quad = t.quad.map(|[x, y]| [x + 20.0, y]); - } - h.run_steps(2); - assert!(h.state().ui.transform.is_some(), "open while the tool stays"); - h.key_press(egui::Key::B); - h.run_steps(2); - let app = h.state(); - assert_eq!(app.ui.tool, Tool::Brush); - assert!(app.ui.transform.is_none() && app.transform_preview.is_none()); - let st = app.session.active().unwrap(); - assert_eq!(st.history.past_len(), steps + 1); - assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(), photocraft_geom::Rect::new(28, 8, 44, 24)); - } - - /// #1400: selecting another layer while transforming applies the box to the layer it was on, - /// and the next transform starts on the newly selected layer. - #[test] - fn selecting_another_layer_applies_the_transform_and_the_next_one_follows() { - let ctx = egui::Context::default(); - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let first = app.session.active().unwrap().active_layer.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(40, 40, 56, 60), &[0.0, 0.0, 1.0, 1.0]); - Ok(()) - }) - .unwrap(); - let second = app.session.active().unwrap().active_layer.unwrap(); - app.run("layer.select", json!({"layer": first.0})).unwrap(); - app.ui.tool = Tool::Move; - crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); - if let Some(t) = app.ui.transform.as_mut() { - t.quad = t.quad.map(|[x, y]| [x + 20.0, y]); - } - let steps = app.session.active().unwrap().history.past_len(); - app.run("layer.select", json!({"layer": second.0})).unwrap(); - end_if_left(&mut app); - assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "the box left the old layer"); - let st = app.session.active().unwrap(); - assert_eq!(st.active_layer, Some(second)); - assert_eq!(st.history.past_len(), steps + 1, "applied as one step"); - let bounds = |id: LayerId| st.doc.layer(id).unwrap().surface().unwrap().content_bounds(); - assert_eq!(bounds(first), photocraft_geom::Rect::new(28, 8, 44, 24), "applied to the layer it was on"); - assert_eq!(bounds(second), photocraft_geom::Rect::new(40, 40, 56, 60), "the new layer is untouched"); - crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); - let t = app.ui.transform.as_ref().unwrap(); - assert_eq!((t.layer, t.rect), (second.0, [40.0, 40.0, 56.0, 60.0]), "the next box is on the selected layer"); - } - - /// The screen rectangle the marching ants cover as [`draw_selection`] paints them over the - /// active document's selection; `None` when it leaves them to the canvas. - fn ants_bounds(app: &PhotocraftApp, xf: &ViewXform) -> Option { - let st = app.session.active().unwrap(); - let sel = st.doc.selection.as_ref().unwrap(); - let segs = crate::outline::outline(sel, sel.content_bounds()); - let ctx = egui::Context::default(); - let mut drawn = false; - let mut output = ctx.run_ui(Default::default(), |ui| { - let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("ants-test"))); - drawn = draw_selection(app, &painter, xf, st.doc.id, &segs, 0.0); - }); - output.textures_delta.clear(); - // The ants are a mesh of straight dashes and line shapes for the slanted ones. - let ants = output.shapes.iter().filter(|s| matches!(s.shape, egui::Shape::Mesh(_) | egui::Shape::LineSegment { .. })); - drawn.then(|| ants.map(|s| s.shape.visual_bounding_rect()).fold(egui::Rect::NOTHING, egui::Rect::union)) - } - - /// The screen rectangle around document points. - fn screen_bounds(xf: &ViewXform, points: &[[f64; 2]]) -> egui::Rect { - egui::Rect::from_points(&points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect::>()) - } - - fn rects_match(a: egui::Rect, b: egui::Rect) -> bool { - (a.min - b.min).abs().max_elem() <= 2.0 && (a.max - b.max).abs().max_elem() <= 2.0 - } - - /// #5297: with a selection, Free Transform's box is the selection's own rectangle (wider here - /// than the pixels it holds), and the marching ants stay on the box through a move, a scale, a - /// rotation and a distort, before anything is applied. Applying leaves them there. - #[test] - fn the_box_is_the_selection_and_the_ants_follow_it() { - let ctx = gpu_ctx(); - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let xf = ViewXform { - rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0)), - zoom: 2.0, - center: [32.0, 32.0], - flip: false, - rotation: 0.0, - aspect: 1.0, - }; - app.run("select.rect", json!({"x": 4, "y": 4, "width": 30, "height": 26})).unwrap(); - assert_eq!(ants_bounds(&app, &xf), None, "no box open: the canvas draws them where they are"); - begin(&mut app, &ctx).unwrap(); - let rest = corners([4.0, 4.0, 34.0, 30.0]); - assert_eq!(app.ui.transform.as_ref().unwrap().quad, rest, "the box is the selection, not the 16 px square in it"); - assert!(rects_match(ants_bounds(&app, &xf).unwrap(), screen_bounds(&xf, &rest)), "untouched, the ants are where they were"); - - let on_the_box = |app: &PhotocraftApp, what: &str| { - let quad = app.ui.transform.as_ref().unwrap().quad; - let (ants, boxed) = (ants_bounds(app, &xf).unwrap(), screen_bounds(&xf, &quad)); - assert!(rects_match(ants, boxed), "{what}: ants {ants:?}, box {boxed:?}"); - }; - if let Some(t) = app.ui.transform.as_mut() { - t.quad = t.quad.map(|[x, y]| [x + 20.0, y + 10.0]); - t.pivot = [t.pivot[0] + 20.0, t.pivot[1] + 10.0]; - } - on_the_box(&app, "moved"); - let moved = app.ui.transform.as_ref().unwrap().quad; - scale_about_pivot(&mut app, 0.5, 1.5); - on_the_box(&app, "scaled"); - rotate_about_pivot(&mut app, 0.6); - on_the_box(&app, "rotated"); - if let Some(t) = app.ui.transform.as_mut() { - t.quad[2] = [t.quad[2][0] + 9.0, t.quad[2][1] + 13.0]; - } - on_the_box(&app, "distorted"); - - // Applied as moved only: the outline is where the ants showed it. - if let Some(t) = app.ui.transform.as_mut() { - t.quad = moved; - } - commit(&mut app); - assert!(app.ui.transform.is_none()); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), photocraft_geom::Rect::new(24, 14, 54, 40)); - assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(), photocraft_geom::Rect::new(28, 18, 44, 34)); - } - - /// #5297: in Warp mode the ants bend with the mesh, and past a Distort's horizon they stop - /// rather than run off to infinity. - #[test] - fn the_ants_follow_a_warp_and_stop_at_a_distorts_horizon() { - let ctx = gpu_ctx(); - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 56, 56)); - let xf = ViewXform { - rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0)), - zoom: 2.0, - center: [32.0, 32.0], - flip: false, - rotation: 0.0, - aspect: 1.0, - }; - app.run("select.rect", json!({"x": 12, "y": 12, "width": 40, "height": 40})).unwrap(); - begin(&mut app, &ctx).unwrap(); - let rest = corners([12.0, 12.0, 52.0, 52.0]); - - // Two corners dragged across each other put half the box past the horizon. - if let Some(t) = app.ui.transform.as_mut() { - t.quad = [[12.0, 12.0], [52.0, 12.0], [20.0, 40.0], [44.0, 40.0]]; - } - let ants = ants_bounds(&app, &xf).unwrap(); - assert!(ants == egui::Rect::NOTHING || (ants.is_finite() && ants.width() < 1e5 && ants.height() < 1e5), "{ants:?}"); - - if let Some(t) = app.ui.transform.as_mut() { - t.quad = rest; - } - enter_warp(&mut app, &ctx); - let arc = Warp::preset(WarpStyle::Arc, 50.0, [12.0, 12.0, 52.0, 52.0]); - app.ui.transform.as_mut().unwrap().warp = Some(arc.clone()); - let ants = ants_bounds(&app, &xf).unwrap(); - assert!(!rects_match(ants, screen_bounds(&xf, &rest)), "the outline left its place: {ants:?}"); - let warped: Vec<[f64; 2]> = rest.iter().map(|p| arc.map(p[0], p[1])).map(|(x, y)| [x, y]).collect(); - assert!(ants.expand(2.0).contains_rect(screen_bounds(&xf, &warped)), "the warped corners are on it: {ants:?}"); - } - - /// Transform Selection moves the selection outline, not a layer: selecting a layer keeps it open. - #[test] - fn selecting_another_layer_keeps_a_transform_selection_open() { - let ctx = egui::Context::default(); - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let first = app.session.active().unwrap().active_layer.unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.run("select.all", json!({})).unwrap(); - begin_selection(&mut app, &ctx).unwrap(); - app.run("layer.select", json!({"layer": first.0})).unwrap(); - end_if_left(&mut app); - assert!(app.ui.transform.as_ref().is_some_and(|t| t.selection)); - } - - /// A control-channel stroke that picks another tool applies the box first, then paints. - #[test] - fn a_pointer_request_with_another_tool_applies_the_transform_first() { - let ctx = egui::Context::default(); - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - app.ui.tool = Tool::Move; - crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); - if let Some(t) = app.ui.transform.as_mut() { - t.quad = t.quad.map(|[x, y]| [x + 20.0, y]); - } - let steps = app.session.active().unwrap().history.past_len(); - let ev = |kind: &str, x: f64| json!({"kind": kind, "x": x, "y": 50.0}); - let events = json!([ev("down", 4.0), ev("move", 32.0), ev("move", 60.0), ev("up", 60.0)]); - let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"tool": "brush", "events": events})); - let _ = crate::control::handle(&mut app, &ctx, &req); - assert!(app.ui.transform.is_none()); - let st = app.session.active().unwrap(); - assert_eq!(st.history.past_len(), steps + 2, "the transform, then the stroke"); - let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); - assert!(b.x0 < 8 && b.x1 >= 44 && b.y0 == 8 && b.y1 > 50, "moved square and stroke: {b:?}"); - } - - /// Drags with real pointer events (snapping off so the drops land exactly). - fn press_drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], m: egui::Modifiers) { - crate::canvas::tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, m); - crate::canvas::tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, m); - } - - #[test] - fn distort_mode_moves_one_corner_and_ignores_rotate_and_edges() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - app.ui.extras.snap = false; - let ctx = egui::Context::default(); - crate::menus::invoke(&mut app, &ctx, "edit.transform.distort", json!({})).unwrap(); - let q0 = app.ui.transform.as_ref().unwrap().quad; - assert_eq!(app.ui.transform.as_ref().unwrap().mode, TransformMode::Distort); - // Outside (rotate) and an edge handle do nothing in Distort. - press_drag(&mut app, [44.0, 44.0], [54.0, 10.0], egui::Modifiers::NONE); - press_drag(&mut app, [24.0, 16.0], [34.0, 16.0], egui::Modifiers::NONE); - assert_eq!(app.ui.transform.as_ref().unwrap().quad, q0); - // A corner moves alone, with no keys held. - press_drag(&mut app, q0[1], [q0[1][0] + 7.0, q0[1][1] - 5.0], egui::Modifiers::NONE); - let q = app.ui.transform.as_ref().unwrap().quad; - assert_eq!(q[1], [q0[1][0] + 7.0, q0[1][1] - 5.0]); - assert_eq!([q[0], q[2], q[3]], [q0[0], q0[2], q0[3]]); - // Free Transform from the menu switches the live box back. - crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); - assert_eq!(app.ui.transform.as_ref().unwrap().mode, TransformMode::Free); - } - - /// #3941: Edit › Transform › Rotate must rotate from a corner handle, not scale. - #[test] - fn rotate_mode_turns_the_box_from_a_corner_handle() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - app.ui.extras.snap = false; - let ctx = egui::Context::default(); - crate::menus::invoke(&mut app, &ctx, "edit.transform.rotate", json!({})).unwrap(); - assert_eq!(app.ui.transform.as_ref().unwrap().mode, TransformMode::Rotate); - let q0 = app.ui.transform.as_ref().unwrap().quad; - press_drag(&mut app, q0[1], [q0[1][0], q0[1][1] + 16.0], egui::Modifiers::NONE); - let q = app.ui.transform.as_ref().unwrap().quad; - let w0 = (q0[1][0] - q0[0][0]).hypot(q0[1][1] - q0[0][1]); - let w = (q[1][0] - q[0][0]).hypot(q[1][1] - q[0][1]); - assert!((w - w0).abs() < 1e-6, "side length stays {w0}, got {w}: {q:?}"); - assert!((q[0][1] - q[1][1]).abs() > 1.0, "the box rotated, not scaled: {q:?}"); - crate::menus::invoke(&mut app, &ctx, "edit.transform.scale", json!({})).unwrap(); - assert_eq!(app.ui.transform.as_ref().unwrap().mode, TransformMode::Free); - } - - fn near2(a: Option<[f64; 2]>, b: [f64; 2]) -> bool { - a.is_some_and(|a| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9) - } - - /// #1767: just outside a corner is the rotate zone: the OS pointer hides for the drawn curved - /// arrow, which bends round that corner. - #[test] - fn the_preview_leaves_out_cells_past_the_horizon() { - // #4863: the bottom corners pulled in and one dragged far out: a concave quad whose - // source straddles the horizon. Its cells there are left out; an ordinary quad keeps all. - let past = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], [[0.0, 0.0], [300.0, 0.0], [60.0, 60.0], [0.0, 300.0]]).unwrap(); - let ahead = front_vertices(&past, 24); - assert!(ahead.iter().any(|a| *a) && ahead.iter().any(|a| !*a), "some of the grid is past the horizon"); - // Three corners are on one side (drawn); the top-left one is past the horizon. - assert!(ahead[24 * 25 + 24] && ahead[24] && ahead[24 * 25], "the three corners in front are drawn"); - assert!(!ahead[0], "the corner past the horizon is left out"); - let plain = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], [[0.0, 0.0], [300.0, 0.0], [280.0, 260.0], [0.0, 300.0]]).unwrap(); - assert!(front_vertices(&plain, 24).iter().all(|a| *a)); - } - - #[test] - fn hovering_just_outside_a_corner_asks_for_the_rotate_cursor() { - let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); - crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); - let tol = handle_tolerance(&app); - let h = std::f64::consts::FRAC_1_SQRT_2; - let (tl, br) = ([32.0 - tol * 1.5, 32.0 - tol * 1.5], [160.0 + tol * 1.5, 160.0 + tol * 1.5]); - let xf = ViewXform::active(&app).unwrap(); - assert_eq!(cursor(&app, &xf, tl, false), Some(CursorIcon::None), "the arrow is drawn instead"); - assert!(near2(rotate_cursor_dir(&app, tl), [h, h]), "{:?}", rotate_cursor_dir(&app, tl)); - assert!(near2(rotate_cursor_dir(&app, br), [-h, -h]), "bends round the bottom-right corner"); - assert_eq!(cursor(&app, &xf, [60.0, 60.0], false), Some(CursorIcon::Move)); - assert_eq!(rotate_cursor_dir(&app, [60.0, 60.0]), None, "inside moves"); - assert_eq!(rotate_cursor_dir(&app, [32.0, 32.0]), None, "the corner handle scales"); - assert_eq!(rotate_cursor_dir(&app, [f64::NAN, 32.0]), None); - } - - // Regression test for #4139: the rotate zone hides the OS pointer (`CursorIcon::None`), so the - // canvas has to draw the curved turn arrow itself where the box has no preview to draw it - // (the preview's overlay draws it otherwise); the pointer vanished over the zone. - #[test] - fn the_rotate_zone_draws_the_turn_arrow_where_the_pointer_is_hidden() { - let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); - app.ui.tool = Tool::Move; - let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - app - }); - h.run_steps(4); - let ctx = h.ctx.clone(); - crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); - h.run_steps(3); - let tol = handle_tolerance(h.state()); - let xf = ViewXform::active(h.state()).unwrap(); - let accent = crate::theme::Tokens::get(&h.ctx).accent_text; - // The arrow's bright stroke: a 17-point arc in the accent colour around the pointer. - let arrows = |h: &egui_kittest::Harness<'_, PhotocraftApp>, at: egui::Pos2| { - h.output() - .shapes - .iter() - .filter(|c| match &c.shape { - egui::Shape::Path(p) => { - p.points.len() == 17 - && p.stroke.width == 1.5 - && p.stroke.color == egui::epaint::ColorMode::Solid(accent) - && p.points.iter().all(|q| q.distance(at) < 40.0) - } - _ => false, - }) - .count() - }; - let outside = xf.to_screen((32.0 - tol * 1.5) as f32, (32.0 - tol * 1.5) as f32); - - // A box with no preview (its overlay is what draws the arrow otherwise). - h.state_mut().transform_preview = None; - h.hover_at(outside); - h.run_steps(3); - assert!(h.state().ui.transform.is_some() && h.state().transform_preview.is_none()); - assert_eq!(h.output().platform_output.cursor_icon, CursorIcon::None, "the OS pointer is hidden in the rotate zone"); - assert_eq!(arrows(&h, outside), 1, "and the curved arrow is drawn in its place"); - - let inside = xf.to_screen(96.0, 96.0); - h.hover_at(inside); - h.run_steps(3); - assert_eq!(arrows(&h, inside), 0, "no arrow over the box"); - } - - /// The resize arrows follow the box's turn and the view's rotation and flip: each handle - /// shows the arrow it resizes along on screen, not the one it had on the upright box. - #[test] - fn resize_cursors_turn_with_the_box_and_the_view() { - use CursorIcon::{ResizeHorizontal as H, ResizeNeSw as NeSw, ResizeNwSe as NwSe, ResizeVertical as V}; - // Box turned (degrees), view rotation, flip → corner 0, corner 1, edge 0, edge 1 (corner - // and edge i + 2 sit opposite, on the same axis). - let cases = [ - (0.0, 0.0, false, [NwSe, NeSw, V, H]), - (90.0, 0.0, false, [NeSw, NwSe, H, V]), - (45.0, 0.0, false, [V, H, NeSw, NwSe]), - (0.0, 0.0, true, [NeSw, NwSe, V, H]), - (0.0, 90.0, false, [NeSw, NwSe, H, V]), - ]; - for (deg, view, flip, want) in cases { - let mut app = app_with_square(256, photocraft_geom::Rect::new(64, 96, 192, 160)); - crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); - let view_index = app.session.active_index().unwrap(); - app.ui.views[view_index].rotation = view; - app.ui.view.flip_horizontal = flip; - let t = app.ui.transform.as_mut().unwrap(); - let (s, c) = f64::to_radians(deg).sin_cos(); - let o = [128.0, 128.0]; - t.quad = t.quad.map(|[x, y]| [o[0] + (x - o[0]) * c - (y - o[1]) * s, o[1] + (x - o[0]) * s + (y - o[1]) * c]); - let t = app.ui.transform.clone().unwrap(); - let xf = ViewXform::active(&app).unwrap(); - let mid = |i: usize| [(t.quad[i][0] + t.quad[(i + 1) % 4][0]) / 2.0, (t.quad[i][1] + t.quad[(i + 1) % 4][1]) / 2.0]; - let got: Vec<_> = (0..4).map(|i| cursor(&app, &xf, t.quad[i], false)).chain((0..4).map(|i| cursor(&app, &xf, mid(i), false))).collect(); - let want = [want[0], want[1], want[0], want[1], want[2], want[3], want[2], want[3]].map(Some); - assert_eq!(got, want, "box {deg}°, view {view}°, flip {flip}"); - } - } - - /// The corners of a wide or tall box show the diagonal arrows, as in Photoshop, not the - /// horizontal or vertical one its long diagonal is nearest to. - #[test] - fn corner_cursors_stay_diagonal_on_a_long_box() { - use CursorIcon::{ResizeNeSw as NeSw, ResizeNwSe as NwSe}; - for rect in [photocraft_geom::Rect::new(8, 112, 248, 144), photocraft_geom::Rect::new(112, 8, 144, 248)] { - let mut app = app_with_square(256, rect); - crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); - let t = app.ui.transform.clone().unwrap(); - let xf = ViewXform::active(&app).unwrap(); - let got: Vec<_> = (0..4).map(|i| cursor(&app, &xf, t.quad[i], false)).collect(); - assert_eq!(got, [NwSe, NeSw, NwSe, NeSw].map(Some), "{rect:?}"); - } - } - - /// A warp split's arrow crosses the split line as it looks on screen: it turns with a turned - /// grid (Warp entered on a rotated box) and with a rotated view. - #[test] - fn warp_split_cursors_turn_with_the_grid_and_the_view() { - use CursorIcon::{ResizeHorizontal as H, ResizeNeSw as NeSw, ResizeNwSe as NwSe, ResizeVertical as V}; - let rect = [0.0, 0.0, 200.0, 100.0]; - let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); - let level = ViewXform { rect: screen, zoom: 1.0, center: [100.0, 50.0], flip: false, rotation: 0.0, aspect: 1.0 }; - // Grid turned (degrees, about its centre), view rotation → Split Vertically, Split Horizontally. - for (grid, view, want) in [(0.0, 0.0, [H, V]), (0.0, 90.0, [V, H]), (90.0, 0.0, [V, H]), (45.0, 0.0, [NwSe, NeSw])] { - let (s, c) = f64::to_radians(grid).sin_cos(); - let m = BezierMesh::identity(rect, 1, 1).map_points(|[x, y]| [100.0 + (x - 100.0) * c - (y - 50.0) * s, 50.0 + (x - 100.0) * s + (y - 50.0) * c]); - let xf = ViewXform { rotation: view, ..level }; - let got = [SplitTool::Vertical, SplitTool::Horizontal].map(|tool| split_cursor(&m, tool, m.param_at([100.0, 50.0]), &xf)); - assert_eq!(got, want, "grid turned {grid}°, view {view}°"); - } - let m = BezierMesh::identity(rect, 1, 1); - assert_eq!(split_cursor(&m, SplitTool::Cross, (0.5, 0.5), &level), CursorIcon::Crosshair); - } - - /// #1767: the readout beside the pointer during a drag (Photoshop's transformation values): - /// the angle while rotating, W/H while scaling, ΔX/ΔY while moving; nothing otherwise. - #[test] - fn the_live_readout_follows_the_drag() { - let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); - app.ui.extras.snap = false; - crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); - assert_eq!(live_readout(&app), None, "not dragging"); - let ev = |app: &mut PhotocraftApp, e| crate::canvas::tool_event(app, e, egui::Modifiers::NONE); - // A quarter turn about the centre (96, 96): from right of the box to below it. - ev(&mut app, ToolEvent::Down { x: 220.0, y: 96.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Move { x: 96.0, y: 220.0, pressure: 1.0 }); - let Some(Readout::Angle(a)) = live_readout(&app) else { panic!("{:?}", live_readout(&app)) }; - assert!((a - 90.0).abs() < 1e-6, "{a}"); - ev(&mut app, ToolEvent::Up { x: 96.0, y: 220.0 }); - assert_eq!(live_readout(&app), None, "released"); - let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); - app.ui.extras.snap = false; - crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); - ev(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Move { x: 65.0, y: 57.0, pressure: 1.0 }); - assert_eq!(live_readout(&app), Some(Readout::Offset([5.0, -3.0]))); - ev(&mut app, ToolEvent::Up { x: 65.0, y: 57.0 }); - // The right edge doubles the width (proportional by default: the height too). - ev(&mut app, ToolEvent::Down { x: 165.0, y: 93.0, pressure: 1.0 }); - ev(&mut app, ToolEvent::Move { x: 293.0, y: 93.0, pressure: 1.0 }); - let Some(Readout::Scale([w, h])) = live_readout(&app) else { panic!("{:?}", live_readout(&app)) }; - assert!((w - 200.0).abs() < 1e-6 && (h - 200.0).abs() < 1e-6, "{w} {h}"); - } - - #[test] - fn a_distort_corner_stops_before_the_box_folds_over() { - // #1323: dragging a corner across the opposite diagonal stops short of it, so the box - // stays convex instead of folding into a bow tie. - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - app.ui.extras.snap = false; - let ctx = egui::Context::default(); - crate::menus::invoke(&mut app, &ctx, "edit.transform.distort", json!({})).unwrap(); - let q0 = app.ui.transform.as_ref().unwrap().quad; - // Top-left far past the bottom-right corner. - press_drag(&mut app, q0[0], [60.0, 60.0], egui::Modifiers::NONE); - let q = app.ui.transform.as_ref().unwrap().quad; - let sign = turns(&q0)[0].signum(); - assert!(turns(&q).iter().all(|t| t * sign > 0.0), "still convex: {q:?}"); - assert_eq!([q[1], q[2], q[3]], [q0[1], q0[2], q0[3]], "the other corners stay put"); - // It went as far as it could along the drag: up to the TR–BL diagonal (x + y = 32). - assert!(q[0][0] > 15.0 && q[0][0] < 16.0 && (q[0][0] - q[0][1]).abs() < 1e-6, "{q:?}"); - // A drag that keeps the box convex is not held back. - press_drag(&mut app, q[0], [2.0, 4.0], egui::Modifiers::NONE); - assert_eq!(app.ui.transform.as_ref().unwrap().quad[0], [2.0, 4.0]); - } - - #[test] - fn keep_convex_leaves_a_degenerate_start_alone() { - let flat = [[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [3.0, 0.0]]; - let to = [[5.0, 5.0], [1.0, 0.0], [2.0, 0.0], [3.0, 0.0]]; - assert_eq!(keep_convex(flat, to), to); - let nan = [[f64::NAN, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]; - let _ = keep_convex(nan, to); - } - - #[test] - fn the_legacy_preference_swaps_corner_proportions_and_stretches_edges() { - let none = egui::Modifiers::NONE; - let corner = Hit::Corner(1); - let edge = Hit::Edge(1); - // Default: proportional (⇧ frees), so the drag keeps its keys. - assert!(!legacy_mods(false, corner, none).shift); - assert!(!legacy_mods(false, edge, none).shift); - // Legacy: corners free by default, ⇧ keeps proportions; edges always stretch one axis; - // ⌘ gestures are left alone. - assert!(legacy_mods(true, corner, none).shift); - assert!(!legacy_mods(true, corner, egui::Modifiers::SHIFT).shift); - assert!(legacy_mods(true, edge, none).shift); - assert!(legacy_mods(true, edge, egui::Modifiers::SHIFT).shift); - assert!(!legacy_mods(true, corner, egui::Modifiers::COMMAND).shift); - assert!(!legacy_mods(true, edge, egui::Modifiers::COMMAND).shift); - // Through the box: a plain corner drag, then a plain right-edge drag, on a 16×16 square. - for (legacy, proportional) in [(false, true), (true, false)] { - for at_edge in [false, true] { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - app.ui.extras.snap = false; - app.session.prefs.edit(|p| p.general.use_legacy_free_transform = legacy); - begin(&mut app, &egui::Context::default()).unwrap(); - let q0 = app.ui.transform.as_ref().unwrap().quad; - let from = if at_edge { [q0[1][0], (q0[1][1] + q0[2][1]) / 2.0] } else { q0[2] }; - press_drag(&mut app, from, [from[0] + 16.0, from[1]], none); - let q = app.ui.transform.as_ref().unwrap().quad; - let (w, h) = (q[2][0] - q[0][0], q[2][1] - q[0][1]); - assert_eq!((w - h).abs() < 1e-6, proportional, "legacy {legacy}, edge {at_edge}: {w} × {h}"); - } - } - } - - /// #4174: turning off the options bar's Maintain Aspect Ratio link frees the handles too, as in - /// Photoshop: a plain corner or edge drag stretches one way, ⇧ keeps the proportions. Linked - /// (the default) is unchanged, and so is the legacy preference. - #[test] - fn the_aspect_link_decides_whether_handle_drags_keep_proportions() { - let (none, shift) = (egui::Modifiers::NONE, egui::Modifiers::SHIFT); - for (unlinked, legacy, mods, proportional) in - [(false, false, none, true), (true, false, none, false), (true, false, shift, true), (true, true, none, false)] - { - for at_edge in [false, true] { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - app.ui.extras.snap = false; - app.ui.transform_unlinked = unlinked; - app.session.prefs.edit(|p| p.general.use_legacy_free_transform = legacy); - begin(&mut app, &egui::Context::default()).unwrap(); - let q0 = app.ui.transform.as_ref().unwrap().quad; - let from = if at_edge { [q0[1][0], (q0[1][1] + q0[2][1]) / 2.0] } else { q0[2] }; - press_drag(&mut app, from, [from[0] + 16.0, from[1]], mods); - let q = app.ui.transform.as_ref().unwrap().quad; - let (w, h) = (q[2][0] - q[0][0], q[2][1] - q[0][1]); - let case = format!("unlinked {unlinked}, legacy {legacy}, shift {}, edge {at_edge}: {w} × {h}", mods.shift); - if legacy && at_edge { - // Legacy edges always stretch their one axis. - assert!((w - 32.0).abs() < 1e-6 && (h - 16.0).abs() < 1e-6, "{case}"); - } else { - assert_eq!((w - h).abs() < 1e-6, proportional, "{case}"); - assert!((w - 32.0).abs() < 1e-6, "{case}"); - } - } - } - // ⌘ gestures (skew, distort) are left alone. - assert!(!unlinked_mods(true, false, Hit::Corner(0), egui::Modifiers::COMMAND).shift); - assert!(!unlinked_mods(true, false, Hit::Inside, none).shift); - } - - #[test] - fn right_click_while_transforming_switches_the_mode() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let ctx = egui::Context::default(); - begin(&mut app, &ctx).unwrap(); - assert!(crate::canvas_tool_menu::open_transform(&mut app, &ctx, [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - let ids: Vec<&str> = crate::canvas_tool_menu::rows(&menu).iter().flatten().map(|e| e.1).collect(); - assert!(ids.contains(&"edit.transform.distort") && ids.contains(&"edit.freeTransform")); - crate::canvas_tool_menu::choose(&mut app, &ctx, "edit.transform.distort"); - assert_eq!(app.ui.transform.as_ref().unwrap().mode, TransformMode::Distort); - } - - #[test] - fn right_click_menu_warp_row_enters_warp_mode() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let ctx = egui::Context::default(); - begin(&mut app, &ctx).unwrap(); - assert!(crate::canvas_tool_menu::open_transform(&mut app, &ctx, [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - assert!(crate::canvas_tool_menu::rows(&menu).iter().flatten().any(|e| e.1 == "edit.transform.warp")); - assert!(crate::canvas_tool_menu::available(&app, &menu, "edit.transform.warp")); - // Only the current mode (Free Transform) is checked: not Scale, Rotate or Warp. - let checked: Vec<&str> = - crate::canvas_tool_menu::rows(&menu).iter().flatten().map(|e| e.1).filter(|id| crate::canvas_tool_menu::mode_checked(&app, &menu, id)).collect(); - assert_eq!(checked, ["edit.freeTransform"]); - crate::canvas_tool_menu::choose(&mut app, &ctx, "edit.transform.warp"); - assert!(app.ui.transform.as_ref().unwrap().warp.is_some()); - // Already warping: the row is no longer offered. - assert!(!crate::canvas_tool_menu::available(&app, &menu, "edit.transform.warp")); - } - - #[test] - fn right_click_menu_offers_warp_for_a_path() { - // Photoshop's Transform Path menu has Warp too (#3027). - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let ctx = egui::Context::default(); - begin(&mut app, &ctx).unwrap(); - app.ui.transform.as_mut().unwrap().path = Some(json!({})); - assert!(crate::canvas_tool_menu::open_transform(&mut app, &ctx, [10.0, 10.0])); - let menu = app.ui.canvas_tool_menu.clone().unwrap(); - assert!(crate::canvas_tool_menu::available(&app, &menu, "edit.transform.warp")); - } - - fn app_with_square(size: u32, fill: photocraft_geom::Rect) -> PhotocraftApp { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": size, "height": size})).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(fill, &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - app - } - - /// #2439: a layer under others keeps its place in the stack while the box is open. The - /// canvas under the box shows only the layers below it; the ones over it are composited on - /// their own and drawn over the moving pixels. - #[test] - fn free_transform_keeps_the_layer_under_the_layers_over_it() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let red = app.session.active().unwrap().active_layer.unwrap(); - 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(16, 16, 40, 40), &[0.0, 0.0, 1.0, 1.0]); - Ok(()) - }) - .unwrap(); - let blue = app.session.active().unwrap().active_layer.unwrap(); - let bg = app.session.active().unwrap().doc.layers[0].id; - app.session.execute("layer.select", json!({"layer": red.0})).unwrap(); - let ctx = gpu_ctx(); - begin(&mut app, &ctx).unwrap(); - let pv = app.transform_preview.as_ref().unwrap(); - assert!(pv.doc.layer(bg).unwrap().visible, "the layers below show under the box"); - assert!(!pv.doc.layer(blue).unwrap().visible, "the layer over it is drawn over the box instead"); - let (texture, rect) = pv.above.as_ref().and_then(|a| a.shown.as_ref()).expect("something covers the layer"); - assert_eq!(*rect, photocraft_geom::Rect::new(16, 16, 40, 40)); - assert_eq!(texture.size(), [24, 24]); - cancel(&mut app); - - // The top layer: nothing to draw over it. - app.session.execute("layer.select", json!({"layer": blue.0})).unwrap(); - begin(&mut app, &ctx).unwrap(); - let pv = app.transform_preview.as_ref().unwrap(); - assert!(pv.above.as_ref().is_some_and(|a| a.shown.is_none())); - assert!(pv.doc.layer(red).unwrap().visible && pv.doc.layer(bg).unwrap().visible); - cancel(&mut app); - } - - #[test] - fn plain_layers_from_the_top_cover_the_moving_one() { - use photocraft_color::BlendMode; - use photocraft_doc::Layer; - let px = |name: &str| Layer::raster(name, photocraft_color::PixelFormat::RGBA8); - let covers = |layers: &[Layer], id: LayerId| { - let mut out = Vec::new(); - covering(layers, id, &mut out); - out - }; - // In a group: the group's layers over it, then the ones over the group; never the layers - // clipped to it. - let (below, target, mut clip, inner_top, top) = (px("below"), px("target"), px("clip"), px("inner top"), px("top")); - clip.clipped = true; - let (t, c, inner, tp) = (target.id, clip.id, inner_top.id, top.id); - let mut layers = vec![below, Layer::group("group", vec![target, clip, inner_top]), top]; - assert_eq!(covers(&layers, t), [tp, inner]); - 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], 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]; - assert_eq!(vis(&under), [true, true, false]); - let mut over = layers.clone(); - show_only(&mut over, &above.ids); - assert_eq!(vis(&over), [false, true, true]); - let inside: Vec = match &over[1].content { - LayerContent::Group(g) => g.children.iter().map(|l| l.visible).collect(), - _ => Vec::new(), - }; - assert_eq!(inside, [false, false, true]); - - // A layer that blends with what is under it stops the search: it and everything under it - // stay in the document under the box. - layers[2].blend = BlendMode::Multiply; - assert!(covers(&layers, t).is_empty()); - layers[2].blend = BlendMode::Normal; - let mut multiply = px("multiply"); - multiply.blend = BlendMode::Multiply; - layers.insert(2, multiply); - assert_eq!(covers(&layers, t), [tp]); - // A group that isn't Normal or Pass Through keeps what is inside it. - layers[1].blend = BlendMode::Screen; - layers.remove(2); - assert_eq!(covers(&layers, t), [tp]); - assert_eq!(covers(&layers, LayerId::fresh()), [tp], "not in the stack: down to the first layer that isn't plain"); - } - - /// A context that reports a real GPU's texture limit (the default reports 2048). - fn gpu_ctx() -> egui::Context { - let ctx = egui::Context::default(); - // Clear the font atlas delta: epaint panics on dropping unapplied deltas in debug builds. - let mut out = ctx.run_ui(egui::RawInput { max_texture_side: Some(16384), ..Default::default() }, |_| {}); - out.textures_delta.clear(); - ctx - } - - #[test] - fn preview_texture_is_full_resolution() { - // #91: the preview used to be sampled down to 2048 px, so big layers looked blurry at 100%. - let mut app = app_with_square(3000, photocraft_geom::Rect::new(10, 20, 2810, 2420)); - let ctx = gpu_ctx(); - begin(&mut app, &ctx).unwrap(); - let pv = app.transform_preview.as_ref().unwrap(); - assert_eq!(pv.texture.size(), [2800, 2400], "one texel per layer pixel"); - // At 100% the texture has at least as many texels as the box covers screen pixels. - let t = app.ui.transform.as_ref().unwrap(); - assert!(pv.texture.size()[0] as f64 >= t.rect[2] - t.rect[0]); - } - - #[test] - fn nested_group_preview_excludes_its_siblings() { - use photocraft_color::PixelFormat; - use photocraft_doc::Layer; - - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let st = app.session.active_mut().unwrap(); - let doc = Arc::make_mut(&mut st.doc); - let target_pixels = doc.layers.pop().unwrap(); - let mut sibling = Layer::raster("sibling", PixelFormat::RGBA8); - sibling.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(12, 12, 20, 20), &[0.0, 0.0, 1.0, 1.0]); - let target = Layer::group("target", vec![target_pixels]); - let target_id = target.id; - doc.layers.push(Layer::group("parent", vec![target, sibling])); - - let (image, _) = preview_image(&st.doc, target_id, None, photocraft_geom::Rect::new(8, 8, 24, 24), 4096, false); - assert_eq!( - image.pixels[8 * image.size[0] + 8], - Color32::from_rgb(255, 0, 0), - "a sibling in the parent group must not be baked into the moving texture" - ); - } - - fn artboard_preview_app(background: photocraft_doc::ArtboardBackground) -> (PhotocraftApp, LayerId, LayerId) { - use photocraft_doc::{Artboard, Layer}; - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let st = app.session.active_mut().unwrap(); - let doc = Arc::make_mut(&mut st.doc); - let red = doc.layers.pop().unwrap(); - let red_id = red.id; - let mut blue = Layer::raster("covering blue", photocraft_color::PixelFormat::RGBA8); - blue.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(16, 16, 40, 40), &[0.0, 0.0, 1.0, 1.0]); - let mut board = Layer::group("board", vec![red, blue]); - let board_id = board.id; - if let LayerContent::Group(g) = &mut board.content { - let mut ab = Artboard::new(photocraft_geom::Rect::new(0, 0, 64, 64)); - ab.background = background; - g.artboard = Some(ab); - } - doc.layers = vec![board]; - (app, board_id, red_id) - } - - #[test] - fn artboard_transform_overlay_does_not_cover_moving_pixels_with_the_board_background() { - use photocraft_doc::ArtboardBackground; - for background in [ArtboardBackground::White, ArtboardBackground::Black] { - let (mut app, board_id, red_id) = artboard_preview_app(background); - let original = app.session.active().unwrap().doc.clone(); - begin(&mut app, &gpu_ctx()).unwrap(); - let pv = app.transform_preview.as_ref().unwrap(); - let (texture, rect) = pv.above.as_ref().unwrap().shown.as_ref().unwrap(); - let (image, _) = texture.level_image(0).unwrap(); - let at = |x: i32, y: i32| image.pixels[(y - rect.y0) as usize * image.size[0] + (x - rect.x0) as usize]; - assert_eq!(at(12, 12), Color32::TRANSPARENT, "the board background belongs under the moving layer"); - assert_eq!(at(20, 20), Color32::BLUE, "covering siblings must still cover the moving layer"); - let under = photocraft_compose::render(&pv.doc, photocraft_geom::Rect::new(0, 0, 64, 64)); - assert_eq!(under.px[12 * 64 + 12], background.rgba().unwrap(), "the board background remains on the base canvas"); - assert!(!pv.doc.layer(red_id).unwrap().visible); - cancel(&mut app); - let LayerContent::Group(g) = &app.session.active().unwrap().doc.layer(board_id).unwrap().content else { panic!("board") }; - assert_eq!(g.artboard.as_ref().unwrap().background, background); - assert!(Arc::ptr_eq(&app.session.active().unwrap().doc, &original), "preview and cancellation do not edit the document"); - } - } - - #[test] - fn artboard_solo_preview_keeps_holes_transparent_and_the_board_clip() { - use photocraft_doc::ArtboardBackground; - let (app, board_id, red_id) = artboard_preview_app(ArtboardBackground::White); - let original = &app.session.active().unwrap().doc; - let mut solo = (**original).clone(); - solo.layer_mut(red_id).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(-2, -2, 1, 1), &[1.0, 0.0, 0.0, 1.0]); - solo_layer(&mut solo.layers, red_id); - let b = photocraft_geom::Rect::new(-2, -2, 66, 66); - let rendered = photocraft_compose::render(&solo, b); - let at = |x: i32, y: i32| rendered.px[(y + 2) as usize * 68 + (x + 2) as usize]; - assert_eq!(at(12, 12), [1.0, 0.0, 0.0, 1.0]); - assert_eq!(at(30, 30), [0.0; 4], "neither the board's white nor another child enters the moving texture"); - assert_eq!(at(-1, -1), [0.0; 4], "the artboard still clips its children"); - let LayerContent::Group(g) = &solo.layer(board_id).unwrap().content else { panic!("board") }; - assert!(g.artboard.is_some(), "keep the board boundary while omitting its background"); - } - - #[test] - fn artboard_moved_as_a_whole_keeps_its_background() { - use photocraft_doc::ArtboardBackground; - let (app, board_id, _) = artboard_preview_app(ArtboardBackground::Black); - let mut doc = (*app.session.active().unwrap().doc).clone(); - solo_layer(&mut doc.layers, board_id); - let rendered = photocraft_compose::render(&doc, photocraft_geom::Rect::new(0, 0, 64, 64)); - assert_eq!(rendered.px[50 * 64 + 50], [0.0, 0.0, 0.0, 1.0]); - show_only(&mut doc.layers, &[board_id]); - let rendered = photocraft_compose::render(&doc, photocraft_geom::Rect::new(0, 0, 64, 64)); - assert_eq!(rendered.px[50 * 64 + 50], [0.0, 0.0, 0.0, 1.0], "a whole covering artboard keeps its own background"); - } - - #[test] - fn nested_group_preview_detaches_every_clipped_ancestor() { - use photocraft_color::PixelFormat; - use photocraft_doc::Layer; - - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let st = app.session.active_mut().unwrap(); - let doc = Arc::make_mut(&mut st.doc); - let target_pixels = doc.layers.pop().unwrap(); - let target = Layer::group("target", vec![target_pixels]); - let target_id = target.id; - let mut middle = Layer::group("middle clipped ancestor", vec![target]); - middle.clipped = true; - let mut inner_base = Layer::raster("hidden inner clipping base", PixelFormat::RGBA8); - inner_base.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 64, 64), &[0.0, 0.0, 1.0, 1.0]); - let mut outer = Layer::group("outer clipped ancestor", vec![inner_base, middle]); - outer.clipped = true; - doc.layers.push(outer); - - let (image, _) = preview_image(&st.doc, target_id, None, photocraft_geom::Rect::new(8, 8, 24, 24), 4096, false); - assert_eq!(image.pixels[8 * image.size[0] + 8], Color32::from_rgb(255, 0, 0), "hidden clipping bases must not make a nested target disappear"); - } - - #[test] - fn unknown_preview_target_keeps_the_previous_document_fallback() { - let app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let st = app.session.active().unwrap(); - let (image, _) = preview_image(&st.doc, LayerId::fresh(), None, photocraft_geom::Rect::new(8, 8, 24, 24), 4096, false); - assert_eq!(image.pixels[8 * image.size[0] + 8], Color32::from_rgb(255, 0, 0)); - } - - /// The textured meshes `draw_content` paints for the moving pixels (not the box or handles). - fn preview_meshes(app: &PhotocraftApp, xf: &ViewXform) -> Vec { - let ctx = gpu_ctx(); - let mut out = ctx.run_ui(egui::RawInput { max_texture_side: Some(16384), ..Default::default() }, |ui| { - let painter = ui.ctx().layer_painter(egui::LayerId::background()); - draw_content(app, &painter, xf); - }); - out.textures_delta.clear(); - out.shapes - .into_iter() - .filter_map(|s| match s.shape { - egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => Some((*m).clone()), - _ => None, - }) - .collect() - } - - #[test] - fn preview_pixels_past_the_canvas_are_hidden() { - // #2027: a box scaled past the canvas drew its pixels over the pasteboard. - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 56, 56)); - begin(&mut app, &gpu_ctx()).unwrap(); - scale_about_pivot(&mut app, 2.0, 2.0); - let q = app.ui.transform.as_ref().unwrap().quad; - assert!(q[0][0] < -10.0 && q[2][1] > 74.0, "the box reaches past the canvas: {q:?}"); - let tol = 1e-3; - for (rotation, flip) in [(0.0, false), (30.0, false), (-75.0, true)] { - let xf = ViewXform { - rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0)), - zoom: 2.0, - center: [32.0, 32.0], - flip, - rotation, - aspect: 1.0, - }; - let meshes = preview_meshes(&app, &xf); - let verts: Vec<[f64; 2]> = meshes.iter().flat_map(|m| m.vertices.iter().map(|v| xf.to_doc(v.pos))).collect(); - assert!(!verts.is_empty(), "the preview still draws (rotation {rotation})"); - for d in &verts { - assert!(d[0] >= -tol && d[1] >= -tol && d[0] <= 64.0 + tol && d[1] <= 64.0 + tol, "vertex {d:?} off the canvas (rotation {rotation})"); - } - // The clipped mesh still covers the whole canvas: the corners lie on it. - for corner in [[0.0, 0.0], [64.0, 0.0], [64.0, 64.0], [0.0, 64.0]] { - assert!(verts.iter().any(|d| (d[0] - corner[0]).abs() < 1e-2 && (d[1] - corner[1]).abs() < 1e-2), "corner {corner:?} (rotation {rotation})"); - } - } - // Inside the canvas the mesh is drawn unchanged (24×24 grid). - cancel(&mut app); - begin(&mut app, &gpu_ctx()).unwrap(); - let xf = ViewXform { - rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(200.0, 200.0)), - zoom: 1.0, - center: [32.0, 32.0], - flip: false, - rotation: 0.0, - aspect: 1.0, - }; - let meshes = preview_meshes(&app, &xf); - assert_eq!(meshes.iter().map(|m| m.vertices.len()).sum::(), 25 * 25); - } - - #[test] - fn shift_body_drag_locks_to_eight_directions_and_switches() { - let mut s = session(); - let g = Gesture { hit: Hit::Inside, start: [40.0, 20.0], quad0: s.quad, pivot0: s.pivot }; - apply_drag(&mut s, g, [60.0, 23.0], egui::Modifiers::SHIFT); - assert!(close(s.quad, corners([20.0, 0.0, 120.0, 50.0])), "horizontal: {:?}", s.quad); - apply_drag(&mut s, g, [60.0, 39.0], egui::Modifiers::SHIFT); - assert!((s.quad[0][0] - s.quad[0][1]).abs() < 1e-9 && s.quad[0][0] > 15.0, "diagonal: {:?}", s.quad[0]); - apply_drag(&mut s, g, [41.0, 60.0], egui::Modifiers::SHIFT); - assert!(close(s.quad, corners([0.0, 40.0, 100.0, 90.0])), "vertical: {:?}", s.quad); - } - - #[test] - fn alt_click_moves_the_reference_point_and_edges_skew() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - let ctx = egui::Context::default(); - begin(&mut app, &ctx).unwrap(); - assert!(pointer(&mut app, ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::ALT)); - pointer(&mut app, ToolEvent::Up { x: 40.0, y: 40.0 }, egui::Modifiers::ALT); - let t = app.ui.transform.as_ref().unwrap(); - assert_eq!(t.pivot, [40.0, 40.0]); - assert_eq!(t.quad, corners(t.rect), "the box didn't move"); - // ⌘ on an edge skews: both corners of the top edge move. - let mut s = session(); - drag(&mut s, [50.0, 0.0], [70.0, 5.0], egui::Modifiers::COMMAND); - assert_eq!((s.quad[0], s.quad[1], s.quad[2]), ([20.0, 5.0], [120.0, 5.0], [100.0, 50.0])); - // ⌘⇧: only along the edge. - let mut s = session(); - drag(&mut s, [50.0, 0.0], [70.0, 5.0], egui::Modifiers::COMMAND | egui::Modifiers::SHIFT); - assert_eq!((s.quad[0], s.quad[1]), ([20.0, 0.0], [120.0, 0.0])); - // ⌘⌥⇧ on a corner: perspective (the paired corner mirrors). - let mut s = session(); - drag(&mut s, [100.0, 0.0], [101.0, -10.0], egui::Modifiers::COMMAND | egui::Modifiers::ALT | egui::Modifiers::SHIFT); - assert_eq!((s.quad[1], s.quad[2]), ([100.0, -10.0], [100.0, 60.0])); - } - - /// `cargo test --release -p photocraft-ui-egui transform_preview_bench -- --ignored --nocapture` - #[test] - #[ignore] - fn transform_preview_bench() { - let (w, h) = (6000, 4000); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": w, "height": h})).unwrap(); - app.sync_views(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session.execute("filter.render.clouds", json!({})).unwrap(); - let ctx = gpu_ctx(); - let t0 = std::time::Instant::now(); - begin(&mut app, &ctx).unwrap(); - let begin_ms = t0.elapsed().as_secs_f64() * 1e3; - // The same with a linked layer mask applied to the texels (#205). - cancel(&mut app); - app.session.execute("layer.layerMask.revealAll", json!({})).unwrap(); - app.session.execute("paint.gradient", json!({"from": [0, 0], "to": [w, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap(); - let t0 = std::time::Instant::now(); - begin(&mut app, &ctx).unwrap(); - let masked_ms = t0.elapsed().as_secs_f64() * 1e3; - eprintln!("transform preview begin {w}x{h}: {begin_ms:.1} ms, with a linked mask {masked_ms:.1} ms"); - let size = app.transform_preview.as_ref().unwrap().texture.size(); - rotate_about_pivot(&mut app, 0.05); - let frame = |zoom: f32| { - let t0 = std::time::Instant::now(); - let _ = ctx.run_ui(egui::RawInput { max_texture_side: Some(16384), ..Default::default() }, |ui| { - let painter = ui.ctx().layer_painter(egui::LayerId::background()); - let xf = ViewXform { - rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 1000.0)), - zoom, - center: [3000.0, 2000.0], - flip: false, - rotation: 0.0, - aspect: 1.0, - }; - draw_content(&app, &painter, &xf); - draw_overlay(&app, &painter, &xf); - }); - t0.elapsed().as_secs_f64() * 1e3 - }; - let first: Vec = [1.0, 0.25, 3.0].iter().map(|z| frame(*z)).collect(); - let n = 50; - let steady = (0..n).map(|i| frame([1.0, 0.25, 3.0][i % 3])).sum::() / n as f64; - eprintln!( - "transform preview {w}x{h}: texture {size:?}, begin {begin_ms:.1} ms, first frame per level (1x, 0.25x, 3x) {first:.1?} ms, steady frame {steady:.3} ms" - ); - } - - #[test] - fn transform_selection_moves_only_the_outline() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); - let px0 = app.session.active().unwrap().doc.layers[0].surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 64, 64)); - let ctx = egui::Context::default(); - crate::menus::invoke(&mut app, &ctx, "select.transformSelection", json!({})).unwrap(); - let t = app.ui.transform.as_ref().unwrap(); - assert!(t.selection && t.rect == [8.0, 8.0, 24.0, 24.0]); - assert!(app.transform_preview.as_ref().unwrap().doc.selection.is_none(), "ants hidden while transforming"); - scale_about_pivot(&mut app, 2.0, 2.0); - commit(&mut app); - let st = app.session.active().unwrap(); - let b = st.doc.selection.as_ref().unwrap().content_bounds(); - assert!(b.width().abs_diff(32) <= 2 && b.x0.abs_diff(0) <= 1, "{b:?}"); - assert_eq!(st.doc.layers[0].surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 64, 64)), px0); - } - - #[test] - fn warp_mode_drags_anchor_with_handles_splits_and_commits() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, a| { - doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 32, 32), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - let ctx = egui::Context::default(); - begin_warp(&mut app, &ctx).unwrap(); - let w = app.ui.transform.as_ref().unwrap().warp.clone().unwrap(); - assert!(w.is_identity()); - // Drag the bottom-right anchor (point 15) by (+10, +6): its two handles follow. - warp_pointer(&mut app, ToolEvent::Down { x: 32.0, y: 32.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); - warp_pointer(&mut app, ToolEvent::Up { x: 42.0, y: 38.0 }, 2.0, egui::Modifiers::NONE); - let m = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.clone().unwrap(); - assert_eq!(m.points[15], [42.0, 38.0]); - let near = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9; - assert!(near(m.points[14], [24.0 + 10.0, 38.0]), "{:?}", m.points[14]); - assert!(near(m.points[11], [42.0, 24.0 + 6.0]), "{:?}", m.points[11]); - split(&mut app, "edit.transform.splitWarpCrosswise", None).unwrap(); - let split_m = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.as_ref().unwrap(); - assert_eq!(split_m.points.last().copied(), Some([42.0, 38.0]), "the corner survives the cut"); - assert!(split_m.us.iter().any(|u| (u - 1.0 / 3.0).abs() < 1e-6) && split_m.us.iter().any(|u| (u - 0.5).abs() < 1e-6)); - commit(&mut app); - let st = app.session.active().unwrap(); - let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); - assert!(b.x1 >= 41 && b.y1 >= 37, "{b:?}"); - assert!(app.ui.transform.is_none()); - // Toggling back to the box drops the warp. - begin_warp(&mut app, &ctx).unwrap(); - leave_warp(&mut app); - assert!(app.ui.transform.as_ref().unwrap().warp.is_none()); - } - - #[test] - fn a_thin_layer_scaled_then_warped_commits_the_curve() { - // #5793: a 3 px column stretched wide, switched to Warp and pulled down in the middle. - // The commit came out straight: the warp's grid was one cell across the 3 source pixels. - let mut app = app_with_square(128, photocraft_geom::Rect::new(40, 20, 43, 60)); - let ctx = egui::Context::default(); - begin(&mut app, &ctx).unwrap(); - scale_about_pivot(&mut app, 30.0, 1.0); - enter_warp(&mut app, &ctx); - warp_pointer(&mut app, ToolEvent::Down { x: 41.5, y: 40.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); - warp_pointer(&mut app, ToolEvent::Move { x: 41.5, y: 70.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); - warp_pointer(&mut app, ToolEvent::Up { x: 41.5, y: 70.0 }, 2.0, egui::Modifiers::NONE); - 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] - }; - // The middle sags below the band's old bottom edge (y 60); the ends stay put. - assert!(alpha(41, 70) > 0.99, "middle {}", alpha(41, 70)); - assert!(alpha(15, 70) < 0.01 && alpha(15, 40) > 0.99, "end {} {}", alpha(15, 70), alpha(15, 40)); - } - - fn warping_square() -> PhotocraftApp { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 32, 32)); - begin_warp(&mut app, &egui::Context::default()).unwrap(); - app - } - - fn warp_mesh(app: &PhotocraftApp) -> BezierMesh { - app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.clone().unwrap() - } - - #[test] - fn warp_drag_from_inside_the_grid_pulls_the_surface_under_the_pointer() { - let mut app = warping_square(); - let before = warp_mesh(&app); - // (20, 20) is mid-cell, far from every anchor and handle. - warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); - assert!(matches!(app.transform_preview.as_ref().unwrap().warp_drag, Some(WarpDrag::Surface { .. }))); - warp_pointer(&mut app, ToolEvent::Move { x: 30.0, y: 14.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); - warp_pointer(&mut app, ToolEvent::Up { x: 30.0, y: 14.0 }, 2.0, egui::Modifiers::NONE); - let after = warp_mesh(&app); - let (s, t) = surface_at(&before, [20.0, 20.0]).unwrap(); - let moved = after.eval(s, t); - assert!((moved[0] - 30.0).abs() < 1e-6 && (moved[1] - 14.0).abs() < 1e-6, "{moved:?}"); - assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_none()); - // The picture keeps filling its frame: a pull in the middle leaves the box corners put. - assert!([0, 3, 12, 15].iter().all(|k| after.points[*k] == before.points[*k])); - assert!(after.points[5] != before.points[5], "the inside of the grid moved"); - } - - /// #7885: a surface drag (a press inside a cell, on no anchor or handle) commits exactly as - /// the preview draws it. The layer is a gradient whose colour encodes where each pixel came - /// from, so every committed pixel says which source point landed there; the preview puts - /// source point `p` at `warp.map(p)`, and the commit must agree. - #[test] - fn warp_surface_drag_commits_as_previewed() { - const N: i32 = 96; - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": N, "height": N})).unwrap(); - app.sync_views(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - let code = |x: f64, y: f64| [x / (N - 1) as f64, y / (N - 1) as f64]; - app.session - .edit("paint", |doc, a| { - let s = doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap(); - for y in 0..N { - for x in 0..N { - let [r, g] = code(x as f64, y as f64); - s.write_pixel(x, y, &[r as f32, g as f32, 0.5, 1.0]); - } - } - Ok(()) - }) - .unwrap(); - begin_warp(&mut app, &egui::Context::default()).unwrap(); - let (start, end) = ([30.0, 30.0], [39.0, 25.0]); - // A press well inside the top-left cell: a surface drag, not a point drag. - warp_pointer(&mut app, ToolEvent::Down { x: start[0], y: start[1], pressure: 1.0 }, 2.0, egui::Modifiers::NONE); - assert!(matches!(app.transform_preview.as_ref().unwrap().warp_drag, Some(WarpDrag::Surface { .. }))); - warp_pointer(&mut app, ToolEvent::Move { x: end[0], y: end[1], pressure: 1.0 }, 2.0, egui::Modifiers::NONE); - warp_pointer(&mut app, ToolEvent::Up { x: end[0], y: end[1] }, 2.0, egui::Modifiers::NONE); - // What the preview draws: the mapping of the warp the session holds. - let previewed = app.ui.transform.as_ref().unwrap().warp.clone().unwrap(); - let landed = previewed.map(start[0], start[1]); - assert!((landed.0 - end[0]).abs() < 1e-6 && (landed.1 - end[1]).abs() < 1e-6, "the grabbed point follows the pointer: {landed:?}"); - 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 from = |x: f64, y: f64| { - let mut p = [0.0f32; 4]; - s.read_pixel(x.round() as i32, y.round() as i32, &mut p); - [p[0] as f64 * (N - 1) as f64, p[1] as f64 * (N - 1) as f64] - }; - // The grabbed point's pixel moved with the pointer: the drag did not get lost. - let got = from(end[0], end[1]); - assert!((got[0] - start[0]).abs() < 2.0 && (got[1] - start[1]).abs() < 2.0, "pixel at the drop point came from {got:?}, not {start:?}"); - // And everywhere else the committed pixels sit where the preview put them. - for j in 1..12 { - for i in 1..12 { - let src = [i as f64 * 8.0, j as f64 * 8.0]; - let (dx, dy) = previewed.map(src[0], src[1]); - if !(1.0..(N - 2) as f64).contains(&dx) || !(1.0..(N - 2) as f64).contains(&dy) { - continue; - } - let got = from(dx, dy); - assert!((got[0] - src[0]).abs() < 2.0 && (got[1] - src[1]).abs() < 2.0, "{src:?} previewed at {:?} but committed {got:?} there", (dx, dy)); - } - } - } - - #[test] - fn a_handle_belongs_to_the_anchor_it_hangs_off() { - assert_eq!(handle_anchor(0, 1), (0, 0)); - assert_eq!(handle_anchor(0, 2), (0, 3)); - assert_eq!(handle_anchor(1, 0), (0, 0)); - assert_eq!(handle_anchor(5, 3), (6, 3)); - assert_eq!(handle_anchor(3, 3), (3, 3)); - } - - #[test] - fn reset_warp_returns_to_the_untouched_grid_and_keeps_the_session() { - let mut app = warping_square(); - warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); - warp_pointer(&mut app, ToolEvent::Up { x: 30.0, y: 14.0 }, 2.0, egui::Modifiers::NONE); - assert!(!app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().is_identity()); - reset_warp(&mut app); - let w = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap(); - assert!(w.is_identity(), "back to the untouched box"); - assert_eq!(w.mesh.as_ref().map(|m| (m.us.len(), m.vs.len())), Some((2, 2))); - assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_none()); - // Not warping: nothing to reset. - leave_warp(&mut app); - reset_warp(&mut app); - assert!(app.ui.transform.as_ref().unwrap().warp.is_none()); - } - - #[test] - fn warp_press_outside_the_grid_grabs_nothing() { - let mut app = warping_square(); - let before = warp_mesh(&app); - warp_pointer(&mut app, ToolEvent::Down { x: 55.0, y: 55.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); - assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_none()); - warp_pointer(&mut app, ToolEvent::Up { x: 60.0, y: 60.0 }, 2.0, egui::Modifiers::NONE); - assert_eq!(warp_mesh(&app), before); - } - - #[test] - fn ctrl_click_cuts_the_grid_both_ways() { - let mut app = warping_square(); - let ctrl = egui::Modifiers::COMMAND; - warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, ctrl); - warp_pointer(&mut app, ToolEvent::Up { x: 20.0, y: 20.0 }, 2.0, ctrl); - let m = warp_mesh(&app); - // A cut each way at the pointer (the default grid's rule-of-thirds guides become real - // lines too, as with the Cross split tool). - assert!(m.us.iter().any(|u| (u - 0.5).abs() < 1e-6), "vertical cut: {:?}", m.us); - assert!(m.vs.iter().any(|v| (v - 0.5).abs() < 1e-6), "horizontal cut: {:?}", m.vs); - } - - #[test] - fn replacing_the_warp_mesh_cancels_a_pending_point_drag() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 32, 32)); - let ctx = egui::Context::default(); - begin_warp(&mut app, &ctx).unwrap(); - for _ in 0..3 { - split(&mut app, "edit.transform.splitWarpCrosswise", None).unwrap(); - } - - pointer(&mut app, ToolEvent::Down { x: 32.0, y: 32.0, pressure: 1.0 }, egui::Modifiers::NONE); - assert!(matches!(app.transform_preview.as_ref().unwrap().warp_drag, Some(WarpDrag::Point { .. })), "the anchor drag is armed"); - - split(&mut app, "edit.transform.removeWarpSplit", None).unwrap(); - assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_none(), "the old mesh index is discarded"); - - // A later control-channel move belongs to the old gesture and must be harmless. - pointer(&mut app, ToolEvent::Move { x: 40.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE); - } - - /// A press on a preset warp that misses its points leaves the preset alone (no invisible undo - /// step); grabbing a point turns it into a custom mesh. - #[test] - fn a_press_on_a_preset_warp_converts_it_only_when_it_grabs_the_grid() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - app.session - .edit("paint", |doc, a| { - doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 32, 32), &[1.0, 0.0, 0.0, 1.0]); - Ok(()) - }) - .unwrap(); - begin_warp(&mut app, &egui::Context::default()).unwrap(); - let t = app.ui.transform.as_mut().unwrap(); - let preset = Warp::preset(WarpStyle::Arc, 50.0, t.rect); - t.warp = Some(preset.clone()); - // Off the grid altogether: a miss. - warp_pointer(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); - warp_pointer(&mut app, ToolEvent::Up { x: 60.0, y: 60.0 }, 2.0, egui::Modifiers::NONE); - assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref(), Some(&preset), "a miss changes nothing"); - // Inside the grid, away from every point: the surface is grabbed, so the preset converts. - warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); - assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().style, WarpStyle::Custom); - warp_pointer(&mut app, ToolEvent::Up { x: 20.0, y: 20.0 }, 2.0, egui::Modifiers::NONE); - app.ui.transform.as_mut().unwrap().warp = Some(preset.clone()); - let corner = preset.to_mesh(1, 1).points[15]; - warp_pointer(&mut app, ToolEvent::Down { x: corner[0], y: corner[1], pressure: 1.0 }, 2.0, egui::Modifiers::NONE); - assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().style, WarpStyle::Custom); - } - - // ---- Layer masks (#205) ---- - - /// `app_with_square` (red over 8..24) plus a reveal-all mask hiding x < 16. - fn masked_app(linked: bool) -> PhotocraftApp { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - app.session.execute("layer.layerMask.revealAll", json!({})).unwrap(); - app.session - .edit("mask", |doc, a| { - let m = doc.layer_mut(a.unwrap()).unwrap().mask.as_mut().unwrap(); - m.surface.fill_rect(photocraft_geom::Rect::new(0, 0, 16, 64), &[0.0]); - m.linked = linked; - Ok(()) - }) - .unwrap(); - app - } - - fn texel_alpha(img: &egui::ColorImage, x: usize, y: usize) -> u8 { - img.pixels[y * img.size[0] + x].a() - } - - #[test] - fn transform_preview_preserves_displayed_profile_colors() { - let bounds = photocraft_geom::Rect::new(0, 0, 8, 8); - for (wide_gamut, monitor, warp) in [(false, "srgb", false), (true, "srgb", false), (false, "display-p3", false), (true, "srgb", true)] { - let mut app = app_with_square(8, bounds); - app.session - .edit("original color sample", |doc, active| { - if wide_gamut { - doc.icc_profile = Some(photocraft_cms::Builtin::AdobeRgbCompat.profile().to_bytes()); - } - doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.55, 0.35, 0.2, 1.0]); - Ok(()) - }) - .unwrap(); - app.session.color.settings.monitor_profile = monitor.into(); - let st = app.session.active().unwrap(); - let display = app.session.color.canvas_display(&st.doc).unwrap(); - assert_eq!(!display.is_identity(), wide_gamut || monitor != "srgb"); - let composite = photocraft_compose::render(&st.doc, bounds); - let expected = crate::canvas::display_image(Some(&display), &composite); - let ctx = gpu_ctx(); - if warp { - begin_warp(&mut app, &ctx).unwrap(); - } else { - begin(&mut app, &ctx).unwrap(); - } - let xf = ViewXform { - rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(80.0, 80.0)), - zoom: 1.0, - center: [4.0, 4.0], - flip: false, - rotation: 0.0, - aspect: 1.0, - }; - let mut out = ctx.run_ui(egui::RawInput { max_texture_side: Some(16384), ..Default::default() }, |ui| { - draw_content(&app, &ui.ctx().layer_painter(egui::LayerId::background()), &xf); - }); - let texture = out - .shapes - .iter() - .find_map(|s| match &s.shape { - egui::Shape::Mesh(mesh) if mesh.texture_id != egui::TextureId::default() => Some(mesh.texture_id), - _ => None, - }) - .expect("transform draws a textured mesh"); - let upload = out.textures_delta.set.get(&texture).and_then(|updates| updates.last()).expect("drawn texture was uploaded"); - let egui::ImageData::Color(image) = &upload.image; - let shown = image.pixels[0]; - out.textures_delta.clear(); - assert_eq!(shown, expected.pixels[0], "transform changed displayed color; wide_gamut={wide_gamut}, monitor={monitor}, warp={warp}"); - } - } - - #[test] - fn preview_applies_the_linked_mask() { - for linked in [true, false] { - let app = masked_app(linked); - let st = app.session.active().unwrap(); - let id = st.active_layer.unwrap(); - let b = photocraft_geom::Rect::new(8, 8, 24, 24); - let (img, _) = preview_image(&st.doc, id, None, b, 4096, false); - // Texel x = doc x − 8: x 10 is hidden by the mask, x 20 shows. - assert_eq!(texel_alpha(&img, 12, 4), 255); - assert_eq!(texel_alpha(&img, 2, 4), if linked { 0 } else { 255 }, "linked={linked}"); - } - // With a selection the lifted pixels carry the mask too. - let mut app = masked_app(true); - app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 12, "height": 16})).unwrap(); - let ctx = egui::Context::default(); - begin(&mut app, &ctx).unwrap(); - let st = app.session.active().unwrap(); - let sel = st.doc.selection.clone().unwrap(); - let id = st.active_layer.unwrap(); - let (lifted, _) = photocraft_engine::transform_cmds::split_selected(st.doc.layer(id).unwrap().surface().unwrap(), &sel).unwrap(); - let b = photocraft_geom::Rect::new(8, 8, 20, 24); - let (img, _) = preview_image(&st.doc, id, Some(&lifted), b, 4096, false); - assert_eq!(texel_alpha(&img, 2, 4), 0, "masked"); - assert_eq!(texel_alpha(&img, 10, 4), 255, "revealed"); - } - - #[test] - fn transform_selection_tint_is_not_document_color() { - let mut app = app_with_square(8, photocraft_geom::Rect::new(0, 0, 8, 8)); - app.session.color.settings.monitor_profile = "display-p3".into(); - app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); - let ctx = gpu_ctx(); - begin_selection(&mut app, &ctx).unwrap(); - let raw = app.transform_preview.as_ref().unwrap().texture.level_image(0).unwrap().0; - let xf = ViewXform { - rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(80.0, 80.0)), - zoom: 1.0, - center: [4.0, 4.0], - flip: false, - rotation: 0.0, - aspect: 1.0, - }; - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { - draw_content(&app, &ui.ctx().layer_painter(egui::LayerId::background()), &xf); - }); - let id = out - .shapes - .iter() - .find_map(|s| match &s.shape { - egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => Some(m.texture_id), - _ => None, - }) - .unwrap(); - let egui::ImageData::Color(shown) = &out.textures_delta.set.get(&id).unwrap().last().unwrap().image; - assert_eq!(shown.pixels, raw.pixels); - out.textures_delta.clear(); - } - - #[test] - fn transform_covering_layer_uses_the_same_monitor_profile() { - let bounds = photocraft_geom::Rect::new(0, 0, 8, 8); - let mut app = app_with_square(8, bounds); - let lower = app.session.active().unwrap().active_layer.unwrap(); - app.session.execute("layer.new.layer", json!({})).unwrap(); - let upper = app.session.active().unwrap().active_layer.unwrap(); - app.session - .edit("original color samples", |doc, _| { - doc.layer_mut(lower).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.55, 0.35, 0.2, 1.0]); - doc.layer_mut(upper).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.2, 0.5, 0.7, 1.0]); - Ok(()) - }) - .unwrap(); - app.session.color.settings.monitor_profile = "display-p3".into(); - let doc = app.session.active().unwrap().doc.clone(); - let display = app.session.color.canvas_display(&doc).unwrap(); - let expected = [lower, upper].map(|id| { - let mut solo = (*doc).clone(); - for layer in &mut solo.layers { - layer.visible = layer.id == id; - } - crate::canvas::display_image(Some(&display), &photocraft_compose::render(&solo, bounds)).pixels[0] - }); - app.session.execute("layer.select", json!({"layer": lower.0})).unwrap(); - let ctx = gpu_ctx(); - begin(&mut app, &ctx).unwrap(); - let xf = ViewXform { - rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(80.0, 80.0)), - zoom: 1.0, - center: [4.0, 4.0], - flip: false, - rotation: 0.0, - aspect: 1.0, - }; - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { - draw_content(&app, &ui.ctx().layer_painter(egui::LayerId::background()), &xf); - }); - let shown: Vec<_> = out - .shapes - .iter() - .filter_map(|s| match &s.shape { - egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => { - let egui::ImageData::Color(image) = &out.textures_delta.set.get(&m.texture_id).unwrap().last().unwrap().image; - Some(image.pixels[0]) - } - _ => None, - }) - .collect(); - out.textures_delta.clear(); - assert_eq!(shown, expected, "moving pixels and covering pixels use the same display conversion"); - } - - #[test] - #[ignore = "requires a GPU adapter; renders profile-managed transform evidence"] - fn transform_profile_visual_evidence() { - let _guard = photocraft_testkit::gpu_lock(); - let destination = std::env::var("PHOTOCRAFT_TRANSFORM_EVIDENCE").unwrap_or_else(|_| "transform-profile-evidence".into()); - std::fs::create_dir_all(&destination).unwrap(); - for monitor in ["srgb", "display-p3"] { - let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).with_max_steps(64).wgpu().build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.set_wgpu(cc.wgpu_render_state.as_ref().unwrap().clone()); - app.run("file.new", json!({"width": 400, "height": 300, "background": "transparent"})).unwrap(); - app.run("layer.new.layer", json!({})).unwrap(); - app.session - .edit("original color swatches", |doc, active| { - let surface = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); - for (x, color) in [(60, [0.55, 0.35, 0.2, 1.0]), (160, [0.2, 0.6, 0.35, 1.0]), (260, [0.3, 0.4, 0.7, 1.0])] { - surface.fill_rect(photocraft_geom::Rect::new(x, 60, x + 80, 220), &color); - } - Ok(()) - }) - .unwrap(); - app.session.color.settings.monitor_profile = monitor.into(); - app.ui.extras.rulers = false; - app.sync_views(); - app.ui.views[0].zoom = 1.0; - app.ui.views[0].center = [200.0, 150.0]; - app.ui.views[0].fit_pending = false; - app - }); - h.run_steps(8); - let app = h.state(); - let view = &app.ui.views[0]; - let xf = ViewXform { rect: app.last_canvas_rect, zoom: view.zoom, center: view.center, flip: false, rotation: 0.0, aspect: 1.0 }; - let points = [100.0, 200.0, 300.0].map(|x| xf.to_screen(x, 100.0) * h.ctx.pixels_per_point()); - let before = h.render().unwrap(); - before.save(std::path::Path::new(&destination).join(format!("{monitor}-before.png"))).unwrap(); - let ctx = h.ctx.clone(); - begin(h.state_mut(), &ctx).unwrap(); - h.run_steps(8); - assert!(h.state().ui.transform.is_some()); - let during = h.render().unwrap(); - during.save(std::path::Path::new(&destination).join(format!("{monitor}-during.png"))).unwrap(); - commit(h.state_mut()); - h.run_steps(8); - assert!(h.state().ui.transform.is_none()); - let after = h.render().unwrap(); - after.save(std::path::Path::new(&destination).join(format!("{monitor}-after.png"))).unwrap(); - for point in points { - let (x, y) = (point.x as u32, point.y as u32); - let expected = before.get_pixel(x, y).0; - assert_ne!(expected[0], expected[1], "sample must hit a color swatch, not the checkerboard"); - for actual in [during.get_pixel(x, y).0, after.get_pixel(x, y).0] { - assert!(actual.iter().zip(expected).all(|(a, b)| a.abs_diff(b) <= 2), "{monitor}: before={expected:?}, shown={actual:?}"); - } - } - } - } - - #[test] - fn preview_feathers_the_linked_mask() { - // A feathered pixel mask without a vector mask: the compositor softens the edge at x 16, - // so the moving texels must be soft there too, not hard until the commit (#4560). - let mut app = masked_app(true); - app.session - .edit("feather", |doc, a| { - doc.layer_mut(a.unwrap()).unwrap().mask.as_mut().unwrap().feather = 4.0; - Ok(()) - }) - .unwrap(); - let st = app.session.active().unwrap(); - let id = st.active_layer.unwrap(); - let b = photocraft_geom::Rect::new(8, 8, 24, 24); - let (img, _) = preview_image(&st.doc, id, None, b, 4096, false); - // Texel x 7 = doc x 15, just inside the hidden half; texel x 8 = doc x 16, just revealed. - assert!(texel_alpha(&img, 7, 4) > 0, "the feather reaches into the hidden side"); - assert!(texel_alpha(&img, 8, 4) < 255, "the feather reaches into the revealed side"); - // The same values the compositor masks the committed layer with. - let m = photocraft_compose::masks::combined_mask(st.doc.layer(id).unwrap(), b).unwrap(); - for x in [6usize, 7, 8, 9, 15] { - let want = (m.sample_channel(8 + x as i32, 12, 0) * 255.0).round() as i32; - assert!((i32::from(texel_alpha(&img, x, 4)) - want).abs() <= 1, "texel {x}"); - } - } - - /// #5239: a smart object clipped to the layer under it previewed as nothing while the box - /// was open (its flattened render hid the clipping base too). - #[test] - fn preview_of_a_clipped_smart_object_is_not_empty() { - let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); - 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(0, 0, 64, 64), &[0.0, 0.0, 1.0, 1.0]); - Ok(()) - }) - .unwrap(); - app.session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - app.session.execute("layer.createClippingMask", json!({})).unwrap(); - let st = app.session.active().unwrap(); - let id = st.active_layer.unwrap(); - assert!(st.doc.layer(id).unwrap().clipped); - let (img, _) = preview_image(&st.doc, id, None, photocraft_geom::Rect::new(0, 0, 64, 64), 4096, false); - assert_eq!(texel_alpha(&img, 32, 32), 255, "the moving object shows"); - } - - #[test] - fn targeted_unlinked_mask_transforms_alone_through_the_box() { - let mut app = masked_app(false); - app.ui.mask_target = true; - let ctx = egui::Context::default(); - begin(&mut app, &ctx).unwrap(); - let t = app.ui.transform.as_ref().unwrap(); - assert_eq!(t.target, Some(json!("mask"))); - assert_eq!(t.rect, [0.0, 0.0, 16.0, 64.0], "the box frames the mask's content"); - // The preview document shows the mask vacated (revealed). - let pd = &app.transform_preview.as_ref().unwrap().doc; - assert!(pd.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(4, 4, 0) > 0.99); - // Move the box 20 px right and commit. - let t = app.ui.transform.as_mut().unwrap(); - t.quad = t.quad.map(|[x, y]| [x + 20.0, y]); - commit(&mut app); - assert!(!app.ui.status_error, "{}", app.ui.status); - let st = app.session.active().unwrap(); - let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); - let m = &l.mask.as_ref().unwrap().surface; - assert!(m.sample_channel(4, 30, 0) > 0.99 && m.sample_channel(30, 30, 0) < 0.01, "mask moved 20 px right"); - assert_eq!(l.surface().unwrap().content_bounds(), photocraft_geom::Rect::new(8, 8, 24, 24), "pixels untouched"); - // Warp mode doesn't apply to a lone mask. - app.ui.mask_target = true; - begin(&mut app, &ctx).unwrap(); - enter_warp(&mut app, &egui::Context::default()); - assert!(app.ui.transform.as_ref().unwrap().warp.is_none()); - } - - #[test] - fn linked_mask_target_transforms_the_layer() { - let mut app = masked_app(true); - app.ui.mask_target = true; - let ctx = egui::Context::default(); - begin(&mut app, &ctx).unwrap(); - assert_eq!(app.ui.transform.as_ref().unwrap().target, None); - assert_eq!(app.ui.transform.as_ref().unwrap().rect, [8.0, 8.0, 24.0, 24.0]); - } - - /// ⌘T with Path Selection and a path transforms the path, not the layer's pixels, as one - /// undoable step; it works on the Background too. - #[test] - fn free_transform_moves_the_selected_path_not_pixels() { - let ctx = egui::Context::default(); - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": true, "knots": [[10, 10], [30, 10], [30, 20], [10, 20]]}]}})).unwrap(); - app.ui.tool = Tool::PathSelection; - assert!(crate::menus::is_enabled(&app, "edit.freeTransform"), "a path is transformable on the Background"); - let pixels = app.session.active().unwrap().doc.layers[0].surface().cloned(); - let steps = app.session.active().unwrap().history.past_len(); - crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); - let t = app.ui.transform.as_mut().unwrap(); - assert_eq!(t.rect, [10.0, 10.0, 30.0, 20.0], "the box frames the path"); - assert_eq!(t.path, Some(json!({"name": "work"}))); - // Twice as wide and 5 px down. - t.quad = [[10.0, 15.0], [50.0, 15.0], [50.0, 25.0], [10.0, 25.0]]; - commit(&mut app); - let st = app.session.active().unwrap(); - assert_eq!(st.history.past_len(), steps + 1, "one step"); - let wp = st.doc.work_path.as_ref().unwrap(); - let anchors: Vec<[f64; 2]> = wp.subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); - assert_eq!(anchors, vec![[10.0, 15.0], [50.0, 15.0], [50.0, 25.0], [10.0, 25.0]]); - assert_eq!(st.doc.layers[0].surface().cloned(), pixels, "the pixels stay put"); - - // ⌘-drag of a corner (Distort) maps the path onto the box (#3027): one step. - crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); - app.ui.transform.as_mut().unwrap().quad[2] = [70.0, 40.0]; - commit(&mut app); - let st = app.session.active().unwrap(); - assert_eq!(st.history.past_len(), steps + 2, "one step: {}", app.ui.status); - let anchors: Vec<[f64; 2]> = st.doc.work_path.as_ref().unwrap().subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); - let want = [[10.0, 15.0], [50.0, 15.0], [70.0, 40.0], [10.0, 25.0]]; - assert!(anchors.iter().zip(want).all(|(a, b)| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9), "{anchors:?}"); - - // Edit › Transform Path › Warp bends it: one more step. - crate::menus::invoke(&mut app, &ctx, "edit.transform.warp", json!({})).unwrap(); - let t = app.ui.transform.as_mut().unwrap(); - assert!(t.warp.is_some(), "Warp mode on a path"); - t.warp = Some(Warp { style: WarpStyle::Arc, bend: 50.0, ..Warp::none(t.rect) }); - commit(&mut app); - let st = app.session.active().unwrap(); - assert_eq!(st.history.past_len(), steps + 3, "one step: {}", app.ui.status); - assert!(st.doc.work_path.as_ref().unwrap().subpaths[0].knots.len() > 4, "the warp bends the edges"); - - // Without a path tool, ⌘T is the pixel transform again. - app.ui.tool = Tool::Move; - app.run("layer.new.layer", json!({})).unwrap(); - assert!(crate::vector_ui::free_transform_path(&app).is_none()); - } - - /// Edit › Transform › Warp on editable type (#3004), as in Photoshop: no rasterize prompt, no - /// mesh to drag, only the warp styles; the commit is the type's own Warp Text, one step, and - /// the layer stays type. - #[test] - fn warp_on_type_takes_a_style_and_keeps_the_type_editable() { - let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); - app.sync_views(); - app.run("type.create", json!({"x": 10, "y": 60, "text": "Hello"})).unwrap(); - let ctx = egui::Context::default(); - let past = |app: &PhotocraftApp| app.session.active().unwrap().history.past_len(); - let before = past(&app); - crate::menus::invoke(&mut app, &ctx, "edit.transform.warp", json!({})).unwrap(); - assert!(app.ui.dialogs.is_empty(), "no prompt"); - let w0 = app.ui.transform.as_ref().and_then(|t| t.warp.clone()).expect("Warp mode"); - assert_eq!(w0.style, WarpStyle::None); - // A drag on the grid changes nothing: type takes only the styles. - let c = [(w0.bounds[0] + w0.bounds[2]) / 2.0, (w0.bounds[1] + w0.bounds[3]) / 2.0]; - warp_pointer(&mut app, ToolEvent::Down { x: w0.bounds[2], y: w0.bounds[3], pressure: 1.0 }, 4.0, egui::Modifiers::NONE); - warp_pointer(&mut app, ToolEvent::Up { x: w0.bounds[2] + 20.0, y: w0.bounds[3] + 15.0 }, 4.0, egui::Modifiers::NONE); - warp_pointer(&mut app, ToolEvent::Down { x: c[0], y: c[1], pressure: 1.0 }, 4.0, egui::Modifiers::NONE); - warp_pointer(&mut app, ToolEvent::Up { x: c[0], y: c[1] + 20.0 }, 4.0, egui::Modifiers::NONE); - assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref(), Some(&w0)); - assert!(split(&mut app, "edit.transform.splitWarpCrosswise", None).is_err()); - // Pick Flag in the options bar, then Enter. - if let Some(w) = app.ui.transform.as_mut().and_then(|t| t.warp.as_mut()) { - *w = Warp { style: WarpStyle::Flag, bend: 40.0, ..Warp::none(w.bounds) }; - } - commit(&mut app); - assert!(!app.ui.status_error, "{}", app.ui.status); - let st = app.session.active().unwrap(); - let LayerContent::Text(t) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("still type") }; - let tw = t.warp.as_ref().expect("Warp Text set"); - assert_eq!((tw.style.as_str(), tw.value, tw.horizontal), ("warpFlag", 40.0, true)); - assert_eq!(past(&app), before + 1, "one history step"); - // Warp again shows Flag; None takes it off in one more step. - begin_warp(&mut app, &ctx).unwrap(); - assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().style, WarpStyle::Flag); - if let Some(t) = app.ui.transform.as_mut() { - t.warp = Some(Warp::none(t.rect)); - } - commit(&mut app); - let st = app.session.active().unwrap(); - assert!(matches!(&st.doc.layer(st.active_layer.unwrap()).unwrap().content, LayerContent::Text(t) if t.warp.is_none())); - assert_eq!(past(&app), before + 2); - } - - #[test] - fn anchor_grid_point_on_quad_and_carry_pivot() { - let quad = [[0.0, 0.0], [100.0, 0.0], [100.0, 50.0], [0.0, 50.0]]; - assert_eq!(point_on_quad(quad, 0), [0.0, 0.0]); - assert_eq!(point_on_quad(quad, 1), [50.0, 0.0]); - assert_eq!(point_on_quad(quad, 2), [100.0, 0.0]); - assert_eq!(point_on_quad(quad, 3), [0.0, 25.0]); - assert_eq!(point_on_quad(quad, 4), [50.0, 25.0]); - assert_eq!(point_on_quad(quad, 5), [100.0, 25.0]); - assert_eq!(point_on_quad(quad, 6), [0.0, 50.0]); - assert_eq!(point_on_quad(quad, 7), [50.0, 50.0]); - assert_eq!(point_on_quad(quad, 8), [100.0, 50.0]); - - let quad_scaled = [[0.0, 0.0], [200.0, 0.0], [200.0, 100.0], [0.0, 100.0]]; - let p_top_right = carry_pivot(quad, quad_scaled, [100.0, 0.0]); - assert_eq!(p_top_right, [200.0, 0.0]); - let p_center = carry_pivot(quad, quad_scaled, [50.0, 25.0]); - assert_eq!(p_center, [100.0, 50.0]); - - for anchor in 0..9 { - assert_eq!(matching_anchor(quad, point_on_quad(quad, anchor)), Some(anchor)); - } - assert_eq!(matching_anchor(quad, [12.3, 45.6]), None); - assert_eq!(matching_anchor(quad, [50.0, 30.0]), None); - } -} +mod tests; diff --git a/crates/ui-egui/src/transform_tool/tests.rs b/crates/ui-egui/src/transform_tool/tests.rs new file mode 100644 index 0000000000..d4f2de642a --- /dev/null +++ b/crates/ui-egui/src/transform_tool/tests.rs @@ -0,0 +1,3004 @@ +use super::*; + +fn session() -> TransformSession { + TransformSession { + session: 1, + layer: 1, + rect: [0.0, 0.0, 100.0, 50.0], + quad: corners([0.0, 0.0, 100.0, 50.0]), + pivot: [50.0, 25.0], + interpolation: "bicubic".into(), + warp: None, + selection: false, + target: None, + path: None, + made: None, + mode: Default::default(), + content_aware: None, + skew_v: 0.0, + } +} + +#[test] +fn a_plain_click_far_outside_accepts_transform_but_a_rotation_drag_does_not() { + let context = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + begin(&mut app, &context).unwrap(); + let before = app.session.active().unwrap().history.past_len(); + let t = app.ui.transform.as_mut().unwrap(); + t.quad = t.quad.map(|[x, y]| [x + 6.0, y]); + let outside = [44.0, 44.0]; + let none = egui::Modifiers::NONE; + assert!(pointer(&mut app, ToolEvent::Down { x: outside[0], y: outside[1], pressure: 1.0 }, none)); + assert!(app.ui.transform.is_some(), "press alone does not accept"); + assert!(pointer(&mut app, ToolEvent::Up { x: outside[0], y: outside[1] }, none)); + assert!(app.ui.transform.is_none(), "a release without a drag commits"); + assert_eq!(app.session.active().unwrap().history.past_len(), before + 1, "one undo step for the transform"); + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert_eq!(layer.surface().unwrap().content_bounds(), photocraft_geom::Rect::new(14, 8, 30, 24)); + + // An outside drag remains a rotation gesture; releasing it does not commit. + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + begin(&mut app, &context).unwrap(); + let start = [44.0, 44.0]; + let end = [44.0, 54.0]; + let original = app.ui.transform.as_ref().unwrap().quad; + pointer(&mut app, ToolEvent::Down { x: start[0], y: start[1], pressure: 1.0 }, none); + pointer(&mut app, ToolEvent::Move { x: end[0], y: end[1], pressure: 1.0 }, none); + pointer(&mut app, ToolEvent::Up { x: end[0], y: end[1] }, none); + assert!(app.ui.transform.is_some(), "rotation stays active after an outside drag"); + assert_ne!(app.ui.transform.as_ref().unwrap().quad, original); +} + +#[test] +fn a_click_near_rotation_handles_accepts_but_drags_and_option_pivot_do_not() { + let t = session(); + let tol = 12.0; + let near = Gesture { hit: Hit::Outside, start: [-18.0, -18.0], quad0: t.quad, pivot0: t.pivot }; + assert!(accepts_outside_click(near, near.start, tol), "a click in the rotation zone accepts; a drag still rotates"); + let far = Gesture { start: [500.0, 500.0], ..near }; + assert!(accepts_outside_click(far, far.start, tol)); + assert!(!accepts_outside_click(far, [512.0, 500.0], tol), "drag does not commit"); + let handle = Gesture { hit: Hit::Corner(0), ..near }; + assert!(!accepts_outside_click(handle, handle.start, tol), "resize handles stay interactive"); + + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + begin(&mut app, &egui::Context::default()).unwrap(); + let p = [44.0, 44.0]; + pointer(&mut app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, egui::Modifiers::ALT); + pointer(&mut app, ToolEvent::Up { x: p[0], y: p[1] }, egui::Modifiers::ALT); + assert!(app.ui.transform.is_some(), "Option-click moves the pivot, never accepts"); + assert_eq!(app.ui.transform.as_ref().unwrap().pivot, p); +} + +#[test] +fn rotate_feedback_only_appears_just_outside_corners() { + let mut t = session(); + assert!(near_rotate_corner(&t, [-18.0, -18.0], 12.0)); + assert!(!near_rotate_corner(&t, [50.0, 25.0], 12.0), "inside moves the box"); + assert!(!near_rotate_corner(&t, [500.0, 500.0], 12.0), "far outside stays generic"); + assert!(!near_rotate_corner(&t, [2.0, 2.0], 12.0), "corner handle resizes"); + t.mode = TransformMode::Distort; + assert!(!near_rotate_corner(&t, [-18.0, -18.0], 12.0)); +} + +#[test] +fn angle_readout_tracks_rotated_quad_and_handles_degenerate_edges() { + let mut t = session(); + assert_eq!(rotation_degrees(t.quad), 0.0); + let pivot = t.pivot; + t.quad = t.quad.map(|q| [pivot[0] - (q[1] - pivot[1]), pivot[1] + (q[0] - pivot[0])]); + assert!((rotation_degrees(t.quad) - 90.0).abs() < 1e-9); + t.quad[1] = t.quad[0]; + assert_eq!(rotation_degrees(t.quad), 0.0); +} + +#[test] +fn transform_bar_pins_warp_cancel_and_commit() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.transform = Some(session()); + let width = 720.0; + let mut h = Harness::builder().with_size(vec2(width, 48.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + ui.horizontal_centered(|ui| options_bar(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(6); + let commit = h.get_by_label("Commit transform").rect(); + let cancel = h.get_by_label("Cancel transform").rect(); + let mode = h.get_by_label("Switch between free transform and warp modes").rect(); + assert!(commit.right() > width - 36.0, "commit sits on the right: {commit:?}"); + assert!(cancel.right() < commit.left() + 1.0, "cancel is left of commit"); + assert!(mode.right() < cancel.left() + 1.0, "warp switch is left of cancel"); + h.get_by_label("Switch between free transform and warp modes").click(); + h.run_steps(2); + assert!(h.state().ui.transform.as_ref().unwrap().warp.is_some()); + h.get_by_label("Switch between free transform and warp modes").click(); + h.run_steps(2); + assert!(h.state().ui.transform.as_ref().unwrap().warp.is_none()); + h.get_by_label("Cancel transform").click(); + h.run_steps(2); + assert!(h.state().ui.transform.is_none()); +} + +#[test] +fn free_transform_bar_buttons_follow_the_fields_on_a_wide_bar() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.transform = Some(session()); + let width = 2400.0; + let mut h = Harness::builder().with_size(vec2(width, 48.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + ui.horizontal_centered(|ui| options_bar(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(6); + let commit = h.get_by_label("Commit transform").rect(); + assert!(commit.right() < width * 0.7, "commit sits next to the fields, not at the far right: {commit:?}"); +} + +#[test] +fn warp_bar_buttons_follow_the_fields_on_a_wide_bar() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.transform = Some(session()); + let width = 2000.0; + let mut h = Harness::builder().with_size(vec2(width, 48.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + ui.horizontal_centered(|ui| options_bar(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(6); + h.get_by_label("Switch between free transform and warp modes").click(); + h.run_steps(4); + assert!(h.state().ui.transform.as_ref().unwrap().warp.is_some()); + let commit = h.get_by_label("Commit transform").rect(); + assert!(commit.right() < width / 2.0, "commit sits next to the fields, not at the far right: {commit:?}"); + let reset = h.get_by_label("Reset warp").rect(); + assert!(reset.right() < commit.left() + 1.0, "reset is left of commit"); + h.get_by_label("Reset warp").click(); + h.run_steps(2); + assert!(h.state().ui.transform.as_ref().unwrap().warp.as_ref().unwrap().is_identity()); +} + +fn eq6(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +/// Scale, skew and rotation read back exactly from the box they make, flips included. +#[test] +fn parts_round_trip() { + for (sx, sy, angle, h, v) in [(1.0, 1.0, 0.0, 0.0, 0.0), (1.5, 0.5, 30.0, 20.0, 0.0), (0.8, -1.2, -120.0, -35.0, 15.0), (2.0, 1.0, 179.0, 0.0, -60.0)] { + let p = Parts { sx, sy, angle: f64::to_radians(angle), skew_h: f64::to_radians(h), skew_v: f64::to_radians(v) }; + let back = Parts::from_columns(p.columns_of(), p.skew_v); + for (a, b) in [(back.sx, p.sx), (back.sy, p.sy), (back.angle, p.angle), (back.skew_h, p.skew_h)] { + assert!(eq6(a, b), "{p:?} read back as {back:?}"); + } + } +} + +/// A box sheared sideways keeps W, H and the angle; only H skew moves (it used to read as a +/// taller box). +#[test] +fn a_sheared_box_reads_as_horizontal_skew() { + let mut t = session(); + // The 100×50 frame with its bottom slid 50·tan 20° to the left: a positive H skew. + let d = 50.0 * 20f64.to_radians().tan(); + t.quad = [[0.0, 0.0], [100.0, 0.0], [100.0 - d, 50.0], [-d, 50.0]]; + let (w, h, angle, skew) = readout(&t); + assert!(eq6(w, 100.0) && eq6(h, 100.0) && eq6(angle, 0.0), "{w} {h} {angle}"); + assert!(eq6(skew, 20.0), "{skew}"); +} + +/// The test box flipped horizontally and vertically, as Edit › Transform › Flip leaves it. +const FLIPPED_H: [[f64; 2]; 4] = [[100.0, 0.0], [0.0, 0.0], [0.0, 50.0], [100.0, 50.0]]; +const FLIPPED_V: [[f64; 2]; 4] = [[0.0, 50.0], [100.0, 50.0], [100.0, 0.0], [0.0, 0.0]]; + +/// Photoshop puts a flip's minus on the flipped axis and keeps the angle at 0: Flip Horizontal +/// reads W -100 %, Flip Vertical H -100 % (it read 180° and nothing at all). +#[test] +fn a_flipped_box_reads_as_a_negative_scale_on_that_axis() { + let mut t = session(); + for (quad, want) in [(FLIPPED_H, (-100.0, 100.0)), (FLIPPED_V, (100.0, -100.0))] { + t.quad = quad; + let (w, h, angle, skew) = readout(&t); + assert!(eq6(w, want.0) && eq6(h, want.1) && eq6(angle, 0.0) && eq6(skew, 0.0), "{quad:?}: {w} {h} {angle} {skew}"); + } + // Flipped both ways is a half turn, not a mirror. + t.quad = [[100.0, 50.0], [0.0, 50.0], [0.0, 0.0], [100.0, 0.0]]; + let (w, h, angle, _) = readout(&t); + assert!(eq6(w, 100.0) && eq6(h, 100.0) && eq6(angle.abs(), 180.0), "{w} {h} {angle}"); +} + +/// The bar's fields act on a flipped box without undoing the flip: angle 0 keeps it as it is, +/// and a typed W scales it and keeps it mirrored. +#[test] +fn bar_fields_keep_a_flipped_box_flipped() { + let flip_h = |app: &mut PhotocraftApp| app.ui.transform.as_mut().unwrap().quad = FLIPPED_H; + let t = type_into_bar_field_with(flip_h, 4, "0"); + assert!(t.quad.iter().flatten().zip(FLIPPED_H.iter().flatten()).all(|(a, b)| eq6(*a, *b)), "{:?}", t.quad); + let t = type_into_bar_field_with(flip_h, 2, "-50"); + let (w, h, angle, _) = readout(&t); + assert!(eq6(w, -50.0) && eq6(h, 50.0) && eq6(angle, 0.0), "{w} {h} {angle}"); + assert!(eq6(t.quad[0][0] - t.quad[1][0], 50.0), "50 px wide, still mirrored: {:?}", t.quad); + let flip_v = |app: &mut PhotocraftApp| app.ui.transform.as_mut().unwrap().quad = FLIPPED_V; + let t = type_into_bar_field_with(flip_v, 3, "-200"); + let (w, h, _, _) = readout(&t); + assert!(eq6(w, 200.0) && eq6(h, -200.0), "{w} {h}"); +} + +/// Typing H and V skews leans the box about the reference point; the angle, W and H fields keep +/// their values, and V stays as typed. +#[test] +fn skew_fields_lean_the_box_about_the_reference_point() { + let t = type_into_bar_field(5, "20"); + let (w, h, angle, skew) = readout(&t); + assert!(eq6(skew, 20.0) && eq6(angle, 0.0) && eq6(w, 100.0) && eq6(h, 100.0), "{w} {h} {angle} {skew}"); + // The pivot (50, 25) stays put: the top edge slid right, the bottom left, by the same amount. + let d = 25.0 * 20f64.to_radians().tan(); + assert!(eq6(t.quad[0][0], d) && eq6(t.quad[0][1], 0.0) && eq6(t.quad[3][0], -d) && eq6(t.quad[3][1], 50.0), "{:?}", t.quad); + + let t = type_into_bar_field(6, "-10"); + assert!(eq6(t.skew_v, -10.0)); + let (w, h, angle, skew) = readout(&t); + assert!(eq6(skew, 0.0) && eq6(angle, 0.0) && eq6(w, 100.0) && eq6(h, 100.0), "{w} {h} {angle} {skew}"); + // The right side rose: tan(−10°) per pixel across, about the pivot. + let d = 50.0 * (-10f64).to_radians().tan(); + assert!(eq6(t.quad[1][1], d) && eq6(t.quad[0][1], -d), "{:?}", t.quad); + // A skew past ±90° would flatten the box: the field stops at the limit. + let t = type_into_bar_field(5, "120"); + assert!(eq6(readout(&t).3, f64::from(SKEW_LIMIT_DEG)), "{}", readout(&t).3); +} + +/// Types `text` + Enter into the `n`th numeric field of the transform bar (X, Y, W, H, angle…). +fn type_into_bar_field(n: usize, text: &str) -> TransformSession { + type_into_bar_field_with(|_| {}, n, text) +} + +/// The transform bar over the test box, after `setup` (e.g. picking the W/H unit). Tall enough +/// for the fields' unit menu to open below the bar unscrolled. +fn bar_harness(setup: impl FnOnce(&mut PhotocraftApp)) -> egui_kittest::Harness<'static, PhotocraftApp> { + use egui_kittest::Harness; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.transform = Some(session()); + setup(&mut app); + let mut h = Harness::builder().with_size(vec2(900.0, 360.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + ui.horizontal_centered(|ui| options_bar(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(6); + h +} + +/// [`type_into_bar_field`] after `setup`. +fn type_into_bar_field_with(setup: impl FnOnce(&mut PhotocraftApp), n: usize, text: &str) -> TransformSession { + use egui_kittest::kittest::Queryable; + let mut h = bar_harness(setup); + h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(n).unwrap().click(); + h.run(); + for c in text.chars() { + h.event(egui::Event::Text(c.to_string())); + h.run(); + } + h.key_press(egui::Key::Enter); + h.run_steps(2); + h.state().ui.transform.clone().unwrap() +} + +/// The values the W and H fields show (the 3rd and 4th numeric fields). +fn shown_size(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> Vec { + use egui_kittest::kittest::{NodeT, Queryable}; + h.get_all_by_role(egui::accesskit::Role::SpinButton).skip(2).take(2).map(|n| n.accesskit_node().value().unwrap_or_default().to_string()).collect() +} + +#[test] +fn size_fields_convert_between_percent_and_lengths() { + use crate::layer_props_ui::LenUnit; + use photocraft_engine::prefs::Unit; + // A 300 px side at 300 ppi is one inch at 100 %. + let at = |unit| LenUnit { unit, dpi: 300.0, ppi: 72.0 }; + for (unit, at_100) in [ + (Unit::Percent, 100.0), + (Unit::Pixels, 300.0), + (Unit::Inches, 1.0), + (Unit::Centimeters, 2.54), + (Unit::Millimeters, 25.4), + (Unit::Points, 72.0), + (Unit::Picas, 6.0), + ] { + let u = at(unit); + let shown = size_shown(&u, 100.0, 300.0); + assert!((f64::from(shown) - at_100).abs() < 1e-3, "{unit:?}: {shown}"); + assert!((size_shown(&u, 150.0, 300.0) - shown * 1.5).abs() < 1e-3, "{unit:?} scales with the box"); + assert!((size_pct(&u, shown * 2.0, 300.0) - 200.0).abs() < 1e-3, "{unit:?}: twice the length is 200 %"); + assert!((size_pct(&u, -shown, 300.0) + 100.0).abs() < 1e-3, "{unit:?}: a negative length flips"); + } + // A degenerate side never divides by zero. + assert!(size_pct(&at(Unit::Inches), 1.0, 0.0).is_finite()); +} + +#[test] +fn w_and_h_take_lengths_in_the_unit_picked_for_them() { + use photocraft_engine::prefs::Unit; + // The test box is 100 × 50 px; with no document open, lengths convert at 72 ppi. + let cm = |app: &mut PhotocraftApp| set_size_unit(app, Unit::Centimeters.name()); + let h = bar_harness(cm); + assert_eq!(shown_size(&h), ["3.53", "1.76"], "the box's size in cm, not 100 %"); + // 7.06 cm is twice the width; linked, the height follows. + let t = type_into_bar_field_with(cm, 2, "7.06"); + let (sx, sy, _, _) = readout(&t); + assert!((sx - 200.0).abs() < 0.2 && (sy - 200.0).abs() < 0.2, "{sx} {sy}"); + // Pixels: an exact width. + let t = type_into_bar_field_with(|app| set_size_unit(app, Unit::Pixels.name()), 2, "250"); + assert!((t.quad[1][0] - t.quad[0][0] - 250.0).abs() < 0.01, "{:?}", t.quad); + // Percent is still the default. + assert_eq!(shown_size(&bar_harness(|_| {})), ["100", "100"]); +} + +/// Opens a document at `dpi` so the W/H fields convert typed lengths at its resolution. +fn at_dpi(app: &mut PhotocraftApp, dpi: f32) { + app.session.execute("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.session + .edit("resolution", |doc, _| { + doc.resolution_dpi = dpi; + Ok(()) + }) + .unwrap(); +} + +/// The box's width and height in px after a W/H edit. +fn box_size(t: &TransformSession) -> (f64, f64) { + (t.quad[1][0] - t.quad[0][0], t.quad[3][1] - t.quad[0][1]) +} + +#[test] +fn w_and_h_in_percent_take_a_typed_length() { + use photocraft_engine::prefs::Unit; + let near = |a: f64, b: f64| (a - b).abs() < 0.01; + // The 100 × 50 px box with W/H showing percent (#6284): a typed length is the box's new side. + for (text, px) in + [("40px", 40.0), ("40 px", 40.0), ("2in", 600.0), ("2 in", 600.0), ("5cm", 5.0 / 2.54 * 300.0), ("25.4mm", 300.0), ("72pt", 300.0), ("1pica", 50.0)] + { + // Linked: the height follows the width. + let t = type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, text); + let (w, h) = box_size(&t); + assert!(near(w, px) && near(h, px / 2.0), "{text} linked: {w} × {h}"); + // Unlinked: only the width changes. + let t = type_into_bar_field_with( + |app| { + at_dpi(app, 300.0); + app.ui.transform_unlinked = true; + }, + 2, + text, + ); + let (w, h) = box_size(&t); + assert!(near(w, px) && near(h, 50.0), "{text} unlinked: {w} × {h}"); + } + // H takes a length too; linked, the width follows. + let t = type_into_bar_field_with(|app| at_dpi(app, 300.0), 3, "1in"); + let (w, h) = box_size(&t); + assert!(near(w, 600.0) && near(h, 300.0), "H 1in: {w} × {h}"); + // A plain number is still the percentage. + let (w, _) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "40")); + assert!(near(w, 40.0), "40 is 40 % of 100 px: {w}"); + // A percentage typed into a length field is that share of the box's original side. + let px = |app: &mut PhotocraftApp| { + at_dpi(app, 300.0); + set_size_unit(app, Unit::Pixels.name()); + }; + let (w, h) = box_size(&type_into_bar_field_with(px, 2, "50%")); + assert!(near(w, 50.0) && near(h, 25.0), "50% in px: {w} × {h}"); + let inches = |app: &mut PhotocraftApp| { + at_dpi(app, 300.0); + set_size_unit(app, Unit::Inches.name()); + }; + let (w, h) = box_size(&type_into_bar_field_with(inches, 3, "300%")); + assert!(near(w, 300.0) && near(h, 150.0), "300% in inches: {w} × {h}"); +} + +#[test] +fn w_and_h_reject_or_clamp_hostile_typed_lengths() { + let near = |a: f64, b: f64| (a - b).abs() < 0.01; + // Text that is no number leaves the box alone. + for text in ["px", "in", "NaN", "%"] { + let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, text)); + assert!(near(w, 100.0) && near(h, 50.0), "{text}: {w} × {h}"); + } + // Invalid text after a number keeps only what applied while typing (a plain number applies + // per keystroke), never a NaN or a box past the largest document. + for text in ["1in/0", "1e400px", "2 inches", "1e308in"] { + let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, text)); + assert!(w.is_finite() && h.is_finite() && w.abs() <= f64::from(POSITION_LIMIT_PX) + 0.01, "{text}: {w} × {h}"); + } + // A huge length stops at the field's limit: the box stays within the largest document. + let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "1e9in")); + assert!(w.is_finite() && w <= f64::from(POSITION_LIMIT_PX) + 0.01 && h <= f64::from(POSITION_LIMIT_PX), "{w} × {h}"); + // A negative length flips, as a negative percentage does. + let (w, _) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "-40px")); + assert!(near(w, -40.0), "{w}"); + // Zero collapses the side without dividing by zero. + let (w, h) = box_size(&type_into_bar_field_with(|app| at_dpi(app, 300.0), 2, "0px")); + assert!(w.is_finite() && h.is_finite(), "{w} × {h}"); +} + +#[test] +fn right_clicking_w_or_h_picks_their_unit_and_remembers_it() { + use egui_kittest::kittest::Queryable; + let mut h = bar_harness(|_| {}); + h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(2).unwrap().click_secondary(); + h.run_steps(2); + h.get_by_label("Inches").click(); + h.run_steps(3); + assert_eq!(size_unit(h.state()).unit, photocraft_engine::prefs::Unit::Inches); + assert_eq!(h.state().session.prefs().dialogs[SIZE_UNIT_KEY]["sizeUnit"], "inches"); + assert_eq!(shown_size(&h), ["1.389", "0.694"], "100 × 50 px at 72 ppi"); + // H opens the same menu, with the current unit checked. + h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(3).unwrap().click_secondary(); + h.run_steps(2); + assert!(h.query_by_label("✓ Inches").is_some(), "the current unit is checked"); + h.get_by_label("Percent").click(); + h.run_steps(3); + assert_eq!(shown_size(&h), ["100", "100"]); + // A hand-edited or stale preference falls back to Percent instead of failing. + h.state_mut().session.prefs.edit(|p| { + p.dialogs.insert(SIZE_UNIT_KEY.into(), json!({"sizeUnit": "furlongs"})); + }); + assert_eq!(size_unit(h.state()).unit, photocraft_engine::prefs::Unit::Percent); + h.state_mut().session.prefs.edit(|p| { + p.dialogs.insert(SIZE_UNIT_KEY.into(), json!("not an object")); + }); + assert_eq!(size_unit(h.state()).unit, photocraft_engine::prefs::Unit::Percent); + set_size_unit(h.state_mut(), "points"); + assert_eq!(size_unit(h.state()).unit, photocraft_engine::prefs::Unit::Points, "a bad entry is replaced, not kept"); +} + +#[test] +fn editing_the_contents_of_a_dropped_file_keeps_the_layer() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + + app.session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + app.sync_views(); + + app.session.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); + app.sync_views(); + + let parent_id = app.session.active().unwrap().doc.id; + let placed_layer = app.session.active().unwrap().active_layer.unwrap(); + + begin_placed(&mut app, &egui::Context::default()).unwrap(); + + app.session.execute("layer.smartObjects.editContents", json!({})).unwrap(); + + assert_ne!(app.session.active().unwrap().doc.id, parent_id, "Edit Contents should activate the child document"); + + end_if_left(&mut app); + + let parent = app.session.documents().iter().find(|st| st.doc.id == parent_id); + + assert!(parent.is_some_and(|st| st.doc.layer(placed_layer).is_some()), "the placed Smart Object must remain in the parent document"); + assert!(app.ui.transform.is_none(), "the transform session should end"); + assert!(app.transform_preview.is_none(), "the transform preview should end"); +} + +/// Polls the app's background jobs until they have all landed. +fn land_jobs(app: &mut PhotocraftApp) { + let ctx = egui::Context::default(); + for _ in 0..2000 { + crate::jobs_ui::tick(app, &ctx); + if !app.session.has_jobs() { + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("the background jobs never landed"); +} + +/// A smart object placed the way a dropped file is (the last step made it), in Free Transform +/// and moved 8 px right, with commits running in the background as in the desktop app: +/// (app, the placed layer, its frame before the move, history steps before the place). +fn moved_place() -> (PhotocraftApp, LayerId, photocraft_geom::Rect, usize) { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let steps = app.session.active().unwrap().history.past_len(); + app.session.execute("layer.duplicate", json!({"inPlace": true})).unwrap(); + app.sync_views(); + let st = app.session.active().unwrap(); + let placed = st.active_layer.unwrap(); + let frame = photocraft_engine::transform_cmds::transform_frame(&st.doc, st.doc.layer(placed).unwrap()); + begin_placed(&mut app, &egui::Context::default()).unwrap(); + let t = app.ui.transform.as_mut().unwrap(); + t.quad = t.quad.map(|[x, y]| [x + 8.0, y]); + app.background_jobs = true; + (app, placed, frame, steps) +} + +fn frame_of(app: &PhotocraftApp, layer: LayerId) -> Option { + let st = app.session.active()?; + Some(photocraft_engine::transform_cmds::transform_frame(&st.doc, st.doc.layer(layer)?)) +} + +/// #5665: picking another tool or selecting another layer while a dropped file is in Free +/// Transform applies the transform when the commit runs in the background too. Ending the +/// box used to cancel that commit, which took the dropped file back (or left a transformed +/// layer where it was). +#[test] +fn another_tool_or_layer_applies_a_transform_committed_in_the_background() { + for by_layer in [false, true] { + let (mut app, placed, frame, steps) = moved_place(); + if by_layer { + let below = app.session.active().unwrap().doc.layers.iter().map(|l| l.id).find(|id| *id != placed).unwrap(); + app.run("layer.select", json!({"layer": below.0})).unwrap(); + } else { + app.ui.tool = if app.ui.tool == Tool::Brush { Tool::Move } else { Tool::Brush }; + } + end_if_left(&mut app); + assert!(committing(&app).is_some(), "the commit runs in the background"); + land_jobs(&mut app); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "the box ended"); + assert_eq!(frame_of(&app, placed), Some(frame.translate(8, 0)), "the dropped file stays, moved (by layer: {by_layer})"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), steps + 1, "the place and its move are one step"); + assert_eq!(st.history.undo_label(), Some(photocraft_engine::file_cmds::PLACE_EMBEDDED)); + } +} + +/// #5667: New Layer while a dropped file is in Free Transform applies the transform first. When +/// the commit runs in the background the command is refused until it has landed, then runs: the +/// place (which takes the move into its step) and the new layer each stay their own step, in +/// that order. +#[test] +fn new_layer_applies_the_open_transform() { + let (mut app, placed, frame, steps) = moved_place(); + let layers = app.session.active().unwrap().doc.layers.len(); + let err = app.run("layer.new.layer", json!({})).unwrap_err(); + assert!(err.contains("Free Transform is still being applied"), "refused while the commit runs: {err}"); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "no layer yet"); + land_jobs(&mut app); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "the box ended"); + assert_eq!(frame_of(&app, placed), Some(frame.translate(8, 0)), "applied as it showed, not the original"); + app.run("layer.new.layer", json!({})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers.len(), layers + 1); + assert_eq!(st.history.past_len(), steps + 2, "the place with its move, then New Layer"); + assert_eq!(st.history.undo_label(), Some("New Layer")); + app.session.undo(); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "one undo takes back the new layer"); + assert_eq!(frame_of(&app, placed), Some(frame.translate(8, 0)), "the transform stays"); +} + +/// #5665, the report's second case through the UI with background jobs on, as in the desktop +/// app: Free Transform on a layer, move it, then click another layer's row in the Layers panel. +#[test] +fn clicking_another_layer_row_applies_the_transform() { + use egui_kittest::kittest::{NodeT, Queryable}; + let app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let layer = app.session.active().unwrap().active_layer.unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_max_steps(64).with_step_dt(1.0 / 60.0).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + let before = frame_of(h.state(), layer).unwrap(); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); + let t = h.state_mut().ui.transform.as_mut().expect("in Free Transform"); + t.quad = t.quad.map(|[x, y]| [x + 8.0, y]); + h.state_mut().background_jobs = true; + h.run_steps(2); + let row = h + .query_all_by_label("Background") + .find(|n| n.accesskit_node().role() == egui::accesskit::Role::Button) + .expect("the Background row") + .rect() + .center(); + h.hover_at(row); + h.run_steps(1); + h.drag_at(row); + h.run_steps(1); + h.drop_at(row); + for _ in 0..400 { + h.run_steps(1); + if h.state().ui.transform.is_none() && !h.state().session.has_jobs() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_ne!(h.state().session.active().unwrap().active_layer, Some(layer), "the click selected the Background"); + assert!(h.state().ui.transform.is_none(), "the box ended"); + assert_eq!(frame_of(h.state(), layer), Some(before.translate(8, 0)), "the move was applied"); +} + +/// Large documents need scales past 10000% and positions past 30000 px (#1267). +#[test] +fn transform_fields_reach_large_documents() { + let t = type_into_bar_field(2, "15000"); + let (sx, sy, _, _) = readout(&t); + assert!((sx - 15000.0).abs() < 0.5 && (sy - 15000.0).abs() < 0.5, "{sx} {sy}"); + assert!((t.quad[1][0] - t.quad[0][0] - 15_000.0).abs() < 1.0, "{:?}", t.quad); + let t = type_into_bar_field(0, "250000"); + assert!((t.pivot[0] - 250_000.0).abs() < 1.0, "{:?}", t.pivot); +} + +/// A typed scale stops where the box reaches the largest document side, not past what can be +/// allocated: the 100 × 50 px test box tops out at 300000 % wide. +#[test] +fn typed_scales_stay_within_the_largest_document() { + assert_eq!(scale_limit_pct(20.0), SCALE_LIMIT_PCT); + assert_eq!(scale_limit_pct(3000.0), 10_000.0); + assert_eq!(scale_limit_pct(1e9), 100.0); + assert_eq!(scale_limit_pct(0.0), SCALE_LIMIT_PCT); + assert_eq!(scale_limit_pct(f64::NAN), SCALE_LIMIT_PCT); + let t = type_into_bar_field(2, "99999999"); + let (sx, sy, _, _) = readout(&t); + let side = t.rect[2] - t.rect[0]; + assert!(sx <= f64::from(scale_limit_pct(side)) + 0.5 && sy <= f64::from(scale_limit_pct(t.rect[3] - t.rect[1])) + 0.5, "{sx} {sy}"); +} + +fn drag(s: &mut TransformSession, from: [f64; 2], to: [f64; 2], mods: egui::Modifiers) { + let g = Gesture { hit: hit(s, from, 8.0), start: from, quad0: s.quad, pivot0: s.pivot }; + apply_drag(s, g, to, mods); +} + +/// A handle drag in Edit › Transform `mode`, as the canvas applies it (on a pixel layer). +fn drag_in(mode: TransformMode, from: [f64; 2], to: [f64; 2], mods: egui::Modifiers) -> [[f64; 2]; 4] { + drag_on(mode, false, from, to, mods) +} + +fn drag_on(mode: TransformMode, type_layer: bool, from: [f64; 2], to: [f64; 2], mods: egui::Modifiers) -> [[f64; 2]; 4] { + let mut s = session(); + let g = Gesture { hit: hit(&s, from, 8.0), start: from, quad0: s.quad, pivot0: s.pivot }; + apply_mode_drag(&mut s, g, to, mode, type_layer, mods); + s.quad +} + +/// Skew on editable type, checked in Photoshop: a corner can't move alone (type stays a +/// parallelogram), so it slides its whole edge: the top or bottom edge for a mostly +/// horizontal drag, the left or right one for a mostly vertical drag. ⌥ moves the opposite +/// edge the other way. Side handles are as on any layer. +#[test] +fn skew_mode_on_type_slides_the_corners_edge() { + let (skew, none) = (TransformMode::Skew, egui::Modifiers::NONE); + assert_eq!(drag_on(skew, true, [100.0, 0.0], [110.0, 3.0], none), [[10.0, 0.0], [110.0, 0.0], [100.0, 50.0], [0.0, 50.0]]); + assert_eq!(drag_on(skew, true, [100.0, 0.0], [102.0, -9.0], none), [[0.0, 0.0], [100.0, -9.0], [100.0, 41.0], [0.0, 50.0]]); + assert_eq!(drag_on(skew, true, [100.0, 0.0], [110.0, 3.0], egui::Modifiers::ALT), [[10.0, 0.0], [110.0, 0.0], [90.0, 50.0], [-10.0, 50.0]]); + assert_eq!(drag_on(skew, true, [50.0, 0.0], [62.0, 7.0], none), [[12.0, 0.0], [112.0, 0.0], [100.0, 50.0], [0.0, 50.0]]); +} + +/// Edit › Transform › Skew, checked in Photoshop (#3437): a corner moves alone, horizontally or +/// vertically (whichever way the drag mostly goes); the top and bottom handles slide only +/// horizontally, the left and right ones only vertically; ⌥ moves the opposite corner or edge +/// the other way. Nothing scales. +#[test] +fn skew_mode_moves_a_corner_or_an_edge_along_one_axis() { + let skew = TransformMode::Skew; + let none = egui::Modifiers::NONE; + // Corner (top right), mostly horizontal, then mostly vertical: only that corner moves. + assert_eq!(drag_in(skew, [100.0, 0.0], [110.0, 3.0], none), [[0.0, 0.0], [110.0, 0.0], [100.0, 50.0], [0.0, 50.0]]); + assert_eq!(drag_in(skew, [100.0, 0.0], [102.0, -9.0], none), [[0.0, 0.0], [100.0, -9.0], [100.0, 50.0], [0.0, 50.0]]); + // Top edge: horizontal only, both its corners. + assert_eq!(drag_in(skew, [50.0, 0.0], [62.0, 7.0], none), [[12.0, 0.0], [112.0, 0.0], [100.0, 50.0], [0.0, 50.0]]); + // Left edge: vertical only. + assert_eq!(drag_in(skew, [0.0, 25.0], [6.0, 33.0], none), [[0.0, 8.0], [100.0, 0.0], [100.0, 50.0], [0.0, 58.0]]); + // ⌥: the opposite corner, and the opposite edge, go the other way. + let alt = egui::Modifiers::ALT; + assert_eq!(drag_in(skew, [100.0, 0.0], [110.0, 3.0], alt), [[0.0, 0.0], [110.0, 0.0], [100.0, 50.0], [-10.0, 50.0]]); + assert_eq!(drag_in(skew, [50.0, 0.0], [62.0, 7.0], alt), [[12.0, 0.0], [112.0, 0.0], [88.0, 50.0], [-12.0, 50.0]]); + // ⇧ changes nothing in Skew mode. + let shift = egui::Modifiers::SHIFT; + assert_eq!(drag_in(skew, [100.0, 0.0], [110.0, 3.0], shift), drag_in(skew, [100.0, 0.0], [110.0, 3.0], none)); + assert_eq!(drag_in(skew, [50.0, 0.0], [62.0, 7.0], shift), drag_in(skew, [50.0, 0.0], [62.0, 7.0], none)); + // A drag outside the box doesn't rotate it in Skew mode. + assert_eq!(drag_in(skew, [130.0, 25.0], [120.0, 60.0], none), corners([0.0, 0.0, 100.0, 50.0])); + // Free Transform is unchanged: a corner scales. + assert_ne!(drag_in(TransformMode::Free, [100.0, 0.0], [110.0, 3.0], none)[2], [100.0, 50.0]); +} + +fn close(a: [[f64; 2]; 4], b: [[f64; 2]; 4]) -> bool { + a.iter().flatten().zip(b.iter().flatten()).all(|(x, y)| (x - y).abs() < 1e-6) +} + +/// On a box smaller than the handles' grab areas the nearest handle wins, so the reference +/// point at the centre doesn't take presses on the corners and edges. +#[test] +fn the_nearest_handle_wins_on_a_small_box() { + let mut s = session(); + s.quad = corners([0.0, 0.0, 16.0, 16.0]); + s.pivot = [8.0, 8.0]; + assert_eq!(hit(&s, [0.0, 0.0], 12.0), Hit::Corner(0)); + assert_eq!(hit(&s, [16.0, 17.0], 12.0), Hit::Corner(2)); + assert_eq!(hit(&s, [8.0, -1.0], 12.0), Hit::Edge(0)); + assert_eq!(hit(&s, [8.0, 8.0], 12.0), Hit::Pivot); + assert_eq!(hit(&s, [40.0, 40.0], 12.0), Hit::Outside); +} + +#[test] +fn interior_patch_points_are_hidden_and_grid_anchors_stay() { + assert!(on_section_edge(0, 0) && on_section_edge(1, 0) && on_section_edge(0, 2)); + assert!(!on_section_edge(1, 1) && !on_section_edge(2, 2)); + let b = [0.0, 0.0, 30.0, 30.0]; + let w = Warp::custom(BezierMesh::identity(b, 1, 1), b); + assert!(warp_hit(&w, [10.0, 10.0], 4.0).is_none(), "the point inside the patch is not shown"); + assert_eq!(warp_hit(&w, [0.0, 0.0], 4.0), Some(0)); + let grid = Warp::custom(BezierMesh::identity(b, 3, 3), b); + assert_eq!(warp_hit(&grid, [10.0, 10.0], 4.0), Some(33), "a grid-corner anchor stays draggable"); + assert!(warp_hit(&grid, [30.0 / 9.0, 30.0 / 9.0], 2.0).is_none()); +} + +#[test] +fn grid_menu_reads_default_and_even_presets() { + let b = [0.0, 0.0, 100.0, 80.0]; + let plain = BezierMesh::identity(b, 1, 1); + assert_eq!(warp_grid_id(&plain), "default"); + assert_eq!(warp_grid_id(&BezierMesh::identity(b, 3, 3)), "3"); + assert_eq!(warp_grid_id(&BezierMesh::identity(b, 4, 4)), "4"); + assert_eq!(warp_grid_id(&BezierMesh::identity(b, 5, 5)), "5"); + assert_eq!(warp_grid_id(&BezierMesh::identity(b, 2, 2)), "custom"); + let mut split = plain.clone(); + assert!(split.split_u(0.5)); + assert_eq!(warp_grid_id(&split), "custom"); + assert!(single_patch(&plain)); + assert!(!single_patch(&BezierMesh::identity(b, 3, 3))); +} + +#[test] +fn split_tool_places_the_line_where_the_pointer_releases() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 32, 32), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + begin_warp(&mut app, &egui::Context::default()).unwrap(); + app.transform_preview.as_mut().unwrap().split_tool = Some(SplitTool::Vertical); + let knots = |app: &PhotocraftApp| app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.as_ref().unwrap().us.clone(); + assert_eq!(knots(&app).len(), 2); + let mods = egui::Modifiers::NONE; + warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, mods); + warp_pointer(&mut app, ToolEvent::Move { x: 14.0, y: 20.0, pressure: 1.0 }, 2.0, mods); + assert_eq!(knots(&app).len(), 2, "the line is only a guide until release"); + warp_pointer(&mut app, ToolEvent::Up { x: 14.0, y: 20.0 }, 2.0, mods); + let us = knots(&app); + let has = |ks: &[f64], u: f64| ks.iter().any(|k| (k - u).abs() < 0.02); + // The default grid's thirds stay; the release cuts the section that contains it. + assert!(has(&us, 0.25) && has(&us, 1.0 / 3.0) && has(&us, 2.0 / 3.0), "{us:?}"); + let vs = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.as_ref().unwrap().vs.clone(); + assert!(has(&vs, 1.0 / 3.0) && has(&vs, 2.0 / 3.0), "horizontal sections stay: {vs:?}"); + assert!(app.transform_preview.as_ref().unwrap().split_tool.is_some(), "the tool stays armed"); + // Option-click in the open places both lines, without a button armed. + app.transform_preview.as_mut().unwrap().split_tool = None; + let alt = egui::Modifiers::ALT; + warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, alt); + warp_pointer(&mut app, ToolEvent::Up { x: 20.0, y: 20.0 }, 2.0, alt); + let m = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.as_ref().unwrap(); + assert!(m.us.len() == us.len() + 1 && has(&m.vs, 0.5), "crosswise cuts the open section: us {:?} vs {:?}", m.us, m.vs); +} + +#[test] +fn split_of_a_grid_cuts_one_section_and_keeps_the_rest() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 32, 32), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + begin_warp(&mut app, &egui::Context::default()).unwrap(); + let rect = app.ui.transform.as_ref().unwrap().rect; + let before = BezierMesh::identity(rect, 3, 3); + app.ui.transform.as_mut().unwrap().warp = Some(Warp::custom(before.clone(), rect)); + // Middle of the centre column (s = 0.5), inside the top row of cells. + let x = rect[0] + 0.5 * (rect[2] - rect[0]); + let y = rect[1] + (1.0 / 6.0) * (rect[3] - rect[1]); + app.transform_preview.as_mut().unwrap().split_tool = Some(SplitTool::Vertical); + let mods = egui::Modifiers::NONE; + warp_pointer(&mut app, ToolEvent::Down { x, y, pressure: 1.0 }, 2.0, mods); + warp_pointer(&mut app, ToolEvent::Up { x, y }, 2.0, mods); + let m = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.as_ref().unwrap(); + assert_eq!(m.vs.len(), before.vs.len(), "horizontal sections are not rebuilt: {:?}", m.vs); + for (a, b) in m.vs.iter().zip(&before.vs) { + assert!((a - b).abs() < 1e-6, "{:?} vs {:?}", m.vs, before.vs); + } + assert_eq!(m.us.len(), before.us.len() + 1, "one cut: {:?}", m.us); + for u in [0.0, 1.0 / 3.0, 0.5, 2.0 / 3.0, 1.0] { + assert!(m.us.iter().any(|k| (k - u).abs() < 1e-3), "missing {u} in {:?}", m.us); + } + let (nx0, nx1) = (before.nx(), m.nx()); + for j in 0..before.ny() { + for i in 0..3 { + let a = before.points[j * nx0 + i]; + let b = m.points[j * nx1 + i]; + assert!((a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6, "left section moved"); + } + } +} + +#[test] +fn corner_drag_scales_proportionally_about_opposite_corner() { + let mut s = session(); + drag(&mut s, [100.0, 50.0], [200.0, 60.0], egui::Modifiers::NONE); + assert!(close(s.quad, corners([0.0, 0.0, 200.0, 100.0])), "{:?}", s.quad); + let mut s = session(); + drag(&mut s, [100.0, 50.0], [200.0, 60.0], egui::Modifiers::SHIFT); + assert!(close(s.quad, corners([0.0, 0.0, 200.0, 60.0])), "shift = free: {:?}", s.quad); +} + +/// Photoshop CC 2019 and later: an edge scales proportionally too, about the middle of the +/// opposite edge, and ⇧ stretches its one axis instead. +#[test] +fn edge_drag_scales_proportionally_about_the_opposite_edge() { + // Right edge: 100 × 50 → 150 × 75; the left edge's middle (0, 25) stays, and so does the + // reference point's place in the box (its centre). + let mut s = session(); + drag(&mut s, [100.0, 25.0], [150.0, 25.0], egui::Modifiers::NONE); + assert!(close(s.quad, corners([0.0, -12.5, 150.0, 62.5])), "{:?}", s.quad); + assert!(near(s.pivot, [75.0, 25.0]), "{:?}", s.pivot); + // Top edge to twice the height: twice the width, about x = 50. + let mut s = session(); + drag(&mut s, [50.0, 0.0], [50.0, -50.0], egui::Modifiers::NONE); + assert!(close(s.quad, corners([-50.0, -50.0, 150.0, 50.0])), "{:?}", s.quad); + // Past the opposite edge: the dragged axis flips, the other only shrinks. + let mut s = session(); + drag(&mut s, [100.0, 25.0], [-50.0, 25.0], egui::Modifiers::NONE); + assert!(close(s.quad, corners([0.0, 12.5, -50.0, 37.5])), "{:?}", s.quad); + // ⇧: one axis. + let mut s = session(); + drag(&mut s, [50.0, 50.0], [50.0, 80.0], egui::Modifiers::SHIFT); + assert!(close(s.quad, corners([0.0, 0.0, 100.0, 80.0])), "{:?}", s.quad); +} + +#[test] +fn alt_scales_edges_about_reference_point() { + let mut s = session(); + drag(&mut s, [100.0, 25.0], [150.0, 25.0], egui::Modifiers::ALT); + assert!(close(s.quad, corners([-50.0, -25.0, 150.0, 75.0])), "{:?}", s.quad); + // ⌥⇧: one axis, about the reference point. + let mut s = session(); + drag(&mut s, [100.0, 25.0], [150.0, 25.0], egui::Modifiers { alt: true, shift: true, ..Default::default() }); + assert!(close(s.quad, corners([-50.0, 0.0, 150.0, 50.0])), "{:?}", s.quad); +} + +/// A reference point moved off the centre (⌥-click) is the centre of ⌥-scaling too, not just +/// of rotation: it stays put and the box scales away from it. +#[test] +fn alt_scales_about_a_moved_reference_point() { + let alt = egui::Modifiers::ALT; + // Reference point on the top-left corner: the bottom-right corner to (200, 100) doubles + // the box, top-left fixed (not centred on the reference point). + let mut s = session(); + s.pivot = [0.0, 0.0]; + drag(&mut s, [100.0, 50.0], [200.0, 100.0], alt); + assert!(close(s.quad, corners([0.0, 0.0, 200.0, 100.0])), "{:?}", s.quad); + assert!(near(s.pivot, [0.0, 0.0]), "{:?}", s.pivot); + // Reference point at (25, 25): the right edge to x = 175 is 2× about x = 25, and + // proportionally 2× about y = 25 too. + let mut s = session(); + s.pivot = [25.0, 25.0]; + drag(&mut s, [100.0, 25.0], [175.0, 25.0], alt); + assert!(close(s.quad, corners([-25.0, -25.0, 175.0, 75.0])), "{:?}", s.quad); + // ⌥⇧: that edge's axis only. + let mut s = session(); + s.pivot = [25.0, 25.0]; + drag(&mut s, [100.0, 25.0], [175.0, 25.0], egui::Modifiers { alt: true, shift: true, ..Default::default() }); + assert!(close(s.quad, corners([-25.0, 0.0, 175.0, 50.0])), "{:?}", s.quad); + // Reference point in line with the dragged corner horizontally: that axis has nothing to + // scale against and stays, the other doubles about it. + let mut s = session(); + s.pivot = [100.0, 50.0]; + drag(&mut s, [100.0, 0.0], [150.0, -50.0], egui::Modifiers { alt: true, shift: true, ..Default::default() }); + assert!(close(s.quad, corners([0.0, -50.0, 100.0, 50.0])), "{:?}", s.quad); +} + +fn near(a: [f64; 2], b: [f64; 2]) -> bool { + (a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6 +} + +/// The reference point is attached to the box (#1329): scaling, skewing, distorting and +/// perspective carry it along to the same place within the box; ⌥-scaling about it and +/// rotating about it leave it put. +#[test] +fn the_reference_point_moves_with_the_box() { + // Corner scale down: the centre stays the centre. + let mut s = session(); + drag(&mut s, [100.0, 50.0], [50.0, 25.0], egui::Modifiers::NONE); + assert!(close(s.quad, corners([0.0, 0.0, 50.0, 25.0])), "{:?}", s.quad); + assert!(near(s.pivot, [25.0, 12.5]), "{:?}", s.pivot); + // A reference point set to a corner stays at that corner; an edge drag carries it too. + let mut s = session(); + s.pivot = [100.0, 0.0]; + drag(&mut s, [50.0, 50.0], [50.0, 80.0], egui::Modifiers::SHIFT); + assert!(near(s.pivot, [100.0, 0.0]), "{:?}", s.pivot); + drag(&mut s, [100.0, 40.0], [150.0, 40.0], egui::Modifiers::SHIFT); + assert!(near(s.pivot, s.quad[1]), "{:?} {:?}", s.pivot, s.quad); + drag(&mut s, [150.0, 40.0], [180.0, 40.0], egui::Modifiers::NONE); + assert!(near(s.pivot, s.quad[1]), "proportional edge drag: {:?} {:?}", s.pivot, s.quad); + // Skew: the centre follows the box's centre. + let mut s = session(); + drag(&mut s, [50.0, 0.0], [70.0, 0.0], egui::Modifiers::COMMAND); + assert!(near(s.pivot, [60.0, 25.0]), "{:?}", s.pivot); + // Distort: a corner reference point stays on its corner. + let mut s = session(); + s.pivot = [0.0, 50.0]; + drag(&mut s, [0.0, 50.0], [-20.0, 70.0], egui::Modifiers::COMMAND); + assert!(near(s.pivot, [-20.0, 70.0]), "{:?}", s.pivot); + // Perspective: the centre stays inside the box, on the box's own centre lines. + let mut s = session(); + drag(&mut s, [100.0, 0.0], [120.0, 0.0], egui::Modifiers { command: true, alt: true, shift: true, ..Default::default() }); + let h = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], s.quad).unwrap(); + let (x, y) = h.apply(0.5, 0.5); + assert!(near(s.pivot, [x, y]), "{:?} vs {:?}", s.pivot, [x, y]); + // ⌥ scales about the reference point: it stays where it is. + let mut s = session(); + drag(&mut s, [100.0, 50.0], [150.0, 75.0], egui::Modifiers::ALT); + assert!(near(s.pivot, [50.0, 25.0]), "{:?}", s.pivot); + // Rotation turns about it. + let mut s = session(); + drag(&mut s, [150.0, 25.0], [50.0, 125.0], egui::Modifiers::NONE); + assert!(near(s.pivot, [50.0, 25.0]), "{:?}", s.pivot); + // From a box collapsed to a point there is no place within it to keep: it stays put. + assert_eq!(carry_pivot([[0.0, 0.0]; 4], corners([0.0, 0.0, 10.0, 10.0]), [5.0, 5.0]), [5.0, 5.0]); +} + +#[test] +fn move_rotate_and_distort() { + let mut s = session(); + drag(&mut s, [40.0, 20.0], [50.0, 30.0], egui::Modifiers::NONE); + assert!(close(s.quad, corners([10.0, 10.0, 110.0, 60.0]))); + assert_eq!(s.pivot, [60.0, 35.0]); + // Rotate 90° about the centre (drag from right of the box to below it). + let mut s = session(); + drag(&mut s, [150.0, 25.0], [50.0, 125.0], egui::Modifiers::NONE); + let (_, _, angle, _) = readout(&s); + assert!((angle - 90.0).abs() < 1e-6, "{angle}"); + // ⇧ snaps: a 50° drag lands on 45°. + let mut s = session(); + let a = 50f64.to_radians(); + drag(&mut s, [150.0, 25.0], [50.0 + 100.0 * a.cos(), 25.0 + 100.0 * a.sin()], egui::Modifiers::SHIFT); + assert!((readout(&s).2 - 45.0).abs() < 1e-6); + // ⌘ corner = distort. + let mut s = session(); + drag(&mut s, [100.0, 0.0], [120.0, -10.0], egui::Modifiers::COMMAND); + assert_eq!(s.quad[1], [120.0, -10.0]); + assert_eq!(s.quad[0], [0.0, 0.0]); +} + +#[test] +fn begin_and_commit_through_the_engine() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 24, 24), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let ctx = egui::Context::default(); + begin(&mut app, &ctx).unwrap(); + assert_eq!(app.ui.transform.as_ref().unwrap().rect, [8.0, 8.0, 24.0, 24.0]); + scale_about_pivot(&mut app, 2.0, 2.0); + commit(&mut app); + let st = app.session.active().unwrap(); + let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); + assert!(b.width().abs_diff(32) <= 2 && b.x0.abs_diff(0) <= 1, "{b:?}"); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none()); +} + +/// A commit the engine refuses (here a collapsed box; a result over the pixel budget, #3773, is +/// refused the same way) shows the reason and keeps the box open, unchanged; picking another +/// tool then ends it. +#[test] +fn a_refused_commit_keeps_the_box_open() { + let ctx = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let (revision, steps) = (app.session.active().unwrap().revision, app.session.active().unwrap().history.past_len()); + begin(&mut app, &ctx).unwrap(); + if let Some(t) = app.ui.transform.as_mut() { + t.quad = [[16.0, 16.0]; 4]; + } + commit(&mut app); + let t = app.ui.transform.as_ref().expect("the box stays open"); + assert_eq!(t.quad, [[16.0, 16.0]; 4], "as the user left it"); + assert!(app.transform_preview.is_some(), "with its preview"); + assert!(app.ui.status.contains("collapses"), "{}", app.ui.status); + let st = app.session.active().unwrap(); + assert_eq!((st.revision, st.history.past_len()), (revision, steps), "the document was not changed"); + app.ui.tool = if app.ui.tool == Tool::Brush { Tool::Move } else { Tool::Brush }; + end_if_left(&mut app); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "another tool ends it"); +} + +/// #6737: Save for Web exports the committed document, so it is off while a box is pending. +#[test] +fn save_for_web_is_off_under_a_pending_transform() { + let ctx = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + assert!(crate::menus::is_enabled(&app, SAVE_FOR_WEB), "enabled with no box"); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + assert!(!crate::menus::is_enabled(&app, SAVE_FOR_WEB), "off under the box"); + assert!(crate::menus::invoke(&mut app, &ctx, SAVE_FOR_WEB, json!({})).is_err(), "the dialog doesn't open"); + let path = std::env::temp_dir().join(format!("pc-web6737-{}.png", std::process::id())).to_string_lossy().into_owned(); + let r = crate::menus::invoke(&mut app, &ctx, SAVE_FOR_WEB, json!({"path": path, "format": "png24"})); + assert!(r.is_err() && !std::path::Path::new(&path).exists(), "nor does the export run"); + assert!(app.ui.transform.is_some(), "the box stays open"); + cancel(&mut app); + assert!(crate::menus::is_enabled(&app, SAVE_FOR_WEB), "back after the box closes"); +} + +/// #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. +#[test] +fn free_transform_a_copy() { + let ctx = egui::Context::default(); + let bounds = |app: &PhotocraftApp, i: usize| app.session.active().unwrap().doc.layers[i].surface().unwrap().content_bounds(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let (layers, steps) = (app.session.active().unwrap().doc.layers.len(), app.session.active().unwrap().history.past_len()); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransformCopy", json!({})).unwrap(); + assert_eq!(app.ui.transform.as_ref().unwrap().made, Some(MadeLayer::Copy)); + assert!(!crate::menus::is_enabled(&app, "edit.freeTransformCopy"), "one transform at a time"); + // Esc: the copy goes too. + cancel(&mut app); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.layers.len(), st.history.past_len()), (layers, steps)); + assert!(!st.history.can_redo(), "nothing to redo"); + // OK: original in place, a moved copy, one step. + crate::menus::invoke(&mut app, &ctx, "edit.freeTransformCopy", json!({})).unwrap(); + if let Some(t) = app.ui.transform.as_mut() { + t.quad = t.quad.map(|[x, y]| [x + 20.0, y]); + } + commit(&mut app); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.layers.len(), st.history.past_len()), (layers + 1, steps + 1)); + assert_eq!(bounds(&app, layers - 1), photocraft_geom::Rect::new(8, 8, 24, 24), "the original stays"); + assert_eq!(bounds(&app, layers), photocraft_geom::Rect::new(28, 8, 44, 24), "the copy moved"); + app.session.undo(); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "one undo removes copy and move"); + // With a selection: Layer via Copy, so only the selected pixels are copied. + app.run("select.rect", json!({"x": 8, "y": 8, "width": 8, "height": 16})).unwrap(); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransformCopy", json!({})).unwrap(); + assert_eq!(app.ui.transform.as_ref().unwrap().rect, [8.0, 8.0, 16.0, 24.0]); + cancel(&mut app); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers); +} + +/// #4112: ⌥⌘T on a cylinder smart object, Warp mode, Enter with nothing touched: the copy +/// keeps the cylinder and stays its own step (no warp step to fold into), so one undo takes +/// back the copy and nothing before it. +#[test] +fn untouched_warp_of_a_cylinder_copy_keeps_its_own_step() { + let ctx = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + app.run("layer.smartObjects.warp", json!({"style": "cylinder", "values": [8, 24, 24, 8, 0.3, 0.3, 0.5], "rect": [8, 8, 24, 24]})).unwrap(); + let warp = |app: &PhotocraftApp, i: usize| match &app.session.active().unwrap().doc.layers[i].content { + photocraft_doc::LayerContent::Smart(sm) => sm.warp.as_ref().map(|w| w.style), + _ => None, + }; + let (layers, steps) = (app.session.active().unwrap().doc.layers.len(), app.session.active().unwrap().history.past_len()); + assert_eq!(warp(&app, layers - 1), Some(WarpStyle::Cylinder)); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransformCopy", json!({})).unwrap(); + enter_warp(&mut app, &ctx); + assert!(app.ui.transform.as_ref().unwrap().warp.is_some(), "Warp mode shows the cylinder"); + commit(&mut app); + assert!(!app.ui.status_error, "{}", app.ui.status); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.layers.len(), st.history.past_len()), (layers + 1, steps + 1)); + assert_eq!(warp(&app, layers), Some(WarpStyle::Cylinder), "the copy is still a cylinder"); + app.session.undo(); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.layers.len(), st.history.past_len()), (layers, steps), "one undo takes back the copy only"); + assert_eq!(warp(&app, layers - 1), Some(WarpStyle::Cylinder)); +} + +/// #1099: cancel, frame cleanup and a commit before the next frame all belong to the +/// original document, including after tab reordering and with shared layer IDs. +#[test] +fn cancelling_a_copy_after_switching_documents_preserves_the_active_document() { + for reorder in [false, true] { + for finish in [cancel, end_if_left, commit] { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let original = app.session.active().unwrap().doc.clone(); + let steps = app.session.active().unwrap().history.past_len(); + begin_copy(&mut app, &egui::Context::default()).unwrap(); + app.ui.transform.as_mut().unwrap().quad = corners([12.0, 8.0, 28.0, 24.0]); + // Cloning a document deliberately shares layer IDs, but gets a fresh document ID. + let other = app.session.active().unwrap().doc.as_ref().clone(); + app.session.add_document(other, None); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + assert!(app.session.undo()); + let st = app.session.active().unwrap(); + let (doc, history, redo, revision, layer) = + (st.doc.clone(), st.history.entries(), st.history.redo_labels().map(str::to_owned).collect::>(), st.revision, st.active_layer); + if reorder { + app.session.move_document(0, 1); + } + finish(&mut app); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none()); + let st = app.session.active().unwrap(); + assert!(Arc::ptr_eq(&st.doc, &doc), "the selected document's pixels are unchanged"); + assert_eq!((st.history.entries(), st.revision, st.active_layer), (history, revision, layer)); + assert_eq!(st.history.redo_labels().collect::>(), redo); + let origin = app.session.documents().iter().find(|st| st.doc.id == original.id).unwrap(); + assert!(Arc::ptr_eq(&origin.doc, &original), "only the originating copy is undone"); + assert_eq!(origin.history.past_len(), steps); + assert!(!origin.history.can_redo()); + } + } +} + +#[test] +fn cancelling_a_copy_after_its_document_closes_does_not_undo_another_document() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + begin_copy(&mut app, &egui::Context::default()).unwrap(); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let steps = app.session.active().unwrap().history.past_len(); + app.session.close(0); + end_if_left(&mut app); + let st = app.session.active().unwrap(); + assert!(Arc::ptr_eq(&st.doc, &doc)); + assert_eq!(st.history.past_len(), steps); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none()); +} + +#[test] +fn cancelling_an_already_undone_copy_preserves_history_and_redo() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + begin_copy(&mut app, &egui::Context::default()).unwrap(); + assert!(app.session.undo()); + let st = app.session.active().unwrap(); + let (doc, history, redo) = (st.doc.clone(), st.history.entries(), st.history.redo_labels().map(str::to_owned).collect::>()); + end_if_left(&mut app); + let st = app.session.active().unwrap(); + assert!(Arc::ptr_eq(&st.doc, &doc)); + assert_eq!(st.history.entries(), history); + assert_eq!(st.history.redo_labels().collect::>(), redo); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none()); +} + +#[test] +fn cancelling_a_copy_does_not_undo_a_later_edit() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + begin_copy(&mut app, &egui::Context::default()).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let st = app.session.active().unwrap(); + let (doc, history) = (st.doc.clone(), st.history.entries()); + cancel(&mut app); + let st = app.session.active().unwrap(); + assert!(Arc::ptr_eq(&st.doc, &doc)); + assert_eq!(st.history.entries(), history); +} + +/// #1384: the Layers panel's opacity, fill, visibility and blend edits to the moving layer +/// and to the others show while the box is open, and survive the commit. +#[test] +fn edits_during_a_transform_show_in_the_preview() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.ui.tool = Tool::Move; + let bg = app.session.active().unwrap().doc.layers[0].id; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); + if let Some(t) = h.state_mut().ui.transform.as_mut() { + t.quad = t.quad.map(|[x, y]| [x + 20.0, y]); + } + h.run_steps(2); + let layer = h.state().ui.transform.as_ref().unwrap().layer; + assert_eq!(h.state().transform_preview.as_ref().unwrap().opacity, 1.0); + + h.state_mut().run("layer.setProps", json!({"layer": layer, "opacity": 0.5, "fill": 0.6, "blend": "Multiply"})).unwrap(); + h.state_mut().run("layer.setProps", json!({"layer": bg.0, "visible": false})).unwrap(); + h.run_steps(2); + let app = h.state(); + assert!(app.ui.transform.is_some(), "the edits leave the box open"); + let pv = app.transform_preview.as_ref().unwrap(); + assert!((pv.opacity - 0.3).abs() < 1e-6, "the moving pixels take the new opacity × fill: {}", pv.opacity); + assert!(!pv.doc.layer(bg).unwrap().visible, "the document under the box follows"); + let moving = pv.doc.layer(LayerId(layer)).unwrap(); + assert!(!moving.visible, "the moving layer stays out of the document under the box"); + assert_eq!(moving.blend, photocraft_color::BlendMode::Multiply); + + h.state_mut().run("layer.setProps", json!({"layer": layer, "visible": false})).unwrap(); + h.run_steps(2); + assert_eq!(h.state().transform_preview.as_ref().unwrap().opacity, 0.0, "hiding the layer hides the moving pixels"); + h.state_mut().run("layer.setProps", json!({"layer": layer, "visible": true})).unwrap(); + + commit(h.state_mut()); + let st = h.state().session.active().unwrap(); + let l = st.doc.layer(LayerId(layer)).unwrap(); + assert_eq!((l.opacity, l.fill_opacity, l.blend), (0.5, 0.6, photocraft_color::BlendMode::Multiply)); + assert_eq!(l.surface().unwrap().content_bounds(), photocraft_geom::Rect::new(28, 8, 44, 24)); +} + +/// #1384 with a selection: the pixels it leaves behind stay in the rebuilt preview without +/// the lifted ones, and take the layer's new properties. +#[test] +fn edits_during_a_selection_transform_keep_the_lifted_pixels_out() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.ui.tool = Tool::Move; + app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 8, "height": 16})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); + h.run_steps(2); + let layer = LayerId(h.state().ui.transform.as_ref().unwrap().layer); + // Alpha in the preview's copy of the layer: in the lifted half (x 8..16) and the rest (16..24). + let left = |app: &PhotocraftApp| { + let s = app.transform_preview.as_ref().unwrap().doc.layer(layer).unwrap().surface().unwrap().clone(); + (s.sample_channel(10, 12, 3), s.sample_channel(20, 12, 3)) + }; + assert_eq!(left(h.state()), (0.0, 1.0), "the selected half is lifted out"); + + h.state_mut().run("layer.setProps", json!({"layer": layer.0, "opacity": 0.4})).unwrap(); + h.run_steps(2); + let app = h.state(); + assert_eq!(left(app), (0.0, 1.0), "still without the lifted pixels"); + let moving = app.transform_preview.as_ref().unwrap().doc.layer(layer).unwrap(); + assert!(moving.visible && (moving.opacity - 0.4).abs() < 1e-6, "what stays behind is drawn with the new opacity"); + assert!((app.transform_preview.as_ref().unwrap().opacity - 0.4).abs() < 1e-6); +} + +/// #670: picking another tool applies the open transform, as one history step. +#[test] +fn picking_another_tool_applies_the_transform() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.ui.tool = Tool::Move; + let steps = app.session.active().unwrap().history.past_len(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); + if let Some(t) = h.state_mut().ui.transform.as_mut() { + t.quad = t.quad.map(|[x, y]| [x + 20.0, y]); + } + h.run_steps(2); + assert!(h.state().ui.transform.is_some(), "open while the tool stays"); + h.key_press(egui::Key::B); + h.run_steps(2); + let app = h.state(); + assert_eq!(app.ui.tool, Tool::Brush); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none()); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), steps + 1); + assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(), photocraft_geom::Rect::new(28, 8, 44, 24)); +} + +/// #1400: selecting another layer while transforming applies the box to the layer it was on, +/// and the next transform starts on the newly selected layer. +#[test] +fn selecting_another_layer_applies_the_transform_and_the_next_one_follows() { + let ctx = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let first = app.session.active().unwrap().active_layer.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(40, 40, 56, 60), &[0.0, 0.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + let second = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.select", json!({"layer": first.0})).unwrap(); + app.ui.tool = Tool::Move; + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + if let Some(t) = app.ui.transform.as_mut() { + t.quad = t.quad.map(|[x, y]| [x + 20.0, y]); + } + let steps = app.session.active().unwrap().history.past_len(); + app.run("layer.select", json!({"layer": second.0})).unwrap(); + end_if_left(&mut app); + assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "the box left the old layer"); + let st = app.session.active().unwrap(); + assert_eq!(st.active_layer, Some(second)); + assert_eq!(st.history.past_len(), steps + 1, "applied as one step"); + let bounds = |id: LayerId| st.doc.layer(id).unwrap().surface().unwrap().content_bounds(); + assert_eq!(bounds(first), photocraft_geom::Rect::new(28, 8, 44, 24), "applied to the layer it was on"); + assert_eq!(bounds(second), photocraft_geom::Rect::new(40, 40, 56, 60), "the new layer is untouched"); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + let t = app.ui.transform.as_ref().unwrap(); + assert_eq!((t.layer, t.rect), (second.0, [40.0, 40.0, 56.0, 60.0]), "the next box is on the selected layer"); +} + +/// The screen rectangle the marching ants cover as [`draw_selection`] paints them over the +/// active document's selection; `None` when it leaves them to the canvas. +fn ants_bounds(app: &PhotocraftApp, xf: &ViewXform) -> Option { + let st = app.session.active().unwrap(); + let sel = st.doc.selection.as_ref().unwrap(); + let segs = crate::outline::outline(sel, sel.content_bounds()); + let ctx = egui::Context::default(); + let mut drawn = false; + let mut output = ctx.run_ui(Default::default(), |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("ants-test"))); + drawn = draw_selection(app, &painter, xf, st.doc.id, &segs, 0.0); + }); + output.textures_delta.clear(); + // The ants are a mesh of straight dashes and line shapes for the slanted ones. + let ants = output.shapes.iter().filter(|s| matches!(s.shape, egui::Shape::Mesh(_) | egui::Shape::LineSegment { .. })); + drawn.then(|| ants.map(|s| s.shape.visual_bounding_rect()).fold(egui::Rect::NOTHING, egui::Rect::union)) +} + +/// The screen rectangle around document points. +fn screen_bounds(xf: &ViewXform, points: &[[f64; 2]]) -> egui::Rect { + egui::Rect::from_points(&points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect::>()) +} + +fn rects_match(a: egui::Rect, b: egui::Rect) -> bool { + (a.min - b.min).abs().max_elem() <= 2.0 && (a.max - b.max).abs().max_elem() <= 2.0 +} + +/// #5297: with a selection, Free Transform's box is the selection's own rectangle (wider here +/// than the pixels it holds), and the marching ants stay on the box through a move, a scale, a +/// rotation and a distort, before anything is applied. Applying leaves them there. +#[test] +fn the_box_is_the_selection_and_the_ants_follow_it() { + let ctx = gpu_ctx(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let xf = ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0)), + zoom: 2.0, + center: [32.0, 32.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + }; + app.run("select.rect", json!({"x": 4, "y": 4, "width": 30, "height": 26})).unwrap(); + assert_eq!(ants_bounds(&app, &xf), None, "no box open: the canvas draws them where they are"); + begin(&mut app, &ctx).unwrap(); + let rest = corners([4.0, 4.0, 34.0, 30.0]); + assert_eq!(app.ui.transform.as_ref().unwrap().quad, rest, "the box is the selection, not the 16 px square in it"); + assert!(rects_match(ants_bounds(&app, &xf).unwrap(), screen_bounds(&xf, &rest)), "untouched, the ants are where they were"); + + let on_the_box = |app: &PhotocraftApp, what: &str| { + let quad = app.ui.transform.as_ref().unwrap().quad; + let (ants, boxed) = (ants_bounds(app, &xf).unwrap(), screen_bounds(&xf, &quad)); + assert!(rects_match(ants, boxed), "{what}: ants {ants:?}, box {boxed:?}"); + }; + if let Some(t) = app.ui.transform.as_mut() { + t.quad = t.quad.map(|[x, y]| [x + 20.0, y + 10.0]); + t.pivot = [t.pivot[0] + 20.0, t.pivot[1] + 10.0]; + } + on_the_box(&app, "moved"); + let moved = app.ui.transform.as_ref().unwrap().quad; + scale_about_pivot(&mut app, 0.5, 1.5); + on_the_box(&app, "scaled"); + rotate_about_pivot(&mut app, 0.6); + on_the_box(&app, "rotated"); + if let Some(t) = app.ui.transform.as_mut() { + t.quad[2] = [t.quad[2][0] + 9.0, t.quad[2][1] + 13.0]; + } + on_the_box(&app, "distorted"); + + // Applied as moved only: the outline is where the ants showed it. + if let Some(t) = app.ui.transform.as_mut() { + t.quad = moved; + } + commit(&mut app); + assert!(app.ui.transform.is_none()); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), photocraft_geom::Rect::new(24, 14, 54, 40)); + assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(), photocraft_geom::Rect::new(28, 18, 44, 34)); +} + +/// #5297: in Warp mode the ants bend with the mesh, and past a Distort's horizon they stop +/// rather than run off to infinity. +#[test] +fn the_ants_follow_a_warp_and_stop_at_a_distorts_horizon() { + let ctx = gpu_ctx(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 56, 56)); + let xf = ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0)), + zoom: 2.0, + center: [32.0, 32.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + }; + app.run("select.rect", json!({"x": 12, "y": 12, "width": 40, "height": 40})).unwrap(); + begin(&mut app, &ctx).unwrap(); + let rest = corners([12.0, 12.0, 52.0, 52.0]); + + // Two corners dragged across each other put half the box past the horizon. + if let Some(t) = app.ui.transform.as_mut() { + t.quad = [[12.0, 12.0], [52.0, 12.0], [20.0, 40.0], [44.0, 40.0]]; + } + let ants = ants_bounds(&app, &xf).unwrap(); + assert!(ants == egui::Rect::NOTHING || (ants.is_finite() && ants.width() < 1e5 && ants.height() < 1e5), "{ants:?}"); + + if let Some(t) = app.ui.transform.as_mut() { + t.quad = rest; + } + enter_warp(&mut app, &ctx); + let arc = Warp::preset(WarpStyle::Arc, 50.0, [12.0, 12.0, 52.0, 52.0]); + app.ui.transform.as_mut().unwrap().warp = Some(arc.clone()); + let ants = ants_bounds(&app, &xf).unwrap(); + assert!(!rects_match(ants, screen_bounds(&xf, &rest)), "the outline left its place: {ants:?}"); + let warped: Vec<[f64; 2]> = rest.iter().map(|p| arc.map(p[0], p[1])).map(|(x, y)| [x, y]).collect(); + assert!(ants.expand(2.0).contains_rect(screen_bounds(&xf, &warped)), "the warped corners are on it: {ants:?}"); +} + +/// Transform Selection moves the selection outline, not a layer: selecting a layer keeps it open. +#[test] +fn selecting_another_layer_keeps_a_transform_selection_open() { + let ctx = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let first = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.all", json!({})).unwrap(); + begin_selection(&mut app, &ctx).unwrap(); + app.run("layer.select", json!({"layer": first.0})).unwrap(); + end_if_left(&mut app); + assert!(app.ui.transform.as_ref().is_some_and(|t| t.selection)); +} + +/// A control-channel stroke that picks another tool applies the box first, then paints. +#[test] +fn a_pointer_request_with_another_tool_applies_the_transform_first() { + let ctx = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.ui.tool = Tool::Move; + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + if let Some(t) = app.ui.transform.as_mut() { + t.quad = t.quad.map(|[x, y]| [x + 20.0, y]); + } + let steps = app.session.active().unwrap().history.past_len(); + let ev = |kind: &str, x: f64| json!({"kind": kind, "x": x, "y": 50.0}); + let events = json!([ev("down", 4.0), ev("move", 32.0), ev("move", 60.0), ev("up", 60.0)]); + let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"tool": "brush", "events": events})); + let _ = crate::control::handle(&mut app, &ctx, &req); + assert!(app.ui.transform.is_none()); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), steps + 2, "the transform, then the stroke"); + let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); + assert!(b.x0 < 8 && b.x1 >= 44 && b.y0 == 8 && b.y1 > 50, "moved square and stroke: {b:?}"); +} + +/// Drags with real pointer events (snapping off so the drops land exactly). +fn press_drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], m: egui::Modifiers) { + crate::canvas::tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, m); + crate::canvas::tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, m); +} + +#[test] +fn distort_mode_moves_one_corner_and_ignores_rotate_and_edges() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.ui.extras.snap = false; + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "edit.transform.distort", json!({})).unwrap(); + let q0 = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(app.ui.transform.as_ref().unwrap().mode, TransformMode::Distort); + // Outside (rotate) and an edge handle do nothing in Distort. + press_drag(&mut app, [44.0, 44.0], [54.0, 10.0], egui::Modifiers::NONE); + press_drag(&mut app, [24.0, 16.0], [34.0, 16.0], egui::Modifiers::NONE); + assert_eq!(app.ui.transform.as_ref().unwrap().quad, q0); + // A corner moves alone, with no keys held. + press_drag(&mut app, q0[1], [q0[1][0] + 7.0, q0[1][1] - 5.0], egui::Modifiers::NONE); + let q = app.ui.transform.as_ref().unwrap().quad; + assert_eq!(q[1], [q0[1][0] + 7.0, q0[1][1] - 5.0]); + assert_eq!([q[0], q[2], q[3]], [q0[0], q0[2], q0[3]]); + // Free Transform from the menu switches the live box back. + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + assert_eq!(app.ui.transform.as_ref().unwrap().mode, TransformMode::Free); +} + +/// #3941: Edit › Transform › Rotate must rotate from a corner handle, not scale. +#[test] +fn rotate_mode_turns_the_box_from_a_corner_handle() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.ui.extras.snap = false; + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "edit.transform.rotate", json!({})).unwrap(); + assert_eq!(app.ui.transform.as_ref().unwrap().mode, TransformMode::Rotate); + let q0 = app.ui.transform.as_ref().unwrap().quad; + press_drag(&mut app, q0[1], [q0[1][0], q0[1][1] + 16.0], egui::Modifiers::NONE); + let q = app.ui.transform.as_ref().unwrap().quad; + let w0 = (q0[1][0] - q0[0][0]).hypot(q0[1][1] - q0[0][1]); + let w = (q[1][0] - q[0][0]).hypot(q[1][1] - q[0][1]); + assert!((w - w0).abs() < 1e-6, "side length stays {w0}, got {w}: {q:?}"); + assert!((q[0][1] - q[1][1]).abs() > 1.0, "the box rotated, not scaled: {q:?}"); + crate::menus::invoke(&mut app, &ctx, "edit.transform.scale", json!({})).unwrap(); + assert_eq!(app.ui.transform.as_ref().unwrap().mode, TransformMode::Free); +} + +fn near2(a: Option<[f64; 2]>, b: [f64; 2]) -> bool { + a.is_some_and(|a| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9) +} + +/// #1767: just outside a corner is the rotate zone: the OS pointer hides for the drawn curved +/// arrow, which bends round that corner. +#[test] +fn the_preview_leaves_out_cells_past_the_horizon() { + // #4863: the bottom corners pulled in and one dragged far out: a concave quad whose + // source straddles the horizon. Its cells there are left out; an ordinary quad keeps all. + let past = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], [[0.0, 0.0], [300.0, 0.0], [60.0, 60.0], [0.0, 300.0]]).unwrap(); + let ahead = front_vertices(&past, 24); + assert!(ahead.iter().any(|a| *a) && ahead.iter().any(|a| !*a), "some of the grid is past the horizon"); + // Three corners are on one side (drawn); the top-left one is past the horizon. + assert!(ahead[24 * 25 + 24] && ahead[24] && ahead[24 * 25], "the three corners in front are drawn"); + assert!(!ahead[0], "the corner past the horizon is left out"); + let plain = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], [[0.0, 0.0], [300.0, 0.0], [280.0, 260.0], [0.0, 300.0]]).unwrap(); + assert!(front_vertices(&plain, 24).iter().all(|a| *a)); +} + +#[test] +fn hovering_just_outside_a_corner_asks_for_the_rotate_cursor() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let tol = handle_tolerance(&app); + let h = std::f64::consts::FRAC_1_SQRT_2; + let (tl, br) = ([32.0 - tol * 1.5, 32.0 - tol * 1.5], [160.0 + tol * 1.5, 160.0 + tol * 1.5]); + let xf = ViewXform::active(&app).unwrap(); + assert_eq!(cursor(&app, &xf, tl, false), Some(CursorIcon::None), "the arrow is drawn instead"); + assert!(near2(rotate_cursor_dir(&app, tl), [h, h]), "{:?}", rotate_cursor_dir(&app, tl)); + assert!(near2(rotate_cursor_dir(&app, br), [-h, -h]), "bends round the bottom-right corner"); + assert_eq!(cursor(&app, &xf, [60.0, 60.0], false), Some(CursorIcon::Move)); + assert_eq!(rotate_cursor_dir(&app, [60.0, 60.0]), None, "inside moves"); + assert_eq!(rotate_cursor_dir(&app, [32.0, 32.0]), None, "the corner handle scales"); + assert_eq!(rotate_cursor_dir(&app, [f64::NAN, 32.0]), None); +} + +// Regression test for #4139: the rotate zone hides the OS pointer (`CursorIcon::None`), so the +// canvas has to draw the curved turn arrow itself where the box has no preview to draw it +// (the preview's overlay draws it otherwise); the pointer vanished over the zone. +#[test] +fn the_rotate_zone_draws_the_turn_arrow_where_the_pointer_is_hidden() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + app.ui.tool = Tool::Move; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); + h.run_steps(3); + let tol = handle_tolerance(h.state()); + let xf = ViewXform::active(h.state()).unwrap(); + let accent = crate::theme::Tokens::get(&h.ctx).accent_text; + // The arrow's bright stroke: a 17-point arc in the accent colour around the pointer. + let arrows = |h: &egui_kittest::Harness<'_, PhotocraftApp>, at: egui::Pos2| { + h.output() + .shapes + .iter() + .filter(|c| match &c.shape { + egui::Shape::Path(p) => { + p.points.len() == 17 + && p.stroke.width == 1.5 + && p.stroke.color == egui::epaint::ColorMode::Solid(accent) + && p.points.iter().all(|q| q.distance(at) < 40.0) + } + _ => false, + }) + .count() + }; + let outside = xf.to_screen((32.0 - tol * 1.5) as f32, (32.0 - tol * 1.5) as f32); + + // A box with no preview (its overlay is what draws the arrow otherwise). + h.state_mut().transform_preview = None; + h.hover_at(outside); + h.run_steps(3); + assert!(h.state().ui.transform.is_some() && h.state().transform_preview.is_none()); + assert_eq!(h.output().platform_output.cursor_icon, CursorIcon::None, "the OS pointer is hidden in the rotate zone"); + assert_eq!(arrows(&h, outside), 1, "and the curved arrow is drawn in its place"); + + let inside = xf.to_screen(96.0, 96.0); + h.hover_at(inside); + h.run_steps(3); + assert_eq!(arrows(&h, inside), 0, "no arrow over the box"); +} + +/// The resize arrows follow the box's turn and the view's rotation and flip: each handle +/// shows the arrow it resizes along on screen, not the one it had on the upright box. +#[test] +fn resize_cursors_turn_with_the_box_and_the_view() { + use CursorIcon::{ResizeHorizontal as H, ResizeNeSw as NeSw, ResizeNwSe as NwSe, ResizeVertical as V}; + // Box turned (degrees), view rotation, flip → corner 0, corner 1, edge 0, edge 1 (corner + // and edge i + 2 sit opposite, on the same axis). + let cases = [ + (0.0, 0.0, false, [NwSe, NeSw, V, H]), + (90.0, 0.0, false, [NeSw, NwSe, H, V]), + (45.0, 0.0, false, [V, H, NeSw, NwSe]), + (0.0, 0.0, true, [NeSw, NwSe, V, H]), + (0.0, 90.0, false, [NeSw, NwSe, H, V]), + ]; + for (deg, view, flip, want) in cases { + let mut app = app_with_square(256, photocraft_geom::Rect::new(64, 96, 192, 160)); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let view_index = app.session.active_index().unwrap(); + app.ui.views[view_index].rotation = view; + app.ui.view.flip_horizontal = flip; + let t = app.ui.transform.as_mut().unwrap(); + let (s, c) = f64::to_radians(deg).sin_cos(); + let o = [128.0, 128.0]; + t.quad = t.quad.map(|[x, y]| [o[0] + (x - o[0]) * c - (y - o[1]) * s, o[1] + (x - o[0]) * s + (y - o[1]) * c]); + let t = app.ui.transform.clone().unwrap(); + let xf = ViewXform::active(&app).unwrap(); + let mid = |i: usize| [(t.quad[i][0] + t.quad[(i + 1) % 4][0]) / 2.0, (t.quad[i][1] + t.quad[(i + 1) % 4][1]) / 2.0]; + let got: Vec<_> = (0..4).map(|i| cursor(&app, &xf, t.quad[i], false)).chain((0..4).map(|i| cursor(&app, &xf, mid(i), false))).collect(); + let want = [want[0], want[1], want[0], want[1], want[2], want[3], want[2], want[3]].map(Some); + assert_eq!(got, want, "box {deg}°, view {view}°, flip {flip}"); + } +} + +/// The corners of a wide or tall box show the diagonal arrows, as in Photoshop, not the +/// horizontal or vertical one its long diagonal is nearest to. +#[test] +fn corner_cursors_stay_diagonal_on_a_long_box() { + use CursorIcon::{ResizeNeSw as NeSw, ResizeNwSe as NwSe}; + for rect in [photocraft_geom::Rect::new(8, 112, 248, 144), photocraft_geom::Rect::new(112, 8, 144, 248)] { + let mut app = app_with_square(256, rect); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let t = app.ui.transform.clone().unwrap(); + let xf = ViewXform::active(&app).unwrap(); + let got: Vec<_> = (0..4).map(|i| cursor(&app, &xf, t.quad[i], false)).collect(); + assert_eq!(got, [NwSe, NeSw, NwSe, NeSw].map(Some), "{rect:?}"); + } +} + +/// A warp split's arrow crosses the split line as it looks on screen: it turns with a turned +/// grid (Warp entered on a rotated box) and with a rotated view. +#[test] +fn warp_split_cursors_turn_with_the_grid_and_the_view() { + use CursorIcon::{ResizeHorizontal as H, ResizeNeSw as NeSw, ResizeNwSe as NwSe, ResizeVertical as V}; + let rect = [0.0, 0.0, 200.0, 100.0]; + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let level = ViewXform { rect: screen, zoom: 1.0, center: [100.0, 50.0], flip: false, rotation: 0.0, aspect: 1.0 }; + // Grid turned (degrees, about its centre), view rotation → Split Vertically, Split Horizontally. + for (grid, view, want) in [(0.0, 0.0, [H, V]), (0.0, 90.0, [V, H]), (90.0, 0.0, [V, H]), (45.0, 0.0, [NwSe, NeSw])] { + let (s, c) = f64::to_radians(grid).sin_cos(); + let m = BezierMesh::identity(rect, 1, 1).map_points(|[x, y]| [100.0 + (x - 100.0) * c - (y - 50.0) * s, 50.0 + (x - 100.0) * s + (y - 50.0) * c]); + let xf = ViewXform { rotation: view, ..level }; + let got = [SplitTool::Vertical, SplitTool::Horizontal].map(|tool| split_cursor(&m, tool, m.param_at([100.0, 50.0]), &xf)); + assert_eq!(got, want, "grid turned {grid}°, view {view}°"); + } + let m = BezierMesh::identity(rect, 1, 1); + assert_eq!(split_cursor(&m, SplitTool::Cross, (0.5, 0.5), &level), CursorIcon::Crosshair); +} + +/// #1767: the readout beside the pointer during a drag (Photoshop's transformation values): +/// the angle while rotating, W/H while scaling, ΔX/ΔY while moving; nothing otherwise. +#[test] +fn the_live_readout_follows_the_drag() { + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + app.ui.extras.snap = false; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + assert_eq!(live_readout(&app), None, "not dragging"); + let ev = |app: &mut PhotocraftApp, e| crate::canvas::tool_event(app, e, egui::Modifiers::NONE); + // A quarter turn about the centre (96, 96): from right of the box to below it. + ev(&mut app, ToolEvent::Down { x: 220.0, y: 96.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 96.0, y: 220.0, pressure: 1.0 }); + let Some(Readout::Angle(a)) = live_readout(&app) else { panic!("{:?}", live_readout(&app)) }; + assert!((a - 90.0).abs() < 1e-6, "{a}"); + ev(&mut app, ToolEvent::Up { x: 96.0, y: 220.0 }); + assert_eq!(live_readout(&app), None, "released"); + let mut app = app_with_square(256, photocraft_geom::Rect::new(32, 32, 160, 160)); + app.ui.extras.snap = false; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + ev(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 65.0, y: 57.0, pressure: 1.0 }); + assert_eq!(live_readout(&app), Some(Readout::Offset([5.0, -3.0]))); + ev(&mut app, ToolEvent::Up { x: 65.0, y: 57.0 }); + // The right edge doubles the width (proportional by default: the height too). + ev(&mut app, ToolEvent::Down { x: 165.0, y: 93.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 293.0, y: 93.0, pressure: 1.0 }); + let Some(Readout::Scale([w, h])) = live_readout(&app) else { panic!("{:?}", live_readout(&app)) }; + assert!((w - 200.0).abs() < 1e-6 && (h - 200.0).abs() < 1e-6, "{w} {h}"); +} + +#[test] +fn a_distort_corner_stops_before_the_box_folds_over() { + // #1323: dragging a corner across the opposite diagonal stops short of it, so the box + // stays convex instead of folding into a bow tie. + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.ui.extras.snap = false; + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "edit.transform.distort", json!({})).unwrap(); + let q0 = app.ui.transform.as_ref().unwrap().quad; + // Top-left far past the bottom-right corner. + press_drag(&mut app, q0[0], [60.0, 60.0], egui::Modifiers::NONE); + let q = app.ui.transform.as_ref().unwrap().quad; + let sign = turns(&q0)[0].signum(); + assert!(turns(&q).iter().all(|t| t * sign > 0.0), "still convex: {q:?}"); + assert_eq!([q[1], q[2], q[3]], [q0[1], q0[2], q0[3]], "the other corners stay put"); + // It went as far as it could along the drag: up to the TR–BL diagonal (x + y = 32). + assert!(q[0][0] > 15.0 && q[0][0] < 16.0 && (q[0][0] - q[0][1]).abs() < 1e-6, "{q:?}"); + // A drag that keeps the box convex is not held back. + press_drag(&mut app, q[0], [2.0, 4.0], egui::Modifiers::NONE); + assert_eq!(app.ui.transform.as_ref().unwrap().quad[0], [2.0, 4.0]); +} + +#[test] +fn keep_convex_leaves_a_degenerate_start_alone() { + let flat = [[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [3.0, 0.0]]; + let to = [[5.0, 5.0], [1.0, 0.0], [2.0, 0.0], [3.0, 0.0]]; + assert_eq!(keep_convex(flat, to), to); + let nan = [[f64::NAN, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]; + let _ = keep_convex(nan, to); +} + +#[test] +fn the_legacy_preference_swaps_corner_proportions_and_stretches_edges() { + let none = egui::Modifiers::NONE; + let corner = Hit::Corner(1); + let edge = Hit::Edge(1); + // Default: proportional (⇧ frees), so the drag keeps its keys. + assert!(!legacy_mods(false, corner, none).shift); + assert!(!legacy_mods(false, edge, none).shift); + // Legacy: corners free by default, ⇧ keeps proportions; edges always stretch one axis; + // ⌘ gestures are left alone. + assert!(legacy_mods(true, corner, none).shift); + assert!(!legacy_mods(true, corner, egui::Modifiers::SHIFT).shift); + assert!(legacy_mods(true, edge, none).shift); + assert!(legacy_mods(true, edge, egui::Modifiers::SHIFT).shift); + assert!(!legacy_mods(true, corner, egui::Modifiers::COMMAND).shift); + assert!(!legacy_mods(true, edge, egui::Modifiers::COMMAND).shift); + // Through the box: a plain corner drag, then a plain right-edge drag, on a 16×16 square. + for (legacy, proportional) in [(false, true), (true, false)] { + for at_edge in [false, true] { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.ui.extras.snap = false; + app.session.prefs.edit(|p| p.general.use_legacy_free_transform = legacy); + begin(&mut app, &egui::Context::default()).unwrap(); + let q0 = app.ui.transform.as_ref().unwrap().quad; + let from = if at_edge { [q0[1][0], (q0[1][1] + q0[2][1]) / 2.0] } else { q0[2] }; + press_drag(&mut app, from, [from[0] + 16.0, from[1]], none); + let q = app.ui.transform.as_ref().unwrap().quad; + let (w, h) = (q[2][0] - q[0][0], q[2][1] - q[0][1]); + assert_eq!((w - h).abs() < 1e-6, proportional, "legacy {legacy}, edge {at_edge}: {w} × {h}"); + } + } +} + +/// #4174: turning off the options bar's Maintain Aspect Ratio link frees the handles too, as in +/// Photoshop: a plain corner or edge drag stretches one way, ⇧ keeps the proportions. Linked +/// (the default) is unchanged, and so is the legacy preference. +#[test] +fn the_aspect_link_decides_whether_handle_drags_keep_proportions() { + let (none, shift) = (egui::Modifiers::NONE, egui::Modifiers::SHIFT); + for (unlinked, legacy, mods, proportional) in + [(false, false, none, true), (true, false, none, false), (true, false, shift, true), (true, true, none, false)] + { + for at_edge in [false, true] { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.ui.extras.snap = false; + app.ui.transform_unlinked = unlinked; + app.session.prefs.edit(|p| p.general.use_legacy_free_transform = legacy); + begin(&mut app, &egui::Context::default()).unwrap(); + let q0 = app.ui.transform.as_ref().unwrap().quad; + let from = if at_edge { [q0[1][0], (q0[1][1] + q0[2][1]) / 2.0] } else { q0[2] }; + press_drag(&mut app, from, [from[0] + 16.0, from[1]], mods); + let q = app.ui.transform.as_ref().unwrap().quad; + let (w, h) = (q[2][0] - q[0][0], q[2][1] - q[0][1]); + let case = format!("unlinked {unlinked}, legacy {legacy}, shift {}, edge {at_edge}: {w} × {h}", mods.shift); + if legacy && at_edge { + // Legacy edges always stretch their one axis. + assert!((w - 32.0).abs() < 1e-6 && (h - 16.0).abs() < 1e-6, "{case}"); + } else { + assert_eq!((w - h).abs() < 1e-6, proportional, "{case}"); + assert!((w - 32.0).abs() < 1e-6, "{case}"); + } + } + } + // ⌘ gestures (skew, distort) are left alone. + assert!(!unlinked_mods(true, false, Hit::Corner(0), egui::Modifiers::COMMAND).shift); + assert!(!unlinked_mods(true, false, Hit::Inside, none).shift); +} + +#[test] +fn right_click_while_transforming_switches_the_mode() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let ctx = egui::Context::default(); + begin(&mut app, &ctx).unwrap(); + assert!(crate::canvas_tool_menu::open_transform(&mut app, &ctx, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + let ids: Vec<&str> = crate::canvas_tool_menu::rows(&menu).iter().flatten().map(|e| e.1).collect(); + assert!(ids.contains(&"edit.transform.distort") && ids.contains(&"edit.freeTransform")); + crate::canvas_tool_menu::choose(&mut app, &ctx, "edit.transform.distort"); + assert_eq!(app.ui.transform.as_ref().unwrap().mode, TransformMode::Distort); +} + +#[test] +fn right_click_menu_warp_row_enters_warp_mode() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let ctx = egui::Context::default(); + begin(&mut app, &ctx).unwrap(); + assert!(crate::canvas_tool_menu::open_transform(&mut app, &ctx, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(crate::canvas_tool_menu::rows(&menu).iter().flatten().any(|e| e.1 == "edit.transform.warp")); + assert!(crate::canvas_tool_menu::available(&app, &menu, "edit.transform.warp")); + // Only the current mode (Free Transform) is checked: not Scale, Rotate or Warp. + let checked: Vec<&str> = + crate::canvas_tool_menu::rows(&menu).iter().flatten().map(|e| e.1).filter(|id| crate::canvas_tool_menu::mode_checked(&app, &menu, id)).collect(); + assert_eq!(checked, ["edit.freeTransform"]); + crate::canvas_tool_menu::choose(&mut app, &ctx, "edit.transform.warp"); + assert!(app.ui.transform.as_ref().unwrap().warp.is_some()); + // Already warping: the row is no longer offered. + assert!(!crate::canvas_tool_menu::available(&app, &menu, "edit.transform.warp")); +} + +#[test] +fn right_click_menu_offers_warp_for_a_path() { + // Photoshop's Transform Path menu has Warp too (#3027). + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let ctx = egui::Context::default(); + begin(&mut app, &ctx).unwrap(); + app.ui.transform.as_mut().unwrap().path = Some(json!({})); + assert!(crate::canvas_tool_menu::open_transform(&mut app, &ctx, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(crate::canvas_tool_menu::available(&app, &menu, "edit.transform.warp")); +} + +fn app_with_square(size: u32, fill: photocraft_geom::Rect) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": size, "height": size})).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(fill, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + app +} + +/// #2439: a layer under others keeps its place in the stack while the box is open. The +/// canvas under the box shows only the layers below it; the ones over it are composited on +/// their own and drawn over the moving pixels. +#[test] +fn free_transform_keeps_the_layer_under_the_layers_over_it() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let red = app.session.active().unwrap().active_layer.unwrap(); + 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(16, 16, 40, 40), &[0.0, 0.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + let blue = app.session.active().unwrap().active_layer.unwrap(); + let bg = app.session.active().unwrap().doc.layers[0].id; + app.session.execute("layer.select", json!({"layer": red.0})).unwrap(); + let ctx = gpu_ctx(); + begin(&mut app, &ctx).unwrap(); + let pv = app.transform_preview.as_ref().unwrap(); + assert!(pv.doc.layer(bg).unwrap().visible, "the layers below show under the box"); + assert!(!pv.doc.layer(blue).unwrap().visible, "the layer over it is drawn over the box instead"); + let (texture, rect) = pv.above.as_ref().and_then(|a| a.shown.as_ref()).expect("something covers the layer"); + assert_eq!(*rect, photocraft_geom::Rect::new(16, 16, 40, 40)); + assert_eq!(texture.size(), [24, 24]); + cancel(&mut app); + + // The top layer: nothing to draw over it. + app.session.execute("layer.select", json!({"layer": blue.0})).unwrap(); + begin(&mut app, &ctx).unwrap(); + let pv = app.transform_preview.as_ref().unwrap(); + assert!(pv.above.as_ref().is_some_and(|a| a.shown.is_none())); + assert!(pv.doc.layer(red).unwrap().visible && pv.doc.layer(bg).unwrap().visible); + cancel(&mut app); +} + +#[test] +fn plain_layers_from_the_top_cover_the_moving_one() { + use photocraft_color::BlendMode; + use photocraft_doc::Layer; + let px = |name: &str| Layer::raster(name, photocraft_color::PixelFormat::RGBA8); + let covers = |layers: &[Layer], id: LayerId| { + let mut out = Vec::new(); + covering(layers, id, &mut out); + out + }; + // In a group: the group's layers over it, then the ones over the group; never the layers + // clipped to it. + let (below, target, mut clip, inner_top, top) = (px("below"), px("target"), px("clip"), px("inner top"), px("top")); + clip.clipped = true; + let (t, c, inner, tp) = (target.id, clip.id, inner_top.id, top.id); + let mut layers = vec![below, Layer::group("group", vec![target, clip, inner_top]), top]; + assert_eq!(covers(&layers, t), [tp, inner]); + 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], 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]; + assert_eq!(vis(&under), [true, true, false]); + let mut over = layers.clone(); + show_only(&mut over, &above.ids); + assert_eq!(vis(&over), [false, true, true]); + let inside: Vec = match &over[1].content { + LayerContent::Group(g) => g.children.iter().map(|l| l.visible).collect(), + _ => Vec::new(), + }; + assert_eq!(inside, [false, false, true]); + + // A layer that blends with what is under it stops the search: it and everything under it + // stay in the document under the box. + layers[2].blend = BlendMode::Multiply; + assert!(covers(&layers, t).is_empty()); + layers[2].blend = BlendMode::Normal; + let mut multiply = px("multiply"); + multiply.blend = BlendMode::Multiply; + layers.insert(2, multiply); + assert_eq!(covers(&layers, t), [tp]); + // A group that isn't Normal or Pass Through keeps what is inside it. + layers[1].blend = BlendMode::Screen; + layers.remove(2); + assert_eq!(covers(&layers, t), [tp]); + assert_eq!(covers(&layers, LayerId::fresh()), [tp], "not in the stack: down to the first layer that isn't plain"); +} + +/// A context that reports a real GPU's texture limit (the default reports 2048). +fn gpu_ctx() -> egui::Context { + let ctx = egui::Context::default(); + // Clear the font atlas delta: epaint panics on dropping unapplied deltas in debug builds. + let mut out = ctx.run_ui(egui::RawInput { max_texture_side: Some(16384), ..Default::default() }, |_| {}); + out.textures_delta.clear(); + ctx +} + +#[test] +fn preview_texture_is_full_resolution() { + // #91: the preview used to be sampled down to 2048 px, so big layers looked blurry at 100%. + let mut app = app_with_square(3000, photocraft_geom::Rect::new(10, 20, 2810, 2420)); + let ctx = gpu_ctx(); + begin(&mut app, &ctx).unwrap(); + let pv = app.transform_preview.as_ref().unwrap(); + assert_eq!(pv.texture.size(), [2800, 2400], "one texel per layer pixel"); + // At 100% the texture has at least as many texels as the box covers screen pixels. + let t = app.ui.transform.as_ref().unwrap(); + assert!(pv.texture.size()[0] as f64 >= t.rect[2] - t.rect[0]); +} + +#[test] +fn nested_group_preview_excludes_its_siblings() { + use photocraft_color::PixelFormat; + use photocraft_doc::Layer; + + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let target_pixels = doc.layers.pop().unwrap(); + let mut sibling = Layer::raster("sibling", PixelFormat::RGBA8); + sibling.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(12, 12, 20, 20), &[0.0, 0.0, 1.0, 1.0]); + let target = Layer::group("target", vec![target_pixels]); + let target_id = target.id; + doc.layers.push(Layer::group("parent", vec![target, sibling])); + + let (image, _) = preview_image(&st.doc, target_id, None, photocraft_geom::Rect::new(8, 8, 24, 24), 4096, false); + assert_eq!( + image.pixels[8 * image.size[0] + 8], + Color32::from_rgb(255, 0, 0), + "a sibling in the parent group must not be baked into the moving texture" + ); +} + +fn artboard_preview_app(background: photocraft_doc::ArtboardBackground) -> (PhotocraftApp, LayerId, LayerId) { + use photocraft_doc::{Artboard, Layer}; + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let red = doc.layers.pop().unwrap(); + let red_id = red.id; + let mut blue = Layer::raster("covering blue", photocraft_color::PixelFormat::RGBA8); + blue.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(16, 16, 40, 40), &[0.0, 0.0, 1.0, 1.0]); + let mut board = Layer::group("board", vec![red, blue]); + let board_id = board.id; + if let LayerContent::Group(g) = &mut board.content { + let mut ab = Artboard::new(photocraft_geom::Rect::new(0, 0, 64, 64)); + ab.background = background; + g.artboard = Some(ab); + } + doc.layers = vec![board]; + (app, board_id, red_id) +} + +#[test] +fn artboard_transform_overlay_does_not_cover_moving_pixels_with_the_board_background() { + use photocraft_doc::ArtboardBackground; + for background in [ArtboardBackground::White, ArtboardBackground::Black] { + let (mut app, board_id, red_id) = artboard_preview_app(background); + let original = app.session.active().unwrap().doc.clone(); + begin(&mut app, &gpu_ctx()).unwrap(); + let pv = app.transform_preview.as_ref().unwrap(); + let (texture, rect) = pv.above.as_ref().unwrap().shown.as_ref().unwrap(); + let (image, _) = texture.level_image(0).unwrap(); + let at = |x: i32, y: i32| image.pixels[(y - rect.y0) as usize * image.size[0] + (x - rect.x0) as usize]; + assert_eq!(at(12, 12), Color32::TRANSPARENT, "the board background belongs under the moving layer"); + assert_eq!(at(20, 20), Color32::BLUE, "covering siblings must still cover the moving layer"); + let under = photocraft_compose::render(&pv.doc, photocraft_geom::Rect::new(0, 0, 64, 64)); + assert_eq!(under.px[12 * 64 + 12], background.rgba().unwrap(), "the board background remains on the base canvas"); + assert!(!pv.doc.layer(red_id).unwrap().visible); + cancel(&mut app); + let LayerContent::Group(g) = &app.session.active().unwrap().doc.layer(board_id).unwrap().content else { panic!("board") }; + assert_eq!(g.artboard.as_ref().unwrap().background, background); + assert!(Arc::ptr_eq(&app.session.active().unwrap().doc, &original), "preview and cancellation do not edit the document"); + } +} + +#[test] +fn artboard_solo_preview_keeps_holes_transparent_and_the_board_clip() { + use photocraft_doc::ArtboardBackground; + let (app, board_id, red_id) = artboard_preview_app(ArtboardBackground::White); + let original = &app.session.active().unwrap().doc; + let mut solo = (**original).clone(); + solo.layer_mut(red_id).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(-2, -2, 1, 1), &[1.0, 0.0, 0.0, 1.0]); + solo_layer(&mut solo.layers, red_id); + let b = photocraft_geom::Rect::new(-2, -2, 66, 66); + let rendered = photocraft_compose::render(&solo, b); + let at = |x: i32, y: i32| rendered.px[(y + 2) as usize * 68 + (x + 2) as usize]; + assert_eq!(at(12, 12), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(at(30, 30), [0.0; 4], "neither the board's white nor another child enters the moving texture"); + assert_eq!(at(-1, -1), [0.0; 4], "the artboard still clips its children"); + let LayerContent::Group(g) = &solo.layer(board_id).unwrap().content else { panic!("board") }; + assert!(g.artboard.is_some(), "keep the board boundary while omitting its background"); +} + +#[test] +fn artboard_moved_as_a_whole_keeps_its_background() { + use photocraft_doc::ArtboardBackground; + let (app, board_id, _) = artboard_preview_app(ArtboardBackground::Black); + let mut doc = (*app.session.active().unwrap().doc).clone(); + solo_layer(&mut doc.layers, board_id); + let rendered = photocraft_compose::render(&doc, photocraft_geom::Rect::new(0, 0, 64, 64)); + assert_eq!(rendered.px[50 * 64 + 50], [0.0, 0.0, 0.0, 1.0]); + show_only(&mut doc.layers, &[board_id]); + let rendered = photocraft_compose::render(&doc, photocraft_geom::Rect::new(0, 0, 64, 64)); + assert_eq!(rendered.px[50 * 64 + 50], [0.0, 0.0, 0.0, 1.0], "a whole covering artboard keeps its own background"); +} + +#[test] +fn nested_group_preview_detaches_every_clipped_ancestor() { + use photocraft_color::PixelFormat; + use photocraft_doc::Layer; + + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let st = app.session.active_mut().unwrap(); + let doc = Arc::make_mut(&mut st.doc); + let target_pixels = doc.layers.pop().unwrap(); + let target = Layer::group("target", vec![target_pixels]); + let target_id = target.id; + let mut middle = Layer::group("middle clipped ancestor", vec![target]); + middle.clipped = true; + let mut inner_base = Layer::raster("hidden inner clipping base", PixelFormat::RGBA8); + inner_base.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 64, 64), &[0.0, 0.0, 1.0, 1.0]); + let mut outer = Layer::group("outer clipped ancestor", vec![inner_base, middle]); + outer.clipped = true; + doc.layers.push(outer); + + let (image, _) = preview_image(&st.doc, target_id, None, photocraft_geom::Rect::new(8, 8, 24, 24), 4096, false); + assert_eq!(image.pixels[8 * image.size[0] + 8], Color32::from_rgb(255, 0, 0), "hidden clipping bases must not make a nested target disappear"); +} + +#[test] +fn unknown_preview_target_keeps_the_previous_document_fallback() { + let app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let st = app.session.active().unwrap(); + let (image, _) = preview_image(&st.doc, LayerId::fresh(), None, photocraft_geom::Rect::new(8, 8, 24, 24), 4096, false); + assert_eq!(image.pixels[8 * image.size[0] + 8], Color32::from_rgb(255, 0, 0)); +} + +/// The textured meshes `draw_content` paints for the moving pixels (not the box or handles). +fn preview_meshes(app: &PhotocraftApp, xf: &ViewXform) -> Vec { + let ctx = gpu_ctx(); + let mut out = ctx.run_ui(egui::RawInput { max_texture_side: Some(16384), ..Default::default() }, |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::background()); + draw_content(app, &painter, xf); + }); + out.textures_delta.clear(); + out.shapes + .into_iter() + .filter_map(|s| match s.shape { + egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => Some((*m).clone()), + _ => None, + }) + .collect() +} + +#[test] +fn preview_pixels_past_the_canvas_are_hidden() { + // #2027: a box scaled past the canvas drew its pixels over the pasteboard. + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 56, 56)); + begin(&mut app, &gpu_ctx()).unwrap(); + scale_about_pivot(&mut app, 2.0, 2.0); + let q = app.ui.transform.as_ref().unwrap().quad; + assert!(q[0][0] < -10.0 && q[2][1] > 74.0, "the box reaches past the canvas: {q:?}"); + let tol = 1e-3; + for (rotation, flip) in [(0.0, false), (30.0, false), (-75.0, true)] { + let xf = ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0)), + zoom: 2.0, + center: [32.0, 32.0], + flip, + rotation, + aspect: 1.0, + }; + let meshes = preview_meshes(&app, &xf); + let verts: Vec<[f64; 2]> = meshes.iter().flat_map(|m| m.vertices.iter().map(|v| xf.to_doc(v.pos))).collect(); + assert!(!verts.is_empty(), "the preview still draws (rotation {rotation})"); + for d in &verts { + assert!(d[0] >= -tol && d[1] >= -tol && d[0] <= 64.0 + tol && d[1] <= 64.0 + tol, "vertex {d:?} off the canvas (rotation {rotation})"); + } + // The clipped mesh still covers the whole canvas: the corners lie on it. + for corner in [[0.0, 0.0], [64.0, 0.0], [64.0, 64.0], [0.0, 64.0]] { + assert!(verts.iter().any(|d| (d[0] - corner[0]).abs() < 1e-2 && (d[1] - corner[1]).abs() < 1e-2), "corner {corner:?} (rotation {rotation})"); + } + } + // Inside the canvas the mesh is drawn unchanged (24×24 grid). + cancel(&mut app); + begin(&mut app, &gpu_ctx()).unwrap(); + let xf = ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(200.0, 200.0)), + zoom: 1.0, + center: [32.0, 32.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + }; + let meshes = preview_meshes(&app, &xf); + assert_eq!(meshes.iter().map(|m| m.vertices.len()).sum::(), 25 * 25); +} + +#[test] +fn shift_body_drag_locks_to_eight_directions_and_switches() { + let mut s = session(); + let g = Gesture { hit: Hit::Inside, start: [40.0, 20.0], quad0: s.quad, pivot0: s.pivot }; + apply_drag(&mut s, g, [60.0, 23.0], egui::Modifiers::SHIFT); + assert!(close(s.quad, corners([20.0, 0.0, 120.0, 50.0])), "horizontal: {:?}", s.quad); + apply_drag(&mut s, g, [60.0, 39.0], egui::Modifiers::SHIFT); + assert!((s.quad[0][0] - s.quad[0][1]).abs() < 1e-9 && s.quad[0][0] > 15.0, "diagonal: {:?}", s.quad[0]); + apply_drag(&mut s, g, [41.0, 60.0], egui::Modifiers::SHIFT); + assert!(close(s.quad, corners([0.0, 40.0, 100.0, 90.0])), "vertical: {:?}", s.quad); +} + +#[test] +fn alt_click_moves_the_reference_point_and_edges_skew() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let ctx = egui::Context::default(); + begin(&mut app, &ctx).unwrap(); + assert!(pointer(&mut app, ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::ALT)); + pointer(&mut app, ToolEvent::Up { x: 40.0, y: 40.0 }, egui::Modifiers::ALT); + let t = app.ui.transform.as_ref().unwrap(); + assert_eq!(t.pivot, [40.0, 40.0]); + assert_eq!(t.quad, corners(t.rect), "the box didn't move"); + // ⌘ on an edge skews: both corners of the top edge move. + let mut s = session(); + drag(&mut s, [50.0, 0.0], [70.0, 5.0], egui::Modifiers::COMMAND); + assert_eq!((s.quad[0], s.quad[1], s.quad[2]), ([20.0, 5.0], [120.0, 5.0], [100.0, 50.0])); + // ⌘⇧: only along the edge. + let mut s = session(); + drag(&mut s, [50.0, 0.0], [70.0, 5.0], egui::Modifiers::COMMAND | egui::Modifiers::SHIFT); + assert_eq!((s.quad[0], s.quad[1]), ([20.0, 0.0], [120.0, 0.0])); + // ⌘⌥⇧ on a corner: perspective (the paired corner mirrors). + let mut s = session(); + drag(&mut s, [100.0, 0.0], [101.0, -10.0], egui::Modifiers::COMMAND | egui::Modifiers::ALT | egui::Modifiers::SHIFT); + assert_eq!((s.quad[1], s.quad[2]), ([100.0, -10.0], [100.0, 60.0])); +} + +/// `cargo test --release -p photocraft-ui-egui transform_preview_bench -- --ignored --nocapture` +#[test] +#[ignore] +fn transform_preview_bench() { + let (w, h) = (6000, 4000); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": w, "height": h})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.execute("filter.render.clouds", json!({})).unwrap(); + let ctx = gpu_ctx(); + let t0 = std::time::Instant::now(); + begin(&mut app, &ctx).unwrap(); + let begin_ms = t0.elapsed().as_secs_f64() * 1e3; + // The same with a linked layer mask applied to the texels (#205). + cancel(&mut app); + app.session.execute("layer.layerMask.revealAll", json!({})).unwrap(); + app.session.execute("paint.gradient", json!({"from": [0, 0], "to": [w, 0], "colors": ["#000000", "#ffffff"], "target": "mask"})).unwrap(); + let t0 = std::time::Instant::now(); + begin(&mut app, &ctx).unwrap(); + let masked_ms = t0.elapsed().as_secs_f64() * 1e3; + eprintln!("transform preview begin {w}x{h}: {begin_ms:.1} ms, with a linked mask {masked_ms:.1} ms"); + let size = app.transform_preview.as_ref().unwrap().texture.size(); + rotate_about_pivot(&mut app, 0.05); + let frame = |zoom: f32| { + let t0 = std::time::Instant::now(); + let _ = ctx.run_ui(egui::RawInput { max_texture_side: Some(16384), ..Default::default() }, |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::background()); + let xf = ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 1000.0)), + zoom, + center: [3000.0, 2000.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + }; + draw_content(&app, &painter, &xf); + draw_overlay(&app, &painter, &xf); + }); + t0.elapsed().as_secs_f64() * 1e3 + }; + let first: Vec = [1.0, 0.25, 3.0].iter().map(|z| frame(*z)).collect(); + let n = 50; + let steady = (0..n).map(|i| frame([1.0, 0.25, 3.0][i % 3])).sum::() / n as f64; + eprintln!( + "transform preview {w}x{h}: texture {size:?}, begin {begin_ms:.1} ms, first frame per level (1x, 0.25x, 3x) {first:.1?} ms, steady frame {steady:.3} ms" + ); +} + +#[test] +fn transform_selection_moves_only_the_outline() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap(); + let px0 = app.session.active().unwrap().doc.layers[0].surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 64, 64)); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "select.transformSelection", json!({})).unwrap(); + let t = app.ui.transform.as_ref().unwrap(); + assert!(t.selection && t.rect == [8.0, 8.0, 24.0, 24.0]); + assert!(app.transform_preview.as_ref().unwrap().doc.selection.is_none(), "ants hidden while transforming"); + scale_about_pivot(&mut app, 2.0, 2.0); + commit(&mut app); + let st = app.session.active().unwrap(); + let b = st.doc.selection.as_ref().unwrap().content_bounds(); + assert!(b.width().abs_diff(32) <= 2 && b.x0.abs_diff(0) <= 1, "{b:?}"); + assert_eq!(st.doc.layers[0].surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 64, 64)), px0); +} + +#[test] +fn warp_mode_drags_anchor_with_handles_splits_and_commits() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 32, 32), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let ctx = egui::Context::default(); + begin_warp(&mut app, &ctx).unwrap(); + let w = app.ui.transform.as_ref().unwrap().warp.clone().unwrap(); + assert!(w.is_identity()); + // Drag the bottom-right anchor (point 15) by (+10, +6): its two handles follow. + warp_pointer(&mut app, ToolEvent::Down { x: 32.0, y: 32.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); + warp_pointer(&mut app, ToolEvent::Up { x: 42.0, y: 38.0 }, 2.0, egui::Modifiers::NONE); + let m = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.clone().unwrap(); + assert_eq!(m.points[15], [42.0, 38.0]); + let near = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9; + assert!(near(m.points[14], [24.0 + 10.0, 38.0]), "{:?}", m.points[14]); + assert!(near(m.points[11], [42.0, 24.0 + 6.0]), "{:?}", m.points[11]); + split(&mut app, "edit.transform.splitWarpCrosswise", None).unwrap(); + let split_m = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.as_ref().unwrap(); + assert_eq!(split_m.points.last().copied(), Some([42.0, 38.0]), "the corner survives the cut"); + assert!(split_m.us.iter().any(|u| (u - 1.0 / 3.0).abs() < 1e-6) && split_m.us.iter().any(|u| (u - 0.5).abs() < 1e-6)); + commit(&mut app); + let st = app.session.active().unwrap(); + let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); + assert!(b.x1 >= 41 && b.y1 >= 37, "{b:?}"); + assert!(app.ui.transform.is_none()); + // Toggling back to the box drops the warp. + begin_warp(&mut app, &ctx).unwrap(); + leave_warp(&mut app); + assert!(app.ui.transform.as_ref().unwrap().warp.is_none()); +} + +#[test] +fn a_thin_layer_scaled_then_warped_commits_the_curve() { + // #5793: a 3 px column stretched wide, switched to Warp and pulled down in the middle. + // The commit came out straight: the warp's grid was one cell across the 3 source pixels. + let mut app = app_with_square(128, photocraft_geom::Rect::new(40, 20, 43, 60)); + let ctx = egui::Context::default(); + begin(&mut app, &ctx).unwrap(); + scale_about_pivot(&mut app, 30.0, 1.0); + enter_warp(&mut app, &ctx); + warp_pointer(&mut app, ToolEvent::Down { x: 41.5, y: 40.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); + warp_pointer(&mut app, ToolEvent::Move { x: 41.5, y: 70.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); + warp_pointer(&mut app, ToolEvent::Up { x: 41.5, y: 70.0 }, 2.0, egui::Modifiers::NONE); + 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] + }; + // The middle sags below the band's old bottom edge (y 60); the ends stay put. + assert!(alpha(41, 70) > 0.99, "middle {}", alpha(41, 70)); + assert!(alpha(15, 70) < 0.01 && alpha(15, 40) > 0.99, "end {} {}", alpha(15, 70), alpha(15, 40)); +} + +fn warping_square() -> PhotocraftApp { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 32, 32)); + begin_warp(&mut app, &egui::Context::default()).unwrap(); + app +} + +fn warp_mesh(app: &PhotocraftApp) -> BezierMesh { + app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().mesh.clone().unwrap() +} + +#[test] +fn warp_drag_from_inside_the_grid_pulls_the_surface_under_the_pointer() { + let mut app = warping_square(); + let before = warp_mesh(&app); + // (20, 20) is mid-cell, far from every anchor and handle. + warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); + assert!(matches!(app.transform_preview.as_ref().unwrap().warp_drag, Some(WarpDrag::Surface { .. }))); + warp_pointer(&mut app, ToolEvent::Move { x: 30.0, y: 14.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); + warp_pointer(&mut app, ToolEvent::Up { x: 30.0, y: 14.0 }, 2.0, egui::Modifiers::NONE); + let after = warp_mesh(&app); + let (s, t) = surface_at(&before, [20.0, 20.0]).unwrap(); + let moved = after.eval(s, t); + assert!((moved[0] - 30.0).abs() < 1e-6 && (moved[1] - 14.0).abs() < 1e-6, "{moved:?}"); + assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_none()); + // The picture keeps filling its frame: a pull in the middle leaves the box corners put. + assert!([0, 3, 12, 15].iter().all(|k| after.points[*k] == before.points[*k])); + assert!(after.points[5] != before.points[5], "the inside of the grid moved"); +} + +/// #7885: a surface drag (a press inside a cell, on no anchor or handle) commits exactly as +/// the preview draws it. The layer is a gradient whose colour encodes where each pixel came +/// from, so every committed pixel says which source point landed there; the preview puts +/// source point `p` at `warp.map(p)`, and the commit must agree. +#[test] +fn warp_surface_drag_commits_as_previewed() { + const N: i32 = 96; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": N, "height": N})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + let code = |x: f64, y: f64| [x / (N - 1) as f64, y / (N - 1) as f64]; + app.session + .edit("paint", |doc, a| { + let s = doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap(); + for y in 0..N { + for x in 0..N { + let [r, g] = code(x as f64, y as f64); + s.write_pixel(x, y, &[r as f32, g as f32, 0.5, 1.0]); + } + } + Ok(()) + }) + .unwrap(); + begin_warp(&mut app, &egui::Context::default()).unwrap(); + let (start, end) = ([30.0, 30.0], [39.0, 25.0]); + // A press well inside the top-left cell: a surface drag, not a point drag. + warp_pointer(&mut app, ToolEvent::Down { x: start[0], y: start[1], pressure: 1.0 }, 2.0, egui::Modifiers::NONE); + assert!(matches!(app.transform_preview.as_ref().unwrap().warp_drag, Some(WarpDrag::Surface { .. }))); + warp_pointer(&mut app, ToolEvent::Move { x: end[0], y: end[1], pressure: 1.0 }, 2.0, egui::Modifiers::NONE); + warp_pointer(&mut app, ToolEvent::Up { x: end[0], y: end[1] }, 2.0, egui::Modifiers::NONE); + // What the preview draws: the mapping of the warp the session holds. + let previewed = app.ui.transform.as_ref().unwrap().warp.clone().unwrap(); + let landed = previewed.map(start[0], start[1]); + assert!((landed.0 - end[0]).abs() < 1e-6 && (landed.1 - end[1]).abs() < 1e-6, "the grabbed point follows the pointer: {landed:?}"); + 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 from = |x: f64, y: f64| { + let mut p = [0.0f32; 4]; + s.read_pixel(x.round() as i32, y.round() as i32, &mut p); + [p[0] as f64 * (N - 1) as f64, p[1] as f64 * (N - 1) as f64] + }; + // The grabbed point's pixel moved with the pointer: the drag did not get lost. + let got = from(end[0], end[1]); + assert!((got[0] - start[0]).abs() < 2.0 && (got[1] - start[1]).abs() < 2.0, "pixel at the drop point came from {got:?}, not {start:?}"); + // And everywhere else the committed pixels sit where the preview put them. + for j in 1..12 { + for i in 1..12 { + let src = [i as f64 * 8.0, j as f64 * 8.0]; + let (dx, dy) = previewed.map(src[0], src[1]); + if !(1.0..(N - 2) as f64).contains(&dx) || !(1.0..(N - 2) as f64).contains(&dy) { + continue; + } + let got = from(dx, dy); + assert!((got[0] - src[0]).abs() < 2.0 && (got[1] - src[1]).abs() < 2.0, "{src:?} previewed at {:?} but committed {got:?} there", (dx, dy)); + } + } +} + +#[test] +fn a_handle_belongs_to_the_anchor_it_hangs_off() { + assert_eq!(handle_anchor(0, 1), (0, 0)); + assert_eq!(handle_anchor(0, 2), (0, 3)); + assert_eq!(handle_anchor(1, 0), (0, 0)); + assert_eq!(handle_anchor(5, 3), (6, 3)); + assert_eq!(handle_anchor(3, 3), (3, 3)); +} + +#[test] +fn reset_warp_returns_to_the_untouched_grid_and_keeps_the_session() { + let mut app = warping_square(); + warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); + warp_pointer(&mut app, ToolEvent::Up { x: 30.0, y: 14.0 }, 2.0, egui::Modifiers::NONE); + assert!(!app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().is_identity()); + reset_warp(&mut app); + let w = app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap(); + assert!(w.is_identity(), "back to the untouched box"); + assert_eq!(w.mesh.as_ref().map(|m| (m.us.len(), m.vs.len())), Some((2, 2))); + assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_none()); + // Not warping: nothing to reset. + leave_warp(&mut app); + reset_warp(&mut app); + assert!(app.ui.transform.as_ref().unwrap().warp.is_none()); +} + +#[test] +fn warp_press_outside_the_grid_grabs_nothing() { + let mut app = warping_square(); + let before = warp_mesh(&app); + warp_pointer(&mut app, ToolEvent::Down { x: 55.0, y: 55.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); + assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_none()); + warp_pointer(&mut app, ToolEvent::Up { x: 60.0, y: 60.0 }, 2.0, egui::Modifiers::NONE); + assert_eq!(warp_mesh(&app), before); +} + +#[test] +fn ctrl_click_cuts_the_grid_both_ways() { + let mut app = warping_square(); + let ctrl = egui::Modifiers::COMMAND; + warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, ctrl); + warp_pointer(&mut app, ToolEvent::Up { x: 20.0, y: 20.0 }, 2.0, ctrl); + let m = warp_mesh(&app); + // A cut each way at the pointer (the default grid's rule-of-thirds guides become real + // lines too, as with the Cross split tool). + assert!(m.us.iter().any(|u| (u - 0.5).abs() < 1e-6), "vertical cut: {:?}", m.us); + assert!(m.vs.iter().any(|v| (v - 0.5).abs() < 1e-6), "horizontal cut: {:?}", m.vs); +} + +#[test] +fn replacing_the_warp_mesh_cancels_a_pending_point_drag() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 32, 32)); + let ctx = egui::Context::default(); + begin_warp(&mut app, &ctx).unwrap(); + for _ in 0..3 { + split(&mut app, "edit.transform.splitWarpCrosswise", None).unwrap(); + } + + pointer(&mut app, ToolEvent::Down { x: 32.0, y: 32.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert!(matches!(app.transform_preview.as_ref().unwrap().warp_drag, Some(WarpDrag::Point { .. })), "the anchor drag is armed"); + + split(&mut app, "edit.transform.removeWarpSplit", None).unwrap(); + assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_none(), "the old mesh index is discarded"); + + // A later control-channel move belongs to the old gesture and must be harmless. + pointer(&mut app, ToolEvent::Move { x: 40.0, y: 40.0, pressure: 1.0 }, egui::Modifiers::NONE); +} + +/// A press on a preset warp that misses its points leaves the preset alone (no invisible undo +/// step); grabbing a point turns it into a custom mesh. +#[test] +fn a_press_on_a_preset_warp_converts_it_only_when_it_grabs_the_grid() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 32, 32), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + begin_warp(&mut app, &egui::Context::default()).unwrap(); + let t = app.ui.transform.as_mut().unwrap(); + let preset = Warp::preset(WarpStyle::Arc, 50.0, t.rect); + t.warp = Some(preset.clone()); + // Off the grid altogether: a miss. + warp_pointer(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); + warp_pointer(&mut app, ToolEvent::Up { x: 60.0, y: 60.0 }, 2.0, egui::Modifiers::NONE); + assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref(), Some(&preset), "a miss changes nothing"); + // Inside the grid, away from every point: the surface is grabbed, so the preset converts. + warp_pointer(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, 2.0, egui::Modifiers::NONE); + assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().style, WarpStyle::Custom); + warp_pointer(&mut app, ToolEvent::Up { x: 20.0, y: 20.0 }, 2.0, egui::Modifiers::NONE); + app.ui.transform.as_mut().unwrap().warp = Some(preset.clone()); + let corner = preset.to_mesh(1, 1).points[15]; + warp_pointer(&mut app, ToolEvent::Down { x: corner[0], y: corner[1], pressure: 1.0 }, 2.0, egui::Modifiers::NONE); + assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().style, WarpStyle::Custom); +} + +// ---- Layer masks (#205) ---- + +/// `app_with_square` (red over 8..24) plus a reveal-all mask hiding x < 16. +fn masked_app(linked: bool) -> PhotocraftApp { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.session.execute("layer.layerMask.revealAll", json!({})).unwrap(); + app.session + .edit("mask", |doc, a| { + let m = doc.layer_mut(a.unwrap()).unwrap().mask.as_mut().unwrap(); + m.surface.fill_rect(photocraft_geom::Rect::new(0, 0, 16, 64), &[0.0]); + m.linked = linked; + Ok(()) + }) + .unwrap(); + app +} + +fn texel_alpha(img: &egui::ColorImage, x: usize, y: usize) -> u8 { + img.pixels[y * img.size[0] + x].a() +} + +#[test] +fn transform_preview_preserves_displayed_profile_colors() { + let bounds = photocraft_geom::Rect::new(0, 0, 8, 8); + for (wide_gamut, monitor, warp) in [(false, "srgb", false), (true, "srgb", false), (false, "display-p3", false), (true, "srgb", true)] { + let mut app = app_with_square(8, bounds); + app.session + .edit("original color sample", |doc, active| { + if wide_gamut { + doc.icc_profile = Some(photocraft_cms::Builtin::AdobeRgbCompat.profile().to_bytes()); + } + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.55, 0.35, 0.2, 1.0]); + Ok(()) + }) + .unwrap(); + app.session.color.settings.monitor_profile = monitor.into(); + let st = app.session.active().unwrap(); + let display = app.session.color.canvas_display(&st.doc).unwrap(); + assert_eq!(!display.is_identity(), wide_gamut || monitor != "srgb"); + let composite = photocraft_compose::render(&st.doc, bounds); + let expected = crate::canvas::display_image(Some(&display), &composite); + let ctx = gpu_ctx(); + if warp { + begin_warp(&mut app, &ctx).unwrap(); + } else { + begin(&mut app, &ctx).unwrap(); + } + let xf = ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(80.0, 80.0)), + zoom: 1.0, + center: [4.0, 4.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + }; + let mut out = ctx.run_ui(egui::RawInput { max_texture_side: Some(16384), ..Default::default() }, |ui| { + draw_content(&app, &ui.ctx().layer_painter(egui::LayerId::background()), &xf); + }); + let texture = out + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Mesh(mesh) if mesh.texture_id != egui::TextureId::default() => Some(mesh.texture_id), + _ => None, + }) + .expect("transform draws a textured mesh"); + let upload = out.textures_delta.set.get(&texture).and_then(|updates| updates.last()).expect("drawn texture was uploaded"); + let egui::ImageData::Color(image) = &upload.image; + let shown = image.pixels[0]; + out.textures_delta.clear(); + assert_eq!(shown, expected.pixels[0], "transform changed displayed color; wide_gamut={wide_gamut}, monitor={monitor}, warp={warp}"); + } +} + +#[test] +fn preview_applies_the_linked_mask() { + for linked in [true, false] { + let app = masked_app(linked); + let st = app.session.active().unwrap(); + let id = st.active_layer.unwrap(); + let b = photocraft_geom::Rect::new(8, 8, 24, 24); + let (img, _) = preview_image(&st.doc, id, None, b, 4096, false); + // Texel x = doc x − 8: x 10 is hidden by the mask, x 20 shows. + assert_eq!(texel_alpha(&img, 12, 4), 255); + assert_eq!(texel_alpha(&img, 2, 4), if linked { 0 } else { 255 }, "linked={linked}"); + } + // With a selection the lifted pixels carry the mask too. + let mut app = masked_app(true); + app.session.execute("select.rect", json!({"x": 8, "y": 8, "width": 12, "height": 16})).unwrap(); + let ctx = egui::Context::default(); + begin(&mut app, &ctx).unwrap(); + let st = app.session.active().unwrap(); + let sel = st.doc.selection.clone().unwrap(); + let id = st.active_layer.unwrap(); + let (lifted, _) = photocraft_engine::transform_cmds::split_selected(st.doc.layer(id).unwrap().surface().unwrap(), &sel).unwrap(); + let b = photocraft_geom::Rect::new(8, 8, 20, 24); + let (img, _) = preview_image(&st.doc, id, Some(&lifted), b, 4096, false); + assert_eq!(texel_alpha(&img, 2, 4), 0, "masked"); + assert_eq!(texel_alpha(&img, 10, 4), 255, "revealed"); +} + +#[test] +fn transform_selection_tint_is_not_document_color() { + let mut app = app_with_square(8, photocraft_geom::Rect::new(0, 0, 8, 8)); + app.session.color.settings.monitor_profile = "display-p3".into(); + app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + let ctx = gpu_ctx(); + begin_selection(&mut app, &ctx).unwrap(); + let raw = app.transform_preview.as_ref().unwrap().texture.level_image(0).unwrap().0; + let xf = ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(80.0, 80.0)), + zoom: 1.0, + center: [4.0, 4.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + }; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + draw_content(&app, &ui.ctx().layer_painter(egui::LayerId::background()), &xf); + }); + let id = out + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => Some(m.texture_id), + _ => None, + }) + .unwrap(); + let egui::ImageData::Color(shown) = &out.textures_delta.set.get(&id).unwrap().last().unwrap().image; + assert_eq!(shown.pixels, raw.pixels); + out.textures_delta.clear(); +} + +#[test] +fn transform_covering_layer_uses_the_same_monitor_profile() { + let bounds = photocraft_geom::Rect::new(0, 0, 8, 8); + let mut app = app_with_square(8, bounds); + let lower = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + let upper = app.session.active().unwrap().active_layer.unwrap(); + app.session + .edit("original color samples", |doc, _| { + doc.layer_mut(lower).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.55, 0.35, 0.2, 1.0]); + doc.layer_mut(upper).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.2, 0.5, 0.7, 1.0]); + Ok(()) + }) + .unwrap(); + app.session.color.settings.monitor_profile = "display-p3".into(); + let doc = app.session.active().unwrap().doc.clone(); + let display = app.session.color.canvas_display(&doc).unwrap(); + let expected = [lower, upper].map(|id| { + let mut solo = (*doc).clone(); + for layer in &mut solo.layers { + layer.visible = layer.id == id; + } + crate::canvas::display_image(Some(&display), &photocraft_compose::render(&solo, bounds)).pixels[0] + }); + app.session.execute("layer.select", json!({"layer": lower.0})).unwrap(); + let ctx = gpu_ctx(); + begin(&mut app, &ctx).unwrap(); + let xf = ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(80.0, 80.0)), + zoom: 1.0, + center: [4.0, 4.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + }; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + draw_content(&app, &ui.ctx().layer_painter(egui::LayerId::background()), &xf); + }); + let shown: Vec<_> = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => { + let egui::ImageData::Color(image) = &out.textures_delta.set.get(&m.texture_id).unwrap().last().unwrap().image; + Some(image.pixels[0]) + } + _ => None, + }) + .collect(); + out.textures_delta.clear(); + assert_eq!(shown, expected, "moving pixels and covering pixels use the same display conversion"); +} + +#[test] +#[ignore = "requires a GPU adapter; renders profile-managed transform evidence"] +fn transform_profile_visual_evidence() { + let _guard = photocraft_testkit::gpu_lock(); + let destination = std::env::var("PHOTOCRAFT_TRANSFORM_EVIDENCE").unwrap_or_else(|_| "transform-profile-evidence".into()); + std::fs::create_dir_all(&destination).unwrap(); + for monitor in ["srgb", "display-p3"] { + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).with_max_steps(64).wgpu().build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.set_wgpu(cc.wgpu_render_state.as_ref().unwrap().clone()); + app.run("file.new", json!({"width": 400, "height": 300, "background": "transparent"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.session + .edit("original color swatches", |doc, active| { + let surface = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for (x, color) in [(60, [0.55, 0.35, 0.2, 1.0]), (160, [0.2, 0.6, 0.35, 1.0]), (260, [0.3, 0.4, 0.7, 1.0])] { + surface.fill_rect(photocraft_geom::Rect::new(x, 60, x + 80, 220), &color); + } + Ok(()) + }) + .unwrap(); + app.session.color.settings.monitor_profile = monitor.into(); + app.ui.extras.rulers = false; + app.sync_views(); + app.ui.views[0].zoom = 1.0; + app.ui.views[0].center = [200.0, 150.0]; + app.ui.views[0].fit_pending = false; + app + }); + h.run_steps(8); + let app = h.state(); + let view = &app.ui.views[0]; + let xf = ViewXform { rect: app.last_canvas_rect, zoom: view.zoom, center: view.center, flip: false, rotation: 0.0, aspect: 1.0 }; + let points = [100.0, 200.0, 300.0].map(|x| xf.to_screen(x, 100.0) * h.ctx.pixels_per_point()); + let before = h.render().unwrap(); + before.save(std::path::Path::new(&destination).join(format!("{monitor}-before.png"))).unwrap(); + let ctx = h.ctx.clone(); + begin(h.state_mut(), &ctx).unwrap(); + h.run_steps(8); + assert!(h.state().ui.transform.is_some()); + let during = h.render().unwrap(); + during.save(std::path::Path::new(&destination).join(format!("{monitor}-during.png"))).unwrap(); + commit(h.state_mut()); + h.run_steps(8); + assert!(h.state().ui.transform.is_none()); + let after = h.render().unwrap(); + after.save(std::path::Path::new(&destination).join(format!("{monitor}-after.png"))).unwrap(); + for point in points { + let (x, y) = (point.x as u32, point.y as u32); + let expected = before.get_pixel(x, y).0; + assert_ne!(expected[0], expected[1], "sample must hit a color swatch, not the checkerboard"); + for actual in [during.get_pixel(x, y).0, after.get_pixel(x, y).0] { + assert!(actual.iter().zip(expected).all(|(a, b)| a.abs_diff(b) <= 2), "{monitor}: before={expected:?}, shown={actual:?}"); + } + } + } +} + +#[test] +fn preview_feathers_the_linked_mask() { + // A feathered pixel mask without a vector mask: the compositor softens the edge at x 16, + // so the moving texels must be soft there too, not hard until the commit (#4560). + let mut app = masked_app(true); + app.session + .edit("feather", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().mask.as_mut().unwrap().feather = 4.0; + Ok(()) + }) + .unwrap(); + let st = app.session.active().unwrap(); + let id = st.active_layer.unwrap(); + let b = photocraft_geom::Rect::new(8, 8, 24, 24); + let (img, _) = preview_image(&st.doc, id, None, b, 4096, false); + // Texel x 7 = doc x 15, just inside the hidden half; texel x 8 = doc x 16, just revealed. + assert!(texel_alpha(&img, 7, 4) > 0, "the feather reaches into the hidden side"); + assert!(texel_alpha(&img, 8, 4) < 255, "the feather reaches into the revealed side"); + // The same values the compositor masks the committed layer with. + let m = photocraft_compose::masks::combined_mask(st.doc.layer(id).unwrap(), b).unwrap(); + for x in [6usize, 7, 8, 9, 15] { + let want = (m.sample_channel(8 + x as i32, 12, 0) * 255.0).round() as i32; + assert!((i32::from(texel_alpha(&img, x, 4)) - want).abs() <= 1, "texel {x}"); + } +} + +/// #5239: a smart object clipped to the layer under it previewed as nothing while the box +/// was open (its flattened render hid the clipping base too). +#[test] +fn preview_of_a_clipped_smart_object_is_not_empty() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + 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(0, 0, 64, 64), &[0.0, 0.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + app.session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + app.session.execute("layer.createClippingMask", json!({})).unwrap(); + let st = app.session.active().unwrap(); + let id = st.active_layer.unwrap(); + assert!(st.doc.layer(id).unwrap().clipped); + let (img, _) = preview_image(&st.doc, id, None, photocraft_geom::Rect::new(0, 0, 64, 64), 4096, false); + assert_eq!(texel_alpha(&img, 32, 32), 255, "the moving object shows"); +} + +#[test] +fn targeted_unlinked_mask_transforms_alone_through_the_box() { + let mut app = masked_app(false); + app.ui.mask_target = true; + let ctx = egui::Context::default(); + begin(&mut app, &ctx).unwrap(); + let t = app.ui.transform.as_ref().unwrap(); + assert_eq!(t.target, Some(json!("mask"))); + assert_eq!(t.rect, [0.0, 0.0, 16.0, 64.0], "the box frames the mask's content"); + // The preview document shows the mask vacated (revealed). + let pd = &app.transform_preview.as_ref().unwrap().doc; + assert!(pd.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(4, 4, 0) > 0.99); + // Move the box 20 px right and commit. + let t = app.ui.transform.as_mut().unwrap(); + t.quad = t.quad.map(|[x, y]| [x + 20.0, y]); + commit(&mut app); + assert!(!app.ui.status_error, "{}", app.ui.status); + let st = app.session.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); + let m = &l.mask.as_ref().unwrap().surface; + assert!(m.sample_channel(4, 30, 0) > 0.99 && m.sample_channel(30, 30, 0) < 0.01, "mask moved 20 px right"); + assert_eq!(l.surface().unwrap().content_bounds(), photocraft_geom::Rect::new(8, 8, 24, 24), "pixels untouched"); + // Warp mode doesn't apply to a lone mask. + app.ui.mask_target = true; + begin(&mut app, &ctx).unwrap(); + enter_warp(&mut app, &egui::Context::default()); + assert!(app.ui.transform.as_ref().unwrap().warp.is_none()); +} + +#[test] +fn linked_mask_target_transforms_the_layer() { + let mut app = masked_app(true); + app.ui.mask_target = true; + let ctx = egui::Context::default(); + begin(&mut app, &ctx).unwrap(); + assert_eq!(app.ui.transform.as_ref().unwrap().target, None); + assert_eq!(app.ui.transform.as_ref().unwrap().rect, [8.0, 8.0, 24.0, 24.0]); +} + +/// ⌘T with Path Selection and a path transforms the path, not the layer's pixels, as one +/// undoable step; it works on the Background too. +#[test] +fn free_transform_moves_the_selected_path_not_pixels() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.run("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": true, "knots": [[10, 10], [30, 10], [30, 20], [10, 20]]}]}})).unwrap(); + app.ui.tool = Tool::PathSelection; + assert!(crate::menus::is_enabled(&app, "edit.freeTransform"), "a path is transformable on the Background"); + let pixels = app.session.active().unwrap().doc.layers[0].surface().cloned(); + let steps = app.session.active().unwrap().history.past_len(); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + let t = app.ui.transform.as_mut().unwrap(); + assert_eq!(t.rect, [10.0, 10.0, 30.0, 20.0], "the box frames the path"); + assert_eq!(t.path, Some(json!({"name": "work"}))); + // Twice as wide and 5 px down. + t.quad = [[10.0, 15.0], [50.0, 15.0], [50.0, 25.0], [10.0, 25.0]]; + commit(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), steps + 1, "one step"); + let wp = st.doc.work_path.as_ref().unwrap(); + let anchors: Vec<[f64; 2]> = wp.subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); + assert_eq!(anchors, vec![[10.0, 15.0], [50.0, 15.0], [50.0, 25.0], [10.0, 25.0]]); + assert_eq!(st.doc.layers[0].surface().cloned(), pixels, "the pixels stay put"); + + // ⌘-drag of a corner (Distort) maps the path onto the box (#3027): one step. + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + app.ui.transform.as_mut().unwrap().quad[2] = [70.0, 40.0]; + commit(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), steps + 2, "one step: {}", app.ui.status); + let anchors: Vec<[f64; 2]> = st.doc.work_path.as_ref().unwrap().subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); + let want = [[10.0, 15.0], [50.0, 15.0], [70.0, 40.0], [10.0, 25.0]]; + assert!(anchors.iter().zip(want).all(|(a, b)| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9), "{anchors:?}"); + + // Edit › Transform Path › Warp bends it: one more step. + crate::menus::invoke(&mut app, &ctx, "edit.transform.warp", json!({})).unwrap(); + let t = app.ui.transform.as_mut().unwrap(); + assert!(t.warp.is_some(), "Warp mode on a path"); + t.warp = Some(Warp { style: WarpStyle::Arc, bend: 50.0, ..Warp::none(t.rect) }); + commit(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), steps + 3, "one step: {}", app.ui.status); + assert!(st.doc.work_path.as_ref().unwrap().subpaths[0].knots.len() > 4, "the warp bends the edges"); + + // Without a path tool, ⌘T is the pixel transform again. + app.ui.tool = Tool::Move; + app.run("layer.new.layer", json!({})).unwrap(); + assert!(crate::vector_ui::free_transform_path(&app).is_none()); +} + +/// Edit › Transform › Warp on editable type (#3004), as in Photoshop: no rasterize prompt, no +/// mesh to drag, only the warp styles; the commit is the type's own Warp Text, one step, and +/// the layer stays type. +#[test] +fn warp_on_type_takes_a_style_and_keeps_the_type_editable() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.sync_views(); + app.run("type.create", json!({"x": 10, "y": 60, "text": "Hello"})).unwrap(); + let ctx = egui::Context::default(); + let past = |app: &PhotocraftApp| app.session.active().unwrap().history.past_len(); + let before = past(&app); + crate::menus::invoke(&mut app, &ctx, "edit.transform.warp", json!({})).unwrap(); + assert!(app.ui.dialogs.is_empty(), "no prompt"); + let w0 = app.ui.transform.as_ref().and_then(|t| t.warp.clone()).expect("Warp mode"); + assert_eq!(w0.style, WarpStyle::None); + // A drag on the grid changes nothing: type takes only the styles. + let c = [(w0.bounds[0] + w0.bounds[2]) / 2.0, (w0.bounds[1] + w0.bounds[3]) / 2.0]; + warp_pointer(&mut app, ToolEvent::Down { x: w0.bounds[2], y: w0.bounds[3], pressure: 1.0 }, 4.0, egui::Modifiers::NONE); + warp_pointer(&mut app, ToolEvent::Up { x: w0.bounds[2] + 20.0, y: w0.bounds[3] + 15.0 }, 4.0, egui::Modifiers::NONE); + warp_pointer(&mut app, ToolEvent::Down { x: c[0], y: c[1], pressure: 1.0 }, 4.0, egui::Modifiers::NONE); + warp_pointer(&mut app, ToolEvent::Up { x: c[0], y: c[1] + 20.0 }, 4.0, egui::Modifiers::NONE); + assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref(), Some(&w0)); + assert!(split(&mut app, "edit.transform.splitWarpCrosswise", None).is_err()); + // Pick Flag in the options bar, then Enter. + if let Some(w) = app.ui.transform.as_mut().and_then(|t| t.warp.as_mut()) { + *w = Warp { style: WarpStyle::Flag, bend: 40.0, ..Warp::none(w.bounds) }; + } + commit(&mut app); + assert!(!app.ui.status_error, "{}", app.ui.status); + let st = app.session.active().unwrap(); + let LayerContent::Text(t) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("still type") }; + let tw = t.warp.as_ref().expect("Warp Text set"); + assert_eq!((tw.style.as_str(), tw.value, tw.horizontal), ("warpFlag", 40.0, true)); + assert_eq!(past(&app), before + 1, "one history step"); + // Warp again shows Flag; None takes it off in one more step. + begin_warp(&mut app, &ctx).unwrap(); + assert_eq!(app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap().style, WarpStyle::Flag); + if let Some(t) = app.ui.transform.as_mut() { + t.warp = Some(Warp::none(t.rect)); + } + commit(&mut app); + let st = app.session.active().unwrap(); + assert!(matches!(&st.doc.layer(st.active_layer.unwrap()).unwrap().content, LayerContent::Text(t) if t.warp.is_none())); + assert_eq!(past(&app), before + 2); +} + +#[test] +fn anchor_grid_point_on_quad_and_carry_pivot() { + let quad = [[0.0, 0.0], [100.0, 0.0], [100.0, 50.0], [0.0, 50.0]]; + assert_eq!(point_on_quad(quad, 0), [0.0, 0.0]); + assert_eq!(point_on_quad(quad, 1), [50.0, 0.0]); + assert_eq!(point_on_quad(quad, 2), [100.0, 0.0]); + assert_eq!(point_on_quad(quad, 3), [0.0, 25.0]); + assert_eq!(point_on_quad(quad, 4), [50.0, 25.0]); + assert_eq!(point_on_quad(quad, 5), [100.0, 25.0]); + assert_eq!(point_on_quad(quad, 6), [0.0, 50.0]); + assert_eq!(point_on_quad(quad, 7), [50.0, 50.0]); + assert_eq!(point_on_quad(quad, 8), [100.0, 50.0]); + + let quad_scaled = [[0.0, 0.0], [200.0, 0.0], [200.0, 100.0], [0.0, 100.0]]; + let p_top_right = carry_pivot(quad, quad_scaled, [100.0, 0.0]); + assert_eq!(p_top_right, [200.0, 0.0]); + let p_center = carry_pivot(quad, quad_scaled, [50.0, 25.0]); + assert_eq!(p_center, [100.0, 50.0]); + + for anchor in 0..9 { + assert_eq!(matching_anchor(quad, point_on_quad(quad, anchor)), Some(anchor)); + } + assert_eq!(matching_anchor(quad, [12.3, 45.6]), None); + assert_eq!(matching_anchor(quad, [50.0, 30.0]), None); +} From 6d1bcd80a70888e4b474df6d918d00d2470baa32 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:41 +0000 Subject: [PATCH 109/259] refactor(ui-egui): move i18n.rs tests to i18n/tests.rs --- crates/ui-egui/src/i18n.rs | 367 +------------------------------ crates/ui-egui/src/i18n/tests.rs | 358 ++++++++++++++++++++++++++++++ 2 files changed, 359 insertions(+), 366 deletions(-) create mode 100644 crates/ui-egui/src/i18n/tests.rs diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 38f378a7b7..51f6d1872f 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -460,372 +460,7 @@ pub fn trn(lang: Lang, n: u64, one: &str, other: &str) -> String { } #[cfg(test)] -mod tests { - use super::catalog::{parse_entries, placeholders}; - use super::*; - - const JA: fn() -> Lang = || Lang::from_code("ja").expect("ja registered"); - const ZH: fn() -> Lang = || Lang::from_code("zh-hant").expect("zh-hant registered"); - const CS: fn() -> Lang = || Lang::from_code("cs").expect("cs registered"); - const ID: fn() -> Lang = || Lang::from_code("id").expect("id registered"); - const VI: fn() -> Lang = || Lang::from_code("vi").expect("vi registered"); - const HI: fn() -> Lang = || Lang::from_code("hi").expect("hi registered"); - - #[test] - fn hindi_tags_resolve() { - for tag in ["hi", "hi-IN", "hi_IN", "hi_IN.UTF-8"] { - assert_eq!(lang_from_tag(tag), Some(HI()), "{tag}"); - } - assert_eq!(HI().name(), "हिन्दी"); - assert_eq!(Lang::from_pref("hi"), HI()); - assert_eq!(Lang::from_pref("HI"), HI()); - } - - #[test] - fn indonesian_tags_resolve() { - for tag in ["id", "id-ID", "id_ID", "id_ID.UTF-8"] { - assert_eq!(lang_from_tag(tag), Some(ID()), "{tag}"); - } - assert_eq!(ID().name(), "Bahasa Indonesia"); - } - - #[test] - fn vietnamese_tags_resolve() { - for tag in ["vi", "vi-VN", "vi_VN", "vi_VN.UTF-8"] { - assert_eq!(lang_from_tag(tag), Some(VI()), "{tag}"); - } - assert_eq!(VI().name(), "Tiếng Việt"); - assert_eq!(Lang::from_pref("vi"), VI()); - assert_eq!(Lang::from_pref("VI"), VI()); - } - - #[test] - fn picker_lists_english_first_then_names_alphabetically() { - let order = Lang::for_picker(); - assert_eq!(order.first().map(|l| l.code()), Some("en")); - assert_eq!(order.len(), Lang::all().count()); - let keys: Vec = order[1..].iter().map(|l| name_sort_key(l.name())).collect(); - assert!(keys.windows(2).all(|w| w[0] <= w[1]), "{keys:?}"); - let pos = |code: &str| order.iter().position(|l| l.code() == code).unwrap_or_else(|| panic!("{code} registered")); - assert!(pos("cs") < pos("de"), "Čeština sorts under C, not after Z"); - assert!(pos("it") < pos("hu"), "Magyar sorts under M, not under its code"); - assert!(pos("tr") < pos("el"), "Latin names come before Greek"); - assert!(pos("uk") < pos("ja"), "Cyrillic names come before CJK"); - assert_eq!(name_sort_key("Tiếng Việt"), "tieng viet"); - assert_eq!(name_sort_key("Türkçe"), "turkce"); - } - - #[test] - fn tags_map_to_languages() { - assert_eq!(lang_from_tag("ja_JP.UTF-8"), Some(JA())); - assert_eq!(lang_from_tag("ja-JP"), Some(JA())); - assert_eq!(lang_from_tag("en_US.UTF-8"), Some(Lang::EN)); - assert_eq!(lang_from_tag("C"), Some(Lang::EN)); - assert_eq!(lang_from_tag("POSIX"), Some(Lang::EN)); - assert_eq!(lang_from_tag("cs_CZ.UTF-8"), Some(CS())); - assert_eq!(lang_from_tag("cs-CZ"), Some(CS())); - assert_eq!(lang_from_tag("fr_FR"), Lang::from_code("fr")); - assert_eq!(lang_from_tag("de_DE"), Lang::from_code("de")); - assert_eq!(lang_from_tag("de-AT"), Lang::from_code("de")); - assert_eq!(lang_from_tag("it_IT.UTF-8"), Lang::from_code("it")); - assert_eq!(lang_from_tag("it-CH"), Lang::from_code("it")); - assert_eq!(lang_from_tag("nl_NL.UTF-8"), Lang::from_code("nl")); - assert_eq!(lang_from_tag("nl-BE"), Lang::from_code("nl")); - assert_eq!(lang_from_tag("hu_HU.UTF-8"), Lang::from_code("hu")); - assert_eq!(lang_from_tag("hu-HU"), Lang::from_code("hu")); - assert_eq!(lang_from_tag("tr_TR.UTF-8"), Lang::from_code("tr")); - assert_eq!(lang_from_tag("tr-TR"), Lang::from_code("tr")); - assert_eq!(lang_from_tag("tr"), Lang::from_code("tr")); - // Traditional Chinese: by region, by script, and with a region after the script. - assert_eq!(lang_from_tag("zh_TW.UTF-8"), Some(ZH())); - assert_eq!(lang_from_tag("zh-TW"), Some(ZH())); - assert_eq!(lang_from_tag("zh-HK"), Some(ZH())); - assert_eq!(lang_from_tag("zh_MO"), Some(ZH())); - assert_eq!(lang_from_tag("zh-Hant"), Some(ZH())); - assert_eq!(lang_from_tag("zh-Hant-TW"), Some(ZH())); - assert_eq!(lang_from_tag("zh-Hant-HK"), Some(ZH())); - // Simplified Chinese locales never pick up the Traditional catalog: they resolve to `zh-hans`. - for tag in ["zh-CN", "zh_CN.UTF-8", "zh_SG", "zh-Hans", "zh-Hans-CN", "zh"] { - assert_ne!(lang_from_tag(tag), Some(ZH()), "{tag}"); - assert_eq!(lang_from_tag(tag), Lang::from_code("zh-hans"), "{tag}"); - } - assert_eq!(lang_from_tag(""), None); - assert_eq!(lang_from_tag("_"), None); - } - - #[test] - fn candidates_walk_from_specific_to_general() { - assert_eq!(candidates("pt_BR.UTF-8"), ["pt-br", "pt"]); - assert_eq!(candidates("zh_TW"), ["zh-tw", "zh-hant", "zh"]); - assert_eq!(candidates("zh-CN"), ["zh-cn", "zh-hans", "zh"]); - assert_eq!(candidates("zh-Hant-HK"), ["zh-hant-hk", "zh-hant", "zh"]); - } - - #[test] - fn preferences_resolve_with_fallback() { - assert_eq!(Lang::from_pref("ja"), JA()); - assert_eq!(Lang::from_pref("JA"), JA()); - assert_eq!(Lang::from_pref("zh-hant"), ZH()); - assert_eq!(Lang::from_pref("ZH-Hant"), ZH()); - assert_eq!(Lang::from_pref("en"), Lang::EN); - // `auto` and unknown codes follow the system (English under test). - assert_eq!(Lang::from_pref("auto"), Lang::EN); - assert_eq!(Lang::from_pref("xx-unknown"), Lang::EN); - } - - #[test] - fn simplified_chinese_resolves_from_preferences() { - let zh = Lang::from_code("zh-hans").expect("zh-hans registered"); - assert_eq!(Lang::from_pref("ZH-Hans"), zh); - assert_eq!(tr(zh, "no such label"), "no such label"); - } - - #[test] - fn spanish_resolves_and_pluralises() { - let es = Lang::from_code("es").expect("es registered"); - for tag in ["es", "es_ES.UTF-8", "es-MX", "es-419"] { - assert_eq!(lang_from_tag(tag), Some(es), "{tag}"); - } - let forms: Vec = [0, 1, 3].into_iter().map(es.0.plural).collect(); - assert_eq!(forms, [1, 0, 1]); - } - - #[test] - fn hungarian_resolves_and_keeps_the_singular_after_counts() { - let hu = Lang::from_code("hu").expect("hu registered"); - for tag in ["hu", "hu_HU.UTF-8", "hu-HU"] { - assert_eq!(lang_from_tag(tag), Some(hu), "{tag}"); - } - assert_eq!(hu.name(), "Magyar"); - let forms: Vec = [0, 1, 3, 21].into_iter().map(hu.0.plural).collect(); - assert_eq!(forms, [0, 0, 0, 0]); - } - - #[test] - fn brazilian_portuguese_resolves_and_pluralises() { - let pt = Lang::from_code("pt-br").expect("pt-br registered"); - for tag in ["pt", "pt-BR", "pt_BR.UTF-8", "pt-PT", "pt_PT.UTF-8"] { - assert_eq!(lang_from_tag(tag), Some(pt), "{tag}"); - } - assert_eq!(candidates("pt_PT"), ["pt-pt", "pt-br", "pt"]); - let forms: Vec = [0, 1, 2].into_iter().map(pt.0.plural).collect(); - assert_eq!(forms, [0, 0, 1]); - } - - #[test] - fn lookups_fall_back_to_english() { - assert_eq!(tr(JA(), "no such label"), "no such label"); - assert_eq!(tr(Lang::EN, "Layer"), "Layer"); - assert_eq!(tr(ZH(), "no such label"), "no such label"); - assert_eq!(tr_id(ZH(), "no.such.id", "Layer"), tr(ZH(), "Layer")); - assert_eq!(tr_id(JA(), "no.such.id", "Layer"), tr(JA(), "Layer")); - assert_eq!(tr_ctx(JA(), "no such context", "Layer"), tr(JA(), "Layer")); - assert_eq!(trn(JA(), 3, "{n} no such message", "{n} no such messages"), "3 no such messages"); - } - - #[test] - fn russian_plural_rule() { - let ru = Lang::from_code("ru").expect("ru registered"); - let forms: Vec = [0, 1, 2, 5, 11, 12, 14, 21, 22, 25, 101, 111, 112].into_iter().map(ru.0.plural).collect(); - assert_eq!(forms, [2, 0, 1, 2, 2, 2, 2, 0, 1, 2, 0, 2, 2]); - } - - #[test] - fn ukrainian_resolves_locales_and_preferences() { - let uk = Lang::from_code("uk").expect("uk registered"); - assert_eq!(uk.name(), "Українська"); - for tag in ["uk", "UK", "uk-UA", "uk_UA", "uk_UA.UTF-8", "uk-UA@euro", "uk-Cyrl-UA"] { - assert_eq!(lang_from_tag(tag), Some(uk), "{tag}"); - assert_eq!(Lang::from_pref(tag), uk, "{tag}"); - } - assert_eq!(tr(uk, "unknown translation"), "unknown translation"); - } - - #[test] - fn ukrainian_plural_rule_handles_teens_and_compound_counts() { - let uk = Lang::from_code("uk").expect("uk registered"); - let counts = [0, 1, 2, 4, 5, 11, 12, 14, 19, 21, 22, 24, 25, 100, 101, 111, 112, 114, 121, 122, u64::MAX]; - let forms: Vec = counts.into_iter().map(uk.0.plural).collect(); - assert_eq!(forms, [2, 0, 1, 1, 2, 2, 2, 2, 2, 0, 1, 1, 2, 2, 0, 2, 2, 2, 0, 1, 2]); - } - - #[test] - fn serbian_resolves_locales_and_preferences() { - let sr = Lang::from_code("sr").expect("sr registered"); - assert_eq!(sr.name(), "Srpski"); - for tag in ["sr", "SR", "sr-RS", "sr_RS", "sr_RS.UTF-8", "sr_RS@latin", "sr-Latn", "sr-Latn-RS", "sr-Cyrl-RS", "sr-ME"] { - assert_eq!(lang_from_tag(tag), Some(sr), "{tag}"); - assert_eq!(Lang::from_pref(tag), sr, "{tag}"); - } - } - - #[test] - fn serbian_plural_rule_handles_teens_and_compound_counts() { - let sr = Lang::from_code("sr").expect("sr registered"); - let counts = [0, 1, 2, 4, 5, 11, 12, 14, 21, 22, 25, 101, 111, 112, 122]; - let forms: Vec = counts.into_iter().map(sr.0.plural).collect(); - assert_eq!(forms, [2, 0, 1, 1, 2, 2, 2, 2, 0, 1, 2, 0, 2, 2, 1]); - } - - #[test] - fn catalog_kinds_are_parsed_and_looked_up() { - let c = Catalog::parse("# c\n\tHello\tこんにちは\n@id\tfile.save\t保存する\nmenu\tWindows\tウィンドウ群\n@plural\t{n} file|{n} files\t{n} 個\n\n"); - assert_eq!(c.plain("Hello"), Some("こんにちは")); - assert_eq!(c.id("file.save"), Some("保存する")); - assert_eq!(c.contextual("menu", "Windows"), Some("ウィンドウ群")); - assert_eq!(c.contextual("other", "Windows"), None); - assert_eq!(c.plural("{n} file", "{n} files", 0), Some("{n} 個")); - assert_eq!(c.plural("{n} file", "{n} files", 5), Some("{n} 個"), "an index past the forms clamps"); - } - - #[test] - fn malformed_lines_are_reported_not_fatal() { - let (entries, errors) = parse_entries("\tok\tはい\nno tabs here\n\tonly\n\ta\tb\tc\textra\n\t\tempty source\n"); - assert_eq!(entries.len(), 1); - assert_eq!(errors.len(), 4, "{errors:?}"); - assert_eq!(parse_entries("\ta\\tb\tx\\ny\\\\z\n").0[0], (String::new(), "a\tb".into(), "x\ny\\z".into())); - } - - #[test] - fn plurals_and_placeholders() { - assert_eq!(trn(Lang::EN, 1, "{n} item", "{n} items"), "1 item"); - assert_eq!(trn(Lang::EN, 0, "{n} item", "{n} items"), "0 items"); - assert_eq!(trn(Lang::EN, 7, "{n} item", "{n} items"), "7 items"); - let cs = fixture_lang(plural_cs, "@plural\t{n} item|{n} items\t{n} one|{n} few|{n} other\n"); - for (n, expected) in [(0, "0 other"), (1, "1 one"), (3, "3 few"), (5, "5 other")] { - assert_eq!(trn(cs, n, "{n} item", "{n} items"), expected); - } - let ja = fixture_lang(plural_none, "@plural\t{n} item|{n} items\t{n} only\n"); - assert_eq!(trn(ja, 1, "{n} item", "{n} items"), "1 only"); - assert_eq!(trn(ja, 7, "{n} item", "{n} items"), "7 only"); - assert_eq!(trn(ja, 7, "{n} file", "{n} files"), "7 files", "a missing row falls back to English"); - assert_eq!(fmt("{b} before {a}", &[("a", "x"), ("b", "y"), ("c", "z")]), "y before x"); - assert_eq!(fmt("{missing}", &[]), "{missing}"); - assert_eq!(placeholders("a {x} b {y} {"), ["x", "y"]); - } - - #[test] - fn french_resolves_and_pluralises() { - let fr = Lang::from_code("fr").expect("fr registered"); - for tag in ["fr", "fr_FR.UTF-8", "fr-CA", "fr_BE", "fr-CH"] { - assert_eq!(lang_from_tag(tag), Some(fr), "{tag}"); - } - let forms: Vec = [0, 1, 2, 5, 100, u64::MAX].into_iter().map(fr.0.plural).collect(); - assert_eq!(forms, [0, 0, 1, 1, 1, 1]); - } - - /// A language whose catalog is `text`, for testing lookups without depending on a bundled - /// catalog's wording. - fn fixture_lang(plural: fn(u64) -> usize, text: &str) -> Lang { - let catalog = OnceLock::new(); - let _ = catalog.set(Catalog::parse(text)); - Lang(Box::leak(Box::new(LangInfo { code: "xx", name: "x", source: b"", plural, complete_menus: false, catalog }))) - } - - #[test] - fn id_and_context_rows_win_over_the_plain_label() { - let lang = fixture_lang(plural_one_other, "\tAll\tplain all\n@id\tselect.all\tid all\nnavigator\tZoom\tcontext zoom\n\tZoom\tplain zoom\n"); - assert_eq!(tr_id(lang, "select.all", "All"), "id all"); - assert_eq!(tr_id(lang, "edit.other", "All"), "plain all"); - assert_eq!(tr(lang, "All"), "plain all"); - assert_eq!(tr_ctx(lang, "navigator", "Zoom"), "context zoom"); - assert_eq!(tr_ctx(lang, "other", "Zoom"), "plain zoom"); - assert_eq!(tr_ctx(lang, "navigator", "Unlisted"), "Unlisted"); - } - - #[test] - fn polish_plural_rule() { - let forms: Vec = [0, 1, 2, 4, 5, 12, 14, 21, 22, 25, 112, 122].into_iter().map(plural_polish).collect(); - assert_eq!(forms, [2, 0, 1, 1, 2, 2, 2, 2, 1, 2, 2, 1]); - } - - #[test] - fn czech_plural_rule() { - let forms: Vec = [0, 1, 2, 3, 4, 5, 11, 12, 21, 22, 100, u64::MAX].into_iter().map(plural_cs).collect(); - assert_eq!(forms, [2, 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]); - } - - /// The packed catalogs in the binary unpack to exactly the `.tsv` files. - #[test] - fn packed_catalogs_match_their_files() { - let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/i18n"); - for l in LANGUAGES.iter().skip(1) { - let file = std::fs::read_to_string(dir.join(format!("{}.tsv", l.code))).unwrap(); - assert_eq!(unpack(l.source).unwrap(), file, "{}", l.code); - assert!(l.source.len() < file.len() / 2, "{}: stored deflated", l.code); - } - assert_eq!(LANGUAGES[0].text(), "", "English has no catalog"); - } - - /// Corrupt catalog data is an error (English is shown), not a panic. - #[test] - fn corrupt_catalog_data_is_an_error() { - assert!(inflate(b"\xff\xff\xff\xff not deflate").is_err()); - let ja = LANGUAGES.iter().find(|l| l.code == "ja").unwrap(); - assert!(inflate(&ja.source[..ja.source.len() / 2]).is_err(), "truncated"); - let info: &'static LangInfo = Box::leak(Box::new(LangInfo { - code: "xx", - name: "x", - source: b"\x00garbage", - plural: plural_none, - complete_menus: false, - catalog: OnceLock::new(), - })); - assert_eq!(info.text(), ""); - assert_eq!(tr(Lang(info), "Layer"), "Layer", "falls back to English"); - } - - /// Packed lines unpack to their keys; references to keys that don't exist are an error, not a - /// panic. - #[test] - fn packed_lines_unpack_and_bad_references_are_errors() { - let keys = ["\tOpen", "@id\tfile.open", "\tClose"]; - let packed = "# c\n\x01Ouvrir\n\x02-1\tOuvrir\n\x02+1\tFermer\n\x03\x01x\n"; - assert_eq!(expand(packed, &keys).unwrap(), "# c\n\tOpen\tOuvrir\n\tOpen\tOuvrir\n\tClose\tFermer\n\x01x\n"); - for bad in ["\x02-1\tx", "\x02 3\tx", "\x023", "\x029223372036854775807\tx", "\x02-9223372036854775808\tx", "\x01a\n\x01b\n\x01c\n\x01d"] { - assert!(expand(bad, &keys).is_err(), "{bad:?}"); - } - } - - /// Every bundled catalog is well-formed and consistent with its sources. - #[test] - fn bundled_catalogs_are_consistent() { - for l in &LANGUAGES { - assert!(l.code == l.code.to_ascii_lowercase() && !l.name.is_empty(), "{}", l.code); - let (entries, errors) = parse_entries(&l.text()); - assert!(errors.is_empty(), "{}: {errors:?}", l.code); - let mut seen = std::collections::HashSet::new(); - for (ctx, src, tr) in &entries { - assert!(seen.insert((ctx.clone(), src.clone())), "{}: duplicate {ctx:?} {src:?}", l.code); - if ctx == "@plural" { - let one_other: Vec<&str> = src.split('|').collect(); - assert_eq!(one_other.len(), 2, "{}: plural source must be `one|other`: {src:?}", l.code); - let forms = (0..=1000).map(l.plural).max().unwrap_or(0) + 1; - assert_eq!(tr.split('|').count(), forms, "{}: {forms} plural forms expected in {src:?}", l.code); - for form in tr.split('|') { - let mut want = placeholders(one_other[1]); - let mut got = placeholders(form); - want.sort_unstable(); - got.sort_unstable(); - assert_eq!(want, got, "{}: placeholders differ in {src:?}", l.code); - } - continue; - } - let mut want = placeholders(src); - let mut got = placeholders(tr); - want.sort_unstable(); - got.sort_unstable(); - assert_eq!(want, got, "{}: placeholders differ in {src:?}", l.code); - if ctx.is_empty() { - assert_eq!(src.ends_with('…'), tr.ends_with('…'), "{}: ellipsis mismatch: {src:?}", l.code); - } - if ctx == "@id" { - assert!(crate::menus::is_live(src) || crate::menu_catalog::CATALOG.iter().any(|m| m.3 == src), "{}: unknown command id {src:?}", l.code); - } - } - } - } -} +mod tests; #[cfg(test)] mod live_tests; diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs new file mode 100644 index 0000000000..cca640fbba --- /dev/null +++ b/crates/ui-egui/src/i18n/tests.rs @@ -0,0 +1,358 @@ +use super::catalog::{parse_entries, placeholders}; +use super::*; + +const JA: fn() -> Lang = || Lang::from_code("ja").expect("ja registered"); +const ZH: fn() -> Lang = || Lang::from_code("zh-hant").expect("zh-hant registered"); +const CS: fn() -> Lang = || Lang::from_code("cs").expect("cs registered"); +const ID: fn() -> Lang = || Lang::from_code("id").expect("id registered"); +const VI: fn() -> Lang = || Lang::from_code("vi").expect("vi registered"); +const HI: fn() -> Lang = || Lang::from_code("hi").expect("hi registered"); + +#[test] +fn hindi_tags_resolve() { + for tag in ["hi", "hi-IN", "hi_IN", "hi_IN.UTF-8"] { + assert_eq!(lang_from_tag(tag), Some(HI()), "{tag}"); + } + assert_eq!(HI().name(), "हिन्दी"); + assert_eq!(Lang::from_pref("hi"), HI()); + assert_eq!(Lang::from_pref("HI"), HI()); +} + +#[test] +fn indonesian_tags_resolve() { + for tag in ["id", "id-ID", "id_ID", "id_ID.UTF-8"] { + assert_eq!(lang_from_tag(tag), Some(ID()), "{tag}"); + } + assert_eq!(ID().name(), "Bahasa Indonesia"); +} + +#[test] +fn vietnamese_tags_resolve() { + for tag in ["vi", "vi-VN", "vi_VN", "vi_VN.UTF-8"] { + assert_eq!(lang_from_tag(tag), Some(VI()), "{tag}"); + } + assert_eq!(VI().name(), "Tiếng Việt"); + assert_eq!(Lang::from_pref("vi"), VI()); + assert_eq!(Lang::from_pref("VI"), VI()); +} + +#[test] +fn picker_lists_english_first_then_names_alphabetically() { + let order = Lang::for_picker(); + assert_eq!(order.first().map(|l| l.code()), Some("en")); + assert_eq!(order.len(), Lang::all().count()); + let keys: Vec = order[1..].iter().map(|l| name_sort_key(l.name())).collect(); + assert!(keys.windows(2).all(|w| w[0] <= w[1]), "{keys:?}"); + let pos = |code: &str| order.iter().position(|l| l.code() == code).unwrap_or_else(|| panic!("{code} registered")); + assert!(pos("cs") < pos("de"), "Čeština sorts under C, not after Z"); + assert!(pos("it") < pos("hu"), "Magyar sorts under M, not under its code"); + assert!(pos("tr") < pos("el"), "Latin names come before Greek"); + assert!(pos("uk") < pos("ja"), "Cyrillic names come before CJK"); + assert_eq!(name_sort_key("Tiếng Việt"), "tieng viet"); + assert_eq!(name_sort_key("Türkçe"), "turkce"); +} + +#[test] +fn tags_map_to_languages() { + assert_eq!(lang_from_tag("ja_JP.UTF-8"), Some(JA())); + assert_eq!(lang_from_tag("ja-JP"), Some(JA())); + assert_eq!(lang_from_tag("en_US.UTF-8"), Some(Lang::EN)); + assert_eq!(lang_from_tag("C"), Some(Lang::EN)); + assert_eq!(lang_from_tag("POSIX"), Some(Lang::EN)); + assert_eq!(lang_from_tag("cs_CZ.UTF-8"), Some(CS())); + assert_eq!(lang_from_tag("cs-CZ"), Some(CS())); + assert_eq!(lang_from_tag("fr_FR"), Lang::from_code("fr")); + assert_eq!(lang_from_tag("de_DE"), Lang::from_code("de")); + assert_eq!(lang_from_tag("de-AT"), Lang::from_code("de")); + assert_eq!(lang_from_tag("it_IT.UTF-8"), Lang::from_code("it")); + assert_eq!(lang_from_tag("it-CH"), Lang::from_code("it")); + assert_eq!(lang_from_tag("nl_NL.UTF-8"), Lang::from_code("nl")); + assert_eq!(lang_from_tag("nl-BE"), Lang::from_code("nl")); + assert_eq!(lang_from_tag("hu_HU.UTF-8"), Lang::from_code("hu")); + assert_eq!(lang_from_tag("hu-HU"), Lang::from_code("hu")); + assert_eq!(lang_from_tag("tr_TR.UTF-8"), Lang::from_code("tr")); + assert_eq!(lang_from_tag("tr-TR"), Lang::from_code("tr")); + assert_eq!(lang_from_tag("tr"), Lang::from_code("tr")); + // Traditional Chinese: by region, by script, and with a region after the script. + assert_eq!(lang_from_tag("zh_TW.UTF-8"), Some(ZH())); + assert_eq!(lang_from_tag("zh-TW"), Some(ZH())); + assert_eq!(lang_from_tag("zh-HK"), Some(ZH())); + assert_eq!(lang_from_tag("zh_MO"), Some(ZH())); + assert_eq!(lang_from_tag("zh-Hant"), Some(ZH())); + assert_eq!(lang_from_tag("zh-Hant-TW"), Some(ZH())); + assert_eq!(lang_from_tag("zh-Hant-HK"), Some(ZH())); + // Simplified Chinese locales never pick up the Traditional catalog: they resolve to `zh-hans`. + for tag in ["zh-CN", "zh_CN.UTF-8", "zh_SG", "zh-Hans", "zh-Hans-CN", "zh"] { + assert_ne!(lang_from_tag(tag), Some(ZH()), "{tag}"); + assert_eq!(lang_from_tag(tag), Lang::from_code("zh-hans"), "{tag}"); + } + assert_eq!(lang_from_tag(""), None); + assert_eq!(lang_from_tag("_"), None); +} + +#[test] +fn candidates_walk_from_specific_to_general() { + assert_eq!(candidates("pt_BR.UTF-8"), ["pt-br", "pt"]); + assert_eq!(candidates("zh_TW"), ["zh-tw", "zh-hant", "zh"]); + assert_eq!(candidates("zh-CN"), ["zh-cn", "zh-hans", "zh"]); + assert_eq!(candidates("zh-Hant-HK"), ["zh-hant-hk", "zh-hant", "zh"]); +} + +#[test] +fn preferences_resolve_with_fallback() { + assert_eq!(Lang::from_pref("ja"), JA()); + assert_eq!(Lang::from_pref("JA"), JA()); + assert_eq!(Lang::from_pref("zh-hant"), ZH()); + assert_eq!(Lang::from_pref("ZH-Hant"), ZH()); + assert_eq!(Lang::from_pref("en"), Lang::EN); + // `auto` and unknown codes follow the system (English under test). + assert_eq!(Lang::from_pref("auto"), Lang::EN); + assert_eq!(Lang::from_pref("xx-unknown"), Lang::EN); +} + +#[test] +fn simplified_chinese_resolves_from_preferences() { + let zh = Lang::from_code("zh-hans").expect("zh-hans registered"); + assert_eq!(Lang::from_pref("ZH-Hans"), zh); + assert_eq!(tr(zh, "no such label"), "no such label"); +} + +#[test] +fn spanish_resolves_and_pluralises() { + let es = Lang::from_code("es").expect("es registered"); + for tag in ["es", "es_ES.UTF-8", "es-MX", "es-419"] { + assert_eq!(lang_from_tag(tag), Some(es), "{tag}"); + } + let forms: Vec = [0, 1, 3].into_iter().map(es.0.plural).collect(); + assert_eq!(forms, [1, 0, 1]); +} + +#[test] +fn hungarian_resolves_and_keeps_the_singular_after_counts() { + let hu = Lang::from_code("hu").expect("hu registered"); + for tag in ["hu", "hu_HU.UTF-8", "hu-HU"] { + assert_eq!(lang_from_tag(tag), Some(hu), "{tag}"); + } + assert_eq!(hu.name(), "Magyar"); + let forms: Vec = [0, 1, 3, 21].into_iter().map(hu.0.plural).collect(); + assert_eq!(forms, [0, 0, 0, 0]); +} + +#[test] +fn brazilian_portuguese_resolves_and_pluralises() { + let pt = Lang::from_code("pt-br").expect("pt-br registered"); + for tag in ["pt", "pt-BR", "pt_BR.UTF-8", "pt-PT", "pt_PT.UTF-8"] { + assert_eq!(lang_from_tag(tag), Some(pt), "{tag}"); + } + assert_eq!(candidates("pt_PT"), ["pt-pt", "pt-br", "pt"]); + let forms: Vec = [0, 1, 2].into_iter().map(pt.0.plural).collect(); + assert_eq!(forms, [0, 0, 1]); +} + +#[test] +fn lookups_fall_back_to_english() { + assert_eq!(tr(JA(), "no such label"), "no such label"); + assert_eq!(tr(Lang::EN, "Layer"), "Layer"); + assert_eq!(tr(ZH(), "no such label"), "no such label"); + assert_eq!(tr_id(ZH(), "no.such.id", "Layer"), tr(ZH(), "Layer")); + assert_eq!(tr_id(JA(), "no.such.id", "Layer"), tr(JA(), "Layer")); + assert_eq!(tr_ctx(JA(), "no such context", "Layer"), tr(JA(), "Layer")); + assert_eq!(trn(JA(), 3, "{n} no such message", "{n} no such messages"), "3 no such messages"); +} + +#[test] +fn russian_plural_rule() { + let ru = Lang::from_code("ru").expect("ru registered"); + let forms: Vec = [0, 1, 2, 5, 11, 12, 14, 21, 22, 25, 101, 111, 112].into_iter().map(ru.0.plural).collect(); + assert_eq!(forms, [2, 0, 1, 2, 2, 2, 2, 0, 1, 2, 0, 2, 2]); +} + +#[test] +fn ukrainian_resolves_locales_and_preferences() { + let uk = Lang::from_code("uk").expect("uk registered"); + assert_eq!(uk.name(), "Українська"); + for tag in ["uk", "UK", "uk-UA", "uk_UA", "uk_UA.UTF-8", "uk-UA@euro", "uk-Cyrl-UA"] { + assert_eq!(lang_from_tag(tag), Some(uk), "{tag}"); + assert_eq!(Lang::from_pref(tag), uk, "{tag}"); + } + assert_eq!(tr(uk, "unknown translation"), "unknown translation"); +} + +#[test] +fn ukrainian_plural_rule_handles_teens_and_compound_counts() { + let uk = Lang::from_code("uk").expect("uk registered"); + let counts = [0, 1, 2, 4, 5, 11, 12, 14, 19, 21, 22, 24, 25, 100, 101, 111, 112, 114, 121, 122, u64::MAX]; + let forms: Vec = counts.into_iter().map(uk.0.plural).collect(); + assert_eq!(forms, [2, 0, 1, 1, 2, 2, 2, 2, 2, 0, 1, 1, 2, 2, 0, 2, 2, 2, 0, 1, 2]); +} + +#[test] +fn serbian_resolves_locales_and_preferences() { + let sr = Lang::from_code("sr").expect("sr registered"); + assert_eq!(sr.name(), "Srpski"); + for tag in ["sr", "SR", "sr-RS", "sr_RS", "sr_RS.UTF-8", "sr_RS@latin", "sr-Latn", "sr-Latn-RS", "sr-Cyrl-RS", "sr-ME"] { + assert_eq!(lang_from_tag(tag), Some(sr), "{tag}"); + assert_eq!(Lang::from_pref(tag), sr, "{tag}"); + } +} + +#[test] +fn serbian_plural_rule_handles_teens_and_compound_counts() { + let sr = Lang::from_code("sr").expect("sr registered"); + let counts = [0, 1, 2, 4, 5, 11, 12, 14, 21, 22, 25, 101, 111, 112, 122]; + let forms: Vec = counts.into_iter().map(sr.0.plural).collect(); + assert_eq!(forms, [2, 0, 1, 1, 2, 2, 2, 2, 0, 1, 2, 0, 2, 2, 1]); +} + +#[test] +fn catalog_kinds_are_parsed_and_looked_up() { + let c = Catalog::parse("# c\n\tHello\tこんにちは\n@id\tfile.save\t保存する\nmenu\tWindows\tウィンドウ群\n@plural\t{n} file|{n} files\t{n} 個\n\n"); + assert_eq!(c.plain("Hello"), Some("こんにちは")); + assert_eq!(c.id("file.save"), Some("保存する")); + assert_eq!(c.contextual("menu", "Windows"), Some("ウィンドウ群")); + assert_eq!(c.contextual("other", "Windows"), None); + assert_eq!(c.plural("{n} file", "{n} files", 0), Some("{n} 個")); + assert_eq!(c.plural("{n} file", "{n} files", 5), Some("{n} 個"), "an index past the forms clamps"); +} + +#[test] +fn malformed_lines_are_reported_not_fatal() { + let (entries, errors) = parse_entries("\tok\tはい\nno tabs here\n\tonly\n\ta\tb\tc\textra\n\t\tempty source\n"); + assert_eq!(entries.len(), 1); + assert_eq!(errors.len(), 4, "{errors:?}"); + assert_eq!(parse_entries("\ta\\tb\tx\\ny\\\\z\n").0[0], (String::new(), "a\tb".into(), "x\ny\\z".into())); +} + +#[test] +fn plurals_and_placeholders() { + assert_eq!(trn(Lang::EN, 1, "{n} item", "{n} items"), "1 item"); + assert_eq!(trn(Lang::EN, 0, "{n} item", "{n} items"), "0 items"); + assert_eq!(trn(Lang::EN, 7, "{n} item", "{n} items"), "7 items"); + let cs = fixture_lang(plural_cs, "@plural\t{n} item|{n} items\t{n} one|{n} few|{n} other\n"); + for (n, expected) in [(0, "0 other"), (1, "1 one"), (3, "3 few"), (5, "5 other")] { + assert_eq!(trn(cs, n, "{n} item", "{n} items"), expected); + } + let ja = fixture_lang(plural_none, "@plural\t{n} item|{n} items\t{n} only\n"); + assert_eq!(trn(ja, 1, "{n} item", "{n} items"), "1 only"); + assert_eq!(trn(ja, 7, "{n} item", "{n} items"), "7 only"); + assert_eq!(trn(ja, 7, "{n} file", "{n} files"), "7 files", "a missing row falls back to English"); + assert_eq!(fmt("{b} before {a}", &[("a", "x"), ("b", "y"), ("c", "z")]), "y before x"); + assert_eq!(fmt("{missing}", &[]), "{missing}"); + assert_eq!(placeholders("a {x} b {y} {"), ["x", "y"]); +} + +#[test] +fn french_resolves_and_pluralises() { + let fr = Lang::from_code("fr").expect("fr registered"); + for tag in ["fr", "fr_FR.UTF-8", "fr-CA", "fr_BE", "fr-CH"] { + assert_eq!(lang_from_tag(tag), Some(fr), "{tag}"); + } + let forms: Vec = [0, 1, 2, 5, 100, u64::MAX].into_iter().map(fr.0.plural).collect(); + assert_eq!(forms, [0, 0, 1, 1, 1, 1]); +} + +/// A language whose catalog is `text`, for testing lookups without depending on a bundled +/// catalog's wording. +fn fixture_lang(plural: fn(u64) -> usize, text: &str) -> Lang { + let catalog = OnceLock::new(); + let _ = catalog.set(Catalog::parse(text)); + Lang(Box::leak(Box::new(LangInfo { code: "xx", name: "x", source: b"", plural, complete_menus: false, catalog }))) +} + +#[test] +fn id_and_context_rows_win_over_the_plain_label() { + let lang = fixture_lang(plural_one_other, "\tAll\tplain all\n@id\tselect.all\tid all\nnavigator\tZoom\tcontext zoom\n\tZoom\tplain zoom\n"); + assert_eq!(tr_id(lang, "select.all", "All"), "id all"); + assert_eq!(tr_id(lang, "edit.other", "All"), "plain all"); + assert_eq!(tr(lang, "All"), "plain all"); + assert_eq!(tr_ctx(lang, "navigator", "Zoom"), "context zoom"); + assert_eq!(tr_ctx(lang, "other", "Zoom"), "plain zoom"); + assert_eq!(tr_ctx(lang, "navigator", "Unlisted"), "Unlisted"); +} + +#[test] +fn polish_plural_rule() { + let forms: Vec = [0, 1, 2, 4, 5, 12, 14, 21, 22, 25, 112, 122].into_iter().map(plural_polish).collect(); + assert_eq!(forms, [2, 0, 1, 1, 2, 2, 2, 2, 1, 2, 2, 1]); +} + +#[test] +fn czech_plural_rule() { + let forms: Vec = [0, 1, 2, 3, 4, 5, 11, 12, 21, 22, 100, u64::MAX].into_iter().map(plural_cs).collect(); + assert_eq!(forms, [2, 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]); +} + +/// The packed catalogs in the binary unpack to exactly the `.tsv` files. +#[test] +fn packed_catalogs_match_their_files() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/i18n"); + for l in LANGUAGES.iter().skip(1) { + let file = std::fs::read_to_string(dir.join(format!("{}.tsv", l.code))).unwrap(); + assert_eq!(unpack(l.source).unwrap(), file, "{}", l.code); + assert!(l.source.len() < file.len() / 2, "{}: stored deflated", l.code); + } + assert_eq!(LANGUAGES[0].text(), "", "English has no catalog"); +} + +/// Corrupt catalog data is an error (English is shown), not a panic. +#[test] +fn corrupt_catalog_data_is_an_error() { + assert!(inflate(b"\xff\xff\xff\xff not deflate").is_err()); + let ja = LANGUAGES.iter().find(|l| l.code == "ja").unwrap(); + assert!(inflate(&ja.source[..ja.source.len() / 2]).is_err(), "truncated"); + let info: &'static LangInfo = + Box::leak(Box::new(LangInfo { code: "xx", name: "x", source: b"\x00garbage", plural: plural_none, complete_menus: false, catalog: OnceLock::new() })); + assert_eq!(info.text(), ""); + assert_eq!(tr(Lang(info), "Layer"), "Layer", "falls back to English"); +} + +/// Packed lines unpack to their keys; references to keys that don't exist are an error, not a +/// panic. +#[test] +fn packed_lines_unpack_and_bad_references_are_errors() { + let keys = ["\tOpen", "@id\tfile.open", "\tClose"]; + let packed = "# c\n\x01Ouvrir\n\x02-1\tOuvrir\n\x02+1\tFermer\n\x03\x01x\n"; + assert_eq!(expand(packed, &keys).unwrap(), "# c\n\tOpen\tOuvrir\n\tOpen\tOuvrir\n\tClose\tFermer\n\x01x\n"); + for bad in ["\x02-1\tx", "\x02 3\tx", "\x023", "\x029223372036854775807\tx", "\x02-9223372036854775808\tx", "\x01a\n\x01b\n\x01c\n\x01d"] { + assert!(expand(bad, &keys).is_err(), "{bad:?}"); + } +} + +/// Every bundled catalog is well-formed and consistent with its sources. +#[test] +fn bundled_catalogs_are_consistent() { + for l in &LANGUAGES { + assert!(l.code == l.code.to_ascii_lowercase() && !l.name.is_empty(), "{}", l.code); + let (entries, errors) = parse_entries(&l.text()); + assert!(errors.is_empty(), "{}: {errors:?}", l.code); + let mut seen = std::collections::HashSet::new(); + for (ctx, src, tr) in &entries { + assert!(seen.insert((ctx.clone(), src.clone())), "{}: duplicate {ctx:?} {src:?}", l.code); + if ctx == "@plural" { + let one_other: Vec<&str> = src.split('|').collect(); + assert_eq!(one_other.len(), 2, "{}: plural source must be `one|other`: {src:?}", l.code); + let forms = (0..=1000).map(l.plural).max().unwrap_or(0) + 1; + assert_eq!(tr.split('|').count(), forms, "{}: {forms} plural forms expected in {src:?}", l.code); + for form in tr.split('|') { + let mut want = placeholders(one_other[1]); + let mut got = placeholders(form); + want.sort_unstable(); + got.sort_unstable(); + assert_eq!(want, got, "{}: placeholders differ in {src:?}", l.code); + } + continue; + } + let mut want = placeholders(src); + let mut got = placeholders(tr); + want.sort_unstable(); + got.sort_unstable(); + assert_eq!(want, got, "{}: placeholders differ in {src:?}", l.code); + if ctx.is_empty() { + assert_eq!(src.ends_with('…'), tr.ends_with('…'), "{}: ellipsis mismatch: {src:?}", l.code); + } + if ctx == "@id" { + assert!(crate::menus::is_live(src) || crate::menu_catalog::CATALOG.iter().any(|m| m.3 == src), "{}: unknown command id {src:?}", l.code); + } + } + } +} From 76b561baa369442a71dbf54c9e00ccad5cf487ae Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:41 +0000 Subject: [PATCH 110/259] refactor(ui-egui): move theme.rs tests to theme/tests.rs --- crates/ui-egui/src/theme.rs | 360 +----------------------------- crates/ui-egui/src/theme/tests.rs | 356 +++++++++++++++++++++++++++++ 2 files changed, 357 insertions(+), 359 deletions(-) create mode 100644 crates/ui-egui/src/theme/tests.rs diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index b2620ced01..822d79e148 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -1104,365 +1104,7 @@ pub fn canvas_bg(t: &Tokens) -> Color32 { } #[cfg(test)] -mod tests { - use super::*; - - fn text_sizes(ctx: &egui::Context) -> Vec { - let mut sizes = Vec::new(); - // The plugin queues changed fonts at the end of a pass; egui applies them next pass. - ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); - ctx.run_ui(Default::default(), |ui| { - // Include custom painter fonts and explicit RichText sizes, not just text styles. - for font in [FontId::proportional(11.5), medium(12.0), semibold(15.0), mono(12.0), TextStyle::Body.resolve(ui.style())] { - sizes.push(ui.painter().layout_no_wrap("Interface 123".into(), font, Color32::WHITE).size()); - } - sizes.push(ui.label(egui::RichText::new("Interface 123").size(13.0)).rect.size()); - }) - .textures_delta - .clear(); - sizes - } - - #[test] - fn ui_font_sizes_scale_shaping_and_row_height_without_accumulating() { - let ctx = egui::Context::default(); - install_fonts(&ctx); - apply(&ctx, ThemeKind::Pro); - let original = text_sizes(&ctx); - let definitions = ctx.fonts(|f| f.definitions().clone()); - for size in [UiFontSize::Tiny, UiFontSize::Small, UiFontSize::Medium, UiFontSize::Large, UiFontSize::Tiny, UiFontSize::Small] { - set_ui_font_size(&ctx, size); - let measured = text_sizes(&ctx); - for (before, after) in original.iter().zip(&measured) { - let expected = *before * font_scale(size); - assert!((after.x - expected.x).abs() < 1.0, "{size:?}: width {after:?} vs {expected:?}"); - // egui rounds ascent/descent and the final row height to pixels separately. - assert!((after.y - expected.y).abs() < 1.1, "{size:?}: height {after:?} vs {expected:?}"); - } - set_ui_font_size(&ctx, size); - assert_eq!(text_sizes(&ctx), measured, "setting the same size twice is stable"); - } - assert_eq!(ctx.fonts(|f| f.definitions().clone()), definitions, "Small restores original font tweaks exactly"); - assert_eq!(ctx.zoom_factor(), 1.0); - } - - // Regression test for #4630: the stock thin scroll bar fades its handle to the same opacity - // as its track while the pointer is on it, so the thumb disappeared when it was grabbed. - #[test] - fn scrollbar_thumb_stays_more_visible_than_its_track_in_every_theme() { - for kind in ThemeKind::ALL { - let ctx = egui::Context::default(); - apply(&ctx, kind); - for theme in [egui::Theme::Dark, egui::Theme::Light] { - let scroll = ctx.style_of(theme).spacing.scroll; - if !scroll.floating { - continue; - } - assert!( - scroll.interact_handle_opacity > scroll.interact_background_opacity, - "{kind:?}/{theme:?}: handle {} vs track {} under the pointer", - scroll.interact_handle_opacity, - scroll.interact_background_opacity - ); - assert_eq!(scroll.interact_handle_opacity, 1.0, "{kind:?}/{theme:?}: the thumb is opaque under the pointer"); - } - } - } - - /// The desktop app installs fonts and loads the saved UI Font Size in its first frame, while - /// egui's default fonts are still active. Any size but Small then panicked on the next pass - /// ("FontFamily::Name("medium") is not bound to any fonts") because the plugin rescaled a - /// copy of the defaults and that replaced the queued Inter stack. - #[test] - fn saved_ui_font_size_survives_first_frame_install() { - let ctx = egui::Context::default(); - let medium_bound = |ctx: &egui::Context| ctx.fonts(|f| f.families().contains(&FontFamily::Name("medium".into()))); - ctx.run_ui(Default::default(), |ui| { - assert!(!medium_bound(ui.ctx()), "egui's defaults are active in the first frame"); - install_fonts(ui.ctx()); - apply(ui.ctx(), ThemeKind::Pro); - set_ui_font_size(ui.ctx(), UiFontSize::Medium); - }) - .textures_delta - .clear(); - let mut width = 0.0; - ctx.run_ui(Default::default(), |ui| { - assert!(medium_bound(ui.ctx()), "the installed stack reaches the second pass"); - width = ui.painter().layout_no_wrap("PhotoCraft".into(), medium(13.0), Color32::WHITE).size().x; - }) - .textures_delta - .clear(); - assert!(width > 0.0); - // The saved size applies one pass later, from the installed stack. - ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); - let mut scaled = 0.0; - ctx.run_ui(Default::default(), |ui| { - assert!(medium_bound(ui.ctx())); - scaled = ui.painter().layout_no_wrap("PhotoCraft".into(), medium(13.0), Color32::WHITE).size().x; - }) - .textures_delta - .clear(); - assert!((scaled - width * font_scale(UiFontSize::Medium)).abs() < 1.0, "{scaled} vs {width} × 14/12"); - // Re-installing (a language change) keeps the size and the named families. - ctx.run_ui(Default::default(), |ui| install_fonts(ui.ctx())).textures_delta.clear(); - for _ in 0..2 { - ctx.run_ui(Default::default(), |ui| { - assert!(medium_bound(ui.ctx())); - let w = ui.painter().layout_no_wrap("PhotoCraft".into(), medium(13.0), Color32::WHITE).size().x; - assert!((w - scaled).abs() < 1.0, "{w} vs {scaled}"); - }) - .textures_delta - .clear(); - } - } - - #[test] - fn pro_light_gray_and_light_themes() { - // #2661: Photoshop's third and fourth brightness levels, with the Pro layout. - for (kind, panel, id, label) in - [(ThemeKind::ProLightGray, 184, "proLightGray", "Pro (Light Gray)"), (ThemeKind::ProLight, 240, "proLight", "Pro (Light)")] - { - let t = Tokens::for_kind(kind); - assert!(t.pro && !t.dark() && !t.bevel && kind.is_pro(), "{kind:?}"); - assert_eq!((t.kind, t.card, t.chrome), (kind, Color32::from_gray(panel), Color32::from_gray(panel))); - assert_eq!((kind.id(), kind.label()), (id, label)); - assert_eq!(ThemeKind::from_name(id), Some(kind)); - assert_eq!(ThemeKind::from_name(label), Some(kind)); - assert!(ThemeKind::ALL.contains(&kind)); - // Text stays readable (WCAG AA for body text, 3:1 for dim and faint labels and icons). - for bg in [t.card, t.chrome, t.dock, t.field, t.hover, t.row_selected, t.tab_strip] { - assert!(contrast(t.text, bg) >= 4.5, "{kind:?} text on {bg:?}: {}", contrast(t.text, bg)); - assert!(contrast(t.icon, bg) >= 3.0, "{kind:?} icon on {bg:?}"); - assert!(contrast(t.text_dim, bg) >= 3.0, "{kind:?} dim text on {bg:?}"); - } - assert!(contrast(t.text_faint, t.card) >= 2.0, "{kind:?} faint text"); - assert!(contrast(t.accent_text, t.card) >= 3.0, "{kind:?} accent text"); - } - // The four Pro levels step from darkest to lightest, as in Photoshop. - let cards = [ThemeKind::Pro, ThemeKind::ProMedium, ThemeKind::ProLightGray, ThemeKind::ProLight].map(|k| Tokens::for_kind(k).card.r()); - assert!(cards.windows(2).all(|w| w[0] < w[1]), "{cards:?}"); - assert!(!ThemeKind::Studio.is_pro() && !ThemeKind::StudioLight.is_pro() && !ThemeKind::Classic.is_pro()); - assert_eq!(ThemeKind::from_name("light gray"), Some(ThemeKind::ProLightGray)); - assert_eq!(ThemeKind::from_name("lightest"), Some(ThemeKind::ProLight)); - } - - #[test] - fn field_selection_is_grey_only_for_the_monochrome_pro_themes() { - // #3789: a text field's selection is a subtle grey in the monochrome Pro themes, not a - // second blue accent; coloured themes keep their accent. - assert_eq!(Tokens::for_kind(ThemeKind::Pro).field_selection(), Color32::from_gray(96)); - assert_eq!(Tokens::for_kind(ThemeKind::ProLight).field_selection(), Color32::from_gray(201)); - assert_eq!(Tokens::for_kind(ThemeKind::Studio).field_selection(), Tokens::for_kind(ThemeKind::Studio).accent_soft); - assert_eq!(Tokens::for_kind(ThemeKind::Classic).field_selection(), Tokens::for_kind(ThemeKind::Classic).accent_soft); - } - - #[test] - fn theme_names_parse() { - assert_eq!(ThemeKind::from_name("Classic"), Some(ThemeKind::Classic)); - assert_eq!(ThemeKind::from_name("studio (light)"), Some(ThemeKind::StudioLight)); - assert_eq!(ThemeKind::from_name("dark"), Some(ThemeKind::Pro)); - assert_eq!(ThemeKind::from_name("light"), Some(ThemeKind::ProLight)); - assert_eq!(ThemeKind::from_name("studio"), Some(ThemeKind::Studio)); - assert_eq!(ThemeKind::from_name("Pro (Medium Gray)"), Some(ThemeKind::ProMedium)); - assert_eq!(ThemeKind::from_name("Solarized Dark"), Some(ThemeKind::SolarizedDark)); - assert_eq!(ThemeKind::from_name("solarized"), Some(ThemeKind::SolarizedDark)); - let m = Tokens::for_kind(ThemeKind::ProMedium); - assert!(m.pro && m.dark() && m.kind == ThemeKind::ProMedium && m.card == Color32::from_rgb(83, 83, 83)); - let s = Tokens::for_kind(ThemeKind::SolarizedDark); - assert!(s.dark() && !s.bevel && s.kind == ThemeKind::SolarizedDark && s.card == Color32::from_rgb(7, 54, 66)); - assert_eq!(ThemeKind::from_name("neon"), None); - } - - #[test] - fn every_palette_keeps_complete_egui_styles_when_the_os_changes() { - for kind in ThemeKind::ALL { - let ctx = egui::Context::default(); - ctx.run_ui(egui::RawInput { system_theme: Some(egui::Theme::Dark), ..Default::default() }, |ui| apply(ui.ctx(), kind)).textures_delta.clear(); - let expected = ctx.global_style(); - for appearance in [Some(egui::Theme::Light), Some(egui::Theme::Dark), None] { - ctx.run_ui(egui::RawInput { system_theme: appearance, ..Default::default() }, |_| {}).textures_delta.clear(); - assert_eq!(Tokens::get(&ctx), Tokens::for_kind(kind)); - assert_eq!(ctx.global_style(), expected, "{kind:?} changed with {appearance:?}"); - assert_eq!(ctx.style_of(egui::Theme::Light), expected); - assert_eq!(ctx.style_of(egui::Theme::Dark), expected); - } - } - } - - #[test] - fn applying_a_palette_clears_a_pinned_native_appearance_preference() { - for pinned in [egui::Theme::Light, egui::Theme::Dark] { - let ctx = egui::Context::default(); - ctx.set_theme(pinned); - apply(&ctx, ThemeKind::ProMedium); - assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::System); - } - } - - #[test] - fn studio_text_contrast_is_high() { - let t = Tokens::for_kind(ThemeKind::Studio); - let p = Tokens::for_kind(ThemeKind::Pro); - assert!(p.pro && !t.pro); - let lum = |c: Color32| 0.2126 * c.r() as f32 + 0.7152 * c.g() as f32 + 0.0722 * c.b() as f32; - assert!(lum(t.text) - lum(t.card) > 180.0); - assert!(lum(t.text_dim) - lum(t.card) > 90.0); - } - - /// WCAG 2 contrast ratio, the measure libadwaita's own palette is held to. - fn contrast(a: Color32, b: Color32) -> f32 { - let lin = |v: u8| { - let c = f32::from(v) / 255.0; - if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } - }; - let lum = |c: Color32| 0.2126 * lin(c.r()) + 0.7152 * lin(c.g()) + 0.0722 * lin(c.b()); - let (hi, lo) = if lum(a) > lum(b) { (lum(a), lum(b)) } else { (lum(b), lum(a)) }; - (hi + 0.05) / (lo + 0.05) - } - - /// The light themes outline their white slider knob so its edge holds WCAG's 3:1 non-text - /// contrast against the panels sliders sit on (#7927); the dark ones keep the plain knob. - #[test] - fn light_themes_outline_the_slider_knob() { - for kind in ThemeKind::ALL { - let t = Tokens::for_kind(kind); - // The Pro layouts keep their dark ring (it rims a grey knob), Classic its bevelled knob. - if t.pro || t.bevel { - continue; - } - match t.knob_outline() { - Some(outline) => { - assert!(!t.dark(), "{kind:?}"); - for panel in [t.dock, t.card, t.chrome] { - assert!(contrast(outline, panel) >= 3.0, "{kind:?}: knob outline {outline:?} on {panel:?}"); - } - } - None => assert!(t.dark(), "{kind:?}: a light theme without a knob outline"), - } - } - assert_eq!(Tokens::for_kind(ThemeKind::Pro).knob_outline(), Some(Color32::from_gray(40)), "Pro is unchanged"); - for kind in [ThemeKind::StudioLight, ThemeKind::Adwaita, ThemeKind::BreezeLight, ThemeKind::SoftLight] { - assert!(Tokens::for_kind(kind).knob_outline().is_some(), "{kind:?}"); - } - } - - #[test] - fn adwaita_themes_parse_and_meet_text_contrast() { - for kind in [ThemeKind::Adwaita, ThemeKind::AdwaitaDark] { - assert_eq!(ThemeKind::from_name(kind.id()), Some(kind)); - assert_eq!(ThemeKind::from_name(kind.label()), Some(kind)); - let t = Tokens::for_kind(kind); - assert_eq!(t.kind, kind); - assert_eq!(t.dark(), kind == ThemeKind::AdwaitaDark); - assert!(!t.pro && !t.bevel, "{kind:?} uses the Studio layout"); - // AA body text (4.5:1) on every surface that carries labels. - for surface in [t.chrome, t.dock, t.card, t.field] { - assert!(contrast(t.text, surface) >= 7.0, "{kind:?}: text on {surface:?}"); - assert!(contrast(t.text_dim, surface) >= 4.5, "{kind:?}: dim text on {surface:?}"); - } - assert!(contrast(t.primary_text, t.primary_bg) >= 3.0, "{kind:?}: suggested-action button label"); - } - assert_eq!(ThemeKind::from_name("gnome dark"), Some(ThemeKind::AdwaitaDark)); - } - - #[test] - fn soft_themes_parse_and_hold_text_contrast() { - for (kind, alias) in [(ThemeKind::SoftDark, "soft dark"), (ThemeKind::SoftLight, "Soft_Light")] { - assert_eq!(ThemeKind::from_name(kind.id()), Some(kind)); - assert_eq!(ThemeKind::from_name(kind.label()), Some(kind)); - assert_eq!(ThemeKind::from_name(alias), Some(kind)); - assert!(ThemeKind::ALL.contains(&kind)); - let t = Tokens::for_kind(kind); - assert_eq!(t.kind, kind); - assert_eq!(t.dark(), kind == ThemeKind::SoftDark); - assert!(!t.pro && !t.bevel); - // Soft means no extremes: surfaces stay off black and white. - for c in [t.chrome, t.canvas, t.dock, t.card, t.field] { - let (hi, lo) = (c.r().max(c.g()).max(c.b()), c.r().min(c.g()).min(c.b())); - assert!(if t.dark() { (32..96).contains(&hi) } else { hi < 255 && lo > 200 }, "{kind:?}: {c:?}"); - } - let tint = |under: Color32| { - let k = f32::from(t.accent_soft.a()) / 255.0; - let ch = |over: u8, under: u8| (f32::from(over) * k + f32::from(under) * (1.0 - k)).round() as u8; - Color32::from_rgb(ch(t.accent.r(), under.r()), ch(t.accent.g(), under.g()), ch(t.accent.b(), under.b())) - }; - let surfaces = [t.chrome, t.canvas, t.dock, t.card, t.field, t.hover, t.pressed, tint(t.dock), tint(t.card)]; - for (i, surface) in surfaces.into_iter().enumerate() { - for (name, colour) in [("text", t.text), ("dim", t.text_dim), ("faint", t.text_faint), ("accent text", t.accent_text)] { - assert!(contrast(colour, surface) >= 4.5, "{kind:?}: {name} on {surface:?}"); - } - // Status colours are marks on hovered or selected surfaces (3:1), text on resting ones. - let floor = if i < 5 { 4.5 } else { 3.0 }; - assert!(contrast(t.danger, surface) >= floor && contrast(t.warning, surface) >= floor, "{kind:?}: status on {surface:?}"); - } - for k in [1.0, 0.93, 0.85] { - assert!(contrast(t.primary_text, t.primary_bg.gamma_multiply(k)) >= 4.5, "{kind:?}: primary at {k}"); - } - } - } - - #[test] - fn breeze_themes_parse_and_meet_text_contrast() { - for (kind, aliases) in [ - (ThemeKind::BreezeLight, ["breeze", "Breeze Light", "breeze_light", "kde", "plasma"]), - (ThemeKind::BreezeDark, ["breeze dark", "Breeze Dark", "breeze_dark", "kde dark", "plasma-dark"]), - ] { - assert_eq!(ThemeKind::from_name(kind.id()), Some(kind)); - assert_eq!(ThemeKind::from_name(kind.label()), Some(kind)); - for alias in aliases { - assert_eq!(ThemeKind::from_name(alias), Some(kind), "{alias}"); - } - assert!(ThemeKind::ALL.contains(&kind)); - let t = Tokens::for_kind(kind); - assert_eq!(t.kind, kind); - assert_eq!(t.dark(), kind == ThemeKind::BreezeDark); - assert!(!t.pro && !t.bevel, "{kind:?} uses the Studio layout"); - // The design intent, not exact values (the palette is an adaptation and may be tuned): - // the canvas is the most recessed surface, then the dock and the cards, and controls - // sit above the cards they are on; the accent is a blue. - let lum = |c: Color32| u32::from(c.r()) + u32::from(c.g()) + u32::from(c.b()); - assert!(lum(t.canvas) < lum(t.dock) && lum(t.dock) < lum(t.card) && lum(t.card) < lum(t.field), "{kind:?}: surface order"); - assert!(t.accent.b() > t.accent.g() && t.accent.g() > t.accent.r(), "blue accent: {:?}", t.accent); - // Plasma's surfaces are cool blue-greys: dark ones stay below 64 per channel and light - // ones above 205, all with a little more blue than red (our own values, close to it). - for c in [t.chrome, t.canvas, t.dock, t.card, t.field] { - assert!(if t.dark() { c.r().max(c.g()).max(c.b()) < 64 } else { c.r().min(c.g()).min(c.b()) > 205 }, "{kind:?}: {c:?}"); - assert!(c.b() > c.r(), "{kind:?}: blue-grey {c:?}"); - } - // All text must read: AA (4.5:1) for every text colour on every surface it can sit on, - // including a hovered or pressed control and a selected (accent-tinted) row. - let tint = |under: Color32| { - let k = f32::from(t.accent_soft.a()) / 255.0; - let ch = |over: u8, under: u8| (f32::from(over) * k + f32::from(under) * (1.0 - k)).round() as u8; - Color32::from_rgb(ch(t.accent.r(), under.r()), ch(t.accent.g(), under.g()), ch(t.accent.b(), under.b())) - }; - let resting = [t.chrome, t.canvas, t.dock, t.card, t.field]; - let active = [t.hover, t.pressed, tint(t.chrome), tint(t.dock), tint(t.card), tint(t.field)]; - for surface in resting.into_iter().chain(active) { - for (name, colour) in [("text", t.text), ("dim text", t.text_dim), ("faint text", t.text_faint), ("accent text", t.accent_text)] { - assert!(contrast(colour, surface) >= 4.5, "{kind:?}: {name} on {surface:?}"); - } - } - // The text must also keep a hierarchy, not collapse into one grey. - assert!(contrast(t.text, t.card) > contrast(t.text_dim, t.card) && contrast(t.text_dim, t.card) > contrast(t.text_faint, t.card), "{kind:?}"); - // Danger and warning colours carry text on the resting surfaces; on hovered, pressed and - // selected ones they are status marks, held to the 3:1 of graphical objects. - for surface in resting { - assert!(contrast(t.danger, surface) >= 4.5, "{kind:?}: danger on {surface:?}"); - assert!(contrast(t.warning, surface) >= 4.5, "{kind:?}: warning on {surface:?}"); - } - for surface in active { - assert!(contrast(t.danger, surface) >= 3.0, "{kind:?}: danger on {surface:?}"); - assert!(contrast(t.warning, surface) >= 3.0, "{kind:?}: warning on {surface:?}"); - } - // A primary button darkens while hovered and pressed (button_impl), so check all three. - for k in [1.0, 0.93, 0.85] { - assert!(contrast(t.primary_text, t.primary_bg.gamma_multiply(k)) >= 4.5, "{kind:?}: primary button label at {k}"); - } - assert!(contrast(t.caption_close_text, t.caption_close) >= 4.5, "{kind:?}: close button glyph"); - } - } -} +mod tests; /// Development feature: live design-token overrides. /// diff --git a/crates/ui-egui/src/theme/tests.rs b/crates/ui-egui/src/theme/tests.rs new file mode 100644 index 0000000000..e6b548089d --- /dev/null +++ b/crates/ui-egui/src/theme/tests.rs @@ -0,0 +1,356 @@ +use super::*; + +fn text_sizes(ctx: &egui::Context) -> Vec { + let mut sizes = Vec::new(); + // The plugin queues changed fonts at the end of a pass; egui applies them next pass. + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); + ctx.run_ui(Default::default(), |ui| { + // Include custom painter fonts and explicit RichText sizes, not just text styles. + for font in [FontId::proportional(11.5), medium(12.0), semibold(15.0), mono(12.0), TextStyle::Body.resolve(ui.style())] { + sizes.push(ui.painter().layout_no_wrap("Interface 123".into(), font, Color32::WHITE).size()); + } + sizes.push(ui.label(egui::RichText::new("Interface 123").size(13.0)).rect.size()); + }) + .textures_delta + .clear(); + sizes +} + +#[test] +fn ui_font_sizes_scale_shaping_and_row_height_without_accumulating() { + let ctx = egui::Context::default(); + install_fonts(&ctx); + apply(&ctx, ThemeKind::Pro); + let original = text_sizes(&ctx); + let definitions = ctx.fonts(|f| f.definitions().clone()); + for size in [UiFontSize::Tiny, UiFontSize::Small, UiFontSize::Medium, UiFontSize::Large, UiFontSize::Tiny, UiFontSize::Small] { + set_ui_font_size(&ctx, size); + let measured = text_sizes(&ctx); + for (before, after) in original.iter().zip(&measured) { + let expected = *before * font_scale(size); + assert!((after.x - expected.x).abs() < 1.0, "{size:?}: width {after:?} vs {expected:?}"); + // egui rounds ascent/descent and the final row height to pixels separately. + assert!((after.y - expected.y).abs() < 1.1, "{size:?}: height {after:?} vs {expected:?}"); + } + set_ui_font_size(&ctx, size); + assert_eq!(text_sizes(&ctx), measured, "setting the same size twice is stable"); + } + assert_eq!(ctx.fonts(|f| f.definitions().clone()), definitions, "Small restores original font tweaks exactly"); + assert_eq!(ctx.zoom_factor(), 1.0); +} + +// Regression test for #4630: the stock thin scroll bar fades its handle to the same opacity +// as its track while the pointer is on it, so the thumb disappeared when it was grabbed. +#[test] +fn scrollbar_thumb_stays_more_visible_than_its_track_in_every_theme() { + for kind in ThemeKind::ALL { + let ctx = egui::Context::default(); + apply(&ctx, kind); + for theme in [egui::Theme::Dark, egui::Theme::Light] { + let scroll = ctx.style_of(theme).spacing.scroll; + if !scroll.floating { + continue; + } + assert!( + scroll.interact_handle_opacity > scroll.interact_background_opacity, + "{kind:?}/{theme:?}: handle {} vs track {} under the pointer", + scroll.interact_handle_opacity, + scroll.interact_background_opacity + ); + assert_eq!(scroll.interact_handle_opacity, 1.0, "{kind:?}/{theme:?}: the thumb is opaque under the pointer"); + } + } +} + +/// The desktop app installs fonts and loads the saved UI Font Size in its first frame, while +/// egui's default fonts are still active. Any size but Small then panicked on the next pass +/// ("FontFamily::Name("medium") is not bound to any fonts") because the plugin rescaled a +/// copy of the defaults and that replaced the queued Inter stack. +#[test] +fn saved_ui_font_size_survives_first_frame_install() { + let ctx = egui::Context::default(); + let medium_bound = |ctx: &egui::Context| ctx.fonts(|f| f.families().contains(&FontFamily::Name("medium".into()))); + ctx.run_ui(Default::default(), |ui| { + assert!(!medium_bound(ui.ctx()), "egui's defaults are active in the first frame"); + install_fonts(ui.ctx()); + apply(ui.ctx(), ThemeKind::Pro); + set_ui_font_size(ui.ctx(), UiFontSize::Medium); + }) + .textures_delta + .clear(); + let mut width = 0.0; + ctx.run_ui(Default::default(), |ui| { + assert!(medium_bound(ui.ctx()), "the installed stack reaches the second pass"); + width = ui.painter().layout_no_wrap("PhotoCraft".into(), medium(13.0), Color32::WHITE).size().x; + }) + .textures_delta + .clear(); + assert!(width > 0.0); + // The saved size applies one pass later, from the installed stack. + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); + let mut scaled = 0.0; + ctx.run_ui(Default::default(), |ui| { + assert!(medium_bound(ui.ctx())); + scaled = ui.painter().layout_no_wrap("PhotoCraft".into(), medium(13.0), Color32::WHITE).size().x; + }) + .textures_delta + .clear(); + assert!((scaled - width * font_scale(UiFontSize::Medium)).abs() < 1.0, "{scaled} vs {width} × 14/12"); + // Re-installing (a language change) keeps the size and the named families. + ctx.run_ui(Default::default(), |ui| install_fonts(ui.ctx())).textures_delta.clear(); + for _ in 0..2 { + ctx.run_ui(Default::default(), |ui| { + assert!(medium_bound(ui.ctx())); + let w = ui.painter().layout_no_wrap("PhotoCraft".into(), medium(13.0), Color32::WHITE).size().x; + assert!((w - scaled).abs() < 1.0, "{w} vs {scaled}"); + }) + .textures_delta + .clear(); + } +} + +#[test] +fn pro_light_gray_and_light_themes() { + // #2661: Photoshop's third and fourth brightness levels, with the Pro layout. + for (kind, panel, id, label) in [(ThemeKind::ProLightGray, 184, "proLightGray", "Pro (Light Gray)"), (ThemeKind::ProLight, 240, "proLight", "Pro (Light)")] + { + let t = Tokens::for_kind(kind); + assert!(t.pro && !t.dark() && !t.bevel && kind.is_pro(), "{kind:?}"); + assert_eq!((t.kind, t.card, t.chrome), (kind, Color32::from_gray(panel), Color32::from_gray(panel))); + assert_eq!((kind.id(), kind.label()), (id, label)); + assert_eq!(ThemeKind::from_name(id), Some(kind)); + assert_eq!(ThemeKind::from_name(label), Some(kind)); + assert!(ThemeKind::ALL.contains(&kind)); + // Text stays readable (WCAG AA for body text, 3:1 for dim and faint labels and icons). + for bg in [t.card, t.chrome, t.dock, t.field, t.hover, t.row_selected, t.tab_strip] { + assert!(contrast(t.text, bg) >= 4.5, "{kind:?} text on {bg:?}: {}", contrast(t.text, bg)); + assert!(contrast(t.icon, bg) >= 3.0, "{kind:?} icon on {bg:?}"); + assert!(contrast(t.text_dim, bg) >= 3.0, "{kind:?} dim text on {bg:?}"); + } + assert!(contrast(t.text_faint, t.card) >= 2.0, "{kind:?} faint text"); + assert!(contrast(t.accent_text, t.card) >= 3.0, "{kind:?} accent text"); + } + // The four Pro levels step from darkest to lightest, as in Photoshop. + let cards = [ThemeKind::Pro, ThemeKind::ProMedium, ThemeKind::ProLightGray, ThemeKind::ProLight].map(|k| Tokens::for_kind(k).card.r()); + assert!(cards.windows(2).all(|w| w[0] < w[1]), "{cards:?}"); + assert!(!ThemeKind::Studio.is_pro() && !ThemeKind::StudioLight.is_pro() && !ThemeKind::Classic.is_pro()); + assert_eq!(ThemeKind::from_name("light gray"), Some(ThemeKind::ProLightGray)); + assert_eq!(ThemeKind::from_name("lightest"), Some(ThemeKind::ProLight)); +} + +#[test] +fn field_selection_is_grey_only_for_the_monochrome_pro_themes() { + // #3789: a text field's selection is a subtle grey in the monochrome Pro themes, not a + // second blue accent; coloured themes keep their accent. + assert_eq!(Tokens::for_kind(ThemeKind::Pro).field_selection(), Color32::from_gray(96)); + assert_eq!(Tokens::for_kind(ThemeKind::ProLight).field_selection(), Color32::from_gray(201)); + assert_eq!(Tokens::for_kind(ThemeKind::Studio).field_selection(), Tokens::for_kind(ThemeKind::Studio).accent_soft); + assert_eq!(Tokens::for_kind(ThemeKind::Classic).field_selection(), Tokens::for_kind(ThemeKind::Classic).accent_soft); +} + +#[test] +fn theme_names_parse() { + assert_eq!(ThemeKind::from_name("Classic"), Some(ThemeKind::Classic)); + assert_eq!(ThemeKind::from_name("studio (light)"), Some(ThemeKind::StudioLight)); + assert_eq!(ThemeKind::from_name("dark"), Some(ThemeKind::Pro)); + assert_eq!(ThemeKind::from_name("light"), Some(ThemeKind::ProLight)); + assert_eq!(ThemeKind::from_name("studio"), Some(ThemeKind::Studio)); + assert_eq!(ThemeKind::from_name("Pro (Medium Gray)"), Some(ThemeKind::ProMedium)); + assert_eq!(ThemeKind::from_name("Solarized Dark"), Some(ThemeKind::SolarizedDark)); + assert_eq!(ThemeKind::from_name("solarized"), Some(ThemeKind::SolarizedDark)); + let m = Tokens::for_kind(ThemeKind::ProMedium); + assert!(m.pro && m.dark() && m.kind == ThemeKind::ProMedium && m.card == Color32::from_rgb(83, 83, 83)); + let s = Tokens::for_kind(ThemeKind::SolarizedDark); + assert!(s.dark() && !s.bevel && s.kind == ThemeKind::SolarizedDark && s.card == Color32::from_rgb(7, 54, 66)); + assert_eq!(ThemeKind::from_name("neon"), None); +} + +#[test] +fn every_palette_keeps_complete_egui_styles_when_the_os_changes() { + for kind in ThemeKind::ALL { + let ctx = egui::Context::default(); + ctx.run_ui(egui::RawInput { system_theme: Some(egui::Theme::Dark), ..Default::default() }, |ui| apply(ui.ctx(), kind)).textures_delta.clear(); + let expected = ctx.global_style(); + for appearance in [Some(egui::Theme::Light), Some(egui::Theme::Dark), None] { + ctx.run_ui(egui::RawInput { system_theme: appearance, ..Default::default() }, |_| {}).textures_delta.clear(); + assert_eq!(Tokens::get(&ctx), Tokens::for_kind(kind)); + assert_eq!(ctx.global_style(), expected, "{kind:?} changed with {appearance:?}"); + assert_eq!(ctx.style_of(egui::Theme::Light), expected); + assert_eq!(ctx.style_of(egui::Theme::Dark), expected); + } + } +} + +#[test] +fn applying_a_palette_clears_a_pinned_native_appearance_preference() { + for pinned in [egui::Theme::Light, egui::Theme::Dark] { + let ctx = egui::Context::default(); + ctx.set_theme(pinned); + apply(&ctx, ThemeKind::ProMedium); + assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::System); + } +} + +#[test] +fn studio_text_contrast_is_high() { + let t = Tokens::for_kind(ThemeKind::Studio); + let p = Tokens::for_kind(ThemeKind::Pro); + assert!(p.pro && !t.pro); + let lum = |c: Color32| 0.2126 * c.r() as f32 + 0.7152 * c.g() as f32 + 0.0722 * c.b() as f32; + assert!(lum(t.text) - lum(t.card) > 180.0); + assert!(lum(t.text_dim) - lum(t.card) > 90.0); +} + +/// WCAG 2 contrast ratio, the measure libadwaita's own palette is held to. +fn contrast(a: Color32, b: Color32) -> f32 { + let lin = |v: u8| { + let c = f32::from(v) / 255.0; + if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } + }; + let lum = |c: Color32| 0.2126 * lin(c.r()) + 0.7152 * lin(c.g()) + 0.0722 * lin(c.b()); + let (hi, lo) = if lum(a) > lum(b) { (lum(a), lum(b)) } else { (lum(b), lum(a)) }; + (hi + 0.05) / (lo + 0.05) +} + +/// The light themes outline their white slider knob so its edge holds WCAG's 3:1 non-text +/// contrast against the panels sliders sit on (#7927); the dark ones keep the plain knob. +#[test] +fn light_themes_outline_the_slider_knob() { + for kind in ThemeKind::ALL { + let t = Tokens::for_kind(kind); + // The Pro layouts keep their dark ring (it rims a grey knob), Classic its bevelled knob. + if t.pro || t.bevel { + continue; + } + match t.knob_outline() { + Some(outline) => { + assert!(!t.dark(), "{kind:?}"); + for panel in [t.dock, t.card, t.chrome] { + assert!(contrast(outline, panel) >= 3.0, "{kind:?}: knob outline {outline:?} on {panel:?}"); + } + } + None => assert!(t.dark(), "{kind:?}: a light theme without a knob outline"), + } + } + assert_eq!(Tokens::for_kind(ThemeKind::Pro).knob_outline(), Some(Color32::from_gray(40)), "Pro is unchanged"); + for kind in [ThemeKind::StudioLight, ThemeKind::Adwaita, ThemeKind::BreezeLight, ThemeKind::SoftLight] { + assert!(Tokens::for_kind(kind).knob_outline().is_some(), "{kind:?}"); + } +} + +#[test] +fn adwaita_themes_parse_and_meet_text_contrast() { + for kind in [ThemeKind::Adwaita, ThemeKind::AdwaitaDark] { + assert_eq!(ThemeKind::from_name(kind.id()), Some(kind)); + assert_eq!(ThemeKind::from_name(kind.label()), Some(kind)); + let t = Tokens::for_kind(kind); + assert_eq!(t.kind, kind); + assert_eq!(t.dark(), kind == ThemeKind::AdwaitaDark); + assert!(!t.pro && !t.bevel, "{kind:?} uses the Studio layout"); + // AA body text (4.5:1) on every surface that carries labels. + for surface in [t.chrome, t.dock, t.card, t.field] { + assert!(contrast(t.text, surface) >= 7.0, "{kind:?}: text on {surface:?}"); + assert!(contrast(t.text_dim, surface) >= 4.5, "{kind:?}: dim text on {surface:?}"); + } + assert!(contrast(t.primary_text, t.primary_bg) >= 3.0, "{kind:?}: suggested-action button label"); + } + assert_eq!(ThemeKind::from_name("gnome dark"), Some(ThemeKind::AdwaitaDark)); +} + +#[test] +fn soft_themes_parse_and_hold_text_contrast() { + for (kind, alias) in [(ThemeKind::SoftDark, "soft dark"), (ThemeKind::SoftLight, "Soft_Light")] { + assert_eq!(ThemeKind::from_name(kind.id()), Some(kind)); + assert_eq!(ThemeKind::from_name(kind.label()), Some(kind)); + assert_eq!(ThemeKind::from_name(alias), Some(kind)); + assert!(ThemeKind::ALL.contains(&kind)); + let t = Tokens::for_kind(kind); + assert_eq!(t.kind, kind); + assert_eq!(t.dark(), kind == ThemeKind::SoftDark); + assert!(!t.pro && !t.bevel); + // Soft means no extremes: surfaces stay off black and white. + for c in [t.chrome, t.canvas, t.dock, t.card, t.field] { + let (hi, lo) = (c.r().max(c.g()).max(c.b()), c.r().min(c.g()).min(c.b())); + assert!(if t.dark() { (32..96).contains(&hi) } else { hi < 255 && lo > 200 }, "{kind:?}: {c:?}"); + } + let tint = |under: Color32| { + let k = f32::from(t.accent_soft.a()) / 255.0; + let ch = |over: u8, under: u8| (f32::from(over) * k + f32::from(under) * (1.0 - k)).round() as u8; + Color32::from_rgb(ch(t.accent.r(), under.r()), ch(t.accent.g(), under.g()), ch(t.accent.b(), under.b())) + }; + let surfaces = [t.chrome, t.canvas, t.dock, t.card, t.field, t.hover, t.pressed, tint(t.dock), tint(t.card)]; + for (i, surface) in surfaces.into_iter().enumerate() { + for (name, colour) in [("text", t.text), ("dim", t.text_dim), ("faint", t.text_faint), ("accent text", t.accent_text)] { + assert!(contrast(colour, surface) >= 4.5, "{kind:?}: {name} on {surface:?}"); + } + // Status colours are marks on hovered or selected surfaces (3:1), text on resting ones. + let floor = if i < 5 { 4.5 } else { 3.0 }; + assert!(contrast(t.danger, surface) >= floor && contrast(t.warning, surface) >= floor, "{kind:?}: status on {surface:?}"); + } + for k in [1.0, 0.93, 0.85] { + assert!(contrast(t.primary_text, t.primary_bg.gamma_multiply(k)) >= 4.5, "{kind:?}: primary at {k}"); + } + } +} + +#[test] +fn breeze_themes_parse_and_meet_text_contrast() { + for (kind, aliases) in [ + (ThemeKind::BreezeLight, ["breeze", "Breeze Light", "breeze_light", "kde", "plasma"]), + (ThemeKind::BreezeDark, ["breeze dark", "Breeze Dark", "breeze_dark", "kde dark", "plasma-dark"]), + ] { + assert_eq!(ThemeKind::from_name(kind.id()), Some(kind)); + assert_eq!(ThemeKind::from_name(kind.label()), Some(kind)); + for alias in aliases { + assert_eq!(ThemeKind::from_name(alias), Some(kind), "{alias}"); + } + assert!(ThemeKind::ALL.contains(&kind)); + let t = Tokens::for_kind(kind); + assert_eq!(t.kind, kind); + assert_eq!(t.dark(), kind == ThemeKind::BreezeDark); + assert!(!t.pro && !t.bevel, "{kind:?} uses the Studio layout"); + // The design intent, not exact values (the palette is an adaptation and may be tuned): + // the canvas is the most recessed surface, then the dock and the cards, and controls + // sit above the cards they are on; the accent is a blue. + let lum = |c: Color32| u32::from(c.r()) + u32::from(c.g()) + u32::from(c.b()); + assert!(lum(t.canvas) < lum(t.dock) && lum(t.dock) < lum(t.card) && lum(t.card) < lum(t.field), "{kind:?}: surface order"); + assert!(t.accent.b() > t.accent.g() && t.accent.g() > t.accent.r(), "blue accent: {:?}", t.accent); + // Plasma's surfaces are cool blue-greys: dark ones stay below 64 per channel and light + // ones above 205, all with a little more blue than red (our own values, close to it). + for c in [t.chrome, t.canvas, t.dock, t.card, t.field] { + assert!(if t.dark() { c.r().max(c.g()).max(c.b()) < 64 } else { c.r().min(c.g()).min(c.b()) > 205 }, "{kind:?}: {c:?}"); + assert!(c.b() > c.r(), "{kind:?}: blue-grey {c:?}"); + } + // All text must read: AA (4.5:1) for every text colour on every surface it can sit on, + // including a hovered or pressed control and a selected (accent-tinted) row. + let tint = |under: Color32| { + let k = f32::from(t.accent_soft.a()) / 255.0; + let ch = |over: u8, under: u8| (f32::from(over) * k + f32::from(under) * (1.0 - k)).round() as u8; + Color32::from_rgb(ch(t.accent.r(), under.r()), ch(t.accent.g(), under.g()), ch(t.accent.b(), under.b())) + }; + let resting = [t.chrome, t.canvas, t.dock, t.card, t.field]; + let active = [t.hover, t.pressed, tint(t.chrome), tint(t.dock), tint(t.card), tint(t.field)]; + for surface in resting.into_iter().chain(active) { + for (name, colour) in [("text", t.text), ("dim text", t.text_dim), ("faint text", t.text_faint), ("accent text", t.accent_text)] { + assert!(contrast(colour, surface) >= 4.5, "{kind:?}: {name} on {surface:?}"); + } + } + // The text must also keep a hierarchy, not collapse into one grey. + assert!(contrast(t.text, t.card) > contrast(t.text_dim, t.card) && contrast(t.text_dim, t.card) > contrast(t.text_faint, t.card), "{kind:?}"); + // Danger and warning colours carry text on the resting surfaces; on hovered, pressed and + // selected ones they are status marks, held to the 3:1 of graphical objects. + for surface in resting { + assert!(contrast(t.danger, surface) >= 4.5, "{kind:?}: danger on {surface:?}"); + assert!(contrast(t.warning, surface) >= 4.5, "{kind:?}: warning on {surface:?}"); + } + for surface in active { + assert!(contrast(t.danger, surface) >= 3.0, "{kind:?}: danger on {surface:?}"); + assert!(contrast(t.warning, surface) >= 3.0, "{kind:?}: warning on {surface:?}"); + } + // A primary button darkens while hovered and pressed (button_impl), so check all three. + for k in [1.0, 0.93, 0.85] { + assert!(contrast(t.primary_text, t.primary_bg.gamma_multiply(k)) >= 4.5, "{kind:?}: primary button label at {k}"); + } + assert!(contrast(t.caption_close_text, t.caption_close) >= 4.5, "{kind:?}: close button glyph"); + } +} From 805d8b77b8c5f60880b71fbcd7157c450c59d685 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:43 +0000 Subject: [PATCH 111/259] refactor(compose): move effects.rs tests to effects/tests.rs --- crates/compose/src/effects.rs | 1064 +-------------------------- crates/compose/src/effects/tests.rs | 1061 ++++++++++++++++++++++++++ 2 files changed, 1062 insertions(+), 1063 deletions(-) create mode 100644 crates/compose/src/effects/tests.rs diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index cc24e479c3..8bd761fd09 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -2445,1066 +2445,4 @@ fn bevel_dists(s: &Map, reach: f32) -> [Vec; 2] { } #[cfg(test)] -mod tests { - use super::*; - - /// Runs `f` with every parallel pass on this thread using `n` threads (1 = in order), whatever its size. - fn with_threads(n: usize, f: impl FnOnce() -> R) -> R { - struct Restore(Option); - impl Drop for Restore { - fn drop(&mut self) { - THREADS.with(|t| t.set(self.0)); - } - } - let _restore = Restore(THREADS.with(|t| t.replace(Some(n)))); - f() - } - - fn bits(v: &[f32]) -> Vec { - v.iter().map(|x| x.to_bits()).collect() - } - - #[test] - fn edt_is_exact() { - let (w, h) = (7, 5); - let mut inside = vec![false; w * h]; - inside[2 * w + 3] = true; - let d = edt(&inside, w, h); - assert_eq!(d[2 * w + 3], 0.0); - assert!((d[2 * w + 6] - 3.0).abs() < 1e-6); - assert!((d[0] - (9.0f32 + 4.0).sqrt()).abs() < 1e-5); - assert!((d[4 * w + 5] - (4.0f32 + 4.0).sqrt()).abs() < 1e-5); - } - - #[test] - fn edt_two_seeds() { - let (w, h) = (10, 1); - let mut inside = vec![false; w]; - inside[0] = true; - inside[9] = true; - let d = edt(&inside, w, h); - assert_eq!(d, vec![0.0, 1.0, 2.0, 3.0, 4.0, 4.0, 3.0, 2.0, 1.0, 0.0]); - } - - #[test] - fn blur_preserves_mass() { - let mut m = Map::new(21, 21, 0.0); - m.v[10 * 21 + 10] = 1.0; - blur(&mut m, 6.0); - let sum: f32 = m.v.iter().sum(); - assert!((sum - 1.0).abs() < 1e-4, "{sum}"); - assert!(m.v[10 * 21 + 10] < 1.0); - } - - #[test] - fn gradient_geometry() { - let b = Rect::new(0, 0, 100, 100); - let t = |s, x, y| gradient_t(s, 0.0, 1.0, false, (0.0, 0.0), b, x, y); - assert!(t(GradientStyle::Linear, 0.0, 50.0) < 0.01); - // Linear / reflected sample pixel corners: the centre is reached half a pixel later. - assert!((t(GradientStyle::Linear, 50.5, 50.0) - 0.5).abs() < 1e-6); - assert!(t(GradientStyle::Linear, 100.0, 50.0) > 0.99); - assert!(t(GradientStyle::Reflected, 50.5, 50.0) < 1e-6); - assert!((t(GradientStyle::Reflected, 0.0, 50.0) - 1.0).abs() < 1e-6); - assert!(t(GradientStyle::Radial, 50.0, 50.0) < 1e-6); - assert!((t(GradientStyle::Radial, 50.0, 0.0) - 1.0).abs() < 1e-6); - assert!((t(GradientStyle::Diamond, 75.0, 75.0) - 1.0).abs() < 1e-6); - let ang = t(GradientStyle::Angle, 50.0, 0.0); - assert!((ang - 0.75).abs() < 1e-3, "{ang}"); - let rev = gradient_t(GradientStyle::Linear, 0.0, 1.0, true, (0.0, 0.0), b, 0.0, 50.0); - assert!(rev > 0.99); - } - - #[test] - fn effect_gradients_snap_end_points_and_sample_corners() { - // 87° over 600 × 60 at (99, 422): end points (397, 482) and (400, 422), so the overlay runs - // along (3, -60) from its midpoint (398.5, 452), sampled at pixel corners. - let frame = Rect::new(99, 422, 699, 482); - let (a, sc, o) = crate::fill_layout::gradient_layout(GradientStyle::Linear, 87.0, 1.0, (0.0, 0.0), frame); - assert!((a - (60f32).atan2(3.0).to_degrees()).abs() < 1e-3, "{a}"); - let t = |x: f32, y: f32| gradient_t(GradientStyle::Linear, a, sc, false, o, frame, x, y); - assert!((t(399.0, 452.5) - 0.5).abs() < 1e-4, "{}", t(399.0, 452.5)); - assert!(t(400.5, 422.5) > 0.99 && t(397.5, 482.5) < 0.01); - } - - #[test] - fn chamfer_uses_euclidean_step_lengths() { - let (w, h) = (9, 9); - let mut inside = vec![false; w * h]; - inside[0] = true; - let (d, near) = chamfer_nearest(&inside, w, h); - let at = |x: usize, y: usize| d[y * w + x]; - assert!((at(3, 0) - 3.0).abs() < 1e-5); - assert!((at(2, 2) - 2.0 * std::f32::consts::SQRT_2).abs() < 1e-5); - assert!((at(1, 2) - 5f32.sqrt()).abs() < 1e-5); - assert!((at(1, 3) - (5f32.sqrt() + 1.0)).abs() < 1e-5, "knight + straight, not √10"); - assert!((at(2, 3) - (5f32.sqrt() + std::f32::consts::SQRT_2)).abs() < 1e-5); - assert!(near.iter().all(|&n| n == 0)); - } - - #[test] - fn spread_dilates_with_the_chamfer_metric() { - // One opaque pixel grown by 3 px: at offset (1, 3) the chamfer distance is √5 + 1 = 3.236 - // (Euclidean 3.162), so the anti-aliased rim keeps 3 + 0.5 − (3.236 − 0.5) = 0.764. - let mut m = Map::new(9, 9, 0.0); - m.v[4 * 9 + 4] = 1.0; - let d = dilate(&m, 3.0); - assert!((d.v[7 * 9 + 5] - 0.764).abs() < 1e-3, "{}", d.v[7 * 9 + 5]); - // (2, 3): √5 + √2 = 3.650 (Euclidean 3.606) leaves 0.350; axis steps are exact. - assert!((d.v[7 * 9 + 6] - (4.0 - 5f32.sqrt() - std::f32::consts::SQRT_2)).abs() < 1e-4, "{}", d.v[7 * 9 + 6]); - assert_eq!(d.v[4 * 9 + 7], 1.0); - } - - #[test] - fn running_sum_tent_matches_the_kernel() { - let (w, h) = (37usize, 23usize); - let src: Vec = (0..w * h).map(|i| ((i * 7919) % 101) as f32 / 100.0).collect(); - for width in [1.0f32, 2.0, 3.5, 5.0, 8.25, 41.0] { - let mut m = Map { w, h, v: src.clone() }; - tent(&mut m, width); - let mut want = Map { w, h, v: src.clone() }; - tent_direct(&mut want, width); - for (a, b) in m.v.iter().zip(&want.v) { - assert!((a - b).abs() < 1e-5, "width {width}: {a} vs {b}"); - } - } - } - - #[test] - fn tent_kernel_is_two_boxes() { - let (r, k) = tent_kernel(5.0); - assert_eq!(r, 4); - let sum: f32 = k.iter().sum(); - assert!((sum - 1.0).abs() < 1e-6); - assert!((k[4] - 5.0 / 25.0).abs() < 1e-6 && (k[0] - 1.0 / 25.0).abs() < 1e-6); - // Fractional widths taper the end taps; width 1 is the identity. - let (r, k) = tent_kernel(4.0); - assert_eq!(r, 4); - assert!(k[0] > 0.0 && k[0] < 1.0 / 25.0); - assert_eq!(tent_kernel(1.0), (0, vec![1.0])); - // #1543: a huge, infinite or NaN width is capped, not turned into a kernel of 2^62 taps. - for w in [1e30, f32::INFINITY, f32::MAX] { - assert_eq!(tent_kernel(w), tent_kernel(MAX_REACH), "{w}"); - } - assert_eq!(tent_kernel(f32::NAN), (0, vec![1.0])); - } - - fn no_tex() -> TextureCtx<'static> { - TextureCtx { rect: Rect::new(0, 0, 1, 1), patterns: &[], anchor: (0.0, 0.0) } - } - - fn square(n: usize, x0: usize, x1: usize) -> Map { - let mut m = Map::new(n, n, 0.0); - for y in x0..x1 { - for x in x0..x1 { - m.v[y * n + x] = 1.0; - } - } - m - } - - fn bevel_of(style: BevelStyle, technique: BevelTechnique) -> Bevel { - Bevel { - enabled: true, - style, - technique, - depth: 1.0, - up: true, - size: 5.0, - soften: 0.0, - angle: 90.0, - altitude: 30.0, - use_global_light: false, - gloss_contour: Contour::Linear, - gloss_anti_alias: false, - highlight: photocraft_doc::FxCommon::new(BlendMode::Screen, 0.75), - highlight_color: photocraft_color::Color::WHITE, - shadow: photocraft_doc::FxCommon::new(BlendMode::Multiply, 0.75), - shadow_color: photocraft_color::Color::BLACK, - contour: None, - texture: None, - } - } - - #[test] - fn smooth_inner_bevel_lights_the_top_edge_inside_only() { - let shape = square(40, 10, 30); - let (maps, paint) = bevel_maps( - &shape, - &bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth), - &GlobalLight::default(), - &no_tex(), - &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES), - ); - assert_eq!(paint, BevelPaint::Inner); - let at = |m: &Map, x: usize, y: usize| m.v[y * 40 + x]; - // Light from the top: highlight along the top edge, shadow along the bottom, flat middle. - assert!(at(&maps[0], 20, 10) > 0.5 && at(&maps[1], 20, 10) == 0.0); - assert!(at(&maps[1], 20, 29) > 0.5); - assert!(at(&maps[0], 20, 20) < 1e-3 && at(&maps[1], 20, 20) < 1e-3); - // Nothing outside the shape; the ramp reaches about `size` inside. - assert_eq!(at(&maps[0], 20, 8), 0.0); - assert!(at(&maps[0], 20, 15) < 0.05); - } - - /// Photoshop 27.11, measured across a straight edge (size 10, depth 100 %, light from the top - /// at 30°): a chisel facet has the slope `depth × size / (2 (size + 1))`, flat right up to the - /// edge pixel for Inner Hard; Inner Soft's edge pixel is half as steep again; Outer Hard - /// still shades, partly, the pixel where its ramp reaches zero `size + 1½` px out. - #[test] - fn chisel_facets_match_photoshop() { - let amount = |g: f32| { - let (se, ce) = 30f32.to_radians().sin_cos(); - ((g * ce + se) / (1.0 + g * g).sqrt() - se) / (1.0 - se) - }; - let n = 80; - let shape = square(n, 20, 60); - let maps = |style, technique| { - let mut b = bevel_of(style, technique); - b.size = 10.0; - bevel_maps(&shape, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)).0 - }; - let at = |m: &Map, y: usize| m.v[y * n + 40]; - let facet = amount(10.0 / 22.0); - let hard = maps(BevelStyle::InnerBevel, BevelTechnique::ChiselHard); - for y in 20..30 { - assert!((at(&hard[0], y) - facet).abs() < 0.01, "inner hard facet at row {y}: {} vs {facet}", at(&hard[0], y)); - } - assert!(at(&hard[0], 30) > 0.05 && at(&hard[0], 30) < facet, "one partial pixel at the end"); - let soft = maps(BevelStyle::InnerBevel, BevelTechnique::ChiselSoft); - assert!((at(&soft[0], 20) - amount(1.5 * 10.0 / 22.0)).abs() < 0.01, "steeper edge pixel: {}", at(&soft[0], 20)); - assert!((at(&soft[0], 24) - facet).abs() < 0.01, "then Chisel Hard's facet"); - let outer = maps(BevelStyle::OuterBevel, BevelTechnique::ChiselHard); - // Below the shape (rows 60..): shadow facet through 10½ px, partial at 11½. - assert!((at(&outer[1], 70) - at(&outer[1], 61)).abs() < 1e-4); - assert!(at(&outer[1], 71) > 0.05 && at(&outer[1], 71) < at(&outer[1], 70)); - assert_eq!(at(&outer[1], 72), 0.0); - } - - #[test] - fn emboss_paints_both_sides_and_pillow_flips_the_outside() { - let shape = square(40, 10, 30); - let l = GlobalLight::default(); - let (e, paint) = - bevel_maps(&shape, &bevel_of(BevelStyle::Emboss, BevelTechnique::Smooth), &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); - assert_eq!((paint, e.len()), (BevelPaint::Both, 2)); - let at = |m: &Map, x: usize, y: usize| m.v[y * 40 + x]; - // Emboss: the slope across the top edge faces the light on both sides. - assert!(at(&e[0], 20, 10) > 0.3 && at(&e[0], 20, 9) > 0.3); - let (p, _) = - bevel_maps(&shape, &bevel_of(BevelStyle::PillowEmboss, BevelTechnique::Smooth), &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); - assert!(at(&p[0], 20, 10) > 0.3 && at(&p[1], 20, 9) > 0.3, "pillow: outside top edge in shadow"); - } - - #[test] - fn emboss_width_rounds_up_and_shades_past_the_blur() { - let mut b = bevel_of(BevelStyle::Emboss, BevelTechnique::Smooth); - b.size = 41.0; - let g = bevel_geom(&b); - assert_eq!((g.width, g.depth), (21.0, 21.0)); - b.size = 5.0; - assert_eq!(bevel_geom(&b).width, 3.0); - // The first row past the height blur's reach still slopes (its upper neighbour is raised), - // so it shades; the row after it does not. - let shape = square(60, 20, 40); - b.size = 9.0; - b.angle = 90.0; - let (m, _) = bevel_maps(&shape, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); - let reach = tent_kernel(bevel_geom(&b).width).0 as usize; - let row = 39 + reach + 1; // last shape row + reach + 1: height 0, neighbour above raised - assert!(m[1].v[row * 60 + 30] > 0.0, "{}", m[1].v[row * 60 + 30]); - assert_eq!(m[1].v[(row + 1) * 60 + 30], 0.0); - } - - /// A `len` x `wid` bar through the middle of a `w` x `h` map at `deg` degrees, anti-aliased by - /// 16 x 16 supersampling (the coverage a scanline rasteriser gives). - fn aa_bar(w: usize, h: usize, deg: f32, len: f32, wid: f32) -> Map { - let (sn, cs) = deg.to_radians().sin_cos(); - let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0); - let mut m = Map::new(w, h, 0.0); - const N: usize = 16; - for y in 0..h { - for x in 0..w { - let mut hit = 0; - for sy in 0..N { - for sx in 0..N { - let (px, py) = (x as f32 + (sx as f32 + 0.5) / N as f32 - cx, y as f32 + (sy as f32 + 0.5) / N as f32 - cy); - let (u, v) = (px * cs + py * sn, -px * sn + py * cs); - hit += usize::from(u.abs() <= len / 2.0 && v.abs() <= wid / 2.0); - } - } - m.v[y * w + x] = hit as f32 / (N * N) as f32; - } - } - m - } - - /// Ripple and bias of a distance field on an `aa_bar` (`inside` or outside it): the worst - /// standard deviation of the error among pixels at the same true distance from a long edge - /// (0.5 px bins, 0.6..8 px, away from the ends), and the worst mean error of a bin. A constant - /// offset is no ripple: only a field that varies along the edge shades in stripes. - fn bar_ripple(f: &[f32], w: usize, h: usize, deg: f32, wid: f32, inside: bool) -> (f32, f32) { - let (sn, cs) = deg.to_radians().sin_cos(); - let mut bins: Vec> = vec![Vec::new(); 16]; - for y in 0..h { - for x in 0..w { - let (px, py) = (x as f32 + 0.5 - w as f32 / 2.0, y as f32 + 0.5 - h as f32 / 2.0); - let (u, v) = (px * cs + py * sn, -px * sn + py * cs); - let truth = if inside { wid / 2.0 - v.abs() } else { v.abs() - wid / 2.0 }; - if u.abs() < 40.0 && (0.6..8.0).contains(&truth) { - bins[(truth * 2.0) as usize].push(f[y * w + x] - truth); - } - } - } - let (mut ripple, mut bias) = (0.0f32, 0.0f32); - for b in bins.iter().filter(|b| b.len() > 8) { - let mean = b.iter().sum::() / b.len() as f32; - let sd = (b.iter().map(|e| (e - mean) * (e - mean)).sum::() / b.len() as f32).sqrt(); - ripple = ripple.max(sd); - bias = bias.max(mean.abs()); - } - (ripple, bias) - } - - /// The worst standard deviation of the chisel shading (highlight minus shadow) along lines - /// parallel to an `aa_bar` 2..6 px in from its edges, the way Issue #1926 measured stripes. - fn bar_shade_ripple(deg: f32, light: f32) -> f32 { - let (w, h) = (220usize, 220usize); - let bar = aa_bar(w, h, deg, 150.0, 16.0); - let mut b = bevel_of(BevelStyle::InnerBevel, BevelTechnique::ChiselHard); - (b.size, b.depth, b.angle, b.altitude) = (8.0, 2.2, light, 32.0); - let (m, _) = bevel_maps(&bar, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); - let (sn, cs) = deg.to_radians().sin_cos(); - let mut worst = 0.0f32; - for o in [-6.0f32, -5.0, -4.0, -3.0, -2.0, 2.0, 3.0, 4.0, 5.0, 6.0] { - let line: Vec = (-60..=60) - .map(|k| { - let t = k as f32 * 0.5; - let (x, y) = (w as f32 / 2.0 + t * cs - o * sn, h as f32 / 2.0 + t * sn + o * cs); - let i = y.floor() as usize * w + x.floor() as usize; - m[0].v[i] - m[1].v[i] - }) - .collect(); - let mean = line.iter().sum::() / line.len() as f32; - worst = worst.max((line.iter().map(|v| (v - mean) * (v - mean)).sum::() / line.len() as f32).sqrt()); - } - worst - } - - /// Coverage of a unit pixel by the half plane `n . p + s >= 0` (`p` from the pixel's centre), - /// by 64 x 64 supersampling. - fn half_plane_coverage(n: [f32; 2], s: f32) -> f32 { - const N: usize = 64; - let mut hit = 0; - for y in 0..N { - for x in 0..N { - let (px, py) = ((x as f32 + 0.5) / N as f32 - 0.5, (y as f32 + 0.5) / N as f32 - 0.5); - hit += usize::from(n[0] * px + n[1] * py + s >= 0.0); - } - } - hit as f32 / (N * N) as f32 - } - - #[test] - fn edge_offset_places_a_straight_edge_by_its_coverage() { - for step in 0..=12 { - let (sn, cs) = (step as f32 * 7.5).to_radians().sin_cos(); - for k in -12..=12 { - let s = k as f32 * 0.05; - let a = half_plane_coverage([cs, sn], s); - // Where the edge only just touches the pixel the coverage hardly moves with it. - if !(0.03..=0.97).contains(&a) { - continue; - } - let got = edge_offset([cs, sn], a); - assert!((got - s).abs() < 0.03, "{}deg s {s}: coverage {a} gave {got}", step as f32 * 7.5); - } - } - // Axis-aligned edges keep `alpha - 1/2`; a pixel no coverage says anything about is 0. - assert!((edge_offset([1.0, 0.0], 0.25) + 0.25).abs() < 1e-6); - assert!((edge_offset([0.0, 1.0], 0.9) - 0.4).abs() < 1e-6); - assert_eq!(edge_offset([0.6, 0.8], f32::NAN), 0.0); - } - - #[test] - fn bevel_distances_equal_the_plain_ones_without_anti_aliasing() { - // Hard edges (no partly covered pixel) and soft ramps (no sharp one) keep the plain fields. - let (w, h) = (96usize, 80usize); - let mut maps = Vec::new(); - for kind in 0..4 { - let mut m = Map::new(w, h, 0.0); - let mut seed = 12345u32; - for y in 0..h { - for x in 0..w { - let (dx, dy) = (x as f32 - 48.0, y as f32 - 40.0); - m.v[y * w + x] = match kind { - 0 => f32::from((50.0..90.0).contains(&(x as f32 * 0.6 + y as f32))), - 1 => f32::from(dx * dx + dy * dy < 30.0 * 30.0), - 2 => { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - f32::from(seed >> 28 < 5 && x > 10 && x < 80) - } - _ => ((20.0 - (dx * dx + dy * dy).sqrt()) / 8.0).clamp(0.0, 1.0), - }; - } - } - maps.push(m); - } - for (i, m) in maps.iter().enumerate() { - let sharp = sharp_edges(m); - assert!(sharp.is_empty(), "map {i} has no anti-aliased edge"); - assert_eq!(bevel_dist_inside(m, &sharp, 1e9), dist_inside(m), "inside, map {i}"); - assert_eq!(bevel_dist_outside(m, &sharp, 1e9), dist_outside(m), "outside, map {i}"); - } - } - - #[test] - fn chisel_distance_has_no_ripple_along_oblique_edges() { - // The plain distance to a pixel's centre ripples with the staircase of an oblique edge (the - // stripes of Issue #1926); at 0 and 45 degrees the staircase is regular and it does not. - let (w, h) = (160, 160); - for deg in [0.0f32, 30.0, 45.0, 60.0, 75.0, 120.0, 150.0] { - let bar = aa_bar(w, h, deg, 120.0, 40.0); - let sharp = sharp_edges(&bar); - let inside = bar_ripple(&bevel_dist_inside(&bar, &sharp, 40.0), w, h, deg, 40.0, true); - let outside = bar_ripple(&bevel_dist_outside(&bar, &sharp, 40.0), w, h, deg, 40.0, false); - for (what, (ripple, bias)) in [("inside", inside), ("outside", outside)] { - assert!(ripple < 0.008 && bias < 0.01, "{deg} deg {what}: ripple {ripple}, bias {bias}"); - } - } - let plain = aa_bar(w, h, 60.0, 120.0, 40.0); - let (ripple, _) = bar_ripple(&dist_inside(&plain), w, h, 60.0, 40.0, true); - assert!(ripple > 0.1, "the plain field still ripples ({ripple}), so the test above means something"); - } - - #[test] - fn edge_normals_follow_straight_edges_to_a_fraction_of_a_degree() { - // The 3x3 gradient is 1-3 degrees off and the error is systematic; the line through the edge - // points of the pixels around one is not. - let (w, h, wid) = (160usize, 160usize, 40.0f32); - for deg in [30.0f32, 60.0, 75.0, 120.0, 150.0] { - let sharp = sharp_edges(&aa_bar(w, h, deg, 120.0, wid)); - let (sn, cs) = deg.to_radians().sin_cos(); - let (mut worst, mut seen) = (0.0f32, 0); - for (i, e) in sharp.iter() { - let (px, py) = ((i % w) as f32 + 0.5 - w as f32 / 2.0, (i / w) as f32 + 0.5 - h as f32 / 2.0); - let (u, v) = (px * cs + py * sn, -px * sn + py * cs); - if u.abs() > 40.0 || (wid / 2.0 - v.abs()).abs() > 1.5 { - continue; - } - let into = if v > 0.0 { [sn, -cs] } else { [-sn, cs] }; - worst = worst.max((e.normal[0] * into[0] + e.normal[1] * into[1]).clamp(-1.0, 1.0).acos().to_degrees()); - seen += 1; - } - assert!(seen > 100 && worst < 0.6, "{deg} deg: {seen} edge pixels, normal off by up to {worst} deg"); - } - } - - #[test] - fn chisel_distance_is_close_on_round_shapes() { - // Circles (a hard stretch of edge at each pole, where the edge lies on a pixel boundary) and - // rounded rectangles on whole pixels (straight hard edges joined to anti-aliased arcs): the - // distance to the sharp pixels alone is up to 0.3 px too long there, so the plain distance - // caps it. Errors are against the exact distance to the shape, 0.6..8 px from its edge. - let worst = |f: &[f32], w: usize, h: usize, sdf: &dyn Fn(f32, f32) -> f32, inside: bool| { - let mut mx = 0.0f32; - for y in 0..h { - for x in 0..w { - let t = sdf(x as f32 + 0.5, y as f32 + 0.5); - let truth = if inside { -t } else { t }; - if (0.6..8.0).contains(&truth) { - mx = mx.max((f[y * w + x] - truth).abs()); - } - } - } - mx - }; - for r in [20.0f32, 40.0, 70.0] { - let (w, h) = (200usize, 200usize); - let m = aa_disc(w, h, r); - let sharp = sharp_edges(&m); - let sdf = |x: f32, y: f32| (x - 100.0).hypot(y - 100.0) - r; - let (i, o) = (worst(&bevel_dist_inside(&m, &sharp, 12.0), w, h, &sdf, true), worst(&bevel_dist_outside(&m, &sharp, 12.0), w, h, &sdf, false)); - assert!(i < 0.05 && o < 0.07, "disc {r}: inside off by {i}, outside by {o}"); - } - for rad in [6.0f32, 12.0, 24.0] { - let (w, h) = (200usize, 160usize); - let m = aa_round_rect(w, h, 20.0, 20.0, 180.0, 140.0, rad); - let sharp = sharp_edges(&m); - let sdf = |x: f32, y: f32| { - let (qx, qy) = ((x - 100.0).abs() - (80.0 - rad), (y - 80.0).abs() - (60.0 - rad)); - qx.max(0.0).hypot(qy.max(0.0)) + qx.max(qy).min(0.0) - rad - }; - let (i, o) = (worst(&bevel_dist_inside(&m, &sharp, 12.0), w, h, &sdf, true), worst(&bevel_dist_outside(&m, &sharp, 12.0), w, h, &sdf, false)); - assert!(i < 0.08 && o < 0.2, "rounded rect, radius {rad}: inside off by {i}, outside by {o}"); - } - } - - #[test] - fn chisel_facets_are_flat_along_oblique_edges() { - // Issue #1926: the facets of a chiselled bar at 30, 60, 120, 150 degrees were striped. - for deg in [0.0f32, 30.0, 45.0, 60.0, 75.0, 120.0, 150.0] { - for light in [-90.0f32, 0.0, 45.0, 120.0] { - let ripple = bar_shade_ripple(deg, light); - assert!(ripple < 0.03, "{deg} deg bar, light {light}: shading ripple {ripple}"); - } - } - } - - #[test] - fn bevel_distances_survive_degenerate_maps() { - let cases: [(usize, usize, f32); 7] = [(0, 0, 0.0), (1, 1, 0.5), (1, 1, 1.0), (2, 2, 0.5), (3, 1, 0.3), (5, 5, f32::NAN), (4, 4, 1.0)]; - for (w, h, a) in cases { - let m = Map::new(w, h, a); - let sharp = sharp_edges(&m); - for reach in [0.0, 8.0, f32::NAN, f32::INFINITY, -3.0] { - assert_eq!(bevel_dist_inside(&m, &sharp, reach).len(), w * h); - assert_eq!(bevel_dist_outside(&m, &sharp, reach).len(), w * h); - } - } - // A single partly covered pixel in an empty map, and an edge on the map's border. - let mut m = Map::new(5, 5, 0.0); - m.v[12] = 0.4; - let _ = (bevel_dist_inside(&m, &sharp_edges(&m), 4.0), bevel_dist_outside(&m, &sharp_edges(&m), 4.0)); - let mut m = Map::new(8, 8, 0.0); - for y in 0..8 { - m.v[y * 8 + 7] = 1.0; - m.v[y * 8 + 6] = 0.5; - } - let _ = (bevel_dist_inside(&m, &sharp_edges(&m), 4.0), bevel_dist_outside(&m, &sharp_edges(&m), 4.0)); - } - - #[test] - fn par_units_visits_every_unit_once_with_its_own_slices() { - // Lengths that leave a short last unit, no second slice, units of different sizes, and nothing at all. - let cases: [(usize, usize, usize, usize); 8] = - [(0, 3, 0, 0), (1, 1, 1, 1), (10, 3, 0, 0), (64, 8, 64, 8), (65, 8, 13, 1), (200, 1, 200, 1), (7, 7, 14, 2), (9, 4, 0, 5)]; - for (la, ua, lb, ub) in cases { - for threads in [1, 2, 3, 8, 64] { - let (mut a, mut b) = (vec![0u32; la], vec![0u32; lb]); - let calls = std::sync::atomic::AtomicUsize::new(0); - with_threads(threads, || { - par_units( - la, - &mut a, - ua, - &mut b, - ub, - || (), - |_, u, sa, sb| { - calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - assert!(sa.len() <= ua && sb.len() <= ub); - for (k, v) in sa.iter_mut().enumerate() { - *v = (u * ua + k) as u32 + 1; - } - for (k, v) in sb.iter_mut().enumerate() { - *v = (u * ub + k) as u32 + 1; - } - }, - ); - }); - assert_eq!(calls.into_inner(), la.div_ceil(ua), "{la} {ua} {lb} {ub} on {threads}"); - assert!(a.iter().enumerate().all(|(i, &v)| v == i as u32 + 1), "a: {la} {ua} {lb} {ub} on {threads}"); - // `b` is written for the units that exist in `a` and no further. - let written = (la.div_ceil(ua) * ub).min(lb); - assert!(b.iter().enumerate().all(|(i, &v)| v == if i < written { i as u32 + 1 } else { 0 }), "b: {la} {ua} {lb} {ub} on {threads}"); - } - } - // A unit size of 0 does nothing. - let mut a = vec![1u8; 4]; - par_units(4, &mut a, 0, &mut [] as &mut [()], 0, || (), |_, _, _, _| panic!("no units")); - } - - #[test] - fn nearest_distances_do_not_depend_on_the_threads() { - // Sizes that do not divide into the thread groups, lines of 1 pixel, and a noisy map where - // many pixels are equally far from two seeds (the nearest one must resolve the same way). - for (w, h) in [(37usize, 23usize), (1, 40), (40, 1), (2, 2), (101, 3), (64, 64)] { - let mut seed = 7u32; - let inside: Vec = (0..w * h) - .map(|_| { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - (seed >> 24).is_multiple_of(11) - }) - .collect(); - let (d1, n1) = with_threads(1, || edt_nearest(&inside, w, h)); - for threads in [2, 3, 8] { - let (d, n) = with_threads(threads, || edt_nearest(&inside, w, h)); - assert_eq!((bits(&d), n), (bits(&d1), n1.clone()), "{w}x{h} on {threads} threads"); - } - // And the nearest pixel is a seed at exactly that distance. - for (i, (&d, &q)) in d1.iter().zip(&n1).enumerate() { - if inside.iter().any(|&b| b) { - let (dx, dy) = ((i % w) as f32 - (q as usize % w) as f32, (i / w) as f32 - (q as usize / w) as f32); - assert!(inside[q as usize] && (dx.hypot(dy) - d).abs() < 1e-3, "{w}x{h} at {i}: {d} vs seed {q}"); - } - } - } - } - - #[test] - fn nearest_distances_survive_degenerate_sizes() { - // The slice does not match the size, or there is nothing: no panic, and a result per input pixel. - for (len, w, h) in [(0usize, 0usize, 0usize), (0, 5, 0), (0, 0, 5), (6, 2, 2), (6, 4, 2), (1, 0, 1)] { - let (d, n) = edt_nearest(&vec![true; len], w, h); - assert_eq!((d.len(), n.len()), (len, len), "{len} px as {w}x{h}"); - } - } - - #[test] - fn chisel_fields_do_not_depend_on_the_threads() { - // Edge pixels at every angle, curves, patchy opacity and an edge along the border, on sizes that - // leave short last groups; one thread (in order) is the reference. - let mut maps = vec![ - aa_disc(97, 83, 30.0), - aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0), - aa_bar(120, 120, 33.0, 100.0, 30.0), - aa_bar(90, 130, 60.0, 150.0, 25.0), - ]; - let mut patchy = aa_disc(101, 101, 40.0); - for (i, v) in patchy.v.iter_mut().enumerate() { - if (i % 101 / 13 + i / 101 / 17) % 5 == 0 { - *v *= 0.6; - } - } - maps.push(patchy); - maps.push(aa_bar(64, 64, 40.0, 220.0, 30.0)); - for (k, m) in maps.iter().enumerate() { - for reach in [3.0f32, 12.0] { - let one = with_threads(1, || (sharp_edges(m), distance_field_of(m, reach))); - for threads in [2, 5, 16] { - let many = with_threads(threads, || (sharp_edges(m), distance_field_of(m, reach))); - assert_eq!(one.0.slot, many.0.slot, "map {k} sharp slots on {threads} threads"); - let edges = |s: &SharpEdges| { - s.pixels.iter().map(|p| (p.at, p.cov.to_bits(), p.edge.offset.to_bits(), p.edge.normal.map(f32::to_bits))).collect::>() - }; - assert_eq!(edges(&one.0), edges(&many.0), "map {k} sharp edges on {threads} threads"); - for (a, b) in one.1.iter().zip(&many.1) { - assert_eq!(bits(a), bits(b), "map {k}, reach {reach} on {threads} threads"); - } - } - } - } - } - - #[test] - fn bevel_maps_do_not_depend_on_the_threads() { - // Every style and technique, softened or not, and a texture; one thread (in order) is the reference. - let mut patchy = aa_disc(101, 101, 40.0); - for (i, v) in patchy.v.iter_mut().enumerate() { - if (i % 101 / 13 + i / 101 / 17) % 5 == 0 { - *v *= 0.6; - } - } - let shapes = [aa_disc(97, 83, 30.0), aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0), aa_bar(90, 130, 60.0, 150.0, 25.0), patchy]; - let mut sf = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); - sf.fill_rect(Rect::new(0, 0, 4, 2), &[0.0, 0.0, 0.0, 1.0]); - sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]); - let pats = [Pattern::new("stripes", sf, 4, 4)]; - let light = GlobalLight::default(); - let styles = [BevelStyle::InnerBevel, BevelStyle::OuterBevel, BevelStyle::Emboss, BevelStyle::PillowEmboss, BevelStyle::StrokeEmboss]; - for (k, shape) in shapes.iter().enumerate() { - let tex = TextureCtx { rect: Rect::new(3, 5, 3 + shape.w as i32, 5 + shape.h as i32), patterns: &pats, anchor: (0.0, 0.0) }; - for style in styles { - for technique in [BevelTechnique::Smooth, BevelTechnique::ChiselHard, BevelTechnique::ChiselSoft] { - for (size, soften, textured) in [(5.0, 0.0, false), (12.0, 2.0, false), (8.0, 0.0, true)] { - let mut b = bevel_of(style, technique); - (b.size, b.soften) = (size, soften); - if textured { - b.texture = Some(photocraft_doc::BevelTexture { - name: "stripes".into(), - id: String::new(), - scale: 1.0, - depth: 1.0, - invert: false, - link: true, - phase: (0.0, 0.0), - }); - } - let run = || bevel_maps(shape, &b, &light, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)).0; - let one = with_threads(1, run); - for threads in [2, 5, 16] { - let many = with_threads(threads, run); - assert_eq!(one.len(), many.len()); - for (j, (a, m)) in one.iter().zip(&many).enumerate() { - assert_eq!(bits(&a.v), bits(&m.v), "shape {k}, {style:?} {technique:?} size {size} map {j} on {threads} threads"); - } - } - } - } - } - } - } - - /// The four fields that use the distance transform, of `m`. - fn distance_field_of(m: &Map, reach: f32) -> Vec> { - [FieldKind::Inside, FieldKind::Outside, FieldKind::BevelInside, FieldKind::BevelOutside] - .map(|k| distance_field(k, m.v.clone(), m.w, m.h, reach)) - .to_vec() - } - - fn aa_disc(w: usize, h: usize, r: f32) -> Map { - let mut m = Map::new(w, h, 0.0); - const N: usize = 16; - for y in 0..h { - for x in 0..w { - let mut hit = 0; - for sy in 0..N { - for sx in 0..N { - let (px, py) = (x as f32 + (sx as f32 + 0.5) / N as f32 - w as f32 / 2.0, y as f32 + (sy as f32 + 0.5) / N as f32 - h as f32 / 2.0); - hit += usize::from(px * px + py * py <= r * r); - } - } - m.v[y * w + x] = hit as f32 / (N * N) as f32; - } - } - m - } - - /// Integer-aligned rounded rectangle (x0..x1 x y0..y1, corner radius `rad`), anti-aliased by supersampling. - fn aa_round_rect(w: usize, h: usize, x0: f32, y0: f32, x1: f32, y1: f32, rad: f32) -> Map { - let sdf = |px: f32, py: f32| { - let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); - let (qx, qy) = ((px - cx).abs() - ((x1 - x0) / 2.0 - rad), (py - cy).abs() - ((y1 - y0) / 2.0 - rad)); - qx.max(0.0).hypot(qy.max(0.0)) + qx.max(qy).min(0.0) - rad - }; - let mut m = Map::new(w, h, 0.0); - const N: usize = 16; - for y in 0..h { - for x in 0..w { - let mut hit = 0; - for sy in 0..N { - for sx in 0..N { - hit += usize::from(sdf(x as f32 + (sx as f32 + 0.5) / N as f32, y as f32 + (sy as f32 + 0.5) / N as f32) <= 0.0); - } - } - m.v[y * w + x] = hit as f32 / (N * N) as f32; - } - } - m - } - - #[test] - fn chisel_hard_has_flat_facets() { - let shape = square(48, 10, 38); - let (m, _) = bevel_maps( - &shape, - &bevel_of(BevelStyle::InnerBevel, BevelTechnique::ChiselHard), - &GlobalLight::default(), - &no_tex(), - &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES), - ); - let at = |x: usize, y: usize| m[0].v[y * 48 + x]; - // A constant slope: equal highlight along the top facet. - assert!(at(24, 12) > 0.1 && (at(24, 12) - at(24, 13)).abs() < 1e-3); - } - - #[test] - fn linear_bevel_contour_leaves_the_height_alone_at_any_range() { - for range in [0.5, 0.7, 1.0] { - let lut = bevel_contour_lut(&photocraft_doc::BevelContour { contour: Contour::Linear, range, anti_alias: false }); - for v in [0.0f32, 0.25, 0.5, 0.75, 1.0] { - assert!((lut_at(&lut, v) - v).abs() < 1e-3, "range {range}: {v} -> {}", lut_at(&lut, v)); - } - } - } - - #[test] - fn bevel_contour_and_texture_shape_the_height() { - let shape = square(40, 6, 34); - let l = GlobalLight::default(); - let plain = bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth); - let (a, _) = bevel_maps(&shape, &plain, &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); - // A contour reshapes the profile (here a ramp folded at its middle). - let mut c = plain.clone(); - let fold = vec![ - photocraft_doc::adjust::CurvePoint { input: 0.0, output: 0.0 }, - photocraft_doc::adjust::CurvePoint { input: 0.5, output: 1.0 }, - photocraft_doc::adjust::CurvePoint { input: 1.0, output: 0.0 }, - ]; - c.contour = Some(photocraft_doc::BevelContour { - contour: Contour::Custom { name: "fold".into(), points: fold, corners: vec![] }, - range: 1.0, - anti_alias: false, - }); - let (b, _) = bevel_maps(&shape, &c, &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); - let diff: f32 = a[1].v.iter().zip(&b[1].v).map(|(x, y)| (x - y).abs()).sum(); - assert!(diff > 5.0, "{diff}"); - // A striped texture lights the flat middle. - let mut sf = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); - sf.fill_rect(Rect::new(0, 0, 4, 2), &[0.0, 0.0, 0.0, 1.0]); - sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]); - let pats = [Pattern::new("stripes", sf, 4, 4)]; - let mut t = plain.clone(); - t.texture = Some(photocraft_doc::BevelTexture { - name: "stripes".into(), - id: String::new(), - scale: 1.0, - depth: 1.0, - invert: false, - link: true, - phase: (0.0, 0.0), - }); - let tex = TextureCtx { rect: Rect::new(0, 0, 40, 40), patterns: &pats, anchor: (0.0, 0.0) }; - let (m, _) = bevel_maps(&shape, &t, &l, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)); - let mid: f32 = (16..24).map(|y| m[0].v[y * 40 + 20] + m[1].v[y * 40 + 20]).sum(); - let flat: f32 = (16..24).map(|y| a[0].v[y * 40 + 20] + a[1].v[y * 40 + 20]).sum(); - assert!(mid > flat + 0.5, "{mid} vs {flat}"); - } - - #[test] - fn glow_range_stretches_the_contour() { - let mut g = Glow { - common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0), - paint: FxPaint::Color(photocraft_color::Color::WHITE), - technique: GlowTechnique::Softer, - spread: 0.0, - size: 10.0, - contour: Contour::Linear, - anti_alias: false, - range: 0.5, - jitter: 0.0, - noise: 0.0, - source: GlowSource::Edge, - }; - let l = glow_lut(&g).unwrap(); - assert!((lut_at(&l, 0.25) - 0.5).abs() < 1e-3 && (lut_at(&l, 0.75) - 1.0).abs() < 1e-6); - g.range = 1.0; - assert!(glow_lut(&g).is_none()); - } - - /// Photoshop 27.11, measured on a 128 px square (Normal, black, 100 %, Range 50 %): a precise - /// glow's coverage across the edge, and a centre-source inner glow as 1 − the edge glow. - #[test] - fn glows_match_photoshop() { - let glow = |technique, size: f32, spread: f32, source| Glow { - common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), - paint: FxPaint::Color(photocraft_color::Color::BLACK), - technique, - spread, - size, - contour: Contour::Linear, - anti_alias: false, - range: 0.5, - jitter: 0.0, - noise: 0.0, - source, - }; - let n = 60; - let mut shape = Map::new(n, n, 0.0); - for y in 20..40 { - for x in 20..40 { - shape.v[y * n + x] = 1.0; - } - } - let at = |m: &Map, x: usize| m.v[30 * n + x]; - // Outer, precise, size 10: Photoshop's black glow over white reads 47, 93, 140, 186, 232 - // at 2, 4, 6, 8 and 10 px out from the edge pixel (alpha 1 − D / 11). - let m = glow_map(&shape, &glow(GlowTechnique::Precise, 10.0, 0.0, GlowSource::Edge), false, (0, 0)); - for (d, ps) in [(2, 47.0f32), (4, 93.0), (6, 140.0), (8, 186.0), (10, 232.0)] { - let got = 255.0 * (1.0 - at(&m, 20 - d)); - assert!((got - ps).abs() <= 1.5, "outer precise at {d} px: {got} vs Photoshop {ps}"); - } - // Spread 40 %: solid for the first 4 px. - let m = glow_map(&shape, &glow(GlowTechnique::Precise, 10.0, 0.4, GlowSource::Edge), false, (0, 0)); - assert!((at(&m, 16) - 1.0).abs() < 1e-6 && at(&m, 14) < 1.0); - // Centre source = 1 − edge, for both techniques. - for t in [GlowTechnique::Precise, GlowTechnique::Softer] { - let e = glow_map(&shape, &glow(t, 6.0, 0.0, GlowSource::Edge), true, (0, 0)); - let c = glow_map(&shape, &glow(t, 6.0, 0.0, GlowSource::Center), true, (0, 0)); - for x in 20..40 { - assert!((at(&c, x) - (1.0 - at(&e, x))).abs() < 1e-5, "{t:?} at {x}"); - } - } - } - - #[test] - fn offsets_follow_light() { - let (dx, dy) = offset(120.0, 10.0); - assert_eq!((dx, dy), (5.0, 9.0)); - } - - fn square_shape(n: usize) -> Map { - let mut m = Map::new(n, n, 0.0); - for y in 5..n - 5 { - for x in 5..n - 5 { - m.v[y * n + x] = 1.0; - } - } - m - } - - #[test] - fn satin_at_distance_zero_matches_photoshop() { - // Photoshop 27.11, Satin black 100 %, angle 90°, Linear contour, distance 0, size 5 over a - // #808080 square: the rows from the top edge read 82, 102, 123, 128. - let s = photocraft_doc::effects::Satin { - common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), - color: photocraft_color::Color::BLACK, - angle: 90.0, - distance: 0.0, - size: 5.0, - contour: Contour::Linear, - anti_alias: false, - invert: false, - }; - let m = satin_map(&square_shape(60), &s); - for (row, gray) in [(5, 82.0), (7, 102.0), (9, 123.0), (11, 128.0), (30, 128.0)] { - let want = 1.0 - gray / 128.0; - let got = m.v[row * 60 + 30]; - assert!((got - want).abs() < 0.02, "row {row}: {got} vs {want}"); - } - } - - fn shadow(noise: f32, origin: (i32, i32)) -> Map { - let s = Shadow { - common: photocraft_doc::FxCommon::new(BlendMode::Multiply, 1.0), - color: photocraft_color::Color::BLACK, - angle: 0.0, - use_global_light: false, - distance: 0.0, - spread: 0.0, - size: 6.0, - contour: Contour::Linear, - anti_alias: false, - noise, - knocks_out: true, - }; - shadow_map(&square_shape(40), &s, &GlobalLight::default(), false, origin) - } - - #[test] - fn shadow_noise_speckles_soft_coverage_deterministically() { - let plain = shadow(0.0, (0, 0)); - let noisy = shadow(0.5, (0, 0)); - let again = shadow(0.5, (0, 0)); - let (mut diff, mut identical) = (0.0f32, true); - for i in 0..plain.v.len() { - diff += (plain.v[i] - noisy.v[i]).abs(); - if noisy.v[i] != again.v[i] { - identical = false; - } - } - assert!(diff > 5.0, "noise changes the soft band: {diff}"); - assert!(identical, "same coords, same speckle"); - // Every value stays a coverage. - assert!(noisy.v.iter().all(|v| (0.0..=1.0).contains(v))); - // The speckle moves with the document origin, not the tile. - let moved = shadow(0.5, (100, 100)); - assert_ne!(noisy.v, moved.v, "hashed from document coordinates"); - // Full noise can punch holes even in the solid part. - let heavy = shadow(1.0, (0, 0)); - assert!(heavy.v.iter().any(|v| *v < 0.5) && heavy.v.iter().any(|v| *v > 0.5), "heavy noise spans the range",); - } - - #[test] - fn box_blur_preserves_faint_coverage_and_empty_gaps() { - let src = [0.0, 0.3, 0.7, 0.0, 0.0, 0.0, 0.0, 1e-20, 0.0, 0.0, 0.0]; - let mut actual = [0.0; 11]; - box_line(&src, 0, &mut actual, 3.0); - assert_eq!(actual[5], 0.0, "an empty window must be exactly empty"); - assert_eq!(actual[10], 0.0, "the second tail must also be empty"); - assert!((actual[7] - 1e-20 / 3.0).abs() < 1e-30, "real faint coverage is not rounded away"); - } - - #[test] - fn effect_noise_does_not_light_up_empty_blur_tails() { - // A sloping antialiased shape leaves rounding residue in a running-sum blur. - // The direct finite-support convolution is the oracle for untouched pixels. - for size in [5.0, 5.5, 13.0] { - let mut shape = Map::new(96, 64, 0.0); - for y in 8..48 { - for x in 8..48 { - shape.v[y * shape.w + x] = ((x as f32 - y as f32 * 0.7) * 0.3).clamp(0.0, 1.0); - } - } - let mut direct = shape.clone(); - tent_direct(&mut direct, size); - let mut actual = shape; - blur(&mut actual, size); - noise(&mut actual, 0.26, 0, 0); - let stray = direct.v.iter().zip(&actual.v).filter(|(reference, noisy)| **reference == 0.0 && **noisy > 1e-5).count(); - assert_eq!(stray, 0, "noise created {stray} visible pixels outside a size-{size} blur"); - } - } - - #[test] - fn glow_noise_follows_the_contour_and_range() { - let g = |noise: f32| Glow { - common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0), - paint: FxPaint::Color(photocraft_color::Color::WHITE), - technique: GlowTechnique::Softer, - spread: 0.0, - size: 6.0, - contour: Contour::Linear, - anti_alias: false, - range: 0.5, - jitter: 0.0, - noise, - source: GlowSource::Edge, - }; - let plain = glow_map(&square_shape(40), &g(0.0), false, (0, 0)); - let noisy = glow_map(&square_shape(40), &g(0.6), false, (0, 0)); - let diff: f32 = plain.v.iter().zip(&noisy.v).map(|(a, b)| (a - b).abs()).sum(); - assert!(diff > 5.0, "glow noise changes the coverage: {diff}"); - } - - /// Issue #7833: the speckle stays inside the glow's visible falloff instead of filling the - /// blur's whole rectangular reach out to the map edge. - #[test] - fn effect_noise_stays_inside_the_visible_falloff() { - let mut shape = Map::new(80, 80, 0.0); - for y in 35..45 { - for x in 35..45 { - shape.v[y * 80 + x] = 1.0; - } - } - let g = |noise: f32| Glow { - common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0), - paint: FxPaint::Color(photocraft_color::Color::WHITE), - technique: GlowTechnique::Softer, - spread: 0.0, - size: 10.0, - contour: Contour::Linear, - anti_alias: false, - range: 0.5, - jitter: 0.0, - noise, - source: GlowSource::Edge, - }; - let s = |noise: f32| Shadow { - common: photocraft_doc::FxCommon::new(BlendMode::Multiply, 1.0), - color: photocraft_color::Color::BLACK, - angle: 0.0, - use_global_light: false, - distance: 0.0, - spread: 0.0, - size: 10.0, - contour: Contour::Linear, - anti_alias: false, - noise, - knocks_out: true, - }; - let light = GlobalLight::default(); - let pairs = [ - ("glow", glow_map(&shape, &g(0.0), false, (0, 0)), glow_map(&shape, &g(0.5), false, (0, 0))), - ("shadow", shadow_map(&shape, &s(0.0), &light, false, (0, 0)), shadow_map(&shape, &s(0.5), &light, false, (0, 0))), - ]; - for (name, plain, noisy) in pairs { - for (i, (p, n)) in plain.v.iter().zip(&noisy.v).enumerate() { - if *p < 1.0 / 255.0 { - assert!(*n <= 2.0 / 255.0, "{name}: pixel ({}, {}) invisible without noise: {p} -> {n}", i % 80, i / 80); - } - } - } - } - - #[test] - fn shifting_by_hostile_distances_does_not_overflow() { - let m = square_shape(12); - for d in [1.0e30, -1.0e30, f32::INFINITY, f32::NAN] { - let s = m.shifted(d, d, 0.0); - assert_eq!(s.v.len(), 144); - } - } -} +mod tests; diff --git a/crates/compose/src/effects/tests.rs b/crates/compose/src/effects/tests.rs new file mode 100644 index 0000000000..c811b89e13 --- /dev/null +++ b/crates/compose/src/effects/tests.rs @@ -0,0 +1,1061 @@ +use super::*; + +/// Runs `f` with every parallel pass on this thread using `n` threads (1 = in order), whatever its size. +fn with_threads(n: usize, f: impl FnOnce() -> R) -> R { + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + THREADS.with(|t| t.set(self.0)); + } + } + let _restore = Restore(THREADS.with(|t| t.replace(Some(n)))); + f() +} + +fn bits(v: &[f32]) -> Vec { + v.iter().map(|x| x.to_bits()).collect() +} + +#[test] +fn edt_is_exact() { + let (w, h) = (7, 5); + let mut inside = vec![false; w * h]; + inside[2 * w + 3] = true; + let d = edt(&inside, w, h); + assert_eq!(d[2 * w + 3], 0.0); + assert!((d[2 * w + 6] - 3.0).abs() < 1e-6); + assert!((d[0] - (9.0f32 + 4.0).sqrt()).abs() < 1e-5); + assert!((d[4 * w + 5] - (4.0f32 + 4.0).sqrt()).abs() < 1e-5); +} + +#[test] +fn edt_two_seeds() { + let (w, h) = (10, 1); + let mut inside = vec![false; w]; + inside[0] = true; + inside[9] = true; + let d = edt(&inside, w, h); + assert_eq!(d, vec![0.0, 1.0, 2.0, 3.0, 4.0, 4.0, 3.0, 2.0, 1.0, 0.0]); +} + +#[test] +fn blur_preserves_mass() { + let mut m = Map::new(21, 21, 0.0); + m.v[10 * 21 + 10] = 1.0; + blur(&mut m, 6.0); + let sum: f32 = m.v.iter().sum(); + assert!((sum - 1.0).abs() < 1e-4, "{sum}"); + assert!(m.v[10 * 21 + 10] < 1.0); +} + +#[test] +fn gradient_geometry() { + let b = Rect::new(0, 0, 100, 100); + let t = |s, x, y| gradient_t(s, 0.0, 1.0, false, (0.0, 0.0), b, x, y); + assert!(t(GradientStyle::Linear, 0.0, 50.0) < 0.01); + // Linear / reflected sample pixel corners: the centre is reached half a pixel later. + assert!((t(GradientStyle::Linear, 50.5, 50.0) - 0.5).abs() < 1e-6); + assert!(t(GradientStyle::Linear, 100.0, 50.0) > 0.99); + assert!(t(GradientStyle::Reflected, 50.5, 50.0) < 1e-6); + assert!((t(GradientStyle::Reflected, 0.0, 50.0) - 1.0).abs() < 1e-6); + assert!(t(GradientStyle::Radial, 50.0, 50.0) < 1e-6); + assert!((t(GradientStyle::Radial, 50.0, 0.0) - 1.0).abs() < 1e-6); + assert!((t(GradientStyle::Diamond, 75.0, 75.0) - 1.0).abs() < 1e-6); + let ang = t(GradientStyle::Angle, 50.0, 0.0); + assert!((ang - 0.75).abs() < 1e-3, "{ang}"); + let rev = gradient_t(GradientStyle::Linear, 0.0, 1.0, true, (0.0, 0.0), b, 0.0, 50.0); + assert!(rev > 0.99); +} + +#[test] +fn effect_gradients_snap_end_points_and_sample_corners() { + // 87° over 600 × 60 at (99, 422): end points (397, 482) and (400, 422), so the overlay runs + // along (3, -60) from its midpoint (398.5, 452), sampled at pixel corners. + let frame = Rect::new(99, 422, 699, 482); + let (a, sc, o) = crate::fill_layout::gradient_layout(GradientStyle::Linear, 87.0, 1.0, (0.0, 0.0), frame); + assert!((a - (60f32).atan2(3.0).to_degrees()).abs() < 1e-3, "{a}"); + let t = |x: f32, y: f32| gradient_t(GradientStyle::Linear, a, sc, false, o, frame, x, y); + assert!((t(399.0, 452.5) - 0.5).abs() < 1e-4, "{}", t(399.0, 452.5)); + assert!(t(400.5, 422.5) > 0.99 && t(397.5, 482.5) < 0.01); +} + +#[test] +fn chamfer_uses_euclidean_step_lengths() { + let (w, h) = (9, 9); + let mut inside = vec![false; w * h]; + inside[0] = true; + let (d, near) = chamfer_nearest(&inside, w, h); + let at = |x: usize, y: usize| d[y * w + x]; + assert!((at(3, 0) - 3.0).abs() < 1e-5); + assert!((at(2, 2) - 2.0 * std::f32::consts::SQRT_2).abs() < 1e-5); + assert!((at(1, 2) - 5f32.sqrt()).abs() < 1e-5); + assert!((at(1, 3) - (5f32.sqrt() + 1.0)).abs() < 1e-5, "knight + straight, not √10"); + assert!((at(2, 3) - (5f32.sqrt() + std::f32::consts::SQRT_2)).abs() < 1e-5); + assert!(near.iter().all(|&n| n == 0)); +} + +#[test] +fn spread_dilates_with_the_chamfer_metric() { + // One opaque pixel grown by 3 px: at offset (1, 3) the chamfer distance is √5 + 1 = 3.236 + // (Euclidean 3.162), so the anti-aliased rim keeps 3 + 0.5 − (3.236 − 0.5) = 0.764. + let mut m = Map::new(9, 9, 0.0); + m.v[4 * 9 + 4] = 1.0; + let d = dilate(&m, 3.0); + assert!((d.v[7 * 9 + 5] - 0.764).abs() < 1e-3, "{}", d.v[7 * 9 + 5]); + // (2, 3): √5 + √2 = 3.650 (Euclidean 3.606) leaves 0.350; axis steps are exact. + assert!((d.v[7 * 9 + 6] - (4.0 - 5f32.sqrt() - std::f32::consts::SQRT_2)).abs() < 1e-4, "{}", d.v[7 * 9 + 6]); + assert_eq!(d.v[4 * 9 + 7], 1.0); +} + +#[test] +fn running_sum_tent_matches_the_kernel() { + let (w, h) = (37usize, 23usize); + let src: Vec = (0..w * h).map(|i| ((i * 7919) % 101) as f32 / 100.0).collect(); + for width in [1.0f32, 2.0, 3.5, 5.0, 8.25, 41.0] { + let mut m = Map { w, h, v: src.clone() }; + tent(&mut m, width); + let mut want = Map { w, h, v: src.clone() }; + tent_direct(&mut want, width); + for (a, b) in m.v.iter().zip(&want.v) { + assert!((a - b).abs() < 1e-5, "width {width}: {a} vs {b}"); + } + } +} + +#[test] +fn tent_kernel_is_two_boxes() { + let (r, k) = tent_kernel(5.0); + assert_eq!(r, 4); + let sum: f32 = k.iter().sum(); + assert!((sum - 1.0).abs() < 1e-6); + assert!((k[4] - 5.0 / 25.0).abs() < 1e-6 && (k[0] - 1.0 / 25.0).abs() < 1e-6); + // Fractional widths taper the end taps; width 1 is the identity. + let (r, k) = tent_kernel(4.0); + assert_eq!(r, 4); + assert!(k[0] > 0.0 && k[0] < 1.0 / 25.0); + assert_eq!(tent_kernel(1.0), (0, vec![1.0])); + // #1543: a huge, infinite or NaN width is capped, not turned into a kernel of 2^62 taps. + for w in [1e30, f32::INFINITY, f32::MAX] { + assert_eq!(tent_kernel(w), tent_kernel(MAX_REACH), "{w}"); + } + assert_eq!(tent_kernel(f32::NAN), (0, vec![1.0])); +} + +fn no_tex() -> TextureCtx<'static> { + TextureCtx { rect: Rect::new(0, 0, 1, 1), patterns: &[], anchor: (0.0, 0.0) } +} + +fn square(n: usize, x0: usize, x1: usize) -> Map { + let mut m = Map::new(n, n, 0.0); + for y in x0..x1 { + for x in x0..x1 { + m.v[y * n + x] = 1.0; + } + } + m +} + +fn bevel_of(style: BevelStyle, technique: BevelTechnique) -> Bevel { + Bevel { + enabled: true, + style, + technique, + depth: 1.0, + up: true, + size: 5.0, + soften: 0.0, + angle: 90.0, + altitude: 30.0, + use_global_light: false, + gloss_contour: Contour::Linear, + gloss_anti_alias: false, + highlight: photocraft_doc::FxCommon::new(BlendMode::Screen, 0.75), + highlight_color: photocraft_color::Color::WHITE, + shadow: photocraft_doc::FxCommon::new(BlendMode::Multiply, 0.75), + shadow_color: photocraft_color::Color::BLACK, + contour: None, + texture: None, + } +} + +#[test] +fn smooth_inner_bevel_lights_the_top_edge_inside_only() { + let shape = square(40, 10, 30); + let (maps, paint) = bevel_maps( + &shape, + &bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth), + &GlobalLight::default(), + &no_tex(), + &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES), + ); + assert_eq!(paint, BevelPaint::Inner); + let at = |m: &Map, x: usize, y: usize| m.v[y * 40 + x]; + // Light from the top: highlight along the top edge, shadow along the bottom, flat middle. + assert!(at(&maps[0], 20, 10) > 0.5 && at(&maps[1], 20, 10) == 0.0); + assert!(at(&maps[1], 20, 29) > 0.5); + assert!(at(&maps[0], 20, 20) < 1e-3 && at(&maps[1], 20, 20) < 1e-3); + // Nothing outside the shape; the ramp reaches about `size` inside. + assert_eq!(at(&maps[0], 20, 8), 0.0); + assert!(at(&maps[0], 20, 15) < 0.05); +} + +/// Photoshop 27.11, measured across a straight edge (size 10, depth 100 %, light from the top +/// at 30°): a chisel facet has the slope `depth × size / (2 (size + 1))`, flat right up to the +/// edge pixel for Inner Hard; Inner Soft's edge pixel is half as steep again; Outer Hard +/// still shades, partly, the pixel where its ramp reaches zero `size + 1½` px out. +#[test] +fn chisel_facets_match_photoshop() { + let amount = |g: f32| { + let (se, ce) = 30f32.to_radians().sin_cos(); + ((g * ce + se) / (1.0 + g * g).sqrt() - se) / (1.0 - se) + }; + let n = 80; + let shape = square(n, 20, 60); + let maps = |style, technique| { + let mut b = bevel_of(style, technique); + b.size = 10.0; + bevel_maps(&shape, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)).0 + }; + let at = |m: &Map, y: usize| m.v[y * n + 40]; + let facet = amount(10.0 / 22.0); + let hard = maps(BevelStyle::InnerBevel, BevelTechnique::ChiselHard); + for y in 20..30 { + assert!((at(&hard[0], y) - facet).abs() < 0.01, "inner hard facet at row {y}: {} vs {facet}", at(&hard[0], y)); + } + assert!(at(&hard[0], 30) > 0.05 && at(&hard[0], 30) < facet, "one partial pixel at the end"); + let soft = maps(BevelStyle::InnerBevel, BevelTechnique::ChiselSoft); + assert!((at(&soft[0], 20) - amount(1.5 * 10.0 / 22.0)).abs() < 0.01, "steeper edge pixel: {}", at(&soft[0], 20)); + assert!((at(&soft[0], 24) - facet).abs() < 0.01, "then Chisel Hard's facet"); + let outer = maps(BevelStyle::OuterBevel, BevelTechnique::ChiselHard); + // Below the shape (rows 60..): shadow facet through 10½ px, partial at 11½. + assert!((at(&outer[1], 70) - at(&outer[1], 61)).abs() < 1e-4); + assert!(at(&outer[1], 71) > 0.05 && at(&outer[1], 71) < at(&outer[1], 70)); + assert_eq!(at(&outer[1], 72), 0.0); +} + +#[test] +fn emboss_paints_both_sides_and_pillow_flips_the_outside() { + let shape = square(40, 10, 30); + let l = GlobalLight::default(); + let (e, paint) = + bevel_maps(&shape, &bevel_of(BevelStyle::Emboss, BevelTechnique::Smooth), &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); + assert_eq!((paint, e.len()), (BevelPaint::Both, 2)); + let at = |m: &Map, x: usize, y: usize| m.v[y * 40 + x]; + // Emboss: the slope across the top edge faces the light on both sides. + assert!(at(&e[0], 20, 10) > 0.3 && at(&e[0], 20, 9) > 0.3); + let (p, _) = + bevel_maps(&shape, &bevel_of(BevelStyle::PillowEmboss, BevelTechnique::Smooth), &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); + assert!(at(&p[0], 20, 10) > 0.3 && at(&p[1], 20, 9) > 0.3, "pillow: outside top edge in shadow"); +} + +#[test] +fn emboss_width_rounds_up_and_shades_past_the_blur() { + let mut b = bevel_of(BevelStyle::Emboss, BevelTechnique::Smooth); + b.size = 41.0; + let g = bevel_geom(&b); + assert_eq!((g.width, g.depth), (21.0, 21.0)); + b.size = 5.0; + assert_eq!(bevel_geom(&b).width, 3.0); + // The first row past the height blur's reach still slopes (its upper neighbour is raised), + // so it shades; the row after it does not. + let shape = square(60, 20, 40); + b.size = 9.0; + b.angle = 90.0; + let (m, _) = bevel_maps(&shape, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); + let reach = tent_kernel(bevel_geom(&b).width).0 as usize; + let row = 39 + reach + 1; // last shape row + reach + 1: height 0, neighbour above raised + assert!(m[1].v[row * 60 + 30] > 0.0, "{}", m[1].v[row * 60 + 30]); + assert_eq!(m[1].v[(row + 1) * 60 + 30], 0.0); +} + +/// A `len` x `wid` bar through the middle of a `w` x `h` map at `deg` degrees, anti-aliased by +/// 16 x 16 supersampling (the coverage a scanline rasteriser gives). +fn aa_bar(w: usize, h: usize, deg: f32, len: f32, wid: f32) -> Map { + let (sn, cs) = deg.to_radians().sin_cos(); + let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0); + let mut m = Map::new(w, h, 0.0); + const N: usize = 16; + for y in 0..h { + for x in 0..w { + let mut hit = 0; + for sy in 0..N { + for sx in 0..N { + let (px, py) = (x as f32 + (sx as f32 + 0.5) / N as f32 - cx, y as f32 + (sy as f32 + 0.5) / N as f32 - cy); + let (u, v) = (px * cs + py * sn, -px * sn + py * cs); + hit += usize::from(u.abs() <= len / 2.0 && v.abs() <= wid / 2.0); + } + } + m.v[y * w + x] = hit as f32 / (N * N) as f32; + } + } + m +} + +/// Ripple and bias of a distance field on an `aa_bar` (`inside` or outside it): the worst +/// standard deviation of the error among pixels at the same true distance from a long edge +/// (0.5 px bins, 0.6..8 px, away from the ends), and the worst mean error of a bin. A constant +/// offset is no ripple: only a field that varies along the edge shades in stripes. +fn bar_ripple(f: &[f32], w: usize, h: usize, deg: f32, wid: f32, inside: bool) -> (f32, f32) { + let (sn, cs) = deg.to_radians().sin_cos(); + let mut bins: Vec> = vec![Vec::new(); 16]; + for y in 0..h { + for x in 0..w { + let (px, py) = (x as f32 + 0.5 - w as f32 / 2.0, y as f32 + 0.5 - h as f32 / 2.0); + let (u, v) = (px * cs + py * sn, -px * sn + py * cs); + let truth = if inside { wid / 2.0 - v.abs() } else { v.abs() - wid / 2.0 }; + if u.abs() < 40.0 && (0.6..8.0).contains(&truth) { + bins[(truth * 2.0) as usize].push(f[y * w + x] - truth); + } + } + } + let (mut ripple, mut bias) = (0.0f32, 0.0f32); + for b in bins.iter().filter(|b| b.len() > 8) { + let mean = b.iter().sum::() / b.len() as f32; + let sd = (b.iter().map(|e| (e - mean) * (e - mean)).sum::() / b.len() as f32).sqrt(); + ripple = ripple.max(sd); + bias = bias.max(mean.abs()); + } + (ripple, bias) +} + +/// The worst standard deviation of the chisel shading (highlight minus shadow) along lines +/// parallel to an `aa_bar` 2..6 px in from its edges, the way Issue #1926 measured stripes. +fn bar_shade_ripple(deg: f32, light: f32) -> f32 { + let (w, h) = (220usize, 220usize); + let bar = aa_bar(w, h, deg, 150.0, 16.0); + let mut b = bevel_of(BevelStyle::InnerBevel, BevelTechnique::ChiselHard); + (b.size, b.depth, b.angle, b.altitude) = (8.0, 2.2, light, 32.0); + let (m, _) = bevel_maps(&bar, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); + let (sn, cs) = deg.to_radians().sin_cos(); + let mut worst = 0.0f32; + for o in [-6.0f32, -5.0, -4.0, -3.0, -2.0, 2.0, 3.0, 4.0, 5.0, 6.0] { + let line: Vec = (-60..=60) + .map(|k| { + let t = k as f32 * 0.5; + let (x, y) = (w as f32 / 2.0 + t * cs - o * sn, h as f32 / 2.0 + t * sn + o * cs); + let i = y.floor() as usize * w + x.floor() as usize; + m[0].v[i] - m[1].v[i] + }) + .collect(); + let mean = line.iter().sum::() / line.len() as f32; + worst = worst.max((line.iter().map(|v| (v - mean) * (v - mean)).sum::() / line.len() as f32).sqrt()); + } + worst +} + +/// Coverage of a unit pixel by the half plane `n . p + s >= 0` (`p` from the pixel's centre), +/// by 64 x 64 supersampling. +fn half_plane_coverage(n: [f32; 2], s: f32) -> f32 { + const N: usize = 64; + let mut hit = 0; + for y in 0..N { + for x in 0..N { + let (px, py) = ((x as f32 + 0.5) / N as f32 - 0.5, (y as f32 + 0.5) / N as f32 - 0.5); + hit += usize::from(n[0] * px + n[1] * py + s >= 0.0); + } + } + hit as f32 / (N * N) as f32 +} + +#[test] +fn edge_offset_places_a_straight_edge_by_its_coverage() { + for step in 0..=12 { + let (sn, cs) = (step as f32 * 7.5).to_radians().sin_cos(); + for k in -12..=12 { + let s = k as f32 * 0.05; + let a = half_plane_coverage([cs, sn], s); + // Where the edge only just touches the pixel the coverage hardly moves with it. + if !(0.03..=0.97).contains(&a) { + continue; + } + let got = edge_offset([cs, sn], a); + assert!((got - s).abs() < 0.03, "{}deg s {s}: coverage {a} gave {got}", step as f32 * 7.5); + } + } + // Axis-aligned edges keep `alpha - 1/2`; a pixel no coverage says anything about is 0. + assert!((edge_offset([1.0, 0.0], 0.25) + 0.25).abs() < 1e-6); + assert!((edge_offset([0.0, 1.0], 0.9) - 0.4).abs() < 1e-6); + assert_eq!(edge_offset([0.6, 0.8], f32::NAN), 0.0); +} + +#[test] +fn bevel_distances_equal_the_plain_ones_without_anti_aliasing() { + // Hard edges (no partly covered pixel) and soft ramps (no sharp one) keep the plain fields. + let (w, h) = (96usize, 80usize); + let mut maps = Vec::new(); + for kind in 0..4 { + let mut m = Map::new(w, h, 0.0); + let mut seed = 12345u32; + for y in 0..h { + for x in 0..w { + let (dx, dy) = (x as f32 - 48.0, y as f32 - 40.0); + m.v[y * w + x] = match kind { + 0 => f32::from((50.0..90.0).contains(&(x as f32 * 0.6 + y as f32))), + 1 => f32::from(dx * dx + dy * dy < 30.0 * 30.0), + 2 => { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + f32::from(seed >> 28 < 5 && x > 10 && x < 80) + } + _ => ((20.0 - (dx * dx + dy * dy).sqrt()) / 8.0).clamp(0.0, 1.0), + }; + } + } + maps.push(m); + } + for (i, m) in maps.iter().enumerate() { + let sharp = sharp_edges(m); + assert!(sharp.is_empty(), "map {i} has no anti-aliased edge"); + assert_eq!(bevel_dist_inside(m, &sharp, 1e9), dist_inside(m), "inside, map {i}"); + assert_eq!(bevel_dist_outside(m, &sharp, 1e9), dist_outside(m), "outside, map {i}"); + } +} + +#[test] +fn chisel_distance_has_no_ripple_along_oblique_edges() { + // The plain distance to a pixel's centre ripples with the staircase of an oblique edge (the + // stripes of Issue #1926); at 0 and 45 degrees the staircase is regular and it does not. + let (w, h) = (160, 160); + for deg in [0.0f32, 30.0, 45.0, 60.0, 75.0, 120.0, 150.0] { + let bar = aa_bar(w, h, deg, 120.0, 40.0); + let sharp = sharp_edges(&bar); + let inside = bar_ripple(&bevel_dist_inside(&bar, &sharp, 40.0), w, h, deg, 40.0, true); + let outside = bar_ripple(&bevel_dist_outside(&bar, &sharp, 40.0), w, h, deg, 40.0, false); + for (what, (ripple, bias)) in [("inside", inside), ("outside", outside)] { + assert!(ripple < 0.008 && bias < 0.01, "{deg} deg {what}: ripple {ripple}, bias {bias}"); + } + } + let plain = aa_bar(w, h, 60.0, 120.0, 40.0); + let (ripple, _) = bar_ripple(&dist_inside(&plain), w, h, 60.0, 40.0, true); + assert!(ripple > 0.1, "the plain field still ripples ({ripple}), so the test above means something"); +} + +#[test] +fn edge_normals_follow_straight_edges_to_a_fraction_of_a_degree() { + // The 3x3 gradient is 1-3 degrees off and the error is systematic; the line through the edge + // points of the pixels around one is not. + let (w, h, wid) = (160usize, 160usize, 40.0f32); + for deg in [30.0f32, 60.0, 75.0, 120.0, 150.0] { + let sharp = sharp_edges(&aa_bar(w, h, deg, 120.0, wid)); + let (sn, cs) = deg.to_radians().sin_cos(); + let (mut worst, mut seen) = (0.0f32, 0); + for (i, e) in sharp.iter() { + let (px, py) = ((i % w) as f32 + 0.5 - w as f32 / 2.0, (i / w) as f32 + 0.5 - h as f32 / 2.0); + let (u, v) = (px * cs + py * sn, -px * sn + py * cs); + if u.abs() > 40.0 || (wid / 2.0 - v.abs()).abs() > 1.5 { + continue; + } + let into = if v > 0.0 { [sn, -cs] } else { [-sn, cs] }; + worst = worst.max((e.normal[0] * into[0] + e.normal[1] * into[1]).clamp(-1.0, 1.0).acos().to_degrees()); + seen += 1; + } + assert!(seen > 100 && worst < 0.6, "{deg} deg: {seen} edge pixels, normal off by up to {worst} deg"); + } +} + +#[test] +fn chisel_distance_is_close_on_round_shapes() { + // Circles (a hard stretch of edge at each pole, where the edge lies on a pixel boundary) and + // rounded rectangles on whole pixels (straight hard edges joined to anti-aliased arcs): the + // distance to the sharp pixels alone is up to 0.3 px too long there, so the plain distance + // caps it. Errors are against the exact distance to the shape, 0.6..8 px from its edge. + let worst = |f: &[f32], w: usize, h: usize, sdf: &dyn Fn(f32, f32) -> f32, inside: bool| { + let mut mx = 0.0f32; + for y in 0..h { + for x in 0..w { + let t = sdf(x as f32 + 0.5, y as f32 + 0.5); + let truth = if inside { -t } else { t }; + if (0.6..8.0).contains(&truth) { + mx = mx.max((f[y * w + x] - truth).abs()); + } + } + } + mx + }; + for r in [20.0f32, 40.0, 70.0] { + let (w, h) = (200usize, 200usize); + let m = aa_disc(w, h, r); + let sharp = sharp_edges(&m); + let sdf = |x: f32, y: f32| (x - 100.0).hypot(y - 100.0) - r; + let (i, o) = (worst(&bevel_dist_inside(&m, &sharp, 12.0), w, h, &sdf, true), worst(&bevel_dist_outside(&m, &sharp, 12.0), w, h, &sdf, false)); + assert!(i < 0.05 && o < 0.07, "disc {r}: inside off by {i}, outside by {o}"); + } + for rad in [6.0f32, 12.0, 24.0] { + let (w, h) = (200usize, 160usize); + let m = aa_round_rect(w, h, 20.0, 20.0, 180.0, 140.0, rad); + let sharp = sharp_edges(&m); + let sdf = |x: f32, y: f32| { + let (qx, qy) = ((x - 100.0).abs() - (80.0 - rad), (y - 80.0).abs() - (60.0 - rad)); + qx.max(0.0).hypot(qy.max(0.0)) + qx.max(qy).min(0.0) - rad + }; + let (i, o) = (worst(&bevel_dist_inside(&m, &sharp, 12.0), w, h, &sdf, true), worst(&bevel_dist_outside(&m, &sharp, 12.0), w, h, &sdf, false)); + assert!(i < 0.08 && o < 0.2, "rounded rect, radius {rad}: inside off by {i}, outside by {o}"); + } +} + +#[test] +fn chisel_facets_are_flat_along_oblique_edges() { + // Issue #1926: the facets of a chiselled bar at 30, 60, 120, 150 degrees were striped. + for deg in [0.0f32, 30.0, 45.0, 60.0, 75.0, 120.0, 150.0] { + for light in [-90.0f32, 0.0, 45.0, 120.0] { + let ripple = bar_shade_ripple(deg, light); + assert!(ripple < 0.03, "{deg} deg bar, light {light}: shading ripple {ripple}"); + } + } +} + +#[test] +fn bevel_distances_survive_degenerate_maps() { + let cases: [(usize, usize, f32); 7] = [(0, 0, 0.0), (1, 1, 0.5), (1, 1, 1.0), (2, 2, 0.5), (3, 1, 0.3), (5, 5, f32::NAN), (4, 4, 1.0)]; + for (w, h, a) in cases { + let m = Map::new(w, h, a); + let sharp = sharp_edges(&m); + for reach in [0.0, 8.0, f32::NAN, f32::INFINITY, -3.0] { + assert_eq!(bevel_dist_inside(&m, &sharp, reach).len(), w * h); + assert_eq!(bevel_dist_outside(&m, &sharp, reach).len(), w * h); + } + } + // A single partly covered pixel in an empty map, and an edge on the map's border. + let mut m = Map::new(5, 5, 0.0); + m.v[12] = 0.4; + let _ = (bevel_dist_inside(&m, &sharp_edges(&m), 4.0), bevel_dist_outside(&m, &sharp_edges(&m), 4.0)); + let mut m = Map::new(8, 8, 0.0); + for y in 0..8 { + m.v[y * 8 + 7] = 1.0; + m.v[y * 8 + 6] = 0.5; + } + let _ = (bevel_dist_inside(&m, &sharp_edges(&m), 4.0), bevel_dist_outside(&m, &sharp_edges(&m), 4.0)); +} + +#[test] +fn par_units_visits_every_unit_once_with_its_own_slices() { + // Lengths that leave a short last unit, no second slice, units of different sizes, and nothing at all. + let cases: [(usize, usize, usize, usize); 8] = + [(0, 3, 0, 0), (1, 1, 1, 1), (10, 3, 0, 0), (64, 8, 64, 8), (65, 8, 13, 1), (200, 1, 200, 1), (7, 7, 14, 2), (9, 4, 0, 5)]; + for (la, ua, lb, ub) in cases { + for threads in [1, 2, 3, 8, 64] { + let (mut a, mut b) = (vec![0u32; la], vec![0u32; lb]); + let calls = std::sync::atomic::AtomicUsize::new(0); + with_threads(threads, || { + par_units( + la, + &mut a, + ua, + &mut b, + ub, + || (), + |_, u, sa, sb| { + calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + assert!(sa.len() <= ua && sb.len() <= ub); + for (k, v) in sa.iter_mut().enumerate() { + *v = (u * ua + k) as u32 + 1; + } + for (k, v) in sb.iter_mut().enumerate() { + *v = (u * ub + k) as u32 + 1; + } + }, + ); + }); + assert_eq!(calls.into_inner(), la.div_ceil(ua), "{la} {ua} {lb} {ub} on {threads}"); + assert!(a.iter().enumerate().all(|(i, &v)| v == i as u32 + 1), "a: {la} {ua} {lb} {ub} on {threads}"); + // `b` is written for the units that exist in `a` and no further. + let written = (la.div_ceil(ua) * ub).min(lb); + assert!(b.iter().enumerate().all(|(i, &v)| v == if i < written { i as u32 + 1 } else { 0 }), "b: {la} {ua} {lb} {ub} on {threads}"); + } + } + // A unit size of 0 does nothing. + let mut a = vec![1u8; 4]; + par_units(4, &mut a, 0, &mut [] as &mut [()], 0, || (), |_, _, _, _| panic!("no units")); +} + +#[test] +fn nearest_distances_do_not_depend_on_the_threads() { + // Sizes that do not divide into the thread groups, lines of 1 pixel, and a noisy map where + // many pixels are equally far from two seeds (the nearest one must resolve the same way). + for (w, h) in [(37usize, 23usize), (1, 40), (40, 1), (2, 2), (101, 3), (64, 64)] { + let mut seed = 7u32; + let inside: Vec = (0..w * h) + .map(|_| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 24).is_multiple_of(11) + }) + .collect(); + let (d1, n1) = with_threads(1, || edt_nearest(&inside, w, h)); + for threads in [2, 3, 8] { + let (d, n) = with_threads(threads, || edt_nearest(&inside, w, h)); + assert_eq!((bits(&d), n), (bits(&d1), n1.clone()), "{w}x{h} on {threads} threads"); + } + // And the nearest pixel is a seed at exactly that distance. + for (i, (&d, &q)) in d1.iter().zip(&n1).enumerate() { + if inside.iter().any(|&b| b) { + let (dx, dy) = ((i % w) as f32 - (q as usize % w) as f32, (i / w) as f32 - (q as usize / w) as f32); + assert!(inside[q as usize] && (dx.hypot(dy) - d).abs() < 1e-3, "{w}x{h} at {i}: {d} vs seed {q}"); + } + } + } +} + +#[test] +fn nearest_distances_survive_degenerate_sizes() { + // The slice does not match the size, or there is nothing: no panic, and a result per input pixel. + for (len, w, h) in [(0usize, 0usize, 0usize), (0, 5, 0), (0, 0, 5), (6, 2, 2), (6, 4, 2), (1, 0, 1)] { + let (d, n) = edt_nearest(&vec![true; len], w, h); + assert_eq!((d.len(), n.len()), (len, len), "{len} px as {w}x{h}"); + } +} + +#[test] +fn chisel_fields_do_not_depend_on_the_threads() { + // Edge pixels at every angle, curves, patchy opacity and an edge along the border, on sizes that + // leave short last groups; one thread (in order) is the reference. + let mut maps = vec![ + aa_disc(97, 83, 30.0), + aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0), + aa_bar(120, 120, 33.0, 100.0, 30.0), + aa_bar(90, 130, 60.0, 150.0, 25.0), + ]; + let mut patchy = aa_disc(101, 101, 40.0); + for (i, v) in patchy.v.iter_mut().enumerate() { + if (i % 101 / 13 + i / 101 / 17) % 5 == 0 { + *v *= 0.6; + } + } + maps.push(patchy); + maps.push(aa_bar(64, 64, 40.0, 220.0, 30.0)); + for (k, m) in maps.iter().enumerate() { + for reach in [3.0f32, 12.0] { + let one = with_threads(1, || (sharp_edges(m), distance_field_of(m, reach))); + for threads in [2, 5, 16] { + let many = with_threads(threads, || (sharp_edges(m), distance_field_of(m, reach))); + assert_eq!(one.0.slot, many.0.slot, "map {k} sharp slots on {threads} threads"); + let edges = |s: &SharpEdges| { + s.pixels.iter().map(|p| (p.at, p.cov.to_bits(), p.edge.offset.to_bits(), p.edge.normal.map(f32::to_bits))).collect::>() + }; + assert_eq!(edges(&one.0), edges(&many.0), "map {k} sharp edges on {threads} threads"); + for (a, b) in one.1.iter().zip(&many.1) { + assert_eq!(bits(a), bits(b), "map {k}, reach {reach} on {threads} threads"); + } + } + } + } +} + +#[test] +fn bevel_maps_do_not_depend_on_the_threads() { + // Every style and technique, softened or not, and a texture; one thread (in order) is the reference. + let mut patchy = aa_disc(101, 101, 40.0); + for (i, v) in patchy.v.iter_mut().enumerate() { + if (i % 101 / 13 + i / 101 / 17) % 5 == 0 { + *v *= 0.6; + } + } + let shapes = [aa_disc(97, 83, 30.0), aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0), aa_bar(90, 130, 60.0, 150.0, 25.0), patchy]; + let mut sf = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); + sf.fill_rect(Rect::new(0, 0, 4, 2), &[0.0, 0.0, 0.0, 1.0]); + sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]); + let pats = [Pattern::new("stripes", sf, 4, 4)]; + let light = GlobalLight::default(); + let styles = [BevelStyle::InnerBevel, BevelStyle::OuterBevel, BevelStyle::Emboss, BevelStyle::PillowEmboss, BevelStyle::StrokeEmboss]; + for (k, shape) in shapes.iter().enumerate() { + let tex = TextureCtx { rect: Rect::new(3, 5, 3 + shape.w as i32, 5 + shape.h as i32), patterns: &pats, anchor: (0.0, 0.0) }; + for style in styles { + for technique in [BevelTechnique::Smooth, BevelTechnique::ChiselHard, BevelTechnique::ChiselSoft] { + for (size, soften, textured) in [(5.0, 0.0, false), (12.0, 2.0, false), (8.0, 0.0, true)] { + let mut b = bevel_of(style, technique); + (b.size, b.soften) = (size, soften); + if textured { + b.texture = Some(photocraft_doc::BevelTexture { + name: "stripes".into(), + id: String::new(), + scale: 1.0, + depth: 1.0, + invert: false, + link: true, + phase: (0.0, 0.0), + }); + } + let run = || bevel_maps(shape, &b, &light, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)).0; + let one = with_threads(1, run); + for threads in [2, 5, 16] { + let many = with_threads(threads, run); + assert_eq!(one.len(), many.len()); + for (j, (a, m)) in one.iter().zip(&many).enumerate() { + assert_eq!(bits(&a.v), bits(&m.v), "shape {k}, {style:?} {technique:?} size {size} map {j} on {threads} threads"); + } + } + } + } + } + } +} + +/// The four fields that use the distance transform, of `m`. +fn distance_field_of(m: &Map, reach: f32) -> Vec> { + [FieldKind::Inside, FieldKind::Outside, FieldKind::BevelInside, FieldKind::BevelOutside] + .map(|k| distance_field(k, m.v.clone(), m.w, m.h, reach)) + .to_vec() +} + +fn aa_disc(w: usize, h: usize, r: f32) -> Map { + let mut m = Map::new(w, h, 0.0); + const N: usize = 16; + for y in 0..h { + for x in 0..w { + let mut hit = 0; + for sy in 0..N { + for sx in 0..N { + let (px, py) = (x as f32 + (sx as f32 + 0.5) / N as f32 - w as f32 / 2.0, y as f32 + (sy as f32 + 0.5) / N as f32 - h as f32 / 2.0); + hit += usize::from(px * px + py * py <= r * r); + } + } + m.v[y * w + x] = hit as f32 / (N * N) as f32; + } + } + m +} + +/// Integer-aligned rounded rectangle (x0..x1 x y0..y1, corner radius `rad`), anti-aliased by supersampling. +fn aa_round_rect(w: usize, h: usize, x0: f32, y0: f32, x1: f32, y1: f32, rad: f32) -> Map { + let sdf = |px: f32, py: f32| { + let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0); + let (qx, qy) = ((px - cx).abs() - ((x1 - x0) / 2.0 - rad), (py - cy).abs() - ((y1 - y0) / 2.0 - rad)); + qx.max(0.0).hypot(qy.max(0.0)) + qx.max(qy).min(0.0) - rad + }; + let mut m = Map::new(w, h, 0.0); + const N: usize = 16; + for y in 0..h { + for x in 0..w { + let mut hit = 0; + for sy in 0..N { + for sx in 0..N { + hit += usize::from(sdf(x as f32 + (sx as f32 + 0.5) / N as f32, y as f32 + (sy as f32 + 0.5) / N as f32) <= 0.0); + } + } + m.v[y * w + x] = hit as f32 / (N * N) as f32; + } + } + m +} + +#[test] +fn chisel_hard_has_flat_facets() { + let shape = square(48, 10, 38); + let (m, _) = bevel_maps( + &shape, + &bevel_of(BevelStyle::InnerBevel, BevelTechnique::ChiselHard), + &GlobalLight::default(), + &no_tex(), + &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES), + ); + let at = |x: usize, y: usize| m[0].v[y * 48 + x]; + // A constant slope: equal highlight along the top facet. + assert!(at(24, 12) > 0.1 && (at(24, 12) - at(24, 13)).abs() < 1e-3); +} + +#[test] +fn linear_bevel_contour_leaves_the_height_alone_at_any_range() { + for range in [0.5, 0.7, 1.0] { + let lut = bevel_contour_lut(&photocraft_doc::BevelContour { contour: Contour::Linear, range, anti_alias: false }); + for v in [0.0f32, 0.25, 0.5, 0.75, 1.0] { + assert!((lut_at(&lut, v) - v).abs() < 1e-3, "range {range}: {v} -> {}", lut_at(&lut, v)); + } + } +} + +#[test] +fn bevel_contour_and_texture_shape_the_height() { + let shape = square(40, 6, 34); + let l = GlobalLight::default(); + let plain = bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth); + let (a, _) = bevel_maps(&shape, &plain, &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); + // A contour reshapes the profile (here a ramp folded at its middle). + let mut c = plain.clone(); + let fold = vec![ + photocraft_doc::adjust::CurvePoint { input: 0.0, output: 0.0 }, + photocraft_doc::adjust::CurvePoint { input: 0.5, output: 1.0 }, + photocraft_doc::adjust::CurvePoint { input: 1.0, output: 0.0 }, + ]; + c.contour = Some(photocraft_doc::BevelContour { + contour: Contour::Custom { name: "fold".into(), points: fold, corners: vec![] }, + range: 1.0, + anti_alias: false, + }); + let (b, _) = bevel_maps(&shape, &c, &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); + let diff: f32 = a[1].v.iter().zip(&b[1].v).map(|(x, y)| (x - y).abs()).sum(); + assert!(diff > 5.0, "{diff}"); + // A striped texture lights the flat middle. + let mut sf = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); + sf.fill_rect(Rect::new(0, 0, 4, 2), &[0.0, 0.0, 0.0, 1.0]); + sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]); + let pats = [Pattern::new("stripes", sf, 4, 4)]; + let mut t = plain.clone(); + t.texture = Some(photocraft_doc::BevelTexture { + name: "stripes".into(), + id: String::new(), + scale: 1.0, + depth: 1.0, + invert: false, + link: true, + phase: (0.0, 0.0), + }); + let tex = TextureCtx { rect: Rect::new(0, 0, 40, 40), patterns: &pats, anchor: (0.0, 0.0) }; + let (m, _) = bevel_maps(&shape, &t, &l, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)); + let mid: f32 = (16..24).map(|y| m[0].v[y * 40 + 20] + m[1].v[y * 40 + 20]).sum(); + let flat: f32 = (16..24).map(|y| a[0].v[y * 40 + 20] + a[1].v[y * 40 + 20]).sum(); + assert!(mid > flat + 0.5, "{mid} vs {flat}"); +} + +#[test] +fn glow_range_stretches_the_contour() { + let mut g = Glow { + common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0), + paint: FxPaint::Color(photocraft_color::Color::WHITE), + technique: GlowTechnique::Softer, + spread: 0.0, + size: 10.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source: GlowSource::Edge, + }; + let l = glow_lut(&g).unwrap(); + assert!((lut_at(&l, 0.25) - 0.5).abs() < 1e-3 && (lut_at(&l, 0.75) - 1.0).abs() < 1e-6); + g.range = 1.0; + assert!(glow_lut(&g).is_none()); +} + +/// Photoshop 27.11, measured on a 128 px square (Normal, black, 100 %, Range 50 %): a precise +/// glow's coverage across the edge, and a centre-source inner glow as 1 − the edge glow. +#[test] +fn glows_match_photoshop() { + let glow = |technique, size: f32, spread: f32, source| Glow { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + paint: FxPaint::Color(photocraft_color::Color::BLACK), + technique, + spread, + size, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source, + }; + let n = 60; + let mut shape = Map::new(n, n, 0.0); + for y in 20..40 { + for x in 20..40 { + shape.v[y * n + x] = 1.0; + } + } + let at = |m: &Map, x: usize| m.v[30 * n + x]; + // Outer, precise, size 10: Photoshop's black glow over white reads 47, 93, 140, 186, 232 + // at 2, 4, 6, 8 and 10 px out from the edge pixel (alpha 1 − D / 11). + let m = glow_map(&shape, &glow(GlowTechnique::Precise, 10.0, 0.0, GlowSource::Edge), false, (0, 0)); + for (d, ps) in [(2, 47.0f32), (4, 93.0), (6, 140.0), (8, 186.0), (10, 232.0)] { + let got = 255.0 * (1.0 - at(&m, 20 - d)); + assert!((got - ps).abs() <= 1.5, "outer precise at {d} px: {got} vs Photoshop {ps}"); + } + // Spread 40 %: solid for the first 4 px. + let m = glow_map(&shape, &glow(GlowTechnique::Precise, 10.0, 0.4, GlowSource::Edge), false, (0, 0)); + assert!((at(&m, 16) - 1.0).abs() < 1e-6 && at(&m, 14) < 1.0); + // Centre source = 1 − edge, for both techniques. + for t in [GlowTechnique::Precise, GlowTechnique::Softer] { + let e = glow_map(&shape, &glow(t, 6.0, 0.0, GlowSource::Edge), true, (0, 0)); + let c = glow_map(&shape, &glow(t, 6.0, 0.0, GlowSource::Center), true, (0, 0)); + for x in 20..40 { + assert!((at(&c, x) - (1.0 - at(&e, x))).abs() < 1e-5, "{t:?} at {x}"); + } + } +} + +#[test] +fn offsets_follow_light() { + let (dx, dy) = offset(120.0, 10.0); + assert_eq!((dx, dy), (5.0, 9.0)); +} + +fn square_shape(n: usize) -> Map { + let mut m = Map::new(n, n, 0.0); + for y in 5..n - 5 { + for x in 5..n - 5 { + m.v[y * n + x] = 1.0; + } + } + m +} + +#[test] +fn satin_at_distance_zero_matches_photoshop() { + // Photoshop 27.11, Satin black 100 %, angle 90°, Linear contour, distance 0, size 5 over a + // #808080 square: the rows from the top edge read 82, 102, 123, 128. + let s = photocraft_doc::effects::Satin { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + color: photocraft_color::Color::BLACK, + angle: 90.0, + distance: 0.0, + size: 5.0, + contour: Contour::Linear, + anti_alias: false, + invert: false, + }; + let m = satin_map(&square_shape(60), &s); + for (row, gray) in [(5, 82.0), (7, 102.0), (9, 123.0), (11, 128.0), (30, 128.0)] { + let want = 1.0 - gray / 128.0; + let got = m.v[row * 60 + 30]; + assert!((got - want).abs() < 0.02, "row {row}: {got} vs {want}"); + } +} + +fn shadow(noise: f32, origin: (i32, i32)) -> Map { + let s = Shadow { + common: photocraft_doc::FxCommon::new(BlendMode::Multiply, 1.0), + color: photocraft_color::Color::BLACK, + angle: 0.0, + use_global_light: false, + distance: 0.0, + spread: 0.0, + size: 6.0, + contour: Contour::Linear, + anti_alias: false, + noise, + knocks_out: true, + }; + shadow_map(&square_shape(40), &s, &GlobalLight::default(), false, origin) +} + +#[test] +fn shadow_noise_speckles_soft_coverage_deterministically() { + let plain = shadow(0.0, (0, 0)); + let noisy = shadow(0.5, (0, 0)); + let again = shadow(0.5, (0, 0)); + let (mut diff, mut identical) = (0.0f32, true); + for i in 0..plain.v.len() { + diff += (plain.v[i] - noisy.v[i]).abs(); + if noisy.v[i] != again.v[i] { + identical = false; + } + } + assert!(diff > 5.0, "noise changes the soft band: {diff}"); + assert!(identical, "same coords, same speckle"); + // Every value stays a coverage. + assert!(noisy.v.iter().all(|v| (0.0..=1.0).contains(v))); + // The speckle moves with the document origin, not the tile. + let moved = shadow(0.5, (100, 100)); + assert_ne!(noisy.v, moved.v, "hashed from document coordinates"); + // Full noise can punch holes even in the solid part. + let heavy = shadow(1.0, (0, 0)); + assert!(heavy.v.iter().any(|v| *v < 0.5) && heavy.v.iter().any(|v| *v > 0.5), "heavy noise spans the range",); +} + +#[test] +fn box_blur_preserves_faint_coverage_and_empty_gaps() { + let src = [0.0, 0.3, 0.7, 0.0, 0.0, 0.0, 0.0, 1e-20, 0.0, 0.0, 0.0]; + let mut actual = [0.0; 11]; + box_line(&src, 0, &mut actual, 3.0); + assert_eq!(actual[5], 0.0, "an empty window must be exactly empty"); + assert_eq!(actual[10], 0.0, "the second tail must also be empty"); + assert!((actual[7] - 1e-20 / 3.0).abs() < 1e-30, "real faint coverage is not rounded away"); +} + +#[test] +fn effect_noise_does_not_light_up_empty_blur_tails() { + // A sloping antialiased shape leaves rounding residue in a running-sum blur. + // The direct finite-support convolution is the oracle for untouched pixels. + for size in [5.0, 5.5, 13.0] { + let mut shape = Map::new(96, 64, 0.0); + for y in 8..48 { + for x in 8..48 { + shape.v[y * shape.w + x] = ((x as f32 - y as f32 * 0.7) * 0.3).clamp(0.0, 1.0); + } + } + let mut direct = shape.clone(); + tent_direct(&mut direct, size); + let mut actual = shape; + blur(&mut actual, size); + noise(&mut actual, 0.26, 0, 0); + let stray = direct.v.iter().zip(&actual.v).filter(|(reference, noisy)| **reference == 0.0 && **noisy > 1e-5).count(); + assert_eq!(stray, 0, "noise created {stray} visible pixels outside a size-{size} blur"); + } +} + +#[test] +fn glow_noise_follows_the_contour_and_range() { + let g = |noise: f32| Glow { + common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0), + paint: FxPaint::Color(photocraft_color::Color::WHITE), + technique: GlowTechnique::Softer, + spread: 0.0, + size: 6.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise, + source: GlowSource::Edge, + }; + let plain = glow_map(&square_shape(40), &g(0.0), false, (0, 0)); + let noisy = glow_map(&square_shape(40), &g(0.6), false, (0, 0)); + let diff: f32 = plain.v.iter().zip(&noisy.v).map(|(a, b)| (a - b).abs()).sum(); + assert!(diff > 5.0, "glow noise changes the coverage: {diff}"); +} + +/// Issue #7833: the speckle stays inside the glow's visible falloff instead of filling the +/// blur's whole rectangular reach out to the map edge. +#[test] +fn effect_noise_stays_inside_the_visible_falloff() { + let mut shape = Map::new(80, 80, 0.0); + for y in 35..45 { + for x in 35..45 { + shape.v[y * 80 + x] = 1.0; + } + } + let g = |noise: f32| Glow { + common: photocraft_doc::FxCommon::new(BlendMode::Screen, 1.0), + paint: FxPaint::Color(photocraft_color::Color::WHITE), + technique: GlowTechnique::Softer, + spread: 0.0, + size: 10.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise, + source: GlowSource::Edge, + }; + let s = |noise: f32| Shadow { + common: photocraft_doc::FxCommon::new(BlendMode::Multiply, 1.0), + color: photocraft_color::Color::BLACK, + angle: 0.0, + use_global_light: false, + distance: 0.0, + spread: 0.0, + size: 10.0, + contour: Contour::Linear, + anti_alias: false, + noise, + knocks_out: true, + }; + let light = GlobalLight::default(); + let pairs = [ + ("glow", glow_map(&shape, &g(0.0), false, (0, 0)), glow_map(&shape, &g(0.5), false, (0, 0))), + ("shadow", shadow_map(&shape, &s(0.0), &light, false, (0, 0)), shadow_map(&shape, &s(0.5), &light, false, (0, 0))), + ]; + for (name, plain, noisy) in pairs { + for (i, (p, n)) in plain.v.iter().zip(&noisy.v).enumerate() { + if *p < 1.0 / 255.0 { + assert!(*n <= 2.0 / 255.0, "{name}: pixel ({}, {}) invisible without noise: {p} -> {n}", i % 80, i / 80); + } + } + } +} + +#[test] +fn shifting_by_hostile_distances_does_not_overflow() { + let m = square_shape(12); + for d in [1.0e30, -1.0e30, f32::INFINITY, f32::NAN] { + let s = m.shifted(d, d, 0.0); + assert_eq!(s.v.len(), 144); + } +} From 120a3b5291873a01f663668b95568139b6ba1cdb Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:44 +0000 Subject: [PATCH 112/259] refactor(compose): move adjust.rs tone_tests to adjust/tone_tests.rs --- crates/compose/src/adjust.rs | 887 +----------------------- crates/compose/src/adjust/tone_tests.rs | 884 +++++++++++++++++++++++ 2 files changed, 885 insertions(+), 886 deletions(-) create mode 100644 crates/compose/src/adjust/tone_tests.rs diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs index cd907e9cfa..5eb3314bbf 100644 --- a/crates/compose/src/adjust.rs +++ b/crates/compose/src/adjust.rs @@ -1613,892 +1613,7 @@ mod lookup_tests { } #[cfg(test)] -mod tone_tests { - use super::*; - use photocraft_geom::Rect; - - fn ramp() -> Buffer { - let rect = Rect::new(0, 0, 8, 8); - let px = (0..64).map(|i| [((i % 8) as f32) / 7.0, ((i / 8) as f32) / 7.0, 0.3, 1.0]).collect(); - Buffer { rect, px } - } - - /// Photoshop 27.11, measured: Brightness/Contrast with Use Legacy on, over a gray ramp - /// (x = 0, 16, …, 240, 255), one row per (brightness, contrast). - /// One pixel through `adj` in a 32-bit document. - fn hdr(adj: &Adjustment, c: [f32; 3]) -> [f32; 3] { - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); - apply_depth(adj, &mut b, Transfer::Gamma(1.0), Some(SampleType::F32)); - [b.px[0][0], b.px[0][1], b.px[0][2]] - } - - /// Photoshop's 32-bit Hue/Saturation (photoshop corpus rgb32 hue-saturation.psd: hue +40, - /// saturation +25, lightness -10): saturated colours leave 0..1, and the saturation factor is - /// 1 / (1 - 63/255), so red becomes (1.0477, 0.649, -0.1477), where 8 bits clip to (0.9, 0.6, 0). - #[test] - fn thirty_two_bit_hue_saturation_is_unclipped() { - let adj = Adjustment::HueSaturation { hue: 40.0, saturation: 25.0, lightness: -10.0, colorize: false, ranges: HueRange::defaults() }; - let near = |got: [f32; 3], want: [f32; 3]| got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3); - for (c, want) in - [([1.0, 0.0, 0.0], [1.0477, 0.649, -0.1477]), ([0.9301, 0.6105, 0.2541], [0.7804, 0.9369, 0.1289]), ([0.0, 0.3864, 1.0], [0.1871, -0.1477, 1.0477])] - { - assert!(near(hdr(&adj, c), want), "{c:?}: {:?}", hdr(&adj, c)); - } - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [1.0, 0.0, 0.0, 1.0]); - apply_depth(&adj, &mut b, Transfer::Srgb, Some(SampleType::U16)); - assert!(b.px[0].iter().all(|v| (0.0..=1.0).contains(v)), "16 bits clip: {:?}", b.px[0]); - } - - /// Photoshop's 32-bit Colorize (photoshop corpus rgb32 hue-saturation-colorize.psd: hue -160, - /// saturation 40, lightness +5): red becomes (0.3445, 0.5852, 0.7055), 0.95 of the chroma an - /// 8-bit Colorize gives at the same lightness, (0.335, 0.5883, 0.715). - #[test] - fn thirty_two_bit_colorize_scales_the_saturation() { - let adj = Adjustment::HueSaturation { hue: -160.0, saturation: 40.0, lightness: 5.0, colorize: true, ranges: HueRange::defaults() }; - let near = |got: [f32; 3], want: [f32; 3]| got.iter().zip(want).all(|(g, w)| (g - w).abs() < 2e-3); - let red = hdr(&adj, [1.0, 0.0, 0.0]); - assert!(near(red, [0.3445, 0.5852, 0.7055]), "{red:?}"); - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [1.0, 0.0, 0.0, 1.0]); - apply_depth(&adj, &mut b, Transfer::Srgb, Some(SampleType::U16)); - assert!(near([b.px[0][0], b.px[0][1], b.px[0][2]], [0.335, 0.5883, 0.715]), "16-bit keeps the full saturation: {:?}", b.px[0]); - } - - /// Photoshop's 32-bit saturation factor (Hue/Saturation on red (1, 0, 0) in a 32-bit document, - /// read back from the saved float TIFF, exact in 1/512): red's R is 0.5 + 0.5 x the factor. - #[test] - fn thirty_two_bit_saturation_steps_match_photoshop() { - for (sat, want) in [ - (10.0, 539.0 / 512.0), - (75.0, 2.4609375), - (90.0, 2673.0 / 512.0), - (99.0, 32.375), - (100.0, 33023.0 / 512.0), - (-10.0, 487.0 / 512.0), - (-25.0, 0.875), - (-50.0, 0.75), - (-100.0, 0.5), - ] { - let adj = Adjustment::HueSaturation { hue: 0.0, saturation: sat, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; - let got = hdr(&adj, [1.0, 0.0, 0.0])[0]; - assert!((got - want).abs() < 1e-4, "saturation {sat}: {got}, Photoshop {want}"); - } - } - - /// 32-bit colours at or above HSL lightness 1 (red at +1 stop, (2, 0, 0)) keep their hue and - /// get their chroma scaled like any other, as in Photoshop; they used to turn NaN or grey. - #[test] - fn thirty_two_bit_hue_saturation_keeps_bright_colours() { - let pale = [280.0 / 255.0, 230.0 / 255.0, 256.0 / 255.0]; - let near = |got: [f32; 3], want: [f32; 3]| got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1e-3 * w.abs().max(1.0)); - for (hue, sat, c, want) in [ - (40.0, 0.0, [2.0, 0.0, 0.0], [2.0, 1.33301, 0.0]), - (40.0, 0.0, pale, [1.09804, 0.930687, 0.901961]), - (0.0, 25.0, [2.0, 0.0, 0.0], [2.32812, -0.328125, -0.328125]), - (0.0, 25.0, pale, [1.13021, 0.869792, 1.00521]), - (0.0, -25.0, [2.0, 0.0, 0.0], [1.75, 0.25, 0.25]), - (0.0, 100.0, [140.0 / 255.0, 115.0 / 255.0, 128.0 / 255.0], [6.77432, -5.77432, 0.750976]), - (0.0, 100.0, [2.0, 0.0, 0.0], [128.996, -126.996, -126.996]), - ] { - let adj = Adjustment::HueSaturation { hue, saturation: sat, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; - let got = hdr(&adj, c); - assert!(near(got, want), "hue {hue}, saturation {sat}, {c:?}: {got:?}, Photoshop {want:?}"); - } - // A master plus a range edit that add up to a whole step stay on it: Reds +96 over a master - // -46 scales red as much as a master +50 alone (in f32 the sum is 0.49999997). - let mut ranges = HueRange::defaults(); - ranges[0].saturation = 96.0; - let summed = Adjustment::HueSaturation { hue: 0.0, saturation: -46.0, lightness: 0.0, colorize: false, ranges }; - let single = Adjustment::HueSaturation { hue: 0.0, saturation: 50.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; - assert_eq!(hdr(&summed, [1.0, 0.0, 0.0]), hdr(&single, [1.0, 0.0, 0.0])); - // Lightness 0 with a negative channel divides by zero the same way. - let adj = Adjustment::HueSaturation { hue: 40.0, saturation: 25.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; - assert!(hdr(&adj, [0.25, -0.25, 0.0]).iter().all(|v| v.is_finite())); - } - - /// Photoshop's own 32-bit results (photoshop corpus rgb32): nothing clips, legacy contrast - /// pivots at 127, the mixer cuts its percentages to 1/1024 and counts 255/512 of the - /// constant, and the Black & White tint keeps values above 1. - #[test] - fn thirty_two_bit_adjustments_match_photoshop_unclipped() { - let near = |got: [f32; 3], want: [f32; 3], tol: f32| got.iter().zip(want).all(|(g, w)| (g - w).abs() <= tol); - let bc = Adjustment::BrightnessContrast { brightness: 25.0, contrast: 30.0, legacy: true }; - // brightness-contrast-legacy.psd - assert!(near(hdr(&bc, [0.4910, 0.0009, 0.9301]), [0.6280, -0.0721, 1.2553], 2e-4), "{:?}", hdr(&bc, [0.4910, 0.0009, 0.9301])); - // channel-mixer.psd: pure red, green, blue and black, exactly. - let mixer = Adjustment::ChannelMixer { matrix: [[0.8, 0.3, -0.1, 0.0], [0.1, 0.9, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0]], monochrome: false }; - for (c, want) in [ - ([1.0, 0.0, 0.0], [0.7998047, 0.1245117, 0.0]), - ([0.0, 1.0, 0.0], [0.2998047, 0.9243164, 0.1992188]), - ([0.0, 0.0, 1.0], [-0.0996094, 0.0249023, 0.6992188]), - ([0.0, 0.0, 0.0], [0.0, 0.0249023, 0.0]), - ] { - assert!(near(hdr(&mixer, c), want, 1e-6), "{c:?}: {:?}", hdr(&mixer, c)); - } - // black-white-tint.psd: white tints past 1. - let bw = Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: Some([0.88235295, 0.827451, 0.7019608]) }; - assert!(near(hdr(&bw, [1.0; 3]), [1.0522, 0.9973, 0.8718], 2e-4), "{:?}", hdr(&bw, [1.0; 3])); - // 8/16-bit documents still clip. - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [1.0, 1.0, 1.0, 1.0]); - apply_depth(&bw, &mut b, Transfer::Srgb, None); - assert!(b.px[0].iter().all(|v| *v <= 1.0)); - } - - #[test] - fn legacy_brightness_contrast_matches_photoshop() { - const X: [u8; 17] = [0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 255]; - let measured: [(f32, f32, [u8; 17]); 7] = [ - (40.0, 0.0, [40, 56, 72, 88, 104, 120, 136, 152, 168, 184, 200, 216, 232, 248, 255, 255, 255]), - (-40.0, 0.0, [0, 0, 0, 8, 24, 40, 56, 72, 88, 104, 120, 136, 152, 168, 184, 200, 215]), - (0.0, 30.0, [0, 0, 0, 14, 37, 60, 82, 105, 128, 151, 174, 196, 219, 242, 255, 255, 255]), - (0.0, -30.0, [38, 49, 61, 72, 83, 94, 106, 117, 128, 139, 150, 162, 173, 184, 195, 207, 217]), - (40.0, 30.0, [3, 25, 48, 71, 94, 117, 139, 162, 185, 208, 231, 253, 255, 255, 255, 255, 255]), - (100.0, 0.0, [100, 116, 132, 148, 164, 180, 196, 212, 228, 244, 255, 255, 255, 255, 255, 255, 255]), - (0.0, 80.0, [0, 0, 0, 0, 0, 0, 0, 48, 128, 208, 255, 255, 255, 255, 255, 255, 255]), - ]; - for (brightness, contrast, want) in measured { - let rect = Rect::new(0, 0, 17, 1); - let px = X.iter().map(|x| [f32::from(*x) / 255.0; 4]).map(|p| [p[0], p[1], p[2], 1.0]).collect(); - let mut b = Buffer { rect, px }; - apply(&Adjustment::BrightnessContrast { brightness, contrast, legacy: true }, &mut b); - for (i, (p, w)) in b.px.iter().zip(want).enumerate() { - let got = (p[0] * 255.0).round() as i32; - assert!((got - i32::from(w)).abs() <= 1, "b {brightness} c {contrast} at {}: {got} vs Photoshop {w}", X[i]); - } - } - } - - /// Pixel → Photoshop's split. 8-bit from psd-tools threshold_rgb.psd: the first three are - /// white though their Rec. 601 grey rounds below 60, and (131, 109, 99) sits exactly on 114.5 - /// at level 115 (halves round down). 16-bit from threshold_16bits_rgb.psd and the photoshop - /// corpus's rgb16 threshold-128.psd, whose mid grey 16448 is level 128 in 16 bits. - #[test] - fn threshold_splits_on_the_luminosity_like_photoshop() { - let c8 = |r: u8, g: u8, b: u8| [r, g, b].map(|v| f32::from(v) / 255.0); - for (c, level, white) in - [(c8(87, 51, 31), 60u8, true), (c8(90, 49, 33), 60, true), (c8(68, 57, 50), 60, true), (c8(48, 63, 72), 60, false), (c8(131, 109, 99), 115, false)] - { - assert_eq!(threshold_white(c, f32::from(level) / 255.0, Some(SampleType::U8)), white, "8-bit {c:?} at {level}"); - } - let c16 = |r: u16, g: u16, b: u16| [r, g, b].map(|v| f32::from(v) / 32768.0); - for (c, level, white) in [ - (c16(8995, 7196, 6425), 60u8, false), - (c16(11180, 6554, 3984), 60, false), - (c16(16448, 16448, 16448), 128, true), - (c16(16447, 16447, 16447), 128, false), - ] { - assert_eq!(threshold_white(c, f32::from(level) / 255.0, Some(SampleType::U16)), white, "16-bit {c:?} at {level}"); - } - // Through the adjustment: neutral black or white. - let mut b = Buffer::filled(Rect::new(0, 0, 1, 1), [87.0 / 255.0, 51.0 / 255.0, 31.0 / 255.0, 1.0]); - apply_depth(&Adjustment::Threshold { level: 60.0 / 255.0 }, &mut b, Transfer::Srgb, Some(SampleType::U8)); - assert_eq!(b.px[0], [1.0, 1.0, 1.0, 1.0]); - } - - /// 16-bit sample → Photoshop's 8-bit level, from psd-tools posterize_16bits_rgb.psd: bins - /// split on the 16-bit sample (10794 and 10923 straddle a third of 32768), and the middle of 3 - /// levels is 128 where 8 bits give 127, while 21 levels keep 25 for 25.5. - #[test] - fn sixteen_bit_posterize_matches_photoshop() { - let points: [(u32, u16, u8); 9] = - [(3, 10794, 0), (3, 10923, 128), (3, 21845, 128), (3, 21974, 255), (13, 2504, 0), (13, 2542, 21), (13, 7453, 42), (13, 7582, 64), (21, 3341, 25)]; - for (levels, x, want) in points { - let got = posterize_in(f32::from(x) / 32768.0, levels, Some(SampleType::U16)); - assert!((got * 255.0 - f32::from(want)).abs() < 1e-3, "{levels} levels at {x}: {} vs Photoshop {want}", got * 255.0); - } - // 8 bits keep their rule. - assert_eq!(posterize_in(128.0 / 255.0, 3, Some(SampleType::U8)), posterize(128.0 / 255.0, 3)); - } - - #[test] - fn color_lookup_with_an_overflowing_stored_size_is_the_identity() { - // A stored document's size is untrusted: (2²²)³ × 3 overflows, which once wrapped past - // the table-length guard and indexed out of bounds. - for size in [1 << 22, u32::MAX] { - let a = Adjustment::ColorLookup { name: "x".into(), lut: Some(std::sync::Arc::new(vec![0.5; 24])), size, tetrahedral: false, dither: false }; - let mut b = ramp(); - apply(&a, &mut b); - assert_eq!(b.px, ramp().px, "size {size}"); - } - } - - /// Photoshop 27.11, measured: Color Balance with one cyan–red slider moved, over a gray ramp - /// (x = 0, 16, …, 240, 255); red and green out (blue follows green on gray). - #[test] - fn color_balance_matches_photoshop() { - const X: [u8; 17] = [0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 255]; - type Row = (&'static str, f32, bool, [u8; 17], [u8; 17]); - let measured: [Row; 6] = [ - ("midtones", 50.0, false, [0, 36, 59, 78, 96, 112, 128, 142, 156, 170, 183, 196, 209, 221, 233, 244, 255], X), - ("shadows", -100.0, false, [0, 0, 0, 0, 0, 0, 0, 7, 23, 43, 67, 93, 122, 154, 186, 221, 255], X), - ("highlights", 100.0, false, [0, 51, 84, 111, 136, 160, 182, 202, 223, 242, 255, 255, 255, 255, 255, 255, 255], X), - ("shadows", 50.0, true, X, [0, 0, 0, 0, 17, 37, 57, 77, 97, 117, 137, 157, 177, 197, 216, 236, 255]), - ( - "midtones", - 100.0, - true, - [0, 36, 59, 78, 96, 112, 128, 142, 156, 170, 183, 196, 209, 221, 233, 244, 255], - [0, 5, 14, 24, 36, 50, 64, 80, 97, 114, 132, 151, 171, 191, 212, 234, 255], - ), - ("highlights", -100.0, true, X, [0, 26, 53, 79, 105, 132, 158, 184, 211, 237, 255, 255, 255, 255, 255, 255, 255]), - ]; - // Two sliders in one tone, Preserve Luminosity on (measured): shadows red and blue +50 darken - // only green; highlights red −50 with green +50 lift green by 100 and blue by 50. - let two = - |tones: [[f32; 3]; 3], x: f32| -> [i32; 3] { std::array::from_fn(|ch| (color_balance_channel(tones, true, ch, x / 255.0) * 255.0).round() as i32) }; - assert_eq!(two([[50.0, 0.0, 50.0], [0.0; 3], [0.0; 3]], 128.0), [128, 97, 128]); - let hi = two([[0.0; 3], [0.0; 3], [-50.0, 50.0, 0.0]], 128.0); - assert!((hi[0] - 128).abs() <= 1 && (hi[1] - 211).abs() <= 1 && (hi[2] - 159).abs() <= 1, "{hi:?}"); - for (tone, amount, preserve, red, green) in measured { - let mut tones = [[0.0f32; 3]; 3]; - tones[["shadows", "midtones", "highlights"].iter().position(|t| *t == tone).unwrap()][0] = amount; - for (i, x) in X.iter().enumerate() { - let v = f32::from(*x) / 255.0; - let got = |ch| (color_balance_channel(tones, preserve, ch, v) * 255.0).round() as i32; - let (r, g) = (got(0), got(1)); - assert!((r - i32::from(red[i])).abs() <= 1, "{tone} {amount} pl {preserve} at {x}: red {r} vs Photoshop {}", red[i]); - assert!((g - i32::from(green[i])).abs() <= 1, "{tone} {amount} pl {preserve} at {x}: green {g} vs Photoshop {}", green[i]); - } - } - } - - /// Photoshop, measured (8-bit gray ramp, every channel): whole settings, where the tones fold - /// into one Levels per channel (#3423). The issue's midtones red +100 / magenta −100 (the - /// shadow toe), its sequoia14 layer with Preserve Luminosity off and on, all nine sliders with - /// Preserve Luminosity on, a black point past the white point, and lowered shadows with raised - /// highlights (their gammas cancel: a straight line between the two points). - #[test] - fn color_balance_whole_settings_match_photoshop() { - const X: [u8; 12] = [0, 4, 8, 16, 32, 64, 96, 128, 160, 192, 224, 255]; - type Case = ([[f32; 3]; 3], bool, [[u8; 12]; 3]); - let cases: [Case; 6] = [ - ( - [[0.0; 3], [100.0, -100.0, 0.0], [0.0; 3]], - false, - [[0, 16, 30, 55, 90, 128, 156, 181, 202, 221, 239, 255], [0, 0, 0, 1, 4, 16, 36, 64, 100, 145, 197, 255], X], - ), - ( - [[-6.0, 22.0, 5.0], [-1.0, -3.0, -8.0], [-1.0, -4.0, -6.0]], - false, - [ - [0, 0, 2, 9, 25, 56, 89, 122, 156, 188, 222, 255], - [0, 5, 9, 18, 35, 67, 100, 131, 163, 194, 225, 255], - [0, 3, 7, 14, 29, 60, 91, 123, 156, 189, 222, 255], - ], - ), - ( - [[-6.0, 22.0, 5.0], [-1.0, -3.0, -8.0], [-1.0, -4.0, -6.0]], - true, - [ - [0, 0, 0, 0, 5, 42, 80, 117, 154, 189, 226, 255], - [0, 4, 8, 16, 33, 66, 98, 130, 162, 195, 226, 255], - [0, 0, 0, 0, 15, 48, 82, 116, 151, 186, 221, 255], - ], - ), - ( - [[40.0, -30.0, 20.0], [-50.0, 25.0, 60.0], [30.0, -70.0, 10.0]], - true, - [ - [0, 1, 3, 9, 25, 69, 126, 193, 255, 255, 255, 255], - [0, 0, 0, 0, 0, 0, 46, 93, 136, 177, 217, 255], - [0, 0, 0, 0, 44, 107, 156, 199, 238, 255, 255, 255], - ], - ), - ( - [[100.0, -100.0, 0.0], [0.0; 3], [-100.0, 100.0, 0.0]], - true, - [X, [0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255], [0, 0, 0, 0, 0, 0, 0, 130, 255, 255, 255, 255]], - ), - ( - [[-76.0, -2.0, 60.0], [0.0; 3], [99.0, 0.0, -30.0]], - false, - [ - [0, 0, 0, 0, 0, 0, 71, 171, 255, 255, 255, 255], - [0, 2, 6, 14, 29, 61, 94, 126, 158, 191, 224, 255], - [0, 6, 11, 21, 39, 73, 106, 137, 168, 197, 227, 255], - ], - ), - ]; - for (tones, preserve, want) in cases { - for (ch, row) in want.iter().enumerate() { - for (x, w) in X.iter().zip(row) { - let got = (color_balance_channel(tones, preserve, ch, f32::from(*x) / 255.0) * 255.0).round() as i32; - assert!((got - i32::from(*w)).abs() <= 1, "{tones:?} pl {preserve} ch {ch} at {x}: {got} vs Photoshop {w}"); - } - } - } - // Hostile input stays in range. - for v in [f32::NAN, -1.0, 2.0, f32::INFINITY] { - let out = color_balance_channel([[f32::NAN, 1e9, -1e9]; 3], true, 7, v); - assert!((0.0..=1.0).contains(&out), "{v}: {out}"); - } - } - - #[test] - fn color_balance_midtones_with_multiple_sliders_preserve_luminosity() { - // A shared offset depends on the two extremes, not the sum of moved sliders. - // The old per-slider product leaves red/blue unchanged for [30, 0, 30]. - let tones = [[0.0; 3], [30.0, 0.0, 30.0], [0.0; 3]]; - for input in [0.25_f32, 0.5, 0.75] { - for (ch, offset) in [-0.15_f32, 0.15, -0.15].into_iter().enumerate() { - let expected = input.powf(2f32.powf(offset)); - let actual = color_balance_channel(tones, true, ch, input); - assert!((actual - expected).abs() < 1e-6, "channel {ch}, input {input}: {actual} vs {expected}"); - } - // Preserve Luminosity off must still affect only the moved channels. - assert_eq!(color_balance_channel(tones, false, 1, input), input); - // One moved slider retains its previous half-strength compensation. - let single = [[0.0; 3], [30.0, 0.0, 0.0], [0.0; 3]]; - assert!((color_balance_channel(single, true, 0, input) - input.powf(2f32.powf(-0.15))).abs() < 1e-6); - assert!((color_balance_channel(single, true, 1, input) - input.powf(2f32.powf(0.15))).abs() < 1e-6); - } - } - - #[test] - fn color_balance_curve_matches_the_per_sample_formula_bitwise() { - // The curve works out its sample-independent terms once; this is the formula it replaced, - // evaluated whole for every sample. - fn per_sample(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize, v: f32) -> f32 { - let [shadows, midtones, highlights] = tones.map(|t| t.map(|s| if s.is_finite() { s.clamp(-100.0, 100.0) } else { 0.0 })); - let own = |t: [f32; 3]| t.get(ch).copied().unwrap_or(0.0); - let max = |t: [f32; 3]| t[0].max(t[1]).max(t[2]); - let min = |t: [f32; 3]| t[0].min(t[1]).min(t[2]); - let (black, white, m) = if preserve_luminosity { - (max(shadows) - own(shadows), own(highlights) - min(highlights), own(midtones) - (max(midtones) + min(midtones)) / 2.0) - } else { - ((-own(shadows)).max(0.0), own(highlights).max(0.0), own(midtones) + (own(shadows) + own(highlights)) / 2.0) - }; - let (b, w) = (black / 255.0, 1.0 - white / 255.0); - let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; - if v >= w { - return 1.0; - } - if v <= b { - return 0.0; - } - let (u, gamma) = ((v - b) / (w - b), 2f32.powf(m / 100.0)); - let e = 1.0 / gamma.max(0.01); - let power = u.powf(e); - if gamma <= 1.0 { - return power; - } - let s0 = 2f32.powf(gamma); - let u0 = (2.0 * s0.powf(1.0 / (e - 1.0))).min(1.0); - if u0.is_nan() || u0 <= 0.0 || u >= u0 { - return power; - } - let (p, d, t) = (u0.powf(e), e * u0.powf(e - 1.0), u / u0); - let (t2, t3) = (t * t, t * t * t); - ((t3 - 2.0 * t2 + t) * u0 * s0 + (3.0 * t2 - 2.0 * t3) * p + (t3 - t2) * u0 * d).clamp(0.0, 1.0) - } - let mut seed = 0x9e37_79b9_u32; - let mut slider = || { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - (seed % 241) as f32 - 120.0 - }; - let mut settings = vec![[[0.0; 3]; 3], [[f32::NAN, 1e9, -1e9]; 3], [[-100.0; 3], [100.0; 3], [100.0; 3]]]; - settings.extend((0..120).map(|_| std::array::from_fn(|_| std::array::from_fn(|_| slider())))); - let samples: Vec = (0..=1024).map(|i| i as f32 / 1024.0).chain([-0.5, 1.5, f32::NAN, f32::INFINITY]).collect(); - for tones in settings { - for preserve in [false, true] { - for ch in [0, 1, 2, 7] { - let curve = BalanceCurve::new(tones, preserve, ch); - for &v in &samples { - let (got, want) = (curve.eval(v), per_sample(tones, preserve, ch, v)); - assert_eq!(got.to_bits(), want.to_bits(), "{tones:?} {preserve} ch {ch} v {v}: {got} vs {want}"); - } - } - } - } - } - - #[test] - fn levels_and_curves_apply_each_channel_before_the_master() { - // These two affine tone adjustments describe the same mapping: - // channel(x) = 1 / 2 + x / 2, then master(x) = x / 2, so 0 maps to 0.25. - // Levels used to apply the master first (0 mapped to 0.5). - let line = |a: f32, b: f32| vec![CurvePoint { input: 0.0, output: a }, CurvePoint { input: 1.0, output: b }]; - let levels = Adjustment::Levels { - master: LevelsChannel { out_white: 0.5, ..Default::default() }, - per_channel: std::array::from_fn(|_| LevelsChannel { out_black: 0.5, ..Default::default() }), - space: ToneSpace::Rgb, - black: Default::default(), - }; - let curves = Adjustment::Curves { - master: line(0.0, 0.5), - per_channel: std::array::from_fn(|_| line(0.5, 1.0)), - space: ToneSpace::Rgb, - black: Vec::new(), - pencil: false, - }; - for depth in [None, Some(SampleType::U8), Some(SampleType::U16), Some(SampleType::F32)] { - let ll = tone_luts_depth(&levels, depth); - let cl = tone_luts_depth(&curves, depth); - for channel in 0..3 { - for index in [0, LUT_SIZE / 4, LUT_SIZE / 2, 3 * LUT_SIZE / 4, LUT_SIZE - 1] { - assert!( - (ll[channel][index] - cl[channel][index]).abs() < 0.01, - "{depth:?} channel {channel} sample {index}: Levels {} vs Curves {}", - ll[channel][index], - cl[channel][index] - ); - } - } - assert!((cl[0][0] - 0.25).abs() < 0.01, "{depth:?}: {}", cl[0][0]); - - // Exercise the compositor's real adjustment path, not only its LUT builder. - for adj in [&levels, &curves] { - let mut pixel = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.0, 0.0, 0.0, 1.0]] }; - apply_depth(adj, &mut pixel, Transfer::Srgb, depth); - for channel in 0..3 { - assert!((pixel.px[0][channel] - 0.25).abs() < 0.01, "{depth:?}: {adj:?} rendered {:?}", pixel.px[0]); - } - } - } - - // Lab has no composite/master tone record. - let mut lab = curves.clone(); - let mut lab_without_master = curves; - if let Adjustment::Curves { space, .. } = &mut lab { - *space = ToneSpace::Lab; - } - if let Adjustment::Curves { master, space, .. } = &mut lab_without_master { - *space = ToneSpace::Lab; - *master = line(0.0, 1.0); - } - assert_eq!(tone_luts(&lab), tone_luts(&lab_without_master)); - } - - #[test] - fn identity_tone_in_every_space_is_identity() { - for space in [ToneSpace::Rgb, ToneSpace::Cmyk, ToneSpace::Lab] { - let mut a = Adjustment::identity_curves(); - if let Adjustment::Curves { space: s, .. } = &mut a { - *s = space; - } - let mut b = ramp(); - apply(&a, &mut b); - for (x, y) in b.px.iter().zip(ramp().px.iter()) { - for k in 0..3 { - assert!((x[k] - y[k]).abs() < 0.02, "{space:?} {x:?} {y:?}"); - } - } - } - } - - #[test] - fn cmyk_black_curve_darkens_and_lab_lightness_lifts() { - let line = |a: f32, b: f32| vec![CurvePoint { input: 0.0, output: a }, CurvePoint { input: 1.0, output: b }]; - // Black brightness 1 -> 0.5: more black ink everywhere. - let a = Adjustment::Curves { - master: line(0.0, 1.0), - per_channel: [line(0.0, 1.0), line(0.0, 1.0), line(0.0, 1.0)], - space: ToneSpace::Cmyk, - black: line(0.0, 0.5), - pencil: false, - }; - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.8, 0.8, 0.8, 1.0]] }; - apply(&a, &mut b); - assert!(b.px[0][0] < 0.7, "{:?}", b.px[0]); - // Lab lightness 0..1 -> 0.2..1 lifts a dark grey; a/b untouched keeps it grey. - let a = Adjustment::Curves { - master: line(1.0, 0.0), // ignored in Lab - per_channel: [line(0.2, 1.0), line(0.0, 1.0), line(0.0, 1.0)], - space: ToneSpace::Lab, - black: Vec::new(), - pencil: false, - }; - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.2, 0.2, 0.2, 1.0]] }; - apply(&a, &mut b); - let p = b.px[0]; - assert!(p[0] > 0.3 && (p[0] - p[2]).abs() < 0.02, "{p:?}"); - } - - #[test] - fn hue_ranges_only_touch_their_colours() { - let mut ranges = HueRange::defaults(); - ranges[0].saturation = -100.0; // desaturate reds - let a = Adjustment::HueSaturation { hue: 0.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges }; - let mut b = Buffer { rect: Rect::new(0, 0, 3, 1), px: vec![[0.9, 0.1, 0.1, 1.0], [0.1, 0.1, 0.9, 1.0], [0.5, 0.5, 0.5, 1.0]] }; - apply(&a, &mut b); - let red = b.px[0]; - assert!((red[0] - red[1]).abs() < 0.05, "red desaturated {red:?}"); - assert!((b.px[1][2] - 0.9).abs() < 1e-4 && (b.px[1][0] - 0.1).abs() < 1e-4, "blue untouched {:?}", b.px[1]); - assert_eq!(b.px[2], [0.5, 0.5, 0.5, 1.0]); - } - - #[test] - fn colorize_at_zero_saturation_is_grey() { - // Photoshop: Colorize at 0% saturation leaves no colour, only the pixel's lightness (#2326). - let px = vec![[0.9, 0.2, 0.1, 1.0], [0.1, 0.6, 0.8, 1.0], [0.5, 0.5, 0.5, 1.0]]; - for depth in [None, Some(SampleType::U8), Some(SampleType::U16), Some(SampleType::F32)] { - for lightness in [0.0, 30.0, -30.0] { - let a = Adjustment::HueSaturation { hue: 200.0, saturation: 0.0, lightness, colorize: true, ranges: HueRange::defaults() }; - let mut b = Buffer { rect: Rect::new(0, 0, 3, 1), px: px.clone() }; - apply_depth(&a, &mut b, Transfer::Srgb, depth); - for p in &b.px { - assert!((p[0] - p[1]).abs() < 1e-4 && (p[1] - p[2]).abs() < 1e-4, "{depth:?} lightness {lightness}: {p:?}"); - } - } - // Low saturations still tint: the old 25% floor no longer hides them. - let tint = |saturation: f32| { - let a = Adjustment::HueSaturation { hue: 0.0, saturation, lightness: 0.0, colorize: true, ranges: HueRange::defaults() }; - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.5, 0.5, 0.5, 1.0]] }; - apply_depth(&a, &mut b, Transfer::Srgb, depth); - b.px[0][0] - b.px[0][2] - }; - assert!(tint(10.0) > 0.05 && tint(10.0) < tint(25.0), "{depth:?}: 10% {} vs 25% {}", tint(10.0), tint(25.0)); - } - } - - /// Photoshop 27.11, measured: Hue/Saturation raising saturation, and Colorize with Lightness. - #[test] - fn hue_saturation_matches_photoshop() { - // (input, hue, saturation, lightness, colorize, Photoshop's output) - type Case = ([u8; 3], f32, f32, f32, bool, [u8; 3]); - let measured: [Case; 8] = [ - ([204, 102, 102], 0.0, 50.0, 0.0, false, [254, 51, 51]), - ([204, 159, 102], 0.0, 50.0, 0.0, false, [254, 164, 51]), - ([204, 102, 102], 0.0, -50.0, 0.0, false, [178, 127, 127]), - ([0, 0, 0], 120.0, 100.0, 30.0, true, [0, 152, 0]), - ([28, 28, 28], 120.0, 100.0, 30.0, true, [0, 192, 0]), - ([160, 160, 160], 30.0, 25.0, -40.0, true, [120, 96, 73]), - ([252, 252, 252], 30.0, 25.0, -40.0, true, [177, 151, 126]), - ([255, 143, 0], 30.0, 25.0, -40.0, true, [95, 76, 58]), - ]; - for (input, hue, saturation, lightness, colorize, want) in measured { - let a = Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges: HueRange::defaults() }; - let c = input.map(|v| v as f32 / 255.0); - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[c[0], c[1], c[2], 1.0]] }; - apply(&a, &mut b); - for (i, w) in want.iter().enumerate() { - let got = b.px[0][i] * 255.0; - assert!((got - *w as f32).abs() <= 2.0, "{input:?} h{hue} s{saturation} l{lightness} colorize {colorize}, channel {i}: {got} vs {w}"); - } - } - } - - /// Photoshop 27.11, measured: a range's Lightness (Blues ±50) moves towards the brightest or darkest channel. - #[test] - fn range_lightness_matches_photoshop() { - let measured = [ - ([0u8, 29, 115], 0.5, [57u8, 71, 115]), - ([0, 64, 255], 0.5, [125, 157, 255]), - ([102, 128, 204], 0.5, [152, 165, 204]), - ([102, 128, 204], -0.5, [102, 115, 154]), - ([0, 18, 115], -0.5, [0, 9, 58]), - ]; - for (input, l, want) in measured { - let got = range_lightness(input.map(|v| v as f32 / 255.0), l); - for i in 0..3 { - assert!((got[i] * 255.0 - want[i] as f32).abs() <= 2.5, "{input:?} channel {i}: {} vs {}", got[i] * 255.0, want[i]); - } - } - } - - /// Photoshop's own render (merged image of psd-tools `adjustments/huesaturation_lightness_rgb.psd`, - /// layer "Hue/Saturation 1"): a dull magenta gets the whole range edit, as a vivid one does (#4089). - #[test] - fn hue_ranges_apply_in_full_to_dull_colours() { - let range = |lightness: f32, bounds: [f32; 4]| HueRange { hue: 0.0, saturation: 0.0, lightness, bounds }; - let ranges = [ - range(-11.0, [-57.0, 4.0, 82.0, 175.0]), - range(100.0, [12.0, 45.0, 75.0, 105.0]), - HueRange::neutral(2), - HueRange::neutral(3), - HueRange::neutral(4), - range(100.0, [-117.0, -50.0, 39.0, 104.0]), - ]; - let a = Adjustment::HueSaturation { hue: 0.0, saturation: 0.0, lightness: 17.0, colorize: false, ranges }; - let measured = [([126u8, 97, 120], [148u8, 148, 148]), ([131, 103, 125], [152, 152, 152]), ([95, 69, 90], [122, 122, 122])]; - for (input, want) in measured { - let c = input.map(|v| v as f32 / 255.0); - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[c[0], c[1], c[2], 1.0]] }; - apply(&a, &mut b); - for (i, w) in want.iter().enumerate() { - let got = b.px[0][i] * 255.0; - assert!((got - *w as f32).abs() <= 2.0, "{input:?} channel {i}: {got} vs {w}"); - } - } - // Greys have no hue, so the ranges leave them alone: only the master Lightness moves them. - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.4, 0.4, 0.4, 1.0]] }; - apply(&a, &mut b); - let p = b.px[0]; - assert!((p[0] - p[1]).abs() < 1e-6 && (p[1] - p[2]).abs() < 1e-6 && (p[0] - (0.4 + 0.6 * 0.17)).abs() < 1e-4, "{p:?}"); - } - - #[test] - fn black_white_weights() { - let d = [40.0, 60.0, 40.0, 60.0, 20.0, 80.0]; - assert!((black_white_gray([0.5; 3], &d) - 0.5).abs() < 1e-6, "greys keep their value"); - assert!((black_white_gray([1.0, 0.0, 0.0], &d) - 0.4).abs() < 1e-6); - assert!((black_white_gray([1.0, 1.0, 0.0], &d) - 0.6).abs() < 1e-6); - let mut w = d; - w[0] = 100.0; - assert!(black_white_gray([1.0, 0.0, 0.0], &w) > black_white_gray([1.0, 0.0, 0.0], &d)); - } - - /// #8537: 32-bit superwhites stay above 1 (Photoshop 27.11: 2.0 stays 2.0, neutrals cap at - /// 16, negatives go to 0); 8-bit still clips at 1. - #[test] - fn black_white_keeps_32_bit_superwhites() { - let adj = Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None }; - let run = |depth, c: f32| { - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[c, c, c, 1.0]] }; - apply_depth(&adj, &mut b, Transfer::Srgb, Some(depth)); - b.px[0][0] - }; - assert_eq!(run(SampleType::F32, 2.0), 2.0); - assert_eq!(run(SampleType::F32, 20.0), 16.0); - assert_eq!(run(SampleType::F32, -0.5), 0.0); - assert_eq!(run(SampleType::U8, 2.0), 1.0); - } - - /// Photoshop 27.11, measured: Black & White (default weights) with Tint over greys. The tint - /// is blended like the Color blend mode: its hue and saturation at the grey's luminosity. - #[test] - fn black_white_tint_matches_photoshop() { - let weights = [40.0, 60.0, 40.0, 60.0, 20.0, 80.0]; - let measured: [([u8; 3], u8, [u8; 3]); 6] = [ - ([255, 0, 0], 24, [81, 1, 1]), - ([255, 0, 0], 120, [255, 64, 64]), - ([255, 0, 0], 240, [255, 235, 235]), - ([0xe1, 0xd3, 0xb3], 120, [133, 119, 87]), - ([0xe1, 0xd3, 0xb3], 24, [33, 24, 1]), - ([0x40, 0x20, 0x10], 120, [144, 112, 96]), - ]; - for (tint, grey, want) in measured { - let tint = Some(tint.map(|v| v as f32 / 255.0)); - let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[grey as f32 / 255.0; 4]] }; - b.px[0][3] = 1.0; - apply(&Adjustment::BlackWhite { weights, tint }, &mut b); - for (i, w) in want.iter().enumerate() { - let got = b.px[0][i] * 255.0; - assert!((got - *w as f32).abs() <= 2.5, "tint {tint:?} grey {grey} channel {i}: {got} vs {w}"); - } - } - } - - #[test] - fn gradient_map_follows_the_w3c_luminosity() { - // Photoshop's Gradient Map is driven by 0.3 R + 0.59 G + 0.11 B (photoshop corpus rgb8 and - // rgb16 gradient-map.psd), not the Rec. 601 grey. - let stops = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]; - for (c, t) in [([0.0, 1.0, 0.0], 0.59), ([1.0, 0.0, 0.0], 0.3), ([0.0, 0.0, 1.0], 0.11), ([0.2, 0.6, 0.9], 0.513)] { - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); - apply(&Adjustment::GradientMap { stops: stops.clone(), reverse: false, dither: false }, &mut b); - assert!((b.px[0][0] - t).abs() < 1e-5, "{c:?}: {}", b.px[0][0]); - } - } - - #[test] - fn gradient_map_dither_stays_close() { - let stops = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]; - let mut a = ramp(); - let mut b = ramp(); - apply(&Adjustment::GradientMap { stops: stops.clone(), reverse: false, dither: false }, &mut a); - apply(&Adjustment::GradientMap { stops, reverse: false, dither: true }, &mut b); - assert!(a.px.iter().zip(&b.px).all(|(x, y)| (x[0] - y[0]).abs() <= 0.5 / 255.0 + 1e-6)); - assert!(a.px.iter().zip(&b.px).any(|(x, y)| x[0] != y[0])); - } - - /// `adj` applied in a Lab document to one encoded sRGB colour, returned as (L, a, b). - fn in_lab(adj: &Adjustment, c: [f32; 3]) -> [f32; 3] { - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); - apply_in(adj, &mut b, Transfer::Srgb, Some(SampleType::U8), ColorMode::Lab); - srgb_to_lab([b.px[0][0], b.px[0][1], b.px[0][2]]) - } - - /// A muted, in-gamut colour from (L, a, b). - fn lab(l: f32, a: f32, b: f32) -> [f32; 3] { - lab_to_srgb([l, a, b]) - } - - fn near(got: [f32; 3], want: [f32; 3], tol: f32) -> bool { - got.iter().zip(want).all(|(g, w)| (g - w).abs() <= tol) - } - - #[test] - fn lab_invert_flips_l_a_and_b() { - let got = in_lab(&Adjustment::Invert, lab(30.0, 12.0, -18.0)); - // n -> 1 - n: L -> 100 - L, a -> -a - 1, b -> -b - 1 (mirrored on the 0..255 grid). - assert!(near(got, [70.0, -13.0, 17.0], 0.6), "{got:?}"); - // On the screen colour it would not be a mirror in Lab. - let mut rgb = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [0.0, 0.0, 0.0, 1.0]); - let c = lab(30.0, 12.0, -18.0); - rgb.px[0] = [c[0], c[1], c[2], 1.0]; - apply(&Adjustment::Invert, &mut rgb); - assert!(!near(srgb_to_lab([rgb.px[0][0], rgb.px[0][1], rgb.px[0][2]]), got, 1.0)); - } - - #[test] - fn sixteen_bit_lab_invert_keeps_greys_neutral() { - // 16-bit Lab Invert mirrors a and b around neutral (photoshop corpus lab16 invert.psd); - // 8-bit bytes land one step off it. - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [0.0, 0.0, 0.0, 1.0]); - let c = lab(40.0, 0.0, 0.0); - b.px[0] = [c[0], c[1], c[2], 1.0]; - apply_in(&Adjustment::Invert, &mut b, Transfer::Srgb, Some(SampleType::U16), ColorMode::Lab); - let got = srgb_to_lab([b.px[0][0], b.px[0][1], b.px[0][2]]); - assert!(near(got, [60.0, 0.0, 0.0], 0.05), "{got:?}"); - assert!(near(in_lab(&Adjustment::Invert, c), [60.0, -1.0, -1.0], 0.1)); - } - - /// `adj` applied in a CMYK document to one encoded sRGB colour. - fn in_cmyk(adj: &Adjustment, c: [f32; 3]) -> [f32; 3] { - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); - apply_in(adj, &mut b, Transfer::Srgb, Some(SampleType::U8), ColorMode::Cmyk); - [b.px[0][0], b.px[0][1], b.px[0][2]] - } - - #[test] - fn cmyk_invert_posterize_and_threshold_work_on_the_inks() { - use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk}; - // Paper inverts to all four inks at 100%, not to RGB black (photoshop corpus cmyk8 invert.psd). - assert!(near(in_cmyk(&Adjustment::Invert, [1.0; 3]), cmyk_to_rgb([1.0; 4]), 2e-3)); - let red = [0.9, 0.2, 0.1]; - assert!(near(in_cmyk(&Adjustment::Invert, red), cmyk_to_rgb(rgb_to_cmyk(red).map(|v| 1.0 - v)), 2e-3)); - let two = cmyk_to_rgb(rgb_to_cmyk(red).map(|v| if v >= 0.5 { 1.0 } else { 0.0 })); - assert!(near(in_cmyk(&Adjustment::Posterize { levels: 2 }, red), two, 2e-3)); - // Threshold's black is the black ink alone (threshold-128.psd), its white the paper. - let t = Adjustment::Threshold { level: 0.5 }; - assert!(near(in_cmyk(&t, [0.2; 3]), cmyk_to_rgb([0.0, 0.0, 0.0, 1.0]), 2e-3)); - assert!(near(in_cmyk(&t, [0.8; 3]), cmyk_to_rgb([0.0; 4]), 2e-3)); - } - - /// CMYK posterizes the stored value 1 - ink: with 3 levels an ink of 85 (stored 170) lands on - /// the middle step, 128 (stored 127), where posterizing the ink would drop it to none (psd-tools - /// posterize_cmyk.psd, levels 3 to 21, exact so). - #[test] - fn cmyk_posterize_works_on_the_stored_values() { - let mut ink = [85.0 / 255.0; 4]; - stored_channels(&Adjustment::Posterize { levels: 3 }, ColorMode::Cmyk, Some(SampleType::U8), &mut ink); - assert!(ink.iter().all(|v| (v * 255.0 - 128.0).abs() < 1e-3), "{ink:?}"); - assert_eq!(posterize(85.0 / 255.0, 3), 0.0, "posterizing the ink itself"); - } - - #[test] - fn cmyk_threshold_compares_the_inks_plain_luma() { - assert_eq!(ink_luma([0.0; 4]), 1.0); - assert_eq!(ink_luma([0.0, 0.0, 0.0, 1.0]), 0.0); - // Two greys either side of level 128 in photoshop corpus cmyk8 threshold-128.psd: black, - // then white (8-bit inks). - let at = |i: [f32; 4]| { - let mut ch = i.map(|v| v / 255.0); - stored_channels(&Adjustment::Threshold { level: 128.0 / 255.0 }, ColorMode::Cmyk, Some(SampleType::U8), &mut ch); - ch - }; - assert_eq!(at([144.0, 122.0, 121.0, 35.0]), [0.0, 0.0, 0.0, 1.0]); - assert_eq!(at([131.0, 110.0, 110.0, 19.0]), [0.0; 4]); - } - - #[test] - fn cmyk_brightness_contrast_curves_each_ink_from_paper() { - use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk}; - // The tone curve runs on each ink's stored value, 1 - ink (photoshop corpus cmyk8 - // brightness-contrast.psd and -legacy.psd): raising brightness takes ink away, and paper - // and solid ink stay put. - let red = [0.9, 0.2, 0.1]; - for legacy in [false, true] { - let adj = Adjustment::BrightnessContrast { brightness: 25.0, contrast: 30.0, legacy }; - let table = ink_brightness_contrast_lut(25.0, 30.0, legacy); - let want = cmyk_to_rgb(rgb_to_cmyk(red).map(|v| 1.0 - lut(&table, 1.0 - v))); - assert!(near(in_cmyk(&adj, red), want, 2e-3), "legacy {legacy}"); - assert!(near(in_cmyk(&adj, [1.0; 3]), [1.0; 3], 2e-3), "legacy {legacy}: paper"); - let solid = cmyk_to_rgb([1.0; 4]); - assert!(near(in_cmyk(&adj, solid), cmyk_to_rgb(rgb_to_cmyk(solid).map(|v| ink_through(&table, v))), 2e-3)); - } - // Legacy +25 / +30 on Photoshop's own 16-bit inks (photoshop corpus cmyk16 - // brightness-contrast-legacy.psd): contrast pivots at 128 in ink, 127 stored. - let legacy = ink_brightness_contrast_lut(25.0, 30.0, true); - for (ink, ps) in [(139.0, 108.0), (160.0, 137.99), (172.0, 155.13), (183.0, 170.85), (196.0, 189.42), (98.0, 49.42), (128.0, 92.28), (168.0, 149.42)] { - let got = ink_through(&legacy, ink / 255.0) * 255.0; - assert!((got - ps).abs() < 0.1, "ink {ink}: {got} vs Photoshop {ps}"); - } - let brighter = Adjustment::BrightnessContrast { brightness: 60.0, contrast: 0.0, legacy: false }; - let ink = ink_brightness_contrast_lut(60.0, 0.0, false); - assert!(ink_through(&ink, 0.5) < 0.5 && ink_through(&ink, 0.0) == 0.0 && (ink_through(&ink, 1.0) - 1.0).abs() < 1e-6); - // On the screen colour it would land elsewhere. - let mut rgb = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [red[0], red[1], red[2], 1.0]); - apply(&brighter, &mut rgb); - assert!(!near(in_cmyk(&brighter, red), [rgb.px[0][0], rgb.px[0][1], rgb.px[0][2]], 0.01)); - } - - #[test] - fn lab_posterize_steps_l_a_and_b() { - let got = in_lab(&Adjustment::Posterize { levels: 2 }, lab(70.0, 20.0, -30.0)); - // Two levels: each normalised channel snaps to 0 or 1 (L 100, a and b at +127 / -128). - assert!(near(got, srgb_to_lab(lab_denorm([1.0, 1.0, 0.0])), 1e-3), "{got:?}"); - let grey = in_lab(&Adjustment::Posterize { levels: 255 }, lab(50.0, 0.0, 0.0)); - assert!(near(grey, [50.0, 0.0, 0.0], 1.1), "255 levels is within a step of the identity: {grey:?}"); - } - - #[test] - fn lab_threshold_splits_on_l_with_a_neutral_result() { - let t = Adjustment::Threshold { level: 0.5 }; - // A saturated blue (L ≈ 32) and yellow (L ≈ 97): black and white, nothing in between. - for (c, white) in [([0.0, 0.0, 1.0], false), ([1.0, 1.0, 0.0], true), (lab(52.0, 40.0, 30.0), true), (lab(48.0, -40.0, 30.0), false)] { - let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); - apply_in(&t, &mut b, Transfer::Srgb, None, ColorMode::Lab); - let v = if white { 1.0 } else { 0.0 }; - assert_eq!(b.px[0], [v, v, v, 1.0], "{c:?}"); - } - } - - #[test] - fn lab_brightness_contrast_moves_l_only() { - for legacy in [false, true] { - let adj = Adjustment::BrightnessContrast { brightness: 40.0, contrast: 30.0, legacy }; - let before = [45.0, 15.0, -20.0]; - let got = in_lab(&adj, lab(before[0], before[1], before[2])); - assert!(got[0] > before[0] + 5.0, "{legacy}: L rises: {got:?}"); - assert!((got[1] - before[1]).abs() < 0.5 && (got[2] - before[2]).abs() < 0.5, "{legacy}: a, b kept: {got:?}"); - } - } - - #[test] - fn lab_gradient_map_follows_l() { - let stops = vec![(0.0, [1.0, 0.0, 0.0]), (1.0, [0.0, 0.0, 1.0])]; - for reverse in [false, true] { - let map = Adjustment::GradientMap { stops: stops.clone(), reverse, dither: false }; - // A grey and a saturated colour with the same L map to the same colour. - let grey = in_lab(&map, lab(60.0, 0.0, 0.0)); - let green = in_lab(&map, lab(60.0, -50.0, 40.0)); - assert!(near(grey, green, 1e-3), "{reverse}: {grey:?} vs {green:?}"); - let t = if reverse { 0.4 } else { 0.6 }; - let want = srgb_to_lab([1.0 - t, 0.0, t]); - assert!(near(grey, want, 0.05), "{reverse}: {grey:?} vs {want:?}"); - } - } - - #[test] - fn other_modes_and_adjustments_keep_the_screen_colour_path() { - let c = [0.2, 0.5, 0.7, 1.0]; - let lab_only = [Adjustment::Invert, Adjustment::Threshold { level: 0.47 }, Adjustment::Posterize { levels: 4 }]; - for adj in - lab_only.iter().chain([&Adjustment::HueSaturation { hue: 30.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }]) - { - for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Grayscale, ColorMode::Lab] { - let (mut a, mut b) = (Buffer::filled(crate::Rect::new(0, 0, 1, 1), c), Buffer::filled(crate::Rect::new(0, 0, 1, 1), c)); - apply_in(adj, &mut a, Transfer::Srgb, None, mode); - apply_depth(adj, &mut b, Transfer::Srgb, None); - let own = (mode == ColorMode::Lab && lab_channel_adjustment(adj)) || (mode == ColorMode::Cmyk && cmyk_channel_adjustment(adj)); - assert_eq!(a.px == b.px, !own, "{adj:?} in {mode:?}"); - } - } - // Transparent pixels are left alone and odd values never panic. - let mut t = Buffer::filled(crate::Rect::new(0, 0, 2, 1), [f32::NAN, 2.0, -1.0, 0.0]); - for adj in lab_only.iter().chain([&Adjustment::GradientMap { stops: vec![], reverse: true, dither: true }]) { - for mode in [ColorMode::Lab, ColorMode::Cmyk] { - apply_in(adj, &mut t, Transfer::Srgb, None, mode); - let mut odd = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [f32::NAN, f32::INFINITY, -3.0, 1.0]); - apply_in(adj, &mut odd, Transfer::Srgb, Some(SampleType::U16), mode); - } - } - assert!(t.px[0][1] == 2.0); - } -} +mod tone_tests; /// Legacy Brightness/Contrast scales contrast around 128 of 255 (contrast 80 keeps 128 at 128, /// measured on Photoshop 27.11; a 0.5 pivot moved it to 130). diff --git a/crates/compose/src/adjust/tone_tests.rs b/crates/compose/src/adjust/tone_tests.rs new file mode 100644 index 0000000000..99b20e9096 --- /dev/null +++ b/crates/compose/src/adjust/tone_tests.rs @@ -0,0 +1,884 @@ +use super::*; +use photocraft_geom::Rect; + +fn ramp() -> Buffer { + let rect = Rect::new(0, 0, 8, 8); + let px = (0..64).map(|i| [((i % 8) as f32) / 7.0, ((i / 8) as f32) / 7.0, 0.3, 1.0]).collect(); + Buffer { rect, px } +} + +/// Photoshop 27.11, measured: Brightness/Contrast with Use Legacy on, over a gray ramp +/// (x = 0, 16, …, 240, 255), one row per (brightness, contrast). +/// One pixel through `adj` in a 32-bit document. +fn hdr(adj: &Adjustment, c: [f32; 3]) -> [f32; 3] { + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); + apply_depth(adj, &mut b, Transfer::Gamma(1.0), Some(SampleType::F32)); + [b.px[0][0], b.px[0][1], b.px[0][2]] +} + +/// Photoshop's 32-bit Hue/Saturation (photoshop corpus rgb32 hue-saturation.psd: hue +40, +/// saturation +25, lightness -10): saturated colours leave 0..1, and the saturation factor is +/// 1 / (1 - 63/255), so red becomes (1.0477, 0.649, -0.1477), where 8 bits clip to (0.9, 0.6, 0). +#[test] +fn thirty_two_bit_hue_saturation_is_unclipped() { + let adj = Adjustment::HueSaturation { hue: 40.0, saturation: 25.0, lightness: -10.0, colorize: false, ranges: HueRange::defaults() }; + let near = |got: [f32; 3], want: [f32; 3]| got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3); + for (c, want) in + [([1.0, 0.0, 0.0], [1.0477, 0.649, -0.1477]), ([0.9301, 0.6105, 0.2541], [0.7804, 0.9369, 0.1289]), ([0.0, 0.3864, 1.0], [0.1871, -0.1477, 1.0477])] + { + assert!(near(hdr(&adj, c), want), "{c:?}: {:?}", hdr(&adj, c)); + } + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [1.0, 0.0, 0.0, 1.0]); + apply_depth(&adj, &mut b, Transfer::Srgb, Some(SampleType::U16)); + assert!(b.px[0].iter().all(|v| (0.0..=1.0).contains(v)), "16 bits clip: {:?}", b.px[0]); +} + +/// Photoshop's 32-bit Colorize (photoshop corpus rgb32 hue-saturation-colorize.psd: hue -160, +/// saturation 40, lightness +5): red becomes (0.3445, 0.5852, 0.7055), 0.95 of the chroma an +/// 8-bit Colorize gives at the same lightness, (0.335, 0.5883, 0.715). +#[test] +fn thirty_two_bit_colorize_scales_the_saturation() { + let adj = Adjustment::HueSaturation { hue: -160.0, saturation: 40.0, lightness: 5.0, colorize: true, ranges: HueRange::defaults() }; + let near = |got: [f32; 3], want: [f32; 3]| got.iter().zip(want).all(|(g, w)| (g - w).abs() < 2e-3); + let red = hdr(&adj, [1.0, 0.0, 0.0]); + assert!(near(red, [0.3445, 0.5852, 0.7055]), "{red:?}"); + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [1.0, 0.0, 0.0, 1.0]); + apply_depth(&adj, &mut b, Transfer::Srgb, Some(SampleType::U16)); + assert!(near([b.px[0][0], b.px[0][1], b.px[0][2]], [0.335, 0.5883, 0.715]), "16-bit keeps the full saturation: {:?}", b.px[0]); +} + +/// Photoshop's 32-bit saturation factor (Hue/Saturation on red (1, 0, 0) in a 32-bit document, +/// read back from the saved float TIFF, exact in 1/512): red's R is 0.5 + 0.5 x the factor. +#[test] +fn thirty_two_bit_saturation_steps_match_photoshop() { + for (sat, want) in [ + (10.0, 539.0 / 512.0), + (75.0, 2.4609375), + (90.0, 2673.0 / 512.0), + (99.0, 32.375), + (100.0, 33023.0 / 512.0), + (-10.0, 487.0 / 512.0), + (-25.0, 0.875), + (-50.0, 0.75), + (-100.0, 0.5), + ] { + let adj = Adjustment::HueSaturation { hue: 0.0, saturation: sat, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; + let got = hdr(&adj, [1.0, 0.0, 0.0])[0]; + assert!((got - want).abs() < 1e-4, "saturation {sat}: {got}, Photoshop {want}"); + } +} + +/// 32-bit colours at or above HSL lightness 1 (red at +1 stop, (2, 0, 0)) keep their hue and +/// get their chroma scaled like any other, as in Photoshop; they used to turn NaN or grey. +#[test] +fn thirty_two_bit_hue_saturation_keeps_bright_colours() { + let pale = [280.0 / 255.0, 230.0 / 255.0, 256.0 / 255.0]; + let near = |got: [f32; 3], want: [f32; 3]| got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1e-3 * w.abs().max(1.0)); + for (hue, sat, c, want) in [ + (40.0, 0.0, [2.0, 0.0, 0.0], [2.0, 1.33301, 0.0]), + (40.0, 0.0, pale, [1.09804, 0.930687, 0.901961]), + (0.0, 25.0, [2.0, 0.0, 0.0], [2.32812, -0.328125, -0.328125]), + (0.0, 25.0, pale, [1.13021, 0.869792, 1.00521]), + (0.0, -25.0, [2.0, 0.0, 0.0], [1.75, 0.25, 0.25]), + (0.0, 100.0, [140.0 / 255.0, 115.0 / 255.0, 128.0 / 255.0], [6.77432, -5.77432, 0.750976]), + (0.0, 100.0, [2.0, 0.0, 0.0], [128.996, -126.996, -126.996]), + ] { + let adj = Adjustment::HueSaturation { hue, saturation: sat, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; + let got = hdr(&adj, c); + assert!(near(got, want), "hue {hue}, saturation {sat}, {c:?}: {got:?}, Photoshop {want:?}"); + } + // A master plus a range edit that add up to a whole step stay on it: Reds +96 over a master + // -46 scales red as much as a master +50 alone (in f32 the sum is 0.49999997). + let mut ranges = HueRange::defaults(); + ranges[0].saturation = 96.0; + let summed = Adjustment::HueSaturation { hue: 0.0, saturation: -46.0, lightness: 0.0, colorize: false, ranges }; + let single = Adjustment::HueSaturation { hue: 0.0, saturation: 50.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; + assert_eq!(hdr(&summed, [1.0, 0.0, 0.0]), hdr(&single, [1.0, 0.0, 0.0])); + // Lightness 0 with a negative channel divides by zero the same way. + let adj = Adjustment::HueSaturation { hue: 40.0, saturation: 25.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }; + assert!(hdr(&adj, [0.25, -0.25, 0.0]).iter().all(|v| v.is_finite())); +} + +/// Photoshop's own 32-bit results (photoshop corpus rgb32): nothing clips, legacy contrast +/// pivots at 127, the mixer cuts its percentages to 1/1024 and counts 255/512 of the +/// constant, and the Black & White tint keeps values above 1. +#[test] +fn thirty_two_bit_adjustments_match_photoshop_unclipped() { + let near = |got: [f32; 3], want: [f32; 3], tol: f32| got.iter().zip(want).all(|(g, w)| (g - w).abs() <= tol); + let bc = Adjustment::BrightnessContrast { brightness: 25.0, contrast: 30.0, legacy: true }; + // brightness-contrast-legacy.psd + assert!(near(hdr(&bc, [0.4910, 0.0009, 0.9301]), [0.6280, -0.0721, 1.2553], 2e-4), "{:?}", hdr(&bc, [0.4910, 0.0009, 0.9301])); + // channel-mixer.psd: pure red, green, blue and black, exactly. + let mixer = Adjustment::ChannelMixer { matrix: [[0.8, 0.3, -0.1, 0.0], [0.1, 0.9, 0.0, 0.05], [0.0, 0.2, 0.7, 0.0]], monochrome: false }; + for (c, want) in [ + ([1.0, 0.0, 0.0], [0.7998047, 0.1245117, 0.0]), + ([0.0, 1.0, 0.0], [0.2998047, 0.9243164, 0.1992188]), + ([0.0, 0.0, 1.0], [-0.0996094, 0.0249023, 0.6992188]), + ([0.0, 0.0, 0.0], [0.0, 0.0249023, 0.0]), + ] { + assert!(near(hdr(&mixer, c), want, 1e-6), "{c:?}: {:?}", hdr(&mixer, c)); + } + // black-white-tint.psd: white tints past 1. + let bw = Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: Some([0.88235295, 0.827451, 0.7019608]) }; + assert!(near(hdr(&bw, [1.0; 3]), [1.0522, 0.9973, 0.8718], 2e-4), "{:?}", hdr(&bw, [1.0; 3])); + // 8/16-bit documents still clip. + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [1.0, 1.0, 1.0, 1.0]); + apply_depth(&bw, &mut b, Transfer::Srgb, None); + assert!(b.px[0].iter().all(|v| *v <= 1.0)); +} + +#[test] +fn legacy_brightness_contrast_matches_photoshop() { + const X: [u8; 17] = [0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 255]; + let measured: [(f32, f32, [u8; 17]); 7] = [ + (40.0, 0.0, [40, 56, 72, 88, 104, 120, 136, 152, 168, 184, 200, 216, 232, 248, 255, 255, 255]), + (-40.0, 0.0, [0, 0, 0, 8, 24, 40, 56, 72, 88, 104, 120, 136, 152, 168, 184, 200, 215]), + (0.0, 30.0, [0, 0, 0, 14, 37, 60, 82, 105, 128, 151, 174, 196, 219, 242, 255, 255, 255]), + (0.0, -30.0, [38, 49, 61, 72, 83, 94, 106, 117, 128, 139, 150, 162, 173, 184, 195, 207, 217]), + (40.0, 30.0, [3, 25, 48, 71, 94, 117, 139, 162, 185, 208, 231, 253, 255, 255, 255, 255, 255]), + (100.0, 0.0, [100, 116, 132, 148, 164, 180, 196, 212, 228, 244, 255, 255, 255, 255, 255, 255, 255]), + (0.0, 80.0, [0, 0, 0, 0, 0, 0, 0, 48, 128, 208, 255, 255, 255, 255, 255, 255, 255]), + ]; + for (brightness, contrast, want) in measured { + let rect = Rect::new(0, 0, 17, 1); + let px = X.iter().map(|x| [f32::from(*x) / 255.0; 4]).map(|p| [p[0], p[1], p[2], 1.0]).collect(); + let mut b = Buffer { rect, px }; + apply(&Adjustment::BrightnessContrast { brightness, contrast, legacy: true }, &mut b); + for (i, (p, w)) in b.px.iter().zip(want).enumerate() { + let got = (p[0] * 255.0).round() as i32; + assert!((got - i32::from(w)).abs() <= 1, "b {brightness} c {contrast} at {}: {got} vs Photoshop {w}", X[i]); + } + } +} + +/// Pixel → Photoshop's split. 8-bit from psd-tools threshold_rgb.psd: the first three are +/// white though their Rec. 601 grey rounds below 60, and (131, 109, 99) sits exactly on 114.5 +/// at level 115 (halves round down). 16-bit from threshold_16bits_rgb.psd and the photoshop +/// corpus's rgb16 threshold-128.psd, whose mid grey 16448 is level 128 in 16 bits. +#[test] +fn threshold_splits_on_the_luminosity_like_photoshop() { + let c8 = |r: u8, g: u8, b: u8| [r, g, b].map(|v| f32::from(v) / 255.0); + for (c, level, white) in + [(c8(87, 51, 31), 60u8, true), (c8(90, 49, 33), 60, true), (c8(68, 57, 50), 60, true), (c8(48, 63, 72), 60, false), (c8(131, 109, 99), 115, false)] + { + assert_eq!(threshold_white(c, f32::from(level) / 255.0, Some(SampleType::U8)), white, "8-bit {c:?} at {level}"); + } + let c16 = |r: u16, g: u16, b: u16| [r, g, b].map(|v| f32::from(v) / 32768.0); + for (c, level, white) in [ + (c16(8995, 7196, 6425), 60u8, false), + (c16(11180, 6554, 3984), 60, false), + (c16(16448, 16448, 16448), 128, true), + (c16(16447, 16447, 16447), 128, false), + ] { + assert_eq!(threshold_white(c, f32::from(level) / 255.0, Some(SampleType::U16)), white, "16-bit {c:?} at {level}"); + } + // Through the adjustment: neutral black or white. + let mut b = Buffer::filled(Rect::new(0, 0, 1, 1), [87.0 / 255.0, 51.0 / 255.0, 31.0 / 255.0, 1.0]); + apply_depth(&Adjustment::Threshold { level: 60.0 / 255.0 }, &mut b, Transfer::Srgb, Some(SampleType::U8)); + assert_eq!(b.px[0], [1.0, 1.0, 1.0, 1.0]); +} + +/// 16-bit sample → Photoshop's 8-bit level, from psd-tools posterize_16bits_rgb.psd: bins +/// split on the 16-bit sample (10794 and 10923 straddle a third of 32768), and the middle of 3 +/// levels is 128 where 8 bits give 127, while 21 levels keep 25 for 25.5. +#[test] +fn sixteen_bit_posterize_matches_photoshop() { + let points: [(u32, u16, u8); 9] = + [(3, 10794, 0), (3, 10923, 128), (3, 21845, 128), (3, 21974, 255), (13, 2504, 0), (13, 2542, 21), (13, 7453, 42), (13, 7582, 64), (21, 3341, 25)]; + for (levels, x, want) in points { + let got = posterize_in(f32::from(x) / 32768.0, levels, Some(SampleType::U16)); + assert!((got * 255.0 - f32::from(want)).abs() < 1e-3, "{levels} levels at {x}: {} vs Photoshop {want}", got * 255.0); + } + // 8 bits keep their rule. + assert_eq!(posterize_in(128.0 / 255.0, 3, Some(SampleType::U8)), posterize(128.0 / 255.0, 3)); +} + +#[test] +fn color_lookup_with_an_overflowing_stored_size_is_the_identity() { + // A stored document's size is untrusted: (2²²)³ × 3 overflows, which once wrapped past + // the table-length guard and indexed out of bounds. + for size in [1 << 22, u32::MAX] { + let a = Adjustment::ColorLookup { name: "x".into(), lut: Some(std::sync::Arc::new(vec![0.5; 24])), size, tetrahedral: false, dither: false }; + let mut b = ramp(); + apply(&a, &mut b); + assert_eq!(b.px, ramp().px, "size {size}"); + } +} + +/// Photoshop 27.11, measured: Color Balance with one cyan–red slider moved, over a gray ramp +/// (x = 0, 16, …, 240, 255); red and green out (blue follows green on gray). +#[test] +fn color_balance_matches_photoshop() { + const X: [u8; 17] = [0, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 255]; + type Row = (&'static str, f32, bool, [u8; 17], [u8; 17]); + let measured: [Row; 6] = [ + ("midtones", 50.0, false, [0, 36, 59, 78, 96, 112, 128, 142, 156, 170, 183, 196, 209, 221, 233, 244, 255], X), + ("shadows", -100.0, false, [0, 0, 0, 0, 0, 0, 0, 7, 23, 43, 67, 93, 122, 154, 186, 221, 255], X), + ("highlights", 100.0, false, [0, 51, 84, 111, 136, 160, 182, 202, 223, 242, 255, 255, 255, 255, 255, 255, 255], X), + ("shadows", 50.0, true, X, [0, 0, 0, 0, 17, 37, 57, 77, 97, 117, 137, 157, 177, 197, 216, 236, 255]), + ( + "midtones", + 100.0, + true, + [0, 36, 59, 78, 96, 112, 128, 142, 156, 170, 183, 196, 209, 221, 233, 244, 255], + [0, 5, 14, 24, 36, 50, 64, 80, 97, 114, 132, 151, 171, 191, 212, 234, 255], + ), + ("highlights", -100.0, true, X, [0, 26, 53, 79, 105, 132, 158, 184, 211, 237, 255, 255, 255, 255, 255, 255, 255]), + ]; + // Two sliders in one tone, Preserve Luminosity on (measured): shadows red and blue +50 darken + // only green; highlights red −50 with green +50 lift green by 100 and blue by 50. + let two = + |tones: [[f32; 3]; 3], x: f32| -> [i32; 3] { std::array::from_fn(|ch| (color_balance_channel(tones, true, ch, x / 255.0) * 255.0).round() as i32) }; + assert_eq!(two([[50.0, 0.0, 50.0], [0.0; 3], [0.0; 3]], 128.0), [128, 97, 128]); + let hi = two([[0.0; 3], [0.0; 3], [-50.0, 50.0, 0.0]], 128.0); + assert!((hi[0] - 128).abs() <= 1 && (hi[1] - 211).abs() <= 1 && (hi[2] - 159).abs() <= 1, "{hi:?}"); + for (tone, amount, preserve, red, green) in measured { + let mut tones = [[0.0f32; 3]; 3]; + tones[["shadows", "midtones", "highlights"].iter().position(|t| *t == tone).unwrap()][0] = amount; + for (i, x) in X.iter().enumerate() { + let v = f32::from(*x) / 255.0; + let got = |ch| (color_balance_channel(tones, preserve, ch, v) * 255.0).round() as i32; + let (r, g) = (got(0), got(1)); + assert!((r - i32::from(red[i])).abs() <= 1, "{tone} {amount} pl {preserve} at {x}: red {r} vs Photoshop {}", red[i]); + assert!((g - i32::from(green[i])).abs() <= 1, "{tone} {amount} pl {preserve} at {x}: green {g} vs Photoshop {}", green[i]); + } + } +} + +/// Photoshop, measured (8-bit gray ramp, every channel): whole settings, where the tones fold +/// into one Levels per channel (#3423). The issue's midtones red +100 / magenta −100 (the +/// shadow toe), its sequoia14 layer with Preserve Luminosity off and on, all nine sliders with +/// Preserve Luminosity on, a black point past the white point, and lowered shadows with raised +/// highlights (their gammas cancel: a straight line between the two points). +#[test] +fn color_balance_whole_settings_match_photoshop() { + const X: [u8; 12] = [0, 4, 8, 16, 32, 64, 96, 128, 160, 192, 224, 255]; + type Case = ([[f32; 3]; 3], bool, [[u8; 12]; 3]); + let cases: [Case; 6] = [ + ( + [[0.0; 3], [100.0, -100.0, 0.0], [0.0; 3]], + false, + [[0, 16, 30, 55, 90, 128, 156, 181, 202, 221, 239, 255], [0, 0, 0, 1, 4, 16, 36, 64, 100, 145, 197, 255], X], + ), + ( + [[-6.0, 22.0, 5.0], [-1.0, -3.0, -8.0], [-1.0, -4.0, -6.0]], + false, + [ + [0, 0, 2, 9, 25, 56, 89, 122, 156, 188, 222, 255], + [0, 5, 9, 18, 35, 67, 100, 131, 163, 194, 225, 255], + [0, 3, 7, 14, 29, 60, 91, 123, 156, 189, 222, 255], + ], + ), + ( + [[-6.0, 22.0, 5.0], [-1.0, -3.0, -8.0], [-1.0, -4.0, -6.0]], + true, + [ + [0, 0, 0, 0, 5, 42, 80, 117, 154, 189, 226, 255], + [0, 4, 8, 16, 33, 66, 98, 130, 162, 195, 226, 255], + [0, 0, 0, 0, 15, 48, 82, 116, 151, 186, 221, 255], + ], + ), + ( + [[40.0, -30.0, 20.0], [-50.0, 25.0, 60.0], [30.0, -70.0, 10.0]], + true, + [ + [0, 1, 3, 9, 25, 69, 126, 193, 255, 255, 255, 255], + [0, 0, 0, 0, 0, 0, 46, 93, 136, 177, 217, 255], + [0, 0, 0, 0, 44, 107, 156, 199, 238, 255, 255, 255], + ], + ), + ( + [[100.0, -100.0, 0.0], [0.0; 3], [-100.0, 100.0, 0.0]], + true, + [X, [0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255], [0, 0, 0, 0, 0, 0, 0, 130, 255, 255, 255, 255]], + ), + ( + [[-76.0, -2.0, 60.0], [0.0; 3], [99.0, 0.0, -30.0]], + false, + [ + [0, 0, 0, 0, 0, 0, 71, 171, 255, 255, 255, 255], + [0, 2, 6, 14, 29, 61, 94, 126, 158, 191, 224, 255], + [0, 6, 11, 21, 39, 73, 106, 137, 168, 197, 227, 255], + ], + ), + ]; + for (tones, preserve, want) in cases { + for (ch, row) in want.iter().enumerate() { + for (x, w) in X.iter().zip(row) { + let got = (color_balance_channel(tones, preserve, ch, f32::from(*x) / 255.0) * 255.0).round() as i32; + assert!((got - i32::from(*w)).abs() <= 1, "{tones:?} pl {preserve} ch {ch} at {x}: {got} vs Photoshop {w}"); + } + } + } + // Hostile input stays in range. + for v in [f32::NAN, -1.0, 2.0, f32::INFINITY] { + let out = color_balance_channel([[f32::NAN, 1e9, -1e9]; 3], true, 7, v); + assert!((0.0..=1.0).contains(&out), "{v}: {out}"); + } +} + +#[test] +fn color_balance_midtones_with_multiple_sliders_preserve_luminosity() { + // A shared offset depends on the two extremes, not the sum of moved sliders. + // The old per-slider product leaves red/blue unchanged for [30, 0, 30]. + let tones = [[0.0; 3], [30.0, 0.0, 30.0], [0.0; 3]]; + for input in [0.25_f32, 0.5, 0.75] { + for (ch, offset) in [-0.15_f32, 0.15, -0.15].into_iter().enumerate() { + let expected = input.powf(2f32.powf(offset)); + let actual = color_balance_channel(tones, true, ch, input); + assert!((actual - expected).abs() < 1e-6, "channel {ch}, input {input}: {actual} vs {expected}"); + } + // Preserve Luminosity off must still affect only the moved channels. + assert_eq!(color_balance_channel(tones, false, 1, input), input); + // One moved slider retains its previous half-strength compensation. + let single = [[0.0; 3], [30.0, 0.0, 0.0], [0.0; 3]]; + assert!((color_balance_channel(single, true, 0, input) - input.powf(2f32.powf(-0.15))).abs() < 1e-6); + assert!((color_balance_channel(single, true, 1, input) - input.powf(2f32.powf(0.15))).abs() < 1e-6); + } +} + +#[test] +fn color_balance_curve_matches_the_per_sample_formula_bitwise() { + // The curve works out its sample-independent terms once; this is the formula it replaced, + // evaluated whole for every sample. + fn per_sample(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize, v: f32) -> f32 { + let [shadows, midtones, highlights] = tones.map(|t| t.map(|s| if s.is_finite() { s.clamp(-100.0, 100.0) } else { 0.0 })); + let own = |t: [f32; 3]| t.get(ch).copied().unwrap_or(0.0); + let max = |t: [f32; 3]| t[0].max(t[1]).max(t[2]); + let min = |t: [f32; 3]| t[0].min(t[1]).min(t[2]); + let (black, white, m) = if preserve_luminosity { + (max(shadows) - own(shadows), own(highlights) - min(highlights), own(midtones) - (max(midtones) + min(midtones)) / 2.0) + } else { + ((-own(shadows)).max(0.0), own(highlights).max(0.0), own(midtones) + (own(shadows) + own(highlights)) / 2.0) + }; + let (b, w) = (black / 255.0, 1.0 - white / 255.0); + let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + if v >= w { + return 1.0; + } + if v <= b { + return 0.0; + } + let (u, gamma) = ((v - b) / (w - b), 2f32.powf(m / 100.0)); + let e = 1.0 / gamma.max(0.01); + let power = u.powf(e); + if gamma <= 1.0 { + return power; + } + let s0 = 2f32.powf(gamma); + let u0 = (2.0 * s0.powf(1.0 / (e - 1.0))).min(1.0); + if u0.is_nan() || u0 <= 0.0 || u >= u0 { + return power; + } + let (p, d, t) = (u0.powf(e), e * u0.powf(e - 1.0), u / u0); + let (t2, t3) = (t * t, t * t * t); + ((t3 - 2.0 * t2 + t) * u0 * s0 + (3.0 * t2 - 2.0 * t3) * p + (t3 - t2) * u0 * d).clamp(0.0, 1.0) + } + let mut seed = 0x9e37_79b9_u32; + let mut slider = || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + (seed % 241) as f32 - 120.0 + }; + let mut settings = vec![[[0.0; 3]; 3], [[f32::NAN, 1e9, -1e9]; 3], [[-100.0; 3], [100.0; 3], [100.0; 3]]]; + settings.extend((0..120).map(|_| std::array::from_fn(|_| std::array::from_fn(|_| slider())))); + let samples: Vec = (0..=1024).map(|i| i as f32 / 1024.0).chain([-0.5, 1.5, f32::NAN, f32::INFINITY]).collect(); + for tones in settings { + for preserve in [false, true] { + for ch in [0, 1, 2, 7] { + let curve = BalanceCurve::new(tones, preserve, ch); + for &v in &samples { + let (got, want) = (curve.eval(v), per_sample(tones, preserve, ch, v)); + assert_eq!(got.to_bits(), want.to_bits(), "{tones:?} {preserve} ch {ch} v {v}: {got} vs {want}"); + } + } + } + } +} + +#[test] +fn levels_and_curves_apply_each_channel_before_the_master() { + // These two affine tone adjustments describe the same mapping: + // channel(x) = 1 / 2 + x / 2, then master(x) = x / 2, so 0 maps to 0.25. + // Levels used to apply the master first (0 mapped to 0.5). + let line = |a: f32, b: f32| vec![CurvePoint { input: 0.0, output: a }, CurvePoint { input: 1.0, output: b }]; + let levels = Adjustment::Levels { + master: LevelsChannel { out_white: 0.5, ..Default::default() }, + per_channel: std::array::from_fn(|_| LevelsChannel { out_black: 0.5, ..Default::default() }), + space: ToneSpace::Rgb, + black: Default::default(), + }; + let curves = Adjustment::Curves { + master: line(0.0, 0.5), + per_channel: std::array::from_fn(|_| line(0.5, 1.0)), + space: ToneSpace::Rgb, + black: Vec::new(), + pencil: false, + }; + for depth in [None, Some(SampleType::U8), Some(SampleType::U16), Some(SampleType::F32)] { + let ll = tone_luts_depth(&levels, depth); + let cl = tone_luts_depth(&curves, depth); + for channel in 0..3 { + for index in [0, LUT_SIZE / 4, LUT_SIZE / 2, 3 * LUT_SIZE / 4, LUT_SIZE - 1] { + assert!( + (ll[channel][index] - cl[channel][index]).abs() < 0.01, + "{depth:?} channel {channel} sample {index}: Levels {} vs Curves {}", + ll[channel][index], + cl[channel][index] + ); + } + } + assert!((cl[0][0] - 0.25).abs() < 0.01, "{depth:?}: {}", cl[0][0]); + + // Exercise the compositor's real adjustment path, not only its LUT builder. + for adj in [&levels, &curves] { + let mut pixel = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.0, 0.0, 0.0, 1.0]] }; + apply_depth(adj, &mut pixel, Transfer::Srgb, depth); + for channel in 0..3 { + assert!((pixel.px[0][channel] - 0.25).abs() < 0.01, "{depth:?}: {adj:?} rendered {:?}", pixel.px[0]); + } + } + } + + // Lab has no composite/master tone record. + let mut lab = curves.clone(); + let mut lab_without_master = curves; + if let Adjustment::Curves { space, .. } = &mut lab { + *space = ToneSpace::Lab; + } + if let Adjustment::Curves { master, space, .. } = &mut lab_without_master { + *space = ToneSpace::Lab; + *master = line(0.0, 1.0); + } + assert_eq!(tone_luts(&lab), tone_luts(&lab_without_master)); +} + +#[test] +fn identity_tone_in_every_space_is_identity() { + for space in [ToneSpace::Rgb, ToneSpace::Cmyk, ToneSpace::Lab] { + let mut a = Adjustment::identity_curves(); + if let Adjustment::Curves { space: s, .. } = &mut a { + *s = space; + } + let mut b = ramp(); + apply(&a, &mut b); + for (x, y) in b.px.iter().zip(ramp().px.iter()) { + for k in 0..3 { + assert!((x[k] - y[k]).abs() < 0.02, "{space:?} {x:?} {y:?}"); + } + } + } +} + +#[test] +fn cmyk_black_curve_darkens_and_lab_lightness_lifts() { + let line = |a: f32, b: f32| vec![CurvePoint { input: 0.0, output: a }, CurvePoint { input: 1.0, output: b }]; + // Black brightness 1 -> 0.5: more black ink everywhere. + let a = Adjustment::Curves { + master: line(0.0, 1.0), + per_channel: [line(0.0, 1.0), line(0.0, 1.0), line(0.0, 1.0)], + space: ToneSpace::Cmyk, + black: line(0.0, 0.5), + pencil: false, + }; + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.8, 0.8, 0.8, 1.0]] }; + apply(&a, &mut b); + assert!(b.px[0][0] < 0.7, "{:?}", b.px[0]); + // Lab lightness 0..1 -> 0.2..1 lifts a dark grey; a/b untouched keeps it grey. + let a = Adjustment::Curves { + master: line(1.0, 0.0), // ignored in Lab + per_channel: [line(0.2, 1.0), line(0.0, 1.0), line(0.0, 1.0)], + space: ToneSpace::Lab, + black: Vec::new(), + pencil: false, + }; + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.2, 0.2, 0.2, 1.0]] }; + apply(&a, &mut b); + let p = b.px[0]; + assert!(p[0] > 0.3 && (p[0] - p[2]).abs() < 0.02, "{p:?}"); +} + +#[test] +fn hue_ranges_only_touch_their_colours() { + let mut ranges = HueRange::defaults(); + ranges[0].saturation = -100.0; // desaturate reds + let a = Adjustment::HueSaturation { hue: 0.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges }; + let mut b = Buffer { rect: Rect::new(0, 0, 3, 1), px: vec![[0.9, 0.1, 0.1, 1.0], [0.1, 0.1, 0.9, 1.0], [0.5, 0.5, 0.5, 1.0]] }; + apply(&a, &mut b); + let red = b.px[0]; + assert!((red[0] - red[1]).abs() < 0.05, "red desaturated {red:?}"); + assert!((b.px[1][2] - 0.9).abs() < 1e-4 && (b.px[1][0] - 0.1).abs() < 1e-4, "blue untouched {:?}", b.px[1]); + assert_eq!(b.px[2], [0.5, 0.5, 0.5, 1.0]); +} + +#[test] +fn colorize_at_zero_saturation_is_grey() { + // Photoshop: Colorize at 0% saturation leaves no colour, only the pixel's lightness (#2326). + let px = vec![[0.9, 0.2, 0.1, 1.0], [0.1, 0.6, 0.8, 1.0], [0.5, 0.5, 0.5, 1.0]]; + for depth in [None, Some(SampleType::U8), Some(SampleType::U16), Some(SampleType::F32)] { + for lightness in [0.0, 30.0, -30.0] { + let a = Adjustment::HueSaturation { hue: 200.0, saturation: 0.0, lightness, colorize: true, ranges: HueRange::defaults() }; + let mut b = Buffer { rect: Rect::new(0, 0, 3, 1), px: px.clone() }; + apply_depth(&a, &mut b, Transfer::Srgb, depth); + for p in &b.px { + assert!((p[0] - p[1]).abs() < 1e-4 && (p[1] - p[2]).abs() < 1e-4, "{depth:?} lightness {lightness}: {p:?}"); + } + } + // Low saturations still tint: the old 25% floor no longer hides them. + let tint = |saturation: f32| { + let a = Adjustment::HueSaturation { hue: 0.0, saturation, lightness: 0.0, colorize: true, ranges: HueRange::defaults() }; + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.5, 0.5, 0.5, 1.0]] }; + apply_depth(&a, &mut b, Transfer::Srgb, depth); + b.px[0][0] - b.px[0][2] + }; + assert!(tint(10.0) > 0.05 && tint(10.0) < tint(25.0), "{depth:?}: 10% {} vs 25% {}", tint(10.0), tint(25.0)); + } +} + +/// Photoshop 27.11, measured: Hue/Saturation raising saturation, and Colorize with Lightness. +#[test] +fn hue_saturation_matches_photoshop() { + // (input, hue, saturation, lightness, colorize, Photoshop's output) + type Case = ([u8; 3], f32, f32, f32, bool, [u8; 3]); + let measured: [Case; 8] = [ + ([204, 102, 102], 0.0, 50.0, 0.0, false, [254, 51, 51]), + ([204, 159, 102], 0.0, 50.0, 0.0, false, [254, 164, 51]), + ([204, 102, 102], 0.0, -50.0, 0.0, false, [178, 127, 127]), + ([0, 0, 0], 120.0, 100.0, 30.0, true, [0, 152, 0]), + ([28, 28, 28], 120.0, 100.0, 30.0, true, [0, 192, 0]), + ([160, 160, 160], 30.0, 25.0, -40.0, true, [120, 96, 73]), + ([252, 252, 252], 30.0, 25.0, -40.0, true, [177, 151, 126]), + ([255, 143, 0], 30.0, 25.0, -40.0, true, [95, 76, 58]), + ]; + for (input, hue, saturation, lightness, colorize, want) in measured { + let a = Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges: HueRange::defaults() }; + let c = input.map(|v| v as f32 / 255.0); + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[c[0], c[1], c[2], 1.0]] }; + apply(&a, &mut b); + for (i, w) in want.iter().enumerate() { + let got = b.px[0][i] * 255.0; + assert!((got - *w as f32).abs() <= 2.0, "{input:?} h{hue} s{saturation} l{lightness} colorize {colorize}, channel {i}: {got} vs {w}"); + } + } +} + +/// Photoshop 27.11, measured: a range's Lightness (Blues ±50) moves towards the brightest or darkest channel. +#[test] +fn range_lightness_matches_photoshop() { + let measured = [ + ([0u8, 29, 115], 0.5, [57u8, 71, 115]), + ([0, 64, 255], 0.5, [125, 157, 255]), + ([102, 128, 204], 0.5, [152, 165, 204]), + ([102, 128, 204], -0.5, [102, 115, 154]), + ([0, 18, 115], -0.5, [0, 9, 58]), + ]; + for (input, l, want) in measured { + let got = range_lightness(input.map(|v| v as f32 / 255.0), l); + for i in 0..3 { + assert!((got[i] * 255.0 - want[i] as f32).abs() <= 2.5, "{input:?} channel {i}: {} vs {}", got[i] * 255.0, want[i]); + } + } +} + +/// Photoshop's own render (merged image of psd-tools `adjustments/huesaturation_lightness_rgb.psd`, +/// layer "Hue/Saturation 1"): a dull magenta gets the whole range edit, as a vivid one does (#4089). +#[test] +fn hue_ranges_apply_in_full_to_dull_colours() { + let range = |lightness: f32, bounds: [f32; 4]| HueRange { hue: 0.0, saturation: 0.0, lightness, bounds }; + let ranges = [ + range(-11.0, [-57.0, 4.0, 82.0, 175.0]), + range(100.0, [12.0, 45.0, 75.0, 105.0]), + HueRange::neutral(2), + HueRange::neutral(3), + HueRange::neutral(4), + range(100.0, [-117.0, -50.0, 39.0, 104.0]), + ]; + let a = Adjustment::HueSaturation { hue: 0.0, saturation: 0.0, lightness: 17.0, colorize: false, ranges }; + let measured = [([126u8, 97, 120], [148u8, 148, 148]), ([131, 103, 125], [152, 152, 152]), ([95, 69, 90], [122, 122, 122])]; + for (input, want) in measured { + let c = input.map(|v| v as f32 / 255.0); + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[c[0], c[1], c[2], 1.0]] }; + apply(&a, &mut b); + for (i, w) in want.iter().enumerate() { + let got = b.px[0][i] * 255.0; + assert!((got - *w as f32).abs() <= 2.0, "{input:?} channel {i}: {got} vs {w}"); + } + } + // Greys have no hue, so the ranges leave them alone: only the master Lightness moves them. + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[0.4, 0.4, 0.4, 1.0]] }; + apply(&a, &mut b); + let p = b.px[0]; + assert!((p[0] - p[1]).abs() < 1e-6 && (p[1] - p[2]).abs() < 1e-6 && (p[0] - (0.4 + 0.6 * 0.17)).abs() < 1e-4, "{p:?}"); +} + +#[test] +fn black_white_weights() { + let d = [40.0, 60.0, 40.0, 60.0, 20.0, 80.0]; + assert!((black_white_gray([0.5; 3], &d) - 0.5).abs() < 1e-6, "greys keep their value"); + assert!((black_white_gray([1.0, 0.0, 0.0], &d) - 0.4).abs() < 1e-6); + assert!((black_white_gray([1.0, 1.0, 0.0], &d) - 0.6).abs() < 1e-6); + let mut w = d; + w[0] = 100.0; + assert!(black_white_gray([1.0, 0.0, 0.0], &w) > black_white_gray([1.0, 0.0, 0.0], &d)); +} + +/// #8537: 32-bit superwhites stay above 1 (Photoshop 27.11: 2.0 stays 2.0, neutrals cap at +/// 16, negatives go to 0); 8-bit still clips at 1. +#[test] +fn black_white_keeps_32_bit_superwhites() { + let adj = Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None }; + let run = |depth, c: f32| { + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[c, c, c, 1.0]] }; + apply_depth(&adj, &mut b, Transfer::Srgb, Some(depth)); + b.px[0][0] + }; + assert_eq!(run(SampleType::F32, 2.0), 2.0); + assert_eq!(run(SampleType::F32, 20.0), 16.0); + assert_eq!(run(SampleType::F32, -0.5), 0.0); + assert_eq!(run(SampleType::U8, 2.0), 1.0); +} + +/// Photoshop 27.11, measured: Black & White (default weights) with Tint over greys. The tint +/// is blended like the Color blend mode: its hue and saturation at the grey's luminosity. +#[test] +fn black_white_tint_matches_photoshop() { + let weights = [40.0, 60.0, 40.0, 60.0, 20.0, 80.0]; + let measured: [([u8; 3], u8, [u8; 3]); 6] = [ + ([255, 0, 0], 24, [81, 1, 1]), + ([255, 0, 0], 120, [255, 64, 64]), + ([255, 0, 0], 240, [255, 235, 235]), + ([0xe1, 0xd3, 0xb3], 120, [133, 119, 87]), + ([0xe1, 0xd3, 0xb3], 24, [33, 24, 1]), + ([0x40, 0x20, 0x10], 120, [144, 112, 96]), + ]; + for (tint, grey, want) in measured { + let tint = Some(tint.map(|v| v as f32 / 255.0)); + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[grey as f32 / 255.0; 4]] }; + b.px[0][3] = 1.0; + apply(&Adjustment::BlackWhite { weights, tint }, &mut b); + for (i, w) in want.iter().enumerate() { + let got = b.px[0][i] * 255.0; + assert!((got - *w as f32).abs() <= 2.5, "tint {tint:?} grey {grey} channel {i}: {got} vs {w}"); + } + } +} + +#[test] +fn gradient_map_follows_the_w3c_luminosity() { + // Photoshop's Gradient Map is driven by 0.3 R + 0.59 G + 0.11 B (photoshop corpus rgb8 and + // rgb16 gradient-map.psd), not the Rec. 601 grey. + let stops = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]; + for (c, t) in [([0.0, 1.0, 0.0], 0.59), ([1.0, 0.0, 0.0], 0.3), ([0.0, 0.0, 1.0], 0.11), ([0.2, 0.6, 0.9], 0.513)] { + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); + apply(&Adjustment::GradientMap { stops: stops.clone(), reverse: false, dither: false }, &mut b); + assert!((b.px[0][0] - t).abs() < 1e-5, "{c:?}: {}", b.px[0][0]); + } +} + +#[test] +fn gradient_map_dither_stays_close() { + let stops = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]; + let mut a = ramp(); + let mut b = ramp(); + apply(&Adjustment::GradientMap { stops: stops.clone(), reverse: false, dither: false }, &mut a); + apply(&Adjustment::GradientMap { stops, reverse: false, dither: true }, &mut b); + assert!(a.px.iter().zip(&b.px).all(|(x, y)| (x[0] - y[0]).abs() <= 0.5 / 255.0 + 1e-6)); + assert!(a.px.iter().zip(&b.px).any(|(x, y)| x[0] != y[0])); +} + +/// `adj` applied in a Lab document to one encoded sRGB colour, returned as (L, a, b). +fn in_lab(adj: &Adjustment, c: [f32; 3]) -> [f32; 3] { + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); + apply_in(adj, &mut b, Transfer::Srgb, Some(SampleType::U8), ColorMode::Lab); + srgb_to_lab([b.px[0][0], b.px[0][1], b.px[0][2]]) +} + +/// A muted, in-gamut colour from (L, a, b). +fn lab(l: f32, a: f32, b: f32) -> [f32; 3] { + lab_to_srgb([l, a, b]) +} + +fn near(got: [f32; 3], want: [f32; 3], tol: f32) -> bool { + got.iter().zip(want).all(|(g, w)| (g - w).abs() <= tol) +} + +#[test] +fn lab_invert_flips_l_a_and_b() { + let got = in_lab(&Adjustment::Invert, lab(30.0, 12.0, -18.0)); + // n -> 1 - n: L -> 100 - L, a -> -a - 1, b -> -b - 1 (mirrored on the 0..255 grid). + assert!(near(got, [70.0, -13.0, 17.0], 0.6), "{got:?}"); + // On the screen colour it would not be a mirror in Lab. + let mut rgb = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [0.0, 0.0, 0.0, 1.0]); + let c = lab(30.0, 12.0, -18.0); + rgb.px[0] = [c[0], c[1], c[2], 1.0]; + apply(&Adjustment::Invert, &mut rgb); + assert!(!near(srgb_to_lab([rgb.px[0][0], rgb.px[0][1], rgb.px[0][2]]), got, 1.0)); +} + +#[test] +fn sixteen_bit_lab_invert_keeps_greys_neutral() { + // 16-bit Lab Invert mirrors a and b around neutral (photoshop corpus lab16 invert.psd); + // 8-bit bytes land one step off it. + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [0.0, 0.0, 0.0, 1.0]); + let c = lab(40.0, 0.0, 0.0); + b.px[0] = [c[0], c[1], c[2], 1.0]; + apply_in(&Adjustment::Invert, &mut b, Transfer::Srgb, Some(SampleType::U16), ColorMode::Lab); + let got = srgb_to_lab([b.px[0][0], b.px[0][1], b.px[0][2]]); + assert!(near(got, [60.0, 0.0, 0.0], 0.05), "{got:?}"); + assert!(near(in_lab(&Adjustment::Invert, c), [60.0, -1.0, -1.0], 0.1)); +} + +/// `adj` applied in a CMYK document to one encoded sRGB colour. +fn in_cmyk(adj: &Adjustment, c: [f32; 3]) -> [f32; 3] { + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); + apply_in(adj, &mut b, Transfer::Srgb, Some(SampleType::U8), ColorMode::Cmyk); + [b.px[0][0], b.px[0][1], b.px[0][2]] +} + +#[test] +fn cmyk_invert_posterize_and_threshold_work_on_the_inks() { + use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk}; + // Paper inverts to all four inks at 100%, not to RGB black (photoshop corpus cmyk8 invert.psd). + assert!(near(in_cmyk(&Adjustment::Invert, [1.0; 3]), cmyk_to_rgb([1.0; 4]), 2e-3)); + let red = [0.9, 0.2, 0.1]; + assert!(near(in_cmyk(&Adjustment::Invert, red), cmyk_to_rgb(rgb_to_cmyk(red).map(|v| 1.0 - v)), 2e-3)); + let two = cmyk_to_rgb(rgb_to_cmyk(red).map(|v| if v >= 0.5 { 1.0 } else { 0.0 })); + assert!(near(in_cmyk(&Adjustment::Posterize { levels: 2 }, red), two, 2e-3)); + // Threshold's black is the black ink alone (threshold-128.psd), its white the paper. + let t = Adjustment::Threshold { level: 0.5 }; + assert!(near(in_cmyk(&t, [0.2; 3]), cmyk_to_rgb([0.0, 0.0, 0.0, 1.0]), 2e-3)); + assert!(near(in_cmyk(&t, [0.8; 3]), cmyk_to_rgb([0.0; 4]), 2e-3)); +} + +/// CMYK posterizes the stored value 1 - ink: with 3 levels an ink of 85 (stored 170) lands on +/// the middle step, 128 (stored 127), where posterizing the ink would drop it to none (psd-tools +/// posterize_cmyk.psd, levels 3 to 21, exact so). +#[test] +fn cmyk_posterize_works_on_the_stored_values() { + let mut ink = [85.0 / 255.0; 4]; + stored_channels(&Adjustment::Posterize { levels: 3 }, ColorMode::Cmyk, Some(SampleType::U8), &mut ink); + assert!(ink.iter().all(|v| (v * 255.0 - 128.0).abs() < 1e-3), "{ink:?}"); + assert_eq!(posterize(85.0 / 255.0, 3), 0.0, "posterizing the ink itself"); +} + +#[test] +fn cmyk_threshold_compares_the_inks_plain_luma() { + assert_eq!(ink_luma([0.0; 4]), 1.0); + assert_eq!(ink_luma([0.0, 0.0, 0.0, 1.0]), 0.0); + // Two greys either side of level 128 in photoshop corpus cmyk8 threshold-128.psd: black, + // then white (8-bit inks). + let at = |i: [f32; 4]| { + let mut ch = i.map(|v| v / 255.0); + stored_channels(&Adjustment::Threshold { level: 128.0 / 255.0 }, ColorMode::Cmyk, Some(SampleType::U8), &mut ch); + ch + }; + assert_eq!(at([144.0, 122.0, 121.0, 35.0]), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(at([131.0, 110.0, 110.0, 19.0]), [0.0; 4]); +} + +#[test] +fn cmyk_brightness_contrast_curves_each_ink_from_paper() { + use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk}; + // The tone curve runs on each ink's stored value, 1 - ink (photoshop corpus cmyk8 + // brightness-contrast.psd and -legacy.psd): raising brightness takes ink away, and paper + // and solid ink stay put. + let red = [0.9, 0.2, 0.1]; + for legacy in [false, true] { + let adj = Adjustment::BrightnessContrast { brightness: 25.0, contrast: 30.0, legacy }; + let table = ink_brightness_contrast_lut(25.0, 30.0, legacy); + let want = cmyk_to_rgb(rgb_to_cmyk(red).map(|v| 1.0 - lut(&table, 1.0 - v))); + assert!(near(in_cmyk(&adj, red), want, 2e-3), "legacy {legacy}"); + assert!(near(in_cmyk(&adj, [1.0; 3]), [1.0; 3], 2e-3), "legacy {legacy}: paper"); + let solid = cmyk_to_rgb([1.0; 4]); + assert!(near(in_cmyk(&adj, solid), cmyk_to_rgb(rgb_to_cmyk(solid).map(|v| ink_through(&table, v))), 2e-3)); + } + // Legacy +25 / +30 on Photoshop's own 16-bit inks (photoshop corpus cmyk16 + // brightness-contrast-legacy.psd): contrast pivots at 128 in ink, 127 stored. + let legacy = ink_brightness_contrast_lut(25.0, 30.0, true); + for (ink, ps) in [(139.0, 108.0), (160.0, 137.99), (172.0, 155.13), (183.0, 170.85), (196.0, 189.42), (98.0, 49.42), (128.0, 92.28), (168.0, 149.42)] { + let got = ink_through(&legacy, ink / 255.0) * 255.0; + assert!((got - ps).abs() < 0.1, "ink {ink}: {got} vs Photoshop {ps}"); + } + let brighter = Adjustment::BrightnessContrast { brightness: 60.0, contrast: 0.0, legacy: false }; + let ink = ink_brightness_contrast_lut(60.0, 0.0, false); + assert!(ink_through(&ink, 0.5) < 0.5 && ink_through(&ink, 0.0) == 0.0 && (ink_through(&ink, 1.0) - 1.0).abs() < 1e-6); + // On the screen colour it would land elsewhere. + let mut rgb = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [red[0], red[1], red[2], 1.0]); + apply(&brighter, &mut rgb); + assert!(!near(in_cmyk(&brighter, red), [rgb.px[0][0], rgb.px[0][1], rgb.px[0][2]], 0.01)); +} + +#[test] +fn lab_posterize_steps_l_a_and_b() { + let got = in_lab(&Adjustment::Posterize { levels: 2 }, lab(70.0, 20.0, -30.0)); + // Two levels: each normalised channel snaps to 0 or 1 (L 100, a and b at +127 / -128). + assert!(near(got, srgb_to_lab(lab_denorm([1.0, 1.0, 0.0])), 1e-3), "{got:?}"); + let grey = in_lab(&Adjustment::Posterize { levels: 255 }, lab(50.0, 0.0, 0.0)); + assert!(near(grey, [50.0, 0.0, 0.0], 1.1), "255 levels is within a step of the identity: {grey:?}"); +} + +#[test] +fn lab_threshold_splits_on_l_with_a_neutral_result() { + let t = Adjustment::Threshold { level: 0.5 }; + // A saturated blue (L ≈ 32) and yellow (L ≈ 97): black and white, nothing in between. + for (c, white) in [([0.0, 0.0, 1.0], false), ([1.0, 1.0, 0.0], true), (lab(52.0, 40.0, 30.0), true), (lab(48.0, -40.0, 30.0), false)] { + let mut b = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); + apply_in(&t, &mut b, Transfer::Srgb, None, ColorMode::Lab); + let v = if white { 1.0 } else { 0.0 }; + assert_eq!(b.px[0], [v, v, v, 1.0], "{c:?}"); + } +} + +#[test] +fn lab_brightness_contrast_moves_l_only() { + for legacy in [false, true] { + let adj = Adjustment::BrightnessContrast { brightness: 40.0, contrast: 30.0, legacy }; + let before = [45.0, 15.0, -20.0]; + let got = in_lab(&adj, lab(before[0], before[1], before[2])); + assert!(got[0] > before[0] + 5.0, "{legacy}: L rises: {got:?}"); + assert!((got[1] - before[1]).abs() < 0.5 && (got[2] - before[2]).abs() < 0.5, "{legacy}: a, b kept: {got:?}"); + } +} + +#[test] +fn lab_gradient_map_follows_l() { + let stops = vec![(0.0, [1.0, 0.0, 0.0]), (1.0, [0.0, 0.0, 1.0])]; + for reverse in [false, true] { + let map = Adjustment::GradientMap { stops: stops.clone(), reverse, dither: false }; + // A grey and a saturated colour with the same L map to the same colour. + let grey = in_lab(&map, lab(60.0, 0.0, 0.0)); + let green = in_lab(&map, lab(60.0, -50.0, 40.0)); + assert!(near(grey, green, 1e-3), "{reverse}: {grey:?} vs {green:?}"); + let t = if reverse { 0.4 } else { 0.6 }; + let want = srgb_to_lab([1.0 - t, 0.0, t]); + assert!(near(grey, want, 0.05), "{reverse}: {grey:?} vs {want:?}"); + } +} + +#[test] +fn other_modes_and_adjustments_keep_the_screen_colour_path() { + let c = [0.2, 0.5, 0.7, 1.0]; + let lab_only = [Adjustment::Invert, Adjustment::Threshold { level: 0.47 }, Adjustment::Posterize { levels: 4 }]; + for adj in + lab_only.iter().chain([&Adjustment::HueSaturation { hue: 30.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }]) + { + for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Grayscale, ColorMode::Lab] { + let (mut a, mut b) = (Buffer::filled(crate::Rect::new(0, 0, 1, 1), c), Buffer::filled(crate::Rect::new(0, 0, 1, 1), c)); + apply_in(adj, &mut a, Transfer::Srgb, None, mode); + apply_depth(adj, &mut b, Transfer::Srgb, None); + let own = (mode == ColorMode::Lab && lab_channel_adjustment(adj)) || (mode == ColorMode::Cmyk && cmyk_channel_adjustment(adj)); + assert_eq!(a.px == b.px, !own, "{adj:?} in {mode:?}"); + } + } + // Transparent pixels are left alone and odd values never panic. + let mut t = Buffer::filled(crate::Rect::new(0, 0, 2, 1), [f32::NAN, 2.0, -1.0, 0.0]); + for adj in lab_only.iter().chain([&Adjustment::GradientMap { stops: vec![], reverse: true, dither: true }]) { + for mode in [ColorMode::Lab, ColorMode::Cmyk] { + apply_in(adj, &mut t, Transfer::Srgb, None, mode); + let mut odd = Buffer::filled(crate::Rect::new(0, 0, 1, 1), [f32::NAN, f32::INFINITY, -3.0, 1.0]); + apply_in(adj, &mut odd, Transfer::Srgb, Some(SampleType::U16), mode); + } + } + assert!(t.px[0][1] == 2.0); +} From 6f35658164a52b900e1aa807c38ddded73bc7f2f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:44 +0000 Subject: [PATCH 113/259] refactor(compose): move masks.rs tests to masks/tests.rs --- crates/compose/src/masks.rs | 356 +----------------------------- crates/compose/src/masks/tests.rs | 353 +++++++++++++++++++++++++++++ 2 files changed, 354 insertions(+), 355 deletions(-) create mode 100644 crates/compose/src/masks/tests.rs diff --git a/crates/compose/src/masks.rs b/crates/compose/src/masks.rs index 7335be90d0..851c9bc509 100644 --- a/crates/compose/src/masks.rs +++ b/crates/compose/src/masks.rs @@ -251,358 +251,4 @@ fn build_mask(layer: &Layer, canvas: Rect) -> Surface { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_doc::LayerMask; - use photocraft_doc::vector::{Knot, Path, Subpath, VectorMask}; - - fn pending(c: &Mutex, k: u64) -> Arc> { - match lookup(c, k) { - CachedMask::Pending(slot, _) => slot, - CachedMask::Hit(_) => panic!("expected a cold mask"), - } - } - - /// A built mask (and no pixel-mask input), as `finish_mask`'s build returns it. - fn test_surface() -> (Surface, Option) { - let mut surface = Surface::new(FORMAT); - surface.fill_rect(Rect::new(0, 0, 2, 2), &[0.5]); - (surface, None) - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn cold_callers_share_one_build_without_retaining_a_second_cache() { - use std::sync::Barrier; - use std::sync::atomic::{AtomicUsize, Ordering}; - - let c = Mutex::new(Cache::default()); - // Acquire all callers' slots before allowing any builder to finish. - let slots: Vec<_> = (0..8).map(|_| pending(&c, 7)).collect(); - assert!(slots.iter().all(|slot| Arc::ptr_eq(slot, &slots[0]))); - let barrier = Barrier::new(slots.len()); - let builds = AtomicUsize::new(0); - let outputs = std::thread::scope(|scope| { - let handles: Vec<_> = slots - .iter() - .map(|slot| { - let (c, barrier, builds) = (&c, &barrier, &builds); - scope.spawn(move || { - barrier.wait(); - finish_mask(c, 7, slot, 0, || { - builds.fetch_add(1, Ordering::SeqCst); - test_surface() - }) - }) - }) - .collect(); - handles.into_iter().map(|handle| handle.join().unwrap()).collect::>() - }); - assert_eq!(builds.load(Ordering::SeqCst), 1); - assert!(outputs.iter().all(|surface| Arc::ptr_eq(surface.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1))); - - // Evicting the retained result cannot make existing callers build again. - c.lock().unwrap().map.clear(); - let again = finish_mask(&c, 7, &slots[0], 0, || panic!("rebuilt an active slot")); - assert!(Arc::ptr_eq(again.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1)); - drop(slots); - let next = pending(&c, 8); - assert_eq!(c.lock().unwrap().in_flight.len(), 1); - drop(next); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn distinct_keys_build_while_another_key_is_paused() { - use std::sync::mpsc; - use std::time::Duration; - - let c = Mutex::new(Cache::default()); - let (started_tx, started_rx) = mpsc::channel(); - let (release_tx, release_rx) = mpsc::channel(); - let (second_tx, second_rx) = mpsc::channel(); - std::thread::scope(|scope| { - let c = &c; - let first = scope.spawn(move || { - cached_mask(c, 1, || { - started_tx.send(()).unwrap(); - release_rx.recv_timeout(Duration::from_secs(10)).unwrap(); - test_surface() - }) - }); - started_rx.recv_timeout(Duration::from_secs(5)).unwrap(); - let second = scope.spawn(move || { - let surface = cached_mask(c, 2, test_surface); - second_tx.send(surface.sample_channel(0, 0, 0)).unwrap(); - }); - assert!((second_rx.recv_timeout(Duration::from_secs(5)).unwrap() - 0.5).abs() <= 1.0 / f32::from(u16::MAX)); - release_tx.send(()).unwrap(); - first.join().unwrap(); - second.join().unwrap(); - }); - } - - #[test] - fn obsolete_in_flight_build_does_not_repopulate_the_cache() { - let c = Mutex::new(Cache::default()); - let old = pending(&c, 1); - c.lock().unwrap().in_flight.clear(); - let current = pending(&c, 1); - assert!(!Arc::ptr_eq(&old, ¤t)); - let old_surface = finish_mask(&c, 1, &old, 0, test_surface); - assert!(c.lock().unwrap().map.is_empty()); - let current_surface = finish_mask(&c, 1, ¤t, 0, test_surface); - assert!(!Arc::ptr_eq(old_surface.tiles().next().unwrap().1, current_surface.tiles().next().unwrap().1)); - assert_eq!(c.lock().unwrap().map.len(), 1); - } - - #[test] - fn a_purge_during_a_shared_build_keeps_the_cache_empty() { - let c = Mutex::new(Cache::default()); - let CachedMask::Pending(slot, generation) = lookup(&c, 1) else { panic!("expected a cold mask") }; - c.lock().unwrap().clear(); - finish_mask(&c, 1, &slot, generation, test_surface); - assert!(c.lock().unwrap().map.is_empty()); - assert_eq!(c.lock().unwrap().bytes, 0); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn parallel_feathered_pixel_mask_returns_the_same_tiles() { - let canvas = Rect::new(0, 0, 600, 400); - let mut layer = Layer::raster("cold shared mask", PixelFormat::RGBA8); - let mut mask = photocraft_doc::LayerMask::reveal_all(); - mask.surface.fill_rect(canvas, &[0.5]); - mask.feather = 8.0; - layer.mask = Some(mask); - let barrier = std::sync::Barrier::new(8); - let outputs = std::thread::scope(|scope| { - let handles: Vec<_> = (0..8) - .map(|_| { - let (layer, barrier) = (&layer, &barrier); - scope.spawn(move || { - barrier.wait(); - combined_mask(layer, canvas).unwrap() - }) - }) - .collect(); - handles.into_iter().map(|handle| handle.join().unwrap()).collect::>() - }); - assert!(outputs.iter().all(|surface| Arc::ptr_eq(surface.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1))); - } - - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn vector_mask_build_inside_a_small_rayon_pool_completes() { - use rayon::prelude::*; - use std::sync::mpsc; - use std::time::Duration; - - let (tx, rx) = mpsc::channel(); - let handle = std::thread::spawn(move || { - let canvas = Rect::new(0, 0, 512, 512); - let mut layer = Layer::raster("rayon vector mask", PixelFormat::RGBA8); - let mut mask = VectorMask::new(photocraft_vector::shapes::ellipse(8.0, 8.0, 496.0, 496.0)); - mask.feather = 8.0; - layer.vector_mask = Some(mask); - let pool = rayon::ThreadPoolBuilder::new().num_threads(2).build().unwrap(); - let outputs: Vec<_> = pool.install(|| (0..8).into_par_iter().map(|_| combined_mask(&layer, canvas).unwrap()).collect()); - assert!(outputs.iter().all(|surface| Arc::ptr_eq(surface.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1))); - tx.send(()).unwrap(); - }); - rx.recv_timeout(Duration::from_secs(10)).expect("mask initializer deadlocked inside Rayon"); - handle.join().unwrap(); - } - - fn one_tile(sample: SampleType) -> Surface { - let mut surface = Surface::with_default(PixelFormat { mode: ColorMode::Grayscale, sample, alpha: false }, &[1.0]); - surface.fill_rect(Rect::new(0, 0, 1, 1), &[0.0]); - surface - } - - #[test] - fn charges_input_and_output_at_every_depth_including_off_canvas_tiles() { - let result = one_tile(SampleType::F32); - for sample in SampleType::ALL { - let mut input = one_tile(sample); - input.fill_rect(Rect::new(1024, 1024, 1025, 1025), &[0.0]); - let tile_pixels = (photocraft_geom::TILE_SIZE * photocraft_geom::TILE_SIZE) as usize; - let expected = tile_pixels * (SampleType::F32.bytes() + 2 * sample.bytes()) + SampleType::F32.bytes() + sample.bytes(); - let bytes = entry_bytes(&result, Some(&input)); - assert_eq!(bytes, expected, "{sample:?}"); - let mut cache = Cache::default(); - cache.insert(1, result.clone(), None, bytes, bytes * 2, cache.generation); - cache.insert(2, result.clone(), None, bytes, bytes * 2, cache.generation); - assert_eq!(cache.bytes, bytes * 2, "shared tiles are conservatively charged per entry"); - } - } - - #[test] - fn byte_budget_evicts_the_least_recently_used_entry() { - let surface = one_tile(SampleType::F32); - let bytes = entry_bytes(&surface, None); - let mut cache = Cache::default(); - cache.insert(1, surface.clone(), None, bytes, bytes * 2, cache.generation); - cache.insert(2, surface.clone(), None, bytes, bytes * 2, cache.generation); - assert!(cache.get(1).is_some()); - cache.insert(3, surface, None, bytes, bytes * 2, cache.generation); - assert!(cache.get(2).is_none()); - assert!(cache.get(1).is_some()); - assert!(cache.get(3).is_some()); - assert_eq!(cache.bytes, bytes * 2); - } - - #[test] - fn entry_limit_also_bounds_masks_with_no_tiles() { - let surface = Surface::new(FORMAT); - let bytes = entry_bytes(&surface, None); - let mut cache = Cache::default(); - for key in 0..CAPACITY as u64 { - cache.insert(key, surface.clone(), None, bytes, CACHE_BUDGET, cache.generation); - } - assert!(cache.get(0).is_some()); - cache.insert(CAPACITY as u64, surface, None, bytes, CACHE_BUDGET, cache.generation); - assert_eq!(cache.map.len(), CAPACITY); - assert!(cache.get(1).is_none()); - assert!(cache.get(0).is_some()); - assert_eq!(cache.bytes, bytes * CAPACITY); - } - - #[test] - fn oversized_results_are_usable_without_retention_or_other_eviction() { - let surface = one_tile(SampleType::F32); - let bytes = entry_bytes(&surface, None); - let mut cache = Cache::default(); - let small = Surface::new(FORMAT); - let small_bytes = entry_bytes(&small, None); - cache.insert(1, small, None, small_bytes, bytes - 1, cache.generation); - let tile = surface.tiles().next().unwrap().1.clone(); - let owners = Arc::strong_count(&tile); - cache.insert(2, surface.clone(), None, bytes, bytes - 1, cache.generation); - assert!(cache.get(2).is_none()); - assert!(cache.get(1).is_some()); - assert_eq!(cache.bytes, small_bytes); - assert_eq!(Arc::strong_count(&tile), owners); - assert_eq!(surface.pixel(0, 0), vec![0.0]); - } - - #[test] - fn replacement_and_purge_release_accounted_bytes_and_tile_references() { - let first = one_tile(SampleType::U8); - let second = one_tile(SampleType::F32); - let first_bytes = entry_bytes(&first, None); - let second_bytes = entry_bytes(&second, None); - let first_tile = first.tiles().next().unwrap().1.clone(); - let second_tile = second.tiles().next().unwrap().1.clone(); - let mut cache = Cache::default(); - cache.insert(1, first.clone(), None, first_bytes, CACHE_BUDGET, cache.generation); - assert_eq!(Arc::strong_count(&first_tile), 3); - cache.insert(1, second.clone(), None, second_bytes, CACHE_BUDGET, cache.generation); - assert_eq!(cache.bytes, second_bytes); - assert_eq!(cache.map.len(), 1); - assert_eq!(Arc::strong_count(&first_tile), 2); - assert_eq!(Arc::strong_count(&second_tile), 3); - assert_eq!(cache.clear(), second_bytes); - assert_eq!(cache.bytes, 0); - assert!(cache.map.is_empty()); - assert_eq!(Arc::strong_count(&second_tile), 2); - assert_eq!(cache.clear(), 0); - } - - #[test] - fn a_build_started_before_purge_cannot_refill_the_cache() { - let surface = one_tile(SampleType::F32); - let bytes = entry_bytes(&surface, None); - let mut cache = Cache::default(); - assert!(cache.get(1).is_none()); - let generation_before_purge = cache.generation; - cache.clear(); - cache.insert(1, surface.clone(), None, bytes, CACHE_BUDGET, generation_before_purge); - assert!(cache.map.is_empty()); - assert_eq!(cache.bytes, 0); - cache.insert(1, surface, None, bytes, CACHE_BUDGET, cache.generation); - assert!(cache.get(1).is_some()); - } - - #[test] - fn pixel_edits_refresh_cached_masks_at_every_depth() { - let canvas = Rect::new(0, 0, 64, 64); - for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { - let mut layer = Layer::raster("edited mask", PixelFormat::RGBA8); - let mut mask = LayerMask::hide_all(); - mask.surface = Surface::new(PixelFormat { sample, ..FORMAT }); - mask.surface.fill_rect(canvas, &[1.0]); - mask.feather = 4.0; - layer.mask = Some(mask); - - let first = combined_mask(&layer, canvas).unwrap(); - assert!((first.sample_channel(32, 32, 0) - 1.0).abs() < 1e-6); - drop(first); - // No document/undo snapshot shares the input. Previously this write could - // reuse the original tile address and return the old cached white mask. - layer.mask.as_mut().unwrap().surface.fill_rect(canvas, &[0.0]); - let edited = combined_mask(&layer, canvas).unwrap(); - assert_eq!(edited.sample_channel(32, 32, 0), 0.0, "{sample:?}"); - - layer.mask.as_mut().unwrap().surface.fill_rect(canvas, &[0.5]); - let repainted = combined_mask(&layer, canvas).unwrap(); - assert!((repainted.sample_channel(32, 32, 0) - 0.5).abs() < 0.005, "{sample:?}"); - let warm = combined_mask(&layer, canvas).unwrap(); - assert!(repainted.tiles().zip(warm.tiles()).all(|((_, a), (_, b))| Arc::ptr_eq(a, b))); - } - } - - #[test] - fn cache_budget_holds_five_50mp_u8_input_u16_result_masks() { - // Account for whole 256×256 tiles, as entry_bytes does, rather than just logical pixels. - let (w, h) = (6336usize, 7920usize); - let tile = photocraft_geom::TILE_SIZE as usize; - let tile_count = w.div_ceil(tile) * h.div_ceil(tile); - let tile_pixels = tile * tile; - let one_entry = tile_count * tile_pixels * (SampleType::U8.bytes() + FORMAT.sample.bytes()); - assert!(one_entry.saturating_mul(5) <= CACHE_BUDGET, "five reported-size masks must fit"); - - let mut cache = Cache::default(); - let surface = Surface::new(FORMAT); - for key in 0..5 { - cache.insert(key, surface.clone(), None, one_entry, CACHE_BUDGET, cache.generation); - } - for key in 0..5 { - assert!(cache.get(key).is_some(), "mask {key} was evicted before the next plan"); - } - } - - #[test] - fn matches_the_cpu_mask_and_is_cached() { - let mut l = Layer::raster("l", PixelFormat::RGBA8); - let pts = [(5.0, 5.0), (30.0, 6.0), (20.0, 28.0)]; - let knots = pts.iter().map(|&(x, y)| Knot::corner(x, y)).collect(); - let mut path = Path::default(); - path.subpaths.push(Subpath { knots, closed: true, ..Default::default() }); - let mut vm = VectorMask::new(path); - vm.density = 0.9; - l.vector_mask = Some(vm); - let canvas = Rect::new(0, 0, 40, 32); - let s = combined_mask(&l, canvas).unwrap(); - let want = photocraft_vector::vector_mask_values(l.vector_mask.as_ref().unwrap(), canvas); - let mut got = Vec::new(); - s.read_region_into(canvas, &mut got); - for (a, b) in got.iter().zip(&want) { - assert!((a - b).abs() <= 1.0 / f32::from(u16::MAX)); - } - let again = combined_mask(&l, canvas).unwrap(); - assert!(s.tiles().zip(again.tiles()).all(|(a, b)| Arc::ptr_eq(a.1, b.1))); - l.vector_mask = None; - assert!(combined_mask(&l, canvas).is_none()); - } - - #[test] - fn hostile_path_coordinates_do_not_overflow() { - let mut l = Layer::raster("l", PixelFormat::RGBA8); - let knots = [(-1.0e30, -1.0e30), (1.0e30, 0.0), (0.0, 1.0e30)].iter().map(|&(x, y)| Knot::corner(x, y)).collect(); - let mut path = Path::default(); - path.subpaths.push(Subpath { knots, closed: true, ..Default::default() }); - l.vector_mask = Some(VectorMask::new(path)); - let _ = combined_mask(&l, Rect::new(0, 0, 8, 8)); - } -} +mod tests; diff --git a/crates/compose/src/masks/tests.rs b/crates/compose/src/masks/tests.rs new file mode 100644 index 0000000000..b6aa42fe1f --- /dev/null +++ b/crates/compose/src/masks/tests.rs @@ -0,0 +1,353 @@ +use super::*; +use photocraft_doc::LayerMask; +use photocraft_doc::vector::{Knot, Path, Subpath, VectorMask}; + +fn pending(c: &Mutex, k: u64) -> Arc> { + match lookup(c, k) { + CachedMask::Pending(slot, _) => slot, + CachedMask::Hit(_) => panic!("expected a cold mask"), + } +} + +/// A built mask (and no pixel-mask input), as `finish_mask`'s build returns it. +fn test_surface() -> (Surface, Option) { + let mut surface = Surface::new(FORMAT); + surface.fill_rect(Rect::new(0, 0, 2, 2), &[0.5]); + (surface, None) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn cold_callers_share_one_build_without_retaining_a_second_cache() { + use std::sync::Barrier; + use std::sync::atomic::{AtomicUsize, Ordering}; + + let c = Mutex::new(Cache::default()); + // Acquire all callers' slots before allowing any builder to finish. + let slots: Vec<_> = (0..8).map(|_| pending(&c, 7)).collect(); + assert!(slots.iter().all(|slot| Arc::ptr_eq(slot, &slots[0]))); + let barrier = Barrier::new(slots.len()); + let builds = AtomicUsize::new(0); + let outputs = std::thread::scope(|scope| { + let handles: Vec<_> = slots + .iter() + .map(|slot| { + let (c, barrier, builds) = (&c, &barrier, &builds); + scope.spawn(move || { + barrier.wait(); + finish_mask(c, 7, slot, 0, || { + builds.fetch_add(1, Ordering::SeqCst); + test_surface() + }) + }) + }) + .collect(); + handles.into_iter().map(|handle| handle.join().unwrap()).collect::>() + }); + assert_eq!(builds.load(Ordering::SeqCst), 1); + assert!(outputs.iter().all(|surface| Arc::ptr_eq(surface.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1))); + + // Evicting the retained result cannot make existing callers build again. + c.lock().unwrap().map.clear(); + let again = finish_mask(&c, 7, &slots[0], 0, || panic!("rebuilt an active slot")); + assert!(Arc::ptr_eq(again.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1)); + drop(slots); + let next = pending(&c, 8); + assert_eq!(c.lock().unwrap().in_flight.len(), 1); + drop(next); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn distinct_keys_build_while_another_key_is_paused() { + use std::sync::mpsc; + use std::time::Duration; + + let c = Mutex::new(Cache::default()); + let (started_tx, started_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let (second_tx, second_rx) = mpsc::channel(); + std::thread::scope(|scope| { + let c = &c; + let first = scope.spawn(move || { + cached_mask(c, 1, || { + started_tx.send(()).unwrap(); + release_rx.recv_timeout(Duration::from_secs(10)).unwrap(); + test_surface() + }) + }); + started_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + let second = scope.spawn(move || { + let surface = cached_mask(c, 2, test_surface); + second_tx.send(surface.sample_channel(0, 0, 0)).unwrap(); + }); + assert!((second_rx.recv_timeout(Duration::from_secs(5)).unwrap() - 0.5).abs() <= 1.0 / f32::from(u16::MAX)); + release_tx.send(()).unwrap(); + first.join().unwrap(); + second.join().unwrap(); + }); +} + +#[test] +fn obsolete_in_flight_build_does_not_repopulate_the_cache() { + let c = Mutex::new(Cache::default()); + let old = pending(&c, 1); + c.lock().unwrap().in_flight.clear(); + let current = pending(&c, 1); + assert!(!Arc::ptr_eq(&old, ¤t)); + let old_surface = finish_mask(&c, 1, &old, 0, test_surface); + assert!(c.lock().unwrap().map.is_empty()); + let current_surface = finish_mask(&c, 1, ¤t, 0, test_surface); + assert!(!Arc::ptr_eq(old_surface.tiles().next().unwrap().1, current_surface.tiles().next().unwrap().1)); + assert_eq!(c.lock().unwrap().map.len(), 1); +} + +#[test] +fn a_purge_during_a_shared_build_keeps_the_cache_empty() { + let c = Mutex::new(Cache::default()); + let CachedMask::Pending(slot, generation) = lookup(&c, 1) else { panic!("expected a cold mask") }; + c.lock().unwrap().clear(); + finish_mask(&c, 1, &slot, generation, test_surface); + assert!(c.lock().unwrap().map.is_empty()); + assert_eq!(c.lock().unwrap().bytes, 0); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn parallel_feathered_pixel_mask_returns_the_same_tiles() { + let canvas = Rect::new(0, 0, 600, 400); + let mut layer = Layer::raster("cold shared mask", PixelFormat::RGBA8); + let mut mask = photocraft_doc::LayerMask::reveal_all(); + mask.surface.fill_rect(canvas, &[0.5]); + mask.feather = 8.0; + layer.mask = Some(mask); + let barrier = std::sync::Barrier::new(8); + let outputs = std::thread::scope(|scope| { + let handles: Vec<_> = (0..8) + .map(|_| { + let (layer, barrier) = (&layer, &barrier); + scope.spawn(move || { + barrier.wait(); + combined_mask(layer, canvas).unwrap() + }) + }) + .collect(); + handles.into_iter().map(|handle| handle.join().unwrap()).collect::>() + }); + assert!(outputs.iter().all(|surface| Arc::ptr_eq(surface.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1))); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn vector_mask_build_inside_a_small_rayon_pool_completes() { + use rayon::prelude::*; + use std::sync::mpsc; + use std::time::Duration; + + let (tx, rx) = mpsc::channel(); + let handle = std::thread::spawn(move || { + let canvas = Rect::new(0, 0, 512, 512); + let mut layer = Layer::raster("rayon vector mask", PixelFormat::RGBA8); + let mut mask = VectorMask::new(photocraft_vector::shapes::ellipse(8.0, 8.0, 496.0, 496.0)); + mask.feather = 8.0; + layer.vector_mask = Some(mask); + let pool = rayon::ThreadPoolBuilder::new().num_threads(2).build().unwrap(); + let outputs: Vec<_> = pool.install(|| (0..8).into_par_iter().map(|_| combined_mask(&layer, canvas).unwrap()).collect()); + assert!(outputs.iter().all(|surface| Arc::ptr_eq(surface.tiles().next().unwrap().1, outputs[0].tiles().next().unwrap().1))); + tx.send(()).unwrap(); + }); + rx.recv_timeout(Duration::from_secs(10)).expect("mask initializer deadlocked inside Rayon"); + handle.join().unwrap(); +} + +fn one_tile(sample: SampleType) -> Surface { + let mut surface = Surface::with_default(PixelFormat { mode: ColorMode::Grayscale, sample, alpha: false }, &[1.0]); + surface.fill_rect(Rect::new(0, 0, 1, 1), &[0.0]); + surface +} + +#[test] +fn charges_input_and_output_at_every_depth_including_off_canvas_tiles() { + let result = one_tile(SampleType::F32); + for sample in SampleType::ALL { + let mut input = one_tile(sample); + input.fill_rect(Rect::new(1024, 1024, 1025, 1025), &[0.0]); + let tile_pixels = (photocraft_geom::TILE_SIZE * photocraft_geom::TILE_SIZE) as usize; + let expected = tile_pixels * (SampleType::F32.bytes() + 2 * sample.bytes()) + SampleType::F32.bytes() + sample.bytes(); + let bytes = entry_bytes(&result, Some(&input)); + assert_eq!(bytes, expected, "{sample:?}"); + let mut cache = Cache::default(); + cache.insert(1, result.clone(), None, bytes, bytes * 2, cache.generation); + cache.insert(2, result.clone(), None, bytes, bytes * 2, cache.generation); + assert_eq!(cache.bytes, bytes * 2, "shared tiles are conservatively charged per entry"); + } +} + +#[test] +fn byte_budget_evicts_the_least_recently_used_entry() { + let surface = one_tile(SampleType::F32); + let bytes = entry_bytes(&surface, None); + let mut cache = Cache::default(); + cache.insert(1, surface.clone(), None, bytes, bytes * 2, cache.generation); + cache.insert(2, surface.clone(), None, bytes, bytes * 2, cache.generation); + assert!(cache.get(1).is_some()); + cache.insert(3, surface, None, bytes, bytes * 2, cache.generation); + assert!(cache.get(2).is_none()); + assert!(cache.get(1).is_some()); + assert!(cache.get(3).is_some()); + assert_eq!(cache.bytes, bytes * 2); +} + +#[test] +fn entry_limit_also_bounds_masks_with_no_tiles() { + let surface = Surface::new(FORMAT); + let bytes = entry_bytes(&surface, None); + let mut cache = Cache::default(); + for key in 0..CAPACITY as u64 { + cache.insert(key, surface.clone(), None, bytes, CACHE_BUDGET, cache.generation); + } + assert!(cache.get(0).is_some()); + cache.insert(CAPACITY as u64, surface, None, bytes, CACHE_BUDGET, cache.generation); + assert_eq!(cache.map.len(), CAPACITY); + assert!(cache.get(1).is_none()); + assert!(cache.get(0).is_some()); + assert_eq!(cache.bytes, bytes * CAPACITY); +} + +#[test] +fn oversized_results_are_usable_without_retention_or_other_eviction() { + let surface = one_tile(SampleType::F32); + let bytes = entry_bytes(&surface, None); + let mut cache = Cache::default(); + let small = Surface::new(FORMAT); + let small_bytes = entry_bytes(&small, None); + cache.insert(1, small, None, small_bytes, bytes - 1, cache.generation); + let tile = surface.tiles().next().unwrap().1.clone(); + let owners = Arc::strong_count(&tile); + cache.insert(2, surface.clone(), None, bytes, bytes - 1, cache.generation); + assert!(cache.get(2).is_none()); + assert!(cache.get(1).is_some()); + assert_eq!(cache.bytes, small_bytes); + assert_eq!(Arc::strong_count(&tile), owners); + assert_eq!(surface.pixel(0, 0), vec![0.0]); +} + +#[test] +fn replacement_and_purge_release_accounted_bytes_and_tile_references() { + let first = one_tile(SampleType::U8); + let second = one_tile(SampleType::F32); + let first_bytes = entry_bytes(&first, None); + let second_bytes = entry_bytes(&second, None); + let first_tile = first.tiles().next().unwrap().1.clone(); + let second_tile = second.tiles().next().unwrap().1.clone(); + let mut cache = Cache::default(); + cache.insert(1, first.clone(), None, first_bytes, CACHE_BUDGET, cache.generation); + assert_eq!(Arc::strong_count(&first_tile), 3); + cache.insert(1, second.clone(), None, second_bytes, CACHE_BUDGET, cache.generation); + assert_eq!(cache.bytes, second_bytes); + assert_eq!(cache.map.len(), 1); + assert_eq!(Arc::strong_count(&first_tile), 2); + assert_eq!(Arc::strong_count(&second_tile), 3); + assert_eq!(cache.clear(), second_bytes); + assert_eq!(cache.bytes, 0); + assert!(cache.map.is_empty()); + assert_eq!(Arc::strong_count(&second_tile), 2); + assert_eq!(cache.clear(), 0); +} + +#[test] +fn a_build_started_before_purge_cannot_refill_the_cache() { + let surface = one_tile(SampleType::F32); + let bytes = entry_bytes(&surface, None); + let mut cache = Cache::default(); + assert!(cache.get(1).is_none()); + let generation_before_purge = cache.generation; + cache.clear(); + cache.insert(1, surface.clone(), None, bytes, CACHE_BUDGET, generation_before_purge); + assert!(cache.map.is_empty()); + assert_eq!(cache.bytes, 0); + cache.insert(1, surface, None, bytes, CACHE_BUDGET, cache.generation); + assert!(cache.get(1).is_some()); +} + +#[test] +fn pixel_edits_refresh_cached_masks_at_every_depth() { + let canvas = Rect::new(0, 0, 64, 64); + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut layer = Layer::raster("edited mask", PixelFormat::RGBA8); + let mut mask = LayerMask::hide_all(); + mask.surface = Surface::new(PixelFormat { sample, ..FORMAT }); + mask.surface.fill_rect(canvas, &[1.0]); + mask.feather = 4.0; + layer.mask = Some(mask); + + let first = combined_mask(&layer, canvas).unwrap(); + assert!((first.sample_channel(32, 32, 0) - 1.0).abs() < 1e-6); + drop(first); + // No document/undo snapshot shares the input. Previously this write could + // reuse the original tile address and return the old cached white mask. + layer.mask.as_mut().unwrap().surface.fill_rect(canvas, &[0.0]); + let edited = combined_mask(&layer, canvas).unwrap(); + assert_eq!(edited.sample_channel(32, 32, 0), 0.0, "{sample:?}"); + + layer.mask.as_mut().unwrap().surface.fill_rect(canvas, &[0.5]); + let repainted = combined_mask(&layer, canvas).unwrap(); + assert!((repainted.sample_channel(32, 32, 0) - 0.5).abs() < 0.005, "{sample:?}"); + let warm = combined_mask(&layer, canvas).unwrap(); + assert!(repainted.tiles().zip(warm.tiles()).all(|((_, a), (_, b))| Arc::ptr_eq(a, b))); + } +} + +#[test] +fn cache_budget_holds_five_50mp_u8_input_u16_result_masks() { + // Account for whole 256×256 tiles, as entry_bytes does, rather than just logical pixels. + let (w, h) = (6336usize, 7920usize); + let tile = photocraft_geom::TILE_SIZE as usize; + let tile_count = w.div_ceil(tile) * h.div_ceil(tile); + let tile_pixels = tile * tile; + let one_entry = tile_count * tile_pixels * (SampleType::U8.bytes() + FORMAT.sample.bytes()); + assert!(one_entry.saturating_mul(5) <= CACHE_BUDGET, "five reported-size masks must fit"); + + let mut cache = Cache::default(); + let surface = Surface::new(FORMAT); + for key in 0..5 { + cache.insert(key, surface.clone(), None, one_entry, CACHE_BUDGET, cache.generation); + } + for key in 0..5 { + assert!(cache.get(key).is_some(), "mask {key} was evicted before the next plan"); + } +} + +#[test] +fn matches_the_cpu_mask_and_is_cached() { + let mut l = Layer::raster("l", PixelFormat::RGBA8); + let pts = [(5.0, 5.0), (30.0, 6.0), (20.0, 28.0)]; + let knots = pts.iter().map(|&(x, y)| Knot::corner(x, y)).collect(); + let mut path = Path::default(); + path.subpaths.push(Subpath { knots, closed: true, ..Default::default() }); + let mut vm = VectorMask::new(path); + vm.density = 0.9; + l.vector_mask = Some(vm); + let canvas = Rect::new(0, 0, 40, 32); + let s = combined_mask(&l, canvas).unwrap(); + let want = photocraft_vector::vector_mask_values(l.vector_mask.as_ref().unwrap(), canvas); + let mut got = Vec::new(); + s.read_region_into(canvas, &mut got); + for (a, b) in got.iter().zip(&want) { + assert!((a - b).abs() <= 1.0 / f32::from(u16::MAX)); + } + let again = combined_mask(&l, canvas).unwrap(); + assert!(s.tiles().zip(again.tiles()).all(|(a, b)| Arc::ptr_eq(a.1, b.1))); + l.vector_mask = None; + assert!(combined_mask(&l, canvas).is_none()); +} + +#[test] +fn hostile_path_coordinates_do_not_overflow() { + let mut l = Layer::raster("l", PixelFormat::RGBA8); + let knots = [(-1.0e30, -1.0e30), (1.0e30, 0.0), (0.0, 1.0e30)].iter().map(|&(x, y)| Knot::corner(x, y)).collect(); + let mut path = Path::default(); + path.subpaths.push(Subpath { knots, closed: true, ..Default::default() }); + l.vector_mask = Some(VectorMask::new(path)); + let _ = combined_mask(&l, Rect::new(0, 0, 8, 8)); +} From 13ae69db56df7ac20ef533e75930010500d85c00 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:45 +0000 Subject: [PATCH 114/259] refactor(automation): move workspace.rs tests to workspace/tests.rs --- crates/automation/src/workspace.rs | 596 +---------------------- crates/automation/src/workspace/tests.rs | 581 ++++++++++++++++++++++ 2 files changed, 582 insertions(+), 595 deletions(-) create mode 100644 crates/automation/src/workspace/tests.rs diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 12e7329180..13cbbb2169 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -483,598 +483,4 @@ impl Drop for ExportSequence { } #[cfg(test)] -mod tests { - use super::*; - - fn roots(name: &str) -> (PathBuf, PathBuf, AuthorizedWorkspace) { - let base = std::env::temp_dir().join(format!("photocraft-workspace-{}-{name}", std::process::id())); - let inside = base.join("inside"); - let outside = base.join("outside"); - let _ = std::fs::remove_dir_all(&base); - std::fs::create_dir_all(&inside).unwrap(); - std::fs::create_dir_all(&outside).unwrap(); - let workspace = AuthorizedWorkspace::new(Some(&inside), Some(&inside)).unwrap(); - (inside, outside, workspace) - } - - #[test] - fn export_cleanup_owns_only_created_files_even_during_unwind() { - let (inside, _, workspace) = roots("export-cleanup"); - std::fs::create_dir(inside.join("frames")).unwrap(); - std::fs::write(inside.join("frames/clip_0009.png"), b"old").unwrap(); - let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let mut export = workspace.export_sequence("frames").unwrap(); - export.write("clip_0000.png", b"new").unwrap(); - assert!(export.write("clip_0009.png", b"overwrite").is_err()); - assert!(export.write("../escape.png", b"escape").is_err()); - panic!("rendering panic"); - })); - assert!(panic.is_err()); - assert_eq!(std::fs::read_dir(inside.join("frames")).unwrap().count(), 1); - assert_eq!(std::fs::read(inside.join("frames/clip_0009.png")).unwrap(), b"old"); - assert!(AuthorizedWorkspace::default().export_sequence("frames").is_err()); - } - - #[cfg(unix)] - #[test] - fn export_directory_symlinks_cannot_escape_the_granted_root() { - let (inside, outside, workspace) = roots("export-symlink"); - std::os::unix::fs::symlink(&outside, inside.join("escape")).unwrap(); - assert!(workspace.export_sequence("escape").is_err()); - assert_eq!(std::fs::read_dir(outside).unwrap().count(), 0); - } - - #[test] - fn valid_read_and_nonexistent_output_write_stay_in_root() { - let (inside, _, workspace) = roots("valid"); - std::fs::write(inside.join("read.txt"), b"canary").unwrap(); - assert_eq!(workspace.read("read.txt").unwrap(), b"canary"); - workspace.write("new-output.txt", b"created").unwrap(); - assert_eq!(std::fs::read(inside.join("new-output.txt")).unwrap(), b"created"); - } - - #[test] - fn large_observed_length_does_not_trigger_a_fixed_limit_or_upfront_reservation() { - let mut shortened = std::io::Cursor::new(b"psb"); - assert_eq!(read_to_observed_length(&mut shortened, (1 << 30) + 1).unwrap(), b"psb"); - } - - #[test] - fn read_growth_is_rejected_at_the_observed_length() { - let mut growing = std::io::repeat(b'x').take(65); - let error = read_to_observed_length(&mut growing, 64).unwrap_err().to_string(); - assert!(error.contains("grew beyond its observed length of 64 bytes"), "{error}"); - let mut allowed = std::io::repeat(b'x').take(64); - assert_eq!(read_to_observed_length(&mut allowed, 64).unwrap().len(), 64); - let mut empty = std::io::Cursor::new(b"x"); - assert!(read_to_observed_length(&mut empty, 0).is_err()); - } - - #[test] - fn open_pcraft_loads_a_directory_below_the_read_root() { - let (inside, _, workspace) = roots("pcraft-dir"); - let doc = photocraft_doc::Document::new("Native", photocraft_doc::Size::new(16, 12), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); - photocraft_format::PcraftWriter::new().save_dir(&doc, &inside.join("native.pcraft"), &photocraft_format::SaveOptions::default()).unwrap(); - let loaded = workspace.open_pcraft("native.pcraft").unwrap().expect("the directory form loads"); - assert_eq!(loaded.name, doc.name); - assert_eq!((loaded.size.width, loaded.size.height), (16, 12)); - } - - #[test] - fn open_pcraft_reports_zip_files_and_missing_paths_clearly() { - let (inside, _, workspace) = roots("pcraft-errors"); - let doc = photocraft_doc::Document::new("Zipped", photocraft_doc::Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); - let zip = inside.join("zipped.pcraft"); - photocraft_format::PcraftWriter::new().save_path(&doc, &zip, &photocraft_format::SaveOptions::default()).unwrap(); - assert!(zip.is_file()); - assert!(workspace.open_pcraft("zipped.pcraft").unwrap().is_none(), "the zip form falls back to the bytes path"); - let error = workspace.open_pcraft("missing.pcraft").unwrap_err().to_string(); - assert!(error.contains("failed"), "a missing path propagates its io error: {error}"); - assert!(AuthorizedWorkspace::default().open_pcraft("x.pcraft").is_err(), "no read authority fails closed"); - } - - #[cfg(unix)] - #[test] - fn open_pcraft_rejects_non_regular_entries_and_escaping_symlinks() { - let (inside, _, workspace) = roots("pcraft-nonregular"); - let bundle = inside.join("native.pcraft"); - std::fs::create_dir_all(bundle.join("manifest.json")).unwrap(); - let error = workspace.open_pcraft("native.pcraft").unwrap_err().to_string(); - assert!(error.contains("not a regular file"), "a directory entry is refused, not streamed: {error}"); - - let (inside2, _, workspace2) = roots("pcraft-symlink"); - let bundle2 = inside2.join("native.pcraft"); - std::fs::create_dir(&bundle2).unwrap(); - std::os::unix::fs::symlink("/dev/zero", bundle2.join("manifest.json")).unwrap(); - assert!(workspace2.open_pcraft("native.pcraft").is_err(), "an escaping symlink entry is refused"); - } - - fn temp_files(dir: &Path) -> Vec { - std::fs::read_dir(dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".tmp")).collect() - } - - #[test] - fn write_replaces_atomically_and_leaves_no_temp_file() { - let (inside, _, workspace) = roots("atomic"); - std::fs::create_dir_all(inside.join("sub")).unwrap(); - workspace.write("sub/out.psd", b"original").unwrap(); - workspace.write("sub/out.psd", b"replacement").unwrap(); - assert_eq!(std::fs::read(inside.join("sub/out.psd")).unwrap(), b"replacement"); - assert!(temp_files(&inside.join("sub")).is_empty()); - // Renaming over a directory fails: nothing is left behind and the directory survives. - std::fs::create_dir_all(inside.join("adir")).unwrap(); - assert!(workspace.write("adir", b"x").is_err()); - assert!(inside.join("adir").is_dir()); - assert!(temp_files(&inside).is_empty()); - } - - /// #7095: replacing a file through the automation path keeps the old file's extended - /// attributes, the same as a save through `atomic_write` does. - #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] - #[test] - fn write_keeps_the_replaced_files_extended_attributes() { - #[cfg(target_os = "macos")] - const TAG: &str = "com.apple.metadata:_kMDItemUserTags"; - #[cfg(not(target_os = "macos"))] - const TAG: &str = "user.photocraft.test"; - - let (inside, _, workspace) = roots("xattr"); - let path = inside.join("doc.psd"); - workspace.write("doc.psd", b"original").unwrap(); - if rustix::fs::setxattr(&path, TAG, b"tagged", rustix::fs::XattrFlags::empty()).is_err() { - return; // a file system without extended attributes: nothing to assert - } - - workspace.write("doc.psd", b"replacement, longer").unwrap(); - - assert_eq!(std::fs::read(&path).unwrap(), b"replacement, longer"); - let mut buf = [0u8; 64]; - let len = rustix::fs::getxattr(&path, TAG, buf.as_mut_slice()).expect("the attribute was dropped"); - assert_eq!(&buf[..len], b"tagged"); - assert!(temp_files(&inside).is_empty()); - } - - #[cfg(unix)] - #[test] - fn write_into_read_only_folder_keeps_the_original() { - use std::os::unix::fs::PermissionsExt; - let (inside, _, workspace) = roots("readonly"); - let ro = inside.join("ro"); - std::fs::create_dir_all(&ro).unwrap(); - std::fs::write(ro.join("doc.psd"), b"original").unwrap(); - std::fs::set_permissions(&ro, std::fs::Permissions::from_mode(0o555)).unwrap(); - let root_user = std::fs::File::create(ro.join("probe")).is_ok(); - if !root_user { - assert!(workspace.write("ro/doc.psd", b"new").is_err()); - assert_eq!(std::fs::read(ro.join("doc.psd")).unwrap(), b"original"); - assert!(temp_files(&ro).is_empty()); - } - std::fs::set_permissions(&ro, std::fs::Permissions::from_mode(0o755)).unwrap(); - } - - #[test] - fn rejects_absolute_traversal_mixed_prefix_and_malformed_paths_without_panicking() { - let (_, _, workspace) = roots("reject"); - for path in [ - "", - "/absolute", - "../escape", - "a/../escape", - "a\\..\\escape", - "a\\b", - "C:/escape", - "a//b", - "./a", - "name:stream", - "NUL", - "con.txt", - "folder/COM1.log", - ] { - assert!(workspace.read(path).is_err(), "read accepted {path:?}"); - assert!(workspace.write(path, b"x").is_err(), "write accepted {path:?}"); - } - } - - #[test] - fn read_and_write_authority_are_separate() { - let (inside, _, _) = roots("separate"); - std::fs::write(inside.join("read.txt"), b"canary").unwrap(); - let read_only = AuthorizedWorkspace::new(Some(&inside), None).unwrap(); - assert_eq!(read_only.read("read.txt").unwrap(), b"canary"); - assert!(read_only.write("blocked.txt", b"x").is_err()); - let write_only = AuthorizedWorkspace::new(None, Some(&inside)).unwrap(); - assert!(write_only.read("read.txt").is_err()); - write_only.write("written.txt", b"ok").unwrap(); - } - - #[test] - fn missing_parent_is_a_stable_error_before_any_file_is_created() { - let (inside, _, workspace) = roots("missing-parent"); - let error = workspace.write("missing/output.txt", b"x").unwrap_err().to_string(); - assert!(error.contains("automation write"), "{error}"); - assert!(!inside.join("missing").exists()); - } - - #[cfg(unix)] - #[test] - fn symlink_escape_is_rejected() { - use std::os::unix::fs::symlink; - - let (inside, outside, workspace) = roots("symlink"); - std::fs::write(outside.join("secret.txt"), b"outside").unwrap(); - symlink(&outside, inside.join("link")).unwrap(); - assert!(workspace.read("link/secret.txt").is_err()); - assert!(workspace.write("link/new.txt", b"blocked").is_err()); - assert!(!outside.join("new.txt").exists()); - } - - #[cfg(windows)] - #[test] - fn windows_symlink_escape_is_rejected_when_supported() { - use std::os::windows::fs::symlink_dir; - - let (inside, outside, workspace) = roots("windows-link"); - std::fs::write(outside.join("secret.txt"), b"outside").unwrap(); - if symlink_dir(&outside, inside.join("link")).is_err() { - return; - } - assert!(workspace.read("link/secret.txt").is_err()); - assert!(workspace.write("link/new.txt", b"blocked").is_err()); - assert!(!outside.join("new.txt").exists()); - } - - #[cfg(windows)] - #[test] - fn windows_junction_escape_is_rejected_when_supported() { - use std::process::Command; - - let (inside, outside, workspace) = roots("windows-junction"); - std::fs::write(outside.join("secret.txt"), b"outside").unwrap(); - let link = inside.join("junction"); - let status = Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(&link).arg(&outside).status(); - if !status.is_ok_and(|status| status.success()) { - return; - } - assert!(workspace.read("junction/secret.txt").is_err()); - assert!(workspace.write("junction/new.txt", b"blocked").is_err()); - assert!(!outside.join("new.txt").exists()); - let _ = std::fs::remove_dir(link); - } - - #[test] - fn filesystem_commands_fail_closed() { - for id in [ - "file.open", - "file.openAs", - "file.save", - "file.saveAs", - "file.saveACopy", - "file.export.saveForWebLegacy", - "pattern.import", - "layer.smartObjects.exportContents", - "layer.smartObjects.replaceContents", - "layer.smartObjects.relinkToFile", - "layer.smartObjects.convertToLinked", - "measurementLog.export", - "layer.videoLayers.reloadFrame", - "edit.colorSettings", - ] { - assert!(authorize_engine_command(id, &serde_json::json!({})).is_err()); - } - assert!(authorize_engine_command("file.new", &serde_json::json!({})).is_ok()); - assert!(authorize_engine_command("file.automate.cropAndStraightenPhotos", &serde_json::json!({})).is_ok()); - assert!(authorize_desktop_engine_command("file.automate.cropAndStraightenPhotos", &serde_json::json!({})).is_ok()); - for id in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers", "layer.smartObjects.saveContents"] { - assert!(authorize_desktop_engine_command(id, &serde_json::json!({"layer": 19})).is_ok(), "{id}"); - } - for id in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers"] { - assert!(authorize_engine_command(id, &serde_json::json!({"path": "/outside/source.psb"})).is_err(), "{id}"); - } - // The UI-level examples in docs/control-protocol.md. - for id in ["view.zoomIn", "window.theme.pro", "edit.search"] { - assert!(authorize_desktop_engine_command(id, &serde_json::json!({})).is_ok(), "{id}"); - } - assert!(authorize_engine_command("image.mode.cmyk", &serde_json::json!({})).is_ok()); - assert!(authorize_desktop_engine_command("image.mode.cmyk", &serde_json::json!({})).is_err()); - assert!(authorize_engine_command("image.mode.rgb", &serde_json::json!({"profile": "/outside/profile.icc"})).is_err()); - assert!(authorize_engine_command("image.mode.rgb", &serde_json::json!({"profile": "srgb"})).is_ok()); - assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "/outside/profile.icc"})).is_err()); - assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "adobe-rgb-compat"})).is_ok()); - assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "working"})).is_ok()); - assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "none"})).is_ok()); - assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "default"})).is_err()); - assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "working-cmyk"})).is_err()); - // Shortcut sets: text in and out is fine; a path reads or writes the filesystem. - let ks = |p: serde_json::Value| authorize_engine_command("edit.keyboardShortcuts", &p); - assert!(ks(serde_json::json!({"exportKys": true, "summarize": true, "importKys": ""})).is_ok()); - for key in ["importKys", "exportKys", "summarize"] { - assert!(ks(serde_json::json!({ key: {"path": "/outside/set.kys"} })).is_err(), "{key}"); - } - assert!(authorize_engine_command("filter.distort.displace", &serde_json::json!({"mapPath": "outside.png"})).is_err()); - assert!(authorize_engine_command("layer.setAdjustment", &serde_json::json!({"file": "outside.cube"})).is_err()); - assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "colorSettings.workingRgb", "value": "outside.icc"})).is_err()); - assert!(authorize_engine_step("file.open", &serde_json::json!({})).is_err()); - assert!(authorize_engine_step("actions.play", &serde_json::json!({})).is_ok()); - // An allowed command can't reach a denied one by running it on its own behalf. - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", serde_json::json!({"width": 4, "height": 4})).unwrap(); - session.authorize = Some(authorize_desktop_engine_step); - let params = serde_json::json!({"to": "grayscale"}); - assert!(authorize_desktop_engine_command("file.automate.conditionalModeChange", ¶ms).is_ok()); - assert!(session.execute("file.automate.conditionalModeChange", params).is_err()); - assert_eq!(session.active().unwrap().doc.mode, photocraft_engine::doc::ColorMode::Rgb); - assert!(authorize_desktop_engine_step("file.saveACopy", &serde_json::json!({})).is_err()); - } - - // Regression test for #3763: `edit.installedProfiles` scans the OS and user ICC folders but - // takes no path parameter, so automation let it through until it was listed as ambient. - #[test] - fn installed_profiles_listing_is_refused_for_automation() { - for params in [serde_json::json!({}), serde_json::json!({"class": "output", "colorSpace": "cmyk"})] { - assert!(authorize_engine_command("edit.installedProfiles", ¶ms).is_err(), "authorize_engine_command allowed it with {params}"); - assert!(authorize_desktop_engine_command("edit.installedProfiles", ¶ms).is_err(), "authorize_desktop_engine_command allowed it with {params}"); - assert!(authorize_engine_step("edit.installedProfiles", ¶ms).is_err(), "authorize_engine_step allowed it with {params}"); - } - // The sandboxed session refuses it before the engine scans any folder. - let mut headless = crate::Headless::new(); - let refused = headless.command_run("edit.installedProfiles", serde_json::json!({})).unwrap_err(); - assert!(refused.to_string().contains("ambient filesystem paths"), "{refused}"); - } - - #[test] - fn apply_data_set_is_judged_by_the_values_it_applies() { - let mut headless = crate::Headless::new(); - headless.command_run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); - let layer = headless.command_run("layer.new.layer", serde_json::json!({})).unwrap()["layer"].clone(); - let defs = [ - serde_json::json!({"name": "shown", "layer": layer, "type": "visibility"}), - serde_json::json!({"name": "photo", "layer": layer, "type": "pixelReplacement"}), - ]; - headless.command_run("image.variables.define", serde_json::json!({"defs": defs})).unwrap(); - let sets = serde_json::json!({"dataSets": [ - {"name": "hidden", "values": [{"variable": "shown", "kind": "visibility", "value": false}]}, - {"name": "swap", "values": [ - {"variable": "shown", "kind": "visibility", "value": false}, - {"variable": "photo", "kind": "pixels", "value": "/outside/photo.png"}, - ]}, - ]}); - headless.command_run("image.variables.dataSets", sets).unwrap(); - let visible = |headless: &crate::Headless| headless.session.active().unwrap().doc.layers.iter().all(|l| l.visible); - let refused = headless.command_run("image.applyDataSet", serde_json::json!({"name": "swap"})).unwrap_err(); - assert!(refused.to_string().contains("ambient filesystem paths"), "{refused}"); - assert!(visible(&headless), "a refused data set applies none of its values"); - assert!(headless.command_run("image.applyDataSet", serde_json::json!({"name": "hidden"})).is_ok()); - assert!(!visible(&headless)); - } - - #[test] - fn automation_rejects_ambient_path_commands_and_preferences() { - for (id, params) in [ - ("brush.presets.importAbr", serde_json::json!({"path": "/outside/set.abr"})), - ("brush.presets.importImage", serde_json::json!({"path": "/outside/tip.png"})), - ("gradient.presets.importGrd", serde_json::json!({"path": "/outside/set.grd"})), - ("plugin.install", serde_json::json!({"path": "/outside/plugin.wasm"})), - ("plugin.reload", serde_json::json!({"path": "/outside/plugins"})), - ("plugin.reload", serde_json::json!({})), - ("plugin.install", serde_json::json!({"path": " "})), - ("swatches.import", serde_json::json!({"path": "/outside/set.aco"})), - ("swatches.export", serde_json::json!({"path": "/outside/set.ase"})), - ("actions.load", serde_json::json!({"path": "/outside/set.atn"})), - ("actions.save", serde_json::json!({"path": "/outside/set.atn"})), - ("style.presets.importAsl", serde_json::json!({"path": "/outside/set.asl"})), - ("style.presets.exportAsl", serde_json::json!({"path": "/outside/set.asl"})), - ("style.presets.exportAsl", serde_json::json!({"path": 5})), - ("layer.layerStyle.contours.load", serde_json::json!({"path": "/outside/set.shc"})), - ("layer.layerStyle.contours.save", serde_json::json!({"path": "/outside/set.shc"})), - ] { - assert!(authorize_engine_command(id, ¶ms).is_err(), "{id}: {params}"); - } - for (id, params) in [ - ("brush.presets.importAbr", serde_json::json!({"data": "QUJD"})), - ("brush.presets.importImage", serde_json::json!({"data": "QUJD"})), - ("gradient.presets.importGrd", serde_json::json!({"data": "QUJD"})), - ("plugin.install", serde_json::json!({"data": "QUJD"})), - ("swatches.import", serde_json::json!({"data": "QUJD"})), - ("swatches.export", serde_json::json!({"format": "ase"})), - ("actions.load", serde_json::json!({"data": "QUJD"})), - ("actions.save", serde_json::json!({"set": "S"})), - ("style.presets.importAsl", serde_json::json!({"data": "QUJD"})), - ("style.presets.exportAsl", serde_json::json!({"group": "Basics"})), - ("layer.layerStyle.contours.load", serde_json::json!({"data": "QUJD"})), - ("layer.layerStyle.contours.save", serde_json::json!({"names": ["a"]})), - ] { - assert!(authorize_engine_command(id, ¶ms).is_ok(), "{id}: {params}"); - } - for path in [ - "", - "colorSettings", - "colorSettings.workingRgb", - "scriptEvents", - "scriptEvents.enabled", - ".scriptEvents", - ".scriptEvents.enabled", - "historyLog.filePath", - ".historyLog.filePath", - "plugIns.additionalPluginsFolder", - "fileHandling.lutFolder", - "fileHandling", - "scratchDisks.disks", - ".", - "..historyLog.filePath", - ] { - assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": path, "value": {}})).is_err(), "{path}"); - } - assert!( - authorize_engine_command("prefs.set", &serde_json::json!({"values": {"interface.language": "fr", "historyLog.filePath": "/outside/log"}})).is_err() - ); - assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "interface.language", "value": "fr"})).is_ok()); - assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "fileHandling.autosave", "value": false})).is_ok()); - } - - #[test] - fn registry_filesystem_path_params_are_classified() { - let probe = serde_json::json!({ - "path": "/outside/photocraft-probe", - "file": "/outside/photocraft-probe.icc", - "mapPath": "/outside/photocraft-probe.png", - "profile": "/outside/photocraft-probe.icc", - "workingRgb": "/outside/photocraft-probe.icc", - "workingCmyk": "/outside/photocraft-probe.icc", - "workingGray": "/outside/photocraft-probe.icc", - "input": "/outside/photocraft-input", - "output": "/outside/photocraft-output", - "paths": ["/outside/photocraft-probe.psd"], - }); - let preference_probe = serde_json::json!({"path": ".scriptEvents", "value": {}}); - let unclassified: Vec<_> = photocraft_engine::command_specs() - .iter() - .filter(|spec| documents_filesystem_path_params(spec.id, spec.params)) - .filter(|spec| { - let params = if spec.id == "prefs.set" { &preference_probe } else { &probe }; - authorize_engine_command(spec.id, params).is_ok() - }) - .map(|spec| spec.id) - .collect(); - assert!(unclassified.is_empty(), "filesystem path parameters in the command registry need an automation policy: {unclassified:?}"); - } - - fn documents_filesystem_path_params(id: &str, params: &str) -> bool { - // These commands return settings or installed-profile paths; they do not accept a host - // filesystem path as an automation input. - if matches!(id, "prefs.get" | "prefs.reset" | "edit.installedProfiles") { - return false; - } - // These registry descriptions refer to document vector paths, not host files. - if matches!( - id, - "filter.blurGallery.pathBlur" - | "filter.render.flame" - | "shape.create" - | "shape.edit" - | "shape.info" - | "shape.presets.list" - | "shape.presets.new" - | "path.list" - | "path.info" - | "path.set" - | "path.transform" - | "path.moveAnchors" - | "path.moveHandle" - | "path.bendSegment" - | "path.convertPoint" - | "path.addAnchor" - | "path.deleteAnchor" - | "path.clippingPath.set" - | "path.rename" - | "path.stroke" - | "type.attachToPath" - | "type.fillPath" - | "type.detachFromPath" - | "select.toWorkPath" - | "layer.vectorMask.add" - | "layer.vectorMask.edit" - | "layer.vectorMask.info" - | "paint.symmetryFromPath" - | "edit.defineCustomShape" - | "layer.combineShapes.unite" - | "layer.combineShapes.subtractFrontShape" - | "layer.combineShapes.intersectShapeAreas" - | "layer.combineShapes.excludeOverlappingShapes" - | "layer.combineShapes.mergeShapeComponents" - ) || id.starts_with("layer.newFillLayer.") - || id.starts_with("layer.newAdjustmentLayer.") - { - // New fill and adjustment layers take a vector path as their vector mask (#1419). - return false; - } - params.to_ascii_lowercase().contains("path") - } - - #[test] - fn whole_preferences_update_cannot_enable_automation_script_events() { - let mut headless = crate::headless::Headless::new(); - let result = headless.command_run( - "prefs.set", - serde_json::json!({ - "path": "", - "value": { - "scriptEvents": { - "enabled": true, - "bindings": [{ - "event": "newDocument", - "steps": [["file.saveACopy", {"path": "/outside/canary.psd"}]] - }] - } - } - }), - ); - assert!(result.is_err()); - - for (id, params) in [ - ("brush.presets.importAbr", serde_json::json!({"path": "/outside/set.abr"})), - ("gradient.presets.importGrd", serde_json::json!({"path": "/outside/set.grd"})), - ("plugin.install", serde_json::json!({"path": "/outside/plugin.wasm"})), - ("plugin.reload", serde_json::json!({"path": "/outside/plugins"})), - ("style.presets.importAsl", serde_json::json!({"path": "/outside/set.asl"})), - ("style.presets.exportAsl", serde_json::json!({"path": "/outside/set.asl"})), - ("prefs.set", serde_json::json!({"path": "historyLog.filePath", "value": "/outside/log"})), - ("prefs.set", serde_json::json!({"values": {"interface.language": "fr", "historyLog.filePath": "/outside/log"}})), - ] { - assert!(headless.command_run(id, params).is_err(), "{id}"); - } - headless.command_run("file.new", serde_json::json!({"width": 5, "height": 5})).unwrap(); - assert!(headless.session.file_menu.event_log.is_empty()); - } - - /// #2176: an absolute path beneath the root names the same file as its relative path; every - /// other absolute path is refused before any file effect. - #[test] - fn absolute_paths_beneath_the_root_are_translated_and_others_refused() { - let (inside, outside, workspace) = roots("absolute-paths"); - let abs = |p: &Path| p.to_string_lossy().into_owned(); - - workspace.write(&abs(&inside.join("a.bin")), b"one").unwrap(); - assert_eq!(std::fs::read(inside.join("a.bin")).unwrap(), b"one"); - assert_eq!(workspace.read(&abs(&inside.join("a.bin"))).unwrap(), b"one"); - // Forward slashes too (on Windows the native spelling uses `\`). - assert_eq!(workspace.read(&abs(&inside.join("a.bin")).replace('\\', "/")).unwrap(), b"one"); - std::fs::create_dir(inside.join("sub")).unwrap(); - workspace.write(&abs(&inside.join("sub").join("b.bin")), b"two").unwrap(); - assert_eq!(std::fs::read(inside.join("sub/b.bin")).unwrap(), b"two"); - assert_eq!(workspace.read("sub/b.bin").unwrap(), b"two", "relative paths still work"); - - let refused = |path: String| { - let error = workspace.write(&path, b"x").unwrap_err().to_string(); - assert!(error.contains("automation path rejected"), "{path}: {error}"); - }; - refused(abs(&outside.join("escape.bin"))); - refused(abs(&inside.join("..").join("outside").join("traversal.bin"))); - refused(abs(&inside)); - refused(abs(&inside.join("CON"))); - refused(format!("{}:hidden", abs(&inside.join("a.bin")))); - // A sibling whose name merely starts with the root's name is not beneath it. - let sibling = inside.with_file_name("inside-sibling"); - std::fs::create_dir_all(&sibling).unwrap(); - refused(abs(&sibling.join("lookalike.bin"))); - refused(format!("{}-sibling/lookalike.bin", abs(&inside))); - // Climbing back out through a subdirectory is refused too. - refused(abs(&inside.join("sub").join("..").join("..").join("outside").join("climb.bin"))); - assert!(!sibling.join("lookalike.bin").exists()); - assert!(!outside.join("climb.bin").exists()); - assert!(!outside.join("escape.bin").exists()); - assert!(!outside.join("traversal.bin").exists()); - assert_eq!(std::fs::read(inside.join("a.bin")).unwrap(), b"one"); - } - - /// Each authority is checked against its own root, and none granted refuses absolute paths. - #[test] - fn absolute_paths_are_checked_against_the_authority_s_own_root() { - let (inside, outside, _) = roots("absolute-authority"); - let workspace = AuthorizedWorkspace::new(Some(&outside), Some(&inside)).unwrap(); - let target = inside.join("written.bin"); - workspace.write(&target.to_string_lossy(), b"w").unwrap(); - assert!(workspace.read(&target.to_string_lossy()).is_err(), "not under the read root"); - let none = AuthorizedWorkspace::default(); - assert!(none.read(&target.to_string_lossy()).is_err()); - } -} +mod tests; diff --git a/crates/automation/src/workspace/tests.rs b/crates/automation/src/workspace/tests.rs new file mode 100644 index 0000000000..2a94de15f2 --- /dev/null +++ b/crates/automation/src/workspace/tests.rs @@ -0,0 +1,581 @@ +use super::*; + +fn roots(name: &str) -> (PathBuf, PathBuf, AuthorizedWorkspace) { + let base = std::env::temp_dir().join(format!("photocraft-workspace-{}-{name}", std::process::id())); + let inside = base.join("inside"); + let outside = base.join("outside"); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let workspace = AuthorizedWorkspace::new(Some(&inside), Some(&inside)).unwrap(); + (inside, outside, workspace) +} + +#[test] +fn export_cleanup_owns_only_created_files_even_during_unwind() { + let (inside, _, workspace) = roots("export-cleanup"); + std::fs::create_dir(inside.join("frames")).unwrap(); + std::fs::write(inside.join("frames/clip_0009.png"), b"old").unwrap(); + let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let mut export = workspace.export_sequence("frames").unwrap(); + export.write("clip_0000.png", b"new").unwrap(); + assert!(export.write("clip_0009.png", b"overwrite").is_err()); + assert!(export.write("../escape.png", b"escape").is_err()); + panic!("rendering panic"); + })); + assert!(panic.is_err()); + assert_eq!(std::fs::read_dir(inside.join("frames")).unwrap().count(), 1); + assert_eq!(std::fs::read(inside.join("frames/clip_0009.png")).unwrap(), b"old"); + assert!(AuthorizedWorkspace::default().export_sequence("frames").is_err()); +} + +#[cfg(unix)] +#[test] +fn export_directory_symlinks_cannot_escape_the_granted_root() { + let (inside, outside, workspace) = roots("export-symlink"); + std::os::unix::fs::symlink(&outside, inside.join("escape")).unwrap(); + assert!(workspace.export_sequence("escape").is_err()); + assert_eq!(std::fs::read_dir(outside).unwrap().count(), 0); +} + +#[test] +fn valid_read_and_nonexistent_output_write_stay_in_root() { + let (inside, _, workspace) = roots("valid"); + std::fs::write(inside.join("read.txt"), b"canary").unwrap(); + assert_eq!(workspace.read("read.txt").unwrap(), b"canary"); + workspace.write("new-output.txt", b"created").unwrap(); + assert_eq!(std::fs::read(inside.join("new-output.txt")).unwrap(), b"created"); +} + +#[test] +fn large_observed_length_does_not_trigger_a_fixed_limit_or_upfront_reservation() { + let mut shortened = std::io::Cursor::new(b"psb"); + assert_eq!(read_to_observed_length(&mut shortened, (1 << 30) + 1).unwrap(), b"psb"); +} + +#[test] +fn read_growth_is_rejected_at_the_observed_length() { + let mut growing = std::io::repeat(b'x').take(65); + let error = read_to_observed_length(&mut growing, 64).unwrap_err().to_string(); + assert!(error.contains("grew beyond its observed length of 64 bytes"), "{error}"); + let mut allowed = std::io::repeat(b'x').take(64); + assert_eq!(read_to_observed_length(&mut allowed, 64).unwrap().len(), 64); + let mut empty = std::io::Cursor::new(b"x"); + assert!(read_to_observed_length(&mut empty, 0).is_err()); +} + +#[test] +fn open_pcraft_loads_a_directory_below_the_read_root() { + let (inside, _, workspace) = roots("pcraft-dir"); + let doc = photocraft_doc::Document::new("Native", photocraft_doc::Size::new(16, 12), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); + photocraft_format::PcraftWriter::new().save_dir(&doc, &inside.join("native.pcraft"), &photocraft_format::SaveOptions::default()).unwrap(); + let loaded = workspace.open_pcraft("native.pcraft").unwrap().expect("the directory form loads"); + assert_eq!(loaded.name, doc.name); + assert_eq!((loaded.size.width, loaded.size.height), (16, 12)); +} + +#[test] +fn open_pcraft_reports_zip_files_and_missing_paths_clearly() { + let (inside, _, workspace) = roots("pcraft-errors"); + let doc = photocraft_doc::Document::new("Zipped", photocraft_doc::Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); + let zip = inside.join("zipped.pcraft"); + photocraft_format::PcraftWriter::new().save_path(&doc, &zip, &photocraft_format::SaveOptions::default()).unwrap(); + assert!(zip.is_file()); + assert!(workspace.open_pcraft("zipped.pcraft").unwrap().is_none(), "the zip form falls back to the bytes path"); + let error = workspace.open_pcraft("missing.pcraft").unwrap_err().to_string(); + assert!(error.contains("failed"), "a missing path propagates its io error: {error}"); + assert!(AuthorizedWorkspace::default().open_pcraft("x.pcraft").is_err(), "no read authority fails closed"); +} + +#[cfg(unix)] +#[test] +fn open_pcraft_rejects_non_regular_entries_and_escaping_symlinks() { + let (inside, _, workspace) = roots("pcraft-nonregular"); + let bundle = inside.join("native.pcraft"); + std::fs::create_dir_all(bundle.join("manifest.json")).unwrap(); + let error = workspace.open_pcraft("native.pcraft").unwrap_err().to_string(); + assert!(error.contains("not a regular file"), "a directory entry is refused, not streamed: {error}"); + + let (inside2, _, workspace2) = roots("pcraft-symlink"); + let bundle2 = inside2.join("native.pcraft"); + std::fs::create_dir(&bundle2).unwrap(); + std::os::unix::fs::symlink("/dev/zero", bundle2.join("manifest.json")).unwrap(); + assert!(workspace2.open_pcraft("native.pcraft").is_err(), "an escaping symlink entry is refused"); +} + +fn temp_files(dir: &Path) -> Vec { + std::fs::read_dir(dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| n.ends_with(".tmp")).collect() +} + +#[test] +fn write_replaces_atomically_and_leaves_no_temp_file() { + let (inside, _, workspace) = roots("atomic"); + std::fs::create_dir_all(inside.join("sub")).unwrap(); + workspace.write("sub/out.psd", b"original").unwrap(); + workspace.write("sub/out.psd", b"replacement").unwrap(); + assert_eq!(std::fs::read(inside.join("sub/out.psd")).unwrap(), b"replacement"); + assert!(temp_files(&inside.join("sub")).is_empty()); + // Renaming over a directory fails: nothing is left behind and the directory survives. + std::fs::create_dir_all(inside.join("adir")).unwrap(); + assert!(workspace.write("adir", b"x").is_err()); + assert!(inside.join("adir").is_dir()); + assert!(temp_files(&inside).is_empty()); +} + +/// #7095: replacing a file through the automation path keeps the old file's extended +/// attributes, the same as a save through `atomic_write` does. +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] +#[test] +fn write_keeps_the_replaced_files_extended_attributes() { + #[cfg(target_os = "macos")] + const TAG: &str = "com.apple.metadata:_kMDItemUserTags"; + #[cfg(not(target_os = "macos"))] + const TAG: &str = "user.photocraft.test"; + + let (inside, _, workspace) = roots("xattr"); + let path = inside.join("doc.psd"); + workspace.write("doc.psd", b"original").unwrap(); + if rustix::fs::setxattr(&path, TAG, b"tagged", rustix::fs::XattrFlags::empty()).is_err() { + return; // a file system without extended attributes: nothing to assert + } + + workspace.write("doc.psd", b"replacement, longer").unwrap(); + + assert_eq!(std::fs::read(&path).unwrap(), b"replacement, longer"); + let mut buf = [0u8; 64]; + let len = rustix::fs::getxattr(&path, TAG, buf.as_mut_slice()).expect("the attribute was dropped"); + assert_eq!(&buf[..len], b"tagged"); + assert!(temp_files(&inside).is_empty()); +} + +#[cfg(unix)] +#[test] +fn write_into_read_only_folder_keeps_the_original() { + use std::os::unix::fs::PermissionsExt; + let (inside, _, workspace) = roots("readonly"); + let ro = inside.join("ro"); + std::fs::create_dir_all(&ro).unwrap(); + std::fs::write(ro.join("doc.psd"), b"original").unwrap(); + std::fs::set_permissions(&ro, std::fs::Permissions::from_mode(0o555)).unwrap(); + let root_user = std::fs::File::create(ro.join("probe")).is_ok(); + if !root_user { + assert!(workspace.write("ro/doc.psd", b"new").is_err()); + assert_eq!(std::fs::read(ro.join("doc.psd")).unwrap(), b"original"); + assert!(temp_files(&ro).is_empty()); + } + std::fs::set_permissions(&ro, std::fs::Permissions::from_mode(0o755)).unwrap(); +} + +#[test] +fn rejects_absolute_traversal_mixed_prefix_and_malformed_paths_without_panicking() { + let (_, _, workspace) = roots("reject"); + for path in + ["", "/absolute", "../escape", "a/../escape", "a\\..\\escape", "a\\b", "C:/escape", "a//b", "./a", "name:stream", "NUL", "con.txt", "folder/COM1.log"] + { + assert!(workspace.read(path).is_err(), "read accepted {path:?}"); + assert!(workspace.write(path, b"x").is_err(), "write accepted {path:?}"); + } +} + +#[test] +fn read_and_write_authority_are_separate() { + let (inside, _, _) = roots("separate"); + std::fs::write(inside.join("read.txt"), b"canary").unwrap(); + let read_only = AuthorizedWorkspace::new(Some(&inside), None).unwrap(); + assert_eq!(read_only.read("read.txt").unwrap(), b"canary"); + assert!(read_only.write("blocked.txt", b"x").is_err()); + let write_only = AuthorizedWorkspace::new(None, Some(&inside)).unwrap(); + assert!(write_only.read("read.txt").is_err()); + write_only.write("written.txt", b"ok").unwrap(); +} + +#[test] +fn missing_parent_is_a_stable_error_before_any_file_is_created() { + let (inside, _, workspace) = roots("missing-parent"); + let error = workspace.write("missing/output.txt", b"x").unwrap_err().to_string(); + assert!(error.contains("automation write"), "{error}"); + assert!(!inside.join("missing").exists()); +} + +#[cfg(unix)] +#[test] +fn symlink_escape_is_rejected() { + use std::os::unix::fs::symlink; + + let (inside, outside, workspace) = roots("symlink"); + std::fs::write(outside.join("secret.txt"), b"outside").unwrap(); + symlink(&outside, inside.join("link")).unwrap(); + assert!(workspace.read("link/secret.txt").is_err()); + assert!(workspace.write("link/new.txt", b"blocked").is_err()); + assert!(!outside.join("new.txt").exists()); +} + +#[cfg(windows)] +#[test] +fn windows_symlink_escape_is_rejected_when_supported() { + use std::os::windows::fs::symlink_dir; + + let (inside, outside, workspace) = roots("windows-link"); + std::fs::write(outside.join("secret.txt"), b"outside").unwrap(); + if symlink_dir(&outside, inside.join("link")).is_err() { + return; + } + assert!(workspace.read("link/secret.txt").is_err()); + assert!(workspace.write("link/new.txt", b"blocked").is_err()); + assert!(!outside.join("new.txt").exists()); +} + +#[cfg(windows)] +#[test] +fn windows_junction_escape_is_rejected_when_supported() { + use std::process::Command; + + let (inside, outside, workspace) = roots("windows-junction"); + std::fs::write(outside.join("secret.txt"), b"outside").unwrap(); + let link = inside.join("junction"); + let status = Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(&link).arg(&outside).status(); + if !status.is_ok_and(|status| status.success()) { + return; + } + assert!(workspace.read("junction/secret.txt").is_err()); + assert!(workspace.write("junction/new.txt", b"blocked").is_err()); + assert!(!outside.join("new.txt").exists()); + let _ = std::fs::remove_dir(link); +} + +#[test] +fn filesystem_commands_fail_closed() { + for id in [ + "file.open", + "file.openAs", + "file.save", + "file.saveAs", + "file.saveACopy", + "file.export.saveForWebLegacy", + "pattern.import", + "layer.smartObjects.exportContents", + "layer.smartObjects.replaceContents", + "layer.smartObjects.relinkToFile", + "layer.smartObjects.convertToLinked", + "measurementLog.export", + "layer.videoLayers.reloadFrame", + "edit.colorSettings", + ] { + assert!(authorize_engine_command(id, &serde_json::json!({})).is_err()); + } + assert!(authorize_engine_command("file.new", &serde_json::json!({})).is_ok()); + assert!(authorize_engine_command("file.automate.cropAndStraightenPhotos", &serde_json::json!({})).is_ok()); + assert!(authorize_desktop_engine_command("file.automate.cropAndStraightenPhotos", &serde_json::json!({})).is_ok()); + for id in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers", "layer.smartObjects.saveContents"] { + assert!(authorize_desktop_engine_command(id, &serde_json::json!({"layer": 19})).is_ok(), "{id}"); + } + for id in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers"] { + assert!(authorize_engine_command(id, &serde_json::json!({"path": "/outside/source.psb"})).is_err(), "{id}"); + } + // The UI-level examples in docs/control-protocol.md. + for id in ["view.zoomIn", "window.theme.pro", "edit.search"] { + assert!(authorize_desktop_engine_command(id, &serde_json::json!({})).is_ok(), "{id}"); + } + assert!(authorize_engine_command("image.mode.cmyk", &serde_json::json!({})).is_ok()); + assert!(authorize_desktop_engine_command("image.mode.cmyk", &serde_json::json!({})).is_err()); + assert!(authorize_engine_command("image.mode.rgb", &serde_json::json!({"profile": "/outside/profile.icc"})).is_err()); + assert!(authorize_engine_command("image.mode.rgb", &serde_json::json!({"profile": "srgb"})).is_ok()); + assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "/outside/profile.icc"})).is_err()); + assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "adobe-rgb-compat"})).is_ok()); + assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "working"})).is_ok()); + assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "none"})).is_ok()); + assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "default"})).is_err()); + assert!(authorize_engine_command("file.new", &serde_json::json!({"profile": "working-cmyk"})).is_err()); + // Shortcut sets: text in and out is fine; a path reads or writes the filesystem. + let ks = |p: serde_json::Value| authorize_engine_command("edit.keyboardShortcuts", &p); + assert!(ks(serde_json::json!({"exportKys": true, "summarize": true, "importKys": ""})).is_ok()); + for key in ["importKys", "exportKys", "summarize"] { + assert!(ks(serde_json::json!({ key: {"path": "/outside/set.kys"} })).is_err(), "{key}"); + } + assert!(authorize_engine_command("filter.distort.displace", &serde_json::json!({"mapPath": "outside.png"})).is_err()); + assert!(authorize_engine_command("layer.setAdjustment", &serde_json::json!({"file": "outside.cube"})).is_err()); + assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "colorSettings.workingRgb", "value": "outside.icc"})).is_err()); + assert!(authorize_engine_step("file.open", &serde_json::json!({})).is_err()); + assert!(authorize_engine_step("actions.play", &serde_json::json!({})).is_ok()); + // An allowed command can't reach a denied one by running it on its own behalf. + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", serde_json::json!({"width": 4, "height": 4})).unwrap(); + session.authorize = Some(authorize_desktop_engine_step); + let params = serde_json::json!({"to": "grayscale"}); + assert!(authorize_desktop_engine_command("file.automate.conditionalModeChange", ¶ms).is_ok()); + assert!(session.execute("file.automate.conditionalModeChange", params).is_err()); + assert_eq!(session.active().unwrap().doc.mode, photocraft_engine::doc::ColorMode::Rgb); + assert!(authorize_desktop_engine_step("file.saveACopy", &serde_json::json!({})).is_err()); +} + +// Regression test for #3763: `edit.installedProfiles` scans the OS and user ICC folders but +// takes no path parameter, so automation let it through until it was listed as ambient. +#[test] +fn installed_profiles_listing_is_refused_for_automation() { + for params in [serde_json::json!({}), serde_json::json!({"class": "output", "colorSpace": "cmyk"})] { + assert!(authorize_engine_command("edit.installedProfiles", ¶ms).is_err(), "authorize_engine_command allowed it with {params}"); + assert!(authorize_desktop_engine_command("edit.installedProfiles", ¶ms).is_err(), "authorize_desktop_engine_command allowed it with {params}"); + assert!(authorize_engine_step("edit.installedProfiles", ¶ms).is_err(), "authorize_engine_step allowed it with {params}"); + } + // The sandboxed session refuses it before the engine scans any folder. + let mut headless = crate::Headless::new(); + let refused = headless.command_run("edit.installedProfiles", serde_json::json!({})).unwrap_err(); + assert!(refused.to_string().contains("ambient filesystem paths"), "{refused}"); +} + +#[test] +fn apply_data_set_is_judged_by_the_values_it_applies() { + let mut headless = crate::Headless::new(); + headless.command_run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); + let layer = headless.command_run("layer.new.layer", serde_json::json!({})).unwrap()["layer"].clone(); + let defs = [ + serde_json::json!({"name": "shown", "layer": layer, "type": "visibility"}), + serde_json::json!({"name": "photo", "layer": layer, "type": "pixelReplacement"}), + ]; + headless.command_run("image.variables.define", serde_json::json!({"defs": defs})).unwrap(); + let sets = serde_json::json!({"dataSets": [ + {"name": "hidden", "values": [{"variable": "shown", "kind": "visibility", "value": false}]}, + {"name": "swap", "values": [ + {"variable": "shown", "kind": "visibility", "value": false}, + {"variable": "photo", "kind": "pixels", "value": "/outside/photo.png"}, + ]}, + ]}); + headless.command_run("image.variables.dataSets", sets).unwrap(); + let visible = |headless: &crate::Headless| headless.session.active().unwrap().doc.layers.iter().all(|l| l.visible); + let refused = headless.command_run("image.applyDataSet", serde_json::json!({"name": "swap"})).unwrap_err(); + assert!(refused.to_string().contains("ambient filesystem paths"), "{refused}"); + assert!(visible(&headless), "a refused data set applies none of its values"); + assert!(headless.command_run("image.applyDataSet", serde_json::json!({"name": "hidden"})).is_ok()); + assert!(!visible(&headless)); +} + +#[test] +fn automation_rejects_ambient_path_commands_and_preferences() { + for (id, params) in [ + ("brush.presets.importAbr", serde_json::json!({"path": "/outside/set.abr"})), + ("brush.presets.importImage", serde_json::json!({"path": "/outside/tip.png"})), + ("gradient.presets.importGrd", serde_json::json!({"path": "/outside/set.grd"})), + ("plugin.install", serde_json::json!({"path": "/outside/plugin.wasm"})), + ("plugin.reload", serde_json::json!({"path": "/outside/plugins"})), + ("plugin.reload", serde_json::json!({})), + ("plugin.install", serde_json::json!({"path": " "})), + ("swatches.import", serde_json::json!({"path": "/outside/set.aco"})), + ("swatches.export", serde_json::json!({"path": "/outside/set.ase"})), + ("actions.load", serde_json::json!({"path": "/outside/set.atn"})), + ("actions.save", serde_json::json!({"path": "/outside/set.atn"})), + ("style.presets.importAsl", serde_json::json!({"path": "/outside/set.asl"})), + ("style.presets.exportAsl", serde_json::json!({"path": "/outside/set.asl"})), + ("style.presets.exportAsl", serde_json::json!({"path": 5})), + ("layer.layerStyle.contours.load", serde_json::json!({"path": "/outside/set.shc"})), + ("layer.layerStyle.contours.save", serde_json::json!({"path": "/outside/set.shc"})), + ] { + assert!(authorize_engine_command(id, ¶ms).is_err(), "{id}: {params}"); + } + for (id, params) in [ + ("brush.presets.importAbr", serde_json::json!({"data": "QUJD"})), + ("brush.presets.importImage", serde_json::json!({"data": "QUJD"})), + ("gradient.presets.importGrd", serde_json::json!({"data": "QUJD"})), + ("plugin.install", serde_json::json!({"data": "QUJD"})), + ("swatches.import", serde_json::json!({"data": "QUJD"})), + ("swatches.export", serde_json::json!({"format": "ase"})), + ("actions.load", serde_json::json!({"data": "QUJD"})), + ("actions.save", serde_json::json!({"set": "S"})), + ("style.presets.importAsl", serde_json::json!({"data": "QUJD"})), + ("style.presets.exportAsl", serde_json::json!({"group": "Basics"})), + ("layer.layerStyle.contours.load", serde_json::json!({"data": "QUJD"})), + ("layer.layerStyle.contours.save", serde_json::json!({"names": ["a"]})), + ] { + assert!(authorize_engine_command(id, ¶ms).is_ok(), "{id}: {params}"); + } + for path in [ + "", + "colorSettings", + "colorSettings.workingRgb", + "scriptEvents", + "scriptEvents.enabled", + ".scriptEvents", + ".scriptEvents.enabled", + "historyLog.filePath", + ".historyLog.filePath", + "plugIns.additionalPluginsFolder", + "fileHandling.lutFolder", + "fileHandling", + "scratchDisks.disks", + ".", + "..historyLog.filePath", + ] { + assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": path, "value": {}})).is_err(), "{path}"); + } + assert!( + authorize_engine_command("prefs.set", &serde_json::json!({"values": {"interface.language": "fr", "historyLog.filePath": "/outside/log"}})).is_err() + ); + assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "interface.language", "value": "fr"})).is_ok()); + assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "fileHandling.autosave", "value": false})).is_ok()); +} + +#[test] +fn registry_filesystem_path_params_are_classified() { + let probe = serde_json::json!({ + "path": "/outside/photocraft-probe", + "file": "/outside/photocraft-probe.icc", + "mapPath": "/outside/photocraft-probe.png", + "profile": "/outside/photocraft-probe.icc", + "workingRgb": "/outside/photocraft-probe.icc", + "workingCmyk": "/outside/photocraft-probe.icc", + "workingGray": "/outside/photocraft-probe.icc", + "input": "/outside/photocraft-input", + "output": "/outside/photocraft-output", + "paths": ["/outside/photocraft-probe.psd"], + }); + let preference_probe = serde_json::json!({"path": ".scriptEvents", "value": {}}); + let unclassified: Vec<_> = photocraft_engine::command_specs() + .iter() + .filter(|spec| documents_filesystem_path_params(spec.id, spec.params)) + .filter(|spec| { + let params = if spec.id == "prefs.set" { &preference_probe } else { &probe }; + authorize_engine_command(spec.id, params).is_ok() + }) + .map(|spec| spec.id) + .collect(); + assert!(unclassified.is_empty(), "filesystem path parameters in the command registry need an automation policy: {unclassified:?}"); +} + +fn documents_filesystem_path_params(id: &str, params: &str) -> bool { + // These commands return settings or installed-profile paths; they do not accept a host + // filesystem path as an automation input. + if matches!(id, "prefs.get" | "prefs.reset" | "edit.installedProfiles") { + return false; + } + // These registry descriptions refer to document vector paths, not host files. + if matches!( + id, + "filter.blurGallery.pathBlur" + | "filter.render.flame" + | "shape.create" + | "shape.edit" + | "shape.info" + | "shape.presets.list" + | "shape.presets.new" + | "path.list" + | "path.info" + | "path.set" + | "path.transform" + | "path.moveAnchors" + | "path.moveHandle" + | "path.bendSegment" + | "path.convertPoint" + | "path.addAnchor" + | "path.deleteAnchor" + | "path.clippingPath.set" + | "path.rename" + | "path.stroke" + | "type.attachToPath" + | "type.fillPath" + | "type.detachFromPath" + | "select.toWorkPath" + | "layer.vectorMask.add" + | "layer.vectorMask.edit" + | "layer.vectorMask.info" + | "paint.symmetryFromPath" + | "edit.defineCustomShape" + | "layer.combineShapes.unite" + | "layer.combineShapes.subtractFrontShape" + | "layer.combineShapes.intersectShapeAreas" + | "layer.combineShapes.excludeOverlappingShapes" + | "layer.combineShapes.mergeShapeComponents" + ) || id.starts_with("layer.newFillLayer.") + || id.starts_with("layer.newAdjustmentLayer.") + { + // New fill and adjustment layers take a vector path as their vector mask (#1419). + return false; + } + params.to_ascii_lowercase().contains("path") +} + +#[test] +fn whole_preferences_update_cannot_enable_automation_script_events() { + let mut headless = crate::headless::Headless::new(); + let result = headless.command_run( + "prefs.set", + serde_json::json!({ + "path": "", + "value": { + "scriptEvents": { + "enabled": true, + "bindings": [{ + "event": "newDocument", + "steps": [["file.saveACopy", {"path": "/outside/canary.psd"}]] + }] + } + } + }), + ); + assert!(result.is_err()); + + for (id, params) in [ + ("brush.presets.importAbr", serde_json::json!({"path": "/outside/set.abr"})), + ("gradient.presets.importGrd", serde_json::json!({"path": "/outside/set.grd"})), + ("plugin.install", serde_json::json!({"path": "/outside/plugin.wasm"})), + ("plugin.reload", serde_json::json!({"path": "/outside/plugins"})), + ("style.presets.importAsl", serde_json::json!({"path": "/outside/set.asl"})), + ("style.presets.exportAsl", serde_json::json!({"path": "/outside/set.asl"})), + ("prefs.set", serde_json::json!({"path": "historyLog.filePath", "value": "/outside/log"})), + ("prefs.set", serde_json::json!({"values": {"interface.language": "fr", "historyLog.filePath": "/outside/log"}})), + ] { + assert!(headless.command_run(id, params).is_err(), "{id}"); + } + headless.command_run("file.new", serde_json::json!({"width": 5, "height": 5})).unwrap(); + assert!(headless.session.file_menu.event_log.is_empty()); +} + +/// #2176: an absolute path beneath the root names the same file as its relative path; every +/// other absolute path is refused before any file effect. +#[test] +fn absolute_paths_beneath_the_root_are_translated_and_others_refused() { + let (inside, outside, workspace) = roots("absolute-paths"); + let abs = |p: &Path| p.to_string_lossy().into_owned(); + + workspace.write(&abs(&inside.join("a.bin")), b"one").unwrap(); + assert_eq!(std::fs::read(inside.join("a.bin")).unwrap(), b"one"); + assert_eq!(workspace.read(&abs(&inside.join("a.bin"))).unwrap(), b"one"); + // Forward slashes too (on Windows the native spelling uses `\`). + assert_eq!(workspace.read(&abs(&inside.join("a.bin")).replace('\\', "/")).unwrap(), b"one"); + std::fs::create_dir(inside.join("sub")).unwrap(); + workspace.write(&abs(&inside.join("sub").join("b.bin")), b"two").unwrap(); + assert_eq!(std::fs::read(inside.join("sub/b.bin")).unwrap(), b"two"); + assert_eq!(workspace.read("sub/b.bin").unwrap(), b"two", "relative paths still work"); + + let refused = |path: String| { + let error = workspace.write(&path, b"x").unwrap_err().to_string(); + assert!(error.contains("automation path rejected"), "{path}: {error}"); + }; + refused(abs(&outside.join("escape.bin"))); + refused(abs(&inside.join("..").join("outside").join("traversal.bin"))); + refused(abs(&inside)); + refused(abs(&inside.join("CON"))); + refused(format!("{}:hidden", abs(&inside.join("a.bin")))); + // A sibling whose name merely starts with the root's name is not beneath it. + let sibling = inside.with_file_name("inside-sibling"); + std::fs::create_dir_all(&sibling).unwrap(); + refused(abs(&sibling.join("lookalike.bin"))); + refused(format!("{}-sibling/lookalike.bin", abs(&inside))); + // Climbing back out through a subdirectory is refused too. + refused(abs(&inside.join("sub").join("..").join("..").join("outside").join("climb.bin"))); + assert!(!sibling.join("lookalike.bin").exists()); + assert!(!outside.join("climb.bin").exists()); + assert!(!outside.join("escape.bin").exists()); + assert!(!outside.join("traversal.bin").exists()); + assert_eq!(std::fs::read(inside.join("a.bin")).unwrap(), b"one"); +} + +/// Each authority is checked against its own root, and none granted refuses absolute paths. +#[test] +fn absolute_paths_are_checked_against_the_authority_s_own_root() { + let (inside, outside, _) = roots("absolute-authority"); + let workspace = AuthorizedWorkspace::new(Some(&outside), Some(&inside)).unwrap(); + let target = inside.join("written.bin"); + workspace.write(&target.to_string_lossy(), b"w").unwrap(); + assert!(workspace.read(&target.to_string_lossy()).is_err(), "not under the read root"); + let none = AuthorizedWorkspace::default(); + assert!(none.read(&target.to_string_lossy()).is_err()); +} From ed0d14d272cd57d4cbb8e39493df63b4f0b95b15 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:46 +0000 Subject: [PATCH 115/259] refactor(automation): move rpc.rs tests to rpc/tests.rs --- crates/automation/src/rpc.rs | 980 +---------------------------- crates/automation/src/rpc/tests.rs | 974 ++++++++++++++++++++++++++++ 2 files changed, 975 insertions(+), 979 deletions(-) create mode 100644 crates/automation/src/rpc/tests.rs diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index b98094eb5d..98ccc9a24a 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -391,982 +391,4 @@ fn serve_tcp_until_idle( } #[cfg(test)] -mod tests { - use super::*; - - fn session() -> Mutex { - Mutex::new(Headless::trusted_local()) - } - - #[test] - fn document_activation_reply_survives_engine_rpc() { - let h = session(); - let mut g = h.lock().unwrap(); - for _ in 0..2 { - g.handle("engine.execute", json!({"command": "file.new", "params": {"width": 4, "height": 4}})).unwrap(); - } - let reply = g.handle("engine.execute", json!({"command": "document.activate", "params": {"offset": -1}})).unwrap(); - assert_eq!(reply, json!({"document": 0})); - let reply = g.handle("engine.execute", json!({"command": "document.activate", "params": {"document": 1}})).unwrap(); - assert_eq!(reply, json!({"document": 1})); - } - - #[test] - fn execute_reports_invalid_filter_parameters_without_changing_history() { - let h = session(); - assert_eq!(respond(&h, r#"{"method":"doc.new","params":{"width":8,"height":8}}"#)["ok"], true); - let before = h.lock().unwrap().inspect(None).unwrap(); - for (params, key) in - [(json!({"radius":"big"}), "radius"), (json!({"radus":3}), "radus"), (json!({"radius":5000}), "radius"), (json!({"radius":-4}), "radius")] - { - for wait in [true, false] { - let request = json!({"method":"engine.execute","params":{"command":"filter.blur.gaussianBlur","params":params,"wait":wait}}); - let reply = respond(&h, &request.to_string()); - assert_eq!(reply["ok"], false); - let error = reply["error"].as_str().unwrap(); - assert!(error.contains("filter.blur.gaussianBlur") && error.contains(key), "{error}"); - assert_eq!(h.lock().unwrap().inspect(None).unwrap(), before); - } - } - } - - /// Pins the reply shape documented in docs/control-protocol.md › Command list replies - /// (#3684): a bare JSON array (not `{"commands": [...]}`), one object per command with - /// exactly these keys (plus an optional `keywords` string), from `engine.commands` (filtered or not) and `command.list`. - #[test] - fn command_list_replies_are_documented_array_of_objects() { - let h = session(); - let mut g = h.lock().unwrap(); - let all = g.handle("engine.commands", json!({})).unwrap(); - let filtered = g.handle("engine.commands", json!({"filter": "BLUR"})).unwrap(); - let engine = g.handle("engine.execute", json!({"command": "command.list"})).unwrap(); - for (name, reply) in [("engine.commands", &all), ("engine.commands {filter}", &filtered), ("command.list", &engine)] { - let items = reply.as_array().unwrap_or_else(|| panic!("{name} must reply with a bare array, got {reply}")); - assert!(!items.is_empty(), "{name}"); - for c in items { - // `keywords` is optional: only commands with other search names carry it (#5060). - let mut keys: Vec<&str> = c.as_object().unwrap().keys().map(String::as_str).filter(|k| *k != "keywords").collect(); - keys.sort_unstable(); - assert!(c.get("keywords").is_none_or(Value::is_string), "{name}: {c}"); - assert_eq!(keys, ["disabledReason", "enabled", "id", "label", "menu", "needsDocument", "params", "shortcut"], "{name}: {c}"); - assert!(c["id"].is_string() && c["label"].is_string() && c["params"].is_string() && c["enabled"].is_boolean(), "{c}"); - assert!(c["needsDocument"].is_boolean(), "{c}"); - assert_eq!(c["disabledReason"].is_null(), c["enabled"] == true, "disabledReason is null exactly when enabled: {c}"); - assert!(c["menu"].as_array().unwrap().iter().all(Value::is_string), "{c}"); - assert!(c["shortcut"].is_string() || c["shortcut"].is_null(), "{c}"); - } - } - let n_all = all.as_array().unwrap().len(); - assert_eq!(engine.as_array().unwrap().len(), n_all); - let filtered = filtered.as_array().unwrap(); - assert!(filtered.len() < n_all); - assert!(filtered.iter().all(|c| format!("{} {}", c["id"], c["label"]).to_lowercase().contains("blur"))); - let new = all.as_array().unwrap().iter().find(|c| c["id"] == "file.new").unwrap(); - assert_eq!((&new["menu"], &new["shortcut"], &new["enabled"]), (&json!(["File"]), &json!("Cmd+N"), &json!(true)), "{new}"); - assert_eq!((&new["disabledReason"], &new["needsDocument"]), (&Value::Null, &json!(false)), "{new}"); - } - - #[test] - fn lines_round_trip_and_errors() { - let h = session(); - let input = concat!( - r#"{"id":1,"method":"doc.new","params":{"width":64,"height":32,"background":"white"}}"#, - "\n", - "\n", - r#"{"id":2,"method":"engine.execute","params":{"command":"layer.new.layer","params":{"name":"Ink"}}}"#, - "\n", - r#"{"id":3,"method":"doc.inspect"}"#, - "\n", - r#"{"id":4,"method":"nope"}"#, - "\n", - "not json\n", - ); - let mut out = Vec::new(); - serve_lines(&h, input.as_bytes(), &mut out).unwrap(); - let replies: Vec = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); - assert_eq!(replies.len(), 5); - assert!(replies[0]["ok"].as_bool().unwrap()); - assert_eq!(replies[1]["id"], 2); - assert!(replies[2]["result"].to_string().contains("Ink")); - assert!(!replies[3]["ok"].as_bool().unwrap()); - assert!(replies[3]["error"].as_str().unwrap().contains("unknown method")); - assert_eq!(replies[4]["id"], Value::Null); - } - - /// Regression: after a panic while the session lock was held, every later request - /// failed with "session lock poisoned"; the server now keeps serving. - #[test] - fn poisoned_session_keeps_serving() { - let h = session(); - let _ = std::thread::scope(|sc| { - sc.spawn(|| { - let _g = h.lock().unwrap(); - panic!("poison the session lock"); - }) - .join() - }); - assert!(h.is_poisoned()); - let r = respond(&h, r#"{"id":1,"method":"doc.new","params":{"width":8,"height":8}}"#); - assert_eq!(r["ok"], true, "{r}"); - } - - #[test] - fn batch_stops_on_error_unless_told_not_to() { - let h = session(); - let mut g = h.lock().unwrap(); - g.handle("doc.new", json!({"width": 16, "height": 16})).unwrap(); - let steps = json!([ - {"command": "layer.new.layer", "params": {"name": "A"}}, - {"command": "no.such.command"}, - {"command": "layer.new.layer", "params": {"name": "B"}}, - {"method": "doc.inspect"} - ]); - let r = g.handle("batch", json!({"steps": steps})).unwrap(); - assert_eq!(r["completed"], 1); - assert_eq!(r["failed"], 1); - assert_eq!(r["results"].as_array().unwrap().len(), 2); - let r = g.handle("batch", json!({"steps": steps, "stopOnError": false})).unwrap(); - assert_eq!(r["completed"], 3); - let insp = &r["results"][3]["result"]; - assert!(insp.to_string().contains("\"B\"")); - } - - #[test] - fn batch_rejects_too_many_steps() { - let h = session(); - let mut g = h.lock().unwrap(); - let steps = vec![json!({"command": "command.list"}); MAX_BATCH_STEPS + 1]; - let error = g.handle("batch", json!({"steps": steps})).unwrap_err(); - assert!(error.to_string().contains("maximum is 256")); - } - - #[test] - fn render_to_file_and_base64() { - let h = session(); - let mut g = h.lock().unwrap(); - g.handle("doc.new", json!({"width": 40, "height": 20, "background": "black"})).unwrap(); - let b = g.handle("doc.render", json!({"maxSide": 10})).unwrap(); - let png = base64::engine::general_purpose::STANDARD.decode(b["base64"].as_str().unwrap()).unwrap(); - let img = photocraft_codecs::decode(&png).unwrap(); - assert_eq!(img.dimensions(), (10, 5)); - let path = std::env::temp_dir().join(format!("pc-rpc-{}.png", std::process::id())); - let r = g.handle("doc.render", json!({"path": path.to_string_lossy(), "maxSide": 0})).unwrap(); - assert!(r["bytes"].as_u64().unwrap() > 0); - assert_eq!(photocraft_codecs::decode(&std::fs::read(&path).unwrap()).unwrap().dimensions(), (40, 20)); - let _ = std::fs::remove_file(path); - } - - #[test] - fn background_jobs_list_wait_and_cancel() { - let mut h = Headless::new(); - h.handle("doc.new", json!({"width": 600, "height": 400})).unwrap(); - h.handle("engine.execute", json!({"command": "layer.new.layer"})).unwrap(); - h.handle("engine.execute", json!({"command": "edit.fill", "params": {"color": "#808080"}})).unwrap(); - // Default: waits, the result is the command's. - let r = h.handle("engine.execute", json!({"command": "filter.noise.addNoise", "params": {"amount": 20}})).unwrap(); - assert!(r["filter"].is_object(), "{r}"); - // wait: false returns a job id at once. - let r = h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 40}, "wait": false})).unwrap(); - let job = r["job"].as_u64().unwrap(); - let listed = h.handle("jobs.list", json!({})).unwrap(); - assert!(listed["jobs"].as_array().unwrap().iter().any(|j| j["id"] == job), "{listed}"); - // Wait for it via jobs.list (which applies finished jobs). - let t = std::time::Instant::now(); - loop { - let l = h.handle("jobs.list", json!({})).unwrap(); - let state = l["jobs"].as_array().unwrap().iter().find(|j| j["id"] == job).map(|j| j["state"].clone()); - if state == Some(json!("done")) { - break; - } - assert!(t.elapsed().as_secs() < 60, "{l}"); - std::thread::sleep(std::time::Duration::from_millis(5)); - } - // Cancel: a second job, cancelled at once, leaves the document unchanged. - let before = h.session.active().unwrap().doc.clone(); - let r = h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 40}, "wait": false})).unwrap(); - let job = r["job"].as_u64().unwrap(); - h.handle("jobs.cancel", json!({"job": job})).unwrap(); - assert!(h.handle("jobs.cancel", json!({"job": "nope"})).is_err()); - let l = h.handle("jobs.list", json!({})).unwrap(); - assert_eq!(l["jobs"].as_array().unwrap().iter().find(|j| j["id"] == job).unwrap()["state"], "cancelled"); - assert!(std::sync::Arc::ptr_eq(&h.session.active().unwrap().doc, &before)); - } - - #[test] - fn batch_steps_can_start_background_jobs() { - let mut h = Headless::new(); - h.handle("doc.new", json!({"width": 600, "height": 400})).unwrap(); - let steps = json!([ - {"command": "layer.new.layer"}, - {"command": "edit.fill", "params": {"color": "#808080"}}, - {"command": "filter.blur.gaussianBlur", "params": {"radius": 40}, "wait": false} - ]); - let r = h.handle("batch", json!({"steps": steps})).unwrap(); - assert_eq!(r["completed"], 3, "{r}"); - let job = r["results"][2]["result"]["job"].as_u64().unwrap_or_else(|| panic!("no job id: {r}")); - assert_eq!(r["results"][2]["result"]["pending"], true); - let listed = h.handle("jobs.list", json!({})).unwrap(); - assert!(listed["jobs"].as_array().unwrap().iter().any(|j| j["id"] == job), "{listed}"); - let t = std::time::Instant::now(); - while h.session.jobs().iter().any(|j| j.id.0 == job) { - assert!(t.elapsed().as_secs() < 60); - std::thread::sleep(std::time::Duration::from_millis(5)); - h.handle("jobs.list", json!({})).unwrap(); - } - } - - /// Regression (#503): a finished `wait: false` job was only applied by a later command or - /// `jobs.list`, so save, inspect, render and `session.list` still saw the document without it. - #[test] - fn every_request_sees_a_finished_background_job() { - let dir = std::env::temp_dir().join(format!("pc-rpc-job-sync-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let (before, after) = (dir.join("before.png"), dir.join("after.png")); - let mut h = Headless::trusted_local(); - h.handle("doc.new", json!({"width": 64, "height": 48})).unwrap(); - h.handle("engine.execute", json!({"command": "filter.noise.addNoise", "params": {"amount": 50}})).unwrap(); - h.handle("doc.save", json!({"path": before.to_string_lossy()})).unwrap(); - let render = |h: &mut Headless| h.handle("doc.render", json!({"maxSide": 0})).unwrap()["base64"].clone(); - let unblurred = render(&mut h); - let revision = |h: &mut Headless| h.handle("session.list", json!({})).unwrap()["documents"][0]["revision"].clone(); - let start = revision(&mut h); - h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 4}, "wait": false})).unwrap(); - // Only reading requests from here on: no command and no `jobs.list`. - let t = std::time::Instant::now(); - while revision(&mut h) == start { - assert!(t.elapsed().as_secs() < 60, "session.list never saw the finished job"); - std::thread::sleep(std::time::Duration::from_millis(5)); - } - let history = h.handle("doc.inspect", json!({})).unwrap()["history"].clone(); - assert_eq!(history.as_array().unwrap().last().unwrap(), "Gaussian Blur", "{history}"); - h.handle("doc.save", json!({"path": after.to_string_lossy()})).unwrap(); - let decode = |p: &std::path::Path| photocraft_codecs::decode(&std::fs::read(p).unwrap()).unwrap().to_rgba8(); - assert_ne!(decode(&before), decode(&after), "the export holds the blur"); - assert_ne!(render(&mut h), unblurred, "the preview holds the blur"); - std::fs::remove_dir_all(dir).unwrap(); - } - - /// Regression: `quality` 85.0 or "85" was ignored (a lossless WebP, reply ok) and 0 or 500 was - /// clamped, where the CLI refuses anything but a whole number from 1 to 100. - #[test] - fn doc_save_rejects_a_bad_quality_instead_of_ignoring_or_clamping_it() { - let dir = std::env::temp_dir().join(format!("pc-rpc-save-quality-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("x.webp"); - let mut h = Headless::trusted_local(); - h.handle("doc.new", json!({"width": 16, "height": 16})).unwrap(); - for q in [json!(85.0), json!("85"), json!(0), json!(500), json!(-5), json!(true)] { - let err = h.handle("doc.save", json!({"path": path.to_string_lossy(), "quality": q})).unwrap_err().to_string(); - assert!(err.contains("quality"), "{q}: {err}"); - assert!(!path.exists(), "{q} wrote a file"); - } - h.handle("doc.save", json!({"path": path.to_string_lossy(), "quality": 85})).unwrap(); - let bytes = std::fs::read(&path).unwrap(); - assert_eq!(bytes.get(12..16), Some(&b"VP8 "[..]), "a WebP saved with a quality is lossy"); - std::fs::remove_dir_all(dir).unwrap(); - } - - #[test] - fn automation_preview_rejects_oversized_full_size_and_numeric_wraparound() { - let mut h = Headless::new(); - h.handle("doc.new", json!({"width": 2049, "height": 1})).unwrap(); - for max in [json!(0), json!(2049), json!(u64::from(u32::MAX) + 1), json!(-1), json!(1.5)] { - assert!(h.handle("doc.render", json!({"maxSide": max})).is_err()); - } - // A smaller preview still works, and rejection leaves the source document intact. - let rendered = h.handle("doc.render", json!({"maxSide": 32})).unwrap(); - let png = base64::engine::general_purpose::STANDARD.decode(rendered["base64"].as_str().unwrap()).unwrap(); - assert_eq!(photocraft_codecs::decode(&png).unwrap().dimensions(), (32, 1)); - assert_eq!(h.session.active().unwrap().doc.size.width, 2049); - } - - #[test] - fn stdio_rejects_oversized_frames_before_dispatch() { - let h = Mutex::new(Headless::new()); - let input = " ".repeat(MAX_REQUEST_BYTES + 1); - let mut out = Vec::new(); - serve_lines(&h, input.as_bytes(), &mut out).unwrap(); - let reply: Value = serde_json::from_slice(&out).unwrap(); - assert_eq!(reply["ok"], false); - assert!(reply["error"].as_str().unwrap().contains("request exceeds")); - assert!(h.lock().unwrap().session.documents().is_empty()); - } - - /// Regression (#505): an over-long or non-UTF-8 line ended the stdio session, losing every - /// open document. Now it gets one error reply, the rest of the line is skipped (never - /// dispatched), and the next request is served. - #[test] - fn stdio_skips_a_rejected_line_and_keeps_the_session() { - let h = Mutex::new(Headless::new()); - let mut input = b"{\"id\":1,\"method\":\"doc.new\",\"params\":{\"width\":8,\"height\":8}}\n".to_vec(); - input.extend(" ".repeat(MAX_REQUEST_BYTES + 1).into_bytes()); - input.extend(b"{\"id\":9,\"method\":\"doc.close\"}\n"); - input.extend(b"\xff\xfe{\"id\":8,\"method\":\"doc.close\"}\n"); - input.extend(b"{\"id\":2,\"method\":\"session.list\"}\n"); - let mut out = Vec::new(); - serve_lines(&h, input.as_slice(), &mut out).unwrap(); - let replies: Vec = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); - assert_eq!(replies.len(), 4, "{replies:?}"); - assert_eq!(replies[0]["ok"], true); - assert!(replies[1]["error"].as_str().unwrap().contains("request exceeds"), "{}", replies[1]); - assert!(replies[2]["error"].as_str().unwrap().contains("not valid UTF-8"), "{}", replies[2]); - assert_eq!(replies[3]["id"], 2); - assert_eq!(replies[3]["result"]["documents"].as_array().unwrap().len(), 1, "the document stays open"); - } - - #[test] - fn preview_rejection_precedes_output_file_creation() { - let root = std::env::temp_dir().join(format!("pc-preview-budget-{}", std::process::id())); - std::fs::create_dir_all(&root).unwrap(); - let workspace = crate::AuthorizedWorkspace::new(None, Some(&root)).unwrap(); - let mut h = Headless::with_workspace(workspace); - h.handle("doc.new", json!({"width": 16, "height": 8})).unwrap(); - let result = h.handle("doc.render", json!({"maxSide": 2049, "path": "rejected.png"})); - assert!(result.unwrap_err().to_string().contains("preview side exceeds")); - assert!(!root.join("rejected.png").exists()); - assert!(h.handle("doc.render", json!({"maxSide": 16, "path": "accepted.png"})).is_ok()); - assert!(root.join("accepted.png").exists()); - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_file(root.join("accepted.png")).unwrap(); - std::fs::remove_dir(root).unwrap(); - } - - #[test] - fn doc_place_reads_through_the_read_root_and_never_outside_it() { - let base = std::env::temp_dir().join(format!("pc-doc-place-{}", std::process::id())); - let root = base.join("workspace"); - let outside = base.join("outside"); - for dir in [&root, &outside] { - std::fs::create_dir_all(dir).unwrap(); - } - let img = photocraft_codecs::Image::from_u8(8, 6, photocraft_codecs::ChannelLayout::Rgb, vec![42; 8 * 6 * 3]).unwrap(); - let png = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); - std::fs::write(root.join("logo.png"), &png).unwrap(); - std::fs::write(outside.join("logo.png"), &png).unwrap(); - let absolute = outside.join("logo.png").to_string_lossy().into_owned(); - - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); - let placed = h.handle("doc.place", json!({"path": "logo.png", "scale": 50})).unwrap(); - assert!(placed["layer"].as_u64().is_some(), "{placed}"); - assert_eq!(placed["scale"].as_f64(), Some(50.0), "the options reach the command: {placed}"); - let inspected = h.handle("doc.inspect", json!({})).unwrap(); - assert_eq!(inspected["layers"].as_array().map(Vec::len), Some(2), "the placed layer is in the document: {inspected}"); - // A path outside the read root is refused the way the ambient command is (#2810). - for (path, reason) in [("../outside/logo.png", "parent traversal"), (absolute.as_str(), "must be inside the automation root")] { - let refused = h.handle("doc.place", json!({"path": path})).unwrap_err().to_string(); - assert!(refused.contains(reason), "{refused}"); - let inspected = h.handle("doc.inspect", json!({})).unwrap(); - assert_eq!(inspected["layers"].as_array().map(Vec::len), Some(2), "nothing was placed: {refused}"); - } - // Trusted local keeps the ambient command: that caller may read the path itself. - let mut t = Headless::trusted_local(); - t.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); - let trusted = t.handle("doc.place", json!({"path": root.join("logo.png").to_string_lossy()})).unwrap(); - assert!(trusted["layer"].as_u64().is_some(), "{trusted}"); - // Release directory capabilities before cleanup on Windows. - drop(t); - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn doc_replace_smart_object_reads_through_the_read_root_and_never_outside_it() { - let base = std::env::temp_dir().join(format!("pc-doc-replace-so-{}", std::process::id())); - let root = base.join("workspace"); - let outside = base.join("outside"); - for dir in [&root, &outside] { - std::fs::create_dir_all(dir).unwrap(); - } - let png = |w: u32, h: u32, v: u8| { - let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, vec![v; (w * h * 3) as usize]).unwrap(); - photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap() - }; - std::fs::write(root.join("logo.png"), png(8, 6, 42)).unwrap(); - std::fs::write(root.join("red.png"), png(8, 6, 200)).unwrap(); - std::fs::write(outside.join("red.png"), png(8, 6, 200)).unwrap(); - let absolute = outside.join("red.png").to_string_lossy().into_owned(); - - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); - let layer = h.handle("doc.place", json!({"path": "logo.png"})).unwrap()["layer"].clone(); - // The smart object's file name and the composite at its centre: what Replace Contents changes. - let contents = |h: &mut Headless| { - let inspected = h.handle("doc.inspect", json!({})).unwrap(); - let layers = inspected["layers"].as_array().unwrap(); - let so = layers.iter().find(|l| l["id"] == layer).unwrap_or_else(|| panic!("{inspected}")); - let name = so["smartSource"]["fileName"].as_str().unwrap_or_default().to_owned(); - let rendered = h.handle("doc.render", json!({"maxSide": 0})).unwrap(); - let png = base64::engine::general_purpose::STANDARD.decode(rendered["base64"].as_str().unwrap()).unwrap(); - let img = photocraft_codecs::decode(&png).unwrap(); - let (w, ht) = img.dimensions(); - let data = img.as_u8().unwrap(); - let channels = data.len() / (w * ht) as usize; - (name, data[((ht / 2 * w + w / 2) as usize) * channels]) - }; - assert_eq!(contents(&mut h), ("logo.png".to_owned(), 42), "the placed contents"); - let replaced = h.handle("doc.replaceSmartObject", json!({"path": "red.png", "layer": layer})).unwrap(); - assert_eq!(replaced["layer"], layer, "{replaced}"); - assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "the contents were replaced"); - h.handle("engine.execute", json!({"command": "edit.undo"})).unwrap(); - assert_eq!(contents(&mut h), ("logo.png".to_owned(), 42), "one undo step restores the old contents"); - h.handle("engine.execute", json!({"command": "edit.redo"})).unwrap(); - assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "redo replaces them again"); - // Outside the read root, a bad layer, a missing path or a file that is no image: refused, nothing changed. - for (params, reason) in [ - (json!({"path": "../outside/red.png"}), "parent traversal"), - (json!({"path": absolute}), "must be inside the automation root"), - (json!({"path": "logo.png", "layer": 999_999}), "no such layer"), - (json!({}), "needs `path`"), - ] { - let refused = h.handle("doc.replaceSmartObject", params).unwrap_err().to_string(); - assert!(refused.contains(reason), "{refused}"); - assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "nothing changed: {refused}"); - } - std::fs::write(root.join("junk.png"), b"not an image").unwrap(); - assert!(h.handle("doc.replaceSmartObject", json!({"path": "junk.png", "layer": layer})).is_err()); - assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "a file that is no image changes nothing"); - // The ambient command keeps its refusal. - let ambient = h.handle("engine.execute", json!({"command": "layer.smartObjects.replaceContents", "params": {"path": "red.png"}})); - assert!(ambient.unwrap_err().to_string().contains("ambient filesystem paths")); - // Trusted local keeps the ambient command. - let mut t = Headless::trusted_local(); - t.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); - let tl = t.handle("doc.place", json!({"path": root.join("logo.png").to_string_lossy()})).unwrap()["layer"].clone(); - let trusted = t.handle("doc.replaceSmartObject", json!({"path": root.join("red.png").to_string_lossy(), "layer": tl})).unwrap(); - assert_eq!(trusted["layer"], tl, "{trusted}"); - drop(t); - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn doc_export_layers_reports_skips_in_workspace_and_trusted_sessions() { - for trusted in [false, true] { - let base = std::env::temp_dir().join(format!("pc-export-skips-{}-{trusted}", std::process::id())); - let _ = std::fs::remove_dir_all(&base); - std::fs::create_dir_all(&base).unwrap(); - let mut h = - if trusted { Headless::trusted_local() } else { Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&base), Some(&base)).unwrap()) }; - h.handle("doc.new", json!({"width": 4, "height": 4, "background": "white", "name": "card"})).unwrap(); - let adjustment = h.handle("engine.execute", json!({"command": "layer.newAdjustmentLayer.levels"})).unwrap()["layer"].clone(); - h.handle("engine.execute", json!({"command": "layer.setProps", "params": {"name": "Levels"}})).unwrap(); - let hidden = h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Hidden"}})).unwrap()["layer"].clone(); - h.handle("engine.execute", json!({"command": "layer.setProps", "params": {"visible": false}})).unwrap(); - // Exercise the actual JSON-lines serve envelope, not only direct dispatch. - let h = Mutex::new(h); - let out_dir = base.join("out").to_string_lossy().into_owned(); - let request = json!({"id": 8491, "method": "doc.exportLayers", "params": {"dir": out_dir}}).to_string() + "\n"; - let mut output = Vec::new(); - serve_lines(&h, request.as_bytes(), &mut output).unwrap(); - let reply: Value = serde_json::from_slice(&output).unwrap(); - assert_eq!(reply["id"], 8491); - assert_eq!(reply["ok"], true, "{reply}"); - assert_eq!(reply["result"]["files"], json!([format!("{out_dir}/card_0001_Background.png")])); - if !trusted { - assert_eq!(reply["result"]["count"], 1); - } - assert_eq!( - reply["result"]["skipped"], - json!([ - {"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"}, - {"layer": adjustment, "name": "Levels", "reason": "adjustment layer has no pixels of its own"} - ]) - ); - assert_eq!(std::fs::read_dir(base.join("out")).unwrap().count(), 1); - let mut h = h.into_inner().unwrap(); - let all_dir = base.join("all").to_string_lossy().into_owned(); - let all = h.export_layers(None, &all_dir, &json!({"visibleOnly": false})).unwrap(); - assert_eq!(all["files"].as_array().unwrap().len(), 2); - assert_eq!(all["skipped"].as_array().unwrap().len(), 1); - // Workspace no-overwrite errors still fail and remove only newly created files. - if !trusted { - let collision = base.join("collision"); - std::fs::create_dir_all(&collision).unwrap(); - std::fs::write(collision.join("card_0002_Background.png"), b"keep").unwrap(); - assert!(h.export_layers(None, &collision.to_string_lossy(), &json!({"visibleOnly": false})).is_err()); - assert_eq!(std::fs::read_dir(&collision).unwrap().count(), 1); - assert_eq!(std::fs::read(collision.join("card_0002_Background.png")).unwrap(), b"keep"); - } - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - } - - #[test] - fn doc_export_layers_writes_only_beneath_the_write_root() { - let base = std::env::temp_dir().join(format!("pc-doc-export-layers-{}", std::process::id())); - let root = base.join("workspace"); - std::fs::create_dir_all(&root).unwrap(); - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.new", json!({"width": 12, "height": 8, "background": "white", "name": "card"})).unwrap(); - h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Badge"}})).unwrap(); - - let out = root.join("out"); - let exported = h.handle("doc.exportLayers", json!({"dir": out.to_string_lossy(), "format": "png", "prefix": "card"})).unwrap(); - assert_eq!(exported["count"].as_u64(), Some(2), "{exported}"); - let mut names: Vec = std::fs::read_dir(&out).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect(); - names.sort(); - assert_eq!(names.len(), 2, "{exported}"); - for name in names { - assert!(name.starts_with("card_") && name.ends_with(".png"), "{name}"); - let bytes = std::fs::read(out.join(&name)).unwrap(); - assert_eq!(photocraft_codecs::decode(&bytes).unwrap().dimensions(), (12, 8), "{name}"); - } - // Outside the write root nothing is created, not even the directory. - let escaped = base.join("escaped"); - let refused = h.handle("doc.exportLayers", json!({"dir": escaped.to_string_lossy()})).unwrap_err().to_string(); - assert!(refused.contains("must be inside the automation root"), "{refused}"); - assert!(!escaped.exists()); - // The ambient command keeps its refusal for the very same directory. - let ambient = - h.handle("engine.execute", json!({"command": "file.export.layersToFiles", "params": {"dir": out.to_string_lossy()}})).unwrap_err().to_string(); - assert!(ambient.contains("ambient filesystem paths"), "{ambient}"); - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn doc_export_data_sets_refuse_collisions_and_import_reads_the_root() { - let base = std::env::temp_dir().join(format!("pc-doc-data-sets-{}", std::process::id())); - let root = base.join("workspace"); - std::fs::create_dir_all(&root).unwrap(); - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "card"})).unwrap(); - let inspected = h.handle("doc.inspect", json!({})).unwrap(); - let layer = inspected["layers"][0]["id"].as_u64().expect("the layer id"); - h.handle("engine.execute", json!({"command": "image.variables.define", "params": {"defs": [{"name": "show", "layer": layer, "type": "visibility"}]}})) - .unwrap(); - h.handle( - "engine.execute", - json!({"command": "image.variables.dataSets", "params": {"dataSets": [ - {"name": "one", "values": [{"variable": "show", "kind": "visibility", "value": true}]}, - {"name": "two", "values": [{"variable": "show", "kind": "visibility", "value": false}]}, - ]}}), - ) - .unwrap(); - - let sets = root.join("sets"); - let exported = h.handle("doc.exportDataSets", json!({"dir": sets.to_string_lossy(), "format": "png"})).unwrap(); - assert_eq!(exported["count"].as_u64(), Some(2), "{exported}"); - assert_eq!(std::fs::read_dir(&sets).unwrap().count(), 2, "{exported}"); - // Colliding names are refused as in the command, before any file is written. - let clash = root.join("clash"); - let refused = h.handle("doc.exportDataSets", json!({"dir": clash.to_string_lossy(), "naming": "{document}"})).unwrap_err().to_string(); - assert!(refused.contains("{index}"), "{refused}"); - assert_eq!(std::fs::read_dir(&clash).unwrap().count(), 0, "no file of the refused batch"); - // A CSV from the read root, and one outside it. - std::fs::write(root.join("sets.csv"), "Data Set,show\none,true\ntwo,false\n").unwrap(); - let imported = h.handle("doc.importDataSets", json!({"path": "sets.csv"})).unwrap(); - assert_eq!(imported["imported"].as_u64(), Some(2), "{imported}"); - std::fs::write(base.join("outside.csv"), "Data Set,show\none,true\n").unwrap(); - let outside = h.handle("doc.importDataSets", json!({"path": base.join("outside.csv").to_string_lossy()})).unwrap_err().to_string(); - assert!(outside.contains("must be inside the automation root"), "{outside}"); - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn indexed_place_replace_and_data_set_methods_keep_the_active_document() { - let base = std::env::temp_dir().join(format!("pc-doc-index-active-{}", std::process::id())); - let root = base.join("workspace"); - std::fs::create_dir_all(&root).unwrap(); - let img = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgb, vec![42; 4 * 4 * 3]).unwrap(); - std::fs::write(root.join("logo.png"), photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); - std::fs::write(root.join("sets.csv"), "Data Set,show\none,true\ntwo,false\n").unwrap(); - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "first"})).unwrap(); - h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "second"})).unwrap(); - let layer = h.handle("doc.inspect", json!({})).unwrap()["layers"][0]["id"].as_u64().expect("the layer id"); - h.handle("engine.execute", json!({"command": "image.variables.define", "params": {"defs": [{"name": "show", "layer": layer, "type": "visibility"}]}})) - .unwrap(); - h.handle("doc.select", json!({"index": 0})).unwrap(); - - let steps = [ - ("doc.place", json!({"path": "logo.png", "index": 1}), true), - // Document 1's active layer is now the placed Smart Object. - ("doc.replaceSmartObject", json!({"path": "logo.png", "index": 1}), true), - ("doc.replaceSmartObject", json!({"path": "missing.png", "index": 1}), false), - ("doc.importDataSets", json!({"path": "sets.csv", "index": 1}), true), - ("doc.exportLayers", json!({"dir": "layers", "index": 1}), true), - ("doc.exportDataSets", json!({"dir": "sets", "index": 1}), true), - // A failing call restores the active document too. - ("doc.importDataSets", json!({"path": "missing.csv", "index": 1}), false), - ]; - for (method, params, succeeds) in steps { - let result = h.handle(method, params.clone()); - assert_eq!(result.is_ok(), succeeds, "{method} {params}: {result:?}"); - assert_eq!(h.session.active_index(), Some(0), "{method} {params} must not select document 1"); - } - assert_eq!(h.session.documents()[0].doc.layer_count(), 1, "nothing was placed into the active document"); - assert_eq!(h.session.documents()[1].doc.layer_count(), 2, "the placed layer is in document 1"); - assert_eq!(std::fs::read_dir(root.join("sets")).unwrap().count(), 2, "document 1's data sets were exported"); - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn doc_export_data_sets_judges_pixel_replacement_paths_like_apply() { - let base = std::env::temp_dir().join(format!("pc-doc-data-set-pixels-{}", std::process::id())); - let root = base.join("workspace"); - std::fs::create_dir_all(&root).unwrap(); - let red = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgb, [255, 0, 0].repeat(16)).unwrap(); - let photo = base.join("photo.png"); - std::fs::write(&photo, photocraft_codecs::encode(&red, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "card"})).unwrap(); - let layer = h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {}})).unwrap()["layer"].clone(); - h.handle( - "engine.execute", - json!({"command": "image.variables.define", "params": {"defs": [{"name": "photo", "layer": layer, "type": "pixelReplacement"}]}}), - ) - .unwrap(); - // Storing the path is allowed; reading it is what the gate judges. - h.handle( - "engine.execute", - json!({"command": "image.variables.dataSets", "params": {"dataSets": [ - {"name": "swap", "values": [{"variable": "photo", "kind": "pixels", "value": photo.to_string_lossy()}]}, - ]}}), - ) - .unwrap(); - let applied = h.handle("engine.execute", json!({"command": "image.applyDataSet", "params": {"name": "swap"}})).unwrap_err().to_string(); - assert!(applied.contains("ambient filesystem paths"), "{applied}"); - let sets = root.join("sets"); - let exported = h.handle("doc.exportDataSets", json!({"dir": sets.to_string_lossy(), "format": "png"})).unwrap_err().to_string(); - assert!(exported.contains("ambient filesystem paths"), "{exported}"); - assert_eq!(std::fs::read_dir(&sets).map_or(0, Iterator::count), 0, "nothing of the refused batch is written"); - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn workspace_psd_saves_embed_no_file_a_linked_smart_object_names() { - use photocraft_engine::doc::{LayerContent, SmartSource}; - - // An image PhotoCraft can open (other linked files are never embedded): an embedded copy - // carries these exact bytes, while pixels written for the layer don't. - let image = photocraft_codecs::Image::from_u8(8, 8, photocraft_codecs::ChannelLayout::Rgb, (0..192u8).collect()).unwrap(); - let marker = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); - let has_marker = |bytes: &[u8]| bytes.windows(marker.len()).any(|w| w == marker.as_slice()); - let base = std::env::temp_dir().join(format!("pc-psd-linked-embed-{}", std::process::id())); - let root = base.join("workspace"); - std::fs::create_dir_all(&root).unwrap(); - let outside = base.join("outside.png"); - std::fs::write(&outside, &marker).unwrap(); - // A document whose smart object names a file outside the roots as its source. - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); - session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let state = session.active_mut().unwrap(); - let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; - smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; - std::fs::write(root.join("in.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); - // A trusted export embeds the linked file, as before. - assert!(has_marker(&photocraft_io::export(&state.doc, "psd", &Default::default()).unwrap().bytes)); - - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.open", json!({"path": "in.pcraft"})).unwrap(); - let saved = h.handle("doc.save", json!({"path": "out.psd"})).unwrap(); - let warnings = saved["warnings"].to_string(); - assert!(warnings.contains("written as pixels"), "{warnings}"); - assert!(!has_marker(&std::fs::read(root.join("out.psd")).unwrap()), "the linked file outside the roots is not embedded"); - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn allowed_filters_do_not_rerender_a_smart_object_from_its_linked_file() { - use photocraft_engine::doc::{LayerContent, SmartSource}; - - let base = std::env::temp_dir().join(format!("pc-linked-rerender-{}", std::process::id())); - let root = base.join("workspace"); - std::fs::create_dir_all(&root).unwrap(); - let red = photocraft_codecs::Image::from_u8(8, 8, photocraft_codecs::ChannelLayout::Rgb, [255, 0, 0].repeat(64)).unwrap(); - let outside = base.join("red.png"); - std::fs::write(&outside, photocraft_codecs::encode(&red, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); - // A document whose white smart object names a file outside the roots as its source. - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); - session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let state = session.active_mut().unwrap(); - let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; - smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; - std::fs::write(root.join("p.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); - - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.open", json!({"path": "p.pcraft"})).unwrap(); - h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 0.5}})).unwrap(); - let doc = &h.session.active().unwrap().doc; - let LayerContent::Smart(smart) = &doc.layers[0].content else { panic!("smart object") }; - assert_eq!(smart.smart_filters.len(), 1, "the filter is still recorded"); - assert_eq!(smart.cache.as_ref().unwrap().rgba(4, 4), [1.0, 1.0, 1.0, 1.0], "the linked file outside the roots is not read"); - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn workspace_layer_exports_keep_linked_smart_objects_as_pixels() { - use photocraft_engine::doc::{LayerContent, SmartSource}; - - const MARKER: &[u8] = b"PHOTOCRAFT-LINKED-0002"; - let has_marker = |bytes: &[u8]| bytes.windows(MARKER.len()).any(|w| w == MARKER); - let base = std::env::temp_dir().join(format!("pc-export-layers-linked-{}", std::process::id())); - let root = base.join("workspace"); - std::fs::create_dir_all(&root).unwrap(); - let outside = base.join("outside.txt"); - std::fs::write(&outside, MARKER).unwrap(); - // A document whose smart object names a file outside the roots as its source. - let mut session = photocraft_engine::Session::new(); - session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); - session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - let state = session.active_mut().unwrap(); - let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; - smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; - std::fs::write(root.join("in.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); - - let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); - h.handle("doc.open", json!({"path": "in.pcraft"})).unwrap(); - let out = root.join("layers"); - for format in ["psd", "psb"] { - let exported = h.handle("doc.exportLayers", json!({"dir": out.to_string_lossy(), "format": format})).unwrap(); - assert_eq!(exported["count"], 1, "{exported}"); - } - let files: Vec<_> = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().path()).collect(); - assert_eq!(files.len(), 2, "{files:?}"); - for file in files { - assert!(!has_marker(&std::fs::read(&file).unwrap()), "{} embeds no file outside the roots", file.display()); - } - // Release directory capabilities before cleanup on Windows. - drop(h); - std::fs::remove_dir_all(base).unwrap(); - } - - #[test] - fn trusted_local_render_keeps_full_size_behavior() { - let mut h = Headless::trusted_local(); - h.handle("doc.new", json!({"width": 2049, "height": 1})).unwrap(); - let rendered = h.handle("doc.render", json!({"maxSide": 0})).unwrap(); - let png = base64::engine::general_purpose::STANDARD.decode(rendered["base64"].as_str().unwrap()).unwrap(); - assert_eq!(photocraft_codecs::decode(&png).unwrap().dimensions(), (2049, 1)); - } - - #[test] - fn methods_lists_the_job_methods_and_every_listed_name_is_served() { - let mut h = Headless::new(); - let listed = h.handle("methods", Value::Null).unwrap(); - let listed: Vec<&str> = listed.as_array().unwrap().iter().map(|m| m.as_str().unwrap()).collect(); - assert_eq!(listed, METHODS); - // The job methods `engine.execute {"wait": false}` depends on are discoverable (#414). - assert!(listed.contains(&"jobs.list") && listed.contains(&"jobs.cancel")); - for m in METHODS { - if let Err(e) = h.handle(m, Value::Null) { - assert!(!e.to_string().contains("unknown method"), "{m} is listed but not served: {e}"); - } - } - assert!(h.handle("jobs.nope", Value::Null).unwrap_err().to_string().contains("unknown method")); - } - - #[test] - fn batch_response_budget_stops_later_steps_even_when_stop_on_error_is_false() { - let mut h = Headless::new(); - let mut steps = vec![json!({"command": "command.list"}); MAX_BATCH_STEPS - 1]; - steps.push(json!({"command": "file.new", "params": {"width": 8, "height": 8}})); - let result = h.batch(&json!({"steps": steps, "stopOnError": false})).unwrap(); - assert_eq!(result["failed"], 1); - assert!(result["results"].as_array().unwrap().last().unwrap()["error"].as_str().unwrap().contains("batch response budget exceeded")); - assert!(h.session.documents().is_empty(), "later edit must not execute after the quota is exhausted"); - assert!(crate::budgets::json_bytes(&result).is_ok()); - assert!(h.handle("methods", Value::Null).is_ok()); - } - - #[test] - fn idle_tcp_daemon_releases_its_port_but_keeps_active_clients() { - use std::io::BufReader; - const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - let h = Arc::new(Mutex::new(Headless::new())); - let (ready_tx, ready_rx) = std::sync::mpsc::channel(); - let (done_tx, done_rx) = std::sync::mpsc::channel(); - let server = std::thread::spawn(move || { - let result = serve_tcp_until_idle("127.0.0.1:0", h, TOKEN.to_owned(), move |addr| ready_tx.send(addr).unwrap(), Duration::from_millis(200)); - done_tx.send(result).unwrap(); - }); - let addr = ready_rx.recv_timeout(Duration::from_secs(2)).unwrap(); - let mut client = std::net::TcpStream::connect(addr).unwrap(); - client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); - let mut reader = BufReader::new(client.try_clone().unwrap()); - writeln!(client, r#"{{"id":"auth","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); - let mut line = String::new(); - reader.read_line(&mut line).unwrap(); - let auth: Value = serde_json::from_str(&line).unwrap(); - assert_eq!(auth["result"]["authenticated"], true); - // The port stays owned well past the idle limit while a client is connected. - assert!( - matches!(done_rx.recv_timeout(Duration::from_millis(450)), Err(std::sync::mpsc::RecvTimeoutError::Timeout)), - "daemon exited with a live client" - ); - drop(reader); - drop(client); - assert!(done_rx.recv_timeout(Duration::from_secs(3)).unwrap().is_ok(), "idle daemon did not exit cleanly"); - server.join().unwrap(); - assert!(TcpListener::bind(addr).is_ok(), "idle listener still owns its port"); - } - - #[test] - fn tcp_serves_loopback() { - use std::io::{BufReader, Write as _}; - const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - let h = Arc::new(Mutex::new(Headless::new())); - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap()); - }); - let addr = rx.recv().unwrap(); - let mut s = std::net::TcpStream::connect(addr).unwrap(); - writeln!(s, r#"{{"id":"auth","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); - let mut reader = BufReader::new(s.try_clone().unwrap()); - let mut line = String::new(); - reader.read_line(&mut line).unwrap(); - let auth: Value = serde_json::from_str(&line).unwrap(); - assert_eq!(auth["result"]["authenticated"], true); - writeln!(s, r#"{{"id":"a","method":"methods"}}"#).unwrap(); - line.clear(); - reader.read_line(&mut line).unwrap(); - let v: Value = serde_json::from_str(&line).unwrap(); - assert_eq!(v["id"], "a"); - assert!(v["result"].as_array().unwrap().iter().any(|m| m == "batch")); - } - - /// #4965: a connection that keeps sending without authenticating is closed at the deadline, - /// and one that authenticated in time keeps being served after it. - #[test] - fn tcp_connections_must_authenticate_before_the_deadline_whatever_they_send() { - use std::io::{BufReader, Write as _}; - use std::time::{Duration, Instant}; - const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - let server = std::thread::spawn(move || { - let h = Mutex::new(Headless::new()); - let mut results = Vec::new(); - for _ in 0..2 { - let (stream, _) = listener.accept().unwrap(); - let started = Instant::now(); - let r = serve_tcp_connection(&h, stream, TOKEN, Duration::from_millis(300)); - results.push((r.map_err(|e| e.kind()), started.elapsed())); - } - results - }); - - // Never a newline, a byte every 20 ms: each read succeeds long before the idle timeout. - let mut slow = std::net::TcpStream::connect(addr).unwrap(); - for _ in 0..150 { - if slow.write_all(b" ").is_err() { - break; - } - std::thread::sleep(Duration::from_millis(20)); - } - drop(slow); - - // Authenticates at once, then asks again 300 ms after the deadline. - let mut s = std::net::TcpStream::connect(addr).unwrap(); - s.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); - writeln!(s, r#"{{"id":"auth","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); - let mut reader = BufReader::new(s.try_clone().unwrap()); - let mut line = String::new(); - reader.read_line(&mut line).unwrap(); - assert_eq!(serde_json::from_str::(&line).unwrap()["result"]["authenticated"], true); - std::thread::sleep(Duration::from_millis(600)); - writeln!(s, r#"{{"id":"a","method":"methods"}}"#).unwrap(); - line.clear(); - reader.read_line(&mut line).unwrap(); - assert_eq!(serde_json::from_str::(&line).unwrap()["id"], "a"); - drop(reader); - drop(s); - - let results = server.join().unwrap(); - let (slow_result, slow_time) = &results[0]; - assert!(matches!(slow_result, Err(std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock)), "{slow_result:?}"); - assert!(*slow_time < Duration::from_secs(3), "the trickle did not extend the deadline: {slow_time:?}"); - assert_eq!(results[1].0, Ok(()), "the authenticated connection ended with its client"); - } - - #[test] - fn tcp_repeat_auth_reports_already_authenticated_and_keeps_serving() { - use std::io::{BufReader, Write as _}; - const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - let h = Arc::new(Mutex::new(Headless::new())); - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap()); - }); - let addr = rx.recv().unwrap(); - let mut s = std::net::TcpStream::connect(addr).unwrap(); - let mut reader = BufReader::new(s.try_clone().unwrap()); - let mut line = String::new(); - for id in ["auth", "again"] { - writeln!(s, r#"{{"id":"{id}","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); - line.clear(); - reader.read_line(&mut line).unwrap(); - } - let again: Value = serde_json::from_str(&line).unwrap(); - assert_eq!(again["id"], "again"); - assert_eq!(again["ok"], false); - assert_eq!(again["error"], "already authenticated"); - writeln!(s, r#"{{"id":"m","method":"methods"}}"#).unwrap(); - line.clear(); - reader.read_line(&mut line).unwrap(); - let v: Value = serde_json::from_str(&line).unwrap(); - assert_eq!(v["id"], "m"); - assert_eq!(v["ok"], true); - } - - #[test] - fn tcp_rejects_requests_before_authentication() { - use std::io::{BufReader, Write as _}; - const TOKEN: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - let h = Arc::new(Mutex::new(Headless::new())); - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap()); - }); - let addr = rx.recv().unwrap(); - let mut s = std::net::TcpStream::connect(addr).unwrap(); - writeln!(s, r#"{{"id":1,"method":"methods"}}"#).unwrap(); - let mut line = String::new(); - BufReader::new(s).read_line(&mut line).unwrap(); - let v: Value = serde_json::from_str(&line).unwrap(); - assert_eq!(v["ok"], false); - assert_eq!(v["error"], "authentication required"); - assert!(v.get("result").is_none()); - } - - #[test] - fn invalid_document_index_is_rejected_not_the_active_document() { - let h = session(); - for _ in 0..2 { - assert_eq!(respond(&h, r#"{"method":"doc.new","params":{"width":8,"height":8}}"#)["ok"], true); - } - let count = |h: &Mutex| h.lock().unwrap().session_list()["documents"].as_array().unwrap().len(); - for index in [json!("0"), json!(-1), json!(0.5), json!(true)] { - for method in ["doc.close", "doc.inspect", "doc.select"] { - let reply = respond(&h, &json!({"method": method, "params": {"index": index}}).to_string()); - assert_eq!(reply["ok"], false, "{method} {index}: {reply}"); - assert!(reply["error"].as_str().unwrap().contains("`index` must be a non-negative integer"), "{reply}"); - } - assert_eq!(count(&h), 2, "index {index} closed a document"); - } - // Null means "the active document", like a missing `index`. - assert_eq!(respond(&h, r#"{"method":"doc.inspect","params":{"index":null}}"#)["ok"], true); - // A valid index still closes that document. - let reply = respond(&h, r#"{"method":"doc.close","params":{"index":0}}"#); - assert_eq!(reply["ok"], true, "{reply}"); - assert_eq!(count(&h), 1); - } -} +mod tests; diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs new file mode 100644 index 0000000000..b7e22b3ffa --- /dev/null +++ b/crates/automation/src/rpc/tests.rs @@ -0,0 +1,974 @@ +use super::*; + +fn session() -> Mutex { + Mutex::new(Headless::trusted_local()) +} + +#[test] +fn document_activation_reply_survives_engine_rpc() { + let h = session(); + let mut g = h.lock().unwrap(); + for _ in 0..2 { + g.handle("engine.execute", json!({"command": "file.new", "params": {"width": 4, "height": 4}})).unwrap(); + } + let reply = g.handle("engine.execute", json!({"command": "document.activate", "params": {"offset": -1}})).unwrap(); + assert_eq!(reply, json!({"document": 0})); + let reply = g.handle("engine.execute", json!({"command": "document.activate", "params": {"document": 1}})).unwrap(); + assert_eq!(reply, json!({"document": 1})); +} + +#[test] +fn execute_reports_invalid_filter_parameters_without_changing_history() { + let h = session(); + assert_eq!(respond(&h, r#"{"method":"doc.new","params":{"width":8,"height":8}}"#)["ok"], true); + let before = h.lock().unwrap().inspect(None).unwrap(); + for (params, key) in + [(json!({"radius":"big"}), "radius"), (json!({"radus":3}), "radus"), (json!({"radius":5000}), "radius"), (json!({"radius":-4}), "radius")] + { + for wait in [true, false] { + let request = json!({"method":"engine.execute","params":{"command":"filter.blur.gaussianBlur","params":params,"wait":wait}}); + let reply = respond(&h, &request.to_string()); + assert_eq!(reply["ok"], false); + let error = reply["error"].as_str().unwrap(); + assert!(error.contains("filter.blur.gaussianBlur") && error.contains(key), "{error}"); + assert_eq!(h.lock().unwrap().inspect(None).unwrap(), before); + } + } +} + +/// Pins the reply shape documented in docs/control-protocol.md › Command list replies +/// (#3684): a bare JSON array (not `{"commands": [...]}`), one object per command with +/// exactly these keys (plus an optional `keywords` string), from `engine.commands` (filtered or not) and `command.list`. +#[test] +fn command_list_replies_are_documented_array_of_objects() { + let h = session(); + let mut g = h.lock().unwrap(); + let all = g.handle("engine.commands", json!({})).unwrap(); + let filtered = g.handle("engine.commands", json!({"filter": "BLUR"})).unwrap(); + let engine = g.handle("engine.execute", json!({"command": "command.list"})).unwrap(); + for (name, reply) in [("engine.commands", &all), ("engine.commands {filter}", &filtered), ("command.list", &engine)] { + let items = reply.as_array().unwrap_or_else(|| panic!("{name} must reply with a bare array, got {reply}")); + assert!(!items.is_empty(), "{name}"); + for c in items { + // `keywords` is optional: only commands with other search names carry it (#5060). + let mut keys: Vec<&str> = c.as_object().unwrap().keys().map(String::as_str).filter(|k| *k != "keywords").collect(); + keys.sort_unstable(); + assert!(c.get("keywords").is_none_or(Value::is_string), "{name}: {c}"); + assert_eq!(keys, ["disabledReason", "enabled", "id", "label", "menu", "needsDocument", "params", "shortcut"], "{name}: {c}"); + assert!(c["id"].is_string() && c["label"].is_string() && c["params"].is_string() && c["enabled"].is_boolean(), "{c}"); + assert!(c["needsDocument"].is_boolean(), "{c}"); + assert_eq!(c["disabledReason"].is_null(), c["enabled"] == true, "disabledReason is null exactly when enabled: {c}"); + assert!(c["menu"].as_array().unwrap().iter().all(Value::is_string), "{c}"); + assert!(c["shortcut"].is_string() || c["shortcut"].is_null(), "{c}"); + } + } + let n_all = all.as_array().unwrap().len(); + assert_eq!(engine.as_array().unwrap().len(), n_all); + let filtered = filtered.as_array().unwrap(); + assert!(filtered.len() < n_all); + assert!(filtered.iter().all(|c| format!("{} {}", c["id"], c["label"]).to_lowercase().contains("blur"))); + let new = all.as_array().unwrap().iter().find(|c| c["id"] == "file.new").unwrap(); + assert_eq!((&new["menu"], &new["shortcut"], &new["enabled"]), (&json!(["File"]), &json!("Cmd+N"), &json!(true)), "{new}"); + assert_eq!((&new["disabledReason"], &new["needsDocument"]), (&Value::Null, &json!(false)), "{new}"); +} + +#[test] +fn lines_round_trip_and_errors() { + let h = session(); + let input = concat!( + r#"{"id":1,"method":"doc.new","params":{"width":64,"height":32,"background":"white"}}"#, + "\n", + "\n", + r#"{"id":2,"method":"engine.execute","params":{"command":"layer.new.layer","params":{"name":"Ink"}}}"#, + "\n", + r#"{"id":3,"method":"doc.inspect"}"#, + "\n", + r#"{"id":4,"method":"nope"}"#, + "\n", + "not json\n", + ); + let mut out = Vec::new(); + serve_lines(&h, input.as_bytes(), &mut out).unwrap(); + let replies: Vec = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(replies.len(), 5); + assert!(replies[0]["ok"].as_bool().unwrap()); + assert_eq!(replies[1]["id"], 2); + assert!(replies[2]["result"].to_string().contains("Ink")); + assert!(!replies[3]["ok"].as_bool().unwrap()); + assert!(replies[3]["error"].as_str().unwrap().contains("unknown method")); + assert_eq!(replies[4]["id"], Value::Null); +} + +/// Regression: after a panic while the session lock was held, every later request +/// failed with "session lock poisoned"; the server now keeps serving. +#[test] +fn poisoned_session_keeps_serving() { + let h = session(); + let _ = std::thread::scope(|sc| { + sc.spawn(|| { + let _g = h.lock().unwrap(); + panic!("poison the session lock"); + }) + .join() + }); + assert!(h.is_poisoned()); + let r = respond(&h, r#"{"id":1,"method":"doc.new","params":{"width":8,"height":8}}"#); + assert_eq!(r["ok"], true, "{r}"); +} + +#[test] +fn batch_stops_on_error_unless_told_not_to() { + let h = session(); + let mut g = h.lock().unwrap(); + g.handle("doc.new", json!({"width": 16, "height": 16})).unwrap(); + let steps = json!([ + {"command": "layer.new.layer", "params": {"name": "A"}}, + {"command": "no.such.command"}, + {"command": "layer.new.layer", "params": {"name": "B"}}, + {"method": "doc.inspect"} + ]); + let r = g.handle("batch", json!({"steps": steps})).unwrap(); + assert_eq!(r["completed"], 1); + assert_eq!(r["failed"], 1); + assert_eq!(r["results"].as_array().unwrap().len(), 2); + let r = g.handle("batch", json!({"steps": steps, "stopOnError": false})).unwrap(); + assert_eq!(r["completed"], 3); + let insp = &r["results"][3]["result"]; + assert!(insp.to_string().contains("\"B\"")); +} + +#[test] +fn batch_rejects_too_many_steps() { + let h = session(); + let mut g = h.lock().unwrap(); + let steps = vec![json!({"command": "command.list"}); MAX_BATCH_STEPS + 1]; + let error = g.handle("batch", json!({"steps": steps})).unwrap_err(); + assert!(error.to_string().contains("maximum is 256")); +} + +#[test] +fn render_to_file_and_base64() { + let h = session(); + let mut g = h.lock().unwrap(); + g.handle("doc.new", json!({"width": 40, "height": 20, "background": "black"})).unwrap(); + let b = g.handle("doc.render", json!({"maxSide": 10})).unwrap(); + let png = base64::engine::general_purpose::STANDARD.decode(b["base64"].as_str().unwrap()).unwrap(); + let img = photocraft_codecs::decode(&png).unwrap(); + assert_eq!(img.dimensions(), (10, 5)); + let path = std::env::temp_dir().join(format!("pc-rpc-{}.png", std::process::id())); + let r = g.handle("doc.render", json!({"path": path.to_string_lossy(), "maxSide": 0})).unwrap(); + assert!(r["bytes"].as_u64().unwrap() > 0); + assert_eq!(photocraft_codecs::decode(&std::fs::read(&path).unwrap()).unwrap().dimensions(), (40, 20)); + let _ = std::fs::remove_file(path); +} + +#[test] +fn background_jobs_list_wait_and_cancel() { + let mut h = Headless::new(); + h.handle("doc.new", json!({"width": 600, "height": 400})).unwrap(); + h.handle("engine.execute", json!({"command": "layer.new.layer"})).unwrap(); + h.handle("engine.execute", json!({"command": "edit.fill", "params": {"color": "#808080"}})).unwrap(); + // Default: waits, the result is the command's. + let r = h.handle("engine.execute", json!({"command": "filter.noise.addNoise", "params": {"amount": 20}})).unwrap(); + assert!(r["filter"].is_object(), "{r}"); + // wait: false returns a job id at once. + let r = h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 40}, "wait": false})).unwrap(); + let job = r["job"].as_u64().unwrap(); + let listed = h.handle("jobs.list", json!({})).unwrap(); + assert!(listed["jobs"].as_array().unwrap().iter().any(|j| j["id"] == job), "{listed}"); + // Wait for it via jobs.list (which applies finished jobs). + let t = std::time::Instant::now(); + loop { + let l = h.handle("jobs.list", json!({})).unwrap(); + let state = l["jobs"].as_array().unwrap().iter().find(|j| j["id"] == job).map(|j| j["state"].clone()); + if state == Some(json!("done")) { + break; + } + assert!(t.elapsed().as_secs() < 60, "{l}"); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + // Cancel: a second job, cancelled at once, leaves the document unchanged. + let before = h.session.active().unwrap().doc.clone(); + let r = h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 40}, "wait": false})).unwrap(); + let job = r["job"].as_u64().unwrap(); + h.handle("jobs.cancel", json!({"job": job})).unwrap(); + assert!(h.handle("jobs.cancel", json!({"job": "nope"})).is_err()); + let l = h.handle("jobs.list", json!({})).unwrap(); + assert_eq!(l["jobs"].as_array().unwrap().iter().find(|j| j["id"] == job).unwrap()["state"], "cancelled"); + assert!(std::sync::Arc::ptr_eq(&h.session.active().unwrap().doc, &before)); +} + +#[test] +fn batch_steps_can_start_background_jobs() { + let mut h = Headless::new(); + h.handle("doc.new", json!({"width": 600, "height": 400})).unwrap(); + let steps = json!([ + {"command": "layer.new.layer"}, + {"command": "edit.fill", "params": {"color": "#808080"}}, + {"command": "filter.blur.gaussianBlur", "params": {"radius": 40}, "wait": false} + ]); + let r = h.handle("batch", json!({"steps": steps})).unwrap(); + assert_eq!(r["completed"], 3, "{r}"); + let job = r["results"][2]["result"]["job"].as_u64().unwrap_or_else(|| panic!("no job id: {r}")); + assert_eq!(r["results"][2]["result"]["pending"], true); + let listed = h.handle("jobs.list", json!({})).unwrap(); + assert!(listed["jobs"].as_array().unwrap().iter().any(|j| j["id"] == job), "{listed}"); + let t = std::time::Instant::now(); + while h.session.jobs().iter().any(|j| j.id.0 == job) { + assert!(t.elapsed().as_secs() < 60); + std::thread::sleep(std::time::Duration::from_millis(5)); + h.handle("jobs.list", json!({})).unwrap(); + } +} + +/// Regression (#503): a finished `wait: false` job was only applied by a later command or +/// `jobs.list`, so save, inspect, render and `session.list` still saw the document without it. +#[test] +fn every_request_sees_a_finished_background_job() { + let dir = std::env::temp_dir().join(format!("pc-rpc-job-sync-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (before, after) = (dir.join("before.png"), dir.join("after.png")); + let mut h = Headless::trusted_local(); + h.handle("doc.new", json!({"width": 64, "height": 48})).unwrap(); + h.handle("engine.execute", json!({"command": "filter.noise.addNoise", "params": {"amount": 50}})).unwrap(); + h.handle("doc.save", json!({"path": before.to_string_lossy()})).unwrap(); + let render = |h: &mut Headless| h.handle("doc.render", json!({"maxSide": 0})).unwrap()["base64"].clone(); + let unblurred = render(&mut h); + let revision = |h: &mut Headless| h.handle("session.list", json!({})).unwrap()["documents"][0]["revision"].clone(); + let start = revision(&mut h); + h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 4}, "wait": false})).unwrap(); + // Only reading requests from here on: no command and no `jobs.list`. + let t = std::time::Instant::now(); + while revision(&mut h) == start { + assert!(t.elapsed().as_secs() < 60, "session.list never saw the finished job"); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let history = h.handle("doc.inspect", json!({})).unwrap()["history"].clone(); + assert_eq!(history.as_array().unwrap().last().unwrap(), "Gaussian Blur", "{history}"); + h.handle("doc.save", json!({"path": after.to_string_lossy()})).unwrap(); + let decode = |p: &std::path::Path| photocraft_codecs::decode(&std::fs::read(p).unwrap()).unwrap().to_rgba8(); + assert_ne!(decode(&before), decode(&after), "the export holds the blur"); + assert_ne!(render(&mut h), unblurred, "the preview holds the blur"); + std::fs::remove_dir_all(dir).unwrap(); +} + +/// Regression: `quality` 85.0 or "85" was ignored (a lossless WebP, reply ok) and 0 or 500 was +/// clamped, where the CLI refuses anything but a whole number from 1 to 100. +#[test] +fn doc_save_rejects_a_bad_quality_instead_of_ignoring_or_clamping_it() { + let dir = std::env::temp_dir().join(format!("pc-rpc-save-quality-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("x.webp"); + let mut h = Headless::trusted_local(); + h.handle("doc.new", json!({"width": 16, "height": 16})).unwrap(); + for q in [json!(85.0), json!("85"), json!(0), json!(500), json!(-5), json!(true)] { + let err = h.handle("doc.save", json!({"path": path.to_string_lossy(), "quality": q})).unwrap_err().to_string(); + assert!(err.contains("quality"), "{q}: {err}"); + assert!(!path.exists(), "{q} wrote a file"); + } + h.handle("doc.save", json!({"path": path.to_string_lossy(), "quality": 85})).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(bytes.get(12..16), Some(&b"VP8 "[..]), "a WebP saved with a quality is lossy"); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn automation_preview_rejects_oversized_full_size_and_numeric_wraparound() { + let mut h = Headless::new(); + h.handle("doc.new", json!({"width": 2049, "height": 1})).unwrap(); + for max in [json!(0), json!(2049), json!(u64::from(u32::MAX) + 1), json!(-1), json!(1.5)] { + assert!(h.handle("doc.render", json!({"maxSide": max})).is_err()); + } + // A smaller preview still works, and rejection leaves the source document intact. + let rendered = h.handle("doc.render", json!({"maxSide": 32})).unwrap(); + let png = base64::engine::general_purpose::STANDARD.decode(rendered["base64"].as_str().unwrap()).unwrap(); + assert_eq!(photocraft_codecs::decode(&png).unwrap().dimensions(), (32, 1)); + assert_eq!(h.session.active().unwrap().doc.size.width, 2049); +} + +#[test] +fn stdio_rejects_oversized_frames_before_dispatch() { + let h = Mutex::new(Headless::new()); + let input = " ".repeat(MAX_REQUEST_BYTES + 1); + let mut out = Vec::new(); + serve_lines(&h, input.as_bytes(), &mut out).unwrap(); + let reply: Value = serde_json::from_slice(&out).unwrap(); + assert_eq!(reply["ok"], false); + assert!(reply["error"].as_str().unwrap().contains("request exceeds")); + assert!(h.lock().unwrap().session.documents().is_empty()); +} + +/// Regression (#505): an over-long or non-UTF-8 line ended the stdio session, losing every +/// open document. Now it gets one error reply, the rest of the line is skipped (never +/// dispatched), and the next request is served. +#[test] +fn stdio_skips_a_rejected_line_and_keeps_the_session() { + let h = Mutex::new(Headless::new()); + let mut input = b"{\"id\":1,\"method\":\"doc.new\",\"params\":{\"width\":8,\"height\":8}}\n".to_vec(); + input.extend(" ".repeat(MAX_REQUEST_BYTES + 1).into_bytes()); + input.extend(b"{\"id\":9,\"method\":\"doc.close\"}\n"); + input.extend(b"\xff\xfe{\"id\":8,\"method\":\"doc.close\"}\n"); + input.extend(b"{\"id\":2,\"method\":\"session.list\"}\n"); + let mut out = Vec::new(); + serve_lines(&h, input.as_slice(), &mut out).unwrap(); + let replies: Vec = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(replies.len(), 4, "{replies:?}"); + assert_eq!(replies[0]["ok"], true); + assert!(replies[1]["error"].as_str().unwrap().contains("request exceeds"), "{}", replies[1]); + assert!(replies[2]["error"].as_str().unwrap().contains("not valid UTF-8"), "{}", replies[2]); + assert_eq!(replies[3]["id"], 2); + assert_eq!(replies[3]["result"]["documents"].as_array().unwrap().len(), 1, "the document stays open"); +} + +#[test] +fn preview_rejection_precedes_output_file_creation() { + let root = std::env::temp_dir().join(format!("pc-preview-budget-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let workspace = crate::AuthorizedWorkspace::new(None, Some(&root)).unwrap(); + let mut h = Headless::with_workspace(workspace); + h.handle("doc.new", json!({"width": 16, "height": 8})).unwrap(); + let result = h.handle("doc.render", json!({"maxSide": 2049, "path": "rejected.png"})); + assert!(result.unwrap_err().to_string().contains("preview side exceeds")); + assert!(!root.join("rejected.png").exists()); + assert!(h.handle("doc.render", json!({"maxSide": 16, "path": "accepted.png"})).is_ok()); + assert!(root.join("accepted.png").exists()); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_file(root.join("accepted.png")).unwrap(); + std::fs::remove_dir(root).unwrap(); +} + +#[test] +fn doc_place_reads_through_the_read_root_and_never_outside_it() { + let base = std::env::temp_dir().join(format!("pc-doc-place-{}", std::process::id())); + let root = base.join("workspace"); + let outside = base.join("outside"); + for dir in [&root, &outside] { + std::fs::create_dir_all(dir).unwrap(); + } + let img = photocraft_codecs::Image::from_u8(8, 6, photocraft_codecs::ChannelLayout::Rgb, vec![42; 8 * 6 * 3]).unwrap(); + let png = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + std::fs::write(root.join("logo.png"), &png).unwrap(); + std::fs::write(outside.join("logo.png"), &png).unwrap(); + let absolute = outside.join("logo.png").to_string_lossy().into_owned(); + + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); + let placed = h.handle("doc.place", json!({"path": "logo.png", "scale": 50})).unwrap(); + assert!(placed["layer"].as_u64().is_some(), "{placed}"); + assert_eq!(placed["scale"].as_f64(), Some(50.0), "the options reach the command: {placed}"); + let inspected = h.handle("doc.inspect", json!({})).unwrap(); + assert_eq!(inspected["layers"].as_array().map(Vec::len), Some(2), "the placed layer is in the document: {inspected}"); + // A path outside the read root is refused the way the ambient command is (#2810). + for (path, reason) in [("../outside/logo.png", "parent traversal"), (absolute.as_str(), "must be inside the automation root")] { + let refused = h.handle("doc.place", json!({"path": path})).unwrap_err().to_string(); + assert!(refused.contains(reason), "{refused}"); + let inspected = h.handle("doc.inspect", json!({})).unwrap(); + assert_eq!(inspected["layers"].as_array().map(Vec::len), Some(2), "nothing was placed: {refused}"); + } + // Trusted local keeps the ambient command: that caller may read the path itself. + let mut t = Headless::trusted_local(); + t.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); + let trusted = t.handle("doc.place", json!({"path": root.join("logo.png").to_string_lossy()})).unwrap(); + assert!(trusted["layer"].as_u64().is_some(), "{trusted}"); + // Release directory capabilities before cleanup on Windows. + drop(t); + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn doc_replace_smart_object_reads_through_the_read_root_and_never_outside_it() { + let base = std::env::temp_dir().join(format!("pc-doc-replace-so-{}", std::process::id())); + let root = base.join("workspace"); + let outside = base.join("outside"); + for dir in [&root, &outside] { + std::fs::create_dir_all(dir).unwrap(); + } + let png = |w: u32, h: u32, v: u8| { + let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, vec![v; (w * h * 3) as usize]).unwrap(); + photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap() + }; + std::fs::write(root.join("logo.png"), png(8, 6, 42)).unwrap(); + std::fs::write(root.join("red.png"), png(8, 6, 200)).unwrap(); + std::fs::write(outside.join("red.png"), png(8, 6, 200)).unwrap(); + let absolute = outside.join("red.png").to_string_lossy().into_owned(); + + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); + let layer = h.handle("doc.place", json!({"path": "logo.png"})).unwrap()["layer"].clone(); + // The smart object's file name and the composite at its centre: what Replace Contents changes. + let contents = |h: &mut Headless| { + let inspected = h.handle("doc.inspect", json!({})).unwrap(); + let layers = inspected["layers"].as_array().unwrap(); + let so = layers.iter().find(|l| l["id"] == layer).unwrap_or_else(|| panic!("{inspected}")); + let name = so["smartSource"]["fileName"].as_str().unwrap_or_default().to_owned(); + let rendered = h.handle("doc.render", json!({"maxSide": 0})).unwrap(); + let png = base64::engine::general_purpose::STANDARD.decode(rendered["base64"].as_str().unwrap()).unwrap(); + let img = photocraft_codecs::decode(&png).unwrap(); + let (w, ht) = img.dimensions(); + let data = img.as_u8().unwrap(); + let channels = data.len() / (w * ht) as usize; + (name, data[((ht / 2 * w + w / 2) as usize) * channels]) + }; + assert_eq!(contents(&mut h), ("logo.png".to_owned(), 42), "the placed contents"); + let replaced = h.handle("doc.replaceSmartObject", json!({"path": "red.png", "layer": layer})).unwrap(); + assert_eq!(replaced["layer"], layer, "{replaced}"); + assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "the contents were replaced"); + h.handle("engine.execute", json!({"command": "edit.undo"})).unwrap(); + assert_eq!(contents(&mut h), ("logo.png".to_owned(), 42), "one undo step restores the old contents"); + h.handle("engine.execute", json!({"command": "edit.redo"})).unwrap(); + assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "redo replaces them again"); + // Outside the read root, a bad layer, a missing path or a file that is no image: refused, nothing changed. + for (params, reason) in [ + (json!({"path": "../outside/red.png"}), "parent traversal"), + (json!({"path": absolute}), "must be inside the automation root"), + (json!({"path": "logo.png", "layer": 999_999}), "no such layer"), + (json!({}), "needs `path`"), + ] { + let refused = h.handle("doc.replaceSmartObject", params).unwrap_err().to_string(); + assert!(refused.contains(reason), "{refused}"); + assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "nothing changed: {refused}"); + } + std::fs::write(root.join("junk.png"), b"not an image").unwrap(); + assert!(h.handle("doc.replaceSmartObject", json!({"path": "junk.png", "layer": layer})).is_err()); + assert_eq!(contents(&mut h), ("red.png".to_owned(), 200), "a file that is no image changes nothing"); + // The ambient command keeps its refusal. + let ambient = h.handle("engine.execute", json!({"command": "layer.smartObjects.replaceContents", "params": {"path": "red.png"}})); + assert!(ambient.unwrap_err().to_string().contains("ambient filesystem paths")); + // Trusted local keeps the ambient command. + let mut t = Headless::trusted_local(); + t.handle("doc.new", json!({"width": 40, "height": 30})).unwrap(); + let tl = t.handle("doc.place", json!({"path": root.join("logo.png").to_string_lossy()})).unwrap()["layer"].clone(); + let trusted = t.handle("doc.replaceSmartObject", json!({"path": root.join("red.png").to_string_lossy(), "layer": tl})).unwrap(); + assert_eq!(trusted["layer"], tl, "{trusted}"); + drop(t); + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn doc_export_layers_reports_skips_in_workspace_and_trusted_sessions() { + for trusted in [false, true] { + let base = std::env::temp_dir().join(format!("pc-export-skips-{}-{trusted}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let mut h = + if trusted { Headless::trusted_local() } else { Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&base), Some(&base)).unwrap()) }; + h.handle("doc.new", json!({"width": 4, "height": 4, "background": "white", "name": "card"})).unwrap(); + let adjustment = h.handle("engine.execute", json!({"command": "layer.newAdjustmentLayer.levels"})).unwrap()["layer"].clone(); + h.handle("engine.execute", json!({"command": "layer.setProps", "params": {"name": "Levels"}})).unwrap(); + let hidden = h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Hidden"}})).unwrap()["layer"].clone(); + h.handle("engine.execute", json!({"command": "layer.setProps", "params": {"visible": false}})).unwrap(); + // Exercise the actual JSON-lines serve envelope, not only direct dispatch. + let h = Mutex::new(h); + let out_dir = base.join("out").to_string_lossy().into_owned(); + let request = json!({"id": 8491, "method": "doc.exportLayers", "params": {"dir": out_dir}}).to_string() + "\n"; + let mut output = Vec::new(); + serve_lines(&h, request.as_bytes(), &mut output).unwrap(); + let reply: Value = serde_json::from_slice(&output).unwrap(); + assert_eq!(reply["id"], 8491); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["result"]["files"], json!([format!("{out_dir}/card_0001_Background.png")])); + if !trusted { + assert_eq!(reply["result"]["count"], 1); + } + assert_eq!( + reply["result"]["skipped"], + json!([ + {"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"}, + {"layer": adjustment, "name": "Levels", "reason": "adjustment layer has no pixels of its own"} + ]) + ); + assert_eq!(std::fs::read_dir(base.join("out")).unwrap().count(), 1); + let mut h = h.into_inner().unwrap(); + let all_dir = base.join("all").to_string_lossy().into_owned(); + let all = h.export_layers(None, &all_dir, &json!({"visibleOnly": false})).unwrap(); + assert_eq!(all["files"].as_array().unwrap().len(), 2); + assert_eq!(all["skipped"].as_array().unwrap().len(), 1); + // Workspace no-overwrite errors still fail and remove only newly created files. + if !trusted { + let collision = base.join("collision"); + std::fs::create_dir_all(&collision).unwrap(); + std::fs::write(collision.join("card_0002_Background.png"), b"keep").unwrap(); + assert!(h.export_layers(None, &collision.to_string_lossy(), &json!({"visibleOnly": false})).is_err()); + assert_eq!(std::fs::read_dir(&collision).unwrap().count(), 1); + assert_eq!(std::fs::read(collision.join("card_0002_Background.png")).unwrap(), b"keep"); + } + drop(h); + std::fs::remove_dir_all(base).unwrap(); + } +} + +#[test] +fn doc_export_layers_writes_only_beneath_the_write_root() { + let base = std::env::temp_dir().join(format!("pc-doc-export-layers-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 12, "height": 8, "background": "white", "name": "card"})).unwrap(); + h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Badge"}})).unwrap(); + + let out = root.join("out"); + let exported = h.handle("doc.exportLayers", json!({"dir": out.to_string_lossy(), "format": "png", "prefix": "card"})).unwrap(); + assert_eq!(exported["count"].as_u64(), Some(2), "{exported}"); + let mut names: Vec = std::fs::read_dir(&out).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names.len(), 2, "{exported}"); + for name in names { + assert!(name.starts_with("card_") && name.ends_with(".png"), "{name}"); + let bytes = std::fs::read(out.join(&name)).unwrap(); + assert_eq!(photocraft_codecs::decode(&bytes).unwrap().dimensions(), (12, 8), "{name}"); + } + // Outside the write root nothing is created, not even the directory. + let escaped = base.join("escaped"); + let refused = h.handle("doc.exportLayers", json!({"dir": escaped.to_string_lossy()})).unwrap_err().to_string(); + assert!(refused.contains("must be inside the automation root"), "{refused}"); + assert!(!escaped.exists()); + // The ambient command keeps its refusal for the very same directory. + let ambient = + h.handle("engine.execute", json!({"command": "file.export.layersToFiles", "params": {"dir": out.to_string_lossy()}})).unwrap_err().to_string(); + assert!(ambient.contains("ambient filesystem paths"), "{ambient}"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn doc_export_data_sets_refuse_collisions_and_import_reads_the_root() { + let base = std::env::temp_dir().join(format!("pc-doc-data-sets-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "card"})).unwrap(); + let inspected = h.handle("doc.inspect", json!({})).unwrap(); + let layer = inspected["layers"][0]["id"].as_u64().expect("the layer id"); + h.handle("engine.execute", json!({"command": "image.variables.define", "params": {"defs": [{"name": "show", "layer": layer, "type": "visibility"}]}})) + .unwrap(); + h.handle( + "engine.execute", + json!({"command": "image.variables.dataSets", "params": {"dataSets": [ + {"name": "one", "values": [{"variable": "show", "kind": "visibility", "value": true}]}, + {"name": "two", "values": [{"variable": "show", "kind": "visibility", "value": false}]}, + ]}}), + ) + .unwrap(); + + let sets = root.join("sets"); + let exported = h.handle("doc.exportDataSets", json!({"dir": sets.to_string_lossy(), "format": "png"})).unwrap(); + assert_eq!(exported["count"].as_u64(), Some(2), "{exported}"); + assert_eq!(std::fs::read_dir(&sets).unwrap().count(), 2, "{exported}"); + // Colliding names are refused as in the command, before any file is written. + let clash = root.join("clash"); + let refused = h.handle("doc.exportDataSets", json!({"dir": clash.to_string_lossy(), "naming": "{document}"})).unwrap_err().to_string(); + assert!(refused.contains("{index}"), "{refused}"); + assert_eq!(std::fs::read_dir(&clash).unwrap().count(), 0, "no file of the refused batch"); + // A CSV from the read root, and one outside it. + std::fs::write(root.join("sets.csv"), "Data Set,show\none,true\ntwo,false\n").unwrap(); + let imported = h.handle("doc.importDataSets", json!({"path": "sets.csv"})).unwrap(); + assert_eq!(imported["imported"].as_u64(), Some(2), "{imported}"); + std::fs::write(base.join("outside.csv"), "Data Set,show\none,true\n").unwrap(); + let outside = h.handle("doc.importDataSets", json!({"path": base.join("outside.csv").to_string_lossy()})).unwrap_err().to_string(); + assert!(outside.contains("must be inside the automation root"), "{outside}"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn indexed_place_replace_and_data_set_methods_keep_the_active_document() { + let base = std::env::temp_dir().join(format!("pc-doc-index-active-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let img = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgb, vec![42; 4 * 4 * 3]).unwrap(); + std::fs::write(root.join("logo.png"), photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); + std::fs::write(root.join("sets.csv"), "Data Set,show\none,true\ntwo,false\n").unwrap(); + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "first"})).unwrap(); + h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "second"})).unwrap(); + let layer = h.handle("doc.inspect", json!({})).unwrap()["layers"][0]["id"].as_u64().expect("the layer id"); + h.handle("engine.execute", json!({"command": "image.variables.define", "params": {"defs": [{"name": "show", "layer": layer, "type": "visibility"}]}})) + .unwrap(); + h.handle("doc.select", json!({"index": 0})).unwrap(); + + let steps = [ + ("doc.place", json!({"path": "logo.png", "index": 1}), true), + // Document 1's active layer is now the placed Smart Object. + ("doc.replaceSmartObject", json!({"path": "logo.png", "index": 1}), true), + ("doc.replaceSmartObject", json!({"path": "missing.png", "index": 1}), false), + ("doc.importDataSets", json!({"path": "sets.csv", "index": 1}), true), + ("doc.exportLayers", json!({"dir": "layers", "index": 1}), true), + ("doc.exportDataSets", json!({"dir": "sets", "index": 1}), true), + // A failing call restores the active document too. + ("doc.importDataSets", json!({"path": "missing.csv", "index": 1}), false), + ]; + for (method, params, succeeds) in steps { + let result = h.handle(method, params.clone()); + assert_eq!(result.is_ok(), succeeds, "{method} {params}: {result:?}"); + assert_eq!(h.session.active_index(), Some(0), "{method} {params} must not select document 1"); + } + assert_eq!(h.session.documents()[0].doc.layer_count(), 1, "nothing was placed into the active document"); + assert_eq!(h.session.documents()[1].doc.layer_count(), 2, "the placed layer is in document 1"); + assert_eq!(std::fs::read_dir(root.join("sets")).unwrap().count(), 2, "document 1's data sets were exported"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn doc_export_data_sets_judges_pixel_replacement_paths_like_apply() { + let base = std::env::temp_dir().join(format!("pc-doc-data-set-pixels-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let red = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgb, [255, 0, 0].repeat(16)).unwrap(); + let photo = base.join("photo.png"); + std::fs::write(&photo, photocraft_codecs::encode(&red, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "card"})).unwrap(); + let layer = h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {}})).unwrap()["layer"].clone(); + h.handle( + "engine.execute", + json!({"command": "image.variables.define", "params": {"defs": [{"name": "photo", "layer": layer, "type": "pixelReplacement"}]}}), + ) + .unwrap(); + // Storing the path is allowed; reading it is what the gate judges. + h.handle( + "engine.execute", + json!({"command": "image.variables.dataSets", "params": {"dataSets": [ + {"name": "swap", "values": [{"variable": "photo", "kind": "pixels", "value": photo.to_string_lossy()}]}, + ]}}), + ) + .unwrap(); + let applied = h.handle("engine.execute", json!({"command": "image.applyDataSet", "params": {"name": "swap"}})).unwrap_err().to_string(); + assert!(applied.contains("ambient filesystem paths"), "{applied}"); + let sets = root.join("sets"); + let exported = h.handle("doc.exportDataSets", json!({"dir": sets.to_string_lossy(), "format": "png"})).unwrap_err().to_string(); + assert!(exported.contains("ambient filesystem paths"), "{exported}"); + assert_eq!(std::fs::read_dir(&sets).map_or(0, Iterator::count), 0, "nothing of the refused batch is written"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn workspace_psd_saves_embed_no_file_a_linked_smart_object_names() { + use photocraft_engine::doc::{LayerContent, SmartSource}; + + // An image PhotoCraft can open (other linked files are never embedded): an embedded copy + // carries these exact bytes, while pixels written for the layer don't. + let image = photocraft_codecs::Image::from_u8(8, 8, photocraft_codecs::ChannelLayout::Rgb, (0..192u8).collect()).unwrap(); + let marker = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let has_marker = |bytes: &[u8]| bytes.windows(marker.len()).any(|w| w == marker.as_slice()); + let base = std::env::temp_dir().join(format!("pc-psd-linked-embed-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let outside = base.join("outside.png"); + std::fs::write(&outside, &marker).unwrap(); + // A document whose smart object names a file outside the roots as its source. + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let state = session.active_mut().unwrap(); + let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; + smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; + std::fs::write(root.join("in.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); + // A trusted export embeds the linked file, as before. + assert!(has_marker(&photocraft_io::export(&state.doc, "psd", &Default::default()).unwrap().bytes)); + + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.open", json!({"path": "in.pcraft"})).unwrap(); + let saved = h.handle("doc.save", json!({"path": "out.psd"})).unwrap(); + let warnings = saved["warnings"].to_string(); + assert!(warnings.contains("written as pixels"), "{warnings}"); + assert!(!has_marker(&std::fs::read(root.join("out.psd")).unwrap()), "the linked file outside the roots is not embedded"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn allowed_filters_do_not_rerender_a_smart_object_from_its_linked_file() { + use photocraft_engine::doc::{LayerContent, SmartSource}; + + let base = std::env::temp_dir().join(format!("pc-linked-rerender-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let red = photocraft_codecs::Image::from_u8(8, 8, photocraft_codecs::ChannelLayout::Rgb, [255, 0, 0].repeat(64)).unwrap(); + let outside = base.join("red.png"); + std::fs::write(&outside, photocraft_codecs::encode(&red, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); + // A document whose white smart object names a file outside the roots as its source. + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let state = session.active_mut().unwrap(); + let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; + smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; + std::fs::write(root.join("p.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); + + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.open", json!({"path": "p.pcraft"})).unwrap(); + h.handle("engine.execute", json!({"command": "filter.blur.gaussianBlur", "params": {"radius": 0.5}})).unwrap(); + let doc = &h.session.active().unwrap().doc; + let LayerContent::Smart(smart) = &doc.layers[0].content else { panic!("smart object") }; + assert_eq!(smart.smart_filters.len(), 1, "the filter is still recorded"); + assert_eq!(smart.cache.as_ref().unwrap().rgba(4, 4), [1.0, 1.0, 1.0, 1.0], "the linked file outside the roots is not read"); + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn workspace_layer_exports_keep_linked_smart_objects_as_pixels() { + use photocraft_engine::doc::{LayerContent, SmartSource}; + + const MARKER: &[u8] = b"PHOTOCRAFT-LINKED-0002"; + let has_marker = |bytes: &[u8]| bytes.windows(MARKER.len()).any(|w| w == MARKER); + let base = std::env::temp_dir().join(format!("pc-export-layers-linked-{}", std::process::id())); + let root = base.join("workspace"); + std::fs::create_dir_all(&root).unwrap(); + let outside = base.join("outside.txt"); + std::fs::write(&outside, MARKER).unwrap(); + // A document whose smart object names a file outside the roots as its source. + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let state = session.active_mut().unwrap(); + let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") }; + smart.source = SmartSource::Linked { path: outside.to_string_lossy().into_owned() }; + std::fs::write(root.join("in.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap(); + + let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); + h.handle("doc.open", json!({"path": "in.pcraft"})).unwrap(); + let out = root.join("layers"); + for format in ["psd", "psb"] { + let exported = h.handle("doc.exportLayers", json!({"dir": out.to_string_lossy(), "format": format})).unwrap(); + assert_eq!(exported["count"], 1, "{exported}"); + } + let files: Vec<_> = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().path()).collect(); + assert_eq!(files.len(), 2, "{files:?}"); + for file in files { + assert!(!has_marker(&std::fs::read(&file).unwrap()), "{} embeds no file outside the roots", file.display()); + } + // Release directory capabilities before cleanup on Windows. + drop(h); + std::fs::remove_dir_all(base).unwrap(); +} + +#[test] +fn trusted_local_render_keeps_full_size_behavior() { + let mut h = Headless::trusted_local(); + h.handle("doc.new", json!({"width": 2049, "height": 1})).unwrap(); + let rendered = h.handle("doc.render", json!({"maxSide": 0})).unwrap(); + let png = base64::engine::general_purpose::STANDARD.decode(rendered["base64"].as_str().unwrap()).unwrap(); + assert_eq!(photocraft_codecs::decode(&png).unwrap().dimensions(), (2049, 1)); +} + +#[test] +fn methods_lists_the_job_methods_and_every_listed_name_is_served() { + let mut h = Headless::new(); + let listed = h.handle("methods", Value::Null).unwrap(); + let listed: Vec<&str> = listed.as_array().unwrap().iter().map(|m| m.as_str().unwrap()).collect(); + assert_eq!(listed, METHODS); + // The job methods `engine.execute {"wait": false}` depends on are discoverable (#414). + assert!(listed.contains(&"jobs.list") && listed.contains(&"jobs.cancel")); + for m in METHODS { + if let Err(e) = h.handle(m, Value::Null) { + assert!(!e.to_string().contains("unknown method"), "{m} is listed but not served: {e}"); + } + } + assert!(h.handle("jobs.nope", Value::Null).unwrap_err().to_string().contains("unknown method")); +} + +#[test] +fn batch_response_budget_stops_later_steps_even_when_stop_on_error_is_false() { + let mut h = Headless::new(); + let mut steps = vec![json!({"command": "command.list"}); MAX_BATCH_STEPS - 1]; + steps.push(json!({"command": "file.new", "params": {"width": 8, "height": 8}})); + let result = h.batch(&json!({"steps": steps, "stopOnError": false})).unwrap(); + assert_eq!(result["failed"], 1); + assert!(result["results"].as_array().unwrap().last().unwrap()["error"].as_str().unwrap().contains("batch response budget exceeded")); + assert!(h.session.documents().is_empty(), "later edit must not execute after the quota is exhausted"); + assert!(crate::budgets::json_bytes(&result).is_ok()); + assert!(h.handle("methods", Value::Null).is_ok()); +} + +#[test] +fn idle_tcp_daemon_releases_its_port_but_keeps_active_clients() { + use std::io::BufReader; + const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let h = Arc::new(Mutex::new(Headless::new())); + let (ready_tx, ready_rx) = std::sync::mpsc::channel(); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let server = std::thread::spawn(move || { + let result = serve_tcp_until_idle("127.0.0.1:0", h, TOKEN.to_owned(), move |addr| ready_tx.send(addr).unwrap(), Duration::from_millis(200)); + done_tx.send(result).unwrap(); + }); + let addr = ready_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + let mut client = std::net::TcpStream::connect(addr).unwrap(); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let mut reader = BufReader::new(client.try_clone().unwrap()); + writeln!(client, r#"{{"id":"auth","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + let auth: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(auth["result"]["authenticated"], true); + // The port stays owned well past the idle limit while a client is connected. + assert!(matches!(done_rx.recv_timeout(Duration::from_millis(450)), Err(std::sync::mpsc::RecvTimeoutError::Timeout)), "daemon exited with a live client"); + drop(reader); + drop(client); + assert!(done_rx.recv_timeout(Duration::from_secs(3)).unwrap().is_ok(), "idle daemon did not exit cleanly"); + server.join().unwrap(); + assert!(TcpListener::bind(addr).is_ok(), "idle listener still owns its port"); +} + +#[test] +fn tcp_serves_loopback() { + use std::io::{BufReader, Write as _}; + const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let h = Arc::new(Mutex::new(Headless::new())); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap()); + }); + let addr = rx.recv().unwrap(); + let mut s = std::net::TcpStream::connect(addr).unwrap(); + writeln!(s, r#"{{"id":"auth","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); + let mut reader = BufReader::new(s.try_clone().unwrap()); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + let auth: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(auth["result"]["authenticated"], true); + writeln!(s, r#"{{"id":"a","method":"methods"}}"#).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + let v: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(v["id"], "a"); + assert!(v["result"].as_array().unwrap().iter().any(|m| m == "batch")); +} + +/// #4965: a connection that keeps sending without authenticating is closed at the deadline, +/// and one that authenticated in time keeps being served after it. +#[test] +fn tcp_connections_must_authenticate_before_the_deadline_whatever_they_send() { + use std::io::{BufReader, Write as _}; + use std::time::{Duration, Instant}; + const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let h = Mutex::new(Headless::new()); + let mut results = Vec::new(); + for _ in 0..2 { + let (stream, _) = listener.accept().unwrap(); + let started = Instant::now(); + let r = serve_tcp_connection(&h, stream, TOKEN, Duration::from_millis(300)); + results.push((r.map_err(|e| e.kind()), started.elapsed())); + } + results + }); + + // Never a newline, a byte every 20 ms: each read succeeds long before the idle timeout. + let mut slow = std::net::TcpStream::connect(addr).unwrap(); + for _ in 0..150 { + if slow.write_all(b" ").is_err() { + break; + } + std::thread::sleep(Duration::from_millis(20)); + } + drop(slow); + + // Authenticates at once, then asks again 300 ms after the deadline. + let mut s = std::net::TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + writeln!(s, r#"{{"id":"auth","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); + let mut reader = BufReader::new(s.try_clone().unwrap()); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap()["result"]["authenticated"], true); + std::thread::sleep(Duration::from_millis(600)); + writeln!(s, r#"{{"id":"a","method":"methods"}}"#).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap()["id"], "a"); + drop(reader); + drop(s); + + let results = server.join().unwrap(); + let (slow_result, slow_time) = &results[0]; + assert!(matches!(slow_result, Err(std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock)), "{slow_result:?}"); + assert!(*slow_time < Duration::from_secs(3), "the trickle did not extend the deadline: {slow_time:?}"); + assert_eq!(results[1].0, Ok(()), "the authenticated connection ended with its client"); +} + +#[test] +fn tcp_repeat_auth_reports_already_authenticated_and_keeps_serving() { + use std::io::{BufReader, Write as _}; + const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let h = Arc::new(Mutex::new(Headless::new())); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap()); + }); + let addr = rx.recv().unwrap(); + let mut s = std::net::TcpStream::connect(addr).unwrap(); + let mut reader = BufReader::new(s.try_clone().unwrap()); + let mut line = String::new(); + for id in ["auth", "again"] { + writeln!(s, r#"{{"id":"{id}","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + } + let again: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(again["id"], "again"); + assert_eq!(again["ok"], false); + assert_eq!(again["error"], "already authenticated"); + writeln!(s, r#"{{"id":"m","method":"methods"}}"#).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + let v: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(v["id"], "m"); + assert_eq!(v["ok"], true); +} + +#[test] +fn tcp_rejects_requests_before_authentication() { + use std::io::{BufReader, Write as _}; + const TOKEN: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let h = Arc::new(Mutex::new(Headless::new())); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap()); + }); + let addr = rx.recv().unwrap(); + let mut s = std::net::TcpStream::connect(addr).unwrap(); + writeln!(s, r#"{{"id":1,"method":"methods"}}"#).unwrap(); + let mut line = String::new(); + BufReader::new(s).read_line(&mut line).unwrap(); + let v: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(v["ok"], false); + assert_eq!(v["error"], "authentication required"); + assert!(v.get("result").is_none()); +} + +#[test] +fn invalid_document_index_is_rejected_not_the_active_document() { + let h = session(); + for _ in 0..2 { + assert_eq!(respond(&h, r#"{"method":"doc.new","params":{"width":8,"height":8}}"#)["ok"], true); + } + let count = |h: &Mutex| h.lock().unwrap().session_list()["documents"].as_array().unwrap().len(); + for index in [json!("0"), json!(-1), json!(0.5), json!(true)] { + for method in ["doc.close", "doc.inspect", "doc.select"] { + let reply = respond(&h, &json!({"method": method, "params": {"index": index}}).to_string()); + assert_eq!(reply["ok"], false, "{method} {index}: {reply}"); + assert!(reply["error"].as_str().unwrap().contains("`index` must be a non-negative integer"), "{reply}"); + } + assert_eq!(count(&h), 2, "index {index} closed a document"); + } + // Null means "the active document", like a missing `index`. + assert_eq!(respond(&h, r#"{"method":"doc.inspect","params":{"index":null}}"#)["ok"], true); + // A valid index still closes that document. + let reply = respond(&h, r#"{"method":"doc.close","params":{"index":0}}"#); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(count(&h), 1); +} From 8b25e3f81be41518fe3a4988b5676fba8f783e62 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:46 +0000 Subject: [PATCH 116/259] refactor(io): move blocks.rs tests to blocks/tests.rs --- crates/io/src/blocks.rs | 340 +--------------------------------- crates/io/src/blocks/tests.rs | 335 +++++++++++++++++++++++++++++++++ 2 files changed, 336 insertions(+), 339 deletions(-) create mode 100644 crates/io/src/blocks/tests.rs diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rs index 0cfe0b5e8e..5e9a76b7ca 100644 --- a/crates/io/src/blocks.rs +++ b/crates/io/src/blocks.rs @@ -916,345 +916,7 @@ pub fn effects_enabled(lfx2: &[u8]) -> bool { } #[cfg(test)] -mod tests { - use super::*; - - fn noise_gradient_fill(min: [i32; 4], max: [i32; 4], add_transparency: bool) -> Descriptor { - let values = |v: [i32; 4]| Value::List(v.into_iter().map(Value::Integer).collect()); - let gradient = Descriptor::new("Grdn") - .with("GrdF", Value::Enumerated { type_id: Id::new("GrdF"), value: Id::new("ClNs") }) - .with("ClrS", Value::Enumerated { type_id: Id::new("ClrS"), value: Id::new("RGBC") }) - .with("ShTr", Value::Boolean(add_transparency)) - .with("VctC", Value::Boolean(true)) - .with("RndS", Value::Integer(9052369)) - .with("Smth", Value::Integer(2048)) - .with("Mnm ", values(min)) - .with("Mxm ", values(max)); - Descriptor::new("null").with("Grad", Value::Descriptor(gradient)) - } - - #[test] - fn constant_rgb_noise_fill_uses_its_exact_colour() { - use photocraft_doc::Fill; - let fill = fill_from_desc(b"GdFl", &noise_gradient_fill([50, 25, 0, 0], [50, 25, 0, 100], false)); - let Some(Fill::Gradient { stops, .. }) = fill else { panic!("constant noise gradient") }; - assert_eq!(stops, vec![(0.0, Color::rgb(0.5, 0.25, 0.0)), (1.0, Color::rgb(0.5, 0.25, 0.0))]); - } - - #[test] - fn variable_or_transparent_noise_stays_a_fill_with_the_placeholder_ramp() { - use photocraft_doc::Fill; - // Photoshop's default Noise gradient (min 0, max 100) and a transparent variant: no - // exact colour is provable, but the fill must parse — the layer keeps its type, its - // stored pixels (`fill_cache`) and its raw `GdFl` block. Only the uncached preview - // shows the placeholder ramp. - for descriptor in [noise_gradient_fill([0, 0, 0, 0], [100, 100, 100, 100], false), noise_gradient_fill([50, 25, 0, 0], [50, 25, 0, 100], true)] { - let Some(Fill::Gradient { stops, .. }) = fill_from_desc(b"GdFl", &descriptor) else { panic!("variable noise gradient must stay a fill layer") }; - assert_eq!(stops, vec![(0.0, Color::BLACK), (1.0, Color::WHITE)]); - } - } - - /// psd-tools layers-minimal/gradient-fill.psd ("Color to Transparent", no stored pixels): a - /// gradient fill's opacity stops reach the model (as its opacity stops; written from stop - /// alpha) and survive a write; the ramp's alpha follows them. - #[test] - fn gradient_fill_opacity_stops_become_alpha() { - use photocraft_color::Color; - use photocraft_doc::{Fill, GradientStyle}; - let red = Color::rgba(1.0, 0.0, 0.0, 1.0); - let f = Fill::gradient(vec![(0.0, red), (1.0, Color { alpha: 0.0, ..red })], 90.0, 1.0, GradientStyle::Linear, false); - let (k, data) = super::write_fill(&f); - let back = super::parse_fill(&k, &data).unwrap(); - let Fill::Gradient { stops, opacity_stops, .. } = &back else { panic!("gradient") }; - assert_eq!(opacity_stops, &vec![(0.0, 1.0), (1.0, 0.0)]); - assert!(stops.iter().all(|s| s.1.c[0] == 1.0 && s.1.c[1] == 0.0)); - let ramp = photocraft_compose::gradient_fill::Ramp::new(&back).unwrap(); - assert_eq!(ramp.sample(0.0)[3], 1.0); - assert!(ramp.sample(1.0)[3] < 0.01); - // Opaque gradients come back without opacity stops. - let (k, data) = super::write_fill(&Fill::gradient(vec![(0.0, red), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false)); - let Some(Fill::Gradient { opacity_stops, .. }) = super::parse_fill(&k, &data) else { panic!("gradient") }; - assert!(opacity_stops.is_empty()); - } - - /// Photoshop 27.11 stores a gradient's method as the enum `gradientsInterpolationMethod` - /// (seen in gradient fill layers saved by scripted Photoshop): a black→white Linear gradient - /// is at 188 of 255 halfway (measured), where Classic gives 128. The key used to be read as - /// `gs99`, which Photoshop doesn't write, so every gradient opened as Classic. - #[test] - fn gradient_fill_reads_the_interpolation_method() { - use photocraft_color::Color; - use photocraft_doc::{Fill, GradientStyle}; - use photocraft_psd::descriptor::{Id, Value}; - let f = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false); - let (k, data) = super::write_fill(&f); - let d = super::parse_prefix_versioned(&data).unwrap(); - let mid = |code: &str| { - let d = - d.clone().with("gradientsInterpolationMethod", Value::Enumerated { type_id: Id::new("gradientInterpolationMethodType"), value: Id::new(code) }); - let back = super::fill_from_desc(&k, &d).unwrap(); - let ramp = photocraft_compose::gradient_fill::Ramp::new(&back).unwrap(); - (ramp.sample(0.5)[0] * 255.0).round() - }; - assert_eq!(mid("Gcls"), 128.0); - assert!((mid("Lnr ") - 188.0).abs() <= 1.0, "Linear: {}", mid("Lnr ")); - assert!((mid("Perc") - 99.0).abs() <= 2.0, "Perceptual: {}", mid("Perc")); - assert!((mid("Smoo") - 99.0).abs() <= 2.0, "Smooth: {}", mid("Smoo")); - } - - #[test] - fn lab_descriptor_colours_round_trip() { - use photocraft_color::ColorMode; - use photocraft_psd::descriptor::{Descriptor, Value}; - let d = Descriptor::new("LbCl").with("Lmnc", Value::Double(19.07)).with("A ", Value::Double(52.29)).with("B ", Value::Double(-85.08)); - let c = super::color_from_desc(&d).unwrap(); - assert_eq!(c.mode, ColorMode::Lab); - assert!((c.c[0] - 0.1907).abs() < 1e-5 && (c.c[1] * 255.0 - 128.0 - 52.29).abs() < 1e-3 && (c.c[2] * 255.0 - 128.0 + 85.08).abs() < 1e-3); - let back = super::color_from_desc(&super::color_to_desc(&c)).unwrap(); - assert_eq!(back.mode, ColorMode::Lab); - for i in 0..3 { - assert!((back.c[i] - c.c[i]).abs() < 1e-6); - } - // Missing components are rejected, not defaulted. - assert!(super::color_from_desc(&Descriptor::new("LbCl").with("Lmnc", Value::Double(50.0))).is_none()); - } - - /// Colours stored as HSB (`HSBC`: `H ` an angle in degrees, `Strt`/`Brgh` 0..100), as in - /// psd-tools `stroke-color-descriptors-hsb-with-rgb-mode.psd`, used to be dropped (#6774). - #[test] - fn hsb_descriptor_colours_parse() { - use photocraft_doc::Fill; - use photocraft_psd::descriptor::{Descriptor, Value}; - let hsb = |h: f64, s: f64, b: f64| { - Descriptor::new("HSBC").with("H ", Value::UnitFloat { unit: *b"#Ang", value: h }).with("Strt", Value::Double(s)).with("Brgh", Value::Double(b)) - }; - let close = |c: [f32; 3], e: [f32; 3]| c.iter().zip(e).all(|(a, b)| (a - b).abs() < 1e-5); - let green = super::color_from_desc(&hsb(120.0, 100.0, 100.0)).unwrap().to_rgb(); - assert!(close(green, [0.0, 1.0, 0.0]), "{green:?}"); - let white = super::color_from_desc(&hsb(0.0, 0.0, 100.0)).unwrap().to_rgb(); - assert!(close(white, [1.0, 1.0, 1.0]), "{white:?}"); - let half = super::color_from_desc(&hsb(240.0, 50.0, 50.0)).unwrap().to_rgb(); - assert!(close(half, [0.25, 0.25, 0.5]), "{half:?}"); - // A solid fill (`SoCo`) with an HSB colour is read, not lost. - let soco = Descriptor::new("null").with("Clr ", Value::Descriptor(hsb(0.0, 100.0, 100.0))); - let Some(Fill::Solid(c)) = super::fill_from_desc(b"SoCo", &soco) else { panic!("solid fill") }; - assert!(close(c.to_rgb(), [1.0, 0.0, 0.0]), "{:?}", c.to_rgb()); - // Missing components are rejected, not defaulted. - assert!(super::color_from_desc(&Descriptor::new("HSBC").with("Strt", Value::Double(50.0))).is_none()); - } - - #[test] - fn color_descriptor_keeps_photocraft_alpha() { - use photocraft_color::Color; - use photocraft_doc::Fill; - let c = Color::rgba(0.2, 0.4, 0.6, 0.25); - let (k, d) = super::fill_to_desc(&Fill::Solid(c)); - let Fill::Solid(back) = super::fill_from_desc(&k, &d).unwrap() else { panic!("solid") }; - assert!((back.alpha - 0.25).abs() < 1e-5); - assert!((back.to_rgb()[0] - 0.2).abs() < 1e-3); - let (k, d) = super::fill_to_desc(&Fill::Solid(Color::rgb(1.0, 0.0, 0.0))); - let Fill::Solid(opaque) = super::fill_from_desc(&k, &d).unwrap() else { panic!("solid") }; - assert!((opaque.alpha - 1.0).abs() < 1e-6); - assert!(super::color_to_desc(&c).get("pcAl").is_none(), "generic colour descriptors have no pcAl"); - } - - #[test] - fn non_finite_photocraft_alpha_is_ignored() { - use photocraft_color::Color; - for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { - let d = super::color_to_desc(&Color::rgb(0.2, 0.4, 0.6)).with("pcAl", Value::Double(bad)); - let c = super::color_from_desc(&d).unwrap(); - assert_eq!(c.alpha, 1.0, "pcAl {bad}"); - } - let d = super::color_to_desc(&Color::rgb(0.2, 0.4, 0.6)).with("pcAl", Value::Double(0.5)); - assert!((super::color_from_desc(&d).unwrap().alpha - 0.5).abs() < 1e-6); - } - - #[test] - fn gradient_stop_alpha_round_trips_once() { - use photocraft_color::Color; - use photocraft_doc::Fill; - let fill = Fill::Gradient { - stops: vec![(0.0, Color::rgba(1.0, 0.0, 0.0, 0.5)), (1.0, Color::WHITE)], - angle: 90.0, - scale: 1.0, - style: photocraft_doc::GradientStyle::Linear, - reverse: false, - opacity_stops: vec![], - midpoints: vec![], - offset: (0.0, 0.0), - dither: false, - align: true, - }; - let (k, d) = super::fill_to_desc(&fill); - let Fill::Gradient { stops, opacity_stops, .. } = super::fill_from_desc(&k, &d).unwrap() else { panic!("grad") }; - assert!((stops[0].1.alpha - 1.0).abs() < 1e-4, "colour alpha lives in Trns, not the stop colour"); - assert!(opacity_stops.iter().any(|(_, a)| (*a - 0.5).abs() < 1e-3), "{opacity_stops:?}"); - } - - #[test] - fn blending_ranges_map_to_blend_if() { - use photocraft_doc::{BlendIf, BlendRange}; - use photocraft_psd::layer::BlendingRanges; - // Full ranges (what every layer without Blend If carries) → the default setting. - assert_eq!(super::blend_if_from_ranges(&BlendingRanges::full(3)), BlendIf::default()); - assert_eq!(super::blend_if_from_ranges(&BlendingRanges::default()), BlendIf::default()); - // Gray: This Layer black split 10/40; Blue (entry 3): Underlying white at 200. - let mut data = BlendingRanges::full(3).data; - data[..4].copy_from_slice(&[10, 40, 255, 255]); - data[3 * 8 + 4..3 * 8 + 8].copy_from_slice(&[0, 0, 200, 200]); - let b = super::blend_if_from_ranges(&BlendingRanges { data: data.clone() }); - assert_eq!(b.get(0), [BlendRange { black: [10, 40], white: [255, 255] }, BlendRange::FULL]); - assert_eq!(b.get(3), [BlendRange::FULL, BlendRange { black: [0, 0], white: [200, 200] }]); - assert_eq!(b.ranges.len(), 4); - assert_eq!(super::ranges_from_blend_if(&b, 3).data, data); - // The default writes full ranges for gray + each channel. - assert_eq!(super::ranges_from_blend_if(&BlendIf::default(), 4), BlendingRanges::full(4)); - // A trimmed setting is padded to the document's channel count. - let mut short = BlendIf::default(); - short.set(0, [BlendRange { black: [5, 5], white: [255, 255] }, BlendRange::FULL]); - let r = super::ranges_from_blend_if(&short, 3); - assert_eq!(r.data.len(), 4 * 8); - assert_eq!(&r.data[..8], &[5, 5, 255, 255, 0, 0, 255, 255]); - assert_eq!(&r.data[8..], &BlendingRanges::full(2).data[..]); - } - - #[test] - fn advanced_blending_blocks_round_trip() { - use photocraft_doc::{AdvancedBlending, Knockout}; - let a = AdvancedBlending { - knockout: Knockout::Deep, - blend_interior: true, - blend_clipped: false, - transparency_shapes: false, - layer_mask_hides_effects: true, - vector_mask_hides_effects: true, - }; - let mut raw = Vec::new(); - super::put_advanced(&a, &mut raw); - assert_eq!(raw.len(), 6); - assert!(raw.contains(&(*b"knko", vec![2, 0, 0, 0]))); - assert!(raw.contains(&(*b"clbl", vec![0, 0, 0, 0]))); - let get = |k: &[u8; 4]| raw.iter().find(|(bk, _)| bk == k).map(|(_, d)| d.as_slice()); - assert_eq!(super::advanced_from_blocks(get), a); - // Defaults: nothing added to a plain layer; existing blocks rewritten in place, in order. - let mut plain = Vec::new(); - super::put_advanced(&AdvancedBlending::default(), &mut plain); - assert!(plain.is_empty()); - let mut kept = vec![(*b"luni", vec![0; 4]), (*b"knko", vec![1, 0, 0, 0]), (*b"clbl", vec![1])]; - super::put_advanced(&AdvancedBlending::default(), &mut kept); - assert_eq!(kept, vec![(*b"luni", vec![0; 4]), (*b"knko", vec![0, 0, 0, 0]), (*b"clbl", vec![1, 0, 0, 0])]); - // Missing and empty blocks read as Photoshop's defaults. - assert!(super::advanced_from_blocks(|_| None).is_default()); - assert!(super::advanced_from_blocks(|_| Some(&[][..])).is_default()); - assert_eq!(super::advanced_from_blocks(|k| (k == b"knko").then_some(&[1u8][..])).knockout, Knockout::Shallow); - } - - #[test] - fn brst_round_trip() { - assert_eq!(super::parse_brst(&[0, 0, 0, 2]), 0b100); - assert_eq!(super::parse_brst(&[0, 0, 0, 0, 0, 0, 0, 1]), 0b11); - assert_eq!(super::brst_data(0b101).unwrap(), vec![0, 0, 0, 0, 0, 0, 0, 2]); - assert_eq!(super::brst_data(0), None); - } - - #[test] - fn placed_layer_warp_is_read() { - use photocraft_geom::warp::WarpStyle; - use photocraft_psd::descriptor::ObjectArray; - let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; - let bounds = Descriptor::new("Rctn") - .with("Top ", Value::UnitFloat { unit: *b"#Pxl", value: 0.0 }) - .with("Left", Value::UnitFloat { unit: *b"#Pxl", value: 0.0 }) - .with("Btom", Value::UnitFloat { unit: *b"#Pxl", value: 30.0 }) - .with("Rght", Value::UnitFloat { unit: *b"#Pxl", value: 60.0 }); - let sold = |warp: Descriptor| { - let mut v = b"soLD".to_vec(); - v.extend_from_slice(&4u32.to_be_bytes()); - v.extend(VersionedDescriptor::new(Descriptor::new("null").with("warp", Value::Descriptor(warp))).to_bytes()); - v - }; - let arc = Descriptor::new("warp") - .with("warpStyle", e("warpStyle", "warpArc")) - .with("warpValue", Value::Double(40.0)) - .with("warpPerspective", Value::Double(0.0)) - .with("warpPerspectiveOther", Value::Double(0.0)) - .with("warpRotate", e("Ornt", "Hrzn")) - .with("bounds", Value::Descriptor(bounds.clone())); - let w = parse_placed_warp(b"SoLd", &sold(arc)).unwrap(); - assert_eq!((w.style, w.bend, w.bounds), (WarpStyle::Arc, 40.0, [0.0, 0.0, 60.0, 30.0])); - let (mut xs, mut ys) = (Vec::new(), Vec::new()); - for j in 0..4 { - for i in 0..4 { - xs.push(f64::from(i) * 20.0 + if i == 3 && j == 3 { 7.0 } else { 0.0 }); - ys.push(f64::from(j) * 10.0); - } - } - let mesh = Descriptor::new("null") - .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: xs }) - .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: ys }); - let custom = Descriptor::new("warp").with("warpStyle", e("warpStyle", "warpCustom")).with("bounds", Value::Descriptor(bounds)).with( - "customEnvelopeWarp", - Value::Descriptor(Descriptor::new("customEnvelopeWarp").with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body: mesh }))), - ); - let w = parse_placed_warp(b"SoLd", &sold(custom)).unwrap(); - assert_eq!(w.style, WarpStyle::Custom); - assert_eq!(w.mesh.as_ref().unwrap().points[15], [67.0, 30.0]); - assert!(parse_placed_warp(b"PlLd", &[0; 20]).is_none()); - } - - #[test] - fn locks_and_labels() { - // Reference values round-trip byte for byte; Background layers carry 0x0D - // (transparency + position + the bit-3 lock reference files write). - for bits in [0u32, 1, 2, 4, 8, 0x0D, 0x8000_0000, 0x8000_000F] { - assert_eq!(lspf_from_locks(&locks_from_lspf(bits)), bits); - } - // Older PhotoCraft files wrote the artboard lock at 0x10; it reads back as artboard - // and is rewritten at the reference value 0x08. - assert!(locks_from_lspf(0x10).artboard); - assert_eq!(lspf_from_locks(&locks_from_lspf(0x10)), 0x08); - for i in 0..8 { - assert_eq!(label_index(label_from_index(i)), i); - } - } - - #[test] - fn fills_roundtrip() { - for f in [ - Fill::Solid(Color::rgb(1.0, 0.5, 0.0)), - Fill::Solid(Color { mode: ColorMode::Cmyk, c: [0.1, 0.2, 0.3, 0.4], alpha: 1.0 }), - Fill::Solid(Color::gray(0.25)), - Fill::gradient(vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], 45.0, 1.0, GradientStyle::Reflected, true), - // A live gradient (Gradient tool): canvas-aligned, offset, midpoints, opacity, dither. - Fill::Gradient { - stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (0.5, Color::rgb(0.0, 1.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], - angle: -33.5, - scale: 2.25, - style: GradientStyle::Radial, - reverse: false, - opacity_stops: vec![(0.0, 1.0), (0.25, 0.5), (1.0, 0.0)], - midpoints: vec![0.25, 0.75], - offset: (0.125, -0.375), - dither: true, - align: false, - }, - Fill::Pattern { name: "Bubbles".into(), scale: 0.5, id: "abc".into(), angle: 30.0, link: false, phase: (3.0, -2.0) }, - ] { - let (k, d) = write_fill(&f); - let back = parse_fill(&k, &d).unwrap(); - match (&f, &back) { - (Fill::Solid(a), Fill::Solid(b)) => { - assert_eq!(a.mode, b.mode); - for i in 0..4 { - assert!((a.c[i] - b.c[i]).abs() < 1e-5); - } - } - _ => assert_eq!(back, f), - } - } - } -} +mod tests; #[cfg(test)] mod more_tests { diff --git a/crates/io/src/blocks/tests.rs b/crates/io/src/blocks/tests.rs new file mode 100644 index 0000000000..59193a9344 --- /dev/null +++ b/crates/io/src/blocks/tests.rs @@ -0,0 +1,335 @@ +use super::*; + +fn noise_gradient_fill(min: [i32; 4], max: [i32; 4], add_transparency: bool) -> Descriptor { + let values = |v: [i32; 4]| Value::List(v.into_iter().map(Value::Integer).collect()); + let gradient = Descriptor::new("Grdn") + .with("GrdF", Value::Enumerated { type_id: Id::new("GrdF"), value: Id::new("ClNs") }) + .with("ClrS", Value::Enumerated { type_id: Id::new("ClrS"), value: Id::new("RGBC") }) + .with("ShTr", Value::Boolean(add_transparency)) + .with("VctC", Value::Boolean(true)) + .with("RndS", Value::Integer(9052369)) + .with("Smth", Value::Integer(2048)) + .with("Mnm ", values(min)) + .with("Mxm ", values(max)); + Descriptor::new("null").with("Grad", Value::Descriptor(gradient)) +} + +#[test] +fn constant_rgb_noise_fill_uses_its_exact_colour() { + use photocraft_doc::Fill; + let fill = fill_from_desc(b"GdFl", &noise_gradient_fill([50, 25, 0, 0], [50, 25, 0, 100], false)); + let Some(Fill::Gradient { stops, .. }) = fill else { panic!("constant noise gradient") }; + assert_eq!(stops, vec![(0.0, Color::rgb(0.5, 0.25, 0.0)), (1.0, Color::rgb(0.5, 0.25, 0.0))]); +} + +#[test] +fn variable_or_transparent_noise_stays_a_fill_with_the_placeholder_ramp() { + use photocraft_doc::Fill; + // Photoshop's default Noise gradient (min 0, max 100) and a transparent variant: no + // exact colour is provable, but the fill must parse — the layer keeps its type, its + // stored pixels (`fill_cache`) and its raw `GdFl` block. Only the uncached preview + // shows the placeholder ramp. + for descriptor in [noise_gradient_fill([0, 0, 0, 0], [100, 100, 100, 100], false), noise_gradient_fill([50, 25, 0, 0], [50, 25, 0, 100], true)] { + let Some(Fill::Gradient { stops, .. }) = fill_from_desc(b"GdFl", &descriptor) else { panic!("variable noise gradient must stay a fill layer") }; + assert_eq!(stops, vec![(0.0, Color::BLACK), (1.0, Color::WHITE)]); + } +} + +/// psd-tools layers-minimal/gradient-fill.psd ("Color to Transparent", no stored pixels): a +/// gradient fill's opacity stops reach the model (as its opacity stops; written from stop +/// alpha) and survive a write; the ramp's alpha follows them. +#[test] +fn gradient_fill_opacity_stops_become_alpha() { + use photocraft_color::Color; + use photocraft_doc::{Fill, GradientStyle}; + let red = Color::rgba(1.0, 0.0, 0.0, 1.0); + let f = Fill::gradient(vec![(0.0, red), (1.0, Color { alpha: 0.0, ..red })], 90.0, 1.0, GradientStyle::Linear, false); + let (k, data) = super::write_fill(&f); + let back = super::parse_fill(&k, &data).unwrap(); + let Fill::Gradient { stops, opacity_stops, .. } = &back else { panic!("gradient") }; + assert_eq!(opacity_stops, &vec![(0.0, 1.0), (1.0, 0.0)]); + assert!(stops.iter().all(|s| s.1.c[0] == 1.0 && s.1.c[1] == 0.0)); + let ramp = photocraft_compose::gradient_fill::Ramp::new(&back).unwrap(); + assert_eq!(ramp.sample(0.0)[3], 1.0); + assert!(ramp.sample(1.0)[3] < 0.01); + // Opaque gradients come back without opacity stops. + let (k, data) = super::write_fill(&Fill::gradient(vec![(0.0, red), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false)); + let Some(Fill::Gradient { opacity_stops, .. }) = super::parse_fill(&k, &data) else { panic!("gradient") }; + assert!(opacity_stops.is_empty()); +} + +/// Photoshop 27.11 stores a gradient's method as the enum `gradientsInterpolationMethod` +/// (seen in gradient fill layers saved by scripted Photoshop): a black→white Linear gradient +/// is at 188 of 255 halfway (measured), where Classic gives 128. The key used to be read as +/// `gs99`, which Photoshop doesn't write, so every gradient opened as Classic. +#[test] +fn gradient_fill_reads_the_interpolation_method() { + use photocraft_color::Color; + use photocraft_doc::{Fill, GradientStyle}; + use photocraft_psd::descriptor::{Id, Value}; + let f = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false); + let (k, data) = super::write_fill(&f); + let d = super::parse_prefix_versioned(&data).unwrap(); + let mid = |code: &str| { + let d = d.clone().with("gradientsInterpolationMethod", Value::Enumerated { type_id: Id::new("gradientInterpolationMethodType"), value: Id::new(code) }); + let back = super::fill_from_desc(&k, &d).unwrap(); + let ramp = photocraft_compose::gradient_fill::Ramp::new(&back).unwrap(); + (ramp.sample(0.5)[0] * 255.0).round() + }; + assert_eq!(mid("Gcls"), 128.0); + assert!((mid("Lnr ") - 188.0).abs() <= 1.0, "Linear: {}", mid("Lnr ")); + assert!((mid("Perc") - 99.0).abs() <= 2.0, "Perceptual: {}", mid("Perc")); + assert!((mid("Smoo") - 99.0).abs() <= 2.0, "Smooth: {}", mid("Smoo")); +} + +#[test] +fn lab_descriptor_colours_round_trip() { + use photocraft_color::ColorMode; + use photocraft_psd::descriptor::{Descriptor, Value}; + let d = Descriptor::new("LbCl").with("Lmnc", Value::Double(19.07)).with("A ", Value::Double(52.29)).with("B ", Value::Double(-85.08)); + let c = super::color_from_desc(&d).unwrap(); + assert_eq!(c.mode, ColorMode::Lab); + assert!((c.c[0] - 0.1907).abs() < 1e-5 && (c.c[1] * 255.0 - 128.0 - 52.29).abs() < 1e-3 && (c.c[2] * 255.0 - 128.0 + 85.08).abs() < 1e-3); + let back = super::color_from_desc(&super::color_to_desc(&c)).unwrap(); + assert_eq!(back.mode, ColorMode::Lab); + for i in 0..3 { + assert!((back.c[i] - c.c[i]).abs() < 1e-6); + } + // Missing components are rejected, not defaulted. + assert!(super::color_from_desc(&Descriptor::new("LbCl").with("Lmnc", Value::Double(50.0))).is_none()); +} + +/// Colours stored as HSB (`HSBC`: `H ` an angle in degrees, `Strt`/`Brgh` 0..100), as in +/// psd-tools `stroke-color-descriptors-hsb-with-rgb-mode.psd`, used to be dropped (#6774). +#[test] +fn hsb_descriptor_colours_parse() { + use photocraft_doc::Fill; + use photocraft_psd::descriptor::{Descriptor, Value}; + let hsb = |h: f64, s: f64, b: f64| { + Descriptor::new("HSBC").with("H ", Value::UnitFloat { unit: *b"#Ang", value: h }).with("Strt", Value::Double(s)).with("Brgh", Value::Double(b)) + }; + let close = |c: [f32; 3], e: [f32; 3]| c.iter().zip(e).all(|(a, b)| (a - b).abs() < 1e-5); + let green = super::color_from_desc(&hsb(120.0, 100.0, 100.0)).unwrap().to_rgb(); + assert!(close(green, [0.0, 1.0, 0.0]), "{green:?}"); + let white = super::color_from_desc(&hsb(0.0, 0.0, 100.0)).unwrap().to_rgb(); + assert!(close(white, [1.0, 1.0, 1.0]), "{white:?}"); + let half = super::color_from_desc(&hsb(240.0, 50.0, 50.0)).unwrap().to_rgb(); + assert!(close(half, [0.25, 0.25, 0.5]), "{half:?}"); + // A solid fill (`SoCo`) with an HSB colour is read, not lost. + let soco = Descriptor::new("null").with("Clr ", Value::Descriptor(hsb(0.0, 100.0, 100.0))); + let Some(Fill::Solid(c)) = super::fill_from_desc(b"SoCo", &soco) else { panic!("solid fill") }; + assert!(close(c.to_rgb(), [1.0, 0.0, 0.0]), "{:?}", c.to_rgb()); + // Missing components are rejected, not defaulted. + assert!(super::color_from_desc(&Descriptor::new("HSBC").with("Strt", Value::Double(50.0))).is_none()); +} + +#[test] +fn color_descriptor_keeps_photocraft_alpha() { + use photocraft_color::Color; + use photocraft_doc::Fill; + let c = Color::rgba(0.2, 0.4, 0.6, 0.25); + let (k, d) = super::fill_to_desc(&Fill::Solid(c)); + let Fill::Solid(back) = super::fill_from_desc(&k, &d).unwrap() else { panic!("solid") }; + assert!((back.alpha - 0.25).abs() < 1e-5); + assert!((back.to_rgb()[0] - 0.2).abs() < 1e-3); + let (k, d) = super::fill_to_desc(&Fill::Solid(Color::rgb(1.0, 0.0, 0.0))); + let Fill::Solid(opaque) = super::fill_from_desc(&k, &d).unwrap() else { panic!("solid") }; + assert!((opaque.alpha - 1.0).abs() < 1e-6); + assert!(super::color_to_desc(&c).get("pcAl").is_none(), "generic colour descriptors have no pcAl"); +} + +#[test] +fn non_finite_photocraft_alpha_is_ignored() { + use photocraft_color::Color; + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let d = super::color_to_desc(&Color::rgb(0.2, 0.4, 0.6)).with("pcAl", Value::Double(bad)); + let c = super::color_from_desc(&d).unwrap(); + assert_eq!(c.alpha, 1.0, "pcAl {bad}"); + } + let d = super::color_to_desc(&Color::rgb(0.2, 0.4, 0.6)).with("pcAl", Value::Double(0.5)); + assert!((super::color_from_desc(&d).unwrap().alpha - 0.5).abs() < 1e-6); +} + +#[test] +fn gradient_stop_alpha_round_trips_once() { + use photocraft_color::Color; + use photocraft_doc::Fill; + let fill = Fill::Gradient { + stops: vec![(0.0, Color::rgba(1.0, 0.0, 0.0, 0.5)), (1.0, Color::WHITE)], + angle: 90.0, + scale: 1.0, + style: photocraft_doc::GradientStyle::Linear, + reverse: false, + opacity_stops: vec![], + midpoints: vec![], + offset: (0.0, 0.0), + dither: false, + align: true, + }; + let (k, d) = super::fill_to_desc(&fill); + let Fill::Gradient { stops, opacity_stops, .. } = super::fill_from_desc(&k, &d).unwrap() else { panic!("grad") }; + assert!((stops[0].1.alpha - 1.0).abs() < 1e-4, "colour alpha lives in Trns, not the stop colour"); + assert!(opacity_stops.iter().any(|(_, a)| (*a - 0.5).abs() < 1e-3), "{opacity_stops:?}"); +} + +#[test] +fn blending_ranges_map_to_blend_if() { + use photocraft_doc::{BlendIf, BlendRange}; + use photocraft_psd::layer::BlendingRanges; + // Full ranges (what every layer without Blend If carries) → the default setting. + assert_eq!(super::blend_if_from_ranges(&BlendingRanges::full(3)), BlendIf::default()); + assert_eq!(super::blend_if_from_ranges(&BlendingRanges::default()), BlendIf::default()); + // Gray: This Layer black split 10/40; Blue (entry 3): Underlying white at 200. + let mut data = BlendingRanges::full(3).data; + data[..4].copy_from_slice(&[10, 40, 255, 255]); + data[3 * 8 + 4..3 * 8 + 8].copy_from_slice(&[0, 0, 200, 200]); + let b = super::blend_if_from_ranges(&BlendingRanges { data: data.clone() }); + assert_eq!(b.get(0), [BlendRange { black: [10, 40], white: [255, 255] }, BlendRange::FULL]); + assert_eq!(b.get(3), [BlendRange::FULL, BlendRange { black: [0, 0], white: [200, 200] }]); + assert_eq!(b.ranges.len(), 4); + assert_eq!(super::ranges_from_blend_if(&b, 3).data, data); + // The default writes full ranges for gray + each channel. + assert_eq!(super::ranges_from_blend_if(&BlendIf::default(), 4), BlendingRanges::full(4)); + // A trimmed setting is padded to the document's channel count. + let mut short = BlendIf::default(); + short.set(0, [BlendRange { black: [5, 5], white: [255, 255] }, BlendRange::FULL]); + let r = super::ranges_from_blend_if(&short, 3); + assert_eq!(r.data.len(), 4 * 8); + assert_eq!(&r.data[..8], &[5, 5, 255, 255, 0, 0, 255, 255]); + assert_eq!(&r.data[8..], &BlendingRanges::full(2).data[..]); +} + +#[test] +fn advanced_blending_blocks_round_trip() { + use photocraft_doc::{AdvancedBlending, Knockout}; + let a = AdvancedBlending { + knockout: Knockout::Deep, + blend_interior: true, + blend_clipped: false, + transparency_shapes: false, + layer_mask_hides_effects: true, + vector_mask_hides_effects: true, + }; + let mut raw = Vec::new(); + super::put_advanced(&a, &mut raw); + assert_eq!(raw.len(), 6); + assert!(raw.contains(&(*b"knko", vec![2, 0, 0, 0]))); + assert!(raw.contains(&(*b"clbl", vec![0, 0, 0, 0]))); + let get = |k: &[u8; 4]| raw.iter().find(|(bk, _)| bk == k).map(|(_, d)| d.as_slice()); + assert_eq!(super::advanced_from_blocks(get), a); + // Defaults: nothing added to a plain layer; existing blocks rewritten in place, in order. + let mut plain = Vec::new(); + super::put_advanced(&AdvancedBlending::default(), &mut plain); + assert!(plain.is_empty()); + let mut kept = vec![(*b"luni", vec![0; 4]), (*b"knko", vec![1, 0, 0, 0]), (*b"clbl", vec![1])]; + super::put_advanced(&AdvancedBlending::default(), &mut kept); + assert_eq!(kept, vec![(*b"luni", vec![0; 4]), (*b"knko", vec![0, 0, 0, 0]), (*b"clbl", vec![1, 0, 0, 0])]); + // Missing and empty blocks read as Photoshop's defaults. + assert!(super::advanced_from_blocks(|_| None).is_default()); + assert!(super::advanced_from_blocks(|_| Some(&[][..])).is_default()); + assert_eq!(super::advanced_from_blocks(|k| (k == b"knko").then_some(&[1u8][..])).knockout, Knockout::Shallow); +} + +#[test] +fn brst_round_trip() { + assert_eq!(super::parse_brst(&[0, 0, 0, 2]), 0b100); + assert_eq!(super::parse_brst(&[0, 0, 0, 0, 0, 0, 0, 1]), 0b11); + assert_eq!(super::brst_data(0b101).unwrap(), vec![0, 0, 0, 0, 0, 0, 0, 2]); + assert_eq!(super::brst_data(0), None); +} + +#[test] +fn placed_layer_warp_is_read() { + use photocraft_geom::warp::WarpStyle; + use photocraft_psd::descriptor::ObjectArray; + let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; + let bounds = Descriptor::new("Rctn") + .with("Top ", Value::UnitFloat { unit: *b"#Pxl", value: 0.0 }) + .with("Left", Value::UnitFloat { unit: *b"#Pxl", value: 0.0 }) + .with("Btom", Value::UnitFloat { unit: *b"#Pxl", value: 30.0 }) + .with("Rght", Value::UnitFloat { unit: *b"#Pxl", value: 60.0 }); + let sold = |warp: Descriptor| { + let mut v = b"soLD".to_vec(); + v.extend_from_slice(&4u32.to_be_bytes()); + v.extend(VersionedDescriptor::new(Descriptor::new("null").with("warp", Value::Descriptor(warp))).to_bytes()); + v + }; + let arc = Descriptor::new("warp") + .with("warpStyle", e("warpStyle", "warpArc")) + .with("warpValue", Value::Double(40.0)) + .with("warpPerspective", Value::Double(0.0)) + .with("warpPerspectiveOther", Value::Double(0.0)) + .with("warpRotate", e("Ornt", "Hrzn")) + .with("bounds", Value::Descriptor(bounds.clone())); + let w = parse_placed_warp(b"SoLd", &sold(arc)).unwrap(); + assert_eq!((w.style, w.bend, w.bounds), (WarpStyle::Arc, 40.0, [0.0, 0.0, 60.0, 30.0])); + let (mut xs, mut ys) = (Vec::new(), Vec::new()); + for j in 0..4 { + for i in 0..4 { + xs.push(f64::from(i) * 20.0 + if i == 3 && j == 3 { 7.0 } else { 0.0 }); + ys.push(f64::from(j) * 10.0); + } + } + let mesh = + Descriptor::new("null").with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: xs }).with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: ys }); + let custom = Descriptor::new("warp").with("warpStyle", e("warpStyle", "warpCustom")).with("bounds", Value::Descriptor(bounds)).with( + "customEnvelopeWarp", + Value::Descriptor(Descriptor::new("customEnvelopeWarp").with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body: mesh }))), + ); + let w = parse_placed_warp(b"SoLd", &sold(custom)).unwrap(); + assert_eq!(w.style, WarpStyle::Custom); + assert_eq!(w.mesh.as_ref().unwrap().points[15], [67.0, 30.0]); + assert!(parse_placed_warp(b"PlLd", &[0; 20]).is_none()); +} + +#[test] +fn locks_and_labels() { + // Reference values round-trip byte for byte; Background layers carry 0x0D + // (transparency + position + the bit-3 lock reference files write). + for bits in [0u32, 1, 2, 4, 8, 0x0D, 0x8000_0000, 0x8000_000F] { + assert_eq!(lspf_from_locks(&locks_from_lspf(bits)), bits); + } + // Older PhotoCraft files wrote the artboard lock at 0x10; it reads back as artboard + // and is rewritten at the reference value 0x08. + assert!(locks_from_lspf(0x10).artboard); + assert_eq!(lspf_from_locks(&locks_from_lspf(0x10)), 0x08); + for i in 0..8 { + assert_eq!(label_index(label_from_index(i)), i); + } +} + +#[test] +fn fills_roundtrip() { + for f in [ + Fill::Solid(Color::rgb(1.0, 0.5, 0.0)), + Fill::Solid(Color { mode: ColorMode::Cmyk, c: [0.1, 0.2, 0.3, 0.4], alpha: 1.0 }), + Fill::Solid(Color::gray(0.25)), + Fill::gradient(vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], 45.0, 1.0, GradientStyle::Reflected, true), + // A live gradient (Gradient tool): canvas-aligned, offset, midpoints, opacity, dither. + Fill::Gradient { + stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (0.5, Color::rgb(0.0, 1.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], + angle: -33.5, + scale: 2.25, + style: GradientStyle::Radial, + reverse: false, + opacity_stops: vec![(0.0, 1.0), (0.25, 0.5), (1.0, 0.0)], + midpoints: vec![0.25, 0.75], + offset: (0.125, -0.375), + dither: true, + align: false, + }, + Fill::Pattern { name: "Bubbles".into(), scale: 0.5, id: "abc".into(), angle: 30.0, link: false, phase: (3.0, -2.0) }, + ] { + let (k, d) = write_fill(&f); + let back = parse_fill(&k, &d).unwrap(); + match (&f, &back) { + (Fill::Solid(a), Fill::Solid(b)) => { + assert_eq!(a.mode, b.mode); + for i in 0..4 { + assert!((a.c[i] - b.c[i]).abs() < 1e-5); + } + } + _ => assert_eq!(back, f), + } + } +} From a56cb885b8bfebe3986099bdb320281e1ce56874 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:47 +0000 Subject: [PATCH 117/259] refactor(io): move blocks.rs more_tests to blocks/more_tests.rs --- crates/io/src/blocks.rs | 512 +---------------------------- crates/io/src/blocks/more_tests.rs | 496 ++++++++++++++++++++++++++++ 2 files changed, 497 insertions(+), 511 deletions(-) create mode 100644 crates/io/src/blocks/more_tests.rs diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rs index 5e9a76b7ca..c280747611 100644 --- a/crates/io/src/blocks.rs +++ b/crates/io/src/blocks.rs @@ -919,514 +919,4 @@ pub fn effects_enabled(lfx2: &[u8]) -> bool { mod tests; #[cfg(test)] -mod more_tests { - use super::*; - - #[test] - fn float_rgb_colors_parse() { - let d = Descriptor::new("RGBC").with("redFloat", Value::Double(1.0)).with("greenFloat", Value::Double(0.5)).with("blueFloat", Value::Double(0.25)); - let c = color_from_desc(&d).unwrap(); - assert_eq!(c.to_rgb(), [1.0, 0.5, 0.25]); - } - - #[test] - fn smart_transform_from_sold() { - let pts = [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0].map(Value::Double).to_vec(); - let d = Descriptor::new("null") - .with("Idnt", Value::Text(UnicodeString::new_nul("uuid-1"))) - .with("Trnf", Value::List(pts)) - .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(50.0)).with("Hght", Value::Double(25.0)))); - let mut data = b"soLD".to_vec(); - data.extend_from_slice(&4u32.to_be_bytes()); - data.extend(VersionedDescriptor::new(d).to_bytes()); - data.extend_from_slice(&[0, 0]); - let (id, a) = parse_smart(b"SoLd", &data); - assert_eq!(id, "uuid-1"); - assert_eq!(a.m, [2.0, 0.0, 0.0, 2.0, 10.0, 20.0]); - assert_eq!(parse_smart(b"PlLd", &data).0, ""); - assert_eq!(parse_plld(&data), None, "soLD data is not a plcL record"); - } - - /// A `PlLd` record (as Photoshop CS2 writes it, with no `SoLd`, #2465) gives its source id and - /// placed corners; with the source size those are the same transform `SoLd` gives. - #[test] - fn plld_id_and_corners() { - use crate::smart_map::{PlacedSpec, plld_bytes}; - let t = Affine { m: [1.5, 0.25, -0.5, 2.0, 10.0, 20.0] }; - let spec = PlacedSpec { idnt: "uuid-cs2", placed: "", transform: t, perspective: None, size: (40.0, 30.0), dpi: 72.0, warp: None, filter_fx: None }; - let data = plld_bytes(&spec, &mut Vec::new()); - let (id, p) = parse_plld(&data).expect("a plcL record"); - assert_eq!(id, "uuid-cs2"); - assert_eq!(p, [10.0, 20.0, 70.0, 30.0, 55.0, 90.0, -5.0, 80.0]); - let back = corners_affine(&p, [0.0, 0.0, 40.0, 30.0]).unwrap(); - for (a, b) in back.m.iter().zip(t.m) { - assert!((a - b).abs() < 1e-12, "{back:?} vs {t:?}"); - } - assert_eq!(corners_perspective([[p[0], p[1]], [p[2], p[3]], [p[4], p[5]], [p[6], p[7]]], (40.0, 30.0)), None, "affine corners"); - assert_eq!(corners_affine(&p, [0.0, 0.0, 0.0, 30.0]), None); - assert_eq!(corners_affine(&p, [0.0, 0.0, f64::NAN, 30.0]), None); - assert_eq!(corners_affine(&p, [5.0, 0.0, 5.0, 30.0]), None, "an empty frame"); - let mut nan = p; - nan[3] = f64::INFINITY; - assert_eq!(corners_affine(&nan, [0.0, 0.0, 40.0, 30.0]), None); - // The placed-layer record is the one block that can be the principal one: PlLd-only - // layers have no smart transform from `parse_smart`. - assert_eq!(parse_smart(b"PlLd", &data), (String::new(), Affine::IDENTITY)); - } - - /// A `PlLd` record's corners frame the same box as `SoLd`'s `Trnf` (#3677): with a custom - /// warp whose control points spill past the source, the control-point box, not the source - /// rect. The CS2 record then places the layer exactly as the equivalent `SoLd` does, with or - /// without the source size (the box needs none). - #[test] - fn plld_corners_frame_a_spilled_custom_warp_like_sold() { - use crate::smart_map::{PlacedSpec, parse_sold, plld_bytes, sold_bytes}; - use photocraft_geom::warp::{BezierMesh, Warp}; - let bounds = [0.0, 0.0, 50.0, 25.0]; - let mut mesh = BezierMesh::identity(bounds, 1, 1); - mesh.points[0] = [-10.0, -5.0]; - mesh.points[15] = [60.0, 25.0]; - let warp = Warp::custom(mesh, bounds); - let t = Affine { m: [2.0, 0.5, -0.25, 2.0, 120.0, 210.0] }; - let spec = PlacedSpec { idnt: "cs2", placed: "p", transform: t, perspective: None, size: (50.0, 25.0), dpi: 72.0, warp: Some(&warp), filter_fx: None }; - let plld = plld_bytes(&spec, &mut Vec::new()); - let sold = sold_bytes(None, &spec, &mut Vec::new()); - let (_, p) = parse_plld(&plld).expect("a plcL record"); - assert_eq!(parse_plld_warp(&plld), PlldWarp::Warp(warp.clone())); - let from_sold = parse_smart(b"SoLd", &sold).1; - assert_eq!(parse_sold(&sold).map(|s| s.transform), Some(from_sold)); - let close = |a: Affine, b: Affine| a.m.iter().zip(b.m).all(|(x, y)| (x - y).abs() < 1e-9); - assert!(close(from_sold, t), "{from_sold:?} vs {t:?}"); - for size in [Some((50.0, 25.0)), None] { - let (got, perspective) = plld_transform(&p, size, Some(&warp)); - assert!(close(got, from_sold), "size {size:?}: {got:?} vs SoLd {from_sold:?}"); - assert_eq!(perspective, None); - } - // Framing the source rect instead would stretch it (the bug #3677 fixed for SoLd). - let rect = corners_affine(&p, [0.0, 0.0, 50.0, 25.0]).unwrap(); - assert!(!close(rect, t), "the test needs a mesh that spills: {rect:?}"); - // With no warp, or a preset one, the frame is the source rect, as before. - let plain = PlacedSpec { warp: None, ..spec }; - let (_, q) = parse_plld(&plld_bytes(&plain, &mut Vec::new())).unwrap(); - assert!(close(plld_transform(&q, Some((50.0, 25.0)), None).0, t)); - } - - /// Malformed `PlLd` data (wrong magic, truncated anywhere, a Pascal length past the end, - /// non-finite corners) reads as `None`, never a panic. - #[test] - fn plld_malformed_is_none() { - use crate::smart_map::{PlacedSpec, plld_bytes}; - let spec = - PlacedSpec { idnt: "id", placed: "", transform: Affine::IDENTITY, perspective: None, size: (4.0, 4.0), dpi: 72.0, warp: None, filter_fx: None }; - let data = plld_bytes(&spec, &mut Vec::new()); - // Magic + version + Pascal "id" + 4 × u32 + 8 × f64: everything after is the warp. - let end = 4 + 4 + 1 + 2 + 16 + 64; - assert!(parse_plld(&data[..end]).is_some()); - for n in 0..end { - assert_eq!(parse_plld(&data[..n]), None, "truncated to {n} bytes"); - } - let mut bad = data.clone(); - bad[..4].copy_from_slice(b"soLD"); - assert_eq!(parse_plld(&bad), None); - let mut long = data.clone(); - long[8] = 255; // a Pascal id longer than the record - assert_eq!(parse_plld(&long[..200.min(long.len())]), None); - let mut nan = data.clone(); - nan[end - 8..end].copy_from_slice(&f64::NAN.to_be_bytes()); - assert_eq!(parse_plld(&nan), None); - assert_eq!(parse_plld(&[]), None); - } - - /// Photoshop CS2 can warp a smart object; `PlLd` keeps that warp after the corners (a u32 - /// warp version, then the versioned `warp` descriptor). It reads back as written, and - /// `warpNone`, an identity warp or a record that stops at its corners mean no warp. - #[test] - fn plld_warps_round_trip() { - use crate::smart_map::{PlacedSpec, plld_bytes}; - use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle}; - let bounds = [0.0, 0.0, 60.0, 30.0]; - let mut arc = Warp::preset(WarpStyle::Arc, 40.0, bounds); - arc.vertical = true; - arc.h_distort = 10.0; - let mut mesh = BezierMesh::identity(bounds, 1, 1); - mesh.points[15] = [67.0, 30.0]; - let custom = Warp::custom(mesh, bounds); - let flat = Warp::preset(WarpStyle::Flag, 0.0, bounds); - for (w, back) in - [(Some(&arc), PlldWarp::Warp(arc.clone())), (Some(&custom), PlldWarp::Warp(custom.clone())), (Some(&flat), PlldWarp::None), (None, PlldWarp::None)] - { - let t = Affine { m: [0.5, 0.0, 0.0, 0.5, 3.0, 4.0] }; - let spec = PlacedSpec { idnt: "w", placed: "", transform: t, perspective: None, size: (60.0, 30.0), dpi: 72.0, warp: w, filter_fx: None }; - let data = plld_bytes(&spec, &mut Vec::new()); - assert_eq!(parse_plld_warp(&data), back, "{w:?}"); - // The corners are unchanged by the warp that follows them. - assert_eq!(parse_plld(&data).map(|(_, p)| p[..2].to_vec()), Some(vec![3.0, 4.0])); - } - let spec = - PlacedSpec { idnt: "id", placed: "", transform: Affine::IDENTITY, perspective: None, size: (4.0, 4.0), dpi: 72.0, warp: None, filter_fx: None }; - let end = 4 + 4 + 1 + 2 + 16 + 64; - let data = plld_bytes(&spec, &mut Vec::new()); - assert_eq!(parse_plld_warp(&data[..end]), PlldWarp::None, "no warp stored"); - assert_eq!(parse_plld_warp(&[data[..end].to_vec(), vec![0; 3]].concat()), PlldWarp::None, "padding"); - } - - /// A `PlLd` warp that is stored but can't be read (truncated, an unknown style, a missing - /// bounds rectangle or mesh) is `Unreadable`, so the import keeps the warped pixels. - #[test] - fn plld_unreadable_warps() { - use crate::smart_map::{PlacedSpec, plld_bytes}; - use photocraft_geom::warp::{Warp, WarpStyle}; - let arc = Warp::preset(WarpStyle::Arc, 40.0, [0.0, 0.0, 4.0, 4.0]); - let spec = PlacedSpec { - idnt: "id", - placed: "", - transform: Affine::IDENTITY, - perspective: None, - size: (4.0, 4.0), - dpi: 72.0, - warp: Some(&arc), - filter_fx: None, - }; - let data = plld_bytes(&spec, &mut Vec::new()); - let end = 4 + 4 + 1 + 2 + 16 + 64; - assert!(matches!(parse_plld_warp(&data), PlldWarp::Warp(_))); - for n in end + 1..data.len() - 4 { - if data[end..n].iter().any(|b| *b != 0) { - assert_eq!(parse_plld_warp(&data[..n]), PlldWarp::Unreadable, "truncated to {n} bytes"); - } - } - let with = |d: Descriptor| [data[..end].to_vec(), vec![0; 4], VersionedDescriptor::new(d).to_bytes()].concat(); - let style = |s: &str| Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new(s) }; - assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpSomethingNew")))), PlldWarp::Unreadable); - assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpArc")))), PlldWarp::Unreadable, "no bounds"); - assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpNone")))), PlldWarp::None); - let bounds = Descriptor::new("classFloatRect") - .with("Top ", Value::Double(0.0)) - .with("Left", Value::Double(0.0)) - .with("Btom", Value::Double(4.0)) - .with("Rght", Value::Double(4.0)); - let custom = Descriptor::new("warp").with("warpStyle", style("warpCustom")).with("bounds", Value::Descriptor(bounds)); - assert_eq!(parse_plld_warp(&with(custom)), PlldWarp::Unreadable, "custom with no mesh"); - assert_eq!(parse_plld_warp(&[data[..end].to_vec(), vec![0, 0, 0, 0, 0, 0, 0, 16, 1, 2]].concat()), PlldWarp::Unreadable); - assert_eq!(parse_plld_warp(&data[..end - 1]), PlldWarp::Unreadable, "the record itself"); - assert_eq!(parse_plld_warp(&[]), PlldWarp::Unreadable); - } - - /// `SoLd` data with a 50 × 25 source, the quad `trnf` and, when given, a custom warp whose - /// 16 control points are `pts`. - fn sold_with_warp(trnf: [f64; 8], pts: Option<&[[f64; 2]]>) -> Vec { - use photocraft_psd::descriptor::ObjectArray; - let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; - let mut d = Descriptor::new("null") - .with("Idnt", Value::Text(UnicodeString::new_nul("uuid-1"))) - .with("Trnf", Value::List(trnf.map(Value::Double).to_vec())) - .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(50.0)).with("Hght", Value::Double(25.0)))); - if let Some(pts) = pts { - let bounds = Descriptor::new("Rctn") - .with("Top ", Value::Double(0.0)) - .with("Left", Value::Double(0.0)) - .with("Btom", Value::Double(25.0)) - .with("Rght", Value::Double(50.0)); - let mesh = Descriptor::new("null") - .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[0]).collect() }) - .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[1]).collect() }); - let warp = Descriptor::new("warp").with("warpStyle", e("warpStyle", "warpCustom")).with("bounds", Value::Descriptor(bounds)).with( - "customEnvelopeWarp", - Value::Descriptor(Descriptor::new("customEnvelopeWarp").with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body: mesh }))), - ); - d = d.with("warp", Value::Descriptor(warp)); - } - let mut data = b"soLD".to_vec(); - data.extend_from_slice(&4u32.to_be_bytes()); - data.extend(VersionedDescriptor::new(d).to_bytes()); - data - } - - /// `SoLd` data with a split (quilt) custom warp, as Photoshop writes it: a `quiltWarp` - /// descriptor with `deformNumCols` × `deformNumRows` control points and the patch boundaries - /// in `quiltSliceX` / `quiltSliceY`. With `plain_warp`, a `warpNone` `warp` key sits next to it. - fn sold_with_quilt(trnf: [f64; 8], cols: f64, rows: f64, sx: &[f64], sy: &[f64], pts: &[[f64; 2]], plain_warp: bool) -> Vec { - use photocraft_psd::descriptor::ObjectArray; - let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; - let bounds = || { - Descriptor::new("Rctn") - .with("Top ", Value::Double(0.0)) - .with("Left", Value::Double(0.0)) - .with("Btom", Value::Double(25.0)) - .with("Rght", Value::Double(50.0)) - }; - let slices = |k: &str, v: &[f64]| { - let body = Descriptor::new("null").with(k, Value::UnitFloats { unit: *b"#Pxl", values: v.to_vec() }); - Value::ObjectArray(ObjectArray { prefix: v.len() as u32, body }) - }; - let mesh = Descriptor::new("null") - .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[0]).collect() }) - .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[1]).collect() }); - let envelope = Descriptor::new("customEnvelopeWarp") - .with("quiltSliceX", slices("quiltSliceX", sx)) - .with("quiltSliceY", slices("quiltSliceY", sy)) - .with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body: mesh })); - let quilt = Descriptor::new("quiltWarp") - .with("warpStyle", e("warpStyle", "warpCustom")) - .with("bounds", Value::Descriptor(bounds())) - .with("deformNumRows", Value::Integer(rows as i32)) - .with("deformNumCols", Value::Double(cols)) - .with("customEnvelopeWarp", Value::Descriptor(envelope)); - let mut d = Descriptor::new("null") - .with("Idnt", Value::Text(UnicodeString::new_nul("uuid-1"))) - .with("Trnf", Value::List(trnf.map(Value::Double).to_vec())) - .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(50.0)).with("Hght", Value::Double(25.0)))); - if plain_warp { - d = d.with( - "warp", - Value::Descriptor(Descriptor::new("warp").with("warpStyle", e("warpStyle", "warpNone")).with("bounds", Value::Descriptor(bounds()))), - ); - } - d = d.with("quiltWarp", Value::Descriptor(quilt)); - let mut data = b"soLD".to_vec(); - data.extend_from_slice(&4u32.to_be_bytes()); - data.extend(VersionedDescriptor::new(d).to_bytes()); - data - } - - /// A 3 × 2 patch identity grid over the 50 × 25 source with one interior control point pulled. - fn quilt_points() -> Vec<[f64; 2]> { - let mut pts = photocraft_geom::warp::BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 3, 2).points; - if let Some(p) = pts.get_mut(10 * 3 + 4) { - p[1] += 3.0; - } - pts - } - - /// Photoshop's split warp (`quiltWarp`, mockups' usual warp) reads as a multi-patch mesh: the - /// patch boundaries become the knots, the control points stay in order, and the quilt wins over - /// the `warpNone` `warp` key written next to it. Before, any mesh but 4 × 4 was dropped and the - /// layer re-rendered flat. - #[test] - fn quilt_warp_is_read_as_a_multi_patch_mesh() { - let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; - let pts = quilt_points(); - // Photoshop pads the outer boundaries a little past the grid's edges. - let data = sold_with_quilt(quad, 10.0, 7.0, &[-0.5, 12.5, 37.5, 50.5], &[-0.5, 12.5, 25.5], &pts, true); - let warp = parse_placed_warp(b"SoLd", &data).expect("a quilt warp"); - let mesh = warp.mesh.as_ref().expect("its mesh"); - assert_eq!(mesh.points, pts); - assert_eq!(mesh.us.len(), 4); - assert_eq!(mesh.vs.len(), 3); - assert_eq!((mesh.us[0], mesh.us[3], mesh.vs[0], mesh.vs[2]), (0.0, 1.0, 0.0, 1.0)); - assert!((mesh.us[1] - 13.0 / 51.0).abs() < 1e-12 && (mesh.vs[1] - 13.0 / 26.0).abs() < 1e-12); - assert!(mesh.is_valid()); - } - - /// A quilt's control points frame the placed quad as a single patch's do (#3677): a grid - /// spilling to x = -10, y = -5 and x = 60 frames a 70 × 30 box. - #[test] - fn quilt_warp_control_box_frames_the_quad() { - let mut pts = quilt_points(); - pts[0] = [-10.0, -5.0]; - if let Some(last) = pts.last_mut() { - *last = [60.0, 25.0]; - } - let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; - let data = sold_with_quilt(quad, 10.0, 7.0, &[0.0, 12.5, 37.5, 50.0], &[0.0, 12.5, 25.0], &pts, false); - assert_eq!(parse_smart(b"SoLd", &data).1.m, [2.0, 0.0, 0.0, 2.0, 120.0, 210.0]); - } - - /// An inconsistent quilt reads as no warp rather than a wrong one, and never panics. - #[test] - fn inconsistent_quilt_warps_are_not_read() { - let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; - let pts = quilt_points(); - let (sx, sy) = ([0.0, 12.5, 37.5, 50.0], [0.0, 12.5, 25.0]); - let read = - |cols: f64, rows: f64, sx: &[f64], sy: &[f64], pts: &[[f64; 2]]| parse_placed_warp(b"SoLd", &sold_with_quilt(quad, cols, rows, sx, sy, pts, false)); - assert!(read(10.0, 7.0, &sx, &sy, &pts).is_some()); - assert!(read(9.0, 7.0, &sx, &sy, &pts).is_none(), "not three points per patch side plus one"); - assert!(read(13.0, 7.0, &sx, &sy, &pts).is_none(), "more points claimed than stored"); - assert!(read(10.0, 7.0, &[0.0, 12.5, 50.0], &sy, &pts).is_none(), "one slice per patch boundary"); - assert!(read(10.0, 7.0, &[0.0, 37.5, 12.5, 50.0], &sy, &pts).is_none(), "slices must increase"); - assert!(read(10.0, 7.0, &[0.0, f64::NAN, 37.5, 50.0], &sy, &pts).is_none()); - assert!(read(1e9, 7.0, &sx, &sy, &pts).is_none(), "an absurd grid is refused before any arithmetic"); - assert!(read(10.0, 7.0, &sx, &sy, &pts[..pts.len() - 1]).is_none()); - let mut nan = pts.clone(); - nan[3] = [f64::NAN, 0.0]; - assert!(read(10.0, 7.0, &sx, &sy, &nan).is_none()); - } - - /// Photoshop's `Trnf` is the image of the custom warp's control-point bounding box, not of the - /// source rect: a mesh spilling to x = -10, y = -5 and x = 60 frames a 70 × 30 box. - #[test] - fn smart_transform_maps_the_warp_control_box_onto_the_quad() { - let mut pts = photocraft_geom::warp::BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 1, 1).points; - pts[0] = [-10.0, -5.0]; - pts[15] = [60.0, 25.0]; - let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; - let (_, a) = parse_smart(b"SoLd", &sold_with_warp(quad, Some(&pts))); - assert_eq!(a.m, [2.0, 0.0, 0.0, 2.0, 120.0, 210.0]); - // Without a warp the source rect is the frame, as before. - assert_eq!(parse_smart(b"SoLd", &sold_with_warp(quad, None)).1.m, [2.8, 0.0, 0.0, 2.4, 100.0, 200.0]); - } - - /// A custom mesh with no area (every control point on one spot) can't frame the quad: the - /// source rect does, with no division by zero. - #[test] - fn smart_transform_with_a_degenerate_warp_box_uses_the_source_rect() { - let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; - let (_, a) = parse_smart(b"SoLd", &sold_with_warp(quad, Some(&[[7.0, 7.0]; 16]))); - assert_eq!(a.m, [2.8, 0.0, 0.0, 2.4, 100.0, 200.0]); - let mut warp = photocraft_geom::warp::Warp::preset(photocraft_geom::warp::WarpStyle::Custom, 0.0, [0.0, 0.0, 50.0, 25.0]); - warp.mesh = Some(photocraft_geom::warp::BezierMesh { us: vec![0.0, 1.0], vs: vec![0.0, 1.0], points: vec![[f64::NAN, 1.0]; 16] }); - assert_eq!(placed_frame(Some(&warp), 50.0, 25.0), [0.0, 0.0, 50.0, 25.0]); - assert_eq!(placed_frame(None, 50.0, 25.0), [0.0, 0.0, 50.0, 25.0]); - } - - /// A `SoLd` placed on `quad` (`Trnf` and `nonAffineTransform`) for a 1000 × 1000 source, - /// warped by `warp`. - fn sold_placed(quad: [f64; 8], warp: Descriptor) -> Vec { - let list = Value::List(quad.iter().map(|v| Value::Double(*v)).collect()); - let d = Descriptor::new("null") - .with("Trnf", list.clone()) - .with("nonAffineTransform", list) - .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(1000.0)).with("Hght", Value::Double(1000.0)))) - .with("warp", Value::Descriptor(warp)); - let mut data = b"soLD".to_vec(); - data.extend_from_slice(&4u32.to_be_bytes()); - data.extend(VersionedDescriptor::new(d).to_bytes()); - data - } - - /// A `warpCylinder` descriptor as #4112 describes it: horizontal, no perspective, seven - /// `warpValues` in the space of `bounds`. - fn cylinder_desc(values: Value) -> Descriptor { - let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; - let bounds = Descriptor::new("classFloatRect") - .with("Top ", Value::Double(0.0)) - .with("Left", Value::Double(0.0)) - .with("Btom", Value::Double(1000.0)) - .with("Rght", Value::Double(1000.0)); - Descriptor::new("warp") - .with("warpStyle", e("warpStyle", "warpCylinder")) - .with("warpValue", Value::Double(0.0)) - .with("warpValues", values) - .with("warpPerspective", Value::Double(0.0)) - .with("warpPerspectiveOther", Value::Double(0.0)) - .with("warpRotate", e("Ornt", "Hrzn")) - .with("bounds", Value::Descriptor(bounds)) - } - - const CYL: [f64; 7] = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5]; - - fn doubles(v: &[f64]) -> Value { - Value::List(v.iter().map(|x| Value::Double(*x)).collect()) - } - - /// A projective placement is framed by the warp `parse_placed_warp` imports: an unreadable - /// `quiltWarp` next to a cylinder under `warp` imports no warp, so the source rect is framed. - #[test] - fn perspective_frame_follows_the_warp_parse_placed_warp_reads() { - let quad = [10.0, 20.0, 410.0, 60.0, 400.0, 480.0, 30.0, 520.0]; - let list = Value::List(quad.iter().map(|v| Value::Double(*v)).collect()); - let unreadable = - Descriptor::new("quiltWarp").with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpSomethingNew") }); - let d = Descriptor::new("null") - .with("Trnf", list.clone()) - .with("nonAffineTransform", list) - .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(1000.0)).with("Hght", Value::Double(1000.0)))) - .with("quiltWarp", Value::Descriptor(unreadable)) - .with("warp", Value::Descriptor(cylinder_desc(doubles(&CYL)))); - let mut data = b"soLD".to_vec(); - data.extend_from_slice(&4u32.to_be_bytes()); - data.extend(VersionedDescriptor::new(d).to_bytes()); - assert_eq!(parse_placed_warp(b"SoLd", &data), None); - let h = photocraft_algo::transform::Homography(parse_smart_perspective(b"SoLd", &data).expect("projective")); - let (px, py) = h.apply(1000.0, 1000.0); - assert!((px - 400.0).abs() < 1e-6 && (py - 480.0).abs() < 1e-6, "{px},{py}"); - } - /// #4112: a `warpCylinder` placed layer comes in as the cylinder its seven values describe, - /// instead of no warp (which re-rendered the contents flat). - #[test] - fn placed_cylinder_warp_is_read() { - use photocraft_geom::warp::{Warp, WarpStyle}; - let quad = [0.0, 0.0, 800.0, 0.0, 800.0, 800.0, 0.0, 800.0]; - let want = Warp::cylinder(&CYL, [0.0, 0.0, 1000.0, 1000.0]).unwrap(); - let w = parse_placed_warp(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).expect("a cylinder"); - assert_eq!(w, want); - assert_eq!(w.style, WarpStyle::Cylinder); - // Values written as one unit-float list read the same. - let floats = Value::UnitFloats { unit: *b"#Pxl", values: CYL.to_vec() }; - assert_eq!(parse_placed_warp(b"SoLE", &sold_placed(quad, cylinder_desc(floats))), Some(want)); - } - - /// Cylinders nobody has measured (vertical, with perspective) and broken values stay - /// unreadable, as every cylinder was before: the layer keeps the pixels Photoshop stored. - #[test] - fn placed_cylinder_warps_that_cant_be_read() { - let quad = [0.0, 0.0, 800.0, 0.0, 800.0, 800.0, 0.0, 800.0]; - let read = |d: Descriptor| parse_placed_warp(b"SoLd", &sold_placed(quad, d)); - let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; - let with = |key: &str, v: Value| { - let mut d = cylinder_desc(doubles(&CYL)); - d.items.iter_mut().filter(|(k, _)| k.is(key)).for_each(|(_, old)| *old = v.clone()); - d - }; - assert!(read(with("warpRotate", e("Ornt", "Vrtc"))).is_none(), "vertical"); - assert!(read(with("warpPerspective", Value::Double(20.0))).is_none(), "perspective"); - assert!(read(with("warpPerspectiveOther", Value::Double(-5.0))).is_none(), "the other perspective"); - assert!(read(cylinder_desc(doubles(&CYL[..6]))).is_none(), "six values"); - assert!(read(cylinder_desc(Value::List(vec![Value::Text(UnicodeString::new_nul("x")); 7]))).is_none(), "not numbers"); - assert!(read(cylinder_desc(Value::Double(1.0))).is_none(), "one number"); - let mut flipped = CYL; - flipped.swap(0, 2); - assert!(read(cylinder_desc(doubles(&flipped))).is_none(), "silhouettes swapped"); - let mut no_values = cylinder_desc(doubles(&CYL)); - no_values.items.retain(|(k, _)| !k.is("warpValues")); - assert!(read(no_values).is_none(), "no warpValues"); - } - - /// Like a custom warp's (#3677), a cylinder's control-point box is what the placement quad - /// frames, for affine corners and for projective ones (`nonAffineTransform`). - #[test] - fn placed_cylinder_quad_frames_its_control_box() { - use photocraft_geom::warp::Warp; - let cb = Warp::cylinder(&CYL, [0.0, 0.0, 1000.0, 1000.0]).unwrap().mesh.unwrap().control_bounds(); - // Affine: the box lands on the quad. - let quad = [10.0, 20.0, 410.0, 20.0, 410.0, 520.0, 10.0, 520.0]; - let (_, a) = parse_smart(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))); - let [m0, m1, m2, m3, m4, m5] = a.m; - let map = |x: f64, y: f64| (m0 * x + m2 * y + m4, m1 * x + m3 * y + m5); - for ((x, y), (qx, qy)) in - [(cb[0], cb[1]), (cb[2], cb[1]), (cb[2], cb[3]), (cb[0], cb[3])].into_iter().zip(quad.as_chunks::<2>().0.iter().map(|p| (p[0], p[1]))) - { - let (px, py) = map(x, y); - assert!((px - qx).abs() < 1e-9 && (py - qy).abs() < 1e-9, "{x},{y} → {px},{py}, not {qx},{qy}"); - } - assert!(parse_smart_perspective(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).is_none(), "affine"); - // Projective: the same box lands on the four corners. - let quad = [10.0, 20.0, 410.0, 60.0, 400.0, 480.0, 30.0, 520.0]; - let h = photocraft_algo::transform::Homography(parse_smart_perspective(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).expect("projective")); - for ((x, y), (qx, qy)) in - [(cb[0], cb[1]), (cb[2], cb[1]), (cb[2], cb[3]), (cb[0], cb[3])].into_iter().zip(quad.as_chunks::<2>().0.iter().map(|p| (p[0], p[1]))) - { - let (px, py) = h.apply(x, y); - assert!((px - qx).abs() < 1e-6 && (py - qy).abs() < 1e-6, "{x},{y} → {px},{py}, not {qx},{qy}"); - } - // Without a warp a projective quad still frames the source rect. - let none = Descriptor::new("warp").with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpNone") }); - let h = photocraft_algo::transform::Homography(parse_smart_perspective(b"SoLd", &sold_placed(quad, none)).expect("projective")); - let (px, py) = h.apply(1000.0, 1000.0); - assert!((px - 400.0).abs() < 1e-6 && (py - 480.0).abs() < 1e-6); - } - - #[test] - fn effects_switch() { - let mut lfx = vec![0, 0, 0, 0]; - lfx.extend(VersionedDescriptor::new(Descriptor::new("null").with("masterFXSwitch", Value::Boolean(false))).to_bytes()); - assert!(!effects_enabled(&lfx)); - assert!(effects_enabled(&[0, 0, 0, 0])); - } - - #[test] - fn tysh_garbage_is_none() { - assert!(parse_tysh(&[0; 10]).is_none()); - } -} +mod more_tests; diff --git a/crates/io/src/blocks/more_tests.rs b/crates/io/src/blocks/more_tests.rs new file mode 100644 index 0000000000..3c41296134 --- /dev/null +++ b/crates/io/src/blocks/more_tests.rs @@ -0,0 +1,496 @@ +use super::*; + +#[test] +fn float_rgb_colors_parse() { + let d = Descriptor::new("RGBC").with("redFloat", Value::Double(1.0)).with("greenFloat", Value::Double(0.5)).with("blueFloat", Value::Double(0.25)); + let c = color_from_desc(&d).unwrap(); + assert_eq!(c.to_rgb(), [1.0, 0.5, 0.25]); +} + +#[test] +fn smart_transform_from_sold() { + let pts = [10.0, 20.0, 110.0, 20.0, 110.0, 70.0, 10.0, 70.0].map(Value::Double).to_vec(); + let d = Descriptor::new("null") + .with("Idnt", Value::Text(UnicodeString::new_nul("uuid-1"))) + .with("Trnf", Value::List(pts)) + .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(50.0)).with("Hght", Value::Double(25.0)))); + let mut data = b"soLD".to_vec(); + data.extend_from_slice(&4u32.to_be_bytes()); + data.extend(VersionedDescriptor::new(d).to_bytes()); + data.extend_from_slice(&[0, 0]); + let (id, a) = parse_smart(b"SoLd", &data); + assert_eq!(id, "uuid-1"); + assert_eq!(a.m, [2.0, 0.0, 0.0, 2.0, 10.0, 20.0]); + assert_eq!(parse_smart(b"PlLd", &data).0, ""); + assert_eq!(parse_plld(&data), None, "soLD data is not a plcL record"); +} + +/// A `PlLd` record (as Photoshop CS2 writes it, with no `SoLd`, #2465) gives its source id and +/// placed corners; with the source size those are the same transform `SoLd` gives. +#[test] +fn plld_id_and_corners() { + use crate::smart_map::{PlacedSpec, plld_bytes}; + let t = Affine { m: [1.5, 0.25, -0.5, 2.0, 10.0, 20.0] }; + let spec = PlacedSpec { idnt: "uuid-cs2", placed: "", transform: t, perspective: None, size: (40.0, 30.0), dpi: 72.0, warp: None, filter_fx: None }; + let data = plld_bytes(&spec, &mut Vec::new()); + let (id, p) = parse_plld(&data).expect("a plcL record"); + assert_eq!(id, "uuid-cs2"); + assert_eq!(p, [10.0, 20.0, 70.0, 30.0, 55.0, 90.0, -5.0, 80.0]); + let back = corners_affine(&p, [0.0, 0.0, 40.0, 30.0]).unwrap(); + for (a, b) in back.m.iter().zip(t.m) { + assert!((a - b).abs() < 1e-12, "{back:?} vs {t:?}"); + } + assert_eq!(corners_perspective([[p[0], p[1]], [p[2], p[3]], [p[4], p[5]], [p[6], p[7]]], (40.0, 30.0)), None, "affine corners"); + assert_eq!(corners_affine(&p, [0.0, 0.0, 0.0, 30.0]), None); + assert_eq!(corners_affine(&p, [0.0, 0.0, f64::NAN, 30.0]), None); + assert_eq!(corners_affine(&p, [5.0, 0.0, 5.0, 30.0]), None, "an empty frame"); + let mut nan = p; + nan[3] = f64::INFINITY; + assert_eq!(corners_affine(&nan, [0.0, 0.0, 40.0, 30.0]), None); + // The placed-layer record is the one block that can be the principal one: PlLd-only + // layers have no smart transform from `parse_smart`. + assert_eq!(parse_smart(b"PlLd", &data), (String::new(), Affine::IDENTITY)); +} + +/// A `PlLd` record's corners frame the same box as `SoLd`'s `Trnf` (#3677): with a custom +/// warp whose control points spill past the source, the control-point box, not the source +/// rect. The CS2 record then places the layer exactly as the equivalent `SoLd` does, with or +/// without the source size (the box needs none). +#[test] +fn plld_corners_frame_a_spilled_custom_warp_like_sold() { + use crate::smart_map::{PlacedSpec, parse_sold, plld_bytes, sold_bytes}; + use photocraft_geom::warp::{BezierMesh, Warp}; + let bounds = [0.0, 0.0, 50.0, 25.0]; + let mut mesh = BezierMesh::identity(bounds, 1, 1); + mesh.points[0] = [-10.0, -5.0]; + mesh.points[15] = [60.0, 25.0]; + let warp = Warp::custom(mesh, bounds); + let t = Affine { m: [2.0, 0.5, -0.25, 2.0, 120.0, 210.0] }; + let spec = PlacedSpec { idnt: "cs2", placed: "p", transform: t, perspective: None, size: (50.0, 25.0), dpi: 72.0, warp: Some(&warp), filter_fx: None }; + let plld = plld_bytes(&spec, &mut Vec::new()); + let sold = sold_bytes(None, &spec, &mut Vec::new()); + let (_, p) = parse_plld(&plld).expect("a plcL record"); + assert_eq!(parse_plld_warp(&plld), PlldWarp::Warp(warp.clone())); + let from_sold = parse_smart(b"SoLd", &sold).1; + assert_eq!(parse_sold(&sold).map(|s| s.transform), Some(from_sold)); + let close = |a: Affine, b: Affine| a.m.iter().zip(b.m).all(|(x, y)| (x - y).abs() < 1e-9); + assert!(close(from_sold, t), "{from_sold:?} vs {t:?}"); + for size in [Some((50.0, 25.0)), None] { + let (got, perspective) = plld_transform(&p, size, Some(&warp)); + assert!(close(got, from_sold), "size {size:?}: {got:?} vs SoLd {from_sold:?}"); + assert_eq!(perspective, None); + } + // Framing the source rect instead would stretch it (the bug #3677 fixed for SoLd). + let rect = corners_affine(&p, [0.0, 0.0, 50.0, 25.0]).unwrap(); + assert!(!close(rect, t), "the test needs a mesh that spills: {rect:?}"); + // With no warp, or a preset one, the frame is the source rect, as before. + let plain = PlacedSpec { warp: None, ..spec }; + let (_, q) = parse_plld(&plld_bytes(&plain, &mut Vec::new())).unwrap(); + assert!(close(plld_transform(&q, Some((50.0, 25.0)), None).0, t)); +} + +/// Malformed `PlLd` data (wrong magic, truncated anywhere, a Pascal length past the end, +/// non-finite corners) reads as `None`, never a panic. +#[test] +fn plld_malformed_is_none() { + use crate::smart_map::{PlacedSpec, plld_bytes}; + let spec = PlacedSpec { idnt: "id", placed: "", transform: Affine::IDENTITY, perspective: None, size: (4.0, 4.0), dpi: 72.0, warp: None, filter_fx: None }; + let data = plld_bytes(&spec, &mut Vec::new()); + // Magic + version + Pascal "id" + 4 × u32 + 8 × f64: everything after is the warp. + let end = 4 + 4 + 1 + 2 + 16 + 64; + assert!(parse_plld(&data[..end]).is_some()); + for n in 0..end { + assert_eq!(parse_plld(&data[..n]), None, "truncated to {n} bytes"); + } + let mut bad = data.clone(); + bad[..4].copy_from_slice(b"soLD"); + assert_eq!(parse_plld(&bad), None); + let mut long = data.clone(); + long[8] = 255; // a Pascal id longer than the record + assert_eq!(parse_plld(&long[..200.min(long.len())]), None); + let mut nan = data.clone(); + nan[end - 8..end].copy_from_slice(&f64::NAN.to_be_bytes()); + assert_eq!(parse_plld(&nan), None); + assert_eq!(parse_plld(&[]), None); +} + +/// Photoshop CS2 can warp a smart object; `PlLd` keeps that warp after the corners (a u32 +/// warp version, then the versioned `warp` descriptor). It reads back as written, and +/// `warpNone`, an identity warp or a record that stops at its corners mean no warp. +#[test] +fn plld_warps_round_trip() { + use crate::smart_map::{PlacedSpec, plld_bytes}; + use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle}; + let bounds = [0.0, 0.0, 60.0, 30.0]; + let mut arc = Warp::preset(WarpStyle::Arc, 40.0, bounds); + arc.vertical = true; + arc.h_distort = 10.0; + let mut mesh = BezierMesh::identity(bounds, 1, 1); + mesh.points[15] = [67.0, 30.0]; + let custom = Warp::custom(mesh, bounds); + let flat = Warp::preset(WarpStyle::Flag, 0.0, bounds); + for (w, back) in + [(Some(&arc), PlldWarp::Warp(arc.clone())), (Some(&custom), PlldWarp::Warp(custom.clone())), (Some(&flat), PlldWarp::None), (None, PlldWarp::None)] + { + let t = Affine { m: [0.5, 0.0, 0.0, 0.5, 3.0, 4.0] }; + let spec = PlacedSpec { idnt: "w", placed: "", transform: t, perspective: None, size: (60.0, 30.0), dpi: 72.0, warp: w, filter_fx: None }; + let data = plld_bytes(&spec, &mut Vec::new()); + assert_eq!(parse_plld_warp(&data), back, "{w:?}"); + // The corners are unchanged by the warp that follows them. + assert_eq!(parse_plld(&data).map(|(_, p)| p[..2].to_vec()), Some(vec![3.0, 4.0])); + } + let spec = PlacedSpec { idnt: "id", placed: "", transform: Affine::IDENTITY, perspective: None, size: (4.0, 4.0), dpi: 72.0, warp: None, filter_fx: None }; + let end = 4 + 4 + 1 + 2 + 16 + 64; + let data = plld_bytes(&spec, &mut Vec::new()); + assert_eq!(parse_plld_warp(&data[..end]), PlldWarp::None, "no warp stored"); + assert_eq!(parse_plld_warp(&[data[..end].to_vec(), vec![0; 3]].concat()), PlldWarp::None, "padding"); +} + +/// A `PlLd` warp that is stored but can't be read (truncated, an unknown style, a missing +/// bounds rectangle or mesh) is `Unreadable`, so the import keeps the warped pixels. +#[test] +fn plld_unreadable_warps() { + use crate::smart_map::{PlacedSpec, plld_bytes}; + use photocraft_geom::warp::{Warp, WarpStyle}; + let arc = Warp::preset(WarpStyle::Arc, 40.0, [0.0, 0.0, 4.0, 4.0]); + let spec = + PlacedSpec { idnt: "id", placed: "", transform: Affine::IDENTITY, perspective: None, size: (4.0, 4.0), dpi: 72.0, warp: Some(&arc), filter_fx: None }; + let data = plld_bytes(&spec, &mut Vec::new()); + let end = 4 + 4 + 1 + 2 + 16 + 64; + assert!(matches!(parse_plld_warp(&data), PlldWarp::Warp(_))); + for n in end + 1..data.len() - 4 { + if data[end..n].iter().any(|b| *b != 0) { + assert_eq!(parse_plld_warp(&data[..n]), PlldWarp::Unreadable, "truncated to {n} bytes"); + } + } + let with = |d: Descriptor| [data[..end].to_vec(), vec![0; 4], VersionedDescriptor::new(d).to_bytes()].concat(); + let style = |s: &str| Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new(s) }; + assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpSomethingNew")))), PlldWarp::Unreadable); + assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpArc")))), PlldWarp::Unreadable, "no bounds"); + assert_eq!(parse_plld_warp(&with(Descriptor::new("warp").with("warpStyle", style("warpNone")))), PlldWarp::None); + let bounds = Descriptor::new("classFloatRect") + .with("Top ", Value::Double(0.0)) + .with("Left", Value::Double(0.0)) + .with("Btom", Value::Double(4.0)) + .with("Rght", Value::Double(4.0)); + let custom = Descriptor::new("warp").with("warpStyle", style("warpCustom")).with("bounds", Value::Descriptor(bounds)); + assert_eq!(parse_plld_warp(&with(custom)), PlldWarp::Unreadable, "custom with no mesh"); + assert_eq!(parse_plld_warp(&[data[..end].to_vec(), vec![0, 0, 0, 0, 0, 0, 0, 16, 1, 2]].concat()), PlldWarp::Unreadable); + assert_eq!(parse_plld_warp(&data[..end - 1]), PlldWarp::Unreadable, "the record itself"); + assert_eq!(parse_plld_warp(&[]), PlldWarp::Unreadable); +} + +/// `SoLd` data with a 50 × 25 source, the quad `trnf` and, when given, a custom warp whose +/// 16 control points are `pts`. +fn sold_with_warp(trnf: [f64; 8], pts: Option<&[[f64; 2]]>) -> Vec { + use photocraft_psd::descriptor::ObjectArray; + let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; + let mut d = Descriptor::new("null") + .with("Idnt", Value::Text(UnicodeString::new_nul("uuid-1"))) + .with("Trnf", Value::List(trnf.map(Value::Double).to_vec())) + .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(50.0)).with("Hght", Value::Double(25.0)))); + if let Some(pts) = pts { + let bounds = Descriptor::new("Rctn") + .with("Top ", Value::Double(0.0)) + .with("Left", Value::Double(0.0)) + .with("Btom", Value::Double(25.0)) + .with("Rght", Value::Double(50.0)); + let mesh = Descriptor::new("null") + .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[0]).collect() }) + .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[1]).collect() }); + let warp = Descriptor::new("warp").with("warpStyle", e("warpStyle", "warpCustom")).with("bounds", Value::Descriptor(bounds)).with( + "customEnvelopeWarp", + Value::Descriptor(Descriptor::new("customEnvelopeWarp").with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body: mesh }))), + ); + d = d.with("warp", Value::Descriptor(warp)); + } + let mut data = b"soLD".to_vec(); + data.extend_from_slice(&4u32.to_be_bytes()); + data.extend(VersionedDescriptor::new(d).to_bytes()); + data +} + +/// `SoLd` data with a split (quilt) custom warp, as Photoshop writes it: a `quiltWarp` +/// descriptor with `deformNumCols` × `deformNumRows` control points and the patch boundaries +/// in `quiltSliceX` / `quiltSliceY`. With `plain_warp`, a `warpNone` `warp` key sits next to it. +fn sold_with_quilt(trnf: [f64; 8], cols: f64, rows: f64, sx: &[f64], sy: &[f64], pts: &[[f64; 2]], plain_warp: bool) -> Vec { + use photocraft_psd::descriptor::ObjectArray; + let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; + let bounds = || { + Descriptor::new("Rctn") + .with("Top ", Value::Double(0.0)) + .with("Left", Value::Double(0.0)) + .with("Btom", Value::Double(25.0)) + .with("Rght", Value::Double(50.0)) + }; + let slices = |k: &str, v: &[f64]| { + let body = Descriptor::new("null").with(k, Value::UnitFloats { unit: *b"#Pxl", values: v.to_vec() }); + Value::ObjectArray(ObjectArray { prefix: v.len() as u32, body }) + }; + let mesh = Descriptor::new("null") + .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[0]).collect() }) + .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: pts.iter().map(|p| p[1]).collect() }); + let envelope = Descriptor::new("customEnvelopeWarp") + .with("quiltSliceX", slices("quiltSliceX", sx)) + .with("quiltSliceY", slices("quiltSliceY", sy)) + .with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body: mesh })); + let quilt = Descriptor::new("quiltWarp") + .with("warpStyle", e("warpStyle", "warpCustom")) + .with("bounds", Value::Descriptor(bounds())) + .with("deformNumRows", Value::Integer(rows as i32)) + .with("deformNumCols", Value::Double(cols)) + .with("customEnvelopeWarp", Value::Descriptor(envelope)); + let mut d = Descriptor::new("null") + .with("Idnt", Value::Text(UnicodeString::new_nul("uuid-1"))) + .with("Trnf", Value::List(trnf.map(Value::Double).to_vec())) + .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(50.0)).with("Hght", Value::Double(25.0)))); + if plain_warp { + d = d + .with("warp", Value::Descriptor(Descriptor::new("warp").with("warpStyle", e("warpStyle", "warpNone")).with("bounds", Value::Descriptor(bounds())))); + } + d = d.with("quiltWarp", Value::Descriptor(quilt)); + let mut data = b"soLD".to_vec(); + data.extend_from_slice(&4u32.to_be_bytes()); + data.extend(VersionedDescriptor::new(d).to_bytes()); + data +} + +/// A 3 × 2 patch identity grid over the 50 × 25 source with one interior control point pulled. +fn quilt_points() -> Vec<[f64; 2]> { + let mut pts = photocraft_geom::warp::BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 3, 2).points; + if let Some(p) = pts.get_mut(10 * 3 + 4) { + p[1] += 3.0; + } + pts +} + +/// Photoshop's split warp (`quiltWarp`, mockups' usual warp) reads as a multi-patch mesh: the +/// patch boundaries become the knots, the control points stay in order, and the quilt wins over +/// the `warpNone` `warp` key written next to it. Before, any mesh but 4 × 4 was dropped and the +/// layer re-rendered flat. +#[test] +fn quilt_warp_is_read_as_a_multi_patch_mesh() { + let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; + let pts = quilt_points(); + // Photoshop pads the outer boundaries a little past the grid's edges. + let data = sold_with_quilt(quad, 10.0, 7.0, &[-0.5, 12.5, 37.5, 50.5], &[-0.5, 12.5, 25.5], &pts, true); + let warp = parse_placed_warp(b"SoLd", &data).expect("a quilt warp"); + let mesh = warp.mesh.as_ref().expect("its mesh"); + assert_eq!(mesh.points, pts); + assert_eq!(mesh.us.len(), 4); + assert_eq!(mesh.vs.len(), 3); + assert_eq!((mesh.us[0], mesh.us[3], mesh.vs[0], mesh.vs[2]), (0.0, 1.0, 0.0, 1.0)); + assert!((mesh.us[1] - 13.0 / 51.0).abs() < 1e-12 && (mesh.vs[1] - 13.0 / 26.0).abs() < 1e-12); + assert!(mesh.is_valid()); +} + +/// A quilt's control points frame the placed quad as a single patch's do (#3677): a grid +/// spilling to x = -10, y = -5 and x = 60 frames a 70 × 30 box. +#[test] +fn quilt_warp_control_box_frames_the_quad() { + let mut pts = quilt_points(); + pts[0] = [-10.0, -5.0]; + if let Some(last) = pts.last_mut() { + *last = [60.0, 25.0]; + } + let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; + let data = sold_with_quilt(quad, 10.0, 7.0, &[0.0, 12.5, 37.5, 50.0], &[0.0, 12.5, 25.0], &pts, false); + assert_eq!(parse_smart(b"SoLd", &data).1.m, [2.0, 0.0, 0.0, 2.0, 120.0, 210.0]); +} + +/// An inconsistent quilt reads as no warp rather than a wrong one, and never panics. +#[test] +fn inconsistent_quilt_warps_are_not_read() { + let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; + let pts = quilt_points(); + let (sx, sy) = ([0.0, 12.5, 37.5, 50.0], [0.0, 12.5, 25.0]); + let read = + |cols: f64, rows: f64, sx: &[f64], sy: &[f64], pts: &[[f64; 2]]| parse_placed_warp(b"SoLd", &sold_with_quilt(quad, cols, rows, sx, sy, pts, false)); + assert!(read(10.0, 7.0, &sx, &sy, &pts).is_some()); + assert!(read(9.0, 7.0, &sx, &sy, &pts).is_none(), "not three points per patch side plus one"); + assert!(read(13.0, 7.0, &sx, &sy, &pts).is_none(), "more points claimed than stored"); + assert!(read(10.0, 7.0, &[0.0, 12.5, 50.0], &sy, &pts).is_none(), "one slice per patch boundary"); + assert!(read(10.0, 7.0, &[0.0, 37.5, 12.5, 50.0], &sy, &pts).is_none(), "slices must increase"); + assert!(read(10.0, 7.0, &[0.0, f64::NAN, 37.5, 50.0], &sy, &pts).is_none()); + assert!(read(1e9, 7.0, &sx, &sy, &pts).is_none(), "an absurd grid is refused before any arithmetic"); + assert!(read(10.0, 7.0, &sx, &sy, &pts[..pts.len() - 1]).is_none()); + let mut nan = pts.clone(); + nan[3] = [f64::NAN, 0.0]; + assert!(read(10.0, 7.0, &sx, &sy, &nan).is_none()); +} + +/// Photoshop's `Trnf` is the image of the custom warp's control-point bounding box, not of the +/// source rect: a mesh spilling to x = -10, y = -5 and x = 60 frames a 70 × 30 box. +#[test] +fn smart_transform_maps_the_warp_control_box_onto_the_quad() { + let mut pts = photocraft_geom::warp::BezierMesh::identity([0.0, 0.0, 50.0, 25.0], 1, 1).points; + pts[0] = [-10.0, -5.0]; + pts[15] = [60.0, 25.0]; + let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; + let (_, a) = parse_smart(b"SoLd", &sold_with_warp(quad, Some(&pts))); + assert_eq!(a.m, [2.0, 0.0, 0.0, 2.0, 120.0, 210.0]); + // Without a warp the source rect is the frame, as before. + assert_eq!(parse_smart(b"SoLd", &sold_with_warp(quad, None)).1.m, [2.8, 0.0, 0.0, 2.4, 100.0, 200.0]); +} + +/// A custom mesh with no area (every control point on one spot) can't frame the quad: the +/// source rect does, with no division by zero. +#[test] +fn smart_transform_with_a_degenerate_warp_box_uses_the_source_rect() { + let quad = [100.0, 200.0, 240.0, 200.0, 240.0, 260.0, 100.0, 260.0]; + let (_, a) = parse_smart(b"SoLd", &sold_with_warp(quad, Some(&[[7.0, 7.0]; 16]))); + assert_eq!(a.m, [2.8, 0.0, 0.0, 2.4, 100.0, 200.0]); + let mut warp = photocraft_geom::warp::Warp::preset(photocraft_geom::warp::WarpStyle::Custom, 0.0, [0.0, 0.0, 50.0, 25.0]); + warp.mesh = Some(photocraft_geom::warp::BezierMesh { us: vec![0.0, 1.0], vs: vec![0.0, 1.0], points: vec![[f64::NAN, 1.0]; 16] }); + assert_eq!(placed_frame(Some(&warp), 50.0, 25.0), [0.0, 0.0, 50.0, 25.0]); + assert_eq!(placed_frame(None, 50.0, 25.0), [0.0, 0.0, 50.0, 25.0]); +} + +/// A `SoLd` placed on `quad` (`Trnf` and `nonAffineTransform`) for a 1000 × 1000 source, +/// warped by `warp`. +fn sold_placed(quad: [f64; 8], warp: Descriptor) -> Vec { + let list = Value::List(quad.iter().map(|v| Value::Double(*v)).collect()); + let d = Descriptor::new("null") + .with("Trnf", list.clone()) + .with("nonAffineTransform", list) + .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(1000.0)).with("Hght", Value::Double(1000.0)))) + .with("warp", Value::Descriptor(warp)); + let mut data = b"soLD".to_vec(); + data.extend_from_slice(&4u32.to_be_bytes()); + data.extend(VersionedDescriptor::new(d).to_bytes()); + data +} + +/// A `warpCylinder` descriptor as #4112 describes it: horizontal, no perspective, seven +/// `warpValues` in the space of `bounds`. +fn cylinder_desc(values: Value) -> Descriptor { + let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; + let bounds = Descriptor::new("classFloatRect") + .with("Top ", Value::Double(0.0)) + .with("Left", Value::Double(0.0)) + .with("Btom", Value::Double(1000.0)) + .with("Rght", Value::Double(1000.0)); + Descriptor::new("warp") + .with("warpStyle", e("warpStyle", "warpCylinder")) + .with("warpValue", Value::Double(0.0)) + .with("warpValues", values) + .with("warpPerspective", Value::Double(0.0)) + .with("warpPerspectiveOther", Value::Double(0.0)) + .with("warpRotate", e("Ornt", "Hrzn")) + .with("bounds", Value::Descriptor(bounds)) +} + +const CYL: [f64; 7] = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5]; + +fn doubles(v: &[f64]) -> Value { + Value::List(v.iter().map(|x| Value::Double(*x)).collect()) +} + +/// A projective placement is framed by the warp `parse_placed_warp` imports: an unreadable +/// `quiltWarp` next to a cylinder under `warp` imports no warp, so the source rect is framed. +#[test] +fn perspective_frame_follows_the_warp_parse_placed_warp_reads() { + let quad = [10.0, 20.0, 410.0, 60.0, 400.0, 480.0, 30.0, 520.0]; + let list = Value::List(quad.iter().map(|v| Value::Double(*v)).collect()); + let unreadable = Descriptor::new("quiltWarp").with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpSomethingNew") }); + let d = Descriptor::new("null") + .with("Trnf", list.clone()) + .with("nonAffineTransform", list) + .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(1000.0)).with("Hght", Value::Double(1000.0)))) + .with("quiltWarp", Value::Descriptor(unreadable)) + .with("warp", Value::Descriptor(cylinder_desc(doubles(&CYL)))); + let mut data = b"soLD".to_vec(); + data.extend_from_slice(&4u32.to_be_bytes()); + data.extend(VersionedDescriptor::new(d).to_bytes()); + assert_eq!(parse_placed_warp(b"SoLd", &data), None); + let h = photocraft_algo::transform::Homography(parse_smart_perspective(b"SoLd", &data).expect("projective")); + let (px, py) = h.apply(1000.0, 1000.0); + assert!((px - 400.0).abs() < 1e-6 && (py - 480.0).abs() < 1e-6, "{px},{py}"); +} +/// #4112: a `warpCylinder` placed layer comes in as the cylinder its seven values describe, +/// instead of no warp (which re-rendered the contents flat). +#[test] +fn placed_cylinder_warp_is_read() { + use photocraft_geom::warp::{Warp, WarpStyle}; + let quad = [0.0, 0.0, 800.0, 0.0, 800.0, 800.0, 0.0, 800.0]; + let want = Warp::cylinder(&CYL, [0.0, 0.0, 1000.0, 1000.0]).unwrap(); + let w = parse_placed_warp(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).expect("a cylinder"); + assert_eq!(w, want); + assert_eq!(w.style, WarpStyle::Cylinder); + // Values written as one unit-float list read the same. + let floats = Value::UnitFloats { unit: *b"#Pxl", values: CYL.to_vec() }; + assert_eq!(parse_placed_warp(b"SoLE", &sold_placed(quad, cylinder_desc(floats))), Some(want)); +} + +/// Cylinders nobody has measured (vertical, with perspective) and broken values stay +/// unreadable, as every cylinder was before: the layer keeps the pixels Photoshop stored. +#[test] +fn placed_cylinder_warps_that_cant_be_read() { + let quad = [0.0, 0.0, 800.0, 0.0, 800.0, 800.0, 0.0, 800.0]; + let read = |d: Descriptor| parse_placed_warp(b"SoLd", &sold_placed(quad, d)); + let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; + let with = |key: &str, v: Value| { + let mut d = cylinder_desc(doubles(&CYL)); + d.items.iter_mut().filter(|(k, _)| k.is(key)).for_each(|(_, old)| *old = v.clone()); + d + }; + assert!(read(with("warpRotate", e("Ornt", "Vrtc"))).is_none(), "vertical"); + assert!(read(with("warpPerspective", Value::Double(20.0))).is_none(), "perspective"); + assert!(read(with("warpPerspectiveOther", Value::Double(-5.0))).is_none(), "the other perspective"); + assert!(read(cylinder_desc(doubles(&CYL[..6]))).is_none(), "six values"); + assert!(read(cylinder_desc(Value::List(vec![Value::Text(UnicodeString::new_nul("x")); 7]))).is_none(), "not numbers"); + assert!(read(cylinder_desc(Value::Double(1.0))).is_none(), "one number"); + let mut flipped = CYL; + flipped.swap(0, 2); + assert!(read(cylinder_desc(doubles(&flipped))).is_none(), "silhouettes swapped"); + let mut no_values = cylinder_desc(doubles(&CYL)); + no_values.items.retain(|(k, _)| !k.is("warpValues")); + assert!(read(no_values).is_none(), "no warpValues"); +} + +/// Like a custom warp's (#3677), a cylinder's control-point box is what the placement quad +/// frames, for affine corners and for projective ones (`nonAffineTransform`). +#[test] +fn placed_cylinder_quad_frames_its_control_box() { + use photocraft_geom::warp::Warp; + let cb = Warp::cylinder(&CYL, [0.0, 0.0, 1000.0, 1000.0]).unwrap().mesh.unwrap().control_bounds(); + // Affine: the box lands on the quad. + let quad = [10.0, 20.0, 410.0, 20.0, 410.0, 520.0, 10.0, 520.0]; + let (_, a) = parse_smart(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))); + let [m0, m1, m2, m3, m4, m5] = a.m; + let map = |x: f64, y: f64| (m0 * x + m2 * y + m4, m1 * x + m3 * y + m5); + for ((x, y), (qx, qy)) in + [(cb[0], cb[1]), (cb[2], cb[1]), (cb[2], cb[3]), (cb[0], cb[3])].into_iter().zip(quad.as_chunks::<2>().0.iter().map(|p| (p[0], p[1]))) + { + let (px, py) = map(x, y); + assert!((px - qx).abs() < 1e-9 && (py - qy).abs() < 1e-9, "{x},{y} → {px},{py}, not {qx},{qy}"); + } + assert!(parse_smart_perspective(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).is_none(), "affine"); + // Projective: the same box lands on the four corners. + let quad = [10.0, 20.0, 410.0, 60.0, 400.0, 480.0, 30.0, 520.0]; + let h = photocraft_algo::transform::Homography(parse_smart_perspective(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).expect("projective")); + for ((x, y), (qx, qy)) in + [(cb[0], cb[1]), (cb[2], cb[1]), (cb[2], cb[3]), (cb[0], cb[3])].into_iter().zip(quad.as_chunks::<2>().0.iter().map(|p| (p[0], p[1]))) + { + let (px, py) = h.apply(x, y); + assert!((px - qx).abs() < 1e-6 && (py - qy).abs() < 1e-6, "{x},{y} → {px},{py}, not {qx},{qy}"); + } + // Without a warp a projective quad still frames the source rect. + let none = Descriptor::new("warp").with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpNone") }); + let h = photocraft_algo::transform::Homography(parse_smart_perspective(b"SoLd", &sold_placed(quad, none)).expect("projective")); + let (px, py) = h.apply(1000.0, 1000.0); + assert!((px - 400.0).abs() < 1e-6 && (py - 480.0).abs() < 1e-6); +} + +#[test] +fn effects_switch() { + let mut lfx = vec![0, 0, 0, 0]; + lfx.extend(VersionedDescriptor::new(Descriptor::new("null").with("masterFXSwitch", Value::Boolean(false))).to_bytes()); + assert!(!effects_enabled(&lfx)); + assert!(effects_enabled(&[0, 0, 0, 0])); +} + +#[test] +fn tysh_garbage_is_none() { + assert!(parse_tysh(&[0; 10]).is_none()); +} From 8f78e623e7e45a0ee33f13db2713e76513205e59 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:48 +0000 Subject: [PATCH 118/259] refactor(io): move camera_raw_map.rs tests to camera_raw_map/tests.rs --- crates/io/src/camera_raw_map.rs | 328 +------------------------- crates/io/src/camera_raw_map/tests.rs | 324 +++++++++++++++++++++++++ 2 files changed, 326 insertions(+), 326 deletions(-) create mode 100644 crates/io/src/camera_raw_map/tests.rs diff --git a/crates/io/src/camera_raw_map.rs b/crates/io/src/camera_raw_map.rs index cfe3ad6be2..a53d6d40c6 100644 --- a/crates/io/src/camera_raw_map.rs +++ b/crates/io/src/camera_raw_map.rs @@ -343,329 +343,5 @@ pub(super) fn export_item(params: &J) -> Result { } #[cfg(test)] -mod tests { - use super::*; - use crate::smart_map::{UNSUPPORTED_FILTER, filter_from_item, item_for_filter}; - use photocraft_color::BlendMode; - - // Parameter values observed in the supplied 18.4 PSD. No source pixels or private - // document metadata are included in this synthetic regression fixture. - fn source_item() -> Descriptor { - let mut d = Descriptor::new(CLASS) - .with("CrVe", Value::Text(UnicodeString::new_nul("18.4"))) - .with("PrVN", Value::Integer(6)) - .with("PrVe", Value::Integer(251920384)) - .with("Ex12", Value::Double(1.15)); - for (key, value) in [ - ("Cr12", -38), - ("Hi12", 35), - ("Sh12", -50), - ("Wh12", 49), - ("Bk12", -34), - ("PC_S", 0), - ("PC_D", -21), - ("PC_L", 38), - ("PC_H", 0), - ("PC_1", 25), - ("PC_2", 50), - ("PC_3", 75), - ] { - d = d.with(key, Value::Integer(value)); - } - for (_, keys) in ARRAYS.iter().skip(1) { - for key in *keys { - let value = match *key { - "HA_R" => -50, - "HA_Y" => 29, - "HA_G" => 1, - _ => 0, - }; - d = d.with(key, Value::Integer(value)); - } - } - let f = SmartFilter { command: COMMAND.into(), params: J::Null, blend: BlendMode::Normal, opacity: 1.0, visible: true }; - Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul("Camera Raw Filter"))) - .with("blendOptions", blend_options(&f)) - .with("enab", Value::Boolean(true)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", rgbc(0.0)) - .with("BckC", rgbc(255.0)) - .with("Fltr", Value::Descriptor(d)) - .with("filterID", Value::Integer(FILTER_ID)) - } - - fn all_controls_item() -> Descriptor { - let mut item = source_item(); - let mut d = get_desc(&item, "Fltr").unwrap().clone(); - set(&mut d, "WBal", Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new("WBal"), value: photocraft_psd::descriptor::Id::new("Cst ") }); - set(&mut d, "ShpR", Value::Double(1.2)); - for (key, value) in [ - ("Temp", -26), - ("Tint", -25), - ("CrTx", -31), - ("Cl12", 30), - ("Dhze", -34), - ("Vibr", 33), - ("Strt", 33), - ("Shrp", 43), - ("ShpD", 36), - ("ShpM", 30), - ("LNR ", 47), - ("LNRD", 50), - ("CNR ", 25), - ("CNRD", 50), - ("STSH", 117), - ("STSS", 52), - ("STHH", 316), - ("STHS", 70), - ("STB ", 35), - ("CgMH", 51), - ("CgMS", 51), - ("CgSL", -24), - ("CgML", 41), - ("CgHL", 28), - ("CgBl", 36), - ("CgGH", 20), - ("CgGS", 61), - ("CgGL", 45), - ("GRNA", 45), - ("GRNS", 25), - ("GRNF", 50), - ("PCVA", 31), - ("PCVM", 50), - ("PCVF", 50), - ("PCVR", 0), - ] { - set(&mut d, key, Value::Integer(value)); - } - for (key, neutral) in NEUTRAL_ONLY { - set(&mut d, key, Value::Integer(*neutral)); - } - for (key, x, y) in [("Crv ", 146, 102), ("CrvR", 90, 174), ("CrvG", 162, 122), ("CrvB", 129, 202)] { - set(&mut d, key, Value::List([0, 0, x, y, 255, 255].into_iter().map(Value::Integer).collect())); - } - set(&mut item, "Fltr", Value::Descriptor(d)); - item - } - - #[test] - fn all_observed_develop_controls_roundtrip_and_patch_only_the_edited_field() { - let source = all_controls_item(); - let f = filter_from_item(&source); - assert_eq!(f.command, COMMAND); - assert_eq!(f.params["temperature"], -26.0); - assert_eq!(f.params["texture"], -31.0); - assert!((f.params["sharpenRadius"].as_f64().unwrap() - 1.2).abs() < 1e-6); - assert_eq!(f.params["gradeHighlights"], json!({"hue": 316.0, "sat": 70.0, "lum": 28.0})); - assert_eq!(f.params["pointCurveBlue"], json!([[0.0, 0.0], [129.0, 202.0], [255.0, 255.0]])); - assert_eq!(item_for_filter(&f).unwrap(), source); - let defaults = default_params().unwrap(); - for (param, key) in SCALARS { - let mut edited = f.clone(); - let mut number = get_param(&defaults, param).unwrap().as_f64().unwrap(); - if get_param(&f.params, param).unwrap().as_f64() == Some(number) { - number += 1.0; - } - *get_param_mut(&mut edited.params, param).unwrap() = json!(number); - let mut expected = get_desc(&source, "Fltr").unwrap().clone(); - set(&mut expected, key, if matches!(*key, "Ex12" | "ShpR") { Value::Double(number) } else { Value::Integer(number as i32) }); - assert_eq!(get_desc(&item_for_filter(&edited).unwrap(), "Fltr"), Some(&expected), "{param}"); - } - for (param, key) in CURVES { - let mut edited = f.clone(); - edited.params[*param] = json!([]); - let item = item_for_filter(&edited).unwrap(); - let mut expected = get_desc(&source, "Fltr").unwrap().clone(); - set(&mut expected, key, Value::List([0, 0, 255, 255].into_iter().map(Value::Integer).collect())); - assert_eq!(get_desc(&item, "Fltr"), Some(&expected), "{param}"); - assert_eq!(filter_from_item(&item).params[*param], json!([]), "{param}"); - } - } - - #[test] - fn active_unimplemented_controls_and_malformed_curves_stay_opaque() { - for (key, neutral) in NEUTRAL_ONLY { - let mut item = all_controls_item(); - let mut d = get_desc(&item, "Fltr").unwrap().clone(); - set(&mut d, key, Value::Integer(neutral + 1)); - set(&mut item, "Fltr", Value::Descriptor(d)); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{key}"); - assert_eq!(item_for_filter(&f).unwrap(), item, "{key}"); - } - for value in [ - Value::List(vec![Value::Integer(0)]), - Value::List([0, 0, 0, 255].into_iter().map(Value::Integer).collect()), - Value::List([0, 0, 255, 256].into_iter().map(Value::Integer).collect()), - Value::List(vec![Value::Double(0.0); 4]), - Value::List(vec![Value::Integer(0); 34]), - ] { - let mut item = all_controls_item(); - let mut d = get_desc(&item, "Fltr").unwrap().clone(); - set(&mut d, "Crv ", value); - set(&mut item, "Fltr", Value::Descriptor(d)); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER); - assert_eq!(item_for_filter(&f).unwrap(), item); - } - } - - #[test] - #[ignore = "requires a user-supplied Camera Raw PSD"] - fn all_sliders_fixture() { - let path = std::env::var("PHOTOCRAFT_CAMERA_RAW_PSD").expect("set PHOTOCRAFT_CAMERA_RAW_PSD"); - let doc = crate::import("fixture.psd", &std::fs::read(path).unwrap()).unwrap().document; - let original = doc - .walk() - .into_iter() - .find_map(|(_, _, layer)| { - let photocraft_doc::LayerContent::Smart(sm) = &layer.content else { return None }; - sm.smart_filters.iter().find_map(|f| { - let item = item_for_filter(f).ok()?; - get_desc(&item, "Fltr").is_some_and(|d| d.class_id.is(CLASS)).then_some(item) - }) - }) - .expect("a Camera Raw descriptor"); - assert_eq!(item_for_filter(&filter_from_item(&original)).unwrap(), original); - let mut projected = original.clone(); - let mut d = get_desc(&original, "Fltr").unwrap().clone(); - // This is a codec projection, not an editable replacement for the source filter: - // active Optics settings have no rendering counterpart, and PCVS is unverified. - d.items.retain(|(key, _)| !["MDis", "VigA", "PCVS"].iter().any(|k| key.is(k))); - set(&mut projected, "Fltr", Value::Descriptor(d)); - let mut f = filter_from_item(&projected); - assert_eq!(f.command, COMMAND); - assert_eq!(f.params["temperature"], -26.0); - assert_eq!(f.params["sharpenAmount"], 43.0); - assert_eq!(f.params["gradeGlobal"], json!({"hue": 20.0, "sat": 61.0, "lum": 45.0})); - assert_eq!(f.params["pointCurveRed"], json!([[0.0, 0.0], [90.0, 174.0], [255.0, 255.0]])); - assert_eq!(item_for_filter(&f).unwrap(), projected); - f.params["exposure"] = json!(0.5); - let mut expected = get_desc(&projected, "Fltr").unwrap().clone(); - set(&mut expected, "Ex12", Value::Double(0.5)); - assert_eq!(get_desc(&item_for_filter(&f).unwrap(), "Fltr"), Some(&expected)); - } - - #[test] - fn light_curve_and_hsl_are_editable_without_rewriting_unchanged_settings() { - let source = source_item().with("futureOuterData", Value::RawData(vec![1, 2, 3, 4])); - let mut f = filter_from_item(&source); - assert_eq!(f.command, COMMAND); - assert!((f.params["exposure"].as_f64().unwrap() - 1.15).abs() < 1e-6); - assert_eq!(f.params["contrast"], -38.0); - assert_eq!(f.params["curveDarks"], -21.0); - assert_eq!(f.params["curveLights"], 38.0); - assert_eq!(f.params["curveSplits"], json!([25.0, 50.0, 75.0])); - assert_eq!(f.params["hslHue"], json!([-50.0, 0.0, 29.0, 1.0, 0.0, 0.0, 0.0, 0.0])); - assert_eq!(item_for_filter(&f).unwrap(), source); - f.params["exposure"] = json!(0.0); - f.params["hslHue"][2] = json!(-20.0); - f.visible = false; - f.opacity = 0.4; - f.blend = BlendMode::Multiply; - let edited = item_for_filter(&f).unwrap(); - let mut expected = get_desc(&source, "Fltr").unwrap().clone(); - set(&mut expected, "Ex12", Value::Double(0.0)); - set(&mut expected, "HA_Y", Value::Integer(-20)); - assert_eq!(get_desc(&edited, "Fltr"), Some(&expected)); - assert_eq!(edited.get("futureOuterData"), source.get("futureOuterData")); - let back = filter_from_item(&edited); - assert_eq!((back.visible, back.blend, back.opacity), (false, BlendMode::Multiply, 0.4)); - assert_eq!(back.params["exposure"], 0.0); - assert_eq!(back.params["hslHue"][2], -20.0); - } - - #[test] - fn new_filters_write_every_verified_control_and_accept_explicit_defaults() { - let mut params = default_params().unwrap(); - params["seed"] = json!(0); - for (param, key) in SCALARS { - let number = match *key { - "Ex12" => 0.75, - "ShpR" => 1.2, - _ => 12.0, - }; - *get_param_mut(&mut params, param).unwrap() = json!(number); - } - for (param, keys) in ARRAYS { - params[*param] = if *param == "curveSplits" { json!([20, 45, 80]) } else { json!((0..keys.len()).map(|i| i as f64 + 1.0).collect::>()) }; - } - let f = SmartFilter { command: COMMAND.into(), params: params.clone(), blend: BlendMode::Screen, opacity: 0.5, visible: false }; - let item = item_for_filter(&f).unwrap(); - let back = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); - assert_eq!((&back.command, back.visible, back.blend, back.opacity), (&f.command, false, BlendMode::Screen, 0.5)); - // Compare slider numbers after both sides have been normalized through CameraRaw. - let typed: CameraRaw = serde_json::from_value(params).unwrap(); - let expected = serde_json::to_value(typed).unwrap(); - for param in SCALARS.iter().map(|(p, _)| *p).chain(ARRAYS.iter().map(|(p, _)| *p)) { - assert_eq!(get_param(&back.params, param), get_param(&expected, param)); - } - } - - #[test] - fn unsupported_processing_settings_remain_opaque_and_lossless() { - for (key, value) in [ - ("LCs ", Value::Text(UnicodeString::new("unknown masks"))), - ("PrVN", Value::Integer(7)), - ("PrVe", Value::Integer(123)), - ("Ex12", Value::Double(f64::INFINITY)), - ("Cr12", Value::Text(UnicodeString::new("bad type"))), - ] { - let mut item = source_item(); - let mut d = get_desc(&item, "Fltr").unwrap().clone(); - set(&mut d, key, value); - set(&mut item, "Fltr", Value::Descriptor(d)); - let f = filter_from_item(&item); - assert_eq!(f.command, UNSUPPORTED_FILTER, "{key}"); - assert_eq!(item_for_filter(&f).unwrap(), item, "{key}"); - } - } - - #[test] - fn fractional_slider_levels_round_instead_of_dropping_the_filter() { - let mut f = filter_from_item(&source_item()); - f.params["contrast"] = json!(-12.4); - f.params["hslHue"][0] = json!(10.5); - f.params["gradeShadows"]["hue"] = json!(359.7); - f.params["pointCurve"] = json!([[0, 0], [100.2, 120.6], [200.6, 180.4], [255, 255]]); - let item = item_for_filter(&f).unwrap(); - let d = get_desc(&item, "Fltr").unwrap(); - assert_eq!(d.get("Cr12"), Some(&Value::Integer(-12))); - assert_eq!(d.get("HA_R"), Some(&Value::Integer(11))); - assert_eq!(d.get("STSH"), Some(&Value::Integer(0))); - assert_eq!(d.get("Crv "), Some(&Value::List([0, 0, 100, 121, 201, 180, 255, 255].into_iter().map(Value::Integer).collect()))); - let back = filter_from_item(&item); - assert_eq!(back.command, COMMAND); - assert_eq!(back.params["contrast"], -12.0); - } - - #[test] - fn unsupported_or_malformed_exports_report_errors() { - for params in [ - J::Null, - json!({"exposure": "bright"}), - json!({"exposure": 1e40}), - json!({"exposure": 6}), - json!({"contrast": 101}), - json!({"hslHue": [1, 2]}), - json!({"curveSplits": [80, 50, 20]}), - json!({"curveSplits": [25, 25, 75]}), - json!({"pointCurve": [[0, 0], [0, 255]]}), - json!({"sharpenRadius": 4}), - json!({"gradeShadows": {"hue": 361}}), - json!({"gradeShadows": {"unknown": 1}}), - json!({"seed": 1}), - json!({"vignetteHighlights": 10}), - json!({"futureSetting": 1}), - json!({TEMPLATE_KEY: "zz"}), - json!({TEMPLATE_KEY: "00"}), - json!({TEMPLATE_KEY: 12}), - json!({TEMPLATE_KEY: "0".repeat(MAX_TEMPLATE_BYTES * 2 + 1)}), - ] { - assert!(export_item(¶ms).is_err()); - } - let wrong = Descriptor::new("filterFX").with("filterID", Value::Integer(1)); - assert!(export_item(&json!({TEMPLATE_KEY: to_hex(&wrong.to_bytes())})).is_err()); - } -} +#[path = "camera_raw_map/tests.rs"] +mod tests; diff --git a/crates/io/src/camera_raw_map/tests.rs b/crates/io/src/camera_raw_map/tests.rs new file mode 100644 index 0000000000..ad40acb25d --- /dev/null +++ b/crates/io/src/camera_raw_map/tests.rs @@ -0,0 +1,324 @@ +use super::*; +use crate::smart_map::{UNSUPPORTED_FILTER, filter_from_item, item_for_filter}; +use photocraft_color::BlendMode; + +// Parameter values observed in the supplied 18.4 PSD. No source pixels or private +// document metadata are included in this synthetic regression fixture. +fn source_item() -> Descriptor { + let mut d = Descriptor::new(CLASS) + .with("CrVe", Value::Text(UnicodeString::new_nul("18.4"))) + .with("PrVN", Value::Integer(6)) + .with("PrVe", Value::Integer(251920384)) + .with("Ex12", Value::Double(1.15)); + for (key, value) in [ + ("Cr12", -38), + ("Hi12", 35), + ("Sh12", -50), + ("Wh12", 49), + ("Bk12", -34), + ("PC_S", 0), + ("PC_D", -21), + ("PC_L", 38), + ("PC_H", 0), + ("PC_1", 25), + ("PC_2", 50), + ("PC_3", 75), + ] { + d = d.with(key, Value::Integer(value)); + } + for (_, keys) in ARRAYS.iter().skip(1) { + for key in *keys { + let value = match *key { + "HA_R" => -50, + "HA_Y" => 29, + "HA_G" => 1, + _ => 0, + }; + d = d.with(key, Value::Integer(value)); + } + } + let f = SmartFilter { command: COMMAND.into(), params: J::Null, blend: BlendMode::Normal, opacity: 1.0, visible: true }; + Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul("Camera Raw Filter"))) + .with("blendOptions", blend_options(&f)) + .with("enab", Value::Boolean(true)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", rgbc(0.0)) + .with("BckC", rgbc(255.0)) + .with("Fltr", Value::Descriptor(d)) + .with("filterID", Value::Integer(FILTER_ID)) +} + +fn all_controls_item() -> Descriptor { + let mut item = source_item(); + let mut d = get_desc(&item, "Fltr").unwrap().clone(); + set(&mut d, "WBal", Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new("WBal"), value: photocraft_psd::descriptor::Id::new("Cst ") }); + set(&mut d, "ShpR", Value::Double(1.2)); + for (key, value) in [ + ("Temp", -26), + ("Tint", -25), + ("CrTx", -31), + ("Cl12", 30), + ("Dhze", -34), + ("Vibr", 33), + ("Strt", 33), + ("Shrp", 43), + ("ShpD", 36), + ("ShpM", 30), + ("LNR ", 47), + ("LNRD", 50), + ("CNR ", 25), + ("CNRD", 50), + ("STSH", 117), + ("STSS", 52), + ("STHH", 316), + ("STHS", 70), + ("STB ", 35), + ("CgMH", 51), + ("CgMS", 51), + ("CgSL", -24), + ("CgML", 41), + ("CgHL", 28), + ("CgBl", 36), + ("CgGH", 20), + ("CgGS", 61), + ("CgGL", 45), + ("GRNA", 45), + ("GRNS", 25), + ("GRNF", 50), + ("PCVA", 31), + ("PCVM", 50), + ("PCVF", 50), + ("PCVR", 0), + ] { + set(&mut d, key, Value::Integer(value)); + } + for (key, neutral) in NEUTRAL_ONLY { + set(&mut d, key, Value::Integer(*neutral)); + } + for (key, x, y) in [("Crv ", 146, 102), ("CrvR", 90, 174), ("CrvG", 162, 122), ("CrvB", 129, 202)] { + set(&mut d, key, Value::List([0, 0, x, y, 255, 255].into_iter().map(Value::Integer).collect())); + } + set(&mut item, "Fltr", Value::Descriptor(d)); + item +} + +#[test] +fn all_observed_develop_controls_roundtrip_and_patch_only_the_edited_field() { + let source = all_controls_item(); + let f = filter_from_item(&source); + assert_eq!(f.command, COMMAND); + assert_eq!(f.params["temperature"], -26.0); + assert_eq!(f.params["texture"], -31.0); + assert!((f.params["sharpenRadius"].as_f64().unwrap() - 1.2).abs() < 1e-6); + assert_eq!(f.params["gradeHighlights"], json!({"hue": 316.0, "sat": 70.0, "lum": 28.0})); + assert_eq!(f.params["pointCurveBlue"], json!([[0.0, 0.0], [129.0, 202.0], [255.0, 255.0]])); + assert_eq!(item_for_filter(&f).unwrap(), source); + let defaults = default_params().unwrap(); + for (param, key) in SCALARS { + let mut edited = f.clone(); + let mut number = get_param(&defaults, param).unwrap().as_f64().unwrap(); + if get_param(&f.params, param).unwrap().as_f64() == Some(number) { + number += 1.0; + } + *get_param_mut(&mut edited.params, param).unwrap() = json!(number); + let mut expected = get_desc(&source, "Fltr").unwrap().clone(); + set(&mut expected, key, if matches!(*key, "Ex12" | "ShpR") { Value::Double(number) } else { Value::Integer(number as i32) }); + assert_eq!(get_desc(&item_for_filter(&edited).unwrap(), "Fltr"), Some(&expected), "{param}"); + } + for (param, key) in CURVES { + let mut edited = f.clone(); + edited.params[*param] = json!([]); + let item = item_for_filter(&edited).unwrap(); + let mut expected = get_desc(&source, "Fltr").unwrap().clone(); + set(&mut expected, key, Value::List([0, 0, 255, 255].into_iter().map(Value::Integer).collect())); + assert_eq!(get_desc(&item, "Fltr"), Some(&expected), "{param}"); + assert_eq!(filter_from_item(&item).params[*param], json!([]), "{param}"); + } +} + +#[test] +fn active_unimplemented_controls_and_malformed_curves_stay_opaque() { + for (key, neutral) in NEUTRAL_ONLY { + let mut item = all_controls_item(); + let mut d = get_desc(&item, "Fltr").unwrap().clone(); + set(&mut d, key, Value::Integer(neutral + 1)); + set(&mut item, "Fltr", Value::Descriptor(d)); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{key}"); + assert_eq!(item_for_filter(&f).unwrap(), item, "{key}"); + } + for value in [ + Value::List(vec![Value::Integer(0)]), + Value::List([0, 0, 0, 255].into_iter().map(Value::Integer).collect()), + Value::List([0, 0, 255, 256].into_iter().map(Value::Integer).collect()), + Value::List(vec![Value::Double(0.0); 4]), + Value::List(vec![Value::Integer(0); 34]), + ] { + let mut item = all_controls_item(); + let mut d = get_desc(&item, "Fltr").unwrap().clone(); + set(&mut d, "Crv ", value); + set(&mut item, "Fltr", Value::Descriptor(d)); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER); + assert_eq!(item_for_filter(&f).unwrap(), item); + } +} + +#[test] +#[ignore = "requires a user-supplied Camera Raw PSD"] +fn all_sliders_fixture() { + let path = std::env::var("PHOTOCRAFT_CAMERA_RAW_PSD").expect("set PHOTOCRAFT_CAMERA_RAW_PSD"); + let doc = crate::import("fixture.psd", &std::fs::read(path).unwrap()).unwrap().document; + let original = doc + .walk() + .into_iter() + .find_map(|(_, _, layer)| { + let photocraft_doc::LayerContent::Smart(sm) = &layer.content else { return None }; + sm.smart_filters.iter().find_map(|f| { + let item = item_for_filter(f).ok()?; + get_desc(&item, "Fltr").is_some_and(|d| d.class_id.is(CLASS)).then_some(item) + }) + }) + .expect("a Camera Raw descriptor"); + assert_eq!(item_for_filter(&filter_from_item(&original)).unwrap(), original); + let mut projected = original.clone(); + let mut d = get_desc(&original, "Fltr").unwrap().clone(); + // This is a codec projection, not an editable replacement for the source filter: + // active Optics settings have no rendering counterpart, and PCVS is unverified. + d.items.retain(|(key, _)| !["MDis", "VigA", "PCVS"].iter().any(|k| key.is(k))); + set(&mut projected, "Fltr", Value::Descriptor(d)); + let mut f = filter_from_item(&projected); + assert_eq!(f.command, COMMAND); + assert_eq!(f.params["temperature"], -26.0); + assert_eq!(f.params["sharpenAmount"], 43.0); + assert_eq!(f.params["gradeGlobal"], json!({"hue": 20.0, "sat": 61.0, "lum": 45.0})); + assert_eq!(f.params["pointCurveRed"], json!([[0.0, 0.0], [90.0, 174.0], [255.0, 255.0]])); + assert_eq!(item_for_filter(&f).unwrap(), projected); + f.params["exposure"] = json!(0.5); + let mut expected = get_desc(&projected, "Fltr").unwrap().clone(); + set(&mut expected, "Ex12", Value::Double(0.5)); + assert_eq!(get_desc(&item_for_filter(&f).unwrap(), "Fltr"), Some(&expected)); +} + +#[test] +fn light_curve_and_hsl_are_editable_without_rewriting_unchanged_settings() { + let source = source_item().with("futureOuterData", Value::RawData(vec![1, 2, 3, 4])); + let mut f = filter_from_item(&source); + assert_eq!(f.command, COMMAND); + assert!((f.params["exposure"].as_f64().unwrap() - 1.15).abs() < 1e-6); + assert_eq!(f.params["contrast"], -38.0); + assert_eq!(f.params["curveDarks"], -21.0); + assert_eq!(f.params["curveLights"], 38.0); + assert_eq!(f.params["curveSplits"], json!([25.0, 50.0, 75.0])); + assert_eq!(f.params["hslHue"], json!([-50.0, 0.0, 29.0, 1.0, 0.0, 0.0, 0.0, 0.0])); + assert_eq!(item_for_filter(&f).unwrap(), source); + f.params["exposure"] = json!(0.0); + f.params["hslHue"][2] = json!(-20.0); + f.visible = false; + f.opacity = 0.4; + f.blend = BlendMode::Multiply; + let edited = item_for_filter(&f).unwrap(); + let mut expected = get_desc(&source, "Fltr").unwrap().clone(); + set(&mut expected, "Ex12", Value::Double(0.0)); + set(&mut expected, "HA_Y", Value::Integer(-20)); + assert_eq!(get_desc(&edited, "Fltr"), Some(&expected)); + assert_eq!(edited.get("futureOuterData"), source.get("futureOuterData")); + let back = filter_from_item(&edited); + assert_eq!((back.visible, back.blend, back.opacity), (false, BlendMode::Multiply, 0.4)); + assert_eq!(back.params["exposure"], 0.0); + assert_eq!(back.params["hslHue"][2], -20.0); +} + +#[test] +fn new_filters_write_every_verified_control_and_accept_explicit_defaults() { + let mut params = default_params().unwrap(); + params["seed"] = json!(0); + for (param, key) in SCALARS { + let number = match *key { + "Ex12" => 0.75, + "ShpR" => 1.2, + _ => 12.0, + }; + *get_param_mut(&mut params, param).unwrap() = json!(number); + } + for (param, keys) in ARRAYS { + params[*param] = if *param == "curveSplits" { json!([20, 45, 80]) } else { json!((0..keys.len()).map(|i| i as f64 + 1.0).collect::>()) }; + } + let f = SmartFilter { command: COMMAND.into(), params: params.clone(), blend: BlendMode::Screen, opacity: 0.5, visible: false }; + let item = item_for_filter(&f).unwrap(); + let back = filter_from_item(&Descriptor::from_bytes(&item.to_bytes()).unwrap()); + assert_eq!((&back.command, back.visible, back.blend, back.opacity), (&f.command, false, BlendMode::Screen, 0.5)); + // Compare slider numbers after both sides have been normalized through CameraRaw. + let typed: CameraRaw = serde_json::from_value(params).unwrap(); + let expected = serde_json::to_value(typed).unwrap(); + for param in SCALARS.iter().map(|(p, _)| *p).chain(ARRAYS.iter().map(|(p, _)| *p)) { + assert_eq!(get_param(&back.params, param), get_param(&expected, param)); + } +} + +#[test] +fn unsupported_processing_settings_remain_opaque_and_lossless() { + for (key, value) in [ + ("LCs ", Value::Text(UnicodeString::new("unknown masks"))), + ("PrVN", Value::Integer(7)), + ("PrVe", Value::Integer(123)), + ("Ex12", Value::Double(f64::INFINITY)), + ("Cr12", Value::Text(UnicodeString::new("bad type"))), + ] { + let mut item = source_item(); + let mut d = get_desc(&item, "Fltr").unwrap().clone(); + set(&mut d, key, value); + set(&mut item, "Fltr", Value::Descriptor(d)); + let f = filter_from_item(&item); + assert_eq!(f.command, UNSUPPORTED_FILTER, "{key}"); + assert_eq!(item_for_filter(&f).unwrap(), item, "{key}"); + } +} + +#[test] +fn fractional_slider_levels_round_instead_of_dropping_the_filter() { + let mut f = filter_from_item(&source_item()); + f.params["contrast"] = json!(-12.4); + f.params["hslHue"][0] = json!(10.5); + f.params["gradeShadows"]["hue"] = json!(359.7); + f.params["pointCurve"] = json!([[0, 0], [100.2, 120.6], [200.6, 180.4], [255, 255]]); + let item = item_for_filter(&f).unwrap(); + let d = get_desc(&item, "Fltr").unwrap(); + assert_eq!(d.get("Cr12"), Some(&Value::Integer(-12))); + assert_eq!(d.get("HA_R"), Some(&Value::Integer(11))); + assert_eq!(d.get("STSH"), Some(&Value::Integer(0))); + assert_eq!(d.get("Crv "), Some(&Value::List([0, 0, 100, 121, 201, 180, 255, 255].into_iter().map(Value::Integer).collect()))); + let back = filter_from_item(&item); + assert_eq!(back.command, COMMAND); + assert_eq!(back.params["contrast"], -12.0); +} + +#[test] +fn unsupported_or_malformed_exports_report_errors() { + for params in [ + J::Null, + json!({"exposure": "bright"}), + json!({"exposure": 1e40}), + json!({"exposure": 6}), + json!({"contrast": 101}), + json!({"hslHue": [1, 2]}), + json!({"curveSplits": [80, 50, 20]}), + json!({"curveSplits": [25, 25, 75]}), + json!({"pointCurve": [[0, 0], [0, 255]]}), + json!({"sharpenRadius": 4}), + json!({"gradeShadows": {"hue": 361}}), + json!({"gradeShadows": {"unknown": 1}}), + json!({"seed": 1}), + json!({"vignetteHighlights": 10}), + json!({"futureSetting": 1}), + json!({TEMPLATE_KEY: "zz"}), + json!({TEMPLATE_KEY: "00"}), + json!({TEMPLATE_KEY: 12}), + json!({TEMPLATE_KEY: "0".repeat(MAX_TEMPLATE_BYTES * 2 + 1)}), + ] { + assert!(export_item(¶ms).is_err()); + } + let wrong = Descriptor::new("filterFX").with("filterID", Value::Integer(1)); + assert!(export_item(&json!({TEMPLATE_KEY: to_hex(&wrong.to_bytes())})).is_err()); +} From 3f92c5d4acf5da18327464a5026b32d9878de42c Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:49 +0000 Subject: [PATCH 119/259] refactor(io): move psd_export.rs tests to psd_export/tests.rs --- crates/io/src/psd_export.rs | 449 +----------------------------- crates/io/src/psd_export/tests.rs | 446 +++++++++++++++++++++++++++++ 2 files changed, 447 insertions(+), 448 deletions(-) create mode 100644 crates/io/src/psd_export/tests.rs diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 7a92cc40d1..af4739b661 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -2027,451 +2027,4 @@ fn mask_parameters(user: Option<(f32, f32)>, vector: Option<(f32, f32)>) -> Opti } #[cfg(test)] -mod tests { - use super::*; - - fn document(width: u32, height: u32) -> Document { - Document::new("size estimate", photocraft_geom::Size::new(width, height), ColorMode::Rgb, SampleType::U8) - } - - /// Photoshop opens a PSD's bottom layer as its Background only when that layer has no - /// transparency channel (measured on Photoshop 27.11: with the channel written, re-exported - /// files reopened with the Background as an ordinary layer). - #[test] - fn a_background_is_written_without_a_transparency_channel() { - use photocraft_color::Color; - let size = photocraft_geom::Size::new(8, 6); - let mut doc = Document::with_background("bg", size, ColorMode::Rgb, SampleType::U8, Color::rgb(0.2, 0.4, 0.6)); - doc.layers.push(Layer::raster("Layer 1", doc.pixel_format())); - let file = document_to_psd(&doc); - let layers = &file.layer_info.as_ref().unwrap().layers; - let ids = |i: usize| layers[i].channels.iter().map(|c| c.id).collect::>(); - assert_eq!(ids(0), vec![0, 1, 2], "the Background has no -1 channel"); - assert_eq!(layers[0].flags.0, LayerFlags::BIT4_USEFUL | LayerFlags::TRANSPARENCY_PROTECTED, "as Photoshop writes it"); - assert!(ids(1).contains(&-1), "other layers keep their transparency"); - // It comes back as the same locked, opaque Background. - let back = crate::import("bg.psd", &file.to_bytes().unwrap()).unwrap().document; - let bg = &back.layers[0]; - assert!(bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); - assert_eq!(bg.surface().unwrap().read_region(back.bounds()), doc.layers[0].surface().unwrap().read_region(doc.bounds())); - // A bottom layer with transparency (or unlocked) is not a Background. - let mut holey = doc.clone(); - holey.layers[0].surface_mut().unwrap().write_pixel(2, 2, &[0.0, 0.0, 0.0, 0.0]); - assert!(document_to_psd(&holey).layer_info.unwrap().layers[0].channels.iter().any(|c| c.id == -1)); - let mut unlocked = doc.clone(); - unlocked.layers[0].locks.position = false; - assert!(document_to_psd(&unlocked).layer_info.unwrap().layers[0].channels.iter().any(|c| c.id == -1)); - } - - /// A flat 1-bit Bitmap file (no layers) opens in Photoshop as its Background; so does it in - /// PhotoCraft, and it is written back as one (no transparency channel). - #[test] - fn a_flat_bitmap_file_opens_and_saves_as_a_background() { - let file = photocraft_psd::testgen::merged_only(Version::Psd, PsdMode::Bitmap, 1, Compression::Raw, 8, 4); - let doc = crate::import("flat.psd", &file.to_bytes().unwrap()).unwrap().document; - let bg = &doc.layers[0]; - assert!(bg.name == "Background" && bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); - // Bitmap has no layers in Photoshop (#4814): the file is saved flat in Bitmap mode, without - // a layer section, and opens as a Background again. - let out = document_to_psd(&doc); - assert_eq!(out.header.color_mode, PsdMode::Bitmap); - assert!(out.layer_info.as_ref().is_none_or(|li| li.layers.is_empty())); - let back = crate::import("flat.psd", &out.to_bytes().unwrap()).unwrap().document; - let bg = &back.layers[0]; - assert!(back.layers.len() == 1 && bg.name == "Background" && bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); - } - - /// A layered document with a spot and an alpha channel. Each channel holds 100 %, 25 %, 75 % - /// and 0 % in four columns, the layout of the Photoshop spot oracles. - fn spot_and_alpha_document() -> Document { - let mut doc = document(4, 1); - doc.layers.push(Layer::group("Group", vec![Layer::raster("Layer 1", doc.pixel_format())])); - let channel = |name: &str| { - let mut s = Surface::new(PixelFormat::GRAY8); - s.write_interleaved(doc.bounds(), &[255, 64, 191, 0]); - photocraft_doc::AlphaChannel::new(name, s) - }; - let mut spot = channel("Spot Color 1"); - spot.spot = Some((photocraft_doc::Color::rgb(0.0, 0.6, 1.0), 0.0)); - let alpha = channel("Alpha 1"); - doc.channels.extend([spot, alpha]); - doc - } - - /// The extra planes after the colour channels (and the merged transparency) of `file`. - fn extra_planes(file: &PsdFile, count: usize) -> Vec { - let planes = file.decode_merged().unwrap(); - let plane = (file.header.width * file.header.height) as usize * usize::from(file.header.depth / 8); - planes[planes.len() - count * plane..].to_vec() - } - - /// Resource 1053's identifiers. - fn alpha_ids(file: &PsdFile) -> Option> { - file.resource(crate::channel_map::ALPHA_IDENTIFIERS).map(|r| r.data.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes(*c)).collect()) - } - - /// A PSD stores spot ink as Photoshop's own PSDs do (0 = solid ink: the 100, 25, 75 and 0 % - /// columns are 0, 191, 64, 255) and an alpha channel straight (255 = selected). The global - /// layer mask stays empty and flag bit 3 stays on the layers only, not on the group's closing - /// divider: Photoshop opens those as they are, and 509 of the corpus's 721 Photoshop PSDs have - /// an empty mask too. Opening the file gives the same ink back. - #[test] - fn psd_stores_spot_ink_as_photoshop_does() { - let doc = spot_and_alpha_document(); - let file = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); - assert_eq!(extra_planes(&file, 2), [0, 191, 64, 255, 255, 64, 191, 0], "spot, then alpha"); - assert_eq!(file.global_layer_mask.as_ref().map(|m| m.data.len()), Some(0)); - let flags: Vec = file.layers().iter().map(|l| l.flags.0 & LayerFlags::BIT4_USEFUL).collect(); - assert_eq!(flags, [0, LayerFlags::BIT4_USEFUL, LayerFlags::BIT4_USEFUL], "closing divider, layer, group"); - let back = crate::import("spot.psd", &file.to_bytes().unwrap()).unwrap().document; - assert!(back.channels[0].spot.is_some() && back.channels[1].spot.is_none()); - for c in &back.channels { - assert_eq!(c.surface.to_interleaved(back.bounds()), [255, 64, 191, 0], "{}", c.name); - } - } - - /// Resource 1053 numbers the extra channels as Photoshop 27.11 does in a new document: 3, 4, 5 - /// in every colour mode, after 0 for the merged transparency when there is one (its - /// transparent PSD lists `0, 3, 4, 5`). A Quick Mask is an extra channel too. Without extra - /// channels there is none. - #[test] - fn psd_alpha_identifiers_number_the_channels_as_photoshop_does() { - use photocraft_color::Color; - let size = photocraft_geom::Size::new(4, 1); - for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Grayscale, ColorMode::Lab] { - let mut doc = Document::with_background("bg", size, mode, SampleType::U8, Color::rgb(1.0, 1.0, 1.0)); - assert_eq!(alpha_ids(&document_to_psd(&doc)), None, "{mode:?} without channels"); - doc.channels = spot_and_alpha_document().channels; - let file = document_to_psd(&doc); - assert!(!file.merged_has_alpha(), "{mode:?}"); - assert_eq!(alpha_ids(&file), Some(vec![3, 4]), "{mode:?}"); - doc.quick_mask = Some(photocraft_doc::AlphaChannel::new("Quick Mask", Surface::new(PixelFormat::GRAY8))); - assert_eq!(alpha_ids(&document_to_psd(&doc)), Some(vec![3, 4, 5]), "{mode:?} with a Quick Mask"); - } - // The empty layer leaves the composite transparent. - let file = document_to_psd(&spot_and_alpha_document()); - assert!(file.merged_has_alpha()); - assert_eq!(alpha_ids(&file), Some(vec![0, 3, 4])); - } - - /// A save writes one fresh 1053 for the channels the document has. A Photoshop file's own is - /// not kept on open (it would be new metadata after every round trip), and one a document - /// carries anyway (kept by an earlier version) is never written: next to the fresh one it - /// would be a second, and without channels it would list channels that are gone. The - /// identifiers here, 3 and 2, are those of psd-tools' `cmyk-alpha-spot.psd` (Photoshop 24.7). - #[test] - fn a_kept_alpha_identifiers_resource_is_not_written() { - let kept = || (crate::channel_map::ALPHA_IDENTIFIERS, String::new(), std::sync::Arc::new([0, 0, 0, 3, 0, 0, 0, 2].to_vec())); - let mut file = document_to_psd(&spot_and_alpha_document()); - file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS); - file.resources.push(ImageResource::new(kept().0, kept().2.to_vec())); - let mut opened = crate::import("ps.psd", &file.to_bytes().unwrap()).unwrap().document; - assert!(!opened.metadata.psd_resources.iter().any(|(id, ..)| *id == crate::channel_map::ALPHA_IDENTIFIERS)); - opened.metadata.psd_resources.push(kept()); - let again = PsdFile::from_bytes(&crate::export(&opened, "x.psd", &crate::ExportOptions::default()).unwrap().bytes).unwrap(); - assert_eq!(again.resources.iter().filter(|r| r.id == crate::channel_map::ALPHA_IDENTIFIERS).count(), 1); - assert_eq!(alpha_ids(&again), Some(vec![0, 3, 4])); - opened.channels.clear(); - assert_eq!(alpha_ids(&document_to_psd(&opened)), None, "no channels left"); - } - - #[test] - fn group_divider_id_wraps_without_colliding_with_imported_layer_ids() { - let mut doc = document(8, 8); - let mut group = Layer::group("Imported group", vec![Layer::raster("Child", doc.pixel_format())]); - group.psd_id = Some(u32::MAX); - doc.layers.push(group); - - let file = document_to_psd(&doc); - let ids: Vec = file.layers().iter().filter_map(|layer| layer.layer_id()).collect(); - let unique: std::collections::HashSet = ids.iter().copied().collect(); - assert_eq!(ids.len(), 3, "group, child and closing divider"); - assert_eq!(unique.len(), ids.len(), "no generated ID may collide"); - assert!(unique.contains(&u32::MAX), "preserve the imported group ID"); - assert!(unique.contains(&1), "reuse the first unused positive ID on wrap"); - - let encoded = file.to_bytes().unwrap(); - let parsed = PsdFile::from_bytes(&encoded).unwrap(); - let reloaded_ids: std::collections::HashSet = parsed.layers().iter().filter_map(|layer| layer.layer_id()).collect(); - assert_eq!(unique, reloaded_ids); - } - - /// #5068: Photoshop won't open a file whose `Lr32` comes before the `Mt32` marker it keeps for - /// a 32-bit document's merged transparency (verified in Photoshop 2026 on psd-tools' - /// `transparentbg.psd` re-saved both ways). The layer block follows a kept marker. - #[test] - fn layer_block_follows_a_kept_merged_transparency_marker() { - for (depth, key, marker) in [ - (SampleType::F32, *b"Lr32", *b"Mt32"), - (SampleType::U16, *b"Lr16", *b"Mt16"), - (SampleType::F32, *b"Lr32", *b"Mtrn"), - (SampleType::F32, *b"Lr32", *b"MTrn"), - ] { - let mut doc = Document::new("t", photocraft_geom::Size::new(8, 6), ColorMode::Rgb, depth); - let mut s = Surface::new(doc.pixel_format()); - s.fill_rect(photocraft_geom::Rect::new(1, 1, 5, 4), &[0.5, 0.2, 0.9, 1.0]); - doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(s))); - doc.metadata.psd_global_blocks = vec![(*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new())), (*b"8BIM", marker, std::sync::Arc::new(Vec::new()))]; - let saved = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); - let LayerInfoPlacement::GlobalBlock { index, key: written, .. } = saved.layer_info_placement else { panic!("{depth:?}: a global layer block") }; - assert_eq!(written, key); - let at = saved.global_blocks.iter().position(|b| b.key == marker).expect("the marker is kept"); - assert!(at < index, "{depth:?}: {marker:?} at {at}, the layer block at {index}"); - } - // Without a marker the layer block stays first. - let mut doc = Document::new("t", photocraft_geom::Size::new(8, 6), ColorMode::Rgb, SampleType::F32); - doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(Surface::new(doc.pixel_format())))); - doc.metadata.psd_global_blocks = vec![(*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new()))]; - let saved = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); - assert!(matches!(saved.layer_info_placement, LayerInfoPlacement::GlobalBlock { index: 0, .. })); - } - - /// A merged-transparency marker kept from the opened file describes that file's composite. - /// Saved with an opaque composite, it would make the first alpha channel read back as the - /// merged transparency, and the channel would be gone: the save drops it. - #[test] - fn an_opaque_save_drops_a_kept_merged_transparency_marker() { - for (depth, marker) in [(SampleType::U8, *b"MTrn"), (SampleType::U8, *b"Mtrn"), (SampleType::U16, *b"Mt16"), (SampleType::F32, *b"Mt32")] { - let case = format!("{depth:?} {}", String::from_utf8_lossy(&marker)); - let mut doc = Document::new("t", photocraft_geom::Size::new(8, 6), ColorMode::Rgb, depth); - let mut s = Surface::new(doc.pixel_format()); - s.fill_rect(photocraft_geom::Rect::new(0, 0, 8, 6), &[0.5, 0.2, 0.9, 1.0]); - doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(s))); - doc.channels.push(photocraft_doc::AlphaChannel::new("Alpha 1", Surface::new(PixelFormat::GRAY8))); - doc.metadata.psd_global_blocks = vec![(*b"8BIM", marker, std::sync::Arc::new(Vec::new()))]; - let file = document_to_psd(&doc); - assert!(!file.global_blocks.iter().any(TaggedBlock::is_merged_transparency_marker), "{case}"); - assert!(!file.merged_has_alpha(), "{case}"); - let back = crate::import("a.psd", &file.to_bytes().unwrap()).unwrap().document; - let names: Vec<&str> = back.channels.iter().map(|c| c.name.as_str()).collect(); - assert_eq!(names, ["Alpha 1"], "{case}"); - } - } - - #[test] - fn unreadable_lr16_warns_on_import_and_is_not_saved_twice() { - // #2700: a 16-bit file whose Lr16 block claims five layers but holds none. - let mut file = photocraft_psd::testgen::merged_only(Version::Psd, PsdMode::Rgb, 16, Compression::Raw, 8, 6); - file.global_layer_mask = Some(GlobalLayerMask::default()); - file.global_blocks.push(TaggedBlock::new(*b"Lr16", vec![0, 5, 0, 0])); - let imported = crate::import("broken.psd", &file.to_bytes().unwrap()).unwrap(); - assert!(imported.warnings.iter().any(|w| w.contains("Lr16") && w.contains("could not be read")), "{:?}", imported.warnings); - - let saved = PsdFile::from_bytes(&document_to_psd(&imported.document).to_bytes().unwrap()).unwrap(); - let ours = matches!(saved.layer_info_placement, LayerInfoPlacement::GlobalBlock { key, .. } if key == *b"Lr16"); - let kept = saved.global_blocks.iter().filter(|b| b.key == *b"Lr16").count(); - assert_eq!((ours, kept), (true, 0), "exactly one Lr16 block: the document's own layers"); - assert_eq!(saved.layers().len(), 1); - } - - #[test] - fn photo_filter_psd_is_four_byte_aligned_and_round_trips() { - let color = [60000u16, 30000, 0].map(|x| x as f32 / 65535.0); - let adjustment = photocraft_doc::Adjustment::PhotoFilter { color, density: 0.14, preserve_luminosity: true }; - let mut doc = - Document::with_background("Photo Filter PSD", photocraft_geom::Size::new(32, 24), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); - let mut layer = Layer::new("Warming Filter", LayerContent::Adjustment(adjustment.clone())); - doc.layers.push(layer.clone()); - - let assert_phfl = |file: &PsdFile| { - let records = &file.layer_info.as_ref().unwrap().layers; - let data = - records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *b"phfl").map(|b| b.data.as_slice()).expect("Photo Filter adjustment data"); - assert_eq!(data.len(), 20, "PSD layer block length includes four-byte padding"); - assert_eq!(&data[0..2], &[0, 2], "version 2 RGB Photo Filter"); - assert_eq!(&data[17..], &[0, 0, 0], "three padding bytes after the 17-byte payload"); - }; - - let exported = document_to_psd(&doc); - assert_phfl(&exported); - let encoded = exported.to_bytes().unwrap(); - let parsed = PsdFile::from_bytes(&encoded).unwrap(); - assert_phfl(&parsed); - let (restored, _) = crate::psd_import::psd_to_document(&parsed); - assert!(restored.layers.iter().any(|l| l.content == LayerContent::Adjustment(adjustment.clone()))); - - // Importing a legacy 18-byte block must still work; saving it again should repair it - // even when the adjustment values have not changed (normally raw blocks are reused). - let mut legacy = crate::adjust_map::write(&adjustment)[0].1.clone(); - legacy.truncate(18); - layer.psd_blocks = vec![(*b"phfl", std::sync::Arc::new(legacy))]; - doc.layers.pop(); - doc.layers.push(layer); - let repaired = document_to_psd(&doc); - assert_phfl(&repaired); - let repaired_bytes = repaired.to_bytes().unwrap(); - assert_phfl(&PsdFile::from_bytes(&repaired_bytes).unwrap()); - } - - #[test] - fn photo_filter_version_3_is_kept_until_edited() { - // The #3777 block (Photoshop CS2, XYZ colour): saved back byte-exact while unchanged. - let v3 = vec![0, 3, 0, 0, 0x5e, 0x7f, 0, 0, 0x61, 0xaa, 0, 0, 0x0e, 0xf3, 0, 0, 0, 0x3f, 1, 0]; - let adjustment = crate::adjust_map::parse(b"phfl", &v3, None, crate::adjust_map::Channels::Rgb); - let photocraft_doc::Adjustment::PhotoFilter { color, .. } = adjustment else { panic!("{adjustment:?}") }; - let mut doc = - Document::with_background("Photo Filter v3", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); - let mut layer = Layer::new("Photo Filter 1", LayerContent::Adjustment(adjustment.clone())); - layer.psd_blocks = vec![(*b"phfl", std::sync::Arc::new(v3.clone()))]; - doc.layers.push(layer); - let phfl = |doc: &Document| { - let file = PsdFile::from_bytes(&document_to_psd(doc).to_bytes().unwrap()).unwrap(); - let records = &file.layer_info.as_ref().unwrap().layers; - records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *b"phfl").map(|b| b.data.clone()).expect("Photo Filter adjustment data") - }; - assert_eq!(phfl(&doc), v3); - // Once edited it is written as version 2 (RGB), and the colour survives. - let edited = photocraft_doc::Adjustment::PhotoFilter { color, density: 0.5, preserve_luminosity: true }; - if let Some(l) = doc.layers.last_mut() { - l.content = LayerContent::Adjustment(edited.clone()); - } - let saved = phfl(&doc); - assert_eq!(&saved[..2], &[0, 2]); - let reread = crate::adjust_map::parse(b"phfl", &saved, None, crate::adjust_map::Channels::Rgb); - let photocraft_doc::Adjustment::PhotoFilter { color: back, density, .. } = reread else { panic!("{reread:?}") }; - assert!(back.iter().zip(color).all(|(b, c)| (b - c).abs() <= 1.0 / 65535.0), "{back:?} vs {color:?}"); - assert_eq!(density, 0.5); - } - - #[test] - fn light_adjustment_is_kept_verbatim_and_warned() { - // #6542: Photoshop 2026's Light layer is a `brit` block whose `CgEd` descriptor carries - // more than Brightness/Contrast. Synthetic block: the extra key names are placeholders. - use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; - let brit = vec![0, 0, 0xff, 0xfe, 0, 127, 0, 0]; - let d = Descriptor::new("null") - .with("Vrsn", Value::Integer(1)) - .with("Brgh", Value::Integer(0)) - .with("Cntr", Value::Integer(-2)) - .with("Exps", Value::Double(-2.3)) - .with("Hghl", Value::Integer(-64)) - .with("useLegacy", Value::Boolean(false)); - let cged = VersionedDescriptor::new(d).to_bytes(); - let adjustment = crate::adjust_map::parse(b"brit", &brit, Some(&cged), crate::adjust_map::Channels::Rgb); - assert_eq!(adjustment, photocraft_doc::Adjustment::Unsupported { psd_key: "brit".into(), raw: brit.clone().into() }); - let mut doc = Document::with_background("Light", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); - let mut layer = Layer::new("Light 1", LayerContent::Adjustment(adjustment)); - layer.psd_blocks = vec![(*b"brit", std::sync::Arc::new(brit.clone())), (*b"CgEd", std::sync::Arc::new(cged.clone()))]; - doc.layers.push(layer); - let block = |file: &PsdFile, key: &[u8; 4]| { - let records = &file.layer_info.as_ref().unwrap().layers; - records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *key).map(|b| b.data.clone()) - }; - let file = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); - let (restored, warnings) = crate::psd_import::psd_to_document(&file); - assert!(warnings.iter().any(|w| w.contains("\"Light 1\"") && w.contains("Light settings")), "{warnings:?}"); - // Saved again unchanged, both blocks are written back byte for byte. - let again = PsdFile::from_bytes(&document_to_psd(&restored).to_bytes().unwrap()).unwrap(); - assert_eq!(block(&again, b"brit").as_deref(), Some(&brit[..])); - assert_eq!(block(&again, b"CgEd").as_deref(), Some(&cged[..])); - // A plain Brightness/Contrast descriptor still reads as Brightness/Contrast. - let plain = crate::adjust_map::write(&photocraft_doc::Adjustment::BrightnessContrast { brightness: 5.0, contrast: -2.0, legacy: false }); - assert!(!crate::adjust_map::is_extended_brit(Some(&plain[1].1))); - } - - #[test] - fn size_limit_boundary_keeps_limit_and_switches_above_it() { - assert!(!exceeds_psd_size_limit(Some(PSD_MAX_FILE_SIZE))); - assert!(exceeds_psd_size_limit(Some(PSD_MAX_FILE_SIZE + 1))); - assert!(exceeds_psd_size_limit(None)); - } - - #[test] - fn encoded_size_estimator_rejects_arithmetic_overflow() { - assert_eq!(estimate_encoded_size(u64::MAX, 0, 0), None); - assert_eq!(estimate_encoded_size(0, u64::MAX, 0), None); - assert_eq!(estimate_encoded_size(0, 0, u64::MAX), Some(u64::MAX)); - assert!(exceeds_psd_size_limit(estimate_psd_size(&document(u32::MAX, u32::MAX)))); - } - - #[test] - fn large_encoded_size_selects_psb_without_changing_explicit_choice() { - let large = document(30_000, 30_000); - assert!(estimate_psd_size(&large).is_some_and(|size| size > PSD_MAX_FILE_SIZE)); - let large_size_exceeds_limit = psd_size_exceeds_limit(&large); - assert_eq!(psd_version(&large, false, large_size_exceeds_limit), Version::Psb); - - let small = document(1, 1); - let small_size_exceeds_limit = psd_size_exceeds_limit(&small); - assert_eq!(psd_version(&small, false, small_size_exceeds_limit), Version::Psd); - assert_eq!(psd_version(&small, true, small_size_exceeds_limit), Version::Psb); - } - #[test] - fn kept_psb_blocks_are_written_as_8bim_in_a_psd() { - // Photoshop 27.11 refuses a PSD holding `8B64` blocks ("not compatible with this - // version"); they came from re-saving a PSB as PSD with its global FMsk and cinf kept. - let mut doc = document(4, 4); - doc.metadata.psd_global_blocks = vec![ - (*b"8B64", *b"FMsk", std::sync::Arc::new(vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50])), - (*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new())), - ]; - let signatures = |force_psb| { - let opts = PsdExportOptions { force_psb, ..PsdExportOptions::default() }; - let bytes = document_to_psd_with(&doc, &opts).0.to_bytes().unwrap(); - let file = PsdFile::from_bytes(&bytes).unwrap(); - file.global_blocks.iter().map(|b| (b.signature, b.key)).collect::>() - }; - assert_eq!(signatures(false), vec![(*b"8BIM", *b"FMsk"), (*b"8BIM", *b"Patt")]); - assert_eq!(signatures(true), vec![(*b"8B64", *b"FMsk"), (*b"8BIM", *b"Patt")], "a PSB keeps 8B64"); - } - - /// A PSB writes every global block with an 8-byte length as `8B64`, the way Photoshop does: - /// kept from a PSD source, `lnk2`, `pths` and `cinf` arrive as `8BIM`, and with that signature - /// and the PSB's 8-byte length Photoshop 27.11 refused the whole file (#7937). Blocks with a - /// 4-byte length keep `8BIM`, and a PSD keeps `8BIM` throughout. - #[test] - fn psb_writes_long_length_blocks_as_8b64() { - let mut doc = document(4, 4); - doc.metadata.psd_global_blocks = vec![ - (*b"8BIM", *b"cinf", std::sync::Arc::new(vec![0, 0, 0, 16, 0, 0, 0, 0])), - (*b"8BIM", *b"pths", std::sync::Arc::new(vec![0, 0, 0, 16, 0, 0, 0, 0])), - (*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new())), - ]; - let written = |force_psb| { - let opts = PsdExportOptions { force_psb, ..PsdExportOptions::default() }; - let bytes = document_to_psd_with(&doc, &opts).0.to_bytes().unwrap(); - let file = PsdFile::from_bytes(&bytes).unwrap(); - let blocks = file.global_blocks.iter().map(|b| (b.signature, b.key, b.data.len())).collect::>(); - (bytes, blocks) - }; - let (bytes, blocks) = written(true); - assert_eq!(blocks, vec![(*b"8B64", *b"cinf", 8), (*b"8B64", *b"pths", 8), (*b"8BIM", *b"Patt", 0)]); - // On disk: the signature, the key, then the 8-byte length. - let at = bytes.windows(8).position(|w| w == b"8B64cinf").expect("8B64cinf in the file"); - assert_eq!(bytes.get(at + 8..at + 16), Some(&[0u8, 0, 0, 0, 0, 0, 0, 8][..])); - assert!(!bytes.windows(8).any(|w| w == b"8BIMcinf" || w == b"8BIMpths")); - let (_, blocks) = written(false); - assert_eq!(blocks, vec![(*b"8BIM", *b"cinf", 8), (*b"8BIM", *b"pths", 8), (*b"8BIM", *b"Patt", 0)], "a PSD keeps 8BIM"); - } - - /// A layered document with transparency in the merged image and an alpha channel: the name - /// and DisplayInfo resources hold one entry per extra channel, the merged transparency first, - /// as in every file Photoshop opens (one short, Photoshop 27.11 refused the file with "Could - /// not import the clipboard because an unexpected end-of-file was encountered"). The alpha - /// channel keeps its own name and options on the way back. - #[test] - fn alpha_names_count_the_merged_transparency() { - let mut doc = document(8, 6); - let mut layer = Layer::raster("Layer 1", doc.pixel_format()); - layer.surface_mut().unwrap().write_pixel(1, 1, &[1.0, 0.0, 0.0, 1.0]); - doc.layers.push(layer); - let mut a = photocraft_doc::AlphaChannel::new("Alpha 1", photocraft_raster::Surface::new(PixelFormat::GRAY8)); - a.opacity = 0.5; - doc.channels.push(a); - let file = document_to_psd(&doc); - let header_extra = usize::from(file.header.channels) - 3; - let names = |id| file.resources.iter().find(|r| r.id == id).map(|r| r.data.clone()).unwrap(); - let pascal = names(1006); - let (mut count, mut i) = (0, 0); - while i < pascal.len() { - count += 1; - i += 1 + usize::from(pascal[i]); - } - assert_eq!((header_extra, count), (2, 2), "transparency + Alpha 1"); - assert_eq!(names(crate::channel_map::DISPLAY_INFO).len(), 4 + 2 * 13); - let back = crate::import("a.psd", &file.to_bytes().unwrap()).unwrap().document; - assert_eq!(back.channels.len(), 1); - assert_eq!(back.channels[0].name, "Alpha 1"); - assert!((back.channels[0].opacity - 0.5).abs() < 1e-6); - } -} +mod tests; diff --git a/crates/io/src/psd_export/tests.rs b/crates/io/src/psd_export/tests.rs new file mode 100644 index 0000000000..5633e30764 --- /dev/null +++ b/crates/io/src/psd_export/tests.rs @@ -0,0 +1,446 @@ +use super::*; + +fn document(width: u32, height: u32) -> Document { + Document::new("size estimate", photocraft_geom::Size::new(width, height), ColorMode::Rgb, SampleType::U8) +} + +/// Photoshop opens a PSD's bottom layer as its Background only when that layer has no +/// transparency channel (measured on Photoshop 27.11: with the channel written, re-exported +/// files reopened with the Background as an ordinary layer). +#[test] +fn a_background_is_written_without_a_transparency_channel() { + use photocraft_color::Color; + let size = photocraft_geom::Size::new(8, 6); + let mut doc = Document::with_background("bg", size, ColorMode::Rgb, SampleType::U8, Color::rgb(0.2, 0.4, 0.6)); + doc.layers.push(Layer::raster("Layer 1", doc.pixel_format())); + let file = document_to_psd(&doc); + let layers = &file.layer_info.as_ref().unwrap().layers; + let ids = |i: usize| layers[i].channels.iter().map(|c| c.id).collect::>(); + assert_eq!(ids(0), vec![0, 1, 2], "the Background has no -1 channel"); + assert_eq!(layers[0].flags.0, LayerFlags::BIT4_USEFUL | LayerFlags::TRANSPARENCY_PROTECTED, "as Photoshop writes it"); + assert!(ids(1).contains(&-1), "other layers keep their transparency"); + // It comes back as the same locked, opaque Background. + let back = crate::import("bg.psd", &file.to_bytes().unwrap()).unwrap().document; + let bg = &back.layers[0]; + assert!(bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); + assert_eq!(bg.surface().unwrap().read_region(back.bounds()), doc.layers[0].surface().unwrap().read_region(doc.bounds())); + // A bottom layer with transparency (or unlocked) is not a Background. + let mut holey = doc.clone(); + holey.layers[0].surface_mut().unwrap().write_pixel(2, 2, &[0.0, 0.0, 0.0, 0.0]); + assert!(document_to_psd(&holey).layer_info.unwrap().layers[0].channels.iter().any(|c| c.id == -1)); + let mut unlocked = doc.clone(); + unlocked.layers[0].locks.position = false; + assert!(document_to_psd(&unlocked).layer_info.unwrap().layers[0].channels.iter().any(|c| c.id == -1)); +} + +/// A flat 1-bit Bitmap file (no layers) opens in Photoshop as its Background; so does it in +/// PhotoCraft, and it is written back as one (no transparency channel). +#[test] +fn a_flat_bitmap_file_opens_and_saves_as_a_background() { + let file = photocraft_psd::testgen::merged_only(Version::Psd, PsdMode::Bitmap, 1, Compression::Raw, 8, 4); + let doc = crate::import("flat.psd", &file.to_bytes().unwrap()).unwrap().document; + let bg = &doc.layers[0]; + assert!(bg.name == "Background" && bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); + // Bitmap has no layers in Photoshop (#4814): the file is saved flat in Bitmap mode, without + // a layer section, and opens as a Background again. + let out = document_to_psd(&doc); + assert_eq!(out.header.color_mode, PsdMode::Bitmap); + assert!(out.layer_info.as_ref().is_none_or(|li| li.layers.is_empty())); + let back = crate::import("flat.psd", &out.to_bytes().unwrap()).unwrap().document; + let bg = &back.layers[0]; + assert!(back.layers.len() == 1 && bg.name == "Background" && bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); +} + +/// A layered document with a spot and an alpha channel. Each channel holds 100 %, 25 %, 75 % +/// and 0 % in four columns, the layout of the Photoshop spot oracles. +fn spot_and_alpha_document() -> Document { + let mut doc = document(4, 1); + doc.layers.push(Layer::group("Group", vec![Layer::raster("Layer 1", doc.pixel_format())])); + let channel = |name: &str| { + let mut s = Surface::new(PixelFormat::GRAY8); + s.write_interleaved(doc.bounds(), &[255, 64, 191, 0]); + photocraft_doc::AlphaChannel::new(name, s) + }; + let mut spot = channel("Spot Color 1"); + spot.spot = Some((photocraft_doc::Color::rgb(0.0, 0.6, 1.0), 0.0)); + let alpha = channel("Alpha 1"); + doc.channels.extend([spot, alpha]); + doc +} + +/// The extra planes after the colour channels (and the merged transparency) of `file`. +fn extra_planes(file: &PsdFile, count: usize) -> Vec { + let planes = file.decode_merged().unwrap(); + let plane = (file.header.width * file.header.height) as usize * usize::from(file.header.depth / 8); + planes[planes.len() - count * plane..].to_vec() +} + +/// Resource 1053's identifiers. +fn alpha_ids(file: &PsdFile) -> Option> { + file.resource(crate::channel_map::ALPHA_IDENTIFIERS).map(|r| r.data.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes(*c)).collect()) +} + +/// A PSD stores spot ink as Photoshop's own PSDs do (0 = solid ink: the 100, 25, 75 and 0 % +/// columns are 0, 191, 64, 255) and an alpha channel straight (255 = selected). The global +/// layer mask stays empty and flag bit 3 stays on the layers only, not on the group's closing +/// divider: Photoshop opens those as they are, and 509 of the corpus's 721 Photoshop PSDs have +/// an empty mask too. Opening the file gives the same ink back. +#[test] +fn psd_stores_spot_ink_as_photoshop_does() { + let doc = spot_and_alpha_document(); + let file = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); + assert_eq!(extra_planes(&file, 2), [0, 191, 64, 255, 255, 64, 191, 0], "spot, then alpha"); + assert_eq!(file.global_layer_mask.as_ref().map(|m| m.data.len()), Some(0)); + let flags: Vec = file.layers().iter().map(|l| l.flags.0 & LayerFlags::BIT4_USEFUL).collect(); + assert_eq!(flags, [0, LayerFlags::BIT4_USEFUL, LayerFlags::BIT4_USEFUL], "closing divider, layer, group"); + let back = crate::import("spot.psd", &file.to_bytes().unwrap()).unwrap().document; + assert!(back.channels[0].spot.is_some() && back.channels[1].spot.is_none()); + for c in &back.channels { + assert_eq!(c.surface.to_interleaved(back.bounds()), [255, 64, 191, 0], "{}", c.name); + } +} + +/// Resource 1053 numbers the extra channels as Photoshop 27.11 does in a new document: 3, 4, 5 +/// in every colour mode, after 0 for the merged transparency when there is one (its +/// transparent PSD lists `0, 3, 4, 5`). A Quick Mask is an extra channel too. Without extra +/// channels there is none. +#[test] +fn psd_alpha_identifiers_number_the_channels_as_photoshop_does() { + use photocraft_color::Color; + let size = photocraft_geom::Size::new(4, 1); + for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Grayscale, ColorMode::Lab] { + let mut doc = Document::with_background("bg", size, mode, SampleType::U8, Color::rgb(1.0, 1.0, 1.0)); + assert_eq!(alpha_ids(&document_to_psd(&doc)), None, "{mode:?} without channels"); + doc.channels = spot_and_alpha_document().channels; + let file = document_to_psd(&doc); + assert!(!file.merged_has_alpha(), "{mode:?}"); + assert_eq!(alpha_ids(&file), Some(vec![3, 4]), "{mode:?}"); + doc.quick_mask = Some(photocraft_doc::AlphaChannel::new("Quick Mask", Surface::new(PixelFormat::GRAY8))); + assert_eq!(alpha_ids(&document_to_psd(&doc)), Some(vec![3, 4, 5]), "{mode:?} with a Quick Mask"); + } + // The empty layer leaves the composite transparent. + let file = document_to_psd(&spot_and_alpha_document()); + assert!(file.merged_has_alpha()); + assert_eq!(alpha_ids(&file), Some(vec![0, 3, 4])); +} + +/// A save writes one fresh 1053 for the channels the document has. A Photoshop file's own is +/// not kept on open (it would be new metadata after every round trip), and one a document +/// carries anyway (kept by an earlier version) is never written: next to the fresh one it +/// would be a second, and without channels it would list channels that are gone. The +/// identifiers here, 3 and 2, are those of psd-tools' `cmyk-alpha-spot.psd` (Photoshop 24.7). +#[test] +fn a_kept_alpha_identifiers_resource_is_not_written() { + let kept = || (crate::channel_map::ALPHA_IDENTIFIERS, String::new(), std::sync::Arc::new([0, 0, 0, 3, 0, 0, 0, 2].to_vec())); + let mut file = document_to_psd(&spot_and_alpha_document()); + file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS); + file.resources.push(ImageResource::new(kept().0, kept().2.to_vec())); + let mut opened = crate::import("ps.psd", &file.to_bytes().unwrap()).unwrap().document; + assert!(!opened.metadata.psd_resources.iter().any(|(id, ..)| *id == crate::channel_map::ALPHA_IDENTIFIERS)); + opened.metadata.psd_resources.push(kept()); + let again = PsdFile::from_bytes(&crate::export(&opened, "x.psd", &crate::ExportOptions::default()).unwrap().bytes).unwrap(); + assert_eq!(again.resources.iter().filter(|r| r.id == crate::channel_map::ALPHA_IDENTIFIERS).count(), 1); + assert_eq!(alpha_ids(&again), Some(vec![0, 3, 4])); + opened.channels.clear(); + assert_eq!(alpha_ids(&document_to_psd(&opened)), None, "no channels left"); +} + +#[test] +fn group_divider_id_wraps_without_colliding_with_imported_layer_ids() { + let mut doc = document(8, 8); + let mut group = Layer::group("Imported group", vec![Layer::raster("Child", doc.pixel_format())]); + group.psd_id = Some(u32::MAX); + doc.layers.push(group); + + let file = document_to_psd(&doc); + let ids: Vec = file.layers().iter().filter_map(|layer| layer.layer_id()).collect(); + let unique: std::collections::HashSet = ids.iter().copied().collect(); + assert_eq!(ids.len(), 3, "group, child and closing divider"); + assert_eq!(unique.len(), ids.len(), "no generated ID may collide"); + assert!(unique.contains(&u32::MAX), "preserve the imported group ID"); + assert!(unique.contains(&1), "reuse the first unused positive ID on wrap"); + + let encoded = file.to_bytes().unwrap(); + let parsed = PsdFile::from_bytes(&encoded).unwrap(); + let reloaded_ids: std::collections::HashSet = parsed.layers().iter().filter_map(|layer| layer.layer_id()).collect(); + assert_eq!(unique, reloaded_ids); +} + +/// #5068: Photoshop won't open a file whose `Lr32` comes before the `Mt32` marker it keeps for +/// a 32-bit document's merged transparency (verified in Photoshop 2026 on psd-tools' +/// `transparentbg.psd` re-saved both ways). The layer block follows a kept marker. +#[test] +fn layer_block_follows_a_kept_merged_transparency_marker() { + for (depth, key, marker) in [ + (SampleType::F32, *b"Lr32", *b"Mt32"), + (SampleType::U16, *b"Lr16", *b"Mt16"), + (SampleType::F32, *b"Lr32", *b"Mtrn"), + (SampleType::F32, *b"Lr32", *b"MTrn"), + ] { + let mut doc = Document::new("t", photocraft_geom::Size::new(8, 6), ColorMode::Rgb, depth); + let mut s = Surface::new(doc.pixel_format()); + s.fill_rect(photocraft_geom::Rect::new(1, 1, 5, 4), &[0.5, 0.2, 0.9, 1.0]); + doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(s))); + doc.metadata.psd_global_blocks = vec![(*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new())), (*b"8BIM", marker, std::sync::Arc::new(Vec::new()))]; + let saved = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); + let LayerInfoPlacement::GlobalBlock { index, key: written, .. } = saved.layer_info_placement else { panic!("{depth:?}: a global layer block") }; + assert_eq!(written, key); + let at = saved.global_blocks.iter().position(|b| b.key == marker).expect("the marker is kept"); + assert!(at < index, "{depth:?}: {marker:?} at {at}, the layer block at {index}"); + } + // Without a marker the layer block stays first. + let mut doc = Document::new("t", photocraft_geom::Size::new(8, 6), ColorMode::Rgb, SampleType::F32); + doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(Surface::new(doc.pixel_format())))); + doc.metadata.psd_global_blocks = vec![(*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new()))]; + let saved = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); + assert!(matches!(saved.layer_info_placement, LayerInfoPlacement::GlobalBlock { index: 0, .. })); +} + +/// A merged-transparency marker kept from the opened file describes that file's composite. +/// Saved with an opaque composite, it would make the first alpha channel read back as the +/// merged transparency, and the channel would be gone: the save drops it. +#[test] +fn an_opaque_save_drops_a_kept_merged_transparency_marker() { + for (depth, marker) in [(SampleType::U8, *b"MTrn"), (SampleType::U8, *b"Mtrn"), (SampleType::U16, *b"Mt16"), (SampleType::F32, *b"Mt32")] { + let case = format!("{depth:?} {}", String::from_utf8_lossy(&marker)); + let mut doc = Document::new("t", photocraft_geom::Size::new(8, 6), ColorMode::Rgb, depth); + let mut s = Surface::new(doc.pixel_format()); + s.fill_rect(photocraft_geom::Rect::new(0, 0, 8, 6), &[0.5, 0.2, 0.9, 1.0]); + doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(s))); + doc.channels.push(photocraft_doc::AlphaChannel::new("Alpha 1", Surface::new(PixelFormat::GRAY8))); + doc.metadata.psd_global_blocks = vec![(*b"8BIM", marker, std::sync::Arc::new(Vec::new()))]; + let file = document_to_psd(&doc); + assert!(!file.global_blocks.iter().any(TaggedBlock::is_merged_transparency_marker), "{case}"); + assert!(!file.merged_has_alpha(), "{case}"); + let back = crate::import("a.psd", &file.to_bytes().unwrap()).unwrap().document; + let names: Vec<&str> = back.channels.iter().map(|c| c.name.as_str()).collect(); + assert_eq!(names, ["Alpha 1"], "{case}"); + } +} + +#[test] +fn unreadable_lr16_warns_on_import_and_is_not_saved_twice() { + // #2700: a 16-bit file whose Lr16 block claims five layers but holds none. + let mut file = photocraft_psd::testgen::merged_only(Version::Psd, PsdMode::Rgb, 16, Compression::Raw, 8, 6); + file.global_layer_mask = Some(GlobalLayerMask::default()); + file.global_blocks.push(TaggedBlock::new(*b"Lr16", vec![0, 5, 0, 0])); + let imported = crate::import("broken.psd", &file.to_bytes().unwrap()).unwrap(); + assert!(imported.warnings.iter().any(|w| w.contains("Lr16") && w.contains("could not be read")), "{:?}", imported.warnings); + + let saved = PsdFile::from_bytes(&document_to_psd(&imported.document).to_bytes().unwrap()).unwrap(); + let ours = matches!(saved.layer_info_placement, LayerInfoPlacement::GlobalBlock { key, .. } if key == *b"Lr16"); + let kept = saved.global_blocks.iter().filter(|b| b.key == *b"Lr16").count(); + assert_eq!((ours, kept), (true, 0), "exactly one Lr16 block: the document's own layers"); + assert_eq!(saved.layers().len(), 1); +} + +#[test] +fn photo_filter_psd_is_four_byte_aligned_and_round_trips() { + let color = [60000u16, 30000, 0].map(|x| x as f32 / 65535.0); + let adjustment = photocraft_doc::Adjustment::PhotoFilter { color, density: 0.14, preserve_luminosity: true }; + let mut doc = + Document::with_background("Photo Filter PSD", photocraft_geom::Size::new(32, 24), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); + let mut layer = Layer::new("Warming Filter", LayerContent::Adjustment(adjustment.clone())); + doc.layers.push(layer.clone()); + + let assert_phfl = |file: &PsdFile| { + let records = &file.layer_info.as_ref().unwrap().layers; + let data = + records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *b"phfl").map(|b| b.data.as_slice()).expect("Photo Filter adjustment data"); + assert_eq!(data.len(), 20, "PSD layer block length includes four-byte padding"); + assert_eq!(&data[0..2], &[0, 2], "version 2 RGB Photo Filter"); + assert_eq!(&data[17..], &[0, 0, 0], "three padding bytes after the 17-byte payload"); + }; + + let exported = document_to_psd(&doc); + assert_phfl(&exported); + let encoded = exported.to_bytes().unwrap(); + let parsed = PsdFile::from_bytes(&encoded).unwrap(); + assert_phfl(&parsed); + let (restored, _) = crate::psd_import::psd_to_document(&parsed); + assert!(restored.layers.iter().any(|l| l.content == LayerContent::Adjustment(adjustment.clone()))); + + // Importing a legacy 18-byte block must still work; saving it again should repair it + // even when the adjustment values have not changed (normally raw blocks are reused). + let mut legacy = crate::adjust_map::write(&adjustment)[0].1.clone(); + legacy.truncate(18); + layer.psd_blocks = vec![(*b"phfl", std::sync::Arc::new(legacy))]; + doc.layers.pop(); + doc.layers.push(layer); + let repaired = document_to_psd(&doc); + assert_phfl(&repaired); + let repaired_bytes = repaired.to_bytes().unwrap(); + assert_phfl(&PsdFile::from_bytes(&repaired_bytes).unwrap()); +} + +#[test] +fn photo_filter_version_3_is_kept_until_edited() { + // The #3777 block (Photoshop CS2, XYZ colour): saved back byte-exact while unchanged. + let v3 = vec![0, 3, 0, 0, 0x5e, 0x7f, 0, 0, 0x61, 0xaa, 0, 0, 0x0e, 0xf3, 0, 0, 0, 0x3f, 1, 0]; + let adjustment = crate::adjust_map::parse(b"phfl", &v3, None, crate::adjust_map::Channels::Rgb); + let photocraft_doc::Adjustment::PhotoFilter { color, .. } = adjustment else { panic!("{adjustment:?}") }; + let mut doc = + Document::with_background("Photo Filter v3", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); + let mut layer = Layer::new("Photo Filter 1", LayerContent::Adjustment(adjustment.clone())); + layer.psd_blocks = vec![(*b"phfl", std::sync::Arc::new(v3.clone()))]; + doc.layers.push(layer); + let phfl = |doc: &Document| { + let file = PsdFile::from_bytes(&document_to_psd(doc).to_bytes().unwrap()).unwrap(); + let records = &file.layer_info.as_ref().unwrap().layers; + records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *b"phfl").map(|b| b.data.clone()).expect("Photo Filter adjustment data") + }; + assert_eq!(phfl(&doc), v3); + // Once edited it is written as version 2 (RGB), and the colour survives. + let edited = photocraft_doc::Adjustment::PhotoFilter { color, density: 0.5, preserve_luminosity: true }; + if let Some(l) = doc.layers.last_mut() { + l.content = LayerContent::Adjustment(edited.clone()); + } + let saved = phfl(&doc); + assert_eq!(&saved[..2], &[0, 2]); + let reread = crate::adjust_map::parse(b"phfl", &saved, None, crate::adjust_map::Channels::Rgb); + let photocraft_doc::Adjustment::PhotoFilter { color: back, density, .. } = reread else { panic!("{reread:?}") }; + assert!(back.iter().zip(color).all(|(b, c)| (b - c).abs() <= 1.0 / 65535.0), "{back:?} vs {color:?}"); + assert_eq!(density, 0.5); +} + +#[test] +fn light_adjustment_is_kept_verbatim_and_warned() { + // #6542: Photoshop 2026's Light layer is a `brit` block whose `CgEd` descriptor carries + // more than Brightness/Contrast. Synthetic block: the extra key names are placeholders. + use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; + let brit = vec![0, 0, 0xff, 0xfe, 0, 127, 0, 0]; + let d = Descriptor::new("null") + .with("Vrsn", Value::Integer(1)) + .with("Brgh", Value::Integer(0)) + .with("Cntr", Value::Integer(-2)) + .with("Exps", Value::Double(-2.3)) + .with("Hghl", Value::Integer(-64)) + .with("useLegacy", Value::Boolean(false)); + let cged = VersionedDescriptor::new(d).to_bytes(); + let adjustment = crate::adjust_map::parse(b"brit", &brit, Some(&cged), crate::adjust_map::Channels::Rgb); + assert_eq!(adjustment, photocraft_doc::Adjustment::Unsupported { psd_key: "brit".into(), raw: brit.clone().into() }); + let mut doc = Document::with_background("Light", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); + let mut layer = Layer::new("Light 1", LayerContent::Adjustment(adjustment)); + layer.psd_blocks = vec![(*b"brit", std::sync::Arc::new(brit.clone())), (*b"CgEd", std::sync::Arc::new(cged.clone()))]; + doc.layers.push(layer); + let block = |file: &PsdFile, key: &[u8; 4]| { + let records = &file.layer_info.as_ref().unwrap().layers; + records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *key).map(|b| b.data.clone()) + }; + let file = PsdFile::from_bytes(&document_to_psd(&doc).to_bytes().unwrap()).unwrap(); + let (restored, warnings) = crate::psd_import::psd_to_document(&file); + assert!(warnings.iter().any(|w| w.contains("\"Light 1\"") && w.contains("Light settings")), "{warnings:?}"); + // Saved again unchanged, both blocks are written back byte for byte. + let again = PsdFile::from_bytes(&document_to_psd(&restored).to_bytes().unwrap()).unwrap(); + assert_eq!(block(&again, b"brit").as_deref(), Some(&brit[..])); + assert_eq!(block(&again, b"CgEd").as_deref(), Some(&cged[..])); + // A plain Brightness/Contrast descriptor still reads as Brightness/Contrast. + let plain = crate::adjust_map::write(&photocraft_doc::Adjustment::BrightnessContrast { brightness: 5.0, contrast: -2.0, legacy: false }); + assert!(!crate::adjust_map::is_extended_brit(Some(&plain[1].1))); +} + +#[test] +fn size_limit_boundary_keeps_limit_and_switches_above_it() { + assert!(!exceeds_psd_size_limit(Some(PSD_MAX_FILE_SIZE))); + assert!(exceeds_psd_size_limit(Some(PSD_MAX_FILE_SIZE + 1))); + assert!(exceeds_psd_size_limit(None)); +} + +#[test] +fn encoded_size_estimator_rejects_arithmetic_overflow() { + assert_eq!(estimate_encoded_size(u64::MAX, 0, 0), None); + assert_eq!(estimate_encoded_size(0, u64::MAX, 0), None); + assert_eq!(estimate_encoded_size(0, 0, u64::MAX), Some(u64::MAX)); + assert!(exceeds_psd_size_limit(estimate_psd_size(&document(u32::MAX, u32::MAX)))); +} + +#[test] +fn large_encoded_size_selects_psb_without_changing_explicit_choice() { + let large = document(30_000, 30_000); + assert!(estimate_psd_size(&large).is_some_and(|size| size > PSD_MAX_FILE_SIZE)); + let large_size_exceeds_limit = psd_size_exceeds_limit(&large); + assert_eq!(psd_version(&large, false, large_size_exceeds_limit), Version::Psb); + + let small = document(1, 1); + let small_size_exceeds_limit = psd_size_exceeds_limit(&small); + assert_eq!(psd_version(&small, false, small_size_exceeds_limit), Version::Psd); + assert_eq!(psd_version(&small, true, small_size_exceeds_limit), Version::Psb); +} +#[test] +fn kept_psb_blocks_are_written_as_8bim_in_a_psd() { + // Photoshop 27.11 refuses a PSD holding `8B64` blocks ("not compatible with this + // version"); they came from re-saving a PSB as PSD with its global FMsk and cinf kept. + let mut doc = document(4, 4); + doc.metadata.psd_global_blocks = vec![ + (*b"8B64", *b"FMsk", std::sync::Arc::new(vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50])), + (*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new())), + ]; + let signatures = |force_psb| { + let opts = PsdExportOptions { force_psb, ..PsdExportOptions::default() }; + let bytes = document_to_psd_with(&doc, &opts).0.to_bytes().unwrap(); + let file = PsdFile::from_bytes(&bytes).unwrap(); + file.global_blocks.iter().map(|b| (b.signature, b.key)).collect::>() + }; + assert_eq!(signatures(false), vec![(*b"8BIM", *b"FMsk"), (*b"8BIM", *b"Patt")]); + assert_eq!(signatures(true), vec![(*b"8B64", *b"FMsk"), (*b"8BIM", *b"Patt")], "a PSB keeps 8B64"); +} + +/// A PSB writes every global block with an 8-byte length as `8B64`, the way Photoshop does: +/// kept from a PSD source, `lnk2`, `pths` and `cinf` arrive as `8BIM`, and with that signature +/// and the PSB's 8-byte length Photoshop 27.11 refused the whole file (#7937). Blocks with a +/// 4-byte length keep `8BIM`, and a PSD keeps `8BIM` throughout. +#[test] +fn psb_writes_long_length_blocks_as_8b64() { + let mut doc = document(4, 4); + doc.metadata.psd_global_blocks = vec![ + (*b"8BIM", *b"cinf", std::sync::Arc::new(vec![0, 0, 0, 16, 0, 0, 0, 0])), + (*b"8BIM", *b"pths", std::sync::Arc::new(vec![0, 0, 0, 16, 0, 0, 0, 0])), + (*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new())), + ]; + let written = |force_psb| { + let opts = PsdExportOptions { force_psb, ..PsdExportOptions::default() }; + let bytes = document_to_psd_with(&doc, &opts).0.to_bytes().unwrap(); + let file = PsdFile::from_bytes(&bytes).unwrap(); + let blocks = file.global_blocks.iter().map(|b| (b.signature, b.key, b.data.len())).collect::>(); + (bytes, blocks) + }; + let (bytes, blocks) = written(true); + assert_eq!(blocks, vec![(*b"8B64", *b"cinf", 8), (*b"8B64", *b"pths", 8), (*b"8BIM", *b"Patt", 0)]); + // On disk: the signature, the key, then the 8-byte length. + let at = bytes.windows(8).position(|w| w == b"8B64cinf").expect("8B64cinf in the file"); + assert_eq!(bytes.get(at + 8..at + 16), Some(&[0u8, 0, 0, 0, 0, 0, 0, 8][..])); + assert!(!bytes.windows(8).any(|w| w == b"8BIMcinf" || w == b"8BIMpths")); + let (_, blocks) = written(false); + assert_eq!(blocks, vec![(*b"8BIM", *b"cinf", 8), (*b"8BIM", *b"pths", 8), (*b"8BIM", *b"Patt", 0)], "a PSD keeps 8BIM"); +} + +/// A layered document with transparency in the merged image and an alpha channel: the name +/// and DisplayInfo resources hold one entry per extra channel, the merged transparency first, +/// as in every file Photoshop opens (one short, Photoshop 27.11 refused the file with "Could +/// not import the clipboard because an unexpected end-of-file was encountered"). The alpha +/// channel keeps its own name and options on the way back. +#[test] +fn alpha_names_count_the_merged_transparency() { + let mut doc = document(8, 6); + let mut layer = Layer::raster("Layer 1", doc.pixel_format()); + layer.surface_mut().unwrap().write_pixel(1, 1, &[1.0, 0.0, 0.0, 1.0]); + doc.layers.push(layer); + let mut a = photocraft_doc::AlphaChannel::new("Alpha 1", photocraft_raster::Surface::new(PixelFormat::GRAY8)); + a.opacity = 0.5; + doc.channels.push(a); + let file = document_to_psd(&doc); + let header_extra = usize::from(file.header.channels) - 3; + let names = |id| file.resources.iter().find(|r| r.id == id).map(|r| r.data.clone()).unwrap(); + let pascal = names(1006); + let (mut count, mut i) = (0, 0); + while i < pascal.len() { + count += 1; + i += 1 + usize::from(pascal[i]); + } + assert_eq!((header_extra, count), (2, 2), "transparency + Alpha 1"); + assert_eq!(names(crate::channel_map::DISPLAY_INFO).len(), 4 + 2 * 13); + let back = crate::import("a.psd", &file.to_bytes().unwrap()).unwrap().document; + assert_eq!(back.channels.len(), 1); + assert_eq!(back.channels[0].name, "Alpha 1"); + assert!((back.channels[0].opacity - 0.5).abs() < 1e-6); +} From 7c22f7bfe8b6b25da136000563863d27770dc9a0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:50 +0000 Subject: [PATCH 120/259] refactor(io): move svg.rs tests to svg/tests.rs --- crates/io/src/svg.rs | 482 +------------------------------------ crates/io/src/svg/tests.rs | 477 ++++++++++++++++++++++++++++++++++++ 2 files changed, 478 insertions(+), 481 deletions(-) create mode 100644 crates/io/src/svg/tests.rs diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 7ff563d466..98161732de 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -987,484 +987,4 @@ fn knots(path: &tiny_skia::Path) -> Vec { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn sniffing_accepts_svg_and_rejects_other_xml() { - assert!(is_svg(b"")); - assert!(is_svg("\u{feff}\n\n".as_bytes())); - assert!(is_svg(b"")); - assert!(!is_svg(b"")); - assert!(!is_svg(b"\x89PNG\r\n")); - assert!(!is_svg(b"")); - } - - #[test] - fn quadratics_become_cubics_and_closing_merges_the_start_knot() { - let mut pb = tiny_skia::PathBuilder::new(); - pb.move_to(0.0, 0.0); - pb.quad_to(5.0, 10.0, 10.0, 0.0); - pb.line_to(0.0, 0.0); - pb.close(); - pb.move_to(20.0, 20.0); - pb.line_to(30.0, 20.0); - let path = pb.finish().unwrap(); - let sp = knots(&path); - assert_eq!(sp.len(), 2); - assert!(sp[0].closed && !sp[1].closed); - // The explicit line back to the start was merged into the first knot. - assert_eq!(sp[0].knots.len(), 2); - let (a, b) = (&sp[0].knots[0], &sp[0].knots[1]); - assert!((a.out_ctrl.x - 10.0 / 3.0).abs() < 1e-9 && (a.out_ctrl.y - 20.0 / 3.0).abs() < 1e-9); - assert!((b.in_ctrl.x - 20.0 / 3.0).abs() < 1e-9 && (b.in_ctrl.y - 20.0 / 3.0).abs() < 1e-9); - assert_eq!(b.anchor, Point::new(10.0, 0.0)); - assert_eq!(sp[1].knots.len(), 2); - } - - #[test] - fn text_without_any_font_is_reported_not_silently_dropped() { - // No font at all (a bare CI image): usvg drops the while parsing, so nothing - // reaches the conversion; the reader still has to say why the text is missing. - fn no_fonts() -> Arc { - Arc::new(usvg::fontdb::Database::new()) - } - let svg = b"II"; - let parsed = parse_with(svg, no_fonts).unwrap(); - assert!(parsed.fontless_text); - let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); - assert!(r.document.layers.is_empty()); - assert!(r.warnings.iter().any(|w| w.contains("font")), "{:?}", r.warnings); - // A drawing without text never loads or misses fonts. - let parsed = - parse_with(b"", no_fonts).unwrap(); - assert!(!parsed.fontless_text); - let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); - assert!(r.warnings.iter().all(|w| !w.contains("font")), "{:?}", r.warnings); - } - - /// #4806: text placed by a `transform` (Illustrator writes `matrix(1 0 0 1 x y)` on every text - /// element), on the text or on a group around it, lands where resvg draws it. usvg leaves the - /// glyph outlines' absolute transforms at identity, so reading them dropped the transform: the - /// text went off the canvas or kept its untransformed place and size. - /// - /// Shaped with the bundled Inter alone, never a system font: on a machine without fonts (a - /// bare CI image or VM) the test would otherwise have nothing to check, and the drawing and - /// its reference come from the same parse, so both use that face. - #[test] - fn transformed_text_lands_where_resvg_draws_it() { - fn inter() -> Arc { - let mut db = usvg::fontdb::Database::new(); - db.load_font_data(photocraft_text::fonts::INTER_REGULAR.to_vec()); - Arc::new(db) - } - assert!(inter().faces().next().is_some(), "the bundled Inter loads"); - let font = r#"font-size="24" font-family="Inter" fill="black""#; - let cases = [ - format!(r#"IHI"#), - format!(r#"IHI"#), - format!(r#"IHI"#), - format!(r#"IHI"#), - format!(r#"IHI"#), - format!(r#"IHI"#), - ]; - for c in cases { - let svg = format!(r#"{c}"#); - let parsed = parse_with(svg.as_bytes(), inter).unwrap(); - assert!(!parsed.fontless_text, "{c}"); - let mut reference = tiny_skia::Pixmap::new(120, 60).unwrap(); - resvg::render(&parsed.tree, tiny_skia::Transform::default(), &mut reference.as_mut()); - let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); - let [layer] = r.document.layers.as_slice() else { panic!("one text layer, got {}: {c}", r.document.layers.len()) }; - assert!(matches!(layer.content, LayerContent::Group(_)), "text stays outline shapes: {c}"); - let imported = photocraft_compose::flatten(&r.document); - let (mut both, mut either) = (0usize, 0usize); - let (mut a_box, mut b_box) = ([i32::MAX, i32::MAX, i32::MIN, i32::MIN], [i32::MAX, i32::MAX, i32::MIN, i32::MIN]); - let grow = |bx: &mut [i32; 4], x: i32, y: i32| *bx = [bx[0].min(x), bx[1].min(y), bx[2].max(x), bx[3].max(y)]; - for (i, px) in reference.pixels().iter().enumerate() { - let (x, y) = ((i % 120) as i32, (i / 120) as i32); - let (a, b) = (imported.get(x, y)[3] > 0.5, px.alpha() > 127); - if a { - grow(&mut a_box, x, y); - } - if b { - grow(&mut b_box, x, y); - } - both += usize::from(a && b); - either += usize::from(a || b); - } - assert!(either > 50, "resvg draws the text on the canvas: {c}"); - // Same place and size to the pixel; the outlines are filled by a different rasteriser, - // so the edges of thin stems may differ by half a pixel. - assert!(a_box.iter().zip(b_box).all(|(a, b)| (a - b).abs() <= 1), "imported {a_box:?}, resvg {b_box:?}: {c}"); - assert!(both * 10 >= either * 7, "imported glyphs cover what resvg draws ({both} of {either} px): {c}"); - } - } - - /// #4266: a group clipped by one path (the PhotoCraft icon's rounded square) stays editable - /// shapes with the clip as its vector mask, and looks as resvg draws the drawing; a clip of - /// two shapes is still rasterised, with the warning. - #[test] - fn a_single_path_clip_becomes_the_groups_vector_mask() { - let svg = br##" - - - - - "##; - let r = import_svg("t", svg).unwrap(); - assert!(r.warnings.iter().all(|w| !w.contains("clip-path")), "{:?}", r.warnings); - let [group] = r.document.layers.as_slice() else { panic!("one group: {:?}", r.document.layers.len()) }; - let LayerContent::Group(g) = &group.content else { panic!("a group") }; - assert_eq!(g.children.len(), 2); - assert!(g.children.iter().all(|c| matches!(c.content, LayerContent::Shape(_))), "editable shapes"); - let mask = group.vector_mask.as_ref().expect("the clip as a vector mask"); - let xs: Vec = mask.path.subpaths.iter().flat_map(|s| s.knots.iter().map(|k| k.anchor.x)).collect(); - let (lo, hi) = (xs.iter().copied().fold(f64::MAX, f64::min), xs.iter().copied().fold(f64::MIN, f64::max)); - assert!((lo - 12.0).abs() < 1e-3 && (hi - 52.0).abs() < 1e-3, "in the group's space: {lo}..{hi}"); - // Pixel for pixel what resvg draws, but for anti-aliasing along the edges. - let ours = photocraft_compose::flatten(&r.document).to_rgba8().pixels; - let tree = parse(svg).unwrap().tree; - let mut pm = tiny_skia::Pixmap::new(64, 64).unwrap(); - resvg::render(&tree, tiny_skia::Transform::default(), &mut pm.as_mut()); - let theirs: Vec = pm - .pixels() - .iter() - .flat_map(|p| { - let c = p.demultiply(); - [c.red(), c.green(), c.blue(), c.alpha()] - }) - .collect(); - let off = ours.chunks(4).zip(theirs.chunks(4)).filter(|(a, b)| a.iter().zip(*b).any(|(x, y)| x.abs_diff(*y) > 48)).count(); - assert!(off < 64, "{off} pixels differ"); - // The report's file: PhotoCraft's own icon opens without the clip-path warning. - let icon = import_svg("photocraft.svg", include_bytes!("../../../assets/app-icon/photocraft.svg")).unwrap(); - assert!(icon.warnings.iter().all(|w| !w.contains("clip-path")), "{:?}", icon.warnings); - assert!(icon.document.layers.iter().any(|l| l.vector_mask.is_some()), "its rounded square is a vector mask"); - // Two shapes in the clip: rasterised, and said so. - let two = br##" - - "##; - let r = import_svg("t", two).unwrap(); - assert!(r.warnings.iter().any(|w| w.contains("clip-path")), "{:?}", r.warnings); - } - - /// A database with the bundled Inter alone, generics resolved without Fontconfig: none of - /// fontdb's Windows defaults (Arial, Times New Roman, Courier New) is in it. - fn inter_only() -> Arc { - let mut db = usvg::fontdb::Database::new(); - db.load_font_data(include_bytes!("../../../assets/fonts/Inter-Regular.ttf").to_vec()); - resolve_generic_families(&mut db, |_| None); - Arc::new(db) - } - - /// Text asking for fonts that aren't installed (`Arial, Helvetica, sans-serif` on a Linux - /// without them) is set in an installed font, as a browser does, instead of being dropped. - #[test] - fn text_in_missing_fonts_falls_back_to_an_installed_one() { - for family in ["Arial, Helvetica, sans-serif", "Times New Roman", "Courier New, monospace", "cursive", "fantasy"] { - let svg = format!( - "II" - ); - let parsed = parse_with(svg.as_bytes(), inter_only).unwrap(); - assert!(!parsed.fontless_text); - let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); - assert_eq!(r.document.layers.first().map(|l| l.name.as_str()), Some("II"), "{family}: {:?}", r.warnings); - } - } - - /// #9406: a font installed on disk (how the system fonts load) is read once, not once per - /// glyph: fontdb re-reads a file source's whole font on every glyph it outlines, about a - /// millisecond a character. The face text is set in comes from memory, and the outlines - /// match the same font loaded from memory in the first place. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn text_in_a_font_on_disk_is_set_from_memory() { - fn inter_on_disk() -> Arc { - let mut db = usvg::fontdb::Database::new(); - let _ = db.load_font_file(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/Inter-Regular.ttf")); - Arc::new(db) - } - assert!(inter_on_disk().faces().all(|f| matches!(f.source, usvg::fontdb::Source::File(_)))); - let svg = b"IHI"; - let parsed = parse_with(svg, inter_on_disk).unwrap(); - let faces: Vec<_> = parsed.tree.fontdb().faces().map(|f| matches!(f.source, usvg::fontdb::Source::Binary(_))).collect(); - assert_eq!(faces, [true], "the face text was set in is held in memory"); - let on_disk = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); - let in_memory = import_parsed("t", parse_with(svg, inter_only).unwrap(), MAX_GROUP_DEPTH).unwrap(); - assert_eq!(on_disk.document.layers.first().map(|l| l.name.as_str()), Some("IHI")); - let outlines = |r: &ImportResult| { - let groups = r.document.layers.iter().filter_map(|l| if let LayerContent::Group(g) = &l.content { Some(g) } else { None }); - groups - .flat_map(|g| &g.children) - .filter_map(|l| if let LayerContent::Shape(s) = &l.content { Some(s.path.clone()) } else { None }) - .collect::>() - }; - assert!(outlines(&on_disk).iter().any(|p| !p.subpaths.is_empty()), "the text has outlines"); - assert_eq!(outlines(&on_disk), outlines(&in_memory)); - } - - /// A font file that no longer loads (replaced or cut short since fontdb indexed it) keeps its - /// faces in the database and isn't remembered: once the file is whole again, text is set - /// from it. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn a_font_file_gone_bad_since_indexing_is_not_cached() { - use std::sync::atomic::{AtomicBool, Ordering}; - static BAD: AtomicBool = AtomicBool::new(true); - fn indexed_then_overwritten() -> Arc { - let path = std::env::temp_dir().join(format!("photocraft-svg-test-bad-{}.ttf", std::process::id())); - std::fs::write(&path, include_bytes!("../../../assets/fonts/Inter-Regular.ttf")).unwrap(); - let mut db = usvg::fontdb::Database::new(); - db.load_font_file(&path).unwrap(); - if BAD.load(Ordering::SeqCst) { - std::fs::write(&path, b"not a font any more").unwrap(); - } - Arc::new(db) - } - let svg = b"IHI"; - let parsed = parse_with(svg, indexed_then_overwritten).unwrap(); - let sources: Vec<_> = parsed.tree.fontdb().faces().map(|f| matches!(f.source, usvg::fontdb::Source::File(_))).collect(); - assert_eq!(sources, [true], "the face stays in the database, on disk"); - BAD.store(false, Ordering::SeqCst); - let parsed = parse_with(svg, indexed_then_overwritten).unwrap(); - let sources: Vec<_> = parsed.tree.fontdb().faces().map(|f| matches!(f.source, usvg::fontdb::Source::Binary(_))).collect(); - assert_eq!(sources, [true], "the whole file is read into memory now"); - let layers = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap().document.layers; - assert_eq!(layers.first().map(|l| l.name.as_str()), Some("IHI")); - assert!( - layers.iter().any(|l| matches!(&l.content, LayerContent::Group(g) if g.children.iter().any(|c| matches!(&c.content, LayerContent::Shape(s) if !s.path.subpaths.is_empty())))), - "the text has outlines" - ); - } - - /// Imports that miss the cache for the same file at once read it once: every one sets its - /// text from the same bytes, not a copy of its own next to the kept one. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn imports_missing_the_same_font_at_once_share_one_read() { - use std::sync::atomic::{AtomicUsize, Ordering}; - static ROUND: AtomicUsize = AtomicUsize::new(0); - fn fresh_file() -> Arc { - let round = ROUND.load(Ordering::SeqCst); - let path = std::env::temp_dir().join(format!("photocraft-svg-test-shared-{}-{round}.ttf", std::process::id())); - let mut db = usvg::fontdb::Database::new(); - db.load_font_file(&path).unwrap(); - Arc::new(db) - } - let svg = b"IHI"; - for round in 0..5 { - ROUND.store(round, Ordering::SeqCst); - let path = std::env::temp_dir().join(format!("photocraft-svg-test-shared-{}-{round}.ttf", std::process::id())); - std::fs::write(&path, include_bytes!("../../../assets/fonts/Inter-Regular.ttf")).unwrap(); - let start = Arc::new(std::sync::Barrier::new(8)); - let threads: Vec<_> = (0..8) - .map(|_| { - let start = start.clone(); - std::thread::spawn(move || { - start.wait(); - let parsed = parse_with(svg, fresh_file).unwrap(); - let bytes: Vec<_> = parsed - .tree - .fontdb() - .faces() - .filter_map(|f| if let usvg::fontdb::Source::Binary(b) = &f.source { Some(Arc::as_ptr(b).cast::() as usize) } else { None }) - .collect(); - bytes - }) - }) - .collect(); - let bytes: Vec<_> = threads.into_iter().flat_map(|t| t.join().unwrap()).collect(); - assert_eq!(bytes.len(), 8, "every import set its text from memory"); - assert!(bytes.iter().all(|&b| b == bytes[0]), "round {round}: {bytes:x?}"); - let _ = std::fs::remove_file(&path); - } - } - - /// #9406: moving a font collection into memory keeps its faces in their order, so the - /// fallback search for a later text still finds the face it found on disk first. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn a_collection_in_memory_keeps_its_face_order() { - fn collection_on_disk() -> Arc { - // A two-face .ttc of the bundled Inter Regular and SemiBold: the `ttcf` header, then - // each font with its table offsets moved by where it starts. - let fonts: [&[u8]; 2] = [include_bytes!("../../../assets/fonts/Inter-Regular.ttf"), include_bytes!("../../../assets/fonts/Inter-SemiBold.ttf")]; - let mut ttc = b"ttcf������".to_vec(); - let mut start = 20; - let mut body = Vec::new(); - for f in fonts { - ttc.extend_from_slice(&u32::try_from(start).unwrap().to_be_bytes()); - let mut font = f.to_vec(); - for t in 0..usize::from(u16::from_be_bytes([font[4], font[5]])) { - let at = 12 + t * 16 + 8; - let off = u32::from_be_bytes(font[at..at + 4].try_into().unwrap()) + u32::try_from(start).unwrap(); - font[at..at + 4].copy_from_slice(&off.to_be_bytes()); - } - font.resize(font.len().next_multiple_of(4), 0); - start += font.len(); - body.extend(font); - } - ttc.extend(body); - let path = std::env::temp_dir().join(format!("photocraft-svg-test-{}.ttc", std::process::id())); - std::fs::write(&path, ttc).unwrap(); - let mut db = usvg::fontdb::Database::new(); - db.load_font_file(&path).unwrap(); - Arc::new(db) - } - let order = |db: &usvg::fontdb::Database| db.faces().map(|f| (f.index, f.weight.0)).collect::>(); - assert_eq!(order(&collection_on_disk()), [(0, 400), (1, 600)]); - let svg = b"IHI"; - let parsed = parse_with(svg, collection_on_disk).unwrap(); - let db = parsed.tree.fontdb(); - assert!(db.faces().all(|f| matches!(f.source, usvg::fontdb::Source::Binary(_))), "both faces of the file are in memory"); - assert_eq!(order(db), [(0, 400), (1, 600)]); - } - - #[test] - fn generic_families_point_at_installed_fonts() { - use usvg::fontdb::Family; - let db = inter_only(); - for g in [Family::SansSerif, Family::Serif, Family::Monospace, Family::Cursive, Family::Fantasy] { - assert_eq!(db.family_name(&g), "Inter", "{g:?}"); - } - // The system's choice wins when installed; a generic whose font is installed stays. - let mut db = usvg::fontdb::Database::new(); - db.load_font_data(include_bytes!("../../../assets/fonts/Inter-Regular.ttf").to_vec()); - db.load_font_data(include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec()); - db.set_cursive_family("Inter"); - resolve_generic_families(&mut db, |g| Some(if g == "serif" { "JetBrains Mono" } else { "Not Installed" }.to_string())); - assert_eq!(db.family_name(&Family::Serif), "JetBrains Mono"); - assert_eq!(db.family_name(&Family::Monospace), "JetBrains Mono", "the bundled mono stand-in"); - assert_eq!(db.family_name(&Family::SansSerif), "Inter"); - assert_eq!(db.family_name(&Family::Cursive), "Inter"); - // An empty database is left alone. - let mut empty = usvg::fontdb::Database::new(); - resolve_generic_families(&mut empty, |_| Some("Inter".into())); - assert_eq!(empty.family_name(&Family::SansSerif), "Arial"); - } - - #[test] - fn rasterized_groups_stop_at_the_aggregate_pixel_budget() { - let mut svg = String::from(""); - svg.push_str(""); - for i in 0..8 { - svg.push_str(&format!("")); - } - svg.push_str(""); - // Enough for one retained 256×256 RGBA8 surface, not eight of them. - let budget = 256u64 * 256 * 4; - let result = import_parsed_with_budget("budget", parse(svg.as_bytes()).unwrap(), MAX_GROUP_DEPTH, budget).unwrap(); - assert_eq!(result.document.layers.len(), 1, "one U8 surface fills the retained-byte allowance"); - assert_eq!(result.document.layers[0].name, "g0"); - assert!(result.warnings.iter().any(|warning| warning.contains("pixel memory")), "{:?}", result.warnings); - } - - #[test] - fn oversized_raster_does_not_consume_budget_for_later_layers() { - let svg = br##" - - - - - - - - - - - "##; - let result = import_parsed_with_budget("budget", parse(svg).unwrap(), MAX_GROUP_DEPTH, 64 * 64 * 4).unwrap(); - assert_eq!(result.document.layers.len(), 1, "the oversized group must not debit the budget"); - assert_eq!(result.document.layers[0].name, "small"); - assert!(result.warnings.iter().any(|w| w.contains("too large to rasterise")), "{:?}", result.warnings); - assert!(!result.warnings.iter().any(|w| w.contains("pixel memory budget")), "{:?}", result.warnings); - } - - #[test] - fn skipped_expensive_raster_does_not_hide_a_smaller_one() { - let svg = br##" - - - - - - - "##; - let result = import_parsed_with_budget("budget", parse(svg).unwrap(), MAX_GROUP_DEPTH, 32 * 32 * 4).unwrap(); - assert_eq!(result.document.layers.len(), 1); - assert_eq!(result.document.layers[0].name, "small"); - assert!(result.warnings.iter().any(|w| w.contains("some rasterised elements were omitted")), "{:?}", result.warnings); - } - - #[test] - fn huge_drawings_scale_to_the_side_limit() { - let tree = parse(b"").unwrap().tree; - let mut w = Vec::new(); - let cv = canvas(&tree, &mut w); - assert_eq!((cv.size.width, cv.size.height), (MAX_SIDE, MAX_SIDE / 2)); - assert_eq!(w.len(), 1); - } - - #[test] - fn resolve_data_rejects_oversized_and_malformed_embedded_png_and_webp() { - let opt = options(Arc::new(usvg::fontdb::Database::new())); - let resolve = &opt.image_href_resolver.resolve_data; - let img = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, vec![255; 12]).unwrap(); - let valid_png = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); - assert!(resolve("image/png", Arc::new(valid_png.clone()), &opt).is_some()); - assert!(resolve("text/plain", Arc::new(valid_png.clone()), &opt).is_some()); - - let mut huge_png = valid_png; - huge_png[16..20].copy_from_slice(&40_000u32.to_be_bytes()); - huge_png[20..24].copy_from_slice(&40_000u32.to_be_bytes()); - assert!(resolve("image/png", Arc::new(huge_png.clone()), &opt).is_none(), "oversized PNG rejected before decode"); - assert!(resolve("text/plain", Arc::new(huge_png), &opt).is_none(), "oversized mime-less PNG rejected before decode"); - - // Malformed WebP header under image/webp or text/plain must be rejected at the probe step. - let bad_webp = b"RIFF\x10\x00\x00\x00WEBPVP8 ".to_vec(); - assert!(resolve("image/webp", Arc::new(bad_webp.clone()), &opt).is_none()); - assert!(resolve("text/plain", Arc::new(bad_webp), &opt).is_none()); - } - - #[test] - fn jpeg_dimensions_come_from_the_frame_header_and_oversized_jpegs_are_refused() { - // SOI, an APP0 segment of length 4, then SOF0 (length 11): 8 bits, height 40000, width 30000. - let jpeg = |h: u16, w: u16| { - let mut v = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0, 0, 0xFF, 0xC0, 0x00, 0x0B, 8]; - v.extend(h.to_be_bytes()); - v.extend(w.to_be_bytes()); - v.extend([1, 1, 0x11, 0]); - v - }; - assert_eq!(jpeg_dimensions(&jpeg(40_000, 30_000)), Some((30_000, 40_000))); - assert_eq!(jpeg_dimensions(&[0xFF, 0xD8, 0xFF, 0xDA, 0, 2]), None); - assert_eq!(jpeg_dimensions(&[0xFF, 0xD8]), None); - let opt = options(Arc::new(usvg::fontdb::Database::new())); - let resolve = &opt.image_href_resolver.resolve_data; - // 1.2 billion pixels would be 4.8 GB of RGBA before resvg scaled anything down. - assert!(resolve("image/jpeg", Arc::new(jpeg(40_000, 30_000)), &opt).is_none()); - assert!(resolve("text/plain", Arc::new(jpeg(40_000, 30_000)), &opt).is_none()); - } - - #[test] - fn resolve_data_rejects_nested_gzip_and_handles_text_plain_svgz() { - use std::io::Write; - fn gz(bytes: &[u8]) -> Vec { - let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); - e.write_all(bytes).unwrap(); - e.finish().unwrap() - } - let opt = options(Arc::new(usvg::fontdb::Database::new())); - let resolve = &opt.image_href_resolver.resolve_data; - let svg = b""; - let once = gz(svg); - assert!(resolve("image/svg+xml", Arc::new(once.clone()), &opt).is_some()); - assert!(resolve("text/plain", Arc::new(once.clone()), &opt).is_some()); - - // Doubly gzip-compressed payload must be rejected rather than decompressed a second time by usvg. - let twice = gz(&once); - assert!(resolve("image/svg+xml", Arc::new(twice.clone()), &opt).is_none()); - assert!(resolve("text/plain", Arc::new(twice), &opt).is_none()); - } -} +mod tests; diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs new file mode 100644 index 0000000000..7127738daa --- /dev/null +++ b/crates/io/src/svg/tests.rs @@ -0,0 +1,477 @@ +use super::*; + +#[test] +fn sniffing_accepts_svg_and_rejects_other_xml() { + assert!(is_svg(b"")); + assert!(is_svg("\u{feff}\n\n".as_bytes())); + assert!(is_svg(b"")); + assert!(!is_svg(b"")); + assert!(!is_svg(b"\x89PNG\r\n")); + assert!(!is_svg(b"")); +} + +#[test] +fn quadratics_become_cubics_and_closing_merges_the_start_knot() { + let mut pb = tiny_skia::PathBuilder::new(); + pb.move_to(0.0, 0.0); + pb.quad_to(5.0, 10.0, 10.0, 0.0); + pb.line_to(0.0, 0.0); + pb.close(); + pb.move_to(20.0, 20.0); + pb.line_to(30.0, 20.0); + let path = pb.finish().unwrap(); + let sp = knots(&path); + assert_eq!(sp.len(), 2); + assert!(sp[0].closed && !sp[1].closed); + // The explicit line back to the start was merged into the first knot. + assert_eq!(sp[0].knots.len(), 2); + let (a, b) = (&sp[0].knots[0], &sp[0].knots[1]); + assert!((a.out_ctrl.x - 10.0 / 3.0).abs() < 1e-9 && (a.out_ctrl.y - 20.0 / 3.0).abs() < 1e-9); + assert!((b.in_ctrl.x - 20.0 / 3.0).abs() < 1e-9 && (b.in_ctrl.y - 20.0 / 3.0).abs() < 1e-9); + assert_eq!(b.anchor, Point::new(10.0, 0.0)); + assert_eq!(sp[1].knots.len(), 2); +} + +#[test] +fn text_without_any_font_is_reported_not_silently_dropped() { + // No font at all (a bare CI image): usvg drops the while parsing, so nothing + // reaches the conversion; the reader still has to say why the text is missing. + fn no_fonts() -> Arc { + Arc::new(usvg::fontdb::Database::new()) + } + let svg = b"II"; + let parsed = parse_with(svg, no_fonts).unwrap(); + assert!(parsed.fontless_text); + let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); + assert!(r.document.layers.is_empty()); + assert!(r.warnings.iter().any(|w| w.contains("font")), "{:?}", r.warnings); + // A drawing without text never loads or misses fonts. + let parsed = + parse_with(b"", no_fonts).unwrap(); + assert!(!parsed.fontless_text); + let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); + assert!(r.warnings.iter().all(|w| !w.contains("font")), "{:?}", r.warnings); +} + +/// #4806: text placed by a `transform` (Illustrator writes `matrix(1 0 0 1 x y)` on every text +/// element), on the text or on a group around it, lands where resvg draws it. usvg leaves the +/// glyph outlines' absolute transforms at identity, so reading them dropped the transform: the +/// text went off the canvas or kept its untransformed place and size. +/// +/// Shaped with the bundled Inter alone, never a system font: on a machine without fonts (a +/// bare CI image or VM) the test would otherwise have nothing to check, and the drawing and +/// its reference come from the same parse, so both use that face. +#[test] +fn transformed_text_lands_where_resvg_draws_it() { + fn inter() -> Arc { + let mut db = usvg::fontdb::Database::new(); + db.load_font_data(photocraft_text::fonts::INTER_REGULAR.to_vec()); + Arc::new(db) + } + assert!(inter().faces().next().is_some(), "the bundled Inter loads"); + let font = r#"font-size="24" font-family="Inter" fill="black""#; + let cases = [ + format!(r#"IHI"#), + format!(r#"IHI"#), + format!(r#"IHI"#), + format!(r#"IHI"#), + format!(r#"IHI"#), + format!(r#"IHI"#), + ]; + for c in cases { + let svg = format!(r#"{c}"#); + let parsed = parse_with(svg.as_bytes(), inter).unwrap(); + assert!(!parsed.fontless_text, "{c}"); + let mut reference = tiny_skia::Pixmap::new(120, 60).unwrap(); + resvg::render(&parsed.tree, tiny_skia::Transform::default(), &mut reference.as_mut()); + let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); + let [layer] = r.document.layers.as_slice() else { panic!("one text layer, got {}: {c}", r.document.layers.len()) }; + assert!(matches!(layer.content, LayerContent::Group(_)), "text stays outline shapes: {c}"); + let imported = photocraft_compose::flatten(&r.document); + let (mut both, mut either) = (0usize, 0usize); + let (mut a_box, mut b_box) = ([i32::MAX, i32::MAX, i32::MIN, i32::MIN], [i32::MAX, i32::MAX, i32::MIN, i32::MIN]); + let grow = |bx: &mut [i32; 4], x: i32, y: i32| *bx = [bx[0].min(x), bx[1].min(y), bx[2].max(x), bx[3].max(y)]; + for (i, px) in reference.pixels().iter().enumerate() { + let (x, y) = ((i % 120) as i32, (i / 120) as i32); + let (a, b) = (imported.get(x, y)[3] > 0.5, px.alpha() > 127); + if a { + grow(&mut a_box, x, y); + } + if b { + grow(&mut b_box, x, y); + } + both += usize::from(a && b); + either += usize::from(a || b); + } + assert!(either > 50, "resvg draws the text on the canvas: {c}"); + // Same place and size to the pixel; the outlines are filled by a different rasteriser, + // so the edges of thin stems may differ by half a pixel. + assert!(a_box.iter().zip(b_box).all(|(a, b)| (a - b).abs() <= 1), "imported {a_box:?}, resvg {b_box:?}: {c}"); + assert!(both * 10 >= either * 7, "imported glyphs cover what resvg draws ({both} of {either} px): {c}"); + } +} + +/// #4266: a group clipped by one path (the PhotoCraft icon's rounded square) stays editable +/// shapes with the clip as its vector mask, and looks as resvg draws the drawing; a clip of +/// two shapes is still rasterised, with the warning. +#[test] +fn a_single_path_clip_becomes_the_groups_vector_mask() { + let svg = br##" + + + + + "##; + let r = import_svg("t", svg).unwrap(); + assert!(r.warnings.iter().all(|w| !w.contains("clip-path")), "{:?}", r.warnings); + let [group] = r.document.layers.as_slice() else { panic!("one group: {:?}", r.document.layers.len()) }; + let LayerContent::Group(g) = &group.content else { panic!("a group") }; + assert_eq!(g.children.len(), 2); + assert!(g.children.iter().all(|c| matches!(c.content, LayerContent::Shape(_))), "editable shapes"); + let mask = group.vector_mask.as_ref().expect("the clip as a vector mask"); + let xs: Vec = mask.path.subpaths.iter().flat_map(|s| s.knots.iter().map(|k| k.anchor.x)).collect(); + let (lo, hi) = (xs.iter().copied().fold(f64::MAX, f64::min), xs.iter().copied().fold(f64::MIN, f64::max)); + assert!((lo - 12.0).abs() < 1e-3 && (hi - 52.0).abs() < 1e-3, "in the group's space: {lo}..{hi}"); + // Pixel for pixel what resvg draws, but for anti-aliasing along the edges. + let ours = photocraft_compose::flatten(&r.document).to_rgba8().pixels; + let tree = parse(svg).unwrap().tree; + let mut pm = tiny_skia::Pixmap::new(64, 64).unwrap(); + resvg::render(&tree, tiny_skia::Transform::default(), &mut pm.as_mut()); + let theirs: Vec = pm + .pixels() + .iter() + .flat_map(|p| { + let c = p.demultiply(); + [c.red(), c.green(), c.blue(), c.alpha()] + }) + .collect(); + let off = ours.chunks(4).zip(theirs.chunks(4)).filter(|(a, b)| a.iter().zip(*b).any(|(x, y)| x.abs_diff(*y) > 48)).count(); + assert!(off < 64, "{off} pixels differ"); + // The report's file: PhotoCraft's own icon opens without the clip-path warning. + let icon = import_svg("photocraft.svg", include_bytes!("../../../../assets/app-icon/photocraft.svg")).unwrap(); + assert!(icon.warnings.iter().all(|w| !w.contains("clip-path")), "{:?}", icon.warnings); + assert!(icon.document.layers.iter().any(|l| l.vector_mask.is_some()), "its rounded square is a vector mask"); + // Two shapes in the clip: rasterised, and said so. + let two = br##" + + "##; + let r = import_svg("t", two).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("clip-path")), "{:?}", r.warnings); +} + +/// A database with the bundled Inter alone, generics resolved without Fontconfig: none of +/// fontdb's Windows defaults (Arial, Times New Roman, Courier New) is in it. +fn inter_only() -> Arc { + let mut db = usvg::fontdb::Database::new(); + db.load_font_data(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec()); + resolve_generic_families(&mut db, |_| None); + Arc::new(db) +} + +/// Text asking for fonts that aren't installed (`Arial, Helvetica, sans-serif` on a Linux +/// without them) is set in an installed font, as a browser does, instead of being dropped. +#[test] +fn text_in_missing_fonts_falls_back_to_an_installed_one() { + for family in ["Arial, Helvetica, sans-serif", "Times New Roman", "Courier New, monospace", "cursive", "fantasy"] { + let svg = format!( + "II" + ); + let parsed = parse_with(svg.as_bytes(), inter_only).unwrap(); + assert!(!parsed.fontless_text); + let r = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); + assert_eq!(r.document.layers.first().map(|l| l.name.as_str()), Some("II"), "{family}: {:?}", r.warnings); + } +} + +/// #9406: a font installed on disk (how the system fonts load) is read once, not once per +/// glyph: fontdb re-reads a file source's whole font on every glyph it outlines, about a +/// millisecond a character. The face text is set in comes from memory, and the outlines +/// match the same font loaded from memory in the first place. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn text_in_a_font_on_disk_is_set_from_memory() { + fn inter_on_disk() -> Arc { + let mut db = usvg::fontdb::Database::new(); + let _ = db.load_font_file(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/Inter-Regular.ttf")); + Arc::new(db) + } + assert!(inter_on_disk().faces().all(|f| matches!(f.source, usvg::fontdb::Source::File(_)))); + let svg = + b"IHI"; + let parsed = parse_with(svg, inter_on_disk).unwrap(); + let faces: Vec<_> = parsed.tree.fontdb().faces().map(|f| matches!(f.source, usvg::fontdb::Source::Binary(_))).collect(); + assert_eq!(faces, [true], "the face text was set in is held in memory"); + let on_disk = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap(); + let in_memory = import_parsed("t", parse_with(svg, inter_only).unwrap(), MAX_GROUP_DEPTH).unwrap(); + assert_eq!(on_disk.document.layers.first().map(|l| l.name.as_str()), Some("IHI")); + let outlines = |r: &ImportResult| { + let groups = r.document.layers.iter().filter_map(|l| if let LayerContent::Group(g) = &l.content { Some(g) } else { None }); + groups.flat_map(|g| &g.children).filter_map(|l| if let LayerContent::Shape(s) = &l.content { Some(s.path.clone()) } else { None }).collect::>() + }; + assert!(outlines(&on_disk).iter().any(|p| !p.subpaths.is_empty()), "the text has outlines"); + assert_eq!(outlines(&on_disk), outlines(&in_memory)); +} + +/// A font file that no longer loads (replaced or cut short since fontdb indexed it) keeps its +/// faces in the database and isn't remembered: once the file is whole again, text is set +/// from it. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_font_file_gone_bad_since_indexing_is_not_cached() { + use std::sync::atomic::{AtomicBool, Ordering}; + static BAD: AtomicBool = AtomicBool::new(true); + fn indexed_then_overwritten() -> Arc { + let path = std::env::temp_dir().join(format!("photocraft-svg-test-bad-{}.ttf", std::process::id())); + std::fs::write(&path, include_bytes!("../../../../assets/fonts/Inter-Regular.ttf")).unwrap(); + let mut db = usvg::fontdb::Database::new(); + db.load_font_file(&path).unwrap(); + if BAD.load(Ordering::SeqCst) { + std::fs::write(&path, b"not a font any more").unwrap(); + } + Arc::new(db) + } + let svg = b"IHI"; + let parsed = parse_with(svg, indexed_then_overwritten).unwrap(); + let sources: Vec<_> = parsed.tree.fontdb().faces().map(|f| matches!(f.source, usvg::fontdb::Source::File(_))).collect(); + assert_eq!(sources, [true], "the face stays in the database, on disk"); + BAD.store(false, Ordering::SeqCst); + let parsed = parse_with(svg, indexed_then_overwritten).unwrap(); + let sources: Vec<_> = parsed.tree.fontdb().faces().map(|f| matches!(f.source, usvg::fontdb::Source::Binary(_))).collect(); + assert_eq!(sources, [true], "the whole file is read into memory now"); + let layers = import_parsed("t", parsed, MAX_GROUP_DEPTH).unwrap().document.layers; + assert_eq!(layers.first().map(|l| l.name.as_str()), Some("IHI")); + assert!( + layers.iter().any(|l| matches!(&l.content, LayerContent::Group(g) if g.children.iter().any(|c| matches!(&c.content, LayerContent::Shape(s) if !s.path.subpaths.is_empty())))), + "the text has outlines" + ); +} + +/// Imports that miss the cache for the same file at once read it once: every one sets its +/// text from the same bytes, not a copy of its own next to the kept one. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn imports_missing_the_same_font_at_once_share_one_read() { + use std::sync::atomic::{AtomicUsize, Ordering}; + static ROUND: AtomicUsize = AtomicUsize::new(0); + fn fresh_file() -> Arc { + let round = ROUND.load(Ordering::SeqCst); + let path = std::env::temp_dir().join(format!("photocraft-svg-test-shared-{}-{round}.ttf", std::process::id())); + let mut db = usvg::fontdb::Database::new(); + db.load_font_file(&path).unwrap(); + Arc::new(db) + } + let svg = b"IHI"; + for round in 0..5 { + ROUND.store(round, Ordering::SeqCst); + let path = std::env::temp_dir().join(format!("photocraft-svg-test-shared-{}-{round}.ttf", std::process::id())); + std::fs::write(&path, include_bytes!("../../../../assets/fonts/Inter-Regular.ttf")).unwrap(); + let start = Arc::new(std::sync::Barrier::new(8)); + let threads: Vec<_> = (0..8) + .map(|_| { + let start = start.clone(); + std::thread::spawn(move || { + start.wait(); + let parsed = parse_with(svg, fresh_file).unwrap(); + let bytes: Vec<_> = parsed + .tree + .fontdb() + .faces() + .filter_map(|f| if let usvg::fontdb::Source::Binary(b) = &f.source { Some(Arc::as_ptr(b).cast::() as usize) } else { None }) + .collect(); + bytes + }) + }) + .collect(); + let bytes: Vec<_> = threads.into_iter().flat_map(|t| t.join().unwrap()).collect(); + assert_eq!(bytes.len(), 8, "every import set its text from memory"); + assert!(bytes.iter().all(|&b| b == bytes[0]), "round {round}: {bytes:x?}"); + let _ = std::fs::remove_file(&path); + } +} + +/// #9406: moving a font collection into memory keeps its faces in their order, so the +/// fallback search for a later text still finds the face it found on disk first. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_collection_in_memory_keeps_its_face_order() { + fn collection_on_disk() -> Arc { + // A two-face .ttc of the bundled Inter Regular and SemiBold: the `ttcf` header, then + // each font with its table offsets moved by where it starts. + let fonts: [&[u8]; 2] = [include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"), include_bytes!("../../../../assets/fonts/Inter-SemiBold.ttf")]; + let mut ttc = b"ttcf������".to_vec(); + let mut start = 20; + let mut body = Vec::new(); + for f in fonts { + ttc.extend_from_slice(&u32::try_from(start).unwrap().to_be_bytes()); + let mut font = f.to_vec(); + for t in 0..usize::from(u16::from_be_bytes([font[4], font[5]])) { + let at = 12 + t * 16 + 8; + let off = u32::from_be_bytes(font[at..at + 4].try_into().unwrap()) + u32::try_from(start).unwrap(); + font[at..at + 4].copy_from_slice(&off.to_be_bytes()); + } + font.resize(font.len().next_multiple_of(4), 0); + start += font.len(); + body.extend(font); + } + ttc.extend(body); + let path = std::env::temp_dir().join(format!("photocraft-svg-test-{}.ttc", std::process::id())); + std::fs::write(&path, ttc).unwrap(); + let mut db = usvg::fontdb::Database::new(); + db.load_font_file(&path).unwrap(); + Arc::new(db) + } + let order = |db: &usvg::fontdb::Database| db.faces().map(|f| (f.index, f.weight.0)).collect::>(); + assert_eq!(order(&collection_on_disk()), [(0, 400), (1, 600)]); + let svg = b"IHI"; + let parsed = parse_with(svg, collection_on_disk).unwrap(); + let db = parsed.tree.fontdb(); + assert!(db.faces().all(|f| matches!(f.source, usvg::fontdb::Source::Binary(_))), "both faces of the file are in memory"); + assert_eq!(order(db), [(0, 400), (1, 600)]); +} + +#[test] +fn generic_families_point_at_installed_fonts() { + use usvg::fontdb::Family; + let db = inter_only(); + for g in [Family::SansSerif, Family::Serif, Family::Monospace, Family::Cursive, Family::Fantasy] { + assert_eq!(db.family_name(&g), "Inter", "{g:?}"); + } + // The system's choice wins when installed; a generic whose font is installed stays. + let mut db = usvg::fontdb::Database::new(); + db.load_font_data(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").to_vec()); + db.load_font_data(include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec()); + db.set_cursive_family("Inter"); + resolve_generic_families(&mut db, |g| Some(if g == "serif" { "JetBrains Mono" } else { "Not Installed" }.to_string())); + assert_eq!(db.family_name(&Family::Serif), "JetBrains Mono"); + assert_eq!(db.family_name(&Family::Monospace), "JetBrains Mono", "the bundled mono stand-in"); + assert_eq!(db.family_name(&Family::SansSerif), "Inter"); + assert_eq!(db.family_name(&Family::Cursive), "Inter"); + // An empty database is left alone. + let mut empty = usvg::fontdb::Database::new(); + resolve_generic_families(&mut empty, |_| Some("Inter".into())); + assert_eq!(empty.family_name(&Family::SansSerif), "Arial"); +} + +#[test] +fn rasterized_groups_stop_at_the_aggregate_pixel_budget() { + let mut svg = String::from(""); + svg.push_str(""); + for i in 0..8 { + svg.push_str(&format!("")); + } + svg.push_str(""); + // Enough for one retained 256×256 RGBA8 surface, not eight of them. + let budget = 256u64 * 256 * 4; + let result = import_parsed_with_budget("budget", parse(svg.as_bytes()).unwrap(), MAX_GROUP_DEPTH, budget).unwrap(); + assert_eq!(result.document.layers.len(), 1, "one U8 surface fills the retained-byte allowance"); + assert_eq!(result.document.layers[0].name, "g0"); + assert!(result.warnings.iter().any(|warning| warning.contains("pixel memory")), "{:?}", result.warnings); +} + +#[test] +fn oversized_raster_does_not_consume_budget_for_later_layers() { + let svg = br##" + + + + + + + + + + + "##; + let result = import_parsed_with_budget("budget", parse(svg).unwrap(), MAX_GROUP_DEPTH, 64 * 64 * 4).unwrap(); + assert_eq!(result.document.layers.len(), 1, "the oversized group must not debit the budget"); + assert_eq!(result.document.layers[0].name, "small"); + assert!(result.warnings.iter().any(|w| w.contains("too large to rasterise")), "{:?}", result.warnings); + assert!(!result.warnings.iter().any(|w| w.contains("pixel memory budget")), "{:?}", result.warnings); +} + +#[test] +fn skipped_expensive_raster_does_not_hide_a_smaller_one() { + let svg = br##" + + + + + + + "##; + let result = import_parsed_with_budget("budget", parse(svg).unwrap(), MAX_GROUP_DEPTH, 32 * 32 * 4).unwrap(); + assert_eq!(result.document.layers.len(), 1); + assert_eq!(result.document.layers[0].name, "small"); + assert!(result.warnings.iter().any(|w| w.contains("some rasterised elements were omitted")), "{:?}", result.warnings); +} + +#[test] +fn huge_drawings_scale_to_the_side_limit() { + let tree = parse(b"").unwrap().tree; + let mut w = Vec::new(); + let cv = canvas(&tree, &mut w); + assert_eq!((cv.size.width, cv.size.height), (MAX_SIDE, MAX_SIDE / 2)); + assert_eq!(w.len(), 1); +} + +#[test] +fn resolve_data_rejects_oversized_and_malformed_embedded_png_and_webp() { + let opt = options(Arc::new(usvg::fontdb::Database::new())); + let resolve = &opt.image_href_resolver.resolve_data; + let img = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, vec![255; 12]).unwrap(); + let valid_png = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + assert!(resolve("image/png", Arc::new(valid_png.clone()), &opt).is_some()); + assert!(resolve("text/plain", Arc::new(valid_png.clone()), &opt).is_some()); + + let mut huge_png = valid_png; + huge_png[16..20].copy_from_slice(&40_000u32.to_be_bytes()); + huge_png[20..24].copy_from_slice(&40_000u32.to_be_bytes()); + assert!(resolve("image/png", Arc::new(huge_png.clone()), &opt).is_none(), "oversized PNG rejected before decode"); + assert!(resolve("text/plain", Arc::new(huge_png), &opt).is_none(), "oversized mime-less PNG rejected before decode"); + + // Malformed WebP header under image/webp or text/plain must be rejected at the probe step. + let bad_webp = b"RIFF\x10\x00\x00\x00WEBPVP8 ".to_vec(); + assert!(resolve("image/webp", Arc::new(bad_webp.clone()), &opt).is_none()); + assert!(resolve("text/plain", Arc::new(bad_webp), &opt).is_none()); +} + +#[test] +fn jpeg_dimensions_come_from_the_frame_header_and_oversized_jpegs_are_refused() { + // SOI, an APP0 segment of length 4, then SOF0 (length 11): 8 bits, height 40000, width 30000. + let jpeg = |h: u16, w: u16| { + let mut v = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0, 0, 0xFF, 0xC0, 0x00, 0x0B, 8]; + v.extend(h.to_be_bytes()); + v.extend(w.to_be_bytes()); + v.extend([1, 1, 0x11, 0]); + v + }; + assert_eq!(jpeg_dimensions(&jpeg(40_000, 30_000)), Some((30_000, 40_000))); + assert_eq!(jpeg_dimensions(&[0xFF, 0xD8, 0xFF, 0xDA, 0, 2]), None); + assert_eq!(jpeg_dimensions(&[0xFF, 0xD8]), None); + let opt = options(Arc::new(usvg::fontdb::Database::new())); + let resolve = &opt.image_href_resolver.resolve_data; + // 1.2 billion pixels would be 4.8 GB of RGBA before resvg scaled anything down. + assert!(resolve("image/jpeg", Arc::new(jpeg(40_000, 30_000)), &opt).is_none()); + assert!(resolve("text/plain", Arc::new(jpeg(40_000, 30_000)), &opt).is_none()); +} + +#[test] +fn resolve_data_rejects_nested_gzip_and_handles_text_plain_svgz() { + use std::io::Write; + fn gz(bytes: &[u8]) -> Vec { + let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + e.write_all(bytes).unwrap(); + e.finish().unwrap() + } + let opt = options(Arc::new(usvg::fontdb::Database::new())); + let resolve = &opt.image_href_resolver.resolve_data; + let svg = b""; + let once = gz(svg); + assert!(resolve("image/svg+xml", Arc::new(once.clone()), &opt).is_some()); + assert!(resolve("text/plain", Arc::new(once.clone()), &opt).is_some()); + + // Doubly gzip-compressed payload must be rejected rather than decompressed a second time by usvg. + let twice = gz(&once); + assert!(resolve("image/svg+xml", Arc::new(twice.clone()), &opt).is_none()); + assert!(resolve("text/plain", Arc::new(twice), &opt).is_none()); +} From a3f6259491b5de021eeb3a5a3d3e287b55f14244 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:51 +0000 Subject: [PATCH 121/259] refactor(io): move adjust_map.rs tests to adjust_map/tests.rs --- crates/io/src/adjust_map.rs | 606 +----------------------------- crates/io/src/adjust_map/tests.rs | 596 +++++++++++++++++++++++++++++ 2 files changed, 597 insertions(+), 605 deletions(-) create mode 100644 crates/io/src/adjust_map/tests.rs diff --git a/crates/io/src/adjust_map.rs b/crates/io/src/adjust_map.rs index 3a9d18f94e..2cac91c4a0 100644 --- a/crates/io/src/adjust_map.rs +++ b/crates/io/src/adjust_map.rs @@ -843,608 +843,4 @@ pub fn write(adj: &Adjustment) -> Vec<([u8; 4], Vec)> { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn gradient_map_v3_methods_and_smoothness() { - let classic = vec![(0.0, [0.0, 0.0, 1.0]), (1.0, [1.0, 1.0, 0.0])]; - let v1 = write_gradient_map(&classic, false, false); - // Version 3 inserts the interpolation method after reverse/dither. - let v3 = |m: &[u8; 4]| { - let mut v = v1.clone(); - v[1] = 3; - v.splice(4..4, m.iter().copied()); - v - }; - let at_t = |data: &[u8], t: f32| match parse(b"grdm", data, None, Channels::Rgb) { - Adjustment::GradientMap { stops, .. } => { - let i = stops.windows(2).position(|w| w[0].0 <= t && t <= w[1].0).unwrap(); - let (x, y) = (stops[i], stops[i + 1]); - let u = (t - x.0) / (y.0 - x.0).max(1e-6); - std::array::from_fn::(|k| x.1[k] + (y.1[k] - x.1[k]) * u) - } - other => panic!("{other:?}"), - }; - let mid = |data: &[u8]| at_t(data, 0.5); - let c = mid(&v3(b"Gcls")); - assert!((c[0] - 0.5).abs() < 1e-3 && (c[2] - 0.5).abs() < 1e-3, "classic = sRGB lerp {c:?}"); - let p = mid(&v3(b"Perc")); - assert!((p[0] - c[0]).abs() > 0.02, "perceptual differs from classic {p:?}"); - // Smoothness 100 % (4096) bends a three-stop ramp. - let three = vec![(0.0, [0.0; 3]), (0.25, [1.0, 0.0, 0.0]), (0.75, [0.0, 0.0, 1.0]), (1.0, [1.0; 3])]; - let mut smooth = write_gradient_map(&three, false, false); - // v1 header/name/count + colour stops + transparency stops + expansion count. - let at = 48 + three.len() * 20; - smooth[at..at + 2].copy_from_slice(&4096u16.to_be_bytes()); - let (a, b) = (at_t(&write_gradient_map(&three, false, false), 0.4), at_t(&smooth, 0.4)); - assert!((0..3).any(|k| (a[k] - b[k]).abs() > 1e-3), "{a:?} {b:?}"); - // Noise gradients (no colour stops) stay unsupported. - assert!(matches!(parse(b"grdm", &[0, 1, 0, 0, 0, 0, 0, 0, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - } - - #[test] - fn pencil_curves_read_and_write_the_map_form() { - // Photoshop's pencil-drawn curves: map flag 1, then 256 output bytes per channel. - let mut block = vec![1, 0, 1, 0, 0, 0, 0b1111]; - let maps: [Vec; 4] = [ - (0..=255u8).rev().collect(), - (0..=255u8).map(|k| if k < 128 { 0 } else { 255 }).collect(), - (0..=255u8).collect(), - (0..=255u8).map(|k| k / 2).collect(), - ]; - for m in &maps { - block.extend_from_slice(m); - } - let a = parse(b"curv", &block, None, Channels::Rgb); - let Adjustment::Curves { master, per_channel, pencil, .. } = &a else { panic!("{a:?}") }; - assert!(*pencil); - assert_eq!(master.len(), CURVE_MAP_LEN); - assert_eq!((master[0].output, master[255].output), (1.0, 0.0)); - assert_eq!((per_channel[0][127].output, per_channel[0][128].output), (0.0, 1.0)); - assert_eq!(write(&a)[0].1, block); - } - - /// A two-stop `grdm` (version 1) whose stops are the colour structures `a` and `b`. - fn grdm_with(a: (u16, [u16; 4]), b: (u16, [u16; 4])) -> Vec { - let mut v = write_gradient_map(&[(0.0, [0.0; 3]), (1.0, [1.0; 3])], false, false); - // Header 4 + name length 4 + "Custom\0" 14 + stop count 2; 20 bytes per stop. - for (i, (space, c)) in [a, b].into_iter().enumerate() { - let at = 24 + 20 * i + 8; - v[at..at + 2].copy_from_slice(&space.to_be_bytes()); - for (k, x) in c.iter().enumerate() { - v[at + 2 + 2 * k..at + 4 + 2 * k].copy_from_slice(&x.to_be_bytes()); - } - } - v - } - - fn ends(a: &Adjustment) -> ([f32; 3], [f32; 3]) { - match a { - Adjustment::GradientMap { stops, .. } => (stops[0].1, stops[stops.len() - 1].1), - other => panic!("{other:?}"), - } - } - - #[test] - fn gradient_map_stops_in_every_colour_space() { - use photocraft_color::{Color, ColorMode}; - let white_rgb = (0, [65535, 65535, 65535, 0]); - // CMYK, stored inverted: 65535 = no ink. Full K only. - let k_only = grdm_with((2, [65535, 65535, 65535, 0]), white_rgb); - let expected = Color { mode: ColorMode::Cmyk, c: [0.0, 0.0, 0.0, 1.0], alpha: 1.0 }.to_rgb(); - for channels in [Channels::Cmyk, Channels::Rgb, Channels::Lab] { - let a = parse(b"grdm", &k_only, None, channels); - let (first, last) = ends(&a); - assert!(first.iter().zip(expected).all(|(x, y)| (x - y).abs() < 1e-5), "{first:?} vs {expected:?}"); - assert!(first[0] < 0.4 && (first[0] - first[2]).abs() < 0.05, "K-only black is a dark neutral: {first:?}"); - assert_eq!(last, [1.0; 3]); - } - // Lab: L 50, a 0, b 0 is a neutral mid grey; L 100 white. - let lab = parse(b"grdm", &grdm_with((7, [5000, 0, 0, 0]), (7, [10000, 0, 0, 0])), None, Channels::Lab); - let (first, last) = ends(&lab); - assert!(first.iter().all(|v| (v - 0.466).abs() < 0.01), "{first:?}"); - assert!(last.iter().all(|v| *v > 0.99), "{last:?}"); - // Lab with chroma: a = +60 is reddish (a and b are signed hundredths). - let red = parse(b"grdm", &grdm_with((7, [5000, 6000, 0, 0]), white_rgb), None, Channels::Lab); - let (first, _) = ends(&red); - assert!(first[0] > first[1] + 0.2, "{first:?}"); - // Grayscale: 0..10000 is ink coverage (10000 = black). - let gray = parse(b"grdm", &grdm_with((8, [10000, 0, 0, 0]), (8, [0, 0, 0, 0])), None, Channels::Gray); - assert_eq!(ends(&gray), ([0.0; 3], [1.0; 3])); - // HSB: hue 240 degrees (2/3 of 65535), full saturation and brightness = blue. - let hsb = parse(b"grdm", &grdm_with((1, [43690, 65535, 65535, 0]), white_rgb), None, Channels::Rgb); - let (first, _) = ends(&hsb); - assert!(first[0] < 1e-3 && first[1] < 1e-3 && (first[2] - 1.0).abs() < 1e-3, "{first:?}"); - // Book colours and unknown ids are not guessed: the block stays raw. - for space in [3u16, 9, 0xFFFF] { - let d = grdm_with((space, [1, 2, 3, 4]), white_rgb); - assert!(matches!(parse(b"grdm", &d, None, Channels::Rgb), Adjustment::Unsupported { .. }), "space {space}"); - } - // Truncated stops never panic. - for n in 0..k_only.len() { - let _ = parse(b"grdm", &k_only[..n], None, Channels::Cmyk); - } - } - - #[test] - fn gradient_map_reverse_and_dither_keep_the_stops_block() { - let original = grdm_with((2, [65535, 65535, 65535, 0]), (7, [10000, 0, 0, 0])); - let Adjustment::GradientMap { stops, .. } = parse(b"grdm", &original, None, Channels::Cmyk) else { panic!() }; - let mut data = original.clone(); - let target = Adjustment::GradientMap { stops: stops.clone(), reverse: true, dither: true }; - assert!(retarget_gradient_map(&mut data, &target, Channels::Cmyk)); - assert_eq!(&data[2..4], &[1, 1]); - assert_eq!(data[4..], original[4..], "the stops keep their colour spaces"); - assert_eq!(parse(b"grdm", &data, None, Channels::Cmyk), target); - // Edited stops are not patched in. - let mut edited = stops; - edited[0].1 = [0.5; 3]; - let mut data2 = original.clone(); - let target = Adjustment::GradientMap { stops: edited, reverse: false, dither: false }; - assert!(!retarget_gradient_map(&mut data2, &target, Channels::Cmyk)); - assert_eq!(data2, original); - assert!(!retarget_gradient_map(&mut [], &target, Channels::Cmyk)); - assert!(!retarget_gradient_map(&mut data2, &Adjustment::Invert, Channels::Cmyk)); - } - - fn rt(a: Adjustment) { - let blocks = write(&a); - assert!(!blocks.is_empty(), "{a:?}"); - let cged = blocks.iter().find(|b| &b.0 == b"CgEd").map(|b| &b.1[..]); - let back = parse(&blocks[0].0, &blocks[0].1, cged, Channels::Rgb); - assert_eq!(back, a); - } - - /// Photoshop keeps the colorize triplet at byte 4 and the master triplet at byte 10, and fills - /// the inactive one with its defaults: colorize (30, 25, 0), master (0, 0, 0). The colorize hue - /// is stored signed (200 -> -160). - #[test] - fn hue2_writes_each_triplet_in_its_own_slot() { - let triplets = |a: &Adjustment| -> Vec { - let blocks = write(a); - (0..6).map(|i| bei16(&blocks[0].1, 4 + 2 * i).unwrap_or(i16::MIN)).collect() - }; - let on = Adjustment::HueSaturation { hue: 200.0, saturation: 40.0, lightness: 10.0, colorize: true, ranges: HueRange::defaults() }; - assert_eq!(triplets(&on), [-160, 40, 10, 0, 0, 0]); - let off = Adjustment::HueSaturation { hue: -30.0, saturation: 20.0, lightness: 5.0, colorize: false, ranges: HueRange::defaults() }; - assert_eq!(triplets(&off), [30, 25, 0, -30, 20, 5]); - } - - #[test] - fn roundtrips() { - rt(Adjustment::Invert); - rt(Adjustment::Threshold { level: 128.0 / 255.0 }); - rt(Adjustment::Posterize { levels: 4 }); - rt(Adjustment::BrightnessContrast { brightness: 20.0, contrast: -10.0, legacy: false }); - rt(Adjustment::BrightnessContrast { brightness: -150.0, contrast: 100.0, legacy: true }); - rt(Adjustment::HueSaturation { hue: 30.0, saturation: -20.0, lightness: 5.0, colorize: false, ranges: HueRange::defaults() }); - rt(Adjustment::HueSaturation { hue: 200.0, saturation: 50.0, lightness: 0.0, colorize: true, ranges: HueRange::defaults() }); - let mut ranges = HueRange::defaults(); - ranges[0] = HueRange { hue: 15.0, saturation: -40.0, lightness: 10.0, bounds: [-60.0, -20.0, 10.0, 30.0] }; - ranges[4].saturation = 25.0; - rt(Adjustment::HueSaturation { hue: -10.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges }); - rt(Adjustment::Exposure { exposure: 1.5, offset: -0.01, gamma: 0.9 }); - let lc = |a: u16, b: u16| LevelsChannel { in_black: f32::from(a) / 255.0, in_white: f32::from(b) / 255.0, gamma: 1.2, out_black: 0.0, out_white: 1.0 }; - rt(Adjustment::Levels { - master: lc(10, 240), - per_channel: [lc(0, 255), lc(5, 250), lc(20, 200)], - space: ToneSpace::Rgb, - black: LevelsChannel::default(), - }); - let pts = |v: &[(u8, u8)]| v.iter().map(|&(i, o)| CurvePoint { input: f32::from(i) / 255.0, output: f32::from(o) / 255.0 }).collect::>(); - rt(Adjustment::Curves { - master: pts(&[(0, 0), (128, 150), (255, 255)]), - per_channel: [pts(&[(0, 10), (255, 255)]), pts(&[(0, 0), (255, 245)]), pts(&[(0, 0), (64, 32), (255, 255)])], - space: ToneSpace::Rgb, - black: Vec::new(), - pencil: false, - }); - // CMYK ink curves and levels keep their black record. - let ink = Adjustment::Curves { - master: pts(&[(0, 0), (255, 255)]), - per_channel: [pts(&[(0, 0), (255, 255)]), pts(&[(0, 30), (255, 255)]), pts(&[(0, 0), (255, 255)])], - space: ToneSpace::Cmyk, - black: pts(&[(0, 0), (128, 100), (255, 255)]), - pencil: false, - }; - let b = write(&ink); - assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Cmyk), ink); - let inkl = Adjustment::Levels { master: lc(0, 255), per_channel: [lc(0, 255), lc(5, 250), lc(0, 255)], space: ToneSpace::Cmyk, black: lc(30, 255) }; - let b = write(&inkl); - assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Cmyk), inkl); - rt(Adjustment::Unsupported { psd_key: "selc".into(), raw: vec![1, 2, 3].into() }); - rt(Adjustment::GradientMap { stops: vec![(0.0, [0.0, 0.0, 0.0]), (0.5, [1.0, 0.0, 0.0]), (1.0, [1.0, 1.0, 1.0])], reverse: true, dither: false }); - rt(Adjustment::GradientMap { stops: vec![(0.0, [0.0, 0.0, 0.0]), (1.0, [1.0, 1.0, 1.0])], reverse: false, dither: true }); - rt(Adjustment::SelectiveColor { relative: true, adjustments: std::array::from_fn(|r| [r as f32 * 10.0 - 40.0, 5.0, -100.0, 100.0]) }); - rt(Adjustment::SelectiveColor { relative: false, adjustments: [[0.0; 4]; 9] }); - rt(Adjustment::Vibrance { vibrance: 35.0, saturation: -12.0 }); - rt(Adjustment::Vibrance { vibrance: 0.0, saturation: 0.0 }); - rt(Adjustment::ColorBalance { shadows: [20.0, -10.0, 5.0], midtones: [-15.0, 10.0, 30.0], highlights: [0.0, 5.0, -100.0], preserve_luminosity: true }); - rt(Adjustment::ColorBalance { shadows: [0.0; 3], midtones: [100.0, 0.0, 0.0], highlights: [0.0; 3], preserve_luminosity: false }); - rt(Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None }); - rt(Adjustment::BlackWhite { weights: [-200.0, 300.0, 0.0, 10.0, 90.0, 30.0], tint: Some([0.9, 0.7, 0.5]) }); - let q = |v: u16| f32::from(v) / 65535.0; - rt(Adjustment::PhotoFilter { color: [q(60000), q(30000), q(0)], density: 0.25, preserve_luminosity: true }); - rt(Adjustment::PhotoFilter { color: [q(0), q(40000), q(65535)], density: 1.0, preserve_luminosity: false }); - rt(Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false }); - rt(Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.1], [0.0, 1.0, 0.0, 0.0], [-2.0, 0.0, 2.0, 0.0]], monochrome: true }); - let id = photocraft_cms::lutfile::LutFile::identity(5); - rt(Adjustment::ColorLookup { name: "Look.cube".into(), lut: Some(std::sync::Arc::new(id.data)), size: 5, tetrahedral: false, dither: true }); - } - - #[test] - fn selective_color_synthetic_block() { - // Absolute; reds = (+10, -20, +30, -40), blacks = (0, 0, 0, 25). - let mut d = vec![0, 1, 0, 1]; - d.extend([0u8; 8]); - for r in 0..9 { - let rec: [i16; 4] = match r { - 0 => [10, -20, 30, -40], - 8 => [0, 0, 0, 25], - _ => [0; 4], - }; - for x in rec { - d.extend(x.to_be_bytes()); - } - } - let a = parse(b"selc", &d, None, Channels::Rgb); - let Adjustment::SelectiveColor { relative, adjustments } = &a else { panic!("{a:?}") }; - assert!(!relative); - assert_eq!(adjustments[0], [10.0, -20.0, 30.0, -40.0]); - assert_eq!(adjustments[8], [0.0, 0.0, 0.0, 25.0]); - // Written back byte-exact. - assert_eq!(write(&a)[0].1, d); - } - - #[test] - fn color_lookup_synthetic_block() { - let cube = b"TITLE \"t\"\nLUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n"; - let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) }; - let desc = Descriptor::new("null") - .with("lookupType", en("colorLookupType", "3DLUT")) - .with("NM ", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul("Id"))) - .with("Dthr", Value::Boolean(true)) - .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE")) - .with("LUT3DFileData", Value::RawData(cube.to_vec())); - let mut d = vec![0, 1]; - d.extend(VersionedDescriptor::new(desc).to_bytes()); - let a = parse(b"clrL", &d, None, Channels::Rgb); - let Adjustment::ColorLookup { name, lut: Some(t), size: 2, dither: true, .. } = &a else { panic!("{a:?}") }; - assert_eq!(name, "Id"); - assert_eq!(&t[..6], &[0.0, 0.0, 0.0, 1.0, 0.0, 0.0]); - // A profile-based lookup (no table) is preserved raw. - let mut p = vec![0, 1]; - p.extend(VersionedDescriptor::new(Descriptor::new("null").with("lookupType", en("colorLookupType", "abstractProfile"))).to_bytes()); - assert!(matches!(parse(b"clrL", &p, None, Channels::Rgb), Adjustment::Unsupported { .. })); - // Each way a lookup can't be read has a reason for the import warning (#1763). - assert_eq!(unreadable_reason(b"clrL", &d), None); - assert!(unreadable_reason(b"clrL", &p).unwrap().contains("colour profile")); - assert!(unreadable_reason(b"clrL", &[0]).unwrap().contains("truncated")); - assert!(unreadable_reason(b"clrL", &[0, 2, 0, 0]).unwrap().contains("version 2")); - assert!(unreadable_reason(b"clrL", &[0, 1, 9]).unwrap().contains("unreadable settings")); - let bad = Descriptor::new("null").with("LUTFormat", en("LUTFormatType", "LUTFormat3DL")).with("LUT3DFileData", Value::RawData(b"not a lut".to_vec())); - let mut b = vec![0, 1]; - b.extend(VersionedDescriptor::new(bad).to_bytes()); - assert!(matches!(parse(b"clrL", &b, None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(unreadable_reason(b"clrL", &b).unwrap().contains("3DL LUT can't be read"), "{:?}", unreadable_reason(b"clrL", &b)); - assert_eq!(label(b"clrL"), "Color Lookup"); - assert!(matches!(parse(b"clrL", &[0, 1, 9], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"selc", &[0, 1, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - } - - fn cube_lookup_block(cube: &[u8]) -> Vec { - let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) }; - let desc = Descriptor::new("null") - .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE")) - .with("LUT3DFileName", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul("domain.cube"))) - .with("LUT3DFileData", Value::RawData(cube.to_vec())); - let mut block = vec![0, 1]; - block.extend(VersionedDescriptor::new(desc).to_bytes()); - block - } - - fn identity_cube(domain: &str) -> Vec { - format!("{domain}LUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n").into_bytes() - } - - #[test] - fn color_lookup_custom_domains_are_kept_unsupported() { - let domains = ["DOMAIN_MIN 0 0 0\nDOMAIN_MAX 0.5 0.5 0.5\n", "DOMAIN_MIN 0 0.25 0\nDOMAIN_MAX 1 0.75 1\n", "LUT_3D_INPUT_RANGE 0 0.5\n"]; - for domain in domains { - let raw = cube_lookup_block(&identity_cube(domain)); - let Adjustment::Unsupported { psd_key, raw: kept } = parse(b"clrL", &raw, None, Channels::Rgb) else { - panic!("custom LUT domain was applied instead of kept unsupported: {domain}") - }; - assert_eq!(psd_key, "clrL"); - assert_eq!(*kept, *raw); - let reason = unreadable_reason(b"clrL", &raw).expect("custom domain has an explanation"); - assert!(reason.contains("DOMAIN_MIN") && reason.contains("DOMAIN_MAX"), "{reason}"); - assert!(reason.to_ascii_lowercase().contains("not supported"), "{reason}"); - } - } - - #[test] - fn color_lookup_default_domains_stay_supported() { - for domain in ["", "DOMAIN_MIN 0 0 0\nDOMAIN_MAX 1 1 1\n"] { - let raw = cube_lookup_block(&identity_cube(domain)); - assert!(matches!(parse(b"clrL", &raw, None, Channels::Rgb), Adjustment::ColorLookup { size: 2, .. })); - assert_eq!(unreadable_reason(b"clrL", &raw), None); - } - } - - #[test] - fn malformed_falls_back_to_unsupported() { - assert!(matches!(parse(b"levl", &[0, 2, 1], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"curv", &[0, 0, 9], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"thrs", &[], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"blnc", &[0; 18], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"vibA", &[0, 0, 0, 15, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"blwh", &[], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"mixr", &[0, 2, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - // A CMYK mixer (black source used) stays raw in CMYK documents; our own RGB layout maps. - let mut cmyk = i16s(&[1, 0]); - for r in 0..4 { - cmyk.extend(i16s(&std::array::from_fn::(|k| if k == r { 100 } else { 0 }))); - } - assert!(matches!(parse(b"mixr", &cmyk, None, Channels::Cmyk), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"mixr", &cmyk, None, Channels::Other), Adjustment::Unsupported { .. })); - let ours = write(&Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: false }); - assert!(matches!(parse(b"mixr", &ours[0].1, None, Channels::Cmyk), Adjustment::ChannelMixer { .. })); - assert!(matches!(parse(b"mixr", &ours[0].1, None, Channels::Other), Adjustment::ChannelMixer { .. })); - assert!(matches!(parse(b"mixr", &[0, 1, 0, 0, 0, 100], None, Channels::Rgb), Adjustment::Unsupported { .. })); - // Photo Filter: unknown version, HSB colour space, out-of-range version-3 XYZ, truncated. - assert!(matches!(parse(b"phfl", &[0, 4, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - assert!(matches!(parse(b"phfl", &[0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 1], None, Channels::Rgb), Adjustment::Unsupported { .. })); - for bad in [[200_000u32, 0, 0], [0, u32::MAX, 0]] { - let mut xyz = vec![0, 3]; - for x in bad { - xyz.extend(x.to_be_bytes()); - } - xyz.extend([0, 0, 0, 25, 1]); - assert!(matches!(parse(b"phfl", &xyz, None, Channels::Rgb), Adjustment::Unsupported { .. })); - } - assert!(matches!(parse(b"phfl", &[0, 2, 0, 0, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); - // Arbitrary bytes never panic, whatever the key. - for key in ADJUSTMENT_KEYS { - for len in 0..64usize { - let d: Vec = (0..len).map(|i| (i * 37 + len) as u8).collect(); - let _ = parse(key, &d, Some(&d), Channels::Rgb); - let _ = parse(key, &d, None, Channels::Other); - } - } - } - - fn i16s(v: &[i16]) -> Vec { - v.iter().flat_map(|x| x.to_be_bytes()).collect() - } - - /// Hand-built blocks laid out per the Adobe spec (no file written by Photoshop involved). - #[test] - fn color_balance_golden_block() { - let mut d = i16s(&[-30, 20, 0, 10, -5, 100, 0, 0, -100]); - d.extend([1, 0]); - let a = parse(b"blnc", &d, None, Channels::Rgb); - assert_eq!( - a, - Adjustment::ColorBalance { shadows: [-30.0, 20.0, 0.0], midtones: [10.0, -5.0, 100.0], highlights: [0.0, 0.0, -100.0], preserve_luminosity: true } - ); - assert_eq!(write(&a), vec![(*b"blnc", d.clone())]); - // The 19-byte form (no trailing pad) parses the same. - assert_eq!(parse(b"blnc", &d[..19], None, Channels::Rgb), a); - } - - #[test] - fn photo_filter_golden_blocks() { - // Version 2, RGB colour structure (65535, 32768, 0), density 40 %, preserve luminosity. - let mut v2 = i16s(&[2, 0]); - v2.extend([0xff, 0xff, 0x80, 0x00, 0, 0, 0, 0]); - v2.extend(40u32.to_be_bytes()); - v2.extend([1, 0, 0, 0]); - assert_eq!(v2.len(), 20, "Photo Filter must occupy 20 bytes"); - assert_eq!(&v2[17..], &[0, 0, 0], "padding is included inside the block length"); - let a = parse(b"phfl", &v2, None, Channels::Rgb); - let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = a else { panic!("{a:?}") }; - assert_eq!(color, [1.0, 32768.0 / 65535.0, 0.0]); - assert_eq!(density, 0.4); - assert_eq!(write(&a)[0].1, v2, "version 2 RGB is written back byte-exact"); - // Older PhotoCraft files used only one padding byte (18 bytes); keep importing them, - // but never produce that Photoshop-incompatible length again. - assert_eq!(parse(b"phfl", &v2[..18], None, Channels::Rgb), a); - for preserve_luminosity in [false, true] { - for density in [0.0, 0.14, 1.0] { - let adjustment = Adjustment::PhotoFilter { color: [0.8, 0.4, 0.2], density, preserve_luminosity }; - let blocks = write(&adjustment); - assert_eq!(blocks.len(), 1); - assert_eq!(blocks[0].0, *b"phfl"); - assert_eq!(blocks[0].1.len(), 20); - assert_eq!(&blocks[0].1[17..], &[0, 0, 0]); - let Adjustment::PhotoFilter { color, density: read_density, preserve_luminosity: read_preserve } = - parse(b"phfl", &blocks[0].1, None, Channels::Rgb) - else { - panic!("written phfl must parse") - }; - assert!(color.iter().zip([0.8, 0.4, 0.2]).all(|(got, expected)| (got - expected).abs() <= 1.0 / 65535.0)); - assert!((read_density - density).abs() < 0.00001); - assert_eq!(read_preserve, preserve_luminosity); - } - } - // Version 2, Lab colour structure: L 50, a 0, b 0 is mid gray. - let mut lab = i16s(&[2, 7, 5000, 0, 0, 0]); - lab.extend(25u32.to_be_bytes()); - lab.push(0); - let Adjustment::PhotoFilter { color, density, preserve_luminosity: false } = parse(b"phfl", &lab, None, Channels::Rgb) else { panic!() }; - assert!(color.iter().all(|c| (c - 0.466).abs() < 0.01), "{color:?}"); - assert_eq!(density, 0.25); - // Version 3: XYZ relative to the D50 white, 1.0 = 32768. White is (32768, 32768, 32768). - let v3 = phfl_v3([32768, 32768, 32768], 100, true); - let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = parse(b"phfl", &v3, None, Channels::Rgb) else { panic!() }; - assert!(color.iter().all(|c| (c - 1.0).abs() < 0.005), "{color:?}"); - assert_eq!(density, 1.0); - // Photoshop's Warming Filter (85) preset, sRGB #EC8A00: the CS2 file of #4940 stores it - // relative to the D50 white as (15548, 12029, 0). - let Adjustment::PhotoFilter { color, density, preserve_luminosity: false } = - parse(b"phfl", &phfl_v3([15548, 12029, 0], 25, false), None, Channels::Rgb) - else { - panic!() - }; - let expected = [0xecu8, 0x8a, 0x00].map(|v| f32::from(v) / 255.0); - assert!(color.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{color:?}"); - assert_eq!(density, 0.25); - // The block from #3777 (Photoshop CS2): the Yellow filter preset, #F9E31C, density 63 %. - let issue = [0, 3, 0, 0, 0x5e, 0x7f, 0, 0, 0x61, 0xaa, 0, 0, 0x0e, 0xf3, 0, 0, 0, 0x3f, 1, 0]; - let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = parse(b"phfl", &issue, None, Channels::Rgb) else { panic!() }; - let expected = [0xf9u8, 0xe3, 0x1c].map(|v| f32::from(v) / 255.0); - assert!(color.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{color:?}"); - assert_eq!(density, 0.63); - // Cooling Filter (82) from #4940: a deep blue outside sRGB; its Z stays under the 2.0 - // garbage guard and the colour clamps to (0, 181, 255). - let Adjustment::PhotoFilter { color: cooling, density, preserve_luminosity: true } = - parse(b"phfl", &phfl_v3([5327, 9584, 65357], 72, true), None, Channels::Rgb) - else { - panic!("Cooling Filter (82) must parse") - }; - let expected = [0u8, 181, 255].map(|v| f32::from(v) / 255.0); - assert!(cooling.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{cooling:?}"); - assert_eq!(density, 0.72); - // The 19-byte form (no trailing pad) parses the same. - assert_eq!(parse(b"phfl", &issue[..19], None, Channels::Rgb), parse(b"phfl", &issue, None, Channels::Rgb)); - // Version 3 is read, never written: an edited filter is saved as version 2 and keeps its colour. - let a = parse(b"phfl", &issue, None, Channels::Rgb); - let w = write(&a); - assert_eq!(&w[0].1[..2], &[0, 2]); - let Adjustment::PhotoFilter { color: back, .. } = parse(b"phfl", &w[0].1, None, Channels::Rgb) else { panic!() }; - assert!(back.iter().zip(color).all(|(b, c)| (b - c).abs() <= 1.0 / 65535.0)); - } - - /// A version 3 Photo Filter block: version, three u32 XYZ components, density, flag, pad. - fn phfl_v3(xyz: [u32; 3], density: u32, preserve_luminosity: bool) -> Vec { - let mut d = vec![0, 3]; - for x in xyz { - d.extend(x.to_be_bytes()); - } - d.extend(density.to_be_bytes()); - d.extend([u8::from(preserve_luminosity), 0]); - d - } - - #[test] - fn channel_mixer_golden_blocks() { - // RGB: red = 100 % R + 20 % const; green = 50 % R + 50 % G; blue = -50 % G + 150 % B - 10 % const. - let mut d = i16s(&[1, 0]); - d.extend(i16s(&[100, 0, 0, 0, 20, 50, 50, 0, 0, 0, 0, -50, 150, 0, -10])); - let a = parse(b"mixr", &d, None, Channels::Rgb); - assert_eq!(a, Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.2], [0.5, 0.5, 0.0, 0.0], [0.0, -0.5, 1.5, -0.1]], monochrome: false }); - // Written with the trailing gray record (a copy of the first row). - let w = write(&a); - assert_eq!(w[0].1[..d.len()], d[..]); - assert_eq!(w[0].1[d.len()..], i16s(&[100, 0, 0, 0, 20])[..]); - // Monochrome with only the gray record: 30/59/11. - let mut m = i16s(&[1, 1]); - m.extend(i16s(&[30, 59, 11, 0, 0])); - let Adjustment::ChannelMixer { matrix, monochrome: true } = parse(b"mixr", &m, None, Channels::Rgb) else { panic!() }; - assert_eq!(matrix[0], [0.3, 0.59, 0.11, 0.0]); - } - - fn vdesc(d: Descriptor) -> Vec { - VersionedDescriptor::new(d).to_bytes() - } - - #[test] - fn vibrance_golden_block() { - let d = vdesc(Descriptor::new("null").with("vibrance", Value::Integer(-40)).with("Strt", Value::Integer(25))); - assert_eq!(&d[..4], &[0, 0, 0, 16], "descriptor version 16"); - assert_eq!(parse(b"vibA", &d, None, Channels::Rgb), Adjustment::Vibrance { vibrance: -40.0, saturation: 25.0 }); - // Photoshop omits zero values. - let only = vdesc(Descriptor::new("null").with("Strt", Value::Integer(10))); - assert_eq!(parse(b"vibA", &only, None, Channels::Rgb), Adjustment::Vibrance { vibrance: 0.0, saturation: 10.0 }); - // Other descriptor versions are rejected (kept raw). - let mut v = d.clone(); - v[3] = 17; - assert!(matches!(parse(b"vibA", &v, None, Channels::Rgb), Adjustment::Unsupported { .. })); - } - - #[test] - fn black_white_golden_block() { - let tint = Descriptor::new("RGBC").with("Rd ", Value::Double(255.0)).with("Grn ", Value::Double(127.5)).with("Bl ", Value::Double(0.0)); - let mut desc = Descriptor::new("null"); - for (k, w) in BW_KEYS.iter().zip([10, 20, 30, 40, 50, 60]) { - desc = desc.with(k, Value::Integer(w)); - } - let d = vdesc( - desc.clone().with("useTint", Value::Boolean(true)).with("tintColor", Value::Descriptor(tint.clone())).with("bwPresetKind", Value::Integer(1)), - ); - let a = parse(b"blwh", &d, None, Channels::Rgb); - assert_eq!(a, Adjustment::BlackWhite { weights: [10.0, 20.0, 30.0, 40.0, 50.0, 60.0], tint: Some([1.0, 0.5, 0.0]) }); - // useTint off: no tint, even with a stored colour. - let off = vdesc(desc.with("useTint", Value::Boolean(false)).with("tintColor", Value::Descriptor(tint))); - assert!(matches!(parse(b"blwh", &off, None, Channels::Rgb), Adjustment::BlackWhite { tint: None, .. })); - // Missing weights take Photoshop's defaults. - let empty = vdesc(Descriptor::new("null")); - assert_eq!(parse(b"blwh", &empty, None, Channels::Rgb), Adjustment::BlackWhite { weights: BW_DEFAULT, tint: None }); - } - - #[test] - fn degenerate_adjustments_still_get_an_encoding() { - // Gradient maps with fewer than two stops render as gray (none) or one colour. - for (stops, want) in - [(vec![], vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]), (vec![(0.3, [0.2, 0.4, 0.6])], vec![(0.0, [0.2, 0.4, 0.6]), (1.0, [0.2, 0.4, 0.6])])] - { - let b = write(&Adjustment::GradientMap { stops, reverse: true, dither: false }); - let back = parse(&b[0].0, &b[0].1, None, Channels::Rgb); - let Adjustment::GradientMap { stops, reverse: true, .. } = back else { panic!("{back:?}") }; - assert_eq!(stops.len(), want.len()); - for (s, w) in stops.iter().zip(&want) { - assert!((s.0 - w.0).abs() < 1e-6 && (0..3).all(|k| (s.1[k] - w.1[k]).abs() < 1e-4), "{s:?} vs {w:?}"); - } - } - // A colour lookup without a (usable) table becomes an identity cube, without dither. - for lut in [None, Some(std::sync::Arc::new(vec![0.5; 7]))] { - let b = write(&Adjustment::ColorLookup { name: "L".into(), lut, size: 3, tetrahedral: false, dither: true }); - let back = parse(&b[0].0, &b[0].1, None, Channels::Rgb); - let Adjustment::ColorLookup { lut: Some(t), size: 2, dither: false, name, .. } = back else { panic!("{back:?}") }; - assert_eq!(name, "L"); - assert_eq!(*t, photocraft_cms::lutfile::LutFile::identity(2).data); - } - // Every kind except a malformed Unsupported key has an encoding. - assert!(write(&Adjustment::Unsupported { psd_key: "abc".into(), raw: Vec::new().into() }).is_empty()); - } - - #[test] - fn non_rgb_ignores_channel_records() { - let lc = LevelsChannel { in_black: 0.1, ..Default::default() }; - let a = Adjustment::Levels { - master: LevelsChannel::default(), - per_channel: [lc.clone(), lc.clone(), lc], - space: ToneSpace::Rgb, - black: LevelsChannel::default(), - }; - let b = write(&a); - match parse(&b[0].0, &b[0].1, None, Channels::Other) { - Adjustment::Levels { per_channel, .. } => assert_eq!(per_channel, <[LevelsChannel; 3]>::default()), - other => panic!("{other:?}"), - } - } - - #[test] - fn gray_uses_first_channel_record_for_all() { - let lc = LevelsChannel { in_black: 44.0 / 255.0, ..Default::default() }; - let a = Adjustment::Levels { - master: LevelsChannel::default(), - per_channel: [lc.clone(), Default::default(), Default::default()], - space: ToneSpace::Rgb, - black: LevelsChannel::default(), - }; - let b = write(&a); - match parse(&b[0].0, &b[0].1, None, Channels::Gray) { - Adjustment::Levels { per_channel, .. } => assert_eq!(per_channel, [lc.clone(), lc.clone(), lc]), - other => panic!("{other:?}"), - } - } - - #[test] - fn legacy_brit_without_cged() { - let a = parse(b"brit", &[0, 10, 0xff, 0xf6, 0, 127, 0], None, Channels::Rgb); - assert_eq!(a, Adjustment::BrightnessContrast { brightness: 10.0, contrast: -10.0, legacy: true }); - } -} +mod tests; diff --git a/crates/io/src/adjust_map/tests.rs b/crates/io/src/adjust_map/tests.rs new file mode 100644 index 0000000000..70727fba4f --- /dev/null +++ b/crates/io/src/adjust_map/tests.rs @@ -0,0 +1,596 @@ +use super::*; + +#[test] +fn gradient_map_v3_methods_and_smoothness() { + let classic = vec![(0.0, [0.0, 0.0, 1.0]), (1.0, [1.0, 1.0, 0.0])]; + let v1 = write_gradient_map(&classic, false, false); + // Version 3 inserts the interpolation method after reverse/dither. + let v3 = |m: &[u8; 4]| { + let mut v = v1.clone(); + v[1] = 3; + v.splice(4..4, m.iter().copied()); + v + }; + let at_t = |data: &[u8], t: f32| match parse(b"grdm", data, None, Channels::Rgb) { + Adjustment::GradientMap { stops, .. } => { + let i = stops.windows(2).position(|w| w[0].0 <= t && t <= w[1].0).unwrap(); + let (x, y) = (stops[i], stops[i + 1]); + let u = (t - x.0) / (y.0 - x.0).max(1e-6); + std::array::from_fn::(|k| x.1[k] + (y.1[k] - x.1[k]) * u) + } + other => panic!("{other:?}"), + }; + let mid = |data: &[u8]| at_t(data, 0.5); + let c = mid(&v3(b"Gcls")); + assert!((c[0] - 0.5).abs() < 1e-3 && (c[2] - 0.5).abs() < 1e-3, "classic = sRGB lerp {c:?}"); + let p = mid(&v3(b"Perc")); + assert!((p[0] - c[0]).abs() > 0.02, "perceptual differs from classic {p:?}"); + // Smoothness 100 % (4096) bends a three-stop ramp. + let three = vec![(0.0, [0.0; 3]), (0.25, [1.0, 0.0, 0.0]), (0.75, [0.0, 0.0, 1.0]), (1.0, [1.0; 3])]; + let mut smooth = write_gradient_map(&three, false, false); + // v1 header/name/count + colour stops + transparency stops + expansion count. + let at = 48 + three.len() * 20; + smooth[at..at + 2].copy_from_slice(&4096u16.to_be_bytes()); + let (a, b) = (at_t(&write_gradient_map(&three, false, false), 0.4), at_t(&smooth, 0.4)); + assert!((0..3).any(|k| (a[k] - b[k]).abs() > 1e-3), "{a:?} {b:?}"); + // Noise gradients (no colour stops) stay unsupported. + assert!(matches!(parse(b"grdm", &[0, 1, 0, 0, 0, 0, 0, 0, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); +} + +#[test] +fn pencil_curves_read_and_write_the_map_form() { + // Photoshop's pencil-drawn curves: map flag 1, then 256 output bytes per channel. + let mut block = vec![1, 0, 1, 0, 0, 0, 0b1111]; + let maps: [Vec; 4] = [ + (0..=255u8).rev().collect(), + (0..=255u8).map(|k| if k < 128 { 0 } else { 255 }).collect(), + (0..=255u8).collect(), + (0..=255u8).map(|k| k / 2).collect(), + ]; + for m in &maps { + block.extend_from_slice(m); + } + let a = parse(b"curv", &block, None, Channels::Rgb); + let Adjustment::Curves { master, per_channel, pencil, .. } = &a else { panic!("{a:?}") }; + assert!(*pencil); + assert_eq!(master.len(), CURVE_MAP_LEN); + assert_eq!((master[0].output, master[255].output), (1.0, 0.0)); + assert_eq!((per_channel[0][127].output, per_channel[0][128].output), (0.0, 1.0)); + assert_eq!(write(&a)[0].1, block); +} + +/// A two-stop `grdm` (version 1) whose stops are the colour structures `a` and `b`. +fn grdm_with(a: (u16, [u16; 4]), b: (u16, [u16; 4])) -> Vec { + let mut v = write_gradient_map(&[(0.0, [0.0; 3]), (1.0, [1.0; 3])], false, false); + // Header 4 + name length 4 + "Custom\0" 14 + stop count 2; 20 bytes per stop. + for (i, (space, c)) in [a, b].into_iter().enumerate() { + let at = 24 + 20 * i + 8; + v[at..at + 2].copy_from_slice(&space.to_be_bytes()); + for (k, x) in c.iter().enumerate() { + v[at + 2 + 2 * k..at + 4 + 2 * k].copy_from_slice(&x.to_be_bytes()); + } + } + v +} + +fn ends(a: &Adjustment) -> ([f32; 3], [f32; 3]) { + match a { + Adjustment::GradientMap { stops, .. } => (stops[0].1, stops[stops.len() - 1].1), + other => panic!("{other:?}"), + } +} + +#[test] +fn gradient_map_stops_in_every_colour_space() { + use photocraft_color::{Color, ColorMode}; + let white_rgb = (0, [65535, 65535, 65535, 0]); + // CMYK, stored inverted: 65535 = no ink. Full K only. + let k_only = grdm_with((2, [65535, 65535, 65535, 0]), white_rgb); + let expected = Color { mode: ColorMode::Cmyk, c: [0.0, 0.0, 0.0, 1.0], alpha: 1.0 }.to_rgb(); + for channels in [Channels::Cmyk, Channels::Rgb, Channels::Lab] { + let a = parse(b"grdm", &k_only, None, channels); + let (first, last) = ends(&a); + assert!(first.iter().zip(expected).all(|(x, y)| (x - y).abs() < 1e-5), "{first:?} vs {expected:?}"); + assert!(first[0] < 0.4 && (first[0] - first[2]).abs() < 0.05, "K-only black is a dark neutral: {first:?}"); + assert_eq!(last, [1.0; 3]); + } + // Lab: L 50, a 0, b 0 is a neutral mid grey; L 100 white. + let lab = parse(b"grdm", &grdm_with((7, [5000, 0, 0, 0]), (7, [10000, 0, 0, 0])), None, Channels::Lab); + let (first, last) = ends(&lab); + assert!(first.iter().all(|v| (v - 0.466).abs() < 0.01), "{first:?}"); + assert!(last.iter().all(|v| *v > 0.99), "{last:?}"); + // Lab with chroma: a = +60 is reddish (a and b are signed hundredths). + let red = parse(b"grdm", &grdm_with((7, [5000, 6000, 0, 0]), white_rgb), None, Channels::Lab); + let (first, _) = ends(&red); + assert!(first[0] > first[1] + 0.2, "{first:?}"); + // Grayscale: 0..10000 is ink coverage (10000 = black). + let gray = parse(b"grdm", &grdm_with((8, [10000, 0, 0, 0]), (8, [0, 0, 0, 0])), None, Channels::Gray); + assert_eq!(ends(&gray), ([0.0; 3], [1.0; 3])); + // HSB: hue 240 degrees (2/3 of 65535), full saturation and brightness = blue. + let hsb = parse(b"grdm", &grdm_with((1, [43690, 65535, 65535, 0]), white_rgb), None, Channels::Rgb); + let (first, _) = ends(&hsb); + assert!(first[0] < 1e-3 && first[1] < 1e-3 && (first[2] - 1.0).abs() < 1e-3, "{first:?}"); + // Book colours and unknown ids are not guessed: the block stays raw. + for space in [3u16, 9, 0xFFFF] { + let d = grdm_with((space, [1, 2, 3, 4]), white_rgb); + assert!(matches!(parse(b"grdm", &d, None, Channels::Rgb), Adjustment::Unsupported { .. }), "space {space}"); + } + // Truncated stops never panic. + for n in 0..k_only.len() { + let _ = parse(b"grdm", &k_only[..n], None, Channels::Cmyk); + } +} + +#[test] +fn gradient_map_reverse_and_dither_keep_the_stops_block() { + let original = grdm_with((2, [65535, 65535, 65535, 0]), (7, [10000, 0, 0, 0])); + let Adjustment::GradientMap { stops, .. } = parse(b"grdm", &original, None, Channels::Cmyk) else { panic!() }; + let mut data = original.clone(); + let target = Adjustment::GradientMap { stops: stops.clone(), reverse: true, dither: true }; + assert!(retarget_gradient_map(&mut data, &target, Channels::Cmyk)); + assert_eq!(&data[2..4], &[1, 1]); + assert_eq!(data[4..], original[4..], "the stops keep their colour spaces"); + assert_eq!(parse(b"grdm", &data, None, Channels::Cmyk), target); + // Edited stops are not patched in. + let mut edited = stops; + edited[0].1 = [0.5; 3]; + let mut data2 = original.clone(); + let target = Adjustment::GradientMap { stops: edited, reverse: false, dither: false }; + assert!(!retarget_gradient_map(&mut data2, &target, Channels::Cmyk)); + assert_eq!(data2, original); + assert!(!retarget_gradient_map(&mut [], &target, Channels::Cmyk)); + assert!(!retarget_gradient_map(&mut data2, &Adjustment::Invert, Channels::Cmyk)); +} + +fn rt(a: Adjustment) { + let blocks = write(&a); + assert!(!blocks.is_empty(), "{a:?}"); + let cged = blocks.iter().find(|b| &b.0 == b"CgEd").map(|b| &b.1[..]); + let back = parse(&blocks[0].0, &blocks[0].1, cged, Channels::Rgb); + assert_eq!(back, a); +} + +/// Photoshop keeps the colorize triplet at byte 4 and the master triplet at byte 10, and fills +/// the inactive one with its defaults: colorize (30, 25, 0), master (0, 0, 0). The colorize hue +/// is stored signed (200 -> -160). +#[test] +fn hue2_writes_each_triplet_in_its_own_slot() { + let triplets = |a: &Adjustment| -> Vec { + let blocks = write(a); + (0..6).map(|i| bei16(&blocks[0].1, 4 + 2 * i).unwrap_or(i16::MIN)).collect() + }; + let on = Adjustment::HueSaturation { hue: 200.0, saturation: 40.0, lightness: 10.0, colorize: true, ranges: HueRange::defaults() }; + assert_eq!(triplets(&on), [-160, 40, 10, 0, 0, 0]); + let off = Adjustment::HueSaturation { hue: -30.0, saturation: 20.0, lightness: 5.0, colorize: false, ranges: HueRange::defaults() }; + assert_eq!(triplets(&off), [30, 25, 0, -30, 20, 5]); +} + +#[test] +fn roundtrips() { + rt(Adjustment::Invert); + rt(Adjustment::Threshold { level: 128.0 / 255.0 }); + rt(Adjustment::Posterize { levels: 4 }); + rt(Adjustment::BrightnessContrast { brightness: 20.0, contrast: -10.0, legacy: false }); + rt(Adjustment::BrightnessContrast { brightness: -150.0, contrast: 100.0, legacy: true }); + rt(Adjustment::HueSaturation { hue: 30.0, saturation: -20.0, lightness: 5.0, colorize: false, ranges: HueRange::defaults() }); + rt(Adjustment::HueSaturation { hue: 200.0, saturation: 50.0, lightness: 0.0, colorize: true, ranges: HueRange::defaults() }); + let mut ranges = HueRange::defaults(); + ranges[0] = HueRange { hue: 15.0, saturation: -40.0, lightness: 10.0, bounds: [-60.0, -20.0, 10.0, 30.0] }; + ranges[4].saturation = 25.0; + rt(Adjustment::HueSaturation { hue: -10.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges }); + rt(Adjustment::Exposure { exposure: 1.5, offset: -0.01, gamma: 0.9 }); + let lc = |a: u16, b: u16| LevelsChannel { in_black: f32::from(a) / 255.0, in_white: f32::from(b) / 255.0, gamma: 1.2, out_black: 0.0, out_white: 1.0 }; + rt(Adjustment::Levels { master: lc(10, 240), per_channel: [lc(0, 255), lc(5, 250), lc(20, 200)], space: ToneSpace::Rgb, black: LevelsChannel::default() }); + let pts = |v: &[(u8, u8)]| v.iter().map(|&(i, o)| CurvePoint { input: f32::from(i) / 255.0, output: f32::from(o) / 255.0 }).collect::>(); + rt(Adjustment::Curves { + master: pts(&[(0, 0), (128, 150), (255, 255)]), + per_channel: [pts(&[(0, 10), (255, 255)]), pts(&[(0, 0), (255, 245)]), pts(&[(0, 0), (64, 32), (255, 255)])], + space: ToneSpace::Rgb, + black: Vec::new(), + pencil: false, + }); + // CMYK ink curves and levels keep their black record. + let ink = Adjustment::Curves { + master: pts(&[(0, 0), (255, 255)]), + per_channel: [pts(&[(0, 0), (255, 255)]), pts(&[(0, 30), (255, 255)]), pts(&[(0, 0), (255, 255)])], + space: ToneSpace::Cmyk, + black: pts(&[(0, 0), (128, 100), (255, 255)]), + pencil: false, + }; + let b = write(&ink); + assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Cmyk), ink); + let inkl = Adjustment::Levels { master: lc(0, 255), per_channel: [lc(0, 255), lc(5, 250), lc(0, 255)], space: ToneSpace::Cmyk, black: lc(30, 255) }; + let b = write(&inkl); + assert_eq!(parse(&b[0].0, &b[0].1, None, Channels::Cmyk), inkl); + rt(Adjustment::Unsupported { psd_key: "selc".into(), raw: vec![1, 2, 3].into() }); + rt(Adjustment::GradientMap { stops: vec![(0.0, [0.0, 0.0, 0.0]), (0.5, [1.0, 0.0, 0.0]), (1.0, [1.0, 1.0, 1.0])], reverse: true, dither: false }); + rt(Adjustment::GradientMap { stops: vec![(0.0, [0.0, 0.0, 0.0]), (1.0, [1.0, 1.0, 1.0])], reverse: false, dither: true }); + rt(Adjustment::SelectiveColor { relative: true, adjustments: std::array::from_fn(|r| [r as f32 * 10.0 - 40.0, 5.0, -100.0, 100.0]) }); + rt(Adjustment::SelectiveColor { relative: false, adjustments: [[0.0; 4]; 9] }); + rt(Adjustment::Vibrance { vibrance: 35.0, saturation: -12.0 }); + rt(Adjustment::Vibrance { vibrance: 0.0, saturation: 0.0 }); + rt(Adjustment::ColorBalance { shadows: [20.0, -10.0, 5.0], midtones: [-15.0, 10.0, 30.0], highlights: [0.0, 5.0, -100.0], preserve_luminosity: true }); + rt(Adjustment::ColorBalance { shadows: [0.0; 3], midtones: [100.0, 0.0, 0.0], highlights: [0.0; 3], preserve_luminosity: false }); + rt(Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None }); + rt(Adjustment::BlackWhite { weights: [-200.0, 300.0, 0.0, 10.0, 90.0, 30.0], tint: Some([0.9, 0.7, 0.5]) }); + let q = |v: u16| f32::from(v) / 65535.0; + rt(Adjustment::PhotoFilter { color: [q(60000), q(30000), q(0)], density: 0.25, preserve_luminosity: true }); + rt(Adjustment::PhotoFilter { color: [q(0), q(40000), q(65535)], density: 1.0, preserve_luminosity: false }); + rt(Adjustment::ChannelMixer { matrix: [[0.5, 0.3, 0.2, 0.0], [0.1, 0.8, 0.1, 0.05], [0.0, 0.2, 0.9, -0.05]], monochrome: false }); + rt(Adjustment::ChannelMixer { matrix: [[0.4, 0.4, 0.2, 0.1], [0.0, 1.0, 0.0, 0.0], [-2.0, 0.0, 2.0, 0.0]], monochrome: true }); + let id = photocraft_cms::lutfile::LutFile::identity(5); + rt(Adjustment::ColorLookup { name: "Look.cube".into(), lut: Some(std::sync::Arc::new(id.data)), size: 5, tetrahedral: false, dither: true }); +} + +#[test] +fn selective_color_synthetic_block() { + // Absolute; reds = (+10, -20, +30, -40), blacks = (0, 0, 0, 25). + let mut d = vec![0, 1, 0, 1]; + d.extend([0u8; 8]); + for r in 0..9 { + let rec: [i16; 4] = match r { + 0 => [10, -20, 30, -40], + 8 => [0, 0, 0, 25], + _ => [0; 4], + }; + for x in rec { + d.extend(x.to_be_bytes()); + } + } + let a = parse(b"selc", &d, None, Channels::Rgb); + let Adjustment::SelectiveColor { relative, adjustments } = &a else { panic!("{a:?}") }; + assert!(!relative); + assert_eq!(adjustments[0], [10.0, -20.0, 30.0, -40.0]); + assert_eq!(adjustments[8], [0.0, 0.0, 0.0, 25.0]); + // Written back byte-exact. + assert_eq!(write(&a)[0].1, d); +} + +#[test] +fn color_lookup_synthetic_block() { + let cube = b"TITLE \"t\"\nLUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n"; + let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) }; + let desc = Descriptor::new("null") + .with("lookupType", en("colorLookupType", "3DLUT")) + .with("NM ", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul("Id"))) + .with("Dthr", Value::Boolean(true)) + .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE")) + .with("LUT3DFileData", Value::RawData(cube.to_vec())); + let mut d = vec![0, 1]; + d.extend(VersionedDescriptor::new(desc).to_bytes()); + let a = parse(b"clrL", &d, None, Channels::Rgb); + let Adjustment::ColorLookup { name, lut: Some(t), size: 2, dither: true, .. } = &a else { panic!("{a:?}") }; + assert_eq!(name, "Id"); + assert_eq!(&t[..6], &[0.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + // A profile-based lookup (no table) is preserved raw. + let mut p = vec![0, 1]; + p.extend(VersionedDescriptor::new(Descriptor::new("null").with("lookupType", en("colorLookupType", "abstractProfile"))).to_bytes()); + assert!(matches!(parse(b"clrL", &p, None, Channels::Rgb), Adjustment::Unsupported { .. })); + // Each way a lookup can't be read has a reason for the import warning (#1763). + assert_eq!(unreadable_reason(b"clrL", &d), None); + assert!(unreadable_reason(b"clrL", &p).unwrap().contains("colour profile")); + assert!(unreadable_reason(b"clrL", &[0]).unwrap().contains("truncated")); + assert!(unreadable_reason(b"clrL", &[0, 2, 0, 0]).unwrap().contains("version 2")); + assert!(unreadable_reason(b"clrL", &[0, 1, 9]).unwrap().contains("unreadable settings")); + let bad = Descriptor::new("null").with("LUTFormat", en("LUTFormatType", "LUTFormat3DL")).with("LUT3DFileData", Value::RawData(b"not a lut".to_vec())); + let mut b = vec![0, 1]; + b.extend(VersionedDescriptor::new(bad).to_bytes()); + assert!(matches!(parse(b"clrL", &b, None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(unreadable_reason(b"clrL", &b).unwrap().contains("3DL LUT can't be read"), "{:?}", unreadable_reason(b"clrL", &b)); + assert_eq!(label(b"clrL"), "Color Lookup"); + assert!(matches!(parse(b"clrL", &[0, 1, 9], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"selc", &[0, 1, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); +} + +fn cube_lookup_block(cube: &[u8]) -> Vec { + let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) }; + let desc = Descriptor::new("null") + .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE")) + .with("LUT3DFileName", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul("domain.cube"))) + .with("LUT3DFileData", Value::RawData(cube.to_vec())); + let mut block = vec![0, 1]; + block.extend(VersionedDescriptor::new(desc).to_bytes()); + block +} + +fn identity_cube(domain: &str) -> Vec { + format!("{domain}LUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n").into_bytes() +} + +#[test] +fn color_lookup_custom_domains_are_kept_unsupported() { + let domains = ["DOMAIN_MIN 0 0 0\nDOMAIN_MAX 0.5 0.5 0.5\n", "DOMAIN_MIN 0 0.25 0\nDOMAIN_MAX 1 0.75 1\n", "LUT_3D_INPUT_RANGE 0 0.5\n"]; + for domain in domains { + let raw = cube_lookup_block(&identity_cube(domain)); + let Adjustment::Unsupported { psd_key, raw: kept } = parse(b"clrL", &raw, None, Channels::Rgb) else { + panic!("custom LUT domain was applied instead of kept unsupported: {domain}") + }; + assert_eq!(psd_key, "clrL"); + assert_eq!(*kept, *raw); + let reason = unreadable_reason(b"clrL", &raw).expect("custom domain has an explanation"); + assert!(reason.contains("DOMAIN_MIN") && reason.contains("DOMAIN_MAX"), "{reason}"); + assert!(reason.to_ascii_lowercase().contains("not supported"), "{reason}"); + } +} + +#[test] +fn color_lookup_default_domains_stay_supported() { + for domain in ["", "DOMAIN_MIN 0 0 0\nDOMAIN_MAX 1 1 1\n"] { + let raw = cube_lookup_block(&identity_cube(domain)); + assert!(matches!(parse(b"clrL", &raw, None, Channels::Rgb), Adjustment::ColorLookup { size: 2, .. })); + assert_eq!(unreadable_reason(b"clrL", &raw), None); + } +} + +#[test] +fn malformed_falls_back_to_unsupported() { + assert!(matches!(parse(b"levl", &[0, 2, 1], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"curv", &[0, 0, 9], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"thrs", &[], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"blnc", &[0; 18], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"vibA", &[0, 0, 0, 15, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"blwh", &[], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"mixr", &[0, 2, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); + // A CMYK mixer (black source used) stays raw in CMYK documents; our own RGB layout maps. + let mut cmyk = i16s(&[1, 0]); + for r in 0..4 { + cmyk.extend(i16s(&std::array::from_fn::(|k| if k == r { 100 } else { 0 }))); + } + assert!(matches!(parse(b"mixr", &cmyk, None, Channels::Cmyk), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"mixr", &cmyk, None, Channels::Other), Adjustment::Unsupported { .. })); + let ours = write(&Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], monochrome: false }); + assert!(matches!(parse(b"mixr", &ours[0].1, None, Channels::Cmyk), Adjustment::ChannelMixer { .. })); + assert!(matches!(parse(b"mixr", &ours[0].1, None, Channels::Other), Adjustment::ChannelMixer { .. })); + assert!(matches!(parse(b"mixr", &[0, 1, 0, 0, 0, 100], None, Channels::Rgb), Adjustment::Unsupported { .. })); + // Photo Filter: unknown version, HSB colour space, out-of-range version-3 XYZ, truncated. + assert!(matches!(parse(b"phfl", &[0, 4, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); + assert!(matches!(parse(b"phfl", &[0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 1], None, Channels::Rgb), Adjustment::Unsupported { .. })); + for bad in [[200_000u32, 0, 0], [0, u32::MAX, 0]] { + let mut xyz = vec![0, 3]; + for x in bad { + xyz.extend(x.to_be_bytes()); + } + xyz.extend([0, 0, 0, 25, 1]); + assert!(matches!(parse(b"phfl", &xyz, None, Channels::Rgb), Adjustment::Unsupported { .. })); + } + assert!(matches!(parse(b"phfl", &[0, 2, 0, 0, 0, 0], None, Channels::Rgb), Adjustment::Unsupported { .. })); + // Arbitrary bytes never panic, whatever the key. + for key in ADJUSTMENT_KEYS { + for len in 0..64usize { + let d: Vec = (0..len).map(|i| (i * 37 + len) as u8).collect(); + let _ = parse(key, &d, Some(&d), Channels::Rgb); + let _ = parse(key, &d, None, Channels::Other); + } + } +} + +fn i16s(v: &[i16]) -> Vec { + v.iter().flat_map(|x| x.to_be_bytes()).collect() +} + +/// Hand-built blocks laid out per the Adobe spec (no file written by Photoshop involved). +#[test] +fn color_balance_golden_block() { + let mut d = i16s(&[-30, 20, 0, 10, -5, 100, 0, 0, -100]); + d.extend([1, 0]); + let a = parse(b"blnc", &d, None, Channels::Rgb); + assert_eq!( + a, + Adjustment::ColorBalance { shadows: [-30.0, 20.0, 0.0], midtones: [10.0, -5.0, 100.0], highlights: [0.0, 0.0, -100.0], preserve_luminosity: true } + ); + assert_eq!(write(&a), vec![(*b"blnc", d.clone())]); + // The 19-byte form (no trailing pad) parses the same. + assert_eq!(parse(b"blnc", &d[..19], None, Channels::Rgb), a); +} + +#[test] +fn photo_filter_golden_blocks() { + // Version 2, RGB colour structure (65535, 32768, 0), density 40 %, preserve luminosity. + let mut v2 = i16s(&[2, 0]); + v2.extend([0xff, 0xff, 0x80, 0x00, 0, 0, 0, 0]); + v2.extend(40u32.to_be_bytes()); + v2.extend([1, 0, 0, 0]); + assert_eq!(v2.len(), 20, "Photo Filter must occupy 20 bytes"); + assert_eq!(&v2[17..], &[0, 0, 0], "padding is included inside the block length"); + let a = parse(b"phfl", &v2, None, Channels::Rgb); + let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = a else { panic!("{a:?}") }; + assert_eq!(color, [1.0, 32768.0 / 65535.0, 0.0]); + assert_eq!(density, 0.4); + assert_eq!(write(&a)[0].1, v2, "version 2 RGB is written back byte-exact"); + // Older PhotoCraft files used only one padding byte (18 bytes); keep importing them, + // but never produce that Photoshop-incompatible length again. + assert_eq!(parse(b"phfl", &v2[..18], None, Channels::Rgb), a); + for preserve_luminosity in [false, true] { + for density in [0.0, 0.14, 1.0] { + let adjustment = Adjustment::PhotoFilter { color: [0.8, 0.4, 0.2], density, preserve_luminosity }; + let blocks = write(&adjustment); + assert_eq!(blocks.len(), 1); + assert_eq!(blocks[0].0, *b"phfl"); + assert_eq!(blocks[0].1.len(), 20); + assert_eq!(&blocks[0].1[17..], &[0, 0, 0]); + let Adjustment::PhotoFilter { color, density: read_density, preserve_luminosity: read_preserve } = + parse(b"phfl", &blocks[0].1, None, Channels::Rgb) + else { + panic!("written phfl must parse") + }; + assert!(color.iter().zip([0.8, 0.4, 0.2]).all(|(got, expected)| (got - expected).abs() <= 1.0 / 65535.0)); + assert!((read_density - density).abs() < 0.00001); + assert_eq!(read_preserve, preserve_luminosity); + } + } + // Version 2, Lab colour structure: L 50, a 0, b 0 is mid gray. + let mut lab = i16s(&[2, 7, 5000, 0, 0, 0]); + lab.extend(25u32.to_be_bytes()); + lab.push(0); + let Adjustment::PhotoFilter { color, density, preserve_luminosity: false } = parse(b"phfl", &lab, None, Channels::Rgb) else { panic!() }; + assert!(color.iter().all(|c| (c - 0.466).abs() < 0.01), "{color:?}"); + assert_eq!(density, 0.25); + // Version 3: XYZ relative to the D50 white, 1.0 = 32768. White is (32768, 32768, 32768). + let v3 = phfl_v3([32768, 32768, 32768], 100, true); + let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = parse(b"phfl", &v3, None, Channels::Rgb) else { panic!() }; + assert!(color.iter().all(|c| (c - 1.0).abs() < 0.005), "{color:?}"); + assert_eq!(density, 1.0); + // Photoshop's Warming Filter (85) preset, sRGB #EC8A00: the CS2 file of #4940 stores it + // relative to the D50 white as (15548, 12029, 0). + let Adjustment::PhotoFilter { color, density, preserve_luminosity: false } = parse(b"phfl", &phfl_v3([15548, 12029, 0], 25, false), None, Channels::Rgb) + else { + panic!() + }; + let expected = [0xecu8, 0x8a, 0x00].map(|v| f32::from(v) / 255.0); + assert!(color.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{color:?}"); + assert_eq!(density, 0.25); + // The block from #3777 (Photoshop CS2): the Yellow filter preset, #F9E31C, density 63 %. + let issue = [0, 3, 0, 0, 0x5e, 0x7f, 0, 0, 0x61, 0xaa, 0, 0, 0x0e, 0xf3, 0, 0, 0, 0x3f, 1, 0]; + let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = parse(b"phfl", &issue, None, Channels::Rgb) else { panic!() }; + let expected = [0xf9u8, 0xe3, 0x1c].map(|v| f32::from(v) / 255.0); + assert!(color.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{color:?}"); + assert_eq!(density, 0.63); + // Cooling Filter (82) from #4940: a deep blue outside sRGB; its Z stays under the 2.0 + // garbage guard and the colour clamps to (0, 181, 255). + let Adjustment::PhotoFilter { color: cooling, density, preserve_luminosity: true } = + parse(b"phfl", &phfl_v3([5327, 9584, 65357], 72, true), None, Channels::Rgb) + else { + panic!("Cooling Filter (82) must parse") + }; + let expected = [0u8, 181, 255].map(|v| f32::from(v) / 255.0); + assert!(cooling.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{cooling:?}"); + assert_eq!(density, 0.72); + // The 19-byte form (no trailing pad) parses the same. + assert_eq!(parse(b"phfl", &issue[..19], None, Channels::Rgb), parse(b"phfl", &issue, None, Channels::Rgb)); + // Version 3 is read, never written: an edited filter is saved as version 2 and keeps its colour. + let a = parse(b"phfl", &issue, None, Channels::Rgb); + let w = write(&a); + assert_eq!(&w[0].1[..2], &[0, 2]); + let Adjustment::PhotoFilter { color: back, .. } = parse(b"phfl", &w[0].1, None, Channels::Rgb) else { panic!() }; + assert!(back.iter().zip(color).all(|(b, c)| (b - c).abs() <= 1.0 / 65535.0)); +} + +/// A version 3 Photo Filter block: version, three u32 XYZ components, density, flag, pad. +fn phfl_v3(xyz: [u32; 3], density: u32, preserve_luminosity: bool) -> Vec { + let mut d = vec![0, 3]; + for x in xyz { + d.extend(x.to_be_bytes()); + } + d.extend(density.to_be_bytes()); + d.extend([u8::from(preserve_luminosity), 0]); + d +} + +#[test] +fn channel_mixer_golden_blocks() { + // RGB: red = 100 % R + 20 % const; green = 50 % R + 50 % G; blue = -50 % G + 150 % B - 10 % const. + let mut d = i16s(&[1, 0]); + d.extend(i16s(&[100, 0, 0, 0, 20, 50, 50, 0, 0, 0, 0, -50, 150, 0, -10])); + let a = parse(b"mixr", &d, None, Channels::Rgb); + assert_eq!(a, Adjustment::ChannelMixer { matrix: [[1.0, 0.0, 0.0, 0.2], [0.5, 0.5, 0.0, 0.0], [0.0, -0.5, 1.5, -0.1]], monochrome: false }); + // Written with the trailing gray record (a copy of the first row). + let w = write(&a); + assert_eq!(w[0].1[..d.len()], d[..]); + assert_eq!(w[0].1[d.len()..], i16s(&[100, 0, 0, 0, 20])[..]); + // Monochrome with only the gray record: 30/59/11. + let mut m = i16s(&[1, 1]); + m.extend(i16s(&[30, 59, 11, 0, 0])); + let Adjustment::ChannelMixer { matrix, monochrome: true } = parse(b"mixr", &m, None, Channels::Rgb) else { panic!() }; + assert_eq!(matrix[0], [0.3, 0.59, 0.11, 0.0]); +} + +fn vdesc(d: Descriptor) -> Vec { + VersionedDescriptor::new(d).to_bytes() +} + +#[test] +fn vibrance_golden_block() { + let d = vdesc(Descriptor::new("null").with("vibrance", Value::Integer(-40)).with("Strt", Value::Integer(25))); + assert_eq!(&d[..4], &[0, 0, 0, 16], "descriptor version 16"); + assert_eq!(parse(b"vibA", &d, None, Channels::Rgb), Adjustment::Vibrance { vibrance: -40.0, saturation: 25.0 }); + // Photoshop omits zero values. + let only = vdesc(Descriptor::new("null").with("Strt", Value::Integer(10))); + assert_eq!(parse(b"vibA", &only, None, Channels::Rgb), Adjustment::Vibrance { vibrance: 0.0, saturation: 10.0 }); + // Other descriptor versions are rejected (kept raw). + let mut v = d.clone(); + v[3] = 17; + assert!(matches!(parse(b"vibA", &v, None, Channels::Rgb), Adjustment::Unsupported { .. })); +} + +#[test] +fn black_white_golden_block() { + let tint = Descriptor::new("RGBC").with("Rd ", Value::Double(255.0)).with("Grn ", Value::Double(127.5)).with("Bl ", Value::Double(0.0)); + let mut desc = Descriptor::new("null"); + for (k, w) in BW_KEYS.iter().zip([10, 20, 30, 40, 50, 60]) { + desc = desc.with(k, Value::Integer(w)); + } + let d = + vdesc(desc.clone().with("useTint", Value::Boolean(true)).with("tintColor", Value::Descriptor(tint.clone())).with("bwPresetKind", Value::Integer(1))); + let a = parse(b"blwh", &d, None, Channels::Rgb); + assert_eq!(a, Adjustment::BlackWhite { weights: [10.0, 20.0, 30.0, 40.0, 50.0, 60.0], tint: Some([1.0, 0.5, 0.0]) }); + // useTint off: no tint, even with a stored colour. + let off = vdesc(desc.with("useTint", Value::Boolean(false)).with("tintColor", Value::Descriptor(tint))); + assert!(matches!(parse(b"blwh", &off, None, Channels::Rgb), Adjustment::BlackWhite { tint: None, .. })); + // Missing weights take Photoshop's defaults. + let empty = vdesc(Descriptor::new("null")); + assert_eq!(parse(b"blwh", &empty, None, Channels::Rgb), Adjustment::BlackWhite { weights: BW_DEFAULT, tint: None }); +} + +#[test] +fn degenerate_adjustments_still_get_an_encoding() { + // Gradient maps with fewer than two stops render as gray (none) or one colour. + for (stops, want) in + [(vec![], vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]), (vec![(0.3, [0.2, 0.4, 0.6])], vec![(0.0, [0.2, 0.4, 0.6]), (1.0, [0.2, 0.4, 0.6])])] + { + let b = write(&Adjustment::GradientMap { stops, reverse: true, dither: false }); + let back = parse(&b[0].0, &b[0].1, None, Channels::Rgb); + let Adjustment::GradientMap { stops, reverse: true, .. } = back else { panic!("{back:?}") }; + assert_eq!(stops.len(), want.len()); + for (s, w) in stops.iter().zip(&want) { + assert!((s.0 - w.0).abs() < 1e-6 && (0..3).all(|k| (s.1[k] - w.1[k]).abs() < 1e-4), "{s:?} vs {w:?}"); + } + } + // A colour lookup without a (usable) table becomes an identity cube, without dither. + for lut in [None, Some(std::sync::Arc::new(vec![0.5; 7]))] { + let b = write(&Adjustment::ColorLookup { name: "L".into(), lut, size: 3, tetrahedral: false, dither: true }); + let back = parse(&b[0].0, &b[0].1, None, Channels::Rgb); + let Adjustment::ColorLookup { lut: Some(t), size: 2, dither: false, name, .. } = back else { panic!("{back:?}") }; + assert_eq!(name, "L"); + assert_eq!(*t, photocraft_cms::lutfile::LutFile::identity(2).data); + } + // Every kind except a malformed Unsupported key has an encoding. + assert!(write(&Adjustment::Unsupported { psd_key: "abc".into(), raw: Vec::new().into() }).is_empty()); +} + +#[test] +fn non_rgb_ignores_channel_records() { + let lc = LevelsChannel { in_black: 0.1, ..Default::default() }; + let a = Adjustment::Levels { + master: LevelsChannel::default(), + per_channel: [lc.clone(), lc.clone(), lc], + space: ToneSpace::Rgb, + black: LevelsChannel::default(), + }; + let b = write(&a); + match parse(&b[0].0, &b[0].1, None, Channels::Other) { + Adjustment::Levels { per_channel, .. } => assert_eq!(per_channel, <[LevelsChannel; 3]>::default()), + other => panic!("{other:?}"), + } +} + +#[test] +fn gray_uses_first_channel_record_for_all() { + let lc = LevelsChannel { in_black: 44.0 / 255.0, ..Default::default() }; + let a = Adjustment::Levels { + master: LevelsChannel::default(), + per_channel: [lc.clone(), Default::default(), Default::default()], + space: ToneSpace::Rgb, + black: LevelsChannel::default(), + }; + let b = write(&a); + match parse(&b[0].0, &b[0].1, None, Channels::Gray) { + Adjustment::Levels { per_channel, .. } => assert_eq!(per_channel, [lc.clone(), lc.clone(), lc]), + other => panic!("{other:?}"), + } +} + +#[test] +fn legacy_brit_without_cged() { + let a = parse(b"brit", &[0, 10, 0xff, 0xf6, 0, 127, 0], None, Channels::Rgb); + assert_eq!(a, Adjustment::BrightnessContrast { brightness: 10.0, contrast: -10.0, legacy: true }); +} From b99e48bee68c8f263e0ae20f471c2491b76433e7 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:52 +0000 Subject: [PATCH 122/259] refactor(io): move psd_import.rs tests to psd_import/tests.rs --- crates/io/src/psd_import.rs | 372 +----------------------------- crates/io/src/psd_import/tests.rs | 369 +++++++++++++++++++++++++++++ 2 files changed, 370 insertions(+), 371 deletions(-) create mode 100644 crates/io/src/psd_import/tests.rs diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 07542bf2c6..2a0f982514 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -1333,374 +1333,4 @@ pub(crate) fn psd_to_document_decoded_integrity( } #[cfg(test)] -mod tests { - use super::*; - use photocraft_psd::descriptor::UnicodeString; - use photocraft_psd::resources::VersionInfo; - use photocraft_psd::{Compression, ImageData, ImageResource, PsdError, Version, testgen}; - - /// #5200: the Multichannel fallback checks its RGBA output against the budget before - /// allocating it (here a 2x2 image, 16 bytes, against caps of 15 and 16 bytes). - #[test] - fn flat_fallback_refuses_an_output_over_the_cap() { - let file = testgen::merged_only(Version::Psd, PsdMode::Multichannel, 8, Compression::Raw, 2, 2); - assert!(file.composite_rgba8().is_err(), "Multichannel goes through the fallback"); - let merged = file.decode_merged(); - assert!(matches!(flat_composite(&file, Some(&merged), 15), Err(PsdError::LimitExceeded(_)))); - let img = flat_composite(&file, Some(&merged), 16).unwrap(); - assert_eq!(img.data.len(), 16); - } - - /// #5200: a composite over the budget is not retried by the fallback (which allocated the - /// refused buffer: 14.4 GB for this 60000x60000 Bitmap header). - #[test] - fn flat_fallback_does_not_retry_an_over_budget_composite() { - let mut file = testgen::small(Version::Psb, Compression::Raw); - file.header.color_mode = PsdMode::Bitmap; - file.header.depth = 1; - file.header.channels = 1; - file.header.width = 60_000; - file.header.height = 60_000; - let merged = Ok(vec![0u8; 16]); - let cap = photocraft_psd::compression::MAX_DECODED_BYTES; - assert!(matches!(flat_composite(&file, Some(&merged), cap), Err(PsdError::LimitExceeded(_)))); - } - - /// #5202: a hostile name length ends the list instead of overflowing. - #[test] - fn unicode_names_stop_at_a_hostile_length() { - let mut data = 1u32.to_be_bytes().to_vec(); - data.extend([0, b'A']); - data.extend(u32::MAX.to_be_bytes()); - data.extend([0, b'B']); - assert_eq!(unicode_names(&data), ["A"]); - } - - /// Verifies an unreadable layer channel sets the structured damage indicator. - #[test] - fn unreadable_layer_channel_marks_conversion_damaged() { - let mut file = testgen::small(Version::Psd, Compression::Raw); - let channel = file.layers_mut()[0].channels.iter_mut().find(|c| c.id == 0).unwrap(); - channel.data.clear(); - assert!(file.layers()[0].decode_channel(0, file.header.depth, file.header.version).is_err()); - - let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); - assert!(damaged); - assert!(warnings.iter().any(|w| w.contains("could not be decoded"))); - } - - /// Verifies an unreadable user-mask channel sets the structured damage indicator. - #[test] - fn unreadable_mask_channel_marks_conversion_damaged() { - let mut file = testgen::small(Version::Psd, Compression::Raw); - let channel = file.layers_mut()[0].channels.iter_mut().find(|c| c.id == CHANNEL_USER_MASK).unwrap(); - channel.data.clear(); - - let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); - assert!(damaged); - assert!(warnings.iter().any(|w| w.contains("could not be decoded"))); - } - - /// A layer whose bounds hold pixels but whose colour and transparency channels are missing - /// lost its pixel data: the open asks before continuing. - #[test] - fn layer_bounds_without_channel_data_mark_conversion_damaged() { - let mut file = testgen::small(Version::Psd, Compression::Raw); - file.layers_mut()[0].channels.retain(|c| c.id == CHANNEL_USER_MASK); - - let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); - assert!(damaged); - assert!(warnings.iter().any(|w| w.contains("no channel data"))); - } - - /// A layer without pixels (an empty layer, or a text or shape layer written without a - /// pixel cache) has empty bounds: nothing is missing, so the file is not damaged even when - /// it lists no colour or transparency channel. - #[test] - fn empty_layer_without_channel_data_is_not_damaged() { - let mut file = testgen::small(Version::Psd, Compression::Raw); - file.layers_mut()[0].channels.retain(|c| c.id == CHANNEL_USER_MASK); - file.layers_mut()[0].rect = Default::default(); - - let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); - assert!(!damaged, "an empty layer marked the PSD damaged: {warnings:?}"); - } - - /// Verifies healthy layer channels do not mark the PSD as damaged. - #[test] - fn valid_layer_channels_keep_conversion_editable() { - let file = testgen::small(Version::Psd, Compression::Raw); - let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); - assert!(!damaged, "unexpectedly marked good PSD damaged: {warnings:?}"); - } - - #[test] - fn merged_plane_checks_offsets() { - let all = [1u8, 2, 3, 4]; - assert_eq!(merged_plane(&all, 1, 2), Some(&[3u8, 4][..])); - assert_eq!(merged_plane(&all, 2, 2), None); - assert_eq!(merged_plane(&all, usize::MAX, 2), None); - } - - /// Resource 1057's data. - fn version_info(writer: UnicodeString, reader: UnicodeString, has_real_merged_data: bool) -> Vec { - VersionInfo { version: 1, has_real_merged_data, writer, reader, file_version: 1 }.to_bytes() - } - - /// The 1057 PhotoCraft 0.1.0 to 0.7.0 wrote: Photoshop CS6's names, NUL-terminated. - fn version_info_cs6(has_real_merged_data: bool) -> Vec { - version_info(UnicodeString::new_nul("Adobe Photoshop"), UnicodeString::new_nul("Adobe Photoshop CS6"), has_real_merged_data) - } - - /// The 1057 PhotoCraft writes since 0.8.2: Photoshop 2026's bytes, no NUL. - fn version_info_2026(has_real_merged_data: bool) -> Vec { - photocraft_psd::resources::version_info_resource(has_real_merged_data).data - } - - /// An opaque 4 × 1 RGB document with the Photoshop spot oracles' channels in their order: - /// "Spot A", "Alpha 1" and "Spot B", each holding 100, 25, 75 and 0 % in four columns. - fn channels_document(depth: SampleType) -> Document { - let mut doc = Document::with_background("old", Size::new(4, 1), ColorMode::Rgb, depth, photocraft_color::Color::rgb(1.0, 1.0, 1.0)); - let gray = PixelFormat::new(ColorMode::Grayscale, depth, false); - let canvas = doc.bounds(); - let channel = |name: &str, spot: Option<(photocraft_color::Color, f32)>| { - let mut s = Surface::new(gray); - s.write_region(canvas, &[1.0, 0.25, 0.75, 0.0]); - AlphaChannel { spot, ..AlphaChannel::new(name, s) } - }; - doc.channels.push(channel("Spot A", Some((photocraft_color::Color::rgb(0.0, 0.627, 1.0), 0.0)))); - doc.channels.push(channel("Alpha 1", None)); - doc.channels.push(channel("Spot B", Some((photocraft_color::Color::rgb(1.0, 0.0, 0.627), 0.5)))); - doc - } - - /// Each channel's values on an 8-bit scale. - fn ink(doc: &Document) -> Vec> { - doc.channels.iter().map(|c| c.surface.read_region(doc.bounds()).iter().map(|v| (v * 255.0).round() as u8).collect()).collect() - } - - fn spots(doc: &Document) -> Vec { - doc.channels.iter().map(|c| c.spot.is_some()).collect() - } - - /// `doc` (opaque, 8 or 16-bit) saved the way PhotoCraft 0.1.0 to 0.16.0 saved it: spot planes - /// straight (the maximum = solid ink), no 1053, and `version_info` as resource 1057. `padded` - /// lays DisplayInfo out in the 14-byte records of 0.1.0 to 0.7.0. - fn as_earlier_photocraft_saved(doc: &Document, version_info: Vec, padded: bool) -> Vec { - let mut file = crate::psd_export::document_to_psd(doc); - assert!(!file.merged_has_alpha()); - file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS); - for r in &mut file.resources { - match r.id { - ids::VERSION_INFO => r.data = version_info.clone(), - crate::channel_map::DISPLAY_INFO if padded => { - let (version, records) = r.data.split_at(4); - r.data = version.iter().copied().chain(records.chunks(13).flat_map(|rec| rec.iter().copied().chain([0]))).collect(); - } - _ => {} - } - } - let mut planes = file.decode_merged().unwrap(); - let plane = planes.len() / usize::from(file.header.channels); - for (k, c) in doc.channels.iter().enumerate() { - if c.spot.is_some() { - // At 8 and 16 bits the complement of a sample is that of each of its bytes. - planes[(3 + k) * plane..(4 + k) * plane].iter_mut().for_each(|b| *b = !*b); - } - } - file.image_data = ImageData::encode(Compression::Raw, &planes, &file.header).unwrap(); - file.to_bytes().unwrap() - } - - /// PSDs that PhotoCraft 0.1.0 to 0.16.0 saved with spot channels store them straight. They - /// open with the ink they had in those versions (which read every plane straight), whichever - /// 1057 they carry. Saved again, they get Photoshop's polarity and a 1053, and reopen with the - /// same ink. (A 0.1.0 to 0.7.0 file's padded records misread every channel's options after - /// the first, here Spot B's kind, as those versions' successors always have; its ink is kept.) - #[test] - fn spot_planes_from_earlier_photocraft_keep_their_ink() { - for depth in [SampleType::U8, SampleType::U16] { - let doc = channels_document(depth); - let cases = [ - ("0.1.0 to 0.7.0", version_info_cs6(true), true), - ("0.8.2 on", version_info_2026(true), false), - ("0.8.2 on, Maximize Compatibility off", version_info_2026(false), false), - ("0.1.0 to 0.7.0, 13-byte records", version_info_cs6(true), false), - ]; - for (what, version_info, padded) in cases { - let bytes = as_earlier_photocraft_saved(&doc, version_info, padded); - assert!(earlier_photocraft_spot_planes(&PsdFile::from_bytes(&bytes).unwrap()), "{what}"); - let opened = crate::import("old.psd", &bytes).unwrap().document; - assert_eq!(ink(&opened), ink(&doc), "{depth:?} {what}: the ink earlier versions opened"); - assert!(spots(&opened)[0], "{depth:?} {what}"); - if !padded { - assert_eq!(spots(&opened), spots(&doc), "{depth:?} {what}"); - } - let saved = crate::export(&opened, "old.psd", &crate::ExportOptions::default()).unwrap(); - let file = PsdFile::from_bytes(&saved.bytes).unwrap(); - assert!(file.resource(crate::channel_map::ALPHA_IDENTIFIERS).is_some() && !earlier_photocraft_spot_planes(&file), "{what}"); - let again = crate::import("again.psd", &saved.bytes).unwrap().document; - assert_eq!(ink(&again), ink(&doc), "{depth:?} {what}: saved again"); - assert_eq!(spots(&again), spots(&opened), "{depth:?} {what}: saved again"); - } - } - } - - /// A 0.1.0 to 0.7.0 file whose first extra channel is an alpha channel, spots after it. In its - /// 14-byte DisplayInfo records the spots' kind bytes sit where a 13-byte reader (main's, and - /// this one's) doesn't look, so only the padded reading finds a spot for the rule. Every plane - /// is then read straight, as those versions read it, and keeps its ink. The 13-byte reader - /// opens each channel's options from shifted bytes, as on main: here every channel opens as - /// an alpha channel. A spot of 2 % solidity puts a 2 where that reader looks for the kind, so - /// that channel opens as a spot: without the rule its plane would be inverted. Saved again and - /// reopened, every channel keeps its ink and kind. - #[test] - fn an_early_file_with_an_alpha_channel_first_keeps_its_ink() { - for solidity in [0.0, 0.02] { - let mut doc = channels_document(SampleType::U8); - doc.channels.swap(0, 1); - doc.channels[1].spot = Some((photocraft_color::Color::rgb(0.0, 0.627, 1.0), solidity)); - let names: Vec<&str> = doc.channels.iter().map(|c| c.name.as_str()).collect(); - assert_eq!(names, ["Alpha 1", "Spot A", "Spot B"]); - let bytes = as_earlier_photocraft_saved(&doc, version_info_cs6(true), true); - let file = PsdFile::from_bytes(&bytes).unwrap(); - let info = &file.resource(crate::channel_map::DISPLAY_INFO).unwrap().data; - let misread = solidity > 0.0; - assert_eq!(crate::channel_map::spot_flags(info, true, 0), [false, misread, false], "{solidity}: 13-byte records"); - assert!(earlier_photocraft_spot_planes(&file), "{solidity}: found in the 14-byte records"); - let opened = crate::import("old.psd", &bytes).unwrap().document; - assert_eq!(ink(&opened), ink(&doc), "{solidity}: the ink 0.7.0 opened"); - assert_eq!(spots(&opened), [false, misread, false], "{solidity}: kinds as main reads them"); - let saved = crate::export(&opened, "old.psd", &crate::ExportOptions::default()).unwrap(); - let again = crate::import("again.psd", &saved.bytes).unwrap().document; - assert_eq!(ink(&again), ink(&doc), "{solidity}: saved again"); - assert_eq!(spots(&again), spots(&opened), "{solidity}: saved again"); - } - } - - /// A file with spots and no 1053 that no earlier PhotoCraft wrote is read in Photoshop's - /// polarity (0 = solid ink). psd-tools' `cmyk-spot.psd` is one: its 1057 names psd-tools as - /// writer and reader. So is a file with no 1057, with Photoshop CS6's names without the NUL, - /// or with bytes after PhotoCraft's. - #[test] - fn other_files_without_alpha_identifiers_use_photoshop_polarity() { - let doc = channels_document(SampleType::U8); - let mut trailing = version_info_2026(true); - trailing.extend([0, 0]); - let cases = [ - ("psd-tools", Some(version_info(UnicodeString::new("psd-tools 1.10.0"), UnicodeString::new("psd-tools 1.10.0"), true))), - ("no 1057", None), - ("CS6 without a NUL", Some(version_info(UnicodeString::new("Adobe Photoshop"), UnicodeString::new("Adobe Photoshop CS6"), true))), - ("bytes after PhotoCraft's 1057", Some(trailing)), - ]; - for (what, info) in cases { - // Photoshop's polarity, as this version writes it, without 1053. - let mut file = crate::psd_export::document_to_psd(&doc); - file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS && r.id != ids::VERSION_INFO); - file.resources.extend(info.map(|d| ImageResource::new(ids::VERSION_INFO, d))); - let bytes = file.to_bytes().unwrap(); - assert!(!earlier_photocraft_spot_planes(&PsdFile::from_bytes(&bytes).unwrap()), "{what}"); - let opened = crate::import("x.psd", &bytes).unwrap().document; - assert_eq!(ink(&opened), ink(&doc), "{what}"); - assert_eq!(spots(&opened), spots(&doc), "{what}"); - } - } - - /// The rule needs a spot in DisplayInfo and no 1053, besides PhotoCraft's 1057. - #[test] - fn the_earlier_photocraft_rule_needs_a_spot_and_no_alpha_identifiers() { - let mut doc = channels_document(SampleType::U8); - let old = PsdFile::from_bytes(&as_earlier_photocraft_saved(&doc, version_info_2026(true), false)).unwrap(); - assert!(earlier_photocraft_spot_planes(&old)); - let mut with_ids = old.clone(); - with_ids.resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, crate::channel_map::alpha_identifiers(false, 3))); - assert!(!earlier_photocraft_spot_planes(&with_ids), "a 1053"); - let mut no_info = old.clone(); - no_info.resources.retain(|r| r.id != crate::channel_map::DISPLAY_INFO); - assert!(!earlier_photocraft_spot_planes(&no_info), "no DisplayInfo"); - doc.channels.retain(|c| c.spot.is_none()); - let alpha_only = PsdFile::from_bytes(&as_earlier_photocraft_saved(&doc, version_info_2026(true), false)).unwrap(); - assert!(!earlier_photocraft_spot_planes(&alpha_only), "alpha channels only"); - } - - /// `doc` as an earlier PhotoCraft saved a Photoshop file it had opened with the first `kept` - /// of `doc`'s channels: it wrote back the Photoshop file's 1053, `stale_ids`, unchanged and - /// those channels' planes as Photoshop stored them (it had read and written them straight), - /// and stored the channels added after them straight. - fn as_earlier_photocraft_resaved(doc: &Document, stale_ids: &[u32], kept: usize) -> Vec { - let mut file = crate::psd_export::document_to_psd(doc); - file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS && r.id != ids::VERSION_INFO); - file.resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, stale_ids.iter().flat_map(|id| id.to_be_bytes()).collect())); - file.resources.push(ImageResource::new(ids::VERSION_INFO, version_info_2026(true))); - let mut planes = file.decode_merged().unwrap(); - let plane = planes.len() / usize::from(file.header.channels); - let first = usize::from(file.header.channels) - doc.channels.len(); - for (k, c) in doc.channels.iter().enumerate().skip(kept) { - if c.spot.is_some() { - planes[(first + k) * plane..(first + k + 1) * plane].iter_mut().for_each(|b| *b = !*b); - } - } - file.image_data = ImageData::encode(Compression::Raw, &planes, &file.header).unwrap(); - file.to_bytes().unwrap() - } - - /// An earlier PhotoCraft kept the 1053 of a Photoshop file it opened and wrote it back - /// unchanged, so a spot channel added there sits behind a 1053 that doesn't list it: a - /// transparent Photoshop document's `[0]` (the white plate of a DTF print, added before - /// saving), the `[0, 3]` of one with a spot channel already, or a `[0]` kept through a - /// flatten that removed the transparency. The added spot is stored straight and keeps its - /// ink; the Photoshop file's own spot keeps Photoshop's polarity. Saved again, both reopen - /// the same. - #[test] - fn a_spot_added_behind_a_kept_alpha_identifiers_resource_keeps_its_ink() { - let transparent = |names: &[&str]| { - let mut doc = channels_document(SampleType::U8); - doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())]; - doc.channels.retain(|c| names.contains(&c.name.as_str())); - doc - }; - let mut flattened = channels_document(SampleType::U8); - flattened.channels.retain(|c| c.name == "Spot A"); - let cases = [ - ("transparent, one spot added", transparent(&["Spot A"]), vec![0], 0), - ("transparent, a Photoshop spot and one added", transparent(&["Spot A", "Spot B"]), vec![0, 3], 1), - ("flattened, one spot added", flattened, vec![0], 0), - ]; - for (what, doc, stale_ids, kept) in cases { - let bytes = as_earlier_photocraft_resaved(&doc, &stale_ids, kept); - let file = PsdFile::from_bytes(&bytes).unwrap(); - assert_eq!(file.merged_has_alpha(), what.starts_with("transparent"), "{what}"); - assert!(earlier_photocraft_spot_planes(&file), "{what}"); - let opened = crate::import("old.psd", &bytes).unwrap().document; - assert_eq!(ink(&opened), ink(&doc), "{what}: the ink earlier versions opened"); - assert_eq!(spots(&opened), spots(&doc), "{what}"); - let saved = crate::export(&opened, "old.psd", &crate::ExportOptions::default()).unwrap(); - let again = crate::import("again.psd", &saved.bytes).unwrap().document; - assert_eq!(ink(&again), ink(&doc), "{what}: saved again"); - } - } - - /// A 1053 that lists every extra channel, as Photoshop and this version write it, keeps the - /// file in Photoshop's polarity, with PhotoCraft's (Photoshop 2026's) 1057 too: a transparent - /// file with a spot, and Photoshop's own `[0]` in a file without a transparency plane. - #[test] - fn a_complete_alpha_identifiers_resource_keeps_photoshop_polarity() { - let mut doc = channels_document(SampleType::U8); - doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())]; - let bytes = as_earlier_photocraft_resaved(&doc, &[0, 3, 4, 5], 3); - let file = PsdFile::from_bytes(&bytes).unwrap(); - assert!(file.merged_has_alpha()); - assert!(!earlier_photocraft_spot_planes(&file)); - assert_eq!(ink(&crate::import("ps.psd", &bytes).unwrap().document), ink(&doc)); - let mut opaque = channels_document(SampleType::U8); - opaque.channels.clear(); - let mut file = PsdFile::from_bytes(&as_earlier_photocraft_resaved(&opaque, &[0], 0)).unwrap(); - file.resources.retain(|r| r.id != crate::channel_map::DISPLAY_INFO); - file.resources.push(ImageResource::new( - crate::channel_map::DISPLAY_INFO, - crate::channel_map::display_info(&channels_document(SampleType::U8).channels.iter().collect::>(), false), - )); - assert_eq!(photoshop_identified_channels(&file), 0, "0 is the transparency's"); - assert!(!earlier_photocraft_spot_planes(&file), "no channel left unlisted"); - } -} +mod tests; diff --git a/crates/io/src/psd_import/tests.rs b/crates/io/src/psd_import/tests.rs new file mode 100644 index 0000000000..66c3bb3cdd --- /dev/null +++ b/crates/io/src/psd_import/tests.rs @@ -0,0 +1,369 @@ +use super::*; +use photocraft_psd::descriptor::UnicodeString; +use photocraft_psd::resources::VersionInfo; +use photocraft_psd::{Compression, ImageData, ImageResource, PsdError, Version, testgen}; + +/// #5200: the Multichannel fallback checks its RGBA output against the budget before +/// allocating it (here a 2x2 image, 16 bytes, against caps of 15 and 16 bytes). +#[test] +fn flat_fallback_refuses_an_output_over_the_cap() { + let file = testgen::merged_only(Version::Psd, PsdMode::Multichannel, 8, Compression::Raw, 2, 2); + assert!(file.composite_rgba8().is_err(), "Multichannel goes through the fallback"); + let merged = file.decode_merged(); + assert!(matches!(flat_composite(&file, Some(&merged), 15), Err(PsdError::LimitExceeded(_)))); + let img = flat_composite(&file, Some(&merged), 16).unwrap(); + assert_eq!(img.data.len(), 16); +} + +/// #5200: a composite over the budget is not retried by the fallback (which allocated the +/// refused buffer: 14.4 GB for this 60000x60000 Bitmap header). +#[test] +fn flat_fallback_does_not_retry_an_over_budget_composite() { + let mut file = testgen::small(Version::Psb, Compression::Raw); + file.header.color_mode = PsdMode::Bitmap; + file.header.depth = 1; + file.header.channels = 1; + file.header.width = 60_000; + file.header.height = 60_000; + let merged = Ok(vec![0u8; 16]); + let cap = photocraft_psd::compression::MAX_DECODED_BYTES; + assert!(matches!(flat_composite(&file, Some(&merged), cap), Err(PsdError::LimitExceeded(_)))); +} + +/// #5202: a hostile name length ends the list instead of overflowing. +#[test] +fn unicode_names_stop_at_a_hostile_length() { + let mut data = 1u32.to_be_bytes().to_vec(); + data.extend([0, b'A']); + data.extend(u32::MAX.to_be_bytes()); + data.extend([0, b'B']); + assert_eq!(unicode_names(&data), ["A"]); +} + +/// Verifies an unreadable layer channel sets the structured damage indicator. +#[test] +fn unreadable_layer_channel_marks_conversion_damaged() { + let mut file = testgen::small(Version::Psd, Compression::Raw); + let channel = file.layers_mut()[0].channels.iter_mut().find(|c| c.id == 0).unwrap(); + channel.data.clear(); + assert!(file.layers()[0].decode_channel(0, file.header.depth, file.header.version).is_err()); + + let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); + assert!(damaged); + assert!(warnings.iter().any(|w| w.contains("could not be decoded"))); +} + +/// Verifies an unreadable user-mask channel sets the structured damage indicator. +#[test] +fn unreadable_mask_channel_marks_conversion_damaged() { + let mut file = testgen::small(Version::Psd, Compression::Raw); + let channel = file.layers_mut()[0].channels.iter_mut().find(|c| c.id == CHANNEL_USER_MASK).unwrap(); + channel.data.clear(); + + let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); + assert!(damaged); + assert!(warnings.iter().any(|w| w.contains("could not be decoded"))); +} + +/// A layer whose bounds hold pixels but whose colour and transparency channels are missing +/// lost its pixel data: the open asks before continuing. +#[test] +fn layer_bounds_without_channel_data_mark_conversion_damaged() { + let mut file = testgen::small(Version::Psd, Compression::Raw); + file.layers_mut()[0].channels.retain(|c| c.id == CHANNEL_USER_MASK); + + let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); + assert!(damaged); + assert!(warnings.iter().any(|w| w.contains("no channel data"))); +} + +/// A layer without pixels (an empty layer, or a text or shape layer written without a +/// pixel cache) has empty bounds: nothing is missing, so the file is not damaged even when +/// it lists no colour or transparency channel. +#[test] +fn empty_layer_without_channel_data_is_not_damaged() { + let mut file = testgen::small(Version::Psd, Compression::Raw); + file.layers_mut()[0].channels.retain(|c| c.id == CHANNEL_USER_MASK); + file.layers_mut()[0].rect = Default::default(); + + let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); + assert!(!damaged, "an empty layer marked the PSD damaged: {warnings:?}"); +} + +/// Verifies healthy layer channels do not mark the PSD as damaged. +#[test] +fn valid_layer_channels_keep_conversion_editable() { + let file = testgen::small(Version::Psd, Compression::Raw); + let (_, warnings, damaged) = psd_to_document_decoded_integrity(&file, &photocraft_raster::Interrupt::NONE, None).unwrap(); + assert!(!damaged, "unexpectedly marked good PSD damaged: {warnings:?}"); +} + +#[test] +fn merged_plane_checks_offsets() { + let all = [1u8, 2, 3, 4]; + assert_eq!(merged_plane(&all, 1, 2), Some(&[3u8, 4][..])); + assert_eq!(merged_plane(&all, 2, 2), None); + assert_eq!(merged_plane(&all, usize::MAX, 2), None); +} + +/// Resource 1057's data. +fn version_info(writer: UnicodeString, reader: UnicodeString, has_real_merged_data: bool) -> Vec { + VersionInfo { version: 1, has_real_merged_data, writer, reader, file_version: 1 }.to_bytes() +} + +/// The 1057 PhotoCraft 0.1.0 to 0.7.0 wrote: Photoshop CS6's names, NUL-terminated. +fn version_info_cs6(has_real_merged_data: bool) -> Vec { + version_info(UnicodeString::new_nul("Adobe Photoshop"), UnicodeString::new_nul("Adobe Photoshop CS6"), has_real_merged_data) +} + +/// The 1057 PhotoCraft writes since 0.8.2: Photoshop 2026's bytes, no NUL. +fn version_info_2026(has_real_merged_data: bool) -> Vec { + photocraft_psd::resources::version_info_resource(has_real_merged_data).data +} + +/// An opaque 4 × 1 RGB document with the Photoshop spot oracles' channels in their order: +/// "Spot A", "Alpha 1" and "Spot B", each holding 100, 25, 75 and 0 % in four columns. +fn channels_document(depth: SampleType) -> Document { + let mut doc = Document::with_background("old", Size::new(4, 1), ColorMode::Rgb, depth, photocraft_color::Color::rgb(1.0, 1.0, 1.0)); + let gray = PixelFormat::new(ColorMode::Grayscale, depth, false); + let canvas = doc.bounds(); + let channel = |name: &str, spot: Option<(photocraft_color::Color, f32)>| { + let mut s = Surface::new(gray); + s.write_region(canvas, &[1.0, 0.25, 0.75, 0.0]); + AlphaChannel { spot, ..AlphaChannel::new(name, s) } + }; + doc.channels.push(channel("Spot A", Some((photocraft_color::Color::rgb(0.0, 0.627, 1.0), 0.0)))); + doc.channels.push(channel("Alpha 1", None)); + doc.channels.push(channel("Spot B", Some((photocraft_color::Color::rgb(1.0, 0.0, 0.627), 0.5)))); + doc +} + +/// Each channel's values on an 8-bit scale. +fn ink(doc: &Document) -> Vec> { + doc.channels.iter().map(|c| c.surface.read_region(doc.bounds()).iter().map(|v| (v * 255.0).round() as u8).collect()).collect() +} + +fn spots(doc: &Document) -> Vec { + doc.channels.iter().map(|c| c.spot.is_some()).collect() +} + +/// `doc` (opaque, 8 or 16-bit) saved the way PhotoCraft 0.1.0 to 0.16.0 saved it: spot planes +/// straight (the maximum = solid ink), no 1053, and `version_info` as resource 1057. `padded` +/// lays DisplayInfo out in the 14-byte records of 0.1.0 to 0.7.0. +fn as_earlier_photocraft_saved(doc: &Document, version_info: Vec, padded: bool) -> Vec { + let mut file = crate::psd_export::document_to_psd(doc); + assert!(!file.merged_has_alpha()); + file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS); + for r in &mut file.resources { + match r.id { + ids::VERSION_INFO => r.data = version_info.clone(), + crate::channel_map::DISPLAY_INFO if padded => { + let (version, records) = r.data.split_at(4); + r.data = version.iter().copied().chain(records.chunks(13).flat_map(|rec| rec.iter().copied().chain([0]))).collect(); + } + _ => {} + } + } + let mut planes = file.decode_merged().unwrap(); + let plane = planes.len() / usize::from(file.header.channels); + for (k, c) in doc.channels.iter().enumerate() { + if c.spot.is_some() { + // At 8 and 16 bits the complement of a sample is that of each of its bytes. + planes[(3 + k) * plane..(4 + k) * plane].iter_mut().for_each(|b| *b = !*b); + } + } + file.image_data = ImageData::encode(Compression::Raw, &planes, &file.header).unwrap(); + file.to_bytes().unwrap() +} + +/// PSDs that PhotoCraft 0.1.0 to 0.16.0 saved with spot channels store them straight. They +/// open with the ink they had in those versions (which read every plane straight), whichever +/// 1057 they carry. Saved again, they get Photoshop's polarity and a 1053, and reopen with the +/// same ink. (A 0.1.0 to 0.7.0 file's padded records misread every channel's options after +/// the first, here Spot B's kind, as those versions' successors always have; its ink is kept.) +#[test] +fn spot_planes_from_earlier_photocraft_keep_their_ink() { + for depth in [SampleType::U8, SampleType::U16] { + let doc = channels_document(depth); + let cases = [ + ("0.1.0 to 0.7.0", version_info_cs6(true), true), + ("0.8.2 on", version_info_2026(true), false), + ("0.8.2 on, Maximize Compatibility off", version_info_2026(false), false), + ("0.1.0 to 0.7.0, 13-byte records", version_info_cs6(true), false), + ]; + for (what, version_info, padded) in cases { + let bytes = as_earlier_photocraft_saved(&doc, version_info, padded); + assert!(earlier_photocraft_spot_planes(&PsdFile::from_bytes(&bytes).unwrap()), "{what}"); + let opened = crate::import("old.psd", &bytes).unwrap().document; + assert_eq!(ink(&opened), ink(&doc), "{depth:?} {what}: the ink earlier versions opened"); + assert!(spots(&opened)[0], "{depth:?} {what}"); + if !padded { + assert_eq!(spots(&opened), spots(&doc), "{depth:?} {what}"); + } + let saved = crate::export(&opened, "old.psd", &crate::ExportOptions::default()).unwrap(); + let file = PsdFile::from_bytes(&saved.bytes).unwrap(); + assert!(file.resource(crate::channel_map::ALPHA_IDENTIFIERS).is_some() && !earlier_photocraft_spot_planes(&file), "{what}"); + let again = crate::import("again.psd", &saved.bytes).unwrap().document; + assert_eq!(ink(&again), ink(&doc), "{depth:?} {what}: saved again"); + assert_eq!(spots(&again), spots(&opened), "{depth:?} {what}: saved again"); + } + } +} + +/// A 0.1.0 to 0.7.0 file whose first extra channel is an alpha channel, spots after it. In its +/// 14-byte DisplayInfo records the spots' kind bytes sit where a 13-byte reader (main's, and +/// this one's) doesn't look, so only the padded reading finds a spot for the rule. Every plane +/// is then read straight, as those versions read it, and keeps its ink. The 13-byte reader +/// opens each channel's options from shifted bytes, as on main: here every channel opens as +/// an alpha channel. A spot of 2 % solidity puts a 2 where that reader looks for the kind, so +/// that channel opens as a spot: without the rule its plane would be inverted. Saved again and +/// reopened, every channel keeps its ink and kind. +#[test] +fn an_early_file_with_an_alpha_channel_first_keeps_its_ink() { + for solidity in [0.0, 0.02] { + let mut doc = channels_document(SampleType::U8); + doc.channels.swap(0, 1); + doc.channels[1].spot = Some((photocraft_color::Color::rgb(0.0, 0.627, 1.0), solidity)); + let names: Vec<&str> = doc.channels.iter().map(|c| c.name.as_str()).collect(); + assert_eq!(names, ["Alpha 1", "Spot A", "Spot B"]); + let bytes = as_earlier_photocraft_saved(&doc, version_info_cs6(true), true); + let file = PsdFile::from_bytes(&bytes).unwrap(); + let info = &file.resource(crate::channel_map::DISPLAY_INFO).unwrap().data; + let misread = solidity > 0.0; + assert_eq!(crate::channel_map::spot_flags(info, true, 0), [false, misread, false], "{solidity}: 13-byte records"); + assert!(earlier_photocraft_spot_planes(&file), "{solidity}: found in the 14-byte records"); + let opened = crate::import("old.psd", &bytes).unwrap().document; + assert_eq!(ink(&opened), ink(&doc), "{solidity}: the ink 0.7.0 opened"); + assert_eq!(spots(&opened), [false, misread, false], "{solidity}: kinds as main reads them"); + let saved = crate::export(&opened, "old.psd", &crate::ExportOptions::default()).unwrap(); + let again = crate::import("again.psd", &saved.bytes).unwrap().document; + assert_eq!(ink(&again), ink(&doc), "{solidity}: saved again"); + assert_eq!(spots(&again), spots(&opened), "{solidity}: saved again"); + } +} + +/// A file with spots and no 1053 that no earlier PhotoCraft wrote is read in Photoshop's +/// polarity (0 = solid ink). psd-tools' `cmyk-spot.psd` is one: its 1057 names psd-tools as +/// writer and reader. So is a file with no 1057, with Photoshop CS6's names without the NUL, +/// or with bytes after PhotoCraft's. +#[test] +fn other_files_without_alpha_identifiers_use_photoshop_polarity() { + let doc = channels_document(SampleType::U8); + let mut trailing = version_info_2026(true); + trailing.extend([0, 0]); + let cases = [ + ("psd-tools", Some(version_info(UnicodeString::new("psd-tools 1.10.0"), UnicodeString::new("psd-tools 1.10.0"), true))), + ("no 1057", None), + ("CS6 without a NUL", Some(version_info(UnicodeString::new("Adobe Photoshop"), UnicodeString::new("Adobe Photoshop CS6"), true))), + ("bytes after PhotoCraft's 1057", Some(trailing)), + ]; + for (what, info) in cases { + // Photoshop's polarity, as this version writes it, without 1053. + let mut file = crate::psd_export::document_to_psd(&doc); + file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS && r.id != ids::VERSION_INFO); + file.resources.extend(info.map(|d| ImageResource::new(ids::VERSION_INFO, d))); + let bytes = file.to_bytes().unwrap(); + assert!(!earlier_photocraft_spot_planes(&PsdFile::from_bytes(&bytes).unwrap()), "{what}"); + let opened = crate::import("x.psd", &bytes).unwrap().document; + assert_eq!(ink(&opened), ink(&doc), "{what}"); + assert_eq!(spots(&opened), spots(&doc), "{what}"); + } +} + +/// The rule needs a spot in DisplayInfo and no 1053, besides PhotoCraft's 1057. +#[test] +fn the_earlier_photocraft_rule_needs_a_spot_and_no_alpha_identifiers() { + let mut doc = channels_document(SampleType::U8); + let old = PsdFile::from_bytes(&as_earlier_photocraft_saved(&doc, version_info_2026(true), false)).unwrap(); + assert!(earlier_photocraft_spot_planes(&old)); + let mut with_ids = old.clone(); + with_ids.resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, crate::channel_map::alpha_identifiers(false, 3))); + assert!(!earlier_photocraft_spot_planes(&with_ids), "a 1053"); + let mut no_info = old.clone(); + no_info.resources.retain(|r| r.id != crate::channel_map::DISPLAY_INFO); + assert!(!earlier_photocraft_spot_planes(&no_info), "no DisplayInfo"); + doc.channels.retain(|c| c.spot.is_none()); + let alpha_only = PsdFile::from_bytes(&as_earlier_photocraft_saved(&doc, version_info_2026(true), false)).unwrap(); + assert!(!earlier_photocraft_spot_planes(&alpha_only), "alpha channels only"); +} + +/// `doc` as an earlier PhotoCraft saved a Photoshop file it had opened with the first `kept` +/// of `doc`'s channels: it wrote back the Photoshop file's 1053, `stale_ids`, unchanged and +/// those channels' planes as Photoshop stored them (it had read and written them straight), +/// and stored the channels added after them straight. +fn as_earlier_photocraft_resaved(doc: &Document, stale_ids: &[u32], kept: usize) -> Vec { + let mut file = crate::psd_export::document_to_psd(doc); + file.resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS && r.id != ids::VERSION_INFO); + file.resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, stale_ids.iter().flat_map(|id| id.to_be_bytes()).collect())); + file.resources.push(ImageResource::new(ids::VERSION_INFO, version_info_2026(true))); + let mut planes = file.decode_merged().unwrap(); + let plane = planes.len() / usize::from(file.header.channels); + let first = usize::from(file.header.channels) - doc.channels.len(); + for (k, c) in doc.channels.iter().enumerate().skip(kept) { + if c.spot.is_some() { + planes[(first + k) * plane..(first + k + 1) * plane].iter_mut().for_each(|b| *b = !*b); + } + } + file.image_data = ImageData::encode(Compression::Raw, &planes, &file.header).unwrap(); + file.to_bytes().unwrap() +} + +/// An earlier PhotoCraft kept the 1053 of a Photoshop file it opened and wrote it back +/// unchanged, so a spot channel added there sits behind a 1053 that doesn't list it: a +/// transparent Photoshop document's `[0]` (the white plate of a DTF print, added before +/// saving), the `[0, 3]` of one with a spot channel already, or a `[0]` kept through a +/// flatten that removed the transparency. The added spot is stored straight and keeps its +/// ink; the Photoshop file's own spot keeps Photoshop's polarity. Saved again, both reopen +/// the same. +#[test] +fn a_spot_added_behind_a_kept_alpha_identifiers_resource_keeps_its_ink() { + let transparent = |names: &[&str]| { + let mut doc = channels_document(SampleType::U8); + doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())]; + doc.channels.retain(|c| names.contains(&c.name.as_str())); + doc + }; + let mut flattened = channels_document(SampleType::U8); + flattened.channels.retain(|c| c.name == "Spot A"); + let cases = [ + ("transparent, one spot added", transparent(&["Spot A"]), vec![0], 0), + ("transparent, a Photoshop spot and one added", transparent(&["Spot A", "Spot B"]), vec![0, 3], 1), + ("flattened, one spot added", flattened, vec![0], 0), + ]; + for (what, doc, stale_ids, kept) in cases { + let bytes = as_earlier_photocraft_resaved(&doc, &stale_ids, kept); + let file = PsdFile::from_bytes(&bytes).unwrap(); + assert_eq!(file.merged_has_alpha(), what.starts_with("transparent"), "{what}"); + assert!(earlier_photocraft_spot_planes(&file), "{what}"); + let opened = crate::import("old.psd", &bytes).unwrap().document; + assert_eq!(ink(&opened), ink(&doc), "{what}: the ink earlier versions opened"); + assert_eq!(spots(&opened), spots(&doc), "{what}"); + let saved = crate::export(&opened, "old.psd", &crate::ExportOptions::default()).unwrap(); + let again = crate::import("again.psd", &saved.bytes).unwrap().document; + assert_eq!(ink(&again), ink(&doc), "{what}: saved again"); + } +} + +/// A 1053 that lists every extra channel, as Photoshop and this version write it, keeps the +/// file in Photoshop's polarity, with PhotoCraft's (Photoshop 2026's) 1057 too: a transparent +/// file with a spot, and Photoshop's own `[0]` in a file without a transparency plane. +#[test] +fn a_complete_alpha_identifiers_resource_keeps_photoshop_polarity() { + let mut doc = channels_document(SampleType::U8); + doc.layers = vec![Layer::raster("Layer 1", doc.pixel_format())]; + let bytes = as_earlier_photocraft_resaved(&doc, &[0, 3, 4, 5], 3); + let file = PsdFile::from_bytes(&bytes).unwrap(); + assert!(file.merged_has_alpha()); + assert!(!earlier_photocraft_spot_planes(&file)); + assert_eq!(ink(&crate::import("ps.psd", &bytes).unwrap().document), ink(&doc)); + let mut opaque = channels_document(SampleType::U8); + opaque.channels.clear(); + let mut file = PsdFile::from_bytes(&as_earlier_photocraft_resaved(&opaque, &[0], 0)).unwrap(); + file.resources.retain(|r| r.id != crate::channel_map::DISPLAY_INFO); + file.resources.push(ImageResource::new( + crate::channel_map::DISPLAY_INFO, + crate::channel_map::display_info(&channels_document(SampleType::U8).channels.iter().collect::>(), false), + )); + assert_eq!(photoshop_identified_channels(&file), 0, "0 is the transparency's"); + assert!(!earlier_photocraft_spot_planes(&file), "no channel left unlisted"); +} From 3867f093ac44d525c59ed7c55f5134d6b730882f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:53 +0000 Subject: [PATCH 123/259] refactor(io): move effects_map.rs tests to effects_map/tests.rs --- crates/io/src/effects_map.rs | 344 +---------------------------- crates/io/src/effects_map/tests.rs | 341 ++++++++++++++++++++++++++++ 2 files changed, 342 insertions(+), 343 deletions(-) create mode 100644 crates/io/src/effects_map/tests.rs diff --git a/crates/io/src/effects_map.rs b/crates/io/src/effects_map.rs index 416aa56b56..36aff72a3a 100644 --- a/crates/io/src/effects_map.rs +++ b/crates/io/src/effects_map.rs @@ -641,346 +641,4 @@ pub fn parse_lrfx(data: &[u8]) -> Option<(bool, Vec)> { #[cfg(test)] #[allow(clippy::unreachable)] // clippy.toml exempts unwrap/expect/panic in tests, not unreachable! -mod tests { - use super::*; - - fn sample_effects() -> Vec { - let g = Gradient { - stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], - opacity_stops: vec![(0.0, 1.0), (1.0, 0.5)], - ..Gradient::default() - }; - vec![ - Effect::default_drop_shadow(), - Effect::DropShadow(Shadow { - distance: 9.0, - spread: 0.25, - contour: Contour::Custom { - name: "Cone".into(), - points: vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 0.5, output: 1.0 }, CurvePoint { input: 1.0, output: 0.0 }], - corners: vec![false, true, false], - }, - ..match Effect::default_drop_shadow() { - Effect::DropShadow(s) => s, - _ => unreachable!(), - } - }), - Effect::InnerShadow(Shadow { - knocks_out: false, - ..match Effect::default_drop_shadow() { - Effect::DropShadow(s) => s, - _ => unreachable!(), - } - }), - Effect::OuterGlow(Glow { - common: FxCommon::new(BlendMode::Screen, 0.5), - paint: FxPaint::Color(Color::rgb(1.0, 1.0, 0.0)), - technique: GlowTechnique::Precise, - spread: 0.1, - size: 8.0, - contour: Contour::Linear, - anti_alias: true, - range: 0.5, - jitter: 0.0, - noise: 0.0, - source: GlowSource::Edge, - }), - Effect::InnerGlow(Glow { - common: FxCommon::new(BlendMode::Screen, 0.75), - paint: FxPaint::Gradient(g.clone()), - technique: GlowTechnique::Softer, - spread: 0.0, - size: 5.0, - contour: Contour::Linear, - anti_alias: false, - range: 0.5, - jitter: 0.0, - noise: 0.0, - source: GlowSource::Center, - }), - Effect::Stroke(StrokeFx { - common: FxCommon::new(BlendMode::Normal, 1.0), - size: 3.0, - position: StrokePosition::Inside, - paint: FxPaint::Color(Color::rgb(0.0, 1.0, 0.0)), - overprint: false, - }), - Effect::Stroke(StrokeFx { - common: FxCommon::new(BlendMode::Multiply, 0.5), - size: 6.0, - position: StrokePosition::Center, - paint: FxPaint::Gradient(g.clone()), - overprint: true, - }), - Effect::ColorOverlay { common: FxCommon::new(BlendMode::Overlay, 0.5), color: Color::rgb(0.0, 0.0, 1.0) }, - Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: g, dither: true, interpolation: None }, - Effect::PatternOverlay { - common: FxCommon::new(BlendMode::Normal, 1.0), - name: "Bubbles".into(), - id: "abc".into(), - scale: 1.0, - angle: 15.0, - link: false, - phase: (4.0, 2.0), - }, - Effect::Satin(Satin { - common: FxCommon::new(BlendMode::Multiply, 0.5), - color: Color::BLACK, - angle: 19.0, - distance: 11.0, - size: 14.0, - contour: Contour::Linear, - anti_alias: true, - invert: true, - }), - Effect::BevelEmboss(Bevel { - enabled: true, - style: BevelStyle::Emboss, - technique: BevelTechnique::ChiselSoft, - depth: 1.5, - up: false, - size: 7.0, - soften: 2.0, - angle: 45.0, - altitude: 40.0, - use_global_light: false, - gloss_contour: Contour::Linear, - gloss_anti_alias: true, - highlight: FxCommon::new(BlendMode::Screen, 0.75), - highlight_color: Color::WHITE, - shadow: FxCommon::new(BlendMode::Multiply, 0.6), - shadow_color: Color::BLACK, - contour: Some(BevelContour { contour: Contour::Linear, range: 0.7, anti_alias: true }), - texture: Some(BevelTexture { name: "Bubbles".into(), id: "abc".into(), scale: 0.5, depth: -2.0, invert: true, link: false, phase: (3.0, 1.0) }), - }), - ] - } - - fn approx(a: &[Effect], b: &[Effect]) { - // Colours go through 0..255 doubles; compare via re-serialization. - assert_eq!(a.len(), b.len()); - assert_eq!(write_lfx2(true, a), write_lfx2(true, b)); - } - - /// `approx` compares re-serialized bytes, so a field the writer drops looks equal on both - /// sides: read the Gloss Contour's Anti-aliased back directly. - #[test] - fn bevel_gloss_anti_alias_is_written() { - let fx: Vec = sample_effects().into_iter().filter(|e| matches!(e, Effect::BevelEmboss(_))).collect(); - assert!(matches!(fx.as_slice(), [Effect::BevelEmboss(b)] if b.gloss_anti_alias)); - let (_, back) = parse_lfx2(&write_lfx2(false, &fx)).unwrap(); - assert!(matches!(back.as_slice(), [Effect::BevelEmboss(b)] if b.gloss_anti_alias), "{back:?}"); - } - - #[test] - fn lfx2_roundtrip_all_kinds() { - let fx = sample_effects(); - let data = write_lfx2(false, &fx); - let (master, back) = parse_lfx2(&data).unwrap(); - assert!(!master); - approx(&fx, &back); - // Kind order is canonical: shadows first ... strokes last. - assert!(matches!(back[0], Effect::DropShadow(_))); - assert!(matches!(back.last().unwrap(), Effect::Stroke(_))); - } - - #[test] - fn stroke_overprint_is_read_and_written() { - for overprint in [false, true] { - let fx = [Effect::Stroke(StrokeFx { - common: FxCommon::new(BlendMode::Normal, 1.0), - size: 3.0, - position: StrokePosition::Outside, - paint: FxPaint::Color(Color::BLACK), - overprint, - })]; - let (_, back) = parse_lfx2(&write_lfx2(false, &fx)).unwrap(); - let [Effect::Stroke(s)] = back.as_slice() else { panic!("{back:?}") }; - assert_eq!(s.overprint, overprint); - } - // A stroke without the key (other writers) has Overprint off. - let d = Descriptor::new("null").with("FrFX", Value::Descriptor(Descriptor::new("FrFX").with("enab", Value::Boolean(true)))); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor::new(d).to_bytes()); - let (_, back) = parse_lfx2(&data).unwrap(); - let [Effect::Stroke(s)] = back.as_slice() else { panic!("{back:?}") }; - assert!(!s.overprint); - } - - #[test] - fn lfx2_ignores_absent_effects_but_keeps_disabled_configured_effects() { - let d = Descriptor::new("null") - .with("DrSh", Value::Descriptor(Descriptor::new("DrSh").with("present", Value::Boolean(false)).with("enab", Value::Boolean(false)))) - .with("FrFX", Value::Descriptor(Descriptor::new("FrFX").with("present", Value::Boolean(true)).with("enab", Value::Boolean(false)))) - .with("SoFi", Value::Descriptor(Descriptor::new("SoFi").with("enab", Value::Boolean(false)))); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor::new(d).to_bytes()); - - let (_, effects) = parse_lfx2(&data).unwrap(); - - assert_eq!(effects.len(), 2); - assert!(effects.iter().all(|effect| !effect.enabled())); - assert!(effects.iter().any(|effect| effect.label() == "Stroke")); - assert!(effects.iter().any(|effect| effect.label() == "Color Overlay")); - } - - #[test] - fn multi_instances_use_multi_keys() { - let fx = sample_effects(); - let data = write_lfx2(true, &fx); - let (vd, _) = VersionedDescriptor::parse_prefix(&data[4..]).unwrap(); - assert!(vd.descriptor.get("dropShadowMulti").is_some()); - assert!(vd.descriptor.get("frameFXMulti").is_some()); - assert!(vd.descriptor.get("SoFi").is_some()); - } - - #[test] - fn blend_names_are_unique() { - let mut s = std::collections::HashSet::new(); - for (_, n) in BLEND_NAMES { - assert!(s.insert(n)); - } - } - - #[test] - fn long_string_blend_ids_parse() { - // Some writers store effect modes as long string IDs (`BlnM` `multiply`, `colorDodge`) - // instead of the four-character codes (psd-tools effects/blend-modes.psd). - let long = |v: &str| Value::Enumerated { type_id: Id::new("BlnM"), value: Id::new(v) }; - let d = Descriptor::new("null") - .with("masterFXSwitch", Value::Boolean(true)) - .with("DrSh", Value::Descriptor(Descriptor::new("DrSh").with("enab", Value::Boolean(true)).with("Md ", long("linearBurn")))) - .with("ebbl", Value::Descriptor(Descriptor::new("ebbl").with("hglM", long("colorDodge")).with("sdwM", long("colorBurn")))) - .with("SoFi", Value::Descriptor(Descriptor::new("SoFi").with("Md ", long("hue")))); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor { version: 16, descriptor: d }.to_bytes()); - let (_, fx) = parse_lfx2(&data).unwrap(); - let modes: Vec = fx - .iter() - .flat_map(|e| match e { - Effect::DropShadow(s) => vec![s.common.blend], - Effect::BevelEmboss(b) => vec![b.highlight.blend, b.shadow.blend], - Effect::ColorOverlay { common, .. } => vec![common.blend], - _ => vec![], - }) - .collect(); - assert_eq!(modes, vec![BlendMode::LinearBurn, BlendMode::ColorDodge, BlendMode::ColorBurn, BlendMode::Hue]); - for (m, n) in BLEND_LONG_NAMES { - assert_eq!(blend_from_id(n.as_bytes()), Some(m)); - } - } - - /// A Gradient Overlay `lfx2` laid out as Photoshop writes it: one black colour, opacity - /// 100 → 0 % with the opacity midpoint `mid` (%), Smoothness `intr` (0..4096) and the method - /// enum `gs99` (Photoshop's key in layer effects; codes `Gcls`, `Lnr `, `Perc`). - fn overlay_lfx2(mid: i32, intr: f64, method: &str) -> Vec { - let black = || Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0)); - let clr = |loc: i32| { - Value::Descriptor( - Descriptor::new("Clrt") - .with("Clr ", Value::Descriptor(black())) - .with("Type", Value::Enumerated { type_id: Id::new("Clry"), value: Id::new("UsrS") }) - .with("Lctn", Value::Integer(loc)) - .with("Mdpn", Value::Integer(50)), - ) - }; - let trn = |loc: i32, op: f32, mid: i32| { - Value::Descriptor(Descriptor::new("TrnS").with("Opct", unit(b"#Prc", op)).with("Lctn", Value::Integer(loc)).with("Mdpn", Value::Integer(mid))) - }; - let grad = Descriptor::new("Grdn") - .with("GrdF", Value::Enumerated { type_id: Id::new("GrdF"), value: Id::new("CstS") }) - .with("Intr", Value::Double(intr)) - .with("Clrs", Value::List(vec![clr(0), clr(4096)])) - .with("Trns", Value::List(vec![trn(0, 100.0, 50), trn(4096, 0.0, mid)])); - let fx = Descriptor::new("GrFl") - .with("enab", Value::Boolean(true)) - .with("Grad", Value::Descriptor(grad)) - .with("Angl", unit(b"#Ang", 0.0)) - .with("gs99", Value::Enumerated { type_id: Id::new("gradientInterpolationMethodType"), value: Id::new(method) }); - let d = Descriptor::new("null").with("masterFXSwitch", Value::Boolean(true)).with("GrFl", Value::Descriptor(fx)); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor { version: 16, descriptor: d }.to_bytes()); - data - } - - fn overlay_opacity(data: &[u8]) -> Vec<(f32, f32)> { - let (_, fx) = parse_lfx2(data).unwrap(); - let Some(Effect::GradientOverlay { gradient, .. }) = fx.first() else { panic!("overlay: {fx:?}") }; - gradient.opacity_stops.clone() - } - - fn opacity_at(o: &[(f32, f32)], t: f32) -> f32 { - let i = o.windows(2).position(|w| t >= w[0].0 && t <= w[1].0).unwrap(); - o[i].1 + (o[i + 1].1 - o[i].1) * (t - o[i].0) / (o[i + 1].0 - o[i].0) - } - - /// #1954: the overlay's transparency follows Smoothness, the opacity midpoints and the method - /// like a gradient fill layer's (Photoshop renders both identically; the values are its - /// composites at t = 0.25 and 0.5). - #[test] - fn gradient_overlay_opacity_follows_smoothness_midpoint_and_method() { - let at = |mid, intr, method: &str, t| opacity_at(&overlay_opacity(&overlay_lfx2(mid, intr, method)), t); - // Plain Classic stays the linear fade it is stored as. - assert_eq!(overlay_opacity(&overlay_lfx2(50, 0.0, "Gcls")), vec![(0.0, 1.0), (1.0, 0.0)]); - // Midpoint 25 %: half transparent a quarter of the way. - assert!((at(25, 0.0, "Gcls", 0.25) - 0.5).abs() < 0.01); - // Smoothness 100 % eases the ends (Photoshop: 0.796 at a quarter). - assert!((at(50, 4096.0, "Gcls", 0.25) - 0.796).abs() < 0.015); - // The method bends the transparency ramp too, not only the colours (Photoshop at the - // middle: 0.631 Linear, 0.255 Perceptual). - assert!((at(50, 0.0, "Lnr ", 0.5) - 0.631).abs() < 0.015); - assert!((at(50, 0.0, "Perc", 0.5) - 0.255).abs() < 0.015); - assert!((at(25, 4096.0, "Perc", 0.25) - 0.255).abs() < 0.015); - } - - /// A regenerated `lfx2` carries the baked ramp as plain (Classic, Smoothness 0) stops, so it - /// reads back unchanged. - #[test] - fn baked_overlay_opacity_round_trips() { - let data = overlay_lfx2(25, 4096.0, "Perc"); - let (master, fx) = parse_lfx2(&data).unwrap(); - let a = overlay_opacity(&data); - let b = overlay_opacity(&write_lfx2(master, &fx)); - assert!(a.len() > 2); - assert_eq!(a.len(), b.len()); - for (x, y) in a.iter().zip(&b) { - assert!((x.0 - y.0).abs() < 1e-3 && (x.1 - y.1).abs() < 1e-4, "{x:?} vs {y:?}"); - } - } - - #[test] - fn garbage_is_none() { - assert!(parse_lfx2(&[0, 0]).is_none()); - assert!(parse_lrfx(&[0, 0, 0, 1, b'X']).is_none()); - } - - #[test] - fn lrfx_drop_shadow() { - // version 0, count 1, 'dsdw' v2 record. - let mut d = vec![0, 0, 0, 1]; - d.extend_from_slice(b"8BIMdsdw"); - let mut rec = Vec::new(); - rec.extend_from_slice(&2u32.to_be_bytes()); // version - rec.extend_from_slice(&(7u32 << 16).to_be_bytes()); // blur (16.16) - rec.extend_from_slice(&0u32.to_be_bytes()); // intensity - rec.extend_from_slice(&(90u32 << 16).to_be_bytes()); // angle - rec.extend_from_slice(&(4u32 << 16).to_be_bytes()); // distance - rec.extend_from_slice(&[0, 0, 0xff, 0xff, 0, 0, 0, 0, 0, 0]); // color: red - rec.extend_from_slice(b"8BIMmul "); - rec.extend_from_slice(&[1, 1, 128]); - rec.extend_from_slice(&[0; 10]); - d.extend_from_slice(&(rec.len() as u32).to_be_bytes()); - d.extend(rec); - let (_, fx) = parse_lrfx(&d).unwrap(); - match &fx[0] { - Effect::DropShadow(s) => { - assert_eq!(s.size, 7.0); - assert_eq!(s.distance, 4.0); - assert_eq!(s.common.blend, BlendMode::Multiply); - assert!((s.common.opacity - 128.0 / 255.0).abs() < 1e-6); - assert_eq!(s.color.c[0], 1.0); - } - other => panic!("{other:?}"), - } - } -} +mod tests; diff --git a/crates/io/src/effects_map/tests.rs b/crates/io/src/effects_map/tests.rs new file mode 100644 index 0000000000..3944739fb8 --- /dev/null +++ b/crates/io/src/effects_map/tests.rs @@ -0,0 +1,341 @@ +use super::*; + +fn sample_effects() -> Vec { + let g = Gradient { + stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], + opacity_stops: vec![(0.0, 1.0), (1.0, 0.5)], + ..Gradient::default() + }; + vec![ + Effect::default_drop_shadow(), + Effect::DropShadow(Shadow { + distance: 9.0, + spread: 0.25, + contour: Contour::Custom { + name: "Cone".into(), + points: vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 0.5, output: 1.0 }, CurvePoint { input: 1.0, output: 0.0 }], + corners: vec![false, true, false], + }, + ..match Effect::default_drop_shadow() { + Effect::DropShadow(s) => s, + _ => unreachable!(), + } + }), + Effect::InnerShadow(Shadow { + knocks_out: false, + ..match Effect::default_drop_shadow() { + Effect::DropShadow(s) => s, + _ => unreachable!(), + } + }), + Effect::OuterGlow(Glow { + common: FxCommon::new(BlendMode::Screen, 0.5), + paint: FxPaint::Color(Color::rgb(1.0, 1.0, 0.0)), + technique: GlowTechnique::Precise, + spread: 0.1, + size: 8.0, + contour: Contour::Linear, + anti_alias: true, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source: GlowSource::Edge, + }), + Effect::InnerGlow(Glow { + common: FxCommon::new(BlendMode::Screen, 0.75), + paint: FxPaint::Gradient(g.clone()), + technique: GlowTechnique::Softer, + spread: 0.0, + size: 5.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source: GlowSource::Center, + }), + Effect::Stroke(StrokeFx { + common: FxCommon::new(BlendMode::Normal, 1.0), + size: 3.0, + position: StrokePosition::Inside, + paint: FxPaint::Color(Color::rgb(0.0, 1.0, 0.0)), + overprint: false, + }), + Effect::Stroke(StrokeFx { + common: FxCommon::new(BlendMode::Multiply, 0.5), + size: 6.0, + position: StrokePosition::Center, + paint: FxPaint::Gradient(g.clone()), + overprint: true, + }), + Effect::ColorOverlay { common: FxCommon::new(BlendMode::Overlay, 0.5), color: Color::rgb(0.0, 0.0, 1.0) }, + Effect::GradientOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), gradient: g, dither: true, interpolation: None }, + Effect::PatternOverlay { + common: FxCommon::new(BlendMode::Normal, 1.0), + name: "Bubbles".into(), + id: "abc".into(), + scale: 1.0, + angle: 15.0, + link: false, + phase: (4.0, 2.0), + }, + Effect::Satin(Satin { + common: FxCommon::new(BlendMode::Multiply, 0.5), + color: Color::BLACK, + angle: 19.0, + distance: 11.0, + size: 14.0, + contour: Contour::Linear, + anti_alias: true, + invert: true, + }), + Effect::BevelEmboss(Bevel { + enabled: true, + style: BevelStyle::Emboss, + technique: BevelTechnique::ChiselSoft, + depth: 1.5, + up: false, + size: 7.0, + soften: 2.0, + angle: 45.0, + altitude: 40.0, + use_global_light: false, + gloss_contour: Contour::Linear, + gloss_anti_alias: true, + highlight: FxCommon::new(BlendMode::Screen, 0.75), + highlight_color: Color::WHITE, + shadow: FxCommon::new(BlendMode::Multiply, 0.6), + shadow_color: Color::BLACK, + contour: Some(BevelContour { contour: Contour::Linear, range: 0.7, anti_alias: true }), + texture: Some(BevelTexture { name: "Bubbles".into(), id: "abc".into(), scale: 0.5, depth: -2.0, invert: true, link: false, phase: (3.0, 1.0) }), + }), + ] +} + +fn approx(a: &[Effect], b: &[Effect]) { + // Colours go through 0..255 doubles; compare via re-serialization. + assert_eq!(a.len(), b.len()); + assert_eq!(write_lfx2(true, a), write_lfx2(true, b)); +} + +/// `approx` compares re-serialized bytes, so a field the writer drops looks equal on both +/// sides: read the Gloss Contour's Anti-aliased back directly. +#[test] +fn bevel_gloss_anti_alias_is_written() { + let fx: Vec = sample_effects().into_iter().filter(|e| matches!(e, Effect::BevelEmboss(_))).collect(); + assert!(matches!(fx.as_slice(), [Effect::BevelEmboss(b)] if b.gloss_anti_alias)); + let (_, back) = parse_lfx2(&write_lfx2(false, &fx)).unwrap(); + assert!(matches!(back.as_slice(), [Effect::BevelEmboss(b)] if b.gloss_anti_alias), "{back:?}"); +} + +#[test] +fn lfx2_roundtrip_all_kinds() { + let fx = sample_effects(); + let data = write_lfx2(false, &fx); + let (master, back) = parse_lfx2(&data).unwrap(); + assert!(!master); + approx(&fx, &back); + // Kind order is canonical: shadows first ... strokes last. + assert!(matches!(back[0], Effect::DropShadow(_))); + assert!(matches!(back.last().unwrap(), Effect::Stroke(_))); +} + +#[test] +fn stroke_overprint_is_read_and_written() { + for overprint in [false, true] { + let fx = [Effect::Stroke(StrokeFx { + common: FxCommon::new(BlendMode::Normal, 1.0), + size: 3.0, + position: StrokePosition::Outside, + paint: FxPaint::Color(Color::BLACK), + overprint, + })]; + let (_, back) = parse_lfx2(&write_lfx2(false, &fx)).unwrap(); + let [Effect::Stroke(s)] = back.as_slice() else { panic!("{back:?}") }; + assert_eq!(s.overprint, overprint); + } + // A stroke without the key (other writers) has Overprint off. + let d = Descriptor::new("null").with("FrFX", Value::Descriptor(Descriptor::new("FrFX").with("enab", Value::Boolean(true)))); + let mut data = 0u32.to_be_bytes().to_vec(); + data.extend(VersionedDescriptor::new(d).to_bytes()); + let (_, back) = parse_lfx2(&data).unwrap(); + let [Effect::Stroke(s)] = back.as_slice() else { panic!("{back:?}") }; + assert!(!s.overprint); +} + +#[test] +fn lfx2_ignores_absent_effects_but_keeps_disabled_configured_effects() { + let d = Descriptor::new("null") + .with("DrSh", Value::Descriptor(Descriptor::new("DrSh").with("present", Value::Boolean(false)).with("enab", Value::Boolean(false)))) + .with("FrFX", Value::Descriptor(Descriptor::new("FrFX").with("present", Value::Boolean(true)).with("enab", Value::Boolean(false)))) + .with("SoFi", Value::Descriptor(Descriptor::new("SoFi").with("enab", Value::Boolean(false)))); + let mut data = 0u32.to_be_bytes().to_vec(); + data.extend(VersionedDescriptor::new(d).to_bytes()); + + let (_, effects) = parse_lfx2(&data).unwrap(); + + assert_eq!(effects.len(), 2); + assert!(effects.iter().all(|effect| !effect.enabled())); + assert!(effects.iter().any(|effect| effect.label() == "Stroke")); + assert!(effects.iter().any(|effect| effect.label() == "Color Overlay")); +} + +#[test] +fn multi_instances_use_multi_keys() { + let fx = sample_effects(); + let data = write_lfx2(true, &fx); + let (vd, _) = VersionedDescriptor::parse_prefix(&data[4..]).unwrap(); + assert!(vd.descriptor.get("dropShadowMulti").is_some()); + assert!(vd.descriptor.get("frameFXMulti").is_some()); + assert!(vd.descriptor.get("SoFi").is_some()); +} + +#[test] +fn blend_names_are_unique() { + let mut s = std::collections::HashSet::new(); + for (_, n) in BLEND_NAMES { + assert!(s.insert(n)); + } +} + +#[test] +fn long_string_blend_ids_parse() { + // Some writers store effect modes as long string IDs (`BlnM` `multiply`, `colorDodge`) + // instead of the four-character codes (psd-tools effects/blend-modes.psd). + let long = |v: &str| Value::Enumerated { type_id: Id::new("BlnM"), value: Id::new(v) }; + let d = Descriptor::new("null") + .with("masterFXSwitch", Value::Boolean(true)) + .with("DrSh", Value::Descriptor(Descriptor::new("DrSh").with("enab", Value::Boolean(true)).with("Md ", long("linearBurn")))) + .with("ebbl", Value::Descriptor(Descriptor::new("ebbl").with("hglM", long("colorDodge")).with("sdwM", long("colorBurn")))) + .with("SoFi", Value::Descriptor(Descriptor::new("SoFi").with("Md ", long("hue")))); + let mut data = 0u32.to_be_bytes().to_vec(); + data.extend(VersionedDescriptor { version: 16, descriptor: d }.to_bytes()); + let (_, fx) = parse_lfx2(&data).unwrap(); + let modes: Vec = fx + .iter() + .flat_map(|e| match e { + Effect::DropShadow(s) => vec![s.common.blend], + Effect::BevelEmboss(b) => vec![b.highlight.blend, b.shadow.blend], + Effect::ColorOverlay { common, .. } => vec![common.blend], + _ => vec![], + }) + .collect(); + assert_eq!(modes, vec![BlendMode::LinearBurn, BlendMode::ColorDodge, BlendMode::ColorBurn, BlendMode::Hue]); + for (m, n) in BLEND_LONG_NAMES { + assert_eq!(blend_from_id(n.as_bytes()), Some(m)); + } +} + +/// A Gradient Overlay `lfx2` laid out as Photoshop writes it: one black colour, opacity +/// 100 → 0 % with the opacity midpoint `mid` (%), Smoothness `intr` (0..4096) and the method +/// enum `gs99` (Photoshop's key in layer effects; codes `Gcls`, `Lnr `, `Perc`). +fn overlay_lfx2(mid: i32, intr: f64, method: &str) -> Vec { + let black = || Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0)); + let clr = |loc: i32| { + Value::Descriptor( + Descriptor::new("Clrt") + .with("Clr ", Value::Descriptor(black())) + .with("Type", Value::Enumerated { type_id: Id::new("Clry"), value: Id::new("UsrS") }) + .with("Lctn", Value::Integer(loc)) + .with("Mdpn", Value::Integer(50)), + ) + }; + let trn = |loc: i32, op: f32, mid: i32| { + Value::Descriptor(Descriptor::new("TrnS").with("Opct", unit(b"#Prc", op)).with("Lctn", Value::Integer(loc)).with("Mdpn", Value::Integer(mid))) + }; + let grad = Descriptor::new("Grdn") + .with("GrdF", Value::Enumerated { type_id: Id::new("GrdF"), value: Id::new("CstS") }) + .with("Intr", Value::Double(intr)) + .with("Clrs", Value::List(vec![clr(0), clr(4096)])) + .with("Trns", Value::List(vec![trn(0, 100.0, 50), trn(4096, 0.0, mid)])); + let fx = Descriptor::new("GrFl") + .with("enab", Value::Boolean(true)) + .with("Grad", Value::Descriptor(grad)) + .with("Angl", unit(b"#Ang", 0.0)) + .with("gs99", Value::Enumerated { type_id: Id::new("gradientInterpolationMethodType"), value: Id::new(method) }); + let d = Descriptor::new("null").with("masterFXSwitch", Value::Boolean(true)).with("GrFl", Value::Descriptor(fx)); + let mut data = 0u32.to_be_bytes().to_vec(); + data.extend(VersionedDescriptor { version: 16, descriptor: d }.to_bytes()); + data +} + +fn overlay_opacity(data: &[u8]) -> Vec<(f32, f32)> { + let (_, fx) = parse_lfx2(data).unwrap(); + let Some(Effect::GradientOverlay { gradient, .. }) = fx.first() else { panic!("overlay: {fx:?}") }; + gradient.opacity_stops.clone() +} + +fn opacity_at(o: &[(f32, f32)], t: f32) -> f32 { + let i = o.windows(2).position(|w| t >= w[0].0 && t <= w[1].0).unwrap(); + o[i].1 + (o[i + 1].1 - o[i].1) * (t - o[i].0) / (o[i + 1].0 - o[i].0) +} + +/// #1954: the overlay's transparency follows Smoothness, the opacity midpoints and the method +/// like a gradient fill layer's (Photoshop renders both identically; the values are its +/// composites at t = 0.25 and 0.5). +#[test] +fn gradient_overlay_opacity_follows_smoothness_midpoint_and_method() { + let at = |mid, intr, method: &str, t| opacity_at(&overlay_opacity(&overlay_lfx2(mid, intr, method)), t); + // Plain Classic stays the linear fade it is stored as. + assert_eq!(overlay_opacity(&overlay_lfx2(50, 0.0, "Gcls")), vec![(0.0, 1.0), (1.0, 0.0)]); + // Midpoint 25 %: half transparent a quarter of the way. + assert!((at(25, 0.0, "Gcls", 0.25) - 0.5).abs() < 0.01); + // Smoothness 100 % eases the ends (Photoshop: 0.796 at a quarter). + assert!((at(50, 4096.0, "Gcls", 0.25) - 0.796).abs() < 0.015); + // The method bends the transparency ramp too, not only the colours (Photoshop at the + // middle: 0.631 Linear, 0.255 Perceptual). + assert!((at(50, 0.0, "Lnr ", 0.5) - 0.631).abs() < 0.015); + assert!((at(50, 0.0, "Perc", 0.5) - 0.255).abs() < 0.015); + assert!((at(25, 4096.0, "Perc", 0.25) - 0.255).abs() < 0.015); +} + +/// A regenerated `lfx2` carries the baked ramp as plain (Classic, Smoothness 0) stops, so it +/// reads back unchanged. +#[test] +fn baked_overlay_opacity_round_trips() { + let data = overlay_lfx2(25, 4096.0, "Perc"); + let (master, fx) = parse_lfx2(&data).unwrap(); + let a = overlay_opacity(&data); + let b = overlay_opacity(&write_lfx2(master, &fx)); + assert!(a.len() > 2); + assert_eq!(a.len(), b.len()); + for (x, y) in a.iter().zip(&b) { + assert!((x.0 - y.0).abs() < 1e-3 && (x.1 - y.1).abs() < 1e-4, "{x:?} vs {y:?}"); + } +} + +#[test] +fn garbage_is_none() { + assert!(parse_lfx2(&[0, 0]).is_none()); + assert!(parse_lrfx(&[0, 0, 0, 1, b'X']).is_none()); +} + +#[test] +fn lrfx_drop_shadow() { + // version 0, count 1, 'dsdw' v2 record. + let mut d = vec![0, 0, 0, 1]; + d.extend_from_slice(b"8BIMdsdw"); + let mut rec = Vec::new(); + rec.extend_from_slice(&2u32.to_be_bytes()); // version + rec.extend_from_slice(&(7u32 << 16).to_be_bytes()); // blur (16.16) + rec.extend_from_slice(&0u32.to_be_bytes()); // intensity + rec.extend_from_slice(&(90u32 << 16).to_be_bytes()); // angle + rec.extend_from_slice(&(4u32 << 16).to_be_bytes()); // distance + rec.extend_from_slice(&[0, 0, 0xff, 0xff, 0, 0, 0, 0, 0, 0]); // color: red + rec.extend_from_slice(b"8BIMmul "); + rec.extend_from_slice(&[1, 1, 128]); + rec.extend_from_slice(&[0; 10]); + d.extend_from_slice(&(rec.len() as u32).to_be_bytes()); + d.extend(rec); + let (_, fx) = parse_lrfx(&d).unwrap(); + match &fx[0] { + Effect::DropShadow(s) => { + assert_eq!(s.size, 7.0); + assert_eq!(s.distance, 4.0); + assert_eq!(s.common.blend, BlendMode::Multiply); + assert!((s.common.opacity - 128.0 / 255.0).abs() < 1e-6); + assert_eq!(s.color.c[0], 1.0); + } + other => panic!("{other:?}"), + } +} From a50edcebb088c8109ec56a774828edf84c40f164 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:53 +0000 Subject: [PATCH 124/259] refactor(raw): move nefc.rs tests to nefc/tests.rs --- crates/raw/src/nefc.rs | 309 +---------------------------------- crates/raw/src/nefc/tests.rs | 306 ++++++++++++++++++++++++++++++++++ 2 files changed, 307 insertions(+), 308 deletions(-) create mode 100644 crates/raw/src/nefc/tests.rs diff --git a/crates/raw/src/nefc.rs b/crates/raw/src/nefc.rs index 2ae312917d..e09d934b4b 100644 --- a/crates/raw/src/nefc.rs +++ b/crates/raw/src/nefc.rs @@ -381,311 +381,4 @@ pub(crate) fn read_compressed(t: &Tiff, raw: &Ifd, note: Option<&(Tiff, Ifd)>, l } #[cfg(test)] -mod tests { - use super::*; - - /// MSB-first bit writer for the test encoder. - #[derive(Default)] - struct Writer { - out: Vec, - acc: u64, - n: u32, - } - - impl Writer { - fn put(&mut self, v: u32, len: u32) { - for i in (0..len).rev() { - self.acc = (self.acc << 1) | u64::from((v >> i) & 1); - self.n += 1; - if self.n == 8 { - self.out.push(self.acc as u8); - self.acc = 0; - self.n = 0; - } - } - } - fn finish(mut self) -> Vec { - if self.n > 0 { - self.out.push((self.acc << (8 - self.n)) as u8); - } - self.out.extend_from_slice(&[0; 4]); - self.out - } - } - - /// `(code, length)` per category, from the canonical table. - fn codes(t: &Table) -> Vec<(u32, u32)> { - let mut out = vec![(0, 0); 17]; - let mut code = 0u32; - let mut symbols = t.symbols.iter(); - for (i, &n) in t.counts.iter().enumerate() { - for _ in 0..n { - let s = *symbols.next().unwrap(); - if s != UNSEEN { - out[s as usize] = (code, i as u32 + 1); - } - code += 1; - } - code <<= 1; - } - out - } - - /// Encodes `values` (samples or curve indices) the way the camera does. - fn encode(values: &[i32], w: usize, t: &Table, seeds: [[i32; 2]; 2]) -> Vec { - let codes = codes(t); - let mut wr = Writer::default(); - let mut vpred = seeds; - for (y, row) in values.chunks(w).enumerate() { - for (x, &v) in row.iter().enumerate() { - let pred = if x < 2 { vpred[y & 1][x] } else { row[x - 2] }; - if x < 2 { - vpred[y & 1][x] = v; - } - let d = v - pred; - let k = 32 - d.unsigned_abs().leading_zeros(); - let (code, len) = codes[k as usize]; - assert!(len > 0, "no code for category {k}"); - wr.put(code, len); - wr.put(if d < 0 { (d + (1 << k) - 1) as u32 } else { d as u32 }, k); - } - } - wr.finish() - } - - /// Smooth gradient + texture + hard edges, within `0..=max`. - fn image(w: usize, h: usize, max: i32, seed: u32) -> Vec { - let mut s = seed; - (0..w * h) - .map(|i| { - let (x, y) = ((i % w) as i32, (i / w) as i32); - s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - let noise = (s >> 24) as i32 % 9 - 4; - let base = (x * 37 + y * 11) % (max / 2) + if (x / 7 + y / 5) % 3 == 0 { max / 3 } else { 0 }; - (base + noise).clamp(0, max) - }) - .collect() - } - - fn lossless(bits: u32) -> DecodeTable { - let s = 1 << (bits - 3); - DecodeTable { encoding: Encoding::Lossless, seeds: [[s, s], [s, s]] } - } - - fn lossy_table(bits: u32, le: bool) -> Vec { - let mut t = vec![0x44, 0x20]; - let put = |t: &mut Vec, v: u16| t.extend_from_slice(&if le { v.to_le_bytes() } else { v.to_be_bytes() }); - for _ in 0..4 { - put(&mut t, 300); - } - put(&mut t, 257); - let max = f64::from((1u32 << bits) - 1); - for i in 0..257u32 { - put(&mut t, (max * (f64::from(i) / 64.0).min(1.0).sqrt()) as u16); - } - t.resize(624, 0); - t - } - - #[test] - fn tables_are_prefix_codes() { - for t in [LOSSLESS_12, LOSSLESS_14, LOSSY_12, LOSSY_14] { - assert_eq!(t.counts.iter().map(|&c| c as usize).sum::(), t.symbols.len()); - let kraft: f64 = t.counts.iter().enumerate().map(|(i, &c)| f64::from(c) / f64::from(1u32 << (i + 1))).sum(); - assert!(kraft <= 1.0); - assert!(Huffman::new(&t).is_ok()); - } - } - - #[test] - fn lossless_round_trip_12_and_14() { - for (bits, t) in [(12, LOSSLESS_12), (14, LOSSLESS_14)] { - let (w, h) = (64, 9); - let max = (1 << bits) - 1; - let mut img = image(w, h, max, bits); - img[5] = 0; - img[7] = max; - img[w + 9] = max; - let table = lossless(bits); - let out = decode(&encode(&img, w, &t, table.seeds), w, h, bits, &table).unwrap(); - assert_eq!(out, img.iter().map(|&v| v as u16).collect::>(), "{bits}-bit"); - } - } - - #[test] - fn lossy_type2_curve_and_round_trip() { - for (bits, t) in [(12u32, LOSSY_12), (14, LOSSY_14)] { - for le in [false, true] { - let table = parse_table(&lossy_table(bits, le), le, bits).unwrap(); - assert_eq!(table.seeds, [[300, 300], [300, 300]]); - let Encoding::Lossy(curve) = &table.encoding else { panic!() }; - let step = (1usize << bits) / 256; - assert_eq!(curve.len(), (1 << bits) + 1); - assert_eq!(curve[64 * step], (1 << bits) - 1); - assert!(curve.windows(2).all(|p| p[0] <= p[1])); - let (w, h) = (48, 7); - let img = image(w, h, 64 * step as i32 - 1, 7); - let out = decode(&encode(&img, w, &t, table.seeds), w, h, bits, &table).unwrap(); - assert_eq!(out, img.iter().map(|&v| curve[v as usize]).collect::>()); - } - } - } - - #[test] - fn lossy_type1_full_curve() { - let mut t = vec![0x44, 0x10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 5]; - for v in [0u16, 100, 400, 900, 1600] { - t.extend_from_slice(&v.to_be_bytes()); - } - let table = parse_table(&t, false, 12).unwrap(); - assert_eq!(table.encoding, Encoding::Lossy(vec![0, 100, 400, 900, 1600])); - let img = vec![0, 4, 1, 3, 2, 2, 4, 0]; - assert_eq!(decode(&encode(&img, 4, &LOSSY_12, table.seeds), 4, 2, 12, &table).unwrap(), vec![0, 1600, 100, 900, 400, 400, 1600, 0]); - } - - #[test] - fn unsupported_and_malformed_tables() { - let unsupported = |r: Result| matches!(r, Err(RawError::Unsupported(_))); - let malformed = |r: Result| matches!(r, Err(RawError::Malformed(_))); - let mut split = lossy_table(12, false); - split[562..564].copy_from_slice(&345u16.to_be_bytes()); - assert!(unsupported(parse_table(&split, false, 12))); - assert!(unsupported(parse_table(&[0x49, 0x30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], false, 12))); - assert!(unsupported(parse_table(&lossy_table(12, false), false, 16))); - assert!(malformed(parse_table(&[], false, 12))); - assert!(malformed(parse_table(&[0x46, 0x30, 8], false, 14))); - assert!(malformed(parse_table(&lossy_table(12, false)[..100], false, 12))); - let mut odd = lossy_table(12, false); - odd[10..12].copy_from_slice(&300u16.to_be_bytes()); - assert!(parse_table(&odd, false, 12).is_err()); - assert!(parse_table(&[0x44, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], false, 12).is_err()); - } - - #[test] - fn modern_lossy_curve_preserves_sensor_adus_at_both_depths() { - for bits in [12u32, 14] { - for le in [false, true] { - let put = |v: u16| if le { v.to_le_bytes() } else { v.to_be_bytes() }; - let mut t = vec![0x44, 0x40]; - for _ in 0..4 { - t.extend(put(256)); - } - t.extend(put(257)); - let white = (1u16 << bits) - 1; - for i in 0..=256u32 { - t.extend(put(((i * 64).min(u32::from(white))) as u16)); - } - t.resize(624, 0); - let parsed = parse_table(&t, le, bits).unwrap(); - let Encoding::Lossy(curve) = &parsed.encoding else { panic!() }; - let range = 1usize << (bits - 2); - assert_eq!(curve.len(), range + 1); - assert_eq!(curve[range], white); - // Stored point 16 is 1024 ADU. It belongs to encoded code 256 - // at 14 bits, code 64 at 12 bits, independent of end-point clipping. - assert_eq!(curve[range / 16], 1024.min(white)); - let indices = vec![0, (range / 16) as i32, (range / 8) as i32, (range / 32) as i32]; - let huffman = if bits == 12 { &LOSSY_12 } else { &LOSSY_14 }; - let src = encode(&indices, 2, huffman, parsed.seeds); - assert_eq!(decode(&src, 2, 2, bits, &parsed).unwrap(), vec![0, 1024, 2048, 512]); - } - } - } - - /// A 14-bit lossless table (version 0x46) with the given seeds. - fn lossless_table(seed: u16, le: bool) -> Vec { - let mut t = vec![0x46, 0x30]; - for _ in 0..4 { - t.extend_from_slice(&if le { seed.to_le_bytes() } else { seed.to_be_bytes() }); - } - t.resize(46, 0); - t - } - - #[test] - fn decodes_through_the_nef_container() { - use crate::testgen::{Val, nef_compressed}; - use crate::{Limits, RawFormat, identify}; - let (w, h) = (40usize, 6usize); - // lossless 14-bit, big-endian maker note, with a BlackLevel tag - let img = image(w, h, 16383, 11); - let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]); - let note = vec![(0x0096, Val::Undefined(lossless_table(2048, false))), (0x003d, Val::Short(vec![600, 600, 600, 600]))]; - let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, note); - assert_eq!(identify(&b), Some(RawFormat::Nef)); - let s = crate::decode(&b, &Limits::default()).unwrap(); - assert_eq!(s.data, img.iter().map(|&v| v as u16).collect::>()); - assert_eq!(s.black.values, vec![600.0; 4]); - // lossy 12-bit type 2, little-endian maker note (newer bodies); the - // 12-bit BlackLevel is scaled from 14-bit units - let table = lossy_table(12, true); - let t = parse_table(&table, true, 12).unwrap(); - let Encoding::Lossy(curve) = &t.encoding else { panic!() }; - let img = image(w, h, 1023, 5); - let src = encode(&img, w, &LOSSY_12, t.seeds); - let note = vec![(0x0096, Val::Undefined(table.clone())), (0x003d, Val::Short(vec![600, 600, 600, 600]))]; - let s = crate::decode(&nef_compressed(w, h, 12, src.clone(), [2, 1, 1, 0], false, note), &Limits::default()).unwrap(); - assert_eq!(s.data, img.iter().map(|&v| curve[v as usize]).collect::>()); - assert_eq!(s.black.values, vec![150.0; 4]); - assert!(crate::develop_sensor(&s, &crate::DevelopOptions::default()).is_ok()); - // "lossy after split" and a missing table stay unsupported (preview fallback) - let mut split = table; - split[562..564].copy_from_slice(&3u16.to_le_bytes()); - let e = crate::decode(&nef_compressed(w, h, 12, src.clone(), [2, 1, 1, 0], false, vec![(0x0096, Val::Undefined(split))]), &Limits::default()); - assert!(matches!(e, Err(RawError::Unsupported(_))), "{e:?}"); - let e = crate::decode(&nef_compressed(w, h, 12, src, [2, 1, 1, 0], false, vec![(0x0001, Val::Short(vec![0]))]), &Limits::default()); - assert!(matches!(&e, Err(RawError::Unsupported(m)) if m.contains("Nikon compressed NEF")), "{e:?}"); - } - - #[test] - fn nikon_without_black_level_tag_is_black_subtracted() { - use crate::testgen::{Val, nef_compressed}; - let (w, h) = (32usize, 8usize); - let img = image(w, h, 16383, 4); - let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]); - let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, vec![(0x0096, Val::Undefined(lossless_table(2048, false)))]); - let s = crate::decode(&b, &crate::Limits::default()).unwrap(); - assert_eq!(s.black.values, vec![0.0]); - assert!(!s.warnings.iter().any(|w| w.contains("black level")), "{:?}", s.warnings); - } - - #[test] - fn truncated_container_never_panics() { - use crate::testgen::{Val, nef_compressed}; - let (w, h) = (32usize, 8usize); - let img = image(w, h, 16383, 2); - let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]); - let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, vec![(0x0096, Val::Undefined(lossless_table(2048, false)))]); - for n in 0..b.len() { - let _ = crate::decode(&b[..n], &crate::Limits::default()); - } - } - - #[test] - fn truncated_and_corrupt_streams_error_never_panic() { - let (w, h) = (64, 16); - let table = lossless(14); - let img = image(w, h, 16383, 3); - let src = encode(&img, w, &LOSSLESS_14, table.seeds); - for cut in [0, 1, 10, src.len() / 2, src.len() - 40] { - assert!(decode(&src[..cut], w, h, 14, &table).is_err(), "cut {cut}"); - } - let mut s = 12345u32; - for i in 0..200 { - let mut bad = src.clone(); - for _ in 0..1 + i % 8 { - s = s.wrapping_mul(1_103_515_245).wrapping_add(12345); - let at = (s >> 8) as usize % bad.len(); - bad[at] ^= 1 << (s % 8); - } - let _ = decode(&bad, w, h, 14, &table); - let noise: Vec = (0..src.len()).map(|k| ((k as u32).wrapping_mul(2_654_435_761) >> (i % 24)) as u8).collect(); - let _ = decode(&noise, w, h, 14, &table); - let _ = decode(&noise, w, h, 12, &lossless(12)); - } - let lossy = parse_table(&lossy_table(12, false), false, 12).unwrap(); - assert!(decode(&[0xff; 64], 8, 8, 12, &lossy).is_err()); - assert!(decode(&src, usize::MAX, 2, 14, &table).is_err()); - assert!(decode(&src, 0, 2, 14, &table).is_err()); - } -} +mod tests; diff --git a/crates/raw/src/nefc/tests.rs b/crates/raw/src/nefc/tests.rs new file mode 100644 index 0000000000..296f850093 --- /dev/null +++ b/crates/raw/src/nefc/tests.rs @@ -0,0 +1,306 @@ +use super::*; + +/// MSB-first bit writer for the test encoder. +#[derive(Default)] +struct Writer { + out: Vec, + acc: u64, + n: u32, +} + +impl Writer { + fn put(&mut self, v: u32, len: u32) { + for i in (0..len).rev() { + self.acc = (self.acc << 1) | u64::from((v >> i) & 1); + self.n += 1; + if self.n == 8 { + self.out.push(self.acc as u8); + self.acc = 0; + self.n = 0; + } + } + } + fn finish(mut self) -> Vec { + if self.n > 0 { + self.out.push((self.acc << (8 - self.n)) as u8); + } + self.out.extend_from_slice(&[0; 4]); + self.out + } +} + +/// `(code, length)` per category, from the canonical table. +fn codes(t: &Table) -> Vec<(u32, u32)> { + let mut out = vec![(0, 0); 17]; + let mut code = 0u32; + let mut symbols = t.symbols.iter(); + for (i, &n) in t.counts.iter().enumerate() { + for _ in 0..n { + let s = *symbols.next().unwrap(); + if s != UNSEEN { + out[s as usize] = (code, i as u32 + 1); + } + code += 1; + } + code <<= 1; + } + out +} + +/// Encodes `values` (samples or curve indices) the way the camera does. +fn encode(values: &[i32], w: usize, t: &Table, seeds: [[i32; 2]; 2]) -> Vec { + let codes = codes(t); + let mut wr = Writer::default(); + let mut vpred = seeds; + for (y, row) in values.chunks(w).enumerate() { + for (x, &v) in row.iter().enumerate() { + let pred = if x < 2 { vpred[y & 1][x] } else { row[x - 2] }; + if x < 2 { + vpred[y & 1][x] = v; + } + let d = v - pred; + let k = 32 - d.unsigned_abs().leading_zeros(); + let (code, len) = codes[k as usize]; + assert!(len > 0, "no code for category {k}"); + wr.put(code, len); + wr.put(if d < 0 { (d + (1 << k) - 1) as u32 } else { d as u32 }, k); + } + } + wr.finish() +} + +/// Smooth gradient + texture + hard edges, within `0..=max`. +fn image(w: usize, h: usize, max: i32, seed: u32) -> Vec { + let mut s = seed; + (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as i32, (i / w) as i32); + s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let noise = (s >> 24) as i32 % 9 - 4; + let base = (x * 37 + y * 11) % (max / 2) + if (x / 7 + y / 5) % 3 == 0 { max / 3 } else { 0 }; + (base + noise).clamp(0, max) + }) + .collect() +} + +fn lossless(bits: u32) -> DecodeTable { + let s = 1 << (bits - 3); + DecodeTable { encoding: Encoding::Lossless, seeds: [[s, s], [s, s]] } +} + +fn lossy_table(bits: u32, le: bool) -> Vec { + let mut t = vec![0x44, 0x20]; + let put = |t: &mut Vec, v: u16| t.extend_from_slice(&if le { v.to_le_bytes() } else { v.to_be_bytes() }); + for _ in 0..4 { + put(&mut t, 300); + } + put(&mut t, 257); + let max = f64::from((1u32 << bits) - 1); + for i in 0..257u32 { + put(&mut t, (max * (f64::from(i) / 64.0).min(1.0).sqrt()) as u16); + } + t.resize(624, 0); + t +} + +#[test] +fn tables_are_prefix_codes() { + for t in [LOSSLESS_12, LOSSLESS_14, LOSSY_12, LOSSY_14] { + assert_eq!(t.counts.iter().map(|&c| c as usize).sum::(), t.symbols.len()); + let kraft: f64 = t.counts.iter().enumerate().map(|(i, &c)| f64::from(c) / f64::from(1u32 << (i + 1))).sum(); + assert!(kraft <= 1.0); + assert!(Huffman::new(&t).is_ok()); + } +} + +#[test] +fn lossless_round_trip_12_and_14() { + for (bits, t) in [(12, LOSSLESS_12), (14, LOSSLESS_14)] { + let (w, h) = (64, 9); + let max = (1 << bits) - 1; + let mut img = image(w, h, max, bits); + img[5] = 0; + img[7] = max; + img[w + 9] = max; + let table = lossless(bits); + let out = decode(&encode(&img, w, &t, table.seeds), w, h, bits, &table).unwrap(); + assert_eq!(out, img.iter().map(|&v| v as u16).collect::>(), "{bits}-bit"); + } +} + +#[test] +fn lossy_type2_curve_and_round_trip() { + for (bits, t) in [(12u32, LOSSY_12), (14, LOSSY_14)] { + for le in [false, true] { + let table = parse_table(&lossy_table(bits, le), le, bits).unwrap(); + assert_eq!(table.seeds, [[300, 300], [300, 300]]); + let Encoding::Lossy(curve) = &table.encoding else { panic!() }; + let step = (1usize << bits) / 256; + assert_eq!(curve.len(), (1 << bits) + 1); + assert_eq!(curve[64 * step], (1 << bits) - 1); + assert!(curve.windows(2).all(|p| p[0] <= p[1])); + let (w, h) = (48, 7); + let img = image(w, h, 64 * step as i32 - 1, 7); + let out = decode(&encode(&img, w, &t, table.seeds), w, h, bits, &table).unwrap(); + assert_eq!(out, img.iter().map(|&v| curve[v as usize]).collect::>()); + } + } +} + +#[test] +fn lossy_type1_full_curve() { + let mut t = vec![0x44, 0x10, 0, 10, 0, 10, 0, 10, 0, 10, 0, 5]; + for v in [0u16, 100, 400, 900, 1600] { + t.extend_from_slice(&v.to_be_bytes()); + } + let table = parse_table(&t, false, 12).unwrap(); + assert_eq!(table.encoding, Encoding::Lossy(vec![0, 100, 400, 900, 1600])); + let img = vec![0, 4, 1, 3, 2, 2, 4, 0]; + assert_eq!(decode(&encode(&img, 4, &LOSSY_12, table.seeds), 4, 2, 12, &table).unwrap(), vec![0, 1600, 100, 900, 400, 400, 1600, 0]); +} + +#[test] +fn unsupported_and_malformed_tables() { + let unsupported = |r: Result| matches!(r, Err(RawError::Unsupported(_))); + let malformed = |r: Result| matches!(r, Err(RawError::Malformed(_))); + let mut split = lossy_table(12, false); + split[562..564].copy_from_slice(&345u16.to_be_bytes()); + assert!(unsupported(parse_table(&split, false, 12))); + assert!(unsupported(parse_table(&[0x49, 0x30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], false, 12))); + assert!(unsupported(parse_table(&lossy_table(12, false), false, 16))); + assert!(malformed(parse_table(&[], false, 12))); + assert!(malformed(parse_table(&[0x46, 0x30, 8], false, 14))); + assert!(malformed(parse_table(&lossy_table(12, false)[..100], false, 12))); + let mut odd = lossy_table(12, false); + odd[10..12].copy_from_slice(&300u16.to_be_bytes()); + assert!(parse_table(&odd, false, 12).is_err()); + assert!(parse_table(&[0x44, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], false, 12).is_err()); +} + +#[test] +fn modern_lossy_curve_preserves_sensor_adus_at_both_depths() { + for bits in [12u32, 14] { + for le in [false, true] { + let put = |v: u16| if le { v.to_le_bytes() } else { v.to_be_bytes() }; + let mut t = vec![0x44, 0x40]; + for _ in 0..4 { + t.extend(put(256)); + } + t.extend(put(257)); + let white = (1u16 << bits) - 1; + for i in 0..=256u32 { + t.extend(put(((i * 64).min(u32::from(white))) as u16)); + } + t.resize(624, 0); + let parsed = parse_table(&t, le, bits).unwrap(); + let Encoding::Lossy(curve) = &parsed.encoding else { panic!() }; + let range = 1usize << (bits - 2); + assert_eq!(curve.len(), range + 1); + assert_eq!(curve[range], white); + // Stored point 16 is 1024 ADU. It belongs to encoded code 256 + // at 14 bits, code 64 at 12 bits, independent of end-point clipping. + assert_eq!(curve[range / 16], 1024.min(white)); + let indices = vec![0, (range / 16) as i32, (range / 8) as i32, (range / 32) as i32]; + let huffman = if bits == 12 { &LOSSY_12 } else { &LOSSY_14 }; + let src = encode(&indices, 2, huffman, parsed.seeds); + assert_eq!(decode(&src, 2, 2, bits, &parsed).unwrap(), vec![0, 1024, 2048, 512]); + } + } +} + +/// A 14-bit lossless table (version 0x46) with the given seeds. +fn lossless_table(seed: u16, le: bool) -> Vec { + let mut t = vec![0x46, 0x30]; + for _ in 0..4 { + t.extend_from_slice(&if le { seed.to_le_bytes() } else { seed.to_be_bytes() }); + } + t.resize(46, 0); + t +} + +#[test] +fn decodes_through_the_nef_container() { + use crate::testgen::{Val, nef_compressed}; + use crate::{Limits, RawFormat, identify}; + let (w, h) = (40usize, 6usize); + // lossless 14-bit, big-endian maker note, with a BlackLevel tag + let img = image(w, h, 16383, 11); + let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]); + let note = vec![(0x0096, Val::Undefined(lossless_table(2048, false))), (0x003d, Val::Short(vec![600, 600, 600, 600]))]; + let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, note); + assert_eq!(identify(&b), Some(RawFormat::Nef)); + let s = crate::decode(&b, &Limits::default()).unwrap(); + assert_eq!(s.data, img.iter().map(|&v| v as u16).collect::>()); + assert_eq!(s.black.values, vec![600.0; 4]); + // lossy 12-bit type 2, little-endian maker note (newer bodies); the + // 12-bit BlackLevel is scaled from 14-bit units + let table = lossy_table(12, true); + let t = parse_table(&table, true, 12).unwrap(); + let Encoding::Lossy(curve) = &t.encoding else { panic!() }; + let img = image(w, h, 1023, 5); + let src = encode(&img, w, &LOSSY_12, t.seeds); + let note = vec![(0x0096, Val::Undefined(table.clone())), (0x003d, Val::Short(vec![600, 600, 600, 600]))]; + let s = crate::decode(&nef_compressed(w, h, 12, src.clone(), [2, 1, 1, 0], false, note), &Limits::default()).unwrap(); + assert_eq!(s.data, img.iter().map(|&v| curve[v as usize]).collect::>()); + assert_eq!(s.black.values, vec![150.0; 4]); + assert!(crate::develop_sensor(&s, &crate::DevelopOptions::default()).is_ok()); + // "lossy after split" and a missing table stay unsupported (preview fallback) + let mut split = table; + split[562..564].copy_from_slice(&3u16.to_le_bytes()); + let e = crate::decode(&nef_compressed(w, h, 12, src.clone(), [2, 1, 1, 0], false, vec![(0x0096, Val::Undefined(split))]), &Limits::default()); + assert!(matches!(e, Err(RawError::Unsupported(_))), "{e:?}"); + let e = crate::decode(&nef_compressed(w, h, 12, src, [2, 1, 1, 0], false, vec![(0x0001, Val::Short(vec![0]))]), &Limits::default()); + assert!(matches!(&e, Err(RawError::Unsupported(m)) if m.contains("Nikon compressed NEF")), "{e:?}"); +} + +#[test] +fn nikon_without_black_level_tag_is_black_subtracted() { + use crate::testgen::{Val, nef_compressed}; + let (w, h) = (32usize, 8usize); + let img = image(w, h, 16383, 4); + let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]); + let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, vec![(0x0096, Val::Undefined(lossless_table(2048, false)))]); + let s = crate::decode(&b, &crate::Limits::default()).unwrap(); + assert_eq!(s.black.values, vec![0.0]); + assert!(!s.warnings.iter().any(|w| w.contains("black level")), "{:?}", s.warnings); +} + +#[test] +fn truncated_container_never_panics() { + use crate::testgen::{Val, nef_compressed}; + let (w, h) = (32usize, 8usize); + let img = image(w, h, 16383, 2); + let src = encode(&img, w, &LOSSLESS_14, [[2048; 2]; 2]); + let b = nef_compressed(w, h, 14, src, [0, 1, 1, 2], true, vec![(0x0096, Val::Undefined(lossless_table(2048, false)))]); + for n in 0..b.len() { + let _ = crate::decode(&b[..n], &crate::Limits::default()); + } +} + +#[test] +fn truncated_and_corrupt_streams_error_never_panic() { + let (w, h) = (64, 16); + let table = lossless(14); + let img = image(w, h, 16383, 3); + let src = encode(&img, w, &LOSSLESS_14, table.seeds); + for cut in [0, 1, 10, src.len() / 2, src.len() - 40] { + assert!(decode(&src[..cut], w, h, 14, &table).is_err(), "cut {cut}"); + } + let mut s = 12345u32; + for i in 0..200 { + let mut bad = src.clone(); + for _ in 0..1 + i % 8 { + s = s.wrapping_mul(1_103_515_245).wrapping_add(12345); + let at = (s >> 8) as usize % bad.len(); + bad[at] ^= 1 << (s % 8); + } + let _ = decode(&bad, w, h, 14, &table); + let noise: Vec = (0..src.len()).map(|k| ((k as u32).wrapping_mul(2_654_435_761) >> (i % 24)) as u8).collect(); + let _ = decode(&noise, w, h, 14, &table); + let _ = decode(&noise, w, h, 12, &lossless(12)); + } + let lossy = parse_table(&lossy_table(12, false), false, 12).unwrap(); + assert!(decode(&[0xff; 64], 8, 8, 12, &lossy).is_err()); + assert!(decode(&src, usize::MAX, 2, 14, &table).is_err()); + assert!(decode(&src, 0, 2, 14, &table).is_err()); +} From bfb3ca12f2e4d501c0d9ed0343771749d353e12d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:54 +0000 Subject: [PATCH 125/259] refactor(gpu): move plan.rs tests to plan/tests.rs --- crates/gpu/src/plan.rs | 344 +---------------------------------- crates/gpu/src/plan/tests.rs | 341 ++++++++++++++++++++++++++++++++++ 2 files changed, 342 insertions(+), 343 deletions(-) create mode 100644 crates/gpu/src/plan/tests.rs diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs index 38cc879b09..a9a266e97a 100644 --- a/crates/gpu/src/plan.rs +++ b/crates/gpu/src/plan.rs @@ -1884,346 +1884,4 @@ fn single_content_pass(layer: &Layer) -> bool { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_color::{Color, ColorMode, SampleType}; - use photocraft_geom::Size; - - #[test] - fn nested_pass_through_groups_with_clipped_layers_are_not_planned_exponentially() { - let mut layers = vec![Layer::raster("leaf", photocraft_color::PixelFormat::RGBA8)]; - for _ in 0..30 { - let group = Layer::group("g", layers); - let mut clipped = Layer::raster("c", photocraft_color::PixelFormat::RGBA8); - clipped.clipped = true; - layers = vec![group, clipped]; - } - let mut doc = Document::new("nest", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); - doc.layers = layers; - let started = std::time::Instant::now(); - let Err(error) = plan(&doc) else { panic!("2^30 plannings must be refused") }; - assert!(error.0.contains("too many nested layers"), "{}", error.0); - assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed()); - } - - #[test] - fn stops_closer_than_one_lut_step_stay_on_the_cpu() { - assert!(check_gradient_stops(&[(0.4999_f32, ()), (0.5, ())]).is_err()); - assert!(check_gradient_stops(&[(0.0_f32, ()), (1.0, ())]).is_ok()); - } - - #[test] - fn lab_channel_adjustments_defer_to_the_cpu_in_lab_documents() { - let lab_rules = [ - Adjustment::Invert, - Adjustment::Posterize { levels: 4 }, - Adjustment::Threshold { level: 0.5 }, - Adjustment::BrightnessContrast { brightness: 10.0, contrast: 5.0, legacy: false }, - Adjustment::GradientMap { stops: vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])], reverse: false, dither: false }, - ]; - for adj in &lab_rules { - assert!(!adjustment_on_gpu(adj, ColorMode::Lab), "{adj:?}"); - for mode in [ColorMode::Rgb, ColorMode::Grayscale] { - assert!(adjustment_on_gpu(adj, mode), "{adj:?} in {mode:?}"); - } - // CMYK documents invert, posterize, threshold and brighten their inks, on the CPU. - let inks = !matches!(adj, Adjustment::GradientMap { .. }); - assert_eq!(adjustment_on_gpu(adj, ColorMode::Cmyk), !inks, "{adj:?} in CMYK"); - } - // CMYK Hue/Saturation works on the inks (on the CPU); Colorize stays on the screen colour. - let ranges = photocraft_doc::adjust::HueRange::defaults(); - let hue = |colorize| Adjustment::HueSaturation { hue: 30.0, saturation: 10.0, lightness: 0.0, colorize, ranges: ranges.clone() }; - assert!(!adjustment_on_gpu(&hue(false), ColorMode::Cmyk) && adjustment_on_gpu(&hue(true), ColorMode::Cmyk)); - assert!(adjustment_on_gpu(&hue(false), ColorMode::Rgb)); - // Screen-colour adjustments stay on the GPU in Lab documents. - assert!(adjustment_on_gpu(&Adjustment::Exposure { exposure: 1.0, offset: 0.0, gamma: 1.0 }, ColorMode::Lab)); - } - - #[test] - fn native_cmyk_fills_fall_back_only_without_a_valid_cache() { - use photocraft_doc::{FillCache, GradientStyle}; - for depth in photocraft_color::SampleType::ALL { - for fill in [Fill::Solid(Color::WHITE), Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false)] { - let mut doc = Document::new("CMYK", photocraft_geom::Size::new(3, 2), photocraft_color::ColorMode::Cmyk, depth); - doc.layers.push(Layer::new("Fill", LayerContent::Fill(fill.clone()))); - assert!(plan(&doc).unwrap_err().0.contains("native CMYK fill")); - doc.layers[0].visible = false; - assert!(plan(&doc).is_ok()); - doc.layers[0].visible = true; - doc.layers[0].fill_cache = Some(FillCache { fill, surface: photocraft_raster::Surface::new(doc.pixel_format()) }); - assert!(plan(&doc).is_ok()); - doc.layers[0].fill_cache.as_mut().unwrap().fill = Fill::Solid(Color::TRANSPARENT); - assert!(plan(&doc).is_err()); - doc.mode = photocraft_color::ColorMode::Rgb; - assert!(plan(&doc).is_ok()); - } - } - } - #[test] - fn outer_glow_plan_knocks_out_see_through_fill() { - use photocraft_doc::{Contour, FxCommon, GlowSource, GlowTechnique}; - - for fill in [0.0, 0.4, 1.0] { - let mut d = Document::with_background("glow", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let mut layer = Layer::raster("frame", d.pixel_format()); - layer.surface_mut().unwrap().fill_rect(Rect::new(16, 16, 48, 48), &[1.0, 0.0, 0.0, 1.0]); - layer.fill_opacity = fill; - layer.effects.items.push(Effect::OuterGlow(Glow { - common: FxCommon::new(BlendMode::Normal, 1.0), - paint: FxPaint::Color(Color::rgb(1.0, 1.0, 0.0)), - technique: GlowTechnique::Softer, - spread: 0.3, - size: 8.0, - contour: Contour::Linear, - anti_alias: false, - range: 0.5, - jitter: 0.0, - noise: 0.0, - source: GlowSource::Edge, - })); - d.layers.push(layer); - let planned = plan(&d).unwrap(); - let glow = planned - .passes - .iter() - .find(|pass| { - pass.kernel == Kernel::FxPaint && pass.flags & F_KNOCKOUT != 0 && pass.color[0] > 0.9 && pass.color[1] > 0.9 && pass.color[2] < 0.1 - }) - .expect("outer glow paint pass"); - assert!((glow.extra[3] - (1.0 - fill)).abs() < 1e-6, "fill {fill}"); - } - } - - #[test] - fn color_lookup_with_an_overflowing_stored_size_uploads_no_table() { - for size in [1 << 22, u32::MAX] { - let a = Adjustment::ColorLookup { name: "x".into(), lut: Some(std::sync::Arc::new(vec![0.5; 24])), size, tetrahedral: false, dither: false }; - let (kind, _, rows) = adjustment_program(&a, Transfer::Srgb, SampleType::U8, photocraft_color::ColorMode::Rgb); - assert_eq!((kind, rows.is_none()), (0, true), "size {size}"); - } - } - - #[test] - fn root_checkpoints_have_only_one_live_input_and_keep_clips_whole() { - for mode in [BlendMode::Normal, BlendMode::PassThrough] { - let mut d = Document::with_background("t", Size::new(32, 24), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let mut clip = Layer::new("clip", LayerContent::Fill(Fill::Solid(Color::rgba(0.2, 0.3, 0.7, 0.4)))); - clip.clipped = true; - let mut group = Layer::group( - "group", - vec![ - Layer::new("fill", LayerContent::Fill(Fill::Solid(Color::rgba(0.9, 0.1, 0.3, 0.6)))), - Layer::new("invert", LayerContent::Adjustment(Adjustment::Invert)), - ], - ); - group.blend = mode; - d.layers.extend([group, clip, Layer::new("top", LayerContent::Adjustment(Adjustment::Invert))]); - let plan = plan(&d).unwrap(); - assert_eq!(plan.checkpoints.iter().map(|c| c.layer_end).collect::>(), vec![1, 3, 4]); - for checkpoint in &plan.checkpoints { - let mut written = std::collections::HashSet::from([checkpoint.slot]); - for pass in &plan.passes[checkpoint.pass_end..] { - for input in [pass.a, pass.b, pass.c, pass.d].into_iter().flatten() { - assert!(written.contains(&input), "a suffix must not need another saved slot: {checkpoint:?}"); - } - written.insert(pass.dst); - } - assert!(written.contains(&plan.root)); - } - } - } - - #[test] - fn slots_are_recycled() { - let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); - for i in 0..10 { - d.layers.push(Layer::raster(format!("l{i}"), d.pixel_format())); - } - let p = plan(&d).unwrap(); - // Empty layers draw nothing: the clear and the background's one fused pass. - assert_eq!(p.passes.len(), 1 + 1); - for (i, l) in d.layers.iter_mut().skip(1).enumerate() { - l.surface_mut().unwrap().fill_rect(Rect::new(i as i32 % 4, 0, 4, 8), &[0.0, 0.0, 1.0, 1.0]); - } - let p = plan(&d).unwrap(); - assert!(p.slots <= 3, "{} slots", p.slots); - // The background, then each small layer blended over its bounds and copied back. - assert_eq!(p.passes.len(), 1 + 1 + 10 * 2); - } - - #[test] - fn small_layers_composite_only_over_their_bounds() { - let mut d = Document::with_background("t", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let mut l = Layer::raster("small", d.pixel_format()); - l.surface_mut().unwrap().fill_rect(Rect::new(10, 12, 20, 30), &[1.0, 0.0, 0.0, 1.0]); - let mut group = Layer::group("g", vec![l]); - group.blend = BlendMode::Normal; - d.layers.push(group); - let p = plan(&d).unwrap(); - let r = Rect::new(10, 12, 20, 30); - // The group's content, its blend and the copy back are all limited to the layer. - assert!(p.passes.iter().filter(|p| matches!(p.kernel, Kernel::Content | Kernel::Blend)).skip(2).all(|p| p.clip == Some(r)), "{:?}", p.passes); - let last = p.passes.last().unwrap(); - assert_eq!((last.kernel, last.dst, last.clip), (Kernel::CopyRect, p.root, Some(r))); - // A layer that covers most of the canvas composites everywhere. - d.layers[1].children_mut().unwrap()[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 60, 60), &[1.0, 0.0, 0.0, 1.0]); - let p = plan(&d).unwrap(); - assert!(p.passes.iter().all(|p| p.clip.is_none())); - } - - #[test] - fn effects_are_planned_in_place() { - let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let mut l = Layer::raster("fx", d.pixel_format()); - l.surface_mut().unwrap().fill_rect(Rect::new(2, 2, 5, 5), &[1.0, 0.0, 0.0, 1.0]); - l.effects.items.push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::WHITE }); - l.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); - d.layers.push(l); - let p = plan(&d).unwrap(); - assert_eq!(p.fx.len(), 1); - let m = photocraft_compose::effects::margin(&d.layers[1]); - assert_eq!(p.fx[0].region, Rect::new(2, 2, 5, 5).inflate(m).intersect(&d.bounds().inflate(m))); - // The effect region covers the whole canvas: the merged result is the backdrop, no copy. - assert!(p.fx[0].region.contains_rect(&d.bounds())); - let last = p.passes.last().unwrap(); - assert_eq!(last.kernel, Kernel::FxMerge); - assert_eq!(last.dst, p.root); - assert!(p.slots <= 6, "{} slots", p.slots); - // On a larger canvas the result lands back in the backdrop slot over the region only. - let mut big = Document::with_background("t", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE); - big.layers.push(d.layers[1].clone()); - let p = plan(&big).unwrap(); - assert!(!p.fx[0].region.contains_rect(&big.bounds())); - let last = p.passes.last().unwrap(); - assert_eq!((last.kernel, last.dst, last.clip), (Kernel::CopyRect, p.root, Some(p.fx[0].region))); - } - - #[test] - fn exterior_effects_merge_from_the_shape() { - // A drop shadow alone: the layer's pixels, the shadow, the merge. With an interior effect - // the layer is built in passes of its own (colour inside the shape, the overlay, alpha). - let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let mut l = Layer::raster("fx", d.pixel_format()); - l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[1.0, 0.0, 0.0, 0.5]); - l.fill_opacity = 0.7; - l.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); - d.layers.push(l); - let p = plan(&d).unwrap(); - let fx: Vec = p.passes.iter().skip(2).map(|p| p.kernel).collect(); - assert_eq!(fx, [Kernel::Content, Kernel::FxPaint, Kernel::FxMerge], "{:?}", p.passes); - let merge = p.passes.last().unwrap(); - assert!(merge.flags & F_LAYER_SHAPE != 0); - assert_eq!(merge.params[0][0], 0.7); - d.layers[1] - .effects - .items - .push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::WHITE }); - let p = plan(&d).unwrap(); - assert!(p.passes.iter().all(|p| p.flags & F_LAYER_SHAPE == 0)); - assert!(p.passes.iter().any(|p| p.kernel == Kernel::FxInit)); - } - - #[test] - fn opaque_fill_layers_skip_what_they_cover() { - let opaque = || Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 30.0, 1.0, photocraft_doc::GradientStyle::Linear, false); - let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); - for i in 0..4 { - // Small painted layers (empty ones plan no passes at all). - let mut l = Layer::raster(format!("l{i}"), d.pixel_format()); - l.surface_mut().unwrap().fill_rect(Rect::new(i, i, i + 2, i + 2), &[0.0, 0.0, 1.0, 1.0]); - d.layers.push(l); - } - d.layers.push(Layer::new("g", LayerContent::Fill(opaque()))); - let mut top = Layer::raster("top", d.pixel_format()); - top.clipped = true; - d.layers.push(top); - // Clear, then the fill and its clipped layer: the background and four rasters are skipped. - let skipped = plan(&d).unwrap().passes.len(); - let mut alone = d.clone(); - alone.layers.drain(..5); - assert_eq!(skipped, plan(&alone).unwrap().passes.len()); - // Anything that lets the layers below show through keeps them. - let see_through: [fn(&mut Layer); 6] = [ - |l| l.opacity = 0.99, - |l| l.fill_opacity = 0.5, - |l| l.blend = BlendMode::Multiply, - |l| l.visible = false, - |l| l.excluded_channels = 1, - |l| { - if let LayerContent::Fill(Fill::Gradient { opacity_stops, .. }) = &mut l.content { - opacity_stops.push((1.0, 0.5)); - } - }, - ]; - for (k, f) in see_through.iter().enumerate() { - let mut d2 = d.clone(); - f(&mut d2.layers[5]); - assert!(plan(&d2).unwrap().passes.len() > skipped, "case {k}: the layers below are planned"); - assert!(!photocraft_compose::occludes_below(&d2.layers[5], ColorMode::Rgb), "case {k}"); - } - let mut translucent = d.clone(); - translucent.layers[5].content = LayerContent::Fill(Fill::Solid(Color::rgba(1.0, 0.0, 0.0, 0.5))); - assert!(!photocraft_compose::occludes_below(&translucent.layers[5], ColorMode::Rgb)); - assert!(photocraft_compose::occludes_below(&d.layers[5], ColorMode::Rgb)); - } - - #[test] - fn blend_if_plans_on_the_gpu() { - let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let mut l = Layer::raster("bi", d.pixel_format()); - l.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); - l.blend_if.set(0, [photocraft_doc::BlendRange { black: [40, 40], white: [255, 255] }, photocraft_doc::BlendRange::FULL]); - d.layers.push(l.clone()); - let blend_if = |d: &Document| plan(d).unwrap().passes.iter().filter(|p| p.flags & F_BLEND_IF != 0).count(); - assert_eq!(blend_if(&d), 1); - // Clipped layers too. - l.clipped = true; - d.layers[1].blend_if = Default::default(); - d.layers.push(l); - assert_eq!(blend_if(&d), 1); - // Outside RGB, Grayscale and Duotone the setting round-trips without applying. - d.mode = ColorMode::Lab; - assert_eq!(blend_if(&d), 0); - } - - #[test] - fn blend_if_params_pack_every_range_exactly() { - let mut bi = photocraft_doc::BlendIf::default(); - bi.set(3, [photocraft_doc::BlendRange { black: [255, 255], white: [0, 1] }, photocraft_doc::BlendRange { black: [12, 200], white: [201, 254] }]); - let f: Vec = blend_if_params(&bi).iter().flatten().copied().collect(); - // Entry 3 (B), this layer then underlying; unset entries are full ranges. - assert_eq!(&f[12..16], &[255.0 * 256.0 + 255.0, 1.0, 12.0 * 256.0 + 200.0, 201.0 * 256.0 + 254.0]); - assert_eq!(&f[0..2], &[0.0, 255.0 * 256.0 + 255.0]); - } - - #[test] - fn advanced_blending_falls_back_to_the_cpu() { - use photocraft_doc::Knockout; - let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); - let mut l = Layer::raster("ko", d.pixel_format()); - l.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); - d.layers.push(l.clone()); - assert!(plan(&d).is_ok(), "defaults stay on the GPU"); - // Switches with nothing to act on (no effects, no clipped layers) stay on the GPU too. - d.layers[1].advanced.blend_interior = true; - d.layers[1].advanced.blend_clipped = false; - assert!(plan(&d).is_ok()); - d.layers[1].advanced.knockout = Knockout::Deep; - assert!(plan(&d).unwrap_err().0.contains("Advanced Blending")); - // Inside groups and clipping groups. - d.layers[1].advanced.knockout = Knockout::None; - let mut c = l.clone(); - c.clipped = true; - d.layers.push(c.clone()); - assert!(plan(&d).is_err(), "clipped layers blended individually"); - d.layers[1].advanced.blend_clipped = true; - assert!(plan(&d).is_ok()); - d.layers[2].advanced.knockout = Knockout::Shallow; - assert!(plan(&d).is_err(), "clipped knockout"); - d.layers.truncate(1); - let mut inner = l; - inner.advanced.knockout = Knockout::Shallow; - d.layers.push(Layer::group("g", vec![inner])); - assert!(plan(&d).is_err(), "knockout inside a group"); - } -} +mod tests; diff --git a/crates/gpu/src/plan/tests.rs b/crates/gpu/src/plan/tests.rs new file mode 100644 index 0000000000..9807732927 --- /dev/null +++ b/crates/gpu/src/plan/tests.rs @@ -0,0 +1,341 @@ +use super::*; +use photocraft_color::{Color, ColorMode, SampleType}; +use photocraft_geom::Size; + +#[test] +fn nested_pass_through_groups_with_clipped_layers_are_not_planned_exponentially() { + let mut layers = vec![Layer::raster("leaf", photocraft_color::PixelFormat::RGBA8)]; + for _ in 0..30 { + let group = Layer::group("g", layers); + let mut clipped = Layer::raster("c", photocraft_color::PixelFormat::RGBA8); + clipped.clipped = true; + layers = vec![group, clipped]; + } + let mut doc = Document::new("nest", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + doc.layers = layers; + let started = std::time::Instant::now(); + let Err(error) = plan(&doc) else { panic!("2^30 plannings must be refused") }; + assert!(error.0.contains("too many nested layers"), "{}", error.0); + assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed()); +} + +#[test] +fn stops_closer_than_one_lut_step_stay_on_the_cpu() { + assert!(check_gradient_stops(&[(0.4999_f32, ()), (0.5, ())]).is_err()); + assert!(check_gradient_stops(&[(0.0_f32, ()), (1.0, ())]).is_ok()); +} + +#[test] +fn lab_channel_adjustments_defer_to_the_cpu_in_lab_documents() { + let lab_rules = [ + Adjustment::Invert, + Adjustment::Posterize { levels: 4 }, + Adjustment::Threshold { level: 0.5 }, + Adjustment::BrightnessContrast { brightness: 10.0, contrast: 5.0, legacy: false }, + Adjustment::GradientMap { stops: vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])], reverse: false, dither: false }, + ]; + for adj in &lab_rules { + assert!(!adjustment_on_gpu(adj, ColorMode::Lab), "{adj:?}"); + for mode in [ColorMode::Rgb, ColorMode::Grayscale] { + assert!(adjustment_on_gpu(adj, mode), "{adj:?} in {mode:?}"); + } + // CMYK documents invert, posterize, threshold and brighten their inks, on the CPU. + let inks = !matches!(adj, Adjustment::GradientMap { .. }); + assert_eq!(adjustment_on_gpu(adj, ColorMode::Cmyk), !inks, "{adj:?} in CMYK"); + } + // CMYK Hue/Saturation works on the inks (on the CPU); Colorize stays on the screen colour. + let ranges = photocraft_doc::adjust::HueRange::defaults(); + let hue = |colorize| Adjustment::HueSaturation { hue: 30.0, saturation: 10.0, lightness: 0.0, colorize, ranges: ranges.clone() }; + assert!(!adjustment_on_gpu(&hue(false), ColorMode::Cmyk) && adjustment_on_gpu(&hue(true), ColorMode::Cmyk)); + assert!(adjustment_on_gpu(&hue(false), ColorMode::Rgb)); + // Screen-colour adjustments stay on the GPU in Lab documents. + assert!(adjustment_on_gpu(&Adjustment::Exposure { exposure: 1.0, offset: 0.0, gamma: 1.0 }, ColorMode::Lab)); +} + +#[test] +fn native_cmyk_fills_fall_back_only_without_a_valid_cache() { + use photocraft_doc::{FillCache, GradientStyle}; + for depth in photocraft_color::SampleType::ALL { + for fill in [Fill::Solid(Color::WHITE), Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false)] { + let mut doc = Document::new("CMYK", photocraft_geom::Size::new(3, 2), photocraft_color::ColorMode::Cmyk, depth); + doc.layers.push(Layer::new("Fill", LayerContent::Fill(fill.clone()))); + assert!(plan(&doc).unwrap_err().0.contains("native CMYK fill")); + doc.layers[0].visible = false; + assert!(plan(&doc).is_ok()); + doc.layers[0].visible = true; + doc.layers[0].fill_cache = Some(FillCache { fill, surface: photocraft_raster::Surface::new(doc.pixel_format()) }); + assert!(plan(&doc).is_ok()); + doc.layers[0].fill_cache.as_mut().unwrap().fill = Fill::Solid(Color::TRANSPARENT); + assert!(plan(&doc).is_err()); + doc.mode = photocraft_color::ColorMode::Rgb; + assert!(plan(&doc).is_ok()); + } + } +} +#[test] +fn outer_glow_plan_knocks_out_see_through_fill() { + use photocraft_doc::{Contour, FxCommon, GlowSource, GlowTechnique}; + + for fill in [0.0, 0.4, 1.0] { + let mut d = Document::with_background("glow", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut layer = Layer::raster("frame", d.pixel_format()); + layer.surface_mut().unwrap().fill_rect(Rect::new(16, 16, 48, 48), &[1.0, 0.0, 0.0, 1.0]); + layer.fill_opacity = fill; + layer.effects.items.push(Effect::OuterGlow(Glow { + common: FxCommon::new(BlendMode::Normal, 1.0), + paint: FxPaint::Color(Color::rgb(1.0, 1.0, 0.0)), + technique: GlowTechnique::Softer, + spread: 0.3, + size: 8.0, + contour: Contour::Linear, + anti_alias: false, + range: 0.5, + jitter: 0.0, + noise: 0.0, + source: GlowSource::Edge, + })); + d.layers.push(layer); + let planned = plan(&d).unwrap(); + let glow = planned + .passes + .iter() + .find(|pass| { + pass.kernel == Kernel::FxPaint && pass.flags & F_KNOCKOUT != 0 && pass.color[0] > 0.9 && pass.color[1] > 0.9 && pass.color[2] < 0.1 + }) + .expect("outer glow paint pass"); + assert!((glow.extra[3] - (1.0 - fill)).abs() < 1e-6, "fill {fill}"); + } +} + +#[test] +fn color_lookup_with_an_overflowing_stored_size_uploads_no_table() { + for size in [1 << 22, u32::MAX] { + let a = Adjustment::ColorLookup { name: "x".into(), lut: Some(std::sync::Arc::new(vec![0.5; 24])), size, tetrahedral: false, dither: false }; + let (kind, _, rows) = adjustment_program(&a, Transfer::Srgb, SampleType::U8, photocraft_color::ColorMode::Rgb); + assert_eq!((kind, rows.is_none()), (0, true), "size {size}"); + } +} + +#[test] +fn root_checkpoints_have_only_one_live_input_and_keep_clips_whole() { + for mode in [BlendMode::Normal, BlendMode::PassThrough] { + let mut d = Document::with_background("t", Size::new(32, 24), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut clip = Layer::new("clip", LayerContent::Fill(Fill::Solid(Color::rgba(0.2, 0.3, 0.7, 0.4)))); + clip.clipped = true; + let mut group = Layer::group( + "group", + vec![ + Layer::new("fill", LayerContent::Fill(Fill::Solid(Color::rgba(0.9, 0.1, 0.3, 0.6)))), + Layer::new("invert", LayerContent::Adjustment(Adjustment::Invert)), + ], + ); + group.blend = mode; + d.layers.extend([group, clip, Layer::new("top", LayerContent::Adjustment(Adjustment::Invert))]); + let plan = plan(&d).unwrap(); + assert_eq!(plan.checkpoints.iter().map(|c| c.layer_end).collect::>(), vec![1, 3, 4]); + for checkpoint in &plan.checkpoints { + let mut written = std::collections::HashSet::from([checkpoint.slot]); + for pass in &plan.passes[checkpoint.pass_end..] { + for input in [pass.a, pass.b, pass.c, pass.d].into_iter().flatten() { + assert!(written.contains(&input), "a suffix must not need another saved slot: {checkpoint:?}"); + } + written.insert(pass.dst); + } + assert!(written.contains(&plan.root)); + } + } +} + +#[test] +fn slots_are_recycled() { + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + for i in 0..10 { + d.layers.push(Layer::raster(format!("l{i}"), d.pixel_format())); + } + let p = plan(&d).unwrap(); + // Empty layers draw nothing: the clear and the background's one fused pass. + assert_eq!(p.passes.len(), 1 + 1); + for (i, l) in d.layers.iter_mut().skip(1).enumerate() { + l.surface_mut().unwrap().fill_rect(Rect::new(i as i32 % 4, 0, 4, 8), &[0.0, 0.0, 1.0, 1.0]); + } + let p = plan(&d).unwrap(); + assert!(p.slots <= 3, "{} slots", p.slots); + // The background, then each small layer blended over its bounds and copied back. + assert_eq!(p.passes.len(), 1 + 1 + 10 * 2); +} + +#[test] +fn small_layers_composite_only_over_their_bounds() { + let mut d = Document::with_background("t", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut l = Layer::raster("small", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 12, 20, 30), &[1.0, 0.0, 0.0, 1.0]); + let mut group = Layer::group("g", vec![l]); + group.blend = BlendMode::Normal; + d.layers.push(group); + let p = plan(&d).unwrap(); + let r = Rect::new(10, 12, 20, 30); + // The group's content, its blend and the copy back are all limited to the layer. + assert!(p.passes.iter().filter(|p| matches!(p.kernel, Kernel::Content | Kernel::Blend)).skip(2).all(|p| p.clip == Some(r)), "{:?}", p.passes); + let last = p.passes.last().unwrap(); + assert_eq!((last.kernel, last.dst, last.clip), (Kernel::CopyRect, p.root, Some(r))); + // A layer that covers most of the canvas composites everywhere. + d.layers[1].children_mut().unwrap()[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 60, 60), &[1.0, 0.0, 0.0, 1.0]); + let p = plan(&d).unwrap(); + assert!(p.passes.iter().all(|p| p.clip.is_none())); +} + +#[test] +fn effects_are_planned_in_place() { + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut l = Layer::raster("fx", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(2, 2, 5, 5), &[1.0, 0.0, 0.0, 1.0]); + l.effects.items.push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::WHITE }); + l.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); + d.layers.push(l); + let p = plan(&d).unwrap(); + assert_eq!(p.fx.len(), 1); + let m = photocraft_compose::effects::margin(&d.layers[1]); + assert_eq!(p.fx[0].region, Rect::new(2, 2, 5, 5).inflate(m).intersect(&d.bounds().inflate(m))); + // The effect region covers the whole canvas: the merged result is the backdrop, no copy. + assert!(p.fx[0].region.contains_rect(&d.bounds())); + let last = p.passes.last().unwrap(); + assert_eq!(last.kernel, Kernel::FxMerge); + assert_eq!(last.dst, p.root); + assert!(p.slots <= 6, "{} slots", p.slots); + // On a larger canvas the result lands back in the backdrop slot over the region only. + let mut big = Document::with_background("t", Size::new(64, 64), ColorMode::Rgb, SampleType::U8, Color::WHITE); + big.layers.push(d.layers[1].clone()); + let p = plan(&big).unwrap(); + assert!(!p.fx[0].region.contains_rect(&big.bounds())); + let last = p.passes.last().unwrap(); + assert_eq!((last.kernel, last.dst, last.clip), (Kernel::CopyRect, p.root, Some(p.fx[0].region))); +} + +#[test] +fn exterior_effects_merge_from_the_shape() { + // A drop shadow alone: the layer's pixels, the shadow, the merge. With an interior effect + // the layer is built in passes of its own (colour inside the shape, the overlay, alpha). + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut l = Layer::raster("fx", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[1.0, 0.0, 0.0, 0.5]); + l.fill_opacity = 0.7; + l.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); + d.layers.push(l); + let p = plan(&d).unwrap(); + let fx: Vec = p.passes.iter().skip(2).map(|p| p.kernel).collect(); + assert_eq!(fx, [Kernel::Content, Kernel::FxPaint, Kernel::FxMerge], "{:?}", p.passes); + let merge = p.passes.last().unwrap(); + assert!(merge.flags & F_LAYER_SHAPE != 0); + assert_eq!(merge.params[0][0], 0.7); + d.layers[1] + .effects + .items + .push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::WHITE }); + let p = plan(&d).unwrap(); + assert!(p.passes.iter().all(|p| p.flags & F_LAYER_SHAPE == 0)); + assert!(p.passes.iter().any(|p| p.kernel == Kernel::FxInit)); +} + +#[test] +fn opaque_fill_layers_skip_what_they_cover() { + let opaque = || Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 30.0, 1.0, photocraft_doc::GradientStyle::Linear, false); + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + for i in 0..4 { + // Small painted layers (empty ones plan no passes at all). + let mut l = Layer::raster(format!("l{i}"), d.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(i, i, i + 2, i + 2), &[0.0, 0.0, 1.0, 1.0]); + d.layers.push(l); + } + d.layers.push(Layer::new("g", LayerContent::Fill(opaque()))); + let mut top = Layer::raster("top", d.pixel_format()); + top.clipped = true; + d.layers.push(top); + // Clear, then the fill and its clipped layer: the background and four rasters are skipped. + let skipped = plan(&d).unwrap().passes.len(); + let mut alone = d.clone(); + alone.layers.drain(..5); + assert_eq!(skipped, plan(&alone).unwrap().passes.len()); + // Anything that lets the layers below show through keeps them. + let see_through: [fn(&mut Layer); 6] = [ + |l| l.opacity = 0.99, + |l| l.fill_opacity = 0.5, + |l| l.blend = BlendMode::Multiply, + |l| l.visible = false, + |l| l.excluded_channels = 1, + |l| { + if let LayerContent::Fill(Fill::Gradient { opacity_stops, .. }) = &mut l.content { + opacity_stops.push((1.0, 0.5)); + } + }, + ]; + for (k, f) in see_through.iter().enumerate() { + let mut d2 = d.clone(); + f(&mut d2.layers[5]); + assert!(plan(&d2).unwrap().passes.len() > skipped, "case {k}: the layers below are planned"); + assert!(!photocraft_compose::occludes_below(&d2.layers[5], ColorMode::Rgb), "case {k}"); + } + let mut translucent = d.clone(); + translucent.layers[5].content = LayerContent::Fill(Fill::Solid(Color::rgba(1.0, 0.0, 0.0, 0.5))); + assert!(!photocraft_compose::occludes_below(&translucent.layers[5], ColorMode::Rgb)); + assert!(photocraft_compose::occludes_below(&d.layers[5], ColorMode::Rgb)); +} + +#[test] +fn blend_if_plans_on_the_gpu() { + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut l = Layer::raster("bi", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); + l.blend_if.set(0, [photocraft_doc::BlendRange { black: [40, 40], white: [255, 255] }, photocraft_doc::BlendRange::FULL]); + d.layers.push(l.clone()); + let blend_if = |d: &Document| plan(d).unwrap().passes.iter().filter(|p| p.flags & F_BLEND_IF != 0).count(); + assert_eq!(blend_if(&d), 1); + // Clipped layers too. + l.clipped = true; + d.layers[1].blend_if = Default::default(); + d.layers.push(l); + assert_eq!(blend_if(&d), 1); + // Outside RGB, Grayscale and Duotone the setting round-trips without applying. + d.mode = ColorMode::Lab; + assert_eq!(blend_if(&d), 0); +} + +#[test] +fn blend_if_params_pack_every_range_exactly() { + let mut bi = photocraft_doc::BlendIf::default(); + bi.set(3, [photocraft_doc::BlendRange { black: [255, 255], white: [0, 1] }, photocraft_doc::BlendRange { black: [12, 200], white: [201, 254] }]); + let f: Vec = blend_if_params(&bi).iter().flatten().copied().collect(); + // Entry 3 (B), this layer then underlying; unset entries are full ranges. + assert_eq!(&f[12..16], &[255.0 * 256.0 + 255.0, 1.0, 12.0 * 256.0 + 200.0, 201.0 * 256.0 + 254.0]); + assert_eq!(&f[0..2], &[0.0, 255.0 * 256.0 + 255.0]); +} + +#[test] +fn advanced_blending_falls_back_to_the_cpu() { + use photocraft_doc::Knockout; + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut l = Layer::raster("ko", d.pixel_format()); + l.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); + d.layers.push(l.clone()); + assert!(plan(&d).is_ok(), "defaults stay on the GPU"); + // Switches with nothing to act on (no effects, no clipped layers) stay on the GPU too. + d.layers[1].advanced.blend_interior = true; + d.layers[1].advanced.blend_clipped = false; + assert!(plan(&d).is_ok()); + d.layers[1].advanced.knockout = Knockout::Deep; + assert!(plan(&d).unwrap_err().0.contains("Advanced Blending")); + // Inside groups and clipping groups. + d.layers[1].advanced.knockout = Knockout::None; + let mut c = l.clone(); + c.clipped = true; + d.layers.push(c.clone()); + assert!(plan(&d).is_err(), "clipped layers blended individually"); + d.layers[1].advanced.blend_clipped = true; + assert!(plan(&d).is_ok()); + d.layers[2].advanced.knockout = Knockout::Shallow; + assert!(plan(&d).is_err(), "clipped knockout"); + d.layers.truncate(1); + let mut inner = l; + inner.advanced.knockout = Knockout::Shallow; + d.layers.push(Layer::group("g", vec![inner])); + assert!(plan(&d).is_err(), "knockout inside a group"); +} From 78d947d51abf6811f9dffc29b86cef96418a5588 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:57 +0000 Subject: [PATCH 126/259] refactor(gpu): move lib.rs tests to tests.rs --- crates/gpu/src/lib.rs | 398 +--------------------------------------- crates/gpu/src/tests.rs | 395 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 396 insertions(+), 397 deletions(-) create mode 100644 crates/gpu/src/tests.rs diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 7770662b15..c139a1860e 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -2980,400 +2980,4 @@ pub fn render_to_vec_stats( } #[cfg(test)] -mod tests { - use super::*; - - /// A run joins `LayerBlend` passes that only feed each other, at most `BATCH` of them, and - /// never ends in the slot it reads from. - fn check_runs(p: &Plan<'_>) -> Vec { - let runs = batch_runs(p); - assert_eq!(runs.len(), p.passes.len()); - for (i, &k) in runs.iter().enumerate() { - assert!((1..=BATCH).contains(&k), "pass {i}: run {k}"); - if k > 1 { - assert_ne!(Some(p.passes[i + k - 1].dst), p.passes[i].a, "run at {i} renders into its input"); - for j in i + 1..i + k { - assert_eq!(p.passes[j].kernel, Kernel::LayerBlend); - assert_eq!(p.passes[j].a, Some(p.passes[j - 1].dst), "run at {i}: pass {j} doesn't read the one before"); - assert!(p.passes[j].mask.is_none() && p.passes[j].mode != photocraft_color::BlendMode::Dissolve, "run at {i}: pass {j}"); - } - } - } - runs - } - - #[test] - fn plain_layers_batch_and_runs_stop_where_a_pass_must_stand_alone() { - use photocraft_color::{BlendMode, Color, ColorMode, SampleType}; - use photocraft_doc::{Document, Layer, LayerMask}; - let mut d = Document::with_background("t", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); - for i in 0..12 { - let mut l = Layer::raster(format!("l{i}"), d.pixel_format()); - l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[0.2, 0.4, 0.6, 0.5]); - d.layers.push(l); - } - let p = plan::plan(&d).unwrap(); - let runs = check_runs(&p); - assert!(runs.iter().any(|k| *k >= 3), "{runs:?}"); - // The cache resumes only where a run starts, so a cached render draws the passes above - // its checkpoint in the same runs as an uncached one; checkpoints inside a run are - // skipped, but a stack of plain layers keeps some to resume at. - let starts = run_starts(&runs); - assert_eq!(starts.len(), runs.len() + 1); - assert!(starts[0] && starts[runs.len()]); - let (mut at, mut i) = (Vec::new(), 0); - while i < runs.len() { - at.push(i); - i += runs[i]; - } - assert_eq!(starts.iter().enumerate().filter(|(_, s)| **s).map(|(i, _)| i).collect::>(), [at, vec![runs.len()]].concat()); - let resumable = p.checkpoints.iter().filter(|c| c.pass_end > 1 && starts[c.pass_end]).count(); - assert!(resumable >= 2 && resumable < p.checkpoints.len(), "{resumable} of {:?}", p.checkpoints); - // A masked or Dissolve layer, or a clipped one, never joins a run as an extra layer. - d.layers[3].mask = Some(LayerMask::hide_all()); - d.layers[6].blend = BlendMode::Dissolve; - d.layers[9].clipped = true; - check_runs(&plan::plan(&d).unwrap()); - // Nothing to batch: a lone layer. - d.layers.truncate(1); - assert_eq!(check_runs(&plan::plan(&d).unwrap()), vec![1; plan::plan(&d).unwrap().passes.len()]); - } - - #[test] - fn batch_records_hold_three_extra_layers_in_the_spare_words() { - let lead = plan::Pass::new(Kernel::LayerBlend, 0); - let mut x = plan::Pass::new(Kernel::LayerBlend, 1); - x.opacity = 0.25; - x.fill = 0.5; - x.color = [0.1, 0.2, 0.3, 0.4]; - let w = batch_op_words(&lead, None, None, &[(&x, Some([1, 2, 3, 4])), (&x, None), (&x, None), (&x, None)]); - assert_eq!(w.len() as u64, OP_UNIFORM); - let word = |i: usize| <[u8; 4]>::try_from(&w[i * 4..i * 4 + 4]).unwrap(); - let f = |i: usize| f32::from_le_bytes(word(i)); - // At most three extras; the first's geometry, colour and parameters in p0, p1, p2. - assert_eq!(i32::from_le_bytes(word(1)), 3); - assert_eq!([f(20), f(21), f(22), f(23)], [1.0, 2.0, 3.0, 4.0]); - assert_eq!([f(24), f(25), f(26), f(27)], [0.1, 0.2, 0.3, 0.4]); - assert_eq!([f(28), f(29), f(31)], [0.25, 0.5, 1.0]); - // The third's parameters in q4; one without pixels says so. - assert_eq!([f(60), f(61), f(63)], [0.25, 0.5, 0.0]); - // Other passes leave the batch words zero. - let plain = op_words(&x, None, None, None); - assert!(plain[44 * 4..].iter().all(|b| *b == 0)); - } - - #[test] - fn runs_of_normal_layers_draw_with_normal_code_alone() { - use photocraft_color::BlendMode; - let pass = |mode: BlendMode, flags: u32| { - let mut p = plan::Pass::new(Kernel::LayerBlend, 0); - p.mode = mode; - p.flags = flags; - p - }; - let normal = pass(BlendMode::Normal, plan::F_HDR); - assert_eq!(batch_kernel(&[normal.clone(), pass(BlendMode::Normal, 0)]), Kernel::LayerBatchNormal); - // Any other mode, text gamma or a Lab document anywhere in the run takes the full shader. - for other in - [pass(BlendMode::Multiply, 0), pass(BlendMode::Dissolve, 0), pass(BlendMode::Normal, plan::F_TEXT_GAMMA), pass(BlendMode::Normal, plan::F_LAB)] - { - assert_eq!(batch_kernel(&[normal.clone(), other.clone()]), Kernel::LayerBatch); - assert_eq!(batch_kernel(&[other, normal.clone()]), Kernel::LayerBatch); - } - } - - #[test] - fn layer_pages_are_admitted_by_evicting_least_recently_used_first() { - let pages = || vec![(5, 'c', 40), (1, 'a', 30), (3, 'b', 20)]; - // Fits already: nothing dropped. - assert!(lru_victims(pages(), 90, 10, 100).is_empty()); - // 90 held + 40 incoming over 100: the oldest page goes first, then the next. - assert_eq!(lru_victims(pages(), 90, 40, 100), vec!['a']); - assert_eq!(lru_victims(pages(), 90, 60, 100), vec!['a', 'b']); - // Out of memory: a zero budget drops every candidate, and an impossible request stops - // when none are left instead of looping or overflowing. - assert_eq!(lru_victims(pages(), 90, 0, 0), vec!['a', 'b', 'c']); - assert_eq!(lru_victims(pages(), u64::MAX, u64::MAX, 1), vec!['a', 'b', 'c']); - assert!(lru_victims(Vec::<(u64, char, u64)>::new(), 90, 40, 100).is_empty()); - } - - #[test] - fn uniform_buffer_sizes_are_checked_before_allocation() { - assert_eq!(uniform_buffer_len(1, 255, 65_536).unwrap(), 65_536); - assert!(uniform_buffer_len(1, 255, 65_535).is_err()); - assert!(uniform_buffer_len(usize::MAX, 1, u64::MAX).is_err()); - assert!(uniform_buffer_len(usize::MAX, 0, u64::MAX).is_err()); - assert!(uniform_buffer_len(1, 16_777_216, u64::MAX).is_err(), "the last record offset cannot be represented by u32"); - #[cfg(target_pointer_width = "64")] - assert_eq!(uniform_buffer_len(1, 16_777_215, u64::MAX).unwrap(), 4_294_967_296, "the last valid u32 dynamic offset is accepted"); - } - - #[test] - fn half_roundtrip() { - for v in [0.0f32, 1.0, 0.5, 0.25, 1.0 / 255.0, 0.333, 65504.0, -2.5, 1e-6] { - let r = f16_to_f32(f32_to_f16(v)); - assert!((r - v).abs() <= v.abs() / 1024.0 + 1e-7, "{v} -> {r}"); - } - } - - #[test] - fn shader_validates() { - let module = wgpu::naga::front::wgsl::parse_str(SHADER).unwrap_or_else(|e| panic!("{}", e.emit_to_string(SHADER))); - wgpu::naga::valid::Validator::new(wgpu::naga::valid::ValidationFlags::all(), wgpu::naga::valid::Capabilities::empty()) - .validate(&module) - .unwrap_or_else(|e| panic!("{e:?}")); - for k in Kernel::DRAWN { - let e = k.entry().unwrap(); - assert!(module.entry_points.iter().any(|ep| ep.name == e), "missing entry point {e}"); - } - } - - /// The decimal float literals in `src` (comments skipped; hex literals are exact, so skipped), - /// with their line numbers. - fn decimal_float_literals(src: &str) -> Vec<(usize, String)> { - let mut out = Vec::new(); - for (n, line) in src.lines().enumerate() { - let code = line.split("//").next().unwrap_or("").as_bytes(); - let mut i = 0; - while i < code.len() { - let digit_or_dot = code[i].is_ascii_digit() || (code[i] == b'.' && code.get(i + 1).is_some_and(u8::is_ascii_digit)); - let word_before = i > 0 && (code[i - 1].is_ascii_alphanumeric() || code[i - 1] == b'_' || code[i - 1] == b'.'); - if !digit_or_dot || word_before { - i += 1; - continue; - } - if code[i] == b'0' && matches!(code.get(i + 1), Some(b'x' | b'X')) { - i += 2; - while i < code.len() && (code[i].is_ascii_hexdigit() || matches!(code[i], b'.' | b'p' | b'P' | b'+' | b'-')) { - i += 1; - } - continue; - } - let start = i; - while i < code.len() && (code[i].is_ascii_digit() || code[i] == b'.') { - i += 1; - } - if i < code.len() && matches!(code[i], b'e' | b'E') { - let mut j = i + 1; - if j < code.len() && matches!(code[j], b'+' | b'-') { - j += 1; - } - if j < code.len() && code[j].is_ascii_digit() { - i = j; - while i < code.len() && code[i].is_ascii_digit() { - i += 1; - } - } - } - out.push((n + 1, String::from_utf8_lossy(&code[start..i]).into_owned())); - } - } - out - } - - /// Browsers' WebGPU shader compiler (Tint) rejects a float literal beyond f32's finite range - /// even when it would round to `f32::MAX` (naga, used natively, rounds it), and then no - /// compositor pipeline builds and the web app falls back to the CPU renderer. `3.40282347e38` - /// was such a literal. - #[test] - fn shader_float_literals_fit_f32() { - let lits = decimal_float_literals(SHADER); - assert!(lits.iter().any(|(_, l)| l == "1.0"), "the scanner finds literals: {lits:?}"); - let bad: Vec<_> = lits.iter().filter(|(_, l)| l.parse::().map_or(true, |v| !v.is_finite() || v.abs() > f64::from(f32::MAX))).collect(); - assert!(bad.is_empty(), "float literals outside f32's finite range (line, literal): {bad:?}"); - } - - #[test] - fn op_record_fits_the_uniform() { - let p = plan::Pass::new(Kernel::FxPaint, 0); - assert_eq!(op_words(&p, None, None, None).len() as u64, OP_UNIFORM); - } - - /// #6534: a 16-bit mask (16-bit documents, feathered or vector combined masks) costs two - /// bytes per pixel on the GPU, twice an 8-bit mask, not four; 32-bit masks stay R32Float. - #[test] - fn sixteen_bit_masks_upload_at_two_bytes_per_pixel() { - let gray = |sample| PixelFormat { sample, ..PixelFormat::GRAY8 }; - assert_eq!(TexKind::for_surface(Role::Mask, PixelFormat::GRAY8).bytes_per_pixel(), 1); - let k16 = TexKind::for_surface(Role::Mask, gray(SampleType::U16)); - assert_eq!(k16.bytes_per_pixel(), 2, "{k16:?}"); - assert_eq!(k16.format().block_copy_size(None), Some(2), "{k16:?}"); - let k32 = TexKind::for_surface(Role::Mask, gray(SampleType::F32)); - assert_eq!(k32.format(), wgpu::TextureFormat::R32Float); - // The texels hold the mask values (a half each), the default pixel included. - let mut s = Surface::with_default(gray(SampleType::U16), &[1.0]); - s.fill_rect(Rect::new(0, 0, 4, 1), &[0.25]); - let c = TileCoord::new(0, 0); - let bytes = convert_tile(&s, s.tile(c), k16, c); - assert_eq!(bytes.len(), (TILE_SIZE * TILE_SIZE) as usize * 2); - assert_eq!(bytes.get(..2), Some(f32_to_f16(0.25).to_le_bytes().as_slice())); - assert_eq!(bytes.get(8..10), Some(f32_to_f16(1.0).to_le_bytes().as_slice())); - assert_eq!(convert_tile(&s, None, k16, c).get(..2), Some(f32_to_f16(1.0).to_le_bytes().as_slice())); - } - - /// #1774: a solid fill shares one tile across every coordinate; it is converted once, and - /// every coordinate (shared or not) still gets exactly the bytes `convert_tile` gives it, at - /// every depth and texture kind. - #[test] - fn convert_tiles_converts_each_distinct_tile_once() { - let area = Rect::new(0, 0, TILE_SIZE * 9, TILE_SIZE * 9); - for (fmt, kind) in [ - (PixelFormat::RGBA8, TexKind::Rgba8Direct), - (PixelFormat { alpha: false, ..PixelFormat::RGBA8 }, TexKind::Rgba8), - (PixelFormat::RGBA16, TexKind::Rgba16F), - (PixelFormat::RGBA32F, TexKind::Rgba16F), - (PixelFormat::GRAY8, TexKind::R8Direct), - (PixelFormat { sample: SampleType::U16, ..PixelFormat::GRAY8 }, TexKind::R16F), - (PixelFormat { sample: SampleType::F32, ..PixelFormat::GRAY8 }, TexKind::R32F), - ] { - let mut s = Surface::new(fmt); - let px = [0.2, 0.4, 0.6, 1.0]; - let n = fmt.channels(); - // Fully covered tiles share one `Arc`; then two tiles get their own pixels. - s.fill_rect(area, &px[..n]); - s.fill_rect(Rect::new(3, 5, 40, 60), &[0.9, 0.1, 0.3, 0.5][..n]); - s.fill_rect(Rect::new(TILE_SIZE * 4 + 7, TILE_SIZE * 2, TILE_SIZE * 4 + 9, TILE_SIZE * 2 + 3), &[0.0; 4][..n]); - let tiles: Vec<_> = area.tiles().filter_map(|c| s.tile(c).map(|t| (c, t.clone()))).collect(); - assert_eq!(tiles.len(), 81, "{fmt:?}"); - let mut seen = Vec::new(); - let converted = convert_tiles(&s, tiles, kind, |t, cs, bytes| { - for &c in cs { - assert!(s.tile(c).is_some_and(|own| Arc::ptr_eq(own, t)), "{fmt:?} {c:?}"); - assert_eq!(bytes, convert_tile(&s, Some(t), kind, c).as_slice(), "{fmt:?} {c:?}"); - seen.push(c); - } - }); - assert_eq!(converted, 3, "{fmt:?}: the shared tile once, plus the two edited ones"); - seen.sort_by_key(|c| (c.ty, c.tx)); - let mut want: Vec<_> = area.tiles().collect(); - want.sort_by_key(|c| (c.ty, c.tx)); - assert_eq!(seen, want, "{fmt:?}: every coordinate once"); - } - // More distinct tiles than one batch: all converted, each coordinate once. - let mut s = Surface::new(PixelFormat::RGBA16); - let wide = Rect::new(0, 0, TILE_SIZE * (CONVERT_BATCH as i32 + 5), TILE_SIZE); - for c in wide.tiles() { - s.fill_rect(Rect::new(c.rect().x0, 0, c.rect().x0 + 1, 1), &[c.tx as f32 / 100.0, 0.0, 0.0, 1.0]); - } - let tiles: Vec<_> = wide.tiles().filter_map(|c| s.tile(c).map(|t| (c, t.clone()))).collect(); - let mut n = 0; - let converted = convert_tiles(&s, tiles, TexKind::Rgba16F, |t, cs, bytes| { - for &c in cs { - assert_eq!(bytes, convert_tile(&s, Some(t), TexKind::Rgba16F, c).as_slice()); - n += 1; - } - }); - assert_eq!((converted, n), (CONVERT_BATCH + 5, CONVERT_BATCH + 5)); - } - - /// The 16-bit and 32-bit float RGB/gray fast paths give exactly the general path's half - /// floats (32-bit samples above 1 and below 0 included). - #[test] - fn sixteen_and_thirty_two_bit_fast_paths_match_the_general_one() { - for fmt in [ - PixelFormat::RGBA16, - PixelFormat { alpha: false, ..PixelFormat::RGBA16 }, - PixelFormat { sample: SampleType::U16, ..PixelFormat::GRAY8 }, - PixelFormat { sample: SampleType::U16, alpha: true, ..PixelFormat::GRAY8 }, - PixelFormat::RGBA32F, - PixelFormat { alpha: false, ..PixelFormat::RGBA32F }, - PixelFormat { sample: SampleType::F32, ..PixelFormat::GRAY8 }, - PixelFormat { sample: SampleType::F32, alpha: true, ..PixelFormat::GRAY8 }, - ] { - let mut s = Surface::new(fmt); - let r = Rect::new(0, 0, TILE_SIZE, TILE_SIZE); - let n = (TILE_SIZE * TILE_SIZE) as usize * fmt.channels(); - let hdr = if fmt.sample == SampleType::F32 { 4.0 } else { 1.0 }; - let data: Vec = (0..n).map(|i| (i as u32).wrapping_mul(2_654_435_761) as f32 / u32::MAX as f32 * hdr - (hdr - 1.0) / 4.0).collect(); - s.write_region(r, &data); - let t = s.tile(TileCoord::new(0, 0)).expect("written").clone(); - let fast = rgb_gray16_to_f16(&fmt, t.bytes()).or_else(|| rgb_gray32_to_f16(&fmt, t.bytes())).expect("fast path"); - let raw = s.read_region(r); - let general: Vec = - raw.chunks_exact(fmt.channels()).flat_map(|px| photocraft_raster::to_rgba(&fmt, px).map(|x| f32_to_f16(x).to_le_bytes())).flatten().collect(); - assert_eq!(fast, general, "{fmt:?}"); - assert_eq!(convert_tile(&s, Some(&t), TexKind::Rgba16F, TileCoord::new(0, 0)), general, "{fmt:?}"); - } - assert!(rgb_gray16_to_f16(&PixelFormat::RGBA8, &[]).is_none()); - assert!(rgb_gray16_to_f16(&PixelFormat { sample: SampleType::U16, ..PixelFormat::CMYKA8 }, &[]).is_none()); - assert!(rgb_gray32_to_f16(&PixelFormat::RGBA16, &[]).is_none()); - assert!(rgb_gray32_to_f16(&PixelFormat { sample: SampleType::F32, ..PixelFormat::CMYKA8 }, &[]).is_none()); - } - - /// CMYK and Lab tiles convert in parallel bands of rows, each run of equal pixels once - /// (#5108): the texels are still exactly the per-pixel conversion's, at 8 and 16 bits, with - /// the built-in CMYK profile and with a document's own (which the worker threads enter). - #[test] - fn colour_managed_tiles_match_the_per_pixel_conversion() { - use photocraft_cms::synth::{CmykParams, cmyk_profile}; - use photocraft_color::ColorMode; - use photocraft_color::convert::{CmykSpace, with_cmyk_space}; - let icc = Arc::new( - cmyk_profile(&CmykParams { description: "GPU test CMYK".into(), tvi: [0.26, 0.26, 0.26, 0.3], grid_a2b: 5, grid_b2a: 9, ..Default::default() }) - .to_bytes(), - ); - let own = CmykSpace::for_profile(Some(&icc)); - assert!(own.is_some(), "the synthetic profile is not the built-in one"); - let area = Rect::new(0, 0, TILE_SIZE * 3, TILE_SIZE); - for (mode, sample, space) in [ - (ColorMode::Cmyk, SampleType::U8, None), - (ColorMode::Cmyk, SampleType::U16, None), - (ColorMode::Cmyk, SampleType::U8, own.clone()), - (ColorMode::Cmyk, SampleType::U16, own.clone()), - (ColorMode::Lab, SampleType::U8, None), - (ColorMode::Lab, SampleType::U16, None), - ] { - let fmt = PixelFormat { mode, sample, alpha: true }; - let kind = TexKind::for_surface(Role::Content, fmt); - assert!(colour_managed(&fmt, kind), "{fmt:?}"); - let ch = fmt.channels(); - let mut s = Surface::new(fmt); - // Tile 0: noise. Tile 1: transparent with a soft dab (runs of equal pixels). Tile 2: - // a flat colour with a few lines of noise. - let n = (TILE_SIZE * TILE_SIZE) as usize * ch; - let noise: Vec = (0..n).map(|i| (i as u32).wrapping_mul(2_654_435_761) as f32 / u32::MAX as f32).collect(); - s.write_region(Rect::new(0, 0, TILE_SIZE, TILE_SIZE), &noise); - let mut dab = [0.8, 0.6, 0.1, 0.05, 0.0]; - for r in (1..30).rev() { - dab[ch - 1] = 1.0 - r as f32 / 30.0; - s.fill_rect(Rect::new(TILE_SIZE + 100 - r, 90 - r, TILE_SIZE + 100 + r, 90 + r), &dab[..ch]); - } - s.fill_rect(Rect::new(TILE_SIZE * 2, 0, TILE_SIZE * 3, TILE_SIZE), &[0.3, 0.2, 0.7, 0.1, 1.0][..ch]); - s.write_region(Rect::new(TILE_SIZE * 2, 40, TILE_SIZE * 3, 43), &noise[..TILE_SIZE as usize * 3 * ch]); - let tiles: Vec<_> = area.tiles().filter_map(|c| s.tile(c).map(|t| (c, t.clone()))).collect(); - assert_eq!(tiles.len(), 3, "{fmt:?}"); - let mut seen = 0; - with_cmyk_space(space.as_ref(), || { - convert_tiles(&s, tiles, kind, |_, cs, bytes| { - for &c in cs { - // The old path: every pixel through `to_rgba` on this thread, in this scope. - let want: Vec = s - .read_region(c.rect()) - .chunks_exact(ch) - .flat_map(|px| { - let v = photocraft_raster::to_rgba(&fmt, px); - match kind { - TexKind::Rgba16F => v.iter().flat_map(|x| f32_to_f16(*x).to_le_bytes()).collect::>(), - _ => v.map(|x| (x.clamp(0.0, 1.0) * 255.0 + 0.5) as u8).to_vec(), - } - }) - .collect(); - assert!( - bytes == want.as_slice(), - "{fmt:?} {c:?} with {}", - if space.is_some() { "the document's profile" } else { "the built-in profile" } - ); - assert_eq!(convert_tile(&s, s.tile(c), kind, c), want, "{fmt:?} {c:?}"); - seen += 1; - } - }); - }); - assert_eq!(seen, 3, "{fmt:?}"); - } - } - - #[test] - fn grid_rounds_out() { - assert_eq!(tile_grid(Rect::new(0, 0, 300, 256)), Rect::new(0, 0, 512, 256)); - } -} +mod tests; diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs new file mode 100644 index 0000000000..f2a6847dd0 --- /dev/null +++ b/crates/gpu/src/tests.rs @@ -0,0 +1,395 @@ +use super::*; + +/// A run joins `LayerBlend` passes that only feed each other, at most `BATCH` of them, and +/// never ends in the slot it reads from. +fn check_runs(p: &Plan<'_>) -> Vec { + let runs = batch_runs(p); + assert_eq!(runs.len(), p.passes.len()); + for (i, &k) in runs.iter().enumerate() { + assert!((1..=BATCH).contains(&k), "pass {i}: run {k}"); + if k > 1 { + assert_ne!(Some(p.passes[i + k - 1].dst), p.passes[i].a, "run at {i} renders into its input"); + for j in i + 1..i + k { + assert_eq!(p.passes[j].kernel, Kernel::LayerBlend); + assert_eq!(p.passes[j].a, Some(p.passes[j - 1].dst), "run at {i}: pass {j} doesn't read the one before"); + assert!(p.passes[j].mask.is_none() && p.passes[j].mode != photocraft_color::BlendMode::Dissolve, "run at {i}: pass {j}"); + } + } + } + runs +} + +#[test] +fn plain_layers_batch_and_runs_stop_where_a_pass_must_stand_alone() { + use photocraft_color::{BlendMode, Color, ColorMode, SampleType}; + use photocraft_doc::{Document, Layer, LayerMask}; + let mut d = Document::with_background("t", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + for i in 0..12 { + let mut l = Layer::raster(format!("l{i}"), d.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 8, 8), &[0.2, 0.4, 0.6, 0.5]); + d.layers.push(l); + } + let p = plan::plan(&d).unwrap(); + let runs = check_runs(&p); + assert!(runs.iter().any(|k| *k >= 3), "{runs:?}"); + // The cache resumes only where a run starts, so a cached render draws the passes above + // its checkpoint in the same runs as an uncached one; checkpoints inside a run are + // skipped, but a stack of plain layers keeps some to resume at. + let starts = run_starts(&runs); + assert_eq!(starts.len(), runs.len() + 1); + assert!(starts[0] && starts[runs.len()]); + let (mut at, mut i) = (Vec::new(), 0); + while i < runs.len() { + at.push(i); + i += runs[i]; + } + assert_eq!(starts.iter().enumerate().filter(|(_, s)| **s).map(|(i, _)| i).collect::>(), [at, vec![runs.len()]].concat()); + let resumable = p.checkpoints.iter().filter(|c| c.pass_end > 1 && starts[c.pass_end]).count(); + assert!(resumable >= 2 && resumable < p.checkpoints.len(), "{resumable} of {:?}", p.checkpoints); + // A masked or Dissolve layer, or a clipped one, never joins a run as an extra layer. + d.layers[3].mask = Some(LayerMask::hide_all()); + d.layers[6].blend = BlendMode::Dissolve; + d.layers[9].clipped = true; + check_runs(&plan::plan(&d).unwrap()); + // Nothing to batch: a lone layer. + d.layers.truncate(1); + assert_eq!(check_runs(&plan::plan(&d).unwrap()), vec![1; plan::plan(&d).unwrap().passes.len()]); +} + +#[test] +fn batch_records_hold_three_extra_layers_in_the_spare_words() { + let lead = plan::Pass::new(Kernel::LayerBlend, 0); + let mut x = plan::Pass::new(Kernel::LayerBlend, 1); + x.opacity = 0.25; + x.fill = 0.5; + x.color = [0.1, 0.2, 0.3, 0.4]; + let w = batch_op_words(&lead, None, None, &[(&x, Some([1, 2, 3, 4])), (&x, None), (&x, None), (&x, None)]); + assert_eq!(w.len() as u64, OP_UNIFORM); + let word = |i: usize| <[u8; 4]>::try_from(&w[i * 4..i * 4 + 4]).unwrap(); + let f = |i: usize| f32::from_le_bytes(word(i)); + // At most three extras; the first's geometry, colour and parameters in p0, p1, p2. + assert_eq!(i32::from_le_bytes(word(1)), 3); + assert_eq!([f(20), f(21), f(22), f(23)], [1.0, 2.0, 3.0, 4.0]); + assert_eq!([f(24), f(25), f(26), f(27)], [0.1, 0.2, 0.3, 0.4]); + assert_eq!([f(28), f(29), f(31)], [0.25, 0.5, 1.0]); + // The third's parameters in q4; one without pixels says so. + assert_eq!([f(60), f(61), f(63)], [0.25, 0.5, 0.0]); + // Other passes leave the batch words zero. + let plain = op_words(&x, None, None, None); + assert!(plain[44 * 4..].iter().all(|b| *b == 0)); +} + +#[test] +fn runs_of_normal_layers_draw_with_normal_code_alone() { + use photocraft_color::BlendMode; + let pass = |mode: BlendMode, flags: u32| { + let mut p = plan::Pass::new(Kernel::LayerBlend, 0); + p.mode = mode; + p.flags = flags; + p + }; + let normal = pass(BlendMode::Normal, plan::F_HDR); + assert_eq!(batch_kernel(&[normal.clone(), pass(BlendMode::Normal, 0)]), Kernel::LayerBatchNormal); + // Any other mode, text gamma or a Lab document anywhere in the run takes the full shader. + for other in + [pass(BlendMode::Multiply, 0), pass(BlendMode::Dissolve, 0), pass(BlendMode::Normal, plan::F_TEXT_GAMMA), pass(BlendMode::Normal, plan::F_LAB)] + { + assert_eq!(batch_kernel(&[normal.clone(), other.clone()]), Kernel::LayerBatch); + assert_eq!(batch_kernel(&[other, normal.clone()]), Kernel::LayerBatch); + } +} + +#[test] +fn layer_pages_are_admitted_by_evicting_least_recently_used_first() { + let pages = || vec![(5, 'c', 40), (1, 'a', 30), (3, 'b', 20)]; + // Fits already: nothing dropped. + assert!(lru_victims(pages(), 90, 10, 100).is_empty()); + // 90 held + 40 incoming over 100: the oldest page goes first, then the next. + assert_eq!(lru_victims(pages(), 90, 40, 100), vec!['a']); + assert_eq!(lru_victims(pages(), 90, 60, 100), vec!['a', 'b']); + // Out of memory: a zero budget drops every candidate, and an impossible request stops + // when none are left instead of looping or overflowing. + assert_eq!(lru_victims(pages(), 90, 0, 0), vec!['a', 'b', 'c']); + assert_eq!(lru_victims(pages(), u64::MAX, u64::MAX, 1), vec!['a', 'b', 'c']); + assert!(lru_victims(Vec::<(u64, char, u64)>::new(), 90, 40, 100).is_empty()); +} + +#[test] +fn uniform_buffer_sizes_are_checked_before_allocation() { + assert_eq!(uniform_buffer_len(1, 255, 65_536).unwrap(), 65_536); + assert!(uniform_buffer_len(1, 255, 65_535).is_err()); + assert!(uniform_buffer_len(usize::MAX, 1, u64::MAX).is_err()); + assert!(uniform_buffer_len(usize::MAX, 0, u64::MAX).is_err()); + assert!(uniform_buffer_len(1, 16_777_216, u64::MAX).is_err(), "the last record offset cannot be represented by u32"); + #[cfg(target_pointer_width = "64")] + assert_eq!(uniform_buffer_len(1, 16_777_215, u64::MAX).unwrap(), 4_294_967_296, "the last valid u32 dynamic offset is accepted"); +} + +#[test] +fn half_roundtrip() { + for v in [0.0f32, 1.0, 0.5, 0.25, 1.0 / 255.0, 0.333, 65504.0, -2.5, 1e-6] { + let r = f16_to_f32(f32_to_f16(v)); + assert!((r - v).abs() <= v.abs() / 1024.0 + 1e-7, "{v} -> {r}"); + } +} + +#[test] +fn shader_validates() { + let module = wgpu::naga::front::wgsl::parse_str(SHADER).unwrap_or_else(|e| panic!("{}", e.emit_to_string(SHADER))); + wgpu::naga::valid::Validator::new(wgpu::naga::valid::ValidationFlags::all(), wgpu::naga::valid::Capabilities::empty()) + .validate(&module) + .unwrap_or_else(|e| panic!("{e:?}")); + for k in Kernel::DRAWN { + let e = k.entry().unwrap(); + assert!(module.entry_points.iter().any(|ep| ep.name == e), "missing entry point {e}"); + } +} + +/// The decimal float literals in `src` (comments skipped; hex literals are exact, so skipped), +/// with their line numbers. +fn decimal_float_literals(src: &str) -> Vec<(usize, String)> { + let mut out = Vec::new(); + for (n, line) in src.lines().enumerate() { + let code = line.split("//").next().unwrap_or("").as_bytes(); + let mut i = 0; + while i < code.len() { + let digit_or_dot = code[i].is_ascii_digit() || (code[i] == b'.' && code.get(i + 1).is_some_and(u8::is_ascii_digit)); + let word_before = i > 0 && (code[i - 1].is_ascii_alphanumeric() || code[i - 1] == b'_' || code[i - 1] == b'.'); + if !digit_or_dot || word_before { + i += 1; + continue; + } + if code[i] == b'0' && matches!(code.get(i + 1), Some(b'x' | b'X')) { + i += 2; + while i < code.len() && (code[i].is_ascii_hexdigit() || matches!(code[i], b'.' | b'p' | b'P' | b'+' | b'-')) { + i += 1; + } + continue; + } + let start = i; + while i < code.len() && (code[i].is_ascii_digit() || code[i] == b'.') { + i += 1; + } + if i < code.len() && matches!(code[i], b'e' | b'E') { + let mut j = i + 1; + if j < code.len() && matches!(code[j], b'+' | b'-') { + j += 1; + } + if j < code.len() && code[j].is_ascii_digit() { + i = j; + while i < code.len() && code[i].is_ascii_digit() { + i += 1; + } + } + } + out.push((n + 1, String::from_utf8_lossy(&code[start..i]).into_owned())); + } + } + out +} + +/// Browsers' WebGPU shader compiler (Tint) rejects a float literal beyond f32's finite range +/// even when it would round to `f32::MAX` (naga, used natively, rounds it), and then no +/// compositor pipeline builds and the web app falls back to the CPU renderer. `3.40282347e38` +/// was such a literal. +#[test] +fn shader_float_literals_fit_f32() { + let lits = decimal_float_literals(SHADER); + assert!(lits.iter().any(|(_, l)| l == "1.0"), "the scanner finds literals: {lits:?}"); + let bad: Vec<_> = lits.iter().filter(|(_, l)| l.parse::().map_or(true, |v| !v.is_finite() || v.abs() > f64::from(f32::MAX))).collect(); + assert!(bad.is_empty(), "float literals outside f32's finite range (line, literal): {bad:?}"); +} + +#[test] +fn op_record_fits_the_uniform() { + let p = plan::Pass::new(Kernel::FxPaint, 0); + assert_eq!(op_words(&p, None, None, None).len() as u64, OP_UNIFORM); +} + +/// #6534: a 16-bit mask (16-bit documents, feathered or vector combined masks) costs two +/// bytes per pixel on the GPU, twice an 8-bit mask, not four; 32-bit masks stay R32Float. +#[test] +fn sixteen_bit_masks_upload_at_two_bytes_per_pixel() { + let gray = |sample| PixelFormat { sample, ..PixelFormat::GRAY8 }; + assert_eq!(TexKind::for_surface(Role::Mask, PixelFormat::GRAY8).bytes_per_pixel(), 1); + let k16 = TexKind::for_surface(Role::Mask, gray(SampleType::U16)); + assert_eq!(k16.bytes_per_pixel(), 2, "{k16:?}"); + assert_eq!(k16.format().block_copy_size(None), Some(2), "{k16:?}"); + let k32 = TexKind::for_surface(Role::Mask, gray(SampleType::F32)); + assert_eq!(k32.format(), wgpu::TextureFormat::R32Float); + // The texels hold the mask values (a half each), the default pixel included. + let mut s = Surface::with_default(gray(SampleType::U16), &[1.0]); + s.fill_rect(Rect::new(0, 0, 4, 1), &[0.25]); + let c = TileCoord::new(0, 0); + let bytes = convert_tile(&s, s.tile(c), k16, c); + assert_eq!(bytes.len(), (TILE_SIZE * TILE_SIZE) as usize * 2); + assert_eq!(bytes.get(..2), Some(f32_to_f16(0.25).to_le_bytes().as_slice())); + assert_eq!(bytes.get(8..10), Some(f32_to_f16(1.0).to_le_bytes().as_slice())); + assert_eq!(convert_tile(&s, None, k16, c).get(..2), Some(f32_to_f16(1.0).to_le_bytes().as_slice())); +} + +/// #1774: a solid fill shares one tile across every coordinate; it is converted once, and +/// every coordinate (shared or not) still gets exactly the bytes `convert_tile` gives it, at +/// every depth and texture kind. +#[test] +fn convert_tiles_converts_each_distinct_tile_once() { + let area = Rect::new(0, 0, TILE_SIZE * 9, TILE_SIZE * 9); + for (fmt, kind) in [ + (PixelFormat::RGBA8, TexKind::Rgba8Direct), + (PixelFormat { alpha: false, ..PixelFormat::RGBA8 }, TexKind::Rgba8), + (PixelFormat::RGBA16, TexKind::Rgba16F), + (PixelFormat::RGBA32F, TexKind::Rgba16F), + (PixelFormat::GRAY8, TexKind::R8Direct), + (PixelFormat { sample: SampleType::U16, ..PixelFormat::GRAY8 }, TexKind::R16F), + (PixelFormat { sample: SampleType::F32, ..PixelFormat::GRAY8 }, TexKind::R32F), + ] { + let mut s = Surface::new(fmt); + let px = [0.2, 0.4, 0.6, 1.0]; + let n = fmt.channels(); + // Fully covered tiles share one `Arc`; then two tiles get their own pixels. + s.fill_rect(area, &px[..n]); + s.fill_rect(Rect::new(3, 5, 40, 60), &[0.9, 0.1, 0.3, 0.5][..n]); + s.fill_rect(Rect::new(TILE_SIZE * 4 + 7, TILE_SIZE * 2, TILE_SIZE * 4 + 9, TILE_SIZE * 2 + 3), &[0.0; 4][..n]); + let tiles: Vec<_> = area.tiles().filter_map(|c| s.tile(c).map(|t| (c, t.clone()))).collect(); + assert_eq!(tiles.len(), 81, "{fmt:?}"); + let mut seen = Vec::new(); + let converted = convert_tiles(&s, tiles, kind, |t, cs, bytes| { + for &c in cs { + assert!(s.tile(c).is_some_and(|own| Arc::ptr_eq(own, t)), "{fmt:?} {c:?}"); + assert_eq!(bytes, convert_tile(&s, Some(t), kind, c).as_slice(), "{fmt:?} {c:?}"); + seen.push(c); + } + }); + assert_eq!(converted, 3, "{fmt:?}: the shared tile once, plus the two edited ones"); + seen.sort_by_key(|c| (c.ty, c.tx)); + let mut want: Vec<_> = area.tiles().collect(); + want.sort_by_key(|c| (c.ty, c.tx)); + assert_eq!(seen, want, "{fmt:?}: every coordinate once"); + } + // More distinct tiles than one batch: all converted, each coordinate once. + let mut s = Surface::new(PixelFormat::RGBA16); + let wide = Rect::new(0, 0, TILE_SIZE * (CONVERT_BATCH as i32 + 5), TILE_SIZE); + for c in wide.tiles() { + s.fill_rect(Rect::new(c.rect().x0, 0, c.rect().x0 + 1, 1), &[c.tx as f32 / 100.0, 0.0, 0.0, 1.0]); + } + let tiles: Vec<_> = wide.tiles().filter_map(|c| s.tile(c).map(|t| (c, t.clone()))).collect(); + let mut n = 0; + let converted = convert_tiles(&s, tiles, TexKind::Rgba16F, |t, cs, bytes| { + for &c in cs { + assert_eq!(bytes, convert_tile(&s, Some(t), TexKind::Rgba16F, c).as_slice()); + n += 1; + } + }); + assert_eq!((converted, n), (CONVERT_BATCH + 5, CONVERT_BATCH + 5)); +} + +/// The 16-bit and 32-bit float RGB/gray fast paths give exactly the general path's half +/// floats (32-bit samples above 1 and below 0 included). +#[test] +fn sixteen_and_thirty_two_bit_fast_paths_match_the_general_one() { + for fmt in [ + PixelFormat::RGBA16, + PixelFormat { alpha: false, ..PixelFormat::RGBA16 }, + PixelFormat { sample: SampleType::U16, ..PixelFormat::GRAY8 }, + PixelFormat { sample: SampleType::U16, alpha: true, ..PixelFormat::GRAY8 }, + PixelFormat::RGBA32F, + PixelFormat { alpha: false, ..PixelFormat::RGBA32F }, + PixelFormat { sample: SampleType::F32, ..PixelFormat::GRAY8 }, + PixelFormat { sample: SampleType::F32, alpha: true, ..PixelFormat::GRAY8 }, + ] { + let mut s = Surface::new(fmt); + let r = Rect::new(0, 0, TILE_SIZE, TILE_SIZE); + let n = (TILE_SIZE * TILE_SIZE) as usize * fmt.channels(); + let hdr = if fmt.sample == SampleType::F32 { 4.0 } else { 1.0 }; + let data: Vec = (0..n).map(|i| (i as u32).wrapping_mul(2_654_435_761) as f32 / u32::MAX as f32 * hdr - (hdr - 1.0) / 4.0).collect(); + s.write_region(r, &data); + let t = s.tile(TileCoord::new(0, 0)).expect("written").clone(); + let fast = rgb_gray16_to_f16(&fmt, t.bytes()).or_else(|| rgb_gray32_to_f16(&fmt, t.bytes())).expect("fast path"); + let raw = s.read_region(r); + let general: Vec = + raw.chunks_exact(fmt.channels()).flat_map(|px| photocraft_raster::to_rgba(&fmt, px).map(|x| f32_to_f16(x).to_le_bytes())).flatten().collect(); + assert_eq!(fast, general, "{fmt:?}"); + assert_eq!(convert_tile(&s, Some(&t), TexKind::Rgba16F, TileCoord::new(0, 0)), general, "{fmt:?}"); + } + assert!(rgb_gray16_to_f16(&PixelFormat::RGBA8, &[]).is_none()); + assert!(rgb_gray16_to_f16(&PixelFormat { sample: SampleType::U16, ..PixelFormat::CMYKA8 }, &[]).is_none()); + assert!(rgb_gray32_to_f16(&PixelFormat::RGBA16, &[]).is_none()); + assert!(rgb_gray32_to_f16(&PixelFormat { sample: SampleType::F32, ..PixelFormat::CMYKA8 }, &[]).is_none()); +} + +/// CMYK and Lab tiles convert in parallel bands of rows, each run of equal pixels once +/// (#5108): the texels are still exactly the per-pixel conversion's, at 8 and 16 bits, with +/// the built-in CMYK profile and with a document's own (which the worker threads enter). +#[test] +fn colour_managed_tiles_match_the_per_pixel_conversion() { + use photocraft_cms::synth::{CmykParams, cmyk_profile}; + use photocraft_color::ColorMode; + use photocraft_color::convert::{CmykSpace, with_cmyk_space}; + let icc = Arc::new( + cmyk_profile(&CmykParams { description: "GPU test CMYK".into(), tvi: [0.26, 0.26, 0.26, 0.3], grid_a2b: 5, grid_b2a: 9, ..Default::default() }) + .to_bytes(), + ); + let own = CmykSpace::for_profile(Some(&icc)); + assert!(own.is_some(), "the synthetic profile is not the built-in one"); + let area = Rect::new(0, 0, TILE_SIZE * 3, TILE_SIZE); + for (mode, sample, space) in [ + (ColorMode::Cmyk, SampleType::U8, None), + (ColorMode::Cmyk, SampleType::U16, None), + (ColorMode::Cmyk, SampleType::U8, own.clone()), + (ColorMode::Cmyk, SampleType::U16, own.clone()), + (ColorMode::Lab, SampleType::U8, None), + (ColorMode::Lab, SampleType::U16, None), + ] { + let fmt = PixelFormat { mode, sample, alpha: true }; + let kind = TexKind::for_surface(Role::Content, fmt); + assert!(colour_managed(&fmt, kind), "{fmt:?}"); + let ch = fmt.channels(); + let mut s = Surface::new(fmt); + // Tile 0: noise. Tile 1: transparent with a soft dab (runs of equal pixels). Tile 2: + // a flat colour with a few lines of noise. + let n = (TILE_SIZE * TILE_SIZE) as usize * ch; + let noise: Vec = (0..n).map(|i| (i as u32).wrapping_mul(2_654_435_761) as f32 / u32::MAX as f32).collect(); + s.write_region(Rect::new(0, 0, TILE_SIZE, TILE_SIZE), &noise); + let mut dab = [0.8, 0.6, 0.1, 0.05, 0.0]; + for r in (1..30).rev() { + dab[ch - 1] = 1.0 - r as f32 / 30.0; + s.fill_rect(Rect::new(TILE_SIZE + 100 - r, 90 - r, TILE_SIZE + 100 + r, 90 + r), &dab[..ch]); + } + s.fill_rect(Rect::new(TILE_SIZE * 2, 0, TILE_SIZE * 3, TILE_SIZE), &[0.3, 0.2, 0.7, 0.1, 1.0][..ch]); + s.write_region(Rect::new(TILE_SIZE * 2, 40, TILE_SIZE * 3, 43), &noise[..TILE_SIZE as usize * 3 * ch]); + let tiles: Vec<_> = area.tiles().filter_map(|c| s.tile(c).map(|t| (c, t.clone()))).collect(); + assert_eq!(tiles.len(), 3, "{fmt:?}"); + let mut seen = 0; + with_cmyk_space(space.as_ref(), || { + convert_tiles(&s, tiles, kind, |_, cs, bytes| { + for &c in cs { + // The old path: every pixel through `to_rgba` on this thread, in this scope. + let want: Vec = s + .read_region(c.rect()) + .chunks_exact(ch) + .flat_map(|px| { + let v = photocraft_raster::to_rgba(&fmt, px); + match kind { + TexKind::Rgba16F => v.iter().flat_map(|x| f32_to_f16(*x).to_le_bytes()).collect::>(), + _ => v.map(|x| (x.clamp(0.0, 1.0) * 255.0 + 0.5) as u8).to_vec(), + } + }) + .collect(); + assert!( + bytes == want.as_slice(), + "{fmt:?} {c:?} with {}", + if space.is_some() { "the document's profile" } else { "the built-in profile" } + ); + assert_eq!(convert_tile(&s, s.tile(c), kind, c), want, "{fmt:?} {c:?}"); + seen += 1; + } + }); + }); + assert_eq!(seen, 3, "{fmt:?}"); + } +} + +#[test] +fn grid_rounds_out() { + assert_eq!(tile_grid(Rect::new(0, 0, 300, 256)), Rect::new(0, 0, 512, 256)); +} From 2d248b9adeb119a65313eddeea6f19a1d25f161d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:17:58 +0000 Subject: [PATCH 127/259] refactor(gpu): move fx.rs tests to fx/tests.rs --- crates/gpu/src/fx.rs | 314 +------------------------------------ crates/gpu/src/fx/tests.rs | 311 ++++++++++++++++++++++++++++++++++++ 2 files changed, 312 insertions(+), 313 deletions(-) create mode 100644 crates/gpu/src/fx/tests.rs diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index 898eb2b87a..34982cd2be 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -757,316 +757,4 @@ pub(crate) fn group_key(layer: &Layer, light: &GlobalLight, pin: &mut dyn FnMut( #[cfg(test)] #[allow(clippy::unreachable)] // clippy.toml exempts unwrap/expect/panic in tests, not unreachable! -mod tests { - use super::*; - use photocraft_color::BlendMode; - use photocraft_doc::FxCommon; - - /// Filled-shape identity survives integer moves, including fractional anchors and handles. - #[test] - fn filled_shape_key_preserves_translation_but_detects_deformation() { - use photocraft_doc::{Fill, Path, ShapeLayer, Subpath}; - let mut layer = Layer::new( - "shape", - LayerContent::Shape(ShapeLayer { - path: Path::new(vec![Subpath::polygon(&[(20.0, 20.0), (70.0, 20.0), (70.0, 60.0), (20.0, 60.0)])]), - fill: Some(Fill::Solid(photocraft_color::Color::WHITE)), - ..Default::default() - }), - ); - let canvas = Rect::new(0, 0, 200, 200); - let before = shape_key(&layer, canvas); - let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; - shape.path = shape.path.transform(&photocraft_geom::Affine::translate(13.0, 7.0)); - assert_eq!(before, shape_key(&layer, canvas)); - let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; - shape.path.subpaths[0].knots[1].anchor.x += 3.0; - assert_ne!(before, shape_key(&layer, canvas)); - - let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; - shape.path = Path::new(vec![Subpath::polygon(&[(0.1, 0.2), (0.3, 0.2), (0.3, 1.7), (0.1, 1.7)])]); - shape.path.subpaths[0].knots[1].out_ctrl = photocraft_geom::Point::new(0.45, 0.65); - let original = shape.path.clone(); - let before = shape_key(&layer, canvas); - for (dx, dy) in [(1.0, 1.0), (-13.0, 7.0), (100_000.0, -100_000.0)] { - let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; - shape.path = original.transform(&photocraft_geom::Affine::translate(dx, dy)); - assert_eq!(before, shape_key(&layer, canvas), "fractional path translated by {dx}, {dy}"); - } - let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; - shape.path.subpaths[0].knots[1].out_ctrl.x += 0.01; - assert_ne!(before, shape_key(&layer, canvas), "a handle deformation invalidates the key"); - } - - #[test] - fn programs_key_on_geometry_not_colour() { - let light = GlobalLight::default(); - let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; - let a = program(&Effect::DropShadow(s.clone()), &light, false); - s.color = photocraft_color::Color::rgb(1.0, 0.0, 0.0); - s.common = FxCommon::new(BlendMode::Screen, 0.3); - let b = program(&Effect::DropShadow(s.clone()), &light, false); - assert_eq!(a.key, b.key); - s.size += 1.0; - assert_ne!(a.key, program(&Effect::DropShadow(s), &light, false).key); - } - - /// A styled group's effect shape follows its own vector mask and its children's Blend If and - /// Advanced Blending, so the cached shape must be rebuilt when any of them changes. - #[test] - fn group_key_follows_vector_mask_blend_if_and_advanced() { - use photocraft_doc::{BlendRange, Knockout, Path, PixelFormat, Subpath, VectorMask}; - let light = GlobalLight::default(); - let group = Layer::group("g", vec![Layer::raster("child", PixelFormat::RGBA8)]); - let base = group_key(&group, &light, &mut |_| {}); - - let mask = |x: f64| VectorMask::new(Path::new(vec![Subpath::polygon(&[(x, 0.0), (x + 10.0, 0.0), (x + 10.0, 10.0)])])); - let mut masked = group.clone(); - masked.vector_mask = Some(mask(0.0)); - let with_mask = group_key(&masked, &light, &mut |_| {}); - assert_ne!(base, with_mask, "adding the group's vector mask"); - masked.vector_mask = Some(mask(5.0)); - assert_ne!(with_mask, group_key(&masked, &light, &mut |_| {}), "moving the group's vector mask"); - - fn child_mut(g: &mut Layer) -> &mut Layer { - let LayerContent::Group(gr) = &mut g.content else { unreachable!() }; - &mut gr.children[0] - } - let mut blend_if = group.clone(); - child_mut(&mut blend_if).blend_if.ranges = vec![[BlendRange { black: [128, 128], white: [255, 255] }, BlendRange::FULL]]; - assert_ne!(base, group_key(&blend_if, &light, &mut |_| {}), "a child's Blend If"); - - let mut advanced = group.clone(); - child_mut(&mut advanced).advanced.knockout = Knockout::Deep; - assert_ne!(base, group_key(&advanced, &light, &mut |_| {}), "a child's Advanced Blending"); - } - - #[test] - fn windows_grow_by_reach_and_temps_are_reused() { - let light = GlobalLight::default(); - let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; - s.spread = 0.5; - let p = program(&Effect::DropShadow(s), &light, false); - let region = Rect::new(-100, -100, 1000, 1000); - let d = Rect::new(0, 0, 10, 10); - let fr = |_| 5; - let w = p.windows(d, region, &fr); - let last = *w.last().unwrap(); - assert!(last.contains_rect(&d.inflate(7)), "{last:?}"); - // Earlier stages need at least as much as later ones read. - assert!(w[0].width() >= last.width()); - let (t, n) = p.temps(); - assert!(n <= 3, "{n} temporaries for {} stages", p.stages.len()); - assert!(t.last().unwrap().is_none()); - } - - /// A distance field computed in bands from grown windows equals the whole-region field - /// wherever it is within its reach (the property incremental updates rely on). - #[test] - fn banded_fields_match_whole_region_within_reach() { - let region = Rect::new(-20, -10, 300, 290); - let (w, h) = (region.width() as usize, region.height() as usize); - let mut shape = vec![0.0f32; w * h]; - for y in 0..h { - for x in 0..w { - let (fx, fy) = (x as f32 - 150.0, y as f32 - 140.0); - let r = (fx * fx + fy * fy).sqrt() + 8.0 * (fy * 0.07).sin() * (fx * 0.05).cos(); - shape[y * w + x] = (90.0 - r).clamp(0.0, 1.0) * if (x / 13 + y / 17) % 5 == 0 { 0.6 } else { 1.0 }; - } - } - for kind in [ - FieldKind::Outside, - FieldKind::Inside, - FieldKind::BevelOutside, - FieldKind::BevelInside, - FieldKind::ChokeInside, - FieldKind::StrokeOutside, - FieldKind::StrokeInside, - FieldKind::StrokeOutsideExact, - FieldKind::StrokeOutsideVector, - FieldKind::StrokeOutsideVectorChamfer, - ] { - let reach = 9; - let whole = photocraft_compose::effects::distance_field(kind, shape.clone(), w, h, reach as f32); - let banded = field(kind, reach, &shape, region, region); - let part = Rect::new(40, 30, 170, 120); - let partial = field(kind, reach, &shape, region, part); - for (i, (a, b)) in whole.iter().zip(&banded).enumerate() { - if a.min(*b) < reach as f32 { - assert!((a - b).abs() < 1e-5, "{kind:?} at {i}: {a} vs {b}"); - } - } - for (i, b) in partial.iter().enumerate() { - let (x, y) = (part.x0 + (i % part.width() as usize) as i32, part.y0 + (i / part.width() as usize) as i32); - let a = whole[(y - region.y0) as usize * w + (x - region.x0) as usize]; - if a.min(*b) < reach as f32 { - assert!((a - b).abs() < 1e-5, "{kind:?} at ({x},{y}): {a} vs {b}"); - } - } - } - } - #[test] - fn windowed_bevel_fields_match_whole_region_on_anti_aliased_edges() { - // The bevel fields read the edge pixels around the foot of the perpendicular and take the - // direction of each from its neighbours, so the halo of a part of the region has to cover all of - // that. A wide bar with clean anti-aliased edges (almost along the 128 row bands the other - // fields use, across them and at an angle) puts sharp edge pixels where bands would meet and - // inside the partial window. The whole region is one window, so it is exactly the CPU's field. - let region = Rect::new(-20, -10, 300, 290); - let (w, h) = (region.width() as usize, region.height() as usize); - let part = Rect::new(40, 30, 170, 120); - let mut too_small_noticed = false; - for deg in [1.5f32, 5.0, 30.0, 88.5] { - let (sn, cs) = deg.to_radians().sin_cos(); - let inside = |x: f32, y: f32| { - let (u, v) = ((x - 150.0) * cs + (y - 128.3) * sn, -(x - 150.0) * sn + (y - 128.3) * cs); - u.abs() <= 140.0 && v.abs() <= 60.0 - }; - let mut shape = vec![0.0f32; w * h]; - for y in 0..h { - for x in 0..w { - let hits = (0..64).filter(|k| inside(x as f32 + ((k % 8) as f32 + 0.5) / 8.0, y as f32 + ((k / 8) as f32 + 0.5) / 8.0)).count(); - shape[y * w + x] = hits as f32 / 64.0; - } - } - for reach in [9, 24] { - for kind in [FieldKind::BevelInside, FieldKind::BevelOutside] { - let whole = photocraft_compose::effects::distance_field(kind, shape.clone(), w, h, reach as f32); - let differs = |part_field: &[f32], out: Rect| { - let ow = out.width() as usize; - part_field - .iter() - .enumerate() - .filter(|&(i, b)| { - let (x, y) = (out.x0 + (i % ow) as i32, out.y0 + (i / ow) as i32); - let a = whole[(y - region.y0) as usize * w + (x - region.x0) as usize]; - a.min(*b) < reach as f32 && (a - b).abs() > 1e-5 - }) - .count() - }; - let all = field(kind, reach, &shape, region, region); - assert!( - all.iter().zip(&whole).all(|(a, b)| a.to_bits() == b.to_bits()), - "{kind:?}, {deg} deg, reach {reach}: the whole region is not the CPU's field" - ); - assert_eq!( - differs(&field(kind, reach, &shape, region, part), part), - 0, - "{kind:?}, {deg} deg, reach {reach}: partial window differs from whole" - ); - // The test can see a halo that is too small: two rows past the part is not enough. - too_small_noticed |= differs(&field_banded(kind, reach, &shape, region, part, 2), part) > 0; - } - } - } - assert!(too_small_noticed, "a 2 row halo went unnoticed, so this test guards nothing"); - } - - /// Both bevel fields from one window (sharp edges found once) are bit for bit the fields - /// computed one at a time, over the whole region and over a part of it. - #[test] - fn paired_bevel_fields_equal_the_fields_one_at_a_time() { - let region = Rect::new(-20, -10, 300, 290); - let (w, h) = (region.width() as usize, region.height() as usize); - let mut shape = vec![0.0f32; w * h]; - for y in 0..h { - for x in 0..w { - let (fx, fy) = (x as f32 - 150.0, y as f32 - 140.0); - let r = (fx * fx + fy * fy).sqrt() + 8.0 * (fy * 0.07).sin() * (fx * 0.05).cos(); - shape[y * w + x] = (90.0 - r).clamp(0.0, 1.0) * if (x / 13 + y / 17) % 5 == 0 { 0.6 } else { 1.0 }; - } - } - let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>(); - for reach in [3, 9, 40] { - for out in [region, Rect::new(40, 30, 170, 120), Rect::new(-20, 200, 300, 290)] { - let [inside, outside] = bevel_fields(reach, &shape, region, out); - assert_eq!(bits(&inside), bits(&field(FieldKind::BevelInside, reach, &shape, region, out)), "inside, reach {reach}, {out:?}"); - assert_eq!(bits(&outside), bits(&field(FieldKind::BevelOutside, reach, &shape, region, out)), "outside, reach {reach}, {out:?}"); - // The banded path (wasm) pairs them per band the same way. - let halo = field_radius(FieldKind::BevelInside, reach) + 1; - let banded = - fields_in_windows(false, &shape, region, out, halo, |s, w, h| photocraft_compose::effects::bevel_distance_fields(s, w, h, reach as f32)); - for (k, kind) in [FieldKind::BevelInside, FieldKind::BevelOutside].into_iter().enumerate() { - let [one] = fields_in_windows(false, &shape, region, out, halo, |s, w, h| { - [photocraft_compose::effects::distance_field(kind, s, w, h, reach as f32)] - }); - assert_eq!(bits(&banded[k]), bits(&one), "banded {kind:?}, reach {reach}, {out:?}"); - } - } - } - } - - /// #3646: a stroke's outer edge is the fitted 5 × 5 chamfer while it is narrow and the exact - /// Euclidean transform once it is wide — the chamfer's octagon facets a wide stroke. The GPU - /// builds it from the field its width picks (`stroke_outside_exact`), while the spread of drop - /// shadows and softer outer glows keeps the chamfer field (fitted to Photoshop, #224) — so - /// routing a wide stroke through the chamfer, or a shadow through the exact field, fails here. - #[test] - fn a_stroke_uses_the_chamfer_narrow_and_the_exact_field_wide() { - use photocraft_color::{BlendMode, Color}; - use photocraft_doc::{FxCommon, FxPaint, StrokeFx, StrokePosition}; - let light = GlobalLight::default(); - let stroke = |size, position| { - Effect::Stroke(StrokeFx { common: FxCommon::new(BlendMode::Normal, 1.0), size, position, paint: FxPaint::Color(Color::BLACK), overprint: false }) - }; - // Narrow (< STROKE_CHAMFER_MAX): the chamfer, exactly as before #3646. - let narrow = program(&stroke(6.0, StrokePosition::Outside), &light, false); - assert!(narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "a narrow raster outside stroke keeps the chamfer: {:?}", narrow.fields); - assert!(!narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideExact), "…not the exact field: {:?}", narrow.fields); - // Wide: the exact transform. - let wide = program(&stroke(40.0, StrokePosition::Outside), &light, false); - assert!( - wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideExact), - "a wide raster outside stroke needs the exact outer field: {:?}", - wide.fields - ); - assert!(!wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "…not the chamfer field: {:?}", wide.fields); - // A shape layer's outline stroke follows the same width rule; the inside edge keeps the chamfer. - let vector_narrow = program(&stroke(6.0, StrokePosition::Outside), &light, true); - assert!(vector_narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideVectorChamfer), "{:?}", vector_narrow.fields); - let vector_wide = program(&stroke(40.0, StrokePosition::Outside), &light, true); - assert!(vector_wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideVector), "{:?}", vector_wide.fields); - let inner = program(&stroke(40.0, StrokePosition::Inside), &light, false); - assert!(inner.fields.iter().any(|(k, _)| *k == FieldKind::StrokeInside), "{:?}", inner.fields); - // The shadow / softer-glow spread is unchanged: still the chamfer. - let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; - s.spread = 0.5; - let shadow = program(&Effect::DropShadow(s), &light, false); - assert!(shadow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "the shadow spread keeps the chamfer: {:?}", shadow.fields); - } - - /// Cached shapes and group keys reserve tile addresses without keeping pixels (#4530): - /// damage still tells a replaced tile from an unchanged one, and a dropped tile's pixels - /// are freed although the entry remembers it. - #[test] - fn shape_tiles_and_group_pins_hold_addresses_not_pixels() { - use photocraft_color::{ColorMode, PixelFormat, SampleType}; - let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true); - let mut s = Surface::new(fmt); - // A ramp, so no two tiles share their pixels. - for x in 0..600 { - let v = x as f32 / 600.0; - s.fill_rect(Rect::new(x, 0, x + 1, 300), &[v, 0.2, 0.9, 1.0]); - } - let first = s.tiles().find(|(c, _)| c.tx == 0 && c.ty == 0).map(|(_, t)| t.clone()).unwrap(); - assert_eq!(Arc::strong_count(&first), 2); - let old = snapshot(&s); - assert_eq!(Arc::strong_count(&first), 2, "the snapshot adds no strong reference"); - assert!(damage(&old, &s).is_empty()); - s.fill_rect(Rect::new(0, 0, 4, 4), &[0.0, 0.0, 0.0, 1.0]); - let origin = s.tiles().map(|(c, _)| *c).find(|c| c.tx == 0 && c.ty == 0).unwrap(); - assert_eq!(damage(&old, &s), origin.rect(), "only the edited tile"); - drop(first); - assert!(old.values().any(|w| w.strong_count() == 0), "the replaced tile's pixels are freed"); - - let child = Layer::new("c", LayerContent::Raster(s)); - let n = child.surface().map_or(0, |s| s.tile_count()); - let group = Layer::group("g", vec![child]); - let mut pins = Vec::new(); - let key = group_key(&group, &GlobalLight::default(), &mut |t| pins.push(Arc::downgrade(t))); - assert_eq!(key, group_key(&group, &GlobalLight::default(), &mut |_| {}), "pinning doesn't change the key"); - assert_eq!(pins.len(), n); - drop(group); - assert!(pins.iter().all(|w| w.strong_count() == 0), "a group's pins keep none of its pixels"); - } -} +mod tests; diff --git a/crates/gpu/src/fx/tests.rs b/crates/gpu/src/fx/tests.rs new file mode 100644 index 0000000000..807d86be80 --- /dev/null +++ b/crates/gpu/src/fx/tests.rs @@ -0,0 +1,311 @@ +use super::*; +use photocraft_color::BlendMode; +use photocraft_doc::FxCommon; + +/// Filled-shape identity survives integer moves, including fractional anchors and handles. +#[test] +fn filled_shape_key_preserves_translation_but_detects_deformation() { + use photocraft_doc::{Fill, Path, ShapeLayer, Subpath}; + let mut layer = Layer::new( + "shape", + LayerContent::Shape(ShapeLayer { + path: Path::new(vec![Subpath::polygon(&[(20.0, 20.0), (70.0, 20.0), (70.0, 60.0), (20.0, 60.0)])]), + fill: Some(Fill::Solid(photocraft_color::Color::WHITE)), + ..Default::default() + }), + ); + let canvas = Rect::new(0, 0, 200, 200); + let before = shape_key(&layer, canvas); + let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; + shape.path = shape.path.transform(&photocraft_geom::Affine::translate(13.0, 7.0)); + assert_eq!(before, shape_key(&layer, canvas)); + let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; + shape.path.subpaths[0].knots[1].anchor.x += 3.0; + assert_ne!(before, shape_key(&layer, canvas)); + + let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; + shape.path = Path::new(vec![Subpath::polygon(&[(0.1, 0.2), (0.3, 0.2), (0.3, 1.7), (0.1, 1.7)])]); + shape.path.subpaths[0].knots[1].out_ctrl = photocraft_geom::Point::new(0.45, 0.65); + let original = shape.path.clone(); + let before = shape_key(&layer, canvas); + for (dx, dy) in [(1.0, 1.0), (-13.0, 7.0), (100_000.0, -100_000.0)] { + let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; + shape.path = original.transform(&photocraft_geom::Affine::translate(dx, dy)); + assert_eq!(before, shape_key(&layer, canvas), "fractional path translated by {dx}, {dy}"); + } + let LayerContent::Shape(shape) = &mut layer.content else { unreachable!() }; + shape.path.subpaths[0].knots[1].out_ctrl.x += 0.01; + assert_ne!(before, shape_key(&layer, canvas), "a handle deformation invalidates the key"); +} + +#[test] +fn programs_key_on_geometry_not_colour() { + let light = GlobalLight::default(); + let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; + let a = program(&Effect::DropShadow(s.clone()), &light, false); + s.color = photocraft_color::Color::rgb(1.0, 0.0, 0.0); + s.common = FxCommon::new(BlendMode::Screen, 0.3); + let b = program(&Effect::DropShadow(s.clone()), &light, false); + assert_eq!(a.key, b.key); + s.size += 1.0; + assert_ne!(a.key, program(&Effect::DropShadow(s), &light, false).key); +} + +/// A styled group's effect shape follows its own vector mask and its children's Blend If and +/// Advanced Blending, so the cached shape must be rebuilt when any of them changes. +#[test] +fn group_key_follows_vector_mask_blend_if_and_advanced() { + use photocraft_doc::{BlendRange, Knockout, Path, PixelFormat, Subpath, VectorMask}; + let light = GlobalLight::default(); + let group = Layer::group("g", vec![Layer::raster("child", PixelFormat::RGBA8)]); + let base = group_key(&group, &light, &mut |_| {}); + + let mask = |x: f64| VectorMask::new(Path::new(vec![Subpath::polygon(&[(x, 0.0), (x + 10.0, 0.0), (x + 10.0, 10.0)])])); + let mut masked = group.clone(); + masked.vector_mask = Some(mask(0.0)); + let with_mask = group_key(&masked, &light, &mut |_| {}); + assert_ne!(base, with_mask, "adding the group's vector mask"); + masked.vector_mask = Some(mask(5.0)); + assert_ne!(with_mask, group_key(&masked, &light, &mut |_| {}), "moving the group's vector mask"); + + fn child_mut(g: &mut Layer) -> &mut Layer { + let LayerContent::Group(gr) = &mut g.content else { unreachable!() }; + &mut gr.children[0] + } + let mut blend_if = group.clone(); + child_mut(&mut blend_if).blend_if.ranges = vec![[BlendRange { black: [128, 128], white: [255, 255] }, BlendRange::FULL]]; + assert_ne!(base, group_key(&blend_if, &light, &mut |_| {}), "a child's Blend If"); + + let mut advanced = group.clone(); + child_mut(&mut advanced).advanced.knockout = Knockout::Deep; + assert_ne!(base, group_key(&advanced, &light, &mut |_| {}), "a child's Advanced Blending"); +} + +#[test] +fn windows_grow_by_reach_and_temps_are_reused() { + let light = GlobalLight::default(); + let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; + s.spread = 0.5; + let p = program(&Effect::DropShadow(s), &light, false); + let region = Rect::new(-100, -100, 1000, 1000); + let d = Rect::new(0, 0, 10, 10); + let fr = |_| 5; + let w = p.windows(d, region, &fr); + let last = *w.last().unwrap(); + assert!(last.contains_rect(&d.inflate(7)), "{last:?}"); + // Earlier stages need at least as much as later ones read. + assert!(w[0].width() >= last.width()); + let (t, n) = p.temps(); + assert!(n <= 3, "{n} temporaries for {} stages", p.stages.len()); + assert!(t.last().unwrap().is_none()); +} + +/// A distance field computed in bands from grown windows equals the whole-region field +/// wherever it is within its reach (the property incremental updates rely on). +#[test] +fn banded_fields_match_whole_region_within_reach() { + let region = Rect::new(-20, -10, 300, 290); + let (w, h) = (region.width() as usize, region.height() as usize); + let mut shape = vec![0.0f32; w * h]; + for y in 0..h { + for x in 0..w { + let (fx, fy) = (x as f32 - 150.0, y as f32 - 140.0); + let r = (fx * fx + fy * fy).sqrt() + 8.0 * (fy * 0.07).sin() * (fx * 0.05).cos(); + shape[y * w + x] = (90.0 - r).clamp(0.0, 1.0) * if (x / 13 + y / 17) % 5 == 0 { 0.6 } else { 1.0 }; + } + } + for kind in [ + FieldKind::Outside, + FieldKind::Inside, + FieldKind::BevelOutside, + FieldKind::BevelInside, + FieldKind::ChokeInside, + FieldKind::StrokeOutside, + FieldKind::StrokeInside, + FieldKind::StrokeOutsideExact, + FieldKind::StrokeOutsideVector, + FieldKind::StrokeOutsideVectorChamfer, + ] { + let reach = 9; + let whole = photocraft_compose::effects::distance_field(kind, shape.clone(), w, h, reach as f32); + let banded = field(kind, reach, &shape, region, region); + let part = Rect::new(40, 30, 170, 120); + let partial = field(kind, reach, &shape, region, part); + for (i, (a, b)) in whole.iter().zip(&banded).enumerate() { + if a.min(*b) < reach as f32 { + assert!((a - b).abs() < 1e-5, "{kind:?} at {i}: {a} vs {b}"); + } + } + for (i, b) in partial.iter().enumerate() { + let (x, y) = (part.x0 + (i % part.width() as usize) as i32, part.y0 + (i / part.width() as usize) as i32); + let a = whole[(y - region.y0) as usize * w + (x - region.x0) as usize]; + if a.min(*b) < reach as f32 { + assert!((a - b).abs() < 1e-5, "{kind:?} at ({x},{y}): {a} vs {b}"); + } + } + } +} +#[test] +fn windowed_bevel_fields_match_whole_region_on_anti_aliased_edges() { + // The bevel fields read the edge pixels around the foot of the perpendicular and take the + // direction of each from its neighbours, so the halo of a part of the region has to cover all of + // that. A wide bar with clean anti-aliased edges (almost along the 128 row bands the other + // fields use, across them and at an angle) puts sharp edge pixels where bands would meet and + // inside the partial window. The whole region is one window, so it is exactly the CPU's field. + let region = Rect::new(-20, -10, 300, 290); + let (w, h) = (region.width() as usize, region.height() as usize); + let part = Rect::new(40, 30, 170, 120); + let mut too_small_noticed = false; + for deg in [1.5f32, 5.0, 30.0, 88.5] { + let (sn, cs) = deg.to_radians().sin_cos(); + let inside = |x: f32, y: f32| { + let (u, v) = ((x - 150.0) * cs + (y - 128.3) * sn, -(x - 150.0) * sn + (y - 128.3) * cs); + u.abs() <= 140.0 && v.abs() <= 60.0 + }; + let mut shape = vec![0.0f32; w * h]; + for y in 0..h { + for x in 0..w { + let hits = (0..64).filter(|k| inside(x as f32 + ((k % 8) as f32 + 0.5) / 8.0, y as f32 + ((k / 8) as f32 + 0.5) / 8.0)).count(); + shape[y * w + x] = hits as f32 / 64.0; + } + } + for reach in [9, 24] { + for kind in [FieldKind::BevelInside, FieldKind::BevelOutside] { + let whole = photocraft_compose::effects::distance_field(kind, shape.clone(), w, h, reach as f32); + let differs = |part_field: &[f32], out: Rect| { + let ow = out.width() as usize; + part_field + .iter() + .enumerate() + .filter(|&(i, b)| { + let (x, y) = (out.x0 + (i % ow) as i32, out.y0 + (i / ow) as i32); + let a = whole[(y - region.y0) as usize * w + (x - region.x0) as usize]; + a.min(*b) < reach as f32 && (a - b).abs() > 1e-5 + }) + .count() + }; + let all = field(kind, reach, &shape, region, region); + assert!( + all.iter().zip(&whole).all(|(a, b)| a.to_bits() == b.to_bits()), + "{kind:?}, {deg} deg, reach {reach}: the whole region is not the CPU's field" + ); + assert_eq!( + differs(&field(kind, reach, &shape, region, part), part), + 0, + "{kind:?}, {deg} deg, reach {reach}: partial window differs from whole" + ); + // The test can see a halo that is too small: two rows past the part is not enough. + too_small_noticed |= differs(&field_banded(kind, reach, &shape, region, part, 2), part) > 0; + } + } + } + assert!(too_small_noticed, "a 2 row halo went unnoticed, so this test guards nothing"); +} + +/// Both bevel fields from one window (sharp edges found once) are bit for bit the fields +/// computed one at a time, over the whole region and over a part of it. +#[test] +fn paired_bevel_fields_equal_the_fields_one_at_a_time() { + let region = Rect::new(-20, -10, 300, 290); + let (w, h) = (region.width() as usize, region.height() as usize); + let mut shape = vec![0.0f32; w * h]; + for y in 0..h { + for x in 0..w { + let (fx, fy) = (x as f32 - 150.0, y as f32 - 140.0); + let r = (fx * fx + fy * fy).sqrt() + 8.0 * (fy * 0.07).sin() * (fx * 0.05).cos(); + shape[y * w + x] = (90.0 - r).clamp(0.0, 1.0) * if (x / 13 + y / 17) % 5 == 0 { 0.6 } else { 1.0 }; + } + } + let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>(); + for reach in [3, 9, 40] { + for out in [region, Rect::new(40, 30, 170, 120), Rect::new(-20, 200, 300, 290)] { + let [inside, outside] = bevel_fields(reach, &shape, region, out); + assert_eq!(bits(&inside), bits(&field(FieldKind::BevelInside, reach, &shape, region, out)), "inside, reach {reach}, {out:?}"); + assert_eq!(bits(&outside), bits(&field(FieldKind::BevelOutside, reach, &shape, region, out)), "outside, reach {reach}, {out:?}"); + // The banded path (wasm) pairs them per band the same way. + let halo = field_radius(FieldKind::BevelInside, reach) + 1; + let banded = + fields_in_windows(false, &shape, region, out, halo, |s, w, h| photocraft_compose::effects::bevel_distance_fields(s, w, h, reach as f32)); + for (k, kind) in [FieldKind::BevelInside, FieldKind::BevelOutside].into_iter().enumerate() { + let [one] = fields_in_windows(false, &shape, region, out, halo, |s, w, h| { + [photocraft_compose::effects::distance_field(kind, s, w, h, reach as f32)] + }); + assert_eq!(bits(&banded[k]), bits(&one), "banded {kind:?}, reach {reach}, {out:?}"); + } + } + } +} + +/// #3646: a stroke's outer edge is the fitted 5 × 5 chamfer while it is narrow and the exact +/// Euclidean transform once it is wide — the chamfer's octagon facets a wide stroke. The GPU +/// builds it from the field its width picks (`stroke_outside_exact`), while the spread of drop +/// shadows and softer outer glows keeps the chamfer field (fitted to Photoshop, #224) — so +/// routing a wide stroke through the chamfer, or a shadow through the exact field, fails here. +#[test] +fn a_stroke_uses_the_chamfer_narrow_and_the_exact_field_wide() { + use photocraft_color::{BlendMode, Color}; + use photocraft_doc::{FxCommon, FxPaint, StrokeFx, StrokePosition}; + let light = GlobalLight::default(); + let stroke = |size, position| { + Effect::Stroke(StrokeFx { common: FxCommon::new(BlendMode::Normal, 1.0), size, position, paint: FxPaint::Color(Color::BLACK), overprint: false }) + }; + // Narrow (< STROKE_CHAMFER_MAX): the chamfer, exactly as before #3646. + let narrow = program(&stroke(6.0, StrokePosition::Outside), &light, false); + assert!(narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "a narrow raster outside stroke keeps the chamfer: {:?}", narrow.fields); + assert!(!narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideExact), "…not the exact field: {:?}", narrow.fields); + // Wide: the exact transform. + let wide = program(&stroke(40.0, StrokePosition::Outside), &light, false); + assert!( + wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideExact), + "a wide raster outside stroke needs the exact outer field: {:?}", + wide.fields + ); + assert!(!wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "…not the chamfer field: {:?}", wide.fields); + // A shape layer's outline stroke follows the same width rule; the inside edge keeps the chamfer. + let vector_narrow = program(&stroke(6.0, StrokePosition::Outside), &light, true); + assert!(vector_narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideVectorChamfer), "{:?}", vector_narrow.fields); + let vector_wide = program(&stroke(40.0, StrokePosition::Outside), &light, true); + assert!(vector_wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideVector), "{:?}", vector_wide.fields); + let inner = program(&stroke(40.0, StrokePosition::Inside), &light, false); + assert!(inner.fields.iter().any(|(k, _)| *k == FieldKind::StrokeInside), "{:?}", inner.fields); + // The shadow / softer-glow spread is unchanged: still the chamfer. + let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; + s.spread = 0.5; + let shadow = program(&Effect::DropShadow(s), &light, false); + assert!(shadow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "the shadow spread keeps the chamfer: {:?}", shadow.fields); +} + +/// Cached shapes and group keys reserve tile addresses without keeping pixels (#4530): +/// damage still tells a replaced tile from an unchanged one, and a dropped tile's pixels +/// are freed although the entry remembers it. +#[test] +fn shape_tiles_and_group_pins_hold_addresses_not_pixels() { + use photocraft_color::{ColorMode, PixelFormat, SampleType}; + let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true); + let mut s = Surface::new(fmt); + // A ramp, so no two tiles share their pixels. + for x in 0..600 { + let v = x as f32 / 600.0; + s.fill_rect(Rect::new(x, 0, x + 1, 300), &[v, 0.2, 0.9, 1.0]); + } + let first = s.tiles().find(|(c, _)| c.tx == 0 && c.ty == 0).map(|(_, t)| t.clone()).unwrap(); + assert_eq!(Arc::strong_count(&first), 2); + let old = snapshot(&s); + assert_eq!(Arc::strong_count(&first), 2, "the snapshot adds no strong reference"); + assert!(damage(&old, &s).is_empty()); + s.fill_rect(Rect::new(0, 0, 4, 4), &[0.0, 0.0, 0.0, 1.0]); + let origin = s.tiles().map(|(c, _)| *c).find(|c| c.tx == 0 && c.ty == 0).unwrap(); + assert_eq!(damage(&old, &s), origin.rect(), "only the edited tile"); + drop(first); + assert!(old.values().any(|w| w.strong_count() == 0), "the replaced tile's pixels are freed"); + + let child = Layer::new("c", LayerContent::Raster(s)); + let n = child.surface().map_or(0, |s| s.tile_count()); + let group = Layer::group("g", vec![child]); + let mut pins = Vec::new(); + let key = group_key(&group, &GlobalLight::default(), &mut |t| pins.push(Arc::downgrade(t))); + assert_eq!(key, group_key(&group, &GlobalLight::default(), &mut |_| {}), "pinning doesn't change the key"); + assert_eq!(pins.len(), n); + drop(group); + assert!(pins.iter().all(|w| w.strong_count() == 0), "a group's pins keep none of its pixels"); +} From 84a9b585b4b7ccef41c9f48f8a4a07fefe6aced4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:18:00 +0000 Subject: [PATCH 128/259] refactor(raster): move lib.rs tests to tests.rs --- crates/raster/src/lib.rs | 785 +------------------------------------ crates/raster/src/tests.rs | 780 ++++++++++++++++++++++++++++++++++++ 2 files changed, 781 insertions(+), 784 deletions(-) create mode 100644 crates/raster/src/tests.rs diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index ce70830f37..4aa50c5a60 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -1237,790 +1237,7 @@ pub fn is_hdr(sample: SampleType) -> bool { } #[cfg(test)] -mod tests { - - /// Manually compare allocating reads with the previous implementation. - #[test] - #[ignore = "manual 24 MP release benchmark"] - fn benchmark_sparse_reads() { - use std::{hint::black_box, time::Instant}; - let rect = Rect::new(0, 0, 6000, 4000); - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for default in [0.0, 0.25] { - let mut s = Surface::with_default(PixelFormat::GRAY8.with_sample(depth), &[default]); - s.fill_rect(Rect::new(257, 257, 266, 266), &[0.75]); - assert_eq!(s.read_region(rect), previous_read_region(&s, rect)); - for trial in 0..6 { - let mut paths = [("main", previous_read_region as fn(&Surface, Rect) -> Vec), ("split", Surface::read_region)]; - if trial % 2 == 1 { - paths.reverse(); - } - for (name, path) in paths { - let t = Instant::now(); - let out = black_box(path)(&s, rect); - let elapsed = t.elapsed().as_secs_f64() * 1000.0; - black_box(&out); - println!("sparse,{depth:?}-{default},{trial},{name},{elapsed:.6}"); - } - } - } - } - } - /// Previous allocating read path, retained as the bitwise-equivalence oracle. - fn previous_read_region(surface: &Surface, r: Rect) -> Vec { - let n = surface.channels(); - let w = r.width() as usize; - let mut out = vec![0.0f32; w * r.height() as usize * n]; - let dp = surface.default_pixel(); - for tc in r.tiles() { - let tr = tc.rect().intersect(&r); - let tile = surface.tiles.get(&tc); - for y in tr.y0..tr.y1 { - for x in tr.x0..tr.x1 { - let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; - match tile { - Some(t) => { - let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n; - for i in 0..n { - out[o + i] = read_sample(&t.data, surface.format.sample, base + i); - } - } - None => out[o..o + n].copy_from_slice(&dp), - } - } - } - } - out - } - /// Distinct tile allocations in `s`. - fn distinct_tiles(s: &Surface) -> usize { - let mut seen: Vec<*const Tile> = s.tiles().map(|(_, t)| Arc::as_ptr(t)).collect(); - seen.sort(); - seen.dedup(); - seen.len() - } - - /// Converting or tone-mapping a surface keeps a shared tile shared (#4531) and gives the - /// same pixels as converting each pixel: a filled background is one tile across the grid, - /// plus some distinct tiles. - #[test] - fn conversion_keeps_shared_tiles_shared() { - let mut s = Surface::new(PixelFormat::RGBA8); - s.fill_rect(Rect::new(0, 0, 2048, 1024), &[0.9, 0.5, 0.2, 1.0]); - s.fill_rect(Rect::new(10, 10, 20, 20), &[0.1, 0.2, 0.3, 0.5]); - let shared_before = distinct_tiles(&s); - assert!(shared_before <= 2 && s.tile_count() == 32, "{shared_before} distinct of {}", s.tile_count()); - let r = Rect::new(0, 0, 2048, 1024); - for to in [PixelFormat::RGBA16, PixelFormat::RGBA32F] { - for out in [s.convert(to), s.try_convert(to).expect("memory")] { - assert_eq!(distinct_tiles(&out), shared_before, "{to:?}: still shared"); - assert_eq!(out.tile_count(), 32); - let (a, b) = (out.read_region(r), s.read_region(r)); - for (pa, pb) in a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0) { - let want = convert_pixel(&s.format(), &to, pb); - assert!(pa.iter().zip(&want).all(|(x, y)| (x - y).abs() < 1e-6), "{to:?}: {pa:?} vs {want:?}"); - } - } - } - let mut m = s.clone(); - m.map_color(|v| v * 0.5); - assert_eq!(distinct_tiles(&m), shared_before, "map_color keeps it shared"); - assert!((m.pixel(1000, 500)[0] - s.pixel(1000, 500)[0] * 0.5).abs() < 1.0 / 255.0); - assert_eq!(s.pixel(1000, 500), vec![s.pixel(1000, 500)[0], s.pixel(1000, 500)[1], s.pixel(1000, 500)[2], 1.0], "the source is untouched"); - } - - use super::*; - use photocraft_color::PixelFormat; - use proptest::prelude::*; - - fn write_region_reference(surface: &mut Surface, r: Rect, data: &[f32]) { - let n = surface.channels(); - let w = r.width() as usize; - assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); - let sample = surface.format.sample; - for tc in r.tiles() { - let tr = tc.rect().intersect(&r); - let t = surface.tile_mut(tc); - for y in tr.y0..tr.y1 { - for x in tr.x0..tr.x1 { - let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; - let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n; - for i in 0..n { - write_sample(&mut t.data, sample, base + i, data[o + i]); - } - } - } - } - } - - #[test] - fn region_writes_match_scalar_bytes_for_every_format() { - let special = [ - 0.0, - -0.0, - 1.0, - -1.0, - 2.0, - f32::INFINITY, - f32::NEG_INFINITY, - f32::NAN, - f32::from_bits(0x7fc12345), - f32::from_bits(0xffc12345), - f32::MIN_POSITIVE, - f32::from_bits(1), - 0.5 / 255.0, - 0.5 / 65535.0, - ]; - for mode in [ - ColorMode::Bitmap, - ColorMode::Grayscale, - ColorMode::Indexed, - ColorMode::Rgb, - ColorMode::Cmyk, - ColorMode::Lab, - ColorMode::Multichannel, - ColorMode::Duotone, - ] { - for sample in SampleType::ALL { - for alpha in [false, true] { - let fmt = PixelFormat::new(mode, sample, alpha); - let mut actual = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); - actual.write_pixel(900, 900, &vec![0.75; fmt.channels()]); - let mut expected = actual.clone(); - for rect in - [Rect::EMPTY, Rect::new(-270, -2, 270, 3), Rect::new(256, 256, 512, 257), Rect::new(-64, -64, 0, 0), Rect::new(255, 250, 258, 270)] - { - let data: Vec<_> = (0..rect.width() as usize * rect.height() as usize * fmt.channels()) - .map(|i| { - if i % 3 == 0 { - special[i / 3 % special.len()] - } else { - // Integer rounding boundaries and deterministic arbitrary f32 bit patterns. - let bits = (i as u32).wrapping_mul(2654435761); - if i % 3 == 1 { ((bits % 65536) as f32 + 0.5) / 65535.0 } else { f32::from_bits(bits) } - } - }) - .collect(); - let snapshot = actual.clone(); - let snapshot_bytes = snapshot.to_interleaved(rect.inflate(1)); - let mut par = actual.clone(); - actual.write_region(rect, &data); - par.write_region_par(rect, &data); - write_region_reference(&mut expected, rect, &data); - assert_eq!(actual, expected, "{fmt:?}, {rect:?}"); - assert_eq!(par, expected, "parallel {fmt:?}, {rect:?}"); - assert_eq!(snapshot.to_interleaved(rect.inflate(1)), snapshot_bytes, "COW snapshot changed"); - // Repeat against already materialised, unshared tiles too. - actual.write_region(rect, &data); - par.write_region_par(rect, &data); - assert_eq!(actual, expected); - assert_eq!(par, expected); - } - } - } - } - } - - /// Mask builds call `write_region` inside a `OnceLock` initializer, where entering Rayon can - /// run another tile's job that waits on the same lock. With every global worker held, a write - /// that queued work on Rayon could not finish. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn write_region_does_not_enter_rayon() { - use std::sync::{Barrier, mpsc}; - let workers = rayon::current_num_threads(); - let held = Arc::new(Barrier::new(workers + 1)); - let release = Arc::new(Barrier::new(workers + 1)); - let (h, rel) = (held.clone(), release.clone()); - rayon::spawn_broadcast(move |_| { - h.wait(); - rel.wait(); - }); - held.wait(); - let (tx, rx) = mpsc::channel(); - std::thread::spawn(move || { - let r = Rect::new(0, 0, 2 * TILE_SIZE, 2 * TILE_SIZE); - let mut s = Surface::new(PixelFormat::RGBA8); - s.write_region(r, &vec![0.5; (r.width() * r.height() * 4) as usize]); - tx.send(()).ok(); - }); - let done = rx.recv_timeout(std::time::Duration::from_secs(5)).is_ok(); - release.wait(); - assert!(done, "write_region waited on the Rayon pool"); - } - - #[test] - fn from_rgba_into_matches_from_rgba() { - for fmt in [PixelFormat::RGBA8, PixelFormat::GRAY8, PixelFormat::GRAYA8, PixelFormat::CMYKA8, PixelFormat::new(ColorMode::Lab, SampleType::F32, true)] { - let mut buf = [0.0f32; 8]; - let n = from_rgba_into(&fmt, [0.2, 0.5, 0.7, 0.4], &mut buf); - assert_eq!(&buf[..n], &from_rgba(&fmt, [0.2, 0.5, 0.7, 0.4])[..]); - } - } - - /// Sample counts above the stack capacity use writable storage without truncating channels. - #[test] - fn sample_buffer_keeps_stack_fast_path_and_supports_dynamic_channels() { - for channels in [1, 8, 9, 32] { - let mut stack = [0.0; 8]; - let mut heap = Vec::new(); - let samples = sample_buffer(channels, &mut stack, &mut heap); - assert_eq!(samples.len(), channels); - samples.fill(0.25); - if channels <= stack.len() { - assert!(heap.is_empty()); - assert_eq!(&stack[..channels], vec![0.25; channels]); - } else { - assert_eq!(heap, vec![0.25; channels]); - } - } - } - - /// Compare sparse reads and converted accessors with the previous allocating path. - #[test] - fn zero_alloc_accessors_match_read_region() { - for (fmt, default) in [ - PixelFormat::RGBA8, - PixelFormat::RGBA16, - PixelFormat::RGBA32F, - PixelFormat::GRAYA8, - PixelFormat::CMYKA8, - PixelFormat::GRAY8, - PixelFormat::GRAY8.with_sample(SampleType::F32), - PixelFormat::new(ColorMode::Lab, SampleType::U16, true), - ] - .into_iter() - .flat_map(|fmt| [0.0, 0.25, -0.0].map(|default| (fmt, default))) - { - let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]); - let mut stack = [0.0; 8]; - let mut heap = Vec::new(); - for capacity in [0, stack.len()] { - let decoded = s.default_samples(&mut stack[..capacity], &mut heap); - assert!(decoded.iter().map(|v| v.to_bits()).eq(s.default_pixel().into_iter().map(f32::to_bits))); - } - let r = Rect::new(-300, -20, 300, 40); - for (i, (x, y)) in [(-299, -19), (0, 0), (255, 39), (256, 10), (299, 0)].into_iter().enumerate() { - let px: Vec = (0..fmt.channels()).map(|c| ((i * 3 + c) % 5) as f32 / 4.0).collect(); - s.write_pixel(x, y, &px); - } - let region = s.read_region(r); - assert!(region.iter().map(|v| v.to_bits()).eq(previous_read_region(&s, r).into_iter().map(f32::to_bits))); - let mut into = vec![9.0; 3]; - s.read_region_into(r, &mut into); - assert_eq!(region, into); - let mut rgba = vec![[0.0; 4]; (r.width() * r.height()) as usize]; - s.read_rgba_into(r, &mut rgba); - let mut rgba8 = vec![[0; 4]; rgba.len()]; - s.read_rgba8_into(r, &mut rgba8); - let n = fmt.channels(); - for (i, p) in region.chunks_exact(n).enumerate() { - let want = to_rgba(&fmt, p); - assert_eq!(rgba8[i], want.map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)); - for c in 0..4 { - assert!((rgba[i][c] - want[c]).abs() < 1e-6, "{fmt:?} px {i}"); - } - let (x, y) = (r.x0 + (i % r.width() as usize) as i32, r.y0 + (i / r.width() as usize) as i32); - for c in 0..n { - let bits = s.sample_channel(x, y, c).to_bits(); - assert_eq!(bits, p[c].to_bits()); - assert_eq!(bits, into[i * n + c].to_bits()); - } - } - assert!(s.has_tiles_in(Rect::new(0, 0, 1, 1))); - assert!(!s.has_tiles_in(Rect::new(1000, 1000, 1001, 1001))); - } - } - - #[test] - fn fallible_region_reads_report_size_overflow() { - let surface = Surface::new(PixelFormat::RGBA8); - let huge = Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX); - assert_eq!(surface.try_read_region(huge), Err(AllocationError::SizeOverflow)); - assert_eq!(surface.try_to_interleaved(huge), Err(AllocationError::SizeOverflow)); - } - - #[test] - fn fallible_region_write_rejects_bad_input_without_mutating_surface() { - let mut surface = Surface::new(PixelFormat::RGBA8); - let before = surface.clone(); - assert_eq!(surface.try_write_region(Rect::new(0, 0, 2, 2), &[1.0]), Err(AllocationError::SizeOverflow)); - assert_eq!(surface, before); - } - - #[test] - fn fallible_tile_edits_move_weakly_cached_pixels_and_copy_shared_pixels() { - for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { - let mut surface = Surface::new(fmt); - let coord = TileCoord::new(0, 0); - let pixels = surface.try_tile_mut(coord).unwrap().bytes().as_ptr(); - let weak = Arc::downgrade(surface.tile(coord).unwrap()); - let tile = surface.try_tile_mut(coord).unwrap(); - assert_eq!(tile.bytes().as_ptr(), pixels); - assert!(weak.upgrade().is_none()); - let snapshot = surface.clone(); - surface.try_write_region(Rect::new(0, 0, 1, 1), &[1.0; 4]).unwrap(); - assert_eq!(snapshot.pixel(0, 0), vec![0.0; 4]); - assert_eq!(surface.pixel(0, 0), vec![1.0; 4]); - } - } - - #[test] - fn fill_rect_shares_covered_tiles_and_edits_stay_local() { - // A 300000² background used to materialize ~360 GB of tiles (#705). - let mut s = Surface::new(PixelFormat::RGBA8); - s.fill_rect(Rect::new(0, 0, 300_000, 300_000), &[1.0, 0.5, 0.0, 1.0]); - let t = |s: &Surface, x, y| s.tile(TileCoord::new(x, y)).unwrap().clone(); - assert!(Arc::ptr_eq(&t(&s, 0, 0), &t(&s, 1000, 900))); - // 300000 is not a multiple of 256: the edge tile is partial and stays its own. - let edge = 300_000 / TILE_SIZE; - assert!(!Arc::ptr_eq(&t(&s, 0, 0), &t(&s, edge, 0))); - assert_eq!(s.pixel(299_999, 299_999), vec![1.0, 128.0 / 255.0, 0.0, 1.0]); - assert_eq!(s.pixel(300_000, 0), vec![0.0; 4]); - s.write_pixel(5, 5, &[0.0, 0.0, 1.0, 1.0]); - assert_eq!(s.pixel(5, 5), vec![0.0, 0.0, 1.0, 1.0]); - assert_eq!(s.pixel(300, 5), vec![1.0, 128.0 / 255.0, 0.0, 1.0]); - assert!(!Arc::ptr_eq(&t(&s, 0, 0), &t(&s, 1, 0))); - } - - #[test] - fn empty_surface_reads_default() { - let s = Surface::new(PixelFormat::RGBA8); - assert_eq!(s.pixel(10, -500), vec![0.0; 4]); - let m = Surface::with_default(PixelFormat::GRAY8, &[1.0]); - assert_eq!(m.pixel(123_456, -9), vec![1.0]); - assert_eq!(m.tile_count(), 0); - } - - #[test] - fn write_read_pixel_every_depth() { - for sample in SampleType::ALL { - let f = PixelFormat::RGBA8.with_sample(sample); - let mut s = Surface::new(f); - s.write_pixel(-3, 700, &[0.2, 0.4, 0.6, 1.0]); - let p = s.pixel(-3, 700); - for (a, b) in p.iter().zip([0.2, 0.4, 0.6, 1.0]) { - assert!((a - b).abs() <= 1.0 / 255.0, "{sample:?}"); - } - assert_eq!(s.tile_count(), 1); - assert_eq!(s.tile_bounds(), TileCoord::containing(-3, 700).rect()); - } - } - - #[test] - fn copy_on_write_shares_untouched_tiles() { - let mut a = Surface::new(PixelFormat::RGBA8); - a.fill_rect(Rect::new(0, 0, 512, 512), &[1.0, 0.0, 0.0, 1.0]); - let mut b = a.clone(); - b.write_pixel(10, 10, &[0.0, 1.0, 0.0, 1.0]); - // a unchanged - assert_eq!(a.pixel(10, 10), vec![1.0, 0.0, 0.0, 1.0]); - assert_eq!(b.pixel(10, 10), vec![0.0, 1.0, 0.0, 1.0]); - // only tile (0,0) was copied - let shared = a.tiles().filter(|(c, t)| Arc::ptr_eq(t, b.tile(**c).unwrap())).count(); - assert_eq!(shared, 3); - } - - #[test] - fn content_bounds_and_prune() { - let mut s = Surface::new(PixelFormat::RGBA8); - s.fill_rect(Rect::new(300, 10, 310, 20), &[1.0, 1.0, 1.0, 1.0]); - s.write_pixel(-5, -5, &[0.0, 0.0, 0.0, 1.0]); - assert_eq!(s.content_bounds(), Rect::new(-5, -5, 310, 20)); - // erase the single pixel -> its tile becomes default and is pruned - s.write_pixel(-5, -5, &[0.0, 0.0, 0.0, 0.0]); - s.prune(); - assert_eq!(s.tile_count(), 1); - assert_eq!(s.content_bounds(), Rect::new(300, 10, 310, 20)); - } - - #[test] - fn interleaved_roundtrip_crossing_tiles() { - let r = Rect::new(-20, 250, 280, 262); - let bpp = PixelFormat::RGBA16.bytes_per_pixel(); - let bytes: Vec = (0..r.width() as usize * r.height() as usize * bpp).map(|i| (i * 31 % 251) as u8).collect(); - let s = Surface::from_interleaved(PixelFormat::RGBA16, r, &bytes); - assert_eq!(s.to_interleaved(r), bytes); - assert_eq!(s.tile_count(), 6); // x tiles -1..=1, y tiles 0..=1 - } - - #[test] - fn region_outside_reads_default() { - let s = Surface::with_default(PixelFormat::GRAY8, &[1.0]); - let v = s.read_region(Rect::new(0, 0, 3, 3)); - assert_eq!(v, vec![1.0; 9]); - } - - #[test] - fn convert_depths_and_models() { - let mut s = Surface::new(PixelFormat::RGBA8); - s.write_pixel(1, 1, &[1.0, 1.0, 1.0, 1.0]); - let g = s.convert(PixelFormat::GRAYA8); - assert!((g.pixel(1, 1)[0] - 1.0).abs() < 1e-2); - let f = s.convert(PixelFormat::RGBA32F); - assert_eq!(f.pixel(1, 1), vec![1.0, 1.0, 1.0, 1.0]); - let c = s.convert(PixelFormat::CMYKA8); - let p = c.pixel(1, 1); - assert!(p[3] < 0.01 && (p[4] - 1.0).abs() < 1e-6); - let back = c.convert(PixelFormat::RGBA8); - assert_eq!(back.pixel(1, 1), vec![1.0, 1.0, 1.0, 1.0]); - } - - #[test] - fn rgba_from_gray_and_cmyk() { - let mut g = Surface::new(PixelFormat::GRAYA8); - g.write_pixel(0, 0, &[0.5, 1.0]); - let v = g.rgba(0, 0); - assert!((v[0] - v[2]).abs() < 1e-6 && (v[3] - 1.0).abs() < 1e-6); - } - - #[test] - fn repeated_cmyk_reads_match_individual_pixels_bitwise() { - let rect = Rect::new(-2, -1, 515, 2); - for depth in SampleType::ALL { - for alpha in [false, true] { - let fmt = PixelFormat::new(ColorMode::Cmyk, depth, alpha); - let mut s = Surface::with_default(fmt, &[0.2, 0.4, 0.6, 0.3, 0.7]); - for (i, x) in (-1..514).enumerate() { - let c = if i / 2 % 256 == 0 { -0.0 } else { (i / 2 % 256) as f32 / 255.0 }; - s.write_pixel(x, 0, &[c, 0.4, 0.6, 0.3, (i % 9) as f32 / 8.0]); - } - let mut out = vec![[0.0; 4]; (rect.width() * rect.height()) as usize]; - s.read_rgba_into(rect, &mut out); - for (i, actual) in out.iter().enumerate() { - let expected = s.rgba(rect.x0 + (i % rect.width() as usize) as i32, rect.y0 + (i / rect.width() as usize) as i32); - assert_eq!(actual.map(f32::to_bits), expected.map(f32::to_bits), "{depth:?}, alpha={alpha}, pixel={i}"); - } - } - } - } - - #[test] - fn rgba_reads_match_individual_pixels_bitwise_in_every_model_and_depth() { - // Across tile edges and a missing tile; float samples include -0, out-of-range and NaN. - let rect = Rect::new(-3, -1, 300, 2); - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab, ColorMode::Cmyk] { - for depth in SampleType::ALL { - for alpha in [false, true] { - let fmt = PixelFormat::new(mode, depth, alpha); - let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); - let values = [-0.0, 0.1, 0.5, 1.0, 1.5, -0.25, f32::NAN, 0.75]; - for (i, x) in (-2..260).enumerate() { - let px: Vec = (0..fmt.channels()).map(|c| values[(i + c * 3) % values.len()]).collect(); - s.write_pixel(x, 0, &px); - } - let mut out = vec![[0.0; 4]; (rect.width() * rect.height()) as usize]; - s.read_rgba_into(rect, &mut out); - for (i, actual) in out.iter().enumerate() { - let expected = s.rgba(rect.x0 + (i % rect.width() as usize) as i32, rect.y0 + (i / rect.width() as usize) as i32); - assert_eq!(actual.map(f32::to_bits), expected.map(f32::to_bits), "{fmt:?}, pixel={i}"); - } - } - } - } - } - - #[test] - fn tile_content_bounds_scans_against_the_given_pixel() { - let mut s = Surface::new(PixelFormat::GRAY8); - s.write_pixel(3, 4, &[1.0]); - s.write_pixel(200, 9, &[1.0]); - let t = s.tile(TileCoord::new(0, 0)).expect("written tile"); - assert_eq!(t.content_bounds(&[0]), Some((3, 4, 201, 10))); - assert_eq!(t.content_bounds(&[255]).map(|b| (b.0, b.1)), Some((0, 0))); - // A malformed pixel is no content, not a panic. - assert_eq!(t.content_bounds(&[]), None); - } - - #[test] - fn tile_content_bounds_match_a_per_pixel_scan() { - // One differing byte at each position of a pixel, at and around the compare-block - // boundaries, in every pixel size; and a pixel that differs from `dp` in every byte. - fn per_pixel(t: &Tile, dp: &[u8]) -> Option<(u16, u16, u16, u16)> { - let (bpp, ts) = (dp.len(), TILE_SIZE as usize); - let mut b: Option<(usize, usize, usize, usize)> = None; - for (i, px) in t.bytes().chunks_exact(bpp).enumerate() { - if px != dp { - let (x, y) = (i % ts, i / ts); - let (x0, y0, x1, y1) = b.unwrap_or((x, y, x, y)); - b = Some((x0.min(x), y0.min(y), x1.max(x), y1.max(y))); - } - } - b.map(|(x0, y0, x1, y1)| (x0 as u16, y0 as u16, x1 as u16 + 1, y1 as u16 + 1)) - } - for bpp in [1, 2, 3, 4, 6, 8, 16] { - let dp: Vec = (0..bpp).map(|i| (i * 37 + 5) as u8).collect(); - let row = TILE_SIZE as usize * bpp; - for spots in [vec![], vec![0], vec![row - 1], vec![63, 64], vec![row * 7 + 127, row * 7 + 128, row * 200 + 5], vec![row * 255 + row / 2]] { - for byte in 0..bpp { - let mut data = dp.repeat(TILE_SIZE as usize * TILE_SIZE as usize); - for &s in &spots { - data[s - s % bpp + byte] ^= 0x5a; - } - let t = Tile { data: data.into_boxed_slice() }; - assert_eq!(t.content_bounds(&dp), per_pixel(&t, &dp), "bpp {bpp}, spots {spots:?}, byte {byte}"); - } - } - let mut data = dp.repeat(TILE_SIZE as usize * TILE_SIZE as usize); - data[row * 3 + 9 * bpp..row * 3 + 10 * bpp].iter_mut().for_each(|b| *b = !*b); - let t = Tile { data: data.into_boxed_slice() }; - assert_eq!(t.content_bounds(&dp), Some((9, 3, 10, 4)), "bpp {bpp}"); - } - } - - #[test] - fn translated_matches_reading_the_moved_pixels() { - // Any offset (whole tiles, negative, across tile edges), every depth, a non-zero default. - for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] { - let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); - let r = Rect::new(-37, 200, 530, 300); - let v: Vec = (0..r.width() * r.height() * fmt.channels() as u32).map(|i| (i % 251) as f32 / 250.0).collect(); - s.write_region(r, &v); - for (dx, dy) in [(0, 0), (256, -512), (1, 0), (-3, 7), (300, -257), (-1000, 999)] { - let t = s.translated(dx, dy, s.content_bounds()); - let moved = r.translate(dx, dy).inflate(3); - assert_eq!(t.read_region(moved), s.read_region(moved.translate(-dx, -dy)), "{fmt:?} by ({dx}, {dy})"); - assert_eq!(t.default_pixel(), s.default_pixel()); - assert_eq!(t.to_interleaved(r.translate(dx, dy)), s.to_interleaved(r), "{fmt:?} by ({dx}, {dy}): not an exact copy"); - } - // Whole tiles: the tiles are shared, not copied. - let t = s.translated(512, -256, s.content_bounds()); - assert!(s.tiles().zip(t.tiles()).all(|((_, a), (_, b))| Arc::ptr_eq(a, b))); - // Tiles without content (allocated, default pixels) are left behind. - let mut padded = s.clone(); - padded.fill_rect(Rect::new(2000, 2000, 2100, 2100), &s.default_pixel()); - assert_eq!(padded.translated(5, 5, s.content_bounds()).tile_count(), s.translated(5, 5, s.content_bounds()).tile_count()); - } - // A solid fill moved off the tile grid keeps sharing its one tile inside, at every depth - // and over a non-zero default pixel, and reads exactly like the copied pixels. - for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] { - let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); - let r = Rect::new(-300, -10, 1300, 1030); - s.fill_rect(r, &vec![0.75; fmt.channels()]); - let fill = s.tile(TileCoord::new(1, 1)).cloned().expect("an inner fill tile"); - for (dx, dy) in [(10, 7), (-1, 0), (0, 300), (-257, 513)] { - let t = s.translated(dx, dy, s.content_bounds()); - let moved = r.translate(dx, dy); - assert_eq!(t.read_region(moved.inflate(3)), s.read_region(moved.inflate(3).translate(-dx, -dy)), "{fmt:?} by ({dx}, {dy})"); - // Targets read only from the fill's whole tiles (x -256..1280, y 0..1024). - let whole = Rect::new(-256, 0, 1280, 1024).translate(dx, dy); - let inner: Vec<_> = t.tiles().filter(|(c, _)| whole.contains_rect(&c.rect())).collect(); - assert!(!inner.is_empty() && inner.iter().all(|(_, a)| Arc::ptr_eq(a, &fill)), "{fmt:?} by ({dx}, {dy}): inner tiles copied"); - } - // Nudged back and forth, the inside keeps sharing one tile (copies of uniform edge - // tiles count as that value too) and the pixels stay exact. - let mut t = s.clone(); - for k in 0..8 { - let d = if k % 2 == 0 { 10 } else { -10 }; - t = t.translated(d, d / 2, t.content_bounds()); - } - // (Targets whose last window read uniform tiles only: one tile in from the fill's whole - // tiles on the sides the last move came from.) - let inner: Vec<_> = t.tiles().filter(|(c, _)| Rect::new(-256, 0, 1024, 768).contains_rect(&c.rect())).map(|(_, a)| a).collect(); - assert!(inner.len() >= 4 && inner.iter().all(|a| Arc::ptr_eq(a, inner[0])), "{fmt:?}: repeated moves copied the inside"); - assert_eq!(t.read_region(r.inflate(3)), s.read_region(r.inflate(3)), "{fmt:?}: back where it started"); - } - // Two solid fills of different values side by side: windows across the seam are - // copied (each tile is uniform, but not with the same value), the rest shared. - for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA32F] { - let mut s = Surface::new(fmt); - s.fill_rect(Rect::new(0, 0, 1024, 768), &vec![0.2; fmt.channels()]); - s.fill_rect(Rect::new(1024, 0, 2048, 768), &vec![0.9; fmt.channels()]); - let t = s.translated(10, 7, s.content_bounds()); - let all = Rect::new(-20, -20, 2100, 800); - assert_eq!(t.read_region(all), s.read_region(all.translate(-10, -7)), "{fmt:?}: two fills"); - let seam = t.tile(TileCoord::new(4, 1)).expect("seam tile"); - let (left, right) = (t.tile(TileCoord::new(2, 1)).expect("left"), t.tile(TileCoord::new(6, 1)).expect("right")); - assert!(!Arc::ptr_eq(seam, left) && !Arc::ptr_eq(seam, right) && !Arc::ptr_eq(left, right), "{fmt:?}: seam aliased"); - } - // An offset of i32::MIN saturates its negation, so the source window isn't the exact - // preimage: no shortcut may apply (a zero pre-fill would leak into the output). - let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.5]); - s.fill_rect(Rect::new(i32::MAX - 1024, 0, i32::MAX - 512, 512), &[0.25]); - let (fill, default) = (s.sample_channel(i32::MAX - 600, 10, 0), s.default_pixel()[0]); - for (dx, dy) in [(i32::MIN, 1), (1, i32::MIN), (i32::MIN, 0)] { - let t = s.translated(dx, dy, s.content_bounds()); - for (c, _) in t.tiles() { - assert!(t.read_region(c.rect()).iter().all(|v| *v == fill || *v == default), "({dx}, {dy}): tile {c:?} holds a pre-fill"); - } - } - // One tile shared but not uniform: each target is copied, not aliased. - let mut s = Surface::new(PixelFormat::GRAY8); - s.write_pixel(3, 4, &[1.0]); - let odd = s.tile(TileCoord::new(0, 0)).cloned().expect("written tile"); - let grid: Vec<_> = (0..9).map(|i| (TileCoord::new(i % 3, i / 3), odd.clone())).collect(); - s.put_tiles(grid); - let t = s.translated(10, 7, s.content_bounds()); - let all = Rect::new(-20, -20, 800, 800); - assert_eq!(t.read_region(all), s.read_region(all.translate(-10, -7))); - assert!(t.tiles().all(|(_, a)| !Arc::ptr_eq(a, &odd))); - // Offsets at the limits don't panic. - let mut s = Surface::new(PixelFormat::GRAY8); - s.write_pixel(5, 5, &[1.0]); - let all = Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX); - let _ = s.translated(i32::MAX, i32::MIN, all); - let _ = s.translated(i32::MIN + 1, 3, all); - } - - /// Many references to one payload, moved off the tile grid: the rebuilt tiles that read the - /// same source tiles at the same offset are one tile, not a copy each. - #[test] - fn translated_shares_tiles_rebuilt_from_shared_sources() { - let fmt = PixelFormat::RGBA8; - let mut one = Surface::new(fmt); - let r = Rect::new(0, 0, TILE_SIZE, TILE_SIZE); - let px: Vec = (0..r.width() * r.height()).flat_map(|i| [(i % 251) as f32 / 255.0, (i % 7) as f32 / 7.0, 0.5, 1.0]).collect(); - one.write_region(r, &px); - let payload = Arc::clone(one.tile(TileCoord::new(0, 0)).unwrap()); - let mut s = Surface::new(fmt); - s.put_tiles((0..16).flat_map(|ty| (0..16).map(move |tx| TileCoord::new(tx, ty))).map(|c| (c, Arc::clone(&payload)))); - let moved = s.translated(7, 5, s.content_bounds()); - let distinct: std::collections::HashSet<_> = moved.tiles().map(|(_, t)| Arc::as_ptr(t)).collect(); - // The 15 × 15 interior tiles read the same four source tiles at the same offset, so they are - // one tile, however many threads build them; only the 64 border tiles (cut by the - // content's edge) are built one by one. - assert!(moved.tile_count() == 289 && distinct.len() == 64 + 1, "{} tiles, {} distinct", moved.tile_count(), distinct.len()); - let all = Rect::new(-50, -50, 16 * TILE_SIZE + 50, 16 * TILE_SIZE + 50); - assert_eq!(moved.read_region(all), s.read_region(all.translate(-7, -5))); - } - - #[test] - fn a_surface_bounds_tile_count_is_counted_not_walked() { - let mut s = Surface::new(PixelFormat::RGBA8); - let far = Rect::new(0, 0, i32::MAX, i32::MAX); - assert_eq!(far.tile_count(), u64::from(i32::MAX as u32 / TILE_SIZE as u32 + 1).pow(2)); - // Not allocated: 2^46 entries is far past any reservation. - assert!(s.try_take_tiles(far).is_err()); - } - - #[test] - fn translated_stores_no_tiles_of_only_the_default_pixel() { - let only_default = |t: &Surface| { - let dp = t.default_pixel(); - t.tiles().filter(|(c, _)| t.read_region(c.rect()).chunks_exact(dp.len()).all(|p| p == dp.as_slice())).count() - }; - // Two blocks a few tiles apart, moved off the tile grid and back: the default-pixel edges - // of their tiles land on tiles of their own, which aren't stored. - for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] { - for default in [0.0, 0.25] { - let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]); - s.fill_rect(Rect::new(0, 0, 300, 300), &vec![1.0; fmt.channels()]); - s.fill_rect(Rect::new(2000, 1000, 2300, 1300), &vec![0.5; fmt.channels()]); - let all = Rect::new(-600, -600, 3000, 2000); - let mut t = s.clone(); - for (dx, dy) in [(100, 56), (-100, -56), (10, 7), (-3, 40), (130, -90), (-137, 43)] { - let moved = t.translated(dx, dy, t.content_bounds()); - assert_eq!(moved.read_region(all), t.read_region(all.translate(-dx, -dy)), "{fmt:?} over {default} by ({dx}, {dy})"); - assert_eq!(only_default(&moved), 0, "{fmt:?} over {default} by ({dx}, {dy})"); - t = moved; - } - assert_eq!(t.read_region(all), s.read_region(all), "{fmt:?} over {default}: back where it started"); - assert_eq!(t.tile_count(), s.tile_count(), "{fmt:?} over {default}: back where it started"); - } - } - // Stored tiles of the default pixel inside `content`: the targets that would share one of - // them (#4414's uniform windows) are left out too. - let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.25]); - s.fill_rect(Rect::new(0, 0, 1024, 1024), &[0.25]); - s.write_pixel(600, 600, &[1.0]); - let content = Rect::new(0, 0, 1024, 1024); - let t = s.translated(10, 7, content); - assert_eq!(only_default(&t), 0); - assert_eq!(t.tile_count(), 1); - assert_eq!(t.read_region(Rect::new(-20, -20, 1100, 1100)), s.read_region(Rect::new(-30, -27, 1090, 1093))); - } - - proptest! { - #[test] - fn region_write_read_roundtrip(x in -600i32..600, y in -600i32..600, w in 1u32..90, h in 1u32..90, seed in any::()) { - let r = Rect::from_xywh(x, y, w, h); - let n = 4usize; - let data: Vec = (0..(w * h) as usize * n).map(|i| ((i as u32).wrapping_mul(2654435761).wrapping_add(seed) % 256) as f32 / 255.0).collect(); - let mut s = Surface::new(PixelFormat::RGBA8); - s.write_region(r, &data); - let back = s.read_region(r); - for (a, b) in back.iter().zip(&data) { - prop_assert!((a - b).abs() < 1e-6); - } - prop_assert_eq!(s.content_bounds().union(&r), r); - } - - #[test] - fn clone_mutation_isolated(x in -300i32..300, y in -300i32..300) { - let mut a = Surface::new(PixelFormat::RGBA8); - a.fill_rect(Rect::new(-256, -256, 256, 256), &[0.5, 0.5, 0.5, 1.0]); - let snapshot = a.clone(); - a.write_pixel(x, y, &[1.0, 0.0, 0.0, 1.0]); - let expect = if Rect::new(-256, -256, 256, 256).contains(x, y) { vec![0.5f32, 0.5, 0.5, 1.0] } else { vec![0.0; 4] }; - let got = snapshot.pixel(x, y); - for (g, e) in got.iter().zip(&expect) { - prop_assert!((g - e).abs() <= 1.0 / 255.0); - } - } - } - - #[test] - fn strided_row_sampling_handles_extreme_coordinates_and_steps() { - for sample in SampleType::ALL { - let mut s = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, sample, false), &[0.25]); - for (x, value) in [(i32::MIN, 0.1), (-1, 0.3), (0, 0.4), (i32::MAX - 1, 0.6), (i32::MAX, 0.9)] { - s.write_pixel(x, 0, &[value]); - } - for y in [0, 256] { - for (x0, step, len) in [(i32::MAX, 1, 1), (i32::MIN, i32::MAX, 3), (0, i32::MAX, 2), (i32::MAX - 1, 1, 2), (i32::MAX, i32::MAX, 0)] { - let mut out = vec![0.0; len]; - s.sample_row_strided(y, x0, step, 0, &mut out); - for (i, &got) in out.iter().enumerate() { - let x = i32::try_from(i64::from(x0) + i as i64 * i64::from(step)).unwrap(); - assert_eq!(got, s.sample_channel(x, y, 0), "{sample:?} y={y} x0={x0} step={step} i={i}"); - } - } - } - } - } - - #[test] - fn strided_row_sampling_uses_default_past_coordinate_range() { - for sample in SampleType::ALL { - let mut s = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, sample, false), &[0.25]); - s.write_pixel(i32::MAX, 0, &[0.75]); - s.write_pixel(i32::MIN, 0, &[1.0]); - for step in [1, i32::MAX] { - let mut out = [0.0; 4]; - s.sample_row_strided(0, i32::MAX, step, 0, &mut out); - assert_eq!(out, [s.sample_channel(i32::MAX, 0, 0), s.default_pixel()[0], s.default_pixel()[0], s.default_pixel()[0]]); - } - } - } - - #[test] - fn strided_row_sampling_matches_sample_channel() { - let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.25]); - s.fill_rect(Rect::new(-300, 10, 200, 40), &[1.0]); - s.fill_rect(Rect::new(250, 10, 700, 20), &[0.5]); - for (y, x0, step) in [(15, -520, 7), (15, -1, 1), (30, 3, 64), (500, 0, 9)] { - let mut out = vec![0.0; 120]; - s.sample_row_strided(y, x0, step, 0, &mut out); - for (i, v) in out.iter().enumerate() { - assert_eq!(*v, s.sample_channel(x0 + i as i32 * step, y, 0), "y={y} x0={x0} step={step} i={i}"); - } - } - } - - #[test] - fn content_bounds_with_tile_skipping() { - // Interior content only; ring tiles present but all-default (unpruned). - let mut s = Surface::new(PixelFormat::GRAY8); - s.fill_rect(Rect::new(0, 0, 1024, 1024), &[0.0]); - s.fill_rect(Rect::new(300, 310, 700, 720), &[1.0]); - assert_eq!(s.content_bounds(), Rect::new(300, 310, 700, 720)); - // Full-canvas content plus a far-away speck. - let mut s = Surface::new(PixelFormat::GRAY8); - s.fill_rect(Rect::new(0, 0, 2000, 1500), &[1.0]); - s.fill_rect(Rect::new(-700, 4000, -699, 4001), &[0.5]); - assert_eq!(s.content_bounds(), Rect::new(-700, 0, 2000, 4001)); - } -} +mod tests; #[cfg(test)] mod echelon_case { diff --git a/crates/raster/src/tests.rs b/crates/raster/src/tests.rs new file mode 100644 index 0000000000..1e8cf30ec7 --- /dev/null +++ b/crates/raster/src/tests.rs @@ -0,0 +1,780 @@ +/// Manually compare allocating reads with the previous implementation. +#[test] +#[ignore = "manual 24 MP release benchmark"] +fn benchmark_sparse_reads() { + use std::{hint::black_box, time::Instant}; + let rect = Rect::new(0, 0, 6000, 4000); + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for default in [0.0, 0.25] { + let mut s = Surface::with_default(PixelFormat::GRAY8.with_sample(depth), &[default]); + s.fill_rect(Rect::new(257, 257, 266, 266), &[0.75]); + assert_eq!(s.read_region(rect), previous_read_region(&s, rect)); + for trial in 0..6 { + let mut paths = [("main", previous_read_region as fn(&Surface, Rect) -> Vec), ("split", Surface::read_region)]; + if trial % 2 == 1 { + paths.reverse(); + } + for (name, path) in paths { + let t = Instant::now(); + let out = black_box(path)(&s, rect); + let elapsed = t.elapsed().as_secs_f64() * 1000.0; + black_box(&out); + println!("sparse,{depth:?}-{default},{trial},{name},{elapsed:.6}"); + } + } + } + } +} +/// Previous allocating read path, retained as the bitwise-equivalence oracle. +fn previous_read_region(surface: &Surface, r: Rect) -> Vec { + let n = surface.channels(); + let w = r.width() as usize; + let mut out = vec![0.0f32; w * r.height() as usize * n]; + let dp = surface.default_pixel(); + for tc in r.tiles() { + let tr = tc.rect().intersect(&r); + let tile = surface.tiles.get(&tc); + for y in tr.y0..tr.y1 { + for x in tr.x0..tr.x1 { + let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; + match tile { + Some(t) => { + let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n; + for i in 0..n { + out[o + i] = read_sample(&t.data, surface.format.sample, base + i); + } + } + None => out[o..o + n].copy_from_slice(&dp), + } + } + } + } + out +} +/// Distinct tile allocations in `s`. +fn distinct_tiles(s: &Surface) -> usize { + let mut seen: Vec<*const Tile> = s.tiles().map(|(_, t)| Arc::as_ptr(t)).collect(); + seen.sort(); + seen.dedup(); + seen.len() +} + +/// Converting or tone-mapping a surface keeps a shared tile shared (#4531) and gives the +/// same pixels as converting each pixel: a filled background is one tile across the grid, +/// plus some distinct tiles. +#[test] +fn conversion_keeps_shared_tiles_shared() { + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(0, 0, 2048, 1024), &[0.9, 0.5, 0.2, 1.0]); + s.fill_rect(Rect::new(10, 10, 20, 20), &[0.1, 0.2, 0.3, 0.5]); + let shared_before = distinct_tiles(&s); + assert!(shared_before <= 2 && s.tile_count() == 32, "{shared_before} distinct of {}", s.tile_count()); + let r = Rect::new(0, 0, 2048, 1024); + for to in [PixelFormat::RGBA16, PixelFormat::RGBA32F] { + for out in [s.convert(to), s.try_convert(to).expect("memory")] { + assert_eq!(distinct_tiles(&out), shared_before, "{to:?}: still shared"); + assert_eq!(out.tile_count(), 32); + let (a, b) = (out.read_region(r), s.read_region(r)); + for (pa, pb) in a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0) { + let want = convert_pixel(&s.format(), &to, pb); + assert!(pa.iter().zip(&want).all(|(x, y)| (x - y).abs() < 1e-6), "{to:?}: {pa:?} vs {want:?}"); + } + } + } + let mut m = s.clone(); + m.map_color(|v| v * 0.5); + assert_eq!(distinct_tiles(&m), shared_before, "map_color keeps it shared"); + assert!((m.pixel(1000, 500)[0] - s.pixel(1000, 500)[0] * 0.5).abs() < 1.0 / 255.0); + assert_eq!(s.pixel(1000, 500), vec![s.pixel(1000, 500)[0], s.pixel(1000, 500)[1], s.pixel(1000, 500)[2], 1.0], "the source is untouched"); +} + +use super::*; +use photocraft_color::PixelFormat; +use proptest::prelude::*; + +fn write_region_reference(surface: &mut Surface, r: Rect, data: &[f32]) { + let n = surface.channels(); + let w = r.width() as usize; + assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); + let sample = surface.format.sample; + for tc in r.tiles() { + let tr = tc.rect().intersect(&r); + let t = surface.tile_mut(tc); + for y in tr.y0..tr.y1 { + for x in tr.x0..tr.x1 { + let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; + let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n; + for i in 0..n { + write_sample(&mut t.data, sample, base + i, data[o + i]); + } + } + } + } +} + +#[test] +fn region_writes_match_scalar_bytes_for_every_format() { + let special = [ + 0.0, + -0.0, + 1.0, + -1.0, + 2.0, + f32::INFINITY, + f32::NEG_INFINITY, + f32::NAN, + f32::from_bits(0x7fc12345), + f32::from_bits(0xffc12345), + f32::MIN_POSITIVE, + f32::from_bits(1), + 0.5 / 255.0, + 0.5 / 65535.0, + ]; + for mode in [ + ColorMode::Bitmap, + ColorMode::Grayscale, + ColorMode::Indexed, + ColorMode::Rgb, + ColorMode::Cmyk, + ColorMode::Lab, + ColorMode::Multichannel, + ColorMode::Duotone, + ] { + for sample in SampleType::ALL { + for alpha in [false, true] { + let fmt = PixelFormat::new(mode, sample, alpha); + let mut actual = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); + actual.write_pixel(900, 900, &vec![0.75; fmt.channels()]); + let mut expected = actual.clone(); + for rect in [Rect::EMPTY, Rect::new(-270, -2, 270, 3), Rect::new(256, 256, 512, 257), Rect::new(-64, -64, 0, 0), Rect::new(255, 250, 258, 270)] + { + let data: Vec<_> = (0..rect.width() as usize * rect.height() as usize * fmt.channels()) + .map(|i| { + if i % 3 == 0 { + special[i / 3 % special.len()] + } else { + // Integer rounding boundaries and deterministic arbitrary f32 bit patterns. + let bits = (i as u32).wrapping_mul(2654435761); + if i % 3 == 1 { ((bits % 65536) as f32 + 0.5) / 65535.0 } else { f32::from_bits(bits) } + } + }) + .collect(); + let snapshot = actual.clone(); + let snapshot_bytes = snapshot.to_interleaved(rect.inflate(1)); + let mut par = actual.clone(); + actual.write_region(rect, &data); + par.write_region_par(rect, &data); + write_region_reference(&mut expected, rect, &data); + assert_eq!(actual, expected, "{fmt:?}, {rect:?}"); + assert_eq!(par, expected, "parallel {fmt:?}, {rect:?}"); + assert_eq!(snapshot.to_interleaved(rect.inflate(1)), snapshot_bytes, "COW snapshot changed"); + // Repeat against already materialised, unshared tiles too. + actual.write_region(rect, &data); + par.write_region_par(rect, &data); + assert_eq!(actual, expected); + assert_eq!(par, expected); + } + } + } + } +} + +/// Mask builds call `write_region` inside a `OnceLock` initializer, where entering Rayon can +/// run another tile's job that waits on the same lock. With every global worker held, a write +/// that queued work on Rayon could not finish. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn write_region_does_not_enter_rayon() { + use std::sync::{Barrier, mpsc}; + let workers = rayon::current_num_threads(); + let held = Arc::new(Barrier::new(workers + 1)); + let release = Arc::new(Barrier::new(workers + 1)); + let (h, rel) = (held.clone(), release.clone()); + rayon::spawn_broadcast(move |_| { + h.wait(); + rel.wait(); + }); + held.wait(); + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let r = Rect::new(0, 0, 2 * TILE_SIZE, 2 * TILE_SIZE); + let mut s = Surface::new(PixelFormat::RGBA8); + s.write_region(r, &vec![0.5; (r.width() * r.height() * 4) as usize]); + tx.send(()).ok(); + }); + let done = rx.recv_timeout(std::time::Duration::from_secs(5)).is_ok(); + release.wait(); + assert!(done, "write_region waited on the Rayon pool"); +} + +#[test] +fn from_rgba_into_matches_from_rgba() { + for fmt in [PixelFormat::RGBA8, PixelFormat::GRAY8, PixelFormat::GRAYA8, PixelFormat::CMYKA8, PixelFormat::new(ColorMode::Lab, SampleType::F32, true)] { + let mut buf = [0.0f32; 8]; + let n = from_rgba_into(&fmt, [0.2, 0.5, 0.7, 0.4], &mut buf); + assert_eq!(&buf[..n], &from_rgba(&fmt, [0.2, 0.5, 0.7, 0.4])[..]); + } +} + +/// Sample counts above the stack capacity use writable storage without truncating channels. +#[test] +fn sample_buffer_keeps_stack_fast_path_and_supports_dynamic_channels() { + for channels in [1, 8, 9, 32] { + let mut stack = [0.0; 8]; + let mut heap = Vec::new(); + let samples = sample_buffer(channels, &mut stack, &mut heap); + assert_eq!(samples.len(), channels); + samples.fill(0.25); + if channels <= stack.len() { + assert!(heap.is_empty()); + assert_eq!(&stack[..channels], vec![0.25; channels]); + } else { + assert_eq!(heap, vec![0.25; channels]); + } + } +} + +/// Compare sparse reads and converted accessors with the previous allocating path. +#[test] +fn zero_alloc_accessors_match_read_region() { + for (fmt, default) in [ + PixelFormat::RGBA8, + PixelFormat::RGBA16, + PixelFormat::RGBA32F, + PixelFormat::GRAYA8, + PixelFormat::CMYKA8, + PixelFormat::GRAY8, + PixelFormat::GRAY8.with_sample(SampleType::F32), + PixelFormat::new(ColorMode::Lab, SampleType::U16, true), + ] + .into_iter() + .flat_map(|fmt| [0.0, 0.25, -0.0].map(|default| (fmt, default))) + { + let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]); + let mut stack = [0.0; 8]; + let mut heap = Vec::new(); + for capacity in [0, stack.len()] { + let decoded = s.default_samples(&mut stack[..capacity], &mut heap); + assert!(decoded.iter().map(|v| v.to_bits()).eq(s.default_pixel().into_iter().map(f32::to_bits))); + } + let r = Rect::new(-300, -20, 300, 40); + for (i, (x, y)) in [(-299, -19), (0, 0), (255, 39), (256, 10), (299, 0)].into_iter().enumerate() { + let px: Vec = (0..fmt.channels()).map(|c| ((i * 3 + c) % 5) as f32 / 4.0).collect(); + s.write_pixel(x, y, &px); + } + let region = s.read_region(r); + assert!(region.iter().map(|v| v.to_bits()).eq(previous_read_region(&s, r).into_iter().map(f32::to_bits))); + let mut into = vec![9.0; 3]; + s.read_region_into(r, &mut into); + assert_eq!(region, into); + let mut rgba = vec![[0.0; 4]; (r.width() * r.height()) as usize]; + s.read_rgba_into(r, &mut rgba); + let mut rgba8 = vec![[0; 4]; rgba.len()]; + s.read_rgba8_into(r, &mut rgba8); + let n = fmt.channels(); + for (i, p) in region.chunks_exact(n).enumerate() { + let want = to_rgba(&fmt, p); + assert_eq!(rgba8[i], want.map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)); + for c in 0..4 { + assert!((rgba[i][c] - want[c]).abs() < 1e-6, "{fmt:?} px {i}"); + } + let (x, y) = (r.x0 + (i % r.width() as usize) as i32, r.y0 + (i / r.width() as usize) as i32); + for c in 0..n { + let bits = s.sample_channel(x, y, c).to_bits(); + assert_eq!(bits, p[c].to_bits()); + assert_eq!(bits, into[i * n + c].to_bits()); + } + } + assert!(s.has_tiles_in(Rect::new(0, 0, 1, 1))); + assert!(!s.has_tiles_in(Rect::new(1000, 1000, 1001, 1001))); + } +} + +#[test] +fn fallible_region_reads_report_size_overflow() { + let surface = Surface::new(PixelFormat::RGBA8); + let huge = Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX); + assert_eq!(surface.try_read_region(huge), Err(AllocationError::SizeOverflow)); + assert_eq!(surface.try_to_interleaved(huge), Err(AllocationError::SizeOverflow)); +} + +#[test] +fn fallible_region_write_rejects_bad_input_without_mutating_surface() { + let mut surface = Surface::new(PixelFormat::RGBA8); + let before = surface.clone(); + assert_eq!(surface.try_write_region(Rect::new(0, 0, 2, 2), &[1.0]), Err(AllocationError::SizeOverflow)); + assert_eq!(surface, before); +} + +#[test] +fn fallible_tile_edits_move_weakly_cached_pixels_and_copy_shared_pixels() { + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + let mut surface = Surface::new(fmt); + let coord = TileCoord::new(0, 0); + let pixels = surface.try_tile_mut(coord).unwrap().bytes().as_ptr(); + let weak = Arc::downgrade(surface.tile(coord).unwrap()); + let tile = surface.try_tile_mut(coord).unwrap(); + assert_eq!(tile.bytes().as_ptr(), pixels); + assert!(weak.upgrade().is_none()); + let snapshot = surface.clone(); + surface.try_write_region(Rect::new(0, 0, 1, 1), &[1.0; 4]).unwrap(); + assert_eq!(snapshot.pixel(0, 0), vec![0.0; 4]); + assert_eq!(surface.pixel(0, 0), vec![1.0; 4]); + } +} + +#[test] +fn fill_rect_shares_covered_tiles_and_edits_stay_local() { + // A 300000² background used to materialize ~360 GB of tiles (#705). + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(0, 0, 300_000, 300_000), &[1.0, 0.5, 0.0, 1.0]); + let t = |s: &Surface, x, y| s.tile(TileCoord::new(x, y)).unwrap().clone(); + assert!(Arc::ptr_eq(&t(&s, 0, 0), &t(&s, 1000, 900))); + // 300000 is not a multiple of 256: the edge tile is partial and stays its own. + let edge = 300_000 / TILE_SIZE; + assert!(!Arc::ptr_eq(&t(&s, 0, 0), &t(&s, edge, 0))); + assert_eq!(s.pixel(299_999, 299_999), vec![1.0, 128.0 / 255.0, 0.0, 1.0]); + assert_eq!(s.pixel(300_000, 0), vec![0.0; 4]); + s.write_pixel(5, 5, &[0.0, 0.0, 1.0, 1.0]); + assert_eq!(s.pixel(5, 5), vec![0.0, 0.0, 1.0, 1.0]); + assert_eq!(s.pixel(300, 5), vec![1.0, 128.0 / 255.0, 0.0, 1.0]); + assert!(!Arc::ptr_eq(&t(&s, 0, 0), &t(&s, 1, 0))); +} + +#[test] +fn empty_surface_reads_default() { + let s = Surface::new(PixelFormat::RGBA8); + assert_eq!(s.pixel(10, -500), vec![0.0; 4]); + let m = Surface::with_default(PixelFormat::GRAY8, &[1.0]); + assert_eq!(m.pixel(123_456, -9), vec![1.0]); + assert_eq!(m.tile_count(), 0); +} + +#[test] +fn write_read_pixel_every_depth() { + for sample in SampleType::ALL { + let f = PixelFormat::RGBA8.with_sample(sample); + let mut s = Surface::new(f); + s.write_pixel(-3, 700, &[0.2, 0.4, 0.6, 1.0]); + let p = s.pixel(-3, 700); + for (a, b) in p.iter().zip([0.2, 0.4, 0.6, 1.0]) { + assert!((a - b).abs() <= 1.0 / 255.0, "{sample:?}"); + } + assert_eq!(s.tile_count(), 1); + assert_eq!(s.tile_bounds(), TileCoord::containing(-3, 700).rect()); + } +} + +#[test] +fn copy_on_write_shares_untouched_tiles() { + let mut a = Surface::new(PixelFormat::RGBA8); + a.fill_rect(Rect::new(0, 0, 512, 512), &[1.0, 0.0, 0.0, 1.0]); + let mut b = a.clone(); + b.write_pixel(10, 10, &[0.0, 1.0, 0.0, 1.0]); + // a unchanged + assert_eq!(a.pixel(10, 10), vec![1.0, 0.0, 0.0, 1.0]); + assert_eq!(b.pixel(10, 10), vec![0.0, 1.0, 0.0, 1.0]); + // only tile (0,0) was copied + let shared = a.tiles().filter(|(c, t)| Arc::ptr_eq(t, b.tile(**c).unwrap())).count(); + assert_eq!(shared, 3); +} + +#[test] +fn content_bounds_and_prune() { + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(300, 10, 310, 20), &[1.0, 1.0, 1.0, 1.0]); + s.write_pixel(-5, -5, &[0.0, 0.0, 0.0, 1.0]); + assert_eq!(s.content_bounds(), Rect::new(-5, -5, 310, 20)); + // erase the single pixel -> its tile becomes default and is pruned + s.write_pixel(-5, -5, &[0.0, 0.0, 0.0, 0.0]); + s.prune(); + assert_eq!(s.tile_count(), 1); + assert_eq!(s.content_bounds(), Rect::new(300, 10, 310, 20)); +} + +#[test] +fn interleaved_roundtrip_crossing_tiles() { + let r = Rect::new(-20, 250, 280, 262); + let bpp = PixelFormat::RGBA16.bytes_per_pixel(); + let bytes: Vec = (0..r.width() as usize * r.height() as usize * bpp).map(|i| (i * 31 % 251) as u8).collect(); + let s = Surface::from_interleaved(PixelFormat::RGBA16, r, &bytes); + assert_eq!(s.to_interleaved(r), bytes); + assert_eq!(s.tile_count(), 6); // x tiles -1..=1, y tiles 0..=1 +} + +#[test] +fn region_outside_reads_default() { + let s = Surface::with_default(PixelFormat::GRAY8, &[1.0]); + let v = s.read_region(Rect::new(0, 0, 3, 3)); + assert_eq!(v, vec![1.0; 9]); +} + +#[test] +fn convert_depths_and_models() { + let mut s = Surface::new(PixelFormat::RGBA8); + s.write_pixel(1, 1, &[1.0, 1.0, 1.0, 1.0]); + let g = s.convert(PixelFormat::GRAYA8); + assert!((g.pixel(1, 1)[0] - 1.0).abs() < 1e-2); + let f = s.convert(PixelFormat::RGBA32F); + assert_eq!(f.pixel(1, 1), vec![1.0, 1.0, 1.0, 1.0]); + let c = s.convert(PixelFormat::CMYKA8); + let p = c.pixel(1, 1); + assert!(p[3] < 0.01 && (p[4] - 1.0).abs() < 1e-6); + let back = c.convert(PixelFormat::RGBA8); + assert_eq!(back.pixel(1, 1), vec![1.0, 1.0, 1.0, 1.0]); +} + +#[test] +fn rgba_from_gray_and_cmyk() { + let mut g = Surface::new(PixelFormat::GRAYA8); + g.write_pixel(0, 0, &[0.5, 1.0]); + let v = g.rgba(0, 0); + assert!((v[0] - v[2]).abs() < 1e-6 && (v[3] - 1.0).abs() < 1e-6); +} + +#[test] +fn repeated_cmyk_reads_match_individual_pixels_bitwise() { + let rect = Rect::new(-2, -1, 515, 2); + for depth in SampleType::ALL { + for alpha in [false, true] { + let fmt = PixelFormat::new(ColorMode::Cmyk, depth, alpha); + let mut s = Surface::with_default(fmt, &[0.2, 0.4, 0.6, 0.3, 0.7]); + for (i, x) in (-1..514).enumerate() { + let c = if i / 2 % 256 == 0 { -0.0 } else { (i / 2 % 256) as f32 / 255.0 }; + s.write_pixel(x, 0, &[c, 0.4, 0.6, 0.3, (i % 9) as f32 / 8.0]); + } + let mut out = vec![[0.0; 4]; (rect.width() * rect.height()) as usize]; + s.read_rgba_into(rect, &mut out); + for (i, actual) in out.iter().enumerate() { + let expected = s.rgba(rect.x0 + (i % rect.width() as usize) as i32, rect.y0 + (i / rect.width() as usize) as i32); + assert_eq!(actual.map(f32::to_bits), expected.map(f32::to_bits), "{depth:?}, alpha={alpha}, pixel={i}"); + } + } + } +} + +#[test] +fn rgba_reads_match_individual_pixels_bitwise_in_every_model_and_depth() { + // Across tile edges and a missing tile; float samples include -0, out-of-range and NaN. + let rect = Rect::new(-3, -1, 300, 2); + for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab, ColorMode::Cmyk] { + for depth in SampleType::ALL { + for alpha in [false, true] { + let fmt = PixelFormat::new(mode, depth, alpha); + let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); + let values = [-0.0, 0.1, 0.5, 1.0, 1.5, -0.25, f32::NAN, 0.75]; + for (i, x) in (-2..260).enumerate() { + let px: Vec = (0..fmt.channels()).map(|c| values[(i + c * 3) % values.len()]).collect(); + s.write_pixel(x, 0, &px); + } + let mut out = vec![[0.0; 4]; (rect.width() * rect.height()) as usize]; + s.read_rgba_into(rect, &mut out); + for (i, actual) in out.iter().enumerate() { + let expected = s.rgba(rect.x0 + (i % rect.width() as usize) as i32, rect.y0 + (i / rect.width() as usize) as i32); + assert_eq!(actual.map(f32::to_bits), expected.map(f32::to_bits), "{fmt:?}, pixel={i}"); + } + } + } + } +} + +#[test] +fn tile_content_bounds_scans_against_the_given_pixel() { + let mut s = Surface::new(PixelFormat::GRAY8); + s.write_pixel(3, 4, &[1.0]); + s.write_pixel(200, 9, &[1.0]); + let t = s.tile(TileCoord::new(0, 0)).expect("written tile"); + assert_eq!(t.content_bounds(&[0]), Some((3, 4, 201, 10))); + assert_eq!(t.content_bounds(&[255]).map(|b| (b.0, b.1)), Some((0, 0))); + // A malformed pixel is no content, not a panic. + assert_eq!(t.content_bounds(&[]), None); +} + +#[test] +fn tile_content_bounds_match_a_per_pixel_scan() { + // One differing byte at each position of a pixel, at and around the compare-block + // boundaries, in every pixel size; and a pixel that differs from `dp` in every byte. + fn per_pixel(t: &Tile, dp: &[u8]) -> Option<(u16, u16, u16, u16)> { + let (bpp, ts) = (dp.len(), TILE_SIZE as usize); + let mut b: Option<(usize, usize, usize, usize)> = None; + for (i, px) in t.bytes().chunks_exact(bpp).enumerate() { + if px != dp { + let (x, y) = (i % ts, i / ts); + let (x0, y0, x1, y1) = b.unwrap_or((x, y, x, y)); + b = Some((x0.min(x), y0.min(y), x1.max(x), y1.max(y))); + } + } + b.map(|(x0, y0, x1, y1)| (x0 as u16, y0 as u16, x1 as u16 + 1, y1 as u16 + 1)) + } + for bpp in [1, 2, 3, 4, 6, 8, 16] { + let dp: Vec = (0..bpp).map(|i| (i * 37 + 5) as u8).collect(); + let row = TILE_SIZE as usize * bpp; + for spots in [vec![], vec![0], vec![row - 1], vec![63, 64], vec![row * 7 + 127, row * 7 + 128, row * 200 + 5], vec![row * 255 + row / 2]] { + for byte in 0..bpp { + let mut data = dp.repeat(TILE_SIZE as usize * TILE_SIZE as usize); + for &s in &spots { + data[s - s % bpp + byte] ^= 0x5a; + } + let t = Tile { data: data.into_boxed_slice() }; + assert_eq!(t.content_bounds(&dp), per_pixel(&t, &dp), "bpp {bpp}, spots {spots:?}, byte {byte}"); + } + } + let mut data = dp.repeat(TILE_SIZE as usize * TILE_SIZE as usize); + data[row * 3 + 9 * bpp..row * 3 + 10 * bpp].iter_mut().for_each(|b| *b = !*b); + let t = Tile { data: data.into_boxed_slice() }; + assert_eq!(t.content_bounds(&dp), Some((9, 3, 10, 4)), "bpp {bpp}"); + } +} + +#[test] +fn translated_matches_reading_the_moved_pixels() { + // Any offset (whole tiles, negative, across tile edges), every depth, a non-zero default. + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] { + let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); + let r = Rect::new(-37, 200, 530, 300); + let v: Vec = (0..r.width() * r.height() * fmt.channels() as u32).map(|i| (i % 251) as f32 / 250.0).collect(); + s.write_region(r, &v); + for (dx, dy) in [(0, 0), (256, -512), (1, 0), (-3, 7), (300, -257), (-1000, 999)] { + let t = s.translated(dx, dy, s.content_bounds()); + let moved = r.translate(dx, dy).inflate(3); + assert_eq!(t.read_region(moved), s.read_region(moved.translate(-dx, -dy)), "{fmt:?} by ({dx}, {dy})"); + assert_eq!(t.default_pixel(), s.default_pixel()); + assert_eq!(t.to_interleaved(r.translate(dx, dy)), s.to_interleaved(r), "{fmt:?} by ({dx}, {dy}): not an exact copy"); + } + // Whole tiles: the tiles are shared, not copied. + let t = s.translated(512, -256, s.content_bounds()); + assert!(s.tiles().zip(t.tiles()).all(|((_, a), (_, b))| Arc::ptr_eq(a, b))); + // Tiles without content (allocated, default pixels) are left behind. + let mut padded = s.clone(); + padded.fill_rect(Rect::new(2000, 2000, 2100, 2100), &s.default_pixel()); + assert_eq!(padded.translated(5, 5, s.content_bounds()).tile_count(), s.translated(5, 5, s.content_bounds()).tile_count()); + } + // A solid fill moved off the tile grid keeps sharing its one tile inside, at every depth + // and over a non-zero default pixel, and reads exactly like the copied pixels. + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] { + let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); + let r = Rect::new(-300, -10, 1300, 1030); + s.fill_rect(r, &vec![0.75; fmt.channels()]); + let fill = s.tile(TileCoord::new(1, 1)).cloned().expect("an inner fill tile"); + for (dx, dy) in [(10, 7), (-1, 0), (0, 300), (-257, 513)] { + let t = s.translated(dx, dy, s.content_bounds()); + let moved = r.translate(dx, dy); + assert_eq!(t.read_region(moved.inflate(3)), s.read_region(moved.inflate(3).translate(-dx, -dy)), "{fmt:?} by ({dx}, {dy})"); + // Targets read only from the fill's whole tiles (x -256..1280, y 0..1024). + let whole = Rect::new(-256, 0, 1280, 1024).translate(dx, dy); + let inner: Vec<_> = t.tiles().filter(|(c, _)| whole.contains_rect(&c.rect())).collect(); + assert!(!inner.is_empty() && inner.iter().all(|(_, a)| Arc::ptr_eq(a, &fill)), "{fmt:?} by ({dx}, {dy}): inner tiles copied"); + } + // Nudged back and forth, the inside keeps sharing one tile (copies of uniform edge + // tiles count as that value too) and the pixels stay exact. + let mut t = s.clone(); + for k in 0..8 { + let d = if k % 2 == 0 { 10 } else { -10 }; + t = t.translated(d, d / 2, t.content_bounds()); + } + // (Targets whose last window read uniform tiles only: one tile in from the fill's whole + // tiles on the sides the last move came from.) + let inner: Vec<_> = t.tiles().filter(|(c, _)| Rect::new(-256, 0, 1024, 768).contains_rect(&c.rect())).map(|(_, a)| a).collect(); + assert!(inner.len() >= 4 && inner.iter().all(|a| Arc::ptr_eq(a, inner[0])), "{fmt:?}: repeated moves copied the inside"); + assert_eq!(t.read_region(r.inflate(3)), s.read_region(r.inflate(3)), "{fmt:?}: back where it started"); + } + // Two solid fills of different values side by side: windows across the seam are + // copied (each tile is uniform, but not with the same value), the rest shared. + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA32F] { + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(0, 0, 1024, 768), &vec![0.2; fmt.channels()]); + s.fill_rect(Rect::new(1024, 0, 2048, 768), &vec![0.9; fmt.channels()]); + let t = s.translated(10, 7, s.content_bounds()); + let all = Rect::new(-20, -20, 2100, 800); + assert_eq!(t.read_region(all), s.read_region(all.translate(-10, -7)), "{fmt:?}: two fills"); + let seam = t.tile(TileCoord::new(4, 1)).expect("seam tile"); + let (left, right) = (t.tile(TileCoord::new(2, 1)).expect("left"), t.tile(TileCoord::new(6, 1)).expect("right")); + assert!(!Arc::ptr_eq(seam, left) && !Arc::ptr_eq(seam, right) && !Arc::ptr_eq(left, right), "{fmt:?}: seam aliased"); + } + // An offset of i32::MIN saturates its negation, so the source window isn't the exact + // preimage: no shortcut may apply (a zero pre-fill would leak into the output). + let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.5]); + s.fill_rect(Rect::new(i32::MAX - 1024, 0, i32::MAX - 512, 512), &[0.25]); + let (fill, default) = (s.sample_channel(i32::MAX - 600, 10, 0), s.default_pixel()[0]); + for (dx, dy) in [(i32::MIN, 1), (1, i32::MIN), (i32::MIN, 0)] { + let t = s.translated(dx, dy, s.content_bounds()); + for (c, _) in t.tiles() { + assert!(t.read_region(c.rect()).iter().all(|v| *v == fill || *v == default), "({dx}, {dy}): tile {c:?} holds a pre-fill"); + } + } + // One tile shared but not uniform: each target is copied, not aliased. + let mut s = Surface::new(PixelFormat::GRAY8); + s.write_pixel(3, 4, &[1.0]); + let odd = s.tile(TileCoord::new(0, 0)).cloned().expect("written tile"); + let grid: Vec<_> = (0..9).map(|i| (TileCoord::new(i % 3, i / 3), odd.clone())).collect(); + s.put_tiles(grid); + let t = s.translated(10, 7, s.content_bounds()); + let all = Rect::new(-20, -20, 800, 800); + assert_eq!(t.read_region(all), s.read_region(all.translate(-10, -7))); + assert!(t.tiles().all(|(_, a)| !Arc::ptr_eq(a, &odd))); + // Offsets at the limits don't panic. + let mut s = Surface::new(PixelFormat::GRAY8); + s.write_pixel(5, 5, &[1.0]); + let all = Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX); + let _ = s.translated(i32::MAX, i32::MIN, all); + let _ = s.translated(i32::MIN + 1, 3, all); +} + +/// Many references to one payload, moved off the tile grid: the rebuilt tiles that read the +/// same source tiles at the same offset are one tile, not a copy each. +#[test] +fn translated_shares_tiles_rebuilt_from_shared_sources() { + let fmt = PixelFormat::RGBA8; + let mut one = Surface::new(fmt); + let r = Rect::new(0, 0, TILE_SIZE, TILE_SIZE); + let px: Vec = (0..r.width() * r.height()).flat_map(|i| [(i % 251) as f32 / 255.0, (i % 7) as f32 / 7.0, 0.5, 1.0]).collect(); + one.write_region(r, &px); + let payload = Arc::clone(one.tile(TileCoord::new(0, 0)).unwrap()); + let mut s = Surface::new(fmt); + s.put_tiles((0..16).flat_map(|ty| (0..16).map(move |tx| TileCoord::new(tx, ty))).map(|c| (c, Arc::clone(&payload)))); + let moved = s.translated(7, 5, s.content_bounds()); + let distinct: std::collections::HashSet<_> = moved.tiles().map(|(_, t)| Arc::as_ptr(t)).collect(); + // The 15 × 15 interior tiles read the same four source tiles at the same offset, so they are + // one tile, however many threads build them; only the 64 border tiles (cut by the + // content's edge) are built one by one. + assert!(moved.tile_count() == 289 && distinct.len() == 64 + 1, "{} tiles, {} distinct", moved.tile_count(), distinct.len()); + let all = Rect::new(-50, -50, 16 * TILE_SIZE + 50, 16 * TILE_SIZE + 50); + assert_eq!(moved.read_region(all), s.read_region(all.translate(-7, -5))); +} + +#[test] +fn a_surface_bounds_tile_count_is_counted_not_walked() { + let mut s = Surface::new(PixelFormat::RGBA8); + let far = Rect::new(0, 0, i32::MAX, i32::MAX); + assert_eq!(far.tile_count(), u64::from(i32::MAX as u32 / TILE_SIZE as u32 + 1).pow(2)); + // Not allocated: 2^46 entries is far past any reservation. + assert!(s.try_take_tiles(far).is_err()); +} + +#[test] +fn translated_stores_no_tiles_of_only_the_default_pixel() { + let only_default = |t: &Surface| { + let dp = t.default_pixel(); + t.tiles().filter(|(c, _)| t.read_region(c.rect()).chunks_exact(dp.len()).all(|p| p == dp.as_slice())).count() + }; + // Two blocks a few tiles apart, moved off the tile grid and back: the default-pixel edges + // of their tiles land on tiles of their own, which aren't stored. + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] { + for default in [0.0, 0.25] { + let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]); + s.fill_rect(Rect::new(0, 0, 300, 300), &vec![1.0; fmt.channels()]); + s.fill_rect(Rect::new(2000, 1000, 2300, 1300), &vec![0.5; fmt.channels()]); + let all = Rect::new(-600, -600, 3000, 2000); + let mut t = s.clone(); + for (dx, dy) in [(100, 56), (-100, -56), (10, 7), (-3, 40), (130, -90), (-137, 43)] { + let moved = t.translated(dx, dy, t.content_bounds()); + assert_eq!(moved.read_region(all), t.read_region(all.translate(-dx, -dy)), "{fmt:?} over {default} by ({dx}, {dy})"); + assert_eq!(only_default(&moved), 0, "{fmt:?} over {default} by ({dx}, {dy})"); + t = moved; + } + assert_eq!(t.read_region(all), s.read_region(all), "{fmt:?} over {default}: back where it started"); + assert_eq!(t.tile_count(), s.tile_count(), "{fmt:?} over {default}: back where it started"); + } + } + // Stored tiles of the default pixel inside `content`: the targets that would share one of + // them (#4414's uniform windows) are left out too. + let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.25]); + s.fill_rect(Rect::new(0, 0, 1024, 1024), &[0.25]); + s.write_pixel(600, 600, &[1.0]); + let content = Rect::new(0, 0, 1024, 1024); + let t = s.translated(10, 7, content); + assert_eq!(only_default(&t), 0); + assert_eq!(t.tile_count(), 1); + assert_eq!(t.read_region(Rect::new(-20, -20, 1100, 1100)), s.read_region(Rect::new(-30, -27, 1090, 1093))); +} + +proptest! { + #[test] + fn region_write_read_roundtrip(x in -600i32..600, y in -600i32..600, w in 1u32..90, h in 1u32..90, seed in any::()) { + let r = Rect::from_xywh(x, y, w, h); + let n = 4usize; + let data: Vec = (0..(w * h) as usize * n).map(|i| ((i as u32).wrapping_mul(2654435761).wrapping_add(seed) % 256) as f32 / 255.0).collect(); + let mut s = Surface::new(PixelFormat::RGBA8); + s.write_region(r, &data); + let back = s.read_region(r); + for (a, b) in back.iter().zip(&data) { + prop_assert!((a - b).abs() < 1e-6); + } + prop_assert_eq!(s.content_bounds().union(&r), r); + } + + #[test] + fn clone_mutation_isolated(x in -300i32..300, y in -300i32..300) { + let mut a = Surface::new(PixelFormat::RGBA8); + a.fill_rect(Rect::new(-256, -256, 256, 256), &[0.5, 0.5, 0.5, 1.0]); + let snapshot = a.clone(); + a.write_pixel(x, y, &[1.0, 0.0, 0.0, 1.0]); + let expect = if Rect::new(-256, -256, 256, 256).contains(x, y) { vec![0.5f32, 0.5, 0.5, 1.0] } else { vec![0.0; 4] }; + let got = snapshot.pixel(x, y); + for (g, e) in got.iter().zip(&expect) { + prop_assert!((g - e).abs() <= 1.0 / 255.0); + } + } +} + +#[test] +fn strided_row_sampling_handles_extreme_coordinates_and_steps() { + for sample in SampleType::ALL { + let mut s = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, sample, false), &[0.25]); + for (x, value) in [(i32::MIN, 0.1), (-1, 0.3), (0, 0.4), (i32::MAX - 1, 0.6), (i32::MAX, 0.9)] { + s.write_pixel(x, 0, &[value]); + } + for y in [0, 256] { + for (x0, step, len) in [(i32::MAX, 1, 1), (i32::MIN, i32::MAX, 3), (0, i32::MAX, 2), (i32::MAX - 1, 1, 2), (i32::MAX, i32::MAX, 0)] { + let mut out = vec![0.0; len]; + s.sample_row_strided(y, x0, step, 0, &mut out); + for (i, &got) in out.iter().enumerate() { + let x = i32::try_from(i64::from(x0) + i as i64 * i64::from(step)).unwrap(); + assert_eq!(got, s.sample_channel(x, y, 0), "{sample:?} y={y} x0={x0} step={step} i={i}"); + } + } + } + } +} + +#[test] +fn strided_row_sampling_uses_default_past_coordinate_range() { + for sample in SampleType::ALL { + let mut s = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, sample, false), &[0.25]); + s.write_pixel(i32::MAX, 0, &[0.75]); + s.write_pixel(i32::MIN, 0, &[1.0]); + for step in [1, i32::MAX] { + let mut out = [0.0; 4]; + s.sample_row_strided(0, i32::MAX, step, 0, &mut out); + assert_eq!(out, [s.sample_channel(i32::MAX, 0, 0), s.default_pixel()[0], s.default_pixel()[0], s.default_pixel()[0]]); + } + } +} + +#[test] +fn strided_row_sampling_matches_sample_channel() { + let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.25]); + s.fill_rect(Rect::new(-300, 10, 200, 40), &[1.0]); + s.fill_rect(Rect::new(250, 10, 700, 20), &[0.5]); + for (y, x0, step) in [(15, -520, 7), (15, -1, 1), (30, 3, 64), (500, 0, 9)] { + let mut out = vec![0.0; 120]; + s.sample_row_strided(y, x0, step, 0, &mut out); + for (i, v) in out.iter().enumerate() { + assert_eq!(*v, s.sample_channel(x0 + i as i32 * step, y, 0), "y={y} x0={x0} step={step} i={i}"); + } + } +} + +#[test] +fn content_bounds_with_tile_skipping() { + // Interior content only; ring tiles present but all-default (unpruned). + let mut s = Surface::new(PixelFormat::GRAY8); + s.fill_rect(Rect::new(0, 0, 1024, 1024), &[0.0]); + s.fill_rect(Rect::new(300, 310, 700, 720), &[1.0]); + assert_eq!(s.content_bounds(), Rect::new(300, 310, 700, 720)); + // Full-canvas content plus a far-away speck. + let mut s = Surface::new(PixelFormat::GRAY8); + s.fill_rect(Rect::new(0, 0, 2000, 1500), &[1.0]); + s.fill_rect(Rect::new(-700, 4000, -699, 4001), &[0.5]); + assert_eq!(s.content_bounds(), Rect::new(-700, 0, 2000, 4001)); +} From e7958711c06556003cc926177419da7d92c5fdc9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:18:01 +0000 Subject: [PATCH 129/259] refactor(photocraft): move services.rs tests to services/tests.rs --- apps/photocraft/src/services.rs | 692 +------------------------- apps/photocraft/src/services/tests.rs | 686 +++++++++++++++++++++++++ 2 files changed, 687 insertions(+), 691 deletions(-) create mode 100644 apps/photocraft/src/services/tests.rs diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 2966eee8ed..47b4bbd34a 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -725,694 +725,4 @@ fn platform_beep() { } #[cfg(test)] -mod tests { - use super::*; - use photocraft_engine::Session; - use photocraft_format::list_recovery; - use photocraft_ui_egui::{PhotocraftApp, prefs_ui}; - use serde_json::{Value, json}; - - /// #6601: a chosen path whose name isn't valid Unicode is reported, never handed on lossily - /// (Open would fail with "No such file", Save would write a second, renamed file). - #[test] - fn a_chosen_path_that_is_not_valid_unicode_is_an_error_not_another_name() { - #[cfg(unix)] - let bad = { - use std::os::unix::ffi::OsStrExt; - std::env::temp_dir().join(std::ffi::OsStr::from_bytes(b"img\xFF.png")) - }; - #[cfg(windows)] - let bad = { - use std::os::windows::ffi::OsStringExt; - let mut wide: Vec = "img".encode_utf16().collect(); - wide.push(0xD800); - wide.extend(".png".encode_utf16()); - std::env::temp_dir().join(std::ffi::OsString::from_wide(&wide)) - }; - let good = std::env::temp_dir().join("ok.png"); - let save = |path: &Path| answer_one(path, true, FileDialogAnswer::SaveTo); - assert!(matches!(save(&bad), FileDialogAnswer::Unavailable(e) if e.contains("not valid Unicode") && e.contains("another name"))); - assert!(matches!(save(&good), FileDialogAnswer::SaveTo(p) if p == good.to_str().unwrap())); - let open = answer([good.as_path(), bad.as_path()], false, FileDialogAnswer::Paths); - assert!(matches!(open, FileDialogAnswer::Unavailable(e) if e.contains("open it again"))); - } - - /// #6121: the file type picked in the save dialog gives the name its extension where the - /// dialog left the one it opened with, and only there. - #[test] - fn the_picked_file_type_gives_the_name_its_extension() { - let exts = |e: &[&str]| e.iter().map(|s| s.to_string()).collect::>(); - let (png, psd) = (exts(&["png"]), exts(&["psd", "psb"])); - let opened = Some("Untitled-1.psd"); - let cases = [ - // PNG picked, the name as the dialog opened (or renamed, its extension kept). - ("/pics/Untitled-1.psd", opened, &png, "/pics/Untitled-1.png"), - ("/pics/art.psd", opened, &png, "/pics/art.png"), - ("/pics/ART.PSD", opened, &png, "/pics/ART.png"), - // No extension: the type's. One PhotoCraft doesn't save is part of the name. - ("/pics/art", opened, &png, "/pics/art.png"), - ("/pics/scan.2024", opened, &png, "/pics/scan.2024.png"), - // Typed, an extension PhotoCraft saves is the user's: kept, whatever the type says - // (the PSD type untouched, or PNG picked and .jpg typed). - ("/pics/art.png", opened, &psd, "/pics/art.png"), - ("/pics/art.jpg", opened, &png, "/pics/art.jpg"), - ("/pics/art.pcraft", opened, &png, "/pics/art.pcraft"), - // Already the type's: kept, including its other extensions. - ("/pics/art.png", opened, &png, "/pics/art.png"), - ("/pics/art.PNG", opened, &png, "/pics/art.PNG"), - ("/pics/big.psb", opened, &psd, "/pics/big.psb"), - // The dialog opened on a .pcraft: that is the extension the type replaces. - ("/pics/art.pcraft", Some("art.pcraft"), &png, "/pics/art.png"), - ("/pics/art.psd", Some("art.pcraft"), &png, "/pics/art.psd"), - ]; - for (typed, opened, chosen, want) in cases { - assert_eq!(with_chosen_type(Path::new(typed), opened, chosen), PathBuf::from(want), "{typed} (opened {opened:?})"); - } - // No type picked: the name as typed. - assert_eq!(with_chosen_type(Path::new("/pics/art.psd"), opened, &[]), PathBuf::from("/pics/art.psd")); - } - - /// Regression using the real clipboard on an isolated Windows CI runner. - #[cfg(target_os = "windows")] - #[test] - #[ignore = "requires exclusive use of the Windows clipboard"] - fn busy_native_clipboard_preserves_copied_shape() { - for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace"] { - let mut native = native(None); - let services = Services { - clipboard_set_image: native.clipboard_set_image.take(), - clipboard_get_image: native.clipboard_get_image.take(), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - app.run("file.new", json!({"width": 80, "height": 60})).unwrap(); - app.run("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); - app.run("edit.copy", json!({})).unwrap(); - assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); - assert!(app.services.clipboard_get_image.as_mut().unwrap()().unwrap().is_some(), "native export succeeded"); - app.run("file.new", json!({"width": 80, "height": 60})).unwrap(); - - // Another thread holds the OS clipboard open beyond arboard's bounded retry window. - let (ready_tx, ready_rx) = std::sync::mpsc::channel(); - let (release_tx, release_rx) = std::sync::mpsc::channel(); - let holder = std::thread::spawn(move || { - // A non-null window distinguishes this owner from arboard's null-window opens. - let guard = winsafe::HWND::GetDesktopWindow().OpenClipboard().unwrap(); - ready_tx.send(()).unwrap(); - release_rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap(); - drop(guard); - }); - ready_rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap(); - let contention = arboard::Clipboard::new().unwrap().get_image().err(); - let first = app.run(id, json!({})); - release_tx.send(()).unwrap(); - holder.join().unwrap(); - assert!(matches!(contention, Some(arboard::Error::ClipboardOccupied)), "diagnostic must actually occupy the clipboard: {contention:?}"); - eprintln!("paste while clipboard occupied: {first:?}"); - assert!(first.is_err(), "report contention rather than a successful no-op"); - assert!( - app.session.clipboard.as_ref().is_some_and(|clip| clip.layers.is_some()), - "a temporary OS read failure must not discard the copied editable shape" - ); - app.run(id, json!({})).unwrap(); - let state = app.session.active().unwrap(); - assert!( - matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Shape(_)), - "retry keeps the shape editable" - ); - } - } - - #[cfg(all(unix, not(target_os = "macos")))] - #[test] - fn open_filters_cover_uppercase_and_mixed_case_extensions() { - // Matches `text` against a glob of literals and `[..]` classes, as the portal would after `*.`. - fn matches(glob: &str, text: &str) -> bool { - let mut text = text.chars(); - let mut glob = glob.chars(); - while let Some(g) = glob.next() { - let class: String = if g == '[' { glob.by_ref().take_while(|&c| c != ']').collect() } else { g.to_string() }; - if !text.next().is_some_and(|t| class.contains(t)) { - return false; - } - } - text.next().is_none() - } - assert_eq!(open_filter_extensions(&["cr2", "pcraft"]), ["[cC][rR]2", "[pP][cC][rR][aA][fF][tT]"]); - let globs = open_filter_extensions(OPEN_EXTS); - assert_eq!(globs.len(), OPEN_EXTS.len()); - for (ext, glob) in OPEN_EXTS.iter().zip(&globs) { - // Every casing: lower, UPPER, and alternating both ways (JpG, jPg). - let alternating = |upper_first: bool| -> String { - ext.chars().enumerate().map(|(i, c)| if (i % 2 == 0) == upper_first { c.to_ascii_uppercase() } else { c }).collect() - }; - for name in [ext.to_string(), ext.to_ascii_uppercase(), alternating(true), alternating(false)] { - assert!(matches(glob, &name), "{glob} should match .{name}"); - } - assert!(!matches(glob, &format!("{ext}x")) && !matches(glob, &ext[..ext.len() - 1]), "{glob} matches only .{ext}"); - } - assert!(!globs.iter().any(|glob| matches(glob, "txt"))); - let svg_filter = open_filters().into_iter().find(|(name, _)| *name == "SVG").map(|(_, exts)| exts).unwrap_or_default(); - assert_eq!(svg_filter, open_filter_extensions(SVG_EXTS)); - let psd_filter = open_filters().into_iter().find(|(name, _)| *name == "Photoshop").map(|(_, exts)| exts).unwrap_or_default(); - assert_eq!(psd_filter, open_filter_extensions(&["psd", "psb", "psdt"])); - assert!(psd_filter.iter().any(|glob| matches(glob, "psd")) && psd_filter.iter().any(|glob| matches(glob, "PSD"))); - assert!(svg_filter.iter().any(|glob| matches(glob, "svg")) && svg_filter.iter().any(|glob| matches(glob, "svgz"))); - } - - /// #6337: after All Formats, every format File › Open reads has its own filter, and no filter - /// offers an extension All Formats doesn't. - #[test] - fn every_open_format_has_its_own_filter() { - let filters = open_filters(); - assert_eq!(filters[0], ("All Formats", open_filter_extensions(OPEN_EXTS)), "All Formats comes first"); - let mut named: Vec<&str> = OPEN_FILTERS.iter().flat_map(|(_, exts)| exts.iter().copied()).collect(); - let total = named.len(); - named.sort_unstable(); - named.dedup(); - assert_eq!(named.len(), total, "an extension is listed under two filters"); - let mut all = OPEN_EXTS.to_vec(); - all.sort_unstable(); - assert_eq!(named, all, "the named filters cover All Formats exactly"); - let names: Vec<&str> = filters.iter().map(|(name, _)| *name).collect(); - for name in ["Photoshop", "Affinity", "HEIF", "PNG", "JPEG", "TIFF", "Portable Bitmap", "OpenEXR", "Radiance HDR", "Paint.NET"] { - assert!(names.contains(&name), "{name}"); - } - } - - #[cfg(not(all(unix, not(target_os = "macos"))))] - #[test] - fn open_filters_keep_literal_extensions_on_windows_and_macos() { - assert_eq!(open_filter_extensions(OPEN_EXTS), OPEN_EXTS); - assert_eq!(open_filter_extensions(&["pcraft"]), ["pcraft"]); - assert_eq!(open_filters().into_iter().find(|(name, _)| *name == "SVG").map(|(_, exts)| exts), Some(vec!["svg".to_string(), "svgz".to_string()])); - assert_eq!( - open_filters().into_iter().find(|(name, _)| *name == "Photoshop").map(|(_, exts)| exts), - Some(vec!["psd".to_string(), "psb".to_string(), "psdt".to_string()]) - ); - } - - #[test] - fn flatpak_builds_have_no_update_transport() { - assert!(update_transport(Some(std::ffi::OsStr::new("ai.storyteller.photocraft"))).is_none()); - assert!(update_transport(None).is_some()); - } - - #[test] - fn xwayland_command_matches_how_photocraft_was_installed() { - // Flatpak: WAYLAND_DISPLAY doesn't reach the sandbox's socket choice; flatpak's flags do. - let flatpak = xwayland_command(Some("ai.storyteller.photocraft"), None, false); - assert_eq!(flatpak.as_deref(), Some("flatpak run --nosocket=wayland --socket=x11 ai.storyteller.photocraft")); - // AppImage: its own path, quoted for the shell (spaces, quotes). - let appimage = xwayland_command(None, Some("/home/me/My Apps/it's.AppImage"), true); - assert_eq!(appimage.as_deref(), Some(r"WAYLAND_DISPLAY= '/home/me/My Apps/it'\''s.AppImage'")); - let bare = xwayland_command(None, Some("/opt/photocraft-0.3.0-linux-x86_64.AppImage"), true); - assert_eq!(bare.as_deref(), Some("WAYLAND_DISPLAY= /opt/photocraft-0.3.0-linux-x86_64.AppImage")); - // deb, rpm, AUR, tarball: the binary on the PATH. - assert_eq!(xwayland_command(None, None, true).as_deref(), Some("WAYLAND_DISPLAY= photocraft")); - assert_eq!(xwayland_command(Some(""), Some(""), true).as_deref(), Some("WAYLAND_DISPLAY= photocraft")); - // No X server (XWayland disabled): nothing to suggest. - assert_eq!(xwayland_command(None, Some("/opt/p.AppImage"), false), None); - } - - /// Tests every native save dialog and records the suggested file name. Each name's file type must come first - /// in the save panel, or the panel appends the first type's extension (`photo.webp.psd`, `photo.gif.psd`). - #[test] - fn every_save_dialog_leads_with_its_own_extension() { - let asked: Rc>> = Rc::default(); - let log = asked.clone(); - // Record each save dialog's suggested name and cancel it, as the user would. - let services = Services { - file_dialog: Some(Box::new(move |request, _parent, reply| { - if let FileDialogRequest::Save { suggested } = request { - log.borrow_mut().push(suggested); - } - reply.send(None); - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - let ctx = egui::Context::default(); - // Dialogs are shown on the next frame: poll once so each is answered before the next asks. - let invoke = |app: &mut PhotocraftApp, id: &str| { - let r = photocraft_ui_egui::menus::invoke(app, &ctx, id, json!({})); - app.poll_file_dialog(&ctx, None); - r - }; - let dialog = |app: &mut PhotocraftApp, id: &str, fields: Value| { - let d = invoke(app, id).unwrap()["dialog"].as_u64().unwrap(); - for (k, v) in fields.as_object().unwrap() { - app.ui.dialog_mut(d).unwrap().fields.insert(k.clone(), v.clone()); - } - let _ = photocraft_ui_egui::dialogs::confirm(app, d); - app.poll_file_dialog(&ctx, None); - }; - new_doc(&mut app, "#ff0000"); - // Save As, Save a Copy. - // Files in a format Save As can't write, like .dng, should suggest .psd instead. - let _ = invoke(&mut app, "file.saveAs"); - for name in ["cat.pcraft", "cat.jpeg", "cat.gif", "cat.bmp", "cat.dng"] { - app.session.active_mut().unwrap().path = Some(name.into()); - let _ = invoke(&mut app, "file.saveAs"); - } - let _ = invoke(&mut app, "file.saveACopy"); - // Export As, Quick Export, Save for Web (with and without slices). - for format in ["png", "jpg", "webp", "tif", "tga"] { - dialog(&mut app, "file.export.exportAs", json!({"format": format})); - } - for format in ["png", "jpg", "gif", "webp"] { - app.run("prefs.set", json!({"path": "export.quickExportFormat", "value": format})).unwrap(); - let _ = invoke(&mut app, "file.export.quickExportAsPng"); - } - for format in ["gif", "png8", "png24", "jpeg", "wbmp"] { - dialog(&mut app, "file.export.saveForWebLegacy", json!({"format": format})); - } - app.run("slice.new", json!({"x": 0, "y": 0, "width": 2, "height": 2})).unwrap(); - dialog(&mut app, "file.export.saveForWebLegacy", json!({"html": true})); - // Measurement Log, Export/Import Presets. - app.run("image.analysis.recordMeasurements", json!({})).unwrap(); - let _ = invoke(&mut app, "measurementLog.export"); - dialog(&mut app, "edit.presets.exportImportPresets", json!({"action": "export"})); - let asked = asked.borrow(); - let exts: Vec<&str> = asked.iter().filter_map(|s| s.rsplit_once('.').map(|(_, e)| e)).collect(); - // The extension each save above should suggest, in order. - let want = [ - "psd", // Save As untitled - "pcraft jpeg gif bmp psd", // Save As opened .pcraft .jpeg .gif .bmp .dng - "psd", // Save a Copy - "png jpg webp tif tga", // Export As - "png jpg gif webp", // Quick Export - "gif png png jpg wbmp html", // Save for Web: gif png8 png24 jpeg wbmp, then with slices - "csv pcpresets", // Measurement Log, Export Presets - ] - .join(" "); - assert_eq!(exts, want.split(' ').collect::>()); - for (name, ext) in asked.iter().zip(exts) { - // The first type's first extension is the one Windows adds to the bare name. - assert_eq!(save_filters(name)[0].1.first().map(String::as_str), Some(ext), "{name}: {:?}", save_filters(name)[0]); - } - assert_eq!(save_filters("Untitled")[0].0, "PSD Document", "no extension keeps the default"); - } - - /// Every flat format Save As offers is one PhotoCraft writes, and ICO is among them (#4357). - #[test] - fn save_as_offers_only_writable_formats_including_ico() { - // Layered formats, and PDF, are written by `photocraft-io`, not a codec. - let layered = ["psd", "psb", "pcraft", "ora", "pdf"]; - for (name, exts) in SAVE_FILTERS { - for ext in exts.iter().filter(|e| !layered.contains(e)) { - let format = photocraft_codecs::from_extension(ext).unwrap_or_else(|| panic!("{name}: .{ext} is no known format")); - assert!(format.caps().write, "{name}: .{ext} can't be written"); - } - } - for ext in ["ico", "gif", "bmp", "dds"] { - assert!(save_filters("Untitled-1.psd").iter().any(|(_, exts)| exts.iter().any(|e| e == ext)), ".{ext} is offered"); - } - assert_eq!(save_filters("icon.ico")[0].0, "ICO", "an .ico name leads with its own type"); - // What Save As writes there: an icon up to 256×256, and a clear error past that. - let doc = |side: u32| { - let mut s = Session::new(); - s.execute("file.new", json!({"width": side, "height": side})).unwrap(); - s.active().unwrap().doc.clone() - }; - let opts = export_options(&photocraft_ui_egui::ExportSettings::default()); - let icon = photocraft_io::export(&doc(256), "icon.ico", &opts).unwrap(); - assert_eq!(icon.bytes[..4], [0, 0, 1, 0], "an ICO header"); - let err = photocraft_io::export(&doc(300), "icon.ico", &opts).map(|_| ()).unwrap_err().to_string(); - assert!(err.contains("256"), "{err}"); - } - - /// #4394: with File name extensions shown, Windows kept `image.psd` when the type was changed to - /// PhotoCraft. Given the bare `image`, it adds the extension of whichever type is picked - /// (checked by hand with rfd 0.17.2 on Windows 11), defaulting to the first type's. - #[test] - fn the_windows_save_dialog_gets_a_bare_name_so_the_type_picks_the_extension() { - for (suggested, name, first) in [ - ("/pics/image.psd", "image", "psd"), - ("/pics/image.psb", "image", "psb"), - ("/pics/image.pcraft", "image", "pcraft"), - ("/pics/sky.fit", "sky", "fit"), - ("cat.jpeg", "cat", "jpeg"), - ("swatches.aco", "swatches", "aco"), - ] { - assert_eq!(dialog_file_name(suggested, true).as_deref(), Some(name), "{suggested}"); - assert_eq!(save_filters(suggested)[0].1[0], first, "{suggested}"); - // Elsewhere the dialogs keep the whole name (see `dialog_file_name`). - let whole = Path::new(suggested).file_name().unwrap().to_string_lossy().into_owned(); - assert_eq!(dialog_file_name(suggested, false), Some(whole), "{suggested}"); - } - // Kept whole: a second dot (Windows could keep `scan.jpg`), the user's upper case, no - // extension, and a dotfile. - for name in ["scan.jpg.psd", "my.photo.psd", "transparent.PNG", "Untitled", ".psd"] { - assert_eq!(dialog_file_name(name, true).as_deref(), Some(name)); - } - assert_eq!(dialog_file_name("", true), None); - } - - /// A name in another letter case reaches the same file where the file system ignores case - /// (Windows, and macOS by default), and only there. Two files with the same contents are two. - #[test] - fn same_file_follows_the_file_system() { - let dir = std::env::temp_dir().join(format!("photocraft-same-file-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let (cat, dog, upper) = (dir.join("CAT.psd"), dir.join("dog.psd"), dir.join("CAT.PSD")); - std::fs::write(&cat, b"same").unwrap(); - std::fs::write(&dog, b"same").unwrap(); - assert!(same_file(&cat, &cat)); - assert!(!same_file(&cat, &dog)); - assert_eq!(same_file(&upper, &cat), upper.exists(), "the same file only where letter case is ignored"); - assert!(!same_file(&dir.join("missing.psd"), &cat)); - std::fs::remove_dir_all(&dir).unwrap(); - } - - /// A hard link is another entry in the folder, though it reaches the same file: a save to it - /// replaces that entry and leaves the other name on the old file. Another spelling of a name, - /// where letter case is ignored, is the same entry. - #[test] - fn a_hard_link_is_another_entry() { - let dir = std::env::temp_dir().join(format!("photocraft-same-entry-{}", std::process::id())); - std::fs::create_dir_all(dir.join("other")).unwrap(); - let (cat, bare, upper, other) = (dir.join("CAT.psd"), dir.join("CAT"), dir.join("CAT.PSD"), dir.join("other").join("CAT.psd")); - std::fs::write(&cat, b"cat").unwrap(); - std::fs::hard_link(&cat, &bare).unwrap(); - std::fs::hard_link(&cat, &other).unwrap(); - // Where both names reach one file (one inode on Unix), the folder still lists both. - let one_file = |_: &Path, _: &Path| true; - assert!(!same_entry(&bare, &cat, one_file)); - assert!(!same_entry(&bare, &cat, same_file)); - assert!(!same_entry(&other, &cat, same_file), "another folder"); - assert!(same_entry(&cat, &cat, one_file)); - assert!(same_entry(&cat, &cat, same_file)); - if upper.exists() { - assert!(same_entry(&upper, &cat, same_file), "one entry where letter case is ignored"); - } else { - std::fs::hard_link(&cat, &upper).unwrap(); - assert!(!same_entry(&upper, &cat, same_file), "two entries where letter case tells names apart"); - } - assert!(!same_entry(&dir.join("missing.psd"), &cat, same_file)); - std::fs::remove_dir_all(&dir).unwrap(); - } - - #[test] - fn block_on_waits_for_a_wake_from_another_thread() { - let (tx, rx) = std::sync::mpsc::channel::(); - let mut woken = false; - let ready = std::future::poll_fn(move |cx| { - if woken { - return std::task::Poll::Ready(7); - } - woken = true; - let _ = tx.send(cx.waker().clone()); - std::task::Poll::Pending - }); - let waker = std::thread::spawn(move || rx.recv().unwrap().wake()); - assert_eq!(block_on(ready), 7); - waker.join().unwrap(); - } - - const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; - const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; - const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; - - /// One app launch with crash recovery in `dir` (dropping it is the crash: background writes - /// already queued finish, nothing else runs). - fn launch(dir: &Path) -> PhotocraftApp { - let mut app = PhotocraftApp::new(Session::new(), recovery_services(Some(dir.to_path_buf()))); - let ctx = egui::Context::default(); - prefs_ui::tick(&mut app, &ctx); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while app.session.has_jobs() && std::time::Instant::now() < deadline { - photocraft_ui_egui::jobs_ui::tick(&mut app, &ctx); - std::thread::sleep(std::time::Duration::from_millis(1)); - } - assert!(!app.session.has_jobs(), "recovery finished"); - app - } - - /// The first pixel of each open document, and whether it's unsaved. - fn open_docs(app: &PhotocraftApp) -> Vec<([f32; 4], bool)> { - app.session.documents().iter().map(|d| (photocraft_compose::flatten(&d.doc).px.first().copied().unwrap_or_default(), d.is_dirty())).collect() - } - - fn index_of(app: &PhotocraftApp, color: [f32; 4]) -> usize { - open_docs(app).iter().position(|(c, _)| *c == color).unwrap() - } - - fn new_doc(app: &mut PhotocraftApp, color: &str) { - app.run("file.new", json!({"width": 4, "height": 4})).unwrap(); - app.run("edit.fill", json!({"color": color})).unwrap(); - } - - fn autosave(app: &mut PhotocraftApp, ctx: &egui::Context) { - prefs_ui::autosave_now(app); - prefs_ui::tick(app, ctx); - } - - #[test] - fn recovered_documents_survive_a_second_crash_until_saved_or_closed() { - let dir = std::env::temp_dir().join(format!("photocraft-recovery-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let ctx = egui::Context::default(); - // Launch 1: two unsaved documents are autosaved, then the app crashes. - { - let mut app = launch(&dir); - new_doc(&mut app, "#ff0000"); - new_doc(&mut app, "#0000ff"); - autosave(&mut app, &ctx); - } - assert_eq!(list_recovery(&dir).len(), 2); - // Launch 2 recovers both and crashes again before its first autosave (#444). - { - let mut app = launch(&dir); - let mut docs = open_docs(&app); - docs.sort_by(|a, b| a.0[0].total_cmp(&b.0[0])); - assert_eq!(docs, [(BLUE, true), (RED, true)], "recovered and still unsaved"); - prefs_ui::tick(&mut app, &ctx); - } - assert_eq!(list_recovery(&dir).len(), 2, "recovering keeps the entries on disk"); - // Launch 3 has both again; autosaving unchanged documents adds nothing, a new document - // (whose id may repeat one from an earlier launch) gets an entry of its own. - { - let mut app = launch(&dir); - assert_eq!(app.session.documents().len(), 2); - autosave(&mut app, &ctx); - new_doc(&mut app, "#00ff00"); - autosave(&mut app, &ctx); - } - assert_eq!(list_recovery(&dir).len(), 3); - // Launch 4: closing and saving recovered documents removes their entries, no duplicates. - let mut app = launch(&dir); - assert_eq!(app.session.documents().len(), 3); - let red = index_of(&app, RED); - app.run("file.close", json!({"document": red})).unwrap(); - // Saving marks the revision saved (the file write itself is the save service's job). - assert!(app.session.set_active(index_of(&app, BLUE))); - let st = app.session.active_mut().unwrap(); - st.saved_revision = st.revision; - prefs_ui::tick(&mut app, &ctx); - let left = list_recovery(&dir); - assert_eq!(left.len(), 1); - assert_eq!(photocraft_compose::flatten(&photocraft_format::recover(&left[0]).unwrap()).px.first().copied(), Some(GREEN)); - let green = index_of(&app, GREEN); - app.run("file.close", json!({"document": green})).unwrap(); - prefs_ui::tick(&mut app, &ctx); - assert!(list_recovery(&dir).is_empty()); - drop(app); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn failed_background_autosave_is_reported_and_retried_without_another_edit() { - let dir = temp("autosave-retry"); - let recovery = dir.join("Recovery"); - // A regular file prevents creation of the recovery bundle directory. - std::fs::write(&recovery, b"blocked").unwrap(); - let ctx = egui::Context::default(); - let mut app = launch(&recovery); - new_doc(&mut app, "#ff0000"); - let revision = app.session.active().unwrap().revision; - assert_ne!(revision, 0, "a sidecar-less bundle lists as revision 0"); - autosave(&mut app, &ctx); - - let mut failed = false; - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - while std::time::Instant::now() < deadline { - prefs_ui::tick(&mut app, &ctx); - if app.ui.status.starts_with("Autosave failed:") { - failed = true; - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - assert!(failed, "background write failures must reach the UI"); - assert!(app.ui.status_error); - assert!(list_recovery(&recovery).is_empty()); - - // No edit occurs: retrying this very same revision must still work. - std::fs::remove_file(&recovery).unwrap(); - std::fs::create_dir(&recovery).unwrap(); - autosave(&mut app, &ctx); - // The worker commits the bundle's manifest before it publishes the sidecar, and - // `list_recovery` lists a committed sidecar-less bundle (revision 0) on its own, so - // the first non-empty listing can come from the middle of the write. Wait for the write - // to finish: the entry then carries the sidecar's revision. - let mut recovered = Vec::new(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - while std::time::Instant::now() < deadline { - prefs_ui::tick(&mut app, &ctx); - recovered = list_recovery(&recovery); - if recovered.iter().any(|e| e.info.revision == revision) { - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - assert_eq!(recovered.len(), 1, "unchanged revision should retry after failure"); - assert_eq!(recovered[0].info.revision, revision); - let restored = photocraft_format::recover(&recovered[0]).unwrap(); - assert_eq!(photocraft_compose::flatten(&restored).px.first().copied(), Some(RED)); - drop(app); - std::fs::remove_dir_all(dir).unwrap(); - } - - use std::sync::atomic::{AtomicUsize, Ordering}; - - fn temp(tag: &str) -> PathBuf { - static N: AtomicUsize = AtomicUsize::new(0); - let d = std::env::temp_dir().join(format!("photocraft-services-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d - } - - fn red_png(w: u32, h: u32) -> Vec { - let img = Image::from_u8(w, h, ChannelLayout::Rgba, [255u8, 0, 0, 255].repeat((w * h) as usize)).unwrap(); - photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).unwrap() - } - - /// A 1×1 uncompressed 32-bit TGA (TGA has no magic number). - fn tga_1x1() -> Vec { - let mut b = vec![0u8, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 32, 8]; - b.extend_from_slice(&[0, 0, 255, 255]); // BGRA red - b - } - - #[test] - fn copied_image_file_pastes_its_pixels() { - let dir = temp("png"); - let png = dir.join("red.png"); - std::fs::write(&png, red_png(3, 2)).unwrap(); - let (w, h, px) = image_from_files(&[png]).unwrap(); - assert_eq!((w, h), (3, 2)); - assert_eq!(px, [255u8, 0, 0, 255].repeat(6)); - } - - #[test] - fn crlf_from_a_uri_list_is_ignored() { - // arboard splits text/uri-list on LF, so GNOME Files' CRLF list leaves a '\r' behind. - let dir = temp("crlf"); - let png = dir.join("red image.png"); - std::fs::write(&png, red_png(2, 2)).unwrap(); - let with_cr = PathBuf::from(format!("{}\r", png.display())); - assert_eq!(image_from_files(&[with_cr]).map(|(w, h, _)| (w, h)), Some((2, 2))); - } - - #[test] - fn non_images_are_skipped_for_the_first_image() { - let dir = temp("mixed"); - let (txt, png) = (dir.join("notes.txt"), dir.join("red.png")); - std::fs::write(&txt, b"not an image").unwrap(); - std::fs::write(&png, red_png(4, 1)).unwrap(); - let missing = dir.join("gone.png"); - assert_eq!(image_from_files(&[missing.clone(), txt.clone(), dir.clone(), png]).map(|(w, h, _)| (w, h)), Some((4, 1))); - assert!(image_from_files(&[missing, txt, dir]).is_none()); - assert!(image_from_files(&[]).is_none()); - } - - #[test] - fn a_damaged_image_is_skipped_not_a_panic() { - let dir = temp("damaged"); - let bad = dir.join("cut.png"); - std::fs::write(&bad, &red_png(8, 8)[..20]).unwrap(); - assert!(image_from_files(&[bad]).is_none()); - } - - fn encoded(format: photocraft_codecs::Format, w: u32, h: u32) -> Vec { - let img = Image::from_u8(w, h, ChannelLayout::Rgba, [255u8, 0, 0, 255].repeat((w * h) as usize)).unwrap(); - photocraft_codecs::encode(&img, format, &EncodeOptions::default()).unwrap() - } - - #[test] - fn non_png_clipboard_images_paste() { - // #2546: a screenshot tool that offers only image/bmp or image/jpeg pasted nothing. - let bmp = encoded(photocraft_codecs::Format::Bmp, 3, 2); - let offers = vec!["text/plain".to_string(), "image/bmp".to_string()]; - let mut asked = Vec::new(); - let got = image_from_offers(&offers, |mime| { - asked.push(mime.to_string()); - Some(bmp.clone()) - }); - assert_eq!(got, Some((3, 2, [255u8, 0, 0, 255].repeat(6)))); - assert_eq!(asked, ["image/bmp"], "text offers are never fetched"); - - let jpeg = encoded(photocraft_codecs::Format::Jpeg, 16, 8); - let offers = vec!["image/jpeg".to_string()]; - assert_eq!(image_from_offers(&offers, |_| Some(jpeg.clone())).map(|(w, h, _)| (w, h)), Some((16, 8))); - } - - #[test] - fn undecodable_clipboard_offers_fall_through_to_the_next() { - let bmp = encoded(photocraft_codecs::Format::Bmp, 2, 2); - let cut = encoded(photocraft_codecs::Format::Png, 8, 8)[..20].to_vec(); - let offers: Vec = ["image/webp", "image/png", "image/x-tga", "image/bmp"].map(String::from).to_vec(); - let got = image_from_offers(&offers, |mime| match mime { - "image/webp" => None, - "image/png" => Some(cut.clone()), - "image/x-tga" => Some(b"not an image".to_vec()), - _ => Some(bmp.clone()), - }); - assert_eq!(got.map(|(w, h, _)| (w, h)), Some((2, 2))); - assert!(image_from_offers(&offers[..3], |_| Some(cut.clone())).is_none()); - assert!(image_from_offers(&[], |_| Some(bmp.clone())).is_none()); - } - - #[test] - fn clipboard_tga_is_trusted_only_by_its_type() { - assert_eq!(image_from_offers(&["image/x-tga".to_string()], |_| Some(tga_1x1())), Some((1, 1, vec![255, 0, 0, 255]))); - assert!(image_from_offers(&["image/x-unknown".to_string()], |_| Some(tga_1x1())).is_none()); - } - - #[test] - fn tga_is_trusted_only_with_its_extension() { - let dir = temp("tga"); - let (tga, bin) = (dir.join("red.tga"), dir.join("red.bin")); - std::fs::write(&tga, tga_1x1()).unwrap(); - std::fs::write(&bin, tga_1x1()).unwrap(); - assert_eq!(image_from_files(&[tga]), Some((1, 1, vec![255, 0, 0, 255]))); - assert!(image_from_files(&[bin]).is_none()); - } - - /// #7582: a panic while reading the OS clipboard (in arboard, or decoding a copied file) is - /// the paste's error in the status bar, not a crash: the document stays and the next paste - /// works. The same for a panic while writing it. - #[test] - fn a_panicking_clipboard_read_is_reported_not_a_crash() { - let panics = Rc::new(Cell::new(true)); - let p = panics.clone(); - let get = guarded_clipboard_get(move || if p.get() { panic!("clipboard decoder bug") } else { Ok(Some((2, 2, [0u8, 0, 255, 255].repeat(4)))) }); - let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(get), ..Default::default() }); - app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); - let layers = app.session.active().unwrap().doc.layers.len(); - - let error = app.run("edit.paste", json!({})).unwrap_err(); - assert!(error.contains("Paste failed"), "{error}"); - assert!(app.ui.status_error && app.ui.status.contains("Paste failed"), "{}", app.ui.status); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "the document is unchanged"); - - panics.set(false); - app.run("edit.paste", json!({})).unwrap(); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1, "the next paste works"); - - let mut set = guarded_clipboard_set(|_: u32, _: u32, _: &[u8]| panic!("clipboard writer bug")); - assert!(set(1, 1, &[0; 4]).unwrap_err().contains("Copy failed")); - } -} +mod tests; diff --git a/apps/photocraft/src/services/tests.rs b/apps/photocraft/src/services/tests.rs new file mode 100644 index 0000000000..f9bce2a367 --- /dev/null +++ b/apps/photocraft/src/services/tests.rs @@ -0,0 +1,686 @@ +use super::*; +use photocraft_engine::Session; +use photocraft_format::list_recovery; +use photocraft_ui_egui::{PhotocraftApp, prefs_ui}; +use serde_json::{Value, json}; + +/// #6601: a chosen path whose name isn't valid Unicode is reported, never handed on lossily +/// (Open would fail with "No such file", Save would write a second, renamed file). +#[test] +fn a_chosen_path_that_is_not_valid_unicode_is_an_error_not_another_name() { + #[cfg(unix)] + let bad = { + use std::os::unix::ffi::OsStrExt; + std::env::temp_dir().join(std::ffi::OsStr::from_bytes(b"img\xFF.png")) + }; + #[cfg(windows)] + let bad = { + use std::os::windows::ffi::OsStringExt; + let mut wide: Vec = "img".encode_utf16().collect(); + wide.push(0xD800); + wide.extend(".png".encode_utf16()); + std::env::temp_dir().join(std::ffi::OsString::from_wide(&wide)) + }; + let good = std::env::temp_dir().join("ok.png"); + let save = |path: &Path| answer_one(path, true, FileDialogAnswer::SaveTo); + assert!(matches!(save(&bad), FileDialogAnswer::Unavailable(e) if e.contains("not valid Unicode") && e.contains("another name"))); + assert!(matches!(save(&good), FileDialogAnswer::SaveTo(p) if p == good.to_str().unwrap())); + let open = answer([good.as_path(), bad.as_path()], false, FileDialogAnswer::Paths); + assert!(matches!(open, FileDialogAnswer::Unavailable(e) if e.contains("open it again"))); +} + +/// #6121: the file type picked in the save dialog gives the name its extension where the +/// dialog left the one it opened with, and only there. +#[test] +fn the_picked_file_type_gives_the_name_its_extension() { + let exts = |e: &[&str]| e.iter().map(|s| s.to_string()).collect::>(); + let (png, psd) = (exts(&["png"]), exts(&["psd", "psb"])); + let opened = Some("Untitled-1.psd"); + let cases = [ + // PNG picked, the name as the dialog opened (or renamed, its extension kept). + ("/pics/Untitled-1.psd", opened, &png, "/pics/Untitled-1.png"), + ("/pics/art.psd", opened, &png, "/pics/art.png"), + ("/pics/ART.PSD", opened, &png, "/pics/ART.png"), + // No extension: the type's. One PhotoCraft doesn't save is part of the name. + ("/pics/art", opened, &png, "/pics/art.png"), + ("/pics/scan.2024", opened, &png, "/pics/scan.2024.png"), + // Typed, an extension PhotoCraft saves is the user's: kept, whatever the type says + // (the PSD type untouched, or PNG picked and .jpg typed). + ("/pics/art.png", opened, &psd, "/pics/art.png"), + ("/pics/art.jpg", opened, &png, "/pics/art.jpg"), + ("/pics/art.pcraft", opened, &png, "/pics/art.pcraft"), + // Already the type's: kept, including its other extensions. + ("/pics/art.png", opened, &png, "/pics/art.png"), + ("/pics/art.PNG", opened, &png, "/pics/art.PNG"), + ("/pics/big.psb", opened, &psd, "/pics/big.psb"), + // The dialog opened on a .pcraft: that is the extension the type replaces. + ("/pics/art.pcraft", Some("art.pcraft"), &png, "/pics/art.png"), + ("/pics/art.psd", Some("art.pcraft"), &png, "/pics/art.psd"), + ]; + for (typed, opened, chosen, want) in cases { + assert_eq!(with_chosen_type(Path::new(typed), opened, chosen), PathBuf::from(want), "{typed} (opened {opened:?})"); + } + // No type picked: the name as typed. + assert_eq!(with_chosen_type(Path::new("/pics/art.psd"), opened, &[]), PathBuf::from("/pics/art.psd")); +} + +/// Regression using the real clipboard on an isolated Windows CI runner. +#[cfg(target_os = "windows")] +#[test] +#[ignore = "requires exclusive use of the Windows clipboard"] +fn busy_native_clipboard_preserves_copied_shape() { + for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace"] { + let mut native = native(None); + let services = + Services { clipboard_set_image: native.clipboard_set_image.take(), clipboard_get_image: native.clipboard_get_image.take(), ..Default::default() }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.run("file.new", json!({"width": 80, "height": 60})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); + assert!(app.services.clipboard_get_image.as_mut().unwrap()().unwrap().is_some(), "native export succeeded"); + app.run("file.new", json!({"width": 80, "height": 60})).unwrap(); + + // Another thread holds the OS clipboard open beyond arboard's bounded retry window. + let (ready_tx, ready_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let holder = std::thread::spawn(move || { + // A non-null window distinguishes this owner from arboard's null-window opens. + let guard = winsafe::HWND::GetDesktopWindow().OpenClipboard().unwrap(); + ready_tx.send(()).unwrap(); + release_rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap(); + drop(guard); + }); + ready_rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap(); + let contention = arboard::Clipboard::new().unwrap().get_image().err(); + let first = app.run(id, json!({})); + release_tx.send(()).unwrap(); + holder.join().unwrap(); + assert!(matches!(contention, Some(arboard::Error::ClipboardOccupied)), "diagnostic must actually occupy the clipboard: {contention:?}"); + eprintln!("paste while clipboard occupied: {first:?}"); + assert!(first.is_err(), "report contention rather than a successful no-op"); + assert!( + app.session.clipboard.as_ref().is_some_and(|clip| clip.layers.is_some()), + "a temporary OS read failure must not discard the copied editable shape" + ); + app.run(id, json!({})).unwrap(); + let state = app.session.active().unwrap(); + assert!( + matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Shape(_)), + "retry keeps the shape editable" + ); + } +} + +#[cfg(all(unix, not(target_os = "macos")))] +#[test] +fn open_filters_cover_uppercase_and_mixed_case_extensions() { + // Matches `text` against a glob of literals and `[..]` classes, as the portal would after `*.`. + fn matches(glob: &str, text: &str) -> bool { + let mut text = text.chars(); + let mut glob = glob.chars(); + while let Some(g) = glob.next() { + let class: String = if g == '[' { glob.by_ref().take_while(|&c| c != ']').collect() } else { g.to_string() }; + if !text.next().is_some_and(|t| class.contains(t)) { + return false; + } + } + text.next().is_none() + } + assert_eq!(open_filter_extensions(&["cr2", "pcraft"]), ["[cC][rR]2", "[pP][cC][rR][aA][fF][tT]"]); + let globs = open_filter_extensions(OPEN_EXTS); + assert_eq!(globs.len(), OPEN_EXTS.len()); + for (ext, glob) in OPEN_EXTS.iter().zip(&globs) { + // Every casing: lower, UPPER, and alternating both ways (JpG, jPg). + let alternating = |upper_first: bool| -> String { + ext.chars().enumerate().map(|(i, c)| if (i % 2 == 0) == upper_first { c.to_ascii_uppercase() } else { c }).collect() + }; + for name in [ext.to_string(), ext.to_ascii_uppercase(), alternating(true), alternating(false)] { + assert!(matches(glob, &name), "{glob} should match .{name}"); + } + assert!(!matches(glob, &format!("{ext}x")) && !matches(glob, &ext[..ext.len() - 1]), "{glob} matches only .{ext}"); + } + assert!(!globs.iter().any(|glob| matches(glob, "txt"))); + let svg_filter = open_filters().into_iter().find(|(name, _)| *name == "SVG").map(|(_, exts)| exts).unwrap_or_default(); + assert_eq!(svg_filter, open_filter_extensions(SVG_EXTS)); + let psd_filter = open_filters().into_iter().find(|(name, _)| *name == "Photoshop").map(|(_, exts)| exts).unwrap_or_default(); + assert_eq!(psd_filter, open_filter_extensions(&["psd", "psb", "psdt"])); + assert!(psd_filter.iter().any(|glob| matches(glob, "psd")) && psd_filter.iter().any(|glob| matches(glob, "PSD"))); + assert!(svg_filter.iter().any(|glob| matches(glob, "svg")) && svg_filter.iter().any(|glob| matches(glob, "svgz"))); +} + +/// #6337: after All Formats, every format File › Open reads has its own filter, and no filter +/// offers an extension All Formats doesn't. +#[test] +fn every_open_format_has_its_own_filter() { + let filters = open_filters(); + assert_eq!(filters[0], ("All Formats", open_filter_extensions(OPEN_EXTS)), "All Formats comes first"); + let mut named: Vec<&str> = OPEN_FILTERS.iter().flat_map(|(_, exts)| exts.iter().copied()).collect(); + let total = named.len(); + named.sort_unstable(); + named.dedup(); + assert_eq!(named.len(), total, "an extension is listed under two filters"); + let mut all = OPEN_EXTS.to_vec(); + all.sort_unstable(); + assert_eq!(named, all, "the named filters cover All Formats exactly"); + let names: Vec<&str> = filters.iter().map(|(name, _)| *name).collect(); + for name in ["Photoshop", "Affinity", "HEIF", "PNG", "JPEG", "TIFF", "Portable Bitmap", "OpenEXR", "Radiance HDR", "Paint.NET"] { + assert!(names.contains(&name), "{name}"); + } +} + +#[cfg(not(all(unix, not(target_os = "macos"))))] +#[test] +fn open_filters_keep_literal_extensions_on_windows_and_macos() { + assert_eq!(open_filter_extensions(OPEN_EXTS), OPEN_EXTS); + assert_eq!(open_filter_extensions(&["pcraft"]), ["pcraft"]); + assert_eq!(open_filters().into_iter().find(|(name, _)| *name == "SVG").map(|(_, exts)| exts), Some(vec!["svg".to_string(), "svgz".to_string()])); + assert_eq!( + open_filters().into_iter().find(|(name, _)| *name == "Photoshop").map(|(_, exts)| exts), + Some(vec!["psd".to_string(), "psb".to_string(), "psdt".to_string()]) + ); +} + +#[test] +fn flatpak_builds_have_no_update_transport() { + assert!(update_transport(Some(std::ffi::OsStr::new("ai.storyteller.photocraft"))).is_none()); + assert!(update_transport(None).is_some()); +} + +#[test] +fn xwayland_command_matches_how_photocraft_was_installed() { + // Flatpak: WAYLAND_DISPLAY doesn't reach the sandbox's socket choice; flatpak's flags do. + let flatpak = xwayland_command(Some("ai.storyteller.photocraft"), None, false); + assert_eq!(flatpak.as_deref(), Some("flatpak run --nosocket=wayland --socket=x11 ai.storyteller.photocraft")); + // AppImage: its own path, quoted for the shell (spaces, quotes). + let appimage = xwayland_command(None, Some("/home/me/My Apps/it's.AppImage"), true); + assert_eq!(appimage.as_deref(), Some(r"WAYLAND_DISPLAY= '/home/me/My Apps/it'\''s.AppImage'")); + let bare = xwayland_command(None, Some("/opt/photocraft-0.3.0-linux-x86_64.AppImage"), true); + assert_eq!(bare.as_deref(), Some("WAYLAND_DISPLAY= /opt/photocraft-0.3.0-linux-x86_64.AppImage")); + // deb, rpm, AUR, tarball: the binary on the PATH. + assert_eq!(xwayland_command(None, None, true).as_deref(), Some("WAYLAND_DISPLAY= photocraft")); + assert_eq!(xwayland_command(Some(""), Some(""), true).as_deref(), Some("WAYLAND_DISPLAY= photocraft")); + // No X server (XWayland disabled): nothing to suggest. + assert_eq!(xwayland_command(None, Some("/opt/p.AppImage"), false), None); +} + +/// Tests every native save dialog and records the suggested file name. Each name's file type must come first +/// in the save panel, or the panel appends the first type's extension (`photo.webp.psd`, `photo.gif.psd`). +#[test] +fn every_save_dialog_leads_with_its_own_extension() { + let asked: Rc>> = Rc::default(); + let log = asked.clone(); + // Record each save dialog's suggested name and cancel it, as the user would. + let services = Services { + file_dialog: Some(Box::new(move |request, _parent, reply| { + if let FileDialogRequest::Save { suggested } = request { + log.borrow_mut().push(suggested); + } + reply.send(None); + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + let ctx = egui::Context::default(); + // Dialogs are shown on the next frame: poll once so each is answered before the next asks. + let invoke = |app: &mut PhotocraftApp, id: &str| { + let r = photocraft_ui_egui::menus::invoke(app, &ctx, id, json!({})); + app.poll_file_dialog(&ctx, None); + r + }; + let dialog = |app: &mut PhotocraftApp, id: &str, fields: Value| { + let d = invoke(app, id).unwrap()["dialog"].as_u64().unwrap(); + for (k, v) in fields.as_object().unwrap() { + app.ui.dialog_mut(d).unwrap().fields.insert(k.clone(), v.clone()); + } + let _ = photocraft_ui_egui::dialogs::confirm(app, d); + app.poll_file_dialog(&ctx, None); + }; + new_doc(&mut app, "#ff0000"); + // Save As, Save a Copy. + // Files in a format Save As can't write, like .dng, should suggest .psd instead. + let _ = invoke(&mut app, "file.saveAs"); + for name in ["cat.pcraft", "cat.jpeg", "cat.gif", "cat.bmp", "cat.dng"] { + app.session.active_mut().unwrap().path = Some(name.into()); + let _ = invoke(&mut app, "file.saveAs"); + } + let _ = invoke(&mut app, "file.saveACopy"); + // Export As, Quick Export, Save for Web (with and without slices). + for format in ["png", "jpg", "webp", "tif", "tga"] { + dialog(&mut app, "file.export.exportAs", json!({"format": format})); + } + for format in ["png", "jpg", "gif", "webp"] { + app.run("prefs.set", json!({"path": "export.quickExportFormat", "value": format})).unwrap(); + let _ = invoke(&mut app, "file.export.quickExportAsPng"); + } + for format in ["gif", "png8", "png24", "jpeg", "wbmp"] { + dialog(&mut app, "file.export.saveForWebLegacy", json!({"format": format})); + } + app.run("slice.new", json!({"x": 0, "y": 0, "width": 2, "height": 2})).unwrap(); + dialog(&mut app, "file.export.saveForWebLegacy", json!({"html": true})); + // Measurement Log, Export/Import Presets. + app.run("image.analysis.recordMeasurements", json!({})).unwrap(); + let _ = invoke(&mut app, "measurementLog.export"); + dialog(&mut app, "edit.presets.exportImportPresets", json!({"action": "export"})); + let asked = asked.borrow(); + let exts: Vec<&str> = asked.iter().filter_map(|s| s.rsplit_once('.').map(|(_, e)| e)).collect(); + // The extension each save above should suggest, in order. + let want = [ + "psd", // Save As untitled + "pcraft jpeg gif bmp psd", // Save As opened .pcraft .jpeg .gif .bmp .dng + "psd", // Save a Copy + "png jpg webp tif tga", // Export As + "png jpg gif webp", // Quick Export + "gif png png jpg wbmp html", // Save for Web: gif png8 png24 jpeg wbmp, then with slices + "csv pcpresets", // Measurement Log, Export Presets + ] + .join(" "); + assert_eq!(exts, want.split(' ').collect::>()); + for (name, ext) in asked.iter().zip(exts) { + // The first type's first extension is the one Windows adds to the bare name. + assert_eq!(save_filters(name)[0].1.first().map(String::as_str), Some(ext), "{name}: {:?}", save_filters(name)[0]); + } + assert_eq!(save_filters("Untitled")[0].0, "PSD Document", "no extension keeps the default"); +} + +/// Every flat format Save As offers is one PhotoCraft writes, and ICO is among them (#4357). +#[test] +fn save_as_offers_only_writable_formats_including_ico() { + // Layered formats, and PDF, are written by `photocraft-io`, not a codec. + let layered = ["psd", "psb", "pcraft", "ora", "pdf"]; + for (name, exts) in SAVE_FILTERS { + for ext in exts.iter().filter(|e| !layered.contains(e)) { + let format = photocraft_codecs::from_extension(ext).unwrap_or_else(|| panic!("{name}: .{ext} is no known format")); + assert!(format.caps().write, "{name}: .{ext} can't be written"); + } + } + for ext in ["ico", "gif", "bmp", "dds"] { + assert!(save_filters("Untitled-1.psd").iter().any(|(_, exts)| exts.iter().any(|e| e == ext)), ".{ext} is offered"); + } + assert_eq!(save_filters("icon.ico")[0].0, "ICO", "an .ico name leads with its own type"); + // What Save As writes there: an icon up to 256×256, and a clear error past that. + let doc = |side: u32| { + let mut s = Session::new(); + s.execute("file.new", json!({"width": side, "height": side})).unwrap(); + s.active().unwrap().doc.clone() + }; + let opts = export_options(&photocraft_ui_egui::ExportSettings::default()); + let icon = photocraft_io::export(&doc(256), "icon.ico", &opts).unwrap(); + assert_eq!(icon.bytes[..4], [0, 0, 1, 0], "an ICO header"); + let err = photocraft_io::export(&doc(300), "icon.ico", &opts).map(|_| ()).unwrap_err().to_string(); + assert!(err.contains("256"), "{err}"); +} + +/// #4394: with File name extensions shown, Windows kept `image.psd` when the type was changed to +/// PhotoCraft. Given the bare `image`, it adds the extension of whichever type is picked +/// (checked by hand with rfd 0.17.2 on Windows 11), defaulting to the first type's. +#[test] +fn the_windows_save_dialog_gets_a_bare_name_so_the_type_picks_the_extension() { + for (suggested, name, first) in [ + ("/pics/image.psd", "image", "psd"), + ("/pics/image.psb", "image", "psb"), + ("/pics/image.pcraft", "image", "pcraft"), + ("/pics/sky.fit", "sky", "fit"), + ("cat.jpeg", "cat", "jpeg"), + ("swatches.aco", "swatches", "aco"), + ] { + assert_eq!(dialog_file_name(suggested, true).as_deref(), Some(name), "{suggested}"); + assert_eq!(save_filters(suggested)[0].1[0], first, "{suggested}"); + // Elsewhere the dialogs keep the whole name (see `dialog_file_name`). + let whole = Path::new(suggested).file_name().unwrap().to_string_lossy().into_owned(); + assert_eq!(dialog_file_name(suggested, false), Some(whole), "{suggested}"); + } + // Kept whole: a second dot (Windows could keep `scan.jpg`), the user's upper case, no + // extension, and a dotfile. + for name in ["scan.jpg.psd", "my.photo.psd", "transparent.PNG", "Untitled", ".psd"] { + assert_eq!(dialog_file_name(name, true).as_deref(), Some(name)); + } + assert_eq!(dialog_file_name("", true), None); +} + +/// A name in another letter case reaches the same file where the file system ignores case +/// (Windows, and macOS by default), and only there. Two files with the same contents are two. +#[test] +fn same_file_follows_the_file_system() { + let dir = std::env::temp_dir().join(format!("photocraft-same-file-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (cat, dog, upper) = (dir.join("CAT.psd"), dir.join("dog.psd"), dir.join("CAT.PSD")); + std::fs::write(&cat, b"same").unwrap(); + std::fs::write(&dog, b"same").unwrap(); + assert!(same_file(&cat, &cat)); + assert!(!same_file(&cat, &dog)); + assert_eq!(same_file(&upper, &cat), upper.exists(), "the same file only where letter case is ignored"); + assert!(!same_file(&dir.join("missing.psd"), &cat)); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A hard link is another entry in the folder, though it reaches the same file: a save to it +/// replaces that entry and leaves the other name on the old file. Another spelling of a name, +/// where letter case is ignored, is the same entry. +#[test] +fn a_hard_link_is_another_entry() { + let dir = std::env::temp_dir().join(format!("photocraft-same-entry-{}", std::process::id())); + std::fs::create_dir_all(dir.join("other")).unwrap(); + let (cat, bare, upper, other) = (dir.join("CAT.psd"), dir.join("CAT"), dir.join("CAT.PSD"), dir.join("other").join("CAT.psd")); + std::fs::write(&cat, b"cat").unwrap(); + std::fs::hard_link(&cat, &bare).unwrap(); + std::fs::hard_link(&cat, &other).unwrap(); + // Where both names reach one file (one inode on Unix), the folder still lists both. + let one_file = |_: &Path, _: &Path| true; + assert!(!same_entry(&bare, &cat, one_file)); + assert!(!same_entry(&bare, &cat, same_file)); + assert!(!same_entry(&other, &cat, same_file), "another folder"); + assert!(same_entry(&cat, &cat, one_file)); + assert!(same_entry(&cat, &cat, same_file)); + if upper.exists() { + assert!(same_entry(&upper, &cat, same_file), "one entry where letter case is ignored"); + } else { + std::fs::hard_link(&cat, &upper).unwrap(); + assert!(!same_entry(&upper, &cat, same_file), "two entries where letter case tells names apart"); + } + assert!(!same_entry(&dir.join("missing.psd"), &cat, same_file)); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn block_on_waits_for_a_wake_from_another_thread() { + let (tx, rx) = std::sync::mpsc::channel::(); + let mut woken = false; + let ready = std::future::poll_fn(move |cx| { + if woken { + return std::task::Poll::Ready(7); + } + woken = true; + let _ = tx.send(cx.waker().clone()); + std::task::Poll::Pending + }); + let waker = std::thread::spawn(move || rx.recv().unwrap().wake()); + assert_eq!(block_on(ready), 7); + waker.join().unwrap(); +} + +const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; +const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; + +/// One app launch with crash recovery in `dir` (dropping it is the crash: background writes +/// already queued finish, nothing else runs). +fn launch(dir: &Path) -> PhotocraftApp { + let mut app = PhotocraftApp::new(Session::new(), recovery_services(Some(dir.to_path_buf()))); + let ctx = egui::Context::default(); + prefs_ui::tick(&mut app, &ctx); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while app.session.has_jobs() && std::time::Instant::now() < deadline { + photocraft_ui_egui::jobs_ui::tick(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(!app.session.has_jobs(), "recovery finished"); + app +} + +/// The first pixel of each open document, and whether it's unsaved. +fn open_docs(app: &PhotocraftApp) -> Vec<([f32; 4], bool)> { + app.session.documents().iter().map(|d| (photocraft_compose::flatten(&d.doc).px.first().copied().unwrap_or_default(), d.is_dirty())).collect() +} + +fn index_of(app: &PhotocraftApp, color: [f32; 4]) -> usize { + open_docs(app).iter().position(|(c, _)| *c == color).unwrap() +} + +fn new_doc(app: &mut PhotocraftApp, color: &str) { + app.run("file.new", json!({"width": 4, "height": 4})).unwrap(); + app.run("edit.fill", json!({"color": color})).unwrap(); +} + +fn autosave(app: &mut PhotocraftApp, ctx: &egui::Context) { + prefs_ui::autosave_now(app); + prefs_ui::tick(app, ctx); +} + +#[test] +fn recovered_documents_survive_a_second_crash_until_saved_or_closed() { + let dir = std::env::temp_dir().join(format!("photocraft-recovery-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let ctx = egui::Context::default(); + // Launch 1: two unsaved documents are autosaved, then the app crashes. + { + let mut app = launch(&dir); + new_doc(&mut app, "#ff0000"); + new_doc(&mut app, "#0000ff"); + autosave(&mut app, &ctx); + } + assert_eq!(list_recovery(&dir).len(), 2); + // Launch 2 recovers both and crashes again before its first autosave (#444). + { + let mut app = launch(&dir); + let mut docs = open_docs(&app); + docs.sort_by(|a, b| a.0[0].total_cmp(&b.0[0])); + assert_eq!(docs, [(BLUE, true), (RED, true)], "recovered and still unsaved"); + prefs_ui::tick(&mut app, &ctx); + } + assert_eq!(list_recovery(&dir).len(), 2, "recovering keeps the entries on disk"); + // Launch 3 has both again; autosaving unchanged documents adds nothing, a new document + // (whose id may repeat one from an earlier launch) gets an entry of its own. + { + let mut app = launch(&dir); + assert_eq!(app.session.documents().len(), 2); + autosave(&mut app, &ctx); + new_doc(&mut app, "#00ff00"); + autosave(&mut app, &ctx); + } + assert_eq!(list_recovery(&dir).len(), 3); + // Launch 4: closing and saving recovered documents removes their entries, no duplicates. + let mut app = launch(&dir); + assert_eq!(app.session.documents().len(), 3); + let red = index_of(&app, RED); + app.run("file.close", json!({"document": red})).unwrap(); + // Saving marks the revision saved (the file write itself is the save service's job). + assert!(app.session.set_active(index_of(&app, BLUE))); + let st = app.session.active_mut().unwrap(); + st.saved_revision = st.revision; + prefs_ui::tick(&mut app, &ctx); + let left = list_recovery(&dir); + assert_eq!(left.len(), 1); + assert_eq!(photocraft_compose::flatten(&photocraft_format::recover(&left[0]).unwrap()).px.first().copied(), Some(GREEN)); + let green = index_of(&app, GREEN); + app.run("file.close", json!({"document": green})).unwrap(); + prefs_ui::tick(&mut app, &ctx); + assert!(list_recovery(&dir).is_empty()); + drop(app); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn failed_background_autosave_is_reported_and_retried_without_another_edit() { + let dir = temp("autosave-retry"); + let recovery = dir.join("Recovery"); + // A regular file prevents creation of the recovery bundle directory. + std::fs::write(&recovery, b"blocked").unwrap(); + let ctx = egui::Context::default(); + let mut app = launch(&recovery); + new_doc(&mut app, "#ff0000"); + let revision = app.session.active().unwrap().revision; + assert_ne!(revision, 0, "a sidecar-less bundle lists as revision 0"); + autosave(&mut app, &ctx); + + let mut failed = false; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while std::time::Instant::now() < deadline { + prefs_ui::tick(&mut app, &ctx); + if app.ui.status.starts_with("Autosave failed:") { + failed = true; + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!(failed, "background write failures must reach the UI"); + assert!(app.ui.status_error); + assert!(list_recovery(&recovery).is_empty()); + + // No edit occurs: retrying this very same revision must still work. + std::fs::remove_file(&recovery).unwrap(); + std::fs::create_dir(&recovery).unwrap(); + autosave(&mut app, &ctx); + // The worker commits the bundle's manifest before it publishes the sidecar, and + // `list_recovery` lists a committed sidecar-less bundle (revision 0) on its own, so + // the first non-empty listing can come from the middle of the write. Wait for the write + // to finish: the entry then carries the sidecar's revision. + let mut recovered = Vec::new(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while std::time::Instant::now() < deadline { + prefs_ui::tick(&mut app, &ctx); + recovered = list_recovery(&recovery); + if recovered.iter().any(|e| e.info.revision == revision) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_eq!(recovered.len(), 1, "unchanged revision should retry after failure"); + assert_eq!(recovered[0].info.revision, revision); + let restored = photocraft_format::recover(&recovered[0]).unwrap(); + assert_eq!(photocraft_compose::flatten(&restored).px.first().copied(), Some(RED)); + drop(app); + std::fs::remove_dir_all(dir).unwrap(); +} + +use std::sync::atomic::{AtomicUsize, Ordering}; + +fn temp(tag: &str) -> PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let d = std::env::temp_dir().join(format!("photocraft-services-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn red_png(w: u32, h: u32) -> Vec { + let img = Image::from_u8(w, h, ChannelLayout::Rgba, [255u8, 0, 0, 255].repeat((w * h) as usize)).unwrap(); + photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).unwrap() +} + +/// A 1×1 uncompressed 32-bit TGA (TGA has no magic number). +fn tga_1x1() -> Vec { + let mut b = vec![0u8, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 32, 8]; + b.extend_from_slice(&[0, 0, 255, 255]); // BGRA red + b +} + +#[test] +fn copied_image_file_pastes_its_pixels() { + let dir = temp("png"); + let png = dir.join("red.png"); + std::fs::write(&png, red_png(3, 2)).unwrap(); + let (w, h, px) = image_from_files(&[png]).unwrap(); + assert_eq!((w, h), (3, 2)); + assert_eq!(px, [255u8, 0, 0, 255].repeat(6)); +} + +#[test] +fn crlf_from_a_uri_list_is_ignored() { + // arboard splits text/uri-list on LF, so GNOME Files' CRLF list leaves a '\r' behind. + let dir = temp("crlf"); + let png = dir.join("red image.png"); + std::fs::write(&png, red_png(2, 2)).unwrap(); + let with_cr = PathBuf::from(format!("{}\r", png.display())); + assert_eq!(image_from_files(&[with_cr]).map(|(w, h, _)| (w, h)), Some((2, 2))); +} + +#[test] +fn non_images_are_skipped_for_the_first_image() { + let dir = temp("mixed"); + let (txt, png) = (dir.join("notes.txt"), dir.join("red.png")); + std::fs::write(&txt, b"not an image").unwrap(); + std::fs::write(&png, red_png(4, 1)).unwrap(); + let missing = dir.join("gone.png"); + assert_eq!(image_from_files(&[missing.clone(), txt.clone(), dir.clone(), png]).map(|(w, h, _)| (w, h)), Some((4, 1))); + assert!(image_from_files(&[missing, txt, dir]).is_none()); + assert!(image_from_files(&[]).is_none()); +} + +#[test] +fn a_damaged_image_is_skipped_not_a_panic() { + let dir = temp("damaged"); + let bad = dir.join("cut.png"); + std::fs::write(&bad, &red_png(8, 8)[..20]).unwrap(); + assert!(image_from_files(&[bad]).is_none()); +} + +fn encoded(format: photocraft_codecs::Format, w: u32, h: u32) -> Vec { + let img = Image::from_u8(w, h, ChannelLayout::Rgba, [255u8, 0, 0, 255].repeat((w * h) as usize)).unwrap(); + photocraft_codecs::encode(&img, format, &EncodeOptions::default()).unwrap() +} + +#[test] +fn non_png_clipboard_images_paste() { + // #2546: a screenshot tool that offers only image/bmp or image/jpeg pasted nothing. + let bmp = encoded(photocraft_codecs::Format::Bmp, 3, 2); + let offers = vec!["text/plain".to_string(), "image/bmp".to_string()]; + let mut asked = Vec::new(); + let got = image_from_offers(&offers, |mime| { + asked.push(mime.to_string()); + Some(bmp.clone()) + }); + assert_eq!(got, Some((3, 2, [255u8, 0, 0, 255].repeat(6)))); + assert_eq!(asked, ["image/bmp"], "text offers are never fetched"); + + let jpeg = encoded(photocraft_codecs::Format::Jpeg, 16, 8); + let offers = vec!["image/jpeg".to_string()]; + assert_eq!(image_from_offers(&offers, |_| Some(jpeg.clone())).map(|(w, h, _)| (w, h)), Some((16, 8))); +} + +#[test] +fn undecodable_clipboard_offers_fall_through_to_the_next() { + let bmp = encoded(photocraft_codecs::Format::Bmp, 2, 2); + let cut = encoded(photocraft_codecs::Format::Png, 8, 8)[..20].to_vec(); + let offers: Vec = ["image/webp", "image/png", "image/x-tga", "image/bmp"].map(String::from).to_vec(); + let got = image_from_offers(&offers, |mime| match mime { + "image/webp" => None, + "image/png" => Some(cut.clone()), + "image/x-tga" => Some(b"not an image".to_vec()), + _ => Some(bmp.clone()), + }); + assert_eq!(got.map(|(w, h, _)| (w, h)), Some((2, 2))); + assert!(image_from_offers(&offers[..3], |_| Some(cut.clone())).is_none()); + assert!(image_from_offers(&[], |_| Some(bmp.clone())).is_none()); +} + +#[test] +fn clipboard_tga_is_trusted_only_by_its_type() { + assert_eq!(image_from_offers(&["image/x-tga".to_string()], |_| Some(tga_1x1())), Some((1, 1, vec![255, 0, 0, 255]))); + assert!(image_from_offers(&["image/x-unknown".to_string()], |_| Some(tga_1x1())).is_none()); +} + +#[test] +fn tga_is_trusted_only_with_its_extension() { + let dir = temp("tga"); + let (tga, bin) = (dir.join("red.tga"), dir.join("red.bin")); + std::fs::write(&tga, tga_1x1()).unwrap(); + std::fs::write(&bin, tga_1x1()).unwrap(); + assert_eq!(image_from_files(&[tga]), Some((1, 1, vec![255, 0, 0, 255]))); + assert!(image_from_files(&[bin]).is_none()); +} + +/// #7582: a panic while reading the OS clipboard (in arboard, or decoding a copied file) is +/// the paste's error in the status bar, not a crash: the document stays and the next paste +/// works. The same for a panic while writing it. +#[test] +fn a_panicking_clipboard_read_is_reported_not_a_crash() { + let panics = Rc::new(Cell::new(true)); + let p = panics.clone(); + let get = guarded_clipboard_get(move || if p.get() { panic!("clipboard decoder bug") } else { Ok(Some((2, 2, [0u8, 0, 255, 255].repeat(4)))) }); + let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(get), ..Default::default() }); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let layers = app.session.active().unwrap().doc.layers.len(); + + let error = app.run("edit.paste", json!({})).unwrap_err(); + assert!(error.contains("Paste failed"), "{error}"); + assert!(app.ui.status_error && app.ui.status.contains("Paste failed"), "{}", app.ui.status); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "the document is unchanged"); + + panics.set(false); + app.run("edit.paste", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1, "the next paste works"); + + let mut set = guarded_clipboard_set(|_: u32, _: u32, _: &[u8]| panic!("clipboard writer bug")); + assert!(set(1, 1, &[0; 4]).unwrap_err().contains("Copy failed")); +} From 844ba37a6523e30becdadd3e539005eaf458fb70 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:18:02 +0000 Subject: [PATCH 130/259] refactor(photocraft): move app_dirs.rs tests to app_dirs/tests.rs --- apps/photocraft/src/app_dirs.rs | 448 +------------------------- apps/photocraft/src/app_dirs/tests.rs | 445 +++++++++++++++++++++++++ 2 files changed, 446 insertions(+), 447 deletions(-) create mode 100644 apps/photocraft/src/app_dirs/tests.rs diff --git a/apps/photocraft/src/app_dirs.rs b/apps/photocraft/src/app_dirs.rs index a75520f3c4..ef1fa438c0 100644 --- a/apps/photocraft/src/app_dirs.rs +++ b/apps/photocraft/src/app_dirs.rs @@ -502,450 +502,4 @@ fn ensure_writable(dir: &Path) -> std::io::Result<()> { } #[cfg(test)] -mod tests { - use super::*; - use std::collections::HashMap; - use std::sync::atomic::{AtomicUsize, Ordering}; - - fn temp(tag: &str) -> PathBuf { - static N: AtomicUsize = AtomicUsize::new(0); - let d = std::env::temp_dir().join(format!("photocraft-app-dirs-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d - } - - fn env_of(pairs: &[(&str, &Path)]) -> impl Fn(&str) -> Option + use<> { - let m: HashMap = pairs.iter().map(|(k, v)| (k.to_string(), v.as_os_str().to_owned())).collect(); - move |k| m.get(k).cloned() - } - - /// A fake user folder that every platform's convention resolves under. - fn fake_home(root: &Path) -> impl Fn(&str) -> Option + use<> { - let home = root.join("home"); - let appdata = root.join("appdata"); - env_of(&[("HOME", &home), ("APPDATA", &appdata)]) - } - - #[test] - fn no_marker_uses_the_platform_dir() { - let root = temp("platform"); - let exe = root.join("bin"); - std::fs::create_dir_all(&exe).unwrap(); - let env = fake_home(&root); - let d = resolve(&env, Some(&exe)); - assert_eq!(d.mode, Mode::Platform); - assert!(d.warning.is_none()); - let dir = d.dir.unwrap(); - assert_eq!(Some(dir.clone()), platform_dir(&env)); - assert!(!dir.starts_with(&exe)); - assert!(!exe.join(PORTABLE_DATA_DIR).exists(), "no portable folder without a marker"); - // The convention per platform. - if cfg!(target_os = "macos") { - assert_eq!(dir, root.join("home/Library/Application Support/Photocraft")); - } else if cfg!(windows) { - assert_eq!(dir, root.join("appdata").join("Photocraft")); - } else { - assert_eq!(dir, root.join("home/.config/photocraft")); - } - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn either_marker_keeps_everything_beside_the_exe() { - for marker in PORTABLE_MARKERS { - let root = temp("portable"); - let exe = root.join("PhotoCraft"); - std::fs::create_dir_all(&exe).unwrap(); - std::fs::write(exe.join(marker), b"").unwrap(); - let d = resolve(fake_home(&root), Some(&exe)); - assert_eq!(d.mode, Mode::Portable, "{marker}"); - assert!(d.warning.is_none()); - let dir = d.dir.unwrap(); - assert_eq!(dir, exe.join(PORTABLE_DATA_DIR)); - assert!(dir.is_dir(), "the data folder is created"); - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "the write probe is removed"); - // Every derived path sits under the exe dir. - for sub in ["preferences.json", "Presets", "Recovery", crate::gpu_startup::MARKER_FILE] { - assert!(dir.join(sub).starts_with(&exe)); - } - assert!(!root.join("home").exists() && !root.join("appdata").exists(), "nothing written to the user folder"); - let _ = std::fs::remove_dir_all(&root); - } - } - - #[test] - fn a_marker_folder_is_not_a_marker() { - let root = temp("dir-marker"); - let exe = root.join("bin"); - std::fs::create_dir_all(exe.join("portable.txt")).unwrap(); - assert_eq!(resolve(fake_home(&root), Some(&exe)).mode, Mode::Platform); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn unwritable_portable_folder_falls_back_with_a_warning() { - let root = temp("unwritable"); - let exe = root.join("bin"); - std::fs::create_dir_all(&exe).unwrap(); - std::fs::write(exe.join("portable.txt"), b"").unwrap(); - // A file where the data folder should go: it can't be created, on every platform. - std::fs::write(exe.join(PORTABLE_DATA_DIR), b"in the way").unwrap(); - let env = fake_home(&root); - let d = resolve(&env, Some(&exe)); - assert_eq!(d.mode, Mode::Platform); - assert_eq!(d.dir, platform_dir(&env)); - let w = d.warning.unwrap(); - assert!(w.contains("portable") && w.contains("isn't writable"), "{w}"); - // No user folder at all: still no panic, just no directory. - let d = resolve(|_| None, Some(&exe)); - assert!(d.dir.is_none() && d.warning.is_some()); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn override_wins_over_portable() { - let root = temp("override"); - let exe = root.join("bin"); - std::fs::create_dir_all(&exe).unwrap(); - std::fs::write(exe.join("portable.txt"), b"").unwrap(); - let custom = root.join("custom"); - let d = resolve(env_of(&[("PHOTOCRAFT_CONFIG_DIR", &custom)]), Some(&exe)); - assert_eq!((d.mode, d.dir), (Mode::Override, Some(custom))); - assert!(!exe.join(PORTABLE_DATA_DIR).exists()); - let _ = std::fs::remove_dir_all(&root); - } - - /// #5648: on Windows, autosaves go to the machine-local `%LOCALAPPDATA%`, not the roaming - /// profile; an override or portable folder keeps them inside itself. - #[test] - fn autosaves_stay_out_of_the_roaming_profile() { - let root = temp("recovery-local"); - let settings = root.join("appdata").join("Photocraft"); - let local = root.join("local"); - let env = env_of(&[("LOCALAPPDATA", &local)]); - let platform = DataDir { dir: Some(settings.clone()), mode: Mode::Platform, warning: None }; - let expected = if cfg!(windows) { local.join("Photocraft").join("Recovery") } else { settings.join("Recovery") }; - assert_eq!(resolve_recovery(&platform, &env), Some(expected)); - for mode in [Mode::Override, Mode::Portable] { - let d = DataDir { dir: Some(settings.clone()), mode, warning: None }; - assert_eq!(resolve_recovery(&d, &env), Some(settings.join("Recovery")), "{mode:?}"); - } - // No (or an empty) LOCALAPPDATA: beside the settings, as before. - let empty = PathBuf::new(); - assert_eq!(resolve_recovery(&platform, env_of(&[("LOCALAPPDATA", &empty)])), Some(settings.join("Recovery"))); - assert_eq!(resolve_recovery(&platform, |_| None), Some(settings.join("Recovery"))); - let nowhere = DataDir { dir: None, mode: Mode::Platform, warning: None }; - assert_eq!(resolve_recovery(&nowhere, |_| None), None); - let _ = std::fs::remove_dir_all(&root); - } - - /// #6612: on Linux (and other XDG systems) autosaves go to `$XDG_STATE_HOME`, by default - /// `~/.local/state`, not the config folder; a relative `XDG_STATE_HOME` is ignored. Windows - /// and macOS don't read it, and an override or portable folder keeps them inside itself. - #[test] - fn autosaves_go_to_the_xdg_state_folder() { - let root = temp("recovery-xdg"); - let settings = root.join("home").join(".config").join("photocraft"); - let home = root.join("home"); - let state = root.join("state"); - let platform = DataDir { dir: Some(settings.clone()), mode: Mode::Platform, warning: None }; - let xdg = !cfg!(windows) && !cfg!(target_os = "macos"); - let expect = |xdg_path: PathBuf| Some(if xdg { xdg_path } else { settings.join("Recovery") }); - assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &state), ("HOME", &home)])), expect(state.join("photocraft").join("Recovery"))); - let default = home.join(".local").join("state").join("photocraft").join("Recovery"); - assert_eq!(resolve_recovery(&platform, env_of(&[("HOME", &home)])), expect(default.clone())); - let relative = PathBuf::from("relative/state"); - assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &relative), ("HOME", &home)])), expect(default.clone())); - let empty = PathBuf::new(); - assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &empty), ("HOME", &home)])), expect(default)); - // No home at all: beside the settings, as before. - assert_eq!(resolve_recovery(&platform, |_| None), Some(settings.join("Recovery"))); - for mode in [Mode::Override, Mode::Portable] { - let d = DataDir { dir: Some(settings.clone()), mode, warning: None }; - assert_eq!(resolve_recovery(&d, env_of(&[("XDG_STATE_HOME", &state), ("HOME", &home)])), Some(settings.join("Recovery")), "{mode:?}"); - } - let _ = std::fs::remove_dir_all(&root); - } - - /// An autosave bundle and its sidecar, as `format::Autosaver` writes them. - fn autosave(dir: &Path, key: &str) { - std::fs::create_dir_all(dir.join(format!("{key}.pcraft"))).unwrap(); - std::fs::write(dir.join(format!("{key}.pcraft")).join("manifest.json"), key).unwrap(); - std::fs::write(dir.join(format!("{key}.json")), key).unwrap(); - } - - #[test] - fn autosaves_from_the_old_folder_move_to_the_new_one() { - let root = temp("recovery-move"); - let legacy = root.join("roaming").join("Recovery"); - let dir = root.join("local").join("Photocraft").join("Recovery"); - autosave(&legacy, "a"); - assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir); - assert!(!legacy.exists(), "the old folder is gone"); - assert_eq!(std::fs::read_to_string(dir.join("a.pcraft").join("manifest.json")).unwrap(), "a"); - assert!(dir.join("a.json").is_file()); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn autosaves_merge_into_an_existing_folder_without_overwriting() { - let root = temp("recovery-merge"); - let legacy = root.join("roaming").join("Recovery"); - let dir = root.join("local").join("Recovery"); - autosave(&legacy, "old"); - autosave(&legacy, "both"); - // A temp file of an interrupted write moves along, for the recovery store's sweep. - let temp_file = ".old.json.4294967294-0.pcsave.tmp"; - std::fs::write(legacy.join(temp_file), b"partial").unwrap(); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("both.json"), "newer").unwrap(); - assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir); - assert!(dir.join(temp_file).is_file() && !legacy.join(temp_file).exists()); - assert!(dir.join("old.pcraft").is_dir() && dir.join("old.json").is_file(), "a whole autosave moves"); - assert_eq!(std::fs::read_to_string(dir.join("both.json")).unwrap(), "newer", "never overwritten"); - assert!(!dir.join("both.pcraft").exists(), "a clashing autosave isn't split"); - assert!(legacy.join("both.pcraft").is_dir() && legacy.join("both.json").is_file(), "it stays behind whole"); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn autosaves_that_cannot_move_keep_being_used_where_they_are() { - let root = temp("recovery-stuck"); - let legacy = root.join("roaming").join("Recovery"); - autosave(&legacy, "a"); - // A file where the new folder's parent should be: nothing can be created there. - std::fs::write(root.join("blocked"), b"in the way").unwrap(); - let dir = root.join("blocked").join("Recovery"); - assert_eq!(adopt_legacy_recovery(&legacy, &dir), legacy); - assert!(legacy.join("a.json").is_file(), "nothing lost"); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn an_empty_old_folder_is_removed_even_where_it_cannot_move() { - let root = temp("recovery-empty"); - let legacy = root.join("roaming").join("Recovery"); - std::fs::create_dir_all(&legacy).unwrap(); - std::fs::write(root.join("blocked"), b"in the way").unwrap(); - let dir = root.join("blocked").join("Recovery"); - assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir, "nothing to keep listed"); - assert!(!legacy.exists(), "the empty old folder is gone"); - let _ = std::fs::remove_dir_all(&root); - } - - /// Where a rename can't cross volumes (a roaming profile on a network share), an autosave - /// is copied whole, nested folders included, and only then removed. - #[test] - fn a_move_across_volumes_copies_then_removes() { - let root = temp("recovery-copy"); - let legacy = root.join("roaming").join("Recovery"); - autosave(&legacy, "a"); - std::fs::create_dir_all(legacy.join("a.pcraft").join("tiles")).unwrap(); - std::fs::write(legacy.join("a.pcraft").join("tiles").join("t0.zst"), b"tile").unwrap(); - let dir = root.join("local").join("Recovery"); - std::fs::create_dir_all(root.join("local")).unwrap(); - move_across(&legacy, &dir).unwrap(); - assert!(!legacy.exists(), "the original is removed after the copy"); - assert_eq!(side_leftovers(&root.join("roaming")), 0, "nothing is left held aside"); - assert_eq!(std::fs::read_to_string(dir.join("a.pcraft").join("manifest.json")).unwrap(), "a"); - assert_eq!(std::fs::read(dir.join("a.pcraft").join("tiles").join("t0.zst")).unwrap(), b"tile"); - assert_eq!(std::fs::read_to_string(dir.join("a.json")).unwrap(), "a"); - // One file on its own, as the per-autosave moves do. - move_across(&dir.join("a.json"), &root.join("a.json")).unwrap(); - assert!(!dir.join("a.json").exists() && root.join("a.json").is_file()); - assert_eq!(side_leftovers(&dir) + side_leftovers(&root), 0); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn a_failed_copy_puts_the_original_back_and_leaves_no_partial_copy() { - let root = temp("recovery-copy-fail"); - let legacy = root.join("Recovery"); - autosave(&legacy, "a"); - // Deeper than any bundle: the copy gives up part way. - let mut deep = legacy.join("a.pcraft"); - for _ in 0..=MAX_COPY_DEPTH { - deep = deep.join("d"); - } - std::fs::create_dir_all(&deep).unwrap(); - let dir = root.join("Local"); - assert!(move_across(&legacy, &dir).is_err()); - assert!(!dir.exists(), "nothing is published"); - assert_eq!(side_leftovers(&root), 0, "no staged copy, nothing left held aside"); - assert!(legacy.join("a.json").is_file() && deep.is_dir(), "the original is back in place"); - // A target that already exists is never copied into or removed. - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("keep"), b"mine").unwrap(); - assert!(move_across(&legacy.join("a.json"), &dir).is_err()); - assert_eq!(std::fs::read(dir.join("keep")).unwrap(), b"mine"); - assert!(legacy.join("a.json").is_file()); - assert_eq!(side_leftovers(&root) + side_leftovers(&legacy), 0); - let _ = std::fs::remove_dir_all(&root); - } - - /// Staged (`.moving`) and held (`.held`) side paths left in `dir`. - fn side_leftovers(dir: &Path) -> usize { - std::fs::read_dir(dir) - .unwrap() - .flatten() - .filter(|e| e.file_name().to_str().is_some_and(|n| side_of(n, STAGED).is_some() || side_of(n, HELD).is_some())) - .count() - } - - /// The target appears after the copy is staged (another process got there first): publishing - /// fails, that process's target keeps its contents, the staged copy is removed and the - /// original is left as it was. Folder and file alike. - #[test] - fn a_target_that_appears_while_copying_is_never_replaced_or_removed() { - let root = temp("recovery-race"); - let legacy = root.join("roaming").join("Recovery"); - autosave(&legacy, "a"); - let local = root.join("local"); - std::fs::create_dir_all(&local).unwrap(); - // A whole folder. - let dir = local.join("Recovery"); - let staged = stage_copy(&legacy, &dir).unwrap(); - autosave(&dir, "theirs"); - let e = publish(&staged, &dir).unwrap_err(); - assert_eq!(e.kind(), std::io::ErrorKind::AlreadyExists); - assert_eq!(std::fs::read_to_string(dir.join("theirs.json")).unwrap(), "theirs", "their folder is intact"); - assert!(!dir.join("a.json").exists(), "nothing was copied into it"); - assert!(!staged.exists() && side_leftovers(&local) == 0, "only the staged copy is removed"); - assert!(legacy.join("a.json").is_file(), "the original is untouched"); - // One file. - let to = dir.join("a.json"); - let staged = stage_copy(&legacy.join("a.json"), &to).unwrap(); - std::fs::write(&to, "theirs").unwrap(); - assert_eq!(publish(&staged, &to).unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); - assert_eq!(std::fs::read_to_string(&to).unwrap(), "theirs"); - assert!(!staged.exists() && legacy.join("a.json").is_file()); - let _ = std::fs::remove_dir_all(&root); - } - - /// A process holds the lock and is copying the old folder (held aside, copy staged) when a - /// second launch gives up waiting. The second launch must get the new folder, never the old - /// one, and what it writes there survives the first one finishing: the publish refuses the - /// now-existing folder and the original is put back, so both autosaves stay (#6412 review). - #[test] - fn a_launch_that_times_out_never_writes_where_a_move_removes() { - let _spawns = crate::no_child_spawns(); - let root = temp("recovery-timeout"); - let legacy = root.join("roaming").join("Recovery"); - autosave(&legacy, "old"); - let local = root.join("local"); - std::fs::create_dir_all(&local).unwrap(); - let dir = local.join("Recovery"); - // First process: takes the lock, sets the original aside and stages its copy, then pauses. - let first = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(local.join(MIGRATION_LOCK)).unwrap(); - first.lock().unwrap(); - let held = hold(&legacy).unwrap(); - let staged = stage_copy(&held, &dir).unwrap(); - // Second launch: times out and writes a newer autosave where it was told to. - let chosen = adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO); - assert_eq!(chosen, dir, "a launch that couldn't get the lock never uses the old folder"); - autosave(&chosen, "new"); - // First process resumes: publish, and on failure put the original back (as `move_across`). - assert_eq!(publish(&staged, &dir).unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); - put_back(&held, &legacy); - drop(first); - assert_eq!(std::fs::read_to_string(dir.join("new.json")).unwrap(), "new", "the newer autosave survives"); - assert_eq!(std::fs::read_to_string(legacy.join("old.json")).unwrap(), "old", "the old one is back in place"); - assert_eq!(side_leftovers(&local) + side_leftovers(&root.join("roaming")), 0); - // The next launch merges them. - assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); - assert!(dir.join("old.json").is_file() && dir.join("new.json").is_file() && !legacy.exists()); - let _ = std::fs::remove_dir_all(&root); - } - - /// A writer that still uses the old path while it is being copied (an older PhotoCraft) - /// starts a new folder there; the move removes only the original it held aside. - #[test] - fn a_write_to_the_old_path_during_a_copy_is_not_removed() { - let root = temp("recovery-old-writer"); - let legacy = root.join("roaming").join("Recovery"); - autosave(&legacy, "old"); - let local = root.join("local"); - std::fs::create_dir_all(&local).unwrap(); - let dir = local.join("Recovery"); - let held = hold(&legacy).unwrap(); - let staged = stage_copy(&held, &dir).unwrap(); - autosave(&legacy, "new"); - publish(&staged, &dir).unwrap(); - std::fs::remove_dir_all(&held).unwrap(); - assert_eq!(std::fs::read_to_string(dir.join("old.json")).unwrap(), "old"); - assert_eq!(std::fs::read_to_string(legacy.join("new.json")).unwrap(), "new", "the new write is untouched"); - let _ = std::fs::remove_dir_all(&root); - } - - /// What a process killed mid-move left is tidied at the next move: a held original is put - /// back (it may be the only copy) and moved, a staged copy is removed; other dot-files and - /// look-alike names are not touched. - #[test] - fn a_killed_move_is_tidied_next_time() { - let root = temp("recovery-stale"); - let roaming = root.join("roaming"); - let legacy = roaming.join("Recovery"); - autosave(&legacy, "a"); - let held = hold(&legacy).unwrap(); - assert!(!legacy.exists() && held.is_dir()); - let local = root.join("local"); - let dir = local.join("Recovery"); - let stale = local.join(".Recovery.4294967294-3.moving"); - autosave(&stale, "half"); - let kept = [local.join(".Recovery.moving"), local.join(".keep.1-x.moving"), local.join("notes.txt")]; - for k in &kept { - std::fs::write(k, b"x").unwrap(); - } - assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); - assert_eq!(std::fs::read_to_string(dir.join("a.json")).unwrap(), "a", "the held original was put back and moved"); - assert!(!stale.exists(), "the stale staged copy is gone"); - assert_eq!(side_leftovers(&roaming), 0); - assert!(kept.iter().all(|k| k.is_file()), "only side names are touched"); - assert_eq!(side_of(".a.json.12-0.moving", STAGED), Some("a.json")); - assert!(side_of("a.json.12-0.moving", STAGED).is_none() && side_of(".a.json.-0.moving", STAGED).is_none()); - assert!(side_of(".a.json.12-0.held", STAGED).is_none() && side_of(".a.json.12-0.held", HELD) == Some("a.json")); - let _ = std::fs::remove_dir_all(&root); - } - - /// While another process holds the move lock, a launch moves nothing and uses the new folder; - /// once the lock is released, the move happens. - #[test] - fn a_move_waits_for_another_process_holding_the_lock() { - let _spawns = crate::no_child_spawns(); - let root = temp("recovery-lock"); - let legacy = root.join("roaming").join("Recovery"); - autosave(&legacy, "a"); - let dir = root.join("local").join("Recovery"); - std::fs::create_dir_all(root.join("local")).unwrap(); - let held = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(root.join("local").join(MIGRATION_LOCK)).unwrap(); - held.lock().unwrap(); - assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); - assert!(legacy.join("a.json").is_file() && !dir.exists(), "nothing moved under another's lock"); - drop(held); - assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); - assert!(dir.join("a.json").is_file() && !legacy.exists()); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn no_old_folder_or_the_same_folder_changes_nothing() { - let root = temp("recovery-noop"); - let dir = root.join("Recovery"); - assert_eq!(adopt_legacy_recovery(&root.join("missing"), &dir), dir); - assert!(!dir.exists(), "nothing is created up front"); - autosave(&dir, "a"); - assert_eq!(adopt_legacy_recovery(&dir, &dir), dir); - assert!(dir.join("a.json").is_file()); - let _ = std::fs::remove_dir_all(&root); - } - - #[test] - fn missing_exe_dir_or_env_never_panics() { - let d = resolve(|_| None, None); - assert_eq!((d.mode, d.dir), (Mode::Platform, None)); - let empty = PathBuf::new(); - let d = resolve(env_of(&[("PHOTOCRAFT_CONFIG_DIR", &empty), ("HOME", &empty), ("APPDATA", &empty)]), None); - assert_eq!(d.dir, None, "empty variables are ignored"); - } -} +mod tests; diff --git a/apps/photocraft/src/app_dirs/tests.rs b/apps/photocraft/src/app_dirs/tests.rs new file mode 100644 index 0000000000..c54299fb58 --- /dev/null +++ b/apps/photocraft/src/app_dirs/tests.rs @@ -0,0 +1,445 @@ +use super::*; +use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; + +fn temp(tag: &str) -> PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let d = std::env::temp_dir().join(format!("photocraft-app-dirs-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn env_of(pairs: &[(&str, &Path)]) -> impl Fn(&str) -> Option + use<> { + let m: HashMap = pairs.iter().map(|(k, v)| (k.to_string(), v.as_os_str().to_owned())).collect(); + move |k| m.get(k).cloned() +} + +/// A fake user folder that every platform's convention resolves under. +fn fake_home(root: &Path) -> impl Fn(&str) -> Option + use<> { + let home = root.join("home"); + let appdata = root.join("appdata"); + env_of(&[("HOME", &home), ("APPDATA", &appdata)]) +} + +#[test] +fn no_marker_uses_the_platform_dir() { + let root = temp("platform"); + let exe = root.join("bin"); + std::fs::create_dir_all(&exe).unwrap(); + let env = fake_home(&root); + let d = resolve(&env, Some(&exe)); + assert_eq!(d.mode, Mode::Platform); + assert!(d.warning.is_none()); + let dir = d.dir.unwrap(); + assert_eq!(Some(dir.clone()), platform_dir(&env)); + assert!(!dir.starts_with(&exe)); + assert!(!exe.join(PORTABLE_DATA_DIR).exists(), "no portable folder without a marker"); + // The convention per platform. + if cfg!(target_os = "macos") { + assert_eq!(dir, root.join("home/Library/Application Support/Photocraft")); + } else if cfg!(windows) { + assert_eq!(dir, root.join("appdata").join("Photocraft")); + } else { + assert_eq!(dir, root.join("home/.config/photocraft")); + } + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn either_marker_keeps_everything_beside_the_exe() { + for marker in PORTABLE_MARKERS { + let root = temp("portable"); + let exe = root.join("PhotoCraft"); + std::fs::create_dir_all(&exe).unwrap(); + std::fs::write(exe.join(marker), b"").unwrap(); + let d = resolve(fake_home(&root), Some(&exe)); + assert_eq!(d.mode, Mode::Portable, "{marker}"); + assert!(d.warning.is_none()); + let dir = d.dir.unwrap(); + assert_eq!(dir, exe.join(PORTABLE_DATA_DIR)); + assert!(dir.is_dir(), "the data folder is created"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "the write probe is removed"); + // Every derived path sits under the exe dir. + for sub in ["preferences.json", "Presets", "Recovery", crate::gpu_startup::MARKER_FILE] { + assert!(dir.join(sub).starts_with(&exe)); + } + assert!(!root.join("home").exists() && !root.join("appdata").exists(), "nothing written to the user folder"); + let _ = std::fs::remove_dir_all(&root); + } +} + +#[test] +fn a_marker_folder_is_not_a_marker() { + let root = temp("dir-marker"); + let exe = root.join("bin"); + std::fs::create_dir_all(exe.join("portable.txt")).unwrap(); + assert_eq!(resolve(fake_home(&root), Some(&exe)).mode, Mode::Platform); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn unwritable_portable_folder_falls_back_with_a_warning() { + let root = temp("unwritable"); + let exe = root.join("bin"); + std::fs::create_dir_all(&exe).unwrap(); + std::fs::write(exe.join("portable.txt"), b"").unwrap(); + // A file where the data folder should go: it can't be created, on every platform. + std::fs::write(exe.join(PORTABLE_DATA_DIR), b"in the way").unwrap(); + let env = fake_home(&root); + let d = resolve(&env, Some(&exe)); + assert_eq!(d.mode, Mode::Platform); + assert_eq!(d.dir, platform_dir(&env)); + let w = d.warning.unwrap(); + assert!(w.contains("portable") && w.contains("isn't writable"), "{w}"); + // No user folder at all: still no panic, just no directory. + let d = resolve(|_| None, Some(&exe)); + assert!(d.dir.is_none() && d.warning.is_some()); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn override_wins_over_portable() { + let root = temp("override"); + let exe = root.join("bin"); + std::fs::create_dir_all(&exe).unwrap(); + std::fs::write(exe.join("portable.txt"), b"").unwrap(); + let custom = root.join("custom"); + let d = resolve(env_of(&[("PHOTOCRAFT_CONFIG_DIR", &custom)]), Some(&exe)); + assert_eq!((d.mode, d.dir), (Mode::Override, Some(custom))); + assert!(!exe.join(PORTABLE_DATA_DIR).exists()); + let _ = std::fs::remove_dir_all(&root); +} + +/// #5648: on Windows, autosaves go to the machine-local `%LOCALAPPDATA%`, not the roaming +/// profile; an override or portable folder keeps them inside itself. +#[test] +fn autosaves_stay_out_of_the_roaming_profile() { + let root = temp("recovery-local"); + let settings = root.join("appdata").join("Photocraft"); + let local = root.join("local"); + let env = env_of(&[("LOCALAPPDATA", &local)]); + let platform = DataDir { dir: Some(settings.clone()), mode: Mode::Platform, warning: None }; + let expected = if cfg!(windows) { local.join("Photocraft").join("Recovery") } else { settings.join("Recovery") }; + assert_eq!(resolve_recovery(&platform, &env), Some(expected)); + for mode in [Mode::Override, Mode::Portable] { + let d = DataDir { dir: Some(settings.clone()), mode, warning: None }; + assert_eq!(resolve_recovery(&d, &env), Some(settings.join("Recovery")), "{mode:?}"); + } + // No (or an empty) LOCALAPPDATA: beside the settings, as before. + let empty = PathBuf::new(); + assert_eq!(resolve_recovery(&platform, env_of(&[("LOCALAPPDATA", &empty)])), Some(settings.join("Recovery"))); + assert_eq!(resolve_recovery(&platform, |_| None), Some(settings.join("Recovery"))); + let nowhere = DataDir { dir: None, mode: Mode::Platform, warning: None }; + assert_eq!(resolve_recovery(&nowhere, |_| None), None); + let _ = std::fs::remove_dir_all(&root); +} + +/// #6612: on Linux (and other XDG systems) autosaves go to `$XDG_STATE_HOME`, by default +/// `~/.local/state`, not the config folder; a relative `XDG_STATE_HOME` is ignored. Windows +/// and macOS don't read it, and an override or portable folder keeps them inside itself. +#[test] +fn autosaves_go_to_the_xdg_state_folder() { + let root = temp("recovery-xdg"); + let settings = root.join("home").join(".config").join("photocraft"); + let home = root.join("home"); + let state = root.join("state"); + let platform = DataDir { dir: Some(settings.clone()), mode: Mode::Platform, warning: None }; + let xdg = !cfg!(windows) && !cfg!(target_os = "macos"); + let expect = |xdg_path: PathBuf| Some(if xdg { xdg_path } else { settings.join("Recovery") }); + assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &state), ("HOME", &home)])), expect(state.join("photocraft").join("Recovery"))); + let default = home.join(".local").join("state").join("photocraft").join("Recovery"); + assert_eq!(resolve_recovery(&platform, env_of(&[("HOME", &home)])), expect(default.clone())); + let relative = PathBuf::from("relative/state"); + assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &relative), ("HOME", &home)])), expect(default.clone())); + let empty = PathBuf::new(); + assert_eq!(resolve_recovery(&platform, env_of(&[("XDG_STATE_HOME", &empty), ("HOME", &home)])), expect(default)); + // No home at all: beside the settings, as before. + assert_eq!(resolve_recovery(&platform, |_| None), Some(settings.join("Recovery"))); + for mode in [Mode::Override, Mode::Portable] { + let d = DataDir { dir: Some(settings.clone()), mode, warning: None }; + assert_eq!(resolve_recovery(&d, env_of(&[("XDG_STATE_HOME", &state), ("HOME", &home)])), Some(settings.join("Recovery")), "{mode:?}"); + } + let _ = std::fs::remove_dir_all(&root); +} + +/// An autosave bundle and its sidecar, as `format::Autosaver` writes them. +fn autosave(dir: &Path, key: &str) { + std::fs::create_dir_all(dir.join(format!("{key}.pcraft"))).unwrap(); + std::fs::write(dir.join(format!("{key}.pcraft")).join("manifest.json"), key).unwrap(); + std::fs::write(dir.join(format!("{key}.json")), key).unwrap(); +} + +#[test] +fn autosaves_from_the_old_folder_move_to_the_new_one() { + let root = temp("recovery-move"); + let legacy = root.join("roaming").join("Recovery"); + let dir = root.join("local").join("Photocraft").join("Recovery"); + autosave(&legacy, "a"); + assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir); + assert!(!legacy.exists(), "the old folder is gone"); + assert_eq!(std::fs::read_to_string(dir.join("a.pcraft").join("manifest.json")).unwrap(), "a"); + assert!(dir.join("a.json").is_file()); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn autosaves_merge_into_an_existing_folder_without_overwriting() { + let root = temp("recovery-merge"); + let legacy = root.join("roaming").join("Recovery"); + let dir = root.join("local").join("Recovery"); + autosave(&legacy, "old"); + autosave(&legacy, "both"); + // A temp file of an interrupted write moves along, for the recovery store's sweep. + let temp_file = ".old.json.4294967294-0.pcsave.tmp"; + std::fs::write(legacy.join(temp_file), b"partial").unwrap(); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("both.json"), "newer").unwrap(); + assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir); + assert!(dir.join(temp_file).is_file() && !legacy.join(temp_file).exists()); + assert!(dir.join("old.pcraft").is_dir() && dir.join("old.json").is_file(), "a whole autosave moves"); + assert_eq!(std::fs::read_to_string(dir.join("both.json")).unwrap(), "newer", "never overwritten"); + assert!(!dir.join("both.pcraft").exists(), "a clashing autosave isn't split"); + assert!(legacy.join("both.pcraft").is_dir() && legacy.join("both.json").is_file(), "it stays behind whole"); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn autosaves_that_cannot_move_keep_being_used_where_they_are() { + let root = temp("recovery-stuck"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "a"); + // A file where the new folder's parent should be: nothing can be created there. + std::fs::write(root.join("blocked"), b"in the way").unwrap(); + let dir = root.join("blocked").join("Recovery"); + assert_eq!(adopt_legacy_recovery(&legacy, &dir), legacy); + assert!(legacy.join("a.json").is_file(), "nothing lost"); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn an_empty_old_folder_is_removed_even_where_it_cannot_move() { + let root = temp("recovery-empty"); + let legacy = root.join("roaming").join("Recovery"); + std::fs::create_dir_all(&legacy).unwrap(); + std::fs::write(root.join("blocked"), b"in the way").unwrap(); + let dir = root.join("blocked").join("Recovery"); + assert_eq!(adopt_legacy_recovery(&legacy, &dir), dir, "nothing to keep listed"); + assert!(!legacy.exists(), "the empty old folder is gone"); + let _ = std::fs::remove_dir_all(&root); +} + +/// Where a rename can't cross volumes (a roaming profile on a network share), an autosave +/// is copied whole, nested folders included, and only then removed. +#[test] +fn a_move_across_volumes_copies_then_removes() { + let root = temp("recovery-copy"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "a"); + std::fs::create_dir_all(legacy.join("a.pcraft").join("tiles")).unwrap(); + std::fs::write(legacy.join("a.pcraft").join("tiles").join("t0.zst"), b"tile").unwrap(); + let dir = root.join("local").join("Recovery"); + std::fs::create_dir_all(root.join("local")).unwrap(); + move_across(&legacy, &dir).unwrap(); + assert!(!legacy.exists(), "the original is removed after the copy"); + assert_eq!(side_leftovers(&root.join("roaming")), 0, "nothing is left held aside"); + assert_eq!(std::fs::read_to_string(dir.join("a.pcraft").join("manifest.json")).unwrap(), "a"); + assert_eq!(std::fs::read(dir.join("a.pcraft").join("tiles").join("t0.zst")).unwrap(), b"tile"); + assert_eq!(std::fs::read_to_string(dir.join("a.json")).unwrap(), "a"); + // One file on its own, as the per-autosave moves do. + move_across(&dir.join("a.json"), &root.join("a.json")).unwrap(); + assert!(!dir.join("a.json").exists() && root.join("a.json").is_file()); + assert_eq!(side_leftovers(&dir) + side_leftovers(&root), 0); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn a_failed_copy_puts_the_original_back_and_leaves_no_partial_copy() { + let root = temp("recovery-copy-fail"); + let legacy = root.join("Recovery"); + autosave(&legacy, "a"); + // Deeper than any bundle: the copy gives up part way. + let mut deep = legacy.join("a.pcraft"); + for _ in 0..=MAX_COPY_DEPTH { + deep = deep.join("d"); + } + std::fs::create_dir_all(&deep).unwrap(); + let dir = root.join("Local"); + assert!(move_across(&legacy, &dir).is_err()); + assert!(!dir.exists(), "nothing is published"); + assert_eq!(side_leftovers(&root), 0, "no staged copy, nothing left held aside"); + assert!(legacy.join("a.json").is_file() && deep.is_dir(), "the original is back in place"); + // A target that already exists is never copied into or removed. + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("keep"), b"mine").unwrap(); + assert!(move_across(&legacy.join("a.json"), &dir).is_err()); + assert_eq!(std::fs::read(dir.join("keep")).unwrap(), b"mine"); + assert!(legacy.join("a.json").is_file()); + assert_eq!(side_leftovers(&root) + side_leftovers(&legacy), 0); + let _ = std::fs::remove_dir_all(&root); +} + +/// Staged (`.moving`) and held (`.held`) side paths left in `dir`. +fn side_leftovers(dir: &Path) -> usize { + std::fs::read_dir(dir) + .unwrap() + .flatten() + .filter(|e| e.file_name().to_str().is_some_and(|n| side_of(n, STAGED).is_some() || side_of(n, HELD).is_some())) + .count() +} + +/// The target appears after the copy is staged (another process got there first): publishing +/// fails, that process's target keeps its contents, the staged copy is removed and the +/// original is left as it was. Folder and file alike. +#[test] +fn a_target_that_appears_while_copying_is_never_replaced_or_removed() { + let root = temp("recovery-race"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "a"); + let local = root.join("local"); + std::fs::create_dir_all(&local).unwrap(); + // A whole folder. + let dir = local.join("Recovery"); + let staged = stage_copy(&legacy, &dir).unwrap(); + autosave(&dir, "theirs"); + let e = publish(&staged, &dir).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read_to_string(dir.join("theirs.json")).unwrap(), "theirs", "their folder is intact"); + assert!(!dir.join("a.json").exists(), "nothing was copied into it"); + assert!(!staged.exists() && side_leftovers(&local) == 0, "only the staged copy is removed"); + assert!(legacy.join("a.json").is_file(), "the original is untouched"); + // One file. + let to = dir.join("a.json"); + let staged = stage_copy(&legacy.join("a.json"), &to).unwrap(); + std::fs::write(&to, "theirs").unwrap(); + assert_eq!(publish(&staged, &to).unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read_to_string(&to).unwrap(), "theirs"); + assert!(!staged.exists() && legacy.join("a.json").is_file()); + let _ = std::fs::remove_dir_all(&root); +} + +/// A process holds the lock and is copying the old folder (held aside, copy staged) when a +/// second launch gives up waiting. The second launch must get the new folder, never the old +/// one, and what it writes there survives the first one finishing: the publish refuses the +/// now-existing folder and the original is put back, so both autosaves stay (#6412 review). +#[test] +fn a_launch_that_times_out_never_writes_where_a_move_removes() { + let _spawns = crate::no_child_spawns(); + let root = temp("recovery-timeout"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "old"); + let local = root.join("local"); + std::fs::create_dir_all(&local).unwrap(); + let dir = local.join("Recovery"); + // First process: takes the lock, sets the original aside and stages its copy, then pauses. + let first = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(local.join(MIGRATION_LOCK)).unwrap(); + first.lock().unwrap(); + let held = hold(&legacy).unwrap(); + let staged = stage_copy(&held, &dir).unwrap(); + // Second launch: times out and writes a newer autosave where it was told to. + let chosen = adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO); + assert_eq!(chosen, dir, "a launch that couldn't get the lock never uses the old folder"); + autosave(&chosen, "new"); + // First process resumes: publish, and on failure put the original back (as `move_across`). + assert_eq!(publish(&staged, &dir).unwrap_err().kind(), std::io::ErrorKind::AlreadyExists); + put_back(&held, &legacy); + drop(first); + assert_eq!(std::fs::read_to_string(dir.join("new.json")).unwrap(), "new", "the newer autosave survives"); + assert_eq!(std::fs::read_to_string(legacy.join("old.json")).unwrap(), "old", "the old one is back in place"); + assert_eq!(side_leftovers(&local) + side_leftovers(&root.join("roaming")), 0); + // The next launch merges them. + assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); + assert!(dir.join("old.json").is_file() && dir.join("new.json").is_file() && !legacy.exists()); + let _ = std::fs::remove_dir_all(&root); +} + +/// A writer that still uses the old path while it is being copied (an older PhotoCraft) +/// starts a new folder there; the move removes only the original it held aside. +#[test] +fn a_write_to_the_old_path_during_a_copy_is_not_removed() { + let root = temp("recovery-old-writer"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "old"); + let local = root.join("local"); + std::fs::create_dir_all(&local).unwrap(); + let dir = local.join("Recovery"); + let held = hold(&legacy).unwrap(); + let staged = stage_copy(&held, &dir).unwrap(); + autosave(&legacy, "new"); + publish(&staged, &dir).unwrap(); + std::fs::remove_dir_all(&held).unwrap(); + assert_eq!(std::fs::read_to_string(dir.join("old.json")).unwrap(), "old"); + assert_eq!(std::fs::read_to_string(legacy.join("new.json")).unwrap(), "new", "the new write is untouched"); + let _ = std::fs::remove_dir_all(&root); +} + +/// What a process killed mid-move left is tidied at the next move: a held original is put +/// back (it may be the only copy) and moved, a staged copy is removed; other dot-files and +/// look-alike names are not touched. +#[test] +fn a_killed_move_is_tidied_next_time() { + let root = temp("recovery-stale"); + let roaming = root.join("roaming"); + let legacy = roaming.join("Recovery"); + autosave(&legacy, "a"); + let held = hold(&legacy).unwrap(); + assert!(!legacy.exists() && held.is_dir()); + let local = root.join("local"); + let dir = local.join("Recovery"); + let stale = local.join(".Recovery.4294967294-3.moving"); + autosave(&stale, "half"); + let kept = [local.join(".Recovery.moving"), local.join(".keep.1-x.moving"), local.join("notes.txt")]; + for k in &kept { + std::fs::write(k, b"x").unwrap(); + } + assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); + assert_eq!(std::fs::read_to_string(dir.join("a.json")).unwrap(), "a", "the held original was put back and moved"); + assert!(!stale.exists(), "the stale staged copy is gone"); + assert_eq!(side_leftovers(&roaming), 0); + assert!(kept.iter().all(|k| k.is_file()), "only side names are touched"); + assert_eq!(side_of(".a.json.12-0.moving", STAGED), Some("a.json")); + assert!(side_of("a.json.12-0.moving", STAGED).is_none() && side_of(".a.json.-0.moving", STAGED).is_none()); + assert!(side_of(".a.json.12-0.held", STAGED).is_none() && side_of(".a.json.12-0.held", HELD) == Some("a.json")); + let _ = std::fs::remove_dir_all(&root); +} + +/// While another process holds the move lock, a launch moves nothing and uses the new folder; +/// once the lock is released, the move happens. +#[test] +fn a_move_waits_for_another_process_holding_the_lock() { + let _spawns = crate::no_child_spawns(); + let root = temp("recovery-lock"); + let legacy = root.join("roaming").join("Recovery"); + autosave(&legacy, "a"); + let dir = root.join("local").join("Recovery"); + std::fs::create_dir_all(root.join("local")).unwrap(); + let held = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(root.join("local").join(MIGRATION_LOCK)).unwrap(); + held.lock().unwrap(); + assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); + assert!(legacy.join("a.json").is_file() && !dir.exists(), "nothing moved under another's lock"); + drop(held); + assert_eq!(adopt_legacy_recovery_waiting(&legacy, &dir, std::time::Duration::ZERO), dir); + assert!(dir.join("a.json").is_file() && !legacy.exists()); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn no_old_folder_or_the_same_folder_changes_nothing() { + let root = temp("recovery-noop"); + let dir = root.join("Recovery"); + assert_eq!(adopt_legacy_recovery(&root.join("missing"), &dir), dir); + assert!(!dir.exists(), "nothing is created up front"); + autosave(&dir, "a"); + assert_eq!(adopt_legacy_recovery(&dir, &dir), dir); + assert!(dir.join("a.json").is_file()); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn missing_exe_dir_or_env_never_panics() { + let d = resolve(|_| None, None); + assert_eq!((d.mode, d.dir), (Mode::Platform, None)); + let empty = PathBuf::new(); + let d = resolve(env_of(&[("PHOTOCRAFT_CONFIG_DIR", &empty), ("HOME", &empty), ("APPDATA", &empty)]), None); + assert_eq!(d.dir, None, "empty variables are ignored"); +} From 32b2cb5aea55f0c965baf2212cb2ed498e93f3fd Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:18:02 +0000 Subject: [PATCH 131/259] refactor(photocraft): move single_instance.rs tests to single_instance/tests.rs --- apps/photocraft/src/single_instance.rs | 376 +------------------ apps/photocraft/src/single_instance/tests.rs | 367 ++++++++++++++++++ 2 files changed, 368 insertions(+), 375 deletions(-) create mode 100644 apps/photocraft/src/single_instance/tests.rs diff --git a/apps/photocraft/src/single_instance.rs b/apps/photocraft/src/single_instance.rs index b193cade68..4d836adc90 100644 --- a/apps/photocraft/src/single_instance.rs +++ b/apps/photocraft/src/single_instance.rs @@ -627,378 +627,4 @@ pub fn absolute(path: &str) -> String { } #[cfg(test)] -mod tests { - use super::*; - use std::path::PathBuf; - use std::sync::mpsc::channel; - - const FAST: Timing = Timing { handoff: Duration::from_millis(1500), ack: Duration::from_millis(500), request: Duration::from_millis(800) }; - - fn temp_dir(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("photocraft-single-instance-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - dir - } - - /// Launch with `paths` on another thread (it blocks until the primary's UI takes them). - fn launch(dir: &Path, paths: &[&str], timing: Timing) -> std::thread::JoinHandle { - let (dir, paths): (PathBuf, Vec) = (dir.to_path_buf(), paths.iter().map(|p| p.to_string()).collect()); - std::thread::spawn(move || claim_with(&dir, &paths, timing)) - } - - /// Play the UI: drain until `n` events arrived (or 5 s passed). - fn drain(ui: &mut OsEventsFn, n: usize) -> Vec { - let mut got = Vec::new(); - let deadline = Instant::now() + Duration::from_secs(5); - while got.len() < n && Instant::now() < deadline { - got.extend(ui()); - std::thread::sleep(Duration::from_millis(10)); - } - got - } - - fn primary(dir: &Path) -> Primary { - match claim_with(dir, &[], FAST) { - Launch::Primary(p) => p, - _ => panic!("first launch should be primary"), - } - } - - /// A socket path short enough for every Unix (`sun_path` is about 100 bytes; macOS: 104). - #[cfg(unix)] - fn short_socket_path(tag: &str) -> PathBuf { - std::env::temp_dir().join(format!("pc-si-{}-{tag}", std::process::id())).join(SOCKET_FILE) - } - - /// The loopback port the primary under `dir` listens on. - fn port_of(dir: &Path) -> u16 { - match read_info(dir).unwrap().0 { - Endpoint::Port(port) => port, - #[cfg(unix)] - Endpoint::Socket(path) => panic!("expected a loopback port, found {}", path.display()), - } - } - - #[test] - fn second_launch_hands_its_paths_to_the_first() { - let dir = temp_dir("handoff"); - let primary = primary(&dir); - let mut ui = primary.connect(&egui::Context::default()); - let paths = ["C:\\art\\one.psd", "/home/a/two é.png"]; - let second = launch(&dir, &paths, TIMING); - assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(paths.iter().map(|p| p.to_string()).collect())]); - assert!(matches!(second.join().unwrap(), Launch::Forwarded)); - // A plain second start (no files) just brings the window forward. - let third = launch(&dir, &[], TIMING); - assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(Vec::new())]); - assert!(matches!(third.join().unwrap(), Launch::Forwarded)); - drop(primary); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn simultaneous_launches_all_land_in_one_instance() { - let dir = temp_dir("race"); - let (tx, rx) = channel(); - for i in 0..6 { - let (dir, tx) = (dir.clone(), tx.clone()); - std::thread::spawn(move || { - let _ = tx.send(claim(&dir, &[format!("file{i}.psd")])); - }); - } - drop(tx); - let (mut primaries, mut forwarded, mut events) = (Vec::new(), 0, Vec::new()); - let mut ui: Option = None; - let deadline = Instant::now() + Duration::from_secs(10); - while primaries.len() + forwarded < 6 && Instant::now() < deadline { - while let Ok(launch) = rx.try_recv() { - match launch { - Launch::Primary(p) => primaries.push(p), - Launch::Forwarded => forwarded += 1, - Launch::Standalone(reason) => panic!("standalone: {reason}"), - } - } - if ui.is_none() - && let Some(p) = primaries.first() - { - ui = Some(p.connect(&egui::Context::default())); - } - if let Some(ui) = ui.as_mut() { - events.extend(ui()); - } - std::thread::sleep(Duration::from_millis(10)); - } - assert_eq!((primaries.len(), forwarded, events.len()), (1, 5, 5)); - drop(primaries); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn a_crashed_instance_leaves_nothing_in_the_way() { - let dir = temp_dir("stale"); - std::fs::create_dir_all(&dir).unwrap(); - // instance.json from a process that is gone; the lock is free. - std::fs::write(dir.join(INFO_FILE), r#"{"port":1,"token":"x","pid":1}"#).unwrap(); - let primary = primary(&dir); - assert!(read_info(&dir).is_some_and(|(endpoint, _)| endpoint != Endpoint::Port(1))); - drop(primary); - // Released with the handle, as on process exit. - assert!(matches!(claim_with(&dir, &[], FAST), Launch::Primary(_))); - let _ = std::fs::remove_dir_all(&dir); - } - - /// Review of #3755, point 1 (and the quitting half of point 3): a launch waiting on a primary - /// that shuts down (closing, or about to relaunch itself in CPU mode) isn't told `ok`; it takes - /// the lock over and opens the file itself. - #[test] - fn a_launch_waiting_on_a_closing_instance_takes_over() { - let dir = temp_dir("closing"); - let primary = primary(&dir); - // The UI never drains (it is shutting down, or never came up). - let waiting = launch(&dir, &["a.psd"], FAST); - std::thread::sleep(Duration::from_millis(200)); - primary.shutdown(); - assert!(matches!(waiting.join().unwrap(), Launch::Primary(_)), "the waiting launch becomes the primary"); - // After shutdown new connections are refused too. - let (endpoint, token) = read_info(&dir).unwrap(); - drop(primary); - let short = Instant::now() + Duration::from_millis(300); - assert!(send(&endpoint, &token, &["b.psd".into()], short).is_err()); - let _ = std::fs::remove_dir_all(&dir); - } - - /// Review of #3755, point 3: a primary whose UI never takes the paths (hung) doesn't - /// acknowledge them, and doesn't keep them queued to open later as well. - #[test] - fn a_hung_instance_never_swallows_a_file() { - let dir = temp_dir("hung-ui"); - let primary = primary(&dir); - let mut ui = primary.connect(&egui::Context::default()); - let started = Instant::now(); - assert!(matches!(claim_with(&dir, &["a.psd".into()], FAST), Launch::Standalone(_))); - assert!(started.elapsed() < FAST.handoff + Duration::from_secs(1), "{:?}", started.elapsed()); - assert!(ui().is_empty(), "withdrawn, not opened later"); - drop(primary); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn requests_without_the_token_or_malformed_are_rejected() { - let token = generate_token().unwrap(); - let ok = parse_request(&json!({"token": token, "open": ["a"], "wait_ms": 250}).to_string(), &token); - assert_eq!(ok, Some((vec!["a".to_string()], Duration::from_millis(250)))); - let wrong = generate_token().unwrap(); - assert_eq!(parse_request(&json!({"token": wrong, "open": ["a"]}).to_string(), &token), None); - for bad in ["", "not json", "{}", r#"{"token":5}"#, &json!({"token": token}).to_string(), &json!({"token": token, "open": [1]}).to_string()] { - assert_eq!(parse_request(bad, &token), None, "{bad:?}"); - } - let many: Vec = (0..=MAX_PATHS).map(|i| i.to_string()).collect(); - assert_eq!(parse_request(&json!({"token": token, "open": many}).to_string(), &token), None); - } - - #[test] - fn a_stalled_client_does_not_hold_up_the_next_launch() { - let dir = temp_dir("stalled"); - let primary = primary(&dir); - let mut ui = primary.connect(&egui::Context::default()); - let port = port_of(&dir); - // Connects and never sends a line (each would otherwise hold the listener). - let stalled: Vec = (0..3).map(|_| TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap()).collect(); - let started = Instant::now(); - let next = launch(&dir, &["b.psd"], FAST); - assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(vec!["b.psd".into()])]); - assert!(matches!(next.join().unwrap(), Launch::Forwarded)); - assert!(started.elapsed() < FAST.request, "took {:?}", started.elapsed()); - drop(stalled); - drop(primary); - let _ = std::fs::remove_dir_all(&dir); - } - - /// A client that trickles a byte at a time can't keep its slot past the request deadline. - #[test] - fn a_trickling_client_is_cut_off_at_the_request_deadline() { - let dir = temp_dir("trickle"); - let primary = primary(&dir); - let port = port_of(&dir); - let mut slow = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap(); - let started = Instant::now(); - let mut cut_off = false; - while started.elapsed() < FAST.request * 4 { - if slow.write_all(b"{").is_err() { - cut_off = true; - break; - } - std::thread::sleep(Duration::from_millis(100)); - } - assert!(cut_off, "still connected after {:?}", started.elapsed()); - assert!(started.elapsed() < FAST.request * 3, "{:?}", started.elapsed()); - drop(primary); - let _ = std::fs::remove_dir_all(&dir); - } - - #[cfg(unix)] - #[test] - fn the_token_file_is_private_to_the_user() { - use std::os::unix::fs::PermissionsExt; - let dir = temp_dir("mode"); - std::fs::create_dir_all(&dir).unwrap(); - // A wide leftover temporary file from a crashed start doesn't widen the new one. - let tmp = dir.join(format!("{INFO_FILE}.{}.tmp", std::process::id())); - std::fs::write(&tmp, "{}").unwrap(); - std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o644)).unwrap(); - write_info(&dir, &Endpoint::Port(1), &generate_token().unwrap()).unwrap(); - let mode = std::fs::metadata(dir.join(INFO_FILE)).unwrap().permissions().mode() & 0o777; - assert_eq!(mode, 0o600); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn an_unreachable_instance_falls_back_to_a_standalone_launch() { - let dir = temp_dir("unreachable"); - std::fs::create_dir_all(&dir).unwrap(); - // Someone holds the lock but nothing listens on the advertised port. - let held = File::create(dir.join(LOCK_FILE)).unwrap(); - held.lock().unwrap(); - let closed = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap().local_addr().unwrap().port(); - write_info(&dir, &Endpoint::Port(closed), &generate_token().unwrap()).unwrap(); - assert!(matches!(claim_with(&dir, &["a.psd".into()], FAST), Launch::Standalone(_))); - drop(held); - let _ = std::fs::remove_dir_all(&dir); - } - - /// Review of #3755, point 2 and the smaller points: who takes part in single-instance. - #[test] - fn only_per_user_launches_without_process_options_take_part() { - let base = LaunchContext { - per_user_settings: true, - new_instance_flag: false, - new_instance_env: None, - control: false, - unreadable_paths: false, - launch_options: &[], - }; - assert_eq!(skip_reason(&base), None); - // A portable copy's folder or a PHOTOCRAFT_CONFIG_DIR may be shared between users. - assert!(skip_reason(&LaunchContext { per_user_settings: false, ..base }).is_some()); - assert!(skip_reason(&LaunchContext { new_instance_flag: true, ..base }).is_some()); - assert!(skip_reason(&LaunchContext { new_instance_env: Some("1"), ..base }).is_some()); - assert_eq!(skip_reason(&LaunchContext { new_instance_env: Some("0"), ..base }), None); - assert_eq!(skip_reason(&LaunchContext { new_instance_env: Some(""), ..base }), None); - assert!(skip_reason(&LaunchContext { control: true, ..base }).is_some()); - assert!(skip_reason(&LaunchContext { unreadable_paths: true, ..base }).is_some()); - let reason = skip_reason(&LaunchContext { launch_options: &[PerProcess::SafeGpu, PerProcess::GpuAdapterEnv], ..base }); - assert_eq!(reason.as_deref(), Some("--safe-gpu, PHOTOCRAFT_GPU_ADAPTER only applies to a new process")); - } - - /// #1540: inside a Flatpak sandbox the hand-off runs over a Unix socket in the app's runtime - /// directory, which every sandbox of the app shares, with the same lock, token and reply. - #[cfg(unix)] - #[test] - fn a_sandboxed_second_launch_hands_its_paths_over_a_unix_socket() { - use std::os::unix::fs::PermissionsExt; - let dir = temp_dir("socket"); - // Short: a Unix socket path is limited to about 100 bytes (macOS: 104). - let socket = short_socket_path("a"); - let transport = Transport::Socket(socket.clone()); - let primary = match claim_in(&dir, &[], FAST, &transport) { - Launch::Primary(p) => p, - _ => panic!("first launch should be primary"), - }; - assert_eq!(std::fs::metadata(&socket).unwrap().permissions().mode() & 0o777, 0o600); - let info: Value = serde_json::from_slice(&std::fs::read(dir.join(INFO_FILE)).unwrap()).unwrap(); - assert_eq!(info.get("socket").and_then(Value::as_str), Some(socket.to_str().unwrap())); - assert!(info.get("port").is_none()); - let mut ui = primary.connect(&egui::Context::default()); - let paths = ["/home/a/one.psd".to_string()]; - let (d, p, t) = (dir.clone(), paths.clone(), transport.clone()); - let second = std::thread::spawn(move || claim_in(&d, &p, TIMING, &t)); - assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(paths.to_vec())]); - assert!(matches!(second.join().unwrap(), Launch::Forwarded)); - // The token still gates the socket. - let (endpoint, _) = read_info(&dir).unwrap(); - assert!(send(&endpoint, "not the token", &["x.psd".into()], Instant::now() + FAST.handoff).is_err()); - primary.shutdown(); - assert!(!socket.exists(), "shutdown removes the socket file"); - // The next primary binds the same path; the old one's drop (a second shutdown) must leave it. - let next = match claim_in(&dir, &[], FAST, &transport) { - Launch::Primary(p) => p, - _ => panic!("the lock is free again"), - }; - drop(primary); - assert!(socket.exists(), "a second shutdown doesn't remove the next primary's socket"); - drop(next); - let _ = std::fs::remove_dir_all(&dir); - } - - /// A socket file left by a crashed primary (and a stale `instance.json` naming it) is replaced. - #[cfg(unix)] - #[test] - fn a_crashed_primary_s_socket_file_does_not_block_the_next_one() { - use std::os::unix::fs::FileTypeExt; - let dir = temp_dir("stale-socket"); - let socket = short_socket_path("b"); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::create_dir_all(socket.parent().unwrap()).unwrap(); - std::fs::write(&socket, b"not a socket").unwrap(); - write_info(&dir, &Endpoint::Socket(socket.clone()), &generate_token().unwrap()).unwrap(); - let primary = match claim_in(&dir, &["a.psd".into()], FAST, &Transport::Socket(socket.clone())) { - Launch::Primary(p) => p, - Launch::Forwarded => panic!("nothing was listening"), - Launch::Standalone(e) => panic!("{e}"), - }; - assert!(std::fs::metadata(&socket).unwrap().file_type().is_socket()); - drop(primary); - let _ = std::fs::remove_dir_all(&dir); - let _ = std::fs::remove_dir_all(socket.parent().unwrap()); - } - - /// The socket transport is chosen only inside a Flatpak with a runtime directory. - #[cfg(unix)] - #[test] - fn the_socket_transport_needs_a_flatpak_id_and_a_runtime_directory() { - use std::ffi::OsStr; - let (id, run) = (OsStr::new("ai.storyteller.photocraft"), OsStr::new("/run/user/1000")); - assert_eq!(sandbox_socket(Some(id), Some(run)), Some(PathBuf::from("/run/user/1000/app/ai.storyteller.photocraft/instance.sock"))); - assert_eq!(sandbox_socket(None, Some(run)), None); - assert_eq!(sandbox_socket(Some(id), None), None); - assert_eq!(sandbox_socket(Some(OsStr::new("")), Some(run)), None); - assert_eq!(sandbox_socket(Some(id), Some(OsStr::new(""))), None); - } - - /// A variable documented as the equivalent of a per-launch flag counts as that flag: a launch - /// that sets only variables has per-process options, so it keeps its own process rather than - /// handing its files to the running instance, which never sees the override. - #[test] - fn an_environment_override_counts_as_a_process_option() { - let with = |values: &[(&str, &str)]| env_launch_options_from(|n| values.iter().find(|(k, _)| *k == n).map(|(_, v)| (*v).into())); - assert_eq!(with(&[("PHOTOCRAFT_PRESENT_MODE", "novsync")]), vec![PerProcess::PresentMode]); - assert_eq!( - with(&[("PHOTOCRAFT_STROKE_TRACE", "strokes.csv"), ("PHOTOCRAFT_FRAME_LATENCY", "2")]), - vec![PerProcess::FrameLatency, PerProcess::StrokeTrace] - ); - // Nothing set, or a value that means off, is an ordinary launch. Each variable is off the way - // it is read where it takes effect, not by one rule shared across all three. - assert!(with(&[]).is_empty()); - assert!(with(&[("PHOTOCRAFT_FRAME_LATENCY", "")]).is_empty()); - // The trace is off at `off` and `false` as well, and a value the presentation parser rejects - // is ignored there, so neither keeps a process of its own here. - assert!(with(&[("PHOTOCRAFT_STROKE_TRACE", "off"), ("PHOTOCRAFT_PRESENT_MODE", "maybe"), ("PHOTOCRAFT_FRAME_LATENCY", "4")]).is_empty()); - // The trace and the two presentation values are trimmed where they take effect. - assert_eq!( - with(&[("PHOTOCRAFT_PRESENT_MODE", " novsync "), ("PHOTOCRAFT_STROKE_TRACE", " 1 ")]), - vec![PerProcess::PresentMode, PerProcess::StrokeTrace] - ); - // The menus and the automation roots are flags' fallbacks: `launch_args::parse` counts them. - assert!(with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", "1"), ("PHOTOCRAFT_AUTOMATION_WRITE_ROOT", "/tmp/out")]).is_empty()); - let base = LaunchContext { - per_user_settings: true, - new_instance_flag: false, - new_instance_env: None, - control: false, - unreadable_paths: false, - launch_options: &[], - }; - let reason = skip_reason(&LaunchContext { launch_options: &with(&[("PHOTOCRAFT_PRESENT_MODE", "novsync")]), ..base }); - assert!(reason.as_deref().is_some_and(|r| r.contains("--present-mode")), "{reason:?}"); - } -} +mod tests; diff --git a/apps/photocraft/src/single_instance/tests.rs b/apps/photocraft/src/single_instance/tests.rs new file mode 100644 index 0000000000..dc5755719f --- /dev/null +++ b/apps/photocraft/src/single_instance/tests.rs @@ -0,0 +1,367 @@ +use super::*; +use std::path::PathBuf; +use std::sync::mpsc::channel; + +const FAST: Timing = Timing { handoff: Duration::from_millis(1500), ack: Duration::from_millis(500), request: Duration::from_millis(800) }; + +fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("photocraft-single-instance-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir +} + +/// Launch with `paths` on another thread (it blocks until the primary's UI takes them). +fn launch(dir: &Path, paths: &[&str], timing: Timing) -> std::thread::JoinHandle { + let (dir, paths): (PathBuf, Vec) = (dir.to_path_buf(), paths.iter().map(|p| p.to_string()).collect()); + std::thread::spawn(move || claim_with(&dir, &paths, timing)) +} + +/// Play the UI: drain until `n` events arrived (or 5 s passed). +fn drain(ui: &mut OsEventsFn, n: usize) -> Vec { + let mut got = Vec::new(); + let deadline = Instant::now() + Duration::from_secs(5); + while got.len() < n && Instant::now() < deadline { + got.extend(ui()); + std::thread::sleep(Duration::from_millis(10)); + } + got +} + +fn primary(dir: &Path) -> Primary { + match claim_with(dir, &[], FAST) { + Launch::Primary(p) => p, + _ => panic!("first launch should be primary"), + } +} + +/// A socket path short enough for every Unix (`sun_path` is about 100 bytes; macOS: 104). +#[cfg(unix)] +fn short_socket_path(tag: &str) -> PathBuf { + std::env::temp_dir().join(format!("pc-si-{}-{tag}", std::process::id())).join(SOCKET_FILE) +} + +/// The loopback port the primary under `dir` listens on. +fn port_of(dir: &Path) -> u16 { + match read_info(dir).unwrap().0 { + Endpoint::Port(port) => port, + #[cfg(unix)] + Endpoint::Socket(path) => panic!("expected a loopback port, found {}", path.display()), + } +} + +#[test] +fn second_launch_hands_its_paths_to_the_first() { + let dir = temp_dir("handoff"); + let primary = primary(&dir); + let mut ui = primary.connect(&egui::Context::default()); + let paths = ["C:\\art\\one.psd", "/home/a/two é.png"]; + let second = launch(&dir, &paths, TIMING); + assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(paths.iter().map(|p| p.to_string()).collect())]); + assert!(matches!(second.join().unwrap(), Launch::Forwarded)); + // A plain second start (no files) just brings the window forward. + let third = launch(&dir, &[], TIMING); + assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(Vec::new())]); + assert!(matches!(third.join().unwrap(), Launch::Forwarded)); + drop(primary); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn simultaneous_launches_all_land_in_one_instance() { + let dir = temp_dir("race"); + let (tx, rx) = channel(); + for i in 0..6 { + let (dir, tx) = (dir.clone(), tx.clone()); + std::thread::spawn(move || { + let _ = tx.send(claim(&dir, &[format!("file{i}.psd")])); + }); + } + drop(tx); + let (mut primaries, mut forwarded, mut events) = (Vec::new(), 0, Vec::new()); + let mut ui: Option = None; + let deadline = Instant::now() + Duration::from_secs(10); + while primaries.len() + forwarded < 6 && Instant::now() < deadline { + while let Ok(launch) = rx.try_recv() { + match launch { + Launch::Primary(p) => primaries.push(p), + Launch::Forwarded => forwarded += 1, + Launch::Standalone(reason) => panic!("standalone: {reason}"), + } + } + if ui.is_none() + && let Some(p) = primaries.first() + { + ui = Some(p.connect(&egui::Context::default())); + } + if let Some(ui) = ui.as_mut() { + events.extend(ui()); + } + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!((primaries.len(), forwarded, events.len()), (1, 5, 5)); + drop(primaries); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_crashed_instance_leaves_nothing_in_the_way() { + let dir = temp_dir("stale"); + std::fs::create_dir_all(&dir).unwrap(); + // instance.json from a process that is gone; the lock is free. + std::fs::write(dir.join(INFO_FILE), r#"{"port":1,"token":"x","pid":1}"#).unwrap(); + let primary = primary(&dir); + assert!(read_info(&dir).is_some_and(|(endpoint, _)| endpoint != Endpoint::Port(1))); + drop(primary); + // Released with the handle, as on process exit. + assert!(matches!(claim_with(&dir, &[], FAST), Launch::Primary(_))); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Review of #3755, point 1 (and the quitting half of point 3): a launch waiting on a primary +/// that shuts down (closing, or about to relaunch itself in CPU mode) isn't told `ok`; it takes +/// the lock over and opens the file itself. +#[test] +fn a_launch_waiting_on_a_closing_instance_takes_over() { + let dir = temp_dir("closing"); + let primary = primary(&dir); + // The UI never drains (it is shutting down, or never came up). + let waiting = launch(&dir, &["a.psd"], FAST); + std::thread::sleep(Duration::from_millis(200)); + primary.shutdown(); + assert!(matches!(waiting.join().unwrap(), Launch::Primary(_)), "the waiting launch becomes the primary"); + // After shutdown new connections are refused too. + let (endpoint, token) = read_info(&dir).unwrap(); + drop(primary); + let short = Instant::now() + Duration::from_millis(300); + assert!(send(&endpoint, &token, &["b.psd".into()], short).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Review of #3755, point 3: a primary whose UI never takes the paths (hung) doesn't +/// acknowledge them, and doesn't keep them queued to open later as well. +#[test] +fn a_hung_instance_never_swallows_a_file() { + let dir = temp_dir("hung-ui"); + let primary = primary(&dir); + let mut ui = primary.connect(&egui::Context::default()); + let started = Instant::now(); + assert!(matches!(claim_with(&dir, &["a.psd".into()], FAST), Launch::Standalone(_))); + assert!(started.elapsed() < FAST.handoff + Duration::from_secs(1), "{:?}", started.elapsed()); + assert!(ui().is_empty(), "withdrawn, not opened later"); + drop(primary); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn requests_without_the_token_or_malformed_are_rejected() { + let token = generate_token().unwrap(); + let ok = parse_request(&json!({"token": token, "open": ["a"], "wait_ms": 250}).to_string(), &token); + assert_eq!(ok, Some((vec!["a".to_string()], Duration::from_millis(250)))); + let wrong = generate_token().unwrap(); + assert_eq!(parse_request(&json!({"token": wrong, "open": ["a"]}).to_string(), &token), None); + for bad in ["", "not json", "{}", r#"{"token":5}"#, &json!({"token": token}).to_string(), &json!({"token": token, "open": [1]}).to_string()] { + assert_eq!(parse_request(bad, &token), None, "{bad:?}"); + } + let many: Vec = (0..=MAX_PATHS).map(|i| i.to_string()).collect(); + assert_eq!(parse_request(&json!({"token": token, "open": many}).to_string(), &token), None); +} + +#[test] +fn a_stalled_client_does_not_hold_up_the_next_launch() { + let dir = temp_dir("stalled"); + let primary = primary(&dir); + let mut ui = primary.connect(&egui::Context::default()); + let port = port_of(&dir); + // Connects and never sends a line (each would otherwise hold the listener). + let stalled: Vec = (0..3).map(|_| TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap()).collect(); + let started = Instant::now(); + let next = launch(&dir, &["b.psd"], FAST); + assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(vec!["b.psd".into()])]); + assert!(matches!(next.join().unwrap(), Launch::Forwarded)); + assert!(started.elapsed() < FAST.request, "took {:?}", started.elapsed()); + drop(stalled); + drop(primary); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A client that trickles a byte at a time can't keep its slot past the request deadline. +#[test] +fn a_trickling_client_is_cut_off_at_the_request_deadline() { + let dir = temp_dir("trickle"); + let primary = primary(&dir); + let port = port_of(&dir); + let mut slow = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap(); + let started = Instant::now(); + let mut cut_off = false; + while started.elapsed() < FAST.request * 4 { + if slow.write_all(b"{").is_err() { + cut_off = true; + break; + } + std::thread::sleep(Duration::from_millis(100)); + } + assert!(cut_off, "still connected after {:?}", started.elapsed()); + assert!(started.elapsed() < FAST.request * 3, "{:?}", started.elapsed()); + drop(primary); + let _ = std::fs::remove_dir_all(&dir); +} + +#[cfg(unix)] +#[test] +fn the_token_file_is_private_to_the_user() { + use std::os::unix::fs::PermissionsExt; + let dir = temp_dir("mode"); + std::fs::create_dir_all(&dir).unwrap(); + // A wide leftover temporary file from a crashed start doesn't widen the new one. + let tmp = dir.join(format!("{INFO_FILE}.{}.tmp", std::process::id())); + std::fs::write(&tmp, "{}").unwrap(); + std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o644)).unwrap(); + write_info(&dir, &Endpoint::Port(1), &generate_token().unwrap()).unwrap(); + let mode = std::fs::metadata(dir.join(INFO_FILE)).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_unreachable_instance_falls_back_to_a_standalone_launch() { + let dir = temp_dir("unreachable"); + std::fs::create_dir_all(&dir).unwrap(); + // Someone holds the lock but nothing listens on the advertised port. + let held = File::create(dir.join(LOCK_FILE)).unwrap(); + held.lock().unwrap(); + let closed = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap().local_addr().unwrap().port(); + write_info(&dir, &Endpoint::Port(closed), &generate_token().unwrap()).unwrap(); + assert!(matches!(claim_with(&dir, &["a.psd".into()], FAST), Launch::Standalone(_))); + drop(held); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Review of #3755, point 2 and the smaller points: who takes part in single-instance. +#[test] +fn only_per_user_launches_without_process_options_take_part() { + let base = LaunchContext { + per_user_settings: true, + new_instance_flag: false, + new_instance_env: None, + control: false, + unreadable_paths: false, + launch_options: &[], + }; + assert_eq!(skip_reason(&base), None); + // A portable copy's folder or a PHOTOCRAFT_CONFIG_DIR may be shared between users. + assert!(skip_reason(&LaunchContext { per_user_settings: false, ..base }).is_some()); + assert!(skip_reason(&LaunchContext { new_instance_flag: true, ..base }).is_some()); + assert!(skip_reason(&LaunchContext { new_instance_env: Some("1"), ..base }).is_some()); + assert_eq!(skip_reason(&LaunchContext { new_instance_env: Some("0"), ..base }), None); + assert_eq!(skip_reason(&LaunchContext { new_instance_env: Some(""), ..base }), None); + assert!(skip_reason(&LaunchContext { control: true, ..base }).is_some()); + assert!(skip_reason(&LaunchContext { unreadable_paths: true, ..base }).is_some()); + let reason = skip_reason(&LaunchContext { launch_options: &[PerProcess::SafeGpu, PerProcess::GpuAdapterEnv], ..base }); + assert_eq!(reason.as_deref(), Some("--safe-gpu, PHOTOCRAFT_GPU_ADAPTER only applies to a new process")); +} + +/// #1540: inside a Flatpak sandbox the hand-off runs over a Unix socket in the app's runtime +/// directory, which every sandbox of the app shares, with the same lock, token and reply. +#[cfg(unix)] +#[test] +fn a_sandboxed_second_launch_hands_its_paths_over_a_unix_socket() { + use std::os::unix::fs::PermissionsExt; + let dir = temp_dir("socket"); + // Short: a Unix socket path is limited to about 100 bytes (macOS: 104). + let socket = short_socket_path("a"); + let transport = Transport::Socket(socket.clone()); + let primary = match claim_in(&dir, &[], FAST, &transport) { + Launch::Primary(p) => p, + _ => panic!("first launch should be primary"), + }; + assert_eq!(std::fs::metadata(&socket).unwrap().permissions().mode() & 0o777, 0o600); + let info: Value = serde_json::from_slice(&std::fs::read(dir.join(INFO_FILE)).unwrap()).unwrap(); + assert_eq!(info.get("socket").and_then(Value::as_str), Some(socket.to_str().unwrap())); + assert!(info.get("port").is_none()); + let mut ui = primary.connect(&egui::Context::default()); + let paths = ["/home/a/one.psd".to_string()]; + let (d, p, t) = (dir.clone(), paths.clone(), transport.clone()); + let second = std::thread::spawn(move || claim_in(&d, &p, TIMING, &t)); + assert_eq!(drain(&mut ui, 1), vec![OsEvent::Open(paths.to_vec())]); + assert!(matches!(second.join().unwrap(), Launch::Forwarded)); + // The token still gates the socket. + let (endpoint, _) = read_info(&dir).unwrap(); + assert!(send(&endpoint, "not the token", &["x.psd".into()], Instant::now() + FAST.handoff).is_err()); + primary.shutdown(); + assert!(!socket.exists(), "shutdown removes the socket file"); + // The next primary binds the same path; the old one's drop (a second shutdown) must leave it. + let next = match claim_in(&dir, &[], FAST, &transport) { + Launch::Primary(p) => p, + _ => panic!("the lock is free again"), + }; + drop(primary); + assert!(socket.exists(), "a second shutdown doesn't remove the next primary's socket"); + drop(next); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A socket file left by a crashed primary (and a stale `instance.json` naming it) is replaced. +#[cfg(unix)] +#[test] +fn a_crashed_primary_s_socket_file_does_not_block_the_next_one() { + use std::os::unix::fs::FileTypeExt; + let dir = temp_dir("stale-socket"); + let socket = short_socket_path("b"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::create_dir_all(socket.parent().unwrap()).unwrap(); + std::fs::write(&socket, b"not a socket").unwrap(); + write_info(&dir, &Endpoint::Socket(socket.clone()), &generate_token().unwrap()).unwrap(); + let primary = match claim_in(&dir, &["a.psd".into()], FAST, &Transport::Socket(socket.clone())) { + Launch::Primary(p) => p, + Launch::Forwarded => panic!("nothing was listening"), + Launch::Standalone(e) => panic!("{e}"), + }; + assert!(std::fs::metadata(&socket).unwrap().file_type().is_socket()); + drop(primary); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(socket.parent().unwrap()); +} + +/// The socket transport is chosen only inside a Flatpak with a runtime directory. +#[cfg(unix)] +#[test] +fn the_socket_transport_needs_a_flatpak_id_and_a_runtime_directory() { + use std::ffi::OsStr; + let (id, run) = (OsStr::new("ai.storyteller.photocraft"), OsStr::new("/run/user/1000")); + assert_eq!(sandbox_socket(Some(id), Some(run)), Some(PathBuf::from("/run/user/1000/app/ai.storyteller.photocraft/instance.sock"))); + assert_eq!(sandbox_socket(None, Some(run)), None); + assert_eq!(sandbox_socket(Some(id), None), None); + assert_eq!(sandbox_socket(Some(OsStr::new("")), Some(run)), None); + assert_eq!(sandbox_socket(Some(id), Some(OsStr::new(""))), None); +} + +/// A variable documented as the equivalent of a per-launch flag counts as that flag: a launch +/// that sets only variables has per-process options, so it keeps its own process rather than +/// handing its files to the running instance, which never sees the override. +#[test] +fn an_environment_override_counts_as_a_process_option() { + let with = |values: &[(&str, &str)]| env_launch_options_from(|n| values.iter().find(|(k, _)| *k == n).map(|(_, v)| (*v).into())); + assert_eq!(with(&[("PHOTOCRAFT_PRESENT_MODE", "novsync")]), vec![PerProcess::PresentMode]); + assert_eq!(with(&[("PHOTOCRAFT_STROKE_TRACE", "strokes.csv"), ("PHOTOCRAFT_FRAME_LATENCY", "2")]), vec![PerProcess::FrameLatency, PerProcess::StrokeTrace]); + // Nothing set, or a value that means off, is an ordinary launch. Each variable is off the way + // it is read where it takes effect, not by one rule shared across all three. + assert!(with(&[]).is_empty()); + assert!(with(&[("PHOTOCRAFT_FRAME_LATENCY", "")]).is_empty()); + // The trace is off at `off` and `false` as well, and a value the presentation parser rejects + // is ignored there, so neither keeps a process of its own here. + assert!(with(&[("PHOTOCRAFT_STROKE_TRACE", "off"), ("PHOTOCRAFT_PRESENT_MODE", "maybe"), ("PHOTOCRAFT_FRAME_LATENCY", "4")]).is_empty()); + // The trace and the two presentation values are trimmed where they take effect. + assert_eq!(with(&[("PHOTOCRAFT_PRESENT_MODE", " novsync "), ("PHOTOCRAFT_STROKE_TRACE", " 1 ")]), vec![PerProcess::PresentMode, PerProcess::StrokeTrace]); + // The menus and the automation roots are flags' fallbacks: `launch_args::parse` counts them. + assert!(with(&[("PHOTOCRAFT_IN_WINDOW_MENUS", "1"), ("PHOTOCRAFT_AUTOMATION_WRITE_ROOT", "/tmp/out")]).is_empty()); + let base = LaunchContext { + per_user_settings: true, + new_instance_flag: false, + new_instance_env: None, + control: false, + unreadable_paths: false, + launch_options: &[], + }; + let reason = skip_reason(&LaunchContext { launch_options: &with(&[("PHOTOCRAFT_PRESENT_MODE", "novsync")]), ..base }); + assert!(reason.as_deref().is_some_and(|r| r.contains("--present-mode")), "{reason:?}"); +} From 411771a737ee72f17171e9c1a827e468886e2d07 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:18:03 +0000 Subject: [PATCH 132/259] refactor(photocraft): move gpu_startup.rs tests to gpu_startup/tests.rs --- apps/photocraft/src/gpu_startup.rs | 603 +---------------------- apps/photocraft/src/gpu_startup/tests.rs | 595 ++++++++++++++++++++++ 2 files changed, 596 insertions(+), 602 deletions(-) create mode 100644 apps/photocraft/src/gpu_startup/tests.rs diff --git a/apps/photocraft/src/gpu_startup.rs b/apps/photocraft/src/gpu_startup.rs index 9b08d4d292..56d721e495 100644 --- a/apps/photocraft/src/gpu_startup.rs +++ b/apps/photocraft/src/gpu_startup.rs @@ -569,605 +569,4 @@ pub fn read_rendering_prefs(path: Option<&Path>) -> (GpuBackend, RenderingMode) } #[cfg(test)] -mod tests { - use super::*; - use GpuBackend::*; - - fn crashed(backend: &str, adapter_backend: &str) -> Marker { - Marker { backend: backend.into(), adapter: "Intel(R) UHD Graphics".into(), adapter_backend: adapter_backend.into(), ..Default::default() } - } - - #[test] - fn low_latency_drawing_is_read_before_the_window_opens_and_defaults_off() { - let dir = std::env::temp_dir().join(format!("photocraft-low-latency-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("preferences.json"); - let read = |json: &str| { - std::fs::write(&file, json).unwrap(); - read_low_latency(Some(&file)) - }; - assert!(read(r#"{"performance":{"lowLatencyDrawing":true}}"#)); - assert!(!read(r#"{"performance":{"lowLatencyDrawing":false}}"#)); - assert!(!read(r#"{"performance":{"lowLatencyDrawing":"nope"}}"#), "garbage keeps the default (off)"); - assert!(!read("not json")); - assert!(!read_low_latency(None), "no settings file: the default (off)"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn display_server_preference_is_read_before_the_window_opens() { - use photocraft_engine::prefs::LinuxDisplayServer; - let dir = std::env::temp_dir().join(format!("photocraft-display-server-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("preferences.json"); - let read = |json: &str| { - std::fs::write(&file, json).unwrap(); - read_display_server(Some(&file)) - }; - assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"x11"}}"#), LinuxDisplayServer::X11); - assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"auto","gpuBackend":"vulkan"}}"#), LinuxDisplayServer::Auto); - // Unknown values, other types, broken JSON and a missing file all start as Auto. - assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"wayland"}}"#), LinuxDisplayServer::Auto); - assert_eq!(read(r#"{"performance":{"linuxDisplayServer":11}}"#), LinuxDisplayServer::Auto); - assert_eq!(read("{not json"), LinuxDisplayServer::Auto); - assert_eq!(read_display_server(Some(&dir.join("missing.json"))), LinuxDisplayServer::Auto); - assert_eq!(read_display_server(None), LinuxDisplayServer::Auto); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn cpu_policy_ignores_hardware_backend_override() { - let p = plan_with_mode(Vulkan, RenderingMode::Cpu, None, Some("vulkan"), false, Os::Windows); - assert_eq!(p.backend, Cpu); - assert!(p.env.is_none()); - assert_eq!(plan_with_mode(Vulkan, RenderingMode::Cpu, Some(&crashed("vulkan", "vulkan")), None, false, Os::Windows).backend, Cpu); - let p = plan_with_mode(Auto, RenderingMode::Gpu, None, Some("vulkan"), true, Os::Windows); - assert_eq!(p.backend, Cpu); - assert!(p.env.is_none()); - } - - #[test] - fn no_marker_uses_the_preference() { - for os in [Os::Windows, Os::Mac, Os::Other] { - let p = plan(Auto, None, None, false, os); - assert_eq!(p, Plan { backend: Auto, env: None, reason: None, remember: false }); - } - assert_eq!(plan(Dx12, None, None, false, Os::Windows).backend, Dx12); - assert_eq!(plan(Gl, None, None, false, Os::Other).backend, Gl); - // A backend the platform lacks is `auto`. - assert_eq!(plan(Metal, None, None, false, Os::Windows).backend, Auto); - assert_eq!(plan(Dx12, None, None, false, Os::Mac).backend, Auto); - assert_eq!(plan(Dx12, None, None, false, Os::Other).backend, Auto); - } - - #[test] - fn a_crash_moves_down_each_chain_and_is_remembered() { - // Windows: Vulkan → DX12 → CPU. - let p = plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Windows); - assert_eq!((p.backend, p.remember), (Dx12, true)); - assert!(p.reason.as_deref().unwrap_or("").contains("vulkan (Intel(R) UHD Graphics)"), "{p:?}"); - assert_eq!(plan(Dx12, Some(&crashed("dx12", "dx12")), None, false, Os::Windows).backend, Cpu); - // Crashed before the adapter was chosen (enumeration): from `auto`. - assert_eq!(plan(Auto, Some(&crashed("auto", "")), None, false, Os::Windows).backend, Dx12); - // `auto` that had already picked DX12 (the Intel default) goes to the CPU. - assert_eq!(plan(Auto, Some(&crashed("auto", "dx12")), None, false, Os::Windows).backend, Cpu); - // Linux: Vulkan → GL → CPU. - assert_eq!(plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Other).backend, Gl); - assert_eq!(plan(Gl, Some(&crashed("gl", "gl")), None, false, Os::Other).backend, Cpu); - // macOS: Metal → CPU. - assert_eq!(plan(Auto, Some(&crashed("auto", "metal")), None, false, Os::Mac).backend, Cpu); - // The CPU path stays there, and isn't "remembered" again. - let p = plan(Cpu, Some(&crashed("cpu", "dx12")), None, false, Os::Windows); - assert_eq!((p.backend, p.remember), (Cpu, false)); - // An unreadable marker still counts as a crash. - assert_eq!(plan(Auto, Some(&Marker::parse("{garbage")), None, false, Os::Windows).backend, Dx12); - } - - #[test] - fn env_override_beats_everything() { - let p = plan(Cpu, Some(&crashed("auto", "vulkan")), Some("vulkan"), false, Os::Windows); - assert_eq!(p.env.as_deref(), Some("vulkan")); - assert_eq!(p.backend, Auto); - assert!(!p.remember); - assert_eq!(backends(&p, Os::Windows), None, "egui reads WGPU_BACKEND itself"); - // A crash under the override doesn't count against `auto` later. - let p = plan(Auto, Some(&Marker { backend: "env:vulkan".into(), ..Default::default() }), None, false, Os::Windows); - assert_eq!(p.backend, Auto); - // Empty means unset. - assert_eq!(plan(Auto, None, Some(" "), false, Os::Windows).env, None); - // --safe-gpu with the override: CPU canvas, the override's backends. - assert_eq!(plan(Auto, None, Some("dx12"), true, Os::Windows).backend, Cpu); - } - - /// #3483: A temporary CPU recovery must not change the next launch. - #[test] - fn cpu_recovery_requires_explicit_confirmation_to_persist() { - let gl_crash = crashed("gl", "gl"); - let cpu = plan_with_mode(Auto, RenderingMode::Auto, Some(&gl_crash), None, false, Os::Other); - assert_eq!((cpu.backend, cpu.remember), (Cpu, true)); - assert_eq!(backend_to_remember(&cpu), None); - - let safe = plan_with_mode(Auto, RenderingMode::Auto, None, None, true, Os::Other); - assert_eq!(safe.backend, Cpu); - assert_eq!(backend_to_remember(&safe), None); - // An unconfirmed fallback leaves the original automatic selection intact. - assert_eq!(plan_with_mode(Auto, RenderingMode::Auto, None, None, false, Os::Other).backend, Auto); - // A working hardware fallback can still be remembered. - let vk_crash = crashed("auto", "vulkan"); - let gl = plan_with_mode(Auto, RenderingMode::Auto, Some(&vk_crash), None, false, Os::Other); - assert_eq!(backend_to_remember(&gl), Some(Gl)); - // CPU explicitly selected in preferences still works. - assert_eq!(plan_with_mode(Auto, RenderingMode::Cpu, None, None, false, Os::Other).backend, Cpu); - } - - #[test] - fn safe_gpu_forces_the_cpu_for_one_launch() { - let p = plan(Vulkan, Some(&crashed("vulkan", "vulkan")), None, true, Os::Other); - assert_eq!((p.backend, p.remember), (Cpu, false)); - assert_eq!(backends(&p, Os::Windows), Some(wgpu::Backends::DX12)); - assert_eq!(backends(&p, Os::Other), Some(wgpu::Backends::GL | wgpu::Backends::VULKAN)); - assert_eq!(backends(&p, Os::Mac), Some(wgpu::Backends::METAL)); - } - - fn cand(vendor: u32, device_type: wgpu::DeviceType, backend: wgpu::Backend) -> Candidate { - Candidate { vendor, device_type, backend, surface_ok: true, wanted: false } - } - - #[test] - fn a_requested_adapter_beats_the_automatic_ranking() { - use wgpu::{Backend as B, DeviceType as T}; - // The order Vulkan lists this machine's GPUs in: iGPU, dGPU, eGPU. - let mut a = [cand(INTEL, T::IntegratedGpu, B::Vulkan), cand(INTEL, T::DiscreteGpu, B::Vulkan), cand(0x10de, T::DiscreteGpu, B::Vulkan)]; - assert_eq!(pick(&a, Auto, Os::Other), Some(1), "automatic takes the first discrete adapter, the Arc"); - a[2].wanted = true; - assert_eq!(pick(&a, Auto, Os::Other), Some(2)); - a[2].wanted = false; - a[0].wanted = true; - assert_eq!(pick(&a, Auto, Os::Other), Some(0), "even the iGPU, when asked for"); - // A wanted adapter that can't present is skipped, not an error. - a[0].surface_ok = false; - assert_eq!(pick(&a, Auto, Os::Other), Some(1)); - assert!(wanted_missed(&a, Some("iris"))); - assert!(!wanted_missed(&a, None)); - a[0].surface_ok = true; - assert!(!wanted_missed(&a, Some("iris"))); - // Among several wanted ones (same GPU on Vulkan and GL) the usual ranking decides. - let mut gl = [cand(0x10de, T::DiscreteGpu, B::Gl), cand(0x10de, T::DiscreteGpu, B::Vulkan)]; - gl.iter_mut().for_each(|c| c.wanted = true); - assert_eq!(pick(&gl, Auto, Os::Other), Some(1)); - } - - #[test] - fn an_adapter_request_applies_on_linux_outside_cpu_mode() { - let w = || Some("nvidia".to_string()); - assert_eq!(applicable_adapter(w(), Auto, true), w()); - assert_eq!(applicable_adapter(w(), Vulkan, true), w()); - assert_eq!(applicable_adapter(w(), Cpu, true), None); - assert_eq!(applicable_adapter(w(), Auto, false), None, "Windows and macOS keep their own selection"); - assert_eq!(applicable_adapter(None, Auto, true), None); - } - - #[test] - fn an_adapter_override_keeps_its_own_process_only_when_it_applies() { - let on = |env, mode, linux| adapter_override_is_process_specific(env, mode, linux); - assert!(on(Some("nvidia"), RenderingMode::Auto, true)); - assert!(on(Some("nvidia"), RenderingMode::Gpu, true)); - assert!(!on(Some("nvidia"), RenderingMode::Cpu, true), "ignored in CPU mode"); - assert!(!on(Some("nvidia"), RenderingMode::Auto, false), "ignored off Linux"); - assert!(!on(Some(" "), RenderingMode::Auto, true)); - assert!(!on(None, RenderingMode::Auto, true)); - } - - #[test] - fn adapter_names_match_loosely_and_the_environment_wins() { - assert!(adapter_matches("NVIDIA GeForce RTX 5060 Ti", "nvidia")); - assert!(adapter_matches("Intel(R) Arc(tm) A370M Graphics (DG2)", " ARC A370M ")); - assert!(!adapter_matches("Intel(R) Iris(R) Xe Graphics (ADL GT2)", "arc")); - assert!(!adapter_matches("anything", "")); - assert!(!adapter_matches("anything", " ")); - assert_eq!(wanted_adapter(None, ""), None); - assert_eq!(wanted_adapter(Some(" "), "iris"), Some("iris".into())); - assert_eq!(wanted_adapter(Some("nvidia"), "iris"), Some("nvidia".into())); - assert_eq!(wanted_adapter(Some(&"x".repeat(1000)), "").map(|w| w.len()), Some(256)); - } - - #[test] - fn gpu_adapter_is_read_before_the_window_opens() { - let dir = std::env::temp_dir().join(format!("photocraft-gpu-adapter-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("preferences.json"); - let read = |json: &str| { - std::fs::write(&file, json).unwrap(); - read_gpu_adapter(Some(&file)) - }; - assert_eq!(read(r#"{"performance":{"gpuAdapter":"nvidia"}}"#), "nvidia"); - assert_eq!(read(r#"{"performance":{"gpuAdapter":7}}"#), ""); - assert_eq!(read(r#"{"performance":{}}"#), ""); - assert_eq!(read("not json"), ""); - assert_eq!(read_gpu_adapter(None), ""); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn intel_on_windows_defaults_to_dx12() { - use wgpu::{Backend as B, DeviceType as T}; - let intel = [cand(INTEL, T::IntegratedGpu, B::Vulkan), cand(INTEL, T::IntegratedGpu, B::Dx12), cand(INTEL, T::IntegratedGpu, B::Gl)]; - let i = pick(&intel, Auto, Os::Windows).unwrap(); - assert_eq!(intel[i].backend, B::Dx12); - assert_eq!(dx12_default_applied(&intel, i, Os::Windows, false), Some("Intel")); - // Elsewhere (and for other vendors) Vulkan stays first. - assert_eq!(intel[pick(&intel, Auto, Os::Other).unwrap()].backend, B::Vulkan); - let nv = [cand(0x10de, T::DiscreteGpu, B::Dx12), cand(0x10de, T::DiscreteGpu, B::Vulkan)]; - let i = pick(&nv, Auto, Os::Windows).unwrap(); - assert_eq!(nv[i].backend, B::Vulkan); - assert_eq!(dx12_default_applied(&nv, i, Os::Windows, false), None); - // Intel iGPU + discrete GPU: the discrete one wins (high performance), on Vulkan. - let hybrid = [intel[0], intel[1], nv[1]]; - assert_eq!(pick(&hybrid, Auto, Os::Windows), Some(2)); - // Adapters that can't present lose to ones that can. - let mut only = [cand(0x10de, T::DiscreteGpu, B::Vulkan), intel[1]]; - only[0].surface_ok = false; - assert_eq!(pick(&only, Auto, Os::Windows), Some(1)); - assert_eq!(pick(&[], Auto, Os::Windows), None); - } - - /// #7537: on Windows on ARM the Adreno Vulkan driver lost the device mid-session and took the - /// window with it; DX12 on the same machine didn't. DXGI and Vulkan report different vendor ids. - #[test] - fn qualcomm_on_windows_defaults_to_dx12() { - use wgpu::{Backend as B, DeviceType as T}; - let adreno = [cand(QUALCOMM, T::IntegratedGpu, B::Vulkan), cand(QUALCOMM_DXGI, T::IntegratedGpu, B::Dx12)]; - let i = pick(&adreno, Auto, Os::Windows).unwrap(); - assert_eq!(adreno[i].backend, B::Dx12); - assert_eq!(dx12_default_applied(&adreno, i, Os::Windows, false), Some("Qualcomm")); - // Only Vulkan offered: still Vulkan, and no note. - assert_eq!(pick(&adreno[..1], Auto, Os::Windows), Some(0)); - assert_eq!(dx12_default_applied(&adreno, 0, Os::Windows, false), None); - // An Intel Vulkan adapter doesn't make a Qualcomm DX12 pick "the default". - let mixed = [cand(INTEL, T::IntegratedGpu, B::Vulkan), adreno[1]]; - assert_eq!(dx12_default_applied(&mixed, 1, Os::Windows, false), None); - // Vulkan left out of the instance (an Intel adapter was listed) speaks only for Intel. - assert_eq!(dx12_default_applied(&adreno[1..], 0, Os::Windows, true), None); - // Elsewhere Vulkan stays first. - assert_eq!(adreno[pick(&adreno, Auto, Os::Other).unwrap()].backend, B::Vulkan); - } - - /// #4: an instance with Vulkan loads the Intel Vulkan driver, which crashed at startup, before - /// the selector picks Intel's DX12 adapter. With an Intel adapter in the DX12 list, `auto` on - /// Windows creates the instance without Vulkan. - #[test] - fn auto_on_windows_with_an_intel_adapter_leaves_vulkan_out_of_the_instance() { - use wgpu::{Backend as B, DeviceType as T}; - const NVIDIA: u32 = 0x10de; - const AMD: u32 = 0x1002; - const WARP: u32 = 0x1414; - let auto = plan(Auto, None, None, false, Os::Windows); - let dx12_gl = Some(wgpu::Backends::DX12 | wgpu::Backends::GL); - assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![INTEL, WARP]), dx12_gl); - // Intel iGPU + discrete GPU: the discrete GPU is then used on DX12. - assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![NVIDIA, INTEL, WARP]), dx12_gl); - // No Intel adapter: egui's default backends, Vulkan included. - assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![NVIDIA, WARP]), None); - assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![AMD]), None); - assert_eq!(windows_auto_backends(&auto, Os::Windows, Vec::new), None); - // `WGPU_BACKEND`, `--safe-gpu`, a chosen backend, a crash fallback and other platforms - // don't list the DX12 adapters at all. - let not_listed = || -> Vec { panic!("DX12 adapters listed") }; - for (p, os) in [ - (plan(Auto, None, Some("vulkan"), false, Os::Windows), Os::Windows), - (plan(Auto, None, None, true, Os::Windows), Os::Windows), - (plan(Vulkan, None, None, false, Os::Windows), Os::Windows), - (plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Windows), Os::Windows), - (plan(Auto, None, None, false, Os::Other), Os::Other), - (plan(Auto, None, None, false, Os::Mac), Os::Mac), - ] { - assert_eq!(windows_auto_backends(&p, os, not_listed), None, "{p:?}"); - } - // Without Vulkan adapters to compare with, System Info still names the Intel default. - let listed = [cand(INTEL, T::IntegratedGpu, B::Dx12), cand(WARP, T::Cpu, B::Dx12), cand(INTEL, T::IntegratedGpu, B::Gl)]; - let i = pick(&listed, Auto, Os::Windows).unwrap(); - assert_eq!(i, 0); - assert_eq!(dx12_default_applied(&listed, i, Os::Windows, true), Some("Intel")); - assert_eq!(dx12_default_applied(&listed, i, Os::Windows, false), None); - } - - #[test] - fn cpu_prefers_software_adapters() { - use wgpu::{Backend as B, DeviceType as T}; - let a = [cand(INTEL, T::IntegratedGpu, B::Dx12), cand(0x1414, T::Cpu, B::Dx12)]; - assert_eq!(pick(&a, Cpu, Os::Windows), Some(1)); - // No software adapter: still something. - assert_eq!(pick(&a[..1], Cpu, Os::Windows), Some(0)); - } - - /// #1337: on Linux with NVIDIA, the only GL adapter (NVIDIA's EGL) can't present, so CPU mode - /// found no adapter and never started. GL still wins whenever it can present. - #[test] - fn cpu_on_linux_falls_back_to_vulkan_only_when_gl_cannot_present() { - use wgpu::{Backend as B, DeviceType as T}; - const NVIDIA: u32 = 0x10de; - let llvmpipe = cand(0x10005, T::Cpu, B::Gl); - let nvidia_gl = cand(NVIDIA, T::DiscreteGpu, B::Gl); - let nvidia_vk = cand(NVIDIA, T::DiscreteGpu, B::Vulkan); - let lavapipe = cand(0x10005, T::Cpu, B::Vulkan); - // GL presents: same choice as GL-only, software first, then hardware GL over any Vulkan. - assert_eq!(pick(&[nvidia_vk, lavapipe, llvmpipe], Cpu, Os::Other), Some(2)); - assert_eq!(pick(&[nvidia_vk, lavapipe, nvidia_gl], Cpu, Os::Other), Some(2)); - // GL can't present: Vulkan for the window, software first. - let mut gl = nvidia_gl; - gl.surface_ok = false; - assert_eq!(pick(&[gl, nvidia_vk, lavapipe], Cpu, Os::Other), Some(2)); - assert_eq!(pick(&[gl, nvidia_vk], Cpu, Os::Other), Some(1)); - // Other backends rank as before. - assert_eq!(pick(&[nvidia_gl, nvidia_vk], Auto, Os::Other), Some(1)); - } - - /// #5191, #1788: a Windows VM offers VMware's SVGA3D over GL (`Other`) and WARP (`Cpu`, DX12). - /// GL drew a black window; WARP works. GL stays the last resort. - #[test] - fn windows_auto_prefers_warp_over_gl() { - use wgpu::{Backend as B, DeviceType as T}; - let svga_gl = cand(0x15ad, T::Other, B::Gl); - let warp = cand(0x1414, T::Cpu, B::Dx12); - assert_eq!(pick(&[svga_gl, warp], Auto, Os::Windows), Some(1)); - assert_eq!(pick(&[cand(INTEL, T::IntegratedGpu, B::Gl), warp], Auto, Os::Windows), Some(1)); - assert_eq!(pick(&[svga_gl], Auto, Os::Windows), Some(0)); - // Elsewhere GL keeps its rank. - assert_eq!(pick(&[svga_gl, warp], Auto, Os::Other), Some(0)); - } - - #[test] - fn adapters_must_present_even_when_none_support_the_surface() { - let mut a = cand(INTEL, wgpu::DeviceType::IntegratedGpu, wgpu::Backend::Dx12); - a.surface_ok = false; - assert_eq!(pick(&[a], Auto, Os::Windows), None); - assert_eq!(pick(&[a], Cpu, Os::Windows), None); - } - - #[test] - fn explicit_policy_overrides_legacy_cpu_backend() { - assert_eq!(plan_with_mode(Cpu, RenderingMode::Gpu, None, None, false, Os::Mac).backend, Auto); - assert_eq!(plan_with_mode(Metal, RenderingMode::Cpu, None, None, false, Os::Mac).backend, Cpu); - assert_eq!(plan_with_mode(Auto, RenderingMode::Gpu, None, None, true, Os::Mac).backend, Cpu); - } - - #[test] - fn marker_round_trip_and_lenient_parse() { - let m = Marker { - backend: "auto".into(), - adapter: "A \"quoted\" GPU".into(), - adapter_backend: "vulkan".into(), - driver: "1.2".into(), - version: "0.1".into(), - }; - assert_eq!(Marker::parse(&m.to_json()), m); - assert_eq!(Marker::parse(""), Marker::default()); - assert_eq!(Marker::parse("[1,2]").tried(), Some(Auto)); - assert_eq!(Marker::parse(r#"{"backend": 7}"#).tried(), Some(Auto)); - assert_eq!(Marker::parse(r#"{"backend": "env:dx12"}"#).tried(), None); - let long = format!(r#"{{"adapter": "{}"}}"#, "x".repeat(10_000)); - assert_eq!(Marker::parse(&long).adapter.len(), 256); - } - - #[test] - fn a_failed_start_keeps_its_marker_only_when_a_safer_backend_exists() { - // GPU backends move down the chain on the next start. - assert!(keep_marker_after_error(&plan(Auto, None, None, false, Os::Other), Os::Other)); - assert!(keep_marker_after_error(&plan(Gl, None, None, false, Os::Other), Os::Other)); - assert!(keep_marker_after_error(&plan(Dx12, None, None, false, Os::Windows), Os::Windows)); - assert!(keep_marker_after_error(&plan(Auto, None, None, false, Os::Mac), Os::Mac)); - // The CPU path is the end of every chain, including the `--safe-gpu` retry. - for os in [Os::Windows, Os::Mac, Os::Other] { - assert!(!keep_marker_after_error(&plan(Cpu, None, None, false, os), os)); - assert!(!keep_marker_after_error(&plan(Auto, None, None, true, os), os)); - } - // `WGPU_BACKEND` is the user's choice; no plan reads its marker. - assert!(!keep_marker_after_error(&plan(Auto, None, Some("vulkan"), false, Os::Other), Os::Other)); - } - - /// A failed CPU start (no usable GL adapter under XWayland) left a `cpu` marker, so every - /// later start was planned on CPU and failed the same way until the marker was deleted by hand. - #[test] - fn a_failed_cpu_start_does_not_pin_later_starts() { - let dir = temp_dir("cpu-error"); - let (_, s) = Sentinel::begin(&dir); - let mut s = s.expect("sentinel"); - let failed = plan(Auto, None, None, true, Os::Other); - s.write(Marker { backend: failed.backend.name().into(), ..Default::default() }).unwrap(); - // eframe returned an error: what `main` does with the marker. - if keep_marker_after_error(&failed, Os::Other) { - drop(s); - } else { - s.finish(); - } - let (prev, _s) = begin_when_unlocked(&dir); - assert_eq!(prev, Previous::Clean); - assert_eq!(plan(Auto, prev.crashed(), None, false, Os::Other).backend, Auto); - let _ = std::fs::remove_dir_all(&dir); - } - - fn temp_dir(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("photocraft-gpu-startup-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - d - } - - /// `Sentinel::begin`, called again up to 50 times, 10 ms apart, while it returns - /// `Previous::Busy`. Other tests in this binary spawn processes: between fork and exec a child - /// briefly shares the marker's flock, so `begin` can see the lock as busy just after a test - /// drops its sentinel. - fn begin_when_unlocked(dir: &Path) -> (Previous, Option) { - let (mut prev, mut s) = Sentinel::begin(dir); - for _ in 0..50 { - if prev != Previous::Busy { - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - (prev, s) = Sentinel::begin(dir); - } - (prev, s) - } - - #[test] - fn sentinel_detects_a_crash_and_clears_on_success() { - let dir = temp_dir("cycle"); - // First launch: nothing left behind. - let (prev, s) = Sentinel::begin(&dir); - assert_eq!(prev, Previous::Clean); - let mut s = s.expect("sentinel"); - s.write(Marker { backend: "auto".into(), ..Default::default() }).unwrap(); - s.write(Marker { backend: "auto".into(), adapter: "GPU".into(), adapter_backend: "vulkan".into(), ..Default::default() }).unwrap(); - // While it is starting, a second instance sees it busy, not crashed. - let (busy, none) = Sentinel::begin(&dir); - assert_eq!(busy, Previous::Busy); - assert!(none.is_none()); - // The process dies in the driver: the lock goes, the marker stays. - drop(s); - let (prev, s) = begin_when_unlocked(&dir); - let m = prev.crashed().cloned().expect("crash detected"); - assert_eq!((m.adapter.as_str(), m.tried()), ("GPU", Some(Vulkan))); - // This start succeeds: the next one finds nothing. - let mut s = s.expect("sentinel"); - s.write(Marker { backend: "dx12".into(), ..Default::default() }).unwrap(); - s.finish(); - assert!(!dir.join(MARKER_FILE).exists()); - let (prev, _s) = Sentinel::begin(&dir); - assert_eq!(prev, Previous::Clean); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn begin_when_unlocked_waits_for_a_briefly_held_lock() { - let dir = temp_dir("shared-lock"); - let (_, s) = Sentinel::begin(&dir); - let mut s = s.expect("sentinel"); - s.write(Marker { backend: "vulkan".into(), ..Default::default() }).unwrap(); - // After the start dies, a second handle on the marker holds the lock for 50 ms, as a - // spawned child's copy of the descriptor does until the child calls exec. - let held = File::open(dir.join(MARKER_FILE)).unwrap(); - drop(s); - held.lock().unwrap(); - assert_eq!(Sentinel::begin(&dir).0, Previous::Busy); - let release = std::thread::spawn(move || { - std::thread::sleep(std::time::Duration::from_millis(50)); - held.unlock().unwrap(); - }); - let (prev, s) = begin_when_unlocked(&dir); - release.join().unwrap(); - assert_eq!(prev.crashed().map(|m| m.backend.as_str()), Some("vulkan")); - s.expect("sentinel").finish(); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn returned_non_graphics_errors_do_not_trigger_backend_recovery() { - let cases = [ - ("success", Ok(()), false), - ("app-error", Err(eframe::Error::AppCreation(Box::new(std::io::Error::other("app setup failed")))), false), - ("gpu-error", Err(eframe::Error::Wgpu(egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no adapter".into()))), true), - ]; - for (name, result, keep) in cases { - let dir = temp_dir(name); - let (_, s) = Sentinel::begin(&dir); - let mut s = s.expect("sentinel"); - s.write(Marker { backend: "vulkan".into(), ..Default::default() }).unwrap(); - if keep_marker_after_run(&result) { - drop(s); - } else { - s.finish(); - } - let (previous, s) = begin_when_unlocked(&dir); - assert_eq!(previous.crashed().is_some(), keep, "{name}: {result:?}"); - if !keep { - assert_eq!(plan(Vulkan, previous.crashed(), None, false, Os::Other).backend, Vulkan); - } - s.expect("sentinel").finish(); - let _ = std::fs::remove_dir_all(&dir); - } - } - - #[test] - fn unwritable_config_dir_is_not_fatal() { - let dir = temp_dir("file"); - std::fs::create_dir_all(dir.parent().unwrap()).unwrap(); - std::fs::write(&dir, b"not a directory").unwrap(); - let (prev, s) = Sentinel::begin(&dir.join("sub")); - assert_eq!(prev, Previous::Clean); - assert!(s.is_none()); - let _ = std::fs::remove_file(&dir); - } - - #[test] - fn prefs_are_read_leniently() { - let dir = temp_dir("prefs"); - std::fs::create_dir_all(&dir).unwrap(); - let p = dir.join("preferences.json"); - assert_eq!(read_rendering_prefs(None), (Auto, RenderingMode::Auto)); - assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); - std::fs::write(&p, r#"{"performance": {"gpuBackend": "dx12", "useGpu": false}, "interface": {}}"#).unwrap(); - assert_eq!(read_rendering_prefs(Some(&p)), (Dx12, RenderingMode::Cpu)); - std::fs::write(&p, r#"{"performance": {"gpuBackend": "quantum"}}"#).unwrap(); - assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); - std::fs::write(&p, r#"{"performance": {"useGpu": false, "renderingMode": "gpu"}}"#).unwrap(); - assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Gpu)); - std::fs::write(&p, "{not json").unwrap(); - assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); - let _ = std::fs::remove_dir_all(&dir); - } - - /// #712: never a `dxcompiler.dll` found through the DLL search path (current directory, PATH). - #[test] - fn dx12_compiler_is_fxc_or_dxc_beside_the_exe() { - use wgpu::Dx12Compiler as C; - let dir = temp_dir("dxc"); - std::fs::create_dir_all(&dir).unwrap(); - assert!(matches!(dx12_compiler(None, None), C::Fxc)); - assert!(matches!(dx12_compiler(None, Some(&dir)), C::Fxc)); - std::fs::write(dir.join("dxcompiler.dll"), b"MZ").unwrap(); - let expected = dir.join("dxcompiler.dll"); - assert!(matches!(dx12_compiler(None, Some(&dir)), C::DynamicDxc { dxc_path } if Path::new(&dxc_path) == expected)); - // An explicit WGPU_DX12_COMPILER wins; an unknown value is ignored. - assert!(matches!(dx12_compiler(Some(" FXC "), Some(&dir)), C::Fxc)); - assert!(matches!(dx12_compiler(Some("dxc"), None), C::DynamicDxc { dxc_path } if dxc_path == "dxcompiler.dll")); - assert!(matches!(dx12_compiler(Some("quantum"), None), C::Fxc)); - let _ = std::fs::remove_dir_all(&dir); - - // The app's setup replaces wgpu's default (`Auto`: DXC by name from the search path). - let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); - let plan = plan(Auto, None, None, false, Os::Windows); - configure(&mut setup, &plan, Os::Windows, None, Arc::new(Mutex::new(None)), Arc::default()); - let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") }; - if std::env::var_os("WGPU_DX12_COMPILER").is_none() { - let safe = match &create.instance_descriptor.backend_options.dx12.shader_compiler { - C::Fxc => true, - C::DynamicDxc { dxc_path } => Path::new(dxc_path).is_absolute(), - C::StaticDxc | C::Auto => false, - }; - assert!(safe, "{:?}", create.instance_descriptor.backend_options.dx12.shader_compiler); - } - } - - #[test] - fn intel_macs_skip_the_indirect_validation_shaders() { - // Metal's compiler crashed on them on Intel Iris Pro, losing the device in every mode (#3107). - assert!(skips_indirect_validation(Os::Mac, true)); - // Apple silicon, Windows and Linux keep wgpu's validation. - for (os, intel) in [(Os::Mac, false), (Os::Windows, true), (Os::Other, true), (Os::Other, false)] { - assert!(!skips_indirect_validation(os, intel), "{os:?} intel={intel}"); - } - for (os, safe_gpu) in [(Os::Windows, false), (Os::Other, true), (Os::Other, false)] { - let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); - let egui_wgpu::WgpuSetup::CreateNew(before) = &setup else { panic!("a new instance") }; - let before = before.instance_descriptor.flags; - configure(&mut setup, &plan(Auto, None, None, safe_gpu, os), os, None, Arc::new(Mutex::new(None)), Arc::default()); - let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") }; - assert_eq!(create.instance_descriptor.flags, before, "{os:?}: flags untouched"); - } - if cfg!(target_arch = "x86_64") && std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() { - let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); - configure(&mut setup, &plan(Auto, None, None, false, Os::Mac), Os::Mac, None, Arc::new(Mutex::new(None)), Arc::default()); - let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") }; - assert!(!create.instance_descriptor.flags.contains(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL)); - } - } -} +mod tests; diff --git a/apps/photocraft/src/gpu_startup/tests.rs b/apps/photocraft/src/gpu_startup/tests.rs new file mode 100644 index 0000000000..ee1f0ce1e6 --- /dev/null +++ b/apps/photocraft/src/gpu_startup/tests.rs @@ -0,0 +1,595 @@ +use super::*; +use GpuBackend::*; + +fn crashed(backend: &str, adapter_backend: &str) -> Marker { + Marker { backend: backend.into(), adapter: "Intel(R) UHD Graphics".into(), adapter_backend: adapter_backend.into(), ..Default::default() } +} + +#[test] +fn low_latency_drawing_is_read_before_the_window_opens_and_defaults_off() { + let dir = std::env::temp_dir().join(format!("photocraft-low-latency-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("preferences.json"); + let read = |json: &str| { + std::fs::write(&file, json).unwrap(); + read_low_latency(Some(&file)) + }; + assert!(read(r#"{"performance":{"lowLatencyDrawing":true}}"#)); + assert!(!read(r#"{"performance":{"lowLatencyDrawing":false}}"#)); + assert!(!read(r#"{"performance":{"lowLatencyDrawing":"nope"}}"#), "garbage keeps the default (off)"); + assert!(!read("not json")); + assert!(!read_low_latency(None), "no settings file: the default (off)"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn display_server_preference_is_read_before_the_window_opens() { + use photocraft_engine::prefs::LinuxDisplayServer; + let dir = std::env::temp_dir().join(format!("photocraft-display-server-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("preferences.json"); + let read = |json: &str| { + std::fs::write(&file, json).unwrap(); + read_display_server(Some(&file)) + }; + assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"x11"}}"#), LinuxDisplayServer::X11); + assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"auto","gpuBackend":"vulkan"}}"#), LinuxDisplayServer::Auto); + // Unknown values, other types, broken JSON and a missing file all start as Auto. + assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"wayland"}}"#), LinuxDisplayServer::Auto); + assert_eq!(read(r#"{"performance":{"linuxDisplayServer":11}}"#), LinuxDisplayServer::Auto); + assert_eq!(read("{not json"), LinuxDisplayServer::Auto); + assert_eq!(read_display_server(Some(&dir.join("missing.json"))), LinuxDisplayServer::Auto); + assert_eq!(read_display_server(None), LinuxDisplayServer::Auto); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn cpu_policy_ignores_hardware_backend_override() { + let p = plan_with_mode(Vulkan, RenderingMode::Cpu, None, Some("vulkan"), false, Os::Windows); + assert_eq!(p.backend, Cpu); + assert!(p.env.is_none()); + assert_eq!(plan_with_mode(Vulkan, RenderingMode::Cpu, Some(&crashed("vulkan", "vulkan")), None, false, Os::Windows).backend, Cpu); + let p = plan_with_mode(Auto, RenderingMode::Gpu, None, Some("vulkan"), true, Os::Windows); + assert_eq!(p.backend, Cpu); + assert!(p.env.is_none()); +} + +#[test] +fn no_marker_uses_the_preference() { + for os in [Os::Windows, Os::Mac, Os::Other] { + let p = plan(Auto, None, None, false, os); + assert_eq!(p, Plan { backend: Auto, env: None, reason: None, remember: false }); + } + assert_eq!(plan(Dx12, None, None, false, Os::Windows).backend, Dx12); + assert_eq!(plan(Gl, None, None, false, Os::Other).backend, Gl); + // A backend the platform lacks is `auto`. + assert_eq!(plan(Metal, None, None, false, Os::Windows).backend, Auto); + assert_eq!(plan(Dx12, None, None, false, Os::Mac).backend, Auto); + assert_eq!(plan(Dx12, None, None, false, Os::Other).backend, Auto); +} + +#[test] +fn a_crash_moves_down_each_chain_and_is_remembered() { + // Windows: Vulkan → DX12 → CPU. + let p = plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Windows); + assert_eq!((p.backend, p.remember), (Dx12, true)); + assert!(p.reason.as_deref().unwrap_or("").contains("vulkan (Intel(R) UHD Graphics)"), "{p:?}"); + assert_eq!(plan(Dx12, Some(&crashed("dx12", "dx12")), None, false, Os::Windows).backend, Cpu); + // Crashed before the adapter was chosen (enumeration): from `auto`. + assert_eq!(plan(Auto, Some(&crashed("auto", "")), None, false, Os::Windows).backend, Dx12); + // `auto` that had already picked DX12 (the Intel default) goes to the CPU. + assert_eq!(plan(Auto, Some(&crashed("auto", "dx12")), None, false, Os::Windows).backend, Cpu); + // Linux: Vulkan → GL → CPU. + assert_eq!(plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Other).backend, Gl); + assert_eq!(plan(Gl, Some(&crashed("gl", "gl")), None, false, Os::Other).backend, Cpu); + // macOS: Metal → CPU. + assert_eq!(plan(Auto, Some(&crashed("auto", "metal")), None, false, Os::Mac).backend, Cpu); + // The CPU path stays there, and isn't "remembered" again. + let p = plan(Cpu, Some(&crashed("cpu", "dx12")), None, false, Os::Windows); + assert_eq!((p.backend, p.remember), (Cpu, false)); + // An unreadable marker still counts as a crash. + assert_eq!(plan(Auto, Some(&Marker::parse("{garbage")), None, false, Os::Windows).backend, Dx12); +} + +#[test] +fn env_override_beats_everything() { + let p = plan(Cpu, Some(&crashed("auto", "vulkan")), Some("vulkan"), false, Os::Windows); + assert_eq!(p.env.as_deref(), Some("vulkan")); + assert_eq!(p.backend, Auto); + assert!(!p.remember); + assert_eq!(backends(&p, Os::Windows), None, "egui reads WGPU_BACKEND itself"); + // A crash under the override doesn't count against `auto` later. + let p = plan(Auto, Some(&Marker { backend: "env:vulkan".into(), ..Default::default() }), None, false, Os::Windows); + assert_eq!(p.backend, Auto); + // Empty means unset. + assert_eq!(plan(Auto, None, Some(" "), false, Os::Windows).env, None); + // --safe-gpu with the override: CPU canvas, the override's backends. + assert_eq!(plan(Auto, None, Some("dx12"), true, Os::Windows).backend, Cpu); +} + +/// #3483: A temporary CPU recovery must not change the next launch. +#[test] +fn cpu_recovery_requires_explicit_confirmation_to_persist() { + let gl_crash = crashed("gl", "gl"); + let cpu = plan_with_mode(Auto, RenderingMode::Auto, Some(&gl_crash), None, false, Os::Other); + assert_eq!((cpu.backend, cpu.remember), (Cpu, true)); + assert_eq!(backend_to_remember(&cpu), None); + + let safe = plan_with_mode(Auto, RenderingMode::Auto, None, None, true, Os::Other); + assert_eq!(safe.backend, Cpu); + assert_eq!(backend_to_remember(&safe), None); + // An unconfirmed fallback leaves the original automatic selection intact. + assert_eq!(plan_with_mode(Auto, RenderingMode::Auto, None, None, false, Os::Other).backend, Auto); + // A working hardware fallback can still be remembered. + let vk_crash = crashed("auto", "vulkan"); + let gl = plan_with_mode(Auto, RenderingMode::Auto, Some(&vk_crash), None, false, Os::Other); + assert_eq!(backend_to_remember(&gl), Some(Gl)); + // CPU explicitly selected in preferences still works. + assert_eq!(plan_with_mode(Auto, RenderingMode::Cpu, None, None, false, Os::Other).backend, Cpu); +} + +#[test] +fn safe_gpu_forces_the_cpu_for_one_launch() { + let p = plan(Vulkan, Some(&crashed("vulkan", "vulkan")), None, true, Os::Other); + assert_eq!((p.backend, p.remember), (Cpu, false)); + assert_eq!(backends(&p, Os::Windows), Some(wgpu::Backends::DX12)); + assert_eq!(backends(&p, Os::Other), Some(wgpu::Backends::GL | wgpu::Backends::VULKAN)); + assert_eq!(backends(&p, Os::Mac), Some(wgpu::Backends::METAL)); +} + +fn cand(vendor: u32, device_type: wgpu::DeviceType, backend: wgpu::Backend) -> Candidate { + Candidate { vendor, device_type, backend, surface_ok: true, wanted: false } +} + +#[test] +fn a_requested_adapter_beats_the_automatic_ranking() { + use wgpu::{Backend as B, DeviceType as T}; + // The order Vulkan lists this machine's GPUs in: iGPU, dGPU, eGPU. + let mut a = [cand(INTEL, T::IntegratedGpu, B::Vulkan), cand(INTEL, T::DiscreteGpu, B::Vulkan), cand(0x10de, T::DiscreteGpu, B::Vulkan)]; + assert_eq!(pick(&a, Auto, Os::Other), Some(1), "automatic takes the first discrete adapter, the Arc"); + a[2].wanted = true; + assert_eq!(pick(&a, Auto, Os::Other), Some(2)); + a[2].wanted = false; + a[0].wanted = true; + assert_eq!(pick(&a, Auto, Os::Other), Some(0), "even the iGPU, when asked for"); + // A wanted adapter that can't present is skipped, not an error. + a[0].surface_ok = false; + assert_eq!(pick(&a, Auto, Os::Other), Some(1)); + assert!(wanted_missed(&a, Some("iris"))); + assert!(!wanted_missed(&a, None)); + a[0].surface_ok = true; + assert!(!wanted_missed(&a, Some("iris"))); + // Among several wanted ones (same GPU on Vulkan and GL) the usual ranking decides. + let mut gl = [cand(0x10de, T::DiscreteGpu, B::Gl), cand(0x10de, T::DiscreteGpu, B::Vulkan)]; + gl.iter_mut().for_each(|c| c.wanted = true); + assert_eq!(pick(&gl, Auto, Os::Other), Some(1)); +} + +#[test] +fn an_adapter_request_applies_on_linux_outside_cpu_mode() { + let w = || Some("nvidia".to_string()); + assert_eq!(applicable_adapter(w(), Auto, true), w()); + assert_eq!(applicable_adapter(w(), Vulkan, true), w()); + assert_eq!(applicable_adapter(w(), Cpu, true), None); + assert_eq!(applicable_adapter(w(), Auto, false), None, "Windows and macOS keep their own selection"); + assert_eq!(applicable_adapter(None, Auto, true), None); +} + +#[test] +fn an_adapter_override_keeps_its_own_process_only_when_it_applies() { + let on = |env, mode, linux| adapter_override_is_process_specific(env, mode, linux); + assert!(on(Some("nvidia"), RenderingMode::Auto, true)); + assert!(on(Some("nvidia"), RenderingMode::Gpu, true)); + assert!(!on(Some("nvidia"), RenderingMode::Cpu, true), "ignored in CPU mode"); + assert!(!on(Some("nvidia"), RenderingMode::Auto, false), "ignored off Linux"); + assert!(!on(Some(" "), RenderingMode::Auto, true)); + assert!(!on(None, RenderingMode::Auto, true)); +} + +#[test] +fn adapter_names_match_loosely_and_the_environment_wins() { + assert!(adapter_matches("NVIDIA GeForce RTX 5060 Ti", "nvidia")); + assert!(adapter_matches("Intel(R) Arc(tm) A370M Graphics (DG2)", " ARC A370M ")); + assert!(!adapter_matches("Intel(R) Iris(R) Xe Graphics (ADL GT2)", "arc")); + assert!(!adapter_matches("anything", "")); + assert!(!adapter_matches("anything", " ")); + assert_eq!(wanted_adapter(None, ""), None); + assert_eq!(wanted_adapter(Some(" "), "iris"), Some("iris".into())); + assert_eq!(wanted_adapter(Some("nvidia"), "iris"), Some("nvidia".into())); + assert_eq!(wanted_adapter(Some(&"x".repeat(1000)), "").map(|w| w.len()), Some(256)); +} + +#[test] +fn gpu_adapter_is_read_before_the_window_opens() { + let dir = std::env::temp_dir().join(format!("photocraft-gpu-adapter-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("preferences.json"); + let read = |json: &str| { + std::fs::write(&file, json).unwrap(); + read_gpu_adapter(Some(&file)) + }; + assert_eq!(read(r#"{"performance":{"gpuAdapter":"nvidia"}}"#), "nvidia"); + assert_eq!(read(r#"{"performance":{"gpuAdapter":7}}"#), ""); + assert_eq!(read(r#"{"performance":{}}"#), ""); + assert_eq!(read("not json"), ""); + assert_eq!(read_gpu_adapter(None), ""); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn intel_on_windows_defaults_to_dx12() { + use wgpu::{Backend as B, DeviceType as T}; + let intel = [cand(INTEL, T::IntegratedGpu, B::Vulkan), cand(INTEL, T::IntegratedGpu, B::Dx12), cand(INTEL, T::IntegratedGpu, B::Gl)]; + let i = pick(&intel, Auto, Os::Windows).unwrap(); + assert_eq!(intel[i].backend, B::Dx12); + assert_eq!(dx12_default_applied(&intel, i, Os::Windows, false), Some("Intel")); + // Elsewhere (and for other vendors) Vulkan stays first. + assert_eq!(intel[pick(&intel, Auto, Os::Other).unwrap()].backend, B::Vulkan); + let nv = [cand(0x10de, T::DiscreteGpu, B::Dx12), cand(0x10de, T::DiscreteGpu, B::Vulkan)]; + let i = pick(&nv, Auto, Os::Windows).unwrap(); + assert_eq!(nv[i].backend, B::Vulkan); + assert_eq!(dx12_default_applied(&nv, i, Os::Windows, false), None); + // Intel iGPU + discrete GPU: the discrete one wins (high performance), on Vulkan. + let hybrid = [intel[0], intel[1], nv[1]]; + assert_eq!(pick(&hybrid, Auto, Os::Windows), Some(2)); + // Adapters that can't present lose to ones that can. + let mut only = [cand(0x10de, T::DiscreteGpu, B::Vulkan), intel[1]]; + only[0].surface_ok = false; + assert_eq!(pick(&only, Auto, Os::Windows), Some(1)); + assert_eq!(pick(&[], Auto, Os::Windows), None); +} + +/// #7537: on Windows on ARM the Adreno Vulkan driver lost the device mid-session and took the +/// window with it; DX12 on the same machine didn't. DXGI and Vulkan report different vendor ids. +#[test] +fn qualcomm_on_windows_defaults_to_dx12() { + use wgpu::{Backend as B, DeviceType as T}; + let adreno = [cand(QUALCOMM, T::IntegratedGpu, B::Vulkan), cand(QUALCOMM_DXGI, T::IntegratedGpu, B::Dx12)]; + let i = pick(&adreno, Auto, Os::Windows).unwrap(); + assert_eq!(adreno[i].backend, B::Dx12); + assert_eq!(dx12_default_applied(&adreno, i, Os::Windows, false), Some("Qualcomm")); + // Only Vulkan offered: still Vulkan, and no note. + assert_eq!(pick(&adreno[..1], Auto, Os::Windows), Some(0)); + assert_eq!(dx12_default_applied(&adreno, 0, Os::Windows, false), None); + // An Intel Vulkan adapter doesn't make a Qualcomm DX12 pick "the default". + let mixed = [cand(INTEL, T::IntegratedGpu, B::Vulkan), adreno[1]]; + assert_eq!(dx12_default_applied(&mixed, 1, Os::Windows, false), None); + // Vulkan left out of the instance (an Intel adapter was listed) speaks only for Intel. + assert_eq!(dx12_default_applied(&adreno[1..], 0, Os::Windows, true), None); + // Elsewhere Vulkan stays first. + assert_eq!(adreno[pick(&adreno, Auto, Os::Other).unwrap()].backend, B::Vulkan); +} + +/// #4: an instance with Vulkan loads the Intel Vulkan driver, which crashed at startup, before +/// the selector picks Intel's DX12 adapter. With an Intel adapter in the DX12 list, `auto` on +/// Windows creates the instance without Vulkan. +#[test] +fn auto_on_windows_with_an_intel_adapter_leaves_vulkan_out_of_the_instance() { + use wgpu::{Backend as B, DeviceType as T}; + const NVIDIA: u32 = 0x10de; + const AMD: u32 = 0x1002; + const WARP: u32 = 0x1414; + let auto = plan(Auto, None, None, false, Os::Windows); + let dx12_gl = Some(wgpu::Backends::DX12 | wgpu::Backends::GL); + assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![INTEL, WARP]), dx12_gl); + // Intel iGPU + discrete GPU: the discrete GPU is then used on DX12. + assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![NVIDIA, INTEL, WARP]), dx12_gl); + // No Intel adapter: egui's default backends, Vulkan included. + assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![NVIDIA, WARP]), None); + assert_eq!(windows_auto_backends(&auto, Os::Windows, || vec![AMD]), None); + assert_eq!(windows_auto_backends(&auto, Os::Windows, Vec::new), None); + // `WGPU_BACKEND`, `--safe-gpu`, a chosen backend, a crash fallback and other platforms + // don't list the DX12 adapters at all. + let not_listed = || -> Vec { panic!("DX12 adapters listed") }; + for (p, os) in [ + (plan(Auto, None, Some("vulkan"), false, Os::Windows), Os::Windows), + (plan(Auto, None, None, true, Os::Windows), Os::Windows), + (plan(Vulkan, None, None, false, Os::Windows), Os::Windows), + (plan(Auto, Some(&crashed("auto", "vulkan")), None, false, Os::Windows), Os::Windows), + (plan(Auto, None, None, false, Os::Other), Os::Other), + (plan(Auto, None, None, false, Os::Mac), Os::Mac), + ] { + assert_eq!(windows_auto_backends(&p, os, not_listed), None, "{p:?}"); + } + // Without Vulkan adapters to compare with, System Info still names the Intel default. + let listed = [cand(INTEL, T::IntegratedGpu, B::Dx12), cand(WARP, T::Cpu, B::Dx12), cand(INTEL, T::IntegratedGpu, B::Gl)]; + let i = pick(&listed, Auto, Os::Windows).unwrap(); + assert_eq!(i, 0); + assert_eq!(dx12_default_applied(&listed, i, Os::Windows, true), Some("Intel")); + assert_eq!(dx12_default_applied(&listed, i, Os::Windows, false), None); +} + +#[test] +fn cpu_prefers_software_adapters() { + use wgpu::{Backend as B, DeviceType as T}; + let a = [cand(INTEL, T::IntegratedGpu, B::Dx12), cand(0x1414, T::Cpu, B::Dx12)]; + assert_eq!(pick(&a, Cpu, Os::Windows), Some(1)); + // No software adapter: still something. + assert_eq!(pick(&a[..1], Cpu, Os::Windows), Some(0)); +} + +/// #1337: on Linux with NVIDIA, the only GL adapter (NVIDIA's EGL) can't present, so CPU mode +/// found no adapter and never started. GL still wins whenever it can present. +#[test] +fn cpu_on_linux_falls_back_to_vulkan_only_when_gl_cannot_present() { + use wgpu::{Backend as B, DeviceType as T}; + const NVIDIA: u32 = 0x10de; + let llvmpipe = cand(0x10005, T::Cpu, B::Gl); + let nvidia_gl = cand(NVIDIA, T::DiscreteGpu, B::Gl); + let nvidia_vk = cand(NVIDIA, T::DiscreteGpu, B::Vulkan); + let lavapipe = cand(0x10005, T::Cpu, B::Vulkan); + // GL presents: same choice as GL-only, software first, then hardware GL over any Vulkan. + assert_eq!(pick(&[nvidia_vk, lavapipe, llvmpipe], Cpu, Os::Other), Some(2)); + assert_eq!(pick(&[nvidia_vk, lavapipe, nvidia_gl], Cpu, Os::Other), Some(2)); + // GL can't present: Vulkan for the window, software first. + let mut gl = nvidia_gl; + gl.surface_ok = false; + assert_eq!(pick(&[gl, nvidia_vk, lavapipe], Cpu, Os::Other), Some(2)); + assert_eq!(pick(&[gl, nvidia_vk], Cpu, Os::Other), Some(1)); + // Other backends rank as before. + assert_eq!(pick(&[nvidia_gl, nvidia_vk], Auto, Os::Other), Some(1)); +} + +/// #5191, #1788: a Windows VM offers VMware's SVGA3D over GL (`Other`) and WARP (`Cpu`, DX12). +/// GL drew a black window; WARP works. GL stays the last resort. +#[test] +fn windows_auto_prefers_warp_over_gl() { + use wgpu::{Backend as B, DeviceType as T}; + let svga_gl = cand(0x15ad, T::Other, B::Gl); + let warp = cand(0x1414, T::Cpu, B::Dx12); + assert_eq!(pick(&[svga_gl, warp], Auto, Os::Windows), Some(1)); + assert_eq!(pick(&[cand(INTEL, T::IntegratedGpu, B::Gl), warp], Auto, Os::Windows), Some(1)); + assert_eq!(pick(&[svga_gl], Auto, Os::Windows), Some(0)); + // Elsewhere GL keeps its rank. + assert_eq!(pick(&[svga_gl, warp], Auto, Os::Other), Some(0)); +} + +#[test] +fn adapters_must_present_even_when_none_support_the_surface() { + let mut a = cand(INTEL, wgpu::DeviceType::IntegratedGpu, wgpu::Backend::Dx12); + a.surface_ok = false; + assert_eq!(pick(&[a], Auto, Os::Windows), None); + assert_eq!(pick(&[a], Cpu, Os::Windows), None); +} + +#[test] +fn explicit_policy_overrides_legacy_cpu_backend() { + assert_eq!(plan_with_mode(Cpu, RenderingMode::Gpu, None, None, false, Os::Mac).backend, Auto); + assert_eq!(plan_with_mode(Metal, RenderingMode::Cpu, None, None, false, Os::Mac).backend, Cpu); + assert_eq!(plan_with_mode(Auto, RenderingMode::Gpu, None, None, true, Os::Mac).backend, Cpu); +} + +#[test] +fn marker_round_trip_and_lenient_parse() { + let m = + Marker { backend: "auto".into(), adapter: "A \"quoted\" GPU".into(), adapter_backend: "vulkan".into(), driver: "1.2".into(), version: "0.1".into() }; + assert_eq!(Marker::parse(&m.to_json()), m); + assert_eq!(Marker::parse(""), Marker::default()); + assert_eq!(Marker::parse("[1,2]").tried(), Some(Auto)); + assert_eq!(Marker::parse(r#"{"backend": 7}"#).tried(), Some(Auto)); + assert_eq!(Marker::parse(r#"{"backend": "env:dx12"}"#).tried(), None); + let long = format!(r#"{{"adapter": "{}"}}"#, "x".repeat(10_000)); + assert_eq!(Marker::parse(&long).adapter.len(), 256); +} + +#[test] +fn a_failed_start_keeps_its_marker_only_when_a_safer_backend_exists() { + // GPU backends move down the chain on the next start. + assert!(keep_marker_after_error(&plan(Auto, None, None, false, Os::Other), Os::Other)); + assert!(keep_marker_after_error(&plan(Gl, None, None, false, Os::Other), Os::Other)); + assert!(keep_marker_after_error(&plan(Dx12, None, None, false, Os::Windows), Os::Windows)); + assert!(keep_marker_after_error(&plan(Auto, None, None, false, Os::Mac), Os::Mac)); + // The CPU path is the end of every chain, including the `--safe-gpu` retry. + for os in [Os::Windows, Os::Mac, Os::Other] { + assert!(!keep_marker_after_error(&plan(Cpu, None, None, false, os), os)); + assert!(!keep_marker_after_error(&plan(Auto, None, None, true, os), os)); + } + // `WGPU_BACKEND` is the user's choice; no plan reads its marker. + assert!(!keep_marker_after_error(&plan(Auto, None, Some("vulkan"), false, Os::Other), Os::Other)); +} + +/// A failed CPU start (no usable GL adapter under XWayland) left a `cpu` marker, so every +/// later start was planned on CPU and failed the same way until the marker was deleted by hand. +#[test] +fn a_failed_cpu_start_does_not_pin_later_starts() { + let dir = temp_dir("cpu-error"); + let (_, s) = Sentinel::begin(&dir); + let mut s = s.expect("sentinel"); + let failed = plan(Auto, None, None, true, Os::Other); + s.write(Marker { backend: failed.backend.name().into(), ..Default::default() }).unwrap(); + // eframe returned an error: what `main` does with the marker. + if keep_marker_after_error(&failed, Os::Other) { + drop(s); + } else { + s.finish(); + } + let (prev, _s) = begin_when_unlocked(&dir); + assert_eq!(prev, Previous::Clean); + assert_eq!(plan(Auto, prev.crashed(), None, false, Os::Other).backend, Auto); + let _ = std::fs::remove_dir_all(&dir); +} + +fn temp_dir(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("photocraft-gpu-startup-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d +} + +/// `Sentinel::begin`, called again up to 50 times, 10 ms apart, while it returns +/// `Previous::Busy`. Other tests in this binary spawn processes: between fork and exec a child +/// briefly shares the marker's flock, so `begin` can see the lock as busy just after a test +/// drops its sentinel. +fn begin_when_unlocked(dir: &Path) -> (Previous, Option) { + let (mut prev, mut s) = Sentinel::begin(dir); + for _ in 0..50 { + if prev != Previous::Busy { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + (prev, s) = Sentinel::begin(dir); + } + (prev, s) +} + +#[test] +fn sentinel_detects_a_crash_and_clears_on_success() { + let dir = temp_dir("cycle"); + // First launch: nothing left behind. + let (prev, s) = Sentinel::begin(&dir); + assert_eq!(prev, Previous::Clean); + let mut s = s.expect("sentinel"); + s.write(Marker { backend: "auto".into(), ..Default::default() }).unwrap(); + s.write(Marker { backend: "auto".into(), adapter: "GPU".into(), adapter_backend: "vulkan".into(), ..Default::default() }).unwrap(); + // While it is starting, a second instance sees it busy, not crashed. + let (busy, none) = Sentinel::begin(&dir); + assert_eq!(busy, Previous::Busy); + assert!(none.is_none()); + // The process dies in the driver: the lock goes, the marker stays. + drop(s); + let (prev, s) = begin_when_unlocked(&dir); + let m = prev.crashed().cloned().expect("crash detected"); + assert_eq!((m.adapter.as_str(), m.tried()), ("GPU", Some(Vulkan))); + // This start succeeds: the next one finds nothing. + let mut s = s.expect("sentinel"); + s.write(Marker { backend: "dx12".into(), ..Default::default() }).unwrap(); + s.finish(); + assert!(!dir.join(MARKER_FILE).exists()); + let (prev, _s) = Sentinel::begin(&dir); + assert_eq!(prev, Previous::Clean); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn begin_when_unlocked_waits_for_a_briefly_held_lock() { + let dir = temp_dir("shared-lock"); + let (_, s) = Sentinel::begin(&dir); + let mut s = s.expect("sentinel"); + s.write(Marker { backend: "vulkan".into(), ..Default::default() }).unwrap(); + // After the start dies, a second handle on the marker holds the lock for 50 ms, as a + // spawned child's copy of the descriptor does until the child calls exec. + let held = File::open(dir.join(MARKER_FILE)).unwrap(); + drop(s); + held.lock().unwrap(); + assert_eq!(Sentinel::begin(&dir).0, Previous::Busy); + let release = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(50)); + held.unlock().unwrap(); + }); + let (prev, s) = begin_when_unlocked(&dir); + release.join().unwrap(); + assert_eq!(prev.crashed().map(|m| m.backend.as_str()), Some("vulkan")); + s.expect("sentinel").finish(); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn returned_non_graphics_errors_do_not_trigger_backend_recovery() { + let cases = [ + ("success", Ok(()), false), + ("app-error", Err(eframe::Error::AppCreation(Box::new(std::io::Error::other("app setup failed")))), false), + ("gpu-error", Err(eframe::Error::Wgpu(egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no adapter".into()))), true), + ]; + for (name, result, keep) in cases { + let dir = temp_dir(name); + let (_, s) = Sentinel::begin(&dir); + let mut s = s.expect("sentinel"); + s.write(Marker { backend: "vulkan".into(), ..Default::default() }).unwrap(); + if keep_marker_after_run(&result) { + drop(s); + } else { + s.finish(); + } + let (previous, s) = begin_when_unlocked(&dir); + assert_eq!(previous.crashed().is_some(), keep, "{name}: {result:?}"); + if !keep { + assert_eq!(plan(Vulkan, previous.crashed(), None, false, Os::Other).backend, Vulkan); + } + s.expect("sentinel").finish(); + let _ = std::fs::remove_dir_all(&dir); + } +} + +#[test] +fn unwritable_config_dir_is_not_fatal() { + let dir = temp_dir("file"); + std::fs::create_dir_all(dir.parent().unwrap()).unwrap(); + std::fs::write(&dir, b"not a directory").unwrap(); + let (prev, s) = Sentinel::begin(&dir.join("sub")); + assert_eq!(prev, Previous::Clean); + assert!(s.is_none()); + let _ = std::fs::remove_file(&dir); +} + +#[test] +fn prefs_are_read_leniently() { + let dir = temp_dir("prefs"); + std::fs::create_dir_all(&dir).unwrap(); + let p = dir.join("preferences.json"); + assert_eq!(read_rendering_prefs(None), (Auto, RenderingMode::Auto)); + assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); + std::fs::write(&p, r#"{"performance": {"gpuBackend": "dx12", "useGpu": false}, "interface": {}}"#).unwrap(); + assert_eq!(read_rendering_prefs(Some(&p)), (Dx12, RenderingMode::Cpu)); + std::fs::write(&p, r#"{"performance": {"gpuBackend": "quantum"}}"#).unwrap(); + assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); + std::fs::write(&p, r#"{"performance": {"useGpu": false, "renderingMode": "gpu"}}"#).unwrap(); + assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Gpu)); + std::fs::write(&p, "{not json").unwrap(); + assert_eq!(read_rendering_prefs(Some(&p)), (Auto, RenderingMode::Auto)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// #712: never a `dxcompiler.dll` found through the DLL search path (current directory, PATH). +#[test] +fn dx12_compiler_is_fxc_or_dxc_beside_the_exe() { + use wgpu::Dx12Compiler as C; + let dir = temp_dir("dxc"); + std::fs::create_dir_all(&dir).unwrap(); + assert!(matches!(dx12_compiler(None, None), C::Fxc)); + assert!(matches!(dx12_compiler(None, Some(&dir)), C::Fxc)); + std::fs::write(dir.join("dxcompiler.dll"), b"MZ").unwrap(); + let expected = dir.join("dxcompiler.dll"); + assert!(matches!(dx12_compiler(None, Some(&dir)), C::DynamicDxc { dxc_path } if Path::new(&dxc_path) == expected)); + // An explicit WGPU_DX12_COMPILER wins; an unknown value is ignored. + assert!(matches!(dx12_compiler(Some(" FXC "), Some(&dir)), C::Fxc)); + assert!(matches!(dx12_compiler(Some("dxc"), None), C::DynamicDxc { dxc_path } if dxc_path == "dxcompiler.dll")); + assert!(matches!(dx12_compiler(Some("quantum"), None), C::Fxc)); + let _ = std::fs::remove_dir_all(&dir); + + // The app's setup replaces wgpu's default (`Auto`: DXC by name from the search path). + let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); + let plan = plan(Auto, None, None, false, Os::Windows); + configure(&mut setup, &plan, Os::Windows, None, Arc::new(Mutex::new(None)), Arc::default()); + let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") }; + if std::env::var_os("WGPU_DX12_COMPILER").is_none() { + let safe = match &create.instance_descriptor.backend_options.dx12.shader_compiler { + C::Fxc => true, + C::DynamicDxc { dxc_path } => Path::new(dxc_path).is_absolute(), + C::StaticDxc | C::Auto => false, + }; + assert!(safe, "{:?}", create.instance_descriptor.backend_options.dx12.shader_compiler); + } +} + +#[test] +fn intel_macs_skip_the_indirect_validation_shaders() { + // Metal's compiler crashed on them on Intel Iris Pro, losing the device in every mode (#3107). + assert!(skips_indirect_validation(Os::Mac, true)); + // Apple silicon, Windows and Linux keep wgpu's validation. + for (os, intel) in [(Os::Mac, false), (Os::Windows, true), (Os::Other, true), (Os::Other, false)] { + assert!(!skips_indirect_validation(os, intel), "{os:?} intel={intel}"); + } + for (os, safe_gpu) in [(Os::Windows, false), (Os::Other, true), (Os::Other, false)] { + let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); + let egui_wgpu::WgpuSetup::CreateNew(before) = &setup else { panic!("a new instance") }; + let before = before.instance_descriptor.flags; + configure(&mut setup, &plan(Auto, None, None, safe_gpu, os), os, None, Arc::new(Mutex::new(None)), Arc::default()); + let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") }; + assert_eq!(create.instance_descriptor.flags, before, "{os:?}: flags untouched"); + } + if cfg!(target_arch = "x86_64") && std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() { + let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); + configure(&mut setup, &plan(Auto, None, None, false, Os::Mac), Os::Mac, None, Arc::new(Mutex::new(None)), Arc::default()); + let egui_wgpu::WgpuSetup::CreateNew(create) = &setup else { panic!("a new instance") }; + assert!(!create.instance_descriptor.flags.contains(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL)); + } +} From 1dc1a17690c6f0b9d2990fa573e86ef270761907 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:18:04 +0000 Subject: [PATCH 133/259] refactor(xtask): move corpus.rs tests to corpus/tests.rs --- xtask/src/corpus.rs | 333 +------------------------------------- xtask/src/corpus/tests.rs | 330 +++++++++++++++++++++++++++++++++++++ 2 files changed, 331 insertions(+), 332 deletions(-) create mode 100644 xtask/src/corpus/tests.rs diff --git a/xtask/src/corpus.rs b/xtask/src/corpus.rs index 4cd276d6c4..4408808642 100644 --- a/xtask/src/corpus.rs +++ b/xtask/src/corpus.rs @@ -468,335 +468,4 @@ pub fn test_cmd(args: &[&str]) -> Result<(), String> { } #[cfg(test)] -mod tests { - use super::*; - - /// The flags each pinned corpus is fetched with by `fetch_all(local, update)`. - fn calls(local: bool, update: bool) -> Vec<(&'static str, bool)> { - let mut seen = Vec::new(); - let r = fetch_pinned(local, update, |c, _, u| { - seen.push((c.name, u)); - Ok(()) - }); - assert_eq!(r, Ok(())); - seen - } - - #[test] - fn all_with_update_manifest_updates_every_pinned_corpus() { - for local in [false, true] { - let seen = calls(local, true); - assert_eq!(seen.len(), corpus_pins::ALL.len()); - assert!(seen.iter().all(|(_, u)| *u), "--all --update-manifest dropped the flag: {seen:?}"); - } - } - - #[test] - fn all_without_update_manifest_only_verifies() { - assert!(calls(false, false).iter().all(|(_, u)| !*u)); - } - - const FIXTURE_FILES: &[(&str, &[u8])] = &[("a.png", b"alpha"), ("b.png", b"beta"), ("PngSuite.LICENSE", b"fixture licence")]; - const FIXTURE_ARCHIVE: &[u8] = b"owned archive fixture"; - - struct Fixture(PathBuf); - - impl Fixture { - fn new() -> Self { - let id = PNGSUITE_STAGE_ID.fetch_add(1, Ordering::Relaxed); - let path = std::env::temp_dir().join(format!("photocraft-pngsuite-test-{}-{id}", std::process::id())); - std::fs::create_dir(&path).unwrap(); - Self(path) - } - - fn cache(&self) -> PathBuf { - self.0.join("pngsuite") - } - - fn old_cache(&self) { - std::fs::create_dir(self.cache()).unwrap(); - std::fs::write(self.cache().join("old.png"), b"old cache bytes").unwrap(); - } - - fn assert_old_cache(&self) { - assert_eq!(std::fs::read(self.cache().join("old.png")).unwrap(), b"old cache bytes"); - assert_eq!(std::fs::read_dir(&self.0).unwrap().count(), 1, "staging was not cleaned"); - } - } - - impl Drop for Fixture { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } - } - - fn fixture_manifest() -> String { - FIXTURE_FILES.iter().map(|(name, bytes)| format!("{} {name}\n", crate::sha256::hex(bytes))).collect() - } - - fn fixture_extract(_: &Path, files: &Path) -> Result<(), String> { - for (name, bytes) in FIXTURE_FILES { - std::fs::write(files.join(name), bytes).map_err(|e| e.to_string())?; - } - Ok(()) - } - - fn fixture_download(archive: &Path) -> Result<(), String> { - std::fs::write(archive, FIXTURE_ARCHIVE).map_err(|e| e.to_string()) - } - - fn fixture_fetch(corpus: &Path) -> Result<(), String> { - fetch_pngsuite_in(corpus, &crate::sha256::hex(FIXTURE_ARCHIVE), &fixture_manifest(), fixture_download, fixture_extract, |from, to| { - std::fs::rename(from, to) - }) - } - - #[test] - fn pngsuite_cache_checks_bytes_names_and_regular_files() { - let f = Fixture::new(); - std::fs::create_dir(f.cache()).unwrap(); - fixture_extract(Path::new("unused"), &f.cache()).unwrap(); - assert!(verify_pngsuite(&f.cache(), &fixture_manifest()).is_ok()); - std::fs::write(f.cache().join("a.png"), b"changed").unwrap(); - assert!(verify_pngsuite(&f.cache(), &fixture_manifest()).unwrap_err().contains("sha256 mismatch")); - fixture_extract(Path::new("unused"), &f.cache()).unwrap(); - std::fs::remove_file(f.cache().join("a.png")).unwrap(); - assert!(verify_pngsuite(&f.cache(), &fixture_manifest()).unwrap_err().contains("missing files")); - fixture_extract(Path::new("unused"), &f.cache()).unwrap(); - std::fs::write(f.cache().join("extra.png"), b"extra").unwrap(); - assert!(verify_pngsuite(&f.cache(), &fixture_manifest()).unwrap_err().contains("unexpected file")); - std::fs::remove_file(f.cache().join("extra.png")).unwrap(); - std::fs::remove_file(f.cache().join("a.png")).unwrap(); - std::fs::create_dir(f.cache().join("a.png")).unwrap(); - assert!(verify_pngsuite(&f.cache(), &fixture_manifest()).unwrap_err().contains("regular file")); - } - - #[test] - fn pngsuite_valid_cache_needs_no_download_or_extraction() { - let f = Fixture::new(); - fixture_fetch(&f.0).unwrap(); - fetch_pngsuite_in( - &f.0, - "unused", - &fixture_manifest(), - |_| panic!("valid cache downloaded"), - |_, _| panic!("valid cache extracted"), - |_, _| panic!("valid cache renamed"), - ) - .unwrap(); - } - - #[test] - fn pngsuite_repairs_unverified_175_file_cache_and_removes_extras() { - let f = Fixture::new(); - std::fs::create_dir(f.cache()).unwrap(); - for i in 0..175 { - std::fs::write(f.cache().join(format!("fake-{i}.png")), b"not a PNG").unwrap(); - } - fixture_fetch(&f.0).unwrap(); - assert!(verify_pngsuite(&f.cache(), &fixture_manifest()).is_ok()); - assert_eq!(std::fs::read_dir(f.cache()).unwrap().count(), FIXTURE_FILES.len()); - assert_eq!(std::fs::read_dir(&f.0).unwrap().count(), 1); - } - - #[test] - fn pngsuite_unexpected_or_truncated_archive_never_reaches_extractor() { - for bad in [b"unexpected".as_slice(), &FIXTURE_ARCHIVE[..4]] { - let f = Fixture::new(); - f.old_cache(); - let e = fetch_pngsuite_in( - &f.0, - &crate::sha256::hex(FIXTURE_ARCHIVE), - &fixture_manifest(), - |a| std::fs::write(a, bad).map_err(|e| e.to_string()), - |_, _| panic!("unverified archive reached extractor"), - |_, _| panic!("unverified archive reached installation"), - ) - .unwrap_err(); - assert!(e.contains("archive sha256 mismatch")); - f.assert_old_cache(); - } - } - - #[test] - fn pngsuite_download_or_extraction_failure_keeps_old_cache() { - let f = Fixture::new(); - f.old_cache(); - assert!( - fetch_pngsuite_in( - &f.0, - "unused", - &fixture_manifest(), - |_| Err("offline".into()), - |_, _| panic!("failed download extracted"), - |_, _| panic!("failed download installed") - ) - .unwrap_err() - .contains("offline") - ); - f.assert_old_cache(); - assert!( - fetch_pngsuite_in( - &f.0, - &crate::sha256::hex(FIXTURE_ARCHIVE), - &fixture_manifest(), - fixture_download, - |_, files| { - std::fs::write(files.join("partial.png"), b"partial").unwrap(); - Err("extract failed".into()) - }, - |_, _| panic!("failed extraction installed") - ) - .unwrap_err() - .contains("extract failed") - ); - f.assert_old_cache(); - for extra in [false, true] { - let e = fetch_pngsuite_in( - &f.0, - &crate::sha256::hex(FIXTURE_ARCHIVE), - &fixture_manifest(), - fixture_download, - |a, files| { - fixture_extract(a, files)?; - if extra { - std::fs::write(files.join("extra.png"), b"extra").unwrap(); - } else { - std::fs::remove_file(files.join("a.png")).unwrap(); - } - Ok(()) - }, - |_, _| panic!("unverified extraction installed"), - ) - .unwrap_err(); - assert!(e.contains(if extra { "unexpected file" } else { "missing files" })); - f.assert_old_cache(); - } - } - - #[test] - fn pngsuite_failed_installation_restores_old_cache() { - for fail_backup in [false, true] { - let f = Fixture::new(); - f.old_cache(); - let e = fetch_pngsuite_in(&f.0, &crate::sha256::hex(FIXTURE_ARCHIVE), &fixture_manifest(), fixture_download, fixture_extract, |from, to| { - if (fail_backup && from == f.cache()) || (!fail_backup && from.file_name().is_some_and(|n| n == "files")) { - Err(std::io::Error::other("injected rename failure")) - } else { - std::fs::rename(from, to) - } - }) - .unwrap_err(); - assert!(e.contains("injected rename failure")); - f.assert_old_cache(); - } - } - - #[test] - fn pngsuite_failed_rollback_retains_and_names_the_backup() { - let f = Fixture::new(); - f.old_cache(); - let e = fetch_pngsuite_in(&f.0, &crate::sha256::hex(FIXTURE_ARCHIVE), &fixture_manifest(), fixture_download, fixture_extract, |from, to| { - if from == f.cache() { std::fs::rename(from, to) } else { Err(std::io::Error::other("injected install and rollback failure")) } - }) - .unwrap_err(); - let stage = std::fs::read_dir(&f.0).unwrap().next().unwrap().unwrap().path(); - let backup = stage.join("previous"); - assert!(e.contains(&backup.display().to_string()), "{e}"); - assert_eq!(std::fs::read(backup.join("old.png")).unwrap(), b"old cache bytes"); - std::fs::rename(backup, f.cache()).unwrap(); - } - - #[test] - fn pngsuite_reads_are_bounded_and_malformed_manifests_are_rejected() { - let f = Fixture::new(); - let file = f.0.join("large"); - std::fs::File::create(&file).unwrap().set_len(PNGSUITE_MAX_ARCHIVE_BYTES + 1).unwrap(); - assert!(pngsuite_bytes(&file, PNGSUITE_MAX_ARCHIVE_BYTES).unwrap_err().contains("regular file")); - for malformed in ["", "invalid", "00 a.png", &format!("{} ../outside\n", crate::sha256::hex(b""))] { - assert!(verify_pngsuite(&f.0, malformed).is_err()); - } - } - - #[test] - fn pngsuite_download_copy_accepts_boundary_and_never_writes_excess() { - let limit = PNGSUITE_MAX_ARCHIVE_BYTES as usize; - for len in [limit - 1, limit, limit + 1, limit * 2] { - let data = vec![0xa5; len]; - let mut out = Vec::new(); - let result = copy_pngsuite_download(&mut std::io::Cursor::new(&data), &mut out); - assert_eq!(result.is_ok(), len <= limit); - assert_eq!(out, data[..len.min(limit)]); - } - } - - // The ordinary test invocation returns immediately. Only this test's child command - // enables emission; it stays alive so cleanup must kill and reap that particular child. - #[test] - fn pngsuite_stream_fixture() { - if std::env::var_os("PHOTOCRAFT_PNGSUITE_STREAM_TEST").is_some() { - let mut out = std::io::stdout().lock(); - for _ in 0..256 { - let _ = out.write_all(&[0xa5; 8192]); - } - std::thread::park(); - } - } - - fn stream_child() -> Child { - Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "corpus::tests::pngsuite_stream_fixture", "--nocapture"]) - .env("PHOTOCRAFT_PNGSUITE_STREAM_TEST", "1") - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .spawn() - .unwrap() - } - - #[test] - fn pngsuite_oversize_and_io_failures_kill_and_reap_only_the_download_child() { - struct FailedRead; - impl Read for FailedRead { - fn read(&mut self, _: &mut [u8]) -> std::io::Result { - Err(std::io::Error::other("injected read failure")) - } - } - struct FailedWrite; - impl Write for FailedWrite { - fn write(&mut self, _: &[u8]) -> std::io::Result { - Err(std::io::Error::other("injected write failure")) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - let mut child = stream_child(); - let stdout = child.stdout.take().unwrap(); - let mut out = Vec::new(); - assert!(finish_pngsuite_download(&mut child, stdout, &mut out).unwrap_err().contains("archive exceeds")); - assert_eq!(out.len() as u64, PNGSUITE_MAX_ARCHIVE_BYTES); - assert!(child.try_wait().unwrap().is_some()); - - let mut child = stream_child(); - assert!(child.try_wait().unwrap().is_none()); - assert!(finish_pngsuite_download(&mut child, FailedRead, &mut Vec::new()).unwrap_err().contains("injected read failure")); - assert!(child.try_wait().unwrap().is_some()); - - let mut child = stream_child(); - let stdout = child.stdout.take().unwrap(); - assert!(finish_pngsuite_download(&mut child, stdout, &mut FailedWrite).unwrap_err().contains("injected write failure")); - assert!(child.try_wait().unwrap().is_some()); - } - - #[cfg(unix)] - #[test] - fn pngsuite_cache_rejects_symlinks_even_when_target_bytes_match() { - let f = Fixture::new(); - std::fs::create_dir(f.cache()).unwrap(); - fixture_extract(Path::new("unused"), &f.cache()).unwrap(); - std::fs::write(f.0.join("target"), b"alpha").unwrap(); - std::fs::remove_file(f.cache().join("a.png")).unwrap(); - std::os::unix::fs::symlink(f.0.join("target"), f.cache().join("a.png")).unwrap(); - assert!(verify_pngsuite(&f.cache(), &fixture_manifest()).unwrap_err().contains("regular file")); - } -} +mod tests; diff --git a/xtask/src/corpus/tests.rs b/xtask/src/corpus/tests.rs new file mode 100644 index 0000000000..b1c7b515a9 --- /dev/null +++ b/xtask/src/corpus/tests.rs @@ -0,0 +1,330 @@ +use super::*; + +/// The flags each pinned corpus is fetched with by `fetch_all(local, update)`. +fn calls(local: bool, update: bool) -> Vec<(&'static str, bool)> { + let mut seen = Vec::new(); + let r = fetch_pinned(local, update, |c, _, u| { + seen.push((c.name, u)); + Ok(()) + }); + assert_eq!(r, Ok(())); + seen +} + +#[test] +fn all_with_update_manifest_updates_every_pinned_corpus() { + for local in [false, true] { + let seen = calls(local, true); + assert_eq!(seen.len(), corpus_pins::ALL.len()); + assert!(seen.iter().all(|(_, u)| *u), "--all --update-manifest dropped the flag: {seen:?}"); + } +} + +#[test] +fn all_without_update_manifest_only_verifies() { + assert!(calls(false, false).iter().all(|(_, u)| !*u)); +} + +const FIXTURE_FILES: &[(&str, &[u8])] = &[("a.png", b"alpha"), ("b.png", b"beta"), ("PngSuite.LICENSE", b"fixture licence")]; +const FIXTURE_ARCHIVE: &[u8] = b"owned archive fixture"; + +struct Fixture(PathBuf); + +impl Fixture { + fn new() -> Self { + let id = PNGSUITE_STAGE_ID.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!("photocraft-pngsuite-test-{}-{id}", std::process::id())); + std::fs::create_dir(&path).unwrap(); + Self(path) + } + + fn cache(&self) -> PathBuf { + self.0.join("pngsuite") + } + + fn old_cache(&self) { + std::fs::create_dir(self.cache()).unwrap(); + std::fs::write(self.cache().join("old.png"), b"old cache bytes").unwrap(); + } + + fn assert_old_cache(&self) { + assert_eq!(std::fs::read(self.cache().join("old.png")).unwrap(), b"old cache bytes"); + assert_eq!(std::fs::read_dir(&self.0).unwrap().count(), 1, "staging was not cleaned"); + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn fixture_manifest() -> String { + FIXTURE_FILES.iter().map(|(name, bytes)| format!("{} {name}\n", crate::sha256::hex(bytes))).collect() +} + +fn fixture_extract(_: &Path, files: &Path) -> Result<(), String> { + for (name, bytes) in FIXTURE_FILES { + std::fs::write(files.join(name), bytes).map_err(|e| e.to_string())?; + } + Ok(()) +} + +fn fixture_download(archive: &Path) -> Result<(), String> { + std::fs::write(archive, FIXTURE_ARCHIVE).map_err(|e| e.to_string()) +} + +fn fixture_fetch(corpus: &Path) -> Result<(), String> { + fetch_pngsuite_in(corpus, &crate::sha256::hex(FIXTURE_ARCHIVE), &fixture_manifest(), fixture_download, fixture_extract, |from, to| { + std::fs::rename(from, to) + }) +} + +#[test] +fn pngsuite_cache_checks_bytes_names_and_regular_files() { + let f = Fixture::new(); + std::fs::create_dir(f.cache()).unwrap(); + fixture_extract(Path::new("unused"), &f.cache()).unwrap(); + assert!(verify_pngsuite(&f.cache(), &fixture_manifest()).is_ok()); + std::fs::write(f.cache().join("a.png"), b"changed").unwrap(); + assert!(verify_pngsuite(&f.cache(), &fixture_manifest()).unwrap_err().contains("sha256 mismatch")); + fixture_extract(Path::new("unused"), &f.cache()).unwrap(); + std::fs::remove_file(f.cache().join("a.png")).unwrap(); + assert!(verify_pngsuite(&f.cache(), &fixture_manifest()).unwrap_err().contains("missing files")); + fixture_extract(Path::new("unused"), &f.cache()).unwrap(); + std::fs::write(f.cache().join("extra.png"), b"extra").unwrap(); + assert!(verify_pngsuite(&f.cache(), &fixture_manifest()).unwrap_err().contains("unexpected file")); + std::fs::remove_file(f.cache().join("extra.png")).unwrap(); + std::fs::remove_file(f.cache().join("a.png")).unwrap(); + std::fs::create_dir(f.cache().join("a.png")).unwrap(); + assert!(verify_pngsuite(&f.cache(), &fixture_manifest()).unwrap_err().contains("regular file")); +} + +#[test] +fn pngsuite_valid_cache_needs_no_download_or_extraction() { + let f = Fixture::new(); + fixture_fetch(&f.0).unwrap(); + fetch_pngsuite_in( + &f.0, + "unused", + &fixture_manifest(), + |_| panic!("valid cache downloaded"), + |_, _| panic!("valid cache extracted"), + |_, _| panic!("valid cache renamed"), + ) + .unwrap(); +} + +#[test] +fn pngsuite_repairs_unverified_175_file_cache_and_removes_extras() { + let f = Fixture::new(); + std::fs::create_dir(f.cache()).unwrap(); + for i in 0..175 { + std::fs::write(f.cache().join(format!("fake-{i}.png")), b"not a PNG").unwrap(); + } + fixture_fetch(&f.0).unwrap(); + assert!(verify_pngsuite(&f.cache(), &fixture_manifest()).is_ok()); + assert_eq!(std::fs::read_dir(f.cache()).unwrap().count(), FIXTURE_FILES.len()); + assert_eq!(std::fs::read_dir(&f.0).unwrap().count(), 1); +} + +#[test] +fn pngsuite_unexpected_or_truncated_archive_never_reaches_extractor() { + for bad in [b"unexpected".as_slice(), &FIXTURE_ARCHIVE[..4]] { + let f = Fixture::new(); + f.old_cache(); + let e = fetch_pngsuite_in( + &f.0, + &crate::sha256::hex(FIXTURE_ARCHIVE), + &fixture_manifest(), + |a| std::fs::write(a, bad).map_err(|e| e.to_string()), + |_, _| panic!("unverified archive reached extractor"), + |_, _| panic!("unverified archive reached installation"), + ) + .unwrap_err(); + assert!(e.contains("archive sha256 mismatch")); + f.assert_old_cache(); + } +} + +#[test] +fn pngsuite_download_or_extraction_failure_keeps_old_cache() { + let f = Fixture::new(); + f.old_cache(); + assert!( + fetch_pngsuite_in( + &f.0, + "unused", + &fixture_manifest(), + |_| Err("offline".into()), + |_, _| panic!("failed download extracted"), + |_, _| panic!("failed download installed") + ) + .unwrap_err() + .contains("offline") + ); + f.assert_old_cache(); + assert!( + fetch_pngsuite_in( + &f.0, + &crate::sha256::hex(FIXTURE_ARCHIVE), + &fixture_manifest(), + fixture_download, + |_, files| { + std::fs::write(files.join("partial.png"), b"partial").unwrap(); + Err("extract failed".into()) + }, + |_, _| panic!("failed extraction installed") + ) + .unwrap_err() + .contains("extract failed") + ); + f.assert_old_cache(); + for extra in [false, true] { + let e = fetch_pngsuite_in( + &f.0, + &crate::sha256::hex(FIXTURE_ARCHIVE), + &fixture_manifest(), + fixture_download, + |a, files| { + fixture_extract(a, files)?; + if extra { + std::fs::write(files.join("extra.png"), b"extra").unwrap(); + } else { + std::fs::remove_file(files.join("a.png")).unwrap(); + } + Ok(()) + }, + |_, _| panic!("unverified extraction installed"), + ) + .unwrap_err(); + assert!(e.contains(if extra { "unexpected file" } else { "missing files" })); + f.assert_old_cache(); + } +} + +#[test] +fn pngsuite_failed_installation_restores_old_cache() { + for fail_backup in [false, true] { + let f = Fixture::new(); + f.old_cache(); + let e = fetch_pngsuite_in(&f.0, &crate::sha256::hex(FIXTURE_ARCHIVE), &fixture_manifest(), fixture_download, fixture_extract, |from, to| { + if (fail_backup && from == f.cache()) || (!fail_backup && from.file_name().is_some_and(|n| n == "files")) { + Err(std::io::Error::other("injected rename failure")) + } else { + std::fs::rename(from, to) + } + }) + .unwrap_err(); + assert!(e.contains("injected rename failure")); + f.assert_old_cache(); + } +} + +#[test] +fn pngsuite_failed_rollback_retains_and_names_the_backup() { + let f = Fixture::new(); + f.old_cache(); + let e = fetch_pngsuite_in(&f.0, &crate::sha256::hex(FIXTURE_ARCHIVE), &fixture_manifest(), fixture_download, fixture_extract, |from, to| { + if from == f.cache() { std::fs::rename(from, to) } else { Err(std::io::Error::other("injected install and rollback failure")) } + }) + .unwrap_err(); + let stage = std::fs::read_dir(&f.0).unwrap().next().unwrap().unwrap().path(); + let backup = stage.join("previous"); + assert!(e.contains(&backup.display().to_string()), "{e}"); + assert_eq!(std::fs::read(backup.join("old.png")).unwrap(), b"old cache bytes"); + std::fs::rename(backup, f.cache()).unwrap(); +} + +#[test] +fn pngsuite_reads_are_bounded_and_malformed_manifests_are_rejected() { + let f = Fixture::new(); + let file = f.0.join("large"); + std::fs::File::create(&file).unwrap().set_len(PNGSUITE_MAX_ARCHIVE_BYTES + 1).unwrap(); + assert!(pngsuite_bytes(&file, PNGSUITE_MAX_ARCHIVE_BYTES).unwrap_err().contains("regular file")); + for malformed in ["", "invalid", "00 a.png", &format!("{} ../outside\n", crate::sha256::hex(b""))] { + assert!(verify_pngsuite(&f.0, malformed).is_err()); + } +} + +#[test] +fn pngsuite_download_copy_accepts_boundary_and_never_writes_excess() { + let limit = PNGSUITE_MAX_ARCHIVE_BYTES as usize; + for len in [limit - 1, limit, limit + 1, limit * 2] { + let data = vec![0xa5; len]; + let mut out = Vec::new(); + let result = copy_pngsuite_download(&mut std::io::Cursor::new(&data), &mut out); + assert_eq!(result.is_ok(), len <= limit); + assert_eq!(out, data[..len.min(limit)]); + } +} + +// The ordinary test invocation returns immediately. Only this test's child command +// enables emission; it stays alive so cleanup must kill and reap that particular child. +#[test] +fn pngsuite_stream_fixture() { + if std::env::var_os("PHOTOCRAFT_PNGSUITE_STREAM_TEST").is_some() { + let mut out = std::io::stdout().lock(); + for _ in 0..256 { + let _ = out.write_all(&[0xa5; 8192]); + } + std::thread::park(); + } +} + +fn stream_child() -> Child { + Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "corpus::tests::pngsuite_stream_fixture", "--nocapture"]) + .env("PHOTOCRAFT_PNGSUITE_STREAM_TEST", "1") + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap() +} + +#[test] +fn pngsuite_oversize_and_io_failures_kill_and_reap_only_the_download_child() { + struct FailedRead; + impl Read for FailedRead { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + Err(std::io::Error::other("injected read failure")) + } + } + struct FailedWrite; + impl Write for FailedWrite { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(std::io::Error::other("injected write failure")) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut child = stream_child(); + let stdout = child.stdout.take().unwrap(); + let mut out = Vec::new(); + assert!(finish_pngsuite_download(&mut child, stdout, &mut out).unwrap_err().contains("archive exceeds")); + assert_eq!(out.len() as u64, PNGSUITE_MAX_ARCHIVE_BYTES); + assert!(child.try_wait().unwrap().is_some()); + + let mut child = stream_child(); + assert!(child.try_wait().unwrap().is_none()); + assert!(finish_pngsuite_download(&mut child, FailedRead, &mut Vec::new()).unwrap_err().contains("injected read failure")); + assert!(child.try_wait().unwrap().is_some()); + + let mut child = stream_child(); + let stdout = child.stdout.take().unwrap(); + assert!(finish_pngsuite_download(&mut child, stdout, &mut FailedWrite).unwrap_err().contains("injected write failure")); + assert!(child.try_wait().unwrap().is_some()); +} + +#[cfg(unix)] +#[test] +fn pngsuite_cache_rejects_symlinks_even_when_target_bytes_match() { + let f = Fixture::new(); + std::fs::create_dir(f.cache()).unwrap(); + fixture_extract(Path::new("unused"), &f.cache()).unwrap(); + std::fs::write(f.0.join("target"), b"alpha").unwrap(); + std::fs::remove_file(f.cache().join("a.png")).unwrap(); + std::os::unix::fs::symlink(f.0.join("target"), f.cache().join("a.png")).unwrap(); + assert!(verify_pngsuite(&f.cache(), &fixture_manifest()).unwrap_err().contains("regular file")); +} From a874637d1acbd5a39edd62a2e11a48a53ce96bea Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:18:52 +0000 Subject: [PATCH 134/259] chore: ignore only the top-level plan/ directory --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index f310f32921..0e71c973d8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ *~ -plan/ +/plan/ /target target/ /dist From da38654abd49e6929d69a48d4a21cf0a621bfe9b Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:34 +0000 Subject: [PATCH 135/259] refactor(algo): move shape_blur_tests.rs to blur2/shape_tests.rs --- crates/algo/src/blur2.rs | 1 - crates/algo/src/{shape_blur_tests.rs => blur2/shape_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/algo/src/{shape_blur_tests.rs => blur2/shape_tests.rs} (100%) diff --git a/crates/algo/src/blur2.rs b/crates/algo/src/blur2.rs index dc57f39adb..08b52f18a0 100644 --- a/crates/algo/src/blur2.rs +++ b/crates/algo/src/blur2.rs @@ -181,7 +181,6 @@ fn conv_spans(src: &Image, out: Rect, ctx: &Ctx, spans: &Spans) -> Vec { } #[cfg(test)] -#[path = "shape_blur_tests.rs"] mod shape_tests; // ---------- smart blur ---------- diff --git a/crates/algo/src/shape_blur_tests.rs b/crates/algo/src/blur2/shape_tests.rs similarity index 100% rename from crates/algo/src/shape_blur_tests.rs rename to crates/algo/src/blur2/shape_tests.rs From 4b796d139ec52d116ca0e4b50b5ff9e84c580c9f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:34 +0000 Subject: [PATCH 136/259] refactor(algo): move smart_blur_tests.rs to blur2/smart_tests.rs --- crates/algo/src/blur2.rs | 1 - crates/algo/src/{smart_blur_tests.rs => blur2/smart_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/algo/src/{smart_blur_tests.rs => blur2/smart_tests.rs} (100%) diff --git a/crates/algo/src/blur2.rs b/crates/algo/src/blur2.rs index 08b52f18a0..5096a9fb9a 100644 --- a/crates/algo/src/blur2.rs +++ b/crates/algo/src/blur2.rs @@ -361,7 +361,6 @@ fn smart_rows(src: &Image, out: Rect, inner: Rect } #[cfg(test)] -#[path = "smart_blur_tests.rs"] mod smart_tests; // ---------- lens blur ---------- diff --git a/crates/algo/src/smart_blur_tests.rs b/crates/algo/src/blur2/smart_tests.rs similarity index 100% rename from crates/algo/src/smart_blur_tests.rs rename to crates/algo/src/blur2/smart_tests.rs From 6275857616e4897c4a44b7be4b67c9190c901867 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:34 +0000 Subject: [PATCH 137/259] refactor(algo): move tests_iris.rs to gallery/tests.rs --- crates/algo/src/gallery.rs | 1 - crates/algo/src/{tests_iris.rs => gallery/tests.rs} | 1 - .../src/{tests_iris_reference.rs => gallery/tests/reference.rs} | 0 3 files changed, 2 deletions(-) rename crates/algo/src/{tests_iris.rs => gallery/tests.rs} (99%) rename crates/algo/src/{tests_iris_reference.rs => gallery/tests/reference.rs} (100%) diff --git a/crates/algo/src/gallery.rs b/crates/algo/src/gallery.rs index 53ed13d3b8..de42dcc0c0 100644 --- a/crates/algo/src/gallery.rs +++ b/crates/algo/src/gallery.rs @@ -15,7 +15,6 @@ use crate::image::{Image, premultiply}; use crate::{BlurPath, Ctx, FieldPin, IrisPin, SpinPin}; #[cfg(test)] -#[path = "tests_iris.rs"] mod tests; #[cfg(test)] diff --git a/crates/algo/src/tests_iris.rs b/crates/algo/src/gallery/tests.rs similarity index 99% rename from crates/algo/src/tests_iris.rs rename to crates/algo/src/gallery/tests.rs index 2d54c8f134..e822d7a938 100644 --- a/crates/algo/src/tests_iris.rs +++ b/crates/algo/src/gallery/tests.rs @@ -2,7 +2,6 @@ use super::*; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_raster::{Interrupt, Surface}; -#[path = "tests_iris_reference.rs"] mod reference; fn image(rect: Rect, ch: usize) -> Image { diff --git a/crates/algo/src/tests_iris_reference.rs b/crates/algo/src/gallery/tests/reference.rs similarity index 100% rename from crates/algo/src/tests_iris_reference.rs rename to crates/algo/src/gallery/tests/reference.rs From fe82c57039b0036604e7ad5c7cdbe45a8271cfe3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:34 +0000 Subject: [PATCH 138/259] refactor(algo): move tests_tilt_shift.rs to gallery/tilt_shift_tests.rs --- crates/algo/src/gallery.rs | 1 - .../src/{tests_tilt_shift.rs => gallery/tilt_shift_tests.rs} | 1 - .../tilt_shift_tests/reference.rs} | 0 3 files changed, 2 deletions(-) rename crates/algo/src/{tests_tilt_shift.rs => gallery/tilt_shift_tests.rs} (99%) rename crates/algo/src/{tests_tilt_shift_reference.rs => gallery/tilt_shift_tests/reference.rs} (100%) diff --git a/crates/algo/src/gallery.rs b/crates/algo/src/gallery.rs index de42dcc0c0..e0d2c44a9e 100644 --- a/crates/algo/src/gallery.rs +++ b/crates/algo/src/gallery.rs @@ -18,7 +18,6 @@ use crate::{BlurPath, Ctx, FieldPin, IrisPin, SpinPin}; mod tests; #[cfg(test)] -#[path = "tests_tilt_shift.rs"] mod tilt_shift_tests; /// Gaussian σ for a gallery blur amount in px. diff --git a/crates/algo/src/tests_tilt_shift.rs b/crates/algo/src/gallery/tilt_shift_tests.rs similarity index 99% rename from crates/algo/src/tests_tilt_shift.rs rename to crates/algo/src/gallery/tilt_shift_tests.rs index b82dd1c2c4..5d3ea66678 100644 --- a/crates/algo/src/tests_tilt_shift.rs +++ b/crates/algo/src/gallery/tilt_shift_tests.rs @@ -2,7 +2,6 @@ use super::*; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_raster::{Interrupt, Surface}; -#[path = "tests_tilt_shift_reference.rs"] mod reference; fn image(rect: Rect, ch: usize) -> Image { diff --git a/crates/algo/src/tests_tilt_shift_reference.rs b/crates/algo/src/gallery/tilt_shift_tests/reference.rs similarity index 100% rename from crates/algo/src/tests_tilt_shift_reference.rs rename to crates/algo/src/gallery/tilt_shift_tests/reference.rs From 7e52b713dd7bf2b811fe1634e3248461353df4f9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:34 +0000 Subject: [PATCH 139/259] refactor(compose): move cmyk_tests.rs to cmyk/tests.rs --- crates/compose/src/cmyk.rs | 1 - crates/compose/src/{cmyk_tests.rs => cmyk/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/compose/src/{cmyk_tests.rs => cmyk/tests.rs} (100%) diff --git a/crates/compose/src/cmyk.rs b/crates/compose/src/cmyk.rs index 52db6582d9..96a6df0ceb 100644 --- a/crates/compose/src/cmyk.rs +++ b/crates/compose/src/cmyk.rs @@ -712,5 +712,4 @@ pub fn render_cmyk_bands(doc: &Document, rect: Rect, band_rows: i32, mut sink } #[cfg(test)] -#[path = "cmyk_tests.rs"] mod tests; diff --git a/crates/compose/src/cmyk_tests.rs b/crates/compose/src/cmyk/tests.rs similarity index 100% rename from crates/compose/src/cmyk_tests.rs rename to crates/compose/src/cmyk/tests.rs From 93ae1101c9a188c248c3186ebff5c94a9ad0948f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 140/259] refactor(engine): move display_color_tests.rs to display_color/tests.rs --- crates/engine/src/display_color.rs | 1 - .../src/{display_color_tests.rs => display_color/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/engine/src/{display_color_tests.rs => display_color/tests.rs} (100%) diff --git a/crates/engine/src/display_color.rs b/crates/engine/src/display_color.rs index 49b36f9031..55a9c83ed9 100644 --- a/crates/engine/src/display_color.rs +++ b/crates/engine/src/display_color.rs @@ -464,5 +464,4 @@ impl ColorState { } #[cfg(test)] -#[path = "display_color_tests.rs"] mod tests; diff --git a/crates/engine/src/display_color_tests.rs b/crates/engine/src/display_color/tests.rs similarity index 100% rename from crates/engine/src/display_color_tests.rs rename to crates/engine/src/display_color/tests.rs From e4095cc3da0b8b424daac7a96cb56708ddce52e0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 141/259] refactor(engine): move jobs_tests.rs to jobs/tests.rs --- crates/engine/src/jobs.rs | 1 - crates/engine/src/{jobs_tests.rs => jobs/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/engine/src/{jobs_tests.rs => jobs/tests.rs} (100%) diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index ffa4db96cb..6799640bad 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -1109,7 +1109,6 @@ pub fn specs() -> Vec { } #[cfg(test)] -#[path = "jobs_tests.rs"] mod tests; #[cfg(test)] diff --git a/crates/engine/src/jobs_tests.rs b/crates/engine/src/jobs/tests.rs similarity index 100% rename from crates/engine/src/jobs_tests.rs rename to crates/engine/src/jobs/tests.rs From c4a3c259031820b85dba7f259a27d4359e18c60f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 142/259] refactor(engine): move flatten_cmyk_tests.rs to pixels/flatten_cmyk_tests.rs --- crates/engine/src/pixels.rs | 1 - crates/engine/src/{ => pixels}/flatten_cmyk_tests.rs | 0 2 files changed, 1 deletion(-) rename crates/engine/src/{ => pixels}/flatten_cmyk_tests.rs (100%) diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rs index 01339e859d..028060e70f 100644 --- a/crates/engine/src/pixels.rs +++ b/crates/engine/src/pixels.rs @@ -123,7 +123,6 @@ pub fn adjust_surface(s: &mut Surface, adj: &Adjustment, selection: Option<&Surf } #[cfg(test)] -#[path = "flatten_cmyk_tests.rs"] mod flatten_cmyk_tests; #[cfg(test)] #[path = "pixels_tests.rs"] diff --git a/crates/engine/src/flatten_cmyk_tests.rs b/crates/engine/src/pixels/flatten_cmyk_tests.rs similarity index 100% rename from crates/engine/src/flatten_cmyk_tests.rs rename to crates/engine/src/pixels/flatten_cmyk_tests.rs From a752019bfd9a6e17a6672079219d2f12c54c2814 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 143/259] refactor(engine): move pixels_tests.rs to pixels/tests.rs --- crates/engine/src/pixels.rs | 1 - crates/engine/src/{pixels_tests.rs => pixels/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/engine/src/{pixels_tests.rs => pixels/tests.rs} (100%) diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rs index 028060e70f..3f6b074153 100644 --- a/crates/engine/src/pixels.rs +++ b/crates/engine/src/pixels.rs @@ -125,7 +125,6 @@ pub fn adjust_surface(s: &mut Surface, adj: &Adjustment, selection: Option<&Surf #[cfg(test)] mod flatten_cmyk_tests; #[cfg(test)] -#[path = "pixels_tests.rs"] mod tests; /// Applies `adj` to a layer mask through the selection. Untouched mask pixels count (they read as diff --git a/crates/engine/src/pixels_tests.rs b/crates/engine/src/pixels/tests.rs similarity index 100% rename from crates/engine/src/pixels_tests.rs rename to crates/engine/src/pixels/tests.rs From ffd8333999ee13dfc3c1dc4d1dcc9eb9f958fb16 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 144/259] refactor(paint): move mixer_reference_tests.rs to mixer/reference_tests.rs --- crates/paint/src/mixer.rs | 1 - .../src/{mixer_reference_tests.rs => mixer/reference_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/paint/src/{mixer_reference_tests.rs => mixer/reference_tests.rs} (100%) diff --git a/crates/paint/src/mixer.rs b/crates/paint/src/mixer.rs index f620520b9b..32b4c265ea 100644 --- a/crates/paint/src/mixer.rs +++ b/crates/paint/src/mixer.rs @@ -440,5 +440,4 @@ mod tests { } #[cfg(test)] -#[path = "mixer_reference_tests.rs"] mod reference_tests; diff --git a/crates/paint/src/mixer_reference_tests.rs b/crates/paint/src/mixer/reference_tests.rs similarity index 100% rename from crates/paint/src/mixer_reference_tests.rs rename to crates/paint/src/mixer/reference_tests.rs From b3a8bf65b134dedcc44ce88d87acb9060e9b9b7a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 145/259] refactor(paint): move render_reference.rs to render/reference.rs --- crates/paint/src/render.rs | 1 - crates/paint/src/{render_reference.rs => render/reference.rs} | 0 2 files changed, 1 deletion(-) rename crates/paint/src/{render_reference.rs => render/reference.rs} (100%) diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index b3246f1f57..cf0835d2dd 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -1293,5 +1293,4 @@ impl RoundTip { } #[cfg(test)] -#[path = "render_reference.rs"] mod reference; diff --git a/crates/paint/src/render_reference.rs b/crates/paint/src/render/reference.rs similarity index 100% rename from crates/paint/src/render_reference.rs rename to crates/paint/src/render/reference.rs From 817d9e3b462138ae577c84a8f35240cd7c69d307 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 146/259] refactor(text): move font_names_tests.rs to fonts/font_names_tests.rs --- crates/text/src/fonts.rs | 1 - crates/text/src/{ => fonts}/font_names_tests.rs | 0 2 files changed, 1 deletion(-) rename crates/text/src/{ => fonts}/font_names_tests.rs (100%) diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rs index a0b64f4e3b..506f83dacd 100644 --- a/crates/text/src/fonts.rs +++ b/crates/text/src/fonts.rs @@ -1147,5 +1147,4 @@ mod tests { } #[cfg(test)] -#[path = "font_names_tests.rs"] mod font_names_tests; diff --git a/crates/text/src/font_names_tests.rs b/crates/text/src/fonts/font_names_tests.rs similarity index 100% rename from crates/text/src/font_names_tests.rs rename to crates/text/src/fonts/font_names_tests.rs From 4dacfeea2bae90b52fc23b283513b7dd73024c6e Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 147/259] refactor(ui-egui): move adjust_editors_tests.rs to adjust_editors/ui_tests.rs --- crates/ui-egui/src/adjust_editors.rs | 1 - .../src/{adjust_editors_tests.rs => adjust_editors/ui_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{adjust_editors_tests.rs => adjust_editors/ui_tests.rs} (100%) diff --git a/crates/ui-egui/src/adjust_editors.rs b/crates/ui-egui/src/adjust_editors.rs index 43217a10f6..099ced0a43 100644 --- a/crates/ui-egui/src/adjust_editors.rs +++ b/crates/ui-egui/src/adjust_editors.rs @@ -1775,5 +1775,4 @@ mod tests { } #[cfg(test)] -#[path = "adjust_editors_tests.rs"] mod ui_tests; diff --git a/crates/ui-egui/src/adjust_editors_tests.rs b/crates/ui-egui/src/adjust_editors/ui_tests.rs similarity index 100% rename from crates/ui-egui/src/adjust_editors_tests.rs rename to crates/ui-egui/src/adjust_editors/ui_tests.rs From 0722b6048d96bb7e4f0443c8727c027d58e54960 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 148/259] refactor(ui-egui): move adjust_preview_tests.rs to adjust_preview/tests.rs --- crates/ui-egui/src/adjust_preview.rs | 1 - .../src/{adjust_preview_tests.rs => adjust_preview/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{adjust_preview_tests.rs => adjust_preview/tests.rs} (100%) diff --git a/crates/ui-egui/src/adjust_preview.rs b/crates/ui-egui/src/adjust_preview.rs index b0362f2056..d82eac9014 100644 --- a/crates/ui-egui/src/adjust_preview.rs +++ b/crates/ui-egui/src/adjust_preview.rs @@ -553,5 +553,4 @@ pub fn live_uncovered(app: &mut PhotocraftApp, doc: DocId, key: u64, visible: Re } #[cfg(test)] -#[path = "adjust_preview_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/adjust_preview_tests.rs b/crates/ui-egui/src/adjust_preview/tests.rs similarity index 100% rename from crates/ui-egui/src/adjust_preview_tests.rs rename to crates/ui-egui/src/adjust_preview/tests.rs From 13292e59068da2d8f9d8f901062577b682ba322a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 149/259] refactor(ui-egui): move anchor_tools_tests.rs to anchor_tools/tests.rs --- crates/ui-egui/src/anchor_tools.rs | 1 - .../ui-egui/src/{anchor_tools_tests.rs => anchor_tools/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{anchor_tools_tests.rs => anchor_tools/tests.rs} (100%) diff --git a/crates/ui-egui/src/anchor_tools.rs b/crates/ui-egui/src/anchor_tools.rs index e6f9ac72d3..62384c330a 100644 --- a/crates/ui-egui/src/anchor_tools.rs +++ b/crates/ui-egui/src/anchor_tools.rs @@ -188,5 +188,4 @@ fn draw_hit(painter: &egui::Painter, to_scr: &dyn Fn([f64; 2]) -> Pos2, accent: } #[cfg(test)] -#[path = "anchor_tools_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/anchor_tools_tests.rs b/crates/ui-egui/src/anchor_tools/tests.rs similarity index 100% rename from crates/ui-egui/src/anchor_tools_tests.rs rename to crates/ui-egui/src/anchor_tools/tests.rs From acce8e969dae96927e5a23a1c6973fc77de9df62 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 150/259] refactor(ui-egui): move apply_color_tests.rs to apply_color/tests.rs --- crates/ui-egui/src/apply_color.rs | 1 - .../ui-egui/src/{apply_color_tests.rs => apply_color/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{apply_color_tests.rs => apply_color/tests.rs} (100%) diff --git a/crates/ui-egui/src/apply_color.rs b/crates/ui-egui/src/apply_color.rs index 28d76113a4..ad5179220a 100644 --- a/crates/ui-egui/src/apply_color.rs +++ b/crates/ui-egui/src/apply_color.rs @@ -152,5 +152,4 @@ fn recolour(app: &mut PhotocraftApp, gesture: Option, any_tool: bool) { } #[cfg(test)] -#[path = "apply_color_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/apply_color_tests.rs b/crates/ui-egui/src/apply_color/tests.rs similarity index 100% rename from crates/ui-egui/src/apply_color_tests.rs rename to crates/ui-egui/src/apply_color/tests.rs From 1c1094db87959379bc3aa2c52f04f16d2756b1e2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 151/259] refactor(ui-egui): move background_redraw_tests.rs to background_redraw/tests.rs --- crates/ui-egui/src/background_redraw.rs | 1 - .../{background_redraw_tests.rs => background_redraw/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{background_redraw_tests.rs => background_redraw/tests.rs} (100%) diff --git a/crates/ui-egui/src/background_redraw.rs b/crates/ui-egui/src/background_redraw.rs index 8b13c01eab..0d2f747877 100644 --- a/crates/ui-egui/src/background_redraw.rs +++ b/crates/ui-egui/src/background_redraw.rs @@ -571,5 +571,4 @@ fn draw( } #[cfg(test)] -#[path = "background_redraw_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/background_redraw_tests.rs b/crates/ui-egui/src/background_redraw/tests.rs similarity index 100% rename from crates/ui-egui/src/background_redraw_tests.rs rename to crates/ui-egui/src/background_redraw/tests.rs From 16c0e03e3ea657af51c394c586fbd24d05f101ce Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 152/259] refactor(ui-egui): move bitmap_dialog_tests.rs to bitmap_dialog/tests.rs --- crates/ui-egui/src/bitmap_dialog.rs | 1 - .../src/{bitmap_dialog_tests.rs => bitmap_dialog/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{bitmap_dialog_tests.rs => bitmap_dialog/tests.rs} (100%) diff --git a/crates/ui-egui/src/bitmap_dialog.rs b/crates/ui-egui/src/bitmap_dialog.rs index d7ff658176..5ca5ec5dc8 100644 --- a/crates/ui-egui/src/bitmap_dialog.rs +++ b/crates/ui-egui/src/bitmap_dialog.rs @@ -164,5 +164,4 @@ pub(crate) fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 153/259] refactor(ui-egui): move brush_panel_tests.rs to brush_panel/tests.rs --- crates/ui-egui/src/brush_panel.rs | 1 - .../ui-egui/src/{brush_panel_tests.rs => brush_panel/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{brush_panel_tests.rs => brush_panel/tests.rs} (100%) diff --git a/crates/ui-egui/src/brush_panel.rs b/crates/ui-egui/src/brush_panel.rs index 4b46204266..615610fa15 100644 --- a/crates/ui-egui/src/brush_panel.rs +++ b/crates/ui-egui/src/brush_panel.rs @@ -562,5 +562,4 @@ pub fn window(app: &mut PhotocraftApp, ctx: &egui::Context) { } #[cfg(test)] -#[path = "brush_panel_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/brush_panel_tests.rs b/crates/ui-egui/src/brush_panel/tests.rs similarity index 100% rename from crates/ui-egui/src/brush_panel_tests.rs rename to crates/ui-egui/src/brush_panel/tests.rs From 7bcf83da2249dc9a02a2dec5c2ef3794e654b3de Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 154/259] refactor(ui-egui): move brush_preset_dialog_tests.rs to brush_preset_dialog/tests.rs --- crates/ui-egui/src/brush_preset_dialog.rs | 1 - .../tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{brush_preset_dialog_tests.rs => brush_preset_dialog/tests.rs} (100%) diff --git a/crates/ui-egui/src/brush_preset_dialog.rs b/crates/ui-egui/src/brush_preset_dialog.rs index 46bf07522e..b47e49f5e1 100644 --- a/crates/ui-egui/src/brush_preset_dialog.rs +++ b/crates/ui-egui/src/brush_preset_dialog.rs @@ -161,5 +161,4 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 155/259] refactor(ui-egui): move brushes_tab_tests.rs to brushes_tab/tests.rs --- crates/ui-egui/src/brushes_tab.rs | 1 - .../ui-egui/src/{brushes_tab_tests.rs => brushes_tab/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{brushes_tab_tests.rs => brushes_tab/tests.rs} (100%) diff --git a/crates/ui-egui/src/brushes_tab.rs b/crates/ui-egui/src/brushes_tab.rs index 050d810603..9633125d79 100644 --- a/crates/ui-egui/src/brushes_tab.rs +++ b/crates/ui-egui/src/brushes_tab.rs @@ -1076,5 +1076,4 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } #[cfg(test)] -#[path = "brushes_tab_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/brushes_tab_tests.rs b/crates/ui-egui/src/brushes_tab/tests.rs similarity index 100% rename from crates/ui-egui/src/brushes_tab_tests.rs rename to crates/ui-egui/src/brushes_tab/tests.rs From 91b0c5a427b4e5a6a17973bcd359024eacfcbe14 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 156/259] refactor(ui-egui): move camera_raw_identity_tests.rs to camera_raw_ui/identity_tests.rs --- crates/ui-egui/src/camera_raw_ui.rs | 1 - .../identity_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{camera_raw_identity_tests.rs => camera_raw_ui/identity_tests.rs} (100%) diff --git a/crates/ui-egui/src/camera_raw_ui.rs b/crates/ui-egui/src/camera_raw_ui.rs index dc6693fca0..411d963c4f 100644 --- a/crates/ui-egui/src/camera_raw_ui.rs +++ b/crates/ui-egui/src/camera_raw_ui.rs @@ -1864,5 +1864,4 @@ fn draw(app: &mut PhotocraftApp, ctx: &egui::Context, own_window: bool) { mod tests; #[cfg(test)] -#[path = "camera_raw_identity_tests.rs"] mod identity_tests; diff --git a/crates/ui-egui/src/camera_raw_identity_tests.rs b/crates/ui-egui/src/camera_raw_ui/identity_tests.rs similarity index 100% rename from crates/ui-egui/src/camera_raw_identity_tests.rs rename to crates/ui-egui/src/camera_raw_ui/identity_tests.rs From 993318fe6adcaebba69ec7356846c81fcb6e6c3b Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 157/259] refactor(ui-egui): move canvas_display_memo_tests.rs to canvas/display_memo_tests.rs --- crates/ui-egui/src/canvas.rs | 1 - .../display_memo_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{canvas_display_memo_tests.rs => canvas/display_memo_tests.rs} (100%) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e71a5253c2..01cb1f3a43 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -7547,7 +7547,6 @@ mod zoom_animation_tests { } } #[cfg(test)] -#[path = "canvas_display_memo_tests.rs"] mod display_memo_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/canvas_display_memo_tests.rs b/crates/ui-egui/src/canvas/display_memo_tests.rs similarity index 100% rename from crates/ui-egui/src/canvas_display_memo_tests.rs rename to crates/ui-egui/src/canvas/display_memo_tests.rs From 19b40951036e9eef8761778f8ee3c51ae96c9a2a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 158/259] refactor(ui-egui): move canvas_cpu_background_tests.rs to canvas/cpu_background_tests.rs --- crates/ui-egui/src/canvas.rs | 1 - .../cpu_background_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{canvas_cpu_background_tests.rs => canvas/cpu_background_tests.rs} (100%) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 01cb1f3a43..aaff7f5cad 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -7550,7 +7550,6 @@ mod zoom_animation_tests { mod display_memo_tests; #[cfg(test)] -#[path = "canvas_cpu_background_tests.rs"] mod cpu_background_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/canvas_cpu_background_tests.rs b/crates/ui-egui/src/canvas/cpu_background_tests.rs similarity index 100% rename from crates/ui-egui/src/canvas_cpu_background_tests.rs rename to crates/ui-egui/src/canvas/cpu_background_tests.rs From 18e5a71614df8253408b8cfef9040c4764c52e03 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 159/259] refactor(ui-egui): move channel_options_ui_tests.rs to channel_options_ui/tests.rs --- crates/ui-egui/src/channel_options_ui.rs | 1 - .../{channel_options_ui_tests.rs => channel_options_ui/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{channel_options_ui_tests.rs => channel_options_ui/tests.rs} (100%) diff --git a/crates/ui-egui/src/channel_options_ui.rs b/crates/ui-egui/src/channel_options_ui.rs index d35ed2ff07..3a3453e840 100644 --- a/crates/ui-egui/src/channel_options_ui.rs +++ b/crates/ui-egui/src/channel_options_ui.rs @@ -252,5 +252,4 @@ pub fn new_spot_body(ui: &mut egui::Ui, f: &mut Map) { } #[cfg(test)] -#[path = "channel_options_ui_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/channel_options_ui_tests.rs b/crates/ui-egui/src/channel_options_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/channel_options_ui_tests.rs rename to crates/ui-egui/src/channel_options_ui/tests.rs From a443efdabc93fa389fafe7dc53bfedbf0ba9d589 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 160/259] refactor(ui-egui): move corner_radius_tests.rs to corner_radius/tests.rs --- crates/ui-egui/src/corner_radius.rs | 1 - .../src/{corner_radius_tests.rs => corner_radius/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{corner_radius_tests.rs => corner_radius/tests.rs} (100%) diff --git a/crates/ui-egui/src/corner_radius.rs b/crates/ui-egui/src/corner_radius.rs index 388ad60a96..a5199b6c9d 100644 --- a/crates/ui-egui/src/corner_radius.rs +++ b/crates/ui-egui/src/corner_radius.rs @@ -330,5 +330,4 @@ pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, to_scr: &dyn Fn([f64; } #[cfg(test)] -#[path = "corner_radius_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/corner_radius_tests.rs b/crates/ui-egui/src/corner_radius/tests.rs similarity index 100% rename from crates/ui-egui/src/corner_radius_tests.rs rename to crates/ui-egui/src/corner_radius/tests.rs From c900617b07f0e2a486df9c4d0b76bc3d4131e044 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 161/259] refactor(ui-egui): move credits_tests.rs to credits/ui_tests.rs --- crates/ui-egui/src/credits.rs | 1 - crates/ui-egui/src/{credits_tests.rs => credits/ui_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{credits_tests.rs => credits/ui_tests.rs} (100%) diff --git a/crates/ui-egui/src/credits.rs b/crates/ui-egui/src/credits.rs index eef2612379..dd10ec47e4 100644 --- a/crates/ui-egui/src/credits.rs +++ b/crates/ui-egui/src/credits.rs @@ -618,5 +618,4 @@ mod tests { } #[cfg(test)] -#[path = "credits_tests.rs"] mod ui_tests; diff --git a/crates/ui-egui/src/credits_tests.rs b/crates/ui-egui/src/credits/ui_tests.rs similarity index 100% rename from crates/ui-egui/src/credits_tests.rs rename to crates/ui-egui/src/credits/ui_tests.rs From 1a719d065d5c42f1696ca28b0bd60b2093ff80ef Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 162/259] refactor(ui-egui): move direct_select_tests.rs to direct_select/tests.rs --- crates/ui-egui/src/direct_select.rs | 1 - .../src/{direct_select_tests.rs => direct_select/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{direct_select_tests.rs => direct_select/tests.rs} (100%) diff --git a/crates/ui-egui/src/direct_select.rs b/crates/ui-egui/src/direct_select.rs index 71fccc3870..6f8ede6a1b 100644 --- a/crates/ui-egui/src/direct_select.rs +++ b/crates/ui-egui/src/direct_select.rs @@ -564,5 +564,4 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, to_scr: &dyn F } #[cfg(test)] -#[path = "direct_select_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/direct_select_tests.rs b/crates/ui-egui/src/direct_select/tests.rs similarity index 100% rename from crates/ui-egui/src/direct_select_tests.rs rename to crates/ui-egui/src/direct_select/tests.rs From d846686aba109058839fb8587e17caa9c2f1b9cd Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 163/259] refactor(ui-egui): move direction_tests.rs to direction/tests.rs --- crates/ui-egui/src/direction.rs | 1 - crates/ui-egui/src/{direction_tests.rs => direction/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{direction_tests.rs => direction/tests.rs} (100%) diff --git a/crates/ui-egui/src/direction.rs b/crates/ui-egui/src/direction.rs index 6eabbb73ef..44bc7cf67f 100644 --- a/crates/ui-egui/src/direction.rs +++ b/crates/ui-egui/src/direction.rs @@ -101,5 +101,4 @@ pub fn below() -> egui::RectAlign { } #[cfg(test)] -#[path = "direction_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/direction_tests.rs b/crates/ui-egui/src/direction/tests.rs similarity index 100% rename from crates/ui-egui/src/direction_tests.rs rename to crates/ui-egui/src/direction/tests.rs From a36953ccda479edb2ae7c31decf892b7e2391273 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:35 +0000 Subject: [PATCH 164/259] refactor(ui-egui): move dock_tests.rs to dock/tests.rs --- crates/ui-egui/src/dock.rs | 1 - crates/ui-egui/src/{dock_tests.rs => dock/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{dock_tests.rs => dock/tests.rs} (100%) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 91cccc453b..bad7f725c3 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -443,5 +443,4 @@ pub fn apply(app: &mut PhotocraftApp, v: &Value) { } #[cfg(test)] -#[path = "dock_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/dock_tests.rs b/crates/ui-egui/src/dock/tests.rs similarity index 100% rename from crates/ui-egui/src/dock_tests.rs rename to crates/ui-egui/src/dock/tests.rs From 6414ed027c594051263b7d40fe5405938ccaeeb9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 165/259] refactor(ui-egui): move fill_ui_tests.rs to fill_ui/tests.rs --- crates/ui-egui/src/fill_ui.rs | 1 - crates/ui-egui/src/{fill_ui_tests.rs => fill_ui/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{fill_ui_tests.rs => fill_ui/tests.rs} (100%) diff --git a/crates/ui-egui/src/fill_ui.rs b/crates/ui-egui/src/fill_ui.rs index 7e2d3e17ed..15c1fcdc60 100644 --- a/crates/ui-egui/src/fill_ui.rs +++ b/crates/ui-egui/src/fill_ui.rs @@ -205,5 +205,4 @@ pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) } #[cfg(test)] -#[path = "fill_ui_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/fill_ui_tests.rs b/crates/ui-egui/src/fill_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/fill_ui_tests.rs rename to crates/ui-egui/src/fill_ui/tests.rs From 8b5acca6053e490c595da19d8258eac80e3f00eb Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 166/259] refactor(ui-egui): move gpu_canvas_mip_tests.rs to gpu_canvas/mip_tests.rs --- crates/ui-egui/src/gpu_canvas.rs | 1 - .../src/{gpu_canvas_mip_tests.rs => gpu_canvas/mip_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{gpu_canvas_mip_tests.rs => gpu_canvas/mip_tests.rs} (100%) diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rs index 7c50c3a924..3d5bd18c65 100644 --- a/crates/ui-egui/src/gpu_canvas.rs +++ b/crates/ui-egui/src/gpu_canvas.rs @@ -2665,7 +2665,6 @@ fn fs(in: V) -> @location(0) vec4 { "#; #[cfg(test)] -#[path = "gpu_canvas_mip_tests.rs"] mod mip_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/gpu_canvas_mip_tests.rs b/crates/ui-egui/src/gpu_canvas/mip_tests.rs similarity index 100% rename from crates/ui-egui/src/gpu_canvas_mip_tests.rs rename to crates/ui-egui/src/gpu_canvas/mip_tests.rs From 6cbb94f83f04866d09ebdb6ab96e6df65335d727 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 167/259] refactor(ui-egui): move histogram_panel_tests.rs to histogram_panel/tests.rs --- crates/ui-egui/src/histogram_panel.rs | 1 - .../src/{histogram_panel_tests.rs => histogram_panel/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{histogram_panel_tests.rs => histogram_panel/tests.rs} (100%) diff --git a/crates/ui-egui/src/histogram_panel.rs b/crates/ui-egui/src/histogram_panel.rs index 74865f22da..5b10587286 100644 --- a/crates/ui-egui/src/histogram_panel.rs +++ b/crates/ui-egui/src/histogram_panel.rs @@ -866,5 +866,4 @@ pub fn inspect(app: &PhotocraftApp) -> Value { } #[cfg(test)] -#[path = "histogram_panel_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/histogram_panel_tests.rs b/crates/ui-egui/src/histogram_panel/tests.rs similarity index 100% rename from crates/ui-egui/src/histogram_panel_tests.rs rename to crates/ui-egui/src/histogram_panel/tests.rs From 6c7e8dc27457daa0a8685ac522aeb72b00b1283d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 168/259] refactor(ui-egui): move jobs_ui_tests.rs to jobs_ui/tests.rs --- crates/ui-egui/src/jobs_ui.rs | 1 - crates/ui-egui/src/{jobs_ui_tests.rs => jobs_ui/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{jobs_ui_tests.rs => jobs_ui/tests.rs} (100%) diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index d66932dafc..a4c30646e7 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -888,5 +888,4 @@ pub fn bytes(b: &[u8]) -> OpenSource { } #[cfg(test)] -#[path = "jobs_ui_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/jobs_ui_tests.rs b/crates/ui-egui/src/jobs_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/jobs_ui_tests.rs rename to crates/ui-egui/src/jobs_ui/tests.rs From f7b78b629f026774c96b9d7f5a68367359c2a5a2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 169/259] refactor(ui-egui): move kys_import_tests.rs to kys_import/tests.rs --- crates/ui-egui/src/kys_import.rs | 1 - crates/ui-egui/src/{kys_import_tests.rs => kys_import/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{kys_import_tests.rs => kys_import/tests.rs} (100%) diff --git a/crates/ui-egui/src/kys_import.rs b/crates/ui-egui/src/kys_import.rs index c58499620f..f36e1dbb96 100644 --- a/crates/ui-egui/src/kys_import.rs +++ b/crates/ui-egui/src/kys_import.rs @@ -246,5 +246,4 @@ pub fn show_offer(app: &mut PhotocraftApp, ctx: &egui::Context) { } #[cfg(test)] -#[path = "kys_import_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/kys_import_tests.rs b/crates/ui-egui/src/kys_import/tests.rs similarity index 100% rename from crates/ui-egui/src/kys_import_tests.rs rename to crates/ui-egui/src/kys_import/tests.rs From e4169261d08d302a21dc4b11c795ba07b11a41da Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 170/259] refactor(ui-egui): move layer_filter_ui_tests.rs to layer_filter_ui/tests.rs --- crates/ui-egui/src/layer_filter_ui.rs | 1 - .../src/{layer_filter_ui_tests.rs => layer_filter_ui/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{layer_filter_ui_tests.rs => layer_filter_ui/tests.rs} (100%) diff --git a/crates/ui-egui/src/layer_filter_ui.rs b/crates/ui-egui/src/layer_filter_ui.rs index 82c17e650e..fd035f3284 100644 --- a/crates/ui-egui/src/layer_filter_ui.rs +++ b/crates/ui-egui/src/layer_filter_ui.rs @@ -158,5 +158,4 @@ pub fn bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } #[cfg(test)] -#[path = "layer_filter_ui_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/layer_filter_ui_tests.rs b/crates/ui-egui/src/layer_filter_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/layer_filter_ui_tests.rs rename to crates/ui-egui/src/layer_filter_ui/tests.rs From 16f9c8b6c477203d0673359515519c9fff63121e Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 171/259] refactor(ui-egui): move layer_reveal_tests.rs to layer_reveal/tests.rs --- crates/ui-egui/src/layer_reveal.rs | 1 - .../ui-egui/src/{layer_reveal_tests.rs => layer_reveal/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{layer_reveal_tests.rs => layer_reveal/tests.rs} (100%) diff --git a/crates/ui-egui/src/layer_reveal.rs b/crates/ui-egui/src/layer_reveal.rs index 14ee2a36b3..2b9976de1b 100644 --- a/crates/ui-egui/src/layer_reveal.rs +++ b/crates/ui-egui/src/layer_reveal.rs @@ -60,5 +60,4 @@ pub fn scroll_to_row(ui: &egui::Ui, top: f32) { } #[cfg(test)] -#[path = "layer_reveal_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/layer_reveal_tests.rs b/crates/ui-egui/src/layer_reveal/tests.rs similarity index 100% rename from crates/ui-egui/src/layer_reveal_tests.rs rename to crates/ui-egui/src/layer_reveal/tests.rs From a2fd8985047e7664c1c6e2d743a8f12047fc8b14 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 172/259] refactor(ui-egui): move menu_keys_tests.rs to menu_keys/harness_tests.rs --- crates/ui-egui/src/menu_keys.rs | 1 - .../src/{menu_keys_tests.rs => menu_keys/harness_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{menu_keys_tests.rs => menu_keys/harness_tests.rs} (100%) diff --git a/crates/ui-egui/src/menu_keys.rs b/crates/ui-egui/src/menu_keys.rs index 2f563f9771..903d2e683d 100644 --- a/crates/ui-egui/src/menu_keys.rs +++ b/crates/ui-egui/src/menu_keys.rs @@ -477,5 +477,4 @@ mod tests { } #[cfg(test)] -#[path = "menu_keys_tests.rs"] mod harness_tests; diff --git a/crates/ui-egui/src/menu_keys_tests.rs b/crates/ui-egui/src/menu_keys/harness_tests.rs similarity index 100% rename from crates/ui-egui/src/menu_keys_tests.rs rename to crates/ui-egui/src/menu_keys/harness_tests.rs From 023924eb182383940c0566fa90f452c5bb5ad0fa Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 173/259] refactor(ui-egui): move menu_nav_tests.rs to menu_nav/tests.rs --- crates/ui-egui/src/menu_nav.rs | 1 - crates/ui-egui/src/{menu_nav_tests.rs => menu_nav/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{menu_nav_tests.rs => menu_nav/tests.rs} (100%) diff --git a/crates/ui-egui/src/menu_nav.rs b/crates/ui-egui/src/menu_nav.rs index 9f5de15c46..fb17c46643 100644 --- a/crates/ui-egui/src/menu_nav.rs +++ b/crates/ui-egui/src/menu_nav.rs @@ -553,5 +553,4 @@ fn scroll_request_id(key: egui::Id) -> egui::Id { } #[cfg(test)] -#[path = "menu_nav_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/menu_nav_tests.rs b/crates/ui-egui/src/menu_nav/tests.rs similarity index 100% rename from crates/ui-egui/src/menu_nav_tests.rs rename to crates/ui-egui/src/menu_nav/tests.rs From bb1aa3f9bf0e886523690b58736c4394019a84f3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 174/259] refactor(ui-egui): move panel_docking_tests.rs to panel_docking/tests.rs --- crates/ui-egui/src/panel_docking.rs | 1 - .../src/{panel_docking_tests.rs => panel_docking/tests.rs} | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) rename crates/ui-egui/src/{panel_docking_tests.rs => panel_docking/tests.rs} (99%) diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index b2cd933235..bf8feeb314 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -894,7 +894,6 @@ pub(crate) mod probe { } #[cfg(test)] -#[path = "panel_docking_tests.rs"] mod tests; #[cfg(test)] diff --git a/crates/ui-egui/src/panel_docking_tests.rs b/crates/ui-egui/src/panel_docking/tests.rs similarity index 99% rename from crates/ui-egui/src/panel_docking_tests.rs rename to crates/ui-egui/src/panel_docking/tests.rs index 85d452a61c..2db737f917 100644 --- a/crates/ui-egui/src/panel_docking_tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -849,7 +849,7 @@ fn the_dock_can_be_as_wide_as_the_window_allows() { /// keys, and the first change saves a versioned workspace. #[test] fn main_workspace_file_loads_as_the_default_and_saves_as_a_workspace() { - let saved: Value = serde_json::from_str(include_str!("../tests/fixtures/main-docking-workspace.json")).unwrap(); + let saved: Value = serde_json::from_str(include_str!("../../tests/fixtures/main-docking-workspace.json")).unwrap(); let mut app = app(); app.ui.theme = crate::theme::ThemeKind::ProMedium; crate::dock::apply(&mut app, &saved); From 0e966821c615774fb6d03eb9a5f1166b548fedf0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 175/259] refactor(ui-egui): move panel_docking_native_tests.rs to panel_docking/native_tests.rs --- crates/ui-egui/src/panel_docking.rs | 1 - .../native_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{panel_docking_native_tests.rs => panel_docking/native_tests.rs} (100%) diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index bf8feeb314..ebddecde2c 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -898,7 +898,6 @@ mod tests; #[cfg(test)] #[cfg(not(target_arch = "wasm32"))] -#[path = "panel_docking_native_tests.rs"] mod native_tests; /// Return positions for panels already hidden in a legacy workspace. diff --git a/crates/ui-egui/src/panel_docking_native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs similarity index 100% rename from crates/ui-egui/src/panel_docking_native_tests.rs rename to crates/ui-egui/src/panel_docking/native_tests.rs From c9c5d58162d474a74234045a867c1cc5ca2ce714 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 176/259] refactor(ui-egui): move layer_pct_slider_tests.rs to panels/layer_pct_slider_tests.rs --- crates/ui-egui/src/panels.rs | 1 - crates/ui-egui/src/{ => panels}/layer_pct_slider_tests.rs | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{ => panels}/layer_pct_slider_tests.rs (100%) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 72e443906e..80e1d0b855 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -5432,7 +5432,6 @@ mod snapshot_row_tests { } #[cfg(test)] -#[path = "layer_pct_slider_tests.rs"] mod layer_pct_slider_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/layer_pct_slider_tests.rs b/crates/ui-egui/src/panels/layer_pct_slider_tests.rs similarity index 100% rename from crates/ui-egui/src/layer_pct_slider_tests.rs rename to crates/ui-egui/src/panels/layer_pct_slider_tests.rs From b3829ba64fb3dc1783bc613eafb74bacdebd2554 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 177/259] refactor(ui-egui): move fx_drag_tests.rs to panels/fx_drag_tests.rs --- crates/ui-egui/src/panels.rs | 1 - crates/ui-egui/src/{ => panels}/fx_drag_tests.rs | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{ => panels}/fx_drag_tests.rs (100%) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 80e1d0b855..8e354c191e 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -5435,7 +5435,6 @@ mod snapshot_row_tests { mod layer_pct_slider_tests; #[cfg(test)] -#[path = "fx_drag_tests.rs"] mod fx_drag_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/fx_drag_tests.rs b/crates/ui-egui/src/panels/fx_drag_tests.rs similarity index 100% rename from crates/ui-egui/src/fx_drag_tests.rs rename to crates/ui-egui/src/panels/fx_drag_tests.rs From da928d74e572b877d49ee6fb4312712902549ecb Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 178/259] refactor(ui-egui): move unsupported_marker_tests.rs to panels/unsupported_marker_tests.rs --- crates/ui-egui/src/panels.rs | 1 - crates/ui-egui/src/{ => panels}/unsupported_marker_tests.rs | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{ => panels}/unsupported_marker_tests.rs (100%) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 8e354c191e..1f614c6b06 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -5438,7 +5438,6 @@ mod layer_pct_slider_tests; mod fx_drag_tests; #[cfg(test)] -#[path = "unsupported_marker_tests.rs"] mod unsupported_marker_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/unsupported_marker_tests.rs b/crates/ui-egui/src/panels/unsupported_marker_tests.rs similarity index 100% rename from crates/ui-egui/src/unsupported_marker_tests.rs rename to crates/ui-egui/src/panels/unsupported_marker_tests.rs From 3b6ebec9d77032d4a13c834c515a56ee54790c9a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 179/259] refactor(ui-egui): move clipping_indicator_tests.rs to panels/clipping_indicator_tests.rs --- crates/ui-egui/src/panels.rs | 1 - crates/ui-egui/src/{ => panels}/clipping_indicator_tests.rs | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{ => panels}/clipping_indicator_tests.rs (100%) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 1f614c6b06..c2c764f750 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -6137,7 +6137,6 @@ mod opacity_row_layout_tests { } #[cfg(test)] -#[path = "clipping_indicator_tests.rs"] mod clipping_indicator_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/clipping_indicator_tests.rs b/crates/ui-egui/src/panels/clipping_indicator_tests.rs similarity index 100% rename from crates/ui-egui/src/clipping_indicator_tests.rs rename to crates/ui-egui/src/panels/clipping_indicator_tests.rs From 917acbbb5b2ead2a7311226b4a329b92305c3562 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 180/259] refactor(ui-egui): move mask_props_ui_tests.rs to panels/mask_properties_tests.rs --- crates/ui-egui/src/panels.rs | 1 - .../{mask_props_ui_tests.rs => panels/mask_properties_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{mask_props_ui_tests.rs => panels/mask_properties_tests.rs} (100%) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index c2c764f750..344cd01d09 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -6140,7 +6140,6 @@ mod opacity_row_layout_tests { mod clipping_indicator_tests; #[cfg(test)] -#[path = "mask_props_ui_tests.rs"] mod mask_properties_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/mask_props_ui_tests.rs b/crates/ui-egui/src/panels/mask_properties_tests.rs similarity index 100% rename from crates/ui-egui/src/mask_props_ui_tests.rs rename to crates/ui-egui/src/panels/mask_properties_tests.rs From 90bfeffe2ad8ede33e403da4bf07bf4e1f637075 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 181/259] refactor(ui-egui): move history_panel_select_tests.rs to panels/history_panel_select_tests.rs --- crates/ui-egui/src/panels.rs | 1 - crates/ui-egui/src/{ => panels}/history_panel_select_tests.rs | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{ => panels}/history_panel_select_tests.rs (100%) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 344cd01d09..9ffe7f5d4a 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -6229,7 +6229,6 @@ mod navigator_animated_zoom_tests { } #[cfg(test)] -#[path = "history_panel_select_tests.rs"] mod history_panel_select_tests; #[cfg(test)] mod layer_click_type_commit_tests { diff --git a/crates/ui-egui/src/history_panel_select_tests.rs b/crates/ui-egui/src/panels/history_panel_select_tests.rs similarity index 100% rename from crates/ui-egui/src/history_panel_select_tests.rs rename to crates/ui-egui/src/panels/history_panel_select_tests.rs From 713f2264dc29a08a4fc084bdba84a034221ccfde Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 182/259] refactor(ui-egui): move pattern_fill_ui_tests.rs to pattern_fill_ui/tests.rs --- crates/ui-egui/src/pattern_fill_ui.rs | 1 - .../src/{pattern_fill_ui_tests.rs => pattern_fill_ui/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{pattern_fill_ui_tests.rs => pattern_fill_ui/tests.rs} (100%) diff --git a/crates/ui-egui/src/pattern_fill_ui.rs b/crates/ui-egui/src/pattern_fill_ui.rs index 33c7b3da3a..9404bf6b54 100644 --- a/crates/ui-egui/src/pattern_fill_ui.rs +++ b/crates/ui-egui/src/pattern_fill_ui.rs @@ -190,5 +190,4 @@ pub(crate) fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 183/259] refactor(ui-egui): move shortcut_capture_tests.rs to prefs_ui/shortcut_capture_tests.rs --- crates/ui-egui/src/prefs_ui.rs | 1 - crates/ui-egui/src/{ => prefs_ui}/shortcut_capture_tests.rs | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{ => prefs_ui}/shortcut_capture_tests.rs (100%) diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index 4d639fa00d..54155ba5ed 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -2739,7 +2739,6 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 184/259] refactor(ui-egui): move shortcut_set_tests.rs to prefs_ui/shortcut_set_tests.rs --- crates/ui-egui/src/prefs_ui.rs | 1 - crates/ui-egui/src/{ => prefs_ui}/shortcut_set_tests.rs | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{ => prefs_ui}/shortcut_set_tests.rs (100%) diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index 54155ba5ed..f5a37134dc 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -2741,7 +2741,6 @@ mod recovery_tests; #[cfg(test)] mod shortcut_capture_tests; #[cfg(test)] -#[path = "shortcut_set_tests.rs"] mod shortcut_set_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/shortcut_set_tests.rs b/crates/ui-egui/src/prefs_ui/shortcut_set_tests.rs similarity index 100% rename from crates/ui-egui/src/shortcut_set_tests.rs rename to crates/ui-egui/src/prefs_ui/shortcut_set_tests.rs From 44e8d000b650c507445a16858b93ce568a05d769 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 185/259] refactor(ui-egui): move props_layout_tests.rs to props_layout/tests.rs --- crates/ui-egui/src/props_layout.rs | 1 - .../ui-egui/src/{props_layout_tests.rs => props_layout/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{props_layout_tests.rs => props_layout/tests.rs} (100%) diff --git a/crates/ui-egui/src/props_layout.rs b/crates/ui-egui/src/props_layout.rs index 8e4089890c..08d3f79e6b 100644 --- a/crates/ui-egui/src/props_layout.rs +++ b/crates/ui-egui/src/props_layout.rs @@ -191,5 +191,4 @@ pub fn quick_actions_ui(app: &PhotocraftApp, ui: &mut egui::Ui, content: &LayerC } #[cfg(test)] -#[path = "props_layout_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/props_layout_tests.rs b/crates/ui-egui/src/props_layout/tests.rs similarity index 100% rename from crates/ui-egui/src/props_layout_tests.rs rename to crates/ui-egui/src/props_layout/tests.rs From a99123cd9835a69b35c6629bf77fc965712b9c5c Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:36 +0000 Subject: [PATCH 186/259] refactor(ui-egui): move rasterize_prompt_tests.rs to rasterize_prompt/tests.rs --- crates/ui-egui/src/rasterize_prompt.rs | 1 - .../src/{rasterize_prompt_tests.rs => rasterize_prompt/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{rasterize_prompt_tests.rs => rasterize_prompt/tests.rs} (100%) diff --git a/crates/ui-egui/src/rasterize_prompt.rs b/crates/ui-egui/src/rasterize_prompt.rs index 76de6a89a5..a6ac9ace68 100644 --- a/crates/ui-egui/src/rasterize_prompt.rs +++ b/crates/ui-egui/src/rasterize_prompt.rs @@ -248,5 +248,4 @@ pub fn run_pending(app: &mut PhotocraftApp, ctx: &egui::Context) { } #[cfg(test)] -#[path = "rasterize_prompt_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/rasterize_prompt_tests.rs b/crates/ui-egui/src/rasterize_prompt/tests.rs similarity index 100% rename from crates/ui-egui/src/rasterize_prompt_tests.rs rename to crates/ui-egui/src/rasterize_prompt/tests.rs From fa3fdcddff639852eb7bc1f5944ea4a31e0d64a3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:37 +0000 Subject: [PATCH 187/259] refactor(ui-egui): move shape_dialog_tests.rs to shape_dialog/tests.rs --- crates/ui-egui/src/shape_dialog.rs | 1 - .../ui-egui/src/{shape_dialog_tests.rs => shape_dialog/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{shape_dialog_tests.rs => shape_dialog/tests.rs} (100%) diff --git a/crates/ui-egui/src/shape_dialog.rs b/crates/ui-egui/src/shape_dialog.rs index 1b2634a330..6824c1cd54 100644 --- a/crates/ui-egui/src/shape_dialog.rs +++ b/crates/ui-egui/src/shape_dialog.rs @@ -262,5 +262,4 @@ pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) } #[cfg(test)] -#[path = "shape_dialog_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/shape_dialog_tests.rs b/crates/ui-egui/src/shape_dialog/tests.rs similarity index 100% rename from crates/ui-egui/src/shape_dialog_tests.rs rename to crates/ui-egui/src/shape_dialog/tests.rs From 54ad493601a0293096747c6eed89314588f81ec0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:37 +0000 Subject: [PATCH 188/259] refactor(ui-egui): move stack_dialog_tests.rs to stack_dialog/tests.rs --- crates/ui-egui/src/stack_dialog.rs | 1 - .../ui-egui/src/{stack_dialog_tests.rs => stack_dialog/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{stack_dialog_tests.rs => stack_dialog/tests.rs} (100%) diff --git a/crates/ui-egui/src/stack_dialog.rs b/crates/ui-egui/src/stack_dialog.rs index e500f7191f..e78563b83e 100644 --- a/crates/ui-egui/src/stack_dialog.rs +++ b/crates/ui-egui/src/stack_dialog.rs @@ -239,5 +239,4 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result Date: Mon, 26 Oct 2026 18:24:37 +0000 Subject: [PATCH 189/259] refactor(ui-egui): move stroke_ui_tests.rs to stroke_ui/tests.rs --- crates/ui-egui/src/stroke_ui.rs | 1 - crates/ui-egui/src/{stroke_ui_tests.rs => stroke_ui/tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{stroke_ui_tests.rs => stroke_ui/tests.rs} (100%) diff --git a/crates/ui-egui/src/stroke_ui.rs b/crates/ui-egui/src/stroke_ui.rs index 1d37927c81..bfb17f2af3 100644 --- a/crates/ui-egui/src/stroke_ui.rs +++ b/crates/ui-egui/src/stroke_ui.rs @@ -113,5 +113,4 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { } #[cfg(test)] -#[path = "stroke_ui_tests.rs"] mod tests; diff --git a/crates/ui-egui/src/stroke_ui_tests.rs b/crates/ui-egui/src/stroke_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/stroke_ui_tests.rs rename to crates/ui-egui/src/stroke_ui/tests.rs From a1c86ad47621f2461ab7d4d8ed9e7cd17ac075d2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:37 +0000 Subject: [PATCH 190/259] refactor(ui-egui): move type_tool_tests.rs to type_tool/canvas_tests.rs --- crates/ui-egui/src/type_tool.rs | 1 - .../src/{type_tool_tests.rs => type_tool/canvas_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{type_tool_tests.rs => type_tool/canvas_tests.rs} (100%) diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index cc8f252efa..f48c5fee08 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -4104,7 +4104,6 @@ fn undo_session(app: &mut PhotocraftApp, ed: &TextEdit) { } #[cfg(test)] -#[path = "type_tool_tests.rs"] mod canvas_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/type_tool_tests.rs b/crates/ui-egui/src/type_tool/canvas_tests.rs similarity index 100% rename from crates/ui-egui/src/type_tool_tests.rs rename to crates/ui-egui/src/type_tool/canvas_tests.rs From 1bd7ad645e74e8b546e8eb120b4af6add658b299 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:37 +0000 Subject: [PATCH 191/259] refactor(ui-egui): move type_font_picker_tests.rs to type_tool/font_picker_tests.rs --- crates/ui-egui/src/type_tool.rs | 1 - .../font_picker_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{type_font_picker_tests.rs => type_tool/font_picker_tests.rs} (100%) diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index f48c5fee08..9e04c9e664 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -4107,7 +4107,6 @@ fn undo_session(app: &mut PhotocraftApp, ed: &TextEdit) { mod canvas_tests; #[cfg(test)] -#[path = "type_font_picker_tests.rs"] mod font_picker_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/type_font_picker_tests.rs b/crates/ui-egui/src/type_tool/font_picker_tests.rs similarity index 100% rename from crates/ui-egui/src/type_font_picker_tests.rs rename to crates/ui-egui/src/type_tool/font_picker_tests.rs From 6bc81afc11fdcc097fc145c60d8b2157d5e6c930 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:37 +0000 Subject: [PATCH 192/259] refactor(ui-egui): move type_commit_tests.rs to type_tool/commit_tests.rs --- crates/ui-egui/src/type_tool.rs | 1 - .../src/{type_commit_tests.rs => type_tool/commit_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{type_commit_tests.rs => type_tool/commit_tests.rs} (100%) diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index 9e04c9e664..219a71e9fb 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -4113,7 +4113,6 @@ mod font_picker_tests; mod tests; #[cfg(test)] -#[path = "type_commit_tests.rs"] mod commit_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/type_commit_tests.rs b/crates/ui-egui/src/type_tool/commit_tests.rs similarity index 100% rename from crates/ui-egui/src/type_commit_tests.rs rename to crates/ui-egui/src/type_tool/commit_tests.rs From 993c3f8faacbeac2b787ee52ac92e76dbb027b9b Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:37 +0000 Subject: [PATCH 193/259] refactor(ui-egui): move path_selection_tests.rs to vector_ui/path_selection_tests.rs --- crates/ui-egui/src/vector_ui.rs | 1 - crates/ui-egui/src/{ => vector_ui}/path_selection_tests.rs | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{ => vector_ui}/path_selection_tests.rs (100%) diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index 36755732ad..1e00684389 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -2019,7 +2019,6 @@ pub fn paths_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { mod tests; #[cfg(test)] -#[path = "path_selection_tests.rs"] mod path_selection_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/path_selection_tests.rs b/crates/ui-egui/src/vector_ui/path_selection_tests.rs similarity index 100% rename from crates/ui-egui/src/path_selection_tests.rs rename to crates/ui-egui/src/vector_ui/path_selection_tests.rs From 6fb48ff0feed0496d650722b3190ec0fc3f00485 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:37 +0000 Subject: [PATCH 194/259] refactor(ui-egui): move pen_draw_tests.rs to vector_ui/pen_draw_tests.rs --- crates/ui-egui/src/vector_ui.rs | 1 - crates/ui-egui/src/{ => vector_ui}/pen_draw_tests.rs | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{ => vector_ui}/pen_draw_tests.rs (100%) diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index 1e00684389..a28d2d236d 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -2022,7 +2022,6 @@ mod tests; mod path_selection_tests; #[cfg(test)] -#[path = "pen_draw_tests.rs"] mod pen_draw_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/pen_draw_tests.rs b/crates/ui-egui/src/vector_ui/pen_draw_tests.rs similarity index 100% rename from crates/ui-egui/src/pen_draw_tests.rs rename to crates/ui-egui/src/vector_ui/pen_draw_tests.rs From 266b37062ec4a1e5214d2da8351395465bb64fe6 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:24:37 +0000 Subject: [PATCH 195/259] refactor(ui-egui): move vector_paint_tests.rs to vector_ui/paint_tests.rs --- crates/ui-egui/src/vector_ui.rs | 1 - .../src/{vector_paint_tests.rs => vector_ui/paint_tests.rs} | 0 2 files changed, 1 deletion(-) rename crates/ui-egui/src/{vector_paint_tests.rs => vector_ui/paint_tests.rs} (100%) diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index a28d2d236d..93e88676aa 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -2025,5 +2025,4 @@ mod path_selection_tests; mod pen_draw_tests; #[cfg(test)] -#[path = "vector_paint_tests.rs"] mod paint_tests; diff --git a/crates/ui-egui/src/vector_paint_tests.rs b/crates/ui-egui/src/vector_ui/paint_tests.rs similarity index 100% rename from crates/ui-egui/src/vector_paint_tests.rs rename to crates/ui-egui/src/vector_ui/paint_tests.rs From 1559d287d627ca6ad64b5fe46a582a90b76d5e57 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:27:11 +0000 Subject: [PATCH 196/259] refactor(algo): move tests_ext.rs to tests/ext.rs --- crates/algo/src/lib.rs | 3 --- crates/algo/src/tests.rs | 1 + crates/algo/src/{tests_ext.rs => tests/ext.rs} | 0 3 files changed, 1 insertion(+), 3 deletions(-) rename crates/algo/src/{tests_ext.rs => tests/ext.rs} (100%) diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index 9e8fa5301d..ece332e37f 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -1375,9 +1375,6 @@ const RESULT_BUDGET: usize = 256 << 20; #[cfg(test)] mod tests; -#[cfg(test)] -mod tests_ext; - #[cfg(test)] mod tests_mosaic; diff --git a/crates/algo/src/tests.rs b/crates/algo/src/tests.rs index 6d7e879346..5f6555fb38 100644 --- a/crates/algo/src/tests.rs +++ b/crates/algo/src/tests.rs @@ -1,5 +1,6 @@ use super::*; use photocraft_color::{PixelFormat, SampleType}; +mod ext; fn fmt(s: SampleType) -> PixelFormat { PixelFormat::new(ColorMode::Rgb, s, true) diff --git a/crates/algo/src/tests_ext.rs b/crates/algo/src/tests/ext.rs similarity index 100% rename from crates/algo/src/tests_ext.rs rename to crates/algo/src/tests/ext.rs From dd784da5ccfd4aedfddd732a497c0562bd827f8d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:27:11 +0000 Subject: [PATCH 197/259] refactor(algo): move tests_mosaic.rs to tests/mosaic.rs --- crates/algo/src/lib.rs | 3 --- crates/algo/src/tests.rs | 1 + crates/algo/src/{tests_mosaic.rs => tests/mosaic.rs} | 0 3 files changed, 1 insertion(+), 3 deletions(-) rename crates/algo/src/{tests_mosaic.rs => tests/mosaic.rs} (100%) diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index ece332e37f..05df48f2e9 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -1375,9 +1375,6 @@ const RESULT_BUDGET: usize = 256 << 20; #[cfg(test)] mod tests; -#[cfg(test)] -mod tests_mosaic; - #[cfg(test)] mod tests_selection_mix; diff --git a/crates/algo/src/tests.rs b/crates/algo/src/tests.rs index 5f6555fb38..0e018eb7ee 100644 --- a/crates/algo/src/tests.rs +++ b/crates/algo/src/tests.rs @@ -1,6 +1,7 @@ use super::*; use photocraft_color::{PixelFormat, SampleType}; mod ext; +mod mosaic; fn fmt(s: SampleType) -> PixelFormat { PixelFormat::new(ColorMode::Rgb, s, true) diff --git a/crates/algo/src/tests_mosaic.rs b/crates/algo/src/tests/mosaic.rs similarity index 100% rename from crates/algo/src/tests_mosaic.rs rename to crates/algo/src/tests/mosaic.rs From 2be8a2e5a824c1f6b2d7629a79109ce4fe06e7b0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:27:11 +0000 Subject: [PATCH 198/259] refactor(algo): move tests_selection_mix.rs to tests/selection_mix.rs --- crates/algo/src/lib.rs | 3 --- crates/algo/src/tests.rs | 1 + .../src/{tests_selection_mix.rs => tests/selection_mix.rs} | 0 3 files changed, 1 insertion(+), 3 deletions(-) rename crates/algo/src/{tests_selection_mix.rs => tests/selection_mix.rs} (100%) diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index 05df48f2e9..04acf276da 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -1375,9 +1375,6 @@ const RESULT_BUDGET: usize = 256 << 20; #[cfg(test)] mod tests; -#[cfg(test)] -mod tests_selection_mix; - /// The current upstream sampler through the identical source/selection/tile pipeline. #[cfg(test)] #[allow(clippy::too_many_arguments)] diff --git a/crates/algo/src/tests.rs b/crates/algo/src/tests.rs index 0e018eb7ee..57b7428330 100644 --- a/crates/algo/src/tests.rs +++ b/crates/algo/src/tests.rs @@ -2,6 +2,7 @@ use super::*; use photocraft_color::{PixelFormat, SampleType}; mod ext; mod mosaic; +mod selection_mix; fn fmt(s: SampleType) -> PixelFormat { PixelFormat::new(ColorMode::Rgb, s, true) diff --git a/crates/algo/src/tests_selection_mix.rs b/crates/algo/src/tests/selection_mix.rs similarity index 100% rename from crates/algo/src/tests_selection_mix.rs rename to crates/algo/src/tests/selection_mix.rs From f513e2d6823ecd14684728c8d4240c957c40467a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:40:35 +0000 Subject: [PATCH 199/259] refactor(engine): move the error, document state and Session impl out of lib.rs --- crates/engine/src/actions_cmds/tests.rs | 5 +- crates/engine/src/adjust_params/tests.rs | 5 +- crates/engine/src/doc_state.rs | 276 ++++++ crates/engine/src/edit_cmds/tests.rs | 3 +- crates/engine/src/error.rs | 32 + crates/engine/src/extra_cmds/tests.rs | 4 +- crates/engine/src/fill_cmds/tests.rs | 8 +- crates/engine/src/filters/validation/tests.rs | 3 +- crates/engine/src/image_cmds/tests.rs | 12 +- crates/engine/src/layer_style/tests.rs | 8 +- crates/engine/src/lib.rs | 896 +----------------- crates/engine/src/paint_cmds/tests.rs | 3 +- crates/engine/src/photo_cmds/tests.rs | 7 +- crates/engine/src/session.rs | 587 ++++++++++++ crates/engine/src/smartselect_cmds/tests.rs | 19 +- crates/engine/src/type_cmds/tests.rs | 16 +- 16 files changed, 932 insertions(+), 952 deletions(-) create mode 100644 crates/engine/src/doc_state.rs create mode 100644 crates/engine/src/error.rs create mode 100644 crates/engine/src/session.rs diff --git a/crates/engine/src/actions_cmds/tests.rs b/crates/engine/src/actions_cmds/tests.rs index 77f8fefc78..b7974784b6 100644 --- a/crates/engine/src/actions_cmds/tests.rs +++ b/crates/engine/src/actions_cmds/tests.rs @@ -813,10 +813,7 @@ fn nested_call_records_one_named_step_and_tracks_child_edits() { s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); let result = s.execute("actions.play", json!({"action": "Parent"})).unwrap(); assert!(result.get("failed").is_none(), "{result}"); - assert_eq!( - s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.as_str()).collect::>(), - ["Before", "Child layer", "Added later", "After"] - ); + assert_eq!(s.active().unwrap().doc.layers.iter().skip(1).map(|l| l.name.as_str()).collect::>(), ["Before", "Child layer", "Added later", "After"]); assert!(s.actions.playback_stack.is_empty()); } diff --git a/crates/engine/src/adjust_params/tests.rs b/crates/engine/src/adjust_params/tests.rs index cfc152c47f..a7b6cc53de 100644 --- a/crates/engine/src/adjust_params/tests.rs +++ b/crates/engine/src/adjust_params/tests.rs @@ -225,10 +225,7 @@ fn black_and_white_eyedroppers_round_trip_near_serialization_boundaries() { assert!(curve.windows(2).all(|pair| pair[1].input - pair[0].input >= CURVE_POINT_DUPLICATE_DISTANCE), "{picker:?} sample={sample}: {curve:?}"); } let output = tone_output(&parsed, [sample; 3]); - assert!( - output.iter().all(|value| (*value - expected_output).abs() < 1e-3), - "{picker:?} sample={sample} output={output:?} expected={expected_output}" - ); + assert!(output.iter().all(|value| (*value - expected_output).abs() < 1e-3), "{picker:?} sample={sample} output={output:?} expected={expected_output}"); } } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs new file mode 100644 index 0000000000..ef7c9445e4 --- /dev/null +++ b/crates/engine/src/doc_state.rs @@ -0,0 +1,276 @@ +use super::*; + +/// Per-document editing state. +#[derive(Clone, Debug)] +pub struct DocState { + pub doc: Arc, + pub history: History, + /// The primary ("key") layer: what single-layer commands act on. Always a member of + /// `selected_layers` when set. + pub active_layer: Option, + /// Every selected layer in the Layers panel (⌘/⇧-click), in selection order. Like + /// `active_layer`, selecting is not a history step, but undo and redo restore the layers each + /// state targeted when the next step was taken; see [`DocState::selected_layers`]. + pub selected_layers: Vec, + /// Anchor of ⇧-click range selection (the last plainly or ⌘-clicked layer). + pub layer_anchor: Option, + pub path: Option, + /// An Affinity document (or its preview) must not acquire the native source as its Save path. + pub source_read_only: bool, + /// Increments on every change; UIs re-render when it moves. + pub revision: u64, + pub saved_revision: u64, + /// Native save cache shared with this document's workers, released with the editing state. + 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). + pub last_damage: Option, + /// 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). + pub channel_view: channel_cmds::ChannelView, + /// Select › Isolate Layers: the Layers panel lists only these layers (empty = off; view state). + pub isolated_layers: Vec, + /// Painting symmetry preset or sampled path (tool state, not document pixels). + pub symmetry: Option, + /// Layers panel: layers whose effects list is collapsed under their row (the fx triangle; + /// view state, not history). Effects lists start open. + pub fx_collapsed: Vec, + /// ⌥-click on a layer's eye (`layer.showOnly`): the layer shown alone and every layer's + /// visibility before, so the next ⌥-click restores it (view state, not history). + pub show_only: Option<(LayerId, Vec<(LayerId, bool)>)>, + /// A floating selection (`select.float`): the cut piece and where it floats, until dropped + /// (view state: the document is unchanged until `select.drop`). + pub floating: Option, + /// Color Sampler points (`view.colorSamplers.*`, #1046): numbered sample positions in document + /// pixel coordinates. Per-document view state: discarded when the document closes, never saved + /// to `.pcraft` or PSD, and not a history step. + pub color_samplers: Vec<[f64; 2]>, + /// History panel snapshots, oldest first (`history.newSnapshot`, #2966): the first (id 0) is + /// the document as opened. Kept for the session only, as in Photoshop: not history states, + /// and not saved with the document. + pub snapshots: Vec, + /// The id the next snapshot gets; ids are never reused, so deleting one keeps the others. + pub(crate) next_snapshot: u64, + /// The snapshot set as the History Brush's source (`history.setSource {snapshot}`); `None`: + /// the source is a state, kept by the history ([`photocraft_ops::History::brush_source`]). + pub(crate) source_snapshot: Option, +} + +impl DocState { + /// Trim the history to its budget, counting the tiles only History panel snapshots hold + /// against it too (#4530). Returns how many states were dropped. + pub fn trim_history(&mut self) -> usize { + let snaps: Vec<&Document> = self.snapshots.iter().map(|s| &*s.doc).collect(); + self.history.trim_with(&self.doc, &snaps) + } + + /// Pixel bytes of the document, the tiles only its history holds and the tiles only its + /// History panel snapshots hold. + pub fn memory_bytes(&self) -> usize { + let snaps: Vec<&Document> = self.snapshots.iter().map(|s| &*s.doc).collect(); + self.history.pixel_bytes(&self.doc).saturating_add(self.history.extra_bytes(&self.doc, &snaps)) + } + + pub fn new(doc: Document, path: Option) -> Self { + let active_layer = doc.top_layer(); + let mut history = History::default(); + let target = LayerTarget { active: active_layer, selected: active_layer.into_iter().collect() }; + history.set_current_layers(target.clone()); + let doc = Arc::new(doc); + // Photoshop's first snapshot: the document as opened, named after it, so the History + // panel's top row can always bring it back (#2966). + let first = history_cmds::Snapshot { id: 0, name: doc.name.clone(), doc: doc.clone(), layers: target }; + Self { + doc, + history, + active_layer, + selected_layers: active_layer.into_iter().collect(), + layer_anchor: active_layer, + path, + source_read_only: false, + revision: 1, + saved_revision: 1, + pcraft_cache: Default::default(), + view_revision: 0, + last_damage: None, + coalesce: None, + channel_view: Default::default(), + isolated_layers: Vec::new(), + symmetry: None, + fx_collapsed: Vec::new(), + show_only: None, + floating: None, + color_samplers: Vec::new(), + snapshots: vec![first], + next_snapshot: 1, + source_snapshot: None, + } + } + /// The selected layers in bottom-to-top document order, always including the active layer. + /// Robust against stale state: ids no longer in the document are skipped, and if the active + /// layer was changed without updating the set, the selection is just the active layer. + pub fn selected_layers(&self) -> Vec { + let Some(active) = self.active_layer else { return Vec::new() }; + let set: &[LayerId] = if self.selected_layers.contains(&active) { &self.selected_layers } else { std::slice::from_ref(&active) }; + self.doc.walk().into_iter().map(|(_, _, l)| l.id).filter(|id| set.contains(id)).collect() + } + pub fn is_layer_selected(&self, id: LayerId) -> bool { + self.active_layer == Some(id) || (self.active_layer.is_some_and(|a| self.selected_layers.contains(&a)) && self.selected_layers.contains(&id)) + } + pub fn is_dirty(&self) -> bool { + self.revision != self.saved_revision + } + /// Whether the step from `before` to the current document leaves a clean document clean: + /// it changed nothing but the selection (#6865). Making, changing or dropping a selection + /// (marquee, lasso, Magic Wand, Quick / Object Selection, Select › …) is a history step but + /// not an edit, so it neither marks the file modified nor makes closing ask to save. + pub(crate) fn keeps_clean(&self, before: &Document) -> bool { + self.saved_revision == self.revision && layer_multi_cmds::selection_only_change(before, &self.doc) + } + /// 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) { + self.revision += 1; + if keep_clean { + self.saved_revision = self.revision; + } + } + /// The targeted layers, as history stores them with each state. + pub(crate) fn layer_target(&self) -> LayerTarget { + LayerTarget { active: self.active_layer, selected: self.selected_layers.clone() } + } +} + +/// App-wide tool state that commands read (foreground colour, brush…). +#[derive(Clone, Debug)] +pub struct ToolState { + pub foreground: [f32; 4], + pub background: [f32; 4], + pub brush: photocraft_paint::BrushSettings, + /// Brush presets (built-ins plus user presets; see `brush.presets.*`). + pub presets: Vec, + /// Bumped whenever `presets` changes ([`Session::brush_presets_changed`]); the preset store + /// syncs when it moves. + pub presets_rev: u64, + /// Mixer Brush paint carried between strokes. + pub mixer: photocraft_paint::mixer::MixerState, + /// The coalescing key of the running `tools.setBrush` gesture and the brush before it, so the + /// gesture journals as one call ([`brush_cmds::coalesce_journal`]). + pub brush_gesture: Option<(String, photocraft_paint::BrushSettings)>, + /// Name of the preset the current brush was last picked from. Kept across later edits (the + /// preset stays "the current brush" so `brush.presets.update` can overwrite it); cleared when + /// the brush is reset or the preset is gone. + pub current_preset: Option, + /// Bumped whenever `brush` or `current_preset` changes ([`ToolState::brush_changed`]). The + /// last-brush persistence watches it instead of comparing the brush itself, so an unchanged + /// brush costs a counter compare per frame, not a clone and serialise. + pub brush_rev: u64, + /// The revision whose value is in `Preferences::last_brush` (a restored one counts as saved): + /// [`brush_rev`](Self::brush_rev) == `brush_saved_rev` means there is nothing new to write. + pub brush_saved_rev: u64, + /// A layer mask is the edit target ([`ToolState::target_mask`]). + pub mask_targeted: bool, + /// The foreground/background pair of the edit target that isn't current: the layer pixels' + /// colours while a mask is targeted, the mask's while the pixels are (#2166). + pub other_colors: [[f32; 4]; 2], + /// Colours picked as CMYK, newest last: the sRGB colour that stands for them and the ink + /// values chosen. The tool colours are stored as sRGB, and an sRGB round trip does not give + /// back what was typed (100/0/0/0 cyan is outside sRGB), so a CMYK document is filled with + /// the inks the person picked (#4196). Matched by colour, so it follows a swap, a reset or a + /// mask pair without bookkeeping. + pub cmyk_picks: Vec<([f32; 3], [f32; 4])>, +} + +impl ToolState { + /// How many CMYK picks are remembered. + const CMYK_PICKS: usize = 8; + + /// Remember that sRGB colour `rgb` was picked as the inks `cmyk` (each 0..1). + pub fn remember_cmyk(&mut self, rgb: [f32; 3], cmyk: [f32; 4]) { + self.cmyk_picks.retain(|(c, _)| *c != rgb); + self.cmyk_picks.push((rgb, cmyk)); + let extra = self.cmyk_picks.len().saturating_sub(Self::CMYK_PICKS); + self.cmyk_picks.drain(..extra); + } + + /// The inks `rgb` was picked as, if it was picked as CMYK. + pub fn picked_cmyk(&self, rgb: [f32; 3]) -> Option<[f32; 4]> { + self.cmyk_picks.iter().rev().find(|(c, _)| *c == rgb).map(|(_, k)| *k) + } + + /// Photoshop's colour pair for a layer mask that has none yet: white foreground, black + /// background (reveal-paint first). + pub const MASK_COLORS: [[f32; 4]; 2] = [[1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]]; + + /// Note that `brush` or `current_preset` changed. Every setter of either (commands and the + /// shell's tool-switch paths) calls this; the last-brush persistence only serialises when the + /// revision has moved since the stored value ([`Self::brush_saved_rev`]). + pub fn brush_changed(&mut self) { + self.brush_rev = self.brush_rev.wrapping_add(1); + } + + /// Switch the edit target between layer pixels and a layer mask. Like Photoshop, the mask and + /// the pixels keep separate app-wide foreground/background pairs: changing the target puts + /// the current pair aside and brings back the other one, so colours picked while a mask is + /// targeted are remembered for masks (#2166). The mask pair starts at [`Self::MASK_COLORS`]. + /// Returns whether the target changed. + pub fn target_mask(&mut self, mask: bool) -> bool { + if self.mask_targeted == mask { + return false; + } + self.mask_targeted = mask; + let [fg, bg] = std::mem::replace(&mut self.other_colors, [self.foreground, self.background]); + self.foreground = fg; + self.background = bg; + true + } +} + +impl Default for ToolState { + fn default() -> Self { + Self { + foreground: [0.0, 0.0, 0.0, 1.0], + background: [1.0, 1.0, 1.0, 1.0], + // Photoshop's Brush tool starts at 10 % Smoothing. + brush: photocraft_paint::BrushSettings { + smoothing: photocraft_paint::brush::Smoothing { amount: 0.1, ..Default::default() }, + ..Default::default() + }, + presets: photocraft_paint::presets::builtin(), + presets_rev: 0, + mixer: Default::default(), + brush_gesture: None, + current_preset: None, + brush_rev: 0, + brush_saved_rev: 0, + mask_targeted: false, + other_colors: Self::MASK_COLORS, + cmyk_picks: Vec::new(), + } + } +} + +/// Layer › Layer Style › Copy Layer Style: the effects and the Blending Options, as Photoshop +/// copies them (Paste Layer Style puts them all on each target). +#[derive(Clone, Debug)] +pub struct CopiedStyle { + pub effects: photocraft_doc::Effects, + pub blend: photocraft_color::BlendMode, + pub fill: f32, + pub advanced: photocraft_doc::AdvancedBlending, + pub blend_if: photocraft_doc::BlendIf, + pub excluded_channels: u32, + /// The colour mode it was copied in: Blend If's channel ranges and the channel restrictions + /// only carry over to a document in the same mode. + pub mode: photocraft_color::ColorMode, +} + +/// The commands whose [`Session::precheck`] is complete: it accepts what `execute` does (Free +/// Transform applies its box before these, and only when they will run), but for the group +/// nesting limit ([`photocraft_doc::MAX_GROUP_DEPTH`]): grouping layers already that deep is +/// refused only as the edit is made. Layer via Copy and +/// Cut aren't: whether they have anything to copy (a selection over transparent pixels, a group +/// or fill layer) is known only when they run. +pub const PRECHECKED: &[&str] = &["layer.new.layer", "layer.new.group", "layer.new.groupFromLayers", "layer.new.layerFromBackground"]; diff --git a/crates/engine/src/edit_cmds/tests.rs b/crates/engine/src/edit_cmds/tests.rs index 38877661f9..e632d9fb71 100644 --- a/crates/engine/src/edit_cmds/tests.rs +++ b/crates/engine/src/edit_cmds/tests.rs @@ -1178,8 +1178,7 @@ fn ruler_origin_is_set_reset_and_undoable() { assert_eq!(s.active().unwrap().doc.ruler_origin, [0.0, 0.0]); s.undo(); assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]); - for bad in [json!({}), json!({"x": 1}), json!({"x": "a", "y": 2}), json!({"x": 1e300, "y": 0}), json!({"x": -2e7, "y": 0}), json!(null), json!([1, 2])] - { + for bad in [json!({}), json!({"x": 1}), json!({"x": "a", "y": 2}), json!({"x": 1e300, "y": 0}), json!({"x": -2e7, "y": 0}), json!(null), json!([1, 2])] { assert!(s.execute("view.setRulerOrigin", bad.clone()).is_err(), "{bad} is refused"); } assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]); diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs new file mode 100644 index 0000000000..e033d8db93 --- /dev/null +++ b/crates/engine/src/error.rs @@ -0,0 +1,32 @@ +use super::*; + +#[derive(Debug, thiserror::Error)] +pub enum EngineError { + #[error("unknown command `{0}`")] + UnknownCommand(String), + #[error("command `{0}` is not available right now: {1}")] + Disabled(String, String), + #[error("invalid parameters for `{cmd}`: {msg}")] + BadParams { cmd: String, msg: String }, + #[error("no active document")] + NoDocument, + #[error("no such layer {0:?}")] + NoLayer(LayerId), + /// [`Self::NoLayer`] as a command reports it: with the layers the document does have, as + /// ids are not positions (#5058). + #[error("no such layer {}; {known}", id.0)] + UnknownLayer { id: LayerId, known: String }, + #[error("{0}")] + Other(String), + /// A background job was cancelled (see [`jobs`]); nothing changed. + #[error("cancelled")] + Cancelled, +} + +pub type Result = std::result::Result; + +impl From for EngineError { + fn from(error: photocraft_raster::AllocationError) -> Self { + Self::Other(format!("not enough memory for this operation ({error}); the document was not changed")) + } +} diff --git a/crates/engine/src/extra_cmds/tests.rs b/crates/engine/src/extra_cmds/tests.rs index b4c6908d3f..97243efd58 100644 --- a/crates/engine/src/extra_cmds/tests.rs +++ b/crates/engine/src/extra_cmds/tests.rs @@ -136,9 +136,7 @@ fn stroke_widths_are_whole_opaque_pixels_like_photoshop() { let (inside, outside) = band(loc, w); // (edge pixel inside, step inward) for left, right, top and bottom; the other // coordinate is the middle of the edge. - for (name, first_in, inward, horizontal) in - [("left", 10, 1, false), ("right", 29, -1, false), ("top", 10, 1, true), ("bottom", 29, -1, true)] - { + for (name, first_in, inward, horizontal) in [("left", 10, 1, false), ("right", 29, -1, false), ("top", 10, 1, true), ("bottom", 29, -1, true)] { for k in -7..7 { // k ≥ 0: k px inside from the edge; k < 0: -k px outside. let c = first_in + k * inward; diff --git a/crates/engine/src/fill_cmds/tests.rs b/crates/engine/src/fill_cmds/tests.rs index 3a9dd61d49..bf46b6f4a6 100644 --- a/crates/engine/src/fill_cmds/tests.rs +++ b/crates/engine/src/fill_cmds/tests.rs @@ -288,11 +288,9 @@ fn unselected_tiles_stay_shared() { s.execute("edit.fill", json!({"color": "#336699"})).unwrap(); let id = s.active().unwrap().active_layer.unwrap(); let surf = |s: &Session| s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().clone(); - for (cmd, params) in [ - ("edit.fill", json!({"color": "#ff0000"})), - ("edit.stroke", json!({"width": 4, "color": "#00ff00", "location": "inside"})), - ("edit.clear", json!({})), - ] { + for (cmd, params) in + [("edit.fill", json!({"color": "#ff0000"})), ("edit.stroke", json!({"width": 4, "color": "#00ff00", "location": "inside"})), ("edit.clear", json!({}))] + { // Two small selections in opposite corners (256 px tiles): the selection's bounds // span every tile, but only the two corner tiles have anything selected. s.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 100})).unwrap(); diff --git a/crates/engine/src/filters/validation/tests.rs b/crates/engine/src/filters/validation/tests.rs index 3541fe8807..408a55b365 100644 --- a/crates/engine/src/filters/validation/tests.rs +++ b/crates/engine/src/filters/validation/tests.rs @@ -290,8 +290,7 @@ fn strict_extended_filters_keep_defaults_targets_history_and_last_filter() { #[test] fn stored_extended_filter_records_still_decode_tolerantly() { use photocraft_algo::{BlurQuality, BlurShape, FilterParams, SmartBlurMode}; - let smart = - crate::filters::params_for("filter.blur.smartBlur", &json!({"radius":-2,"threshold":900,"quality":"old","mode":false,"extra":true})).unwrap(); + let smart = crate::filters::params_for("filter.blur.smartBlur", &json!({"radius":-2,"threshold":900,"quality":"old","mode":false,"extra":true})).unwrap(); assert!(matches!(smart, FilterParams::SmartBlur { radius: 0.1, threshold: 100.0, quality: BlurQuality::High, mode: SmartBlurMode::Normal })); let shape = crate::filters::params_for("filter.blur.shapeBlur", &json!({"radius":2000,"shape":"old"})).unwrap(); assert!(matches!(shape, FilterParams::ShapeBlur { radius: 1000.0, shape: BlurShape::Circle })); diff --git a/crates/engine/src/image_cmds/tests.rs b/crates/engine/src/image_cmds/tests.rs index 3b9dc7f03f..3061ce69c0 100644 --- a/crates/engine/src/image_cmds/tests.rs +++ b/crates/engine/src/image_cmds/tests.rs @@ -199,15 +199,9 @@ fn image_size_refuses_a_raster_past_the_budget() { #[test] fn image_size_keeps_canvas_edges_opaque() { for depth in [8, 16, 32] { - for (w, resample) in [ - (60, "bicubic"), - (41, "lanczos"), - (15, "bilinear"), - (77, "preserveDetails"), - (21, "bicubicSharper"), - (47, "automatic"), - (9, "bicubicAutomatic"), - ] { + for (w, resample) in + [(60, "bicubic"), (41, "lanczos"), (15, "bilinear"), (77, "preserveDetails"), (21, "bicubicSharper"), (47, "automatic"), (9, "bicubicAutomatic")] + { let mut s = Session::new(); s.execute("file.new", json!({"width": 30, "height": 20, "depth": depth, "background": "#336699"})).unwrap(); s.execute("select.all", json!({})).unwrap(); diff --git a/crates/engine/src/layer_style/tests.rs b/crates/engine/src/layer_style/tests.rs index 95cc631cf5..87e80ef898 100644 --- a/crates/engine/src/layer_style/tests.rs +++ b/crates/engine/src/layer_style/tests.rs @@ -294,9 +294,7 @@ fn snapshot(fx: &Effect) -> Value { #[test] fn every_kind_has_factory_defaults() { - for kind in - ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "satin", "bevelEmboss"] - { + for kind in ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "satin", "bevelEmboss"] { assert!(effect_defaults(kind).as_object().is_some_and(|o| !o.is_empty()), "{kind}"); assert!(effect_from_params(kind, &json!({})).is_some(), "{kind}"); } @@ -523,9 +521,7 @@ fn make_default_then_reset_restores_it() { /// black. Both now give Photoshop's Reset to Default: 1 px, inside, Normal, 100 %, black. #[test] fn fresh_effects_match_the_dialog_factory_defaults() { - for kind in - ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "satin", "bevelEmboss"] - { + for kind in ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "satin", "bevelEmboss"] { let bare = effect_from_params(kind, &json!({})).unwrap(); let dialog = effect_from_params(kind, &effect_defaults(kind)).unwrap(); assert_eq!(bare, dialog, "{kind}"); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c49e555071..1633d59b6c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -153,36 +153,15 @@ pub use photocraft_doc as doc; pub use photocraft_paint as paint; pub use photocraft_paint::BrushSettings; -#[derive(Debug, thiserror::Error)] -pub enum EngineError { - #[error("unknown command `{0}`")] - UnknownCommand(String), - #[error("command `{0}` is not available right now: {1}")] - Disabled(String, String), - #[error("invalid parameters for `{cmd}`: {msg}")] - BadParams { cmd: String, msg: String }, - #[error("no active document")] - NoDocument, - #[error("no such layer {0:?}")] - NoLayer(LayerId), - /// [`Self::NoLayer`] as a command reports it: with the layers the document does have, as - /// ids are not positions (#5058). - #[error("no such layer {}; {known}", id.0)] - UnknownLayer { id: LayerId, known: String }, - #[error("{0}")] - Other(String), - /// A background job was cancelled (see [`jobs`]); nothing changed. - #[error("cancelled")] - Cancelled, -} +mod doc_state; +mod error; +mod session; -pub type Result = std::result::Result; - -impl From for EngineError { - fn from(error: photocraft_raster::AllocationError) -> Self { - Self::Other(format!("not enough memory for this operation ({error}); the document was not changed")) - } -} +pub use doc_state::{CopiedStyle, DocState, PRECHECKED, ToolState}; +pub use error::{EngineError, Result}; +pub(crate) use session::fix_selection; +pub use session::move_item; +use session::restore_target; /// The pixels of a raster layer (typically one a command just created), as an error instead /// of a panic if the layer has none. @@ -197,281 +176,6 @@ pub(crate) fn active_layer_of(s: &Session) -> std::result::Result<&photocraft_do d.active_layer.and_then(|id| d.doc.layer(id)).ok_or_else(|| "no active layer".into()) } -/// Per-document editing state. -#[derive(Clone, Debug)] -pub struct DocState { - pub doc: Arc, - pub history: History, - /// The primary ("key") layer: what single-layer commands act on. Always a member of - /// `selected_layers` when set. - pub active_layer: Option, - /// Every selected layer in the Layers panel (⌘/⇧-click), in selection order. Like - /// `active_layer`, selecting is not a history step, but undo and redo restore the layers each - /// state targeted when the next step was taken; see [`DocState::selected_layers`]. - pub selected_layers: Vec, - /// Anchor of ⇧-click range selection (the last plainly or ⌘-clicked layer). - pub layer_anchor: Option, - pub path: Option, - /// An Affinity document (or its preview) must not acquire the native source as its Save path. - pub source_read_only: bool, - /// Increments on every change; UIs re-render when it moves. - pub revision: u64, - pub saved_revision: u64, - /// Native save cache shared with this document's workers, released with the editing state. - 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). - pub last_damage: Option, - /// 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). - pub channel_view: channel_cmds::ChannelView, - /// Select › Isolate Layers: the Layers panel lists only these layers (empty = off; view state). - pub isolated_layers: Vec, - /// Painting symmetry preset or sampled path (tool state, not document pixels). - pub symmetry: Option, - /// Layers panel: layers whose effects list is collapsed under their row (the fx triangle; - /// view state, not history). Effects lists start open. - pub fx_collapsed: Vec, - /// ⌥-click on a layer's eye (`layer.showOnly`): the layer shown alone and every layer's - /// visibility before, so the next ⌥-click restores it (view state, not history). - pub show_only: Option<(LayerId, Vec<(LayerId, bool)>)>, - /// A floating selection (`select.float`): the cut piece and where it floats, until dropped - /// (view state: the document is unchanged until `select.drop`). - pub floating: Option, - /// Color Sampler points (`view.colorSamplers.*`, #1046): numbered sample positions in document - /// pixel coordinates. Per-document view state: discarded when the document closes, never saved - /// to `.pcraft` or PSD, and not a history step. - pub color_samplers: Vec<[f64; 2]>, - /// History panel snapshots, oldest first (`history.newSnapshot`, #2966): the first (id 0) is - /// the document as opened. Kept for the session only, as in Photoshop: not history states, - /// and not saved with the document. - pub snapshots: Vec, - /// The id the next snapshot gets; ids are never reused, so deleting one keeps the others. - next_snapshot: u64, - /// The snapshot set as the History Brush's source (`history.setSource {snapshot}`); `None`: - /// the source is a state, kept by the history ([`photocraft_ops::History::brush_source`]). - pub(crate) source_snapshot: Option, -} - -impl DocState { - /// Trim the history to its budget, counting the tiles only History panel snapshots hold - /// against it too (#4530). Returns how many states were dropped. - pub fn trim_history(&mut self) -> usize { - let snaps: Vec<&Document> = self.snapshots.iter().map(|s| &*s.doc).collect(); - self.history.trim_with(&self.doc, &snaps) - } - - /// Pixel bytes of the document, the tiles only its history holds and the tiles only its - /// History panel snapshots hold. - pub fn memory_bytes(&self) -> usize { - let snaps: Vec<&Document> = self.snapshots.iter().map(|s| &*s.doc).collect(); - self.history.pixel_bytes(&self.doc).saturating_add(self.history.extra_bytes(&self.doc, &snaps)) - } - - pub fn new(doc: Document, path: Option) -> Self { - let active_layer = doc.top_layer(); - let mut history = History::default(); - let target = LayerTarget { active: active_layer, selected: active_layer.into_iter().collect() }; - history.set_current_layers(target.clone()); - let doc = Arc::new(doc); - // Photoshop's first snapshot: the document as opened, named after it, so the History - // panel's top row can always bring it back (#2966). - let first = history_cmds::Snapshot { id: 0, name: doc.name.clone(), doc: doc.clone(), layers: target }; - Self { - doc, - history, - active_layer, - selected_layers: active_layer.into_iter().collect(), - layer_anchor: active_layer, - path, - source_read_only: false, - revision: 1, - saved_revision: 1, - pcraft_cache: Default::default(), - view_revision: 0, - last_damage: None, - coalesce: None, - channel_view: Default::default(), - isolated_layers: Vec::new(), - symmetry: None, - fx_collapsed: Vec::new(), - show_only: None, - floating: None, - color_samplers: Vec::new(), - snapshots: vec![first], - next_snapshot: 1, - source_snapshot: None, - } - } - /// The selected layers in bottom-to-top document order, always including the active layer. - /// Robust against stale state: ids no longer in the document are skipped, and if the active - /// layer was changed without updating the set, the selection is just the active layer. - pub fn selected_layers(&self) -> Vec { - let Some(active) = self.active_layer else { return Vec::new() }; - let set: &[LayerId] = if self.selected_layers.contains(&active) { &self.selected_layers } else { std::slice::from_ref(&active) }; - self.doc.walk().into_iter().map(|(_, _, l)| l.id).filter(|id| set.contains(id)).collect() - } - pub fn is_layer_selected(&self, id: LayerId) -> bool { - self.active_layer == Some(id) || (self.active_layer.is_some_and(|a| self.selected_layers.contains(&a)) && self.selected_layers.contains(&id)) - } - pub fn is_dirty(&self) -> bool { - self.revision != self.saved_revision - } - /// Whether the step from `before` to the current document leaves a clean document clean: - /// it changed nothing but the selection (#6865). Making, changing or dropping a selection - /// (marquee, lasso, Magic Wand, Quick / Object Selection, Select › …) is a history step but - /// not an edit, so it neither marks the file modified nor makes closing ask to save. - pub(crate) fn keeps_clean(&self, before: &Document) -> bool { - self.saved_revision == self.revision && layer_multi_cmds::selection_only_change(before, &self.doc) - } - /// 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) { - self.revision += 1; - if keep_clean { - self.saved_revision = self.revision; - } - } - /// The targeted layers, as history stores them with each state. - fn layer_target(&self) -> LayerTarget { - LayerTarget { active: self.active_layer, selected: self.selected_layers.clone() } - } -} - -/// App-wide tool state that commands read (foreground colour, brush…). -#[derive(Clone, Debug)] -pub struct ToolState { - pub foreground: [f32; 4], - pub background: [f32; 4], - pub brush: photocraft_paint::BrushSettings, - /// Brush presets (built-ins plus user presets; see `brush.presets.*`). - pub presets: Vec, - /// Bumped whenever `presets` changes ([`Session::brush_presets_changed`]); the preset store - /// syncs when it moves. - pub presets_rev: u64, - /// Mixer Brush paint carried between strokes. - pub mixer: photocraft_paint::mixer::MixerState, - /// The coalescing key of the running `tools.setBrush` gesture and the brush before it, so the - /// gesture journals as one call ([`brush_cmds::coalesce_journal`]). - pub brush_gesture: Option<(String, photocraft_paint::BrushSettings)>, - /// Name of the preset the current brush was last picked from. Kept across later edits (the - /// preset stays "the current brush" so `brush.presets.update` can overwrite it); cleared when - /// the brush is reset or the preset is gone. - pub current_preset: Option, - /// Bumped whenever `brush` or `current_preset` changes ([`ToolState::brush_changed`]). The - /// last-brush persistence watches it instead of comparing the brush itself, so an unchanged - /// brush costs a counter compare per frame, not a clone and serialise. - pub brush_rev: u64, - /// The revision whose value is in `Preferences::last_brush` (a restored one counts as saved): - /// [`brush_rev`](Self::brush_rev) == `brush_saved_rev` means there is nothing new to write. - pub brush_saved_rev: u64, - /// A layer mask is the edit target ([`ToolState::target_mask`]). - pub mask_targeted: bool, - /// The foreground/background pair of the edit target that isn't current: the layer pixels' - /// colours while a mask is targeted, the mask's while the pixels are (#2166). - pub other_colors: [[f32; 4]; 2], - /// Colours picked as CMYK, newest last: the sRGB colour that stands for them and the ink - /// values chosen. The tool colours are stored as sRGB, and an sRGB round trip does not give - /// back what was typed (100/0/0/0 cyan is outside sRGB), so a CMYK document is filled with - /// the inks the person picked (#4196). Matched by colour, so it follows a swap, a reset or a - /// mask pair without bookkeeping. - pub cmyk_picks: Vec<([f32; 3], [f32; 4])>, -} - -impl ToolState { - /// How many CMYK picks are remembered. - const CMYK_PICKS: usize = 8; - - /// Remember that sRGB colour `rgb` was picked as the inks `cmyk` (each 0..1). - pub fn remember_cmyk(&mut self, rgb: [f32; 3], cmyk: [f32; 4]) { - self.cmyk_picks.retain(|(c, _)| *c != rgb); - self.cmyk_picks.push((rgb, cmyk)); - let extra = self.cmyk_picks.len().saturating_sub(Self::CMYK_PICKS); - self.cmyk_picks.drain(..extra); - } - - /// The inks `rgb` was picked as, if it was picked as CMYK. - pub fn picked_cmyk(&self, rgb: [f32; 3]) -> Option<[f32; 4]> { - self.cmyk_picks.iter().rev().find(|(c, _)| *c == rgb).map(|(_, k)| *k) - } - - /// Photoshop's colour pair for a layer mask that has none yet: white foreground, black - /// background (reveal-paint first). - pub const MASK_COLORS: [[f32; 4]; 2] = [[1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]]; - - /// Note that `brush` or `current_preset` changed. Every setter of either (commands and the - /// shell's tool-switch paths) calls this; the last-brush persistence only serialises when the - /// revision has moved since the stored value ([`Self::brush_saved_rev`]). - pub fn brush_changed(&mut self) { - self.brush_rev = self.brush_rev.wrapping_add(1); - } - - /// Switch the edit target between layer pixels and a layer mask. Like Photoshop, the mask and - /// the pixels keep separate app-wide foreground/background pairs: changing the target puts - /// the current pair aside and brings back the other one, so colours picked while a mask is - /// targeted are remembered for masks (#2166). The mask pair starts at [`Self::MASK_COLORS`]. - /// Returns whether the target changed. - pub fn target_mask(&mut self, mask: bool) -> bool { - if self.mask_targeted == mask { - return false; - } - self.mask_targeted = mask; - let [fg, bg] = std::mem::replace(&mut self.other_colors, [self.foreground, self.background]); - self.foreground = fg; - self.background = bg; - true - } -} - -impl Default for ToolState { - fn default() -> Self { - Self { - foreground: [0.0, 0.0, 0.0, 1.0], - background: [1.0, 1.0, 1.0, 1.0], - // Photoshop's Brush tool starts at 10 % Smoothing. - brush: photocraft_paint::BrushSettings { - smoothing: photocraft_paint::brush::Smoothing { amount: 0.1, ..Default::default() }, - ..Default::default() - }, - presets: photocraft_paint::presets::builtin(), - presets_rev: 0, - mixer: Default::default(), - brush_gesture: None, - current_preset: None, - brush_rev: 0, - brush_saved_rev: 0, - mask_targeted: false, - other_colors: Self::MASK_COLORS, - cmyk_picks: Vec::new(), - } - } -} - -/// Layer › Layer Style › Copy Layer Style: the effects and the Blending Options, as Photoshop -/// copies them (Paste Layer Style puts them all on each target). -#[derive(Clone, Debug)] -pub struct CopiedStyle { - pub effects: photocraft_doc::Effects, - pub blend: photocraft_color::BlendMode, - pub fill: f32, - pub advanced: photocraft_doc::AdvancedBlending, - pub blend_if: photocraft_doc::BlendIf, - pub excluded_channels: u32, - /// The colour mode it was copied in: Blend If's channel ranges and the channel restrictions - /// only carry over to a document in the same mode. - pub mode: photocraft_color::ColorMode, -} - -/// The commands whose [`Session::precheck`] is complete: it accepts what `execute` does (Free -/// Transform applies its box before these, and only when they will run), but for the group -/// nesting limit ([`photocraft_doc::MAX_GROUP_DEPTH`]): grouping layers already that deep is -/// refused only as the edit is made. Layer via Copy and -/// Cut aren't: whether they have anything to copy (a selection over transparent pixels, a group -/// or fill layer) is known only when they run. -pub const PRECHECKED: &[&str] = &["layer.new.layer", "layer.new.group", "layer.new.groupFromLayers", "layer.new.layerFromBackground"]; - #[derive(Default)] pub struct Session { docs: Vec, @@ -567,590 +271,6 @@ pub struct Session { next_held_open: u64, } -/// Move item `i` of `v` to position `to`, clamped to the end. Returns where it went; `None` when -/// `i` is out of range. -pub fn move_item(v: &mut Vec, i: usize, to: usize) -> Option { - if i >= v.len() { - return None; - } - let x = v.remove(i); - let to = to.min(v.len()); - v.insert(to, x); - Some(to) -} - -impl Session { - pub fn new() -> Self { - Self::default() - } - - pub fn documents(&self) -> &[DocState] { - &self.docs - } - pub fn active_index(&self) -> Option { - self.active - } - pub fn active(&self) -> Option<&DocState> { - self.active.and_then(|i| self.docs.get(i)) - } - pub fn active_mut(&mut self) -> Option<&mut DocState> { - self.active.and_then(|i| self.docs.get_mut(i)) - } - /// Monotonic active-document generation. It changes when a different document becomes - /// active, including a switch away and back between two observations; equal values therefore - /// mean the document was not switched in between. - pub fn active_generation(&self) -> u64 { - self.active_generation - } - /// Bump [`Self::active_generation`] when the active document id changed. Call after every - /// assignment to `self.active`. - pub(crate) fn note_active_change(&mut self) { - let id = self.active().map(|st| st.doc.id); - if id != self.active_doc_for_generation { - self.active_doc_for_generation = id; - self.active_generation = self.active_generation.wrapping_add(1); - } - } - pub fn set_active(&mut self, index: usize) -> bool { - if index < self.docs.len() { - self.active = Some(index); - self.note_active_change(); - self.sync_tools_mask_target(); - true - } else { - false - } - } - - /// Color Sampler points dropped by the last canvas-size change (crop, Canvas Size, Image Size, - /// rotation) since this was last called, for the status message. See [`edit`](Self::edit). - pub fn take_samplers_removed(&mut self) -> usize { - std::mem::take(&mut self.samplers_removed) - } - - /// Move the Color Sampler points through `a` in the next [`Session::edit`] (crop, Canvas Size, - /// Image Size, rotation), dropping the ones that land outside the new canvas. View state: the - /// points stay pinned to their pixels, no history step. Cleared by the edit it is set for. - /// The painting symmetry moves through `a` too. - pub(crate) fn set_sampler_map(&mut self, a: photocraft_geom::Affine) { - self.set_canvas_map(a, a); - } - - /// [`set_sampler_map`](Self::set_sampler_map) for an edit whose sampler map differs from its - /// geometry map (a flip or rotation maps pixel centres): `geometry` moves the painting symmetry. - pub(crate) fn set_canvas_map(&mut self, geometry: photocraft_geom::Affine, samplers: photocraft_geom::Affine) { - self.sampler_map = Some(samplers); - self.symmetry_map = Some(geometry); - } - - pub fn sync_tools_mask_target(&mut self) { - let mask = self.active().is_some_and(|st| st.channel_view.target == crate::channel_cmds::ChannelTarget::LayerMask); - self.tools.target_mask(mask); - } - - /// Move the document at `from` to tab position `to` (clamped to the last), keeping the active - /// document active. Returns its new index; `None` when `from` is out of range. - pub fn move_document(&mut self, from: usize, to: usize) -> Option { - let active = self.active().map(|d| d.doc.id); - let to = move_item(&mut self.docs, from, to)?; - self.active = active.and_then(|id| self.docs.iter().position(|d| d.doc.id == id)); - self.note_active_change(); - Some(to) - } - - /// Add a document (from File → New, an import, etc.) and make it active. - /// Preserve its identity unless another open document already owns it. - /// Identity-dependent callers must read the admitted document at the returned index. - pub fn add_document(&mut self, mut doc: Document, path: Option) -> usize { - // Persisted IDs can overlap the allocator, so check every replacement too. - while self.docs.iter().any(|st| st.doc.id == doc.id) { - doc.id = photocraft_doc::DocId::fresh(); - } - let mut st = DocState::new(doc, path); - st.history.max_states = self.prefs.get().performance.history_states.max(1) as usize; - st.history.max_bytes = self.prefs.get().performance.history_budget_bytes(); - self.docs.push(st); - let i = self.docs.len() - 1; - self.active = Some(i); - self.note_active_change(); - i - } - - /// Holds a decoded document back from opening (see `held_opens`); returns its id. - pub(crate) fn hold_open(&mut self, doc: Document, source_read_only: bool) -> u64 { - self.next_held_open = self.next_held_open.wrapping_add(1); - self.held_opens.push((self.next_held_open, doc, source_read_only)); - self.next_held_open - } - - /// 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)> { - let i = self.held_opens.iter().position(|(h, _, _)| *h == id)?; - let (_, doc, read_only) = self.held_opens.remove(i); - Some((doc, read_only)) - } - - pub fn close(&mut self, index: usize) -> Option { - if index >= self.docs.len() { - return None; - } - smart_cmds::on_close(self, index); - if let Some(id) = self.docs.get(index).map(|d| d.doc.id) { - self.cancel_jobs_on(id); - self.subject_cache.forget_doc(id); - self.object_finder.forget_doc(id); - } - let d = self.docs.remove(index); - self.active = if self.docs.is_empty() { - None - } else { - Some(match self.active { - Some(active) if active > index => active - 1, - Some(active) if active < index => active, - _ => index.min(self.docs.len() - 1), - }) - }; - self.note_active_change(); - Some(d) - } - - /// Run a command by id with JSON params. Returns a JSON result. - /// - /// Any command accepts an optional `"coalesce": ""` param: consecutive edits with the same - /// key (and no other edit, undo or redo in between) share one history step, like Photoshop's - /// single "Edit Type Layer" step for a whole typing session or one step per slider drag. - /// - /// Runs synchronously, including job-capable commands (see [`jobs`]; [`Session::start`] runs - /// those in the background). - pub fn execute(&mut self, id: &str, params: Value) -> Result { - match self.dispatch(id, params, false)? { - jobs::Started::Done(v) => Ok(v), - // Not reached: inline dispatch never starts a job. Waiting is still correct. - jobs::Started::Job(j) => self.wait_job(j), - } - } - - /// Offer a finished live stroke to the next command: a `paint.stroke` / `paint.pencil` whose - /// params match it exactly takes its pixels instead of rendering the stroke again (its result - /// then says `"fromLive": true`); any other command drops the offer. The command still runs - /// through the normal dispatch, so authorization, the journal and history are unchanged. - pub fn offer_live_stroke(&mut self, live: brush_cmds::LiveStroke) -> Result<()> { - self.live_commit = Some(live.into_commit()?); - Ok(()) - } - - /// [`Self::offer_live_stroke`] for a live Clone Stamp or History Brush stroke, taken by the - /// `paint.cloneStamp` / `paint.historyBrush` it was drawn for. Refused for the Healing Brush - /// (it blends on release) and when the brush, layer or clone source changed during the stroke. - pub fn offer_live_retouch(&mut self, live: retouch_cmds::LiveRetouch) -> Result<()> { - let commit = live.into_commit(self)?; - self.live_commit = Some(commit); - Ok(()) - } - - /// [`Self::offer_live_stroke`] for a live Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke, - /// taken by the command it was drawn for: the stroke's finishing dabs are run first. Refused - /// when the brush, tool options or layer changed during the stroke. - pub fn offer_live_dab(&mut self, live: retouch_cmds::LiveDab) -> Result<()> { - // A refused offer withdraws the previous one too. - self.live_commit = None; - let commit = live.into_commit(self)?; - self.live_commit = Some(commit); - Ok(()) - } - - /// Withdraw an offer the command didn't take. - pub fn clear_live_stroke(&mut self) { - self.live_commit = None; - } - - /// Check a call without running it: the command exists, its params have the shape - /// [`Self::execute`] requires (New Layer's fully), and it can run now. For a caller that does - /// something first only when the command will go through: Free Transform applies its box - /// before a new layer is made. - /// - /// Complete for the commands in [`PRECHECKED`]: there it accepts what `execute` accepts, but - /// for the group nesting limit (a test holds the two together). For others it checks only what they share. - pub fn precheck(&mut self, id: &str, params: &Value) -> Result<()> { - let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; - if !(params.is_object() || params.is_null()) { - return Err(EngineError::BadParams { cmd: id.to_string(), msg: "params must be a JSON object".into() }); - } - crate::param_check::check(spec, params)?; - crate::filters::validate_params(id, params)?; - if id == "layer.new.layer" { - crate::new_layer::parse(params)?; - } - // A command that takes `"layer"` (an id or a name, as it resolves it) fails on one the - // document doesn't have. - if spec.params.contains("\"layer\":id") - && let Some(l) = commands::explicit_layer(self, params)? - && self.active().is_none_or(|st| st.doc.layer(l).is_none()) - { - return Err(EngineError::BadParams { cmd: id.to_string(), msg: format!("no layer {}", l.0) }); - } - self.admit(id, spec, params).map(|_| ()) - } - - /// What `dispatch` checks once the params are valid and a floating selection has dropped: - /// the precondition (on a named layer for commands that take one), a job running on the - /// document, a hidden target. The run params (the Channels panel's target filled in) when it - /// may run. - pub(crate) fn admit(&mut self, id: &str, spec: &commands::CommandSpec, params: &Value) -> Result { - let run_params = channel_cmds::inject_target(self, id, commands::inject_kind(id, params.clone())); - if let Err(why) = self.explicit_layer_enabled(spec, params).unwrap_or_else(|| self.precondition(spec, &run_params)) { - return Err(EngineError::Disabled(id.to_string(), why)); - } - if let Some(why) = self.job_conflict(id, spec.journal) { - return Err(EngineError::Disabled(id.to_string(), why)); - } - // Painting on or moving a hidden layer is refused, as in Photoshop (#571). - if let Some(why) = hidden_target::refusal(self, id, params) { - return Err(EngineError::Other(why.into())); - } - Ok(run_params) - } - - /// Is the command currently runnable? (drives menu enablement) - pub fn is_enabled(&self, id: &str) -> bool { - self.is_enabled_with(id, &Value::Null) - } - - /// [`Self::is_enabled`] for a call with `params`: their `"target"` can enable a command, as a - /// targeted layer mask enables Image › Adjustments › Invert on an adjustment layer (#780). - pub fn is_enabled_with(&self, id: &str, params: &Value) -> bool { - self.disabled_reason_with(id, params).is_none() - } - - /// Why the command can't run now (None = it can): its own precondition, or a background job - /// running on the active document. - pub fn disabled_reason(&self, id: &str) -> Option { - self.disabled_reason_with(id, &Value::Null) - } - - /// [`Self::disabled_reason`] for a call with `params`. - pub fn disabled_reason_with(&self, id: &str, params: &Value) -> Option { - let Some(s) = commands::find(id) else { return Some(format!("unknown command `{id}`")) }; - self.precondition(s, &channel_cmds::inject_target(self, id, params.clone())).err().or_else(|| self.job_conflict(id, s.journal)) - } - - /// The command's own precondition for a call with `params` (their target filled in). - fn precondition(&self, spec: &commands::CommandSpec, params: &Value) -> std::result::Result<(), String> { - if self.names_existing_layer(spec.id, params) { - return Ok(()); - } - // `ifPresent`: with no Background there is nothing to do, which isn't an error. - if spec.id == "layer.new.layerFromBackground" && params.get("ifPresent").and_then(Value::as_bool) == Some(true) { - return self.active().map(|_| ()).ok_or_else(|| "no document open".into()); - } - channel_cmds::mask_target_enabled(self, spec.id, params).unwrap_or_else(|| (spec.enabled)(self)) - } - - /// Whether `id` is a layer command whose `"layer"` param names an existing layer, so it needs no - /// active layer (#2457). Matches how `layer_param` resolves the layer when the command runs. - fn names_existing_layer(&self, id: &str, params: &Value) -> bool { - matches!(id, "layer.hideLayers" | "layer.showLayers" | "layer.renameLayer") - && params.get("layer").and_then(Value::as_u64).is_some_and(|l| self.active().is_some_and(|st| st.doc.layer(LayerId(l)).is_some())) - } - - /// The precondition of a command whose params document `"layer":id` (it acts on that layer), - /// when `params` name an existing layer of the active document: checked on that layer rather - /// than on the active one, which stays active (#466). A script, action or agent can then - /// Replace Contents, Rasterize or Merge Down a layer without selecting it first. `None` for - /// other commands, or without such a layer. - pub(crate) fn explicit_layer_enabled(&mut self, spec: &commands::CommandSpec, params: &Value) -> Option> { - if !spec.params.contains("\"layer\":id") { - return None; - } - let target = LayerId(params.get("layer")?.as_u64()?); - let d = self.active_mut()?; - d.doc.layer(target)?; - let active = d.active_layer.replace(target); - let r = self.precondition(spec, params); - if let Some(d) = self.active_mut() { - d.active_layer = active; - } - Some(r) - } - - /// Apply an undoable edit to the active document. - pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Option) -> Result) -> Result { - // Every mutation path (linked-file refresh, transform, place) re-renders smart objects - // through this entry; the requesting session's authority must reach those renders. - let _authorization = crate::jobs::render_authorization_scope(self.authorize); - let _document = crate::doc_path::scope(self.active().and_then(|d| d.path.as_deref()).map(std::path::Path::new)); - let restrict = self.color_restrict; - let filter_mask_layer = self.filter_mask_layer; - let sampler_map = self.sampler_map.take(); - let symmetry_map = self.symmetry_map.take(); - let st = self.active_mut().ok_or(EngineError::NoDocument)?; - let before = st.doc.clone(); - // Selecting layers is not a step, so the state this edit leaves behind targets what was - // selected just before it (#1356): undoing a stroke keeps the painted layer active. - let prior = st.layer_target(); - let mut doc = (*before).clone(); - let mut active = st.active_layer; - let r = f(&mut doc, &mut active)?; - if let (Some(k), Some(id)) = (restrict, active) { - channel_cmds::restrict_to_color(&before, &mut doc, id, k); - } - if let Some(id) = filter_mask_layer { - smart_cmds::refresh_after_filter_mask_edit(&mut doc, id)?; - } - st.doc = Arc::new(doc); - st.active_layer = active; - fix_selection(st); - channel_cmds::fix_view(st); - // A canvas-size change (crop, Canvas Size, Image Size, rotation) moves the Color Sampler - // points with their pixels and drops the ones that land outside the new canvas. View - // state: not a history step. A mapped edit (the four above) gives the exact map; any other - // size change falls back to dropping whatever is now outside. - let mut samplers_removed = 0; - if let Some(a) = sampler_map { - let bounds = st.doc.bounds(); - let n = st.color_samplers.len(); - st.color_samplers.retain_mut(|p| { - let q = a.apply(photocraft_geom::Point::new(p[0], p[1])); - *p = [q.x, q.y]; - bounds.contains(q.x.floor() as i32, q.y.floor() as i32) - }); - samplers_removed = n - st.color_samplers.len(); - } else if st.doc.size != before.size { - let bounds = st.doc.bounds(); - let n = st.color_samplers.len(); - st.color_samplers.retain(|p| bounds.contains(p[0].floor() as i32, p[1].floor() as i32)); - samplers_removed = n - st.color_samplers.len(); - } - // The painting symmetry stays on its pixels too (Photoshop keeps it as a path). - if let Some(a) = symmetry_map { - st.symmetry = st.symmetry.take().and_then(|sym| sym.transform(&a)); - } - // The pixels the edit can have changed, as its undo would report them: nothing for a - // selection, guides or a layer's name (a new lasso selection used to recomposite a large - // document, seconds on the CPU path, #1773), a new or deleted layer's bounds (a - // duplicate or a paste), and everything when that can't be bounded. A command may still - // report its own, tighter damage after this. - let damage = layer_multi_cmds::step_damage(&before, &st.doc); - let keep_clean = st.keeps_clean(&before); - let key = self.coalesce_request.clone(); - let st = self.active_mut().ok_or(EngineError::NoDocument)?; - let layers = st.layer_target(); - if key.is_none() || st.coalesce != key || !st.history.can_undo() { - st.history.set_current_layers(prior); - st.history.record(label, before, layers); - st.trim_history(); - } else { - st.history.set_current_layers(layers); - } - st.coalesce = key; - st.bump_revision(keep_clean); - st.last_damage = damage; - self.samplers_removed += samplers_removed; - if damage.is_none_or(|d| !d.is_empty()) { - // Free the mask early; a stale entry would only miss (it is keyed by pixels). - self.subject_cache = Default::default(); - self.object_finder = Default::default(); - } - Ok(r) - } - - /// Replace the active document's active layer without creating a history step. - pub fn select_layer(&mut self, id: LayerId) -> Result<()> { - let st = self.active_mut().ok_or(EngineError::NoDocument)?; - if st.doc.layer(id).is_none() { - return Err(EngineError::NoLayer(id)); - } - st.active_layer = Some(id); - st.selected_layers = vec![id]; - st.layer_anchor = Some(id); - channel_cmds::fix_view(st); - // Selecting a layer is not an edit: keep a clean document clean. - let clean = st.saved_revision == st.revision; - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(photocraft_geom::Rect::EMPTY); - Ok(()) - } - - /// Put back a layer selection (active layer, selected layers, anchor) that a step moved, such - /// as the undo ending an empty Type Mask, which restores the selection from before it. `None` - /// is no layer selected. Selected layers that are gone are dropped; an active layer that is - /// gone is an error and changes nothing. Like [`Self::select_layer`], not an edit. - pub fn restore_layer_selection(&mut self, active: Option, selected: &[LayerId], anchor: Option) -> Result<()> { - let st = self.active_mut().ok_or(EngineError::NoDocument)?; - if let Some(id) = active - && st.doc.layer(id).is_none() - { - return Err(EngineError::NoLayer(id)); - } - st.active_layer = active; - st.selected_layers = selected.to_vec(); - st.layer_anchor = anchor.filter(|_| active.is_some()); - fix_selection(st); - channel_cmds::fix_view(st); - let clean = st.saved_revision == st.revision; - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(photocraft_geom::Rect::EMPTY); - Ok(()) - } - - /// Re-renders the pixels of type layers whose font arrived after they were drawn (the web - /// build fetches served fonts on demand, `photocraft_text::served`). The layers' model is - /// unchanged, so this is no history step and leaves a clean document clean. Unknown documents - /// and layers are skipped. A document a background job is computing from must not move under - /// it: its layers are returned, to try again later. - pub fn refresh_type_layers(&mut self, layers: &[(photocraft_doc::DocId, LayerId)]) -> Vec<(photocraft_doc::DocId, LayerId)> { - let mut busy = Vec::new(); - let mut docs: Vec = Vec::new(); - for (d, _) in layers { - if !docs.contains(d) { - docs.push(*d); - } - } - for doc_id in docs { - let mine = layers.iter().filter(|(d, _)| *d == doc_id); - if self.job_on(doc_id).is_some() { - busy.extend(mine); - continue; - } - let Some(st) = self.docs.iter_mut().find(|st| st.doc.id == doc_id) else { continue }; - let snapshot = st.doc.clone(); - let mut doc = (*snapshot).clone(); - let mut changed = false; - for (_, id) in mine { - if let Some(photocraft_doc::Layer { content: photocraft_doc::LayerContent::Text(t), .. }) = doc.layer_mut(*id) { - type_cmds::refresh(&snapshot, t); - changed = true; - } - } - if changed { - let clean = st.saved_revision == st.revision; - st.doc = Arc::new(doc); - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = None; - } - } - busy - } - - pub fn undo(&mut self) -> bool { - // A background job is computing from the current state: it must not move under it. - if self.active_job().is_some() { - return false; - } - let Some(st) = self.active_mut() else { return false }; - st.coalesce = None; - match st.history.undo(st.doc.clone()) { - // Undo Clear History: the list comes back, the document is the same one. Not an - // edit: keep a clean document clean (the revision still moves for the panels). - Some((d, layers)) if Arc::ptr_eq(&d, &st.doc) => { - restore_target(st, layers); - let clean = !st.is_dirty(); - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(photocraft_geom::Rect::EMPTY); - true - } - Some((mut d, layers)) => { - // Save As changes file identity outside history, just like the saved path. - if d.name != st.doc.name { - Arc::make_mut(&mut d).name.clone_from(&st.doc.name); - } - // Pixels this step can have touched, so the canvas recomposites only that - // (it recomposited everything before). - let damage = layer_multi_cmds::step_damage(&d, &st.doc); - let before = std::mem::replace(&mut st.doc, d); - let keep_clean = st.keeps_clean(&before); - restore_target(st, layers); - st.bump_revision(keep_clean); - st.last_damage = damage; - true - } - None => false, - } - } - - pub fn redo(&mut self) -> bool { - if self.active_job().is_some() { - return false; - } - let Some(st) = self.active_mut() else { return false }; - st.coalesce = None; - match st.history.redo(st.doc.clone()) { - Some((mut d, layers)) => { - if d.name != st.doc.name { - Arc::make_mut(&mut d).name.clone_from(&st.doc.name); - } - let damage = layer_multi_cmds::step_damage(&st.doc, &d); - let before = std::mem::replace(&mut st.doc, d); - let keep_clean = st.keeps_clean(&before); - restore_target(st, layers); - st.bump_revision(keep_clean); - st.last_damage = damage; - true - } - None => false, - } - } -} - -/// Undo / redo: target the layers the restored state targeted, as far as they still exist. -fn restore_target(st: &mut DocState, layers: LayerTarget) { - // Deselect Layers is a valid history target, not a missing layer to replace with the top - // layer. An edit after deselection must undo back to no active or selected layers (#3042). - if layers.active.is_none() && layers.selected.is_empty() { - st.active_layer = None; - st.selected_layers.clear(); - st.layer_anchor = None; - channel_cmds::fix_view(st); - return; - } - if layers.active.is_some_and(|id| st.doc.layer(id).is_some()) { - st.active_layer = layers.active; - st.selected_layers = layers.selected; - } - fix_active(st); -} - -fn fix_active(st: &mut DocState) { - if st.active_layer.is_none_or(|id| st.doc.layer(id).is_none()) { - st.active_layer = st.doc.top_layer(); - } - fix_selection(st); - channel_cmds::fix_view(st); -} - -/// Keep the layer selection valid after the document or the active layer changed: drop deleted -/// layers, and collapse to the active layer when a command made a non-member active. -pub(crate) fn fix_selection(st: &mut DocState) { - let Some(active) = st.active_layer else { - st.selected_layers.clear(); - return; - }; - if !st.selected_layers.contains(&active) { - st.selected_layers = vec![active]; - } else { - let live: std::collections::HashSet = st.doc.walk().into_iter().map(|(_, _, l)| l.id).collect(); - st.selected_layers.retain(|id| live.contains(id)); - let mut seen = std::collections::HashSet::new(); - st.selected_layers.retain(|id| seen.insert(*id)); - } - if st.layer_anchor.is_some_and(|a| !st.selected_layers.contains(&a)) { - st.layer_anchor = Some(active); - } -} - #[cfg(test)] mod fill_layer_mode_tests; #[cfg(test)] diff --git a/crates/engine/src/paint_cmds/tests.rs b/crates/engine/src/paint_cmds/tests.rs index a2d11d3e3c..ba30e9d719 100644 --- a/crates/engine/src/paint_cmds/tests.rs +++ b/crates/engine/src/paint_cmds/tests.rs @@ -265,8 +265,7 @@ fn gradient_dither_breaks_banding() { // per-pixel noise with dither on (which breaks 8-bit banding). let run = |dither: bool| { let mut s = session(); - s.execute("paint.gradient", json!({"from": [0, 0], "to": [19, 0], "colors": [[0.5, 0.5, 0.5, 1.0], [0.5, 0.5, 0.5, 1.0]], "dither": dither})) - .unwrap(); + s.execute("paint.gradient", json!({"from": [0, 0], "to": [19, 0], "colors": [[0.5, 0.5, 0.5, 1.0], [0.5, 0.5, 0.5, 1.0]], "dither": dither})).unwrap(); (0..19).map(|x| px(&s, x, 5)[0]).collect::>() }; let smooth = run(false); diff --git a/crates/engine/src/photo_cmds/tests.rs b/crates/engine/src/photo_cmds/tests.rs index 1fdf35f8b2..8d0152a986 100644 --- a/crates/engine/src/photo_cmds/tests.rs +++ b/crates/engine/src/photo_cmds/tests.rs @@ -211,11 +211,8 @@ fn crop_and_straighten_keeps_duotone_inks() { let mut s = Session::new(); s.add_document(scan_with_one_photo(), None); s.execute("image.mode.grayscale", json!({})).unwrap(); - s.execute( - "image.mode.duotone", - json!({"type": "duotone", "inks": [{"name": "Black", "color": [0, 0, 0]}, {"name": "Orange", "color": [255, 128, 0]}]}), - ) - .unwrap(); + s.execute("image.mode.duotone", json!({"type": "duotone", "inks": [{"name": "Black", "color": [0, 0, 0]}, {"name": "Orange", "color": [255, 128, 0]}]})) + .unwrap(); let src = s.documents()[0].doc.duotone.clone(); assert!(src.is_some()); let r = s.execute("file.automate.cropAndStraightenPhotos", json!({})).unwrap(); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs new file mode 100644 index 0000000000..7233436391 --- /dev/null +++ b/crates/engine/src/session.rs @@ -0,0 +1,587 @@ +use super::doc_state::DocState; +use super::error::{EngineError, Result}; +use super::*; + +/// Move item `i` of `v` to position `to`, clamped to the end. Returns where it went; `None` when +/// `i` is out of range. +pub fn move_item(v: &mut Vec, i: usize, to: usize) -> Option { + if i >= v.len() { + return None; + } + let x = v.remove(i); + let to = to.min(v.len()); + v.insert(to, x); + Some(to) +} + +impl Session { + pub fn new() -> Self { + Self::default() + } + + pub fn documents(&self) -> &[DocState] { + &self.docs + } + pub fn active_index(&self) -> Option { + self.active + } + pub fn active(&self) -> Option<&DocState> { + self.active.and_then(|i| self.docs.get(i)) + } + pub fn active_mut(&mut self) -> Option<&mut DocState> { + self.active.and_then(|i| self.docs.get_mut(i)) + } + /// Monotonic active-document generation. It changes when a different document becomes + /// active, including a switch away and back between two observations; equal values therefore + /// mean the document was not switched in between. + pub fn active_generation(&self) -> u64 { + self.active_generation + } + /// Bump [`Self::active_generation`] when the active document id changed. Call after every + /// assignment to `self.active`. + pub(crate) fn note_active_change(&mut self) { + let id = self.active().map(|st| st.doc.id); + if id != self.active_doc_for_generation { + self.active_doc_for_generation = id; + self.active_generation = self.active_generation.wrapping_add(1); + } + } + pub fn set_active(&mut self, index: usize) -> bool { + if index < self.docs.len() { + self.active = Some(index); + self.note_active_change(); + self.sync_tools_mask_target(); + true + } else { + false + } + } + + /// Color Sampler points dropped by the last canvas-size change (crop, Canvas Size, Image Size, + /// rotation) since this was last called, for the status message. See [`edit`](Self::edit). + pub fn take_samplers_removed(&mut self) -> usize { + std::mem::take(&mut self.samplers_removed) + } + + /// Move the Color Sampler points through `a` in the next [`Session::edit`] (crop, Canvas Size, + /// Image Size, rotation), dropping the ones that land outside the new canvas. View state: the + /// points stay pinned to their pixels, no history step. Cleared by the edit it is set for. + /// The painting symmetry moves through `a` too. + pub(crate) fn set_sampler_map(&mut self, a: photocraft_geom::Affine) { + self.set_canvas_map(a, a); + } + + /// [`set_sampler_map`](Self::set_sampler_map) for an edit whose sampler map differs from its + /// geometry map (a flip or rotation maps pixel centres): `geometry` moves the painting symmetry. + pub(crate) fn set_canvas_map(&mut self, geometry: photocraft_geom::Affine, samplers: photocraft_geom::Affine) { + self.sampler_map = Some(samplers); + self.symmetry_map = Some(geometry); + } + + pub fn sync_tools_mask_target(&mut self) { + let mask = self.active().is_some_and(|st| st.channel_view.target == crate::channel_cmds::ChannelTarget::LayerMask); + self.tools.target_mask(mask); + } + + /// Move the document at `from` to tab position `to` (clamped to the last), keeping the active + /// document active. Returns its new index; `None` when `from` is out of range. + pub fn move_document(&mut self, from: usize, to: usize) -> Option { + let active = self.active().map(|d| d.doc.id); + let to = move_item(&mut self.docs, from, to)?; + self.active = active.and_then(|id| self.docs.iter().position(|d| d.doc.id == id)); + self.note_active_change(); + Some(to) + } + + /// Add a document (from File → New, an import, etc.) and make it active. + /// Preserve its identity unless another open document already owns it. + /// Identity-dependent callers must read the admitted document at the returned index. + pub fn add_document(&mut self, mut doc: Document, path: Option) -> usize { + // Persisted IDs can overlap the allocator, so check every replacement too. + while self.docs.iter().any(|st| st.doc.id == doc.id) { + doc.id = photocraft_doc::DocId::fresh(); + } + let mut st = DocState::new(doc, path); + st.history.max_states = self.prefs.get().performance.history_states.max(1) as usize; + st.history.max_bytes = self.prefs.get().performance.history_budget_bytes(); + self.docs.push(st); + let i = self.docs.len() - 1; + self.active = Some(i); + self.note_active_change(); + i + } + + /// Holds a decoded document back from opening (see `held_opens`); returns its id. + pub(crate) fn hold_open(&mut self, doc: Document, source_read_only: bool) -> u64 { + self.next_held_open = self.next_held_open.wrapping_add(1); + self.held_opens.push((self.next_held_open, doc, source_read_only)); + self.next_held_open + } + + /// 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)> { + let i = self.held_opens.iter().position(|(h, _, _)| *h == id)?; + let (_, doc, read_only) = self.held_opens.remove(i); + Some((doc, read_only)) + } + + pub fn close(&mut self, index: usize) -> Option { + if index >= self.docs.len() { + return None; + } + smart_cmds::on_close(self, index); + if let Some(id) = self.docs.get(index).map(|d| d.doc.id) { + self.cancel_jobs_on(id); + self.subject_cache.forget_doc(id); + self.object_finder.forget_doc(id); + } + let d = self.docs.remove(index); + self.active = if self.docs.is_empty() { + None + } else { + Some(match self.active { + Some(active) if active > index => active - 1, + Some(active) if active < index => active, + _ => index.min(self.docs.len() - 1), + }) + }; + self.note_active_change(); + Some(d) + } + + /// Run a command by id with JSON params. Returns a JSON result. + /// + /// Any command accepts an optional `"coalesce": ""` param: consecutive edits with the same + /// key (and no other edit, undo or redo in between) share one history step, like Photoshop's + /// single "Edit Type Layer" step for a whole typing session or one step per slider drag. + /// + /// Runs synchronously, including job-capable commands (see [`jobs`]; [`Session::start`] runs + /// those in the background). + pub fn execute(&mut self, id: &str, params: Value) -> Result { + match self.dispatch(id, params, false)? { + jobs::Started::Done(v) => Ok(v), + // Not reached: inline dispatch never starts a job. Waiting is still correct. + jobs::Started::Job(j) => self.wait_job(j), + } + } + + /// Offer a finished live stroke to the next command: a `paint.stroke` / `paint.pencil` whose + /// params match it exactly takes its pixels instead of rendering the stroke again (its result + /// then says `"fromLive": true`); any other command drops the offer. The command still runs + /// through the normal dispatch, so authorization, the journal and history are unchanged. + pub fn offer_live_stroke(&mut self, live: brush_cmds::LiveStroke) -> Result<()> { + self.live_commit = Some(live.into_commit()?); + Ok(()) + } + + /// [`Self::offer_live_stroke`] for a live Clone Stamp or History Brush stroke, taken by the + /// `paint.cloneStamp` / `paint.historyBrush` it was drawn for. Refused for the Healing Brush + /// (it blends on release) and when the brush, layer or clone source changed during the stroke. + pub fn offer_live_retouch(&mut self, live: retouch_cmds::LiveRetouch) -> Result<()> { + let commit = live.into_commit(self)?; + self.live_commit = Some(commit); + Ok(()) + } + + /// [`Self::offer_live_stroke`] for a live Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke, + /// taken by the command it was drawn for: the stroke's finishing dabs are run first. Refused + /// when the brush, tool options or layer changed during the stroke. + pub fn offer_live_dab(&mut self, live: retouch_cmds::LiveDab) -> Result<()> { + // A refused offer withdraws the previous one too. + self.live_commit = None; + let commit = live.into_commit(self)?; + self.live_commit = Some(commit); + Ok(()) + } + + /// Withdraw an offer the command didn't take. + pub fn clear_live_stroke(&mut self) { + self.live_commit = None; + } + + /// Check a call without running it: the command exists, its params have the shape + /// [`Self::execute`] requires (New Layer's fully), and it can run now. For a caller that does + /// something first only when the command will go through: Free Transform applies its box + /// before a new layer is made. + /// + /// Complete for the commands in [`PRECHECKED`]: there it accepts what `execute` accepts, but + /// for the group nesting limit (a test holds the two together). For others it checks only what they share. + pub fn precheck(&mut self, id: &str, params: &Value) -> Result<()> { + let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; + if !(params.is_object() || params.is_null()) { + return Err(EngineError::BadParams { cmd: id.to_string(), msg: "params must be a JSON object".into() }); + } + crate::param_check::check(spec, params)?; + crate::filters::validate_params(id, params)?; + if id == "layer.new.layer" { + crate::new_layer::parse(params)?; + } + // A command that takes `"layer"` (an id or a name, as it resolves it) fails on one the + // document doesn't have. + if spec.params.contains("\"layer\":id") + && let Some(l) = commands::explicit_layer(self, params)? + && self.active().is_none_or(|st| st.doc.layer(l).is_none()) + { + return Err(EngineError::BadParams { cmd: id.to_string(), msg: format!("no layer {}", l.0) }); + } + self.admit(id, spec, params).map(|_| ()) + } + + /// What `dispatch` checks once the params are valid and a floating selection has dropped: + /// the precondition (on a named layer for commands that take one), a job running on the + /// document, a hidden target. The run params (the Channels panel's target filled in) when it + /// may run. + pub(crate) fn admit(&mut self, id: &str, spec: &commands::CommandSpec, params: &Value) -> Result { + let run_params = channel_cmds::inject_target(self, id, commands::inject_kind(id, params.clone())); + if let Err(why) = self.explicit_layer_enabled(spec, params).unwrap_or_else(|| self.precondition(spec, &run_params)) { + return Err(EngineError::Disabled(id.to_string(), why)); + } + if let Some(why) = self.job_conflict(id, spec.journal) { + return Err(EngineError::Disabled(id.to_string(), why)); + } + // Painting on or moving a hidden layer is refused, as in Photoshop (#571). + if let Some(why) = hidden_target::refusal(self, id, params) { + return Err(EngineError::Other(why.into())); + } + Ok(run_params) + } + + /// Is the command currently runnable? (drives menu enablement) + pub fn is_enabled(&self, id: &str) -> bool { + self.is_enabled_with(id, &Value::Null) + } + + /// [`Self::is_enabled`] for a call with `params`: their `"target"` can enable a command, as a + /// targeted layer mask enables Image › Adjustments › Invert on an adjustment layer (#780). + pub fn is_enabled_with(&self, id: &str, params: &Value) -> bool { + self.disabled_reason_with(id, params).is_none() + } + + /// Why the command can't run now (None = it can): its own precondition, or a background job + /// running on the active document. + pub fn disabled_reason(&self, id: &str) -> Option { + self.disabled_reason_with(id, &Value::Null) + } + + /// [`Self::disabled_reason`] for a call with `params`. + pub fn disabled_reason_with(&self, id: &str, params: &Value) -> Option { + let Some(s) = commands::find(id) else { return Some(format!("unknown command `{id}`")) }; + self.precondition(s, &channel_cmds::inject_target(self, id, params.clone())).err().or_else(|| self.job_conflict(id, s.journal)) + } + + /// The command's own precondition for a call with `params` (their target filled in). + fn precondition(&self, spec: &commands::CommandSpec, params: &Value) -> std::result::Result<(), String> { + if self.names_existing_layer(spec.id, params) { + return Ok(()); + } + // `ifPresent`: with no Background there is nothing to do, which isn't an error. + if spec.id == "layer.new.layerFromBackground" && params.get("ifPresent").and_then(Value::as_bool) == Some(true) { + return self.active().map(|_| ()).ok_or_else(|| "no document open".into()); + } + channel_cmds::mask_target_enabled(self, spec.id, params).unwrap_or_else(|| (spec.enabled)(self)) + } + + /// Whether `id` is a layer command whose `"layer"` param names an existing layer, so it needs no + /// active layer (#2457). Matches how `layer_param` resolves the layer when the command runs. + fn names_existing_layer(&self, id: &str, params: &Value) -> bool { + matches!(id, "layer.hideLayers" | "layer.showLayers" | "layer.renameLayer") + && params.get("layer").and_then(Value::as_u64).is_some_and(|l| self.active().is_some_and(|st| st.doc.layer(LayerId(l)).is_some())) + } + + /// The precondition of a command whose params document `"layer":id` (it acts on that layer), + /// when `params` name an existing layer of the active document: checked on that layer rather + /// than on the active one, which stays active (#466). A script, action or agent can then + /// Replace Contents, Rasterize or Merge Down a layer without selecting it first. `None` for + /// other commands, or without such a layer. + pub(crate) fn explicit_layer_enabled(&mut self, spec: &commands::CommandSpec, params: &Value) -> Option> { + if !spec.params.contains("\"layer\":id") { + return None; + } + let target = LayerId(params.get("layer")?.as_u64()?); + let d = self.active_mut()?; + d.doc.layer(target)?; + let active = d.active_layer.replace(target); + let r = self.precondition(spec, params); + if let Some(d) = self.active_mut() { + d.active_layer = active; + } + Some(r) + } + + /// Apply an undoable edit to the active document. + pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Option) -> Result) -> Result { + // Every mutation path (linked-file refresh, transform, place) re-renders smart objects + // through this entry; the requesting session's authority must reach those renders. + let _authorization = crate::jobs::render_authorization_scope(self.authorize); + let _document = crate::doc_path::scope(self.active().and_then(|d| d.path.as_deref()).map(std::path::Path::new)); + let restrict = self.color_restrict; + let filter_mask_layer = self.filter_mask_layer; + let sampler_map = self.sampler_map.take(); + let symmetry_map = self.symmetry_map.take(); + let st = self.active_mut().ok_or(EngineError::NoDocument)?; + let before = st.doc.clone(); + // Selecting layers is not a step, so the state this edit leaves behind targets what was + // selected just before it (#1356): undoing a stroke keeps the painted layer active. + let prior = st.layer_target(); + let mut doc = (*before).clone(); + let mut active = st.active_layer; + let r = f(&mut doc, &mut active)?; + if let (Some(k), Some(id)) = (restrict, active) { + channel_cmds::restrict_to_color(&before, &mut doc, id, k); + } + if let Some(id) = filter_mask_layer { + smart_cmds::refresh_after_filter_mask_edit(&mut doc, id)?; + } + st.doc = Arc::new(doc); + st.active_layer = active; + fix_selection(st); + channel_cmds::fix_view(st); + // A canvas-size change (crop, Canvas Size, Image Size, rotation) moves the Color Sampler + // points with their pixels and drops the ones that land outside the new canvas. View + // state: not a history step. A mapped edit (the four above) gives the exact map; any other + // size change falls back to dropping whatever is now outside. + let mut samplers_removed = 0; + if let Some(a) = sampler_map { + let bounds = st.doc.bounds(); + let n = st.color_samplers.len(); + st.color_samplers.retain_mut(|p| { + let q = a.apply(photocraft_geom::Point::new(p[0], p[1])); + *p = [q.x, q.y]; + bounds.contains(q.x.floor() as i32, q.y.floor() as i32) + }); + samplers_removed = n - st.color_samplers.len(); + } else if st.doc.size != before.size { + let bounds = st.doc.bounds(); + let n = st.color_samplers.len(); + st.color_samplers.retain(|p| bounds.contains(p[0].floor() as i32, p[1].floor() as i32)); + samplers_removed = n - st.color_samplers.len(); + } + // The painting symmetry stays on its pixels too (Photoshop keeps it as a path). + if let Some(a) = symmetry_map { + st.symmetry = st.symmetry.take().and_then(|sym| sym.transform(&a)); + } + // The pixels the edit can have changed, as its undo would report them: nothing for a + // selection, guides or a layer's name (a new lasso selection used to recomposite a large + // document, seconds on the CPU path, #1773), a new or deleted layer's bounds (a + // duplicate or a paste), and everything when that can't be bounded. A command may still + // report its own, tighter damage after this. + let damage = layer_multi_cmds::step_damage(&before, &st.doc); + let keep_clean = st.keeps_clean(&before); + let key = self.coalesce_request.clone(); + let st = self.active_mut().ok_or(EngineError::NoDocument)?; + let layers = st.layer_target(); + if key.is_none() || st.coalesce != key || !st.history.can_undo() { + st.history.set_current_layers(prior); + st.history.record(label, before, layers); + st.trim_history(); + } else { + st.history.set_current_layers(layers); + } + st.coalesce = key; + st.bump_revision(keep_clean); + st.last_damage = damage; + self.samplers_removed += samplers_removed; + if damage.is_none_or(|d| !d.is_empty()) { + // Free the mask early; a stale entry would only miss (it is keyed by pixels). + self.subject_cache = Default::default(); + self.object_finder = Default::default(); + } + Ok(r) + } + + /// Replace the active document's active layer without creating a history step. + pub fn select_layer(&mut self, id: LayerId) -> Result<()> { + let st = self.active_mut().ok_or(EngineError::NoDocument)?; + if st.doc.layer(id).is_none() { + return Err(EngineError::NoLayer(id)); + } + st.active_layer = Some(id); + st.selected_layers = vec![id]; + st.layer_anchor = Some(id); + channel_cmds::fix_view(st); + // Selecting a layer is not an edit: keep a clean document clean. + let clean = st.saved_revision == st.revision; + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = Some(photocraft_geom::Rect::EMPTY); + Ok(()) + } + + /// Put back a layer selection (active layer, selected layers, anchor) that a step moved, such + /// as the undo ending an empty Type Mask, which restores the selection from before it. `None` + /// is no layer selected. Selected layers that are gone are dropped; an active layer that is + /// gone is an error and changes nothing. Like [`Self::select_layer`], not an edit. + pub fn restore_layer_selection(&mut self, active: Option, selected: &[LayerId], anchor: Option) -> Result<()> { + let st = self.active_mut().ok_or(EngineError::NoDocument)?; + if let Some(id) = active + && st.doc.layer(id).is_none() + { + return Err(EngineError::NoLayer(id)); + } + st.active_layer = active; + st.selected_layers = selected.to_vec(); + st.layer_anchor = anchor.filter(|_| active.is_some()); + fix_selection(st); + channel_cmds::fix_view(st); + let clean = st.saved_revision == st.revision; + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = Some(photocraft_geom::Rect::EMPTY); + Ok(()) + } + + /// Re-renders the pixels of type layers whose font arrived after they were drawn (the web + /// build fetches served fonts on demand, `photocraft_text::served`). The layers' model is + /// unchanged, so this is no history step and leaves a clean document clean. Unknown documents + /// and layers are skipped. A document a background job is computing from must not move under + /// it: its layers are returned, to try again later. + pub fn refresh_type_layers(&mut self, layers: &[(photocraft_doc::DocId, LayerId)]) -> Vec<(photocraft_doc::DocId, LayerId)> { + let mut busy = Vec::new(); + let mut docs: Vec = Vec::new(); + for (d, _) in layers { + if !docs.contains(d) { + docs.push(*d); + } + } + for doc_id in docs { + let mine = layers.iter().filter(|(d, _)| *d == doc_id); + if self.job_on(doc_id).is_some() { + busy.extend(mine); + continue; + } + let Some(st) = self.docs.iter_mut().find(|st| st.doc.id == doc_id) else { continue }; + let snapshot = st.doc.clone(); + let mut doc = (*snapshot).clone(); + let mut changed = false; + for (_, id) in mine { + if let Some(photocraft_doc::Layer { content: photocraft_doc::LayerContent::Text(t), .. }) = doc.layer_mut(*id) { + type_cmds::refresh(&snapshot, t); + changed = true; + } + } + if changed { + let clean = st.saved_revision == st.revision; + st.doc = Arc::new(doc); + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = None; + } + } + busy + } + + pub fn undo(&mut self) -> bool { + // A background job is computing from the current state: it must not move under it. + if self.active_job().is_some() { + return false; + } + let Some(st) = self.active_mut() else { return false }; + st.coalesce = None; + match st.history.undo(st.doc.clone()) { + // Undo Clear History: the list comes back, the document is the same one. Not an + // edit: keep a clean document clean (the revision still moves for the panels). + Some((d, layers)) if Arc::ptr_eq(&d, &st.doc) => { + restore_target(st, layers); + let clean = !st.is_dirty(); + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = Some(photocraft_geom::Rect::EMPTY); + true + } + Some((mut d, layers)) => { + // Save As changes file identity outside history, just like the saved path. + if d.name != st.doc.name { + Arc::make_mut(&mut d).name.clone_from(&st.doc.name); + } + // Pixels this step can have touched, so the canvas recomposites only that + // (it recomposited everything before). + let damage = layer_multi_cmds::step_damage(&d, &st.doc); + let before = std::mem::replace(&mut st.doc, d); + let keep_clean = st.keeps_clean(&before); + restore_target(st, layers); + st.bump_revision(keep_clean); + st.last_damage = damage; + true + } + None => false, + } + } + + pub fn redo(&mut self) -> bool { + if self.active_job().is_some() { + return false; + } + let Some(st) = self.active_mut() else { return false }; + st.coalesce = None; + match st.history.redo(st.doc.clone()) { + Some((mut d, layers)) => { + if d.name != st.doc.name { + Arc::make_mut(&mut d).name.clone_from(&st.doc.name); + } + let damage = layer_multi_cmds::step_damage(&st.doc, &d); + let before = std::mem::replace(&mut st.doc, d); + let keep_clean = st.keeps_clean(&before); + restore_target(st, layers); + st.bump_revision(keep_clean); + st.last_damage = damage; + true + } + None => false, + } + } +} + +/// Undo / redo: target the layers the restored state targeted, as far as they still exist. +pub(crate) fn restore_target(st: &mut DocState, layers: LayerTarget) { + // Deselect Layers is a valid history target, not a missing layer to replace with the top + // layer. An edit after deselection must undo back to no active or selected layers (#3042). + if layers.active.is_none() && layers.selected.is_empty() { + st.active_layer = None; + st.selected_layers.clear(); + st.layer_anchor = None; + channel_cmds::fix_view(st); + return; + } + if layers.active.is_some_and(|id| st.doc.layer(id).is_some()) { + st.active_layer = layers.active; + st.selected_layers = layers.selected; + } + fix_active(st); +} + +fn fix_active(st: &mut DocState) { + if st.active_layer.is_none_or(|id| st.doc.layer(id).is_none()) { + st.active_layer = st.doc.top_layer(); + } + fix_selection(st); + channel_cmds::fix_view(st); +} + +/// Keep the layer selection valid after the document or the active layer changed: drop deleted +/// layers, and collapse to the active layer when a command made a non-member active. +pub(crate) fn fix_selection(st: &mut DocState) { + let Some(active) = st.active_layer else { + st.selected_layers.clear(); + return; + }; + if !st.selected_layers.contains(&active) { + st.selected_layers = vec![active]; + } else { + let live: std::collections::HashSet = st.doc.walk().into_iter().map(|(_, _, l)| l.id).collect(); + st.selected_layers.retain(|id| live.contains(id)); + let mut seen = std::collections::HashSet::new(); + st.selected_layers.retain(|id| seen.insert(*id)); + } + if st.layer_anchor.is_some_and(|a| !st.selected_layers.contains(&a)) { + st.layer_anchor = Some(active); + } +} diff --git a/crates/engine/src/smartselect_cmds/tests.rs b/crates/engine/src/smartselect_cmds/tests.rs index f71cae6f85..8cb19565b5 100644 --- a/crates/engine/src/smartselect_cmds/tests.rs +++ b/crates/engine/src/smartselect_cmds/tests.rs @@ -526,10 +526,7 @@ fn sel_bytes(s: &Session, w: i32, h: i32) -> Vec { #[test] fn refine_edge_refuses_a_selection_too_large_to_refine() { let mut s = Session::new(); - s.add_document( - Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8), - None, - ); + s.add_document(Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8), None); s.execute("select.rect", json!({"x": 10, "y": 60, "width": 10, "height": 10})).unwrap(); let small = s.active().and_then(|d| d.doc.selection.clone()).expect("selected"); let diagonal = json!({"edits": [{"tool": "brush", "points": [[0, 0], [99_999, 99_999]], "size": 1}]}); @@ -553,10 +550,7 @@ fn refine_edge_refuses_a_selection_too_large_to_refine() { #[test] fn refine_edge_refuses_edits_that_cross_too_many_tiles() { let mut s = Session::new(); - s.add_document( - Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8), - None, - ); + s.add_document(Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8), None); s.execute("select.rect", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); let before = s.active().and_then(|d| d.doc.selection.clone()).expect("selected"); let zigzag: Vec<[f32; 2]> = (0..20).map(|i| [if i % 2 == 0 { 0.0 } else { 99_999.0 }, i as f32 * 5000.0]).collect(); @@ -590,10 +584,8 @@ fn refine_edge_edits_apply_each_tool_at_every_depth() { // Quick Selection grows across the cool region; subtracting it again leaves the start. let quick = run(&mut s, json!([{"tool": "quick", "points": [[100, 50], [110, 50]], "size": 8}])); assert!(at(&quick, 120, 80) >= 128 && at(&quick, 5, 5) >= 128 && at(&quick, 40, 60) < 128, "depth {depth}: quick"); - let back = run( - &mut s, - json!([{"tool": "quick", "points": [[100, 50]], "size": 8}, {"tool": "quick", "points": [[100, 50]], "size": 8, "mode": "subtract"}]), - ); + let back = + run(&mut s, json!([{"tool": "quick", "points": [[100, 50]], "size": 8}, {"tool": "quick", "points": [[100, 50]], "size": 8, "mode": "subtract"}])); assert!(at(&back, 120, 80) < 128 && at(&back, 5, 5) >= 128, "depth {depth}: quick subtract"); // The Brush paints exactly where it goes. let brush = run(&mut s, json!([{"tool": "brush", "points": [[30, 80], [60, 80]], "size": 10}])); @@ -677,8 +669,7 @@ fn refine_edge_edits_match_the_tools_and_reach_the_outputs() { fn refine_edge_rejects_bad_edits_and_keeps_the_selection() { let mut s = blurred_edge_selected(); let before = sel_bytes(&s, 80, 40); - for bad in - [json!(7), json!([{"tool": "nope"}]), json!([{"tool": "lasso", "points": [[0, 0]]}]), json!([{"tool": "brush", "points": [[0, 0]], "size": -1}])] + for bad in [json!(7), json!([{"tool": "nope"}]), json!([{"tool": "lasso", "points": [[0, 0]]}]), json!([{"tool": "brush", "points": [[0, 0]], "size": -1}])] { assert!(s.execute("select.refineEdge", json!({"edits": bad})).is_err(), "{bad}"); assert_eq!(sel_bytes(&s, 80, 40), before, "{bad}"); diff --git a/crates/engine/src/type_cmds/tests.rs b/crates/engine/src/type_cmds/tests.rs index 81ce84d699..b9851d27e1 100644 --- a/crates/engine/src/type_cmds/tests.rs +++ b/crates/engine/src/type_cmds/tests.rs @@ -367,9 +367,8 @@ fn trailing_empty_paragraph_styles_without_changing_previous_lines() { #[test] fn set_style_paragraph_and_box() { let mut s = session(); - let id = s.execute("type.create", json!({"box": [10, 10, 80, 80], "text": "one two three four five six seven", "size": 12})).unwrap()["layer"] - .as_u64() - .unwrap(); + let id = + s.execute("type.create", json!({"box": [10, 10, 80, 80], "text": "one two three four five six seven", "size": 12})).unwrap()["layer"].as_u64().unwrap(); let info = s.execute("type.setStyle", json!({"layer": id, "align": "center", "leading": 20})).unwrap(); let lines = info["lines"].as_array().unwrap(); assert!(lines.len() >= 3); @@ -569,8 +568,7 @@ b", "size": 20}), Xb"}), ) .unwrap(); - let paragraphs: Vec<(usize, photocraft_doc::text::TextAlign)> = - text_layer(&s, id).paragraph_runs().into_iter().map(|r| (r.len, r.style.align)).collect(); + let paragraphs: Vec<(usize, photocraft_doc::text::TextAlign)> = text_layer(&s, id).paragraph_runs().into_iter().map(|r| (r.len, r.style.align)).collect(); assert_eq!(paragraphs.first().map(|p| p.0), Some(2), "{paragraphs:?}"); assert_eq!(paragraphs.get(1).copied(), Some((2, photocraft_doc::text::TextAlign::Right)), "{paragraphs:?}"); } @@ -773,9 +771,11 @@ fn relative_steps_move_each_character_from_its_own_value() { // Clamped to the ranges. s.execute("type.setStyle", json!({"layer": id, "leadingBy": -5000, "baselineShiftBy": 10000, "trackingBy": -11000})).unwrap(); let t = text_layer(&s, id); - assert!(t.char_runs().iter().all(|r| r.style.leading_pt == Some(LEADING_MIN_PT) - && r.style.baseline_shift_pt == BASELINE_SHIFT_MAX_PT - && r.style.tracking == TRACKING_MIN as f32)); + assert!( + t.char_runs().iter().all(|r| r.style.leading_pt == Some(LEADING_MIN_PT) + && r.style.baseline_shift_pt == BASELINE_SHIFT_MAX_PT + && r.style.tracking == TRACKING_MIN as f32) + ); // A collapsed range in non-empty text changes no character. let before = text_layer(&s, id).char_runs(); s.execute("type.setStyle", json!({"layer": id, "range": [3, 3], "trackingBy": 100})).unwrap(); From f0a3c5527b5bc27b3874a995d0b599c43257a133 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:41:49 +0000 Subject: [PATCH 200/259] refactor(engine): split session.rs into session/ --- crates/engine/src/session.rs | 588 +------------------------ crates/engine/src/session/documents.rs | 165 +++++++ crates/engine/src/session/execute.rs | 244 ++++++++++ crates/engine/src/session/history.rs | 104 +++++ crates/engine/src/session/layers.rs | 91 ++++ 5 files changed, 610 insertions(+), 582 deletions(-) create mode 100644 crates/engine/src/session/documents.rs create mode 100644 crates/engine/src/session/execute.rs create mode 100644 crates/engine/src/session/history.rs create mode 100644 crates/engine/src/session/layers.rs diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 7233436391..18eb3dc80a 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -2,586 +2,10 @@ use super::doc_state::DocState; use super::error::{EngineError, Result}; use super::*; -/// Move item `i` of `v` to position `to`, clamped to the end. Returns where it went; `None` when -/// `i` is out of range. -pub fn move_item(v: &mut Vec, i: usize, to: usize) -> Option { - if i >= v.len() { - return None; - } - let x = v.remove(i); - let to = to.min(v.len()); - v.insert(to, x); - Some(to) -} +mod documents; +mod execute; +mod history; +mod layers; -impl Session { - pub fn new() -> Self { - Self::default() - } - - pub fn documents(&self) -> &[DocState] { - &self.docs - } - pub fn active_index(&self) -> Option { - self.active - } - pub fn active(&self) -> Option<&DocState> { - self.active.and_then(|i| self.docs.get(i)) - } - pub fn active_mut(&mut self) -> Option<&mut DocState> { - self.active.and_then(|i| self.docs.get_mut(i)) - } - /// Monotonic active-document generation. It changes when a different document becomes - /// active, including a switch away and back between two observations; equal values therefore - /// mean the document was not switched in between. - pub fn active_generation(&self) -> u64 { - self.active_generation - } - /// Bump [`Self::active_generation`] when the active document id changed. Call after every - /// assignment to `self.active`. - pub(crate) fn note_active_change(&mut self) { - let id = self.active().map(|st| st.doc.id); - if id != self.active_doc_for_generation { - self.active_doc_for_generation = id; - self.active_generation = self.active_generation.wrapping_add(1); - } - } - pub fn set_active(&mut self, index: usize) -> bool { - if index < self.docs.len() { - self.active = Some(index); - self.note_active_change(); - self.sync_tools_mask_target(); - true - } else { - false - } - } - - /// Color Sampler points dropped by the last canvas-size change (crop, Canvas Size, Image Size, - /// rotation) since this was last called, for the status message. See [`edit`](Self::edit). - pub fn take_samplers_removed(&mut self) -> usize { - std::mem::take(&mut self.samplers_removed) - } - - /// Move the Color Sampler points through `a` in the next [`Session::edit`] (crop, Canvas Size, - /// Image Size, rotation), dropping the ones that land outside the new canvas. View state: the - /// points stay pinned to their pixels, no history step. Cleared by the edit it is set for. - /// The painting symmetry moves through `a` too. - pub(crate) fn set_sampler_map(&mut self, a: photocraft_geom::Affine) { - self.set_canvas_map(a, a); - } - - /// [`set_sampler_map`](Self::set_sampler_map) for an edit whose sampler map differs from its - /// geometry map (a flip or rotation maps pixel centres): `geometry` moves the painting symmetry. - pub(crate) fn set_canvas_map(&mut self, geometry: photocraft_geom::Affine, samplers: photocraft_geom::Affine) { - self.sampler_map = Some(samplers); - self.symmetry_map = Some(geometry); - } - - pub fn sync_tools_mask_target(&mut self) { - let mask = self.active().is_some_and(|st| st.channel_view.target == crate::channel_cmds::ChannelTarget::LayerMask); - self.tools.target_mask(mask); - } - - /// Move the document at `from` to tab position `to` (clamped to the last), keeping the active - /// document active. Returns its new index; `None` when `from` is out of range. - pub fn move_document(&mut self, from: usize, to: usize) -> Option { - let active = self.active().map(|d| d.doc.id); - let to = move_item(&mut self.docs, from, to)?; - self.active = active.and_then(|id| self.docs.iter().position(|d| d.doc.id == id)); - self.note_active_change(); - Some(to) - } - - /// Add a document (from File → New, an import, etc.) and make it active. - /// Preserve its identity unless another open document already owns it. - /// Identity-dependent callers must read the admitted document at the returned index. - pub fn add_document(&mut self, mut doc: Document, path: Option) -> usize { - // Persisted IDs can overlap the allocator, so check every replacement too. - while self.docs.iter().any(|st| st.doc.id == doc.id) { - doc.id = photocraft_doc::DocId::fresh(); - } - let mut st = DocState::new(doc, path); - st.history.max_states = self.prefs.get().performance.history_states.max(1) as usize; - st.history.max_bytes = self.prefs.get().performance.history_budget_bytes(); - self.docs.push(st); - let i = self.docs.len() - 1; - self.active = Some(i); - self.note_active_change(); - i - } - - /// Holds a decoded document back from opening (see `held_opens`); returns its id. - pub(crate) fn hold_open(&mut self, doc: Document, source_read_only: bool) -> u64 { - self.next_held_open = self.next_held_open.wrapping_add(1); - self.held_opens.push((self.next_held_open, doc, source_read_only)); - self.next_held_open - } - - /// 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)> { - let i = self.held_opens.iter().position(|(h, _, _)| *h == id)?; - let (_, doc, read_only) = self.held_opens.remove(i); - Some((doc, read_only)) - } - - pub fn close(&mut self, index: usize) -> Option { - if index >= self.docs.len() { - return None; - } - smart_cmds::on_close(self, index); - if let Some(id) = self.docs.get(index).map(|d| d.doc.id) { - self.cancel_jobs_on(id); - self.subject_cache.forget_doc(id); - self.object_finder.forget_doc(id); - } - let d = self.docs.remove(index); - self.active = if self.docs.is_empty() { - None - } else { - Some(match self.active { - Some(active) if active > index => active - 1, - Some(active) if active < index => active, - _ => index.min(self.docs.len() - 1), - }) - }; - self.note_active_change(); - Some(d) - } - - /// Run a command by id with JSON params. Returns a JSON result. - /// - /// Any command accepts an optional `"coalesce": ""` param: consecutive edits with the same - /// key (and no other edit, undo or redo in between) share one history step, like Photoshop's - /// single "Edit Type Layer" step for a whole typing session or one step per slider drag. - /// - /// Runs synchronously, including job-capable commands (see [`jobs`]; [`Session::start`] runs - /// those in the background). - pub fn execute(&mut self, id: &str, params: Value) -> Result { - match self.dispatch(id, params, false)? { - jobs::Started::Done(v) => Ok(v), - // Not reached: inline dispatch never starts a job. Waiting is still correct. - jobs::Started::Job(j) => self.wait_job(j), - } - } - - /// Offer a finished live stroke to the next command: a `paint.stroke` / `paint.pencil` whose - /// params match it exactly takes its pixels instead of rendering the stroke again (its result - /// then says `"fromLive": true`); any other command drops the offer. The command still runs - /// through the normal dispatch, so authorization, the journal and history are unchanged. - pub fn offer_live_stroke(&mut self, live: brush_cmds::LiveStroke) -> Result<()> { - self.live_commit = Some(live.into_commit()?); - Ok(()) - } - - /// [`Self::offer_live_stroke`] for a live Clone Stamp or History Brush stroke, taken by the - /// `paint.cloneStamp` / `paint.historyBrush` it was drawn for. Refused for the Healing Brush - /// (it blends on release) and when the brush, layer or clone source changed during the stroke. - pub fn offer_live_retouch(&mut self, live: retouch_cmds::LiveRetouch) -> Result<()> { - let commit = live.into_commit(self)?; - self.live_commit = Some(commit); - Ok(()) - } - - /// [`Self::offer_live_stroke`] for a live Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke, - /// taken by the command it was drawn for: the stroke's finishing dabs are run first. Refused - /// when the brush, tool options or layer changed during the stroke. - pub fn offer_live_dab(&mut self, live: retouch_cmds::LiveDab) -> Result<()> { - // A refused offer withdraws the previous one too. - self.live_commit = None; - let commit = live.into_commit(self)?; - self.live_commit = Some(commit); - Ok(()) - } - - /// Withdraw an offer the command didn't take. - pub fn clear_live_stroke(&mut self) { - self.live_commit = None; - } - - /// Check a call without running it: the command exists, its params have the shape - /// [`Self::execute`] requires (New Layer's fully), and it can run now. For a caller that does - /// something first only when the command will go through: Free Transform applies its box - /// before a new layer is made. - /// - /// Complete for the commands in [`PRECHECKED`]: there it accepts what `execute` accepts, but - /// for the group nesting limit (a test holds the two together). For others it checks only what they share. - pub fn precheck(&mut self, id: &str, params: &Value) -> Result<()> { - let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; - if !(params.is_object() || params.is_null()) { - return Err(EngineError::BadParams { cmd: id.to_string(), msg: "params must be a JSON object".into() }); - } - crate::param_check::check(spec, params)?; - crate::filters::validate_params(id, params)?; - if id == "layer.new.layer" { - crate::new_layer::parse(params)?; - } - // A command that takes `"layer"` (an id or a name, as it resolves it) fails on one the - // document doesn't have. - if spec.params.contains("\"layer\":id") - && let Some(l) = commands::explicit_layer(self, params)? - && self.active().is_none_or(|st| st.doc.layer(l).is_none()) - { - return Err(EngineError::BadParams { cmd: id.to_string(), msg: format!("no layer {}", l.0) }); - } - self.admit(id, spec, params).map(|_| ()) - } - - /// What `dispatch` checks once the params are valid and a floating selection has dropped: - /// the precondition (on a named layer for commands that take one), a job running on the - /// document, a hidden target. The run params (the Channels panel's target filled in) when it - /// may run. - pub(crate) fn admit(&mut self, id: &str, spec: &commands::CommandSpec, params: &Value) -> Result { - let run_params = channel_cmds::inject_target(self, id, commands::inject_kind(id, params.clone())); - if let Err(why) = self.explicit_layer_enabled(spec, params).unwrap_or_else(|| self.precondition(spec, &run_params)) { - return Err(EngineError::Disabled(id.to_string(), why)); - } - if let Some(why) = self.job_conflict(id, spec.journal) { - return Err(EngineError::Disabled(id.to_string(), why)); - } - // Painting on or moving a hidden layer is refused, as in Photoshop (#571). - if let Some(why) = hidden_target::refusal(self, id, params) { - return Err(EngineError::Other(why.into())); - } - Ok(run_params) - } - - /// Is the command currently runnable? (drives menu enablement) - pub fn is_enabled(&self, id: &str) -> bool { - self.is_enabled_with(id, &Value::Null) - } - - /// [`Self::is_enabled`] for a call with `params`: their `"target"` can enable a command, as a - /// targeted layer mask enables Image › Adjustments › Invert on an adjustment layer (#780). - pub fn is_enabled_with(&self, id: &str, params: &Value) -> bool { - self.disabled_reason_with(id, params).is_none() - } - - /// Why the command can't run now (None = it can): its own precondition, or a background job - /// running on the active document. - pub fn disabled_reason(&self, id: &str) -> Option { - self.disabled_reason_with(id, &Value::Null) - } - - /// [`Self::disabled_reason`] for a call with `params`. - pub fn disabled_reason_with(&self, id: &str, params: &Value) -> Option { - let Some(s) = commands::find(id) else { return Some(format!("unknown command `{id}`")) }; - self.precondition(s, &channel_cmds::inject_target(self, id, params.clone())).err().or_else(|| self.job_conflict(id, s.journal)) - } - - /// The command's own precondition for a call with `params` (their target filled in). - fn precondition(&self, spec: &commands::CommandSpec, params: &Value) -> std::result::Result<(), String> { - if self.names_existing_layer(spec.id, params) { - return Ok(()); - } - // `ifPresent`: with no Background there is nothing to do, which isn't an error. - if spec.id == "layer.new.layerFromBackground" && params.get("ifPresent").and_then(Value::as_bool) == Some(true) { - return self.active().map(|_| ()).ok_or_else(|| "no document open".into()); - } - channel_cmds::mask_target_enabled(self, spec.id, params).unwrap_or_else(|| (spec.enabled)(self)) - } - - /// Whether `id` is a layer command whose `"layer"` param names an existing layer, so it needs no - /// active layer (#2457). Matches how `layer_param` resolves the layer when the command runs. - fn names_existing_layer(&self, id: &str, params: &Value) -> bool { - matches!(id, "layer.hideLayers" | "layer.showLayers" | "layer.renameLayer") - && params.get("layer").and_then(Value::as_u64).is_some_and(|l| self.active().is_some_and(|st| st.doc.layer(LayerId(l)).is_some())) - } - - /// The precondition of a command whose params document `"layer":id` (it acts on that layer), - /// when `params` name an existing layer of the active document: checked on that layer rather - /// than on the active one, which stays active (#466). A script, action or agent can then - /// Replace Contents, Rasterize or Merge Down a layer without selecting it first. `None` for - /// other commands, or without such a layer. - pub(crate) fn explicit_layer_enabled(&mut self, spec: &commands::CommandSpec, params: &Value) -> Option> { - if !spec.params.contains("\"layer\":id") { - return None; - } - let target = LayerId(params.get("layer")?.as_u64()?); - let d = self.active_mut()?; - d.doc.layer(target)?; - let active = d.active_layer.replace(target); - let r = self.precondition(spec, params); - if let Some(d) = self.active_mut() { - d.active_layer = active; - } - Some(r) - } - - /// Apply an undoable edit to the active document. - pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Option) -> Result) -> Result { - // Every mutation path (linked-file refresh, transform, place) re-renders smart objects - // through this entry; the requesting session's authority must reach those renders. - let _authorization = crate::jobs::render_authorization_scope(self.authorize); - let _document = crate::doc_path::scope(self.active().and_then(|d| d.path.as_deref()).map(std::path::Path::new)); - let restrict = self.color_restrict; - let filter_mask_layer = self.filter_mask_layer; - let sampler_map = self.sampler_map.take(); - let symmetry_map = self.symmetry_map.take(); - let st = self.active_mut().ok_or(EngineError::NoDocument)?; - let before = st.doc.clone(); - // Selecting layers is not a step, so the state this edit leaves behind targets what was - // selected just before it (#1356): undoing a stroke keeps the painted layer active. - let prior = st.layer_target(); - let mut doc = (*before).clone(); - let mut active = st.active_layer; - let r = f(&mut doc, &mut active)?; - if let (Some(k), Some(id)) = (restrict, active) { - channel_cmds::restrict_to_color(&before, &mut doc, id, k); - } - if let Some(id) = filter_mask_layer { - smart_cmds::refresh_after_filter_mask_edit(&mut doc, id)?; - } - st.doc = Arc::new(doc); - st.active_layer = active; - fix_selection(st); - channel_cmds::fix_view(st); - // A canvas-size change (crop, Canvas Size, Image Size, rotation) moves the Color Sampler - // points with their pixels and drops the ones that land outside the new canvas. View - // state: not a history step. A mapped edit (the four above) gives the exact map; any other - // size change falls back to dropping whatever is now outside. - let mut samplers_removed = 0; - if let Some(a) = sampler_map { - let bounds = st.doc.bounds(); - let n = st.color_samplers.len(); - st.color_samplers.retain_mut(|p| { - let q = a.apply(photocraft_geom::Point::new(p[0], p[1])); - *p = [q.x, q.y]; - bounds.contains(q.x.floor() as i32, q.y.floor() as i32) - }); - samplers_removed = n - st.color_samplers.len(); - } else if st.doc.size != before.size { - let bounds = st.doc.bounds(); - let n = st.color_samplers.len(); - st.color_samplers.retain(|p| bounds.contains(p[0].floor() as i32, p[1].floor() as i32)); - samplers_removed = n - st.color_samplers.len(); - } - // The painting symmetry stays on its pixels too (Photoshop keeps it as a path). - if let Some(a) = symmetry_map { - st.symmetry = st.symmetry.take().and_then(|sym| sym.transform(&a)); - } - // The pixels the edit can have changed, as its undo would report them: nothing for a - // selection, guides or a layer's name (a new lasso selection used to recomposite a large - // document, seconds on the CPU path, #1773), a new or deleted layer's bounds (a - // duplicate or a paste), and everything when that can't be bounded. A command may still - // report its own, tighter damage after this. - let damage = layer_multi_cmds::step_damage(&before, &st.doc); - let keep_clean = st.keeps_clean(&before); - let key = self.coalesce_request.clone(); - let st = self.active_mut().ok_or(EngineError::NoDocument)?; - let layers = st.layer_target(); - if key.is_none() || st.coalesce != key || !st.history.can_undo() { - st.history.set_current_layers(prior); - st.history.record(label, before, layers); - st.trim_history(); - } else { - st.history.set_current_layers(layers); - } - st.coalesce = key; - st.bump_revision(keep_clean); - st.last_damage = damage; - self.samplers_removed += samplers_removed; - if damage.is_none_or(|d| !d.is_empty()) { - // Free the mask early; a stale entry would only miss (it is keyed by pixels). - self.subject_cache = Default::default(); - self.object_finder = Default::default(); - } - Ok(r) - } - - /// Replace the active document's active layer without creating a history step. - pub fn select_layer(&mut self, id: LayerId) -> Result<()> { - let st = self.active_mut().ok_or(EngineError::NoDocument)?; - if st.doc.layer(id).is_none() { - return Err(EngineError::NoLayer(id)); - } - st.active_layer = Some(id); - st.selected_layers = vec![id]; - st.layer_anchor = Some(id); - channel_cmds::fix_view(st); - // Selecting a layer is not an edit: keep a clean document clean. - let clean = st.saved_revision == st.revision; - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(photocraft_geom::Rect::EMPTY); - Ok(()) - } - - /// Put back a layer selection (active layer, selected layers, anchor) that a step moved, such - /// as the undo ending an empty Type Mask, which restores the selection from before it. `None` - /// is no layer selected. Selected layers that are gone are dropped; an active layer that is - /// gone is an error and changes nothing. Like [`Self::select_layer`], not an edit. - pub fn restore_layer_selection(&mut self, active: Option, selected: &[LayerId], anchor: Option) -> Result<()> { - let st = self.active_mut().ok_or(EngineError::NoDocument)?; - if let Some(id) = active - && st.doc.layer(id).is_none() - { - return Err(EngineError::NoLayer(id)); - } - st.active_layer = active; - st.selected_layers = selected.to_vec(); - st.layer_anchor = anchor.filter(|_| active.is_some()); - fix_selection(st); - channel_cmds::fix_view(st); - let clean = st.saved_revision == st.revision; - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(photocraft_geom::Rect::EMPTY); - Ok(()) - } - - /// Re-renders the pixels of type layers whose font arrived after they were drawn (the web - /// build fetches served fonts on demand, `photocraft_text::served`). The layers' model is - /// unchanged, so this is no history step and leaves a clean document clean. Unknown documents - /// and layers are skipped. A document a background job is computing from must not move under - /// it: its layers are returned, to try again later. - pub fn refresh_type_layers(&mut self, layers: &[(photocraft_doc::DocId, LayerId)]) -> Vec<(photocraft_doc::DocId, LayerId)> { - let mut busy = Vec::new(); - let mut docs: Vec = Vec::new(); - for (d, _) in layers { - if !docs.contains(d) { - docs.push(*d); - } - } - for doc_id in docs { - let mine = layers.iter().filter(|(d, _)| *d == doc_id); - if self.job_on(doc_id).is_some() { - busy.extend(mine); - continue; - } - let Some(st) = self.docs.iter_mut().find(|st| st.doc.id == doc_id) else { continue }; - let snapshot = st.doc.clone(); - let mut doc = (*snapshot).clone(); - let mut changed = false; - for (_, id) in mine { - if let Some(photocraft_doc::Layer { content: photocraft_doc::LayerContent::Text(t), .. }) = doc.layer_mut(*id) { - type_cmds::refresh(&snapshot, t); - changed = true; - } - } - if changed { - let clean = st.saved_revision == st.revision; - st.doc = Arc::new(doc); - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = None; - } - } - busy - } - - pub fn undo(&mut self) -> bool { - // A background job is computing from the current state: it must not move under it. - if self.active_job().is_some() { - return false; - } - let Some(st) = self.active_mut() else { return false }; - st.coalesce = None; - match st.history.undo(st.doc.clone()) { - // Undo Clear History: the list comes back, the document is the same one. Not an - // edit: keep a clean document clean (the revision still moves for the panels). - Some((d, layers)) if Arc::ptr_eq(&d, &st.doc) => { - restore_target(st, layers); - let clean = !st.is_dirty(); - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(photocraft_geom::Rect::EMPTY); - true - } - Some((mut d, layers)) => { - // Save As changes file identity outside history, just like the saved path. - if d.name != st.doc.name { - Arc::make_mut(&mut d).name.clone_from(&st.doc.name); - } - // Pixels this step can have touched, so the canvas recomposites only that - // (it recomposited everything before). - let damage = layer_multi_cmds::step_damage(&d, &st.doc); - let before = std::mem::replace(&mut st.doc, d); - let keep_clean = st.keeps_clean(&before); - restore_target(st, layers); - st.bump_revision(keep_clean); - st.last_damage = damage; - true - } - None => false, - } - } - - pub fn redo(&mut self) -> bool { - if self.active_job().is_some() { - return false; - } - let Some(st) = self.active_mut() else { return false }; - st.coalesce = None; - match st.history.redo(st.doc.clone()) { - Some((mut d, layers)) => { - if d.name != st.doc.name { - Arc::make_mut(&mut d).name.clone_from(&st.doc.name); - } - let damage = layer_multi_cmds::step_damage(&st.doc, &d); - let before = std::mem::replace(&mut st.doc, d); - let keep_clean = st.keeps_clean(&before); - restore_target(st, layers); - st.bump_revision(keep_clean); - st.last_damage = damage; - true - } - None => false, - } - } -} - -/// Undo / redo: target the layers the restored state targeted, as far as they still exist. -pub(crate) fn restore_target(st: &mut DocState, layers: LayerTarget) { - // Deselect Layers is a valid history target, not a missing layer to replace with the top - // layer. An edit after deselection must undo back to no active or selected layers (#3042). - if layers.active.is_none() && layers.selected.is_empty() { - st.active_layer = None; - st.selected_layers.clear(); - st.layer_anchor = None; - channel_cmds::fix_view(st); - return; - } - if layers.active.is_some_and(|id| st.doc.layer(id).is_some()) { - st.active_layer = layers.active; - st.selected_layers = layers.selected; - } - fix_active(st); -} - -fn fix_active(st: &mut DocState) { - if st.active_layer.is_none_or(|id| st.doc.layer(id).is_none()) { - st.active_layer = st.doc.top_layer(); - } - fix_selection(st); - channel_cmds::fix_view(st); -} - -/// Keep the layer selection valid after the document or the active layer changed: drop deleted -/// layers, and collapse to the active layer when a command made a non-member active. -pub(crate) fn fix_selection(st: &mut DocState) { - let Some(active) = st.active_layer else { - st.selected_layers.clear(); - return; - }; - if !st.selected_layers.contains(&active) { - st.selected_layers = vec![active]; - } else { - let live: std::collections::HashSet = st.doc.walk().into_iter().map(|(_, _, l)| l.id).collect(); - st.selected_layers.retain(|id| live.contains(id)); - let mut seen = std::collections::HashSet::new(); - st.selected_layers.retain(|id| seen.insert(*id)); - } - if st.layer_anchor.is_some_and(|a| !st.selected_layers.contains(&a)) { - st.layer_anchor = Some(active); - } -} +pub use documents::move_item; +pub(crate) use history::{fix_selection, restore_target}; diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs new file mode 100644 index 0000000000..ea20944fbc --- /dev/null +++ b/crates/engine/src/session/documents.rs @@ -0,0 +1,165 @@ +use super::history::fix_selection; +use super::*; + +/// Move item `i` of `v` to position `to`, clamped to the end. Returns where it went; `None` when +/// `i` is out of range. +pub fn move_item(v: &mut Vec, i: usize, to: usize) -> Option { + if i >= v.len() { + return None; + } + let x = v.remove(i); + let to = to.min(v.len()); + v.insert(to, x); + Some(to) +} + +impl Session { + pub fn new() -> Self { + Self::default() + } + + pub fn documents(&self) -> &[DocState] { + &self.docs + } + + pub fn active_index(&self) -> Option { + self.active + } + + pub fn active(&self) -> Option<&DocState> { + self.active.and_then(|i| self.docs.get(i)) + } + + pub fn active_mut(&mut self) -> Option<&mut DocState> { + self.active.and_then(|i| self.docs.get_mut(i)) + } + + /// Monotonic active-document generation. It changes when a different document becomes + /// active, including a switch away and back between two observations; equal values therefore + /// mean the document was not switched in between. + pub fn active_generation(&self) -> u64 { + self.active_generation + } + + /// Bump [`Self::active_generation`] when the active document id changed. Call after every + /// assignment to `self.active`. + pub(crate) fn note_active_change(&mut self) { + let id = self.active().map(|st| st.doc.id); + if id != self.active_doc_for_generation { + self.active_doc_for_generation = id; + self.active_generation = self.active_generation.wrapping_add(1); + } + } + + pub fn set_active(&mut self, index: usize) -> bool { + if index < self.docs.len() { + self.active = Some(index); + self.note_active_change(); + self.sync_tools_mask_target(); + true + } else { + false + } + } + + /// Color Sampler points dropped by the last canvas-size change (crop, Canvas Size, Image Size, + /// rotation) since this was last called, for the status message. See [`edit`](Self::edit). + pub fn take_samplers_removed(&mut self) -> usize { + std::mem::take(&mut self.samplers_removed) + } + + /// Move the Color Sampler points through `a` in the next [`Session::edit`] (crop, Canvas Size, + /// Image Size, rotation), dropping the ones that land outside the new canvas. View state: the + /// points stay pinned to their pixels, no history step. Cleared by the edit it is set for. + /// The painting symmetry moves through `a` too. + pub(crate) fn set_sampler_map(&mut self, a: photocraft_geom::Affine) { + self.set_canvas_map(a, a); + } + + /// [`set_sampler_map`](Self::set_sampler_map) for an edit whose sampler map differs from its + /// geometry map (a flip or rotation maps pixel centres): `geometry` moves the painting symmetry. + pub(crate) fn set_canvas_map(&mut self, geometry: photocraft_geom::Affine, samplers: photocraft_geom::Affine) { + self.sampler_map = Some(samplers); + self.symmetry_map = Some(geometry); + } + + pub fn sync_tools_mask_target(&mut self) { + let mask = self.active().is_some_and(|st| st.channel_view.target == crate::channel_cmds::ChannelTarget::LayerMask); + self.tools.target_mask(mask); + } + + /// Move the document at `from` to tab position `to` (clamped to the last), keeping the active + /// document active. Returns its new index; `None` when `from` is out of range. + pub fn move_document(&mut self, from: usize, to: usize) -> Option { + let active = self.active().map(|d| d.doc.id); + let to = move_item(&mut self.docs, from, to)?; + self.active = active.and_then(|id| self.docs.iter().position(|d| d.doc.id == id)); + self.note_active_change(); + Some(to) + } + + /// Add a document (from File → New, an import, etc.) and make it active. + /// Preserve its identity unless another open document already owns it. + /// Identity-dependent callers must read the admitted document at the returned index. + pub fn add_document(&mut self, mut doc: Document, path: Option) -> usize { + // Persisted IDs can overlap the allocator, so check every replacement too. + while self.docs.iter().any(|st| st.doc.id == doc.id) { + doc.id = photocraft_doc::DocId::fresh(); + } + let mut st = DocState::new(doc, path); + st.history.max_states = self.prefs.get().performance.history_states.max(1) as usize; + st.history.max_bytes = self.prefs.get().performance.history_budget_bytes(); + self.docs.push(st); + let i = self.docs.len() - 1; + self.active = Some(i); + self.note_active_change(); + i + } + + /// Holds a decoded document back from opening (see `held_opens`); returns its id. + pub(crate) fn hold_open(&mut self, doc: Document, source_read_only: bool) -> u64 { + self.next_held_open = self.next_held_open.wrapping_add(1); + self.held_opens.push((self.next_held_open, doc, source_read_only)); + self.next_held_open + } + + /// 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)> { + let i = self.held_opens.iter().position(|(h, _, _)| *h == id)?; + let (_, doc, read_only) = self.held_opens.remove(i); + Some((doc, read_only)) + } + + pub fn close(&mut self, index: usize) -> Option { + if index >= self.docs.len() { + return None; + } + smart_cmds::on_close(self, index); + if let Some(id) = self.docs.get(index).map(|d| d.doc.id) { + self.cancel_jobs_on(id); + self.subject_cache.forget_doc(id); + self.object_finder.forget_doc(id); + } + let d = self.docs.remove(index); + self.active = if self.docs.is_empty() { + None + } else { + Some(match self.active { + Some(active) if active > index => active - 1, + Some(active) if active < index => active, + _ => index.min(self.docs.len() - 1), + }) + }; + self.note_active_change(); + Some(d) + } +} + +pub(super) fn fix_active(st: &mut DocState) { + if st.active_layer.is_none_or(|id| st.doc.layer(id).is_none()) { + st.active_layer = st.doc.top_layer(); + } + fix_selection(st); + channel_cmds::fix_view(st); +} diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs new file mode 100644 index 0000000000..c3822673bb --- /dev/null +++ b/crates/engine/src/session/execute.rs @@ -0,0 +1,244 @@ +use super::history::fix_selection; +use super::*; + +impl Session { + /// Run a command by id with JSON params. Returns a JSON result. + /// + /// Any command accepts an optional `"coalesce": ""` param: consecutive edits with the same + /// key (and no other edit, undo or redo in between) share one history step, like Photoshop's + /// single "Edit Type Layer" step for a whole typing session or one step per slider drag. + /// + /// Runs synchronously, including job-capable commands (see [`jobs`]; [`Session::start`] runs + /// those in the background). + pub fn execute(&mut self, id: &str, params: Value) -> Result { + match self.dispatch(id, params, false)? { + jobs::Started::Done(v) => Ok(v), + // Not reached: inline dispatch never starts a job. Waiting is still correct. + jobs::Started::Job(j) => self.wait_job(j), + } + } + + /// Offer a finished live stroke to the next command: a `paint.stroke` / `paint.pencil` whose + /// params match it exactly takes its pixels instead of rendering the stroke again (its result + /// then says `"fromLive": true`); any other command drops the offer. The command still runs + /// through the normal dispatch, so authorization, the journal and history are unchanged. + pub fn offer_live_stroke(&mut self, live: brush_cmds::LiveStroke) -> Result<()> { + self.live_commit = Some(live.into_commit()?); + Ok(()) + } + + /// [`Self::offer_live_stroke`] for a live Clone Stamp or History Brush stroke, taken by the + /// `paint.cloneStamp` / `paint.historyBrush` it was drawn for. Refused for the Healing Brush + /// (it blends on release) and when the brush, layer or clone source changed during the stroke. + pub fn offer_live_retouch(&mut self, live: retouch_cmds::LiveRetouch) -> Result<()> { + let commit = live.into_commit(self)?; + self.live_commit = Some(commit); + Ok(()) + } + + /// [`Self::offer_live_stroke`] for a live Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke, + /// taken by the command it was drawn for: the stroke's finishing dabs are run first. Refused + /// when the brush, tool options or layer changed during the stroke. + pub fn offer_live_dab(&mut self, live: retouch_cmds::LiveDab) -> Result<()> { + // A refused offer withdraws the previous one too. + self.live_commit = None; + let commit = live.into_commit(self)?; + self.live_commit = Some(commit); + Ok(()) + } + + /// Withdraw an offer the command didn't take. + pub fn clear_live_stroke(&mut self) { + self.live_commit = None; + } + + /// Check a call without running it: the command exists, its params have the shape + /// [`Self::execute`] requires (New Layer's fully), and it can run now. For a caller that does + /// something first only when the command will go through: Free Transform applies its box + /// before a new layer is made. + /// + /// Complete for the commands in [`PRECHECKED`]: there it accepts what `execute` accepts, but + /// for the group nesting limit (a test holds the two together). For others it checks only what they share. + pub fn precheck(&mut self, id: &str, params: &Value) -> Result<()> { + let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; + if !(params.is_object() || params.is_null()) { + return Err(EngineError::BadParams { cmd: id.to_string(), msg: "params must be a JSON object".into() }); + } + crate::param_check::check(spec, params)?; + crate::filters::validate_params(id, params)?; + if id == "layer.new.layer" { + crate::new_layer::parse(params)?; + } + // A command that takes `"layer"` (an id or a name, as it resolves it) fails on one the + // document doesn't have. + if spec.params.contains("\"layer\":id") + && let Some(l) = commands::explicit_layer(self, params)? + && self.active().is_none_or(|st| st.doc.layer(l).is_none()) + { + return Err(EngineError::BadParams { cmd: id.to_string(), msg: format!("no layer {}", l.0) }); + } + self.admit(id, spec, params).map(|_| ()) + } + + /// What `dispatch` checks once the params are valid and a floating selection has dropped: + /// the precondition (on a named layer for commands that take one), a job running on the + /// document, a hidden target. The run params (the Channels panel's target filled in) when it + /// may run. + pub(crate) fn admit(&mut self, id: &str, spec: &commands::CommandSpec, params: &Value) -> Result { + let run_params = channel_cmds::inject_target(self, id, commands::inject_kind(id, params.clone())); + if let Err(why) = self.explicit_layer_enabled(spec, params).unwrap_or_else(|| self.precondition(spec, &run_params)) { + return Err(EngineError::Disabled(id.to_string(), why)); + } + if let Some(why) = self.job_conflict(id, spec.journal) { + return Err(EngineError::Disabled(id.to_string(), why)); + } + // Painting on or moving a hidden layer is refused, as in Photoshop (#571). + if let Some(why) = hidden_target::refusal(self, id, params) { + return Err(EngineError::Other(why.into())); + } + Ok(run_params) + } + + /// Is the command currently runnable? (drives menu enablement) + pub fn is_enabled(&self, id: &str) -> bool { + self.is_enabled_with(id, &Value::Null) + } + + /// [`Self::is_enabled`] for a call with `params`: their `"target"` can enable a command, as a + /// targeted layer mask enables Image › Adjustments › Invert on an adjustment layer (#780). + pub fn is_enabled_with(&self, id: &str, params: &Value) -> bool { + self.disabled_reason_with(id, params).is_none() + } + + /// Why the command can't run now (None = it can): its own precondition, or a background job + /// running on the active document. + pub fn disabled_reason(&self, id: &str) -> Option { + self.disabled_reason_with(id, &Value::Null) + } + + /// [`Self::disabled_reason`] for a call with `params`. + pub fn disabled_reason_with(&self, id: &str, params: &Value) -> Option { + let Some(s) = commands::find(id) else { return Some(format!("unknown command `{id}`")) }; + self.precondition(s, &channel_cmds::inject_target(self, id, params.clone())).err().or_else(|| self.job_conflict(id, s.journal)) + } + + /// The command's own precondition for a call with `params` (their target filled in). + fn precondition(&self, spec: &commands::CommandSpec, params: &Value) -> std::result::Result<(), String> { + if self.names_existing_layer(spec.id, params) { + return Ok(()); + } + // `ifPresent`: with no Background there is nothing to do, which isn't an error. + if spec.id == "layer.new.layerFromBackground" && params.get("ifPresent").and_then(Value::as_bool) == Some(true) { + return self.active().map(|_| ()).ok_or_else(|| "no document open".into()); + } + channel_cmds::mask_target_enabled(self, spec.id, params).unwrap_or_else(|| (spec.enabled)(self)) + } + + /// Whether `id` is a layer command whose `"layer"` param names an existing layer, so it needs no + /// active layer (#2457). Matches how `layer_param` resolves the layer when the command runs. + fn names_existing_layer(&self, id: &str, params: &Value) -> bool { + matches!(id, "layer.hideLayers" | "layer.showLayers" | "layer.renameLayer") + && params.get("layer").and_then(Value::as_u64).is_some_and(|l| self.active().is_some_and(|st| st.doc.layer(LayerId(l)).is_some())) + } + + /// The precondition of a command whose params document `"layer":id` (it acts on that layer), + /// when `params` name an existing layer of the active document: checked on that layer rather + /// than on the active one, which stays active (#466). A script, action or agent can then + /// Replace Contents, Rasterize or Merge Down a layer without selecting it first. `None` for + /// other commands, or without such a layer. + pub(crate) fn explicit_layer_enabled(&mut self, spec: &commands::CommandSpec, params: &Value) -> Option> { + if !spec.params.contains("\"layer\":id") { + return None; + } + let target = LayerId(params.get("layer")?.as_u64()?); + let d = self.active_mut()?; + d.doc.layer(target)?; + let active = d.active_layer.replace(target); + let r = self.precondition(spec, params); + if let Some(d) = self.active_mut() { + d.active_layer = active; + } + Some(r) + } + + /// Apply an undoable edit to the active document. + pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Option) -> Result) -> Result { + // Every mutation path (linked-file refresh, transform, place) re-renders smart objects + // through this entry; the requesting session's authority must reach those renders. + let _authorization = crate::jobs::render_authorization_scope(self.authorize); + let _document = crate::doc_path::scope(self.active().and_then(|d| d.path.as_deref()).map(std::path::Path::new)); + let restrict = self.color_restrict; + let filter_mask_layer = self.filter_mask_layer; + let sampler_map = self.sampler_map.take(); + let symmetry_map = self.symmetry_map.take(); + let st = self.active_mut().ok_or(EngineError::NoDocument)?; + let before = st.doc.clone(); + // Selecting layers is not a step, so the state this edit leaves behind targets what was + // selected just before it (#1356): undoing a stroke keeps the painted layer active. + let prior = st.layer_target(); + let mut doc = (*before).clone(); + let mut active = st.active_layer; + let r = f(&mut doc, &mut active)?; + if let (Some(k), Some(id)) = (restrict, active) { + channel_cmds::restrict_to_color(&before, &mut doc, id, k); + } + if let Some(id) = filter_mask_layer { + smart_cmds::refresh_after_filter_mask_edit(&mut doc, id)?; + } + st.doc = Arc::new(doc); + st.active_layer = active; + fix_selection(st); + channel_cmds::fix_view(st); + // A canvas-size change (crop, Canvas Size, Image Size, rotation) moves the Color Sampler + // points with their pixels and drops the ones that land outside the new canvas. View + // state: not a history step. A mapped edit (the four above) gives the exact map; any other + // size change falls back to dropping whatever is now outside. + let mut samplers_removed = 0; + if let Some(a) = sampler_map { + let bounds = st.doc.bounds(); + let n = st.color_samplers.len(); + st.color_samplers.retain_mut(|p| { + let q = a.apply(photocraft_geom::Point::new(p[0], p[1])); + *p = [q.x, q.y]; + bounds.contains(q.x.floor() as i32, q.y.floor() as i32) + }); + samplers_removed = n - st.color_samplers.len(); + } else if st.doc.size != before.size { + let bounds = st.doc.bounds(); + let n = st.color_samplers.len(); + st.color_samplers.retain(|p| bounds.contains(p[0].floor() as i32, p[1].floor() as i32)); + samplers_removed = n - st.color_samplers.len(); + } + // The painting symmetry stays on its pixels too (Photoshop keeps it as a path). + if let Some(a) = symmetry_map { + st.symmetry = st.symmetry.take().and_then(|sym| sym.transform(&a)); + } + // The pixels the edit can have changed, as its undo would report them: nothing for a + // selection, guides or a layer's name (a new lasso selection used to recomposite a large + // document, seconds on the CPU path, #1773), a new or deleted layer's bounds (a + // duplicate or a paste), and everything when that can't be bounded. A command may still + // report its own, tighter damage after this. + let damage = layer_multi_cmds::step_damage(&before, &st.doc); + let keep_clean = st.keeps_clean(&before); + let key = self.coalesce_request.clone(); + let st = self.active_mut().ok_or(EngineError::NoDocument)?; + let layers = st.layer_target(); + if key.is_none() || st.coalesce != key || !st.history.can_undo() { + st.history.set_current_layers(prior); + st.history.record(label, before, layers); + st.trim_history(); + } else { + st.history.set_current_layers(layers); + } + st.coalesce = key; + st.bump_revision(keep_clean); + st.last_damage = damage; + self.samplers_removed += samplers_removed; + if damage.is_none_or(|d| !d.is_empty()) { + // Free the mask early; a stale entry would only miss (it is keyed by pixels). + self.subject_cache = Default::default(); + self.object_finder = Default::default(); + } + Ok(r) + } +} diff --git a/crates/engine/src/session/history.rs b/crates/engine/src/session/history.rs new file mode 100644 index 0000000000..0d619f47e9 --- /dev/null +++ b/crates/engine/src/session/history.rs @@ -0,0 +1,104 @@ +use super::documents::fix_active; +use super::*; + +impl Session { + pub fn undo(&mut self) -> bool { + // A background job is computing from the current state: it must not move under it. + if self.active_job().is_some() { + return false; + } + let Some(st) = self.active_mut() else { return false }; + st.coalesce = None; + match st.history.undo(st.doc.clone()) { + // Undo Clear History: the list comes back, the document is the same one. Not an + // edit: keep a clean document clean (the revision still moves for the panels). + Some((d, layers)) if Arc::ptr_eq(&d, &st.doc) => { + restore_target(st, layers); + let clean = !st.is_dirty(); + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = Some(photocraft_geom::Rect::EMPTY); + true + } + Some((mut d, layers)) => { + // Save As changes file identity outside history, just like the saved path. + if d.name != st.doc.name { + Arc::make_mut(&mut d).name.clone_from(&st.doc.name); + } + // Pixels this step can have touched, so the canvas recomposites only that + // (it recomposited everything before). + let damage = layer_multi_cmds::step_damage(&d, &st.doc); + let before = std::mem::replace(&mut st.doc, d); + let keep_clean = st.keeps_clean(&before); + restore_target(st, layers); + st.bump_revision(keep_clean); + st.last_damage = damage; + true + } + None => false, + } + } + + pub fn redo(&mut self) -> bool { + if self.active_job().is_some() { + return false; + } + let Some(st) = self.active_mut() else { return false }; + st.coalesce = None; + match st.history.redo(st.doc.clone()) { + Some((mut d, layers)) => { + if d.name != st.doc.name { + Arc::make_mut(&mut d).name.clone_from(&st.doc.name); + } + let damage = layer_multi_cmds::step_damage(&st.doc, &d); + let before = std::mem::replace(&mut st.doc, d); + let keep_clean = st.keeps_clean(&before); + restore_target(st, layers); + st.bump_revision(keep_clean); + st.last_damage = damage; + true + } + None => false, + } + } +} + +/// Undo / redo: target the layers the restored state targeted, as far as they still exist. +pub(crate) fn restore_target(st: &mut DocState, layers: LayerTarget) { + // Deselect Layers is a valid history target, not a missing layer to replace with the top + // layer. An edit after deselection must undo back to no active or selected layers (#3042). + if layers.active.is_none() && layers.selected.is_empty() { + st.active_layer = None; + st.selected_layers.clear(); + st.layer_anchor = None; + channel_cmds::fix_view(st); + return; + } + if layers.active.is_some_and(|id| st.doc.layer(id).is_some()) { + st.active_layer = layers.active; + st.selected_layers = layers.selected; + } + fix_active(st); +} + +/// Keep the layer selection valid after the document or the active layer changed: drop deleted +/// layers, and collapse to the active layer when a command made a non-member active. +pub(crate) fn fix_selection(st: &mut DocState) { + let Some(active) = st.active_layer else { + st.selected_layers.clear(); + return; + }; + if !st.selected_layers.contains(&active) { + st.selected_layers = vec![active]; + } else { + let live: std::collections::HashSet = st.doc.walk().into_iter().map(|(_, _, l)| l.id).collect(); + st.selected_layers.retain(|id| live.contains(id)); + let mut seen = std::collections::HashSet::new(); + st.selected_layers.retain(|id| seen.insert(*id)); + } + if st.layer_anchor.is_some_and(|a| !st.selected_layers.contains(&a)) { + st.layer_anchor = Some(active); + } +} diff --git a/crates/engine/src/session/layers.rs b/crates/engine/src/session/layers.rs new file mode 100644 index 0000000000..b6e5d1c688 --- /dev/null +++ b/crates/engine/src/session/layers.rs @@ -0,0 +1,91 @@ +use super::history::fix_selection; +use super::*; + +impl Session { + /// Replace the active document's active layer without creating a history step. + pub fn select_layer(&mut self, id: LayerId) -> Result<()> { + let st = self.active_mut().ok_or(EngineError::NoDocument)?; + if st.doc.layer(id).is_none() { + return Err(EngineError::NoLayer(id)); + } + st.active_layer = Some(id); + st.selected_layers = vec![id]; + st.layer_anchor = Some(id); + channel_cmds::fix_view(st); + // Selecting a layer is not an edit: keep a clean document clean. + let clean = st.saved_revision == st.revision; + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = Some(photocraft_geom::Rect::EMPTY); + Ok(()) + } + + /// Put back a layer selection (active layer, selected layers, anchor) that a step moved, such + /// as the undo ending an empty Type Mask, which restores the selection from before it. `None` + /// is no layer selected. Selected layers that are gone are dropped; an active layer that is + /// gone is an error and changes nothing. Like [`Self::select_layer`], not an edit. + pub fn restore_layer_selection(&mut self, active: Option, selected: &[LayerId], anchor: Option) -> Result<()> { + let st = self.active_mut().ok_or(EngineError::NoDocument)?; + if let Some(id) = active + && st.doc.layer(id).is_none() + { + return Err(EngineError::NoLayer(id)); + } + st.active_layer = active; + st.selected_layers = selected.to_vec(); + st.layer_anchor = anchor.filter(|_| active.is_some()); + fix_selection(st); + channel_cmds::fix_view(st); + let clean = st.saved_revision == st.revision; + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = Some(photocraft_geom::Rect::EMPTY); + Ok(()) + } + + /// Re-renders the pixels of type layers whose font arrived after they were drawn (the web + /// build fetches served fonts on demand, `photocraft_text::served`). The layers' model is + /// unchanged, so this is no history step and leaves a clean document clean. Unknown documents + /// and layers are skipped. A document a background job is computing from must not move under + /// it: its layers are returned, to try again later. + pub fn refresh_type_layers(&mut self, layers: &[(photocraft_doc::DocId, LayerId)]) -> Vec<(photocraft_doc::DocId, LayerId)> { + let mut busy = Vec::new(); + let mut docs: Vec = Vec::new(); + for (d, _) in layers { + if !docs.contains(d) { + docs.push(*d); + } + } + for doc_id in docs { + let mine = layers.iter().filter(|(d, _)| *d == doc_id); + if self.job_on(doc_id).is_some() { + busy.extend(mine); + continue; + } + let Some(st) = self.docs.iter_mut().find(|st| st.doc.id == doc_id) else { continue }; + let snapshot = st.doc.clone(); + let mut doc = (*snapshot).clone(); + let mut changed = false; + for (_, id) in mine { + if let Some(photocraft_doc::Layer { content: photocraft_doc::LayerContent::Text(t), .. }) = doc.layer_mut(*id) { + type_cmds::refresh(&snapshot, t); + changed = true; + } + } + if changed { + let clean = st.saved_revision == st.revision; + st.doc = Arc::new(doc); + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = None; + } + } + busy + } +} From cfe8a1d9913f17d0785d96d6f59ccbdb839ce63b Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:57:27 +0000 Subject: [PATCH 201/259] refactor(engine): split atn_cmds.rs into atn_cmds/ --- crates/engine/src/atn_cmds.rs | 4234 +-------------------- crates/engine/src/atn_cmds/adjustments.rs | 515 +++ crates/engine/src/atn_cmds/convert.rs | 273 ++ crates/engine/src/atn_cmds/descriptors.rs | 266 ++ crates/engine/src/atn_cmds/events.rs | 609 +++ crates/engine/src/atn_cmds/fields.rs | 113 + crates/engine/src/atn_cmds/files.rs | 140 + crates/engine/src/atn_cmds/steps_doc.rs | 558 +++ crates/engine/src/atn_cmds/steps_image.rs | 453 +++ crates/engine/src/atn_cmds/steps_layer.rs | 576 +++ crates/engine/src/atn_cmds/steps_make.rs | 607 +++ crates/engine/src/atn_cmds/tables.rs | 180 + 12 files changed, 4329 insertions(+), 4195 deletions(-) create mode 100644 crates/engine/src/atn_cmds/adjustments.rs create mode 100644 crates/engine/src/atn_cmds/convert.rs create mode 100644 crates/engine/src/atn_cmds/descriptors.rs create mode 100644 crates/engine/src/atn_cmds/events.rs create mode 100644 crates/engine/src/atn_cmds/fields.rs create mode 100644 crates/engine/src/atn_cmds/files.rs create mode 100644 crates/engine/src/atn_cmds/steps_doc.rs create mode 100644 crates/engine/src/atn_cmds/steps_image.rs create mode 100644 crates/engine/src/atn_cmds/steps_layer.rs create mode 100644 crates/engine/src/atn_cmds/steps_make.rs create mode 100644 crates/engine/src/atn_cmds/tables.rs diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index 244c21479a..32e5405d1a 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -25,6 +25,45 @@ use crate::actions_cmds::Action; use crate::commands::CommandSpec; use crate::{EngineError, Result, Session}; +mod adjustments; +mod convert; +mod descriptors; +mod events; +mod fields; +mod files; +mod steps_doc; +mod steps_image; +mod steps_layer; +mod steps_make; +mod tables; + +#[cfg(test)] +use adjustments::selective_from; +pub use convert::{Imported, Skipped, Unsupported, export, function_key_name, import, parse_function_key}; +#[cfg(test)] +use convert::{MAX_NAME_CHARS, export_item, normalise}; +#[cfg(test)] +use descriptors::{ + PCT, PT, PX, ang, class, class_ref, code, color_desc, color_hex, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, get_ref, layer_ref, long, + name_ref, path_text, path_value, pct, px, target_ref, text, trimmed, +}; +use descriptors::{jbool, jstr}; +#[cfg(test)] +use events::{EVENTS, event_and_descriptor, event_for}; +#[cfg(test)] +use fields::Mapped; +use files::{load, save}; +#[cfg(test)] +use steps_doc::crop_from; +#[cfg(test)] +use steps_image::transform_to; +#[cfg(test)] +use steps_layer::quick_mask_ref; +#[cfg(test)] +use steps_make::make_from; +#[cfg(test)] +use tables::{blend_label, blend_ps, channel_ref}; + /// A step PhotoCraft cannot play yet, kept verbatim (`{"event", "name", "descriptor": base64}`). pub const PHOTOSHOP_STEP: &str = "actions.photoshopStep"; /// Photoshop's Insert Stop: `{"message", "allowContinue"}`. @@ -40,4201 +79,6 @@ fn always(_: &Session) -> std::result::Result<(), String> { Ok(()) } -// ------------------------------------------------------------------ descriptor access - -fn num(v: &D) -> Option { - match v { - D::Integer(i) => Some(f64::from(*i)), - D::LargeInteger(i) => Some(*i as f64), - D::Double(d) | D::UnitFloat { value: d, .. } => Some(*d), - _ => None, - } - .filter(|f| f.is_finite()) -} - -fn trimmed(id: &Id) -> String { - String::from_utf8_lossy(id.as_bytes()).trim_end().to_string() -} - -fn get_num(d: &Descriptor, k: &str) -> Option { - d.get(k).and_then(num) -} - -fn get_bool(d: &Descriptor, k: &str) -> Option { - match d.get(k) { - Some(D::Boolean(b)) => Some(*b), - _ => None, - } -} - -fn get_text(d: &Descriptor, k: &str) -> Option { - match d.get(k) { - Some(D::Text(t)) => Some(t.to_string_lossy()), - _ => None, - } -} - -/// An enumerated value's id, trailing spaces removed (`Ordn.Trgt` → `"Trgt"`). -fn get_enum(d: &Descriptor, k: &str) -> Option { - match d.get(k) { - Some(D::Enumerated { value, .. }) => Some(trimmed(value)), - _ => None, - } -} - -fn get_obj<'a>(d: &'a Descriptor, k: &str) -> Option<&'a Descriptor> { - match d.get(k) { - Some(D::Descriptor(o) | D::GlobalObject(o)) => Some(o), - _ => None, - } -} - -fn get_list<'a>(d: &'a Descriptor, k: &str) -> Option<&'a [D]> { - match d.get(k) { - Some(D::List(l)) => Some(l), - _ => None, - } -} - -fn get_ref<'a>(d: &'a Descriptor, k: &str) -> Option<&'a [ReferenceItem]> { - match d.get(k) { - Some(D::Reference(r)) => Some(r), - _ => None, - } -} - -/// The class of a reference's first item, trimmed (`Lyr`, `Chnl`, `AdjL`…). -fn ref_class(r: &[ReferenceItem]) -> Option { - Some(trimmed(match r.first()? { - ReferenceItem::Property { class, .. } - | ReferenceItem::Class(class) - | ReferenceItem::Enumerated { class, .. } - | ReferenceItem::Offset { class, .. } - | ReferenceItem::Identifier { class, .. } - | ReferenceItem::Index { class, .. } - | ReferenceItem::Name { class, .. } => &class.class_id, - })) -} - -/// How a reference names its target: the ordinal (`Trgt`, `Frnt`…), a name, a property… -enum Target { - Ordinal(String), - Name(String), - Property(String), - Class, - Offset(i32), - Index(u32), - Other, -} - -fn target(r: &[ReferenceItem]) -> Target { - match r.first() { - Some(ReferenceItem::Enumerated { value, .. }) => Target::Ordinal(trimmed(value)), - Some(ReferenceItem::Name { name, .. }) => Target::Name(name.to_string_lossy()), - Some(ReferenceItem::Property { key, .. }) => Target::Property(trimmed(key)), - Some(ReferenceItem::Class(_)) => Target::Class, - Some(ReferenceItem::Offset { offset, .. }) => Target::Offset(*offset), - Some(ReferenceItem::Index { index, .. }) => Target::Index(*index), - _ => Target::Other, - } -} - -/// `{"layer": name}` for a reference that names a layer, `{}` for the target layer, `None` -/// for anything else (an index or id: meaningless in another document). -fn layer_target(r: &[ReferenceItem]) -> Option> { - let mut m = Map::new(); - match target(r) { - Target::Ordinal(o) if o == "Trgt" => {} - Target::Name(n) => { - m.insert("layer".into(), json!(n)); - } - Target::Property(p) if p == "Bckg" => { - m.insert("layer".into(), json!("Background")); - } - _ => return None, - } - Some(m) -} - -// ------------------------------------------------------------------ descriptor building - -/// A Photoshop id: codes shorter than four characters are space-padded (`H `, `Rd `), -/// longer names stay strings. -fn code(s: &str) -> Id { - if s.len() < 4 { Id::new(&format!("{s:<4}")) } else { Id::new(s) } -} - -fn class(c: &str) -> Class { - Class { name: UnicodeString::new_nul(""), class_id: code(c) } -} - -/// The pixel and percent units of a `UntF` value. -const PX: [u8; 4] = *b"#Pxl"; -const PCT: [u8; 4] = *b"#Prc"; -/// Points (1/72 in): what Photoshop calls "relative" units. -const PT: [u8; 4] = *b"#Rlt"; - -fn px(v: f64) -> D { - D::UnitFloat { unit: PX, value: v } -} - -fn pct(v: f64) -> D { - D::UnitFloat { unit: *b"#Prc", value: v } -} - -fn ang(v: f64) -> D { - D::UnitFloat { unit: *b"#Ang", value: v } -} - -fn long(v: f64) -> D { - D::Integer(v.round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32) -} - -fn text(s: &str) -> D { - D::Text(UnicodeString::new_nul(s)) -} - -fn enm(ty: &str, v: &str) -> D { - D::Enumerated { type_id: code(ty), value: code(v) } -} - -fn target_ref(cls: &str) -> D { - D::Reference(vec![ReferenceItem::Enumerated { class: class(cls), type_id: Id::new("Ordn"), value: Id::new("Trgt") }]) -} - -fn name_ref(cls: &str, name: &str) -> D { - D::Reference(vec![ReferenceItem::Name { class: class(cls), name: UnicodeString::new_nul(name) }]) -} - -fn class_ref(cls: &str) -> D { - D::Reference(vec![ReferenceItem::Class(class(cls))]) -} - -/// The `null` reference for a command's `layer` param: by name, else the target layer. -fn layer_ref(p: &Value) -> Option { - match p.get("layer") { - None | Some(Value::Null) => Some(target_ref("Lyr ")), - Some(Value::String(n)) => Some(name_ref("Lyr ", n)), - _ => None, - } -} - -fn desc(cls: &str) -> Descriptor { - Descriptor::new(cls) -} - -// ------------------------------------------------------------------ JSON access - -fn jnum(p: &Value, k: &str) -> Option { - p.get(k).and_then(Value::as_f64).filter(|f| f.is_finite()) -} - -fn jbool(p: &Value, k: &str) -> Option { - p.get(k).and_then(Value::as_bool) -} - -fn jstr<'a>(p: &'a Value, k: &str) -> Option<&'a str> { - p.get(k).and_then(Value::as_str) -} - -// ------------------------------------------------------------------ colours and enums - -/// A Photoshop colour object as `#rrggbb`: `RGBC` (0..255), `HSBC`, `Grsc`. -fn color_hex(c: &Descriptor) -> Option { - let hex = |r: f64, g: f64, b: f64| { - format!("#{:02x}{:02x}{:02x}", r.round().clamp(0.0, 255.0) as u8, g.round().clamp(0.0, 255.0) as u8, b.round().clamp(0.0, 255.0) as u8) - }; - if let (Some(r), Some(g), Some(b)) = (get_num(c, "Rd "), get_num(c, "Grn "), get_num(c, "Bl ")) { - return Some(hex(r, g, b)); - } - if let (Some(h), Some(s), Some(v)) = (get_num(c, "H "), get_num(c, "Strt"), get_num(c, "Brgh")) { - let (s, v) = ((s / 100.0).clamp(0.0, 1.0), (v / 100.0).clamp(0.0, 1.0)); - let h = h.rem_euclid(360.0) / 60.0; - let i = h.floor(); - let f = h - i; - let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f))); - let (r, g, b) = match i as i32 { - 0 => (v, t, p), - 1 => (q, v, p), - 2 => (p, v, t), - 3 => (p, q, v), - 4 => (t, p, v), - _ => (v, p, q), - }; - return Some(hex(r * 255.0, g * 255.0, b * 255.0)); - } - get_num(c, "Gry ").map(|g| { - let v = 255.0 - g * 2.55; - hex(v, v, v) - }) -} - -fn color_desc(hex: &str) -> Option { - let h = hex.strip_prefix('#')?; - if h.len() != 6 || !h.is_ascii() { - return None; - } - let ch = |i: usize| u8::from_str_radix(h.get(i..i + 2)?, 16).ok().map(f64::from); - Some(desc("RGBC").with("Rd ", D::Double(ch(0)?)).with("Grn ", D::Double(ch(2)?)).with("Bl ", D::Double(ch(4)?))) -} - -/// A `Pth ` value's text: Photoshop stores `"txtu"`, a little-endian total length, a -/// little-endian UTF-16 unit count and the units (NUL-terminated). -fn path_text(v: &D) -> Option { - let D::Path(b) = v else { return None }; - if b.get(0..4)? != b"txtu" { - return None; - } - let n = u32::from_le_bytes(b.get(8..12)?.try_into().ok()?) as usize; - let units: Vec = b.get(12..12usize.checked_add(n.checked_mul(2)?)?)?.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); - let text = String::from_utf16_lossy(&units); - let text = text.trim_end_matches('\0'); - (!text.is_empty()).then(|| text.to_string()) -} - -fn path_value(text: &str) -> D { - let units: Vec = text.encode_utf16().chain(std::iter::once(0)).collect(); - let mut b = b"txtu".to_vec(); - b.extend_from_slice(&((12 + units.len() * 2) as u32).to_le_bytes()); - b.extend_from_slice(&(units.len() as u32).to_le_bytes()); - for u in units { - b.extend_from_slice(&u.to_le_bytes()); - } - D::Path(b) -} - -/// Photoshop's `BlnM` enumeration ↔ PhotoCraft's blend mode labels. -const BLEND_MODES: &[(&str, &str)] = &[ - ("Nrml", "Normal"), - ("normal", "Normal"), - ("Dslv", "Dissolve"), - ("dissolve", "Dissolve"), - ("Drkn", "Darken"), - ("darken", "Darken"), - ("Mltp", "Multiply"), - ("multiply", "Multiply"), - ("CBrn", "Color Burn"), - ("colorBurn", "Color Burn"), - ("linearBurn", "Linear Burn"), - ("darkerColor", "Darker Color"), - ("Lghn", "Lighten"), - ("lighten", "Lighten"), - ("Scrn", "Screen"), - ("screen", "Screen"), - ("CDdg", "Color Dodge"), - ("colorDodge", "Color Dodge"), - ("linearDodge", "Linear Dodge (Add)"), - ("lighterColor", "Lighter Color"), - ("Ovrl", "Overlay"), - ("overlay", "Overlay"), - ("SftL", "Soft Light"), - ("softLight", "Soft Light"), - ("HrdL", "Hard Light"), - ("hardLight", "Hard Light"), - ("vividLight", "Vivid Light"), - ("linearLight", "Linear Light"), - ("pinLight", "Pin Light"), - ("hardMix", "Hard Mix"), - ("Dfrn", "Difference"), - ("difference", "Difference"), - ("Xclu", "Exclusion"), - ("exclusion", "Exclusion"), - ("blendSubtraction", "Subtract"), - ("blendDivide", "Divide"), - ("H", "Hue"), - ("hue", "Hue"), - ("Strt", "Saturation"), - ("saturation", "Saturation"), - ("Clr", "Color"), - ("color", "Color"), - ("Lmns", "Luminosity"), - ("luminosity", "Luminosity"), - ("PsTh", "Pass Through"), - ("passThrough", "Pass Through"), -]; - -fn blend_label(ps: &str) -> Option<&'static str> { - BLEND_MODES.iter().find(|(k, _)| *k == ps).map(|(_, v)| *v) -} - -fn blend_ps(label: &str) -> Option<&'static str> { - crate::commands::blend_from_str(label).and_then(|m| BLEND_MODES.iter().find(|(_, v)| crate::commands::blend_from_str(v) == Some(m))).map(|(k, _)| *k) -} - -/// Photoshop ↔ PhotoCraft value tables; Photoshop codes compare without their space padding. -fn lookup<'a>(table: &'a [(&'a str, &'a str)], key: &str) -> Option<&'a str> { - table.iter().find(|(k, _)| k.trim_end() == key.trim_end()).map(|(_, v)| *v) -} - -fn lookup_back<'a>(table: &'a [(&'a str, &'a str)], value: &str) -> Option<&'a str> { - table.iter().find(|(_, v)| *v == value).map(|(k, _)| *k) -} - -/// `Chnl` enumeration ↔ the per-channel keys of the adjustment commands. -const CHANNELS: &[(&str, &str)] = &[ - ("Rd", "red"), - ("Grn", "green"), - ("Bl", "blue"), - ("Gry", "gray"), - ("Cyn", "cyan"), - ("Mgnt", "magenta"), - ("Yllw", "yellow"), - ("Blck", "black"), - ("Lmnc", "lightness"), - ("A", "a"), - ("B", "b"), -]; - -/// The channel an adjustment entry's `Chnl` reference names: `None` = the composite. -fn channel_key(d: &Descriptor) -> Option> { - let r = get_ref(d, "Chnl")?; - Some(match target(r) { - Target::Ordinal(o) if o == "Trgt" || o == "Cmps" => None, - Target::Ordinal(o) => Some(lookup(CHANNELS, &o)?), - _ => return None, - }) -} - -/// A Levels or Curves entry's channel: `Chnl.Cmps` for the composite, as Photoshop records it. -/// Photoshop silently skips a Set whose composite is `Ordn.Trgt` (#8543). -fn channel_ref(key: Option<&str>) -> D { - let value = key.and_then(|k| lookup_back(CHANNELS, k)); - D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code(value.unwrap_or("Cmps")) }]) -} - -// ------------------------------------------------------------------ field tables - -#[derive(Clone, Copy)] -enum Kind { - Px, - Pct, - Ang, - Long, - /// An integer field whose value must survive conversion without rounding or saturation. - ExactLong, - Dbl, - Bool, - /// An enumeration: its type id and the Photoshop ↔ PhotoCraft value pairs. - Enum(&'static str, &'static [(&'static str, &'static str)]), - /// A blend mode (`BlnM`). - Blend, - /// A colour object ↔ `#rrggbb`. - Color, -} - -/// One descriptor key ↔ one command param. -struct F(&'static str, &'static str, Kind); - -/// Import mapped descriptor fields, leaving absent values to command defaults. -/// Return `None` when a present enum, blend mode or colour cannot be represented. -fn fields_from(d: &Descriptor, fields: &[F]) -> Option> { - let mut m = Map::new(); - for F(key, param, kind) in fields { - let v = match kind { - Kind::Px | Kind::Pct | Kind::Ang | Kind::Long | Kind::ExactLong | Kind::Dbl => get_num(d, key).map(Value::from), - Kind::Bool => get_bool(d, key).map(Value::from), - Kind::Enum(_, table) => match get_enum(d, key) { - Some(e) => Some(Value::from(lookup(table, &e)?)), - None => None, - }, - Kind::Blend => match get_enum(d, key) { - Some(e) => Some(Value::from(blend_label(&e)?)), - None => None, - }, - Kind::Color => match get_obj(d, key) { - Some(c) => Some(Value::from(color_hex(c)?)), - None => None, - }, - }; - if let Some(v) = v { - m.insert((*param).into(), v); - } - } - Some(m) -} - -/// Export supplied mapped params, omitting absent values to preserve event defaults. -/// Return `None` for unsupported values; `ExactLong` also rejects rounding or saturation. -fn fields_to(p: &Value, fields: &[F], mut d: Descriptor) -> Option { - for F(key, param, kind) in fields { - let Some(v) = p.get(param) else { continue }; - let out = match kind { - Kind::Px => px(v.as_f64()?), - Kind::Pct => pct(v.as_f64()?), - Kind::Ang => ang(v.as_f64()?), - // A value outside the descriptor's 32-bit integer refuses the step rather than being - // clamped to another value (an Add Noise seed above i32::MAX replayed as i32::MAX, #7287). - Kind::Long => { - let n = v.as_f64()?.round(); - if !(f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&n) { - return None; - } - long(n) - } - Kind::ExactLong => { - let number = v.as_f64()?; - let integer = number as i32; - if f64::from(integer) != number { - return None; - } - D::Integer(integer) - } - Kind::Dbl => D::Double(v.as_f64()?), - Kind::Bool => D::Boolean(v.as_bool()?), - Kind::Enum(ty, table) => enm(ty, lookup_back(table, v.as_str()?)?), - Kind::Blend => enm("BlnM", blend_ps(v.as_str()?)?), - Kind::Color => D::Descriptor(color_desc(v.as_str()?)?), - }; - d = d.with(key, out); - } - Some(d) -} - -// ------------------------------------------------------------------ adjustments - -/// The `Adjs` entries of a per-channel adjustment (Levels, Curves): `(channel key, entry)`. -fn per_channel(d: &Descriptor) -> Option, &Descriptor)>> { - get_list(d, "Adjs")? - .iter() - .map(|v| match v { - D::Descriptor(e) => Some((channel_key(e)?, e)), - _ => None, - }) - .collect() -} - -fn levels_from(d: &Descriptor) -> Option { - if get_bool(d, "Auto") == Some(true) { - return None; - } - let mut out = Map::new(); - for (chan, e) in per_channel(d)? { - let mut m = Map::new(); - if let Some(i) = get_list(e, "Inpt") { - if let Some(v) = i.first().and_then(num) { - m.insert("inBlack".into(), v.into()); - } - if let Some(v) = i.get(1).and_then(num) { - m.insert("inWhite".into(), v.into()); - } - } - if let Some(o) = get_list(e, "Otpt") { - if let Some(v) = o.first().and_then(num) { - m.insert("outBlack".into(), v.into()); - } - if let Some(v) = o.get(1).and_then(num) { - m.insert("outWhite".into(), v.into()); - } - } - if let Some(g) = get_num(e, "Gmm ") { - m.insert("gamma".into(), g.into()); - } - match chan { - None => out.extend(m), - Some(k) => { - out.insert(k.into(), Value::Object(m)); - } - } - } - Some(Value::Object(out)) -} - -fn levels_entry(chan: Option<&str>, p: &Value) -> Descriptor { - let mut e = desc("LvlA").with("Chnl", channel_ref(chan)); - if jnum(p, "inBlack").is_some() || jnum(p, "inWhite").is_some() { - e = e.with("Inpt", D::List(vec![long(jnum(p, "inBlack").unwrap_or(0.0)), long(jnum(p, "inWhite").unwrap_or(255.0))])); - } - if let Some(g) = jnum(p, "gamma") { - e = e.with("Gmm ", D::Double(g)); - } - if jnum(p, "outBlack").is_some() || jnum(p, "outWhite").is_some() { - e = e.with("Otpt", D::List(vec![long(jnum(p, "outBlack").unwrap_or(0.0)), long(jnum(p, "outWhite").unwrap_or(255.0))])); - } - e -} - -fn levels_to(p: &Value) -> Option { - let mut entries = vec![D::Descriptor(levels_entry(None, p))]; - for (_, k) in CHANNELS { - if let Some(c) = p.get(*k).filter(|v| v.is_object()) { - entries.push(D::Descriptor(levels_entry(Some(k), c))); - } - } - Some(desc("Lvls").with("presetKind", enm("presetKindType", "presetKindCustom")).with("Adjs", D::List(entries))) -} - -fn curve_points(e: &Descriptor) -> Option { - let pts: Option> = get_list(e, "Crv ")? - .iter() - .map(|v| match v { - D::Descriptor(pt) => Some(json!([get_num(pt, "Hrzn")?, get_num(pt, "Vrtc")?])), - _ => None, - }) - .collect(); - pts.map(Value::Array) -} - -fn curves_from(d: &Descriptor) -> Option { - let mut out = Map::new(); - for (chan, e) in per_channel(d)? { - let pts = curve_points(e)?; - out.insert(chan.unwrap_or("points").into(), pts); - } - Some(Value::Object(out)) -} - -fn curve_entry(chan: Option<&str>, pts: &Value) -> Option { - let list: Option> = pts - .as_array()? - .iter() - .map(|pt| { - let a = pt.as_array()?; - Some(D::Descriptor(desc("Pnt ").with("Hrzn", D::Double(a.first()?.as_f64()?)).with("Vrtc", D::Double(a.get(1)?.as_f64()?)))) - }) - .collect(); - Some(desc("CrvA").with("Chnl", channel_ref(chan)).with("Crv ", D::List(list?))) -} - -fn curves_to(p: &Value) -> Option { - let mut entries = Vec::new(); - if let Some(pts) = p.get("points") { - entries.push(D::Descriptor(curve_entry(None, pts)?)); - } - for (_, k) in CHANNELS { - if let Some(pts) = p.get(*k) { - entries.push(D::Descriptor(curve_entry(Some(k), pts)?)); - } - } - Some(desc("Crvs").with("presetKind", enm("presetKindType", "presetKindCustom")).with("Adjs", D::List(entries))) -} - -/// The hue key of a Hue/Saturation adjustment (`Hst2`): Photoshop's `H ` (#8302). -const HUE_KEY: &str = "H "; - -const HUE_RANGES: [&str; 6] = ["reds", "yellows", "greens", "cyans", "blues", "magentas"]; - -fn hue_sat_from(d: &Descriptor) -> Option { - let mut out = Map::new(); - if let Some(c) = get_bool(d, "Clrz") { - out.insert("colorize".into(), c.into()); - } - for e in get_list(d, "Adjs").unwrap_or(&[]) { - let D::Descriptor(e) = e else { return None }; - let mut m = Map::new(); - // Photoshop's hue key is `H ` (stringID "hue", #8302); PhotoCraft wrote `Hue ` before, - // so its own older files still read. - let hue = get_num(e, HUE_KEY).or_else(|| get_num(e, "Hue ")); - for (param, v) in [("hue", hue), ("saturation", get_num(e, "Strt")), ("lightness", get_num(e, "Lght"))] { - if let Some(v) = v { - m.insert(param.into(), v.into()); - } - } - match get_num(e, "LclR") { - None => out.extend(m), - Some(r) => { - let name = *HUE_RANGES.get((r as usize).checked_sub(1)?)?; - if let (Some(a), Some(b), Some(c), Some(dd)) = (get_num(e, "BgnR"), get_num(e, "BgnS"), get_num(e, "EndS"), get_num(e, "EndR")) { - m.insert("range".into(), json!([a, b, c, dd])); - } - out.insert(name.into(), Value::Object(m)); - } - } - } - Some(Value::Object(out)) -} - -fn hue_entry(p: &Value, range: Option<(usize, &Value)>) -> Option { - let mut e = desc("Hst2"); - if let Some((i, r)) = range { - e = e.with("LclR", long(i as f64 + 1.0)); - if let Some(a) = r.get("range").and_then(Value::as_array) - && a.len() == 4 - { - for (k, v) in ["BgnR", "BgnS", "EndS", "EndR"].iter().zip(a) { - e = e.with(k, long(v.as_f64()?)); - } - } - } - for (key, param) in [(HUE_KEY, "hue"), ("Strt", "saturation"), ("Lght", "lightness")] { - e = e.with(key, long(jnum(p, param).unwrap_or(0.0))); - } - Some(e) -} - -// Exporters leave out a param the step doesn't set only where Photoshop plays the missing key -// as PhotoCraft's default (checked against Photoshop: Fill opacity and mode, Crop delete, -// Selective Color method, Channel Mixer monochrome, Paint Bucket contiguous; Gradient Map -// reverse and dither, which Photoshop itself leaves out when off). Elsewhere they -// write PhotoCraft's default, as Photoshop plays a missing key differently (Color Balance -// preserve luminosity off, Canvas Size anchored top left, Apply Image Normal) or refuses the -// step (Paint Bucket without a tolerance). -fn hue_sat_to(p: &Value) -> Option { - let d = desc("HStr").with("presetKind", enm("presetKindType", "presetKindCustom")).with("Clrz", D::Boolean(jbool(p, "colorize").unwrap_or(false))); - let mut entries = vec![D::Descriptor(hue_entry(p, None)?)]; - for (i, name) in HUE_RANGES.iter().enumerate() { - if let Some(r) = p.get(*name).filter(|v| v.is_object()) { - entries.push(D::Descriptor(hue_entry(r, Some((i, r)))?)); - } - } - Some(d.with("Adjs", D::List(entries))) -} - -fn triple(d: &Descriptor, k: &str) -> Option { - let l = get_list(d, k)?; - let v: Option> = l.iter().map(num).collect(); - Some(json!(v?)) -} - -fn triple_to(p: &Value, k: &str) -> Option { - Some(D::List(p.get(k)?.as_array()?.iter().map(|v| v.as_f64().map(long)).collect::>>()?)) -} - -fn color_balance_from(d: &Descriptor) -> Option { - let mut out = Map::new(); - for (key, param) in [("ShdL", "shadows"), ("MdtL", "midtones"), ("HghL", "highlights")] { - if let Some(v) = triple(d, key) { - out.insert(param.into(), v); - } - } - if let Some(b) = get_bool(d, "PrsL") { - out.insert("preserveLuminosity".into(), b.into()); - } - Some(Value::Object(out)) -} - -fn color_balance_to(p: &Value) -> Option { - let mut d = desc("ClrB"); - for (key, param) in [("ShdL", "shadows"), ("MdtL", "midtones"), ("HghL", "highlights")] { - d = d.with(key, triple_to(p, param).unwrap_or_else(|| D::List(vec![long(0.0), long(0.0), long(0.0)]))); - } - Some(d.with("PrsL", D::Boolean(jbool(p, "preserveLuminosity").unwrap_or(true)))) -} - -const BW: &[F] = &[ - F("Rd ", "reds", Kind::Long), - F("Yllw", "yellows", Kind::Long), - F("Grn ", "greens", Kind::Long), - F("Cyn ", "cyans", Kind::Long), - F("Bl ", "blues", Kind::Long), - F("Mgnt", "magentas", Kind::Long), - F("useTint", "tint", Kind::Bool), - F("tintColor", "tintColor", Kind::Color), -]; - -fn mixer_channel(e: &Descriptor) -> Option { - Some(json!([get_num(e, "Rd ").unwrap_or(0.0), get_num(e, "Grn ").unwrap_or(0.0), get_num(e, "Bl ").unwrap_or(0.0), get_num(e, "Cnst").unwrap_or(0.0)])) -} - -fn channel_mixer_from(d: &Descriptor) -> Option { - let mut out = Map::new(); - for (key, param) in [("Rd ", "red"), ("Grn ", "green"), ("Bl ", "blue"), ("Gry ", "gray")] { - if let Some(e) = get_obj(d, key) { - out.insert(param.into(), mixer_channel(e)?); - } - } - if let Some(m) = get_bool(d, "Mnch") { - out.insert("monochrome".into(), m.into()); - } - Some(Value::Object(out)) -} - -fn channel_mixer_to(p: &Value) -> Option { - let mut d = desc("ChnM").with("presetKind", enm("presetKindType", "presetKindCustom")); - for (key, param) in [("Rd ", "red"), ("Grn ", "green"), ("Bl ", "blue"), ("Gry ", "gray")] { - if let Some(a) = p.get(param).and_then(Value::as_array) { - let v = |i: usize| a.get(i).and_then(Value::as_f64).unwrap_or(0.0); - d = d.with(key, D::Descriptor(desc("ChMx").with("Rd ", pct(v(0))).with("Grn ", pct(v(1))).with("Bl ", pct(v(2))).with("Cnst", pct(v(3))))); - } - } - if let Some(m) = jbool(p, "monochrome") { - d = d.with("Mnch", D::Boolean(m)); - } - Some(d) -} - -/// Photoshop's `Clrs` colour-range enumeration. Yellows is `Ylws` (`Yllw` is the yellow ink -/// key); earlier PhotoCraft builds wrote `Yllw`, which import still reads (#6745). -const SELECTIVE_RANGES: &[(&str, &str)] = &[ - ("Rds", "reds"), - ("Ylws", "yellows"), - ("Grns", "greens"), - ("Cyns", "cyans"), - ("Bls", "blues"), - ("Mgnt", "magentas"), - ("Whts", "whites"), - ("Ntrl", "neutrals"), - ("Blks", "blacks"), -]; - -fn selective_from(d: &Descriptor) -> Option { - let mut out = Map::new(); - if let Some(m) = get_enum(d, "Mthd") { - out.insert("method".into(), (if m == "Absl" { "absolute" } else { "relative" }).into()); - } - for e in get_list(d, "ClrC").unwrap_or(&[]) { - let D::Descriptor(e) = e else { return None }; - let range = get_enum(e, "Clrs")?; - let name = lookup(SELECTIVE_RANGES, if range == "Yllw" { "Ylws" } else { &range })?; - let v = |k: &str| get_num(e, k).unwrap_or(0.0); - out.insert(name.into(), json!([v("Cyn "), v("Mgnt"), v("Yllw"), v("Blck")])); - } - Some(Value::Object(out)) -} - -fn selective_to(p: &Value) -> Option { - // Match command execution: scalar components override only the selected range, `relative` - // takes precedence over `method`, and invalid values must not become a different edit. - let photocraft_doc::Adjustment::SelectiveColor { relative, adjustments } = crate::adjust_cmds::selective_from_params(p, None).ok()? else { - return None; - }; - let mut list = Vec::new(); - for (name, row) in crate::adjust_cmds::RANGES.into_iter().zip(adjustments) { - if p.get(name).is_some_and(|v| !v.is_null()) || jstr(p, "colors") == Some(name) { - let ps = lookup_back(SELECTIVE_RANGES, name)?; - let [cyan, magenta, yellow, black] = row.map(f64::from); - list.push(D::Descriptor( - desc("ClrC") - .with("Clrs", enm("Clrs", ps)) - .with("Cyn ", pct(cyan)) - .with("Mgnt", pct(magenta)) - .with("Yllw", pct(yellow)) - .with("Blck", pct(black)), - )); - } - } - Some( - desc("SlcC") - .with("presetKind", enm("presetKindType", "presetKindCustom")) - .with("Mthd", enm("CrcM", if relative { "Rltv" } else { "Absl" })) - .with("ClrC", D::List(list)), - ) -} - -/// Gradient Map: the gradient's colour stops at 0..4096 → `stops: [[0..1, "#rrggbb"], …]`. -fn gradient_map_from(d: &Descriptor) -> Option { - let grad = get_obj(d, "Grad")?; - let stops: Option> = get_list(grad, "Clrs")? - .iter() - .map(|v| match v { - D::Descriptor(stop) => Some(json!([(get_num(stop, "Lctn")? / 4096.0).clamp(0.0, 1.0), color_hex(get_obj(stop, "Clr ")?)?])), - _ => None, - }) - .collect(); - let mut out = json!({"stops": stops?}); - if let Some(r) = get_bool(d, "Rvrs") { - out["reverse"] = json!(r); - } - if let Some(dd) = get_bool(d, "Dthr") { - out["dither"] = json!(dd); - } - Some(out) -} - -fn gradient_map_to(p: &Value) -> Option { - let stops: Option> = p - .get("stops")? - .as_array()? - .iter() - .map(|st| { - let a = st.as_array()?; - Some(D::Descriptor( - desc("Clrt") - .with("Clr ", D::Descriptor(color_desc(a.get(1)?.as_str()?)?)) - .with("Type", enm("Clry", "UsrS")) - .with("Lctn", long((a.first()?.as_f64()? * 4096.0).round())) - .with("Mdpn", long(50.0)), - )) - }) - .collect(); - let transparency = D::List(vec![ - D::Descriptor(desc("TrnS").with("Opct", pct(100.0)).with("Lctn", long(0.0)).with("Mdpn", long(50.0))), - D::Descriptor(desc("TrnS").with("Opct", pct(100.0)).with("Lctn", long(4096.0)).with("Mdpn", long(50.0))), - ]); - let grad = desc("Grdn") - .with("Nm ", text("Custom")) - .with("GrdF", enm("GrdF", "CstS")) - .with("Intr", D::Double(4096.0)) - .with("Clrs", D::List(stops?)) - .with("Trns", transparency); - let mut d = desc("GdMp").with("Grad", D::Descriptor(grad)); - if let Some(r) = jbool(p, "reverse") { - d = d.with("Rvrs", D::Boolean(r)); - } - if let Some(dd) = jbool(p, "dither") { - d = d.with("Dthr", D::Boolean(dd)); - } - Some(d) -} - -/// An adjustment: its Photoshop class (usually also the direct event's code; Black & White and -/// Photo Filter run by name), the command suffix (`image.adjustments.`, `layer.newAdjustmentLayer.`), and -/// the converters between the adjustment descriptor and the command params. -struct Adjustment { - class: &'static str, - suffix: &'static str, - from: fn(&Descriptor) -> Option, - to: fn(&Value) -> Option, -} - -macro_rules! adj_fields { - ($class:literal, $suffix:literal, $fields:expr) => { - Adjustment { class: $class, suffix: $suffix, from: |d| fields_from(d, $fields).map(Value::Object), to: |p| fields_to(p, $fields, desc($class)) } - }; -} - -const ADJUSTMENTS: &[Adjustment] = &[ - Adjustment { class: "Lvls", suffix: "levels", from: levels_from, to: levels_to }, - Adjustment { class: "Crvs", suffix: "curves", from: curves_from, to: curves_to }, - Adjustment { class: "HStr", suffix: "hueSaturation", from: hue_sat_from, to: hue_sat_to }, - adj_fields!("BrgC", "brightnessContrast", &[F("Brgh", "brightness", Kind::Long), F("Cntr", "contrast", Kind::Long), F("useLegacy", "legacy", Kind::Bool)]), - adj_fields!("Thrs", "threshold", &[F("Lvl ", "level", Kind::Long)]), - adj_fields!("Pstr", "posterize", &[F("Lvls", "levels", Kind::Long)]), - adj_fields!("Invr", "invert", &[]), - Adjustment { class: "ClrB", suffix: "colorBalance", from: color_balance_from, to: color_balance_to }, - adj_fields!("Vbrn", "vibrance", &[F("vibrance", "vibrance", Kind::Long), F("Strt", "saturation", Kind::Long)]), - adj_fields!("Exps", "exposure", &[F("Exps", "exposure", Kind::Dbl), F("Ofst", "offset", Kind::Dbl), F("gammaCorrection", "gamma", Kind::Dbl)]), - Adjustment { class: "PhtF", suffix: "photoFilter", from: |d| fields_from(d, PHOTO_FILTER_FIELDS).map(Value::Object), to: photo_filter_to }, - adj_fields!("BanW", "blackWhite", BW), - Adjustment { class: "ChnM", suffix: "channelMixer", from: channel_mixer_from, to: channel_mixer_to }, - Adjustment { class: "SlcC", suffix: "selectiveColor", from: selective_from, to: selective_to }, - Adjustment { class: "GdMp", suffix: "gradientMap", from: gradient_map_from, to: gradient_map_to }, -]; - -/// Adjustment classes PhotoCraft once exported, with the class Photoshop uses. Measured in -/// Photoshop (#8481): a Make whose Black & White type is `BlnW` fails ("the command Make is not -/// currently available"), `BanW` runs. Import keeps accepting them so actions saved before still -/// load; export never writes them. -const LEGACY_CLASSES: &[(&str, &str)] = &[("BlnW", "BanW")]; - -/// The adjustment with Photoshop class `c`, or the one an old PhotoCraft class stands for. -fn adjustment_by_class(c: &str) -> Option<&'static Adjustment> { - let c = c.trim_end(); - let c = LEGACY_CLASSES.iter().find(|(old, _)| *old == c).map_or(c, |(_, class)| class); - ADJUSTMENTS.iter().find(|a| a.class.trim_end() == c) -} - -const PHOTO_FILTER_FIELDS: &[F] = &[F("Clr ", "color", Kind::Color), F("Dnst", "density", Kind::Long), F("PrsL", "preserveLuminosity", Kind::Bool)]; - -/// A `PhtF` step whose params carry a `filter` preset without an explicit `color`: the descriptor -/// form is colour-only (Photoshop stores no preset key — the `phfl` notes in `crates/io` conclude -/// the same from its CS2 oracles), so the resolved colour must be written, or re-imported playback -/// falls back to the default warming filter. With both present, the explicit colour wins, as when -/// running the command. An unknown preset id keeps the old export (no colour) instead of failing. -fn photo_filter_to(p: &Value) -> Option { - let mut p = p.clone(); - if p.get("color").is_none() { - let hex = p.get("filter").and_then(Value::as_str).and_then(preset_color); - if let (Some(hex), Some(o)) = (hex, p.as_object_mut()) { - o.insert("color".into(), hex.into()); - } - } - fields_to(&p, PHOTO_FILTER_FIELDS, desc("PhtF")) -} - -/// The preset id's resolved `#rrggbb`, or none (no id given, or an unknown one). -fn preset_color(id: &str) -> Option { - crate::adjust_params::PHOTO_FILTERS.iter().find(|f| f.0 == id).map(|(_, _, rgb)| format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])) -} - -fn adjustment_by_suffix(suffix: &str) -> Option<&'static Adjustment> { - ADJUSTMENTS.iter().find(|a| a.suffix == suffix) -} - -// ------------------------------------------------------------------ the event table - -/// What one Photoshop step maps to. -enum Mapped { - /// One or more PhotoCraft steps (a `make` with a name becomes new layer + rename). - Steps(Vec<(String, Value)>), - /// No PhotoCraft equivalent; `harmless` steps (tool selections…) are imported switched off. - Unsupported { harmless: bool }, -} - -fn step(id: &str, params: Value) -> Mapped { - Mapped::Steps(vec![(id.to_string(), params)]) -} - -fn steps(v: Vec<(&str, Value)>) -> Mapped { - Mapped::Steps(v.into_iter().map(|(id, p)| (id.to_string(), p)).collect()) -} - -fn none(id: &str) -> Mapped { - step(id, json!({})) -} - -/// An event: code (empty when Photoshop only has a string name), string name, the panel -/// label, the command ids it exports (the first is the one simple events import to), and the -/// two converters. -struct Event { - code: &'static str, - name: &'static str, - label: &'static str, - ids: &'static [&'static str], - from: fn(&Descriptor) -> Mapped, - to: fn(&str, &Value) -> Option, -} - -macro_rules! ev { - ($code:literal, $name:literal, $label:literal, $id:literal, $fields:expr) => { - ev!($code, $name, $label, $id, $fields, unless | _ | false) - }; - // `unless`: params the descriptor can't carry, so such a step isn't exported (it would replay - // differently) rather than losing them. - ($code:literal, $name:literal, $label:literal, $id:literal, $fields:expr, unless $skip:expr) => { - Event { - code: $code, - name: $name, - label: $label, - ids: &[$id], - from: |d| match fields_from(d, $fields) { - Some(m) => step($id, Value::Object(m)), - None => Mapped::Unsupported { harmless: false }, - }, - to: |_, p| if pixel_target(p) && !($skip)(p) && holds_its_settings($id, p) { fields_to(p, $fields, desc("null")) } else { None }, - } - }; -} - -/// Minimum / Maximum with Preserve: Roundness. The descriptor here maps the radius only, and -/// Photoshop's encoding of the shape isn't verified, so such a step is not exported: it would -/// replay as the default Squareness (#7233). -fn preserves_roundness(p: &Value) -> bool { - p.get("preserve").and_then(Value::as_str) == Some("roundness") -} - -/// Whether any of the boolean `flags` is on in `p` (present, not null and not `false`). -fn flag_set(p: &Value, flags: &[&str]) -> bool { - flags.iter().any(|f| p.get(*f).is_some_and(|v| !v.is_null() && *v != Value::Bool(false))) -} - -/// Select > Modify with "Apply effect at canvas bounds": the descriptor has no field for it, so such a -/// step is not exported (it would replay without the option). -fn applies_at_canvas_bounds(p: &Value) -> bool { - flag_set(p, &["applyAtCanvasBounds"]) -} - -/// Settings a mapped event has no field for, by command: `(param, the value the event plays as)`. -/// Photoshop's event has nowhere to put these, so a step that sets one cannot be written: it -/// would import as a different edit, silently. Such a step is refused, the way [`pixel_target`] -/// refuses a filter aimed at a mask -- and no key Photoshop does not define is invented for it, -/// which the clean-room rule forbids and which would make the file wrong in another reader. -/// -/// A step that leaves the setting at the value the event plays as exports as before. -/// How a setting the event cannot carry behaves once the step is replayed without it. Which of -/// the two a setting takes follows the command's own reading of it, not the parameter spec. -enum Lost { - /// Replay uses this value, so only a step already at it survives. Numbers and strings are - /// both compared as written, since the commands below read these settings as written. - ReplaysAs(&'static str), - /// The command reads only this one spelling as anything other than what replay does, so every - /// other value survives -- a differently cased one included, because it too plays as replay's. - DiffersAt(&'static str), -} - -const UNHOLDABLE: &[(&str, &[(&str, Lost)])] = &[ - // Crst carries ClSz only; replay seeds the pattern from 0 (#7668). - ("filter.pixelate.crystallize", &[("seed", Lost::ReplaysAs("0"))]), - // RdlB carries Amnt, BlrM and BlrQ; replay spins or zooms about the middle of the layer. - ("filter.blur.radialBlur", &[("centerX", Lost::ReplaysAs("0.5")), ("centerY", Lost::ReplaysAs("0.5"))]), - // Mnm /Mxm carry Rds only; replay keeps squareness, and so does the command for anything but - // the exact string "roundness" -- see `preserve` in filters.rs. - ("filter.other.minimum", &[("preserve", Lost::DiffersAt("roundness"))]), - ("filter.other.maximum", &[("preserve", Lost::DiffersAt("roundness"))]), -]; - -/// Whether every setting of `p` that its event cannot hold would play the same without it -/// (see [`UNHOLDABLE`]). -fn holds_its_settings(id: &str, p: &Value) -> bool { - let Some((_, settings)) = UNHOLDABLE.iter().find(|(cmd, _)| *cmd == id) else { return true }; - settings.iter().all(|(param, lost)| match (p.get(param), lost) { - (None | Some(Value::Null), _) => true, - (Some(v), Lost::ReplaysAs(played)) => v.as_str() == Some(played) || v.as_f64().is_some_and(|n| played.parse::().is_ok_and(|d| n == d)), - (Some(v), Lost::DiffersAt(spelling)) => v.as_str() != Some(spelling), - }) -} - -/// Whether `p` edits the layer's pixels: no `"target"` or `"target":"pixels"`. Photoshop's -/// descriptor for a plain event has no field for a mask, Quick Mask or channel target, so such -/// a step can't be exported faithfully. -fn pixel_target(p: &Value) -> bool { - p.get("target").is_none_or(|t| t.as_str() == Some("pixels")) -} - -const INTERPOLATION: &[(&str, &str)] = &[ - ("Bcbc", "bicubic"), - ("Blnr", "bilinear"), - ("Nrst", "nearest"), - ("bicubicSharper", "bicubicSharper"), - ("bicubicSmoother", "bicubicSmoother"), - ("bicubicAutomatic", "bicubicAutomatic"), - ("automaticInterpolation", "automatic"), - ("preserveDetailsUpscale", "preserveDetails"), - ("deepUpscale", "preserveDetails"), -]; -const NOISE: &[(&str, &str)] = &[("Unfr", "uniform"), ("Gsn ", "gaussian")]; -const OFFSET_FILL: &[(&str, &str)] = &[("Wrp ", "wrap"), ("Rpt ", "repeat"), ("Bckg", "transparent")]; -const TRIM: &[(&str, &str)] = &[("Trns", "transparent"), ("topLeftPixelColor", "topLeft"), ("bottomRightPixelColor", "bottomRight")]; -const EXTENSION: &[(&str, &str)] = &[("Bckg", "background"), ("Frgd", "foreground"), ("Wht ", "white"), ("Blck", "black"), ("Trns", "transparent")]; -const FILL_CONTENTS: &[(&str, &str)] = &[ - ("FrgC", "foreground"), - ("BckC", "background"), - ("Wht ", "white"), - ("Blck", "black"), - ("Gry ", "gray"), - ("Clr ", "color"), - ("HstS", "history"), - ("contentAware", "contentAware"), -]; -const STROKE_LOCATION: &[(&str, &str)] = &[("Insd", "inside"), ("Cntr", "center"), ("OtsF", "outside")]; -const INTENT: &[(&str, &str)] = &[("Img ", "perceptual"), ("Clrm", "relative"), ("Grp ", "saturation"), ("AbsC", "absolute")]; -const PROFILES: &[(&str, &str)] = - &[("sRGB IEC61966-2.1", "srgb"), ("Display P3", "display-p3"), ("Adobe RGB (1998)", "adobe-rgb-compat"), ("ProPhoto RGB", "prophoto-compat")]; -/// Smart Blur quality. Photoshop's codes come first, so they are what an export writes (measured in -/// Photoshop: `Hgh `/`Mdm `/`Low ` play back as its fallback, low quality). The old codes after -/// them still read, for actions PhotoCraft wrote before. -const SMART_BLUR_QUALITY: &[(&str, &str)] = &[("SBQL", "low"), ("SBQM", "medium"), ("SBQH", "high"), ("Hgh ", "high"), ("Mdm ", "medium"), ("Low ", "low")]; -const SMART_BLUR_MODE: &[(&str, &str)] = &[("SBMN", "normal"), ("SBME", "edgeOnly"), ("SBMO", "overlayEdge")]; -const RADIAL_METHOD: &[(&str, &str)] = &[("Spn ", "spin"), ("Zm ", "zoom")]; -const RADIAL_QUALITY: &[(&str, &str)] = &[("Drft", "draft"), ("Gd ", "good"), ("Bst ", "best")]; -const LABEL_COLORS: &[(&str, &str)] = - &[("None", "none"), ("Rd", "red"), ("Orng", "orange"), ("Ylw", "yellow"), ("Grn", "green"), ("Bl", "blue"), ("Vlt", "violet"), ("Gry", "gray")]; -const ALIGN: &[(&str, &str)] = - &[("AdLf", "leftEdges"), ("AdCH", "horizontalCenters"), ("AdRg", "rightEdges"), ("AdTp", "topEdges"), ("AdCV", "verticalCenters"), ("AdBt", "bottomEdges")]; -const PURGE: &[(&str, &str)] = &[("Al", "all"), ("Clpb", "clipboard"), ("Hsty", "histories"), ("Undo", "undo")]; -const MODES: &[(&str, &str)] = &[("RGBM", "rgb"), ("Grys", "grayscale"), ("CMYM", "cmyk"), ("LbCM", "lab"), ("Mltc", "multichannel")]; - -// Events whose target depends on the descriptor (`make`, `set`, `select`…): custom converters. - -fn adjustment_steps(a: &Adjustment, prefix: &str, type_desc: Option<&Descriptor>) -> Mapped { - let params = match type_desc { - Some(t) if get_enum(t, "presetKind").as_deref() != Some("presetKindDefault") => match (a.from)(t) { - Some(p) => p, - None => return Mapped::Unsupported { harmless: false }, - }, - _ => json!({}), - }; - step(&format!("{prefix}{}", a.suffix), params) -} - -/// A `patternLayer` descriptor's pattern, scale, angle and link as the params of -/// `layer.newFillLayer.pattern` / `layer.fill.pattern.set`. The pattern goes by name: ids differ -/// between Photoshop's library and one rebuilt from the same `.pat` file. None for a pattern -/// recorded without a name or id. -fn pattern_params(t: &Descriptor) -> Option> { - let mut p = Map::new(); - if let Some(ptrn) = get_obj(t, "Ptrn") { - let key = get_text(ptrn, "Nm ").filter(|n| !n.is_empty()).or_else(|| get_text(ptrn, "Idnt").filter(|i| !i.is_empty()))?; - p.insert("pattern".into(), key.into()); - } - if let Some(s) = get_num(t, "Scl ") { - p.insert("scale".into(), s.into()); - } - if let Some(a) = get_num(t, "Angl") { - p.insert("angle".into(), a.into()); - } - if let Some(l) = get_bool(t, "Algn") { - p.insert("link".into(), l.into()); - } - Some(p) -} - -/// The `patternLayer` descriptor for [`pattern_params`]' params. -fn pattern_desc(p: &Value) -> Option { - let mut t = desc("patternLayer"); - if let Some(n) = jstr(p, "pattern") { - t = t.with("Ptrn", D::Descriptor(desc("Ptrn").with("Nm ", text(n)))); - } - if let Some(s) = jnum(p, "scale") { - t = t.with("Scl ", pct(s)); - } - if let Some(a) = jnum(p, "angle") { - t = t.with("Angl", ang(a)); - } - if let Some(l) = jbool(p, "link") { - t = t.with("Algn", D::Boolean(l)); - } - if p.get("phase").is_some() { - return None; - } - Some(t) -} - -/// Layer › Layer Mask: the `UsrM` value of an Add Layer Mask `Mk` ↔ its command. -const MASK_USING: &[(&str, &str)] = &[ - ("RvlA", "layer.layerMask.revealAll"), - ("HdAl", "layer.layerMask.hideAll"), - ("RvlS", "layer.layerMask.revealSelection"), - ("HdSl", "layer.layerMask.hideSelection"), -]; - -fn make_from(d: &Descriptor) -> Mapped { - // Duplicate layer/group into a new document: `Mk` with a document class, a layer - // `Usng`, an optional `Nm` (the new document's name) and an optional `LyrN` - // (the copy's name). A `Dplc` with a `T` document reference (duplicate into another - // open document) stays a kept Photoshop step: document indices mean nothing at replay. - if let Some(r) = get_ref(d, "null") - && ref_class(r).as_deref() == Some("Dcmn") - && matches!(target(r), Target::Class) - && let Some(u) = get_ref(d, "Usng") - && matches!(ref_class(u).as_deref(), Some("Lyr") | Some("layerSection")) - && let Some(mut p) = layer_target(u) - { - p.insert("document".into(), "new".into()); - if let Some(n) = get_text(d, "Nm ") { - p.insert("documentName".into(), n.into()); - } - if let Some(n) = get_text(d, "LyrN") { - p.insert("name".into(), n.into()); - } - return step("layer.duplicate", Value::Object(p)); - } - // Add Layer Mask: a `Chnl` class made at the mask channel, `Usng` what it reveals. - if let Some(D::Class(c)) = d.get("Nw ") - && trimmed(&c.class_id) == "Chnl" - { - // The target layer's mask only: a further item (a `Lyr` by name…) puts it on another layer. - let at_mask = get_ref(d, "At ") - .is_some_and(|r| r.len() == 1 && ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Ordinal(o) if o == "Msk")); - return match get_enum(d, "Usng").and_then(|u| lookup(MASK_USING, &u)) { - Some(id) if at_mask => none(id), - _ => Mapped::Unsupported { harmless: false }, - }; - } - if let Some(nw) = get_obj(d, "Nw ") { - // Layer via Copy / Cut (`Usng` = the selection), or a new document. - if get_enum(d, "Usng").as_deref() == Some("Slct") { - let id = if get_bool(d, "Cpy ") == Some(true) { "layer.new.layerViaCopy" } else { "layer.new.layerViaCut" }; - let mut v = vec![(id, json!({}))]; - if let Some(n) = get_text(nw, "Nm ") { - v.push(("layer.setProps", json!({"name": n}))); - } - return steps(v); - } - if get_text(nw, "preset").is_some() { - return none("file.newFromClipboard"); - } - if let (Some(w), Some(h)) = (get_num(nw, "Wdth"), get_num(nw, "Hght")) { - let res = get_num(nw, "Rslt").unwrap_or(72.0); - // Dimensions are in points (`#Rlt`) unless given in pixels. - let to_px = |k: &str, v: f64| match nw.get(k) { - Some(D::UnitFloat { unit: PX, .. }) => v, - _ => v * res / 72.0, - }; - let mut p = json!({"width": to_px("Wdth", w).round(), "height": to_px("Hght", h).round(), "resolution": res}); - if let Some(n) = get_text(nw, "Nm ") { - p["name"] = json!(n); - } - if let Some(D::Class(c)) = nw.get("Md ") - && let Some(m) = lookup(MODES, &trimmed(&c.class_id)) - { - p["mode"] = json!(m); - } - if let Some(depth) = get_num(nw, "Dpth") { - p["depth"] = json!(depth); - } - if let Some(f) = get_enum(nw, "Fl ") { - p["background"] = json!(match f.as_str() { - "Wht" => "white", - "BckC" => "backgroundColor", - "Trns" => "transparent", - _ => "white", - }); - } - return step("file.new", p); - } - return Mapped::Unsupported { harmless: false }; - } - let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; - let using = get_obj(d, "Usng"); - let type_desc = using.and_then(|u| get_obj(u, "Type")); - match ref_class(r).as_deref() { - Some("Lyr") => { - let mut p = Map::new(); - if let Some(u) = using { - if let Some(n) = get_text(u, "Nm ") { - p.insert("name".into(), n.into()); - } - if let Some(o) = get_num(u, "Opct") { - p.insert("opacity".into(), (o / 100.0).into()); - } - if let Some(m) = get_enum(u, "Md ").and_then(|m| blend_label(&m)) { - p.insert("mode".into(), m.into()); - } - } - step("layer.new.layer", Value::Object(p)) - } - Some("AdjL") => match type_desc.and_then(|t| adjustment_by_class(&trimmed(&t.class_id))) { - Some(a) => adjustment_steps(a, "layer.newAdjustmentLayer.", type_desc), - None => Mapped::Unsupported { harmless: false }, - }, - Some("contentLayer") => match type_desc { - Some(t) if t.class_id.is("solidColorLayer") => match get_obj(t, "Clr ").and_then(color_hex) { - Some(c) => step("layer.newFillLayer.solidColor", json!({"color": c})), - None => none("layer.newFillLayer.solidColor"), - }, - Some(t) if t.class_id.is("patternLayer") => match pattern_params(t) { - Some(p) => step("layer.newFillLayer.pattern", Value::Object(p)), - None => Mapped::Unsupported { harmless: false }, - }, - _ => Mapped::Unsupported { harmless: false }, - }, - Some("layerSection") => { - let mut p = Map::new(); - if let Some(n) = using.and_then(|u| get_text(u, "Nm ")) { - p.insert("name".into(), n.into()); - } - match get_ref(d, "From") { - // A named source layer stays the source (#7236); a target reference and an - // index/id source (our exporter never writes those) keep the old implicit - // import: the group lands on the current selection at playback. - Some(r) => { - if let Some(t) = layer_target(r) { - p.extend(t); - } - step("layer.groupLayers", Value::Object(p)) - } - None => step("layer.new.group", Value::Object(p)), - } - } - _ => Mapped::Unsupported { harmless: false }, - } -} - -fn make_to(id: &str, p: &Value) -> Option { - let with_name = |cls: &str| { - let mut u = desc(cls); - if let Some(n) = jstr(p, "name") { - u = u.with("Nm ", text(n)); - } - u - }; - Some(match id { - "layer.new.layer" => { - // The descriptor carries the name, opacity and mode only. A step that also clips to - // the layer below, labels the layer, fills it with the neutral colour or places it - // below the active layer would replay as a different layer, so it isn't exported - // (strict export fails, a partial one skips it: #7502, #7512, #7513, #7514). - let set = |key: &str, default: Value| p.get(key).is_some_and(|v| !v.is_null() && *v != default); - if set("clipToPrevious", Value::Bool(false)) - || set("color", json!("none")) - || set("fillNeutral", Value::Bool(false)) - || set("position", json!("above")) - { - return None; - } - let mut u = with_name("Lyr "); - if let Some(o) = jnum(p, "opacity") { - u = u.with("Opct", pct(o * 100.0)); - } - if let Some(m) = jstr(p, "mode").and_then(blend_ps) { - u = u.with("Md ", enm("BlnM", m)); - } - desc("null").with("null", class_ref("Lyr ")).with("Usng", D::Descriptor(u)) - } - "layer.new.group" => desc("null").with("null", class_ref("layerSection")).with("Usng", D::Descriptor(with_name("layerSection"))), - "layer.groupLayers" => { - // An explicit source layer goes in by name like every other layer reference; a - // step without one keeps the target-layer form (#7236). - desc("null").with("null", class_ref("layerSection")).with("From", layer_ref(p)?).with("Usng", D::Descriptor(with_name("layerSection"))) - } - "layer.new.layerViaCopy" | "layer.new.layerViaCut" => { - let mut d = desc("null").with("Nw ", D::Descriptor(desc("Lyr "))).with("Usng", enm("ArSl", "Slct")); - if id == "layer.new.layerViaCopy" { - d = d.with("Cpy ", D::Boolean(true)); - } - d - } - "layer.newFillLayer.solidColor" => { - let mut t = desc("solidColorLayer"); - // The descriptor's colour is opaque RGB: a colour with alpha, or one it can't parse, - // would replay as the default black (#7507). - if let Some(c) = p.get("color").filter(|v| !v.is_null()) { - t = t.with("Clr ", D::Descriptor(c.as_str().and_then(color_desc)?)); - } - desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t)))) - } - "layer.newFillLayer.pattern" => { - if p.get("path").is_some() { - return None; - } - let t = pattern_desc(p)?; - desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t)))) - } - "layer.duplicate" => { - // Duplicate into a new document is a `Mk`, not a `Dplc` (see `make_from`). - // Anything else falls through to the `Dplc` event below. - if jstr(p, "document") != Some("new") { - return None; - } - let mut d = desc("null").with("null", class_ref("Dcmn")).with("Usng", layer_ref(p)?); - if let Some(n) = jstr(p, "documentName") { - d = d.with("Nm ", text(n)); - } - if let Some(n) = jstr(p, "name") { - d = d.with("LyrN", text(n)); - } - d - } - "layer.layerMask.revealAll" | "layer.layerMask.hideAll" | "layer.layerMask.revealSelection" | "layer.layerMask.hideSelection" => { - // Photoshop adds the mask to the target layer only. - if p.get("layer").is_some() { - return None; - } - let at = D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code("Msk ") }]); - desc("null").with("Nw ", D::Class(class("Chnl"))).with("At ", at).with("Usng", enm("UsrM", lookup_back(MASK_USING, id)?)) - } - "file.newFromClipboard" => desc("null").with("Nw ", D::Descriptor(desc("Dcmn").with("preset", text("Clipboard")))), - "file.new" => { - let mut n = desc("Dcmn"); - if let Some(name) = jstr(p, "name") { - n = n.with("Nm ", text(name)); - } - if let Some(m) = jstr(p, "mode").and_then(|m| lookup_back(MODES, if m == "gray" { "grayscale" } else { m })) { - n = n.with("Md ", D::Class(class(m))); - } - n = n.with("Wdth", px(jnum(p, "width").unwrap_or(1920.0))).with("Hght", px(jnum(p, "height").unwrap_or(1080.0))); - n = n.with("Rslt", D::UnitFloat { unit: *b"#Rsl", value: jnum(p, "resolution").unwrap_or(72.0) }); - // `Fl ` is white, transparent or Photoshop's own background colour: black, a hex - // colour or a given `backgroundColor` would replay as something else (#7503). - if p.get("backgroundColor").is_some_and(|v| !v.is_null()) { - return None; - } - let fill = match p.get("background").filter(|v| !v.is_null()) { - None => "Wht ", - Some(b) => match b.as_str()? { - "white" => "Wht ", - "transparent" => "Trns", - "backgroundColor" => "BckC", - _ => return None, - }, - }; - n = n.with("Fl ", enm("Fl ", fill)).with("Dpth", long(jnum(p, "depth").unwrap_or(8.0))); - desc("null").with("Nw ", D::Descriptor(n)) - } - _ => { - let suffix = id.strip_prefix("layer.newAdjustmentLayer.")?; - let a = adjustment_by_suffix(suffix)?; - let t = if p.as_object().is_some_and(|o| o.is_empty()) { - desc(a.class).with("presetKind", enm("presetKindType", "presetKindDefault")) - } else { - (a.to)(p)? - }; - desc("null").with("null", class_ref("AdjL")).with("Usng", D::Descriptor(desc("AdjL").with("Type", D::Descriptor(t)))) - } - }) -} - -fn set_from(d: &Descriptor) -> Mapped { - let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; - let unsupported = Mapped::Unsupported { harmless: false }; - match (ref_class(r).as_deref(), target(r)) { - (Some("Chnl"), Target::Property(p)) if p == "fsel" => match d.get("T ") { - Some(D::Enumerated { value, .. }) => match trimmed(value).as_str() { - "Al" => none("select.all"), - "None" => none("select.deselect"), - "Prvs" => none("select.reselect"), - _ => unsupported, - }, - Some(D::Reference(t)) => match (ref_class(t).as_deref(), target(t)) { - (Some("Chnl"), Target::Ordinal(o)) if o == "Trsp" => step("select.loadSelection", json!({"channel": "transparency"})), - // ⌘-click on the targeted channel (a layer mask after `select` of `Msk`). - (Some("Chnl"), Target::Ordinal(o)) if o == "Trgt" => step("select.loadSelection", json!({"channel": "targeted"})), - (Some("Chnl"), Target::Name(n)) => step("select.loadSelection", json!({"channel": n})), - _ => unsupported, - }, - Some(D::Descriptor(t)) if t.class_id.is("Plgn") => { - let pts: Option> = get_list(t, "Pts ") - .unwrap_or(&[]) - .iter() - .map(|v| match v { - D::Descriptor(pt) => Some(json!([get_num(pt, "Hrzn")?, get_num(pt, "Vrtc")?])), - _ => None, - }) - .collect(); - match pts { - Some(pts) if pts.len() >= 3 => step("select.lasso", json!({"points": pts})), - _ => unsupported, - } - } - Some(D::Descriptor(t)) if t.class_id.is("Rctn") || t.class_id.is("Elps") => { - let (Some(top), Some(left), Some(bottom), Some(right)) = (get_num(t, "Top "), get_num(t, "Left"), get_num(t, "Btom"), get_num(t, "Rght")) - else { - return unsupported; - }; - let mut p = json!({"x": left.round(), "y": top.round(), "width": (right - left).round().max(0.0), "height": (bottom - top).round().max(0.0)}); - if t.class_id.is("Elps") { - p["ellipse"] = json!(true); - } - step("select.rect", p) - } - _ => unsupported, - }, - // 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})), - // 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" => { - // On an image that opened as a normal layer there is no Background to convert; - // Photoshop stops there, but the step's purpose (an editable layer) is met. - // Photoshop's `set` of another layer doesn't target it: the selected layer stays. - let mut v = vec![("layer.new.layerFromBackground", json!({"ifPresent": true, "select": false}))]; - let mut props = Map::new(); - props.insert("layer".into(), "Layer 0".into()); - if let Some(t) = get_obj(d, "T ") { - if let Some(n) = get_text(t, "Nm ") { - props.insert("name".into(), n.into()); - } - if let Some(o) = get_num(t, "Opct").filter(|o| (o - 100.0).abs() > 1e-9) { - props.insert("opacity".into(), (o / 100.0).into()); - } - match get_enum(t, "Md ").as_deref() { - None | Some("Nrml") => {} - Some(m) => match blend_label(m) { - Some(label) => { - props.insert("blend".into(), label.into()); - } - None => return unsupported, - }, - } - } - if props.len() > 1 { - v.push(("layer.setProps", Value::Object(props))); - } - steps(v) - } - // The toolbox colours. - (Some("Clr"), Target::Property(p)) if p == "FrgC" || p == "BckC" => match get_obj(d, "T ").and_then(color_hex) { - Some(hex) => step("tools.setColors", json!({(if p == "FrgC" { "foreground" } else { "background" }): hex})), - None => unsupported, - }, - (Some("Lyr"), _) => { - let Some(mut p) = layer_target(r) else { return unsupported }; - let Some(t) = get_obj(d, "T ") else { return unsupported }; - let mut v = Vec::new(); - if let Some(c) = get_enum(t, "Clr ").and_then(|c| lookup(LABEL_COLORS, &c)) { - let mut lp = p.clone(); - lp.insert("color".into(), c.into()); - v.push(("layer.setLabelColor", Value::Object(lp))); - } - if let Some(n) = get_text(t, "Nm ") { - p.insert("name".into(), n.into()); - } - if let Some(o) = get_num(t, "Opct") { - p.insert("opacity".into(), (o / 100.0).into()); - } - if let Some(f) = get_num(t, "fillOpacity") { - p.insert("fill".into(), (f / 100.0).into()); - } - if let Some(m) = get_enum(t, "Md ") { - let Some(label) = blend_label(&m) else { return unsupported }; - p.insert("blend".into(), label.into()); - } - if let Some(vis) = get_bool(t, "Vsbl") { - p.insert("visible".into(), vis.into()); - } - if p.keys().any(|k| k != "layer") { - v.push(("layer.setProps", Value::Object(p))); - } - if v.is_empty() { unsupported } else { steps(v) } - } - // A Pattern Fill layer's pattern (double-click its thumbnail). - (Some("contentLayer"), Target::Ordinal(o)) if o == "Trgt" => match get_obj(d, "T ") { - Some(t) if t.class_id.is("patternLayer") => match pattern_params(t) { - Some(p) if !p.is_empty() => step("layer.fill.pattern.set", Value::Object(p)), - _ => unsupported, - }, - _ => unsupported, - }, - (Some("AdjL"), Target::Ordinal(o)) if o == "Trgt" => { - match get_obj(d, "T ").and_then(|t| adjustment_by_class(&trimmed(&t.class_id)).map(|a| (a, t))) { - Some((a, t)) => match (a.from)(t) { - // `kind` names the adjustment so Save Actions can write the class back. - // Not on an empty set (Photoshop's "reset to default"): params with any key - // merge, none reset. - Some(mut p) => { - if let Some(o) = p.as_object_mut().filter(|o| !o.is_empty()) { - o.insert("kind".into(), json!(a.suffix)); - } - step("layer.setAdjustment", p) - } - None => unsupported, - }, - None => unsupported, - } - } - _ => unsupported, - } -} - -fn set_to(id: &str, p: &Value) -> Option { - let fsel = D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: Id::new("fsel") }]); - let sel = |t: D| desc("null").with("null", fsel.clone()).with("T ", t); - Some(match id { - "select.all" => sel(enm("Ordn", "Al ")), - "select.deselect" => sel(enm("Ordn", "None")), - "select.reselect" => sel(enm("Ordn", "Prvs")), - // The descriptor loads a plain new selection: inverting it or combining it with the current - // one (add, subtract, intersect) would be lost (#7506). - "select.loadSelection" - if p.get("invert").is_some_and(|v| *v != Value::Bool(false) && !v.is_null()) - || p.get("operation").is_some_and(|v| *v != json!("new") && !v.is_null()) => - { - return None; - } - "select.loadSelection" => match jstr(p, "channel")? { - "transparency" => sel(D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: Id::new("Chnl"), value: Id::new("Trsp") }])), - "targeted" => sel(D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: Id::new("Ordn"), value: Id::new("Trgt") }])), - name => sel(name_ref("Chnl", name)), - }, - "select.lasso" => { - let pts: Option> = p - .get("points")? - .as_array()? - .iter() - .map(|pt| { - let a = pt.as_array()?; - Some(D::Descriptor(desc("Pnt ").with("Hrzn", px(a.first()?.as_f64()?)).with("Vrtc", px(a.get(1)?.as_f64()?)))) - }) - .collect(); - sel(D::Descriptor(desc("Plgn").with("Pts ", D::List(pts?)))) - } - "select.editInQuickMaskMode" => { - if jbool(p, "on") != Some(true) { - return None; - } - desc("null").with("null", quick_mask_ref()) - } - "tools.setColors" => { - // One colour per Photoshop step: a step that sets both (or any other key) doesn't - // export rather than lose one. - if p.as_object().is_some_and(|o| o.keys().any(|k| k != "foreground" && k != "background")) { - return None; - } - let (key, hex) = match (jstr(p, "foreground"), jstr(p, "background")) { - (Some(f), None) => ("FrgC", f), - (None, Some(b)) => ("BckC", b), - _ => return None, - }; - desc("null") - .with("null", D::Reference(vec![ReferenceItem::Property { class: class("Clr "), key: code(key) }])) - .with("T ", D::Descriptor(color_desc(hex)?)) - } - "select.rect" => { - match jstr(p, "mode") { - None | Some("replace") => {} - Some(_) => return None, - } - let (x, y, w, h) = (jnum(p, "x")?, jnum(p, "y")?, jnum(p, "width")?, jnum(p, "height")?); - let cls = if jbool(p, "ellipse") == Some(true) { "Elps" } else { "Rctn" }; - sel(D::Descriptor(desc(cls).with("Top ", px(y)).with("Left", px(x)).with("Btom", px(y + h)).with("Rght", px(x + w)))) - } - "layer.setProps" | "layer.renameLayer" | "layer.setLabelColor" => { - // Only these keys map onto the `Lyr ` descriptor; locks, clipping, Advanced Blending - // channels or an explicit `layers` list would be dropped (#7196, #7246). - const MAPPED: [&str; 7] = ["layer", "name", "opacity", "fill", "blend", "visible", "color"]; - if p.as_object().is_some_and(|m| m.iter().any(|(k, v)| !v.is_null() && !MAPPED.contains(&k.as_str()))) { - return None; - } - let mut t = desc("Lyr "); - if let Some(n) = jstr(p, "name") { - t = t.with("Nm ", text(n)); - } - if let Some(o) = jnum(p, "opacity") { - t = t.with("Opct", pct(o * 100.0)); - } - if let Some(f) = jnum(p, "fill") { - t = t.with("fillOpacity", pct(f * 100.0)); - } - if let Some(m) = jstr(p, "blend") { - t = t.with("Md ", enm("BlnM", blend_ps(m)?)); - } - if let Some(v) = jbool(p, "visible") { - t = t.with("Vsbl", D::Boolean(v)); - } - if let Some(c) = jstr(p, "color") { - t = t.with("Clr ", enm("Clr ", lookup_back(LABEL_COLORS, c)?)); - } - if t.items.is_empty() { - return None; - } - desc("null").with("null", layer_ref(p)?).with("T ", D::Descriptor(t)) - } - "layer.new.layerFromBackground" => { - let bckg = D::Reference(vec![ReferenceItem::Property { class: class("Lyr "), key: Id::new("Bckg") }]); - desc("null").with("null", bckg).with("T ", D::Descriptor(desc("Lyr ").with("Opct", pct(100.0)).with("Md ", enm("BlnM", "Nrml")))) - } - "layer.fill.pattern.set" => { - if p.get("layer").is_some() || p.get("document").is_some() { - return None; - } - desc("null").with("null", target_ref("contentLayer")).with("T ", D::Descriptor(pattern_desc(p)?)) - } - "layer.setAdjustment" => { - // The adjustment kind isn't in the params: Photoshop needs it, so only steps that - // name one (`kind`) export. - let kind = jstr(p, "kind")?; - // `layer.setAdjustment` changes only the settings it names. Color Balance and - // Hue/Saturation descriptors carry every setting, filling absent ones with defaults, - // so a partial edit would replay as one that also resets the rest (#8531). - // Present and of the shape the writer reads: anything else it would write as 0. - let number = |p: &Value, k: &str| p.get(k).and_then(Value::as_f64).is_some_and(f64::is_finite); - let numbers = |p: &Value, keys: &[&str]| keys.iter().all(|k| number(p, k)); - let flag = |k: &str| p.get(k).is_some_and(Value::is_boolean); - let triplet = - |k: &str| p.get(k).and_then(Value::as_array).is_some_and(|a| a.len() == 3 && a.iter().all(|v| v.as_f64().is_some_and(f64::is_finite))); - let complete = match kind { - "colorBalance" => ["shadows", "midtones", "highlights"].iter().all(|k| triplet(k)) && flag("preserveLuminosity"), - // Every colour range written carries its own hue, saturation and lightness too. - "hueSaturation" => { - flag("colorize") - && numbers(p, &["hue", "saturation", "lightness"]) - && HUE_RANGES.iter().filter_map(|r| p.get(*r).filter(|v| !v.is_null())).all(|r| { - // Bounds, when given, are the four whole numbers `hue_entry` writes (as integers); - // otherwise it drops or rounds them. - let bounds = r.get("range").filter(|v| !v.is_null()).is_none_or(|v| { - v.as_array().is_some_and(|a| a.len() == 4 && a.iter().all(|b| b.as_f64().is_some_and(|b| b.is_finite() && b.fract() == 0.0))) - }); - r.is_object() && numbers(r, &["hue", "saturation", "lightness"]) && bounds - }) - } - _ => true, - }; - if !complete { - return None; - } - let a = adjustment_by_suffix(kind)?; - desc("null").with("null", target_ref("AdjL")).with("T ", D::Descriptor((a.to)(p)?)) - } - _ => return None, - }) -} - -/// Tool classes Photoshop records when an action switches tools: no document effect. -fn is_tool_class(c: &str) -> bool { - c.ends_with("Tl") || c.ends_with("Tool") -} - -fn select_from(d: &Descriptor) -> Mapped { - let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; - match (ref_class(r).as_deref(), target(r)) { - (Some("Lyr"), Target::Name(n)) => { - let mut p = json!({"layer": n}); - match get_enum(d, "selectionModifier").as_deref() { - Some("addToSelection") => p["mode"] = json!("add"), - Some("removeFromSelection") => p["mode"] = json!("remove"), - // Shift-click: select everything between the active layer and this one. - Some("addToSelectionContinuous") => p["mode"] = json!("range"), - _ => {} - } - step("layer.select", p) - } - // The Channels panel: the active layer's mask, or back to the composite (`RGB`, `CMYK`…). - (Some("Chnl"), Target::Ordinal(o)) => match o.as_str() { - "Msk" => step("channel.target", json!({"channel": "mask"})), - "RGB" | "CMYK" | "Lab" | "Gry" => step("channel.target", json!({"channel": "composite"})), - // Re-selecting the channel that is already targeted changes nothing. - "Trgt" => Mapped::Unsupported { harmless: true }, - _ => Mapped::Unsupported { harmless: false }, - }, - // History › Step Backward / Step Forward. - (Some("HstS"), Target::Ordinal(o)) if o == "Prvs" => none("edit.undo"), - (Some("HstS"), Target::Ordinal(o)) if o == "Nxt" => none("edit.redo"), - (Some("Lyr"), Target::Ordinal(o)) => { - // Shift+Alt+[ / ] add the next layer to the selection instead of replacing it. - let add = get_enum(d, "selectionModifier").as_deref() == Some("addToSelection"); - match (o.as_str(), add) { - ("Frwr", false) => none("layer.selectAbove"), - ("Frwr", true) => none("layer.addAboveToSelection"), - ("Bckw", false) => none("layer.selectBelow"), - ("Bckw", true) => none("layer.addBelowToSelection"), - ("Frnt", _) => none("layer.selectTop"), - ("Back", _) => none("layer.selectBottom"), - _ => Mapped::Unsupported { harmless: false }, - } - } - (Some(c), Target::Class) if is_tool_class(c) => Mapped::Unsupported { harmless: true }, - // A menu item chosen while recording (`Mn`): the View menu's zoom items replay. - (Some("Mn"), Target::Ordinal(item)) => match lookup(MENU_ITEMS, &item) { - Some(id) => none(id), - None => Mapped::Unsupported { harmless: false }, - }, - // Switching to another open document: its offset from the active one, -1 for the previous - // tab and 1 for the next (a template action copies from one and pastes into the other, #7103). - (Some("Dcmn"), Target::Offset(o)) => step("document.activate", json!({"offset": o})), - _ => Mapped::Unsupported { harmless: false }, - } -} - -/// `MnIt` menu-item codes ↔ the shell's view commands. -const MENU_ITEMS: &[(&str, &str)] = &[("FtOn", "view.fitOnScreen"), ("ActP", "view.actualPixels"), ("ZmIn", "view.zoomIn"), ("ZmOt", "view.zoomOut")]; - -fn select_to(id: &str, p: &Value) -> Option { - let ord = |o: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code(o) }]); - let enumerated = |cls: &str, ty: &str, v: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class(cls), type_id: code(ty), value: code(v) }]); - Some(match id { - "layer.select" => { - if p.get("occurrence").is_some() { - return None; - } - let name = jstr(p, "name").or_else(|| jstr(p, "layer"))?; - let mut d = desc("null").with("null", name_ref("Lyr ", name)); - match jstr(p, "mode") { - None | Some("replace") => {} - Some("add") => d = d.with("selectionModifier", enm("selectionModifierType", "addToSelection")), - Some("remove") => d = d.with("selectionModifier", enm("selectionModifierType", "removeFromSelection")), - Some("range") => d = d.with("selectionModifier", enm("selectionModifierType", "addToSelectionContinuous")), - Some(_) => return None, - } - d.with("MkVs", D::Boolean(false)) - } - "channel.target" => { - let v = match jstr(p, "channel") { - Some("mask") => "Msk ", - None | Some("composite") => "RGB ", - Some(_) => return None, - }; - desc("null").with("null", enumerated("Chnl", "Chnl", v)).with("MkVs", D::Boolean(false)) - } - "edit.undo" => desc("null").with("null", enumerated("HstS", "Ordn", "Prvs")), - "edit.redo" => desc("null").with("null", enumerated("HstS", "Ordn", "Nxt ")), - "layer.selectAbove" => desc("null").with("null", ord("Frwr")), - "layer.selectBelow" => desc("null").with("null", ord("Bckw")), - "layer.addAboveToSelection" => desc("null").with("null", ord("Frwr")).with("selectionModifier", enm("selectionModifierType", "addToSelection")), - "layer.addBelowToSelection" => desc("null").with("null", ord("Bckw")).with("selectionModifier", enm("selectionModifierType", "addToSelection")), - "layer.selectTop" => desc("null").with("null", ord("Frnt")), - "layer.selectBottom" => desc("null").with("null", ord("Back")), - // An absolute tab index has no Photoshop equivalent; an offset is what Photoshop records. - "document.activate" if p.get("document").is_none_or(Value::is_null) => { - let offset = i32::try_from(p.get("offset")?.as_i64()?).ok()?; - desc("null").with("null", D::Reference(vec![ReferenceItem::Offset { class: class("Dcmn"), offset }])) - } - _ => { - let item = lookup_back(MENU_ITEMS, id)?; - desc("null").with("null", D::Reference(vec![ReferenceItem::Enumerated { class: class("Mn "), type_id: code("MnIt"), value: code(item) }])) - } - }) -} - -fn delete_from(d: &Descriptor) -> Mapped { - match get_ref(d, "null") { - None => none("edit.clear"), - Some(r) if ref_class(r).as_deref() == Some("Lyr") => match layer_target(r) { - Some(p) => step("layer.delete", Value::Object(p)), - None => Mapped::Unsupported { harmless: false }, - }, - // The targeted channel of a layer is its mask (what Photoshop records after making an - // adjustment layer over a selection and discarding the mask). - Some(r) if ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Ordinal(o) if o == "Trgt") => none("layer.layerMask.delete"), - Some(_) => Mapped::Unsupported { harmless: false }, - } -} - -fn quick_mask_ref() -> D { - D::Reference(vec![ - ReferenceItem::Property { class: class("Prpr"), key: code("QucM") }, - ReferenceItem::Enumerated { class: class("Dcmn"), type_id: code("Ordn"), value: code("Trgt") }, - ]) -} - -fn clear_from(d: &Descriptor) -> Mapped { - match get_ref(d, "null").map(target) { - Some(Target::Property(p)) if p == "QucM" => step("select.editInQuickMaskMode", json!({"on": false})), - None => none("edit.clear"), - _ => Mapped::Unsupported { harmless: false }, - } -} - -fn clear_to(id: &str, p: &Value) -> Option { - match id { - "select.editInQuickMaskMode" if jbool(p, "on") == Some(false) => Some(desc("null").with("null", quick_mask_ref())), - _ => None, - } -} - -/// `placeEvent`: File › Place Embedded / Linked, with the file and the recorded scale. -fn place_from(d: &Descriptor) -> Mapped { - let Some(path) = d.get("null").and_then(path_text) else { return Mapped::Unsupported { harmless: false } }; - let mut p = json!({"path": path}); - if let Some(w) = get_num(d, "Wdth") { - p["scale"] = json!(w); - } - step(if get_bool(d, "Lnkd") == Some(true) { "file.placeLinked" } else { "file.placeEmbedded" }, p) -} - -fn place_to(id: &str, p: &Value) -> Option { - let mut d = desc("null").with("null", path_value(jstr(p, "path")?)).with("FTcs", enm("QCSt", "Qcsa")); - if let Some(s) = jnum(p, "scale") { - d = d.with("Wdth", pct(s)).with("Hght", pct(s)); - } - Some(d.with("Lnkd", D::Boolean(id == "file.placeLinked")).with("Antl", D::Boolean(true))) -} - -/// `open`: File › Open of a recorded path. -fn open_from(d: &Descriptor) -> Mapped { - match d.get("null").and_then(path_text) { - Some(path) => step("file.openAs", json!({"path": path})), - None => Mapped::Unsupported { harmless: false }, - } -} - -fn open_to(_: &str, p: &Value) -> Option { - Some(desc("null").with("null", path_value(jstr(p, "path")?))) -} - -/// Save As format classes (`As`) and the extensions PhotoCraft saves them under. The first -/// extension of a class is the one exported, and the first class of an extension is the one -/// written back. `WebPFormat` is Photoshop's built-in WebP (checked against Photoshop 2026); the -/// Google classes come from the older WebPShop plug-in and are only read. -const SAVE_FORMATS: &[(&str, &[&str])] = &[ - ("Pht3", &["psd"]), - ("PNGF", &["png"]), - ("JPEG", &["jpg", "jpeg"]), - ("TIFF", &["tif", "tiff"]), - ("BMPF", &["bmp"]), - ("WebPFormat", &["webp"]), - ("Google WebPShop", &["webp"]), - ("Google WebP", &["webp"]), -]; - -fn path_extension(path: &str) -> Option { - let name = path.rsplit(['/', '\\']).next()?; - let (stem, ext) = name.rsplit_once('.')?; - (!stem.is_empty() && !ext.is_empty()).then(|| ext.to_ascii_lowercase()) -} - -/// `save`: a plain Save, or a Save As (`As` format, `In` destination, `Cpy` As a Copy). -/// Only a destination that is a file of the recorded format imports: a folder (#5430), a missing -/// or unknown format or a mismatched extension stays a kept Photoshop step, so playback stops -/// before writing rather than saving over the played file (#7102). -fn save_from(d: &Descriptor) -> Mapped { - let unsupported = Mapped::Unsupported { harmless: false }; - if d.get("As ").is_none() && d.get("In ").is_none() { - return step("file.save", json!({})); - } - // A Save As needs a format descriptor to check the destination against: without one (or - // with a format that isn't a descriptor) the step is kept. - let Some(format) = get_obj(d, "As ") else { return unsupported }; - let Some(path) = d.get("In ").and_then(path_text) else { return unsupported }; - if get_bool(d, "DIDr") == Some(true) { - return unsupported; - } - let Some(ext) = path_extension(&path) else { return unsupported }; - let class = trimmed(&format.class_id); - let Some((_, exts)) = SAVE_FORMATS.iter().find(|(c, _)| *c == class) else { return unsupported }; - if !exts.contains(&ext.as_str()) { - return unsupported; - } - step(if get_bool(d, "Cpy ") == Some(true) { "file.saveACopy" } else { "file.saveAs" }, json!({"path": path})) -} - -fn save_to(id: &str, p: &Value) -> Option { - if id == "file.save" { - return Some(desc("null")); - } - let path = jstr(p, "path")?; - let ext = path_extension(path)?; - let (class, _) = SAVE_FORMATS.iter().find(|(_, exts)| exts.contains(&ext.as_str()))?; - let d = desc("null").with("As ", D::Descriptor(desc(class))).with("In ", path_value(path)); - Some(if id == "file.saveACopy" { d.with("Cpy ", D::Boolean(true)) } else { d }) -} - -/// Photoshop's four-character condition codes that differ from the string ids. -const CONDITION_CODES: &[(&str, &str)] = &[("Lyrs", "hasLayers")]; - -/// `conditional`: Insert Conditional, with its Then and Else actions by name. -fn conditional_from(d: &Descriptor) -> Mapped { - let Some(c) = get_enum(d, "null") else { return Mapped::Unsupported { harmless: false } }; - let condition = lookup(CONDITION_CODES, &c).unwrap_or(c.as_str()); - if !crate::actions_edit_cmds::CONDITIONS.contains(&condition) { - return Mapped::Unsupported { harmless: false }; - } - let branch = |key: &str| match get_ref(d, key).map(target) { - // Clipped like the stored action names, so the load-time rename map finds it. - Some(Target::Name(n)) => Some(clip_name(&n)), - _ => None, - }; - step("actions.conditional", json!({"if": condition, "then": branch("then"), "else": branch("else")})) -} - -fn conditional_to(_: &str, p: &Value) -> Option { - let condition = jstr(p, "if")?; - let code = lookup_back(CONDITION_CODES, condition).unwrap_or(condition); - let mut d = desc("null").with("null", enm("Cndt", code)); - for key in ["then", "else"] { - if let Some(name) = jstr(p, key) { - let mut items = vec![ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul(name) }]; - if let Some(set) = jstr(p, "set") { - items.push(ReferenceItem::Name { class: class("ASet"), name: UnicodeString::new_nul(set) }); - } - d = d.with(key, D::Reference(items)); - } - } - Some(d) -} - -/// `close`: Photoshop's Save prompt answer becomes a Save step before the Close. -fn close_from(d: &Descriptor) -> Mapped { - if get_enum(d, "Svng").as_deref() == Some("Ys") { steps(vec![("file.save", json!({})), ("file.close", json!({}))]) } else { none("file.close") } -} - -/// A Close of an explicit document has no mapping here: written as a plain Close it would -/// close the active document on playback, so it is left to `skipUnsupported`. -fn close_to(_: &str, p: &Value) -> Option { - if p.get("document").is_some_and(|d| !d.is_null()) { - return None; - } - Some(desc("null").with("Svng", enm("YsN ", "N "))) -} - -/// `transform`: Photoshop records a Free Transform relative to the frame (offset of its centre, -/// width/height in percent, angle). A layer moved only becomes `layer.translate`; anything -/// else is `edit.transform`'s relative form; the selection's frame is `select.transformSelection`. -fn transform_from(d: &Descriptor) -> Mapped { - // No reference (a smart object replaced in place, `replaceLayer`) means the target layer. - let target_layer = [ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code("Trgt") }]; - let r: &[ReferenceItem] = get_ref(d, "null").unwrap_or(&target_layer); - let unsupported = Mapped::Unsupported { harmless: false }; - let mut p = Map::new(); - if let Some(o) = get_obj(d, "Ofst") { - let in_px = |k: &str| matches!(o.get(k), Some(D::UnitFloat { unit: PX, .. })); - if !in_px("Hrzn") || !in_px("Vrtc") { - return unsupported; - } - if let Some(x) = get_num(o, "Hrzn") { - p.insert("dx".into(), x.into()); - } - if let Some(y) = get_num(o, "Vrtc") { - p.insert("dy".into(), y.into()); - } - } - for (key, param) in [("Wdth", "scaleX"), ("Hght", "scaleY"), ("Angl", "rotate")] { - if let Some(v) = get_num(d, key) { - p.insert(param.into(), v.into()); - } - } - if d.get("Skew").is_some() || d.get("Usng").is_some() { - return unsupported; - } - // A whole-pixel move is a plain `layer.translate`; a fractional one needs `edit.transform` - // to keep its sub-pixel placement and interpolation. - let whole_pixels = ["dx", "dy"].iter().all(|k| p.get(*k).and_then(Value::as_f64).is_none_or(|v| v.fract() == 0.0)); - let geometry_only = p.keys().all(|k| k == "dx" || k == "dy") && whole_pixels; - // The resampling applies to a selection as much as to a layer (#7515). - // Photoshop's bicubic variants are kept (the transforms render them as Bicubic, and they export - // back unchanged); Automatic and Preserve Details become the nearest bicubic choice. Dropping - // them fell back to the command's default, bilinear for a selection (#8697). - let interpolation = get_enum(d, "Intr").and_then(|i| lookup(INTERPOLATION, &i)).and_then(|i| match i { - "bicubic" | "bilinear" | "nearest" | "bicubicSharper" | "bicubicSmoother" | "bicubicAutomatic" => Some(i), - "automatic" => Some("bicubicAutomatic"), - "preserveDetails" => Some("bicubic"), - _ => None, - }); - match (ref_class(r).as_deref(), target(r)) { - (Some("Chnl"), Target::Property(prop)) if prop == "fsel" => { - if let Some(i) = interpolation { - p.insert("interpolation".into(), i.into()); - } - step("select.transformSelection", Value::Object(p)) - } - (Some("Lyr"), _) => { - let Some(mut lp) = layer_target(r) else { return unsupported }; - if geometry_only { - lp.insert("dx".into(), p.get("dx").and_then(Value::as_f64).unwrap_or(0.0).into()); - lp.insert("dy".into(), p.get("dy").and_then(Value::as_f64).unwrap_or(0.0).into()); - return step("layer.translate", Value::Object(lp)); - } - lp.extend(p); - if let Some(i) = interpolation { - lp.insert("interpolation".into(), i.into()); - } - step("edit.transform", Value::Object(lp)) - } - _ => unsupported, - } -} - -fn transform_to(id: &str, p: &Value) -> Option { - let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); - if ["quad", "corners", "matrix", "rect"].iter().any(|k| given(k)) { - return None; - } - // The descriptor scales and rotates about the centre (`FTcs` average) without skew or warp: - // another reference point, a skew or a warp would replay as a different transform (#7516, - // #7517, #7518, #7519). - let nonzero = |k: &str| p.get(k).is_some_and(|v| !v.is_null() && v.as_f64() != Some(0.0)); - let off_centre = p.get("reference").is_some_and(|v| !v.is_null() && *v != json!("center")); - if nonzero("skewX") || nonzero("skewY") || off_centre || ["warp", "style", "mesh", "grid"].iter().any(|k| given(k)) { - return None; - } - let target = match id { - // The `Trnf` descriptor has no field for a mask, Quick Mask or alpha channel target; a - // layer reference would transform the layer's pixels instead. - "edit.transform" if !pixel_target(p) => return None, - "edit.transform" => layer_ref(p)?, - "select.transformSelection" => D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: code("fsel") }]), - _ => return None, - }; - let mut d = desc("null").with("null", target).with("FTcs", enm("QCSt", "Qcsa")); - d = d.with("Ofst", D::Descriptor(desc("Ofst").with("Hrzn", px(jnum(p, "dx").unwrap_or(0.0))).with("Vrtc", px(jnum(p, "dy").unwrap_or(0.0))))); - for (key, param) in [("Wdth", "scaleX"), ("Hght", "scaleY")] { - if let Some(v) = jnum(p, param) { - d = d.with(key, pct(v)); - } - } - if let Some(a) = jnum(p, "rotate") { - d = d.with("Angl", ang(a)); - } - if let Some(i) = jstr(p, "interpolation").and_then(|i| lookup_back(INTERPOLATION, i)) { - d = d.with("Intr", enm("Intp", i)); - } - Some(d) -} - -/// `Clcn` (Apply Image / Calculations blending) ↔ `image.applyImage`'s `blending`. -const CALC_BLEND: &[(&str, &str)] = &[ - ("Nrml", "normal"), - ("Mltp", "multiply"), - ("Scrn", "screen"), - ("Ovrl", "overlay"), - ("SftL", "softLight"), - ("HrdL", "hardLight"), - ("CDdg", "colorDodge"), - ("CBrn", "colorBurn"), - ("Drkn", "darken"), - ("Lghn", "lighten"), - ("Dfrn", "difference"), - ("Xclu", "exclusion"), - ("linearBurn", "linearBurn"), - ("linearDodge", "linearDodge"), - ("Add ", "add"), - ("Sbtr", "subtract"), -]; -const SOURCE_CHANNELS: &[(&str, &str)] = - &[("RGB", "composite"), ("CMYK", "composite"), ("Lab", "composite"), ("Trsp", "transparency"), ("Msk", "mask"), ("fsel", "selection")]; - -fn apply_image_from(d: &Descriptor) -> Mapped { - let unsupported = Mapped::Unsupported { harmless: false }; - let Some(with) = get_obj(d, "With") else { return unsupported }; - let Some(r) = get_ref(with, "T ") else { return unsupported }; - let mut source = Map::new(); - for item in r { - match item { - ReferenceItem::Enumerated { class, value, .. } if class.class_id.is("Chnl") => { - let v = trimmed(value); - let Some(channel) = lookup(SOURCE_CHANNELS, &v).or_else(|| lookup(CHANNELS, &v)) else { return unsupported }; - source.insert("channel".into(), channel.into()); - } - // A named (alpha) channel. - ReferenceItem::Name { class, name } if class.class_id.is("Chnl") => { - source.insert("channel".into(), name.to_string_lossy().into()); - } - ReferenceItem::Name { class, name } if class.class_id.is("Lyr ") => { - source.insert("layer".into(), name.to_string_lossy().into()); - } - ReferenceItem::Enumerated { class, value, .. } if class.class_id.is("Lyr ") && trimmed(value) == "Mrgd" => { - source.insert("layer".into(), "merged".into()); - } - _ => return unsupported, - } - } - if let Some(i) = get_bool(with, "Invr") { - source.insert("invert".into(), i.into()); - } - let mut p = json!({"source": source}); - if let Some(c) = get_enum(with, "Clcl") { - match lookup(CALC_BLEND, &c) { - Some(b) => p["blending"] = json!(b), - None => return unsupported, - } - } - for (key, param) in [("Scl ", "scale"), ("Ofst", "offset"), ("Opct", "opacity")] { - if let Some(v) = get_num(with, key) { - p[param] = json!(v); - } - } - if let Some(t) = get_bool(with, "PrsT") { - p["preserveTransparency"] = json!(t); - } - step("image.applyImage", p) -} - -/// Apply Image's source channel as a `Chnl` reference item. The dialog sends Channels-panel names -/// ("RGB", "Red", "Alpha 1"), which the command reads case-insensitively: the composite names map to -/// the composite, colour names to their enumeration, and any other name to a named (alpha) channel, -/// as Photoshop records it. -fn apply_image_channel(channel: &str) -> Option { - let l = channel.to_ascii_lowercase(); - let key = match l.as_str() { - "rgb" | "cmyk" | "lab" | "merged" => "composite", - "layermask" => "mask", - // Sources the command knows by keyword but Photoshop has no channel for. - "quickmask" | "quick mask" | "vectormask" | "vector mask" => return None, - other => other, - }; - Some(match lookup_back(SOURCE_CHANNELS, key).or_else(|| lookup_back(CHANNELS, key)) { - Some(chan) => ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code(chan) }, - None if !channel.trim().is_empty() => ReferenceItem::Name { class: class("Chnl"), name: UnicodeString::new_nul(channel) }, - None => return None, - }) -} - -fn apply_image_to(_: &str, p: &Value) -> Option { - // The optional blending mask has no descriptor mapping: refuse it rather than drop it, - // which would widen the edit to the whole layer. - let mask_channel = match p.get("mask") { - Some(m) => m.get("channel"), - None => p.get("maskChannel"), - }; - if mask_channel.is_some_and(|c| !(c.is_null() || c == "none" || c == "")) { - return None; - } - // The Apply Image dialog sends flat `sourceLayer`/`sourceChannel`/`sourceInvert` fields; read - // them as the command does, or the export would quietly reset them to the merged composite. - let source = crate::channel_cmds::source_spec(p, "source", "source").unwrap_or(json!({})); - // A source from another open document has no event form here: skip the step, don't rewrite it. - if source.get("document").is_some_and(|d| !d.is_null()) { - return None; - } - // A layer id or channel index has no name to record: refuse it rather than write the composite. - let not_name = |k: &str| source.get(k).is_some_and(|v| !(v.is_null() || v.is_string())); - if !source.is_object() || not_name("layer") || not_name("channel") { - return None; - } - let mut items = vec![apply_image_channel(jstr(&source, "channel").unwrap_or("composite"))?]; - match jstr(&source, "layer") { - Some("merged") | None => items.push(ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code("Mrgd") }), - Some(name) => items.push(ReferenceItem::Name { class: class("Lyr "), name: UnicodeString::new_nul(name) }), - } - let mut with = desc("null").with("T ", D::Reference(items)); - if let Some(i) = jbool(&source, "invert") { - with = with.with("Invr", D::Boolean(i)); - } - with = with.with("Clcl", enm("Clcn", lookup_back(CALC_BLEND, jstr(p, "blending").unwrap_or("multiply"))?)); - if let Some(v) = jnum(p, "opacity") { - with = with.with("Opct", pct(v)); - } - if let Some(v) = jnum(p, "scale") { - with = with.with("Scl ", D::Double(v)); - } - if let Some(v) = jnum(p, "offset") { - with = with.with("Ofst", D::Double(v)); - } - if let Some(t) = jbool(p, "preserveTransparency") { - with = with.with("PrsT", D::Boolean(t)); - } - Some(desc("null").with("With", D::Descriptor(with))) -} - -const WEB_FORMATS: &[(&str, &str)] = &[("PN24", "png24"), ("PN8", "png8"), ("JPEG", "jpeg"), ("GIFf", "gif"), ("WBMP", "wbmp")]; - -/// `export` (Save for Web): needs the destination path (`In`), as the command writes a file. -fn export_from(d: &Descriptor) -> Mapped { - let unsupported = Mapped::Unsupported { harmless: false }; - let Some(u) = get_obj(d, "Usng") else { return unsupported }; - let Some(path) = d.get("In ").and_then(path_text) else { return unsupported }; - let mut p = json!({"path": path}); - if let Some(f) = get_enum(u, "Fmt ") { - match lookup(WEB_FORMATS, &f) { - Some(f) => p["format"] = json!(f), - None => return unsupported, - } - } - for (key, param) in [("Intr", "interlaced"), ("Trns", "transparency"), ("EICC", "embedIcc"), ("Prgr", "progressive"), ("Optm", "optimized")] { - if let Some(b) = get_bool(u, key) { - p[param] = json!(b); - } - } - for (key, param) in [("Qlty", "quality"), ("NCol", "colors")] { - if let Some(v) = get_num(u, key) { - p[param] = json!(v); - } - } - if get_bool(u, "Mtt ") == Some(false) { - p["matte"] = json!("none"); - } else if let (Some(r), Some(g), Some(b)) = (get_num(u, "MttR"), get_num(u, "MttG"), get_num(u, "MttB")) { - p["matte"] = - json!(format!("#{:02x}{:02x}{:02x}", r.round().clamp(0.0, 255.0) as u8, g.round().clamp(0.0, 255.0) as u8, b.round().clamp(0.0, 255.0) as u8)); - } - step("file.export.saveForWebLegacy", p) -} - -fn export_to(_: &str, p: &Value) -> Option { - let path = jstr(p, "path")?; - let mut u = desc("SaveForWeb").with("Op ", enm("SWOp", "OpSa")).with("Fmt ", enm("IRFm", lookup_back(WEB_FORMATS, jstr(p, "format").unwrap_or("png24"))?)); - for (key, param, default) in [ - ("Intr", "interlaced", false), - ("Trns", "transparency", true), - ("EICC", "embedIcc", false), - ("Prgr", "progressive", false), - ("Optm", "optimized", true), - ] { - u = u.with(key, D::Boolean(jbool(p, param).unwrap_or(default))); - } - if let Some(q) = jnum(p, "quality") { - u = u.with("Qlty", long(q)); - } - if let Some(c) = jnum(p, "colors") { - u = u.with("NCol", long(c)); - } - match jstr(p, "matte") { - Some("none") => u = u.with("Mtt ", D::Boolean(false)), - matte => { - let c = color_desc(matte.unwrap_or("#ffffff"))?; - u = u - .with("Mtt ", D::Boolean(true)) - .with("MttR", get_num(&c, "Rd ").map(long)?) - .with("MttG", get_num(&c, "Grn ").map(long)?) - .with("MttB", get_num(&c, "Bl ").map(long)?); - } - } - Some(desc("null").with("Usng", D::Descriptor(u)).with("In ", path_value(path))) -} - -fn delete_to(id: &str, p: &Value) -> Option { - Some(match id { - "edit.clear" => desc("null"), - "layer.delete" => desc("null").with("null", layer_ref(p)?), - "layer.layerMask.delete" => desc("null").with("null", target_ref("Chnl")), - _ => return None, - }) -} - -/// `hide` / `show` take a list of references (or one). -fn visibility_from(d: &Descriptor, id: &str) -> Mapped { - let refs: Vec<&[ReferenceItem]> = match d.get("null") { - Some(D::List(l)) => l.iter().filter_map(|v| if let D::Reference(r) = v { Some(r.as_slice()) } else { None }).collect(), - Some(D::Reference(r)) => vec![r.as_slice()], - _ => return Mapped::Unsupported { harmless: false }, - }; - let mut v = Vec::new(); - for r in refs { - match layer_target(r) { - Some(p) => v.push((id, Value::Object(p))), - None => return Mapped::Unsupported { harmless: false }, - } - } - if v.is_empty() { Mapped::Unsupported { harmless: false } } else { steps(v) } -} - -fn visibility_to(_: &str, p: &Value) -> Option { - Some(desc("null").with("null", D::List(vec![layer_ref(p)?]))) -} - -fn move_from(d: &Descriptor) -> Mapped { - let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; - // The selection outline nudged. - if ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Property(p) if p == "fsel") { - return match get_obj(d, "T ") { - Some(t) if matches!(t.get("Hrzn"), Some(D::UnitFloat { unit: PX, .. })) => match (get_num(t, "Hrzn"), get_num(t, "Vrtc")) { - (Some(dx), Some(dy)) => step("select.transformSelection", json!({"dx": dx.round(), "dy": dy.round()})), - _ => Mapped::Unsupported { harmless: false }, - }, - _ => Mapped::Unsupported { harmless: false }, - }; - } - if ref_class(r).as_deref() != Some("Lyr") { - return Mapped::Unsupported { harmless: false }; - } - let Some(mut p) = layer_target(r) else { return Mapped::Unsupported { harmless: false } }; - match d.get("T ") { - Some(D::Descriptor(t)) => { - let unit = |k: &str| match t.get(k) { - Some(D::UnitFloat { unit, .. }) => Some(*unit), - _ => None, - }; - let (Some(dx), Some(dy)) = (get_num(t, "Hrzn"), get_num(t, "Vrtc")) else { return Mapped::Unsupported { harmless: false } }; - match (unit("Hrzn"), unit("Vrtc")) { - (Some(PX), Some(PX)) => { - p.insert("dx".into(), dx.round().into()); - p.insert("dy".into(), dy.round().into()); - } - // A nudge recorded with the rulers in other units: points, converted to pixels - // at the resolution of the document the action plays on. - (Some(PT), Some(PT)) => { - p.insert("dx".into(), dx.into()); - p.insert("dy".into(), dy.into()); - p.insert("units".into(), "pt".into()); - } - _ => return Mapped::Unsupported { harmless: false }, - } - step("layer.translate", Value::Object(p)) - } - Some(D::Reference(t)) => { - let id = match target(t) { - Target::Ordinal(o) if o == "Frnt" => "layer.arrange.bringToFront", - Target::Ordinal(o) if o == "Back" => "layer.arrange.sendToBack", - Target::Ordinal(o) if o == "Nxt" => "layer.arrange.bringForward", - Target::Ordinal(o) if o == "Prvs" => "layer.arrange.sendBackward", - Target::Offset(1) => "layer.arrange.bringForward", - Target::Offset(-1) => "layer.arrange.sendBackward", - // Index 0 is the bottom of the stack. - Target::Index(0) => "layer.arrange.sendToBack", - _ => return Mapped::Unsupported { harmless: false }, - }; - step(id, Value::Object(p)) - } - _ => Mapped::Unsupported { harmless: false }, - } -} - -fn move_to(id: &str, p: &Value) -> Option { - let ord = |o: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code(o) }]); - let t = match id { - "layer.translate" => { - let unit = match jstr(p, "units") { - None | Some("px") => PX, - Some("pt") => PT, - Some(_) => return None, - }; - let v = |k: &str| D::UnitFloat { unit, value: jnum(p, k).unwrap_or(0.0) }; - D::Descriptor(desc("Ofst").with("Hrzn", v("dx")).with("Vrtc", v("dy"))) - } - "layer.arrange.bringToFront" => ord("Frnt"), - "layer.arrange.sendToBack" => ord("Back"), - "layer.arrange.bringForward" => ord("Nxt "), - "layer.arrange.sendBackward" => ord("Prvs"), - _ => return None, - }; - Some(desc("null").with("null", layer_ref(p)?).with("T ", t)) -} - -fn duplicate_from(d: &Descriptor) -> Mapped { - let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; - match ref_class(r).as_deref() { - Some("Lyr") => { - // A `T` document reference (duplicate into another open document) has no - // replayable meaning here: keep the step verbatim rather than misplay it. - if get_ref(d, "T ").is_some() { - return Mapped::Unsupported { harmless: false }; - } - let Some(mut p) = layer_target(r) else { return Mapped::Unsupported { harmless: false } }; - if let Some(n) = get_text(d, "Nm ") { - p.insert("name".into(), n.into()); - } - step("layer.duplicate", Value::Object(p)) - } - Some("Dcmn") => { - let mut p = Map::new(); - if let Some(n) = get_text(d, "Nm ") { - p.insert("name".into(), n.into()); - } - if let Some(m) = get_bool(d, "Mrgd") { - p.insert("mergedOnly".into(), m.into()); - } - step("image.duplicate", Value::Object(p)) - } - _ => Mapped::Unsupported { harmless: false }, - } -} - -fn duplicate_to(id: &str, p: &Value) -> Option { - // Duplicate into a new document is a `Mk` (handled above); let it fall through. - if id == "layer.duplicate" && jstr(p, "document") == Some("new") { - return None; - } - // Photoshop's Duplicate has no in-place flag: a plain one would place the artboard copy beside - // the original on playback. - if id == "layer.duplicate" && jbool(p, "inPlace") == Some(true) { - return None; - } - let mut d = match id { - "layer.duplicate" => desc("null").with("null", layer_ref(p)?), - "image.duplicate" => { - desc("null").with("null", D::Reference(vec![ReferenceItem::Enumerated { class: class("Dcmn"), type_id: Id::new("Ordn"), value: Id::new("Frst") }])) - } - _ => return None, - }; - if let Some(n) = jstr(p, "name") { - d = d.with("Nm ", text(n)); - } - if let Some(m) = jbool(p, "mergedOnly") { - d = d.with("Mrgd", D::Boolean(m)); - } - Some(d) -} - -/// Only a comp name in the active document is portable across action playback. -fn apply_comp_from(d: &Descriptor) -> Mapped { - match get_ref(d, "null") { - Some([ReferenceItem::Name { class, name }]) if trimmed(&class.class_id) == "compsClass" => { - step("layerComp.apply", json!({"comp": name.to_string_lossy()})) - } - _ => Mapped::Unsupported { harmless: false }, - } -} - -fn apply_comp_to(_: &str, p: &Value) -> Option { - Some(desc("null").with("null", name_ref("compsClass", jstr(p, "comp")?))) -} - -fn play_from(d: &Descriptor) -> Mapped { - match get_ref(d, "null").map(target) { - Some(Target::Name(n)) => step("actions.play", json!({"action": clip_name(&n)})), - _ => Mapped::Unsupported { harmless: false }, - } -} - -fn play_to(_: &str, p: &Value) -> Option { - let name = jstr(p, "action")?; - // The Play Action descriptor written here carries no starting step, so a call from a later step is not a whole call. - if p.get("from").is_some_and(|v| !v.is_null() && v.as_f64() != Some(0.0)) { - return None; - } - let mut items = vec![ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul(name) }]; - if let Some(set) = jstr(p, "set") { - items.push(ReferenceItem::Name { class: class("ASet"), name: UnicodeString::new_nul(set) }); - } - Some(desc("null").with("null", D::Reference(items))) -} - -fn fill_from(d: &Descriptor) -> Mapped { - if let Some(from) = get_obj(d, "From") { - // The Paint Bucket tool's click: its point is in pixels, or in percent of the canvas - // (not replayable without the document size). - let in_px = |k: &str| matches!(from.get(k), Some(D::UnitFloat { unit: PX, .. })); - let (Some(x), Some(y)) = (get_num(from, "Hrzn"), get_num(from, "Vrtc")) else { return Mapped::Unsupported { harmless: false } }; - if !in_px("Hrzn") || !in_px("Vrtc") { - return Mapped::Unsupported { harmless: false }; - } - let mut p = json!({"x": x.round(), "y": y.round()}); - match get_enum(d, "Usng").as_deref() { - Some("FrgC") | None => {} - Some("Pttn") => p["contents"] = json!("pattern"), - Some("Clr") => match get_obj(d, "Clr ").and_then(color_hex) { - Some(c) => p["color"] = json!(c), - None => return Mapped::Unsupported { harmless: false }, - }, - Some(_) => return Mapped::Unsupported { harmless: false }, - } - if let Some(t) = get_num(d, "Tlrn") { - p["tolerance"] = json!(t); - } - if let Some(c) = get_bool(d, "Cntg") { - p["contiguous"] = json!(c); - } - if let Some(a) = get_bool(d, "AntA") { - p["antiAlias"] = json!(a); - } - if let Some(m) = get_bool(d, "Mrgd") { - p["sampleAllLayers"] = json!(m); - } - if let Some(o) = get_num(d, "Opct") { - p["opacity"] = json!(o); - } - return step("paint.bucket", p); - } - let Some(contents) = get_enum(d, "Usng").and_then(|u| lookup(FILL_CONTENTS, &u)) else { return Mapped::Unsupported { harmless: false } }; - let mut p = json!({"contents": contents}); - if contents == "color" { - match get_obj(d, "Clr ").and_then(color_hex) { - Some(c) => p["color"] = json!(c), - None => return Mapped::Unsupported { harmless: false }, - } - } - if let Some(o) = get_num(d, "Opct") { - p["opacity"] = json!(o); - } - if let Some(m) = get_enum(d, "Md ") { - match blend_label(&m) { - Some(l) => p["mode"] = json!(l), - None => return Mapped::Unsupported { harmless: false }, - } - } - if let Some(t) = get_bool(d, "PrsT") { - p["preserveTransparency"] = json!(t); - } - step("edit.fill", p) -} - -fn fill_to(id: &str, p: &Value) -> Option { - if id == "paint.bucket" { - let mut d = desc("null").with("From", D::Descriptor(desc("Pnt ").with("Hrzn", px(jnum(p, "x")?)).with("Vrtc", px(jnum(p, "y")?)))); - d = d.with("Tlrn", long(jnum(p, "tolerance").unwrap_or(32.0))).with("AntA", D::Boolean(jbool(p, "antiAlias").unwrap_or(true))); - // `source` is the command's older name for `contents`. - d = if p.get("contents").or_else(|| p.get("source")).and_then(Value::as_str) == Some("pattern") { - // `Pttn` names no pattern and holds no placement: a chosen pattern, a scale, an angle - // or a phase would replay with the current pattern at its defaults (#7543, #7544, - // #7545, #7546). - let num = |k: &str, default: f64| p.get(k).is_some_and(|v| !v.is_null() && v.as_f64() != Some(default)); - let phase = p.get("phase").is_some_and(|v| !v.is_null() && v.as_array().is_none_or(|a| a.iter().any(|c| c.as_f64() != Some(0.0)))); - if p.get("pattern").is_some_and(|v| !v.is_null()) || num("scale", 100.0) || num("angle", 0.0) || phase { - return None; - } - d.with("Usng", enm("FlCn", "Pttn")) - } else { - // An explicit colour overrides the foreground (#7199): it travels as Fill's `Clr `. - match bucket_color(p.get("color"))? { - Some(c) => d.with("Usng", enm("FlCn", "Clr ")).with("Clr ", D::Descriptor(c)), - None => d.with("Usng", enm("FlCn", "FrgC")), - } - }; - if let Some(o) = jnum(p, "opacity") { - d = d.with("Opct", pct(o)); - } - if let Some(c) = jbool(p, "contiguous") { - d = d.with("Cntg", D::Boolean(c)); - } - if let Some(m) = jbool(p, "sampleAllLayers") { - d = d.with("Mrgd", D::Boolean(m)); - } - return Some(d); - } - let contents = jstr(p, "contents").unwrap_or("color"); - let mut d = desc("null").with("Usng", enm("FlCn", lookup_back(FILL_CONTENTS, contents)?)); - if contents == "color" { - d = d.with("Clr ", D::Descriptor(color_desc(jstr(p, "color")?)?)); - } - if let Some(o) = jnum(p, "opacity") { - d = d.with("Opct", pct(o)); - } - if let Some(m) = jstr(p, "mode") { - d = d.with("Md ", enm("BlnM", blend_ps(m)?)); - } - if let Some(t) = jbool(p, "preserveTransparency") { - d = d.with("PrsT", D::Boolean(t)); - } - Some(d) -} - -/// The Paint Bucket's `color` as `paint.bucket` reads it (`[r, g, b(, a)]` in 0..=1 or -/// `#rrggbb(aa)`): `Some(None)` when it fills with the foreground (no colour, or a string the -/// command doesn't read), `None` when the colour can't be written (not opaque, or outside 0..=1). -fn bucket_color(v: Option<&Value>) -> Option> { - let rgba = match v { - Some(Value::Array(a)) if a.len() >= 3 => { - let c: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(); - [*c.first()?, *c.get(1)?, *c.get(2)?, c.get(3).copied().unwrap_or(1.0)] - } - Some(Value::String(h)) => { - let h = h.trim_start_matches('#'); - let c = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| f64::from(v) / 255.0); - let (Some(r), Some(g), Some(b)) = (c(0), c(2), c(4)) else { return Some(None) }; - [r, g, b, c(6).unwrap_or(1.0)] - } - _ => return Some(None), - }; - if rgba[3] != 1.0 || !rgba.iter().all(|v| (0.0..=1.0).contains(v)) { - return None; - } - Some(Some(desc("RGBC").with("Rd ", D::Double(rgba[0] * 255.0)).with("Grn ", D::Double(rgba[1] * 255.0)).with("Bl ", D::Double(rgba[2] * 255.0)))) -} - -/// Preserve the command's effective integer width instead of rounding its input again. -fn stroke_to(_: &str, p: &Value) -> Option { - if !pixel_target(p) { - return None; - } - let mut params = if p.is_null() { Map::new() } else { p.as_object()?.clone() }; - params.insert("width".into(), Value::from(crate::extra_cmds::stroke_width(p))); - fields_to(&Value::Object(params), STROKE, desc("null")) -} - -const STROKE: &[F] = &[ - F("Wdth", "width", Kind::Long), - F("Lctn", "location", Kind::Enum("StrL", STROKE_LOCATION)), - F("Opct", "opacity", Kind::Pct), - F("Md ", "mode", Kind::Blend), - F("Clr ", "color", Kind::Color), - F("PrsT", "preserveTransparency", Kind::Bool), -]; - -/// Whether an event's `null` reference targets a layer (Edit › Transform) rather than the -/// document (Image › Image Rotation). -fn targets_layer(d: &Descriptor) -> bool { - get_ref(d, "null").and_then(ref_class).as_deref() == Some("Lyr") -} - -fn rotate_from(d: &Descriptor) -> Mapped { - let Some(angle) = get_num(d, "Angl") else { return Mapped::Unsupported { harmless: false } }; - let a = angle.rem_euclid(360.0); - let (layer, doc) = if (a - 90.0).abs() < 1e-6 { - ("edit.transform.rotate90Cw", "image.imageRotation.90cw") - } else if (a - 270.0).abs() < 1e-6 { - ("edit.transform.rotate90Ccw", "image.imageRotation.90ccw") - } else if (a - 180.0).abs() < 1e-6 { - ("edit.transform.rotate180", "image.imageRotation.180") - } else if targets_layer(d) { - return Mapped::Unsupported { harmless: false }; - } else { - let mut p = json!({"angle": angle.abs(), "direction": if angle < 0.0 { "ccw" } else { "cw" }}); - if let Some(i) = get_enum(d, "Intr").and_then(|i| lookup(INTERPOLATION, &i)).filter(|i| matches!(*i, "bicubic" | "bilinear" | "nearest")) { - p["interpolation"] = i.into(); - } - return step("image.rotation.arbitrary", p); - }; - none(if targets_layer(d) { layer } else { doc }) -} - -fn rotate_to(id: &str, p: &Value) -> Option { - let (angle, layer) = match id { - "edit.transform.rotate90Cw" => (90.0, true), - "edit.transform.rotate90Ccw" => (-90.0, true), - "edit.transform.rotate180" => (180.0, true), - "image.imageRotation.90cw" => (90.0, false), - "image.imageRotation.90ccw" => (-90.0, false), - "image.imageRotation.180" => (180.0, false), - "image.rotation.arbitrary" => (jnum(p, "angle")? * if jstr(p, "direction") == Some("ccw") { -1.0 } else { 1.0 }, false), - _ => return None, - }; - let mut d = desc("null"); - if layer { - d = d.with("null", target_ref("Lyr ")); - } - d = d.with("Angl", ang(angle)); - if id == "image.rotation.arbitrary" - && let Some(i) = p.get("interpolation") - { - // The command resamples with nearest, bilinear or bicubic; any other value can't be - // carried faithfully, so refuse rather than replay with a different interpolation. - let i = match i.as_str()? { - "nearestNeighbor" => "nearest", - i @ ("bicubic" | "bilinear" | "nearest") => i, - _ => return None, - }; - d = d.with("Intr", enm("Intp", lookup_back(INTERPOLATION, i)?)); - } - Some(d) -} - -fn flip_from(d: &Descriptor) -> Mapped { - let Some(axis) = get_enum(d, "Axis") else { return Mapped::Unsupported { harmless: false } }; - let horizontal = axis == "Hrzn"; - none(match (targets_layer(d), horizontal) { - (true, true) => "edit.transform.flipHorizontal", - (true, false) => "edit.transform.flipVertical", - (false, true) => "image.imageRotation.flipCanvasHorizontal", - (false, false) => "image.imageRotation.flipCanvasVertical", - }) -} - -fn flip_to(id: &str, _: &Value) -> Option { - let (layer, axis) = match id { - "edit.transform.flipHorizontal" => (true, "Hrzn"), - "edit.transform.flipVertical" => (true, "Vrtc"), - "image.imageRotation.flipCanvasHorizontal" => (false, "Hrzn"), - "image.imageRotation.flipCanvasVertical" => (false, "Vrtc"), - _ => return None, - }; - let mut d = desc("null"); - if layer { - d = d.with("null", target_ref("Lyr ")); - } - Some(d.with("Axis", enm("Ornt", axis))) -} - -fn convert_mode_from(d: &Descriptor) -> Mapped { - if let Some(depth) = get_num(d, "Dpth") { - return match depth as i64 { - 8 => none("image.mode.bits8"), - 16 => none("image.mode.bits16"), - 32 => none("image.mode.bits32"), - _ => Mapped::Unsupported { harmless: false }, - }; - } - // The mode as an enumeration (`ClrS.Grys`), a class (`Grys`), or an object of the mode's - // class holding its options (`BtmM {Rslt, Mthd}`, `Grys {Rt}` from Bitmap). - let (mode, options) = match d.get("T ") { - Some(D::Enumerated { value, .. }) => (trimmed(value), None), - Some(D::Class(c)) => (trimmed(&c.class_id), None), - Some(D::Descriptor(o)) => (trimmed(&o.class_id), Some(o)), - _ => return Mapped::Unsupported { harmless: false }, - }; - if mode == "BtmM" { - return bitmap_from(options); - } - // Bitmap to Grayscale records a size ratio; only 1 keeps the pixels as they are. - if options.and_then(|o| get_num(o, "Rt ")).is_some_and(|r| (r - 1.0).abs() > 1e-9) { - return Mapped::Unsupported { harmless: false }; - } - match lookup(MODES, &mode) { - Some(m) => none(&format!("image.mode.{m}")), - None => Mapped::Unsupported { harmless: false }, - } -} - -const BITMAP_METHOD: &[(&str, &str)] = &[("Thrh", "threshold"), ("PtnD", "pattern"), ("DfnD", "diffusion")]; - -/// Image › Mode › Bitmap. Its Output resolution resamples the image, keeping the print size, -/// before the conversion; at the document's own resolution that is a no-op. Halftone screens -/// and custom patterns stay unsupported. -fn bitmap_from(options: Option<&Descriptor>) -> Mapped { - let Some(o) = options else { return none("image.mode.bitmap") }; - let method = match get_enum(o, "Mthd") { - None => "diffusion", - Some(m) => match lookup(BITMAP_METHOD, &m) { - Some(m) => m, - None => return Mapped::Unsupported { harmless: false }, - }, - }; - let convert = ("image.mode.bitmap", json!({"method": method})); - match get_num(o, "Rslt") { - Some(r) => steps(vec![("image.imageSize", json!({"resolution": r, "resample": "bicubic", "keepPrintSize": true})), convert]), - None => steps(vec![convert]), - } -} - -fn bitmap_to(p: &Value) -> Option { - let method = lookup_back(BITMAP_METHOD, jstr(p, "method").unwrap_or("diffusion"))?; - Some(desc("null").with("T ", D::Descriptor(desc("BtmM").with("Mthd", enm("Mthd", method))))) -} - -fn convert_mode_to(id: &str, p: &Value) -> Option { - Some(match id { - "image.mode.bits8" => desc("null").with("Dpth", long(8.0)), - "image.mode.bits16" => desc("null").with("Dpth", long(16.0)), - "image.mode.bits32" => desc("null").with("Dpth", long(32.0)), - "image.mode.bitmap" => bitmap_to(p)?, - _ => desc("null").with("T ", enm("ClrS", lookup_back(MODES, id.strip_prefix("image.mode.")?)?)), - }) -} - -fn canvas_size_from(d: &Descriptor) -> Mapped { - let mut p = Map::new(); - for (k, param) in [("Wdth", "width"), ("Hght", "height")] { - match d.get(k) { - Some(D::UnitFloat { unit: PX, value }) => { - p.insert(param.into(), value.round().into()); - } - Some(_) => return Mapped::Unsupported { harmless: false }, - None => {} - } - } - if let Some(r) = get_bool(d, "Rltv") { - p.insert("relative".into(), r.into()); - } - let v = get_enum(d, "Vrtc").unwrap_or_else(|| "Cntr".into()); - let h = get_enum(d, "Hrzn").unwrap_or_else(|| "Cntr".into()); - let anchor = match (v.as_str(), h.as_str()) { - ("Top", "Left") => "topLeft", - ("Top", "Cntr") => "top", - ("Top", "Rght") => "topRight", - ("Cntr", "Left") => "left", - ("Cntr", "Cntr") => "center", - ("Cntr", "Rght") => "right", - ("Bttm", "Left") => "bottomLeft", - ("Bttm", "Cntr") => "bottom", - ("Bttm", "Rght") => "bottomRight", - _ => return Mapped::Unsupported { harmless: false }, - }; - p.insert("anchor".into(), anchor.into()); - if let Some(c) = get_enum(d, "canvasExtensionColorType") { - match lookup(EXTENSION, &c) { - Some(c) => { - p.insert("extensionColor".into(), c.into()); - } - None => match get_obj(d, "canvasExtensionColor").and_then(color_hex) { - Some(hex) => { - p.insert("extensionColor".into(), hex.into()); - } - None => return Mapped::Unsupported { harmless: false }, - }, - } - } - step("image.canvasSize", Value::Object(p)) -} - -fn canvas_size_to(_: &str, p: &Value) -> Option { - let anchor = jstr(p, "anchor").unwrap_or("center"); - let v = if anchor.starts_with("top") { - "Top " - } else if anchor.starts_with("bottom") { - "Bttm" - } else { - "Cntr" - }; - let h = if anchor.to_ascii_lowercase().ends_with("left") { - "Left" - } else if anchor.to_ascii_lowercase().ends_with("right") { - "Rght" - } else { - "Cntr" - }; - let mut d = desc("null"); - if let Some(r) = jbool(p, "relative") { - d = d.with("Rltv", D::Boolean(r)); - } - if let Some(w) = jnum(p, "width") { - d = d.with("Wdth", px(w)); - } - if let Some(hh) = jnum(p, "height") { - d = d.with("Hght", px(hh)); - } - d = d.with("Hrzn", enm("HrzL", h)).with("Vrtc", enm("VrtL", v)); - if let Some(c) = jstr(p, "extensionColor") { - d = match lookup_back(EXTENSION, c) { - Some(e) => d.with("canvasExtensionColorType", enm("canvasExtensionColorType", e)), - None => d.with("canvasExtensionColorType", enm("canvasExtensionColorType", "Othr")).with("canvasExtensionColor", D::Descriptor(color_desc(c)?)), - }; - } - Some(d) -} - -fn image_size_from(d: &Descriptor) -> Mapped { - let mut p = Map::new(); - let mut percent: Option = None; - for (k, param) in [("Wdth", "width"), ("Hght", "height")] { - match d.get(k) { - Some(D::UnitFloat { unit: PX, value }) => { - p.insert(param.into(), value.round().into()); - } - // Percent scales both sides at playback; two different percentages, or physical - // units, need the document's size and resolution and stay unsupported. - Some(D::UnitFloat { unit: PCT, value }) => match percent { - Some(other) if (other - value).abs() > 1e-9 => return Mapped::Unsupported { harmless: false }, - _ => percent = Some(*value), - }, - Some(_) => return Mapped::Unsupported { harmless: false }, - None => {} - } - } - if let Some(pc) = percent { - p.insert("percent".into(), pc.into()); - } - if let Some(r) = get_num(d, "Rslt") { - p.insert("resolution".into(), r.into()); - } - if let Some(i) = get_enum(d, "Intr") { - match lookup(INTERPOLATION, &i) { - Some(i) => { - p.insert("resample".into(), i.into()); - // Resample on with only the resolution changed: Photoshop keeps the print size. - if p.contains_key("resolution") && !p.contains_key("width") && !p.contains_key("height") && !p.contains_key("percent") { - p.insert("keepPrintSize".into(), true.into()); - } - } - None => return Mapped::Unsupported { harmless: false }, - } - } else if p.contains_key("resolution") && !p.contains_key("width") && !p.contains_key("height") && !p.contains_key("percent") { - p.insert("resample".into(), "none".into()); - } - if p.is_empty() { - return Mapped::Unsupported { harmless: false }; - } - step("image.imageSize", Value::Object(p)) -} - -/// Shadows/Highlights (`adaptCorrect`, #5830): the shadow and highlight tones are `shadowMode` -/// and `highlightMode` objects (amount and width in %, radius in px), then the black and white -/// clips (%), midtone contrast (`center`) and colour correction. Each key is read as its char ID -/// or its string ID, whichever the file used; absent keys keep the command's defaults. -const SHADOWS_HIGHLIGHTS_TONES: [(&str, &str, &str); 2] = [("sdwM", "shadowMode", "shadow"), ("hglM", "highlightMode", "highlight")]; -const SHADOWS_HIGHLIGHTS_TONE: [(&str, &str, &str); 3] = [("Amnt", "amount", "Amount"), ("Wdth", "width", "Tone"), ("Rds ", "radius", "Radius")]; -const SHADOWS_HIGHLIGHTS: [(&str, &str, &str); 4] = - [("BlcC", "blackClip", "blackClip"), ("WhtC", "whiteClip", "whiteClip"), ("Cntr", "center", "midtone"), ("ClrC", "colorCorrection", "color")]; - -fn shadows_highlights_from(d: &Descriptor) -> Mapped { - let mut m = Map::new(); - for (code, name, prefix) in SHADOWS_HIGHLIGHTS_TONES { - let Some(t) = get_obj(d, code).or_else(|| get_obj(d, name)) else { continue }; - for (code, name, suffix) in SHADOWS_HIGHLIGHTS_TONE { - if let Some(v) = get_num(t, code).or_else(|| get_num(t, name)) { - m.insert(format!("{prefix}{suffix}"), Value::from(v)); - } - } - } - for (code, name, param) in SHADOWS_HIGHLIGHTS { - if let Some(v) = get_num(d, code).or_else(|| get_num(d, name)) { - m.insert(param.into(), Value::from(v)); - } - } - step("image.adjustments.shadowsHighlights", Value::Object(m)) -} - -fn shadows_highlights_to(_: &str, p: &Value) -> Option { - let mut d = desc("null"); - for (_, name, prefix) in SHADOWS_HIGHLIGHTS_TONES { - let mut t = desc("adaptCorrectTones"); - for (_, key, suffix) in SHADOWS_HIGHLIGHTS_TONE { - if let Some(v) = jnum(p, &format!("{prefix}{suffix}")) { - t = t.with(key, if suffix == "Radius" { long(v) } else { pct(v) }); - } - } - d = d.with(name, D::Descriptor(t)); - } - for (_, key, param) in SHADOWS_HIGHLIGHTS { - if let Some(v) = jnum(p, param) { - d = d.with(key, if matches!(param, "midtone" | "color") { long(v) } else { D::Double(v) }); - } - } - Some(d) -} - -fn image_size_to(_: &str, p: &Value) -> Option { - // Resolution only with Resample on imports as keep-print-size; a command without it cannot be told apart. - if jnum(p, "resolution").is_some() - && jnum(p, "width").is_none() - && jnum(p, "height").is_none() - && jnum(p, "percent").is_none() - && jstr(p, "resample").is_some_and(|r| r != "none") - && jbool(p, "keepPrintSize") != Some(true) - { - return None; - } - let mut d = desc("null"); - // `resample: "none"` changes the resolution only and the command ignores any size then. The - // descriptor has no "none" (it is the absence of `Intr`), so writing the ignored size would - // turn the step into a pixel resize on playback (#7189). - let resolution_only = jstr(p, "resample") == Some("none"); - if resolution_only && jnum(p, "resolution").is_none() { - // Nothing left to record: the step changes nothing. - return None; - } - if let Some(pc) = jnum(p, "percent").filter(|_| !resolution_only) { - d = d.with("Wdth", pct(pc)).with("Hght", pct(pc)).with("CnsP", D::Boolean(true)); - } - if let Some(w) = jnum(p, "width").filter(|_| !resolution_only) { - d = d.with("Wdth", px(w)); - } - if let Some(h) = jnum(p, "height").filter(|_| !resolution_only) { - d = d.with("Hght", px(h)); - } - if let Some(r) = jnum(p, "resolution") { - d = d.with("Rslt", D::UnitFloat { unit: *b"#Rsl", value: r }); - } - if let Some(i) = jstr(p, "resample").filter(|r| *r != "none") { - d = d.with("Intr", enm("Intp", lookup_back(INTERPOLATION, i)?)); - } - Some(d) -} - -fn crop_from(d: &Descriptor) -> Mapped { - let mut p = Map::new(); - if let Some(t) = get_obj(d, "To ") { - // Pixels only, like Canvas Size: a side in percent or points needs the document's size - // or resolution and must not be played as pixels. - let side = |k: &str| match t.get(k) { - Some(D::UnitFloat { unit: PX, value }) if value.is_finite() => Some(*value), - _ => None, - }; - let (Some(top), Some(left), Some(bottom), Some(right)) = (side("Top "), side("Left"), side("Btom"), side("Rght")) else { - return Mapped::Unsupported { harmless: false }; - }; - p.insert("x".into(), left.round().into()); - p.insert("y".into(), top.round().into()); - p.insert("width".into(), (right - left).round().into()); - p.insert("height".into(), (bottom - top).round().into()); - } - if let Some(a) = get_num(d, "Angl") { - p.insert("angle".into(), a.into()); - } - if let Some(del) = get_bool(d, "Dlt ") { - p.insert("deleteCroppedPixels".into(), del.into()); - } - step("image.crop", Value::Object(p)) -} - -fn crop_to(_: &str, p: &Value) -> Option { - // The W x H x Resolution output options have no field here: refuse rather than export a plain - // rectangle crop that keeps the old size and resolution on replay. - if ["targetWidth", "targetHeight", "resolution"].iter().any(|k| p.get(k).is_some_and(|v| !v.is_null())) { - return None; - } - let mut d = desc("null"); - if let (Some(x), Some(y), Some(w), Some(h)) = (jnum(p, "x"), jnum(p, "y"), jnum(p, "width"), jnum(p, "height")) { - d = d.with("To ", D::Descriptor(desc("Rctn").with("Top ", px(y)).with("Left", px(x)).with("Btom", px(y + h)).with("Rght", px(x + w)))); - } - if let Some(a) = jnum(p, "angle") { - d = d.with("Angl", ang(a)); - } - if let Some(del) = jbool(p, "deleteCroppedPixels") { - d = d.with("Dlt ", D::Boolean(del)); - } - Some(d) -} - -fn stop_from(d: &Descriptor) -> Mapped { - step(STOP_MESSAGE, json!({"message": get_text(d, "Msge").unwrap_or_default(), "allowContinue": get_bool(d, "Cntn").unwrap_or(false)})) -} - -fn stop_to(_: &str, p: &Value) -> Option { - Some(desc("null").with("Msge", text(jstr(p, "message").unwrap_or(""))).with("Cntn", D::Boolean(jbool(p, "allowContinue").unwrap_or(false)))) -} - -fn paste_from(d: &Descriptor) -> Mapped { - none(if get_bool(d, "inPlace") == Some(true) { "edit.pasteSpecial.pasteInPlace" } else { "edit.paste" }) -} - -fn paste_to(id: &str, _: &Value) -> Option { - let mut d = desc("null"); - if id == "edit.pasteSpecial.pasteInPlace" { - d = d.with("inPlace", D::Boolean(true)); - } - Some(d.with("AntA", enm("Annt", "Anno"))) -} - -fn merge_visible_from(d: &Descriptor) -> Mapped { - none(if get_bool(d, "Dplc") == Some(true) { "layer.stampVisible" } else { "layer.mergeVisible" }) -} - -fn merge_visible_to(id: &str, _: &Value) -> Option { - Some(if id == "layer.stampVisible" { desc("null").with("Dplc", D::Boolean(true)) } else { desc("null") }) -} - -fn align_from(d: &Descriptor) -> Mapped { - match get_enum(d, "Usng").and_then(|u| lookup(ALIGN, &u)) { - Some(a) => step(&format!("layer.align.{a}"), if get_bool(d, "alignToCanvas") == Some(true) { json!({"to": "canvas"}) } else { json!({}) }), - None => Mapped::Unsupported { harmless: false }, - } -} - -fn align_to(id: &str, p: &Value) -> Option { - let a = lookup_back(ALIGN, id.strip_prefix("layer.align.")?)?; - Some(desc("null").with("null", target_ref("Lyr ")).with("Usng", enm("ADSt", a)).with("alignToCanvas", D::Boolean(jstr(p, "to") == Some("canvas")))) -} - -fn purge_from(d: &Descriptor) -> Mapped { - match get_enum(d, "null").and_then(|u| lookup(PURGE, &u)) { - Some(p) => none(&format!("edit.purge.{p}")), - None => Mapped::Unsupported { harmless: true }, - } -} - -fn purge_to(id: &str, _: &Value) -> Option { - Some(desc("null").with("null", enm("PrgI", lookup_back(PURGE, id.strip_prefix("edit.purge.")?)?))) -} - -fn reset_from(d: &Descriptor) -> Mapped { - match get_ref(d, "null").map(target) { - Some(Target::Property(p)) if p == "Clrs" => none("tools.defaultColors"), - _ => Mapped::Unsupported { harmless: true }, - } -} - -fn reset_to(_: &str, _: &Value) -> Option { - Some(desc("null").with("null", D::Reference(vec![ReferenceItem::Property { class: class("Clr "), key: Id::new("Clrs") }]))) -} - -fn profile_from(d: &Descriptor, id: &str) -> Mapped { - let name = get_text(d, "T ").or_else(|| get_text(d, "profile")); - let Some(profile) = name.as_deref().and_then(|n| lookup(PROFILES, n)) else { return Mapped::Unsupported { harmless: false } }; - let mut p = json!({"profile": profile}); - if id == "edit.convertToProfile" { - if let Some(i) = get_enum(d, "Inte").and_then(|i| lookup(INTENT, &i)) { - p["intent"] = json!(i); - } - if let Some(b) = get_bool(d, "MpBl") { - p["bpc"] = json!(b); - } - } - step(id, p) -} - -fn profile_to(id: &str, p: &Value) -> Option { - let name = lookup_back(PROFILES, jstr(p, "profile")?)?; - let mut d = desc("null").with("null", target_ref("Dcmn")); - if id == "edit.convertToProfile" { - d = d - .with("T ", text(name)) - .with("Inte", enm("Inte", lookup_back(INTENT, jstr(p, "intent").unwrap_or("relative"))?)) - .with("MpBl", D::Boolean(jbool(p, "bpc").unwrap_or(true))); - } else { - d = d.with("profile", text(name)); - } - Some(d) -} - -fn levels_event_from(d: &Descriptor) -> Mapped { - if get_bool(d, "Auto") == Some(true) { - return none("image.autoTone"); - } - if get_bool(d, "AuCo") == Some(true) { - return none("image.autoContrast"); - } - match levels_from(d) { - Some(p) => step("image.adjustments.levels", p), - None => Mapped::Unsupported { harmless: false }, - } -} - -fn levels_event_to(id: &str, p: &Value) -> Option { - Some(match id { - "image.autoTone" => desc("null").with("Auto", D::Boolean(true)), - "image.autoContrast" => desc("null").with("AuCo", D::Boolean(true)), - _ => levels_to(p)?, - }) -} - -/// A direct adjustment event (Image › Adjustments › …). The command id is `image.adjustments.` -/// unless it is given. -macro_rules! adjustment_event { - ($code:literal, $class:literal, $name:literal, $label:literal) => { - adjustment_event!($code, $class, $name, $label, concat!("image.adjustments.", $name)) - }; - ($code:literal, $class:literal, $name:literal, $label:literal, $id:expr) => { - Event { - code: $code, - name: $name, - label: $label, - ids: &[$id], - from: |d| match adjustment_by_class($class) { - Some(a) => adjustment_steps(a, "image.adjustments.", Some(d)), - None => Mapped::Unsupported { harmless: false }, - }, - to: |_, p| adjustment_by_class($class).and_then(|a| (a.to)(p)), - } - }; -} - -const RIPPLE_SIZE: &[(&str, &str)] = &[("Sml", "small"), ("Mdm", "medium"), ("Lrg", "large")]; - -/// Whether a Select and Mask step carries Refine Edge Brush strokes or the workspace's tool -/// edits (Quick Selection, Brush, Lasso…), which no descriptor holds. -fn has_refine_strokes(p: &Value) -> bool { - p.get("refineStrokes").is_some_and(|v| !v.is_null() && v.as_array().is_none_or(|a| !a.is_empty())) || crate::select_mask_edits::has_edits(p) -} - -/// Select and Mask to Photoshop. The descriptor has no field for the Refine Edge Brush or the -/// workspace's tools, so a step with `refineStrokes` or `edits` can't be exported faithfully. One with `sampleAllLayers` is not -/// exported here either: it exports as `smartBrushWorkspace`. -fn refine_edge_to(_: &str, p: &Value) -> Option { - if !pixel_target(p) || p.get("sampleAllLayers").is_some() || has_refine_strokes(p) { - return None; - } - fields_to(p, REFINE_EDGE, desc("null")) -} - -/// Select and Mask (`refineSelectionEdge`). Smart Radius, decontamination and the output follow -/// Photoshop's; the edge itself is PhotoCraft's own matting, so results differ in detail. -const REFINE_EDGE: &[F] = &[ - F("refineEdgeBorderRadius", "radius", Kind::Px), - F("refineEdgeAutoRadius", "smartRadius", Kind::Bool), - F("refineEdgeSmooth", "smooth", Kind::Long), - F("refineEdgeFeatherRadius", "feather", Kind::Px), - F("refineEdgeBorderContrast", "contrast", Kind::Pct), - F("refineEdgeChoke", "shiftEdge", Kind::Pct), - F("refineEdgeDecontaminate", "decontaminate", Kind::Bool), - F("refineEdgeDeconAmount", "amount", Kind::Pct), - F("refineEdgeOutput", "output", Kind::Enum("refineEdgeOutput", REFINE_OUTPUT)), -]; -const REFINE_OUTPUT: &[(&str, &str)] = &[ - ("refineEdgeOutputSelection", "selection"), - ("refineEdgeOutputUserMask", "layerMask"), - ("refineEdgeOutputNewLayer", "newLayer"), - ("refineEdgeOutputNewLayerWithMask", "newLayerWithMask"), - ("refineEdgeOutputNewDocument", "newDocument"), - ("refineEdgeOutputNewDocumentWithMask", "newDocumentWithMask"), -]; - -/// Filter Gallery effects (`GEfc` with the effect in `GEfk`): Photoshop's effect code, the -/// command, and its fields. A stack of several effects stays unsupported. -const GALLERY: &[(&str, &str, &[F])] = &[("Spt", "filter.gallery.spatter", &[F("SprR", "sprayRadius", Kind::Long), F("Smth", "smoothness", Kind::Long)])]; -const GALLERY_IDS: &[&str] = &["filter.gallery.spatter"]; - -fn gallery_from(d: &Descriptor) -> Mapped { - let Some(effect) = get_enum(d, "GEfk") else { return Mapped::Unsupported { harmless: false } }; - match GALLERY.iter().find(|(code, _, _)| *code == effect).and_then(|(_, id, fields)| Some((*id, fields_from(d, fields)?))) { - Some((id, p)) => step(id, Value::Object(p)), - None => Mapped::Unsupported { harmless: false }, - } -} - -fn gallery_to(id: &str, p: &Value) -> Option { - let (code, _, fields) = GALLERY.iter().find(|(_, cmd, _)| *cmd == id)?; - fields_to(p, fields, desc("null").with("GEfk", enm("GEft", code))) -} - -/// Select and Mask as Photoshop CC 2015.5 and later record it (`smartBrushWorkspace`); the -/// older Refine Edge event is [`REFINE_EDGE`], which is also what Select and Mask exports as. -const SMART_BRUSH: &[F] = &[ - F("smartBrushRadius", "radius", Kind::Px), - F("smartBrushUseSmartRadius", "smartRadius", Kind::Bool), - F("smartBrushSmooth", "smooth", Kind::Long), - F("smartBrushFeather", "feather", Kind::Px), - F("smartBrushContrast", "contrast", Kind::Pct), - F("smartBrushShiftEdge", "shiftEdge", Kind::Pct), - F("smartBrushDecontaminate", "decontaminate", Kind::Bool), - F("smartBrushDeconAmount", "amount", Kind::Pct), - F("refineEdgeOutput", "output", Kind::Enum("refineEdgeOutput", REFINE_OUTPUT)), - F("sampleAllLayers", "sampleAllLayers", Kind::Bool), -]; - -/// Select › Color Range's `Clrs` presets ↔ `select.colorRange`'s `select`. -const COLOR_RANGE: &[(&str, &str)] = &[ - ("Rds", "reds"), - ("Ylws", "yellows"), - ("Grns", "greens"), - ("Cyns", "cyans"), - ("Bls", "blues"), - ("Mgnt", "magentas"), - ("Hghl", "highlights"), - ("Mdtn", "midtones"), - ("Shdw", "shadows"), - ("OtOf", "outOfGamut"), - ("skinTone", "skinTones"), -]; - -/// The Color Range keys the converter reads (or that don't change a preset's result: -/// `colorModel` is the model of sampled colours). -const COLOR_RANGE_KEYS: &[&str] = &[ - "Clrs", - "Fzns", - "Invr", - "colorModel", - "shadowsFuzziness", - "shadowsUpperLimit", - "midtonesFuzziness", - "midtonesLowerLimit", - "midtonesUpperLimit", - "highlightsFuzziness", - "highlightsLowerLimit", -]; - -/// Color Range (`ClrR`) with a preset. Sampled Colors records Lab minimum and maximum colours, -/// which `select.colorRange` (eyedropper points on the image) can't reproduce, and an unknown -/// key (Detect Faces, Localized Color Clusters…) could change the result: both stay -/// unsupported. -fn color_range_from(d: &Descriptor) -> Mapped { - let unsupported = Mapped::Unsupported { harmless: false }; - if d.items.iter().any(|(k, _)| !COLOR_RANGE_KEYS.contains(&trimmed(k).as_str())) { - return unsupported; - } - let Some(preset) = get_enum(d, "Clrs").and_then(|c| lookup(COLOR_RANGE, &c)) else { return unsupported }; - let mut p = Map::new(); - p.insert("select".into(), preset.into()); - let key = |suffix: &str| get_num(d, &format!("{preset}{suffix}")); - match preset { - "skinTones" => { - if let Some(f) = get_num(d, "Fzns") { - p.insert("fuzziness".into(), f.into()); - } - } - "shadows" | "midtones" | "highlights" => { - if let Some(f) = key("Fuzziness") { - p.insert("fuzziness".into(), f.into()); - } - let range = match (preset, key("LowerLimit"), key("UpperLimit")) { - ("shadows", _, hi) => hi.map(Value::from), - ("highlights", lo, _) => lo.map(Value::from), - (_, Some(lo), Some(hi)) => Some(json!([lo, hi])), - (_, None, None) => None, - _ => return unsupported, - }; - if let Some(r) = range { - p.insert("tonalRange".into(), r); - } - } - _ => {} - } - if get_bool(d, "Invr") == Some(true) { - p.insert("invert".into(), true.into()); - } - step("select.colorRange", Value::Object(p)) -} - -fn color_range_to(_: &str, p: &Value) -> Option { - let preset = jstr(p, "select")?; - if p.as_object()?.keys().any(|k| !matches!(k.as_str(), "select" | "fuzziness" | "tonalRange" | "invert")) { - return None; - } - let mut d = desc("null").with("Clrs", enm("Clrs", lookup_back(COLOR_RANGE, preset)?)); - let tonal = matches!(preset, "shadows" | "midtones" | "highlights"); - if let Some(f) = jnum(p, "fuzziness") { - match preset { - "skinTones" => d = d.with("Fzns", long(f)), - _ if tonal => d = d.with(&format!("{preset}Fuzziness"), long(f)), - _ => {} - } - } - if let Some(r) = p.get("tonalRange") { - match preset { - "shadows" => d = d.with("shadowsUpperLimit", long(r.as_f64()?)), - "highlights" => d = d.with("highlightsLowerLimit", long(r.as_f64()?)), - "midtones" => { - let a = r.as_array()?; - d = d.with("midtonesLowerLimit", long(a.first()?.as_f64()?)).with("midtonesUpperLimit", long(a.get(1)?.as_f64()?)); - } - _ => return None, - } - } - if jbool(p, "invert") == Some(true) { - d = d.with("Invr", D::Boolean(true)); - } - Some(d) -} - -/// Create / Release Clipping Mask (`groupEvent` / `ungroup`) on the target or a named layer. -fn clipping_from(d: &Descriptor, id: &str) -> Mapped { - match get_ref(d, "null") { - None => none(id), - Some(r) if ref_class(r).as_deref() == Some("Lyr") => match layer_target(r) { - Some(p) => step(id, Value::Object(p)), - None => Mapped::Unsupported { harmless: false }, - }, - Some(_) => Mapped::Unsupported { harmless: false }, - } -} - -fn clipping_to(_: &str, p: &Value) -> Option { - Some(desc("null").with("null", layer_ref(p)?)) -} - -/// A clipping mask event: `clipping_from` / `clipping_to` with one command id. -macro_rules! clipping_event { - ($code:literal, $name:literal, $label:literal, $id:literal) => { - Event { code: $code, name: $name, label: $label, ids: &[$id], from: |d| clipping_from(d, $id), to: clipping_to } - }; -} - -const RADIAL_BLUR_FIELDS: &[F] = - &[F("Amnt", "amount", Kind::Long), F("BlrM", "method", Kind::Enum("BlrM", RADIAL_METHOD)), F("BlrQ", "quality", Kind::Enum("BlrQ", RADIAL_QUALITY))]; - -fn radial_blur_from(d: &Descriptor) -> Mapped { - match fields_from(d, RADIAL_BLUR_FIELDS) { - Some(m) => step("filter.blur.radialBlur", Value::Object(m)), - None => Mapped::Unsupported { harmless: false }, - } -} - -fn radial_blur_to(_: &str, p: &Value) -> Option { - if !pixel_target(p) { - return None; - } - // Photoshop's Radial Blur has no center parameter and always blurs from the center (0.5, 0.5). - // An explicit center must match 0.5 exactly; any non-default center cannot be faithfully exported. - let is_default_center = |k: &str| match p.get(k) { - None | Some(Value::Null) => true, - Some(v) => v.as_f64() == Some(0.5), - }; - if !is_default_center("centerX") || !is_default_center("centerY") { - return None; - } - fields_to(p, RADIAL_BLUR_FIELDS, desc("null")) -} - -/// Every Photoshop event PhotoCraft maps. The order matters only for the panel label. -const EVENTS: &[Event] = &[ - // Filters. - ev!("GsnB", "gaussianBlur", "Gaussian Blur", "filter.blur.gaussianBlur", &[F("Rds ", "radius", Kind::Px)]), - ev!( - "UnsM", - "unsharpMask", - "Unsharp Mask", - "filter.sharpen.unsharpMask", - &[F("Amnt", "amount", Kind::Pct), F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)] - ), - ev!( - "AdNs", - "addNoise", - "Add Noise", - "filter.noise.addNoise", - &[ - F("Dstr", "distribution", Kind::Enum("Dstr", NOISE)), - F("Nose", "amount", Kind::Pct), - F("Mnch", "monochromatic", Kind::Bool), - F("FlRs", "seed", Kind::Long) - ] - ), - ev!("Mdn ", "median", "Median", "filter.noise.median", &[F("Rds ", "radius", Kind::Px)]), - ev!("DstS", "dustAndScratches", "Dust & Scratches", "filter.noise.dustAndScratches", &[F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)]), - ev!("Dspc", "despeckle", "Despeckle", "filter.noise.despeckle", &[]), - // Photoshop records Emboss's angle, height and amount as plain integers (#7946). - ev!( - "Embs", - "emboss", - "Emboss", - "filter.stylize.emboss", - &[F("Angl", "angle", Kind::Long), F("Hght", "height", Kind::Long), F("Amnt", "amount", Kind::Long)] - ), - ev!("MtnB", "motionBlur", "Motion Blur", "filter.blur.motionBlur", &[F("Angl", "angle", Kind::Ang), F("Dstn", "distance", Kind::Px)]), - ev!("", "boxblur", "Box Blur", "filter.blur.boxBlur", &[F("Rds ", "radius", Kind::Px)]), - ev!("", "surfaceBlur", "Surface Blur", "filter.blur.surfaceBlur", &[F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)]), - ev!( - "SmrB", - "smartBlur", - "Smart Blur", - "filter.blur.smartBlur", - &[ - F("Rds ", "radius", Kind::Dbl), - F("Thsh", "threshold", Kind::Dbl), - F("SmBQ", "quality", Kind::Enum("SmBQ", SMART_BLUR_QUALITY)), - F("SmBM", "mode", Kind::Enum("SmBM", SMART_BLUR_MODE)) - ] - ), - Event { code: "RdlB", name: "radialBlur", label: "Radial Blur", ids: &["filter.blur.radialBlur"], from: radial_blur_from, to: radial_blur_to }, - ev!("Blr ", "blur", "Blur", "filter.blur.blur", &[]), - ev!("BlrM", "blurMore", "Blur More", "filter.blur.blurMore", &[]), - ev!("Shrp", "sharpen", "Sharpen", "filter.sharpen.sharpen", &[]), - ev!("ShrM", "sharpenMore", "Sharpen More", "filter.sharpen.sharpenMore", &[]), - ev!("ShrE", "sharpenEdges", "Sharpen Edges", "filter.sharpen.sharpenEdges", &[]), - ev!("HghP", "highPass", "High Pass", "filter.other.highPass", &[F("Rds ", "radius", Kind::Px)]), - ev!("Mnm ", "minimum", "Minimum", "filter.other.minimum", &[F("Rds ", "radius", Kind::Px)], unless preserves_roundness), - ev!("Mxm ", "maximum", "Maximum", "filter.other.maximum", &[F("Rds ", "radius", Kind::Px)], unless preserves_roundness), - ev!( - "Ofst", - "offset", - "Offset", - "filter.other.offset", - &[F("Hrzn", "horizontal", Kind::Long), F("Vrtc", "vertical", Kind::Long), F("Fl ", "undefinedAreas", Kind::Enum("FlMd", OFFSET_FILL))] - ), - ev!("Rple", "ripple", "Ripple", "filter.distort.ripple", &[F("Amnt", "amount", Kind::ExactLong), F("RplS", "size", Kind::Enum("RplS", RIPPLE_SIZE))]), - ev!("Crst", "crystallize", "Crystallize", "filter.pixelate.crystallize", &[F("ClSz", "cellSize", Kind::ExactLong)]), - Event { code: "GEfc", name: "filterGallery", label: "Filter Gallery", ids: GALLERY_IDS, from: gallery_from, to: gallery_to }, - // Adjustments (Image › Adjustments). - Event { - code: "", - name: "adaptCorrect", - label: "Shadows/Highlights", - ids: &["image.adjustments.shadowsHighlights"], - from: shadows_highlights_from, - to: shadows_highlights_to, - }, - Event { - code: "Lvls", - name: "levels", - label: "Levels", - ids: &["image.adjustments.levels", "image.autoTone", "image.autoContrast"], - from: levels_event_from, - to: levels_event_to, - }, - adjustment_event!("Crvs", "Crvs", "curves", "Curves"), - adjustment_event!("HStr", "HStr", "hueSaturation", "Hue/Saturation"), - adjustment_event!("BrgC", "BrgC", "brightnessEvent", "Brightness/Contrast", "image.adjustments.brightnessContrast"), - adjustment_event!("Thrs", "Thrs", "threshold", "Threshold"), - adjustment_event!("Pstr", "Pstr", "posterize", "Posterize"), - adjustment_event!("Invr", "Invr", "invert", "Invert"), - adjustment_event!("ClrB", "ClrB", "colorBalance", "Color Balance"), - adjustment_event!("Vbrn", "Vbrn", "vibrance", "Vibrance"), - adjustment_event!("Exps", "Exps", "exposure", "Exposure"), - // Photoshop runs Photo Filter by name only: `PhtF` is the class, not an event (#8301). - adjustment_event!("", "PhtF", "photoFilter", "Photo Filter"), - adjustment_event!("", "BanW", "blackAndWhite", "Black & White", "image.adjustments.blackWhite"), - adjustment_event!("ChnM", "ChnM", "channelMixer", "Channel Mixer"), - adjustment_event!("GdMp", "GdMp", "gradientMapEvent", "Gradient Map", "image.adjustments.gradientMap"), - adjustment_event!("SlcC", "SlcC", "selectiveColor", "Selective Color"), - ev!("Dstt", "desaturate", "Desaturate", "image.adjustments.desaturate", &[]), - ev!("Eqlz", "equalize", "Equalize", "image.adjustments.equalize", &[]), - ev!("", "autoColor", "Auto Color", "image.autoColor", &[]), - // Image. - Event { code: "ImgS", name: "imageSize", label: "Image Size", ids: &["image.imageSize"], from: image_size_from, to: image_size_to }, - Event { code: "CnvS", name: "canvasSize", label: "Canvas Size", ids: &["image.canvasSize"], from: canvas_size_from, to: canvas_size_to }, - Event { - code: "Rtte", - name: "rotateEventEnum", - label: "Rotate", - ids: &[ - "image.imageRotation.90cw", - "image.imageRotation.90ccw", - "image.imageRotation.180", - "image.rotation.arbitrary", - "edit.transform.rotate90Cw", - "edit.transform.rotate90Ccw", - "edit.transform.rotate180", - ], - from: rotate_from, - to: rotate_to, - }, - Event { - code: "Flip", - name: "flip", - label: "Flip", - ids: &[ - "image.imageRotation.flipCanvasHorizontal", - "image.imageRotation.flipCanvasVertical", - "edit.transform.flipHorizontal", - "edit.transform.flipVertical", - ], - from: flip_from, - to: flip_to, - }, - Event { code: "Crop", name: "crop", label: "Crop", ids: &["image.crop"], from: crop_from, to: crop_to }, - ev!( - "", - "trim", - "Trim", - "image.trim", - &[ - F("trimBasedOn", "basedOn", Kind::Enum("trimBasedOn", TRIM)), - F("Top ", "top", Kind::Bool), - F("Btom", "bottom", Kind::Bool), - F("Left", "left", Kind::Bool), - F("Rght", "right", Kind::Bool) - ] - ), - ev!("RvlA", "revealAll", "Reveal All", "image.revealAll", &[]), - Event { - code: "CnvM", - name: "convertMode", - label: "Convert Mode", - ids: &[ - "image.mode.rgb", - "image.mode.grayscale", - "image.mode.cmyk", - "image.mode.lab", - "image.mode.multichannel", - "image.mode.bits8", - "image.mode.bits16", - "image.mode.bits32", - "image.mode.bitmap", - ], - from: convert_mode_from, - to: convert_mode_to, - }, - Event { code: "Dplc", name: "duplicate", label: "Duplicate", ids: &["layer.duplicate", "image.duplicate"], from: duplicate_from, to: duplicate_to }, - // Layers. - Event { - code: "Mk ", - name: "make", - label: "Make", - ids: &[ - "layer.new.layer", - "layer.new.group", - "layer.groupLayers", - "layer.duplicate", - "layer.new.layerViaCopy", - "layer.new.layerViaCut", - "layer.newFillLayer.solidColor", - "layer.newFillLayer.pattern", - "layer.newAdjustmentLayer.levels", - "layer.newAdjustmentLayer.curves", - "layer.newAdjustmentLayer.hueSaturation", - "layer.newAdjustmentLayer.brightnessContrast", - "layer.newAdjustmentLayer.threshold", - "layer.newAdjustmentLayer.posterize", - "layer.newAdjustmentLayer.invert", - "layer.newAdjustmentLayer.colorBalance", - "layer.newAdjustmentLayer.vibrance", - "layer.newAdjustmentLayer.exposure", - "layer.newAdjustmentLayer.photoFilter", - "layer.newAdjustmentLayer.blackWhite", - "layer.newAdjustmentLayer.channelMixer", - "layer.newAdjustmentLayer.selectiveColor", - "layer.newAdjustmentLayer.gradientMap", - "layer.layerMask.revealAll", - "layer.layerMask.hideAll", - "layer.layerMask.revealSelection", - "layer.layerMask.hideSelection", - "file.new", - "file.newFromClipboard", - ], - from: make_from, - to: make_to, - }, - Event { - code: "setd", - name: "set", - label: "Set", - ids: &[ - "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", - "layer.new.layerFromBackground", - ], - from: set_from, - to: set_to, - }, - Event { - code: "slct", - name: "select", - label: "Select", - ids: &[ - "layer.select", - "layer.selectAbove", - "layer.selectBelow", - "layer.addAboveToSelection", - "layer.addBelowToSelection", - "layer.selectTop", - "layer.selectBottom", - "channel.target", - "edit.undo", - "edit.redo", - "view.fitOnScreen", - "view.actualPixels", - "view.zoomIn", - "view.zoomOut", - "document.activate", - ], - from: select_from, - to: select_to, - }, - Event { code: "Dlt ", name: "delete", label: "Delete", ids: &["layer.delete", "edit.clear", "layer.layerMask.delete"], from: delete_from, to: delete_to }, - Event { code: "", name: "clearEvent", label: "Clear", ids: &["select.editInQuickMaskMode"], from: clear_from, to: clear_to }, - Event { - code: "Trnf", - name: "transform", - label: "Transform", - ids: &["edit.transform", "select.transformSelection"], - from: transform_from, - to: transform_to, - }, - Event { code: "AppI", name: "applyImageEvent", label: "Apply Image", ids: &["image.applyImage"], from: apply_image_from, to: apply_image_to }, - ev!("", "newPlacedLayer", "Convert to Smart Object", "layer.smartObjects.convertToSmartObject", &[]), - ev!("", "placedLayerEditContents", "Edit Contents", "layer.smartObjects.editContents", &[]), - ev!("", "updatePlacedLayer", "Update Smart Objects", "layer.smartObjects.updateModifiedContent", &[]), - Event { code: "Hd ", name: "hide", label: "Hide", ids: &["layer.hideLayers"], from: |d| visibility_from(d, "layer.hideLayers"), to: visibility_to }, - Event { code: "Shw ", name: "show", label: "Show", ids: &["layer.showLayers"], from: |d| visibility_from(d, "layer.showLayers"), to: visibility_to }, - Event { - code: "move", - name: "move", - label: "Move", - ids: &["layer.translate", "layer.arrange.bringToFront", "layer.arrange.sendToBack", "layer.arrange.bringForward", "layer.arrange.sendBackward"], - from: move_from, - to: move_to, - }, - ev!("FltI", "flattenImage", "Flatten Image", "layer.flattenImage", &[]), - Event { - code: "MrgV", - name: "mergeVisible", - label: "Merge Visible", - ids: &["layer.mergeVisible", "layer.stampVisible"], - from: merge_visible_from, - to: merge_visible_to, - }, - ev!("Mrg2", "mergeLayersNew", "Merge Layers", "layer.mergeLayers", &[]), - clipping_event!("Ungr", "ungroup", "Release Clipping Mask", "layer.releaseClippingMask"), - ev!("CpTL", "copyToLayer", "Layer Via Copy", "layer.new.layerViaCopy", &[]), - ev!("CtTL", "cutToLayer", "Layer Via Cut", "layer.new.layerViaCut", &[]), - ev!("", "rasterizeLayer", "Rasterize", "layer.rasterize.layer", &[]), - ev!("", "selectAllLayers", "Select All Layers", "select.allLayers", &[]), - ev!("", "selectNoLayers", "Deselect Layers", "select.deselectLayers", &[]), - clipping_event!("GrpL", "groupEvent", "Create Clipping Mask", "layer.createClippingMask"), - ev!("", "ungroupLayersEvent", "Ungroup Layers", "layer.ungroupLayers", &[]), - ev!("", "copyEffects", "Copy Layer Style", "layer.layerStyle.copyLayerStyle", &[]), - ev!("", "pasteEffects", "Paste Layer Style", "layer.layerStyle.pasteLayerStyle", &[]), - Event { - code: "", - name: "collapseAllGroupsEvent", - label: "Collapse All Groups", - ids: &["layer.setExpanded"], - from: |_| step("layer.setExpanded", json!({"all": true, "expanded": false})), - to: |_, p| (jbool(p, "all") == Some(true) && jbool(p, "expanded") == Some(false)).then(|| desc("null")), - }, - ev!("Dfrg", "defringe", "Defringe", "layer.matting.defringe", &[F("Wdth", "width", Kind::Px)]), - Event { - code: "Algn", - name: "align", - label: "Align", - ids: &[ - "layer.align.leftEdges", - "layer.align.horizontalCenters", - "layer.align.rightEdges", - "layer.align.topEdges", - "layer.align.verticalCenters", - "layer.align.bottomEdges", - ], - from: align_from, - to: align_to, - }, - // Selection. - ev!("Invs", "inverse", "Inverse", "select.inverse", &[]), - ev!("Fthr", "feather", "Feather", "select.modify.feather", &[F("Rds ", "radius", Kind::Px)], unless applies_at_canvas_bounds), - ev!("Expn", "expand", "Expand", "select.modify.expand", &[F("By ", "radius", Kind::Px)], unless applies_at_canvas_bounds), - ev!("Cntc", "contract", "Contract", "select.modify.contract", &[F("By ", "radius", Kind::Px)], unless applies_at_canvas_bounds), - ev!("Smth", "smoothness", "Smooth", "select.modify.smooth", &[F("Rds ", "radius", Kind::Px)], unless applies_at_canvas_bounds), - ev!("Brdr", "border", "Border", "select.modify.border", &[F("Wdth", "radius", Kind::Px)]), - ev!("Grow", "grow", "Grow", "select.grow", &[F("Tlrn", "tolerance", Kind::Long)]), - ev!("Smlr", "similar", "Similar", "select.similar", &[F("Tlrn", "tolerance", Kind::Long)]), - // `refineSelectionEdge` has no Sample All Layers, so a step with it exports as - // `smartBrushWorkspace` instead of dropping it. - Event { - code: "", - name: "refineSelectionEdge", - label: "Select and Mask", - ids: &["select.refineEdge"], - from: |d| match fields_from(d, REFINE_EDGE) { - Some(m) => step("select.refineEdge", Value::Object(m)), - None => Mapped::Unsupported { harmless: false }, - }, - to: refine_edge_to, - }, - ev!("", "smartBrushWorkspace", "Select and Mask", "select.refineEdge", SMART_BRUSH, unless has_refine_strokes), - ev!("", "autoCutout", "Select Subject", "select.subject", &[F("sampleAllLayers", "sampleAllLayers", Kind::Bool)]), - Event { code: "ClrR", name: "colorRange", label: "Color Range", ids: &["select.colorRange"], from: color_range_from, to: color_range_to }, - // Edit. - Event { code: "Fl ", name: "fill", label: "Fill", ids: &["edit.fill", "paint.bucket"], from: fill_from, to: fill_to }, - Event { - code: "Strk", - name: "stroke", - label: "Stroke", - ids: &["edit.stroke"], - from: |d| match fields_from(d, STROKE) { - Some(m) => step("edit.stroke", Value::Object(m)), - None => Mapped::Unsupported { harmless: false }, - }, - to: stroke_to, - }, - ev!("copy", "copyEvent", "Copy", "edit.copy", &[]), - ev!("CpyM", "copyMerged", "Copy Merged", "edit.copyMerged", &[]), - ev!("cut ", "cut", "Cut", "edit.cut", &[]), - Event { code: "past", name: "paste", label: "Paste", ids: &["edit.paste", "edit.pasteSpecial.pasteInPlace"], from: paste_from, to: paste_to }, - Event { - code: "Prge", - name: "purge", - label: "Purge", - ids: &["edit.purge.all", "edit.purge.clipboard", "edit.purge.histories", "edit.purge.undo"], - from: purge_from, - to: purge_to, - }, - Event { code: "Rset", name: "reset", label: "Reset", ids: &["tools.defaultColors"], from: reset_from, to: reset_to }, - ev!("Exch", "exchange", "Exchange", "tools.swapColors", &[]), - Event { - code: "", - name: "assignProfile", - label: "Assign Profile", - ids: &["edit.assignProfile"], - from: |d| profile_from(d, "edit.assignProfile"), - to: profile_to, - }, - Event { - code: "", - name: "convertToProfile", - label: "Convert to Profile", - ids: &["edit.convertToProfile"], - from: |d| profile_from(d, "edit.convertToProfile"), - to: profile_to, - }, - // File and actions. - Event { code: "Cls ", name: "close", label: "Close", ids: &["file.close"], from: close_from, to: close_to }, - Event { code: "Expr", name: "export", label: "Export", ids: &["file.export.saveForWebLegacy"], from: export_from, to: export_to }, - Event { code: "Plc ", name: "placeEvent", label: "Place", ids: &["file.placeEmbedded", "file.placeLinked"], from: place_from, to: place_to }, - Event { code: "Opn ", name: "open", label: "Open", ids: &["file.openAs"], from: open_from, to: open_to }, - Event { code: "", name: "conditional", label: "If", ids: &["actions.conditional"], from: conditional_from, to: conditional_to }, - Event { code: "save", name: "save", label: "Save", ids: &["file.save", "file.saveAs", "file.saveACopy"], from: save_from, to: save_to }, - ev!("Rvrt", "revert", "Revert", "file.revert", &[]), - Event { code: "Ply ", name: "play", label: "Play", ids: &["actions.play"], from: play_from, to: play_to }, - Event { code: "", name: "applyComp", label: "Apply Layer Comp", ids: &["layerComp.apply"], from: apply_comp_from, to: apply_comp_to }, - Event { code: "Stop", name: "stop", label: "Stop", ids: &[STOP_MESSAGE], from: stop_from, to: stop_to }, -]; - -/// Four-char codes PhotoCraft once exported for events Photoshop only runs by name (or by -/// another code), with the name they stand for. Measured in Photoshop: `executeAction` with -/// these codes fails ("the command is not currently available"), and `Fltn` is the -/// `flatness` property, not the flatten event. Import keeps accepting them so actions saved -/// before still load; export never writes them. -const LEGACY_CODES: &[(&str, &str)] = - &[("BoxB", "boxblur"), ("SrfB", "surfaceBlur"), ("Fltn", "flattenImage"), ("BlnW", "blackAndWhite"), ("PhtF", "photoFilter")]; - -fn event_for(item: &AtnEvent) -> Option<&'static Event> { - let id = item.id(); - let find = |id: &str| EVENTS.iter().find(|e| (!e.code.is_empty() && e.code.trim_end() == id.trim_end()) || e.name == id); - find(&id).or_else(|| match item { - AtnEvent::Code(_) => LEGACY_CODES.iter().find(|(code, _)| *code == id).and_then(|(_, name)| find(name)), - AtnEvent::Name(_) => None, - }) -} - -/// The event `id` exports as: the first event listing it whose converter accepts the params -/// (Quick Mask on is a `set`, off a `clearEvent`). -fn event_and_descriptor(id: &str, params: &Value) -> Option<(&'static Event, Descriptor)> { - EVENTS.iter().filter(|e| e.ids.contains(&id)).find_map(|e| (e.to)(id, params).map(|d| (e, d))) -} - -// ------------------------------------------------------------------ import - -/// A step with no PhotoCraft equivalent. -#[derive(Clone, Debug, PartialEq, serde::Serialize)] -pub struct Unsupported { - pub action: String, - pub step: usize, - pub event: String, - pub name: String, -} - -/// What a `.atn` file imports to. -#[derive(Clone, Debug, Default)] -pub struct Imported { - pub set: String, - pub actions: Vec, - /// Function keys the file assigns, as `(action name, key)`. - pub function_keys: Vec<(String, String)>, - pub unsupported: Vec, - pub warnings: Vec, -} - -fn photoshop_step(item: &AtnItem) -> (String, Value) { - let descriptor = item.descriptor.as_ref().map(|d| photocraft_paint::tile::b64_encode(&d.to_bytes())); - let event_kind = match &item.event { - AtnEvent::Code(_) => "code", - AtnEvent::Name(_) => "name", - }; - (PHOTOSHOP_STEP.into(), json!({"event": item.event.id(), "eventKind": event_kind, "name": item.label(), "descriptor": descriptor})) -} - -/// Integral floats become integers (`2.0` → `2`), as the commands' own docs and recordings -/// use, so an imported step reads and compares like a recorded one. -fn normalise(v: &mut Value) { - match v { - Value::Number(n) => { - if let Some(f) = n.as_f64() - && f.fract() == 0.0 - && f.abs() < 9.0e15 - && n.as_i64().is_none() - { - *v = Value::from(f as i64); - } - } - Value::Array(a) => a.iter_mut().for_each(normalise), - Value::Object(o) => o.values_mut().for_each(normalise), - _ => {} - } -} - -/// Longest action or set name kept (Photoshop's own limit is 255). A file's names are lengths it -/// chooses, and each is copied into every action and every unsupported-step diagnostic. -const MAX_NAME_CHARS: usize = 1024; - -fn clip_name(s: &str) -> String { - s.chars().take(MAX_NAME_CHARS).collect() -} - -fn convert_action(a: &AtnAction, set: &str, unsupported: &mut Vec) -> Action { - let name = clip_name(&a.name.to_string_lossy()); - let mut action = Action::new(name.clone(), Vec::new()); - action.set = Some(clip_name(set)); - for (i, item) in a.items.iter().enumerate() { - let mapped = match (event_for(&item.event), &item.descriptor) { - (Some(e), Some(d)) => (e.from)(d), - (Some(e), None) => (e.from)(&Descriptor::default()), - (None, _) => Mapped::Unsupported { harmless: false }, - }; - let (new_steps, enabled) = match mapped { - Mapped::Steps(s) => (s, item.enabled), - Mapped::Unsupported { harmless } => { - unsupported.push(Unsupported { action: name.clone(), step: i, event: item.event.id(), name: item.label() }); - (vec![photoshop_step(item)], item.enabled && !harmless) - } - }; - for mut s in new_steps { - normalise(&mut s.1); - let idx = action.steps.len(); - action.steps.push(s); - if !enabled { - action.disabled.insert(idx); - } - if item.with_dialog { - action.dialogs.insert(idx); - } - } - } - action -} - -/// Convert a `.atn` file. Fails only when the file is unreadable: every step imports, as a -/// command or as a kept Photoshop step. -pub fn import(bytes: &[u8]) -> std::result::Result { - let file = atn::parse(bytes).map_err(|e| e.to_string())?; - let set = file.name.to_string_lossy(); - let set = if set.trim().is_empty() { DEFAULT_SET.to_string() } else { clip_name(&set) }; - let mut out = Imported { set: set.clone(), warnings: file.warnings.clone(), ..Default::default() }; - for a in &file.actions { - let action = convert_action(a, &set, &mut out.unsupported); - if a.function_key > 0 { - out.function_keys.push((action.name.clone(), function_key_name(a.function_key, a.shift, a.command))); - } - out.actions.push(action); - } - Ok(out) -} - -// ------------------------------------------------------------------ export - -/// A step Save Actions could not express as a Photoshop event. -#[derive(Clone, Debug, PartialEq, serde::Serialize)] -pub struct Skipped { - pub action: String, - pub step: usize, - pub id: String, -} - -fn export_item(id: &str, params: &Value, set: &str) -> Option { - if id == PHOTOSHOP_STEP { - let event = jstr(params, "event")?; - let event = match params.get("eventKind") { - Some(Value::String(kind)) if kind == "code" => AtnEvent::Code(event.as_bytes().try_into().ok()?), - Some(Value::String(kind)) if kind == "name" => AtnEvent::name(event), - Some(_) => return None, - // Older PhotoCraft action data did not retain the event kind. Keep its previous - // best-effort export behavior for compatibility. - None => match event.as_bytes() { - [a, b, c, d] => AtnEvent::Code([*a, *b, *c, *d]), - _ => AtnEvent::name(event), - }, - }; - let descriptor = match jstr(params, "descriptor") { - Some(b64) => Some(Descriptor::from_bytes(&photocraft_paint::tile::b64_decode(b64)?).ok()?), - None => None, - }; - return Some(AtnItem { event, dictionary: jstr(params, "name").unwrap_or("").as_bytes().to_vec(), descriptor, ..Default::default() }); - } - let mut params = params.clone(); - if (id == "actions.play" || id == "actions.conditional") && params.get("set").is_none() { - params["set"] = json!(set); - } - let (e, descriptor) = event_and_descriptor(id, ¶ms)?; - let event = if e.code.is_empty() { AtnEvent::name(e.name) } else { AtnEvent::Code(e.code.as_bytes().try_into().ok()?) }; - Some(AtnItem { event, dictionary: e.label.as_bytes().to_vec(), descriptor: Some(descriptor), ..Default::default() }) -} - -/// Photoshop applies only the rename when a Set mixes it with opacity or blend mode (#8304). -/// Write each layer property separately, renaming last so named references still resolve. -fn export_items(id: &str, params: &Value, set: &str) -> Option> { - let item = export_item(id, params, set)?; - if id != "layer.setProps" { - return Some(vec![item]); - } - let descriptor = item.descriptor.as_ref()?; - let properties = get_obj(descriptor, "T ")?; - if properties.items.len() <= 1 { - return Some(vec![item]); - } - let target = descriptor.get("null")?; - let mut items = Vec::with_capacity(properties.items.len()); - for (key, value) in properties.items.iter().filter(|(k, _)| !k.is("Nm ")).chain(properties.items.iter().filter(|(k, _)| k.is("Nm "))) { - let mut property = properties.clone(); - property.items = vec![(key.clone(), value.clone())]; - let descriptor = desc("null").with("null", target.clone()).with("T ", D::Descriptor(property)); - items.push(AtnItem { descriptor: Some(descriptor), ..item.clone() }); - } - Some(items) -} - -/// An action's key as a shortcut string: `F5`, with Photoshop's Shift and Command options -/// `Shift+F5`, `Cmd+F5` or `Cmd+Shift+F5` (#7646). -pub fn function_key_name(key: u16, shift: bool, command: bool) -> String { - format!("{}{}F{key}", if command { "Cmd+" } else { "" }, if shift { "Shift+" } else { "" }) -} - -/// The `.atn` function key (1…15), Shift and Command of a shortcut string, or `None` for -/// anything else. -pub fn parse_function_key(key: &str) -> Option<(u16, bool, bool)> { - let (mut shift, mut command) = (false, false); - let mut rest = key; - loop { - if let Some(r) = rest.strip_prefix("Cmd+").filter(|_| !command) { - (command, rest) = (true, r); - } else if let Some(r) = rest.strip_prefix("Shift+").filter(|_| !shift) { - (shift, rest) = (true, r); - } else { - break; - } - } - let n = rest.strip_prefix('F')?.parse::().ok().filter(|n| (1..=15).contains(n))?; - Some((n, shift, command)) -} - -/// The `.atn` bytes of `actions` as the set `set`. `function_keys` gives each action's key -/// (`F1`…`F15`, with `Shift+` and `Cmd+` as [`function_key_name`] writes them). Steps with no Photoshop equivalent are an error unless `skip_unsupported`. -pub fn export( - set: &str, - actions: &[&Action], - function_keys: &[(String, String)], - skip_unsupported: bool, -) -> std::result::Result<(Vec, Vec), String> { - let mut skipped = Vec::new(); - let mut file = AtnFile { name: UnicodeString::new_nul(set), expanded: true, actions: Vec::new(), warnings: Vec::new() }; - for a in actions { - let mut out = AtnAction { name: UnicodeString::new_nul(&a.name), expanded: false, ..Default::default() }; - if let Some((n, shift, command)) = function_keys.iter().find(|(n, _)| n == &a.name).and_then(|(_, key)| parse_function_key(key)) { - (out.function_key, out.shift, out.command) = (n, shift, command); - } - for (i, (id, params)) in a.steps.iter().enumerate() { - let Some(items) = export_items(id, params, set) else { - if skip_unsupported { - skipped.push(Skipped { action: a.name.clone(), step: i, id: id.clone() }); - continue; - } - let step_name = match params.get("layer") { - Some(Value::Number(n)) => format!("`{id}` with numeric layer {n}"), - _ => format!("`{id}`"), - }; - return Err(format!( - "step {} of `{}` ({step_name}) has no Photoshop equivalent; pass \"skipUnsupported\": true to leave it out", - i + 1, - a.name - )); - }; - for mut item in items { - item.enabled = a.step_enabled(i); - item.with_dialog = a.dialogs.contains(&i); - item.dialog_options = if item.with_dialog { 2 } else { 0 }; - out.items.push(item); - } - } - file.actions.push(out); - } - let bytes = atn::write(&file).map_err(|e| e.to_string())?; - Ok((bytes, skipped)) -} - -// ------------------------------------------------------------------ commands - -/// Assigns names not already used, as `name`, `name 2`, `name 3`… A plain linear scan of the -/// taken list per candidate is cubic when an action file repeats one base name many times, so -/// membership uses a set and the next suffix to try is cached per base name. -struct UniqueNames { - taken: std::collections::HashSet, - next_suffix: std::collections::HashMap, -} - -impl UniqueNames { - fn new>(existing: I) -> Self { - UniqueNames { taken: existing.into_iter().collect(), next_suffix: std::collections::HashMap::new() } - } - - /// Reserves and returns a unique name derived from `name`, recording it as taken. - fn claim(&mut self, name: &str) -> String { - if self.taken.insert(name.to_string()) { - return name.to_string(); - } - let mut i = self.next_suffix.get(name).copied().unwrap_or(2); - loop { - let candidate = format!("{name} {i}"); - i += 1; - if self.taken.insert(candidate.clone()) { - self.next_suffix.insert(name.to_string(), i); - return candidate; - } - } - } -} - -fn load(s: &mut Session, p: &Value) -> Result { - let cmd = "actions.load"; - if s.actions.recording.is_some() || s.actions.playing > 0 { - return Err(bad(cmd, "stop recording or playing before loading actions")); - } - let (bytes, _) = crate::preset_import_cmds::file_bytes(p, cmd, ".atn file")?; - let mut imp = import(&bytes).map_err(|e| bad(cmd, e))?; - match p.get("set") { - None | Some(Value::Null) => {} - Some(Value::String(n)) if !n.trim().is_empty() => { - imp.set = n.trim().to_string(); - for a in &mut imp.actions { - a.set = Some(imp.set.clone()); - } - } - Some(_) => return Err(bad(cmd, "`set` must be a non-empty string")), - } - let replace = match p.get("replace") { - None | Some(Value::Null) => true, - Some(Value::Bool(b)) => *b, - Some(_) => return Err(bad(cmd, "`replace` must be true or false")), - }; - if replace { - s.actions.list.retain(|a| a.set.as_deref() != Some(imp.set.as_str())); - } - let mut taken = UniqueNames::new(s.actions.list.iter().map(|a| a.name.clone())); - let mut names = Vec::with_capacity(imp.actions.len()); - // The file's name of each action that had to be renamed, and its new name. - let mut renamed: std::collections::HashMap = std::collections::HashMap::new(); - let mut steps = 0usize; - let mut added = Vec::with_capacity(imp.actions.len()); - for mut a in imp.actions { - let name = taken.claim(&a.name); - if name != a.name { - renamed.entry(a.name.clone()).or_insert_with(|| name.clone()); - } - a.name = name.clone(); - steps = steps.saturating_add(a.steps.len()); - names.push(name); - added.push(a); - } - // Play and Conditional steps call actions by name: follow the renames in the actions just - // loaded, each target looked up once by the name the file gave it. - for a in &mut added { - for (id, params) in &mut a.steps { - let keys: &[&str] = match id.as_str() { - "actions.play" => &["action"], - "actions.conditional" => &["then", "else"], - _ => &[], - }; - for key in keys { - if let Some(to) = params.get(*key).and_then(Value::as_str).and_then(|n| renamed.get(n)) { - params[*key] = json!(to); - } - } - } - } - s.actions.list.extend(added); - let keys: Vec<(String, String)> = imp.function_keys.into_iter().map(|(n, k)| (renamed.get(&n).cloned().unwrap_or(n), k)).collect(); - if !keys.is_empty() { - s.edit_prefs(|prefs| { - for (name, key) in &keys { - // A function key belongs to one action. - prefs.shortcuts.retain(|k, v| !(k.starts_with(crate::actions_cmds::PLAY_SHORTCUT_PREFIX) && v == key)); - prefs.shortcuts.insert(format!("{}{name}", crate::actions_cmds::PLAY_SHORTCUT_PREFIX), key.clone()); - } - }); - } - s.actions.touch(); - Ok(json!({ - "set": imp.set, - "actions": names, - "steps": steps, - "unsupported": imp.unsupported, - "functionKeys": keys.iter().map(|(n, k)| json!({"action": n, "key": k})).collect::>(), - "warnings": imp.warnings, - })) -} - -fn save(s: &mut Session, p: &Value) -> Result { - let cmd = "actions.save"; - crate::actions_cmds::flush_recording(s)?; - let skip = match p.get("skipUnsupported") { - None | Some(Value::Null) => false, - Some(Value::Bool(b)) => *b, - Some(_) => return Err(bad(cmd, "`skipUnsupported` must be true or false")), - }; - let set_param = match p.get("set") { - None | Some(Value::Null) => None, - Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), - Some(_) => return Err(bad(cmd, "`set` must be a non-empty string")), - }; - let (set, actions): (String, Vec<&Action>) = if p.get("action").is_some() { - let idx = crate::actions_cmds::resolve(&s.actions.list, p, cmd)?; - let a = &s.actions.list[idx]; - (set_param.or_else(|| a.set.clone()).unwrap_or_else(|| a.name.clone()), vec![a]) - } else if let Some(set) = set_param { - let list: Vec<&Action> = s.actions.list.iter().filter(|a| a.set.as_deref() == Some(set.as_str())).collect(); - if list.is_empty() { - return Err(bad(cmd, format!("no actions in a set named `{set}`"))); - } - (set, list) - } else { - (DEFAULT_SET.to_string(), s.actions.list.iter().collect()) - }; - if actions.is_empty() { - return Err(bad(cmd, "there are no actions to save")); - } - let names: Vec = actions.iter().map(|a| a.name.clone()).collect(); - let keys: Vec<(String, String)> = - s.prefs().shortcuts.iter().filter_map(|(k, v)| k.strip_prefix(crate::actions_cmds::PLAY_SHORTCUT_PREFIX).map(|n| (n.to_string(), v.clone()))).collect(); - let (bytes, skipped) = export(&set, &actions, &keys, skip).map_err(|e| bad(cmd, e))?; - let steps: usize = actions.iter().map(|a| a.steps.len()).sum::().saturating_sub(skipped.len()); - let mut out = json!({"set": set, "actions": names, "steps": steps, "bytes": bytes.len(), "skipped": skipped}); - match p.get("path") { - None | Some(Value::Null) => { - out["data"] = json!(photocraft_paint::tile::b64_encode(&bytes)); - } - Some(Value::String(path)) if !path.trim().is_empty() => { - write_file(path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; - out["path"] = json!(path); - } - Some(_) => return Err(bad(cmd, "`path` must be a non-empty string")), - } - Ok(out) -} - -#[cfg(not(target_arch = "wasm32"))] -fn write_file(path: &str, bytes: &[u8]) -> std::io::Result<()> { - // Atomic replacement (temporary file + rename): a failed write keeps the previous ATN (#7290). - photocraft_format::atomic_write(std::path::Path::new(path), bytes) -} - -#[cfg(target_arch = "wasm32")] -fn write_file(path: &str, _bytes: &[u8]) -> std::io::Result<()> { - Err(std::io::Error::other(format!("cannot write paths on the web ({path}); omit `path` to get the bytes back as `data`"))) -} - fn stop_message(_: &mut Session, p: &Value) -> Result { let message = jstr(p, "message").unwrap_or("Stop").to_string(); if jbool(p, "allowContinue").unwrap_or(false) { diff --git a/crates/engine/src/atn_cmds/adjustments.rs b/crates/engine/src/atn_cmds/adjustments.rs new file mode 100644 index 0000000000..321ca5ebc4 --- /dev/null +++ b/crates/engine/src/atn_cmds/adjustments.rs @@ -0,0 +1,515 @@ +use super::descriptors::{color_desc, color_hex, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, jbool, jnum, jstr, long, num, pct, text}; +use super::fields::{F, Kind, Mapped, fields_from, fields_to, step}; +use super::tables::{CHANNELS, channel_key, channel_ref, lookup, lookup_back}; +use super::*; + +// ------------------------------------------------------------------ adjustments + +/// The `Adjs` entries of a per-channel adjustment (Levels, Curves): `(channel key, entry)`. +fn per_channel(d: &Descriptor) -> Option, &Descriptor)>> { + get_list(d, "Adjs")? + .iter() + .map(|v| match v { + D::Descriptor(e) => Some((channel_key(e)?, e)), + _ => None, + }) + .collect() +} + +pub(super) fn levels_from(d: &Descriptor) -> Option { + if get_bool(d, "Auto") == Some(true) { + return None; + } + let mut out = Map::new(); + for (chan, e) in per_channel(d)? { + let mut m = Map::new(); + if let Some(i) = get_list(e, "Inpt") { + if let Some(v) = i.first().and_then(num) { + m.insert("inBlack".into(), v.into()); + } + if let Some(v) = i.get(1).and_then(num) { + m.insert("inWhite".into(), v.into()); + } + } + if let Some(o) = get_list(e, "Otpt") { + if let Some(v) = o.first().and_then(num) { + m.insert("outBlack".into(), v.into()); + } + if let Some(v) = o.get(1).and_then(num) { + m.insert("outWhite".into(), v.into()); + } + } + if let Some(g) = get_num(e, "Gmm ") { + m.insert("gamma".into(), g.into()); + } + match chan { + None => out.extend(m), + Some(k) => { + out.insert(k.into(), Value::Object(m)); + } + } + } + Some(Value::Object(out)) +} + +fn levels_entry(chan: Option<&str>, p: &Value) -> Descriptor { + let mut e = desc("LvlA").with("Chnl", channel_ref(chan)); + if jnum(p, "inBlack").is_some() || jnum(p, "inWhite").is_some() { + e = e.with("Inpt", D::List(vec![long(jnum(p, "inBlack").unwrap_or(0.0)), long(jnum(p, "inWhite").unwrap_or(255.0))])); + } + if let Some(g) = jnum(p, "gamma") { + e = e.with("Gmm ", D::Double(g)); + } + if jnum(p, "outBlack").is_some() || jnum(p, "outWhite").is_some() { + e = e.with("Otpt", D::List(vec![long(jnum(p, "outBlack").unwrap_or(0.0)), long(jnum(p, "outWhite").unwrap_or(255.0))])); + } + e +} + +pub(super) fn levels_to(p: &Value) -> Option { + let mut entries = vec![D::Descriptor(levels_entry(None, p))]; + for (_, k) in CHANNELS { + if let Some(c) = p.get(*k).filter(|v| v.is_object()) { + entries.push(D::Descriptor(levels_entry(Some(k), c))); + } + } + Some(desc("Lvls").with("presetKind", enm("presetKindType", "presetKindCustom")).with("Adjs", D::List(entries))) +} + +fn curve_points(e: &Descriptor) -> Option { + let pts: Option> = get_list(e, "Crv ")? + .iter() + .map(|v| match v { + D::Descriptor(pt) => Some(json!([get_num(pt, "Hrzn")?, get_num(pt, "Vrtc")?])), + _ => None, + }) + .collect(); + pts.map(Value::Array) +} + +fn curves_from(d: &Descriptor) -> Option { + let mut out = Map::new(); + for (chan, e) in per_channel(d)? { + let pts = curve_points(e)?; + out.insert(chan.unwrap_or("points").into(), pts); + } + Some(Value::Object(out)) +} + +fn curve_entry(chan: Option<&str>, pts: &Value) -> Option { + let list: Option> = pts + .as_array()? + .iter() + .map(|pt| { + let a = pt.as_array()?; + Some(D::Descriptor(desc("Pnt ").with("Hrzn", D::Double(a.first()?.as_f64()?)).with("Vrtc", D::Double(a.get(1)?.as_f64()?)))) + }) + .collect(); + Some(desc("CrvA").with("Chnl", channel_ref(chan)).with("Crv ", D::List(list?))) +} + +fn curves_to(p: &Value) -> Option { + let mut entries = Vec::new(); + if let Some(pts) = p.get("points") { + entries.push(D::Descriptor(curve_entry(None, pts)?)); + } + for (_, k) in CHANNELS { + if let Some(pts) = p.get(*k) { + entries.push(D::Descriptor(curve_entry(Some(k), pts)?)); + } + } + Some(desc("Crvs").with("presetKind", enm("presetKindType", "presetKindCustom")).with("Adjs", D::List(entries))) +} + +/// The hue key of a Hue/Saturation adjustment (`Hst2`): Photoshop's `H ` (#8302). +const HUE_KEY: &str = "H "; + +pub(super) const HUE_RANGES: [&str; 6] = ["reds", "yellows", "greens", "cyans", "blues", "magentas"]; + +fn hue_sat_from(d: &Descriptor) -> Option { + let mut out = Map::new(); + if let Some(c) = get_bool(d, "Clrz") { + out.insert("colorize".into(), c.into()); + } + for e in get_list(d, "Adjs").unwrap_or(&[]) { + let D::Descriptor(e) = e else { return None }; + let mut m = Map::new(); + // Photoshop's hue key is `H ` (stringID "hue", #8302); PhotoCraft wrote `Hue ` before, + // so its own older files still read. + let hue = get_num(e, HUE_KEY).or_else(|| get_num(e, "Hue ")); + for (param, v) in [("hue", hue), ("saturation", get_num(e, "Strt")), ("lightness", get_num(e, "Lght"))] { + if let Some(v) = v { + m.insert(param.into(), v.into()); + } + } + match get_num(e, "LclR") { + None => out.extend(m), + Some(r) => { + let name = *HUE_RANGES.get((r as usize).checked_sub(1)?)?; + if let (Some(a), Some(b), Some(c), Some(dd)) = (get_num(e, "BgnR"), get_num(e, "BgnS"), get_num(e, "EndS"), get_num(e, "EndR")) { + m.insert("range".into(), json!([a, b, c, dd])); + } + out.insert(name.into(), Value::Object(m)); + } + } + } + Some(Value::Object(out)) +} + +fn hue_entry(p: &Value, range: Option<(usize, &Value)>) -> Option { + let mut e = desc("Hst2"); + if let Some((i, r)) = range { + e = e.with("LclR", long(i as f64 + 1.0)); + if let Some(a) = r.get("range").and_then(Value::as_array) + && a.len() == 4 + { + for (k, v) in ["BgnR", "BgnS", "EndS", "EndR"].iter().zip(a) { + e = e.with(k, long(v.as_f64()?)); + } + } + } + for (key, param) in [(HUE_KEY, "hue"), ("Strt", "saturation"), ("Lght", "lightness")] { + e = e.with(key, long(jnum(p, param).unwrap_or(0.0))); + } + Some(e) +} + +// Exporters leave out a param the step doesn't set only where Photoshop plays the missing key +// as PhotoCraft's default (checked against Photoshop: Fill opacity and mode, Crop delete, +// Selective Color method, Channel Mixer monochrome, Paint Bucket contiguous; Gradient Map +// reverse and dither, which Photoshop itself leaves out when off). Elsewhere they +// write PhotoCraft's default, as Photoshop plays a missing key differently (Color Balance +// preserve luminosity off, Canvas Size anchored top left, Apply Image Normal) or refuses the +// step (Paint Bucket without a tolerance). +fn hue_sat_to(p: &Value) -> Option { + let d = desc("HStr").with("presetKind", enm("presetKindType", "presetKindCustom")).with("Clrz", D::Boolean(jbool(p, "colorize").unwrap_or(false))); + let mut entries = vec![D::Descriptor(hue_entry(p, None)?)]; + for (i, name) in HUE_RANGES.iter().enumerate() { + if let Some(r) = p.get(*name).filter(|v| v.is_object()) { + entries.push(D::Descriptor(hue_entry(r, Some((i, r)))?)); + } + } + Some(d.with("Adjs", D::List(entries))) +} + +fn triple(d: &Descriptor, k: &str) -> Option { + let l = get_list(d, k)?; + let v: Option> = l.iter().map(num).collect(); + Some(json!(v?)) +} + +fn triple_to(p: &Value, k: &str) -> Option { + Some(D::List(p.get(k)?.as_array()?.iter().map(|v| v.as_f64().map(long)).collect::>>()?)) +} + +fn color_balance_from(d: &Descriptor) -> Option { + let mut out = Map::new(); + for (key, param) in [("ShdL", "shadows"), ("MdtL", "midtones"), ("HghL", "highlights")] { + if let Some(v) = triple(d, key) { + out.insert(param.into(), v); + } + } + if let Some(b) = get_bool(d, "PrsL") { + out.insert("preserveLuminosity".into(), b.into()); + } + Some(Value::Object(out)) +} + +fn color_balance_to(p: &Value) -> Option { + let mut d = desc("ClrB"); + for (key, param) in [("ShdL", "shadows"), ("MdtL", "midtones"), ("HghL", "highlights")] { + d = d.with(key, triple_to(p, param).unwrap_or_else(|| D::List(vec![long(0.0), long(0.0), long(0.0)]))); + } + Some(d.with("PrsL", D::Boolean(jbool(p, "preserveLuminosity").unwrap_or(true)))) +} + +const BW: &[F] = &[ + F("Rd ", "reds", Kind::Long), + F("Yllw", "yellows", Kind::Long), + F("Grn ", "greens", Kind::Long), + F("Cyn ", "cyans", Kind::Long), + F("Bl ", "blues", Kind::Long), + F("Mgnt", "magentas", Kind::Long), + F("useTint", "tint", Kind::Bool), + F("tintColor", "tintColor", Kind::Color), +]; + +fn mixer_channel(e: &Descriptor) -> Option { + Some(json!([get_num(e, "Rd ").unwrap_or(0.0), get_num(e, "Grn ").unwrap_or(0.0), get_num(e, "Bl ").unwrap_or(0.0), get_num(e, "Cnst").unwrap_or(0.0)])) +} + +fn channel_mixer_from(d: &Descriptor) -> Option { + let mut out = Map::new(); + for (key, param) in [("Rd ", "red"), ("Grn ", "green"), ("Bl ", "blue"), ("Gry ", "gray")] { + if let Some(e) = get_obj(d, key) { + out.insert(param.into(), mixer_channel(e)?); + } + } + if let Some(m) = get_bool(d, "Mnch") { + out.insert("monochrome".into(), m.into()); + } + Some(Value::Object(out)) +} + +fn channel_mixer_to(p: &Value) -> Option { + let mut d = desc("ChnM").with("presetKind", enm("presetKindType", "presetKindCustom")); + for (key, param) in [("Rd ", "red"), ("Grn ", "green"), ("Bl ", "blue"), ("Gry ", "gray")] { + if let Some(a) = p.get(param).and_then(Value::as_array) { + let v = |i: usize| a.get(i).and_then(Value::as_f64).unwrap_or(0.0); + d = d.with(key, D::Descriptor(desc("ChMx").with("Rd ", pct(v(0))).with("Grn ", pct(v(1))).with("Bl ", pct(v(2))).with("Cnst", pct(v(3))))); + } + } + if let Some(m) = jbool(p, "monochrome") { + d = d.with("Mnch", D::Boolean(m)); + } + Some(d) +} + +/// Photoshop's `Clrs` colour-range enumeration. Yellows is `Ylws` (`Yllw` is the yellow ink +/// key); earlier PhotoCraft builds wrote `Yllw`, which import still reads (#6745). +const SELECTIVE_RANGES: &[(&str, &str)] = &[ + ("Rds", "reds"), + ("Ylws", "yellows"), + ("Grns", "greens"), + ("Cyns", "cyans"), + ("Bls", "blues"), + ("Mgnt", "magentas"), + ("Whts", "whites"), + ("Ntrl", "neutrals"), + ("Blks", "blacks"), +]; + +pub(super) fn selective_from(d: &Descriptor) -> Option { + let mut out = Map::new(); + if let Some(m) = get_enum(d, "Mthd") { + out.insert("method".into(), (if m == "Absl" { "absolute" } else { "relative" }).into()); + } + for e in get_list(d, "ClrC").unwrap_or(&[]) { + let D::Descriptor(e) = e else { return None }; + let range = get_enum(e, "Clrs")?; + let name = lookup(SELECTIVE_RANGES, if range == "Yllw" { "Ylws" } else { &range })?; + let v = |k: &str| get_num(e, k).unwrap_or(0.0); + out.insert(name.into(), json!([v("Cyn "), v("Mgnt"), v("Yllw"), v("Blck")])); + } + Some(Value::Object(out)) +} + +fn selective_to(p: &Value) -> Option { + // Match command execution: scalar components override only the selected range, `relative` + // takes precedence over `method`, and invalid values must not become a different edit. + let photocraft_doc::Adjustment::SelectiveColor { relative, adjustments } = crate::adjust_cmds::selective_from_params(p, None).ok()? else { + return None; + }; + let mut list = Vec::new(); + for (name, row) in crate::adjust_cmds::RANGES.into_iter().zip(adjustments) { + if p.get(name).is_some_and(|v| !v.is_null()) || jstr(p, "colors") == Some(name) { + let ps = lookup_back(SELECTIVE_RANGES, name)?; + let [cyan, magenta, yellow, black] = row.map(f64::from); + list.push(D::Descriptor( + desc("ClrC") + .with("Clrs", enm("Clrs", ps)) + .with("Cyn ", pct(cyan)) + .with("Mgnt", pct(magenta)) + .with("Yllw", pct(yellow)) + .with("Blck", pct(black)), + )); + } + } + Some( + desc("SlcC") + .with("presetKind", enm("presetKindType", "presetKindCustom")) + .with("Mthd", enm("CrcM", if relative { "Rltv" } else { "Absl" })) + .with("ClrC", D::List(list)), + ) +} + +/// Gradient Map: the gradient's colour stops at 0..4096 → `stops: [[0..1, "#rrggbb"], …]`. +fn gradient_map_from(d: &Descriptor) -> Option { + let grad = get_obj(d, "Grad")?; + let stops: Option> = get_list(grad, "Clrs")? + .iter() + .map(|v| match v { + D::Descriptor(stop) => Some(json!([(get_num(stop, "Lctn")? / 4096.0).clamp(0.0, 1.0), color_hex(get_obj(stop, "Clr ")?)?])), + _ => None, + }) + .collect(); + let mut out = json!({"stops": stops?}); + if let Some(r) = get_bool(d, "Rvrs") { + out["reverse"] = json!(r); + } + if let Some(dd) = get_bool(d, "Dthr") { + out["dither"] = json!(dd); + } + Some(out) +} + +fn gradient_map_to(p: &Value) -> Option { + let stops: Option> = p + .get("stops")? + .as_array()? + .iter() + .map(|st| { + let a = st.as_array()?; + Some(D::Descriptor( + desc("Clrt") + .with("Clr ", D::Descriptor(color_desc(a.get(1)?.as_str()?)?)) + .with("Type", enm("Clry", "UsrS")) + .with("Lctn", long((a.first()?.as_f64()? * 4096.0).round())) + .with("Mdpn", long(50.0)), + )) + }) + .collect(); + let transparency = D::List(vec![ + D::Descriptor(desc("TrnS").with("Opct", pct(100.0)).with("Lctn", long(0.0)).with("Mdpn", long(50.0))), + D::Descriptor(desc("TrnS").with("Opct", pct(100.0)).with("Lctn", long(4096.0)).with("Mdpn", long(50.0))), + ]); + let grad = desc("Grdn") + .with("Nm ", text("Custom")) + .with("GrdF", enm("GrdF", "CstS")) + .with("Intr", D::Double(4096.0)) + .with("Clrs", D::List(stops?)) + .with("Trns", transparency); + let mut d = desc("GdMp").with("Grad", D::Descriptor(grad)); + if let Some(r) = jbool(p, "reverse") { + d = d.with("Rvrs", D::Boolean(r)); + } + if let Some(dd) = jbool(p, "dither") { + d = d.with("Dthr", D::Boolean(dd)); + } + Some(d) +} + +/// An adjustment: its Photoshop class (usually also the direct event's code; Black & White and +/// Photo Filter run by name), the command suffix (`image.adjustments.`, `layer.newAdjustmentLayer.`), and +/// the converters between the adjustment descriptor and the command params. +pub(super) struct Adjustment { + pub(super) class: &'static str, + pub(super) suffix: &'static str, + pub(super) from: fn(&Descriptor) -> Option, + pub(super) to: fn(&Value) -> Option, +} + +macro_rules! adj_fields { + ($class:literal, $suffix:literal, $fields:expr) => { + Adjustment { class: $class, suffix: $suffix, from: |d| fields_from(d, $fields).map(Value::Object), to: |p| fields_to(p, $fields, desc($class)) } + }; +} + +const ADJUSTMENTS: &[Adjustment] = &[ + Adjustment { class: "Lvls", suffix: "levels", from: levels_from, to: levels_to }, + Adjustment { class: "Crvs", suffix: "curves", from: curves_from, to: curves_to }, + Adjustment { class: "HStr", suffix: "hueSaturation", from: hue_sat_from, to: hue_sat_to }, + adj_fields!("BrgC", "brightnessContrast", &[F("Brgh", "brightness", Kind::Long), F("Cntr", "contrast", Kind::Long), F("useLegacy", "legacy", Kind::Bool)]), + adj_fields!("Thrs", "threshold", &[F("Lvl ", "level", Kind::Long)]), + adj_fields!("Pstr", "posterize", &[F("Lvls", "levels", Kind::Long)]), + adj_fields!("Invr", "invert", &[]), + Adjustment { class: "ClrB", suffix: "colorBalance", from: color_balance_from, to: color_balance_to }, + adj_fields!("Vbrn", "vibrance", &[F("vibrance", "vibrance", Kind::Long), F("Strt", "saturation", Kind::Long)]), + adj_fields!("Exps", "exposure", &[F("Exps", "exposure", Kind::Dbl), F("Ofst", "offset", Kind::Dbl), F("gammaCorrection", "gamma", Kind::Dbl)]), + Adjustment { class: "PhtF", suffix: "photoFilter", from: |d| fields_from(d, PHOTO_FILTER_FIELDS).map(Value::Object), to: photo_filter_to }, + adj_fields!("BanW", "blackWhite", BW), + Adjustment { class: "ChnM", suffix: "channelMixer", from: channel_mixer_from, to: channel_mixer_to }, + Adjustment { class: "SlcC", suffix: "selectiveColor", from: selective_from, to: selective_to }, + Adjustment { class: "GdMp", suffix: "gradientMap", from: gradient_map_from, to: gradient_map_to }, +]; + +/// Adjustment classes PhotoCraft once exported, with the class Photoshop uses. Measured in +/// Photoshop (#8481): a Make whose Black & White type is `BlnW` fails ("the command Make is not +/// currently available"), `BanW` runs. Import keeps accepting them so actions saved before still +/// load; export never writes them. +const LEGACY_CLASSES: &[(&str, &str)] = &[("BlnW", "BanW")]; + +/// The adjustment with Photoshop class `c`, or the one an old PhotoCraft class stands for. +pub(super) fn adjustment_by_class(c: &str) -> Option<&'static Adjustment> { + let c = c.trim_end(); + let c = LEGACY_CLASSES.iter().find(|(old, _)| *old == c).map_or(c, |(_, class)| class); + ADJUSTMENTS.iter().find(|a| a.class.trim_end() == c) +} + +const PHOTO_FILTER_FIELDS: &[F] = &[F("Clr ", "color", Kind::Color), F("Dnst", "density", Kind::Long), F("PrsL", "preserveLuminosity", Kind::Bool)]; + +/// A `PhtF` step whose params carry a `filter` preset without an explicit `color`: the descriptor +/// form is colour-only (Photoshop stores no preset key — the `phfl` notes in `crates/io` conclude +/// the same from its CS2 oracles), so the resolved colour must be written, or re-imported playback +/// falls back to the default warming filter. With both present, the explicit colour wins, as when +/// running the command. An unknown preset id keeps the old export (no colour) instead of failing. +fn photo_filter_to(p: &Value) -> Option { + let mut p = p.clone(); + if p.get("color").is_none() { + let hex = p.get("filter").and_then(Value::as_str).and_then(preset_color); + if let (Some(hex), Some(o)) = (hex, p.as_object_mut()) { + o.insert("color".into(), hex.into()); + } + } + fields_to(&p, PHOTO_FILTER_FIELDS, desc("PhtF")) +} + +/// The preset id's resolved `#rrggbb`, or none (no id given, or an unknown one). +fn preset_color(id: &str) -> Option { + crate::adjust_params::PHOTO_FILTERS.iter().find(|f| f.0 == id).map(|(_, _, rgb)| format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])) +} + +pub(super) fn adjustment_by_suffix(suffix: &str) -> Option<&'static Adjustment> { + ADJUSTMENTS.iter().find(|a| a.suffix == suffix) +} + +// Events whose target depends on the descriptor (`make`, `set`, `select`…): custom converters. + +pub(super) fn adjustment_steps(a: &Adjustment, prefix: &str, type_desc: Option<&Descriptor>) -> Mapped { + let params = match type_desc { + Some(t) if get_enum(t, "presetKind").as_deref() != Some("presetKindDefault") => match (a.from)(t) { + Some(p) => p, + None => return Mapped::Unsupported { harmless: false }, + }, + _ => json!({}), + }; + step(&format!("{prefix}{}", a.suffix), params) +} + +/// Shadows/Highlights (`adaptCorrect`, #5830): the shadow and highlight tones are `shadowMode` +/// and `highlightMode` objects (amount and width in %, radius in px), then the black and white +/// clips (%), midtone contrast (`center`) and colour correction. Each key is read as its char ID +/// or its string ID, whichever the file used; absent keys keep the command's defaults. +const SHADOWS_HIGHLIGHTS_TONES: [(&str, &str, &str); 2] = [("sdwM", "shadowMode", "shadow"), ("hglM", "highlightMode", "highlight")]; + +const SHADOWS_HIGHLIGHTS_TONE: [(&str, &str, &str); 3] = [("Amnt", "amount", "Amount"), ("Wdth", "width", "Tone"), ("Rds ", "radius", "Radius")]; + +const SHADOWS_HIGHLIGHTS: [(&str, &str, &str); 4] = + [("BlcC", "blackClip", "blackClip"), ("WhtC", "whiteClip", "whiteClip"), ("Cntr", "center", "midtone"), ("ClrC", "colorCorrection", "color")]; + +pub(super) fn shadows_highlights_from(d: &Descriptor) -> Mapped { + let mut m = Map::new(); + for (code, name, prefix) in SHADOWS_HIGHLIGHTS_TONES { + let Some(t) = get_obj(d, code).or_else(|| get_obj(d, name)) else { continue }; + for (code, name, suffix) in SHADOWS_HIGHLIGHTS_TONE { + if let Some(v) = get_num(t, code).or_else(|| get_num(t, name)) { + m.insert(format!("{prefix}{suffix}"), Value::from(v)); + } + } + } + for (code, name, param) in SHADOWS_HIGHLIGHTS { + if let Some(v) = get_num(d, code).or_else(|| get_num(d, name)) { + m.insert(param.into(), Value::from(v)); + } + } + step("image.adjustments.shadowsHighlights", Value::Object(m)) +} + +pub(super) fn shadows_highlights_to(_: &str, p: &Value) -> Option { + let mut d = desc("null"); + for (_, name, prefix) in SHADOWS_HIGHLIGHTS_TONES { + let mut t = desc("adaptCorrectTones"); + for (_, key, suffix) in SHADOWS_HIGHLIGHTS_TONE { + if let Some(v) = jnum(p, &format!("{prefix}{suffix}")) { + t = t.with(key, if suffix == "Radius" { long(v) } else { pct(v) }); + } + } + d = d.with(name, D::Descriptor(t)); + } + for (_, key, param) in SHADOWS_HIGHLIGHTS { + if let Some(v) = jnum(p, param) { + d = d.with(key, if matches!(param, "midtone" | "color") { long(v) } else { D::Double(v) }); + } + } + Some(d) +} diff --git a/crates/engine/src/atn_cmds/convert.rs b/crates/engine/src/atn_cmds/convert.rs new file mode 100644 index 0000000000..b23c578ac6 --- /dev/null +++ b/crates/engine/src/atn_cmds/convert.rs @@ -0,0 +1,273 @@ +use super::descriptors::{desc, get_obj, jstr}; +use super::events::{event_and_descriptor, event_for}; +use super::fields::Mapped; +use super::*; + +// ------------------------------------------------------------------ import + +/// A step with no PhotoCraft equivalent. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +pub struct Unsupported { + pub action: String, + pub step: usize, + pub event: String, + pub name: String, +} + +/// What a `.atn` file imports to. +#[derive(Clone, Debug, Default)] +pub struct Imported { + pub set: String, + pub actions: Vec, + /// Function keys the file assigns, as `(action name, key)`. + pub function_keys: Vec<(String, String)>, + pub unsupported: Vec, + pub warnings: Vec, +} + +fn photoshop_step(item: &AtnItem) -> (String, Value) { + let descriptor = item.descriptor.as_ref().map(|d| photocraft_paint::tile::b64_encode(&d.to_bytes())); + let event_kind = match &item.event { + AtnEvent::Code(_) => "code", + AtnEvent::Name(_) => "name", + }; + (PHOTOSHOP_STEP.into(), json!({"event": item.event.id(), "eventKind": event_kind, "name": item.label(), "descriptor": descriptor})) +} + +/// Integral floats become integers (`2.0` → `2`), as the commands' own docs and recordings +/// use, so an imported step reads and compares like a recorded one. +pub(super) fn normalise(v: &mut Value) { + match v { + Value::Number(n) => { + if let Some(f) = n.as_f64() + && f.fract() == 0.0 + && f.abs() < 9.0e15 + && n.as_i64().is_none() + { + *v = Value::from(f as i64); + } + } + Value::Array(a) => a.iter_mut().for_each(normalise), + Value::Object(o) => o.values_mut().for_each(normalise), + _ => {} + } +} + +/// Longest action or set name kept (Photoshop's own limit is 255). A file's names are lengths it +/// chooses, and each is copied into every action and every unsupported-step diagnostic. +pub(super) const MAX_NAME_CHARS: usize = 1024; + +pub(super) fn clip_name(s: &str) -> String { + s.chars().take(MAX_NAME_CHARS).collect() +} + +fn convert_action(a: &AtnAction, set: &str, unsupported: &mut Vec) -> Action { + let name = clip_name(&a.name.to_string_lossy()); + let mut action = Action::new(name.clone(), Vec::new()); + action.set = Some(clip_name(set)); + for (i, item) in a.items.iter().enumerate() { + let mapped = match (event_for(&item.event), &item.descriptor) { + (Some(e), Some(d)) => (e.from)(d), + (Some(e), None) => (e.from)(&Descriptor::default()), + (None, _) => Mapped::Unsupported { harmless: false }, + }; + let (new_steps, enabled) = match mapped { + Mapped::Steps(s) => (s, item.enabled), + Mapped::Unsupported { harmless } => { + unsupported.push(Unsupported { action: name.clone(), step: i, event: item.event.id(), name: item.label() }); + (vec![photoshop_step(item)], item.enabled && !harmless) + } + }; + for mut s in new_steps { + normalise(&mut s.1); + let idx = action.steps.len(); + action.steps.push(s); + if !enabled { + action.disabled.insert(idx); + } + if item.with_dialog { + action.dialogs.insert(idx); + } + } + } + action +} + +/// Convert a `.atn` file. Fails only when the file is unreadable: every step imports, as a +/// command or as a kept Photoshop step. +pub fn import(bytes: &[u8]) -> std::result::Result { + let file = atn::parse(bytes).map_err(|e| e.to_string())?; + let set = file.name.to_string_lossy(); + let set = if set.trim().is_empty() { DEFAULT_SET.to_string() } else { clip_name(&set) }; + let mut out = Imported { set: set.clone(), warnings: file.warnings.clone(), ..Default::default() }; + for a in &file.actions { + let action = convert_action(a, &set, &mut out.unsupported); + if a.function_key > 0 { + out.function_keys.push((action.name.clone(), function_key_name(a.function_key, a.shift, a.command))); + } + out.actions.push(action); + } + Ok(out) +} + +// ------------------------------------------------------------------ export + +/// A step Save Actions could not express as a Photoshop event. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +pub struct Skipped { + pub action: String, + pub step: usize, + pub id: String, +} + +pub(super) fn export_item(id: &str, params: &Value, set: &str) -> Option { + if id == PHOTOSHOP_STEP { + let event = jstr(params, "event")?; + let event = match params.get("eventKind") { + Some(Value::String(kind)) if kind == "code" => AtnEvent::Code(event.as_bytes().try_into().ok()?), + Some(Value::String(kind)) if kind == "name" => AtnEvent::name(event), + Some(_) => return None, + // Older PhotoCraft action data did not retain the event kind. Keep its previous + // best-effort export behavior for compatibility. + None => match event.as_bytes() { + [a, b, c, d] => AtnEvent::Code([*a, *b, *c, *d]), + _ => AtnEvent::name(event), + }, + }; + let descriptor = match jstr(params, "descriptor") { + Some(b64) => Some(Descriptor::from_bytes(&photocraft_paint::tile::b64_decode(b64)?).ok()?), + None => None, + }; + return Some(AtnItem { event, dictionary: jstr(params, "name").unwrap_or("").as_bytes().to_vec(), descriptor, ..Default::default() }); + } + let mut params = params.clone(); + if (id == "actions.play" || id == "actions.conditional") && params.get("set").is_none() { + params["set"] = json!(set); + } + let (e, descriptor) = event_and_descriptor(id, ¶ms)?; + let event = if e.code.is_empty() { AtnEvent::name(e.name) } else { AtnEvent::Code(e.code.as_bytes().try_into().ok()?) }; + Some(AtnItem { event, dictionary: e.label.as_bytes().to_vec(), descriptor: Some(descriptor), ..Default::default() }) +} + +/// Photoshop applies only the rename when a Set mixes it with opacity or blend mode (#8304). +/// Write each layer property separately, renaming last so named references still resolve. +fn export_items(id: &str, params: &Value, set: &str) -> Option> { + let item = export_item(id, params, set)?; + if id != "layer.setProps" { + return Some(vec![item]); + } + let descriptor = item.descriptor.as_ref()?; + let properties = get_obj(descriptor, "T ")?; + if properties.items.len() <= 1 { + return Some(vec![item]); + } + let target = descriptor.get("null")?; + let mut items = Vec::with_capacity(properties.items.len()); + for (key, value) in properties.items.iter().filter(|(k, _)| !k.is("Nm ")).chain(properties.items.iter().filter(|(k, _)| k.is("Nm "))) { + let mut property = properties.clone(); + property.items = vec![(key.clone(), value.clone())]; + let descriptor = desc("null").with("null", target.clone()).with("T ", D::Descriptor(property)); + items.push(AtnItem { descriptor: Some(descriptor), ..item.clone() }); + } + Some(items) +} + +/// An action's key as a shortcut string: `F5`, with Photoshop's Shift and Command options +/// `Shift+F5`, `Cmd+F5` or `Cmd+Shift+F5` (#7646). +pub fn function_key_name(key: u16, shift: bool, command: bool) -> String { + format!("{}{}F{key}", if command { "Cmd+" } else { "" }, if shift { "Shift+" } else { "" }) +} + +/// The `.atn` function key (1…15), Shift and Command of a shortcut string, or `None` for +/// anything else. +pub fn parse_function_key(key: &str) -> Option<(u16, bool, bool)> { + let (mut shift, mut command) = (false, false); + let mut rest = key; + loop { + if let Some(r) = rest.strip_prefix("Cmd+").filter(|_| !command) { + (command, rest) = (true, r); + } else if let Some(r) = rest.strip_prefix("Shift+").filter(|_| !shift) { + (shift, rest) = (true, r); + } else { + break; + } + } + let n = rest.strip_prefix('F')?.parse::().ok().filter(|n| (1..=15).contains(n))?; + Some((n, shift, command)) +} + +/// The `.atn` bytes of `actions` as the set `set`. `function_keys` gives each action's key +/// (`F1`…`F15`, with `Shift+` and `Cmd+` as [`function_key_name`] writes them). Steps with no Photoshop equivalent are an error unless `skip_unsupported`. +pub fn export( + set: &str, + actions: &[&Action], + function_keys: &[(String, String)], + skip_unsupported: bool, +) -> std::result::Result<(Vec, Vec), String> { + let mut skipped = Vec::new(); + let mut file = AtnFile { name: UnicodeString::new_nul(set), expanded: true, actions: Vec::new(), warnings: Vec::new() }; + for a in actions { + let mut out = AtnAction { name: UnicodeString::new_nul(&a.name), expanded: false, ..Default::default() }; + if let Some((n, shift, command)) = function_keys.iter().find(|(n, _)| n == &a.name).and_then(|(_, key)| parse_function_key(key)) { + (out.function_key, out.shift, out.command) = (n, shift, command); + } + for (i, (id, params)) in a.steps.iter().enumerate() { + let Some(items) = export_items(id, params, set) else { + if skip_unsupported { + skipped.push(Skipped { action: a.name.clone(), step: i, id: id.clone() }); + continue; + } + let step_name = match params.get("layer") { + Some(Value::Number(n)) => format!("`{id}` with numeric layer {n}"), + _ => format!("`{id}`"), + }; + return Err(format!( + "step {} of `{}` ({step_name}) has no Photoshop equivalent; pass \"skipUnsupported\": true to leave it out", + i + 1, + a.name + )); + }; + for mut item in items { + item.enabled = a.step_enabled(i); + item.with_dialog = a.dialogs.contains(&i); + item.dialog_options = if item.with_dialog { 2 } else { 0 }; + out.items.push(item); + } + } + file.actions.push(out); + } + let bytes = atn::write(&file).map_err(|e| e.to_string())?; + Ok((bytes, skipped)) +} + +// ------------------------------------------------------------------ commands + +/// Assigns names not already used, as `name`, `name 2`, `name 3`… A plain linear scan of the +/// taken list per candidate is cubic when an action file repeats one base name many times, so +/// membership uses a set and the next suffix to try is cached per base name. +pub(super) struct UniqueNames { + taken: std::collections::HashSet, + next_suffix: std::collections::HashMap, +} + +impl UniqueNames { + pub(super) fn new>(existing: I) -> Self { + UniqueNames { taken: existing.into_iter().collect(), next_suffix: std::collections::HashMap::new() } + } + + /// Reserves and returns a unique name derived from `name`, recording it as taken. + pub(super) fn claim(&mut self, name: &str) -> String { + if self.taken.insert(name.to_string()) { + return name.to_string(); + } + let mut i = self.next_suffix.get(name).copied().unwrap_or(2); + loop { + let candidate = format!("{name} {i}"); + i += 1; + if self.taken.insert(candidate.clone()) { + self.next_suffix.insert(name.to_string(), i); + return candidate; + } + } + } +} diff --git a/crates/engine/src/atn_cmds/descriptors.rs b/crates/engine/src/atn_cmds/descriptors.rs new file mode 100644 index 0000000000..0fbecf60da --- /dev/null +++ b/crates/engine/src/atn_cmds/descriptors.rs @@ -0,0 +1,266 @@ +use super::*; + +// ------------------------------------------------------------------ descriptor access + +pub(super) fn num(v: &D) -> Option { + match v { + D::Integer(i) => Some(f64::from(*i)), + D::LargeInteger(i) => Some(*i as f64), + D::Double(d) | D::UnitFloat { value: d, .. } => Some(*d), + _ => None, + } + .filter(|f| f.is_finite()) +} + +pub(super) fn trimmed(id: &Id) -> String { + String::from_utf8_lossy(id.as_bytes()).trim_end().to_string() +} + +pub(super) fn get_num(d: &Descriptor, k: &str) -> Option { + d.get(k).and_then(num) +} + +pub(super) fn get_bool(d: &Descriptor, k: &str) -> Option { + match d.get(k) { + Some(D::Boolean(b)) => Some(*b), + _ => None, + } +} + +pub(super) fn get_text(d: &Descriptor, k: &str) -> Option { + match d.get(k) { + Some(D::Text(t)) => Some(t.to_string_lossy()), + _ => None, + } +} + +/// An enumerated value's id, trailing spaces removed (`Ordn.Trgt` → `"Trgt"`). +pub(super) fn get_enum(d: &Descriptor, k: &str) -> Option { + match d.get(k) { + Some(D::Enumerated { value, .. }) => Some(trimmed(value)), + _ => None, + } +} + +pub(super) fn get_obj<'a>(d: &'a Descriptor, k: &str) -> Option<&'a Descriptor> { + match d.get(k) { + Some(D::Descriptor(o) | D::GlobalObject(o)) => Some(o), + _ => None, + } +} + +pub(super) fn get_list<'a>(d: &'a Descriptor, k: &str) -> Option<&'a [D]> { + match d.get(k) { + Some(D::List(l)) => Some(l), + _ => None, + } +} + +pub(super) fn get_ref<'a>(d: &'a Descriptor, k: &str) -> Option<&'a [ReferenceItem]> { + match d.get(k) { + Some(D::Reference(r)) => Some(r), + _ => None, + } +} + +/// The class of a reference's first item, trimmed (`Lyr`, `Chnl`, `AdjL`…). +pub(super) fn ref_class(r: &[ReferenceItem]) -> Option { + Some(trimmed(match r.first()? { + ReferenceItem::Property { class, .. } + | ReferenceItem::Class(class) + | ReferenceItem::Enumerated { class, .. } + | ReferenceItem::Offset { class, .. } + | ReferenceItem::Identifier { class, .. } + | ReferenceItem::Index { class, .. } + | ReferenceItem::Name { class, .. } => &class.class_id, + })) +} + +/// How a reference names its target: the ordinal (`Trgt`, `Frnt`…), a name, a property… +pub(super) enum Target { + Ordinal(String), + Name(String), + Property(String), + Class, + Offset(i32), + Index(u32), + Other, +} + +pub(super) fn target(r: &[ReferenceItem]) -> Target { + match r.first() { + Some(ReferenceItem::Enumerated { value, .. }) => Target::Ordinal(trimmed(value)), + Some(ReferenceItem::Name { name, .. }) => Target::Name(name.to_string_lossy()), + Some(ReferenceItem::Property { key, .. }) => Target::Property(trimmed(key)), + Some(ReferenceItem::Class(_)) => Target::Class, + Some(ReferenceItem::Offset { offset, .. }) => Target::Offset(*offset), + Some(ReferenceItem::Index { index, .. }) => Target::Index(*index), + _ => Target::Other, + } +} + +/// `{"layer": name}` for a reference that names a layer, `{}` for the target layer, `None` +/// for anything else (an index or id: meaningless in another document). +pub(super) fn layer_target(r: &[ReferenceItem]) -> Option> { + let mut m = Map::new(); + match target(r) { + Target::Ordinal(o) if o == "Trgt" => {} + Target::Name(n) => { + m.insert("layer".into(), json!(n)); + } + Target::Property(p) if p == "Bckg" => { + m.insert("layer".into(), json!("Background")); + } + _ => return None, + } + Some(m) +} + +// ------------------------------------------------------------------ descriptor building + +/// A Photoshop id: codes shorter than four characters are space-padded (`H `, `Rd `), +/// longer names stay strings. +pub(super) fn code(s: &str) -> Id { + if s.len() < 4 { Id::new(&format!("{s:<4}")) } else { Id::new(s) } +} + +pub(super) fn class(c: &str) -> Class { + Class { name: UnicodeString::new_nul(""), class_id: code(c) } +} + +/// The pixel and percent units of a `UntF` value. +pub(super) const PX: [u8; 4] = *b"#Pxl"; + +pub(super) const PCT: [u8; 4] = *b"#Prc"; + +/// Points (1/72 in): what Photoshop calls "relative" units. +pub(super) const PT: [u8; 4] = *b"#Rlt"; + +pub(super) fn px(v: f64) -> D { + D::UnitFloat { unit: PX, value: v } +} + +pub(super) fn pct(v: f64) -> D { + D::UnitFloat { unit: *b"#Prc", value: v } +} + +pub(super) fn ang(v: f64) -> D { + D::UnitFloat { unit: *b"#Ang", value: v } +} + +pub(super) fn long(v: f64) -> D { + D::Integer(v.round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32) +} + +pub(super) fn text(s: &str) -> D { + D::Text(UnicodeString::new_nul(s)) +} + +pub(super) fn enm(ty: &str, v: &str) -> D { + D::Enumerated { type_id: code(ty), value: code(v) } +} + +pub(super) fn target_ref(cls: &str) -> D { + D::Reference(vec![ReferenceItem::Enumerated { class: class(cls), type_id: Id::new("Ordn"), value: Id::new("Trgt") }]) +} + +pub(super) fn name_ref(cls: &str, name: &str) -> D { + D::Reference(vec![ReferenceItem::Name { class: class(cls), name: UnicodeString::new_nul(name) }]) +} + +pub(super) fn class_ref(cls: &str) -> D { + D::Reference(vec![ReferenceItem::Class(class(cls))]) +} + +/// The `null` reference for a command's `layer` param: by name, else the target layer. +pub(super) fn layer_ref(p: &Value) -> Option { + match p.get("layer") { + None | Some(Value::Null) => Some(target_ref("Lyr ")), + Some(Value::String(n)) => Some(name_ref("Lyr ", n)), + _ => None, + } +} + +pub(super) fn desc(cls: &str) -> Descriptor { + Descriptor::new(cls) +} + +// ------------------------------------------------------------------ JSON access + +pub(super) fn jnum(p: &Value, k: &str) -> Option { + p.get(k).and_then(Value::as_f64).filter(|f| f.is_finite()) +} + +pub(super) fn jbool(p: &Value, k: &str) -> Option { + p.get(k).and_then(Value::as_bool) +} + +pub(super) fn jstr<'a>(p: &'a Value, k: &str) -> Option<&'a str> { + p.get(k).and_then(Value::as_str) +} + +// ------------------------------------------------------------------ colours and enums + +/// A Photoshop colour object as `#rrggbb`: `RGBC` (0..255), `HSBC`, `Grsc`. +pub(super) fn color_hex(c: &Descriptor) -> Option { + let hex = |r: f64, g: f64, b: f64| { + format!("#{:02x}{:02x}{:02x}", r.round().clamp(0.0, 255.0) as u8, g.round().clamp(0.0, 255.0) as u8, b.round().clamp(0.0, 255.0) as u8) + }; + if let (Some(r), Some(g), Some(b)) = (get_num(c, "Rd "), get_num(c, "Grn "), get_num(c, "Bl ")) { + return Some(hex(r, g, b)); + } + if let (Some(h), Some(s), Some(v)) = (get_num(c, "H "), get_num(c, "Strt"), get_num(c, "Brgh")) { + let (s, v) = ((s / 100.0).clamp(0.0, 1.0), (v / 100.0).clamp(0.0, 1.0)); + let h = h.rem_euclid(360.0) / 60.0; + let i = h.floor(); + let f = h - i; + let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f))); + let (r, g, b) = match i as i32 { + 0 => (v, t, p), + 1 => (q, v, p), + 2 => (p, v, t), + 3 => (p, q, v), + 4 => (t, p, v), + _ => (v, p, q), + }; + return Some(hex(r * 255.0, g * 255.0, b * 255.0)); + } + get_num(c, "Gry ").map(|g| { + let v = 255.0 - g * 2.55; + hex(v, v, v) + }) +} + +pub(super) fn color_desc(hex: &str) -> Option { + let h = hex.strip_prefix('#')?; + if h.len() != 6 || !h.is_ascii() { + return None; + } + let ch = |i: usize| u8::from_str_radix(h.get(i..i + 2)?, 16).ok().map(f64::from); + Some(desc("RGBC").with("Rd ", D::Double(ch(0)?)).with("Grn ", D::Double(ch(2)?)).with("Bl ", D::Double(ch(4)?))) +} + +/// A `Pth ` value's text: Photoshop stores `"txtu"`, a little-endian total length, a +/// little-endian UTF-16 unit count and the units (NUL-terminated). +pub(super) fn path_text(v: &D) -> Option { + let D::Path(b) = v else { return None }; + if b.get(0..4)? != b"txtu" { + return None; + } + let n = u32::from_le_bytes(b.get(8..12)?.try_into().ok()?) as usize; + let units: Vec = b.get(12..12usize.checked_add(n.checked_mul(2)?)?)?.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); + let text = String::from_utf16_lossy(&units); + let text = text.trim_end_matches('\0'); + (!text.is_empty()).then(|| text.to_string()) +} + +pub(super) fn path_value(text: &str) -> D { + let units: Vec = text.encode_utf16().chain(std::iter::once(0)).collect(); + let mut b = b"txtu".to_vec(); + b.extend_from_slice(&((12 + units.len() * 2) as u32).to_le_bytes()); + b.extend_from_slice(&(units.len() as u32).to_le_bytes()); + for u in units { + b.extend_from_slice(&u.to_le_bytes()); + } + D::Path(b) +} diff --git a/crates/engine/src/atn_cmds/events.rs b/crates/engine/src/atn_cmds/events.rs new file mode 100644 index 0000000000..6d2fbc4382 --- /dev/null +++ b/crates/engine/src/atn_cmds/events.rs @@ -0,0 +1,609 @@ +use super::adjustments::{adjustment_by_class, adjustment_steps, levels_from, levels_to, shadows_highlights_from, shadows_highlights_to}; +use super::descriptors::{desc, get_bool, get_ref, jbool, layer_ref, layer_target, ref_class}; +use super::fields::{F, Kind, Mapped, fields_from, fields_to, none, step}; +use super::steps_doc::{ + align_from, align_to, canvas_size_from, canvas_size_to, close_from, close_to, conditional_from, conditional_to, convert_mode_from, convert_mode_to, + crop_from, crop_to, export_from, export_to, image_size_from, image_size_to, merge_visible_from, merge_visible_to, open_from, open_to, paste_from, paste_to, + place_from, place_to, profile_from, profile_to, purge_from, purge_to, reset_from, reset_to, save_from, save_to, stop_from, stop_to, +}; +use super::steps_image::{ + GALLERY_IDS, REFINE_EDGE, RIPPLE_SIZE, SMART_BRUSH, apply_image_from, apply_image_to, color_range_from, color_range_to, gallery_from, gallery_to, + has_refine_strokes, radial_blur_from, radial_blur_to, refine_edge_to, transform_from, transform_to, +}; +use super::steps_layer::{ + STROKE, apply_comp_from, apply_comp_to, clear_from, clear_to, delete_from, delete_to, duplicate_from, duplicate_to, fill_from, fill_to, flip_from, flip_to, + move_from, move_to, play_from, play_to, rotate_from, rotate_to, select_from, select_to, stroke_to, visibility_from, visibility_to, +}; +use super::steps_make::{make_from, make_to, set_from, set_to}; +use super::tables::{NOISE, OFFSET_FILL, SMART_BLUR_MODE, SMART_BLUR_QUALITY, TRIM}; +use super::*; + +/// An event: code (empty when Photoshop only has a string name), string name, the panel +/// label, the command ids it exports (the first is the one simple events import to), and the +/// two converters. +pub(super) struct Event { + pub(super) code: &'static str, + pub(super) name: &'static str, + pub(super) label: &'static str, + pub(super) ids: &'static [&'static str], + pub(super) from: fn(&Descriptor) -> Mapped, + to: fn(&str, &Value) -> Option, +} + +macro_rules! ev { + ($code:literal, $name:literal, $label:literal, $id:literal, $fields:expr) => { + ev!($code, $name, $label, $id, $fields, unless | _ | false) + }; + // `unless`: params the descriptor can't carry, so such a step isn't exported (it would replay + // differently) rather than losing them. + ($code:literal, $name:literal, $label:literal, $id:literal, $fields:expr, unless $skip:expr) => { + Event { + code: $code, + name: $name, + label: $label, + ids: &[$id], + from: |d| match fields_from(d, $fields) { + Some(m) => step($id, Value::Object(m)), + None => Mapped::Unsupported { harmless: false }, + }, + to: |_, p| if pixel_target(p) && !($skip)(p) && holds_its_settings($id, p) { fields_to(p, $fields, desc("null")) } else { None }, + } + }; +} + +/// Minimum / Maximum with Preserve: Roundness. The descriptor here maps the radius only, and +/// Photoshop's encoding of the shape isn't verified, so such a step is not exported: it would +/// replay as the default Squareness (#7233). +fn preserves_roundness(p: &Value) -> bool { + p.get("preserve").and_then(Value::as_str) == Some("roundness") +} + +/// Whether any of the boolean `flags` is on in `p` (present, not null and not `false`). +fn flag_set(p: &Value, flags: &[&str]) -> bool { + flags.iter().any(|f| p.get(*f).is_some_and(|v| !v.is_null() && *v != Value::Bool(false))) +} + +/// Select > Modify with "Apply effect at canvas bounds": the descriptor has no field for it, so such a +/// step is not exported (it would replay without the option). +fn applies_at_canvas_bounds(p: &Value) -> bool { + flag_set(p, &["applyAtCanvasBounds"]) +} + +/// Settings a mapped event has no field for, by command: `(param, the value the event plays as)`. +/// Photoshop's event has nowhere to put these, so a step that sets one cannot be written: it +/// would import as a different edit, silently. Such a step is refused, the way [`pixel_target`] +/// refuses a filter aimed at a mask -- and no key Photoshop does not define is invented for it, +/// which the clean-room rule forbids and which would make the file wrong in another reader. +/// +/// A step that leaves the setting at the value the event plays as exports as before. +/// How a setting the event cannot carry behaves once the step is replayed without it. Which of +/// the two a setting takes follows the command's own reading of it, not the parameter spec. +enum Lost { + /// Replay uses this value, so only a step already at it survives. Numbers and strings are + /// both compared as written, since the commands below read these settings as written. + ReplaysAs(&'static str), + /// The command reads only this one spelling as anything other than what replay does, so every + /// other value survives -- a differently cased one included, because it too plays as replay's. + DiffersAt(&'static str), +} + +const UNHOLDABLE: &[(&str, &[(&str, Lost)])] = &[ + // Crst carries ClSz only; replay seeds the pattern from 0 (#7668). + ("filter.pixelate.crystallize", &[("seed", Lost::ReplaysAs("0"))]), + // RdlB carries Amnt, BlrM and BlrQ; replay spins or zooms about the middle of the layer. + ("filter.blur.radialBlur", &[("centerX", Lost::ReplaysAs("0.5")), ("centerY", Lost::ReplaysAs("0.5"))]), + // Mnm /Mxm carry Rds only; replay keeps squareness, and so does the command for anything but + // the exact string "roundness" -- see `preserve` in filters.rs. + ("filter.other.minimum", &[("preserve", Lost::DiffersAt("roundness"))]), + ("filter.other.maximum", &[("preserve", Lost::DiffersAt("roundness"))]), +]; + +/// Whether every setting of `p` that its event cannot hold would play the same without it +/// (see [`UNHOLDABLE`]). +fn holds_its_settings(id: &str, p: &Value) -> bool { + let Some((_, settings)) = UNHOLDABLE.iter().find(|(cmd, _)| *cmd == id) else { return true }; + settings.iter().all(|(param, lost)| match (p.get(param), lost) { + (None | Some(Value::Null), _) => true, + (Some(v), Lost::ReplaysAs(played)) => v.as_str() == Some(played) || v.as_f64().is_some_and(|n| played.parse::().is_ok_and(|d| n == d)), + (Some(v), Lost::DiffersAt(spelling)) => v.as_str() != Some(spelling), + }) +} + +/// Whether `p` edits the layer's pixels: no `"target"` or `"target":"pixels"`. Photoshop's +/// descriptor for a plain event has no field for a mask, Quick Mask or channel target, so such +/// a step can't be exported faithfully. +pub(super) fn pixel_target(p: &Value) -> bool { + p.get("target").is_none_or(|t| t.as_str() == Some("pixels")) +} + +fn levels_event_from(d: &Descriptor) -> Mapped { + if get_bool(d, "Auto") == Some(true) { + return none("image.autoTone"); + } + if get_bool(d, "AuCo") == Some(true) { + return none("image.autoContrast"); + } + match levels_from(d) { + Some(p) => step("image.adjustments.levels", p), + None => Mapped::Unsupported { harmless: false }, + } +} + +fn levels_event_to(id: &str, p: &Value) -> Option { + Some(match id { + "image.autoTone" => desc("null").with("Auto", D::Boolean(true)), + "image.autoContrast" => desc("null").with("AuCo", D::Boolean(true)), + _ => levels_to(p)?, + }) +} + +/// A direct adjustment event (Image › Adjustments › …). The command id is `image.adjustments.` +/// unless it is given. +macro_rules! adjustment_event { + ($code:literal, $class:literal, $name:literal, $label:literal) => { + adjustment_event!($code, $class, $name, $label, concat!("image.adjustments.", $name)) + }; + ($code:literal, $class:literal, $name:literal, $label:literal, $id:expr) => { + Event { + code: $code, + name: $name, + label: $label, + ids: &[$id], + from: |d| match adjustment_by_class($class) { + Some(a) => adjustment_steps(a, "image.adjustments.", Some(d)), + None => Mapped::Unsupported { harmless: false }, + }, + to: |_, p| adjustment_by_class($class).and_then(|a| (a.to)(p)), + } + }; +} + +/// Create / Release Clipping Mask (`groupEvent` / `ungroup`) on the target or a named layer. +fn clipping_from(d: &Descriptor, id: &str) -> Mapped { + match get_ref(d, "null") { + None => none(id), + Some(r) if ref_class(r).as_deref() == Some("Lyr") => match layer_target(r) { + Some(p) => step(id, Value::Object(p)), + None => Mapped::Unsupported { harmless: false }, + }, + Some(_) => Mapped::Unsupported { harmless: false }, + } +} + +fn clipping_to(_: &str, p: &Value) -> Option { + Some(desc("null").with("null", layer_ref(p)?)) +} + +/// A clipping mask event: `clipping_from` / `clipping_to` with one command id. +macro_rules! clipping_event { + ($code:literal, $name:literal, $label:literal, $id:literal) => { + Event { code: $code, name: $name, label: $label, ids: &[$id], from: |d| clipping_from(d, $id), to: clipping_to } + }; +} + +/// Every Photoshop event PhotoCraft maps. The order matters only for the panel label. +pub(super) const EVENTS: &[Event] = &[ + // Filters. + ev!("GsnB", "gaussianBlur", "Gaussian Blur", "filter.blur.gaussianBlur", &[F("Rds ", "radius", Kind::Px)]), + ev!( + "UnsM", + "unsharpMask", + "Unsharp Mask", + "filter.sharpen.unsharpMask", + &[F("Amnt", "amount", Kind::Pct), F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)] + ), + ev!( + "AdNs", + "addNoise", + "Add Noise", + "filter.noise.addNoise", + &[ + F("Dstr", "distribution", Kind::Enum("Dstr", NOISE)), + F("Nose", "amount", Kind::Pct), + F("Mnch", "monochromatic", Kind::Bool), + F("FlRs", "seed", Kind::Long) + ] + ), + ev!("Mdn ", "median", "Median", "filter.noise.median", &[F("Rds ", "radius", Kind::Px)]), + ev!("DstS", "dustAndScratches", "Dust & Scratches", "filter.noise.dustAndScratches", &[F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)]), + ev!("Dspc", "despeckle", "Despeckle", "filter.noise.despeckle", &[]), + // Photoshop records Emboss's angle, height and amount as plain integers (#7946). + ev!( + "Embs", + "emboss", + "Emboss", + "filter.stylize.emboss", + &[F("Angl", "angle", Kind::Long), F("Hght", "height", Kind::Long), F("Amnt", "amount", Kind::Long)] + ), + ev!("MtnB", "motionBlur", "Motion Blur", "filter.blur.motionBlur", &[F("Angl", "angle", Kind::Ang), F("Dstn", "distance", Kind::Px)]), + ev!("", "boxblur", "Box Blur", "filter.blur.boxBlur", &[F("Rds ", "radius", Kind::Px)]), + ev!("", "surfaceBlur", "Surface Blur", "filter.blur.surfaceBlur", &[F("Rds ", "radius", Kind::Px), F("Thsh", "threshold", Kind::Long)]), + ev!( + "SmrB", + "smartBlur", + "Smart Blur", + "filter.blur.smartBlur", + &[ + F("Rds ", "radius", Kind::Dbl), + F("Thsh", "threshold", Kind::Dbl), + F("SmBQ", "quality", Kind::Enum("SmBQ", SMART_BLUR_QUALITY)), + F("SmBM", "mode", Kind::Enum("SmBM", SMART_BLUR_MODE)) + ] + ), + Event { code: "RdlB", name: "radialBlur", label: "Radial Blur", ids: &["filter.blur.radialBlur"], from: radial_blur_from, to: radial_blur_to }, + ev!("Blr ", "blur", "Blur", "filter.blur.blur", &[]), + ev!("BlrM", "blurMore", "Blur More", "filter.blur.blurMore", &[]), + ev!("Shrp", "sharpen", "Sharpen", "filter.sharpen.sharpen", &[]), + ev!("ShrM", "sharpenMore", "Sharpen More", "filter.sharpen.sharpenMore", &[]), + ev!("ShrE", "sharpenEdges", "Sharpen Edges", "filter.sharpen.sharpenEdges", &[]), + ev!("HghP", "highPass", "High Pass", "filter.other.highPass", &[F("Rds ", "radius", Kind::Px)]), + ev!("Mnm ", "minimum", "Minimum", "filter.other.minimum", &[F("Rds ", "radius", Kind::Px)], unless preserves_roundness), + ev!("Mxm ", "maximum", "Maximum", "filter.other.maximum", &[F("Rds ", "radius", Kind::Px)], unless preserves_roundness), + ev!( + "Ofst", + "offset", + "Offset", + "filter.other.offset", + &[F("Hrzn", "horizontal", Kind::Long), F("Vrtc", "vertical", Kind::Long), F("Fl ", "undefinedAreas", Kind::Enum("FlMd", OFFSET_FILL))] + ), + ev!("Rple", "ripple", "Ripple", "filter.distort.ripple", &[F("Amnt", "amount", Kind::ExactLong), F("RplS", "size", Kind::Enum("RplS", RIPPLE_SIZE))]), + ev!("Crst", "crystallize", "Crystallize", "filter.pixelate.crystallize", &[F("ClSz", "cellSize", Kind::ExactLong)]), + Event { code: "GEfc", name: "filterGallery", label: "Filter Gallery", ids: GALLERY_IDS, from: gallery_from, to: gallery_to }, + // Adjustments (Image › Adjustments). + Event { + code: "", + name: "adaptCorrect", + label: "Shadows/Highlights", + ids: &["image.adjustments.shadowsHighlights"], + from: shadows_highlights_from, + to: shadows_highlights_to, + }, + Event { + code: "Lvls", + name: "levels", + label: "Levels", + ids: &["image.adjustments.levels", "image.autoTone", "image.autoContrast"], + from: levels_event_from, + to: levels_event_to, + }, + adjustment_event!("Crvs", "Crvs", "curves", "Curves"), + adjustment_event!("HStr", "HStr", "hueSaturation", "Hue/Saturation"), + adjustment_event!("BrgC", "BrgC", "brightnessEvent", "Brightness/Contrast", "image.adjustments.brightnessContrast"), + adjustment_event!("Thrs", "Thrs", "threshold", "Threshold"), + adjustment_event!("Pstr", "Pstr", "posterize", "Posterize"), + adjustment_event!("Invr", "Invr", "invert", "Invert"), + adjustment_event!("ClrB", "ClrB", "colorBalance", "Color Balance"), + adjustment_event!("Vbrn", "Vbrn", "vibrance", "Vibrance"), + adjustment_event!("Exps", "Exps", "exposure", "Exposure"), + // Photoshop runs Photo Filter by name only: `PhtF` is the class, not an event (#8301). + adjustment_event!("", "PhtF", "photoFilter", "Photo Filter"), + adjustment_event!("", "BanW", "blackAndWhite", "Black & White", "image.adjustments.blackWhite"), + adjustment_event!("ChnM", "ChnM", "channelMixer", "Channel Mixer"), + adjustment_event!("GdMp", "GdMp", "gradientMapEvent", "Gradient Map", "image.adjustments.gradientMap"), + adjustment_event!("SlcC", "SlcC", "selectiveColor", "Selective Color"), + ev!("Dstt", "desaturate", "Desaturate", "image.adjustments.desaturate", &[]), + ev!("Eqlz", "equalize", "Equalize", "image.adjustments.equalize", &[]), + ev!("", "autoColor", "Auto Color", "image.autoColor", &[]), + // Image. + Event { code: "ImgS", name: "imageSize", label: "Image Size", ids: &["image.imageSize"], from: image_size_from, to: image_size_to }, + Event { code: "CnvS", name: "canvasSize", label: "Canvas Size", ids: &["image.canvasSize"], from: canvas_size_from, to: canvas_size_to }, + Event { + code: "Rtte", + name: "rotateEventEnum", + label: "Rotate", + ids: &[ + "image.imageRotation.90cw", + "image.imageRotation.90ccw", + "image.imageRotation.180", + "image.rotation.arbitrary", + "edit.transform.rotate90Cw", + "edit.transform.rotate90Ccw", + "edit.transform.rotate180", + ], + from: rotate_from, + to: rotate_to, + }, + Event { + code: "Flip", + name: "flip", + label: "Flip", + ids: &[ + "image.imageRotation.flipCanvasHorizontal", + "image.imageRotation.flipCanvasVertical", + "edit.transform.flipHorizontal", + "edit.transform.flipVertical", + ], + from: flip_from, + to: flip_to, + }, + Event { code: "Crop", name: "crop", label: "Crop", ids: &["image.crop"], from: crop_from, to: crop_to }, + ev!( + "", + "trim", + "Trim", + "image.trim", + &[ + F("trimBasedOn", "basedOn", Kind::Enum("trimBasedOn", TRIM)), + F("Top ", "top", Kind::Bool), + F("Btom", "bottom", Kind::Bool), + F("Left", "left", Kind::Bool), + F("Rght", "right", Kind::Bool) + ] + ), + ev!("RvlA", "revealAll", "Reveal All", "image.revealAll", &[]), + Event { + code: "CnvM", + name: "convertMode", + label: "Convert Mode", + ids: &[ + "image.mode.rgb", + "image.mode.grayscale", + "image.mode.cmyk", + "image.mode.lab", + "image.mode.multichannel", + "image.mode.bits8", + "image.mode.bits16", + "image.mode.bits32", + "image.mode.bitmap", + ], + from: convert_mode_from, + to: convert_mode_to, + }, + Event { code: "Dplc", name: "duplicate", label: "Duplicate", ids: &["layer.duplicate", "image.duplicate"], from: duplicate_from, to: duplicate_to }, + // Layers. + Event { + code: "Mk ", + name: "make", + label: "Make", + ids: &[ + "layer.new.layer", + "layer.new.group", + "layer.groupLayers", + "layer.duplicate", + "layer.new.layerViaCopy", + "layer.new.layerViaCut", + "layer.newFillLayer.solidColor", + "layer.newFillLayer.pattern", + "layer.newAdjustmentLayer.levels", + "layer.newAdjustmentLayer.curves", + "layer.newAdjustmentLayer.hueSaturation", + "layer.newAdjustmentLayer.brightnessContrast", + "layer.newAdjustmentLayer.threshold", + "layer.newAdjustmentLayer.posterize", + "layer.newAdjustmentLayer.invert", + "layer.newAdjustmentLayer.colorBalance", + "layer.newAdjustmentLayer.vibrance", + "layer.newAdjustmentLayer.exposure", + "layer.newAdjustmentLayer.photoFilter", + "layer.newAdjustmentLayer.blackWhite", + "layer.newAdjustmentLayer.channelMixer", + "layer.newAdjustmentLayer.selectiveColor", + "layer.newAdjustmentLayer.gradientMap", + "layer.layerMask.revealAll", + "layer.layerMask.hideAll", + "layer.layerMask.revealSelection", + "layer.layerMask.hideSelection", + "file.new", + "file.newFromClipboard", + ], + from: make_from, + to: make_to, + }, + Event { + code: "setd", + name: "set", + label: "Set", + ids: &[ + "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", + "layer.new.layerFromBackground", + ], + from: set_from, + to: set_to, + }, + Event { + code: "slct", + name: "select", + label: "Select", + ids: &[ + "layer.select", + "layer.selectAbove", + "layer.selectBelow", + "layer.addAboveToSelection", + "layer.addBelowToSelection", + "layer.selectTop", + "layer.selectBottom", + "channel.target", + "edit.undo", + "edit.redo", + "view.fitOnScreen", + "view.actualPixels", + "view.zoomIn", + "view.zoomOut", + "document.activate", + ], + from: select_from, + to: select_to, + }, + Event { code: "Dlt ", name: "delete", label: "Delete", ids: &["layer.delete", "edit.clear", "layer.layerMask.delete"], from: delete_from, to: delete_to }, + Event { code: "", name: "clearEvent", label: "Clear", ids: &["select.editInQuickMaskMode"], from: clear_from, to: clear_to }, + Event { + code: "Trnf", + name: "transform", + label: "Transform", + ids: &["edit.transform", "select.transformSelection"], + from: transform_from, + to: transform_to, + }, + Event { code: "AppI", name: "applyImageEvent", label: "Apply Image", ids: &["image.applyImage"], from: apply_image_from, to: apply_image_to }, + ev!("", "newPlacedLayer", "Convert to Smart Object", "layer.smartObjects.convertToSmartObject", &[]), + ev!("", "placedLayerEditContents", "Edit Contents", "layer.smartObjects.editContents", &[]), + ev!("", "updatePlacedLayer", "Update Smart Objects", "layer.smartObjects.updateModifiedContent", &[]), + Event { code: "Hd ", name: "hide", label: "Hide", ids: &["layer.hideLayers"], from: |d| visibility_from(d, "layer.hideLayers"), to: visibility_to }, + Event { code: "Shw ", name: "show", label: "Show", ids: &["layer.showLayers"], from: |d| visibility_from(d, "layer.showLayers"), to: visibility_to }, + Event { + code: "move", + name: "move", + label: "Move", + ids: &["layer.translate", "layer.arrange.bringToFront", "layer.arrange.sendToBack", "layer.arrange.bringForward", "layer.arrange.sendBackward"], + from: move_from, + to: move_to, + }, + ev!("FltI", "flattenImage", "Flatten Image", "layer.flattenImage", &[]), + Event { + code: "MrgV", + name: "mergeVisible", + label: "Merge Visible", + ids: &["layer.mergeVisible", "layer.stampVisible"], + from: merge_visible_from, + to: merge_visible_to, + }, + ev!("Mrg2", "mergeLayersNew", "Merge Layers", "layer.mergeLayers", &[]), + clipping_event!("Ungr", "ungroup", "Release Clipping Mask", "layer.releaseClippingMask"), + ev!("CpTL", "copyToLayer", "Layer Via Copy", "layer.new.layerViaCopy", &[]), + ev!("CtTL", "cutToLayer", "Layer Via Cut", "layer.new.layerViaCut", &[]), + ev!("", "rasterizeLayer", "Rasterize", "layer.rasterize.layer", &[]), + ev!("", "selectAllLayers", "Select All Layers", "select.allLayers", &[]), + ev!("", "selectNoLayers", "Deselect Layers", "select.deselectLayers", &[]), + clipping_event!("GrpL", "groupEvent", "Create Clipping Mask", "layer.createClippingMask"), + ev!("", "ungroupLayersEvent", "Ungroup Layers", "layer.ungroupLayers", &[]), + ev!("", "copyEffects", "Copy Layer Style", "layer.layerStyle.copyLayerStyle", &[]), + ev!("", "pasteEffects", "Paste Layer Style", "layer.layerStyle.pasteLayerStyle", &[]), + Event { + code: "", + name: "collapseAllGroupsEvent", + label: "Collapse All Groups", + ids: &["layer.setExpanded"], + from: |_| step("layer.setExpanded", json!({"all": true, "expanded": false})), + to: |_, p| (jbool(p, "all") == Some(true) && jbool(p, "expanded") == Some(false)).then(|| desc("null")), + }, + ev!("Dfrg", "defringe", "Defringe", "layer.matting.defringe", &[F("Wdth", "width", Kind::Px)]), + Event { + code: "Algn", + name: "align", + label: "Align", + ids: &[ + "layer.align.leftEdges", + "layer.align.horizontalCenters", + "layer.align.rightEdges", + "layer.align.topEdges", + "layer.align.verticalCenters", + "layer.align.bottomEdges", + ], + from: align_from, + to: align_to, + }, + // Selection. + ev!("Invs", "inverse", "Inverse", "select.inverse", &[]), + ev!("Fthr", "feather", "Feather", "select.modify.feather", &[F("Rds ", "radius", Kind::Px)], unless applies_at_canvas_bounds), + ev!("Expn", "expand", "Expand", "select.modify.expand", &[F("By ", "radius", Kind::Px)], unless applies_at_canvas_bounds), + ev!("Cntc", "contract", "Contract", "select.modify.contract", &[F("By ", "radius", Kind::Px)], unless applies_at_canvas_bounds), + ev!("Smth", "smoothness", "Smooth", "select.modify.smooth", &[F("Rds ", "radius", Kind::Px)], unless applies_at_canvas_bounds), + ev!("Brdr", "border", "Border", "select.modify.border", &[F("Wdth", "radius", Kind::Px)]), + ev!("Grow", "grow", "Grow", "select.grow", &[F("Tlrn", "tolerance", Kind::Long)]), + ev!("Smlr", "similar", "Similar", "select.similar", &[F("Tlrn", "tolerance", Kind::Long)]), + // `refineSelectionEdge` has no Sample All Layers, so a step with it exports as + // `smartBrushWorkspace` instead of dropping it. + Event { + code: "", + name: "refineSelectionEdge", + label: "Select and Mask", + ids: &["select.refineEdge"], + from: |d| match fields_from(d, REFINE_EDGE) { + Some(m) => step("select.refineEdge", Value::Object(m)), + None => Mapped::Unsupported { harmless: false }, + }, + to: refine_edge_to, + }, + ev!("", "smartBrushWorkspace", "Select and Mask", "select.refineEdge", SMART_BRUSH, unless has_refine_strokes), + ev!("", "autoCutout", "Select Subject", "select.subject", &[F("sampleAllLayers", "sampleAllLayers", Kind::Bool)]), + Event { code: "ClrR", name: "colorRange", label: "Color Range", ids: &["select.colorRange"], from: color_range_from, to: color_range_to }, + // Edit. + Event { code: "Fl ", name: "fill", label: "Fill", ids: &["edit.fill", "paint.bucket"], from: fill_from, to: fill_to }, + Event { + code: "Strk", + name: "stroke", + label: "Stroke", + ids: &["edit.stroke"], + from: |d| match fields_from(d, STROKE) { + Some(m) => step("edit.stroke", Value::Object(m)), + None => Mapped::Unsupported { harmless: false }, + }, + to: stroke_to, + }, + ev!("copy", "copyEvent", "Copy", "edit.copy", &[]), + ev!("CpyM", "copyMerged", "Copy Merged", "edit.copyMerged", &[]), + ev!("cut ", "cut", "Cut", "edit.cut", &[]), + Event { code: "past", name: "paste", label: "Paste", ids: &["edit.paste", "edit.pasteSpecial.pasteInPlace"], from: paste_from, to: paste_to }, + Event { + code: "Prge", + name: "purge", + label: "Purge", + ids: &["edit.purge.all", "edit.purge.clipboard", "edit.purge.histories", "edit.purge.undo"], + from: purge_from, + to: purge_to, + }, + Event { code: "Rset", name: "reset", label: "Reset", ids: &["tools.defaultColors"], from: reset_from, to: reset_to }, + ev!("Exch", "exchange", "Exchange", "tools.swapColors", &[]), + Event { + code: "", + name: "assignProfile", + label: "Assign Profile", + ids: &["edit.assignProfile"], + from: |d| profile_from(d, "edit.assignProfile"), + to: profile_to, + }, + Event { + code: "", + name: "convertToProfile", + label: "Convert to Profile", + ids: &["edit.convertToProfile"], + from: |d| profile_from(d, "edit.convertToProfile"), + to: profile_to, + }, + // File and actions. + Event { code: "Cls ", name: "close", label: "Close", ids: &["file.close"], from: close_from, to: close_to }, + Event { code: "Expr", name: "export", label: "Export", ids: &["file.export.saveForWebLegacy"], from: export_from, to: export_to }, + Event { code: "Plc ", name: "placeEvent", label: "Place", ids: &["file.placeEmbedded", "file.placeLinked"], from: place_from, to: place_to }, + Event { code: "Opn ", name: "open", label: "Open", ids: &["file.openAs"], from: open_from, to: open_to }, + Event { code: "", name: "conditional", label: "If", ids: &["actions.conditional"], from: conditional_from, to: conditional_to }, + Event { code: "save", name: "save", label: "Save", ids: &["file.save", "file.saveAs", "file.saveACopy"], from: save_from, to: save_to }, + ev!("Rvrt", "revert", "Revert", "file.revert", &[]), + Event { code: "Ply ", name: "play", label: "Play", ids: &["actions.play"], from: play_from, to: play_to }, + Event { code: "", name: "applyComp", label: "Apply Layer Comp", ids: &["layerComp.apply"], from: apply_comp_from, to: apply_comp_to }, + Event { code: "Stop", name: "stop", label: "Stop", ids: &[STOP_MESSAGE], from: stop_from, to: stop_to }, +]; + +/// Four-char codes PhotoCraft once exported for events Photoshop only runs by name (or by +/// another code), with the name they stand for. Measured in Photoshop: `executeAction` with +/// these codes fails ("the command is not currently available"), and `Fltn` is the +/// `flatness` property, not the flatten event. Import keeps accepting them so actions saved +/// before still load; export never writes them. +const LEGACY_CODES: &[(&str, &str)] = + &[("BoxB", "boxblur"), ("SrfB", "surfaceBlur"), ("Fltn", "flattenImage"), ("BlnW", "blackAndWhite"), ("PhtF", "photoFilter")]; + +pub(super) fn event_for(item: &AtnEvent) -> Option<&'static Event> { + let id = item.id(); + let find = |id: &str| EVENTS.iter().find(|e| (!e.code.is_empty() && e.code.trim_end() == id.trim_end()) || e.name == id); + find(&id).or_else(|| match item { + AtnEvent::Code(_) => LEGACY_CODES.iter().find(|(code, _)| *code == id).and_then(|(_, name)| find(name)), + AtnEvent::Name(_) => None, + }) +} + +/// The event `id` exports as: the first event listing it whose converter accepts the params +/// (Quick Mask on is a `set`, off a `clearEvent`). +pub(super) fn event_and_descriptor(id: &str, params: &Value) -> Option<(&'static Event, Descriptor)> { + EVENTS.iter().filter(|e| e.ids.contains(&id)).find_map(|e| (e.to)(id, params).map(|d| (e, d))) +} diff --git a/crates/engine/src/atn_cmds/fields.rs b/crates/engine/src/atn_cmds/fields.rs new file mode 100644 index 0000000000..8dd32a283c --- /dev/null +++ b/crates/engine/src/atn_cmds/fields.rs @@ -0,0 +1,113 @@ +use super::descriptors::{ang, color_desc, color_hex, enm, get_bool, get_enum, get_num, get_obj, long, pct, px}; +use super::tables::{blend_label, blend_ps, lookup, lookup_back}; +use super::*; + +// ------------------------------------------------------------------ field tables + +#[derive(Clone, Copy)] +pub(super) enum Kind { + Px, + Pct, + Ang, + Long, + /// An integer field whose value must survive conversion without rounding or saturation. + ExactLong, + Dbl, + Bool, + /// An enumeration: its type id and the Photoshop ↔ PhotoCraft value pairs. + Enum(&'static str, &'static [(&'static str, &'static str)]), + /// A blend mode (`BlnM`). + Blend, + /// A colour object ↔ `#rrggbb`. + Color, +} + +/// One descriptor key ↔ one command param. +pub(super) struct F(pub(super) &'static str, pub(super) &'static str, pub(super) Kind); + +/// Import mapped descriptor fields, leaving absent values to command defaults. +/// Return `None` when a present enum, blend mode or colour cannot be represented. +pub(super) fn fields_from(d: &Descriptor, fields: &[F]) -> Option> { + let mut m = Map::new(); + for F(key, param, kind) in fields { + let v = match kind { + Kind::Px | Kind::Pct | Kind::Ang | Kind::Long | Kind::ExactLong | Kind::Dbl => get_num(d, key).map(Value::from), + Kind::Bool => get_bool(d, key).map(Value::from), + Kind::Enum(_, table) => match get_enum(d, key) { + Some(e) => Some(Value::from(lookup(table, &e)?)), + None => None, + }, + Kind::Blend => match get_enum(d, key) { + Some(e) => Some(Value::from(blend_label(&e)?)), + None => None, + }, + Kind::Color => match get_obj(d, key) { + Some(c) => Some(Value::from(color_hex(c)?)), + None => None, + }, + }; + if let Some(v) = v { + m.insert((*param).into(), v); + } + } + Some(m) +} + +/// Export supplied mapped params, omitting absent values to preserve event defaults. +/// Return `None` for unsupported values; `ExactLong` also rejects rounding or saturation. +pub(super) fn fields_to(p: &Value, fields: &[F], mut d: Descriptor) -> Option { + for F(key, param, kind) in fields { + let Some(v) = p.get(param) else { continue }; + let out = match kind { + Kind::Px => px(v.as_f64()?), + Kind::Pct => pct(v.as_f64()?), + Kind::Ang => ang(v.as_f64()?), + // A value outside the descriptor's 32-bit integer refuses the step rather than being + // clamped to another value (an Add Noise seed above i32::MAX replayed as i32::MAX, #7287). + Kind::Long => { + let n = v.as_f64()?.round(); + if !(f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&n) { + return None; + } + long(n) + } + Kind::ExactLong => { + let number = v.as_f64()?; + let integer = number as i32; + if f64::from(integer) != number { + return None; + } + D::Integer(integer) + } + Kind::Dbl => D::Double(v.as_f64()?), + Kind::Bool => D::Boolean(v.as_bool()?), + Kind::Enum(ty, table) => enm(ty, lookup_back(table, v.as_str()?)?), + Kind::Blend => enm("BlnM", blend_ps(v.as_str()?)?), + Kind::Color => D::Descriptor(color_desc(v.as_str()?)?), + }; + d = d.with(key, out); + } + Some(d) +} + +// ------------------------------------------------------------------ the event table + +/// What one Photoshop step maps to. +pub(super) enum Mapped { + /// One or more PhotoCraft steps (a `make` with a name becomes new layer + rename). + Steps(Vec<(String, Value)>), + /// No PhotoCraft equivalent; `harmless` steps (tool selections…) are imported switched off. + Unsupported { harmless: bool }, +} + +pub(super) fn step(id: &str, params: Value) -> Mapped { + Mapped::Steps(vec![(id.to_string(), params)]) +} + +pub(super) fn steps(v: Vec<(&str, Value)>) -> Mapped { + Mapped::Steps(v.into_iter().map(|(id, p)| (id.to_string(), p)).collect()) +} + +pub(super) fn none(id: &str) -> Mapped { + step(id, json!({})) +} diff --git a/crates/engine/src/atn_cmds/files.rs b/crates/engine/src/atn_cmds/files.rs new file mode 100644 index 0000000000..9666a443bb --- /dev/null +++ b/crates/engine/src/atn_cmds/files.rs @@ -0,0 +1,140 @@ +use super::convert::{UniqueNames, export, import}; +use super::*; + +pub(super) fn load(s: &mut Session, p: &Value) -> Result { + let cmd = "actions.load"; + if s.actions.recording.is_some() || s.actions.playing > 0 { + return Err(bad(cmd, "stop recording or playing before loading actions")); + } + let (bytes, _) = crate::preset_import_cmds::file_bytes(p, cmd, ".atn file")?; + let mut imp = import(&bytes).map_err(|e| bad(cmd, e))?; + match p.get("set") { + None | Some(Value::Null) => {} + Some(Value::String(n)) if !n.trim().is_empty() => { + imp.set = n.trim().to_string(); + for a in &mut imp.actions { + a.set = Some(imp.set.clone()); + } + } + Some(_) => return Err(bad(cmd, "`set` must be a non-empty string")), + } + let replace = match p.get("replace") { + None | Some(Value::Null) => true, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(cmd, "`replace` must be true or false")), + }; + if replace { + s.actions.list.retain(|a| a.set.as_deref() != Some(imp.set.as_str())); + } + let mut taken = UniqueNames::new(s.actions.list.iter().map(|a| a.name.clone())); + let mut names = Vec::with_capacity(imp.actions.len()); + // The file's name of each action that had to be renamed, and its new name. + let mut renamed: std::collections::HashMap = std::collections::HashMap::new(); + let mut steps = 0usize; + let mut added = Vec::with_capacity(imp.actions.len()); + for mut a in imp.actions { + let name = taken.claim(&a.name); + if name != a.name { + renamed.entry(a.name.clone()).or_insert_with(|| name.clone()); + } + a.name = name.clone(); + steps = steps.saturating_add(a.steps.len()); + names.push(name); + added.push(a); + } + // Play and Conditional steps call actions by name: follow the renames in the actions just + // loaded, each target looked up once by the name the file gave it. + for a in &mut added { + for (id, params) in &mut a.steps { + let keys: &[&str] = match id.as_str() { + "actions.play" => &["action"], + "actions.conditional" => &["then", "else"], + _ => &[], + }; + for key in keys { + if let Some(to) = params.get(*key).and_then(Value::as_str).and_then(|n| renamed.get(n)) { + params[*key] = json!(to); + } + } + } + } + s.actions.list.extend(added); + let keys: Vec<(String, String)> = imp.function_keys.into_iter().map(|(n, k)| (renamed.get(&n).cloned().unwrap_or(n), k)).collect(); + if !keys.is_empty() { + s.edit_prefs(|prefs| { + for (name, key) in &keys { + // A function key belongs to one action. + prefs.shortcuts.retain(|k, v| !(k.starts_with(crate::actions_cmds::PLAY_SHORTCUT_PREFIX) && v == key)); + prefs.shortcuts.insert(format!("{}{name}", crate::actions_cmds::PLAY_SHORTCUT_PREFIX), key.clone()); + } + }); + } + s.actions.touch(); + Ok(json!({ + "set": imp.set, + "actions": names, + "steps": steps, + "unsupported": imp.unsupported, + "functionKeys": keys.iter().map(|(n, k)| json!({"action": n, "key": k})).collect::>(), + "warnings": imp.warnings, + })) +} + +pub(super) fn save(s: &mut Session, p: &Value) -> Result { + let cmd = "actions.save"; + crate::actions_cmds::flush_recording(s)?; + let skip = match p.get("skipUnsupported") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(cmd, "`skipUnsupported` must be true or false")), + }; + let set_param = match p.get("set") { + None | Some(Value::Null) => None, + Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), + Some(_) => return Err(bad(cmd, "`set` must be a non-empty string")), + }; + let (set, actions): (String, Vec<&Action>) = if p.get("action").is_some() { + let idx = crate::actions_cmds::resolve(&s.actions.list, p, cmd)?; + let a = &s.actions.list[idx]; + (set_param.or_else(|| a.set.clone()).unwrap_or_else(|| a.name.clone()), vec![a]) + } else if let Some(set) = set_param { + let list: Vec<&Action> = s.actions.list.iter().filter(|a| a.set.as_deref() == Some(set.as_str())).collect(); + if list.is_empty() { + return Err(bad(cmd, format!("no actions in a set named `{set}`"))); + } + (set, list) + } else { + (DEFAULT_SET.to_string(), s.actions.list.iter().collect()) + }; + if actions.is_empty() { + return Err(bad(cmd, "there are no actions to save")); + } + let names: Vec = actions.iter().map(|a| a.name.clone()).collect(); + let keys: Vec<(String, String)> = + s.prefs().shortcuts.iter().filter_map(|(k, v)| k.strip_prefix(crate::actions_cmds::PLAY_SHORTCUT_PREFIX).map(|n| (n.to_string(), v.clone()))).collect(); + let (bytes, skipped) = export(&set, &actions, &keys, skip).map_err(|e| bad(cmd, e))?; + let steps: usize = actions.iter().map(|a| a.steps.len()).sum::().saturating_sub(skipped.len()); + let mut out = json!({"set": set, "actions": names, "steps": steps, "bytes": bytes.len(), "skipped": skipped}); + match p.get("path") { + None | Some(Value::Null) => { + out["data"] = json!(photocraft_paint::tile::b64_encode(&bytes)); + } + Some(Value::String(path)) if !path.trim().is_empty() => { + write_file(path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; + out["path"] = json!(path); + } + Some(_) => return Err(bad(cmd, "`path` must be a non-empty string")), + } + Ok(out) +} + +#[cfg(not(target_arch = "wasm32"))] +fn write_file(path: &str, bytes: &[u8]) -> std::io::Result<()> { + // Atomic replacement (temporary file + rename): a failed write keeps the previous ATN (#7290). + photocraft_format::atomic_write(std::path::Path::new(path), bytes) +} + +#[cfg(target_arch = "wasm32")] +fn write_file(path: &str, _bytes: &[u8]) -> std::io::Result<()> { + Err(std::io::Error::other(format!("cannot write paths on the web ({path}); omit `path` to get the bytes back as `data`"))) +} diff --git a/crates/engine/src/atn_cmds/steps_doc.rs b/crates/engine/src/atn_cmds/steps_doc.rs new file mode 100644 index 0000000000..36100c1066 --- /dev/null +++ b/crates/engine/src/atn_cmds/steps_doc.rs @@ -0,0 +1,558 @@ +use super::convert::clip_name; +use super::descriptors::{ + PCT, PX, Target, ang, class, color_desc, color_hex, desc, enm, get_bool, get_enum, get_num, get_obj, get_ref, get_text, jbool, jnum, jstr, long, path_text, + path_value, pct, px, target, target_ref, text, trimmed, +}; +use super::fields::{Mapped, none, step, steps}; +use super::tables::{ALIGN, EXTENSION, INTENT, INTERPOLATION, MODES, PROFILES, PURGE, SAVE_FORMATS, lookup, lookup_back}; +use super::*; + +/// `placeEvent`: File › Place Embedded / Linked, with the file and the recorded scale. +pub(super) fn place_from(d: &Descriptor) -> Mapped { + let Some(path) = d.get("null").and_then(path_text) else { return Mapped::Unsupported { harmless: false } }; + let mut p = json!({"path": path}); + if let Some(w) = get_num(d, "Wdth") { + p["scale"] = json!(w); + } + step(if get_bool(d, "Lnkd") == Some(true) { "file.placeLinked" } else { "file.placeEmbedded" }, p) +} + +pub(super) fn place_to(id: &str, p: &Value) -> Option { + let mut d = desc("null").with("null", path_value(jstr(p, "path")?)).with("FTcs", enm("QCSt", "Qcsa")); + if let Some(s) = jnum(p, "scale") { + d = d.with("Wdth", pct(s)).with("Hght", pct(s)); + } + Some(d.with("Lnkd", D::Boolean(id == "file.placeLinked")).with("Antl", D::Boolean(true))) +} + +/// `open`: File › Open of a recorded path. +pub(super) fn open_from(d: &Descriptor) -> Mapped { + match d.get("null").and_then(path_text) { + Some(path) => step("file.openAs", json!({"path": path})), + None => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn open_to(_: &str, p: &Value) -> Option { + Some(desc("null").with("null", path_value(jstr(p, "path")?))) +} + +fn path_extension(path: &str) -> Option { + let name = path.rsplit(['/', '\\']).next()?; + let (stem, ext) = name.rsplit_once('.')?; + (!stem.is_empty() && !ext.is_empty()).then(|| ext.to_ascii_lowercase()) +} + +/// `save`: a plain Save, or a Save As (`As` format, `In` destination, `Cpy` As a Copy). +/// Only a destination that is a file of the recorded format imports: a folder (#5430), a missing +/// or unknown format or a mismatched extension stays a kept Photoshop step, so playback stops +/// before writing rather than saving over the played file (#7102). +pub(super) fn save_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + if d.get("As ").is_none() && d.get("In ").is_none() { + return step("file.save", json!({})); + } + // A Save As needs a format descriptor to check the destination against: without one (or + // with a format that isn't a descriptor) the step is kept. + let Some(format) = get_obj(d, "As ") else { return unsupported }; + let Some(path) = d.get("In ").and_then(path_text) else { return unsupported }; + if get_bool(d, "DIDr") == Some(true) { + return unsupported; + } + let Some(ext) = path_extension(&path) else { return unsupported }; + let class = trimmed(&format.class_id); + let Some((_, exts)) = SAVE_FORMATS.iter().find(|(c, _)| *c == class) else { return unsupported }; + if !exts.contains(&ext.as_str()) { + return unsupported; + } + step(if get_bool(d, "Cpy ") == Some(true) { "file.saveACopy" } else { "file.saveAs" }, json!({"path": path})) +} + +pub(super) fn save_to(id: &str, p: &Value) -> Option { + if id == "file.save" { + return Some(desc("null")); + } + let path = jstr(p, "path")?; + let ext = path_extension(path)?; + let (class, _) = SAVE_FORMATS.iter().find(|(_, exts)| exts.contains(&ext.as_str()))?; + let d = desc("null").with("As ", D::Descriptor(desc(class))).with("In ", path_value(path)); + Some(if id == "file.saveACopy" { d.with("Cpy ", D::Boolean(true)) } else { d }) +} + +/// Photoshop's four-character condition codes that differ from the string ids. +const CONDITION_CODES: &[(&str, &str)] = &[("Lyrs", "hasLayers")]; + +/// `conditional`: Insert Conditional, with its Then and Else actions by name. +pub(super) fn conditional_from(d: &Descriptor) -> Mapped { + let Some(c) = get_enum(d, "null") else { return Mapped::Unsupported { harmless: false } }; + let condition = lookup(CONDITION_CODES, &c).unwrap_or(c.as_str()); + if !crate::actions_edit_cmds::CONDITIONS.contains(&condition) { + return Mapped::Unsupported { harmless: false }; + } + let branch = |key: &str| match get_ref(d, key).map(target) { + // Clipped like the stored action names, so the load-time rename map finds it. + Some(Target::Name(n)) => Some(clip_name(&n)), + _ => None, + }; + step("actions.conditional", json!({"if": condition, "then": branch("then"), "else": branch("else")})) +} + +pub(super) fn conditional_to(_: &str, p: &Value) -> Option { + let condition = jstr(p, "if")?; + let code = lookup_back(CONDITION_CODES, condition).unwrap_or(condition); + let mut d = desc("null").with("null", enm("Cndt", code)); + for key in ["then", "else"] { + if let Some(name) = jstr(p, key) { + let mut items = vec![ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul(name) }]; + if let Some(set) = jstr(p, "set") { + items.push(ReferenceItem::Name { class: class("ASet"), name: UnicodeString::new_nul(set) }); + } + d = d.with(key, D::Reference(items)); + } + } + Some(d) +} + +/// `close`: Photoshop's Save prompt answer becomes a Save step before the Close. +pub(super) fn close_from(d: &Descriptor) -> Mapped { + if get_enum(d, "Svng").as_deref() == Some("Ys") { steps(vec![("file.save", json!({})), ("file.close", json!({}))]) } else { none("file.close") } +} + +/// A Close of an explicit document has no mapping here: written as a plain Close it would +/// close the active document on playback, so it is left to `skipUnsupported`. +pub(super) fn close_to(_: &str, p: &Value) -> Option { + if p.get("document").is_some_and(|d| !d.is_null()) { + return None; + } + Some(desc("null").with("Svng", enm("YsN ", "N "))) +} + +const WEB_FORMATS: &[(&str, &str)] = &[("PN24", "png24"), ("PN8", "png8"), ("JPEG", "jpeg"), ("GIFf", "gif"), ("WBMP", "wbmp")]; + +/// `export` (Save for Web): needs the destination path (`In`), as the command writes a file. +pub(super) fn export_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + let Some(u) = get_obj(d, "Usng") else { return unsupported }; + let Some(path) = d.get("In ").and_then(path_text) else { return unsupported }; + let mut p = json!({"path": path}); + if let Some(f) = get_enum(u, "Fmt ") { + match lookup(WEB_FORMATS, &f) { + Some(f) => p["format"] = json!(f), + None => return unsupported, + } + } + for (key, param) in [("Intr", "interlaced"), ("Trns", "transparency"), ("EICC", "embedIcc"), ("Prgr", "progressive"), ("Optm", "optimized")] { + if let Some(b) = get_bool(u, key) { + p[param] = json!(b); + } + } + for (key, param) in [("Qlty", "quality"), ("NCol", "colors")] { + if let Some(v) = get_num(u, key) { + p[param] = json!(v); + } + } + if get_bool(u, "Mtt ") == Some(false) { + p["matte"] = json!("none"); + } else if let (Some(r), Some(g), Some(b)) = (get_num(u, "MttR"), get_num(u, "MttG"), get_num(u, "MttB")) { + p["matte"] = + json!(format!("#{:02x}{:02x}{:02x}", r.round().clamp(0.0, 255.0) as u8, g.round().clamp(0.0, 255.0) as u8, b.round().clamp(0.0, 255.0) as u8)); + } + step("file.export.saveForWebLegacy", p) +} + +pub(super) fn export_to(_: &str, p: &Value) -> Option { + let path = jstr(p, "path")?; + let mut u = desc("SaveForWeb").with("Op ", enm("SWOp", "OpSa")).with("Fmt ", enm("IRFm", lookup_back(WEB_FORMATS, jstr(p, "format").unwrap_or("png24"))?)); + for (key, param, default) in [ + ("Intr", "interlaced", false), + ("Trns", "transparency", true), + ("EICC", "embedIcc", false), + ("Prgr", "progressive", false), + ("Optm", "optimized", true), + ] { + u = u.with(key, D::Boolean(jbool(p, param).unwrap_or(default))); + } + if let Some(q) = jnum(p, "quality") { + u = u.with("Qlty", long(q)); + } + if let Some(c) = jnum(p, "colors") { + u = u.with("NCol", long(c)); + } + match jstr(p, "matte") { + Some("none") => u = u.with("Mtt ", D::Boolean(false)), + matte => { + let c = color_desc(matte.unwrap_or("#ffffff"))?; + u = u + .with("Mtt ", D::Boolean(true)) + .with("MttR", get_num(&c, "Rd ").map(long)?) + .with("MttG", get_num(&c, "Grn ").map(long)?) + .with("MttB", get_num(&c, "Bl ").map(long)?); + } + } + Some(desc("null").with("Usng", D::Descriptor(u)).with("In ", path_value(path))) +} + +pub(super) fn convert_mode_from(d: &Descriptor) -> Mapped { + if let Some(depth) = get_num(d, "Dpth") { + return match depth as i64 { + 8 => none("image.mode.bits8"), + 16 => none("image.mode.bits16"), + 32 => none("image.mode.bits32"), + _ => Mapped::Unsupported { harmless: false }, + }; + } + // The mode as an enumeration (`ClrS.Grys`), a class (`Grys`), or an object of the mode's + // class holding its options (`BtmM {Rslt, Mthd}`, `Grys {Rt}` from Bitmap). + let (mode, options) = match d.get("T ") { + Some(D::Enumerated { value, .. }) => (trimmed(value), None), + Some(D::Class(c)) => (trimmed(&c.class_id), None), + Some(D::Descriptor(o)) => (trimmed(&o.class_id), Some(o)), + _ => return Mapped::Unsupported { harmless: false }, + }; + if mode == "BtmM" { + return bitmap_from(options); + } + // Bitmap to Grayscale records a size ratio; only 1 keeps the pixels as they are. + if options.and_then(|o| get_num(o, "Rt ")).is_some_and(|r| (r - 1.0).abs() > 1e-9) { + return Mapped::Unsupported { harmless: false }; + } + match lookup(MODES, &mode) { + Some(m) => none(&format!("image.mode.{m}")), + None => Mapped::Unsupported { harmless: false }, + } +} + +const BITMAP_METHOD: &[(&str, &str)] = &[("Thrh", "threshold"), ("PtnD", "pattern"), ("DfnD", "diffusion")]; + +/// Image › Mode › Bitmap. Its Output resolution resamples the image, keeping the print size, +/// before the conversion; at the document's own resolution that is a no-op. Halftone screens +/// and custom patterns stay unsupported. +fn bitmap_from(options: Option<&Descriptor>) -> Mapped { + let Some(o) = options else { return none("image.mode.bitmap") }; + let method = match get_enum(o, "Mthd") { + None => "diffusion", + Some(m) => match lookup(BITMAP_METHOD, &m) { + Some(m) => m, + None => return Mapped::Unsupported { harmless: false }, + }, + }; + let convert = ("image.mode.bitmap", json!({"method": method})); + match get_num(o, "Rslt") { + Some(r) => steps(vec![("image.imageSize", json!({"resolution": r, "resample": "bicubic", "keepPrintSize": true})), convert]), + None => steps(vec![convert]), + } +} + +fn bitmap_to(p: &Value) -> Option { + let method = lookup_back(BITMAP_METHOD, jstr(p, "method").unwrap_or("diffusion"))?; + Some(desc("null").with("T ", D::Descriptor(desc("BtmM").with("Mthd", enm("Mthd", method))))) +} + +pub(super) fn convert_mode_to(id: &str, p: &Value) -> Option { + Some(match id { + "image.mode.bits8" => desc("null").with("Dpth", long(8.0)), + "image.mode.bits16" => desc("null").with("Dpth", long(16.0)), + "image.mode.bits32" => desc("null").with("Dpth", long(32.0)), + "image.mode.bitmap" => bitmap_to(p)?, + _ => desc("null").with("T ", enm("ClrS", lookup_back(MODES, id.strip_prefix("image.mode.")?)?)), + }) +} + +pub(super) fn canvas_size_from(d: &Descriptor) -> Mapped { + let mut p = Map::new(); + for (k, param) in [("Wdth", "width"), ("Hght", "height")] { + match d.get(k) { + Some(D::UnitFloat { unit: PX, value }) => { + p.insert(param.into(), value.round().into()); + } + Some(_) => return Mapped::Unsupported { harmless: false }, + None => {} + } + } + if let Some(r) = get_bool(d, "Rltv") { + p.insert("relative".into(), r.into()); + } + let v = get_enum(d, "Vrtc").unwrap_or_else(|| "Cntr".into()); + let h = get_enum(d, "Hrzn").unwrap_or_else(|| "Cntr".into()); + let anchor = match (v.as_str(), h.as_str()) { + ("Top", "Left") => "topLeft", + ("Top", "Cntr") => "top", + ("Top", "Rght") => "topRight", + ("Cntr", "Left") => "left", + ("Cntr", "Cntr") => "center", + ("Cntr", "Rght") => "right", + ("Bttm", "Left") => "bottomLeft", + ("Bttm", "Cntr") => "bottom", + ("Bttm", "Rght") => "bottomRight", + _ => return Mapped::Unsupported { harmless: false }, + }; + p.insert("anchor".into(), anchor.into()); + if let Some(c) = get_enum(d, "canvasExtensionColorType") { + match lookup(EXTENSION, &c) { + Some(c) => { + p.insert("extensionColor".into(), c.into()); + } + None => match get_obj(d, "canvasExtensionColor").and_then(color_hex) { + Some(hex) => { + p.insert("extensionColor".into(), hex.into()); + } + None => return Mapped::Unsupported { harmless: false }, + }, + } + } + step("image.canvasSize", Value::Object(p)) +} + +pub(super) fn canvas_size_to(_: &str, p: &Value) -> Option { + let anchor = jstr(p, "anchor").unwrap_or("center"); + let v = if anchor.starts_with("top") { + "Top " + } else if anchor.starts_with("bottom") { + "Bttm" + } else { + "Cntr" + }; + let h = if anchor.to_ascii_lowercase().ends_with("left") { + "Left" + } else if anchor.to_ascii_lowercase().ends_with("right") { + "Rght" + } else { + "Cntr" + }; + let mut d = desc("null"); + if let Some(r) = jbool(p, "relative") { + d = d.with("Rltv", D::Boolean(r)); + } + if let Some(w) = jnum(p, "width") { + d = d.with("Wdth", px(w)); + } + if let Some(hh) = jnum(p, "height") { + d = d.with("Hght", px(hh)); + } + d = d.with("Hrzn", enm("HrzL", h)).with("Vrtc", enm("VrtL", v)); + if let Some(c) = jstr(p, "extensionColor") { + d = match lookup_back(EXTENSION, c) { + Some(e) => d.with("canvasExtensionColorType", enm("canvasExtensionColorType", e)), + None => d.with("canvasExtensionColorType", enm("canvasExtensionColorType", "Othr")).with("canvasExtensionColor", D::Descriptor(color_desc(c)?)), + }; + } + Some(d) +} + +pub(super) fn image_size_from(d: &Descriptor) -> Mapped { + let mut p = Map::new(); + let mut percent: Option = None; + for (k, param) in [("Wdth", "width"), ("Hght", "height")] { + match d.get(k) { + Some(D::UnitFloat { unit: PX, value }) => { + p.insert(param.into(), value.round().into()); + } + // Percent scales both sides at playback; two different percentages, or physical + // units, need the document's size and resolution and stay unsupported. + Some(D::UnitFloat { unit: PCT, value }) => match percent { + Some(other) if (other - value).abs() > 1e-9 => return Mapped::Unsupported { harmless: false }, + _ => percent = Some(*value), + }, + Some(_) => return Mapped::Unsupported { harmless: false }, + None => {} + } + } + if let Some(pc) = percent { + p.insert("percent".into(), pc.into()); + } + if let Some(r) = get_num(d, "Rslt") { + p.insert("resolution".into(), r.into()); + } + if let Some(i) = get_enum(d, "Intr") { + match lookup(INTERPOLATION, &i) { + Some(i) => { + p.insert("resample".into(), i.into()); + // Resample on with only the resolution changed: Photoshop keeps the print size. + if p.contains_key("resolution") && !p.contains_key("width") && !p.contains_key("height") && !p.contains_key("percent") { + p.insert("keepPrintSize".into(), true.into()); + } + } + None => return Mapped::Unsupported { harmless: false }, + } + } else if p.contains_key("resolution") && !p.contains_key("width") && !p.contains_key("height") && !p.contains_key("percent") { + p.insert("resample".into(), "none".into()); + } + if p.is_empty() { + return Mapped::Unsupported { harmless: false }; + } + step("image.imageSize", Value::Object(p)) +} + +pub(super) fn image_size_to(_: &str, p: &Value) -> Option { + // Resolution only with Resample on imports as keep-print-size; a command without it cannot be told apart. + if jnum(p, "resolution").is_some() + && jnum(p, "width").is_none() + && jnum(p, "height").is_none() + && jnum(p, "percent").is_none() + && jstr(p, "resample").is_some_and(|r| r != "none") + && jbool(p, "keepPrintSize") != Some(true) + { + return None; + } + let mut d = desc("null"); + // `resample: "none"` changes the resolution only and the command ignores any size then. The + // descriptor has no "none" (it is the absence of `Intr`), so writing the ignored size would + // turn the step into a pixel resize on playback (#7189). + let resolution_only = jstr(p, "resample") == Some("none"); + if resolution_only && jnum(p, "resolution").is_none() { + // Nothing left to record: the step changes nothing. + return None; + } + if let Some(pc) = jnum(p, "percent").filter(|_| !resolution_only) { + d = d.with("Wdth", pct(pc)).with("Hght", pct(pc)).with("CnsP", D::Boolean(true)); + } + if let Some(w) = jnum(p, "width").filter(|_| !resolution_only) { + d = d.with("Wdth", px(w)); + } + if let Some(h) = jnum(p, "height").filter(|_| !resolution_only) { + d = d.with("Hght", px(h)); + } + if let Some(r) = jnum(p, "resolution") { + d = d.with("Rslt", D::UnitFloat { unit: *b"#Rsl", value: r }); + } + if let Some(i) = jstr(p, "resample").filter(|r| *r != "none") { + d = d.with("Intr", enm("Intp", lookup_back(INTERPOLATION, i)?)); + } + Some(d) +} + +pub(super) fn crop_from(d: &Descriptor) -> Mapped { + let mut p = Map::new(); + if let Some(t) = get_obj(d, "To ") { + // Pixels only, like Canvas Size: a side in percent or points needs the document's size + // or resolution and must not be played as pixels. + let side = |k: &str| match t.get(k) { + Some(D::UnitFloat { unit: PX, value }) if value.is_finite() => Some(*value), + _ => None, + }; + let (Some(top), Some(left), Some(bottom), Some(right)) = (side("Top "), side("Left"), side("Btom"), side("Rght")) else { + return Mapped::Unsupported { harmless: false }; + }; + p.insert("x".into(), left.round().into()); + p.insert("y".into(), top.round().into()); + p.insert("width".into(), (right - left).round().into()); + p.insert("height".into(), (bottom - top).round().into()); + } + if let Some(a) = get_num(d, "Angl") { + p.insert("angle".into(), a.into()); + } + if let Some(del) = get_bool(d, "Dlt ") { + p.insert("deleteCroppedPixels".into(), del.into()); + } + step("image.crop", Value::Object(p)) +} + +pub(super) fn crop_to(_: &str, p: &Value) -> Option { + // The W x H x Resolution output options have no field here: refuse rather than export a plain + // rectangle crop that keeps the old size and resolution on replay. + if ["targetWidth", "targetHeight", "resolution"].iter().any(|k| p.get(k).is_some_and(|v| !v.is_null())) { + return None; + } + let mut d = desc("null"); + if let (Some(x), Some(y), Some(w), Some(h)) = (jnum(p, "x"), jnum(p, "y"), jnum(p, "width"), jnum(p, "height")) { + d = d.with("To ", D::Descriptor(desc("Rctn").with("Top ", px(y)).with("Left", px(x)).with("Btom", px(y + h)).with("Rght", px(x + w)))); + } + if let Some(a) = jnum(p, "angle") { + d = d.with("Angl", ang(a)); + } + if let Some(del) = jbool(p, "deleteCroppedPixels") { + d = d.with("Dlt ", D::Boolean(del)); + } + Some(d) +} + +pub(super) fn stop_from(d: &Descriptor) -> Mapped { + step(STOP_MESSAGE, json!({"message": get_text(d, "Msge").unwrap_or_default(), "allowContinue": get_bool(d, "Cntn").unwrap_or(false)})) +} + +pub(super) fn stop_to(_: &str, p: &Value) -> Option { + Some(desc("null").with("Msge", text(jstr(p, "message").unwrap_or(""))).with("Cntn", D::Boolean(jbool(p, "allowContinue").unwrap_or(false)))) +} + +pub(super) fn paste_from(d: &Descriptor) -> Mapped { + none(if get_bool(d, "inPlace") == Some(true) { "edit.pasteSpecial.pasteInPlace" } else { "edit.paste" }) +} + +pub(super) fn paste_to(id: &str, _: &Value) -> Option { + let mut d = desc("null"); + if id == "edit.pasteSpecial.pasteInPlace" { + d = d.with("inPlace", D::Boolean(true)); + } + Some(d.with("AntA", enm("Annt", "Anno"))) +} + +pub(super) fn merge_visible_from(d: &Descriptor) -> Mapped { + none(if get_bool(d, "Dplc") == Some(true) { "layer.stampVisible" } else { "layer.mergeVisible" }) +} + +pub(super) fn merge_visible_to(id: &str, _: &Value) -> Option { + Some(if id == "layer.stampVisible" { desc("null").with("Dplc", D::Boolean(true)) } else { desc("null") }) +} + +pub(super) fn align_from(d: &Descriptor) -> Mapped { + match get_enum(d, "Usng").and_then(|u| lookup(ALIGN, &u)) { + Some(a) => step(&format!("layer.align.{a}"), if get_bool(d, "alignToCanvas") == Some(true) { json!({"to": "canvas"}) } else { json!({}) }), + None => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn align_to(id: &str, p: &Value) -> Option { + let a = lookup_back(ALIGN, id.strip_prefix("layer.align.")?)?; + Some(desc("null").with("null", target_ref("Lyr ")).with("Usng", enm("ADSt", a)).with("alignToCanvas", D::Boolean(jstr(p, "to") == Some("canvas")))) +} + +pub(super) fn purge_from(d: &Descriptor) -> Mapped { + match get_enum(d, "null").and_then(|u| lookup(PURGE, &u)) { + Some(p) => none(&format!("edit.purge.{p}")), + None => Mapped::Unsupported { harmless: true }, + } +} + +pub(super) fn purge_to(id: &str, _: &Value) -> Option { + Some(desc("null").with("null", enm("PrgI", lookup_back(PURGE, id.strip_prefix("edit.purge.")?)?))) +} + +pub(super) fn reset_from(d: &Descriptor) -> Mapped { + match get_ref(d, "null").map(target) { + Some(Target::Property(p)) if p == "Clrs" => none("tools.defaultColors"), + _ => Mapped::Unsupported { harmless: true }, + } +} + +pub(super) fn reset_to(_: &str, _: &Value) -> Option { + Some(desc("null").with("null", D::Reference(vec![ReferenceItem::Property { class: class("Clr "), key: Id::new("Clrs") }]))) +} + +pub(super) fn profile_from(d: &Descriptor, id: &str) -> Mapped { + let name = get_text(d, "T ").or_else(|| get_text(d, "profile")); + let Some(profile) = name.as_deref().and_then(|n| lookup(PROFILES, n)) else { return Mapped::Unsupported { harmless: false } }; + let mut p = json!({"profile": profile}); + if id == "edit.convertToProfile" { + if let Some(i) = get_enum(d, "Inte").and_then(|i| lookup(INTENT, &i)) { + p["intent"] = json!(i); + } + if let Some(b) = get_bool(d, "MpBl") { + p["bpc"] = json!(b); + } + } + step(id, p) +} + +pub(super) fn profile_to(id: &str, p: &Value) -> Option { + let name = lookup_back(PROFILES, jstr(p, "profile")?)?; + let mut d = desc("null").with("null", target_ref("Dcmn")); + if id == "edit.convertToProfile" { + d = d + .with("T ", text(name)) + .with("Inte", enm("Inte", lookup_back(INTENT, jstr(p, "intent").unwrap_or("relative"))?)) + .with("MpBl", D::Boolean(jbool(p, "bpc").unwrap_or(true))); + } else { + d = d.with("profile", text(name)); + } + Some(d) +} diff --git a/crates/engine/src/atn_cmds/steps_image.rs b/crates/engine/src/atn_cmds/steps_image.rs new file mode 100644 index 0000000000..bb8e1c82fd --- /dev/null +++ b/crates/engine/src/atn_cmds/steps_image.rs @@ -0,0 +1,453 @@ +use super::descriptors::{ + PX, Target, ang, class, code, desc, enm, get_bool, get_enum, get_num, get_obj, get_ref, jbool, jnum, jstr, layer_ref, layer_target, long, pct, px, + ref_class, target, trimmed, +}; +use super::events::pixel_target; +use super::fields::{F, Kind, Mapped, fields_from, fields_to, step}; +use super::tables::{CHANNELS, INTERPOLATION, RADIAL_METHOD, RADIAL_QUALITY, lookup, lookup_back}; +use super::*; + +/// `transform`: Photoshop records a Free Transform relative to the frame (offset of its centre, +/// width/height in percent, angle). A layer moved only becomes `layer.translate`; anything +/// else is `edit.transform`'s relative form; the selection's frame is `select.transformSelection`. +pub(super) fn transform_from(d: &Descriptor) -> Mapped { + // No reference (a smart object replaced in place, `replaceLayer`) means the target layer. + let target_layer = [ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code("Trgt") }]; + let r: &[ReferenceItem] = get_ref(d, "null").unwrap_or(&target_layer); + let unsupported = Mapped::Unsupported { harmless: false }; + let mut p = Map::new(); + if let Some(o) = get_obj(d, "Ofst") { + let in_px = |k: &str| matches!(o.get(k), Some(D::UnitFloat { unit: PX, .. })); + if !in_px("Hrzn") || !in_px("Vrtc") { + return unsupported; + } + if let Some(x) = get_num(o, "Hrzn") { + p.insert("dx".into(), x.into()); + } + if let Some(y) = get_num(o, "Vrtc") { + p.insert("dy".into(), y.into()); + } + } + for (key, param) in [("Wdth", "scaleX"), ("Hght", "scaleY"), ("Angl", "rotate")] { + if let Some(v) = get_num(d, key) { + p.insert(param.into(), v.into()); + } + } + if d.get("Skew").is_some() || d.get("Usng").is_some() { + return unsupported; + } + // A whole-pixel move is a plain `layer.translate`; a fractional one needs `edit.transform` + // to keep its sub-pixel placement and interpolation. + let whole_pixels = ["dx", "dy"].iter().all(|k| p.get(*k).and_then(Value::as_f64).is_none_or(|v| v.fract() == 0.0)); + let geometry_only = p.keys().all(|k| k == "dx" || k == "dy") && whole_pixels; + // The resampling applies to a selection as much as to a layer (#7515). + // Photoshop's bicubic variants are kept (the transforms render them as Bicubic, and they export + // back unchanged); Automatic and Preserve Details become the nearest bicubic choice. Dropping + // them fell back to the command's default, bilinear for a selection (#8697). + let interpolation = get_enum(d, "Intr").and_then(|i| lookup(INTERPOLATION, &i)).and_then(|i| match i { + "bicubic" | "bilinear" | "nearest" | "bicubicSharper" | "bicubicSmoother" | "bicubicAutomatic" => Some(i), + "automatic" => Some("bicubicAutomatic"), + "preserveDetails" => Some("bicubic"), + _ => None, + }); + match (ref_class(r).as_deref(), target(r)) { + (Some("Chnl"), Target::Property(prop)) if prop == "fsel" => { + if let Some(i) = interpolation { + p.insert("interpolation".into(), i.into()); + } + step("select.transformSelection", Value::Object(p)) + } + (Some("Lyr"), _) => { + let Some(mut lp) = layer_target(r) else { return unsupported }; + if geometry_only { + lp.insert("dx".into(), p.get("dx").and_then(Value::as_f64).unwrap_or(0.0).into()); + lp.insert("dy".into(), p.get("dy").and_then(Value::as_f64).unwrap_or(0.0).into()); + return step("layer.translate", Value::Object(lp)); + } + lp.extend(p); + if let Some(i) = interpolation { + lp.insert("interpolation".into(), i.into()); + } + step("edit.transform", Value::Object(lp)) + } + _ => unsupported, + } +} + +pub(super) fn transform_to(id: &str, p: &Value) -> Option { + let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); + if ["quad", "corners", "matrix", "rect"].iter().any(|k| given(k)) { + return None; + } + // The descriptor scales and rotates about the centre (`FTcs` average) without skew or warp: + // another reference point, a skew or a warp would replay as a different transform (#7516, + // #7517, #7518, #7519). + let nonzero = |k: &str| p.get(k).is_some_and(|v| !v.is_null() && v.as_f64() != Some(0.0)); + let off_centre = p.get("reference").is_some_and(|v| !v.is_null() && *v != json!("center")); + if nonzero("skewX") || nonzero("skewY") || off_centre || ["warp", "style", "mesh", "grid"].iter().any(|k| given(k)) { + return None; + } + let target = match id { + // The `Trnf` descriptor has no field for a mask, Quick Mask or alpha channel target; a + // layer reference would transform the layer's pixels instead. + "edit.transform" if !pixel_target(p) => return None, + "edit.transform" => layer_ref(p)?, + "select.transformSelection" => D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: code("fsel") }]), + _ => return None, + }; + let mut d = desc("null").with("null", target).with("FTcs", enm("QCSt", "Qcsa")); + d = d.with("Ofst", D::Descriptor(desc("Ofst").with("Hrzn", px(jnum(p, "dx").unwrap_or(0.0))).with("Vrtc", px(jnum(p, "dy").unwrap_or(0.0))))); + for (key, param) in [("Wdth", "scaleX"), ("Hght", "scaleY")] { + if let Some(v) = jnum(p, param) { + d = d.with(key, pct(v)); + } + } + if let Some(a) = jnum(p, "rotate") { + d = d.with("Angl", ang(a)); + } + if let Some(i) = jstr(p, "interpolation").and_then(|i| lookup_back(INTERPOLATION, i)) { + d = d.with("Intr", enm("Intp", i)); + } + Some(d) +} + +/// `Clcn` (Apply Image / Calculations blending) ↔ `image.applyImage`'s `blending`. +const CALC_BLEND: &[(&str, &str)] = &[ + ("Nrml", "normal"), + ("Mltp", "multiply"), + ("Scrn", "screen"), + ("Ovrl", "overlay"), + ("SftL", "softLight"), + ("HrdL", "hardLight"), + ("CDdg", "colorDodge"), + ("CBrn", "colorBurn"), + ("Drkn", "darken"), + ("Lghn", "lighten"), + ("Dfrn", "difference"), + ("Xclu", "exclusion"), + ("linearBurn", "linearBurn"), + ("linearDodge", "linearDodge"), + ("Add ", "add"), + ("Sbtr", "subtract"), +]; + +const SOURCE_CHANNELS: &[(&str, &str)] = + &[("RGB", "composite"), ("CMYK", "composite"), ("Lab", "composite"), ("Trsp", "transparency"), ("Msk", "mask"), ("fsel", "selection")]; + +pub(super) fn apply_image_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + let Some(with) = get_obj(d, "With") else { return unsupported }; + let Some(r) = get_ref(with, "T ") else { return unsupported }; + let mut source = Map::new(); + for item in r { + match item { + ReferenceItem::Enumerated { class, value, .. } if class.class_id.is("Chnl") => { + let v = trimmed(value); + let Some(channel) = lookup(SOURCE_CHANNELS, &v).or_else(|| lookup(CHANNELS, &v)) else { return unsupported }; + source.insert("channel".into(), channel.into()); + } + // A named (alpha) channel. + ReferenceItem::Name { class, name } if class.class_id.is("Chnl") => { + source.insert("channel".into(), name.to_string_lossy().into()); + } + ReferenceItem::Name { class, name } if class.class_id.is("Lyr ") => { + source.insert("layer".into(), name.to_string_lossy().into()); + } + ReferenceItem::Enumerated { class, value, .. } if class.class_id.is("Lyr ") && trimmed(value) == "Mrgd" => { + source.insert("layer".into(), "merged".into()); + } + _ => return unsupported, + } + } + if let Some(i) = get_bool(with, "Invr") { + source.insert("invert".into(), i.into()); + } + let mut p = json!({"source": source}); + if let Some(c) = get_enum(with, "Clcl") { + match lookup(CALC_BLEND, &c) { + Some(b) => p["blending"] = json!(b), + None => return unsupported, + } + } + for (key, param) in [("Scl ", "scale"), ("Ofst", "offset"), ("Opct", "opacity")] { + if let Some(v) = get_num(with, key) { + p[param] = json!(v); + } + } + if let Some(t) = get_bool(with, "PrsT") { + p["preserveTransparency"] = json!(t); + } + step("image.applyImage", p) +} + +/// Apply Image's source channel as a `Chnl` reference item. The dialog sends Channels-panel names +/// ("RGB", "Red", "Alpha 1"), which the command reads case-insensitively: the composite names map to +/// the composite, colour names to their enumeration, and any other name to a named (alpha) channel, +/// as Photoshop records it. +fn apply_image_channel(channel: &str) -> Option { + let l = channel.to_ascii_lowercase(); + let key = match l.as_str() { + "rgb" | "cmyk" | "lab" | "merged" => "composite", + "layermask" => "mask", + // Sources the command knows by keyword but Photoshop has no channel for. + "quickmask" | "quick mask" | "vectormask" | "vector mask" => return None, + other => other, + }; + Some(match lookup_back(SOURCE_CHANNELS, key).or_else(|| lookup_back(CHANNELS, key)) { + Some(chan) => ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code(chan) }, + None if !channel.trim().is_empty() => ReferenceItem::Name { class: class("Chnl"), name: UnicodeString::new_nul(channel) }, + None => return None, + }) +} + +pub(super) fn apply_image_to(_: &str, p: &Value) -> Option { + // The optional blending mask has no descriptor mapping: refuse it rather than drop it, + // which would widen the edit to the whole layer. + let mask_channel = match p.get("mask") { + Some(m) => m.get("channel"), + None => p.get("maskChannel"), + }; + if mask_channel.is_some_and(|c| !(c.is_null() || c == "none" || c == "")) { + return None; + } + // The Apply Image dialog sends flat `sourceLayer`/`sourceChannel`/`sourceInvert` fields; read + // them as the command does, or the export would quietly reset them to the merged composite. + let source = crate::channel_cmds::source_spec(p, "source", "source").unwrap_or(json!({})); + // A source from another open document has no event form here: skip the step, don't rewrite it. + if source.get("document").is_some_and(|d| !d.is_null()) { + return None; + } + // A layer id or channel index has no name to record: refuse it rather than write the composite. + let not_name = |k: &str| source.get(k).is_some_and(|v| !(v.is_null() || v.is_string())); + if !source.is_object() || not_name("layer") || not_name("channel") { + return None; + } + let mut items = vec![apply_image_channel(jstr(&source, "channel").unwrap_or("composite"))?]; + match jstr(&source, "layer") { + Some("merged") | None => items.push(ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code("Mrgd") }), + Some(name) => items.push(ReferenceItem::Name { class: class("Lyr "), name: UnicodeString::new_nul(name) }), + } + let mut with = desc("null").with("T ", D::Reference(items)); + if let Some(i) = jbool(&source, "invert") { + with = with.with("Invr", D::Boolean(i)); + } + with = with.with("Clcl", enm("Clcn", lookup_back(CALC_BLEND, jstr(p, "blending").unwrap_or("multiply"))?)); + if let Some(v) = jnum(p, "opacity") { + with = with.with("Opct", pct(v)); + } + if let Some(v) = jnum(p, "scale") { + with = with.with("Scl ", D::Double(v)); + } + if let Some(v) = jnum(p, "offset") { + with = with.with("Ofst", D::Double(v)); + } + if let Some(t) = jbool(p, "preserveTransparency") { + with = with.with("PrsT", D::Boolean(t)); + } + Some(desc("null").with("With", D::Descriptor(with))) +} + +pub(super) const RIPPLE_SIZE: &[(&str, &str)] = &[("Sml", "small"), ("Mdm", "medium"), ("Lrg", "large")]; + +/// Whether a Select and Mask step carries Refine Edge Brush strokes or the workspace's tool +/// edits (Quick Selection, Brush, Lasso…), which no descriptor holds. +pub(super) fn has_refine_strokes(p: &Value) -> bool { + p.get("refineStrokes").is_some_and(|v| !v.is_null() && v.as_array().is_none_or(|a| !a.is_empty())) || crate::select_mask_edits::has_edits(p) +} + +/// Select and Mask to Photoshop. The descriptor has no field for the Refine Edge Brush or the +/// workspace's tools, so a step with `refineStrokes` or `edits` can't be exported faithfully. One with `sampleAllLayers` is not +/// exported here either: it exports as `smartBrushWorkspace`. +pub(super) fn refine_edge_to(_: &str, p: &Value) -> Option { + if !pixel_target(p) || p.get("sampleAllLayers").is_some() || has_refine_strokes(p) { + return None; + } + fields_to(p, REFINE_EDGE, desc("null")) +} + +/// Select and Mask (`refineSelectionEdge`). Smart Radius, decontamination and the output follow +/// Photoshop's; the edge itself is PhotoCraft's own matting, so results differ in detail. +pub(super) const REFINE_EDGE: &[F] = &[ + F("refineEdgeBorderRadius", "radius", Kind::Px), + F("refineEdgeAutoRadius", "smartRadius", Kind::Bool), + F("refineEdgeSmooth", "smooth", Kind::Long), + F("refineEdgeFeatherRadius", "feather", Kind::Px), + F("refineEdgeBorderContrast", "contrast", Kind::Pct), + F("refineEdgeChoke", "shiftEdge", Kind::Pct), + F("refineEdgeDecontaminate", "decontaminate", Kind::Bool), + F("refineEdgeDeconAmount", "amount", Kind::Pct), + F("refineEdgeOutput", "output", Kind::Enum("refineEdgeOutput", REFINE_OUTPUT)), +]; + +const REFINE_OUTPUT: &[(&str, &str)] = &[ + ("refineEdgeOutputSelection", "selection"), + ("refineEdgeOutputUserMask", "layerMask"), + ("refineEdgeOutputNewLayer", "newLayer"), + ("refineEdgeOutputNewLayerWithMask", "newLayerWithMask"), + ("refineEdgeOutputNewDocument", "newDocument"), + ("refineEdgeOutputNewDocumentWithMask", "newDocumentWithMask"), +]; + +/// Filter Gallery effects (`GEfc` with the effect in `GEfk`): Photoshop's effect code, the +/// command, and its fields. A stack of several effects stays unsupported. +const GALLERY: &[(&str, &str, &[F])] = &[("Spt", "filter.gallery.spatter", &[F("SprR", "sprayRadius", Kind::Long), F("Smth", "smoothness", Kind::Long)])]; + +pub(super) const GALLERY_IDS: &[&str] = &["filter.gallery.spatter"]; + +pub(super) fn gallery_from(d: &Descriptor) -> Mapped { + let Some(effect) = get_enum(d, "GEfk") else { return Mapped::Unsupported { harmless: false } }; + match GALLERY.iter().find(|(code, _, _)| *code == effect).and_then(|(_, id, fields)| Some((*id, fields_from(d, fields)?))) { + Some((id, p)) => step(id, Value::Object(p)), + None => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn gallery_to(id: &str, p: &Value) -> Option { + let (code, _, fields) = GALLERY.iter().find(|(_, cmd, _)| *cmd == id)?; + fields_to(p, fields, desc("null").with("GEfk", enm("GEft", code))) +} + +/// Select and Mask as Photoshop CC 2015.5 and later record it (`smartBrushWorkspace`); the +/// older Refine Edge event is [`REFINE_EDGE`], which is also what Select and Mask exports as. +pub(super) const SMART_BRUSH: &[F] = &[ + F("smartBrushRadius", "radius", Kind::Px), + F("smartBrushUseSmartRadius", "smartRadius", Kind::Bool), + F("smartBrushSmooth", "smooth", Kind::Long), + F("smartBrushFeather", "feather", Kind::Px), + F("smartBrushContrast", "contrast", Kind::Pct), + F("smartBrushShiftEdge", "shiftEdge", Kind::Pct), + F("smartBrushDecontaminate", "decontaminate", Kind::Bool), + F("smartBrushDeconAmount", "amount", Kind::Pct), + F("refineEdgeOutput", "output", Kind::Enum("refineEdgeOutput", REFINE_OUTPUT)), + F("sampleAllLayers", "sampleAllLayers", Kind::Bool), +]; + +/// Select › Color Range's `Clrs` presets ↔ `select.colorRange`'s `select`. +const COLOR_RANGE: &[(&str, &str)] = &[ + ("Rds", "reds"), + ("Ylws", "yellows"), + ("Grns", "greens"), + ("Cyns", "cyans"), + ("Bls", "blues"), + ("Mgnt", "magentas"), + ("Hghl", "highlights"), + ("Mdtn", "midtones"), + ("Shdw", "shadows"), + ("OtOf", "outOfGamut"), + ("skinTone", "skinTones"), +]; + +/// The Color Range keys the converter reads (or that don't change a preset's result: +/// `colorModel` is the model of sampled colours). +const COLOR_RANGE_KEYS: &[&str] = &[ + "Clrs", + "Fzns", + "Invr", + "colorModel", + "shadowsFuzziness", + "shadowsUpperLimit", + "midtonesFuzziness", + "midtonesLowerLimit", + "midtonesUpperLimit", + "highlightsFuzziness", + "highlightsLowerLimit", +]; + +/// Color Range (`ClrR`) with a preset. Sampled Colors records Lab minimum and maximum colours, +/// which `select.colorRange` (eyedropper points on the image) can't reproduce, and an unknown +/// key (Detect Faces, Localized Color Clusters…) could change the result: both stay +/// unsupported. +pub(super) fn color_range_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + if d.items.iter().any(|(k, _)| !COLOR_RANGE_KEYS.contains(&trimmed(k).as_str())) { + return unsupported; + } + let Some(preset) = get_enum(d, "Clrs").and_then(|c| lookup(COLOR_RANGE, &c)) else { return unsupported }; + let mut p = Map::new(); + p.insert("select".into(), preset.into()); + let key = |suffix: &str| get_num(d, &format!("{preset}{suffix}")); + match preset { + "skinTones" => { + if let Some(f) = get_num(d, "Fzns") { + p.insert("fuzziness".into(), f.into()); + } + } + "shadows" | "midtones" | "highlights" => { + if let Some(f) = key("Fuzziness") { + p.insert("fuzziness".into(), f.into()); + } + let range = match (preset, key("LowerLimit"), key("UpperLimit")) { + ("shadows", _, hi) => hi.map(Value::from), + ("highlights", lo, _) => lo.map(Value::from), + (_, Some(lo), Some(hi)) => Some(json!([lo, hi])), + (_, None, None) => None, + _ => return unsupported, + }; + if let Some(r) = range { + p.insert("tonalRange".into(), r); + } + } + _ => {} + } + if get_bool(d, "Invr") == Some(true) { + p.insert("invert".into(), true.into()); + } + step("select.colorRange", Value::Object(p)) +} + +pub(super) fn color_range_to(_: &str, p: &Value) -> Option { + let preset = jstr(p, "select")?; + if p.as_object()?.keys().any(|k| !matches!(k.as_str(), "select" | "fuzziness" | "tonalRange" | "invert")) { + return None; + } + let mut d = desc("null").with("Clrs", enm("Clrs", lookup_back(COLOR_RANGE, preset)?)); + let tonal = matches!(preset, "shadows" | "midtones" | "highlights"); + if let Some(f) = jnum(p, "fuzziness") { + match preset { + "skinTones" => d = d.with("Fzns", long(f)), + _ if tonal => d = d.with(&format!("{preset}Fuzziness"), long(f)), + _ => {} + } + } + if let Some(r) = p.get("tonalRange") { + match preset { + "shadows" => d = d.with("shadowsUpperLimit", long(r.as_f64()?)), + "highlights" => d = d.with("highlightsLowerLimit", long(r.as_f64()?)), + "midtones" => { + let a = r.as_array()?; + d = d.with("midtonesLowerLimit", long(a.first()?.as_f64()?)).with("midtonesUpperLimit", long(a.get(1)?.as_f64()?)); + } + _ => return None, + } + } + if jbool(p, "invert") == Some(true) { + d = d.with("Invr", D::Boolean(true)); + } + Some(d) +} + +const RADIAL_BLUR_FIELDS: &[F] = + &[F("Amnt", "amount", Kind::Long), F("BlrM", "method", Kind::Enum("BlrM", RADIAL_METHOD)), F("BlrQ", "quality", Kind::Enum("BlrQ", RADIAL_QUALITY))]; + +pub(super) fn radial_blur_from(d: &Descriptor) -> Mapped { + match fields_from(d, RADIAL_BLUR_FIELDS) { + Some(m) => step("filter.blur.radialBlur", Value::Object(m)), + None => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn radial_blur_to(_: &str, p: &Value) -> Option { + if !pixel_target(p) { + return None; + } + // Photoshop's Radial Blur has no center parameter and always blurs from the center (0.5, 0.5). + // An explicit center must match 0.5 exactly; any non-default center cannot be faithfully exported. + let is_default_center = |k: &str| match p.get(k) { + None | Some(Value::Null) => true, + Some(v) => v.as_f64() == Some(0.5), + }; + if !is_default_center("centerX") || !is_default_center("centerY") { + return None; + } + fields_to(p, RADIAL_BLUR_FIELDS, desc("null")) +} diff --git a/crates/engine/src/atn_cmds/steps_layer.rs b/crates/engine/src/atn_cmds/steps_layer.rs new file mode 100644 index 0000000000..36e77d624b --- /dev/null +++ b/crates/engine/src/atn_cmds/steps_layer.rs @@ -0,0 +1,576 @@ +use super::convert::clip_name; +use super::descriptors::{ + PT, PX, Target, ang, class, code, color_desc, color_hex, desc, enm, get_bool, get_enum, get_num, get_obj, get_ref, get_text, jbool, jnum, jstr, layer_ref, + layer_target, long, name_ref, pct, px, ref_class, target, target_ref, text, trimmed, +}; +use super::events::pixel_target; +use super::fields::{F, Kind, Mapped, fields_to, none, step, steps}; +use super::steps_make::is_tool_class; +use super::tables::{FILL_CONTENTS, INTERPOLATION, MENU_ITEMS, STROKE_LOCATION, blend_label, blend_ps, lookup, lookup_back}; +use super::*; + +pub(super) fn select_from(d: &Descriptor) -> Mapped { + let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; + match (ref_class(r).as_deref(), target(r)) { + (Some("Lyr"), Target::Name(n)) => { + let mut p = json!({"layer": n}); + match get_enum(d, "selectionModifier").as_deref() { + Some("addToSelection") => p["mode"] = json!("add"), + Some("removeFromSelection") => p["mode"] = json!("remove"), + // Shift-click: select everything between the active layer and this one. + Some("addToSelectionContinuous") => p["mode"] = json!("range"), + _ => {} + } + step("layer.select", p) + } + // The Channels panel: the active layer's mask, or back to the composite (`RGB`, `CMYK`…). + (Some("Chnl"), Target::Ordinal(o)) => match o.as_str() { + "Msk" => step("channel.target", json!({"channel": "mask"})), + "RGB" | "CMYK" | "Lab" | "Gry" => step("channel.target", json!({"channel": "composite"})), + // Re-selecting the channel that is already targeted changes nothing. + "Trgt" => Mapped::Unsupported { harmless: true }, + _ => Mapped::Unsupported { harmless: false }, + }, + // History › Step Backward / Step Forward. + (Some("HstS"), Target::Ordinal(o)) if o == "Prvs" => none("edit.undo"), + (Some("HstS"), Target::Ordinal(o)) if o == "Nxt" => none("edit.redo"), + (Some("Lyr"), Target::Ordinal(o)) => { + // Shift+Alt+[ / ] add the next layer to the selection instead of replacing it. + let add = get_enum(d, "selectionModifier").as_deref() == Some("addToSelection"); + match (o.as_str(), add) { + ("Frwr", false) => none("layer.selectAbove"), + ("Frwr", true) => none("layer.addAboveToSelection"), + ("Bckw", false) => none("layer.selectBelow"), + ("Bckw", true) => none("layer.addBelowToSelection"), + ("Frnt", _) => none("layer.selectTop"), + ("Back", _) => none("layer.selectBottom"), + _ => Mapped::Unsupported { harmless: false }, + } + } + (Some(c), Target::Class) if is_tool_class(c) => Mapped::Unsupported { harmless: true }, + // A menu item chosen while recording (`Mn`): the View menu's zoom items replay. + (Some("Mn"), Target::Ordinal(item)) => match lookup(MENU_ITEMS, &item) { + Some(id) => none(id), + None => Mapped::Unsupported { harmless: false }, + }, + // Switching to another open document: its offset from the active one, -1 for the previous + // tab and 1 for the next (a template action copies from one and pastes into the other, #7103). + (Some("Dcmn"), Target::Offset(o)) => step("document.activate", json!({"offset": o})), + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn select_to(id: &str, p: &Value) -> Option { + let ord = |o: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code(o) }]); + let enumerated = |cls: &str, ty: &str, v: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class(cls), type_id: code(ty), value: code(v) }]); + Some(match id { + "layer.select" => { + if p.get("occurrence").is_some() { + return None; + } + let name = jstr(p, "name").or_else(|| jstr(p, "layer"))?; + let mut d = desc("null").with("null", name_ref("Lyr ", name)); + match jstr(p, "mode") { + None | Some("replace") => {} + Some("add") => d = d.with("selectionModifier", enm("selectionModifierType", "addToSelection")), + Some("remove") => d = d.with("selectionModifier", enm("selectionModifierType", "removeFromSelection")), + Some("range") => d = d.with("selectionModifier", enm("selectionModifierType", "addToSelectionContinuous")), + Some(_) => return None, + } + d.with("MkVs", D::Boolean(false)) + } + "channel.target" => { + let v = match jstr(p, "channel") { + Some("mask") => "Msk ", + None | Some("composite") => "RGB ", + Some(_) => return None, + }; + desc("null").with("null", enumerated("Chnl", "Chnl", v)).with("MkVs", D::Boolean(false)) + } + "edit.undo" => desc("null").with("null", enumerated("HstS", "Ordn", "Prvs")), + "edit.redo" => desc("null").with("null", enumerated("HstS", "Ordn", "Nxt ")), + "layer.selectAbove" => desc("null").with("null", ord("Frwr")), + "layer.selectBelow" => desc("null").with("null", ord("Bckw")), + "layer.addAboveToSelection" => desc("null").with("null", ord("Frwr")).with("selectionModifier", enm("selectionModifierType", "addToSelection")), + "layer.addBelowToSelection" => desc("null").with("null", ord("Bckw")).with("selectionModifier", enm("selectionModifierType", "addToSelection")), + "layer.selectTop" => desc("null").with("null", ord("Frnt")), + "layer.selectBottom" => desc("null").with("null", ord("Back")), + // An absolute tab index has no Photoshop equivalent; an offset is what Photoshop records. + "document.activate" if p.get("document").is_none_or(Value::is_null) => { + let offset = i32::try_from(p.get("offset")?.as_i64()?).ok()?; + desc("null").with("null", D::Reference(vec![ReferenceItem::Offset { class: class("Dcmn"), offset }])) + } + _ => { + let item = lookup_back(MENU_ITEMS, id)?; + desc("null").with("null", D::Reference(vec![ReferenceItem::Enumerated { class: class("Mn "), type_id: code("MnIt"), value: code(item) }])) + } + }) +} + +pub(super) fn delete_from(d: &Descriptor) -> Mapped { + match get_ref(d, "null") { + None => none("edit.clear"), + Some(r) if ref_class(r).as_deref() == Some("Lyr") => match layer_target(r) { + Some(p) => step("layer.delete", Value::Object(p)), + None => Mapped::Unsupported { harmless: false }, + }, + // The targeted channel of a layer is its mask (what Photoshop records after making an + // adjustment layer over a selection and discarding the mask). + Some(r) if ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Ordinal(o) if o == "Trgt") => none("layer.layerMask.delete"), + Some(_) => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn quick_mask_ref() -> D { + D::Reference(vec![ + ReferenceItem::Property { class: class("Prpr"), key: code("QucM") }, + ReferenceItem::Enumerated { class: class("Dcmn"), type_id: code("Ordn"), value: code("Trgt") }, + ]) +} + +pub(super) fn clear_from(d: &Descriptor) -> Mapped { + match get_ref(d, "null").map(target) { + Some(Target::Property(p)) if p == "QucM" => step("select.editInQuickMaskMode", json!({"on": false})), + None => none("edit.clear"), + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn clear_to(id: &str, p: &Value) -> Option { + match id { + "select.editInQuickMaskMode" if jbool(p, "on") == Some(false) => Some(desc("null").with("null", quick_mask_ref())), + _ => None, + } +} + +pub(super) fn delete_to(id: &str, p: &Value) -> Option { + Some(match id { + "edit.clear" => desc("null"), + "layer.delete" => desc("null").with("null", layer_ref(p)?), + "layer.layerMask.delete" => desc("null").with("null", target_ref("Chnl")), + _ => return None, + }) +} + +/// `hide` / `show` take a list of references (or one). +pub(super) fn visibility_from(d: &Descriptor, id: &str) -> Mapped { + let refs: Vec<&[ReferenceItem]> = match d.get("null") { + Some(D::List(l)) => l.iter().filter_map(|v| if let D::Reference(r) = v { Some(r.as_slice()) } else { None }).collect(), + Some(D::Reference(r)) => vec![r.as_slice()], + _ => return Mapped::Unsupported { harmless: false }, + }; + let mut v = Vec::new(); + for r in refs { + match layer_target(r) { + Some(p) => v.push((id, Value::Object(p))), + None => return Mapped::Unsupported { harmless: false }, + } + } + if v.is_empty() { Mapped::Unsupported { harmless: false } } else { steps(v) } +} + +pub(super) fn visibility_to(_: &str, p: &Value) -> Option { + Some(desc("null").with("null", D::List(vec![layer_ref(p)?]))) +} + +pub(super) fn move_from(d: &Descriptor) -> Mapped { + let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; + // The selection outline nudged. + if ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Property(p) if p == "fsel") { + return match get_obj(d, "T ") { + Some(t) if matches!(t.get("Hrzn"), Some(D::UnitFloat { unit: PX, .. })) => match (get_num(t, "Hrzn"), get_num(t, "Vrtc")) { + (Some(dx), Some(dy)) => step("select.transformSelection", json!({"dx": dx.round(), "dy": dy.round()})), + _ => Mapped::Unsupported { harmless: false }, + }, + _ => Mapped::Unsupported { harmless: false }, + }; + } + if ref_class(r).as_deref() != Some("Lyr") { + return Mapped::Unsupported { harmless: false }; + } + let Some(mut p) = layer_target(r) else { return Mapped::Unsupported { harmless: false } }; + match d.get("T ") { + Some(D::Descriptor(t)) => { + let unit = |k: &str| match t.get(k) { + Some(D::UnitFloat { unit, .. }) => Some(*unit), + _ => None, + }; + let (Some(dx), Some(dy)) = (get_num(t, "Hrzn"), get_num(t, "Vrtc")) else { return Mapped::Unsupported { harmless: false } }; + match (unit("Hrzn"), unit("Vrtc")) { + (Some(PX), Some(PX)) => { + p.insert("dx".into(), dx.round().into()); + p.insert("dy".into(), dy.round().into()); + } + // A nudge recorded with the rulers in other units: points, converted to pixels + // at the resolution of the document the action plays on. + (Some(PT), Some(PT)) => { + p.insert("dx".into(), dx.into()); + p.insert("dy".into(), dy.into()); + p.insert("units".into(), "pt".into()); + } + _ => return Mapped::Unsupported { harmless: false }, + } + step("layer.translate", Value::Object(p)) + } + Some(D::Reference(t)) => { + let id = match target(t) { + Target::Ordinal(o) if o == "Frnt" => "layer.arrange.bringToFront", + Target::Ordinal(o) if o == "Back" => "layer.arrange.sendToBack", + Target::Ordinal(o) if o == "Nxt" => "layer.arrange.bringForward", + Target::Ordinal(o) if o == "Prvs" => "layer.arrange.sendBackward", + Target::Offset(1) => "layer.arrange.bringForward", + Target::Offset(-1) => "layer.arrange.sendBackward", + // Index 0 is the bottom of the stack. + Target::Index(0) => "layer.arrange.sendToBack", + _ => return Mapped::Unsupported { harmless: false }, + }; + step(id, Value::Object(p)) + } + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn move_to(id: &str, p: &Value) -> Option { + let ord = |o: &str| D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: code("Ordn"), value: code(o) }]); + let t = match id { + "layer.translate" => { + let unit = match jstr(p, "units") { + None | Some("px") => PX, + Some("pt") => PT, + Some(_) => return None, + }; + let v = |k: &str| D::UnitFloat { unit, value: jnum(p, k).unwrap_or(0.0) }; + D::Descriptor(desc("Ofst").with("Hrzn", v("dx")).with("Vrtc", v("dy"))) + } + "layer.arrange.bringToFront" => ord("Frnt"), + "layer.arrange.sendToBack" => ord("Back"), + "layer.arrange.bringForward" => ord("Nxt "), + "layer.arrange.sendBackward" => ord("Prvs"), + _ => return None, + }; + Some(desc("null").with("null", layer_ref(p)?).with("T ", t)) +} + +pub(super) fn duplicate_from(d: &Descriptor) -> Mapped { + let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; + match ref_class(r).as_deref() { + Some("Lyr") => { + // A `T` document reference (duplicate into another open document) has no + // replayable meaning here: keep the step verbatim rather than misplay it. + if get_ref(d, "T ").is_some() { + return Mapped::Unsupported { harmless: false }; + } + let Some(mut p) = layer_target(r) else { return Mapped::Unsupported { harmless: false } }; + if let Some(n) = get_text(d, "Nm ") { + p.insert("name".into(), n.into()); + } + step("layer.duplicate", Value::Object(p)) + } + Some("Dcmn") => { + let mut p = Map::new(); + if let Some(n) = get_text(d, "Nm ") { + p.insert("name".into(), n.into()); + } + if let Some(m) = get_bool(d, "Mrgd") { + p.insert("mergedOnly".into(), m.into()); + } + step("image.duplicate", Value::Object(p)) + } + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn duplicate_to(id: &str, p: &Value) -> Option { + // Duplicate into a new document is a `Mk` (handled above); let it fall through. + if id == "layer.duplicate" && jstr(p, "document") == Some("new") { + return None; + } + // Photoshop's Duplicate has no in-place flag: a plain one would place the artboard copy beside + // the original on playback. + if id == "layer.duplicate" && jbool(p, "inPlace") == Some(true) { + return None; + } + let mut d = match id { + "layer.duplicate" => desc("null").with("null", layer_ref(p)?), + "image.duplicate" => { + desc("null").with("null", D::Reference(vec![ReferenceItem::Enumerated { class: class("Dcmn"), type_id: Id::new("Ordn"), value: Id::new("Frst") }])) + } + _ => return None, + }; + if let Some(n) = jstr(p, "name") { + d = d.with("Nm ", text(n)); + } + if let Some(m) = jbool(p, "mergedOnly") { + d = d.with("Mrgd", D::Boolean(m)); + } + Some(d) +} + +/// Only a comp name in the active document is portable across action playback. +pub(super) fn apply_comp_from(d: &Descriptor) -> Mapped { + match get_ref(d, "null") { + Some([ReferenceItem::Name { class, name }]) if trimmed(&class.class_id) == "compsClass" => { + step("layerComp.apply", json!({"comp": name.to_string_lossy()})) + } + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn apply_comp_to(_: &str, p: &Value) -> Option { + Some(desc("null").with("null", name_ref("compsClass", jstr(p, "comp")?))) +} + +pub(super) fn play_from(d: &Descriptor) -> Mapped { + match get_ref(d, "null").map(target) { + Some(Target::Name(n)) => step("actions.play", json!({"action": clip_name(&n)})), + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn play_to(_: &str, p: &Value) -> Option { + let name = jstr(p, "action")?; + // The Play Action descriptor written here carries no starting step, so a call from a later step is not a whole call. + if p.get("from").is_some_and(|v| !v.is_null() && v.as_f64() != Some(0.0)) { + return None; + } + let mut items = vec![ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul(name) }]; + if let Some(set) = jstr(p, "set") { + items.push(ReferenceItem::Name { class: class("ASet"), name: UnicodeString::new_nul(set) }); + } + Some(desc("null").with("null", D::Reference(items))) +} + +pub(super) fn fill_from(d: &Descriptor) -> Mapped { + if let Some(from) = get_obj(d, "From") { + // The Paint Bucket tool's click: its point is in pixels, or in percent of the canvas + // (not replayable without the document size). + let in_px = |k: &str| matches!(from.get(k), Some(D::UnitFloat { unit: PX, .. })); + let (Some(x), Some(y)) = (get_num(from, "Hrzn"), get_num(from, "Vrtc")) else { return Mapped::Unsupported { harmless: false } }; + if !in_px("Hrzn") || !in_px("Vrtc") { + return Mapped::Unsupported { harmless: false }; + } + let mut p = json!({"x": x.round(), "y": y.round()}); + match get_enum(d, "Usng").as_deref() { + Some("FrgC") | None => {} + Some("Pttn") => p["contents"] = json!("pattern"), + Some("Clr") => match get_obj(d, "Clr ").and_then(color_hex) { + Some(c) => p["color"] = json!(c), + None => return Mapped::Unsupported { harmless: false }, + }, + Some(_) => return Mapped::Unsupported { harmless: false }, + } + if let Some(t) = get_num(d, "Tlrn") { + p["tolerance"] = json!(t); + } + if let Some(c) = get_bool(d, "Cntg") { + p["contiguous"] = json!(c); + } + if let Some(a) = get_bool(d, "AntA") { + p["antiAlias"] = json!(a); + } + if let Some(m) = get_bool(d, "Mrgd") { + p["sampleAllLayers"] = json!(m); + } + if let Some(o) = get_num(d, "Opct") { + p["opacity"] = json!(o); + } + return step("paint.bucket", p); + } + let Some(contents) = get_enum(d, "Usng").and_then(|u| lookup(FILL_CONTENTS, &u)) else { return Mapped::Unsupported { harmless: false } }; + let mut p = json!({"contents": contents}); + if contents == "color" { + match get_obj(d, "Clr ").and_then(color_hex) { + Some(c) => p["color"] = json!(c), + None => return Mapped::Unsupported { harmless: false }, + } + } + if let Some(o) = get_num(d, "Opct") { + p["opacity"] = json!(o); + } + if let Some(m) = get_enum(d, "Md ") { + match blend_label(&m) { + Some(l) => p["mode"] = json!(l), + None => return Mapped::Unsupported { harmless: false }, + } + } + if let Some(t) = get_bool(d, "PrsT") { + p["preserveTransparency"] = json!(t); + } + step("edit.fill", p) +} + +pub(super) fn fill_to(id: &str, p: &Value) -> Option { + if id == "paint.bucket" { + let mut d = desc("null").with("From", D::Descriptor(desc("Pnt ").with("Hrzn", px(jnum(p, "x")?)).with("Vrtc", px(jnum(p, "y")?)))); + d = d.with("Tlrn", long(jnum(p, "tolerance").unwrap_or(32.0))).with("AntA", D::Boolean(jbool(p, "antiAlias").unwrap_or(true))); + // `source` is the command's older name for `contents`. + d = if p.get("contents").or_else(|| p.get("source")).and_then(Value::as_str) == Some("pattern") { + // `Pttn` names no pattern and holds no placement: a chosen pattern, a scale, an angle + // or a phase would replay with the current pattern at its defaults (#7543, #7544, + // #7545, #7546). + let num = |k: &str, default: f64| p.get(k).is_some_and(|v| !v.is_null() && v.as_f64() != Some(default)); + let phase = p.get("phase").is_some_and(|v| !v.is_null() && v.as_array().is_none_or(|a| a.iter().any(|c| c.as_f64() != Some(0.0)))); + if p.get("pattern").is_some_and(|v| !v.is_null()) || num("scale", 100.0) || num("angle", 0.0) || phase { + return None; + } + d.with("Usng", enm("FlCn", "Pttn")) + } else { + // An explicit colour overrides the foreground (#7199): it travels as Fill's `Clr `. + match bucket_color(p.get("color"))? { + Some(c) => d.with("Usng", enm("FlCn", "Clr ")).with("Clr ", D::Descriptor(c)), + None => d.with("Usng", enm("FlCn", "FrgC")), + } + }; + if let Some(o) = jnum(p, "opacity") { + d = d.with("Opct", pct(o)); + } + if let Some(c) = jbool(p, "contiguous") { + d = d.with("Cntg", D::Boolean(c)); + } + if let Some(m) = jbool(p, "sampleAllLayers") { + d = d.with("Mrgd", D::Boolean(m)); + } + return Some(d); + } + let contents = jstr(p, "contents").unwrap_or("color"); + let mut d = desc("null").with("Usng", enm("FlCn", lookup_back(FILL_CONTENTS, contents)?)); + if contents == "color" { + d = d.with("Clr ", D::Descriptor(color_desc(jstr(p, "color")?)?)); + } + if let Some(o) = jnum(p, "opacity") { + d = d.with("Opct", pct(o)); + } + if let Some(m) = jstr(p, "mode") { + d = d.with("Md ", enm("BlnM", blend_ps(m)?)); + } + if let Some(t) = jbool(p, "preserveTransparency") { + d = d.with("PrsT", D::Boolean(t)); + } + Some(d) +} + +/// The Paint Bucket's `color` as `paint.bucket` reads it (`[r, g, b(, a)]` in 0..=1 or +/// `#rrggbb(aa)`): `Some(None)` when it fills with the foreground (no colour, or a string the +/// command doesn't read), `None` when the colour can't be written (not opaque, or outside 0..=1). +fn bucket_color(v: Option<&Value>) -> Option> { + let rgba = match v { + Some(Value::Array(a)) if a.len() >= 3 => { + let c: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(); + [*c.first()?, *c.get(1)?, *c.get(2)?, c.get(3).copied().unwrap_or(1.0)] + } + Some(Value::String(h)) => { + let h = h.trim_start_matches('#'); + let c = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| f64::from(v) / 255.0); + let (Some(r), Some(g), Some(b)) = (c(0), c(2), c(4)) else { return Some(None) }; + [r, g, b, c(6).unwrap_or(1.0)] + } + _ => return Some(None), + }; + if rgba[3] != 1.0 || !rgba.iter().all(|v| (0.0..=1.0).contains(v)) { + return None; + } + Some(Some(desc("RGBC").with("Rd ", D::Double(rgba[0] * 255.0)).with("Grn ", D::Double(rgba[1] * 255.0)).with("Bl ", D::Double(rgba[2] * 255.0)))) +} + +/// Preserve the command's effective integer width instead of rounding its input again. +pub(super) fn stroke_to(_: &str, p: &Value) -> Option { + if !pixel_target(p) { + return None; + } + let mut params = if p.is_null() { Map::new() } else { p.as_object()?.clone() }; + params.insert("width".into(), Value::from(crate::extra_cmds::stroke_width(p))); + fields_to(&Value::Object(params), STROKE, desc("null")) +} + +pub(super) const STROKE: &[F] = &[ + F("Wdth", "width", Kind::Long), + F("Lctn", "location", Kind::Enum("StrL", STROKE_LOCATION)), + F("Opct", "opacity", Kind::Pct), + F("Md ", "mode", Kind::Blend), + F("Clr ", "color", Kind::Color), + F("PrsT", "preserveTransparency", Kind::Bool), +]; + +/// Whether an event's `null` reference targets a layer (Edit › Transform) rather than the +/// document (Image › Image Rotation). +fn targets_layer(d: &Descriptor) -> bool { + get_ref(d, "null").and_then(ref_class).as_deref() == Some("Lyr") +} + +pub(super) fn rotate_from(d: &Descriptor) -> Mapped { + let Some(angle) = get_num(d, "Angl") else { return Mapped::Unsupported { harmless: false } }; + let a = angle.rem_euclid(360.0); + let (layer, doc) = if (a - 90.0).abs() < 1e-6 { + ("edit.transform.rotate90Cw", "image.imageRotation.90cw") + } else if (a - 270.0).abs() < 1e-6 { + ("edit.transform.rotate90Ccw", "image.imageRotation.90ccw") + } else if (a - 180.0).abs() < 1e-6 { + ("edit.transform.rotate180", "image.imageRotation.180") + } else if targets_layer(d) { + return Mapped::Unsupported { harmless: false }; + } else { + let mut p = json!({"angle": angle.abs(), "direction": if angle < 0.0 { "ccw" } else { "cw" }}); + if let Some(i) = get_enum(d, "Intr").and_then(|i| lookup(INTERPOLATION, &i)).filter(|i| matches!(*i, "bicubic" | "bilinear" | "nearest")) { + p["interpolation"] = i.into(); + } + return step("image.rotation.arbitrary", p); + }; + none(if targets_layer(d) { layer } else { doc }) +} + +pub(super) fn rotate_to(id: &str, p: &Value) -> Option { + let (angle, layer) = match id { + "edit.transform.rotate90Cw" => (90.0, true), + "edit.transform.rotate90Ccw" => (-90.0, true), + "edit.transform.rotate180" => (180.0, true), + "image.imageRotation.90cw" => (90.0, false), + "image.imageRotation.90ccw" => (-90.0, false), + "image.imageRotation.180" => (180.0, false), + "image.rotation.arbitrary" => (jnum(p, "angle")? * if jstr(p, "direction") == Some("ccw") { -1.0 } else { 1.0 }, false), + _ => return None, + }; + let mut d = desc("null"); + if layer { + d = d.with("null", target_ref("Lyr ")); + } + d = d.with("Angl", ang(angle)); + if id == "image.rotation.arbitrary" + && let Some(i) = p.get("interpolation") + { + // The command resamples with nearest, bilinear or bicubic; any other value can't be + // carried faithfully, so refuse rather than replay with a different interpolation. + let i = match i.as_str()? { + "nearestNeighbor" => "nearest", + i @ ("bicubic" | "bilinear" | "nearest") => i, + _ => return None, + }; + d = d.with("Intr", enm("Intp", lookup_back(INTERPOLATION, i)?)); + } + Some(d) +} + +pub(super) fn flip_from(d: &Descriptor) -> Mapped { + let Some(axis) = get_enum(d, "Axis") else { return Mapped::Unsupported { harmless: false } }; + let horizontal = axis == "Hrzn"; + none(match (targets_layer(d), horizontal) { + (true, true) => "edit.transform.flipHorizontal", + (true, false) => "edit.transform.flipVertical", + (false, true) => "image.imageRotation.flipCanvasHorizontal", + (false, false) => "image.imageRotation.flipCanvasVertical", + }) +} + +pub(super) fn flip_to(id: &str, _: &Value) -> Option { + let (layer, axis) = match id { + "edit.transform.flipHorizontal" => (true, "Hrzn"), + "edit.transform.flipVertical" => (true, "Vrtc"), + "image.imageRotation.flipCanvasHorizontal" => (false, "Hrzn"), + "image.imageRotation.flipCanvasVertical" => (false, "Vrtc"), + _ => return None, + }; + let mut d = desc("null"); + if layer { + d = d.with("null", target_ref("Lyr ")); + } + Some(d.with("Axis", enm("Ornt", axis))) +} diff --git a/crates/engine/src/atn_cmds/steps_make.rs b/crates/engine/src/atn_cmds/steps_make.rs new file mode 100644 index 0000000000..696a1f17f8 --- /dev/null +++ b/crates/engine/src/atn_cmds/steps_make.rs @@ -0,0 +1,607 @@ +use super::adjustments::{HUE_RANGES, adjustment_by_class, adjustment_by_suffix, adjustment_steps}; +use super::descriptors::{ + PX, Target, ang, class, class_ref, code, color_desc, color_hex, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, get_ref, get_text, jbool, jnum, + jstr, layer_ref, layer_target, long, name_ref, pct, px, ref_class, target, target_ref, text, trimmed, +}; +use super::fields::{Mapped, none, step, steps}; +use super::steps_layer::quick_mask_ref; +use super::tables::{LABEL_COLORS, MODES, blend_label, blend_ps, lookup, lookup_back}; +use super::*; + +/// A `patternLayer` descriptor's pattern, scale, angle and link as the params of +/// `layer.newFillLayer.pattern` / `layer.fill.pattern.set`. The pattern goes by name: ids differ +/// between Photoshop's library and one rebuilt from the same `.pat` file. None for a pattern +/// recorded without a name or id. +fn pattern_params(t: &Descriptor) -> Option> { + let mut p = Map::new(); + if let Some(ptrn) = get_obj(t, "Ptrn") { + let key = get_text(ptrn, "Nm ").filter(|n| !n.is_empty()).or_else(|| get_text(ptrn, "Idnt").filter(|i| !i.is_empty()))?; + p.insert("pattern".into(), key.into()); + } + if let Some(s) = get_num(t, "Scl ") { + p.insert("scale".into(), s.into()); + } + if let Some(a) = get_num(t, "Angl") { + p.insert("angle".into(), a.into()); + } + if let Some(l) = get_bool(t, "Algn") { + p.insert("link".into(), l.into()); + } + Some(p) +} + +/// The `patternLayer` descriptor for [`pattern_params`]' params. +fn pattern_desc(p: &Value) -> Option { + let mut t = desc("patternLayer"); + if let Some(n) = jstr(p, "pattern") { + t = t.with("Ptrn", D::Descriptor(desc("Ptrn").with("Nm ", text(n)))); + } + if let Some(s) = jnum(p, "scale") { + t = t.with("Scl ", pct(s)); + } + if let Some(a) = jnum(p, "angle") { + t = t.with("Angl", ang(a)); + } + if let Some(l) = jbool(p, "link") { + t = t.with("Algn", D::Boolean(l)); + } + if p.get("phase").is_some() { + return None; + } + Some(t) +} + +/// Layer › Layer Mask: the `UsrM` value of an Add Layer Mask `Mk` ↔ its command. +const MASK_USING: &[(&str, &str)] = &[ + ("RvlA", "layer.layerMask.revealAll"), + ("HdAl", "layer.layerMask.hideAll"), + ("RvlS", "layer.layerMask.revealSelection"), + ("HdSl", "layer.layerMask.hideSelection"), +]; + +pub(super) fn make_from(d: &Descriptor) -> Mapped { + // Duplicate layer/group into a new document: `Mk` with a document class, a layer + // `Usng`, an optional `Nm` (the new document's name) and an optional `LyrN` + // (the copy's name). A `Dplc` with a `T` document reference (duplicate into another + // open document) stays a kept Photoshop step: document indices mean nothing at replay. + if let Some(r) = get_ref(d, "null") + && ref_class(r).as_deref() == Some("Dcmn") + && matches!(target(r), Target::Class) + && let Some(u) = get_ref(d, "Usng") + && matches!(ref_class(u).as_deref(), Some("Lyr") | Some("layerSection")) + && let Some(mut p) = layer_target(u) + { + p.insert("document".into(), "new".into()); + if let Some(n) = get_text(d, "Nm ") { + p.insert("documentName".into(), n.into()); + } + if let Some(n) = get_text(d, "LyrN") { + p.insert("name".into(), n.into()); + } + return step("layer.duplicate", Value::Object(p)); + } + // Add Layer Mask: a `Chnl` class made at the mask channel, `Usng` what it reveals. + if let Some(D::Class(c)) = d.get("Nw ") + && trimmed(&c.class_id) == "Chnl" + { + // The target layer's mask only: a further item (a `Lyr` by name…) puts it on another layer. + let at_mask = get_ref(d, "At ") + .is_some_and(|r| r.len() == 1 && ref_class(r).as_deref() == Some("Chnl") && matches!(target(r), Target::Ordinal(o) if o == "Msk")); + return match get_enum(d, "Usng").and_then(|u| lookup(MASK_USING, &u)) { + Some(id) if at_mask => none(id), + _ => Mapped::Unsupported { harmless: false }, + }; + } + if let Some(nw) = get_obj(d, "Nw ") { + // Layer via Copy / Cut (`Usng` = the selection), or a new document. + if get_enum(d, "Usng").as_deref() == Some("Slct") { + let id = if get_bool(d, "Cpy ") == Some(true) { "layer.new.layerViaCopy" } else { "layer.new.layerViaCut" }; + let mut v = vec![(id, json!({}))]; + if let Some(n) = get_text(nw, "Nm ") { + v.push(("layer.setProps", json!({"name": n}))); + } + return steps(v); + } + if get_text(nw, "preset").is_some() { + return none("file.newFromClipboard"); + } + if let (Some(w), Some(h)) = (get_num(nw, "Wdth"), get_num(nw, "Hght")) { + let res = get_num(nw, "Rslt").unwrap_or(72.0); + // Dimensions are in points (`#Rlt`) unless given in pixels. + let to_px = |k: &str, v: f64| match nw.get(k) { + Some(D::UnitFloat { unit: PX, .. }) => v, + _ => v * res / 72.0, + }; + let mut p = json!({"width": to_px("Wdth", w).round(), "height": to_px("Hght", h).round(), "resolution": res}); + if let Some(n) = get_text(nw, "Nm ") { + p["name"] = json!(n); + } + if let Some(D::Class(c)) = nw.get("Md ") + && let Some(m) = lookup(MODES, &trimmed(&c.class_id)) + { + p["mode"] = json!(m); + } + if let Some(depth) = get_num(nw, "Dpth") { + p["depth"] = json!(depth); + } + if let Some(f) = get_enum(nw, "Fl ") { + p["background"] = json!(match f.as_str() { + "Wht" => "white", + "BckC" => "backgroundColor", + "Trns" => "transparent", + _ => "white", + }); + } + return step("file.new", p); + } + return Mapped::Unsupported { harmless: false }; + } + let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; + let using = get_obj(d, "Usng"); + let type_desc = using.and_then(|u| get_obj(u, "Type")); + match ref_class(r).as_deref() { + Some("Lyr") => { + let mut p = Map::new(); + if let Some(u) = using { + if let Some(n) = get_text(u, "Nm ") { + p.insert("name".into(), n.into()); + } + if let Some(o) = get_num(u, "Opct") { + p.insert("opacity".into(), (o / 100.0).into()); + } + if let Some(m) = get_enum(u, "Md ").and_then(|m| blend_label(&m)) { + p.insert("mode".into(), m.into()); + } + } + step("layer.new.layer", Value::Object(p)) + } + Some("AdjL") => match type_desc.and_then(|t| adjustment_by_class(&trimmed(&t.class_id))) { + Some(a) => adjustment_steps(a, "layer.newAdjustmentLayer.", type_desc), + None => Mapped::Unsupported { harmless: false }, + }, + Some("contentLayer") => match type_desc { + Some(t) if t.class_id.is("solidColorLayer") => match get_obj(t, "Clr ").and_then(color_hex) { + Some(c) => step("layer.newFillLayer.solidColor", json!({"color": c})), + None => none("layer.newFillLayer.solidColor"), + }, + Some(t) if t.class_id.is("patternLayer") => match pattern_params(t) { + Some(p) => step("layer.newFillLayer.pattern", Value::Object(p)), + None => Mapped::Unsupported { harmless: false }, + }, + _ => Mapped::Unsupported { harmless: false }, + }, + Some("layerSection") => { + let mut p = Map::new(); + if let Some(n) = using.and_then(|u| get_text(u, "Nm ")) { + p.insert("name".into(), n.into()); + } + match get_ref(d, "From") { + // A named source layer stays the source (#7236); a target reference and an + // index/id source (our exporter never writes those) keep the old implicit + // import: the group lands on the current selection at playback. + Some(r) => { + if let Some(t) = layer_target(r) { + p.extend(t); + } + step("layer.groupLayers", Value::Object(p)) + } + None => step("layer.new.group", Value::Object(p)), + } + } + _ => Mapped::Unsupported { harmless: false }, + } +} + +pub(super) fn make_to(id: &str, p: &Value) -> Option { + let with_name = |cls: &str| { + let mut u = desc(cls); + if let Some(n) = jstr(p, "name") { + u = u.with("Nm ", text(n)); + } + u + }; + Some(match id { + "layer.new.layer" => { + // The descriptor carries the name, opacity and mode only. A step that also clips to + // the layer below, labels the layer, fills it with the neutral colour or places it + // below the active layer would replay as a different layer, so it isn't exported + // (strict export fails, a partial one skips it: #7502, #7512, #7513, #7514). + let set = |key: &str, default: Value| p.get(key).is_some_and(|v| !v.is_null() && *v != default); + if set("clipToPrevious", Value::Bool(false)) + || set("color", json!("none")) + || set("fillNeutral", Value::Bool(false)) + || set("position", json!("above")) + { + return None; + } + let mut u = with_name("Lyr "); + if let Some(o) = jnum(p, "opacity") { + u = u.with("Opct", pct(o * 100.0)); + } + if let Some(m) = jstr(p, "mode").and_then(blend_ps) { + u = u.with("Md ", enm("BlnM", m)); + } + desc("null").with("null", class_ref("Lyr ")).with("Usng", D::Descriptor(u)) + } + "layer.new.group" => desc("null").with("null", class_ref("layerSection")).with("Usng", D::Descriptor(with_name("layerSection"))), + "layer.groupLayers" => { + // An explicit source layer goes in by name like every other layer reference; a + // step without one keeps the target-layer form (#7236). + desc("null").with("null", class_ref("layerSection")).with("From", layer_ref(p)?).with("Usng", D::Descriptor(with_name("layerSection"))) + } + "layer.new.layerViaCopy" | "layer.new.layerViaCut" => { + let mut d = desc("null").with("Nw ", D::Descriptor(desc("Lyr "))).with("Usng", enm("ArSl", "Slct")); + if id == "layer.new.layerViaCopy" { + d = d.with("Cpy ", D::Boolean(true)); + } + d + } + "layer.newFillLayer.solidColor" => { + let mut t = desc("solidColorLayer"); + // The descriptor's colour is opaque RGB: a colour with alpha, or one it can't parse, + // would replay as the default black (#7507). + if let Some(c) = p.get("color").filter(|v| !v.is_null()) { + t = t.with("Clr ", D::Descriptor(c.as_str().and_then(color_desc)?)); + } + desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t)))) + } + "layer.newFillLayer.pattern" => { + if p.get("path").is_some() { + return None; + } + let t = pattern_desc(p)?; + desc("null").with("null", class_ref("contentLayer")).with("Usng", D::Descriptor(desc("contentLayer").with("Type", D::Descriptor(t)))) + } + "layer.duplicate" => { + // Duplicate into a new document is a `Mk`, not a `Dplc` (see `make_from`). + // Anything else falls through to the `Dplc` event below. + if jstr(p, "document") != Some("new") { + return None; + } + let mut d = desc("null").with("null", class_ref("Dcmn")).with("Usng", layer_ref(p)?); + if let Some(n) = jstr(p, "documentName") { + d = d.with("Nm ", text(n)); + } + if let Some(n) = jstr(p, "name") { + d = d.with("LyrN", text(n)); + } + d + } + "layer.layerMask.revealAll" | "layer.layerMask.hideAll" | "layer.layerMask.revealSelection" | "layer.layerMask.hideSelection" => { + // Photoshop adds the mask to the target layer only. + if p.get("layer").is_some() { + return None; + } + let at = D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code("Msk ") }]); + desc("null").with("Nw ", D::Class(class("Chnl"))).with("At ", at).with("Usng", enm("UsrM", lookup_back(MASK_USING, id)?)) + } + "file.newFromClipboard" => desc("null").with("Nw ", D::Descriptor(desc("Dcmn").with("preset", text("Clipboard")))), + "file.new" => { + let mut n = desc("Dcmn"); + if let Some(name) = jstr(p, "name") { + n = n.with("Nm ", text(name)); + } + if let Some(m) = jstr(p, "mode").and_then(|m| lookup_back(MODES, if m == "gray" { "grayscale" } else { m })) { + n = n.with("Md ", D::Class(class(m))); + } + n = n.with("Wdth", px(jnum(p, "width").unwrap_or(1920.0))).with("Hght", px(jnum(p, "height").unwrap_or(1080.0))); + n = n.with("Rslt", D::UnitFloat { unit: *b"#Rsl", value: jnum(p, "resolution").unwrap_or(72.0) }); + // `Fl ` is white, transparent or Photoshop's own background colour: black, a hex + // colour or a given `backgroundColor` would replay as something else (#7503). + if p.get("backgroundColor").is_some_and(|v| !v.is_null()) { + return None; + } + let fill = match p.get("background").filter(|v| !v.is_null()) { + None => "Wht ", + Some(b) => match b.as_str()? { + "white" => "Wht ", + "transparent" => "Trns", + "backgroundColor" => "BckC", + _ => return None, + }, + }; + n = n.with("Fl ", enm("Fl ", fill)).with("Dpth", long(jnum(p, "depth").unwrap_or(8.0))); + desc("null").with("Nw ", D::Descriptor(n)) + } + _ => { + let suffix = id.strip_prefix("layer.newAdjustmentLayer.")?; + let a = adjustment_by_suffix(suffix)?; + let t = if p.as_object().is_some_and(|o| o.is_empty()) { + desc(a.class).with("presetKind", enm("presetKindType", "presetKindDefault")) + } else { + (a.to)(p)? + }; + desc("null").with("null", class_ref("AdjL")).with("Usng", D::Descriptor(desc("AdjL").with("Type", D::Descriptor(t)))) + } + }) +} + +pub(super) fn set_from(d: &Descriptor) -> Mapped { + let Some(r) = get_ref(d, "null") else { return Mapped::Unsupported { harmless: false } }; + let unsupported = Mapped::Unsupported { harmless: false }; + match (ref_class(r).as_deref(), target(r)) { + (Some("Chnl"), Target::Property(p)) if p == "fsel" => match d.get("T ") { + Some(D::Enumerated { value, .. }) => match trimmed(value).as_str() { + "Al" => none("select.all"), + "None" => none("select.deselect"), + "Prvs" => none("select.reselect"), + _ => unsupported, + }, + Some(D::Reference(t)) => match (ref_class(t).as_deref(), target(t)) { + (Some("Chnl"), Target::Ordinal(o)) if o == "Trsp" => step("select.loadSelection", json!({"channel": "transparency"})), + // ⌘-click on the targeted channel (a layer mask after `select` of `Msk`). + (Some("Chnl"), Target::Ordinal(o)) if o == "Trgt" => step("select.loadSelection", json!({"channel": "targeted"})), + (Some("Chnl"), Target::Name(n)) => step("select.loadSelection", json!({"channel": n})), + _ => unsupported, + }, + Some(D::Descriptor(t)) if t.class_id.is("Plgn") => { + let pts: Option> = get_list(t, "Pts ") + .unwrap_or(&[]) + .iter() + .map(|v| match v { + D::Descriptor(pt) => Some(json!([get_num(pt, "Hrzn")?, get_num(pt, "Vrtc")?])), + _ => None, + }) + .collect(); + match pts { + Some(pts) if pts.len() >= 3 => step("select.lasso", json!({"points": pts})), + _ => unsupported, + } + } + Some(D::Descriptor(t)) if t.class_id.is("Rctn") || t.class_id.is("Elps") => { + let (Some(top), Some(left), Some(bottom), Some(right)) = (get_num(t, "Top "), get_num(t, "Left"), get_num(t, "Btom"), get_num(t, "Rght")) + else { + return unsupported; + }; + let mut p = json!({"x": left.round(), "y": top.round(), "width": (right - left).round().max(0.0), "height": (bottom - top).round().max(0.0)}); + if t.class_id.is("Elps") { + p["ellipse"] = json!(true); + } + step("select.rect", p) + } + _ => unsupported, + }, + // 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})), + // 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" => { + // On an image that opened as a normal layer there is no Background to convert; + // Photoshop stops there, but the step's purpose (an editable layer) is met. + // Photoshop's `set` of another layer doesn't target it: the selected layer stays. + let mut v = vec![("layer.new.layerFromBackground", json!({"ifPresent": true, "select": false}))]; + let mut props = Map::new(); + props.insert("layer".into(), "Layer 0".into()); + if let Some(t) = get_obj(d, "T ") { + if let Some(n) = get_text(t, "Nm ") { + props.insert("name".into(), n.into()); + } + if let Some(o) = get_num(t, "Opct").filter(|o| (o - 100.0).abs() > 1e-9) { + props.insert("opacity".into(), (o / 100.0).into()); + } + match get_enum(t, "Md ").as_deref() { + None | Some("Nrml") => {} + Some(m) => match blend_label(m) { + Some(label) => { + props.insert("blend".into(), label.into()); + } + None => return unsupported, + }, + } + } + if props.len() > 1 { + v.push(("layer.setProps", Value::Object(props))); + } + steps(v) + } + // The toolbox colours. + (Some("Clr"), Target::Property(p)) if p == "FrgC" || p == "BckC" => match get_obj(d, "T ").and_then(color_hex) { + Some(hex) => step("tools.setColors", json!({(if p == "FrgC" { "foreground" } else { "background" }): hex})), + None => unsupported, + }, + (Some("Lyr"), _) => { + let Some(mut p) = layer_target(r) else { return unsupported }; + let Some(t) = get_obj(d, "T ") else { return unsupported }; + let mut v = Vec::new(); + if let Some(c) = get_enum(t, "Clr ").and_then(|c| lookup(LABEL_COLORS, &c)) { + let mut lp = p.clone(); + lp.insert("color".into(), c.into()); + v.push(("layer.setLabelColor", Value::Object(lp))); + } + if let Some(n) = get_text(t, "Nm ") { + p.insert("name".into(), n.into()); + } + if let Some(o) = get_num(t, "Opct") { + p.insert("opacity".into(), (o / 100.0).into()); + } + if let Some(f) = get_num(t, "fillOpacity") { + p.insert("fill".into(), (f / 100.0).into()); + } + if let Some(m) = get_enum(t, "Md ") { + let Some(label) = blend_label(&m) else { return unsupported }; + p.insert("blend".into(), label.into()); + } + if let Some(vis) = get_bool(t, "Vsbl") { + p.insert("visible".into(), vis.into()); + } + if p.keys().any(|k| k != "layer") { + v.push(("layer.setProps", Value::Object(p))); + } + if v.is_empty() { unsupported } else { steps(v) } + } + // A Pattern Fill layer's pattern (double-click its thumbnail). + (Some("contentLayer"), Target::Ordinal(o)) if o == "Trgt" => match get_obj(d, "T ") { + Some(t) if t.class_id.is("patternLayer") => match pattern_params(t) { + Some(p) if !p.is_empty() => step("layer.fill.pattern.set", Value::Object(p)), + _ => unsupported, + }, + _ => unsupported, + }, + (Some("AdjL"), Target::Ordinal(o)) if o == "Trgt" => { + match get_obj(d, "T ").and_then(|t| adjustment_by_class(&trimmed(&t.class_id)).map(|a| (a, t))) { + Some((a, t)) => match (a.from)(t) { + // `kind` names the adjustment so Save Actions can write the class back. + // Not on an empty set (Photoshop's "reset to default"): params with any key + // merge, none reset. + Some(mut p) => { + if let Some(o) = p.as_object_mut().filter(|o| !o.is_empty()) { + o.insert("kind".into(), json!(a.suffix)); + } + step("layer.setAdjustment", p) + } + None => unsupported, + }, + None => unsupported, + } + } + _ => unsupported, + } +} + +pub(super) fn set_to(id: &str, p: &Value) -> Option { + let fsel = D::Reference(vec![ReferenceItem::Property { class: class("Chnl"), key: Id::new("fsel") }]); + let sel = |t: D| desc("null").with("null", fsel.clone()).with("T ", t); + Some(match id { + "select.all" => sel(enm("Ordn", "Al ")), + "select.deselect" => sel(enm("Ordn", "None")), + "select.reselect" => sel(enm("Ordn", "Prvs")), + // The descriptor loads a plain new selection: inverting it or combining it with the current + // one (add, subtract, intersect) would be lost (#7506). + "select.loadSelection" + if p.get("invert").is_some_and(|v| *v != Value::Bool(false) && !v.is_null()) + || p.get("operation").is_some_and(|v| *v != json!("new") && !v.is_null()) => + { + return None; + } + "select.loadSelection" => match jstr(p, "channel")? { + "transparency" => sel(D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: Id::new("Chnl"), value: Id::new("Trsp") }])), + "targeted" => sel(D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: Id::new("Ordn"), value: Id::new("Trgt") }])), + name => sel(name_ref("Chnl", name)), + }, + "select.lasso" => { + let pts: Option> = p + .get("points")? + .as_array()? + .iter() + .map(|pt| { + let a = pt.as_array()?; + Some(D::Descriptor(desc("Pnt ").with("Hrzn", px(a.first()?.as_f64()?)).with("Vrtc", px(a.get(1)?.as_f64()?)))) + }) + .collect(); + sel(D::Descriptor(desc("Plgn").with("Pts ", D::List(pts?)))) + } + "select.editInQuickMaskMode" => { + if jbool(p, "on") != Some(true) { + return None; + } + desc("null").with("null", quick_mask_ref()) + } + "tools.setColors" => { + // One colour per Photoshop step: a step that sets both (or any other key) doesn't + // export rather than lose one. + if p.as_object().is_some_and(|o| o.keys().any(|k| k != "foreground" && k != "background")) { + return None; + } + let (key, hex) = match (jstr(p, "foreground"), jstr(p, "background")) { + (Some(f), None) => ("FrgC", f), + (None, Some(b)) => ("BckC", b), + _ => return None, + }; + desc("null") + .with("null", D::Reference(vec![ReferenceItem::Property { class: class("Clr "), key: code(key) }])) + .with("T ", D::Descriptor(color_desc(hex)?)) + } + "select.rect" => { + match jstr(p, "mode") { + None | Some("replace") => {} + Some(_) => return None, + } + let (x, y, w, h) = (jnum(p, "x")?, jnum(p, "y")?, jnum(p, "width")?, jnum(p, "height")?); + let cls = if jbool(p, "ellipse") == Some(true) { "Elps" } else { "Rctn" }; + sel(D::Descriptor(desc(cls).with("Top ", px(y)).with("Left", px(x)).with("Btom", px(y + h)).with("Rght", px(x + w)))) + } + "layer.setProps" | "layer.renameLayer" | "layer.setLabelColor" => { + // Only these keys map onto the `Lyr ` descriptor; locks, clipping, Advanced Blending + // channels or an explicit `layers` list would be dropped (#7196, #7246). + const MAPPED: [&str; 7] = ["layer", "name", "opacity", "fill", "blend", "visible", "color"]; + if p.as_object().is_some_and(|m| m.iter().any(|(k, v)| !v.is_null() && !MAPPED.contains(&k.as_str()))) { + return None; + } + let mut t = desc("Lyr "); + if let Some(n) = jstr(p, "name") { + t = t.with("Nm ", text(n)); + } + if let Some(o) = jnum(p, "opacity") { + t = t.with("Opct", pct(o * 100.0)); + } + if let Some(f) = jnum(p, "fill") { + t = t.with("fillOpacity", pct(f * 100.0)); + } + if let Some(m) = jstr(p, "blend") { + t = t.with("Md ", enm("BlnM", blend_ps(m)?)); + } + if let Some(v) = jbool(p, "visible") { + t = t.with("Vsbl", D::Boolean(v)); + } + if let Some(c) = jstr(p, "color") { + t = t.with("Clr ", enm("Clr ", lookup_back(LABEL_COLORS, c)?)); + } + if t.items.is_empty() { + return None; + } + desc("null").with("null", layer_ref(p)?).with("T ", D::Descriptor(t)) + } + "layer.new.layerFromBackground" => { + let bckg = D::Reference(vec![ReferenceItem::Property { class: class("Lyr "), key: Id::new("Bckg") }]); + desc("null").with("null", bckg).with("T ", D::Descriptor(desc("Lyr ").with("Opct", pct(100.0)).with("Md ", enm("BlnM", "Nrml")))) + } + "layer.fill.pattern.set" => { + if p.get("layer").is_some() || p.get("document").is_some() { + return None; + } + desc("null").with("null", target_ref("contentLayer")).with("T ", D::Descriptor(pattern_desc(p)?)) + } + "layer.setAdjustment" => { + // The adjustment kind isn't in the params: Photoshop needs it, so only steps that + // name one (`kind`) export. + let kind = jstr(p, "kind")?; + // `layer.setAdjustment` changes only the settings it names. Color Balance and + // Hue/Saturation descriptors carry every setting, filling absent ones with defaults, + // so a partial edit would replay as one that also resets the rest (#8531). + // Present and of the shape the writer reads: anything else it would write as 0. + let number = |p: &Value, k: &str| p.get(k).and_then(Value::as_f64).is_some_and(f64::is_finite); + let numbers = |p: &Value, keys: &[&str]| keys.iter().all(|k| number(p, k)); + let flag = |k: &str| p.get(k).is_some_and(Value::is_boolean); + let triplet = + |k: &str| p.get(k).and_then(Value::as_array).is_some_and(|a| a.len() == 3 && a.iter().all(|v| v.as_f64().is_some_and(f64::is_finite))); + let complete = match kind { + "colorBalance" => ["shadows", "midtones", "highlights"].iter().all(|k| triplet(k)) && flag("preserveLuminosity"), + // Every colour range written carries its own hue, saturation and lightness too. + "hueSaturation" => { + flag("colorize") + && numbers(p, &["hue", "saturation", "lightness"]) + && HUE_RANGES.iter().filter_map(|r| p.get(*r).filter(|v| !v.is_null())).all(|r| { + // Bounds, when given, are the four whole numbers `hue_entry` writes (as integers); + // otherwise it drops or rounds them. + let bounds = r.get("range").filter(|v| !v.is_null()).is_none_or(|v| { + v.as_array().is_some_and(|a| a.len() == 4 && a.iter().all(|b| b.as_f64().is_some_and(|b| b.is_finite() && b.fract() == 0.0))) + }); + r.is_object() && numbers(r, &["hue", "saturation", "lightness"]) && bounds + }) + } + _ => true, + }; + if !complete { + return None; + } + let a = adjustment_by_suffix(kind)?; + desc("null").with("null", target_ref("AdjL")).with("T ", D::Descriptor((a.to)(p)?)) + } + _ => return None, + }) +} + +/// Tool classes Photoshop records when an action switches tools: no document effect. +pub(super) fn is_tool_class(c: &str) -> bool { + c.ends_with("Tl") || c.ends_with("Tool") +} diff --git a/crates/engine/src/atn_cmds/tables.rs b/crates/engine/src/atn_cmds/tables.rs new file mode 100644 index 0000000000..13b4bb9e8d --- /dev/null +++ b/crates/engine/src/atn_cmds/tables.rs @@ -0,0 +1,180 @@ +use super::descriptors::{Target, class, code, get_ref, target}; +use super::*; + +/// Photoshop's `BlnM` enumeration ↔ PhotoCraft's blend mode labels. +const BLEND_MODES: &[(&str, &str)] = &[ + ("Nrml", "Normal"), + ("normal", "Normal"), + ("Dslv", "Dissolve"), + ("dissolve", "Dissolve"), + ("Drkn", "Darken"), + ("darken", "Darken"), + ("Mltp", "Multiply"), + ("multiply", "Multiply"), + ("CBrn", "Color Burn"), + ("colorBurn", "Color Burn"), + ("linearBurn", "Linear Burn"), + ("darkerColor", "Darker Color"), + ("Lghn", "Lighten"), + ("lighten", "Lighten"), + ("Scrn", "Screen"), + ("screen", "Screen"), + ("CDdg", "Color Dodge"), + ("colorDodge", "Color Dodge"), + ("linearDodge", "Linear Dodge (Add)"), + ("lighterColor", "Lighter Color"), + ("Ovrl", "Overlay"), + ("overlay", "Overlay"), + ("SftL", "Soft Light"), + ("softLight", "Soft Light"), + ("HrdL", "Hard Light"), + ("hardLight", "Hard Light"), + ("vividLight", "Vivid Light"), + ("linearLight", "Linear Light"), + ("pinLight", "Pin Light"), + ("hardMix", "Hard Mix"), + ("Dfrn", "Difference"), + ("difference", "Difference"), + ("Xclu", "Exclusion"), + ("exclusion", "Exclusion"), + ("blendSubtraction", "Subtract"), + ("blendDivide", "Divide"), + ("H", "Hue"), + ("hue", "Hue"), + ("Strt", "Saturation"), + ("saturation", "Saturation"), + ("Clr", "Color"), + ("color", "Color"), + ("Lmns", "Luminosity"), + ("luminosity", "Luminosity"), + ("PsTh", "Pass Through"), + ("passThrough", "Pass Through"), +]; + +pub(super) fn blend_label(ps: &str) -> Option<&'static str> { + BLEND_MODES.iter().find(|(k, _)| *k == ps).map(|(_, v)| *v) +} + +pub(super) fn blend_ps(label: &str) -> Option<&'static str> { + crate::commands::blend_from_str(label).and_then(|m| BLEND_MODES.iter().find(|(_, v)| crate::commands::blend_from_str(v) == Some(m))).map(|(k, _)| *k) +} + +/// Photoshop ↔ PhotoCraft value tables; Photoshop codes compare without their space padding. +pub(super) fn lookup<'a>(table: &'a [(&'a str, &'a str)], key: &str) -> Option<&'a str> { + table.iter().find(|(k, _)| k.trim_end() == key.trim_end()).map(|(_, v)| *v) +} + +pub(super) fn lookup_back<'a>(table: &'a [(&'a str, &'a str)], value: &str) -> Option<&'a str> { + table.iter().find(|(_, v)| *v == value).map(|(k, _)| *k) +} + +/// `Chnl` enumeration ↔ the per-channel keys of the adjustment commands. +pub(super) const CHANNELS: &[(&str, &str)] = &[ + ("Rd", "red"), + ("Grn", "green"), + ("Bl", "blue"), + ("Gry", "gray"), + ("Cyn", "cyan"), + ("Mgnt", "magenta"), + ("Yllw", "yellow"), + ("Blck", "black"), + ("Lmnc", "lightness"), + ("A", "a"), + ("B", "b"), +]; + +/// The channel an adjustment entry's `Chnl` reference names: `None` = the composite. +pub(super) fn channel_key(d: &Descriptor) -> Option> { + let r = get_ref(d, "Chnl")?; + Some(match target(r) { + Target::Ordinal(o) if o == "Trgt" || o == "Cmps" => None, + Target::Ordinal(o) => Some(lookup(CHANNELS, &o)?), + _ => return None, + }) +} + +/// A Levels or Curves entry's channel: `Chnl.Cmps` for the composite, as Photoshop records it. +/// Photoshop silently skips a Set whose composite is `Ordn.Trgt` (#8543). +pub(super) fn channel_ref(key: Option<&str>) -> D { + let value = key.and_then(|k| lookup_back(CHANNELS, k)); + D::Reference(vec![ReferenceItem::Enumerated { class: class("Chnl"), type_id: code("Chnl"), value: code(value.unwrap_or("Cmps")) }]) +} + +pub(super) const INTERPOLATION: &[(&str, &str)] = &[ + ("Bcbc", "bicubic"), + ("Blnr", "bilinear"), + ("Nrst", "nearest"), + ("bicubicSharper", "bicubicSharper"), + ("bicubicSmoother", "bicubicSmoother"), + ("bicubicAutomatic", "bicubicAutomatic"), + ("automaticInterpolation", "automatic"), + ("preserveDetailsUpscale", "preserveDetails"), + ("deepUpscale", "preserveDetails"), +]; + +pub(super) const NOISE: &[(&str, &str)] = &[("Unfr", "uniform"), ("Gsn ", "gaussian")]; + +pub(super) const OFFSET_FILL: &[(&str, &str)] = &[("Wrp ", "wrap"), ("Rpt ", "repeat"), ("Bckg", "transparent")]; + +pub(super) const TRIM: &[(&str, &str)] = &[("Trns", "transparent"), ("topLeftPixelColor", "topLeft"), ("bottomRightPixelColor", "bottomRight")]; + +pub(super) const EXTENSION: &[(&str, &str)] = &[("Bckg", "background"), ("Frgd", "foreground"), ("Wht ", "white"), ("Blck", "black"), ("Trns", "transparent")]; + +pub(super) const FILL_CONTENTS: &[(&str, &str)] = &[ + ("FrgC", "foreground"), + ("BckC", "background"), + ("Wht ", "white"), + ("Blck", "black"), + ("Gry ", "gray"), + ("Clr ", "color"), + ("HstS", "history"), + ("contentAware", "contentAware"), +]; + +pub(super) const STROKE_LOCATION: &[(&str, &str)] = &[("Insd", "inside"), ("Cntr", "center"), ("OtsF", "outside")]; + +pub(super) const INTENT: &[(&str, &str)] = &[("Img ", "perceptual"), ("Clrm", "relative"), ("Grp ", "saturation"), ("AbsC", "absolute")]; + +pub(super) const PROFILES: &[(&str, &str)] = + &[("sRGB IEC61966-2.1", "srgb"), ("Display P3", "display-p3"), ("Adobe RGB (1998)", "adobe-rgb-compat"), ("ProPhoto RGB", "prophoto-compat")]; + +/// Smart Blur quality. Photoshop's codes come first, so they are what an export writes (measured in +/// Photoshop: `Hgh `/`Mdm `/`Low ` play back as its fallback, low quality). The old codes after +/// them still read, for actions PhotoCraft wrote before. +pub(super) const SMART_BLUR_QUALITY: &[(&str, &str)] = + &[("SBQL", "low"), ("SBQM", "medium"), ("SBQH", "high"), ("Hgh ", "high"), ("Mdm ", "medium"), ("Low ", "low")]; + +pub(super) const SMART_BLUR_MODE: &[(&str, &str)] = &[("SBMN", "normal"), ("SBME", "edgeOnly"), ("SBMO", "overlayEdge")]; + +pub(super) const RADIAL_METHOD: &[(&str, &str)] = &[("Spn ", "spin"), ("Zm ", "zoom")]; + +pub(super) const RADIAL_QUALITY: &[(&str, &str)] = &[("Drft", "draft"), ("Gd ", "good"), ("Bst ", "best")]; + +pub(super) const LABEL_COLORS: &[(&str, &str)] = + &[("None", "none"), ("Rd", "red"), ("Orng", "orange"), ("Ylw", "yellow"), ("Grn", "green"), ("Bl", "blue"), ("Vlt", "violet"), ("Gry", "gray")]; + +pub(super) const ALIGN: &[(&str, &str)] = + &[("AdLf", "leftEdges"), ("AdCH", "horizontalCenters"), ("AdRg", "rightEdges"), ("AdTp", "topEdges"), ("AdCV", "verticalCenters"), ("AdBt", "bottomEdges")]; + +pub(super) const PURGE: &[(&str, &str)] = &[("Al", "all"), ("Clpb", "clipboard"), ("Hsty", "histories"), ("Undo", "undo")]; + +pub(super) const MODES: &[(&str, &str)] = &[("RGBM", "rgb"), ("Grys", "grayscale"), ("CMYM", "cmyk"), ("LbCM", "lab"), ("Mltc", "multichannel")]; + +/// `MnIt` menu-item codes ↔ the shell's view commands. +pub(super) const MENU_ITEMS: &[(&str, &str)] = + &[("FtOn", "view.fitOnScreen"), ("ActP", "view.actualPixels"), ("ZmIn", "view.zoomIn"), ("ZmOt", "view.zoomOut")]; + +/// Save As format classes (`As`) and the extensions PhotoCraft saves them under. The first +/// extension of a class is the one exported, and the first class of an extension is the one +/// written back. `WebPFormat` is Photoshop's built-in WebP (checked against Photoshop 2026); the +/// Google classes come from the older WebPShop plug-in and are only read. +pub(super) const SAVE_FORMATS: &[(&str, &[&str])] = &[ + ("Pht3", &["psd"]), + ("PNGF", &["png"]), + ("JPEG", &["jpg", "jpeg"]), + ("TIFF", &["tif", "tiff"]), + ("BMPF", &["bmp"]), + ("WebPFormat", &["webp"]), + ("Google WebPShop", &["webp"]), + ("Google WebP", &["webp"]), +]; From 2fd1e065a19883698ce18f719394ab52415adb2c Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:57:27 +0000 Subject: [PATCH 202/259] refactor(engine): split prefs.rs into prefs/ --- crates/engine/src/prefs.rs | 1316 +------------------------- crates/engine/src/prefs/cmds.rs | 197 ++++ crates/engine/src/prefs/customize.rs | 306 ++++++ crates/engine/src/prefs/files.rs | 199 ++++ crates/engine/src/prefs/shortcuts.rs | 213 +++++ crates/engine/src/prefs/store.rs | 123 +++ crates/engine/src/prefs/validate.rs | 272 ++++++ 7 files changed, 1329 insertions(+), 1297 deletions(-) create mode 100644 crates/engine/src/prefs/cmds.rs create mode 100644 crates/engine/src/prefs/customize.rs create mode 100644 crates/engine/src/prefs/files.rs create mode 100644 crates/engine/src/prefs/shortcuts.rs create mode 100644 crates/engine/src/prefs/store.rs create mode 100644 crates/engine/src/prefs/validate.rs diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 1525741a5e..24cba73d4d 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -433,6 +433,25 @@ impl Default for Tools { /// since a whole-section update or a hand-edited preferences file can store anything. pub use photocraft_paint::ResponseCurve as PressureCurve; +mod cmds; +mod customize; +mod files; +mod shortcuts; +mod store; +mod validate; + +pub use cmds::specs; +#[cfg(test)] +pub(crate) use files::write_files_atomically; +pub use shortcuts::{ + ALTERNATE_SHORTCUTS, BindKind, MAX_ALTERNATES, TEMPORARY_TOOLS, alternate_keys, bindable_items, conflicts, default_alternates, normalize_shortcut, + reserved_shortcut, +}; +use store::read_lenient; +pub use store::{InvalidPref, PREFS_VERSION, PrefsStore}; +pub use validate::{HIDDEN_UNTIL_IMPLEMENTED, LINUX_ONLY, SECTIONS, choices, gpu_adapter_matches, is_color, is_hidden, parse_hex, range}; +use validate::{check_value, get_path, keyed, set_path}; + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct HistoryLog { @@ -1122,276 +1141,6 @@ pub struct Preferences { pub layer_mask_overlay: LayerMaskOverlay, } -/// Preferences dialog sections in Photoshop's order: (id, title). -pub const SECTIONS: [(&str, &str); 18] = [ - ("general", "General"), - ("interface", "Interface"), - ("workspace", "Workspace"), - ("tools", "Tools"), - ("historyLog", "History Log"), - ("fileHandling", "File Handling"), - ("export", "Export"), - ("performance", "Performance"), - ("scratchDisks", "Scratch Disks"), - ("cursors", "Cursors"), - ("transparencyAndGamut", "Transparency & Gamut"), - ("unitsAndRulers", "Units & Rulers"), - ("guidesGridAndSlices", "Guides, Grid & Slices"), - ("plugIns", "Plug-ins"), - ("type", "Type"), - ("enhancedControls", "Enhanced Controls"), - ("rawDefaults", "Camera Raw Defaults"), - ("integrations", "Integrations"), -]; - -/// Preferences that nothing reads yet, so Edit › Preferences doesn't show them: a control that -/// does nothing is worse than a missing one (https://github.com/storytold/photocraft/issues/204). -/// They still load, save and round-trip through `prefs.get` / `prefs.set` unchanged. -/// -/// When you implement one, remove it here; the `prefs_usage` test fails while a listed -/// preference is read anywhere outside `prefs.rs`, and while an unlisted one is read nowhere. -pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[ - "general.colorPicker", - "workspace.autoShowHiddenPanels", - "workspace.enableFloatingDocumentWindowDocking", - "performance.effectCacheMb", - "performance.legacyCompositing", - "scratchDisks.disks", - "unitsAndRulers.columnWidth", - "unitsAndRulers.gutter", - "plugIns.showExtensionPanels", - "plugIns.allowScriptsToConnect", - "type.textEngine", - "enhancedControls.scrubbySliderAcceleration", -]; - -/// Is the preference at `path` (`"section.key"`) hidden from the Preferences dialog? -pub fn is_hidden(path: &str) -> bool { - HIDDEN_UNTIL_IMPLEMENTED.contains(&path) || (!cfg!(target_os = "linux") && LINUX_ONLY.contains(&path)) -} - -/// Preferences that only do something on Linux; the dialog doesn't show them elsewhere. They -/// still load, save and round-trip on every platform. -pub const LINUX_ONLY: &[&str] = &["performance.linuxDisplayServer", "performance.gpuAdapter"]; - -/// Whether a graphics adapter called `name` is the one `performance.gpuAdapter` (`wanted`) asks -/// for: every whitespace-separated word of `wanted` appears in the name, ignoring case ("nvidia", -/// "arc a370m"). An empty `wanted` matches nothing. Startup and Preferences share this. -pub fn gpu_adapter_matches(name: &str, wanted: &str) -> bool { - let name = name.to_lowercase(); - let mut words = wanted.split_whitespace().peekable(); - words.peek().is_some() && words.all(|w| name.contains(&w.to_lowercase())) -} - -/// Choices of an enumerated preference (dotted path, e.g. `"cursors.painting"`). -pub fn choices(path: &str) -> Option<&'static [&'static str]> { - Some(match path { - "general.colorPicker" => ColorPicker::NAMES, - "general.imageInterpolation" => Interpolation::NAMES, - "interface.theme" => Theme::NAMES, - "interface.appearanceMode" => AppearanceMode::NAMES, - "interface.darkTheme" => DarkTheme::NAMES, - "interface.lightTheme" => LightTheme::NAMES, - "interface.canvasColor" => CanvasColor::NAMES, - "interface.canvasBorder" => CanvasBorder::NAMES, - "interface.uiScale" => UiScale::NAMES, - "interface.uiFontSize" => UiFontSize::NAMES, - "historyLog.destination" => LogDestination::NAMES, - "historyLog.detail" => LogDetail::NAMES, - "fileHandling.imagePreviews" | "fileHandling.maximizePsdCompatibility" => Ask::NAMES, - "export.quickExportFormat" => QuickExportFormat::NAMES, - "export.quickExportLocation" => ExportLocation::NAMES, - "export.metadata" => ExportMetadata::NAMES, - "cursors.painting" => PaintingCursor::NAMES, - "cursors.other" => OtherCursor::NAMES, - "tools.rightClickWithPaintingTools" => RightClickPaint::NAMES, - "transparencyAndGamut.gridSize" => CheckerSize::NAMES, - "transparencyAndGamut.gridColors" => CheckerColors::NAMES, - "unitsAndRulers.rulers" | "guidesGridAndSlices.gridUnit" => Unit::NAMES, - "unitsAndRulers.typeUnits" => TypeUnit::NAMES, - "unitsAndRulers.pointSize" => PointSize::NAMES, - "guidesGridAndSlices.guideStyle" | "guidesGridAndSlices.gridStyle" => LineStyle::NAMES, - "type.textEngine" => TextEngine::NAMES, - "type.fontPreview" => FontPreview::NAMES, - "rawDefaults.colorSpace" => RawColorSpace::NAMES, - "rawDefaults.bitDepth" => RawDepth::NAMES, - "rawDefaults.sharpenFor" => RawSharpen::NAMES, - "rawDefaults.demosaic" => RawDemosaic::NAMES, - "performance.gpuBackend" => GpuBackend::NAMES, - "performance.linuxDisplayServer" => LinuxDisplayServer::NAMES, - "performance.renderingMode" => RenderingMode::NAMES, - _ => return None, - }) -} - -/// Valid range of a numeric preference. -pub fn range(path: &str) -> Option<(f64, f64)> { - Some(match path { - "fileHandling.autosaveMinutes" => (1.0, 240.0), - "fileHandling.recentFileCount" => (0.0, 100.0), - "tools.nudgeBundlePauseMs" => (100.0, 10_000.0), - "fileHandling.rasterizeSvgGroupsDeeperThan" => (0.0, photocraft_doc::MAX_GROUP_DEPTH as f64), - "interface.notificationDurationSeconds" => (1.0, 120.0), - "export.jpegQuality" | "export.webpQuality" => (1.0, 100.0), - "performance.memoryUsageMb" => (256.0, 1_048_576.0), - "performance.gpuMemoryMb" => (0.0, 1_048_576.0), - "performance.historyStates" => (1.0, 1000.0), - "performance.cacheLevels" => (1.0, 8.0), - "performance.cacheTileSize" => (256.0, 16384.0), - "performance.effectCacheMb" => (16.0, 65536.0), - "transparencyAndGamut.gamutWarningOpacity" => (1.0, 100.0), - "unitsAndRulers.columnWidth" | "unitsAndRulers.gutter" => (0.0, 10_000.0), - "unitsAndRulers.printResolution" | "unitsAndRulers.screenResolution" | "rawDefaults.resolution" => (1.0, 10_000.0), - "guidesGridAndSlices.gridlineEvery" => (0.001, 10_000.0), - "guidesGridAndSlices.subdivisions" => (1.0, 100.0), - "layerMaskOverlay.opacity" => (0.0, 100.0), - "type.recentFonts" => (0.0, 50.0), - "integrations.controlPort" => (0.0, 65535.0), - _ => return None, - }) -} - -/// Is this preference a `#rrggbb` colour? -pub fn is_color(path: &str) -> bool { - if choices(path).is_some() || path.starts_with("shortcuts.") || path.starts_with("alternateShortcuts.") || path.starts_with("menus.") { - return false; - } - if path == "layerMaskOverlay.color" { - return true; - } - let leaf = path.rsplit('.').next().unwrap_or(path); - matches!( - leaf, - "guideColor" - | "smartGuideColor" - | "gridColor" - | "sliceColor" - | "canvasCustomColor" - | "brushPreviewColor" - | "gamutWarningColor" - | "customLight" - | "customDark" - ) -} - -pub fn parse_hex(s: &str) -> Option<[u8; 3]> { - let s = s.trim().trim_start_matches('#'); - if s.len() != 6 { - return None; - } - let b = |i: usize| s.get(i..i + 2).and_then(|s| u8::from_str_radix(s, 16).ok()); - Some([b(0)?, b(2)?, b(4)?]) -} - -// ------------------------------------------------------------------ JSON paths - -/// Map keys that are command ids (which contain dots): `shortcuts.`, -/// `alternateShortcuts.`, `menus.colors.`. -fn keyed(path: &str) -> Option<(&str, &str)> { - for prefix in ["shortcuts.", "alternateShortcuts.", "menus.colors."] { - if let Some(id) = path.strip_prefix(prefix) { - return Some((&prefix[..prefix.len() - 1], id)); - } - } - None -} - -fn get_path<'a>(root: &'a Value, path: &str) -> Option<&'a Value> { - if path.is_empty() { - return Some(root); - } - if let Some((map, id)) = keyed(path) { - return get_path(root, map)?.get(id); - } - path.split('.').try_fold(root, |v, k| v.get(k)) -} - -/// Set `value` at `path` (creating keys only inside free-form maps such as `shortcuts`). -fn set_path(root: &mut Value, path: &str, value: Value) -> std::result::Result<(), String> { - if let Some((map, id)) = keyed(path) { - let mut cur = &mut *root; - for k in map.split('.') { - cur = cur.get_mut(k).ok_or_else(|| format!("unknown preference `{path}`"))?; - } - cur.as_object_mut().ok_or_else(|| format!("`{map}` is not a map"))?.insert(id.to_string(), value); - return Ok(()); - } - let keys: Vec<&str> = path.split('.').filter(|k| !k.is_empty()).collect(); - let Some((last, parents)) = keys.split_last() else { return Err("empty path".into()) }; - let mut cur = root; - for k in parents { - cur = cur.get_mut(*k).ok_or_else(|| format!("unknown preference `{path}`"))?; - } - let free_map = matches!(parents.first(), Some(&"shortcuts")) || (parents.len() == 2 && parents[0] == "menus" && parents[1] == "colors"); - let obj = cur.as_object_mut().ok_or_else(|| format!("`{path}` is not inside a section"))?; - if !obj.contains_key(*last) && !free_map { - return Err(format!("unknown preference `{path}`")); - } - obj.insert(last.to_string(), value); - Ok(()) -} - -/// Validate one value for `path` before it is stored (choices, ranges, colours). -fn check_value(path: &str, v: &Value) -> std::result::Result<(), String> { - if path == "interface.favoriteThemes" { - let items = v.as_array().ok_or("`interface.favoriteThemes` must be a list of theme ids")?; - if items.len() > Theme::NAMES.len() { - return Err("`interface.favoriteThemes` contains too many themes".into()); - } - let mut seen = Vec::with_capacity(items.len()); - for item in items { - let theme = item.as_str().and_then(Theme::parse).ok_or_else(|| format!("unknown favorite theme `{item}`"))?; - if seen.contains(&theme) { - return Err(format!("duplicate favorite theme `{}`", theme.name())); - } - seen.push(theme); - } - } - if path == "performance.renderingMode" && v.is_null() { - return Ok(()); // Legacy policy, resolved from useGpu and gpuBackend. - } - if let Some(c) = choices(path) { - let s = v.as_str().ok_or_else(|| format!("`{path}` must be one of {}", c.join("|")))?; - if !c.contains(&s) { - return Err(format!("`{path}` must be one of {} (got `{s}`)", c.join("|"))); - } - } - if path == "interface.language" { - let ok = v.as_str().is_some_and(|s| !s.is_empty() && s.len() <= 16 && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')); - if !ok { - return Err("`interface.language` must be `auto` or a language code such as `en` or `ja`".into()); - } - } - if let Some((lo, hi)) = range(path) { - let x = v.as_f64().ok_or_else(|| format!("`{path}` must be a number"))?; - if !(lo..=hi).contains(&x) { - return Err(format!("`{path}` must be within {lo}..{hi} (got {x})")); - } - } - if is_color(path) && v.as_str().and_then(parse_hex).is_none() { - return Err(format!("`{path}` must be a #rrggbb colour")); - } - if path == "tools.pressureCurve" { - let pts = v.as_array().ok_or("`tools.pressureCurve` must be a list of [input, output] points")?; - if !(2..=PressureCurve::MAX_POINTS).contains(&pts.len()) { - return Err(format!("`tools.pressureCurve` needs 2..={} points (got {})", PressureCurve::MAX_POINTS, pts.len())); - } - for p in pts { - let ok = p.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(|x| x.as_f64().is_some_and(|x| (0.0..=1.0).contains(&x)))); - if !ok { - return Err(format!("`tools.pressureCurve` points are [input, output] pairs within 0..1 (got {p})")); - } - } - } - if let Some(sc) = path.strip_prefix("shortcuts.") { - let s = v.as_str().ok_or_else(|| format!("shortcut for `{sc}` must be a string"))?; - if !s.is_empty() && normalize_shortcut(s).is_none() { - return Err(format!("`{s}` is not a valid shortcut (e.g. Cmd+Shift+N, F7)")); - } - } - Ok(()) -} - impl Preferences { /// The preferences as JSON (camelCase keys). pub fn to_json(&self) -> Value { @@ -1506,340 +1255,6 @@ impl Preferences { } } -/// Most further keys one command may hold; Photoshop's own defaults use one. -pub const MAX_ALTERNATES: usize = 8; - -/// Validate and normalise a command's alternate keys: a list of shortcut strings (a single -/// string is a one-key list, `""` none). -pub fn alternate_keys(v: &Value) -> std::result::Result, String> { - let items: Vec<&Value> = match v { - Value::String(s) if s.is_empty() => Vec::new(), - Value::String(_) => vec![v], - Value::Array(a) => a.iter().collect(), - _ => return Err("alternate shortcuts are a list of shortcuts (e.g. [\"F3\"])".into()), - }; - if items.len() > MAX_ALTERNATES { - return Err(format!("at most {MAX_ALTERNATES} alternate shortcuts (got {})", items.len())); - } - let mut out: Vec = Vec::with_capacity(items.len()); - for item in items { - let s = item.as_str().ok_or_else(|| format!("alternate shortcut `{item}` must be a string"))?; - let n = normalize_shortcut(s).ok_or_else(|| format!("`{s}` is not a valid shortcut (e.g. Cmd+Shift+N, F7)"))?; - if !out.contains(&n) { - out.push(n); - } - } - Ok(out) -} - -// ------------------------------------------------------------------ shortcuts - -/// Canonical spelling of a shortcut: modifiers in `Cmd+Ctrl+Alt+Shift` order, key last -/// (single characters upper-cased). `None` if it has no key or an unknown modifier. -pub fn normalize_shortcut(s: &str) -> Option { - let s = s.trim(); - if s.is_empty() { - return None; - } - let (mut cmd, mut ctrl, mut alt, mut shift) = (false, false, false, false); - let mut key: Option = None; - // A trailing "+" key is spelled "Cmd++". - let (body, plus_key) = if s.ends_with("++") || s == "+" { (s.trim_end_matches('+'), true) } else { (s, false) }; - for part in body.split('+').filter(|p| !p.is_empty()) { - match part.to_ascii_lowercase().as_str() { - "cmd" | "command" | "⌘" | "meta" | "super" => cmd = true, - "ctrl" | "control" | "⌃" => ctrl = true, - "alt" | "option" | "opt" | "⌥" => alt = true, - "shift" | "⇧" => shift = true, - _ => { - if key.is_some() { - return None; - } - let k = if part.chars().count() == 1 { part.to_uppercase() } else { capitalize(part) }; - key = Some(k); - } - } - } - if plus_key { - if key.is_some() { - return None; - } - key = Some("+".into()); - } - let key = key?; - let mut out = Vec::new(); - if cmd { - out.push("Cmd"); - } - if ctrl { - out.push("Ctrl"); - } - if alt { - out.push("Alt"); - } - if shift { - out.push("Shift"); - } - let mut s = out.join("+"); - if !s.is_empty() { - s.push('+'); - } - s.push_str(&key); - Some(s) -} - -/// Key names spelled with more than one capital (egui's `Key::name`): Title case would turn -/// `PageUp` into `Pageup`, which no key matches, so a binding saved that way never fired (#6827). -const MULTI_WORD_KEYS: [&str; 8] = - ["PageUp", "PageDown", "OpenBracket", "CloseBracket", "OpenCurlyBracket", "CloseCurlyBracket", "BrowserBack", "IntlBackslash"]; - -fn capitalize(s: &str) -> String { - if let Some(k) = MULTI_WORD_KEYS.iter().find(|k| k.eq_ignore_ascii_case(s)) { - return (*k).to_string(); - } - let mut c = s.chars(); - match c.next() { - Some(f) if f.is_ascii_alphabetic() => { - let rest: String = c.collect(); - // Function keys stay upper-case (F1…F24); named keys are Title case. - if f.eq_ignore_ascii_case(&'f') && rest.chars().all(|c| c.is_ascii_digit()) && !rest.is_empty() { - format!("F{rest}") - } else { - format!("{}{}", f.to_ascii_uppercase(), rest.to_ascii_lowercase()) - } - } - _ => s.to_string(), - } -} - -/// Hold-and-release gestures (#249): temporary tools that last while their key is held and give -/// the previous tool back on release. They are bound like shortcuts (Edit › Keyboard Shortcuts › -/// Tools › Temporary, `edit.keyboardShortcuts`) but held rather than pressed, so they are not -/// commands; the UI reads their keys through [`Preferences::shortcut`]. While a selection or -/// shape is being dragged, the Hand key repositions it instead of panning (Photoshop's Space). -/// The erase key keeps the Brush or Pencil and makes its strokes erase (Photoshop's `~`). -pub const TEMPORARY_TOOLS: &[(&str, &str, &str)] = &[ - ("tools.temporary.hand", "Hand Tool (hold)", "Space"), - ("tools.temporary.zoomIn", "Zoom In (hold, drag to scrub)", "Cmd+Space"), - ("tools.temporary.zoomOut", "Zoom Out (hold)", "Alt+Space"), - ("tools.temporary.erase", "Erase with Brush or Pencil (hold)", "`"), -]; - -/// Photoshop's second default keys (#3665): (command, key). Each command keeps its main key -/// (the one its menu shows) and answers these as well, as in Photoshop's default set: the -/// legacy function keys F2 Cut, F3 Copy, F4 Paste and Shift+F7 Inverse; Shift+Backspace -/// (Shift+Delete on a Mac) for Fill; ⌘+ beside ⌘= for Zoom In; and off the Mac, Ctrl+F4 beside -/// Ctrl+W for Close (Windows' close-document key; macOS keeps Ctrl+F4 for window focus). -pub const ALTERNATE_SHORTCUTS: &[(&str, &str)] = &[ - ("edit.cut", "F2"), - ("edit.copy", "F3"), - ("edit.paste", "F4"), - ("edit.fill", "Shift+Backspace"), - ("select.inverse", "Shift+F7"), - ("view.zoomIn", "Cmd++"), - #[cfg(not(target_os = "macos"))] - ("file.close", "Cmd+F4"), -]; - -/// A command's default alternate keys ([`ALTERNATE_SHORTCUTS`]). -pub fn default_alternates(id: &str) -> impl Iterator + '_ { - ALTERNATE_SHORTCUTS.iter().filter(move |(c, _)| *c == id).map(|(_, sc)| *sc) -} - -/// Keys the system takes before the app sees them (switching apps, closing the window, force -/// quit): `edit.keyboardShortcuts` won't bind them, as Photoshop won't. `sc` is in our notation, -/// where `Cmd` is Ctrl off the Mac. -pub fn reserved_shortcut(sc: &str) -> bool { - let Some(n) = normalize_shortcut(sc) else { return false }; - let reserved: &[&str] = if cfg!(target_os = "macos") { - &["Cmd+Tab", "Cmd+Shift+Tab", "Cmd+Alt+Escape", "Cmd+`"] - } else if cfg!(target_os = "windows") { - &["Alt+Tab", "Alt+Shift+Tab", "Alt+F4", "Cmd+Alt+Delete", "Cmd+Escape", "Cmd+Shift+Escape"] - } else { - // Linux and the BSDs: window switching and closing, and the virtual consoles. - &[ - "Alt+Tab", - "Alt+Shift+Tab", - "Alt+F4", - "Cmd+Alt+Delete", - "Cmd+Alt+F1", - "Cmd+Alt+F2", - "Cmd+Alt+F3", - "Cmd+Alt+F4", - "Cmd+Alt+F5", - "Cmd+Alt+F6", - "Cmd+Alt+F7", - "Cmd+Alt+F8", - "Cmd+Alt+F9", - "Cmd+Alt+F10", - "Cmd+Alt+F11", - "Cmd+Alt+F12", - ] - }; - reserved.iter().filter_map(|r| normalize_shortcut(r)).any(|r| r == n) -} - -/// What a bindable id is: a command (the engine's or the shell's), a tool, or a held tool. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BindKind { - Command, - Tool, - Hold, -} - -/// Every bindable id: (id, label, menu path, default key, kind). The engine's commands, the -/// shell's ([`crate::shell_commands::SHELL_COMMANDS`]), the tools and the held temporary tools, -/// so Edit › Keyboard Shortcuts works the same with or without the app's UI. -pub fn bindable_items() -> impl Iterator, BindKind)> { - let engine = crate::command_specs().iter().map(|c| (c.id, c.label, c.menu, c.shortcut, BindKind::Command)); - let shell = crate::shell_commands::SHELL_COMMANDS.iter().map(|c| (c.0, c.1, c.2, c.3, BindKind::Command)); - let tools = crate::shell_commands::TOOLS.iter().map(|t| (t.0, t.1, &["Tools"][..], t.2, BindKind::Tool)); - let hold = TEMPORARY_TOOLS.iter().map(|t| (t.0, t.1, &["Tools", "Temporary"][..], Some(t.2), BindKind::Hold)); - engine.chain(shell).chain(tools).chain(hold) -} - -/// Every bindable id with its default. -fn bindable() -> impl Iterator)> { - bindable_items().map(|i| (i.0, i.3)) -} - -fn is_tool(id: &str) -> bool { - crate::shell_commands::tool_default(id).is_some() -} - -/// Shortcuts bound to more than one command: (shortcut, ids). `bindings` are (id, shortcut). -pub fn conflicts<'a>(bindings: impl IntoIterator) -> Vec<(String, Vec)> { - let mut by: BTreeMap> = BTreeMap::new(); - for (id, sc) in bindings { - if let Some(n) = normalize_shortcut(sc) { - by.entry(n).or_default().push(id.to_string()); - } - } - by.into_iter().filter(|(_, ids)| ids.len() > 1).collect() -} - -// ------------------------------------------------------------------ store - -/// The session's preferences plus a revision counter that moves on every change (frontends -/// persist when it moves). -#[derive(Clone, Debug, Default)] -pub struct PrefsStore { - values: Preferences, - rev: u64, -} - -impl PrefsStore { - pub fn get(&self) -> &Preferences { - &self.values - } - /// Change preferences; bumps the revision. - pub fn edit(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R { - self.rev += 1; - f(&mut self.values) - } - pub fn rev(&self) -> u64 { - self.rev - } -} - -/// The preferences file format written by [`Session::prefs_value`]. 2: Use Shift Key for Tool -/// Switch stored as chosen (before, a stored `false` was the old default; see `load_prefs_json`). -pub const PREFS_VERSION: u64 = 2; - -/// A saved preference [`Session::load_prefs_json`] couldn't read (a wrong type, an unknown -/// choice) and left at its default. -#[derive(Clone, Debug, PartialEq)] -pub struct InvalidPref { - /// JSON keys from the top of the preferences file (`["fileHandling", "recentFileCount"]`), - /// kept apart because keys such as command ids contain dots. - pub keys: Vec, - /// The value the file held there. - pub value: Value, -} - -impl InvalidPref { - /// The dotted path, as `prefs.get` and `prefs.set` take it. - pub fn path(&self) -> String { - self.keys.join(".") - } -} - -/// How deep [`read_lenient`] looks for the readable parts of an unreadable value. -const LENIENT_DEPTH: usize = 32; - -/// Read `v` as a `T`. When that fails, start from `T::default()` and lay the file's values over -/// it one at a time, keeping each one the whole still reads with and descending into objects -/// that don't, so one bad value resets only itself. The values left out are added to -/// `invalid`, their keys after `prefix`. -fn read_lenient(v: Value, prefix: &[&str], invalid: &mut Vec) -> T -where - T: Default + Serialize + for<'de> Deserialize<'de>, -{ - if let Ok(t) = T::deserialize(&v) { - return t; - } - let prefix: Vec = prefix.iter().map(|k| (*k).to_string()).collect(); - let mut acc = serde_json::to_value(T::default()).unwrap_or(Value::Null); - let fits = |root: &Value| T::deserialize(root).is_ok(); - match v { - Value::Object(file) if acc.is_object() && fits(&acc) => { - lay_over(&mut acc, &mut Vec::new(), file, &fits, &prefix, invalid); - T::deserialize(&acc).unwrap_or_default() - } - value => { - invalid.push(InvalidPref { keys: prefix, value }); - T::default() - } - } -} - -/// [`read_lenient`]'s walk: lay `file` over the object at `at` inside `root`, key by key, so that -/// `root` always reads (`fits`). -fn lay_over( - root: &mut Value, - at: &mut Vec, - file: Map, - fits: &dyn Fn(&Value) -> bool, - prefix: &[String], - invalid: &mut Vec, -) { - for (k, fv) in file { - let Some(obj) = object_at(root, at) else { return }; - let old = obj.insert(k.clone(), fv.clone()); - if fits(root) { - continue; - } - // Back to the default. An object keeps its parts that read, and so does a new map entry - // (a shortcut set, a workspace) when it reads from an empty object. - let Some(obj) = object_at(root, at) else { return }; - let mut descend = fv.is_object() && at.len() < LENIENT_DEPTH && matches!(old, None | Some(Value::Object(_))); - match old { - Some(o) => obj.insert(k.clone(), o), - None if descend => obj.insert(k.clone(), Value::Object(Map::new())), - None => obj.remove(&k), - }; - at.push(k); - if descend && !fits(root) { - descend = false; - if let Some((key, parent)) = at.split_last() - && let Some(obj) = object_at(root, parent) - { - obj.remove(key); - } - } - match fv { - Value::Object(m) if descend => lay_over(root, at, m, fits, prefix, invalid), - value => invalid.push(InvalidPref { keys: prefix.iter().chain(at.iter()).cloned().collect(), value }), - } - at.pop(); - } -} - -/// The JSON object at `path` inside `root`. -fn object_at<'a>(root: &'a mut Value, path: &[String]) -> Option<&'a mut Map> { - path.iter().try_fold(root, |cur, k| cur.get_mut(k.as_str()))?.as_object_mut() -} - impl Session { /// The current preferences. pub fn prefs(&self) -> &Preferences { @@ -2068,699 +1483,6 @@ impl Session { } } -// ------------------------------------------------------------------ commands - -fn always(_: &Session) -> std::result::Result<(), String> { - Ok(()) -} - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} - -fn prefs_get(s: &mut Session, p: &Value) -> Result { - let path = p.get("path").and_then(Value::as_str).unwrap_or(""); - let v = s.prefs_view(); - get_path(&v, path).cloned().ok_or_else(|| bad("prefs.get", format!("unknown preference `{path}`"))) -} - -fn prefs_set(s: &mut Session, p: &Value) -> Result { - let cmd = "prefs.set"; - let mut changes: Vec<(String, Value)> = Vec::new(); - if let Some(path) = p.get("path").and_then(Value::as_str) { - changes.push((path.to_string(), p.get("value").cloned().ok_or_else(|| bad(cmd, "missing `value`"))?)); - } - if let Some(m) = p.get("values").and_then(Value::as_object) { - changes.extend(m.iter().map(|(k, v)| (k.clone(), v.clone()))); - } - if changes.is_empty() { - return Err(bad(cmd, "give `path` and `value`, or `values: {path: value, …}`")); - } - // All or nothing: validate against a scratch copy first. - let (saved_prefs, saved_color) = (s.prefs().clone(), s.color.settings.clone()); - let mut color_changed = false; - for (path, v) in &changes { - match s.set_pref(path, v.clone(), false) { - Ok(touched) => color_changed |= touched, - Err(e) => { - s.prefs.edit(|p| *p = saved_prefs); - s.color.settings = saved_color; - return Err(bad(cmd, e)); - } - } - } - if color_changed && let Err(e) = crate::color_cmds::validate_settings(&s.color.settings) { - s.prefs.edit(|p| *p = saved_prefs); - s.color.settings = saved_color; - return Err(bad(cmd, e)); - } - // `colorSettings.blendTextGamma` lives in the compositor too, as `edit.colorSettings` sets it. - photocraft_compose::psblend::set_text_gamma(s.color.settings.blend_text_gamma); - s.apply_prefs(); - let view = s.prefs_view(); - let out: Map = changes.iter().map(|(k, _)| (k.clone(), get_path(&view, k).cloned().unwrap_or(Value::Null))).collect(); - Ok(Value::Object(out)) -} - -fn prefs_reset(s: &mut Session, p: &Value) -> Result { - let path = p.get("path").or_else(|| p.get("section")).and_then(Value::as_str); - match path { - Some("colorSettings") => s.color.settings = Default::default(), - // One colour setting: `Preferences` has no `colorSettings`, so take the default - // from `ColorSettings` and route it like `prefs.set` does. - Some(path) if path.starts_with("colorSettings.") => { - let defaults = serde_json::to_value(crate::color_cmds::ColorSettings::default()).map_err(|e| bad("prefs.reset", e.to_string()))?; - let key = path.strip_prefix("colorSettings.").unwrap_or(path); - let def = get_path(&defaults, key).cloned().ok_or_else(|| bad("prefs.reset", format!("unknown preference `{path}`")))?; - s.set_pref(path, def, true).map_err(|e| bad("prefs.reset", e))?; - } - None => { - s.color.settings = Default::default(); - s.edit_prefs(|p| p.reset(None)).map_err(|e| bad("prefs.reset", e))?; - } - Some(path) => { - let mut next = s.prefs().clone(); - next.reset(Some(path)).map_err(|e| bad("prefs.reset", e))?; - s.edit_prefs(|p| *p = next); - } - } - s.prefs.edit(|_| ()); - photocraft_compose::psblend::set_text_gamma(s.color.settings.blend_text_gamma); - s.apply_prefs(); - if path.is_some_and(|path| keyed(path).is_some()) { - // The removed override is absent, so reading its old path would report an error. - Ok(Value::Null) - } else { - prefs_get(s, &json!({"path": path.unwrap_or("")})) - } -} - -/// `edit.preferences.
`: the section's values (the GUI opens the dialog on it instead). -fn preferences_section(s: &mut Session, p: &Value) -> Result { - let section = p.get("__section").and_then(Value::as_str).unwrap_or("general").to_string(); - let title = SECTIONS.iter().find(|(id, _)| *id == section).map_or("General", |(_, t)| *t); - let values = s.prefs().get(§ion).unwrap_or(Value::Null); - Ok(json!({"section": section, "title": title, "values": values})) -} - -/// Edit › Keyboard Shortcuts (engine part): list, change and reset application shortcuts. -fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result { - let cmd = "edit.keyboardShortcuts"; - // Every change lands at once, after all of it validated: a bad key leaves the set as it was. - let mut next = s.prefs().clone(); - // A set loads first, so the call's other changes apply on top of it. - let mut changed = crate::shortcut_sets::load(&mut next, p).map_err(|e| bad(cmd, e))?; - if let Some(r) = p.get("reset") { - match r { - Value::Bool(true) => { - next.shortcuts.clear(); - next.alternate_shortcuts.clear(); - changed = true; - } - Value::Array(ids) => { - for id in ids.iter().filter_map(Value::as_str) { - next.shortcuts.remove(id); - next.alternate_shortcuts.remove(id); - } - changed = true; - } - _ => {} - } - } - // A Photoshop `.kys` set (`importKys`, its XML text) becomes `set` and `alternates` entries, - // matched by label (`crate::kys`); a key equal to the command's default restores the - // default, and keys given in `set` / `alternates` as well win over the file's. - let imported; - let mut import = None; - let p = match p.get("importKys") { - Some(v) => { - // The file's text, or {"path": …} to read it. - let read; - let xml = match v { - Value::String(s) => s.as_str(), - Value::Object(o) => { - let path = - o.get("path").and_then(Value::as_str).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, "`importKys.path` is a .kys file"))?; - read = read_text_file(path, crate::kys::MAX_BYTES).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - read.as_str() - } - _ => return Err(bad(cmd, "`importKys` is the text of a .kys file, or {\"path\": …}")), - }; - let set = crate::kys::parse(xml).map_err(|e| bad(cmd, e))?; - let plan = crate::kys::plan(crate::kys::command_candidates(), &set); - let mut merged = serde_json::Map::new(); - // A key the system reserves is left out (reported as `reserved`), not a failed import. - let mut skipped: Vec = Vec::new(); - for (id, sc) in plan.set.iter().filter(|(id, sc)| { - let bad = reserved_shortcut(sc); - if bad { - skipped.push(format!("{id}: {sc}")); - } - !bad - }) { - let default = crate::command_specs().iter().find(|c| c.id == id).and_then(|c| c.shortcut).and_then(normalize_shortcut); - merged.insert(id.clone(), if default.as_deref() == Some(sc.as_str()) { Value::Null } else { json!(sc) }); - } - // Tool keys: a tool's own letter restores it (and its Shift cycling). - let tools = crate::shell_commands::TOOLS.iter().map(|t| (t.0, t.1)); - let (tool_keys, unknown_tools) = crate::kys::plan_tools(tools, &set); - for (id, key) in &tool_keys { - let own = crate::shell_commands::tool_default(id).flatten().is_some_and(|d| d.eq_ignore_ascii_case(key)); - merged.insert(id.clone(), if own { Value::Null } else { json!(key) }); - } - merged.extend(p.get("set").and_then(Value::as_object).cloned().unwrap_or_default()); - let mut alternates = serde_json::Map::new(); - for (id, keys) in &plan.alternate_keys { - let keys: &Vec = &keys.iter().filter(|k| !reserved_shortcut(k)).cloned().collect(); - let main = plan.set.get(id).map(String::as_str); - let default = Preferences::default().alternates(id, main); - alternates.insert(id.clone(), if *keys == default { Value::Null } else { json!(keys) }); - } - alternates.extend(p.get("alternates").and_then(Value::as_object).cloned().unwrap_or_default()); - import = Some(json!({ - "name": set.name, - "imported": plan.set.len(), - "set": plan.set, - "unknown": plan.unknown, - "unreadable": plan.unreadable, - "alternates": plan.alternates, - "alternateKeys": plan.alternate_keys, - "toolKeys": set.tool_keys, - "tools": tool_keys, - "unknownTools": unknown_tools, - "reserved": skipped, - "windows": set.windows, - })); - let mut with_import = p.clone(); - with_import["set"] = Value::Object(merged); - with_import["alternates"] = Value::Object(alternates); - imported = with_import; - &imported - } - None => p, - }; - let empty = serde_json::Map::new(); - let set = match p.get("set") { - Some(Value::Object(m)) => m, - _ => &empty, - }; - let alts = match p.get("alternates") { - None | Some(Value::Null) => &empty, - Some(v) => v.as_object().ok_or_else(|| bad(cmd, "`alternates` maps command ids to lists of shortcuts"))?, - }; - if !set.is_empty() || !alts.is_empty() { - let allow_unknown = p.get("allowUnknown").and_then(Value::as_bool).unwrap_or(false); - changed = true; - // Reserved system keys can't be bound, by hand or from a file. - let reserved = |v: &Value| -> Option { - let keys = match v { - Value::String(s) => vec![s.clone()], - other => alternate_keys(other).unwrap_or_default(), - }; - keys.into_iter().find(|k| reserved_shortcut(k)) - }; - if let Some((id, k)) = set.iter().chain(alts.iter()).find_map(|(id, v)| reserved(v).map(|k| (id, k))) { - return Err(bad(cmd, format!("`{k}` (for `{id}`) is reserved by the system and can't be assigned"))); - } - for (id, v) in set { - if !bindable().any(|(b, _)| b == id) && !allow_unknown { - return Err(bad(cmd, format!("unknown command `{id}`"))); - } - next.set(&format!("shortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?; - } - for (id, v) in alts { - if !bindable().any(|(b, _)| b == id) && default_alternates(id).next().is_none() && !allow_unknown { - return Err(bad(cmd, format!("unknown command `{id}`"))); - } - next.set(&format!("alternateShortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?; - } - // Like Photoshop, a shortcut moved to a new command is taken away from the old one, - // whether the old one held it as its main key or as an alternate (#3665). - if p.get("removeConflicts").and_then(Value::as_bool).unwrap_or(true) { - let assigned: Vec<(&str, String)> = set - .iter() - .filter_map(|(id, v)| Some((id.as_str(), v.as_str().and_then(normalize_shortcut)?))) - .chain(alts.iter().flat_map(|(id, v)| alternate_keys(v).unwrap_or_default().into_iter().map(move |k| (id.as_str(), k)))) - .collect(); - for (id, sc) in assigned { - for (c, def) in bindable() { - // Tools may share a key: they cycle with Shift, as Photoshop's groups do. - if is_tool(id) && is_tool(c) { - continue; - } - // Never strip a command that this same call is assigning: - // two entries for one key are a clash inside the call, which - // the returned conflicts list reports (#719). Stripping - // each other here unbound both silently. - if c == id || set.contains_key(c) || alts.contains_key(c) { - continue; - } - let main = next.shortcut(c, def).map(str::to_string); - if main.as_deref().and_then(normalize_shortcut).as_deref() == Some(sc.as_str()) { - next.shortcuts.insert(c.to_string(), String::new()); - } - let held = next.alternates(c, main.as_deref()); - if held.contains(&sc) { - next.alternate_shortcuts.insert(c.to_string(), held.into_iter().filter(|k| *k != sc).collect()); - } - } - } - } - } - // Then the sets are saved, deleted or switched, from the bindings as they now stand. - changed |= crate::shortcut_sets::store(&mut next, p).map_err(|e| bad(cmd, e))?; - // The reply and the exports read the bindings as they will be; they are committed only once - // the exports are written, so a bad export target changes nothing. - let prefs = &next; - let filter = p.get("filter").and_then(Value::as_str).map(str::to_ascii_lowercase); - let list: Vec = bindable_items() - .filter(|c| filter.as_ref().is_none_or(|f| c.0.to_ascii_lowercase().contains(f) || c.1.to_ascii_lowercase().contains(f))) - .filter(|c| { - p.get("list").and_then(Value::as_bool).unwrap_or(false) - || filter.is_some() - || prefs.shortcuts.contains_key(c.0) - || prefs.alternate_shortcuts.contains_key(c.0) - }) - .map(|(id, label, menu, def, kind)| { - let main = prefs.shortcut(id, def); - let defaults: Vec<&str> = default_alternates(id).collect(); - let mut v = json!({"id": id, "label": label, "menu": menu, "default": def, "shortcut": main, "alternates": prefs.alternates(id, main)}); - if !defaults.is_empty() { - v["defaultAlternates"] = json!(defaults); - } - match kind { - BindKind::Hold => v["hold"] = json!(true), - BindKind::Tool => v["tool"] = json!(true), - BindKind::Command => {} - } - v - }) - .collect(); - let mut bindings: Vec<(&str, String)> = Vec::new(); - for (id, def) in bindable() { - let main = prefs.shortcut(id, def); - bindings.extend(main.map(|m| (id, m.to_string()))); - bindings.extend(prefs.alternates(id, main).into_iter().map(|k| (id, k))); - } - // Tools sharing a key are a cycling group, not a conflict. - let conflicts: Vec = conflicts(bindings.iter().map(|(id, k)| (*id, k.as_str()))) - .into_iter() - .filter(|(_, ids)| !ids.iter().all(|id| is_tool(id))) - .map(|(sc, ids)| json!({"shortcut": sc, "commands": ids})) - .collect(); - let mut out = json!({"overrides": prefs.shortcuts, "alternateOverrides": prefs.alternate_shortcuts, "commands": list, "conflicts": conflicts}); - if let (Some(o), Value::Object(sets)) = (out.as_object_mut(), crate::shortcut_sets::describe(prefs)) { - o.extend(sets); - } - // The bindings as a `.kys` file, or Photoshop's Summarize page: every bindable item (the - // engine's commands, the shell's commands and the tools). - let set_name = if prefs.shortcut_set.is_empty() { crate::shortcut_sets::DEFAULTS_NAME } else { prefs.shortcut_set.as_str() }; - // Both targets are resolved and their texts made before anything is written, and a path that - // can't be written is refused before either file is: a bad export changes nothing. - let kys_target = file_target(cmd, p.get("exportKys"))?; - let html_target = file_target(cmd, p.get("summarize"))?; - let mut files: Vec<(&str, String, String)> = Vec::new(); - if let Some(target) = kys_target { - let entries: Vec = - crate::shortcut_sets::bound(prefs).into_iter().map(|b| crate::kys::Entry { id: b.id, label: b.label, tool: b.tool, keys: b.keys }).collect(); - let text = crate::kys::write(set_name, &entries); - match target { - Some(path) => files.push(("kysPath", path, text)), - None => out["kys"] = json!(text), - } - } - if let Some(target) = html_target { - let v = p.get("summarize").cloned().unwrap_or(Value::Null); - let mac = v.get("mac").and_then(Value::as_bool).unwrap_or(cfg!(target_os = "macos")); - let mut sections: Vec = Vec::new(); - for crate::shortcut_sets::Bound { label, menu, keys, .. } in crate::shortcut_sets::bound(prefs) { - match sections.iter_mut().find(|(m, _)| *m == menu) { - Some((_, rows)) => rows.push((label, keys)), - None => sections.push((menu, vec![(label, keys)])), - } - } - let html = crate::shortcut_sets::summarize(set_name, §ions, mac); - match target { - Some(path) => files.push(("htmlPath", path, html)), - None => out["html"] = json!(html), - } - } - for (_, path, _) in &files { - writable(path).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - } - let list: Vec<(&str, &str)> = files.iter().map(|(_, path, text)| (path.as_str(), text.as_str())).collect(); - write_files_atomically(&list, &rename_path).map_err(|e| bad(cmd, e))?; - for (key, path, _) in &files { - out[*key] = json!(path); - } - if changed { - s.edit_prefs(|p| *p = next); - } - if let Some(import) = import { - out["import"] = import; - } - Ok(out) -} - -/// An output parameter (`exportKys`, `summarize`): absent or false → `None`; true (or an object -/// without `path`) → `Some(None)`, the text comes back in the reply; `{"path": …}` → -/// `Some(Some(path))`, written there. -fn file_target(cmd: &str, v: Option<&Value>) -> Result>> { - match v { - None | Some(Value::Null) | Some(Value::Bool(false)) => Ok(None), - Some(Value::Bool(true)) => Ok(Some(None)), - Some(Value::Object(o)) => match o.get("path") { - None | Some(Value::Null) => Ok(Some(None)), - Some(Value::String(s)) if !s.trim().is_empty() => Ok(Some(Some(s.clone()))), - Some(_) => Err(bad(cmd, "`path` must be a non-empty string")), - }, - Some(_) => Err(bad(cmd, "expected true or {\"path\": …}")), - } -} - -#[cfg(not(target_arch = "wasm32"))] -fn read_text_file(path: &str, max: usize) -> std::result::Result { - let meta = std::fs::metadata(path).map_err(|e| e.to_string())?; - if !meta.is_file() || meta.len() > max as u64 { - return Err(format!("not a file of at most {} KiB", max / 1024)); - } - std::fs::read_to_string(path).map_err(|e| e.to_string()) -} - -#[cfg(target_arch = "wasm32")] -fn read_text_file(_: &str, _: usize) -> std::result::Result { - Err("paths can't be read on the web; pass the file's text instead".into()) -} - -/// Whether `path` can be written: not a folder, in a folder that exists. -#[cfg(not(target_arch = "wasm32"))] -fn writable(path: &str) -> std::result::Result<(), String> { - let p = std::path::Path::new(path); - if p.is_dir() { - return Err("is a folder".into()); - } - if std::fs::metadata(p).is_ok_and(|m| m.permissions().readonly()) { - return Err("is read-only".into()); - } - match p.parent().filter(|d| !d.as_os_str().is_empty()) { - Some(d) if !d.is_dir() => Err("its folder doesn't exist".into()), - _ => Ok(()), - } -} - -#[cfg(target_arch = "wasm32")] -fn writable(_: &str) -> std::result::Result<(), String> { - Err("paths can't be written on the web; omit `path` to get the text back".into()) -} - -#[cfg(not(target_arch = "wasm32"))] -fn rename_path(from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> { - std::fs::rename(from, to) -} - -#[cfg(target_arch = "wasm32")] -fn rename_path(_: &std::path::Path, _: &std::path::Path) -> std::io::Result<()> { - Err(std::io::Error::other("paths can't be written on the web")) -} - -/// Where `path` points, for telling whether two targets are one file: its folder resolved, its -/// name compared without case where the file system ignores it. -#[cfg(not(target_arch = "wasm32"))] -fn path_key(path: &str) -> String { - let p = std::path::Path::new(path); - let dir = p.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(std::path::Path::new(".")); - let dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()); - let key = dir.join(p.file_name().unwrap_or_default()).to_string_lossy().into_owned(); - if cfg!(any(target_os = "windows", target_os = "macos")) { key.to_lowercase() } else { key } -} - -/// A new, empty file beside `path` with a name nothing else uses (`create_new`), for staging -/// (`kind` "tmp") or a backup ("bak"). -#[cfg(not(target_arch = "wasm32"))] -fn sibling(path: &str, kind: &str) -> std::io::Result<(std::path::PathBuf, std::fs::File)> { - for n in 0..1000u32 { - let p = std::path::PathBuf::from(format!("{path}.{}-{n}.photocraft-{kind}", std::process::id())); - match std::fs::OpenOptions::new().write(true).create_new(true).open(&p) { - Ok(f) => return Ok((p, f)), - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(e) => return Err(e), - } - } - Err(std::io::Error::other("no free name beside it")) -} - -/// Write `files` ((path, text)) all or nothing. Each text is staged in a new file beside its -/// target; once every one is written, each existing target is moved aside to a backup and the -/// staged file moved in. Any failure moves the backups back and removes what was staged, so the -/// user's files end as they began; on success the backups go. Two targets naming one file are -/// refused. `rename` is `std::fs::rename` (a test fails it on purpose). -#[cfg(not(target_arch = "wasm32"))] -pub(crate) fn write_files_atomically( - files: &[(&str, &str)], - rename: &dyn Fn(&std::path::Path, &std::path::Path) -> std::io::Result<()>, -) -> std::result::Result<(), String> { - use std::io::Write; - use std::path::{Path, PathBuf}; - for (i, (a, _)) in files.iter().enumerate() { - if files.iter().skip(i + 1).any(|(b, _)| path_key(a) == path_key(b)) { - return Err(format!("{a}: two exports to the same file")); - } - } - let mut staged: Vec = Vec::new(); - let drop_all = |paths: &[PathBuf]| { - for p in paths { - let _ = std::fs::remove_file(p); - } - }; - for (path, text) in files { - let (tmp, mut f) = match sibling(path, "tmp") { - Ok(v) => v, - Err(e) => { - drop_all(&staged); - return Err(format!("{path}: {e}")); - } - }; - staged.push(tmp); - if let Err(e) = f.write_all(text.as_bytes()).and_then(|()| f.sync_all()) { - drop_all(&staged); - return Err(format!("{path}: {e}")); - } - } - // (target, its backup) of each file moved in so far. - let mut moved: Vec<(&Path, Option)> = Vec::new(); - // Put each backup back over its target (a target that had none is removed). What couldn't be - // put back is named, so the user can find their previous file. - let undo = |moved: &[(&Path, Option)]| -> String { - let mut stranded = Vec::new(); - for (target, backup) in moved.iter().rev() { - match backup { - Some(b) => { - if rename(b, target).is_err() { - stranded.push(format!("the previous {} is at {}", target.display(), b.display())); - } - } - None => { - let _ = std::fs::remove_file(target); - } - } - } - if stranded.is_empty() { String::new() } else { format!(" ({})", stranded.join("; ")) } - }; - for ((path, _), tmp) in files.iter().zip(&staged) { - let target = Path::new(*path); - let backup = if target.exists() { - let moved_aside = sibling(path, "bak").and_then(|(b, f)| { - drop(f); - match rename(target, &b) { - Ok(()) => Ok(b), - Err(e) => { - // The placeholder the backup name reserved goes too. - let _ = std::fs::remove_file(&b); - Err(e) - } - } - }); - match moved_aside { - Ok(b) => Some(b), - Err(e) => { - let stranded = undo(&moved); - drop_all(&staged); - return Err(format!("{path}: {e}{stranded}")); - } - } - } else { - None - }; - if let Err(e) = rename(tmp, target) { - let mut stranded = undo(&moved); - if let Some(b) = &backup - && rename(b, target).is_err() - { - stranded = format!("{stranded} (the previous {path} is at {})", b.display()); - } - drop_all(&staged); - return Err(format!("{path}: {e}{stranded}")); - } - moved.push((target, backup)); - } - for (_, backup) in moved { - if let Some(b) = backup { - let _ = std::fs::remove_file(b); - } - } - Ok(()) -} - -#[cfg(target_arch = "wasm32")] -pub(crate) fn write_files_atomically( - files: &[(&str, &str)], - _: &dyn Fn(&std::path::Path, &std::path::Path) -> std::io::Result<()>, -) -> std::result::Result<(), String> { - if files.is_empty() { Ok(()) } else { Err("paths can't be written on the web; omit `path` to get the text back".into()) } -} - -/// Edit › Menus: hide/show items and give them colours. -fn menus(s: &mut Session, p: &Value) -> Result { - let ids = |k: &str| -> Vec { - p.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default() - }; - const COLORS: [&str; 8] = ["none", "red", "orange", "yellow", "green", "blue", "violet", "gray"]; - if let Some(m) = p.get("color").and_then(Value::as_object) { - for v in m.values() { - if let Some(c) = v.as_str().filter(|c| !COLORS.contains(c)) { - return Err(bad("edit.menus", format!("unknown colour `{c}` ({})", COLORS.join("|")))); - } - } - } - let (hide, show) = (ids("hide"), ids("show")); - if let Some(id) = hide.iter().find(|id| !MenuCustomization::hideable(id)) { - return Err(bad("edit.menus", format!("`{id}` can't be hidden"))); - } - s.edit_prefs(|pr| { - if p.get("reset").and_then(Value::as_bool) == Some(true) { - pr.menus = MenuCustomization::default(); - } - for id in hide { - if !pr.menus.hidden.contains(&id) { - pr.menus.hidden.push(id); - } - } - pr.menus.hidden.retain(|h| !show.contains(h)); - if let Some(m) = p.get("color").and_then(Value::as_object) { - for (id, v) in m { - match v.as_str() { - Some(c) if c != "none" => { - pr.menus.colors.insert(id.clone(), c.to_string()); - } - _ => { - pr.menus.colors.remove(id); - } - } - } - } - }); - Ok(serde_json::to_value(&s.prefs().menus).unwrap_or_default()) -} - -/// Edit › Toolbar: hide tools and reorder the toolbar. -fn toolbar(s: &mut Session, p: &Value) -> Result { - let ids = |k: &str| -> Option> { p.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()) }; - s.edit_prefs(|pr| { - if p.get("reset").and_then(Value::as_bool) == Some(true) { - pr.toolbar = ToolbarCustomization::default(); - } - if let Some(h) = ids("hidden") { - pr.toolbar.hidden = h; - } - if let Some(o) = ids("order") { - pr.toolbar.order = o; - } - }); - Ok(serde_json::to_value(&s.prefs().toolbar).unwrap_or_default()) -} - -macro_rules! spec { - ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $run:expr, $journal:expr) => { - CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: always, run: $run, journal: $journal } - }; -} - -macro_rules! section { - ($id:literal, $label:literal) => { - section!($id, $label, None) - }; - ($id:literal, $label:literal, $shortcut:expr) => { - CommandSpec { id: $id, label: $label, menu: &["Edit", "Preferences"], shortcut: $shortcut, params: r##"{}"##, enabled: always, run: |s, _| preferences_section(s, &json!({"__section": section_of($id)})), journal: false } - }; -} - -fn section_of(id: &str) -> &str { - id.rsplit('.').next().unwrap_or("general") -} - -/// Preference command specs. -pub fn specs() -> Vec { - vec![ - spec!( - "prefs.get", - "Get Preferences", - [], - None, - r##"{"path":"section.key"?=everything (e.g. "performance.historyStates", "colorSettings.workingRgb")}"##, - prefs_get, - false - ), - spec!( - "prefs.set", - "Set Preferences", - [], - None, - r##"{"path":"section.key","value":json} or {"values":{"section.key":json,…}} (validated; all or nothing)"##, - prefs_set, - false - ), - spec!("prefs.reset", "Reset Preferences", [], None, r##"{"path":"section|section.key"?=everything}"##, prefs_reset, false), - // Photoshop: ⌘K opens Preferences › General (⌘, is Layer › Hide Layers). - section!("edit.preferences.general", "General…", Some("Cmd+K")), - section!("edit.preferences.interface", "Interface…"), - section!("edit.preferences.workspace", "Workspace…"), - section!("edit.preferences.tools", "Tools…"), - section!("edit.preferences.historyLog", "History Log…"), - section!("edit.preferences.fileHandling", "File Handling…"), - section!("edit.preferences.export", "Export…"), - section!("edit.preferences.performance", "Performance…"), - section!("edit.preferences.scratchDisks", "Scratch Disks…"), - section!("edit.preferences.cursors", "Cursors…"), - section!("edit.preferences.transparencyAndGamut", "Transparency & Gamut…"), - section!("edit.preferences.unitsAndRulers", "Units & Rulers…"), - section!("edit.preferences.guidesGridAndSlices", "Guides, Grid & Slices…"), - section!("edit.preferences.plugIns", "Plug-ins…"), - section!("edit.preferences.type", "Type…"), - section!("edit.preferences.enhancedControls", "Enhanced Controls…"), - section!("edit.preferences.rawDefaults", "Camera Raw…"), - section!("edit.preferences.integrations", "Integrations…"), - spec!( - "edit.keyboardShortcuts", - "Keyboard Shortcuts…", - ["Edit"], - Some("Cmd+Alt+Shift+K"), - r##"{"set":{"|tools.temporary.hand|zoomIn|zoomOut":"Cmd+Shift+X"|""(remove)|null(default)}?,"alternates":{"":["F3",…]|[](none)|null(default)}?,"reset":true|["",…]?,"removeConflicts":bool=true,"filter":str?,"list":bool=false,"importKys":"<.kys XML>"|{"path":".kys"}?,"useSet":""|""(defaults)?,"saveSet":""?,"deleteSet":""?,"sets":{"":{"shortcuts":{…},"alternateShortcuts":{…}}}?,"activeSet":""|""?,"exportKys":true|{"path":".kys"}?,"summarize":true|{"mac":bool,"path":".html"}?} (with a path the file is written and the reply has kysPath/htmlPath instead of kys/html)"##, - keyboard_shortcuts, - true - ), - spec!( - "edit.menus", - "Menus…", - ["Edit"], - Some("Cmd+Alt+Shift+M"), - r##"{"hide":["",…]?,"show":["",…]?,"color":{"":"red|orange|yellow|green|blue|violet|gray|none"}?,"reset":bool=false}"##, - menus, - true - ), - spec!("edit.toolbar", "Toolbar…", ["Edit"], None, r##"{"hidden":["",…]?,"order":["",…]?,"reset":bool=false}"##, toolbar, true), - ] -} - #[cfg(test)] #[path = "prefs/tests.rs"] mod tests; diff --git a/crates/engine/src/prefs/cmds.rs b/crates/engine/src/prefs/cmds.rs new file mode 100644 index 0000000000..b8f92356da --- /dev/null +++ b/crates/engine/src/prefs/cmds.rs @@ -0,0 +1,197 @@ +use super::customize::{keyboard_shortcuts, menus}; +use super::validate::{SECTIONS, get_path, keyed}; +use super::*; + +// ------------------------------------------------------------------ commands + +fn always(_: &Session) -> std::result::Result<(), String> { + Ok(()) +} + +pub(super) fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +fn prefs_get(s: &mut Session, p: &Value) -> Result { + let path = p.get("path").and_then(Value::as_str).unwrap_or(""); + let v = s.prefs_view(); + get_path(&v, path).cloned().ok_or_else(|| bad("prefs.get", format!("unknown preference `{path}`"))) +} + +fn prefs_set(s: &mut Session, p: &Value) -> Result { + let cmd = "prefs.set"; + let mut changes: Vec<(String, Value)> = Vec::new(); + if let Some(path) = p.get("path").and_then(Value::as_str) { + changes.push((path.to_string(), p.get("value").cloned().ok_or_else(|| bad(cmd, "missing `value`"))?)); + } + if let Some(m) = p.get("values").and_then(Value::as_object) { + changes.extend(m.iter().map(|(k, v)| (k.clone(), v.clone()))); + } + if changes.is_empty() { + return Err(bad(cmd, "give `path` and `value`, or `values: {path: value, …}`")); + } + // All or nothing: validate against a scratch copy first. + let (saved_prefs, saved_color) = (s.prefs().clone(), s.color.settings.clone()); + let mut color_changed = false; + for (path, v) in &changes { + match s.set_pref(path, v.clone(), false) { + Ok(touched) => color_changed |= touched, + Err(e) => { + s.prefs.edit(|p| *p = saved_prefs); + s.color.settings = saved_color; + return Err(bad(cmd, e)); + } + } + } + if color_changed && let Err(e) = crate::color_cmds::validate_settings(&s.color.settings) { + s.prefs.edit(|p| *p = saved_prefs); + s.color.settings = saved_color; + return Err(bad(cmd, e)); + } + // `colorSettings.blendTextGamma` lives in the compositor too, as `edit.colorSettings` sets it. + photocraft_compose::psblend::set_text_gamma(s.color.settings.blend_text_gamma); + s.apply_prefs(); + let view = s.prefs_view(); + let out: Map = changes.iter().map(|(k, _)| (k.clone(), get_path(&view, k).cloned().unwrap_or(Value::Null))).collect(); + Ok(Value::Object(out)) +} + +fn prefs_reset(s: &mut Session, p: &Value) -> Result { + let path = p.get("path").or_else(|| p.get("section")).and_then(Value::as_str); + match path { + Some("colorSettings") => s.color.settings = Default::default(), + // One colour setting: `Preferences` has no `colorSettings`, so take the default + // from `ColorSettings` and route it like `prefs.set` does. + Some(path) if path.starts_with("colorSettings.") => { + let defaults = serde_json::to_value(crate::color_cmds::ColorSettings::default()).map_err(|e| bad("prefs.reset", e.to_string()))?; + let key = path.strip_prefix("colorSettings.").unwrap_or(path); + let def = get_path(&defaults, key).cloned().ok_or_else(|| bad("prefs.reset", format!("unknown preference `{path}`")))?; + s.set_pref(path, def, true).map_err(|e| bad("prefs.reset", e))?; + } + None => { + s.color.settings = Default::default(); + s.edit_prefs(|p| p.reset(None)).map_err(|e| bad("prefs.reset", e))?; + } + Some(path) => { + let mut next = s.prefs().clone(); + next.reset(Some(path)).map_err(|e| bad("prefs.reset", e))?; + s.edit_prefs(|p| *p = next); + } + } + s.prefs.edit(|_| ()); + photocraft_compose::psblend::set_text_gamma(s.color.settings.blend_text_gamma); + s.apply_prefs(); + if path.is_some_and(|path| keyed(path).is_some()) { + // The removed override is absent, so reading its old path would report an error. + Ok(Value::Null) + } else { + prefs_get(s, &json!({"path": path.unwrap_or("")})) + } +} + +/// `edit.preferences.
`: the section's values (the GUI opens the dialog on it instead). +fn preferences_section(s: &mut Session, p: &Value) -> Result { + let section = p.get("__section").and_then(Value::as_str).unwrap_or("general").to_string(); + let title = SECTIONS.iter().find(|(id, _)| *id == section).map_or("General", |(_, t)| *t); + let values = s.prefs().get(§ion).unwrap_or(Value::Null); + Ok(json!({"section": section, "title": title, "values": values})) +} + +/// Edit › Toolbar: hide tools and reorder the toolbar. +fn toolbar(s: &mut Session, p: &Value) -> Result { + let ids = |k: &str| -> Option> { p.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()) }; + s.edit_prefs(|pr| { + if p.get("reset").and_then(Value::as_bool) == Some(true) { + pr.toolbar = ToolbarCustomization::default(); + } + if let Some(h) = ids("hidden") { + pr.toolbar.hidden = h; + } + if let Some(o) = ids("order") { + pr.toolbar.order = o; + } + }); + Ok(serde_json::to_value(&s.prefs().toolbar).unwrap_or_default()) +} + +macro_rules! spec { + ($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $run:expr, $journal:expr) => { + CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: always, run: $run, journal: $journal } + }; +} + +macro_rules! section { + ($id:literal, $label:literal) => { + section!($id, $label, None) + }; + ($id:literal, $label:literal, $shortcut:expr) => { + CommandSpec { id: $id, label: $label, menu: &["Edit", "Preferences"], shortcut: $shortcut, params: r##"{}"##, enabled: always, run: |s, _| preferences_section(s, &json!({"__section": section_of($id)})), journal: false } + }; +} + +fn section_of(id: &str) -> &str { + id.rsplit('.').next().unwrap_or("general") +} + +/// Preference command specs. +pub fn specs() -> Vec { + vec![ + spec!( + "prefs.get", + "Get Preferences", + [], + None, + r##"{"path":"section.key"?=everything (e.g. "performance.historyStates", "colorSettings.workingRgb")}"##, + prefs_get, + false + ), + spec!( + "prefs.set", + "Set Preferences", + [], + None, + r##"{"path":"section.key","value":json} or {"values":{"section.key":json,…}} (validated; all or nothing)"##, + prefs_set, + false + ), + spec!("prefs.reset", "Reset Preferences", [], None, r##"{"path":"section|section.key"?=everything}"##, prefs_reset, false), + // Photoshop: ⌘K opens Preferences › General (⌘, is Layer › Hide Layers). + section!("edit.preferences.general", "General…", Some("Cmd+K")), + section!("edit.preferences.interface", "Interface…"), + section!("edit.preferences.workspace", "Workspace…"), + section!("edit.preferences.tools", "Tools…"), + section!("edit.preferences.historyLog", "History Log…"), + section!("edit.preferences.fileHandling", "File Handling…"), + section!("edit.preferences.export", "Export…"), + section!("edit.preferences.performance", "Performance…"), + section!("edit.preferences.scratchDisks", "Scratch Disks…"), + section!("edit.preferences.cursors", "Cursors…"), + section!("edit.preferences.transparencyAndGamut", "Transparency & Gamut…"), + section!("edit.preferences.unitsAndRulers", "Units & Rulers…"), + section!("edit.preferences.guidesGridAndSlices", "Guides, Grid & Slices…"), + section!("edit.preferences.plugIns", "Plug-ins…"), + section!("edit.preferences.type", "Type…"), + section!("edit.preferences.enhancedControls", "Enhanced Controls…"), + section!("edit.preferences.rawDefaults", "Camera Raw…"), + section!("edit.preferences.integrations", "Integrations…"), + spec!( + "edit.keyboardShortcuts", + "Keyboard Shortcuts…", + ["Edit"], + Some("Cmd+Alt+Shift+K"), + r##"{"set":{"|tools.temporary.hand|zoomIn|zoomOut":"Cmd+Shift+X"|""(remove)|null(default)}?,"alternates":{"":["F3",…]|[](none)|null(default)}?,"reset":true|["",…]?,"removeConflicts":bool=true,"filter":str?,"list":bool=false,"importKys":"<.kys XML>"|{"path":".kys"}?,"useSet":""|""(defaults)?,"saveSet":""?,"deleteSet":""?,"sets":{"":{"shortcuts":{…},"alternateShortcuts":{…}}}?,"activeSet":""|""?,"exportKys":true|{"path":".kys"}?,"summarize":true|{"mac":bool,"path":".html"}?} (with a path the file is written and the reply has kysPath/htmlPath instead of kys/html)"##, + keyboard_shortcuts, + true + ), + spec!( + "edit.menus", + "Menus…", + ["Edit"], + Some("Cmd+Alt+Shift+M"), + r##"{"hide":["",…]?,"show":["",…]?,"color":{"":"red|orange|yellow|green|blue|violet|gray|none"}?,"reset":bool=false}"##, + menus, + true + ), + spec!("edit.toolbar", "Toolbar…", ["Edit"], None, r##"{"hidden":["",…]?,"order":["",…]?,"reset":bool=false}"##, toolbar, true), + ] +} diff --git a/crates/engine/src/prefs/customize.rs b/crates/engine/src/prefs/customize.rs new file mode 100644 index 0000000000..e6d76723c8 --- /dev/null +++ b/crates/engine/src/prefs/customize.rs @@ -0,0 +1,306 @@ +use super::cmds::bad; +use super::files::{file_target, read_text_file, rename_path, writable, write_files_atomically}; +use super::shortcuts::{BindKind, alternate_keys, bindable, bindable_items, conflicts, default_alternates, is_tool, normalize_shortcut, reserved_shortcut}; +use super::*; + +/// Edit › Keyboard Shortcuts (engine part): list, change and reset application shortcuts. +pub(super) fn keyboard_shortcuts(s: &mut Session, p: &Value) -> Result { + let cmd = "edit.keyboardShortcuts"; + // Every change lands at once, after all of it validated: a bad key leaves the set as it was. + let mut next = s.prefs().clone(); + // A set loads first, so the call's other changes apply on top of it. + let mut changed = crate::shortcut_sets::load(&mut next, p).map_err(|e| bad(cmd, e))?; + if let Some(r) = p.get("reset") { + match r { + Value::Bool(true) => { + next.shortcuts.clear(); + next.alternate_shortcuts.clear(); + changed = true; + } + Value::Array(ids) => { + for id in ids.iter().filter_map(Value::as_str) { + next.shortcuts.remove(id); + next.alternate_shortcuts.remove(id); + } + changed = true; + } + _ => {} + } + } + // A Photoshop `.kys` set (`importKys`, its XML text) becomes `set` and `alternates` entries, + // matched by label (`crate::kys`); a key equal to the command's default restores the + // default, and keys given in `set` / `alternates` as well win over the file's. + let imported; + let mut import = None; + let p = match p.get("importKys") { + Some(v) => { + // The file's text, or {"path": …} to read it. + let read; + let xml = match v { + Value::String(s) => s.as_str(), + Value::Object(o) => { + let path = + o.get("path").and_then(Value::as_str).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, "`importKys.path` is a .kys file"))?; + read = read_text_file(path, crate::kys::MAX_BYTES).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + read.as_str() + } + _ => return Err(bad(cmd, "`importKys` is the text of a .kys file, or {\"path\": …}")), + }; + let set = crate::kys::parse(xml).map_err(|e| bad(cmd, e))?; + let plan = crate::kys::plan(crate::kys::command_candidates(), &set); + let mut merged = serde_json::Map::new(); + // A key the system reserves is left out (reported as `reserved`), not a failed import. + let mut skipped: Vec = Vec::new(); + for (id, sc) in plan.set.iter().filter(|(id, sc)| { + let bad = reserved_shortcut(sc); + if bad { + skipped.push(format!("{id}: {sc}")); + } + !bad + }) { + let default = crate::command_specs().iter().find(|c| c.id == id).and_then(|c| c.shortcut).and_then(normalize_shortcut); + merged.insert(id.clone(), if default.as_deref() == Some(sc.as_str()) { Value::Null } else { json!(sc) }); + } + // Tool keys: a tool's own letter restores it (and its Shift cycling). + let tools = crate::shell_commands::TOOLS.iter().map(|t| (t.0, t.1)); + let (tool_keys, unknown_tools) = crate::kys::plan_tools(tools, &set); + for (id, key) in &tool_keys { + let own = crate::shell_commands::tool_default(id).flatten().is_some_and(|d| d.eq_ignore_ascii_case(key)); + merged.insert(id.clone(), if own { Value::Null } else { json!(key) }); + } + merged.extend(p.get("set").and_then(Value::as_object).cloned().unwrap_or_default()); + let mut alternates = serde_json::Map::new(); + for (id, keys) in &plan.alternate_keys { + let keys: &Vec = &keys.iter().filter(|k| !reserved_shortcut(k)).cloned().collect(); + let main = plan.set.get(id).map(String::as_str); + let default = Preferences::default().alternates(id, main); + alternates.insert(id.clone(), if *keys == default { Value::Null } else { json!(keys) }); + } + alternates.extend(p.get("alternates").and_then(Value::as_object).cloned().unwrap_or_default()); + import = Some(json!({ + "name": set.name, + "imported": plan.set.len(), + "set": plan.set, + "unknown": plan.unknown, + "unreadable": plan.unreadable, + "alternates": plan.alternates, + "alternateKeys": plan.alternate_keys, + "toolKeys": set.tool_keys, + "tools": tool_keys, + "unknownTools": unknown_tools, + "reserved": skipped, + "windows": set.windows, + })); + let mut with_import = p.clone(); + with_import["set"] = Value::Object(merged); + with_import["alternates"] = Value::Object(alternates); + imported = with_import; + &imported + } + None => p, + }; + let empty = serde_json::Map::new(); + let set = match p.get("set") { + Some(Value::Object(m)) => m, + _ => &empty, + }; + let alts = match p.get("alternates") { + None | Some(Value::Null) => &empty, + Some(v) => v.as_object().ok_or_else(|| bad(cmd, "`alternates` maps command ids to lists of shortcuts"))?, + }; + if !set.is_empty() || !alts.is_empty() { + let allow_unknown = p.get("allowUnknown").and_then(Value::as_bool).unwrap_or(false); + changed = true; + // Reserved system keys can't be bound, by hand or from a file. + let reserved = |v: &Value| -> Option { + let keys = match v { + Value::String(s) => vec![s.clone()], + other => alternate_keys(other).unwrap_or_default(), + }; + keys.into_iter().find(|k| reserved_shortcut(k)) + }; + if let Some((id, k)) = set.iter().chain(alts.iter()).find_map(|(id, v)| reserved(v).map(|k| (id, k))) { + return Err(bad(cmd, format!("`{k}` (for `{id}`) is reserved by the system and can't be assigned"))); + } + for (id, v) in set { + if !bindable().any(|(b, _)| b == id) && !allow_unknown { + return Err(bad(cmd, format!("unknown command `{id}`"))); + } + next.set(&format!("shortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?; + } + for (id, v) in alts { + if !bindable().any(|(b, _)| b == id) && default_alternates(id).next().is_none() && !allow_unknown { + return Err(bad(cmd, format!("unknown command `{id}`"))); + } + next.set(&format!("alternateShortcuts.{id}"), v.clone()).map_err(|e| bad(cmd, e))?; + } + // Like Photoshop, a shortcut moved to a new command is taken away from the old one, + // whether the old one held it as its main key or as an alternate (#3665). + if p.get("removeConflicts").and_then(Value::as_bool).unwrap_or(true) { + let assigned: Vec<(&str, String)> = set + .iter() + .filter_map(|(id, v)| Some((id.as_str(), v.as_str().and_then(normalize_shortcut)?))) + .chain(alts.iter().flat_map(|(id, v)| alternate_keys(v).unwrap_or_default().into_iter().map(move |k| (id.as_str(), k)))) + .collect(); + for (id, sc) in assigned { + for (c, def) in bindable() { + // Tools may share a key: they cycle with Shift, as Photoshop's groups do. + if is_tool(id) && is_tool(c) { + continue; + } + // Never strip a command that this same call is assigning: + // two entries for one key are a clash inside the call, which + // the returned conflicts list reports (#719). Stripping + // each other here unbound both silently. + if c == id || set.contains_key(c) || alts.contains_key(c) { + continue; + } + let main = next.shortcut(c, def).map(str::to_string); + if main.as_deref().and_then(normalize_shortcut).as_deref() == Some(sc.as_str()) { + next.shortcuts.insert(c.to_string(), String::new()); + } + let held = next.alternates(c, main.as_deref()); + if held.contains(&sc) { + next.alternate_shortcuts.insert(c.to_string(), held.into_iter().filter(|k| *k != sc).collect()); + } + } + } + } + } + // Then the sets are saved, deleted or switched, from the bindings as they now stand. + changed |= crate::shortcut_sets::store(&mut next, p).map_err(|e| bad(cmd, e))?; + // The reply and the exports read the bindings as they will be; they are committed only once + // the exports are written, so a bad export target changes nothing. + let prefs = &next; + let filter = p.get("filter").and_then(Value::as_str).map(str::to_ascii_lowercase); + let list: Vec = bindable_items() + .filter(|c| filter.as_ref().is_none_or(|f| c.0.to_ascii_lowercase().contains(f) || c.1.to_ascii_lowercase().contains(f))) + .filter(|c| { + p.get("list").and_then(Value::as_bool).unwrap_or(false) + || filter.is_some() + || prefs.shortcuts.contains_key(c.0) + || prefs.alternate_shortcuts.contains_key(c.0) + }) + .map(|(id, label, menu, def, kind)| { + let main = prefs.shortcut(id, def); + let defaults: Vec<&str> = default_alternates(id).collect(); + let mut v = json!({"id": id, "label": label, "menu": menu, "default": def, "shortcut": main, "alternates": prefs.alternates(id, main)}); + if !defaults.is_empty() { + v["defaultAlternates"] = json!(defaults); + } + match kind { + BindKind::Hold => v["hold"] = json!(true), + BindKind::Tool => v["tool"] = json!(true), + BindKind::Command => {} + } + v + }) + .collect(); + let mut bindings: Vec<(&str, String)> = Vec::new(); + for (id, def) in bindable() { + let main = prefs.shortcut(id, def); + bindings.extend(main.map(|m| (id, m.to_string()))); + bindings.extend(prefs.alternates(id, main).into_iter().map(|k| (id, k))); + } + // Tools sharing a key are a cycling group, not a conflict. + let conflicts: Vec = conflicts(bindings.iter().map(|(id, k)| (*id, k.as_str()))) + .into_iter() + .filter(|(_, ids)| !ids.iter().all(|id| is_tool(id))) + .map(|(sc, ids)| json!({"shortcut": sc, "commands": ids})) + .collect(); + let mut out = json!({"overrides": prefs.shortcuts, "alternateOverrides": prefs.alternate_shortcuts, "commands": list, "conflicts": conflicts}); + if let (Some(o), Value::Object(sets)) = (out.as_object_mut(), crate::shortcut_sets::describe(prefs)) { + o.extend(sets); + } + // The bindings as a `.kys` file, or Photoshop's Summarize page: every bindable item (the + // engine's commands, the shell's commands and the tools). + let set_name = if prefs.shortcut_set.is_empty() { crate::shortcut_sets::DEFAULTS_NAME } else { prefs.shortcut_set.as_str() }; + // Both targets are resolved and their texts made before anything is written, and a path that + // can't be written is refused before either file is: a bad export changes nothing. + let kys_target = file_target(cmd, p.get("exportKys"))?; + let html_target = file_target(cmd, p.get("summarize"))?; + let mut files: Vec<(&str, String, String)> = Vec::new(); + if let Some(target) = kys_target { + let entries: Vec = + crate::shortcut_sets::bound(prefs).into_iter().map(|b| crate::kys::Entry { id: b.id, label: b.label, tool: b.tool, keys: b.keys }).collect(); + let text = crate::kys::write(set_name, &entries); + match target { + Some(path) => files.push(("kysPath", path, text)), + None => out["kys"] = json!(text), + } + } + if let Some(target) = html_target { + let v = p.get("summarize").cloned().unwrap_or(Value::Null); + let mac = v.get("mac").and_then(Value::as_bool).unwrap_or(cfg!(target_os = "macos")); + let mut sections: Vec = Vec::new(); + for crate::shortcut_sets::Bound { label, menu, keys, .. } in crate::shortcut_sets::bound(prefs) { + match sections.iter_mut().find(|(m, _)| *m == menu) { + Some((_, rows)) => rows.push((label, keys)), + None => sections.push((menu, vec![(label, keys)])), + } + } + let html = crate::shortcut_sets::summarize(set_name, §ions, mac); + match target { + Some(path) => files.push(("htmlPath", path, html)), + None => out["html"] = json!(html), + } + } + for (_, path, _) in &files { + writable(path).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + } + let list: Vec<(&str, &str)> = files.iter().map(|(_, path, text)| (path.as_str(), text.as_str())).collect(); + write_files_atomically(&list, &rename_path).map_err(|e| bad(cmd, e))?; + for (key, path, _) in &files { + out[*key] = json!(path); + } + if changed { + s.edit_prefs(|p| *p = next); + } + if let Some(import) = import { + out["import"] = import; + } + Ok(out) +} + +/// Edit › Menus: hide/show items and give them colours. +pub(super) fn menus(s: &mut Session, p: &Value) -> Result { + let ids = |k: &str| -> Vec { + p.get(k).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default() + }; + const COLORS: [&str; 8] = ["none", "red", "orange", "yellow", "green", "blue", "violet", "gray"]; + if let Some(m) = p.get("color").and_then(Value::as_object) { + for v in m.values() { + if let Some(c) = v.as_str().filter(|c| !COLORS.contains(c)) { + return Err(bad("edit.menus", format!("unknown colour `{c}` ({})", COLORS.join("|")))); + } + } + } + let (hide, show) = (ids("hide"), ids("show")); + if let Some(id) = hide.iter().find(|id| !MenuCustomization::hideable(id)) { + return Err(bad("edit.menus", format!("`{id}` can't be hidden"))); + } + s.edit_prefs(|pr| { + if p.get("reset").and_then(Value::as_bool) == Some(true) { + pr.menus = MenuCustomization::default(); + } + for id in hide { + if !pr.menus.hidden.contains(&id) { + pr.menus.hidden.push(id); + } + } + pr.menus.hidden.retain(|h| !show.contains(h)); + if let Some(m) = p.get("color").and_then(Value::as_object) { + for (id, v) in m { + match v.as_str() { + Some(c) if c != "none" => { + pr.menus.colors.insert(id.clone(), c.to_string()); + } + _ => { + pr.menus.colors.remove(id); + } + } + } + } + }); + Ok(serde_json::to_value(&s.prefs().menus).unwrap_or_default()) +} diff --git a/crates/engine/src/prefs/files.rs b/crates/engine/src/prefs/files.rs new file mode 100644 index 0000000000..d24205228a --- /dev/null +++ b/crates/engine/src/prefs/files.rs @@ -0,0 +1,199 @@ +use super::cmds::bad; +use super::*; + +/// An output parameter (`exportKys`, `summarize`): absent or false → `None`; true (or an object +/// without `path`) → `Some(None)`, the text comes back in the reply; `{"path": …}` → +/// `Some(Some(path))`, written there. +pub(super) fn file_target(cmd: &str, v: Option<&Value>) -> Result>> { + match v { + None | Some(Value::Null) | Some(Value::Bool(false)) => Ok(None), + Some(Value::Bool(true)) => Ok(Some(None)), + Some(Value::Object(o)) => match o.get("path") { + None | Some(Value::Null) => Ok(Some(None)), + Some(Value::String(s)) if !s.trim().is_empty() => Ok(Some(Some(s.clone()))), + Some(_) => Err(bad(cmd, "`path` must be a non-empty string")), + }, + Some(_) => Err(bad(cmd, "expected true or {\"path\": …}")), + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn read_text_file(path: &str, max: usize) -> std::result::Result { + let meta = std::fs::metadata(path).map_err(|e| e.to_string())?; + if !meta.is_file() || meta.len() > max as u64 { + return Err(format!("not a file of at most {} KiB", max / 1024)); + } + std::fs::read_to_string(path).map_err(|e| e.to_string()) +} + +#[cfg(target_arch = "wasm32")] +pub(super) fn read_text_file(_: &str, _: usize) -> std::result::Result { + Err("paths can't be read on the web; pass the file's text instead".into()) +} + +/// Whether `path` can be written: not a folder, in a folder that exists. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn writable(path: &str) -> std::result::Result<(), String> { + let p = std::path::Path::new(path); + if p.is_dir() { + return Err("is a folder".into()); + } + if std::fs::metadata(p).is_ok_and(|m| m.permissions().readonly()) { + return Err("is read-only".into()); + } + match p.parent().filter(|d| !d.as_os_str().is_empty()) { + Some(d) if !d.is_dir() => Err("its folder doesn't exist".into()), + _ => Ok(()), + } +} + +#[cfg(target_arch = "wasm32")] +pub(super) fn writable(_: &str) -> std::result::Result<(), String> { + Err("paths can't be written on the web; omit `path` to get the text back".into()) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn rename_path(from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> { + std::fs::rename(from, to) +} + +#[cfg(target_arch = "wasm32")] +pub(super) fn rename_path(_: &std::path::Path, _: &std::path::Path) -> std::io::Result<()> { + Err(std::io::Error::other("paths can't be written on the web")) +} + +/// Where `path` points, for telling whether two targets are one file: its folder resolved, its +/// name compared without case where the file system ignores it. +#[cfg(not(target_arch = "wasm32"))] +fn path_key(path: &str) -> String { + let p = std::path::Path::new(path); + let dir = p.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(std::path::Path::new(".")); + let dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()); + let key = dir.join(p.file_name().unwrap_or_default()).to_string_lossy().into_owned(); + if cfg!(any(target_os = "windows", target_os = "macos")) { key.to_lowercase() } else { key } +} + +/// A new, empty file beside `path` with a name nothing else uses (`create_new`), for staging +/// (`kind` "tmp") or a backup ("bak"). +#[cfg(not(target_arch = "wasm32"))] +fn sibling(path: &str, kind: &str) -> std::io::Result<(std::path::PathBuf, std::fs::File)> { + for n in 0..1000u32 { + let p = std::path::PathBuf::from(format!("{path}.{}-{n}.photocraft-{kind}", std::process::id())); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&p) { + Ok(f) => return Ok((p, f)), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + } + Err(std::io::Error::other("no free name beside it")) +} + +/// Write `files` ((path, text)) all or nothing. Each text is staged in a new file beside its +/// target; once every one is written, each existing target is moved aside to a backup and the +/// staged file moved in. Any failure moves the backups back and removes what was staged, so the +/// user's files end as they began; on success the backups go. Two targets naming one file are +/// refused. `rename` is `std::fs::rename` (a test fails it on purpose). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn write_files_atomically( + files: &[(&str, &str)], + rename: &dyn Fn(&std::path::Path, &std::path::Path) -> std::io::Result<()>, +) -> std::result::Result<(), String> { + use std::io::Write; + use std::path::{Path, PathBuf}; + for (i, (a, _)) in files.iter().enumerate() { + if files.iter().skip(i + 1).any(|(b, _)| path_key(a) == path_key(b)) { + return Err(format!("{a}: two exports to the same file")); + } + } + let mut staged: Vec = Vec::new(); + let drop_all = |paths: &[PathBuf]| { + for p in paths { + let _ = std::fs::remove_file(p); + } + }; + for (path, text) in files { + let (tmp, mut f) = match sibling(path, "tmp") { + Ok(v) => v, + Err(e) => { + drop_all(&staged); + return Err(format!("{path}: {e}")); + } + }; + staged.push(tmp); + if let Err(e) = f.write_all(text.as_bytes()).and_then(|()| f.sync_all()) { + drop_all(&staged); + return Err(format!("{path}: {e}")); + } + } + // (target, its backup) of each file moved in so far. + let mut moved: Vec<(&Path, Option)> = Vec::new(); + // Put each backup back over its target (a target that had none is removed). What couldn't be + // put back is named, so the user can find their previous file. + let undo = |moved: &[(&Path, Option)]| -> String { + let mut stranded = Vec::new(); + for (target, backup) in moved.iter().rev() { + match backup { + Some(b) => { + if rename(b, target).is_err() { + stranded.push(format!("the previous {} is at {}", target.display(), b.display())); + } + } + None => { + let _ = std::fs::remove_file(target); + } + } + } + if stranded.is_empty() { String::new() } else { format!(" ({})", stranded.join("; ")) } + }; + for ((path, _), tmp) in files.iter().zip(&staged) { + let target = Path::new(*path); + let backup = if target.exists() { + let moved_aside = sibling(path, "bak").and_then(|(b, f)| { + drop(f); + match rename(target, &b) { + Ok(()) => Ok(b), + Err(e) => { + // The placeholder the backup name reserved goes too. + let _ = std::fs::remove_file(&b); + Err(e) + } + } + }); + match moved_aside { + Ok(b) => Some(b), + Err(e) => { + let stranded = undo(&moved); + drop_all(&staged); + return Err(format!("{path}: {e}{stranded}")); + } + } + } else { + None + }; + if let Err(e) = rename(tmp, target) { + let mut stranded = undo(&moved); + if let Some(b) = &backup + && rename(b, target).is_err() + { + stranded = format!("{stranded} (the previous {path} is at {})", b.display()); + } + drop_all(&staged); + return Err(format!("{path}: {e}{stranded}")); + } + moved.push((target, backup)); + } + for (_, backup) in moved { + if let Some(b) = backup { + let _ = std::fs::remove_file(b); + } + } + Ok(()) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn write_files_atomically( + files: &[(&str, &str)], + _: &dyn Fn(&std::path::Path, &std::path::Path) -> std::io::Result<()>, +) -> std::result::Result<(), String> { + if files.is_empty() { Ok(()) } else { Err("paths can't be written on the web; omit `path` to get the text back".into()) } +} diff --git a/crates/engine/src/prefs/shortcuts.rs b/crates/engine/src/prefs/shortcuts.rs new file mode 100644 index 0000000000..47ba5a5f83 --- /dev/null +++ b/crates/engine/src/prefs/shortcuts.rs @@ -0,0 +1,213 @@ +use super::*; + +/// Most further keys one command may hold; Photoshop's own defaults use one. +pub const MAX_ALTERNATES: usize = 8; + +/// Validate and normalise a command's alternate keys: a list of shortcut strings (a single +/// string is a one-key list, `""` none). +pub fn alternate_keys(v: &Value) -> std::result::Result, String> { + let items: Vec<&Value> = match v { + Value::String(s) if s.is_empty() => Vec::new(), + Value::String(_) => vec![v], + Value::Array(a) => a.iter().collect(), + _ => return Err("alternate shortcuts are a list of shortcuts (e.g. [\"F3\"])".into()), + }; + if items.len() > MAX_ALTERNATES { + return Err(format!("at most {MAX_ALTERNATES} alternate shortcuts (got {})", items.len())); + } + let mut out: Vec = Vec::with_capacity(items.len()); + for item in items { + let s = item.as_str().ok_or_else(|| format!("alternate shortcut `{item}` must be a string"))?; + let n = normalize_shortcut(s).ok_or_else(|| format!("`{s}` is not a valid shortcut (e.g. Cmd+Shift+N, F7)"))?; + if !out.contains(&n) { + out.push(n); + } + } + Ok(out) +} + +// ------------------------------------------------------------------ shortcuts + +/// Canonical spelling of a shortcut: modifiers in `Cmd+Ctrl+Alt+Shift` order, key last +/// (single characters upper-cased). `None` if it has no key or an unknown modifier. +pub fn normalize_shortcut(s: &str) -> Option { + let s = s.trim(); + if s.is_empty() { + return None; + } + let (mut cmd, mut ctrl, mut alt, mut shift) = (false, false, false, false); + let mut key: Option = None; + // A trailing "+" key is spelled "Cmd++". + let (body, plus_key) = if s.ends_with("++") || s == "+" { (s.trim_end_matches('+'), true) } else { (s, false) }; + for part in body.split('+').filter(|p| !p.is_empty()) { + match part.to_ascii_lowercase().as_str() { + "cmd" | "command" | "⌘" | "meta" | "super" => cmd = true, + "ctrl" | "control" | "⌃" => ctrl = true, + "alt" | "option" | "opt" | "⌥" => alt = true, + "shift" | "⇧" => shift = true, + _ => { + if key.is_some() { + return None; + } + let k = if part.chars().count() == 1 { part.to_uppercase() } else { capitalize(part) }; + key = Some(k); + } + } + } + if plus_key { + if key.is_some() { + return None; + } + key = Some("+".into()); + } + let key = key?; + let mut out = Vec::new(); + if cmd { + out.push("Cmd"); + } + if ctrl { + out.push("Ctrl"); + } + if alt { + out.push("Alt"); + } + if shift { + out.push("Shift"); + } + let mut s = out.join("+"); + if !s.is_empty() { + s.push('+'); + } + s.push_str(&key); + Some(s) +} + +/// Key names spelled with more than one capital (egui's `Key::name`): Title case would turn +/// `PageUp` into `Pageup`, which no key matches, so a binding saved that way never fired (#6827). +const MULTI_WORD_KEYS: [&str; 8] = + ["PageUp", "PageDown", "OpenBracket", "CloseBracket", "OpenCurlyBracket", "CloseCurlyBracket", "BrowserBack", "IntlBackslash"]; + +fn capitalize(s: &str) -> String { + if let Some(k) = MULTI_WORD_KEYS.iter().find(|k| k.eq_ignore_ascii_case(s)) { + return (*k).to_string(); + } + let mut c = s.chars(); + match c.next() { + Some(f) if f.is_ascii_alphabetic() => { + let rest: String = c.collect(); + // Function keys stay upper-case (F1…F24); named keys are Title case. + if f.eq_ignore_ascii_case(&'f') && rest.chars().all(|c| c.is_ascii_digit()) && !rest.is_empty() { + format!("F{rest}") + } else { + format!("{}{}", f.to_ascii_uppercase(), rest.to_ascii_lowercase()) + } + } + _ => s.to_string(), + } +} + +/// Hold-and-release gestures (#249): temporary tools that last while their key is held and give +/// the previous tool back on release. They are bound like shortcuts (Edit › Keyboard Shortcuts › +/// Tools › Temporary, `edit.keyboardShortcuts`) but held rather than pressed, so they are not +/// commands; the UI reads their keys through [`Preferences::shortcut`]. While a selection or +/// shape is being dragged, the Hand key repositions it instead of panning (Photoshop's Space). +/// The erase key keeps the Brush or Pencil and makes its strokes erase (Photoshop's `~`). +pub const TEMPORARY_TOOLS: &[(&str, &str, &str)] = &[ + ("tools.temporary.hand", "Hand Tool (hold)", "Space"), + ("tools.temporary.zoomIn", "Zoom In (hold, drag to scrub)", "Cmd+Space"), + ("tools.temporary.zoomOut", "Zoom Out (hold)", "Alt+Space"), + ("tools.temporary.erase", "Erase with Brush or Pencil (hold)", "`"), +]; + +/// Photoshop's second default keys (#3665): (command, key). Each command keeps its main key +/// (the one its menu shows) and answers these as well, as in Photoshop's default set: the +/// legacy function keys F2 Cut, F3 Copy, F4 Paste and Shift+F7 Inverse; Shift+Backspace +/// (Shift+Delete on a Mac) for Fill; ⌘+ beside ⌘= for Zoom In; and off the Mac, Ctrl+F4 beside +/// Ctrl+W for Close (Windows' close-document key; macOS keeps Ctrl+F4 for window focus). +pub const ALTERNATE_SHORTCUTS: &[(&str, &str)] = &[ + ("edit.cut", "F2"), + ("edit.copy", "F3"), + ("edit.paste", "F4"), + ("edit.fill", "Shift+Backspace"), + ("select.inverse", "Shift+F7"), + ("view.zoomIn", "Cmd++"), + #[cfg(not(target_os = "macos"))] + ("file.close", "Cmd+F4"), +]; + +/// A command's default alternate keys ([`ALTERNATE_SHORTCUTS`]). +pub fn default_alternates(id: &str) -> impl Iterator + '_ { + ALTERNATE_SHORTCUTS.iter().filter(move |(c, _)| *c == id).map(|(_, sc)| *sc) +} + +/// Keys the system takes before the app sees them (switching apps, closing the window, force +/// quit): `edit.keyboardShortcuts` won't bind them, as Photoshop won't. `sc` is in our notation, +/// where `Cmd` is Ctrl off the Mac. +pub fn reserved_shortcut(sc: &str) -> bool { + let Some(n) = normalize_shortcut(sc) else { return false }; + let reserved: &[&str] = if cfg!(target_os = "macos") { + &["Cmd+Tab", "Cmd+Shift+Tab", "Cmd+Alt+Escape", "Cmd+`"] + } else if cfg!(target_os = "windows") { + &["Alt+Tab", "Alt+Shift+Tab", "Alt+F4", "Cmd+Alt+Delete", "Cmd+Escape", "Cmd+Shift+Escape"] + } else { + // Linux and the BSDs: window switching and closing, and the virtual consoles. + &[ + "Alt+Tab", + "Alt+Shift+Tab", + "Alt+F4", + "Cmd+Alt+Delete", + "Cmd+Alt+F1", + "Cmd+Alt+F2", + "Cmd+Alt+F3", + "Cmd+Alt+F4", + "Cmd+Alt+F5", + "Cmd+Alt+F6", + "Cmd+Alt+F7", + "Cmd+Alt+F8", + "Cmd+Alt+F9", + "Cmd+Alt+F10", + "Cmd+Alt+F11", + "Cmd+Alt+F12", + ] + }; + reserved.iter().filter_map(|r| normalize_shortcut(r)).any(|r| r == n) +} + +/// What a bindable id is: a command (the engine's or the shell's), a tool, or a held tool. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BindKind { + Command, + Tool, + Hold, +} + +/// Every bindable id: (id, label, menu path, default key, kind). The engine's commands, the +/// shell's ([`crate::shell_commands::SHELL_COMMANDS`]), the tools and the held temporary tools, +/// so Edit › Keyboard Shortcuts works the same with or without the app's UI. +pub fn bindable_items() -> impl Iterator, BindKind)> { + let engine = crate::command_specs().iter().map(|c| (c.id, c.label, c.menu, c.shortcut, BindKind::Command)); + let shell = crate::shell_commands::SHELL_COMMANDS.iter().map(|c| (c.0, c.1, c.2, c.3, BindKind::Command)); + let tools = crate::shell_commands::TOOLS.iter().map(|t| (t.0, t.1, &["Tools"][..], t.2, BindKind::Tool)); + let hold = TEMPORARY_TOOLS.iter().map(|t| (t.0, t.1, &["Tools", "Temporary"][..], Some(t.2), BindKind::Hold)); + engine.chain(shell).chain(tools).chain(hold) +} + +/// Every bindable id with its default. +pub(super) fn bindable() -> impl Iterator)> { + bindable_items().map(|i| (i.0, i.3)) +} + +pub(super) fn is_tool(id: &str) -> bool { + crate::shell_commands::tool_default(id).is_some() +} + +/// Shortcuts bound to more than one command: (shortcut, ids). `bindings` are (id, shortcut). +pub fn conflicts<'a>(bindings: impl IntoIterator) -> Vec<(String, Vec)> { + let mut by: BTreeMap> = BTreeMap::new(); + for (id, sc) in bindings { + if let Some(n) = normalize_shortcut(sc) { + by.entry(n).or_default().push(id.to_string()); + } + } + by.into_iter().filter(|(_, ids)| ids.len() > 1).collect() +} diff --git a/crates/engine/src/prefs/store.rs b/crates/engine/src/prefs/store.rs new file mode 100644 index 0000000000..2e0c3e7576 --- /dev/null +++ b/crates/engine/src/prefs/store.rs @@ -0,0 +1,123 @@ +use super::*; + +// ------------------------------------------------------------------ store + +/// The session's preferences plus a revision counter that moves on every change (frontends +/// persist when it moves). +#[derive(Clone, Debug, Default)] +pub struct PrefsStore { + values: Preferences, + rev: u64, +} + +impl PrefsStore { + pub fn get(&self) -> &Preferences { + &self.values + } + /// Change preferences; bumps the revision. + pub fn edit(&mut self, f: impl FnOnce(&mut Preferences) -> R) -> R { + self.rev += 1; + f(&mut self.values) + } + pub fn rev(&self) -> u64 { + self.rev + } +} + +/// The preferences file format written by [`Session::prefs_value`]. 2: Use Shift Key for Tool +/// Switch stored as chosen (before, a stored `false` was the old default; see `load_prefs_json`). +pub const PREFS_VERSION: u64 = 2; + +/// A saved preference [`Session::load_prefs_json`] couldn't read (a wrong type, an unknown +/// choice) and left at its default. +#[derive(Clone, Debug, PartialEq)] +pub struct InvalidPref { + /// JSON keys from the top of the preferences file (`["fileHandling", "recentFileCount"]`), + /// kept apart because keys such as command ids contain dots. + pub keys: Vec, + /// The value the file held there. + pub value: Value, +} + +impl InvalidPref { + /// The dotted path, as `prefs.get` and `prefs.set` take it. + pub fn path(&self) -> String { + self.keys.join(".") + } +} + +/// How deep [`read_lenient`] looks for the readable parts of an unreadable value. +const LENIENT_DEPTH: usize = 32; + +/// Read `v` as a `T`. When that fails, start from `T::default()` and lay the file's values over +/// it one at a time, keeping each one the whole still reads with and descending into objects +/// that don't, so one bad value resets only itself. The values left out are added to +/// `invalid`, their keys after `prefix`. +pub(super) fn read_lenient(v: Value, prefix: &[&str], invalid: &mut Vec) -> T +where + T: Default + Serialize + for<'de> Deserialize<'de>, +{ + if let Ok(t) = T::deserialize(&v) { + return t; + } + let prefix: Vec = prefix.iter().map(|k| (*k).to_string()).collect(); + let mut acc = serde_json::to_value(T::default()).unwrap_or(Value::Null); + let fits = |root: &Value| T::deserialize(root).is_ok(); + match v { + Value::Object(file) if acc.is_object() && fits(&acc) => { + lay_over(&mut acc, &mut Vec::new(), file, &fits, &prefix, invalid); + T::deserialize(&acc).unwrap_or_default() + } + value => { + invalid.push(InvalidPref { keys: prefix, value }); + T::default() + } + } +} + +/// [`read_lenient`]'s walk: lay `file` over the object at `at` inside `root`, key by key, so that +/// `root` always reads (`fits`). +fn lay_over( + root: &mut Value, + at: &mut Vec, + file: Map, + fits: &dyn Fn(&Value) -> bool, + prefix: &[String], + invalid: &mut Vec, +) { + for (k, fv) in file { + let Some(obj) = object_at(root, at) else { return }; + let old = obj.insert(k.clone(), fv.clone()); + if fits(root) { + continue; + } + // Back to the default. An object keeps its parts that read, and so does a new map entry + // (a shortcut set, a workspace) when it reads from an empty object. + let Some(obj) = object_at(root, at) else { return }; + let mut descend = fv.is_object() && at.len() < LENIENT_DEPTH && matches!(old, None | Some(Value::Object(_))); + match old { + Some(o) => obj.insert(k.clone(), o), + None if descend => obj.insert(k.clone(), Value::Object(Map::new())), + None => obj.remove(&k), + }; + at.push(k); + if descend && !fits(root) { + descend = false; + if let Some((key, parent)) = at.split_last() + && let Some(obj) = object_at(root, parent) + { + obj.remove(key); + } + } + match fv { + Value::Object(m) if descend => lay_over(root, at, m, fits, prefix, invalid), + value => invalid.push(InvalidPref { keys: prefix.iter().chain(at.iter()).cloned().collect(), value }), + } + at.pop(); + } +} + +/// The JSON object at `path` inside `root`. +fn object_at<'a>(root: &'a mut Value, path: &[String]) -> Option<&'a mut Map> { + path.iter().try_fold(root, |cur, k| cur.get_mut(k.as_str()))?.as_object_mut() +} diff --git a/crates/engine/src/prefs/validate.rs b/crates/engine/src/prefs/validate.rs new file mode 100644 index 0000000000..af637f90d9 --- /dev/null +++ b/crates/engine/src/prefs/validate.rs @@ -0,0 +1,272 @@ +use super::shortcuts::normalize_shortcut; +use super::*; + +/// Preferences dialog sections in Photoshop's order: (id, title). +pub const SECTIONS: [(&str, &str); 18] = [ + ("general", "General"), + ("interface", "Interface"), + ("workspace", "Workspace"), + ("tools", "Tools"), + ("historyLog", "History Log"), + ("fileHandling", "File Handling"), + ("export", "Export"), + ("performance", "Performance"), + ("scratchDisks", "Scratch Disks"), + ("cursors", "Cursors"), + ("transparencyAndGamut", "Transparency & Gamut"), + ("unitsAndRulers", "Units & Rulers"), + ("guidesGridAndSlices", "Guides, Grid & Slices"), + ("plugIns", "Plug-ins"), + ("type", "Type"), + ("enhancedControls", "Enhanced Controls"), + ("rawDefaults", "Camera Raw Defaults"), + ("integrations", "Integrations"), +]; + +/// Preferences that nothing reads yet, so Edit › Preferences doesn't show them: a control that +/// does nothing is worse than a missing one (https://github.com/storytold/photocraft/issues/204). +/// They still load, save and round-trip through `prefs.get` / `prefs.set` unchanged. +/// +/// When you implement one, remove it here; the `prefs_usage` test fails while a listed +/// preference is read anywhere outside `prefs.rs`, and while an unlisted one is read nowhere. +pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[ + "general.colorPicker", + "workspace.autoShowHiddenPanels", + "workspace.enableFloatingDocumentWindowDocking", + "performance.effectCacheMb", + "performance.legacyCompositing", + "scratchDisks.disks", + "unitsAndRulers.columnWidth", + "unitsAndRulers.gutter", + "plugIns.showExtensionPanels", + "plugIns.allowScriptsToConnect", + "type.textEngine", + "enhancedControls.scrubbySliderAcceleration", +]; + +/// Is the preference at `path` (`"section.key"`) hidden from the Preferences dialog? +pub fn is_hidden(path: &str) -> bool { + HIDDEN_UNTIL_IMPLEMENTED.contains(&path) || (!cfg!(target_os = "linux") && LINUX_ONLY.contains(&path)) +} + +/// Preferences that only do something on Linux; the dialog doesn't show them elsewhere. They +/// still load, save and round-trip on every platform. +pub const LINUX_ONLY: &[&str] = &["performance.linuxDisplayServer", "performance.gpuAdapter"]; + +/// Whether a graphics adapter called `name` is the one `performance.gpuAdapter` (`wanted`) asks +/// for: every whitespace-separated word of `wanted` appears in the name, ignoring case ("nvidia", +/// "arc a370m"). An empty `wanted` matches nothing. Startup and Preferences share this. +pub fn gpu_adapter_matches(name: &str, wanted: &str) -> bool { + let name = name.to_lowercase(); + let mut words = wanted.split_whitespace().peekable(); + words.peek().is_some() && words.all(|w| name.contains(&w.to_lowercase())) +} + +/// Choices of an enumerated preference (dotted path, e.g. `"cursors.painting"`). +pub fn choices(path: &str) -> Option<&'static [&'static str]> { + Some(match path { + "general.colorPicker" => ColorPicker::NAMES, + "general.imageInterpolation" => Interpolation::NAMES, + "interface.theme" => Theme::NAMES, + "interface.appearanceMode" => AppearanceMode::NAMES, + "interface.darkTheme" => DarkTheme::NAMES, + "interface.lightTheme" => LightTheme::NAMES, + "interface.canvasColor" => CanvasColor::NAMES, + "interface.canvasBorder" => CanvasBorder::NAMES, + "interface.uiScale" => UiScale::NAMES, + "interface.uiFontSize" => UiFontSize::NAMES, + "historyLog.destination" => LogDestination::NAMES, + "historyLog.detail" => LogDetail::NAMES, + "fileHandling.imagePreviews" | "fileHandling.maximizePsdCompatibility" => Ask::NAMES, + "export.quickExportFormat" => QuickExportFormat::NAMES, + "export.quickExportLocation" => ExportLocation::NAMES, + "export.metadata" => ExportMetadata::NAMES, + "cursors.painting" => PaintingCursor::NAMES, + "cursors.other" => OtherCursor::NAMES, + "tools.rightClickWithPaintingTools" => RightClickPaint::NAMES, + "transparencyAndGamut.gridSize" => CheckerSize::NAMES, + "transparencyAndGamut.gridColors" => CheckerColors::NAMES, + "unitsAndRulers.rulers" | "guidesGridAndSlices.gridUnit" => Unit::NAMES, + "unitsAndRulers.typeUnits" => TypeUnit::NAMES, + "unitsAndRulers.pointSize" => PointSize::NAMES, + "guidesGridAndSlices.guideStyle" | "guidesGridAndSlices.gridStyle" => LineStyle::NAMES, + "type.textEngine" => TextEngine::NAMES, + "type.fontPreview" => FontPreview::NAMES, + "rawDefaults.colorSpace" => RawColorSpace::NAMES, + "rawDefaults.bitDepth" => RawDepth::NAMES, + "rawDefaults.sharpenFor" => RawSharpen::NAMES, + "rawDefaults.demosaic" => RawDemosaic::NAMES, + "performance.gpuBackend" => GpuBackend::NAMES, + "performance.linuxDisplayServer" => LinuxDisplayServer::NAMES, + "performance.renderingMode" => RenderingMode::NAMES, + _ => return None, + }) +} + +/// Valid range of a numeric preference. +pub fn range(path: &str) -> Option<(f64, f64)> { + Some(match path { + "fileHandling.autosaveMinutes" => (1.0, 240.0), + "fileHandling.recentFileCount" => (0.0, 100.0), + "tools.nudgeBundlePauseMs" => (100.0, 10_000.0), + "fileHandling.rasterizeSvgGroupsDeeperThan" => (0.0, photocraft_doc::MAX_GROUP_DEPTH as f64), + "interface.notificationDurationSeconds" => (1.0, 120.0), + "export.jpegQuality" | "export.webpQuality" => (1.0, 100.0), + "performance.memoryUsageMb" => (256.0, 1_048_576.0), + "performance.gpuMemoryMb" => (0.0, 1_048_576.0), + "performance.historyStates" => (1.0, 1000.0), + "performance.cacheLevels" => (1.0, 8.0), + "performance.cacheTileSize" => (256.0, 16384.0), + "performance.effectCacheMb" => (16.0, 65536.0), + "transparencyAndGamut.gamutWarningOpacity" => (1.0, 100.0), + "unitsAndRulers.columnWidth" | "unitsAndRulers.gutter" => (0.0, 10_000.0), + "unitsAndRulers.printResolution" | "unitsAndRulers.screenResolution" | "rawDefaults.resolution" => (1.0, 10_000.0), + "guidesGridAndSlices.gridlineEvery" => (0.001, 10_000.0), + "guidesGridAndSlices.subdivisions" => (1.0, 100.0), + "layerMaskOverlay.opacity" => (0.0, 100.0), + "type.recentFonts" => (0.0, 50.0), + "integrations.controlPort" => (0.0, 65535.0), + _ => return None, + }) +} + +/// Is this preference a `#rrggbb` colour? +pub fn is_color(path: &str) -> bool { + if choices(path).is_some() || path.starts_with("shortcuts.") || path.starts_with("alternateShortcuts.") || path.starts_with("menus.") { + return false; + } + if path == "layerMaskOverlay.color" { + return true; + } + let leaf = path.rsplit('.').next().unwrap_or(path); + matches!( + leaf, + "guideColor" + | "smartGuideColor" + | "gridColor" + | "sliceColor" + | "canvasCustomColor" + | "brushPreviewColor" + | "gamutWarningColor" + | "customLight" + | "customDark" + ) +} + +pub fn parse_hex(s: &str) -> Option<[u8; 3]> { + let s = s.trim().trim_start_matches('#'); + if s.len() != 6 { + return None; + } + let b = |i: usize| s.get(i..i + 2).and_then(|s| u8::from_str_radix(s, 16).ok()); + Some([b(0)?, b(2)?, b(4)?]) +} + +// ------------------------------------------------------------------ JSON paths + +/// Map keys that are command ids (which contain dots): `shortcuts.`, +/// `alternateShortcuts.`, `menus.colors.`. +pub(super) fn keyed(path: &str) -> Option<(&str, &str)> { + for prefix in ["shortcuts.", "alternateShortcuts.", "menus.colors."] { + if let Some(id) = path.strip_prefix(prefix) { + return Some((&prefix[..prefix.len() - 1], id)); + } + } + None +} + +pub(super) fn get_path<'a>(root: &'a Value, path: &str) -> Option<&'a Value> { + if path.is_empty() { + return Some(root); + } + if let Some((map, id)) = keyed(path) { + return get_path(root, map)?.get(id); + } + path.split('.').try_fold(root, |v, k| v.get(k)) +} + +/// Set `value` at `path` (creating keys only inside free-form maps such as `shortcuts`). +pub(super) fn set_path(root: &mut Value, path: &str, value: Value) -> std::result::Result<(), String> { + if let Some((map, id)) = keyed(path) { + let mut cur = &mut *root; + for k in map.split('.') { + cur = cur.get_mut(k).ok_or_else(|| format!("unknown preference `{path}`"))?; + } + cur.as_object_mut().ok_or_else(|| format!("`{map}` is not a map"))?.insert(id.to_string(), value); + return Ok(()); + } + let keys: Vec<&str> = path.split('.').filter(|k| !k.is_empty()).collect(); + let Some((last, parents)) = keys.split_last() else { return Err("empty path".into()) }; + let mut cur = root; + for k in parents { + cur = cur.get_mut(*k).ok_or_else(|| format!("unknown preference `{path}`"))?; + } + let free_map = matches!(parents.first(), Some(&"shortcuts")) || (parents.len() == 2 && parents[0] == "menus" && parents[1] == "colors"); + let obj = cur.as_object_mut().ok_or_else(|| format!("`{path}` is not inside a section"))?; + if !obj.contains_key(*last) && !free_map { + return Err(format!("unknown preference `{path}`")); + } + obj.insert(last.to_string(), value); + Ok(()) +} + +/// Validate one value for `path` before it is stored (choices, ranges, colours). +pub(super) fn check_value(path: &str, v: &Value) -> std::result::Result<(), String> { + if path == "interface.favoriteThemes" { + let items = v.as_array().ok_or("`interface.favoriteThemes` must be a list of theme ids")?; + if items.len() > Theme::NAMES.len() { + return Err("`interface.favoriteThemes` contains too many themes".into()); + } + let mut seen = Vec::with_capacity(items.len()); + for item in items { + let theme = item.as_str().and_then(Theme::parse).ok_or_else(|| format!("unknown favorite theme `{item}`"))?; + if seen.contains(&theme) { + return Err(format!("duplicate favorite theme `{}`", theme.name())); + } + seen.push(theme); + } + } + if path == "performance.renderingMode" && v.is_null() { + return Ok(()); // Legacy policy, resolved from useGpu and gpuBackend. + } + if let Some(c) = choices(path) { + let s = v.as_str().ok_or_else(|| format!("`{path}` must be one of {}", c.join("|")))?; + if !c.contains(&s) { + return Err(format!("`{path}` must be one of {} (got `{s}`)", c.join("|"))); + } + } + if path == "interface.language" { + let ok = v.as_str().is_some_and(|s| !s.is_empty() && s.len() <= 16 && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')); + if !ok { + return Err("`interface.language` must be `auto` or a language code such as `en` or `ja`".into()); + } + } + if let Some((lo, hi)) = range(path) { + let x = v.as_f64().ok_or_else(|| format!("`{path}` must be a number"))?; + if !(lo..=hi).contains(&x) { + return Err(format!("`{path}` must be within {lo}..{hi} (got {x})")); + } + } + if is_color(path) && v.as_str().and_then(parse_hex).is_none() { + return Err(format!("`{path}` must be a #rrggbb colour")); + } + if path == "tools.pressureCurve" { + let pts = v.as_array().ok_or("`tools.pressureCurve` must be a list of [input, output] points")?; + if !(2..=PressureCurve::MAX_POINTS).contains(&pts.len()) { + return Err(format!("`tools.pressureCurve` needs 2..={} points (got {})", PressureCurve::MAX_POINTS, pts.len())); + } + for p in pts { + let ok = p.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(|x| x.as_f64().is_some_and(|x| (0.0..=1.0).contains(&x)))); + if !ok { + return Err(format!("`tools.pressureCurve` points are [input, output] pairs within 0..1 (got {p})")); + } + } + } + if let Some(sc) = path.strip_prefix("shortcuts.") { + let s = v.as_str().ok_or_else(|| format!("shortcut for `{sc}` must be a string"))?; + if !s.is_empty() && normalize_shortcut(s).is_none() { + return Err(format!("`{s}` is not a valid shortcut (e.g. Cmd+Shift+N, F7)")); + } + } + Ok(()) +} From e0eb3f4b1b4728035764c688902910b366a8dc44 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:57:27 +0000 Subject: [PATCH 203/259] refactor(engine): split commands.rs into commands/ --- crates/engine/src/commands.rs | 632 +------------------- crates/engine/src/commands/adjust_params.rs | 123 ++++ crates/engine/src/commands/enabled.rs | 100 ++++ crates/engine/src/commands/layer_params.rs | 113 ++++ crates/engine/src/commands/ops.rs | 160 +++++ crates/engine/src/commands/params.rs | 140 +++++ 6 files changed, 654 insertions(+), 614 deletions(-) create mode 100644 crates/engine/src/commands/adjust_params.rs create mode 100644 crates/engine/src/commands/enabled.rs create mode 100644 crates/engine/src/commands/layer_params.rs create mode 100644 crates/engine/src/commands/ops.rs create mode 100644 crates/engine/src/commands/params.rs diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 8c1c6937d7..bfef73b7b7 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -27,98 +27,6 @@ pub struct CommandSpec { pub journal: bool, } -pub(crate) fn always(_: &Session) -> std::result::Result<(), String> { - Ok(()) -} -fn has_doc(s: &Session) -> std::result::Result<(), String> { - s.active().map(|_| ()).ok_or_else(|| "no document open".into()) -} -fn has_layer(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - d.active_layer.filter(|id| d.doc.layer(*id).is_some()).map(|_| ()).ok_or_else(|| "no active layer".into()) -} -fn has_pixel_layer(s: &Session) -> std::result::Result<(), String> { - let l = crate::active_layer_of(s)?; - if matches!(l.content, LayerContent::Raster(_)) { - Ok(()) - } else { - Err(format!("active layer is {} {} layer, not a pixel layer", l.content.article(), l.content.kind_name())) - } -} -/// A pixel layer, or a targeted alpha channel / Quick Mask (adjustments and fills apply to it). -fn has_pixel_or_channel(s: &Session) -> std::result::Result<(), String> { - if crate::channel_cmds::edits_channel(s) { - return Ok(()); - } - has_pixel_layer(s) -} -/// A layer that can be painted: pixels, or any layer with a mask (paint with `"target":"mask"`). -pub(crate) fn has_paintable(s: &Session) -> std::result::Result<(), String> { - if crate::channel_cmds::edits_channel(s) { - return Ok(()); - } - let l = crate::active_layer_of(s)?; - if matches!(l.content, LayerContent::Raster(_)) || l.mask.is_some() { - Ok(()) - } else { - Err(format!("active layer is {} {} layer without a mask", l.content.article(), l.content.kind_name())) - } -} - -/// Surface a paint command writes to: the layer's pixels, its mask with `"target":"mask"`, or a -/// smart object's filter mask with `"target":"filterMask"`. -pub(crate) fn paint_surface<'a>(doc: &'a mut Document, id: LayerId, p: &Value) -> Result<&'a mut photocraft_raster::Surface> { - if is_mask_target(p) { - check_all_unlocked(doc, id)?; - } else { - check_pixels_unlocked(doc, id)?; - } - if crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::FilterMask { - return crate::smart_cmds::filter_mask_surface(doc, id); - } - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if is_mask_target(p) { - l.mask.as_mut().map(|m| &mut m.surface).ok_or_else(|| EngineError::Other("layer has no mask".into())) - } else { - l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into())) - } -} - -pub(crate) fn check_all_unlocked(doc: &Document, id: LayerId) -> Result<()> { - let locks = doc.effective_locks(id); - let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; - if locks.all { - return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))); - } - Ok(()) -} - -/// Refuse a layer whose pixels are locked (directly or through a group), with Photoshop's message. -pub(crate) fn check_pixels_unlocked(doc: &Document, id: LayerId) -> Result<()> { - let locks = doc.effective_locks(id); - let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; - if locks.pixels || locks.all { - return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))); - } - Ok(()) -} - -/// The params target a grayscale mask of the layer: its layer mask (`"mask"`) or, on a smart -/// object, its filter mask (`"filterMask"`). -pub(crate) fn is_mask_target(p: &Value) -> bool { - matches!(p.get("target").and_then(Value::as_str), Some("mask" | "filterMask")) -} - -fn can_undo(s: &Session) -> std::result::Result<(), String> { - s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "nothing to undo".into()) -} -fn can_redo(s: &Session) -> std::result::Result<(), String> { - s.active().filter(|d| d.history.can_redo()).map(|_| ()).ok_or_else(|| "nothing to redo".into()) -} -fn has_selection(s: &Session) -> std::result::Result<(), String> { - s.active().filter(|d| d.doc.selection.is_some()).map(|_| ()).ok_or_else(|| "no selection".into()) -} - /// Image › Image Rotation by a right angle or a flip (pixels, vectors, guides, … all move). fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result { if let Some(d) = s.active() { @@ -141,6 +49,24 @@ macro_rules! cmd { }; } +mod adjust_params; +mod enabled; +mod layer_params; +mod ops; +mod params; + +pub(crate) use adjust_params::inject_kind; +use adjust_params::{adjust_mode, destructive_adjust, doc_mode, gray_tone_params, new_adjustment}; +pub use adjust_params::{adjustment_from_params, adjustment_kind}; +pub(crate) use enabled::{always, check_all_unlocked, check_pixels_unlocked, has_paintable, is_mask_target, paint_surface}; +use enabled::{can_redo, can_undo, has_doc, has_layer, has_pixel_layer, has_pixel_or_channel, has_selection}; +pub use layer_params::blend_from_str; +pub(crate) use layer_params::{NEW_LAYER_PATH, explicit_layer, layer_listing, layer_panel_option, layer_param, mask_at_depth, mask_new_layer, selection_mask}; +use ops::{arrange, merge_group, set_mask, set_mask_and_deselect}; +pub(crate) use ops::{layer_copy, translate_layer}; +use params::{bad, set_clipped}; +pub(crate) use params::{check_f32_values, color_param, int, int_i32, parse_hex, u32_id, u32_id_param}; + pub fn command_specs() -> &'static [CommandSpec] { ®istry().specs } @@ -206,336 +132,6 @@ fn registry() -> &'static Registry { REGISTRY.get_or_init(|| Registry::new(build())) } -// ---------- param helpers ---------- - -fn bad(cmd: &str, msg: impl Into) -> EngineError { - EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } -} -/// Integer parameter that also accepts JSON floats (UIs send `12.0`); rounds. -pub(crate) fn int(p: &Value, key: &str) -> Option { - p.get(key).and_then(|v| v.as_i64().or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round() as i64))) -} - -/// [`int`] narrowed to `i32` for geometry: `None` when absent, and a bad-params error when the -/// value would wrap through `as i32` — out-of-range integers truncate by multiples of 2^32, -/// which silently relocates geometry (`dx = 2^32 + 50` moves 50 px, `3e9` goes negative) -/// instead of erroring. -pub(crate) fn int_i32(cmd: &str, p: &Value, key: &str) -> Result> { - match int(p, key) { - None => Ok(None), - Some(v) => i32::try_from(v).map(Some).map_err(|_| bad(cmd, format!("`{key}` = {v} is outside the 32-bit coordinate range"))), - } -} - -/// An id (layer comp, slice, style…) from a JSON value: a bad-params error unless it is a whole -/// number in `u32` range. `as u32` would wrap `2^32 + 1` to `1` and target a real item. -pub(crate) fn u32_id(cmd: &str, key: &str, v: &Value) -> Result { - v.as_u64().and_then(|n| u32::try_from(n).ok()).ok_or_else(|| bad(cmd, format!("`{key}` = {v} is not a valid id (0..={})", u32::MAX))) -} - -/// [`u32_id`] of `p[key]`: `None` when absent. -pub(crate) fn u32_id_param(cmd: &str, p: &Value, key: &str) -> Result> { - p.get(key).map(|v| u32_id(cmd, key, v)).transpose() -} - -/// JSON numbers may be finite f64 values but overflow when stored in a document's f32 field. -pub(crate) fn finite_f32(cmd: &str, key: &str, value: f64) -> Result { - let narrowed = value as f32; - if narrowed.is_finite() { Ok(narrowed) } else { Err(bad(cmd, format!("`{key}` must fit a finite 32-bit number"))) } -} - -/// Effect/type parameters contain nested colour arrays and snapshots as well as scalars. -/// Validate before parsing or editing, including numbers hidden in an effect snapshot. -pub(crate) fn check_f32_values(cmd: &str, value: &Value) -> Result<()> { - // Bound the call stack, without allocating a work list proportional to an input array. - fn check(cmd: &str, value: &Value, depth: usize) -> Result<()> { - if depth > 64 { - return Err(bad(cmd, "parameters nested deeper than 64 levels")); - } - match value { - Value::Number(n) => { - finite_f32(cmd, "number", n.as_f64().ok_or_else(|| bad(cmd, "invalid number"))?)?; - } - Value::Array(a) => { - for v in a { - check(cmd, v, depth + 1)?; - } - } - Value::Object(o) => { - for v in o.values() { - check(cmd, v, depth + 1)?; - } - } - _ => {} - } - Ok(()) - } - check(cmd, value, 0) -} - -pub(crate) fn color_param(cmd: &str, p: &Value, key: &str, default: [f32; 4]) -> Result<[f32; 4]> { - Ok(match p.get(key) { - Some(Value::Array(a)) if a.len() >= 3 => { - let mut out = [0.0, 0.0, 0.0, 1.0]; - for (slot, value) in out.iter_mut().zip(a) { - *slot = finite_f32(cmd, key, value.as_f64().unwrap_or(0.0))?; - } - out - } - Some(Value::String(s)) => parse_hex(s).unwrap_or(default), - _ => default, - }) -} -pub(crate) fn parse_hex(s: &str) -> Option<[f32; 4]> { - let s = s.trim_start_matches('#'); - // `from_str_radix` accepts a leading '+', so "+f" would read as 0x0f. - if !s.bytes().all(|c| c.is_ascii_hexdigit()) { - return None; - } - let b = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| v as f32 / 255.0); - match s.len() { - 6 => Some([b(0)?, b(2)?, b(4)?, 1.0]), - 8 => Some([b(0)?, b(2)?, b(4)?, b(6)?]), - _ => None, - } -} -/// Layer › Create / Release Clipping Mask. With a `layer` param, just that layer. Otherwise, as in -/// Photoshop, the selection (#1248): Create clips every selected layer except the lowest, which -/// becomes the base; Release releases every selected layer. Releasing a clipped layer also -/// releases the clipped layers above it in its group, as Adobe documents ("removes the selected -/// layer and any layers above it from the clipping mask"), so none is left clipped to a layer -/// that is no longer clipped. One history step either way. -fn set_clipped(s: &mut Session, p: &Value, clip: bool) -> Result { - let label = if clip { "Create Clipping Mask" } else { "Release Clipping Mask" }; - let ids: Vec = if p.get("layer").is_some() { - vec![layer_param(s, p)?] - } else { - let selected = s.active().ok_or(EngineError::NoDocument)?.selected_layers(); - match (clip, selected.as_slice()) { - (_, []) => vec![layer_param(s, p)?], - (_, [one]) => vec![*one], - (true, [_base, rest @ ..]) => rest.to_vec(), - (false, all) => all.to_vec(), - } - }; - let ids = if clip { - ids - } else { - let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; - let mut all = ids.clone(); - for id in ids.iter().filter(|id| doc.layer(**id).is_some_and(|l| l.clipped)) { - for above in crate::clip_group::clipped_above(doc, *id) { - if !all.contains(&above) { - all.push(above); - } - } - } - all - }; - s.edit(label, |doc, _| { - for id in &ids { - doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.clipped = clip; - } - Ok(()) - })?; - Ok(json!({"layers": ids.iter().map(|id| id.0).collect::>()})) -} - -/// The layer a command's `"layer"` param names: an id, or a name (the topmost layer of that -/// name, as Photoshop's "select layer by name" action step finds it, so a loaded action replays -/// in another document; a name that matches no layer exactly matches regardless of case, so -/// `"background"` finds the Background). `None` when the param is absent. -pub(crate) fn explicit_layer(s: &Session, p: &Value) -> Result> { - match p.get("layer") { - Some(Value::Number(n)) => { - n.as_u64().map(|id| Some(LayerId(id))).ok_or_else(|| EngineError::Other(format!("layer id {n} is not a non-negative integer"))) - } - Some(Value::String(name)) => { - let d = s.active().ok_or(EngineError::NoDocument)?; - let layers = d.doc.walk(); - let mut top_down = layers.iter().rev(); - top_down - .clone() - .find(|(_, _, l)| l.name == *name) - .or_else(|| top_down.find(|(_, _, l)| l.name.to_lowercase() == name.to_lowercase())) - .map(|(_, _, l)| Some(l.id)) - .ok_or_else(|| EngineError::Other(format!("no layer named \"{name}\"; {}", layer_listing(&d.doc)))) - } - Some(Value::Null) | None => Ok(None), - Some(other) => Err(EngineError::Other(format!("`layer` must be an id or a name, not {other}"))), - } -} - -/// The layers of `doc` as a caller can name them, for an error about a layer that isn't there: -/// `the document's layers are 2 "Background", 3 "Layer 1"` (top-down, at most 20). -pub(crate) fn layer_listing(doc: &Document) -> String { - const MAX: usize = 20; - let layers = doc.walk(); - if layers.is_empty() { - return "the document has no layers".into(); - } - // Names are unbounded input: each one is cut at NAME characters so the error stays short. - const NAME: usize = 64; - let name = |n: &str| match n.char_indices().nth(NAME) { - Some((cut, _)) => format!("{}…", &n[..cut]), - None => n.to_string(), - }; - let mut list: Vec = layers.iter().rev().take(MAX).map(|(_, _, l)| format!("{} {:?}", l.id.0, name(&l.name))).collect(); - if layers.len() > MAX { - list.push(format!("… {} more (see `document.inspect`)", layers.len() - MAX)); - } - format!("the document's layers are {} (a `layer` param takes an id or a name)", list.join(", ")) -} - -/// The layer a command targets: [`explicit_layer`], else the active layer. -pub(crate) fn layer_param(s: &Session, p: &Value) -> Result { - match explicit_layer(s, p)? { - Some(id) => Ok(id), - None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())), - } -} -pub fn blend_from_str(s: &str) -> Option { - let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], ""); - let want = norm(s); - std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()).find(|m| norm(m.label()) == want || norm(&format!("{m:?}")) == want) -} - -/// The active selection as the mask of a layer being created, or None without a selection. -/// Photoshop masks a new adjustment or fill layer with the selection, so the adjustment acts on -/// the selected area only (#1250); the selection itself stays, as Reveal Selection leaves it. -pub(crate) fn selection_mask(doc: &Document) -> Result> { - doc.selection.as_ref().map(|sel| mask_at_depth(LayerMask { surface: sel.clone(), ..LayerMask::reveal_all() }, doc.depth)).transpose() -} - -/// New pixel masks use the document's depth, as PSD saves/imports do. Otherwise a later soft -/// brush stroke quantizes differently depending on whether the document reopened as PSD or -/// native. Converting a selection keeps its coverage and does not alter the selection itself. -pub(crate) fn mask_at_depth(mut mask: LayerMask, depth: SampleType) -> Result { - let format = mask.surface.format().with_sample(depth); - if mask.surface.format() != format { - mask.surface = mask.surface.try_convert(format)?; - } - Ok(mask) -} - -/// Options from the Layers Panel flyout live in preferences so headless/keyboard commands -/// behave exactly like pointer-triggered commands. Old preferences preserve Photoshop defaults. -pub(crate) fn layer_panel_option(s: &Session, key: &str, fallback: bool) -> bool { - s.prefs().dialogs.get("ui.layersPanelOptions").and_then(|v| v.get(key)).and_then(Value::as_bool).unwrap_or(fallback) -} - -/// Mask a fill or adjustment layer being created, as Photoshop does: the path selected in the -/// Paths panel (`"path"`: `"work"`, a saved path's name or a path object) becomes its vector -/// mask, which makes a Solid Color fill a shape (#1419); without one, the selection becomes its -/// layer mask ([`selection_mask`]); without either, a white mask reveals the whole layer (#1768). -/// A path that isn't there is an error. -pub(crate) fn mask_new_layer(doc: &Document, l: &mut Layer, p: &Value, cmd: &str, default_mask: bool) -> Result<()> { - let path = match p.get("path") { - None | Some(Value::Null) => None, - Some(Value::String(n)) if crate::vector_cmds::is_work(Some(n)) => Some(doc.work_path.clone().ok_or_else(|| bad(cmd, "no work path"))?), - Some(Value::String(n)) => { - Some(doc.paths.iter().find(|sp| sp.name == *n).map(|sp| sp.path.clone()).ok_or_else(|| bad(cmd, format!("no path named \"{n}\"")))?) - } - Some(v) => Some(crate::vector_cmds::parse_path(v).map_err(|e| bad(cmd, e))?), - }; - match path { - Some(path) => l.vector_mask = Some(photocraft_doc::VectorMask::new(path)), - None => { - l.mask = selection_mask(doc)?.or_else(|| default_mask.then(LayerMask::reveal_all)).map(|mask| mask_at_depth(mask, doc.depth)).transpose()?; - } - } - Ok(()) -} - -/// The `"path"` param of the new fill and adjustment layer commands ([`mask_new_layer`]). -pub(crate) const NEW_LAYER_PATH: &str = - r##""path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask, or white with no selection)"##; - -/// Add an adjustment layer above the active one; it takes the mask `mask_new_layer` builds from `p` (a path, the selection, or the default white mask). -fn new_adjustment(s: &mut Session, adj: Adjustment, p: &Value, cmd: &str) -> Result { - let label = format!("New {} Layer", adj.label()); - let name = adj.label().to_string(); - let id = s.edit(&label, |doc, active| { - let mut l = Layer::new(doc.next_layer_name(&name), LayerContent::Adjustment(adj)); - mask_new_layer(doc, &mut l, p, cmd, true)?; - let id = doc.insert_above(*active, l); - *active = Some(id); - Ok(id) - })?; - Ok(json!({ "layer": id.0 })) -} - -/// Apply `adj` in place to the targeted layer mask, the targeted alpha channel or Quick Mask, or else the active layer's pixels, as one history step named `label`. -fn destructive_adjust(s: &mut Session, label: &str, adj: Adjustment, p: &Value) -> Result { - if is_mask_target(p) { - // The targeted layer mask (#780): ⌘I inverts it, as in Photoshop. - let id = layer_param(s, &Value::Null)?; - return s.edit(label, |doc, _| { - check_all_unlocked(doc, id)?; - let sel = doc.selection.clone(); - pixels::adjust_mask(paint_surface(doc, id, p)?, &adj, sel.as_ref()).map_err(EngineError::Other)?; - Ok(Value::Null) - }); - } - if crate::channel_cmds::is_channel_target(p) { - // Alpha channel / Quick Mask target: the adjustment runs on the grayscale channel as on - // a layer mask, its unstored black included, so ⌘I in Quick Mask inverts it all (#6095). - return s.edit(label, |doc, _| { - let sel = doc.selection.clone(); - if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, None, p)? { - pixels::adjust_mask(surf, &adj, sel.as_ref()).map_err(EngineError::Other)?; - } - Ok(Value::Null) - }); - } - let id = layer_param(s, &Value::Null)?; - s.edit(label, |doc, _| { - let sel = doc.selection.clone(); - let mode = doc.mode; - let surf = paint_surface(doc, id, &Value::Null)?; - pixels::adjust_surface(surf, &adj, sel.as_ref(), mode).map_err(EngineError::Other)?; - Ok(()) - })?; - Ok(Value::Null) -} - -/// Lenient adjustment from params for previews: bad params fall back to the kind's defaults. -/// Commands use the checked [`crate::adjust_params::from_params`]. -pub fn adjustment_from_params(kind: &str, p: &Value) -> Adjustment { - crate::adjust_params::from_params(kind, p, None, ColorMode::Rgb) - .or_else(|_| crate::adjust_params::default_for(kind, ColorMode::Rgb)) - .unwrap_or(Adjustment::Invert) -} - -fn doc_mode(s: &Session) -> ColorMode { - s.active().map_or(ColorMode::Rgb, |d| d.doc.mode) -} - -/// The colour mode a destructive adjustment parses its tone space in: a targeted layer mask, -/// saved channel or Quick Mask holds gray levels whatever the document's mode, so Curves and -/// Levels stay in the neutral space instead of Lab (where the composite is ignored) or CMYK -/// (where the curve runs on the inks) (#5335). -fn adjust_mode(s: &Session, p: &Value) -> ColorMode { - if is_mask_target(p) || crate::channel_cmds::is_channel_target(p) { ColorMode::Grayscale } else { doc_mode(s) } -} - -/// Tone params for a gray plane target: the document-space channel records are dropped, because -/// those keys select the Lab or CMYK tone space and a plane only holds levels (#5335). -fn gray_tone_params(p: &Value) -> Value { - match p { - Value::Object(m) => { - let mut o = Map::new(); - for (k, v) in m { - if !matches!(k.as_str(), "cyan" | "magenta" | "yellow" | "black" | "lightness" | "a" | "b") { - o.insert(k.clone(), v.clone()); - } - } - Value::Object(o) - } - other => other.clone(), - } -} - // ---------- the table ---------- #[allow(clippy::too_many_lines)] @@ -1623,198 +1219,6 @@ fn test_panic_command() -> CommandSpec { CommandSpec { id: "test.panic", label: "Test Panic", menu: &[], shortcut: None, params: r##"{}"##, enabled: |_: &Session| Ok(()), run, journal: false } } -/// Commands generated from a table share one `run` fn; the kind is recovered from the id. -pub(crate) fn inject_kind(id: &str, params: Value) -> Value { - let kind = id.strip_prefix("layer.newAdjustmentLayer.").or_else(|| id.strip_prefix("image.adjustments.")); - match (kind, params) { - (Some(k), Value::Object(mut m)) => { - m.insert("__kind".into(), Value::String(k.into())); - Value::Object(m) - } - (Some(k), _) => json!({ "__kind": k }), - (None, p) => p, - } -} - -pub fn adjustment_kind(a: &Adjustment) -> &'static str { - match a { - Adjustment::BrightnessContrast { .. } => "brightnessContrast", - Adjustment::Levels { .. } => "levels", - Adjustment::Curves { .. } => "curves", - Adjustment::Exposure { .. } => "exposure", - Adjustment::Vibrance { .. } => "vibrance", - Adjustment::HueSaturation { .. } => "hueSaturation", - Adjustment::ColorBalance { .. } => "colorBalance", - Adjustment::BlackWhite { .. } => "blackWhite", - Adjustment::PhotoFilter { .. } => "photoFilter", - Adjustment::ChannelMixer { .. } => "channelMixer", - Adjustment::Posterize { .. } => "posterize", - Adjustment::Threshold { .. } => "threshold", - Adjustment::GradientMap { .. } => "gradientMap", - Adjustment::SelectiveColor { .. } => "selectiveColor", - Adjustment::ColorLookup { .. } => "colorLookup", - Adjustment::Unsupported { .. } => "unsupported", - _ => "invert", - } -} - -fn arrange(s: &mut Session, p: &Value, delta: i32) -> Result { - let id = layer_param(s, p)?; - s.edit("Arrange", |doc, _| { - // The Background stays at the bottom: it doesn't move and nothing goes below it. - let bg = crate::background_cmds::background_id(doc); - if bg == Some(id) { - return Err(EngineError::Other("the Background layer can't be moved".into())); - } - let steps = match delta { - i32::MAX => 10_000, - i32::MIN => -10_000, - d => d, - }; - let dir = steps.signum(); - let before = crate::clip_group::Before::read(doc, &[id]); - let mut moved = false; - for _ in 0..steps.abs() { - if !doc.shift(id, dir) { - break; - } - if crate::background_cmds::keep_background_at_bottom(bg, doc).is_err() { - doc.shift(id, -dir); - break; - } - moved = true; - } - if !moved { - return Err(EngineError::Other("layer can't move further".into())); - } - crate::clip_group::settle(doc, &[id], &before, false); - Ok(()) - })?; - Ok(Value::Null) -} - -/// Add (`Some`) or remove (`None`) a layer mask. Adding acts on every selected layer that can take -/// one ([`crate::layer_multi_cmds::mask_targets`]), in one history step. -fn set_mask(s: &mut Session, p: &Value, label: &str, mask: Option) -> Result { - set_mask_with(s, p, label, mask, false) -} - -/// [`set_mask`] that also drops the selection the mask was made from, in the same history step. -fn set_mask_and_deselect(s: &mut Session, p: &Value, label: &str, mask: LayerMask) -> Result { - set_mask_with(s, p, label, Some(mask), true) -} - -fn set_mask_with(s: &mut Session, p: &Value, label: &str, mask: Option, deselect: bool) -> Result { - let ids = if mask.is_some() { crate::layer_multi_cmds::mask_targets(s, p)? } else { vec![layer_param(s, p)?] }; - s.edit(label, |doc, _| { - let mask = mask.clone().map(|mask| mask_at_depth(mask, doc.depth)).transpose()?; - for id in &ids { - check_all_unlocked(doc, *id)?; - if mask.is_some() { - crate::extra_cmds::background_to_layer_for_mask(doc, *id); - } - doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.mask = mask.clone(); - } - if deselect { - doc.selection = None; - } - Ok(()) - })?; - Ok(Value::Null) -} - -/// Move a layer's pixels, linked mask and type by whole pixels (vectors move via -/// `vector_cmds::translate_vectors`). -pub(crate) fn translate_layer(doc: &Document, l: &mut Layer, dx: i32, dy: i32) { - use crate::layer_multi_cmds::shift_surface as translate_surface; - // Linked patterns in the layer's effects move with it. - if let Some(r) = &mut l.effects.reference { - *r = (r.0 + f64::from(dx), r.1 + f64::from(dy)); - } - if let Some(m) = &mut l.mask - && m.linked - { - m.surface = translate_surface(&m.surface, dx, dy); - } - match &mut l.content { - LayerContent::Raster(s) => *s = translate_surface(s, dx, dy), - LayerContent::Text(t) => { - t.transform = photocraft_geom::Affine::translate(dx as f64, dy as f64).mul(&t.transform); - // A whole-pixel move shifts the rendered text and its PSD position as they are. - // Re-rendering would replace Photoshop's rendering of imported type, and drop the - // text when its font is missing (artboard export, moving type with the Move tool). - let raw = t.psd_raw.as_deref().map(|r| photocraft_text::psd::translate_tysh(r, f64::from(dx), f64::from(dy))); - match (&mut t.cache, raw) { - (Some(c), Some(Some(r))) => { - *c = translate_surface(c, dx, dy); - t.psd_raw = Some(std::sync::Arc::new(r)); - } - (Some(c), None) => *c = translate_surface(c, dx, dy), - _ => crate::type_cmds::refresh(doc, t), - } - } - LayerContent::Group(g) => { - // Moving an artboard moves the board with its contents. - if let Some(a) = &mut g.artboard { - a.rect = a.rect.translate(dx, dy); - } - for c in &mut g.children { - translate_layer(doc, c, dx, dy); - } - } - LayerContent::Smart(sm) => crate::smart_cmds::shift_smart(sm, dx, dy), - _ => {} - } -} - -/// A copy of layer `id` as Layer › Duplicate Layer makes it, not yet in the document: a fresh id, -/// "… copy" appended to the name, and a copy of the Background layer is an ordinary, unlocked -/// layer (Photoshop). -pub(crate) fn layer_copy(doc: &Document, id: LayerId, add_copy: bool) -> Result { - let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?; - // A copy of the Background layer is an ordinary, unlocked layer (Photoshop). - let from_background = doc.is_background(id); - let mut dup = src.duplicate(); - if add_copy { - dup.name = doc.copy_name(&dup.name); - } - if from_background { - dup.locks = Default::default(); - } - Ok(dup) -} - -/// Layer › Merge Group (⌘E with a group selected, #3832): the group's visible contents, as they -/// show, become one pixel layer in its place, named after it. Like Photoshop, the layer keeps the -/// group's opacity, blend mode (Pass Through becomes Normal), clipping and locks; the group's mask -/// and style are applied to the pixels. -fn merge_group(s: &mut Session, id: LayerId) -> Result { - s.edit("Merge Group", |doc, active| { - let group = doc.layer(id).ok_or(EngineError::NoLayer(id))?.clone(); - if !group.visible { - return Err(EngineError::Other("the group is hidden".into())); - } - let fmt = doc.pixel_format(); - let fmt = photocraft_color::PixelFormat::new(fmt.mode, fmt.sample, true); - let mut solo = group.clone(); - solo.opacity = 1.0; - solo.blend = photocraft_doc::BlendMode::Normal; - solo.clipped = false; - let mut tmp = doc.clone(); - tmp.layers = vec![solo]; - let mut merged = Layer::new(group.name.clone(), LayerContent::Raster(pixels::composite_layers_uncropped(&tmp, fmt))); - merged.id = group.id; - merged.opacity = group.opacity; - merged.blend = if group.blend == photocraft_doc::BlendMode::PassThrough { photocraft_doc::BlendMode::Normal } else { group.blend }; - merged.clipped = group.clipped; - merged.locks = group.locks; - *doc.layer_mut(id).ok_or(EngineError::NoLayer(id))? = merged; - *active = Some(id); - Ok(()) - })?; - Ok(json!({ "layer": id.0 })) -} - #[cfg(test)] mod registry_tests { use super::*; diff --git a/crates/engine/src/commands/adjust_params.rs b/crates/engine/src/commands/adjust_params.rs new file mode 100644 index 0000000000..d70ff79dcb --- /dev/null +++ b/crates/engine/src/commands/adjust_params.rs @@ -0,0 +1,123 @@ +use super::enabled::{check_all_unlocked, is_mask_target, paint_surface}; +use super::layer_params::{layer_param, mask_new_layer}; +use super::*; + +/// Add an adjustment layer above the active one; it takes the mask `mask_new_layer` builds from `p` (a path, the selection, or the default white mask). +pub(super) fn new_adjustment(s: &mut Session, adj: Adjustment, p: &Value, cmd: &str) -> Result { + let label = format!("New {} Layer", adj.label()); + let name = adj.label().to_string(); + let id = s.edit(&label, |doc, active| { + let mut l = Layer::new(doc.next_layer_name(&name), LayerContent::Adjustment(adj)); + mask_new_layer(doc, &mut l, p, cmd, true)?; + let id = doc.insert_above(*active, l); + *active = Some(id); + Ok(id) + })?; + Ok(json!({ "layer": id.0 })) +} + +/// Apply `adj` in place to the targeted layer mask, the targeted alpha channel or Quick Mask, or else the active layer's pixels, as one history step named `label`. +pub(super) fn destructive_adjust(s: &mut Session, label: &str, adj: Adjustment, p: &Value) -> Result { + if is_mask_target(p) { + // The targeted layer mask (#780): ⌘I inverts it, as in Photoshop. + let id = layer_param(s, &Value::Null)?; + return s.edit(label, |doc, _| { + check_all_unlocked(doc, id)?; + let sel = doc.selection.clone(); + pixels::adjust_mask(paint_surface(doc, id, p)?, &adj, sel.as_ref()).map_err(EngineError::Other)?; + Ok(Value::Null) + }); + } + if crate::channel_cmds::is_channel_target(p) { + // Alpha channel / Quick Mask target: the adjustment runs on the grayscale channel as on + // a layer mask, its unstored black included, so ⌘I in Quick Mask inverts it all (#6095). + return s.edit(label, |doc, _| { + let sel = doc.selection.clone(); + if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, None, p)? { + pixels::adjust_mask(surf, &adj, sel.as_ref()).map_err(EngineError::Other)?; + } + Ok(Value::Null) + }); + } + let id = layer_param(s, &Value::Null)?; + s.edit(label, |doc, _| { + let sel = doc.selection.clone(); + let mode = doc.mode; + let surf = paint_surface(doc, id, &Value::Null)?; + pixels::adjust_surface(surf, &adj, sel.as_ref(), mode).map_err(EngineError::Other)?; + Ok(()) + })?; + Ok(Value::Null) +} + +/// Lenient adjustment from params for previews: bad params fall back to the kind's defaults. +/// Commands use the checked [`crate::adjust_params::from_params`]. +pub fn adjustment_from_params(kind: &str, p: &Value) -> Adjustment { + crate::adjust_params::from_params(kind, p, None, ColorMode::Rgb) + .or_else(|_| crate::adjust_params::default_for(kind, ColorMode::Rgb)) + .unwrap_or(Adjustment::Invert) +} + +pub(super) fn doc_mode(s: &Session) -> ColorMode { + s.active().map_or(ColorMode::Rgb, |d| d.doc.mode) +} + +/// The colour mode a destructive adjustment parses its tone space in: a targeted layer mask, +/// saved channel or Quick Mask holds gray levels whatever the document's mode, so Curves and +/// Levels stay in the neutral space instead of Lab (where the composite is ignored) or CMYK +/// (where the curve runs on the inks) (#5335). +pub(super) fn adjust_mode(s: &Session, p: &Value) -> ColorMode { + if is_mask_target(p) || crate::channel_cmds::is_channel_target(p) { ColorMode::Grayscale } else { doc_mode(s) } +} + +/// Tone params for a gray plane target: the document-space channel records are dropped, because +/// those keys select the Lab or CMYK tone space and a plane only holds levels (#5335). +pub(super) fn gray_tone_params(p: &Value) -> Value { + match p { + Value::Object(m) => { + let mut o = Map::new(); + for (k, v) in m { + if !matches!(k.as_str(), "cyan" | "magenta" | "yellow" | "black" | "lightness" | "a" | "b") { + o.insert(k.clone(), v.clone()); + } + } + Value::Object(o) + } + other => other.clone(), + } +} + +/// Commands generated from a table share one `run` fn; the kind is recovered from the id. +pub(crate) fn inject_kind(id: &str, params: Value) -> Value { + let kind = id.strip_prefix("layer.newAdjustmentLayer.").or_else(|| id.strip_prefix("image.adjustments.")); + match (kind, params) { + (Some(k), Value::Object(mut m)) => { + m.insert("__kind".into(), Value::String(k.into())); + Value::Object(m) + } + (Some(k), _) => json!({ "__kind": k }), + (None, p) => p, + } +} + +pub fn adjustment_kind(a: &Adjustment) -> &'static str { + match a { + Adjustment::BrightnessContrast { .. } => "brightnessContrast", + Adjustment::Levels { .. } => "levels", + Adjustment::Curves { .. } => "curves", + Adjustment::Exposure { .. } => "exposure", + Adjustment::Vibrance { .. } => "vibrance", + Adjustment::HueSaturation { .. } => "hueSaturation", + Adjustment::ColorBalance { .. } => "colorBalance", + Adjustment::BlackWhite { .. } => "blackWhite", + Adjustment::PhotoFilter { .. } => "photoFilter", + Adjustment::ChannelMixer { .. } => "channelMixer", + Adjustment::Posterize { .. } => "posterize", + Adjustment::Threshold { .. } => "threshold", + Adjustment::GradientMap { .. } => "gradientMap", + Adjustment::SelectiveColor { .. } => "selectiveColor", + Adjustment::ColorLookup { .. } => "colorLookup", + Adjustment::Unsupported { .. } => "unsupported", + _ => "invert", + } +} diff --git a/crates/engine/src/commands/enabled.rs b/crates/engine/src/commands/enabled.rs new file mode 100644 index 0000000000..c609b9e0ba --- /dev/null +++ b/crates/engine/src/commands/enabled.rs @@ -0,0 +1,100 @@ +use super::*; + +pub(crate) fn always(_: &Session) -> std::result::Result<(), String> { + Ok(()) +} + +pub(super) fn has_doc(s: &Session) -> std::result::Result<(), String> { + s.active().map(|_| ()).ok_or_else(|| "no document open".into()) +} + +pub(super) fn has_layer(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + d.active_layer.filter(|id| d.doc.layer(*id).is_some()).map(|_| ()).ok_or_else(|| "no active layer".into()) +} + +pub(super) fn has_pixel_layer(s: &Session) -> std::result::Result<(), String> { + let l = crate::active_layer_of(s)?; + if matches!(l.content, LayerContent::Raster(_)) { + Ok(()) + } else { + Err(format!("active layer is {} {} layer, not a pixel layer", l.content.article(), l.content.kind_name())) + } +} + +/// A pixel layer, or a targeted alpha channel / Quick Mask (adjustments and fills apply to it). +pub(super) fn has_pixel_or_channel(s: &Session) -> std::result::Result<(), String> { + if crate::channel_cmds::edits_channel(s) { + return Ok(()); + } + has_pixel_layer(s) +} + +/// A layer that can be painted: pixels, or any layer with a mask (paint with `"target":"mask"`). +pub(crate) fn has_paintable(s: &Session) -> std::result::Result<(), String> { + if crate::channel_cmds::edits_channel(s) { + return Ok(()); + } + let l = crate::active_layer_of(s)?; + if matches!(l.content, LayerContent::Raster(_)) || l.mask.is_some() { + Ok(()) + } else { + Err(format!("active layer is {} {} layer without a mask", l.content.article(), l.content.kind_name())) + } +} + +/// Surface a paint command writes to: the layer's pixels, its mask with `"target":"mask"`, or a +/// smart object's filter mask with `"target":"filterMask"`. +pub(crate) fn paint_surface<'a>(doc: &'a mut Document, id: LayerId, p: &Value) -> Result<&'a mut photocraft_raster::Surface> { + if is_mask_target(p) { + check_all_unlocked(doc, id)?; + } else { + check_pixels_unlocked(doc, id)?; + } + if crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::FilterMask { + return crate::smart_cmds::filter_mask_surface(doc, id); + } + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if is_mask_target(p) { + l.mask.as_mut().map(|m| &mut m.surface).ok_or_else(|| EngineError::Other("layer has no mask".into())) + } else { + l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into())) + } +} + +pub(crate) fn check_all_unlocked(doc: &Document, id: LayerId) -> Result<()> { + let locks = doc.effective_locks(id); + let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + if locks.all { + return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))); + } + Ok(()) +} + +/// Refuse a layer whose pixels are locked (directly or through a group), with Photoshop's message. +pub(crate) fn check_pixels_unlocked(doc: &Document, id: LayerId) -> Result<()> { + let locks = doc.effective_locks(id); + let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + if locks.pixels || locks.all { + return Err(EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))); + } + Ok(()) +} + +/// The params target a grayscale mask of the layer: its layer mask (`"mask"`) or, on a smart +/// object, its filter mask (`"filterMask"`). +pub(crate) fn is_mask_target(p: &Value) -> bool { + matches!(p.get("target").and_then(Value::as_str), Some("mask" | "filterMask")) +} + +pub(super) fn can_undo(s: &Session) -> std::result::Result<(), String> { + s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "nothing to undo".into()) +} + +pub(super) fn can_redo(s: &Session) -> std::result::Result<(), String> { + s.active().filter(|d| d.history.can_redo()).map(|_| ()).ok_or_else(|| "nothing to redo".into()) +} + +pub(super) fn has_selection(s: &Session) -> std::result::Result<(), String> { + s.active().filter(|d| d.doc.selection.is_some()).map(|_| ()).ok_or_else(|| "no selection".into()) +} diff --git a/crates/engine/src/commands/layer_params.rs b/crates/engine/src/commands/layer_params.rs new file mode 100644 index 0000000000..057be4a02c --- /dev/null +++ b/crates/engine/src/commands/layer_params.rs @@ -0,0 +1,113 @@ +use super::params::bad; +use super::*; + +/// The layer a command's `"layer"` param names: an id, or a name (the topmost layer of that +/// name, as Photoshop's "select layer by name" action step finds it, so a loaded action replays +/// in another document; a name that matches no layer exactly matches regardless of case, so +/// `"background"` finds the Background). `None` when the param is absent. +pub(crate) fn explicit_layer(s: &Session, p: &Value) -> Result> { + match p.get("layer") { + Some(Value::Number(n)) => { + n.as_u64().map(|id| Some(LayerId(id))).ok_or_else(|| EngineError::Other(format!("layer id {n} is not a non-negative integer"))) + } + Some(Value::String(name)) => { + let d = s.active().ok_or(EngineError::NoDocument)?; + let layers = d.doc.walk(); + let mut top_down = layers.iter().rev(); + top_down + .clone() + .find(|(_, _, l)| l.name == *name) + .or_else(|| top_down.find(|(_, _, l)| l.name.to_lowercase() == name.to_lowercase())) + .map(|(_, _, l)| Some(l.id)) + .ok_or_else(|| EngineError::Other(format!("no layer named \"{name}\"; {}", layer_listing(&d.doc)))) + } + Some(Value::Null) | None => Ok(None), + Some(other) => Err(EngineError::Other(format!("`layer` must be an id or a name, not {other}"))), + } +} + +/// The layers of `doc` as a caller can name them, for an error about a layer that isn't there: +/// `the document's layers are 2 "Background", 3 "Layer 1"` (top-down, at most 20). +pub(crate) fn layer_listing(doc: &Document) -> String { + const MAX: usize = 20; + let layers = doc.walk(); + if layers.is_empty() { + return "the document has no layers".into(); + } + // Names are unbounded input: each one is cut at NAME characters so the error stays short. + const NAME: usize = 64; + let name = |n: &str| match n.char_indices().nth(NAME) { + Some((cut, _)) => format!("{}…", &n[..cut]), + None => n.to_string(), + }; + let mut list: Vec = layers.iter().rev().take(MAX).map(|(_, _, l)| format!("{} {:?}", l.id.0, name(&l.name))).collect(); + if layers.len() > MAX { + list.push(format!("… {} more (see `document.inspect`)", layers.len() - MAX)); + } + format!("the document's layers are {} (a `layer` param takes an id or a name)", list.join(", ")) +} + +/// The layer a command targets: [`explicit_layer`], else the active layer. +pub(crate) fn layer_param(s: &Session, p: &Value) -> Result { + match explicit_layer(s, p)? { + Some(id) => Ok(id), + None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())), + } +} + +pub fn blend_from_str(s: &str) -> Option { + let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], ""); + let want = norm(s); + std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()).find(|m| norm(m.label()) == want || norm(&format!("{m:?}")) == want) +} + +/// The active selection as the mask of a layer being created, or None without a selection. +/// Photoshop masks a new adjustment or fill layer with the selection, so the adjustment acts on +/// the selected area only (#1250); the selection itself stays, as Reveal Selection leaves it. +pub(crate) fn selection_mask(doc: &Document) -> Result> { + doc.selection.as_ref().map(|sel| mask_at_depth(LayerMask { surface: sel.clone(), ..LayerMask::reveal_all() }, doc.depth)).transpose() +} + +/// New pixel masks use the document's depth, as PSD saves/imports do. Otherwise a later soft +/// brush stroke quantizes differently depending on whether the document reopened as PSD or +/// native. Converting a selection keeps its coverage and does not alter the selection itself. +pub(crate) fn mask_at_depth(mut mask: LayerMask, depth: SampleType) -> Result { + let format = mask.surface.format().with_sample(depth); + if mask.surface.format() != format { + mask.surface = mask.surface.try_convert(format)?; + } + Ok(mask) +} + +/// Options from the Layers Panel flyout live in preferences so headless/keyboard commands +/// behave exactly like pointer-triggered commands. Old preferences preserve Photoshop defaults. +pub(crate) fn layer_panel_option(s: &Session, key: &str, fallback: bool) -> bool { + s.prefs().dialogs.get("ui.layersPanelOptions").and_then(|v| v.get(key)).and_then(Value::as_bool).unwrap_or(fallback) +} + +/// Mask a fill or adjustment layer being created, as Photoshop does: the path selected in the +/// Paths panel (`"path"`: `"work"`, a saved path's name or a path object) becomes its vector +/// mask, which makes a Solid Color fill a shape (#1419); without one, the selection becomes its +/// layer mask ([`selection_mask`]); without either, a white mask reveals the whole layer (#1768). +/// A path that isn't there is an error. +pub(crate) fn mask_new_layer(doc: &Document, l: &mut Layer, p: &Value, cmd: &str, default_mask: bool) -> Result<()> { + let path = match p.get("path") { + None | Some(Value::Null) => None, + Some(Value::String(n)) if crate::vector_cmds::is_work(Some(n)) => Some(doc.work_path.clone().ok_or_else(|| bad(cmd, "no work path"))?), + Some(Value::String(n)) => { + Some(doc.paths.iter().find(|sp| sp.name == *n).map(|sp| sp.path.clone()).ok_or_else(|| bad(cmd, format!("no path named \"{n}\"")))?) + } + Some(v) => Some(crate::vector_cmds::parse_path(v).map_err(|e| bad(cmd, e))?), + }; + match path { + Some(path) => l.vector_mask = Some(photocraft_doc::VectorMask::new(path)), + None => { + l.mask = selection_mask(doc)?.or_else(|| default_mask.then(LayerMask::reveal_all)).map(|mask| mask_at_depth(mask, doc.depth)).transpose()?; + } + } + Ok(()) +} + +/// The `"path"` param of the new fill and adjustment layer commands ([`mask_new_layer`]). +pub(crate) const NEW_LAYER_PATH: &str = + r##""path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask, or white with no selection)"##; diff --git a/crates/engine/src/commands/ops.rs b/crates/engine/src/commands/ops.rs new file mode 100644 index 0000000000..776f47e020 --- /dev/null +++ b/crates/engine/src/commands/ops.rs @@ -0,0 +1,160 @@ +use super::enabled::check_all_unlocked; +use super::layer_params::{layer_param, mask_at_depth}; +use super::*; + +pub(super) fn arrange(s: &mut Session, p: &Value, delta: i32) -> Result { + let id = layer_param(s, p)?; + s.edit("Arrange", |doc, _| { + // The Background stays at the bottom: it doesn't move and nothing goes below it. + let bg = crate::background_cmds::background_id(doc); + if bg == Some(id) { + return Err(EngineError::Other("the Background layer can't be moved".into())); + } + let steps = match delta { + i32::MAX => 10_000, + i32::MIN => -10_000, + d => d, + }; + let dir = steps.signum(); + let before = crate::clip_group::Before::read(doc, &[id]); + let mut moved = false; + for _ in 0..steps.abs() { + if !doc.shift(id, dir) { + break; + } + if crate::background_cmds::keep_background_at_bottom(bg, doc).is_err() { + doc.shift(id, -dir); + break; + } + moved = true; + } + if !moved { + return Err(EngineError::Other("layer can't move further".into())); + } + crate::clip_group::settle(doc, &[id], &before, false); + Ok(()) + })?; + Ok(Value::Null) +} + +/// Add (`Some`) or remove (`None`) a layer mask. Adding acts on every selected layer that can take +/// one ([`crate::layer_multi_cmds::mask_targets`]), in one history step. +pub(super) fn set_mask(s: &mut Session, p: &Value, label: &str, mask: Option) -> Result { + set_mask_with(s, p, label, mask, false) +} + +/// [`set_mask`] that also drops the selection the mask was made from, in the same history step. +pub(super) fn set_mask_and_deselect(s: &mut Session, p: &Value, label: &str, mask: LayerMask) -> Result { + set_mask_with(s, p, label, Some(mask), true) +} + +fn set_mask_with(s: &mut Session, p: &Value, label: &str, mask: Option, deselect: bool) -> Result { + let ids = if mask.is_some() { crate::layer_multi_cmds::mask_targets(s, p)? } else { vec![layer_param(s, p)?] }; + s.edit(label, |doc, _| { + let mask = mask.clone().map(|mask| mask_at_depth(mask, doc.depth)).transpose()?; + for id in &ids { + check_all_unlocked(doc, *id)?; + if mask.is_some() { + crate::extra_cmds::background_to_layer_for_mask(doc, *id); + } + doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.mask = mask.clone(); + } + if deselect { + doc.selection = None; + } + Ok(()) + })?; + Ok(Value::Null) +} + +/// Move a layer's pixels, linked mask and type by whole pixels (vectors move via +/// `vector_cmds::translate_vectors`). +pub(crate) fn translate_layer(doc: &Document, l: &mut Layer, dx: i32, dy: i32) { + use crate::layer_multi_cmds::shift_surface as translate_surface; + // Linked patterns in the layer's effects move with it. + if let Some(r) = &mut l.effects.reference { + *r = (r.0 + f64::from(dx), r.1 + f64::from(dy)); + } + if let Some(m) = &mut l.mask + && m.linked + { + m.surface = translate_surface(&m.surface, dx, dy); + } + match &mut l.content { + LayerContent::Raster(s) => *s = translate_surface(s, dx, dy), + LayerContent::Text(t) => { + t.transform = photocraft_geom::Affine::translate(dx as f64, dy as f64).mul(&t.transform); + // A whole-pixel move shifts the rendered text and its PSD position as they are. + // Re-rendering would replace Photoshop's rendering of imported type, and drop the + // text when its font is missing (artboard export, moving type with the Move tool). + let raw = t.psd_raw.as_deref().map(|r| photocraft_text::psd::translate_tysh(r, f64::from(dx), f64::from(dy))); + match (&mut t.cache, raw) { + (Some(c), Some(Some(r))) => { + *c = translate_surface(c, dx, dy); + t.psd_raw = Some(std::sync::Arc::new(r)); + } + (Some(c), None) => *c = translate_surface(c, dx, dy), + _ => crate::type_cmds::refresh(doc, t), + } + } + LayerContent::Group(g) => { + // Moving an artboard moves the board with its contents. + if let Some(a) = &mut g.artboard { + a.rect = a.rect.translate(dx, dy); + } + for c in &mut g.children { + translate_layer(doc, c, dx, dy); + } + } + LayerContent::Smart(sm) => crate::smart_cmds::shift_smart(sm, dx, dy), + _ => {} + } +} + +/// A copy of layer `id` as Layer › Duplicate Layer makes it, not yet in the document: a fresh id, +/// "… copy" appended to the name, and a copy of the Background layer is an ordinary, unlocked +/// layer (Photoshop). +pub(crate) fn layer_copy(doc: &Document, id: LayerId, add_copy: bool) -> Result { + let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + // A copy of the Background layer is an ordinary, unlocked layer (Photoshop). + let from_background = doc.is_background(id); + let mut dup = src.duplicate(); + if add_copy { + dup.name = doc.copy_name(&dup.name); + } + if from_background { + dup.locks = Default::default(); + } + Ok(dup) +} + +/// Layer › Merge Group (⌘E with a group selected, #3832): the group's visible contents, as they +/// show, become one pixel layer in its place, named after it. Like Photoshop, the layer keeps the +/// group's opacity, blend mode (Pass Through becomes Normal), clipping and locks; the group's mask +/// and style are applied to the pixels. +pub(super) fn merge_group(s: &mut Session, id: LayerId) -> Result { + s.edit("Merge Group", |doc, active| { + let group = doc.layer(id).ok_or(EngineError::NoLayer(id))?.clone(); + if !group.visible { + return Err(EngineError::Other("the group is hidden".into())); + } + let fmt = doc.pixel_format(); + let fmt = photocraft_color::PixelFormat::new(fmt.mode, fmt.sample, true); + let mut solo = group.clone(); + solo.opacity = 1.0; + solo.blend = photocraft_doc::BlendMode::Normal; + solo.clipped = false; + let mut tmp = doc.clone(); + tmp.layers = vec![solo]; + let mut merged = Layer::new(group.name.clone(), LayerContent::Raster(pixels::composite_layers_uncropped(&tmp, fmt))); + merged.id = group.id; + merged.opacity = group.opacity; + merged.blend = if group.blend == photocraft_doc::BlendMode::PassThrough { photocraft_doc::BlendMode::Normal } else { group.blend }; + merged.clipped = group.clipped; + merged.locks = group.locks; + *doc.layer_mut(id).ok_or(EngineError::NoLayer(id))? = merged; + *active = Some(id); + Ok(()) + })?; + Ok(json!({ "layer": id.0 })) +} diff --git a/crates/engine/src/commands/params.rs b/crates/engine/src/commands/params.rs new file mode 100644 index 0000000000..0ed899c073 --- /dev/null +++ b/crates/engine/src/commands/params.rs @@ -0,0 +1,140 @@ +use super::layer_params::layer_param; +use super::*; + +// ---------- param helpers ---------- + +pub(super) fn bad(cmd: &str, msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } +} + +/// Integer parameter that also accepts JSON floats (UIs send `12.0`); rounds. +pub(crate) fn int(p: &Value, key: &str) -> Option { + p.get(key).and_then(|v| v.as_i64().or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round() as i64))) +} + +/// [`int`] narrowed to `i32` for geometry: `None` when absent, and a bad-params error when the +/// value would wrap through `as i32` — out-of-range integers truncate by multiples of 2^32, +/// which silently relocates geometry (`dx = 2^32 + 50` moves 50 px, `3e9` goes negative) +/// instead of erroring. +pub(crate) fn int_i32(cmd: &str, p: &Value, key: &str) -> Result> { + match int(p, key) { + None => Ok(None), + Some(v) => i32::try_from(v).map(Some).map_err(|_| bad(cmd, format!("`{key}` = {v} is outside the 32-bit coordinate range"))), + } +} + +/// An id (layer comp, slice, style…) from a JSON value: a bad-params error unless it is a whole +/// number in `u32` range. `as u32` would wrap `2^32 + 1` to `1` and target a real item. +pub(crate) fn u32_id(cmd: &str, key: &str, v: &Value) -> Result { + v.as_u64().and_then(|n| u32::try_from(n).ok()).ok_or_else(|| bad(cmd, format!("`{key}` = {v} is not a valid id (0..={})", u32::MAX))) +} + +/// [`u32_id`] of `p[key]`: `None` when absent. +pub(crate) fn u32_id_param(cmd: &str, p: &Value, key: &str) -> Result> { + p.get(key).map(|v| u32_id(cmd, key, v)).transpose() +} + +/// JSON numbers may be finite f64 values but overflow when stored in a document's f32 field. +pub(crate) fn finite_f32(cmd: &str, key: &str, value: f64) -> Result { + let narrowed = value as f32; + if narrowed.is_finite() { Ok(narrowed) } else { Err(bad(cmd, format!("`{key}` must fit a finite 32-bit number"))) } +} + +/// Effect/type parameters contain nested colour arrays and snapshots as well as scalars. +/// Validate before parsing or editing, including numbers hidden in an effect snapshot. +pub(crate) fn check_f32_values(cmd: &str, value: &Value) -> Result<()> { + // Bound the call stack, without allocating a work list proportional to an input array. + fn check(cmd: &str, value: &Value, depth: usize) -> Result<()> { + if depth > 64 { + return Err(bad(cmd, "parameters nested deeper than 64 levels")); + } + match value { + Value::Number(n) => { + finite_f32(cmd, "number", n.as_f64().ok_or_else(|| bad(cmd, "invalid number"))?)?; + } + Value::Array(a) => { + for v in a { + check(cmd, v, depth + 1)?; + } + } + Value::Object(o) => { + for v in o.values() { + check(cmd, v, depth + 1)?; + } + } + _ => {} + } + Ok(()) + } + check(cmd, value, 0) +} + +pub(crate) fn color_param(cmd: &str, p: &Value, key: &str, default: [f32; 4]) -> Result<[f32; 4]> { + Ok(match p.get(key) { + Some(Value::Array(a)) if a.len() >= 3 => { + let mut out = [0.0, 0.0, 0.0, 1.0]; + for (slot, value) in out.iter_mut().zip(a) { + *slot = finite_f32(cmd, key, value.as_f64().unwrap_or(0.0))?; + } + out + } + Some(Value::String(s)) => parse_hex(s).unwrap_or(default), + _ => default, + }) +} + +pub(crate) fn parse_hex(s: &str) -> Option<[f32; 4]> { + let s = s.trim_start_matches('#'); + // `from_str_radix` accepts a leading '+', so "+f" would read as 0x0f. + if !s.bytes().all(|c| c.is_ascii_hexdigit()) { + return None; + } + let b = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| v as f32 / 255.0); + match s.len() { + 6 => Some([b(0)?, b(2)?, b(4)?, 1.0]), + 8 => Some([b(0)?, b(2)?, b(4)?, b(6)?]), + _ => None, + } +} + +/// Layer › Create / Release Clipping Mask. With a `layer` param, just that layer. Otherwise, as in +/// Photoshop, the selection (#1248): Create clips every selected layer except the lowest, which +/// becomes the base; Release releases every selected layer. Releasing a clipped layer also +/// releases the clipped layers above it in its group, as Adobe documents ("removes the selected +/// layer and any layers above it from the clipping mask"), so none is left clipped to a layer +/// that is no longer clipped. One history step either way. +pub(super) fn set_clipped(s: &mut Session, p: &Value, clip: bool) -> Result { + let label = if clip { "Create Clipping Mask" } else { "Release Clipping Mask" }; + let ids: Vec = if p.get("layer").is_some() { + vec![layer_param(s, p)?] + } else { + let selected = s.active().ok_or(EngineError::NoDocument)?.selected_layers(); + match (clip, selected.as_slice()) { + (_, []) => vec![layer_param(s, p)?], + (_, [one]) => vec![*one], + (true, [_base, rest @ ..]) => rest.to_vec(), + (false, all) => all.to_vec(), + } + }; + let ids = if clip { + ids + } else { + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let mut all = ids.clone(); + for id in ids.iter().filter(|id| doc.layer(**id).is_some_and(|l| l.clipped)) { + for above in crate::clip_group::clipped_above(doc, *id) { + if !all.contains(&above) { + all.push(above); + } + } + } + all + }; + s.edit(label, |doc, _| { + for id in &ids { + doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.clipped = clip; + } + Ok(()) + })?; + Ok(json!({"layers": ids.iter().map(|id| id.0).collect::>()})) +} From 8a2750cf346f0512bf6b29105cf19404d68e2974 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:57:27 +0000 Subject: [PATCH 204/259] refactor(engine): split layer_multi_cmds.rs into layer_multi_cmds/ --- crates/engine/src/layer_multi_cmds.rs | 1683 +---------------- crates/engine/src/layer_multi_cmds/align.rs | 162 ++ crates/engine/src/layer_multi_cmds/damage.rs | 517 +++++ crates/engine/src/layer_multi_cmds/moves.rs | 428 +++++ .../engine/src/layer_multi_cmds/selection.rs | 285 +++ .../engine/src/layer_multi_cmds/structure.rs | 288 +++ 6 files changed, 1699 insertions(+), 1664 deletions(-) create mode 100644 crates/engine/src/layer_multi_cmds/align.rs create mode 100644 crates/engine/src/layer_multi_cmds/damage.rs create mode 100644 crates/engine/src/layer_multi_cmds/moves.rs create mode 100644 crates/engine/src/layer_multi_cmds/selection.rs create mode 100644 crates/engine/src/layer_multi_cmds/structure.rs diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs index 726920571f..3966432975 100644 --- a/crates/engine/src/layer_multi_cmds.rs +++ b/crates/engine/src/layer_multi_cmds.rs @@ -13,348 +13,26 @@ use serde_json::{Value, json}; use crate::commands::{CommandSpec, int_i32}; use crate::{DocState, EngineError, Result, Session}; -// ---------- selection state ---------- +mod align; +mod damage; +mod moves; +mod selection; +mod structure; -fn doc_state(s: &Session) -> std::result::Result<&DocState, String> { - s.active().ok_or_else(|| "no document open".into()) -} - -/// Selected layers of the active document, bottom-to-top. -pub fn selected(s: &Session) -> Vec { - s.active().map(DocState::selected_layers).unwrap_or_default() -} - -/// The layers a layer command acts on: the `layer` param when given, else every selected layer -/// (bottom-to-top), else the active layer. A single layer behaves exactly as before. -pub(crate) fn targets(s: &Session, p: &serde_json::Value) -> Result> { - if p.get("layer").is_some() { - return Ok(vec![crate::commands::layer_param(s, p)?]); - } - match selected(s) { - sel if sel.is_empty() => Ok(vec![crate::commands::layer_param(s, p)?]), - sel => Ok(sel), - } -} - -/// [`targets`] for a command that adds a layer mask: with several layers selected, those that can -/// take one (no layer mask yet, not the Background); one layer is taken as given. -pub(crate) fn mask_targets(s: &Session, p: &serde_json::Value) -> Result> { - let ids = targets(s, p)?; - if ids.len() < 2 { - return Ok(ids); - } - let d = s.active().ok_or(EngineError::NoDocument)?; - let ids: Vec = ids.into_iter().filter(|id| d.doc.layer(*id).is_some_and(|l| l.mask.is_none() && !d.doc.is_background(l.id))).collect(); - if ids.is_empty() { - return Err(EngineError::Other("none of the selected layers can take a layer mask".into())); - } - Ok(ids) -} - -/// Ids in `ids` that have no ancestor also in `ids` (a selected group already carries its -/// selected children), bottom-to-top. -pub(crate) fn top_level(doc: &Document, ids: &[LayerId]) -> Vec { - let walk = doc.walk(); - let paths: Vec<_> = walk.iter().filter(|(_, _, l)| ids.contains(&l.id)).map(|(p, _, l)| (p.clone(), l.id)).collect(); - paths.iter().filter(|(p, _)| !paths.iter().any(|(q, _)| q.len() < p.len() && p.starts_with(q))).map(|(_, id)| *id).collect() -} - -/// Replace the layer selection without a history step (like [`Session::select_layer`]). -pub fn set_selection(s: &mut Session, ids: Vec, active: Option, anchor: Option) -> Result<()> { - let st = s.active_mut().ok_or(EngineError::NoDocument)?; - if let Some(bad) = ids.iter().chain(active.iter()).find(|id| st.doc.layer(**id).is_none()) { - return Err(EngineError::NoLayer(*bad)); - } - let active = active.or_else(|| ids.last().copied()); - st.selected_layers = ids; - if let Some(a) = active - && !st.selected_layers.contains(&a) - { - st.selected_layers.push(a); - } - st.active_layer = active; - st.layer_anchor = anchor.or(active); - crate::fix_selection(st); - // Selecting layers is not an edit: keep a clean document clean. - let clean = st.saved_revision == st.revision; - st.revision += 1; - if clean { - st.saved_revision = st.revision; - } - st.last_damage = Some(Rect::EMPTY); - Ok(()) -} - -/// After a structural edit, make `ids` the selection (dropping any that no longer exist), which -/// is also what the edit's history state targets. -pub(crate) fn reselect(s: &mut Session, ids: Vec, active: Option) { - if let Some(st) = s.active_mut() { - st.selected_layers = ids; - if let Some(a) = active { - st.active_layer = Some(a); - st.layer_anchor = Some(a); - } - crate::fix_selection(st); - let layers = st.layer_target(); - st.history.set_current_layers(layers); - } -} - -/// Capture a selection target while its name is still known. Later renames/deletions must not -/// change an earlier recorded selection. Direct, non-recording calls retain their numeric IDs. -pub(crate) fn recorded_selection(s: &Session, mut p: Value) -> Value { - let Some(id) = p.get("layer").and_then(Value::as_u64).map(LayerId) else { return p }; - let Some(st) = s.active() else { return p }; - let Some(layer) = st.doc.layer(id) else { return p }; - let matches: Vec<_> = st.doc.walk().into_iter().filter(|(_, _, l)| l.name == layer.name).map(|(_, _, l)| l.id).collect(); - let Some(occurrence) = matches.iter().position(|candidate| *candidate == id) else { return p }; - if let Some(fields) = p.as_object_mut() { - fields.remove("layer"); - fields.insert("name".into(), json!(layer.name)); - if matches.len() > 1 { - fields.insert("occurrence".into(), json!(occurrence)); - } - } - p -} - -/// The layers named `name`, in document order, other than the ones being moved and (groups) their -/// contents. Moving layers never changes the others' order, so an occurrence counted among these -/// means the same layer before the move (when an action replays it) and after it (when the step -/// is recorded). -fn same_named_targets(doc: &photocraft_doc::Document, name: &str, moved: &[LayerId]) -> Vec { - fn subtree(l: &Layer, out: &mut Vec, depth: usize) { - out.push(l.id); - if depth < 256 - && let Some(children) = l.children() - { - children.iter().for_each(|c| subtree(c, out, depth + 1)); - } - } - let mut skip = Vec::new(); - for l in moved.iter().filter_map(|id| doc.layer(*id)) { - subtree(l, &mut skip, 0); - } - doc.walk().into_iter().filter(|(_, _, l)| l.name == name && !skip.contains(&l.id)).map(|(_, _, l)| l.id).collect() -} - -/// A Layers-panel drag of the selected layer records its drop target by name (and which of -/// several same-named layers it is), as [`recorded_selection`] does: the id means nothing in the -/// document the action plays in later, so playback failed with "no such layer" (#7845). Drags of -/// several layers, or of a layer that isn't the selected one, keep their ids. -fn recorded_move(s: &Session, mut p: Value, pre_selected: Option<&[LayerId]>) -> Value { - if p.get("layers").is_some() { - return p; - } - let Some(st) = s.active() else { return p }; - let moved = match p.get("layer") { - None => st.active_layer, - Some(v) => match v.as_u64().map(LayerId) { - Some(id) if pre_selected.map_or_else(|| st.selected_layers().as_slice() == [id], |sel| sel == [id]) => Some(id), - _ => return p, - }, - }; - if let Some(fields) = p.as_object_mut() { - fields.remove("layer"); - } - let Some(id) = p.get("target").and_then(Value::as_u64).map(LayerId) else { return p }; - let Some(layer) = st.doc.layer(id) else { return p }; - // A copy leaves its source where it is (it may even land beside it), so the source stays a - // candidate; the new copy (the active layer once the step has run, which is when it is - // recorded) is left out instead, as it doesn't exist yet when the step replays. - let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); - let skip = if copy { st.active_layer.filter(|a| Some(*a) != moved) } else { moved }; - let matches = same_named_targets(&st.doc, &layer.name, skip.as_slice()); - let Some(occurrence) = matches.iter().position(|candidate| *candidate == id) else { return p }; - if let Some(fields) = p.as_object_mut() { - fields.insert("target".into(), json!(layer.name)); - if matches.len() > 1 { - fields.insert("targetOccurrence".into(), json!(occurrence)); - } - } - p -} - -/// `layer.moveTo`'s drop target: an id, or a name with `targetOccurrence` choosing among layers -/// that share it (in document order, the `moved` layers aside; required when several do). -fn move_target(s: &Session, p: &Value, moved: &[LayerId]) -> Result { - const CMD: &str = "layer.moveTo"; - match p.get("target") { - Some(Value::String(name)) => { - let occurrence = p - .get("targetOccurrence") - .map(|v| v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(CMD, "`targetOccurrence` must be a non-negative integer"))) - .transpose()?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let matches = same_named_targets(&st.doc, name, moved); - if matches.len() > 1 && occurrence.is_none() { - return Err(bad(CMD, format!("multiple layers named `{name}`; specify `targetOccurrence`"))); - } - let index = occurrence.unwrap_or(0); - matches.get(index).copied().ok_or_else(|| bad(CMD, format!("no layer named `{name}` at occurrence {index}"))) - } - Some(v) => v.as_u64().map(LayerId).ok_or_else(|| bad(CMD, "`target` must be a layer id or name")), - None => Err(bad(CMD, "missing `target`")), - } -} - -/// Normalise parameters when recording an action step. -/// -/// For `layer.select`, captures the layer by name. For other commands, if a numeric `layer` -/// parameter references the document's sole selected layer, normalises it to the target form -/// (omitting `layer`) so that the recorded step applies to whatever layer is targeted when -/// replayed or exported to `.atn` (#7248). -pub(crate) fn recorded_step(s: &Session, id: &str, p: Value, pre_selected: Option<&[LayerId]>) -> Value { - if id == "layer.select" { - return recorded_selection(s, p); - } - if id == "layer.moveTo" { - return recorded_move(s, p, pre_selected); - } - let Some(layer_id) = p.get("layer").and_then(Value::as_u64).map(LayerId) else { return p }; - let is_sole_selected = match pre_selected { - Some(sel) => sel == [layer_id], - None => s.active().is_some_and(|st| st.selected_layers().as_slice() == [layer_id]), - }; - if is_sole_selected { - let mut p = p; - if let Some(fields) = p.as_object_mut() { - fields.remove("layer"); - } - return p; - } - p -} - -fn selection_target(s: &Session, p: &Value) -> Result { - let Some(name) = p.get("name") else { - if p.get("occurrence").is_some() { - return Err(bad("layer.select", "`occurrence` requires `name`")); - } - return crate::commands::explicit_layer(s, p)?.ok_or_else(|| bad("layer.select", "needs `layer` or `name`")); - }; - if p.get("layer").is_some() { - return Err(bad("layer.select", "use either `layer` or `name`, not both")); - } - let name = name.as_str().ok_or_else(|| bad("layer.select", "`name` must be a string"))?; - let occurrence = p - .get("occurrence") - .map(|v| v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad("layer.select", "`occurrence` must be a non-negative integer"))) - .transpose()?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let matches: Vec<_> = st.doc.walk().into_iter().filter(|(_, _, l)| l.name == name).map(|(_, _, l)| l.id).collect(); - if matches.len() > 1 && occurrence.is_none() { - return Err(bad("layer.select", format!("multiple layers named `{name}`; specify `occurrence`"))); - } - let index = occurrence.unwrap_or(0); - matches.get(index).copied().ok_or_else(|| bad("layer.select", format!("no layer named `{name}` at occurrence {index}"))) -} - -/// Layer rows follow the Layers panel's visual order, not Document::walk's storage order. -/// Closed groups hide their children unless both endpoints were selected programmatically. -fn range_order(layers: &[Layer], include_collapsed: bool, out: &mut Vec) { - for layer in layers.iter().rev() { - out.push(layer.id); - if let LayerContent::Group(group) = &layer.content - && (group.expanded || include_collapsed) - { - range_order(&group.children, include_collapsed, out); - } - } -} - -/// `layer.select`: `{"layer": id, "mode": "replace|toggle|range|add|remove"}`. -pub fn select(s: &mut Session, p: &Value) -> Result { - let id = selection_target(s, p)?; - let mode = p.get("mode").and_then(Value::as_str).unwrap_or("replace"); - let st = s.active().ok_or(EngineError::NoDocument)?; - if st.doc.layer(id).is_none() { - return Err(EngineError::NoLayer(id)); - } - let mut sel = st.selected_layers(); - match mode { - "replace" => s.select_layer(id)?, - "add" => { - if !sel.contains(&id) { - sel.push(id); - } - set_selection(s, sel, Some(id), Some(id))?; - } - "toggle" => { - if sel.contains(&id) { - if sel.len() == 1 { - // Photoshop keeps at least the clicked layer targeted. - return Ok(json!({"selected": [id.0]})); - } - sel.retain(|x| *x != id); - let active = if st.active_layer == Some(id) { sel.last().copied() } else { st.active_layer }; - set_selection(s, sel, active, active)?; - } else { - sel.push(id); - set_selection(s, sel, Some(id), Some(id))?; - } - } - // Toggle's removing half: a layer that isn't selected stays unselected (Photoshop's - // `removeFromSelection`, recorded by actions). - "remove" => { - if sel.contains(&id) && sel.len() > 1 { - sel.retain(|x| *x != id); - let active = if st.active_layer == Some(id) { sel.last().copied() } else { st.active_layer }; - set_selection(s, sel, active, active)?; - } - } - "range" => { - let anchor = st.layer_anchor.filter(|a| st.doc.layer(*a).is_some()).or(st.active_layer).unwrap_or(id); - let mut order = Vec::new(); - range_order(&st.doc.layers, false, &mut order); - // Engine clients may target a child of a collapsed group that the panel cannot - // click. Retain that capability by using expanded visual order for such calls. - if !order.contains(&anchor) || !order.contains(&id) { - order.clear(); - range_order(&st.doc.layers, true, &mut order); - } - let (a, b) = (order.iter().position(|x| *x == anchor).unwrap_or(0), order.iter().position(|x| *x == id).unwrap_or(0)); - let range = order[a.min(b)..=a.max(b)].to_vec(); - set_selection(s, range, Some(id), Some(anchor))?; - } - other => return Err(bad("layer.select", format!("unknown mode `{other}`"))), - } - Ok(json!({"selected": selected(s).iter().map(|l| l.0).collect::>()})) -} - -fn select_all_layers(s: &mut Session) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let ids: Vec = d.doc.walk().into_iter().filter(|(_, _, l)| !d.doc.is_background(l.id)).map(|(_, _, l)| l.id).collect(); - if ids.is_empty() { - return Err(EngineError::Other("there are no layers to select".into())); - } - let active = d.active_layer.filter(|a| ids.contains(a)).or(ids.last().copied()); - let n = ids.len(); - set_selection(s, ids, active, None)?; - Ok(json!({"selected": n})) -} - -fn find_layers(s: &mut Session, p: &Value) -> Result { - let needle = p.get("name").and_then(Value::as_str).ok_or_else(|| bad("select.findLayers", "missing `name`"))?.to_lowercase(); - let d = s.active().ok_or(EngineError::NoDocument)?; - let ids: Vec = d.doc.walk().into_iter().filter(|(_, _, l)| l.name.to_lowercase().contains(&needle)).map(|(_, _, l)| l.id).collect(); - if ids.is_empty() { - return Err(EngineError::Other(format!("no layer name contains \"{needle}\""))); - } - let out = ids.iter().map(|l| l.0).collect::>(); - set_selection(s, ids, None, None)?; - Ok(json!({"selected": out})) -} - -fn select_linked(s: &mut Session) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let groups = link_groups(&d.doc, &d.selected_layers()); - let ids: Vec = d.doc.walk().into_iter().filter(|(_, _, l)| l.link_group.is_some_and(|g| groups.contains(&g))).map(|(_, _, l)| l.id).collect(); - let active = d.active_layer.filter(|a| ids.contains(a)).or(ids.last().copied()); - let n = ids.len(); - set_selection(s, ids, active, active)?; - Ok(json!({"selected": n})) -} +use align::{align, distribute}; +pub use damage::{layer_bounds, layers_damage, same_pixels, selection_only_change, step_damage}; +pub(crate) use damage::{note_damage, note_inert_insert, note_insert}; +use moves::link_groups; +pub(crate) use moves::shift_surface; +#[cfg(test)] +pub(crate) use moves::with_links; +pub use moves::{move_targets, move_to, moved, moved_target, moves_mask_alone, preview_move, translate}; +use selection::{doc_state, find_layers, select_all_layers, select_linked}; +pub(crate) use selection::{mask_targets, recorded_step, reselect, targets, top_level}; +pub use selection::{select, selected, set_selection}; +pub(crate) use structure::{check_group_depth, deletion_neighbours}; +pub use structure::{delete_selected, duplicate_selected, group_layers, set_visible_selected}; +use structure::{link_layers, lock_layers, merge_layers, rename_layer, reverse}; // ---------- enabled predicates ---------- @@ -397,1329 +75,6 @@ fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } } -// ---------- moving layers ---------- - -fn link_groups(doc: &Document, ids: &[LayerId]) -> Vec { - let mut g: Vec = ids.iter().filter_map(|id| doc.layer(*id)?.link_group).collect(); - g.sort_unstable(); - g.dedup(); - g -} - -/// `ids` plus every layer linked to one of them. -pub(crate) fn with_links(doc: &Document, ids: &[LayerId]) -> Vec { - let groups = link_groups(doc, ids); - let mut out = ids.to_vec(); - if !groups.is_empty() { - for (_, _, l) in doc.walk() { - if l.link_group.is_some_and(|g| groups.contains(&g)) && !out.contains(&l.id) { - out.push(l.id); - } - } - } - out -} - -/// Move layers by whole pixels the way the Move tool does: pixels, linked masks, type and -/// vector content (shapes, linked vector masks) all move together. `before` is `doc` as it was -/// before any of the moves (the edit's starting document), read when type and shapes re-render. -pub(crate) fn move_layers(doc: &mut Document, before: &Document, moves: &[(LayerId, i32, i32)]) -> Result<()> { - for &(id, dx, dy) in moves { - if dx == 0 && dy == 0 { - continue; - } - let locks = doc.effective_locks(id); - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if locks.position || locks.all { - return Err(EngineError::Other(format!("layer \"{}\" is position-locked", l.name))); - } - crate::commands::translate_layer(before, l, dx, dy); - crate::vector_cmds::translate_vectors(before, l, dx as f64, dy as f64); - } - Ok(()) -} - -/// Does a move aimed at the layer mask (`"target":"mask"`) move `l`'s mask alone? Only an -/// unlinked mask does (the chain off); a linked one moves with its layer, as in Photoshop. -pub fn moves_mask_alone(l: &Layer) -> bool { - l.mask.as_ref().is_some_and(|m| !m.linked) -} - -/// `layer.translate`: the explicit layer, or every selected layer, plus their linked layers. -/// With `"target":"mask"` a layer whose mask is unlinked moves that mask alone. -pub fn translate(s: &mut Session, p: &Value) -> Result { - let (dx, dy) = match p.get("units").and_then(Value::as_str) { - None | Some("px") => (int_i32("layer.translate", p, "dx")?.unwrap_or(0), int_i32("layer.translate", p, "dy")?.unwrap_or(0)), - // Points (1/72 in), as a Photoshop action records a nudge: whole pixels at this - // document's resolution. - Some("pt") => { - let dpi = s.active().map_or(72.0, |d| f64::from(d.doc.resolution_dpi)); - let to_px = |key: &str| -> Result { - let pt = match p.get(key) { - None => 0.0, - Some(v) => v.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad("layer.translate", format!("`{key}` must be a number")))?, - }; - let px = (pt * dpi / 72.0).round(); - if px.abs() > f64::from(i32::MAX) { - return Err(bad("layer.translate", format!("`{key}` = {pt} pt is outside the 32-bit coordinate range"))); - } - Ok(px as i32) - }; - (to_px("dx")?, to_px("dy")?) - } - Some(other) => return Err(bad("layer.translate", format!("unknown units `{other}` (px|pt)"))), - }; - let carry = match p.get("selection") { - None | Some(Value::Null) => false, - Some(v) => v.as_bool().ok_or_else(|| bad("layer.translate", "`selection` must be a boolean"))?, - }; - if dx == 0 && dy == 0 { - return Ok(Value::Null); - } - let roots = match crate::commands::explicit_layer(s, p)? { - Some(id) => vec![id], - None => selected(s), - }; - if roots.is_empty() { - return Err(EngineError::Other("no active layer".into())); - } - let mask_target = p.get("target").and_then(Value::as_str) == Some("mask"); - let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); - let ids = 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); - if ids.is_empty() && alone.is_empty() { - return Err(EngineError::NoLayer(roots[0])); - } - let moves: Vec<_> = ids.iter().map(|&id| (id, dx, dy)).collect(); - move_layers(doc, &before, &moves)?; - for id in alone { - let locks = doc.effective_locks(id); - let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if locks.position || locks.all { - return Err(EngineError::Other(format!("layer \"{}\" is position-locked", l.name))); - } - if let Some(m) = &mut l.mask { - m.surface = shift_surface(&m.surface, dx, dy); - } - ids.push(id); - } - // 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); - } - // The Move tool carries the selection along when it moves several layers whole, as - // Photoshop does (#7538): one step, so Undo takes both back. - if carry { - doc.selection = doc.selection.as_ref().map(|sel| shift_surface(sel, dx, dy)); - } - Ok(ids) - })?; - note_damage(s, &before, &ids); - Ok(Value::Null) -} - -/// The layers a move of `roots` takes along: their linked layers, without layers whose group -/// is also moving (the group carries them). -pub fn move_targets(doc: &Document, roots: &[LayerId]) -> Vec { - top_level(doc, &with_links(doc, roots)) -} - -/// `doc` with the layers `ids` ([`move_targets`]) moved by whole pixels, as `layer.translate` -/// leaves them: the Move tool's live preview while it drags. Type, shape and smart-object pixels -/// shift as they are instead of re-rendering (the commit re-renders them), so a drag frame costs -/// copying the moving pixels only. -pub fn moved(doc: &Document, ids: &[LayerId], dx: i32, dy: i32) -> Result { - moved_target(doc, ids, dx, dy, false) -} - -/// [`moved`] for a drag aimed at the layer mask (`mask_target`): unlinked masks move alone. -pub fn moved_target(doc: &Document, ids: &[LayerId], dx: i32, dy: i32, mask_target: bool) -> Result { - let mut out = doc.clone(); - for &id in ids { - let locks = doc.effective_locks(id); - let l = out.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - if locks.position || locks.all { - return Err(EngineError::Other(format!("layer \"{}\" is position-locked", l.name))); - } - if mask_target && moves_mask_alone(l) { - if let Some(m) = &mut l.mask { - m.surface = shift_surface(&m.surface, dx, dy); - } - continue; - } - shift_shown(doc, l, dx, dy); - } - Ok(out) -} - -/// `photocraft_algo::resample::translate_surface` with the content scan cached per tile (a Move -/// drag shifts the same layers every frame; scanning them each time cost more than the copy). -pub(crate) fn shift_surface(s: &photocraft_raster::Surface, dx: i32, dy: i32) -> photocraft_raster::Surface { - s.translated(dx, dy, photocraft_compose::bounds::content_bounds(s)) -} - -/// [`crate::commands::translate_layer`] plus the vector side, without re-rendering anything. -fn shift_shown(doc: &Document, l: &mut Layer, dx: i32, dy: i32) { - use self::shift_surface as translate_surface; - let a = photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy)); - if let Some(r) = &mut l.effects.reference { - *r = (r.0 + f64::from(dx), r.1 + f64::from(dy)); - } - if let Some(m) = l.mask.as_mut().filter(|m| m.linked) { - m.surface = translate_surface(&m.surface, dx, dy); - } - if let Some(vm) = l.vector_mask.as_mut().filter(|v| v.linked) { - vm.path = vm.path.transform(&a); - } - match &mut l.content { - LayerContent::Raster(s) => *s = translate_surface(s, dx, dy), - LayerContent::Text(t) => { - t.transform = a.mul(&t.transform); - if let Some(c) = &mut t.cache { - *c = translate_surface(c, dx, dy); - } - } - LayerContent::Shape(sh) => crate::vector_cmds::shift_shape(doc, sh, f64::from(dx), f64::from(dy)), - LayerContent::Smart(sm) => crate::smart_cmds::shift_smart(sm, dx, dy), - LayerContent::Group(g) => { - if let Some(ab) = &mut g.artboard { - ab.rect = ab.rect.translate(dx, dy); - } - g.children.iter_mut().for_each(|c| shift_shown(doc, c, dx, dy)); - } - LayerContent::Adjustment(_) | LayerContent::Fill(_) => {} - } -} - -/// The document pixels an edit of the layers `ids` (moved, shown, hidden or restyled; contents -/// otherwise as they were) can have changed from `before` to `after`, or `None` for anywhere. -pub fn layers_damage(before: &Document, after: &Document, ids: &[LayerId]) -> Option { - let mut out = Rect::EMPTY; - for d in [before, after] { - let canvas = d.bounds(); - for id in ids { - // A layer gone from one side (never for a move) changes who knows what. - let (siblings, k, outer) = siblings_of(d, *id)?; - let b = photocraft_compose::change_bounds_in(siblings, k, outer, canvas)?; - if !b.is_empty() { - out = if out.is_empty() { b } else { out.union(&b) }; - } - } - } - Some(out) -} - -/// The sibling list holding layer `id` in `doc` (bottom→top), its index there, and the list -/// holding its parent group with the group's index (`None` at the top level). -type Siblings<'d> = (&'d [Layer], usize, Option<(&'d [Layer], usize)>); -fn siblings_of(doc: &Document, id: LayerId) -> Option> { - let path = doc.path_of(id)?; - let (&k, parent) = path.split_last()?; - let Some((&g, grand)) = parent.split_last() else { return Some((doc.layers.as_slice(), k, None)) }; - let outer = if grand.is_empty() { doc.layers.as_slice() } else { doc.layer_at(grand)?.children()? }; - Some((outer.get(g)?.children()?, k, Some((outer, g)))) -} - -/// Report [`layers_damage`] as the active document's last change, so the canvas recomposites -/// only that (grown by the effect reach around it) instead of everything. -pub(crate) fn note_damage(s: &mut Session, before: &Document, ids: &[LayerId]) { - let Some(st) = s.active_mut() else { return }; - if before.size != st.doc.size { - return; - } - st.last_damage = layers_damage(before, &st.doc, ids); -} - -/// Whether two surfaces hold identical pixels: same format and default pixel, and the same -/// copy-on-write tile pointers at the same coordinates. Both documents stay alive during the -/// comparison, so tile addresses cannot be reused under it. -fn surfaces_equal(a: &photocraft_raster::Surface, b: &photocraft_raster::Surface) -> bool { - a.format() == b.format() - && a.default_pixel() == b.default_pixel() - && a.tile_count() == b.tile_count() - && a.tiles().zip(b.tiles()).all(|((ca, ta), (cb, tb))| ca == cb && std::sync::Arc::ptr_eq(ta, tb)) -} - -/// Byte blobs kept in `Arc`s (PSD raw blocks, embedded smart-object sources): pointer-identical -/// or content-equal (they are small compared to pixels, and undo steps rarely re-parse them). -fn blob_equal(x: &std::sync::Arc>, y: &std::sync::Arc>) -> bool { - std::sync::Arc::ptr_eq(x, y) || (x.len() == y.len() && x.as_slice() == y.as_slice()) -} - -fn blobs_equal(a: &Option>>, b: &Option>>) -> bool { - match (a, b) { - (None, None) => true, - (Some(x), Some(y)) => blob_equal(x, y), - _ => false, - } -} - -/// Layer masks (also the smart-filter mask): scalars plus tile-pointer surface identity. -fn masks_equal(a: &Option, b: &Option) -> bool { - match (a, b) { - (None, None) => true, - (Some(x), Some(y)) => { - x.enabled == y.enabled && x.linked == y.linked && x.density == y.density && x.feather == y.feather && surfaces_equal(&x.surface, &y.surface) - } - _ => false, - } -} - -fn texts_equal(a: &photocraft_doc::TextLayer, b: &photocraft_doc::TextLayer) -> bool { - a.text == b.text - && a.font_family == b.font_family - && a.size_pt == b.size_pt - && a.color == b.color - && a.transform == b.transform - && a.runs == b.runs - && a.paragraphs == b.paragraphs - && a.shape == b.shape - && a.orientation == b.orientation - && a.antialias == b.antialias - && a.warp == b.warp - && match (&a.cache, &b.cache) { - (None, None) => true, - (Some(x), Some(y)) => surfaces_equal(x, y), - _ => false, - } - && blobs_equal(&a.psd_raw, &b.psd_raw) -} - -fn smarts_equal(a: &photocraft_doc::SmartObject, b: &photocraft_doc::SmartObject) -> bool { - a.filters_enabled == b.filters_enabled - && a.transform == b.transform - && a.smart_filters == b.smart_filters - && a.stack_mode == b.stack_mode - && a.perspective == b.perspective - && a.warp == b.warp - && match (&a.source, &b.source) { - (photocraft_doc::SmartSource::Embedded { file_name: x, bytes: xb }, photocraft_doc::SmartSource::Embedded { file_name: y, bytes: yb }) => { - x == y && blob_equal(xb, yb) - } - (photocraft_doc::SmartSource::Linked { path: x }, photocraft_doc::SmartSource::Linked { path: y }) => x == y, - _ => false, - } - && match (&a.cache, &b.cache) { - (None, None) => true, - (Some(x), Some(y)) => surfaces_equal(x, y), - _ => false, - } - && blobs_equal(&a.psd_raw, &b.psd_raw) - && masks_equal(&a.filter_mask, &b.filter_mask) -} - -/// Extra alpha/spot channels (the image itself in Multichannel mode). -fn alpha_channels_equal(a: &photocraft_doc::AlphaChannel, b: &photocraft_doc::AlphaChannel) -> bool { - a.name == b.name && a.spot == b.spot && a.color == b.color && a.opacity == b.opacity && a.indicates == b.indicates && surfaces_equal(&a.surface, &b.surface) -} - -/// Whether two layers render to identical pixels in place. Everything the compositor reads is -/// compared structurally — no hashing, a hash collision would under-report damage; pixels are -/// identified by their copy-on-write tile pointers. Group children are deliberately *not* -/// compared here: the caller walks into them, so an edit inside a group damages only the -/// edited child's extent, not the whole group's. The destructure is exhaustive, so a new -/// `Layer` field fails to compile until it is classified: compared, or explicitly ignored -/// (name, locks, label, `psd_blocks`, `psd_id`, link group, XMP — none of them composite; video -/// bails out earlier in the walk). -fn layer_pixels_equal(a: &Layer, b: &Layer) -> bool { - let Layer { - id, - name: _, - visible, - locks: _, - blend, - opacity, - fill_opacity, - clipped, - mask, - vector_mask, - effects, - label: _, - content, - psd_blocks: _, - psd_id: _, - fill_cache, - link_group: _, - excluded_channels, - blend_if, - advanced, - video: _, - xmp: _, - } = a; - *id == b.id - && *visible == b.visible - && *blend == b.blend - && *opacity == b.opacity - && *fill_opacity == b.fill_opacity - && *clipped == b.clipped - && masks_equal(mask, &b.mask) - && *vector_mask == b.vector_mask - && *effects == b.effects - && *excluded_channels == b.excluded_channels - && *blend_if == b.blend_if - && *advanced == b.advanced - && match (content, &b.content) { - (LayerContent::Raster(x), LayerContent::Raster(y)) => surfaces_equal(x, y), - // Children are walked separately; only the group's own clipping frame counts. - (LayerContent::Group(x), LayerContent::Group(y)) => x.artboard == y.artboard, - (LayerContent::Fill(x), LayerContent::Fill(y)) => x == y, - (LayerContent::Adjustment(x), LayerContent::Adjustment(y)) => x == y, - (LayerContent::Text(x), LayerContent::Text(y)) => texts_equal(x, y), - (LayerContent::Shape(x), LayerContent::Shape(y)) => x == y, - (LayerContent::Smart(x), LayerContent::Smart(y)) => smarts_equal(x, y), - _ => false, - } - && match (fill_cache, &b.fill_cache) { - (None, None) => true, - (Some(x), Some(y)) => x.fill == y.fill && surfaces_equal(&x.surface, &y.surface), - _ => false, - } -} - -/// Document-level fields the compositor reads: all must match for a bounded damage claim. The -/// destructure is exhaustive, so a new `Document` field fails to compile until it is classified -/// here — compared when it composites, or explicitly ignored (the pixel-irrelevant allowlist: -/// identity, name, selection, guides, paths, layer comps, annotations, automation state). -fn doc_pixels_equal(a: &Document, b: &Document) -> bool { - let Document { - id: _, - name: _, - size, - resolution_dpi, - mode, - depth, - icc_profile, - layers: _, - channels, - guides: _, - ruler_origin: _, - selection: _, - metadata: _, - global_light, - paths: _, - work_path: _, - clipping_path: _, - quick_mask, - quick_mask_unselected: _, - patterns, - color_table, - duotone, - layer_comps: _, - last_applied_comp: _, - last_document_state: _, - measurement: _, - notes: _, - text_styles: _, - slices: _, - variables: _, - timeline: _, - file_encoding: _, - } = a; - *size == b.size - && resolution_dpi.to_bits() == b.resolution_dpi.to_bits() - && *mode == b.mode - && *depth == b.depth - && icc_profile.as_deref() == b.icc_profile.as_deref() - && channels.len() == b.channels.len() - && channels.iter().zip(&b.channels).all(|(x, y)| alpha_channels_equal(x, y)) - && *global_light == b.global_light - && match (quick_mask, &b.quick_mask) { - (None, None) => true, - (Some(x), Some(y)) => alpha_channels_equal(x, y), - _ => false, - } - && *patterns == b.patterns - && *color_table == b.color_table - && *duotone == b.duotone -} - -/// 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. -/// Conservative (`false`) past a nesting depth no real document reaches. -pub fn same_pixels(a: &Document, b: &Document) -> bool { - pixels_equal_with(a, b, |_, _| false) -} - -/// [`same_pixels`], with video layers equal when `video_equal` says their frame stacks are. -fn pixels_equal_with(a: &Document, b: &Document, video_equal: fn(&VideoData, &VideoData) -> bool) -> bool { - fn walk(xs: &[Layer], ys: &[Layer], depth: usize, video_equal: fn(&VideoData, &VideoData) -> bool) -> bool { - depth < 256 - && xs.len() == ys.len() - && xs.iter().zip(ys).all(|(x, y)| { - layer_pixels_equal(x, y) - && match (&x.video, &y.video) { - (None, None) => true, - (Some(vx), Some(vy)) => video_equal(vx, vy), - _ => false, - } - && match (x.children(), y.children()) { - (Some(xc), Some(yc)) => walk(xc, yc, depth + 1, video_equal), - (None, None) => true, - _ => false, - } - }) - } - doc_pixels_equal(a, b) && walk(&a.layers, &b.layers, 0, video_equal) -} - -/// Whether two video layers hold the same frames: the same settings and stack shape -/// (`VideoData`'s own, shallow equality) and the same tile pointers in every frame, painted and -/// original. Pointer compares only, like [`surfaces_equal`]. -fn video_frames_equal(a: &VideoData, b: &VideoData) -> bool { - let frames = |x: &[photocraft_raster::Surface], y: &[photocraft_raster::Surface]| x.len() == y.len() && x.iter().zip(y).all(|(f, g)| surfaces_equal(f, g)); - *a == *b - && frames(&a.frames, &b.frames) - && match (&a.original_frames, &b.original_frames) { - (Some(x), Some(y)) => frames(x, y), - (None, None) => true, - _ => false, - } -} - -/// Whether `a` and `b` differ at most in their selection (#6865): a selection step, which must -/// not mark a clean document modified. Pixels compare by tile pointer (as in [`same_pixels`], -/// plus every frame of a video layer, whose own equality is shallow); every other field compares -/// structurally, where copy-on-write `Arc`s of `Eq` data short-circuit on pointer identity. The -/// destructure is exhaustive, so a new `Document` field fails to compile until it is classified. -pub fn selection_only_change(a: &Document, b: &Document) -> bool { - let Document { - id, - name, - size: _, - resolution_dpi: _, - mode: _, - depth: _, - icc_profile: _, - layers, - channels: _, - guides, - ruler_origin, - selection: _, - metadata, - global_light: _, - paths, - work_path, - clipping_path, - quick_mask: _, - quick_mask_unselected, - patterns: _, - color_table: _, - duotone: _, - layer_comps, - last_applied_comp, - last_document_state, - measurement, - notes, - text_styles, - slices, - variables, - timeline, - file_encoding, - } = a; - // The ignored fields above are the pixel ones `pixels_equal_with` already compares. - pixels_equal_with(a, b, video_frames_equal) - && *id == b.id - && *name == b.name - && *layers == b.layers - && *guides == b.guides - && *ruler_origin == b.ruler_origin - && *metadata == b.metadata - && *paths == b.paths - && *work_path == b.work_path - && *clipping_path == b.clipping_path - && *quick_mask_unselected == b.quick_mask_unselected - && *layer_comps == b.layer_comps - && *last_applied_comp == b.last_applied_comp - && *last_document_state == b.last_document_state - && *measurement == b.measurement - && *notes == b.notes - && *text_styles == b.text_styles - && *slices == b.slices - && *variables == b.variables - && *timeline == b.timeline - && *file_encoding == b.file_encoding -} - -/// Pixels a single history step can have changed between `a` and `b` (the documents on either -/// side of an edit, its undo or its redo): the union of the change bounds of every layer whose -/// pixels differ, so a local edit recomposites only that area instead of the whole canvas. A -/// layer only one side has (a duplicate, a paste, a deleted layer) counts where it draws (see -/// [`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 -/// 12 MP layer used to recomposite every layer of the document (#2883, P8/P9 in -/// `perf/budgets.toml`). -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)>; - fn walk(xs: &[Layer], ys: &[Layer], (ox, oy): (Outer, Outer), a: &Document, b: &Document, out: &mut Rect) -> bool { - // 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) }; - } - true - }; - 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), - _ if inert_at(ys, j) => { - j += 1; - continue; - } - _ if inert_at(xs, i) => { - i += 1; - continue; - } - (_, Some(y)) if xs.iter().all(|x| x.id != y.id) => { - if !one_sided(ys, j, oy, 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) { - return false; - } - i += 1; - continue; - } - // Both sides have the layer, in another order. - _ => return false, - }; - let (xk, yk) = (i, j); - i += 1; - j += 1; - 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 { - return false; - } - if !layer_pixels_equal(x, y) { - // 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 { - return false; - }; - *out = if out.is_empty() { bx.union(&by) } else { out.union(&bx).union(&by) }; - } - match (x.children(), y.children()) { - (Some(xc), Some(yc)) => { - if !walk(xc, yc, (Some((xs, xk)), Some((ys, yk))), a, b, out) { - return false; - } - } - (None, None) => {} - _ => return false, - } - } - } - let mut out = Rect::EMPTY; - if walk(&a.layers, &b.layers, (None, None), a, b, &mut out) { Some(out) } else { None } -} - -/// 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 -/// 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))) - } - 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) -} - -/// Whether `layers[k]` draws nothing wherever it sits, so adding or removing it leaves the -/// composite as it was: an empty pixel layer (no tiles, transparent default) or an empty group, -/// in a Normal or Pass Through blend with no mask, vector mask, effects or Advanced Blending. -/// A clipping base that would gain or lose the clipped layers above it is not inert. -fn inert_at(layers: &[Layer], k: usize) -> bool { - let Some(l) = layers.get(k) else { return false }; - let empty = match &l.content { - LayerContent::Raster(s) => s.tile_count() == 0 && s.format().alpha && s.default_bytes().iter().all(|b| *b == 0), - LayerContent::Group(g) => g.children.is_empty() && g.artboard.is_none(), - _ => false, - }; - empty - && matches!(l.blend, photocraft_doc::BlendMode::Normal | photocraft_doc::BlendMode::PassThrough) - && l.mask.is_none() - && l.vector_mask.is_none() - && !photocraft_compose::effects::has_effects(l) - && l.fill_cache.is_none() - && l.video.is_none() - && l.advanced == photocraft_doc::AdvancedBlending::default() - && (l.clipped || layers.get(k + 1).is_none_or(|above| !above.clipped)) -} - -/// Report that adding layer `id` to the active document changed no pixels when it draws -/// nothing ([`inert_at`]), so the canvas doesn't recomposite every layer for it (#1771). Looks -/// only at the new layer and its neighbour, never at other layers' tiles. -pub(crate) fn note_inert_insert(s: &mut Session, id: LayerId) { - let Some(st) = s.active_mut() else { return }; - let Some(path) = st.doc.path_of(id) else { return }; - let Some((&k, parent)) = path.split_last() else { return }; - let siblings = if parent.is_empty() { Some(st.doc.layers.as_slice()) } else { st.doc.layer_at(parent).and_then(Layer::children) }; - if siblings.is_some_and(|sib| inert_at(sib, k)) { - st.last_damage = Some(Rect::EMPTY); - } -} - -/// 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); -} - -/// Content bounds used by Align/Distribute: the layer's pixels (type and shape layers use their -/// rendered pixels), or the union of a group's children. Fill and adjustment layers have none. -pub fn layer_bounds(l: &Layer) -> Option { - let r = match &l.content { - LayerContent::Group(g) => g.children.iter().filter_map(layer_bounds).fold(Rect::EMPTY, |a, b| a.union(&b)), - _ => l.surface().map(|s| s.content_bounds()).unwrap_or(Rect::EMPTY), - }; - (!r.is_empty()).then_some(r) -} - -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Edge { - Top, - VCenter, - Bottom, - Left, - HCenter, - Right, -} - -impl Edge { - fn parse(k: &str) -> Option { - Some(match k { - "topEdges" => Edge::Top, - "verticalCenters" => Edge::VCenter, - "bottomEdges" => Edge::Bottom, - "leftEdges" => Edge::Left, - "horizontalCenters" => Edge::HCenter, - "rightEdges" => Edge::Right, - _ => return None, - }) - } - fn vertical(self) -> bool { - matches!(self, Edge::Top | Edge::VCenter | Edge::Bottom) - } - /// The edge's coordinate, doubled so centres stay integral. - fn value2(self, r: &Rect) -> i64 { - let (a, b) = if self.vertical() { (r.y0, r.y1) } else { (r.x0, r.x1) }; - match self { - Edge::Top | Edge::Left => 2 * a as i64, - Edge::Bottom | Edge::Right => 2 * b as i64, - Edge::VCenter | Edge::HCenter => a as i64 + b as i64, - } - } - fn delta(self, d: i32) -> (i32, i32) { - if self.vertical() { (0, d) } else { (d, 0) } - } -} - -/// Selected top-level layers that have content bounds, bottom-to-top. -fn bounded_selection(doc: &Document, sel: &[LayerId]) -> Vec<(LayerId, Rect)> { - top_level(doc, sel).into_iter().filter_map(|id| Some((id, layer_bounds(doc.layer(id)?)?))).collect() -} - -fn align(s: &mut Session, p: &Value, kind: &str) -> Result { - let cmd = format!("layer.align.{kind}"); - let edge = Edge::parse(kind).ok_or_else(|| bad(&cmd, "unknown edge"))?; - let sel = selected(s); - let to = p.get("to").and_then(Value::as_str).unwrap_or("auto").to_string(); - let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); - let moved = s.edit("Align", |doc, _| { - let items = bounded_selection(doc, &sel); - if items.is_empty() { - return Err(EngineError::Other("the selected layers have no content to align".into())); - } - let target = match to.as_str() { - "canvas" => doc.bounds(), - "selection" => doc.selection.as_ref().map(|m| m.content_bounds()).ok_or_else(|| EngineError::Other("there is no selection to align to".into()))?, - "auto" | "layers" => match (&doc.selection, sel.len()) { - // Photoshop: with an active selection, the layers align to its bounds (Layer › Align - // Layers to Selection), however many are selected. - (Some(m), _) if to == "auto" && !m.content_bounds().is_empty() => m.content_bounds(), - // One layer with no selection aligns to the canvas (otherwise it would align to - // itself), or to the artboard it sits in, as in Photoshop (#7945). - (None, 1) if to == "auto" => items.first().map_or_else(|| doc.bounds(), |(id, _)| board_or_canvas(doc, *id)), - _ => items.iter().fold(Rect::EMPTY, |a, (_, b)| a.union(b)), - }, - other => return Err(bad(&cmd, format!("`to` must be auto|layers|selection|canvas, not `{other}`"))), - }; - if target.is_empty() { - return Err(EngineError::Other("nothing to align to".into())); - } - let t2 = edge.value2(&target); - let moves: Vec<(LayerId, i32, i32)> = items - .iter() - .flat_map(|(id, r)| { - let d = (t2 - edge.value2(r)).div_euclid(2) as i32; - let (dx, dy) = edge.delta(d); - // Linked layers travel with the layer they are linked to. - with_links(doc, &[*id]).into_iter().map(move |l| (l, dx, dy)) - }) - .collect(); - let moves = dedup_moves(doc, moves); - move_layers(doc, &before, &moves)?; - Ok(moves.iter().filter(|m| m.1 != 0 || m.2 != 0).count()) - })?; - Ok(json!({"moved": moved})) -} - -/// The bounds a lone layer aligns to: the artboard holding it, else the canvas. An artboard -/// itself aligns to the canvas. -fn board_or_canvas(doc: &Document, id: LayerId) -> Rect { - doc.artboard_of(id).filter(|board| *board != id).and_then(|board| doc.layer(board)?.artboard().map(|a| a.rect)).unwrap_or_else(|| doc.bounds()) -} - -/// One move per layer (first wins), skipping layers nested in another moved layer. -fn dedup_moves(doc: &Document, moves: Vec<(LayerId, i32, i32)>) -> Vec<(LayerId, i32, i32)> { - let mut out: Vec<(LayerId, i32, i32)> = Vec::new(); - for m in moves { - if !out.iter().any(|o| o.0 == m.0) { - out.push(m); - } - } - let ids: Vec = out.iter().map(|m| m.0).collect(); - let keep = top_level(doc, &ids); - out.retain(|m| keep.contains(&m.0)); - out -} - -fn distribute(s: &mut Session, kind: &str) -> Result { - let sel = selected(s); - let kind = kind.to_string(); - let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); - let moved = s.edit("Distribute", |doc, _| { - let mut items = bounded_selection(doc, &sel); - if items.len() < 3 { - return Err(EngineError::Other("distributing needs three or more layers with content".into())); - } - let n = items.len(); - let mut moves = Vec::new(); - match kind.as_str() { - "horizontally" | "vertically" => { - // Equal gaps between neighbours; the outermost layers stay put. - let v = kind == "vertically"; - let lo = |r: &Rect| if v { r.y0 } else { r.x0 } as i64; - let hi = |r: &Rect| if v { r.y1 } else { r.x1 } as i64; - items.sort_by_key(|(_, r)| (lo(r) + hi(r), lo(r))); - let span = hi(&items[n - 1].1) - lo(&items[0].1); - let total: i64 = items.iter().map(|(_, r)| hi(r) - lo(r)).sum(); - let gap = (span - total) as f64 / (n - 1) as f64; - let mut cursor = lo(&items[0].1) as f64; - for (id, r) in &items { - let want = cursor.round() as i64; - let d = (want - lo(r)) as i32; - moves.push(if v { (*id, 0, d) } else { (*id, d, 0) }); - cursor += (hi(r) - lo(r)) as f64 + gap; - } - } - k => { - let edge = Edge::parse(k).ok_or_else(|| bad("layer.distribute", format!("unknown kind `{k}`")))?; - items.sort_by_key(|(_, r)| edge.value2(r)); - let (first, last) = (edge.value2(&items[0].1) as f64, edge.value2(&items[n - 1].1) as f64); - for (i, (id, r)) in items.iter().enumerate() { - let want2 = first + (last - first) * i as f64 / (n - 1) as f64; - let d = ((want2 - edge.value2(r) as f64) / 2.0).round() as i32; - let (dx, dy) = edge.delta(d); - moves.push((*id, dx, dy)); - } - } - } - let moves: Vec<_> = moves.into_iter().flat_map(|(id, dx, dy)| with_links(doc, &[id]).into_iter().map(move |l| (l, dx, dy))).collect(); - let moves = dedup_moves(doc, moves); - move_layers(doc, &before, &moves)?; - Ok(moves.iter().filter(|m| m.1 != 0 || m.2 != 0).count()) - })?; - Ok(json!({"moved": moved})) -} - -/// Reorder one or multiple layers to a single destination in one undoable edit. -/// -/// Explicit `layers` are ordered according to the source document, not caller ordering. -/// A transient snapshot for the Layers panel's "Preview on canvas when reordering layers". -/// Uses the same source ordering and insertion semantics as `move_to`, but never edits history. -/// Invalid/self-referential hover targets return None (the committed image stays visible). -pub fn preview_move(doc: &Document, p: &Value, add_copy: bool) -> Option { - let target = LayerId(p.get("target")?.as_u64()?); - let position = p.get("position")?.as_str()?; - if !matches!(position, "above" | "below" | "into") { - return None; - } - let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); - let ids = if let Some(ids) = p.get("layers") { - ids.as_array()?.iter().map(|v| v.as_u64().map(LayerId)).collect::>>()? - } else { - vec![LayerId(p.get("layer")?.as_u64()?)] - }; - if ids.is_empty() || doc.layer(target).is_none() { - return None; - } - let moved_ids = top_level(doc, &ids); - if moved_ids.is_empty() || moved_ids.iter().any(|id| doc.layer(*id).is_none()) { - return None; - } - if moved_ids.len() == 1 && moved_ids[0] == target && !copy { - return None; - } - let target_path = doc.path_of(target)?; - for id in &moved_ids { - let path = doc.path_of(*id)?; - if target_path.starts_with(&path) && !(copy && *id == target && position != "into") { - return None; - } - } - if position == "into" && !doc.layer(target)?.is_group() { - return None; - } - // The very structural move the drop commits, so the preview shows the same clip groups, - // Background handling and group-depth refusals; a drop `move_to` would refuse has no preview. - let mut preview = doc.clone(); - apply_move(&mut preview, &moved_ids, target, position, copy, add_copy).ok()?; - Some(preview) -} - -/// The document-only part of `move_to`, shared with [`preview_move`] so the Layers panel's hover -/// preview cannot drift from what the drop commits. Moves (or, with `copy`, duplicates) the -/// top-level `moved_ids` to `pos` (`above`, `below` or `into`) `target`, then applies the -/// group-depth cap, the Background-stays-at-the-bottom rule and the clip-group rules -/// (`clip_group::settle`). Returns the ids of the new copies (empty for a move). On `Err` `doc` is -/// half edited: run it inside `Session::edit` or on a scratch copy. -fn apply_move(doc: &mut Document, moved_ids: &[LayerId], target: LayerId, pos: &str, copy: bool, add_copy: bool) -> Result> { - const CMD: &str = "layer.moveTo"; - let background = crate::background_cmds::background_id(doc); - let before = if copy { Default::default() } else { crate::clip_group::Before::read(doc, moved_ids) }; - let mut moved = Vec::with_capacity(moved_ids.len()); - for &id in moved_ids { - moved.push(if copy { crate::commands::layer_copy(doc, id, add_copy)? } else { doc.remove(id).ok_or(EngineError::NoLayer(id))? }); - } - let copies: Vec = if copy { moved.iter().map(|l| l.id).collect() } else { Vec::new() }; - // Look up the destination AFTER removing every source: its indices may have shifted. - let path = doc.path_of(target).ok_or(EngineError::NoLayer(target))?; - if pos == "into" { - let children = doc.layer_at_mut(&path).and_then(Layer::children_mut).ok_or_else(|| bad(CMD, "target is not a group"))?; - children.extend(moved); - } else { - let (&idx, parent) = path.split_last().ok_or(EngineError::NoLayer(target))?; - let siblings = if parent.is_empty() { - &mut doc.layers - } else { - doc.layer_at_mut(parent).and_then(Layer::children_mut).ok_or_else(|| bad(CMD, "target's parent is not a group"))? - }; - let at = if pos == "below" { idx } else { idx + 1 }; - siblings.splice(at..at, moved); - } - check_group_depth(doc, "Reorder Layer")?; - crate::background_cmds::keep_background_at_bottom(background, doc)?; - crate::clip_group::settle(doc, if copy { &copies } else { moved_ids }, &before, false); - Ok(copies) -} - -/// Selected descendants of a moved group remain inside their parent; only top-level -/// selected nodes are detached, and every reference is validated before editing. -pub fn move_to(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "layer.moveTo"; - let pos = p.get("position").and_then(Value::as_str).unwrap_or("above"); - if !matches!(pos, "above" | "below" | "into") { - return Err(bad(CMD, "position must be above, below, or into")); - } - // ⌥-drag in the Layers panel: duplicates land at the target and the layers stay put. - let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); - - let batch = p.get("layers"); - if batch.is_some() && p.get("layer").is_some() { - return Err(bad(CMD, "give either `layer` or `layers`, not both")); - } - let requested = if let Some(raw) = batch { - let arr = raw.as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad(CMD, "`layers` must be a nonempty array of ids"))?; - let mut ids = Vec::with_capacity(arr.len()); - for item in arr { - let id = LayerId(item.as_u64().ok_or_else(|| bad(CMD, "every layer id must be an unsigned integer"))?); - if ids.contains(&id) { - return Err(bad(CMD, "duplicate layer id")); - } - ids.push(id); - } - ids - } else { - vec![crate::commands::layer_param(s, p)?] - }; - // A copy moves nothing, so its source stays a candidate (⌥-dragging a layer beside itself). - let target = move_target(s, p, if copy { &[] } else { &requested })?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let doc = &st.doc; - let target_path = doc.path_of(target).ok_or(EngineError::NoLayer(target))?; - for &id in &requested { - if doc.layer(id).is_none() { - return Err(EngineError::NoLayer(id)); - } - } - let moved_ids = top_level(doc, &requested); - if moved_ids.len() == 1 && moved_ids[0] == target && batch.is_none() && !copy { - // Preserve single-layer drag-to-self semantics. - return Ok(Value::Null); - } - // Also rejects dragging a selected group onto any of its descendants. - for id in &moved_ids { - let path = doc.path_of(*id).ok_or(EngineError::NoLayer(*id))?; - // A copy may land beside its own source (not inside it). - let beside_itself = copy && *id == target && pos != "into"; - if target_path.starts_with(&path) && !beside_itself { - return Err(bad(CMD, "target cannot be one of the moved layers or its descendant")); - } - } - if pos == "into" && doc.layer(target).is_none_or(|l| !l.is_group()) { - return Err(bad(CMD, "target is not a group")); - } - - let original_active = st.active_layer; - let add_copy = crate::commands::layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true); - let (count, copies) = s.edit(if copy { "Duplicate Layer" } else { "Reorder Layers" }, |doc, active| { - let copies = apply_move(doc, &moved_ids, target, pos, copy, add_copy)?; - *active = if copy { - copies.last().copied() - } else if batch.is_some() { - original_active.filter(|id| requested.contains(id)).or_else(|| requested.last().copied()) - } else { - moved_ids.first().copied() - }; - Ok((moved_ids.len(), copies)) - })?; - if copy { - let ids: Vec = copies.iter().map(|id| id.0).collect(); - if batch.is_some() { - let active = copies.last().copied(); - reselect(s, copies, active); - return Ok(json!({"moved": count, "layers": ids})); - } - return Ok(json!({"layer": ids.first()})); - } - if batch.is_some() { - let active = original_active.filter(|id| requested.contains(id)).or_else(|| requested.last().copied()); - reselect(s, requested, active); - Ok(json!({"moved": count})) - } else { - Ok(Value::Null) - } -} - -// ---------- structural commands ---------- - -fn link_layers(s: &mut Session) -> Result { - let sel = selected(s); - let linked = s.edit("Link Layers", |doc, _| { - let groups: Vec> = sel.iter().map(|id| doc.layer(*id).and_then(|l| l.link_group)).collect(); - // Already one link group (or a single linked layer): unlink, like Photoshop's toggle. - let first = groups.first().copied().flatten(); - let unlink = first.is_some() && groups.iter().all(|g| *g == first); - // A loaded file can store any id up to u64::MAX, so the new id must not be a bare - // max + 1 (#961). Unlinking needs no new id at all. - let next = if unlink { None } else { Some(doc.unused_link_group().ok_or_else(|| bad("layer.linkLayers", "no free link group id is left"))?) }; - for id in &sel { - let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; - l.link_group = next; - } - // A group left with a single member is no longer a link. - let mut counts = std::collections::HashMap::::new(); - for (_, _, l) in doc.walk() { - if let Some(g) = l.link_group { - *counts.entry(g).or_default() += 1; - } - } - let lonely: Vec = - doc.walk().iter().filter(|(_, _, l)| l.link_group.is_some_and(|g| counts.get(&g).is_some_and(|&c| c < 2))).map(|(_, _, l)| l.id).collect(); - for id in lonely { - if let Some(l) = doc.layer_mut(id) { - l.link_group = None; - } - } - Ok(!unlink) - })?; - Ok(json!({"linked": linked})) -} - -fn lock_layers(s: &mut Session, p: &Value) -> Result { - let sel = selected(s); - let keys = ["transparency", "pixels", "position", "artboard", "all"]; - let given: Vec<(&str, bool)> = keys.iter().filter_map(|k| Some((*k, p.get(*k)?.as_bool()?))).collect(); - s.edit("Lock Layers", |doc, _| { - // No explicit locks: toggle "lock all" (on unless every selected layer is already locked). - let all_locked = sel.iter().all(|id| doc.layer(*id).is_some_and(|l| l.locks.all)); - let given: Vec<(&str, bool)> = if given.is_empty() { vec![("all", !all_locked)] } else { given.clone() }; - for id in &sel { - let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; - for (k, v) in &given { - l.locks.set(k, *v); - } - } - Ok(()) - })?; - Ok(json!({"layers": sel.len()})) -} - -fn rename_layer(s: &mut Session, p: &Value) -> Result { - let name = p.get("name").and_then(Value::as_str).filter(|n| !n.trim().is_empty()).ok_or_else(|| bad("layer.renameLayer", "missing `name`"))?.to_string(); - let id = crate::commands::layer_param(s, p)?; - s.edit("Rename Layer", |doc, _| { - doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.name = name; - Ok(()) - })?; - Ok(Value::Null) -} - -fn reverse(s: &mut Session) -> Result { - let sel = selected(s); - s.edit("Reverse", |doc, _| { - let background = crate::background_cmds::background_id(doc); - let ids = top_level(doc, &sel); - if ids.len() < 2 { - return Err(EngineError::Other("select two or more layers to reverse".into())); - } - let paths: Vec> = ids.iter().map(|id| doc.path_of(*id).ok_or(EngineError::NoLayer(*id))).collect::>()?; - let layers: Vec = ids.iter().map(|id| doc.layer(*id).cloned().ok_or(EngineError::NoLayer(*id))).collect::>()?; - // Slots are disjoint (no layer is nested in another), so writing whole layers back to the - // same paths never shifts another slot. - for (path, l) in paths.iter().zip(layers.into_iter().rev()) { - *doc.layer_at_mut(path).ok_or_else(|| EngineError::Other("layer tree changed".into()))? = l; - } - crate::background_cmds::keep_background_at_bottom(background, doc) - })?; - Ok(Value::Null) -} - -/// Refuses an edit that left `doc` nested deeper than [`photocraft_doc::MAX_GROUP_DEPTH`] -/// groups. Called at the end of a `Session::edit` closure, so an `Err` leaves the document and -/// history untouched. -pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> { - if doc.max_group_depth() > photocraft_doc::MAX_GROUP_DEPTH { - return Err(EngineError::Other(format!("{what} would nest layers deeper than {} groups", photocraft_doc::MAX_GROUP_DEPTH))); - } - Ok(()) -} - -/// Group Layers (⌘G) / Group from Layers: the explicit layer, or every selected layer, moves -/// into a new, collapsed group placed where the top-most of them was. Bottom-to-top order is -/// preserved. -pub fn group_layers(s: &mut Session, p: &Value) -> Result { - let ids = match crate::commands::explicit_layer(s, p)? { - Some(id) => vec![id], - None => selected(s), - }; - if ids.is_empty() { - return Err(EngineError::Other("no layer selected".into())); - } - let name = p.get("name").and_then(Value::as_str).map(str::to_string); - let gid = s.edit("Group Layers", |doc, active| { - let ids = top_level(doc, &ids); - let top = *ids.last().ok_or(EngineError::NoLayer(LayerId(0)))?; - let name = name.unwrap_or_else(|| doc.next_layer_name("Group")); - // Photoshop creates the group collapsed, so the panel shows one row in place of the layers. - let mut group = Layer::group(name, vec![]); - if let LayerContent::Group(g) = &mut group.content { - g.expanded = false; - } - let gid = doc.insert_above(Some(top), group); - let mut children = Vec::with_capacity(ids.len()); - for id in &ids { - children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?); - } - *doc.layer_mut(gid).and_then(Layer::children_mut).ok_or(EngineError::NoLayer(gid))? = children; - check_group_depth(doc, "Group Layers")?; - *active = Some(gid); - Ok(gid) - })?; - reselect(s, vec![gid], Some(gid)); - Ok(json!({ "layer": gid.0 })) -} - -fn merge_layers(s: &mut Session) -> Result { - let sel = selected(s); - if sel.len() < 2 { - // ⌘E on a lone group is Photoshop's Merge Group (#3832); on a layer, Merge Down. - if let Some(&id) = sel.first() - && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Group(_))) - { - return s.execute("layer.mergeGroup", json!({ "layer": id.0 })); - } - return s.execute("layer.mergeDown", json!({})); - } - let mid = s.edit("Merge Layers", |doc, active| { - let ids = top_level(doc, &sel); - let lowest_id = *ids.first().ok_or_else(|| EngineError::Other("Merge Layers needs two or more layers".into()))?; - let is_background = doc.is_background(lowest_id); - - let mut solo = doc.clone(); - solo.layers = ids.iter().filter_map(|id| doc.layer(*id)).filter(|l| l.visible).cloned().collect(); - if solo.layers.is_empty() { - return Err(EngineError::Other("the selected layers are all hidden".into())); - } - - if is_background { - let base = doc.layer(lowest_id).ok_or(EngineError::NoLayer(lowest_id))?.clone(); - let fmt = doc.pixel_format(); - let mut merged = Layer::raster(base.name.clone(), fmt); - merged.locks = base.locks; - merged.label = base.label; - merged.id = lowest_id; - merged.blend = base.blend; - merged.opacity = 1.0; - *crate::pixels_mut(&mut merged)? = crate::pixels::composite_layers(&solo, fmt, None); - for id in &ids[1..] { - doc.remove(*id); - } - *doc.layer_mut(lowest_id).ok_or(EngineError::NoLayer(lowest_id))? = merged; - *active = Some(lowest_id); - Ok(lowest_id) - } else { - let top_id = *ids.last().ok_or_else(|| EngineError::Other("Merge Layers needs two or more layers".into()))?; - let top = doc.layer(top_id).ok_or(EngineError::NoLayer(top_id))?.clone(); - let fmt = doc.pixel_format(); - let fmt = PixelFormat::new(fmt.mode, fmt.sample, true); - let mut merged = Layer::raster(top.name.clone(), fmt); - merged.locks = top.locks; - merged.label = top.label; - // Clipped layers of one chain merge into a layer still clipped to their base. Clipped - // layers of different chains don't: the result, at the top one's slot, would clip the - // lower chain's pixels to the upper chain's base. - let base = crate::clip_group::base_of(doc, top_id); - merged.clipped = base.is_some() && solo.layers.iter().all(|l| l.clipped && crate::clip_group::base_of(doc, l.id) == base); - *crate::pixels_mut(&mut merged)? = crate::pixels::composite_layers_uncropped(&solo, fmt); - let mid = merged.id; - // Hidden selected layers are discarded, as in Photoshop. - for id in &ids[..ids.len() - 1] { - doc.remove(*id); - } - *doc.layer_mut(top_id).ok_or(EngineError::NoLayer(top_id))? = merged; - *active = Some(mid); - Ok(mid) - } - })?; - reselect(s, vec![mid], Some(mid)); - Ok(json!({ "layer": mid.0 })) -} - -/// Next visible layer row below the deleted target, then rows above in reverse order. -/// Group headers precede their children in the UI, unlike Document::walk's storage order. -pub(crate) fn deletion_neighbours(doc: &Document, target: LayerId) -> Vec { - let rows = |expand_all: bool| { - let mut stack: Vec<&Layer> = doc.layers.iter().collect(); - let mut order = Vec::new(); - while let Some(layer) = stack.pop() { - order.push(layer.id); - if let LayerContent::Group(group) = &layer.content - && (expand_all || group.expanded) - { - stack.extend(group.children.iter()); - } - } - order - }; - let mut order = rows(false); - if !order.contains(&target) { - order = rows(true); - } - let Some(index) = order.iter().position(|id| *id == target) else { - return Vec::new(); - }; - order.iter().skip(index + 1).chain(order.iter().take(index).rev()).copied().collect() -} - -/// Delete Layer with several layers selected. -pub fn delete_selected(s: &mut Session) -> Result { - let sel = selected(s); - s.edit("Delete Layers", |doc, active| { - let ids = top_level(doc, &sel); - let neighbours = active.map(|id| deletion_neighbours(doc, id)).unwrap_or_default(); - let before = crate::clip_group::Before::read(doc, &ids); - for id in &ids { - doc.remove(*id).ok_or(EngineError::NoLayer(*id))?; - } - crate::clip_group::settle(doc, &[], &before, false); - if doc.layers.is_empty() { - return Err(EngineError::Other("a document must keep at least one layer".into())); - } - *active = neighbours.into_iter().find(|candidate| doc.layer(*candidate).is_some()); - Ok(()) - })?; - Ok(json!({"deleted": sel.len()})) -} - -/// Duplicate Layer with several layers selected: each copy goes above its original and the -/// copies become the selection. Artboard copies go beside their boards unless `in_place` -/// ([`crate::artboard_cmds::place_copy`]). `label` names the history step (Layer via Copy reuses -/// this path, #2777). -pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Result { - 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 (copies, active) = s.edit(label, |doc, active| { - let mut copies = Vec::new(); - let mut new_active = None; - for id in top_level(doc, &sel) { - // Match the single-layer duplicate path: Background copies become - // ordinary layers, while normal copies retain their original locks. - 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)?; - } - if Some(id) == old_active { - new_active = Some(nid); - } - copies.push(nid); - } - let a = new_active.or(copies.last().copied()); - *active = a; - Ok((copies, a)) - })?; - let out = copies.iter().map(|l| l.0).collect::>(); - reselect(s, copies, active); - Ok(json!({"layers": out, "layer": active.map(|l| l.0)})) -} - -/// Show/hide every selected layer in one step. -pub fn set_visible_selected(s: &mut Session, visible: bool) -> Result { - let sel = selected(s); - s.edit(if visible { "Show Layers" } else { "Hide Layers" }, |doc, _| { - for id in &sel { - doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.visible = visible; - } - Ok(()) - })?; - Ok(Value::Null) -} - /// Is more than one layer selected (so single-layer commands should act on the whole set)? pub fn multi(s: &Session, p: &Value) -> bool { p.get("layer").is_none() && selected(s).len() > 1 diff --git a/crates/engine/src/layer_multi_cmds/align.rs b/crates/engine/src/layer_multi_cmds/align.rs new file mode 100644 index 0000000000..b6a98f07a0 --- /dev/null +++ b/crates/engine/src/layer_multi_cmds/align.rs @@ -0,0 +1,162 @@ +use super::damage::layer_bounds; +use super::moves::{move_layers, with_links}; +use super::selection::{selected, top_level}; +use super::*; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Edge { + Top, + VCenter, + Bottom, + Left, + HCenter, + Right, +} + +impl Edge { + fn parse(k: &str) -> Option { + Some(match k { + "topEdges" => Edge::Top, + "verticalCenters" => Edge::VCenter, + "bottomEdges" => Edge::Bottom, + "leftEdges" => Edge::Left, + "horizontalCenters" => Edge::HCenter, + "rightEdges" => Edge::Right, + _ => return None, + }) + } + fn vertical(self) -> bool { + matches!(self, Edge::Top | Edge::VCenter | Edge::Bottom) + } + /// The edge's coordinate, doubled so centres stay integral. + fn value2(self, r: &Rect) -> i64 { + let (a, b) = if self.vertical() { (r.y0, r.y1) } else { (r.x0, r.x1) }; + match self { + Edge::Top | Edge::Left => 2 * a as i64, + Edge::Bottom | Edge::Right => 2 * b as i64, + Edge::VCenter | Edge::HCenter => a as i64 + b as i64, + } + } + fn delta(self, d: i32) -> (i32, i32) { + if self.vertical() { (0, d) } else { (d, 0) } + } +} + +/// Selected top-level layers that have content bounds, bottom-to-top. +fn bounded_selection(doc: &Document, sel: &[LayerId]) -> Vec<(LayerId, Rect)> { + top_level(doc, sel).into_iter().filter_map(|id| Some((id, layer_bounds(doc.layer(id)?)?))).collect() +} + +pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result { + let cmd = format!("layer.align.{kind}"); + let edge = Edge::parse(kind).ok_or_else(|| bad(&cmd, "unknown edge"))?; + let sel = selected(s); + let to = p.get("to").and_then(Value::as_str).unwrap_or("auto").to_string(); + let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); + let moved = s.edit("Align", |doc, _| { + let items = bounded_selection(doc, &sel); + if items.is_empty() { + return Err(EngineError::Other("the selected layers have no content to align".into())); + } + let target = match to.as_str() { + "canvas" => doc.bounds(), + "selection" => doc.selection.as_ref().map(|m| m.content_bounds()).ok_or_else(|| EngineError::Other("there is no selection to align to".into()))?, + "auto" | "layers" => match (&doc.selection, sel.len()) { + // Photoshop: with an active selection, the layers align to its bounds (Layer › Align + // Layers to Selection), however many are selected. + (Some(m), _) if to == "auto" && !m.content_bounds().is_empty() => m.content_bounds(), + // One layer with no selection aligns to the canvas (otherwise it would align to + // itself), or to the artboard it sits in, as in Photoshop (#7945). + (None, 1) if to == "auto" => items.first().map_or_else(|| doc.bounds(), |(id, _)| board_or_canvas(doc, *id)), + _ => items.iter().fold(Rect::EMPTY, |a, (_, b)| a.union(b)), + }, + other => return Err(bad(&cmd, format!("`to` must be auto|layers|selection|canvas, not `{other}`"))), + }; + if target.is_empty() { + return Err(EngineError::Other("nothing to align to".into())); + } + let t2 = edge.value2(&target); + let moves: Vec<(LayerId, i32, i32)> = items + .iter() + .flat_map(|(id, r)| { + let d = (t2 - edge.value2(r)).div_euclid(2) as i32; + let (dx, dy) = edge.delta(d); + // Linked layers travel with the layer they are linked to. + with_links(doc, &[*id]).into_iter().map(move |l| (l, dx, dy)) + }) + .collect(); + let moves = dedup_moves(doc, moves); + move_layers(doc, &before, &moves)?; + Ok(moves.iter().filter(|m| m.1 != 0 || m.2 != 0).count()) + })?; + Ok(json!({"moved": moved})) +} + +/// The bounds a lone layer aligns to: the artboard holding it, else the canvas. An artboard +/// itself aligns to the canvas. +fn board_or_canvas(doc: &Document, id: LayerId) -> Rect { + doc.artboard_of(id).filter(|board| *board != id).and_then(|board| doc.layer(board)?.artboard().map(|a| a.rect)).unwrap_or_else(|| doc.bounds()) +} + +/// One move per layer (first wins), skipping layers nested in another moved layer. +fn dedup_moves(doc: &Document, moves: Vec<(LayerId, i32, i32)>) -> Vec<(LayerId, i32, i32)> { + let mut out: Vec<(LayerId, i32, i32)> = Vec::new(); + for m in moves { + if !out.iter().any(|o| o.0 == m.0) { + out.push(m); + } + } + let ids: Vec = out.iter().map(|m| m.0).collect(); + let keep = top_level(doc, &ids); + out.retain(|m| keep.contains(&m.0)); + out +} + +pub(super) fn distribute(s: &mut Session, kind: &str) -> Result { + let sel = selected(s); + let kind = kind.to_string(); + let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); + let moved = s.edit("Distribute", |doc, _| { + let mut items = bounded_selection(doc, &sel); + if items.len() < 3 { + return Err(EngineError::Other("distributing needs three or more layers with content".into())); + } + let n = items.len(); + let mut moves = Vec::new(); + match kind.as_str() { + "horizontally" | "vertically" => { + // Equal gaps between neighbours; the outermost layers stay put. + let v = kind == "vertically"; + let lo = |r: &Rect| if v { r.y0 } else { r.x0 } as i64; + let hi = |r: &Rect| if v { r.y1 } else { r.x1 } as i64; + items.sort_by_key(|(_, r)| (lo(r) + hi(r), lo(r))); + let span = hi(&items[n - 1].1) - lo(&items[0].1); + let total: i64 = items.iter().map(|(_, r)| hi(r) - lo(r)).sum(); + let gap = (span - total) as f64 / (n - 1) as f64; + let mut cursor = lo(&items[0].1) as f64; + for (id, r) in &items { + let want = cursor.round() as i64; + let d = (want - lo(r)) as i32; + moves.push(if v { (*id, 0, d) } else { (*id, d, 0) }); + cursor += (hi(r) - lo(r)) as f64 + gap; + } + } + k => { + let edge = Edge::parse(k).ok_or_else(|| bad("layer.distribute", format!("unknown kind `{k}`")))?; + items.sort_by_key(|(_, r)| edge.value2(r)); + let (first, last) = (edge.value2(&items[0].1) as f64, edge.value2(&items[n - 1].1) as f64); + for (i, (id, r)) in items.iter().enumerate() { + let want2 = first + (last - first) * i as f64 / (n - 1) as f64; + let d = ((want2 - edge.value2(r) as f64) / 2.0).round() as i32; + let (dx, dy) = edge.delta(d); + moves.push((*id, dx, dy)); + } + } + } + let moves: Vec<_> = moves.into_iter().flat_map(|(id, dx, dy)| with_links(doc, &[id]).into_iter().map(move |l| (l, dx, dy))).collect(); + let moves = dedup_moves(doc, moves); + move_layers(doc, &before, &moves)?; + Ok(moves.iter().filter(|m| m.1 != 0 || m.2 != 0).count()) + })?; + Ok(json!({"moved": moved})) +} diff --git a/crates/engine/src/layer_multi_cmds/damage.rs b/crates/engine/src/layer_multi_cmds/damage.rs new file mode 100644 index 0000000000..acc49ff88c --- /dev/null +++ b/crates/engine/src/layer_multi_cmds/damage.rs @@ -0,0 +1,517 @@ +use super::*; + +/// The document pixels an edit of the layers `ids` (moved, shown, hidden or restyled; contents +/// otherwise as they were) can have changed from `before` to `after`, or `None` for anywhere. +pub fn layers_damage(before: &Document, after: &Document, ids: &[LayerId]) -> Option { + let mut out = Rect::EMPTY; + for d in [before, after] { + let canvas = d.bounds(); + for id in ids { + // A layer gone from one side (never for a move) changes who knows what. + let (siblings, k, outer) = siblings_of(d, *id)?; + let b = photocraft_compose::change_bounds_in(siblings, k, outer, canvas)?; + if !b.is_empty() { + out = if out.is_empty() { b } else { out.union(&b) }; + } + } + } + Some(out) +} + +/// The sibling list holding layer `id` in `doc` (bottom→top), its index there, and the list +/// holding its parent group with the group's index (`None` at the top level). +type Siblings<'d> = (&'d [Layer], usize, Option<(&'d [Layer], usize)>); + +fn siblings_of(doc: &Document, id: LayerId) -> Option> { + let path = doc.path_of(id)?; + let (&k, parent) = path.split_last()?; + let Some((&g, grand)) = parent.split_last() else { return Some((doc.layers.as_slice(), k, None)) }; + let outer = if grand.is_empty() { doc.layers.as_slice() } else { doc.layer_at(grand)?.children()? }; + Some((outer.get(g)?.children()?, k, Some((outer, g)))) +} + +/// Report [`layers_damage`] as the active document's last change, so the canvas recomposites +/// only that (grown by the effect reach around it) instead of everything. +pub(crate) fn note_damage(s: &mut Session, before: &Document, ids: &[LayerId]) { + let Some(st) = s.active_mut() else { return }; + if before.size != st.doc.size { + return; + } + st.last_damage = layers_damage(before, &st.doc, ids); +} + +/// Whether two surfaces hold identical pixels: same format and default pixel, and the same +/// copy-on-write tile pointers at the same coordinates. Both documents stay alive during the +/// comparison, so tile addresses cannot be reused under it. +fn surfaces_equal(a: &photocraft_raster::Surface, b: &photocraft_raster::Surface) -> bool { + a.format() == b.format() + && a.default_pixel() == b.default_pixel() + && a.tile_count() == b.tile_count() + && a.tiles().zip(b.tiles()).all(|((ca, ta), (cb, tb))| ca == cb && std::sync::Arc::ptr_eq(ta, tb)) +} + +/// Byte blobs kept in `Arc`s (PSD raw blocks, embedded smart-object sources): pointer-identical +/// or content-equal (they are small compared to pixels, and undo steps rarely re-parse them). +fn blob_equal(x: &std::sync::Arc>, y: &std::sync::Arc>) -> bool { + std::sync::Arc::ptr_eq(x, y) || (x.len() == y.len() && x.as_slice() == y.as_slice()) +} + +fn blobs_equal(a: &Option>>, b: &Option>>) -> bool { + match (a, b) { + (None, None) => true, + (Some(x), Some(y)) => blob_equal(x, y), + _ => false, + } +} + +/// Layer masks (also the smart-filter mask): scalars plus tile-pointer surface identity. +fn masks_equal(a: &Option, b: &Option) -> bool { + match (a, b) { + (None, None) => true, + (Some(x), Some(y)) => { + x.enabled == y.enabled && x.linked == y.linked && x.density == y.density && x.feather == y.feather && surfaces_equal(&x.surface, &y.surface) + } + _ => false, + } +} + +fn texts_equal(a: &photocraft_doc::TextLayer, b: &photocraft_doc::TextLayer) -> bool { + a.text == b.text + && a.font_family == b.font_family + && a.size_pt == b.size_pt + && a.color == b.color + && a.transform == b.transform + && a.runs == b.runs + && a.paragraphs == b.paragraphs + && a.shape == b.shape + && a.orientation == b.orientation + && a.antialias == b.antialias + && a.warp == b.warp + && match (&a.cache, &b.cache) { + (None, None) => true, + (Some(x), Some(y)) => surfaces_equal(x, y), + _ => false, + } + && blobs_equal(&a.psd_raw, &b.psd_raw) +} + +fn smarts_equal(a: &photocraft_doc::SmartObject, b: &photocraft_doc::SmartObject) -> bool { + a.filters_enabled == b.filters_enabled + && a.transform == b.transform + && a.smart_filters == b.smart_filters + && a.stack_mode == b.stack_mode + && a.perspective == b.perspective + && a.warp == b.warp + && match (&a.source, &b.source) { + (photocraft_doc::SmartSource::Embedded { file_name: x, bytes: xb }, photocraft_doc::SmartSource::Embedded { file_name: y, bytes: yb }) => { + x == y && blob_equal(xb, yb) + } + (photocraft_doc::SmartSource::Linked { path: x }, photocraft_doc::SmartSource::Linked { path: y }) => x == y, + _ => false, + } + && match (&a.cache, &b.cache) { + (None, None) => true, + (Some(x), Some(y)) => surfaces_equal(x, y), + _ => false, + } + && blobs_equal(&a.psd_raw, &b.psd_raw) + && masks_equal(&a.filter_mask, &b.filter_mask) +} + +/// Extra alpha/spot channels (the image itself in Multichannel mode). +fn alpha_channels_equal(a: &photocraft_doc::AlphaChannel, b: &photocraft_doc::AlphaChannel) -> bool { + a.name == b.name && a.spot == b.spot && a.color == b.color && a.opacity == b.opacity && a.indicates == b.indicates && surfaces_equal(&a.surface, &b.surface) +} + +/// Whether two layers render to identical pixels in place. Everything the compositor reads is +/// compared structurally — no hashing, a hash collision would under-report damage; pixels are +/// identified by their copy-on-write tile pointers. Group children are deliberately *not* +/// compared here: the caller walks into them, so an edit inside a group damages only the +/// edited child's extent, not the whole group's. The destructure is exhaustive, so a new +/// `Layer` field fails to compile until it is classified: compared, or explicitly ignored +/// (name, locks, label, `psd_blocks`, `psd_id`, link group, XMP — none of them composite; video +/// bails out earlier in the walk). +fn layer_pixels_equal(a: &Layer, b: &Layer) -> bool { + let Layer { + id, + name: _, + visible, + locks: _, + blend, + opacity, + fill_opacity, + clipped, + mask, + vector_mask, + effects, + label: _, + content, + psd_blocks: _, + psd_id: _, + fill_cache, + link_group: _, + excluded_channels, + blend_if, + advanced, + video: _, + xmp: _, + } = a; + *id == b.id + && *visible == b.visible + && *blend == b.blend + && *opacity == b.opacity + && *fill_opacity == b.fill_opacity + && *clipped == b.clipped + && masks_equal(mask, &b.mask) + && *vector_mask == b.vector_mask + && *effects == b.effects + && *excluded_channels == b.excluded_channels + && *blend_if == b.blend_if + && *advanced == b.advanced + && match (content, &b.content) { + (LayerContent::Raster(x), LayerContent::Raster(y)) => surfaces_equal(x, y), + // Children are walked separately; only the group's own clipping frame counts. + (LayerContent::Group(x), LayerContent::Group(y)) => x.artboard == y.artboard, + (LayerContent::Fill(x), LayerContent::Fill(y)) => x == y, + (LayerContent::Adjustment(x), LayerContent::Adjustment(y)) => x == y, + (LayerContent::Text(x), LayerContent::Text(y)) => texts_equal(x, y), + (LayerContent::Shape(x), LayerContent::Shape(y)) => x == y, + (LayerContent::Smart(x), LayerContent::Smart(y)) => smarts_equal(x, y), + _ => false, + } + && match (fill_cache, &b.fill_cache) { + (None, None) => true, + (Some(x), Some(y)) => x.fill == y.fill && surfaces_equal(&x.surface, &y.surface), + _ => false, + } +} + +/// Document-level fields the compositor reads: all must match for a bounded damage claim. The +/// destructure is exhaustive, so a new `Document` field fails to compile until it is classified +/// here — compared when it composites, or explicitly ignored (the pixel-irrelevant allowlist: +/// identity, name, selection, guides, paths, layer comps, annotations, automation state). +fn doc_pixels_equal(a: &Document, b: &Document) -> bool { + let Document { + id: _, + name: _, + size, + resolution_dpi, + mode, + depth, + icc_profile, + layers: _, + channels, + guides: _, + ruler_origin: _, + selection: _, + metadata: _, + global_light, + paths: _, + work_path: _, + clipping_path: _, + quick_mask, + quick_mask_unselected: _, + patterns, + color_table, + duotone, + layer_comps: _, + last_applied_comp: _, + last_document_state: _, + measurement: _, + notes: _, + text_styles: _, + slices: _, + variables: _, + timeline: _, + file_encoding: _, + } = a; + *size == b.size + && resolution_dpi.to_bits() == b.resolution_dpi.to_bits() + && *mode == b.mode + && *depth == b.depth + && icc_profile.as_deref() == b.icc_profile.as_deref() + && channels.len() == b.channels.len() + && channels.iter().zip(&b.channels).all(|(x, y)| alpha_channels_equal(x, y)) + && *global_light == b.global_light + && match (quick_mask, &b.quick_mask) { + (None, None) => true, + (Some(x), Some(y)) => alpha_channels_equal(x, y), + _ => false, + } + && *patterns == b.patterns + && *color_table == b.color_table + && *duotone == b.duotone +} + +/// 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. +/// Conservative (`false`) past a nesting depth no real document reaches. +pub fn same_pixels(a: &Document, b: &Document) -> bool { + pixels_equal_with(a, b, |_, _| false) +} + +/// [`same_pixels`], with video layers equal when `video_equal` says their frame stacks are. +fn pixels_equal_with(a: &Document, b: &Document, video_equal: fn(&VideoData, &VideoData) -> bool) -> bool { + fn walk(xs: &[Layer], ys: &[Layer], depth: usize, video_equal: fn(&VideoData, &VideoData) -> bool) -> bool { + depth < 256 + && xs.len() == ys.len() + && xs.iter().zip(ys).all(|(x, y)| { + layer_pixels_equal(x, y) + && match (&x.video, &y.video) { + (None, None) => true, + (Some(vx), Some(vy)) => video_equal(vx, vy), + _ => false, + } + && match (x.children(), y.children()) { + (Some(xc), Some(yc)) => walk(xc, yc, depth + 1, video_equal), + (None, None) => true, + _ => false, + } + }) + } + doc_pixels_equal(a, b) && walk(&a.layers, &b.layers, 0, video_equal) +} + +/// Whether two video layers hold the same frames: the same settings and stack shape +/// (`VideoData`'s own, shallow equality) and the same tile pointers in every frame, painted and +/// original. Pointer compares only, like [`surfaces_equal`]. +fn video_frames_equal(a: &VideoData, b: &VideoData) -> bool { + let frames = |x: &[photocraft_raster::Surface], y: &[photocraft_raster::Surface]| x.len() == y.len() && x.iter().zip(y).all(|(f, g)| surfaces_equal(f, g)); + *a == *b + && frames(&a.frames, &b.frames) + && match (&a.original_frames, &b.original_frames) { + (Some(x), Some(y)) => frames(x, y), + (None, None) => true, + _ => false, + } +} + +/// Whether `a` and `b` differ at most in their selection (#6865): a selection step, which must +/// not mark a clean document modified. Pixels compare by tile pointer (as in [`same_pixels`], +/// plus every frame of a video layer, whose own equality is shallow); every other field compares +/// structurally, where copy-on-write `Arc`s of `Eq` data short-circuit on pointer identity. The +/// destructure is exhaustive, so a new `Document` field fails to compile until it is classified. +pub fn selection_only_change(a: &Document, b: &Document) -> bool { + let Document { + id, + name, + size: _, + resolution_dpi: _, + mode: _, + depth: _, + icc_profile: _, + layers, + channels: _, + guides, + ruler_origin, + selection: _, + metadata, + global_light: _, + paths, + work_path, + clipping_path, + quick_mask: _, + quick_mask_unselected, + patterns: _, + color_table: _, + duotone: _, + layer_comps, + last_applied_comp, + last_document_state, + measurement, + notes, + text_styles, + slices, + variables, + timeline, + file_encoding, + } = a; + // The ignored fields above are the pixel ones `pixels_equal_with` already compares. + pixels_equal_with(a, b, video_frames_equal) + && *id == b.id + && *name == b.name + && *layers == b.layers + && *guides == b.guides + && *ruler_origin == b.ruler_origin + && *metadata == b.metadata + && *paths == b.paths + && *work_path == b.work_path + && *clipping_path == b.clipping_path + && *quick_mask_unselected == b.quick_mask_unselected + && *layer_comps == b.layer_comps + && *last_applied_comp == b.last_applied_comp + && *last_document_state == b.last_document_state + && *measurement == b.measurement + && *notes == b.notes + && *text_styles == b.text_styles + && *slices == b.slices + && *variables == b.variables + && *timeline == b.timeline + && *file_encoding == b.file_encoding +} + +/// Pixels a single history step can have changed between `a` and `b` (the documents on either +/// side of an edit, its undo or its redo): the union of the change bounds of every layer whose +/// pixels differ, so a local edit recomposites only that area instead of the whole canvas. A +/// layer only one side has (a duplicate, a paste, a deleted layer) counts where it draws (see +/// [`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 +/// 12 MP layer used to recomposite every layer of the document (#2883, P8/P9 in +/// `perf/budgets.toml`). +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)>; + fn walk(xs: &[Layer], ys: &[Layer], (ox, oy): (Outer, Outer), a: &Document, b: &Document, out: &mut Rect) -> bool { + // 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) }; + } + true + }; + 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), + _ if inert_at(ys, j) => { + j += 1; + continue; + } + _ if inert_at(xs, i) => { + i += 1; + continue; + } + (_, Some(y)) if xs.iter().all(|x| x.id != y.id) => { + if !one_sided(ys, j, oy, 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) { + return false; + } + i += 1; + continue; + } + // Both sides have the layer, in another order. + _ => return false, + }; + let (xk, yk) = (i, j); + i += 1; + j += 1; + 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 { + return false; + } + if !layer_pixels_equal(x, y) { + // 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 { + return false; + }; + *out = if out.is_empty() { bx.union(&by) } else { out.union(&bx).union(&by) }; + } + match (x.children(), y.children()) { + (Some(xc), Some(yc)) => { + if !walk(xc, yc, (Some((xs, xk)), Some((ys, yk))), a, b, out) { + return false; + } + } + (None, None) => {} + _ => return false, + } + } + } + let mut out = Rect::EMPTY; + if walk(&a.layers, &b.layers, (None, None), a, b, &mut out) { Some(out) } else { None } +} + +/// 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 +/// 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))) + } + 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) +} + +/// Whether `layers[k]` draws nothing wherever it sits, so adding or removing it leaves the +/// composite as it was: an empty pixel layer (no tiles, transparent default) or an empty group, +/// in a Normal or Pass Through blend with no mask, vector mask, effects or Advanced Blending. +/// A clipping base that would gain or lose the clipped layers above it is not inert. +fn inert_at(layers: &[Layer], k: usize) -> bool { + let Some(l) = layers.get(k) else { return false }; + let empty = match &l.content { + LayerContent::Raster(s) => s.tile_count() == 0 && s.format().alpha && s.default_bytes().iter().all(|b| *b == 0), + LayerContent::Group(g) => g.children.is_empty() && g.artboard.is_none(), + _ => false, + }; + empty + && matches!(l.blend, photocraft_doc::BlendMode::Normal | photocraft_doc::BlendMode::PassThrough) + && l.mask.is_none() + && l.vector_mask.is_none() + && !photocraft_compose::effects::has_effects(l) + && l.fill_cache.is_none() + && l.video.is_none() + && l.advanced == photocraft_doc::AdvancedBlending::default() + && (l.clipped || layers.get(k + 1).is_none_or(|above| !above.clipped)) +} + +/// Report that adding layer `id` to the active document changed no pixels when it draws +/// nothing ([`inert_at`]), so the canvas doesn't recomposite every layer for it (#1771). Looks +/// only at the new layer and its neighbour, never at other layers' tiles. +pub(crate) fn note_inert_insert(s: &mut Session, id: LayerId) { + let Some(st) = s.active_mut() else { return }; + let Some(path) = st.doc.path_of(id) else { return }; + let Some((&k, parent)) = path.split_last() else { return }; + let siblings = if parent.is_empty() { Some(st.doc.layers.as_slice()) } else { st.doc.layer_at(parent).and_then(Layer::children) }; + if siblings.is_some_and(|sib| inert_at(sib, k)) { + st.last_damage = Some(Rect::EMPTY); + } +} + +/// 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); +} + +/// Content bounds used by Align/Distribute: the layer's pixels (type and shape layers use their +/// rendered pixels), or the union of a group's children. Fill and adjustment layers have none. +pub fn layer_bounds(l: &Layer) -> Option { + let r = match &l.content { + LayerContent::Group(g) => g.children.iter().filter_map(layer_bounds).fold(Rect::EMPTY, |a, b| a.union(&b)), + _ => l.surface().map(|s| s.content_bounds()).unwrap_or(Rect::EMPTY), + }; + (!r.is_empty()).then_some(r) +} diff --git a/crates/engine/src/layer_multi_cmds/moves.rs b/crates/engine/src/layer_multi_cmds/moves.rs new file mode 100644 index 0000000000..a8f4a04918 --- /dev/null +++ b/crates/engine/src/layer_multi_cmds/moves.rs @@ -0,0 +1,428 @@ +use super::damage::note_damage; +use super::selection::{reselect, same_named_targets, selected, top_level}; +use super::structure::check_group_depth; +use super::*; + +/// A Layers-panel drag of the selected layer records its drop target by name (and which of +/// several same-named layers it is), as [`recorded_selection`] does: the id means nothing in the +/// document the action plays in later, so playback failed with "no such layer" (#7845). Drags of +/// several layers, or of a layer that isn't the selected one, keep their ids. +pub(super) fn recorded_move(s: &Session, mut p: Value, pre_selected: Option<&[LayerId]>) -> Value { + if p.get("layers").is_some() { + return p; + } + let Some(st) = s.active() else { return p }; + let moved = match p.get("layer") { + None => st.active_layer, + Some(v) => match v.as_u64().map(LayerId) { + Some(id) if pre_selected.map_or_else(|| st.selected_layers().as_slice() == [id], |sel| sel == [id]) => Some(id), + _ => return p, + }, + }; + if let Some(fields) = p.as_object_mut() { + fields.remove("layer"); + } + let Some(id) = p.get("target").and_then(Value::as_u64).map(LayerId) else { return p }; + let Some(layer) = st.doc.layer(id) else { return p }; + // A copy leaves its source where it is (it may even land beside it), so the source stays a + // candidate; the new copy (the active layer once the step has run, which is when it is + // recorded) is left out instead, as it doesn't exist yet when the step replays. + let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); + let skip = if copy { st.active_layer.filter(|a| Some(*a) != moved) } else { moved }; + let matches = same_named_targets(&st.doc, &layer.name, skip.as_slice()); + let Some(occurrence) = matches.iter().position(|candidate| *candidate == id) else { return p }; + if let Some(fields) = p.as_object_mut() { + fields.insert("target".into(), json!(layer.name)); + if matches.len() > 1 { + fields.insert("targetOccurrence".into(), json!(occurrence)); + } + } + p +} + +/// `layer.moveTo`'s drop target: an id, or a name with `targetOccurrence` choosing among layers +/// that share it (in document order, the `moved` layers aside; required when several do). +fn move_target(s: &Session, p: &Value, moved: &[LayerId]) -> Result { + const CMD: &str = "layer.moveTo"; + match p.get("target") { + Some(Value::String(name)) => { + let occurrence = p + .get("targetOccurrence") + .map(|v| v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(CMD, "`targetOccurrence` must be a non-negative integer"))) + .transpose()?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let matches = same_named_targets(&st.doc, name, moved); + if matches.len() > 1 && occurrence.is_none() { + return Err(bad(CMD, format!("multiple layers named `{name}`; specify `targetOccurrence`"))); + } + let index = occurrence.unwrap_or(0); + matches.get(index).copied().ok_or_else(|| bad(CMD, format!("no layer named `{name}` at occurrence {index}"))) + } + Some(v) => v.as_u64().map(LayerId).ok_or_else(|| bad(CMD, "`target` must be a layer id or name")), + None => Err(bad(CMD, "missing `target`")), + } +} + +// ---------- moving layers ---------- + +pub(super) fn link_groups(doc: &Document, ids: &[LayerId]) -> Vec { + let mut g: Vec = ids.iter().filter_map(|id| doc.layer(*id)?.link_group).collect(); + g.sort_unstable(); + g.dedup(); + g +} + +/// `ids` plus every layer linked to one of them. +pub(crate) fn with_links(doc: &Document, ids: &[LayerId]) -> Vec { + let groups = link_groups(doc, ids); + let mut out = ids.to_vec(); + if !groups.is_empty() { + for (_, _, l) in doc.walk() { + if l.link_group.is_some_and(|g| groups.contains(&g)) && !out.contains(&l.id) { + out.push(l.id); + } + } + } + out +} + +/// Move layers by whole pixels the way the Move tool does: pixels, linked masks, type and +/// vector content (shapes, linked vector masks) all move together. `before` is `doc` as it was +/// before any of the moves (the edit's starting document), read when type and shapes re-render. +pub(crate) fn move_layers(doc: &mut Document, before: &Document, moves: &[(LayerId, i32, i32)]) -> Result<()> { + for &(id, dx, dy) in moves { + if dx == 0 && dy == 0 { + continue; + } + let locks = doc.effective_locks(id); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if locks.position || locks.all { + return Err(EngineError::Other(format!("layer \"{}\" is position-locked", l.name))); + } + crate::commands::translate_layer(before, l, dx, dy); + crate::vector_cmds::translate_vectors(before, l, dx as f64, dy as f64); + } + Ok(()) +} + +/// Does a move aimed at the layer mask (`"target":"mask"`) move `l`'s mask alone? Only an +/// unlinked mask does (the chain off); a linked one moves with its layer, as in Photoshop. +pub fn moves_mask_alone(l: &Layer) -> bool { + l.mask.as_ref().is_some_and(|m| !m.linked) +} + +/// `layer.translate`: the explicit layer, or every selected layer, plus their linked layers. +/// With `"target":"mask"` a layer whose mask is unlinked moves that mask alone. +pub fn translate(s: &mut Session, p: &Value) -> Result { + let (dx, dy) = match p.get("units").and_then(Value::as_str) { + None | Some("px") => (int_i32("layer.translate", p, "dx")?.unwrap_or(0), int_i32("layer.translate", p, "dy")?.unwrap_or(0)), + // Points (1/72 in), as a Photoshop action records a nudge: whole pixels at this + // document's resolution. + Some("pt") => { + let dpi = s.active().map_or(72.0, |d| f64::from(d.doc.resolution_dpi)); + let to_px = |key: &str| -> Result { + let pt = match p.get(key) { + None => 0.0, + Some(v) => v.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad("layer.translate", format!("`{key}` must be a number")))?, + }; + let px = (pt * dpi / 72.0).round(); + if px.abs() > f64::from(i32::MAX) { + return Err(bad("layer.translate", format!("`{key}` = {pt} pt is outside the 32-bit coordinate range"))); + } + Ok(px as i32) + }; + (to_px("dx")?, to_px("dy")?) + } + Some(other) => return Err(bad("layer.translate", format!("unknown units `{other}` (px|pt)"))), + }; + let carry = match p.get("selection") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad("layer.translate", "`selection` must be a boolean"))?, + }; + if dx == 0 && dy == 0 { + return Ok(Value::Null); + } + let roots = match crate::commands::explicit_layer(s, p)? { + Some(id) => vec![id], + None => selected(s), + }; + if roots.is_empty() { + return Err(EngineError::Other("no active layer".into())); + } + let mask_target = p.get("target").and_then(Value::as_str) == Some("mask"); + let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); + let ids = 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); + if ids.is_empty() && alone.is_empty() { + return Err(EngineError::NoLayer(roots[0])); + } + let moves: Vec<_> = ids.iter().map(|&id| (id, dx, dy)).collect(); + move_layers(doc, &before, &moves)?; + for id in alone { + let locks = doc.effective_locks(id); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if locks.position || locks.all { + return Err(EngineError::Other(format!("layer \"{}\" is position-locked", l.name))); + } + if let Some(m) = &mut l.mask { + m.surface = shift_surface(&m.surface, dx, dy); + } + ids.push(id); + } + // 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); + } + // The Move tool carries the selection along when it moves several layers whole, as + // Photoshop does (#7538): one step, so Undo takes both back. + if carry { + doc.selection = doc.selection.as_ref().map(|sel| shift_surface(sel, dx, dy)); + } + Ok(ids) + })?; + note_damage(s, &before, &ids); + Ok(Value::Null) +} + +/// The layers a move of `roots` takes along: their linked layers, without layers whose group +/// is also moving (the group carries them). +pub fn move_targets(doc: &Document, roots: &[LayerId]) -> Vec { + top_level(doc, &with_links(doc, roots)) +} + +/// `doc` with the layers `ids` ([`move_targets`]) moved by whole pixels, as `layer.translate` +/// leaves them: the Move tool's live preview while it drags. Type, shape and smart-object pixels +/// shift as they are instead of re-rendering (the commit re-renders them), so a drag frame costs +/// copying the moving pixels only. +pub fn moved(doc: &Document, ids: &[LayerId], dx: i32, dy: i32) -> Result { + moved_target(doc, ids, dx, dy, false) +} + +/// [`moved`] for a drag aimed at the layer mask (`mask_target`): unlinked masks move alone. +pub fn moved_target(doc: &Document, ids: &[LayerId], dx: i32, dy: i32, mask_target: bool) -> Result { + let mut out = doc.clone(); + for &id in ids { + let locks = doc.effective_locks(id); + let l = out.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + if locks.position || locks.all { + return Err(EngineError::Other(format!("layer \"{}\" is position-locked", l.name))); + } + if mask_target && moves_mask_alone(l) { + if let Some(m) = &mut l.mask { + m.surface = shift_surface(&m.surface, dx, dy); + } + continue; + } + shift_shown(doc, l, dx, dy); + } + Ok(out) +} + +/// `photocraft_algo::resample::translate_surface` with the content scan cached per tile (a Move +/// drag shifts the same layers every frame; scanning them each time cost more than the copy). +pub(crate) fn shift_surface(s: &photocraft_raster::Surface, dx: i32, dy: i32) -> photocraft_raster::Surface { + s.translated(dx, dy, photocraft_compose::bounds::content_bounds(s)) +} + +/// [`crate::commands::translate_layer`] plus the vector side, without re-rendering anything. +fn shift_shown(doc: &Document, l: &mut Layer, dx: i32, dy: i32) { + use self::shift_surface as translate_surface; + let a = photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy)); + if let Some(r) = &mut l.effects.reference { + *r = (r.0 + f64::from(dx), r.1 + f64::from(dy)); + } + if let Some(m) = l.mask.as_mut().filter(|m| m.linked) { + m.surface = translate_surface(&m.surface, dx, dy); + } + if let Some(vm) = l.vector_mask.as_mut().filter(|v| v.linked) { + vm.path = vm.path.transform(&a); + } + match &mut l.content { + LayerContent::Raster(s) => *s = translate_surface(s, dx, dy), + LayerContent::Text(t) => { + t.transform = a.mul(&t.transform); + if let Some(c) = &mut t.cache { + *c = translate_surface(c, dx, dy); + } + } + LayerContent::Shape(sh) => crate::vector_cmds::shift_shape(doc, sh, f64::from(dx), f64::from(dy)), + LayerContent::Smart(sm) => crate::smart_cmds::shift_smart(sm, dx, dy), + LayerContent::Group(g) => { + if let Some(ab) = &mut g.artboard { + ab.rect = ab.rect.translate(dx, dy); + } + g.children.iter_mut().for_each(|c| shift_shown(doc, c, dx, dy)); + } + LayerContent::Adjustment(_) | LayerContent::Fill(_) => {} + } +} + +/// Reorder one or multiple layers to a single destination in one undoable edit. +/// +/// Explicit `layers` are ordered according to the source document, not caller ordering. +/// A transient snapshot for the Layers panel's "Preview on canvas when reordering layers". +/// Uses the same source ordering and insertion semantics as `move_to`, but never edits history. +/// Invalid/self-referential hover targets return None (the committed image stays visible). +pub fn preview_move(doc: &Document, p: &Value, add_copy: bool) -> Option { + let target = LayerId(p.get("target")?.as_u64()?); + let position = p.get("position")?.as_str()?; + if !matches!(position, "above" | "below" | "into") { + return None; + } + let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); + let ids = if let Some(ids) = p.get("layers") { + ids.as_array()?.iter().map(|v| v.as_u64().map(LayerId)).collect::>>()? + } else { + vec![LayerId(p.get("layer")?.as_u64()?)] + }; + if ids.is_empty() || doc.layer(target).is_none() { + return None; + } + let moved_ids = top_level(doc, &ids); + if moved_ids.is_empty() || moved_ids.iter().any(|id| doc.layer(*id).is_none()) { + return None; + } + if moved_ids.len() == 1 && moved_ids[0] == target && !copy { + return None; + } + let target_path = doc.path_of(target)?; + for id in &moved_ids { + let path = doc.path_of(*id)?; + if target_path.starts_with(&path) && !(copy && *id == target && position != "into") { + return None; + } + } + if position == "into" && !doc.layer(target)?.is_group() { + return None; + } + // The very structural move the drop commits, so the preview shows the same clip groups, + // Background handling and group-depth refusals; a drop `move_to` would refuse has no preview. + let mut preview = doc.clone(); + apply_move(&mut preview, &moved_ids, target, position, copy, add_copy).ok()?; + Some(preview) +} + +/// The document-only part of `move_to`, shared with [`preview_move`] so the Layers panel's hover +/// preview cannot drift from what the drop commits. Moves (or, with `copy`, duplicates) the +/// top-level `moved_ids` to `pos` (`above`, `below` or `into`) `target`, then applies the +/// group-depth cap, the Background-stays-at-the-bottom rule and the clip-group rules +/// (`clip_group::settle`). Returns the ids of the new copies (empty for a move). On `Err` `doc` is +/// half edited: run it inside `Session::edit` or on a scratch copy. +fn apply_move(doc: &mut Document, moved_ids: &[LayerId], target: LayerId, pos: &str, copy: bool, add_copy: bool) -> Result> { + const CMD: &str = "layer.moveTo"; + let background = crate::background_cmds::background_id(doc); + let before = if copy { Default::default() } else { crate::clip_group::Before::read(doc, moved_ids) }; + let mut moved = Vec::with_capacity(moved_ids.len()); + for &id in moved_ids { + moved.push(if copy { crate::commands::layer_copy(doc, id, add_copy)? } else { doc.remove(id).ok_or(EngineError::NoLayer(id))? }); + } + let copies: Vec = if copy { moved.iter().map(|l| l.id).collect() } else { Vec::new() }; + // Look up the destination AFTER removing every source: its indices may have shifted. + let path = doc.path_of(target).ok_or(EngineError::NoLayer(target))?; + if pos == "into" { + let children = doc.layer_at_mut(&path).and_then(Layer::children_mut).ok_or_else(|| bad(CMD, "target is not a group"))?; + children.extend(moved); + } else { + let (&idx, parent) = path.split_last().ok_or(EngineError::NoLayer(target))?; + let siblings = if parent.is_empty() { + &mut doc.layers + } else { + doc.layer_at_mut(parent).and_then(Layer::children_mut).ok_or_else(|| bad(CMD, "target's parent is not a group"))? + }; + let at = if pos == "below" { idx } else { idx + 1 }; + siblings.splice(at..at, moved); + } + check_group_depth(doc, "Reorder Layer")?; + crate::background_cmds::keep_background_at_bottom(background, doc)?; + crate::clip_group::settle(doc, if copy { &copies } else { moved_ids }, &before, false); + Ok(copies) +} + +/// Selected descendants of a moved group remain inside their parent; only top-level +/// selected nodes are detached, and every reference is validated before editing. +pub fn move_to(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "layer.moveTo"; + let pos = p.get("position").and_then(Value::as_str).unwrap_or("above"); + if !matches!(pos, "above" | "below" | "into") { + return Err(bad(CMD, "position must be above, below, or into")); + } + // ⌥-drag in the Layers panel: duplicates land at the target and the layers stay put. + let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); + + let batch = p.get("layers"); + if batch.is_some() && p.get("layer").is_some() { + return Err(bad(CMD, "give either `layer` or `layers`, not both")); + } + let requested = if let Some(raw) = batch { + let arr = raw.as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad(CMD, "`layers` must be a nonempty array of ids"))?; + let mut ids = Vec::with_capacity(arr.len()); + for item in arr { + let id = LayerId(item.as_u64().ok_or_else(|| bad(CMD, "every layer id must be an unsigned integer"))?); + if ids.contains(&id) { + return Err(bad(CMD, "duplicate layer id")); + } + ids.push(id); + } + ids + } else { + vec![crate::commands::layer_param(s, p)?] + }; + // A copy moves nothing, so its source stays a candidate (⌥-dragging a layer beside itself). + let target = move_target(s, p, if copy { &[] } else { &requested })?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let doc = &st.doc; + let target_path = doc.path_of(target).ok_or(EngineError::NoLayer(target))?; + for &id in &requested { + if doc.layer(id).is_none() { + return Err(EngineError::NoLayer(id)); + } + } + let moved_ids = top_level(doc, &requested); + if moved_ids.len() == 1 && moved_ids[0] == target && batch.is_none() && !copy { + // Preserve single-layer drag-to-self semantics. + return Ok(Value::Null); + } + // Also rejects dragging a selected group onto any of its descendants. + for id in &moved_ids { + let path = doc.path_of(*id).ok_or(EngineError::NoLayer(*id))?; + // A copy may land beside its own source (not inside it). + let beside_itself = copy && *id == target && pos != "into"; + if target_path.starts_with(&path) && !beside_itself { + return Err(bad(CMD, "target cannot be one of the moved layers or its descendant")); + } + } + if pos == "into" && doc.layer(target).is_none_or(|l| !l.is_group()) { + return Err(bad(CMD, "target is not a group")); + } + + let original_active = st.active_layer; + let add_copy = crate::commands::layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true); + let (count, copies) = s.edit(if copy { "Duplicate Layer" } else { "Reorder Layers" }, |doc, active| { + let copies = apply_move(doc, &moved_ids, target, pos, copy, add_copy)?; + *active = if copy { + copies.last().copied() + } else if batch.is_some() { + original_active.filter(|id| requested.contains(id)).or_else(|| requested.last().copied()) + } else { + moved_ids.first().copied() + }; + Ok((moved_ids.len(), copies)) + })?; + if copy { + let ids: Vec = copies.iter().map(|id| id.0).collect(); + if batch.is_some() { + let active = copies.last().copied(); + reselect(s, copies, active); + return Ok(json!({"moved": count, "layers": ids})); + } + return Ok(json!({"layer": ids.first()})); + } + if batch.is_some() { + let active = original_active.filter(|id| requested.contains(id)).or_else(|| requested.last().copied()); + reselect(s, requested, active); + Ok(json!({"moved": count})) + } else { + Ok(Value::Null) + } +} diff --git a/crates/engine/src/layer_multi_cmds/selection.rs b/crates/engine/src/layer_multi_cmds/selection.rs new file mode 100644 index 0000000000..9400760c8e --- /dev/null +++ b/crates/engine/src/layer_multi_cmds/selection.rs @@ -0,0 +1,285 @@ +use super::moves::{link_groups, recorded_move}; +use super::*; + +// ---------- selection state ---------- + +pub(super) fn doc_state(s: &Session) -> std::result::Result<&DocState, String> { + s.active().ok_or_else(|| "no document open".into()) +} + +/// Selected layers of the active document, bottom-to-top. +pub fn selected(s: &Session) -> Vec { + s.active().map(DocState::selected_layers).unwrap_or_default() +} + +/// The layers a layer command acts on: the `layer` param when given, else every selected layer +/// (bottom-to-top), else the active layer. A single layer behaves exactly as before. +pub(crate) fn targets(s: &Session, p: &serde_json::Value) -> Result> { + if p.get("layer").is_some() { + return Ok(vec![crate::commands::layer_param(s, p)?]); + } + match selected(s) { + sel if sel.is_empty() => Ok(vec![crate::commands::layer_param(s, p)?]), + sel => Ok(sel), + } +} + +/// [`targets`] for a command that adds a layer mask: with several layers selected, those that can +/// take one (no layer mask yet, not the Background); one layer is taken as given. +pub(crate) fn mask_targets(s: &Session, p: &serde_json::Value) -> Result> { + let ids = targets(s, p)?; + if ids.len() < 2 { + return Ok(ids); + } + let d = s.active().ok_or(EngineError::NoDocument)?; + let ids: Vec = ids.into_iter().filter(|id| d.doc.layer(*id).is_some_and(|l| l.mask.is_none() && !d.doc.is_background(l.id))).collect(); + if ids.is_empty() { + return Err(EngineError::Other("none of the selected layers can take a layer mask".into())); + } + Ok(ids) +} + +/// Ids in `ids` that have no ancestor also in `ids` (a selected group already carries its +/// selected children), bottom-to-top. +pub(crate) fn top_level(doc: &Document, ids: &[LayerId]) -> Vec { + let walk = doc.walk(); + let paths: Vec<_> = walk.iter().filter(|(_, _, l)| ids.contains(&l.id)).map(|(p, _, l)| (p.clone(), l.id)).collect(); + paths.iter().filter(|(p, _)| !paths.iter().any(|(q, _)| q.len() < p.len() && p.starts_with(q))).map(|(_, id)| *id).collect() +} + +/// Replace the layer selection without a history step (like [`Session::select_layer`]). +pub fn set_selection(s: &mut Session, ids: Vec, active: Option, anchor: Option) -> Result<()> { + let st = s.active_mut().ok_or(EngineError::NoDocument)?; + if let Some(bad) = ids.iter().chain(active.iter()).find(|id| st.doc.layer(**id).is_none()) { + return Err(EngineError::NoLayer(*bad)); + } + let active = active.or_else(|| ids.last().copied()); + st.selected_layers = ids; + if let Some(a) = active + && !st.selected_layers.contains(&a) + { + st.selected_layers.push(a); + } + st.active_layer = active; + st.layer_anchor = anchor.or(active); + crate::fix_selection(st); + // Selecting layers is not an edit: keep a clean document clean. + let clean = st.saved_revision == st.revision; + st.revision += 1; + if clean { + st.saved_revision = st.revision; + } + st.last_damage = Some(Rect::EMPTY); + Ok(()) +} + +/// After a structural edit, make `ids` the selection (dropping any that no longer exist), which +/// is also what the edit's history state targets. +pub(crate) fn reselect(s: &mut Session, ids: Vec, active: Option) { + if let Some(st) = s.active_mut() { + st.selected_layers = ids; + if let Some(a) = active { + st.active_layer = Some(a); + st.layer_anchor = Some(a); + } + crate::fix_selection(st); + let layers = st.layer_target(); + st.history.set_current_layers(layers); + } +} + +/// Capture a selection target while its name is still known. Later renames/deletions must not +/// change an earlier recorded selection. Direct, non-recording calls retain their numeric IDs. +pub(crate) fn recorded_selection(s: &Session, mut p: Value) -> Value { + let Some(id) = p.get("layer").and_then(Value::as_u64).map(LayerId) else { return p }; + let Some(st) = s.active() else { return p }; + let Some(layer) = st.doc.layer(id) else { return p }; + let matches: Vec<_> = st.doc.walk().into_iter().filter(|(_, _, l)| l.name == layer.name).map(|(_, _, l)| l.id).collect(); + let Some(occurrence) = matches.iter().position(|candidate| *candidate == id) else { return p }; + if let Some(fields) = p.as_object_mut() { + fields.remove("layer"); + fields.insert("name".into(), json!(layer.name)); + if matches.len() > 1 { + fields.insert("occurrence".into(), json!(occurrence)); + } + } + p +} + +/// The layers named `name`, in document order, other than the ones being moved and (groups) their +/// contents. Moving layers never changes the others' order, so an occurrence counted among these +/// means the same layer before the move (when an action replays it) and after it (when the step +/// is recorded). +pub(super) fn same_named_targets(doc: &photocraft_doc::Document, name: &str, moved: &[LayerId]) -> Vec { + fn subtree(l: &Layer, out: &mut Vec, depth: usize) { + out.push(l.id); + if depth < 256 + && let Some(children) = l.children() + { + children.iter().for_each(|c| subtree(c, out, depth + 1)); + } + } + let mut skip = Vec::new(); + for l in moved.iter().filter_map(|id| doc.layer(*id)) { + subtree(l, &mut skip, 0); + } + doc.walk().into_iter().filter(|(_, _, l)| l.name == name && !skip.contains(&l.id)).map(|(_, _, l)| l.id).collect() +} + +/// Normalise parameters when recording an action step. +/// +/// For `layer.select`, captures the layer by name. For other commands, if a numeric `layer` +/// parameter references the document's sole selected layer, normalises it to the target form +/// (omitting `layer`) so that the recorded step applies to whatever layer is targeted when +/// replayed or exported to `.atn` (#7248). +pub(crate) fn recorded_step(s: &Session, id: &str, p: Value, pre_selected: Option<&[LayerId]>) -> Value { + if id == "layer.select" { + return recorded_selection(s, p); + } + if id == "layer.moveTo" { + return recorded_move(s, p, pre_selected); + } + let Some(layer_id) = p.get("layer").and_then(Value::as_u64).map(LayerId) else { return p }; + let is_sole_selected = match pre_selected { + Some(sel) => sel == [layer_id], + None => s.active().is_some_and(|st| st.selected_layers().as_slice() == [layer_id]), + }; + if is_sole_selected { + let mut p = p; + if let Some(fields) = p.as_object_mut() { + fields.remove("layer"); + } + return p; + } + p +} + +fn selection_target(s: &Session, p: &Value) -> Result { + let Some(name) = p.get("name") else { + if p.get("occurrence").is_some() { + return Err(bad("layer.select", "`occurrence` requires `name`")); + } + return crate::commands::explicit_layer(s, p)?.ok_or_else(|| bad("layer.select", "needs `layer` or `name`")); + }; + if p.get("layer").is_some() { + return Err(bad("layer.select", "use either `layer` or `name`, not both")); + } + let name = name.as_str().ok_or_else(|| bad("layer.select", "`name` must be a string"))?; + let occurrence = p + .get("occurrence") + .map(|v| v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad("layer.select", "`occurrence` must be a non-negative integer"))) + .transpose()?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let matches: Vec<_> = st.doc.walk().into_iter().filter(|(_, _, l)| l.name == name).map(|(_, _, l)| l.id).collect(); + if matches.len() > 1 && occurrence.is_none() { + return Err(bad("layer.select", format!("multiple layers named `{name}`; specify `occurrence`"))); + } + let index = occurrence.unwrap_or(0); + matches.get(index).copied().ok_or_else(|| bad("layer.select", format!("no layer named `{name}` at occurrence {index}"))) +} + +/// Layer rows follow the Layers panel's visual order, not Document::walk's storage order. +/// Closed groups hide their children unless both endpoints were selected programmatically. +fn range_order(layers: &[Layer], include_collapsed: bool, out: &mut Vec) { + for layer in layers.iter().rev() { + out.push(layer.id); + if let LayerContent::Group(group) = &layer.content + && (group.expanded || include_collapsed) + { + range_order(&group.children, include_collapsed, out); + } + } +} + +/// `layer.select`: `{"layer": id, "mode": "replace|toggle|range|add|remove"}`. +pub fn select(s: &mut Session, p: &Value) -> Result { + let id = selection_target(s, p)?; + let mode = p.get("mode").and_then(Value::as_str).unwrap_or("replace"); + let st = s.active().ok_or(EngineError::NoDocument)?; + if st.doc.layer(id).is_none() { + return Err(EngineError::NoLayer(id)); + } + let mut sel = st.selected_layers(); + match mode { + "replace" => s.select_layer(id)?, + "add" => { + if !sel.contains(&id) { + sel.push(id); + } + set_selection(s, sel, Some(id), Some(id))?; + } + "toggle" => { + if sel.contains(&id) { + if sel.len() == 1 { + // Photoshop keeps at least the clicked layer targeted. + return Ok(json!({"selected": [id.0]})); + } + sel.retain(|x| *x != id); + let active = if st.active_layer == Some(id) { sel.last().copied() } else { st.active_layer }; + set_selection(s, sel, active, active)?; + } else { + sel.push(id); + set_selection(s, sel, Some(id), Some(id))?; + } + } + // Toggle's removing half: a layer that isn't selected stays unselected (Photoshop's + // `removeFromSelection`, recorded by actions). + "remove" => { + if sel.contains(&id) && sel.len() > 1 { + sel.retain(|x| *x != id); + let active = if st.active_layer == Some(id) { sel.last().copied() } else { st.active_layer }; + set_selection(s, sel, active, active)?; + } + } + "range" => { + let anchor = st.layer_anchor.filter(|a| st.doc.layer(*a).is_some()).or(st.active_layer).unwrap_or(id); + let mut order = Vec::new(); + range_order(&st.doc.layers, false, &mut order); + // Engine clients may target a child of a collapsed group that the panel cannot + // click. Retain that capability by using expanded visual order for such calls. + if !order.contains(&anchor) || !order.contains(&id) { + order.clear(); + range_order(&st.doc.layers, true, &mut order); + } + let (a, b) = (order.iter().position(|x| *x == anchor).unwrap_or(0), order.iter().position(|x| *x == id).unwrap_or(0)); + let range = order[a.min(b)..=a.max(b)].to_vec(); + set_selection(s, range, Some(id), Some(anchor))?; + } + other => return Err(bad("layer.select", format!("unknown mode `{other}`"))), + } + Ok(json!({"selected": selected(s).iter().map(|l| l.0).collect::>()})) +} + +pub(super) fn select_all_layers(s: &mut Session) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let ids: Vec = d.doc.walk().into_iter().filter(|(_, _, l)| !d.doc.is_background(l.id)).map(|(_, _, l)| l.id).collect(); + if ids.is_empty() { + return Err(EngineError::Other("there are no layers to select".into())); + } + let active = d.active_layer.filter(|a| ids.contains(a)).or(ids.last().copied()); + let n = ids.len(); + set_selection(s, ids, active, None)?; + Ok(json!({"selected": n})) +} + +pub(super) fn find_layers(s: &mut Session, p: &Value) -> Result { + let needle = p.get("name").and_then(Value::as_str).ok_or_else(|| bad("select.findLayers", "missing `name`"))?.to_lowercase(); + let d = s.active().ok_or(EngineError::NoDocument)?; + let ids: Vec = d.doc.walk().into_iter().filter(|(_, _, l)| l.name.to_lowercase().contains(&needle)).map(|(_, _, l)| l.id).collect(); + if ids.is_empty() { + return Err(EngineError::Other(format!("no layer name contains \"{needle}\""))); + } + let out = ids.iter().map(|l| l.0).collect::>(); + set_selection(s, ids, None, None)?; + Ok(json!({"selected": out})) +} + +pub(super) fn select_linked(s: &mut Session) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let groups = link_groups(&d.doc, &d.selected_layers()); + let ids: Vec = d.doc.walk().into_iter().filter(|(_, _, l)| l.link_group.is_some_and(|g| groups.contains(&g))).map(|(_, _, l)| l.id).collect(); + let active = d.active_layer.filter(|a| ids.contains(a)).or(ids.last().copied()); + let n = ids.len(); + set_selection(s, ids, active, active)?; + Ok(json!({"selected": n})) +} diff --git a/crates/engine/src/layer_multi_cmds/structure.rs b/crates/engine/src/layer_multi_cmds/structure.rs new file mode 100644 index 0000000000..7800db630f --- /dev/null +++ b/crates/engine/src/layer_multi_cmds/structure.rs @@ -0,0 +1,288 @@ +use super::selection::{reselect, selected, top_level}; +use super::*; + +// ---------- structural commands ---------- + +pub(super) fn link_layers(s: &mut Session) -> Result { + let sel = selected(s); + let linked = s.edit("Link Layers", |doc, _| { + let groups: Vec> = sel.iter().map(|id| doc.layer(*id).and_then(|l| l.link_group)).collect(); + // Already one link group (or a single linked layer): unlink, like Photoshop's toggle. + let first = groups.first().copied().flatten(); + let unlink = first.is_some() && groups.iter().all(|g| *g == first); + // A loaded file can store any id up to u64::MAX, so the new id must not be a bare + // max + 1 (#961). Unlinking needs no new id at all. + let next = if unlink { None } else { Some(doc.unused_link_group().ok_or_else(|| bad("layer.linkLayers", "no free link group id is left"))?) }; + for id in &sel { + let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; + l.link_group = next; + } + // A group left with a single member is no longer a link. + let mut counts = std::collections::HashMap::::new(); + for (_, _, l) in doc.walk() { + if let Some(g) = l.link_group { + *counts.entry(g).or_default() += 1; + } + } + let lonely: Vec = + doc.walk().iter().filter(|(_, _, l)| l.link_group.is_some_and(|g| counts.get(&g).is_some_and(|&c| c < 2))).map(|(_, _, l)| l.id).collect(); + for id in lonely { + if let Some(l) = doc.layer_mut(id) { + l.link_group = None; + } + } + Ok(!unlink) + })?; + Ok(json!({"linked": linked})) +} + +pub(super) fn lock_layers(s: &mut Session, p: &Value) -> Result { + let sel = selected(s); + let keys = ["transparency", "pixels", "position", "artboard", "all"]; + let given: Vec<(&str, bool)> = keys.iter().filter_map(|k| Some((*k, p.get(*k)?.as_bool()?))).collect(); + s.edit("Lock Layers", |doc, _| { + // No explicit locks: toggle "lock all" (on unless every selected layer is already locked). + let all_locked = sel.iter().all(|id| doc.layer(*id).is_some_and(|l| l.locks.all)); + let given: Vec<(&str, bool)> = if given.is_empty() { vec![("all", !all_locked)] } else { given.clone() }; + for id in &sel { + let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; + for (k, v) in &given { + l.locks.set(k, *v); + } + } + Ok(()) + })?; + Ok(json!({"layers": sel.len()})) +} + +pub(super) fn rename_layer(s: &mut Session, p: &Value) -> Result { + let name = p.get("name").and_then(Value::as_str).filter(|n| !n.trim().is_empty()).ok_or_else(|| bad("layer.renameLayer", "missing `name`"))?.to_string(); + let id = crate::commands::layer_param(s, p)?; + s.edit("Rename Layer", |doc, _| { + doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.name = name; + Ok(()) + })?; + Ok(Value::Null) +} + +pub(super) fn reverse(s: &mut Session) -> Result { + let sel = selected(s); + s.edit("Reverse", |doc, _| { + let background = crate::background_cmds::background_id(doc); + let ids = top_level(doc, &sel); + if ids.len() < 2 { + return Err(EngineError::Other("select two or more layers to reverse".into())); + } + let paths: Vec> = ids.iter().map(|id| doc.path_of(*id).ok_or(EngineError::NoLayer(*id))).collect::>()?; + let layers: Vec = ids.iter().map(|id| doc.layer(*id).cloned().ok_or(EngineError::NoLayer(*id))).collect::>()?; + // Slots are disjoint (no layer is nested in another), so writing whole layers back to the + // same paths never shifts another slot. + for (path, l) in paths.iter().zip(layers.into_iter().rev()) { + *doc.layer_at_mut(path).ok_or_else(|| EngineError::Other("layer tree changed".into()))? = l; + } + crate::background_cmds::keep_background_at_bottom(background, doc) + })?; + Ok(Value::Null) +} + +/// Refuses an edit that left `doc` nested deeper than [`photocraft_doc::MAX_GROUP_DEPTH`] +/// groups. Called at the end of a `Session::edit` closure, so an `Err` leaves the document and +/// history untouched. +pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> { + if doc.max_group_depth() > photocraft_doc::MAX_GROUP_DEPTH { + return Err(EngineError::Other(format!("{what} would nest layers deeper than {} groups", photocraft_doc::MAX_GROUP_DEPTH))); + } + Ok(()) +} + +/// Group Layers (⌘G) / Group from Layers: the explicit layer, or every selected layer, moves +/// into a new, collapsed group placed where the top-most of them was. Bottom-to-top order is +/// preserved. +pub fn group_layers(s: &mut Session, p: &Value) -> Result { + let ids = match crate::commands::explicit_layer(s, p)? { + Some(id) => vec![id], + None => selected(s), + }; + if ids.is_empty() { + return Err(EngineError::Other("no layer selected".into())); + } + let name = p.get("name").and_then(Value::as_str).map(str::to_string); + let gid = s.edit("Group Layers", |doc, active| { + let ids = top_level(doc, &ids); + let top = *ids.last().ok_or(EngineError::NoLayer(LayerId(0)))?; + let name = name.unwrap_or_else(|| doc.next_layer_name("Group")); + // Photoshop creates the group collapsed, so the panel shows one row in place of the layers. + let mut group = Layer::group(name, vec![]); + if let LayerContent::Group(g) = &mut group.content { + g.expanded = false; + } + let gid = doc.insert_above(Some(top), group); + let mut children = Vec::with_capacity(ids.len()); + for id in &ids { + children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?); + } + *doc.layer_mut(gid).and_then(Layer::children_mut).ok_or(EngineError::NoLayer(gid))? = children; + check_group_depth(doc, "Group Layers")?; + *active = Some(gid); + Ok(gid) + })?; + reselect(s, vec![gid], Some(gid)); + Ok(json!({ "layer": gid.0 })) +} + +pub(super) fn merge_layers(s: &mut Session) -> Result { + let sel = selected(s); + if sel.len() < 2 { + // ⌘E on a lone group is Photoshop's Merge Group (#3832); on a layer, Merge Down. + if let Some(&id) = sel.first() + && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Group(_))) + { + return s.execute("layer.mergeGroup", json!({ "layer": id.0 })); + } + return s.execute("layer.mergeDown", json!({})); + } + let mid = s.edit("Merge Layers", |doc, active| { + let ids = top_level(doc, &sel); + let lowest_id = *ids.first().ok_or_else(|| EngineError::Other("Merge Layers needs two or more layers".into()))?; + let is_background = doc.is_background(lowest_id); + + let mut solo = doc.clone(); + solo.layers = ids.iter().filter_map(|id| doc.layer(*id)).filter(|l| l.visible).cloned().collect(); + if solo.layers.is_empty() { + return Err(EngineError::Other("the selected layers are all hidden".into())); + } + + if is_background { + let base = doc.layer(lowest_id).ok_or(EngineError::NoLayer(lowest_id))?.clone(); + let fmt = doc.pixel_format(); + let mut merged = Layer::raster(base.name.clone(), fmt); + merged.locks = base.locks; + merged.label = base.label; + merged.id = lowest_id; + merged.blend = base.blend; + merged.opacity = 1.0; + *crate::pixels_mut(&mut merged)? = crate::pixels::composite_layers(&solo, fmt, None); + for id in &ids[1..] { + doc.remove(*id); + } + *doc.layer_mut(lowest_id).ok_or(EngineError::NoLayer(lowest_id))? = merged; + *active = Some(lowest_id); + Ok(lowest_id) + } else { + let top_id = *ids.last().ok_or_else(|| EngineError::Other("Merge Layers needs two or more layers".into()))?; + let top = doc.layer(top_id).ok_or(EngineError::NoLayer(top_id))?.clone(); + let fmt = doc.pixel_format(); + let fmt = PixelFormat::new(fmt.mode, fmt.sample, true); + let mut merged = Layer::raster(top.name.clone(), fmt); + merged.locks = top.locks; + merged.label = top.label; + // Clipped layers of one chain merge into a layer still clipped to their base. Clipped + // layers of different chains don't: the result, at the top one's slot, would clip the + // lower chain's pixels to the upper chain's base. + let base = crate::clip_group::base_of(doc, top_id); + merged.clipped = base.is_some() && solo.layers.iter().all(|l| l.clipped && crate::clip_group::base_of(doc, l.id) == base); + *crate::pixels_mut(&mut merged)? = crate::pixels::composite_layers_uncropped(&solo, fmt); + let mid = merged.id; + // Hidden selected layers are discarded, as in Photoshop. + for id in &ids[..ids.len() - 1] { + doc.remove(*id); + } + *doc.layer_mut(top_id).ok_or(EngineError::NoLayer(top_id))? = merged; + *active = Some(mid); + Ok(mid) + } + })?; + reselect(s, vec![mid], Some(mid)); + Ok(json!({ "layer": mid.0 })) +} + +/// Next visible layer row below the deleted target, then rows above in reverse order. +/// Group headers precede their children in the UI, unlike Document::walk's storage order. +pub(crate) fn deletion_neighbours(doc: &Document, target: LayerId) -> Vec { + let rows = |expand_all: bool| { + let mut stack: Vec<&Layer> = doc.layers.iter().collect(); + let mut order = Vec::new(); + while let Some(layer) = stack.pop() { + order.push(layer.id); + if let LayerContent::Group(group) = &layer.content + && (expand_all || group.expanded) + { + stack.extend(group.children.iter()); + } + } + order + }; + let mut order = rows(false); + if !order.contains(&target) { + order = rows(true); + } + let Some(index) = order.iter().position(|id| *id == target) else { + return Vec::new(); + }; + order.iter().skip(index + 1).chain(order.iter().take(index).rev()).copied().collect() +} + +/// Delete Layer with several layers selected. +pub fn delete_selected(s: &mut Session) -> Result { + let sel = selected(s); + s.edit("Delete Layers", |doc, active| { + let ids = top_level(doc, &sel); + let neighbours = active.map(|id| deletion_neighbours(doc, id)).unwrap_or_default(); + let before = crate::clip_group::Before::read(doc, &ids); + for id in &ids { + doc.remove(*id).ok_or(EngineError::NoLayer(*id))?; + } + crate::clip_group::settle(doc, &[], &before, false); + if doc.layers.is_empty() { + return Err(EngineError::Other("a document must keep at least one layer".into())); + } + *active = neighbours.into_iter().find(|candidate| doc.layer(*candidate).is_some()); + Ok(()) + })?; + Ok(json!({"deleted": sel.len()})) +} + +/// Duplicate Layer with several layers selected: each copy goes above its original and the +/// copies become the selection. Artboard copies go beside their boards unless `in_place` +/// ([`crate::artboard_cmds::place_copy`]). `label` names the history step (Layer via Copy reuses +/// this path, #2777). +pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Result { + 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 (copies, active) = s.edit(label, |doc, active| { + let mut copies = Vec::new(); + let mut new_active = None; + for id in top_level(doc, &sel) { + // Match the single-layer duplicate path: Background copies become + // ordinary layers, while normal copies retain their original locks. + 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)?; + } + if Some(id) == old_active { + new_active = Some(nid); + } + copies.push(nid); + } + let a = new_active.or(copies.last().copied()); + *active = a; + Ok((copies, a)) + })?; + let out = copies.iter().map(|l| l.0).collect::>(); + reselect(s, copies, active); + Ok(json!({"layers": out, "layer": active.map(|l| l.0)})) +} + +/// Show/hide every selected layer in one step. +pub fn set_visible_selected(s: &mut Session, visible: bool) -> Result { + let sel = selected(s); + s.edit(if visible { "Show Layers" } else { "Hide Layers" }, |doc, _| { + for id in &sel { + doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.visible = visible; + } + Ok(()) + })?; + Ok(Value::Null) +} From 2f4f76224c8be471845ea2904919eabe1b5b15be Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:57:27 +0000 Subject: [PATCH 205/259] refactor(engine): split edit_menu_cmds.rs into edit_menu_cmds/ --- crates/engine/src/edit_menu_cmds.rs | 1241 +---------------- .../src/edit_menu_cmds/content_aware.rs | 531 +++++++ .../src/edit_menu_cmds/content_aware_scale.rs | 202 +++ crates/engine/src/edit_menu_cmds/fade.rs | 90 ++ .../engine/src/edit_menu_cmds/find_replace.rs | 163 +++ crates/engine/src/edit_menu_cmds/presets.rs | 150 ++ crates/engine/src/edit_menu_cmds/purge.rs | 95 ++ 7 files changed, 1252 insertions(+), 1220 deletions(-) create mode 100644 crates/engine/src/edit_menu_cmds/content_aware.rs create mode 100644 crates/engine/src/edit_menu_cmds/content_aware_scale.rs create mode 100644 crates/engine/src/edit_menu_cmds/fade.rs create mode 100644 crates/engine/src/edit_menu_cmds/find_replace.rs create mode 100644 crates/engine/src/edit_menu_cmds/presets.rs create mode 100644 crates/engine/src/edit_menu_cmds/purge.rs diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rs index 0ef173d242..f7603d2908 100644 --- a/crates/engine/src/edit_menu_cmds.rs +++ b/crates/engine/src/edit_menu_cmds.rs @@ -164,23 +164,6 @@ fn writable_surface(doc: &mut Document, id: LayerId) -> Result<&mut Surface> { l.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into())) } -// ------------------------------------------------------------------ Fade - -fn can_fade(s: &Session) -> std::result::Result<(), String> { - let st = s.active().ok_or("no document open")?; - let f = s.edit_state.fade.as_ref().ok_or("nothing to fade")?; - if f.doc != st.doc.id || f.revision != st.revision || !st.history.can_undo() { - return Err("Fade is only available right after a filter, adjustment or painting step".into()); - } - if surface_of(&st.doc, f.target).is_none() { - return Err(match f.target { - FadeTarget::Pixels(_) | FadeTarget::Mask(_) => "the faded layer no longer exists".into(), - FadeTarget::Channel(_) | FadeTarget::QuickMask => "the faded channel no longer exists".into(), - }); - } - Ok(()) -} - fn surface_of(doc: &Document, target: FadeTarget) -> Option<&Surface> { match target { FadeTarget::Pixels(id) => doc.layer(id)?.surface(), @@ -199,1209 +182,6 @@ fn surface_of_mut(doc: &mut Document, target: FadeTarget) -> Option<&mut Surface } } -/// Blend `after` back towards `before` over `area`: `before + opacity × (B(before, after) − before)` -/// with blend mode `mode` (premultiplied, so alpha changes fade too). -pub fn fade_surface(before: &Surface, after: &mut Surface, area: Rect, mode: BlendMode, opacity: f32) -> Result<()> { - let fmt = after.format(); - let n = fmt.channels(); - if area.is_empty() || n == 0 { - return Ok(()); - } - let b = crate::allocation::read_region(before, area, "fading pixels")?; - let mut a = crate::allocation::read_region(after, area, "fading pixels")?; - let k = opacity.clamp(0.0, 1.0); - let lerp_premul = |pb: &[f32], pa: &[f32], out: &mut [f32], alpha: bool| { - let m = out.len(); - if !alpha { - for c in 0..m { - out[c] = pb[c] + (pa[c] - pb[c]) * k; - } - return; - } - let (ab, aa) = (pb[m - 1], pa[m - 1]); - let ao = ab + (aa - ab) * k; - for c in 0..m - 1 { - let pm = pb[c] * ab + (pa[c] * aa - pb[c] * ab) * k; - out[c] = if ao > 1e-9 { pm / ao } else { 0.0 }; - } - out[m - 1] = ao; - }; - let mut tmp = crate::allocation::filled(n, 0.0f32, "fading pixels")?; - for (pa, pb) in a.chunks_exact_mut(n).zip(b.chunks_exact(n)) { - if mode == BlendMode::Normal || n == 1 { - lerp_premul(pb, pa, &mut tmp, fmt.alpha); - pa.copy_from_slice(&tmp); - } else { - let rb = to_rgba(&fmt, pb); - let ra = to_rgba(&fmt, pa); - let blended = photocraft_color::blend::composite(mode, rb, ra, 1.0); - let mut o = [0.0f32; 4]; - lerp_premul(&rb, &blended, &mut o, true); - let mut enc = [0.0f32; 8]; - from_rgba_into(&fmt, o, &mut enc); - pa.copy_from_slice(&enc[..n]); - } - } - after.try_write_region(area, &a)?; - Ok(()) -} - -fn fade(s: &mut Session, p: &Value) -> Result { - let cmd = "edit.fade"; - let src = s.edit_state.fade.clone().ok_or_else(|| bad(cmd, "nothing to fade"))?; - let opacity = f32_or(p, "opacity", 100.0).clamp(0.0, 100.0) / 100.0; - let mode = blend_from_str(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let prev = st.history.past_len().checked_sub(1).and_then(|i| st.history.state(i)).ok_or_else(|| bad(cmd, "no previous state"))?; - let before = surface_of(&prev, src.target).cloned().ok_or_else(|| EngineError::Other("the layer or channel did not exist before this step".into()))?; - let now = surface_of(&st.doc, src.target).ok_or_else(|| EngineError::Other("the faded layer or channel no longer exists".into()))?; - if now.format() != before.format() { - return Err(EngineError::Other("can't fade a step that changed the layer's pixel format".into())); - } - // A uniform mask can change every pixel without storing a single tile. In that case - // the content bounds are empty, but Fade must still blend across the canvas. - let area = if before.default_pixel() != now.default_pixel() { st.doc.bounds() } else { before.content_bounds().union(&now.content_bounds()) }; - let label = format!("Fade {}", src.label); - s.edit(&label, |doc, _| { - let surf = surface_of_mut(doc, src.target).ok_or_else(|| EngineError::Other("the faded layer or channel no longer exists".into()))?; - fade_surface(&before, surf, area, mode, opacity)?; - surf.prune(); - Ok(()) - })?; - Ok(json!({"faded": src.label, "opacity": opacity * 100.0, "mode": mode.label()})) -} - -// ------------------------------------------------------------------ Purge - -fn history_bytes(s: &Session, all: bool) -> usize { - let docs: Vec<&crate::DocState> = if all { s.documents().iter().collect() } else { s.active().into_iter().collect() }; - // Purge keeps the snapshots, so the tiles they share with the states aren't freed. - docs.iter() - .map(|d| { - let snaps: Vec<&photocraft_doc::Document> = d.snapshots.iter().map(|s| &*s.doc).collect(); - d.history.unique_bytes_besides(&d.doc, &snaps) - }) - .sum() -} - -fn clip_bytes(s: &Session) -> usize { - s.clipboard.as_ref().map_or(0, |c| c.surface.tiles().map(|(_, t)| t.bytes().len()).sum()) -} - -fn purge(s: &mut Session, what: &str) -> Result { - let mut freed = 0usize; - let mut items: Vec<&str> = Vec::new(); - if matches!(what, "undo" | "all") && s.active().is_some_and(|d| d.history.can_undo()) { - let before = history_bytes(s, false); - if let Some(st) = s.active_mut() { - st.history.purge_last(); - } - freed += before.saturating_sub(history_bytes(s, false)); - items.push("undo"); - } - if matches!(what, "clipboard" | "all") && (s.clipboard.is_some() || s.style_clipboard.is_some()) { - freed += clip_bytes(s); - s.clipboard = None; - s.style_clipboard = None; - items.push("clipboard"); - } - if matches!(what, "histories" | "all") { - let b = history_bytes(s, true); - if s.documents().iter().any(|d| d.history.can_undo() || d.history.can_redo()) { - for st in &mut s.docs { - st.history.clear(); - st.coalesce = None; - } - freed += b; - items.push("histories"); - } - } - if what == "all" { - let fx = photocraft_compose::purge_effect_cache(); - if fx > 0 { - freed += fx; - items.push("effect cache"); - } - let masks = photocraft_compose::masks::purge_cache(); - if masks > 0 { - freed = freed.saturating_add(masks); - items.push("mask cache"); - } - let stages = crate::smart_cmds::purge_stack_cache(); - if stages > 0 { - freed = freed.saturating_add(stages); - items.push("smart filter cache"); - } - let strokes = photocraft_compose::shape_split::purge_cache(); - if strokes > 0 { - freed = freed.saturating_add(strokes); - items.push("shape stroke cache"); - } - } - s.edit_state.fade = None; - let msg = if items.is_empty() { "nothing to purge".to_string() } else { format!("purged {}", items.join(", ")) }; - Ok(json!({"purged": items, "bytes": freed, "message": msg})) -} - -fn can_purge_undo(s: &Session) -> std::result::Result<(), String> { - s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "nothing to purge".into()) -} -fn can_purge_clipboard(s: &Session) -> std::result::Result<(), String> { - if s.clipboard.is_some() || s.style_clipboard.is_some() { Ok(()) } else { Err("the clipboard is empty".into()) } -} -fn can_purge_histories(s: &Session) -> std::result::Result<(), String> { - if s.documents().iter().any(|d| d.history.can_undo() || d.history.can_redo()) { Ok(()) } else { Err("no history to purge".into()) } -} -fn can_purge_all(s: &Session) -> std::result::Result<(), String> { - can_purge_histories(s).or_else(|_| can_purge_clipboard(s)).or_else(|_| { - if photocraft_compose::effect_cache_bytes() > 0 || photocraft_compose::masks::cache_bytes() > 0 || crate::smart_cmds::stack_cache_bytes() > 0 { - Ok(()) - } else { - Err("nothing to purge".into()) - } - }) -} - -// ------------------------------------------------------------------ Content-Aware Fill - -fn can_caf(s: &Session) -> std::result::Result<(), String> { - pixel_layer(s)?; - let d = s.active().ok_or("no document open")?; - if d.doc.selection.as_ref().is_none_or(|m| m.content_bounds().is_empty()) { - return Err("make a selection around what to remove".into()); - } - Ok(()) -} - -/// Mask surface (gray) of an alpha channel by index or name. -pub(crate) fn channel_mask<'a>(doc: &'a Document, v: &Value) -> Option<&'a Surface> { - match v { - Value::Number(n) => doc.channels.get(n.as_u64()? as usize).map(|c| &c.surface), - Value::String(name) => doc.channels.iter().find(|c| c.name == *name).map(|c| &c.surface), - _ => None, - } -} - -/// `key` as an `[x, y, w, h]` rectangle. The saturating float→int casts bound each component; -/// the additions saturate too — `area: [1e30, 0, 1e30, 10]` is a whole-canvas window, not an -/// overflow (it panicked in debug builds before the `saturating_add`). -fn rect_param(p: &Value, key: &str, cmd: &str) -> Result { - let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y, w, h]")))?; - let n = |i: usize| { - a.get(i) - .and_then(Value::as_f64) - .filter(|f| f.is_finite()) - .map(|v| v.round() as i32) - .ok_or_else(|| bad(cmd, format!("`{key}` must be four finite numbers"))) - }; - let (x, y, w, h) = (n(0)?, n(1)?, n(2)?, n(3)?); - Ok(Rect::new(x, y, x.saturating_add(w.max(0)), y.saturating_add(h.max(0)))) -} - -fn content_aware_fill(s: &mut Session, p: &Value) -> Result { - content_aware_fill_as(s, p, "edit.contentAwareFill", "Content-Aware Fill") -} - -/// Delete and Fill Selection (#1286): Photoshop's one-click removal from the selection-tool -/// context menu. Content-Aware Fill into the layer, no dialog, sampling as Edit › Fill does (the -/// whole window, measured on Photoshop 25.4) with the default colour adaptation. -fn delete_and_fill(s: &mut Session, _: &Value) -> Result { - content_aware_fill_as(s, &json!({"sampling": "rectangular"}), "edit.deleteAndFillSelection", "Delete and Fill Selection") -} - -/// Everything one Content-Aware Fill needs, worked out from the document and the command's -/// params. The Content-Aware Fill workspace runs exactly this for its preview, so what it shows -/// is what OK and Apply write. -pub struct CafPlan { - pub layer: LayerId, - /// The rectangle worked on: the sampling window, and any sampling-brush strokes or custom - /// area beyond it. - pub rect: Rect, - /// Photoshop's sampling window around the fill area (`content_aware::sampling_window`). - pub window: Rect, - pub fmt: PixelFormat, - /// What is sampled over `rect`: the target's pixels, or with Sample All Layers the visible - /// composite in the target's encoding. - pub img: Vec, - /// The target's own pixels over `rect` when they differ from `img` (Sample All Layers); see - /// [`CafPlan::layer_pixels`]. - pub layer_px: Option>, - /// The fill area (selection coverage, after the workspace's lasso edits) over `rect`. - pub cover: Vec, - pub hole: Vec, - /// What may be copied from: the sampling option's area before the brush strokes, and after. - pub base: Vec, - pub source: Vec, - pub opts: photocraft_algo::content_aware::FillOptions, - pub output: String, -} - -impl CafPlan { - /// The target layer's pixels over `rect`. - pub fn layer_pixels(&self) -> &[f32] { - self.layer_px.as_deref().unwrap_or(&self.img) - } -} - -/// The workspace's lasso edits of the fill area: `{"op": "new|add|subtract|intersect", "points": -/// [[x, y], ...]}` or `{"op": "expand|contract", "by": px}`, applied in order. -#[derive(Clone, Debug, PartialEq)] -pub enum FillEdit { - Lasso { op: SelOp, points: Vec<[f64; 2]> }, - Grow(i32), -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum SelOp { - New, - Add, - Subtract, - Intersect, -} - -/// Most `fillEdits` and `samplingStrokes` one fill takes, and most points in all of them -/// together: the strokes and lassos are painted pixel by pixel, segment by segment. -pub const MAX_CAF_EDITS: usize = 1_000; -pub const MAX_CAF_POINTS: usize = 200_000; - -fn points_param(v: &Value, cmd: &str, what: &str, budget: &mut usize) -> Result> { - let a = v.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("{what} needs `points` [[x, y], ...]")))?; - *budget = budget.checked_sub(a.len()).ok_or_else(|| bad(cmd, format!("at most {MAX_CAF_POINTS} points in all fill edits and sampling strokes")))?; - a.iter() - .map(|p| { - let x = p.get(0).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() < 1e7); - let y = p.get(1).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() < 1e7); - match (x, y) { - (Some(x), Some(y)) => Ok([x, y]), - _ => Err(bad(cmd, format!("{what} points must be pairs of finite numbers"))), - } - }) - .collect() -} - -/// `p[key]` as an array of at most [`MAX_CAF_EDITS`] entries (empty when absent). -fn edits_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a [Value]> { - let Some(a) = p.get(key) else { return Ok(&[]) }; - let a = a.as_array().ok_or_else(|| bad(cmd, format!("`{key}` must be an array")))?; - if a.len() > MAX_CAF_EDITS { - return Err(bad(cmd, format!("`{key}` takes at most {MAX_CAF_EDITS} entries"))); - } - Ok(a) -} - -fn fill_edits(p: &Value, cmd: &str, budget: &mut usize) -> Result> { - edits_param(p, "fillEdits", cmd)? - .iter() - .map(|e| { - let op = e.get("op").and_then(Value::as_str).unwrap_or(""); - Ok(match op { - "expand" | "contract" => { - let by = e - .get("by") - .and_then(Value::as_f64) - .filter(|v| v.is_finite() && (0.0..=1000.0).contains(v)) - .ok_or_else(|| bad(cmd, "`by` must be 0..1000 px"))?; - FillEdit::Grow(if op == "expand" { by.round() as i32 } else { -(by.round() as i32) }) - } - "new" | "add" | "subtract" | "intersect" => FillEdit::Lasso { - op: match op { - "new" => SelOp::New, - "add" => SelOp::Add, - "subtract" => SelOp::Subtract, - _ => SelOp::Intersect, - }, - points: points_param(e, cmd, "a lasso edit", budget)?, - }, - o => return Err(bad(cmd, format!("unknown fill edit `{o}` (new|add|subtract|intersect|expand|contract)"))), - }) - }) - .collect() -} - -fn sampling_strokes(p: &Value, cmd: &str, budget: &mut usize) -> Result> { - edits_param(p, "samplingStrokes", cmd)? - .iter() - .map(|e| { - let add = match e.get("mode").and_then(Value::as_str).unwrap_or("add") { - "add" => true, - "subtract" => false, - o => return Err(bad(cmd, format!("unknown stroke mode `{o}` (add|subtract)"))), - }; - let size = e - .get("size") - .and_then(Value::as_f64) - .filter(|v| v.is_finite() && (1.0..=5000.0).contains(v)) - .ok_or_else(|| bad(cmd, "a stroke's `size` must be 1..5000 px"))?; - Ok(photocraft_algo::content_aware::SamplingStroke { add, size, points: points_param(e, cmd, "a sampling stroke", budget)? }) - }) - .collect() -} - -/// A Content-Aware Fill's params, checked against the document before any pixel is read. -struct CafParams<'a> { - sel: &'a Surface, - /// The selection's bounds on the canvas. - sb: Rect, - edits: Vec, - strokes: Vec, - sampling: String, - custom_mask: Option<&'a Surface>, - custom_rect: Option, - opts: photocraft_algo::content_aware::FillOptions, - output: String, - surf: &'a Surface, -} - -fn caf_params<'a>(doc: &'a Document, id: LayerId, p: &Value, cmd: &str) -> Result> { - use photocraft_algo::content_aware::{FillOptions, color_level, rotation_level}; - let sel = doc.selection.as_ref().ok_or_else(|| bad(cmd, "no selection"))?; - let sb = sel.content_bounds().intersect(&doc.bounds()); - if sb.is_empty() { - return Err(bad(cmd, "the selection is outside the canvas")); - } - let mut budget = MAX_CAF_POINTS; - let edits = fill_edits(p, cmd, &mut budget)?; - let strokes = sampling_strokes(p, cmd, &mut budget)?; - let sampling = str_or(p, "sampling", "auto").to_string(); - let custom_mask: Option<&Surface> = p.get("channel").and_then(|v| channel_mask(doc, v)); - let custom_rect = if p.get("area").is_some() { Some(rect_param(p, "area", cmd)?) } else { None }; - match sampling.as_str() { - "auto" | "rectangular" => {} - // The workspace's Custom: only what the Sampling Brush adds. - "custom" if custom_rect.is_some() || custom_mask.is_some() || strokes.iter().any(|s| s.add) => {} - "custom" => return Err(bad(cmd, "custom sampling needs `area` [x,y,w,h], `channel` (alpha channel index or name) or `samplingStrokes`")), - other => return Err(bad(cmd, format!("unknown sampling `{other}` (auto|rectangular|custom)"))), - } - let opts = FillOptions { - color_adaptation: color_level(str_or(p, "colorAdaptation", "default")), - rotations: rotation_level(str_or(p, "rotationAdaptation", "none")), - scale: bool_or(p, "scale", false), - mirror: bool_or(p, "mirror", false), - seed: p.get("seed").and_then(Value::as_u64).unwrap_or(1), - }; - let output = str_or(p, "output", "current").to_string(); - if !matches!(output.as_str(), "current" | "new" | "duplicate") { - return Err(bad(cmd, "`output` must be current|new|duplicate")); - } - let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; - Ok(CafParams { sel, sb, edits, strokes, sampling, custom_mask, custom_rect, opts, output, surf }) -} - -/// Work out a Content-Aware Fill (see [`CafPlan`]) on layer `id` of `doc`. -pub fn content_aware_plan(doc: &Document, id: LayerId, p: &Value, cmd: &str) -> Result { - content_aware_plan_with(doc, id, p, cmd, &photocraft_raster::Interrupt::NONE) -} - -/// [`content_aware_plan`], asking `ctl` row by row whether to stop ([`EngineError::Cancelled`]). -pub fn content_aware_plan_with(doc: &Document, id: LayerId, p: &Value, cmd: &str, ctl: &photocraft_raster::Interrupt) -> Result { - use photocraft_algo::content_aware::{auto_sampling_with, grow_mask, paint_strokes, polygon_mask}; - use rayon::prelude::*; - - use crate::fill_cmds::{read_window, read_window_mask}; - let CafParams { sel, sb, edits, strokes, sampling, custom_mask, custom_rect, opts, output, surf } = caf_params(doc, id, p, cmd)?; - let canvas = doc.bounds(); - let cancel = || ctl.cancelled(); - let stop = || if ctl.cancelled() { Err(EngineError::Cancelled) } else { Ok(()) }; - // The fill area: the selection, then the lasso edits, over a rectangle that holds them all. - let grow: i32 = edits.iter().map(|e| if let FillEdit::Grow(b) = e { b.max(&0) } else { &0 }).sum(); - let reach = edits.iter().fold(sb, |r, e| match e { - FillEdit::Lasso { points, .. } => { - points.iter().fold(r, |r, q| r.union(&Rect::new(q[0].floor() as i32, q[1].floor() as i32, q[0].floor() as i32 + 1, q[1].floor() as i32 + 1))) - } - FillEdit::Grow(_) => r, - }); - let er = reach.inflate(grow.saturating_add(1)).intersect(&canvas); - let (ew, eh) = crate::fill_cmds::window_size(er)?; - let ecover = read_window_mask(sel, er, &cancel).ok_or(EngineError::Cancelled)?; - let mut ehole: Vec = ecover.par_iter().map(|c| *c > 0.0).collect(); - for e in &edits { - stop()?; - match e { - FillEdit::Lasso { op, points } => { - let m = polygon_mask(er, points); - for (h, v) in ehole.iter_mut().zip(&m) { - *h = match op { - SelOp::New => *v, - SelOp::Add => *h || *v, - SelOp::Subtract => *h && !*v, - SelOp::Intersect => *h && *v, - }; - } - } - FillEdit::Grow(by) => ehole = grow_mask(&ehole, ew, eh, *by), - } - } - let (bx0, by0, bx1, by1) = mask_bounds(ew, eh, &ehole); - if bx1 <= bx0 { - return Err(bad(cmd, "the fill area is empty")); - } - let hb = Rect::new(er.x0 + bx0 as i32, er.y0 + by0 as i32, er.x0 + bx1 as i32, er.y0 + by1 as i32); - // Photoshop's window (`content_aware::sampling_window`) for Auto and Rectangular; `margin` - // asks for a rectangle that far around the fill area instead. - let window = match sampling.as_str() { - "rectangular" => match int(p, "margin") { - Some(m) => hb.inflate(m.clamp(0, 100_000) as i32), - None => crate::fill_cmds::sampling_window(hb, canvas), - }, - "custom" => match (custom_rect, custom_mask) { - (Some(r), _) => r, - (None, Some(m)) => m.content_bounds(), - (None, None) => hb, - } - .union(&hb) - .inflate(4), - _ => crate::fill_cmds::sampling_window(hb, canvas), - } - .intersect(&canvas); - // Strokes that add to the sampling area may reach past the window. - let rect = strokes.iter().filter(|s| s.add).fold(window, |r, s| r.union(&s.bounds())).intersect(&canvas); - let fmt = surf.format(); - // Photoshop's Sample All Layers checkbox is off unless the caller asks. When the active - // layer has no pixels in the window there is nothing to sample, so that case uses the - // visible composite (#4026). An explicit false still reads only this layer. - let sample_all = match p.get("sampleAllLayers").and_then(Value::as_bool) { - Some(v) => v, - None => surf.content_bounds().intersect(&window).is_empty(), - }; - let n = fmt.channels(); - // Refuse a window too large to read before allocating for it, whatever the sampling (#963). - let (w, h) = crate::fill_cmds::window_size(rect)?; - let pixels = read_window(surf, rect, &cancel).ok_or(EngineError::Cancelled)?; - let (img, layer_px) = if sample_all { - stop()?; - (crate::retouch_cmds::composite_region(doc, Some(id), crate::retouch_cmds::SampleLayers::All, rect, fmt).data, Some(pixels)) - } else { - (pixels, None) - }; - stop()?; - let mut cover = vec![0.0f32; w * h]; - let mut hole = vec![false; w * h]; - cover.par_chunks_mut(w.max(1)).zip(hole.par_chunks_mut(w.max(1))).enumerate().try_for_each(|(y, (crow, hrow))| { - stop()?; - let dy = rect.y0 + y as i32; - if dy < er.y0 || dy >= er.y1 { - return Ok(()); - } - for (x, (c, hl)) in crow.iter_mut().zip(hrow.iter_mut()).enumerate() { - let dx = rect.x0 + x as i32; - if dx >= er.x0 && dx < er.x1 { - let j = (dy - er.y0) as usize * ew + (dx - er.x0) as usize; - let (eh, ec) = (ehole.get(j).copied().unwrap_or(false), ecover.get(j).copied().unwrap_or(0.0)); - *hl = eh; - // Pixels the lasso added are filled outright; selected ones by their coverage. - *c = if eh { if ec > 0.0 { ec } else { 1.0 } } else { 0.0 }; - } - } - Ok::<(), EngineError>(()) - })?; - drop((ecover, ehole)); - // The sampling option's area: Auto keeps what looks like the surroundings within the window, - // Rectangular the whole window, Custom the given area (or nothing, for the brush to add to). - let mut base = vec![false; w * h]; - match sampling.as_str() { - "auto" | "rectangular" => { - let (ww, wh) = (window.width() as usize, window.height() as usize); - let (ox, oy) = ((window.x0 - rect.x0) as usize, (window.y0 - rect.y0) as usize); - let area: Vec = match sampling.as_str() { - "auto" if window == rect => auto_sampling_with(w, h, n, &img, &hole, ctl).map_err(|_| EngineError::Cancelled)?, - "auto" => { - let mut wimg = vec![0.0f32; ww * wh * n]; - let mut whole = vec![false; ww * wh]; - for y in 0..wh { - let s = ((oy + y) * w + ox) * n; - wimg[y * ww * n..(y + 1) * ww * n].copy_from_slice(&img[s..s + ww * n]); - whole[y * ww..(y + 1) * ww].copy_from_slice(&hole[(oy + y) * w + ox..(oy + y) * w + ox + ww]); - } - auto_sampling_with(ww, wh, n, &wimg, &whole, ctl).map_err(|_| EngineError::Cancelled)? - } - _ => vec![true; ww * wh], - }; - for y in 0..wh { - base[(oy + y) * w + ox..(oy + y) * w + ox + ww].copy_from_slice(&area[y * ww..(y + 1) * ww]); - } - } - _ => match (custom_rect, custom_mask) { - (Some(r), _) => base.par_iter_mut().enumerate().for_each(|(i, b)| *b = r.contains(rect.x0 + (i % w) as i32, rect.y0 + (i / w) as i32)), - (None, Some(m)) => { - let v = read_window_mask(m, rect, &cancel).ok_or(EngineError::Cancelled)?; - base.par_iter_mut().zip(&v).for_each(|(b, v)| *b = *v > 0.5); - } - (None, None) => {} - }, - } - stop()?; - base.par_iter_mut().zip(&hole).for_each(|(b, h)| *b &= !*h); - let mut source = base.clone(); - paint_strokes(&mut source, rect, &strokes); - source.par_iter_mut().zip(&hole).for_each(|(s, h)| *s &= !*h); - Ok(CafPlan { layer: id, rect, window, fmt, img, layer_px, cover, hole, base, source, opts, output }) -} - -fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: &'static str) -> Result { - use photocraft_algo::content_aware::fill_owned; - // The workspace names the layer it opened on: after an Apply to a new layer that one is - // active, but the fill still samples the original. - let id = match p.get("layer").and_then(Value::as_u64) { - Some(l) => pixel_layer_id(s, LayerId(l)), - None => pixel_layer(s), - } - .map_err(EngineError::Other)?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let doc = st.doc.clone(); - // Check the params before the job starts. - caf_params(&doc, id, p, cmd)?; - let p = p.clone(); - // A background job when started with `Session::start` (#210): working out the fill area and - // the sampling area, reading the pixels and the PatchMatch fill run on a worker against the - // document snapshot, cancellable per row band. - crate::jobs::run( - s, - label, - true, - move |ctx| { - use rayon::prelude::*; - ctx.progress(0.0, label); - let cancel = || ctx.cancelled(); - let plan = content_aware_plan_with(&doc, id, &p, cmd, &photocraft_raster::Interrupt::cancel_only(&cancel))?; - let CafPlan { layer, rect, fmt, img, layer_px, cover, hole, source, opts, output, .. } = plan; - // Patches come only from the sampling area outside the fill area. With none (a - // Rectangular `margin` of 0, a Custom area inside the selection or off the canvas) - // the fill would be black (#6532), so refuse instead. The workspace's preview builds - // the same plan and may show an empty area while the Sampling Brush adds to it. - if !source.iter().any(|s| *s) { - return Err(bad(cmd, "nothing to sample from: the sampling area has no pixels outside the fill area")); - } - let (w, h) = (rect.width() as usize, rect.height() as usize); - let n = fmt.channels(); - // The fill changes only the fill area: keep the layer's pixels and the coverage over - // its bounds for the apply step, and fill the sampled pixels themselves. - let (bx0, by0, bx1, by1) = mask_bounds(w, h, &hole); - let own = layer_px.as_deref().unwrap_or(&img); - let original: Vec = (by0..by1).flat_map(|y| own[(y * w + bx0) * n..(y * w + bx1) * n].iter().copied()).collect(); - let cover: Vec = (by0..by1).flat_map(|y| cover[y * w + bx0..y * w + bx1].iter().copied()).collect(); - let n_hole = cover.iter().filter(|c| **c > 0.0).count(); - ctx.check()?; - let mut filled = ctx.stage(0.05, 1.0, label, |ctl| fill_owned(w, h, n, img, &hole, &source, &opts, ctl)).map_err(|_| EngineError::Cancelled)?; - // Sampled from all layers: outside the fill area the window keeps the layer's pixels. - if let Some(own) = layer_px { - filled.par_chunks_mut(n.max(1)).zip(own.par_chunks(n.max(1))).zip(hole.par_iter()).for_each(|((f, o), h)| { - if !*h { - f.copy_from_slice(o); - } - }); - } - Ok((layer, rect, fmt, output, FilledWindow { filled, bounds: (bx0, by0, bx1, by1), original, cover, n_hole })) - }, - move |s, (layer, rect, fmt, output, done)| apply_content_aware_fill(s, label, layer, &output, fmt, rect, done), - ) -} - -/// A Content-Aware Fill's result for its apply step: the filled window (the same as the -/// original outside the selected pixels) and, over the bounds of the selected pixels (in window -/// coordinates), the original pixels and the selection's coverage. -struct FilledWindow { - filled: Vec, - bounds: (usize, usize, usize, usize), - original: Vec, - cover: Vec, - n_hole: usize, -} - -/// `f(window index, index over the bounds, coverage)` for each selected pixel of a -/// [`FilledWindow`] (`w` wide). -fn each_selected(w: usize, (bx0, by0, bx1, by1): (usize, usize, usize, usize), cover: &[f32], mut f: impl FnMut(usize, usize, f32)) { - let bw = bx1.saturating_sub(bx0); - for y in by0..by1 { - for x in bx0..bx1 { - let k = (y - by0) * bw + (x - bx0); - if let Some(&c) = cover.get(k) - && c > 0.0 - { - f(y * w + x, k, c); - } - } - } -} - -/// Bounds `(x0, y0, x1, y1)` of the set cells of a `w × h` mask (all zero when there are none). -fn mask_bounds(w: usize, h: usize, m: &[bool]) -> (usize, usize, usize, usize) { - use rayon::prelude::*; - if w == 0 { - return (0, 0, 0, 0); - } - let rows: Vec> = - m.par_chunks(w).take(h).map(|row| Some((row.iter().position(|v| *v)?, row.iter().rposition(|v| *v)? + 1))).collect(); - let mut b: Option<(usize, usize, usize, usize)> = None; - for (y, span) in rows.into_iter().enumerate() { - if let Some((x0, x1)) = span { - b = Some(b.map_or((x0, y, x1, y + 1), |(bx0, by0, bx1, _)| (bx0.min(x0), by0, bx1.max(x1), y + 1))); - } - } - b.unwrap_or((0, 0, 0, 0)) -} - -/// Write a Content-Aware Fill result (the job's apply step): into the layer, a new layer or a -/// duplicate, as one undo step. -fn apply_content_aware_fill(s: &mut Session, label: &str, id: LayerId, output: &str, fmt: PixelFormat, window: Rect, done: FilledWindow) -> Result { - let n = fmt.channels(); - let (w, h) = (window.width() as usize, window.height() as usize); - let FilledWindow { mut filled, bounds, original, cover, n_hole } = done; - let layer = s.edit(label, |doc, active| { - let target = match output { - "new" => { - let mut l = Layer::raster(doc.next_layer_name("Content-Aware Fill"), PixelFormat { alpha: true, ..fmt }); - let mut px = vec![0.0f32; w * h * n.max(1)]; - let lf = l.surface().map(|s| s.format()).unwrap_or(fmt); - let ln = lf.channels(); - px.resize(w * h * ln, 0.0); - each_selected(w, bounds, &cover, |i, _, c| { - let rgba = to_rgba(&fmt, &filled[i * n..(i + 1) * n]); - let mut enc = [0.0f32; 8]; - from_rgba_into(&lf, [rgba[0], rgba[1], rgba[2], rgba[3] * c], &mut enc); - px[i * ln..(i + 1) * ln].copy_from_slice(&enc[..ln]); - }); - if let Some(s) = l.surface_mut() { - s.write_region(window, &px); - s.prune(); - } - let nid = doc.insert_above(Some(id), l); - *active = Some(nid); - return Ok(nid); - } - "duplicate" => { - let mut dup = doc.layer(id).ok_or(EngineError::NoLayer(id))?.duplicate(); - dup.name = doc.copy_name(&dup.name); - let nid = doc.insert_above(Some(id), dup); - *active = Some(nid); - nid - } - _ => id, - }; - let surf = writable_surface(doc, target)?; - // The fill blended in by the coverage (elsewhere it is the original). - each_selected(w, bounds, &cover, |i, k, c| { - for ch in 0..n { - let (j, o) = (i * n + ch, k * n + ch); - filled[j] = original[o] + (filled[j] - original[o]) * c; - } - }); - surf.write_region(window, &filled); - Ok(target) - })?; - Ok(json!({"layer": layer.0, "filled": n_hole, "window": [window.x0, window.y0, window.width(), window.height()]})) -} - -// ------------------------------------------------------------------ Content-Aware Scale - -/// Reach of Content-Aware Scale's `x`/`y`: the largest document side. -const CAS_POSITION_LIMIT: f64 = 300_000.0; - -/// What Content-Aware Scale does, read from its params against the active document: the -/// command and the transform box's live preview ([`ContentAwareScalePreview`]) share it. -struct CasPlan { - doc: std::sync::Arc, - layer: LayerId, - /// The area scaled: the selection's bounds, else the layer's content. - region: Rect, - /// Where the result goes: `x`, `y` (default: the region's corner), `width`, `height`. - dst: Rect, - amount: f32, - protect: Option, - skin_tones: bool, -} - -fn cas_plan(s: &Session, p: &Value) -> Result { - let cmd = "edit.contentAwareScale"; - let id = pixel_layer(s).map_err(EngineError::Other)?; - let st = s.active().ok_or(EngineError::NoDocument)?; - let doc = st.doc.clone(); - let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; - let region = match &doc.selection { - Some(sel) => sel.content_bounds().intersect(&doc.bounds()), - None => surf.content_bounds(), - }; - if region.is_empty() { - return Err(EngineError::Other("nothing to scale: the layer is empty".into())); - } - let (w, h) = (region.width() as usize, region.height() as usize); - let dim = |k: &str, pct: &str, cur: usize| -> Result { - let v = match (p.get(k).and_then(Value::as_f64), p.get(pct).and_then(Value::as_f64)) { - (Some(px), _) => px, - (None, Some(pc)) => cur as f64 * pc / 100.0, - (None, None) => cur as f64, - }; - if !(1.0..=60_000.0).contains(&v) { - return Err(bad(cmd, format!("`{k}` must be 1..60000 px"))); - } - Ok(v.round() as u32) - }; - let (nw, nh) = (dim("width", "scaleX", w)?, dim("height", "scaleY", h)?); - let at = |k: &str, cur: i32| -> Result { - match p.get(k).filter(|v| !v.is_null()) { - None => Ok(cur), - Some(v) => match v.as_f64() { - Some(x) if (-CAS_POSITION_LIMIT..=CAS_POSITION_LIMIT).contains(&x) => Ok(x.round() as i32), - _ => Err(bad(cmd, format!("`{k}` must be a number of px within ±300000"))), - }, - } - }; - let dst = Rect::from_xywh(at("x", region.x0)?, at("y", region.y0)?, nw, nh); - let amount = f32_or(p, "amount", 100.0).clamp(0.0, 100.0) / 100.0; - // Protection: an alpha channel and/or skin tones. - let protect = match p.get("protect").filter(|v| !v.is_null() && v.as_str() != Some("none")) { - Some(v) => Some(channel_mask(&doc, v).cloned().ok_or_else(|| bad(cmd, "`protect` must name an alpha channel (index or name) or \"none\""))?), - None => None, - }; - let skin_tones = bool_or(p, "protectSkinTones", false); - Ok(CasPlan { doc, layer: id, region, dst, amount: if amount.is_finite() { amount } else { 1.0 }, protect, skin_tones }) -} - -/// The scaled pixels: `img` (`w`×`h`, `fmt`) seam-carved to `nw`×`nh` where the protection -/// (`protect`, one value per pixel, and the skin tones when asked) steers the seams, blended with -/// a plain resample by `amount` (0..1). Checks `ctx` for cancellation before every seam. -#[allow(clippy::too_many_arguments)] -fn cas_pixels( - ctx: &crate::jobs::JobCtx, - label: &str, - img: &[f32], - (w, h): (usize, usize), - fmt: PixelFormat, - mut protect: Option>, - skin_tones: bool, - (nw, nh): (usize, usize), - amount: f32, -) -> Result> { - use photocraft_algo::seam::{carve_with, resize_bilinear, skin_mask}; - let n = fmt.channels(); - if skin_tones { - let rgba: Vec = img.chunks_exact(n).flat_map(|px| to_rgba(&fmt, px)).collect(); - let skin = skin_mask(w, h, 4, &rgba); - protect = Some(match protect { - Some(pm) => pm.iter().zip(&skin).map(|(a, b)| a.max(*b)).collect(), - None => skin, - }); - } - ctx.check()?; - let carved = if amount > 0.0 { - ctx.stage(0.05, 0.95, label, |ctl| carve_with(w, h, n, img, protect.as_deref(), nw, nh, ctl)).map_err(|_| EngineError::Cancelled)? - } else { - Vec::new() - }; - let plain = if amount < 1.0 { resize_bilinear(w, h, n, img, nw, nh) } else { Vec::new() }; - Ok(match (carved.is_empty(), plain.is_empty()) { - (false, true) => carved, - (true, false) => plain, - _ => carved.iter().zip(&plain).map(|(c, l)| l + (c - l) * amount).collect::>(), - }) -} - -fn content_aware_scale(s: &mut Session, p: &Value) -> Result { - let CasPlan { doc, layer: id, region, dst, amount, protect: protect_mask, skin_tones } = cas_plan(s, p)?; - let (w, h) = (region.width() as usize, region.height() as usize); - let (nw, nh) = (dst.width() as usize, dst.height() as usize); - let label = "Content-Aware Scale"; - // A background job when started with `Session::start` (#210): seam carving runs on a worker - // against the document snapshot and checks for cancellation before every seam. - crate::jobs::run( - s, - label, - true, - move |ctx| { - ctx.progress(0.0, label); - let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; - let img = surf.read_region(region); - let protect: Option> = - protect_mask.map(|m| (0..w * h).map(|i| m.sample_channel(region.x0 + (i % w) as i32, region.y0 + (i / w) as i32, 0)).collect()); - cas_pixels(ctx, label, &img, (w, h), surf.format(), protect, skin_tones, (nw, nh), amount) - }, - move |s, out| { - s.edit(label, |doc, _| { - let surf = writable_surface(doc, id)?; - crate::pixels::try_clear_surface(surf, region, None)?; - surf.write_region(dst, &out); - surf.prune(); - Ok(()) - })?; - Ok(json!({"from": [w, h], "to": [nw, nh], "bounds": [dst.x0, dst.y0, nw, nh]})) - }, - ) -} - -/// Content-Aware Scale on a reduced copy, for the transform box's live preview (#3096): the -/// command's own carving, on the area scaled down so the longer of its sides before and after -/// is at most `max_side` px. Prepared from the session ([`ContentAwareScalePreview::new`]) and -/// [`run`](ContentAwareScalePreview::run) on any thread. -pub struct ContentAwareScalePreview { - plan: CasPlan, - max_side: u32, -} - -impl ContentAwareScalePreview { - /// `p` takes `edit.contentAwareScale`'s params; the same ones fail the same way. - pub fn new(s: &Session, p: &Value, max_side: u32) -> Result { - Ok(Self { plan: cas_plan(s, p)?, max_side: max_side.max(1) }) - } - - /// The area scaled, in document px. - pub fn region(&self) -> Rect { - self.plan.region - } - - /// The reduced sizes of the area before and after: `[w, h, new w, new h]`. - fn reduced(&self) -> [usize; 4] { - let (region, dst) = (self.plan.region, self.plan.dst); - let (w, h, nw, nh) = (region.width(), region.height(), dst.width(), dst.height()); - let k = (f64::from(w.max(h).max(nw).max(nh)) / f64::from(self.max_side)).max(1.0); - let side = |v: u32| ((f64::from(v) / k).round() as usize).max(1); - [side(w), side(h), side(nw), side(nh)] - } - - /// The size of [`run`](Self::run)'s result, px. - pub fn size(&self) -> [u32; 2] { - let [_, _, w, h] = self.reduced(); - [w as u32, h as u32] - } - - /// The scaled pixels at the reduced size ([`size`](Self::size)), in the layer's format, as a - /// surface with its corner at the origin. Checks `ctx` for cancellation before every seam. - pub fn run(&self, ctx: &crate::jobs::JobCtx) -> Result { - let CasPlan { doc, layer, region, dst: _, amount, protect, skin_tones } = &self.plan; - let surf = doc.layer(*layer).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(*layer))?; - let fmt = surf.format(); - let n = fmt.channels(); - let (w, h) = (region.width(), region.height()); - let [pw, ph, pnw, pnh] = self.reduced(); - // Nearest samples of the area (and of the protecting channel) at the reduced size. - let src_x: Vec = (0..pw).map(|i| region.x0 + (((i as f64 + 0.5) * f64::from(w) / pw as f64) as i32).min(w as i32 - 1)).collect(); - let src_y = |j: usize| region.y0 + (((j as f64 + 0.5) * f64::from(h) / ph as f64) as i32).min(h as i32 - 1); - let mut img = Vec::with_capacity(pw * ph * n); - for j in 0..ph { - ctx.check()?; - let row = surf.read_region(Rect::from_xywh(region.x0, src_y(j), w, 1)); - for &x in &src_x { - let at = (x - region.x0) as usize * n; - img.extend_from_slice(row.get(at..at + n).ok_or_else(|| EngineError::Other("preview read out of bounds".into()))?); - } - } - let protect = protect.as_ref().map(|m| (0..pw * ph).map(|i| m.sample_channel(src_x[i % pw], src_y(i / pw), 0)).collect()); - let out = cas_pixels(ctx, "Content-Aware Scale", &img, (pw, ph), fmt, protect, *skin_tones, (pnw, pnh), *amount)?; - let mut s = Surface::new(fmt); - s.write_region(Rect::from_xywh(0, 0, pnw as u32, pnh as u32), &out); - Ok(s) - } -} - -// ------------------------------------------------------------------ Define Brush / Custom Shape - -fn define_brush_preset(s: &mut Session, p: &Value) -> Result { - let name = match p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) { - Some(n) => n.to_string(), - None => { - let n = s.tools.presets.iter().filter(|b| b.name.starts_with("Sampled Brush")).count() + 1; - format!("Sampled Brush {n}") - } - }; - s.execute("brush.defineFromSelection", json!({"name": name})) -} - -/// The path Define Custom Shape uses: `"work"`, a saved path name, else the work path, the -/// active shape layer, the active layer's vector mask, or the last saved path. -pub(crate) fn current_path(doc: &Document, active: Option, spec: Option<&str>) -> Option { - let ok = |p: &Path| !p.subpaths.is_empty(); - match spec { - Some("work") => return doc.work_path.clone().filter(ok), - Some(name) => return doc.paths.iter().find(|n| n.name == name).map(|n| n.path.clone()).filter(ok), - None => {} - } - if let Some(p) = doc.work_path.clone().filter(ok) { - return Some(p); - } - if let Some(l) = active.and_then(|id| doc.layer(id)) { - if let LayerContent::Shape(sh) = &l.content - && ok(&sh.path) - { - return Some(sh.path.clone()); - } - if let Some(vm) = l.vector_mask.as_ref().filter(|v| ok(&v.path)) { - return Some(vm.path.clone()); - } - } - doc.paths.last().map(|n| n.path.clone()).filter(ok) -} - -fn can_define_shape(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - current_path(&d.doc, d.active_layer, None).map(|_| ()).ok_or_else(|| "select a path or shape layer first".into()) -} - -fn define_custom_shape(s: &mut Session, p: &Value) -> Result { - let st = s.active().ok_or(EngineError::NoDocument)?; - let path = current_path(&st.doc, st.active_layer, p.get("path").and_then(Value::as_str)).ok_or_else(|| bad("edit.defineCustomShape", "no such path"))?; - let name = p - .get("name") - .and_then(Value::as_str) - .map(str::trim) - .filter(|n| !n.is_empty()) - .map(str::to_string) - .unwrap_or_else(|| format!("Shape {}", s.edit_state.custom_shapes.len() + 1)); - let shapes = &mut s.edit_state.custom_shapes; - match shapes.iter_mut().find(|c| c.name == name) { - Some(c) => c.path = path, - None => shapes.push(CustomShape { name: name.clone(), path }), - } - Ok(json!({"name": name, "count": shapes.len()})) -} - -// ------------------------------------------------------------------ Find and Replace Text - -/// Byte ranges of `find` in `text` (case-insensitive unless `case`; whole words only with `whole`). -pub fn find_matches(text: &str, find: &str, case: bool, whole: bool) -> Vec<(usize, usize)> { - if find.is_empty() { - return Vec::new(); - } - let norm = |c: char| -> String { if case { c.to_string() } else { c.to_lowercase().collect() } }; - let needle: String = find.chars().map(norm).collect(); - let mut out = Vec::new(); - let mut at = 0; - while at < text.len() { - // Compare char by char so case folding that changes byte lengths stays aligned. - let mut hay = String::new(); - let mut end = at; - for (i, c) in text[at..].char_indices() { - if hay.len() >= needle.len() { - break; - } - hay.push_str(&norm(c)); - end = at + i + c.len_utf8(); - } - if hay == needle { - let word = |c: Option| c.is_some_and(|c| c.is_alphanumeric() || c == '_'); - let before = text[..at].chars().next_back(); - let after = text[end..].chars().next(); - if !whole || (!word(before) && !word(after)) { - out.push((at, end)); - at = end; - continue; - } - } - at += text[at..].chars().next().map_or(1, char::len_utf8); - } - out -} - -fn type_layers(doc: &Document, forward: bool) -> Vec { - // Layers panel order: top first. - let mut ids: Vec = - doc.walk().into_iter().rev().filter(|(p, _, l)| matches!(l.content, LayerContent::Text(_)) && !doc.locks_at(p).all).map(|(_, _, l)| l.id).collect(); - if !forward { - ids.reverse(); - } - ids -} - -fn has_type_layer(s: &Session) -> std::result::Result<(), String> { - let d = s.active().ok_or("no document open")?; - if type_layers(&d.doc, true).is_empty() { Err("the document has no type layers".into()) } else { Ok(()) } -} - -fn find_replace(s: &mut Session, p: &Value) -> Result { - let cmd = "edit.findAndReplaceText"; - let find = p.get("find").and_then(Value::as_str).filter(|f| !f.is_empty()).ok_or_else(|| bad(cmd, "missing `find`"))?.to_string(); - let replace = str_or(p, "replace", "").to_string(); - let (case, whole, forward, all_layers) = - (bool_or(p, "caseSensitive", false), bool_or(p, "wholeWord", false), bool_or(p, "forward", true), bool_or(p, "allLayers", true)); - let action = str_or(p, "action", "changeAll").to_string(); - let st = s.active().ok_or(EngineError::NoDocument)?; - let mut layers = type_layers(&st.doc, forward); - if !all_layers { - let active = layer_param(s, p).ok(); - layers.retain(|id| Some(*id) == active); - } - let text_of = |doc: &Document, id: LayerId| -> Option { - match &doc.layer(id)?.content { - LayerContent::Text(t) => Some(t.text.clone()), - _ => None, - } - }; - match action.as_str() { - "changeAll" => { - let doc = st.doc.clone(); - let plan: Vec<(LayerId, Vec<(usize, usize)>)> = - layers.iter().filter_map(|id| Some((*id, find_matches(&text_of(&doc, *id)?, &find, case, whole)))).filter(|(_, m)| !m.is_empty()).collect(); - let count: usize = plan.iter().map(|(_, m)| m.len()).sum(); - if count == 0 { - return Ok(json!({"count": 0, "layers": 0})); - } - s.edit("Replace All Text", |doc, _| { - let (dpi, format) = (doc.resolution_dpi, doc.pixel_format()); - for (id, matches) in &plan { - if let Some(LayerContent::Text(t)) = doc.layer_mut(*id).map(|l| &mut l.content) { - for (a, b) in matches.iter().rev() { - crate::type_cmds::replace_text(t, *a, *b, &replace); - } - crate::type_cmds::refresh_at(dpi, format, t); - } - } - Ok(()) - })?; - s.edit_state.find_cursor = None; - Ok(json!({"count": count, "layers": plan.len()})) - } - "find" | "change" | "changeFind" => { - let doc = st.doc.clone(); - let cursor = s.edit_state.find_cursor; - let mut changed = None; - if action != "find" - && let Some((id, a, b)) = cursor - && text_of(&doc, id).is_some_and(|t| find_matches(&t, &find, case, whole).contains(&(a, b))) - { - crate::type_cmds::check_text_unlocked(&doc, id)?; - s.edit("Replace Text", |doc, _| { - let (dpi, format) = (doc.resolution_dpi, doc.pixel_format()); - if let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) { - crate::type_cmds::replace_text(t, a, b, &replace); - crate::type_cmds::refresh_at(dpi, format, t); - } - Ok(()) - })?; - let end = a + replace.len(); - // Collapse the cursor on the side the search moves away from, so the next search - // skips the replaced text even when the replacement still matches. - let c = if forward { end } else { a }; - s.edit_state.find_cursor = Some((id, c, c)); - changed = Some((id, a, end)); - if action == "change" { - return Ok(json!({"changed": {"layer": id.0, "start": a, "end": end}})); - } - } - // Find the next match after the cursor (wrapping through the layers). - let doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); - let cursor = s.edit_state.find_cursor; - let start = cursor.and_then(|(id, _, _)| layers.iter().position(|l| *l == id)).unwrap_or(0); - for k in 0..=layers.len() { - // `allLayers: false` with a non-type layer active leaves no layers to search (#703). - let Some(&id) = layers.get((start + k) % layers.len().max(1)) else { break }; - let Some(text) = text_of(&doc, id) else { continue }; - let ms = find_matches(&text, &find, case, whole); - let hit = match (k, cursor) { - (0, Some((cid, a, b))) if cid == id => { - if forward { - ms.into_iter().find(|m| m.0 >= b) - } else { - ms.into_iter().rev().find(|m| m.1 <= a) - } - } - _ => { - if forward { - ms.into_iter().next() - } else { - ms.into_iter().next_back() - } - } - }; - if let Some((a, b)) = hit { - s.edit_state.find_cursor = Some((id, a, b)); - let _ = s.select_layer(id); - return Ok( - json!({"found": {"layer": id.0, "start": a, "end": b, "text": &text[a..b]}, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))}), - ); - } - } - s.edit_state.find_cursor = None; - Ok(json!({"found": null, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))})) - } - other => Err(bad(cmd, format!("unknown action `{other}` (find|change|changeFind|changeAll)"))), - } -} - -// ------------------------------------------------------------------ presets - -/// Libraries the Preset Manager edits (patterns export as `.pat` with `pattern.export`). -const PRESET_KINDS: [&str; 3] = ["brushes", "customShapes", "patterns"]; - -fn preset_names(s: &Session, kind: &str) -> Option> { - Some(match kind { - "brushes" => s.tools.presets.iter().map(|b| b.name.clone()).collect(), - "customShapes" => s.edit_state.custom_shapes.iter().map(|c| c.name.clone()).collect(), - "patterns" => s.patterns.items.iter().map(|p| p.name.clone()).collect(), - _ => return None, - }) -} - -fn preset_index(s: &Session, kind: &str, p: &Value) -> Result { - let names = preset_names(s, kind).ok_or_else(|| bad("edit.presets.presetManager", format!("unknown preset kind `{kind}` ({})", PRESET_KINDS.join("|"))))?; - if let Some(i) = p.get("index").and_then(Value::as_u64) { - return if (i as usize) < names.len() { Ok(i as usize) } else { Err(bad("edit.presets.presetManager", format!("no preset {i}"))) }; - } - let name = p.get("name").and_then(Value::as_str).ok_or_else(|| bad("edit.presets.presetManager", "give `index` or `name`"))?; - names.iter().position(|n| n == name).ok_or_else(|| bad("edit.presets.presetManager", format!("no preset named `{name}`"))) -} - -fn preset_manager(s: &mut Session, p: &Value) -> Result { - let cmd = "edit.presets.presetManager"; - let action = str_or(p, "action", "list"); - if action == "list" { - let kinds: Vec<&str> = match p.get("kind").and_then(Value::as_str) { - Some(k) => vec![k], - None => PRESET_KINDS.to_vec(), - }; - let mut out = serde_json::Map::new(); - for k in kinds { - out.insert(k.to_string(), json!(preset_names(s, k).ok_or_else(|| bad(cmd, format!("unknown preset kind `{k}`")))?)); - } - return Ok(Value::Object(out)); - } - let kind = p.get("kind").and_then(Value::as_str).ok_or_else(|| bad(cmd, "missing `kind`"))?.to_string(); - let i = preset_index(s, &kind, p)?; - match action { - "rename" => { - let new = - p.get("newName").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "missing `newName`"))?.to_string(); - match kind.as_str() { - // Same rules as Brush Settings: no duplicate names (case-insensitive), the current - // preset follows, a renamed built-in is the user's preset now (and persists as one). - "brushes" => crate::brush_preset_cmds::rename_at(s, i, &new, cmd)?, - "patterns" => s.patterns.items[i].name = new, - _ => s.edit_state.custom_shapes[i].name = new, - } - } - "delete" => match kind.as_str() { - "brushes" => { - let gone = s.tools.presets.remove(i); - crate::brush_cmds::forget_deleted_preset(s, &gone.name); - } - "patterns" => drop(s.patterns.items.remove(i)), - _ => drop(s.edit_state.custom_shapes.remove(i)), - }, - "move" => { - let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "missing `to`"))? as usize; - match kind.as_str() { - "brushes" => crate::move_item(&mut s.tools.presets, i, to), - "patterns" => crate::move_item(&mut s.patterns.items, i, to), - _ => crate::move_item(&mut s.edit_state.custom_shapes, i, to), - }; - } - other => return Err(bad(cmd, format!("unknown action `{other}` (list|rename|delete|move)"))), - } - if kind == "brushes" { - s.brush_presets_changed(); - } - Ok(json!({kind.clone(): preset_names(s, &kind)})) -} - -/// Exported preset file (`.pcpresets`, JSON). -#[derive(Clone, Debug, Default, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct PresetFile { - pub format: String, - pub version: u32, - pub brushes: Vec, - pub custom_shapes: Vec, - pub tool_presets: Vec, -} - -pub const PRESET_FORMAT: &str = "photocraft-presets"; - fn export_import(s: &mut Session, p: &Value) -> Result { let cmd = "edit.presets.exportImportPresets"; let kinds: Vec = p @@ -1511,6 +291,27 @@ macro_rules! spec { }; } +mod content_aware; +mod content_aware_scale; +mod fade; +mod find_replace; +mod presets; +mod purge; + +pub(crate) use content_aware::channel_mask; +pub use content_aware::{CafPlan, FillEdit, MAX_CAF_EDITS, MAX_CAF_POINTS, SelOp, content_aware_plan, content_aware_plan_with}; +use content_aware::{can_caf, content_aware_fill, delete_and_fill}; +pub use content_aware_scale::ContentAwareScalePreview; +use content_aware_scale::content_aware_scale; +pub use fade::fade_surface; +use fade::{can_fade, fade}; +pub use find_replace::find_matches; +use find_replace::{find_replace, has_type_layer}; +pub(crate) use presets::current_path; +pub use presets::{PRESET_FORMAT, PresetFile}; +use presets::{can_define_shape, define_brush_preset, define_custom_shape, preset_manager}; +use purge::{can_purge_all, can_purge_clipboard, can_purge_histories, can_purge_undo, purge}; + pub fn specs() -> Vec { vec![ spec!( diff --git a/crates/engine/src/edit_menu_cmds/content_aware.rs b/crates/engine/src/edit_menu_cmds/content_aware.rs new file mode 100644 index 0000000000..0fe3cedd3f --- /dev/null +++ b/crates/engine/src/edit_menu_cmds/content_aware.rs @@ -0,0 +1,531 @@ +use super::*; + +// ------------------------------------------------------------------ Content-Aware Fill + +pub(super) fn can_caf(s: &Session) -> std::result::Result<(), String> { + pixel_layer(s)?; + let d = s.active().ok_or("no document open")?; + if d.doc.selection.as_ref().is_none_or(|m| m.content_bounds().is_empty()) { + return Err("make a selection around what to remove".into()); + } + Ok(()) +} + +/// Mask surface (gray) of an alpha channel by index or name. +pub(crate) fn channel_mask<'a>(doc: &'a Document, v: &Value) -> Option<&'a Surface> { + match v { + Value::Number(n) => doc.channels.get(n.as_u64()? as usize).map(|c| &c.surface), + Value::String(name) => doc.channels.iter().find(|c| c.name == *name).map(|c| &c.surface), + _ => None, + } +} + +/// `key` as an `[x, y, w, h]` rectangle. The saturating float→int casts bound each component; +/// the additions saturate too — `area: [1e30, 0, 1e30, 10]` is a whole-canvas window, not an +/// overflow (it panicked in debug builds before the `saturating_add`). +fn rect_param(p: &Value, key: &str, cmd: &str) -> Result { + let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y, w, h]")))?; + let n = |i: usize| { + a.get(i) + .and_then(Value::as_f64) + .filter(|f| f.is_finite()) + .map(|v| v.round() as i32) + .ok_or_else(|| bad(cmd, format!("`{key}` must be four finite numbers"))) + }; + let (x, y, w, h) = (n(0)?, n(1)?, n(2)?, n(3)?); + Ok(Rect::new(x, y, x.saturating_add(w.max(0)), y.saturating_add(h.max(0)))) +} + +pub(super) fn content_aware_fill(s: &mut Session, p: &Value) -> Result { + content_aware_fill_as(s, p, "edit.contentAwareFill", "Content-Aware Fill") +} + +/// Delete and Fill Selection (#1286): Photoshop's one-click removal from the selection-tool +/// context menu. Content-Aware Fill into the layer, no dialog, sampling as Edit › Fill does (the +/// whole window, measured on Photoshop 25.4) with the default colour adaptation. +pub(super) fn delete_and_fill(s: &mut Session, _: &Value) -> Result { + content_aware_fill_as(s, &json!({"sampling": "rectangular"}), "edit.deleteAndFillSelection", "Delete and Fill Selection") +} + +/// Everything one Content-Aware Fill needs, worked out from the document and the command's +/// params. The Content-Aware Fill workspace runs exactly this for its preview, so what it shows +/// is what OK and Apply write. +pub struct CafPlan { + pub layer: LayerId, + /// The rectangle worked on: the sampling window, and any sampling-brush strokes or custom + /// area beyond it. + pub rect: Rect, + /// Photoshop's sampling window around the fill area (`content_aware::sampling_window`). + pub window: Rect, + pub fmt: PixelFormat, + /// What is sampled over `rect`: the target's pixels, or with Sample All Layers the visible + /// composite in the target's encoding. + pub img: Vec, + /// The target's own pixels over `rect` when they differ from `img` (Sample All Layers); see + /// [`CafPlan::layer_pixels`]. + pub layer_px: Option>, + /// The fill area (selection coverage, after the workspace's lasso edits) over `rect`. + pub cover: Vec, + pub hole: Vec, + /// What may be copied from: the sampling option's area before the brush strokes, and after. + pub base: Vec, + pub source: Vec, + pub opts: photocraft_algo::content_aware::FillOptions, + pub output: String, +} + +impl CafPlan { + /// The target layer's pixels over `rect`. + pub fn layer_pixels(&self) -> &[f32] { + self.layer_px.as_deref().unwrap_or(&self.img) + } +} + +/// The workspace's lasso edits of the fill area: `{"op": "new|add|subtract|intersect", "points": +/// [[x, y], ...]}` or `{"op": "expand|contract", "by": px}`, applied in order. +#[derive(Clone, Debug, PartialEq)] +pub enum FillEdit { + Lasso { op: SelOp, points: Vec<[f64; 2]> }, + Grow(i32), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SelOp { + New, + Add, + Subtract, + Intersect, +} + +/// Most `fillEdits` and `samplingStrokes` one fill takes, and most points in all of them +/// together: the strokes and lassos are painted pixel by pixel, segment by segment. +pub const MAX_CAF_EDITS: usize = 1_000; + +pub const MAX_CAF_POINTS: usize = 200_000; + +fn points_param(v: &Value, cmd: &str, what: &str, budget: &mut usize) -> Result> { + let a = v.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("{what} needs `points` [[x, y], ...]")))?; + *budget = budget.checked_sub(a.len()).ok_or_else(|| bad(cmd, format!("at most {MAX_CAF_POINTS} points in all fill edits and sampling strokes")))?; + a.iter() + .map(|p| { + let x = p.get(0).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() < 1e7); + let y = p.get(1).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() < 1e7); + match (x, y) { + (Some(x), Some(y)) => Ok([x, y]), + _ => Err(bad(cmd, format!("{what} points must be pairs of finite numbers"))), + } + }) + .collect() +} + +/// `p[key]` as an array of at most [`MAX_CAF_EDITS`] entries (empty when absent). +fn edits_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a [Value]> { + let Some(a) = p.get(key) else { return Ok(&[]) }; + let a = a.as_array().ok_or_else(|| bad(cmd, format!("`{key}` must be an array")))?; + if a.len() > MAX_CAF_EDITS { + return Err(bad(cmd, format!("`{key}` takes at most {MAX_CAF_EDITS} entries"))); + } + Ok(a) +} + +fn fill_edits(p: &Value, cmd: &str, budget: &mut usize) -> Result> { + edits_param(p, "fillEdits", cmd)? + .iter() + .map(|e| { + let op = e.get("op").and_then(Value::as_str).unwrap_or(""); + Ok(match op { + "expand" | "contract" => { + let by = e + .get("by") + .and_then(Value::as_f64) + .filter(|v| v.is_finite() && (0.0..=1000.0).contains(v)) + .ok_or_else(|| bad(cmd, "`by` must be 0..1000 px"))?; + FillEdit::Grow(if op == "expand" { by.round() as i32 } else { -(by.round() as i32) }) + } + "new" | "add" | "subtract" | "intersect" => FillEdit::Lasso { + op: match op { + "new" => SelOp::New, + "add" => SelOp::Add, + "subtract" => SelOp::Subtract, + _ => SelOp::Intersect, + }, + points: points_param(e, cmd, "a lasso edit", budget)?, + }, + o => return Err(bad(cmd, format!("unknown fill edit `{o}` (new|add|subtract|intersect|expand|contract)"))), + }) + }) + .collect() +} + +fn sampling_strokes(p: &Value, cmd: &str, budget: &mut usize) -> Result> { + edits_param(p, "samplingStrokes", cmd)? + .iter() + .map(|e| { + let add = match e.get("mode").and_then(Value::as_str).unwrap_or("add") { + "add" => true, + "subtract" => false, + o => return Err(bad(cmd, format!("unknown stroke mode `{o}` (add|subtract)"))), + }; + let size = e + .get("size") + .and_then(Value::as_f64) + .filter(|v| v.is_finite() && (1.0..=5000.0).contains(v)) + .ok_or_else(|| bad(cmd, "a stroke's `size` must be 1..5000 px"))?; + Ok(photocraft_algo::content_aware::SamplingStroke { add, size, points: points_param(e, cmd, "a sampling stroke", budget)? }) + }) + .collect() +} + +/// A Content-Aware Fill's params, checked against the document before any pixel is read. +struct CafParams<'a> { + sel: &'a Surface, + /// The selection's bounds on the canvas. + sb: Rect, + edits: Vec, + strokes: Vec, + sampling: String, + custom_mask: Option<&'a Surface>, + custom_rect: Option, + opts: photocraft_algo::content_aware::FillOptions, + output: String, + surf: &'a Surface, +} + +fn caf_params<'a>(doc: &'a Document, id: LayerId, p: &Value, cmd: &str) -> Result> { + use photocraft_algo::content_aware::{FillOptions, color_level, rotation_level}; + let sel = doc.selection.as_ref().ok_or_else(|| bad(cmd, "no selection"))?; + let sb = sel.content_bounds().intersect(&doc.bounds()); + if sb.is_empty() { + return Err(bad(cmd, "the selection is outside the canvas")); + } + let mut budget = MAX_CAF_POINTS; + let edits = fill_edits(p, cmd, &mut budget)?; + let strokes = sampling_strokes(p, cmd, &mut budget)?; + let sampling = str_or(p, "sampling", "auto").to_string(); + let custom_mask: Option<&Surface> = p.get("channel").and_then(|v| channel_mask(doc, v)); + let custom_rect = if p.get("area").is_some() { Some(rect_param(p, "area", cmd)?) } else { None }; + match sampling.as_str() { + "auto" | "rectangular" => {} + // The workspace's Custom: only what the Sampling Brush adds. + "custom" if custom_rect.is_some() || custom_mask.is_some() || strokes.iter().any(|s| s.add) => {} + "custom" => return Err(bad(cmd, "custom sampling needs `area` [x,y,w,h], `channel` (alpha channel index or name) or `samplingStrokes`")), + other => return Err(bad(cmd, format!("unknown sampling `{other}` (auto|rectangular|custom)"))), + } + let opts = FillOptions { + color_adaptation: color_level(str_or(p, "colorAdaptation", "default")), + rotations: rotation_level(str_or(p, "rotationAdaptation", "none")), + scale: bool_or(p, "scale", false), + mirror: bool_or(p, "mirror", false), + seed: p.get("seed").and_then(Value::as_u64).unwrap_or(1), + }; + let output = str_or(p, "output", "current").to_string(); + if !matches!(output.as_str(), "current" | "new" | "duplicate") { + return Err(bad(cmd, "`output` must be current|new|duplicate")); + } + let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; + Ok(CafParams { sel, sb, edits, strokes, sampling, custom_mask, custom_rect, opts, output, surf }) +} + +/// Work out a Content-Aware Fill (see [`CafPlan`]) on layer `id` of `doc`. +pub fn content_aware_plan(doc: &Document, id: LayerId, p: &Value, cmd: &str) -> Result { + content_aware_plan_with(doc, id, p, cmd, &photocraft_raster::Interrupt::NONE) +} + +/// [`content_aware_plan`], asking `ctl` row by row whether to stop ([`EngineError::Cancelled`]). +pub fn content_aware_plan_with(doc: &Document, id: LayerId, p: &Value, cmd: &str, ctl: &photocraft_raster::Interrupt) -> Result { + use photocraft_algo::content_aware::{auto_sampling_with, grow_mask, paint_strokes, polygon_mask}; + use rayon::prelude::*; + + use crate::fill_cmds::{read_window, read_window_mask}; + let CafParams { sel, sb, edits, strokes, sampling, custom_mask, custom_rect, opts, output, surf } = caf_params(doc, id, p, cmd)?; + let canvas = doc.bounds(); + let cancel = || ctl.cancelled(); + let stop = || if ctl.cancelled() { Err(EngineError::Cancelled) } else { Ok(()) }; + // The fill area: the selection, then the lasso edits, over a rectangle that holds them all. + let grow: i32 = edits.iter().map(|e| if let FillEdit::Grow(b) = e { b.max(&0) } else { &0 }).sum(); + let reach = edits.iter().fold(sb, |r, e| match e { + FillEdit::Lasso { points, .. } => { + points.iter().fold(r, |r, q| r.union(&Rect::new(q[0].floor() as i32, q[1].floor() as i32, q[0].floor() as i32 + 1, q[1].floor() as i32 + 1))) + } + FillEdit::Grow(_) => r, + }); + let er = reach.inflate(grow.saturating_add(1)).intersect(&canvas); + let (ew, eh) = crate::fill_cmds::window_size(er)?; + let ecover = read_window_mask(sel, er, &cancel).ok_or(EngineError::Cancelled)?; + let mut ehole: Vec = ecover.par_iter().map(|c| *c > 0.0).collect(); + for e in &edits { + stop()?; + match e { + FillEdit::Lasso { op, points } => { + let m = polygon_mask(er, points); + for (h, v) in ehole.iter_mut().zip(&m) { + *h = match op { + SelOp::New => *v, + SelOp::Add => *h || *v, + SelOp::Subtract => *h && !*v, + SelOp::Intersect => *h && *v, + }; + } + } + FillEdit::Grow(by) => ehole = grow_mask(&ehole, ew, eh, *by), + } + } + let (bx0, by0, bx1, by1) = mask_bounds(ew, eh, &ehole); + if bx1 <= bx0 { + return Err(bad(cmd, "the fill area is empty")); + } + let hb = Rect::new(er.x0 + bx0 as i32, er.y0 + by0 as i32, er.x0 + bx1 as i32, er.y0 + by1 as i32); + // Photoshop's window (`content_aware::sampling_window`) for Auto and Rectangular; `margin` + // asks for a rectangle that far around the fill area instead. + let window = match sampling.as_str() { + "rectangular" => match int(p, "margin") { + Some(m) => hb.inflate(m.clamp(0, 100_000) as i32), + None => crate::fill_cmds::sampling_window(hb, canvas), + }, + "custom" => match (custom_rect, custom_mask) { + (Some(r), _) => r, + (None, Some(m)) => m.content_bounds(), + (None, None) => hb, + } + .union(&hb) + .inflate(4), + _ => crate::fill_cmds::sampling_window(hb, canvas), + } + .intersect(&canvas); + // Strokes that add to the sampling area may reach past the window. + let rect = strokes.iter().filter(|s| s.add).fold(window, |r, s| r.union(&s.bounds())).intersect(&canvas); + let fmt = surf.format(); + // Photoshop's Sample All Layers checkbox is off unless the caller asks. When the active + // layer has no pixels in the window there is nothing to sample, so that case uses the + // visible composite (#4026). An explicit false still reads only this layer. + let sample_all = match p.get("sampleAllLayers").and_then(Value::as_bool) { + Some(v) => v, + None => surf.content_bounds().intersect(&window).is_empty(), + }; + let n = fmt.channels(); + // Refuse a window too large to read before allocating for it, whatever the sampling (#963). + let (w, h) = crate::fill_cmds::window_size(rect)?; + let pixels = read_window(surf, rect, &cancel).ok_or(EngineError::Cancelled)?; + let (img, layer_px) = if sample_all { + stop()?; + (crate::retouch_cmds::composite_region(doc, Some(id), crate::retouch_cmds::SampleLayers::All, rect, fmt).data, Some(pixels)) + } else { + (pixels, None) + }; + stop()?; + let mut cover = vec![0.0f32; w * h]; + let mut hole = vec![false; w * h]; + cover.par_chunks_mut(w.max(1)).zip(hole.par_chunks_mut(w.max(1))).enumerate().try_for_each(|(y, (crow, hrow))| { + stop()?; + let dy = rect.y0 + y as i32; + if dy < er.y0 || dy >= er.y1 { + return Ok(()); + } + for (x, (c, hl)) in crow.iter_mut().zip(hrow.iter_mut()).enumerate() { + let dx = rect.x0 + x as i32; + if dx >= er.x0 && dx < er.x1 { + let j = (dy - er.y0) as usize * ew + (dx - er.x0) as usize; + let (eh, ec) = (ehole.get(j).copied().unwrap_or(false), ecover.get(j).copied().unwrap_or(0.0)); + *hl = eh; + // Pixels the lasso added are filled outright; selected ones by their coverage. + *c = if eh { if ec > 0.0 { ec } else { 1.0 } } else { 0.0 }; + } + } + Ok::<(), EngineError>(()) + })?; + drop((ecover, ehole)); + // The sampling option's area: Auto keeps what looks like the surroundings within the window, + // Rectangular the whole window, Custom the given area (or nothing, for the brush to add to). + let mut base = vec![false; w * h]; + match sampling.as_str() { + "auto" | "rectangular" => { + let (ww, wh) = (window.width() as usize, window.height() as usize); + let (ox, oy) = ((window.x0 - rect.x0) as usize, (window.y0 - rect.y0) as usize); + let area: Vec = match sampling.as_str() { + "auto" if window == rect => auto_sampling_with(w, h, n, &img, &hole, ctl).map_err(|_| EngineError::Cancelled)?, + "auto" => { + let mut wimg = vec![0.0f32; ww * wh * n]; + let mut whole = vec![false; ww * wh]; + for y in 0..wh { + let s = ((oy + y) * w + ox) * n; + wimg[y * ww * n..(y + 1) * ww * n].copy_from_slice(&img[s..s + ww * n]); + whole[y * ww..(y + 1) * ww].copy_from_slice(&hole[(oy + y) * w + ox..(oy + y) * w + ox + ww]); + } + auto_sampling_with(ww, wh, n, &wimg, &whole, ctl).map_err(|_| EngineError::Cancelled)? + } + _ => vec![true; ww * wh], + }; + for y in 0..wh { + base[(oy + y) * w + ox..(oy + y) * w + ox + ww].copy_from_slice(&area[y * ww..(y + 1) * ww]); + } + } + _ => match (custom_rect, custom_mask) { + (Some(r), _) => base.par_iter_mut().enumerate().for_each(|(i, b)| *b = r.contains(rect.x0 + (i % w) as i32, rect.y0 + (i / w) as i32)), + (None, Some(m)) => { + let v = read_window_mask(m, rect, &cancel).ok_or(EngineError::Cancelled)?; + base.par_iter_mut().zip(&v).for_each(|(b, v)| *b = *v > 0.5); + } + (None, None) => {} + }, + } + stop()?; + base.par_iter_mut().zip(&hole).for_each(|(b, h)| *b &= !*h); + let mut source = base.clone(); + paint_strokes(&mut source, rect, &strokes); + source.par_iter_mut().zip(&hole).for_each(|(s, h)| *s &= !*h); + Ok(CafPlan { layer: id, rect, window, fmt, img, layer_px, cover, hole, base, source, opts, output }) +} + +fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: &'static str) -> Result { + use photocraft_algo::content_aware::fill_owned; + // The workspace names the layer it opened on: after an Apply to a new layer that one is + // active, but the fill still samples the original. + let id = match p.get("layer").and_then(Value::as_u64) { + Some(l) => pixel_layer_id(s, LayerId(l)), + None => pixel_layer(s), + } + .map_err(EngineError::Other)?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let doc = st.doc.clone(); + // Check the params before the job starts. + caf_params(&doc, id, p, cmd)?; + let p = p.clone(); + // A background job when started with `Session::start` (#210): working out the fill area and + // the sampling area, reading the pixels and the PatchMatch fill run on a worker against the + // document snapshot, cancellable per row band. + crate::jobs::run( + s, + label, + true, + move |ctx| { + use rayon::prelude::*; + ctx.progress(0.0, label); + let cancel = || ctx.cancelled(); + let plan = content_aware_plan_with(&doc, id, &p, cmd, &photocraft_raster::Interrupt::cancel_only(&cancel))?; + let CafPlan { layer, rect, fmt, img, layer_px, cover, hole, source, opts, output, .. } = plan; + // Patches come only from the sampling area outside the fill area. With none (a + // Rectangular `margin` of 0, a Custom area inside the selection or off the canvas) + // the fill would be black (#6532), so refuse instead. The workspace's preview builds + // the same plan and may show an empty area while the Sampling Brush adds to it. + if !source.iter().any(|s| *s) { + return Err(bad(cmd, "nothing to sample from: the sampling area has no pixels outside the fill area")); + } + let (w, h) = (rect.width() as usize, rect.height() as usize); + let n = fmt.channels(); + // The fill changes only the fill area: keep the layer's pixels and the coverage over + // its bounds for the apply step, and fill the sampled pixels themselves. + let (bx0, by0, bx1, by1) = mask_bounds(w, h, &hole); + let own = layer_px.as_deref().unwrap_or(&img); + let original: Vec = (by0..by1).flat_map(|y| own[(y * w + bx0) * n..(y * w + bx1) * n].iter().copied()).collect(); + let cover: Vec = (by0..by1).flat_map(|y| cover[y * w + bx0..y * w + bx1].iter().copied()).collect(); + let n_hole = cover.iter().filter(|c| **c > 0.0).count(); + ctx.check()?; + let mut filled = ctx.stage(0.05, 1.0, label, |ctl| fill_owned(w, h, n, img, &hole, &source, &opts, ctl)).map_err(|_| EngineError::Cancelled)?; + // Sampled from all layers: outside the fill area the window keeps the layer's pixels. + if let Some(own) = layer_px { + filled.par_chunks_mut(n.max(1)).zip(own.par_chunks(n.max(1))).zip(hole.par_iter()).for_each(|((f, o), h)| { + if !*h { + f.copy_from_slice(o); + } + }); + } + Ok((layer, rect, fmt, output, FilledWindow { filled, bounds: (bx0, by0, bx1, by1), original, cover, n_hole })) + }, + move |s, (layer, rect, fmt, output, done)| apply_content_aware_fill(s, label, layer, &output, fmt, rect, done), + ) +} + +/// A Content-Aware Fill's result for its apply step: the filled window (the same as the +/// original outside the selected pixels) and, over the bounds of the selected pixels (in window +/// coordinates), the original pixels and the selection's coverage. +struct FilledWindow { + filled: Vec, + bounds: (usize, usize, usize, usize), + original: Vec, + cover: Vec, + n_hole: usize, +} + +/// `f(window index, index over the bounds, coverage)` for each selected pixel of a +/// [`FilledWindow`] (`w` wide). +fn each_selected(w: usize, (bx0, by0, bx1, by1): (usize, usize, usize, usize), cover: &[f32], mut f: impl FnMut(usize, usize, f32)) { + let bw = bx1.saturating_sub(bx0); + for y in by0..by1 { + for x in bx0..bx1 { + let k = (y - by0) * bw + (x - bx0); + if let Some(&c) = cover.get(k) + && c > 0.0 + { + f(y * w + x, k, c); + } + } + } +} + +/// Bounds `(x0, y0, x1, y1)` of the set cells of a `w × h` mask (all zero when there are none). +fn mask_bounds(w: usize, h: usize, m: &[bool]) -> (usize, usize, usize, usize) { + use rayon::prelude::*; + if w == 0 { + return (0, 0, 0, 0); + } + let rows: Vec> = + m.par_chunks(w).take(h).map(|row| Some((row.iter().position(|v| *v)?, row.iter().rposition(|v| *v)? + 1))).collect(); + let mut b: Option<(usize, usize, usize, usize)> = None; + for (y, span) in rows.into_iter().enumerate() { + if let Some((x0, x1)) = span { + b = Some(b.map_or((x0, y, x1, y + 1), |(bx0, by0, bx1, _)| (bx0.min(x0), by0, bx1.max(x1), y + 1))); + } + } + b.unwrap_or((0, 0, 0, 0)) +} + +/// Write a Content-Aware Fill result (the job's apply step): into the layer, a new layer or a +/// duplicate, as one undo step. +fn apply_content_aware_fill(s: &mut Session, label: &str, id: LayerId, output: &str, fmt: PixelFormat, window: Rect, done: FilledWindow) -> Result { + let n = fmt.channels(); + let (w, h) = (window.width() as usize, window.height() as usize); + let FilledWindow { mut filled, bounds, original, cover, n_hole } = done; + let layer = s.edit(label, |doc, active| { + let target = match output { + "new" => { + let mut l = Layer::raster(doc.next_layer_name("Content-Aware Fill"), PixelFormat { alpha: true, ..fmt }); + let mut px = vec![0.0f32; w * h * n.max(1)]; + let lf = l.surface().map(|s| s.format()).unwrap_or(fmt); + let ln = lf.channels(); + px.resize(w * h * ln, 0.0); + each_selected(w, bounds, &cover, |i, _, c| { + let rgba = to_rgba(&fmt, &filled[i * n..(i + 1) * n]); + let mut enc = [0.0f32; 8]; + from_rgba_into(&lf, [rgba[0], rgba[1], rgba[2], rgba[3] * c], &mut enc); + px[i * ln..(i + 1) * ln].copy_from_slice(&enc[..ln]); + }); + if let Some(s) = l.surface_mut() { + s.write_region(window, &px); + s.prune(); + } + let nid = doc.insert_above(Some(id), l); + *active = Some(nid); + return Ok(nid); + } + "duplicate" => { + let mut dup = doc.layer(id).ok_or(EngineError::NoLayer(id))?.duplicate(); + dup.name = doc.copy_name(&dup.name); + let nid = doc.insert_above(Some(id), dup); + *active = Some(nid); + nid + } + _ => id, + }; + let surf = writable_surface(doc, target)?; + // The fill blended in by the coverage (elsewhere it is the original). + each_selected(w, bounds, &cover, |i, k, c| { + for ch in 0..n { + let (j, o) = (i * n + ch, k * n + ch); + filled[j] = original[o] + (filled[j] - original[o]) * c; + } + }); + surf.write_region(window, &filled); + Ok(target) + })?; + Ok(json!({"layer": layer.0, "filled": n_hole, "window": [window.x0, window.y0, window.width(), window.height()]})) +} diff --git a/crates/engine/src/edit_menu_cmds/content_aware_scale.rs b/crates/engine/src/edit_menu_cmds/content_aware_scale.rs new file mode 100644 index 0000000000..998f30821a --- /dev/null +++ b/crates/engine/src/edit_menu_cmds/content_aware_scale.rs @@ -0,0 +1,202 @@ +use super::content_aware::channel_mask; +use super::*; + +// ------------------------------------------------------------------ Content-Aware Scale + +/// Reach of Content-Aware Scale's `x`/`y`: the largest document side. +const CAS_POSITION_LIMIT: f64 = 300_000.0; + +/// What Content-Aware Scale does, read from its params against the active document: the +/// command and the transform box's live preview ([`ContentAwareScalePreview`]) share it. +struct CasPlan { + doc: std::sync::Arc, + layer: LayerId, + /// The area scaled: the selection's bounds, else the layer's content. + region: Rect, + /// Where the result goes: `x`, `y` (default: the region's corner), `width`, `height`. + dst: Rect, + amount: f32, + protect: Option, + skin_tones: bool, +} + +fn cas_plan(s: &Session, p: &Value) -> Result { + let cmd = "edit.contentAwareScale"; + let id = pixel_layer(s).map_err(EngineError::Other)?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let doc = st.doc.clone(); + let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; + let region = match &doc.selection { + Some(sel) => sel.content_bounds().intersect(&doc.bounds()), + None => surf.content_bounds(), + }; + if region.is_empty() { + return Err(EngineError::Other("nothing to scale: the layer is empty".into())); + } + let (w, h) = (region.width() as usize, region.height() as usize); + let dim = |k: &str, pct: &str, cur: usize| -> Result { + let v = match (p.get(k).and_then(Value::as_f64), p.get(pct).and_then(Value::as_f64)) { + (Some(px), _) => px, + (None, Some(pc)) => cur as f64 * pc / 100.0, + (None, None) => cur as f64, + }; + if !(1.0..=60_000.0).contains(&v) { + return Err(bad(cmd, format!("`{k}` must be 1..60000 px"))); + } + Ok(v.round() as u32) + }; + let (nw, nh) = (dim("width", "scaleX", w)?, dim("height", "scaleY", h)?); + let at = |k: &str, cur: i32| -> Result { + match p.get(k).filter(|v| !v.is_null()) { + None => Ok(cur), + Some(v) => match v.as_f64() { + Some(x) if (-CAS_POSITION_LIMIT..=CAS_POSITION_LIMIT).contains(&x) => Ok(x.round() as i32), + _ => Err(bad(cmd, format!("`{k}` must be a number of px within ±300000"))), + }, + } + }; + let dst = Rect::from_xywh(at("x", region.x0)?, at("y", region.y0)?, nw, nh); + let amount = f32_or(p, "amount", 100.0).clamp(0.0, 100.0) / 100.0; + // Protection: an alpha channel and/or skin tones. + let protect = match p.get("protect").filter(|v| !v.is_null() && v.as_str() != Some("none")) { + Some(v) => Some(channel_mask(&doc, v).cloned().ok_or_else(|| bad(cmd, "`protect` must name an alpha channel (index or name) or \"none\""))?), + None => None, + }; + let skin_tones = bool_or(p, "protectSkinTones", false); + Ok(CasPlan { doc, layer: id, region, dst, amount: if amount.is_finite() { amount } else { 1.0 }, protect, skin_tones }) +} + +/// The scaled pixels: `img` (`w`×`h`, `fmt`) seam-carved to `nw`×`nh` where the protection +/// (`protect`, one value per pixel, and the skin tones when asked) steers the seams, blended with +/// a plain resample by `amount` (0..1). Checks `ctx` for cancellation before every seam. +#[allow(clippy::too_many_arguments)] +fn cas_pixels( + ctx: &crate::jobs::JobCtx, + label: &str, + img: &[f32], + (w, h): (usize, usize), + fmt: PixelFormat, + mut protect: Option>, + skin_tones: bool, + (nw, nh): (usize, usize), + amount: f32, +) -> Result> { + use photocraft_algo::seam::{carve_with, resize_bilinear, skin_mask}; + let n = fmt.channels(); + if skin_tones { + let rgba: Vec = img.chunks_exact(n).flat_map(|px| to_rgba(&fmt, px)).collect(); + let skin = skin_mask(w, h, 4, &rgba); + protect = Some(match protect { + Some(pm) => pm.iter().zip(&skin).map(|(a, b)| a.max(*b)).collect(), + None => skin, + }); + } + ctx.check()?; + let carved = if amount > 0.0 { + ctx.stage(0.05, 0.95, label, |ctl| carve_with(w, h, n, img, protect.as_deref(), nw, nh, ctl)).map_err(|_| EngineError::Cancelled)? + } else { + Vec::new() + }; + let plain = if amount < 1.0 { resize_bilinear(w, h, n, img, nw, nh) } else { Vec::new() }; + Ok(match (carved.is_empty(), plain.is_empty()) { + (false, true) => carved, + (true, false) => plain, + _ => carved.iter().zip(&plain).map(|(c, l)| l + (c - l) * amount).collect::>(), + }) +} + +pub(super) fn content_aware_scale(s: &mut Session, p: &Value) -> Result { + let CasPlan { doc, layer: id, region, dst, amount, protect: protect_mask, skin_tones } = cas_plan(s, p)?; + let (w, h) = (region.width() as usize, region.height() as usize); + let (nw, nh) = (dst.width() as usize, dst.height() as usize); + let label = "Content-Aware Scale"; + // A background job when started with `Session::start` (#210): seam carving runs on a worker + // against the document snapshot and checks for cancellation before every seam. + crate::jobs::run( + s, + label, + true, + move |ctx| { + ctx.progress(0.0, label); + let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; + let img = surf.read_region(region); + let protect: Option> = + protect_mask.map(|m| (0..w * h).map(|i| m.sample_channel(region.x0 + (i % w) as i32, region.y0 + (i / w) as i32, 0)).collect()); + cas_pixels(ctx, label, &img, (w, h), surf.format(), protect, skin_tones, (nw, nh), amount) + }, + move |s, out| { + s.edit(label, |doc, _| { + let surf = writable_surface(doc, id)?; + crate::pixels::try_clear_surface(surf, region, None)?; + surf.write_region(dst, &out); + surf.prune(); + Ok(()) + })?; + Ok(json!({"from": [w, h], "to": [nw, nh], "bounds": [dst.x0, dst.y0, nw, nh]})) + }, + ) +} + +/// Content-Aware Scale on a reduced copy, for the transform box's live preview (#3096): the +/// command's own carving, on the area scaled down so the longer of its sides before and after +/// is at most `max_side` px. Prepared from the session ([`ContentAwareScalePreview::new`]) and +/// [`run`](ContentAwareScalePreview::run) on any thread. +pub struct ContentAwareScalePreview { + plan: CasPlan, + max_side: u32, +} + +impl ContentAwareScalePreview { + /// `p` takes `edit.contentAwareScale`'s params; the same ones fail the same way. + pub fn new(s: &Session, p: &Value, max_side: u32) -> Result { + Ok(Self { plan: cas_plan(s, p)?, max_side: max_side.max(1) }) + } + + /// The area scaled, in document px. + pub fn region(&self) -> Rect { + self.plan.region + } + + /// The reduced sizes of the area before and after: `[w, h, new w, new h]`. + fn reduced(&self) -> [usize; 4] { + let (region, dst) = (self.plan.region, self.plan.dst); + let (w, h, nw, nh) = (region.width(), region.height(), dst.width(), dst.height()); + let k = (f64::from(w.max(h).max(nw).max(nh)) / f64::from(self.max_side)).max(1.0); + let side = |v: u32| ((f64::from(v) / k).round() as usize).max(1); + [side(w), side(h), side(nw), side(nh)] + } + + /// The size of [`run`](Self::run)'s result, px. + pub fn size(&self) -> [u32; 2] { + let [_, _, w, h] = self.reduced(); + [w as u32, h as u32] + } + + /// The scaled pixels at the reduced size ([`size`](Self::size)), in the layer's format, as a + /// surface with its corner at the origin. Checks `ctx` for cancellation before every seam. + pub fn run(&self, ctx: &crate::jobs::JobCtx) -> Result { + let CasPlan { doc, layer, region, dst: _, amount, protect, skin_tones } = &self.plan; + let surf = doc.layer(*layer).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(*layer))?; + let fmt = surf.format(); + let n = fmt.channels(); + let (w, h) = (region.width(), region.height()); + let [pw, ph, pnw, pnh] = self.reduced(); + // Nearest samples of the area (and of the protecting channel) at the reduced size. + let src_x: Vec = (0..pw).map(|i| region.x0 + (((i as f64 + 0.5) * f64::from(w) / pw as f64) as i32).min(w as i32 - 1)).collect(); + let src_y = |j: usize| region.y0 + (((j as f64 + 0.5) * f64::from(h) / ph as f64) as i32).min(h as i32 - 1); + let mut img = Vec::with_capacity(pw * ph * n); + for j in 0..ph { + ctx.check()?; + let row = surf.read_region(Rect::from_xywh(region.x0, src_y(j), w, 1)); + for &x in &src_x { + let at = (x - region.x0) as usize * n; + img.extend_from_slice(row.get(at..at + n).ok_or_else(|| EngineError::Other("preview read out of bounds".into()))?); + } + } + let protect = protect.as_ref().map(|m| (0..pw * ph).map(|i| m.sample_channel(src_x[i % pw], src_y(i / pw), 0)).collect()); + let out = cas_pixels(ctx, "Content-Aware Scale", &img, (pw, ph), fmt, protect, *skin_tones, (pnw, pnh), *amount)?; + let mut s = Surface::new(fmt); + s.write_region(Rect::from_xywh(0, 0, pnw as u32, pnh as u32), &out); + Ok(s) + } +} diff --git a/crates/engine/src/edit_menu_cmds/fade.rs b/crates/engine/src/edit_menu_cmds/fade.rs new file mode 100644 index 0000000000..5ab5e4455b --- /dev/null +++ b/crates/engine/src/edit_menu_cmds/fade.rs @@ -0,0 +1,90 @@ +use super::*; + +// ------------------------------------------------------------------ Fade + +pub(super) fn can_fade(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + let f = s.edit_state.fade.as_ref().ok_or("nothing to fade")?; + if f.doc != st.doc.id || f.revision != st.revision || !st.history.can_undo() { + return Err("Fade is only available right after a filter, adjustment or painting step".into()); + } + if surface_of(&st.doc, f.target).is_none() { + return Err(match f.target { + FadeTarget::Pixels(_) | FadeTarget::Mask(_) => "the faded layer no longer exists".into(), + FadeTarget::Channel(_) | FadeTarget::QuickMask => "the faded channel no longer exists".into(), + }); + } + Ok(()) +} + +/// Blend `after` back towards `before` over `area`: `before + opacity × (B(before, after) − before)` +/// with blend mode `mode` (premultiplied, so alpha changes fade too). +pub fn fade_surface(before: &Surface, after: &mut Surface, area: Rect, mode: BlendMode, opacity: f32) -> Result<()> { + let fmt = after.format(); + let n = fmt.channels(); + if area.is_empty() || n == 0 { + return Ok(()); + } + let b = crate::allocation::read_region(before, area, "fading pixels")?; + let mut a = crate::allocation::read_region(after, area, "fading pixels")?; + let k = opacity.clamp(0.0, 1.0); + let lerp_premul = |pb: &[f32], pa: &[f32], out: &mut [f32], alpha: bool| { + let m = out.len(); + if !alpha { + for c in 0..m { + out[c] = pb[c] + (pa[c] - pb[c]) * k; + } + return; + } + let (ab, aa) = (pb[m - 1], pa[m - 1]); + let ao = ab + (aa - ab) * k; + for c in 0..m - 1 { + let pm = pb[c] * ab + (pa[c] * aa - pb[c] * ab) * k; + out[c] = if ao > 1e-9 { pm / ao } else { 0.0 }; + } + out[m - 1] = ao; + }; + let mut tmp = crate::allocation::filled(n, 0.0f32, "fading pixels")?; + for (pa, pb) in a.chunks_exact_mut(n).zip(b.chunks_exact(n)) { + if mode == BlendMode::Normal || n == 1 { + lerp_premul(pb, pa, &mut tmp, fmt.alpha); + pa.copy_from_slice(&tmp); + } else { + let rb = to_rgba(&fmt, pb); + let ra = to_rgba(&fmt, pa); + let blended = photocraft_color::blend::composite(mode, rb, ra, 1.0); + let mut o = [0.0f32; 4]; + lerp_premul(&rb, &blended, &mut o, true); + let mut enc = [0.0f32; 8]; + from_rgba_into(&fmt, o, &mut enc); + pa.copy_from_slice(&enc[..n]); + } + } + after.try_write_region(area, &a)?; + Ok(()) +} + +pub(super) fn fade(s: &mut Session, p: &Value) -> Result { + let cmd = "edit.fade"; + let src = s.edit_state.fade.clone().ok_or_else(|| bad(cmd, "nothing to fade"))?; + let opacity = f32_or(p, "opacity", 100.0).clamp(0.0, 100.0) / 100.0; + let mode = blend_from_str(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?; + let st = s.active().ok_or(EngineError::NoDocument)?; + let prev = st.history.past_len().checked_sub(1).and_then(|i| st.history.state(i)).ok_or_else(|| bad(cmd, "no previous state"))?; + let before = surface_of(&prev, src.target).cloned().ok_or_else(|| EngineError::Other("the layer or channel did not exist before this step".into()))?; + let now = surface_of(&st.doc, src.target).ok_or_else(|| EngineError::Other("the faded layer or channel no longer exists".into()))?; + if now.format() != before.format() { + return Err(EngineError::Other("can't fade a step that changed the layer's pixel format".into())); + } + // A uniform mask can change every pixel without storing a single tile. In that case + // the content bounds are empty, but Fade must still blend across the canvas. + let area = if before.default_pixel() != now.default_pixel() { st.doc.bounds() } else { before.content_bounds().union(&now.content_bounds()) }; + let label = format!("Fade {}", src.label); + s.edit(&label, |doc, _| { + let surf = surface_of_mut(doc, src.target).ok_or_else(|| EngineError::Other("the faded layer or channel no longer exists".into()))?; + fade_surface(&before, surf, area, mode, opacity)?; + surf.prune(); + Ok(()) + })?; + Ok(json!({"faded": src.label, "opacity": opacity * 100.0, "mode": mode.label()})) +} diff --git a/crates/engine/src/edit_menu_cmds/find_replace.rs b/crates/engine/src/edit_menu_cmds/find_replace.rs new file mode 100644 index 0000000000..91f16950f1 --- /dev/null +++ b/crates/engine/src/edit_menu_cmds/find_replace.rs @@ -0,0 +1,163 @@ +use super::*; + +// ------------------------------------------------------------------ Find and Replace Text + +/// Byte ranges of `find` in `text` (case-insensitive unless `case`; whole words only with `whole`). +pub fn find_matches(text: &str, find: &str, case: bool, whole: bool) -> Vec<(usize, usize)> { + if find.is_empty() { + return Vec::new(); + } + let norm = |c: char| -> String { if case { c.to_string() } else { c.to_lowercase().collect() } }; + let needle: String = find.chars().map(norm).collect(); + let mut out = Vec::new(); + let mut at = 0; + while at < text.len() { + // Compare char by char so case folding that changes byte lengths stays aligned. + let mut hay = String::new(); + let mut end = at; + for (i, c) in text[at..].char_indices() { + if hay.len() >= needle.len() { + break; + } + hay.push_str(&norm(c)); + end = at + i + c.len_utf8(); + } + if hay == needle { + let word = |c: Option| c.is_some_and(|c| c.is_alphanumeric() || c == '_'); + let before = text[..at].chars().next_back(); + let after = text[end..].chars().next(); + if !whole || (!word(before) && !word(after)) { + out.push((at, end)); + at = end; + continue; + } + } + at += text[at..].chars().next().map_or(1, char::len_utf8); + } + out +} + +fn type_layers(doc: &Document, forward: bool) -> Vec { + // Layers panel order: top first. + let mut ids: Vec = + doc.walk().into_iter().rev().filter(|(p, _, l)| matches!(l.content, LayerContent::Text(_)) && !doc.locks_at(p).all).map(|(_, _, l)| l.id).collect(); + if !forward { + ids.reverse(); + } + ids +} + +pub(super) fn has_type_layer(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + if type_layers(&d.doc, true).is_empty() { Err("the document has no type layers".into()) } else { Ok(()) } +} + +pub(super) fn find_replace(s: &mut Session, p: &Value) -> Result { + let cmd = "edit.findAndReplaceText"; + let find = p.get("find").and_then(Value::as_str).filter(|f| !f.is_empty()).ok_or_else(|| bad(cmd, "missing `find`"))?.to_string(); + let replace = str_or(p, "replace", "").to_string(); + let (case, whole, forward, all_layers) = + (bool_or(p, "caseSensitive", false), bool_or(p, "wholeWord", false), bool_or(p, "forward", true), bool_or(p, "allLayers", true)); + let action = str_or(p, "action", "changeAll").to_string(); + let st = s.active().ok_or(EngineError::NoDocument)?; + let mut layers = type_layers(&st.doc, forward); + if !all_layers { + let active = layer_param(s, p).ok(); + layers.retain(|id| Some(*id) == active); + } + let text_of = |doc: &Document, id: LayerId| -> Option { + match &doc.layer(id)?.content { + LayerContent::Text(t) => Some(t.text.clone()), + _ => None, + } + }; + match action.as_str() { + "changeAll" => { + let doc = st.doc.clone(); + let plan: Vec<(LayerId, Vec<(usize, usize)>)> = + layers.iter().filter_map(|id| Some((*id, find_matches(&text_of(&doc, *id)?, &find, case, whole)))).filter(|(_, m)| !m.is_empty()).collect(); + let count: usize = plan.iter().map(|(_, m)| m.len()).sum(); + if count == 0 { + return Ok(json!({"count": 0, "layers": 0})); + } + s.edit("Replace All Text", |doc, _| { + let (dpi, format) = (doc.resolution_dpi, doc.pixel_format()); + for (id, matches) in &plan { + if let Some(LayerContent::Text(t)) = doc.layer_mut(*id).map(|l| &mut l.content) { + for (a, b) in matches.iter().rev() { + crate::type_cmds::replace_text(t, *a, *b, &replace); + } + crate::type_cmds::refresh_at(dpi, format, t); + } + } + Ok(()) + })?; + s.edit_state.find_cursor = None; + Ok(json!({"count": count, "layers": plan.len()})) + } + "find" | "change" | "changeFind" => { + let doc = st.doc.clone(); + let cursor = s.edit_state.find_cursor; + let mut changed = None; + if action != "find" + && let Some((id, a, b)) = cursor + && text_of(&doc, id).is_some_and(|t| find_matches(&t, &find, case, whole).contains(&(a, b))) + { + crate::type_cmds::check_text_unlocked(&doc, id)?; + s.edit("Replace Text", |doc, _| { + let (dpi, format) = (doc.resolution_dpi, doc.pixel_format()); + if let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) { + crate::type_cmds::replace_text(t, a, b, &replace); + crate::type_cmds::refresh_at(dpi, format, t); + } + Ok(()) + })?; + let end = a + replace.len(); + // Collapse the cursor on the side the search moves away from, so the next search + // skips the replaced text even when the replacement still matches. + let c = if forward { end } else { a }; + s.edit_state.find_cursor = Some((id, c, c)); + changed = Some((id, a, end)); + if action == "change" { + return Ok(json!({"changed": {"layer": id.0, "start": a, "end": end}})); + } + } + // Find the next match after the cursor (wrapping through the layers). + let doc = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); + let cursor = s.edit_state.find_cursor; + let start = cursor.and_then(|(id, _, _)| layers.iter().position(|l| *l == id)).unwrap_or(0); + for k in 0..=layers.len() { + // `allLayers: false` with a non-type layer active leaves no layers to search (#703). + let Some(&id) = layers.get((start + k) % layers.len().max(1)) else { break }; + let Some(text) = text_of(&doc, id) else { continue }; + let ms = find_matches(&text, &find, case, whole); + let hit = match (k, cursor) { + (0, Some((cid, a, b))) if cid == id => { + if forward { + ms.into_iter().find(|m| m.0 >= b) + } else { + ms.into_iter().rev().find(|m| m.1 <= a) + } + } + _ => { + if forward { + ms.into_iter().next() + } else { + ms.into_iter().next_back() + } + } + }; + if let Some((a, b)) = hit { + s.edit_state.find_cursor = Some((id, a, b)); + let _ = s.select_layer(id); + return Ok( + json!({"found": {"layer": id.0, "start": a, "end": b, "text": &text[a..b]}, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))}), + ); + } + } + s.edit_state.find_cursor = None; + Ok(json!({"found": null, "changed": changed.map(|(l, a, b)| json!({"layer": l.0, "start": a, "end": b}))})) + } + other => Err(bad(cmd, format!("unknown action `{other}` (find|change|changeFind|changeAll)"))), + } +} diff --git a/crates/engine/src/edit_menu_cmds/presets.rs b/crates/engine/src/edit_menu_cmds/presets.rs new file mode 100644 index 0000000000..8f26426287 --- /dev/null +++ b/crates/engine/src/edit_menu_cmds/presets.rs @@ -0,0 +1,150 @@ +use super::*; + +// ------------------------------------------------------------------ Define Brush / Custom Shape + +pub(super) fn define_brush_preset(s: &mut Session, p: &Value) -> Result { + let name = match p.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) { + Some(n) => n.to_string(), + None => { + let n = s.tools.presets.iter().filter(|b| b.name.starts_with("Sampled Brush")).count() + 1; + format!("Sampled Brush {n}") + } + }; + s.execute("brush.defineFromSelection", json!({"name": name})) +} + +/// The path Define Custom Shape uses: `"work"`, a saved path name, else the work path, the +/// active shape layer, the active layer's vector mask, or the last saved path. +pub(crate) fn current_path(doc: &Document, active: Option, spec: Option<&str>) -> Option { + let ok = |p: &Path| !p.subpaths.is_empty(); + match spec { + Some("work") => return doc.work_path.clone().filter(ok), + Some(name) => return doc.paths.iter().find(|n| n.name == name).map(|n| n.path.clone()).filter(ok), + None => {} + } + if let Some(p) = doc.work_path.clone().filter(ok) { + return Some(p); + } + if let Some(l) = active.and_then(|id| doc.layer(id)) { + if let LayerContent::Shape(sh) = &l.content + && ok(&sh.path) + { + return Some(sh.path.clone()); + } + if let Some(vm) = l.vector_mask.as_ref().filter(|v| ok(&v.path)) { + return Some(vm.path.clone()); + } + } + doc.paths.last().map(|n| n.path.clone()).filter(ok) +} + +pub(super) fn can_define_shape(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + current_path(&d.doc, d.active_layer, None).map(|_| ()).ok_or_else(|| "select a path or shape layer first".into()) +} + +pub(super) fn define_custom_shape(s: &mut Session, p: &Value) -> Result { + let st = s.active().ok_or(EngineError::NoDocument)?; + let path = current_path(&st.doc, st.active_layer, p.get("path").and_then(Value::as_str)).ok_or_else(|| bad("edit.defineCustomShape", "no such path"))?; + let name = p + .get("name") + .and_then(Value::as_str) + .map(str::trim) + .filter(|n| !n.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| format!("Shape {}", s.edit_state.custom_shapes.len() + 1)); + let shapes = &mut s.edit_state.custom_shapes; + match shapes.iter_mut().find(|c| c.name == name) { + Some(c) => c.path = path, + None => shapes.push(CustomShape { name: name.clone(), path }), + } + Ok(json!({"name": name, "count": shapes.len()})) +} + +// ------------------------------------------------------------------ presets + +/// Libraries the Preset Manager edits (patterns export as `.pat` with `pattern.export`). +const PRESET_KINDS: [&str; 3] = ["brushes", "customShapes", "patterns"]; + +fn preset_names(s: &Session, kind: &str) -> Option> { + Some(match kind { + "brushes" => s.tools.presets.iter().map(|b| b.name.clone()).collect(), + "customShapes" => s.edit_state.custom_shapes.iter().map(|c| c.name.clone()).collect(), + "patterns" => s.patterns.items.iter().map(|p| p.name.clone()).collect(), + _ => return None, + }) +} + +fn preset_index(s: &Session, kind: &str, p: &Value) -> Result { + let names = preset_names(s, kind).ok_or_else(|| bad("edit.presets.presetManager", format!("unknown preset kind `{kind}` ({})", PRESET_KINDS.join("|"))))?; + if let Some(i) = p.get("index").and_then(Value::as_u64) { + return if (i as usize) < names.len() { Ok(i as usize) } else { Err(bad("edit.presets.presetManager", format!("no preset {i}"))) }; + } + let name = p.get("name").and_then(Value::as_str).ok_or_else(|| bad("edit.presets.presetManager", "give `index` or `name`"))?; + names.iter().position(|n| n == name).ok_or_else(|| bad("edit.presets.presetManager", format!("no preset named `{name}`"))) +} + +pub(super) fn preset_manager(s: &mut Session, p: &Value) -> Result { + let cmd = "edit.presets.presetManager"; + let action = str_or(p, "action", "list"); + if action == "list" { + let kinds: Vec<&str> = match p.get("kind").and_then(Value::as_str) { + Some(k) => vec![k], + None => PRESET_KINDS.to_vec(), + }; + let mut out = serde_json::Map::new(); + for k in kinds { + out.insert(k.to_string(), json!(preset_names(s, k).ok_or_else(|| bad(cmd, format!("unknown preset kind `{k}`")))?)); + } + return Ok(Value::Object(out)); + } + let kind = p.get("kind").and_then(Value::as_str).ok_or_else(|| bad(cmd, "missing `kind`"))?.to_string(); + let i = preset_index(s, &kind, p)?; + match action { + "rename" => { + let new = + p.get("newName").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "missing `newName`"))?.to_string(); + match kind.as_str() { + // Same rules as Brush Settings: no duplicate names (case-insensitive), the current + // preset follows, a renamed built-in is the user's preset now (and persists as one). + "brushes" => crate::brush_preset_cmds::rename_at(s, i, &new, cmd)?, + "patterns" => s.patterns.items[i].name = new, + _ => s.edit_state.custom_shapes[i].name = new, + } + } + "delete" => match kind.as_str() { + "brushes" => { + let gone = s.tools.presets.remove(i); + crate::brush_cmds::forget_deleted_preset(s, &gone.name); + } + "patterns" => drop(s.patterns.items.remove(i)), + _ => drop(s.edit_state.custom_shapes.remove(i)), + }, + "move" => { + let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "missing `to`"))? as usize; + match kind.as_str() { + "brushes" => crate::move_item(&mut s.tools.presets, i, to), + "patterns" => crate::move_item(&mut s.patterns.items, i, to), + _ => crate::move_item(&mut s.edit_state.custom_shapes, i, to), + }; + } + other => return Err(bad(cmd, format!("unknown action `{other}` (list|rename|delete|move)"))), + } + if kind == "brushes" { + s.brush_presets_changed(); + } + Ok(json!({kind.clone(): preset_names(s, &kind)})) +} + +/// Exported preset file (`.pcpresets`, JSON). +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct PresetFile { + pub format: String, + pub version: u32, + pub brushes: Vec, + pub custom_shapes: Vec, + pub tool_presets: Vec, +} + +pub const PRESET_FORMAT: &str = "photocraft-presets"; diff --git a/crates/engine/src/edit_menu_cmds/purge.rs b/crates/engine/src/edit_menu_cmds/purge.rs new file mode 100644 index 0000000000..a422e82bfb --- /dev/null +++ b/crates/engine/src/edit_menu_cmds/purge.rs @@ -0,0 +1,95 @@ +use super::*; + +// ------------------------------------------------------------------ Purge + +fn history_bytes(s: &Session, all: bool) -> usize { + let docs: Vec<&crate::DocState> = if all { s.documents().iter().collect() } else { s.active().into_iter().collect() }; + // Purge keeps the snapshots, so the tiles they share with the states aren't freed. + docs.iter() + .map(|d| { + let snaps: Vec<&photocraft_doc::Document> = d.snapshots.iter().map(|s| &*s.doc).collect(); + d.history.unique_bytes_besides(&d.doc, &snaps) + }) + .sum() +} + +fn clip_bytes(s: &Session) -> usize { + s.clipboard.as_ref().map_or(0, |c| c.surface.tiles().map(|(_, t)| t.bytes().len()).sum()) +} + +pub(super) fn purge(s: &mut Session, what: &str) -> Result { + let mut freed = 0usize; + let mut items: Vec<&str> = Vec::new(); + if matches!(what, "undo" | "all") && s.active().is_some_and(|d| d.history.can_undo()) { + let before = history_bytes(s, false); + if let Some(st) = s.active_mut() { + st.history.purge_last(); + } + freed += before.saturating_sub(history_bytes(s, false)); + items.push("undo"); + } + if matches!(what, "clipboard" | "all") && (s.clipboard.is_some() || s.style_clipboard.is_some()) { + freed += clip_bytes(s); + s.clipboard = None; + s.style_clipboard = None; + items.push("clipboard"); + } + if matches!(what, "histories" | "all") { + let b = history_bytes(s, true); + if s.documents().iter().any(|d| d.history.can_undo() || d.history.can_redo()) { + for st in &mut s.docs { + st.history.clear(); + st.coalesce = None; + } + freed += b; + items.push("histories"); + } + } + if what == "all" { + let fx = photocraft_compose::purge_effect_cache(); + if fx > 0 { + freed += fx; + items.push("effect cache"); + } + let masks = photocraft_compose::masks::purge_cache(); + if masks > 0 { + freed = freed.saturating_add(masks); + items.push("mask cache"); + } + let stages = crate::smart_cmds::purge_stack_cache(); + if stages > 0 { + freed = freed.saturating_add(stages); + items.push("smart filter cache"); + } + let strokes = photocraft_compose::shape_split::purge_cache(); + if strokes > 0 { + freed = freed.saturating_add(strokes); + items.push("shape stroke cache"); + } + } + s.edit_state.fade = None; + let msg = if items.is_empty() { "nothing to purge".to_string() } else { format!("purged {}", items.join(", ")) }; + Ok(json!({"purged": items, "bytes": freed, "message": msg})) +} + +pub(super) fn can_purge_undo(s: &Session) -> std::result::Result<(), String> { + s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "nothing to purge".into()) +} + +pub(super) fn can_purge_clipboard(s: &Session) -> std::result::Result<(), String> { + if s.clipboard.is_some() || s.style_clipboard.is_some() { Ok(()) } else { Err("the clipboard is empty".into()) } +} + +pub(super) fn can_purge_histories(s: &Session) -> std::result::Result<(), String> { + if s.documents().iter().any(|d| d.history.can_undo() || d.history.can_redo()) { Ok(()) } else { Err("no history to purge".into()) } +} + +pub(super) fn can_purge_all(s: &Session) -> std::result::Result<(), String> { + can_purge_histories(s).or_else(|_| can_purge_clipboard(s)).or_else(|_| { + if photocraft_compose::effect_cache_bytes() > 0 || photocraft_compose::masks::cache_bytes() > 0 || crate::smart_cmds::stack_cache_bytes() > 0 { + Ok(()) + } else { + Err("nothing to purge".into()) + } + }) +} From 7f31ed863cad7d5311838282155e407457b6fc81 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:57:27 +0000 Subject: [PATCH 206/259] refactor(engine): split file_cmds.rs into file_cmds/ --- crates/engine/src/file_cmds.rs | 1841 +-------------------- crates/engine/src/file_cmds/batch_run.rs | 326 ++++ crates/engine/src/file_cmds/export.rs | 231 +++ crates/engine/src/file_cmds/info.rs | 337 ++++ crates/engine/src/file_cmds/open.rs | 226 +++ crates/engine/src/file_cmds/paths.rs | 228 +++ crates/engine/src/file_cmds/processing.rs | 251 +++ crates/engine/src/file_cmds/save.rs | 235 +++ 8 files changed, 1866 insertions(+), 1809 deletions(-) create mode 100644 crates/engine/src/file_cmds/batch_run.rs create mode 100644 crates/engine/src/file_cmds/export.rs create mode 100644 crates/engine/src/file_cmds/info.rs create mode 100644 crates/engine/src/file_cmds/open.rs create mode 100644 crates/engine/src/file_cmds/paths.rs create mode 100644 crates/engine/src/file_cmds/processing.rs create mode 100644 crates/engine/src/file_cmds/save.rs diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 261e3d8608..efdd3ad8bf 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -20,6 +20,38 @@ use serde_json::{Value, json}; use crate::commands::{CommandSpec, layer_param}; use crate::{EngineError, Result, Session}; +mod batch_run; +mod export; +mod info; +mod open; +mod paths; +mod processing; +mod save; + +pub use batch_run::OutputClaims; +pub(crate) use batch_run::{BatchInput, batch_inputs, batch_keeps_step, batch_save_point, process_files}; +#[cfg(test)] +pub(crate) use batch_run::{MAX_SUBFOLDER_DEPTH, list_images_tree}; +use batch_run::{batch, same_format}; +pub use export::{LayerExportReport, SkippedExportLayer, bake_cube, export_layers_report_with, export_layers_with}; +use export::{color_lookup_tables, layers_to_files, push_unique}; +use info::file_info; +pub use info::{CAMERA_FIELDS, camera_data, read_file_info, write_file_info}; +#[cfg(test)] +use info::{exposure_text, find_element}; +pub use open::{PLACE_EMBEDDED, open_bytes_as, place_bytes, raw_defaults}; +use open::{close_all, close_others, open_as, place, revert}; +pub(crate) use open::{import, tag_exr_colorspace}; +use paths::is_file; +#[cfg(test)] +use paths::openable_name; +pub use paths::{extension, holds, holds_at, is_template, layered_extension, list_images, losses_at, same_file, saves_in_place, template_name, untitled_name}; +pub(crate) use paths::{file_name, forward_slashes, is_windows_device_name, join, portable_device_name, read_file, sanitize, stem, write_file}; +use processing::{conditional_mode_change, fit_image, flatten_all_effects, flatten_all_masks, image_processor, load_files_into_stack}; +use save::save_a_copy; +pub(crate) use save::{SaveOpts, encode, save_doc}; +pub use save::{dds_param, dpx_bits_param, jpeg_format_param, jpeg_quality, tga_bits_param, tiff_compression_param, tiff_would_write_layers}; + mod batch_naming; // ---------- predicates ---------- @@ -65,84 +97,6 @@ fn has_shape(s: &Session) -> std::result::Result<(), String> { } } -// ---------- file system (native only) ---------- - -#[cfg(not(target_arch = "wasm32"))] -fn is_file(path: &str) -> bool { - std::path::Path::new(path).is_file() -} -#[cfg(target_arch = "wasm32")] -fn is_file(_path: &str) -> bool { - false -} - -#[cfg(not(target_arch = "wasm32"))] -/// Every file the engine opens is read here: in bounded reads, with a clear error when it does -/// not fit in memory (see [`photocraft_format::read`]). -pub(crate) fn read_file(path: &str) -> Result> { - photocraft_format::read_file(std::path::Path::new(path)).map_err(|e| EngineError::Other(format!("{path}: {e}"))) -} -#[cfg(target_arch = "wasm32")] -pub(crate) fn read_file(path: &str) -> Result> { - Err(EngineError::Other(format!("cannot read {path}: no file system on the web"))) -} - -#[cfg(not(target_arch = "wasm32"))] -/// Every file the engine writes goes through here: crash-safe (temp file + fsync + rename, see -/// [`photocraft_format::atomic`]), so a failed save never destroys the previous file. -pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> { - photocraft_format::atomic_write(std::path::Path::new(path), bytes).map_err(|e| EngineError::Other(e.to_string())) -} -#[cfg(target_arch = "wasm32")] -pub(crate) fn write_file(path: &str, _bytes: &[u8]) -> Result<()> { - Err(EngineError::Other(format!("cannot write {path}: no file system on the web"))) -} - -/// Files of a folder that look like images we can open, sorted by name. -#[cfg(not(target_arch = "wasm32"))] -pub fn list_images(dir: &str) -> Result> { - let rd = std::fs::read_dir(dir).map_err(|e| EngineError::Other(format!("{dir}: {e}")))?; - let mut out: Vec = rd - .filter_map(|e| e.ok()) - .map(|e| e.path()) - .filter(|p| p.is_file() && openable_name(&p.to_string_lossy())) - .map(|p| p.to_string_lossy().into_owned()) - .collect(); - out.sort(); - Ok(out) -} -#[cfg(target_arch = "wasm32")] -pub fn list_images(dir: &str) -> Result> { - Err(EngineError::Other(format!("cannot list {dir}: no file system on the web"))) -} - -/// Whether a folder entry is one the batch commands open: an `OPENABLE` extension, or GIMP's -/// gzipped `.xcf.gz`, whose last extension alone says nothing. -#[cfg(not(target_arch = "wasm32"))] -fn openable_name(path: &str) -> bool { - let lower = file_name(path).to_ascii_lowercase(); - lower.ends_with(".xcf.gz") || lower.rsplit_once('.').is_some_and(|(_, ext)| OPENABLE.contains(&ext)) -} - -/// Extensions the batch commands pick up from a folder. -#[cfg(not(target_arch = "wasm32"))] -const OPENABLE: &[&str] = &[ - "pdn", "ora", "xcf", "xcfgz", "kra", "krz", "psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", - "ico", "pnm", "ppm", "pgm", "fits", "fit", "fts", "dpx", "heic", "heif", "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz", "af", "afdesign", - "afphoto", "afpub", -]; - -/// Whether saving `doc` as a TIFF writes Photoshop layer data (anything beyond a lone -/// Background layer). The UI asks before such a save when the "ask before saving layered TIFF" -/// preference is on; see `photocraft_io::tiff_layers`. -pub fn tiff_would_write_layers(doc: &Document) -> bool { - photocraft_io::tiff_layers::would_write_layers(doc) -} - -pub(crate) fn file_name(path: &str) -> String { - path.rsplit(['/', '\\']).next().unwrap_or(path).to_string() -} - impl crate::DocState { /// Complete a successful document save. File identity is not a history step; callers must /// finish the write first and must not call this for a copy or export. @@ -156,392 +110,6 @@ impl crate::DocState { } } -/// The lower-case extension of the file name in `path` (none for `.hidden` or `name`). -pub fn extension(path: &str) -> Option { - file_name(path).rsplit_once('.').filter(|(base, ext)| !base.is_empty() && !ext.is_empty()).map(|(_, ext)| ext.to_ascii_lowercase()) -} - -/// Whether a save without a new path may write back to `path` as far as its format goes: only -/// layered files (PSD, PSB, OpenRaster, .pcraft). A flat file goes through Save As instead, so it -/// is never flattened over the original. Whether this document fits is [`holds_at`]. -pub fn saves_in_place(path: &str) -> bool { - extension(path).is_some_and(|ext| layered_extension(&ext)) -} - -/// Whether the lower-case extension `ext` names a layered document format (PSD, PSB, OpenRaster, -/// .pcraft). A save to one becomes the document's file; any other format is a copy for automation -/// saves, desktop and headless alike (#1547, #2579). -pub fn layered_extension(ext: &str) -> bool { - matches!(ext, "psd" | "psb" | "pcraft" | "ora") -} - -/// Whether a file in format `ext` (lower-case) holds the whole of `doc`, so it can be the -/// document's own file: PSD, PSB and .pcraft always; OpenRaster only when it drops nothing (no -/// adjustment layers, styles, masks…, [`photocraft_io::ora_losses`]). A save to a format that -/// doesn't hold the document is a copy, and File › Save goes through Save As, so an editable -/// original is never overwritten with less than it had (#3806). -pub fn holds(doc: &photocraft_doc::Document, ext: &str) -> bool { - match ext { - "psd" | "psb" | "pcraft" => true, - "ora" => photocraft_io::ora_losses(doc).is_empty(), - _ => false, - } -} - -/// [`holds`] for the file at `path`. -pub fn holds_at(doc: &photocraft_doc::Document, path: &str) -> bool { - extension(path).is_some_and(|ext| holds(doc, &ext)) -} - -/// What a save of `doc` to `path` would leave out when its format can't hold it: OpenRaster's -/// [`photocraft_io::ora_losses`]; empty for other formats. -pub fn losses_at(doc: &photocraft_doc::Document, path: &str) -> Vec { - match extension(path).as_deref() { - Some("ora") => photocraft_io::ora_losses(doc), - _ => Vec::new(), - } -} - -/// Whether `path` names a document template (.psdt). A template opens as a new untitled document -/// without its path, so a save never writes over the template. -pub fn is_template(path: &str) -> bool { - extension(path).as_deref() == Some("psdt") -} - -/// The first "`base`-N" that isn't `taken`. -pub fn untitled_name(base: &str, taken: impl Fn(&str) -> bool) -> String { - (1..).map(|i| format!("{base}-{i}")).find(|n| !taken(n)).unwrap_or_default() -} - -/// The name a document opened from `path` gets when `path` is a template: the first "Untitled-N" -/// no open document has. -pub fn template_name(s: &Session, path: &str) -> Option { - is_template(path).then(|| untitled_name("Untitled", |n| s.documents().iter().any(|d| d.doc.name == n))) -} - -pub(crate) fn stem(path: &str) -> String { - let n = file_name(path); - match n.rfind('.') { - Some(i) if i > 0 => n[..i].to_string(), - _ => n, - } -} - -/// Whether `a` and `b` name the same file: the same text, or, when both exist, the same file on -/// disk (a hard link, a different case on a case-insensitive volume, `./` or `..` in one of them). -pub fn same_file(a: impl AsRef, b: impl AsRef) -> bool { - let (a, b) = (a.as_ref(), b.as_ref()); - if a == b { - return true; - } - #[cfg(unix)] - { - use std::os::unix::fs::MetadataExt; - if let (Ok(x), Ok(y)) = (std::fs::metadata(a), std::fs::metadata(b)) { - return x.dev() == y.dev() && x.ino() == y.ino(); - } - } - #[cfg(windows)] - { - // The volume serial number and file index of each, as unix compares dev and inode, so a - // hard link (another name for the file) is the same file. - if let Ok(same) = same_file::is_same_file(a, b) { - return same; - } - // Should a file not open: NTFS and FAT compare names without case. - if let (Ok(x), Ok(y)) = (std::fs::canonicalize(a), std::fs::canonicalize(b)) { - return x.to_string_lossy().to_lowercase() == y.to_string_lossy().to_lowercase(); - } - } - false -} - -/// A path as command results report it: `/` between components, whatever the platform. -/// -/// `join` already builds with `/`, but a directory from the caller or from `std::path::absolute` -/// carries the native separator, which would leave a reported path mixed. The control channel -/// takes `/` and rejects alternate separators (`AuthorizedWorkspace` in `crates/automation`), so -/// a result spelt this way can be handed straight back to it. Verbatim and UNC prefixes keep -/// theirs: Win32 does not accept `/` after a leading `\\`. -pub(crate) fn forward_slashes(path: String) -> String { - if path.starts_with(r"\\") { path } else { path.replace('\\', "/") } -} - -pub(crate) fn join(dir: &str, name: &str) -> String { - if dir.is_empty() { - name.to_string() - } else if dir.ends_with('/') || dir.ends_with('\\') { - format!("{dir}{name}") - } else { - format!("{dir}/{name}") - } -} - -/// A file-name-safe version of a layer name. A Windows device name (`nul`, `con.v2`) gets a `_` -/// before its first dot, so the file or folder is usable on Windows, wherever it was written. -pub(crate) fn sanitize(name: &str) -> String { - let s: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_' | ' ' | '.') { c } else { '_' }).collect(); - let s = s.trim().trim_matches('.').to_string(); - if s.is_empty() { "layer".into() } else { portable_device_name(s) } -} - -/// `name` with a `_` before its first dot when it is a Windows device name (`nul` → `nul_`, -/// `com1.v2` → `com1_.v2`); a `_` at the end would leave the device stem in place. -pub(crate) fn portable_device_name(name: String) -> String { - if !is_windows_device_name(&name) { - return name; - } - match name.split_once('.') { - Some((device, rest)) => format!("{device}_.{rest}"), - None => format!("{name}_"), - } -} - -/// Whether `component` names a Windows device (`CON`, `NUL`, `COM1`…, with any extension): -/// Windows opens the device instead of a file or folder of that name. `COM` and `LPT` take the -/// superscript digits ¹ ² ³ as well, as Windows does. -pub(crate) fn is_windows_device_name(component: &str) -> bool { - let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase(); - let port = |n: &str| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"); - matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") - || stem.strip_prefix("COM").is_some_and(port) - || stem.strip_prefix("LPT").is_some_and(port) -} - -pub(crate) fn import(name: &str, bytes: &[u8]) -> Result { - import_result(name, bytes).map(|r| r.document) -} - -/// [`import`] for a file that becomes a document of its own (Revert, Load Files into Stack; -/// Batch's scratch sessions use [`import_at_raw_ppi`]): a developed raw gets Preferences › Raw -/// Defaults › Resolution, as it does through File › Open. -pub(crate) fn import_opened(s: &Session, name: &str, bytes: &[u8]) -> Result { - import_at_raw_ppi(s.prefs().raw_defaults.resolution, name, bytes) -} - -fn import_at_raw_ppi(raw_ppi: f64, name: &str, bytes: &[u8]) -> Result { - let r = import_result(name, bytes)?; - let mut doc = r.document; - raw_resolution(raw_ppi, &r.warnings, &mut doc); - Ok(doc) -} - -fn import_result(name: &str, bytes: &[u8]) -> Result { - crate::allocation::checkpoint("importing document")?; - let r = photocraft_io::import(name, bytes).map_err(|e| EngineError::Other(format!("{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 { - return Err(EngineError::Other(format!( - "{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) -} - -/// What a headless save writes beyond the format: JPEG quality and format, TIFF layers, Targa -/// bits, DPX bits, DDS compression and mipmaps, PSD previews and the PSD merged image. -#[derive(Debug, Clone, Copy)] -pub(crate) struct SaveOpts { - /// Photoshop's 0–12 JPEG scale. - pub quality: Option, - /// JPEG Options › Format Options (`"jpegFormat"`); unset, Baseline ("Standard"). - pub jpeg_format: Option, - /// TIFF: keep the layers. Off unless a command's params ask (`"tiffLayers": true`). - pub tiff_layers: bool, - /// Targa: 24 or 32 bits per pixel (`"tgaBits"`); unset, 32 with an alpha channel or - /// transparency, else 24. - pub tga_bits: Option, - /// DPX: 8, 10, 12 or 16 bits per sample (`"dpxBits"`); unset, 8 for an 8-bit document, else 16. - pub dpx_bits: Option, - /// TIFF: the image compression (`"tiffCompression": "none" | "lzw" | "zip"`); unset, none. - pub tiff_compression: Option, - /// DDS: the compression and whether to write the mip chain (`"ddsCompression"`, - /// `"ddsMipmaps"`); unset, uncompressed without mipmaps. - pub dds: photocraft_io::DdsOptions, - /// PSD/PSB: embed the thumbnail resource (Preferences › File Handling › Image Previews). - pub image_previews: bool, - /// PSD/PSB: write the real merged image (Preferences › File Handling › Maximize PSD and PSB - /// File Compatibility). - pub psd_maximize_compatibility: bool, -} - -impl Default for SaveOpts { - fn default() -> Self { - SaveOpts { - quality: None, - jpeg_format: None, - tiff_layers: false, - tga_bits: None, - dpx_bits: None, - tiff_compression: None, - dds: photocraft_io::DdsOptions::default(), - image_previews: true, - psd_maximize_compatibility: true, - } - } -} - -impl SaveOpts { - /// `quality`, `jpegFormat`, `tiffLayers` and `tgaBits` from command `cmd`'s params (a - /// `jpegFormat` it doesn't name or a `tgaBits` other than 24 or 32 is an error); the image - /// previews and the PSD merged image from the session's File Handling preferences (Ask When - /// Saving has no dialog here, so it saves them, as Photoshop's Save As checkbox and its - /// Maximize Compatibility checkbox both start on). - pub(crate) fn from_params(s: &Session, p: &Value, cmd: &str) -> Result { - let file_handling = &s.prefs().file_handling; - Ok(SaveOpts { - quality: f64_param(p, "quality"), - jpeg_format: jpeg_format_param(p, cmd)?, - tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), - tga_bits: tga_bits_param(p, cmd)?, - dpx_bits: dpx_bits_param(p, cmd)?, - tiff_compression: tiff_compression_param(p, cmd)?, - dds: dds_param(p, cmd)?.unwrap_or_default(), - image_previews: file_handling.image_previews != crate::prefs::Ask::Never, - psd_maximize_compatibility: file_handling.maximize_psd_compatibility != crate::prefs::Ask::Never, - }) - } - - pub(crate) fn or_quality(mut self, q: f64) -> Self { - self.quality = self.quality.or(Some(q)); - self - } -} - -impl From> for SaveOpts { - fn from(quality: Option) -> Self { - SaveOpts { quality, ..Default::default() } - } -} - -/// The Targa bits per pixel in `p` (`"tgaBits": 24 | 32`; absent or null: the automatic choice). -/// Anything else is a bad parameter of command `cmd`. Shared by every save that takes it (the -/// engine's commands, the app's Save As and control channel, the headless server). -pub fn tga_bits_param(p: &Value, cmd: &str) -> Result> { - match p.get("tgaBits") { - None | Some(Value::Null) => Ok(None), - Some(v) => v - .as_u64() - .and_then(photocraft_io::TgaBits::from_bits) - .map(Some) - .ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("`tgaBits` must be 24 or 32, got {v}") }), - } -} - -/// The TIFF compression in `p` (`"tiffCompression": "none" | "lzw" | "zip"`, Photoshop's TIFF -/// Options; absent or null: none). Anything else is a bad parameter of command `cmd` (#5301). -pub fn tiff_compression_param(p: &Value, cmd: &str) -> Result> { - use photocraft_codecs::TiffCompression; - match p.get("tiffCompression") { - None | Some(Value::Null) => Ok(None), - Some(v) => match v.as_str() { - Some("none") => Ok(Some(TiffCompression::None)), - Some("lzw") => Ok(Some(TiffCompression::Lzw)), - Some("zip") => Ok(Some(TiffCompression::Deflate)), - _ => Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("`tiffCompression` must be \"none\", \"lzw\" or \"zip\", got {v}") }), - }, - } -} - -/// The JPEG format in `p` (`"jpegFormat": "baseline" | "optimized" | "progressive"`; absent or -/// null: Baseline). Anything else is a bad parameter of command `cmd`. Shared like -/// [`tga_bits_param`]. -pub fn jpeg_format_param(p: &Value, cmd: &str) -> Result> { - match p.get("jpegFormat") { - None | Some(Value::Null) => Ok(None), - Some(v) => v.as_str().and_then(photocraft_codecs::JpegFormat::parse).map(Some).ok_or_else(|| EngineError::BadParams { - cmd: cmd.into(), - msg: format!("`jpegFormat` must be \"baseline\", \"optimized\" or \"progressive\", got {v}"), - }), - } -} - -/// Photoshop's 0–12 JPEG quality as the encoder's 1–100 (0 → 1, 12 → 100, linear between; out of -/// range is clamped, and NaN or infinite is 100). -pub fn jpeg_quality(q: f64) -> u8 { - if q.is_finite() { (q.clamp(0.0, 12.0) / 12.0 * 99.0 + 1.0).round() as u8 } else { 100 } -} - -/// The DPX bits per sample in `p` (`"dpxBits": 8 | 10 | 12 | 16`; absent or null: the document's -/// depth). Anything else is a bad parameter of command `cmd`. -pub fn dpx_bits_param(p: &Value, cmd: &str) -> Result> { - match p.get("dpxBits") { - None | Some(Value::Null) => Ok(None), - Some(v) => v - .as_u64() - .and_then(photocraft_io::DpxBits::from_bits) - .map(Some) - .ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("`dpxBits` must be 8, 10, 12 or 16, got {v}") }), - } -} - -/// The DDS options in `p`: `"ddsCompression": "none" | "bc1" | "bc2" | "bc3"` (or the DXT names) -/// and `"ddsMipmaps": bool`. `None` when neither is given (Save As then asks); either alone -/// leaves the other at its default (uncompressed, no mipmaps). Anything else is a bad parameter -/// of command `cmd`. -pub fn dds_param(p: &Value, cmd: &str) -> Result> { - let bad = |msg: String| EngineError::BadParams { cmd: cmd.into(), msg }; - let compression = match p.get("ddsCompression") { - None | Some(Value::Null) => None, - Some(v) => Some( - v.as_str() - .and_then(photocraft_io::DdsCompression::from_name) - .ok_or_else(|| bad(format!("`ddsCompression` must be \"none\", \"bc1\", \"bc2\" or \"bc3\", got {v}")))?, - ), - }; - let mipmaps = match p.get("ddsMipmaps") { - None | Some(Value::Null) => None, - Some(v) => Some(v.as_bool().ok_or_else(|| bad(format!("`ddsMipmaps` must be true or false, got {v}")))?), - }; - if compression.is_none() && mipmaps.is_none() { - return Ok(None); - } - Ok(Some(photocraft_io::DdsOptions { compression: compression.unwrap_or_default(), mipmaps: mipmaps.unwrap_or(false) })) -} - -/// Encodes `doc` for `path`'s extension. -pub(crate) fn encode(doc: &Document, path: &str, save: impl Into) -> Result<(Vec, Vec)> { - crate::allocation::checkpoint("saving document")?; - let save = save.into(); - let mut opts = photocraft_io::ExportOptions { - tiff_layers: save.tiff_layers, - tga_bits: save.tga_bits, - image_previews: save.image_previews, - psd_maximize_compatibility: save.psd_maximize_compatibility, - // Linked files a PSD embeds are resolved against the document being worked on. - document_path: crate::doc_path::current(), - // An untrusted session's stored paths are document data: embed none of them. - read_linked_files: !crate::jobs::authorization_installed(), - ..Default::default() - }; - // No quality chosen: write the file the way it was opened (a JPEG at its own quality, a WebP - // lossy or lossless as it was), as Photoshop's Save does. - photocraft_io::apply_file_encoding(doc, &mut opts.encode); - opts.encode.dpx_bits = save.dpx_bits; - if let Some(c) = save.tiff_compression { - opts.encode.tiff_compression = c; - } - opts.encode.dds = save.dds; - if let Some(q) = save.quality { - let q = jpeg_quality(q); - opts.encode.jpeg_quality = q; - // A quality on a WebP save asks for the lossy encoder; the default WebP stays lossless. - opts.encode.webp_quality = q; - opts.encode.webp_lossless = false; - } - if let Some(f) = save.jpeg_format { - opts.encode.jpeg_format = f; - } - photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| EngineError::Other(format!("{path}: {e}"))) -} - -pub(crate) fn save_doc(doc: &Document, path: &str, save: impl Into) -> Result> { - let (bytes, warnings) = encode(doc, path, save)?; - write_file(path, &bytes)?; - Ok(warnings) -} - pub(crate) fn str_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a str> { p.get(key).and_then(Value::as_str).filter(|v| !v.is_empty()).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("missing \"{key}\"") }) } @@ -588,1351 +156,6 @@ pub(crate) fn flattened_checked(doc: &Document, fmt: PixelFormat, cmd: &str) -> Ok(flattened(doc, fmt)) } -// ---------- close / revert / save a copy / open as ---------- - -fn close_all(s: &mut Session) -> Result { - let n = s.documents().len(); - while !s.documents().is_empty() { - s.close(s.documents().len() - 1); - } - Ok(json!({"closed": n})) -} - -fn close_others(s: &mut Session, p: &Value) -> Result { - let keep = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?; - if keep >= s.documents().len() { - return Err(EngineError::BadParams { cmd: "file.closeOthers".into(), msg: format!("no document {keep}") }); - } - let n = s.documents().len() - 1; - for i in (0..s.documents().len()).rev() { - if i != keep { - s.close(i); - } - } - s.set_active(0); - Ok(json!({"closed": n})) -} - -/// File › Revert: reload the saved file as one history step (undoable, like Photoshop's -/// "Revert" history state); the document is clean afterwards. -fn revert(s: &mut Session) -> Result { - let path = s.active().and_then(|d| d.path.clone()).ok_or(EngineError::Other("the document has never been saved".into()))?; - let bytes = read_file(&path)?; - let fresh = import_opened(s, &file_name(&path), &bytes)?; - s.edit("Revert", |doc, active| { - let (id, name) = (doc.id, doc.name.clone()); - *doc = fresh; - // Keep the identity (colour state, views and caches are keyed by it) and the tab name. - doc.id = id; - doc.name = name; - *active = doc.top_layer(); - Ok(()) - })?; - let st = s.active_mut().ok_or(EngineError::NoDocument)?; - st.saved_revision = st.revision; - Ok(json!({"path": path, "layers": st.doc.layers.len()})) -} - -fn save_a_copy(s: &mut Session, p: &Value) -> Result { - let path = str_param(p, "path", "file.saveACopy")?.to_string(); - let d = s.active().ok_or(EngineError::NoDocument)?; - // A copy over the document's own file replaces it, and a flat or lossy format can't be - // undone, so it takes an explicit `overwrite` (#7437). The desktop dialog writes through the - // shell, after the OS has confirmed the replace. - if d.path.as_deref().is_some_and(|own| same_file(&path, own)) && p.get("overwrite").and_then(Value::as_bool) != Some(true) { - return Err(EngineError::BadParams { - cmd: "file.saveACopy".into(), - msg: "`path` is the document's own file, so the copy would replace it: choose another path, or pass \"overwrite\": true".into(), - }); - } - let mut doc = (*d.doc).clone(); - if p.get("layers").and_then(Value::as_bool) == Some(false) { - // "Layers" unchecked in Save a Copy: write the flattened image. - let fmt = doc.pixel_format(); - let px = flattened_checked(&doc, fmt, "file.saveACopy")?; - doc.layers = vec![Layer::new("Background", LayerContent::Raster(px))]; - } - let warnings = save_doc(&doc, &path, SaveOpts::from_params(s, p, "file.saveACopy")?)?; - Ok(json!({"path": path, "warnings": warnings})) -} - -/// Open a file's bytes, decoding them as the format `as_ext` (Open As) when given. -/// EXR/HDR rarely states its colour space, so io tags it with the linear-sRGB default. -/// With File Handling's ACEScg option on, such an EXR opens as ACEScg instead (AP1, -/// linear) — the working space ACES render pipelines write. Only the io default is -/// replaced; an embedded or EXIF-declared profile is kept untouched. -pub(crate) fn tag_exr_colorspace(s: &Session, name: &str, doc: &mut Document) { - if !name.to_ascii_lowercase().ends_with(".exr") || !s.prefs.get().file_handling.exr_aces_cg { - return; - } - let linear = photocraft_cms::Builtin::LinearSrgb.profile().to_bytes(); - if doc.icc_profile.as_ref().map(|v| v.as_slice()) == Some(linear.as_slice()) { - doc.icc_profile = Some(photocraft_cms::Builtin::AcesCg.profile().to_bytes()); - } -} - -/// Edit › Preferences › Raw Defaults › Resolution: the ppi a raw developed on open gets, as -/// Camera Raw's workflow options set it (the raw itself states none). `warnings` are the -/// import's notes, which say whether the raw was developed or only its preview opened. -pub fn raw_defaults(s: &Session, warnings: &[String], doc: &mut Document) { - raw_resolution(s.prefs().raw_defaults.resolution, warnings, doc); -} - -fn raw_resolution(ppi: f64, warnings: &[String], doc: &mut Document) { - if ppi.is_finite() && warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)) { - doc.resolution_dpi = ppi.clamp(1.0, 10_000.0) as f32; - } -} - -pub fn open_bytes_as(s: &mut Session, name: &str, bytes: &[u8], as_ext: Option<&str>, path: Option) -> Result { - crate::allocation::checkpoint("importing document")?; - let decode_name = match as_ext { - Some(ext) => format!("{}.{}", stem(name), ext.trim_start_matches('.')), - None => name.to_string(), - }; - let r = photocraft_io::import(&decode_name, bytes).map_err(|e| EngineError::Other(format!("{decode_name}: {e}")))?; - let mut doc = r.document; - tag_exr_colorspace(s, &decode_name, &mut doc); - raw_defaults(s, &r.warnings, &mut doc); - let path = match template_name(s, name) { - Some(untitled) => { - doc.name = untitled; - None - } - None => { - doc.name = file_name(name); - path - } - }; - // Color Settings policies (preserve / convert / discard the embedded profile). - let (i, color) = s.open_document(doc, path.filter(|_| !r.source_read_only)); - if let Some(st) = s.active_mut() { - st.source_read_only = r.source_read_only; - } - // Import notes (e.g. how a camera raw was developed, or that only its preview opened). - Ok(json!({"document": i, "color": color, "warnings": r.warnings})) -} - -fn open_as(s: &mut Session, p: &Value) -> Result { - let path = str_param(p, "path", "file.openAs")?.to_string(); - let bytes = read_file(&path)?; - let as_ext = p.get("as").or_else(|| p.get("format")).and_then(Value::as_str); - open_bytes_as(s, &path, &bytes, as_ext, Some(path.clone())) -} - -// ---------- place ---------- - -/// History label of an embedded place. -pub const PLACE_EMBEDDED: &str = "Place Embedded"; - -/// Place a file's bytes as a smart object layer, centred, and (with Preferences ▸ General ▸ -/// Resize Image During Place, on by default) scaled down to fit when larger than the canvas. -/// `linked` makes it a linked smart object that refers to that path instead of embedding the bytes. -/// With Preferences ▸ General ▸ Always Create Smart Objects When Placing off, an embedded place -/// lands as a plain pixel layer instead (an explicit `"smartObject": false` asks for one). -pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec, linked: Option, p: &Value) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let (cw, ch) = (d.doc.size.width as f64, d.doc.size.height as f64); - let fmt = d.doc.pixel_format(); - let vector = photocraft_io::svg::is_svg(&bytes); - let opts = crate::jobs::import_options(s.prefs()); - let imported = photocraft_io::import_with_options(name, &bytes, &opts).map_err(|e| EngineError::Other(format!("{name}: {e}")))?; - if imported.preview_only { - return Err(EngineError::Other(format!( - "{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" - ))); - } - let src = imported.document; - let (w, h) = (src.size.width as f64, src.size.height as f64); - // The implicit `fit` is Preferences ▸ General ▸ Resize Image During Place (on by default). - let fit = p.get("fit").and_then(Value::as_bool).unwrap_or(s.prefs().general.resize_image_during_place); - let scale = match f64_param(p, "scale") { - Some(k) => (k / 100.0).max(1e-4), - None if fit && (w > cw || h > ch) => (cw / w).min(ch / h), - None => 1.0, - }; - let center = match p.get("center").and_then(Value::as_array) { - Some(c) if c.len() == 2 => (c[0].as_f64().unwrap_or(cw / 2.0), c[1].as_f64().unwrap_or(ch / 2.0)), - _ => (cw / 2.0, ch / 2.0), - }; - let (dx, dy) = ((center.0 - w * scale / 2.0).round(), (center.1 - h * scale / 2.0).round()); - let mut px = flattened_checked(&src, fmt, "file.place")?; - if (scale - 1.0).abs() > 1e-9 { - px = resize_surface(&px, scale, scale, Resample::Bicubic); - } - let px = translate_surface(&px, dx as i32, dy as i32); - // Preferences ▸ General ▸ Always Create Smart Objects When Placing (on by default): off, an - // embedded place lands as a plain pixel layer. A linked place is always a smart object. - let smart = linked.is_some() || p.get("smartObject").and_then(Value::as_bool).unwrap_or(s.prefs().general.always_create_smart_objects_when_placing); - let source = match linked { - Some(path) => SmartSource::Linked { path }, - None => SmartSource::Embedded { file_name: file_name(name), bytes: Arc::new(bytes) }, - }; - let layer_name = stem(name); - let label = if matches!(&source, SmartSource::Linked { .. }) { "Place Linked" } else { PLACE_EMBEDDED }; - let id = s.edit(label, |doc, active| { - let layer = if smart { - let mut so = SmartObject::new(source, Affine { m: [scale, 0.0, 0.0, scale, dx, dy] }, Some(px)); - // A vector source (SVG) renders at its placement scale instead of as a resampled raster. - if vector && let Some(sharp) = crate::smart_cmds::render(doc, &so)? { - so.cache = Some(sharp); - } - Layer::new(layer_name, LayerContent::Smart(so)) - } else { - Layer::new(layer_name, LayerContent::Raster(px)) - }; - let id = doc.insert_above(*active, layer); - *active = Some(id); - Ok(id) - })?; - Ok(json!({"layer": id.0, "scale": scale * 100.0, "bounds": [dx, dy, dx + w * scale, dy + h * scale], "smartObject": smart})) -} - -fn place(s: &mut Session, p: &Value, linked: bool) -> Result { - let cmd = if linked { "file.placeLinked" } else { "file.placeEmbedded" }; - let path = str_param(p, "path", cmd)?.to_string(); - let bytes = read_file(&path)?; - // The link is stored absolute: a relative one would later be taken from the document's - // folder (`doc_path`), not the working directory the path was given in. - let link = linked.then(|| { - if std::path::Path::new(&path).is_relative() { - std::path::absolute(&path).map_or_else(|_| path.clone(), |a| a.to_string_lossy().into_owned()) - } else { - path.clone() - } - }); - place_bytes(s, &path, bytes, link, p) -} - -// ---------- File Info (XMP) ---------- - -/// The File Info fields we edit, as (JSON key, XMP property, container kind). -const INFO_FIELDS: [(&str, &str, &str); 6] = [ - ("title", "dc:title", "Alt"), - ("author", "dc:creator", "Seq"), - ("description", "dc:description", "Alt"), - ("keywords", "dc:subject", "Bag"), - ("copyright", "dc:rights", "Alt"), - ("authorTitle", "photoshop:AuthorsPosition", ""), -]; - -fn xml_escape(s: &str) -> String { - s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) -} - -fn xml_unescape(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - let mut rest = s; - while let Some(i) = rest.find('&') { - out.push_str(&rest[..i]); - rest = &rest[i..]; - let decoded = rest.as_bytes().iter().take(13).position(|&b| b == b';').and_then(|e| { - let c = match &rest[1..e] { - "lt" => '<', - "gt" => '>', - "quot" => '"', - "apos" => '\'', - "amp" => '&', - n => { - let n = n.strip_prefix('#')?; - let code = match n.strip_prefix(['x', 'X']) { - Some(h) => u32::from_str_radix(h, 16).ok()?, - None => n.parse().ok()?, - }; - char::from_u32(code)? - } - }; - Some((c, e + 1)) - }); - match decoded { - Some((c, len)) => { - out.push(c); - rest = &rest[len..]; - } - None => { - out.push('&'); - rest = &rest[1..]; - } - } - } - out.push_str(rest); - out -} - -/// The element `…` (first occurrence) as (start, end, inner). -fn find_element<'a>(xmp: &'a str, tag: &str) -> Option<(usize, usize, &'a str)> { - let open = format!("<{tag}"); - let mut from = 0; - while let Some(i) = xmp[from..].find(&open).map(|i| i + from) { - let after = xmp[i + open.len()..].chars().next(); - if matches!(after, Some('>' | ' ' | '/' | '\n' | '\r' | '\t')) { - let gt = xmp[i..].find('>')? + i; - if xmp[..gt].ends_with('/') { - return Some((i, gt + 1, "")); - } - let close = format!(""); - let c = xmp[gt..].find(&close)? + gt; - return Some((i, c + close.len(), &xmp[gt + 1..c])); - } - from = i + open.len(); - } - None -} - -/// `rdf:li` values of a container (or the element text for simple properties). -fn li_values(inner: &str) -> Vec { - let mut out = Vec::new(); - let mut rest = inner; - while let Some((a, b, v)) = find_element(rest, "rdf:li") { - out.push(xml_unescape(v.trim())); - rest = &rest[b..]; - let _ = a; - } - if out.is_empty() && !inner.contains('<') && !inner.trim().is_empty() { - out.push(xml_unescape(inner.trim())); - } - out -} - -/// Attribute form `prop="value"` on an `rdf:Description`. -fn find_attr<'a>(xmp: &'a str, prop: &str) -> Option<(usize, usize, &'a str)> { - let key = format!(" {prop}=\""); - let i = xmp.find(&key)?; - let v0 = i + key.len(); - let v1 = xmp[v0..].find('"')? + v0; - Some((i, v1 + 1, &xmp[v0..v1])) -} - -/// File Info fields read from an XMP packet. -pub fn read_file_info(xmp: Option<&str>) -> Value { - let mut m = serde_json::Map::new(); - let x = xmp.unwrap_or(""); - for (key, prop, kind) in INFO_FIELDS { - let vals = match find_element(x, prop) { - Some((_, _, inner)) => li_values(inner), - None => find_attr(x, prop).map(|(_, _, v)| vec![xml_unescape(v)]).unwrap_or_default(), - }; - let v = if kind == "Bag" { - json!(vals) - } else if kind == "Seq" { - json!(vals.join("; ")) - } else { - json!(vals.into_iter().next().unwrap_or_default()) - }; - m.insert(key.into(), v); - } - let marked = - find_element(x, "xmpRights:Marked").map(|(_, _, v)| v.trim().to_string()).or_else(|| find_attr(x, "xmpRights:Marked").map(|(_, _, v)| v.to_string())); - m.insert( - "copyrightStatus".into(), - json!(match marked.as_deref() { - Some("True") => "copyrighted", - Some("False") => "publicDomain", - _ => "unknown", - }), - ); - let url = find_element(x, "xmpRights:WebStatement") - .map(|(_, _, v)| xml_unescape(v.trim())) - .or_else(|| find_attr(x, "xmpRights:WebStatement").map(|(_, _, v)| xml_unescape(v))); - m.insert("copyrightUrl".into(), json!(url.unwrap_or_default())); - Value::Object(m) -} - -/// File Info's read-only Camera Data, as (result key, English label) in display order. -pub const CAMERA_FIELDS: [(&str, &str); 9] = [ - ("make", "Make"), - ("model", "Model"), - ("dateTaken", "Date Taken"), - ("exposure", "Exposure"), - ("fNumber", "F-Stop"), - ("iso", "ISO Speed"), - ("focalLength", "Focal Length"), - ("focalLength35mm", "Focal Length (35 mm)"), - ("lens", "Lens"), -]; - -/// `v` with at most `decimals` decimals and no trailing zeros (33.10 → "33.1", 8.0 → "8"). -fn short_num(v: f64, decimals: usize) -> String { - let s = format!("{v:.decimals$}"); - if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s } -} - -/// `v` to three significant digits, with no trailing zeros (0.031714 → "0.0317", 0.4 → "0.4"). -/// Two decimals threw away most of a slow shutter speed: a stored 0.031714 s printed as "0.03 s", -/// which is 5 % off, and a stored 0.0215 s printed as "0.02 s", 7 % off (#6958). -fn sig3(v: f64) -> String { - let magnitude = v.abs().log10().floor(); - // Clamped at both ends: a value at the large end must not ask for a negative field width, and - // at the small end the field is widened rather than truncated, so a positive exposure never - // reads as "0 s". 320 is beyond f64's decimal range, so it always terminates. - let decimals = if magnitude.is_finite() { (2.0 - magnitude).clamp(0.0, 320.0) } else { 0.0 }; - short_num(v, decimals as usize) -} - -/// Exposure time as cameras print it: "1/250 s" for fractions of a second, "0.4 s" or "2 s" -/// when the reciprocal isn't a whole number or the exposure is a second or longer. -fn exposure_text(t: f64) -> Option { - if !(t.is_finite() && t > 0.0) { - return None; - } - let r = 1.0 / t; - let n = r.round(); - // Below 1/10 s the reciprocal is above 10, so its nearest whole number puts the shown time - // within 5 % of the stored one, and is the form a photographer expects ("1/32 s"). The test - // used to be relative to the reciprocal, so it shrank as the exposure slowed: under 1/50 s it - // fell below half a rounding step and nearly every fraction fell through to the decimal form - // (#6958). Above 1/10 s the fraction is only right when the reciprocal is very nearly whole - // (1/2 s, 1/4 s) — 0.4 s stays "0.4 s" rather than becoming "1/3 s". - let fraction = n.is_finite() && (1.0..=1e9).contains(&n) && (t < 0.1 || (t < 1.0 && n > 1.0 && (r - n).abs() <= r * 0.01)); - if fraction { - return Some(format!("1/{} s", n as u64)); - } - Some(format!("{} s", sig3(t))) -} - -/// EXIF (`2024:02:17 12:40:19`) or XMP (`2024-02-17T12:40:19.00+01:00`) dates as -/// `2024-02-17 12:40:19`; anything else is shown as stored. -fn date_text(s: &str) -> String { - let b = s.trim().as_bytes(); - let digits = |r: &[usize]| r.iter().all(|&i| b.get(i).is_some_and(u8::is_ascii_digit)); - let sep = |i: usize, set: &[u8]| b.get(i).is_some_and(|c| set.contains(c)); - let ch = |i: usize| b.get(i).map_or('0', |&c| c as char); - let part = |r: std::ops::Range| r.map(ch).collect::(); - if !(digits(&[0, 1, 2, 3, 5, 6, 8, 9]) && sep(4, b":-") && sep(7, b":-")) { - return s.trim().to_string(); - } - let date = format!("{}-{}-{}", part(0..4), part(5..7), part(8..10)); - if digits(&[11, 12, 14, 15, 17, 18]) && sep(10, b" T") && sep(13, b":") && sep(16, b":") { format!("{date} {}", part(11..19)) } else { date } -} - -/// A single XMP value: the first `rdf:li` of a container, element text or attribute. -fn xmp_value(x: &str, prop: &str) -> Option { - let v = match find_element(x, prop) { - Some((_, _, inner)) => li_values(inner).into_iter().next(), - None => find_attr(x, prop).map(|(_, _, v)| xml_unescape(v)), - }?; - let v = v.trim().to_string(); - (!v.is_empty()).then_some(v) -} - -/// An XMP number: a rational "331/10" or a decimal. -fn xmp_number(x: &str, prop: &str) -> Option { - let v = xmp_value(x, prop)?; - let n = match v.split_once('/') { - Some((a, b)) => { - let (a, b) = (a.trim().parse::().ok()?, b.trim().parse::().ok()?); - (b != 0.0).then(|| a / b)? - } - None => v.parse::().ok()?, - }; - n.is_finite().then_some(n) -} - -/// File Info's read-only Camera Data (keys of [`CAMERA_FIELDS`], present ones only), formatted -/// for display. Read from the EXIF block (JPEG APP1, PSD resource 1058, …); properties it lacks -/// fall back to the XMP `tiff:`/`exif:`/`aux:` copies (files without an EXIF block). -pub fn camera_data(exif: Option<&[u8]>, xmp: Option<&str>) -> Value { - let e = exif.map(photocraft_algo::exif::read).unwrap_or_default(); - let x = xmp.unwrap_or(""); - let text = |v: Option, props: &[&str]| v.or_else(|| props.iter().find_map(|p| xmp_value(x, p))); - let num = - |v: Option, props: &[&str]| v.filter(|v| v.is_finite() && *v > 0.0).or_else(|| props.iter().find_map(|p| xmp_number(x, p))).filter(|v| *v > 0.0); - let values = [ - text(e.make, &["tiff:Make"]), - text(e.model, &["tiff:Model"]), - text(e.date_taken, &["exif:DateTimeOriginal"]).map(|d| date_text(&d)), - num(e.exposure_time, &["exif:ExposureTime"]).and_then(exposure_text), - num(e.f_number, &["exif:FNumber"]).map(|n| format!("f/{}", short_num(n, 1))), - num(e.iso, &["exif:ISOSpeedRatings", "exifEX:PhotographicSensitivity"]).map(|n| format!("ISO {}", n.round())), - num(e.focal_length, &["exif:FocalLength"]).map(|f| format!("{} mm", short_num(f, 1))), - num(e.focal_length_35mm, &["exif:FocalLengthIn35mmFilm"]).map(|f| format!("{} mm", short_num(f, 1))), - text(e.lens, &["exifEX:LensModel", "aux:Lens"]), - ]; - let mut m = serde_json::Map::new(); - for ((key, _), v) in CAMERA_FIELDS.into_iter().zip(values) { - // Hostile files can carry megabytes of "lens name"; the dialog shows a line. - if let Some(v) = v.map(|v| v.chars().take(200).collect::()).filter(|v| !v.is_empty()) { - m.insert(key.into(), json!(v)); - } - } - Value::Object(m) -} - -/// Rewrites only changed File Info fields of an XMP packet (creating one when there is none), -/// keeping the other properties verbatim. Edited properties move into their own -/// `rdf:Description` (several descriptions per packet are valid XMP). -pub fn write_file_info(xmp: Option<&str>, info: &Value) -> String { - let cur = read_file_info(xmp); - // The dialog submits all fields, including unchanged language alternatives. - let changed = |key: &str| info.get(key).is_some_and(|v| cur.get(key) != Some(v)); - let mut x = xmp.filter(|s| s.contains("")).map(str::to_string).unwrap_or_else(|| { - "\n\n \n \n\n".to_string() - }); - for (key, prop, _) in INFO_FIELDS.into_iter().chain([("copyrightStatus", "xmpRights:Marked", ""), ("copyrightUrl", "xmpRights:WebStatement", "")]) { - if !changed(key) { - continue; - } - while let Some((a, b, _)) = find_element(&x, prop) { - x.replace_range(a..b, ""); - } - while let Some((a, b, _)) = find_attr(&x, prop) { - x.replace_range(a..b, ""); - } - } - let get = |k: &str| info.get(k).filter(|_| changed(k)).cloned().unwrap_or(Value::Null); - let mut body = String::new(); - for (key, prop, kind) in INFO_FIELDS { - let vals: Vec = match get(key) { - Value::Array(a) => a.iter().filter_map(|v| v.as_str()).map(str::to_string).filter(|v| !v.is_empty()).collect(), - Value::String(s) if kind == "Bag" || kind == "Seq" => s.split([';', ',']).map(|v| v.trim().to_string()).filter(|v| !v.is_empty()).collect(), - Value::String(s) if !s.is_empty() => vec![s], - _ => Vec::new(), - }; - if vals.is_empty() { - continue; - } - let items: String = vals - .iter() - .map(|v| { - if kind == "Alt" { format!("{}", xml_escape(v)) } else { format!("{}", xml_escape(v)) } - }) - .collect(); - if kind.is_empty() { - body.push_str(&format!(" <{prop}>{}\n", xml_escape(&vals[0]))); - } else { - body.push_str(&format!(" <{prop}>{items}\n")); - } - } - match get("copyrightStatus").as_str() { - Some("copyrighted") => body.push_str(" True\n"), - Some("publicDomain") => body.push_str(" False\n"), - _ => {} - } - if let Some(u) = get("copyrightUrl").as_str().filter(|u| !u.is_empty()) { - body.push_str(&format!(" {}\n", xml_escape(u))); - } - if !body.is_empty() { - let desc = format!( - " \n{body} \n " - ); - let at = x.rfind("").unwrap_or(x.len()); - x.insert_str(at, &desc); - } - x -} - -fn file_info(s: &mut Session, p: &Value) -> Result { - let keys = ["title", "author", "authorTitle", "description", "keywords", "copyright", "copyrightStatus", "copyrightUrl"]; - let edits = p.as_object().is_some_and(|m| m.keys().any(|k| keys.contains(&k.as_str()))); - if edits { - let xmp = s.active().ok_or(EngineError::NoDocument)?.doc.metadata.xmp.clone(); - let new = write_file_info(xmp.as_deref(), p); - s.edit("File Info", |doc, _| { - doc.metadata.xmp = Some(new.into()); - Ok(()) - })?; - } - let d = s.active().ok_or(EngineError::NoDocument)?; - let mut info = read_file_info(d.doc.metadata.xmp.as_deref()); - if let Value::Object(m) = &mut info { - m.insert("camera".into(), camera_data(d.doc.metadata.exif.as_deref().map(Vec::as_slice), d.doc.metadata.xmp.as_deref())); - } - Ok(info) -} - -// ---------- Automate ---------- - -fn fit_image(s: &mut Session, p: &Value) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let (w, h) = (d.doc.size.width as f64, d.doc.size.height as f64); - let bw = size_param(p, "width").unwrap_or(w); - let bh = size_param(p, "height").unwrap_or(h); - let k = (bw / w).min(bh / h); - if (k > 1.0 && p.get("dontEnlarge").and_then(Value::as_bool).unwrap_or(false)) || ((w * k).round() == w && (h * k).round() == h) { - return Ok(json!({"width": w, "height": h, "changed": false})); - } - let (nw, nh) = ((w * k).round().max(1.0), (h * k).round().max(1.0)); - let resample = p.get("resample").and_then(Value::as_str).unwrap_or("bicubic"); - s.execute("image.imageSize", json!({"width": nw, "height": nh, "resample": resample}))?; - Ok(json!({"width": nw, "height": nh, "changed": true})) -} - -fn mode_name(m: ColorMode) -> &'static str { - match m { - ColorMode::Bitmap => "bitmap", - ColorMode::Grayscale => "grayscale", - ColorMode::Duotone => "duotone", - ColorMode::Indexed => "indexed", - ColorMode::Rgb => "rgb", - ColorMode::Cmyk => "cmyk", - ColorMode::Lab => "lab", - ColorMode::Multichannel => "multichannel", - } -} - -fn conditional_mode_change(s: &mut Session, p: &Value) -> Result { - let cmd = "file.automate.conditionalModeChange"; - let to = str_param(p, "to", cmd)?.to_ascii_lowercase(); - let to = match to.as_str() { - "gray" | "grayscale" => "grayscale", - "rgb" => "rgb", - "cmyk" => "cmyk", - "lab" => "lab", - other => return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("unsupported target mode \"{other}\" (rgb, grayscale, cmyk, lab)") }), - }; - let cur = mode_name(s.active().ok_or(EngineError::NoDocument)?.doc.mode); - // One spelling per source mode, for the array and the single-string forms alike (#7042). - let norm = |v: &str| { - let v = v.to_ascii_lowercase(); - if v == "gray" { "grayscale".to_string() } else { v } - }; - let from: Vec = match p.get("from") { - Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(norm).collect(), - Some(Value::String(v)) => vec![norm(v)], - _ => vec!["any".into()], - }; - if cur == to || !(from.iter().any(|f| f == "any" || f == cur)) { - return Ok(json!({"changed": false, "mode": cur})); - } - s.execute(&format!("image.mode.{to}"), json!({}))?; - Ok(json!({"changed": true, "mode": to})) -} - -/// One `[id, params]` / `{command, params}` / `{id, params}` step of an action. -fn parse_steps(v: &Value) -> Result> { - let bad = |m: &str| EngineError::BadParams { cmd: "file.automate.batch".into(), msg: m.into() }; - let arr = v.as_array().ok_or_else(|| bad("\"steps\" must be an array"))?; - arr.iter() - .map(|st| match st { - Value::Array(a) if !a.is_empty() => { - Ok((a[0].as_str().ok_or_else(|| bad("step id must be a string"))?.to_string(), a.get(1).cloned().unwrap_or(json!({})))) - } - Value::Object(o) => { - let id = o.get("command").or_else(|| o.get("id")).and_then(Value::as_str).ok_or_else(|| bad("step needs \"command\""))?; - Ok((id.to_string(), o.get("params").cloned().unwrap_or(json!({})))) - } - Value::String(id) => Ok((id.clone(), json!({}))), - _ => Err(bad("each step is [id, params] or {\"command\", \"params\"}")), - }) - .collect() -} - -/// Inputs of a batch command: `"input"` is a folder or an array of files. -pub(crate) fn batch_inputs(p: &Value, cmd: &str) -> Result> { - match p.get("input").or_else(|| p.get("files")) { - Some(Value::Array(a)) => Ok(a.iter().filter_map(Value::as_str).map(str::to_string).collect()), - Some(Value::String(dir)) => list_images(dir), - _ => Err(EngineError::BadParams { cmd: cmd.into(), msg: "missing \"input\" (folder or array of files)".into() }), - } -} - -/// One input of a batch run: the file, and the folder it sits in relative to the input folder -/// (`""` at the top level, `"a/b"` two levels down), which its result keeps under `output`. -#[derive(Clone, Debug, PartialEq)] -pub(crate) struct BatchInput { - pub path: String, - pub rel_dir: String, -} - -/// Subfolders below a batch input folder are walked at most this deep ("Include All Subfolders"). -pub(crate) const MAX_SUBFOLDER_DEPTH: usize = 32; -/// A batch over subfolders lists at most this many files; a larger tree is an error, not a run -/// that silently stops partway. -pub(crate) const MAX_SUBFOLDER_FILES: usize = 100_000; - -/// [`batch_inputs`] for the commands whose Photoshop dialog has "Include All Subfolders" (Batch, -/// Image Processor): with `"includeSubfolders": true` a folder input also yields the images in its -/// subfolders, each tagged with its relative folder. `output` (when inside the input folder, as -/// the dialog's default `
\n{t}\n\n\n\n\n\n", - t = html_escape(title) - ); - for (j, mut tds) in by_row.into_iter().enumerate() { - tds.sort_by_key(|(c, _)| *c); - s.push_str("\t\n"); - for (_, td) in tds { - s.push_str(&td); - } - if let Some(sp) = spacer { - s.push_str(&format!("\t\t\n", html_escape(sp), ys[j + 1] - ys[j])); - } - s.push_str("\t\n"); - } - if let Some(sp) = spacer { - s.push_str("\t\n"); - for i in 0..nc { - s.push_str(&format!("\t\t\n", html_escape(sp), xs[i + 1] - xs[i])); - } - s.push_str("\t\t\n\t\n"); - } - s.push_str("
\n\t\t\t\"\"
\n\t\t\t\"\"
\n\n\n\n"); - s -} - -/// File › Export › Save for Web (Legacy). -fn save_for_web(s: &mut Session, p: &Value) -> Result { - save_for_web_impl(s, p, &mut write_file, true) -} - -/// Save for Web through a platform writer (native files or browser downloads). -/// The writer receives every image, spacer and HTML file. A write error stops the export; -/// only a complete export remembers its settings and fires the export event. A custom writer -/// that targets the local filesystem must enforce its own path confinement. -pub fn save_for_web_with_writer(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - save_for_web_impl(s, p, write, false) -} - -/// Settings to seed the Save for Web dialog from on the next launch: `file_menu` is session -/// state, so a complete export also writes the preferences' remembered dialog settings (like -/// Fill, Liquify and the filter dialogs). The destination is per export, never remembered. -fn remember_web_settings(s: &mut Session, cmd: &str, settings: &Value) { - let mut m = settings.clone(); - if let Some(o) = m.as_object_mut() { - for k in ["path", "dir", "trustedSliceHtml"] { - o.remove(k); - } - } - s.prefs.edit(|p| { - p.dialogs.insert(cmd.to_string(), m); - }); -} - -fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>, native_paths: bool) -> Result { - let cmd = "file.export.saveForWebLegacy"; - if let Some(authorize) = s.authorize { - authorize(cmd, p)?; - } - // Direct platform calls must export the moved selection as it appears on the canvas, - // just as Session::execute does before dispatching the native command. - crate::float_cmds::before_command(s, cmd)?; - let st = WebSettings::from_params(p, cmd)?; - let d = s.active().ok_or(EngineError::NoDocument)?; - let doc = d.doc.clone(); - let (wdoc, sx, sy) = web_document(&doc, p, &st)?; - let buf = photocraft_compose::flatten(&wdoc); - let bw = wdoc.size.width as usize; - let icc = wdoc.icc_profile.as_deref().map(|v| v.as_slice()); - let xmp = web_xmp(&doc, st.metadata); - let exif = web_exif(&doc, st.metadata); - let dpi = wdoc.resolution_dpi; - let warnings = web_warnings(&st, exif, dpi); - let all = slices::resolve(&doc); - let pick = p.get("slices").and_then(Value::as_str).unwrap_or("all"); - let numbers: Option> = p.get("numbers").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()); - let chosen: Vec<&ResolvedSlice> = all - .iter() - .filter(|r| match (&numbers, pick) { - (Some(n), _) => n.contains(&(r.number as u64)), - (None, "user") => r.origin != photocraft_doc::SliceOrigin::Auto, - _ => true, - }) - .collect(); - let single = p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()); - let dir = p.get("dir").and_then(Value::as_str).filter(|v| !v.is_empty()); - let mut last_web = p.clone(); - // A trusted-markup decision applies to this export only, never to another document opened - // with the dialog's remembered settings. - if let Some(last) = last_web.as_object_mut() { - last.remove("trustedSliceHtml"); - } - // Estimate only (the dialog's annotations): the whole image, or each chosen slice. - if single.is_none() && dir.is_none() { - let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?; - return Ok( - json!({"format": o.ext, "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "colorTable": o.color_table.iter().map(|c| rgb_hex(*c)).collect::>(), "transparentIndex": o.transparent_index}), - ); - } - if let Some(path) = single.filter(|_| dir.is_none() && (all.len() == 1 || p.get("slices").is_none())) { - let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?; - write(path, &o.bytes)?; - remember_web_settings(s, cmd, &last_web); - s.file_menu.last_web = Some(last_web); - crate::automate_cmds::fire_event(s, "export"); - return Ok(json!({"files": [path], "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "warnings": warnings})); - } - let dir = - dir.map(str::to_string).or_else(|| single.and_then(|f| std::path::Path::new(f).parent().map(|d| d.to_string_lossy().into_owned()))).unwrap_or_default(); - let html = p.get("html").and_then(Value::as_bool).unwrap_or(false); - let images = web_images_folder(p.get("imagesFolder").and_then(Value::as_str).unwrap_or("images"), cmd)?; - let trusted_slice_html = p.get("trustedSliceHtml").and_then(Value::as_bool).unwrap_or(false); - let base = portable_generated_stem(single.map(stem).unwrap_or_else(|| slices::base_name(&doc))); - let mut files = Vec::new(); - let mut cells: Vec<(Rect, String, String)> = Vec::new(); - let mut total = 0usize; - // Output names are unique (case-insensitively, for macOS and Windows file systems): two - // slices named alike, or names that sanitize alike, must not overwrite each other. The HTML - // page's spacer image is reserved. - let mut used: std::collections::HashSet = std::collections::HashSet::new(); - if html { - used.insert("spacer.gif".into()); - } - let mut unique = |stem: &str, ext: &str| { - let mut name = format!("{stem}.{ext}"); - let mut k = 2u32; - while !used.insert(name.to_lowercase()) { - name = format!("{stem}_{k}.{ext}"); - k = k.saturating_add(1); - } - name - }; - // Slices never overlap here: one covered by later slices comes as its visible pieces (see - // `slices::resolve`), each its own image and cell, as Photoshop's subslices. A no-image cell's - // text goes into its first piece only. - let mut texted = std::collections::HashSet::new(); - for r in &chosen { - let piece = scale_rect(r.rect, sx, sy).intersect(&wdoc.bounds()); - if piece.is_empty() { - continue; - } - let stored = r.id.and_then(|id| doc.slices.get(id)); - if r.kind == SliceKind::NoImage { - let text = stored - .filter(|s| texted.insert(s.id)) - .map(|s| if trusted_slice_html && s.cell_text_is_html { s.cell_text.clone() } else { html_escape(&s.cell_text) }) - .unwrap_or_default(); - let bg = stored.and_then(|s| s.background).map(|c| format!(" bgcolor=\"#{:02X}{:02X}{:02X}\"", c[1], c[2], c[3])).unwrap_or_default(); - cells.push((piece, bg, text)); - continue; - } - let o = optimize(&buf.px, bw, piece, &st, icc, exif, xmp.as_deref(), dpi, false)?; - let name = unique(&slice_file(&r.name), o.ext); - let rel = if images.is_empty() { name.clone() } else { format!("{images}/{name}") }; - let out = join(&dir, &rel); - write(&web_derived_path(&dir, &rel, native_paths)?, &o.bytes)?; - total += o.bytes.len(); - files.push(out); - let alt = stored.map_or(String::new(), |s| html_escape(&s.alt)); - let img = format!("\n\t\t\t\"{alt}\"", html_escape(&rel), piece.width(), piece.height()); - let body = match stored.filter(|s| safe_slice_url(&s.url)) { - Some(s) => { - let target = if s.target.is_empty() { String::new() } else { format!(" target=\"{}\"", html_escape(&s.target)) }; - format!("\n\t\t\t{img}", html_escape(&s.url)) - } - None => img, - }; - cells.push((piece, String::new(), body)); - } - let mut html_path = None; - if html { - let grid = cells.len() > 1; - let spacer = grid.then(|| if images.is_empty() { "spacer.gif".to_string() } else { format!("{images}/spacer.gif") }); - if let Some(sp) = &spacer { - let gif = photocraft_codecs::web::encode_gif_indexed(1, 1, &[0], &[[0, 0, 0]], Some(0), false).map_err(other)?; - write(&web_derived_path(&dir, sp, native_paths)?, &gif)?; - } - let page = html_table(&base, wdoc.size.width, wdoc.size.height, &cells, spacer.as_deref()); - let hp = join(&dir, &format!("{base}.html")); - write(&web_derived_path(&dir, &format!("{base}.html"), native_paths)?, page.as_bytes())?; - html_path = Some(hp); - } - remember_web_settings(s, cmd, &last_web); - s.file_menu.last_web = Some(last_web); - crate::automate_cmds::fire_event(s, "export"); - Ok( - json!({"files": files, "html": html_path, "bytes": total, "slices": chosen.len(), "width": wdoc.size.width, "height": wdoc.size.height, "warnings": warnings}), - ) -} - -// ---------- Export Preferences / Quick Export ---------- - -/// File › Export › Export Preferences…: sets the given `export.*` preferences through `prefs.set` -/// (validated like any other preference) and returns the whole section. -fn export_preferences(s: &mut Session, p: &Value) -> Result { - let cmd = "file.export.exportPreferences"; - let mut values = serde_json::Map::new(); - for (k, key) in [ - ("quickExportFormat", "export.quickExportFormat"), - ("quickExportLocation", "export.quickExportLocation"), - ("jpegQuality", "export.jpegQuality"), - ("webpLossless", "export.webpLossless"), - ("webpQuality", "export.webpQuality"), - ("metadata", "export.metadata"), - ("convertToSrgb", "export.convertToSrgb"), - ] { - if let Some(v) = p.get(k) { - values.insert(key.into(), v.clone()); - } - } - if !values.is_empty() { - s.execute("prefs.set", json!({"values": values})).map_err(|e| bad(cmd, e.to_string()))?; - } - Ok(json!({"section": "export", "values": s.prefs().get("export").unwrap_or(Value::Null)})) -} - -/// The Quick Export format's extension (Export Preferences › Format). -fn quick_export_ext(s: &Session) -> String { - serde_json::to_value(s.prefs().export.quick_export_format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "png".into()) -} - -/// Where Quick Export writes the active document with no `path` given: `.` beside -/// its file, when Export Preferences › Location is Same Folder and the document has a file. -pub fn quick_export_target(s: &Session) -> Option { - let same = s.prefs().export.quick_export_location == crate::prefs::ExportLocation::SameFolder; - let dp = s.active()?.path.as_deref().filter(|_| same)?; - let dir = std::path::Path::new(dp).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(); - Some(join(&dir, &format!("{}.{}", stem(dp), quick_export_ext(s)))) -} - -/// Whether [`quick_export_target`] is the active document's own file (a document opened from -/// `photo.png` and exported as PNG), which Quick Export must not replace without asking (#6599). -pub fn quick_export_target_is_own_file(s: &Session) -> bool { - let own = s.active().and_then(|d| d.path.as_deref()); - quick_export_target(s).zip(own).is_some_and(|(target, own)| crate::file_cmds::same_file(&target, own)) -} - -/// File › Export › Quick Export as : the format, quality, metadata, colour space and -/// location from Export Preferences. `path` overrides the location ("ask" needs one). -fn quick_export(s: &mut Session, p: &Value) -> Result { - let cmd = "file.export.quickExport"; - let prefs = s.prefs().export.clone(); - let fmt = quick_export_ext(s); - let path = match p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()) { - Some(v) => v.to_string(), - None => { - let Some(target) = quick_export_target(s) else { - return Err(bad(cmd, "missing `path` (Export Preferences › Location is \"ask\", or the document was never saved)")); - }; - // The document's own file is never replaced by an export the user didn't name (#6599). - if quick_export_target_is_own_file(s) { - return Err(bad(cmd, format!("the export would replace the document's own file {target}; give a `path`"))); - } - target - } - }; - // The name typed in the save dialog wins over Export Preferences' format: Quick Export as PNG - // renamed to `photo.jpeg` must write a JPEG, not PNG bytes upload checks refuse (#8519). - let fmt = match crate::file_cmds::extension(&path).as_deref() { - None => fmt, - Some("jpg" | "jpeg") => "jpg".into(), - Some(e @ ("png" | "gif" | "webp" | "exr")) => e.into(), - Some(e) => return Err(bad(cmd, format!("Quick Export writes PNG, JPEG, GIF, WebP or EXR, not .{e}; use Export As"))), - }; - let d = s.active().ok_or(EngineError::NoDocument)?; - let doc = d.doc.clone(); - if fmt == "exr" { - // EXR keeps floating-point scene values. The ordinary exporter converts to linear - // light; the web/sRGB pipeline would instead clamp HDR and negative values. - let opts = photocraft_io::ExportOptions { xmp: photocraft_io::XmpEmbed::None, ..Default::default() }; - let out = photocraft_io::export(&doc, "exr", &opts).map_err(other)?; - write_file(&path, &out.bytes)?; - crate::automate_cmds::fire_event(s, "export"); - return Ok(json!({"path": path, "format": fmt, "bytes": out.bytes.len(), "warnings": out.warnings})); - } - let metadata = serde_json::to_value(prefs.metadata).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); - let mut o = serde_json::Map::new(); - o.insert( - "metadata".into(), - json!(if metadata == "all" { - "all" - } else if metadata == "none" { - "none" - } else { - "copyright" - }), - ); - o.insert("convertToSrgb".into(), json!(prefs.convert_to_srgb)); - o.insert("transparency".into(), json!(true)); - o.insert("matte".into(), json!("#ffffff")); - match fmt.as_str() { - "jpg" => { - o.insert("format".into(), json!("jpeg")); - o.insert("quality".into(), json!(prefs.jpeg_quality.min(100))); - } - "gif" => { - o.insert("format".into(), json!("gif")); - } - "webp" => { - // WebP uses the regular exporter. Its optional quality is in the Photoshop-style - // 0–12 save scale: invert that mapping so the codec receives the chosen 1–100. - // Keeping quality absent preserves the historical lossless Quick Export behavior. - let (wdoc, _, _) = web_document(&doc, &json!({}), &WebSettings { convert_to_srgb: prefs.convert_to_srgb, ..Default::default() })?; - let quality = if prefs.webp_lossless { None } else { Some((f64::from(prefs.webp_quality.clamp(1, 100)) - 1.0) * 12.0 / 99.0) }; - let warnings = crate::file_cmds::save_doc(&wdoc, &path, quality)?; - crate::automate_cmds::fire_event(s, "export"); - return Ok(json!({"path": path, "format": fmt, "warnings": warnings})); - } - _ => { - o.insert("format".into(), json!("png24")); - } - } - let q = Value::Object(o); - let st = WebSettings::from_params(&q, cmd)?; - let (wdoc, _, _) = web_document(&doc, &json!({}), &st)?; - let buf = photocraft_compose::flatten(&wdoc); - let xmp = web_xmp(&doc, st.metadata); - let exif = web_exif(&doc, st.metadata); - let opt = optimize( - &buf.px, - wdoc.size.width as usize, - wdoc.bounds(), - &st, - wdoc.icc_profile.as_deref().map(|v| v.as_slice()), - exif, - xmp.as_deref(), - wdoc.resolution_dpi, - false, - )?; - write_file(&path, &opt.bytes)?; - crate::automate_cmds::fire_event(s, "export"); - Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len(), "warnings": web_warnings(&st, exif, wdoc.resolution_dpi)})) -} - -// ---------- Generate › Image Assets ---------- - -/// One asset requested by a layer name. -#[derive(Clone, Debug, PartialEq)] -pub struct AssetSpec { - /// Relative output path (folders allowed), extension included. - pub file: String, - /// png8 | png24 | png32 | jpg | gif | webp - pub format: String, - /// JPEG quality 1..=100. - pub quality: Option, - /// Uniform scale (1.0 = 100 %). - pub scale: Option, - /// Target width / height in px (`?` = keep aspect). - pub width: Option, - pub height: Option, -} - -/// A `default` layer variant: size plus a folder (`low/`) or name suffix (`@2x`). -#[derive(Clone, Debug, Default, PartialEq)] -pub struct AssetDefault { - pub scale: Option, - pub width: Option, - pub height: Option, - pub folder: String, - pub suffix: String, -} - -fn unit_px(tok: &str, dpi: f64) -> Option> { - if tok == "?" { - return Some(None); - } - let (num, k) = if let Some(n) = tok.strip_suffix("px") { - (n, 1.0) - } else if let Some(n) = tok.strip_suffix("in") { - (n, dpi) - } else if let Some(n) = tok.strip_suffix("cm") { - (n, dpi / 2.54) - } else if let Some(n) = tok.strip_suffix("mm") { - (n, dpi / 25.4) - } else { - (tok, 1.0) - }; - num.trim().parse::().ok().filter(|v| *v > 0.0).map(|v| Some(v * k)) -} - -/// `200%` or `WxH` (units px/in/cm/mm, `?` wildcard) at the start of `item`; returns the size and -/// the rest. -fn parse_size(item: &str, dpi: f64) -> (Option, Option, Option, &str) { - let item = item.trim(); - let (first, rest) = item.split_once(char::is_whitespace).map_or((item, ""), |(a, b)| (a, b.trim())); - if let Some(pc) = first.strip_suffix('%').and_then(|n| n.parse::().ok()).filter(|v| *v > 0.0) { - return (Some(pc / 100.0), None, None, rest); - } - // "100x50", "2in x 1in", "?x100" - if let Some((w, h)) = first.split_once(['x', 'X']).filter(|(w, h)| !w.is_empty() && !h.is_empty()) - && let (Some(w), Some(h)) = (unit_px(w, dpi), unit_px(h, dpi)) - { - return (None, w, h, rest); - } - // Spaced form "2in x 1in name.png": three tokens. - let toks: Vec<&str> = item.split_whitespace().collect(); - if toks.len() >= 4 - && toks[1].eq_ignore_ascii_case("x") - && let (Some(w), Some(h)) = (unit_px(toks[0], dpi), unit_px(toks[2], dpi)) - { - // Skip exactly the three size tokens; searching for the name's first word could match inside the size. - let mut rest = item; - for _ in 0..3 { - rest = rest.trim_start().trim_start_matches(|c: char| !c.is_whitespace()); - } - return (None, w, h, rest.trim_start()); - } - (None, None, None, item) -} - -/// Parses a layer name into its asset specs (empty when it names no asset). -pub fn parse_asset_name(name: &str, dpi: f64) -> Vec { - let mut out = Vec::new(); - for item in name.split([',', '+']) { - let (scale, width, height, rest) = parse_size(item, dpi); - let file = rest.trim(); - let Some((stem_part, ext)) = file.rsplit_once('.') else { continue }; - if stem_part.is_empty() { - continue; - } - let ext_l = ext.to_ascii_lowercase(); - let (format, quality, out_ext) = if let Some(q) = ext_l.strip_prefix("jpeg").or_else(|| ext_l.strip_prefix("jpg")) { - let q = q.trim(); - let quality = if q.is_empty() { - None - } else if let Some(pc) = q.strip_suffix('%') { - pc.parse::().ok().map(|v| v.clamp(1, 100) as u8) - } else { - // 1–10 scale. - q.parse::().ok().map(|v| (v.clamp(1, 10) * 10) as u8) - }; - if !q.is_empty() && quality.is_none() { - continue; - } - ("jpg".to_string(), quality, if ext_l.starts_with("jpeg") { "jpeg" } else { "jpg" }) - } else { - match ext_l.as_str() { - "png" | "png32" => ("png32".to_string(), None, "png"), - "png24" => ("png24".to_string(), None, "png"), - "png8" => ("png8".to_string(), None, "png"), - "gif" => ("gif".to_string(), None, "gif"), - "webp" => ("webp".to_string(), None, "webp"), - _ => continue, - } - }; - out.push(AssetSpec { file: format!("{stem_part}.{out_ext}"), format, quality, scale, width, height }); - } - out -} - -/// Parses a `default …` layer name into its variants. -pub fn parse_defaults(name: &str, dpi: f64) -> Option> { - let rest = name.trim().strip_prefix("default")?; - if !rest.is_empty() && !rest.starts_with(char::is_whitespace) { - return None; - } - let mut v = Vec::new(); - for item in rest.split([',', '+']) { - let (scale, width, height, tail) = parse_size(item, dpi); - let tail = tail.trim(); - let (folder, suffix) = match tail.rfind('/') { - Some(i) => (tail[..=i].to_string(), tail[i + 1..].to_string()), - None => (String::new(), tail.to_string()), - }; - if scale.is_none() && width.is_none() && height.is_none() && folder.is_empty() && suffix.is_empty() { - continue; - } - v.push(AssetDefault { scale, width, height, folder, suffix }); - } - Some(v) -} - -fn asset_settings(spec: &AssetSpec) -> WebSettings { - let base = WebSettings { transparency: true, matte: None, metadata: WebMetadata::None, ..WebSettings::default() }; - match spec.format.as_str() { - "jpg" => WebSettings { format: WebFormat::Jpeg, quality: spec.quality.unwrap_or(90), matte: Some([1.0, 1.0, 1.0]), ..base }, - "png8" => WebSettings { format: WebFormat::Png8, dither: Dither::None, ..base }, - "png24" => WebSettings { format: WebFormat::Png24, transparency: false, matte: Some([1.0, 1.0, 1.0]), ..base }, - "gif" => WebSettings { format: WebFormat::Gif, dither: Dither::None, ..base }, - _ => WebSettings { format: WebFormat::Png24, ..base }, - } -} - -/// Layer names and `default` folders are document data, so reject unsafe output components. -fn asset_path_components(relative: &str) -> Result> { - // Split both separator styles even on Unix, where a backslash would otherwise be a legal - // filename. This also catches Windows drive, rooted, and UNC paths on every platform. - let mut parts = Vec::new(); - for part in relative.split(['/', '\\']) { - if part.is_empty() - || part == "." - || part == ".." - || part.ends_with('.') - || part.ends_with(' ') - || part.contains(':') - || part.contains('\0') - || is_windows_device_name(part) - { - return Err(other(format!("asset path {relative:?} has an unsafe component {part:?}"))); - } - parts.push(part); - } - Ok(parts) -} - -/// Resolve a generated asset below the selected output directory. The atomic writer follows an -/// existing file symlink, so reject it and directory symlinks before writing. -fn asset_output_path(dir: &str, relative: &str) -> Result<(String, String)> { - if dir.is_empty() { - return Err(other("image assets need an output directory")); - } - let mut parts = asset_path_components(relative)?; - // Keep the caller's spelling in the result (for example /var on macOS), while writes use - // the canonical directory so a symlink in the selected root cannot move the destination. - let mut reported = std::path::PathBuf::from(dir); - for part in &parts { - reported.push(part); - } - let file = parts.pop().ok_or_else(|| other(format!("asset path {relative:?} is empty")))?; - let chosen_root: std::path::PathBuf = std::path::Path::new(dir).components().collect(); - std::fs::create_dir_all(&chosen_root).map_err(|e| other(format!("asset output directory {dir:?}: {e}")))?; - // The caller chose this root, so a symlink to an existing directory is intentional. All - // document-derived components below it are checked against its canonical target. - let root = std::fs::canonicalize(&chosen_root).map_err(|e| other(format!("asset output directory {dir:?}: {e}")))?; - let mut parent = root.clone(); - for part in parts { - parent.push(part); - match std::fs::symlink_metadata(&parent) { - Ok(meta) if meta.file_type().is_symlink() => { - return Err(other(format!("asset path {relative:?} crosses a symlink at {}", parent.display()))); - } - Ok(meta) if !meta.is_dir() => { - return Err(other(format!("asset path {relative:?} has a non-directory at {}", parent.display()))); - } - Ok(_) => {} - Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - std::fs::create_dir(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?; - } - Err(e) => return Err(other(format!("asset folder {}: {e}", parent.display()))), - } - let actual = std::fs::canonicalize(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?; - if !actual.starts_with(&root) { - return Err(other(format!("asset path {relative:?} escapes output directory {dir:?}"))); - } - parent = actual; - } - let parent = std::fs::canonicalize(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?; - if !parent.starts_with(&root) { - return Err(other(format!("asset path {relative:?} escapes output directory {dir:?}"))); - } - let output = parent.join(file); - match std::fs::symlink_metadata(&output) { - Ok(meta) if meta.file_type().is_symlink() => { - return Err(other(format!("asset path {relative:?} points to a symlink"))); - } - Ok(meta) if !meta.is_file() => { - return Err(other(format!("asset path {relative:?} is not a file"))); - } - Ok(_) => {} - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => return Err(other(format!("asset path {relative:?}: {e}"))), - } - Ok((output.to_string_lossy().into_owned(), reported.to_string_lossy().into_owned())) -} - -/// Exports every asset named by `doc`'s layers into `dir`. Returns (files, errors). -/// -/// Each file is written once per run (#6614): when two layers (or two default variants) name the -/// same file, the one higher in the Layers panel keeps it and the other is reported in `errors`. -/// Names are compared ignoring case, as `Logo.png` and `logo.png` are one file on Windows and -/// macOS. -/// -/// A layer is trimmed to its visible pixels; an artboard keeps its whole board, transparent edges -/// included, as File › Export › Artboards to Files writes it (Photoshop's Generator exports an -/// artboard asset at the board's bounds). -pub fn generate_assets(doc: &Document, dir: &str) -> (Vec, Vec) { - let dpi = f64::from(doc.resolution_dpi.max(1.0)); - let mut defaults: Option> = None; - let mut by_layer: Vec> = Vec::new(); - for (_, _, l) in doc.walk() { - if let Some(d) = parse_defaults(&l.name, dpi) { - defaults = Some(d); - continue; - } - if matches!(l.content, LayerContent::Adjustment(_)) { - continue; - } - by_layer.push(parse_asset_name(&l.name, dpi).into_iter().map(|spec| (l.id, spec)).collect()); - } - // Top layer first, as the Layers panel lists them (`walk` goes bottom to top). - let jobs: Vec<(LayerId, AssetSpec)> = by_layer.into_iter().rev().flatten().collect(); - let variants: Vec = match defaults { - Some(d) if !d.is_empty() => d, - _ => vec![AssetDefault::default()], - }; - let mut files = Vec::new(); - let mut errors = Vec::new(); - let mut written = std::collections::HashSet::new(); - for (id, spec) in &jobs { - for v in &variants { - let r = (|| -> Result { - let (name_stem, ext) = spec.file.rsplit_once('.').unwrap_or((spec.file.as_str(), "png")); - let rel = format!("{}{}{}.{ext}", v.folder, name_stem, v.suffix); - let key = asset_path_components(&rel)?.join("/").to_lowercase(); - if written.contains(&key) { - return Err(other(format!("{rel}: another layer already writes this file; rename one of the layers"))); - } - let mut one = match crate::artboard_cmds::artboard_document(doc, *id)? { - // Like Photoshop's Generator, a board with nothing on it is refused rather - // than written as a blank file. - Some(board) if !has_pixels(&board) => return Err(other("the layer is empty")), - Some(board) => board, - None => crate::layer_menu_cmds::layer_document(doc, *id)?, - }; - one.metadata = Default::default(); - let (w0, h0) = (f64::from(one.size.width), f64::from(one.size.height)); - // The layer's own size spec wins; default variants scale on top of it. - let mut k = spec.scale.unwrap_or(1.0); - let (mut tw, mut th) = (w0 * k, h0 * k); - match (spec.width, spec.height) { - (Some(w), Some(h)) => (tw, th) = (w, h), - (Some(w), None) => (tw, th) = (w, h0 * w / w0), - (None, Some(h)) => (tw, th) = (w0 * h / h0, h), - _ => {} - } - k = v.scale.unwrap_or(1.0); - tw *= k; - th *= k; - match (v.width, v.height) { - (Some(w), Some(h)) => (tw, th) = (w, h), - (Some(w), None) => (tw, th) = (w, th * w / tw), - (None, Some(h)) => (tw, th) = (tw * h / th, h), - _ => {} - } - let st = asset_settings(spec); - let p = json!({"width": tw.round().max(1.0), "height": th.round().max(1.0)}); - let (wdoc, _, _) = web_document(&one, &p, &WebSettings { convert_to_srgb: true, ..st.clone() })?; - if spec.format == "webp" { - let (out, reported) = asset_output_path(dir, &rel)?; - crate::file_cmds::save_doc(&wdoc, &out, None)?; - written.insert(key); - return Ok(reported); - } - let buf = photocraft_compose::flatten(&wdoc); - let o = optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, None, wdoc.resolution_dpi, false)?; - let (out, reported) = asset_output_path(dir, &rel)?; - write_file(&out, &o.bytes)?; - written.insert(key); - Ok(reported) - })(); - match r { - Ok(f) => files.push(f), - Err(e) => errors.push(json!({"asset": spec.file, "error": e.to_string()})), - } - } - } - (files, errors) -} - -/// Whether any pixel of `doc` is not fully transparent. -fn has_pixels(doc: &Document) -> bool { - photocraft_compose::render(doc, doc.bounds()).px.iter().any(|q| q[3] > 0.0) -} - -/// `/-assets`. -pub fn assets_dir(doc_path: &str) -> String { - let p = std::path::Path::new(doc_path); - let dir = p.parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(); - join(&dir, &format!("{}-assets", stem(doc_path))) -} - -/// File › Generate › Image Assets: toggles generation for the active document (or sets it with -/// `on`) and, when it is on and the output folder is known, writes the assets now. -fn image_assets(s: &mut Session, p: &Value) -> Result { - let d = s.active().ok_or(EngineError::NoDocument)?; - let id: DocId = d.doc.id; - let was = s.file_menu.image_assets.contains(&id); - let on = p.get("on").and_then(Value::as_bool).unwrap_or(!was); - if on { - if !was { - s.file_menu.image_assets.push(id); - } - } else { - s.file_menu.image_assets.retain(|x| *x != id); - } - let d = s.active().ok_or(EngineError::NoDocument)?; - let dir = p.get("dir").and_then(Value::as_str).map(str::to_string).or_else(|| d.path.as_deref().map(assets_dir)); - if !on { - return Ok(json!({"enabled": false})); - } - match dir { - Some(dir) if !cfg!(target_arch = "wasm32") => { - let (files, errors) = generate_assets(&d.doc, &dir); - Ok(json!({"enabled": true, "dir": dir, "files": files, "errors": errors})) - } - _ => Ok(json!({"enabled": true, "dir": null, "files": [], "note": "assets are written when the document is saved"})), - } -} - /// After a save: regenerate the document's image assets when Generate › Image Assets is on. pub fn on_saved(s: &Session, index: usize) -> Option { let d = s.documents().get(index)?; diff --git a/crates/engine/src/web_cmds/assets.rs b/crates/engine/src/web_cmds/assets.rs new file mode 100644 index 0000000000..23f2da990c --- /dev/null +++ b/crates/engine/src/web_cmds/assets.rs @@ -0,0 +1,368 @@ +use super::optimizer::{optimize, web_document}; +use super::settings::{WebFormat, WebMetadata, WebSettings}; +use super::*; + +// ---------- Generate › Image Assets ---------- + +/// One asset requested by a layer name. +#[derive(Clone, Debug, PartialEq)] +pub struct AssetSpec { + /// Relative output path (folders allowed), extension included. + pub file: String, + /// png8 | png24 | png32 | jpg | gif | webp + pub format: String, + /// JPEG quality 1..=100. + pub quality: Option, + /// Uniform scale (1.0 = 100 %). + pub scale: Option, + /// Target width / height in px (`?` = keep aspect). + pub width: Option, + pub height: Option, +} + +/// A `default` layer variant: size plus a folder (`low/`) or name suffix (`@2x`). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AssetDefault { + pub scale: Option, + pub width: Option, + pub height: Option, + pub folder: String, + pub suffix: String, +} + +fn unit_px(tok: &str, dpi: f64) -> Option> { + if tok == "?" { + return Some(None); + } + let (num, k) = if let Some(n) = tok.strip_suffix("px") { + (n, 1.0) + } else if let Some(n) = tok.strip_suffix("in") { + (n, dpi) + } else if let Some(n) = tok.strip_suffix("cm") { + (n, dpi / 2.54) + } else if let Some(n) = tok.strip_suffix("mm") { + (n, dpi / 25.4) + } else { + (tok, 1.0) + }; + num.trim().parse::().ok().filter(|v| *v > 0.0).map(|v| Some(v * k)) +} + +/// `200%` or `WxH` (units px/in/cm/mm, `?` wildcard) at the start of `item`; returns the size and +/// the rest. +fn parse_size(item: &str, dpi: f64) -> (Option, Option, Option, &str) { + let item = item.trim(); + let (first, rest) = item.split_once(char::is_whitespace).map_or((item, ""), |(a, b)| (a, b.trim())); + if let Some(pc) = first.strip_suffix('%').and_then(|n| n.parse::().ok()).filter(|v| *v > 0.0) { + return (Some(pc / 100.0), None, None, rest); + } + // "100x50", "2in x 1in", "?x100" + if let Some((w, h)) = first.split_once(['x', 'X']).filter(|(w, h)| !w.is_empty() && !h.is_empty()) + && let (Some(w), Some(h)) = (unit_px(w, dpi), unit_px(h, dpi)) + { + return (None, w, h, rest); + } + // Spaced form "2in x 1in name.png": three tokens. + let toks: Vec<&str> = item.split_whitespace().collect(); + if toks.len() >= 4 + && toks[1].eq_ignore_ascii_case("x") + && let (Some(w), Some(h)) = (unit_px(toks[0], dpi), unit_px(toks[2], dpi)) + { + // Skip exactly the three size tokens; searching for the name's first word could match inside the size. + let mut rest = item; + for _ in 0..3 { + rest = rest.trim_start().trim_start_matches(|c: char| !c.is_whitespace()); + } + return (None, w, h, rest.trim_start()); + } + (None, None, None, item) +} + +/// Parses a layer name into its asset specs (empty when it names no asset). +pub fn parse_asset_name(name: &str, dpi: f64) -> Vec { + let mut out = Vec::new(); + for item in name.split([',', '+']) { + let (scale, width, height, rest) = parse_size(item, dpi); + let file = rest.trim(); + let Some((stem_part, ext)) = file.rsplit_once('.') else { continue }; + if stem_part.is_empty() { + continue; + } + let ext_l = ext.to_ascii_lowercase(); + let (format, quality, out_ext) = if let Some(q) = ext_l.strip_prefix("jpeg").or_else(|| ext_l.strip_prefix("jpg")) { + let q = q.trim(); + let quality = if q.is_empty() { + None + } else if let Some(pc) = q.strip_suffix('%') { + pc.parse::().ok().map(|v| v.clamp(1, 100) as u8) + } else { + // 1–10 scale. + q.parse::().ok().map(|v| (v.clamp(1, 10) * 10) as u8) + }; + if !q.is_empty() && quality.is_none() { + continue; + } + ("jpg".to_string(), quality, if ext_l.starts_with("jpeg") { "jpeg" } else { "jpg" }) + } else { + match ext_l.as_str() { + "png" | "png32" => ("png32".to_string(), None, "png"), + "png24" => ("png24".to_string(), None, "png"), + "png8" => ("png8".to_string(), None, "png"), + "gif" => ("gif".to_string(), None, "gif"), + "webp" => ("webp".to_string(), None, "webp"), + _ => continue, + } + }; + out.push(AssetSpec { file: format!("{stem_part}.{out_ext}"), format, quality, scale, width, height }); + } + out +} + +/// Parses a `default …` layer name into its variants. +pub fn parse_defaults(name: &str, dpi: f64) -> Option> { + let rest = name.trim().strip_prefix("default")?; + if !rest.is_empty() && !rest.starts_with(char::is_whitespace) { + return None; + } + let mut v = Vec::new(); + for item in rest.split([',', '+']) { + let (scale, width, height, tail) = parse_size(item, dpi); + let tail = tail.trim(); + let (folder, suffix) = match tail.rfind('/') { + Some(i) => (tail[..=i].to_string(), tail[i + 1..].to_string()), + None => (String::new(), tail.to_string()), + }; + if scale.is_none() && width.is_none() && height.is_none() && folder.is_empty() && suffix.is_empty() { + continue; + } + v.push(AssetDefault { scale, width, height, folder, suffix }); + } + Some(v) +} + +fn asset_settings(spec: &AssetSpec) -> WebSettings { + let base = WebSettings { transparency: true, matte: None, metadata: WebMetadata::None, ..WebSettings::default() }; + match spec.format.as_str() { + "jpg" => WebSettings { format: WebFormat::Jpeg, quality: spec.quality.unwrap_or(90), matte: Some([1.0, 1.0, 1.0]), ..base }, + "png8" => WebSettings { format: WebFormat::Png8, dither: Dither::None, ..base }, + "png24" => WebSettings { format: WebFormat::Png24, transparency: false, matte: Some([1.0, 1.0, 1.0]), ..base }, + "gif" => WebSettings { format: WebFormat::Gif, dither: Dither::None, ..base }, + _ => WebSettings { format: WebFormat::Png24, ..base }, + } +} + +/// Layer names and `default` folders are document data, so reject unsafe output components. +pub(super) fn asset_path_components(relative: &str) -> Result> { + // Split both separator styles even on Unix, where a backslash would otherwise be a legal + // filename. This also catches Windows drive, rooted, and UNC paths on every platform. + let mut parts = Vec::new(); + for part in relative.split(['/', '\\']) { + if part.is_empty() + || part == "." + || part == ".." + || part.ends_with('.') + || part.ends_with(' ') + || part.contains(':') + || part.contains('\0') + || is_windows_device_name(part) + { + return Err(other(format!("asset path {relative:?} has an unsafe component {part:?}"))); + } + parts.push(part); + } + Ok(parts) +} + +/// Resolve a generated asset below the selected output directory. The atomic writer follows an +/// existing file symlink, so reject it and directory symlinks before writing. +pub(super) fn asset_output_path(dir: &str, relative: &str) -> Result<(String, String)> { + if dir.is_empty() { + return Err(other("image assets need an output directory")); + } + let mut parts = asset_path_components(relative)?; + // Keep the caller's spelling in the result (for example /var on macOS), while writes use + // the canonical directory so a symlink in the selected root cannot move the destination. + let mut reported = std::path::PathBuf::from(dir); + for part in &parts { + reported.push(part); + } + let file = parts.pop().ok_or_else(|| other(format!("asset path {relative:?} is empty")))?; + let chosen_root: std::path::PathBuf = std::path::Path::new(dir).components().collect(); + std::fs::create_dir_all(&chosen_root).map_err(|e| other(format!("asset output directory {dir:?}: {e}")))?; + // The caller chose this root, so a symlink to an existing directory is intentional. All + // document-derived components below it are checked against its canonical target. + let root = std::fs::canonicalize(&chosen_root).map_err(|e| other(format!("asset output directory {dir:?}: {e}")))?; + let mut parent = root.clone(); + for part in parts { + parent.push(part); + match std::fs::symlink_metadata(&parent) { + Ok(meta) if meta.file_type().is_symlink() => { + return Err(other(format!("asset path {relative:?} crosses a symlink at {}", parent.display()))); + } + Ok(meta) if !meta.is_dir() => { + return Err(other(format!("asset path {relative:?} has a non-directory at {}", parent.display()))); + } + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + std::fs::create_dir(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?; + } + Err(e) => return Err(other(format!("asset folder {}: {e}", parent.display()))), + } + let actual = std::fs::canonicalize(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?; + if !actual.starts_with(&root) { + return Err(other(format!("asset path {relative:?} escapes output directory {dir:?}"))); + } + parent = actual; + } + let parent = std::fs::canonicalize(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?; + if !parent.starts_with(&root) { + return Err(other(format!("asset path {relative:?} escapes output directory {dir:?}"))); + } + let output = parent.join(file); + match std::fs::symlink_metadata(&output) { + Ok(meta) if meta.file_type().is_symlink() => { + return Err(other(format!("asset path {relative:?} points to a symlink"))); + } + Ok(meta) if !meta.is_file() => { + return Err(other(format!("asset path {relative:?} is not a file"))); + } + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(other(format!("asset path {relative:?}: {e}"))), + } + Ok((output.to_string_lossy().into_owned(), reported.to_string_lossy().into_owned())) +} + +/// Exports every asset named by `doc`'s layers into `dir`. Returns (files, errors). +/// +/// Each file is written once per run (#6614): when two layers (or two default variants) name the +/// same file, the one higher in the Layers panel keeps it and the other is reported in `errors`. +/// Names are compared ignoring case, as `Logo.png` and `logo.png` are one file on Windows and +/// macOS. +/// +/// A layer is trimmed to its visible pixels; an artboard keeps its whole board, transparent edges +/// included, as File › Export › Artboards to Files writes it (Photoshop's Generator exports an +/// artboard asset at the board's bounds). +pub fn generate_assets(doc: &Document, dir: &str) -> (Vec, Vec) { + let dpi = f64::from(doc.resolution_dpi.max(1.0)); + let mut defaults: Option> = None; + let mut by_layer: Vec> = Vec::new(); + for (_, _, l) in doc.walk() { + if let Some(d) = parse_defaults(&l.name, dpi) { + defaults = Some(d); + continue; + } + if matches!(l.content, LayerContent::Adjustment(_)) { + continue; + } + by_layer.push(parse_asset_name(&l.name, dpi).into_iter().map(|spec| (l.id, spec)).collect()); + } + // Top layer first, as the Layers panel lists them (`walk` goes bottom to top). + let jobs: Vec<(LayerId, AssetSpec)> = by_layer.into_iter().rev().flatten().collect(); + let variants: Vec = match defaults { + Some(d) if !d.is_empty() => d, + _ => vec![AssetDefault::default()], + }; + let mut files = Vec::new(); + let mut errors = Vec::new(); + let mut written = std::collections::HashSet::new(); + for (id, spec) in &jobs { + for v in &variants { + let r = (|| -> Result { + let (name_stem, ext) = spec.file.rsplit_once('.').unwrap_or((spec.file.as_str(), "png")); + let rel = format!("{}{}{}.{ext}", v.folder, name_stem, v.suffix); + let key = asset_path_components(&rel)?.join("/").to_lowercase(); + if written.contains(&key) { + return Err(other(format!("{rel}: another layer already writes this file; rename one of the layers"))); + } + let mut one = match crate::artboard_cmds::artboard_document(doc, *id)? { + // Like Photoshop's Generator, a board with nothing on it is refused rather + // than written as a blank file. + Some(board) if !has_pixels(&board) => return Err(other("the layer is empty")), + Some(board) => board, + None => crate::layer_menu_cmds::layer_document(doc, *id)?, + }; + one.metadata = Default::default(); + let (w0, h0) = (f64::from(one.size.width), f64::from(one.size.height)); + // The layer's own size spec wins; default variants scale on top of it. + let mut k = spec.scale.unwrap_or(1.0); + let (mut tw, mut th) = (w0 * k, h0 * k); + match (spec.width, spec.height) { + (Some(w), Some(h)) => (tw, th) = (w, h), + (Some(w), None) => (tw, th) = (w, h0 * w / w0), + (None, Some(h)) => (tw, th) = (w0 * h / h0, h), + _ => {} + } + k = v.scale.unwrap_or(1.0); + tw *= k; + th *= k; + match (v.width, v.height) { + (Some(w), Some(h)) => (tw, th) = (w, h), + (Some(w), None) => (tw, th) = (w, th * w / tw), + (None, Some(h)) => (tw, th) = (tw * h / th, h), + _ => {} + } + let st = asset_settings(spec); + let p = json!({"width": tw.round().max(1.0), "height": th.round().max(1.0)}); + let (wdoc, _, _) = web_document(&one, &p, &WebSettings { convert_to_srgb: true, ..st.clone() })?; + if spec.format == "webp" { + let (out, reported) = asset_output_path(dir, &rel)?; + crate::file_cmds::save_doc(&wdoc, &out, None)?; + written.insert(key); + return Ok(reported); + } + let buf = photocraft_compose::flatten(&wdoc); + let o = optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, None, wdoc.resolution_dpi, false)?; + let (out, reported) = asset_output_path(dir, &rel)?; + write_file(&out, &o.bytes)?; + written.insert(key); + Ok(reported) + })(); + match r { + Ok(f) => files.push(f), + Err(e) => errors.push(json!({"asset": spec.file, "error": e.to_string()})), + } + } + } + (files, errors) +} + +/// Whether any pixel of `doc` is not fully transparent. +fn has_pixels(doc: &Document) -> bool { + photocraft_compose::render(doc, doc.bounds()).px.iter().any(|q| q[3] > 0.0) +} + +/// `/-assets`. +pub fn assets_dir(doc_path: &str) -> String { + let p = std::path::Path::new(doc_path); + let dir = p.parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(); + join(&dir, &format!("{}-assets", stem(doc_path))) +} + +/// File › Generate › Image Assets: toggles generation for the active document (or sets it with +/// `on`) and, when it is on and the output folder is known, writes the assets now. +pub(super) fn image_assets(s: &mut Session, p: &Value) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let id: DocId = d.doc.id; + let was = s.file_menu.image_assets.contains(&id); + let on = p.get("on").and_then(Value::as_bool).unwrap_or(!was); + if on { + if !was { + s.file_menu.image_assets.push(id); + } + } else { + s.file_menu.image_assets.retain(|x| *x != id); + } + let d = s.active().ok_or(EngineError::NoDocument)?; + let dir = p.get("dir").and_then(Value::as_str).map(str::to_string).or_else(|| d.path.as_deref().map(assets_dir)); + if !on { + return Ok(json!({"enabled": false})); + } + match dir { + Some(dir) if !cfg!(target_arch = "wasm32") => { + let (files, errors) = generate_assets(&d.doc, &dir); + Ok(json!({"enabled": true, "dir": dir, "files": files, "errors": errors})) + } + _ => Ok(json!({"enabled": true, "dir": null, "files": [], "note": "assets are written when the document is saved"})), + } +} diff --git a/crates/engine/src/web_cmds/optimizer.rs b/crates/engine/src/web_cmds/optimizer.rs new file mode 100644 index 0000000000..98116d7d37 --- /dev/null +++ b/crates/engine/src/web_cmds/optimizer.rs @@ -0,0 +1,394 @@ +use super::settings::{WebFormat, WebMetadata, WebSettings}; +use super::*; + +// ---------- the image ---------- + +/// The document as Save for Web sees it: RGB (converted to sRGB unless told otherwise), resized +/// by `"width"`/`"height"`/`"percent"`, flattened. Returns the document and the scale factors. +pub fn web_document(doc: &Document, p: &Value, st: &WebSettings) -> Result<(Document, f64, f64)> { + let mut tmp = Session::new(); + tmp.add_document(doc.clone(), None); + let mode = doc.mode; + if mode != photocraft_color::ColorMode::Rgb { + tmp.execute("image.mode.rgb", json!({}))?; + } + if st.convert_to_srgb && doc.icc_profile.is_some() { + // Documents without a profile are treated as sRGB already. + tmp.execute("edit.convertToProfile", json!({"profile": "srgb", "intent": "perceptual"}))?; + } + let (w0, h0) = (f64::from(doc.size.width), f64::from(doc.size.height)); + let pct = p.get("percent").and_then(Value::as_f64).filter(|v| *v > 0.0); + let w = p.get("width").and_then(Value::as_f64).filter(|v| *v > 0.0); + let h = p.get("height").and_then(Value::as_f64).filter(|v| *v > 0.0); + let (nw, nh) = match (pct, w, h) { + (Some(pc), _, _) => (w0 * pc / 100.0, h0 * pc / 100.0), + (_, Some(w), Some(h)) => (w, h), + (_, Some(w), None) => (w, h0 * w / w0), + (_, None, Some(h)) => (w0 * h / h0, h), + _ => (w0, h0), + }; + let (nw, nh) = (nw.round().max(1.0), nh.round().max(1.0)); + if (nw - w0).abs() >= 1.0 || (nh - h0).abs() >= 1.0 { + let resample = p.get("resample").and_then(Value::as_str).unwrap_or("bicubic"); + tmp.execute("image.imageSize", json!({"width": nw, "height": nh, "resample": resample}))?; + } + let out = (*tmp.active().ok_or(EngineError::NoDocument)?.doc).clone(); + Ok((out, nw / w0, nh / h0)) +} + +/// An optimised image. +#[derive(Clone, Debug)] +pub struct Optimized { + pub bytes: Vec, + pub ext: &'static str, + pub width: u32, + pub height: u32, + /// Colours in the palette (indexed formats). + pub colors: Option, + /// Opaque source palette before replacements (empty for non-indexed formats). + pub color_table: Vec<[u8; 3]>, + pub transparent_index: Option, + /// Indexed pixels for previews; empty for non-indexed formats or when preview is disabled. + pub indices: Vec, + /// What the optimised file looks like, straight RGBA8 (for the dialog's previews). + pub preview: Vec, +} + +pub(super) fn to8(v: f32) -> u8 { + (v.clamp(0.0, 1.0) * 255.0).round() as u8 +} + +/// XMP to embed for the metadata choice. +pub fn web_xmp(doc: &Document, m: WebMetadata) -> Option { + let xmp = doc.metadata.xmp.as_deref()?; + match m { + WebMetadata::None => None, + WebMetadata::All | WebMetadata::AllExceptCameraInfo => Some(xmp.to_string()), + WebMetadata::Copyright | WebMetadata::CopyrightAndContact => { + let info = crate::file_cmds::read_file_info(Some(xmp)); + let mut keep = serde_json::Map::new(); + let mut keys = vec!["copyright", "copyrightStatus", "copyrightUrl"]; + if m == WebMetadata::CopyrightAndContact { + keys.extend(["author", "authorTitle"]); + } + for k in keys { + if let Some(v) = info.get(k).filter(|v| v.as_str().is_some_and(|s| !s.is_empty()) || v.is_array()) { + keep.insert(k.into(), v.clone()); + } + } + (!keep.is_empty()).then(|| crate::file_cmds::write_file_info(None, &Value::Object(keep))) + } + } +} + +/// The photo's EXIF to embed for the metadata choice: only "All" carries it (#7436). +pub fn web_exif(doc: &Document, m: WebMetadata) -> Option<&[u8]> { + doc.metadata.exif.as_deref().map(Vec::as_slice).filter(|_| m == WebMetadata::All) +} + +/// The response's warnings: EXIF that a JPEG couldn't hold (one segment, about 64 KB). +pub(super) fn web_warnings(st: &WebSettings, exif: Option<&[u8]>, dpi: f32) -> Vec { + exif.filter(|x| st.format == WebFormat::Jpeg && !photocraft_codecs::web::jpeg_exif_fits(x, Some(dpi))) + .map(|x| photocraft_codecs::FidelityWarning::MetadataTooLarge { what: "EXIF", bytes: x.len() }.to_string()) + .into_iter() + .collect() +} + +/// Optimises `rect` of `px` (straight RGBA, `bw` wide) with `st`. `preview` also returns what +/// the file looks like (the dialog's panes); exports skip it. +#[allow(clippy::too_many_arguments)] +pub fn optimize( + px: &[[f32; 4]], + bw: usize, + rect: Rect, + st: &WebSettings, + icc: Option<&[u8]>, + exif: Option<&[u8]>, + xmp: Option<&str>, + dpi: f32, + preview: bool, +) -> Result { + if bw == 0 || rect.x0 < 0 || rect.y0 < 0 || rect.is_empty() || rect.x1 as usize > bw || (rect.y1 as usize).checked_mul(bw).is_none_or(|end| end > px.len()) + { + return Err(other("slice is outside the pixel buffer")); + } + let (w, h) = (rect.width() as usize, rect.height() as usize); + let row = |y: i32| { + let o = y as usize * bw; + px.get(o + rect.x0 as usize..o + rect.x1 as usize).unwrap_or(&[]) + }; + let region = || (rect.y0..rect.y1).flat_map(row); + let matte = st.matte.unwrap_or([1.0, 1.0, 1.0]); + let over = |p: &[f32; 4]| -> [f32; 4] { + [p[0] * p[3] + matte[0] * (1.0 - p[3]), p[1] * p[3] + matte[1] * (1.0 - p[3]), p[2] * p[3] + matte[2] * (1.0 - p[3]), 1.0] + }; + let (ww, hh) = (w as u32, h as u32); + let e = |e: photocraft_codecs::CodecError| other(e); + let mut look: Vec = Vec::new(); + let mut color_table = Vec::new(); + let mut transparent_index = None; + let mut indices = Vec::new(); + let (bytes, colors) = match st.format { + WebFormat::Png24 => { + let alpha = st.transparency && region().any(|p| p[3] < 1.0); + let k = if alpha { 4 } else { 3 }; + let mut data = Vec::with_capacity(w * h * k); + for p in region() { + let q = if alpha { *p } else { over(p) }; + data.extend_from_slice(&[to8(q[0]), to8(q[1]), to8(q[2]), to8(q[3])][..k]); + } + if preview { + look = if alpha { data.clone() } else { data.as_chunks::<3>().0.iter().flat_map(|c| [c[0], c[1], c[2], 255]).collect() }; + } + let layout = if alpha { photocraft_codecs::ChannelLayout::Rgba } else { photocraft_codecs::ChannelLayout::Rgb }; + let meta = photocraft_codecs::Metadata { dpi: Some((dpi, dpi)), xmp: xmp.map(str::to_string), ..Default::default() }; + let img = photocraft_codecs::Image::from_u8(ww, hh, layout, data).map_err(e)?.with_icc(icc.map(<[u8]>::to_vec)).with_meta(meta); + let opts = photocraft_codecs::EncodeOptions { + png_interlaced: st.interlaced, + embed_icc: icc.is_some(), + embed_metadata: xmp.is_some(), + ..Default::default() + }; + (photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &opts).map_err(e)?, None) + } + WebFormat::Jpeg => { + let mut rgb = Vec::with_capacity(w * h * 3); + for p in region() { + let q = over(p); + rgb.extend_from_slice(&[to8(q[0]), to8(q[1]), to8(q[2])]); + } + // Save for Web's 0–100 quality → encoder 1–100. + let q = st.quality.max(1); + let bytes = + photocraft_codecs::web::encode_jpeg_rgb8(ww, hh, &rgb, q, st.progressive, st.optimized, icc.filter(|_| st.embed_icc), Some(dpi), exif, xmp) + .map_err(e)?; + if preview { + // The preview shows the compression artefacts. + look = match photocraft_codecs::decode(&bytes) { + Ok(img) => img.convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8).data().to_vec(), + Err(_) => rgb.as_chunks::<3>().0.iter().flat_map(|c| [c[0], c[1], c[2], 255]).collect(), + }; + } + (bytes, None) + } + WebFormat::Wbmp => { + let mut gray: Vec = region() + .map(|p| { + let q = over(p); + 0.299 * q[0] + 0.587 * q[1] + 0.114 * q[2] + }) + .collect(); + let method = match st.dither { + Dither::None => quantize::BitmapMethod::Threshold, + Dither::Pattern => quantize::BitmapMethod::Pattern, + _ => quantize::BitmapMethod::Diffusion, + }; + quantize::to_bitmap(&mut gray, w, method); + let white: Vec = gray.iter().map(|v| *v > 0.5).collect(); + if preview { + look = white.iter().flat_map(|b| if *b { [255, 255, 255, 255] } else { [0, 0, 0, 255] }).collect(); + } + (photocraft_codecs::web::encode_wbmp(ww, hh, &white).map_err(e)?, Some(2)) + } + WebFormat::Gif | WebFormat::Png8 => { + let transparent = st.transparency && region().any(|p| p[3] < 0.5); + // Partially transparent edges blend with the matte; with transparency off everything does. + let mut work: Vec<[f32; 4]> = region() + .map(|p| { + if st.transparency && p[3] < 0.5 { + [0.0, 0.0, 0.0, 0.0] + } else if st.transparency && st.matte.is_none() { + [p[0], p[1], p[2], 1.0] + } else { + over(p) + } + }) + .collect(); + let room = if transparent { st.colors.saturating_sub(1).max(2) } else { st.colors }; + let mut pal = if let Some(table) = &st.color_table { + if table.is_empty() || table.len() > if transparent { 255 } else { 256 } { + return Err(other("colorTable has too many entries for this image's transparency")); + } + table.clone() + } else { + // Large images: build adaptive palettes from an even ~1 MP sample (Exact needs all). + let n_opaque = work.iter().filter(|p| p[3] >= 0.5).count(); + let step = if n_opaque > 1 << 20 && st.palette != PaletteKind::Exact { n_opaque / (1 << 20) + 1 } else { 1 }; + let mut src: Vec<[f32; 4]> = work.iter().filter(|p| p[3] >= 0.5).step_by(step).copied().collect(); + if src.is_empty() { + src = work.clone(); + } + quantize::build_palette(&src, st.palette, room, Forced::None).map_err(other)? + }; + if st.web_snap > 0.0 && st.color_table.is_none() { + let tol = (st.web_snap * 255.0) as u8; + for c in &mut pal { + let snap = c.map(|x| ((f32::from(x) / 51.0).round() * 51.0) as u8); + if c.iter().zip(snap).all(|(a, b)| a.abs_diff(b) <= tol) { + *c = snap; + } + } + } + if transparent { + pal.truncate(255); + } + let first = pal.first().copied().ok_or_else(|| other("empty colour table"))?; + color_table = pal.clone(); + let t = transparent.then(|| { + pal.push(first); + pal.len() - 1 + }); + transparent_index = t; + let idx = quantize_rows(&mut work, w, &pal, st.dither, st.dither_amount, t); + for (index, color) in &st.color_table_edits { + let slot = pal.get_mut(*index).filter(|_| Some(*index) != t).ok_or_else(|| other("colour edit is outside the opaque palette"))?; + *slot = *color; + } + if preview { + look = idx + .iter() + .flat_map(|k| { + let c = pal.get(*k as usize).copied().unwrap_or(first); + [c[0], c[1], c[2], if Some(*k as usize) == t { 0 } else { 255 }] + }) + .collect(); + } + let tt = t.map(|v| v as u8); + let bytes = if st.format == WebFormat::Gif { + photocraft_codecs::web::encode_gif_indexed(ww, hh, &idx, &pal, tt, st.interlaced).map_err(e)? + } else { + photocraft_codecs::encode_png_indexed(ww, hh, &idx, &pal, tt, None, None).map_err(e)? + }; + if preview { + indices = idx; + } + (bytes, Some(pal.len())) + } + }; + Ok(Optimized { bytes, ext: st.format.ext(), width: ww, height: hh, colors, color_table, transparent_index, indices, preview: look }) +} + +/// Nearest palette entry through a lazily filled 6-bit-per-channel inverse colour map: each +/// 4×4×4 cell is resolved once (by its centre), so large images cost a table lookup per pixel +/// instead of a palette scan. `t` (the transparent index) is never returned. +struct InverseMap<'a> { + pal: &'a [[u8; 3]], + t: Option, + lut: Vec, +} + +impl<'a> InverseMap<'a> { + fn new(pal: &'a [[u8; 3]], t: Option) -> Self { + InverseMap { pal, t, lut: vec![u16::MAX; 1 << 18] } + } + #[inline] + fn get(&mut self, c: [f32; 3]) -> usize { + let q = c.map(|v| ((v.clamp(0.0, 1.0) * 255.0).round() as usize) >> 2); + let key = q[0] << 12 | q[1] << 6 | q[2]; + let v = self.lut[key]; + if v != u16::MAX { + return usize::from(v); + } + let center = q.map(|v| (v * 4 + 2) as f32); + let mut best = (f32::MAX, 0usize); + for (i, e) in self.pal.iter().enumerate() { + if Some(i) == self.t { + continue; + } + let d: f32 = (0..3).map(|k| (center[k] - f32::from(e[k])).powi(2)).sum(); + if d < best.0 { + best = (d, i); + } + } + self.lut[key] = best.1 as u16; + best.1 + } +} + +fn hash01(x: usize, y: usize) -> f32 { + let mut h = (x as u32).wrapping_mul(0x8da6_b343) ^ (y as u32).wrapping_mul(0xd816_3841) ^ 0x2545_f491; + h ^= h >> 13; + h = h.wrapping_mul(0x5bd1_e995); + h ^= h >> 15; + (h & 0xffff) as f32 / 65535.0 +} + +/// Palette mapping with dithering (Floyd–Steinberg diffusion, 8×8 Bayer pattern, noise), like +/// `algo::quantize::quantize` but through [`InverseMap`]. `y0` keeps patterns continuous across +/// bands. Pixels with alpha < ½ take index `t`. +fn quantize_band(px: &mut [[f32; 4]], w: usize, y0: usize, pal: &[[u8; 3]], dither: Dither, amount: f32, t: Option) -> Vec { + let h = px.len() / w.max(1); + let mut map = InverseMap::new(pal, t); + let mut idx = vec![0u8; px.len()]; + let opaque_n = pal.len() - usize::from(t.is_some()); + let spread = (1.0 / (opaque_n as f32).cbrt().max(1.0)).min(0.5) * amount.clamp(0.0, 1.0); + let a = amount.clamp(0.0, 1.0); + let mut cur = vec![[0.0f32; 3]; if dither == Dither::Diffusion { w + 2 } else { 0 }]; + let mut next = cur.clone(); + for y in 0..h { + if dither == Dither::Diffusion { + std::mem::swap(&mut cur, &mut next); + next.iter_mut().for_each(|e| *e = [0.0; 3]); + } + for x in 0..w { + let i = y * w + x; + let p = px[i]; + if p[3] < 0.5 + && let Some(t) = t + { + idx[i] = t as u8; + continue; + } + let mut c = [p[0], p[1], p[2]]; + match dither { + Dither::None => {} + Dither::Diffusion => (0..3).for_each(|k| c[k] += cur[x + 1][k]), + Dither::Pattern => { + let d = quantize::bayer8(x, y0 + y) * spread; + c = c.map(|v| v + d); + } + Dither::Noise => { + let d = (hash01(x, y0 + y) - 0.5) * spread; + c = c.map(|v| v + d); + } + } + let c = c.map(|v| v.clamp(0.0, 1.0)); + let k = map.get(c); + idx[i] = k as u8; + if dither == Dither::Diffusion { + let e = pal[k].map(|v| f32::from(v) / 255.0); + let d: [f32; 3] = std::array::from_fn(|q| (c[q] - e[q]) * a); + for q in 0..3 { + cur[x + 2][q] += d[q] * 7.0 / 16.0; + next[x][q] += d[q] * 3.0 / 16.0; + next[x + 1][q] += d[q] * 5.0 / 16.0; + next[x + 2][q] += d[q] / 16.0; + } + } + } + } + idx +} + +/// [`quantize_band`] over the whole image, in parallel bands of 64 rows when the dither is +/// position-independent. Error diffusion carries error down the image, so it stays sequential. +fn quantize_rows(px: &mut [[f32; 4]], w: usize, pal: &[[u8; 3]], dither: Dither, amount: f32, t: Option) -> Vec { + let h = px.len() / w.max(1); + if dither == Dither::Diffusion || h < 128 || cfg!(target_arch = "wasm32") { + return quantize_band(px, w, 0, pal, dither, amount, t); + } + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + let band = w * 64; + let mut idx = vec![0u8; px.len()]; + px.par_chunks_mut(band) + .zip(idx.par_chunks_mut(band)) + .enumerate() + .for_each(|(i, (p, out))| out.copy_from_slice(&quantize_band(p, w, i * 64, pal, dither, amount, t))); + idx + } + // Single-threaded on wasm (the early return above always takes this path there). + #[cfg(target_arch = "wasm32")] + quantize_band(px, w, 0, pal, dither, amount, t) +} diff --git a/crates/engine/src/web_cmds/quick.rs b/crates/engine/src/web_cmds/quick.rs new file mode 100644 index 0000000000..c017eb3d2f --- /dev/null +++ b/crates/engine/src/web_cmds/quick.rs @@ -0,0 +1,147 @@ +use super::optimizer::{optimize, web_document, web_exif, web_warnings, web_xmp}; +use super::settings::WebSettings; +use super::*; + +// ---------- Export Preferences / Quick Export ---------- + +/// File › Export › Export Preferences…: sets the given `export.*` preferences through `prefs.set` +/// (validated like any other preference) and returns the whole section. +pub(super) fn export_preferences(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export.exportPreferences"; + let mut values = serde_json::Map::new(); + for (k, key) in [ + ("quickExportFormat", "export.quickExportFormat"), + ("quickExportLocation", "export.quickExportLocation"), + ("jpegQuality", "export.jpegQuality"), + ("webpLossless", "export.webpLossless"), + ("webpQuality", "export.webpQuality"), + ("metadata", "export.metadata"), + ("convertToSrgb", "export.convertToSrgb"), + ] { + if let Some(v) = p.get(k) { + values.insert(key.into(), v.clone()); + } + } + if !values.is_empty() { + s.execute("prefs.set", json!({"values": values})).map_err(|e| bad(cmd, e.to_string()))?; + } + Ok(json!({"section": "export", "values": s.prefs().get("export").unwrap_or(Value::Null)})) +} + +/// The Quick Export format's extension (Export Preferences › Format). +fn quick_export_ext(s: &Session) -> String { + serde_json::to_value(s.prefs().export.quick_export_format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "png".into()) +} + +/// Where Quick Export writes the active document with no `path` given: `.` beside +/// its file, when Export Preferences › Location is Same Folder and the document has a file. +pub fn quick_export_target(s: &Session) -> Option { + let same = s.prefs().export.quick_export_location == crate::prefs::ExportLocation::SameFolder; + let dp = s.active()?.path.as_deref().filter(|_| same)?; + let dir = std::path::Path::new(dp).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(); + Some(join(&dir, &format!("{}.{}", stem(dp), quick_export_ext(s)))) +} + +/// Whether [`quick_export_target`] is the active document's own file (a document opened from +/// `photo.png` and exported as PNG), which Quick Export must not replace without asking (#6599). +pub fn quick_export_target_is_own_file(s: &Session) -> bool { + let own = s.active().and_then(|d| d.path.as_deref()); + quick_export_target(s).zip(own).is_some_and(|(target, own)| crate::file_cmds::same_file(&target, own)) +} + +/// File › Export › Quick Export as : the format, quality, metadata, colour space and +/// location from Export Preferences. `path` overrides the location ("ask" needs one). +pub(super) fn quick_export(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export.quickExport"; + let prefs = s.prefs().export.clone(); + let fmt = quick_export_ext(s); + let path = match p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()) { + Some(v) => v.to_string(), + None => { + let Some(target) = quick_export_target(s) else { + return Err(bad(cmd, "missing `path` (Export Preferences › Location is \"ask\", or the document was never saved)")); + }; + // The document's own file is never replaced by an export the user didn't name (#6599). + if quick_export_target_is_own_file(s) { + return Err(bad(cmd, format!("the export would replace the document's own file {target}; give a `path`"))); + } + target + } + }; + // The name typed in the save dialog wins over Export Preferences' format: Quick Export as PNG + // renamed to `photo.jpeg` must write a JPEG, not PNG bytes upload checks refuse (#8519). + let fmt = match crate::file_cmds::extension(&path).as_deref() { + None => fmt, + Some("jpg" | "jpeg") => "jpg".into(), + Some(e @ ("png" | "gif" | "webp" | "exr")) => e.into(), + Some(e) => return Err(bad(cmd, format!("Quick Export writes PNG, JPEG, GIF, WebP or EXR, not .{e}; use Export As"))), + }; + let d = s.active().ok_or(EngineError::NoDocument)?; + let doc = d.doc.clone(); + if fmt == "exr" { + // EXR keeps floating-point scene values. The ordinary exporter converts to linear + // light; the web/sRGB pipeline would instead clamp HDR and negative values. + let opts = photocraft_io::ExportOptions { xmp: photocraft_io::XmpEmbed::None, ..Default::default() }; + let out = photocraft_io::export(&doc, "exr", &opts).map_err(other)?; + write_file(&path, &out.bytes)?; + crate::automate_cmds::fire_event(s, "export"); + return Ok(json!({"path": path, "format": fmt, "bytes": out.bytes.len(), "warnings": out.warnings})); + } + let metadata = serde_json::to_value(prefs.metadata).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); + let mut o = serde_json::Map::new(); + o.insert( + "metadata".into(), + json!(if metadata == "all" { + "all" + } else if metadata == "none" { + "none" + } else { + "copyright" + }), + ); + o.insert("convertToSrgb".into(), json!(prefs.convert_to_srgb)); + o.insert("transparency".into(), json!(true)); + o.insert("matte".into(), json!("#ffffff")); + match fmt.as_str() { + "jpg" => { + o.insert("format".into(), json!("jpeg")); + o.insert("quality".into(), json!(prefs.jpeg_quality.min(100))); + } + "gif" => { + o.insert("format".into(), json!("gif")); + } + "webp" => { + // WebP uses the regular exporter. Its optional quality is in the Photoshop-style + // 0–12 save scale: invert that mapping so the codec receives the chosen 1–100. + // Keeping quality absent preserves the historical lossless Quick Export behavior. + let (wdoc, _, _) = web_document(&doc, &json!({}), &WebSettings { convert_to_srgb: prefs.convert_to_srgb, ..Default::default() })?; + let quality = if prefs.webp_lossless { None } else { Some((f64::from(prefs.webp_quality.clamp(1, 100)) - 1.0) * 12.0 / 99.0) }; + let warnings = crate::file_cmds::save_doc(&wdoc, &path, quality)?; + crate::automate_cmds::fire_event(s, "export"); + return Ok(json!({"path": path, "format": fmt, "warnings": warnings})); + } + _ => { + o.insert("format".into(), json!("png24")); + } + } + let q = Value::Object(o); + let st = WebSettings::from_params(&q, cmd)?; + let (wdoc, _, _) = web_document(&doc, &json!({}), &st)?; + let buf = photocraft_compose::flatten(&wdoc); + let xmp = web_xmp(&doc, st.metadata); + let exif = web_exif(&doc, st.metadata); + let opt = optimize( + &buf.px, + wdoc.size.width as usize, + wdoc.bounds(), + &st, + wdoc.icc_profile.as_deref().map(|v| v.as_slice()), + exif, + xmp.as_deref(), + wdoc.resolution_dpi, + false, + )?; + write_file(&path, &opt.bytes)?; + crate::automate_cmds::fire_event(s, "export"); + Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len(), "warnings": web_warnings(&st, exif, wdoc.resolution_dpi)})) +} diff --git a/crates/engine/src/web_cmds/save_web.rs b/crates/engine/src/web_cmds/save_web.rs new file mode 100644 index 0000000000..eeca746754 --- /dev/null +++ b/crates/engine/src/web_cmds/save_web.rs @@ -0,0 +1,304 @@ +use super::assets::{asset_output_path, asset_path_components}; +use super::optimizer::{optimize, web_document, web_exif, web_warnings, web_xmp}; +use super::settings::{WebSettings, rgb_hex}; +use super::*; + +/// A file-name-safe slice name. +fn slice_file(name: &str) -> String { + let s: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_') { c } else { '_' }).collect(); + let s = if s.is_empty() { "slice".into() } else { s }; + portable_generated_stem(s) +} + +/// Generated filenames should remain usable on Windows even when a document or slice is named +/// after a reserved device. Caller-supplied path components are still rejected below. +fn portable_generated_stem(stem: String) -> String { + portable_device_name(stem) +} + +fn html_escape(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +/// Imported slice URLs are document data. Only ordinary web/contact links and relative links +/// become anchors; an unsupported scheme leaves the image unlinked. +fn safe_slice_url(url: &str) -> bool { + if url.is_empty() || url.trim() != url || url.chars().any(|c| c.is_control() || c == '\\') { + return false; + } + let delimiter = url.find(['/', '?', '#']).unwrap_or(url.len()); + let Some(colon) = url.find(':').filter(|pos| *pos < delimiter) else { + return true; + }; + let scheme = url.get(..colon).unwrap_or_default().to_ascii_lowercase(); + let rest = url.get(colon + 1..).unwrap_or_default(); + match scheme.as_str() { + "http" | "https" | "ftp" | "ftps" => rest.strip_prefix("//").is_some_and(|host| !host.is_empty() && !host.starts_with('/')), + "mailto" | "tel" => !rest.is_empty(), + _ => false, + } +} + +/// Keep the image folder relative to the selected export directory on every platform. +fn web_images_folder(images: &str, cmd: &str) -> Result { + if images.is_empty() { + return Ok(String::new()); + } + let trimmed = images.trim_end_matches(['/', '\\']); + if trimmed.is_empty() { + return Err(bad(cmd, "imagesFolder must be a relative folder name")); + } + let parts = asset_path_components(trimmed).map_err(|e| bad(cmd, format!("imagesFolder: {e}")))?; + Ok(parts.join("/")) +} + +fn web_output_path(dir: &str, relative: &str) -> Result { + let root = if dir.is_empty() { "." } else { dir }; + asset_output_path(root, relative).map(|(actual, _)| actual) +} + +fn web_derived_path(dir: &str, relative: &str, native_paths: bool) -> Result { + if native_paths { + web_output_path(dir, relative) + } else { + // Browser downloads use logical names, without a host filesystem to inspect. + asset_path_components(relative)?; + Ok(join(dir, relative)) + } +} + +fn scale_rect(r: Rect, sx: f64, sy: f64) -> Rect { + Rect::new( + (f64::from(r.x0) * sx).round() as i32, + (f64::from(r.y0) * sy).round() as i32, + (f64::from(r.x1) * sx).round() as i32, + (f64::from(r.y1) * sy).round() as i32, + ) +} + +/// The HTML table for `cells` (rect, td body) over a `w`×`h` image: one column per distinct x +/// edge, one row per y edge, colspan/rowspan per slice, and a spacer row fixing column widths. +fn html_table(title: &str, w: u32, h: u32, cells: &[(Rect, String, String)], spacer: Option<&str>) -> String { + let mut xs: Vec = cells.iter().flat_map(|(r, _, _)| [r.x0, r.x1]).collect(); + let mut ys: Vec = cells.iter().flat_map(|(r, _, _)| [r.y0, r.y1]).collect(); + xs.sort_unstable(); + xs.dedup(); + ys.sort_unstable(); + ys.dedup(); + let col = |x: i32| xs.iter().position(|v| *v == x).unwrap_or(0); + let row = |y: i32| ys.iter().position(|v| *v == y).unwrap_or(0); + let (nc, nr) = (xs.len().saturating_sub(1), ys.len().saturating_sub(1)); + let mut taken = vec![false; nc * nr]; + let mut by_row: Vec> = vec![Vec::new(); nr]; + for (r, attrs, body) in cells { + let (c0, c1, r0, r1) = (col(r.x0), col(r.x1), row(r.y0), row(r.y1)); + if (r0..r1).any(|j| (c0..c1).any(|i| taken[j * nc + i])) { + continue; // overlapped (the caller cuts slices into visible pieces, so this can't happen) + } + for j in r0..r1 { + for i in c0..c1 { + taken[j * nc + i] = true; + } + } + let mut td = String::from("\t\t 1 { + td.push_str(&format!(" colspan=\"{}\"", c1 - c0)); + } + if r1 - r0 > 1 { + td.push_str(&format!(" rowspan=\"{}\"", r1 - r0)); + } + td.push_str(attrs); + td.push('>'); + td.push_str(body); + td.push_str("\n"); + by_row[r0].push((c0, td)); + } + let mut s = format!( + "\n\n{t}\n\n\n\n\n\n", + t = html_escape(title) + ); + for (j, mut tds) in by_row.into_iter().enumerate() { + tds.sort_by_key(|(c, _)| *c); + s.push_str("\t\n"); + for (_, td) in tds { + s.push_str(&td); + } + if let Some(sp) = spacer { + s.push_str(&format!("\t\t\n", html_escape(sp), ys[j + 1] - ys[j])); + } + s.push_str("\t\n"); + } + if let Some(sp) = spacer { + s.push_str("\t\n"); + for i in 0..nc { + s.push_str(&format!("\t\t\n", html_escape(sp), xs[i + 1] - xs[i])); + } + s.push_str("\t\t\n\t\n"); + } + s.push_str("
\n\t\t\t\"\"
\n\t\t\t\"\"
\n\n\n\n"); + s +} + +/// File › Export › Save for Web (Legacy). +pub(super) fn save_for_web(s: &mut Session, p: &Value) -> Result { + save_for_web_impl(s, p, &mut write_file, true) +} + +/// Save for Web through a platform writer (native files or browser downloads). +/// The writer receives every image, spacer and HTML file. A write error stops the export; +/// only a complete export remembers its settings and fires the export event. A custom writer +/// that targets the local filesystem must enforce its own path confinement. +pub fn save_for_web_with_writer(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { + save_for_web_impl(s, p, write, false) +} + +/// Settings to seed the Save for Web dialog from on the next launch: `file_menu` is session +/// state, so a complete export also writes the preferences' remembered dialog settings (like +/// Fill, Liquify and the filter dialogs). The destination is per export, never remembered. +fn remember_web_settings(s: &mut Session, cmd: &str, settings: &Value) { + let mut m = settings.clone(); + if let Some(o) = m.as_object_mut() { + for k in ["path", "dir", "trustedSliceHtml"] { + o.remove(k); + } + } + s.prefs.edit(|p| { + p.dialogs.insert(cmd.to_string(), m); + }); +} + +fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>, native_paths: bool) -> Result { + let cmd = "file.export.saveForWebLegacy"; + if let Some(authorize) = s.authorize { + authorize(cmd, p)?; + } + // Direct platform calls must export the moved selection as it appears on the canvas, + // just as Session::execute does before dispatching the native command. + crate::float_cmds::before_command(s, cmd)?; + let st = WebSettings::from_params(p, cmd)?; + let d = s.active().ok_or(EngineError::NoDocument)?; + let doc = d.doc.clone(); + let (wdoc, sx, sy) = web_document(&doc, p, &st)?; + let buf = photocraft_compose::flatten(&wdoc); + let bw = wdoc.size.width as usize; + let icc = wdoc.icc_profile.as_deref().map(|v| v.as_slice()); + let xmp = web_xmp(&doc, st.metadata); + let exif = web_exif(&doc, st.metadata); + let dpi = wdoc.resolution_dpi; + let warnings = web_warnings(&st, exif, dpi); + let all = slices::resolve(&doc); + let pick = p.get("slices").and_then(Value::as_str).unwrap_or("all"); + let numbers: Option> = p.get("numbers").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).collect()); + let chosen: Vec<&ResolvedSlice> = all + .iter() + .filter(|r| match (&numbers, pick) { + (Some(n), _) => n.contains(&(r.number as u64)), + (None, "user") => r.origin != photocraft_doc::SliceOrigin::Auto, + _ => true, + }) + .collect(); + let single = p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty()); + let dir = p.get("dir").and_then(Value::as_str).filter(|v| !v.is_empty()); + let mut last_web = p.clone(); + // A trusted-markup decision applies to this export only, never to another document opened + // with the dialog's remembered settings. + if let Some(last) = last_web.as_object_mut() { + last.remove("trustedSliceHtml"); + } + // Estimate only (the dialog's annotations): the whole image, or each chosen slice. + if single.is_none() && dir.is_none() { + let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?; + return Ok( + json!({"format": o.ext, "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "colorTable": o.color_table.iter().map(|c| rgb_hex(*c)).collect::>(), "transparentIndex": o.transparent_index}), + ); + } + if let Some(path) = single.filter(|_| dir.is_none() && (all.len() == 1 || p.get("slices").is_none())) { + let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, exif, xmp.as_deref(), dpi, false)?; + write(path, &o.bytes)?; + remember_web_settings(s, cmd, &last_web); + s.file_menu.last_web = Some(last_web); + crate::automate_cmds::fire_event(s, "export"); + return Ok(json!({"files": [path], "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors, "warnings": warnings})); + } + let dir = + dir.map(str::to_string).or_else(|| single.and_then(|f| std::path::Path::new(f).parent().map(|d| d.to_string_lossy().into_owned()))).unwrap_or_default(); + let html = p.get("html").and_then(Value::as_bool).unwrap_or(false); + let images = web_images_folder(p.get("imagesFolder").and_then(Value::as_str).unwrap_or("images"), cmd)?; + let trusted_slice_html = p.get("trustedSliceHtml").and_then(Value::as_bool).unwrap_or(false); + let base = portable_generated_stem(single.map(stem).unwrap_or_else(|| slices::base_name(&doc))); + let mut files = Vec::new(); + let mut cells: Vec<(Rect, String, String)> = Vec::new(); + let mut total = 0usize; + // Output names are unique (case-insensitively, for macOS and Windows file systems): two + // slices named alike, or names that sanitize alike, must not overwrite each other. The HTML + // page's spacer image is reserved. + let mut used: std::collections::HashSet = std::collections::HashSet::new(); + if html { + used.insert("spacer.gif".into()); + } + let mut unique = |stem: &str, ext: &str| { + let mut name = format!("{stem}.{ext}"); + let mut k = 2u32; + while !used.insert(name.to_lowercase()) { + name = format!("{stem}_{k}.{ext}"); + k = k.saturating_add(1); + } + name + }; + // Slices never overlap here: one covered by later slices comes as its visible pieces (see + // `slices::resolve`), each its own image and cell, as Photoshop's subslices. A no-image cell's + // text goes into its first piece only. + let mut texted = std::collections::HashSet::new(); + for r in &chosen { + let piece = scale_rect(r.rect, sx, sy).intersect(&wdoc.bounds()); + if piece.is_empty() { + continue; + } + let stored = r.id.and_then(|id| doc.slices.get(id)); + if r.kind == SliceKind::NoImage { + let text = stored + .filter(|s| texted.insert(s.id)) + .map(|s| if trusted_slice_html && s.cell_text_is_html { s.cell_text.clone() } else { html_escape(&s.cell_text) }) + .unwrap_or_default(); + let bg = stored.and_then(|s| s.background).map(|c| format!(" bgcolor=\"#{:02X}{:02X}{:02X}\"", c[1], c[2], c[3])).unwrap_or_default(); + cells.push((piece, bg, text)); + continue; + } + let o = optimize(&buf.px, bw, piece, &st, icc, exif, xmp.as_deref(), dpi, false)?; + let name = unique(&slice_file(&r.name), o.ext); + let rel = if images.is_empty() { name.clone() } else { format!("{images}/{name}") }; + let out = join(&dir, &rel); + write(&web_derived_path(&dir, &rel, native_paths)?, &o.bytes)?; + total += o.bytes.len(); + files.push(out); + let alt = stored.map_or(String::new(), |s| html_escape(&s.alt)); + let img = format!("\n\t\t\t\"{alt}\"", html_escape(&rel), piece.width(), piece.height()); + let body = match stored.filter(|s| safe_slice_url(&s.url)) { + Some(s) => { + let target = if s.target.is_empty() { String::new() } else { format!(" target=\"{}\"", html_escape(&s.target)) }; + format!("\n\t\t\t{img}", html_escape(&s.url)) + } + None => img, + }; + cells.push((piece, String::new(), body)); + } + let mut html_path = None; + if html { + let grid = cells.len() > 1; + let spacer = grid.then(|| if images.is_empty() { "spacer.gif".to_string() } else { format!("{images}/spacer.gif") }); + if let Some(sp) = &spacer { + let gif = photocraft_codecs::web::encode_gif_indexed(1, 1, &[0], &[[0, 0, 0]], Some(0), false).map_err(other)?; + write(&web_derived_path(&dir, sp, native_paths)?, &gif)?; + } + let page = html_table(&base, wdoc.size.width, wdoc.size.height, &cells, spacer.as_deref()); + let hp = join(&dir, &format!("{base}.html")); + write(&web_derived_path(&dir, &format!("{base}.html"), native_paths)?, page.as_bytes())?; + html_path = Some(hp); + } + remember_web_settings(s, cmd, &last_web); + s.file_menu.last_web = Some(last_web); + crate::automate_cmds::fire_event(s, "export"); + Ok( + json!({"files": files, "html": html_path, "bytes": total, "slices": chosen.len(), "width": wdoc.size.width, "height": wdoc.size.height, "warnings": warnings}), + ) +} diff --git a/crates/engine/src/web_cmds/settings.rs b/crates/engine/src/web_cmds/settings.rs new file mode 100644 index 0000000000..19314673c0 --- /dev/null +++ b/crates/engine/src/web_cmds/settings.rs @@ -0,0 +1,303 @@ +use super::optimizer::to8; +use super::*; + +// ---------- settings ---------- + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WebFormat { + Gif, + Png8, + Png24, + Jpeg, + Wbmp, +} + +impl WebFormat { + pub fn from_id(s: &str) -> Option { + Some(match s.to_ascii_lowercase().as_str() { + "gif" => WebFormat::Gif, + "png8" | "png-8" => WebFormat::Png8, + "png24" | "png-24" | "png" | "png32" => WebFormat::Png24, + "jpeg" | "jpg" => WebFormat::Jpeg, + "wbmp" => WebFormat::Wbmp, + _ => return None, + }) + } + pub fn ext(self) -> &'static str { + match self { + WebFormat::Gif => "gif", + WebFormat::Png8 | WebFormat::Png24 => "png", + WebFormat::Jpeg => "jpg", + WebFormat::Wbmp => "wbmp", + } + } + pub fn indexed(self) -> bool { + matches!(self, WebFormat::Gif | WebFormat::Png8) + } +} + +/// Which metadata Save for Web embeds (JPEG only, like Photoshop's legacy exporter). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WebMetadata { + None, + Copyright, + CopyrightAndContact, + /// All the XMP, none of the photo's EXIF (camera, date taken, GPS). + AllExceptCameraInfo, + /// All the XMP and the photo's EXIF. + All, +} + +/// One optimisation preset (the right-hand side of the Save for Web dialog). +#[derive(Clone, Debug, PartialEq)] +pub struct WebSettings { + pub format: WebFormat, + pub palette: PaletteKind, + pub colors: usize, + /// Fixed opaque source palette in index order. + pub color_table: Option>, + /// Replacements applied after quantization, preserving pixel indices. + pub color_table_edits: std::collections::BTreeMap, + pub dither: Dither, + /// 0..=1. + pub dither_amount: f32, + pub transparency: bool, + /// Edge / background colour (0..=1 RGB); None = no matte (hard alpha threshold). + pub matte: Option<[f32; 3]>, + pub interlaced: bool, + /// Web Snap: palette entries within this distance (0..=1 of the channel range) snap to the + /// web-safe cube. + pub web_snap: f32, + /// JPEG quality 0..=100. + pub quality: u8, + pub progressive: bool, + pub optimized: bool, + pub embed_icc: bool, + pub metadata: WebMetadata, + pub convert_to_srgb: bool, +} + +impl Default for WebSettings { + fn default() -> Self { + WebSettings { + format: WebFormat::Png24, + palette: PaletteKind::Selective, + colors: 256, + color_table: None, + color_table_edits: Default::default(), + dither: Dither::Diffusion, + dither_amount: 0.88, + transparency: true, + matte: Some([1.0, 1.0, 1.0]), + interlaced: false, + web_snap: 0.0, + quality: 60, + progressive: false, + optimized: true, + embed_icc: false, + metadata: WebMetadata::Copyright, + convert_to_srgb: true, + } + } +} + +fn hex3(s: &str) -> Option<[f32; 3]> { + let s = s.trim_start_matches('#'); + let b = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| f32::from(v) / 255.0); + (s.len() == 6).then_some(())?; + Some([b(0)?, b(2)?, b(4)?]) +} + +impl WebSettings { + /// Settings from command parameters (missing keys keep the defaults; Photoshop's preset + /// names such as "GIF 128 Dithered" or "JPEG High" are accepted as `"preset"`). + /// + /// Without a preset there is no matte, as in Photoshop's scripted Save for Web + /// (`ExportOptionsSaveForWeb` left at its defaults): a GIF or PNG-8 keeps the colour of its + /// partly transparent pixels instead of lightening them towards white (#4115). Formats + /// without transparency still go over white. + pub fn from_params(p: &Value, cmd: &str) -> Result { + let mut st = WebSettings { matte: None, ..WebSettings::default() }; + if let Some(preset) = p.get("preset").and_then(Value::as_str) { + st = preset_settings(preset).ok_or_else(|| bad(cmd, format!("unknown preset `{preset}`")))?; + } + let s = |k: &str| p.get(k).and_then(Value::as_str); + if let Some(f) = s("format") { + st.format = WebFormat::from_id(f).ok_or_else(|| bad(cmd, format!("unknown format `{f}` (gif|png8|png24|jpeg|wbmp)")))?; + } + if let Some(k) = s("palette") { + st.palette = match k { + "restrictive" | "web" => PaletteKind::Web, + k => PaletteKind::from_id(k).ok_or_else(|| { + bad(cmd, format!("unknown palette `{k}` (perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform)")) + })?, + }; + } + if let Some(n) = crate::commands::int(p, "colors").filter(|v| *v > 0).map(|v| v as u64) { + st.colors = (n as usize).clamp(2, 256); + } + if let Some(d) = s("dither") { + st.dither = match d { + "none" | "noDither" => Dither::None, + "diffusion" => Dither::Diffusion, + "pattern" => Dither::Pattern, + "noise" => Dither::Noise, + d => return Err(bad(cmd, format!("unknown dither `{d}` (none|diffusion|pattern|noise)"))), + }; + } + if let Some(a) = p.get("ditherAmount").and_then(Value::as_f64) { + st.dither_amount = (a as f32 / 100.0).clamp(0.0, 1.0); + } + if let Some(b) = p.get("transparency").and_then(Value::as_bool) { + st.transparency = b; + } + match s("matte") { + Some("none") => st.matte = None, + Some(c) => st.matte = Some(hex3(c).ok_or_else(|| bad(cmd, "matte is \"none\" or \"#rrggbb\""))?), + None => {} + } + for (k, slot) in [ + ("interlaced", &mut st.interlaced), + ("progressive", &mut st.progressive), + ("optimized", &mut st.optimized), + ("embedIcc", &mut st.embed_icc), + ("convertToSrgb", &mut st.convert_to_srgb), + ] { + if let Some(b) = p.get(k).and_then(Value::as_bool) { + *slot = b; + } + } + if let Some(w) = p.get("webSnap").and_then(Value::as_f64) { + st.web_snap = (w as f32 / 100.0).clamp(0.0, 1.0); + } + if let Some(q) = p.get("quality").and_then(Value::as_f64) { + st.quality = q.clamp(0.0, 100.0).round() as u8; + } + if let Some(m) = s("metadata") { + st.metadata = match m { + "none" => WebMetadata::None, + "copyright" => WebMetadata::Copyright, + "copyrightAndContact" | "contact" => WebMetadata::CopyrightAndContact, + "allExceptCameraInfo" => WebMetadata::AllExceptCameraInfo, + "all" => WebMetadata::All, + m => return Err(bad(cmd, format!("unknown metadata `{m}` (none|copyright|copyrightAndContact|allExceptCameraInfo|all)"))), + }; + } + if let Some(table) = p.get("colorTable") { + let table = table.as_array().filter(|a| (1..=256).contains(&a.len())).ok_or_else(|| bad(cmd, "colorTable must contain 1–256 #rrggbb colours"))?; + st.color_table = Some( + table + .iter() + .map(|v| v.as_str().and_then(hex3).map(|c| c.map(to8)).ok_or_else(|| bad(cmd, "colorTable entries must be #rrggbb colours"))) + .collect::>>()?, + ); + } + if let Some(edits) = p.get("colorTableEdits") { + let edits = edits + .as_object() + .filter(|m| m.len() <= 256) + .ok_or_else(|| bad(cmd, "colorTableEdits must be an object of palette indices to #rrggbb colours"))?; + let table = st.color_table.as_ref().ok_or_else(|| bad(cmd, "colorTableEdits requires colorTable"))?; + for (index, value) in edits { + let index = index.parse::().ok().filter(|i| *i < table.len()).ok_or_else(|| bad(cmd, "colorTableEdits index is outside colorTable"))?; + let color = value.as_str().and_then(hex3).map(|c| c.map(to8)).ok_or_else(|| bad(cmd, "colorTableEdits values must be #rrggbb colours"))?; + st.color_table_edits.insert(index, color); + } + } + Ok(st) + } +} + +impl WebSettings { + /// The settings as command parameters (the inverse of [`WebSettings::from_params`]). + pub fn to_params(&self) -> Value { + let format = match self.format { + WebFormat::Gif => "gif", + WebFormat::Png8 => "png8", + WebFormat::Png24 => "png24", + WebFormat::Jpeg => "jpeg", + WebFormat::Wbmp => "wbmp", + }; + let palette = match self.palette { + PaletteKind::Exact => "exact", + PaletteKind::SystemMac => "systemMac", + PaletteKind::SystemWindows => "systemWindows", + PaletteKind::Web => "restrictive", + PaletteKind::Uniform => "uniform", + PaletteKind::Perceptual => "perceptual", + PaletteKind::Selective => "selective", + PaletteKind::Adaptive => "adaptive", + }; + let dither = match self.dither { + Dither::None => "none", + Dither::Diffusion => "diffusion", + Dither::Pattern => "pattern", + Dither::Noise => "noise", + }; + let metadata = match self.metadata { + WebMetadata::None => "none", + WebMetadata::Copyright => "copyright", + WebMetadata::CopyrightAndContact => "copyrightAndContact", + WebMetadata::AllExceptCameraInfo => "allExceptCameraInfo", + WebMetadata::All => "all", + }; + let matte = self.matte.map_or("none".to_string(), |c| format!("#{:02x}{:02x}{:02x}", to8(c[0]), to8(c[1]), to8(c[2]))); + let mut p = json!({"format": format, "palette": palette, "colors": self.colors, "dither": dither, "ditherAmount": (self.dither_amount * 100.0).round(), "transparency": self.transparency, "matte": matte, "interlaced": self.interlaced, "webSnap": (self.web_snap * 100.0).round(), "quality": self.quality, "progressive": self.progressive, "optimized": self.optimized, "embedIcc": self.embed_icc, "metadata": metadata, "convertToSrgb": self.convert_to_srgb}); + if let Some(table) = &self.color_table { + p["colorTable"] = json!(table.iter().map(|c| rgb_hex(*c)).collect::>()); + } + if !self.color_table_edits.is_empty() { + p["colorTableEdits"] = + json!(self.color_table_edits.iter().map(|(i, c)| (i.to_string(), rgb_hex(*c))).collect::>()); + } + p + } +} + +/// A palette colour in command/control-channel notation. +pub fn rgb_hex(c: [u8; 3]) -> String { + format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]) +} + +/// Save for Web's named presets. +pub const PRESETS: [&str; 12] = [ + "GIF 128 Dithered", + "GIF 128 No Dither", + "GIF 32 Dithered", + "GIF 32 No Dither", + "GIF 64 Dithered", + "GIF 64 No Dither", + "GIF Restrictive", + "JPEG High", + "JPEG Low", + "JPEG Medium", + "PNG-24", + "PNG-8 128 Dithered", +]; + +pub fn preset_settings(name: &str) -> Option { + let d = WebSettings::default(); + let gif = |colors: usize, dither: bool| WebSettings { + format: WebFormat::Gif, + colors, + dither: if dither { Dither::Diffusion } else { Dither::None }, + ..WebSettings::default() + }; + Some(match name { + "GIF 128 Dithered" => gif(128, true), + "GIF 128 No Dither" => gif(128, false), + "GIF 32 Dithered" => gif(32, true), + "GIF 32 No Dither" => gif(32, false), + "GIF 64 Dithered" => gif(64, true), + "GIF 64 No Dither" => gif(64, false), + "GIF Restrictive" => WebSettings { palette: PaletteKind::Web, ..gif(256, true) }, + "JPEG High" => WebSettings { format: WebFormat::Jpeg, quality: 60, ..d }, + "JPEG Low" => WebSettings { format: WebFormat::Jpeg, quality: 10, ..d }, + "JPEG Medium" => WebSettings { format: WebFormat::Jpeg, quality: 30, ..d }, + "JPEG Maximum" => WebSettings { format: WebFormat::Jpeg, quality: 100, ..d }, + "JPEG Very High" => WebSettings { format: WebFormat::Jpeg, quality: 80, ..d }, + "PNG-24" => WebSettings { format: WebFormat::Png24, ..d }, + "PNG-8 128 Dithered" => WebSettings { format: WebFormat::Png8, colors: 128, ..d }, + _ => return None, + }) +} From c25ba4145a838c0a87db621e28254e81472dbb29 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:54:25 +0000 Subject: [PATCH 212/259] refactor(ui-egui): move the app impl and services out of lib.rs --- crates/ui-egui/src/app.rs | 3003 ++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 3417 +------------------------------- crates/ui-egui/src/services.rs | 441 +++++ 3 files changed, 3455 insertions(+), 3406 deletions(-) create mode 100644 crates/ui-egui/src/app.rs create mode 100644 crates/ui-egui/src/services.rs diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs new file mode 100644 index 0000000000..a5f9760d16 --- /dev/null +++ b/crates/ui-egui/src/app.rs @@ -0,0 +1,3003 @@ +use super::services::{ExportSettings, FormatChoices, SAVE_OPTIONS_OPEN, SaveKind, Services, plain_raster, saved_revision_after_write}; +use super::*; + +impl PhotocraftApp { + pub fn new(mut session: Session, mut services: Services) -> Self { + session.updates.check = services.check_updates.take(); + let mut app = Self { + session, + ui: UiState::default(), + services, + canvases: HashMap::new(), + navigator_textures: HashMap::new(), + display_memo: HashMap::new(), + navigator_gpu: HashMap::new(), + navigator_plain: std::collections::HashSet::new(), + info_samplers: None, + monitors: Default::default(), + checker: None, + drag: None, + move_blocked: false, + tool_override: None, + live_stroke: None, + committed_stroke: None, + retouch_from_live: false, + trail: None, + remove_pending: Vec::new(), + remove_pending_target: None, + remove_trail: None, + menu_cache: None, + move_preview: None, + move_hover: None, + move_distance: None, + object_finder: None, + blend_preview: None, + reorder_preview: None, + reorder_preview_hit: false, + patch_preview: None, + cam_preview: None, + magnetic: Default::default(), + secondary_erase: false, + held_erase: false, + defer_live_stroke: false, + press_stroke: false, + last_stroke_end: None, + brush_resize: None, + quick_pick: false, + brush_resize_armed: false, + alt_sampling: false, + mixer_sampling: false, + caps_lock: false, + opacity_keys: None, + control_rx: None, + captures: screenshot::Captures::default(), + type_ime: type_tool::ImeState::default(), + input_waiters: Vec::new(), + live_adjust: None, + frame: 0, + notices_hovered: false, + styled: false, + integrated_titlebar: false, + custom_titlebar: false, + last_window_title: String::new(), + fonts_ready: false, + last_canvas_rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)), + arrange_start: 0, + ppp: 1.0, + drop_canvas_rect: None, + tab_strip: None, + drop_places: Default::default(), + view_docs: Vec::new(), + fps: 0.0, + last_frame_time: 0.0, + thumbs: HashMap::new(), + thumb_frames: HashMap::new(), + snapshot_thumbs: HashMap::new(), + thumb_documents: Vec::new(), + bounds_cache: HashMap::new(), + proxy: None, + proxy_uploaded: None, + outline_cache: None, + filter_preview: None, + smart_filter_targets: Default::default(), + #[cfg(not(target_arch = "wasm32"))] + filter_preview_worker: Default::default(), + redraws: Default::default(), + kept: Default::default(), + color_range: None, + adjust_preview: None, + live_adjust_preview: None, + synthetic: Vec::new(), + synthetic_batch: None, + synthetic_reinject: false, + synthetic_snapshot: None, + automation_input: false, + paused_playbacks: Default::default(), + channel_thumbs: None, + channel_views: HashMap::new(), + type_layout: None, + type_clicks: None, + type_transform_preview: None, + type_font_preview: None, + guide_drag: None, + layer_box: None, + crop: Default::default(), + pcrop: Default::default(), + hover_doc: None, + hover_layer: None, + canvas_hover_layer: None, + clone_preview: None, + info_sample: None, + os_clip_sig: None, + clip_unmirrored: true, + clip_external: false, + clip_read_for_paste: false, + transform_preview: None, + move_mods: Default::default(), + nudge_bundle: Default::default(), + style_preview: None, + text_style_preview: None, + solid_fill_preview: None, + pattern_fill_preview: None, + shape_fill_preview: None, + distort: Default::default(), + gradient: Default::default(), + camera_raw: None, + pending_raw_open: None, + raw_redevelop: Vec::new(), + wide_angle: None, + dialog_edits: Default::default(), + pending_after_prompt: None, + tone_hist: None, + doc_hist: None, + doc_hist_preview: None, + hist_job: None, + hist_uncached: None, + gpu: None, + window_device: None, + window_lost: false, + window_recovery_retry: None, + gpu_render_state: None, + gpu_fault: None, + gpu_oom_retries: 0, + started: None, + perf: Default::default(), + stroke_trace: stroke_trace::StrokeTrace::from_env(), + prefs_rt: Default::default(), + updates_rt: Default::default(), + discard: None, + file_dialog: None, + tiff_options: None, + save_dirs: HashMap::new(), + disk_stamps: HashMap::new(), + targa_options: None, + jpeg_options: None, + dds_options: None, + held_opens: Default::default(), + allow_close: false, + stylus: Default::default(), + control_click: Default::default(), + background_jobs: false, + min_frame_ms: None, + last_frame_start_ms: 0.0, + jobs: Default::default(), + #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] + live_tokens: theme::live::LiveTokens::from_env(), + }; + // Saved preferences are in place before the first frame; recovery starts in upkeep. + prefs_ui::load(&mut app); + layers_panel_ui::restore_options(&mut app); + histogram_panel::restore_options(&mut app); + // After the saved preferences, which say whether the set was already offered. + kys_import::offer_import(&mut app); + notices::wayland_file_drop_guidance(&mut app); + // File › Scripts › Script Events Manager: "Start Application". + photocraft_engine::automate_cmds::fire_event(&mut app.session, "startApplication"); + app + } + + /// Draw the document canvas on the GPU (custom WGSL shader) instead of via egui textures. + /// Call from the app creator with `cc.wgpu_render_state`; without it the CPU path is used. + pub fn set_wgpu(&mut self, rs: eframe::egui_wgpu::RenderState) { + // Preferences › Performance › cache tile size (PHOTOCRAFT_GPU_TILE still overrides). + let tile = self.session.prefs().performance.cache_tile_size; + // Escaped driver/setup panics must leave the session and CPU canvas alive. + self.perf.gpu_info.set_adapter(&rs.adapter.get_info()); + // The browser has no adapter list (egui-wgpu only has it natively). + #[cfg(not(target_arch = "wasm32"))] + self.perf.gpu_info.set_available(&rs.available_adapters); + self.gpu_render_state = Some(rs.clone()); + let gpu = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| gpu_canvas::GpuCanvas::with_tile(&rs, Some(tile)))) { + Ok(gpu) => gpu, + Err(payload) => { + let detail = payload + .downcast_ref::() + .cloned() + .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string())) + .unwrap_or_else(|| "GPU canvas initialization failed".into()); + self.perf.gpu_info.canvas = "cpu".into(); + self.perf.gpu_info.fallback = Some(detail.clone()); + gpu_status::queue_fallback_notice(self, detail); + self.watch_window_device(&rs.device); + return; + } + }; + self.perf.gpu_info.canvas = "gpu".into(); + self.window_device = Some((rs.device.clone(), gpu.health().clone())); + self.gpu = Some(gpu); + self.prefs_rt.gpu_style = None; + } + + /// Whether the document canvas currently draws on the GPU (false on the CPU path, and after + /// the device was lost). + pub fn gpu_active(&self) -> bool { + self.gpu.is_some() + } + + /// The GPU canvas's device health flag (tests inject faults through it). + pub fn gpu_health(&self) -> Option { + self.gpu.as_ref().map(|g| g.health().clone()) + } + + /// Watch the device the window draws with when the GPU canvas doesn't (the CPU canvas), so + /// its loss is handled like the GPU canvas's (see `gpu_status::check_window`). + pub fn watch_window_device(&mut self, device: &eframe::wgpu::Device) { + self.window_device = Some((device.clone(), photocraft_gpu::DeviceHealth::watch(device))); + } + + /// Whether the window's graphics device was lost, so the app saves its documents for + /// recovery and closes once they are saved (#3438). + pub fn window_lost(&self) -> bool { + self.window_lost + } + + /// Destroy the window's graphics device, as a driver reset does (`ui.gpu.simulateLoss` + /// with `destroy`, tests). Returns whether there was one. + pub fn destroy_window_device(&mut self) -> bool { + self.window_device.as_ref().map(|(device, _)| device.destroy()).is_some() + } + + /// Run `hook` once the app has rendered its first frames (and a document opened at launch + /// has drawn): the desktop app clears its crash-safe GPU startup marker there. + pub fn on_started(&mut self, hook: impl FnOnce(&mut PhotocraftApp) + 'static) { + self.started = Some(Box::new(hook)); + } + + /// Per-frame GPU health check (called from `logic`; tests call it directly): falls back to + /// the CPU canvas after a device loss and runs the started hook. + pub fn check_gpu(&mut self, ctx: &egui::Context) { + gpu_status::check(self, ctx); + } + + /// Attach a control channel (requests arrive from a transport thread: TCP, stdin, tests). + pub fn with_control(mut self, rx: Receiver) -> Self { + self.control_rx = Some(rx); + self + } + + /// Run an engine command, reporting errors in the status bar. + pub fn run(&mut self, id: &str, params: Value) -> Result { + if let Some(result) = delete_layer_prompt::intercept(self, id, ¶ms) { + return result; + } + if let Some(result) = mask_trash_prompt::intercept(self, id, ¶ms) { + return result; + } + // Automation input also gates every step a command runs on its behalf (`actions.play`). + let gate = if self.automation_input && self.session.authorize.is_none() { self.services.automation_authorize } else { None }; + if gate.is_some() { + self.session.authorize = gate; + } + let result = self.run_command(id, params); + if gate.is_some() { + self.session.authorize = None; + } + // An explicit channel target (⌘2, ⌘\, ⌘3…) decides what the Layers panel targets too: + // ⌘2 after the mask was targeted goes back to the layer's pixels. + if result.is_ok() && id.starts_with("channel.target") { + if let Some(t) = self.session.active().map(|st| st.channel_view.target) { + use photocraft_engine::channel_cmds::ChannelTarget; + self.ui.mask_target = t == ChannelTarget::LayerMask; + self.ui.vector_mask_target = t == ChannelTarget::VectorMask; + } + self.sync_mask_targets(); + } + result + } + + pub(crate) fn run_command(&mut self, id: &str, params: Value) -> Result { + if !vector_ui::cancel_stale(self) { + return Err(self.ui.status.clone()); + } + if matches!(id, "paint.setSymmetry" | "paint.symmetryFromPath" | "paint.symmetryDisable") { + self.ui.symmetry_transform = None; + } + let clip_read = std::mem::take(&mut self.clip_read_for_paste); + if self.automation_input + && let Some(authorize) = self.services.automation_command.as_ref() + { + authorize(id, ¶ms)?; + } + // A new layer while Free Transform is open applies the transform first, as Photoshop does + // (#5667): History reads the transform (or Place Embedded), then New Layer. Only for a + // command that can run; a transform refused or still being applied keeps the box open and + // the command doesn't run. + if photocraft_engine::PRECHECKED.contains(&id) && self.ui.transform.is_some() { + // Bad params or a command that can't run leave the box as it is. + self.session.precheck(id, ¶ms).map_err(|e| e.to_string())?; + transform_tool::commit(self); + if transform_tool::committing(self).is_some() { + return Err(tl!("Free Transform is still being applied; try again when it has finished.").into()); + } + if self.ui.transform.is_some() { + return Err(if self.ui.status.is_empty() { tl!("The transform couldn't be applied.").into() } else { self.ui.status.clone() }); + } + } + actions::suspended_guard(self, id)?; + if let Some(result) = panel_docking::command(self, id, ¶ms) { + return result; + } + if let Some(r) = transform_tool::intercept(self, id) { + return r; + } + if let Some(r) = crate::crop_ui::intercept(self, id) { + return r; + } + let t0 = gpu_canvas::now_ms(); + // The OS clipboard is read only on an explicit paste, never in the background (privacy, CPU). + if matches!(id, "edit.paste" | "edit.pasteSpecial.pasteInPlace" | "file.newFromClipboard") { + if !clip_read { + self.import_os_clipboard()?; + } + if self.session.clipboard.is_none() && self.services.clipboard_get_image.is_some() { + if self.services.clipboard_unreadable.as_ref().is_some_and(|unreadable| unreadable()) { + // The clipboard may well hold an image that can't be reached: say why. + notices::clipboard_unreadable(self); + return Ok(serde_json::json!({"pasted": false})); + } + // Enabled on the strength of the OS clipboard, which held no image: a quiet no-op. + let message = "Nothing to paste: the clipboard holds no image"; + self.ui.status = tl!(message).into(); + self.ui.status_error = false; + return Ok(serde_json::json!({"pasted": false})); + } + } + let suppress_events = self.automation_input && self.session.prefs().script_events.enabled; + if suppress_events { + self.session.edit_prefs(|prefs| prefs.script_events.enabled = false); + } + // Long commands become background jobs when enabled (`jobs_ui`); the rest run inline. + let params = self.with_mask_target(id, params); + let params = vector_ui::with_active_path(self, id, params); + let path_mask = vector_ui::takes_path_mask(id) && params.get("path").is_some_and(|v| !v.is_null()); + let on_active_layer = self + .session + .active() + .is_some_and(|st| st.active_layer.is_some_and(|layer| params.get("layer").and_then(Value::as_u64).is_none_or(|target| target == layer.0))); + let creates_active_mask = + matches!(id, "layer.layerMask.revealAll" | "layer.layerMask.hideAll" | "layer.layerMask.revealSelection" | "layer.layerMask.hideSelection") + && on_active_layer; + let creates_active_vector_mask = matches!( + id, + "layer.vectorMask.add" | "layer.vectorMask.fromPath" | "layer.vectorMask.revealAll" | "layer.vectorMask.hideAll" | "layer.vectorMask.currentPath" + ) && on_active_layer; + let r = if id == "actions.play" { + actions::play(self, ¶ms) + } else if photocraft_engine::actions_cmds::shell_view_command(id) { + actions::run_view(self, id, params) + } else { + jobs_ui::run(self, id, params) + }; + let creates_adjustment_or_fill = id.starts_with("layer.newAdjustmentLayer.") || id.starts_with("layer.newFillLayer."); + if r.is_ok() && ADDS_LAYER_MASK.contains(&id) { + // Adding an explicit mask targets it, as in Photoshop (#2166). + self.ui.mask_target = true; + self.ui.vector_mask_target = false; + self.ui.properties_layer = None; + } else if r.is_ok() && creates_adjustment_or_fill { + // Panel Options may suppress a fill layer's default mask. Never target a + // nonexistent mask; an active path creates a vector mask instead. + let masks = self + .session + .active() + .and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))) + .map(|layer| (layer.mask.is_some(), layer.vector_mask.is_some())) + .unwrap_or((false, false)); + self.ui.mask_target = masks.0; + self.ui.vector_mask_target = !masks.0 && masks.1; + // Keep Properties on the new layer contents, as on main (#3369). + self.ui.properties_layer = self.session.active().and_then(|st| st.active_layer).map(|l| l.0); + } + if r.is_ok() && creates_adjustment_or_fill { + // Properties comes to the front, shown and expanded, so the new layer's settings can + // be edited at once, as in Photoshop (#4028). The layer is made whatever happens here. + if self.ui.docking.is_some() { + let _ = panel_docking::command(self, "window.panel.activate", &json!({"panel": "properties"})); + } else { + self.ui.dock_tabs.properties = 0; + dock::reveal(self, dock::Group::Properties); + } + } + // Making a new selection reveals its outline after View > Extras was hidden (#5597). + // These interactive selection commands complete inline; a failed command, deselection, + // or painting inside an existing selection must leave the user's view choice alone. + if r.as_ref().is_ok_and(|v| v.get("changed") != Some(&Value::Bool(false)) && v.get("pending") != Some(&Value::Bool(true))) + && matches!( + id, + "select.rect" + | "select.lasso" + | "select.magneticLasso" + | "select.magicWand" + | "select.quick" + | "select.object" + | "select.loadSelection" + | "select.loadLuminosity" + | "path.toSelection" + ) + && self.session.active().is_some_and(|st| st.doc.selection.is_some()) + { + self.ui.view.extras = true; + } + if r.is_ok() && id == "select.toWorkPath" { + // Make Work Path selects the new work path in the Paths panel, as in Photoshop. + self.ui.selected_path = Some("work".into()); + } + if r.is_ok() && path_mask { + // The new layer's vector mask becomes the active path, as in Photoshop: the path it + // was made from is no longer selected, so the next fill layer isn't masked by it too. + self.ui.selected_path = Some("layer".into()); + } + if r.is_ok() && creates_active_mask { + // Adding a mask selects its thumbnail: the next brush or footer Delete targets it. + self.ui.mask_target = true; + self.ui.vector_mask_target = false; + } + if r.is_ok() && creates_active_vector_mask { + // Likewise a new vector mask (#4728): Properties shows its Density and Feather, and a + // mask made from a path becomes the active path. + self.ui.vector_mask_target = true; + self.ui.mask_target = false; + if matches!(id, "layer.vectorMask.currentPath" | "layer.vectorMask.fromPath") { + self.ui.selected_path = Some("layer".into()); + } + } + if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "edit.copyMerged") { + self.clip_external = false; + self.export_os_clipboard(); + } + self.perf.last_command = id.to_string(); + self.perf.command_ms = gpu_canvas::now_ms() - t0; + match &r { + Ok(_) => { + if self.ui.status_error { + self.ui.status.clear(); + self.ui.status_error = false; + } + self.sync_views(); + let removed = self.session.take_samplers_removed(); + if removed > 0 && !self.ui.status_error { + // A canvas-size change (crop, Canvas Size, Image Size, rotation) dropped Color + // Sampler points that fell outside the new canvas (#1046). + self.ui.status = crate::i18n::trn(crate::i18n::current(), removed as u64, "{n} sample point removed", "{n} sample points removed"); + self.ui.status_error = false; + } + } + Err(e) => { + self.ui.status = e.clone(); + self.ui.status_error = true; + } + } + if suppress_events { + self.session.edit_prefs(|prefs| prefs.script_events.enabled = true); + } + r + } + + /// Keep one view per document, in tab order: a view and its windows stay with their document + /// when tabs move (`document.move`) or close. + /// The tool pointer events go to: a held temporary tool when there is one (⌘ is the Move + /// tool, `hold_keys::cmd_moves`), else the selected tool. + pub fn active_tool(&self) -> state::Tool { + self.tool_override.unwrap_or(self.ui.tool) + } + + pub fn sync_views(&mut self) { + type_transform::cancel_stale(self); + crate::cam_transform::cancel_stale(self); + crate::lasso_ui::cancel_stale(self); + // A polygon under construction belongs to the Polygonal Lasso tool, not the next tool. + if self.ui.tool != Tool::PolygonLasso { + self.ui.polygon.clear(); + self.ui.polygon_mode.clear(); + } + // ... and to the document it was started on. + crate::canvas::polygon_cancel_stale(self); + crate::crop_ui::cancel_stale(self); + crate::distort_ui::cancel_stale(self); + crate::perspective_crop_ui::cancel_stale(self); + // A pen path under construction belongs to the document it was started on too. + vector_ui::cancel_stale(self); + let ids: Vec = self.session.documents().iter().map(|d| d.doc.id).collect(); + // Where the document of view `i` is now. Views not tracked yet keep their index. + let now = |i: usize| match self.view_docs.get(i) { + Some(id) => ids.iter().position(|d| d == id), + None => (i < ids.len()).then_some(i), + }; + let mut views: Vec> = ids.iter().map(|_| None).collect(); + for (i, v) in std::mem::take(&mut self.ui.views).into_iter().enumerate() { + if let Some(slot) = now(i).and_then(|to| views.get_mut(to)) { + *slot = Some(v); + } + } + self.ui.views = views.into_iter().map(Option::unwrap_or_default).collect(); + self.ui.windows.retain_mut(|w| now(w.document).map(|d| w.document = d).is_some()); + if !self.session.prefs().workspace.open_documents_as_tabs { + let new_docs: Vec = ids.iter().enumerate().filter(|(_, id)| !self.view_docs.contains(id)).map(|(i, _)| i).collect(); + for &idx in &new_docs { + if !self.ui.windows.iter().any(|w| w.document == idx) { + crate::view_cmds::float_window(self, idx, idx); + } + } + } + self.canvases.retain(|(doc, _), _| ids.contains(doc)); + self.navigator_textures.retain(|doc, _| ids.contains(doc)); + self.view_docs = ids; + self.prune_thumbs(); + self.sync_mask_targets(); + // Channel-view textures outlive a hidden view (cheap re-show), not their document. + if !self.channel_views.is_empty() { + let docs = self.session.documents(); + self.channel_views.retain(|id, _| docs.iter().any(|d| d.doc.id.0 == *id)); + } + // Commands may close and reopen a preserved-ID document before the next repaint. + canvas::retain_gpu_documents(self); + } + + /// Record `path` as the most-recently-opened file (File › Open Recent): de-duplicated, newest + /// first, capped at Preferences › File Handling › Recent File List Contains. The list lives in + /// the preferences (`fileHandling.recentFiles`), so it survives a restart; `ui.recent_files` + /// mirrors it for the menus and the Home screen. + pub fn push_recent(&mut self, path: &str) { + let cap = self.recent_cap(); + let mut r = self.session.prefs().file_handling.recent_files.clone(); + r.retain(|p| p != path); + r.insert(0, path.to_string()); + r.truncate(cap); + self.ui.recent_files = r.clone(); + self.session.prefs.edit(|p| p.file_handling.recent_files = r); + } + + /// Records a picked type family for the font menu's Recent group, capped by + /// Preferences ▸ Type ▸ Recent Fonts (0 keeps no list), most recent first, de-duplicated. + pub fn note_recent_font(&mut self, family: &str) { + let cap = self.session.prefs().type_.recent_fonts.min(50) as usize; + let r = &mut self.ui.recent_fonts; + r.retain(|f| f != family); + if cap == 0 { + r.clear(); + return; + } + r.insert(0, family.to_string()); + r.truncate(cap); + } + + /// Preferences ▸ Type ▸ Recent Fonts: a smaller cap (or 0) applies to the existing list at + /// once, not only after the next pick. + pub fn sync_recent_fonts(&mut self) { + self.ui.recent_fonts.truncate(self.session.prefs().type_.recent_fonts.min(50) as usize); + } + + /// File › Open Recent › Clear Recent File List. + pub fn clear_recent(&mut self) { + self.ui.recent_files.clear(); + self.session.prefs.edit(|p| p.file_handling.recent_files.clear()); + } + + /// Take one file off the recent list (the Home screen's × or Remove from Recent, #2691). The + /// file stays on disk, and opening it again lists it again. + pub fn remove_recent(&mut self, path: &str) { + self.ui.recent_files.retain(|p| p != path); + self.session.prefs.edit(|p| p.file_handling.recent_files.retain(|r| r != path)); + } + + /// How many recent files to remember ("Recent File List Contains", 0–100). + pub fn recent_cap(&self) -> usize { + self.session.prefs().file_handling.recent_file_count.min(100) as usize + } + + /// Mirror the stored recent-file list into the UI state (after loading the preferences, or + /// when the Preferences dialog or an agent changes the list or its length). Cheap enough to + /// run every frame: a slice comparison of at most 100 paths, no allocation unless it changed. + pub fn sync_recent(&mut self) { + let cap = self.recent_cap(); + let stored = &self.session.prefs().file_handling.recent_files; + let want = stored.get(..cap.min(stored.len())).unwrap_or_default(); + if self.ui.recent_files.as_slice() != want { + self.ui.recent_files = want.to_vec(); + } + } + + /// Open a file's bytes as a new document named `name`; returns the import warnings (also + /// shown to the user). Files from disk go through [`open_file`](Self::open_file), which also + /// remembers the path. Brush and gradient files go to the preset libraries instead. + pub fn open_bytes(&mut self, name: &str, bytes: &[u8]) -> Result, String> { + self.open_bytes_from(name, bytes, None) + } + + /// [`Self::open_bytes`] for a file read from `path` (File › Save writes back there; it goes + /// to Open Recent), when known. + pub(crate) fn open_bytes_from(&mut self, name: &str, bytes: &[u8], path: Option<&str>) -> Result, String> { + if let Some(r) = preset_files_ui::open(self, name, bytes) { + return r.map(|()| Vec::new()); + } + let name = &self.open_name(name); + // Decoded on a worker: a tab with progress appears now, the document when it's ready + // (warnings are shown then). + if self.background_jobs { + jobs_ui::start_open(self, name, path.map(str::to_string), jobs_ui::bytes(bytes))?; + return Ok(Vec::new()); + } + let import = self.services.import.as_ref().ok_or("no importer configured")?; + let opts = photocraft_engine::jobs::import_options(self.session.prefs()); + let (mut doc, warnings, damaged) = if photocraft_io::is_psd(bytes) { + // Read PSD damage as structured information in the same decode, not by + // retrying an error or matching the text of a compatibility warning. + let (r, damaged) = photocraft_io::import_for_open(name, bytes, &opts).map_err(|e| e.to_string())?; + (r.document, r.warnings, damaged) + } else { + let (doc, warnings) = import(name, bytes, &opts)?; + (doc, warnings, false) + }; + // Preferences › Raw Defaults › Resolution, as the engine's open applies it. + photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc); + // Edit › Color Settings policies apply on open; Ask When Opening holds the file back + // until its prompt is answered, and later files wait behind it (`open_prompt`). + // Missing fonts are read from the document itself: it may not be open yet (#4559). + let warnings = file_open::with_missing_fonts_of(&doc, warnings); + // A developed raw has no embedded profile to ask about. + let developed = warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)); + let question = self.session.color.open_question(&doc).filter(|_| !developed); + let wants_raw = camera_raw_ui::wants_open_dialog(self, &warnings); + open_prompt::arrive( + self, + open_prompt::Held { + doc, + read_only: photocraft_io::affinity::is_affinity(bytes), + damage_pending: damaged, + name: name.to_string(), + path: path.map(str::to_string), + warnings: warnings.clone(), + bytes: (wants_raw && path.is_none()).then(|| std::sync::Arc::new(bytes.to_vec())), + slot: None, + question, + policy_applied: false, + }, + ); + Ok(warnings) + } + + /// Open bytes supplied by an authenticated automation client without + /// invoking user-configured script-event paths outside the granted root. + /// Returns the import warnings (also shown to the user). Brush and gradient + /// files go to the preset libraries, as for interactive opens. + pub fn open_automation_bytes(&mut self, name: &str, bytes: &[u8]) -> Result, String> { + let events_enabled = self.session.prefs().script_events.enabled; + if events_enabled { + self.session.edit_prefs(|prefs| prefs.script_events.enabled = false); + } + let result = match preset_files_ui::open(self, name, bytes) { + Some(r) => r.map(|()| Vec::new()), + None => self.import_automation_document(name, bytes), + }; + if events_enabled { + self.session.edit_prefs(|prefs| prefs.script_events.enabled = true); + } + result + } + + /// The document half of [`open_automation_bytes`](Self::open_automation_bytes): no script + /// events and no Color Settings policy (which may read user-configured profile paths). + fn import_automation_document(&mut self, name: &str, bytes: &[u8]) -> Result, String> { + let import = self.services.import.as_ref().ok_or("no importer configured")?; + let opts = photocraft_engine::jobs::import_options(self.session.prefs()); + let (mut doc, warnings) = import(name, bytes, &opts)?; + photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc); + // The caller records the path it read from. + self.session.add_document(doc, None); + if let Some(st) = self.session.active_mut() { + st.source_read_only = photocraft_io::affinity::is_affinity(bytes); + } + self.sync_views(); + self.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]); + self.ui.status_error = false; + notices::io_warnings(self, &crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]), &warnings); + Ok(warnings) + } + + /// Save the active document to `path`, or to a path chosen in the save dialog (which + /// continues on a later frame, see `file_dialog`). Returns `{"path", "warnings"}` (the export + /// warnings are also shown to the user). + pub fn save_as(&mut self, path: Option) -> Result { + self.save_as_with(path, FormatChoices::default()) + } + + /// [`Self::save_as`] with the format choices already made, which skip their prompts: + /// `file.save` and `file.saveAs` with `tgaBits` (no Targa Options), `ddsCompression` or + /// `ddsMipmaps` (no DDS Options), or `quality` or `jpegFormat` (no JPEG Options). + pub fn save_as_with(&mut self, path: Option, choices: FormatChoices) -> Result { + self.save_dialog_flow(path, choices, false) + } + + /// [`Self::save_as_with`]. `plain_save` marks File › Save that had to ask for a file name + /// (a flat file): confirming the document's own file is recorded as a `file.save` step, + /// which writes whichever file the action is played on, not as a Save As to a fixed path. + pub(crate) fn save_dialog_flow(&mut self, path: Option, choices: FormatChoices, plain_save: bool) -> Result { + if self.save_options_open() { + return Err(SAVE_OPTIONS_OPEN.into()); + } + // Edit Contents documents save back into their smart object. + if path.is_none() && self.session.is_enabled("layer.smartObjects.saveContents") { + self.run("layer.smartObjects.saveContents", serde_json::json!({}))?; + return Ok(serde_json::json!({"path": "smart object", "warnings": []})); + } + if let Some(path) = path { + return self.save_to(path, choices); + } + let st = self.session.active().ok_or("no document")?; + // PDN imports default to our native format, which preserves Paint.NET's blend modes; + // Krita imports to OpenRaster, which Krita opens with its layers. + // Other files keep their format only when it can retain their layers. A plain raster + // (including an unlocked transparent PNG) can keep its flat format; editable contents, + // masks and layer appearance settings need a layered format even with just one layer. + let flat = plain_raster(&st.doc).is_some(); + let ext = st.path.as_deref().and_then(|p| std::path::Path::new(p).extension()).map(|e| e.to_string_lossy().to_ascii_lowercase()); + // An OpenRaster file only when it holds the whole document (#3806): else PSD is offered. + let holds_ora = st.path.as_deref().is_some_and(|p| photocraft_engine::file_cmds::holds_at(&st.doc, p)); + let writable = ext.is_some_and(|e| { + matches!(e.as_str(), photocraft_format::EXTENSION | "psd" | "psb" | "tif" | "tiff") + || (e == "ora" && holds_ora) + || (flat && photocraft_codecs::from_extension(&e).is_some_and(|f| f.caps().write)) + }); + let suggested = match &st.path { + Some(p) if writable => p.clone(), + p => { + let source = p.as_deref().unwrap_or(&st.doc.name); + let ext = match photocraft_engine::file_cmds::extension(source).as_deref() { + Some("pdn") => "pcraft", + Some("kra" | "krz") => "ora", + _ => "psd", + }; + std::path::Path::new(source).with_extension(ext).to_string_lossy().into_owned() + } + }; + let doc = st.doc.id; + self.pick_save(&suggested, move |app, path| { + app.with_document(doc, |app| { + let own = app.session.active().and_then(|st| st.path.clone()); + // Confirming the document's own file: ask first if another app changed it (#6596). + if plain_save + && own.as_deref() == Some(path.as_str()) + && let Some(r) = crate::disk_change_prompt::intercept(app, doc, &path, true, choices) + { + return r; + } + let r = app.save_to(path.clone(), choices)?; + if plain_save && own.as_deref() == Some(path.as_str()) { + app.journal_as_plain_save(&path); + } + Ok(r) + }) + }) + } + + /// [`Self::save_as_with`] once the path is known. + pub(crate) fn save_to(&mut self, path: String, choices: FormatChoices) -> Result { + // An RGB Targa asks for its bits per pixel, a DDS texture for its compression, and a JPEG + // for its quality and format, unless the caller chose them; the save continues from the + // prompt (still a copy when it would be one without the prompt), which records the step + // once answered. + if choices.tga_bits.is_none() && targa_options_ui::wants_prompt(self, &path) { + let copy = self.saves_copy(&path, None)?; + targa_options_ui::park(self, path.clone(), copy, "file.saveAs")?; + return Ok(serde_json::json!({"path": path, "warnings": []})); + } + if choices.dds.is_none() && dds_options_ui::wants_prompt(&path) { + let copy = self.saves_copy(&path, None)?; + dds_options_ui::park(self, path.clone(), copy, "file.saveAs")?; + return Ok(serde_json::json!({"path": path, "warnings": []})); + } + if choices.jpeg.is_none() && jpeg_options_ui::wants_prompt(self, &path) { + let copy = self.saves_copy(&path, None)?; + jpeg_options_ui::park(self, path.clone(), copy, "file.saveAs")?; + return Ok(serde_json::json!({"path": path, "warnings": []})); + } + // A layered TIFF asks about its layers first (Preferences › File Handling); the save + // continues from the prompt, which records the step once answered. + if tiff_options_ui::wants_prompt(self, &path) { + tiff_options_ui::park(self, path.clone())?; + return Ok(serde_json::json!({"path": path, "warnings": []})); + } + self.save_as_step(path, None, choices) + } + + /// File › Save back to the document's own file, recorded as a `file.save` step with the + /// Targa, DDS or JPEG answer in `choices` (a replayed or scripted Save of a flat file brings + /// its own). + pub(crate) fn save_in_place(&mut self, path: String, choices: FormatChoices) -> Result { + if self.save_options_open() { + return Err(SAVE_OPTIONS_OPEN.into()); + } + let r = self.write_save(path, None, choices)?; + // JPEG Options are recorded only where they change something + // ([`jpeg_options_ui::plain_save_step`]); the Targa and DDS answers as given. + let mut step = jpeg_options_ui::plain_save_step(choices.jpeg); + FormatChoices { jpeg: None, ..choices }.record(&mut step); + self.session.journal.push(("file.save".into(), step)); + Ok(r) + } + + /// Writes the Save As and journals it as a `file.saveAs` step with its path (and TIFF, + /// Targa, DDS or JPEG answer), so an action being recorded keeps it (#2032). + fn save_as_step(&mut self, path: String, tiff_layers: Option, choices: FormatChoices) -> Result { + let r = self.write_save(path.clone(), tiff_layers, choices)?; + let mut step = serde_json::json!({"path": path}); + if let Some(layers) = tiff_layers { + step["tiffLayers"] = layers.into(); + } + choices.record(&mut step); + self.session.journal.push(("file.saveAs".into(), step)); + Ok(r) + } + + /// Re-label the Save As just journaled for `path` as File › Save (see [`Self::save_dialog_flow`]), + /// keeping its Targa, DDS or JPEG answer so playback writes the file the same way. A save + /// parked behind Targa, DDS or JPEG Options hasn't been journaled yet: it is recorded as + /// File › Save once answered. + pub(crate) fn journal_as_plain_save(&mut self, path: &str) { + let parked = [ + self.targa_options.as_mut().map(|p| (&p.path, &mut p.record)), + self.dds_options.as_mut().map(|p| (&p.path, &mut p.record)), + self.jpeg_options.as_mut().map(|p| (&p.path, &mut p.record)), + ]; + if let Some((_, record)) = parked.into_iter().flatten().find(|(p, record)| p.as_str() == path && **record == "file.saveAs") { + *record = "file.save"; + return; + } + // Only the path goes: a script's format answer stays, so a replay writes the file it is + // played on the same way. Any other answer (TIFF layers) keeps the Save As. + if let Some(last) = self.session.journal.last_mut() + && last.0 == "file.saveAs" + && last.1.get("path").and_then(Value::as_str) == Some(path) + && let Some(step) = last.1.as_object() + && step.keys().all(|k| matches!(k.as_str(), "path" | "tgaBits" | "ddsCompression" | "ddsMipmaps" | "quality" | "jpegFormat")) + { + let mut step = step.clone(); + step.remove("path"); + *last = ("file.save".into(), Value::Object(step)); + } + } + + /// Replays a recorded `file.save` / `file.saveAs` / `file.saveACopy` / `file.export.exportAs` + /// step: no dialog or prompt, and the recorded TIFF, Targa, DDS or JPEG answer (if any) stands + /// in for its prompt. + pub(crate) fn replay_save(&mut self, id: &str, params: &Value) -> Result { + if self.save_options_open() { + return Err(SAVE_OPTIONS_OPEN.into()); + } + if id == "file.save" { + // The file the action is played on: one that holds the whole document, or a flat + // file a recorded Save confirmed in the dialog while the document is still a plain + // raster, so it is never flattened over (#3531, #3806). A flat file's recorded Targa, + // DDS or JPEG answer writes the same way, without asking. + let choices = FormatChoices::from_step(params, id)?; + let st = self.session.active().ok_or("no document")?; + let flat_own = |p: &str| { + !photocraft_engine::file_cmds::saves_in_place(p) + && plain_raster(&st.doc).is_some() + && photocraft_engine::file_cmds::extension(p).is_some_and(|e| photocraft_codecs::from_extension(&e).is_some_and(|f| f.caps().write)) + }; + let path = st.path.clone().filter(|p| photocraft_engine::file_cmds::holds_at(&st.doc, p) || flat_own(p)).ok_or( + "Save writes back only to the document's own PSD, PSB, .pcraft or OpenRaster file (OpenRaster only when it holds everything), or to its own flat file while the document is a single plain layer", + )?; + return self.save_in_place(path, choices); + } + if id == crate::export_dialog::COMMAND { + // Export As has its own settings, its TGA bits included (#7207). + return crate::export_dialog::replay(self, params); + } + let path = params.get("path").and_then(Value::as_str).filter(|p| !p.is_empty()).ok_or("Save As needs a `path`")?; + let choices = FormatChoices::from_step(params, id)?; + if id == "file.saveACopy" { + // A copy: the document keeps its own file and unsaved state, as when recorded (#4373). + let doc = self.session.active().ok_or("no document")?.doc.clone(); + return crate::view_cmds::write_copy(self, &doc, path, choices); + } + self.save_as_step(path.to_string(), params.get("tiffLayers").and_then(Value::as_bool), choices) + } + + /// What a save writes by default under the preferences: File Handling › Image Previews + /// decides whether a PSD/PSB gets its thumbnail, and Maximize PSD and PSB File Compatibility + /// whether it gets its real merged image. Ask When Saving has no dialog here yet, so it saves + /// both, as Photoshop's checkboxes start on. A JPEG or WebP is written the way the active + /// document's file was (its JPEG quality, a WebP lossy at its quality or lossless), as + /// Photoshop's Save and Save As options start there. + pub(crate) fn save_settings(&self) -> ExportSettings { + let file_handling = &self.session.prefs().file_handling; + let previews = file_handling.image_previews != photocraft_engine::prefs::Ask::Never; + let maximize = file_handling.maximize_psd_compatibility != photocraft_engine::prefs::Ask::Never; + let mut settings = ExportSettings { image_previews: previews, psd_maximize_compatibility: maximize, ..ExportSettings::default() }; + if let Some(st) = self.session.active() { + let e = &st.doc.file_encoding; + settings.jpeg_quality = e.jpeg_quality.map(|q| q.clamp(1, 100)); + settings.webp_lossless = e.webp_lossless.unwrap_or(settings.webp_lossless); + settings.webp_quality = e.webp_quality.map(|q| q.min(100)); + settings.document_path = st.path.as_deref().map(std::path::PathBuf::from); + settings.pcraft_cache = Some(st.pcraft_cache.clone()); + } + settings + } + + /// Whether saving the active document to `path` writes a copy. `tiff_layers` is the TIFF + /// Options answer: `Some(false)` discards the layers and saves a copy. + fn saves_copy(&self, path: &str, tiff_layers: Option) -> Result { + // A flat file that can't hold the document (its layers, or the layered file it lives in) + // is written as a copy, as in Photoshop: the document keeps its file, so Save still + // writes the layered original and the edits stay unsaved (#2550). + // An OpenRaster file that can't hold everything (adjustment layers, styles…) is a copy too, + // so the editable document isn't marked saved after losing them (#3806). + let st = self.session.active().ok_or("no document")?; + let tiff = |p: &str| matches!(photocraft_engine::file_cmds::extension(p).as_deref(), Some("tif" | "tiff")); + let holds = photocraft_engine::file_cmds::holds_at(&st.doc, path) || tiff(path); + let lives_layered = st.path.as_deref().is_some_and(|p| photocraft_engine::file_cmds::saves_in_place(p) || tiff(p)); + Ok(tiff_layers == Some(false) || (!holds && (plain_raster(&st.doc).is_none() || lives_layered))) + } + + /// Writes the active document to a known path. `tiff_layers` is the TIFF Options answer: + /// `Some(false)` discards the layers and saves a copy. `choices` are the Targa bits per pixel + /// (`None`: 32 with an alpha channel or transparency, else 24), the DDS options and the JPEG + /// Options. + fn write_save(&mut self, path: String, tiff_layers: Option, choices: FormatChoices) -> Result { + let copy = self.saves_copy(&path, tiff_layers)?; + let settings = choices.apply(ExportSettings { tiff_layers: tiff_layers.unwrap_or(ExportSettings::default().tiff_layers), ..self.save_settings() }); + match self.write_document(path.clone(), &settings, copy)? { + Some((path, warnings)) => Ok(serde_json::json!({"path": path, "warnings": warnings})), + None => Ok(serde_json::json!({"path": path, "warnings": [], "pending": true, "job": self.jobs.last_started.map(|j| j.0)})), + } + } + + /// Encodes the active document with `settings` and writes it to `path`, which becomes the + /// document's path unless saving a copy. A copy leaves the original's path and unsaved + /// changes intact. Returns the path and the export warnings (also shown to the user), or + /// `None` when the save went to a background job (#2017), which finishes it in + /// [`jobs_ui::tick`]. + pub(crate) fn write_document(&mut self, path: String, settings: &ExportSettings, copy: bool) -> Result)>, String> { + if self.background_jobs + && let Some(save) = self.services.save_file.clone() + { + return jobs_ui::start_save(self, path, settings.clone(), copy, save, false); + } + let st = self.session.active().ok_or("no document")?; + let (doc, written, previous) = (st.doc.id, st.revision, st.saved_revision); + let export = self.services.export.as_ref().ok_or("no exporter configured")?; + let (bytes, warnings) = export(&st.doc, &path, settings)?; + let write = self.services.write.as_mut().ok_or("no writer configured")?; + write(&path, &bytes)?; + let revision = saved_revision_after_write(!self.services.write_unconfirmed, written, previous); + self.saved(doc, revision, &path, &warnings, copy); + Ok(Some((path, warnings))) + } + + /// After `saver` was written to `path`, any other open document bound to that file no longer + /// matches it: it loses the file and is marked unsaved, so it can't stay "saved" while its file + /// holds something else, closing it asks first, and its own Save asks for a name instead of + /// writing over the new file (#6597). Paths are compared as files, so another letter case on a + /// case-insensitive volume or a hard link counts. A notice names the documents affected. + pub(crate) fn detach_others_from_file(&mut self, path: &str, saver: DocId) { + let others: Vec<(DocId, String)> = self + .session + .documents() + .iter() + .filter(|st| st.doc.id != saver && st.path.as_deref().is_some_and(|p| photocraft_engine::file_cmds::same_file(p, path))) + .map(|st| (st.doc.id, st.doc.name.clone())) + .collect(); + let mut detached = Vec::new(); + for (id, name) in others { + let done = self.with_document(id, |app| { + let st = app.session.active_mut().ok_or("no document")?; + st.path = None; + // No revision ever equals this, so the document reads as unsaved until saved again. + st.saved_revision = u64::MAX; + Ok(()) + }); + if done.is_ok() { + detached.push(name); + } + } + if detached.is_empty() { + return; + } + let name = file_open::display_name(path); + let title = { + let template = "{name} was saved over from another tab"; + crate::i18n::fmt(tl!(template), &[("name", name.as_str())]) + }; + let lines = detached + .iter() + .map(|doc| { + let template = "\"{doc}\" no longer has a file and is marked unsaved: save it under a new name to keep it"; + crate::i18n::fmt(tl!(template), &[("doc", doc.as_str())]) + }) + .collect(); + notices::post(self, title, lines, false, None); + } + + /// Record a written save of document `doc` as it was at `revision`: its name, path and saved + /// state (unless a copy), the status, script events and the warnings. + pub(crate) fn saved(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool) { + self.saved_inner(doc, revision, path, warnings, copy, SaveKind::User); + } + + /// [`Self::saved`] for automation saves: no user-configured hooks (docs/control-protocol.md). + pub(crate) fn saved_automation(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool) { + self.saved_inner(doc, revision, path, warnings, copy, SaveKind::Automation); + } + + fn saved_inner(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool, kind: SaveKind) { + // Automation: only a layered save becomes the document's file; a flat one is a + // copy, as in the headless server (#2579). + let (hooks, arm) = match kind { + SaveKind::User => (true, true), + SaveKind::Automation => { + let holds = self.session.documents().iter().find(|st| st.doc.id == doc).is_some_and(|st| photocraft_engine::file_cmds::holds_at(&st.doc, path)); + (false, holds) + } + }; + self.ui.status = crate::i18n::fmt(tl!("Saved {name}"), &[("name", path)]); + // The file was written, copy or not: another tab bound to it no longer matches it. + self.detach_others_from_file(path, doc); + if !copy { + // A background save may finish while another document is active (or after its + // document was closed, when there is nothing left to record). + let _ = self.with_document(doc, |app| { + if let Some(st) = app.session.active_mut() + && arm + { + st.saved_to(path.to_string()); + // The job locked the document, but record the revision that was written. + st.saved_revision = revision; + app.remember_stamp(doc, path); + } + // "Save Document" script events and File › Generate › Image Assets. + if hooks + && let Some(i) = app.session.active_index() + && let Some(r) = photocraft_engine::automate_cmds::document_saved(&mut app.session, i) + { + let template = "Saved {path}; image assets: {n} in {dir}"; + app.ui.status = crate::i18n::fmt( + tl!(template), + &[("path", path), ("n", &r["files"].as_array().map_or(0, Vec::len).to_string()), ("dir", r["dir"].as_str().unwrap_or(""))], + ); + } + Ok(()) + }); + // The file the document now lives in goes to the top of Open Recent and the Home + // screen, as opening it does (#4400). Automation saves don't touch the user's list. + if hooks { + self.push_recent(path); + } + } else if self.disk_stamps.get(&doc).is_some_and(|(own, _)| own == path) { + // A copy written over the document's own file is this app's change too. + self.remember_stamp(doc, path); + } + self.ui.status_error = false; + let what = crate::i18n::fmt(tl!("Saved {name}"), &[("name", file_open::display_name(path).as_str())]); + notices::io_warnings(self, &what, warnings); + self.sync_views(); + } + + /// Note how `doc`'s own file at `path` looks now that the document read or wrote it. + pub(crate) fn remember_stamp(&mut self, doc: photocraft_doc::DocId, path: &str) { + match self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)) { + Some(now) => self.disk_stamps.insert(doc, (path.to_string(), now)), + None => self.disk_stamps.remove(&doc), + }; + } + + /// Another app changed `doc`'s own file at `path` since the document was opened from it or + /// last saved to it. A file that is gone, or one never stamped, counts as unchanged. + pub(crate) fn changed_on_disk(&self, doc: photocraft_doc::DocId, path: &str) -> bool { + let Some((own, then)) = self.disk_stamps.get(&doc) else { return false }; + own == path && self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)).is_some_and(|now| now != *then) + } + + /// TIFF, Targa, DDS or JPEG Options is waiting on an answer before a save is written. + pub(crate) fn save_options_open(&self) -> bool { + self.tiff_options.is_some() || self.targa_options.is_some() || self.dds_options.is_some() || self.jpeg_options.is_some() + } + + /// Writes a save that waited on a format prompt (Targa, DDS or JPEG Options) once answered: + /// journals `step` as its command (`file.saveAs` for Save As, `file.saveACopy` for Save a + /// Copy, `file.save` for a plain Save), so an action being recorded keeps it with this answer + /// (#2032, #4373), reports a failure in the status bar, and releases a close prompt waiting on + /// the save. + pub(crate) fn write_answered_save(&mut self, ctx: &egui::Context, doc: DocId, path: String, settings: &ExportSettings, copy: bool, step: (&str, Value)) { + let written = self.with_document(doc, |app| app.write_document(path, settings, copy)); + if written.is_ok() { + self.session.journal.push((step.0.into(), step.1)); + } + match written { + Err(e) => { + self.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]); + self.ui.status_error = true; + } + Ok(Some(_)) if !copy => crate::discard_ui::saved_document(self, ctx, doc), + // A background save releases the close prompt when it finishes (`jobs_ui`). + Ok(_) => {} + } + } + + /// A print worker may still be handing a job to the system queue. + pub(crate) fn printing(&self) -> bool { + self.session.jobs().iter().any(|j| matches!(j.command.as_str(), "file.print" | "file.printOneCopy")) + } + + /// A save is running in the background. + pub(crate) fn saving(&self) -> bool { + !self.jobs.saves.is_empty() + } + + /// Save through the control session's capability-scoped writer. No file + /// picker or ambient writer is reachable from this path. Returns the path + /// written and the export warnings (also shown to the user). + pub fn save_automation(&mut self, path: Option) -> Result { + self.save_automation_with(path, FormatChoices::default()) + } + + /// [`Self::save_automation`] writing with the format `choices` given (a Targa's `None`: 32 + /// with an alpha channel or transparency, else 24; a DDS texture's: uncompressed without + /// mipmaps; a JPEG's: the file's own quality, Baseline). Automation saves never prompt. + pub fn save_automation_with(&mut self, path: Option, choices: FormatChoices) -> Result { + let target = { + let state = self.session.active().ok_or("no document")?; + // As File › Save: without `path` only a layered file is written back (#416). + path.or_else(|| state.path.clone().filter(|p| photocraft_engine::file_cmds::holds_at(&state.doc, p))).ok_or( + "pass `path`: a save without one writes back only to the document's own PSD, PSB, .pcraft or OpenRaster file, and to OpenRaster only when it holds everything (adjustment layers, styles and masks don't fit)", + )? + }; + let reply = |path: &str, warnings: &[String]| json!({"path": path, "warnings": warnings}); + // Only the target is granted: a linked smart object's stored path is document data, so + // PSD export writes that layer as pixels instead of embedding the file. + let settings = ExportSettings { read_linked_files: false, ..choices.apply(self.save_settings()) }; + // #2017: the File › Save worker path, so the encode doesn't block the frame loop. + if self.background_jobs + && let Some(save) = self.services.automation_save.clone() + { + return match jobs_ui::start_save(self, target.clone(), settings, false, save, true)? { + Some((path, warnings)) => Ok(reply(&path, &warnings)), + None => { + let job = self.jobs.last_started; + Ok(json!({"path": target, "job": job, "pending": true, "warnings": []})) + } + }; + } + let state = self.session.active().ok_or("no document")?; + let (doc, revision) = (state.doc.id, state.revision); + let export = self.services.export.as_ref().ok_or("no exporter configured")?; + let (bytes, warnings) = export(&state.doc, &target, &settings)?; + let write = self.services.automation_write.as_mut().ok_or("automation write authority is not configured")?; + write(&target, &bytes)?; + self.saved_automation(doc, revision, &target, &warnings, false); + Ok(reply(&target, &warnings)) + } + + pub(crate) fn drain_control(&mut self, ctx: &egui::Context) { + let Some(rx) = self.control_rx.take() else { return }; + while let Ok(req) = rx.try_recv() { + let reply = req.reply.clone(); + if req.deadline.is_some_and(|deadline| std::time::Instant::now() >= deadline) || !req.dispatch.start() { + let _ = reply.send(serde_json::json!({"ok": false, "error": control::expired_error()})); + continue; + } + match control::handle(self, ctx, &req) { + control::Outcome::Done(v) => { + let _ = reply.send(v); + } + control::Outcome::AfterInput => self.input_waiters.push(reply), + control::Outcome::AfterJob(job) => self.jobs.waiters.push((job, reply)), + control::Outcome::Screenshot { token, path } => { + // Admission is budgeted here, after this pass's completed captures were + // drained, so a just-finished request never causes a false rejection. + let settle = screenshot::settle_ms(ctx.global_style().animation_time); + let document = self.document_identity(); + if let Err((reply, e)) = self.captures.admit(token, path, reply, document, settle, screenshot::now()) { + let _ = reply.send(serde_json::json!({"ok": false, "error": e})); + } + } + } + // `ui.set` may have changed the edit target: the next request sees its colours. + self.sync_mask_targets(); + } + self.control_rx = Some(rx); + } + + /// The active document's identity at admission: a queued capture never applies to another + /// document. Includes the revision so a saved image is attributable to a known state. + pub(crate) fn document_identity(&self) -> Option { + self.session.active().map(|st| screenshot::DocumentId { document: st.doc.id.0, revision: st.revision, generation: self.session.active_generation() }) + } + + /// Issue due screenshot requests. UI phase only: settling counts real layout passes, and the + /// geometry epoch is that of the pass the image will be rendered from. + fn issue_captures(&mut self, ctx: &egui::Context) { + // A discarded pass (popup sizing, `request_discard`) will be re-run: capture only a pass + // whose UI state will actually be present. + if ctx.will_discard() { + return; + } + let now = screenshot::now(); + let doc = self.document_identity(); + let finished = self.captures.issue(ctx, now, doc, |callback| screenshot::send_command(ctx, callback)); + self.finish_captures(finished); + } + + /// Collect callbacks and expire requests. Logic phase; the image is encoded and written here, + /// on the UI thread, never inside the callback. + fn drain_captures(&mut self, ctx: &egui::Context) { + let now = screenshot::now(); + let doc = self.document_identity(); + // begin_pass supplies the new RawInput before App::logic; run_logic refreshes native + // viewport metadata too. Observe it before any completed callback can be delivered. + let current = screenshot::CaptureGeometry::current(ctx, doc); + self.captures.note_geometry(current); + let observed = self.captures.last_geometry(); + let finished = self.captures.drain(now, observed, doc); + self.finish_captures(finished); + } + + fn finish_captures(&mut self, finished: Vec) { + for f in finished { + let reply = match f.result { + Ok(image) => { + let [w, h] = image.size; + // The encoder takes RGBA bytes; its copy is bounded by the same per-image + // reservation as the retained image, and the image itself is released first. + match w.checked_mul(h).and_then(|n| n.checked_mul(4)) { + Some(bytes) if bytes <= screenshot::MAX_IMAGE_BYTES => { + let rgba: Vec = image.pixels.iter().flat_map(|c| c.to_array()).collect(); + drop(image); + control::save_screenshot_rgba(self, w, h, &rgba, f.path.as_deref()) + } + _ => serde_json::json!({ + "ok": false, + "error": format!( + "screenshot {} failed: the image exceeds the {} MiB encode budget", + f.token, + screenshot::MAX_IMAGE_BYTES / (1 << 20) + ), + }), + } + } + Err(e) => serde_json::json!({"ok": false, "error": e}), + }; + if let Some(tx) = f.reply { + let _ = tx.send(reply); + } + } + } +} + +impl PhotocraftApp { + /// Wait out the rest of [`Self::min_frame_ms`] since the last frame started. + fn cap_frame_rate(&mut self) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(min) = self.min_frame_ms.filter(|m| m.is_finite() && *m > 0.0) { + let wait = min.min(100.0) - (gpu_canvas::now_ms() - self.last_frame_start_ms); + if wait > 0.0 { + std::thread::sleep(std::time::Duration::from_secs_f64(wait / 1000.0)); + } + } + self.last_frame_start_ms = gpu_canvas::now_ms(); + } +} + +impl PhotocraftApp { + /// Install the callback-mode markers in an app creator, before the first `run_ui` on this + /// Context (and again through [`Self::setup_context`] when a host replaces its Context). + /// Installing while a pass is already running cannot mark that pass; it only arms the next. + pub fn install_type_reset_hooks(ctx: &egui::Context) { + type_tool::install_reset_hooks(ctx); + } + + /// The host's UI tail, after all panels and any shell-side model/focus mutations. + pub fn finish_type_reset_pass(&mut self, ctx: &egui::Context) { + type_tool::finish_reset_pass(self, ctx); + } + + /// The host's logic tail; full UI passes leave availability to their later UI tail. + pub fn finish_type_reset_logic(&mut self, ctx: &egui::Context) { + type_tool::finish_reset_logic(self, ctx); + } + + /// Shared logic body. A wrapping host owns the final reset tail after its own work. + pub fn logic_frame(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { + self.cap_frame_rate(); + i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language)); + // Caps Lock state read from the OS once per frame (see `Services::caps_lock`): the canvas + // cursor block needs it before the frame renders. `None` (Wayland/web) keeps `false`. + self.caps_lock = self.services.caps_lock.as_mut().is_some_and(|f| f()); + tool_cursor::set_wayland(ctx, self.services.is_wayland); + if !self.styled { + Self::setup_context(ctx, self.ui.theme); + self.styled = true; + } else { + self.fonts_ready = true; + } + self.frame += 1; + let now = ctx.input(|i| i.time); + let dt = (now - self.last_frame_time) as f32; + if dt > 0.0 { + self.fps = self.fps * 0.9 + (1.0 / dt).min(240.0) * 0.1; + } + self.last_frame_time = now; + self.sync_views(); + crate::type_font_preview::follow_hover(self, ctx); + self.check_gpu(ctx); + #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] + if self.live_tokens.poll(ctx, self.ui.theme) { + self.checker = None; + } + // Finish or expire outstanding captures first, so a new request admitted in this pass + // sees their released budget. + self.drain_captures(ctx); + self.drain_control(ctx); + native_menu::run(self, ctx); + // Switching tools commits, also between the Type and Type Mask tools. + if self.ui.text_edit.as_ref().is_some_and(|ed| !self.ui.tool.is_type() || ed.mask != self.ui.tool.is_type_mask()) { + type_tool::commit(self); + } + // So does selecting another layer or document by any route (#6483). + type_tool::end_if_left(self); + if self.ui.pen.as_ref().is_some_and(|p| !p.drawn_with(self.ui.tool)) { + vector_ui::pen_commit(self, false); + } + transform_tool::end_if_left(self); + shape_stroke_ui::sync_editor(self, ctx); + prefs_ui::tick(self, ctx); + updates_ui::tick(self, ctx); + monitor_status::poll_frame(self, ctx, frame); + // Control requests and persisted preferences can change the language in this frame. + i18n::sync_context(ctx, &self.session.prefs().interface.language); + type_tool::sync_font_names(ctx, self.session.prefs().type_.show_font_names_in_english); + // A window bigger than its display (1440 × 900 on 1366 × 768) runs under the taskbar: + // maximize it into the work area once (#315). + work_area::fit_window(ctx); + discard_ui::guard_window_close(self, ctx); + // Background jobs: apply finished ones, keep frames coming, Esc cancels (before the + // shortcuts see Esc). + if !screen_picker::tick(self, ctx) { + jobs_ui::tick(self, ctx); + #[cfg(not(target_arch = "wasm32"))] + filter_preview_worker::discard_closed(self); + if type_tool::in_ui_pass(ctx) { + if self.fonts_ready { + shortcuts::handle(self, ctx); + } else { + type_tool::controls_only(self, ctx); + } + } + } + let arrived: Vec<(String, Vec)> = + self.services.inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default(); + for (name, bytes) in arrived { + if let Err(e) = self.open_bytes(&name, &bytes) { + self.open_failed(&name, &e); + } + } + // Web drops onto the canvas, read since the last frame: placed below, one at a time. + let to_place: Vec<(String, Vec)> = + self.services.place_inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default(); + self.drop_places.extend(to_place.into_iter().map(|(name, bytes)| file_open::DropPlace::Bytes(name, bytes))); + // Finder double-click / Open With / Dock drops (macOS open-documents events). + self.drain_os_events(ctx); + // While files are dragged over the window it gets no pointer events: keep frames coming so + // the tab strip can follow the pointer. + if ctx.input(|i| !i.raw.hovered_files.is_empty()) { + ctx.request_repaint(); + } + let dropped = ctx.input(|i| i.raw.dropped_files.clone()); + if !dropped.is_empty() { + let at = self.services.cursor_pos.as_mut().and_then(|f| f(ctx)); + self.open_dropped(ctx, dropped, at); + // Files dragged in from another app's window: PhotoCraft comes to the front and takes + // the keyboard, as Photoshop does, instead of staying behind the source (#5687). + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + } + self.place_next_dropped(ctx); + // The control transport wakes the UI on arrival (ctx.request_repaint); only poll while a + // screenshot is pending. (Polling every 50 ms here made idle apps render at 20 fps.) + if self.captures.any_pending() { + ctx.request_repaint_after(std::time::Duration::from_millis(16)); + } + // A hidden host runs no UI pass: a queued (or re-queued) capture asks for one. An issued + // capture's own `Screenshot` command forces its paint; asking again would spin a hidden + // window while a slow readback is in flight. Synthetic input queued during hidden ticks + // needs the same wake: its events sit in eframe's preserved input until a UI pass. + if self.captures.any_unissued() || self.synthetic_batch.is_some() || !self.synthetic.is_empty() { + ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden); + } + self.poll_file_dialog(ctx, Some(frame)); + } + + /// Shared UI body. A wrapping host must call `finish_type_reset_pass` after return, + /// including when this body returns early without drawing an editor. + pub fn ui_frame(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + let ctx = ui.ctx().clone(); + // One control owner even when this callback cannot draw the custom editor. + if !self.fonts_ready + || !self.ui.dialogs.is_empty() + || screen_picker::busy(&ctx) + || self.ui.text_edit.is_none() + || ctx.text_edit_focused() + || ctx.egui_wants_keyboard_input() + { + type_tool::controls_only(self, &ctx); + } + // 0.36 saved panel sizes under `Id::unique(name)`; 0.37 reads parent-scoped keys. Data-only, + // so it runs even before fonts are ready; the old keys stay for a 0.36 rollback. + panels::migrate_panel_state(&ctx); + // A real UI pass, not a hidden `run_logic` tick: record the capture geometry (the + // document identity included) and count one settling pass. `run_logic` leaves these + // input values stale; only this real UI phase counts toward settling. + let geometry = screenshot::CaptureGeometry::current(&ctx, self.document_identity()); + self.captures.note_geometry(geometry); + self.captures.note_pass(); + // A real UI pass consumes the one in-flight synthetic batch (see `inject_synthetic`). + self.begin_synthetic_pass(&ctx); + self.hover_layer = None; + i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language)); + // Fonts registered via set_fonts only take effect next frame; named families would panic now. + if !self.fonts_ready { + // egui consumed this pass's input without PhotoCraft handling it: keep the synthetic + // batch for the next pass instead of losing the step. + self.defer_synthetic_pass(); + ctx.request_repaint(); + self.automation_input = false; + // No editor was drawn this pass: end its IME context rather than keep a stale owner. + type_tool::sync_ime(self, &ctx); + return; + } + let t0 = gpu_canvas::now_ms(); + self.perf.frame_refresh_ms = 0.0; + self.stroke_trace.cpu_prev(frame.info().cpu_usage); + // A text field's right-click menu, before any field is drawn (text_field_menu.rs). + text_field_menu::show(&ctx); + // The wheel goes to a focused value field before the canvas or a panel sees it (#5473). + field_wheel::begin_frame(&ctx); + // Each painting tool keeps its own brush (#218), so switch the active tool's brush in + // before anything this frame reads it (the cursor, the options bar, a stroke). + // Preferences ▸ Type ▸ Recent Fonts: a smaller cap (or 0) trims the existing list at + // once, not only after the next pick. + self.sync_recent_fonts(); + paint_mouse::sync_tool_brush(self); + // A unit typed into a value field (`1in` in a px field) converts at the active document's + // resolution, as in Photoshop. + let ppi = self.session.prefs().units_and_rulers.point_size.per_inch(); + let dpi = self.session.active().map_or(72.0, |d| f64::from(d.doc.resolution_dpi.max(1.0))); + crate::widgets::set_field_resolution(&ctx, dpi, ppi); + // View › Screen Mode › Full Screen Mode: only the image, on black (F or Esc returns). + screen_picker::show(&ctx); + if screen_picker::busy(&ctx) && screen_picker::showing(&ctx) { + egui::Modal::new(egui::Id::unique("screen-color-wait")).show(&ctx, |ui| { + ui.spinner(); + ui.label(tl!("Pick a screen pixel or press Esc to cancel")); + if ui.button(tl!("Cancel")).clicked() { + screen_picker::cancel(&ctx); + } + }); + // This pass handled its input (the modal above ran): deliver the synthetic batch. + self.finish_synthetic_pass(); + self.automation_input = false; + type_tool::sync_ime(self, &ctx); + gpu_status::check_window(self, &ctx); + return; + } + if screen_picker::busy(&ctx) { + ui.disable(); + ui.set_opacity(1.0); + } + // The OS title bar (and the taskbar / Alt-Tab entry) follows the active file; with the + // system title bar this is where the document name lives, as the in-app title is hidden. + panels::sync_window_title(self, &ctx); + let chrome = !self.ui.view.hides_chrome(); + if chrome { + self.ui.panels.full_screen_chrome = false; + } + // In Full Screen Mode, Tab shows the menu bar, options bar, toolbar and dock (#6760). + let tabbed_in = !chrome && self.ui.panels.full_screen_chrome; + if (chrome || tabbed_in) && self.ui.panels.menu_bar { + panels::title_bar(self, ui); + } + if (chrome && self.ui.panels.options_bar) || tabbed_in { + panels::options_bar(self, ui); + } + if chrome && self.ui.panels.status_bar { + panels::status_bar(self, ui); + } + if (chrome && self.ui.panels.toolbar) || tabbed_in { + panels::toolbar(self, ui); + } + // craft-ui's layout holds the canvas as its protected `canvas` panel. + let docking = (chrome && self.ui.panels.dock) || tabbed_in; + 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); + }); + panels::properties_window(self, &ctx); + } + brush_panel::window(self, &ctx); + preset_panels::windows(self, &ctx); + gradient_ui::editor_window(self, &ctx); + type_panels_ui::windows(self, &ctx); + analysis_ui::windows(self, &ctx); + timeline_ui::windows(self, &ctx); + workspace_ui::windows(self, &ctx); + palette::show(self, &ctx); + dialogs::show(self, &ctx); + layers_panel_ui::show_dialog(self, &ctx); + rasterize_prompt::run_pending(self, &ctx); + jobs_ui::dialog(self, &ctx); + discard_ui::show(self, &ctx); + tiff_options_ui::show(self, &ctx); + targa_options_ui::show(self, &ctx); + jpeg_options_ui::show(self, &ctx); + dds_options_ui::show(self, &ctx); + distort_ui::show(self, &ctx); + camera_raw_ui::show(self, &ctx); + wide_angle_ui::show(self, &ctx); + canvas::extra_windows(self, &ctx); + notices::show(self, &ctx); + updates_ui::show(self, &ctx); + gpu_status::show_fallback(self, &ctx); + kys_import::show_offer(self, &ctx); + if self.titlebar_modal_drag(chrome) { + titlebar::modal_drag_overlay(&ctx); + } + if self.custom_titlebar { + titlebar::resize_zones(ui); + } + // A device lost while drawing this frame: switch to the CPU canvas before the next one. + gpu_status::check(self, &ctx); + // The Brush Preset picker's view (its gear's card parts and the footer scale) is + // remembered once the pointer is up. Here, after every panel, rather than in the + // picker's own code: the control channel can set it while the picker is closed. + brush_picker::persist(self, &ctx); + // The tool's brush (settings and tip references) is remembered the same way. Like the + // picker's view, in the frame loop, so the control channel can set it with the panels + // closed; the engine's revision counter keeps an unchanged brush free. + last_brush::persist(self, &ctx); + // Tool options are remembered between launches the same way (#2814). + tool_memory::persist(self, &ctx); + // So are View › Extras, Show and Snap To (#3762). + view_cmds::persist(self, &ctx); + // Remember the 0.37 panel sizes so a later 0.36 rollback's newer old-key values win on + // the next upgrade (see `panels::migrate_panel_state`). + panels::remember_panel_state(&ctx); + self.automation_input = false; + shape_stroke_ui::finish_frame(self, &ctx); + native_menu::sync(self, &ctx); + if screen_picker::busy(&ctx) { + // Block input without a backdrop: the worker may still be capturing the screen. + egui::Modal::new(egui::Id::unique("screen-color-wait")).frame(egui::Frame::NONE).backdrop_color(egui::Color32::TRANSPARENT).show(&ctx, |_| {}); + ctx.set_cursor_icon(egui::CursorIcon::Wait); + } + let ui_ms = gpu_canvas::now_ms() - t0; + // A GPU measurement lands a frame or two after the refresh it belongs to. Refreshes + // carry them out, but the last refresh before the app settles has none following it, so + // drain the timer here too or its number is never reported. Drain it either way: a + // measurement left sitting would surface later against an unrelated refresh. Report it + // only while the canvas is still on the GPU, since a CPU refresh clears `gpu_ms` + // precisely so a GPU number is never shown as that refresh's. + if let Some(gpu) = &self.gpu + && let Some(t) = gpu.take_gpu_timing() + && self.perf.last_refresh.starts_with("gpu") + { + self.perf.record_gpu(t); + } + self.perf.frame(ui_ms); + if self.stroke_trace.enabled() { + self.stroke_trace.canvas(self.perf.frame_refresh_ms); + let info = &self.perf.gpu_info; + self.stroke_trace.end_frame(ui_ms, self.live_stroke.is_some(), || { + let gpu = format!("{} {}", info.backend, info.adapter).trim().to_string(); + if info.present.is_empty() { gpu } else { format!("{gpu}, {}", info.present) } + }); + } + // This pass handled its input: the in-flight synthetic batch is delivered once and the + // next step may be injected on the next frame. + self.finish_synthetic_pass(); + // Synthetic input is injected one press/release step per frame: keep frames coming until + // the queue is empty, then release control replies waiting on it. + // Only a pass that reached the end of the UI and delivered the in-flight batch counts as + // settled input; an early-returning pass keeps the batch (and the waiting replies). + if !self.synthetic.is_empty() || self.synthetic_batch.is_some() { + ctx.request_repaint(); + } else if !self.input_waiters.is_empty() { + for w in self.input_waiters.drain(..) { + let _ = w.send(serde_json::json!({"ok": true, "result": null})); + } + } + // A menu or dialog can start a filter after `jobs_ui::tick` ran in this frame. Keep + // polling it even when the platform would otherwise put the event loop to sleep. + jobs_ui::keep_polling(self, &ctx); + // Menus and buttons in this frame may have asked for a file dialog. + self.poll_file_dialog(&ctx, Some(frame)); + // The Type tool's IME descriptor is the last writer of this pass: every panel and the + // canvas have finished mutating the model, and an absent/focus-moved editor ends here. + type_tool::sync_ime(self, &ctx); + // Issue any due `ui.screenshot` now that this pass's state is settled: a queued request + // that has waited its passes and animation delay captures exactly this frame. + self.issue_captures(&ctx); + // Last, after everything drawn this frame: a lost window device can't draw it (#3438). + gpu_status::check_window(self, &ctx); + } +} + +impl eframe::App for PhotocraftApp { + fn on_exit(&mut self) { + if let Err(err) = tool_memory::save_on_exit(self) { + log::warn!("Preferences: could not save the final tool selection: {err}"); + } + // Release a pending screenshot's image budget and answer its control request; the + // callback is inert afterwards (it holds only a weak slot). + let finished = self.captures.cancel_all("the application is closing"); + self.finish_captures(finished); + } + + fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { + self.logic_frame(ctx, frame); + self.finish_type_reset_logic(ctx); + } + + fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) { + let frame_start = gpu_canvas::now_ms(); + // An undecorated window gets its caption back when the toolkit changes its flags + // (maximize, restore, …): take it off again before the frame is laid out (#2246). + if let Some(window_frame) = self.services.window_frame.as_mut() { + window_frame(); + } + // Native menu key equivalents become the key presses they were (see `native_menu`). + if let Some(menu) = self.services.native_menu.as_mut() { + menu.raw_input(raw_input); + } + // While a text field of a floating panel's own window has the keyboard, the dock area + // hands that window the text keys in this input and converts them there. + if craft_ui::docking::typing_window(ctx).is_none() { + shortcuts::clipboard_keys(ctx, ctx.text_edit_focused() || self.ui.text_edit.is_some(), raw_input); + } + // Windows precision touchpads and some Linux Wayland compositors send pinches + // as fractional Ctrl + wheel rather than a native Zoom event (#4566). + // Leave Ctrl+whole-notch mouse scrolling alone, and honour the pinch preference. + if cfg!(any(target_os = "windows", target_os = "linux")) && self.session.prefs().enhanced_controls.zoom_with_trackpad_pinch { + wheel_nav::fold_legacy_pinch(ctx, raw_input); + } + self.inject_synthetic(ctx, raw_input); + // After the control channel's own events (`ui.type`) join the OS's, before any widget. + widgets::cap_text_events(&mut raw_input.events); + self.control_click.normalize(&mut raw_input.events, cfg!(target_os = "macos")); + // A pen held still is no touch screen's press-and-hold right click (stylus.rs). + let pen_down = self.stylus.pen_contacts.observe(&raw_input.events); + stylus::pen_hold_is_no_right_click(ctx, pen_down); + if self.custom_titlebar { + titlebar::release_after_os_resize(ctx, raw_input); + } + if self.stroke_trace.enabled() { + // The OS's moves and the control channel's (injected just above). + let moves = raw_input.events.iter().filter(|e| matches!(e, egui::Event::PointerMoved(_))).count(); + self.stroke_trace.begin_frame(frame_start, moves); + } + } + + fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + self.ui_frame(ui, frame); + self.finish_type_reset_pass(ui.ctx()); + } +} + +/// Remove one contiguous run equal to `batch` from `events` (eframe's preserved synthetic +/// input). A no-op when the run is not present. +fn remove_event_run(events: &mut Vec, batch: &[egui::Event]) { + if batch.is_empty() || batch.len() > events.len() { + return; + } + if let Some(pos) = events.windows(batch.len()).position(|w| w == batch) { + events.drain(pos..pos + batch.len()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_dropped(f: &(dyn egui::DroppedFile + Send + Sync)) -> Result, String> { + f.bytes() +} + +/// The active layer is an adjustment layer. It has no pixels, so painting and filling it edit its +/// mask even when its icon thumbnail, not the mask, is the Layers panel's target, as in +/// Photoshop (#4298). +pub(crate) fn adjustment_layer_active(st: &photocraft_engine::DocState) -> bool { + st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| matches!(l.content, photocraft_doc::LayerContent::Adjustment(_))) +} + +/// On the web, dropped-file bytes arrive asynchronously; the web shell handles drops itself. +#[cfg(target_arch = "wasm32")] +fn read_dropped(_f: &dyn egui::DroppedFile) -> Result, String> { + Err("drag-and-drop on the web is handled by the page; use File → Open".into()) +} + +impl PhotocraftApp { + /// Whether the title bar's free gap gets the drag overlay this frame: the app draws its title + /// strip (`chrome`: not hidden by the screen mode) and a dialog's modal layer covers it. Not + /// only with the custom title bar: on macOS the strip under the traffic lights is the window's + /// title bar too, and an open dialog (Embedded Profile Mismatch…) left it undraggable (#5826). + pub(crate) fn titlebar_modal_drag(&self, chrome: bool) -> bool { + chrome && self.ui.panels.menu_bar && !self.ui.dialogs.is_empty() + } + + /// `params` aimed at the active layer's mask (`"target":"mask"`) when the Layers panel targets + /// it and command `id` edits the target (adjustments, filters, fills) without naming one: + /// ⌘I then inverts the mask, as in Photoshop (#780). A targeted alpha channel or Quick Mask + /// mode wins, as the engine routes those itself. + pub fn with_mask_target(&self, id: &str, params: Value) -> Value { + if !photocraft_engine::channel_cmds::follows_target(id) || params.get("target").is_some() { + return params; + } + // A filter mask is painted, filled and filtered in place; it doesn't float or move, and + // Edit › Transform, Apply Image and the dialog filters act on the smart object. + let target = if self.filter_mask_targeted() && photocraft_engine::channel_cmds::follows_filter_mask(id) { + "filterMask" + } else if self.layer_mask_targeted() { + "mask" + } else { + return params; + }; + match params { + Value::Object(mut m) => { + m.insert("target".into(), Value::from(target)); + Value::Object(m) + } + _ => serde_json::json!({ "target": target }), + } + } + + /// The Layers panel targets the active smart object's filter mask (FILE-215-3), and no alpha + /// channel or Quick Mask takes over. + pub fn filter_mask_targeted(&self) -> bool { + let Some(st) = self.session.active() else { return false }; + let Some(id) = st.active_layer.filter(|id| self.ui.filter_mask_target == Some(id.0)) else { return false }; + let composite = st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::Composite && st.doc.quick_mask.is_none(); + composite && st.doc.layer(id).is_some_and(|l| matches!(&l.content, photocraft_doc::LayerContent::Smart(sm) if !sm.smart_filters.is_empty())) + } + + /// The active layer's mask is what pixel commands edit: the Layers panel targets it, the layer + /// is an adjustment layer (no pixels of its own), or every colour channel is off and that mask + /// is the picture. An alpha channel or Quick Mask wins, as the engine routes those itself. + pub fn layer_mask_targeted(&self) -> bool { + let Some(st) = self.session.active() else { return false }; + let layer_mask = st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::LayerMask; + let composite = (st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::Composite || layer_mask) && st.doc.quick_mask.is_none(); + let has_mask = st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.mask.is_some()); + if !composite || !has_mask { + return false; + } + if self.ui.mask_target || layer_mask || adjustment_layer_active(st) { + return true; + } + let colors_off = st.channel_view.visible_colors(photocraft_engine::channel_cmds::color_count(&st.doc)) == 0; + let alpha_on = (0..st.doc.channels.len()).any(|i| st.channel_view.alpha_shown(i)); + colors_off && !alpha_on + } + + /// Targeting the pixels, the layer mask or the vector mask ends a shown filter mask (⌥-click + /// on its thumbnail): while it shows, [`Self::sync_mask_targets`] keeps the filter mask + /// targeted, so strokes would keep landing there. + pub(crate) fn end_filter_mask_view(&mut self) { + let Some(v) = self.session.active().and_then(photocraft_engine::mask_view_cmds::current).filter(|v| v.filter) else { return }; + let off = serde_json::json!({"layer": v.layer.0, "mode": "off", "mask": "filter"}); + if let Err(err) = self.session.execute(photocraft_engine::mask_view_cmds::ID, off) { + log::warn!("could not end the filter mask view: {err}"); + } + } + + /// Explicitly targeting a filter mask ends any conflicting mask view; untargeting it ends its + /// own view too. + pub(crate) fn select_filter_mask_target(&mut self, layer: Option) { + if layer.is_none() { + self.end_filter_mask_view(); + } + if layer.is_some() { + if let Some(st) = self.session.active_mut() { + if st.channel_view.layer_mask.is_some_and(|v| !v.filter || Some(v.layer.0) != layer) { + st.channel_view.layer_mask = None; + } + if matches!( + st.channel_view.target, + photocraft_engine::channel_cmds::ChannelTarget::LayerMask | photocraft_engine::channel_cmds::ChannelTarget::VectorMask + ) { + st.channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Composite; + } + } + self.ui.mask_target = false; + self.ui.vector_mask_target = false; + } + self.ui.filter_mask_target = layer; + self.sync_mask_targets(); + } + + /// Viewing a layer mask (#196) targets it; a vector-mask target needs a vector mask on the + /// active layer (a shape layer's path is its content, not a mask). Targeting a mask or the + /// pixels brings back that target's foreground/background pair, as in Photoshop (#2166). + pub(crate) fn sync_mask_targets(&mut self) { + if let Some(st) = self.session.active_mut() { + use photocraft_engine::channel_cmds::ChannelTarget; + let channel = st.channel_view.target; + match photocraft_engine::mask_view_cmds::current(st) { + Some(v) if v.filter => { + self.ui.filter_mask_target = Some(v.layer.0); + self.ui.mask_target = false; + self.ui.vector_mask_target = false; + } + Some(_) => { + self.ui.mask_target = true; + self.ui.vector_mask_target = false; + self.ui.filter_mask_target = None; + } + None if channel == ChannelTarget::LayerMask => { + self.ui.mask_target = true; + self.ui.vector_mask_target = false; + } + None if channel == ChannelTarget::VectorMask => { + self.ui.vector_mask_target = true; + self.ui.mask_target = false; + } + None => {} + } + if self.ui.mask_target || self.ui.vector_mask_target { + self.ui.filter_mask_target = None; + } + if self.ui.vector_mask_target && !mask_thumbs_ui::has_vector_mask(st) { + self.ui.vector_mask_target = false; + } + if self.ui.mask_target && st.active_layer.and_then(|id| st.doc.layer(id)).is_none_or(|l| l.mask.is_none()) { + self.ui.mask_target = false; + } + if !self.ui.mask_target && st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::LayerMask { + st.channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Composite; + } + if !self.ui.mask_target || self.ui.properties_layer != st.active_layer.map(|l| l.0) { + self.ui.properties_layer = None; + } + } + if self.ui.filter_mask_target.is_some() && !self.filter_mask_targeted() { + self.ui.filter_mask_target = None; + } + let mask = self.layer_mask_targeted() || self.filter_mask_targeted(); + self.session.tools.target_mask(mask); + } + + fn prune_thumbs(&mut self) { + let documents = self.session.documents(); + if self.thumb_documents.len() == documents.len() + && self.thumb_documents.iter().zip(documents).all(|((id, snapshot), st)| *id == st.doc.id && snapshot.ptr_eq(&std::sync::Arc::downgrade(&st.doc))) + { + return; + } + // Check snapshots every sync, but walk the layer tree only after it changes. A Weak + // tracks replacement (including undo and preserved-ID reopen) without retaining pixels. + if !self.thumbs.is_empty() { + let mut live = std::collections::HashSet::new(); + let mut pending: Vec<_> = documents.iter().flat_map(|st| &st.doc.layers).collect(); + while let Some(layer) = pending.pop() { + live.insert((layer.id, mask_thumbs_ui::THUMB_LAYER)); + if layer.mask.is_some() { + live.insert((layer.id, mask_thumbs_ui::THUMB_MASK)); + } + if layer.vector_mask.is_some() { + live.insert((layer.id, mask_thumbs_ui::THUMB_VECTOR)); + } + if matches!(&layer.content, photocraft_doc::LayerContent::Smart(sm) if sm.filter_mask.is_some()) { + live.insert((layer.id, mask_thumbs_ui::THUMB_SMART_MASK)); + } + if let Some(children) = layer.children() { + pending.extend(children); + } + } + // Native files can restore IDs: retain the union across all open documents, rather + // than deleting an ID just because one document containing it was closed. + self.thumbs.retain(|key, _| live.contains(key)); + self.thumb_frames.retain(|id, _| live.contains(&(*id, mask_thumbs_ui::THUMB_LAYER))); + } + self.thumb_documents = documents.iter().map(|st| (st.doc.id, std::sync::Arc::downgrade(&st.doc))).collect(); + } + + pub fn set_theme(&mut self, ctx: &egui::Context, kind: theme::ThemeKind) { + if let Err(e) = self.run("prefs.set", serde_json::json!({"path": "interface.theme", "value": kind.id()})) { + self.ui.status = e; + } else { + self.apply_theme(ctx, kind); + } + } + + pub(crate) fn apply_theme(&mut self, ctx: &egui::Context, kind: theme::ThemeKind) { + // Color and Swatches trade indices between Pro and Studio layouts. + if let Some(selected) = dock::Group::Color.tabs(theme::Tokens::for_kind(self.ui.theme).pro).get(self.ui.dock_tabs.color) + && let Some(tab) = dock::Group::Color.tabs(theme::Tokens::for_kind(kind).pro).iter().position(|name| name == selected) + { + self.ui.dock_tabs.color = tab; + } + self.ui.theme = kind; + panel_docking::sync_visibility(self); + theme::apply(ctx, kind); + self.checker = None; + } + + /// Cached 64px thumbnail of a pixel-ish layer, letterboxed in a square, and the document + /// area it frames: the canvas, or with Clip Thumbnails to Layer Bounds the layer's pixels. + pub fn layer_thumb(&mut self, ctx: &egui::Context, doc: &Document, layer: &photocraft_doc::Layer) -> (egui::TextureId, photocraft_geom::Rect) { + let clip = self.session.prefs().interface.clip_thumbnails_to_layer_bounds; + // Key by content, not document revision: COW tiles change pointer only when their pixels + // change, so unrelated edits (e.g. painting another layer) don't rebuild this thumbnail. + let rev = layer.surface().map_or(0, surface_fingerprint) ^ (doc.size.width as u64) << 40 ^ u64::from(clip) << 63; + let key = (layer.id, mask_thumbs_ui::THUMB_LAYER); + if let Some((r, tex)) = self.thumbs.get(&key) + && *r == rev + && let Some(frame) = self.thumb_frames.get(&layer.id) + { + return (tex.id(), *frame); + } + let canvas = doc.bounds(); + let frame = layer_thumb_frame(layer, canvas, clip); + let mut px = [0.0f32; 8]; + let img = thumb_image(frame, 64, |x, y| { + let Some(s) = layer.surface() else { return [0.0; 4] }; + let n = s.channels(); + s.read_pixel(x, y, &mut px[..n]); + photocraft_raster::to_rgba(&s.format(), &px[..n]) + }); + self.thumb_frames.insert(layer.id, frame); + (self.store_thumb(ctx, key, rev, img), frame) + } + + /// The History panel thumbnail of snapshot `snap` of document `doc` (#2966): its composite, + /// centred in a square. Thumbnails of `doc`'s snapshots not in `live` are dropped. + pub fn snapshot_thumb(&mut self, ctx: &egui::Context, doc: DocId, snap: &photocraft_engine::history_cmds::Snapshot, live: &[u64]) -> egui::TextureId { + self.snapshot_thumbs.retain(|(d, id), _| *d != doc || live.contains(id)); + if let Some(tex) = self.snapshot_thumbs.get(&(doc, snap.id)) { + return tex.id(); + } + let comp = photocraft_compose::thumbnail(&snap.doc, 56); + let (w, h) = (comp.width as usize, comp.height as usize); + let side = w.max(h); + let (ox, oy) = ((side - w) / 2, (side - h) / 2); + let mut px = vec![egui::Color32::TRANSPARENT; side * side]; + for (i, &[r, g, b, a]) in comp.pixels.as_chunks::<4>().0.iter().enumerate() { + if let Some(out) = px.get_mut((i / w + oy) * side + i % w + ox) { + *out = egui::Color32::from_rgba_unmultiplied(r, g, b, a); + } + } + let tex = ctx.load_texture(format!("snapshot-{}", snap.id), egui::ColorImage::new([side, side], px), egui::TextureOptions::LINEAR); + let id = tex.id(); + self.snapshot_thumbs.insert((doc, snap.id), tex); + id + } + + /// The cached thumbnail of `mask`, the layer mask of layer `id`. + pub fn mask_thumb(&mut self, ctx: &egui::Context, doc: &Document, id: photocraft_doc::LayerId, mask: &photocraft_doc::LayerMask) -> egui::TextureId { + self.mask_thumb_kind(ctx, doc, id, mask, mask_thumbs_ui::THUMB_MASK) + } + + /// The thumbnail of `mask` under cache `kind`, re-rendered only when the mask's pixels or the document size change; Smart Filter and layer masks are cached apart. + pub(crate) fn mask_thumb_kind( + &mut self, + ctx: &egui::Context, + doc: &Document, + id: photocraft_doc::LayerId, + mask: &photocraft_doc::LayerMask, + kind: u8, + ) -> egui::TextureId { + let rev = surface_fingerprint(&mask.surface) ^ (doc.size.width as u64) << 40 ^ (doc.size.height as u64) << 16; + let key = (id, kind); + if let Some((r, tex)) = self.thumbs.get(&key) + && *r == rev + { + return tex.id(); + } + let mut v = [0.0f32; 1]; + let img = thumb_image(doc.bounds(), 64, |x, y| { + mask.surface.read_pixel(x, y, &mut v); + [v[0], v[0], v[0], 1.0] + }); + self.store_thumb(ctx, key, rev, img) + } + + pub(crate) fn store_thumb(&mut self, ctx: &egui::Context, key: (photocraft_doc::LayerId, u8), rev: u64, img: egui::ColorImage) -> egui::TextureId { + match self.thumbs.get_mut(&key) { + Some((r, tex)) => { + tex.set(img, egui::TextureOptions::LINEAR); + *r = rev; + tex.id() + } + None => { + let tex = ctx.load_texture(format!("thumb-{}-{}", key.0.0, key.1), img, egui::TextureOptions::LINEAR); + let id = tex.id(); + self.thumbs.insert(key, (rev, tex)); + id + } + } + } +} + +/// Cheap identity of a surface's pixels: its default (untouched) pixel, tile coordinates and +/// `Arc` pointers. The default pixel matters: inverting or filling a tile-less mask only changes +/// it (#2117). +pub fn surface_fingerprint(s: &photocraft_raster::Surface) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ s.tile_count() as u64; + for &b in s.default_bytes() { + h = (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3); + } + for (c, t) in s.tiles() { + let p = std::sync::Arc::as_ptr(t) as usize as u64; + h = (h ^ p ^ ((c.tx as u64) << 32 | c.ty as u32 as u64)).wrapping_mul(0x100_0000_01b3); + } + h +} + +/// The document area a layer thumbnail frames: the canvas, or with `clip` the layer's pixels on +/// it (the canvas again when it has none there, so an empty layer still shows the page shape). +pub(crate) fn layer_thumb_frame(layer: &photocraft_doc::Layer, canvas: photocraft_geom::Rect, clip: bool) -> photocraft_geom::Rect { + if !clip { + return canvas; + } + let bounds = layer.surface().map_or(photocraft_geom::Rect::EMPTY, photocraft_compose::bounds::content_bounds).intersect(&canvas); + if bounds.is_empty() { canvas } else { bounds } +} + +/// Square thumbnail of the document area `frame`, letterboxed, sampling `f(x, y)` in document +/// space. +fn thumb_image(frame: photocraft_geom::Rect, side: usize, mut f: impl FnMut(i32, i32) -> [f32; 4]) -> egui::ColorImage { + let (w, h) = (frame.width().max(1) as f32, frame.height().max(1) as f32); + let scale = w.max(h) / side as f32; + let (ox, oy) = ((side as f32 - w / scale) / 2.0, (side as f32 - h / scale) / 2.0); + let mut px = vec![egui::Color32::TRANSPARENT; side * side]; + for ty in 0..side { + for tx in 0..side { + let dx = (tx as f32 - ox + 0.5) * scale; + let dy = (ty as f32 - oy + 0.5) * scale; + if dx < 0.0 || dy < 0.0 || dx >= w || dy >= h { + continue; + } + let c = f(frame.x0.saturating_add(dx as i32), frame.y0.saturating_add(dy as i32)); + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + px[ty * side + tx] = egui::Color32::from_rgba_unmultiplied(q(c[0]), q(c[1]), q(c[2]), q(c[3])); + } + } + egui::ColorImage::new([side, side], px) +} + +impl PhotocraftApp { + /// The document/focus identity the in-flight synthetic batch was queued for. + fn synthetic_target(&self, ctx: &egui::Context) -> SyntheticTarget { + SyntheticTarget { document: self.document_identity(), focus: ctx.memory(|m| m.focused()) } + } + + fn synthetic_target_matches(&self, ctx: &egui::Context) -> bool { + self.synthetic_snapshot.is_some_and(|queued| queued.matches(self.synthetic_target(ctx))) + } + + /// Put at most one queued synthetic batch into this pass's input. + /// + /// The batch is appended once and tracked; `begin_pass` consumes it. While it is in flight no + /// further step is drained, so hidden logic ticks cannot accumulate several batches into one + /// pass. A document or focus change observed here is before eframe consumes the events, so the + /// batch is dropped and its waiting control replies fail instead of landing somewhere else. + /// If a pass consumed it but PhotoCraft returned before handling input (fonts not ready), the + /// same batch is appended again on the next hook, exactly once. + pub(crate) fn inject_synthetic(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) { + if self.synthetic_batch.is_some() { + if !self.synthetic_target_matches(ctx) { + // eframe may already carry the batch in its preserved input: withdraw exactly + // those events before the host consumes them, then fail the waiting replies. + if let Some(batch) = self.synthetic_batch.as_ref() { + remove_event_run(&mut raw_input.events, batch); + } + self.cancel_synthetic("the active document or focus changed while the input was queued"); + return; + } + if self.synthetic_reinject { + if let Some(batch) = self.synthetic_batch.clone() { + raw_input.events.extend(batch); + } + self.synthetic_reinject = false; + self.automation_input = true; + } + return; + } + if self.synthetic.is_empty() { + return; + } + let events = self.take_synthetic_step(); + if events.is_empty() { + return; + } + self.synthetic_snapshot = Some(self.synthetic_target(ctx)); + raw_input.events.extend(events.iter().cloned()); + self.synthetic_batch = Some(events); + } + + /// A pass begins with the in-flight batch. The events are already in this pass's input, so a + /// target change detected now cannot withdraw them: deliver them (never half-apply) and keep + /// `automation_input` set so the commands they trigger still go through the automation policy. + /// `inject_synthetic` performs the withdrawable check, before the host consumes the events. + /// Called at the start of `App::ui` only (a hidden `run_logic` tick consumes no input). + pub(crate) fn begin_synthetic_pass(&mut self, ctx: &egui::Context) { + if self.synthetic_batch.is_none() { + return; + } + if !self.synthetic_target_matches(ctx) { + log::warn!("synthetic input: the document or focus changed inside the pass; delivering it as automation input"); + } + self.automation_input = true; + } + + /// One full UI pass handled the in-flight batch: deliver it once and let the next step in. + pub(crate) fn finish_synthetic_pass(&mut self) { + let _ = self.synthetic_batch.take(); + self.synthetic_snapshot = None; + self.synthetic_reinject = false; + } + + /// The pass returned before the input handling (fonts not ready): keep the batch and have the + /// next hook append it again exactly once, because egui already consumed the events. + pub(crate) fn defer_synthetic_pass(&mut self) { + if self.synthetic_batch.is_some() { + self.synthetic_reinject = true; + } + } + + /// Drop the in-flight batch and fail the replies waiting on it. + fn cancel_synthetic(&mut self, reason: &str) { + let pending = self.synthetic_batch.take().is_some() || !self.synthetic.is_empty(); + self.synthetic.clear(); + self.synthetic_snapshot = None; + self.synthetic_reinject = false; + self.automation_input = false; + if pending || !self.input_waiters.is_empty() { + for w in self.input_waiters.drain(..) { + let _ = w.send(serde_json::json!({"ok": false, "error": format!("input cancelled: {reason}")})); + } + } + } + + /// Next step of queued synthetic input (automation): events up to and including the first + /// release, so egui sees press and release in separate frames. Hosts that don't call + /// `raw_input_hook` (offscreen harnesses) feed these to their input themselves. + pub fn take_synthetic_step(&mut self) -> Vec { + let n = self + .synthetic + .iter() + .position(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. } | egui::Event::Key { pressed: false, .. })) + .map_or(self.synthetic.len(), |i| i + 1); + let events: Vec<_> = self.synthetic.drain(..n).collect(); + if !events.is_empty() { + self.automation_input = true; + } + events + } + + /// Install fonts, image loaders and the theme. Call from the app creator (and again for a + /// replacement Context) before the first `run_ui` so the very first frame renders and the + /// Type reset begin/end pass markers exist; otherwise `logic` does it and the first frame is + /// skipped, with the begin-pass marker necessarily starting on the following pass. + pub fn setup_context(ctx: &egui::Context, kind: theme::ThemeKind) { + Self::install_type_reset_hooks(ctx); + ctx.add_plugin(tool_cursor::CursorLifecycle); + ctx.add_plugin(single_line_drag::SingleLineDrag::default()); + theme::install_fonts(ctx); + egui_extras::install_image_loaders(ctx); + theme::apply(ctx, kind); + // Right-click in any text field: its Cut / Copy / Paste menu (text_field_menu.rs). + ctx.add_plugin(text_field_menu::TextFieldMenu); + // egui's own ⌘+ / ⌘- / ⌘0 scale the whole interface; PhotoCraft zooms the canvas instead + // (shortcuts.rs), like Photoshop. + ctx.options_mut(|o| o.zoom_with_keyboard = false); + // ⌘/Ctrl + wheel scrolls sideways, as in Photoshop; only a pinch zooms (wheel_nav.rs). + wheel_nav::configure(ctx); + } +} + +impl PhotocraftApp { + /// Cached `Surface::content_bounds` keyed by an id and the surface's tile identity. + pub fn cached_bounds(&mut self, key: u64, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { + let rev = surface_fingerprint(surface); + if let Some((r, b)) = self.bounds_cache.get(&key) + && *r == rev + { + return *b; + } + let b = surface.content_bounds(); + if self.bounds_cache.len() > 256 { + self.bounds_cache.clear(); + } + self.bounds_cache.insert(key, (rev, b)); + b + } + + /// The box Properties › Transform shows for `layer` (X, Y, W, H): its pixels' bounds, but a + /// soft shape's path and stroke, whose Density and Feather render past them (#5846), as its + /// transform frame does. + pub fn layer_frame_bounds(&mut self, layer: &photocraft_doc::Layer, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { + match &layer.content { + photocraft_doc::LayerContent::Shape(sh) if sh.has_soft_mask() => { + // Cached per rendering, like the pixel bounds: the frame renders strips of the shape. + let (key, rev) = (layer.id.0 | 1 << 63, surface_fingerprint(surface)); + if let Some((r, b)) = self.bounds_cache.get(&key) + && *r == rev + { + return *b; + } + let canvas = self.session.active().map_or_else(|| surface.content_bounds(), |st| st.doc.bounds()); + let b = photocraft_compose::soft_shape_frame(sh, surface.format(), canvas).unwrap_or(photocraft_geom::Rect::EMPTY); + if self.bounds_cache.len() > 256 { + self.bounds_cache.clear(); + } + self.bounds_cache.insert(key, (rev, b)); + b + } + _ => self.cached_bounds(layer.id.0, surface), + } + } +} + +impl PhotocraftApp { + /// Zoom of the active document's main view: screen (device) pixels per document pixel, the + /// user-facing factor (`100%` is `1.0`). + pub fn current_zoom(&self) -> f32 { + self.session.active_index().and_then(|i| self.ui.views.get(i)).map_or(1.0, |v| v.zoom) + } + + /// Screen (device) pixels per egui point of the canvas (`ctx.pixels_per_point`), as of the + /// last canvas frame. `1.0` before the first frame. + pub fn canvas_ppp(&self) -> f32 { + if self.ppp.is_finite() && self.ppp > 0.0 { self.ppp } else { 1.0 } + } + + /// The active view's zoom in egui points per document pixel: the unit every screen-space + /// distance, tolerance and texture-level choice on the canvas is measured in. + pub fn point_zoom(&self) -> f32 { + self.current_zoom() / self.canvas_ppp() + } +} + +impl PhotocraftApp { + /// Channels panel thumbnails of the active document snapshot: the composite, + /// each colour channel (when there is more than one), each alpha channel, then the Quick Mask. + pub fn channel_thumbs(&mut self, ctx: &egui::Context) -> Vec { + let Some(st) = self.session.active() else { + self.channel_thumbs = None; + return Vec::new(); + }; + let (id, doc) = (st.doc.id, st.doc.clone()); + // View-only commands bump revision without changing pixels. Keeping a Weak pins allocation + // identity against address reuse without retaining the document's pixel data. + let snapshot = std::sync::Arc::downgrade(&doc); + let show_color = self.session.prefs().interface.show_channels_in_color; + // A step that changes only the selection (a marquee, Deselect) makes a new snapshot with + // the same pixels: keep the thumbnails, a full composite at 56 px costs ~0.7 s on a + // layered 20 MP document (#4518). + let current = match &mut self.channel_thumbs { + Some((d, old, in_color, _)) if *d == id && *in_color == show_color => { + let same = old.ptr_eq(&snapshot) || old.upgrade().is_some_and(|prev| same_but_selection(&prev, &doc)); + if same { + *old = snapshot.clone(); + } + same + } + _ => false, + }; + if !current { + let comp = photocraft_compose::thumbnail(&doc, 56); + let (w, h) = (comp.width as usize, comp.height as usize); + let side = w.max(h); + let make = |f: &dyn Fn(&[u8]) -> egui::Color32, name: &str| { + let mut px = vec![egui::Color32::TRANSPARENT; side * side]; + let (ox, oy) = ((side - w) / 2, (side - h) / 2); + for y in 0..h { + for x in 0..w { + let o = (y * w + x) * 4; + px[(y + oy) * side + x + ox] = f(&comp.pixels[o..o + 4]); + } + } + (format!("chan-{name}"), egui::ColorImage::new([side, side], px)) + }; + let fmt = doc.pixel_format(); + let colors = fmt.mode.color_channels(); + let mut texs = vec![make(&|p| egui::Color32::from_rgb(p[0], p[1], p[2]), "composite")]; + if colors > 1 { + for k in 0..colors { + let cmyk = fmt.mode == photocraft_doc::ColorMode::Cmyk; + texs.push(make( + &|p| { + let rgba = [p[0], p[1], p[2], 255].map(|v| f32::from(v) / 255.0); + let x = photocraft_raster::from_rgba(&fmt, rgba)[k]; + let g = if cmyk { 1.0 - x } else { x }; + let byte = (g.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + channel_tint(fmt.mode, k, byte, show_color) + }, + &format!("c{k}"), + )); + } + } + // Alpha channels and the Quick Mask, sampled at thumbnail resolution. + let (dw, dh) = (doc.size.width.max(1) as f32, doc.size.height.max(1) as f32); + for (i, ch) in doc.channels.iter().chain(doc.quick_mask.as_ref()).enumerate() { + let mut px = vec![egui::Color32::TRANSPARENT; side * side]; + let (ox, oy) = ((side - w) / 2, (side - h) / 2); + for y in 0..h { + for x in 0..w { + let sx = ((x as f32 + 0.5) * dw / w as f32) as i32; + let sy = ((y as f32 + 0.5) * dh / h as f32) as i32; + let v = ch.surface.sample_channel(sx, sy, 0); + px[(y + oy) * side + x + ox] = egui::Color32::from_gray((v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + } + } + texs.push((format!("chan-a{i}"), egui::ColorImage::new([side, side], px))); + } + // Update the textures already uploaded rather than allocating new ones. + let mut handles = match self.channel_thumbs.take() { + Some((d, _, _, h)) if d == id => h, + _ => Vec::new(), + }; + handles.truncate(texs.len()); + for (i, (name, image)) in texs.into_iter().enumerate() { + match handles.get_mut(i) { + Some(h) => h.set(image, egui::TextureOptions::LINEAR), + None => handles.push(ctx.load_texture(name, image, egui::TextureOptions::LINEAR)), + } + } + self.channel_thumbs = Some((id, snapshot, show_color, handles)); + } + self.channel_thumbs.as_ref().map(|(_, _, _, t)| t.iter().map(|t| t.id()).collect()).unwrap_or_default() + } +} + +/// Whether `new` differs from `old` at most in its selection, so every composite and channel +/// thumbnail of it is unchanged. Tiles compare by pointer first, so this costs little. +fn same_but_selection(old: &Document, new: &Document) -> bool { + if old.selection == new.selection { + return old == new; + } + let mut o = old.clone(); + o.selection = new.selection.clone(); + o == *new +} + +/// Layer › Layer Mask commands that add a layer mask: Photoshop targets the new mask (#2166). +const ADDS_LAYER_MASK: [&str; 5] = [ + "layer.layerMask.revealAll", + "layer.layerMask.hideAll", + "layer.layerMask.revealSelection", + "layer.layerMask.hideSelection", + "layer.layerMask.fromTransparency", +]; + +/// The New Document dialog's key in the preferences' `dialogs` map. +const NEW_DOCUMENT: &str = "file.new"; + +/// New Document fields its OK remembers (#1810): the size, resolution, mode, depth, background and +/// display units. Not the name, the preset or the clipboard size. +const NEW_DOCUMENT_REMEMBERED: [&str; 8] = ["width", "height", "resolution", "mode", "depth", "background", "__unit", "__resUnit"]; + +/// A remembered value the dialog can show (a corrupt preference is ignored). +fn remembered_new_document_value(key: &str, v: &serde_json::Value) -> bool { + match key { + "width" | "height" => v.as_u64().is_some_and(|n| (1..=300_000).contains(&n)), + "resolution" => v.as_f64().is_some_and(|r| r.is_finite() && r > 0.0 && r <= 30_000.0), + "depth" => v.as_u64().is_some_and(|d| matches!(d, 1 | 8 | 16 | 32)), + _ => v.as_str().is_some_and(|s| !s.is_empty() && s.len() <= 64), + } +} + +/// Remember the New Document fields `f` its OK used, for the next New Document. +pub(crate) fn remember_new_document(app: &mut PhotocraftApp, f: &serde_json::Map) { + let kept: serde_json::Map = + NEW_DOCUMENT_REMEMBERED.iter().filter_map(|k| f.get(*k).filter(|v| remembered_new_document_value(k, v)).map(|v| (k.to_string(), v.clone()))).collect(); + app.session.prefs.edit(|p| p.dialogs.insert(NEW_DOCUMENT.into(), serde_json::Value::Object(kept))); +} + +fn clip_signature(w: u32, h: u32, px: &[u8]) -> u64 { + let mut sig = (w as u64) << 32 | h as u64; + for b in px.iter().step_by(997) { + sig = sig.rotate_left(5) ^ *b as u64; + } + sig +} + +/// A channel thumbnail pixel whose lightness is `byte` (255 = white: full light, no ink). +/// Preferences ▸ Interface ▸ Show Channels in Color tints RGB channels from black to their +/// primary and CMYK channels from white to their ink, as Photoshop does; otherwise grey. +fn channel_tint(mode: photocraft_doc::ColorMode, k: usize, byte: u8, in_color: bool) -> egui::Color32 { + use photocraft_doc::ColorMode::{Cmyk, Rgb}; + if !in_color { + return egui::Color32::from_gray(byte); + } + match (mode, k) { + (Rgb, 0) => egui::Color32::from_rgb(byte, 0, 0), + (Rgb, 1) => egui::Color32::from_rgb(0, byte, 0), + (Rgb, 2) => egui::Color32::from_rgb(0, 0, byte), + (Cmyk, 0) => egui::Color32::from_rgb(byte, 255, 255), + (Cmyk, 1) => egui::Color32::from_rgb(255, byte, 255), + (Cmyk, 2) => egui::Color32::from_rgb(255, 255, byte), + _ => egui::Color32::from_gray(byte), + } +} + +impl PhotocraftApp { + /// Mirror the session clipboard onto the OS clipboard (RGBA8). + fn export_os_clipboard(&mut self) { + self.clip_unmirrored = true; + if !self.session.prefs().general.export_clipboard { + return; + } + let (Some(set), Some(clip)) = (self.services.clipboard_set_image.as_mut(), self.session.clipboard.as_ref()) else { return }; + let b = clip.bounds; + if b.is_empty() { + return; + } + let mut px = vec![[0u8; 4]; b.width() as usize * b.height() as usize]; + clip.surface.read_rgba8_into(b, &mut px); + let bytes: Vec = px.into_iter().flatten().collect(); + if set(b.width(), b.height(), &bytes).is_ok() { + self.os_clip_sig = Some(clip_signature(b.width(), b.height(), &bytes)); + self.clip_unmirrored = false; + } + } + + /// File › New's fields: the defaults, then the settings of the last document made with the + /// dialog (Photoshop starts from them, #1810), then the Clipboard preset (the clipboard image's + /// size, selected) when the clipboard holds an image. Opening the dialog is an explicit + /// request, so the OS clipboard is read here, as for a paste. + pub(crate) fn new_document_fields(&mut self) -> serde_json::Map { + let mut f = crate::state::UiState::new_document_fields(); + if let Some(serde_json::Value::Object(saved)) = self.session.prefs().dialogs.get(NEW_DOCUMENT) { + for k in NEW_DOCUMENT_REMEMBERED { + if let Some(v) = saved.get(k).filter(|v| remembered_new_document_value(k, v)) { + f.insert(k.into(), v.clone()); + } + } + } + if self.import_os_clipboard().is_err() { + return f; + } + if let Some(c) = self.session.clipboard.as_ref().filter(|c| !c.bounds.is_empty()) { + crate::new_doc_ui::set_clipboard(&mut f, c.bounds.width(), c.bounds.height()); + } + f + } + + /// If the OS clipboard holds an image that isn't the one we put there, make it the session + /// clipboard (so ⌘V pastes screenshots and images copied in other apps, like Photoshop). + /// Returns `Ok(true)` when a new external image was imported. Once the OS clipboard no longer holds + /// the image we mirrored or imported (text or a file was copied since), that image is stale: + /// it is dropped rather than pasted. Unexported internal copies survive unavailable or empty + /// system clipboards. + pub(crate) fn import_os_clipboard(&mut self) -> Result { + let Some(get) = self.services.clipboard_get_image.as_mut() else { return Ok(false) }; + // A read failure says nothing about the clipboard contents. Keep our editable copy and + // its signature rather than treating the failure as an empty image. + let image = match get() { + Ok(image) => image, + Err(error) => { + // An unexported copy remains usable without an OS clipboard (for example, in + // a Wayland sandbox). Mirrored/imported copies still require a successful read + // before pasting, because their system contents may have changed. + if self.clip_unmirrored && !self.clip_external && self.session.clipboard.is_some() { + return Ok(false); + } + if self.session.clipboard.is_none() && self.services.clipboard_unreadable.as_ref().is_some_and(|unreadable| unreadable()) { + // Let paste explain the unavailable backend without treating a saved copy as empty. + return Ok(false); + } + self.ui.status = error.clone(); + self.ui.status_error = true; + return Err(error); + } + }; + let image = image.filter(|(w, h, bytes)| *w > 0 && *h > 0 && bytes.len() == *w as usize * *h as usize * 4); + let Some((w, h, bytes)) = image else { + if self.os_clip_sig.take().is_some() && !self.clip_unmirrored { + self.session.clipboard = None; + self.clip_external = false; + self.clip_unmirrored = true; + } + return Ok(false); + }; + let sig = clip_signature(w, h, &bytes); + if self.os_clip_sig == Some(sig) && self.session.clipboard.is_some() { + return Ok(false); + } + let r = photocraft_geom::Rect::new(0, 0, w as i32, h as i32); + let mut surface = photocraft_raster::Surface::from_interleaved(photocraft_color::PixelFormat::RGBA8, r, &bytes); + surface.prune(); + self.session.clipboard = Some(photocraft_engine::edit_cmds::Clip { surface, bounds: r, layers: None, resolution: None, source: None }); + self.os_clip_sig = Some(sig); + self.clip_external = true; + self.clip_unmirrored = false; + Ok(true) + } +} + +#[cfg(test)] +mod clipboard_tests { + use super::*; + use std::sync::{Arc, Mutex}; + + #[test] + fn os_clipboard_bridge() { + let os: OsClip = Arc::default(); + let (a, b) = (os.clone(), os.clone()); + let services = Services { + clipboard_set_image: Some(Box::new(move |w: u32, h: u32, px: &[u8]| { + *a.lock().unwrap() = Some((w, h, px.to_vec())); + Ok(()) + })), + clipboard_get_image: Some(Box::new(move || Ok(b.lock().unwrap().clone()))), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.session.execute("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.run("select.rect", serde_json::json!({"x": 0, "y": 0, "width": 8, "height": 4})).unwrap(); + app.run("edit.copy", serde_json::json!({})).unwrap(); + let (w, h, px) = os.lock().unwrap().clone().unwrap(); + assert_eq!((w, h, px.len()), (8, 4, 8 * 4 * 4)); + // Our own image comes back unchanged (no re-import, keeps the original position). + assert!(!app.import_os_clipboard().unwrap()); + // Text copied elsewhere replaces our image: nothing to paste, not the stale image. + let ours = os.lock().unwrap().take(); + assert!(!app.import_os_clipboard().unwrap()); + assert!(app.session.clipboard.is_none()); + *os.lock().unwrap() = ours; + app.run("edit.copy", serde_json::json!({})).unwrap(); + // Another app puts a 3×2 red image on the clipboard: ⌘V pastes it. + *os.lock().unwrap() = Some((3, 2, [255u8, 0, 0, 255].repeat(6))); + app.run("edit.paste", serde_json::json!({})).unwrap(); + let st = app.session.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + assert_eq!(surf.content_bounds().width(), 3); + } + + #[test] + fn os_clipboard_honours_export_clipboard_preference() { + let os: OsClip = Arc::default(); + let a = os.clone(); + let services = Services { + clipboard_set_image: Some(Box::new(move |w: u32, h: u32, px: &[u8]| { + *a.lock().unwrap() = Some((w, h, px.to_vec())); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.session.execute("prefs.set", serde_json::json!({"values": {"general.exportClipboard": false}})).unwrap(); + app.session.execute("file.new", serde_json::json!({"width": 32, "height": 32})).unwrap(); + app.sync_views(); + app.run("select.rect", serde_json::json!({"x": 0, "y": 0, "width": 8, "height": 4})).unwrap(); + app.run("edit.copy", serde_json::json!({})).unwrap(); + assert!(os.lock().unwrap().is_none(), "copy does not mirror to OS clipboard when export_clipboard is off"); + } + + type OsClip = Arc)>>>; + + #[test] + fn failed_clipboard_reads_preserve_editable_contents_until_retry() { + use std::sync::atomic::{AtomicBool, Ordering}; + for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace", "file.newFromClipboard"] { + let os = OsClip::default(); + let busy = Arc::new(AtomicBool::new(false)); + let (write, read, unavailable) = (os.clone(), os.clone(), busy.clone()); + let services = Services { + clipboard_set_image: Some(Box::new(move |w, h, bytes| { + *write.lock().unwrap() = Some((w, h, bytes.to_vec())); + Ok(()) + })), + clipboard_get_image: Some(Box::new(move || { + if unavailable.load(Ordering::SeqCst) { Err("clipboard is busy".into()) } else { Ok(read.lock().unwrap().clone()) } + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); + app.run("shape.create", serde_json::json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); + app.run("edit.copy", serde_json::json!({})).unwrap(); + app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); + let signature = app.os_clip_sig; + assert!(signature.is_some()); + let before = app.session.active().unwrap().doc.walk().len(); + busy.store(true, Ordering::SeqCst); + let result = crate::menus::invoke(&mut app, &egui::Context::default(), id, serde_json::json!({})); + assert_eq!(result.unwrap_err(), "clipboard is busy", "{id}"); + assert!(app.ui.status_error); + assert_eq!(app.session.documents().len(), 2); + assert_eq!(app.session.active().unwrap().doc.walk().len(), before); + assert_eq!(app.os_clip_sig, signature); + assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); + // The New dialog also reads the clipboard; a failed preset probe must preserve it. + app.new_document_fields(); + assert_eq!(app.os_clip_sig, signature); + assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); + // An automation error must not leave script events disabled by the dispatch guard. + app.automation_input = true; + app.session.edit_prefs(|prefs| prefs.script_events.enabled = true); + assert!(app.run(id, serde_json::json!({})).is_err()); + assert!(app.session.prefs().script_events.enabled); + app.automation_input = false; + busy.store(false, Ordering::SeqCst); + app.run("edit.pasteSpecial.pasteInPlace", serde_json::json!({})).unwrap(); + let state = app.session.active().unwrap(); + assert!(matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Shape(_))); + assert!(!app.ui.status_error); + } + } + + #[test] + fn internal_only_clipboard_remains_usable_when_native_access_fails() { + use std::sync::atomic::{AtomicBool, Ordering}; + for export in [true, false] { + for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace", "file.newFromClipboard"] { + let os = OsClip::default(); + let unavailable = Arc::new(AtomicBool::new(true)); + let (read, failed) = (os.clone(), unavailable.clone()); + let services = Services { + clipboard_set_image: Some(Box::new(|_, _, _| Err("clipboard unavailable".into()))), + clipboard_get_image: Some(Box::new(move || { + if failed.load(Ordering::SeqCst) { Err("clipboard unavailable".into()) } else { Ok(read.lock().unwrap().clone()) } + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.session.edit_prefs(|prefs| prefs.general.export_clipboard = export); + app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); + app.run("shape.create", serde_json::json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); + app.run("edit.copy", serde_json::json!({})).unwrap(); + app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); + assert!(app.os_clip_sig.is_none() && !app.clip_external); + let bounds = app.session.clipboard.as_ref().unwrap().bounds; + assert_eq!(app.new_document_fields()["__preset"], "Clipboard"); + crate::menus::invoke(&mut app, &egui::Context::default(), id, serde_json::json!({})).unwrap(); + assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); + assert!(!app.ui.status_error); + if id == "file.newFromClipboard" { + assert_eq!(app.session.documents().len(), 3); + let doc = &app.session.active().unwrap().doc; + assert_eq!((doc.size.width, doc.size.height), (bounds.width(), bounds.height())); + } else { + assert_eq!(app.session.documents().len(), 2); + let state = app.session.active().unwrap(); + assert!(matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Shape(_))); + } + app.run("edit.purge.clipboard", serde_json::json!({})).unwrap(); + assert!(app.session.clipboard.is_none()); + assert!(app.run("edit.paste", serde_json::json!({})).is_err(), "purged content must not be a fallback"); + // The fallback is only for failed reads: a later successful external image wins. + *os.lock().unwrap() = Some((3, 2, [0u8, 0, 255, 255].repeat(6))); + unavailable.store(false, Ordering::SeqCst); + app.run("edit.paste", serde_json::json!({})).unwrap(); + assert!(app.clip_external && app.os_clip_sig.is_some()); + let clip = app.session.clipboard.as_ref().unwrap(); + assert!(clip.layers.is_none()); + assert_eq!((clip.bounds.width(), clip.bounds.height()), (3, 2)); + } + } + } + + #[test] + fn newer_unexported_copies_do_not_track_an_older_os_signature() { + use std::sync::atomic::{AtomicBool, Ordering}; + for imported in [true, false] { + for disable_export in [true, false] { + for copy_id in ["edit.copy", "edit.cut", "edit.copyMerged"] { + let os = OsClip::default(); + let write_fails = Arc::new(AtomicBool::new(false)); + let read_fails = Arc::new(AtomicBool::new(false)); + let (write, read, failed_write, failed_read) = (os.clone(), os.clone(), write_fails.clone(), read_fails.clone()); + let services = Services { + clipboard_set_image: Some(Box::new(move |w, h, bytes| { + if failed_write.load(Ordering::SeqCst) { + return Err("clipboard unavailable".into()); + } + *write.lock().unwrap() = Some((w, h, bytes.to_vec())); + Ok(()) + })), + clipboard_get_image: Some(Box::new(move || { + if failed_read.load(Ordering::SeqCst) { Err("clipboard unavailable".into()) } else { Ok(read.lock().unwrap().clone()) } + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); + if imported { + *os.lock().unwrap() = Some((2, 2, [255u8, 0, 0, 255].repeat(4))); + assert!(app.import_os_clipboard().unwrap()); + } else { + app.run("edit.fill", serde_json::json!({"color": "#ff0000"})).unwrap(); + app.run("edit.copy", serde_json::json!({})).unwrap(); + } + let old_signature = app.os_clip_sig; + assert!(old_signature.is_some() && !app.clip_unmirrored); + app.run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); + app.run("edit.fill", serde_json::json!({"color": "#0000ff"})).unwrap(); + write_fails.store(true, Ordering::SeqCst); + app.session.edit_prefs(|prefs| prefs.general.export_clipboard = !disable_export); + app.run(copy_id, serde_json::json!({})).unwrap(); + let copied = app.session.clipboard.clone().unwrap(); + assert!(app.clip_unmirrored && !app.clip_external); + assert_eq!(app.os_clip_sig, old_signature); + assert_eq!(copied.surface.rgba(0, 0), [0.0, 0.0, 1.0, 1.0]); + // An old successful export/import must not block the newer internal copy. + read_fails.store(true, Ordering::SeqCst); + app.run("edit.pasteSpecial.pasteInPlace", serde_json::json!({})).unwrap(); + assert_eq!(app.os_clip_sig, old_signature); + assert!(app.clip_unmirrored && !app.clip_external); + read_fails.store(false, Ordering::SeqCst); + assert!(!app.import_os_clipboard().unwrap(), "unchanged old OS image must not overwrite the newer copy"); + assert_eq!(app.session.clipboard.as_ref().unwrap().surface.rgba(0, 0), copied.surface.rgba(0, 0)); + *os.lock().unwrap() = None; + assert!(!app.import_os_clipboard().unwrap(), "empty OS clipboard must not discard an unexported copy"); + assert!(app.os_clip_sig.is_none() && app.clip_unmirrored); + assert_eq!(app.session.clipboard.as_ref().unwrap().surface.rgba(0, 0), copied.surface.rgba(0, 0)); + // A different external image supersedes the internal copy and disables fallback. + *os.lock().unwrap() = Some((3, 2, [0u8, 255, 0, 255].repeat(6))); + assert!(app.import_os_clipboard().unwrap()); + assert!(app.clip_external && !app.clip_unmirrored); + let clip = app.session.clipboard.as_ref().unwrap(); + assert_eq!((clip.bounds.width(), clip.bounds.height()), (3, 2)); + read_fails.store(true, Ordering::SeqCst); + assert!(app.run("edit.paste", serde_json::json!({})).is_err()); + } + } + } + } + + #[test] + fn failed_clipboard_reads_do_not_paste_an_external_or_missing_copy() { + use std::sync::atomic::{AtomicBool, Ordering}; + for external in [true, false] { + let unavailable = Arc::new(AtomicBool::new(false)); + let failed = unavailable.clone(); + let services = Services { + clipboard_get_image: Some(Box::new(move || { + if failed.load(Ordering::SeqCst) { Err("clipboard unavailable".into()) } else { Ok(Some((3, 2, [255u8, 0, 0, 255].repeat(6)))) } + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); + if external { + assert!(app.import_os_clipboard().unwrap()); + } + let signature = app.os_clip_sig; + let before = app.session.active().unwrap().doc.walk().len(); + unavailable.store(true, Ordering::SeqCst); + for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace", "file.newFromClipboard"] { + let result = crate::menus::invoke(&mut app, &egui::Context::default(), id, serde_json::json!({})); + assert_eq!(result.unwrap_err(), "clipboard unavailable", "{id}"); + assert!(app.ui.status_error); + assert_eq!(app.session.documents().len(), 1); + assert_eq!(app.session.active().unwrap().doc.walk().len(), before); + assert_eq!(app.os_clip_sig, signature); + assert_eq!(app.session.clipboard.is_some(), external); + assert_eq!(app.clip_external, external); + } + } + } + + /// An app whose OS clipboard is `os`, counting every read in `reads`. + fn app_with_os_clipboard(os: &OsClip, reads: &Arc) -> PhotocraftApp { + let (b, n) = (os.clone(), reads.clone()); + let get = move || { + n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(b.lock().unwrap().clone()) + }; + let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(Box::new(get)), ..Default::default() }); + app.session.execute("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app + } + + /// Paste is enabled from the clipboard service alone (no read); the explicit paste imports + /// the OS image, once, and centres it in the view like Photoshop does for foreign clipboard + /// content. + #[test] + fn external_clipboard_enables_and_centres_paste() { + let (os, reads) = (OsClip::default(), Arc::default()); + let mut app = app_with_os_clipboard(&os, &reads); + *os.lock().unwrap() = Some((4, 4, [255u8, 0, 0, 255].repeat(16))); + assert!(app.session.clipboard.is_none()); + assert!(crate::menus::is_enabled(&app, "edit.paste")); + assert!(crate::menus::is_enabled(&app, "edit.pasteSpecial.pasteInPlace")); + assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 0, "enablement never reads the clipboard"); + app.ui.views[0].center = [40.0, 20.0]; + let r = crate::menus::invoke(&mut app, &egui::Context::default(), "edit.paste", serde_json::json!({})).unwrap(); + assert_eq!(r["offset"], serde_json::json!([38, 18]), "external image is centred in the view: {r}"); + assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 1, "one read per explicit paste"); + // Without a clipboard service Paste greys until something is copied in the app. + let mut plain = PhotocraftApp::new(Session::new(), Services::default()); + plain.session.execute("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); + assert!(!crate::menus::is_enabled(&plain, "edit.paste")); + } + + /// #368: an image copied in another app opens as a document of its own, from File › New + /// from Clipboard or from Paste with nothing open. + #[test] + fn os_clipboard_image_becomes_a_new_document() { + let (os, reads) = (OsClip::default(), Arc::new(std::sync::atomic::AtomicUsize::new(0))); + let (b, n) = (os.clone(), Arc::clone(&reads)); + let get = move || { + n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(b.lock().unwrap().clone()) + }; + let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(Box::new(get)), ..Default::default() }); + let ctx = egui::Context::default(); + // Listed right after File › New…, enabled without reading the clipboard. + let items = crate::menus::menu_items(&app); + let at = items.iter().position(|i| i.id == "file.new").unwrap(); + assert_eq!(items[at + 1].id, "file.newFromClipboard"); + assert!(items[at + 1].enabled && crate::menus::is_enabled(&app, "edit.paste")); + assert!(!crate::menus::is_enabled(&app, "edit.pasteSpecial.pasteInPlace"), "Paste in Place needs a document"); + assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 0); + // An empty clipboard is a quiet no-op. + let r = crate::menus::invoke(&mut app, &ctx, "file.newFromClipboard", serde_json::json!({})).unwrap(); + assert_eq!(r["pasted"], serde_json::json!(false)); + assert!(app.session.documents().is_empty() && !app.ui.status_error); + // Paste with nothing open makes the document. + *os.lock().unwrap() = Some((5, 3, [0u8, 0, 255, 255].repeat(15))); + crate::menus::invoke(&mut app, &ctx, "edit.paste", serde_json::json!({})).unwrap(); + let d = &app.session.active().unwrap().doc; + assert_eq!((d.size.width, d.size.height, d.layers.len()), (5, 3, 1)); + assert_eq!(app.ui.views.len(), 1, "the new document has a view"); + assert!(app.has_unsaved_work(), "closing after Paste must ask to save"); + // New from Clipboard with a document open adds another. + crate::menus::invoke(&mut app, &ctx, "file.newFromClipboard", serde_json::json!({})).unwrap(); + assert_eq!(app.session.documents().len(), 2); + assert!(app.session.documents().iter().all(|d| d.is_dirty())); + assert!(crate::discard_ui::intercept(&mut app, "file.close", &serde_json::json!({})), "Close must ask before discarding clipboard pixels"); + } + + #[test] + fn pasting_an_empty_or_non_image_os_clipboard_is_a_quiet_no_op() { + let (os, reads) = (OsClip::default(), Arc::default()); + let mut app = app_with_os_clipboard(&os, &reads); + let layers = app.session.active().unwrap().doc.layers.len(); + let r = crate::menus::invoke(&mut app, &egui::Context::default(), "edit.paste", serde_json::json!({})).unwrap(); + assert_eq!(r["pasted"], serde_json::json!(false)); + assert_eq!(app.run("edit.pasteSpecial.pasteInPlace", serde_json::json!({})).unwrap()["pasted"], serde_json::json!(false)); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers); + assert!(!app.ui.status_error && !app.ui.status.is_empty()); + } + + #[test] + fn idle_frames_never_read_the_os_clipboard() { + let (os, reads) = (OsClip::default(), Arc::::default()); + *os.lock().unwrap() = Some((4, 4, [255u8, 0, 0, 255].repeat(16))); + let (b, n) = (os.clone(), reads.clone()); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let get = move || { + n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(b.lock().unwrap().clone()) + }; + let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(Box::new(get)), ..Default::default() }); + app.session.execute("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); + app + }); + for _ in 0..20 { + h.step(); + } + assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 0, "the OS clipboard is read only on an explicit paste"); + assert!(h.state().session.clipboard.is_none()); + } + + /// #2928: with the layer mask targeted, ⌘C copies the mask's values as grayscale, not the + /// layer's pixels — so ⌘V (targeting another layer's mask, #1035) moves the mask itself. + #[test] + fn copy_with_the_mask_targeted_copies_the_mask_not_the_pixels() { + let (os, reads) = (OsClip::default(), Arc::default()); + let mut app = app_with_os_clipboard(&os, &reads); + app.run("layer.new.layer", serde_json::json!({})).unwrap(); + app.run("layer.layerMask.hideAll", serde_json::json!({})).unwrap(); + // Black pixels, a white square in the mask: the copy must carry the mask. + app.run("select.all", serde_json::json!({})).unwrap(); + app.run("edit.fill", serde_json::json!({"color": "#000000"})).unwrap(); + app.run("select.rect", serde_json::json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); + app.run("edit.fill", serde_json::json!({"color": "#ffffff", "target": "mask"})).unwrap(); + app.run("select.deselect", serde_json::json!({})).unwrap(); + app.ui.mask_target = true; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.copy", serde_json::json!({})).unwrap(); + let clip = app.session.clipboard.clone().expect("the mask was copied"); + let st = app.session.active().unwrap(); + let (w, h) = (st.doc.size.width as i32, st.doc.size.height as i32); + assert_eq!( + [clip.bounds.x0, clip.bounds.y0, clip.bounds.width() as i32, clip.bounds.height() as i32], + [0, 0, w, h], + "the mask, whole — not the black pixels" + ); + let px = clip.surface.rgba(6, 6); + assert!(px[0] > 0.99 && px[3] > 0.99, "white mask values: {px:?}"); + assert!(clip.surface.rgba(20, 20)[0] < 0.01, "the hidden area copies as black"); + } + + /// #1035: with the layer mask targeted (its thumbnail clicked), ⌘V pastes the clipboard's + /// luminosity into the mask instead of making a layer. + #[test] + fn paste_with_the_mask_targeted_goes_into_the_mask() { + let (os, reads) = (OsClip::default(), Arc::default()); + let mut app = app_with_os_clipboard(&os, &reads); + app.run("layer.new.layer", serde_json::json!({})).unwrap(); + app.run("layer.layerMask.hideAll", serde_json::json!({})).unwrap(); + app.ui.mask_target = true; + app.ui.views[0].center = [32.0, 32.0]; + *os.lock().unwrap() = Some((4, 4, [128u8, 128, 128, 255].repeat(16))); + let layers = app.session.active().unwrap().doc.layer_count(); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.paste", serde_json::json!({})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layer_count(), layers, "no new layer"); + let mask = st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap(); + assert!((mask.value(32, 32) - 128.0 / 255.0).abs() < 2.0 / 255.0, "the grey, centred in the view: {}", mask.value(32, 32)); + assert_eq!(mask.value(0, 0), 0.0, "the rest of the mask is unchanged"); + } + + /// #2166, measured in Photoshop 25.1: adding a layer mask targets it with white/black, and + /// the pixels and the mask each keep their own foreground/background pair. + #[test] + fn targeting_a_mask_swaps_to_its_own_colour_pair() { + use serde_json::json; + const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; + const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; + const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; + const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; + const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0]; + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + let masked = app.run("layer.new.layer", json!({})).unwrap()["layer"].clone(); + app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); + let pair = |app: &PhotocraftApp| (app.session.tools.foreground, app.session.tools.background); + let target = |app: &mut PhotocraftApp, mask: bool| { + app.ui.mask_target = mask; + app.sync_views(); + }; + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + assert!(app.ui.mask_target, "the new mask is targeted"); + assert_eq!(pair(&app), (WHITE, BLACK)); + target(&mut app, false); + assert_eq!(pair(&app), (RED, BLUE), "the pixels get their colours back"); + target(&mut app, true); + assert_eq!(pair(&app), (WHITE, BLACK)); + target(&mut app, false); + app.run("tools.setColors", json!({"foreground": "#00ff00"})).unwrap(); + target(&mut app, true); + assert_eq!(pair(&app), (WHITE, BLACK)); + target(&mut app, false); + assert_eq!(pair(&app), (GREEN, BLUE)); + // A layer without a mask edits its pixels: their pair. + target(&mut app, true); + app.run("layer.new.layer", json!({})).unwrap(); + assert_eq!(pair(&app), (GREEN, BLUE)); + app.run("layer.select", json!({"layer": masked})).unwrap(); + target(&mut app, true); + assert_eq!(pair(&app), (WHITE, BLACK)); + app.run("layer.layerMask.delete", json!({})).unwrap(); + assert_eq!(pair(&app), (GREEN, BLUE), "deleting the targeted mask goes back to the pixels"); + } +} + +#[cfg(test)] +mod channel_tint_tests { + use super::channel_tint; + use egui::Color32; + use photocraft_doc::ColorMode::{Cmyk, Grayscale, Rgb}; + + #[test] + fn channels_in_color_tint_rgb_from_black_and_cmyk_inks_from_white() { + assert_eq!(channel_tint(Rgb, 0, 255, true), Color32::from_rgb(255, 0, 0)); + assert_eq!(channel_tint(Rgb, 2, 0, true), Color32::BLACK); + // CMYK: no ink is white, full ink is the ink's colour. + assert_eq!(channel_tint(Cmyk, 0, 255, true), Color32::WHITE); + assert_eq!(channel_tint(Cmyk, 0, 0, true), Color32::from_rgb(0, 255, 255)); + assert_eq!(channel_tint(Cmyk, 1, 0, true), Color32::from_rgb(255, 0, 255)); + assert_eq!(channel_tint(Cmyk, 2, 0, true), Color32::from_rgb(255, 255, 0)); + assert_eq!(channel_tint(Cmyk, 3, 0, true), Color32::BLACK); + assert_eq!(channel_tint(Grayscale, 0, 77, true), Color32::from_gray(77)); + assert_eq!(channel_tint(Rgb, 0, 77, false), Color32::from_gray(77)); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index adf7b4f959..bbfd0e8b75 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -280,412 +280,18 @@ pub use file_dialog::{FileDialogAnswer, FileDialogFn, FileDialogReply, FileDialo pub use file_open::OsEvent; pub use state::{Tool, UiState}; -/// The error a save gets while another save waits on its format prompt. -pub(crate) const SAVE_OPTIONS_OPEN: &str = "Answer the TIFF, Targa, DDS or JPEG Options before starting another save"; +mod app; +mod services; -/// The format answers a save takes instead of asking: the Targa bits per pixel (`"tgaBits"`), -/// the DDS options (`"ddsCompression"`, `"ddsMipmaps"`) and JPEG Options (`"quality"` 0–12, -/// `"jpegFormat"`). `None` asks in Save As and takes the default in automation saves, which never -/// prompt. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct FormatChoices { - pub tga_bits: Option, - pub dds: Option, - pub jpeg: Option, -} - -impl FormatChoices { - /// The answers in command or control call `cmd`'s params; a bad value is an error. - pub fn from_params(params: &Value, cmd: &str) -> Result { - Ok(FormatChoices { - tga_bits: targa_options_ui::bits_param(params, cmd)?, - dds: dds_options_ui::options_param(params, cmd)?, - jpeg: jpeg_options_ui::choice_param(params, cmd)?, - }) - } - - /// The answers in a recorded save step, read as leniently as the engine command that may have - /// recorded it (see [`jpeg_options_ui::recorded_choice`]). - pub(crate) fn from_step(params: &Value, cmd: &str) -> Result { - Ok(FormatChoices { - tga_bits: targa_options_ui::bits_param(params, cmd)?, - dds: dds_options_ui::options_param(params, cmd)?, - jpeg: jpeg_options_ui::recorded_choice(params, cmd)?, - }) - } - - /// The export settings with these answers applied. - pub fn apply(self, settings: ExportSettings) -> ExportSettings { - let settings = ExportSettings { tga_bits: self.tga_bits.or(settings.tga_bits), dds: self.dds.unwrap_or(settings.dds), ..settings }; - match self.jpeg { - Some(j) => j.apply(settings), - None => settings, - } - } - - /// Adds the answers to a recorded save step. - pub(crate) fn record(self, step: &mut Value) { - if let Some(bits) = self.tga_bits { - step["tgaBits"] = bits.bits().into(); - } - if let Some(dds) = self.dds { - dds_options_ui::record(dds, step); - } - if let Some(j) = self.jpeg { - j.record(step); - } - } -} - -/// Decode a file: (document, warnings about anything approximated or dropped). -pub type ImportFn = Box Result<(Document, Vec), String>>; -/// Encoder settings chosen in Export As (the file format comes from the name's extension). -#[derive(Clone, Debug, PartialEq)] -pub struct ExportSettings { - /// JPEG quality 1–100 (None = codec default). - pub jpeg_quality: Option, - /// JPEG Options › Format Options: baseline, baseline optimized or progressive. - pub jpeg_format: photocraft_codecs::JpegFormat, - /// WebP: lossless (VP8L) rather than lossy (VP8 at [`Self::webp_quality`]). - pub webp_lossless: bool, - /// Lossy WebP quality 1–100 (None = codec default). - pub webp_quality: Option, - /// TIFF: keep the layers (Photoshop layer data); `false` is "Discard Layers and Save a Copy". - pub tiff_layers: bool, - /// Embed the document's whole XMP packet. `true` by default (Save As keeps the metadata); - /// Export As starts at Metadata: None, since the packet can carry the text of every type - /// layer and one id per placed document (#647). - pub xmp_all: bool, - /// Targa: bits per pixel from Targa Options or Export As (`None`: 32 with an alpha channel or - /// transparency, else 24). - pub tga_bits: Option, - /// DDS: the compression and mip chain from DDS Options (uncompressed without mipmaps unless - /// chosen). - pub dds: photocraft_io::DdsOptions, - /// PSD/PSB: embed a thumbnail (Preferences › File Handling › Image Previews; see - /// [`PhotocraftApp::save_settings`]). - pub image_previews: bool, - /// PSD/PSB: write the real merged image (Preferences › File Handling › Maximize PSD and PSB - /// File Compatibility; see [`PhotocraftApp::save_settings`]). - pub psd_maximize_compatibility: bool, - /// Embed the document's ICC profile when the format supports it. On for Save As and, unless - /// Export As turns it off, for export. - pub embed_icc: bool, - /// Embed EXIF, resolution and other non-XMP metadata when the format supports it. Export As - /// turns this off for Metadata: None; Save As leaves it on. - pub embed_metadata: bool, - /// The path of the document's own file, which linked smart objects that PSD/PSB embed are - /// resolved against ([`photocraft_io::ExportOptions::document_path`]). - pub document_path: Option, - /// Native save cache owned by the open document; exports without one remain one-shot. - pub pcraft_cache: Option, - /// Read and embed the files linked smart objects name ([`photocraft_io::ExportOptions::read_linked_files`]). - /// Off for automation saves, which are granted only their target. - pub read_linked_files: bool, -} - -impl Default for ExportSettings { - fn default() -> Self { - ExportSettings { - jpeg_quality: None, - jpeg_format: photocraft_codecs::JpegFormat::Baseline, - webp_lossless: true, - webp_quality: None, - tiff_layers: true, - xmp_all: true, - tga_bits: None, - dds: photocraft_io::DdsOptions::default(), - image_previews: true, - psd_maximize_compatibility: true, - embed_icc: true, - embed_metadata: true, - document_path: None, - pcraft_cache: None, - read_linked_files: true, - } - } -} - -impl ExportSettings { - /// The IO export options these encoder settings select. Save As and Export As share this so - /// a profile or metadata choice cannot be applied in one and forgotten in the other. - pub fn io_options(&self) -> photocraft_io::ExportOptions { - let mut opts = photocraft_io::ExportOptions::default(); - if let Some(q) = self.jpeg_quality { - opts.encode.jpeg_quality = q; - } - opts.encode.jpeg_format = self.jpeg_format; - opts.encode.webp_lossless = self.webp_lossless; - if let Some(q) = self.webp_quality { - opts.encode.webp_quality = q; - } - opts.encode.embed_icc = self.embed_icc; - opts.encode.embed_metadata = self.embed_metadata; - opts.tiff_layers = self.tiff_layers; - opts.xmp = if self.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None }; - opts.tga_bits = self.tga_bits; - opts.encode.dds = self.dds; - opts.image_previews = self.image_previews; - opts.psd_maximize_compatibility = self.psd_maximize_compatibility; - opts.document_path = self.document_path.clone(); - opts.pcraft_cache = self.pcraft_cache.clone(); - opts.read_linked_files = self.read_linked_files; - opts - } -} - -/// The document's lone layer when it is a plain raster a flat file keeps: visible, at full -/// opacity, in Normal mode, with no masks, effects or blending restrictions (#2234). -pub(crate) fn plain_raster(doc: &Document) -> Option<&photocraft_doc::Layer> { - match doc.layers.as_slice() { - [layer] - if matches!(layer.content, photocraft_doc::LayerContent::Raster(_)) - && layer.visible - && layer.opacity >= 1.0 - && layer.fill_opacity >= 1.0 - && layer.mask.is_none() - && layer.vector_mask.is_none() - && layer.effects.items.is_empty() - && layer.effects.psd_raw.is_none() - && matches!(layer.blend, photocraft_color::BlendMode::Normal | photocraft_color::BlendMode::PassThrough) - && photocraft_compose::channel_weights(layer, doc.mode).is_none() - && !photocraft_compose::blend_if_active(layer, doc.mode) => - { - Some(layer) - } - _ => None, - } -} - -/// Encode a document: (file bytes, warnings about anything approximated or dropped). -pub type ExportFn = Box Result<(Vec, Vec), String>>; -pub type WriteFn = Box Result<(), String>>; -/// What a file on disk looked like when a document last read or wrote it: File › Save asks -/// before replacing a file another app changed since (#6596). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct FileStamp { - pub len: u64, - pub modified: Option, -} -/// The [`FileStamp`] of the file at a path, `None` when it can't be read. -pub type FileStampFn = Box Option>; -/// Whether two paths name one entry in one folder on disk; false when either can't be read. -pub type SameFileFn = Box bool>; -/// Encode a document and write it to a path, reporting the stage to the job; returns the export -/// warnings. Runs on a worker thread (see [`Services::save_file`]). It must call -/// [`jobs_ui::SaveCtl::commit`] right before replacing the file, and write nothing if that fails. -pub type SaveFileFn = std::sync::Arc Result, String> + Send + Sync>; - -/// The revision a document counts as saved at after `written` went to its writer: that one when -/// the writer confirms the bytes were stored, else still `previous`, so the document stays -/// unsaved. A browser download is only a request the user can cancel (#4962). -pub(crate) fn saved_revision_after_write(confirmed: bool, written: u64, previous: u64) -> u64 { - if confirmed { written } else { previous } -} - -/// Who a finished save serves. -#[derive(Clone, Copy)] -pub(crate) enum SaveKind { - /// Interactive: arm the document's file and fire user-configured hooks. - User, - /// Automation: flat formats stay copies (#2579) and hooks never fire. - Automation, -} -/// Read bytes through the desktop control session's authorized read root. -pub type AutomationReadFn = Box Result<(String, Vec), String>>; -/// Write bytes through the desktop control session's authorized write root. -pub type AutomationWriteFn = Box Result<(), String>>; -/// Load a directory-form `.pcraft` through the authorized read root, returning its display -/// name (the file name) and the loaded document. `Ok(None)` marks a regular file: the -/// caller falls back to the bytes path for the zip form. -pub type AutomationOpenPcraftFn = Box Result, String>>; -/// Reject engine commands which still perform ambient filesystem I/O. -pub type AutomationCommandFn = Box Result<(), String>>; -/// Open a URL in the system browser (native) — reliable cross-platform, unlike `ctx.open_url`. -pub type OpenUrlFn = Box Result<(), String>>; -pub type EncodePngFn = Box Result, String>>; -/// Put an RGBA8 image (width, height, pixels) on the OS clipboard. -pub type ClipboardSetFn = Box Result<(), String>>; -/// Read an RGBA8 image from the OS clipboard. `Ok(None)` means no image is available; -/// `Err` means the contents could not be read and must not invalidate the internal copy. -pub type ClipboardGetFn = Box Result)>, String>>; -/// Whether the last clipboard read found no way to reach the OS clipboard at all. -pub type ClipboardUnreadableFn = Box bool>; -/// Shared queue of (file name, bytes) delivered asynchronously. -pub type Inbox = std::sync::Arc)>>>; -/// Read the saved preferences text (`None` when there is none yet). -pub type LoadTextFn = Box Option>; -/// Persist the preferences text. -pub type SaveTextFn = Box Result<(), String>>; -/// Platform appearance when egui cannot detect it (for example, Wayland without a theme event). -pub type SystemThemeFn = Box Option>; -/// Autosave a document snapshot for crash recovery: (snapshot, revision, original path). -pub type AutosaveFn = Box, u64, Option<&str>) -> Result<(), String>>; -/// Poll successful or failed background writes: (document id, revision, result). -pub type AutosaveResultsFn = Box Vec<(u64, u64, Result<(), String>)>>; -/// Drop the recovery data of a document (by `DocId` value) once it is saved or closed. -pub type DiscardAutosaveFn = Box; -/// List recoverable documents without decoding them. Their data stays until the documents are -/// saved or closed; the shell runs each entry's loader on a background worker. -pub type RecoverFn = Box Vec>; -/// Photoshop's own keyboard shortcut set on this machine, as (source path, `.kys` XML text): -/// the newest install's live `Keyboard Shortcuts.psp` on the desktop, `None` without one. -pub type PhotoshopShortcutsFn = Box Option<(String, String)>>; -/// A recovered document (by `DocId` value, once open) takes over its recovery entry (by key): -/// its autosaves replace the entry, and saving or closing it drops the entry. -pub type AdoptAutosaveFn = Box; - -/// A recovery entry [`RecoverFn`] found; its loader owns only the data it needs to read. -pub struct Recoverable { - /// The recovery entry to adopt once loading succeeds (see [`AdoptAutosaveFn`]). - pub key: String, - pub name: String, - /// Where the user last saved it, if anywhere. - pub path: Option, - pub load: Box Result + Send + 'static>, -} -/// Append text to a file (History Log). -pub type AppendTextFn = Box Result<(), String>>; -/// Requests from the operating system since the last call (see [`OsEvent`]). -pub type OsEventsFn = Box Vec>; -/// Ends the app the platform's own way (see [`Services::quit`]). -pub type QuitFn = Box; -/// Where the OS pointer is now, in egui points within the window; `None` when unknown. -pub type CursorPosFn = Box Option>; -/// Whether Caps Lock is toggled on, read from the OS. `None` where the platform cannot -/// report it (native Wayland): the cursor then follows the cursor preference (#1758). -pub type CapsLockFn = Box bool>; -/// Keeps an undecorated window's OS frame from offsetting its content and pointer (#2246). -/// Called once per frame; `None` when the window is decorated or the platform needs no fixing. -pub type WindowFrameFn = Box; -/// The caption buttons' current style ([`Services::caption_style`]). -pub type CaptionStyleFn = Box CaptionStyle>; -/// Physical right mouse button or stylus barrel button down (Windows; read for brush resize). -pub type RightButtonDownFn = Box bool + Send + Sync>; - -/// Platform services injected by the app binary (file dialogs, codecs), keeping this crate free of -/// I/O dependencies. -#[derive(Default)] -pub struct Services { - /// User-initiated desktop/browser pixel sampling. - pub screen_pick: Option, - /// Decode a file's bytes into a document (PSD, PNG, JPEG, …). - pub import: Option, - /// Encode a document for a file name (format chosen by extension). - pub export: Option, - /// Background save over the automation write authority (`app.save`, #2017): same worker - /// contract as `save_file`, but the bytes go through the capability-scoped workspace. - pub automation_save: Option, - /// Show an Open or Save dialog without waiting for it (see `file_dialog`). - pub file_dialog: Option, - /// Write bytes to a path (native) or trigger a download (web). - pub write: Option, - /// Size and modification time of a file (native); `None` on the web, where Save never - /// writes back to a file. - pub file_stamp: Option, - /// Whether two paths name one entry in one folder (native): a save dialog's answer and the - /// path the save writes to after Lowercase Extension, on a file system that ignores letter - /// case. A hard link is another entry. A save asks before replacing an entry it finds - /// different (`replace_prompt`). - pub same_file: Option, - /// `write` only asks for the bytes to be kept (a browser download, which the user can - /// cancel and which reports nothing back), so a save through it names the document but - /// leaves its changes unsaved and the leave-page guard armed (#4962). - pub write_unconfirmed: bool, - /// Encode and write in one step on a worker thread, so a large save doesn't freeze the - /// window (#2017). With background jobs on, saves use it instead of `export` and `write`. - pub save_file: Option, - /// File access used only by control/MCP requests. Interactive dialogs keep - /// using `file_dialog` and `write` with the user's authority. - pub automation_read: Option, - pub automation_write: Option, - pub automation_open_pcraft: Option, - pub automation_command: Option, - /// Same policy as [`Self::automation_command`], as a function pointer the engine calls for - /// each step of `actions.play`. Installed on the session only while a control request or - /// an automation-driven [`PhotocraftApp::run`] runs, so a local play of a recorded `file.*` step still works. - pub automation_authorize: Option photocraft_engine::Result<()>>, - /// Encode an RGBA8 image as PNG (used for screenshots and `ui.render`). - pub encode_png: Option, - /// Open a URL in the system browser (native). Falls back to `ctx.open_url` (web) when unset. - pub open_url: Option, - /// Preferences ▸ General ▸ Beep When Done: the platform's default beep, played when a - /// background job finishes successfully. `None` in the web build (and in tests). - pub beep: Option, - /// Starts a background check for published releases (desktop, outside Flatpak). - pub check_updates: Option, - /// Files delivered asynchronously (web drag-and-drop): drained every frame and opened as - /// documents. - pub inbox: Option, - /// Files delivered asynchronously for a drop onto the active document's canvas (web - /// drag-and-drop, routed by [`PhotocraftApp::dropped_on_canvas`]): placed as layers like a - /// desktop canvas drop (Place Embedded, each in Free Transform). - pub place_inbox: Option, - /// OS clipboard images: copies go out, screenshots and images from other apps come in. - pub clipboard_set_image: Option, - pub clipboard_get_image: Option, - /// True when the last `clipboard_get_image` read had no clipboard to read, as in a Flatpak on - /// Wayland (#5031), rather than a clipboard that holds no image. `None` where that can't happen. - pub clipboard_unreadable: Option, - /// Preferences persistence: the platform config directory on native, browser storage on - /// the web (see `prefs_ui`). - pub load_prefs: Option, - pub save_prefs: Option, - /// Photoshop's live keyboard shortcut set, imported once at first launch (`kys_import`). - pub photoshop_shortcuts: Option, - pub system_theme: Option, - /// The native window is connected directly to a Wayland compositor. - pub is_wayland: bool, - /// On Wayland, the shell command that starts this install under XWayland, where native file - /// drops work (#386); `None` when there is no X server to run it on. - pub xwayland_command: Option, - /// Crash-recovery autosave (Preferences › File Handling) and recovery at launch. - pub autosave: Option, - /// None for services that report synchronous success through `autosave`. - pub autosave_results: Option, - /// Finish every queued crash-recovery autosave and wait for it, with outcomes like - /// `autosave_results`. For a session that ends without asking: the window's graphics device - /// was lost (see `gpu_status::check_window`). - pub flush_autosaves: Option, - pub discard_autosave: Option, - pub recover: Option, - pub adopt_autosave: Option, - /// History Log text file output. - pub append_text: Option, - /// OS requests (macOS open-documents / quit Apple events), polled every frame. - pub os_events: Option, - /// The pointer position read from the OS (desktop) or from the page's drag events (web): - /// file drops carry none, and the window gets no pointer events during an OS drag (see - /// `file_open::DropTarget`). - pub cursor_pos: Option, - /// Caps Lock toggled on (desktop; `None` on Wayland and the web). Read once per frame, so - /// the canvas can show the precise crosshair for painting tools, whatever the preference. - pub caps_lock: Option, - /// Keeps the undecorated window borderless, so the content and the pointer stay aligned - /// (Windows custom title bar, #2246). Called once per frame; `None` when the window is - /// decorated or the platform needs no fixing. - pub window_frame: Option, - /// How the custom title bar's caption buttons look and where they sit (Linux: the desktop's - /// style and button layout). Read every frame, with the context to wake when it changes; - /// `None` keeps Windows' buttons at the right end. - pub caption_style: Option, - /// Physical right mouse button or pen barrel button currently down. - pub right_button_down: Option, - /// The persistent brush preset store, loading in the background (desktop; see - /// `photocraft_engine::preset_store`). Attached to the session once it arrives; without - /// one, brush presets are session-only unless the shell attached a store before startup. - pub preset_store: Option>, - /// Reads the displays and their ICC profiles in the background (desktop macOS; see - /// `monitor_status`). Without one, the canvas uses the profile chosen in Color Settings, or sRGB. - pub read_displays: Option, - /// The macOS menu bar, when the desktop app installed one; the in-window menus are hidden then. - pub native_menu: Option, - /// Ends the app once leaving is settled (nothing unsaved, or the prompt answered), instead of - /// letting eframe close the window. macOS: `-[NSApplication terminate:]`. Closing the window - /// while AppKit's run loop is still going crashes or hangs Touch Bar Macs (#1575, #1458). - /// Without one, eframe closes the window and the app ends with it. - pub quit: Option, -} +use app::read_dropped; +#[cfg(test)] +use app::layer_thumb_frame; +pub use app::surface_fingerprint; +pub(crate) use app::{adjustment_layer_active, remember_new_document}; +#[cfg(test)] +pub(crate) use services::saved_revision_after_write; +pub use services::{AdoptAutosaveFn, AppendTextFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, CaptionStyleFn, ClipboardGetFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn, ExportSettings, FileStamp, FileStampFn, FormatChoices, ImportFn, Inbox, LoadTextFn, OpenUrlFn, OsEventsFn, PhotoshopShortcutsFn, QuitFn, Recoverable, RecoverFn, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, WindowFrameFn, WriteFn}; +pub(crate) use services::SAVE_OPTIONS_OPEN; /// The Info panel's cached sample: pixel x, y, document revision and Eyedropper Sample Size. type InfoSampleKey = (i32, i32, u64, u32); @@ -1063,2522 +669,6 @@ impl SyntheticTarget { } } -impl PhotocraftApp { - pub fn new(mut session: Session, mut services: Services) -> Self { - session.updates.check = services.check_updates.take(); - let mut app = Self { - session, - ui: UiState::default(), - services, - canvases: HashMap::new(), - navigator_textures: HashMap::new(), - display_memo: HashMap::new(), - navigator_gpu: HashMap::new(), - navigator_plain: std::collections::HashSet::new(), - info_samplers: None, - monitors: Default::default(), - checker: None, - drag: None, - move_blocked: false, - tool_override: None, - live_stroke: None, - committed_stroke: None, - retouch_from_live: false, - trail: None, - remove_pending: Vec::new(), - remove_pending_target: None, - remove_trail: None, - menu_cache: None, - move_preview: None, - move_hover: None, - move_distance: None, - object_finder: None, - blend_preview: None, - reorder_preview: None, - reorder_preview_hit: false, - patch_preview: None, - cam_preview: None, - magnetic: Default::default(), - secondary_erase: false, - held_erase: false, - defer_live_stroke: false, - press_stroke: false, - last_stroke_end: None, - brush_resize: None, - quick_pick: false, - brush_resize_armed: false, - alt_sampling: false, - mixer_sampling: false, - caps_lock: false, - opacity_keys: None, - control_rx: None, - captures: screenshot::Captures::default(), - type_ime: type_tool::ImeState::default(), - input_waiters: Vec::new(), - live_adjust: None, - frame: 0, - notices_hovered: false, - styled: false, - integrated_titlebar: false, - custom_titlebar: false, - last_window_title: String::new(), - fonts_ready: false, - last_canvas_rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)), - arrange_start: 0, - ppp: 1.0, - drop_canvas_rect: None, - tab_strip: None, - drop_places: Default::default(), - view_docs: Vec::new(), - fps: 0.0, - last_frame_time: 0.0, - thumbs: HashMap::new(), - thumb_frames: HashMap::new(), - snapshot_thumbs: HashMap::new(), - thumb_documents: Vec::new(), - bounds_cache: HashMap::new(), - proxy: None, - proxy_uploaded: None, - outline_cache: None, - filter_preview: None, - smart_filter_targets: Default::default(), - #[cfg(not(target_arch = "wasm32"))] - filter_preview_worker: Default::default(), - redraws: Default::default(), - kept: Default::default(), - color_range: None, - adjust_preview: None, - live_adjust_preview: None, - synthetic: Vec::new(), - synthetic_batch: None, - synthetic_reinject: false, - synthetic_snapshot: None, - automation_input: false, - paused_playbacks: Default::default(), - channel_thumbs: None, - channel_views: HashMap::new(), - type_layout: None, - type_clicks: None, - type_transform_preview: None, - type_font_preview: None, - guide_drag: None, - layer_box: None, - crop: Default::default(), - pcrop: Default::default(), - hover_doc: None, - hover_layer: None, - canvas_hover_layer: None, - clone_preview: None, - info_sample: None, - os_clip_sig: None, - clip_unmirrored: true, - clip_external: false, - clip_read_for_paste: false, - transform_preview: None, - move_mods: Default::default(), - nudge_bundle: Default::default(), - style_preview: None, - text_style_preview: None, - solid_fill_preview: None, - pattern_fill_preview: None, - shape_fill_preview: None, - distort: Default::default(), - gradient: Default::default(), - camera_raw: None, - pending_raw_open: None, - raw_redevelop: Vec::new(), - wide_angle: None, - dialog_edits: Default::default(), - pending_after_prompt: None, - tone_hist: None, - doc_hist: None, - doc_hist_preview: None, - hist_job: None, - hist_uncached: None, - gpu: None, - window_device: None, - window_lost: false, - window_recovery_retry: None, - gpu_render_state: None, - gpu_fault: None, - gpu_oom_retries: 0, - started: None, - perf: Default::default(), - stroke_trace: stroke_trace::StrokeTrace::from_env(), - prefs_rt: Default::default(), - updates_rt: Default::default(), - discard: None, - file_dialog: None, - tiff_options: None, - save_dirs: HashMap::new(), - disk_stamps: HashMap::new(), - targa_options: None, - jpeg_options: None, - dds_options: None, - held_opens: Default::default(), - allow_close: false, - stylus: Default::default(), - control_click: Default::default(), - background_jobs: false, - min_frame_ms: None, - last_frame_start_ms: 0.0, - jobs: Default::default(), - #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] - live_tokens: theme::live::LiveTokens::from_env(), - }; - // Saved preferences are in place before the first frame; recovery starts in upkeep. - prefs_ui::load(&mut app); - layers_panel_ui::restore_options(&mut app); - histogram_panel::restore_options(&mut app); - // After the saved preferences, which say whether the set was already offered. - kys_import::offer_import(&mut app); - notices::wayland_file_drop_guidance(&mut app); - // File › Scripts › Script Events Manager: "Start Application". - photocraft_engine::automate_cmds::fire_event(&mut app.session, "startApplication"); - app - } - - /// Draw the document canvas on the GPU (custom WGSL shader) instead of via egui textures. - /// Call from the app creator with `cc.wgpu_render_state`; without it the CPU path is used. - pub fn set_wgpu(&mut self, rs: eframe::egui_wgpu::RenderState) { - // Preferences › Performance › cache tile size (PHOTOCRAFT_GPU_TILE still overrides). - let tile = self.session.prefs().performance.cache_tile_size; - // Escaped driver/setup panics must leave the session and CPU canvas alive. - self.perf.gpu_info.set_adapter(&rs.adapter.get_info()); - // The browser has no adapter list (egui-wgpu only has it natively). - #[cfg(not(target_arch = "wasm32"))] - self.perf.gpu_info.set_available(&rs.available_adapters); - self.gpu_render_state = Some(rs.clone()); - let gpu = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| gpu_canvas::GpuCanvas::with_tile(&rs, Some(tile)))) { - Ok(gpu) => gpu, - Err(payload) => { - let detail = payload - .downcast_ref::() - .cloned() - .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string())) - .unwrap_or_else(|| "GPU canvas initialization failed".into()); - self.perf.gpu_info.canvas = "cpu".into(); - self.perf.gpu_info.fallback = Some(detail.clone()); - gpu_status::queue_fallback_notice(self, detail); - self.watch_window_device(&rs.device); - return; - } - }; - self.perf.gpu_info.canvas = "gpu".into(); - self.window_device = Some((rs.device.clone(), gpu.health().clone())); - self.gpu = Some(gpu); - self.prefs_rt.gpu_style = None; - } - - /// Whether the document canvas currently draws on the GPU (false on the CPU path, and after - /// the device was lost). - pub fn gpu_active(&self) -> bool { - self.gpu.is_some() - } - - /// The GPU canvas's device health flag (tests inject faults through it). - pub fn gpu_health(&self) -> Option { - self.gpu.as_ref().map(|g| g.health().clone()) - } - - /// Watch the device the window draws with when the GPU canvas doesn't (the CPU canvas), so - /// its loss is handled like the GPU canvas's (see `gpu_status::check_window`). - pub fn watch_window_device(&mut self, device: &eframe::wgpu::Device) { - self.window_device = Some((device.clone(), photocraft_gpu::DeviceHealth::watch(device))); - } - - /// Whether the window's graphics device was lost, so the app saves its documents for - /// recovery and closes once they are saved (#3438). - pub fn window_lost(&self) -> bool { - self.window_lost - } - - /// Destroy the window's graphics device, as a driver reset does (`ui.gpu.simulateLoss` - /// with `destroy`, tests). Returns whether there was one. - pub fn destroy_window_device(&mut self) -> bool { - self.window_device.as_ref().map(|(device, _)| device.destroy()).is_some() - } - - /// Run `hook` once the app has rendered its first frames (and a document opened at launch - /// has drawn): the desktop app clears its crash-safe GPU startup marker there. - pub fn on_started(&mut self, hook: impl FnOnce(&mut PhotocraftApp) + 'static) { - self.started = Some(Box::new(hook)); - } - - /// Per-frame GPU health check (called from `logic`; tests call it directly): falls back to - /// the CPU canvas after a device loss and runs the started hook. - pub fn check_gpu(&mut self, ctx: &egui::Context) { - gpu_status::check(self, ctx); - } - - /// Attach a control channel (requests arrive from a transport thread: TCP, stdin, tests). - pub fn with_control(mut self, rx: Receiver) -> Self { - self.control_rx = Some(rx); - self - } - - /// Run an engine command, reporting errors in the status bar. - pub fn run(&mut self, id: &str, params: Value) -> Result { - if let Some(result) = delete_layer_prompt::intercept(self, id, ¶ms) { - return result; - } - if let Some(result) = mask_trash_prompt::intercept(self, id, ¶ms) { - return result; - } - // Automation input also gates every step a command runs on its behalf (`actions.play`). - let gate = if self.automation_input && self.session.authorize.is_none() { self.services.automation_authorize } else { None }; - if gate.is_some() { - self.session.authorize = gate; - } - let result = self.run_command(id, params); - if gate.is_some() { - self.session.authorize = None; - } - // An explicit channel target (⌘2, ⌘\, ⌘3…) decides what the Layers panel targets too: - // ⌘2 after the mask was targeted goes back to the layer's pixels. - if result.is_ok() && id.starts_with("channel.target") { - if let Some(t) = self.session.active().map(|st| st.channel_view.target) { - use photocraft_engine::channel_cmds::ChannelTarget; - self.ui.mask_target = t == ChannelTarget::LayerMask; - self.ui.vector_mask_target = t == ChannelTarget::VectorMask; - } - self.sync_mask_targets(); - } - result - } - - fn run_command(&mut self, id: &str, params: Value) -> Result { - if !vector_ui::cancel_stale(self) { - return Err(self.ui.status.clone()); - } - if matches!(id, "paint.setSymmetry" | "paint.symmetryFromPath" | "paint.symmetryDisable") { - self.ui.symmetry_transform = None; - } - let clip_read = std::mem::take(&mut self.clip_read_for_paste); - if self.automation_input - && let Some(authorize) = self.services.automation_command.as_ref() - { - authorize(id, ¶ms)?; - } - // A new layer while Free Transform is open applies the transform first, as Photoshop does - // (#5667): History reads the transform (or Place Embedded), then New Layer. Only for a - // command that can run; a transform refused or still being applied keeps the box open and - // the command doesn't run. - if photocraft_engine::PRECHECKED.contains(&id) && self.ui.transform.is_some() { - // Bad params or a command that can't run leave the box as it is. - self.session.precheck(id, ¶ms).map_err(|e| e.to_string())?; - transform_tool::commit(self); - if transform_tool::committing(self).is_some() { - return Err(tl!("Free Transform is still being applied; try again when it has finished.").into()); - } - if self.ui.transform.is_some() { - return Err(if self.ui.status.is_empty() { tl!("The transform couldn't be applied.").into() } else { self.ui.status.clone() }); - } - } - actions::suspended_guard(self, id)?; - if let Some(result) = panel_docking::command(self, id, ¶ms) { - return result; - } - if let Some(r) = transform_tool::intercept(self, id) { - return r; - } - if let Some(r) = crate::crop_ui::intercept(self, id) { - return r; - } - let t0 = gpu_canvas::now_ms(); - // The OS clipboard is read only on an explicit paste, never in the background (privacy, CPU). - if matches!(id, "edit.paste" | "edit.pasteSpecial.pasteInPlace" | "file.newFromClipboard") { - if !clip_read { - self.import_os_clipboard()?; - } - if self.session.clipboard.is_none() && self.services.clipboard_get_image.is_some() { - if self.services.clipboard_unreadable.as_ref().is_some_and(|unreadable| unreadable()) { - // The clipboard may well hold an image that can't be reached: say why. - notices::clipboard_unreadable(self); - return Ok(serde_json::json!({"pasted": false})); - } - // Enabled on the strength of the OS clipboard, which held no image: a quiet no-op. - let message = "Nothing to paste: the clipboard holds no image"; - self.ui.status = tl!(message).into(); - self.ui.status_error = false; - return Ok(serde_json::json!({"pasted": false})); - } - } - let suppress_events = self.automation_input && self.session.prefs().script_events.enabled; - if suppress_events { - self.session.edit_prefs(|prefs| prefs.script_events.enabled = false); - } - // Long commands become background jobs when enabled (`jobs_ui`); the rest run inline. - let params = self.with_mask_target(id, params); - let params = vector_ui::with_active_path(self, id, params); - let path_mask = vector_ui::takes_path_mask(id) && params.get("path").is_some_and(|v| !v.is_null()); - let on_active_layer = self - .session - .active() - .is_some_and(|st| st.active_layer.is_some_and(|layer| params.get("layer").and_then(Value::as_u64).is_none_or(|target| target == layer.0))); - let creates_active_mask = - matches!(id, "layer.layerMask.revealAll" | "layer.layerMask.hideAll" | "layer.layerMask.revealSelection" | "layer.layerMask.hideSelection") - && on_active_layer; - let creates_active_vector_mask = matches!( - id, - "layer.vectorMask.add" | "layer.vectorMask.fromPath" | "layer.vectorMask.revealAll" | "layer.vectorMask.hideAll" | "layer.vectorMask.currentPath" - ) && on_active_layer; - let r = if id == "actions.play" { - actions::play(self, ¶ms) - } else if photocraft_engine::actions_cmds::shell_view_command(id) { - actions::run_view(self, id, params) - } else { - jobs_ui::run(self, id, params) - }; - let creates_adjustment_or_fill = id.starts_with("layer.newAdjustmentLayer.") || id.starts_with("layer.newFillLayer."); - if r.is_ok() && ADDS_LAYER_MASK.contains(&id) { - // Adding an explicit mask targets it, as in Photoshop (#2166). - self.ui.mask_target = true; - self.ui.vector_mask_target = false; - self.ui.properties_layer = None; - } else if r.is_ok() && creates_adjustment_or_fill { - // Panel Options may suppress a fill layer's default mask. Never target a - // nonexistent mask; an active path creates a vector mask instead. - let masks = self - .session - .active() - .and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))) - .map(|layer| (layer.mask.is_some(), layer.vector_mask.is_some())) - .unwrap_or((false, false)); - self.ui.mask_target = masks.0; - self.ui.vector_mask_target = !masks.0 && masks.1; - // Keep Properties on the new layer contents, as on main (#3369). - self.ui.properties_layer = self.session.active().and_then(|st| st.active_layer).map(|l| l.0); - } - if r.is_ok() && creates_adjustment_or_fill { - // Properties comes to the front, shown and expanded, so the new layer's settings can - // be edited at once, as in Photoshop (#4028). The layer is made whatever happens here. - if self.ui.docking.is_some() { - let _ = panel_docking::command(self, "window.panel.activate", &json!({"panel": "properties"})); - } else { - self.ui.dock_tabs.properties = 0; - dock::reveal(self, dock::Group::Properties); - } - } - // Making a new selection reveals its outline after View > Extras was hidden (#5597). - // These interactive selection commands complete inline; a failed command, deselection, - // or painting inside an existing selection must leave the user's view choice alone. - if r.as_ref().is_ok_and(|v| v.get("changed") != Some(&Value::Bool(false)) && v.get("pending") != Some(&Value::Bool(true))) - && matches!( - id, - "select.rect" - | "select.lasso" - | "select.magneticLasso" - | "select.magicWand" - | "select.quick" - | "select.object" - | "select.loadSelection" - | "select.loadLuminosity" - | "path.toSelection" - ) - && self.session.active().is_some_and(|st| st.doc.selection.is_some()) - { - self.ui.view.extras = true; - } - if r.is_ok() && id == "select.toWorkPath" { - // Make Work Path selects the new work path in the Paths panel, as in Photoshop. - self.ui.selected_path = Some("work".into()); - } - if r.is_ok() && path_mask { - // The new layer's vector mask becomes the active path, as in Photoshop: the path it - // was made from is no longer selected, so the next fill layer isn't masked by it too. - self.ui.selected_path = Some("layer".into()); - } - if r.is_ok() && creates_active_mask { - // Adding a mask selects its thumbnail: the next brush or footer Delete targets it. - self.ui.mask_target = true; - self.ui.vector_mask_target = false; - } - if r.is_ok() && creates_active_vector_mask { - // Likewise a new vector mask (#4728): Properties shows its Density and Feather, and a - // mask made from a path becomes the active path. - self.ui.vector_mask_target = true; - self.ui.mask_target = false; - if matches!(id, "layer.vectorMask.currentPath" | "layer.vectorMask.fromPath") { - self.ui.selected_path = Some("layer".into()); - } - } - if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "edit.copyMerged") { - self.clip_external = false; - self.export_os_clipboard(); - } - self.perf.last_command = id.to_string(); - self.perf.command_ms = gpu_canvas::now_ms() - t0; - match &r { - Ok(_) => { - if self.ui.status_error { - self.ui.status.clear(); - self.ui.status_error = false; - } - self.sync_views(); - let removed = self.session.take_samplers_removed(); - if removed > 0 && !self.ui.status_error { - // A canvas-size change (crop, Canvas Size, Image Size, rotation) dropped Color - // Sampler points that fell outside the new canvas (#1046). - self.ui.status = crate::i18n::trn(crate::i18n::current(), removed as u64, "{n} sample point removed", "{n} sample points removed"); - self.ui.status_error = false; - } - } - Err(e) => { - self.ui.status = e.clone(); - self.ui.status_error = true; - } - } - if suppress_events { - self.session.edit_prefs(|prefs| prefs.script_events.enabled = true); - } - r - } - - /// Keep one view per document, in tab order: a view and its windows stay with their document - /// when tabs move (`document.move`) or close. - /// The tool pointer events go to: a held temporary tool when there is one (⌘ is the Move - /// tool, `hold_keys::cmd_moves`), else the selected tool. - pub fn active_tool(&self) -> state::Tool { - self.tool_override.unwrap_or(self.ui.tool) - } - - pub fn sync_views(&mut self) { - type_transform::cancel_stale(self); - crate::cam_transform::cancel_stale(self); - crate::lasso_ui::cancel_stale(self); - // A polygon under construction belongs to the Polygonal Lasso tool, not the next tool. - if self.ui.tool != Tool::PolygonLasso { - self.ui.polygon.clear(); - self.ui.polygon_mode.clear(); - } - // ... and to the document it was started on. - crate::canvas::polygon_cancel_stale(self); - crate::crop_ui::cancel_stale(self); - crate::distort_ui::cancel_stale(self); - crate::perspective_crop_ui::cancel_stale(self); - // A pen path under construction belongs to the document it was started on too. - vector_ui::cancel_stale(self); - let ids: Vec = self.session.documents().iter().map(|d| d.doc.id).collect(); - // Where the document of view `i` is now. Views not tracked yet keep their index. - let now = |i: usize| match self.view_docs.get(i) { - Some(id) => ids.iter().position(|d| d == id), - None => (i < ids.len()).then_some(i), - }; - let mut views: Vec> = ids.iter().map(|_| None).collect(); - for (i, v) in std::mem::take(&mut self.ui.views).into_iter().enumerate() { - if let Some(slot) = now(i).and_then(|to| views.get_mut(to)) { - *slot = Some(v); - } - } - self.ui.views = views.into_iter().map(Option::unwrap_or_default).collect(); - self.ui.windows.retain_mut(|w| now(w.document).map(|d| w.document = d).is_some()); - if !self.session.prefs().workspace.open_documents_as_tabs { - let new_docs: Vec = ids.iter().enumerate().filter(|(_, id)| !self.view_docs.contains(id)).map(|(i, _)| i).collect(); - for &idx in &new_docs { - if !self.ui.windows.iter().any(|w| w.document == idx) { - crate::view_cmds::float_window(self, idx, idx); - } - } - } - self.canvases.retain(|(doc, _), _| ids.contains(doc)); - self.navigator_textures.retain(|doc, _| ids.contains(doc)); - self.view_docs = ids; - self.prune_thumbs(); - self.sync_mask_targets(); - // Channel-view textures outlive a hidden view (cheap re-show), not their document. - if !self.channel_views.is_empty() { - let docs = self.session.documents(); - self.channel_views.retain(|id, _| docs.iter().any(|d| d.doc.id.0 == *id)); - } - // Commands may close and reopen a preserved-ID document before the next repaint. - canvas::retain_gpu_documents(self); - } - - /// Record `path` as the most-recently-opened file (File › Open Recent): de-duplicated, newest - /// first, capped at Preferences › File Handling › Recent File List Contains. The list lives in - /// the preferences (`fileHandling.recentFiles`), so it survives a restart; `ui.recent_files` - /// mirrors it for the menus and the Home screen. - pub fn push_recent(&mut self, path: &str) { - let cap = self.recent_cap(); - let mut r = self.session.prefs().file_handling.recent_files.clone(); - r.retain(|p| p != path); - r.insert(0, path.to_string()); - r.truncate(cap); - self.ui.recent_files = r.clone(); - self.session.prefs.edit(|p| p.file_handling.recent_files = r); - } - - /// Records a picked type family for the font menu's Recent group, capped by - /// Preferences ▸ Type ▸ Recent Fonts (0 keeps no list), most recent first, de-duplicated. - pub fn note_recent_font(&mut self, family: &str) { - let cap = self.session.prefs().type_.recent_fonts.min(50) as usize; - let r = &mut self.ui.recent_fonts; - r.retain(|f| f != family); - if cap == 0 { - r.clear(); - return; - } - r.insert(0, family.to_string()); - r.truncate(cap); - } - - /// Preferences ▸ Type ▸ Recent Fonts: a smaller cap (or 0) applies to the existing list at - /// once, not only after the next pick. - pub fn sync_recent_fonts(&mut self) { - self.ui.recent_fonts.truncate(self.session.prefs().type_.recent_fonts.min(50) as usize); - } - - /// File › Open Recent › Clear Recent File List. - pub fn clear_recent(&mut self) { - self.ui.recent_files.clear(); - self.session.prefs.edit(|p| p.file_handling.recent_files.clear()); - } - - /// Take one file off the recent list (the Home screen's × or Remove from Recent, #2691). The - /// file stays on disk, and opening it again lists it again. - pub fn remove_recent(&mut self, path: &str) { - self.ui.recent_files.retain(|p| p != path); - self.session.prefs.edit(|p| p.file_handling.recent_files.retain(|r| r != path)); - } - - /// How many recent files to remember ("Recent File List Contains", 0–100). - pub fn recent_cap(&self) -> usize { - self.session.prefs().file_handling.recent_file_count.min(100) as usize - } - - /// Mirror the stored recent-file list into the UI state (after loading the preferences, or - /// when the Preferences dialog or an agent changes the list or its length). Cheap enough to - /// run every frame: a slice comparison of at most 100 paths, no allocation unless it changed. - pub fn sync_recent(&mut self) { - let cap = self.recent_cap(); - let stored = &self.session.prefs().file_handling.recent_files; - let want = stored.get(..cap.min(stored.len())).unwrap_or_default(); - if self.ui.recent_files.as_slice() != want { - self.ui.recent_files = want.to_vec(); - } - } - - /// Open a file's bytes as a new document named `name`; returns the import warnings (also - /// shown to the user). Files from disk go through [`open_file`](Self::open_file), which also - /// remembers the path. Brush and gradient files go to the preset libraries instead. - pub fn open_bytes(&mut self, name: &str, bytes: &[u8]) -> Result, String> { - self.open_bytes_from(name, bytes, None) - } - - /// [`Self::open_bytes`] for a file read from `path` (File › Save writes back there; it goes - /// to Open Recent), when known. - pub(crate) fn open_bytes_from(&mut self, name: &str, bytes: &[u8], path: Option<&str>) -> Result, String> { - if let Some(r) = preset_files_ui::open(self, name, bytes) { - return r.map(|()| Vec::new()); - } - let name = &self.open_name(name); - // Decoded on a worker: a tab with progress appears now, the document when it's ready - // (warnings are shown then). - if self.background_jobs { - jobs_ui::start_open(self, name, path.map(str::to_string), jobs_ui::bytes(bytes))?; - return Ok(Vec::new()); - } - let import = self.services.import.as_ref().ok_or("no importer configured")?; - let opts = photocraft_engine::jobs::import_options(self.session.prefs()); - let (mut doc, warnings, damaged) = if photocraft_io::is_psd(bytes) { - // Read PSD damage as structured information in the same decode, not by - // retrying an error or matching the text of a compatibility warning. - let (r, damaged) = photocraft_io::import_for_open(name, bytes, &opts).map_err(|e| e.to_string())?; - (r.document, r.warnings, damaged) - } else { - let (doc, warnings) = import(name, bytes, &opts)?; - (doc, warnings, false) - }; - // Preferences › Raw Defaults › Resolution, as the engine's open applies it. - photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc); - // Edit › Color Settings policies apply on open; Ask When Opening holds the file back - // until its prompt is answered, and later files wait behind it (`open_prompt`). - // Missing fonts are read from the document itself: it may not be open yet (#4559). - let warnings = file_open::with_missing_fonts_of(&doc, warnings); - // A developed raw has no embedded profile to ask about. - let developed = warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)); - let question = self.session.color.open_question(&doc).filter(|_| !developed); - let wants_raw = camera_raw_ui::wants_open_dialog(self, &warnings); - open_prompt::arrive( - self, - open_prompt::Held { - doc, - read_only: photocraft_io::affinity::is_affinity(bytes), - damage_pending: damaged, - name: name.to_string(), - path: path.map(str::to_string), - warnings: warnings.clone(), - bytes: (wants_raw && path.is_none()).then(|| std::sync::Arc::new(bytes.to_vec())), - slot: None, - question, - policy_applied: false, - }, - ); - Ok(warnings) - } - - /// Open bytes supplied by an authenticated automation client without - /// invoking user-configured script-event paths outside the granted root. - /// Returns the import warnings (also shown to the user). Brush and gradient - /// files go to the preset libraries, as for interactive opens. - pub fn open_automation_bytes(&mut self, name: &str, bytes: &[u8]) -> Result, String> { - let events_enabled = self.session.prefs().script_events.enabled; - if events_enabled { - self.session.edit_prefs(|prefs| prefs.script_events.enabled = false); - } - let result = match preset_files_ui::open(self, name, bytes) { - Some(r) => r.map(|()| Vec::new()), - None => self.import_automation_document(name, bytes), - }; - if events_enabled { - self.session.edit_prefs(|prefs| prefs.script_events.enabled = true); - } - result - } - - /// The document half of [`open_automation_bytes`](Self::open_automation_bytes): no script - /// events and no Color Settings policy (which may read user-configured profile paths). - fn import_automation_document(&mut self, name: &str, bytes: &[u8]) -> Result, String> { - let import = self.services.import.as_ref().ok_or("no importer configured")?; - let opts = photocraft_engine::jobs::import_options(self.session.prefs()); - let (mut doc, warnings) = import(name, bytes, &opts)?; - photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc); - // The caller records the path it read from. - self.session.add_document(doc, None); - if let Some(st) = self.session.active_mut() { - st.source_read_only = photocraft_io::affinity::is_affinity(bytes); - } - self.sync_views(); - self.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]); - self.ui.status_error = false; - notices::io_warnings(self, &crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]), &warnings); - Ok(warnings) - } - - /// Save the active document to `path`, or to a path chosen in the save dialog (which - /// continues on a later frame, see `file_dialog`). Returns `{"path", "warnings"}` (the export - /// warnings are also shown to the user). - pub fn save_as(&mut self, path: Option) -> Result { - self.save_as_with(path, FormatChoices::default()) - } - - /// [`Self::save_as`] with the format choices already made, which skip their prompts: - /// `file.save` and `file.saveAs` with `tgaBits` (no Targa Options), `ddsCompression` or - /// `ddsMipmaps` (no DDS Options), or `quality` or `jpegFormat` (no JPEG Options). - pub fn save_as_with(&mut self, path: Option, choices: FormatChoices) -> Result { - self.save_dialog_flow(path, choices, false) - } - - /// [`Self::save_as_with`]. `plain_save` marks File › Save that had to ask for a file name - /// (a flat file): confirming the document's own file is recorded as a `file.save` step, - /// which writes whichever file the action is played on, not as a Save As to a fixed path. - pub(crate) fn save_dialog_flow(&mut self, path: Option, choices: FormatChoices, plain_save: bool) -> Result { - if self.save_options_open() { - return Err(SAVE_OPTIONS_OPEN.into()); - } - // Edit Contents documents save back into their smart object. - if path.is_none() && self.session.is_enabled("layer.smartObjects.saveContents") { - self.run("layer.smartObjects.saveContents", serde_json::json!({}))?; - return Ok(serde_json::json!({"path": "smart object", "warnings": []})); - } - if let Some(path) = path { - return self.save_to(path, choices); - } - let st = self.session.active().ok_or("no document")?; - // PDN imports default to our native format, which preserves Paint.NET's blend modes; - // Krita imports to OpenRaster, which Krita opens with its layers. - // Other files keep their format only when it can retain their layers. A plain raster - // (including an unlocked transparent PNG) can keep its flat format; editable contents, - // masks and layer appearance settings need a layered format even with just one layer. - let flat = plain_raster(&st.doc).is_some(); - let ext = st.path.as_deref().and_then(|p| std::path::Path::new(p).extension()).map(|e| e.to_string_lossy().to_ascii_lowercase()); - // An OpenRaster file only when it holds the whole document (#3806): else PSD is offered. - let holds_ora = st.path.as_deref().is_some_and(|p| photocraft_engine::file_cmds::holds_at(&st.doc, p)); - let writable = ext.is_some_and(|e| { - matches!(e.as_str(), photocraft_format::EXTENSION | "psd" | "psb" | "tif" | "tiff") - || (e == "ora" && holds_ora) - || (flat && photocraft_codecs::from_extension(&e).is_some_and(|f| f.caps().write)) - }); - let suggested = match &st.path { - Some(p) if writable => p.clone(), - p => { - let source = p.as_deref().unwrap_or(&st.doc.name); - let ext = match photocraft_engine::file_cmds::extension(source).as_deref() { - Some("pdn") => "pcraft", - Some("kra" | "krz") => "ora", - _ => "psd", - }; - std::path::Path::new(source).with_extension(ext).to_string_lossy().into_owned() - } - }; - let doc = st.doc.id; - self.pick_save(&suggested, move |app, path| { - app.with_document(doc, |app| { - let own = app.session.active().and_then(|st| st.path.clone()); - // Confirming the document's own file: ask first if another app changed it (#6596). - if plain_save - && own.as_deref() == Some(path.as_str()) - && let Some(r) = crate::disk_change_prompt::intercept(app, doc, &path, true, choices) - { - return r; - } - let r = app.save_to(path.clone(), choices)?; - if plain_save && own.as_deref() == Some(path.as_str()) { - app.journal_as_plain_save(&path); - } - Ok(r) - }) - }) - } - - /// [`Self::save_as_with`] once the path is known. - pub(crate) fn save_to(&mut self, path: String, choices: FormatChoices) -> Result { - // An RGB Targa asks for its bits per pixel, a DDS texture for its compression, and a JPEG - // for its quality and format, unless the caller chose them; the save continues from the - // prompt (still a copy when it would be one without the prompt), which records the step - // once answered. - if choices.tga_bits.is_none() && targa_options_ui::wants_prompt(self, &path) { - let copy = self.saves_copy(&path, None)?; - targa_options_ui::park(self, path.clone(), copy, "file.saveAs")?; - return Ok(serde_json::json!({"path": path, "warnings": []})); - } - if choices.dds.is_none() && dds_options_ui::wants_prompt(&path) { - let copy = self.saves_copy(&path, None)?; - dds_options_ui::park(self, path.clone(), copy, "file.saveAs")?; - return Ok(serde_json::json!({"path": path, "warnings": []})); - } - if choices.jpeg.is_none() && jpeg_options_ui::wants_prompt(self, &path) { - let copy = self.saves_copy(&path, None)?; - jpeg_options_ui::park(self, path.clone(), copy, "file.saveAs")?; - return Ok(serde_json::json!({"path": path, "warnings": []})); - } - // A layered TIFF asks about its layers first (Preferences › File Handling); the save - // continues from the prompt, which records the step once answered. - if tiff_options_ui::wants_prompt(self, &path) { - tiff_options_ui::park(self, path.clone())?; - return Ok(serde_json::json!({"path": path, "warnings": []})); - } - self.save_as_step(path, None, choices) - } - - /// File › Save back to the document's own file, recorded as a `file.save` step with the - /// Targa, DDS or JPEG answer in `choices` (a replayed or scripted Save of a flat file brings - /// its own). - pub(crate) fn save_in_place(&mut self, path: String, choices: FormatChoices) -> Result { - if self.save_options_open() { - return Err(SAVE_OPTIONS_OPEN.into()); - } - let r = self.write_save(path, None, choices)?; - // JPEG Options are recorded only where they change something - // ([`jpeg_options_ui::plain_save_step`]); the Targa and DDS answers as given. - let mut step = jpeg_options_ui::plain_save_step(choices.jpeg); - FormatChoices { jpeg: None, ..choices }.record(&mut step); - self.session.journal.push(("file.save".into(), step)); - Ok(r) - } - - /// Writes the Save As and journals it as a `file.saveAs` step with its path (and TIFF, - /// Targa, DDS or JPEG answer), so an action being recorded keeps it (#2032). - fn save_as_step(&mut self, path: String, tiff_layers: Option, choices: FormatChoices) -> Result { - let r = self.write_save(path.clone(), tiff_layers, choices)?; - let mut step = serde_json::json!({"path": path}); - if let Some(layers) = tiff_layers { - step["tiffLayers"] = layers.into(); - } - choices.record(&mut step); - self.session.journal.push(("file.saveAs".into(), step)); - Ok(r) - } - - /// Re-label the Save As just journaled for `path` as File › Save (see [`Self::save_dialog_flow`]), - /// keeping its Targa, DDS or JPEG answer so playback writes the file the same way. A save - /// parked behind Targa, DDS or JPEG Options hasn't been journaled yet: it is recorded as - /// File › Save once answered. - pub(crate) fn journal_as_plain_save(&mut self, path: &str) { - let parked = [ - self.targa_options.as_mut().map(|p| (&p.path, &mut p.record)), - self.dds_options.as_mut().map(|p| (&p.path, &mut p.record)), - self.jpeg_options.as_mut().map(|p| (&p.path, &mut p.record)), - ]; - if let Some((_, record)) = parked.into_iter().flatten().find(|(p, record)| p.as_str() == path && **record == "file.saveAs") { - *record = "file.save"; - return; - } - // Only the path goes: a script's format answer stays, so a replay writes the file it is - // played on the same way. Any other answer (TIFF layers) keeps the Save As. - if let Some(last) = self.session.journal.last_mut() - && last.0 == "file.saveAs" - && last.1.get("path").and_then(Value::as_str) == Some(path) - && let Some(step) = last.1.as_object() - && step.keys().all(|k| matches!(k.as_str(), "path" | "tgaBits" | "ddsCompression" | "ddsMipmaps" | "quality" | "jpegFormat")) - { - let mut step = step.clone(); - step.remove("path"); - *last = ("file.save".into(), Value::Object(step)); - } - } - - /// Replays a recorded `file.save` / `file.saveAs` / `file.saveACopy` / `file.export.exportAs` - /// step: no dialog or prompt, and the recorded TIFF, Targa, DDS or JPEG answer (if any) stands - /// in for its prompt. - pub(crate) fn replay_save(&mut self, id: &str, params: &Value) -> Result { - if self.save_options_open() { - return Err(SAVE_OPTIONS_OPEN.into()); - } - if id == "file.save" { - // The file the action is played on: one that holds the whole document, or a flat - // file a recorded Save confirmed in the dialog while the document is still a plain - // raster, so it is never flattened over (#3531, #3806). A flat file's recorded Targa, - // DDS or JPEG answer writes the same way, without asking. - let choices = FormatChoices::from_step(params, id)?; - let st = self.session.active().ok_or("no document")?; - let flat_own = |p: &str| { - !photocraft_engine::file_cmds::saves_in_place(p) - && plain_raster(&st.doc).is_some() - && photocraft_engine::file_cmds::extension(p).is_some_and(|e| photocraft_codecs::from_extension(&e).is_some_and(|f| f.caps().write)) - }; - let path = st.path.clone().filter(|p| photocraft_engine::file_cmds::holds_at(&st.doc, p) || flat_own(p)).ok_or( - "Save writes back only to the document's own PSD, PSB, .pcraft or OpenRaster file (OpenRaster only when it holds everything), or to its own flat file while the document is a single plain layer", - )?; - return self.save_in_place(path, choices); - } - if id == crate::export_dialog::COMMAND { - // Export As has its own settings, its TGA bits included (#7207). - return crate::export_dialog::replay(self, params); - } - let path = params.get("path").and_then(Value::as_str).filter(|p| !p.is_empty()).ok_or("Save As needs a `path`")?; - let choices = FormatChoices::from_step(params, id)?; - if id == "file.saveACopy" { - // A copy: the document keeps its own file and unsaved state, as when recorded (#4373). - let doc = self.session.active().ok_or("no document")?.doc.clone(); - return crate::view_cmds::write_copy(self, &doc, path, choices); - } - self.save_as_step(path.to_string(), params.get("tiffLayers").and_then(Value::as_bool), choices) - } - - /// What a save writes by default under the preferences: File Handling › Image Previews - /// decides whether a PSD/PSB gets its thumbnail, and Maximize PSD and PSB File Compatibility - /// whether it gets its real merged image. Ask When Saving has no dialog here yet, so it saves - /// both, as Photoshop's checkboxes start on. A JPEG or WebP is written the way the active - /// document's file was (its JPEG quality, a WebP lossy at its quality or lossless), as - /// Photoshop's Save and Save As options start there. - pub(crate) fn save_settings(&self) -> ExportSettings { - let file_handling = &self.session.prefs().file_handling; - let previews = file_handling.image_previews != photocraft_engine::prefs::Ask::Never; - let maximize = file_handling.maximize_psd_compatibility != photocraft_engine::prefs::Ask::Never; - let mut settings = ExportSettings { image_previews: previews, psd_maximize_compatibility: maximize, ..ExportSettings::default() }; - if let Some(st) = self.session.active() { - let e = &st.doc.file_encoding; - settings.jpeg_quality = e.jpeg_quality.map(|q| q.clamp(1, 100)); - settings.webp_lossless = e.webp_lossless.unwrap_or(settings.webp_lossless); - settings.webp_quality = e.webp_quality.map(|q| q.min(100)); - settings.document_path = st.path.as_deref().map(std::path::PathBuf::from); - settings.pcraft_cache = Some(st.pcraft_cache.clone()); - } - settings - } - - /// Whether saving the active document to `path` writes a copy. `tiff_layers` is the TIFF - /// Options answer: `Some(false)` discards the layers and saves a copy. - fn saves_copy(&self, path: &str, tiff_layers: Option) -> Result { - // A flat file that can't hold the document (its layers, or the layered file it lives in) - // is written as a copy, as in Photoshop: the document keeps its file, so Save still - // writes the layered original and the edits stay unsaved (#2550). - // An OpenRaster file that can't hold everything (adjustment layers, styles…) is a copy too, - // so the editable document isn't marked saved after losing them (#3806). - let st = self.session.active().ok_or("no document")?; - let tiff = |p: &str| matches!(photocraft_engine::file_cmds::extension(p).as_deref(), Some("tif" | "tiff")); - let holds = photocraft_engine::file_cmds::holds_at(&st.doc, path) || tiff(path); - let lives_layered = st.path.as_deref().is_some_and(|p| photocraft_engine::file_cmds::saves_in_place(p) || tiff(p)); - Ok(tiff_layers == Some(false) || (!holds && (plain_raster(&st.doc).is_none() || lives_layered))) - } - - /// Writes the active document to a known path. `tiff_layers` is the TIFF Options answer: - /// `Some(false)` discards the layers and saves a copy. `choices` are the Targa bits per pixel - /// (`None`: 32 with an alpha channel or transparency, else 24), the DDS options and the JPEG - /// Options. - fn write_save(&mut self, path: String, tiff_layers: Option, choices: FormatChoices) -> Result { - let copy = self.saves_copy(&path, tiff_layers)?; - let settings = choices.apply(ExportSettings { tiff_layers: tiff_layers.unwrap_or(ExportSettings::default().tiff_layers), ..self.save_settings() }); - match self.write_document(path.clone(), &settings, copy)? { - Some((path, warnings)) => Ok(serde_json::json!({"path": path, "warnings": warnings})), - None => Ok(serde_json::json!({"path": path, "warnings": [], "pending": true, "job": self.jobs.last_started.map(|j| j.0)})), - } - } - - /// Encodes the active document with `settings` and writes it to `path`, which becomes the - /// document's path unless saving a copy. A copy leaves the original's path and unsaved - /// changes intact. Returns the path and the export warnings (also shown to the user), or - /// `None` when the save went to a background job (#2017), which finishes it in - /// [`jobs_ui::tick`]. - pub(crate) fn write_document(&mut self, path: String, settings: &ExportSettings, copy: bool) -> Result)>, String> { - if self.background_jobs - && let Some(save) = self.services.save_file.clone() - { - return jobs_ui::start_save(self, path, settings.clone(), copy, save, false); - } - let st = self.session.active().ok_or("no document")?; - let (doc, written, previous) = (st.doc.id, st.revision, st.saved_revision); - let export = self.services.export.as_ref().ok_or("no exporter configured")?; - let (bytes, warnings) = export(&st.doc, &path, settings)?; - let write = self.services.write.as_mut().ok_or("no writer configured")?; - write(&path, &bytes)?; - let revision = saved_revision_after_write(!self.services.write_unconfirmed, written, previous); - self.saved(doc, revision, &path, &warnings, copy); - Ok(Some((path, warnings))) - } - - /// After `saver` was written to `path`, any other open document bound to that file no longer - /// matches it: it loses the file and is marked unsaved, so it can't stay "saved" while its file - /// holds something else, closing it asks first, and its own Save asks for a name instead of - /// writing over the new file (#6597). Paths are compared as files, so another letter case on a - /// case-insensitive volume or a hard link counts. A notice names the documents affected. - pub(crate) fn detach_others_from_file(&mut self, path: &str, saver: DocId) { - let others: Vec<(DocId, String)> = self - .session - .documents() - .iter() - .filter(|st| st.doc.id != saver && st.path.as_deref().is_some_and(|p| photocraft_engine::file_cmds::same_file(p, path))) - .map(|st| (st.doc.id, st.doc.name.clone())) - .collect(); - let mut detached = Vec::new(); - for (id, name) in others { - let done = self.with_document(id, |app| { - let st = app.session.active_mut().ok_or("no document")?; - st.path = None; - // No revision ever equals this, so the document reads as unsaved until saved again. - st.saved_revision = u64::MAX; - Ok(()) - }); - if done.is_ok() { - detached.push(name); - } - } - if detached.is_empty() { - return; - } - let name = file_open::display_name(path); - let title = { - let template = "{name} was saved over from another tab"; - crate::i18n::fmt(tl!(template), &[("name", name.as_str())]) - }; - let lines = detached - .iter() - .map(|doc| { - let template = "\"{doc}\" no longer has a file and is marked unsaved: save it under a new name to keep it"; - crate::i18n::fmt(tl!(template), &[("doc", doc.as_str())]) - }) - .collect(); - notices::post(self, title, lines, false, None); - } - - /// Record a written save of document `doc` as it was at `revision`: its name, path and saved - /// state (unless a copy), the status, script events and the warnings. - pub(crate) fn saved(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool) { - self.saved_inner(doc, revision, path, warnings, copy, SaveKind::User); - } - - /// [`Self::saved`] for automation saves: no user-configured hooks (docs/control-protocol.md). - pub(crate) fn saved_automation(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool) { - self.saved_inner(doc, revision, path, warnings, copy, SaveKind::Automation); - } - - fn saved_inner(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool, kind: SaveKind) { - // Automation: only a layered save becomes the document's file; a flat one is a - // copy, as in the headless server (#2579). - let (hooks, arm) = match kind { - SaveKind::User => (true, true), - SaveKind::Automation => { - let holds = self.session.documents().iter().find(|st| st.doc.id == doc).is_some_and(|st| photocraft_engine::file_cmds::holds_at(&st.doc, path)); - (false, holds) - } - }; - self.ui.status = crate::i18n::fmt(tl!("Saved {name}"), &[("name", path)]); - // The file was written, copy or not: another tab bound to it no longer matches it. - self.detach_others_from_file(path, doc); - if !copy { - // A background save may finish while another document is active (or after its - // document was closed, when there is nothing left to record). - let _ = self.with_document(doc, |app| { - if let Some(st) = app.session.active_mut() - && arm - { - st.saved_to(path.to_string()); - // The job locked the document, but record the revision that was written. - st.saved_revision = revision; - app.remember_stamp(doc, path); - } - // "Save Document" script events and File › Generate › Image Assets. - if hooks - && let Some(i) = app.session.active_index() - && let Some(r) = photocraft_engine::automate_cmds::document_saved(&mut app.session, i) - { - let template = "Saved {path}; image assets: {n} in {dir}"; - app.ui.status = crate::i18n::fmt( - tl!(template), - &[("path", path), ("n", &r["files"].as_array().map_or(0, Vec::len).to_string()), ("dir", r["dir"].as_str().unwrap_or(""))], - ); - } - Ok(()) - }); - // The file the document now lives in goes to the top of Open Recent and the Home - // screen, as opening it does (#4400). Automation saves don't touch the user's list. - if hooks { - self.push_recent(path); - } - } else if self.disk_stamps.get(&doc).is_some_and(|(own, _)| own == path) { - // A copy written over the document's own file is this app's change too. - self.remember_stamp(doc, path); - } - self.ui.status_error = false; - let what = crate::i18n::fmt(tl!("Saved {name}"), &[("name", file_open::display_name(path).as_str())]); - notices::io_warnings(self, &what, warnings); - self.sync_views(); - } - - /// Note how `doc`'s own file at `path` looks now that the document read or wrote it. - pub(crate) fn remember_stamp(&mut self, doc: photocraft_doc::DocId, path: &str) { - match self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)) { - Some(now) => self.disk_stamps.insert(doc, (path.to_string(), now)), - None => self.disk_stamps.remove(&doc), - }; - } - - /// Another app changed `doc`'s own file at `path` since the document was opened from it or - /// last saved to it. A file that is gone, or one never stamped, counts as unchanged. - pub(crate) fn changed_on_disk(&self, doc: photocraft_doc::DocId, path: &str) -> bool { - let Some((own, then)) = self.disk_stamps.get(&doc) else { return false }; - own == path && self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)).is_some_and(|now| now != *then) - } - - /// TIFF, Targa, DDS or JPEG Options is waiting on an answer before a save is written. - pub(crate) fn save_options_open(&self) -> bool { - self.tiff_options.is_some() || self.targa_options.is_some() || self.dds_options.is_some() || self.jpeg_options.is_some() - } - - /// Writes a save that waited on a format prompt (Targa, DDS or JPEG Options) once answered: - /// journals `step` as its command (`file.saveAs` for Save As, `file.saveACopy` for Save a - /// Copy, `file.save` for a plain Save), so an action being recorded keeps it with this answer - /// (#2032, #4373), reports a failure in the status bar, and releases a close prompt waiting on - /// the save. - pub(crate) fn write_answered_save(&mut self, ctx: &egui::Context, doc: DocId, path: String, settings: &ExportSettings, copy: bool, step: (&str, Value)) { - let written = self.with_document(doc, |app| app.write_document(path, settings, copy)); - if written.is_ok() { - self.session.journal.push((step.0.into(), step.1)); - } - match written { - Err(e) => { - self.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]); - self.ui.status_error = true; - } - Ok(Some(_)) if !copy => crate::discard_ui::saved_document(self, ctx, doc), - // A background save releases the close prompt when it finishes (`jobs_ui`). - Ok(_) => {} - } - } - - /// A print worker may still be handing a job to the system queue. - pub(crate) fn printing(&self) -> bool { - self.session.jobs().iter().any(|j| matches!(j.command.as_str(), "file.print" | "file.printOneCopy")) - } - - /// A save is running in the background. - pub(crate) fn saving(&self) -> bool { - !self.jobs.saves.is_empty() - } - - /// Save through the control session's capability-scoped writer. No file - /// picker or ambient writer is reachable from this path. Returns the path - /// written and the export warnings (also shown to the user). - pub fn save_automation(&mut self, path: Option) -> Result { - self.save_automation_with(path, FormatChoices::default()) - } - - /// [`Self::save_automation`] writing with the format `choices` given (a Targa's `None`: 32 - /// with an alpha channel or transparency, else 24; a DDS texture's: uncompressed without - /// mipmaps; a JPEG's: the file's own quality, Baseline). Automation saves never prompt. - pub fn save_automation_with(&mut self, path: Option, choices: FormatChoices) -> Result { - let target = { - let state = self.session.active().ok_or("no document")?; - // As File › Save: without `path` only a layered file is written back (#416). - path.or_else(|| state.path.clone().filter(|p| photocraft_engine::file_cmds::holds_at(&state.doc, p))).ok_or( - "pass `path`: a save without one writes back only to the document's own PSD, PSB, .pcraft or OpenRaster file, and to OpenRaster only when it holds everything (adjustment layers, styles and masks don't fit)", - )? - }; - let reply = |path: &str, warnings: &[String]| json!({"path": path, "warnings": warnings}); - // Only the target is granted: a linked smart object's stored path is document data, so - // PSD export writes that layer as pixels instead of embedding the file. - let settings = ExportSettings { read_linked_files: false, ..choices.apply(self.save_settings()) }; - // #2017: the File › Save worker path, so the encode doesn't block the frame loop. - if self.background_jobs - && let Some(save) = self.services.automation_save.clone() - { - return match jobs_ui::start_save(self, target.clone(), settings, false, save, true)? { - Some((path, warnings)) => Ok(reply(&path, &warnings)), - None => { - let job = self.jobs.last_started; - Ok(json!({"path": target, "job": job, "pending": true, "warnings": []})) - } - }; - } - let state = self.session.active().ok_or("no document")?; - let (doc, revision) = (state.doc.id, state.revision); - let export = self.services.export.as_ref().ok_or("no exporter configured")?; - let (bytes, warnings) = export(&state.doc, &target, &settings)?; - let write = self.services.automation_write.as_mut().ok_or("automation write authority is not configured")?; - write(&target, &bytes)?; - self.saved_automation(doc, revision, &target, &warnings, false); - Ok(reply(&target, &warnings)) - } - - fn drain_control(&mut self, ctx: &egui::Context) { - let Some(rx) = self.control_rx.take() else { return }; - while let Ok(req) = rx.try_recv() { - let reply = req.reply.clone(); - if req.deadline.is_some_and(|deadline| std::time::Instant::now() >= deadline) || !req.dispatch.start() { - let _ = reply.send(serde_json::json!({"ok": false, "error": control::expired_error()})); - continue; - } - match control::handle(self, ctx, &req) { - control::Outcome::Done(v) => { - let _ = reply.send(v); - } - control::Outcome::AfterInput => self.input_waiters.push(reply), - control::Outcome::AfterJob(job) => self.jobs.waiters.push((job, reply)), - control::Outcome::Screenshot { token, path } => { - // Admission is budgeted here, after this pass's completed captures were - // drained, so a just-finished request never causes a false rejection. - let settle = screenshot::settle_ms(ctx.global_style().animation_time); - let document = self.document_identity(); - if let Err((reply, e)) = self.captures.admit(token, path, reply, document, settle, screenshot::now()) { - let _ = reply.send(serde_json::json!({"ok": false, "error": e})); - } - } - } - // `ui.set` may have changed the edit target: the next request sees its colours. - self.sync_mask_targets(); - } - self.control_rx = Some(rx); - } - - /// The active document's identity at admission: a queued capture never applies to another - /// document. Includes the revision so a saved image is attributable to a known state. - fn document_identity(&self) -> Option { - self.session.active().map(|st| screenshot::DocumentId { document: st.doc.id.0, revision: st.revision, generation: self.session.active_generation() }) - } - - /// Issue due screenshot requests. UI phase only: settling counts real layout passes, and the - /// geometry epoch is that of the pass the image will be rendered from. - fn issue_captures(&mut self, ctx: &egui::Context) { - // A discarded pass (popup sizing, `request_discard`) will be re-run: capture only a pass - // whose UI state will actually be present. - if ctx.will_discard() { - return; - } - let now = screenshot::now(); - let doc = self.document_identity(); - let finished = self.captures.issue(ctx, now, doc, |callback| screenshot::send_command(ctx, callback)); - self.finish_captures(finished); - } - - /// Collect callbacks and expire requests. Logic phase; the image is encoded and written here, - /// on the UI thread, never inside the callback. - fn drain_captures(&mut self, ctx: &egui::Context) { - let now = screenshot::now(); - let doc = self.document_identity(); - // begin_pass supplies the new RawInput before App::logic; run_logic refreshes native - // viewport metadata too. Observe it before any completed callback can be delivered. - let current = screenshot::CaptureGeometry::current(ctx, doc); - self.captures.note_geometry(current); - let observed = self.captures.last_geometry(); - let finished = self.captures.drain(now, observed, doc); - self.finish_captures(finished); - } - - fn finish_captures(&mut self, finished: Vec) { - for f in finished { - let reply = match f.result { - Ok(image) => { - let [w, h] = image.size; - // The encoder takes RGBA bytes; its copy is bounded by the same per-image - // reservation as the retained image, and the image itself is released first. - match w.checked_mul(h).and_then(|n| n.checked_mul(4)) { - Some(bytes) if bytes <= screenshot::MAX_IMAGE_BYTES => { - let rgba: Vec = image.pixels.iter().flat_map(|c| c.to_array()).collect(); - drop(image); - control::save_screenshot_rgba(self, w, h, &rgba, f.path.as_deref()) - } - _ => serde_json::json!({ - "ok": false, - "error": format!( - "screenshot {} failed: the image exceeds the {} MiB encode budget", - f.token, - screenshot::MAX_IMAGE_BYTES / (1 << 20) - ), - }), - } - } - Err(e) => serde_json::json!({"ok": false, "error": e}), - }; - if let Some(tx) = f.reply { - let _ = tx.send(reply); - } - } - } -} - -impl PhotocraftApp { - /// Wait out the rest of [`Self::min_frame_ms`] since the last frame started. - fn cap_frame_rate(&mut self) { - #[cfg(not(target_arch = "wasm32"))] - if let Some(min) = self.min_frame_ms.filter(|m| m.is_finite() && *m > 0.0) { - let wait = min.min(100.0) - (gpu_canvas::now_ms() - self.last_frame_start_ms); - if wait > 0.0 { - std::thread::sleep(std::time::Duration::from_secs_f64(wait / 1000.0)); - } - } - self.last_frame_start_ms = gpu_canvas::now_ms(); - } -} - -impl PhotocraftApp { - /// Install the callback-mode markers in an app creator, before the first `run_ui` on this - /// Context (and again through [`Self::setup_context`] when a host replaces its Context). - /// Installing while a pass is already running cannot mark that pass; it only arms the next. - pub fn install_type_reset_hooks(ctx: &egui::Context) { - type_tool::install_reset_hooks(ctx); - } - - /// The host's UI tail, after all panels and any shell-side model/focus mutations. - pub fn finish_type_reset_pass(&mut self, ctx: &egui::Context) { - type_tool::finish_reset_pass(self, ctx); - } - - /// The host's logic tail; full UI passes leave availability to their later UI tail. - pub fn finish_type_reset_logic(&mut self, ctx: &egui::Context) { - type_tool::finish_reset_logic(self, ctx); - } - - /// Shared logic body. A wrapping host owns the final reset tail after its own work. - pub fn logic_frame(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { - self.cap_frame_rate(); - i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language)); - // Caps Lock state read from the OS once per frame (see `Services::caps_lock`): the canvas - // cursor block needs it before the frame renders. `None` (Wayland/web) keeps `false`. - self.caps_lock = self.services.caps_lock.as_mut().is_some_and(|f| f()); - tool_cursor::set_wayland(ctx, self.services.is_wayland); - if !self.styled { - Self::setup_context(ctx, self.ui.theme); - self.styled = true; - } else { - self.fonts_ready = true; - } - self.frame += 1; - let now = ctx.input(|i| i.time); - let dt = (now - self.last_frame_time) as f32; - if dt > 0.0 { - self.fps = self.fps * 0.9 + (1.0 / dt).min(240.0) * 0.1; - } - self.last_frame_time = now; - self.sync_views(); - crate::type_font_preview::follow_hover(self, ctx); - self.check_gpu(ctx); - #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] - if self.live_tokens.poll(ctx, self.ui.theme) { - self.checker = None; - } - // Finish or expire outstanding captures first, so a new request admitted in this pass - // sees their released budget. - self.drain_captures(ctx); - self.drain_control(ctx); - native_menu::run(self, ctx); - // Switching tools commits, also between the Type and Type Mask tools. - if self.ui.text_edit.as_ref().is_some_and(|ed| !self.ui.tool.is_type() || ed.mask != self.ui.tool.is_type_mask()) { - type_tool::commit(self); - } - // So does selecting another layer or document by any route (#6483). - type_tool::end_if_left(self); - if self.ui.pen.as_ref().is_some_and(|p| !p.drawn_with(self.ui.tool)) { - vector_ui::pen_commit(self, false); - } - transform_tool::end_if_left(self); - shape_stroke_ui::sync_editor(self, ctx); - prefs_ui::tick(self, ctx); - updates_ui::tick(self, ctx); - monitor_status::poll_frame(self, ctx, frame); - // Control requests and persisted preferences can change the language in this frame. - i18n::sync_context(ctx, &self.session.prefs().interface.language); - type_tool::sync_font_names(ctx, self.session.prefs().type_.show_font_names_in_english); - // A window bigger than its display (1440 × 900 on 1366 × 768) runs under the taskbar: - // maximize it into the work area once (#315). - work_area::fit_window(ctx); - discard_ui::guard_window_close(self, ctx); - // Background jobs: apply finished ones, keep frames coming, Esc cancels (before the - // shortcuts see Esc). - if !screen_picker::tick(self, ctx) { - jobs_ui::tick(self, ctx); - #[cfg(not(target_arch = "wasm32"))] - filter_preview_worker::discard_closed(self); - if type_tool::in_ui_pass(ctx) { - if self.fonts_ready { - shortcuts::handle(self, ctx); - } else { - type_tool::controls_only(self, ctx); - } - } - } - let arrived: Vec<(String, Vec)> = - self.services.inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default(); - for (name, bytes) in arrived { - if let Err(e) = self.open_bytes(&name, &bytes) { - self.open_failed(&name, &e); - } - } - // Web drops onto the canvas, read since the last frame: placed below, one at a time. - let to_place: Vec<(String, Vec)> = - self.services.place_inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default(); - self.drop_places.extend(to_place.into_iter().map(|(name, bytes)| file_open::DropPlace::Bytes(name, bytes))); - // Finder double-click / Open With / Dock drops (macOS open-documents events). - self.drain_os_events(ctx); - // While files are dragged over the window it gets no pointer events: keep frames coming so - // the tab strip can follow the pointer. - if ctx.input(|i| !i.raw.hovered_files.is_empty()) { - ctx.request_repaint(); - } - let dropped = ctx.input(|i| i.raw.dropped_files.clone()); - if !dropped.is_empty() { - let at = self.services.cursor_pos.as_mut().and_then(|f| f(ctx)); - self.open_dropped(ctx, dropped, at); - // Files dragged in from another app's window: PhotoCraft comes to the front and takes - // the keyboard, as Photoshop does, instead of staying behind the source (#5687). - ctx.send_viewport_cmd(egui::ViewportCommand::Focus); - } - self.place_next_dropped(ctx); - // The control transport wakes the UI on arrival (ctx.request_repaint); only poll while a - // screenshot is pending. (Polling every 50 ms here made idle apps render at 20 fps.) - if self.captures.any_pending() { - ctx.request_repaint_after(std::time::Duration::from_millis(16)); - } - // A hidden host runs no UI pass: a queued (or re-queued) capture asks for one. An issued - // capture's own `Screenshot` command forces its paint; asking again would spin a hidden - // window while a slow readback is in flight. Synthetic input queued during hidden ticks - // needs the same wake: its events sit in eframe's preserved input until a UI pass. - if self.captures.any_unissued() || self.synthetic_batch.is_some() || !self.synthetic.is_empty() { - ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden); - } - self.poll_file_dialog(ctx, Some(frame)); - } - - /// Shared UI body. A wrapping host must call `finish_type_reset_pass` after return, - /// including when this body returns early without drawing an editor. - pub fn ui_frame(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { - let ctx = ui.ctx().clone(); - // One control owner even when this callback cannot draw the custom editor. - if !self.fonts_ready - || !self.ui.dialogs.is_empty() - || screen_picker::busy(&ctx) - || self.ui.text_edit.is_none() - || ctx.text_edit_focused() - || ctx.egui_wants_keyboard_input() - { - type_tool::controls_only(self, &ctx); - } - // 0.36 saved panel sizes under `Id::unique(name)`; 0.37 reads parent-scoped keys. Data-only, - // so it runs even before fonts are ready; the old keys stay for a 0.36 rollback. - panels::migrate_panel_state(&ctx); - // A real UI pass, not a hidden `run_logic` tick: record the capture geometry (the - // document identity included) and count one settling pass. `run_logic` leaves these - // input values stale; only this real UI phase counts toward settling. - let geometry = screenshot::CaptureGeometry::current(&ctx, self.document_identity()); - self.captures.note_geometry(geometry); - self.captures.note_pass(); - // A real UI pass consumes the one in-flight synthetic batch (see `inject_synthetic`). - self.begin_synthetic_pass(&ctx); - self.hover_layer = None; - i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language)); - // Fonts registered via set_fonts only take effect next frame; named families would panic now. - if !self.fonts_ready { - // egui consumed this pass's input without PhotoCraft handling it: keep the synthetic - // batch for the next pass instead of losing the step. - self.defer_synthetic_pass(); - ctx.request_repaint(); - self.automation_input = false; - // No editor was drawn this pass: end its IME context rather than keep a stale owner. - type_tool::sync_ime(self, &ctx); - return; - } - let t0 = gpu_canvas::now_ms(); - self.perf.frame_refresh_ms = 0.0; - self.stroke_trace.cpu_prev(frame.info().cpu_usage); - // A text field's right-click menu, before any field is drawn (text_field_menu.rs). - text_field_menu::show(&ctx); - // The wheel goes to a focused value field before the canvas or a panel sees it (#5473). - field_wheel::begin_frame(&ctx); - // Each painting tool keeps its own brush (#218), so switch the active tool's brush in - // before anything this frame reads it (the cursor, the options bar, a stroke). - // Preferences ▸ Type ▸ Recent Fonts: a smaller cap (or 0) trims the existing list at - // once, not only after the next pick. - self.sync_recent_fonts(); - paint_mouse::sync_tool_brush(self); - // A unit typed into a value field (`1in` in a px field) converts at the active document's - // resolution, as in Photoshop. - let ppi = self.session.prefs().units_and_rulers.point_size.per_inch(); - let dpi = self.session.active().map_or(72.0, |d| f64::from(d.doc.resolution_dpi.max(1.0))); - crate::widgets::set_field_resolution(&ctx, dpi, ppi); - // View › Screen Mode › Full Screen Mode: only the image, on black (F or Esc returns). - screen_picker::show(&ctx); - if screen_picker::busy(&ctx) && screen_picker::showing(&ctx) { - egui::Modal::new(egui::Id::unique("screen-color-wait")).show(&ctx, |ui| { - ui.spinner(); - ui.label(tl!("Pick a screen pixel or press Esc to cancel")); - if ui.button(tl!("Cancel")).clicked() { - screen_picker::cancel(&ctx); - } - }); - // This pass handled its input (the modal above ran): deliver the synthetic batch. - self.finish_synthetic_pass(); - self.automation_input = false; - type_tool::sync_ime(self, &ctx); - gpu_status::check_window(self, &ctx); - return; - } - if screen_picker::busy(&ctx) { - ui.disable(); - ui.set_opacity(1.0); - } - // The OS title bar (and the taskbar / Alt-Tab entry) follows the active file; with the - // system title bar this is where the document name lives, as the in-app title is hidden. - panels::sync_window_title(self, &ctx); - let chrome = !self.ui.view.hides_chrome(); - if chrome { - self.ui.panels.full_screen_chrome = false; - } - // In Full Screen Mode, Tab shows the menu bar, options bar, toolbar and dock (#6760). - let tabbed_in = !chrome && self.ui.panels.full_screen_chrome; - if (chrome || tabbed_in) && self.ui.panels.menu_bar { - panels::title_bar(self, ui); - } - if (chrome && self.ui.panels.options_bar) || tabbed_in { - panels::options_bar(self, ui); - } - if chrome && self.ui.panels.status_bar { - panels::status_bar(self, ui); - } - if (chrome && self.ui.panels.toolbar) || tabbed_in { - panels::toolbar(self, ui); - } - // craft-ui's layout holds the canvas as its protected `canvas` panel. - let docking = (chrome && self.ui.panels.dock) || tabbed_in; - 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); - }); - panels::properties_window(self, &ctx); - } - brush_panel::window(self, &ctx); - preset_panels::windows(self, &ctx); - gradient_ui::editor_window(self, &ctx); - type_panels_ui::windows(self, &ctx); - analysis_ui::windows(self, &ctx); - timeline_ui::windows(self, &ctx); - workspace_ui::windows(self, &ctx); - palette::show(self, &ctx); - dialogs::show(self, &ctx); - layers_panel_ui::show_dialog(self, &ctx); - rasterize_prompt::run_pending(self, &ctx); - jobs_ui::dialog(self, &ctx); - discard_ui::show(self, &ctx); - tiff_options_ui::show(self, &ctx); - targa_options_ui::show(self, &ctx); - jpeg_options_ui::show(self, &ctx); - dds_options_ui::show(self, &ctx); - distort_ui::show(self, &ctx); - camera_raw_ui::show(self, &ctx); - wide_angle_ui::show(self, &ctx); - canvas::extra_windows(self, &ctx); - notices::show(self, &ctx); - updates_ui::show(self, &ctx); - gpu_status::show_fallback(self, &ctx); - kys_import::show_offer(self, &ctx); - if self.titlebar_modal_drag(chrome) { - titlebar::modal_drag_overlay(&ctx); - } - if self.custom_titlebar { - titlebar::resize_zones(ui); - } - // A device lost while drawing this frame: switch to the CPU canvas before the next one. - gpu_status::check(self, &ctx); - // The Brush Preset picker's view (its gear's card parts and the footer scale) is - // remembered once the pointer is up. Here, after every panel, rather than in the - // picker's own code: the control channel can set it while the picker is closed. - brush_picker::persist(self, &ctx); - // The tool's brush (settings and tip references) is remembered the same way. Like the - // picker's view, in the frame loop, so the control channel can set it with the panels - // closed; the engine's revision counter keeps an unchanged brush free. - last_brush::persist(self, &ctx); - // Tool options are remembered between launches the same way (#2814). - tool_memory::persist(self, &ctx); - // So are View › Extras, Show and Snap To (#3762). - view_cmds::persist(self, &ctx); - // Remember the 0.37 panel sizes so a later 0.36 rollback's newer old-key values win on - // the next upgrade (see `panels::migrate_panel_state`). - panels::remember_panel_state(&ctx); - self.automation_input = false; - shape_stroke_ui::finish_frame(self, &ctx); - native_menu::sync(self, &ctx); - if screen_picker::busy(&ctx) { - // Block input without a backdrop: the worker may still be capturing the screen. - egui::Modal::new(egui::Id::unique("screen-color-wait")).frame(egui::Frame::NONE).backdrop_color(egui::Color32::TRANSPARENT).show(&ctx, |_| {}); - ctx.set_cursor_icon(egui::CursorIcon::Wait); - } - let ui_ms = gpu_canvas::now_ms() - t0; - // A GPU measurement lands a frame or two after the refresh it belongs to. Refreshes - // carry them out, but the last refresh before the app settles has none following it, so - // drain the timer here too or its number is never reported. Drain it either way: a - // measurement left sitting would surface later against an unrelated refresh. Report it - // only while the canvas is still on the GPU, since a CPU refresh clears `gpu_ms` - // precisely so a GPU number is never shown as that refresh's. - if let Some(gpu) = &self.gpu - && let Some(t) = gpu.take_gpu_timing() - && self.perf.last_refresh.starts_with("gpu") - { - self.perf.record_gpu(t); - } - self.perf.frame(ui_ms); - if self.stroke_trace.enabled() { - self.stroke_trace.canvas(self.perf.frame_refresh_ms); - let info = &self.perf.gpu_info; - self.stroke_trace.end_frame(ui_ms, self.live_stroke.is_some(), || { - let gpu = format!("{} {}", info.backend, info.adapter).trim().to_string(); - if info.present.is_empty() { gpu } else { format!("{gpu}, {}", info.present) } - }); - } - // This pass handled its input: the in-flight synthetic batch is delivered once and the - // next step may be injected on the next frame. - self.finish_synthetic_pass(); - // Synthetic input is injected one press/release step per frame: keep frames coming until - // the queue is empty, then release control replies waiting on it. - // Only a pass that reached the end of the UI and delivered the in-flight batch counts as - // settled input; an early-returning pass keeps the batch (and the waiting replies). - if !self.synthetic.is_empty() || self.synthetic_batch.is_some() { - ctx.request_repaint(); - } else if !self.input_waiters.is_empty() { - for w in self.input_waiters.drain(..) { - let _ = w.send(serde_json::json!({"ok": true, "result": null})); - } - } - // A menu or dialog can start a filter after `jobs_ui::tick` ran in this frame. Keep - // polling it even when the platform would otherwise put the event loop to sleep. - jobs_ui::keep_polling(self, &ctx); - // Menus and buttons in this frame may have asked for a file dialog. - self.poll_file_dialog(&ctx, Some(frame)); - // The Type tool's IME descriptor is the last writer of this pass: every panel and the - // canvas have finished mutating the model, and an absent/focus-moved editor ends here. - type_tool::sync_ime(self, &ctx); - // Issue any due `ui.screenshot` now that this pass's state is settled: a queued request - // that has waited its passes and animation delay captures exactly this frame. - self.issue_captures(&ctx); - // Last, after everything drawn this frame: a lost window device can't draw it (#3438). - gpu_status::check_window(self, &ctx); - } -} - -impl eframe::App for PhotocraftApp { - fn on_exit(&mut self) { - if let Err(err) = tool_memory::save_on_exit(self) { - log::warn!("Preferences: could not save the final tool selection: {err}"); - } - // Release a pending screenshot's image budget and answer its control request; the - // callback is inert afterwards (it holds only a weak slot). - let finished = self.captures.cancel_all("the application is closing"); - self.finish_captures(finished); - } - - fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { - self.logic_frame(ctx, frame); - self.finish_type_reset_logic(ctx); - } - - fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) { - let frame_start = gpu_canvas::now_ms(); - // An undecorated window gets its caption back when the toolkit changes its flags - // (maximize, restore, …): take it off again before the frame is laid out (#2246). - if let Some(window_frame) = self.services.window_frame.as_mut() { - window_frame(); - } - // Native menu key equivalents become the key presses they were (see `native_menu`). - if let Some(menu) = self.services.native_menu.as_mut() { - menu.raw_input(raw_input); - } - // While a text field of a floating panel's own window has the keyboard, the dock area - // hands that window the text keys in this input and converts them there. - if craft_ui::docking::typing_window(ctx).is_none() { - shortcuts::clipboard_keys(ctx, ctx.text_edit_focused() || self.ui.text_edit.is_some(), raw_input); - } - // Windows precision touchpads and some Linux Wayland compositors send pinches - // as fractional Ctrl + wheel rather than a native Zoom event (#4566). - // Leave Ctrl+whole-notch mouse scrolling alone, and honour the pinch preference. - if cfg!(any(target_os = "windows", target_os = "linux")) && self.session.prefs().enhanced_controls.zoom_with_trackpad_pinch { - wheel_nav::fold_legacy_pinch(ctx, raw_input); - } - self.inject_synthetic(ctx, raw_input); - // After the control channel's own events (`ui.type`) join the OS's, before any widget. - widgets::cap_text_events(&mut raw_input.events); - self.control_click.normalize(&mut raw_input.events, cfg!(target_os = "macos")); - // A pen held still is no touch screen's press-and-hold right click (stylus.rs). - let pen_down = self.stylus.pen_contacts.observe(&raw_input.events); - stylus::pen_hold_is_no_right_click(ctx, pen_down); - if self.custom_titlebar { - titlebar::release_after_os_resize(ctx, raw_input); - } - if self.stroke_trace.enabled() { - // The OS's moves and the control channel's (injected just above). - let moves = raw_input.events.iter().filter(|e| matches!(e, egui::Event::PointerMoved(_))).count(); - self.stroke_trace.begin_frame(frame_start, moves); - } - } - - fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { - self.ui_frame(ui, frame); - self.finish_type_reset_pass(ui.ctx()); - } -} - -/// Remove one contiguous run equal to `batch` from `events` (eframe's preserved synthetic -/// input). A no-op when the run is not present. -fn remove_event_run(events: &mut Vec, batch: &[egui::Event]) { - if batch.is_empty() || batch.len() > events.len() { - return; - } - if let Some(pos) = events.windows(batch.len()).position(|w| w == batch) { - events.drain(pos..pos + batch.len()); - } -} - -#[cfg(not(target_arch = "wasm32"))] -fn read_dropped(f: &(dyn egui::DroppedFile + Send + Sync)) -> Result, String> { - f.bytes() -} - -/// The active layer is an adjustment layer. It has no pixels, so painting and filling it edit its -/// mask even when its icon thumbnail, not the mask, is the Layers panel's target, as in -/// Photoshop (#4298). -pub(crate) fn adjustment_layer_active(st: &photocraft_engine::DocState) -> bool { - st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| matches!(l.content, photocraft_doc::LayerContent::Adjustment(_))) -} - -/// On the web, dropped-file bytes arrive asynchronously; the web shell handles drops itself. -#[cfg(target_arch = "wasm32")] -fn read_dropped(_f: &dyn egui::DroppedFile) -> Result, String> { - Err("drag-and-drop on the web is handled by the page; use File → Open".into()) -} - -impl PhotocraftApp { - /// Whether the title bar's free gap gets the drag overlay this frame: the app draws its title - /// strip (`chrome`: not hidden by the screen mode) and a dialog's modal layer covers it. Not - /// only with the custom title bar: on macOS the strip under the traffic lights is the window's - /// title bar too, and an open dialog (Embedded Profile Mismatch…) left it undraggable (#5826). - pub(crate) fn titlebar_modal_drag(&self, chrome: bool) -> bool { - chrome && self.ui.panels.menu_bar && !self.ui.dialogs.is_empty() - } - - /// `params` aimed at the active layer's mask (`"target":"mask"`) when the Layers panel targets - /// it and command `id` edits the target (adjustments, filters, fills) without naming one: - /// ⌘I then inverts the mask, as in Photoshop (#780). A targeted alpha channel or Quick Mask - /// mode wins, as the engine routes those itself. - pub fn with_mask_target(&self, id: &str, params: Value) -> Value { - if !photocraft_engine::channel_cmds::follows_target(id) || params.get("target").is_some() { - return params; - } - // A filter mask is painted, filled and filtered in place; it doesn't float or move, and - // Edit › Transform, Apply Image and the dialog filters act on the smart object. - let target = if self.filter_mask_targeted() && photocraft_engine::channel_cmds::follows_filter_mask(id) { - "filterMask" - } else if self.layer_mask_targeted() { - "mask" - } else { - return params; - }; - match params { - Value::Object(mut m) => { - m.insert("target".into(), Value::from(target)); - Value::Object(m) - } - _ => serde_json::json!({ "target": target }), - } - } - - /// The Layers panel targets the active smart object's filter mask (FILE-215-3), and no alpha - /// channel or Quick Mask takes over. - pub fn filter_mask_targeted(&self) -> bool { - let Some(st) = self.session.active() else { return false }; - let Some(id) = st.active_layer.filter(|id| self.ui.filter_mask_target == Some(id.0)) else { return false }; - let composite = st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::Composite && st.doc.quick_mask.is_none(); - composite && st.doc.layer(id).is_some_and(|l| matches!(&l.content, photocraft_doc::LayerContent::Smart(sm) if !sm.smart_filters.is_empty())) - } - - /// The active layer's mask is what pixel commands edit: the Layers panel targets it, the layer - /// is an adjustment layer (no pixels of its own), or every colour channel is off and that mask - /// is the picture. An alpha channel or Quick Mask wins, as the engine routes those itself. - pub fn layer_mask_targeted(&self) -> bool { - let Some(st) = self.session.active() else { return false }; - let layer_mask = st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::LayerMask; - let composite = (st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::Composite || layer_mask) && st.doc.quick_mask.is_none(); - let has_mask = st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.mask.is_some()); - if !composite || !has_mask { - return false; - } - if self.ui.mask_target || layer_mask || adjustment_layer_active(st) { - return true; - } - let colors_off = st.channel_view.visible_colors(photocraft_engine::channel_cmds::color_count(&st.doc)) == 0; - let alpha_on = (0..st.doc.channels.len()).any(|i| st.channel_view.alpha_shown(i)); - colors_off && !alpha_on - } - - /// Targeting the pixels, the layer mask or the vector mask ends a shown filter mask (⌥-click - /// on its thumbnail): while it shows, [`Self::sync_mask_targets`] keeps the filter mask - /// targeted, so strokes would keep landing there. - pub(crate) fn end_filter_mask_view(&mut self) { - let Some(v) = self.session.active().and_then(photocraft_engine::mask_view_cmds::current).filter(|v| v.filter) else { return }; - let off = serde_json::json!({"layer": v.layer.0, "mode": "off", "mask": "filter"}); - if let Err(err) = self.session.execute(photocraft_engine::mask_view_cmds::ID, off) { - log::warn!("could not end the filter mask view: {err}"); - } - } - - /// Explicitly targeting a filter mask ends any conflicting mask view; untargeting it ends its - /// own view too. - pub(crate) fn select_filter_mask_target(&mut self, layer: Option) { - if layer.is_none() { - self.end_filter_mask_view(); - } - if layer.is_some() { - if let Some(st) = self.session.active_mut() { - if st.channel_view.layer_mask.is_some_and(|v| !v.filter || Some(v.layer.0) != layer) { - st.channel_view.layer_mask = None; - } - if matches!( - st.channel_view.target, - photocraft_engine::channel_cmds::ChannelTarget::LayerMask | photocraft_engine::channel_cmds::ChannelTarget::VectorMask - ) { - st.channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Composite; - } - } - self.ui.mask_target = false; - self.ui.vector_mask_target = false; - } - self.ui.filter_mask_target = layer; - self.sync_mask_targets(); - } - - /// Viewing a layer mask (#196) targets it; a vector-mask target needs a vector mask on the - /// active layer (a shape layer's path is its content, not a mask). Targeting a mask or the - /// pixels brings back that target's foreground/background pair, as in Photoshop (#2166). - pub(crate) fn sync_mask_targets(&mut self) { - if let Some(st) = self.session.active_mut() { - use photocraft_engine::channel_cmds::ChannelTarget; - let channel = st.channel_view.target; - match photocraft_engine::mask_view_cmds::current(st) { - Some(v) if v.filter => { - self.ui.filter_mask_target = Some(v.layer.0); - self.ui.mask_target = false; - self.ui.vector_mask_target = false; - } - Some(_) => { - self.ui.mask_target = true; - self.ui.vector_mask_target = false; - self.ui.filter_mask_target = None; - } - None if channel == ChannelTarget::LayerMask => { - self.ui.mask_target = true; - self.ui.vector_mask_target = false; - } - None if channel == ChannelTarget::VectorMask => { - self.ui.vector_mask_target = true; - self.ui.mask_target = false; - } - None => {} - } - if self.ui.mask_target || self.ui.vector_mask_target { - self.ui.filter_mask_target = None; - } - if self.ui.vector_mask_target && !mask_thumbs_ui::has_vector_mask(st) { - self.ui.vector_mask_target = false; - } - if self.ui.mask_target && st.active_layer.and_then(|id| st.doc.layer(id)).is_none_or(|l| l.mask.is_none()) { - self.ui.mask_target = false; - } - if !self.ui.mask_target && st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::LayerMask { - st.channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Composite; - } - if !self.ui.mask_target || self.ui.properties_layer != st.active_layer.map(|l| l.0) { - self.ui.properties_layer = None; - } - } - if self.ui.filter_mask_target.is_some() && !self.filter_mask_targeted() { - self.ui.filter_mask_target = None; - } - let mask = self.layer_mask_targeted() || self.filter_mask_targeted(); - self.session.tools.target_mask(mask); - } - - fn prune_thumbs(&mut self) { - let documents = self.session.documents(); - if self.thumb_documents.len() == documents.len() - && self.thumb_documents.iter().zip(documents).all(|((id, snapshot), st)| *id == st.doc.id && snapshot.ptr_eq(&std::sync::Arc::downgrade(&st.doc))) - { - return; - } - // Check snapshots every sync, but walk the layer tree only after it changes. A Weak - // tracks replacement (including undo and preserved-ID reopen) without retaining pixels. - if !self.thumbs.is_empty() { - let mut live = std::collections::HashSet::new(); - let mut pending: Vec<_> = documents.iter().flat_map(|st| &st.doc.layers).collect(); - while let Some(layer) = pending.pop() { - live.insert((layer.id, mask_thumbs_ui::THUMB_LAYER)); - if layer.mask.is_some() { - live.insert((layer.id, mask_thumbs_ui::THUMB_MASK)); - } - if layer.vector_mask.is_some() { - live.insert((layer.id, mask_thumbs_ui::THUMB_VECTOR)); - } - if matches!(&layer.content, photocraft_doc::LayerContent::Smart(sm) if sm.filter_mask.is_some()) { - live.insert((layer.id, mask_thumbs_ui::THUMB_SMART_MASK)); - } - if let Some(children) = layer.children() { - pending.extend(children); - } - } - // Native files can restore IDs: retain the union across all open documents, rather - // than deleting an ID just because one document containing it was closed. - self.thumbs.retain(|key, _| live.contains(key)); - self.thumb_frames.retain(|id, _| live.contains(&(*id, mask_thumbs_ui::THUMB_LAYER))); - } - self.thumb_documents = documents.iter().map(|st| (st.doc.id, std::sync::Arc::downgrade(&st.doc))).collect(); - } - - pub fn set_theme(&mut self, ctx: &egui::Context, kind: theme::ThemeKind) { - if let Err(e) = self.run("prefs.set", serde_json::json!({"path": "interface.theme", "value": kind.id()})) { - self.ui.status = e; - } else { - self.apply_theme(ctx, kind); - } - } - - pub(crate) fn apply_theme(&mut self, ctx: &egui::Context, kind: theme::ThemeKind) { - // Color and Swatches trade indices between Pro and Studio layouts. - if let Some(selected) = dock::Group::Color.tabs(theme::Tokens::for_kind(self.ui.theme).pro).get(self.ui.dock_tabs.color) - && let Some(tab) = dock::Group::Color.tabs(theme::Tokens::for_kind(kind).pro).iter().position(|name| name == selected) - { - self.ui.dock_tabs.color = tab; - } - self.ui.theme = kind; - panel_docking::sync_visibility(self); - theme::apply(ctx, kind); - self.checker = None; - } - - /// Cached 64px thumbnail of a pixel-ish layer, letterboxed in a square, and the document - /// area it frames: the canvas, or with Clip Thumbnails to Layer Bounds the layer's pixels. - pub fn layer_thumb(&mut self, ctx: &egui::Context, doc: &Document, layer: &photocraft_doc::Layer) -> (egui::TextureId, photocraft_geom::Rect) { - let clip = self.session.prefs().interface.clip_thumbnails_to_layer_bounds; - // Key by content, not document revision: COW tiles change pointer only when their pixels - // change, so unrelated edits (e.g. painting another layer) don't rebuild this thumbnail. - let rev = layer.surface().map_or(0, surface_fingerprint) ^ (doc.size.width as u64) << 40 ^ u64::from(clip) << 63; - let key = (layer.id, mask_thumbs_ui::THUMB_LAYER); - if let Some((r, tex)) = self.thumbs.get(&key) - && *r == rev - && let Some(frame) = self.thumb_frames.get(&layer.id) - { - return (tex.id(), *frame); - } - let canvas = doc.bounds(); - let frame = layer_thumb_frame(layer, canvas, clip); - let mut px = [0.0f32; 8]; - let img = thumb_image(frame, 64, |x, y| { - let Some(s) = layer.surface() else { return [0.0; 4] }; - let n = s.channels(); - s.read_pixel(x, y, &mut px[..n]); - photocraft_raster::to_rgba(&s.format(), &px[..n]) - }); - self.thumb_frames.insert(layer.id, frame); - (self.store_thumb(ctx, key, rev, img), frame) - } - - /// The History panel thumbnail of snapshot `snap` of document `doc` (#2966): its composite, - /// centred in a square. Thumbnails of `doc`'s snapshots not in `live` are dropped. - pub fn snapshot_thumb(&mut self, ctx: &egui::Context, doc: DocId, snap: &photocraft_engine::history_cmds::Snapshot, live: &[u64]) -> egui::TextureId { - self.snapshot_thumbs.retain(|(d, id), _| *d != doc || live.contains(id)); - if let Some(tex) = self.snapshot_thumbs.get(&(doc, snap.id)) { - return tex.id(); - } - let comp = photocraft_compose::thumbnail(&snap.doc, 56); - let (w, h) = (comp.width as usize, comp.height as usize); - let side = w.max(h); - let (ox, oy) = ((side - w) / 2, (side - h) / 2); - let mut px = vec![egui::Color32::TRANSPARENT; side * side]; - for (i, &[r, g, b, a]) in comp.pixels.as_chunks::<4>().0.iter().enumerate() { - if let Some(out) = px.get_mut((i / w + oy) * side + i % w + ox) { - *out = egui::Color32::from_rgba_unmultiplied(r, g, b, a); - } - } - let tex = ctx.load_texture(format!("snapshot-{}", snap.id), egui::ColorImage::new([side, side], px), egui::TextureOptions::LINEAR); - let id = tex.id(); - self.snapshot_thumbs.insert((doc, snap.id), tex); - id - } - - /// The cached thumbnail of `mask`, the layer mask of layer `id`. - pub fn mask_thumb(&mut self, ctx: &egui::Context, doc: &Document, id: photocraft_doc::LayerId, mask: &photocraft_doc::LayerMask) -> egui::TextureId { - self.mask_thumb_kind(ctx, doc, id, mask, mask_thumbs_ui::THUMB_MASK) - } - - /// The thumbnail of `mask` under cache `kind`, re-rendered only when the mask's pixels or the document size change; Smart Filter and layer masks are cached apart. - pub(crate) fn mask_thumb_kind( - &mut self, - ctx: &egui::Context, - doc: &Document, - id: photocraft_doc::LayerId, - mask: &photocraft_doc::LayerMask, - kind: u8, - ) -> egui::TextureId { - let rev = surface_fingerprint(&mask.surface) ^ (doc.size.width as u64) << 40 ^ (doc.size.height as u64) << 16; - let key = (id, kind); - if let Some((r, tex)) = self.thumbs.get(&key) - && *r == rev - { - return tex.id(); - } - let mut v = [0.0f32; 1]; - let img = thumb_image(doc.bounds(), 64, |x, y| { - mask.surface.read_pixel(x, y, &mut v); - [v[0], v[0], v[0], 1.0] - }); - self.store_thumb(ctx, key, rev, img) - } - - fn store_thumb(&mut self, ctx: &egui::Context, key: (photocraft_doc::LayerId, u8), rev: u64, img: egui::ColorImage) -> egui::TextureId { - match self.thumbs.get_mut(&key) { - Some((r, tex)) => { - tex.set(img, egui::TextureOptions::LINEAR); - *r = rev; - tex.id() - } - None => { - let tex = ctx.load_texture(format!("thumb-{}-{}", key.0.0, key.1), img, egui::TextureOptions::LINEAR); - let id = tex.id(); - self.thumbs.insert(key, (rev, tex)); - id - } - } - } -} - -/// Cheap identity of a surface's pixels: its default (untouched) pixel, tile coordinates and -/// `Arc` pointers. The default pixel matters: inverting or filling a tile-less mask only changes -/// it (#2117). -pub fn surface_fingerprint(s: &photocraft_raster::Surface) -> u64 { - let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ s.tile_count() as u64; - for &b in s.default_bytes() { - h = (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3); - } - for (c, t) in s.tiles() { - let p = std::sync::Arc::as_ptr(t) as usize as u64; - h = (h ^ p ^ ((c.tx as u64) << 32 | c.ty as u32 as u64)).wrapping_mul(0x100_0000_01b3); - } - h -} - -/// The document area a layer thumbnail frames: the canvas, or with `clip` the layer's pixels on -/// it (the canvas again when it has none there, so an empty layer still shows the page shape). -fn layer_thumb_frame(layer: &photocraft_doc::Layer, canvas: photocraft_geom::Rect, clip: bool) -> photocraft_geom::Rect { - if !clip { - return canvas; - } - let bounds = layer.surface().map_or(photocraft_geom::Rect::EMPTY, photocraft_compose::bounds::content_bounds).intersect(&canvas); - if bounds.is_empty() { canvas } else { bounds } -} - -/// Square thumbnail of the document area `frame`, letterboxed, sampling `f(x, y)` in document -/// space. -fn thumb_image(frame: photocraft_geom::Rect, side: usize, mut f: impl FnMut(i32, i32) -> [f32; 4]) -> egui::ColorImage { - let (w, h) = (frame.width().max(1) as f32, frame.height().max(1) as f32); - let scale = w.max(h) / side as f32; - let (ox, oy) = ((side as f32 - w / scale) / 2.0, (side as f32 - h / scale) / 2.0); - let mut px = vec![egui::Color32::TRANSPARENT; side * side]; - for ty in 0..side { - for tx in 0..side { - let dx = (tx as f32 - ox + 0.5) * scale; - let dy = (ty as f32 - oy + 0.5) * scale; - if dx < 0.0 || dy < 0.0 || dx >= w || dy >= h { - continue; - } - let c = f(frame.x0.saturating_add(dx as i32), frame.y0.saturating_add(dy as i32)); - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - px[ty * side + tx] = egui::Color32::from_rgba_unmultiplied(q(c[0]), q(c[1]), q(c[2]), q(c[3])); - } - } - egui::ColorImage::new([side, side], px) -} - -impl PhotocraftApp { - /// The document/focus identity the in-flight synthetic batch was queued for. - fn synthetic_target(&self, ctx: &egui::Context) -> SyntheticTarget { - SyntheticTarget { document: self.document_identity(), focus: ctx.memory(|m| m.focused()) } - } - - fn synthetic_target_matches(&self, ctx: &egui::Context) -> bool { - self.synthetic_snapshot.is_some_and(|queued| queued.matches(self.synthetic_target(ctx))) - } - - /// Put at most one queued synthetic batch into this pass's input. - /// - /// The batch is appended once and tracked; `begin_pass` consumes it. While it is in flight no - /// further step is drained, so hidden logic ticks cannot accumulate several batches into one - /// pass. A document or focus change observed here is before eframe consumes the events, so the - /// batch is dropped and its waiting control replies fail instead of landing somewhere else. - /// If a pass consumed it but PhotoCraft returned before handling input (fonts not ready), the - /// same batch is appended again on the next hook, exactly once. - fn inject_synthetic(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) { - if self.synthetic_batch.is_some() { - if !self.synthetic_target_matches(ctx) { - // eframe may already carry the batch in its preserved input: withdraw exactly - // those events before the host consumes them, then fail the waiting replies. - if let Some(batch) = self.synthetic_batch.as_ref() { - remove_event_run(&mut raw_input.events, batch); - } - self.cancel_synthetic("the active document or focus changed while the input was queued"); - return; - } - if self.synthetic_reinject { - if let Some(batch) = self.synthetic_batch.clone() { - raw_input.events.extend(batch); - } - self.synthetic_reinject = false; - self.automation_input = true; - } - return; - } - if self.synthetic.is_empty() { - return; - } - let events = self.take_synthetic_step(); - if events.is_empty() { - return; - } - self.synthetic_snapshot = Some(self.synthetic_target(ctx)); - raw_input.events.extend(events.iter().cloned()); - self.synthetic_batch = Some(events); - } - - /// A pass begins with the in-flight batch. The events are already in this pass's input, so a - /// target change detected now cannot withdraw them: deliver them (never half-apply) and keep - /// `automation_input` set so the commands they trigger still go through the automation policy. - /// `inject_synthetic` performs the withdrawable check, before the host consumes the events. - /// Called at the start of `App::ui` only (a hidden `run_logic` tick consumes no input). - fn begin_synthetic_pass(&mut self, ctx: &egui::Context) { - if self.synthetic_batch.is_none() { - return; - } - if !self.synthetic_target_matches(ctx) { - log::warn!("synthetic input: the document or focus changed inside the pass; delivering it as automation input"); - } - self.automation_input = true; - } - - /// One full UI pass handled the in-flight batch: deliver it once and let the next step in. - fn finish_synthetic_pass(&mut self) { - let _ = self.synthetic_batch.take(); - self.synthetic_snapshot = None; - self.synthetic_reinject = false; - } - - /// The pass returned before the input handling (fonts not ready): keep the batch and have the - /// next hook append it again exactly once, because egui already consumed the events. - fn defer_synthetic_pass(&mut self) { - if self.synthetic_batch.is_some() { - self.synthetic_reinject = true; - } - } - - /// Drop the in-flight batch and fail the replies waiting on it. - fn cancel_synthetic(&mut self, reason: &str) { - let pending = self.synthetic_batch.take().is_some() || !self.synthetic.is_empty(); - self.synthetic.clear(); - self.synthetic_snapshot = None; - self.synthetic_reinject = false; - self.automation_input = false; - if pending || !self.input_waiters.is_empty() { - for w in self.input_waiters.drain(..) { - let _ = w.send(serde_json::json!({"ok": false, "error": format!("input cancelled: {reason}")})); - } - } - } - - /// Next step of queued synthetic input (automation): events up to and including the first - /// release, so egui sees press and release in separate frames. Hosts that don't call - /// `raw_input_hook` (offscreen harnesses) feed these to their input themselves. - pub fn take_synthetic_step(&mut self) -> Vec { - let n = self - .synthetic - .iter() - .position(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. } | egui::Event::Key { pressed: false, .. })) - .map_or(self.synthetic.len(), |i| i + 1); - let events: Vec<_> = self.synthetic.drain(..n).collect(); - if !events.is_empty() { - self.automation_input = true; - } - events - } - - /// Install fonts, image loaders and the theme. Call from the app creator (and again for a - /// replacement Context) before the first `run_ui` so the very first frame renders and the - /// Type reset begin/end pass markers exist; otherwise `logic` does it and the first frame is - /// skipped, with the begin-pass marker necessarily starting on the following pass. - pub fn setup_context(ctx: &egui::Context, kind: theme::ThemeKind) { - Self::install_type_reset_hooks(ctx); - ctx.add_plugin(tool_cursor::CursorLifecycle); - ctx.add_plugin(single_line_drag::SingleLineDrag::default()); - theme::install_fonts(ctx); - egui_extras::install_image_loaders(ctx); - theme::apply(ctx, kind); - // Right-click in any text field: its Cut / Copy / Paste menu (text_field_menu.rs). - ctx.add_plugin(text_field_menu::TextFieldMenu); - // egui's own ⌘+ / ⌘- / ⌘0 scale the whole interface; PhotoCraft zooms the canvas instead - // (shortcuts.rs), like Photoshop. - ctx.options_mut(|o| o.zoom_with_keyboard = false); - // ⌘/Ctrl + wheel scrolls sideways, as in Photoshop; only a pinch zooms (wheel_nav.rs). - wheel_nav::configure(ctx); - } -} - -impl PhotocraftApp { - /// Cached `Surface::content_bounds` keyed by an id and the surface's tile identity. - pub fn cached_bounds(&mut self, key: u64, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { - let rev = surface_fingerprint(surface); - if let Some((r, b)) = self.bounds_cache.get(&key) - && *r == rev - { - return *b; - } - let b = surface.content_bounds(); - if self.bounds_cache.len() > 256 { - self.bounds_cache.clear(); - } - self.bounds_cache.insert(key, (rev, b)); - b - } - - /// The box Properties › Transform shows for `layer` (X, Y, W, H): its pixels' bounds, but a - /// soft shape's path and stroke, whose Density and Feather render past them (#5846), as its - /// transform frame does. - pub fn layer_frame_bounds(&mut self, layer: &photocraft_doc::Layer, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { - match &layer.content { - photocraft_doc::LayerContent::Shape(sh) if sh.has_soft_mask() => { - // Cached per rendering, like the pixel bounds: the frame renders strips of the shape. - let (key, rev) = (layer.id.0 | 1 << 63, surface_fingerprint(surface)); - if let Some((r, b)) = self.bounds_cache.get(&key) - && *r == rev - { - return *b; - } - let canvas = self.session.active().map_or_else(|| surface.content_bounds(), |st| st.doc.bounds()); - let b = photocraft_compose::soft_shape_frame(sh, surface.format(), canvas).unwrap_or(photocraft_geom::Rect::EMPTY); - if self.bounds_cache.len() > 256 { - self.bounds_cache.clear(); - } - self.bounds_cache.insert(key, (rev, b)); - b - } - _ => self.cached_bounds(layer.id.0, surface), - } - } -} - -impl PhotocraftApp { - /// Zoom of the active document's main view: screen (device) pixels per document pixel, the - /// user-facing factor (`100%` is `1.0`). - pub fn current_zoom(&self) -> f32 { - self.session.active_index().and_then(|i| self.ui.views.get(i)).map_or(1.0, |v| v.zoom) - } - - /// Screen (device) pixels per egui point of the canvas (`ctx.pixels_per_point`), as of the - /// last canvas frame. `1.0` before the first frame. - pub fn canvas_ppp(&self) -> f32 { - if self.ppp.is_finite() && self.ppp > 0.0 { self.ppp } else { 1.0 } - } - - /// The active view's zoom in egui points per document pixel: the unit every screen-space - /// distance, tolerance and texture-level choice on the canvas is measured in. - pub fn point_zoom(&self) -> f32 { - self.current_zoom() / self.canvas_ppp() - } -} - -impl PhotocraftApp { - /// Channels panel thumbnails of the active document snapshot: the composite, - /// each colour channel (when there is more than one), each alpha channel, then the Quick Mask. - pub fn channel_thumbs(&mut self, ctx: &egui::Context) -> Vec { - let Some(st) = self.session.active() else { - self.channel_thumbs = None; - return Vec::new(); - }; - let (id, doc) = (st.doc.id, st.doc.clone()); - // View-only commands bump revision without changing pixels. Keeping a Weak pins allocation - // identity against address reuse without retaining the document's pixel data. - let snapshot = std::sync::Arc::downgrade(&doc); - let show_color = self.session.prefs().interface.show_channels_in_color; - // A step that changes only the selection (a marquee, Deselect) makes a new snapshot with - // the same pixels: keep the thumbnails, a full composite at 56 px costs ~0.7 s on a - // layered 20 MP document (#4518). - let current = match &mut self.channel_thumbs { - Some((d, old, in_color, _)) if *d == id && *in_color == show_color => { - let same = old.ptr_eq(&snapshot) || old.upgrade().is_some_and(|prev| same_but_selection(&prev, &doc)); - if same { - *old = snapshot.clone(); - } - same - } - _ => false, - }; - if !current { - let comp = photocraft_compose::thumbnail(&doc, 56); - let (w, h) = (comp.width as usize, comp.height as usize); - let side = w.max(h); - let make = |f: &dyn Fn(&[u8]) -> egui::Color32, name: &str| { - let mut px = vec![egui::Color32::TRANSPARENT; side * side]; - let (ox, oy) = ((side - w) / 2, (side - h) / 2); - for y in 0..h { - for x in 0..w { - let o = (y * w + x) * 4; - px[(y + oy) * side + x + ox] = f(&comp.pixels[o..o + 4]); - } - } - (format!("chan-{name}"), egui::ColorImage::new([side, side], px)) - }; - let fmt = doc.pixel_format(); - let colors = fmt.mode.color_channels(); - let mut texs = vec![make(&|p| egui::Color32::from_rgb(p[0], p[1], p[2]), "composite")]; - if colors > 1 { - for k in 0..colors { - let cmyk = fmt.mode == photocraft_doc::ColorMode::Cmyk; - texs.push(make( - &|p| { - let rgba = [p[0], p[1], p[2], 255].map(|v| f32::from(v) / 255.0); - let x = photocraft_raster::from_rgba(&fmt, rgba)[k]; - let g = if cmyk { 1.0 - x } else { x }; - let byte = (g.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - channel_tint(fmt.mode, k, byte, show_color) - }, - &format!("c{k}"), - )); - } - } - // Alpha channels and the Quick Mask, sampled at thumbnail resolution. - let (dw, dh) = (doc.size.width.max(1) as f32, doc.size.height.max(1) as f32); - for (i, ch) in doc.channels.iter().chain(doc.quick_mask.as_ref()).enumerate() { - let mut px = vec![egui::Color32::TRANSPARENT; side * side]; - let (ox, oy) = ((side - w) / 2, (side - h) / 2); - for y in 0..h { - for x in 0..w { - let sx = ((x as f32 + 0.5) * dw / w as f32) as i32; - let sy = ((y as f32 + 0.5) * dh / h as f32) as i32; - let v = ch.surface.sample_channel(sx, sy, 0); - px[(y + oy) * side + x + ox] = egui::Color32::from_gray((v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); - } - } - texs.push((format!("chan-a{i}"), egui::ColorImage::new([side, side], px))); - } - // Update the textures already uploaded rather than allocating new ones. - let mut handles = match self.channel_thumbs.take() { - Some((d, _, _, h)) if d == id => h, - _ => Vec::new(), - }; - handles.truncate(texs.len()); - for (i, (name, image)) in texs.into_iter().enumerate() { - match handles.get_mut(i) { - Some(h) => h.set(image, egui::TextureOptions::LINEAR), - None => handles.push(ctx.load_texture(name, image, egui::TextureOptions::LINEAR)), - } - } - self.channel_thumbs = Some((id, snapshot, show_color, handles)); - } - self.channel_thumbs.as_ref().map(|(_, _, _, t)| t.iter().map(|t| t.id()).collect()).unwrap_or_default() - } -} - -/// Whether `new` differs from `old` at most in its selection, so every composite and channel -/// thumbnail of it is unchanged. Tiles compare by pointer first, so this costs little. -fn same_but_selection(old: &Document, new: &Document) -> bool { - if old.selection == new.selection { - return old == new; - } - let mut o = old.clone(); - o.selection = new.selection.clone(); - o == *new -} - -/// Layer › Layer Mask commands that add a layer mask: Photoshop targets the new mask (#2166). -const ADDS_LAYER_MASK: [&str; 5] = [ - "layer.layerMask.revealAll", - "layer.layerMask.hideAll", - "layer.layerMask.revealSelection", - "layer.layerMask.hideSelection", - "layer.layerMask.fromTransparency", -]; - -/// The New Document dialog's key in the preferences' `dialogs` map. -const NEW_DOCUMENT: &str = "file.new"; - -/// New Document fields its OK remembers (#1810): the size, resolution, mode, depth, background and -/// display units. Not the name, the preset or the clipboard size. -const NEW_DOCUMENT_REMEMBERED: [&str; 8] = ["width", "height", "resolution", "mode", "depth", "background", "__unit", "__resUnit"]; - -/// A remembered value the dialog can show (a corrupt preference is ignored). -fn remembered_new_document_value(key: &str, v: &serde_json::Value) -> bool { - match key { - "width" | "height" => v.as_u64().is_some_and(|n| (1..=300_000).contains(&n)), - "resolution" => v.as_f64().is_some_and(|r| r.is_finite() && r > 0.0 && r <= 30_000.0), - "depth" => v.as_u64().is_some_and(|d| matches!(d, 1 | 8 | 16 | 32)), - _ => v.as_str().is_some_and(|s| !s.is_empty() && s.len() <= 64), - } -} - -/// Remember the New Document fields `f` its OK used, for the next New Document. -pub(crate) fn remember_new_document(app: &mut PhotocraftApp, f: &serde_json::Map) { - let kept: serde_json::Map = - NEW_DOCUMENT_REMEMBERED.iter().filter_map(|k| f.get(*k).filter(|v| remembered_new_document_value(k, v)).map(|v| (k.to_string(), v.clone()))).collect(); - app.session.prefs.edit(|p| p.dialogs.insert(NEW_DOCUMENT.into(), serde_json::Value::Object(kept))); -} - -fn clip_signature(w: u32, h: u32, px: &[u8]) -> u64 { - let mut sig = (w as u64) << 32 | h as u64; - for b in px.iter().step_by(997) { - sig = sig.rotate_left(5) ^ *b as u64; - } - sig -} - -/// A channel thumbnail pixel whose lightness is `byte` (255 = white: full light, no ink). -/// Preferences ▸ Interface ▸ Show Channels in Color tints RGB channels from black to their -/// primary and CMYK channels from white to their ink, as Photoshop does; otherwise grey. -fn channel_tint(mode: photocraft_doc::ColorMode, k: usize, byte: u8, in_color: bool) -> egui::Color32 { - use photocraft_doc::ColorMode::{Cmyk, Rgb}; - if !in_color { - return egui::Color32::from_gray(byte); - } - match (mode, k) { - (Rgb, 0) => egui::Color32::from_rgb(byte, 0, 0), - (Rgb, 1) => egui::Color32::from_rgb(0, byte, 0), - (Rgb, 2) => egui::Color32::from_rgb(0, 0, byte), - (Cmyk, 0) => egui::Color32::from_rgb(byte, 255, 255), - (Cmyk, 1) => egui::Color32::from_rgb(255, byte, 255), - (Cmyk, 2) => egui::Color32::from_rgb(255, 255, byte), - _ => egui::Color32::from_gray(byte), - } -} - -impl PhotocraftApp { - /// Mirror the session clipboard onto the OS clipboard (RGBA8). - fn export_os_clipboard(&mut self) { - self.clip_unmirrored = true; - if !self.session.prefs().general.export_clipboard { - return; - } - let (Some(set), Some(clip)) = (self.services.clipboard_set_image.as_mut(), self.session.clipboard.as_ref()) else { return }; - let b = clip.bounds; - if b.is_empty() { - return; - } - let mut px = vec![[0u8; 4]; b.width() as usize * b.height() as usize]; - clip.surface.read_rgba8_into(b, &mut px); - let bytes: Vec = px.into_iter().flatten().collect(); - if set(b.width(), b.height(), &bytes).is_ok() { - self.os_clip_sig = Some(clip_signature(b.width(), b.height(), &bytes)); - self.clip_unmirrored = false; - } - } - - /// File › New's fields: the defaults, then the settings of the last document made with the - /// dialog (Photoshop starts from them, #1810), then the Clipboard preset (the clipboard image's - /// size, selected) when the clipboard holds an image. Opening the dialog is an explicit - /// request, so the OS clipboard is read here, as for a paste. - pub(crate) fn new_document_fields(&mut self) -> serde_json::Map { - let mut f = crate::state::UiState::new_document_fields(); - if let Some(serde_json::Value::Object(saved)) = self.session.prefs().dialogs.get(NEW_DOCUMENT) { - for k in NEW_DOCUMENT_REMEMBERED { - if let Some(v) = saved.get(k).filter(|v| remembered_new_document_value(k, v)) { - f.insert(k.into(), v.clone()); - } - } - } - if self.import_os_clipboard().is_err() { - return f; - } - if let Some(c) = self.session.clipboard.as_ref().filter(|c| !c.bounds.is_empty()) { - crate::new_doc_ui::set_clipboard(&mut f, c.bounds.width(), c.bounds.height()); - } - f - } - - /// If the OS clipboard holds an image that isn't the one we put there, make it the session - /// clipboard (so ⌘V pastes screenshots and images copied in other apps, like Photoshop). - /// Returns `Ok(true)` when a new external image was imported. Once the OS clipboard no longer holds - /// the image we mirrored or imported (text or a file was copied since), that image is stale: - /// it is dropped rather than pasted. Unexported internal copies survive unavailable or empty - /// system clipboards. - pub(crate) fn import_os_clipboard(&mut self) -> Result { - let Some(get) = self.services.clipboard_get_image.as_mut() else { return Ok(false) }; - // A read failure says nothing about the clipboard contents. Keep our editable copy and - // its signature rather than treating the failure as an empty image. - let image = match get() { - Ok(image) => image, - Err(error) => { - // An unexported copy remains usable without an OS clipboard (for example, in - // a Wayland sandbox). Mirrored/imported copies still require a successful read - // before pasting, because their system contents may have changed. - if self.clip_unmirrored && !self.clip_external && self.session.clipboard.is_some() { - return Ok(false); - } - if self.session.clipboard.is_none() && self.services.clipboard_unreadable.as_ref().is_some_and(|unreadable| unreadable()) { - // Let paste explain the unavailable backend without treating a saved copy as empty. - return Ok(false); - } - self.ui.status = error.clone(); - self.ui.status_error = true; - return Err(error); - } - }; - let image = image.filter(|(w, h, bytes)| *w > 0 && *h > 0 && bytes.len() == *w as usize * *h as usize * 4); - let Some((w, h, bytes)) = image else { - if self.os_clip_sig.take().is_some() && !self.clip_unmirrored { - self.session.clipboard = None; - self.clip_external = false; - self.clip_unmirrored = true; - } - return Ok(false); - }; - let sig = clip_signature(w, h, &bytes); - if self.os_clip_sig == Some(sig) && self.session.clipboard.is_some() { - return Ok(false); - } - let r = photocraft_geom::Rect::new(0, 0, w as i32, h as i32); - let mut surface = photocraft_raster::Surface::from_interleaved(photocraft_color::PixelFormat::RGBA8, r, &bytes); - surface.prune(); - self.session.clipboard = Some(photocraft_engine::edit_cmds::Clip { surface, bounds: r, layers: None, resolution: None, source: None }); - self.os_clip_sig = Some(sig); - self.clip_external = true; - self.clip_unmirrored = false; - Ok(true) - } -} - #[cfg(test)] mod lifecycle_tests; @@ -3730,491 +820,6 @@ mod polygon_lasso_tests; #[cfg(test)] mod window_frame_tests; -#[cfg(test)] -mod clipboard_tests { - use super::*; - use std::sync::{Arc, Mutex}; - - #[test] - fn os_clipboard_bridge() { - let os: OsClip = Arc::default(); - let (a, b) = (os.clone(), os.clone()); - let services = Services { - clipboard_set_image: Some(Box::new(move |w: u32, h: u32, px: &[u8]| { - *a.lock().unwrap() = Some((w, h, px.to_vec())); - Ok(()) - })), - clipboard_get_image: Some(Box::new(move || Ok(b.lock().unwrap().clone()))), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - app.session.execute("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app.run("select.rect", serde_json::json!({"x": 0, "y": 0, "width": 8, "height": 4})).unwrap(); - app.run("edit.copy", serde_json::json!({})).unwrap(); - let (w, h, px) = os.lock().unwrap().clone().unwrap(); - assert_eq!((w, h, px.len()), (8, 4, 8 * 4 * 4)); - // Our own image comes back unchanged (no re-import, keeps the original position). - assert!(!app.import_os_clipboard().unwrap()); - // Text copied elsewhere replaces our image: nothing to paste, not the stale image. - let ours = os.lock().unwrap().take(); - assert!(!app.import_os_clipboard().unwrap()); - assert!(app.session.clipboard.is_none()); - *os.lock().unwrap() = ours; - app.run("edit.copy", serde_json::json!({})).unwrap(); - // Another app puts a 3×2 red image on the clipboard: ⌘V pastes it. - *os.lock().unwrap() = Some((3, 2, [255u8, 0, 0, 255].repeat(6))); - app.run("edit.paste", serde_json::json!({})).unwrap(); - let st = app.session.active().unwrap(); - let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - assert_eq!(surf.content_bounds().width(), 3); - } - - #[test] - fn os_clipboard_honours_export_clipboard_preference() { - let os: OsClip = Arc::default(); - let a = os.clone(); - let services = Services { - clipboard_set_image: Some(Box::new(move |w: u32, h: u32, px: &[u8]| { - *a.lock().unwrap() = Some((w, h, px.to_vec())); - Ok(()) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - app.session.execute("prefs.set", serde_json::json!({"values": {"general.exportClipboard": false}})).unwrap(); - app.session.execute("file.new", serde_json::json!({"width": 32, "height": 32})).unwrap(); - app.sync_views(); - app.run("select.rect", serde_json::json!({"x": 0, "y": 0, "width": 8, "height": 4})).unwrap(); - app.run("edit.copy", serde_json::json!({})).unwrap(); - assert!(os.lock().unwrap().is_none(), "copy does not mirror to OS clipboard when export_clipboard is off"); - } - - type OsClip = Arc)>>>; - - #[test] - fn failed_clipboard_reads_preserve_editable_contents_until_retry() { - use std::sync::atomic::{AtomicBool, Ordering}; - for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace", "file.newFromClipboard"] { - let os = OsClip::default(); - let busy = Arc::new(AtomicBool::new(false)); - let (write, read, unavailable) = (os.clone(), os.clone(), busy.clone()); - let services = Services { - clipboard_set_image: Some(Box::new(move |w, h, bytes| { - *write.lock().unwrap() = Some((w, h, bytes.to_vec())); - Ok(()) - })), - clipboard_get_image: Some(Box::new(move || { - if unavailable.load(Ordering::SeqCst) { Err("clipboard is busy".into()) } else { Ok(read.lock().unwrap().clone()) } - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); - app.run("shape.create", serde_json::json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); - app.run("edit.copy", serde_json::json!({})).unwrap(); - app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); - let signature = app.os_clip_sig; - assert!(signature.is_some()); - let before = app.session.active().unwrap().doc.walk().len(); - busy.store(true, Ordering::SeqCst); - let result = crate::menus::invoke(&mut app, &egui::Context::default(), id, serde_json::json!({})); - assert_eq!(result.unwrap_err(), "clipboard is busy", "{id}"); - assert!(app.ui.status_error); - assert_eq!(app.session.documents().len(), 2); - assert_eq!(app.session.active().unwrap().doc.walk().len(), before); - assert_eq!(app.os_clip_sig, signature); - assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); - // The New dialog also reads the clipboard; a failed preset probe must preserve it. - app.new_document_fields(); - assert_eq!(app.os_clip_sig, signature); - assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); - // An automation error must not leave script events disabled by the dispatch guard. - app.automation_input = true; - app.session.edit_prefs(|prefs| prefs.script_events.enabled = true); - assert!(app.run(id, serde_json::json!({})).is_err()); - assert!(app.session.prefs().script_events.enabled); - app.automation_input = false; - busy.store(false, Ordering::SeqCst); - app.run("edit.pasteSpecial.pasteInPlace", serde_json::json!({})).unwrap(); - let state = app.session.active().unwrap(); - assert!(matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Shape(_))); - assert!(!app.ui.status_error); - } - } - - #[test] - fn internal_only_clipboard_remains_usable_when_native_access_fails() { - use std::sync::atomic::{AtomicBool, Ordering}; - for export in [true, false] { - for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace", "file.newFromClipboard"] { - let os = OsClip::default(); - let unavailable = Arc::new(AtomicBool::new(true)); - let (read, failed) = (os.clone(), unavailable.clone()); - let services = Services { - clipboard_set_image: Some(Box::new(|_, _, _| Err("clipboard unavailable".into()))), - clipboard_get_image: Some(Box::new(move || { - if failed.load(Ordering::SeqCst) { Err("clipboard unavailable".into()) } else { Ok(read.lock().unwrap().clone()) } - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - app.session.edit_prefs(|prefs| prefs.general.export_clipboard = export); - app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); - app.run("shape.create", serde_json::json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); - app.run("edit.copy", serde_json::json!({})).unwrap(); - app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); - assert!(app.os_clip_sig.is_none() && !app.clip_external); - let bounds = app.session.clipboard.as_ref().unwrap().bounds; - assert_eq!(app.new_document_fields()["__preset"], "Clipboard"); - crate::menus::invoke(&mut app, &egui::Context::default(), id, serde_json::json!({})).unwrap(); - assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); - assert!(!app.ui.status_error); - if id == "file.newFromClipboard" { - assert_eq!(app.session.documents().len(), 3); - let doc = &app.session.active().unwrap().doc; - assert_eq!((doc.size.width, doc.size.height), (bounds.width(), bounds.height())); - } else { - assert_eq!(app.session.documents().len(), 2); - let state = app.session.active().unwrap(); - assert!(matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Shape(_))); - } - app.run("edit.purge.clipboard", serde_json::json!({})).unwrap(); - assert!(app.session.clipboard.is_none()); - assert!(app.run("edit.paste", serde_json::json!({})).is_err(), "purged content must not be a fallback"); - // The fallback is only for failed reads: a later successful external image wins. - *os.lock().unwrap() = Some((3, 2, [0u8, 0, 255, 255].repeat(6))); - unavailable.store(false, Ordering::SeqCst); - app.run("edit.paste", serde_json::json!({})).unwrap(); - assert!(app.clip_external && app.os_clip_sig.is_some()); - let clip = app.session.clipboard.as_ref().unwrap(); - assert!(clip.layers.is_none()); - assert_eq!((clip.bounds.width(), clip.bounds.height()), (3, 2)); - } - } - } - - #[test] - fn newer_unexported_copies_do_not_track_an_older_os_signature() { - use std::sync::atomic::{AtomicBool, Ordering}; - for imported in [true, false] { - for disable_export in [true, false] { - for copy_id in ["edit.copy", "edit.cut", "edit.copyMerged"] { - let os = OsClip::default(); - let write_fails = Arc::new(AtomicBool::new(false)); - let read_fails = Arc::new(AtomicBool::new(false)); - let (write, read, failed_write, failed_read) = (os.clone(), os.clone(), write_fails.clone(), read_fails.clone()); - let services = Services { - clipboard_set_image: Some(Box::new(move |w, h, bytes| { - if failed_write.load(Ordering::SeqCst) { - return Err("clipboard unavailable".into()); - } - *write.lock().unwrap() = Some((w, h, bytes.to_vec())); - Ok(()) - })), - clipboard_get_image: Some(Box::new(move || { - if failed_read.load(Ordering::SeqCst) { Err("clipboard unavailable".into()) } else { Ok(read.lock().unwrap().clone()) } - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - app.run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); - if imported { - *os.lock().unwrap() = Some((2, 2, [255u8, 0, 0, 255].repeat(4))); - assert!(app.import_os_clipboard().unwrap()); - } else { - app.run("edit.fill", serde_json::json!({"color": "#ff0000"})).unwrap(); - app.run("edit.copy", serde_json::json!({})).unwrap(); - } - let old_signature = app.os_clip_sig; - assert!(old_signature.is_some() && !app.clip_unmirrored); - app.run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); - app.run("edit.fill", serde_json::json!({"color": "#0000ff"})).unwrap(); - write_fails.store(true, Ordering::SeqCst); - app.session.edit_prefs(|prefs| prefs.general.export_clipboard = !disable_export); - app.run(copy_id, serde_json::json!({})).unwrap(); - let copied = app.session.clipboard.clone().unwrap(); - assert!(app.clip_unmirrored && !app.clip_external); - assert_eq!(app.os_clip_sig, old_signature); - assert_eq!(copied.surface.rgba(0, 0), [0.0, 0.0, 1.0, 1.0]); - // An old successful export/import must not block the newer internal copy. - read_fails.store(true, Ordering::SeqCst); - app.run("edit.pasteSpecial.pasteInPlace", serde_json::json!({})).unwrap(); - assert_eq!(app.os_clip_sig, old_signature); - assert!(app.clip_unmirrored && !app.clip_external); - read_fails.store(false, Ordering::SeqCst); - assert!(!app.import_os_clipboard().unwrap(), "unchanged old OS image must not overwrite the newer copy"); - assert_eq!(app.session.clipboard.as_ref().unwrap().surface.rgba(0, 0), copied.surface.rgba(0, 0)); - *os.lock().unwrap() = None; - assert!(!app.import_os_clipboard().unwrap(), "empty OS clipboard must not discard an unexported copy"); - assert!(app.os_clip_sig.is_none() && app.clip_unmirrored); - assert_eq!(app.session.clipboard.as_ref().unwrap().surface.rgba(0, 0), copied.surface.rgba(0, 0)); - // A different external image supersedes the internal copy and disables fallback. - *os.lock().unwrap() = Some((3, 2, [0u8, 255, 0, 255].repeat(6))); - assert!(app.import_os_clipboard().unwrap()); - assert!(app.clip_external && !app.clip_unmirrored); - let clip = app.session.clipboard.as_ref().unwrap(); - assert_eq!((clip.bounds.width(), clip.bounds.height()), (3, 2)); - read_fails.store(true, Ordering::SeqCst); - assert!(app.run("edit.paste", serde_json::json!({})).is_err()); - } - } - } - } - - #[test] - fn failed_clipboard_reads_do_not_paste_an_external_or_missing_copy() { - use std::sync::atomic::{AtomicBool, Ordering}; - for external in [true, false] { - let unavailable = Arc::new(AtomicBool::new(false)); - let failed = unavailable.clone(); - let services = Services { - clipboard_get_image: Some(Box::new(move || { - if failed.load(Ordering::SeqCst) { Err("clipboard unavailable".into()) } else { Ok(Some((3, 2, [255u8, 0, 0, 255].repeat(6)))) } - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); - if external { - assert!(app.import_os_clipboard().unwrap()); - } - let signature = app.os_clip_sig; - let before = app.session.active().unwrap().doc.walk().len(); - unavailable.store(true, Ordering::SeqCst); - for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace", "file.newFromClipboard"] { - let result = crate::menus::invoke(&mut app, &egui::Context::default(), id, serde_json::json!({})); - assert_eq!(result.unwrap_err(), "clipboard unavailable", "{id}"); - assert!(app.ui.status_error); - assert_eq!(app.session.documents().len(), 1); - assert_eq!(app.session.active().unwrap().doc.walk().len(), before); - assert_eq!(app.os_clip_sig, signature); - assert_eq!(app.session.clipboard.is_some(), external); - assert_eq!(app.clip_external, external); - } - } - } - - /// An app whose OS clipboard is `os`, counting every read in `reads`. - fn app_with_os_clipboard(os: &OsClip, reads: &Arc) -> PhotocraftApp { - let (b, n) = (os.clone(), reads.clone()); - let get = move || { - n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(b.lock().unwrap().clone()) - }; - let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(Box::new(get)), ..Default::default() }); - app.session.execute("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app - } - - /// Paste is enabled from the clipboard service alone (no read); the explicit paste imports - /// the OS image, once, and centres it in the view like Photoshop does for foreign clipboard - /// content. - #[test] - fn external_clipboard_enables_and_centres_paste() { - let (os, reads) = (OsClip::default(), Arc::default()); - let mut app = app_with_os_clipboard(&os, &reads); - *os.lock().unwrap() = Some((4, 4, [255u8, 0, 0, 255].repeat(16))); - assert!(app.session.clipboard.is_none()); - assert!(crate::menus::is_enabled(&app, "edit.paste")); - assert!(crate::menus::is_enabled(&app, "edit.pasteSpecial.pasteInPlace")); - assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 0, "enablement never reads the clipboard"); - app.ui.views[0].center = [40.0, 20.0]; - let r = crate::menus::invoke(&mut app, &egui::Context::default(), "edit.paste", serde_json::json!({})).unwrap(); - assert_eq!(r["offset"], serde_json::json!([38, 18]), "external image is centred in the view: {r}"); - assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 1, "one read per explicit paste"); - // Without a clipboard service Paste greys until something is copied in the app. - let mut plain = PhotocraftApp::new(Session::new(), Services::default()); - plain.session.execute("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); - assert!(!crate::menus::is_enabled(&plain, "edit.paste")); - } - - /// #368: an image copied in another app opens as a document of its own, from File › New - /// from Clipboard or from Paste with nothing open. - #[test] - fn os_clipboard_image_becomes_a_new_document() { - let (os, reads) = (OsClip::default(), Arc::new(std::sync::atomic::AtomicUsize::new(0))); - let (b, n) = (os.clone(), Arc::clone(&reads)); - let get = move || { - n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(b.lock().unwrap().clone()) - }; - let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(Box::new(get)), ..Default::default() }); - let ctx = egui::Context::default(); - // Listed right after File › New…, enabled without reading the clipboard. - let items = crate::menus::menu_items(&app); - let at = items.iter().position(|i| i.id == "file.new").unwrap(); - assert_eq!(items[at + 1].id, "file.newFromClipboard"); - assert!(items[at + 1].enabled && crate::menus::is_enabled(&app, "edit.paste")); - assert!(!crate::menus::is_enabled(&app, "edit.pasteSpecial.pasteInPlace"), "Paste in Place needs a document"); - assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 0); - // An empty clipboard is a quiet no-op. - let r = crate::menus::invoke(&mut app, &ctx, "file.newFromClipboard", serde_json::json!({})).unwrap(); - assert_eq!(r["pasted"], serde_json::json!(false)); - assert!(app.session.documents().is_empty() && !app.ui.status_error); - // Paste with nothing open makes the document. - *os.lock().unwrap() = Some((5, 3, [0u8, 0, 255, 255].repeat(15))); - crate::menus::invoke(&mut app, &ctx, "edit.paste", serde_json::json!({})).unwrap(); - let d = &app.session.active().unwrap().doc; - assert_eq!((d.size.width, d.size.height, d.layers.len()), (5, 3, 1)); - assert_eq!(app.ui.views.len(), 1, "the new document has a view"); - assert!(app.has_unsaved_work(), "closing after Paste must ask to save"); - // New from Clipboard with a document open adds another. - crate::menus::invoke(&mut app, &ctx, "file.newFromClipboard", serde_json::json!({})).unwrap(); - assert_eq!(app.session.documents().len(), 2); - assert!(app.session.documents().iter().all(|d| d.is_dirty())); - assert!(crate::discard_ui::intercept(&mut app, "file.close", &serde_json::json!({})), "Close must ask before discarding clipboard pixels"); - } - - #[test] - fn pasting_an_empty_or_non_image_os_clipboard_is_a_quiet_no_op() { - let (os, reads) = (OsClip::default(), Arc::default()); - let mut app = app_with_os_clipboard(&os, &reads); - let layers = app.session.active().unwrap().doc.layers.len(); - let r = crate::menus::invoke(&mut app, &egui::Context::default(), "edit.paste", serde_json::json!({})).unwrap(); - assert_eq!(r["pasted"], serde_json::json!(false)); - assert_eq!(app.run("edit.pasteSpecial.pasteInPlace", serde_json::json!({})).unwrap()["pasted"], serde_json::json!(false)); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers); - assert!(!app.ui.status_error && !app.ui.status.is_empty()); - } - - #[test] - fn idle_frames_never_read_the_os_clipboard() { - let (os, reads) = (OsClip::default(), Arc::::default()); - *os.lock().unwrap() = Some((4, 4, [255u8, 0, 0, 255].repeat(16))); - let (b, n) = (os.clone(), reads.clone()); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - let get = move || { - n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(b.lock().unwrap().clone()) - }; - let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(Box::new(get)), ..Default::default() }); - app.session.execute("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); - app - }); - for _ in 0..20 { - h.step(); - } - assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 0, "the OS clipboard is read only on an explicit paste"); - assert!(h.state().session.clipboard.is_none()); - } - - /// #2928: with the layer mask targeted, ⌘C copies the mask's values as grayscale, not the - /// layer's pixels — so ⌘V (targeting another layer's mask, #1035) moves the mask itself. - #[test] - fn copy_with_the_mask_targeted_copies_the_mask_not_the_pixels() { - let (os, reads) = (OsClip::default(), Arc::default()); - let mut app = app_with_os_clipboard(&os, &reads); - app.run("layer.new.layer", serde_json::json!({})).unwrap(); - app.run("layer.layerMask.hideAll", serde_json::json!({})).unwrap(); - // Black pixels, a white square in the mask: the copy must carry the mask. - app.run("select.all", serde_json::json!({})).unwrap(); - app.run("edit.fill", serde_json::json!({"color": "#000000"})).unwrap(); - app.run("select.rect", serde_json::json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); - app.run("edit.fill", serde_json::json!({"color": "#ffffff", "target": "mask"})).unwrap(); - app.run("select.deselect", serde_json::json!({})).unwrap(); - app.ui.mask_target = true; - crate::menus::invoke(&mut app, &egui::Context::default(), "edit.copy", serde_json::json!({})).unwrap(); - let clip = app.session.clipboard.clone().expect("the mask was copied"); - let st = app.session.active().unwrap(); - let (w, h) = (st.doc.size.width as i32, st.doc.size.height as i32); - assert_eq!( - [clip.bounds.x0, clip.bounds.y0, clip.bounds.width() as i32, clip.bounds.height() as i32], - [0, 0, w, h], - "the mask, whole — not the black pixels" - ); - let px = clip.surface.rgba(6, 6); - assert!(px[0] > 0.99 && px[3] > 0.99, "white mask values: {px:?}"); - assert!(clip.surface.rgba(20, 20)[0] < 0.01, "the hidden area copies as black"); - } - - /// #1035: with the layer mask targeted (its thumbnail clicked), ⌘V pastes the clipboard's - /// luminosity into the mask instead of making a layer. - #[test] - fn paste_with_the_mask_targeted_goes_into_the_mask() { - let (os, reads) = (OsClip::default(), Arc::default()); - let mut app = app_with_os_clipboard(&os, &reads); - app.run("layer.new.layer", serde_json::json!({})).unwrap(); - app.run("layer.layerMask.hideAll", serde_json::json!({})).unwrap(); - app.ui.mask_target = true; - app.ui.views[0].center = [32.0, 32.0]; - *os.lock().unwrap() = Some((4, 4, [128u8, 128, 128, 255].repeat(16))); - let layers = app.session.active().unwrap().doc.layer_count(); - crate::menus::invoke(&mut app, &egui::Context::default(), "edit.paste", serde_json::json!({})).unwrap(); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.layer_count(), layers, "no new layer"); - let mask = st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap(); - assert!((mask.value(32, 32) - 128.0 / 255.0).abs() < 2.0 / 255.0, "the grey, centred in the view: {}", mask.value(32, 32)); - assert_eq!(mask.value(0, 0), 0.0, "the rest of the mask is unchanged"); - } - - /// #2166, measured in Photoshop 25.1: adding a layer mask targets it with white/black, and - /// the pixels and the mask each keep their own foreground/background pair. - #[test] - fn targeting_a_mask_swaps_to_its_own_colour_pair() { - use serde_json::json; - const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; - const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; - const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; - const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; - const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0]; - let mut app = PhotocraftApp::new(Session::new(), Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - let masked = app.run("layer.new.layer", json!({})).unwrap()["layer"].clone(); - app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); - let pair = |app: &PhotocraftApp| (app.session.tools.foreground, app.session.tools.background); - let target = |app: &mut PhotocraftApp, mask: bool| { - app.ui.mask_target = mask; - app.sync_views(); - }; - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - assert!(app.ui.mask_target, "the new mask is targeted"); - assert_eq!(pair(&app), (WHITE, BLACK)); - target(&mut app, false); - assert_eq!(pair(&app), (RED, BLUE), "the pixels get their colours back"); - target(&mut app, true); - assert_eq!(pair(&app), (WHITE, BLACK)); - target(&mut app, false); - app.run("tools.setColors", json!({"foreground": "#00ff00"})).unwrap(); - target(&mut app, true); - assert_eq!(pair(&app), (WHITE, BLACK)); - target(&mut app, false); - assert_eq!(pair(&app), (GREEN, BLUE)); - // A layer without a mask edits its pixels: their pair. - target(&mut app, true); - app.run("layer.new.layer", json!({})).unwrap(); - assert_eq!(pair(&app), (GREEN, BLUE)); - app.run("layer.select", json!({"layer": masked})).unwrap(); - target(&mut app, true); - assert_eq!(pair(&app), (WHITE, BLACK)); - app.run("layer.layerMask.delete", json!({})).unwrap(); - assert_eq!(pair(&app), (GREEN, BLUE), "deleting the targeted mask goes back to the pixels"); - } -} - -#[cfg(test)] -mod channel_tint_tests { - use super::channel_tint; - use egui::Color32; - use photocraft_doc::ColorMode::{Cmyk, Grayscale, Rgb}; - - #[test] - fn channels_in_color_tint_rgb_from_black_and_cmyk_inks_from_white() { - assert_eq!(channel_tint(Rgb, 0, 255, true), Color32::from_rgb(255, 0, 0)); - assert_eq!(channel_tint(Rgb, 2, 0, true), Color32::BLACK); - // CMYK: no ink is white, full ink is the ink's colour. - assert_eq!(channel_tint(Cmyk, 0, 255, true), Color32::WHITE); - assert_eq!(channel_tint(Cmyk, 0, 0, true), Color32::from_rgb(0, 255, 255)); - assert_eq!(channel_tint(Cmyk, 1, 0, true), Color32::from_rgb(255, 0, 255)); - assert_eq!(channel_tint(Cmyk, 2, 0, true), Color32::from_rgb(255, 255, 0)); - assert_eq!(channel_tint(Cmyk, 3, 0, true), Color32::BLACK); - assert_eq!(channel_tint(Grayscale, 0, 77, true), Color32::from_gray(77)); - assert_eq!(channel_tint(Rgb, 0, 77, false), Color32::from_gray(77)); - } -} - #[cfg(test)] mod browse_field_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs new file mode 100644 index 0000000000..d330884a0a --- /dev/null +++ b/crates/ui-egui/src/services.rs @@ -0,0 +1,441 @@ +use super::*; + +/// The error a save gets while another save waits on its format prompt. +pub(crate) const SAVE_OPTIONS_OPEN: &str = "Answer the TIFF, Targa, DDS or JPEG Options before starting another save"; + +/// The format answers a save takes instead of asking: the Targa bits per pixel (`"tgaBits"`), +/// the DDS options (`"ddsCompression"`, `"ddsMipmaps"`) and JPEG Options (`"quality"` 0–12, +/// `"jpegFormat"`). `None` asks in Save As and takes the default in automation saves, which never +/// prompt. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct FormatChoices { + pub tga_bits: Option, + pub dds: Option, + pub jpeg: Option, +} + +impl FormatChoices { + /// The answers in command or control call `cmd`'s params; a bad value is an error. + pub fn from_params(params: &Value, cmd: &str) -> Result { + Ok(FormatChoices { + tga_bits: targa_options_ui::bits_param(params, cmd)?, + dds: dds_options_ui::options_param(params, cmd)?, + jpeg: jpeg_options_ui::choice_param(params, cmd)?, + }) + } + + /// The answers in a recorded save step, read as leniently as the engine command that may have + /// recorded it (see [`jpeg_options_ui::recorded_choice`]). + pub(crate) fn from_step(params: &Value, cmd: &str) -> Result { + Ok(FormatChoices { + tga_bits: targa_options_ui::bits_param(params, cmd)?, + dds: dds_options_ui::options_param(params, cmd)?, + jpeg: jpeg_options_ui::recorded_choice(params, cmd)?, + }) + } + + /// The export settings with these answers applied. + pub fn apply(self, settings: ExportSettings) -> ExportSettings { + let settings = ExportSettings { tga_bits: self.tga_bits.or(settings.tga_bits), dds: self.dds.unwrap_or(settings.dds), ..settings }; + match self.jpeg { + Some(j) => j.apply(settings), + None => settings, + } + } + + /// Adds the answers to a recorded save step. + pub(crate) fn record(self, step: &mut Value) { + if let Some(bits) = self.tga_bits { + step["tgaBits"] = bits.bits().into(); + } + if let Some(dds) = self.dds { + dds_options_ui::record(dds, step); + } + if let Some(j) = self.jpeg { + j.record(step); + } + } +} + +/// Decode a file: (document, warnings about anything approximated or dropped). +pub type ImportFn = Box Result<(Document, Vec), String>>; + +/// Encoder settings chosen in Export As (the file format comes from the name's extension). +#[derive(Clone, Debug, PartialEq)] +pub struct ExportSettings { + /// JPEG quality 1–100 (None = codec default). + pub jpeg_quality: Option, + /// JPEG Options › Format Options: baseline, baseline optimized or progressive. + pub jpeg_format: photocraft_codecs::JpegFormat, + /// WebP: lossless (VP8L) rather than lossy (VP8 at [`Self::webp_quality`]). + pub webp_lossless: bool, + /// Lossy WebP quality 1–100 (None = codec default). + pub webp_quality: Option, + /// TIFF: keep the layers (Photoshop layer data); `false` is "Discard Layers and Save a Copy". + pub tiff_layers: bool, + /// Embed the document's whole XMP packet. `true` by default (Save As keeps the metadata); + /// Export As starts at Metadata: None, since the packet can carry the text of every type + /// layer and one id per placed document (#647). + pub xmp_all: bool, + /// Targa: bits per pixel from Targa Options or Export As (`None`: 32 with an alpha channel or + /// transparency, else 24). + pub tga_bits: Option, + /// DDS: the compression and mip chain from DDS Options (uncompressed without mipmaps unless + /// chosen). + pub dds: photocraft_io::DdsOptions, + /// PSD/PSB: embed a thumbnail (Preferences › File Handling › Image Previews; see + /// [`PhotocraftApp::save_settings`]). + pub image_previews: bool, + /// PSD/PSB: write the real merged image (Preferences › File Handling › Maximize PSD and PSB + /// File Compatibility; see [`PhotocraftApp::save_settings`]). + pub psd_maximize_compatibility: bool, + /// Embed the document's ICC profile when the format supports it. On for Save As and, unless + /// Export As turns it off, for export. + pub embed_icc: bool, + /// Embed EXIF, resolution and other non-XMP metadata when the format supports it. Export As + /// turns this off for Metadata: None; Save As leaves it on. + pub embed_metadata: bool, + /// The path of the document's own file, which linked smart objects that PSD/PSB embed are + /// resolved against ([`photocraft_io::ExportOptions::document_path`]). + pub document_path: Option, + /// Native save cache owned by the open document; exports without one remain one-shot. + pub pcraft_cache: Option, + /// Read and embed the files linked smart objects name ([`photocraft_io::ExportOptions::read_linked_files`]). + /// Off for automation saves, which are granted only their target. + pub read_linked_files: bool, +} + +impl Default for ExportSettings { + fn default() -> Self { + ExportSettings { + jpeg_quality: None, + jpeg_format: photocraft_codecs::JpegFormat::Baseline, + webp_lossless: true, + webp_quality: None, + tiff_layers: true, + xmp_all: true, + tga_bits: None, + dds: photocraft_io::DdsOptions::default(), + image_previews: true, + psd_maximize_compatibility: true, + embed_icc: true, + embed_metadata: true, + document_path: None, + pcraft_cache: None, + read_linked_files: true, + } + } +} + +impl ExportSettings { + /// The IO export options these encoder settings select. Save As and Export As share this so + /// a profile or metadata choice cannot be applied in one and forgotten in the other. + pub fn io_options(&self) -> photocraft_io::ExportOptions { + let mut opts = photocraft_io::ExportOptions::default(); + if let Some(q) = self.jpeg_quality { + opts.encode.jpeg_quality = q; + } + opts.encode.jpeg_format = self.jpeg_format; + opts.encode.webp_lossless = self.webp_lossless; + if let Some(q) = self.webp_quality { + opts.encode.webp_quality = q; + } + opts.encode.embed_icc = self.embed_icc; + opts.encode.embed_metadata = self.embed_metadata; + opts.tiff_layers = self.tiff_layers; + opts.xmp = if self.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None }; + opts.tga_bits = self.tga_bits; + opts.encode.dds = self.dds; + opts.image_previews = self.image_previews; + opts.psd_maximize_compatibility = self.psd_maximize_compatibility; + opts.document_path = self.document_path.clone(); + opts.pcraft_cache = self.pcraft_cache.clone(); + opts.read_linked_files = self.read_linked_files; + opts + } +} + +/// The document's lone layer when it is a plain raster a flat file keeps: visible, at full +/// opacity, in Normal mode, with no masks, effects or blending restrictions (#2234). +pub(crate) fn plain_raster(doc: &Document) -> Option<&photocraft_doc::Layer> { + match doc.layers.as_slice() { + [layer] + if matches!(layer.content, photocraft_doc::LayerContent::Raster(_)) + && layer.visible + && layer.opacity >= 1.0 + && layer.fill_opacity >= 1.0 + && layer.mask.is_none() + && layer.vector_mask.is_none() + && layer.effects.items.is_empty() + && layer.effects.psd_raw.is_none() + && matches!(layer.blend, photocraft_color::BlendMode::Normal | photocraft_color::BlendMode::PassThrough) + && photocraft_compose::channel_weights(layer, doc.mode).is_none() + && !photocraft_compose::blend_if_active(layer, doc.mode) => + { + Some(layer) + } + _ => None, + } +} + +/// Encode a document: (file bytes, warnings about anything approximated or dropped). +pub type ExportFn = Box Result<(Vec, Vec), String>>; + +pub type WriteFn = Box Result<(), String>>; + +/// What a file on disk looked like when a document last read or wrote it: File › Save asks +/// before replacing a file another app changed since (#6596). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FileStamp { + pub len: u64, + pub modified: Option, +} + +/// The [`FileStamp`] of the file at a path, `None` when it can't be read. +pub type FileStampFn = Box Option>; + +/// Whether two paths name one entry in one folder on disk; false when either can't be read. +pub type SameFileFn = Box bool>; + +/// Encode a document and write it to a path, reporting the stage to the job; returns the export +/// warnings. Runs on a worker thread (see [`Services::save_file`]). It must call +/// [`jobs_ui::SaveCtl::commit`] right before replacing the file, and write nothing if that fails. +pub type SaveFileFn = std::sync::Arc Result, String> + Send + Sync>; + +/// The revision a document counts as saved at after `written` went to its writer: that one when +/// the writer confirms the bytes were stored, else still `previous`, so the document stays +/// unsaved. A browser download is only a request the user can cancel (#4962). +pub(crate) fn saved_revision_after_write(confirmed: bool, written: u64, previous: u64) -> u64 { + if confirmed { written } else { previous } +} + +/// Who a finished save serves. +#[derive(Clone, Copy)] +pub(crate) enum SaveKind { + /// Interactive: arm the document's file and fire user-configured hooks. + User, + /// Automation: flat formats stay copies (#2579) and hooks never fire. + Automation, +} + +/// Read bytes through the desktop control session's authorized read root. +pub type AutomationReadFn = Box Result<(String, Vec), String>>; + +/// Write bytes through the desktop control session's authorized write root. +pub type AutomationWriteFn = Box Result<(), String>>; + +/// Load a directory-form `.pcraft` through the authorized read root, returning its display +/// name (the file name) and the loaded document. `Ok(None)` marks a regular file: the +/// caller falls back to the bytes path for the zip form. +pub type AutomationOpenPcraftFn = Box Result, String>>; + +/// Reject engine commands which still perform ambient filesystem I/O. +pub type AutomationCommandFn = Box Result<(), String>>; + +/// Open a URL in the system browser (native) — reliable cross-platform, unlike `ctx.open_url`. +pub type OpenUrlFn = Box Result<(), String>>; + +pub type EncodePngFn = Box Result, String>>; + +/// Put an RGBA8 image (width, height, pixels) on the OS clipboard. +pub type ClipboardSetFn = Box Result<(), String>>; + +/// Read an RGBA8 image from the OS clipboard. `Ok(None)` means no image is available; +/// `Err` means the contents could not be read and must not invalidate the internal copy. +pub type ClipboardGetFn = Box Result)>, String>>; + +/// Whether the last clipboard read found no way to reach the OS clipboard at all. +pub type ClipboardUnreadableFn = Box bool>; + +/// Shared queue of (file name, bytes) delivered asynchronously. +pub type Inbox = std::sync::Arc)>>>; + +/// Read the saved preferences text (`None` when there is none yet). +pub type LoadTextFn = Box Option>; + +/// Persist the preferences text. +pub type SaveTextFn = Box Result<(), String>>; + +/// Platform appearance when egui cannot detect it (for example, Wayland without a theme event). +pub type SystemThemeFn = Box Option>; + +/// Autosave a document snapshot for crash recovery: (snapshot, revision, original path). +pub type AutosaveFn = Box, u64, Option<&str>) -> Result<(), String>>; + +/// Poll successful or failed background writes: (document id, revision, result). +pub type AutosaveResultsFn = Box Vec<(u64, u64, Result<(), String>)>>; + +/// Drop the recovery data of a document (by `DocId` value) once it is saved or closed. +pub type DiscardAutosaveFn = Box; + +/// List recoverable documents without decoding them. Their data stays until the documents are +/// saved or closed; the shell runs each entry's loader on a background worker. +pub type RecoverFn = Box Vec>; + +/// Photoshop's own keyboard shortcut set on this machine, as (source path, `.kys` XML text): +/// the newest install's live `Keyboard Shortcuts.psp` on the desktop, `None` without one. +pub type PhotoshopShortcutsFn = Box Option<(String, String)>>; + +/// A recovered document (by `DocId` value, once open) takes over its recovery entry (by key): +/// its autosaves replace the entry, and saving or closing it drops the entry. +pub type AdoptAutosaveFn = Box; + +/// A recovery entry [`RecoverFn`] found; its loader owns only the data it needs to read. +pub struct Recoverable { + /// The recovery entry to adopt once loading succeeds (see [`AdoptAutosaveFn`]). + pub key: String, + pub name: String, + /// Where the user last saved it, if anywhere. + pub path: Option, + pub load: Box Result + Send + 'static>, +} + +/// Append text to a file (History Log). +pub type AppendTextFn = Box Result<(), String>>; + +/// Requests from the operating system since the last call (see [`OsEvent`]). +pub type OsEventsFn = Box Vec>; + +/// Ends the app the platform's own way (see [`Services::quit`]). +pub type QuitFn = Box; + +/// Where the OS pointer is now, in egui points within the window; `None` when unknown. +pub type CursorPosFn = Box Option>; + +/// Whether Caps Lock is toggled on, read from the OS. `None` where the platform cannot +/// report it (native Wayland): the cursor then follows the cursor preference (#1758). +pub type CapsLockFn = Box bool>; + +/// Keeps an undecorated window's OS frame from offsetting its content and pointer (#2246). +/// Called once per frame; `None` when the window is decorated or the platform needs no fixing. +pub type WindowFrameFn = Box; + +/// The caption buttons' current style ([`Services::caption_style`]). +pub type CaptionStyleFn = Box CaptionStyle>; + +/// Physical right mouse button or stylus barrel button down (Windows; read for brush resize). +pub type RightButtonDownFn = Box bool + Send + Sync>; + +/// Platform services injected by the app binary (file dialogs, codecs), keeping this crate free of +/// I/O dependencies. +#[derive(Default)] +pub struct Services { + /// User-initiated desktop/browser pixel sampling. + pub screen_pick: Option, + /// Decode a file's bytes into a document (PSD, PNG, JPEG, …). + pub import: Option, + /// Encode a document for a file name (format chosen by extension). + pub export: Option, + /// Background save over the automation write authority (`app.save`, #2017): same worker + /// contract as `save_file`, but the bytes go through the capability-scoped workspace. + pub automation_save: Option, + /// Show an Open or Save dialog without waiting for it (see `file_dialog`). + pub file_dialog: Option, + /// Write bytes to a path (native) or trigger a download (web). + pub write: Option, + /// Size and modification time of a file (native); `None` on the web, where Save never + /// writes back to a file. + pub file_stamp: Option, + /// Whether two paths name one entry in one folder (native): a save dialog's answer and the + /// path the save writes to after Lowercase Extension, on a file system that ignores letter + /// case. A hard link is another entry. A save asks before replacing an entry it finds + /// different (`replace_prompt`). + pub same_file: Option, + /// `write` only asks for the bytes to be kept (a browser download, which the user can + /// cancel and which reports nothing back), so a save through it names the document but + /// leaves its changes unsaved and the leave-page guard armed (#4962). + pub write_unconfirmed: bool, + /// Encode and write in one step on a worker thread, so a large save doesn't freeze the + /// window (#2017). With background jobs on, saves use it instead of `export` and `write`. + pub save_file: Option, + /// File access used only by control/MCP requests. Interactive dialogs keep + /// using `file_dialog` and `write` with the user's authority. + pub automation_read: Option, + pub automation_write: Option, + pub automation_open_pcraft: Option, + pub automation_command: Option, + /// Same policy as [`Self::automation_command`], as a function pointer the engine calls for + /// each step of `actions.play`. Installed on the session only while a control request or + /// an automation-driven [`PhotocraftApp::run`] runs, so a local play of a recorded `file.*` step still works. + pub automation_authorize: Option photocraft_engine::Result<()>>, + /// Encode an RGBA8 image as PNG (used for screenshots and `ui.render`). + pub encode_png: Option, + /// Open a URL in the system browser (native). Falls back to `ctx.open_url` (web) when unset. + pub open_url: Option, + /// Preferences ▸ General ▸ Beep When Done: the platform's default beep, played when a + /// background job finishes successfully. `None` in the web build (and in tests). + pub beep: Option, + /// Starts a background check for published releases (desktop, outside Flatpak). + pub check_updates: Option, + /// Files delivered asynchronously (web drag-and-drop): drained every frame and opened as + /// documents. + pub inbox: Option, + /// Files delivered asynchronously for a drop onto the active document's canvas (web + /// drag-and-drop, routed by [`PhotocraftApp::dropped_on_canvas`]): placed as layers like a + /// desktop canvas drop (Place Embedded, each in Free Transform). + pub place_inbox: Option, + /// OS clipboard images: copies go out, screenshots and images from other apps come in. + pub clipboard_set_image: Option, + pub clipboard_get_image: Option, + /// True when the last `clipboard_get_image` read had no clipboard to read, as in a Flatpak on + /// Wayland (#5031), rather than a clipboard that holds no image. `None` where that can't happen. + pub clipboard_unreadable: Option, + /// Preferences persistence: the platform config directory on native, browser storage on + /// the web (see `prefs_ui`). + pub load_prefs: Option, + pub save_prefs: Option, + /// Photoshop's live keyboard shortcut set, imported once at first launch (`kys_import`). + pub photoshop_shortcuts: Option, + pub system_theme: Option, + /// The native window is connected directly to a Wayland compositor. + pub is_wayland: bool, + /// On Wayland, the shell command that starts this install under XWayland, where native file + /// drops work (#386); `None` when there is no X server to run it on. + pub xwayland_command: Option, + /// Crash-recovery autosave (Preferences › File Handling) and recovery at launch. + pub autosave: Option, + /// None for services that report synchronous success through `autosave`. + pub autosave_results: Option, + /// Finish every queued crash-recovery autosave and wait for it, with outcomes like + /// `autosave_results`. For a session that ends without asking: the window's graphics device + /// was lost (see `gpu_status::check_window`). + pub flush_autosaves: Option, + pub discard_autosave: Option, + pub recover: Option, + pub adopt_autosave: Option, + /// History Log text file output. + pub append_text: Option, + /// OS requests (macOS open-documents / quit Apple events), polled every frame. + pub os_events: Option, + /// The pointer position read from the OS (desktop) or from the page's drag events (web): + /// file drops carry none, and the window gets no pointer events during an OS drag (see + /// `file_open::DropTarget`). + pub cursor_pos: Option, + /// Caps Lock toggled on (desktop; `None` on Wayland and the web). Read once per frame, so + /// the canvas can show the precise crosshair for painting tools, whatever the preference. + pub caps_lock: Option, + /// Keeps the undecorated window borderless, so the content and the pointer stay aligned + /// (Windows custom title bar, #2246). Called once per frame; `None` when the window is + /// decorated or the platform needs no fixing. + pub window_frame: Option, + /// How the custom title bar's caption buttons look and where they sit (Linux: the desktop's + /// style and button layout). Read every frame, with the context to wake when it changes; + /// `None` keeps Windows' buttons at the right end. + pub caption_style: Option, + /// Physical right mouse button or pen barrel button currently down. + pub right_button_down: Option, + /// The persistent brush preset store, loading in the background (desktop; see + /// `photocraft_engine::preset_store`). Attached to the session once it arrives; without + /// one, brush presets are session-only unless the shell attached a store before startup. + pub preset_store: Option>, + /// Reads the displays and their ICC profiles in the background (desktop macOS; see + /// `monitor_status`). Without one, the canvas uses the profile chosen in Color Settings, or sRGB. + pub read_displays: Option, + /// The macOS menu bar, when the desktop app installed one; the in-window menus are hidden then. + pub native_menu: Option, + /// Ends the app once leaving is settled (nothing unsaved, or the prompt answered), instead of + /// letting eframe close the window. macOS: `-[NSApplication terminate:]`. Closing the window + /// while AppKit's run loop is still going crashes or hangs Touch Bar Macs (#1575, #1458). + /// Without one, eframe closes the window and the app ends with it. + pub quit: Option, +} From 0d1d412305637c911d1cb7315f7c5144db467ec7 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:55:29 +0000 Subject: [PATCH 213/259] refactor(ui-egui): split app.rs into app/ --- crates/ui-egui/src/app.rs | 2324 +------------------------- crates/ui-egui/src/app/clipboard.rs | 82 + crates/ui-egui/src/app/commands.rs | 290 ++++ crates/ui-egui/src/app/control.rs | 39 + crates/ui-egui/src/app/files.rs | 678 ++++++++ crates/ui-egui/src/app/frame.rs | 344 ++++ crates/ui-egui/src/app/gpu.rs | 76 + crates/ui-egui/src/app/ime.rs | 20 + crates/ui-egui/src/app/input.rs | 134 ++ crates/ui-egui/src/app/prefs.rs | 68 + crates/ui-egui/src/app/screenshot.rs | 62 + crates/ui-egui/src/app/targets.rs | 151 ++ crates/ui-egui/src/app/thumbs.rs | 366 ++++ crates/ui-egui/src/app/view.rs | 21 + crates/ui-egui/src/app/window.rs | 11 + 15 files changed, 2365 insertions(+), 2301 deletions(-) create mode 100644 crates/ui-egui/src/app/clipboard.rs create mode 100644 crates/ui-egui/src/app/commands.rs create mode 100644 crates/ui-egui/src/app/control.rs create mode 100644 crates/ui-egui/src/app/files.rs create mode 100644 crates/ui-egui/src/app/frame.rs create mode 100644 crates/ui-egui/src/app/gpu.rs create mode 100644 crates/ui-egui/src/app/ime.rs create mode 100644 crates/ui-egui/src/app/input.rs create mode 100644 crates/ui-egui/src/app/prefs.rs create mode 100644 crates/ui-egui/src/app/screenshot.rs create mode 100644 crates/ui-egui/src/app/targets.rs create mode 100644 crates/ui-egui/src/app/thumbs.rs create mode 100644 crates/ui-egui/src/app/view.rs create mode 100644 crates/ui-egui/src/app/window.rs diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index a5f9760d16..0dd8f9adc0 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -1,6 +1,28 @@ use super::services::{ExportSettings, FormatChoices, SAVE_OPTIONS_OPEN, SaveKind, Services, plain_raster, saved_revision_after_write}; use super::*; +mod clipboard; +mod commands; +mod control; +mod files; +mod frame; +mod gpu; +mod ime; +mod input; +mod prefs; +mod screenshot; +mod targets; +mod thumbs; +mod view; +mod window; + +pub(crate) use files::remember_new_document; +pub(crate) use input::read_dropped; +pub(crate) use targets::adjustment_layer_active; +pub use thumbs::surface_fingerprint; +#[cfg(test)] +pub(crate) use thumbs::layer_thumb_frame; + impl PhotocraftApp { pub fn new(mut session: Session, mut services: Services) -> Self { session.updates.check = services.check_updates.take(); @@ -50,7 +72,7 @@ impl PhotocraftApp { caps_lock: false, opacity_keys: None, control_rx: None, - captures: screenshot::Captures::default(), + captures: crate::screenshot::Captures::default(), type_ime: type_tool::ImeState::default(), input_waiters: Vec::new(), live_adjust: None, @@ -175,1455 +197,6 @@ impl PhotocraftApp { photocraft_engine::automate_cmds::fire_event(&mut app.session, "startApplication"); app } - - /// Draw the document canvas on the GPU (custom WGSL shader) instead of via egui textures. - /// Call from the app creator with `cc.wgpu_render_state`; without it the CPU path is used. - pub fn set_wgpu(&mut self, rs: eframe::egui_wgpu::RenderState) { - // Preferences › Performance › cache tile size (PHOTOCRAFT_GPU_TILE still overrides). - let tile = self.session.prefs().performance.cache_tile_size; - // Escaped driver/setup panics must leave the session and CPU canvas alive. - self.perf.gpu_info.set_adapter(&rs.adapter.get_info()); - // The browser has no adapter list (egui-wgpu only has it natively). - #[cfg(not(target_arch = "wasm32"))] - self.perf.gpu_info.set_available(&rs.available_adapters); - self.gpu_render_state = Some(rs.clone()); - let gpu = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| gpu_canvas::GpuCanvas::with_tile(&rs, Some(tile)))) { - Ok(gpu) => gpu, - Err(payload) => { - let detail = payload - .downcast_ref::() - .cloned() - .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string())) - .unwrap_or_else(|| "GPU canvas initialization failed".into()); - self.perf.gpu_info.canvas = "cpu".into(); - self.perf.gpu_info.fallback = Some(detail.clone()); - gpu_status::queue_fallback_notice(self, detail); - self.watch_window_device(&rs.device); - return; - } - }; - self.perf.gpu_info.canvas = "gpu".into(); - self.window_device = Some((rs.device.clone(), gpu.health().clone())); - self.gpu = Some(gpu); - self.prefs_rt.gpu_style = None; - } - - /// Whether the document canvas currently draws on the GPU (false on the CPU path, and after - /// the device was lost). - pub fn gpu_active(&self) -> bool { - self.gpu.is_some() - } - - /// The GPU canvas's device health flag (tests inject faults through it). - pub fn gpu_health(&self) -> Option { - self.gpu.as_ref().map(|g| g.health().clone()) - } - - /// Watch the device the window draws with when the GPU canvas doesn't (the CPU canvas), so - /// its loss is handled like the GPU canvas's (see `gpu_status::check_window`). - pub fn watch_window_device(&mut self, device: &eframe::wgpu::Device) { - self.window_device = Some((device.clone(), photocraft_gpu::DeviceHealth::watch(device))); - } - - /// Whether the window's graphics device was lost, so the app saves its documents for - /// recovery and closes once they are saved (#3438). - pub fn window_lost(&self) -> bool { - self.window_lost - } - - /// Destroy the window's graphics device, as a driver reset does (`ui.gpu.simulateLoss` - /// with `destroy`, tests). Returns whether there was one. - pub fn destroy_window_device(&mut self) -> bool { - self.window_device.as_ref().map(|(device, _)| device.destroy()).is_some() - } - - /// Run `hook` once the app has rendered its first frames (and a document opened at launch - /// has drawn): the desktop app clears its crash-safe GPU startup marker there. - pub fn on_started(&mut self, hook: impl FnOnce(&mut PhotocraftApp) + 'static) { - self.started = Some(Box::new(hook)); - } - - /// Per-frame GPU health check (called from `logic`; tests call it directly): falls back to - /// the CPU canvas after a device loss and runs the started hook. - pub fn check_gpu(&mut self, ctx: &egui::Context) { - gpu_status::check(self, ctx); - } - - /// Attach a control channel (requests arrive from a transport thread: TCP, stdin, tests). - pub fn with_control(mut self, rx: Receiver) -> Self { - self.control_rx = Some(rx); - self - } - - /// Run an engine command, reporting errors in the status bar. - pub fn run(&mut self, id: &str, params: Value) -> Result { - if let Some(result) = delete_layer_prompt::intercept(self, id, ¶ms) { - return result; - } - if let Some(result) = mask_trash_prompt::intercept(self, id, ¶ms) { - return result; - } - // Automation input also gates every step a command runs on its behalf (`actions.play`). - let gate = if self.automation_input && self.session.authorize.is_none() { self.services.automation_authorize } else { None }; - if gate.is_some() { - self.session.authorize = gate; - } - let result = self.run_command(id, params); - if gate.is_some() { - self.session.authorize = None; - } - // An explicit channel target (⌘2, ⌘\, ⌘3…) decides what the Layers panel targets too: - // ⌘2 after the mask was targeted goes back to the layer's pixels. - if result.is_ok() && id.starts_with("channel.target") { - if let Some(t) = self.session.active().map(|st| st.channel_view.target) { - use photocraft_engine::channel_cmds::ChannelTarget; - self.ui.mask_target = t == ChannelTarget::LayerMask; - self.ui.vector_mask_target = t == ChannelTarget::VectorMask; - } - self.sync_mask_targets(); - } - result - } - - pub(crate) fn run_command(&mut self, id: &str, params: Value) -> Result { - if !vector_ui::cancel_stale(self) { - return Err(self.ui.status.clone()); - } - if matches!(id, "paint.setSymmetry" | "paint.symmetryFromPath" | "paint.symmetryDisable") { - self.ui.symmetry_transform = None; - } - let clip_read = std::mem::take(&mut self.clip_read_for_paste); - if self.automation_input - && let Some(authorize) = self.services.automation_command.as_ref() - { - authorize(id, ¶ms)?; - } - // A new layer while Free Transform is open applies the transform first, as Photoshop does - // (#5667): History reads the transform (or Place Embedded), then New Layer. Only for a - // command that can run; a transform refused or still being applied keeps the box open and - // the command doesn't run. - if photocraft_engine::PRECHECKED.contains(&id) && self.ui.transform.is_some() { - // Bad params or a command that can't run leave the box as it is. - self.session.precheck(id, ¶ms).map_err(|e| e.to_string())?; - transform_tool::commit(self); - if transform_tool::committing(self).is_some() { - return Err(tl!("Free Transform is still being applied; try again when it has finished.").into()); - } - if self.ui.transform.is_some() { - return Err(if self.ui.status.is_empty() { tl!("The transform couldn't be applied.").into() } else { self.ui.status.clone() }); - } - } - actions::suspended_guard(self, id)?; - if let Some(result) = panel_docking::command(self, id, ¶ms) { - return result; - } - if let Some(r) = transform_tool::intercept(self, id) { - return r; - } - if let Some(r) = crate::crop_ui::intercept(self, id) { - return r; - } - let t0 = gpu_canvas::now_ms(); - // The OS clipboard is read only on an explicit paste, never in the background (privacy, CPU). - if matches!(id, "edit.paste" | "edit.pasteSpecial.pasteInPlace" | "file.newFromClipboard") { - if !clip_read { - self.import_os_clipboard()?; - } - if self.session.clipboard.is_none() && self.services.clipboard_get_image.is_some() { - if self.services.clipboard_unreadable.as_ref().is_some_and(|unreadable| unreadable()) { - // The clipboard may well hold an image that can't be reached: say why. - notices::clipboard_unreadable(self); - return Ok(serde_json::json!({"pasted": false})); - } - // Enabled on the strength of the OS clipboard, which held no image: a quiet no-op. - let message = "Nothing to paste: the clipboard holds no image"; - self.ui.status = tl!(message).into(); - self.ui.status_error = false; - return Ok(serde_json::json!({"pasted": false})); - } - } - let suppress_events = self.automation_input && self.session.prefs().script_events.enabled; - if suppress_events { - self.session.edit_prefs(|prefs| prefs.script_events.enabled = false); - } - // Long commands become background jobs when enabled (`jobs_ui`); the rest run inline. - let params = self.with_mask_target(id, params); - let params = vector_ui::with_active_path(self, id, params); - let path_mask = vector_ui::takes_path_mask(id) && params.get("path").is_some_and(|v| !v.is_null()); - let on_active_layer = self - .session - .active() - .is_some_and(|st| st.active_layer.is_some_and(|layer| params.get("layer").and_then(Value::as_u64).is_none_or(|target| target == layer.0))); - let creates_active_mask = - matches!(id, "layer.layerMask.revealAll" | "layer.layerMask.hideAll" | "layer.layerMask.revealSelection" | "layer.layerMask.hideSelection") - && on_active_layer; - let creates_active_vector_mask = matches!( - id, - "layer.vectorMask.add" | "layer.vectorMask.fromPath" | "layer.vectorMask.revealAll" | "layer.vectorMask.hideAll" | "layer.vectorMask.currentPath" - ) && on_active_layer; - let r = if id == "actions.play" { - actions::play(self, ¶ms) - } else if photocraft_engine::actions_cmds::shell_view_command(id) { - actions::run_view(self, id, params) - } else { - jobs_ui::run(self, id, params) - }; - let creates_adjustment_or_fill = id.starts_with("layer.newAdjustmentLayer.") || id.starts_with("layer.newFillLayer."); - if r.is_ok() && ADDS_LAYER_MASK.contains(&id) { - // Adding an explicit mask targets it, as in Photoshop (#2166). - self.ui.mask_target = true; - self.ui.vector_mask_target = false; - self.ui.properties_layer = None; - } else if r.is_ok() && creates_adjustment_or_fill { - // Panel Options may suppress a fill layer's default mask. Never target a - // nonexistent mask; an active path creates a vector mask instead. - let masks = self - .session - .active() - .and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))) - .map(|layer| (layer.mask.is_some(), layer.vector_mask.is_some())) - .unwrap_or((false, false)); - self.ui.mask_target = masks.0; - self.ui.vector_mask_target = !masks.0 && masks.1; - // Keep Properties on the new layer contents, as on main (#3369). - self.ui.properties_layer = self.session.active().and_then(|st| st.active_layer).map(|l| l.0); - } - if r.is_ok() && creates_adjustment_or_fill { - // Properties comes to the front, shown and expanded, so the new layer's settings can - // be edited at once, as in Photoshop (#4028). The layer is made whatever happens here. - if self.ui.docking.is_some() { - let _ = panel_docking::command(self, "window.panel.activate", &json!({"panel": "properties"})); - } else { - self.ui.dock_tabs.properties = 0; - dock::reveal(self, dock::Group::Properties); - } - } - // Making a new selection reveals its outline after View > Extras was hidden (#5597). - // These interactive selection commands complete inline; a failed command, deselection, - // or painting inside an existing selection must leave the user's view choice alone. - if r.as_ref().is_ok_and(|v| v.get("changed") != Some(&Value::Bool(false)) && v.get("pending") != Some(&Value::Bool(true))) - && matches!( - id, - "select.rect" - | "select.lasso" - | "select.magneticLasso" - | "select.magicWand" - | "select.quick" - | "select.object" - | "select.loadSelection" - | "select.loadLuminosity" - | "path.toSelection" - ) - && self.session.active().is_some_and(|st| st.doc.selection.is_some()) - { - self.ui.view.extras = true; - } - if r.is_ok() && id == "select.toWorkPath" { - // Make Work Path selects the new work path in the Paths panel, as in Photoshop. - self.ui.selected_path = Some("work".into()); - } - if r.is_ok() && path_mask { - // The new layer's vector mask becomes the active path, as in Photoshop: the path it - // was made from is no longer selected, so the next fill layer isn't masked by it too. - self.ui.selected_path = Some("layer".into()); - } - if r.is_ok() && creates_active_mask { - // Adding a mask selects its thumbnail: the next brush or footer Delete targets it. - self.ui.mask_target = true; - self.ui.vector_mask_target = false; - } - if r.is_ok() && creates_active_vector_mask { - // Likewise a new vector mask (#4728): Properties shows its Density and Feather, and a - // mask made from a path becomes the active path. - self.ui.vector_mask_target = true; - self.ui.mask_target = false; - if matches!(id, "layer.vectorMask.currentPath" | "layer.vectorMask.fromPath") { - self.ui.selected_path = Some("layer".into()); - } - } - if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "edit.copyMerged") { - self.clip_external = false; - self.export_os_clipboard(); - } - self.perf.last_command = id.to_string(); - self.perf.command_ms = gpu_canvas::now_ms() - t0; - match &r { - Ok(_) => { - if self.ui.status_error { - self.ui.status.clear(); - self.ui.status_error = false; - } - self.sync_views(); - let removed = self.session.take_samplers_removed(); - if removed > 0 && !self.ui.status_error { - // A canvas-size change (crop, Canvas Size, Image Size, rotation) dropped Color - // Sampler points that fell outside the new canvas (#1046). - self.ui.status = crate::i18n::trn(crate::i18n::current(), removed as u64, "{n} sample point removed", "{n} sample points removed"); - self.ui.status_error = false; - } - } - Err(e) => { - self.ui.status = e.clone(); - self.ui.status_error = true; - } - } - if suppress_events { - self.session.edit_prefs(|prefs| prefs.script_events.enabled = true); - } - r - } - - /// Keep one view per document, in tab order: a view and its windows stay with their document - /// when tabs move (`document.move`) or close. - /// The tool pointer events go to: a held temporary tool when there is one (⌘ is the Move - /// tool, `hold_keys::cmd_moves`), else the selected tool. - pub fn active_tool(&self) -> state::Tool { - self.tool_override.unwrap_or(self.ui.tool) - } - - pub fn sync_views(&mut self) { - type_transform::cancel_stale(self); - crate::cam_transform::cancel_stale(self); - crate::lasso_ui::cancel_stale(self); - // A polygon under construction belongs to the Polygonal Lasso tool, not the next tool. - if self.ui.tool != Tool::PolygonLasso { - self.ui.polygon.clear(); - self.ui.polygon_mode.clear(); - } - // ... and to the document it was started on. - crate::canvas::polygon_cancel_stale(self); - crate::crop_ui::cancel_stale(self); - crate::distort_ui::cancel_stale(self); - crate::perspective_crop_ui::cancel_stale(self); - // A pen path under construction belongs to the document it was started on too. - vector_ui::cancel_stale(self); - let ids: Vec = self.session.documents().iter().map(|d| d.doc.id).collect(); - // Where the document of view `i` is now. Views not tracked yet keep their index. - let now = |i: usize| match self.view_docs.get(i) { - Some(id) => ids.iter().position(|d| d == id), - None => (i < ids.len()).then_some(i), - }; - let mut views: Vec> = ids.iter().map(|_| None).collect(); - for (i, v) in std::mem::take(&mut self.ui.views).into_iter().enumerate() { - if let Some(slot) = now(i).and_then(|to| views.get_mut(to)) { - *slot = Some(v); - } - } - self.ui.views = views.into_iter().map(Option::unwrap_or_default).collect(); - self.ui.windows.retain_mut(|w| now(w.document).map(|d| w.document = d).is_some()); - if !self.session.prefs().workspace.open_documents_as_tabs { - let new_docs: Vec = ids.iter().enumerate().filter(|(_, id)| !self.view_docs.contains(id)).map(|(i, _)| i).collect(); - for &idx in &new_docs { - if !self.ui.windows.iter().any(|w| w.document == idx) { - crate::view_cmds::float_window(self, idx, idx); - } - } - } - self.canvases.retain(|(doc, _), _| ids.contains(doc)); - self.navigator_textures.retain(|doc, _| ids.contains(doc)); - self.view_docs = ids; - self.prune_thumbs(); - self.sync_mask_targets(); - // Channel-view textures outlive a hidden view (cheap re-show), not their document. - if !self.channel_views.is_empty() { - let docs = self.session.documents(); - self.channel_views.retain(|id, _| docs.iter().any(|d| d.doc.id.0 == *id)); - } - // Commands may close and reopen a preserved-ID document before the next repaint. - canvas::retain_gpu_documents(self); - } - - /// Record `path` as the most-recently-opened file (File › Open Recent): de-duplicated, newest - /// first, capped at Preferences › File Handling › Recent File List Contains. The list lives in - /// the preferences (`fileHandling.recentFiles`), so it survives a restart; `ui.recent_files` - /// mirrors it for the menus and the Home screen. - pub fn push_recent(&mut self, path: &str) { - let cap = self.recent_cap(); - let mut r = self.session.prefs().file_handling.recent_files.clone(); - r.retain(|p| p != path); - r.insert(0, path.to_string()); - r.truncate(cap); - self.ui.recent_files = r.clone(); - self.session.prefs.edit(|p| p.file_handling.recent_files = r); - } - - /// Records a picked type family for the font menu's Recent group, capped by - /// Preferences ▸ Type ▸ Recent Fonts (0 keeps no list), most recent first, de-duplicated. - pub fn note_recent_font(&mut self, family: &str) { - let cap = self.session.prefs().type_.recent_fonts.min(50) as usize; - let r = &mut self.ui.recent_fonts; - r.retain(|f| f != family); - if cap == 0 { - r.clear(); - return; - } - r.insert(0, family.to_string()); - r.truncate(cap); - } - - /// Preferences ▸ Type ▸ Recent Fonts: a smaller cap (or 0) applies to the existing list at - /// once, not only after the next pick. - pub fn sync_recent_fonts(&mut self) { - self.ui.recent_fonts.truncate(self.session.prefs().type_.recent_fonts.min(50) as usize); - } - - /// File › Open Recent › Clear Recent File List. - pub fn clear_recent(&mut self) { - self.ui.recent_files.clear(); - self.session.prefs.edit(|p| p.file_handling.recent_files.clear()); - } - - /// Take one file off the recent list (the Home screen's × or Remove from Recent, #2691). The - /// file stays on disk, and opening it again lists it again. - pub fn remove_recent(&mut self, path: &str) { - self.ui.recent_files.retain(|p| p != path); - self.session.prefs.edit(|p| p.file_handling.recent_files.retain(|r| r != path)); - } - - /// How many recent files to remember ("Recent File List Contains", 0–100). - pub fn recent_cap(&self) -> usize { - self.session.prefs().file_handling.recent_file_count.min(100) as usize - } - - /// Mirror the stored recent-file list into the UI state (after loading the preferences, or - /// when the Preferences dialog or an agent changes the list or its length). Cheap enough to - /// run every frame: a slice comparison of at most 100 paths, no allocation unless it changed. - pub fn sync_recent(&mut self) { - let cap = self.recent_cap(); - let stored = &self.session.prefs().file_handling.recent_files; - let want = stored.get(..cap.min(stored.len())).unwrap_or_default(); - if self.ui.recent_files.as_slice() != want { - self.ui.recent_files = want.to_vec(); - } - } - - /// Open a file's bytes as a new document named `name`; returns the import warnings (also - /// shown to the user). Files from disk go through [`open_file`](Self::open_file), which also - /// remembers the path. Brush and gradient files go to the preset libraries instead. - pub fn open_bytes(&mut self, name: &str, bytes: &[u8]) -> Result, String> { - self.open_bytes_from(name, bytes, None) - } - - /// [`Self::open_bytes`] for a file read from `path` (File › Save writes back there; it goes - /// to Open Recent), when known. - pub(crate) fn open_bytes_from(&mut self, name: &str, bytes: &[u8], path: Option<&str>) -> Result, String> { - if let Some(r) = preset_files_ui::open(self, name, bytes) { - return r.map(|()| Vec::new()); - } - let name = &self.open_name(name); - // Decoded on a worker: a tab with progress appears now, the document when it's ready - // (warnings are shown then). - if self.background_jobs { - jobs_ui::start_open(self, name, path.map(str::to_string), jobs_ui::bytes(bytes))?; - return Ok(Vec::new()); - } - let import = self.services.import.as_ref().ok_or("no importer configured")?; - let opts = photocraft_engine::jobs::import_options(self.session.prefs()); - let (mut doc, warnings, damaged) = if photocraft_io::is_psd(bytes) { - // Read PSD damage as structured information in the same decode, not by - // retrying an error or matching the text of a compatibility warning. - let (r, damaged) = photocraft_io::import_for_open(name, bytes, &opts).map_err(|e| e.to_string())?; - (r.document, r.warnings, damaged) - } else { - let (doc, warnings) = import(name, bytes, &opts)?; - (doc, warnings, false) - }; - // Preferences › Raw Defaults › Resolution, as the engine's open applies it. - photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc); - // Edit › Color Settings policies apply on open; Ask When Opening holds the file back - // until its prompt is answered, and later files wait behind it (`open_prompt`). - // Missing fonts are read from the document itself: it may not be open yet (#4559). - let warnings = file_open::with_missing_fonts_of(&doc, warnings); - // A developed raw has no embedded profile to ask about. - let developed = warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)); - let question = self.session.color.open_question(&doc).filter(|_| !developed); - let wants_raw = camera_raw_ui::wants_open_dialog(self, &warnings); - open_prompt::arrive( - self, - open_prompt::Held { - doc, - read_only: photocraft_io::affinity::is_affinity(bytes), - damage_pending: damaged, - name: name.to_string(), - path: path.map(str::to_string), - warnings: warnings.clone(), - bytes: (wants_raw && path.is_none()).then(|| std::sync::Arc::new(bytes.to_vec())), - slot: None, - question, - policy_applied: false, - }, - ); - Ok(warnings) - } - - /// Open bytes supplied by an authenticated automation client without - /// invoking user-configured script-event paths outside the granted root. - /// Returns the import warnings (also shown to the user). Brush and gradient - /// files go to the preset libraries, as for interactive opens. - pub fn open_automation_bytes(&mut self, name: &str, bytes: &[u8]) -> Result, String> { - let events_enabled = self.session.prefs().script_events.enabled; - if events_enabled { - self.session.edit_prefs(|prefs| prefs.script_events.enabled = false); - } - let result = match preset_files_ui::open(self, name, bytes) { - Some(r) => r.map(|()| Vec::new()), - None => self.import_automation_document(name, bytes), - }; - if events_enabled { - self.session.edit_prefs(|prefs| prefs.script_events.enabled = true); - } - result - } - - /// The document half of [`open_automation_bytes`](Self::open_automation_bytes): no script - /// events and no Color Settings policy (which may read user-configured profile paths). - fn import_automation_document(&mut self, name: &str, bytes: &[u8]) -> Result, String> { - let import = self.services.import.as_ref().ok_or("no importer configured")?; - let opts = photocraft_engine::jobs::import_options(self.session.prefs()); - let (mut doc, warnings) = import(name, bytes, &opts)?; - photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc); - // The caller records the path it read from. - self.session.add_document(doc, None); - if let Some(st) = self.session.active_mut() { - st.source_read_only = photocraft_io::affinity::is_affinity(bytes); - } - self.sync_views(); - self.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]); - self.ui.status_error = false; - notices::io_warnings(self, &crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]), &warnings); - Ok(warnings) - } - - /// Save the active document to `path`, or to a path chosen in the save dialog (which - /// continues on a later frame, see `file_dialog`). Returns `{"path", "warnings"}` (the export - /// warnings are also shown to the user). - pub fn save_as(&mut self, path: Option) -> Result { - self.save_as_with(path, FormatChoices::default()) - } - - /// [`Self::save_as`] with the format choices already made, which skip their prompts: - /// `file.save` and `file.saveAs` with `tgaBits` (no Targa Options), `ddsCompression` or - /// `ddsMipmaps` (no DDS Options), or `quality` or `jpegFormat` (no JPEG Options). - pub fn save_as_with(&mut self, path: Option, choices: FormatChoices) -> Result { - self.save_dialog_flow(path, choices, false) - } - - /// [`Self::save_as_with`]. `plain_save` marks File › Save that had to ask for a file name - /// (a flat file): confirming the document's own file is recorded as a `file.save` step, - /// which writes whichever file the action is played on, not as a Save As to a fixed path. - pub(crate) fn save_dialog_flow(&mut self, path: Option, choices: FormatChoices, plain_save: bool) -> Result { - if self.save_options_open() { - return Err(SAVE_OPTIONS_OPEN.into()); - } - // Edit Contents documents save back into their smart object. - if path.is_none() && self.session.is_enabled("layer.smartObjects.saveContents") { - self.run("layer.smartObjects.saveContents", serde_json::json!({}))?; - return Ok(serde_json::json!({"path": "smart object", "warnings": []})); - } - if let Some(path) = path { - return self.save_to(path, choices); - } - let st = self.session.active().ok_or("no document")?; - // PDN imports default to our native format, which preserves Paint.NET's blend modes; - // Krita imports to OpenRaster, which Krita opens with its layers. - // Other files keep their format only when it can retain their layers. A plain raster - // (including an unlocked transparent PNG) can keep its flat format; editable contents, - // masks and layer appearance settings need a layered format even with just one layer. - let flat = plain_raster(&st.doc).is_some(); - let ext = st.path.as_deref().and_then(|p| std::path::Path::new(p).extension()).map(|e| e.to_string_lossy().to_ascii_lowercase()); - // An OpenRaster file only when it holds the whole document (#3806): else PSD is offered. - let holds_ora = st.path.as_deref().is_some_and(|p| photocraft_engine::file_cmds::holds_at(&st.doc, p)); - let writable = ext.is_some_and(|e| { - matches!(e.as_str(), photocraft_format::EXTENSION | "psd" | "psb" | "tif" | "tiff") - || (e == "ora" && holds_ora) - || (flat && photocraft_codecs::from_extension(&e).is_some_and(|f| f.caps().write)) - }); - let suggested = match &st.path { - Some(p) if writable => p.clone(), - p => { - let source = p.as_deref().unwrap_or(&st.doc.name); - let ext = match photocraft_engine::file_cmds::extension(source).as_deref() { - Some("pdn") => "pcraft", - Some("kra" | "krz") => "ora", - _ => "psd", - }; - std::path::Path::new(source).with_extension(ext).to_string_lossy().into_owned() - } - }; - let doc = st.doc.id; - self.pick_save(&suggested, move |app, path| { - app.with_document(doc, |app| { - let own = app.session.active().and_then(|st| st.path.clone()); - // Confirming the document's own file: ask first if another app changed it (#6596). - if plain_save - && own.as_deref() == Some(path.as_str()) - && let Some(r) = crate::disk_change_prompt::intercept(app, doc, &path, true, choices) - { - return r; - } - let r = app.save_to(path.clone(), choices)?; - if plain_save && own.as_deref() == Some(path.as_str()) { - app.journal_as_plain_save(&path); - } - Ok(r) - }) - }) - } - - /// [`Self::save_as_with`] once the path is known. - pub(crate) fn save_to(&mut self, path: String, choices: FormatChoices) -> Result { - // An RGB Targa asks for its bits per pixel, a DDS texture for its compression, and a JPEG - // for its quality and format, unless the caller chose them; the save continues from the - // prompt (still a copy when it would be one without the prompt), which records the step - // once answered. - if choices.tga_bits.is_none() && targa_options_ui::wants_prompt(self, &path) { - let copy = self.saves_copy(&path, None)?; - targa_options_ui::park(self, path.clone(), copy, "file.saveAs")?; - return Ok(serde_json::json!({"path": path, "warnings": []})); - } - if choices.dds.is_none() && dds_options_ui::wants_prompt(&path) { - let copy = self.saves_copy(&path, None)?; - dds_options_ui::park(self, path.clone(), copy, "file.saveAs")?; - return Ok(serde_json::json!({"path": path, "warnings": []})); - } - if choices.jpeg.is_none() && jpeg_options_ui::wants_prompt(self, &path) { - let copy = self.saves_copy(&path, None)?; - jpeg_options_ui::park(self, path.clone(), copy, "file.saveAs")?; - return Ok(serde_json::json!({"path": path, "warnings": []})); - } - // A layered TIFF asks about its layers first (Preferences › File Handling); the save - // continues from the prompt, which records the step once answered. - if tiff_options_ui::wants_prompt(self, &path) { - tiff_options_ui::park(self, path.clone())?; - return Ok(serde_json::json!({"path": path, "warnings": []})); - } - self.save_as_step(path, None, choices) - } - - /// File › Save back to the document's own file, recorded as a `file.save` step with the - /// Targa, DDS or JPEG answer in `choices` (a replayed or scripted Save of a flat file brings - /// its own). - pub(crate) fn save_in_place(&mut self, path: String, choices: FormatChoices) -> Result { - if self.save_options_open() { - return Err(SAVE_OPTIONS_OPEN.into()); - } - let r = self.write_save(path, None, choices)?; - // JPEG Options are recorded only where they change something - // ([`jpeg_options_ui::plain_save_step`]); the Targa and DDS answers as given. - let mut step = jpeg_options_ui::plain_save_step(choices.jpeg); - FormatChoices { jpeg: None, ..choices }.record(&mut step); - self.session.journal.push(("file.save".into(), step)); - Ok(r) - } - - /// Writes the Save As and journals it as a `file.saveAs` step with its path (and TIFF, - /// Targa, DDS or JPEG answer), so an action being recorded keeps it (#2032). - fn save_as_step(&mut self, path: String, tiff_layers: Option, choices: FormatChoices) -> Result { - let r = self.write_save(path.clone(), tiff_layers, choices)?; - let mut step = serde_json::json!({"path": path}); - if let Some(layers) = tiff_layers { - step["tiffLayers"] = layers.into(); - } - choices.record(&mut step); - self.session.journal.push(("file.saveAs".into(), step)); - Ok(r) - } - - /// Re-label the Save As just journaled for `path` as File › Save (see [`Self::save_dialog_flow`]), - /// keeping its Targa, DDS or JPEG answer so playback writes the file the same way. A save - /// parked behind Targa, DDS or JPEG Options hasn't been journaled yet: it is recorded as - /// File › Save once answered. - pub(crate) fn journal_as_plain_save(&mut self, path: &str) { - let parked = [ - self.targa_options.as_mut().map(|p| (&p.path, &mut p.record)), - self.dds_options.as_mut().map(|p| (&p.path, &mut p.record)), - self.jpeg_options.as_mut().map(|p| (&p.path, &mut p.record)), - ]; - if let Some((_, record)) = parked.into_iter().flatten().find(|(p, record)| p.as_str() == path && **record == "file.saveAs") { - *record = "file.save"; - return; - } - // Only the path goes: a script's format answer stays, so a replay writes the file it is - // played on the same way. Any other answer (TIFF layers) keeps the Save As. - if let Some(last) = self.session.journal.last_mut() - && last.0 == "file.saveAs" - && last.1.get("path").and_then(Value::as_str) == Some(path) - && let Some(step) = last.1.as_object() - && step.keys().all(|k| matches!(k.as_str(), "path" | "tgaBits" | "ddsCompression" | "ddsMipmaps" | "quality" | "jpegFormat")) - { - let mut step = step.clone(); - step.remove("path"); - *last = ("file.save".into(), Value::Object(step)); - } - } - - /// Replays a recorded `file.save` / `file.saveAs` / `file.saveACopy` / `file.export.exportAs` - /// step: no dialog or prompt, and the recorded TIFF, Targa, DDS or JPEG answer (if any) stands - /// in for its prompt. - pub(crate) fn replay_save(&mut self, id: &str, params: &Value) -> Result { - if self.save_options_open() { - return Err(SAVE_OPTIONS_OPEN.into()); - } - if id == "file.save" { - // The file the action is played on: one that holds the whole document, or a flat - // file a recorded Save confirmed in the dialog while the document is still a plain - // raster, so it is never flattened over (#3531, #3806). A flat file's recorded Targa, - // DDS or JPEG answer writes the same way, without asking. - let choices = FormatChoices::from_step(params, id)?; - let st = self.session.active().ok_or("no document")?; - let flat_own = |p: &str| { - !photocraft_engine::file_cmds::saves_in_place(p) - && plain_raster(&st.doc).is_some() - && photocraft_engine::file_cmds::extension(p).is_some_and(|e| photocraft_codecs::from_extension(&e).is_some_and(|f| f.caps().write)) - }; - let path = st.path.clone().filter(|p| photocraft_engine::file_cmds::holds_at(&st.doc, p) || flat_own(p)).ok_or( - "Save writes back only to the document's own PSD, PSB, .pcraft or OpenRaster file (OpenRaster only when it holds everything), or to its own flat file while the document is a single plain layer", - )?; - return self.save_in_place(path, choices); - } - if id == crate::export_dialog::COMMAND { - // Export As has its own settings, its TGA bits included (#7207). - return crate::export_dialog::replay(self, params); - } - let path = params.get("path").and_then(Value::as_str).filter(|p| !p.is_empty()).ok_or("Save As needs a `path`")?; - let choices = FormatChoices::from_step(params, id)?; - if id == "file.saveACopy" { - // A copy: the document keeps its own file and unsaved state, as when recorded (#4373). - let doc = self.session.active().ok_or("no document")?.doc.clone(); - return crate::view_cmds::write_copy(self, &doc, path, choices); - } - self.save_as_step(path.to_string(), params.get("tiffLayers").and_then(Value::as_bool), choices) - } - - /// What a save writes by default under the preferences: File Handling › Image Previews - /// decides whether a PSD/PSB gets its thumbnail, and Maximize PSD and PSB File Compatibility - /// whether it gets its real merged image. Ask When Saving has no dialog here yet, so it saves - /// both, as Photoshop's checkboxes start on. A JPEG or WebP is written the way the active - /// document's file was (its JPEG quality, a WebP lossy at its quality or lossless), as - /// Photoshop's Save and Save As options start there. - pub(crate) fn save_settings(&self) -> ExportSettings { - let file_handling = &self.session.prefs().file_handling; - let previews = file_handling.image_previews != photocraft_engine::prefs::Ask::Never; - let maximize = file_handling.maximize_psd_compatibility != photocraft_engine::prefs::Ask::Never; - let mut settings = ExportSettings { image_previews: previews, psd_maximize_compatibility: maximize, ..ExportSettings::default() }; - if let Some(st) = self.session.active() { - let e = &st.doc.file_encoding; - settings.jpeg_quality = e.jpeg_quality.map(|q| q.clamp(1, 100)); - settings.webp_lossless = e.webp_lossless.unwrap_or(settings.webp_lossless); - settings.webp_quality = e.webp_quality.map(|q| q.min(100)); - settings.document_path = st.path.as_deref().map(std::path::PathBuf::from); - settings.pcraft_cache = Some(st.pcraft_cache.clone()); - } - settings - } - - /// Whether saving the active document to `path` writes a copy. `tiff_layers` is the TIFF - /// Options answer: `Some(false)` discards the layers and saves a copy. - fn saves_copy(&self, path: &str, tiff_layers: Option) -> Result { - // A flat file that can't hold the document (its layers, or the layered file it lives in) - // is written as a copy, as in Photoshop: the document keeps its file, so Save still - // writes the layered original and the edits stay unsaved (#2550). - // An OpenRaster file that can't hold everything (adjustment layers, styles…) is a copy too, - // so the editable document isn't marked saved after losing them (#3806). - let st = self.session.active().ok_or("no document")?; - let tiff = |p: &str| matches!(photocraft_engine::file_cmds::extension(p).as_deref(), Some("tif" | "tiff")); - let holds = photocraft_engine::file_cmds::holds_at(&st.doc, path) || tiff(path); - let lives_layered = st.path.as_deref().is_some_and(|p| photocraft_engine::file_cmds::saves_in_place(p) || tiff(p)); - Ok(tiff_layers == Some(false) || (!holds && (plain_raster(&st.doc).is_none() || lives_layered))) - } - - /// Writes the active document to a known path. `tiff_layers` is the TIFF Options answer: - /// `Some(false)` discards the layers and saves a copy. `choices` are the Targa bits per pixel - /// (`None`: 32 with an alpha channel or transparency, else 24), the DDS options and the JPEG - /// Options. - fn write_save(&mut self, path: String, tiff_layers: Option, choices: FormatChoices) -> Result { - let copy = self.saves_copy(&path, tiff_layers)?; - let settings = choices.apply(ExportSettings { tiff_layers: tiff_layers.unwrap_or(ExportSettings::default().tiff_layers), ..self.save_settings() }); - match self.write_document(path.clone(), &settings, copy)? { - Some((path, warnings)) => Ok(serde_json::json!({"path": path, "warnings": warnings})), - None => Ok(serde_json::json!({"path": path, "warnings": [], "pending": true, "job": self.jobs.last_started.map(|j| j.0)})), - } - } - - /// Encodes the active document with `settings` and writes it to `path`, which becomes the - /// document's path unless saving a copy. A copy leaves the original's path and unsaved - /// changes intact. Returns the path and the export warnings (also shown to the user), or - /// `None` when the save went to a background job (#2017), which finishes it in - /// [`jobs_ui::tick`]. - pub(crate) fn write_document(&mut self, path: String, settings: &ExportSettings, copy: bool) -> Result)>, String> { - if self.background_jobs - && let Some(save) = self.services.save_file.clone() - { - return jobs_ui::start_save(self, path, settings.clone(), copy, save, false); - } - let st = self.session.active().ok_or("no document")?; - let (doc, written, previous) = (st.doc.id, st.revision, st.saved_revision); - let export = self.services.export.as_ref().ok_or("no exporter configured")?; - let (bytes, warnings) = export(&st.doc, &path, settings)?; - let write = self.services.write.as_mut().ok_or("no writer configured")?; - write(&path, &bytes)?; - let revision = saved_revision_after_write(!self.services.write_unconfirmed, written, previous); - self.saved(doc, revision, &path, &warnings, copy); - Ok(Some((path, warnings))) - } - - /// After `saver` was written to `path`, any other open document bound to that file no longer - /// matches it: it loses the file and is marked unsaved, so it can't stay "saved" while its file - /// holds something else, closing it asks first, and its own Save asks for a name instead of - /// writing over the new file (#6597). Paths are compared as files, so another letter case on a - /// case-insensitive volume or a hard link counts. A notice names the documents affected. - pub(crate) fn detach_others_from_file(&mut self, path: &str, saver: DocId) { - let others: Vec<(DocId, String)> = self - .session - .documents() - .iter() - .filter(|st| st.doc.id != saver && st.path.as_deref().is_some_and(|p| photocraft_engine::file_cmds::same_file(p, path))) - .map(|st| (st.doc.id, st.doc.name.clone())) - .collect(); - let mut detached = Vec::new(); - for (id, name) in others { - let done = self.with_document(id, |app| { - let st = app.session.active_mut().ok_or("no document")?; - st.path = None; - // No revision ever equals this, so the document reads as unsaved until saved again. - st.saved_revision = u64::MAX; - Ok(()) - }); - if done.is_ok() { - detached.push(name); - } - } - if detached.is_empty() { - return; - } - let name = file_open::display_name(path); - let title = { - let template = "{name} was saved over from another tab"; - crate::i18n::fmt(tl!(template), &[("name", name.as_str())]) - }; - let lines = detached - .iter() - .map(|doc| { - let template = "\"{doc}\" no longer has a file and is marked unsaved: save it under a new name to keep it"; - crate::i18n::fmt(tl!(template), &[("doc", doc.as_str())]) - }) - .collect(); - notices::post(self, title, lines, false, None); - } - - /// Record a written save of document `doc` as it was at `revision`: its name, path and saved - /// state (unless a copy), the status, script events and the warnings. - pub(crate) fn saved(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool) { - self.saved_inner(doc, revision, path, warnings, copy, SaveKind::User); - } - - /// [`Self::saved`] for automation saves: no user-configured hooks (docs/control-protocol.md). - pub(crate) fn saved_automation(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool) { - self.saved_inner(doc, revision, path, warnings, copy, SaveKind::Automation); - } - - fn saved_inner(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool, kind: SaveKind) { - // Automation: only a layered save becomes the document's file; a flat one is a - // copy, as in the headless server (#2579). - let (hooks, arm) = match kind { - SaveKind::User => (true, true), - SaveKind::Automation => { - let holds = self.session.documents().iter().find(|st| st.doc.id == doc).is_some_and(|st| photocraft_engine::file_cmds::holds_at(&st.doc, path)); - (false, holds) - } - }; - self.ui.status = crate::i18n::fmt(tl!("Saved {name}"), &[("name", path)]); - // The file was written, copy or not: another tab bound to it no longer matches it. - self.detach_others_from_file(path, doc); - if !copy { - // A background save may finish while another document is active (or after its - // document was closed, when there is nothing left to record). - let _ = self.with_document(doc, |app| { - if let Some(st) = app.session.active_mut() - && arm - { - st.saved_to(path.to_string()); - // The job locked the document, but record the revision that was written. - st.saved_revision = revision; - app.remember_stamp(doc, path); - } - // "Save Document" script events and File › Generate › Image Assets. - if hooks - && let Some(i) = app.session.active_index() - && let Some(r) = photocraft_engine::automate_cmds::document_saved(&mut app.session, i) - { - let template = "Saved {path}; image assets: {n} in {dir}"; - app.ui.status = crate::i18n::fmt( - tl!(template), - &[("path", path), ("n", &r["files"].as_array().map_or(0, Vec::len).to_string()), ("dir", r["dir"].as_str().unwrap_or(""))], - ); - } - Ok(()) - }); - // The file the document now lives in goes to the top of Open Recent and the Home - // screen, as opening it does (#4400). Automation saves don't touch the user's list. - if hooks { - self.push_recent(path); - } - } else if self.disk_stamps.get(&doc).is_some_and(|(own, _)| own == path) { - // A copy written over the document's own file is this app's change too. - self.remember_stamp(doc, path); - } - self.ui.status_error = false; - let what = crate::i18n::fmt(tl!("Saved {name}"), &[("name", file_open::display_name(path).as_str())]); - notices::io_warnings(self, &what, warnings); - self.sync_views(); - } - - /// Note how `doc`'s own file at `path` looks now that the document read or wrote it. - pub(crate) fn remember_stamp(&mut self, doc: photocraft_doc::DocId, path: &str) { - match self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)) { - Some(now) => self.disk_stamps.insert(doc, (path.to_string(), now)), - None => self.disk_stamps.remove(&doc), - }; - } - - /// Another app changed `doc`'s own file at `path` since the document was opened from it or - /// last saved to it. A file that is gone, or one never stamped, counts as unchanged. - pub(crate) fn changed_on_disk(&self, doc: photocraft_doc::DocId, path: &str) -> bool { - let Some((own, then)) = self.disk_stamps.get(&doc) else { return false }; - own == path && self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)).is_some_and(|now| now != *then) - } - - /// TIFF, Targa, DDS or JPEG Options is waiting on an answer before a save is written. - pub(crate) fn save_options_open(&self) -> bool { - self.tiff_options.is_some() || self.targa_options.is_some() || self.dds_options.is_some() || self.jpeg_options.is_some() - } - - /// Writes a save that waited on a format prompt (Targa, DDS or JPEG Options) once answered: - /// journals `step` as its command (`file.saveAs` for Save As, `file.saveACopy` for Save a - /// Copy, `file.save` for a plain Save), so an action being recorded keeps it with this answer - /// (#2032, #4373), reports a failure in the status bar, and releases a close prompt waiting on - /// the save. - pub(crate) fn write_answered_save(&mut self, ctx: &egui::Context, doc: DocId, path: String, settings: &ExportSettings, copy: bool, step: (&str, Value)) { - let written = self.with_document(doc, |app| app.write_document(path, settings, copy)); - if written.is_ok() { - self.session.journal.push((step.0.into(), step.1)); - } - match written { - Err(e) => { - self.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]); - self.ui.status_error = true; - } - Ok(Some(_)) if !copy => crate::discard_ui::saved_document(self, ctx, doc), - // A background save releases the close prompt when it finishes (`jobs_ui`). - Ok(_) => {} - } - } - - /// A print worker may still be handing a job to the system queue. - pub(crate) fn printing(&self) -> bool { - self.session.jobs().iter().any(|j| matches!(j.command.as_str(), "file.print" | "file.printOneCopy")) - } - - /// A save is running in the background. - pub(crate) fn saving(&self) -> bool { - !self.jobs.saves.is_empty() - } - - /// Save through the control session's capability-scoped writer. No file - /// picker or ambient writer is reachable from this path. Returns the path - /// written and the export warnings (also shown to the user). - pub fn save_automation(&mut self, path: Option) -> Result { - self.save_automation_with(path, FormatChoices::default()) - } - - /// [`Self::save_automation`] writing with the format `choices` given (a Targa's `None`: 32 - /// with an alpha channel or transparency, else 24; a DDS texture's: uncompressed without - /// mipmaps; a JPEG's: the file's own quality, Baseline). Automation saves never prompt. - pub fn save_automation_with(&mut self, path: Option, choices: FormatChoices) -> Result { - let target = { - let state = self.session.active().ok_or("no document")?; - // As File › Save: without `path` only a layered file is written back (#416). - path.or_else(|| state.path.clone().filter(|p| photocraft_engine::file_cmds::holds_at(&state.doc, p))).ok_or( - "pass `path`: a save without one writes back only to the document's own PSD, PSB, .pcraft or OpenRaster file, and to OpenRaster only when it holds everything (adjustment layers, styles and masks don't fit)", - )? - }; - let reply = |path: &str, warnings: &[String]| json!({"path": path, "warnings": warnings}); - // Only the target is granted: a linked smart object's stored path is document data, so - // PSD export writes that layer as pixels instead of embedding the file. - let settings = ExportSettings { read_linked_files: false, ..choices.apply(self.save_settings()) }; - // #2017: the File › Save worker path, so the encode doesn't block the frame loop. - if self.background_jobs - && let Some(save) = self.services.automation_save.clone() - { - return match jobs_ui::start_save(self, target.clone(), settings, false, save, true)? { - Some((path, warnings)) => Ok(reply(&path, &warnings)), - None => { - let job = self.jobs.last_started; - Ok(json!({"path": target, "job": job, "pending": true, "warnings": []})) - } - }; - } - let state = self.session.active().ok_or("no document")?; - let (doc, revision) = (state.doc.id, state.revision); - let export = self.services.export.as_ref().ok_or("no exporter configured")?; - let (bytes, warnings) = export(&state.doc, &target, &settings)?; - let write = self.services.automation_write.as_mut().ok_or("automation write authority is not configured")?; - write(&target, &bytes)?; - self.saved_automation(doc, revision, &target, &warnings, false); - Ok(reply(&target, &warnings)) - } - - pub(crate) fn drain_control(&mut self, ctx: &egui::Context) { - let Some(rx) = self.control_rx.take() else { return }; - while let Ok(req) = rx.try_recv() { - let reply = req.reply.clone(); - if req.deadline.is_some_and(|deadline| std::time::Instant::now() >= deadline) || !req.dispatch.start() { - let _ = reply.send(serde_json::json!({"ok": false, "error": control::expired_error()})); - continue; - } - match control::handle(self, ctx, &req) { - control::Outcome::Done(v) => { - let _ = reply.send(v); - } - control::Outcome::AfterInput => self.input_waiters.push(reply), - control::Outcome::AfterJob(job) => self.jobs.waiters.push((job, reply)), - control::Outcome::Screenshot { token, path } => { - // Admission is budgeted here, after this pass's completed captures were - // drained, so a just-finished request never causes a false rejection. - let settle = screenshot::settle_ms(ctx.global_style().animation_time); - let document = self.document_identity(); - if let Err((reply, e)) = self.captures.admit(token, path, reply, document, settle, screenshot::now()) { - let _ = reply.send(serde_json::json!({"ok": false, "error": e})); - } - } - } - // `ui.set` may have changed the edit target: the next request sees its colours. - self.sync_mask_targets(); - } - self.control_rx = Some(rx); - } - - /// The active document's identity at admission: a queued capture never applies to another - /// document. Includes the revision so a saved image is attributable to a known state. - pub(crate) fn document_identity(&self) -> Option { - self.session.active().map(|st| screenshot::DocumentId { document: st.doc.id.0, revision: st.revision, generation: self.session.active_generation() }) - } - - /// Issue due screenshot requests. UI phase only: settling counts real layout passes, and the - /// geometry epoch is that of the pass the image will be rendered from. - fn issue_captures(&mut self, ctx: &egui::Context) { - // A discarded pass (popup sizing, `request_discard`) will be re-run: capture only a pass - // whose UI state will actually be present. - if ctx.will_discard() { - return; - } - let now = screenshot::now(); - let doc = self.document_identity(); - let finished = self.captures.issue(ctx, now, doc, |callback| screenshot::send_command(ctx, callback)); - self.finish_captures(finished); - } - - /// Collect callbacks and expire requests. Logic phase; the image is encoded and written here, - /// on the UI thread, never inside the callback. - fn drain_captures(&mut self, ctx: &egui::Context) { - let now = screenshot::now(); - let doc = self.document_identity(); - // begin_pass supplies the new RawInput before App::logic; run_logic refreshes native - // viewport metadata too. Observe it before any completed callback can be delivered. - let current = screenshot::CaptureGeometry::current(ctx, doc); - self.captures.note_geometry(current); - let observed = self.captures.last_geometry(); - let finished = self.captures.drain(now, observed, doc); - self.finish_captures(finished); - } - - fn finish_captures(&mut self, finished: Vec) { - for f in finished { - let reply = match f.result { - Ok(image) => { - let [w, h] = image.size; - // The encoder takes RGBA bytes; its copy is bounded by the same per-image - // reservation as the retained image, and the image itself is released first. - match w.checked_mul(h).and_then(|n| n.checked_mul(4)) { - Some(bytes) if bytes <= screenshot::MAX_IMAGE_BYTES => { - let rgba: Vec = image.pixels.iter().flat_map(|c| c.to_array()).collect(); - drop(image); - control::save_screenshot_rgba(self, w, h, &rgba, f.path.as_deref()) - } - _ => serde_json::json!({ - "ok": false, - "error": format!( - "screenshot {} failed: the image exceeds the {} MiB encode budget", - f.token, - screenshot::MAX_IMAGE_BYTES / (1 << 20) - ), - }), - } - } - Err(e) => serde_json::json!({"ok": false, "error": e}), - }; - if let Some(tx) = f.reply { - let _ = tx.send(reply); - } - } - } -} - -impl PhotocraftApp { - /// Wait out the rest of [`Self::min_frame_ms`] since the last frame started. - fn cap_frame_rate(&mut self) { - #[cfg(not(target_arch = "wasm32"))] - if let Some(min) = self.min_frame_ms.filter(|m| m.is_finite() && *m > 0.0) { - let wait = min.min(100.0) - (gpu_canvas::now_ms() - self.last_frame_start_ms); - if wait > 0.0 { - std::thread::sleep(std::time::Duration::from_secs_f64(wait / 1000.0)); - } - } - self.last_frame_start_ms = gpu_canvas::now_ms(); - } -} - -impl PhotocraftApp { - /// Install the callback-mode markers in an app creator, before the first `run_ui` on this - /// Context (and again through [`Self::setup_context`] when a host replaces its Context). - /// Installing while a pass is already running cannot mark that pass; it only arms the next. - pub fn install_type_reset_hooks(ctx: &egui::Context) { - type_tool::install_reset_hooks(ctx); - } - - /// The host's UI tail, after all panels and any shell-side model/focus mutations. - pub fn finish_type_reset_pass(&mut self, ctx: &egui::Context) { - type_tool::finish_reset_pass(self, ctx); - } - - /// The host's logic tail; full UI passes leave availability to their later UI tail. - pub fn finish_type_reset_logic(&mut self, ctx: &egui::Context) { - type_tool::finish_reset_logic(self, ctx); - } - - /// Shared logic body. A wrapping host owns the final reset tail after its own work. - pub fn logic_frame(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { - self.cap_frame_rate(); - i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language)); - // Caps Lock state read from the OS once per frame (see `Services::caps_lock`): the canvas - // cursor block needs it before the frame renders. `None` (Wayland/web) keeps `false`. - self.caps_lock = self.services.caps_lock.as_mut().is_some_and(|f| f()); - tool_cursor::set_wayland(ctx, self.services.is_wayland); - if !self.styled { - Self::setup_context(ctx, self.ui.theme); - self.styled = true; - } else { - self.fonts_ready = true; - } - self.frame += 1; - let now = ctx.input(|i| i.time); - let dt = (now - self.last_frame_time) as f32; - if dt > 0.0 { - self.fps = self.fps * 0.9 + (1.0 / dt).min(240.0) * 0.1; - } - self.last_frame_time = now; - self.sync_views(); - crate::type_font_preview::follow_hover(self, ctx); - self.check_gpu(ctx); - #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] - if self.live_tokens.poll(ctx, self.ui.theme) { - self.checker = None; - } - // Finish or expire outstanding captures first, so a new request admitted in this pass - // sees their released budget. - self.drain_captures(ctx); - self.drain_control(ctx); - native_menu::run(self, ctx); - // Switching tools commits, also between the Type and Type Mask tools. - if self.ui.text_edit.as_ref().is_some_and(|ed| !self.ui.tool.is_type() || ed.mask != self.ui.tool.is_type_mask()) { - type_tool::commit(self); - } - // So does selecting another layer or document by any route (#6483). - type_tool::end_if_left(self); - if self.ui.pen.as_ref().is_some_and(|p| !p.drawn_with(self.ui.tool)) { - vector_ui::pen_commit(self, false); - } - transform_tool::end_if_left(self); - shape_stroke_ui::sync_editor(self, ctx); - prefs_ui::tick(self, ctx); - updates_ui::tick(self, ctx); - monitor_status::poll_frame(self, ctx, frame); - // Control requests and persisted preferences can change the language in this frame. - i18n::sync_context(ctx, &self.session.prefs().interface.language); - type_tool::sync_font_names(ctx, self.session.prefs().type_.show_font_names_in_english); - // A window bigger than its display (1440 × 900 on 1366 × 768) runs under the taskbar: - // maximize it into the work area once (#315). - work_area::fit_window(ctx); - discard_ui::guard_window_close(self, ctx); - // Background jobs: apply finished ones, keep frames coming, Esc cancels (before the - // shortcuts see Esc). - if !screen_picker::tick(self, ctx) { - jobs_ui::tick(self, ctx); - #[cfg(not(target_arch = "wasm32"))] - filter_preview_worker::discard_closed(self); - if type_tool::in_ui_pass(ctx) { - if self.fonts_ready { - shortcuts::handle(self, ctx); - } else { - type_tool::controls_only(self, ctx); - } - } - } - let arrived: Vec<(String, Vec)> = - self.services.inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default(); - for (name, bytes) in arrived { - if let Err(e) = self.open_bytes(&name, &bytes) { - self.open_failed(&name, &e); - } - } - // Web drops onto the canvas, read since the last frame: placed below, one at a time. - let to_place: Vec<(String, Vec)> = - self.services.place_inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default(); - self.drop_places.extend(to_place.into_iter().map(|(name, bytes)| file_open::DropPlace::Bytes(name, bytes))); - // Finder double-click / Open With / Dock drops (macOS open-documents events). - self.drain_os_events(ctx); - // While files are dragged over the window it gets no pointer events: keep frames coming so - // the tab strip can follow the pointer. - if ctx.input(|i| !i.raw.hovered_files.is_empty()) { - ctx.request_repaint(); - } - let dropped = ctx.input(|i| i.raw.dropped_files.clone()); - if !dropped.is_empty() { - let at = self.services.cursor_pos.as_mut().and_then(|f| f(ctx)); - self.open_dropped(ctx, dropped, at); - // Files dragged in from another app's window: PhotoCraft comes to the front and takes - // the keyboard, as Photoshop does, instead of staying behind the source (#5687). - ctx.send_viewport_cmd(egui::ViewportCommand::Focus); - } - self.place_next_dropped(ctx); - // The control transport wakes the UI on arrival (ctx.request_repaint); only poll while a - // screenshot is pending. (Polling every 50 ms here made idle apps render at 20 fps.) - if self.captures.any_pending() { - ctx.request_repaint_after(std::time::Duration::from_millis(16)); - } - // A hidden host runs no UI pass: a queued (or re-queued) capture asks for one. An issued - // capture's own `Screenshot` command forces its paint; asking again would spin a hidden - // window while a slow readback is in flight. Synthetic input queued during hidden ticks - // needs the same wake: its events sit in eframe's preserved input until a UI pass. - if self.captures.any_unissued() || self.synthetic_batch.is_some() || !self.synthetic.is_empty() { - ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden); - } - self.poll_file_dialog(ctx, Some(frame)); - } - - /// Shared UI body. A wrapping host must call `finish_type_reset_pass` after return, - /// including when this body returns early without drawing an editor. - pub fn ui_frame(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { - let ctx = ui.ctx().clone(); - // One control owner even when this callback cannot draw the custom editor. - if !self.fonts_ready - || !self.ui.dialogs.is_empty() - || screen_picker::busy(&ctx) - || self.ui.text_edit.is_none() - || ctx.text_edit_focused() - || ctx.egui_wants_keyboard_input() - { - type_tool::controls_only(self, &ctx); - } - // 0.36 saved panel sizes under `Id::unique(name)`; 0.37 reads parent-scoped keys. Data-only, - // so it runs even before fonts are ready; the old keys stay for a 0.36 rollback. - panels::migrate_panel_state(&ctx); - // A real UI pass, not a hidden `run_logic` tick: record the capture geometry (the - // document identity included) and count one settling pass. `run_logic` leaves these - // input values stale; only this real UI phase counts toward settling. - let geometry = screenshot::CaptureGeometry::current(&ctx, self.document_identity()); - self.captures.note_geometry(geometry); - self.captures.note_pass(); - // A real UI pass consumes the one in-flight synthetic batch (see `inject_synthetic`). - self.begin_synthetic_pass(&ctx); - self.hover_layer = None; - i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language)); - // Fonts registered via set_fonts only take effect next frame; named families would panic now. - if !self.fonts_ready { - // egui consumed this pass's input without PhotoCraft handling it: keep the synthetic - // batch for the next pass instead of losing the step. - self.defer_synthetic_pass(); - ctx.request_repaint(); - self.automation_input = false; - // No editor was drawn this pass: end its IME context rather than keep a stale owner. - type_tool::sync_ime(self, &ctx); - return; - } - let t0 = gpu_canvas::now_ms(); - self.perf.frame_refresh_ms = 0.0; - self.stroke_trace.cpu_prev(frame.info().cpu_usage); - // A text field's right-click menu, before any field is drawn (text_field_menu.rs). - text_field_menu::show(&ctx); - // The wheel goes to a focused value field before the canvas or a panel sees it (#5473). - field_wheel::begin_frame(&ctx); - // Each painting tool keeps its own brush (#218), so switch the active tool's brush in - // before anything this frame reads it (the cursor, the options bar, a stroke). - // Preferences ▸ Type ▸ Recent Fonts: a smaller cap (or 0) trims the existing list at - // once, not only after the next pick. - self.sync_recent_fonts(); - paint_mouse::sync_tool_brush(self); - // A unit typed into a value field (`1in` in a px field) converts at the active document's - // resolution, as in Photoshop. - let ppi = self.session.prefs().units_and_rulers.point_size.per_inch(); - let dpi = self.session.active().map_or(72.0, |d| f64::from(d.doc.resolution_dpi.max(1.0))); - crate::widgets::set_field_resolution(&ctx, dpi, ppi); - // View › Screen Mode › Full Screen Mode: only the image, on black (F or Esc returns). - screen_picker::show(&ctx); - if screen_picker::busy(&ctx) && screen_picker::showing(&ctx) { - egui::Modal::new(egui::Id::unique("screen-color-wait")).show(&ctx, |ui| { - ui.spinner(); - ui.label(tl!("Pick a screen pixel or press Esc to cancel")); - if ui.button(tl!("Cancel")).clicked() { - screen_picker::cancel(&ctx); - } - }); - // This pass handled its input (the modal above ran): deliver the synthetic batch. - self.finish_synthetic_pass(); - self.automation_input = false; - type_tool::sync_ime(self, &ctx); - gpu_status::check_window(self, &ctx); - return; - } - if screen_picker::busy(&ctx) { - ui.disable(); - ui.set_opacity(1.0); - } - // The OS title bar (and the taskbar / Alt-Tab entry) follows the active file; with the - // system title bar this is where the document name lives, as the in-app title is hidden. - panels::sync_window_title(self, &ctx); - let chrome = !self.ui.view.hides_chrome(); - if chrome { - self.ui.panels.full_screen_chrome = false; - } - // In Full Screen Mode, Tab shows the menu bar, options bar, toolbar and dock (#6760). - let tabbed_in = !chrome && self.ui.panels.full_screen_chrome; - if (chrome || tabbed_in) && self.ui.panels.menu_bar { - panels::title_bar(self, ui); - } - if (chrome && self.ui.panels.options_bar) || tabbed_in { - panels::options_bar(self, ui); - } - if chrome && self.ui.panels.status_bar { - panels::status_bar(self, ui); - } - if (chrome && self.ui.panels.toolbar) || tabbed_in { - panels::toolbar(self, ui); - } - // craft-ui's layout holds the canvas as its protected `canvas` panel. - let docking = (chrome && self.ui.panels.dock) || tabbed_in; - 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); - }); - panels::properties_window(self, &ctx); - } - brush_panel::window(self, &ctx); - preset_panels::windows(self, &ctx); - gradient_ui::editor_window(self, &ctx); - type_panels_ui::windows(self, &ctx); - analysis_ui::windows(self, &ctx); - timeline_ui::windows(self, &ctx); - workspace_ui::windows(self, &ctx); - palette::show(self, &ctx); - dialogs::show(self, &ctx); - layers_panel_ui::show_dialog(self, &ctx); - rasterize_prompt::run_pending(self, &ctx); - jobs_ui::dialog(self, &ctx); - discard_ui::show(self, &ctx); - tiff_options_ui::show(self, &ctx); - targa_options_ui::show(self, &ctx); - jpeg_options_ui::show(self, &ctx); - dds_options_ui::show(self, &ctx); - distort_ui::show(self, &ctx); - camera_raw_ui::show(self, &ctx); - wide_angle_ui::show(self, &ctx); - canvas::extra_windows(self, &ctx); - notices::show(self, &ctx); - updates_ui::show(self, &ctx); - gpu_status::show_fallback(self, &ctx); - kys_import::show_offer(self, &ctx); - if self.titlebar_modal_drag(chrome) { - titlebar::modal_drag_overlay(&ctx); - } - if self.custom_titlebar { - titlebar::resize_zones(ui); - } - // A device lost while drawing this frame: switch to the CPU canvas before the next one. - gpu_status::check(self, &ctx); - // The Brush Preset picker's view (its gear's card parts and the footer scale) is - // remembered once the pointer is up. Here, after every panel, rather than in the - // picker's own code: the control channel can set it while the picker is closed. - brush_picker::persist(self, &ctx); - // The tool's brush (settings and tip references) is remembered the same way. Like the - // picker's view, in the frame loop, so the control channel can set it with the panels - // closed; the engine's revision counter keeps an unchanged brush free. - last_brush::persist(self, &ctx); - // Tool options are remembered between launches the same way (#2814). - tool_memory::persist(self, &ctx); - // So are View › Extras, Show and Snap To (#3762). - view_cmds::persist(self, &ctx); - // Remember the 0.37 panel sizes so a later 0.36 rollback's newer old-key values win on - // the next upgrade (see `panels::migrate_panel_state`). - panels::remember_panel_state(&ctx); - self.automation_input = false; - shape_stroke_ui::finish_frame(self, &ctx); - native_menu::sync(self, &ctx); - if screen_picker::busy(&ctx) { - // Block input without a backdrop: the worker may still be capturing the screen. - egui::Modal::new(egui::Id::unique("screen-color-wait")).frame(egui::Frame::NONE).backdrop_color(egui::Color32::TRANSPARENT).show(&ctx, |_| {}); - ctx.set_cursor_icon(egui::CursorIcon::Wait); - } - let ui_ms = gpu_canvas::now_ms() - t0; - // A GPU measurement lands a frame or two after the refresh it belongs to. Refreshes - // carry them out, but the last refresh before the app settles has none following it, so - // drain the timer here too or its number is never reported. Drain it either way: a - // measurement left sitting would surface later against an unrelated refresh. Report it - // only while the canvas is still on the GPU, since a CPU refresh clears `gpu_ms` - // precisely so a GPU number is never shown as that refresh's. - if let Some(gpu) = &self.gpu - && let Some(t) = gpu.take_gpu_timing() - && self.perf.last_refresh.starts_with("gpu") - { - self.perf.record_gpu(t); - } - self.perf.frame(ui_ms); - if self.stroke_trace.enabled() { - self.stroke_trace.canvas(self.perf.frame_refresh_ms); - let info = &self.perf.gpu_info; - self.stroke_trace.end_frame(ui_ms, self.live_stroke.is_some(), || { - let gpu = format!("{} {}", info.backend, info.adapter).trim().to_string(); - if info.present.is_empty() { gpu } else { format!("{gpu}, {}", info.present) } - }); - } - // This pass handled its input: the in-flight synthetic batch is delivered once and the - // next step may be injected on the next frame. - self.finish_synthetic_pass(); - // Synthetic input is injected one press/release step per frame: keep frames coming until - // the queue is empty, then release control replies waiting on it. - // Only a pass that reached the end of the UI and delivered the in-flight batch counts as - // settled input; an early-returning pass keeps the batch (and the waiting replies). - if !self.synthetic.is_empty() || self.synthetic_batch.is_some() { - ctx.request_repaint(); - } else if !self.input_waiters.is_empty() { - for w in self.input_waiters.drain(..) { - let _ = w.send(serde_json::json!({"ok": true, "result": null})); - } - } - // A menu or dialog can start a filter after `jobs_ui::tick` ran in this frame. Keep - // polling it even when the platform would otherwise put the event loop to sleep. - jobs_ui::keep_polling(self, &ctx); - // Menus and buttons in this frame may have asked for a file dialog. - self.poll_file_dialog(&ctx, Some(frame)); - // The Type tool's IME descriptor is the last writer of this pass: every panel and the - // canvas have finished mutating the model, and an absent/focus-moved editor ends here. - type_tool::sync_ime(self, &ctx); - // Issue any due `ui.screenshot` now that this pass's state is settled: a queued request - // that has waited its passes and animation delay captures exactly this frame. - self.issue_captures(&ctx); - // Last, after everything drawn this frame: a lost window device can't draw it (#3438). - gpu_status::check_window(self, &ctx); - } } impl eframe::App for PhotocraftApp { @@ -1687,836 +260,6 @@ impl eframe::App for PhotocraftApp { } } -/// Remove one contiguous run equal to `batch` from `events` (eframe's preserved synthetic -/// input). A no-op when the run is not present. -fn remove_event_run(events: &mut Vec, batch: &[egui::Event]) { - if batch.is_empty() || batch.len() > events.len() { - return; - } - if let Some(pos) = events.windows(batch.len()).position(|w| w == batch) { - events.drain(pos..pos + batch.len()); - } -} - -#[cfg(not(target_arch = "wasm32"))] -pub(crate) fn read_dropped(f: &(dyn egui::DroppedFile + Send + Sync)) -> Result, String> { - f.bytes() -} - -/// The active layer is an adjustment layer. It has no pixels, so painting and filling it edit its -/// mask even when its icon thumbnail, not the mask, is the Layers panel's target, as in -/// Photoshop (#4298). -pub(crate) fn adjustment_layer_active(st: &photocraft_engine::DocState) -> bool { - st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| matches!(l.content, photocraft_doc::LayerContent::Adjustment(_))) -} - -/// On the web, dropped-file bytes arrive asynchronously; the web shell handles drops itself. -#[cfg(target_arch = "wasm32")] -fn read_dropped(_f: &dyn egui::DroppedFile) -> Result, String> { - Err("drag-and-drop on the web is handled by the page; use File → Open".into()) -} - -impl PhotocraftApp { - /// Whether the title bar's free gap gets the drag overlay this frame: the app draws its title - /// strip (`chrome`: not hidden by the screen mode) and a dialog's modal layer covers it. Not - /// only with the custom title bar: on macOS the strip under the traffic lights is the window's - /// title bar too, and an open dialog (Embedded Profile Mismatch…) left it undraggable (#5826). - pub(crate) fn titlebar_modal_drag(&self, chrome: bool) -> bool { - chrome && self.ui.panels.menu_bar && !self.ui.dialogs.is_empty() - } - - /// `params` aimed at the active layer's mask (`"target":"mask"`) when the Layers panel targets - /// it and command `id` edits the target (adjustments, filters, fills) without naming one: - /// ⌘I then inverts the mask, as in Photoshop (#780). A targeted alpha channel or Quick Mask - /// mode wins, as the engine routes those itself. - pub fn with_mask_target(&self, id: &str, params: Value) -> Value { - if !photocraft_engine::channel_cmds::follows_target(id) || params.get("target").is_some() { - return params; - } - // A filter mask is painted, filled and filtered in place; it doesn't float or move, and - // Edit › Transform, Apply Image and the dialog filters act on the smart object. - let target = if self.filter_mask_targeted() && photocraft_engine::channel_cmds::follows_filter_mask(id) { - "filterMask" - } else if self.layer_mask_targeted() { - "mask" - } else { - return params; - }; - match params { - Value::Object(mut m) => { - m.insert("target".into(), Value::from(target)); - Value::Object(m) - } - _ => serde_json::json!({ "target": target }), - } - } - - /// The Layers panel targets the active smart object's filter mask (FILE-215-3), and no alpha - /// channel or Quick Mask takes over. - pub fn filter_mask_targeted(&self) -> bool { - let Some(st) = self.session.active() else { return false }; - let Some(id) = st.active_layer.filter(|id| self.ui.filter_mask_target == Some(id.0)) else { return false }; - let composite = st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::Composite && st.doc.quick_mask.is_none(); - composite && st.doc.layer(id).is_some_and(|l| matches!(&l.content, photocraft_doc::LayerContent::Smart(sm) if !sm.smart_filters.is_empty())) - } - - /// The active layer's mask is what pixel commands edit: the Layers panel targets it, the layer - /// is an adjustment layer (no pixels of its own), or every colour channel is off and that mask - /// is the picture. An alpha channel or Quick Mask wins, as the engine routes those itself. - pub fn layer_mask_targeted(&self) -> bool { - let Some(st) = self.session.active() else { return false }; - let layer_mask = st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::LayerMask; - let composite = (st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::Composite || layer_mask) && st.doc.quick_mask.is_none(); - let has_mask = st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.mask.is_some()); - if !composite || !has_mask { - return false; - } - if self.ui.mask_target || layer_mask || adjustment_layer_active(st) { - return true; - } - let colors_off = st.channel_view.visible_colors(photocraft_engine::channel_cmds::color_count(&st.doc)) == 0; - let alpha_on = (0..st.doc.channels.len()).any(|i| st.channel_view.alpha_shown(i)); - colors_off && !alpha_on - } - - /// Targeting the pixels, the layer mask or the vector mask ends a shown filter mask (⌥-click - /// on its thumbnail): while it shows, [`Self::sync_mask_targets`] keeps the filter mask - /// targeted, so strokes would keep landing there. - pub(crate) fn end_filter_mask_view(&mut self) { - let Some(v) = self.session.active().and_then(photocraft_engine::mask_view_cmds::current).filter(|v| v.filter) else { return }; - let off = serde_json::json!({"layer": v.layer.0, "mode": "off", "mask": "filter"}); - if let Err(err) = self.session.execute(photocraft_engine::mask_view_cmds::ID, off) { - log::warn!("could not end the filter mask view: {err}"); - } - } - - /// Explicitly targeting a filter mask ends any conflicting mask view; untargeting it ends its - /// own view too. - pub(crate) fn select_filter_mask_target(&mut self, layer: Option) { - if layer.is_none() { - self.end_filter_mask_view(); - } - if layer.is_some() { - if let Some(st) = self.session.active_mut() { - if st.channel_view.layer_mask.is_some_and(|v| !v.filter || Some(v.layer.0) != layer) { - st.channel_view.layer_mask = None; - } - if matches!( - st.channel_view.target, - photocraft_engine::channel_cmds::ChannelTarget::LayerMask | photocraft_engine::channel_cmds::ChannelTarget::VectorMask - ) { - st.channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Composite; - } - } - self.ui.mask_target = false; - self.ui.vector_mask_target = false; - } - self.ui.filter_mask_target = layer; - self.sync_mask_targets(); - } - - /// Viewing a layer mask (#196) targets it; a vector-mask target needs a vector mask on the - /// active layer (a shape layer's path is its content, not a mask). Targeting a mask or the - /// pixels brings back that target's foreground/background pair, as in Photoshop (#2166). - pub(crate) fn sync_mask_targets(&mut self) { - if let Some(st) = self.session.active_mut() { - use photocraft_engine::channel_cmds::ChannelTarget; - let channel = st.channel_view.target; - match photocraft_engine::mask_view_cmds::current(st) { - Some(v) if v.filter => { - self.ui.filter_mask_target = Some(v.layer.0); - self.ui.mask_target = false; - self.ui.vector_mask_target = false; - } - Some(_) => { - self.ui.mask_target = true; - self.ui.vector_mask_target = false; - self.ui.filter_mask_target = None; - } - None if channel == ChannelTarget::LayerMask => { - self.ui.mask_target = true; - self.ui.vector_mask_target = false; - } - None if channel == ChannelTarget::VectorMask => { - self.ui.vector_mask_target = true; - self.ui.mask_target = false; - } - None => {} - } - if self.ui.mask_target || self.ui.vector_mask_target { - self.ui.filter_mask_target = None; - } - if self.ui.vector_mask_target && !mask_thumbs_ui::has_vector_mask(st) { - self.ui.vector_mask_target = false; - } - if self.ui.mask_target && st.active_layer.and_then(|id| st.doc.layer(id)).is_none_or(|l| l.mask.is_none()) { - self.ui.mask_target = false; - } - if !self.ui.mask_target && st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::LayerMask { - st.channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Composite; - } - if !self.ui.mask_target || self.ui.properties_layer != st.active_layer.map(|l| l.0) { - self.ui.properties_layer = None; - } - } - if self.ui.filter_mask_target.is_some() && !self.filter_mask_targeted() { - self.ui.filter_mask_target = None; - } - let mask = self.layer_mask_targeted() || self.filter_mask_targeted(); - self.session.tools.target_mask(mask); - } - - fn prune_thumbs(&mut self) { - let documents = self.session.documents(); - if self.thumb_documents.len() == documents.len() - && self.thumb_documents.iter().zip(documents).all(|((id, snapshot), st)| *id == st.doc.id && snapshot.ptr_eq(&std::sync::Arc::downgrade(&st.doc))) - { - return; - } - // Check snapshots every sync, but walk the layer tree only after it changes. A Weak - // tracks replacement (including undo and preserved-ID reopen) without retaining pixels. - if !self.thumbs.is_empty() { - let mut live = std::collections::HashSet::new(); - let mut pending: Vec<_> = documents.iter().flat_map(|st| &st.doc.layers).collect(); - while let Some(layer) = pending.pop() { - live.insert((layer.id, mask_thumbs_ui::THUMB_LAYER)); - if layer.mask.is_some() { - live.insert((layer.id, mask_thumbs_ui::THUMB_MASK)); - } - if layer.vector_mask.is_some() { - live.insert((layer.id, mask_thumbs_ui::THUMB_VECTOR)); - } - if matches!(&layer.content, photocraft_doc::LayerContent::Smart(sm) if sm.filter_mask.is_some()) { - live.insert((layer.id, mask_thumbs_ui::THUMB_SMART_MASK)); - } - if let Some(children) = layer.children() { - pending.extend(children); - } - } - // Native files can restore IDs: retain the union across all open documents, rather - // than deleting an ID just because one document containing it was closed. - self.thumbs.retain(|key, _| live.contains(key)); - self.thumb_frames.retain(|id, _| live.contains(&(*id, mask_thumbs_ui::THUMB_LAYER))); - } - self.thumb_documents = documents.iter().map(|st| (st.doc.id, std::sync::Arc::downgrade(&st.doc))).collect(); - } - - pub fn set_theme(&mut self, ctx: &egui::Context, kind: theme::ThemeKind) { - if let Err(e) = self.run("prefs.set", serde_json::json!({"path": "interface.theme", "value": kind.id()})) { - self.ui.status = e; - } else { - self.apply_theme(ctx, kind); - } - } - - pub(crate) fn apply_theme(&mut self, ctx: &egui::Context, kind: theme::ThemeKind) { - // Color and Swatches trade indices between Pro and Studio layouts. - if let Some(selected) = dock::Group::Color.tabs(theme::Tokens::for_kind(self.ui.theme).pro).get(self.ui.dock_tabs.color) - && let Some(tab) = dock::Group::Color.tabs(theme::Tokens::for_kind(kind).pro).iter().position(|name| name == selected) - { - self.ui.dock_tabs.color = tab; - } - self.ui.theme = kind; - panel_docking::sync_visibility(self); - theme::apply(ctx, kind); - self.checker = None; - } - - /// Cached 64px thumbnail of a pixel-ish layer, letterboxed in a square, and the document - /// area it frames: the canvas, or with Clip Thumbnails to Layer Bounds the layer's pixels. - pub fn layer_thumb(&mut self, ctx: &egui::Context, doc: &Document, layer: &photocraft_doc::Layer) -> (egui::TextureId, photocraft_geom::Rect) { - let clip = self.session.prefs().interface.clip_thumbnails_to_layer_bounds; - // Key by content, not document revision: COW tiles change pointer only when their pixels - // change, so unrelated edits (e.g. painting another layer) don't rebuild this thumbnail. - let rev = layer.surface().map_or(0, surface_fingerprint) ^ (doc.size.width as u64) << 40 ^ u64::from(clip) << 63; - let key = (layer.id, mask_thumbs_ui::THUMB_LAYER); - if let Some((r, tex)) = self.thumbs.get(&key) - && *r == rev - && let Some(frame) = self.thumb_frames.get(&layer.id) - { - return (tex.id(), *frame); - } - let canvas = doc.bounds(); - let frame = layer_thumb_frame(layer, canvas, clip); - let mut px = [0.0f32; 8]; - let img = thumb_image(frame, 64, |x, y| { - let Some(s) = layer.surface() else { return [0.0; 4] }; - let n = s.channels(); - s.read_pixel(x, y, &mut px[..n]); - photocraft_raster::to_rgba(&s.format(), &px[..n]) - }); - self.thumb_frames.insert(layer.id, frame); - (self.store_thumb(ctx, key, rev, img), frame) - } - - /// The History panel thumbnail of snapshot `snap` of document `doc` (#2966): its composite, - /// centred in a square. Thumbnails of `doc`'s snapshots not in `live` are dropped. - pub fn snapshot_thumb(&mut self, ctx: &egui::Context, doc: DocId, snap: &photocraft_engine::history_cmds::Snapshot, live: &[u64]) -> egui::TextureId { - self.snapshot_thumbs.retain(|(d, id), _| *d != doc || live.contains(id)); - if let Some(tex) = self.snapshot_thumbs.get(&(doc, snap.id)) { - return tex.id(); - } - let comp = photocraft_compose::thumbnail(&snap.doc, 56); - let (w, h) = (comp.width as usize, comp.height as usize); - let side = w.max(h); - let (ox, oy) = ((side - w) / 2, (side - h) / 2); - let mut px = vec![egui::Color32::TRANSPARENT; side * side]; - for (i, &[r, g, b, a]) in comp.pixels.as_chunks::<4>().0.iter().enumerate() { - if let Some(out) = px.get_mut((i / w + oy) * side + i % w + ox) { - *out = egui::Color32::from_rgba_unmultiplied(r, g, b, a); - } - } - let tex = ctx.load_texture(format!("snapshot-{}", snap.id), egui::ColorImage::new([side, side], px), egui::TextureOptions::LINEAR); - let id = tex.id(); - self.snapshot_thumbs.insert((doc, snap.id), tex); - id - } - - /// The cached thumbnail of `mask`, the layer mask of layer `id`. - pub fn mask_thumb(&mut self, ctx: &egui::Context, doc: &Document, id: photocraft_doc::LayerId, mask: &photocraft_doc::LayerMask) -> egui::TextureId { - self.mask_thumb_kind(ctx, doc, id, mask, mask_thumbs_ui::THUMB_MASK) - } - - /// The thumbnail of `mask` under cache `kind`, re-rendered only when the mask's pixels or the document size change; Smart Filter and layer masks are cached apart. - pub(crate) fn mask_thumb_kind( - &mut self, - ctx: &egui::Context, - doc: &Document, - id: photocraft_doc::LayerId, - mask: &photocraft_doc::LayerMask, - kind: u8, - ) -> egui::TextureId { - let rev = surface_fingerprint(&mask.surface) ^ (doc.size.width as u64) << 40 ^ (doc.size.height as u64) << 16; - let key = (id, kind); - if let Some((r, tex)) = self.thumbs.get(&key) - && *r == rev - { - return tex.id(); - } - let mut v = [0.0f32; 1]; - let img = thumb_image(doc.bounds(), 64, |x, y| { - mask.surface.read_pixel(x, y, &mut v); - [v[0], v[0], v[0], 1.0] - }); - self.store_thumb(ctx, key, rev, img) - } - - pub(crate) fn store_thumb(&mut self, ctx: &egui::Context, key: (photocraft_doc::LayerId, u8), rev: u64, img: egui::ColorImage) -> egui::TextureId { - match self.thumbs.get_mut(&key) { - Some((r, tex)) => { - tex.set(img, egui::TextureOptions::LINEAR); - *r = rev; - tex.id() - } - None => { - let tex = ctx.load_texture(format!("thumb-{}-{}", key.0.0, key.1), img, egui::TextureOptions::LINEAR); - let id = tex.id(); - self.thumbs.insert(key, (rev, tex)); - id - } - } - } -} - -/// Cheap identity of a surface's pixels: its default (untouched) pixel, tile coordinates and -/// `Arc` pointers. The default pixel matters: inverting or filling a tile-less mask only changes -/// it (#2117). -pub fn surface_fingerprint(s: &photocraft_raster::Surface) -> u64 { - let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ s.tile_count() as u64; - for &b in s.default_bytes() { - h = (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3); - } - for (c, t) in s.tiles() { - let p = std::sync::Arc::as_ptr(t) as usize as u64; - h = (h ^ p ^ ((c.tx as u64) << 32 | c.ty as u32 as u64)).wrapping_mul(0x100_0000_01b3); - } - h -} - -/// The document area a layer thumbnail frames: the canvas, or with `clip` the layer's pixels on -/// it (the canvas again when it has none there, so an empty layer still shows the page shape). -pub(crate) fn layer_thumb_frame(layer: &photocraft_doc::Layer, canvas: photocraft_geom::Rect, clip: bool) -> photocraft_geom::Rect { - if !clip { - return canvas; - } - let bounds = layer.surface().map_or(photocraft_geom::Rect::EMPTY, photocraft_compose::bounds::content_bounds).intersect(&canvas); - if bounds.is_empty() { canvas } else { bounds } -} - -/// Square thumbnail of the document area `frame`, letterboxed, sampling `f(x, y)` in document -/// space. -fn thumb_image(frame: photocraft_geom::Rect, side: usize, mut f: impl FnMut(i32, i32) -> [f32; 4]) -> egui::ColorImage { - let (w, h) = (frame.width().max(1) as f32, frame.height().max(1) as f32); - let scale = w.max(h) / side as f32; - let (ox, oy) = ((side as f32 - w / scale) / 2.0, (side as f32 - h / scale) / 2.0); - let mut px = vec![egui::Color32::TRANSPARENT; side * side]; - for ty in 0..side { - for tx in 0..side { - let dx = (tx as f32 - ox + 0.5) * scale; - let dy = (ty as f32 - oy + 0.5) * scale; - if dx < 0.0 || dy < 0.0 || dx >= w || dy >= h { - continue; - } - let c = f(frame.x0.saturating_add(dx as i32), frame.y0.saturating_add(dy as i32)); - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - px[ty * side + tx] = egui::Color32::from_rgba_unmultiplied(q(c[0]), q(c[1]), q(c[2]), q(c[3])); - } - } - egui::ColorImage::new([side, side], px) -} - -impl PhotocraftApp { - /// The document/focus identity the in-flight synthetic batch was queued for. - fn synthetic_target(&self, ctx: &egui::Context) -> SyntheticTarget { - SyntheticTarget { document: self.document_identity(), focus: ctx.memory(|m| m.focused()) } - } - - fn synthetic_target_matches(&self, ctx: &egui::Context) -> bool { - self.synthetic_snapshot.is_some_and(|queued| queued.matches(self.synthetic_target(ctx))) - } - - /// Put at most one queued synthetic batch into this pass's input. - /// - /// The batch is appended once and tracked; `begin_pass` consumes it. While it is in flight no - /// further step is drained, so hidden logic ticks cannot accumulate several batches into one - /// pass. A document or focus change observed here is before eframe consumes the events, so the - /// batch is dropped and its waiting control replies fail instead of landing somewhere else. - /// If a pass consumed it but PhotoCraft returned before handling input (fonts not ready), the - /// same batch is appended again on the next hook, exactly once. - pub(crate) fn inject_synthetic(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) { - if self.synthetic_batch.is_some() { - if !self.synthetic_target_matches(ctx) { - // eframe may already carry the batch in its preserved input: withdraw exactly - // those events before the host consumes them, then fail the waiting replies. - if let Some(batch) = self.synthetic_batch.as_ref() { - remove_event_run(&mut raw_input.events, batch); - } - self.cancel_synthetic("the active document or focus changed while the input was queued"); - return; - } - if self.synthetic_reinject { - if let Some(batch) = self.synthetic_batch.clone() { - raw_input.events.extend(batch); - } - self.synthetic_reinject = false; - self.automation_input = true; - } - return; - } - if self.synthetic.is_empty() { - return; - } - let events = self.take_synthetic_step(); - if events.is_empty() { - return; - } - self.synthetic_snapshot = Some(self.synthetic_target(ctx)); - raw_input.events.extend(events.iter().cloned()); - self.synthetic_batch = Some(events); - } - - /// A pass begins with the in-flight batch. The events are already in this pass's input, so a - /// target change detected now cannot withdraw them: deliver them (never half-apply) and keep - /// `automation_input` set so the commands they trigger still go through the automation policy. - /// `inject_synthetic` performs the withdrawable check, before the host consumes the events. - /// Called at the start of `App::ui` only (a hidden `run_logic` tick consumes no input). - pub(crate) fn begin_synthetic_pass(&mut self, ctx: &egui::Context) { - if self.synthetic_batch.is_none() { - return; - } - if !self.synthetic_target_matches(ctx) { - log::warn!("synthetic input: the document or focus changed inside the pass; delivering it as automation input"); - } - self.automation_input = true; - } - - /// One full UI pass handled the in-flight batch: deliver it once and let the next step in. - pub(crate) fn finish_synthetic_pass(&mut self) { - let _ = self.synthetic_batch.take(); - self.synthetic_snapshot = None; - self.synthetic_reinject = false; - } - - /// The pass returned before the input handling (fonts not ready): keep the batch and have the - /// next hook append it again exactly once, because egui already consumed the events. - pub(crate) fn defer_synthetic_pass(&mut self) { - if self.synthetic_batch.is_some() { - self.synthetic_reinject = true; - } - } - - /// Drop the in-flight batch and fail the replies waiting on it. - fn cancel_synthetic(&mut self, reason: &str) { - let pending = self.synthetic_batch.take().is_some() || !self.synthetic.is_empty(); - self.synthetic.clear(); - self.synthetic_snapshot = None; - self.synthetic_reinject = false; - self.automation_input = false; - if pending || !self.input_waiters.is_empty() { - for w in self.input_waiters.drain(..) { - let _ = w.send(serde_json::json!({"ok": false, "error": format!("input cancelled: {reason}")})); - } - } - } - - /// Next step of queued synthetic input (automation): events up to and including the first - /// release, so egui sees press and release in separate frames. Hosts that don't call - /// `raw_input_hook` (offscreen harnesses) feed these to their input themselves. - pub fn take_synthetic_step(&mut self) -> Vec { - let n = self - .synthetic - .iter() - .position(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. } | egui::Event::Key { pressed: false, .. })) - .map_or(self.synthetic.len(), |i| i + 1); - let events: Vec<_> = self.synthetic.drain(..n).collect(); - if !events.is_empty() { - self.automation_input = true; - } - events - } - - /// Install fonts, image loaders and the theme. Call from the app creator (and again for a - /// replacement Context) before the first `run_ui` so the very first frame renders and the - /// Type reset begin/end pass markers exist; otherwise `logic` does it and the first frame is - /// skipped, with the begin-pass marker necessarily starting on the following pass. - pub fn setup_context(ctx: &egui::Context, kind: theme::ThemeKind) { - Self::install_type_reset_hooks(ctx); - ctx.add_plugin(tool_cursor::CursorLifecycle); - ctx.add_plugin(single_line_drag::SingleLineDrag::default()); - theme::install_fonts(ctx); - egui_extras::install_image_loaders(ctx); - theme::apply(ctx, kind); - // Right-click in any text field: its Cut / Copy / Paste menu (text_field_menu.rs). - ctx.add_plugin(text_field_menu::TextFieldMenu); - // egui's own ⌘+ / ⌘- / ⌘0 scale the whole interface; PhotoCraft zooms the canvas instead - // (shortcuts.rs), like Photoshop. - ctx.options_mut(|o| o.zoom_with_keyboard = false); - // ⌘/Ctrl + wheel scrolls sideways, as in Photoshop; only a pinch zooms (wheel_nav.rs). - wheel_nav::configure(ctx); - } -} - -impl PhotocraftApp { - /// Cached `Surface::content_bounds` keyed by an id and the surface's tile identity. - pub fn cached_bounds(&mut self, key: u64, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { - let rev = surface_fingerprint(surface); - if let Some((r, b)) = self.bounds_cache.get(&key) - && *r == rev - { - return *b; - } - let b = surface.content_bounds(); - if self.bounds_cache.len() > 256 { - self.bounds_cache.clear(); - } - self.bounds_cache.insert(key, (rev, b)); - b - } - - /// The box Properties › Transform shows for `layer` (X, Y, W, H): its pixels' bounds, but a - /// soft shape's path and stroke, whose Density and Feather render past them (#5846), as its - /// transform frame does. - pub fn layer_frame_bounds(&mut self, layer: &photocraft_doc::Layer, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { - match &layer.content { - photocraft_doc::LayerContent::Shape(sh) if sh.has_soft_mask() => { - // Cached per rendering, like the pixel bounds: the frame renders strips of the shape. - let (key, rev) = (layer.id.0 | 1 << 63, surface_fingerprint(surface)); - if let Some((r, b)) = self.bounds_cache.get(&key) - && *r == rev - { - return *b; - } - let canvas = self.session.active().map_or_else(|| surface.content_bounds(), |st| st.doc.bounds()); - let b = photocraft_compose::soft_shape_frame(sh, surface.format(), canvas).unwrap_or(photocraft_geom::Rect::EMPTY); - if self.bounds_cache.len() > 256 { - self.bounds_cache.clear(); - } - self.bounds_cache.insert(key, (rev, b)); - b - } - _ => self.cached_bounds(layer.id.0, surface), - } - } -} - -impl PhotocraftApp { - /// Zoom of the active document's main view: screen (device) pixels per document pixel, the - /// user-facing factor (`100%` is `1.0`). - pub fn current_zoom(&self) -> f32 { - self.session.active_index().and_then(|i| self.ui.views.get(i)).map_or(1.0, |v| v.zoom) - } - - /// Screen (device) pixels per egui point of the canvas (`ctx.pixels_per_point`), as of the - /// last canvas frame. `1.0` before the first frame. - pub fn canvas_ppp(&self) -> f32 { - if self.ppp.is_finite() && self.ppp > 0.0 { self.ppp } else { 1.0 } - } - - /// The active view's zoom in egui points per document pixel: the unit every screen-space - /// distance, tolerance and texture-level choice on the canvas is measured in. - pub fn point_zoom(&self) -> f32 { - self.current_zoom() / self.canvas_ppp() - } -} - -impl PhotocraftApp { - /// Channels panel thumbnails of the active document snapshot: the composite, - /// each colour channel (when there is more than one), each alpha channel, then the Quick Mask. - pub fn channel_thumbs(&mut self, ctx: &egui::Context) -> Vec { - let Some(st) = self.session.active() else { - self.channel_thumbs = None; - return Vec::new(); - }; - let (id, doc) = (st.doc.id, st.doc.clone()); - // View-only commands bump revision without changing pixels. Keeping a Weak pins allocation - // identity against address reuse without retaining the document's pixel data. - let snapshot = std::sync::Arc::downgrade(&doc); - let show_color = self.session.prefs().interface.show_channels_in_color; - // A step that changes only the selection (a marquee, Deselect) makes a new snapshot with - // the same pixels: keep the thumbnails, a full composite at 56 px costs ~0.7 s on a - // layered 20 MP document (#4518). - let current = match &mut self.channel_thumbs { - Some((d, old, in_color, _)) if *d == id && *in_color == show_color => { - let same = old.ptr_eq(&snapshot) || old.upgrade().is_some_and(|prev| same_but_selection(&prev, &doc)); - if same { - *old = snapshot.clone(); - } - same - } - _ => false, - }; - if !current { - let comp = photocraft_compose::thumbnail(&doc, 56); - let (w, h) = (comp.width as usize, comp.height as usize); - let side = w.max(h); - let make = |f: &dyn Fn(&[u8]) -> egui::Color32, name: &str| { - let mut px = vec![egui::Color32::TRANSPARENT; side * side]; - let (ox, oy) = ((side - w) / 2, (side - h) / 2); - for y in 0..h { - for x in 0..w { - let o = (y * w + x) * 4; - px[(y + oy) * side + x + ox] = f(&comp.pixels[o..o + 4]); - } - } - (format!("chan-{name}"), egui::ColorImage::new([side, side], px)) - }; - let fmt = doc.pixel_format(); - let colors = fmt.mode.color_channels(); - let mut texs = vec![make(&|p| egui::Color32::from_rgb(p[0], p[1], p[2]), "composite")]; - if colors > 1 { - for k in 0..colors { - let cmyk = fmt.mode == photocraft_doc::ColorMode::Cmyk; - texs.push(make( - &|p| { - let rgba = [p[0], p[1], p[2], 255].map(|v| f32::from(v) / 255.0); - let x = photocraft_raster::from_rgba(&fmt, rgba)[k]; - let g = if cmyk { 1.0 - x } else { x }; - let byte = (g.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - channel_tint(fmt.mode, k, byte, show_color) - }, - &format!("c{k}"), - )); - } - } - // Alpha channels and the Quick Mask, sampled at thumbnail resolution. - let (dw, dh) = (doc.size.width.max(1) as f32, doc.size.height.max(1) as f32); - for (i, ch) in doc.channels.iter().chain(doc.quick_mask.as_ref()).enumerate() { - let mut px = vec![egui::Color32::TRANSPARENT; side * side]; - let (ox, oy) = ((side - w) / 2, (side - h) / 2); - for y in 0..h { - for x in 0..w { - let sx = ((x as f32 + 0.5) * dw / w as f32) as i32; - let sy = ((y as f32 + 0.5) * dh / h as f32) as i32; - let v = ch.surface.sample_channel(sx, sy, 0); - px[(y + oy) * side + x + ox] = egui::Color32::from_gray((v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); - } - } - texs.push((format!("chan-a{i}"), egui::ColorImage::new([side, side], px))); - } - // Update the textures already uploaded rather than allocating new ones. - let mut handles = match self.channel_thumbs.take() { - Some((d, _, _, h)) if d == id => h, - _ => Vec::new(), - }; - handles.truncate(texs.len()); - for (i, (name, image)) in texs.into_iter().enumerate() { - match handles.get_mut(i) { - Some(h) => h.set(image, egui::TextureOptions::LINEAR), - None => handles.push(ctx.load_texture(name, image, egui::TextureOptions::LINEAR)), - } - } - self.channel_thumbs = Some((id, snapshot, show_color, handles)); - } - self.channel_thumbs.as_ref().map(|(_, _, _, t)| t.iter().map(|t| t.id()).collect()).unwrap_or_default() - } -} - -/// Whether `new` differs from `old` at most in its selection, so every composite and channel -/// thumbnail of it is unchanged. Tiles compare by pointer first, so this costs little. -fn same_but_selection(old: &Document, new: &Document) -> bool { - if old.selection == new.selection { - return old == new; - } - let mut o = old.clone(); - o.selection = new.selection.clone(); - o == *new -} - -/// Layer › Layer Mask commands that add a layer mask: Photoshop targets the new mask (#2166). -const ADDS_LAYER_MASK: [&str; 5] = [ - "layer.layerMask.revealAll", - "layer.layerMask.hideAll", - "layer.layerMask.revealSelection", - "layer.layerMask.hideSelection", - "layer.layerMask.fromTransparency", -]; - -/// The New Document dialog's key in the preferences' `dialogs` map. -const NEW_DOCUMENT: &str = "file.new"; - -/// New Document fields its OK remembers (#1810): the size, resolution, mode, depth, background and -/// display units. Not the name, the preset or the clipboard size. -const NEW_DOCUMENT_REMEMBERED: [&str; 8] = ["width", "height", "resolution", "mode", "depth", "background", "__unit", "__resUnit"]; - -/// A remembered value the dialog can show (a corrupt preference is ignored). -fn remembered_new_document_value(key: &str, v: &serde_json::Value) -> bool { - match key { - "width" | "height" => v.as_u64().is_some_and(|n| (1..=300_000).contains(&n)), - "resolution" => v.as_f64().is_some_and(|r| r.is_finite() && r > 0.0 && r <= 30_000.0), - "depth" => v.as_u64().is_some_and(|d| matches!(d, 1 | 8 | 16 | 32)), - _ => v.as_str().is_some_and(|s| !s.is_empty() && s.len() <= 64), - } -} - -/// Remember the New Document fields `f` its OK used, for the next New Document. -pub(crate) fn remember_new_document(app: &mut PhotocraftApp, f: &serde_json::Map) { - let kept: serde_json::Map = - NEW_DOCUMENT_REMEMBERED.iter().filter_map(|k| f.get(*k).filter(|v| remembered_new_document_value(k, v)).map(|v| (k.to_string(), v.clone()))).collect(); - app.session.prefs.edit(|p| p.dialogs.insert(NEW_DOCUMENT.into(), serde_json::Value::Object(kept))); -} - -fn clip_signature(w: u32, h: u32, px: &[u8]) -> u64 { - let mut sig = (w as u64) << 32 | h as u64; - for b in px.iter().step_by(997) { - sig = sig.rotate_left(5) ^ *b as u64; - } - sig -} - -/// A channel thumbnail pixel whose lightness is `byte` (255 = white: full light, no ink). -/// Preferences ▸ Interface ▸ Show Channels in Color tints RGB channels from black to their -/// primary and CMYK channels from white to their ink, as Photoshop does; otherwise grey. -fn channel_tint(mode: photocraft_doc::ColorMode, k: usize, byte: u8, in_color: bool) -> egui::Color32 { - use photocraft_doc::ColorMode::{Cmyk, Rgb}; - if !in_color { - return egui::Color32::from_gray(byte); - } - match (mode, k) { - (Rgb, 0) => egui::Color32::from_rgb(byte, 0, 0), - (Rgb, 1) => egui::Color32::from_rgb(0, byte, 0), - (Rgb, 2) => egui::Color32::from_rgb(0, 0, byte), - (Cmyk, 0) => egui::Color32::from_rgb(byte, 255, 255), - (Cmyk, 1) => egui::Color32::from_rgb(255, byte, 255), - (Cmyk, 2) => egui::Color32::from_rgb(255, 255, byte), - _ => egui::Color32::from_gray(byte), - } -} - -impl PhotocraftApp { - /// Mirror the session clipboard onto the OS clipboard (RGBA8). - fn export_os_clipboard(&mut self) { - self.clip_unmirrored = true; - if !self.session.prefs().general.export_clipboard { - return; - } - let (Some(set), Some(clip)) = (self.services.clipboard_set_image.as_mut(), self.session.clipboard.as_ref()) else { return }; - let b = clip.bounds; - if b.is_empty() { - return; - } - let mut px = vec![[0u8; 4]; b.width() as usize * b.height() as usize]; - clip.surface.read_rgba8_into(b, &mut px); - let bytes: Vec = px.into_iter().flatten().collect(); - if set(b.width(), b.height(), &bytes).is_ok() { - self.os_clip_sig = Some(clip_signature(b.width(), b.height(), &bytes)); - self.clip_unmirrored = false; - } - } - - /// File › New's fields: the defaults, then the settings of the last document made with the - /// dialog (Photoshop starts from them, #1810), then the Clipboard preset (the clipboard image's - /// size, selected) when the clipboard holds an image. Opening the dialog is an explicit - /// request, so the OS clipboard is read here, as for a paste. - pub(crate) fn new_document_fields(&mut self) -> serde_json::Map { - let mut f = crate::state::UiState::new_document_fields(); - if let Some(serde_json::Value::Object(saved)) = self.session.prefs().dialogs.get(NEW_DOCUMENT) { - for k in NEW_DOCUMENT_REMEMBERED { - if let Some(v) = saved.get(k).filter(|v| remembered_new_document_value(k, v)) { - f.insert(k.into(), v.clone()); - } - } - } - if self.import_os_clipboard().is_err() { - return f; - } - if let Some(c) = self.session.clipboard.as_ref().filter(|c| !c.bounds.is_empty()) { - crate::new_doc_ui::set_clipboard(&mut f, c.bounds.width(), c.bounds.height()); - } - f - } - - /// If the OS clipboard holds an image that isn't the one we put there, make it the session - /// clipboard (so ⌘V pastes screenshots and images copied in other apps, like Photoshop). - /// Returns `Ok(true)` when a new external image was imported. Once the OS clipboard no longer holds - /// the image we mirrored or imported (text or a file was copied since), that image is stale: - /// it is dropped rather than pasted. Unexported internal copies survive unavailable or empty - /// system clipboards. - pub(crate) fn import_os_clipboard(&mut self) -> Result { - let Some(get) = self.services.clipboard_get_image.as_mut() else { return Ok(false) }; - // A read failure says nothing about the clipboard contents. Keep our editable copy and - // its signature rather than treating the failure as an empty image. - let image = match get() { - Ok(image) => image, - Err(error) => { - // An unexported copy remains usable without an OS clipboard (for example, in - // a Wayland sandbox). Mirrored/imported copies still require a successful read - // before pasting, because their system contents may have changed. - if self.clip_unmirrored && !self.clip_external && self.session.clipboard.is_some() { - return Ok(false); - } - if self.session.clipboard.is_none() && self.services.clipboard_unreadable.as_ref().is_some_and(|unreadable| unreadable()) { - // Let paste explain the unavailable backend without treating a saved copy as empty. - return Ok(false); - } - self.ui.status = error.clone(); - self.ui.status_error = true; - return Err(error); - } - }; - let image = image.filter(|(w, h, bytes)| *w > 0 && *h > 0 && bytes.len() == *w as usize * *h as usize * 4); - let Some((w, h, bytes)) = image else { - if self.os_clip_sig.take().is_some() && !self.clip_unmirrored { - self.session.clipboard = None; - self.clip_external = false; - self.clip_unmirrored = true; - } - return Ok(false); - }; - let sig = clip_signature(w, h, &bytes); - if self.os_clip_sig == Some(sig) && self.session.clipboard.is_some() { - return Ok(false); - } - let r = photocraft_geom::Rect::new(0, 0, w as i32, h as i32); - let mut surface = photocraft_raster::Surface::from_interleaved(photocraft_color::PixelFormat::RGBA8, r, &bytes); - surface.prune(); - self.session.clipboard = Some(photocraft_engine::edit_cmds::Clip { surface, bounds: r, layers: None, resolution: None, source: None }); - self.os_clip_sig = Some(sig); - self.clip_external = true; - self.clip_unmirrored = false; - Ok(true) - } -} - #[cfg(test)] mod clipboard_tests { use super::*; @@ -2980,24 +723,3 @@ mod clipboard_tests { assert_eq!(pair(&app), (GREEN, BLUE), "deleting the targeted mask goes back to the pixels"); } } - -#[cfg(test)] -mod channel_tint_tests { - use super::channel_tint; - use egui::Color32; - use photocraft_doc::ColorMode::{Cmyk, Grayscale, Rgb}; - - #[test] - fn channels_in_color_tint_rgb_from_black_and_cmyk_inks_from_white() { - assert_eq!(channel_tint(Rgb, 0, 255, true), Color32::from_rgb(255, 0, 0)); - assert_eq!(channel_tint(Rgb, 2, 0, true), Color32::BLACK); - // CMYK: no ink is white, full ink is the ink's colour. - assert_eq!(channel_tint(Cmyk, 0, 255, true), Color32::WHITE); - assert_eq!(channel_tint(Cmyk, 0, 0, true), Color32::from_rgb(0, 255, 255)); - assert_eq!(channel_tint(Cmyk, 1, 0, true), Color32::from_rgb(255, 0, 255)); - assert_eq!(channel_tint(Cmyk, 2, 0, true), Color32::from_rgb(255, 255, 0)); - assert_eq!(channel_tint(Cmyk, 3, 0, true), Color32::BLACK); - assert_eq!(channel_tint(Grayscale, 0, 77, true), Color32::from_gray(77)); - assert_eq!(channel_tint(Rgb, 0, 77, false), Color32::from_gray(77)); - } -} diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs new file mode 100644 index 0000000000..0b268f2b9b --- /dev/null +++ b/crates/ui-egui/src/app/clipboard.rs @@ -0,0 +1,82 @@ +use super::*; + +fn clip_signature(w: u32, h: u32, px: &[u8]) -> u64 { + let mut sig = (w as u64) << 32 | h as u64; + for b in px.iter().step_by(997) { + sig = sig.rotate_left(5) ^ *b as u64; + } + sig +} + +impl PhotocraftApp { + /// Mirror the session clipboard onto the OS clipboard (RGBA8). + pub(super) fn export_os_clipboard(&mut self) { + self.clip_unmirrored = true; + if !self.session.prefs().general.export_clipboard { + return; + } + let (Some(set), Some(clip)) = (self.services.clipboard_set_image.as_mut(), self.session.clipboard.as_ref()) else { return }; + let b = clip.bounds; + if b.is_empty() { + return; + } + let mut px = vec![[0u8; 4]; b.width() as usize * b.height() as usize]; + clip.surface.read_rgba8_into(b, &mut px); + let bytes: Vec = px.into_iter().flatten().collect(); + if set(b.width(), b.height(), &bytes).is_ok() { + self.os_clip_sig = Some(clip_signature(b.width(), b.height(), &bytes)); + self.clip_unmirrored = false; + } + } + + /// If the OS clipboard holds an image that isn't the one we put there, make it the session + /// clipboard (so ⌘V pastes screenshots and images copied in other apps, like Photoshop). + /// Returns `Ok(true)` when a new external image was imported. Once the OS clipboard no longer holds + /// the image we mirrored or imported (text or a file was copied since), that image is stale: + /// it is dropped rather than pasted. Unexported internal copies survive unavailable or empty + /// system clipboards. + pub(crate) fn import_os_clipboard(&mut self) -> Result { + let Some(get) = self.services.clipboard_get_image.as_mut() else { return Ok(false) }; + // A read failure says nothing about the clipboard contents. Keep our editable copy and + // its signature rather than treating the failure as an empty image. + let image = match get() { + Ok(image) => image, + Err(error) => { + // An unexported copy remains usable without an OS clipboard (for example, in + // a Wayland sandbox). Mirrored/imported copies still require a successful read + // before pasting, because their system contents may have changed. + if self.clip_unmirrored && !self.clip_external && self.session.clipboard.is_some() { + return Ok(false); + } + if self.session.clipboard.is_none() && self.services.clipboard_unreadable.as_ref().is_some_and(|unreadable| unreadable()) { + // Let paste explain the unavailable backend without treating a saved copy as empty. + return Ok(false); + } + self.ui.status = error.clone(); + self.ui.status_error = true; + return Err(error); + } + }; + let image = image.filter(|(w, h, bytes)| *w > 0 && *h > 0 && bytes.len() == *w as usize * *h as usize * 4); + let Some((w, h, bytes)) = image else { + if self.os_clip_sig.take().is_some() && !self.clip_unmirrored { + self.session.clipboard = None; + self.clip_external = false; + self.clip_unmirrored = true; + } + return Ok(false); + }; + let sig = clip_signature(w, h, &bytes); + if self.os_clip_sig == Some(sig) && self.session.clipboard.is_some() { + return Ok(false); + } + let r = photocraft_geom::Rect::new(0, 0, w as i32, h as i32); + let mut surface = photocraft_raster::Surface::from_interleaved(photocraft_color::PixelFormat::RGBA8, r, &bytes); + surface.prune(); + self.session.clipboard = Some(photocraft_engine::edit_cmds::Clip { surface, bounds: r, layers: None, resolution: None, source: None }); + self.os_clip_sig = Some(sig); + self.clip_external = true; + self.clip_unmirrored = false; + Ok(true) + } +} diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs new file mode 100644 index 0000000000..1ae200be26 --- /dev/null +++ b/crates/ui-egui/src/app/commands.rs @@ -0,0 +1,290 @@ +use super::*; + +impl PhotocraftApp { + /// Run an engine command, reporting errors in the status bar. + pub fn run(&mut self, id: &str, params: Value) -> Result { + if let Some(result) = delete_layer_prompt::intercept(self, id, ¶ms) { + return result; + } + if let Some(result) = mask_trash_prompt::intercept(self, id, ¶ms) { + return result; + } + // Automation input also gates every step a command runs on its behalf (`actions.play`). + let gate = if self.automation_input && self.session.authorize.is_none() { self.services.automation_authorize } else { None }; + if gate.is_some() { + self.session.authorize = gate; + } + let result = self.run_command(id, params); + if gate.is_some() { + self.session.authorize = None; + } + // An explicit channel target (⌘2, ⌘\, ⌘3…) decides what the Layers panel targets too: + // ⌘2 after the mask was targeted goes back to the layer's pixels. + if result.is_ok() && id.starts_with("channel.target") { + if let Some(t) = self.session.active().map(|st| st.channel_view.target) { + use photocraft_engine::channel_cmds::ChannelTarget; + self.ui.mask_target = t == ChannelTarget::LayerMask; + self.ui.vector_mask_target = t == ChannelTarget::VectorMask; + } + self.sync_mask_targets(); + } + result + } + + pub(crate) fn run_command(&mut self, id: &str, params: Value) -> Result { + if !vector_ui::cancel_stale(self) { + return Err(self.ui.status.clone()); + } + if matches!(id, "paint.setSymmetry" | "paint.symmetryFromPath" | "paint.symmetryDisable") { + self.ui.symmetry_transform = None; + } + let clip_read = std::mem::take(&mut self.clip_read_for_paste); + if self.automation_input + && let Some(authorize) = self.services.automation_command.as_ref() + { + authorize(id, ¶ms)?; + } + // A new layer while Free Transform is open applies the transform first, as Photoshop does + // (#5667): History reads the transform (or Place Embedded), then New Layer. Only for a + // command that can run; a transform refused or still being applied keeps the box open and + // the command doesn't run. + if photocraft_engine::PRECHECKED.contains(&id) && self.ui.transform.is_some() { + // Bad params or a command that can't run leave the box as it is. + self.session.precheck(id, ¶ms).map_err(|e| e.to_string())?; + transform_tool::commit(self); + if transform_tool::committing(self).is_some() { + return Err(tl!("Free Transform is still being applied; try again when it has finished.").into()); + } + if self.ui.transform.is_some() { + return Err(if self.ui.status.is_empty() { tl!("The transform couldn't be applied.").into() } else { self.ui.status.clone() }); + } + } + actions::suspended_guard(self, id)?; + if let Some(result) = panel_docking::command(self, id, ¶ms) { + return result; + } + if let Some(r) = transform_tool::intercept(self, id) { + return r; + } + if let Some(r) = crate::crop_ui::intercept(self, id) { + return r; + } + let t0 = gpu_canvas::now_ms(); + // The OS clipboard is read only on an explicit paste, never in the background (privacy, CPU). + if matches!(id, "edit.paste" | "edit.pasteSpecial.pasteInPlace" | "file.newFromClipboard") { + if !clip_read { + self.import_os_clipboard()?; + } + if self.session.clipboard.is_none() && self.services.clipboard_get_image.is_some() { + if self.services.clipboard_unreadable.as_ref().is_some_and(|unreadable| unreadable()) { + // The clipboard may well hold an image that can't be reached: say why. + notices::clipboard_unreadable(self); + return Ok(serde_json::json!({"pasted": false})); + } + // Enabled on the strength of the OS clipboard, which held no image: a quiet no-op. + let message = "Nothing to paste: the clipboard holds no image"; + self.ui.status = tl!(message).into(); + self.ui.status_error = false; + return Ok(serde_json::json!({"pasted": false})); + } + } + let suppress_events = self.automation_input && self.session.prefs().script_events.enabled; + if suppress_events { + self.session.edit_prefs(|prefs| prefs.script_events.enabled = false); + } + // Long commands become background jobs when enabled (`jobs_ui`); the rest run inline. + let params = self.with_mask_target(id, params); + let params = vector_ui::with_active_path(self, id, params); + let path_mask = vector_ui::takes_path_mask(id) && params.get("path").is_some_and(|v| !v.is_null()); + let on_active_layer = self + .session + .active() + .is_some_and(|st| st.active_layer.is_some_and(|layer| params.get("layer").and_then(Value::as_u64).is_none_or(|target| target == layer.0))); + let creates_active_mask = + matches!(id, "layer.layerMask.revealAll" | "layer.layerMask.hideAll" | "layer.layerMask.revealSelection" | "layer.layerMask.hideSelection") + && on_active_layer; + let creates_active_vector_mask = matches!( + id, + "layer.vectorMask.add" | "layer.vectorMask.fromPath" | "layer.vectorMask.revealAll" | "layer.vectorMask.hideAll" | "layer.vectorMask.currentPath" + ) && on_active_layer; + let r = if id == "actions.play" { + actions::play(self, ¶ms) + } else if photocraft_engine::actions_cmds::shell_view_command(id) { + actions::run_view(self, id, params) + } else { + jobs_ui::run(self, id, params) + }; + let creates_adjustment_or_fill = id.starts_with("layer.newAdjustmentLayer.") || id.starts_with("layer.newFillLayer."); + if r.is_ok() && ADDS_LAYER_MASK.contains(&id) { + // Adding an explicit mask targets it, as in Photoshop (#2166). + self.ui.mask_target = true; + self.ui.vector_mask_target = false; + self.ui.properties_layer = None; + } else if r.is_ok() && creates_adjustment_or_fill { + // Panel Options may suppress a fill layer's default mask. Never target a + // nonexistent mask; an active path creates a vector mask instead. + let masks = self + .session + .active() + .and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))) + .map(|layer| (layer.mask.is_some(), layer.vector_mask.is_some())) + .unwrap_or((false, false)); + self.ui.mask_target = masks.0; + self.ui.vector_mask_target = !masks.0 && masks.1; + // Keep Properties on the new layer contents, as on main (#3369). + self.ui.properties_layer = self.session.active().and_then(|st| st.active_layer).map(|l| l.0); + } + if r.is_ok() && creates_adjustment_or_fill { + // Properties comes to the front, shown and expanded, so the new layer's settings can + // be edited at once, as in Photoshop (#4028). The layer is made whatever happens here. + if self.ui.docking.is_some() { + let _ = panel_docking::command(self, "window.panel.activate", &json!({"panel": "properties"})); + } else { + self.ui.dock_tabs.properties = 0; + dock::reveal(self, dock::Group::Properties); + } + } + // Making a new selection reveals its outline after View > Extras was hidden (#5597). + // These interactive selection commands complete inline; a failed command, deselection, + // or painting inside an existing selection must leave the user's view choice alone. + if r.as_ref().is_ok_and(|v| v.get("changed") != Some(&Value::Bool(false)) && v.get("pending") != Some(&Value::Bool(true))) + && matches!( + id, + "select.rect" + | "select.lasso" + | "select.magneticLasso" + | "select.magicWand" + | "select.quick" + | "select.object" + | "select.loadSelection" + | "select.loadLuminosity" + | "path.toSelection" + ) + && self.session.active().is_some_and(|st| st.doc.selection.is_some()) + { + self.ui.view.extras = true; + } + if r.is_ok() && id == "select.toWorkPath" { + // Make Work Path selects the new work path in the Paths panel, as in Photoshop. + self.ui.selected_path = Some("work".into()); + } + if r.is_ok() && path_mask { + // The new layer's vector mask becomes the active path, as in Photoshop: the path it + // was made from is no longer selected, so the next fill layer isn't masked by it too. + self.ui.selected_path = Some("layer".into()); + } + if r.is_ok() && creates_active_mask { + // Adding a mask selects its thumbnail: the next brush or footer Delete targets it. + self.ui.mask_target = true; + self.ui.vector_mask_target = false; + } + if r.is_ok() && creates_active_vector_mask { + // Likewise a new vector mask (#4728): Properties shows its Density and Feather, and a + // mask made from a path becomes the active path. + self.ui.vector_mask_target = true; + self.ui.mask_target = false; + if matches!(id, "layer.vectorMask.currentPath" | "layer.vectorMask.fromPath") { + self.ui.selected_path = Some("layer".into()); + } + } + if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "edit.copyMerged") { + self.clip_external = false; + self.export_os_clipboard(); + } + self.perf.last_command = id.to_string(); + self.perf.command_ms = gpu_canvas::now_ms() - t0; + match &r { + Ok(_) => { + if self.ui.status_error { + self.ui.status.clear(); + self.ui.status_error = false; + } + self.sync_views(); + let removed = self.session.take_samplers_removed(); + if removed > 0 && !self.ui.status_error { + // A canvas-size change (crop, Canvas Size, Image Size, rotation) dropped Color + // Sampler points that fell outside the new canvas (#1046). + self.ui.status = crate::i18n::trn(crate::i18n::current(), removed as u64, "{n} sample point removed", "{n} sample points removed"); + self.ui.status_error = false; + } + } + Err(e) => { + self.ui.status = e.clone(); + self.ui.status_error = true; + } + } + if suppress_events { + self.session.edit_prefs(|prefs| prefs.script_events.enabled = true); + } + r + } + + /// Keep one view per document, in tab order: a view and its windows stay with their document + /// when tabs move (`document.move`) or close. + /// The tool pointer events go to: a held temporary tool when there is one (⌘ is the Move + /// tool, `hold_keys::cmd_moves`), else the selected tool. + pub fn active_tool(&self) -> state::Tool { + self.tool_override.unwrap_or(self.ui.tool) + } + + pub fn sync_views(&mut self) { + type_transform::cancel_stale(self); + crate::cam_transform::cancel_stale(self); + crate::lasso_ui::cancel_stale(self); + // A polygon under construction belongs to the Polygonal Lasso tool, not the next tool. + if self.ui.tool != Tool::PolygonLasso { + self.ui.polygon.clear(); + self.ui.polygon_mode.clear(); + } + // ... and to the document it was started on. + crate::canvas::polygon_cancel_stale(self); + crate::crop_ui::cancel_stale(self); + crate::distort_ui::cancel_stale(self); + crate::perspective_crop_ui::cancel_stale(self); + // A pen path under construction belongs to the document it was started on too. + vector_ui::cancel_stale(self); + let ids: Vec = self.session.documents().iter().map(|d| d.doc.id).collect(); + // Where the document of view `i` is now. Views not tracked yet keep their index. + let now = |i: usize| match self.view_docs.get(i) { + Some(id) => ids.iter().position(|d| d == id), + None => (i < ids.len()).then_some(i), + }; + let mut views: Vec> = ids.iter().map(|_| None).collect(); + for (i, v) in std::mem::take(&mut self.ui.views).into_iter().enumerate() { + if let Some(slot) = now(i).and_then(|to| views.get_mut(to)) { + *slot = Some(v); + } + } + self.ui.views = views.into_iter().map(Option::unwrap_or_default).collect(); + self.ui.windows.retain_mut(|w| now(w.document).map(|d| w.document = d).is_some()); + if !self.session.prefs().workspace.open_documents_as_tabs { + let new_docs: Vec = ids.iter().enumerate().filter(|(_, id)| !self.view_docs.contains(id)).map(|(i, _)| i).collect(); + for &idx in &new_docs { + if !self.ui.windows.iter().any(|w| w.document == idx) { + crate::view_cmds::float_window(self, idx, idx); + } + } + } + self.canvases.retain(|(doc, _), _| ids.contains(doc)); + self.navigator_textures.retain(|doc, _| ids.contains(doc)); + self.view_docs = ids; + self.prune_thumbs(); + self.sync_mask_targets(); + // Channel-view textures outlive a hidden view (cheap re-show), not their document. + if !self.channel_views.is_empty() { + let docs = self.session.documents(); + self.channel_views.retain(|id, _| docs.iter().any(|d| d.doc.id.0 == *id)); + } + // Commands may close and reopen a preserved-ID document before the next repaint. + canvas::retain_gpu_documents(self); + } +} + +/// Layer › Layer Mask commands that add a layer mask: Photoshop targets the new mask (#2166). +const ADDS_LAYER_MASK: [&str; 5] = [ + "layer.layerMask.revealAll", + "layer.layerMask.hideAll", + "layer.layerMask.revealSelection", + "layer.layerMask.hideSelection", + "layer.layerMask.fromTransparency", +]; diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs new file mode 100644 index 0000000000..e6005b6782 --- /dev/null +++ b/crates/ui-egui/src/app/control.rs @@ -0,0 +1,39 @@ +use super::*; + +impl PhotocraftApp { + /// Attach a control channel (requests arrive from a transport thread: TCP, stdin, tests). + pub fn with_control(mut self, rx: Receiver) -> Self { + self.control_rx = Some(rx); + self + } + + pub(crate) fn drain_control(&mut self, ctx: &egui::Context) { + let Some(rx) = self.control_rx.take() else { return }; + while let Ok(req) = rx.try_recv() { + let reply = req.reply.clone(); + if req.deadline.is_some_and(|deadline| std::time::Instant::now() >= deadline) || !req.dispatch.start() { + let _ = reply.send(serde_json::json!({"ok": false, "error": crate::control::expired_error()})); + continue; + } + match crate::control::handle(self, ctx, &req) { + crate::control::Outcome::Done(v) => { + let _ = reply.send(v); + } + crate::control::Outcome::AfterInput => self.input_waiters.push(reply), + crate::control::Outcome::AfterJob(job) => self.jobs.waiters.push((job, reply)), + crate::control::Outcome::Screenshot { token, path } => { + // Admission is budgeted here, after this pass's completed captures were + // drained, so a just-finished request never causes a false rejection. + let settle = crate::screenshot::settle_ms(ctx.global_style().animation_time); + let document = self.document_identity(); + if let Err((reply, e)) = self.captures.admit(token, path, reply, document, settle, crate::screenshot::now()) { + let _ = reply.send(serde_json::json!({"ok": false, "error": e})); + } + } + } + // `ui.set` may have changed the edit target: the next request sees its colours. + self.sync_mask_targets(); + } + self.control_rx = Some(rx); + } +} diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs new file mode 100644 index 0000000000..ebd30492de --- /dev/null +++ b/crates/ui-egui/src/app/files.rs @@ -0,0 +1,678 @@ +use super::*; + +impl PhotocraftApp { + /// Record `path` as the most-recently-opened file (File › Open Recent): de-duplicated, newest + /// first, capped at Preferences › File Handling › Recent File List Contains. The list lives in + /// the preferences (`fileHandling.recentFiles`), so it survives a restart; `ui.recent_files` + /// mirrors it for the menus and the Home screen. + pub fn push_recent(&mut self, path: &str) { + let cap = self.recent_cap(); + let mut r = self.session.prefs().file_handling.recent_files.clone(); + r.retain(|p| p != path); + r.insert(0, path.to_string()); + r.truncate(cap); + self.ui.recent_files = r.clone(); + self.session.prefs.edit(|p| p.file_handling.recent_files = r); + } + + /// File › Open Recent › Clear Recent File List. + pub fn clear_recent(&mut self) { + self.ui.recent_files.clear(); + self.session.prefs.edit(|p| p.file_handling.recent_files.clear()); + } + + /// Take one file off the recent list (the Home screen's × or Remove from Recent, #2691). The + /// file stays on disk, and opening it again lists it again. + pub fn remove_recent(&mut self, path: &str) { + self.ui.recent_files.retain(|p| p != path); + self.session.prefs.edit(|p| p.file_handling.recent_files.retain(|r| r != path)); + } + + /// How many recent files to remember ("Recent File List Contains", 0–100). + pub fn recent_cap(&self) -> usize { + self.session.prefs().file_handling.recent_file_count.min(100) as usize + } + + /// Mirror the stored recent-file list into the UI state (after loading the preferences, or + /// when the Preferences dialog or an agent changes the list or its length). Cheap enough to + /// run every frame: a slice comparison of at most 100 paths, no allocation unless it changed. + pub fn sync_recent(&mut self) { + let cap = self.recent_cap(); + let stored = &self.session.prefs().file_handling.recent_files; + let want = stored.get(..cap.min(stored.len())).unwrap_or_default(); + if self.ui.recent_files.as_slice() != want { + self.ui.recent_files = want.to_vec(); + } + } + + /// Open a file's bytes as a new document named `name`; returns the import warnings (also + /// shown to the user). Files from disk go through [`open_file`](Self::open_file), which also + /// remembers the path. Brush and gradient files go to the preset libraries instead. + pub fn open_bytes(&mut self, name: &str, bytes: &[u8]) -> Result, String> { + self.open_bytes_from(name, bytes, None) + } + + /// [`Self::open_bytes`] for a file read from `path` (File › Save writes back there; it goes + /// to Open Recent), when known. + pub(crate) fn open_bytes_from(&mut self, name: &str, bytes: &[u8], path: Option<&str>) -> Result, String> { + if let Some(r) = preset_files_ui::open(self, name, bytes) { + return r.map(|()| Vec::new()); + } + let name = &self.open_name(name); + // Decoded on a worker: a tab with progress appears now, the document when it's ready + // (warnings are shown then). + if self.background_jobs { + jobs_ui::start_open(self, name, path.map(str::to_string), jobs_ui::bytes(bytes))?; + return Ok(Vec::new()); + } + let import = self.services.import.as_ref().ok_or("no importer configured")?; + let opts = photocraft_engine::jobs::import_options(self.session.prefs()); + let (mut doc, warnings, damaged) = if photocraft_io::is_psd(bytes) { + // Read PSD damage as structured information in the same decode, not by + // retrying an error or matching the text of a compatibility warning. + let (r, damaged) = photocraft_io::import_for_open(name, bytes, &opts).map_err(|e| e.to_string())?; + (r.document, r.warnings, damaged) + } else { + let (doc, warnings) = import(name, bytes, &opts)?; + (doc, warnings, false) + }; + // Preferences › Raw Defaults › Resolution, as the engine's open applies it. + photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc); + // Edit › Color Settings policies apply on open; Ask When Opening holds the file back + // until its prompt is answered, and later files wait behind it (`open_prompt`). + // Missing fonts are read from the document itself: it may not be open yet (#4559). + let warnings = file_open::with_missing_fonts_of(&doc, warnings); + // A developed raw has no embedded profile to ask about. + let developed = warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)); + let question = self.session.color.open_question(&doc).filter(|_| !developed); + let wants_raw = camera_raw_ui::wants_open_dialog(self, &warnings); + open_prompt::arrive( + self, + open_prompt::Held { + doc, + read_only: photocraft_io::affinity::is_affinity(bytes), + damage_pending: damaged, + name: name.to_string(), + path: path.map(str::to_string), + warnings: warnings.clone(), + bytes: (wants_raw && path.is_none()).then(|| std::sync::Arc::new(bytes.to_vec())), + slot: None, + question, + policy_applied: false, + }, + ); + Ok(warnings) + } + + /// Open bytes supplied by an authenticated automation client without + /// invoking user-configured script-event paths outside the granted root. + /// Returns the import warnings (also shown to the user). Brush and gradient + /// files go to the preset libraries, as for interactive opens. + pub fn open_automation_bytes(&mut self, name: &str, bytes: &[u8]) -> Result, String> { + let events_enabled = self.session.prefs().script_events.enabled; + if events_enabled { + self.session.edit_prefs(|prefs| prefs.script_events.enabled = false); + } + let result = match preset_files_ui::open(self, name, bytes) { + Some(r) => r.map(|()| Vec::new()), + None => self.import_automation_document(name, bytes), + }; + if events_enabled { + self.session.edit_prefs(|prefs| prefs.script_events.enabled = true); + } + result + } + + /// The document half of [`open_automation_bytes`](Self::open_automation_bytes): no script + /// events and no Color Settings policy (which may read user-configured profile paths). + fn import_automation_document(&mut self, name: &str, bytes: &[u8]) -> Result, String> { + let import = self.services.import.as_ref().ok_or("no importer configured")?; + let opts = photocraft_engine::jobs::import_options(self.session.prefs()); + let (mut doc, warnings) = import(name, bytes, &opts)?; + photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc); + // The caller records the path it read from. + self.session.add_document(doc, None); + if let Some(st) = self.session.active_mut() { + st.source_read_only = photocraft_io::affinity::is_affinity(bytes); + } + self.sync_views(); + self.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]); + self.ui.status_error = false; + notices::io_warnings(self, &crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]), &warnings); + Ok(warnings) + } + + /// Save the active document to `path`, or to a path chosen in the save dialog (which + /// continues on a later frame, see `file_dialog`). Returns `{"path", "warnings"}` (the export + /// warnings are also shown to the user). + pub fn save_as(&mut self, path: Option) -> Result { + self.save_as_with(path, FormatChoices::default()) + } + + /// [`Self::save_as`] with the format choices already made, which skip their prompts: + /// `file.save` and `file.saveAs` with `tgaBits` (no Targa Options), `ddsCompression` or + /// `ddsMipmaps` (no DDS Options), or `quality` or `jpegFormat` (no JPEG Options). + pub fn save_as_with(&mut self, path: Option, choices: FormatChoices) -> Result { + self.save_dialog_flow(path, choices, false) + } + + /// [`Self::save_as_with`]. `plain_save` marks File › Save that had to ask for a file name + /// (a flat file): confirming the document's own file is recorded as a `file.save` step, + /// which writes whichever file the action is played on, not as a Save As to a fixed path. + pub(crate) fn save_dialog_flow(&mut self, path: Option, choices: FormatChoices, plain_save: bool) -> Result { + if self.save_options_open() { + return Err(SAVE_OPTIONS_OPEN.into()); + } + // Edit Contents documents save back into their smart object. + if path.is_none() && self.session.is_enabled("layer.smartObjects.saveContents") { + self.run("layer.smartObjects.saveContents", serde_json::json!({}))?; + return Ok(serde_json::json!({"path": "smart object", "warnings": []})); + } + if let Some(path) = path { + return self.save_to(path, choices); + } + let st = self.session.active().ok_or("no document")?; + // PDN imports default to our native format, which preserves Paint.NET's blend modes; + // Krita imports to OpenRaster, which Krita opens with its layers. + // Other files keep their format only when it can retain their layers. A plain raster + // (including an unlocked transparent PNG) can keep its flat format; editable contents, + // masks and layer appearance settings need a layered format even with just one layer. + let flat = plain_raster(&st.doc).is_some(); + let ext = st.path.as_deref().and_then(|p| std::path::Path::new(p).extension()).map(|e| e.to_string_lossy().to_ascii_lowercase()); + // An OpenRaster file only when it holds the whole document (#3806): else PSD is offered. + let holds_ora = st.path.as_deref().is_some_and(|p| photocraft_engine::file_cmds::holds_at(&st.doc, p)); + let writable = ext.is_some_and(|e| { + matches!(e.as_str(), photocraft_format::EXTENSION | "psd" | "psb" | "tif" | "tiff") + || (e == "ora" && holds_ora) + || (flat && photocraft_codecs::from_extension(&e).is_some_and(|f| f.caps().write)) + }); + let suggested = match &st.path { + Some(p) if writable => p.clone(), + p => { + let source = p.as_deref().unwrap_or(&st.doc.name); + let ext = match photocraft_engine::file_cmds::extension(source).as_deref() { + Some("pdn") => "pcraft", + Some("kra" | "krz") => "ora", + _ => "psd", + }; + std::path::Path::new(source).with_extension(ext).to_string_lossy().into_owned() + } + }; + let doc = st.doc.id; + self.pick_save(&suggested, move |app, path| { + app.with_document(doc, |app| { + let own = app.session.active().and_then(|st| st.path.clone()); + // Confirming the document's own file: ask first if another app changed it (#6596). + if plain_save + && own.as_deref() == Some(path.as_str()) + && let Some(r) = crate::disk_change_prompt::intercept(app, doc, &path, true, choices) + { + return r; + } + let r = app.save_to(path.clone(), choices)?; + if plain_save && own.as_deref() == Some(path.as_str()) { + app.journal_as_plain_save(&path); + } + Ok(r) + }) + }) + } + + /// [`Self::save_as_with`] once the path is known. + pub(crate) fn save_to(&mut self, path: String, choices: FormatChoices) -> Result { + // An RGB Targa asks for its bits per pixel, a DDS texture for its compression, and a JPEG + // for its quality and format, unless the caller chose them; the save continues from the + // prompt (still a copy when it would be one without the prompt), which records the step + // once answered. + if choices.tga_bits.is_none() && targa_options_ui::wants_prompt(self, &path) { + let copy = self.saves_copy(&path, None)?; + targa_options_ui::park(self, path.clone(), copy, "file.saveAs")?; + return Ok(serde_json::json!({"path": path, "warnings": []})); + } + if choices.dds.is_none() && dds_options_ui::wants_prompt(&path) { + let copy = self.saves_copy(&path, None)?; + dds_options_ui::park(self, path.clone(), copy, "file.saveAs")?; + return Ok(serde_json::json!({"path": path, "warnings": []})); + } + if choices.jpeg.is_none() && jpeg_options_ui::wants_prompt(self, &path) { + let copy = self.saves_copy(&path, None)?; + jpeg_options_ui::park(self, path.clone(), copy, "file.saveAs")?; + return Ok(serde_json::json!({"path": path, "warnings": []})); + } + // A layered TIFF asks about its layers first (Preferences › File Handling); the save + // continues from the prompt, which records the step once answered. + if tiff_options_ui::wants_prompt(self, &path) { + tiff_options_ui::park(self, path.clone())?; + return Ok(serde_json::json!({"path": path, "warnings": []})); + } + self.save_as_step(path, None, choices) + } + + /// File › Save back to the document's own file, recorded as a `file.save` step with the + /// Targa, DDS or JPEG answer in `choices` (a replayed or scripted Save of a flat file brings + /// its own). + pub(crate) fn save_in_place(&mut self, path: String, choices: FormatChoices) -> Result { + if self.save_options_open() { + return Err(SAVE_OPTIONS_OPEN.into()); + } + let r = self.write_save(path, None, choices)?; + // JPEG Options are recorded only where they change something + // ([`jpeg_options_ui::plain_save_step`]); the Targa and DDS answers as given. + let mut step = jpeg_options_ui::plain_save_step(choices.jpeg); + FormatChoices { jpeg: None, ..choices }.record(&mut step); + self.session.journal.push(("file.save".into(), step)); + Ok(r) + } + + /// Writes the Save As and journals it as a `file.saveAs` step with its path (and TIFF, + /// Targa, DDS or JPEG answer), so an action being recorded keeps it (#2032). + fn save_as_step(&mut self, path: String, tiff_layers: Option, choices: FormatChoices) -> Result { + let r = self.write_save(path.clone(), tiff_layers, choices)?; + let mut step = serde_json::json!({"path": path}); + if let Some(layers) = tiff_layers { + step["tiffLayers"] = layers.into(); + } + choices.record(&mut step); + self.session.journal.push(("file.saveAs".into(), step)); + Ok(r) + } + + /// Re-label the Save As just journaled for `path` as File › Save (see [`Self::save_dialog_flow`]), + /// keeping its Targa, DDS or JPEG answer so playback writes the file the same way. A save + /// parked behind Targa, DDS or JPEG Options hasn't been journaled yet: it is recorded as + /// File › Save once answered. + pub(crate) fn journal_as_plain_save(&mut self, path: &str) { + let parked = [ + self.targa_options.as_mut().map(|p| (&p.path, &mut p.record)), + self.dds_options.as_mut().map(|p| (&p.path, &mut p.record)), + self.jpeg_options.as_mut().map(|p| (&p.path, &mut p.record)), + ]; + if let Some((_, record)) = parked.into_iter().flatten().find(|(p, record)| p.as_str() == path && **record == "file.saveAs") { + *record = "file.save"; + return; + } + // Only the path goes: a script's format answer stays, so a replay writes the file it is + // played on the same way. Any other answer (TIFF layers) keeps the Save As. + if let Some(last) = self.session.journal.last_mut() + && last.0 == "file.saveAs" + && last.1.get("path").and_then(Value::as_str) == Some(path) + && let Some(step) = last.1.as_object() + && step.keys().all(|k| matches!(k.as_str(), "path" | "tgaBits" | "ddsCompression" | "ddsMipmaps" | "quality" | "jpegFormat")) + { + let mut step = step.clone(); + step.remove("path"); + *last = ("file.save".into(), Value::Object(step)); + } + } + + /// Replays a recorded `file.save` / `file.saveAs` / `file.saveACopy` / `file.export.exportAs` + /// step: no dialog or prompt, and the recorded TIFF, Targa, DDS or JPEG answer (if any) stands + /// in for its prompt. + pub(crate) fn replay_save(&mut self, id: &str, params: &Value) -> Result { + if self.save_options_open() { + return Err(SAVE_OPTIONS_OPEN.into()); + } + if id == "file.save" { + // The file the action is played on: one that holds the whole document, or a flat + // file a recorded Save confirmed in the dialog while the document is still a plain + // raster, so it is never flattened over (#3531, #3806). A flat file's recorded Targa, + // DDS or JPEG answer writes the same way, without asking. + let choices = FormatChoices::from_step(params, id)?; + let st = self.session.active().ok_or("no document")?; + let flat_own = |p: &str| { + !photocraft_engine::file_cmds::saves_in_place(p) + && plain_raster(&st.doc).is_some() + && photocraft_engine::file_cmds::extension(p).is_some_and(|e| photocraft_codecs::from_extension(&e).is_some_and(|f| f.caps().write)) + }; + let path = st.path.clone().filter(|p| photocraft_engine::file_cmds::holds_at(&st.doc, p) || flat_own(p)).ok_or( + "Save writes back only to the document's own PSD, PSB, .pcraft or OpenRaster file (OpenRaster only when it holds everything), or to its own flat file while the document is a single plain layer", + )?; + return self.save_in_place(path, choices); + } + if id == crate::export_dialog::COMMAND { + // Export As has its own settings, its TGA bits included (#7207). + return crate::export_dialog::replay(self, params); + } + let path = params.get("path").and_then(Value::as_str).filter(|p| !p.is_empty()).ok_or("Save As needs a `path`")?; + let choices = FormatChoices::from_step(params, id)?; + if id == "file.saveACopy" { + // A copy: the document keeps its own file and unsaved state, as when recorded (#4373). + let doc = self.session.active().ok_or("no document")?.doc.clone(); + return crate::view_cmds::write_copy(self, &doc, path, choices); + } + self.save_as_step(path.to_string(), params.get("tiffLayers").and_then(Value::as_bool), choices) + } + + /// What a save writes by default under the preferences: File Handling › Image Previews + /// decides whether a PSD/PSB gets its thumbnail, and Maximize PSD and PSB File Compatibility + /// whether it gets its real merged image. Ask When Saving has no dialog here yet, so it saves + /// both, as Photoshop's checkboxes start on. A JPEG or WebP is written the way the active + /// document's file was (its JPEG quality, a WebP lossy at its quality or lossless), as + /// Photoshop's Save and Save As options start there. + pub(crate) fn save_settings(&self) -> ExportSettings { + let file_handling = &self.session.prefs().file_handling; + let previews = file_handling.image_previews != photocraft_engine::prefs::Ask::Never; + let maximize = file_handling.maximize_psd_compatibility != photocraft_engine::prefs::Ask::Never; + let mut settings = ExportSettings { image_previews: previews, psd_maximize_compatibility: maximize, ..ExportSettings::default() }; + if let Some(st) = self.session.active() { + let e = &st.doc.file_encoding; + settings.jpeg_quality = e.jpeg_quality.map(|q| q.clamp(1, 100)); + settings.webp_lossless = e.webp_lossless.unwrap_or(settings.webp_lossless); + settings.webp_quality = e.webp_quality.map(|q| q.min(100)); + settings.document_path = st.path.as_deref().map(std::path::PathBuf::from); + settings.pcraft_cache = Some(st.pcraft_cache.clone()); + } + settings + } + + /// Whether saving the active document to `path` writes a copy. `tiff_layers` is the TIFF + /// Options answer: `Some(false)` discards the layers and saves a copy. + fn saves_copy(&self, path: &str, tiff_layers: Option) -> Result { + // A flat file that can't hold the document (its layers, or the layered file it lives in) + // is written as a copy, as in Photoshop: the document keeps its file, so Save still + // writes the layered original and the edits stay unsaved (#2550). + // An OpenRaster file that can't hold everything (adjustment layers, styles…) is a copy too, + // so the editable document isn't marked saved after losing them (#3806). + let st = self.session.active().ok_or("no document")?; + let tiff = |p: &str| matches!(photocraft_engine::file_cmds::extension(p).as_deref(), Some("tif" | "tiff")); + let holds = photocraft_engine::file_cmds::holds_at(&st.doc, path) || tiff(path); + let lives_layered = st.path.as_deref().is_some_and(|p| photocraft_engine::file_cmds::saves_in_place(p) || tiff(p)); + Ok(tiff_layers == Some(false) || (!holds && (plain_raster(&st.doc).is_none() || lives_layered))) + } + + /// Writes the active document to a known path. `tiff_layers` is the TIFF Options answer: + /// `Some(false)` discards the layers and saves a copy. `choices` are the Targa bits per pixel + /// (`None`: 32 with an alpha channel or transparency, else 24), the DDS options and the JPEG + /// Options. + fn write_save(&mut self, path: String, tiff_layers: Option, choices: FormatChoices) -> Result { + let copy = self.saves_copy(&path, tiff_layers)?; + let settings = choices.apply(ExportSettings { tiff_layers: tiff_layers.unwrap_or(ExportSettings::default().tiff_layers), ..self.save_settings() }); + match self.write_document(path.clone(), &settings, copy)? { + Some((path, warnings)) => Ok(serde_json::json!({"path": path, "warnings": warnings})), + None => Ok(serde_json::json!({"path": path, "warnings": [], "pending": true, "job": self.jobs.last_started.map(|j| j.0)})), + } + } + + /// Encodes the active document with `settings` and writes it to `path`, which becomes the + /// document's path unless saving a copy. A copy leaves the original's path and unsaved + /// changes intact. Returns the path and the export warnings (also shown to the user), or + /// `None` when the save went to a background job (#2017), which finishes it in + /// [`jobs_ui::tick`]. + pub(crate) fn write_document(&mut self, path: String, settings: &ExportSettings, copy: bool) -> Result)>, String> { + if self.background_jobs + && let Some(save) = self.services.save_file.clone() + { + return jobs_ui::start_save(self, path, settings.clone(), copy, save, false); + } + let st = self.session.active().ok_or("no document")?; + let (doc, written, previous) = (st.doc.id, st.revision, st.saved_revision); + let export = self.services.export.as_ref().ok_or("no exporter configured")?; + let (bytes, warnings) = export(&st.doc, &path, settings)?; + let write = self.services.write.as_mut().ok_or("no writer configured")?; + write(&path, &bytes)?; + let revision = saved_revision_after_write(!self.services.write_unconfirmed, written, previous); + self.saved(doc, revision, &path, &warnings, copy); + Ok(Some((path, warnings))) + } + + /// After `saver` was written to `path`, any other open document bound to that file no longer + /// matches it: it loses the file and is marked unsaved, so it can't stay "saved" while its file + /// holds something else, closing it asks first, and its own Save asks for a name instead of + /// writing over the new file (#6597). Paths are compared as files, so another letter case on a + /// case-insensitive volume or a hard link counts. A notice names the documents affected. + pub(crate) fn detach_others_from_file(&mut self, path: &str, saver: DocId) { + let others: Vec<(DocId, String)> = self + .session + .documents() + .iter() + .filter(|st| st.doc.id != saver && st.path.as_deref().is_some_and(|p| photocraft_engine::file_cmds::same_file(p, path))) + .map(|st| (st.doc.id, st.doc.name.clone())) + .collect(); + let mut detached = Vec::new(); + for (id, name) in others { + let done = self.with_document(id, |app| { + let st = app.session.active_mut().ok_or("no document")?; + st.path = None; + // No revision ever equals this, so the document reads as unsaved until saved again. + st.saved_revision = u64::MAX; + Ok(()) + }); + if done.is_ok() { + detached.push(name); + } + } + if detached.is_empty() { + return; + } + let name = file_open::display_name(path); + let title = { + let template = "{name} was saved over from another tab"; + crate::i18n::fmt(tl!(template), &[("name", name.as_str())]) + }; + let lines = detached + .iter() + .map(|doc| { + let template = "\"{doc}\" no longer has a file and is marked unsaved: save it under a new name to keep it"; + crate::i18n::fmt(tl!(template), &[("doc", doc.as_str())]) + }) + .collect(); + notices::post(self, title, lines, false, None); + } + + /// Record a written save of document `doc` as it was at `revision`: its name, path and saved + /// state (unless a copy), the status, script events and the warnings. + pub(crate) fn saved(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool) { + self.saved_inner(doc, revision, path, warnings, copy, SaveKind::User); + } + + /// [`Self::saved`] for automation saves: no user-configured hooks (docs/control-protocol.md). + pub(crate) fn saved_automation(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool) { + self.saved_inner(doc, revision, path, warnings, copy, SaveKind::Automation); + } + + fn saved_inner(&mut self, doc: DocId, revision: u64, path: &str, warnings: &[String], copy: bool, kind: SaveKind) { + // Automation: only a layered save becomes the document's file; a flat one is a + // copy, as in the headless server (#2579). + let (hooks, arm) = match kind { + SaveKind::User => (true, true), + SaveKind::Automation => { + let holds = self.session.documents().iter().find(|st| st.doc.id == doc).is_some_and(|st| photocraft_engine::file_cmds::holds_at(&st.doc, path)); + (false, holds) + } + }; + self.ui.status = crate::i18n::fmt(tl!("Saved {name}"), &[("name", path)]); + // The file was written, copy or not: another tab bound to it no longer matches it. + self.detach_others_from_file(path, doc); + if !copy { + // A background save may finish while another document is active (or after its + // document was closed, when there is nothing left to record). + let _ = self.with_document(doc, |app| { + if let Some(st) = app.session.active_mut() + && arm + { + st.saved_to(path.to_string()); + // The job locked the document, but record the revision that was written. + st.saved_revision = revision; + app.remember_stamp(doc, path); + } + // "Save Document" script events and File › Generate › Image Assets. + if hooks + && let Some(i) = app.session.active_index() + && let Some(r) = photocraft_engine::automate_cmds::document_saved(&mut app.session, i) + { + let template = "Saved {path}; image assets: {n} in {dir}"; + app.ui.status = crate::i18n::fmt( + tl!(template), + &[("path", path), ("n", &r["files"].as_array().map_or(0, Vec::len).to_string()), ("dir", r["dir"].as_str().unwrap_or(""))], + ); + } + Ok(()) + }); + // The file the document now lives in goes to the top of Open Recent and the Home + // screen, as opening it does (#4400). Automation saves don't touch the user's list. + if hooks { + self.push_recent(path); + } + } else if self.disk_stamps.get(&doc).is_some_and(|(own, _)| own == path) { + // A copy written over the document's own file is this app's change too. + self.remember_stamp(doc, path); + } + self.ui.status_error = false; + let what = crate::i18n::fmt(tl!("Saved {name}"), &[("name", file_open::display_name(path).as_str())]); + notices::io_warnings(self, &what, warnings); + self.sync_views(); + } + + /// Note how `doc`'s own file at `path` looks now that the document read or wrote it. + pub(crate) fn remember_stamp(&mut self, doc: photocraft_doc::DocId, path: &str) { + match self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)) { + Some(now) => self.disk_stamps.insert(doc, (path.to_string(), now)), + None => self.disk_stamps.remove(&doc), + }; + } + + /// Another app changed `doc`'s own file at `path` since the document was opened from it or + /// last saved to it. A file that is gone, or one never stamped, counts as unchanged. + pub(crate) fn changed_on_disk(&self, doc: photocraft_doc::DocId, path: &str) -> bool { + let Some((own, then)) = self.disk_stamps.get(&doc) else { return false }; + own == path && self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)).is_some_and(|now| now != *then) + } + + /// TIFF, Targa, DDS or JPEG Options is waiting on an answer before a save is written. + pub(crate) fn save_options_open(&self) -> bool { + self.tiff_options.is_some() || self.targa_options.is_some() || self.dds_options.is_some() || self.jpeg_options.is_some() + } + + /// Writes a save that waited on a format prompt (Targa, DDS or JPEG Options) once answered: + /// journals `step` as its command (`file.saveAs` for Save As, `file.saveACopy` for Save a + /// Copy, `file.save` for a plain Save), so an action being recorded keeps it with this answer + /// (#2032, #4373), reports a failure in the status bar, and releases a close prompt waiting on + /// the save. + pub(crate) fn write_answered_save(&mut self, ctx: &egui::Context, doc: DocId, path: String, settings: &ExportSettings, copy: bool, step: (&str, Value)) { + let written = self.with_document(doc, |app| app.write_document(path, settings, copy)); + if written.is_ok() { + self.session.journal.push((step.0.into(), step.1)); + } + match written { + Err(e) => { + self.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]); + self.ui.status_error = true; + } + Ok(Some(_)) if !copy => crate::discard_ui::saved_document(self, ctx, doc), + // A background save releases the close prompt when it finishes (`jobs_ui`). + Ok(_) => {} + } + } + + /// A print worker may still be handing a job to the system queue. + pub(crate) fn printing(&self) -> bool { + self.session.jobs().iter().any(|j| matches!(j.command.as_str(), "file.print" | "file.printOneCopy")) + } + + /// A save is running in the background. + pub(crate) fn saving(&self) -> bool { + !self.jobs.saves.is_empty() + } + + /// Save through the control session's capability-scoped writer. No file + /// picker or ambient writer is reachable from this path. Returns the path + /// written and the export warnings (also shown to the user). + pub fn save_automation(&mut self, path: Option) -> Result { + self.save_automation_with(path, FormatChoices::default()) + } + + /// [`Self::save_automation`] writing with the format `choices` given (a Targa's `None`: 32 + /// with an alpha channel or transparency, else 24; a DDS texture's: uncompressed without + /// mipmaps; a JPEG's: the file's own quality, Baseline). Automation saves never prompt. + pub fn save_automation_with(&mut self, path: Option, choices: FormatChoices) -> Result { + let target = { + let state = self.session.active().ok_or("no document")?; + // As File › Save: without `path` only a layered file is written back (#416). + path.or_else(|| state.path.clone().filter(|p| photocraft_engine::file_cmds::holds_at(&state.doc, p))).ok_or( + "pass `path`: a save without one writes back only to the document's own PSD, PSB, .pcraft or OpenRaster file, and to OpenRaster only when it holds everything (adjustment layers, styles and masks don't fit)", + )? + }; + let reply = |path: &str, warnings: &[String]| json!({"path": path, "warnings": warnings}); + // Only the target is granted: a linked smart object's stored path is document data, so + // PSD export writes that layer as pixels instead of embedding the file. + let settings = ExportSettings { read_linked_files: false, ..choices.apply(self.save_settings()) }; + // #2017: the File › Save worker path, so the encode doesn't block the frame loop. + if self.background_jobs + && let Some(save) = self.services.automation_save.clone() + { + return match jobs_ui::start_save(self, target.clone(), settings, false, save, true)? { + Some((path, warnings)) => Ok(reply(&path, &warnings)), + None => { + let job = self.jobs.last_started; + Ok(json!({"path": target, "job": job, "pending": true, "warnings": []})) + } + }; + } + let state = self.session.active().ok_or("no document")?; + let (doc, revision) = (state.doc.id, state.revision); + let export = self.services.export.as_ref().ok_or("no exporter configured")?; + let (bytes, warnings) = export(&state.doc, &target, &settings)?; + let write = self.services.automation_write.as_mut().ok_or("automation write authority is not configured")?; + write(&target, &bytes)?; + self.saved_automation(doc, revision, &target, &warnings, false); + Ok(reply(&target, &warnings)) + } + + /// The active document's identity at admission: a queued capture never applies to another + /// document. Includes the revision so a saved image is attributable to a known state. + pub(crate) fn document_identity(&self) -> Option { + self.session.active().map(|st| crate::screenshot::DocumentId { + document: st.doc.id.0, + revision: st.revision, + generation: self.session.active_generation(), + }) + } +} + +/// The New Document dialog's key in the preferences' `dialogs` map. +const NEW_DOCUMENT: &str = "file.new"; + +/// New Document fields its OK remembers (#1810): the size, resolution, mode, depth, background and +/// display units. Not the name, the preset or the clipboard size. +const NEW_DOCUMENT_REMEMBERED: [&str; 8] = ["width", "height", "resolution", "mode", "depth", "background", "__unit", "__resUnit"]; + +/// A remembered value the dialog can show (a corrupt preference is ignored). +fn remembered_new_document_value(key: &str, v: &serde_json::Value) -> bool { + match key { + "width" | "height" => v.as_u64().is_some_and(|n| (1..=300_000).contains(&n)), + "resolution" => v.as_f64().is_some_and(|r| r.is_finite() && r > 0.0 && r <= 30_000.0), + "depth" => v.as_u64().is_some_and(|d| matches!(d, 1 | 8 | 16 | 32)), + _ => v.as_str().is_some_and(|s| !s.is_empty() && s.len() <= 64), + } +} + +/// Remember the New Document fields `f` its OK used, for the next New Document. +pub(crate) fn remember_new_document(app: &mut PhotocraftApp, f: &serde_json::Map) { + let kept: serde_json::Map = + NEW_DOCUMENT_REMEMBERED.iter().filter_map(|k| f.get(*k).filter(|v| remembered_new_document_value(k, v)).map(|v| (k.to_string(), v.clone()))).collect(); + app.session.prefs.edit(|p| p.dialogs.insert(NEW_DOCUMENT.into(), serde_json::Value::Object(kept))); +} + +impl PhotocraftApp { + /// File › New's fields: the defaults, then the settings of the last document made with the + /// dialog (Photoshop starts from them, #1810), then the Clipboard preset (the clipboard image's + /// size, selected) when the clipboard holds an image. Opening the dialog is an explicit + /// request, so the OS clipboard is read here, as for a paste. + pub(crate) fn new_document_fields(&mut self) -> serde_json::Map { + let mut f = crate::state::UiState::new_document_fields(); + if let Some(serde_json::Value::Object(saved)) = self.session.prefs().dialogs.get(NEW_DOCUMENT) { + for k in NEW_DOCUMENT_REMEMBERED { + if let Some(v) = saved.get(k).filter(|v| remembered_new_document_value(k, v)) { + f.insert(k.into(), v.clone()); + } + } + } + if self.import_os_clipboard().is_err() { + return f; + } + if let Some(c) = self.session.clipboard.as_ref().filter(|c| !c.bounds.is_empty()) { + crate::new_doc_ui::set_clipboard(&mut f, c.bounds.width(), c.bounds.height()); + } + f + } +} diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs new file mode 100644 index 0000000000..6969db33c1 --- /dev/null +++ b/crates/ui-egui/src/app/frame.rs @@ -0,0 +1,344 @@ +use super::*; + +impl PhotocraftApp { + /// Wait out the rest of [`Self::min_frame_ms`] since the last frame started. + fn cap_frame_rate(&mut self) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(min) = self.min_frame_ms.filter(|m| m.is_finite() && *m > 0.0) { + let wait = min.min(100.0) - (gpu_canvas::now_ms() - self.last_frame_start_ms); + if wait > 0.0 { + std::thread::sleep(std::time::Duration::from_secs_f64(wait / 1000.0)); + } + } + self.last_frame_start_ms = gpu_canvas::now_ms(); + } +} + +impl PhotocraftApp { + /// Shared logic body. A wrapping host owns the final reset tail after its own work. + pub fn logic_frame(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { + self.cap_frame_rate(); + i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language)); + // Caps Lock state read from the OS once per frame (see `Services::caps_lock`): the canvas + // cursor block needs it before the frame renders. `None` (Wayland/web) keeps `false`. + self.caps_lock = self.services.caps_lock.as_mut().is_some_and(|f| f()); + tool_cursor::set_wayland(ctx, self.services.is_wayland); + if !self.styled { + Self::setup_context(ctx, self.ui.theme); + self.styled = true; + } else { + self.fonts_ready = true; + } + self.frame += 1; + let now = ctx.input(|i| i.time); + let dt = (now - self.last_frame_time) as f32; + if dt > 0.0 { + self.fps = self.fps * 0.9 + (1.0 / dt).min(240.0) * 0.1; + } + self.last_frame_time = now; + self.sync_views(); + crate::type_font_preview::follow_hover(self, ctx); + self.check_gpu(ctx); + #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] + if self.live_tokens.poll(ctx, self.ui.theme) { + self.checker = None; + } + // Finish or expire outstanding captures first, so a new request admitted in this pass + // sees their released budget. + self.drain_captures(ctx); + self.drain_control(ctx); + native_menu::run(self, ctx); + // Switching tools commits, also between the Type and Type Mask tools. + if self.ui.text_edit.as_ref().is_some_and(|ed| !self.ui.tool.is_type() || ed.mask != self.ui.tool.is_type_mask()) { + type_tool::commit(self); + } + // So does selecting another layer or document by any route (#6483). + type_tool::end_if_left(self); + if self.ui.pen.as_ref().is_some_and(|p| !p.drawn_with(self.ui.tool)) { + vector_ui::pen_commit(self, false); + } + transform_tool::end_if_left(self); + shape_stroke_ui::sync_editor(self, ctx); + prefs_ui::tick(self, ctx); + updates_ui::tick(self, ctx); + monitor_status::poll_frame(self, ctx, frame); + // Control requests and persisted preferences can change the language in this frame. + i18n::sync_context(ctx, &self.session.prefs().interface.language); + type_tool::sync_font_names(ctx, self.session.prefs().type_.show_font_names_in_english); + // A window bigger than its display (1440 × 900 on 1366 × 768) runs under the taskbar: + // maximize it into the work area once (#315). + work_area::fit_window(ctx); + discard_ui::guard_window_close(self, ctx); + // Background jobs: apply finished ones, keep frames coming, Esc cancels (before the + // shortcuts see Esc). + if !screen_picker::tick(self, ctx) { + jobs_ui::tick(self, ctx); + #[cfg(not(target_arch = "wasm32"))] + filter_preview_worker::discard_closed(self); + if type_tool::in_ui_pass(ctx) { + if self.fonts_ready { + shortcuts::handle(self, ctx); + } else { + type_tool::controls_only(self, ctx); + } + } + } + let arrived: Vec<(String, Vec)> = + self.services.inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default(); + for (name, bytes) in arrived { + if let Err(e) = self.open_bytes(&name, &bytes) { + self.open_failed(&name, &e); + } + } + // Web drops onto the canvas, read since the last frame: placed below, one at a time. + let to_place: Vec<(String, Vec)> = + self.services.place_inbox.as_ref().map(|q| std::mem::take(&mut *q.lock().unwrap_or_else(|e| e.into_inner()))).unwrap_or_default(); + self.drop_places.extend(to_place.into_iter().map(|(name, bytes)| file_open::DropPlace::Bytes(name, bytes))); + // Finder double-click / Open With / Dock drops (macOS open-documents events). + self.drain_os_events(ctx); + // While files are dragged over the window it gets no pointer events: keep frames coming so + // the tab strip can follow the pointer. + if ctx.input(|i| !i.raw.hovered_files.is_empty()) { + ctx.request_repaint(); + } + let dropped = ctx.input(|i| i.raw.dropped_files.clone()); + if !dropped.is_empty() { + let at = self.services.cursor_pos.as_mut().and_then(|f| f(ctx)); + self.open_dropped(ctx, dropped, at); + // Files dragged in from another app's window: PhotoCraft comes to the front and takes + // the keyboard, as Photoshop does, instead of staying behind the source (#5687). + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + } + self.place_next_dropped(ctx); + // The control transport wakes the UI on arrival (ctx.request_repaint); only poll while a + // screenshot is pending. (Polling every 50 ms here made idle apps render at 20 fps.) + if self.captures.any_pending() { + ctx.request_repaint_after(std::time::Duration::from_millis(16)); + } + // A hidden host runs no UI pass: a queued (or re-queued) capture asks for one. An issued + // capture's own `Screenshot` command forces its paint; asking again would spin a hidden + // window while a slow readback is in flight. Synthetic input queued during hidden ticks + // needs the same wake: its events sit in eframe's preserved input until a UI pass. + if self.captures.any_unissued() || self.synthetic_batch.is_some() || !self.synthetic.is_empty() { + ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaintWhileHidden); + } + self.poll_file_dialog(ctx, Some(frame)); + } + + /// Shared UI body. A wrapping host must call `finish_type_reset_pass` after return, + /// including when this body returns early without drawing an editor. + pub fn ui_frame(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + let ctx = ui.ctx().clone(); + // One control owner even when this callback cannot draw the custom editor. + if !self.fonts_ready + || !self.ui.dialogs.is_empty() + || screen_picker::busy(&ctx) + || self.ui.text_edit.is_none() + || ctx.text_edit_focused() + || ctx.egui_wants_keyboard_input() + { + type_tool::controls_only(self, &ctx); + } + // 0.36 saved panel sizes under `Id::unique(name)`; 0.37 reads parent-scoped keys. Data-only, + // so it runs even before fonts are ready; the old keys stay for a 0.36 rollback. + panels::migrate_panel_state(&ctx); + // A real UI pass, not a hidden `run_logic` tick: record the capture geometry (the + // document identity included) and count one settling pass. `run_logic` leaves these + // input values stale; only this real UI phase counts toward settling. + let geometry = crate::screenshot::CaptureGeometry::current(&ctx, self.document_identity()); + self.captures.note_geometry(geometry); + self.captures.note_pass(); + // A real UI pass consumes the one in-flight synthetic batch (see `inject_synthetic`). + self.begin_synthetic_pass(&ctx); + self.hover_layer = None; + i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language)); + // Fonts registered via set_fonts only take effect next frame; named families would panic now. + if !self.fonts_ready { + // egui consumed this pass's input without PhotoCraft handling it: keep the synthetic + // batch for the next pass instead of losing the step. + self.defer_synthetic_pass(); + ctx.request_repaint(); + self.automation_input = false; + // No editor was drawn this pass: end its IME context rather than keep a stale owner. + type_tool::sync_ime(self, &ctx); + return; + } + let t0 = gpu_canvas::now_ms(); + self.perf.frame_refresh_ms = 0.0; + self.stroke_trace.cpu_prev(frame.info().cpu_usage); + // A text field's right-click menu, before any field is drawn (text_field_menu.rs). + text_field_menu::show(&ctx); + // The wheel goes to a focused value field before the canvas or a panel sees it (#5473). + field_wheel::begin_frame(&ctx); + // Each painting tool keeps its own brush (#218), so switch the active tool's brush in + // before anything this frame reads it (the cursor, the options bar, a stroke). + // Preferences ▸ Type ▸ Recent Fonts: a smaller cap (or 0) trims the existing list at + // once, not only after the next pick. + self.sync_recent_fonts(); + paint_mouse::sync_tool_brush(self); + // A unit typed into a value field (`1in` in a px field) converts at the active document's + // resolution, as in Photoshop. + let ppi = self.session.prefs().units_and_rulers.point_size.per_inch(); + let dpi = self.session.active().map_or(72.0, |d| f64::from(d.doc.resolution_dpi.max(1.0))); + crate::widgets::set_field_resolution(&ctx, dpi, ppi); + // View › Screen Mode › Full Screen Mode: only the image, on black (F or Esc returns). + screen_picker::show(&ctx); + if screen_picker::busy(&ctx) && screen_picker::showing(&ctx) { + egui::Modal::new(egui::Id::unique("screen-color-wait")).show(&ctx, |ui| { + ui.spinner(); + ui.label(tl!("Pick a screen pixel or press Esc to cancel")); + if ui.button(tl!("Cancel")).clicked() { + screen_picker::cancel(&ctx); + } + }); + // This pass handled its input (the modal above ran): deliver the synthetic batch. + self.finish_synthetic_pass(); + self.automation_input = false; + type_tool::sync_ime(self, &ctx); + gpu_status::check_window(self, &ctx); + return; + } + if screen_picker::busy(&ctx) { + ui.disable(); + ui.set_opacity(1.0); + } + // The OS title bar (and the taskbar / Alt-Tab entry) follows the active file; with the + // system title bar this is where the document name lives, as the in-app title is hidden. + panels::sync_window_title(self, &ctx); + let chrome = !self.ui.view.hides_chrome(); + if chrome { + self.ui.panels.full_screen_chrome = false; + } + // In Full Screen Mode, Tab shows the menu bar, options bar, toolbar and dock (#6760). + let tabbed_in = !chrome && self.ui.panels.full_screen_chrome; + if (chrome || tabbed_in) && self.ui.panels.menu_bar { + panels::title_bar(self, ui); + } + if (chrome && self.ui.panels.options_bar) || tabbed_in { + panels::options_bar(self, ui); + } + if chrome && self.ui.panels.status_bar { + panels::status_bar(self, ui); + } + if (chrome && self.ui.panels.toolbar) || tabbed_in { + panels::toolbar(self, ui); + } + // craft-ui's layout holds the canvas as its protected `canvas` panel. + let docking = (chrome && self.ui.panels.dock) || tabbed_in; + 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); + }); + panels::properties_window(self, &ctx); + } + brush_panel::window(self, &ctx); + preset_panels::windows(self, &ctx); + gradient_ui::editor_window(self, &ctx); + type_panels_ui::windows(self, &ctx); + analysis_ui::windows(self, &ctx); + timeline_ui::windows(self, &ctx); + workspace_ui::windows(self, &ctx); + palette::show(self, &ctx); + dialogs::show(self, &ctx); + layers_panel_ui::show_dialog(self, &ctx); + rasterize_prompt::run_pending(self, &ctx); + jobs_ui::dialog(self, &ctx); + discard_ui::show(self, &ctx); + tiff_options_ui::show(self, &ctx); + targa_options_ui::show(self, &ctx); + jpeg_options_ui::show(self, &ctx); + dds_options_ui::show(self, &ctx); + distort_ui::show(self, &ctx); + camera_raw_ui::show(self, &ctx); + wide_angle_ui::show(self, &ctx); + canvas::extra_windows(self, &ctx); + notices::show(self, &ctx); + updates_ui::show(self, &ctx); + gpu_status::show_fallback(self, &ctx); + kys_import::show_offer(self, &ctx); + if self.titlebar_modal_drag(chrome) { + titlebar::modal_drag_overlay(&ctx); + } + if self.custom_titlebar { + titlebar::resize_zones(ui); + } + // A device lost while drawing this frame: switch to the CPU canvas before the next one. + gpu_status::check(self, &ctx); + // The Brush Preset picker's view (its gear's card parts and the footer scale) is + // remembered once the pointer is up. Here, after every panel, rather than in the + // picker's own code: the control channel can set it while the picker is closed. + brush_picker::persist(self, &ctx); + // The tool's brush (settings and tip references) is remembered the same way. Like the + // picker's view, in the frame loop, so the control channel can set it with the panels + // closed; the engine's revision counter keeps an unchanged brush free. + last_brush::persist(self, &ctx); + // Tool options are remembered between launches the same way (#2814). + tool_memory::persist(self, &ctx); + // So are View › Extras, Show and Snap To (#3762). + view_cmds::persist(self, &ctx); + // Remember the 0.37 panel sizes so a later 0.36 rollback's newer old-key values win on + // the next upgrade (see `panels::migrate_panel_state`). + panels::remember_panel_state(&ctx); + self.automation_input = false; + shape_stroke_ui::finish_frame(self, &ctx); + native_menu::sync(self, &ctx); + if screen_picker::busy(&ctx) { + // Block input without a backdrop: the worker may still be capturing the screen. + egui::Modal::new(egui::Id::unique("screen-color-wait")).frame(egui::Frame::NONE).backdrop_color(egui::Color32::TRANSPARENT).show(&ctx, |_| {}); + ctx.set_cursor_icon(egui::CursorIcon::Wait); + } + let ui_ms = gpu_canvas::now_ms() - t0; + // A GPU measurement lands a frame or two after the refresh it belongs to. Refreshes + // carry them out, but the last refresh before the app settles has none following it, so + // drain the timer here too or its number is never reported. Drain it either way: a + // measurement left sitting would surface later against an unrelated refresh. Report it + // only while the canvas is still on the GPU, since a CPU refresh clears `gpu_ms` + // precisely so a GPU number is never shown as that refresh's. + if let Some(gpu) = &self.gpu + && let Some(t) = gpu.take_gpu_timing() + && self.perf.last_refresh.starts_with("gpu") + { + self.perf.record_gpu(t); + } + self.perf.frame(ui_ms); + if self.stroke_trace.enabled() { + self.stroke_trace.canvas(self.perf.frame_refresh_ms); + let info = &self.perf.gpu_info; + self.stroke_trace.end_frame(ui_ms, self.live_stroke.is_some(), || { + let gpu = format!("{} {}", info.backend, info.adapter).trim().to_string(); + if info.present.is_empty() { gpu } else { format!("{gpu}, {}", info.present) } + }); + } + // This pass handled its input: the in-flight synthetic batch is delivered once and the + // next step may be injected on the next frame. + self.finish_synthetic_pass(); + // Synthetic input is injected one press/release step per frame: keep frames coming until + // the queue is empty, then release control replies waiting on it. + // Only a pass that reached the end of the UI and delivered the in-flight batch counts as + // settled input; an early-returning pass keeps the batch (and the waiting replies). + if !self.synthetic.is_empty() || self.synthetic_batch.is_some() { + ctx.request_repaint(); + } else if !self.input_waiters.is_empty() { + for w in self.input_waiters.drain(..) { + let _ = w.send(serde_json::json!({"ok": true, "result": null})); + } + } + // A menu or dialog can start a filter after `jobs_ui::tick` ran in this frame. Keep + // polling it even when the platform would otherwise put the event loop to sleep. + jobs_ui::keep_polling(self, &ctx); + // Menus and buttons in this frame may have asked for a file dialog. + self.poll_file_dialog(&ctx, Some(frame)); + // The Type tool's IME descriptor is the last writer of this pass: every panel and the + // canvas have finished mutating the model, and an absent/focus-moved editor ends here. + type_tool::sync_ime(self, &ctx); + // Issue any due `ui.screenshot` now that this pass's state is settled: a queued request + // that has waited its passes and animation delay captures exactly this frame. + self.issue_captures(&ctx); + // Last, after everything drawn this frame: a lost window device can't draw it (#3438). + gpu_status::check_window(self, &ctx); + } +} diff --git a/crates/ui-egui/src/app/gpu.rs b/crates/ui-egui/src/app/gpu.rs new file mode 100644 index 0000000000..73c08338ed --- /dev/null +++ b/crates/ui-egui/src/app/gpu.rs @@ -0,0 +1,76 @@ +use super::*; + +impl PhotocraftApp { + /// Draw the document canvas on the GPU (custom WGSL shader) instead of via egui textures. + /// Call from the app creator with `cc.wgpu_render_state`; without it the CPU path is used. + pub fn set_wgpu(&mut self, rs: eframe::egui_wgpu::RenderState) { + // Preferences › Performance › cache tile size (PHOTOCRAFT_GPU_TILE still overrides). + let tile = self.session.prefs().performance.cache_tile_size; + // Escaped driver/setup panics must leave the session and CPU canvas alive. + self.perf.gpu_info.set_adapter(&rs.adapter.get_info()); + // The browser has no adapter list (egui-wgpu only has it natively). + #[cfg(not(target_arch = "wasm32"))] + self.perf.gpu_info.set_available(&rs.available_adapters); + self.gpu_render_state = Some(rs.clone()); + let gpu = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| gpu_canvas::GpuCanvas::with_tile(&rs, Some(tile)))) { + Ok(gpu) => gpu, + Err(payload) => { + let detail = payload + .downcast_ref::() + .cloned() + .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string())) + .unwrap_or_else(|| "GPU canvas initialization failed".into()); + self.perf.gpu_info.canvas = "cpu".into(); + self.perf.gpu_info.fallback = Some(detail.clone()); + gpu_status::queue_fallback_notice(self, detail); + self.watch_window_device(&rs.device); + return; + } + }; + self.perf.gpu_info.canvas = "gpu".into(); + self.window_device = Some((rs.device.clone(), gpu.health().clone())); + self.gpu = Some(gpu); + self.prefs_rt.gpu_style = None; + } + + /// Whether the document canvas currently draws on the GPU (false on the CPU path, and after + /// the device was lost). + pub fn gpu_active(&self) -> bool { + self.gpu.is_some() + } + + /// The GPU canvas's device health flag (tests inject faults through it). + pub fn gpu_health(&self) -> Option { + self.gpu.as_ref().map(|g| g.health().clone()) + } + + /// Watch the device the window draws with when the GPU canvas doesn't (the CPU canvas), so + /// its loss is handled like the GPU canvas's (see `gpu_status::check_window`). + pub fn watch_window_device(&mut self, device: &eframe::wgpu::Device) { + self.window_device = Some((device.clone(), photocraft_gpu::DeviceHealth::watch(device))); + } + + /// Whether the window's graphics device was lost, so the app saves its documents for + /// recovery and closes once they are saved (#3438). + pub fn window_lost(&self) -> bool { + self.window_lost + } + + /// Destroy the window's graphics device, as a driver reset does (`ui.gpu.simulateLoss` + /// with `destroy`, tests). Returns whether there was one. + pub fn destroy_window_device(&mut self) -> bool { + self.window_device.as_ref().map(|(device, _)| device.destroy()).is_some() + } + + /// Run `hook` once the app has rendered its first frames (and a document opened at launch + /// has drawn): the desktop app clears its crash-safe GPU startup marker there. + pub fn on_started(&mut self, hook: impl FnOnce(&mut PhotocraftApp) + 'static) { + self.started = Some(Box::new(hook)); + } + + /// Per-frame GPU health check (called from `logic`; tests call it directly): falls back to + /// the CPU canvas after a device loss and runs the started hook. + pub fn check_gpu(&mut self, ctx: &egui::Context) { + gpu_status::check(self, ctx); + } +} diff --git a/crates/ui-egui/src/app/ime.rs b/crates/ui-egui/src/app/ime.rs new file mode 100644 index 0000000000..a0fa5b193f --- /dev/null +++ b/crates/ui-egui/src/app/ime.rs @@ -0,0 +1,20 @@ +use super::*; + +impl PhotocraftApp { + /// Install the callback-mode markers in an app creator, before the first `run_ui` on this + /// Context (and again through [`Self::setup_context`] when a host replaces its Context). + /// Installing while a pass is already running cannot mark that pass; it only arms the next. + pub fn install_type_reset_hooks(ctx: &egui::Context) { + type_tool::install_reset_hooks(ctx); + } + + /// The host's UI tail, after all panels and any shell-side model/focus mutations. + pub fn finish_type_reset_pass(&mut self, ctx: &egui::Context) { + type_tool::finish_reset_pass(self, ctx); + } + + /// The host's logic tail; full UI passes leave availability to their later UI tail. + pub fn finish_type_reset_logic(&mut self, ctx: &egui::Context) { + type_tool::finish_reset_logic(self, ctx); + } +} diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs new file mode 100644 index 0000000000..9b26957e58 --- /dev/null +++ b/crates/ui-egui/src/app/input.rs @@ -0,0 +1,134 @@ +use super::*; + +/// Remove one contiguous run equal to `batch` from `events` (eframe's preserved synthetic +/// input). A no-op when the run is not present. +fn remove_event_run(events: &mut Vec, batch: &[egui::Event]) { + if batch.is_empty() || batch.len() > events.len() { + return; + } + if let Some(pos) = events.windows(batch.len()).position(|w| w == batch) { + events.drain(pos..pos + batch.len()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_dropped(f: &(dyn egui::DroppedFile + Send + Sync)) -> Result, String> { + f.bytes() +} + +/// On the web, dropped-file bytes arrive asynchronously; the web shell handles drops itself. +#[cfg(target_arch = "wasm32")] +pub(crate) fn read_dropped(_f: &dyn egui::DroppedFile) -> Result, String> { + Err("drag-and-drop on the web is handled by the page; use File → Open".into()) +} + +impl PhotocraftApp { + /// The document/focus identity the in-flight synthetic batch was queued for. + fn synthetic_target(&self, ctx: &egui::Context) -> SyntheticTarget { + SyntheticTarget { document: self.document_identity(), focus: ctx.memory(|m| m.focused()) } + } + + fn synthetic_target_matches(&self, ctx: &egui::Context) -> bool { + self.synthetic_snapshot.is_some_and(|queued| queued.matches(self.synthetic_target(ctx))) + } + + /// Put at most one queued synthetic batch into this pass's input. + /// + /// The batch is appended once and tracked; `begin_pass` consumes it. While it is in flight no + /// further step is drained, so hidden logic ticks cannot accumulate several batches into one + /// pass. A document or focus change observed here is before eframe consumes the events, so the + /// batch is dropped and its waiting control replies fail instead of landing somewhere else. + /// If a pass consumed it but PhotoCraft returned before handling input (fonts not ready), the + /// same batch is appended again on the next hook, exactly once. + pub(crate) fn inject_synthetic(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) { + if self.synthetic_batch.is_some() { + if !self.synthetic_target_matches(ctx) { + // eframe may already carry the batch in its preserved input: withdraw exactly + // those events before the host consumes them, then fail the waiting replies. + if let Some(batch) = self.synthetic_batch.as_ref() { + remove_event_run(&mut raw_input.events, batch); + } + self.cancel_synthetic("the active document or focus changed while the input was queued"); + return; + } + if self.synthetic_reinject { + if let Some(batch) = self.synthetic_batch.clone() { + raw_input.events.extend(batch); + } + self.synthetic_reinject = false; + self.automation_input = true; + } + return; + } + if self.synthetic.is_empty() { + return; + } + let events = self.take_synthetic_step(); + if events.is_empty() { + return; + } + self.synthetic_snapshot = Some(self.synthetic_target(ctx)); + raw_input.events.extend(events.iter().cloned()); + self.synthetic_batch = Some(events); + } + + /// A pass begins with the in-flight batch. The events are already in this pass's input, so a + /// target change detected now cannot withdraw them: deliver them (never half-apply) and keep + /// `automation_input` set so the commands they trigger still go through the automation policy. + /// `inject_synthetic` performs the withdrawable check, before the host consumes the events. + /// Called at the start of `App::ui` only (a hidden `run_logic` tick consumes no input). + pub(crate) fn begin_synthetic_pass(&mut self, ctx: &egui::Context) { + if self.synthetic_batch.is_none() { + return; + } + if !self.synthetic_target_matches(ctx) { + log::warn!("synthetic input: the document or focus changed inside the pass; delivering it as automation input"); + } + self.automation_input = true; + } + + /// One full UI pass handled the in-flight batch: deliver it once and let the next step in. + pub(crate) fn finish_synthetic_pass(&mut self) { + let _ = self.synthetic_batch.take(); + self.synthetic_snapshot = None; + self.synthetic_reinject = false; + } + + /// The pass returned before the input handling (fonts not ready): keep the batch and have the + /// next hook append it again exactly once, because egui already consumed the events. + pub(crate) fn defer_synthetic_pass(&mut self) { + if self.synthetic_batch.is_some() { + self.synthetic_reinject = true; + } + } + + /// Drop the in-flight batch and fail the replies waiting on it. + fn cancel_synthetic(&mut self, reason: &str) { + let pending = self.synthetic_batch.take().is_some() || !self.synthetic.is_empty(); + self.synthetic.clear(); + self.synthetic_snapshot = None; + self.synthetic_reinject = false; + self.automation_input = false; + if pending || !self.input_waiters.is_empty() { + for w in self.input_waiters.drain(..) { + let _ = w.send(serde_json::json!({"ok": false, "error": format!("input cancelled: {reason}")})); + } + } + } + + /// Next step of queued synthetic input (automation): events up to and including the first + /// release, so egui sees press and release in separate frames. Hosts that don't call + /// `raw_input_hook` (offscreen harnesses) feed these to their input themselves. + pub fn take_synthetic_step(&mut self) -> Vec { + let n = self + .synthetic + .iter() + .position(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. } | egui::Event::Key { pressed: false, .. })) + .map_or(self.synthetic.len(), |i| i + 1); + let events: Vec<_> = self.synthetic.drain(..n).collect(); + if !events.is_empty() { + self.automation_input = true; + } + events + } +} diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs new file mode 100644 index 0000000000..0e19c3a88e --- /dev/null +++ b/crates/ui-egui/src/app/prefs.rs @@ -0,0 +1,68 @@ +use super::*; + +impl PhotocraftApp { + /// Records a picked type family for the font menu's Recent group, capped by + /// Preferences ▸ Type ▸ Recent Fonts (0 keeps no list), most recent first, de-duplicated. + pub fn note_recent_font(&mut self, family: &str) { + let cap = self.session.prefs().type_.recent_fonts.min(50) as usize; + let r = &mut self.ui.recent_fonts; + r.retain(|f| f != family); + if cap == 0 { + r.clear(); + return; + } + r.insert(0, family.to_string()); + r.truncate(cap); + } + + /// Preferences ▸ Type ▸ Recent Fonts: a smaller cap (or 0) applies to the existing list at + /// once, not only after the next pick. + pub fn sync_recent_fonts(&mut self) { + self.ui.recent_fonts.truncate(self.session.prefs().type_.recent_fonts.min(50) as usize); + } +} + +impl PhotocraftApp { + pub fn set_theme(&mut self, ctx: &egui::Context, kind: theme::ThemeKind) { + if let Err(e) = self.run("prefs.set", serde_json::json!({"path": "interface.theme", "value": kind.id()})) { + self.ui.status = e; + } else { + self.apply_theme(ctx, kind); + } + } + + pub(crate) fn apply_theme(&mut self, ctx: &egui::Context, kind: theme::ThemeKind) { + // Color and Swatches trade indices between Pro and Studio layouts. + if let Some(selected) = dock::Group::Color.tabs(theme::Tokens::for_kind(self.ui.theme).pro).get(self.ui.dock_tabs.color) + && let Some(tab) = dock::Group::Color.tabs(theme::Tokens::for_kind(kind).pro).iter().position(|name| name == selected) + { + self.ui.dock_tabs.color = tab; + } + self.ui.theme = kind; + panel_docking::sync_visibility(self); + theme::apply(ctx, kind); + self.checker = None; + } +} + +impl PhotocraftApp { + /// Install fonts, image loaders and the theme. Call from the app creator (and again for a + /// replacement Context) before the first `run_ui` so the very first frame renders and the + /// Type reset begin/end pass markers exist; otherwise `logic` does it and the first frame is + /// skipped, with the begin-pass marker necessarily starting on the following pass. + pub fn setup_context(ctx: &egui::Context, kind: theme::ThemeKind) { + Self::install_type_reset_hooks(ctx); + ctx.add_plugin(tool_cursor::CursorLifecycle); + ctx.add_plugin(single_line_drag::SingleLineDrag::default()); + theme::install_fonts(ctx); + egui_extras::install_image_loaders(ctx); + theme::apply(ctx, kind); + // Right-click in any text field: its Cut / Copy / Paste menu (text_field_menu.rs). + ctx.add_plugin(text_field_menu::TextFieldMenu); + // egui's own ⌘+ / ⌘- / ⌘0 scale the whole interface; PhotoCraft zooms the canvas instead + // (shortcuts.rs), like Photoshop. + ctx.options_mut(|o| o.zoom_with_keyboard = false); + // ⌘/Ctrl + wheel scrolls sideways, as in Photoshop; only a pinch zooms (wheel_nav.rs). + wheel_nav::configure(ctx); + } +} diff --git a/crates/ui-egui/src/app/screenshot.rs b/crates/ui-egui/src/app/screenshot.rs new file mode 100644 index 0000000000..41ff5feff4 --- /dev/null +++ b/crates/ui-egui/src/app/screenshot.rs @@ -0,0 +1,62 @@ +use super::*; + +impl PhotocraftApp { + /// Issue due screenshot requests. UI phase only: settling counts real layout passes, and the + /// geometry epoch is that of the pass the image will be rendered from. + pub(super) fn issue_captures(&mut self, ctx: &egui::Context) { + // A discarded pass (popup sizing, `request_discard`) will be re-run: capture only a pass + // whose UI state will actually be present. + if ctx.will_discard() { + return; + } + let now = crate::screenshot::now(); + let doc = self.document_identity(); + let finished = self.captures.issue(ctx, now, doc, |callback| crate::screenshot::send_command(ctx, callback)); + self.finish_captures(finished); + } + + /// Collect callbacks and expire requests. Logic phase; the image is encoded and written here, + /// on the UI thread, never inside the callback. + pub(super) fn drain_captures(&mut self, ctx: &egui::Context) { + let now = crate::screenshot::now(); + let doc = self.document_identity(); + // begin_pass supplies the new RawInput before App::logic; run_logic refreshes native + // viewport metadata too. Observe it before any completed callback can be delivered. + let current = crate::screenshot::CaptureGeometry::current(ctx, doc); + self.captures.note_geometry(current); + let observed = self.captures.last_geometry(); + let finished = self.captures.drain(now, observed, doc); + self.finish_captures(finished); + } + + pub(super) fn finish_captures(&mut self, finished: Vec) { + for f in finished { + let reply = match f.result { + Ok(image) => { + let [w, h] = image.size; + // The encoder takes RGBA bytes; its copy is bounded by the same per-image + // reservation as the retained image, and the image itself is released first. + match w.checked_mul(h).and_then(|n| n.checked_mul(4)) { + Some(bytes) if bytes <= crate::screenshot::MAX_IMAGE_BYTES => { + let rgba: Vec = image.pixels.iter().flat_map(|c| c.to_array()).collect(); + drop(image); + crate::control::save_screenshot_rgba(self, w, h, &rgba, f.path.as_deref()) + } + _ => serde_json::json!({ + "ok": false, + "error": format!( + "screenshot {} failed: the image exceeds the {} MiB encode budget", + f.token, + crate::screenshot::MAX_IMAGE_BYTES / (1 << 20) + ), + }), + } + } + Err(e) => serde_json::json!({"ok": false, "error": e}), + }; + if let Some(tx) = f.reply { + let _ = tx.send(reply); + } + } + } +} diff --git a/crates/ui-egui/src/app/targets.rs b/crates/ui-egui/src/app/targets.rs new file mode 100644 index 0000000000..8a22273b69 --- /dev/null +++ b/crates/ui-egui/src/app/targets.rs @@ -0,0 +1,151 @@ +use super::*; + +/// The active layer is an adjustment layer. It has no pixels, so painting and filling it edit its +/// mask even when its icon thumbnail, not the mask, is the Layers panel's target, as in +/// Photoshop (#4298). +pub(crate) fn adjustment_layer_active(st: &photocraft_engine::DocState) -> bool { + st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| matches!(l.content, photocraft_doc::LayerContent::Adjustment(_))) +} + +impl PhotocraftApp { + /// `params` aimed at the active layer's mask (`"target":"mask"`) when the Layers panel targets + /// it and command `id` edits the target (adjustments, filters, fills) without naming one: + /// ⌘I then inverts the mask, as in Photoshop (#780). A targeted alpha channel or Quick Mask + /// mode wins, as the engine routes those itself. + pub fn with_mask_target(&self, id: &str, params: Value) -> Value { + if !photocraft_engine::channel_cmds::follows_target(id) || params.get("target").is_some() { + return params; + } + // A filter mask is painted, filled and filtered in place; it doesn't float or move, and + // Edit › Transform, Apply Image and the dialog filters act on the smart object. + let target = if self.filter_mask_targeted() && photocraft_engine::channel_cmds::follows_filter_mask(id) { + "filterMask" + } else if self.layer_mask_targeted() { + "mask" + } else { + return params; + }; + match params { + Value::Object(mut m) => { + m.insert("target".into(), Value::from(target)); + Value::Object(m) + } + _ => serde_json::json!({ "target": target }), + } + } + + /// The Layers panel targets the active smart object's filter mask (FILE-215-3), and no alpha + /// channel or Quick Mask takes over. + pub fn filter_mask_targeted(&self) -> bool { + let Some(st) = self.session.active() else { return false }; + let Some(id) = st.active_layer.filter(|id| self.ui.filter_mask_target == Some(id.0)) else { return false }; + let composite = st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::Composite && st.doc.quick_mask.is_none(); + composite && st.doc.layer(id).is_some_and(|l| matches!(&l.content, photocraft_doc::LayerContent::Smart(sm) if !sm.smart_filters.is_empty())) + } + + /// The active layer's mask is what pixel commands edit: the Layers panel targets it, the layer + /// is an adjustment layer (no pixels of its own), or every colour channel is off and that mask + /// is the picture. An alpha channel or Quick Mask wins, as the engine routes those itself. + pub fn layer_mask_targeted(&self) -> bool { + let Some(st) = self.session.active() else { return false }; + let layer_mask = st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::LayerMask; + let composite = (st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::Composite || layer_mask) && st.doc.quick_mask.is_none(); + let has_mask = st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.mask.is_some()); + if !composite || !has_mask { + return false; + } + if self.ui.mask_target || layer_mask || adjustment_layer_active(st) { + return true; + } + let colors_off = st.channel_view.visible_colors(photocraft_engine::channel_cmds::color_count(&st.doc)) == 0; + let alpha_on = (0..st.doc.channels.len()).any(|i| st.channel_view.alpha_shown(i)); + colors_off && !alpha_on + } + + /// Targeting the pixels, the layer mask or the vector mask ends a shown filter mask (⌥-click + /// on its thumbnail): while it shows, [`Self::sync_mask_targets`] keeps the filter mask + /// targeted, so strokes would keep landing there. + pub(crate) fn end_filter_mask_view(&mut self) { + let Some(v) = self.session.active().and_then(photocraft_engine::mask_view_cmds::current).filter(|v| v.filter) else { return }; + let off = serde_json::json!({"layer": v.layer.0, "mode": "off", "mask": "filter"}); + if let Err(err) = self.session.execute(photocraft_engine::mask_view_cmds::ID, off) { + log::warn!("could not end the filter mask view: {err}"); + } + } + + /// Explicitly targeting a filter mask ends any conflicting mask view; untargeting it ends its + /// own view too. + pub(crate) fn select_filter_mask_target(&mut self, layer: Option) { + if layer.is_none() { + self.end_filter_mask_view(); + } + if layer.is_some() { + if let Some(st) = self.session.active_mut() { + if st.channel_view.layer_mask.is_some_and(|v| !v.filter || Some(v.layer.0) != layer) { + st.channel_view.layer_mask = None; + } + if matches!( + st.channel_view.target, + photocraft_engine::channel_cmds::ChannelTarget::LayerMask | photocraft_engine::channel_cmds::ChannelTarget::VectorMask + ) { + st.channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Composite; + } + } + self.ui.mask_target = false; + self.ui.vector_mask_target = false; + } + self.ui.filter_mask_target = layer; + self.sync_mask_targets(); + } + + /// Viewing a layer mask (#196) targets it; a vector-mask target needs a vector mask on the + /// active layer (a shape layer's path is its content, not a mask). Targeting a mask or the + /// pixels brings back that target's foreground/background pair, as in Photoshop (#2166). + pub(crate) fn sync_mask_targets(&mut self) { + if let Some(st) = self.session.active_mut() { + use photocraft_engine::channel_cmds::ChannelTarget; + let channel = st.channel_view.target; + match photocraft_engine::mask_view_cmds::current(st) { + Some(v) if v.filter => { + self.ui.filter_mask_target = Some(v.layer.0); + self.ui.mask_target = false; + self.ui.vector_mask_target = false; + } + Some(_) => { + self.ui.mask_target = true; + self.ui.vector_mask_target = false; + self.ui.filter_mask_target = None; + } + None if channel == ChannelTarget::LayerMask => { + self.ui.mask_target = true; + self.ui.vector_mask_target = false; + } + None if channel == ChannelTarget::VectorMask => { + self.ui.vector_mask_target = true; + self.ui.mask_target = false; + } + None => {} + } + if self.ui.mask_target || self.ui.vector_mask_target { + self.ui.filter_mask_target = None; + } + if self.ui.vector_mask_target && !mask_thumbs_ui::has_vector_mask(st) { + self.ui.vector_mask_target = false; + } + if self.ui.mask_target && st.active_layer.and_then(|id| st.doc.layer(id)).is_none_or(|l| l.mask.is_none()) { + self.ui.mask_target = false; + } + if !self.ui.mask_target && st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::LayerMask { + st.channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Composite; + } + if !self.ui.mask_target || self.ui.properties_layer != st.active_layer.map(|l| l.0) { + self.ui.properties_layer = None; + } + } + if self.ui.filter_mask_target.is_some() && !self.filter_mask_targeted() { + self.ui.filter_mask_target = None; + } + let mask = self.layer_mask_targeted() || self.filter_mask_targeted(); + self.session.tools.target_mask(mask); + } +} diff --git a/crates/ui-egui/src/app/thumbs.rs b/crates/ui-egui/src/app/thumbs.rs new file mode 100644 index 0000000000..a5a52ccffc --- /dev/null +++ b/crates/ui-egui/src/app/thumbs.rs @@ -0,0 +1,366 @@ +use super::*; + +impl PhotocraftApp { + pub(super) fn prune_thumbs(&mut self) { + let documents = self.session.documents(); + if self.thumb_documents.len() == documents.len() + && self.thumb_documents.iter().zip(documents).all(|((id, snapshot), st)| *id == st.doc.id && snapshot.ptr_eq(&std::sync::Arc::downgrade(&st.doc))) + { + return; + } + // Check snapshots every sync, but walk the layer tree only after it changes. A Weak + // tracks replacement (including undo and preserved-ID reopen) without retaining pixels. + if !self.thumbs.is_empty() { + let mut live = std::collections::HashSet::new(); + let mut pending: Vec<_> = documents.iter().flat_map(|st| &st.doc.layers).collect(); + while let Some(layer) = pending.pop() { + live.insert((layer.id, mask_thumbs_ui::THUMB_LAYER)); + if layer.mask.is_some() { + live.insert((layer.id, mask_thumbs_ui::THUMB_MASK)); + } + if layer.vector_mask.is_some() { + live.insert((layer.id, mask_thumbs_ui::THUMB_VECTOR)); + } + if matches!(&layer.content, photocraft_doc::LayerContent::Smart(sm) if sm.filter_mask.is_some()) { + live.insert((layer.id, mask_thumbs_ui::THUMB_SMART_MASK)); + } + if let Some(children) = layer.children() { + pending.extend(children); + } + } + // Native files can restore IDs: retain the union across all open documents, rather + // than deleting an ID just because one document containing it was closed. + self.thumbs.retain(|key, _| live.contains(key)); + self.thumb_frames.retain(|id, _| live.contains(&(*id, mask_thumbs_ui::THUMB_LAYER))); + } + self.thumb_documents = documents.iter().map(|st| (st.doc.id, std::sync::Arc::downgrade(&st.doc))).collect(); + } + + /// Cached 64px thumbnail of a pixel-ish layer, letterboxed in a square, and the document + /// area it frames: the canvas, or with Clip Thumbnails to Layer Bounds the layer's pixels. + pub fn layer_thumb(&mut self, ctx: &egui::Context, doc: &Document, layer: &photocraft_doc::Layer) -> (egui::TextureId, photocraft_geom::Rect) { + let clip = self.session.prefs().interface.clip_thumbnails_to_layer_bounds; + // Key by content, not document revision: COW tiles change pointer only when their pixels + // change, so unrelated edits (e.g. painting another layer) don't rebuild this thumbnail. + let rev = layer.surface().map_or(0, surface_fingerprint) ^ (doc.size.width as u64) << 40 ^ u64::from(clip) << 63; + let key = (layer.id, mask_thumbs_ui::THUMB_LAYER); + if let Some((r, tex)) = self.thumbs.get(&key) + && *r == rev + && let Some(frame) = self.thumb_frames.get(&layer.id) + { + return (tex.id(), *frame); + } + let canvas = doc.bounds(); + let frame = layer_thumb_frame(layer, canvas, clip); + let mut px = [0.0f32; 8]; + let img = thumb_image(frame, 64, |x, y| { + let Some(s) = layer.surface() else { return [0.0; 4] }; + let n = s.channels(); + s.read_pixel(x, y, &mut px[..n]); + photocraft_raster::to_rgba(&s.format(), &px[..n]) + }); + self.thumb_frames.insert(layer.id, frame); + (self.store_thumb(ctx, key, rev, img), frame) + } + + /// The History panel thumbnail of snapshot `snap` of document `doc` (#2966): its composite, + /// centred in a square. Thumbnails of `doc`'s snapshots not in `live` are dropped. + pub fn snapshot_thumb(&mut self, ctx: &egui::Context, doc: DocId, snap: &photocraft_engine::history_cmds::Snapshot, live: &[u64]) -> egui::TextureId { + self.snapshot_thumbs.retain(|(d, id), _| *d != doc || live.contains(id)); + if let Some(tex) = self.snapshot_thumbs.get(&(doc, snap.id)) { + return tex.id(); + } + let comp = photocraft_compose::thumbnail(&snap.doc, 56); + let (w, h) = (comp.width as usize, comp.height as usize); + let side = w.max(h); + let (ox, oy) = ((side - w) / 2, (side - h) / 2); + let mut px = vec![egui::Color32::TRANSPARENT; side * side]; + for (i, &[r, g, b, a]) in comp.pixels.as_chunks::<4>().0.iter().enumerate() { + if let Some(out) = px.get_mut((i / w + oy) * side + i % w + ox) { + *out = egui::Color32::from_rgba_unmultiplied(r, g, b, a); + } + } + let tex = ctx.load_texture(format!("snapshot-{}", snap.id), egui::ColorImage::new([side, side], px), egui::TextureOptions::LINEAR); + let id = tex.id(); + self.snapshot_thumbs.insert((doc, snap.id), tex); + id + } + + /// The cached thumbnail of `mask`, the layer mask of layer `id`. + pub fn mask_thumb(&mut self, ctx: &egui::Context, doc: &Document, id: photocraft_doc::LayerId, mask: &photocraft_doc::LayerMask) -> egui::TextureId { + self.mask_thumb_kind(ctx, doc, id, mask, mask_thumbs_ui::THUMB_MASK) + } + + /// The thumbnail of `mask` under cache `kind`, re-rendered only when the mask's pixels or the document size change; Smart Filter and layer masks are cached apart. + pub(crate) fn mask_thumb_kind( + &mut self, + ctx: &egui::Context, + doc: &Document, + id: photocraft_doc::LayerId, + mask: &photocraft_doc::LayerMask, + kind: u8, + ) -> egui::TextureId { + let rev = surface_fingerprint(&mask.surface) ^ (doc.size.width as u64) << 40 ^ (doc.size.height as u64) << 16; + let key = (id, kind); + if let Some((r, tex)) = self.thumbs.get(&key) + && *r == rev + { + return tex.id(); + } + let mut v = [0.0f32; 1]; + let img = thumb_image(doc.bounds(), 64, |x, y| { + mask.surface.read_pixel(x, y, &mut v); + [v[0], v[0], v[0], 1.0] + }); + self.store_thumb(ctx, key, rev, img) + } + + pub(crate) fn store_thumb(&mut self, ctx: &egui::Context, key: (photocraft_doc::LayerId, u8), rev: u64, img: egui::ColorImage) -> egui::TextureId { + match self.thumbs.get_mut(&key) { + Some((r, tex)) => { + tex.set(img, egui::TextureOptions::LINEAR); + *r = rev; + tex.id() + } + None => { + let tex = ctx.load_texture(format!("thumb-{}-{}", key.0.0, key.1), img, egui::TextureOptions::LINEAR); + let id = tex.id(); + self.thumbs.insert(key, (rev, tex)); + id + } + } + } +} + +/// Cheap identity of a surface's pixels: its default (untouched) pixel, tile coordinates and +/// `Arc` pointers. The default pixel matters: inverting or filling a tile-less mask only changes +/// it (#2117). +pub fn surface_fingerprint(s: &photocraft_raster::Surface) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ s.tile_count() as u64; + for &b in s.default_bytes() { + h = (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3); + } + for (c, t) in s.tiles() { + let p = std::sync::Arc::as_ptr(t) as usize as u64; + h = (h ^ p ^ ((c.tx as u64) << 32 | c.ty as u32 as u64)).wrapping_mul(0x100_0000_01b3); + } + h +} + +/// The document area a layer thumbnail frames: the canvas, or with `clip` the layer's pixels on +/// it (the canvas again when it has none there, so an empty layer still shows the page shape). +pub(crate) fn layer_thumb_frame(layer: &photocraft_doc::Layer, canvas: photocraft_geom::Rect, clip: bool) -> photocraft_geom::Rect { + if !clip { + return canvas; + } + let bounds = layer.surface().map_or(photocraft_geom::Rect::EMPTY, photocraft_compose::bounds::content_bounds).intersect(&canvas); + if bounds.is_empty() { canvas } else { bounds } +} + +/// Square thumbnail of the document area `frame`, letterboxed, sampling `f(x, y)` in document +/// space. +fn thumb_image(frame: photocraft_geom::Rect, side: usize, mut f: impl FnMut(i32, i32) -> [f32; 4]) -> egui::ColorImage { + let (w, h) = (frame.width().max(1) as f32, frame.height().max(1) as f32); + let scale = w.max(h) / side as f32; + let (ox, oy) = ((side as f32 - w / scale) / 2.0, (side as f32 - h / scale) / 2.0); + let mut px = vec![egui::Color32::TRANSPARENT; side * side]; + for ty in 0..side { + for tx in 0..side { + let dx = (tx as f32 - ox + 0.5) * scale; + let dy = (ty as f32 - oy + 0.5) * scale; + if dx < 0.0 || dy < 0.0 || dx >= w || dy >= h { + continue; + } + let c = f(frame.x0.saturating_add(dx as i32), frame.y0.saturating_add(dy as i32)); + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + px[ty * side + tx] = egui::Color32::from_rgba_unmultiplied(q(c[0]), q(c[1]), q(c[2]), q(c[3])); + } + } + egui::ColorImage::new([side, side], px) +} + +impl PhotocraftApp { + /// Cached `Surface::content_bounds` keyed by an id and the surface's tile identity. + pub fn cached_bounds(&mut self, key: u64, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { + let rev = surface_fingerprint(surface); + if let Some((r, b)) = self.bounds_cache.get(&key) + && *r == rev + { + return *b; + } + let b = surface.content_bounds(); + if self.bounds_cache.len() > 256 { + self.bounds_cache.clear(); + } + self.bounds_cache.insert(key, (rev, b)); + b + } + + /// The box Properties › Transform shows for `layer` (X, Y, W, H): its pixels' bounds, but a + /// soft shape's path and stroke, whose Density and Feather render past them (#5846), as its + /// transform frame does. + pub fn layer_frame_bounds(&mut self, layer: &photocraft_doc::Layer, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { + match &layer.content { + photocraft_doc::LayerContent::Shape(sh) if sh.has_soft_mask() => { + // Cached per rendering, like the pixel bounds: the frame renders strips of the shape. + let (key, rev) = (layer.id.0 | 1 << 63, surface_fingerprint(surface)); + if let Some((r, b)) = self.bounds_cache.get(&key) + && *r == rev + { + return *b; + } + let canvas = self.session.active().map_or_else(|| surface.content_bounds(), |st| st.doc.bounds()); + let b = photocraft_compose::soft_shape_frame(sh, surface.format(), canvas).unwrap_or(photocraft_geom::Rect::EMPTY); + if self.bounds_cache.len() > 256 { + self.bounds_cache.clear(); + } + self.bounds_cache.insert(key, (rev, b)); + b + } + _ => self.cached_bounds(layer.id.0, surface), + } + } +} + +impl PhotocraftApp { + /// Channels panel thumbnails of the active document snapshot: the composite, + /// each colour channel (when there is more than one), each alpha channel, then the Quick Mask. + pub fn channel_thumbs(&mut self, ctx: &egui::Context) -> Vec { + let Some(st) = self.session.active() else { + self.channel_thumbs = None; + return Vec::new(); + }; + let (id, doc) = (st.doc.id, st.doc.clone()); + // View-only commands bump revision without changing pixels. Keeping a Weak pins allocation + // identity against address reuse without retaining the document's pixel data. + let snapshot = std::sync::Arc::downgrade(&doc); + let show_color = self.session.prefs().interface.show_channels_in_color; + // A step that changes only the selection (a marquee, Deselect) makes a new snapshot with + // the same pixels: keep the thumbnails, a full composite at 56 px costs ~0.7 s on a + // layered 20 MP document (#4518). + let current = match &mut self.channel_thumbs { + Some((d, old, in_color, _)) if *d == id && *in_color == show_color => { + let same = old.ptr_eq(&snapshot) || old.upgrade().is_some_and(|prev| same_but_selection(&prev, &doc)); + if same { + *old = snapshot.clone(); + } + same + } + _ => false, + }; + if !current { + let comp = photocraft_compose::thumbnail(&doc, 56); + let (w, h) = (comp.width as usize, comp.height as usize); + let side = w.max(h); + let make = |f: &dyn Fn(&[u8]) -> egui::Color32, name: &str| { + let mut px = vec![egui::Color32::TRANSPARENT; side * side]; + let (ox, oy) = ((side - w) / 2, (side - h) / 2); + for y in 0..h { + for x in 0..w { + let o = (y * w + x) * 4; + px[(y + oy) * side + x + ox] = f(&comp.pixels[o..o + 4]); + } + } + (format!("chan-{name}"), egui::ColorImage::new([side, side], px)) + }; + let fmt = doc.pixel_format(); + let colors = fmt.mode.color_channels(); + let mut texs = vec![make(&|p| egui::Color32::from_rgb(p[0], p[1], p[2]), "composite")]; + if colors > 1 { + for k in 0..colors { + let cmyk = fmt.mode == photocraft_doc::ColorMode::Cmyk; + texs.push(make( + &|p| { + let rgba = [p[0], p[1], p[2], 255].map(|v| f32::from(v) / 255.0); + let x = photocraft_raster::from_rgba(&fmt, rgba)[k]; + let g = if cmyk { 1.0 - x } else { x }; + let byte = (g.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + channel_tint(fmt.mode, k, byte, show_color) + }, + &format!("c{k}"), + )); + } + } + // Alpha channels and the Quick Mask, sampled at thumbnail resolution. + let (dw, dh) = (doc.size.width.max(1) as f32, doc.size.height.max(1) as f32); + for (i, ch) in doc.channels.iter().chain(doc.quick_mask.as_ref()).enumerate() { + let mut px = vec![egui::Color32::TRANSPARENT; side * side]; + let (ox, oy) = ((side - w) / 2, (side - h) / 2); + for y in 0..h { + for x in 0..w { + let sx = ((x as f32 + 0.5) * dw / w as f32) as i32; + let sy = ((y as f32 + 0.5) * dh / h as f32) as i32; + let v = ch.surface.sample_channel(sx, sy, 0); + px[(y + oy) * side + x + ox] = egui::Color32::from_gray((v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + } + } + texs.push((format!("chan-a{i}"), egui::ColorImage::new([side, side], px))); + } + // Update the textures already uploaded rather than allocating new ones. + let mut handles = match self.channel_thumbs.take() { + Some((d, _, _, h)) if d == id => h, + _ => Vec::new(), + }; + handles.truncate(texs.len()); + for (i, (name, image)) in texs.into_iter().enumerate() { + match handles.get_mut(i) { + Some(h) => h.set(image, egui::TextureOptions::LINEAR), + None => handles.push(ctx.load_texture(name, image, egui::TextureOptions::LINEAR)), + } + } + self.channel_thumbs = Some((id, snapshot, show_color, handles)); + } + self.channel_thumbs.as_ref().map(|(_, _, _, t)| t.iter().map(|t| t.id()).collect()).unwrap_or_default() + } +} + +/// Whether `new` differs from `old` at most in its selection, so every composite and channel +/// thumbnail of it is unchanged. Tiles compare by pointer first, so this costs little. +fn same_but_selection(old: &Document, new: &Document) -> bool { + if old.selection == new.selection { + return old == new; + } + let mut o = old.clone(); + o.selection = new.selection.clone(); + o == *new +} + +/// A channel thumbnail pixel whose lightness is `byte` (255 = white: full light, no ink). +/// Preferences ▸ Interface ▸ Show Channels in Color tints RGB channels from black to their +/// primary and CMYK channels from white to their ink, as Photoshop does; otherwise grey. +fn channel_tint(mode: photocraft_doc::ColorMode, k: usize, byte: u8, in_color: bool) -> egui::Color32 { + use photocraft_doc::ColorMode::{Cmyk, Rgb}; + if !in_color { + return egui::Color32::from_gray(byte); + } + match (mode, k) { + (Rgb, 0) => egui::Color32::from_rgb(byte, 0, 0), + (Rgb, 1) => egui::Color32::from_rgb(0, byte, 0), + (Rgb, 2) => egui::Color32::from_rgb(0, 0, byte), + (Cmyk, 0) => egui::Color32::from_rgb(byte, 255, 255), + (Cmyk, 1) => egui::Color32::from_rgb(255, byte, 255), + (Cmyk, 2) => egui::Color32::from_rgb(255, 255, byte), + _ => egui::Color32::from_gray(byte), + } +} + +#[cfg(test)] +mod channel_tint_tests { + use super::channel_tint; + use egui::Color32; + use photocraft_doc::ColorMode::{Cmyk, Grayscale, Rgb}; + + #[test] + fn channels_in_color_tint_rgb_from_black_and_cmyk_inks_from_white() { + assert_eq!(channel_tint(Rgb, 0, 255, true), Color32::from_rgb(255, 0, 0)); + assert_eq!(channel_tint(Rgb, 2, 0, true), Color32::BLACK); + // CMYK: no ink is white, full ink is the ink's colour. + assert_eq!(channel_tint(Cmyk, 0, 255, true), Color32::WHITE); + assert_eq!(channel_tint(Cmyk, 0, 0, true), Color32::from_rgb(0, 255, 255)); + assert_eq!(channel_tint(Cmyk, 1, 0, true), Color32::from_rgb(255, 0, 255)); + assert_eq!(channel_tint(Cmyk, 2, 0, true), Color32::from_rgb(255, 255, 0)); + assert_eq!(channel_tint(Cmyk, 3, 0, true), Color32::BLACK); + assert_eq!(channel_tint(Grayscale, 0, 77, true), Color32::from_gray(77)); + assert_eq!(channel_tint(Rgb, 0, 77, false), Color32::from_gray(77)); + } +} diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs new file mode 100644 index 0000000000..1505677b94 --- /dev/null +++ b/crates/ui-egui/src/app/view.rs @@ -0,0 +1,21 @@ +use super::*; + +impl PhotocraftApp { + /// Zoom of the active document's main view: screen (device) pixels per document pixel, the + /// user-facing factor (`100%` is `1.0`). + pub fn current_zoom(&self) -> f32 { + self.session.active_index().and_then(|i| self.ui.views.get(i)).map_or(1.0, |v| v.zoom) + } + + /// Screen (device) pixels per egui point of the canvas (`ctx.pixels_per_point`), as of the + /// last canvas frame. `1.0` before the first frame. + pub fn canvas_ppp(&self) -> f32 { + if self.ppp.is_finite() && self.ppp > 0.0 { self.ppp } else { 1.0 } + } + + /// The active view's zoom in egui points per document pixel: the unit every screen-space + /// distance, tolerance and texture-level choice on the canvas is measured in. + pub fn point_zoom(&self) -> f32 { + self.current_zoom() / self.canvas_ppp() + } +} diff --git a/crates/ui-egui/src/app/window.rs b/crates/ui-egui/src/app/window.rs new file mode 100644 index 0000000000..0379f77d20 --- /dev/null +++ b/crates/ui-egui/src/app/window.rs @@ -0,0 +1,11 @@ +use super::*; + +impl PhotocraftApp { + /// Whether the title bar's free gap gets the drag overlay this frame: the app draws its title + /// strip (`chrome`: not hidden by the screen mode) and a dialog's modal layer covers it. Not + /// only with the custom title bar: on macOS the strip under the traffic lights is the window's + /// title bar too, and an open dialog (Embedded Profile Mismatch…) left it undraggable (#5826). + pub(crate) fn titlebar_modal_drag(&self, chrome: bool) -> bool { + chrome && self.ui.panels.menu_bar && !self.ui.dialogs.is_empty() + } +} From 8829b5eb072bbd2a541820c1862258a69f1fc2cf Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:58:55 +0000 Subject: [PATCH 214/259] refactor(ui-egui): move app.rs clipboard_tests to app/clipboard_tests.rs --- crates/ui-egui/src/app.rs | 465 +--------------------- crates/ui-egui/src/app/clipboard_tests.rs | 460 +++++++++++++++++++++ 2 files changed, 462 insertions(+), 463 deletions(-) create mode 100644 crates/ui-egui/src/app/clipboard_tests.rs diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 0dd8f9adc0..2ce599e30e 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -19,9 +19,9 @@ mod window; pub(crate) use files::remember_new_document; pub(crate) use input::read_dropped; pub(crate) use targets::adjustment_layer_active; -pub use thumbs::surface_fingerprint; #[cfg(test)] pub(crate) use thumbs::layer_thumb_frame; +pub use thumbs::surface_fingerprint; impl PhotocraftApp { pub fn new(mut session: Session, mut services: Services) -> Self { @@ -261,465 +261,4 @@ impl eframe::App for PhotocraftApp { } #[cfg(test)] -mod clipboard_tests { - use super::*; - use std::sync::{Arc, Mutex}; - - #[test] - fn os_clipboard_bridge() { - let os: OsClip = Arc::default(); - let (a, b) = (os.clone(), os.clone()); - let services = Services { - clipboard_set_image: Some(Box::new(move |w: u32, h: u32, px: &[u8]| { - *a.lock().unwrap() = Some((w, h, px.to_vec())); - Ok(()) - })), - clipboard_get_image: Some(Box::new(move || Ok(b.lock().unwrap().clone()))), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - app.session.execute("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app.run("select.rect", serde_json::json!({"x": 0, "y": 0, "width": 8, "height": 4})).unwrap(); - app.run("edit.copy", serde_json::json!({})).unwrap(); - let (w, h, px) = os.lock().unwrap().clone().unwrap(); - assert_eq!((w, h, px.len()), (8, 4, 8 * 4 * 4)); - // Our own image comes back unchanged (no re-import, keeps the original position). - assert!(!app.import_os_clipboard().unwrap()); - // Text copied elsewhere replaces our image: nothing to paste, not the stale image. - let ours = os.lock().unwrap().take(); - assert!(!app.import_os_clipboard().unwrap()); - assert!(app.session.clipboard.is_none()); - *os.lock().unwrap() = ours; - app.run("edit.copy", serde_json::json!({})).unwrap(); - // Another app puts a 3×2 red image on the clipboard: ⌘V pastes it. - *os.lock().unwrap() = Some((3, 2, [255u8, 0, 0, 255].repeat(6))); - app.run("edit.paste", serde_json::json!({})).unwrap(); - let st = app.session.active().unwrap(); - let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); - assert_eq!(surf.content_bounds().width(), 3); - } - - #[test] - fn os_clipboard_honours_export_clipboard_preference() { - let os: OsClip = Arc::default(); - let a = os.clone(); - let services = Services { - clipboard_set_image: Some(Box::new(move |w: u32, h: u32, px: &[u8]| { - *a.lock().unwrap() = Some((w, h, px.to_vec())); - Ok(()) - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - app.session.execute("prefs.set", serde_json::json!({"values": {"general.exportClipboard": false}})).unwrap(); - app.session.execute("file.new", serde_json::json!({"width": 32, "height": 32})).unwrap(); - app.sync_views(); - app.run("select.rect", serde_json::json!({"x": 0, "y": 0, "width": 8, "height": 4})).unwrap(); - app.run("edit.copy", serde_json::json!({})).unwrap(); - assert!(os.lock().unwrap().is_none(), "copy does not mirror to OS clipboard when export_clipboard is off"); - } - - type OsClip = Arc)>>>; - - #[test] - fn failed_clipboard_reads_preserve_editable_contents_until_retry() { - use std::sync::atomic::{AtomicBool, Ordering}; - for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace", "file.newFromClipboard"] { - let os = OsClip::default(); - let busy = Arc::new(AtomicBool::new(false)); - let (write, read, unavailable) = (os.clone(), os.clone(), busy.clone()); - let services = Services { - clipboard_set_image: Some(Box::new(move |w, h, bytes| { - *write.lock().unwrap() = Some((w, h, bytes.to_vec())); - Ok(()) - })), - clipboard_get_image: Some(Box::new(move || { - if unavailable.load(Ordering::SeqCst) { Err("clipboard is busy".into()) } else { Ok(read.lock().unwrap().clone()) } - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); - app.run("shape.create", serde_json::json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); - app.run("edit.copy", serde_json::json!({})).unwrap(); - app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); - let signature = app.os_clip_sig; - assert!(signature.is_some()); - let before = app.session.active().unwrap().doc.walk().len(); - busy.store(true, Ordering::SeqCst); - let result = crate::menus::invoke(&mut app, &egui::Context::default(), id, serde_json::json!({})); - assert_eq!(result.unwrap_err(), "clipboard is busy", "{id}"); - assert!(app.ui.status_error); - assert_eq!(app.session.documents().len(), 2); - assert_eq!(app.session.active().unwrap().doc.walk().len(), before); - assert_eq!(app.os_clip_sig, signature); - assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); - // The New dialog also reads the clipboard; a failed preset probe must preserve it. - app.new_document_fields(); - assert_eq!(app.os_clip_sig, signature); - assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); - // An automation error must not leave script events disabled by the dispatch guard. - app.automation_input = true; - app.session.edit_prefs(|prefs| prefs.script_events.enabled = true); - assert!(app.run(id, serde_json::json!({})).is_err()); - assert!(app.session.prefs().script_events.enabled); - app.automation_input = false; - busy.store(false, Ordering::SeqCst); - app.run("edit.pasteSpecial.pasteInPlace", serde_json::json!({})).unwrap(); - let state = app.session.active().unwrap(); - assert!(matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Shape(_))); - assert!(!app.ui.status_error); - } - } - - #[test] - fn internal_only_clipboard_remains_usable_when_native_access_fails() { - use std::sync::atomic::{AtomicBool, Ordering}; - for export in [true, false] { - for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace", "file.newFromClipboard"] { - let os = OsClip::default(); - let unavailable = Arc::new(AtomicBool::new(true)); - let (read, failed) = (os.clone(), unavailable.clone()); - let services = Services { - clipboard_set_image: Some(Box::new(|_, _, _| Err("clipboard unavailable".into()))), - clipboard_get_image: Some(Box::new(move || { - if failed.load(Ordering::SeqCst) { Err("clipboard unavailable".into()) } else { Ok(read.lock().unwrap().clone()) } - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - app.session.edit_prefs(|prefs| prefs.general.export_clipboard = export); - app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); - app.run("shape.create", serde_json::json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); - app.run("edit.copy", serde_json::json!({})).unwrap(); - app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); - assert!(app.os_clip_sig.is_none() && !app.clip_external); - let bounds = app.session.clipboard.as_ref().unwrap().bounds; - assert_eq!(app.new_document_fields()["__preset"], "Clipboard"); - crate::menus::invoke(&mut app, &egui::Context::default(), id, serde_json::json!({})).unwrap(); - assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); - assert!(!app.ui.status_error); - if id == "file.newFromClipboard" { - assert_eq!(app.session.documents().len(), 3); - let doc = &app.session.active().unwrap().doc; - assert_eq!((doc.size.width, doc.size.height), (bounds.width(), bounds.height())); - } else { - assert_eq!(app.session.documents().len(), 2); - let state = app.session.active().unwrap(); - assert!(matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Shape(_))); - } - app.run("edit.purge.clipboard", serde_json::json!({})).unwrap(); - assert!(app.session.clipboard.is_none()); - assert!(app.run("edit.paste", serde_json::json!({})).is_err(), "purged content must not be a fallback"); - // The fallback is only for failed reads: a later successful external image wins. - *os.lock().unwrap() = Some((3, 2, [0u8, 0, 255, 255].repeat(6))); - unavailable.store(false, Ordering::SeqCst); - app.run("edit.paste", serde_json::json!({})).unwrap(); - assert!(app.clip_external && app.os_clip_sig.is_some()); - let clip = app.session.clipboard.as_ref().unwrap(); - assert!(clip.layers.is_none()); - assert_eq!((clip.bounds.width(), clip.bounds.height()), (3, 2)); - } - } - } - - #[test] - fn newer_unexported_copies_do_not_track_an_older_os_signature() { - use std::sync::atomic::{AtomicBool, Ordering}; - for imported in [true, false] { - for disable_export in [true, false] { - for copy_id in ["edit.copy", "edit.cut", "edit.copyMerged"] { - let os = OsClip::default(); - let write_fails = Arc::new(AtomicBool::new(false)); - let read_fails = Arc::new(AtomicBool::new(false)); - let (write, read, failed_write, failed_read) = (os.clone(), os.clone(), write_fails.clone(), read_fails.clone()); - let services = Services { - clipboard_set_image: Some(Box::new(move |w, h, bytes| { - if failed_write.load(Ordering::SeqCst) { - return Err("clipboard unavailable".into()); - } - *write.lock().unwrap() = Some((w, h, bytes.to_vec())); - Ok(()) - })), - clipboard_get_image: Some(Box::new(move || { - if failed_read.load(Ordering::SeqCst) { Err("clipboard unavailable".into()) } else { Ok(read.lock().unwrap().clone()) } - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - app.run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); - if imported { - *os.lock().unwrap() = Some((2, 2, [255u8, 0, 0, 255].repeat(4))); - assert!(app.import_os_clipboard().unwrap()); - } else { - app.run("edit.fill", serde_json::json!({"color": "#ff0000"})).unwrap(); - app.run("edit.copy", serde_json::json!({})).unwrap(); - } - let old_signature = app.os_clip_sig; - assert!(old_signature.is_some() && !app.clip_unmirrored); - app.run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); - app.run("edit.fill", serde_json::json!({"color": "#0000ff"})).unwrap(); - write_fails.store(true, Ordering::SeqCst); - app.session.edit_prefs(|prefs| prefs.general.export_clipboard = !disable_export); - app.run(copy_id, serde_json::json!({})).unwrap(); - let copied = app.session.clipboard.clone().unwrap(); - assert!(app.clip_unmirrored && !app.clip_external); - assert_eq!(app.os_clip_sig, old_signature); - assert_eq!(copied.surface.rgba(0, 0), [0.0, 0.0, 1.0, 1.0]); - // An old successful export/import must not block the newer internal copy. - read_fails.store(true, Ordering::SeqCst); - app.run("edit.pasteSpecial.pasteInPlace", serde_json::json!({})).unwrap(); - assert_eq!(app.os_clip_sig, old_signature); - assert!(app.clip_unmirrored && !app.clip_external); - read_fails.store(false, Ordering::SeqCst); - assert!(!app.import_os_clipboard().unwrap(), "unchanged old OS image must not overwrite the newer copy"); - assert_eq!(app.session.clipboard.as_ref().unwrap().surface.rgba(0, 0), copied.surface.rgba(0, 0)); - *os.lock().unwrap() = None; - assert!(!app.import_os_clipboard().unwrap(), "empty OS clipboard must not discard an unexported copy"); - assert!(app.os_clip_sig.is_none() && app.clip_unmirrored); - assert_eq!(app.session.clipboard.as_ref().unwrap().surface.rgba(0, 0), copied.surface.rgba(0, 0)); - // A different external image supersedes the internal copy and disables fallback. - *os.lock().unwrap() = Some((3, 2, [0u8, 255, 0, 255].repeat(6))); - assert!(app.import_os_clipboard().unwrap()); - assert!(app.clip_external && !app.clip_unmirrored); - let clip = app.session.clipboard.as_ref().unwrap(); - assert_eq!((clip.bounds.width(), clip.bounds.height()), (3, 2)); - read_fails.store(true, Ordering::SeqCst); - assert!(app.run("edit.paste", serde_json::json!({})).is_err()); - } - } - } - } - - #[test] - fn failed_clipboard_reads_do_not_paste_an_external_or_missing_copy() { - use std::sync::atomic::{AtomicBool, Ordering}; - for external in [true, false] { - let unavailable = Arc::new(AtomicBool::new(false)); - let failed = unavailable.clone(); - let services = Services { - clipboard_get_image: Some(Box::new(move || { - if failed.load(Ordering::SeqCst) { Err("clipboard unavailable".into()) } else { Ok(Some((3, 2, [255u8, 0, 0, 255].repeat(6)))) } - })), - ..Default::default() - }; - let mut app = PhotocraftApp::new(Session::new(), services); - app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); - if external { - assert!(app.import_os_clipboard().unwrap()); - } - let signature = app.os_clip_sig; - let before = app.session.active().unwrap().doc.walk().len(); - unavailable.store(true, Ordering::SeqCst); - for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace", "file.newFromClipboard"] { - let result = crate::menus::invoke(&mut app, &egui::Context::default(), id, serde_json::json!({})); - assert_eq!(result.unwrap_err(), "clipboard unavailable", "{id}"); - assert!(app.ui.status_error); - assert_eq!(app.session.documents().len(), 1); - assert_eq!(app.session.active().unwrap().doc.walk().len(), before); - assert_eq!(app.os_clip_sig, signature); - assert_eq!(app.session.clipboard.is_some(), external); - assert_eq!(app.clip_external, external); - } - } - } - - /// An app whose OS clipboard is `os`, counting every read in `reads`. - fn app_with_os_clipboard(os: &OsClip, reads: &Arc) -> PhotocraftApp { - let (b, n) = (os.clone(), reads.clone()); - let get = move || { - n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(b.lock().unwrap().clone()) - }; - let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(Box::new(get)), ..Default::default() }); - app.session.execute("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); - app.sync_views(); - app - } - - /// Paste is enabled from the clipboard service alone (no read); the explicit paste imports - /// the OS image, once, and centres it in the view like Photoshop does for foreign clipboard - /// content. - #[test] - fn external_clipboard_enables_and_centres_paste() { - let (os, reads) = (OsClip::default(), Arc::default()); - let mut app = app_with_os_clipboard(&os, &reads); - *os.lock().unwrap() = Some((4, 4, [255u8, 0, 0, 255].repeat(16))); - assert!(app.session.clipboard.is_none()); - assert!(crate::menus::is_enabled(&app, "edit.paste")); - assert!(crate::menus::is_enabled(&app, "edit.pasteSpecial.pasteInPlace")); - assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 0, "enablement never reads the clipboard"); - app.ui.views[0].center = [40.0, 20.0]; - let r = crate::menus::invoke(&mut app, &egui::Context::default(), "edit.paste", serde_json::json!({})).unwrap(); - assert_eq!(r["offset"], serde_json::json!([38, 18]), "external image is centred in the view: {r}"); - assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 1, "one read per explicit paste"); - // Without a clipboard service Paste greys until something is copied in the app. - let mut plain = PhotocraftApp::new(Session::new(), Services::default()); - plain.session.execute("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); - assert!(!crate::menus::is_enabled(&plain, "edit.paste")); - } - - /// #368: an image copied in another app opens as a document of its own, from File › New - /// from Clipboard or from Paste with nothing open. - #[test] - fn os_clipboard_image_becomes_a_new_document() { - let (os, reads) = (OsClip::default(), Arc::new(std::sync::atomic::AtomicUsize::new(0))); - let (b, n) = (os.clone(), Arc::clone(&reads)); - let get = move || { - n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(b.lock().unwrap().clone()) - }; - let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(Box::new(get)), ..Default::default() }); - let ctx = egui::Context::default(); - // Listed right after File › New…, enabled without reading the clipboard. - let items = crate::menus::menu_items(&app); - let at = items.iter().position(|i| i.id == "file.new").unwrap(); - assert_eq!(items[at + 1].id, "file.newFromClipboard"); - assert!(items[at + 1].enabled && crate::menus::is_enabled(&app, "edit.paste")); - assert!(!crate::menus::is_enabled(&app, "edit.pasteSpecial.pasteInPlace"), "Paste in Place needs a document"); - assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 0); - // An empty clipboard is a quiet no-op. - let r = crate::menus::invoke(&mut app, &ctx, "file.newFromClipboard", serde_json::json!({})).unwrap(); - assert_eq!(r["pasted"], serde_json::json!(false)); - assert!(app.session.documents().is_empty() && !app.ui.status_error); - // Paste with nothing open makes the document. - *os.lock().unwrap() = Some((5, 3, [0u8, 0, 255, 255].repeat(15))); - crate::menus::invoke(&mut app, &ctx, "edit.paste", serde_json::json!({})).unwrap(); - let d = &app.session.active().unwrap().doc; - assert_eq!((d.size.width, d.size.height, d.layers.len()), (5, 3, 1)); - assert_eq!(app.ui.views.len(), 1, "the new document has a view"); - assert!(app.has_unsaved_work(), "closing after Paste must ask to save"); - // New from Clipboard with a document open adds another. - crate::menus::invoke(&mut app, &ctx, "file.newFromClipboard", serde_json::json!({})).unwrap(); - assert_eq!(app.session.documents().len(), 2); - assert!(app.session.documents().iter().all(|d| d.is_dirty())); - assert!(crate::discard_ui::intercept(&mut app, "file.close", &serde_json::json!({})), "Close must ask before discarding clipboard pixels"); - } - - #[test] - fn pasting_an_empty_or_non_image_os_clipboard_is_a_quiet_no_op() { - let (os, reads) = (OsClip::default(), Arc::default()); - let mut app = app_with_os_clipboard(&os, &reads); - let layers = app.session.active().unwrap().doc.layers.len(); - let r = crate::menus::invoke(&mut app, &egui::Context::default(), "edit.paste", serde_json::json!({})).unwrap(); - assert_eq!(r["pasted"], serde_json::json!(false)); - assert_eq!(app.run("edit.pasteSpecial.pasteInPlace", serde_json::json!({})).unwrap()["pasted"], serde_json::json!(false)); - assert_eq!(app.session.active().unwrap().doc.layers.len(), layers); - assert!(!app.ui.status_error && !app.ui.status.is_empty()); - } - - #[test] - fn idle_frames_never_read_the_os_clipboard() { - let (os, reads) = (OsClip::default(), Arc::::default()); - *os.lock().unwrap() = Some((4, 4, [255u8, 0, 0, 255].repeat(16))); - let (b, n) = (os.clone(), reads.clone()); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(move |cc| { - PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); - let get = move || { - n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(b.lock().unwrap().clone()) - }; - let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(Box::new(get)), ..Default::default() }); - app.session.execute("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); - app - }); - for _ in 0..20 { - h.step(); - } - assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 0, "the OS clipboard is read only on an explicit paste"); - assert!(h.state().session.clipboard.is_none()); - } - - /// #2928: with the layer mask targeted, ⌘C copies the mask's values as grayscale, not the - /// layer's pixels — so ⌘V (targeting another layer's mask, #1035) moves the mask itself. - #[test] - fn copy_with_the_mask_targeted_copies_the_mask_not_the_pixels() { - let (os, reads) = (OsClip::default(), Arc::default()); - let mut app = app_with_os_clipboard(&os, &reads); - app.run("layer.new.layer", serde_json::json!({})).unwrap(); - app.run("layer.layerMask.hideAll", serde_json::json!({})).unwrap(); - // Black pixels, a white square in the mask: the copy must carry the mask. - app.run("select.all", serde_json::json!({})).unwrap(); - app.run("edit.fill", serde_json::json!({"color": "#000000"})).unwrap(); - app.run("select.rect", serde_json::json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); - app.run("edit.fill", serde_json::json!({"color": "#ffffff", "target": "mask"})).unwrap(); - app.run("select.deselect", serde_json::json!({})).unwrap(); - app.ui.mask_target = true; - crate::menus::invoke(&mut app, &egui::Context::default(), "edit.copy", serde_json::json!({})).unwrap(); - let clip = app.session.clipboard.clone().expect("the mask was copied"); - let st = app.session.active().unwrap(); - let (w, h) = (st.doc.size.width as i32, st.doc.size.height as i32); - assert_eq!( - [clip.bounds.x0, clip.bounds.y0, clip.bounds.width() as i32, clip.bounds.height() as i32], - [0, 0, w, h], - "the mask, whole — not the black pixels" - ); - let px = clip.surface.rgba(6, 6); - assert!(px[0] > 0.99 && px[3] > 0.99, "white mask values: {px:?}"); - assert!(clip.surface.rgba(20, 20)[0] < 0.01, "the hidden area copies as black"); - } - - /// #1035: with the layer mask targeted (its thumbnail clicked), ⌘V pastes the clipboard's - /// luminosity into the mask instead of making a layer. - #[test] - fn paste_with_the_mask_targeted_goes_into_the_mask() { - let (os, reads) = (OsClip::default(), Arc::default()); - let mut app = app_with_os_clipboard(&os, &reads); - app.run("layer.new.layer", serde_json::json!({})).unwrap(); - app.run("layer.layerMask.hideAll", serde_json::json!({})).unwrap(); - app.ui.mask_target = true; - app.ui.views[0].center = [32.0, 32.0]; - *os.lock().unwrap() = Some((4, 4, [128u8, 128, 128, 255].repeat(16))); - let layers = app.session.active().unwrap().doc.layer_count(); - crate::menus::invoke(&mut app, &egui::Context::default(), "edit.paste", serde_json::json!({})).unwrap(); - let st = app.session.active().unwrap(); - assert_eq!(st.doc.layer_count(), layers, "no new layer"); - let mask = st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap(); - assert!((mask.value(32, 32) - 128.0 / 255.0).abs() < 2.0 / 255.0, "the grey, centred in the view: {}", mask.value(32, 32)); - assert_eq!(mask.value(0, 0), 0.0, "the rest of the mask is unchanged"); - } - - /// #2166, measured in Photoshop 25.1: adding a layer mask targets it with white/black, and - /// the pixels and the mask each keep their own foreground/background pair. - #[test] - fn targeting_a_mask_swaps_to_its_own_colour_pair() { - use serde_json::json; - const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; - const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; - const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; - const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; - const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0]; - let mut app = PhotocraftApp::new(Session::new(), Services::default()); - app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); - let masked = app.run("layer.new.layer", json!({})).unwrap()["layer"].clone(); - app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); - let pair = |app: &PhotocraftApp| (app.session.tools.foreground, app.session.tools.background); - let target = |app: &mut PhotocraftApp, mask: bool| { - app.ui.mask_target = mask; - app.sync_views(); - }; - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - assert!(app.ui.mask_target, "the new mask is targeted"); - assert_eq!(pair(&app), (WHITE, BLACK)); - target(&mut app, false); - assert_eq!(pair(&app), (RED, BLUE), "the pixels get their colours back"); - target(&mut app, true); - assert_eq!(pair(&app), (WHITE, BLACK)); - target(&mut app, false); - app.run("tools.setColors", json!({"foreground": "#00ff00"})).unwrap(); - target(&mut app, true); - assert_eq!(pair(&app), (WHITE, BLACK)); - target(&mut app, false); - assert_eq!(pair(&app), (GREEN, BLUE)); - // A layer without a mask edits its pixels: their pair. - target(&mut app, true); - app.run("layer.new.layer", json!({})).unwrap(); - assert_eq!(pair(&app), (GREEN, BLUE)); - app.run("layer.select", json!({"layer": masked})).unwrap(); - target(&mut app, true); - assert_eq!(pair(&app), (WHITE, BLACK)); - app.run("layer.layerMask.delete", json!({})).unwrap(); - assert_eq!(pair(&app), (GREEN, BLUE), "deleting the targeted mask goes back to the pixels"); - } -} +mod clipboard_tests; diff --git a/crates/ui-egui/src/app/clipboard_tests.rs b/crates/ui-egui/src/app/clipboard_tests.rs new file mode 100644 index 0000000000..65318b174f --- /dev/null +++ b/crates/ui-egui/src/app/clipboard_tests.rs @@ -0,0 +1,460 @@ +use super::*; +use std::sync::{Arc, Mutex}; + +#[test] +fn os_clipboard_bridge() { + let os: OsClip = Arc::default(); + let (a, b) = (os.clone(), os.clone()); + let services = Services { + clipboard_set_image: Some(Box::new(move |w: u32, h: u32, px: &[u8]| { + *a.lock().unwrap() = Some((w, h, px.to_vec())); + Ok(()) + })), + clipboard_get_image: Some(Box::new(move || Ok(b.lock().unwrap().clone()))), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.session.execute("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.run("select.rect", serde_json::json!({"x": 0, "y": 0, "width": 8, "height": 4})).unwrap(); + app.run("edit.copy", serde_json::json!({})).unwrap(); + let (w, h, px) = os.lock().unwrap().clone().unwrap(); + assert_eq!((w, h, px.len()), (8, 4, 8 * 4 * 4)); + // Our own image comes back unchanged (no re-import, keeps the original position). + assert!(!app.import_os_clipboard().unwrap()); + // Text copied elsewhere replaces our image: nothing to paste, not the stale image. + let ours = os.lock().unwrap().take(); + assert!(!app.import_os_clipboard().unwrap()); + assert!(app.session.clipboard.is_none()); + *os.lock().unwrap() = ours; + app.run("edit.copy", serde_json::json!({})).unwrap(); + // Another app puts a 3×2 red image on the clipboard: ⌘V pastes it. + *os.lock().unwrap() = Some((3, 2, [255u8, 0, 0, 255].repeat(6))); + app.run("edit.paste", serde_json::json!({})).unwrap(); + let st = app.session.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + assert_eq!(surf.content_bounds().width(), 3); +} + +#[test] +fn os_clipboard_honours_export_clipboard_preference() { + let os: OsClip = Arc::default(); + let a = os.clone(); + let services = Services { + clipboard_set_image: Some(Box::new(move |w: u32, h: u32, px: &[u8]| { + *a.lock().unwrap() = Some((w, h, px.to_vec())); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.session.execute("prefs.set", serde_json::json!({"values": {"general.exportClipboard": false}})).unwrap(); + app.session.execute("file.new", serde_json::json!({"width": 32, "height": 32})).unwrap(); + app.sync_views(); + app.run("select.rect", serde_json::json!({"x": 0, "y": 0, "width": 8, "height": 4})).unwrap(); + app.run("edit.copy", serde_json::json!({})).unwrap(); + assert!(os.lock().unwrap().is_none(), "copy does not mirror to OS clipboard when export_clipboard is off"); +} + +type OsClip = Arc)>>>; + +#[test] +fn failed_clipboard_reads_preserve_editable_contents_until_retry() { + use std::sync::atomic::{AtomicBool, Ordering}; + for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace", "file.newFromClipboard"] { + let os = OsClip::default(); + let busy = Arc::new(AtomicBool::new(false)); + let (write, read, unavailable) = (os.clone(), os.clone(), busy.clone()); + let services = Services { + clipboard_set_image: Some(Box::new(move |w, h, bytes| { + *write.lock().unwrap() = Some((w, h, bytes.to_vec())); + Ok(()) + })), + clipboard_get_image: Some(Box::new(move || { + if unavailable.load(Ordering::SeqCst) { Err("clipboard is busy".into()) } else { Ok(read.lock().unwrap().clone()) } + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); + app.run("shape.create", serde_json::json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); + app.run("edit.copy", serde_json::json!({})).unwrap(); + app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); + let signature = app.os_clip_sig; + assert!(signature.is_some()); + let before = app.session.active().unwrap().doc.walk().len(); + busy.store(true, Ordering::SeqCst); + let result = crate::menus::invoke(&mut app, &egui::Context::default(), id, serde_json::json!({})); + assert_eq!(result.unwrap_err(), "clipboard is busy", "{id}"); + assert!(app.ui.status_error); + assert_eq!(app.session.documents().len(), 2); + assert_eq!(app.session.active().unwrap().doc.walk().len(), before); + assert_eq!(app.os_clip_sig, signature); + assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); + // The New dialog also reads the clipboard; a failed preset probe must preserve it. + app.new_document_fields(); + assert_eq!(app.os_clip_sig, signature); + assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); + // An automation error must not leave script events disabled by the dispatch guard. + app.automation_input = true; + app.session.edit_prefs(|prefs| prefs.script_events.enabled = true); + assert!(app.run(id, serde_json::json!({})).is_err()); + assert!(app.session.prefs().script_events.enabled); + app.automation_input = false; + busy.store(false, Ordering::SeqCst); + app.run("edit.pasteSpecial.pasteInPlace", serde_json::json!({})).unwrap(); + let state = app.session.active().unwrap(); + assert!(matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Shape(_))); + assert!(!app.ui.status_error); + } +} + +#[test] +fn internal_only_clipboard_remains_usable_when_native_access_fails() { + use std::sync::atomic::{AtomicBool, Ordering}; + for export in [true, false] { + for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace", "file.newFromClipboard"] { + let os = OsClip::default(); + let unavailable = Arc::new(AtomicBool::new(true)); + let (read, failed) = (os.clone(), unavailable.clone()); + let services = Services { + clipboard_set_image: Some(Box::new(|_, _, _| Err("clipboard unavailable".into()))), + clipboard_get_image: Some(Box::new(move || { + if failed.load(Ordering::SeqCst) { Err("clipboard unavailable".into()) } else { Ok(read.lock().unwrap().clone()) } + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.session.edit_prefs(|prefs| prefs.general.export_clipboard = export); + app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); + app.run("shape.create", serde_json::json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); + app.run("edit.copy", serde_json::json!({})).unwrap(); + app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); + assert!(app.os_clip_sig.is_none() && !app.clip_external); + let bounds = app.session.clipboard.as_ref().unwrap().bounds; + assert_eq!(app.new_document_fields()["__preset"], "Clipboard"); + crate::menus::invoke(&mut app, &egui::Context::default(), id, serde_json::json!({})).unwrap(); + assert!(app.session.clipboard.as_ref().unwrap().layers.is_some()); + assert!(!app.ui.status_error); + if id == "file.newFromClipboard" { + assert_eq!(app.session.documents().len(), 3); + let doc = &app.session.active().unwrap().doc; + assert_eq!((doc.size.width, doc.size.height), (bounds.width(), bounds.height())); + } else { + assert_eq!(app.session.documents().len(), 2); + let state = app.session.active().unwrap(); + assert!(matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Shape(_))); + } + app.run("edit.purge.clipboard", serde_json::json!({})).unwrap(); + assert!(app.session.clipboard.is_none()); + assert!(app.run("edit.paste", serde_json::json!({})).is_err(), "purged content must not be a fallback"); + // The fallback is only for failed reads: a later successful external image wins. + *os.lock().unwrap() = Some((3, 2, [0u8, 0, 255, 255].repeat(6))); + unavailable.store(false, Ordering::SeqCst); + app.run("edit.paste", serde_json::json!({})).unwrap(); + assert!(app.clip_external && app.os_clip_sig.is_some()); + let clip = app.session.clipboard.as_ref().unwrap(); + assert!(clip.layers.is_none()); + assert_eq!((clip.bounds.width(), clip.bounds.height()), (3, 2)); + } + } +} + +#[test] +fn newer_unexported_copies_do_not_track_an_older_os_signature() { + use std::sync::atomic::{AtomicBool, Ordering}; + for imported in [true, false] { + for disable_export in [true, false] { + for copy_id in ["edit.copy", "edit.cut", "edit.copyMerged"] { + let os = OsClip::default(); + let write_fails = Arc::new(AtomicBool::new(false)); + let read_fails = Arc::new(AtomicBool::new(false)); + let (write, read, failed_write, failed_read) = (os.clone(), os.clone(), write_fails.clone(), read_fails.clone()); + let services = Services { + clipboard_set_image: Some(Box::new(move |w, h, bytes| { + if failed_write.load(Ordering::SeqCst) { + return Err("clipboard unavailable".into()); + } + *write.lock().unwrap() = Some((w, h, bytes.to_vec())); + Ok(()) + })), + clipboard_get_image: Some(Box::new(move || { + if failed_read.load(Ordering::SeqCst) { Err("clipboard unavailable".into()) } else { Ok(read.lock().unwrap().clone()) } + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); + if imported { + *os.lock().unwrap() = Some((2, 2, [255u8, 0, 0, 255].repeat(4))); + assert!(app.import_os_clipboard().unwrap()); + } else { + app.run("edit.fill", serde_json::json!({"color": "#ff0000"})).unwrap(); + app.run("edit.copy", serde_json::json!({})).unwrap(); + } + let old_signature = app.os_clip_sig; + assert!(old_signature.is_some() && !app.clip_unmirrored); + app.run("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); + app.run("edit.fill", serde_json::json!({"color": "#0000ff"})).unwrap(); + write_fails.store(true, Ordering::SeqCst); + app.session.edit_prefs(|prefs| prefs.general.export_clipboard = !disable_export); + app.run(copy_id, serde_json::json!({})).unwrap(); + let copied = app.session.clipboard.clone().unwrap(); + assert!(app.clip_unmirrored && !app.clip_external); + assert_eq!(app.os_clip_sig, old_signature); + assert_eq!(copied.surface.rgba(0, 0), [0.0, 0.0, 1.0, 1.0]); + // An old successful export/import must not block the newer internal copy. + read_fails.store(true, Ordering::SeqCst); + app.run("edit.pasteSpecial.pasteInPlace", serde_json::json!({})).unwrap(); + assert_eq!(app.os_clip_sig, old_signature); + assert!(app.clip_unmirrored && !app.clip_external); + read_fails.store(false, Ordering::SeqCst); + assert!(!app.import_os_clipboard().unwrap(), "unchanged old OS image must not overwrite the newer copy"); + assert_eq!(app.session.clipboard.as_ref().unwrap().surface.rgba(0, 0), copied.surface.rgba(0, 0)); + *os.lock().unwrap() = None; + assert!(!app.import_os_clipboard().unwrap(), "empty OS clipboard must not discard an unexported copy"); + assert!(app.os_clip_sig.is_none() && app.clip_unmirrored); + assert_eq!(app.session.clipboard.as_ref().unwrap().surface.rgba(0, 0), copied.surface.rgba(0, 0)); + // A different external image supersedes the internal copy and disables fallback. + *os.lock().unwrap() = Some((3, 2, [0u8, 255, 0, 255].repeat(6))); + assert!(app.import_os_clipboard().unwrap()); + assert!(app.clip_external && !app.clip_unmirrored); + let clip = app.session.clipboard.as_ref().unwrap(); + assert_eq!((clip.bounds.width(), clip.bounds.height()), (3, 2)); + read_fails.store(true, Ordering::SeqCst); + assert!(app.run("edit.paste", serde_json::json!({})).is_err()); + } + } + } +} + +#[test] +fn failed_clipboard_reads_do_not_paste_an_external_or_missing_copy() { + use std::sync::atomic::{AtomicBool, Ordering}; + for external in [true, false] { + let unavailable = Arc::new(AtomicBool::new(false)); + let failed = unavailable.clone(); + let services = Services { + clipboard_get_image: Some(Box::new(move || { + if failed.load(Ordering::SeqCst) { Err("clipboard unavailable".into()) } else { Ok(Some((3, 2, [255u8, 0, 0, 255].repeat(6)))) } + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.run("file.new", serde_json::json!({"width": 80, "height": 60})).unwrap(); + if external { + assert!(app.import_os_clipboard().unwrap()); + } + let signature = app.os_clip_sig; + let before = app.session.active().unwrap().doc.walk().len(); + unavailable.store(true, Ordering::SeqCst); + for id in ["edit.paste", "edit.pasteSpecial.pasteInPlace", "file.newFromClipboard"] { + let result = crate::menus::invoke(&mut app, &egui::Context::default(), id, serde_json::json!({})); + assert_eq!(result.unwrap_err(), "clipboard unavailable", "{id}"); + assert!(app.ui.status_error); + assert_eq!(app.session.documents().len(), 1); + assert_eq!(app.session.active().unwrap().doc.walk().len(), before); + assert_eq!(app.os_clip_sig, signature); + assert_eq!(app.session.clipboard.is_some(), external); + assert_eq!(app.clip_external, external); + } + } +} + +/// An app whose OS clipboard is `os`, counting every read in `reads`. +fn app_with_os_clipboard(os: &OsClip, reads: &Arc) -> PhotocraftApp { + let (b, n) = (os.clone(), reads.clone()); + let get = move || { + n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(b.lock().unwrap().clone()) + }; + let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(Box::new(get)), ..Default::default() }); + app.session.execute("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app +} + +/// Paste is enabled from the clipboard service alone (no read); the explicit paste imports +/// the OS image, once, and centres it in the view like Photoshop does for foreign clipboard +/// content. +#[test] +fn external_clipboard_enables_and_centres_paste() { + let (os, reads) = (OsClip::default(), Arc::default()); + let mut app = app_with_os_clipboard(&os, &reads); + *os.lock().unwrap() = Some((4, 4, [255u8, 0, 0, 255].repeat(16))); + assert!(app.session.clipboard.is_none()); + assert!(crate::menus::is_enabled(&app, "edit.paste")); + assert!(crate::menus::is_enabled(&app, "edit.pasteSpecial.pasteInPlace")); + assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 0, "enablement never reads the clipboard"); + app.ui.views[0].center = [40.0, 20.0]; + let r = crate::menus::invoke(&mut app, &egui::Context::default(), "edit.paste", serde_json::json!({})).unwrap(); + assert_eq!(r["offset"], serde_json::json!([38, 18]), "external image is centred in the view: {r}"); + assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 1, "one read per explicit paste"); + // Without a clipboard service Paste greys until something is copied in the app. + let mut plain = PhotocraftApp::new(Session::new(), Services::default()); + plain.session.execute("file.new", serde_json::json!({"width": 8, "height": 8})).unwrap(); + assert!(!crate::menus::is_enabled(&plain, "edit.paste")); +} + +/// #368: an image copied in another app opens as a document of its own, from File › New +/// from Clipboard or from Paste with nothing open. +#[test] +fn os_clipboard_image_becomes_a_new_document() { + let (os, reads) = (OsClip::default(), Arc::new(std::sync::atomic::AtomicUsize::new(0))); + let (b, n) = (os.clone(), Arc::clone(&reads)); + let get = move || { + n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(b.lock().unwrap().clone()) + }; + let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(Box::new(get)), ..Default::default() }); + let ctx = egui::Context::default(); + // Listed right after File › New…, enabled without reading the clipboard. + let items = crate::menus::menu_items(&app); + let at = items.iter().position(|i| i.id == "file.new").unwrap(); + assert_eq!(items[at + 1].id, "file.newFromClipboard"); + assert!(items[at + 1].enabled && crate::menus::is_enabled(&app, "edit.paste")); + assert!(!crate::menus::is_enabled(&app, "edit.pasteSpecial.pasteInPlace"), "Paste in Place needs a document"); + assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 0); + // An empty clipboard is a quiet no-op. + let r = crate::menus::invoke(&mut app, &ctx, "file.newFromClipboard", serde_json::json!({})).unwrap(); + assert_eq!(r["pasted"], serde_json::json!(false)); + assert!(app.session.documents().is_empty() && !app.ui.status_error); + // Paste with nothing open makes the document. + *os.lock().unwrap() = Some((5, 3, [0u8, 0, 255, 255].repeat(15))); + crate::menus::invoke(&mut app, &ctx, "edit.paste", serde_json::json!({})).unwrap(); + let d = &app.session.active().unwrap().doc; + assert_eq!((d.size.width, d.size.height, d.layers.len()), (5, 3, 1)); + assert_eq!(app.ui.views.len(), 1, "the new document has a view"); + assert!(app.has_unsaved_work(), "closing after Paste must ask to save"); + // New from Clipboard with a document open adds another. + crate::menus::invoke(&mut app, &ctx, "file.newFromClipboard", serde_json::json!({})).unwrap(); + assert_eq!(app.session.documents().len(), 2); + assert!(app.session.documents().iter().all(|d| d.is_dirty())); + assert!(crate::discard_ui::intercept(&mut app, "file.close", &serde_json::json!({})), "Close must ask before discarding clipboard pixels"); +} + +#[test] +fn pasting_an_empty_or_non_image_os_clipboard_is_a_quiet_no_op() { + let (os, reads) = (OsClip::default(), Arc::default()); + let mut app = app_with_os_clipboard(&os, &reads); + let layers = app.session.active().unwrap().doc.layers.len(); + let r = crate::menus::invoke(&mut app, &egui::Context::default(), "edit.paste", serde_json::json!({})).unwrap(); + assert_eq!(r["pasted"], serde_json::json!(false)); + assert_eq!(app.run("edit.pasteSpecial.pasteInPlace", serde_json::json!({})).unwrap()["pasted"], serde_json::json!(false)); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers); + assert!(!app.ui.status_error && !app.ui.status.is_empty()); +} + +#[test] +fn idle_frames_never_read_the_os_clipboard() { + let (os, reads) = (OsClip::default(), Arc::::default()); + *os.lock().unwrap() = Some((4, 4, [255u8, 0, 0, 255].repeat(16))); + let (b, n) = (os.clone(), reads.clone()); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let get = move || { + n.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(b.lock().unwrap().clone()) + }; + let mut app = PhotocraftApp::new(Session::new(), Services { clipboard_get_image: Some(Box::new(get)), ..Default::default() }); + app.session.execute("file.new", serde_json::json!({"width": 64, "height": 64})).unwrap(); + app + }); + for _ in 0..20 { + h.step(); + } + assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 0, "the OS clipboard is read only on an explicit paste"); + assert!(h.state().session.clipboard.is_none()); +} + +/// #2928: with the layer mask targeted, ⌘C copies the mask's values as grayscale, not the +/// layer's pixels — so ⌘V (targeting another layer's mask, #1035) moves the mask itself. +#[test] +fn copy_with_the_mask_targeted_copies_the_mask_not_the_pixels() { + let (os, reads) = (OsClip::default(), Arc::default()); + let mut app = app_with_os_clipboard(&os, &reads); + app.run("layer.new.layer", serde_json::json!({})).unwrap(); + app.run("layer.layerMask.hideAll", serde_json::json!({})).unwrap(); + // Black pixels, a white square in the mask: the copy must carry the mask. + app.run("select.all", serde_json::json!({})).unwrap(); + app.run("edit.fill", serde_json::json!({"color": "#000000"})).unwrap(); + app.run("select.rect", serde_json::json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); + app.run("edit.fill", serde_json::json!({"color": "#ffffff", "target": "mask"})).unwrap(); + app.run("select.deselect", serde_json::json!({})).unwrap(); + app.ui.mask_target = true; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.copy", serde_json::json!({})).unwrap(); + let clip = app.session.clipboard.clone().expect("the mask was copied"); + let st = app.session.active().unwrap(); + let (w, h) = (st.doc.size.width as i32, st.doc.size.height as i32); + assert_eq!( + [clip.bounds.x0, clip.bounds.y0, clip.bounds.width() as i32, clip.bounds.height() as i32], + [0, 0, w, h], + "the mask, whole — not the black pixels" + ); + let px = clip.surface.rgba(6, 6); + assert!(px[0] > 0.99 && px[3] > 0.99, "white mask values: {px:?}"); + assert!(clip.surface.rgba(20, 20)[0] < 0.01, "the hidden area copies as black"); +} + +/// #1035: with the layer mask targeted (its thumbnail clicked), ⌘V pastes the clipboard's +/// luminosity into the mask instead of making a layer. +#[test] +fn paste_with_the_mask_targeted_goes_into_the_mask() { + let (os, reads) = (OsClip::default(), Arc::default()); + let mut app = app_with_os_clipboard(&os, &reads); + app.run("layer.new.layer", serde_json::json!({})).unwrap(); + app.run("layer.layerMask.hideAll", serde_json::json!({})).unwrap(); + app.ui.mask_target = true; + app.ui.views[0].center = [32.0, 32.0]; + *os.lock().unwrap() = Some((4, 4, [128u8, 128, 128, 255].repeat(16))); + let layers = app.session.active().unwrap().doc.layer_count(); + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.paste", serde_json::json!({})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layer_count(), layers, "no new layer"); + let mask = st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap(); + assert!((mask.value(32, 32) - 128.0 / 255.0).abs() < 2.0 / 255.0, "the grey, centred in the view: {}", mask.value(32, 32)); + assert_eq!(mask.value(0, 0), 0.0, "the rest of the mask is unchanged"); +} + +/// #2166, measured in Photoshop 25.1: adding a layer mask targets it with white/black, and +/// the pixels and the mask each keep their own foreground/background pair. +#[test] +fn targeting_a_mask_swaps_to_its_own_colour_pair() { + use serde_json::json; + const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; + const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; + const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; + const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; + const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0]; + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + let masked = app.run("layer.new.layer", json!({})).unwrap()["layer"].clone(); + app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap(); + let pair = |app: &PhotocraftApp| (app.session.tools.foreground, app.session.tools.background); + let target = |app: &mut PhotocraftApp, mask: bool| { + app.ui.mask_target = mask; + app.sync_views(); + }; + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + assert!(app.ui.mask_target, "the new mask is targeted"); + assert_eq!(pair(&app), (WHITE, BLACK)); + target(&mut app, false); + assert_eq!(pair(&app), (RED, BLUE), "the pixels get their colours back"); + target(&mut app, true); + assert_eq!(pair(&app), (WHITE, BLACK)); + target(&mut app, false); + app.run("tools.setColors", json!({"foreground": "#00ff00"})).unwrap(); + target(&mut app, true); + assert_eq!(pair(&app), (WHITE, BLACK)); + target(&mut app, false); + assert_eq!(pair(&app), (GREEN, BLUE)); + // A layer without a mask edits its pixels: their pair. + target(&mut app, true); + app.run("layer.new.layer", json!({})).unwrap(); + assert_eq!(pair(&app), (GREEN, BLUE)); + app.run("layer.select", json!({"layer": masked})).unwrap(); + target(&mut app, true); + assert_eq!(pair(&app), (WHITE, BLACK)); + app.run("layer.layerMask.delete", json!({})).unwrap(); + assert_eq!(pair(&app), (GREEN, BLUE), "deleting the targeted mask goes back to the pixels"); +} From 8cc050b012a369799f25607b299ca94bbacea360 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:09:43 +0000 Subject: [PATCH 215/259] refactor(ui-egui): split panels.rs into panels/ --- crates/ui-egui/src/panels.rs | 4615 +------------------ crates/ui-egui/src/panels/brush_controls.rs | 128 + crates/ui-egui/src/panels/color.rs | 277 ++ crates/ui-egui/src/panels/dock.rs | 121 + crates/ui-egui/src/panels/history.rs | 326 ++ crates/ui-egui/src/panels/info.rs | 135 + crates/ui-egui/src/panels/layer_drag.rs | 367 ++ crates/ui-egui/src/panels/layer_row.rs | 458 ++ crates/ui-egui/src/panels/layers.rs | 580 +++ crates/ui-egui/src/panels/navigator.rs | 223 + crates/ui-egui/src/panels/options_bar.rs | 755 +++ crates/ui-egui/src/panels/panel_state.rs | 96 + crates/ui-egui/src/panels/properties.rs | 273 ++ crates/ui-egui/src/panels/status_bar.rs | 74 + crates/ui-egui/src/panels/title_bar.rs | 208 + crates/ui-egui/src/panels/toolbar.rs | 571 +++ 16 files changed, 4654 insertions(+), 4553 deletions(-) create mode 100644 crates/ui-egui/src/panels/brush_controls.rs create mode 100644 crates/ui-egui/src/panels/color.rs create mode 100644 crates/ui-egui/src/panels/dock.rs create mode 100644 crates/ui-egui/src/panels/history.rs create mode 100644 crates/ui-egui/src/panels/info.rs create mode 100644 crates/ui-egui/src/panels/layer_drag.rs create mode 100644 crates/ui-egui/src/panels/layer_row.rs create mode 100644 crates/ui-egui/src/panels/layers.rs create mode 100644 crates/ui-egui/src/panels/navigator.rs create mode 100644 crates/ui-egui/src/panels/options_bar.rs create mode 100644 crates/ui-egui/src/panels/panel_state.rs create mode 100644 crates/ui-egui/src/panels/properties.rs create mode 100644 crates/ui-egui/src/panels/status_bar.rs create mode 100644 crates/ui-egui/src/panels/title_bar.rs create mode 100644 crates/ui-egui/src/panels/toolbar.rs diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 9ffe7f5d4a..a4c556ce37 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -11,879 +11,74 @@ use crate::state::Tool; use crate::theme::{self, Tokens}; use crate::{PhotocraftApp, icons, widgets}; -// ----------------------------------------------------------------------------- panel state +mod brush_controls; +mod color; +mod dock; +mod history; +mod info; +mod layer_drag; +mod layer_row; +mod layers; +mod navigator; +mod options_bar; +mod panel_state; +mod properties; +mod status_bar; +mod title_bar; +mod toolbar; -/// The persisted [`egui::PanelState`] key for the panel named `salt` in this context's root UI. -/// -/// egui 0.37 derives a panel's id from its parent [`egui::Ui`]: -/// `panel_ui.scope_id().with_salt(salt)`. For the root Ui that is -/// `ctx.viewport_id().root_ui_id().with(salt)`, whereas 0.36 stored the same panels under -/// `Id::new(salt)` (`Id::unique(salt)` has the same hash). Use this in tests and migrations; never -/// substitute [`egui::Ui::unique_id`], which is unstable. -pub fn panel_state_id(ctx: &egui::Context, salt: impl egui::AsIdSalt) -> egui::Id { - ctx.viewport_id().root_ui_id().with(salt) -} - -/// The panels whose saved sizes moved to a parent-scoped key in 0.37. -const PANEL_STATE_KEYS: &[&str] = &["dock", "title_bar", "options_bar", "status_bar", "toolbar", "rail", "shared-panel-dock"]; - -/// What the two keys held when this build last looked at a panel, so a later startup can tell -/// which one a 0.36 rollback or a 0.37 session wrote last. -#[derive(Clone, Copy, serde::Serialize, serde::Deserialize)] -struct PanelStamp { - old: [f32; 4], - new: [f32; 4], -} - -fn rect_key(state: egui::containers::panel::PanelState) -> [f32; 4] { - let r = state.outer_rect; - [r.min.x, r.min.y, r.max.x, r.max.y] -} - -fn stamp_id(name: &str) -> egui::Id { - egui::Id::unique(format!("photocraft-panel-state-stamp:{name}")) -} - -/// Copy 0.36 `PanelState` entries to their 0.37 parent-scoped keys. -/// -/// The old `Id::unique(name)` entry is left in place so a 0.36 build still reads the same saved -/// widths. On a later startup, a stamp of both keys decides which one is newer: if a 0.36 build -/// resized the panel after the migration (the old key differs from the stamp, the new one does -/// not), the old key wins; a 0.37 resize (the new key differs) is kept. If both changed the order -/// is unknown; the new key is kept, so a 0.37 resize *after* a 0.36 rollback resize can still be -/// lost (documented in the plan's rollback section). Data-only: call it before any panel is shown. -pub fn migrate_panel_state(ctx: &egui::Context) { - use egui::containers::panel::PanelState; - let done = egui::Id::unique("photocraft-panel-state-migrated"); - if ctx.data(|d| d.get_temp::(done).unwrap_or(false)) { - return; - } - for name in PANEL_STATE_KEYS { - let old_id = egui::Id::unique(*name); - let new_id = panel_state_id(ctx, *name); - let id = stamp_id(name); - let old = PanelState::load(ctx, old_id); - let new = PanelState::load(ctx, new_id); - let stamp = ctx.data_mut(|d| d.get_persisted::(id)); - let Some(old) = old else { continue }; - let old_key = rect_key(old); - match (new, stamp) { - (None, _) => { - // First migration: copy, and remember what both keys held. - ctx.data_mut(|d| d.insert_persisted(new_id, old)); - ctx.data_mut(|d| d.insert_persisted(id, PanelStamp { old: old_key, new: old_key })); - } - (Some(new), None) => { - // A partial migration or a pre-existing 0.37 value: keep it and start stamping. - ctx.data_mut(|d| d.insert_persisted(id, PanelStamp { old: old_key, new: rect_key(new) })); - } - (Some(new), Some(stamp)) => { - let old_changed = old_key != stamp.old; - let new_changed = rect_key(new) != stamp.new; - if old_changed && !new_changed { - // A 0.36 rollback resized the panel after the migration: its key is newer. - ctx.data_mut(|d| d.insert_persisted(new_id, old)); - ctx.data_mut(|d| d.insert_persisted(id, PanelStamp { old: old_key, new: old_key })); - } else if new_changed { - ctx.data_mut(|d| d.insert_persisted(id, PanelStamp { old: old_key, new: rect_key(new) })); - } - } - } - } - ctx.data_mut(|d| d.insert_temp(done, true)); -} - -/// Remember the 0.37 panel sizes this session ends a pass with, so a later 0.36 rollback's newer -/// old-key values can be recognized. Cheap when nothing changed (no write). -pub fn remember_panel_state(ctx: &egui::Context) { - use egui::containers::panel::PanelState; - for name in PANEL_STATE_KEYS { - let Some(new) = PanelState::load(ctx, panel_state_id(ctx, *name)) else { continue }; - let id = stamp_id(name); - let Some(stamp) = ctx.data_mut(|d| d.get_persisted::(id)) else { continue }; - let new_key = rect_key(new); - if new_key != stamp.new { - ctx.data_mut(|d| d.insert_persisted(id, PanelStamp { old: stamp.old, new: new_key })); - } - } -} - -// ----------------------------------------------------------------------------- toolbar - -/// 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. -const TOOL_SECTIONS: &[&[&[Tool]]] = &[ - &[&[Tool::Move, Tool::Artboard]], - &[ - &[Tool::RectMarquee, Tool::EllipseMarquee, Tool::SingleRowMarquee, Tool::SingleColumnMarquee], - &[Tool::Lasso, Tool::PolygonLasso, Tool::MagneticLasso], - &[Tool::ObjectSelection, Tool::QuickSelection, Tool::MagicWand], - &[Tool::Crop, Tool::PerspectiveCrop, Tool::Slice, Tool::SliceSelect], - &[Tool::Frame], - &[Tool::Eyedropper, Tool::ColorSampler, Tool::Ruler, Tool::Note, Tool::Count], - ], - &[ - &[Tool::Remove, Tool::SpotHealing, Tool::Healing, Tool::Patch, Tool::ContentAwareMove, Tool::RedEye], - &[Tool::Brush, Tool::Pencil, Tool::MixerBrush, Tool::ColorReplacement], - &[Tool::CloneStamp, Tool::PatternStamp], - &[Tool::HistoryBrush, Tool::ArtHistoryBrush], - &[Tool::Eraser, Tool::BackgroundEraser, Tool::MagicEraser], - &[Tool::Gradient, Tool::PaintBucket], - &[Tool::Blur, Tool::Sharpen, Tool::Smudge], - &[Tool::Dodge, Tool::Burn, Tool::Sponge], - ], - &[ - &[Tool::Pen, Tool::FreeformPen, Tool::CurvaturePen, Tool::AddAnchorPoint, Tool::DeleteAnchorPoint, Tool::ConvertPoint], - &[Tool::Type, Tool::VerticalType, Tool::VerticalTypeMask, Tool::HorizontalTypeMask], - &[Tool::PathSelection, Tool::DirectSelection], - &[Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line, Tool::CustomShape], - ], - &[&[Tool::Hand, Tool::RotateView], &[Tool::Zoom]], -]; - -/// The tool a slot shows: the current tool if it belongs to the slot, else the last one used. -fn slot_tool(ui: &egui::Ui, current: Tool, slot: &[Tool], key: egui::Id) -> Tool { - if slot.contains(¤t) { - ui.data_mut(|d| d.insert_temp(key, current)); - return current; - } - ui.data(|d| d.get_temp::(key)).filter(|t| slot.contains(t)).unwrap_or(slot[0]) -} - -/// [`TOOL_SECTIONS`] without the tools hidden in Edit › Toolbar (`hidden` holds tool names: the -/// dialog writes `Tool` debug names, `edit.toolbar` takes any name `Tool::from_name` reads). A -/// slot keeps only its visible tools, so its flyout lists just those; a slot with none left is -/// dropped, and so is a section with no slots. Each slot carries its index in `TOOL_SECTIONS`, -/// so its remembered tool and flyout stay put when other slots are hidden. -fn visible_sections(hidden: &[String]) -> Vec)>> { - let hidden: Vec = hidden.iter().map(String::as_str).filter_map(Tool::from_name).collect(); - let mut index = 0usize; - let mut sections = Vec::new(); - for section in TOOL_SECTIONS { - let mut slots = Vec::new(); - for slot in section.iter() { - let tools: Vec = slot.iter().copied().filter(|tool| !hidden.contains(tool)).collect(); - if !tools.is_empty() { - slots.push((index, tools)); - } - index += 1; - } - if !slots.is_empty() { - sections.push(slots); - } - } - sections -} - -/// A primary-button gesture started on this tool; open only after it leaves its hit area. -/// Using pointer origin rather than `Response::dragged` also works for click-only icon buttons. -fn tool_flyout_drag_open(button: Rect, origin: Option, pointer: Option, primary_down: bool) -> bool { - primary_down && origin.is_some_and(|p| button.contains(p)) && pointer.is_some_and(|p| !button.contains(p)) -} - -/// A toolbar press cannot click a flyout row in egui because the press began elsewhere. -fn tool_flyout_release(row: Rect, pointer: Option, released: bool, from_button: bool) -> bool { - released && from_button && pointer.is_some_and(|p| row.contains(p)) -} - -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 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") }; - 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); - } - 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(ui, app.ui.tool, slot, key); - 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); - } - if resp.clicked() && ui.data(|d| d.get_temp::(held_id)) != Some(key) { - crate::tool_memory::select(app, tool); - } - // Double-clicking the Hand tool fits the image on screen (Photoshop). - if resp.double_clicked() && 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 resp.double_clicked() && tool == Tool::Zoom { - crate::tool_memory::select(app, tool); - let _ = app.run("view.actualPixels", json!({})); - } - // 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 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), - 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)) - }); - if pressed_outside || ui.input(|i| i.key_pressed(egui::Key::Escape)) { - ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id)); - } - } - } - }); - } - } - if icons::button(ui, "ellipsis", bx, false, tl!("Edit Toolbar…")).clicked() { - let _ = crate::menus::invoke(app, &ctx, "edit.toolbar", json!({})); - } - 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 _ = crate::menus::invoke(app, &ctx, "select.editInQuickMaskMode", json!({})); - } - let sm = icons::button_with_icon_size_tip(ui, "app-window", bx, (bx * 0.52).round(), false, tl!("Change Screen Mode (F)"), tool_tips); - paint_toolbar_flyout_indicator(ui, &t, &sm); - - // 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); - if ui.add(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 -/// toolbar glyphs (#2665); the other themes keep the general icon-button proportion. -fn toolbar_icon_size(box_size: f32, pro: bool) -> f32 { - (box_size * if pro { 2.0 / 3.0 } else { 0.52 }).round() -} - -/// 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) { - let r = resp.rect; - let tri = if crate::direction::is_rtl() { - 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)] - }; - ui.painter().add(egui::Shape::convex_polygon(tri, tokens.text_faint, Stroke::NONE)); -} +#[cfg(test)] +use color::color_field_height; +#[cfg(test)] +pub(crate) use color::{hsva_color32, hsva_srgb, srgb_bytes}; +pub(crate) use color::{color_field, color_field_fill_id, field_chips, field_hsva, offer_color_field_fill, srgb_hsva}; +#[cfg(test)] +pub(crate) use dock::DOCK_MIN_WIDTH; +pub use dock::{dock_area, request_dock_width}; +pub(crate) use dock::{canvas_panel, dock_body, dock_width_id, dock_width_range}; +#[cfg(test)] +use history::history; +#[cfg(test)] +pub(crate) use history::select_snapshot; +pub(crate) use history::selected_snapshot; +#[cfg(test)] +use info::info_panel; +pub(crate) use info::{sampler_readouts, SamplerReadouts}; +#[cfg(test)] +use layer_drag::{background_drop_refused, layer_drop_payload}; +pub(crate) use layer_drag::{dropped_on, layer_drag_edge_scroll}; +#[cfg(test)] +use layer_row::{layer_thumb_fit, paint_clipping_indicator}; +#[cfg(test)] +pub(crate) use layer_row::thumb_load_badge; +#[cfg(test)] +use layers::{layers, opacity_row_layout, simple_lock_toggle}; +#[cfg(test)] +use navigator::{NAV_ROW_H, navigator, navigator_zoom_drag_id, navigator_zoom_to}; +#[cfg(test)] +pub(crate) use navigator::{last_navigator_controls, last_navigator_preview}; +#[cfg(test)] +use options_bar::options_bar_height; +#[cfg(test)] +use options_bar::LAYER_PCT_W; +pub use options_bar::options_bar; +pub(crate) use options_bar::{FIXED_SIZE_MAX_PX, opt_label}; +pub use panel_state::{migrate_panel_state, panel_state_id, remember_panel_state}; +#[cfg(test)] +use properties::{adjustments_grid, properties_body}; +pub use properties::properties_window; +pub use status_bar::{status_bar, status_bar_heights}; +#[cfg(test)] +use title_bar::title_x; +pub use title_bar::{sync_window_title, system_title_bar, title_bar, window_title}; +#[cfg(test)] +use toolbar::{chips_height, color_chips, STUDIO_CHIP, tool_flyout_drag_open, tool_flyout_release, TOOL_SECTIONS, toolbar_icon_size, visible_sections}; +pub use toolbar::{paint_toolbar_flyout_indicator, toolbar}; fn c32(c: [f32; 4]) -> Color32 { Color32::from_rgba_unmultiplied((c[0] * 255.0) as u8, (c[1] * 255.0) as u8, (c[2] * 255.0) as u8, (c[3] * 255.0) as u8) } -/// Colour chips: chip size and the background chip's offset (points). -fn chip_metrics(pro: bool) -> (f32, f32) { - if pro { (18.0, 10.0) } else { (21.0, 12.0) } -} - -/// Height of the default-colours and swap icons over the chips. -const CHIP_ICON: f32 = 13.0; - -/// Studio themes: round chip diameter and the background chip's vertical offset (points). -const STUDIO_CHIP: (f32, f32) = (30.0, 19.0); -/// Room under the round chips for the Default Colors and Switch Colors buttons. -const STUDIO_ROW: f32 = 15.0; -/// Room above the stacked round chips so Default Colors, at their top-right, clears them. -const STUDIO_TOP: f32 = 6.0; - -/// Height of the colour chips block. -fn chips_height(pro: bool, studio: bool, wide: bool) -> f32 { - if studio && wide { - return STUDIO_CHIP.0 + STUDIO_ROW; - } - if studio { - return STUDIO_TOP + STUDIO_CHIP.0 + STUDIO_CHIP.1 + STUDIO_ROW; - } - let (chip, step) = chip_metrics(pro); - CHIP_ICON + 3.0 + chip + step -} - -/// Photoshop's foreground / background colour chips: the Default Colors (D) and Switch Colors (X) -/// icons above them, the foreground chip over the background one, all centred in the toolbar -/// column and kept inside it. -fn color_chips(app: &mut PhotocraftApp, ui: &mut egui::Ui, two_columns: bool, column: f32) { - let t = Tokens::get(ui.ctx()); - // Studio themes: round chips stacked vertically, the controls below them. - let studio = t.round_chips; - let (chip, step) = if studio { STUDIO_CHIP } else { chip_metrics(t.pro) }; - // With two tool columns (a short window) the round chips lie side by side, which saves height. - let wide = studio && two_columns; - let group = if studio && !wide { chip } else { chip + step }; - let w = column.max(group); - let (rect, _) = ui.allocate_exact_size(vec2(w, chips_height(t.pro, studio, wide)), Sense::hover()); - let left = (rect.left() + (w - group) / 2.0).round(); - let (fg, bg) = if wide { - let fg = Rect::from_min_size(pos2(left, rect.top()), vec2(chip, chip)); - (fg, fg.translate(vec2(step, 0.0))) - } else if studio { - let fg = Rect::from_min_size(pos2(left, rect.top() + STUDIO_TOP), vec2(chip, chip)); - (fg, fg.translate(vec2(0.0, step))) - } else { - let fg = Rect::from_min_size(pos2(left, rect.top() + CHIP_ICON + 3.0), vec2(chip, chip)); - (fg, fg.translate(vec2(step, step))) - }; - let radius = t.radius_sm.min(3.0); - let p = ui.painter(); - if studio { - let dot = |r: Rect, color: Color32| { - p.circle_filled(r.center(), r.width() / 2.0, color); - // A light line inside a dark one, so any colour reads against the toolbar. - p.circle_stroke(r.center(), r.width() / 2.0 - 0.5, Stroke::new(1.0, t.text.gamma_multiply(0.9))); - p.circle_stroke(r.center(), r.width() / 2.0 + 0.5, Stroke::new(1.0, t.field_border)); - }; - dot(bg, c32(app.session.tools.background)); - // The foreground chip sits on the background one, a toolbar-coloured gap between them. - p.circle_filled(fg.center(), fg.width() / 2.0 + 2.0, t.chrome); - dot(fg, c32(app.session.tools.foreground)); - } else { - let frame = |r: Rect| { - // A light line inside a dark one, so any colour reads against the toolbar. - p.rect_stroke(r, radius, Stroke::new(1.0, t.text.gamma_multiply(0.9)), StrokeKind::Inside); - p.rect_stroke(r, radius, Stroke::new(1.0, t.field_border), StrokeKind::Outside); - }; - p.rect_filled(bg, radius, c32(app.session.tools.background)); - frame(bg); - p.rect_filled(fg.expand(2.0), radius + 2.0, t.chrome); - p.rect_filled(fg, radius, c32(app.session.tools.foreground)); - frame(fg); - } - // Photoshop: clicking a chip opens the Color Picker for that colour. - let bg_resp = ui.interact(bg, ui.scope_id().with("bgchip"), Sense::click()); - let fg_resp = ui.interact(fg, ui.scope_id().with("fgchip"), Sense::click()); - if fg_resp.on_hover_text(tl!("Set foreground color")).clicked() { - crate::color_picker_ui::open(app, "foreground"); - } else if bg_resp.on_hover_text(tl!("Set background color")).clicked() { - crate::color_picker_ui::open(app, "background"); - } - // Default Colors at the left, Switch Colors at the right, over the chips. - let (dr, sr) = if studio { - // Switch Colors is a curve right under the chips, centred on them so its heads touch - // them. Default Colors never moves it: at the left edge beside it when the chips lie side - // by side, at the block's top-right corner when they are stacked. - let (cx, row) = ((fg.center().x + bg.center().x) / 2.0, fg.bottom().max(bg.bottom()) + 3.5); - let default = if wide { - Rect::from_center_size(pos2(rect.left() + CHIP_ICON / 2.0, row), vec2(CHIP_ICON, CHIP_ICON)) - } else { - // Just high enough that its bottom-left corner clears the foreground chip's outline. - let x = rect.right() - CHIP_ICON; - let (dx, r) = ((x - fg.center().x).max(0.0), fg.width() / 2.0 + 1.0); - let clear = if dx < r { (r * r - dx * dx).sqrt() } else { 0.0 }; - Rect::from_min_size(pos2(x, fg.center().y - clear - CHIP_ICON), vec2(CHIP_ICON, CHIP_ICON)) - }; - (Some(default), Rect::from_center_size(pos2(cx, row), vec2(20.0, 14.0))) - } else { - let icon = |x: f32| Rect::from_min_size(pos2(x, rect.top()), vec2(CHIP_ICON, CHIP_ICON)); - (Some(icon(left)), icon(left + group - CHIP_ICON)) - }; - let d = dr.map(|dr| ui.interact(dr, ui.scope_id().with("default-colors"), Sense::click())); - let s = ui.interact(sr, ui.scope_id().with("swap-colors"), Sense::click()); - let p = ui.painter(); - for (r, resp) in dr.into_iter().zip(d.iter()).chain([(sr, &s)]) { - if resp.hovered() && !studio { - p.rect_filled(r.expand(2.0), radius, t.hover); - } - } - let ink = |resp: &egui::Response| if resp.hovered() { t.text } else { t.icon }; - if studio { - // Switch Colors: a shallow curve hugging the bottom chip, with a filled head at each end. - // It glows on hover instead of getting a button box. - let hot = s.hovered(); - let stroke = Stroke::new(1.5, ink(&s)); - let (c, rad) = (pos2(sr.center().x, sr.center().y - 5.0), 9.0); - let (from, to) = (0.45, std::f32::consts::PI - 0.45); - let arc: Vec<_> = (0..=12) - .map(|i| { - let a = from + (to - from) * i as f32 / 12.0; - c + vec2(rad * a.cos(), rad * a.sin()) - }) - .collect(); - if hot { - p.add(egui::Shape::line(arc.clone(), Stroke::new(5.0, t.text.gamma_multiply(0.18)))); - } - let ends = [(arc[0], from, -1.0_f32), (arc[arc.len() - 1], to, 1.0)]; - p.add(egui::Shape::line(arc, stroke)); - // Each head points along the curve, away from its middle. - for (end, a, sign) in ends { - let dir = vec2(-a.sin(), a.cos()) * sign; - let side = vec2(-dir.y, dir.x); - let tip = end + dir * 2.5; - let base = tip - dir * 5.0; - p.add(egui::Shape::convex_polygon(vec![tip, base + side * 3.0, base - side * 3.0], ink(&s), Stroke::NONE)); - } - } else { - // Switch Colors: the compact clockwise bend has left- and down-pointing heads. - // swap_arrow.rs owns its geometry and the pixel-level render regression test. - crate::swap_arrow::paint(p, sr.min, ink(&s)); - } - // Default Colors: a small black chip over a small white one. - if let (Some(dr), Some(d)) = (dr, d.as_ref()) { - let small = 7.0; - let (b, w) = (Rect::from_min_size(dr.min + vec2(1.0, 1.0), vec2(small, small)), Rect::from_min_size(dr.min + vec2(5.0, 5.0), vec2(small, small))); - p.rect_filled(w, 1.0, Color32::WHITE); - p.rect_stroke(w, 1.0, Stroke::new(1.0, ink(d)), StrokeKind::Inside); - p.rect_filled(b.expand(1.0), 1.5, t.chrome); - p.rect_filled(b, 1.0, Color32::BLACK); - p.rect_stroke(b, 1.0, Stroke::new(1.0, ink(d)), StrokeKind::Inside); - } - if let Some(d) = &d { - d.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Default colours (D)"))); - } - s.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Swap colours (X)"))); - if s.on_hover_text(tl!("Swap colours (X)")).clicked() { - chip_command(app, "tools.swapColors"); - } - if d.is_some_and(|d| d.on_hover_text(tl!("Default colours (D)")).clicked()) { - chip_command(app, "tools.defaultColors"); - } -} - -/// Run Switch Colors or Default Colors from the chips. As in Photoshop, characters highlighted -/// in the type layer being edited take the new foreground colour, like picking one (#5690). -fn chip_command(app: &mut PhotocraftApp, id: &str) { - if app.run(id, json!({})).is_ok() { - crate::type_tool::foreground_changed(app); - } -} - -// ----------------------------------------------------------------------------- title bar - -/// The app's top bar: brand mark, menus, the document title and the workspace controls. With -/// [`PhotocraftApp::custom_titlebar`] (Windows and Linux) it is also the window's title bar, as in -/// Photoshop on Windows: the caption buttons take its ends (`titlebar`). With the system -/// title bar (Windows and Linux, `system_title_bar`) the OS draws its own icon and title, so the -/// in-app bar shows menus and workspace controls only: no brand mark, no centred title. -pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - let custom = app.custom_titlebar; - let system = system_title_bar(app); - // The caption buttons' room at each end (`titlebar`); a side with buttons has no margin. - let (caption_left, caption_right) = crate::titlebar::reserved(app, ui.ctx()); - let left = if cfg!(target_os = "macos") && app.integrated_titlebar { - 78 - } else if caption_left > 0.0 { - 0 - } else { - 10 - }; - let right = if caption_right > 0.0 { 0 } else { 10 }; - let bar = egui::Panel::top("title_bar") - .exact_size(crate::titlebar::bar_height(app, ui.ctx(), if t.pro { 32.0 } else { 38.0 })) - .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin { left, right, top: 0, bottom: 0 })) - .show(ui, |ui| { - let full = ui.max_rect(); - // Only the free gap between the menus and the far-end controls drags the window: a - // press on a menu title must open the menu, never move the window. The gap is last - // frame's, as the menus are laid out after this. - let span_id = ui.scope_id().with("titledrag-span"); - let (gap_l, gap_r) = ui.ctx().data(|d| d.get_temp::<(f32, f32)>(span_id)).unwrap_or((full.right(), full.right())); - let gap = egui::Rect::from_x_y_ranges(gap_l.max(full.left())..=gap_r.min(full.right()).max(gap_l), full.y_range()); - ui.ctx().data_mut(|d| d.insert_temp(crate::titlebar::modal_drag_area_id(), gap)); - let drag = ui.interact(gap, ui.scope_id().with("titledrag"), Sense::click_and_drag()); - if drag.drag_started_by(egui::PointerButton::Primary) { - crate::titlebar::start_os_move(ui.ctx()); - } - if drag.double_clicked() { - let max = ui.ctx().input(|i| i.viewport().maximized.unwrap_or(false)); - ui.ctx().send_viewport_cmd(egui::ViewportCommand::Maximized(!max)); - } - // Preferences › Interface › Show File Name In Title: with it off the bar keeps the - // app name and the unsaved dot, since the tabs already name the file (#5037). - let show_name = app.session.prefs().interface.show_file_name_in_title; - let title = app - .session - .active() - .map(|d| format!("{}{}", if show_name { d.doc.name.as_str() } else { "PhotoCraft" }, if d.is_dirty() { " •" } else { "" })) - .unwrap_or_else(|| "PhotoCraft".into()); - // The menus and the far-end controls are laid out first; the title is centred in - // whatever room is left between them (`free`, left to right: menus then controls, or - // controls then menus in a right-to-left UI), shortened or dropped rather than drawn - // over them. - let rtl = crate::direction::is_rtl(); - let mut free = (full.left(), full.right()); - crate::direction::horizontal_centered(ui, |ui| { - // The menus start beside the caption buttons at their end, if it has any. - let lead = if rtl { caption_right } else { caption_left }; - if lead > 0.0 { - ui.add_space(lead + 4.0); - } - if !system { - let side = if t.pro { 18.0 } else { 20.0 }; - let (mark, _) = ui.allocate_exact_size(vec2(side, side), Sense::hover()); - crate::brand::paint_mark(ui, mark); - ui.add_space(6.0); - } - // With the macOS menu bar the menus are at the top of the screen instead. Either way - // this is the menus' inner edge, facing the title. - let menus_end = if app.services.native_menu.is_some() { - if rtl { ui.cursor().right() } else { ui.cursor().left() } - } else { - crate::menus::menu_bar(app, ui) - }; - // The menu bar takes the whole row, so the far-end group gets its own rect: from - // the menus to the bar's end, or to the caption buttons. - let group = if rtl { - let left_edge = if caption_left > 0.0 { full.left() + caption_left + 4.0 } else { full.left() }; - egui::Rect::from_min_max(egui::pos2(left_edge, full.top()), egui::pos2((menus_end - TITLE_GAP).max(left_edge), full.bottom())) - } else { - let right_edge = if caption_right > 0.0 { full.right() - caption_right - 4.0 } else { full.right() }; - egui::Rect::from_min_max(egui::pos2((menus_end + TITLE_GAP).min(right_edge), full.top()), egui::pos2(right_edge, full.bottom())) - }; - let mut group_ui = ui.new_child(egui::UiBuilder::new().max_rect(group).layout(crate::direction::trailing())); - let controls_end = { - let ui = &mut group_ui; - ui.spacing_mut().item_spacing.x = 6.0; - let mut ws = app.ui.workspace.clone(); - let options = crate::workspace_ui::switcher_options(app); - let opts: Vec<(String, &str)> = options.iter().map(|(k, l)| (k.clone(), l.as_str())).collect(); - // A narrow bar drops what is also in a menu, the theme toggle first - // (Preferences), then search (Edit › Search), and narrows the switcher - // (Window › Workspace) before anything runs over. - let room = ui.available_width(); - let icons_shown: u8 = if room >= WORKSPACE_MIN + 2.0 * ICON_SLOT { - 2 - } else if room >= WORKSPACE_MIN + ICON_SLOT { - 1 - } else { - 0 - }; - let ws_width = (room - f32::from(icons_shown) * ICON_SLOT - 6.0).clamp(WORKSPACE_MIN, 130.0); - if room >= WORKSPACE_MIN && widgets::dropdown(ui, "workspace", tl!("Workspace"), &mut ws, &opts, ws_width) { - app.ui.workspace = ws; - crate::menus::apply_workspace(app); - } - if icons_shown >= 1 - && icons::button(ui, "search", 28.0, app.ui.palette_open, &crate::shortcuts::tip_label(app, "Search commands", "edit.search")).clicked() - { - app.ui.palette_open = !app.ui.palette_open; - } - let (theme_icon, appearance_label) = match app.session.prefs().interface.appearance_mode { - photocraft_engine::prefs::AppearanceMode::Auto => ("monitor", tl!("Auto")), - photocraft_engine::prefs::AppearanceMode::Dark => ("moon", tl!("Dark")), - photocraft_engine::prefs::AppearanceMode::Light => ("sun", tl!("Light")), - }; - let appearance_tip = format!("{}: {}", tl!("Appearance Mode"), appearance_label); - if icons_shown >= 2 { - let button = icons::button(ui, theme_icon, 28.0, false, &appearance_tip); - if button.clicked() { - crate::prefs_ui::cycle_appearance(app, ui.ctx()); - } - button.context_menu(|ui| crate::prefs_ui::appearance_context_menu(app, ui)); - } - if rtl { ui.min_rect().right() } else { ui.min_rect().left() } - }; - free = if rtl { (controls_end, menus_end) } else { (menus_end, controls_end) }; - }); - ui.ctx().data_mut(|d| d.insert_temp(span_id, free)); - if system { - return; - } - // A right-to-left document name in display order (the OS title keeps the logical text), - // in a left-to-right line: "— PhotoCraft" stays after the name, at the right. - let title = crate::bidi_text::visual_ltr(&title).into_owned(); - let font = theme::medium(13.0); - let galley = ui.painter().layout_no_wrap(title.clone(), font.clone(), t.text_dim); - if let Some(x) = title_x(full.center().x, free.0, free.1, galley.size().x) { - ui.painter().galley(egui::pos2(x, full.center().y - galley.size().y / 2.0), galley, t.text_dim); - } else if free.1 - free.0 > 80.0 { - // Too narrow for the whole name: show the start of it, elided, in the free gap - // next to the menus. - let avail = free.1 - free.0 - 2.0 * TITLE_GAP; - let mut job = egui::text::LayoutJob::simple_singleline(title, font, t.text_dim); - job.wrap = egui::text::TextWrapping::truncate_at_width(avail); - let g = ui.painter().layout_job(job); - let x = if rtl { free.1 - TITLE_GAP - g.size().x } else { free.0 + TITLE_GAP }; - ui.painter().galley(egui::pos2(x, full.center().y - g.size().y / 2.0), g, t.text_dim); - } - }); - if custom { - crate::titlebar::caption_buttons(app, ui, bar.response.rect); - } -} - -/// Whether the window shows the system's title bar instead of the app drawing its own: Windows -/// and Linux with Preferences › Interface › System Title Bar. macOS always has system decorations, -/// but keeps the in-app brand mark and centred title, so it never counts as system mode here; nor -/// does the web build (the browser tab has no document title), nor an embedder or the snapshot -/// example that never turned the preference on. -pub fn system_title_bar(app: &PhotocraftApp) -> bool { - !app.custom_titlebar && app.session.prefs().interface.system_title_bar && !cfg!(any(target_os = "macos", target_arch = "wasm32")) -} - -/// The OS window title: the active document's name suffixed with the app name (a `*` prefix -/// marks unsaved changes, like the `•` in the app-drawn title), or just the app name with no -/// document open. With Preferences › Interface › Show File Name In Title off, the file name -/// drops out and only the app name (and the `*`) remains (#5037). -pub fn window_title(app: &PhotocraftApp) -> String { - if !app.session.prefs().interface.show_file_name_in_title { - return format!("{}PhotoCraft", if app.session.active().is_some_and(|d| d.is_dirty()) { "*" } else { "" }); - } - app.session.active().map(|d| format!("{}{} \u{2014} PhotoCraft", if d.is_dirty() { "*" } else { "" }, d.doc.name)).unwrap_or_else(|| "PhotoCraft".into()) -} - -/// Keep the OS window title (and the taskbar / Alt-Tab entry) on the active file. Sends -/// `ViewportCommand::Title` only when the title changed since the last frame. -pub fn sync_window_title(app: &mut PhotocraftApp, ctx: &egui::Context) { - let want = window_title(app); - if app.last_window_title != want { - app.last_window_title = want.clone(); - ctx.send_viewport_cmd(egui::ViewportCommand::Title(want)); - } -} - -/// Minimum space kept between the window title and the menus or controls beside it. -const TITLE_GAP: f32 = 16.0; -/// The workspace switcher's narrowest width, and one 28 pt title-bar icon with its spacing. -const WORKSPACE_MIN: f32 = 90.0; -const ICON_SLOT: f32 = 34.0; - -/// Left edge for a title `width` wide: centred on `center` when it fits in the free gap from -/// `left` to `right` (the menus' and the controls' facing edges, whichever side each is on), -/// else slid into that gap; None when the gap is too small for the whole title. -fn title_x(center: f32, left: f32, right: f32, width: f32) -> Option { - let (lo, hi) = (left + TITLE_GAP, right - TITLE_GAP - width); - if !(lo.is_finite() && hi.is_finite() && width.is_finite()) || hi < lo { - return None; - } - if !center.is_finite() { - return Some(lo); - } - Some((center - width / 2.0).clamp(lo, hi)) -} - #[cfg(test)] mod title_tests { use super::{system_title_bar, title_x, window_title}; @@ -1027,1306 +222,11 @@ mod title_tests { } } -// Custom controls also need to bring keyboard focus into a scroll viewport. -fn reveal_focused_control(ui: &egui::Ui) { - // read_response reprocesses pointer events. Reading a popup's newly focused field - // during its opening click can undo the focus that the popup just requested. - if ui.input(|input| input.pointer.any_pressed() || input.pointer.any_released()) { - return; - } - let focused = ui.memory(|memory| memory.focused()); - let key = ui.scope_id().with("scroll-focused-control"); - let changed = ui.data_mut(|data| { - let previous = data.get_temp::>(key).flatten(); - data.insert_temp(key, focused); - previous != focused - }); - if changed - && let Some(response) = focused.and_then(|id| ui.ctx().read_response(id)) - && response.layer_id == ui.layer_id() - && ui.min_rect().contains_rect(response.rect) - { - ui.scroll_to_rect(response.rect, Some(egui::Align::Center)); - } -} - -// ----------------------------------------------------------------------------- options bar - -/// Options bar height: Preferences ▸ Workspace ▸ Enable Narrow Options Bar trims it, as in -/// Photoshop, leaving the document more room. -fn options_bar_height(pro: bool, narrow: bool) -> f32 { - match (pro, narrow) { - (true, false) => 36.0, - (true, true) => 30.0, - (false, false) => 42.0, - (false, true) => 34.0, - } -} - -pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - let narrow = app.session.prefs().workspace.narrow_options_bar(); - egui::Panel::top("options_bar") - .exact_size(options_bar_height(t.pro, narrow)) - .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(10, 0))) - .show(ui, |ui| { - ui.style_mut().spacing.scroll = egui::style::ScrollStyle { bar_width: 4.0, ..egui::style::ScrollStyle::floating() }; - egui::ScrollArea::horizontal().id_salt("tool-options").auto_shrink([false, false]).show(ui, |ui| { - // Font ink can extend beyond its advance width at fractional positions. - // Include its gutter in the container layout, including right-aligned actions. - egui::Frame::NONE.inner_margin(egui::Margin { right: 2, ..Default::default() }).show(ui, |ui| { - crate::direction::horizontal_centered(ui, |ui| { - if t.pro { - crate::chrome_ui::home_button(app, ui); - widgets::vline(ui, 22.0); - } - let tool_icon = icons::button(ui, icons::tool_icon(app.ui.tool), if t.pro { 26.0 } else { 28.0 }, !t.pro, tl!(app.ui.tool.label())); - // Photoshop: right-click the tool icon for Reset Tool / Reset All Tools (#2825). - let mut reset = None; - tool_icon.context_menu(|ui| { - if ui.button(tl!("Reset Tool")).clicked() { - reset = Some("tool.reset"); - ui.close(); - } - if ui.button(tl!("Reset All Tools")).clicked() { - reset = Some("tool.resetAll"); - ui.close(); - } - }); - if let Some(id) = reset - && let Err(e) = crate::menus::invoke(app, ui.ctx(), id, json!({})) - { - app.ui.status = e; - } - if t.pro { - let (r, _) = ui.allocate_exact_size(vec2(10.0, 20.0), Sense::hover()); - icons::paint(ui, r, "chevron-down", 10.0, t.text_faint); - } - widgets::vline(ui, 22.0); - if app.ui.transform.is_some() { - crate::transform_tool::options_bar(app, ui); - return; - } - if crate::symmetry_ui::options_bar(app, ui) || crate::distort_ui::options_bar(app, ui) { - return; - } - let tool = app.ui.tool; - // The options bar shows the active tool's brush: switch it in before drawing the - // chip, so a tool change swaps the brush with it (Photoshop keeps one per tool). - crate::paint_mouse::sync_tool_brush(app); - // Brush edits here go through `tools.setBrush`, one journal entry per gesture (Rule 1). - if (tool.is_brushlike() && !matches!(tool, Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::Eraser)) - || tool == Tool::QuickSelection - { - brush_preset_chip(ui, &app.session.tools.brush, &mut app.ui); - crate::brush_picker::settings_toggle(app, ui); - widgets::vline(ui, 22.0); - } - if matches!(tool, Tool::CloneStamp | Tool::PatternStamp | Tool::HistoryBrush | Tool::Healing) { - let before = app.session.tools.brush.clone(); - let mut brush = before.clone(); - // Mode is the tool's own brush's, kept per tool like its size. - if let Some(modes) = crate::blend_keys::tool_modes(tool) { - opt_label(ui, tl!("Mode")); - if let Some(Some(m)) = - tool_mode_dropdown(ui, "retouch-mode", &modes, Some(crate::blend_keys::brush_tool_mode(tool, brush.mode))) - { - brush.mode = m; - } - } - if tool == Tool::CloneStamp { - let width = if t.pro { 62.0 } else { 66.0 }; - percent_field(ui, tl!("Opacity"), &mut brush.opacity, 1.0..=100.0, width); - percent_field(ui, tl!("Flow"), &mut brush.flow, 1.0..=100.0, width); - } - crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush); - widgets::vline(ui, 22.0); - } - if crate::eraser_ui::options_bar(app, ui, tool) - || crate::retouch_ui::options_bar(app, ui, tool) - || crate::vector_ui::options_bar(app, ui, tool) - || crate::analysis_ui::options_bar(app, ui, tool) - || crate::slice_ui::options_bar(app, ui, tool) - || crate::frame_tool::options_bar(app, ui, tool) - || crate::artboard_tool::options_bar(app, ui, tool) - { - return; - } - let brush_before = app.session.tools.brush.clone(); - let mut brush = brush_before.clone(); - let b = &mut brush; - match app.ui.tool { - Tool::Brush | Tool::Eraser if t.pro => { - // A Block-mode Eraser has a fixed size, opacity and flow (Photoshop, #2770). - let block = crate::eraser_ui::block_mode(app, app.ui.tool); - ui.add_enabled_ui(!block, |ui| { - brush_preset_chip(ui, b, &mut app.ui); - crate::brush_picker::settings_toggle(app, ui); - }); - widgets::vline(ui, 22.0); - // The Eraser has no blend mode: its Mode is Brush, Pencil or Block (#2662). - if app.ui.tool == Tool::Eraser { - crate::eraser_ui::mode_dropdown(ui, &mut app.ui.tool_options.eraser_mode); - } else { - opt_label(ui, tl!("Mode")); - let held = app.held_erase; - paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held); - } - ui.add_enabled_ui(!block, |ui| { - percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 62.0); - if icons::button(ui, "circle-dot", 24.0, b.pressure_opacity, tl!("Always use pressure for opacity")).clicked() { - b.pressure_opacity = !b.pressure_opacity; - } - }); - // 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| { - percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 62.0); - 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")); - smoothing_field(ui, b, 58.0); - smoothing_options(ui, b); - widgets::vline(ui, 22.0); - if icons::button(ui, "circle-dot", 24.0, b.pressure_size, tl!("Always use pressure for size")).clicked() { - b.pressure_size = !b.pressure_size; - } - } - // Pencil: Photoshop's options (no hardness or flow: the pencil is always hard). - Tool::Pencil => { - brush_preset_chip(ui, b, &mut app.ui); - crate::brush_picker::settings_toggle(app, ui); - widgets::vline(ui, 22.0); - if !t.pro { - opt_label(ui, tl!("Size")); - widgets::value_field(ui, &mut b.size, 1.0..=photocraft_engine::paint::MAX_BRUSH_SIZE, "px", 76.0); - widgets::vline(ui, 22.0); - } - opt_label(ui, tl!("Mode")); - let held = app.held_erase; - paint_mode_dropdown(ui, "pencil-mode", b, &mut app.ui.tool_options.pencil_clear, held); - percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, if t.pro { 62.0 } else { 66.0 }); - 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")); - } - Tool::Brush | Tool::Eraser => { - brush_preset_chip(ui, b, &mut app.ui); - crate::brush_picker::settings_toggle(app, ui); - widgets::vline(ui, 22.0); - // A Block-mode Eraser has a fixed size, opacity and flow (Photoshop, #2770). - let block = crate::eraser_ui::block_mode(app, app.ui.tool); - ui.add_enabled_ui(!block, |ui| { - opt_label(ui, tl!("Size")); - widgets::value_field(ui, &mut b.size, 1.0..=photocraft_engine::paint::MAX_BRUSH_SIZE, "px", 76.0); - }); - widgets::vline(ui, 22.0); - if app.ui.tool == Tool::Eraser { - crate::eraser_ui::mode_dropdown(ui, &mut app.ui.tool_options.eraser_mode); - } else { - opt_label(ui, tl!("Mode")); - let held = app.held_erase; - paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held); - } - // A Pencil-mode Eraser is always hard and at full flow (Photoshop). - let fixed = block || crate::eraser_ui::pencil_mode(app, app.ui.tool); - ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Hardness"), &mut b.hardness, 0.0..=100.0, 66.0)); - ui.add_enabled_ui(!block, |ui| percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 66.0)); - ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 66.0)); - opt_label(ui, tl!("Smoothing")); - smoothing_field(ui, b, 66.0); - widgets::vline(ui, 22.0); - widgets::toggle(ui, &mut b.pressure_size, tl!("Pressure for Size")); - widgets::toggle(ui, &mut b.pressure_opacity, tl!("Pressure for Opacity")); - } - Tool::MixerBrush => { - brush_preset_chip(ui, b, &mut app.ui); - crate::brush_picker::settings_toggle(app, ui); - widgets::vline(ui, 22.0); - mixer_load_swatch(app, ui); - let m = &mut b.mixer; - for (icon, on, tip) in [ - ("brush", &mut m.load_after_stroke, tl!("Load the brush after each stroke")), - ("brush-cleaning", &mut m.clean_after_stroke, tl!("Clean the brush after each stroke")), - ] { - if icons::button(ui, icon, 24.0, *on, tip).clicked() { - *on = !*on; - } - } - 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), - ] { - percent_field(ui, label, value, 0.0..=100.0, 62.0); - } - widgets::vline(ui, 22.0); - widgets::checkbox(ui, &mut b.mixer.sample_all_layers, tl!("Sample All Layers")); - } - Tool::RectMarquee | Tool::EllipseMarquee | Tool::SingleRowMarquee | Tool::SingleColumnMarquee => { - ui.spacing_mut().item_spacing.x = 2.0; - for (i, (icon, tip)) in [ - ("square", tl!("New selection").to_string()), - ("plus", crate::i18n::fmt(tl!("Add to selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift"))])), - ("minus", crate::i18n::fmt(tl!("Subtract from selection ({key})"), &[("key", &crate::shortcuts::pretty("Alt"))])), - ( - "squares-subtract", - crate::i18n::fmt(tl!("Intersect with selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift+Alt"))]), - ), - ] - .iter() - .enumerate() - { - if icons::button(ui, icon, 24.0, app.ui.selection_mode == i as u8, tip).clicked() { - app.ui.selection_mode = i as u8; - } - } - ui.spacing_mut().item_spacing.x = 8.0; - widgets::vline(ui, 22.0); - let (units, size) = fixed_size_units(app); - let o = &mut app.ui.tool_options; - opt_label(ui, tl!("Feather")); - widgets::value_field(ui, &mut o.feather, 0.0..=1000.0, "px", 62.0); - // Photoshop greys Anti-alias for the Rectangular Marquee (its edges are always hard). - ui.add_enabled_ui(app.ui.tool == Tool::EllipseMarquee, |ui| widgets::checkbox(ui, &mut o.anti_alias, tl!("Anti-alias"))); - widgets::vline(ui, 22.0); - // A single row or column has no style or size: Photoshop greys them. - let sized = matches!(app.ui.tool, Tool::RectMarquee | Tool::EllipseMarquee); - ui.add_enabled_ui(sized, |ui| opt_label(ui, tl!("Style"))); - let styles = [ - ("normal".to_string(), tl!("Normal")), - ("fixedRatio".to_string(), tl!("Fixed Ratio")), - ("fixedSize".to_string(), tl!("Fixed Size")), - ]; - if ui - .add_enabled_ui(sized, |ui| widgets::dropdown(ui, "marquee-style", tl!("Style"), &mut o.marquee_style, &styles, 96.0)) - .inner - { - (o.marquee_width, o.marquee_height) = if o.marquee_style == "fixedSize" { (64.0, 64.0) } else { (1.0, 1.0) }; - } - let fixed = sized && o.marquee_style != "normal"; - let fixed_size = o.marquee_style == "fixedSize"; - // Fixed Size shows its pixels in the unit picked by right-clicking Width or Height (#7910). - let units = widgets::FieldUnits { unit: photocraft_engine::prefs::Unit::parse(&o.marquee_unit).unwrap_or_default(), ..units }; - ui.add_enabled_ui(fixed, |ui| { - let mut picked = None; - opt_label(ui, tl!("Width")); - if fixed_size { - picked = fixed_size_field(ui, &mut o.marquee_width, units, size[0]); - } else { - widgets::value_field(ui, &mut o.marquee_width, crate::tool_memory::style_range(&o.marquee_style), "", 62.0); - } - if icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked() { - std::mem::swap(&mut o.marquee_width, &mut o.marquee_height); - } - opt_label(ui, tl!("Height")); - if fixed_size { - picked = fixed_size_field(ui, &mut o.marquee_height, units, size[1]).or(picked); - } else { - widgets::value_field(ui, &mut o.marquee_height, crate::tool_memory::style_range(&o.marquee_style), "", 62.0); - } - if let Some(name) = picked { - o.marquee_unit = name.into(); - } - }); - widgets::vline(ui, 22.0); - select_and_mask_button(app, ui); - } - Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso => { - selection_mode_buttons(app, ui); - widgets::vline(ui, 22.0); - opt_label(ui, tl!("Feather")); - widgets::value_field(ui, &mut app.ui.tool_options.feather, 0.0..=1000.0, "px", 62.0); - widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias")); - widgets::vline(ui, 22.0); - if app.ui.tool == Tool::MagneticLasso { - let o = &mut app.ui.tool_options; - opt_label(ui, tl!("Width")); - widgets::value_field(ui, &mut o.magnetic_width, 1.0..=256.0, "px", 58.0) - .on_hover_text(tl!("Follows only edges this close to the pointer ([ and ] change it)")); - opt_label(ui, tl!("Contrast")); - widgets::value_field(ui, &mut o.magnetic_contrast, 1.0..=100.0, "%", 58.0) - .on_hover_text(tl!("Higher values follow only edges that contrast sharply with their surroundings")); - opt_label(ui, tl!("Frequency")); - widgets::value_field(ui, &mut o.magnetic_frequency, 0.0..=100.0, "", 50.0) - .on_hover_text(tl!("How often fastening points are placed by themselves")); - if icons::button(ui, "circle-dot", 24.0, o.magnetic_pressure, tl!("Use tablet pressure to change pen width")).clicked() { - o.magnetic_pressure = !o.magnetic_pressure; - } - widgets::vline(ui, 22.0); - } - select_and_mask_button(app, ui); - if crate::lasso_ui::active(app) || (app.ui.tool == Tool::PolygonLasso && !app.ui.polygon.is_empty()) { - hint( - ui, - &crate::i18n::fmt( - tl!("Click the first point or press {key} to close · Esc cancels"), - &[("key", &crate::shortcuts::pretty("Enter"))], - ), - ); - } else if app.ui.tool == Tool::Lasso { - hint(ui, tl!("Hold Alt while drawing for straight segments")); - } - if app.ui.tool == Tool::MagneticLasso && app.ui.magnetic.active() { - hint( - ui, - &crate::i18n::fmt( - tl!("Click the first point or press {key} to close · {del} removes a point · Esc cancels"), - &[("key", &crate::shortcuts::pretty("Enter")), ("del", &crate::shortcuts::pretty("Backspace"))], - ), - ); - } - } - Tool::MagicWand => { - selection_mode_buttons(app, ui); - widgets::vline(ui, 22.0); - opt_label(ui, tl!("Tolerance")); - widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0); - widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias")); - widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous")); - widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.magic_wand, tl!("Sample All Layers")); - widgets::vline(ui, 22.0); - if widgets::secondary_button(ui, tl!("Select Subject"), 0.0).clicked() { - let r = app.run("select.subject", json!({})); - crate::retouch_ui::report_smart_result(app, r, tl!("No subject found — try Object Selection or the Lasso")); - } - select_and_mask_button(app, ui); - } - Tool::PaintBucket => { - opt_label(ui, tl!("Fill")); - let mut src = u8::from(app.ui.tool_options.bucket_fill_pattern); - if widgets::dropdown(ui, "bucket-src", tl!("Source"), &mut src, &[(0u8, tl!("Foreground")), (1, tl!("Pattern"))], 100.0) { - app.ui.tool_options.bucket_fill_pattern = src == 1; - } - opt_label(ui, tl!("Mode")); - if let Some(modes) = crate::blend_keys::tool_modes(tool) { - let o = &mut app.ui.tool_options; - let current = if o.bucket_clear { None } else { Some(o.bucket_blend_mode) }; - if let Some(m) = tool_mode_dropdown(ui, "bucket-mode", &modes, current) { - o.bucket_clear = m.is_none(); - if let Some(m) = m { - o.bucket_blend_mode = m; - } - } - } - opt_label(ui, tl!("Opacity")); - widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0); - opt_label(ui, tl!("Tolerance")); - widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0); - widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias")); - widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous")); - widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.paint_bucket, tl!("All Layers")); - } - Tool::Gradient => { - // Live "Gradient" (a Gradient Fill layer) or "Classic gradient" (pixels). - let mut classic = app.ui.tool_options.gradient_classic; - if widgets::dropdown(ui, "gradient-mode", tl!("Mode"), &mut classic, &[(false, "Gradient"), (true, "Classic gradient")], 118.0) - { - app.ui.tool_options.gradient_classic = classic; - } - // Live "Gradient" (a Gradient Fill layer) or "Classic gradient" (pixels): - // both paint with the same engine-owned preset (#1651), and either swatch - // click opens the Gradient Editor window, as in Photoshop. - if crate::gradient_ui::preset_swatch(app, ui) { - app.ui.panels.gradient_editor = true; - } - widgets::vline(ui, 22.0); - ui.spacing_mut().item_spacing.x = 2.0; - let before = app.ui.tool_options.clone(); - for (style, icon, tip) in [ - ("linear", "gradient", tl!("Linear Gradient")), - ("radial", "circle", tl!("Radial Gradient")), - ("angle", "rotate-cw", tl!("Angle Gradient")), - ("reflected", "arrow-left-right", tl!("Reflected Gradient")), - ("diamond", "diamond", tl!("Diamond Gradient")), - ] { - if icons::button(ui, icon, 24.0, app.ui.tool_options.gradient_style == style, tip).clicked() { - app.ui.tool_options.gradient_style = style.into(); - } - } - ui.spacing_mut().item_spacing.x = 8.0; - widgets::vline(ui, 22.0); - opt_label(ui, tl!("Mode")); - let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); - // The wheel over it steps the mode, as over the Layers panel's (#2061). - widgets::dropdown_wheel_hovered( - ui, - "gradient-blend-mode", - tl!("Blend Mode"), - &mut app.ui.tool_options.gradient_blend_mode, - &opts, - 96.0, - ); - opt_label(ui, tl!("Opacity")); - let r = widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0); - // Live while scrubbed, one undo step per scrub (#5012). - let drag_key = r.id.with("gradient-opacity-drag"); - if r.drag_started() { - let n = ui.ctx().cumulative_pass_nr(); - ui.data_mut(|d| d.insert_temp(drag_key, n)); - } - if r.changed() { - let drag = if r.dragged() { ui.data(|d| d.get_temp::(drag_key)) } else { None }; - crate::gradient_ui::opacity_changed(app, drag); - } - widgets::checkbox(ui, &mut app.ui.tool_options.gradient_reverse, tl!("Reverse")); - widgets::checkbox(ui, &mut app.ui.tool_options.gradient_dither, tl!("Dither")); - // Live mode: the options also change a selected gradient fill layer. - crate::gradient_ui::options_changed(app, &before); - } - Tool::PerspectiveCrop => crate::perspective_crop_ui::options_bar(app, ui), - Tool::Crop => { - let before_ratio = crate::crop_ui::preset_ratio(app); - let doc_size = app.session.active().map_or((0.0, 0.0), |s| (f64::from(s.doc.size.width), f64::from(s.doc.size.height))); - // Ratios, sizes, saved presets, New / Delete Crop Preset… (#2443, #1919). - crate::crop_presets::dropdown(app, ui); - let o = &mut app.ui.tool_options; - let mut ratio_base = None; - if o.crop_ratio == crate::crop_size::WHR { - crate::crop_size::fields(o, ui); - } else { - // Keep partial edits in ToolOptions so the first side survives a frame; - // Original Ratio shows the document's numbers, as Photoshop does. - let (mut rw, mut rh) = crate::crop_size::custom_ratio_fields(o, doc_size); - let decimals = crate::crop_size::RATIO_DECIMALS; - let fw = widgets::value_field_prec(ui, &mut rw, 0.0..=99_999.0, "", 54.0, decimals); - let swap = icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked(); - let fh = widgets::value_field_prec(ui, &mut rh, 0.0..=99_999.0, "", 54.0, decimals); - let (cw, ch) = (fw.changed(), fh.changed()); - if swap { - std::mem::swap(&mut rw, &mut rh); - } - if cw || ch || swap { - crate::crop_size::set_custom_ratio_fields(o, rw, rh); - } - // Every ratio typed or scrubbed in one edit fits from the frame the edit - // started with: 1:3 on the way to 16:3 mustn't shrink it first (#7752). - let base_id = egui::Id::unique("crop-ratio-edit-base"); - if cw || ch { - ratio_base = ui.data(|d| d.get_temp::<[f64; 4]>(base_id)).or(app.ui.crop_rect); - } - if ![&fw, &fh].iter().any(|f| f.has_focus() || f.dragged()) { - ui.data_mut(|d| d.remove::<[f64; 4]>(base_id)); - } else if let Some(base) = ratio_base { - ui.data_mut(|d| d.insert_temp(base_id, base)); - } - } - widgets::vline(ui, 22.0); - if widgets::secondary_button(ui, tl!("Clear"), 0.0).clicked() { - crate::crop_size::clear_ratio(o); - } - crate::crop_straighten::options_button(&mut app.crop.straighten, ui); - crate::crop_overlay::options_button(o, ui); - let pick_shield_color = crate::crop_shield::options_button(&mut o.crop_shield, ui); - widgets::checkbox(ui, &mut o.crop_delete, tl!("Delete Cropped Pixels")); - // Fill: what a turned or extending crop puts where the image doesn't reach - // (#3823). Generative Expand is not offered. - ui.label(tl!("Fill:")); - widgets::dropdown( - ui, - "crop-fill", - tl!("Fill:"), - &mut o.crop_content_aware, - &[(false, tl!("Background (Default)")), (true, tl!("Content-Aware Fill"))], - 150.0, - ); - if crate::crop_ui::preset_ratio(app) != before_ratio { - match ratio_base { - Some(base) => crate::crop_ui::apply_ratio_from(app, base), - None => crate::crop_ui::apply_ratio(app), - } - } - if pick_shield_color { - crate::crop_shield::pick_custom_color(app); - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icons::button( - ui, - "check", - 26.0, - false, - &crate::i18n::fmt(tl!("Commit current crop operation ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]), - ) - .clicked() - { - crate::canvas::commit_crop(app); - } - if icons::button(ui, "ban", 26.0, false, tl!("Cancel current crop operation (Esc)")).clicked() { - crate::crop_ui::cancel(app); - } - }); - } - // Every theme gets the font, style and size controls (#1387), as with Auto-Select (#1275). - Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::options_bar(app, ui), - Tool::Move => { - let o = &mut app.ui.tool_options; - widgets::checkbox(ui, &mut o.move_auto_select, tl!("Auto-Select:")); - widgets::dropdown( - ui, - "move-target", - tl!("Auto-Select:"), - &mut o.move_target, - &[("layer".to_string(), tl!("Layer")), ("group".to_string(), tl!("Group"))], - 76.0, - ); - widgets::vline(ui, 22.0); - widgets::checkbox(ui, &mut o.move_show_transform, tl!("Show Transform Controls")); - widgets::vline(ui, 22.0); - crate::align_bar::options(app, ui); - } - Tool::Eyedropper => crate::eyedropper_ui::options(app, ui), - Tool::Zoom => { - // 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() { - 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() - && let Some(i) = app.session.active_index() - { - app.ui.views[i].zoom = 1.0; - 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; - app.ui.views[i].fill_pending = false; - } - } - Tool::RotateView => { - hint(ui, tl!("Drag around the centre to rotate the view · Shift constrains to 15°")); - if let Some(i) = app.session.active_index() { - ui.label(tl!("Angle")); - let mut angle = app.ui.views.get(i).map(|v| v.rotation).unwrap_or(0.0); - if widgets::value_field(ui, &mut angle, -180.0..=180.0, "°", 56.0).changed() - && let Some(v) = app.ui.views.get_mut(i) - { - v.rotation = crate::rotate_view::wrap_deg(angle); - } - if widgets::secondary_button(ui, tl!("Reset View"), 0.0).clicked() - && let Some(v) = app.ui.views.get_mut(i) - { - v.rotation = 0.0; - } - } - } - Tool::Hand => { - 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() - { - app.ui.views[i].zoom = 1.0; - 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; - app.ui.views[i].fill_pending = false; - } - 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; - app.ui.views[i].fill_pending = false; - } - if widgets::secondary_button(ui, tl!("Fill Screen"), 0.0).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; - } - } - // Retouching and smart-selection tools draw their bar in `retouch_ui::options_bar`. - _ => {} - } - // Painting symmetry is independent of visual theme. Keep the options-bar - // action available for Brush, Pencil and Eraser in every palette (#2659). - if matches!(tool, Tool::Brush | Tool::Pencil | Tool::Eraser) { - crate::symmetry_ui::menu(app, ui); - } - crate::brush_panel::commit_gesture(app, ui.ctx(), &brush_before, &brush); - }); - reveal_focused_control(ui); - }); - }); - }); -} - -/// Width of the Layers panel's Opacity and Fill fields, with room for their pop-up slider's ▾. -const LAYER_PCT_W: f32 = 66.0 + widgets::POPUP_ARROW_W; - -/// The `layer.setProps` edit of a Layers panel Opacity or Fill (`key`) field at `pct` percent. A -/// drag of the pop-up slider (`drag`) coalesces into one history step, as in Photoshop. -fn pct_action(target: &Value, key: &str, pct: f32, drag: Option) -> (String, Value) { - let mut p = target.clone(); - p[key] = json!(pct / 100.0); - if let Some(n) = drag { - p["coalesce"] = json!(format!("layer-{key}-slider:{n}")); - } - ("layer.setProps".into(), p) -} - fn label(ui: &mut egui::Ui, s: &str) { let t = Tokens::get(ui.ctx()); ui.label(RichText::new(s).color(t.text_dim)); } -/// Photoshop's scrubby Opacity/Fill labels: drag horizontally to change the percentage without -/// hitting the small number field. The unique drag ID coalesces every frame into one undo step. -fn scrub_pct_label(ui: &mut egui::Ui, text: &str, percent: &mut f32, max_w: f32) -> widgets::PopupFieldResponse { - // Elide to the room left in the row (full text on hover): a longer translation shrinks here - // instead of running over the fixed controls beside it (#3580). - let resp = widgets::elided_label_sensed(ui, text, max_w, Sense::click_and_drag()).on_hover_cursor(egui::CursorIcon::ResizeHorizontal); - let key = resp.id.with("percent-label-drag"); - if resp.drag_started() { - let stamp = ui.ctx().cumulative_pass_nr(); - ui.data_mut(|d| d.insert_temp(key, (*percent, stamp))); - } - let mut out = widgets::PopupFieldResponse::default(); - if resp.dragged() - && let Some((start, stamp)) = ui.data(|d| d.get_temp::<(f32, u64)>(key)) - && let (Some(origin), Some(pos)) = (ui.input(|i| i.pointer.press_origin()), resp.interact_pointer_pos()) - { - // Match DragValue's 0.5 percentage-point per screen point; do not jump on press. - let next = (start + (pos.x - origin.x) * 0.5).clamp(0.0, 100.0); - if next.is_finite() && next != *percent { - *percent = next; - out.changed = true; - out.drag = Some(stamp); - } - } - if resp.drag_stopped() { - ui.data_mut(|d| d.remove::<(f32, u64)>(key)); - } - out -} - -/// Width of `s` as [`label`] draws it (body text). -fn body_text_width(ui: &egui::Ui, s: &str) -> f32 { - let font = egui::TextStyle::Body.resolve(ui.style()); - ui.painter().layout_no_wrap(s.to_string(), font, Color32::WHITE).size().x -} - -/// Options-bar label: Photoshop writes "Size:" with a colon. -/// An options-bar label; one right before a value field scrubs it when dragged (Photoshop). -pub(crate) fn opt_label(ui: &mut egui::Ui, s: &str) { - let t = Tokens::get(ui.ctx()); - let text = if t.pro && !s.ends_with(':') { format!("{s}:") } else { s.to_string() }; - let label = ui.add(egui::Label::new(RichText::new(tl!(&text)).color(t.text_dim)).selectable(false)); - widgets::scrub_option_label(ui, &label); -} - -/// The largest Fixed Size side, in pixels. -pub(crate) const FIXED_SIZE_MAX_PX: f64 = 300_000.0; - -/// The resolution Fixed Size's units convert at (the active document's, 72 ppi without one) and -/// the document's size in pixels, which a percentage is of. The unit is the caller's. -fn fixed_size_units(app: &PhotocraftApp) -> (widgets::FieldUnits, [f64; 2]) { - let ppi = app.session.prefs().units_and_rulers.point_size.per_inch(); - let (dpi, size) = app - .session - .active() - .map_or((72.0, [1.0, 1.0]), |d| (f64::from(d.doc.resolution_dpi.max(1.0)), [f64::from(d.doc.size.width), f64::from(d.doc.size.height)])); - (widgets::FieldUnits { unit: photocraft_engine::prefs::Unit::Pixels, dpi, ppi }, size) -} - -/// One of Fixed Size's Width and Height (#7910): `px` shown in `units.unit` (a typed unit converts), -/// still stored in pixels. A right-click lists the units, as on the rulers; returns the one picked. -fn fixed_size_field(ui: &mut egui::Ui, px: &mut f32, units: widgets::FieldUnits, extent: f64) -> Option<&'static str> { - let widgets::FieldUnits { unit, dpi, ppi } = units; - let to_unit = |px: f64| unit.from_px(px, dpi, extent, ppi) as f32; - let before = to_unit(f64::from(*px)); - let mut v = before; - let places = unit.decimals() as u32; - let resp = widgets::value_field_extent(ui, &mut v, to_unit(1.0)..=to_unit(FIXED_SIZE_MAX_PX), unit.suffix(), 62.0, places, units, extent); - // Leaving the field re-reads the rounded text it showed (100 px at 72 ppi reads back as - // 1.389 in); that isn't an edit, so the pixels stay exact. - let shown = |x: f32| (f64::from(x) * 10f64.powi(places as i32)).round(); - if resp.changed() && shown(v) != shown(before) { - *px = unit.to_px(f64::from(v), dpi, extent, ppi).clamp(1.0, FIXED_SIZE_MAX_PX) as f32; - } - let mut picked = None; - resp.context_menu(|ui| picked = crate::rulers::unit_menu(ui, unit)); - picked -} - -fn percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) { - opt_label(ui, label); - let mut percent = *value * 100.0; - if widgets::value_field_named(ui, label, &mut percent, range, "%", width).changed() { - *value = percent / 100.0; - } -} - -fn hint(ui: &mut egui::Ui, s: &str) { - let t = Tokens::get(ui.ctx()); - ui.label(RichText::new(s).color(t.text_faint)); -} - -// ----------------------------------------------------------------------------- status bar - -/// The status bar's height and the height of the controls in it (zoom field, Fit), which leaves -/// them an even margin above and below inside the bar (#2823). -pub fn status_bar_heights(t: &Tokens) -> (f32, f32) { - if t.pro { (24.0, 18.0) } else { (30.0, 22.0) } -} - -pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - egui::Panel::bottom("status_bar") - .exact_size(status_bar_heights(&t).0) - .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(10, 0))) - .show(ui, |ui| { - let control_h = status_bar_heights(&t).1; - // Read from the right in a right-to-left UI, with the trailing group at the left. - crate::direction::horizontal_centered(ui, |ui| { - if t.pro { - crate::chrome_ui::status_bar_pro(app, ui); - // Background job progress with Cancel, at the far end (#210). - ui.with_layout(crate::direction::trailing(), |ui| { - crate::jobs_ui::status_progress(app, ui); - crate::background_redraw::status(app, ui); - crate::chrome_ui::gpu_memory_status(app, ui); - }); - return; - } - if let (Some(st), Some(i)) = (app.session.active(), app.session.active_index()) { - let (w, h, mode, bits, layers) = - (st.doc.size.width, st.doc.size.height, crate::canvas::mode_label(&st.doc), st.doc.depth.bits(), st.doc.layer_count()); - let mut pct = app.ui.views[i].zoom * 100.0; - if widgets::compact_wrapping_value_field(ui, &mut pct, crate::zoom_levels::percent_range(&app.ui.views[i]), "%", vec2(78.0, control_h)) - .accessible_name(tl!("Zoom")) - .changed() - { - app.ui.views[i].zoom = crate::zoom_levels::clamp(pct / 100.0, app.ui.views[i].doc_size); - app.ui.views[i].zoom_animating = false; - app.ui.views[i].zoom_anchor = None; - app.ui.views[i].fit_pending = false; - } - widgets::vline(ui, 16.0); - label(ui, &crate::i18n::fmt(tl!("{mode} Color · {bits} bit"), &[("mode", mode), ("bits", &bits.to_string())])); - widgets::vline(ui, 16.0); - label(ui, &format!("{w} × {h} px")); - widgets::vline(ui, 16.0); - label(ui, &crate::i18n::trn(crate::i18n::current(), layers as u64, "{n} layer", "{n} layers")); - } else { - label(ui, tl!("No document")); - } - if !app.ui.status.is_empty() { - widgets::vline(ui, 16.0); - let is_err = app.ui.status_error || app.ui.status.starts_with("Couldn"); - ui.label(RichText::new(&app.ui.status).color(if is_err { t.warning } else { t.text_faint })); - } - ui.with_layout(crate::direction::trailing(), |ui| { - if app.session.active().is_some() - && !t.pro - && widgets::compact_button(ui, tl!("Fit"), control_h).clicked() - && let Some(i) = app.session.active_index() - { - app.ui.views[i].fit_pending = true; - } - if app.session.has_jobs() { - ui.add_space(6.0); - crate::jobs_ui::status_progress(app, ui); - } - crate::background_redraw::status(app, ui); - crate::chrome_ui::gpu_memory_status(app, ui); - }); - }); - }); -} - -// ----------------------------------------------------------------------------- dock - -/// The panels and the canvas in the space left by the menus, bars and toolbar: craft-ui's -/// docking layout, with the icon rail at the window's end edge in the Studio themes. -pub fn dock_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - if app.ui.panels.rail && !t.pro { - rail(app, ui, &t); - } - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::panel_docking::show(app, ui)); - crate::dock::persist(app, ui.ctx()); -} - -/// 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) { - let t = Tokens::get(ui.ctx()); - let backdrop = if app.ui.view.hides_chrome() { egui::Color32::BLACK } else { crate::prefs_ui::pasteboard_color(app).unwrap_or(t.canvas) }; - if app.ui.panels.rail && t.pro { - rail(app, ui, &t); - } - egui::CentralPanel::default().frame(egui::Frame::NONE.fill(backdrop)).show(ui, |ui| crate::canvas::document_area(app, ui)); -} - -/// 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) }; - 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); - } - } - } - }); -} - -/// The dock's narrowest width (points). It is the right dock, on the left in a right-to-left UI. -pub(crate) const DOCK_MIN_WIDTH: f32 = 250.0; -/// What the dock leaves the toolbar and the canvas when it is widest (points). -const DOCK_LEAVES: f32 = 400.0; - -/// The dock's width range (points) in a window `window_width` wide: from [`DOCK_MIN_WIDTH`] to -/// everything but [`DOCK_LEAVES`], and never capped below the old 520, so two-column layouts can -/// be as wide as the window allows (#7896). -pub(crate) fn dock_width_range(window_width: f32) -> std::ops::RangeInclusive { - let max = if window_width.is_finite() { (window_width - DOCK_LEAVES).max(520.0) } else { 520.0 }; - DOCK_MIN_WIDTH..=max -} - -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. -pub fn request_dock_width(ctx: &egui::Context, w: f32) { - 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)); -} - -/// One dock group's tab content; `panel_docking` bounds it and scrolls it when it's taller. -pub(crate) fn dock_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, group: crate::dock::Group, tab: usize) { - use crate::dock::Group; - let pro = Tokens::get(ui.ctx()).pro; - match (group, tab) { - (Group::Color, 2) => crate::preset_panels::gradients_panel(app, ui), - (Group::Color, 3) => crate::preset_panels::patterns_panel(app, ui), - // The Color tab is the same in every theme, in the mode picked from its panel menu - // (#6000); only the tab order differs between themes. - (Group::Color, tab) if group.tabs(pro).get(tab) == Some(&"Color") => crate::color_panel_ui::panel(app, ui), - (Group::Color, _) => crate::swatches_ui::panel(app, ui), - (Group::Properties, 0) => properties_body(app, ui), - (Group::Properties, _) => adjustments_grid(app, ui), - (Group::Character, tab) => crate::type_tool::character_panel(app, ui, tab == 1), - (Group::Navigator, 0) => navigator(app, ui), - (Group::Navigator, 1) => crate::histogram_panel::show(app, ui), - (Group::Navigator, _) => info_panel(app, ui), - (Group::History, 0) => history(app, ui), - (Group::History, 1) => crate::actions::panel(app, ui), - (Group::History, _) => crate::comps_ui::panel(app, ui), - (Group::Layers, 0) => layers(app, ui), - (Group::Layers, 1) => channels(app, ui), - (Group::Layers, _) => crate::vector_ui::paths_panel(app, ui), - (Group::Brushes, _) => crate::brushes_tab::show(app, ui), - } -} - -/// The active document's pixel under the pointer, if the pointer is over the image. -pub(crate) fn hover_pixel(app: &PhotocraftApp) -> Option<(i32, i32)> { - let size = app.session.active()?.doc.size; - app.hover_doc.map(|p| (p[0].floor() as i32, p[1].floor() as i32)).filter(|(x, y)| *x >= 0 && *y >= 0 && *x < size.width as i32 && *y < size.height as i32) -} - -/// The colour the Info panel reads at document pixel `(x, y)`, straight RGBA 0..1: averaged over -/// the Eyedropper's Sample Size, as in Photoshop (#1649), and cached per pixel and revision. -pub(crate) fn pointer_sample(app: &mut PhotocraftApp, (x, y): (i32, i32)) -> Option<[f32; 4]> { - let rev = app.session.active()?.revision; - let sample_size = app.ui.tool_options.eyedropper_size; - if let Some(((cx, cy, cr, cs), v)) = app.info_sample - && (cx, cy, cr, cs) == (x, y, rev, sample_size) - { - return Some(v); - } - let params = json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5, "size": sample_size}); - let v: Vec = serde_json::from_value(app.session.execute("document.sampleColor", params).ok()?).ok()?; - let v = [*v.first()?, *v.get(1)?, *v.get(2)?, *v.get(3)?]; - app.info_sample = Some(((x, y, rev, sample_size), v)); - Some(v) -} - -/// Photoshop's Info panel: colour under the pointer (RGB and CMYK), position, selection size. -fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - let Some(st) = app.session.active() else { - empty(ui, tl!("No document")); - return; - }; - let (size, origin) = (st.doc.size, st.doc.ruler_origin); - let cmyk_space = photocraft_compose::cmyk_space(&st.doc); - // Positions and sizes in the ruler unit (Preferences › Units & Rulers). - let units = app.session.prefs().units_and_rulers.clone(); - let dpi = st.doc.resolution_dpi as f64; - let fx = move |px: f64| units.format(px, dpi, size.width as f64); - let units_y = app.session.prefs().units_and_rulers.clone(); - let fy = move |px: f64| units_y.format(px, dpi, size.height as f64); - let sel = st.doc.selection.as_ref().map(photocraft_compose::bounds::content_bounds); - let pos = hover_pixel(app); - // While a guide is dragged (#5728), the Info panel shows its position in one axis only, even - // when the pointer is outside the canvas (ruler drags do not update `hover_doc` there). - let (guide_x, guide_y) = match app.guide_drag { - Some(d) if d.vertical => (Some(d.pos), None), - Some(d) => (None, Some(d.pos)), - None => (None, None), - }; - let rgba = pos.and_then(|p| pointer_sample(app, p)); - let mono = theme::mono(11.5); - let row = |ui: &mut egui::Ui, k: &str, v: String| { - ui.horizontal(|ui| { - ui.add_sized([18.0, 16.0], egui::Label::new(RichText::new(k).color(t.text_dim).size(11.5))); - ui.label(RichText::new(v).font(mono.clone()).color(t.text)); - }); - }; - ui.columns(2, |cols| { - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; - let dash = || "—".to_string(); - row(&mut cols[0], "R:", rgba.map_or_else(dash, |c| q(c[0]).to_string())); - row(&mut cols[0], "G:", rgba.map_or_else(dash, |c| q(c[1]).to_string())); - row(&mut cols[0], "B:", rgba.map_or_else(dash, |c| q(c[2]).to_string())); - // Colour-managed CMYK in percent like Photoshop's readout, through the same conversion as - // the Color Picker (#8101) and the Color Sampler readout (`sampler_cmds::device_cmyk`). - let cmyk = - rgba.map(|c| photocraft_color::convert::with_cmyk_space(cmyk_space.as_ref(), || photocraft_engine::sampler_cmds::device_cmyk(c[0], c[1], c[2]))); - for (i, k) in ["C:", "M:", "Y:", "K:"].iter().enumerate() { - row(&mut cols[1], k, cmyk.map_or_else(dash, |c| format!("{}%", c[i]))); - } - }); - widgets::hairline(ui); - ui.columns(2, |cols| { - let dash = || "—".to_string(); - // Measured from the rulers' zero point (#2955). - row(&mut cols[0], "X:", guide_x.map(|p| fx(p - origin[0])).or_else(|| pos.map(|p| fx(p.0 as f64 - origin[0]))).unwrap_or_else(dash)); - row(&mut cols[0], "Y:", guide_y.map(|p| fy(p - origin[1])).or_else(|| pos.map(|p| fy(p.1 as f64 - origin[1]))).unwrap_or_else(dash)); - row(&mut cols[1], "W:", sel.map_or_else(dash, |r| fx(r.width() as f64))); - row(&mut cols[1], "H:", sel.map_or_else(dash, |r| fy(r.height() as f64))); - }); - widgets::hairline(ui); - ui.label( - RichText::new(crate::i18n::fmt(tl!("Doc: {w} × {h} px"), &[("w", &size.width.to_string()), ("h", &size.height.to_string())])) - .color(t.text_dim) - .size(11.5), - ); - // Color Sampler points (#1046): each under its number, with its position in the current ruler - // unit and the same RGB/CMYK readout as the pointer (one composite pixel each). - let samplers = sampler_readouts(app); - if !samplers.is_empty() { - widgets::hairline(ui); - let cell = |ui: &mut egui::Ui, s: String| { - ui.label(RichText::new(s).font(mono.clone()).color(t.text)); - }; - for s in samplers.iter() { - let n = s["number"].as_i64().unwrap_or(0); - let at = s["position"] - .as_array() - .map_or((0.0, 0.0), |a| (a.first().and_then(Value::as_f64).unwrap_or(0.0), a.get(1).and_then(Value::as_f64).unwrap_or(0.0))); - let num = |v: &Value, i: usize| v.get(i).and_then(Value::as_i64).map_or_else(|| "—".to_string(), |n| n.to_string()); - let (rgb, cmyk) = (&s["rgb"], &s["cmyk"]); - ui.horizontal(|ui| { - ui.add_sized([24.0, 16.0], egui::Label::new(RichText::new(format!("#{n}")).color(t.text_dim).size(11.5))); - cell(ui, format!("X: {} Y: {}", fx(at.0), fy(at.1))); - }); - ui.horizontal(|ui| { - ui.add_sized([24.0, 16.0], egui::Label::new(RichText::new("").size(11.5))); - cell(ui, format!("R:{} G:{} B:{}", num(rgb, 0), num(rgb, 1), num(rgb, 2))); - }); - ui.horizontal(|ui| { - ui.add_sized([24.0, 16.0], egui::Label::new(RichText::new("").size(11.5))); - cell(ui, format!("C:{}% M:{}% Y:{}% K:{}%", num(cmyk, 0), num(cmyk, 1), num(cmyk, 2), num(cmyk, 3))); - }); - } - } -} - -/// The Info panel's Color Sampler readouts and the (document, revision) they were composited for. -pub(crate) type SamplerReadouts = ((photocraft_doc::DocId, u64), std::sync::Arc>); - -/// The Color Sampler readouts of the active document, composited once per revision (#4528): -/// adding, moving or deleting a sampler and every pixel edit bump the revision, so between them -/// the Info panel reuses them instead of compositing each point through the stack every frame. -pub(crate) fn sampler_readouts(app: &mut PhotocraftApp) -> std::sync::Arc> { - let Some(key) = app.session.active().map(|s| (s.doc.id, s.revision)) else { return std::sync::Arc::default() }; - if let Some((k, v)) = &app.info_samplers - && *k == key - { - return v.clone(); - } - let list = app.session.execute("view.colorSamplers.list", json!({})).ok(); - let v = std::sync::Arc::new(list.as_ref().and_then(|v| v["samplers"].as_array()).cloned().unwrap_or_default()); - app.info_samplers = Some((key, v.clone())); - v -} - -fn navigator(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - let Some(idx) = app.session.active_index() else { - empty(ui, tl!("No document")); - return; - }; - let ctx = ui.ctx().clone(); - let size = app.session.documents()[idx].doc.size; - let avail = ui.available_width(); - // The preview fills the group's height above the zoom controls (their height as measured - // last frame), so it grows when the group is made taller, as in Photoshop (#2726). - let controls_h = ui.data(|d| d.get_temp::(navigator_controls_id())).unwrap_or(48.0); - let left = ui.available_height() - controls_h; - let box_h = if left.is_finite() { left.max(40.0) } else { 150.0 }; - let (frame, resp) = ui.allocate_exact_size(vec2(avail, box_h), Sense::click_and_drag()); - ui.painter().rect_filled(frame, t.radius_sm, t.canvas); - let rect = navigator_fit(frame, size.width, size.height); - ui.data_mut(|d| d.insert_temp(navigator_preview_id(), rect)); - // On the GPU canvas, its own texture at this size (#4518); otherwise the CPU thumbnail. - if let Some(params) = crate::canvas::navigator_gpu_view(app, idx, rect, &ctx) { - crate::gpu_canvas::GpuCanvas::paint(ui.painter(), rect, params); - } else if crate::canvas::navigator_waits_for_gpu(app, idx, &ctx) { - widgets::checker(ui.painter(), rect, 6.0); - } else { - let Some(tex) = crate::canvas::navigator_texture(app, &ctx, idx) else { return }; - widgets::checker(ui.painter(), rect, 6.0); - ui.painter().image(tex, rect, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE); - } - let s = rect.width() / size.width.max(1) as f32; - // ⌘/Ctrl-drag over the preview draws a rectangle the view then zooms to, as in Photoshop - // (#6872); a plain click or drag moves the view. - let command = crate::workspace_ui::sticky_mods(app, ctx.input(|i| i.modifiers)).command; - if resp.drag_started() && command { - let start = ctx.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()); - ui.data_mut(|d| match start { - Some(p) => { - d.insert_temp(navigator_zoom_drag_id(), p); - } - None => d.remove::(navigator_zoom_drag_id()), - }); - } - let zoom_from = ui.data(|d| d.get_temp::(navigator_zoom_drag_id())); - if let Some(from) = zoom_from { - if let Some(to) = resp.interact_pointer_pos() { - let r = Rect::from_two_pos(from, to).intersect(rect); - crate::tool_feedback::draw_ants(ui.painter(), &[r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()], true); - if resp.drag_stopped() { - let doc_rect = Rect::from_min_max(((r.min - rect.min) / s).to_pos2(), ((r.max - rect.min) / s).to_pos2()); - let (canvas, ppp, aspect) = (app.last_canvas_rect, app.canvas_ppp(), app.ui.view.display_aspect()); - navigator_zoom_to(&mut app.ui.views[idx], doc_rect, [size.width, size.height], canvas.size(), ppp, aspect); - } - } - if resp.drag_stopped() || !resp.dragged() { - ui.data_mut(|d| d.remove::(navigator_zoom_drag_id())); - } - } else if (resp.clicked() || resp.dragged()) - && let Some(pp) = resp.interact_pointer_pos() - { - let d = (pp - rect.min) / s; - app.ui.views[idx].center = [d.x.clamp(0.0, size.width as f32), d.y.clamp(0.0, size.height as f32)]; - app.ui.views[idx].zoom_animating = false; - app.ui.views[idx].zoom_anchor = None; - app.ui.views[idx].fit_pending = false; - } - if command && resp.hovered() { - ctx.set_cursor_icon(egui::CursorIcon::ZoomIn); - } - // The Navigator has its own zoom target: an unmodified wheel over the preview - // should zoom even when the document canvas is configured to scroll on wheel. - // Use the canvas wheel classifier to honour one ×1.1 step per notch, - // eased over its frames or instant as General › Animated Zoom says. - let pinch_zooms = app.session.prefs().enhanced_controls.zoom_with_trackpad_pinch; - let animated_zoom = app.session.prefs().general.animated_zoom; - let touch_gestures = app.session.prefs().enhanced_controls.touch_gestures; - let navigator_wheel = egui::Id::unique("pc-navigator-wheel"); - if resp.hovered() - && let Some(crate::wheel_nav::Wheel::Zoom(factor)) = - crate::wheel_nav::read_with(&ctx, true, pinch_zooms, animated_zoom, navigator_wheel, true, true, touch_gestures) - { - let view = &mut app.ui.views[idx]; - let next = crate::zoom_levels::clamp(view.zoom * factor, view.doc_size); - if next != view.zoom * factor { - crate::wheel_nav::settle(&ctx, navigator_wheel); - } - if next != view.zoom { - view.zoom = next; - view.zoom_animating = false; - view.zoom_anchor = None; - view.fit_pending = false; - } - } - // Visible-area rectangle. - let v = app.ui.views[idx].clone(); - let canvas = app.last_canvas_rect; - let (zoom, center) = - if v.zoom_animating && app.session.prefs().general.animated_zoom { v.display_camera.unwrap_or((v.zoom, v.center)) } else { (v.zoom, v.center) }; - let point_zoom = (zoom / app.canvas_ppp()).max(1e-6); - // Pixel aspect correction shows fewer document columns across the same canvas width. - let vw = canvas.width() / point_zoom / app.ui.view.display_aspect() * s; - let vh = canvas.height() / point_zoom * s; - let c = pos2(rect.min.x + center[0] * s, rect.min.y + center[1] * s); - let vr = Rect::from_center_size(c, vec2(vw, vh)).intersect(frame.shrink(1.0)); - ui.painter().rect_stroke(vr, 2.0, Stroke::new(1.5, Color32::from_rgb(255, 84, 84)), StrokeKind::Middle); - // Photoshop's one row under the preview (#4840): the zoom, typed in percent, then Zoom Out, - // the slider and Zoom In. - let controls = ui.vertical(|ui| { - ui.add_space(4.0); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - let set = |app: &mut PhotocraftApp, zoom: f32, animate: bool| { - let target = crate::zoom_levels::clamp(zoom, v.doc_size); - if target != app.ui.views[idx].zoom { - app.ui.views[idx].zoom = target; - app.ui.views[idx].request_zoom_animation(animate && app.session.prefs().general.animated_zoom); - } - app.ui.views[idx].fit_pending = false; - }; - let mut pct = v.zoom * 100.0; - let field = widgets::compact_wrapping_value_field(ui, &mut pct, crate::zoom_levels::percent_range(&app.ui.views[idx]), "%", vec2(64.0, NAV_ROW_H)) - .accessible_name(tl!("Zoom")); - if field.changed() { - set(app, pct / 100.0, false); - } - let out = crate::brush_picker::named(icons::button(ui, "minus", NAV_ROW_H, false, tl!("Zoom Out")), "Zoom Out"); - if out.clicked() { - set(app, crate::zoom_levels::step(v.zoom, -1, v.doc_size), true); - } - // The whole zoom range, and always the current zoom: a narrower slider would pull it back. - let (lo, hi) = (crate::zoom_levels::min(v.doc_size).min(v.zoom).log2(), crate::zoom_levels::MAX.max(v.zoom).log2()); - let mut lz = v.zoom.log2(); - let slider_w = (ui.available_width() - NAV_ROW_H - 4.0).max(60.0); - let slid = ui.allocate_ui(vec2(slider_w, NAV_ROW_H), |ui| lz.is_finite() && widgets::slider(ui, &mut lz, lo..=hi, None).changed()).inner; - if slid { - set(app, 2f32.powf(lz), false); - } - let zin = crate::brush_picker::named(icons::button(ui, "plus", NAV_ROW_H, false, tl!("Zoom In")), "Zoom In"); - if zin.clicked() { - set(app, crate::zoom_levels::step(v.zoom, 1, v.doc_size), true); - } - }); - }); - // From the preview's bottom, so the spacing above the controls counts too. - let controls = Rect::from_min_max(pos2(frame.left(), frame.bottom()), pos2(frame.right(), controls.response.rect.bottom())); - ui.data_mut(|d| { - d.insert_temp(navigator_controls_id(), controls.height()); - d.insert_temp(navigator_controls_rect_id(), controls); - }); -} - -/// Height of the Navigator's zoom row: its field, buttons and slider. -const NAV_ROW_H: f32 = 22.0; - -/// The document's `w` × `h` fitted inside the Navigator's `frame` with an 8 pt inset, centred and -/// keeping its aspect. -fn navigator_fit(frame: Rect, w: u32, h: u32) -> Rect { - let inner = (frame.size() - vec2(16.0, 16.0)).max(vec2(1.0, 1.0)); - let (w, h) = (w.max(1) as f32, h.max(1) as f32); - let s = (inner.x / w).min(inner.y / h); - Rect::from_center_size(frame.center(), vec2(w * s, h * s)) -} - -/// Where a ⌘/Ctrl-drag over the Navigator's preview started, while it lasts. -fn navigator_zoom_drag_id() -> egui::Id { - egui::Id::unique("navigator-zoom-drag") -} - -/// Zoom `view` so the document rectangle `doc_rect` (pixels) fills a canvas of `canvas` points, -/// centred on it, as a Navigator ⌘/Ctrl-drag does (#6872). `doc` is the document's size in -/// pixels (the view's own copy is only set once the canvas has been drawn), `ppp` the canvas's -/// device pixels per point and `aspect` the pixel aspect ratio shown; the zoom stays within the -/// zoom range. A rectangle under 2 document pixels across zooms one step in on its centre. -fn navigator_zoom_to(view: &mut crate::state::View, doc_rect: Rect, doc: [u32; 2], canvas: egui::Vec2, ppp: f32, aspect: f32) { - // Checked before clipping: `min`/`max` would turn a NaN edge into a document edge. - if ![doc_rect.min.x, doc_rect.min.y, doc_rect.max.x, doc_rect.max.y].iter().all(|v| v.is_finite()) { - return; - } - let (w, h) = (doc[0] as f32, doc[1] as f32); - let r = doc_rect.intersect(Rect::from_min_size(Pos2::ZERO, vec2(w, h))); - if r.width() < 0.0 || r.height() < 0.0 { - return; - } - let aspect = if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 }; - let zoom = if r.width() < 2.0 || r.height() < 2.0 || canvas.x <= 0.0 || canvas.y <= 0.0 { - crate::zoom_levels::step(view.zoom, 1, view.doc_size) - } else { - // Document columns shown across the canvas are `canvas.x / (point_zoom * aspect)`. - let point_zoom = (canvas.x / (r.width() * aspect)).min(canvas.y / r.height()); - point_zoom * ppp - }; - if !zoom.is_finite() { - return; - } - view.zoom = crate::zoom_levels::clamp(zoom, view.doc_size); - view.center = [r.center().x, r.center().y]; - view.fit_pending = false; - view.request_zoom_animation(false); -} - -fn navigator_preview_id() -> egui::Id { - egui::Id::unique("navigator-preview-rect") -} - -fn navigator_controls_id() -> egui::Id { - egui::Id::unique("navigator-controls-height") -} - -fn navigator_controls_rect_id() -> egui::Id { - egui::Id::unique("navigator-controls-rect") -} - -/// Where the Navigator drew its document preview last frame. -#[cfg(test)] -pub(crate) fn last_navigator_preview(ctx: &egui::Context) -> Option { - ctx.data(|d| d.get_temp(navigator_preview_id())) -} - -/// The Navigator's zoom controls (below the preview) last frame. -#[cfg(test)] -pub(crate) fn last_navigator_controls(ctx: &egui::Context) -> Option { - ctx.data(|d| d.get_temp(navigator_controls_rect_id())) -} - #[cfg(test)] mod navigator_wheel_tests { use super::*; @@ -2559,2397 +459,6 @@ fn empty(ui: &mut egui::Ui, s: &str) { ui.add_space(6.0); } -// ----------------------------------------------------------------------------- layers - -/// The simple themes' single lock button. On the Background it converts the layer to a normal -/// one, as clicking the Background's lock does in Photoshop. Elsewhere it clears every lock when -/// any is set, and locks all otherwise. Toggling only "lock all" would leave the Background's -/// transparency lock (still showing as locked), and a second click would lock its pixels, -/// shutting out the Eraser and every other paint tool (#76). -/// The Basic layout's lock toggle: the active layer's state decides, and every target follows it -/// (`targets`: `{"layer": id}` or `{"layers": [ids]}`). -fn simple_lock_toggle(background: bool, l: &Layer, targets: &Value) -> (String, Value) { - if background { - return ("layer.new.layerFromBackground".into(), json!({})); - } - let locks = - if l.locks.any() { json!({"transparency": false, "pixels": false, "position": false, "artboard": false, "all": false}) } else { json!({"all": true}) }; - let mut p = targets.clone(); - p["locks"] = locks; - ("layer.setProps".into(), p) -} - -/// The Layers panel's blend modes: Photoshop's, plus the layer's own Paint.NET mode when it has one -/// (an imported `.pdn`), so the menu matches Photoshop's for every other layer. -fn blend_options(groups: bool, current: BlendMode) -> Vec<(BlendMode, &'static str)> { - let own = Some(current).filter(|m| !m.has_psd_equivalent()); - std::iter::once(BlendMode::PassThrough).filter(|_| groups).chain(BlendMode::LAYER_MODES).chain(own).map(|m| (m, m.label())).collect() -} - -/// Scroll the Layers panel while holding a layer drag over its top/bottom edge or past them. -/// -/// Returns the *content* displacement in points for this frame, so positive moves the -/// list downward (reveals rows above) and negative upward (reveals rows below). -/// The speed ramps with proximity to the edge and clamps to the maximum speed when -/// dragged outside, using elapsed time instead of assuming a particular refresh rate. -pub(crate) fn layer_drag_edge_scroll(pointer: Option, viewport: Rect, dragging: bool, dt: f32) -> f32 { - if !dragging || viewport.width() <= 0.0 || viewport.height() <= 0.0 || dt.is_nan() || dt <= 0.0 { - return 0.0; - } - let Some(pointer) = pointer.filter(|p| p.x.is_finite() && p.y.is_finite() && p.x >= viewport.left() && p.x <= viewport.right()) else { - return 0.0; - }; - let edge = 32.0_f32.min(viewport.height() * 0.25); - let top = ((edge - (pointer.y - viewport.top())) / edge).clamp(0.0, 1.0); - let bottom = ((edge - (viewport.bottom() - pointer.y)) / edge).clamp(0.0, 1.0); - let direction = top - bottom; - if direction == 0.0 { - return 0.0; - } - let velocity = 80.0 + 520.0 * direction.abs(); - direction.signum() * velocity * dt.clamp(0.0, 0.05) -} - -/// Fit blend mode + Opacity into the available Layers-panel width (#2309). -/// Preserve the normal translated label when there is room; on a narrow dock, -/// keep the field interactive and give the dropdown the remaining width. -fn opacity_row_layout(available: f32, label_width: f32, gap: f32) -> (f32, bool) { - let full_right = label_width + LAYER_PCT_W + 2.0 * gap + 16.0; - // The label shows while the blend dropdown keeps a usable width (at the default dock width - // with an English label it does; a long translated label on a narrow dock gives way). - let show_label = available >= full_right + 80.0; - let reserved = LAYER_PCT_W + gap + if show_label { label_width + gap + 16.0 } else { 0.0 }; - ((available - reserved).max(40.0), show_label) -} - -/// Blend mode, Opacity, the locks and Fill with no layer selected: Photoshop keeps them in place, -/// greyed out at Normal, 100% and unlocked, instead of removing them (#8880). Same layout as the -/// active layer's rows in `layers`. -fn inactive_blend_rows(ui: &mut egui::Ui, pro: bool) { - ui.add_enabled_ui(false, |ui| { - ui.horizontal(|ui| { - let opacity_label = if pro { tl!("Opacity:") } else { tl!("Opacity") }; - let (blend_width, show_opacity_label) = opacity_row_layout(ui.available_width(), body_text_width(ui, opacity_label), ui.spacing().item_spacing.x); - let mut m = BlendMode::Normal; - let options = blend_options(false, m); - widgets::dropdown_wheel_hovered(ui, "blend", tl!("Blend Mode"), &mut m, &options, blend_width); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut o = 100.0; - widgets::popup_value_field(ui, opacity_label, &mut o, 0.0..=100.0, "%", LAYER_PCT_W); - if show_opacity_label { - scrub_pct_label(ui, opacity_label, &mut o, ui.available_width()); - } - }); - }); - ui.add_space((theme::ROW_GAP - ui.spacing().item_spacing.y).max(0.0)); - ui.horizontal(|ui| { - let lock_label = if pro { tl!("Lock:") } else { tl!("Lock") }; - let lang = crate::i18n::current(); - let fill_label = if pro { crate::i18n::tr_ctx(lang, "layers", "Fill:") } else { crate::i18n::tr_ctx(lang, "layers", "Fill") }; - let gap = ui.spacing().item_spacing.x; - let icons_w = if pro { 5.0 * 20.0 + gap } else { 22.0 + gap }; - let fits = body_text_width(ui, lock_label) + icons_w + body_text_width(ui, fill_label) + LAYER_PCT_W + 2.0 * gap <= ui.available_width(); - if fits { - label(ui, lock_label); - } - if pro { - ui.scope(|ui| { - ui.spacing_mut().item_spacing.x = 0.0; - for (icon, tip) in [ - ("grid-3x3", tl!("Lock transparent pixels")), - ("brush", tl!("Lock image pixels")), - ("move", tl!("Lock position")), - ("scan", tl!("Prevent auto-nesting in and out of Artboards and Frames")), - ("lock", tl!("Lock all")), - ] { - icons::button(ui, icon, 20.0, false, tip); - } - }); - } else { - icons::button(ui, "lock-open", 22.0, false, tl!("Lock layer")); - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut f = 100.0; - widgets::popup_value_field(ui, fill_label, &mut f, 0.0..=100.0, "%", LAYER_PCT_W); - scrub_pct_label(ui, fill_label, &mut f, ui.available_width()); - }); - }); - ui.add_space(2.0); - }); -} - -fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - // A new active layer opens its parent groups and is scrolled into view (#152). - let reveal = crate::layer_reveal::track(app, ui.ctx()); - let Some(st) = app.session.active() else { - empty(ui, tl!("No document")); - return; - }; - let doc = st.doc.clone(); - let active = st.active_layer; - let active_layer = active.and_then(|id| doc.layer(id)); - let selection = st.selected_layers(); - let isolated = st.isolated_layers.clone(); - let mut actions: Vec<(String, Value)> = Vec::new(); - - let t = Tokens::get(ui.ctx()); - app.reorder_preview_hit = false; - if !ui.input(|i| i.pointer.primary_down()) || !app.ui.layers_panel_options.preview_on_canvas_when_reordering_layers { - app.reorder_preview = None; - } - if t.pro && app.ui.layers_panel_options.show_filters { - crate::layer_filter_ui::bar(app, ui); - ui.add_space(4.0); - } - if let Some(l) = active_layer { - // With several layers selected, blend mode, Opacity, Fill and the locks change every one - // of them, as in Photoshop; the controls show the active layer's values. - // The Background stays out of a several-layer change until Photoshop's behaviour is - // confirmed (#5856): Opacity, Fill or a blend mode would turn it into Layer 0. - let ids: Vec = if selection.len() > 1 && selection.contains(&l.id) { - selection.iter().copied().filter(|id| *id == l.id || !doc.layer(*id).is_some_and(|x| crate::doc_props_ui::is_background(&doc, x))).collect() - } else { - vec![l.id] - }; - let targets = if ids.len() > 1 { json!({"layers": ids.iter().map(|id| id.0).collect::>()}) } else { json!({"layer": l.id.0}) }; - // Photoshop greys blend mode, Opacity and Fill for the Background layer. (With the - // Background among several selected, what Photoshop does awaits a check: #5856.) - let bg = crate::doc_props_ui::is_background(&doc, l); - // Pass Through is a group's mode: offered only when every target is a group. - let all_groups = ids.iter().all(|id| doc.layer(*id).is_some_and(|x| x.is_group())); - ui.horizontal(|ui| { - ui.add_enabled_ui(!bg, |ui| { - let mut m = l.blend; - // Reserve space for the numeric field first. On a narrow dock, hide the - // redundant visible Opacity label rather than force the dropdown beyond - // the panel's right edge (#2309). The numeric field keeps its name. - let opacity_label = if t.pro { tl!("Opacity:") } else { tl!("Opacity") }; - let (blend_width, show_opacity_label) = - opacity_row_layout(ui.available_width(), body_text_width(ui, opacity_label), ui.spacing().item_spacing.x); - let (chosen, hovered) = - widgets::dropdown_wheel_hovered(ui, "blend", tl!("Blend Mode"), &mut m, &blend_options(all_groups, l.blend), blend_width); - // One step per choice: a click, an arrow key or each wheel notch (#1747). - for m in &chosen { - let mut p = targets.clone(); - p["blend"] = json!(m.label()); - actions.push(("layer.setProps".into(), p)); - } - // Hovering a mode previews it on the canvas (#970). - crate::blend_preview::hover(app, &ids, hovered.filter(|_| chosen.is_empty())); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut o = l.opacity * 100.0; - let field = widgets::popup_value_field(ui, opacity_label, &mut o, 0.0..=100.0, "%", LAYER_PCT_W); - // On a narrow dock the (scrubby) label yields its room to the controls (#2309). - let scrub = if show_opacity_label { - scrub_pct_label(ui, opacity_label, &mut o, ui.available_width()) - } else { - widgets::PopupFieldResponse::default() - }; - if field.changed || scrub.changed { - actions.push(pct_action(&targets, "opacity", o, scrub.drag.or(field.drag))); - } - }); - }); - }); - // Docks zero the item spacing: keep the Opacity and Fill fields apart (#155). - ui.add_space((theme::ROW_GAP - ui.spacing().item_spacing.y).max(0.0)); - ui.horizontal(|ui| { - let lock_label = if t.pro { tl!("Lock:") } else { tl!("Lock") }; - // Layer fill opacity (≠ Edit › Fill / path fill → Tô). - let lang = crate::i18n::current(); - let fill_label = if t.pro { crate::i18n::tr_ctx(lang, "layers", "Fill:") } else { crate::i18n::tr_ctx(lang, "layers", "Fill") }; - // In a narrow panel with long translated labels, drop the "Lock:" text (the icons keep - // their tooltips) rather than let the Fill label run over the lock icons. - let gap = ui.spacing().item_spacing.x; - let icons_w = if t.pro { 5.0 * 20.0 + gap } else { 22.0 + gap }; - let fits = body_text_width(ui, lock_label) + icons_w + body_text_width(ui, fill_label) + LAYER_PCT_W + 2.0 * gap <= ui.available_width(); - if fits { - label(ui, lock_label); - } - if t.pro { - // The lock icons touch, but only they: the Fill label keeps the same gap before its - // field as Opacity's, so both stack in one right-aligned column (#2085). - ui.scope(|ui| { - ui.spacing_mut().item_spacing.x = 0.0; - let lk = l.locks; - for (key, icon, tip, on) in [ - ("transparency", "grid-3x3", tl!("Lock transparent pixels"), lk.transparency), - ("pixels", "brush", tl!("Lock image pixels"), lk.pixels), - ("position", "move", tl!("Lock position"), lk.position), - ("artboard", "scan", tl!("Prevent auto-nesting in and out of Artboards and Frames"), lk.artboard), - ("all", "lock", tl!("Lock all"), lk.all), - ] { - // Lock Image Pixels includes Lock Transparent Pixels, which waits for it (#4892). - let enabled = key != "transparency" || !lk.pixels; - if ui.add_enabled_ui(enabled, |ui| icons::button(ui, icon, 20.0, on, tip)).inner.clicked() { - let mut p = targets.clone(); - p["locks"] = json!({ key: !on }); - actions.push(("layer.setProps".into(), p)); - } - } - }); - } - if !t.pro { - let locked = l.locks.any(); - if icons::button(ui, if locked { "lock" } else { "lock-open" }, 22.0, locked, tl!("Lock layer")).clicked() { - actions.push(simple_lock_toggle(crate::doc_props_ui::is_background(&doc, l), l, &targets)); - } - } - ui.add_enabled_ui(!bg, |ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut f = l.fill_opacity * 100.0; - let field = widgets::popup_value_field(ui, fill_label, &mut f, 0.0..=100.0, "%", LAYER_PCT_W); - let scrub = scrub_pct_label(ui, fill_label, &mut f, ui.available_width()); - if field.changed || scrub.changed { - actions.push(pct_action(&targets, "fill", f, scrub.drag.or(field.drag))); - } - }) - }); - }); - ui.add_space(2.0); - } else { - inactive_blend_rows(ui, t.pro); - } - - // Top of the stack first, groups above their contents, closed groups' contents hidden (#126). - let rows = crate::layer_tree_ui::panel_rows(app, &doc); - let ctx = ui.ctx().clone(); - let footer = widgets::footer_height(ui) + ui.spacing().item_spacing.y; - let fill = ui.available_height() > footer + 60.0; - let rows_h = if fill { ui.available_height() - footer } else { f32::INFINITY }; - egui::ScrollArea::vertical() - // Keep each document's position independent, even when tab indices change (#5522). - .id_salt(("layer-rows", doc.id.0)) - .max_height(rows_h) - .min_scrolled_height(if fill { rows_h } else { 0.0 }) - .auto_shrink([false, !fill]) - .show(ui, |ui| { - // The drag keys are set only by actual layer-row and fx drags, not clicks or - // ordinary scrolling. The ScrollArea applies this to its own content. - // An fx drag that never saw its release (the panel was hidden) must not outlive the button. - if !ctx.input(|i| i.pointer.primary_down() || i.pointer.any_released()) { - ctx.data_mut(|d| d.remove::(fx_drag_key())); - ctx.data_mut(|d| d.remove::(mask_drag_key())); - ctx.data_mut(|d| d.remove::(crate::smart_ui::drag_key())); - } - let held = ctx.data(|d| { - d.get_temp::(egui::Id::unique("layer-drag")).is_some() - || d.get_temp::(fx_drag_key()).is_some() - || d.get_temp::(crate::smart_ui::drag_key()).is_some() - }); - let dragging = held && ctx.input(|i| i.pointer.primary_down()); - let pointer = ctx.input(|i| i.pointer.interact_pos()); - let delta = layer_drag_edge_scroll(pointer, ui.clip_rect(), dragging, ctx.input(|i| i.stable_dt)); - if delta != 0.0 { - ui.scroll_with_delta(vec2(0.0, delta)); - ctx.request_repaint(); - } - let filter = crate::layer_filter_ui::Filter::of(&app.ui); - let fx_collapsed = app.session.active().map(|d| d.fx_collapsed.clone()).unwrap_or_default(); - crate::layer_row_ui::begin(ui.ctx()); - // The drawn rows, top to bottom (#1721): the space between them and below the last - // one is a drop zone too. - let mut drawn: Vec<(LayerId, Rect)> = Vec::new(); - for &(depth, l) in &rows { - // Select › Isolate Layers. - if !photocraft_engine::select_extra_cmds::isolation_shows(&doc, &isolated, l.id) { - continue; - } - if !filter.shows(l) { - continue; - } - let row = RowSel { selected: selection.contains(&l.id), primary: active == Some(l.id), multi: selection.len() > 1 }; - let top = ui.cursor().top(); - drawn.push((l.id, layer_row(app, &ctx, ui, &doc, l, depth, row, &mut actions))); - if reveal == Some(l.id) { - crate::layer_reveal::scroll_to_row(ui, top); - } - if !l.effects.items.is_empty() && fx_collapsed.iter().all(|id| *id != l.id) { - effect_rows(app, ui, l, depth, &mut actions); - } - if !fx_collapsed.contains(&l.id) { - crate::smart_ui::filter_rows(app, ui, &doc, l, depth, &mut actions); - } - } - // The bottom of everything drawn: the last layer's effect and Smart Filter rows sit - // under its own row (#8764). - let rows_bottom = ui.min_rect().bottom(); - // #1721: the list takes drops everywhere, not only on a row (Photoshop): the space - // between two rows lands above the lower one, the empty space below the bottom-most - // row below it. Both copy with ⌥ held, move without. - for w in drawn.windows(2) { - let gap = Rect::from_min_max(pos2(w[0].1.left(), w[0].1.bottom()), pos2(w[0].1.right(), w[1].1.top())); - layer_drop_zone(app, &ctx, ui, gap, (w[1].0, w[1].1), "above", &mut actions); - } - if let Some(&(last, last_rect)) = drawn.last() { - let below = Rect::from_min_max(pos2(last_rect.left(), last_rect.bottom()), pos2(last_rect.right(), ui.clip_rect().bottom())); - layer_drop_zone(app, &ctx, ui, below, (last, last_rect), "below", &mut actions); - // A click on that empty space deselects every layer, as in Photoshop (#8100). It - // starts under the last layer's sub-rows, which take their own clicks. - let empty = Rect::from_min_max(pos2(below.left(), rows_bottom), below.max); - if empty.height() > 0.0 && ui.interact(empty, ui.scope_id().with("layers-empty-space"), Sense::click()).clicked() && !selection.is_empty() { - actions.push(("select.deselectLayers".into(), json!({}))); - } - } - // Tab / ⇧Tab in a rename: rename the layer below / above next, as in Photoshop. The - // Background isn't renamed in place (double-clicking it converts it), so it ends there. - if let Some((from, up)) = crate::layer_row_ui::take_next_rename(ui.ctx()) - && let Some(at) = drawn.iter().position(|(id, _)| id.0 == from) - && let Some(&(next, _)) = if up { at.checked_sub(1).and_then(|i| drawn.get(i)) } else { drawn.get(at + 1) } - && let Some(l) = doc.layer(next).filter(|l| !crate::doc_props_ui::is_background(&doc, l)) - && let Some(done) = crate::layer_row_ui::start_rename(ui.ctx(), next.0, &l.name) - { - actions.push(done); - } - // ⌥-click the line between two layers: clip / release the upper one (#967). - crate::clip_line_ui::show(ui, &doc, &mut actions); - // A rename whose row is gone (deleted, filtered out, inside a closed group) ends, - // committed: nothing else could commit or cancel it. - if let Some(layer) = crate::layer_row_ui::renaming(ui.ctx()) - && !crate::layer_row_ui::recorded(ui.ctx()).iter().any(|r| r.layer == layer) - && let Some(done) = crate::layer_row_ui::end_rename(ui.ctx(), true) - { - actions.push(done); - } - // Likewise a selected smart filter whose row is gone. - crate::smart_ui::forget_hidden(ui.ctx(), doc.id); - }); - // Leaving the list or hovering an invalid target immediately cancels the temporary - // image. The release still uses the actual command, not the preview snapshot. - if !app.reorder_preview_hit { - app.reorder_preview = None; - } - // A layer being dragged can also be dropped on the footer's Delete, New Layer and Group - // buttons (#736); read the drag before it ends. - let footer_drag = ctx.data(|d| d.get_temp::(egui::Id::unique("layer-drag"))).map(|id| { - let in_selection = selection.iter().any(|s| s.0 == id); - (id, in_selection) - }); - // An effect row can be dropped on Delete too (#3102), and a mask's thumbnail (#3113, #3119). - let fx_footer_drag = ctx.data(|d| d.get_temp::(fx_drag_key())); - fx_drag_feedback(&ctx, &doc); - // And a smart filter's row (#4271). - let filter_footer_drag = ctx.data(|d| d.get_temp::(crate::smart_ui::drag_key())); - crate::smart_ui::drag_feedback(&ctx, &doc); - let mask_footer_drag = ctx.data(|d| d.get_temp::(mask_drag_key())); - if let Some((_, kind)) = mask_footer_drag - && let Some(p) = ctx.input(|i| i.pointer.interact_pos()) - { - let label = if kind == MaskKind::Vector { tl!("Vector Mask") } else { tl!("Layer Mask") }; - crate::layer_transfer::ghost(&ctx, p, label); - } - // End any layer drag after every row has had a chance to accept the drop. - if ctx.input(|i| i.pointer.any_released()) { - ctx.data_mut(|d| d.remove::(egui::Id::unique("layer-drag"))); - ctx.data_mut(|d| d.remove::(fx_drag_key())); - ctx.data_mut(|d| d.remove::(mask_drag_key())); - ctx.data_mut(|d| d.remove::(crate::smart_ui::drag_key())); - } - widgets::panel_footer(ui, |ui| { - let active_layer = active.and_then(|id| doc.layer(id)); - let (delete, label) = if app.ui.vector_mask_target && active_layer.is_some_and(|l| l.vector_mask.is_some()) { - ("layer.vectorMask.delete", "Delete Vector Mask") - } else if app.ui.mask_target && active_layer.is_some_and(|l| l.mask.is_some()) { - ("layer.layerMask.delete", "Delete Layer Mask") - } else { - ("layer.delete", "Delete layer") - }; - let trash = icons::button(ui, "trash", 26.0, false, tl!(label)); - // A selected smart filter row is what Delete removes, as in Photoshop (#4751). - let picked_filter = crate::smart_ui::selected(&ctx, &doc, active); - if trash.clicked() - && let Some(picked) = picked_filter - { - actions.push(crate::smart_ui::trash_action(picked)); - crate::smart_ui::deselect(&ctx, doc.id); - } else if trash.clicked() { - // Like Photoshop, ⌥/Alt-click deletes without asking. - let confirm = delete == "layer.delete" && !ui.input(|i| i.modifiers.alt); - let params = if confirm { json!({"__trash": true}) } else { json!({}) }; - actions.push((delete.into(), params)); - } - actions.extend(footer_drop(ui, &trash, footer_drag, "layer.delete")); - actions.extend(fx_trash_drop(ui, &trash, fx_footer_drag)); - if let Some(drag) = filter_footer_drag - && dropped_on(ui, &trash) - { - actions.push(crate::smart_ui::trash_action(drag)); - } - // Photoshop asks "Apply mask to layer before removing?" or "Delete the vector mask?" - // (`mask_trash_prompt`). - if let Some((layer, kind)) = mask_footer_drag - && dropped_on(ui, &trash) - { - actions.push(crate::mask_trash_prompt::drop_action(layer, kind)); - } - // A click follows the selected thumbnail; name that action for screen readers even - // though dropping a whole layer row onto the same button always deletes the layer. - trash.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(label))); - let new_layer = icons::button(ui, "square-plus", 26.0, false, &crate::shortcuts::tip_label(app, "Create a new layer", "layer.new.layer")); - if new_layer.clicked() { - // A click makes the layer above the selection; ⌥-click asks first (the New Layer - // dialog) and ⌘/Ctrl-click adds it below, as in Photoshop. - let (alt, below) = ui.input(|i| (i.modifiers.alt, i.modifiers.command)); - let params = if alt { - Value::Null - } else if below { - json!({"position": "below"}) - } else { - json!({}) - }; - actions.push(("layer.new.layer".into(), params)); - } - actions.extend(footer_drop(ui, &new_layer, footer_drag, "layer.duplicate")); - let group = icons::button(ui, "folder", 26.0, false, tl!("Create a new group")); - if group.clicked() { - // Multiple selected layers share one group. Shift also groups a single selection. - let shift = ui.input(|i| i.modifiers.shift); - let cmd = if (shift || selection.len() > 1) && active_layer.is_some() { "layer.groupLayers" } else { "layer.new.group" }; - actions.push((cmd.into(), json!({}))); - } - actions.extend(footer_drop(ui, &group, footer_drag, "layer.groupLayers")); - let adj = footer_menu_button(ui, "adjustment-layer", 26.0, tl!("Create new fill or adjustment layer")); - // Opens on the press like Photoshop's: drag onto an item and release to choose it (#2071). - crate::press_menu::show(&adj, |ui, menu| { - ui.set_min_width(190.0); - for c in photocraft_engine::command_specs().iter().filter(|c| c.id.starts_with("layer.newAdjustmentLayer.")) { - if menu.item(ui, tl!(c.label).trim_end_matches('…')) { - actions.push((c.id.into(), json!({}))); - } - } - ui.separator(); - if menu.item(ui, tl!("Solid Color…")) { - actions.push(("layer.newFillLayer.solidColor".into(), json!({}))); - } - if menu.item(ui, tl!("Gradient…")) { - actions.push(("layer.newFillLayer.gradient".into(), json!({}))); - } - }); - // Like Photoshop the button never replaces a mask (#2075): with a layer mask it adds a - // vector mask, and with both it is greyed. - let alt = ui.input(|i| i.modifiers.alt); - let mask_cmd = crate::layer_menu_ui::mask_button_command(active_layer, doc.selection.is_some(), alt); - let mask_tip = if active_layer.is_some_and(|l| l.mask.is_some()) { - tl!("Add vector mask").to_string() - } else { - crate::i18n::fmt(tl!("Add a mask (from the selection; {key} inverts)"), &[("key", &crate::shortcuts::pretty("Alt"))]) - }; - let mask_btn = ui.add_enabled_ui(mask_cmd.is_some(), |ui| icons::button(ui, "layer-mask", 26.0, false, &mask_tip)).inner; - mask_btn.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &mask_tip)); - if mask_btn.clicked() - && let Some(cmd) = mask_cmd - { - // A path selected in the Paths panel becomes the vector mask, as in Photoshop (#4728); - // Alt still inverts it. - match crate::vector_ui::selected_document_path(app).filter(|_| cmd.starts_with("layer.vectorMask.")) { - Some(name) => actions.push(("layer.vectorMask.currentPath".into(), json!({"name": name, "hide": alt}))), - None => actions.push((cmd.into(), json!({}))), - } - } - let fx = fx_button(ui, 26.0, tl!("Add a layer style")); - crate::press_menu::show(&fx, |ui, menu| { - ui.set_min_width(180.0); - if menu.item(ui, tl!("Blending Options…")) { - crate::layer_style::open(app, None); - } - ui.separator(); - for &(kind, label) in crate::layer_style::KINDS { - if menu.item(ui, format!("{}…", tl!(label))) { - crate::layer_style::open(app, Some(kind)); - } - } - }); - // Photoshop's footer starts with Link Layers (enabled with two or more layers selected). - let can_link = app.session.is_enabled("layer.linkLayers"); - if ui.add_enabled_ui(can_link, |ui| icons::button(ui, "link-2", 26.0, false, tl!("Link layers"))).inner.clicked() { - actions.push(("layer.linkLayers".into(), json!({}))); - } - }); - for (id, p) in actions { - // A row click commits even when it selects the layer already being edited (#5584). - // Finish before selection changes so the existing type session keeps its own target. - if id == "layer.select" && app.ui.text_edit.is_some() { - crate::type_tool::commit(app); - } - if id == "ui.maskTarget" { - app.end_filter_mask_view(); - app.ui.mask_target = p.as_bool().unwrap_or(false); - app.ui.vector_mask_target = false; - app.ui.filter_mask_target = None; - app.sync_mask_targets(); - continue; - } - if id == "ui.vectorMaskTarget" { - app.end_filter_mask_view(); - app.ui.vector_mask_target = p.as_bool().unwrap_or(false); - app.ui.mask_target = false; - app.ui.filter_mask_target = None; - app.sync_mask_targets(); - continue; - } - if id == "ui.filterMaskTarget" { - app.select_filter_mask_target(p.as_u64()); - continue; - } - // Double-clicking a mask thumbnail opens its settings: show Properties. - if id == "ui.properties" { - app.ui.panels.properties = true; - app.ui.dock_tabs.properties = 0; - app.ui.dock.collapsed.retain(|g| *g != crate::dock::Group::Properties); - continue; - } - if p.is_null() || id == "layer.newFillLayer.solidColor" { - // Context-menu items and the Layers footer's Solid Color… action behave like - // their menu-bar twins. In particular, a new Solid Color fill opens its picker. - let ctx = ui.ctx().clone(); - let params = if p.is_null() { json!({}) } else { p }; - if let Err(e) = crate::menus::invoke(app, &ctx, &id, params) { - app.ui.status = e; - app.ui.status_error = true; - } - continue; - } - let _ = app.run(&id, p); - } -} - -/// A layer row dragged onto a Layers panel footer button, as in Photoshop: onto Delete deletes it, -/// onto New Layer duplicates it, onto New Group groups it. A row that is part of the selection -/// carries the whole selection; any other row goes alone. Highlights the button while over it and -/// returns the command on release. -fn footer_drop(ui: &egui::Ui, button: &egui::Response, drag: Option<(u64, bool)>, command: &str) -> Option<(String, Value)> { - // Named for screen readers (and tests) after the command a drop runs. - button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, footer_label(command))); - let (layer, in_selection) = drag?; - dropped_on(ui, button).then(|| (command.into(), if in_selection { json!({}) } else { json!({"layer": layer}) })) -} - -/// While something is dragged over a footer `button`: highlights it, and is true on the release. -pub(crate) fn dropped_on(ui: &egui::Ui, button: &egui::Response) -> bool { - let Some(p) = ui.ctx().input(|i| i.pointer.interact_pos()) else { return false }; - if !button.rect.contains(p) { - return false; - } - let t = Tokens::get(ui.ctx()); - ui.painter().rect_stroke(button.rect, t.radius_sm, Stroke::new(2.0, t.accent), StrokeKind::Inside); - ui.ctx().input(|i| i.pointer.any_released()) -} - -/// Effects dragged onto the footer's Delete button, as in Photoshop (#3102): the "Effects" row -/// clears the layer style, an effect's row deletes just that effect. -fn fx_trash_drop(ui: &egui::Ui, button: &egui::Response, drag: Option) -> Option<(String, Value)> { - let (layer, effect) = drag?; - if !dropped_on(ui, button) { - return None; - } - let params = match effect { - Some(i) => json!({"layer": layer, "effect": i}), - None => json!({"layer": layer}), - }; - Some(("layer.layerStyle.clear".into(), params)) -} - -fn footer_label(command: &str) -> &'static str { - match command { - "layer.delete" => tl!("Delete layer"), - "layer.duplicate" => tl!("Create a new layer"), - _ => tl!("Create a new group"), - } -} - -/// The small down-arrow makes it clear that the footer icon expands into a menu. -fn footer_menu_arrow(ui: &egui::Ui, rect: Rect) { - let t = Tokens::get(ui.ctx()); - let arrow = Rect::from_min_size(rect.right_bottom() - vec2(11.0, 10.0), vec2(9.0, 9.0)); - icons::paint(ui, arrow, "chevron-down", 8.0, t.text_dim); -} - -fn footer_menu_button(ui: &mut egui::Ui, icon: &str, size: f32, tip: &str) -> egui::Response { - let response = icons::button(ui, icon, size, false, tip); - // Named for screen readers (and tests) after its tooltip. - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); - footer_menu_arrow(ui, response.rect); - response -} - -/// Photoshop's italic "fx" footer button (no icon-font equivalent). -fn fx_button(ui: &mut egui::Ui, size: f32, tip: &str) -> egui::Response { - let t = Tokens::get(ui.ctx()); - let (r, resp) = ui.allocate_exact_size(vec2(size, size), Sense::click()); - if resp.hovered() { - ui.painter().rect_filled(r, t.radius_sm, t.hover); - } - let mut job = egui::text::LayoutJob::default(); - job.append("fx", 0.0, egui::TextFormat { font_id: egui::FontId::proportional(15.0), color: t.icon, italics: true, ..Default::default() }); - let g = ui.painter().layout_job(job); - ui.painter().galley(r.center() - g.size() / 2.0, g, t.icon); - footer_menu_arrow(ui, r); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); - resp.on_hover_text(tip) -} - -/// How a Layers panel row is selected: in the (multi-)selection, the primary/active layer, and -/// whether several layers are selected. -#[derive(Clone, Copy)] -struct RowSel { - selected: bool, - primary: bool, - multi: bool, -} - -/// The badge beside the pointer over a thumbnail ⌘-click loads with these modifiers: none for a -/// new selection, + for ⇧ (add), − for ⌥ (subtract), × for ⇧⌥ (intersect). -pub(crate) fn thumb_load_badge(m: egui::Modifiers) -> Option { - crate::tool_feedback::Badge::from_mode(crate::channels_panel::load_operation(m)) -} - -/// The cursor over a thumbnail ⌘-click loads as a selection: a pointing hand, with the selection -/// mode's badge (#7824). -fn thumb_load_cursor(ctx: &egui::Context, p: Pos2, m: egui::Modifiers) { - ctx.set_cursor_icon(egui::CursorIcon::PointingHand); - if let Some(badge) = thumb_load_badge(m) { - let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("thumb-load-badge"))); - crate::tool_feedback::draw_badge(&painter, p, badge, false); - } -} - -/// `layer.select` mode for a click with these modifiers (Photoshop: ⌘-click toggles, ⇧-click -/// selects a range, a plain click selects one layer). -fn select_mode(m: egui::Modifiers) -> &'static str { - if m.command { - "toggle" - } else if m.shift { - "range" - } else { - "replace" - } -} - -/// A drag down the Layers panel's eye column (Photoshop): the first eye toggles and every row -/// swept over gets the same visibility, once per row, all in one history step. -#[derive(Clone)] -struct EyeSweep { - visible: bool, - /// The `coalesce` key shared by the drag's `layer.setProps` calls. - key: u64, - swept: Vec, -} - -/// Starts an eye-column sweep from `eye`, or applies a running one to the row `row` of `l`. -fn eye_sweep(ctx: &egui::Context, l: &Layer, row: Rect, eye: &egui::Response, actions: &mut Vec<(String, Value)>) { - let id = egui::Id::unique("layer-eye-sweep"); - let set = - |visible: bool, key: u64| ("layer.setProps".to_string(), json!({"layer": l.id.0, "visible": visible, "coalesce": format!("layer-eye-sweep:{key}")})); - if eye.drag_started() { - let sweep = EyeSweep { visible: !l.visible, key: ctx.cumulative_pass_nr(), swept: vec![l.id.0] }; - actions.push(set(sweep.visible, sweep.key)); - ctx.data_mut(|d| d.insert_temp(id, sweep)); - return; - } - let Some(mut sweep) = ctx.data(|d| d.get_temp::(id)) else { return }; - let (down, pos, delta) = ctx.input(|i| (i.pointer.primary_down(), i.pointer.interact_pos(), i.pointer.delta())); - if !down { - ctx.data_mut(|d| d.remove::(id)); - return; - } - // Everything the pointer passed since the last frame, so a fast drag skips no row. - let Some(p) = pos else { return }; - let (y0, y1) = ((p.y - delta.y).min(p.y), (p.y - delta.y).max(p.y)); - if y1 < row.top() || y0 >= row.bottom() || sweep.swept.contains(&l.id.0) { - return; - } - if l.visible != sweep.visible { - actions.push(set(sweep.visible, sweep.key)); - } - sweep.swept.push(l.id.0); - ctx.data_mut(|d| d.insert_temp(id, sweep)); -} - -/// Marker in the clipped row's existing 12-point slot, beside its thumbnail. -fn paint_clipping_indicator(painter: &egui::Painter, at: Pos2, color: Color32) { - let tip = at + vec2(5.0, 3.0); - let stroke = Stroke::new(1.0, color); - painter.add(egui::Shape::line(vec![at + vec2(9.0, -4.0), at + vec2(5.0, -4.0), tip], stroke)); - painter.add(egui::Shape::line(vec![at + vec2(2.0, 0.0), tip, at + vec2(8.0, 0.0)], stroke)); -} - -/// One row of the Layers panel for `l`, `depth` levels inside groups or artboards: it paints the -/// row, queues what a click or drag on it asks for in `actions`, and returns the row's rect. -#[allow(clippy::too_many_arguments)] -fn layer_row( - app: &mut PhotocraftApp, - ctx: &egui::Context, - ui: &mut egui::Ui, - doc: &photocraft_doc::Document, - l: &Layer, - depth: usize, - row: RowSel, - actions: &mut Vec<(String, Value)>, -) -> Rect { - let selected = row.selected; - let t = Tokens::get(ctx); - // The Layers Panel Options thumbnail size controls rows and both layer/mask thumbnails. - let (base, row_h) = crate::layers_panel_ui::thumbnail_geometry(app.ui.layers_panel_options.thumbnail_size, t.pro); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click_and_drag()); - // With thumbnails off no mask thumbnail is drawn, so none may keep catching drags from older frames. - if base == 0.0 { - crate::mask_thumbs_ui::forget(ctx, l.id.0); - } - // A drag from a mask's thumbnail drags that mask, not the layer (#3113, #3119). - let mask_drag = starts_mask_drag(ctx, l, &resp); - if let Some(kind) = mask_drag { - ctx.data_mut(|d| d.insert_temp::(mask_drag_key(), (l.id.0, kind))); - } - let mask_drag = mask_drag.is_some(); - layer_drag_and_drop(app, ctx, ui, l, rect, &resp, actions); - fx_drop(ctx, ui, l, rect, actions); - crate::smart_ui::drop_on_row(ctx, ui, l, rect, actions); - if resp.drag_started() && !mask_drag { - crate::layer_transfer::begin_from_panel(app, ctx, l.id); - } - // Rows are painted: name them for screen readers and UI tests. - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &l.name)); - // A row scrolled out of view only keeps its place (#125): a layout's hundreds of rows would - // otherwise lay out names, icons and thumbnails every frame. Group rows stay whole: their - // disclosure triangle is a widget (accessibility, scroll-to). - if !ui.is_rect_visible(rect) && !l.is_group() && !resp.context_menu_opened() && crate::layer_row_ui::renaming(ctx) != Some(l.id.0) { - return rect; - } - let painter = ui.painter_at(rect.expand(1.0)); - let is_hovered = resp.hovered() || app.canvas_hover_layer == Some(l.id); - if resp.hovered() { - app.hover_layer = Some(l.id); - } - if t.pro { - if selected { - painter.rect_filled(rect, 0.0, t.row_selected); - } else if is_hovered { - painter.rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5)); - painter.rect_filled(rect, 0.0, t.accent.gamma_multiply(0.12)); - } - } else if selected { - painter.rect_filled(rect, t.radius, t.hover); - painter.rect_stroke(rect, t.radius, Stroke::new(1.0, t.field_border), StrokeKind::Inside); - } else if is_hovered { - painter.rect_filled(rect, t.radius, t.hover.gamma_multiply(0.5)); - painter.rect_filled(rect, t.radius, t.accent.gamma_multiply(0.12)); - } - let eye_cell = Rect::from_min_max(rect.left_top(), pos2((rect.left() + 30.0).min(rect.right()), rect.bottom())); - if let Some((_, background)) = t.layer_label_colors(l.label) { - painter.rect_filled(eye_cell, 0.0, background); - } - if t.pro { - // Paint dividers over the label so the eye column stays distinct. - painter.line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator)); - painter.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator)); - } - let mut x = rect.left() + 6.0; - // The whole eye column takes drags too (so a drag starting on it never reorders the row): dragging down - // the eyes gives every row swept over the visibility the first eye toggled to (#8467). - let eye_resp = ui.interact(eye_cell, ui.scope_id().with(("eye", l.id.0)), Sense::click_and_drag()); - // A hidden layer's eye box is left empty (still clickable; the whole column takes the click, #8467). - if l.visible { - // Centre the drawing in the column while preserving the visibility hit area. - icons::paint(ui, eye_cell, "eye", 15.0, t.layer_label_icon(l.label)); - } - eye_sweep(ctx, l, rect, &eye_resp, actions); - if eye_resp.clicked() { - // ⌥-click shows only this layer; ⌥-click it again to restore the others. - if ui.input(|i| i.modifiers.alt) { - actions.push(("layer.showOnly".into(), json!({"layer": l.id.0}))); - } else { - actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "visible": !l.visible}))); - } - } - eye_resp.context_menu(|ui| { - crate::widgets::style_spectrum_popup_menu(ui); - crate::layer_menu_ui::color_choices(app, ui, l, row.multi && selected, actions); - }); - // Everything but the thumbnails, the indentation and the name, so a narrow panel squeezes - // the indentation first, then the thumbnails (a layer with two masks has three). - let others = 6.0 - + 28.0 - + if l.is_group() { crate::layer_tree_ui::TRIANGLE_W } else { 0.0 } - + if l.clipped { 12.0 } else { 0.0 } - + crate::layer_row_ui::reserved_width(l); - let ts = if base == 0.0 { 0.0 } else { crate::mask_thumbs_ui::thumb_size(l, base, rect.width() - others) }; - let fixed = others + if ts == 0.0 { 0.0 } else { ts + 6.0 + crate::mask_thumbs_ui::width(l, ts) }; - // A layer inside a group (or an artboard) indents one step more than its depth, past the - // triangle's column, so it sits right of its parent: with only its depth its thumbnail lined - // up under the group's, hiding the hierarchy. Top-level rows don't move. - let steps = if !l.is_group() && depth > 0 { depth + 1 } else { depth }; - x += 28.0 + crate::layer_row_ui::indent(steps, rect.width(), fixed); - let toggled = crate::layer_tree_ui::disclosure(ui, rect, &mut x, l, actions); - if l.clipped { - paint_clipping_indicator(&painter, pos2(x, rect.center().y), t.text_faint); - x += 12.0; - } - let thumb = Rect::from_min_size(pos2(x, rect.center().y - ts / 2.0), vec2(ts, ts)); - if ts > 0.0 { - draw_layer_thumb(app, ctx, ui, doc, l, thumb, row.primary); - x += ts + 6.0; - } - // With thumbnails disabled the labels and disclosure controls remain interactive. - let masks = if ts > 0.0 { crate::mask_thumbs_ui::paint(app, ctx, ui, &painter, doc, l, &mut x, rect.center().y, ts, actions) } else { Default::default() }; - let mask_rect = masks.thumb(crate::mask_thumbs_ui::MaskKind::Pixel); - let vector_rect = masks.thumb(crate::mask_thumbs_ui::MaskKind::Vector); - // Photoshop frames the targeted thumbnail (pixels, mask or vector mask) of the active layer - // with corner brackets. - if row.primary && ts > 0.0 { - let target = if app.ui.filter_mask_target == Some(l.id.0) && app.filter_mask_targeted() { - // The Smart Filters row's filter mask thumbnail carries the brackets. - None - } else if app.ui.vector_mask_target && vector_rect.is_some() { - vector_rect - } else if app.ui.mask_target { - mask_rect.or(Some(thumb)) - } else { - Some(thumb) - }; - if let Some(r) = target { - crate::mask_thumbs_ui::paint_brackets(&painter, r, t.text); - } - } - // Right-hand indicators first; the name gets what is left and ends in "…" (#144). - let fx_open = app.session.active().is_none_or(|d| !d.fx_collapsed.contains(&l.id)); - let (name_right, indicators, fx_toggled) = crate::layer_row_ui::indicators(ui, &painter, rect, x, l, fx_open, actions); - // Dragging the fx badge drags all the layer's effects, not the layer (Photoshop). Like the eye, - // it takes the drag from the row; clicks still reach the row. - if let Some(&(_, badge)) = indicators.iter().find(|(k, _)| *k == crate::layer_row_ui::Indicator::Fx) - && ui.interact(badge, ui.scope_id().with(("fx-badge", l.id.0)), Sense::drag()).drag_started() - { - start_fx_drag(ctx, l.id, None); - } - // Clicking the lock icon unlocks the layer, and makes the Background a normal one (Photoshop, - // #4723). It takes the click from the row, so the row isn't selected. - if let Some(&(_, lock)) = indicators.iter().find(|(k, _)| *k == crate::layer_row_ui::Indicator::Lock) - && ui.interact(lock, ui.scope_id().with(("row-lock", l.id.0)), Sense::click()).clicked() - { - actions.push(simple_lock_toggle(doc.is_background(l.id), l, &json!({"layer": l.id.0}))); - } - let name_color = if l.visible { t.text } else { t.text_faint }; - let font = if selected && !t.pro { theme::medium(13.0) } else { egui::FontId::proportional(if t.pro { 12.0 } else { 13.0 }) }; - // Photoshop before 2026 set the Background layer's name in italics; 2026 sets it upright. - let italic = !t.pro && doc.is_background(l.id); - // Photoshop rows show only the name; the kind sub-label is a Studio-theme addition. - let is_pixel = t.pro || ts == 0.0 || matches!(l.content, LayerContent::Raster(_)); - let name_rect = crate::layer_row_ui::truncated(&painter, &l.name, font, name_color, italic, name_right - x).map(|galley| { - let text_pos = pos2(x, rect.center().y - galley.size().y / 2.0 - if is_pixel { 0.0 } else { 7.0 }); - let r = Rect::from_min_size(text_pos, galley.size()); - painter.galley(text_pos, galley, name_color); - r - }); - if !is_pixel { - let sub = match &l.content { - LayerContent::Adjustment(a) => tl!(a.label()).to_string(), - LayerContent::Group(g) => crate::i18n::trn(crate::i18n::current(), g.children.len() as u64, "Group · {n} layer", "Group · {n} layers"), - other => tl!(other.kind_name()).to_string(), - }; - crate::layer_row_ui::label(&painter, x, rect.center().y + 8.0, name_right, &sub, egui::FontId::proportional(11.0), t.text_faint); - } - crate::layer_row_ui::record( - ctx, - crate::layer_row_ui::RowRects { layer: l.id.0, row: rect, thumbnail: (ts > 0.0).then_some(thumb), name: name_rect, indicators }, - ); - // ⌘-click a layer, mask or vector-mask thumbnail loads its transparency / mask / path as a - // selection (⇧ add, ⌥ subtract, ⇧⌥ intersect) instead of changing the layer selection. - let load_at = |m: egui::Modifiers, p: Pos2| { - if !m.command { - return None; - } - if let Some(kind) = masks.hit(p) { - return Some(crate::mask_thumbs_ui::load_params(l, kind, m)); - } - // The Background has no transparency to load: Photoshop treats the click as a plain one. - (ts > 0.0 && !doc.is_background(l.id) && thumb.expand(2.0).contains(p)) - .then(|| json!({"channel": "transparency", "layer": l.id.0, "operation": crate::channels_panel::load_operation(m)})) - }; - let thumb_load = resp.clicked().then(|| (ui.input(|i| i.modifiers), resp.interact_pointer_pos())).and_then(|(m, pos)| load_at(m, pos?)); - // Over a thumbnail that ⌘ would load, the cursor says what the click does, as in Photoshop (#7824). - if let Some(p) = resp.hover_pos() { - let m = ui.input(|i| i.modifiers); - if load_at(m, p).is_some() { - thumb_load_cursor(ctx, p, m); - } - } - // ⇧-click a mask thumbnail: disable / enable that mask; ⌥-click a layer mask: view it. - let mask_toggle = resp.clicked().then(|| (ui.input(|i| i.modifiers), resp.interact_pointer_pos())).and_then(|(m, pos)| { - let kind = masks.hit(pos?)?; - crate::mask_thumbs_ui::click_command(l, kind, m) - }); - if let Some(p) = thumb_load { - actions.push(("select.loadSelection".into(), p)); - } else if let Some(cmd) = mask_toggle { - actions.push(cmd); - } else if resp.clicked() && !eye_resp.clicked() && !toggled && !fx_toggled && !masks.clicked { - let m = ui.input(|i| i.modifiers); - let pos = resp.interact_pointer_pos(); - let on_thumb = ts > 0.0 && pos.is_some_and(|p| thumb.expand(2.0).contains(p)); - // ⌘-click on the Background thumbnail stands in for the plain click (there is no - // transparency to load): it selects the Background alone, not toggled into the set. - let mode = if m.command && on_thumb && doc.is_background(l.id) { "replace" } else { select_mode(m) }; - actions.push(("layer.select".into(), json!({"layer": l.id.0, "mode": mode}))); - crate::smart_ui::deselect(ctx, doc.id); - // A thumbnail explicitly selects content or a mask. Selecting an adjustment/fill row - // defaults to its mask, but clicking its content thumbnail must leave the mask target. - let on_mask = mask_rect.zip(pos).is_some_and(|(r, p)| r.expand(2.0).contains(p)); - let on_vector = pos.and_then(|p| masks.hit(p)) == Some(crate::mask_thumbs_ui::MaskKind::Vector); - // Clicking the layer thumbnail leaves mask view (#196). - let viewing = app.session.active().and_then(photocraft_engine::mask_view_cmds::current).filter(|v| v.layer == l.id); - if let Some(v) = viewing.filter(|_| on_thumb) { - let mask = if v.filter { "filter" } else { "layer" }; - actions.push((photocraft_engine::mask_view_cmds::ID.into(), json!({"layer": l.id.0, "mode": "off", "mask": mask}))); - } - let content_less = matches!(l.content, LayerContent::Adjustment(_) | LayerContent::Fill(_)); - if on_vector { - // The vector mask thumbnail targets the vector mask: the path tools edit it and the - // Paths panel selects the layer's path. - app.ui.selected_path = Some("layer".into()); - actions.push(("ui.vectorMaskTarget".into(), json!(true))); - } else if on_mask || (content_less && l.mask.is_some() && !on_thumb) { - if on_mask { - // The mask thumbnail also switches Properties to the mask (#3369). - app.ui.properties_layer = None; - } - actions.push(("ui.maskTarget".into(), json!(true))); - } else if on_thumb || !row.primary { - actions.push(("ui.maskTarget".into(), json!(false))); - } - // ⌥-click the layer thumbnail: fit the layer on screen, as Photoshop does. - if on_thumb && m.alt && !m.shift && !m.command { - actions.push(("view.fitLayersOnScreen".into(), Value::Null)); - } - } - // Double-click: the name renames in place (over the row's full height, not just the glyphs: - // #651); the Background, which can't be renamed while it's locked, becomes a normal layer; an - // adjustment, fill or shape thumbnail opens its settings (a solid colour: the Color Picker, - // #2812) and a Smart Object thumbnail its contents, and a type thumbnail edits its text; - // anywhere else on the row opens Layer Style (#350, #537). - // The first click already made this the active layer. - if resp.double_clicked() { - let pos = resp.interact_pointer_pos(); - let on = |r: Rect| pos.is_some_and(|p| r.expand(2.0).contains(p)); - if crate::doc_props_ui::is_background(doc, l) { - actions.push(("layer.new.layerFromBackground".into(), json!({}))); - } else if name_rect.is_some_and(|n| on(Rect::from_x_y_ranges(n.x_range(), rect.y_range()))) { - if let Some(done) = crate::layer_row_ui::start_rename(ctx, l.id.0, &l.name) { - // One rename at a time: starting this one commits any other (#314). - actions.push(done); - } - } else if let Some(kind) = pos.and_then(|p| masks.hit(p)) { - match kind { - crate::mask_thumbs_ui::MaskKind::Pixel => actions.push(("ui.maskTarget".into(), json!(true))), - crate::mask_thumbs_ui::MaskKind::Vector => actions.push(("ui.vectorMaskTarget".into(), json!(true))), - } - if let Some((cmd, val)) = crate::mask_thumbs_ui::double_click_command(app, kind) { - // The preference launches Select and Mask on a pixel mask. - actions.push((cmd.into(), val)); - } else { - // Otherwise double-click opens the mask's settings (Density/Feather). - actions.push(("ui.properties".into(), json!(true))); - } - } else if pos.and_then(|p| masks.hit(p)).is_none() { - let id = match &l.content { - LayerContent::Adjustment(_) | LayerContent::Fill(_) | LayerContent::Shape(_) if ts > 0.0 && on(thumb) => "layer.layerContentOptions", - LayerContent::Smart(_) if ts > 0.0 && on(thumb) => "layer.smartObjects.editContents", - LayerContent::Text(_) if ts > 0.0 && on(thumb) => "type.editText", - _ => "layer.layerStyle.blendingOptions", - }; - if crate::menus::is_enabled(app, id) { - // Null params: run like the menu item, dialog included. - actions.push((id.into(), Value::Null)); - } - } - } - let edit_rect = Rect::from_min_max(pos2(x - 3.0, rect.center().y - 11.0), pos2(name_right.max(x + 40.0), rect.center().y + 11.0)); - if let Some(done) = crate::layer_row_ui::rename_field(ui, l.id.0, edit_rect) { - actions.push(done); - } - // The visibility icon has its own color menu, and the layer-mask thumbnail its mask menu - // (#4575); elsewhere use the full layer menu. - let on_mask_id = ui.scope_id().with(("mask-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)); - } - if !eye_resp.secondary_clicked() && !eye_resp.context_menu_opened() { - resp.context_menu(|ui| { - crate::widgets::style_spectrum_popup_menu(ui); - if ui.ctx().data(|d| d.get_temp::(on_mask_id)).unwrap_or(false) { - crate::layer_menu_ui::show_mask(app, ui, l, 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) - && let Some(done) = crate::layer_row_ui::start_rename(ui.ctx(), l.id.0, &l.name) - { - actions.push(done); - } - }); - } - rect -} - -/// Screen rect and UVs for a layer thumbnail: the document-shaped part of the square cell and of -/// the letterboxed square texture, so tall and wide documents don't show empty bars. -fn layer_thumb_fit(cell: Rect, w: u32, h: u32) -> (Rect, Rect) { - crate::channels_panel::fit_thumb(cell, w, h) -} - -fn draw_layer_thumb(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &egui::Ui, doc: &photocraft_doc::Document, l: &Layer, rect: Rect, selected: bool) { - let t = Tokens::get(ctx); - let p = ui.painter(); - match &l.content { - LayerContent::Adjustment(_) | LayerContent::Group(_) => { - p.rect_filled(rect, 6.0, t.field); - let icon = if l.is_group() { "folder" } else { "contrast" }; - icons::paint(ui, rect, icon, 18.0, t.icon); - } - LayerContent::Text(_) => { - // Photoshop: type layers show a "T" tile rather than a pixel thumbnail. - p.rect_filled(rect, if t.pro { 0.0 } else { 6.0 }, Color32::from_gray(if t.pro { 222 } else { 236 })); - icons::paint(ui, rect, "type", 20.0, Color32::from_gray(40)); - } - // Gradient fills show the gradient itself (Photoshop); solid ones their colour. - LayerContent::Fill(f) if crate::gradient_ui::paint_thumbnail(ui, l.id, f, rect) => {} - LayerContent::Fill(photocraft_doc::Fill::Solid(color)) => { - crate::solid_fill_ui::paint_thumbnail(ui, crate::solid_fill_ui::thumbnail_color(app, doc.id, l.id, *color), rect); - } - LayerContent::Fill(_) => { - let c = [128, 128, 128, 255]; - p.rect_filled(rect, 6.0, Color32::from_rgba_unmultiplied(c[0], c[1], c[2], c[3])); - } - _ => { - // Keep row layout and outside thumbnail decorations when the image is clipped. - if ui.is_rect_visible(rect) { - // The texture is a letterboxed square: draw only the part its frame (the document, - // or the layer's bounds) fills. - let (tex, frame) = app.layer_thumb(ctx, doc, l); - let (fitted, uv) = layer_thumb_fit(rect, frame.width(), frame.height()); - widgets::checker(p, fitted, 5.0); - p.image(tex, fitted, uv, Color32::WHITE); - } - } - } - let stroke = if t.pro { - Stroke::new(1.0, Color32::from_gray(20)) - } else if selected { - Stroke::new(1.5, t.text) - } else { - Stroke::new(1.0, t.field_border) - }; - p.rect_stroke(rect, CornerRadius::same(if t.pro { 0 } else { 5 }), stroke, StrokeKind::Outside); - crate::smart_ui::thumb_badge(ui, l, rect); -} - -fn channels(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - crate::channels_panel::show(app, ui); -} - -fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - let Some(st) = app.session.active() else { - empty(ui, tl!("No document")); - return; - }; - let entries = st.history.entries(); - let current = entries.len() - 1; - let redo: Vec = st.history.redo_labels().map(str::to_string).collect(); - let doc_id = st.doc.id; - let source = photocraft_engine::history_source_cmds::source(st); - let selected_snap = selected_snapshot(ui.ctx(), st); - let spot = (doc_id, history_spot(st)); - let ctx = ui.ctx().clone(); - // A row dragged onto the trash (#5324); a drag that never saw its release must not outlive it. - if !ctx.input(|i| i.pointer.primary_down() || i.pointer.any_released()) { - ctx.data_mut(|d| d.remove::(history_drag_key())); - } - let drag = ctx.data(|d| d.get_temp::(history_drag_key())); - let mut snap_cmd = None; - let mut target: Option = None; - let mut set_source: Option = None; - let all = entries.iter().map(|e| (e.clone(), false)).chain(redo.iter().map(|e| (e.clone(), true))); - // The dock gives History a fixed height: the rows scroll above the footer. - let footer = if t.pro { widgets::footer_height(ui) + ui.spacing().item_spacing.y } else { 0.0 }; - let max_h = (ui.available_height() - footer).max(40.0); - // Follow the current state when the history moves (a new step, Undo, a state row) or another - // document comes up (`spot`), scrolling only if its row is hidden (#5909). Other changes (a - // layer click, a channel eye) and a selected snapshot leave the list where the user put it. - let follow_id = egui::Id::unique("history-follow"); - let moved = ui.ctx().data_mut(|d| { - let moved = d.get_temp::<(photocraft_doc::DocId, HistorySpot)>(follow_id).as_ref() != Some(&spot); - d.insert_temp(follow_id, spot); - moved - }); - let follow = moved && selected_snap.is_none(); - egui::ScrollArea::vertical().id_salt("history-rows").max_height(max_h).auto_shrink([false, false]).show(ui, |ui| { - // Snapshots head the list and scroll with the states, so many of them never push the - // footer out of a short dock. - snap_cmd = snapshot_rows(app, ui, selected_snap); - let mut current_rect = None; - for (i, (e, is_redo)) in all.enumerate() { - // The current state shows selected unless a snapshot is (Photoshop highlights one row). - let selected = i == current && selected_snap.is_none(); - // Past states can be dragged onto the trash; the oldest one can't be deleted. - let sense = if is_redo || i == 0 { Sense::click() } else { Sense::click_and_drag() }; - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), sense); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &e)); - if resp.drag_started() { - ui.ctx().data_mut(|d| d.insert_temp(history_drag_key(), HistoryDrag::State(i))); - } - if i == current { - current_rect = Some(rect); - } - if selected { - ui.painter().rect_filled(rect, if t.pro { 0.0 } else { t.radius_sm }, if t.pro { t.row_selected } else { t.accent_soft }); - } else if resp.hovered() { - ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5)); - } - let icon = match e.as_str() { - s if s.contains("Brush") || s.contains("Eraser") => "brush", - // 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 color = if is_redo { t.text_faint } else { t.text }; - icons::paint( - ui, - Rect::from_center_size(pos2(rect.left() + 42.0, rect.center().y), vec2(16.0, 16.0)), - icon, - 12.0, - if is_redo { t.text_faint } else { t.icon }, - ); - ui.painter().text(pos2(rect.left() + 58.0, rect.center().y), Align2::LEFT_CENTER, &e, egui::FontId::proportional(12.0), color); - if history_source_column(ui, rect, egui::Id::unique(("history-source", i)), source == Some(HistorySource::State(i))) { - set_source = Some(i); - } - if resp.clicked() && i != current { - target = Some(i); - } else if resp.clicked() && selected_snap.is_some() { - // The current state is already the document: clicking it only selects it. - ctx.data_mut(|d| d.remove::(selected_snapshot_key(doc_id))); - } - } - if follow && let Some(rect) = current_rect { - // No alignment: a row already in view stays put. No animation, as the Layers panel reveal. - ui.scroll_to_rect_animation(rect, None, egui::style::ScrollAnimation::none()); - } - }); - if let Some(i) = set_source - && let Err(e) = app.run("history.setSource", json!({"state": i})) - { - app.ui.status = e; - app.ui.status_error = true; - } - if let Some(drag) = drag - && let Some(p) = ctx.input(|i| i.pointer.interact_pos()) - { - let label = match drag { - HistoryDrag::Snapshot(id) => app.session.active().and_then(|st| st.snapshots.iter().find(|s| s.id == id)).map(|s| s.name.clone()), - HistoryDrag::State(i) => entries.get(i).cloned(), - }; - crate::layer_transfer::ghost(&ctx, p, &label.unwrap_or_default()); - } - let mut footer_cmd: Option<(&str, Value)> = None; - let mut snapshot_dialog = false; - if t.pro { - // With a snapshot selected the trash deletes it, as in Photoshop (#5324). - let can_delete = selected_snap.is_some() || app.session.is_enabled("history.deleteState"); - let can_new = app.session.is_enabled("history.newDocument"); - widgets::panel_footer(ui, |ui| { - let trash = ui.add_enabled_ui(can_delete, |ui| icons::button(ui, "trash", 26.0, false, tl!("Delete current state"))).inner; - if trash.clicked() { - footer_cmd = Some(match selected_snap { - Some(id) => ("history.deleteSnapshot", json!({"snapshot": id})), - None => ("history.deleteState", json!({})), - }); - } - // A snapshot or a past state dragged onto the trash is deleted (#5324). - if let Some(drag) = drag - && dropped_on(ui, &trash) - { - footer_cmd = Some(match drag { - HistoryDrag::Snapshot(id) => ("history.deleteSnapshot", json!({"snapshot": id})), - HistoryDrag::State(i) => ("history.deleteState", json!({"state": i})), - }); - } - let can_snap = app.session.is_enabled("history.newSnapshot"); - // ⌥-click opens New Snapshot (name, From) instead, as in Photoshop. - if ui.add_enabled_ui(can_snap, |ui| icons::button(ui, "scan", 26.0, false, tl!("Create new snapshot"))).inner.clicked() { - if ui.input(|i| i.modifiers.alt) { - snapshot_dialog = true; - } else { - footer_cmd = Some(("history.newSnapshot", json!({}))); - } - } - if ui.add_enabled_ui(can_new, |ui| icons::button(ui, "file-plus", 26.0, false, tl!("Create new document from current state"))).inner.clicked() { - footer_cmd = Some(("history.newDocument", json!({}))); - } - }); - } - if ctx.input(|i| i.pointer.any_released()) { - ctx.data_mut(|d| d.remove::(history_drag_key())); - } - // An open Free Transform owns Undo (transform_tool::intercept): stepping the document's history under - // its box would leave it transforming pixels that changed. - if snapshot_dialog { - crate::snapshot_dialog::open(app); - } - // Selecting a snapshot changes the document, so it waits for an open transform like the rows. - let snap_cmd = snap_cmd.filter(|(cmd, _)| *cmd != "history.selectSnapshot" || app.ui.transform.is_none()); - if let Some((cmd, p)) = footer_cmd.filter(|_| app.ui.transform.is_none()).or(snap_cmd) { - let picked = (cmd == "history.selectSnapshot").then(|| p.get("snapshot").and_then(Value::as_u64)).flatten(); - match app.run(cmd, p) { - Err(e) => { - app.ui.status = e; - app.ui.status_error = true; - } - // The snapshot stays selected while the document is the state the click made. - Ok(_) => { - if let (Some(id), Some(st)) = (picked, app.session.active()) { - select_snapshot(&ctx, st, id); - } - } - } - } - // One command per click (#2966): stepping with Undo/Redo once per state made the canvas - // recomposite the whole document. - if let Some(state) = target.filter(|_| app.ui.transform.is_none()) - && let Err(e) = app.run("history.selectState", json!({ "state": state })) - { - app.ui.status = e; - app.ui.status_error = true; - } -} - -/// 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. -fn history_source_column(ui: &mut egui::Ui, row: Rect, salt: egui::Id, is_source: bool) -> bool { - let t = Tokens::get(ui.ctx()); - let cell = Rect::from_min_size(row.min, vec2(24.0, row.height())); - let resp = ui.interact(cell, ui.scope_id().with(salt), Sense::click()).on_hover_text(tl!("Sets the source for the history brush")); - if is_source { - icons::paint(ui, cell.shrink(4.0), icons::tool_icon(Tool::HistoryBrush), 12.0, t.icon); - } else if resp.hovered() { - icons::paint(ui, cell.shrink(4.0), icons::tool_icon(Tool::HistoryBrush), 12.0, t.text_faint); - } - resp.clicked() -} - -/// A History panel row being dragged, for a drop on the trash (#5324). -#[derive(Clone, Copy, Debug)] -enum HistoryDrag { - Snapshot(u64), - State(usize), -} - -fn history_drag_key() -> egui::Id { - egui::Id::unique("history-drag") -} - -/// The snapshot the History panel shows selected (#5324), and where the history stood after its -/// click: the number of past states, the current state's name, the number of redo states and the -/// newest past state. That last one is a new document on every step, also at the state limit, -/// where the counts and a repeated name stay the same. -type SelectedSnapshot = (u64, HistorySpot); -type HistorySpot = (usize, Option, usize, Option); - -fn history_spot(st: &photocraft_engine::DocState) -> HistorySpot { - let newest = st.history.past_len().checked_sub(1).and_then(|i| st.history.state(i)).map(|d| std::sync::Arc::as_ptr(&d) as usize); - (st.history.past_len(), st.history.entries().pop(), st.history.redo_labels().count(), newest) -} - -fn selected_snapshot_key(doc: photocraft_doc::DocId) -> egui::Id { - egui::Id::unique(("history-snapshot-selected", doc)) -} - -/// Select snapshot `id` at the history's current state, as a click on its row does. -pub(crate) fn select_snapshot(ctx: &egui::Context, st: &photocraft_engine::DocState, id: u64) { - ctx.data_mut(|d| d.insert_temp::(selected_snapshot_key(st.doc.id), (id, history_spot(st)))); -} - -/// The selected snapshot: the one last clicked, while it still exists and the history is still at -/// the state that click made. Any other step (an edit, Undo, a state row) deselects it, as in -/// Photoshop. -pub(crate) fn selected_snapshot(ctx: &egui::Context, st: &photocraft_engine::DocState) -> Option { - let key = selected_snapshot_key(st.doc.id); - let (id, spot) = ctx.data(|d| d.get_temp::(key))?; - let live = spot == history_spot(st) && st.snapshots.iter().any(|s| s.id == id); - if !live { - ctx.data_mut(|d| d.remove::(key)); - } - live.then_some(id) -} - -/// The History panel's snapshot rows (#2966), under the opening row, each with its thumbnail and -/// name: a click returns to the snapshot (a new state) and selects it, a double-click or -/// right-click › Rename… edits the name in place (Enter or a click elsewhere keeps it, Escape -/// cancels), right-click › Delete removes it, and a drag onto the trash too (#5324). Returns the -/// command a row asks for. -fn snapshot_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, selected: Option) -> Option<(&'static str, Value)> { - let t = Tokens::get(ui.ctx()); - let st = app.session.active()?; - let (doc_id, snaps) = (st.doc.id, st.snapshots.clone()); - let source = photocraft_engine::history_source_cmds::source(st); - let live: Vec = snaps.iter().map(|s| s.id).collect(); - // Per document: snapshot ids restart in each, and a tab switch must not carry the edit over. - let rename_id = egui::Id::unique(("history-snapshot-rename", doc_id)); - let mut renaming: Option<(u64, String)> = ui.data(|d| d.get_temp(rename_id)).flatten(); - let mut cmd = None; - let ctx = ui.ctx().clone(); - for snap in &snaps { - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::click_and_drag()); - let is_selected = selected == Some(snap.id); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, is_selected, &snap.name)); - if resp.drag_started() { - ctx.data_mut(|d| d.insert_temp(history_drag_key(), HistoryDrag::Snapshot(snap.id))); - } - if is_selected { - ui.painter().rect_filled(rect, if t.pro { 0.0 } else { t.radius_sm }, if t.pro { t.row_selected } else { t.accent_soft }); - } else if resp.hovered() { - ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5)); - } - let thumb = Rect::from_min_size(pos2(rect.left() + 28.0, rect.center().y - 14.0), vec2(28.0, 28.0)); - widgets::checker(ui.painter(), thumb, 4.0); - let tex = app.snapshot_thumb(&ctx, doc_id, snap, &live); - ui.painter().image(tex, thumb, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE); - ui.painter().rect_stroke(thumb, 0.0, Stroke::new(1.0, t.separator), StrokeKind::Outside); - match renaming.as_mut().filter(|(id, _)| *id == snap.id) { - Some((_, text)) => { - let field = Rect::from_min_max(pos2(thumb.right() + 6.0, rect.center().y - 10.0), pos2(rect.right() - 6.0, rect.center().y + 10.0)); - let r = ui.put(field, egui::TextEdit::singleline(text)).accessible_name(tl!("Name")); - if r.lost_focus() { - if !ui.input(|i| i.key_pressed(egui::Key::Escape)) { - cmd = Some(("history.renameSnapshot", json!({"snapshot": snap.id, "name": text.clone()}))); - } - renaming = None; - } else if !r.has_focus() { - // Starting to rename: focus the field with the whole name selected, so typing - // replaces it (Photoshop). - r.request_focus(); - if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), r.id) { - let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(text.chars().count())); - state.cursor.set_char_range(Some(all)); - state.store(ui.ctx(), r.id); - } - } - } - None => { - ui.painter().text(pos2(thumb.right() + 8.0, rect.center().y), Align2::LEFT_CENTER, &snap.name, egui::FontId::proportional(12.0), t.text); - } - } - if history_source_column(ui, rect, egui::Id::unique(("history-snapshot-source", snap.id)), source == Some(HistorySource::Snapshot(snap.id))) { - cmd = Some(("history.setSource", json!({"snapshot": snap.id}))); - } else if resp.double_clicked() { - renaming = Some((snap.id, snap.name.clone())); - } else if resp.clicked() { - cmd = Some(("history.selectSnapshot", json!({"snapshot": snap.id}))); - } - resp.context_menu(|ui| { - if ui.button(tl!("Rename…")).clicked() { - renaming = Some((snap.id, snap.name.clone())); - ui.close(); - } - if ui.button(tl!("Delete")).clicked() { - cmd = Some(("history.deleteSnapshot", json!({"snapshot": snap.id}))); - ui.close(); - } - }); - } - if !snaps.is_empty() { - let y = ui.cursor().top(); - ui.painter().hline(ui.max_rect().x_range(), y, Stroke::new(1.0, t.separator)); - } - ui.data_mut(|d| d.insert_temp(rename_id, renaming)); - cmd -} - -// ----------------------------------------------------------------------------- properties - -/// Floating Properties card anchored to the canvas' top-right corner. It has the docked group's -/// tabs: Properties (`properties_body`: document, layer, adjustment and mask properties) and -/// Adjustments (`adjustments_grid`). -pub fn properties_window(app: &mut PhotocraftApp, ctx: &egui::Context) { - if app.ui.docking.is_some() { - return; - } - // Pro (Photoshop) docks Properties; Studio floats it over the canvas. - if !app.ui.panels.properties || Tokens::get(ctx).pro { - return; - } - if app.session.active().is_none() { - return; - } - let t = Tokens::get(ctx); - let canvas = app.last_canvas_rect; - let width = 320.0; - let pos = pos2(canvas.right() - width - 12.0, canvas.top() + 44.0); - let frame = egui::Frame::NONE - .fill(t.card) - .stroke(Stroke::new(1.0, t.card_border)) - .corner_radius(CornerRadius::same(t.radius_lg as u8)) - .shadow(egui::Shadow { offset: [0, 12], blur: 36, spread: 0, color: t.shadow }) - .inner_margin(egui::Margin::same(14)); - // A floating panel (Order::Middle like other panels, so menus, popups and dialogs stay above - // it), anchored to the canvas corner and dragged by its title off the part being worked on. - let card_id = egui::Id::unique("properties-card"); - let offset: egui::Vec2 = ctx.data(|m| m.get_temp(card_id)).unwrap_or_default(); - let mut drag = egui::Vec2::ZERO; - let shown = egui::Area::new(card_id).order(egui::Order::Middle).fixed_pos(pos + offset).show(ctx, |ui| { - frame.show(ui, |ui| { - ui.set_width(width - 28.0); - // Properties | Adjustments, as on the docked group (#7265). - let group = crate::dock::Group::Properties; - let visible = app.ui.dock.visible_tabs(group, false); - let indices: Vec = visible.iter().map(|(i, _)| *i).collect(); - let tabs: Vec<&str> = visible.iter().map(|(_, name)| *name).collect(); - let mut sel = indices.iter().position(|i| *i == app.ui.dock_tabs.properties).unwrap_or(0); - let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::hover()); - let hide = Rect::from_min_max(pos2(row.right() - 22.0, row.top() + 1.0), pos2(row.right(), row.bottom() - 1.0)); - if icons::button(&mut ui.new_child(egui::UiBuilder::new().max_rect(hide)), "minus", 22.0, false, tl!("Hide Properties")).clicked() { - app.ui.panels.properties = false; - } - // The title bar drags the card; registered before the tabs so they keep their clicks. - let bar = Rect::from_min_max(row.min, pos2((hide.left() - 6.0).max(row.left()), row.bottom())); - let grip = ui.interact(bar, card_id.with("title"), Sense::drag()); - if grip.hovered() || grip.dragged() { - ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); - } - drag = grip.drag_delta(); - let context = crate::tab_strip::pill_tabs(ui, card_id.with("tabs"), bar, &tabs, &mut sel); - if let Some(&picked) = indices.get(sel) { - app.ui.dock_tabs.properties = picked; - } - match context { - Some(crate::tab_strip::TabContextAction::Close(i)) => { - if let Some(&tab) = indices.get(i) { - crate::dock::close_tab(app, group, tab, false); - } - } - Some(crate::tab_strip::TabContextAction::CloseGroup) => app.ui.panels.properties = false, - None => {} - } - ui.add_space(6.0); - widgets::hairline(ui); - ui.add_space(8.0); - match indices.get(sel) { - Some(0) | None => properties_body(app, ui), - Some(_) => adjustments_grid(app, ui), - } - }); - }); - if drag != egui::Vec2::ZERO && canvas.is_positive() { - // Keep the title bar inside the canvas. - let r = shown.response.rect.translate(drag); - let dx = (canvas.left() - r.left()).max(0.0) - (r.right() - canvas.right()).max(0.0); - let dy = (canvas.top() - r.top()).max(0.0) - (r.top() + 40.0 - canvas.bottom()).max(0.0); - ctx.data_mut(|m| m.insert_temp(card_id, offset + drag + egui::vec2(dx, dy))); - } -} - -fn adjustment_controls(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj: &photocraft_doc::Adjustment) { - // Keep the scope reachable before tall editors and within a compact dock (#5231). - // Adjustment layers affect the stack by default; clipping limits them to their base. - if let Some(mut clip) = app.session.active().and_then(|s| s.doc.layer(id).map(|l| l.clipped)) - && widgets::toggle(ui, &mut clip, tl!("Clip to layer below")).changed() - { - let _ = app.run("layer.setProps", json!({"layer": id.0, "clipped": clip})); - } - ui.add_space(6.0); - crate::adjust_editors::layer_editor(app, ui, id, adj); - ui.add_space(6.0); - if let Some(mut vis) = app.session.active().and_then(|s| s.doc.layer(id).map(|l| l.visible)) - && widgets::toggle(ui, &mut vis, tl!("Adjustment visible")).changed() - { - let _ = app.run("layer.setProps", json!({"layer": id.0, "visible": vis})); - } - ui.add_space(6.0); - if widgets::secondary_button(ui, tl!("Reset to defaults"), ui.available_width()).clicked() { - let doc = app.session.active().map_or(0, |s| s.doc.id.0); - // Photoshop's two-step Reset where measured (Color Balance), else the defaults. - let params = crate::adjust_editors::properties_reset(ui.ctx(), doc, id, adj).unwrap_or_else(|| json!({"layer": id.0})); - let _ = app.run("layer.setAdjustment", params); - app.live_adjust = None; - } -} - -fn layer_controls(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) { - let t = Tokens::get(ui.ctx()); - if let Some(s) = layer.surface() { - let b = app.layer_frame_bounds(layer, s); - egui::Grid::new("props-grid").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { - for (k, v) in [("X", b.x0.to_string()), ("Y", b.y0.to_string()), ("W", b.width().to_string()), ("H", b.height().to_string())] { - ui.label(RichText::new(k).color(t.text_dim)); - ui.label(RichText::new(format!("{v} px")).font(theme::mono(12.0)).color(t.text)); - ui.end_row(); - } - }); - ui.add_space(6.0); - } - let mut o = layer.opacity * 100.0; - let r = widgets::slider_row(ui, tl!("Opacity"), &mut o, 0.0..=100.0, "%", None); - if r.drag_stopped() || (r.changed() && !r.dragged()) { - let _ = app.run("layer.setProps", json!({"layer": layer.id.0, "opacity": o / 100.0})); - } - let mut f = layer.fill_opacity * 100.0; - let r = widgets::slider_row(ui, crate::i18n::tr_ctx(crate::i18n::current(), "layers", "Fill"), &mut f, 0.0..=100.0, "%", None); - if r.drag_stopped() || (r.changed() && !r.dragged()) { - let _ = app.run("layer.setProps", json!({"layer": layer.id.0, "fill": f / 100.0})); - } -} - -/// Docked Properties body (Pro theme). -fn properties_body(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let identity = app.session.active().map(|st| (st.doc.id, st.active_layer, app.ui.mask_target, app.ui.vector_mask_target, app.ui.properties_layer)); - ui.push_id(("properties-target", identity), |ui| properties_body_inner(app, ui)); -} - -fn properties_body_inner(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - let Some(st) = app.session.active() else { - empty(ui, tl!("No properties")); - return; - }; - let doc = st.doc.clone(); - if let Some(layer) = st.active_layer.and_then(|id| doc.layer(id)) - && crate::mask_props_ui::targeted(app, layer) - { - crate::props_layout::header(ui, layer); - crate::mask_props_ui::properties(app, ui, layer); - return; - } - // The vector mask's own controls, when its thumbnail is targeted. - if let Some(layer) = st.active_layer.and_then(|id| doc.layer(id)) - && crate::mask_props_ui::vector_targeted(app, layer) - { - crate::props_layout::header(ui, layer); - crate::mask_props_ui::vector_properties(app, ui, layer); - return; - } - // Photoshop shows the Document properties when nothing or the Background layer is selected, - // with Align and Distribute above them when the Background is one of several (#4608). - if crate::doc_props_ui::shows_document(&st.doc, st.active_layer) { - if t.pro && st.selected_layers().len() > 1 { - crate::layer_props_ui::selection_align(app, ui); - } - crate::doc_props_ui::properties(app, ui); - return; - } - let Some(id) = st.active_layer else { return }; - // Borrowed from the document snapshot: cloning the layer every frame copied whole groups. - let Some(layer) = doc.layer(id) else { return }; - // Header: kind icon, layer name and kind (#155); sections below draw their own separators. - crate::props_layout::header(ui, layer); - let is_adjustment = matches!(layer.content, LayerContent::Adjustment(_)); - if is_adjustment || layer.artboard().is_some() || !t.pro { - ui.add_space(4.0); - widgets::hairline(ui); - ui.add_space(6.0); - } - if let LayerContent::Adjustment(adj) = &layer.content { - adjustment_controls(app, ui, id, adj); - } else if layer.artboard().is_some() { - crate::artboard_ui::properties(app, ui, layer); - } else if t.pro { - // Transform, Align, the kind's sections and Quick Actions. - crate::layer_props_ui::properties(app, ui, layer); - } else { - if matches!(layer.content, LayerContent::Fill(photocraft_doc::Fill::Gradient { .. })) { - crate::gradient_ui::properties(app, ui, layer); - ui.add_space(6.0); - } - layer_controls(app, ui, layer); - if matches!(layer.content, LayerContent::Text(_)) { - crate::type_tool::type_properties(app, ui); - } - if matches!(layer.content, LayerContent::Shape(_)) { - crate::vector_ui::shape_properties(app, ui, id); - crate::mask_props_ui::shape_properties(app, ui, layer); - } - } -} - -/// Photoshop's Adjustments panel: a grid of one-click adjustment layers. -fn adjustments_grid(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - ui.label(RichText::new(tl!("Add an adjustment")).color(t.text_dim)); - ui.add_space(4.0); - let items: [(&str, &str, &str); 16] = [ - ("brightnessContrast", "sun", tl!("Brightness/Contrast")), - ("levels", "gauge", tl!("Levels")), - ("curves", "pen-tool", tl!("Curves")), - ("exposure", "scan", tl!("Exposure")), - ("vibrance", "sparkles", tl!("Vibrance")), - ("hueSaturation", "droplet", tl!("Hue/Saturation")), - ("colorBalance", "blend", tl!("Color Balance")), - ("blackWhite", "contrast", tl!("Black & White")), - ("photoFilter", "circle-dot", tl!("Photo Filter")), - ("channelMixer", "sliders-horizontal", tl!("Channel Mixer")), - ("invert", "squares-subtract", tl!("Invert")), - ("posterize", "layers", tl!("Posterize")), - ("threshold", "square", tl!("Threshold")), - ("gradientMap", "palette", tl!("Gradient Map")), - ("selectiveColor", "swatch-book", tl!("Selective Color")), - ("colorLookup", "grid-3x3", tl!("Color Lookup")), - ]; - let mut run = None; - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing = vec2(2.0, 2.0); - for (kind, icon, tip) in items { - if icons::button(ui, icon, 30.0, false, tip).clicked() { - run = Some(format!("layer.newAdjustmentLayer.{kind}")); - } - } - }); - if let Some(id) = run { - let _ = app.run(&id, json!({})); - app.ui.dock_tabs.properties = 0; - } -} - -/// The Color panel's foreground and background chips. A click picks the colour the field edits, -/// framed; a double-click opens the Color Picker on it. -pub(crate) fn field_chips(app: &mut PhotocraftApp, ui: &mut egui::Ui, chips: Rect) { - let t = Tokens::get(ui.ctx()); - let bgr = Rect::from_min_size(chips.min + vec2(13.0, 13.0), vec2(22.0, 22.0)); - let fgr = Rect::from_min_size(chips.min + vec2(3.0, 3.0), vec2(22.0, 22.0)); - let frame = Stroke::new(1.0, t.text_dim); - let bg_active = app.ui.color_panel.background; - let p = ui.painter(); - p.rect_filled(bgr, 2.0, c32(app.session.tools.background)); - p.rect_stroke(bgr, 2.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside); - if bg_active { - p.rect_stroke(bgr.expand(2.0), 2.0, frame, StrokeKind::Outside); - } - p.rect_filled(fgr, 2.0, c32(app.session.tools.foreground)); - p.rect_stroke(fgr, 2.0, Stroke::new(1.0, Color32::from_gray(210)), StrokeKind::Outside); - if !bg_active { - p.rect_stroke(fgr.expand(2.0), 2.0, frame, StrokeKind::Outside); - } - // The foreground is on top, so it takes the clicks where the two overlap. - let bg_resp = ui.interact(bgr, ui.scope_id().with("field-bg"), Sense::click()); - let fg_resp = ui.interact(fgr, ui.scope_id().with("field-fg"), Sense::click()); - let picked = if fg_resp.clicked() { false } else { bg_resp.clicked() || bg_active }; - app.ui.color_panel.background = picked; - if fg_resp.double_clicked() || bg_resp.double_clicked() { - crate::color_picker_ui::open(app, if picked { "background" } else { "foreground" }); - } -} - -/// Where the dock tells the Color field how tall its group body is. -pub(crate) fn color_field_fill_id() -> egui::Id { - egui::Id::unique("color-field-fill-height") -} - -/// The Color field stretches to its dock group's height instead of a fixed 120 pt, in every theme -/// (#6000): a dock calls this with the group body's `ui` before drawing the tab. -pub(crate) fn offer_color_field_fill(ui: &egui::Ui, pro: bool, group: crate::dock::Group, tab: usize) { - if group == crate::dock::Group::Color && group.tabs(pro).get(tab) == Some(&"Color") { - let inner = ui.available_height().max(0.0); - ui.data_mut(|d| d.insert_temp(color_field_fill_id(), inner)); - } -} - -/// Height of the Color field: the group body's height (when docked) less the hex/RGB readout, -/// which folds onto a second line in a narrow dock. 120 pt when nothing sets a height. -fn color_field_height(avail: Option, width: f32) -> f32 { - let reserve = 32.0 + if width < 280.0 { 26.0 } else { 0.0 }; - // When docked, shrink the field so the hex/RGB readout stays in view (#6885). A 120 pt floor - // here pushed the readout below the scroll area in a compact Color group. - avail.filter(|a| a.is_finite()).map_or(120.0, |a| (a - reserve).clamp(0.0, 2000.0)) -} - -/// The colour the SV field draws for `hsva`, with what the field showed last (`hue`, `saturation`) -/// filling in what the colour itself cannot carry: a grey has no hue of its own, and black has -/// neither hue nor saturation — so a drag that bottoms out into black would otherwise round-trip -/// through RGB as `s = 0` and drop the knob from the bottom-right corner to the bottom-left one -/// (#3228). -pub(crate) fn field_hsva(mut hsva: egui::ecolor::Hsva, remembered: (f32, f32)) -> egui::ecolor::Hsva { - if hsva.v < 0.01 { - hsva.h = remembered.0; - hsva.s = remembered.1; - } else if hsva.s < 0.01 { - // A grey: the saturation really is zero (that is where the knob belongs), only the hue - // is undefined. - hsva.h = remembered.0; - } - hsva -} - -/// Photoshop's Color panel Hue Cube (saturation/brightness field + hue strip) or Brightness Cube -/// (hue/saturation field + brightness strip), drawn as shaded meshes, over a hex/RGB readout. -pub(crate) fn color_field(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - let bg_active = app.ui.color_panel.background; - let key = egui::Id::unique(("color-field-hue", bg_active)); - let mut hsva = srgb_hsva(if bg_active { app.session.tools.background } else { app.session.tools.foreground }); - // What the field showed last: a grey carries no hue, black neither hue nor saturation (#3228). - let remembered: (f32, f32) = ui.data(|d| d.get_temp(key)).unwrap_or((hsva.h, hsva.s)); - hsva = field_hsva(hsva, remembered); - let w = ui.available_width(); - let strip_w = 14.0; - // Photoshop's Color panel field fills the panel in every theme (#6000): take the height the - // dock offers, less the hex/RGB readout (which folds onto a second line in a narrow dock) and - // the theme's spacing between the rows. Without a dock, 120 pt. - let gaps = 2.0 * ui.spacing().item_spacing.y; - let fill = ui.data(|d| d.get_temp::(color_field_fill_id())).map(|a| a - gaps); - let h = color_field_height(fill, w); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 8.0; - let (chips, _) = ui.allocate_exact_size(vec2(38.0, h), Sense::hover()); - field_chips(app, ui, chips); - // Hue Cube: saturation across and brightness up, hue on the strip. Brightness Cube (the - // Color Picker's B mode): hue across and saturation up, brightness on the strip. - let brightness = app.ui.color_panel.mode == crate::state::ColorPanelMode::BrightnessCube; - let field_w = w - 38.0 - strip_w - 16.0; - let (field, fresp) = ui.allocate_exact_size(vec2(field_w, h), Sense::click_and_drag()); - let at = |x: f32, y: f32| { - if brightness { egui::ecolor::Hsva::new(x.min(0.9999), 1.0 - y, hsva.v, 1.0) } else { egui::ecolor::Hsva::new(hsva.h, x, 1.0 - y, 1.0) } - }; - ui.painter().add(color_grid(field, 16, |x, y| hsva_color32(at(x, y)))); - ui.painter().rect_stroke(field, 0.0, Stroke::new(1.0, t.separator), StrokeKind::Outside); - let field_pick = widgets::pick_pos(&fresp); - if let Some(p) = field_pick { - let x = ((p.x - field.left()) / field.width()).clamp(0.0, 1.0); - let y = ((p.y - field.top()) / field.height()).clamp(0.0, 1.0); - if brightness { - hsva.h = x.min(0.9999); - hsva.s = 1.0 - y; - } else { - hsva.s = x; - hsva.v = 1.0 - y; - } - } - let (kx, ky) = if brightness { (hsva.h, 1.0 - hsva.s) } else { (hsva.s, 1.0 - hsva.v) }; - let knob = pos2(field.left() + kx * field.width(), field.top() + ky * field.height()); - ui.painter().circle_stroke(knob, 5.0, Stroke::new(1.5, Color32::WHITE)); - ui.painter().circle_stroke(knob, 6.5, Stroke::new(1.0, Color32::from_black_alpha(160))); - // The strip: hue (red at both ends, as Photoshop's) or brightness (the colour down to black). - let (strip, sresp) = ui.allocate_exact_size(vec2(strip_w, h), Sense::click_and_drag()); - let strip_at = |f: f32| { - if brightness { egui::ecolor::Hsva::new(hsva.h, hsva.s, 1.0 - f, 1.0) } else { egui::ecolor::Hsva::new(1.0 - f, 1.0, 1.0, 1.0) } - }; - ui.painter().add(color_grid(strip, 24, |_, y| hsva_color32(strip_at(y)))); - let strip_pick = widgets::pick_pos(&sresp); - if let Some(p) = strip_pick { - let f = ((p.y - strip.top()) / strip.height()).clamp(0.0, 1.0); - if brightness { - hsva.v = 1.0 - f; - } else { - hsva.h = 1.0 - f.min(0.9999); - } - } - let y = strip.top() + (1.0 - if brightness { hsva.v } else { hsva.h }) * strip.height(); - let tri = vec![pos2(strip.right() + 1.0, y), pos2(strip.right() + 6.0, y - 4.0), pos2(strip.right() + 6.0, y + 4.0)]; - ui.painter().add(egui::Shape::convex_polygon(tri, t.text, Stroke::NONE)); - if field_pick.is_some() || strip_pick.is_some() { - if bg_active { - app.session.tools.background = hsva_srgb(hsva); - } else if app.session.tools.foreground != hsva_srgb(hsva) { - // A held, unmoved press repeats the pick: restyle selected type only on a change. - app.session.tools.foreground = hsva_srgb(hsva); - crate::apply_color::foreground_changed(app, crate::apply_color::gesture(ui.ctx())); - } - ui.data_mut(|d| d.insert_temp(key, (hsva.h, hsva.s))); - } - }); - ui.add_space(6.0); - ui.horizontal(|ui| { - let mut c = if bg_active { app.session.tools.background } else { app.session.tools.foreground }; - if color_readout(ui, ui.scope_id().with(("color-field", bg_active)), &mut c) { - if bg_active { - app.session.tools.background = c; - } else { - app.session.tools.foreground = c; - crate::apply_color::foreground_changed(app, crate::apply_color::gesture(ui.ctx())); - } - // Keep the hue for greys, so the field marker doesn't jump to red; the saturation with - // it, so a later black lands on the corner it was last dragged to (#3228). - let h = srgb_hsva(c); - if h.s >= 0.01 && h.v >= 0.01 { - ui.data_mut(|d| d.insert_temp(key, (h.h, h.s))); - } - } - }); - crate::apply_color::track_focus(ui.ctx()); -} - -/// A smooth-shaded `n` x `n` grid over `rect`, coloured by `color(x, y)` with x and y in 0..1 -/// (y down). -pub(crate) fn color_grid(rect: Rect, n: usize, color: impl Fn(f32, f32) -> Color32) -> egui::Mesh { - let n = n.max(1); - let mut mesh = egui::Mesh::default(); - for j in 0..=n { - for i in 0..=n { - let (x, y) = (i as f32 / n as f32, j as f32 / n as f32); - mesh.colored_vertex(pos2(rect.left() + x * rect.width(), rect.top() + y * rect.height()), color(x, y)); - } - } - let row = (n + 1) as u32; - for j in 0..n as u32 { - for i in 0..n as u32 { - let a = j * row + i; - mesh.add_triangle(a, a + 1, a + row + 1); - mesh.add_triangle(a, a + row + 1, a + row); - } - } - mesh -} - -/// Tool colours are sRGB-encoded floats; egui's Hsva works on sRGB bytes via these helpers -/// (its `from_rgba_unmultiplied` expects *linear* RGB, which gave wrong readouts). -pub(crate) fn srgb_bytes(c: [f32; 4]) -> [u8; 3] { - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - [q(c[0]), q(c[1]), q(c[2])] -} - -/// The Color panel's HSB, as Photoshop's and the Color Picker's: on the sRGB-encoded values, -/// so a 50% grey has Brightness 50%. egui's `Hsva` conversions work in linear light, which put -/// that grey at 22% and drew the field's middle as 188 (#3323); `Hsva` only holds the numbers. -pub(crate) fn srgb_hsva(c: [f32; 4]) -> egui::ecolor::Hsva { - let [h, s, v] = photocraft_color::convert::rgb_to_hsb([c[0], c[1], c[2]].map(|v| v.clamp(0.0, 1.0))); - egui::ecolor::Hsva::new(h / 360.0, s, v, 1.0) -} - -/// The inverse of srgb_hsva: the Color panel's HSB back to sRGB-encoded values. -pub(crate) fn hsva_srgb(h: egui::ecolor::Hsva) -> [f32; 4] { - let [r, g, b] = photocraft_color::convert::hsb_to_rgb([h.h * 360.0, h.s.clamp(0.0, 1.0), h.v.clamp(0.0, 1.0)]); - [r, g, b, 1.0] -} - -/// The colour to draw for Color panel HSB `h` (see [`srgb_hsva`]). -pub(crate) fn hsva_color32(h: egui::ecolor::Hsva) -> Color32 { - let [r, g, b] = srgb_bytes(hsva_srgb(h)); - Color32::from_rgb(r, g, b) -} - -/// The Color panel's editable colour readout: a hex field and R, G, B fields, all drawn like the -/// dock's [`widgets::value_field`] so they sit in the theme. Editing any of them sets `color` -/// (sRGB-encoded floats) and returns `true`. -pub(crate) fn color_readout(ui: &mut egui::Ui, id: egui::Id, color: &mut [f32; 4]) -> bool { - let t = Tokens::get(ui.ctx()); - let mut changed = false; - // Wrapped so the fields fold onto a second line in a narrow dock instead of being clipped. - ui.horizontal_wrapped(|ui| { - // Docks zero the item spacing; keep the fields apart. - ui.spacing_mut().item_spacing.x = 4.0; - ui.label(RichText::new("#").font(theme::mono(12.0)).color(t.text_faint)); - changed = hex_edit(ui, id.with("hex"), color); - let [mut r, mut g, mut b] = srgb_bytes(*color).map(f32::from); - let mut rgb = false; - for (label, name, v) in [("R", tl!("Red"), &mut r), ("G", tl!("Green"), &mut g), ("B", tl!("Blue"), &mut b)] { - ui.label(RichText::new(label).font(theme::mono(11.0)).color(t.text_faint)); - rgb |= widgets::value_field(ui, v, 0.0..=255.0, "", 38.0).accessible_name(name).changed(); - } - if rgb { - *color = [r / 255.0, g / 255.0, b / 255.0, 1.0]; - changed = true; - } - }); - changed -} - -/// The hex field of [`color_readout`]: type a colour with or without the leading `#`. Valid input -/// sets `color` and returns `true`. While it has focus it shows exactly what is typed, so partial -/// or invalid input isn't overwritten by the colour; an invalid entry snaps back when focus leaves. -fn hex_edit(ui: &mut egui::Ui, id: egui::Id, color: &mut [f32; 4]) -> bool { - let t = Tokens::get(ui.ctx()); - let (rect, _) = ui.allocate_exact_size(vec2(64.0, 24.0), Sense::hover()); - widgets::surface(ui, rect, t.field, false); - if !t.bevel { - ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); - } - let [r, g, b] = srgb_bytes(*color); - let typing = if ui.memory(|m| m.has_focus(id)) { ui.data(|d| d.get_temp::(id)) } else { None }; - let mut text = typing.unwrap_or_else(|| format!("{r:02X}{g:02X}{b:02X}")); - let field = rect.shrink2(vec2(5.0, 2.0)); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(field).layout(egui::Layout::left_to_right(egui::Align::Center))); - // Room for a pasted "#rrggbb"; the parse trims it, and the field shows plain digits otherwise. - // `Frame::NONE`: the themed surface above is this field's frame. - let resp = child - .add(egui::TextEdit::singleline(&mut text).id(id).char_limit(7).desired_width(field.width()).frame(egui::Frame::NONE).font(theme::mono(12.0))) - .accessible_name(tl!("Color")); - if resp.has_focus() { - ui.data_mut(|d| d.insert_temp(id, text.clone())); - } else { - ui.data_mut(|d| d.remove::(id)); - } - if resp.changed() - && let Some(c) = crate::color_picker_ui::parse_hex(&text) - { - *color = [c[0], c[1], c[2], 1.0]; - return true; - } - false -} - -/// Photoshop's brush preset picker chip: a soft/hard round tip preview with the size underneath. -/// Draw a round brush tip preview (hard core fading to a soft edge). -fn brush_tip(p: &egui::Painter, c: egui::Pos2, rad: f32, hardness: f32, color: Color32) { - let inner = rad * hardness.clamp(0.05, 1.0); - let steps = 8; - for k in (0..=steps).rev() { - let f = k as f32 / steps as f32; - let rr = inner + (rad - inner) * f; - let a = if hardness >= 0.99 { 1.0 } else { (1.0 - f).powf(1.5) }; - p.circle_filled(c, rr, color.gamma_multiply(a)); - } -} - -/// A painting tool's Mode dropdown over `modes` (`None` is Clear); the wheel over it steps the -/// mode. Returns the mode picked this frame. -fn tool_mode_dropdown(ui: &mut egui::Ui, id: &str, modes: &[Option], current: Option) -> Option> { - let opts: Vec<(Option, &str)> = modes.iter().map(|m| (*m, m.map_or("Clear", BlendMode::label))).collect(); - let mut mode = current; - let chosen = widgets::dropdown_wheel_hovered(ui, id, tl!("Mode"), &mut mode, &opts, 96.0).0; - chosen.last().copied() -} - -/// The Brush's or Pencil's Mode dropdown: the blend modes, with Photoshop's painting-only Clear -/// after Dissolve (#3439). Clear erases with the brush (`clear`); it shows while chosen, or while -/// `~` is held (`held`). The wheel over it steps the mode, as over the Layers panel's (#2061). -fn paint_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraft_engine::BrushSettings, clear: &mut bool, held: bool) { - let mut opts: Vec<(Option, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (Some(*m), m.label())).collect(); - let at = opts.iter().position(|o| o.0 == Some(BlendMode::Dissolve)).map_or(opts.len(), |i| i + 1); - opts.insert(at, (None, "Clear")); - let mut mode = if *clear || held { None } else { Some(b.mode) }; - if !widgets::dropdown_wheel_hovered(ui, id, tl!("Mode"), &mut mode, &opts, 96.0).0.is_empty() { - *clear = mode.is_none(); - if let Some(m) = mode { - b.mode = m; - } - } -} - -/// Options-bar Smoothing % (the brush's stroke smoothing; the live stroke and the commit use it). -fn smoothing_field(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings, width: f32) { - let mut sm = (b.smoothing.amount * 100.0).round(); - if widgets::value_field_named(ui, tl!("Smoothing"), &mut sm, 0.0..=100.0, "%", width).changed() { - b.smoothing.enabled = true; - b.smoothing.amount = (sm / 100.0).clamp(0.0, 1.0); - } -} - -/// Options-bar gear beside Smoothing: Photoshop's smoothing options popup, edited on the brush -/// like the Smoothing % (so they stay per tool and reach the live stroke and the commit). -fn smoothing_options(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings) { - let resp = icons::button(ui, "settings", 24.0, false, tl!("Set additional smoothing options")); - let resp = crate::brush_picker::named(resp, "Set additional smoothing options"); - egui::Popup::from_toggle_button_response(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - let s = &mut b.smoothing; - 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")); - }); -} - -/// 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. -fn mixer_load_swatch(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - let (r, _) = ui.allocate_exact_size(vec2(40.0, 26.0), Sense::hover()); - let resp = ui.interact(r, ui.scope_id().with("mixer-brush-load"), Sense::click()); - if resp.hovered() { - ui.painter().rect_filled(r, t.radius_sm, t.hover); - } - let chip = Rect::from_min_size(pos2(r.left() + 4.0, r.center().y - 8.0), vec2(16.0, 16.0)); - let p = ui.painter(); - match app.session.tools.mixer.next_load(app.session.tools.foreground) { - Some(c) => { - p.rect_filled(chip, 2.0, c32(c)); - } - None => { - p.rect_filled(chip, 2.0, t.field); - p.line_segment([chip.left_bottom(), chip.right_top()], Stroke::new(1.0, t.text_faint)); - } - } - p.rect_stroke(chip, 2.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside); - icons::paint(ui, Rect::from_center_size(pos2(r.right() - 9.0, r.center().y), vec2(10.0, 10.0)), "chevron-down", 9.0, t.text_faint); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Current Brush Load"))); - let resp = resp.on_hover_text(tl!("Current Brush Load")); - let mut run = None; - egui::Popup::menu(&resp).show(|ui| { - if ui.button(tl!("Load Brush")).clicked() { - run = Some("brush.mixer.load"); - } - if ui.button(tl!("Clean Brush")).clicked() { - run = Some("brush.mixer.clean"); - } - }); - if let Some(id) = run - && let Err(e) = app.run(id, json!({})) - { - app.ui.status = e; - app.ui.status_error = true; - } -} - -/// Options-bar brush chip: a click shows or hides Photoshop's Brush Preset picker below it (size, -/// hardness, the preset library), the one a right-click on the canvas opens. -fn brush_preset_chip(ui: &mut egui::Ui, b: &photocraft_engine::BrushSettings, state: &mut crate::state::UiState) { - let t = Tokens::get(ui.ctx()); - let (r, _) = ui.allocate_exact_size(vec2(44.0, 30.0), Sense::hover()); - let resp = ui.interact(r, crate::brush_picker::chip_id(), Sense::click()); - if resp.hovered() || state.brush_picker.is_some() { - ui.painter().rect_filled(r, t.radius_sm, t.hover); - } - let c = pos2(r.left() + 14.0, r.top() + 11.0); - // Photoshop's white tip vanishes on light chrome; light themes use their icon colour. - let tip = if t.dark() { Color32::WHITE } else { t.icon }; - brush_tip(ui.painter(), c, 7.0, b.hardness, tip); - ui.painter().text(pos2(c.x, r.bottom() - 5.0), Align2::CENTER_CENTER, format!("{}", b.size.round() as i64), egui::FontId::proportional(9.5), t.text_dim); - icons::paint(ui, Rect::from_center_size(pos2(r.right() - 9.0, c.y), vec2(10.0, 10.0)), "chevron-down", 9.0, t.text_faint); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Brush Preset picker"))); - if resp.on_hover_text(tl!("Brush Preset picker")).clicked() { - if state.brush_picker.is_some() { - crate::brush_picker::close(state); - } else { - crate::brush_picker::open(state, ui.ctx(), [r.left(), r.bottom() + 2.0]); - } - } -} - -/// A drag from within a multi-selection moves the whole selection, not only the grabbed -/// row. Dragging an unselected row keeps the existing single-layer behavior. -fn layer_drop_payload(dragged: u64, target: LayerId, position: &str, selected: &[LayerId]) -> Value { - if selected.len() > 1 && selected.contains(&LayerId(dragged)) { - json!({"layers": selected.iter().map(|id| id.0).collect::>(), "target": target.0, "position": position}) - } else { - json!({"layer": dragged, "target": target.0, "position": position}) - } -} - -/// Would this drop move the Background off the bottom, or put a layer below it? Photoshop -/// refuses both (no drop indicator); ⌥-dragging the Background still copies it above. -fn background_drop_refused(doc: &photocraft_doc::Document, payload: &Value, target: LayerId, position: &str, copy: bool) -> bool { - let Some(bg) = doc.layers.first().filter(|b| crate::doc_props_ui::is_background(doc, b)).map(|b| b.id) else { return false }; - let moves_bg = - !copy && (payload["layer"].as_u64() == Some(bg.0) || payload["layers"].as_array().is_some_and(|a| a.iter().any(|v| v.as_u64() == Some(bg.0)))); - moves_bg || (target == bg && position == "below") -} - -/// Drag a layer row to reorder: drop above, below, or inside an existing group. With ⌥ held on -/// release the layers stay put and copies land there instead (Photoshop). -/// Multi-layer moves are atomic (one undo step), using the engine's stable document order. -fn layer_drag_and_drop( - app: &mut PhotocraftApp, - ctx: &egui::Context, - ui: &egui::Ui, - l: &Layer, - rect: Rect, - resp: &egui::Response, - actions: &mut Vec<(String, Value)>, -) { - let t = Tokens::get(ctx); - let key = egui::Id::unique("layer-drag"); - // A drag from the mask thumbnail (`starts_mask_drag`) moves the mask, not the layer. - let mask_drag = ctx.data(|d| d.get_temp::(mask_drag_key())).is_some_and(|(id, _)| id == l.id.0); - if resp.drag_started() && !mask_drag { - ctx.data_mut(|d| d.insert_temp(key, l.id.0)); - } - let Some(dragged) = ctx.data(|d| d.get_temp::(key)) else { return }; - let pointer = ctx.input(|i| i.pointer.interact_pos()); - let released = ctx.input(|i| i.pointer.any_released()); - let copy = ctx.input(|i| i.modifiers.alt); - if dragged == l.id.0 { - // Ghost label following the pointer, and the copy cursor while ⌥ is held. - if let Some(p) = pointer { - crate::layer_transfer::ghost(ctx, p, &l.name); - } - if copy { - ctx.set_cursor_icon(egui::CursorIcon::Copy); - } - // #1721: with ⌥ held the row also takes the drop onto itself — the only drop target a - // single-layer document has. The copy lands above or below it (never into a group's own - // centre). A multi-selection is left alone: the engine copies it beside each of its own - // layers, not onto one of them. - let selected = app.session.active().map(|st| st.selected_layers()).unwrap_or_default(); - let in_multi = selected.len() > 1 && selected.contains(&l.id); - if copy - && !in_multi - && let Some(p) = pointer.filter(|p| rect.contains(*p)) - { - let position = if (p.y - rect.top()) / rect.height() < 0.5 { "above" } else { "below" }; - let painter = ui.painter(); - if position == "above" { - painter.line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, t.accent)); - } else { - painter.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(2.0, t.accent)); - } - let mut payload = layer_drop_payload(dragged, l.id, position, &selected); - if let Some(o) = payload.as_object_mut() { - o.insert("copy".into(), json!(true)); - } - if released { - app.reorder_preview = None; - actions.push(("layer.moveTo".into(), payload)); - } else if ctx.input(|i| i.pointer.primary_down()) { - crate::layers_panel_ui::preview_reorder(app, &payload); - } - } - return; - } - let Some(p) = pointer else { return }; - if !rect.contains(p) { - return; - } - let f = (p.y - rect.top()) / rect.height(); - let position = if l.is_group() && (0.3..0.7).contains(&f) { - "into" - } else if f < 0.5 { - "above" - } else { - "below" - }; - let Some(st) = app.session.active() else { return }; - let mut payload = layer_drop_payload(dragged, l.id, position, &st.selected_layers()); - if background_drop_refused(&st.doc, &payload, l.id, position, copy) { - return; - } - let painter = ui.painter(); - match position { - "into" => { - painter.rect_stroke(rect.shrink(1.0), t.radius_sm, Stroke::new(2.0, t.accent), StrokeKind::Inside); - } - "above" => { - painter.line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, t.accent)); - } - _ => { - painter.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(2.0, t.accent)); - } - } - if copy && let Some(o) = payload.as_object_mut() { - o.insert("copy".into(), json!(true)); - } - if !released && ctx.input(|i| i.pointer.primary_down()) { - crate::layers_panel_ui::preview_reorder(app, &payload); - } - if released { - app.reorder_preview = None; - actions.push(("layer.moveTo".into(), payload)); - } -} - -/// #1721: the drop zones no row owns — the space between two rows and the empty space below the -/// bottom-most one. The drop lands on `target` at `position` (`above` or `below` its row): a copy -/// with ⌥ held on release (Photoshop), a move without. A multi-selection dropped on the row it -/// was grabbed from is left alone: the engine can only copy it beside each of its own layers. -fn layer_drop_zone( - app: &mut PhotocraftApp, - ctx: &egui::Context, - ui: &egui::Ui, - zone: Rect, - target: (LayerId, Rect), - position: &'static str, - actions: &mut Vec<(String, Value)>, -) { - let Some(dragged) = ctx.data(|d| d.get_temp::(egui::Id::unique("layer-drag"))) else { return }; - let selected = app.session.active().map(|st| st.selected_layers()).unwrap_or_default(); - if target.0 == LayerId(dragged) && selected.len() > 1 && selected.contains(&target.0) { - return; - } - let Some(p) = ctx.input(|i| i.pointer.interact_pos()) else { return }; - if !zone.contains(p) { - return; - } - let t = Tokens::get(ctx); - let line = if position == "above" { [target.1.left_top(), target.1.right_top()] } else { [target.1.left_bottom(), target.1.right_bottom()] }; - ui.painter().line_segment(line, Stroke::new(2.0, t.accent)); - let mut payload = layer_drop_payload(dragged, target.0, position, &selected); - if ctx.input(|i| i.modifiers.alt) - && let Some(o) = payload.as_object_mut() - { - o.insert("copy".into(), json!(true)); - } - if ctx.input(|i| i.pointer.any_released()) { - app.reorder_preview = None; - actions.push(("layer.moveTo".into(), payload)); - } else if ctx.input(|i| i.pointer.primary_down()) { - crate::layers_panel_ui::preview_reorder(app, &payload); - } -} - -/// An fx row being dragged: the layer it belongs to and the effect index (`None` = the "Effects" -/// row, all of them). -type FxDrag = (u64, Option); - -/// A mask thumbnail being dragged: the layer and which of its masks (#3113, #3119). -type MaskDrag = (u64, MaskKind); - -fn mask_drag_key() -> egui::Id { - egui::Id::unique("mask-drag") -} - -/// Which mask's thumbnail (where it was drawn last frame) the row's drag starts on, if any. -fn starts_mask_drag(ctx: &egui::Context, l: &Layer, resp: &egui::Response) -> Option { - if !resp.drag_started() { - return None; - } - let p = ctx.input(|i| i.pointer.press_origin())?; - let (thumbs, _) = crate::mask_thumbs_ui::recorded(ctx, l.id.0)?; - let kind = thumbs.iter().find(|(_, r)| r.contains(p))?.0; - let present = match kind { - MaskKind::Pixel => l.mask.is_some(), - MaskKind::Vector => l.vector_mask.is_some(), - }; - present.then_some(kind) -} - -fn fx_drag_key() -> egui::Id { - egui::Id::unique("fx-drag") -} - -/// Start dragging the effects of `layer`: one (`effect`) or all of them. -fn start_fx_drag(ctx: &egui::Context, layer: LayerId, effect: Option) { - ctx.data_mut(|d| d.insert_temp::(fx_drag_key(), (layer.0, effect))); -} - -/// While effects are dragged: their name by the pointer, and the copy cursor while ⌥ is held. -fn fx_drag_feedback(ctx: &egui::Context, doc: &photocraft_doc::Document) { - let Some((from, effect)) = ctx.data(|d| d.get_temp::(fx_drag_key())) else { return }; - let Some(p) = ctx.input(|i| i.pointer.interact_pos()) else { return }; - // `Effect::label` is the English key; translate for the drag ghost like the Layers panel rows. - let label = match effect { - Some(i) => doc.layer(LayerId(from)).and_then(|l| l.effects.items.get(i)).map(|e| tl!(e.label())).unwrap_or_default(), - None => tl!("Effects"), - }; - crate::layer_transfer::ghost(ctx, p, label); - if ctx.input(|i| i.modifiers.alt) { - ctx.set_cursor_icon(egui::CursorIcon::Copy); - } -} - -/// The command for dropping effects of layer `from` on `target`: they move there, or with ⌥ held -/// on release are copied (Photoshop). `effect` is one effect row, or all effects when `None`. -fn fx_drop_action(from: u64, effect: Option, target: LayerId, copy: bool) -> (String, Value) { - let mut payload = json!({"from": from, "to": target.0, "copy": copy}); - if let Some(o) = payload.as_object_mut() - && let Some(i) = effect - { - o.insert("effect".into(), json!(i)); - } - ("layer.layerStyle.transferEffects".into(), payload) -} - -/// A layer row accepts the fx row being dragged: outlined while the pointer is over it, dropped -/// on release. -fn fx_drop(ctx: &egui::Context, ui: &egui::Ui, l: &Layer, rect: Rect, actions: &mut Vec<(String, Value)>) { - let Some((from, effect)) = ctx.data(|d| d.get_temp::(fx_drag_key())) else { return }; - let Some(p) = ctx.input(|i| i.pointer.interact_pos()) else { return }; - if from == l.id.0 || !rect.contains(p) { - return; - } - let t = Tokens::get(ctx); - ui.painter().rect_stroke(rect.shrink(1.0), t.radius_sm, Stroke::new(2.0, t.accent), StrokeKind::Inside); - if ctx.input(|i| i.pointer.any_released()) { - actions.push(fx_drop_action(from, effect, l.id, ctx.input(|i| i.modifiers.alt))); - } -} - -/// Photoshop shows a layer's effects as indented sub-rows ("Effects", then each effect). The eye -/// on "Effects" shows or hides them all, the eye on an effect's row just that one (#1622). -fn effect_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth: usize, actions: &mut Vec<(String, Value)>) { - let t = Tokens::get(ui.ctx()); - let indent = 30.0 + depth as f32 * 14.0 + 34.0; - // English `Effect::label` keys stay for kind matching; display goes through `tl!` (catalogs - // already have Drop Shadow → 投影, Effects → 效果, …). - let mut rows: Vec<(String, bool, Option<&'static str>)> = vec![(tl!("Effects").into(), l.effects.enabled, None)]; - for e in &l.effects.items { - let kind = crate::layer_style::KINDS.iter().find(|k| k.1 == e.label()).map(|k| k.0); - rows.push((tl!(e.label()).into(), e.enabled(), kind)); - } - for (i, (name, on, kind)) in rows.into_iter().enumerate() { - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); - // Drag the row onto another layer to move its effects there, ⌥-drag to copy them. - if resp.drag_started() { - start_fx_drag(ui.ctx(), l.id, i.checked_sub(1)); - } - if !ui.is_rect_visible(rect) { - continue; - } - if resp.hovered() { - ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.35)); - } - if t.pro { - ui.painter().line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator)); - } - // Nested under the layer's eye column so an effect does not read as its own layer (#4572). - let eye = Rect::from_min_size(pos2(rect.left() + 36.0, rect.center().y - 9.0), vec2(18.0, 18.0)); - // A hidden effect's eye box is left empty (still clickable), like a hidden layer's. - if on { - icons::paint(ui, eye, "eye", 12.0, t.icon); - } - // The whole eye column of the row takes the click, so it never opens the Layer Style dialog. - let eye_cell = Rect::from_min_max(pos2(rect.left() + 30.0, rect.top()), pos2((rect.left() + 58.0).min(rect.right()), rect.bottom())); - if ui.interact(eye_cell, ui.scope_id().with(("fx-eye", l.id.0, i)), Sense::click()).clicked() { - let mut params = json!({"layer": l.id.0, "visible": !on}); - if let (Some(index), Some(o)) = (i.checked_sub(1), params.as_object_mut()) { - o.insert("index".into(), json!(index)); - } - actions.push(("layer.setEffectsVisible".into(), params)); - } - let x = rect.left() + indent + if i == 0 { 8.0 } else { 24.0 }; - if i == 0 { - icons::paint(ui, Rect::from_center_size(pos2(x - 12.0, rect.center().y), vec2(14.0, 14.0)), "sparkles", 11.0, t.text_dim); - } - let right = rect.right() - crate::layer_row_ui::RIGHT_PAD; - crate::layer_row_ui::label( - ui.painter(), - x, - rect.center().y, - right, - &name, - egui::FontId::proportional(11.5), - if on { t.text_dim } else { t.text_faint }, - ); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name.clone())); - if resp.double_clicked() { - crate::layer_style::open_for_layer(app, l.id, kind); - } - // #2846: right-click opens the layer style menu (Create Layer, Copy Layer Style…), as in Photoshop. - resp.context_menu(|ui| { - crate::widgets::style_spectrum_popup_menu(ui); - crate::layer_menu_ui::show_effects(app, ui, l, actions); - }); - } -} - -/// The options bar's Select and Mask… button: greyed out, as the menu item is, until there is a -/// selection (or a layer mask) to refine (#7520). -fn select_and_mask_button(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let enabled = crate::menus::is_enabled(app, "select.selectAndMask"); - let clicked = ui.add_enabled_ui(enabled, |ui| widgets::secondary_button(ui, tl!("Select and Mask…"), 0.0).clicked()).inner; - if clicked { - let _ = crate::menus::invoke(app, ui.ctx(), "select.selectAndMask", json!({})); - } -} - -/// New / add / subtract / intersect selection buttons (shared by selection tools). -fn selection_mode_buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - ui.spacing_mut().item_spacing.x = 2.0; - for (i, (icon, tip)) in [ - ("square", tl!("New selection").to_string()), - ("plus", crate::i18n::fmt(tl!("Add to selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift"))])), - ("minus", crate::i18n::fmt(tl!("Subtract from selection ({key})"), &[("key", &crate::shortcuts::pretty("Alt"))])), - ("squares-subtract", crate::i18n::fmt(tl!("Intersect with selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift+Alt"))])), - ] - .iter() - .enumerate() - { - if icons::button(ui, icon, 24.0, app.ui.selection_mode == i as u8, tip).clicked() { - app.ui.selection_mode = i as u8; - } - } - ui.spacing_mut().item_spacing.x = 8.0; -} - #[cfg(test)] mod symmetry_theme_tests { use super::*; diff --git a/crates/ui-egui/src/panels/brush_controls.rs b/crates/ui-egui/src/panels/brush_controls.rs new file mode 100644 index 0000000000..eb5bcc7374 --- /dev/null +++ b/crates/ui-egui/src/panels/brush_controls.rs @@ -0,0 +1,128 @@ +use super::*; + +/// Photoshop's brush preset picker chip: a soft/hard round tip preview with the size underneath. +/// Draw a round brush tip preview (hard core fading to a soft edge). +fn brush_tip(p: &egui::Painter, c: egui::Pos2, rad: f32, hardness: f32, color: Color32) { + let inner = rad * hardness.clamp(0.05, 1.0); + let steps = 8; + for k in (0..=steps).rev() { + let f = k as f32 / steps as f32; + let rr = inner + (rad - inner) * f; + let a = if hardness >= 0.99 { 1.0 } else { (1.0 - f).powf(1.5) }; + p.circle_filled(c, rr, color.gamma_multiply(a)); + } +} + +/// A painting tool's Mode dropdown over `modes` (`None` is Clear); the wheel over it steps the +/// mode. Returns the mode picked this frame. +pub(super) fn tool_mode_dropdown(ui: &mut egui::Ui, id: &str, modes: &[Option], current: Option) -> Option> { + let opts: Vec<(Option, &str)> = modes.iter().map(|m| (*m, m.map_or("Clear", BlendMode::label))).collect(); + let mut mode = current; + let chosen = widgets::dropdown_wheel_hovered(ui, id, tl!("Mode"), &mut mode, &opts, 96.0).0; + chosen.last().copied() +} + +/// The Brush's or Pencil's Mode dropdown: the blend modes, with Photoshop's painting-only Clear +/// after Dissolve (#3439). Clear erases with the brush (`clear`); it shows while chosen, or while +/// `~` is held (`held`). The wheel over it steps the mode, as over the Layers panel's (#2061). +pub(super) fn paint_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraft_engine::BrushSettings, clear: &mut bool, held: bool) { + let mut opts: Vec<(Option, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (Some(*m), m.label())).collect(); + let at = opts.iter().position(|o| o.0 == Some(BlendMode::Dissolve)).map_or(opts.len(), |i| i + 1); + opts.insert(at, (None, "Clear")); + let mut mode = if *clear || held { None } else { Some(b.mode) }; + if !widgets::dropdown_wheel_hovered(ui, id, tl!("Mode"), &mut mode, &opts, 96.0).0.is_empty() { + *clear = mode.is_none(); + if let Some(m) = mode { + b.mode = m; + } + } +} + +/// 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) { + let mut sm = (b.smoothing.amount * 100.0).round(); + if widgets::value_field_named(ui, tl!("Smoothing"), &mut sm, 0.0..=100.0, "%", width).changed() { + b.smoothing.enabled = true; + b.smoothing.amount = (sm / 100.0).clamp(0.0, 1.0); + } +} + +/// Options-bar gear beside Smoothing: Photoshop's smoothing options popup, edited on the brush +/// like the Smoothing % (so they stay per tool and reach the live stroke and the commit). +pub(super) fn smoothing_options(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings) { + let resp = icons::button(ui, "settings", 24.0, false, tl!("Set additional smoothing options")); + let resp = crate::brush_picker::named(resp, "Set additional smoothing options"); + egui::Popup::from_toggle_button_response(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + let s = &mut b.smoothing; + 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")); + }); +} + +/// 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) { + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(40.0, 26.0), Sense::hover()); + let resp = ui.interact(r, ui.scope_id().with("mixer-brush-load"), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(r, t.radius_sm, t.hover); + } + let chip = Rect::from_min_size(pos2(r.left() + 4.0, r.center().y - 8.0), vec2(16.0, 16.0)); + let p = ui.painter(); + match app.session.tools.mixer.next_load(app.session.tools.foreground) { + Some(c) => { + p.rect_filled(chip, 2.0, c32(c)); + } + None => { + p.rect_filled(chip, 2.0, t.field); + p.line_segment([chip.left_bottom(), chip.right_top()], Stroke::new(1.0, t.text_faint)); + } + } + p.rect_stroke(chip, 2.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside); + icons::paint(ui, Rect::from_center_size(pos2(r.right() - 9.0, r.center().y), vec2(10.0, 10.0)), "chevron-down", 9.0, t.text_faint); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Current Brush Load"))); + let resp = resp.on_hover_text(tl!("Current Brush Load")); + let mut run = None; + egui::Popup::menu(&resp).show(|ui| { + if ui.button(tl!("Load Brush")).clicked() { + run = Some("brush.mixer.load"); + } + if ui.button(tl!("Clean Brush")).clicked() { + run = Some("brush.mixer.clean"); + } + }); + if let Some(id) = run + && let Err(e) = app.run(id, json!({})) + { + app.ui.status = e; + app.ui.status_error = true; + } +} + +/// Options-bar brush chip: a click shows or hides Photoshop's Brush Preset picker below it (size, +/// hardness, the preset library), the one a right-click on the canvas opens. +pub(super) fn brush_preset_chip(ui: &mut egui::Ui, b: &photocraft_engine::BrushSettings, state: &mut crate::state::UiState) { + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(44.0, 30.0), Sense::hover()); + let resp = ui.interact(r, crate::brush_picker::chip_id(), Sense::click()); + if resp.hovered() || state.brush_picker.is_some() { + ui.painter().rect_filled(r, t.radius_sm, t.hover); + } + let c = pos2(r.left() + 14.0, r.top() + 11.0); + // Photoshop's white tip vanishes on light chrome; light themes use their icon colour. + let tip = if t.dark() { Color32::WHITE } else { t.icon }; + brush_tip(ui.painter(), c, 7.0, b.hardness, tip); + ui.painter().text(pos2(c.x, r.bottom() - 5.0), Align2::CENTER_CENTER, format!("{}", b.size.round() as i64), egui::FontId::proportional(9.5), t.text_dim); + icons::paint(ui, Rect::from_center_size(pos2(r.right() - 9.0, c.y), vec2(10.0, 10.0)), "chevron-down", 9.0, t.text_faint); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Brush Preset picker"))); + if resp.on_hover_text(tl!("Brush Preset picker")).clicked() { + if state.brush_picker.is_some() { + crate::brush_picker::close(state); + } else { + crate::brush_picker::open(state, ui.ctx(), [r.left(), r.bottom() + 2.0]); + } + } +} diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs new file mode 100644 index 0000000000..592e4a902b --- /dev/null +++ b/crates/ui-egui/src/panels/color.rs @@ -0,0 +1,277 @@ +use super::*; + +/// The Color panel's foreground and background chips. A click picks the colour the field edits, +/// framed; a double-click opens the Color Picker on it. +pub(crate) fn field_chips(app: &mut PhotocraftApp, ui: &mut egui::Ui, chips: Rect) { + let t = Tokens::get(ui.ctx()); + let bgr = Rect::from_min_size(chips.min + vec2(13.0, 13.0), vec2(22.0, 22.0)); + let fgr = Rect::from_min_size(chips.min + vec2(3.0, 3.0), vec2(22.0, 22.0)); + let frame = Stroke::new(1.0, t.text_dim); + let bg_active = app.ui.color_panel.background; + let p = ui.painter(); + p.rect_filled(bgr, 2.0, c32(app.session.tools.background)); + p.rect_stroke(bgr, 2.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside); + if bg_active { + p.rect_stroke(bgr.expand(2.0), 2.0, frame, StrokeKind::Outside); + } + p.rect_filled(fgr, 2.0, c32(app.session.tools.foreground)); + p.rect_stroke(fgr, 2.0, Stroke::new(1.0, Color32::from_gray(210)), StrokeKind::Outside); + if !bg_active { + p.rect_stroke(fgr.expand(2.0), 2.0, frame, StrokeKind::Outside); + } + // The foreground is on top, so it takes the clicks where the two overlap. + let bg_resp = ui.interact(bgr, ui.scope_id().with("field-bg"), Sense::click()); + let fg_resp = ui.interact(fgr, ui.scope_id().with("field-fg"), Sense::click()); + let picked = if fg_resp.clicked() { false } else { bg_resp.clicked() || bg_active }; + app.ui.color_panel.background = picked; + if fg_resp.double_clicked() || bg_resp.double_clicked() { + crate::color_picker_ui::open(app, if picked { "background" } else { "foreground" }); + } +} + +/// Where the dock tells the Color field how tall its group body is. +pub(crate) fn color_field_fill_id() -> egui::Id { + egui::Id::unique("color-field-fill-height") +} + +/// The Color field stretches to its dock group's height instead of a fixed 120 pt, in every theme +/// (#6000): a dock calls this with the group body's `ui` before drawing the tab. +pub(crate) fn offer_color_field_fill(ui: &egui::Ui, pro: bool, group: crate::dock::Group, tab: usize) { + if group == crate::dock::Group::Color && group.tabs(pro).get(tab) == Some(&"Color") { + let inner = ui.available_height().max(0.0); + ui.data_mut(|d| d.insert_temp(color_field_fill_id(), inner)); + } +} + +/// Height of the Color field: the group body's height (when docked) less the hex/RGB readout, +/// which folds onto a second line in a narrow dock. 120 pt when nothing sets a height. +pub(super) fn color_field_height(avail: Option, width: f32) -> f32 { + let reserve = 32.0 + if width < 280.0 { 26.0 } else { 0.0 }; + // When docked, shrink the field so the hex/RGB readout stays in view (#6885). A 120 pt floor + // here pushed the readout below the scroll area in a compact Color group. + avail.filter(|a| a.is_finite()).map_or(120.0, |a| (a - reserve).clamp(0.0, 2000.0)) +} + +/// The colour the SV field draws for `hsva`, with what the field showed last (`hue`, `saturation`) +/// filling in what the colour itself cannot carry: a grey has no hue of its own, and black has +/// neither hue nor saturation — so a drag that bottoms out into black would otherwise round-trip +/// through RGB as `s = 0` and drop the knob from the bottom-right corner to the bottom-left one +/// (#3228). +pub(crate) fn field_hsva(mut hsva: egui::ecolor::Hsva, remembered: (f32, f32)) -> egui::ecolor::Hsva { + if hsva.v < 0.01 { + hsva.h = remembered.0; + hsva.s = remembered.1; + } else if hsva.s < 0.01 { + // A grey: the saturation really is zero (that is where the knob belongs), only the hue + // is undefined. + hsva.h = remembered.0; + } + hsva +} + +/// Photoshop's Color panel Hue Cube (saturation/brightness field + hue strip) or Brightness Cube +/// (hue/saturation field + brightness strip), drawn as shaded meshes, over a hex/RGB readout. +pub(crate) fn color_field(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + let bg_active = app.ui.color_panel.background; + let key = egui::Id::unique(("color-field-hue", bg_active)); + let mut hsva = srgb_hsva(if bg_active { app.session.tools.background } else { app.session.tools.foreground }); + // What the field showed last: a grey carries no hue, black neither hue nor saturation (#3228). + let remembered: (f32, f32) = ui.data(|d| d.get_temp(key)).unwrap_or((hsva.h, hsva.s)); + hsva = field_hsva(hsva, remembered); + let w = ui.available_width(); + let strip_w = 14.0; + // Photoshop's Color panel field fills the panel in every theme (#6000): take the height the + // dock offers, less the hex/RGB readout (which folds onto a second line in a narrow dock) and + // the theme's spacing between the rows. Without a dock, 120 pt. + let gaps = 2.0 * ui.spacing().item_spacing.y; + let fill = ui.data(|d| d.get_temp::(color_field_fill_id())).map(|a| a - gaps); + let h = color_field_height(fill, w); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 8.0; + let (chips, _) = ui.allocate_exact_size(vec2(38.0, h), Sense::hover()); + field_chips(app, ui, chips); + // Hue Cube: saturation across and brightness up, hue on the strip. Brightness Cube (the + // Color Picker's B mode): hue across and saturation up, brightness on the strip. + let brightness = app.ui.color_panel.mode == crate::state::ColorPanelMode::BrightnessCube; + let field_w = w - 38.0 - strip_w - 16.0; + let (field, fresp) = ui.allocate_exact_size(vec2(field_w, h), Sense::click_and_drag()); + let at = |x: f32, y: f32| { + if brightness { egui::ecolor::Hsva::new(x.min(0.9999), 1.0 - y, hsva.v, 1.0) } else { egui::ecolor::Hsva::new(hsva.h, x, 1.0 - y, 1.0) } + }; + ui.painter().add(color_grid(field, 16, |x, y| hsva_color32(at(x, y)))); + ui.painter().rect_stroke(field, 0.0, Stroke::new(1.0, t.separator), StrokeKind::Outside); + let field_pick = widgets::pick_pos(&fresp); + if let Some(p) = field_pick { + let x = ((p.x - field.left()) / field.width()).clamp(0.0, 1.0); + let y = ((p.y - field.top()) / field.height()).clamp(0.0, 1.0); + if brightness { + hsva.h = x.min(0.9999); + hsva.s = 1.0 - y; + } else { + hsva.s = x; + hsva.v = 1.0 - y; + } + } + let (kx, ky) = if brightness { (hsva.h, 1.0 - hsva.s) } else { (hsva.s, 1.0 - hsva.v) }; + let knob = pos2(field.left() + kx * field.width(), field.top() + ky * field.height()); + ui.painter().circle_stroke(knob, 5.0, Stroke::new(1.5, Color32::WHITE)); + ui.painter().circle_stroke(knob, 6.5, Stroke::new(1.0, Color32::from_black_alpha(160))); + // The strip: hue (red at both ends, as Photoshop's) or brightness (the colour down to black). + let (strip, sresp) = ui.allocate_exact_size(vec2(strip_w, h), Sense::click_and_drag()); + let strip_at = |f: f32| { + if brightness { egui::ecolor::Hsva::new(hsva.h, hsva.s, 1.0 - f, 1.0) } else { egui::ecolor::Hsva::new(1.0 - f, 1.0, 1.0, 1.0) } + }; + ui.painter().add(color_grid(strip, 24, |_, y| hsva_color32(strip_at(y)))); + let strip_pick = widgets::pick_pos(&sresp); + if let Some(p) = strip_pick { + let f = ((p.y - strip.top()) / strip.height()).clamp(0.0, 1.0); + if brightness { + hsva.v = 1.0 - f; + } else { + hsva.h = 1.0 - f.min(0.9999); + } + } + let y = strip.top() + (1.0 - if brightness { hsva.v } else { hsva.h }) * strip.height(); + let tri = vec![pos2(strip.right() + 1.0, y), pos2(strip.right() + 6.0, y - 4.0), pos2(strip.right() + 6.0, y + 4.0)]; + ui.painter().add(egui::Shape::convex_polygon(tri, t.text, Stroke::NONE)); + if field_pick.is_some() || strip_pick.is_some() { + if bg_active { + app.session.tools.background = hsva_srgb(hsva); + } else if app.session.tools.foreground != hsva_srgb(hsva) { + // A held, unmoved press repeats the pick: restyle selected type only on a change. + app.session.tools.foreground = hsva_srgb(hsva); + crate::apply_color::foreground_changed(app, crate::apply_color::gesture(ui.ctx())); + } + ui.data_mut(|d| d.insert_temp(key, (hsva.h, hsva.s))); + } + }); + ui.add_space(6.0); + ui.horizontal(|ui| { + let mut c = if bg_active { app.session.tools.background } else { app.session.tools.foreground }; + if color_readout(ui, ui.scope_id().with(("color-field", bg_active)), &mut c) { + if bg_active { + app.session.tools.background = c; + } else { + app.session.tools.foreground = c; + crate::apply_color::foreground_changed(app, crate::apply_color::gesture(ui.ctx())); + } + // Keep the hue for greys, so the field marker doesn't jump to red; the saturation with + // it, so a later black lands on the corner it was last dragged to (#3228). + let h = srgb_hsva(c); + if h.s >= 0.01 && h.v >= 0.01 { + ui.data_mut(|d| d.insert_temp(key, (h.h, h.s))); + } + } + }); + crate::apply_color::track_focus(ui.ctx()); +} + +/// A smooth-shaded `n` x `n` grid over `rect`, coloured by `color(x, y)` with x and y in 0..1 +/// (y down). +pub(crate) fn color_grid(rect: Rect, n: usize, color: impl Fn(f32, f32) -> Color32) -> egui::Mesh { + let n = n.max(1); + let mut mesh = egui::Mesh::default(); + for j in 0..=n { + for i in 0..=n { + let (x, y) = (i as f32 / n as f32, j as f32 / n as f32); + mesh.colored_vertex(pos2(rect.left() + x * rect.width(), rect.top() + y * rect.height()), color(x, y)); + } + } + let row = (n + 1) as u32; + for j in 0..n as u32 { + for i in 0..n as u32 { + let a = j * row + i; + mesh.add_triangle(a, a + 1, a + row + 1); + mesh.add_triangle(a, a + row + 1, a + row); + } + } + mesh +} + +/// Tool colours are sRGB-encoded floats; egui's Hsva works on sRGB bytes via these helpers +/// (its `from_rgba_unmultiplied` expects *linear* RGB, which gave wrong readouts). +pub(crate) fn srgb_bytes(c: [f32; 4]) -> [u8; 3] { + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + [q(c[0]), q(c[1]), q(c[2])] +} + +/// The Color panel's HSB, as Photoshop's and the Color Picker's: on the sRGB-encoded values, +/// so a 50% grey has Brightness 50%. egui's `Hsva` conversions work in linear light, which put +/// that grey at 22% and drew the field's middle as 188 (#3323); `Hsva` only holds the numbers. +pub(crate) fn srgb_hsva(c: [f32; 4]) -> egui::ecolor::Hsva { + let [h, s, v] = photocraft_color::convert::rgb_to_hsb([c[0], c[1], c[2]].map(|v| v.clamp(0.0, 1.0))); + egui::ecolor::Hsva::new(h / 360.0, s, v, 1.0) +} + +/// The inverse of srgb_hsva: the Color panel's HSB back to sRGB-encoded values. +pub(crate) fn hsva_srgb(h: egui::ecolor::Hsva) -> [f32; 4] { + let [r, g, b] = photocraft_color::convert::hsb_to_rgb([h.h * 360.0, h.s.clamp(0.0, 1.0), h.v.clamp(0.0, 1.0)]); + [r, g, b, 1.0] +} + +/// The colour to draw for Color panel HSB `h` (see [`srgb_hsva`]). +pub(crate) fn hsva_color32(h: egui::ecolor::Hsva) -> Color32 { + let [r, g, b] = srgb_bytes(hsva_srgb(h)); + Color32::from_rgb(r, g, b) +} + +/// The Color panel's editable colour readout: a hex field and R, G, B fields, all drawn like the +/// dock's [`widgets::value_field`] so they sit in the theme. Editing any of them sets `color` +/// (sRGB-encoded floats) and returns `true`. +pub(crate) fn color_readout(ui: &mut egui::Ui, id: egui::Id, color: &mut [f32; 4]) -> bool { + let t = Tokens::get(ui.ctx()); + let mut changed = false; + // Wrapped so the fields fold onto a second line in a narrow dock instead of being clipped. + ui.horizontal_wrapped(|ui| { + // Docks zero the item spacing; keep the fields apart. + ui.spacing_mut().item_spacing.x = 4.0; + ui.label(RichText::new("#").font(theme::mono(12.0)).color(t.text_faint)); + changed = hex_edit(ui, id.with("hex"), color); + let [mut r, mut g, mut b] = srgb_bytes(*color).map(f32::from); + let mut rgb = false; + for (label, name, v) in [("R", tl!("Red"), &mut r), ("G", tl!("Green"), &mut g), ("B", tl!("Blue"), &mut b)] { + ui.label(RichText::new(label).font(theme::mono(11.0)).color(t.text_faint)); + rgb |= widgets::value_field(ui, v, 0.0..=255.0, "", 38.0).accessible_name(name).changed(); + } + if rgb { + *color = [r / 255.0, g / 255.0, b / 255.0, 1.0]; + changed = true; + } + }); + changed +} + +/// The hex field of [`color_readout`]: type a colour with or without the leading `#`. Valid input +/// sets `color` and returns `true`. While it has focus it shows exactly what is typed, so partial +/// or invalid input isn't overwritten by the colour; an invalid entry snaps back when focus leaves. +fn hex_edit(ui: &mut egui::Ui, id: egui::Id, color: &mut [f32; 4]) -> bool { + let t = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(vec2(64.0, 24.0), Sense::hover()); + widgets::surface(ui, rect, t.field, false); + if !t.bevel { + ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); + } + let [r, g, b] = srgb_bytes(*color); + let typing = if ui.memory(|m| m.has_focus(id)) { ui.data(|d| d.get_temp::(id)) } else { None }; + let mut text = typing.unwrap_or_else(|| format!("{r:02X}{g:02X}{b:02X}")); + let field = rect.shrink2(vec2(5.0, 2.0)); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(field).layout(egui::Layout::left_to_right(egui::Align::Center))); + // Room for a pasted "#rrggbb"; the parse trims it, and the field shows plain digits otherwise. + // `Frame::NONE`: the themed surface above is this field's frame. + let resp = child + .add(egui::TextEdit::singleline(&mut text).id(id).char_limit(7).desired_width(field.width()).frame(egui::Frame::NONE).font(theme::mono(12.0))) + .accessible_name(tl!("Color")); + if resp.has_focus() { + ui.data_mut(|d| d.insert_temp(id, text.clone())); + } else { + ui.data_mut(|d| d.remove::(id)); + } + if resp.changed() + && let Some(c) = crate::color_picker_ui::parse_hex(&text) + { + *color = [c[0], c[1], c[2], 1.0]; + return true; + } + false +} diff --git a/crates/ui-egui/src/panels/dock.rs b/crates/ui-egui/src/panels/dock.rs new file mode 100644 index 0000000000..99f2afc7a8 --- /dev/null +++ b/crates/ui-egui/src/panels/dock.rs @@ -0,0 +1,121 @@ +use super::history::history; +use super::info::info_panel; +use super::layers::{channels, layers}; +use super::navigator::navigator; +use super::properties::{adjustments_grid, properties_body}; +use super::*; + +// ----------------------------------------------------------------------------- dock + +/// The panels and the canvas in the space left by the menus, bars and toolbar: craft-ui's +/// docking layout, with the icon rail at the window's end edge in the Studio themes. +pub fn dock_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + if app.ui.panels.rail && !t.pro { + rail(app, ui, &t); + } + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::panel_docking::show(app, ui)); + crate::dock::persist(app, ui.ctx()); +} + +/// 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) { + let t = Tokens::get(ui.ctx()); + let backdrop = if app.ui.view.hides_chrome() { egui::Color32::BLACK } else { crate::prefs_ui::pasteboard_color(app).unwrap_or(t.canvas) }; + if app.ui.panels.rail && t.pro { + rail(app, ui, &t); + } + egui::CentralPanel::default().frame(egui::Frame::NONE.fill(backdrop)).show(ui, |ui| crate::canvas::document_area(app, ui)); +} + +/// 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) }; + 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); + } + } + } + }); +} + +/// The dock's narrowest width (points). It is the right dock, on the left in a right-to-left UI. +pub(crate) const DOCK_MIN_WIDTH: f32 = 250.0; + +/// What the dock leaves the toolbar and the canvas when it is widest (points). +const DOCK_LEAVES: f32 = 400.0; + +/// The dock's width range (points) in a window `window_width` wide: from [`DOCK_MIN_WIDTH`] to +/// everything but [`DOCK_LEAVES`], and never capped below the old 520, so two-column layouts can +/// be as wide as the window allows (#7896). +pub(crate) fn dock_width_range(window_width: f32) -> std::ops::RangeInclusive { + let max = if window_width.is_finite() { (window_width - DOCK_LEAVES).max(520.0) } else { 520.0 }; + DOCK_MIN_WIDTH..=max +} + +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. +pub fn request_dock_width(ctx: &egui::Context, w: f32) { + 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)); +} + +/// One dock group's tab content; `panel_docking` bounds it and scrolls it when it's taller. +pub(crate) fn dock_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, group: crate::dock::Group, tab: usize) { + use crate::dock::Group; + let pro = Tokens::get(ui.ctx()).pro; + match (group, tab) { + (Group::Color, 2) => crate::preset_panels::gradients_panel(app, ui), + (Group::Color, 3) => crate::preset_panels::patterns_panel(app, ui), + // The Color tab is the same in every theme, in the mode picked from its panel menu + // (#6000); only the tab order differs between themes. + (Group::Color, tab) if group.tabs(pro).get(tab) == Some(&"Color") => crate::color_panel_ui::panel(app, ui), + (Group::Color, _) => crate::swatches_ui::panel(app, ui), + (Group::Properties, 0) => properties_body(app, ui), + (Group::Properties, _) => adjustments_grid(app, ui), + (Group::Character, tab) => crate::type_tool::character_panel(app, ui, tab == 1), + (Group::Navigator, 0) => navigator(app, ui), + (Group::Navigator, 1) => crate::histogram_panel::show(app, ui), + (Group::Navigator, _) => info_panel(app, ui), + (Group::History, 0) => history(app, ui), + (Group::History, 1) => crate::actions::panel(app, ui), + (Group::History, _) => crate::comps_ui::panel(app, ui), + (Group::Layers, 0) => layers(app, ui), + (Group::Layers, 1) => channels(app, ui), + (Group::Layers, _) => crate::vector_ui::paths_panel(app, ui), + (Group::Brushes, _) => crate::brushes_tab::show(app, ui), + } +} diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs new file mode 100644 index 0000000000..9f8d6033cb --- /dev/null +++ b/crates/ui-egui/src/panels/history.rs @@ -0,0 +1,326 @@ +use super::layer_drag::dropped_on; +use super::*; + +pub(super) fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + let Some(st) = app.session.active() else { + empty(ui, tl!("No document")); + return; + }; + let entries = st.history.entries(); + let current = entries.len() - 1; + let redo: Vec = st.history.redo_labels().map(str::to_string).collect(); + let doc_id = st.doc.id; + let source = photocraft_engine::history_source_cmds::source(st); + let selected_snap = selected_snapshot(ui.ctx(), st); + let spot = (doc_id, history_spot(st)); + let ctx = ui.ctx().clone(); + // A row dragged onto the trash (#5324); a drag that never saw its release must not outlive it. + if !ctx.input(|i| i.pointer.primary_down() || i.pointer.any_released()) { + ctx.data_mut(|d| d.remove::(history_drag_key())); + } + let drag = ctx.data(|d| d.get_temp::(history_drag_key())); + let mut snap_cmd = None; + let mut target: Option = None; + let mut set_source: Option = None; + let all = entries.iter().map(|e| (e.clone(), false)).chain(redo.iter().map(|e| (e.clone(), true))); + // The dock gives History a fixed height: the rows scroll above the footer. + let footer = if t.pro { widgets::footer_height(ui) + ui.spacing().item_spacing.y } else { 0.0 }; + let max_h = (ui.available_height() - footer).max(40.0); + // Follow the current state when the history moves (a new step, Undo, a state row) or another + // document comes up (`spot`), scrolling only if its row is hidden (#5909). Other changes (a + // layer click, a channel eye) and a selected snapshot leave the list where the user put it. + let follow_id = egui::Id::unique("history-follow"); + let moved = ui.ctx().data_mut(|d| { + let moved = d.get_temp::<(photocraft_doc::DocId, HistorySpot)>(follow_id).as_ref() != Some(&spot); + d.insert_temp(follow_id, spot); + moved + }); + let follow = moved && selected_snap.is_none(); + egui::ScrollArea::vertical().id_salt("history-rows").max_height(max_h).auto_shrink([false, false]).show(ui, |ui| { + // Snapshots head the list and scroll with the states, so many of them never push the + // footer out of a short dock. + snap_cmd = snapshot_rows(app, ui, selected_snap); + let mut current_rect = None; + for (i, (e, is_redo)) in all.enumerate() { + // The current state shows selected unless a snapshot is (Photoshop highlights one row). + let selected = i == current && selected_snap.is_none(); + // Past states can be dragged onto the trash; the oldest one can't be deleted. + let sense = if is_redo || i == 0 { Sense::click() } else { Sense::click_and_drag() }; + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), sense); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &e)); + if resp.drag_started() { + ui.ctx().data_mut(|d| d.insert_temp(history_drag_key(), HistoryDrag::State(i))); + } + if i == current { + current_rect = Some(rect); + } + if selected { + ui.painter().rect_filled(rect, if t.pro { 0.0 } else { t.radius_sm }, if t.pro { t.row_selected } else { t.accent_soft }); + } else if resp.hovered() { + ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5)); + } + let icon = match e.as_str() { + s if s.contains("Brush") || s.contains("Eraser") => "brush", + // 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 color = if is_redo { t.text_faint } else { t.text }; + icons::paint( + ui, + Rect::from_center_size(pos2(rect.left() + 42.0, rect.center().y), vec2(16.0, 16.0)), + icon, + 12.0, + if is_redo { t.text_faint } else { t.icon }, + ); + ui.painter().text(pos2(rect.left() + 58.0, rect.center().y), Align2::LEFT_CENTER, &e, egui::FontId::proportional(12.0), color); + if history_source_column(ui, rect, egui::Id::unique(("history-source", i)), source == Some(HistorySource::State(i))) { + set_source = Some(i); + } + if resp.clicked() && i != current { + target = Some(i); + } else if resp.clicked() && selected_snap.is_some() { + // The current state is already the document: clicking it only selects it. + ctx.data_mut(|d| d.remove::(selected_snapshot_key(doc_id))); + } + } + if follow && let Some(rect) = current_rect { + // No alignment: a row already in view stays put. No animation, as the Layers panel reveal. + ui.scroll_to_rect_animation(rect, None, egui::style::ScrollAnimation::none()); + } + }); + if let Some(i) = set_source + && let Err(e) = app.run("history.setSource", json!({"state": i})) + { + app.ui.status = e; + app.ui.status_error = true; + } + if let Some(drag) = drag + && let Some(p) = ctx.input(|i| i.pointer.interact_pos()) + { + let label = match drag { + HistoryDrag::Snapshot(id) => app.session.active().and_then(|st| st.snapshots.iter().find(|s| s.id == id)).map(|s| s.name.clone()), + HistoryDrag::State(i) => entries.get(i).cloned(), + }; + crate::layer_transfer::ghost(&ctx, p, &label.unwrap_or_default()); + } + let mut footer_cmd: Option<(&str, Value)> = None; + let mut snapshot_dialog = false; + if t.pro { + // With a snapshot selected the trash deletes it, as in Photoshop (#5324). + let can_delete = selected_snap.is_some() || app.session.is_enabled("history.deleteState"); + let can_new = app.session.is_enabled("history.newDocument"); + widgets::panel_footer(ui, |ui| { + let trash = ui.add_enabled_ui(can_delete, |ui| icons::button(ui, "trash", 26.0, false, tl!("Delete current state"))).inner; + if trash.clicked() { + footer_cmd = Some(match selected_snap { + Some(id) => ("history.deleteSnapshot", json!({"snapshot": id})), + None => ("history.deleteState", json!({})), + }); + } + // A snapshot or a past state dragged onto the trash is deleted (#5324). + if let Some(drag) = drag + && dropped_on(ui, &trash) + { + footer_cmd = Some(match drag { + HistoryDrag::Snapshot(id) => ("history.deleteSnapshot", json!({"snapshot": id})), + HistoryDrag::State(i) => ("history.deleteState", json!({"state": i})), + }); + } + let can_snap = app.session.is_enabled("history.newSnapshot"); + // ⌥-click opens New Snapshot (name, From) instead, as in Photoshop. + if ui.add_enabled_ui(can_snap, |ui| icons::button(ui, "scan", 26.0, false, tl!("Create new snapshot"))).inner.clicked() { + if ui.input(|i| i.modifiers.alt) { + snapshot_dialog = true; + } else { + footer_cmd = Some(("history.newSnapshot", json!({}))); + } + } + if ui.add_enabled_ui(can_new, |ui| icons::button(ui, "file-plus", 26.0, false, tl!("Create new document from current state"))).inner.clicked() { + footer_cmd = Some(("history.newDocument", json!({}))); + } + }); + } + if ctx.input(|i| i.pointer.any_released()) { + ctx.data_mut(|d| d.remove::(history_drag_key())); + } + // An open Free Transform owns Undo (transform_tool::intercept): stepping the document's history under + // its box would leave it transforming pixels that changed. + if snapshot_dialog { + crate::snapshot_dialog::open(app); + } + // Selecting a snapshot changes the document, so it waits for an open transform like the rows. + let snap_cmd = snap_cmd.filter(|(cmd, _)| *cmd != "history.selectSnapshot" || app.ui.transform.is_none()); + if let Some((cmd, p)) = footer_cmd.filter(|_| app.ui.transform.is_none()).or(snap_cmd) { + let picked = (cmd == "history.selectSnapshot").then(|| p.get("snapshot").and_then(Value::as_u64)).flatten(); + match app.run(cmd, p) { + Err(e) => { + app.ui.status = e; + app.ui.status_error = true; + } + // The snapshot stays selected while the document is the state the click made. + Ok(_) => { + if let (Some(id), Some(st)) = (picked, app.session.active()) { + select_snapshot(&ctx, st, id); + } + } + } + } + // One command per click (#2966): stepping with Undo/Redo once per state made the canvas + // recomposite the whole document. + if let Some(state) = target.filter(|_| app.ui.transform.is_none()) + && let Err(e) = app.run("history.selectState", json!({ "state": state })) + { + app.ui.status = e; + app.ui.status_error = true; + } +} + +/// 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. +fn history_source_column(ui: &mut egui::Ui, row: Rect, salt: egui::Id, is_source: bool) -> bool { + let t = Tokens::get(ui.ctx()); + let cell = Rect::from_min_size(row.min, vec2(24.0, row.height())); + let resp = ui.interact(cell, ui.scope_id().with(salt), Sense::click()).on_hover_text(tl!("Sets the source for the history brush")); + if is_source { + icons::paint(ui, cell.shrink(4.0), icons::tool_icon(Tool::HistoryBrush), 12.0, t.icon); + } else if resp.hovered() { + icons::paint(ui, cell.shrink(4.0), icons::tool_icon(Tool::HistoryBrush), 12.0, t.text_faint); + } + resp.clicked() +} + +/// A History panel row being dragged, for a drop on the trash (#5324). +#[derive(Clone, Copy, Debug)] +enum HistoryDrag { + Snapshot(u64), + State(usize), +} + +fn history_drag_key() -> egui::Id { + egui::Id::unique("history-drag") +} + +/// The snapshot the History panel shows selected (#5324), and where the history stood after its +/// click: the number of past states, the current state's name, the number of redo states and the +/// newest past state. That last one is a new document on every step, also at the state limit, +/// where the counts and a repeated name stay the same. +type SelectedSnapshot = (u64, HistorySpot); + +type HistorySpot = (usize, Option, usize, Option); + +fn history_spot(st: &photocraft_engine::DocState) -> HistorySpot { + let newest = st.history.past_len().checked_sub(1).and_then(|i| st.history.state(i)).map(|d| std::sync::Arc::as_ptr(&d) as usize); + (st.history.past_len(), st.history.entries().pop(), st.history.redo_labels().count(), newest) +} + +fn selected_snapshot_key(doc: photocraft_doc::DocId) -> egui::Id { + egui::Id::unique(("history-snapshot-selected", doc)) +} + +/// Select snapshot `id` at the history's current state, as a click on its row does. +pub(crate) fn select_snapshot(ctx: &egui::Context, st: &photocraft_engine::DocState, id: u64) { + ctx.data_mut(|d| d.insert_temp::(selected_snapshot_key(st.doc.id), (id, history_spot(st)))); +} + +/// The selected snapshot: the one last clicked, while it still exists and the history is still at +/// the state that click made. Any other step (an edit, Undo, a state row) deselects it, as in +/// Photoshop. +pub(crate) fn selected_snapshot(ctx: &egui::Context, st: &photocraft_engine::DocState) -> Option { + let key = selected_snapshot_key(st.doc.id); + let (id, spot) = ctx.data(|d| d.get_temp::(key))?; + let live = spot == history_spot(st) && st.snapshots.iter().any(|s| s.id == id); + if !live { + ctx.data_mut(|d| d.remove::(key)); + } + live.then_some(id) +} + +/// The History panel's snapshot rows (#2966), under the opening row, each with its thumbnail and +/// name: a click returns to the snapshot (a new state) and selects it, a double-click or +/// right-click › Rename… edits the name in place (Enter or a click elsewhere keeps it, Escape +/// cancels), right-click › Delete removes it, and a drag onto the trash too (#5324). Returns the +/// command a row asks for. +fn snapshot_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, selected: Option) -> Option<(&'static str, Value)> { + let t = Tokens::get(ui.ctx()); + let st = app.session.active()?; + let (doc_id, snaps) = (st.doc.id, st.snapshots.clone()); + let source = photocraft_engine::history_source_cmds::source(st); + let live: Vec = snaps.iter().map(|s| s.id).collect(); + // Per document: snapshot ids restart in each, and a tab switch must not carry the edit over. + let rename_id = egui::Id::unique(("history-snapshot-rename", doc_id)); + let mut renaming: Option<(u64, String)> = ui.data(|d| d.get_temp(rename_id)).flatten(); + let mut cmd = None; + let ctx = ui.ctx().clone(); + for snap in &snaps { + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::click_and_drag()); + let is_selected = selected == Some(snap.id); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, is_selected, &snap.name)); + if resp.drag_started() { + ctx.data_mut(|d| d.insert_temp(history_drag_key(), HistoryDrag::Snapshot(snap.id))); + } + if is_selected { + ui.painter().rect_filled(rect, if t.pro { 0.0 } else { t.radius_sm }, if t.pro { t.row_selected } else { t.accent_soft }); + } else if resp.hovered() { + ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5)); + } + let thumb = Rect::from_min_size(pos2(rect.left() + 28.0, rect.center().y - 14.0), vec2(28.0, 28.0)); + widgets::checker(ui.painter(), thumb, 4.0); + let tex = app.snapshot_thumb(&ctx, doc_id, snap, &live); + ui.painter().image(tex, thumb, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE); + ui.painter().rect_stroke(thumb, 0.0, Stroke::new(1.0, t.separator), StrokeKind::Outside); + match renaming.as_mut().filter(|(id, _)| *id == snap.id) { + Some((_, text)) => { + let field = Rect::from_min_max(pos2(thumb.right() + 6.0, rect.center().y - 10.0), pos2(rect.right() - 6.0, rect.center().y + 10.0)); + let r = ui.put(field, egui::TextEdit::singleline(text)).accessible_name(tl!("Name")); + if r.lost_focus() { + if !ui.input(|i| i.key_pressed(egui::Key::Escape)) { + cmd = Some(("history.renameSnapshot", json!({"snapshot": snap.id, "name": text.clone()}))); + } + renaming = None; + } else if !r.has_focus() { + // Starting to rename: focus the field with the whole name selected, so typing + // replaces it (Photoshop). + r.request_focus(); + if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), r.id) { + let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(text.chars().count())); + state.cursor.set_char_range(Some(all)); + state.store(ui.ctx(), r.id); + } + } + } + None => { + ui.painter().text(pos2(thumb.right() + 8.0, rect.center().y), Align2::LEFT_CENTER, &snap.name, egui::FontId::proportional(12.0), t.text); + } + } + if history_source_column(ui, rect, egui::Id::unique(("history-snapshot-source", snap.id)), source == Some(HistorySource::Snapshot(snap.id))) { + cmd = Some(("history.setSource", json!({"snapshot": snap.id}))); + } else if resp.double_clicked() { + renaming = Some((snap.id, snap.name.clone())); + } else if resp.clicked() { + cmd = Some(("history.selectSnapshot", json!({"snapshot": snap.id}))); + } + resp.context_menu(|ui| { + if ui.button(tl!("Rename…")).clicked() { + renaming = Some((snap.id, snap.name.clone())); + ui.close(); + } + if ui.button(tl!("Delete")).clicked() { + cmd = Some(("history.deleteSnapshot", json!({"snapshot": snap.id}))); + ui.close(); + } + }); + } + if !snaps.is_empty() { + let y = ui.cursor().top(); + ui.painter().hline(ui.max_rect().x_range(), y, Stroke::new(1.0, t.separator)); + } + ui.data_mut(|d| d.insert_temp(rename_id, renaming)); + cmd +} diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs new file mode 100644 index 0000000000..41a16d9f97 --- /dev/null +++ b/crates/ui-egui/src/panels/info.rs @@ -0,0 +1,135 @@ +use super::*; + +/// The active document's pixel under the pointer, if the pointer is over the image. +pub(crate) fn hover_pixel(app: &PhotocraftApp) -> Option<(i32, i32)> { + let size = app.session.active()?.doc.size; + app.hover_doc.map(|p| (p[0].floor() as i32, p[1].floor() as i32)).filter(|(x, y)| *x >= 0 && *y >= 0 && *x < size.width as i32 && *y < size.height as i32) +} + +/// The colour the Info panel reads at document pixel `(x, y)`, straight RGBA 0..1: averaged over +/// the Eyedropper's Sample Size, as in Photoshop (#1649), and cached per pixel and revision. +pub(crate) fn pointer_sample(app: &mut PhotocraftApp, (x, y): (i32, i32)) -> Option<[f32; 4]> { + let rev = app.session.active()?.revision; + let sample_size = app.ui.tool_options.eyedropper_size; + if let Some(((cx, cy, cr, cs), v)) = app.info_sample + && (cx, cy, cr, cs) == (x, y, rev, sample_size) + { + return Some(v); + } + let params = json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5, "size": sample_size}); + let v: Vec = serde_json::from_value(app.session.execute("document.sampleColor", params).ok()?).ok()?; + let v = [*v.first()?, *v.get(1)?, *v.get(2)?, *v.get(3)?]; + app.info_sample = Some(((x, y, rev, sample_size), v)); + Some(v) +} + +/// Photoshop's Info panel: colour under the pointer (RGB and CMYK), position, selection size. +pub(super) fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + let Some(st) = app.session.active() else { + empty(ui, tl!("No document")); + return; + }; + let (size, origin) = (st.doc.size, st.doc.ruler_origin); + let cmyk_space = photocraft_compose::cmyk_space(&st.doc); + // Positions and sizes in the ruler unit (Preferences › Units & Rulers). + let units = app.session.prefs().units_and_rulers.clone(); + let dpi = st.doc.resolution_dpi as f64; + let fx = move |px: f64| units.format(px, dpi, size.width as f64); + let units_y = app.session.prefs().units_and_rulers.clone(); + let fy = move |px: f64| units_y.format(px, dpi, size.height as f64); + let sel = st.doc.selection.as_ref().map(photocraft_compose::bounds::content_bounds); + let pos = hover_pixel(app); + // While a guide is dragged (#5728), the Info panel shows its position in one axis only, even + // when the pointer is outside the canvas (ruler drags do not update `hover_doc` there). + let (guide_x, guide_y) = match app.guide_drag { + Some(d) if d.vertical => (Some(d.pos), None), + Some(d) => (None, Some(d.pos)), + None => (None, None), + }; + let rgba = pos.and_then(|p| pointer_sample(app, p)); + let mono = theme::mono(11.5); + let row = |ui: &mut egui::Ui, k: &str, v: String| { + ui.horizontal(|ui| { + ui.add_sized([18.0, 16.0], egui::Label::new(RichText::new(k).color(t.text_dim).size(11.5))); + ui.label(RichText::new(v).font(mono.clone()).color(t.text)); + }); + }; + ui.columns(2, |cols| { + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; + let dash = || "—".to_string(); + row(&mut cols[0], "R:", rgba.map_or_else(dash, |c| q(c[0]).to_string())); + row(&mut cols[0], "G:", rgba.map_or_else(dash, |c| q(c[1]).to_string())); + row(&mut cols[0], "B:", rgba.map_or_else(dash, |c| q(c[2]).to_string())); + // Colour-managed CMYK in percent like Photoshop's readout, through the same conversion as + // the Color Picker (#8101) and the Color Sampler readout (`sampler_cmds::device_cmyk`). + let cmyk = + rgba.map(|c| photocraft_color::convert::with_cmyk_space(cmyk_space.as_ref(), || photocraft_engine::sampler_cmds::device_cmyk(c[0], c[1], c[2]))); + for (i, k) in ["C:", "M:", "Y:", "K:"].iter().enumerate() { + row(&mut cols[1], k, cmyk.map_or_else(dash, |c| format!("{}%", c[i]))); + } + }); + widgets::hairline(ui); + ui.columns(2, |cols| { + let dash = || "—".to_string(); + // Measured from the rulers' zero point (#2955). + row(&mut cols[0], "X:", guide_x.map(|p| fx(p - origin[0])).or_else(|| pos.map(|p| fx(p.0 as f64 - origin[0]))).unwrap_or_else(dash)); + row(&mut cols[0], "Y:", guide_y.map(|p| fy(p - origin[1])).or_else(|| pos.map(|p| fy(p.1 as f64 - origin[1]))).unwrap_or_else(dash)); + row(&mut cols[1], "W:", sel.map_or_else(dash, |r| fx(r.width() as f64))); + row(&mut cols[1], "H:", sel.map_or_else(dash, |r| fy(r.height() as f64))); + }); + widgets::hairline(ui); + ui.label( + RichText::new(crate::i18n::fmt(tl!("Doc: {w} × {h} px"), &[("w", &size.width.to_string()), ("h", &size.height.to_string())])) + .color(t.text_dim) + .size(11.5), + ); + // Color Sampler points (#1046): each under its number, with its position in the current ruler + // unit and the same RGB/CMYK readout as the pointer (one composite pixel each). + let samplers = sampler_readouts(app); + if !samplers.is_empty() { + widgets::hairline(ui); + let cell = |ui: &mut egui::Ui, s: String| { + ui.label(RichText::new(s).font(mono.clone()).color(t.text)); + }; + for s in samplers.iter() { + let n = s["number"].as_i64().unwrap_or(0); + let at = s["position"] + .as_array() + .map_or((0.0, 0.0), |a| (a.first().and_then(Value::as_f64).unwrap_or(0.0), a.get(1).and_then(Value::as_f64).unwrap_or(0.0))); + let num = |v: &Value, i: usize| v.get(i).and_then(Value::as_i64).map_or_else(|| "—".to_string(), |n| n.to_string()); + let (rgb, cmyk) = (&s["rgb"], &s["cmyk"]); + ui.horizontal(|ui| { + ui.add_sized([24.0, 16.0], egui::Label::new(RichText::new(format!("#{n}")).color(t.text_dim).size(11.5))); + cell(ui, format!("X: {} Y: {}", fx(at.0), fy(at.1))); + }); + ui.horizontal(|ui| { + ui.add_sized([24.0, 16.0], egui::Label::new(RichText::new("").size(11.5))); + cell(ui, format!("R:{} G:{} B:{}", num(rgb, 0), num(rgb, 1), num(rgb, 2))); + }); + ui.horizontal(|ui| { + ui.add_sized([24.0, 16.0], egui::Label::new(RichText::new("").size(11.5))); + cell(ui, format!("C:{}% M:{}% Y:{}% K:{}%", num(cmyk, 0), num(cmyk, 1), num(cmyk, 2), num(cmyk, 3))); + }); + } + } +} + +/// The Info panel's Color Sampler readouts and the (document, revision) they were composited for. +pub(crate) type SamplerReadouts = ((photocraft_doc::DocId, u64), std::sync::Arc>); + +/// The Color Sampler readouts of the active document, composited once per revision (#4528): +/// adding, moving or deleting a sampler and every pixel edit bump the revision, so between them +/// the Info panel reuses them instead of compositing each point through the stack every frame. +pub(crate) fn sampler_readouts(app: &mut PhotocraftApp) -> std::sync::Arc> { + let Some(key) = app.session.active().map(|s| (s.doc.id, s.revision)) else { return std::sync::Arc::default() }; + if let Some((k, v)) = &app.info_samplers + && *k == key + { + return v.clone(); + } + let list = app.session.execute("view.colorSamplers.list", json!({})).ok(); + let v = std::sync::Arc::new(list.as_ref().and_then(|v| v["samplers"].as_array()).cloned().unwrap_or_default()); + app.info_samplers = Some((key, v.clone())); + v +} diff --git a/crates/ui-egui/src/panels/layer_drag.rs b/crates/ui-egui/src/panels/layer_drag.rs new file mode 100644 index 0000000000..fd9a5d9b47 --- /dev/null +++ b/crates/ui-egui/src/panels/layer_drag.rs @@ -0,0 +1,367 @@ +use super::layers::footer_label; +use super::*; + +/// Scroll the Layers panel while holding a layer drag over its top/bottom edge or past them. +/// +/// Returns the *content* displacement in points for this frame, so positive moves the +/// list downward (reveals rows above) and negative upward (reveals rows below). +/// The speed ramps with proximity to the edge and clamps to the maximum speed when +/// dragged outside, using elapsed time instead of assuming a particular refresh rate. +pub(crate) fn layer_drag_edge_scroll(pointer: Option, viewport: Rect, dragging: bool, dt: f32) -> f32 { + if !dragging || viewport.width() <= 0.0 || viewport.height() <= 0.0 || dt.is_nan() || dt <= 0.0 { + return 0.0; + } + let Some(pointer) = pointer.filter(|p| p.x.is_finite() && p.y.is_finite() && p.x >= viewport.left() && p.x <= viewport.right()) else { + return 0.0; + }; + let edge = 32.0_f32.min(viewport.height() * 0.25); + let top = ((edge - (pointer.y - viewport.top())) / edge).clamp(0.0, 1.0); + let bottom = ((edge - (viewport.bottom() - pointer.y)) / edge).clamp(0.0, 1.0); + let direction = top - bottom; + if direction == 0.0 { + return 0.0; + } + let velocity = 80.0 + 520.0 * direction.abs(); + direction.signum() * velocity * dt.clamp(0.0, 0.05) +} + +/// A layer row dragged onto a Layers panel footer button, as in Photoshop: onto Delete deletes it, +/// onto New Layer duplicates it, onto New Group groups it. A row that is part of the selection +/// carries the whole selection; any other row goes alone. Highlights the button while over it and +/// returns the command on release. +pub(super) fn footer_drop(ui: &egui::Ui, button: &egui::Response, drag: Option<(u64, bool)>, command: &str) -> Option<(String, Value)> { + // Named for screen readers (and tests) after the command a drop runs. + button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, footer_label(command))); + let (layer, in_selection) = drag?; + dropped_on(ui, button).then(|| (command.into(), if in_selection { json!({}) } else { json!({"layer": layer}) })) +} + +/// While something is dragged over a footer `button`: highlights it, and is true on the release. +pub(crate) fn dropped_on(ui: &egui::Ui, button: &egui::Response) -> bool { + let Some(p) = ui.ctx().input(|i| i.pointer.interact_pos()) else { return false }; + if !button.rect.contains(p) { + return false; + } + let t = Tokens::get(ui.ctx()); + ui.painter().rect_stroke(button.rect, t.radius_sm, Stroke::new(2.0, t.accent), StrokeKind::Inside); + ui.ctx().input(|i| i.pointer.any_released()) +} + +/// Effects dragged onto the footer's Delete button, as in Photoshop (#3102): the "Effects" row +/// clears the layer style, an effect's row deletes just that effect. +pub(super) fn fx_trash_drop(ui: &egui::Ui, button: &egui::Response, drag: Option) -> Option<(String, Value)> { + let (layer, effect) = drag?; + if !dropped_on(ui, button) { + return None; + } + let params = match effect { + Some(i) => json!({"layer": layer, "effect": i}), + None => json!({"layer": layer}), + }; + Some(("layer.layerStyle.clear".into(), params)) +} + +/// A drag from within a multi-selection moves the whole selection, not only the grabbed +/// row. Dragging an unselected row keeps the existing single-layer behavior. +pub(super) fn layer_drop_payload(dragged: u64, target: LayerId, position: &str, selected: &[LayerId]) -> Value { + if selected.len() > 1 && selected.contains(&LayerId(dragged)) { + json!({"layers": selected.iter().map(|id| id.0).collect::>(), "target": target.0, "position": position}) + } else { + json!({"layer": dragged, "target": target.0, "position": position}) + } +} + +/// Would this drop move the Background off the bottom, or put a layer below it? Photoshop +/// refuses both (no drop indicator); ⌥-dragging the Background still copies it above. +pub(super) fn background_drop_refused(doc: &photocraft_doc::Document, payload: &Value, target: LayerId, position: &str, copy: bool) -> bool { + let Some(bg) = doc.layers.first().filter(|b| crate::doc_props_ui::is_background(doc, b)).map(|b| b.id) else { return false }; + let moves_bg = + !copy && (payload["layer"].as_u64() == Some(bg.0) || payload["layers"].as_array().is_some_and(|a| a.iter().any(|v| v.as_u64() == Some(bg.0)))); + moves_bg || (target == bg && position == "below") +} + +/// Drag a layer row to reorder: drop above, below, or inside an existing group. With ⌥ held on +/// release the layers stay put and copies land there instead (Photoshop). +/// Multi-layer moves are atomic (one undo step), using the engine's stable document order. +pub(super) fn layer_drag_and_drop( + app: &mut PhotocraftApp, + ctx: &egui::Context, + ui: &egui::Ui, + l: &Layer, + rect: Rect, + resp: &egui::Response, + actions: &mut Vec<(String, Value)>, +) { + let t = Tokens::get(ctx); + let key = egui::Id::unique("layer-drag"); + // A drag from the mask thumbnail (`starts_mask_drag`) moves the mask, not the layer. + let mask_drag = ctx.data(|d| d.get_temp::(mask_drag_key())).is_some_and(|(id, _)| id == l.id.0); + if resp.drag_started() && !mask_drag { + ctx.data_mut(|d| d.insert_temp(key, l.id.0)); + } + let Some(dragged) = ctx.data(|d| d.get_temp::(key)) else { return }; + let pointer = ctx.input(|i| i.pointer.interact_pos()); + let released = ctx.input(|i| i.pointer.any_released()); + let copy = ctx.input(|i| i.modifiers.alt); + if dragged == l.id.0 { + // Ghost label following the pointer, and the copy cursor while ⌥ is held. + if let Some(p) = pointer { + crate::layer_transfer::ghost(ctx, p, &l.name); + } + if copy { + ctx.set_cursor_icon(egui::CursorIcon::Copy); + } + // #1721: with ⌥ held the row also takes the drop onto itself — the only drop target a + // single-layer document has. The copy lands above or below it (never into a group's own + // centre). A multi-selection is left alone: the engine copies it beside each of its own + // layers, not onto one of them. + let selected = app.session.active().map(|st| st.selected_layers()).unwrap_or_default(); + let in_multi = selected.len() > 1 && selected.contains(&l.id); + if copy + && !in_multi + && let Some(p) = pointer.filter(|p| rect.contains(*p)) + { + let position = if (p.y - rect.top()) / rect.height() < 0.5 { "above" } else { "below" }; + let painter = ui.painter(); + if position == "above" { + painter.line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, t.accent)); + } else { + painter.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(2.0, t.accent)); + } + let mut payload = layer_drop_payload(dragged, l.id, position, &selected); + if let Some(o) = payload.as_object_mut() { + o.insert("copy".into(), json!(true)); + } + if released { + app.reorder_preview = None; + actions.push(("layer.moveTo".into(), payload)); + } else if ctx.input(|i| i.pointer.primary_down()) { + crate::layers_panel_ui::preview_reorder(app, &payload); + } + } + return; + } + let Some(p) = pointer else { return }; + if !rect.contains(p) { + return; + } + let f = (p.y - rect.top()) / rect.height(); + let position = if l.is_group() && (0.3..0.7).contains(&f) { + "into" + } else if f < 0.5 { + "above" + } else { + "below" + }; + let Some(st) = app.session.active() else { return }; + let mut payload = layer_drop_payload(dragged, l.id, position, &st.selected_layers()); + if background_drop_refused(&st.doc, &payload, l.id, position, copy) { + return; + } + let painter = ui.painter(); + match position { + "into" => { + painter.rect_stroke(rect.shrink(1.0), t.radius_sm, Stroke::new(2.0, t.accent), StrokeKind::Inside); + } + "above" => { + painter.line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, t.accent)); + } + _ => { + painter.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(2.0, t.accent)); + } + } + if copy && let Some(o) = payload.as_object_mut() { + o.insert("copy".into(), json!(true)); + } + if !released && ctx.input(|i| i.pointer.primary_down()) { + crate::layers_panel_ui::preview_reorder(app, &payload); + } + if released { + app.reorder_preview = None; + actions.push(("layer.moveTo".into(), payload)); + } +} + +/// #1721: the drop zones no row owns — the space between two rows and the empty space below the +/// bottom-most one. The drop lands on `target` at `position` (`above` or `below` its row): a copy +/// with ⌥ held on release (Photoshop), a move without. A multi-selection dropped on the row it +/// was grabbed from is left alone: the engine can only copy it beside each of its own layers. +pub(super) fn layer_drop_zone( + app: &mut PhotocraftApp, + ctx: &egui::Context, + ui: &egui::Ui, + zone: Rect, + target: (LayerId, Rect), + position: &'static str, + actions: &mut Vec<(String, Value)>, +) { + let Some(dragged) = ctx.data(|d| d.get_temp::(egui::Id::unique("layer-drag"))) else { return }; + let selected = app.session.active().map(|st| st.selected_layers()).unwrap_or_default(); + if target.0 == LayerId(dragged) && selected.len() > 1 && selected.contains(&target.0) { + return; + } + let Some(p) = ctx.input(|i| i.pointer.interact_pos()) else { return }; + if !zone.contains(p) { + return; + } + let t = Tokens::get(ctx); + let line = if position == "above" { [target.1.left_top(), target.1.right_top()] } else { [target.1.left_bottom(), target.1.right_bottom()] }; + ui.painter().line_segment(line, Stroke::new(2.0, t.accent)); + let mut payload = layer_drop_payload(dragged, target.0, position, &selected); + if ctx.input(|i| i.modifiers.alt) + && let Some(o) = payload.as_object_mut() + { + o.insert("copy".into(), json!(true)); + } + if ctx.input(|i| i.pointer.any_released()) { + app.reorder_preview = None; + actions.push(("layer.moveTo".into(), payload)); + } else if ctx.input(|i| i.pointer.primary_down()) { + crate::layers_panel_ui::preview_reorder(app, &payload); + } +} + +/// An fx row being dragged: the layer it belongs to and the effect index (`None` = the "Effects" +/// row, all of them). +pub(super) type FxDrag = (u64, Option); + +/// A mask thumbnail being dragged: the layer and which of its masks (#3113, #3119). +pub(super) type MaskDrag = (u64, MaskKind); + +pub(super) fn mask_drag_key() -> egui::Id { + egui::Id::unique("mask-drag") +} + +/// Which mask's thumbnail (where it was drawn last frame) the row's drag starts on, if any. +pub(super) fn starts_mask_drag(ctx: &egui::Context, l: &Layer, resp: &egui::Response) -> Option { + if !resp.drag_started() { + return None; + } + let p = ctx.input(|i| i.pointer.press_origin())?; + let (thumbs, _) = crate::mask_thumbs_ui::recorded(ctx, l.id.0)?; + let kind = thumbs.iter().find(|(_, r)| r.contains(p))?.0; + let present = match kind { + MaskKind::Pixel => l.mask.is_some(), + MaskKind::Vector => l.vector_mask.is_some(), + }; + present.then_some(kind) +} + +pub(super) fn fx_drag_key() -> egui::Id { + egui::Id::unique("fx-drag") +} + +/// Start dragging the effects of `layer`: one (`effect`) or all of them. +pub(super) fn start_fx_drag(ctx: &egui::Context, layer: LayerId, effect: Option) { + ctx.data_mut(|d| d.insert_temp::(fx_drag_key(), (layer.0, effect))); +} + +/// While effects are dragged: their name by the pointer, and the copy cursor while ⌥ is held. +pub(super) fn fx_drag_feedback(ctx: &egui::Context, doc: &photocraft_doc::Document) { + let Some((from, effect)) = ctx.data(|d| d.get_temp::(fx_drag_key())) else { return }; + let Some(p) = ctx.input(|i| i.pointer.interact_pos()) else { return }; + // `Effect::label` is the English key; translate for the drag ghost like the Layers panel rows. + let label = match effect { + Some(i) => doc.layer(LayerId(from)).and_then(|l| l.effects.items.get(i)).map(|e| tl!(e.label())).unwrap_or_default(), + None => tl!("Effects"), + }; + crate::layer_transfer::ghost(ctx, p, label); + if ctx.input(|i| i.modifiers.alt) { + ctx.set_cursor_icon(egui::CursorIcon::Copy); + } +} + +/// The command for dropping effects of layer `from` on `target`: they move there, or with ⌥ held +/// on release are copied (Photoshop). `effect` is one effect row, or all effects when `None`. +fn fx_drop_action(from: u64, effect: Option, target: LayerId, copy: bool) -> (String, Value) { + let mut payload = json!({"from": from, "to": target.0, "copy": copy}); + if let Some(o) = payload.as_object_mut() + && let Some(i) = effect + { + o.insert("effect".into(), json!(i)); + } + ("layer.layerStyle.transferEffects".into(), payload) +} + +/// A layer row accepts the fx row being dragged: outlined while the pointer is over it, dropped +/// on release. +pub(super) fn fx_drop(ctx: &egui::Context, ui: &egui::Ui, l: &Layer, rect: Rect, actions: &mut Vec<(String, Value)>) { + let Some((from, effect)) = ctx.data(|d| d.get_temp::(fx_drag_key())) else { return }; + let Some(p) = ctx.input(|i| i.pointer.interact_pos()) else { return }; + if from == l.id.0 || !rect.contains(p) { + return; + } + let t = Tokens::get(ctx); + ui.painter().rect_stroke(rect.shrink(1.0), t.radius_sm, Stroke::new(2.0, t.accent), StrokeKind::Inside); + if ctx.input(|i| i.pointer.any_released()) { + actions.push(fx_drop_action(from, effect, l.id, ctx.input(|i| i.modifiers.alt))); + } +} + +/// Photoshop shows a layer's effects as indented sub-rows ("Effects", then each effect). The eye +/// on "Effects" shows or hides them all, the eye on an effect's row just that one (#1622). +pub(super) fn effect_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth: usize, actions: &mut Vec<(String, Value)>) { + let t = Tokens::get(ui.ctx()); + let indent = 30.0 + depth as f32 * 14.0 + 34.0; + // English `Effect::label` keys stay for kind matching; display goes through `tl!` (catalogs + // already have Drop Shadow → 投影, Effects → 效果, …). + let mut rows: Vec<(String, bool, Option<&'static str>)> = vec![(tl!("Effects").into(), l.effects.enabled, None)]; + for e in &l.effects.items { + let kind = crate::layer_style::KINDS.iter().find(|k| k.1 == e.label()).map(|k| k.0); + rows.push((tl!(e.label()).into(), e.enabled(), kind)); + } + for (i, (name, on, kind)) in rows.into_iter().enumerate() { + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); + // Drag the row onto another layer to move its effects there, ⌥-drag to copy them. + if resp.drag_started() { + start_fx_drag(ui.ctx(), l.id, i.checked_sub(1)); + } + if !ui.is_rect_visible(rect) { + continue; + } + if resp.hovered() { + ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.35)); + } + if t.pro { + ui.painter().line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator)); + } + // Nested under the layer's eye column so an effect does not read as its own layer (#4572). + let eye = Rect::from_min_size(pos2(rect.left() + 36.0, rect.center().y - 9.0), vec2(18.0, 18.0)); + // A hidden effect's eye box is left empty (still clickable), like a hidden layer's. + if on { + icons::paint(ui, eye, "eye", 12.0, t.icon); + } + // The whole eye column of the row takes the click, so it never opens the Layer Style dialog. + let eye_cell = Rect::from_min_max(pos2(rect.left() + 30.0, rect.top()), pos2((rect.left() + 58.0).min(rect.right()), rect.bottom())); + if ui.interact(eye_cell, ui.scope_id().with(("fx-eye", l.id.0, i)), Sense::click()).clicked() { + let mut params = json!({"layer": l.id.0, "visible": !on}); + if let (Some(index), Some(o)) = (i.checked_sub(1), params.as_object_mut()) { + o.insert("index".into(), json!(index)); + } + actions.push(("layer.setEffectsVisible".into(), params)); + } + let x = rect.left() + indent + if i == 0 { 8.0 } else { 24.0 }; + if i == 0 { + icons::paint(ui, Rect::from_center_size(pos2(x - 12.0, rect.center().y), vec2(14.0, 14.0)), "sparkles", 11.0, t.text_dim); + } + let right = rect.right() - crate::layer_row_ui::RIGHT_PAD; + crate::layer_row_ui::label( + ui.painter(), + x, + rect.center().y, + right, + &name, + egui::FontId::proportional(11.5), + if on { t.text_dim } else { t.text_faint }, + ); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name.clone())); + if resp.double_clicked() { + crate::layer_style::open_for_layer(app, l.id, kind); + } + // #2846: right-click opens the layer style menu (Create Layer, Copy Layer Style…), as in Photoshop. + resp.context_menu(|ui| { + crate::widgets::style_spectrum_popup_menu(ui); + crate::layer_menu_ui::show_effects(app, ui, l, actions); + }); + } +} diff --git a/crates/ui-egui/src/panels/layer_row.rs b/crates/ui-egui/src/panels/layer_row.rs new file mode 100644 index 0000000000..959ca07da8 --- /dev/null +++ b/crates/ui-egui/src/panels/layer_row.rs @@ -0,0 +1,458 @@ +use super::layer_drag::{MaskDrag, fx_drop, layer_drag_and_drop, mask_drag_key, start_fx_drag, starts_mask_drag}; +use super::layers::simple_lock_toggle; +use super::*; + +/// How a Layers panel row is selected: in the (multi-)selection, the primary/active layer, and +/// whether several layers are selected. +#[derive(Clone, Copy)] +pub(super) struct RowSel { + pub(super) selected: bool, + pub(super) primary: bool, + pub(super) multi: bool, +} + +/// The badge beside the pointer over a thumbnail ⌘-click loads with these modifiers: none for a +/// new selection, + for ⇧ (add), − for ⌥ (subtract), × for ⇧⌥ (intersect). +pub(crate) fn thumb_load_badge(m: egui::Modifiers) -> Option { + crate::tool_feedback::Badge::from_mode(crate::channels_panel::load_operation(m)) +} + +/// The cursor over a thumbnail ⌘-click loads as a selection: a pointing hand, with the selection +/// mode's badge (#7824). +fn thumb_load_cursor(ctx: &egui::Context, p: Pos2, m: egui::Modifiers) { + ctx.set_cursor_icon(egui::CursorIcon::PointingHand); + if let Some(badge) = thumb_load_badge(m) { + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("thumb-load-badge"))); + crate::tool_feedback::draw_badge(&painter, p, badge, false); + } +} + +/// `layer.select` mode for a click with these modifiers (Photoshop: ⌘-click toggles, ⇧-click +/// selects a range, a plain click selects one layer). +fn select_mode(m: egui::Modifiers) -> &'static str { + if m.command { + "toggle" + } else if m.shift { + "range" + } else { + "replace" + } +} + +/// A drag down the Layers panel's eye column (Photoshop): the first eye toggles and every row +/// swept over gets the same visibility, once per row, all in one history step. +#[derive(Clone)] +struct EyeSweep { + visible: bool, + /// The `coalesce` key shared by the drag's `layer.setProps` calls. + key: u64, + swept: Vec, +} + +/// Starts an eye-column sweep from `eye`, or applies a running one to the row `row` of `l`. +fn eye_sweep(ctx: &egui::Context, l: &Layer, row: Rect, eye: &egui::Response, actions: &mut Vec<(String, Value)>) { + let id = egui::Id::unique("layer-eye-sweep"); + let set = + |visible: bool, key: u64| ("layer.setProps".to_string(), json!({"layer": l.id.0, "visible": visible, "coalesce": format!("layer-eye-sweep:{key}")})); + if eye.drag_started() { + let sweep = EyeSweep { visible: !l.visible, key: ctx.cumulative_pass_nr(), swept: vec![l.id.0] }; + actions.push(set(sweep.visible, sweep.key)); + ctx.data_mut(|d| d.insert_temp(id, sweep)); + return; + } + let Some(mut sweep) = ctx.data(|d| d.get_temp::(id)) else { return }; + let (down, pos, delta) = ctx.input(|i| (i.pointer.primary_down(), i.pointer.interact_pos(), i.pointer.delta())); + if !down { + ctx.data_mut(|d| d.remove::(id)); + return; + } + // Everything the pointer passed since the last frame, so a fast drag skips no row. + let Some(p) = pos else { return }; + let (y0, y1) = ((p.y - delta.y).min(p.y), (p.y - delta.y).max(p.y)); + if y1 < row.top() || y0 >= row.bottom() || sweep.swept.contains(&l.id.0) { + return; + } + if l.visible != sweep.visible { + actions.push(set(sweep.visible, sweep.key)); + } + sweep.swept.push(l.id.0); + ctx.data_mut(|d| d.insert_temp(id, sweep)); +} + +/// Marker in the clipped row's existing 12-point slot, beside its thumbnail. +pub(super) fn paint_clipping_indicator(painter: &egui::Painter, at: Pos2, color: Color32) { + let tip = at + vec2(5.0, 3.0); + let stroke = Stroke::new(1.0, color); + painter.add(egui::Shape::line(vec![at + vec2(9.0, -4.0), at + vec2(5.0, -4.0), tip], stroke)); + painter.add(egui::Shape::line(vec![at + vec2(2.0, 0.0), tip, at + vec2(8.0, 0.0)], stroke)); +} + +/// One row of the Layers panel for `l`, `depth` levels inside groups or artboards: it paints the +/// row, queues what a click or drag on it asks for in `actions`, and returns the row's rect. +#[allow(clippy::too_many_arguments)] +pub(super) fn layer_row( + app: &mut PhotocraftApp, + ctx: &egui::Context, + ui: &mut egui::Ui, + doc: &photocraft_doc::Document, + l: &Layer, + depth: usize, + row: RowSel, + actions: &mut Vec<(String, Value)>, +) -> Rect { + let selected = row.selected; + let t = Tokens::get(ctx); + // The Layers Panel Options thumbnail size controls rows and both layer/mask thumbnails. + let (base, row_h) = crate::layers_panel_ui::thumbnail_geometry(app.ui.layers_panel_options.thumbnail_size, t.pro); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click_and_drag()); + // With thumbnails off no mask thumbnail is drawn, so none may keep catching drags from older frames. + if base == 0.0 { + crate::mask_thumbs_ui::forget(ctx, l.id.0); + } + // A drag from a mask's thumbnail drags that mask, not the layer (#3113, #3119). + let mask_drag = starts_mask_drag(ctx, l, &resp); + if let Some(kind) = mask_drag { + ctx.data_mut(|d| d.insert_temp::(mask_drag_key(), (l.id.0, kind))); + } + let mask_drag = mask_drag.is_some(); + layer_drag_and_drop(app, ctx, ui, l, rect, &resp, actions); + fx_drop(ctx, ui, l, rect, actions); + crate::smart_ui::drop_on_row(ctx, ui, l, rect, actions); + if resp.drag_started() && !mask_drag { + crate::layer_transfer::begin_from_panel(app, ctx, l.id); + } + // Rows are painted: name them for screen readers and UI tests. + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &l.name)); + // A row scrolled out of view only keeps its place (#125): a layout's hundreds of rows would + // otherwise lay out names, icons and thumbnails every frame. Group rows stay whole: their + // disclosure triangle is a widget (accessibility, scroll-to). + if !ui.is_rect_visible(rect) && !l.is_group() && !resp.context_menu_opened() && crate::layer_row_ui::renaming(ctx) != Some(l.id.0) { + return rect; + } + let painter = ui.painter_at(rect.expand(1.0)); + let is_hovered = resp.hovered() || app.canvas_hover_layer == Some(l.id); + if resp.hovered() { + app.hover_layer = Some(l.id); + } + if t.pro { + if selected { + painter.rect_filled(rect, 0.0, t.row_selected); + } else if is_hovered { + painter.rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5)); + painter.rect_filled(rect, 0.0, t.accent.gamma_multiply(0.12)); + } + } else if selected { + painter.rect_filled(rect, t.radius, t.hover); + painter.rect_stroke(rect, t.radius, Stroke::new(1.0, t.field_border), StrokeKind::Inside); + } else if is_hovered { + painter.rect_filled(rect, t.radius, t.hover.gamma_multiply(0.5)); + painter.rect_filled(rect, t.radius, t.accent.gamma_multiply(0.12)); + } + let eye_cell = Rect::from_min_max(rect.left_top(), pos2((rect.left() + 30.0).min(rect.right()), rect.bottom())); + if let Some((_, background)) = t.layer_label_colors(l.label) { + painter.rect_filled(eye_cell, 0.0, background); + } + if t.pro { + // Paint dividers over the label so the eye column stays distinct. + painter.line_segment([pos2(rect.left() + 30.0, rect.top()), pos2(rect.left() + 30.0, rect.bottom())], Stroke::new(1.0, t.separator)); + painter.line_segment([rect.left_bottom(), rect.right_bottom()], Stroke::new(1.0, t.separator)); + } + let mut x = rect.left() + 6.0; + // The whole eye column takes drags too (so a drag starting on it never reorders the row): dragging down + // the eyes gives every row swept over the visibility the first eye toggled to (#8467). + let eye_resp = ui.interact(eye_cell, ui.scope_id().with(("eye", l.id.0)), Sense::click_and_drag()); + // A hidden layer's eye box is left empty (still clickable; the whole column takes the click, #8467). + if l.visible { + // Centre the drawing in the column while preserving the visibility hit area. + icons::paint(ui, eye_cell, "eye", 15.0, t.layer_label_icon(l.label)); + } + eye_sweep(ctx, l, rect, &eye_resp, actions); + if eye_resp.clicked() { + // ⌥-click shows only this layer; ⌥-click it again to restore the others. + if ui.input(|i| i.modifiers.alt) { + actions.push(("layer.showOnly".into(), json!({"layer": l.id.0}))); + } else { + actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "visible": !l.visible}))); + } + } + eye_resp.context_menu(|ui| { + crate::widgets::style_spectrum_popup_menu(ui); + crate::layer_menu_ui::color_choices(app, ui, l, row.multi && selected, actions); + }); + // Everything but the thumbnails, the indentation and the name, so a narrow panel squeezes + // the indentation first, then the thumbnails (a layer with two masks has three). + let others = 6.0 + + 28.0 + + if l.is_group() { crate::layer_tree_ui::TRIANGLE_W } else { 0.0 } + + if l.clipped { 12.0 } else { 0.0 } + + crate::layer_row_ui::reserved_width(l); + let ts = if base == 0.0 { 0.0 } else { crate::mask_thumbs_ui::thumb_size(l, base, rect.width() - others) }; + let fixed = others + if ts == 0.0 { 0.0 } else { ts + 6.0 + crate::mask_thumbs_ui::width(l, ts) }; + // A layer inside a group (or an artboard) indents one step more than its depth, past the + // triangle's column, so it sits right of its parent: with only its depth its thumbnail lined + // up under the group's, hiding the hierarchy. Top-level rows don't move. + let steps = if !l.is_group() && depth > 0 { depth + 1 } else { depth }; + x += 28.0 + crate::layer_row_ui::indent(steps, rect.width(), fixed); + let toggled = crate::layer_tree_ui::disclosure(ui, rect, &mut x, l, actions); + if l.clipped { + paint_clipping_indicator(&painter, pos2(x, rect.center().y), t.text_faint); + x += 12.0; + } + let thumb = Rect::from_min_size(pos2(x, rect.center().y - ts / 2.0), vec2(ts, ts)); + if ts > 0.0 { + draw_layer_thumb(app, ctx, ui, doc, l, thumb, row.primary); + x += ts + 6.0; + } + // With thumbnails disabled the labels and disclosure controls remain interactive. + let masks = if ts > 0.0 { crate::mask_thumbs_ui::paint(app, ctx, ui, &painter, doc, l, &mut x, rect.center().y, ts, actions) } else { Default::default() }; + let mask_rect = masks.thumb(crate::mask_thumbs_ui::MaskKind::Pixel); + let vector_rect = masks.thumb(crate::mask_thumbs_ui::MaskKind::Vector); + // Photoshop frames the targeted thumbnail (pixels, mask or vector mask) of the active layer + // with corner brackets. + if row.primary && ts > 0.0 { + let target = if app.ui.filter_mask_target == Some(l.id.0) && app.filter_mask_targeted() { + // The Smart Filters row's filter mask thumbnail carries the brackets. + None + } else if app.ui.vector_mask_target && vector_rect.is_some() { + vector_rect + } else if app.ui.mask_target { + mask_rect.or(Some(thumb)) + } else { + Some(thumb) + }; + if let Some(r) = target { + crate::mask_thumbs_ui::paint_brackets(&painter, r, t.text); + } + } + // Right-hand indicators first; the name gets what is left and ends in "…" (#144). + let fx_open = app.session.active().is_none_or(|d| !d.fx_collapsed.contains(&l.id)); + let (name_right, indicators, fx_toggled) = crate::layer_row_ui::indicators(ui, &painter, rect, x, l, fx_open, actions); + // Dragging the fx badge drags all the layer's effects, not the layer (Photoshop). Like the eye, + // it takes the drag from the row; clicks still reach the row. + if let Some(&(_, badge)) = indicators.iter().find(|(k, _)| *k == crate::layer_row_ui::Indicator::Fx) + && ui.interact(badge, ui.scope_id().with(("fx-badge", l.id.0)), Sense::drag()).drag_started() + { + start_fx_drag(ctx, l.id, None); + } + // Clicking the lock icon unlocks the layer, and makes the Background a normal one (Photoshop, + // #4723). It takes the click from the row, so the row isn't selected. + if let Some(&(_, lock)) = indicators.iter().find(|(k, _)| *k == crate::layer_row_ui::Indicator::Lock) + && ui.interact(lock, ui.scope_id().with(("row-lock", l.id.0)), Sense::click()).clicked() + { + actions.push(simple_lock_toggle(doc.is_background(l.id), l, &json!({"layer": l.id.0}))); + } + let name_color = if l.visible { t.text } else { t.text_faint }; + let font = if selected && !t.pro { theme::medium(13.0) } else { egui::FontId::proportional(if t.pro { 12.0 } else { 13.0 }) }; + // Photoshop before 2026 set the Background layer's name in italics; 2026 sets it upright. + let italic = !t.pro && doc.is_background(l.id); + // Photoshop rows show only the name; the kind sub-label is a Studio-theme addition. + let is_pixel = t.pro || ts == 0.0 || matches!(l.content, LayerContent::Raster(_)); + let name_rect = crate::layer_row_ui::truncated(&painter, &l.name, font, name_color, italic, name_right - x).map(|galley| { + let text_pos = pos2(x, rect.center().y - galley.size().y / 2.0 - if is_pixel { 0.0 } else { 7.0 }); + let r = Rect::from_min_size(text_pos, galley.size()); + painter.galley(text_pos, galley, name_color); + r + }); + if !is_pixel { + let sub = match &l.content { + LayerContent::Adjustment(a) => tl!(a.label()).to_string(), + LayerContent::Group(g) => crate::i18n::trn(crate::i18n::current(), g.children.len() as u64, "Group · {n} layer", "Group · {n} layers"), + other => tl!(other.kind_name()).to_string(), + }; + crate::layer_row_ui::label(&painter, x, rect.center().y + 8.0, name_right, &sub, egui::FontId::proportional(11.0), t.text_faint); + } + crate::layer_row_ui::record( + ctx, + crate::layer_row_ui::RowRects { layer: l.id.0, row: rect, thumbnail: (ts > 0.0).then_some(thumb), name: name_rect, indicators }, + ); + // ⌘-click a layer, mask or vector-mask thumbnail loads its transparency / mask / path as a + // selection (⇧ add, ⌥ subtract, ⇧⌥ intersect) instead of changing the layer selection. + let load_at = |m: egui::Modifiers, p: Pos2| { + if !m.command { + return None; + } + if let Some(kind) = masks.hit(p) { + return Some(crate::mask_thumbs_ui::load_params(l, kind, m)); + } + // The Background has no transparency to load: Photoshop treats the click as a plain one. + (ts > 0.0 && !doc.is_background(l.id) && thumb.expand(2.0).contains(p)) + .then(|| json!({"channel": "transparency", "layer": l.id.0, "operation": crate::channels_panel::load_operation(m)})) + }; + let thumb_load = resp.clicked().then(|| (ui.input(|i| i.modifiers), resp.interact_pointer_pos())).and_then(|(m, pos)| load_at(m, pos?)); + // Over a thumbnail that ⌘ would load, the cursor says what the click does, as in Photoshop (#7824). + if let Some(p) = resp.hover_pos() { + let m = ui.input(|i| i.modifiers); + if load_at(m, p).is_some() { + thumb_load_cursor(ctx, p, m); + } + } + // ⇧-click a mask thumbnail: disable / enable that mask; ⌥-click a layer mask: view it. + let mask_toggle = resp.clicked().then(|| (ui.input(|i| i.modifiers), resp.interact_pointer_pos())).and_then(|(m, pos)| { + let kind = masks.hit(pos?)?; + crate::mask_thumbs_ui::click_command(l, kind, m) + }); + if let Some(p) = thumb_load { + actions.push(("select.loadSelection".into(), p)); + } else if let Some(cmd) = mask_toggle { + actions.push(cmd); + } else if resp.clicked() && !eye_resp.clicked() && !toggled && !fx_toggled && !masks.clicked { + let m = ui.input(|i| i.modifiers); + let pos = resp.interact_pointer_pos(); + let on_thumb = ts > 0.0 && pos.is_some_and(|p| thumb.expand(2.0).contains(p)); + // ⌘-click on the Background thumbnail stands in for the plain click (there is no + // transparency to load): it selects the Background alone, not toggled into the set. + let mode = if m.command && on_thumb && doc.is_background(l.id) { "replace" } else { select_mode(m) }; + actions.push(("layer.select".into(), json!({"layer": l.id.0, "mode": mode}))); + crate::smart_ui::deselect(ctx, doc.id); + // A thumbnail explicitly selects content or a mask. Selecting an adjustment/fill row + // defaults to its mask, but clicking its content thumbnail must leave the mask target. + let on_mask = mask_rect.zip(pos).is_some_and(|(r, p)| r.expand(2.0).contains(p)); + let on_vector = pos.and_then(|p| masks.hit(p)) == Some(crate::mask_thumbs_ui::MaskKind::Vector); + // Clicking the layer thumbnail leaves mask view (#196). + let viewing = app.session.active().and_then(photocraft_engine::mask_view_cmds::current).filter(|v| v.layer == l.id); + if let Some(v) = viewing.filter(|_| on_thumb) { + let mask = if v.filter { "filter" } else { "layer" }; + actions.push((photocraft_engine::mask_view_cmds::ID.into(), json!({"layer": l.id.0, "mode": "off", "mask": mask}))); + } + let content_less = matches!(l.content, LayerContent::Adjustment(_) | LayerContent::Fill(_)); + if on_vector { + // The vector mask thumbnail targets the vector mask: the path tools edit it and the + // Paths panel selects the layer's path. + app.ui.selected_path = Some("layer".into()); + actions.push(("ui.vectorMaskTarget".into(), json!(true))); + } else if on_mask || (content_less && l.mask.is_some() && !on_thumb) { + if on_mask { + // The mask thumbnail also switches Properties to the mask (#3369). + app.ui.properties_layer = None; + } + actions.push(("ui.maskTarget".into(), json!(true))); + } else if on_thumb || !row.primary { + actions.push(("ui.maskTarget".into(), json!(false))); + } + // ⌥-click the layer thumbnail: fit the layer on screen, as Photoshop does. + if on_thumb && m.alt && !m.shift && !m.command { + actions.push(("view.fitLayersOnScreen".into(), Value::Null)); + } + } + // Double-click: the name renames in place (over the row's full height, not just the glyphs: + // #651); the Background, which can't be renamed while it's locked, becomes a normal layer; an + // adjustment, fill or shape thumbnail opens its settings (a solid colour: the Color Picker, + // #2812) and a Smart Object thumbnail its contents, and a type thumbnail edits its text; + // anywhere else on the row opens Layer Style (#350, #537). + // The first click already made this the active layer. + if resp.double_clicked() { + let pos = resp.interact_pointer_pos(); + let on = |r: Rect| pos.is_some_and(|p| r.expand(2.0).contains(p)); + if crate::doc_props_ui::is_background(doc, l) { + actions.push(("layer.new.layerFromBackground".into(), json!({}))); + } else if name_rect.is_some_and(|n| on(Rect::from_x_y_ranges(n.x_range(), rect.y_range()))) { + if let Some(done) = crate::layer_row_ui::start_rename(ctx, l.id.0, &l.name) { + // One rename at a time: starting this one commits any other (#314). + actions.push(done); + } + } else if let Some(kind) = pos.and_then(|p| masks.hit(p)) { + match kind { + crate::mask_thumbs_ui::MaskKind::Pixel => actions.push(("ui.maskTarget".into(), json!(true))), + crate::mask_thumbs_ui::MaskKind::Vector => actions.push(("ui.vectorMaskTarget".into(), json!(true))), + } + if let Some((cmd, val)) = crate::mask_thumbs_ui::double_click_command(app, kind) { + // The preference launches Select and Mask on a pixel mask. + actions.push((cmd.into(), val)); + } else { + // Otherwise double-click opens the mask's settings (Density/Feather). + actions.push(("ui.properties".into(), json!(true))); + } + } else if pos.and_then(|p| masks.hit(p)).is_none() { + let id = match &l.content { + LayerContent::Adjustment(_) | LayerContent::Fill(_) | LayerContent::Shape(_) if ts > 0.0 && on(thumb) => "layer.layerContentOptions", + LayerContent::Smart(_) if ts > 0.0 && on(thumb) => "layer.smartObjects.editContents", + LayerContent::Text(_) if ts > 0.0 && on(thumb) => "type.editText", + _ => "layer.layerStyle.blendingOptions", + }; + if crate::menus::is_enabled(app, id) { + // Null params: run like the menu item, dialog included. + actions.push((id.into(), Value::Null)); + } + } + } + let edit_rect = Rect::from_min_max(pos2(x - 3.0, rect.center().y - 11.0), pos2(name_right.max(x + 40.0), rect.center().y + 11.0)); + if let Some(done) = crate::layer_row_ui::rename_field(ui, l.id.0, edit_rect) { + actions.push(done); + } + // The visibility icon has its own color menu, and the layer-mask thumbnail its mask menu + // (#4575); elsewhere use the full layer menu. + let on_mask_id = ui.scope_id().with(("mask-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)); + } + if !eye_resp.secondary_clicked() && !eye_resp.context_menu_opened() { + resp.context_menu(|ui| { + crate::widgets::style_spectrum_popup_menu(ui); + if ui.ctx().data(|d| d.get_temp::(on_mask_id)).unwrap_or(false) { + crate::layer_menu_ui::show_mask(app, ui, l, 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) + && let Some(done) = crate::layer_row_ui::start_rename(ui.ctx(), l.id.0, &l.name) + { + actions.push(done); + } + }); + } + rect +} + +/// Screen rect and UVs for a layer thumbnail: the document-shaped part of the square cell and of +/// the letterboxed square texture, so tall and wide documents don't show empty bars. +pub(super) fn layer_thumb_fit(cell: Rect, w: u32, h: u32) -> (Rect, Rect) { + crate::channels_panel::fit_thumb(cell, w, h) +} + +fn draw_layer_thumb(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &egui::Ui, doc: &photocraft_doc::Document, l: &Layer, rect: Rect, selected: bool) { + let t = Tokens::get(ctx); + let p = ui.painter(); + match &l.content { + LayerContent::Adjustment(_) | LayerContent::Group(_) => { + p.rect_filled(rect, 6.0, t.field); + let icon = if l.is_group() { "folder" } else { "contrast" }; + icons::paint(ui, rect, icon, 18.0, t.icon); + } + LayerContent::Text(_) => { + // Photoshop: type layers show a "T" tile rather than a pixel thumbnail. + p.rect_filled(rect, if t.pro { 0.0 } else { 6.0 }, Color32::from_gray(if t.pro { 222 } else { 236 })); + icons::paint(ui, rect, "type", 20.0, Color32::from_gray(40)); + } + // Gradient fills show the gradient itself (Photoshop); solid ones their colour. + LayerContent::Fill(f) if crate::gradient_ui::paint_thumbnail(ui, l.id, f, rect) => {} + LayerContent::Fill(photocraft_doc::Fill::Solid(color)) => { + crate::solid_fill_ui::paint_thumbnail(ui, crate::solid_fill_ui::thumbnail_color(app, doc.id, l.id, *color), rect); + } + LayerContent::Fill(_) => { + let c = [128, 128, 128, 255]; + p.rect_filled(rect, 6.0, Color32::from_rgba_unmultiplied(c[0], c[1], c[2], c[3])); + } + _ => { + // Keep row layout and outside thumbnail decorations when the image is clipped. + if ui.is_rect_visible(rect) { + // The texture is a letterboxed square: draw only the part its frame (the document, + // or the layer's bounds) fills. + let (tex, frame) = app.layer_thumb(ctx, doc, l); + let (fitted, uv) = layer_thumb_fit(rect, frame.width(), frame.height()); + widgets::checker(p, fitted, 5.0); + p.image(tex, fitted, uv, Color32::WHITE); + } + } + } + let stroke = if t.pro { + Stroke::new(1.0, Color32::from_gray(20)) + } else if selected { + Stroke::new(1.5, t.text) + } else { + Stroke::new(1.0, t.field_border) + }; + p.rect_stroke(rect, CornerRadius::same(if t.pro { 0 } else { 5 }), stroke, StrokeKind::Outside); + crate::smart_ui::thumb_badge(ui, l, rect); +} diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs new file mode 100644 index 0000000000..11251902e8 --- /dev/null +++ b/crates/ui-egui/src/panels/layers.rs @@ -0,0 +1,580 @@ +use super::layer_drag::{ + FxDrag, MaskDrag, dropped_on, effect_rows, footer_drop, fx_drag_feedback, fx_drag_key, fx_trash_drop, layer_drag_edge_scroll, layer_drop_zone, + mask_drag_key, +}; +use super::layer_row::{RowSel, layer_row}; +use super::options_bar::{LAYER_PCT_W, body_text_width, pct_action, scrub_pct_label}; +use super::*; + +// ----------------------------------------------------------------------------- layers + +/// The simple themes' single lock button. On the Background it converts the layer to a normal +/// one, as clicking the Background's lock does in Photoshop. Elsewhere it clears every lock when +/// any is set, and locks all otherwise. Toggling only "lock all" would leave the Background's +/// transparency lock (still showing as locked), and a second click would lock its pixels, +/// shutting out the Eraser and every other paint tool (#76). +/// The Basic layout's lock toggle: the active layer's state decides, and every target follows it +/// (`targets`: `{"layer": id}` or `{"layers": [ids]}`). +pub(super) fn simple_lock_toggle(background: bool, l: &Layer, targets: &Value) -> (String, Value) { + if background { + return ("layer.new.layerFromBackground".into(), json!({})); + } + let locks = + if l.locks.any() { json!({"transparency": false, "pixels": false, "position": false, "artboard": false, "all": false}) } else { json!({"all": true}) }; + let mut p = targets.clone(); + p["locks"] = locks; + ("layer.setProps".into(), p) +} + +/// The Layers panel's blend modes: Photoshop's, plus the layer's own Paint.NET mode when it has one +/// (an imported `.pdn`), so the menu matches Photoshop's for every other layer. +fn blend_options(groups: bool, current: BlendMode) -> Vec<(BlendMode, &'static str)> { + let own = Some(current).filter(|m| !m.has_psd_equivalent()); + std::iter::once(BlendMode::PassThrough).filter(|_| groups).chain(BlendMode::LAYER_MODES).chain(own).map(|m| (m, m.label())).collect() +} + +/// Fit blend mode + Opacity into the available Layers-panel width (#2309). +/// Preserve the normal translated label when there is room; on a narrow dock, +/// keep the field interactive and give the dropdown the remaining width. +pub(super) fn opacity_row_layout(available: f32, label_width: f32, gap: f32) -> (f32, bool) { + let full_right = label_width + LAYER_PCT_W + 2.0 * gap + 16.0; + // The label shows while the blend dropdown keeps a usable width (at the default dock width + // with an English label it does; a long translated label on a narrow dock gives way). + let show_label = available >= full_right + 80.0; + let reserved = LAYER_PCT_W + gap + if show_label { label_width + gap + 16.0 } else { 0.0 }; + ((available - reserved).max(40.0), show_label) +} + +/// Blend mode, Opacity, the locks and Fill with no layer selected: Photoshop keeps them in place, +/// greyed out at Normal, 100% and unlocked, instead of removing them (#8880). Same layout as the +/// active layer's rows in `layers`. +fn inactive_blend_rows(ui: &mut egui::Ui, pro: bool) { + ui.add_enabled_ui(false, |ui| { + ui.horizontal(|ui| { + let opacity_label = if pro { tl!("Opacity:") } else { tl!("Opacity") }; + let (blend_width, show_opacity_label) = opacity_row_layout(ui.available_width(), body_text_width(ui, opacity_label), ui.spacing().item_spacing.x); + let mut m = BlendMode::Normal; + let options = blend_options(false, m); + widgets::dropdown_wheel_hovered(ui, "blend", tl!("Blend Mode"), &mut m, &options, blend_width); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut o = 100.0; + widgets::popup_value_field(ui, opacity_label, &mut o, 0.0..=100.0, "%", LAYER_PCT_W); + if show_opacity_label { + scrub_pct_label(ui, opacity_label, &mut o, ui.available_width()); + } + }); + }); + ui.add_space((theme::ROW_GAP - ui.spacing().item_spacing.y).max(0.0)); + ui.horizontal(|ui| { + let lock_label = if pro { tl!("Lock:") } else { tl!("Lock") }; + let lang = crate::i18n::current(); + let fill_label = if pro { crate::i18n::tr_ctx(lang, "layers", "Fill:") } else { crate::i18n::tr_ctx(lang, "layers", "Fill") }; + let gap = ui.spacing().item_spacing.x; + let icons_w = if pro { 5.0 * 20.0 + gap } else { 22.0 + gap }; + let fits = body_text_width(ui, lock_label) + icons_w + body_text_width(ui, fill_label) + LAYER_PCT_W + 2.0 * gap <= ui.available_width(); + if fits { + label(ui, lock_label); + } + if pro { + ui.scope(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + for (icon, tip) in [ + ("grid-3x3", tl!("Lock transparent pixels")), + ("brush", tl!("Lock image pixels")), + ("move", tl!("Lock position")), + ("scan", tl!("Prevent auto-nesting in and out of Artboards and Frames")), + ("lock", tl!("Lock all")), + ] { + icons::button(ui, icon, 20.0, false, tip); + } + }); + } else { + icons::button(ui, "lock-open", 22.0, false, tl!("Lock layer")); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut f = 100.0; + widgets::popup_value_field(ui, fill_label, &mut f, 0.0..=100.0, "%", LAYER_PCT_W); + scrub_pct_label(ui, fill_label, &mut f, ui.available_width()); + }); + }); + ui.add_space(2.0); + }); +} + +pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + // A new active layer opens its parent groups and is scrolled into view (#152). + let reveal = crate::layer_reveal::track(app, ui.ctx()); + let Some(st) = app.session.active() else { + empty(ui, tl!("No document")); + return; + }; + let doc = st.doc.clone(); + let active = st.active_layer; + let active_layer = active.and_then(|id| doc.layer(id)); + let selection = st.selected_layers(); + let isolated = st.isolated_layers.clone(); + let mut actions: Vec<(String, Value)> = Vec::new(); + + let t = Tokens::get(ui.ctx()); + app.reorder_preview_hit = false; + if !ui.input(|i| i.pointer.primary_down()) || !app.ui.layers_panel_options.preview_on_canvas_when_reordering_layers { + app.reorder_preview = None; + } + if t.pro && app.ui.layers_panel_options.show_filters { + crate::layer_filter_ui::bar(app, ui); + ui.add_space(4.0); + } + if let Some(l) = active_layer { + // With several layers selected, blend mode, Opacity, Fill and the locks change every one + // of them, as in Photoshop; the controls show the active layer's values. + // The Background stays out of a several-layer change until Photoshop's behaviour is + // confirmed (#5856): Opacity, Fill or a blend mode would turn it into Layer 0. + let ids: Vec = if selection.len() > 1 && selection.contains(&l.id) { + selection.iter().copied().filter(|id| *id == l.id || !doc.layer(*id).is_some_and(|x| crate::doc_props_ui::is_background(&doc, x))).collect() + } else { + vec![l.id] + }; + let targets = if ids.len() > 1 { json!({"layers": ids.iter().map(|id| id.0).collect::>()}) } else { json!({"layer": l.id.0}) }; + // Photoshop greys blend mode, Opacity and Fill for the Background layer. (With the + // Background among several selected, what Photoshop does awaits a check: #5856.) + let bg = crate::doc_props_ui::is_background(&doc, l); + // Pass Through is a group's mode: offered only when every target is a group. + let all_groups = ids.iter().all(|id| doc.layer(*id).is_some_and(|x| x.is_group())); + ui.horizontal(|ui| { + ui.add_enabled_ui(!bg, |ui| { + let mut m = l.blend; + // Reserve space for the numeric field first. On a narrow dock, hide the + // redundant visible Opacity label rather than force the dropdown beyond + // the panel's right edge (#2309). The numeric field keeps its name. + let opacity_label = if t.pro { tl!("Opacity:") } else { tl!("Opacity") }; + let (blend_width, show_opacity_label) = + opacity_row_layout(ui.available_width(), body_text_width(ui, opacity_label), ui.spacing().item_spacing.x); + let (chosen, hovered) = + widgets::dropdown_wheel_hovered(ui, "blend", tl!("Blend Mode"), &mut m, &blend_options(all_groups, l.blend), blend_width); + // One step per choice: a click, an arrow key or each wheel notch (#1747). + for m in &chosen { + let mut p = targets.clone(); + p["blend"] = json!(m.label()); + actions.push(("layer.setProps".into(), p)); + } + // Hovering a mode previews it on the canvas (#970). + crate::blend_preview::hover(app, &ids, hovered.filter(|_| chosen.is_empty())); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut o = l.opacity * 100.0; + let field = widgets::popup_value_field(ui, opacity_label, &mut o, 0.0..=100.0, "%", LAYER_PCT_W); + // On a narrow dock the (scrubby) label yields its room to the controls (#2309). + let scrub = if show_opacity_label { + scrub_pct_label(ui, opacity_label, &mut o, ui.available_width()) + } else { + widgets::PopupFieldResponse::default() + }; + if field.changed || scrub.changed { + actions.push(pct_action(&targets, "opacity", o, scrub.drag.or(field.drag))); + } + }); + }); + }); + // Docks zero the item spacing: keep the Opacity and Fill fields apart (#155). + ui.add_space((theme::ROW_GAP - ui.spacing().item_spacing.y).max(0.0)); + ui.horizontal(|ui| { + let lock_label = if t.pro { tl!("Lock:") } else { tl!("Lock") }; + // Layer fill opacity (≠ Edit › Fill / path fill → Tô). + let lang = crate::i18n::current(); + let fill_label = if t.pro { crate::i18n::tr_ctx(lang, "layers", "Fill:") } else { crate::i18n::tr_ctx(lang, "layers", "Fill") }; + // In a narrow panel with long translated labels, drop the "Lock:" text (the icons keep + // their tooltips) rather than let the Fill label run over the lock icons. + let gap = ui.spacing().item_spacing.x; + let icons_w = if t.pro { 5.0 * 20.0 + gap } else { 22.0 + gap }; + let fits = body_text_width(ui, lock_label) + icons_w + body_text_width(ui, fill_label) + LAYER_PCT_W + 2.0 * gap <= ui.available_width(); + if fits { + label(ui, lock_label); + } + if t.pro { + // The lock icons touch, but only they: the Fill label keeps the same gap before its + // field as Opacity's, so both stack in one right-aligned column (#2085). + ui.scope(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + let lk = l.locks; + for (key, icon, tip, on) in [ + ("transparency", "grid-3x3", tl!("Lock transparent pixels"), lk.transparency), + ("pixels", "brush", tl!("Lock image pixels"), lk.pixels), + ("position", "move", tl!("Lock position"), lk.position), + ("artboard", "scan", tl!("Prevent auto-nesting in and out of Artboards and Frames"), lk.artboard), + ("all", "lock", tl!("Lock all"), lk.all), + ] { + // Lock Image Pixels includes Lock Transparent Pixels, which waits for it (#4892). + let enabled = key != "transparency" || !lk.pixels; + if ui.add_enabled_ui(enabled, |ui| icons::button(ui, icon, 20.0, on, tip)).inner.clicked() { + let mut p = targets.clone(); + p["locks"] = json!({ key: !on }); + actions.push(("layer.setProps".into(), p)); + } + } + }); + } + if !t.pro { + let locked = l.locks.any(); + if icons::button(ui, if locked { "lock" } else { "lock-open" }, 22.0, locked, tl!("Lock layer")).clicked() { + actions.push(simple_lock_toggle(crate::doc_props_ui::is_background(&doc, l), l, &targets)); + } + } + ui.add_enabled_ui(!bg, |ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut f = l.fill_opacity * 100.0; + let field = widgets::popup_value_field(ui, fill_label, &mut f, 0.0..=100.0, "%", LAYER_PCT_W); + let scrub = scrub_pct_label(ui, fill_label, &mut f, ui.available_width()); + if field.changed || scrub.changed { + actions.push(pct_action(&targets, "fill", f, scrub.drag.or(field.drag))); + } + }) + }); + }); + ui.add_space(2.0); + } else { + inactive_blend_rows(ui, t.pro); + } + + // Top of the stack first, groups above their contents, closed groups' contents hidden (#126). + let rows = crate::layer_tree_ui::panel_rows(app, &doc); + let ctx = ui.ctx().clone(); + let footer = widgets::footer_height(ui) + ui.spacing().item_spacing.y; + let fill = ui.available_height() > footer + 60.0; + let rows_h = if fill { ui.available_height() - footer } else { f32::INFINITY }; + egui::ScrollArea::vertical() + // Keep each document's position independent, even when tab indices change (#5522). + .id_salt(("layer-rows", doc.id.0)) + .max_height(rows_h) + .min_scrolled_height(if fill { rows_h } else { 0.0 }) + .auto_shrink([false, !fill]) + .show(ui, |ui| { + // The drag keys are set only by actual layer-row and fx drags, not clicks or + // ordinary scrolling. The ScrollArea applies this to its own content. + // An fx drag that never saw its release (the panel was hidden) must not outlive the button. + if !ctx.input(|i| i.pointer.primary_down() || i.pointer.any_released()) { + ctx.data_mut(|d| d.remove::(fx_drag_key())); + ctx.data_mut(|d| d.remove::(mask_drag_key())); + ctx.data_mut(|d| d.remove::(crate::smart_ui::drag_key())); + } + let held = ctx.data(|d| { + d.get_temp::(egui::Id::unique("layer-drag")).is_some() + || d.get_temp::(fx_drag_key()).is_some() + || d.get_temp::(crate::smart_ui::drag_key()).is_some() + }); + let dragging = held && ctx.input(|i| i.pointer.primary_down()); + let pointer = ctx.input(|i| i.pointer.interact_pos()); + let delta = layer_drag_edge_scroll(pointer, ui.clip_rect(), dragging, ctx.input(|i| i.stable_dt)); + if delta != 0.0 { + ui.scroll_with_delta(vec2(0.0, delta)); + ctx.request_repaint(); + } + let filter = crate::layer_filter_ui::Filter::of(&app.ui); + let fx_collapsed = app.session.active().map(|d| d.fx_collapsed.clone()).unwrap_or_default(); + crate::layer_row_ui::begin(ui.ctx()); + // The drawn rows, top to bottom (#1721): the space between them and below the last + // one is a drop zone too. + let mut drawn: Vec<(LayerId, Rect)> = Vec::new(); + for &(depth, l) in &rows { + // Select › Isolate Layers. + if !photocraft_engine::select_extra_cmds::isolation_shows(&doc, &isolated, l.id) { + continue; + } + if !filter.shows(l) { + continue; + } + let row = RowSel { selected: selection.contains(&l.id), primary: active == Some(l.id), multi: selection.len() > 1 }; + let top = ui.cursor().top(); + drawn.push((l.id, layer_row(app, &ctx, ui, &doc, l, depth, row, &mut actions))); + if reveal == Some(l.id) { + crate::layer_reveal::scroll_to_row(ui, top); + } + if !l.effects.items.is_empty() && fx_collapsed.iter().all(|id| *id != l.id) { + effect_rows(app, ui, l, depth, &mut actions); + } + if !fx_collapsed.contains(&l.id) { + crate::smart_ui::filter_rows(app, ui, &doc, l, depth, &mut actions); + } + } + // The bottom of everything drawn: the last layer's effect and Smart Filter rows sit + // under its own row (#8764). + let rows_bottom = ui.min_rect().bottom(); + // #1721: the list takes drops everywhere, not only on a row (Photoshop): the space + // between two rows lands above the lower one, the empty space below the bottom-most + // row below it. Both copy with ⌥ held, move without. + for w in drawn.windows(2) { + let gap = Rect::from_min_max(pos2(w[0].1.left(), w[0].1.bottom()), pos2(w[0].1.right(), w[1].1.top())); + layer_drop_zone(app, &ctx, ui, gap, (w[1].0, w[1].1), "above", &mut actions); + } + if let Some(&(last, last_rect)) = drawn.last() { + let below = Rect::from_min_max(pos2(last_rect.left(), last_rect.bottom()), pos2(last_rect.right(), ui.clip_rect().bottom())); + layer_drop_zone(app, &ctx, ui, below, (last, last_rect), "below", &mut actions); + // A click on that empty space deselects every layer, as in Photoshop (#8100). It + // starts under the last layer's sub-rows, which take their own clicks. + let empty = Rect::from_min_max(pos2(below.left(), rows_bottom), below.max); + if empty.height() > 0.0 && ui.interact(empty, ui.scope_id().with("layers-empty-space"), Sense::click()).clicked() && !selection.is_empty() { + actions.push(("select.deselectLayers".into(), json!({}))); + } + } + // Tab / ⇧Tab in a rename: rename the layer below / above next, as in Photoshop. The + // Background isn't renamed in place (double-clicking it converts it), so it ends there. + if let Some((from, up)) = crate::layer_row_ui::take_next_rename(ui.ctx()) + && let Some(at) = drawn.iter().position(|(id, _)| id.0 == from) + && let Some(&(next, _)) = if up { at.checked_sub(1).and_then(|i| drawn.get(i)) } else { drawn.get(at + 1) } + && let Some(l) = doc.layer(next).filter(|l| !crate::doc_props_ui::is_background(&doc, l)) + && let Some(done) = crate::layer_row_ui::start_rename(ui.ctx(), next.0, &l.name) + { + actions.push(done); + } + // ⌥-click the line between two layers: clip / release the upper one (#967). + crate::clip_line_ui::show(ui, &doc, &mut actions); + // A rename whose row is gone (deleted, filtered out, inside a closed group) ends, + // committed: nothing else could commit or cancel it. + if let Some(layer) = crate::layer_row_ui::renaming(ui.ctx()) + && !crate::layer_row_ui::recorded(ui.ctx()).iter().any(|r| r.layer == layer) + && let Some(done) = crate::layer_row_ui::end_rename(ui.ctx(), true) + { + actions.push(done); + } + // Likewise a selected smart filter whose row is gone. + crate::smart_ui::forget_hidden(ui.ctx(), doc.id); + }); + // Leaving the list or hovering an invalid target immediately cancels the temporary + // image. The release still uses the actual command, not the preview snapshot. + if !app.reorder_preview_hit { + app.reorder_preview = None; + } + // A layer being dragged can also be dropped on the footer's Delete, New Layer and Group + // buttons (#736); read the drag before it ends. + let footer_drag = ctx.data(|d| d.get_temp::(egui::Id::unique("layer-drag"))).map(|id| { + let in_selection = selection.iter().any(|s| s.0 == id); + (id, in_selection) + }); + // An effect row can be dropped on Delete too (#3102), and a mask's thumbnail (#3113, #3119). + let fx_footer_drag = ctx.data(|d| d.get_temp::(fx_drag_key())); + fx_drag_feedback(&ctx, &doc); + // And a smart filter's row (#4271). + let filter_footer_drag = ctx.data(|d| d.get_temp::(crate::smart_ui::drag_key())); + crate::smart_ui::drag_feedback(&ctx, &doc); + let mask_footer_drag = ctx.data(|d| d.get_temp::(mask_drag_key())); + if let Some((_, kind)) = mask_footer_drag + && let Some(p) = ctx.input(|i| i.pointer.interact_pos()) + { + let label = if kind == MaskKind::Vector { tl!("Vector Mask") } else { tl!("Layer Mask") }; + crate::layer_transfer::ghost(&ctx, p, label); + } + // End any layer drag after every row has had a chance to accept the drop. + if ctx.input(|i| i.pointer.any_released()) { + ctx.data_mut(|d| d.remove::(egui::Id::unique("layer-drag"))); + ctx.data_mut(|d| d.remove::(fx_drag_key())); + ctx.data_mut(|d| d.remove::(mask_drag_key())); + ctx.data_mut(|d| d.remove::(crate::smart_ui::drag_key())); + } + widgets::panel_footer(ui, |ui| { + let active_layer = active.and_then(|id| doc.layer(id)); + let (delete, label) = if app.ui.vector_mask_target && active_layer.is_some_and(|l| l.vector_mask.is_some()) { + ("layer.vectorMask.delete", "Delete Vector Mask") + } else if app.ui.mask_target && active_layer.is_some_and(|l| l.mask.is_some()) { + ("layer.layerMask.delete", "Delete Layer Mask") + } else { + ("layer.delete", "Delete layer") + }; + let trash = icons::button(ui, "trash", 26.0, false, tl!(label)); + // A selected smart filter row is what Delete removes, as in Photoshop (#4751). + let picked_filter = crate::smart_ui::selected(&ctx, &doc, active); + if trash.clicked() + && let Some(picked) = picked_filter + { + actions.push(crate::smart_ui::trash_action(picked)); + crate::smart_ui::deselect(&ctx, doc.id); + } else if trash.clicked() { + // Like Photoshop, ⌥/Alt-click deletes without asking. + let confirm = delete == "layer.delete" && !ui.input(|i| i.modifiers.alt); + let params = if confirm { json!({"__trash": true}) } else { json!({}) }; + actions.push((delete.into(), params)); + } + actions.extend(footer_drop(ui, &trash, footer_drag, "layer.delete")); + actions.extend(fx_trash_drop(ui, &trash, fx_footer_drag)); + if let Some(drag) = filter_footer_drag + && dropped_on(ui, &trash) + { + actions.push(crate::smart_ui::trash_action(drag)); + } + // Photoshop asks "Apply mask to layer before removing?" or "Delete the vector mask?" + // (`mask_trash_prompt`). + if let Some((layer, kind)) = mask_footer_drag + && dropped_on(ui, &trash) + { + actions.push(crate::mask_trash_prompt::drop_action(layer, kind)); + } + // A click follows the selected thumbnail; name that action for screen readers even + // though dropping a whole layer row onto the same button always deletes the layer. + trash.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(label))); + let new_layer = icons::button(ui, "square-plus", 26.0, false, &crate::shortcuts::tip_label(app, "Create a new layer", "layer.new.layer")); + if new_layer.clicked() { + // A click makes the layer above the selection; ⌥-click asks first (the New Layer + // dialog) and ⌘/Ctrl-click adds it below, as in Photoshop. + let (alt, below) = ui.input(|i| (i.modifiers.alt, i.modifiers.command)); + let params = if alt { + Value::Null + } else if below { + json!({"position": "below"}) + } else { + json!({}) + }; + actions.push(("layer.new.layer".into(), params)); + } + actions.extend(footer_drop(ui, &new_layer, footer_drag, "layer.duplicate")); + let group = icons::button(ui, "folder", 26.0, false, tl!("Create a new group")); + if group.clicked() { + // Multiple selected layers share one group. Shift also groups a single selection. + let shift = ui.input(|i| i.modifiers.shift); + let cmd = if (shift || selection.len() > 1) && active_layer.is_some() { "layer.groupLayers" } else { "layer.new.group" }; + actions.push((cmd.into(), json!({}))); + } + actions.extend(footer_drop(ui, &group, footer_drag, "layer.groupLayers")); + let adj = footer_menu_button(ui, "adjustment-layer", 26.0, tl!("Create new fill or adjustment layer")); + // Opens on the press like Photoshop's: drag onto an item and release to choose it (#2071). + crate::press_menu::show(&adj, |ui, menu| { + ui.set_min_width(190.0); + for c in photocraft_engine::command_specs().iter().filter(|c| c.id.starts_with("layer.newAdjustmentLayer.")) { + if menu.item(ui, tl!(c.label).trim_end_matches('…')) { + actions.push((c.id.into(), json!({}))); + } + } + ui.separator(); + if menu.item(ui, tl!("Solid Color…")) { + actions.push(("layer.newFillLayer.solidColor".into(), json!({}))); + } + if menu.item(ui, tl!("Gradient…")) { + actions.push(("layer.newFillLayer.gradient".into(), json!({}))); + } + }); + // Like Photoshop the button never replaces a mask (#2075): with a layer mask it adds a + // vector mask, and with both it is greyed. + let alt = ui.input(|i| i.modifiers.alt); + let mask_cmd = crate::layer_menu_ui::mask_button_command(active_layer, doc.selection.is_some(), alt); + let mask_tip = if active_layer.is_some_and(|l| l.mask.is_some()) { + tl!("Add vector mask").to_string() + } else { + crate::i18n::fmt(tl!("Add a mask (from the selection; {key} inverts)"), &[("key", &crate::shortcuts::pretty("Alt"))]) + }; + let mask_btn = ui.add_enabled_ui(mask_cmd.is_some(), |ui| icons::button(ui, "layer-mask", 26.0, false, &mask_tip)).inner; + mask_btn.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &mask_tip)); + if mask_btn.clicked() + && let Some(cmd) = mask_cmd + { + // A path selected in the Paths panel becomes the vector mask, as in Photoshop (#4728); + // Alt still inverts it. + match crate::vector_ui::selected_document_path(app).filter(|_| cmd.starts_with("layer.vectorMask.")) { + Some(name) => actions.push(("layer.vectorMask.currentPath".into(), json!({"name": name, "hide": alt}))), + None => actions.push((cmd.into(), json!({}))), + } + } + let fx = fx_button(ui, 26.0, tl!("Add a layer style")); + crate::press_menu::show(&fx, |ui, menu| { + ui.set_min_width(180.0); + if menu.item(ui, tl!("Blending Options…")) { + crate::layer_style::open(app, None); + } + ui.separator(); + for &(kind, label) in crate::layer_style::KINDS { + if menu.item(ui, format!("{}…", tl!(label))) { + crate::layer_style::open(app, Some(kind)); + } + } + }); + // Photoshop's footer starts with Link Layers (enabled with two or more layers selected). + let can_link = app.session.is_enabled("layer.linkLayers"); + if ui.add_enabled_ui(can_link, |ui| icons::button(ui, "link-2", 26.0, false, tl!("Link layers"))).inner.clicked() { + actions.push(("layer.linkLayers".into(), json!({}))); + } + }); + for (id, p) in actions { + // A row click commits even when it selects the layer already being edited (#5584). + // Finish before selection changes so the existing type session keeps its own target. + if id == "layer.select" && app.ui.text_edit.is_some() { + crate::type_tool::commit(app); + } + if id == "ui.maskTarget" { + app.end_filter_mask_view(); + app.ui.mask_target = p.as_bool().unwrap_or(false); + app.ui.vector_mask_target = false; + app.ui.filter_mask_target = None; + app.sync_mask_targets(); + continue; + } + if id == "ui.vectorMaskTarget" { + app.end_filter_mask_view(); + app.ui.vector_mask_target = p.as_bool().unwrap_or(false); + app.ui.mask_target = false; + app.ui.filter_mask_target = None; + app.sync_mask_targets(); + continue; + } + if id == "ui.filterMaskTarget" { + app.select_filter_mask_target(p.as_u64()); + continue; + } + // Double-clicking a mask thumbnail opens its settings: show Properties. + if id == "ui.properties" { + app.ui.panels.properties = true; + app.ui.dock_tabs.properties = 0; + app.ui.dock.collapsed.retain(|g| *g != crate::dock::Group::Properties); + continue; + } + if p.is_null() || id == "layer.newFillLayer.solidColor" { + // Context-menu items and the Layers footer's Solid Color… action behave like + // their menu-bar twins. In particular, a new Solid Color fill opens its picker. + let ctx = ui.ctx().clone(); + let params = if p.is_null() { json!({}) } else { p }; + if let Err(e) = crate::menus::invoke(app, &ctx, &id, params) { + app.ui.status = e; + app.ui.status_error = true; + } + continue; + } + let _ = app.run(&id, p); + } +} + +pub(super) fn footer_label(command: &str) -> &'static str { + match command { + "layer.delete" => tl!("Delete layer"), + "layer.duplicate" => tl!("Create a new layer"), + _ => tl!("Create a new group"), + } +} + +/// The small down-arrow makes it clear that the footer icon expands into a menu. +fn footer_menu_arrow(ui: &egui::Ui, rect: Rect) { + let t = Tokens::get(ui.ctx()); + let arrow = Rect::from_min_size(rect.right_bottom() - vec2(11.0, 10.0), vec2(9.0, 9.0)); + icons::paint(ui, arrow, "chevron-down", 8.0, t.text_dim); +} + +fn footer_menu_button(ui: &mut egui::Ui, icon: &str, size: f32, tip: &str) -> egui::Response { + let response = icons::button(ui, icon, size, false, tip); + // Named for screen readers (and tests) after its tooltip. + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); + footer_menu_arrow(ui, response.rect); + response +} + +/// Photoshop's italic "fx" footer button (no icon-font equivalent). +fn fx_button(ui: &mut egui::Ui, size: f32, tip: &str) -> egui::Response { + let t = Tokens::get(ui.ctx()); + let (r, resp) = ui.allocate_exact_size(vec2(size, size), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(r, t.radius_sm, t.hover); + } + let mut job = egui::text::LayoutJob::default(); + job.append("fx", 0.0, egui::TextFormat { font_id: egui::FontId::proportional(15.0), color: t.icon, italics: true, ..Default::default() }); + let g = ui.painter().layout_job(job); + ui.painter().galley(r.center() - g.size() / 2.0, g, t.icon); + footer_menu_arrow(ui, r); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); + resp.on_hover_text(tip) +} + +pub(super) fn channels(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + crate::channels_panel::show(app, ui); +} diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs new file mode 100644 index 0000000000..a6bfbf00c8 --- /dev/null +++ b/crates/ui-egui/src/panels/navigator.rs @@ -0,0 +1,223 @@ +use super::*; + +pub(super) fn navigator(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + let Some(idx) = app.session.active_index() else { + empty(ui, tl!("No document")); + return; + }; + let ctx = ui.ctx().clone(); + let size = app.session.documents()[idx].doc.size; + let avail = ui.available_width(); + // The preview fills the group's height above the zoom controls (their height as measured + // last frame), so it grows when the group is made taller, as in Photoshop (#2726). + let controls_h = ui.data(|d| d.get_temp::(navigator_controls_id())).unwrap_or(48.0); + let left = ui.available_height() - controls_h; + let box_h = if left.is_finite() { left.max(40.0) } else { 150.0 }; + let (frame, resp) = ui.allocate_exact_size(vec2(avail, box_h), Sense::click_and_drag()); + ui.painter().rect_filled(frame, t.radius_sm, t.canvas); + let rect = navigator_fit(frame, size.width, size.height); + ui.data_mut(|d| d.insert_temp(navigator_preview_id(), rect)); + // On the GPU canvas, its own texture at this size (#4518); otherwise the CPU thumbnail. + if let Some(params) = crate::canvas::navigator_gpu_view(app, idx, rect, &ctx) { + crate::gpu_canvas::GpuCanvas::paint(ui.painter(), rect, params); + } else if crate::canvas::navigator_waits_for_gpu(app, idx, &ctx) { + widgets::checker(ui.painter(), rect, 6.0); + } else { + let Some(tex) = crate::canvas::navigator_texture(app, &ctx, idx) else { return }; + widgets::checker(ui.painter(), rect, 6.0); + ui.painter().image(tex, rect, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE); + } + let s = rect.width() / size.width.max(1) as f32; + // ⌘/Ctrl-drag over the preview draws a rectangle the view then zooms to, as in Photoshop + // (#6872); a plain click or drag moves the view. + let command = crate::workspace_ui::sticky_mods(app, ctx.input(|i| i.modifiers)).command; + if resp.drag_started() && command { + let start = ctx.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()); + ui.data_mut(|d| match start { + Some(p) => { + d.insert_temp(navigator_zoom_drag_id(), p); + } + None => d.remove::(navigator_zoom_drag_id()), + }); + } + let zoom_from = ui.data(|d| d.get_temp::(navigator_zoom_drag_id())); + if let Some(from) = zoom_from { + if let Some(to) = resp.interact_pointer_pos() { + let r = Rect::from_two_pos(from, to).intersect(rect); + crate::tool_feedback::draw_ants(ui.painter(), &[r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()], true); + if resp.drag_stopped() { + let doc_rect = Rect::from_min_max(((r.min - rect.min) / s).to_pos2(), ((r.max - rect.min) / s).to_pos2()); + let (canvas, ppp, aspect) = (app.last_canvas_rect, app.canvas_ppp(), app.ui.view.display_aspect()); + navigator_zoom_to(&mut app.ui.views[idx], doc_rect, [size.width, size.height], canvas.size(), ppp, aspect); + } + } + if resp.drag_stopped() || !resp.dragged() { + ui.data_mut(|d| d.remove::(navigator_zoom_drag_id())); + } + } else if (resp.clicked() || resp.dragged()) + && let Some(pp) = resp.interact_pointer_pos() + { + let d = (pp - rect.min) / s; + app.ui.views[idx].center = [d.x.clamp(0.0, size.width as f32), d.y.clamp(0.0, size.height as f32)]; + app.ui.views[idx].zoom_animating = false; + app.ui.views[idx].zoom_anchor = None; + app.ui.views[idx].fit_pending = false; + } + if command && resp.hovered() { + ctx.set_cursor_icon(egui::CursorIcon::ZoomIn); + } + // The Navigator has its own zoom target: an unmodified wheel over the preview + // should zoom even when the document canvas is configured to scroll on wheel. + // Use the canvas wheel classifier to honour one ×1.1 step per notch, + // eased over its frames or instant as General › Animated Zoom says. + let pinch_zooms = app.session.prefs().enhanced_controls.zoom_with_trackpad_pinch; + let animated_zoom = app.session.prefs().general.animated_zoom; + let touch_gestures = app.session.prefs().enhanced_controls.touch_gestures; + let navigator_wheel = egui::Id::unique("pc-navigator-wheel"); + if resp.hovered() + && let Some(crate::wheel_nav::Wheel::Zoom(factor)) = + crate::wheel_nav::read_with(&ctx, true, pinch_zooms, animated_zoom, navigator_wheel, true, true, touch_gestures) + { + let view = &mut app.ui.views[idx]; + let next = crate::zoom_levels::clamp(view.zoom * factor, view.doc_size); + if next != view.zoom * factor { + crate::wheel_nav::settle(&ctx, navigator_wheel); + } + if next != view.zoom { + view.zoom = next; + view.zoom_animating = false; + view.zoom_anchor = None; + view.fit_pending = false; + } + } + // Visible-area rectangle. + let v = app.ui.views[idx].clone(); + let canvas = app.last_canvas_rect; + let (zoom, center) = + if v.zoom_animating && app.session.prefs().general.animated_zoom { v.display_camera.unwrap_or((v.zoom, v.center)) } else { (v.zoom, v.center) }; + let point_zoom = (zoom / app.canvas_ppp()).max(1e-6); + // Pixel aspect correction shows fewer document columns across the same canvas width. + let vw = canvas.width() / point_zoom / app.ui.view.display_aspect() * s; + let vh = canvas.height() / point_zoom * s; + let c = pos2(rect.min.x + center[0] * s, rect.min.y + center[1] * s); + let vr = Rect::from_center_size(c, vec2(vw, vh)).intersect(frame.shrink(1.0)); + ui.painter().rect_stroke(vr, 2.0, Stroke::new(1.5, Color32::from_rgb(255, 84, 84)), StrokeKind::Middle); + // Photoshop's one row under the preview (#4840): the zoom, typed in percent, then Zoom Out, + // the slider and Zoom In. + let controls = ui.vertical(|ui| { + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let set = |app: &mut PhotocraftApp, zoom: f32, animate: bool| { + let target = crate::zoom_levels::clamp(zoom, v.doc_size); + if target != app.ui.views[idx].zoom { + app.ui.views[idx].zoom = target; + app.ui.views[idx].request_zoom_animation(animate && app.session.prefs().general.animated_zoom); + } + app.ui.views[idx].fit_pending = false; + }; + let mut pct = v.zoom * 100.0; + let field = widgets::compact_wrapping_value_field(ui, &mut pct, crate::zoom_levels::percent_range(&app.ui.views[idx]), "%", vec2(64.0, NAV_ROW_H)) + .accessible_name(tl!("Zoom")); + if field.changed() { + set(app, pct / 100.0, false); + } + let out = crate::brush_picker::named(icons::button(ui, "minus", NAV_ROW_H, false, tl!("Zoom Out")), "Zoom Out"); + if out.clicked() { + set(app, crate::zoom_levels::step(v.zoom, -1, v.doc_size), true); + } + // The whole zoom range, and always the current zoom: a narrower slider would pull it back. + let (lo, hi) = (crate::zoom_levels::min(v.doc_size).min(v.zoom).log2(), crate::zoom_levels::MAX.max(v.zoom).log2()); + let mut lz = v.zoom.log2(); + let slider_w = (ui.available_width() - NAV_ROW_H - 4.0).max(60.0); + let slid = ui.allocate_ui(vec2(slider_w, NAV_ROW_H), |ui| lz.is_finite() && widgets::slider(ui, &mut lz, lo..=hi, None).changed()).inner; + if slid { + set(app, 2f32.powf(lz), false); + } + let zin = crate::brush_picker::named(icons::button(ui, "plus", NAV_ROW_H, false, tl!("Zoom In")), "Zoom In"); + if zin.clicked() { + set(app, crate::zoom_levels::step(v.zoom, 1, v.doc_size), true); + } + }); + }); + // From the preview's bottom, so the spacing above the controls counts too. + let controls = Rect::from_min_max(pos2(frame.left(), frame.bottom()), pos2(frame.right(), controls.response.rect.bottom())); + ui.data_mut(|d| { + d.insert_temp(navigator_controls_id(), controls.height()); + d.insert_temp(navigator_controls_rect_id(), controls); + }); +} + +/// Height of the Navigator's zoom row: its field, buttons and slider. +pub(super) const NAV_ROW_H: f32 = 22.0; + +/// The document's `w` × `h` fitted inside the Navigator's `frame` with an 8 pt inset, centred and +/// keeping its aspect. +fn navigator_fit(frame: Rect, w: u32, h: u32) -> Rect { + let inner = (frame.size() - vec2(16.0, 16.0)).max(vec2(1.0, 1.0)); + let (w, h) = (w.max(1) as f32, h.max(1) as f32); + let s = (inner.x / w).min(inner.y / h); + Rect::from_center_size(frame.center(), vec2(w * s, h * s)) +} + +/// Where a ⌘/Ctrl-drag over the Navigator's preview started, while it lasts. +pub(super) fn navigator_zoom_drag_id() -> egui::Id { + egui::Id::unique("navigator-zoom-drag") +} + +/// Zoom `view` so the document rectangle `doc_rect` (pixels) fills a canvas of `canvas` points, +/// centred on it, as a Navigator ⌘/Ctrl-drag does (#6872). `doc` is the document's size in +/// pixels (the view's own copy is only set once the canvas has been drawn), `ppp` the canvas's +/// device pixels per point and `aspect` the pixel aspect ratio shown; the zoom stays within the +/// zoom range. A rectangle under 2 document pixels across zooms one step in on its centre. +pub(super) fn navigator_zoom_to(view: &mut crate::state::View, doc_rect: Rect, doc: [u32; 2], canvas: egui::Vec2, ppp: f32, aspect: f32) { + // Checked before clipping: `min`/`max` would turn a NaN edge into a document edge. + if ![doc_rect.min.x, doc_rect.min.y, doc_rect.max.x, doc_rect.max.y].iter().all(|v| v.is_finite()) { + return; + } + let (w, h) = (doc[0] as f32, doc[1] as f32); + let r = doc_rect.intersect(Rect::from_min_size(Pos2::ZERO, vec2(w, h))); + if r.width() < 0.0 || r.height() < 0.0 { + return; + } + let aspect = if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 }; + let zoom = if r.width() < 2.0 || r.height() < 2.0 || canvas.x <= 0.0 || canvas.y <= 0.0 { + crate::zoom_levels::step(view.zoom, 1, view.doc_size) + } else { + // Document columns shown across the canvas are `canvas.x / (point_zoom * aspect)`. + let point_zoom = (canvas.x / (r.width() * aspect)).min(canvas.y / r.height()); + point_zoom * ppp + }; + if !zoom.is_finite() { + return; + } + view.zoom = crate::zoom_levels::clamp(zoom, view.doc_size); + view.center = [r.center().x, r.center().y]; + view.fit_pending = false; + view.request_zoom_animation(false); +} + +fn navigator_preview_id() -> egui::Id { + egui::Id::unique("navigator-preview-rect") +} + +fn navigator_controls_id() -> egui::Id { + egui::Id::unique("navigator-controls-height") +} + +fn navigator_controls_rect_id() -> egui::Id { + egui::Id::unique("navigator-controls-rect") +} + +/// Where the Navigator drew its document preview last frame. +#[cfg(test)] +pub(crate) fn last_navigator_preview(ctx: &egui::Context) -> Option { + ctx.data(|d| d.get_temp(navigator_preview_id())) +} + +/// The Navigator's zoom controls (below the preview) last frame. +#[cfg(test)] +pub(crate) fn last_navigator_controls(ctx: &egui::Context) -> Option { + ctx.data(|d| d.get_temp(navigator_controls_rect_id())) +} diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs new file mode 100644 index 0000000000..e24c3b4e6b --- /dev/null +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -0,0 +1,755 @@ +use super::brush_controls::{brush_preset_chip, 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::*; + +// Custom controls also need to bring keyboard focus into a scroll viewport. +pub(super) fn reveal_focused_control(ui: &egui::Ui) { + // read_response reprocesses pointer events. Reading a popup's newly focused field + // during its opening click can undo the focus that the popup just requested. + if ui.input(|input| input.pointer.any_pressed() || input.pointer.any_released()) { + return; + } + let focused = ui.memory(|memory| memory.focused()); + let key = ui.scope_id().with("scroll-focused-control"); + let changed = ui.data_mut(|data| { + let previous = data.get_temp::>(key).flatten(); + data.insert_temp(key, focused); + previous != focused + }); + if changed + && let Some(response) = focused.and_then(|id| ui.ctx().read_response(id)) + && response.layer_id == ui.layer_id() + && ui.min_rect().contains_rect(response.rect) + { + ui.scroll_to_rect(response.rect, Some(egui::Align::Center)); + } +} + +// ----------------------------------------------------------------------------- options bar + +/// Options bar height: Preferences ▸ Workspace ▸ Enable Narrow Options Bar trims it, as in +/// Photoshop, leaving the document more room. +pub(super) fn options_bar_height(pro: bool, narrow: bool) -> f32 { + match (pro, narrow) { + (true, false) => 36.0, + (true, true) => 30.0, + (false, false) => 42.0, + (false, true) => 34.0, + } +} + +pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + let narrow = app.session.prefs().workspace.narrow_options_bar(); + egui::Panel::top("options_bar") + .exact_size(options_bar_height(t.pro, narrow)) + .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(10, 0))) + .show(ui, |ui| { + ui.style_mut().spacing.scroll = egui::style::ScrollStyle { bar_width: 4.0, ..egui::style::ScrollStyle::floating() }; + egui::ScrollArea::horizontal().id_salt("tool-options").auto_shrink([false, false]).show(ui, |ui| { + // Font ink can extend beyond its advance width at fractional positions. + // Include its gutter in the container layout, including right-aligned actions. + egui::Frame::NONE.inner_margin(egui::Margin { right: 2, ..Default::default() }).show(ui, |ui| { + crate::direction::horizontal_centered(ui, |ui| { + if t.pro { + crate::chrome_ui::home_button(app, ui); + widgets::vline(ui, 22.0); + } + let tool_icon = icons::button(ui, icons::tool_icon(app.ui.tool), if t.pro { 26.0 } else { 28.0 }, !t.pro, tl!(app.ui.tool.label())); + // Photoshop: right-click the tool icon for Reset Tool / Reset All Tools (#2825). + let mut reset = None; + tool_icon.context_menu(|ui| { + if ui.button(tl!("Reset Tool")).clicked() { + reset = Some("tool.reset"); + ui.close(); + } + if ui.button(tl!("Reset All Tools")).clicked() { + reset = Some("tool.resetAll"); + ui.close(); + } + }); + if let Some(id) = reset + && let Err(e) = crate::menus::invoke(app, ui.ctx(), id, json!({})) + { + app.ui.status = e; + } + if t.pro { + let (r, _) = ui.allocate_exact_size(vec2(10.0, 20.0), Sense::hover()); + icons::paint(ui, r, "chevron-down", 10.0, t.text_faint); + } + widgets::vline(ui, 22.0); + if app.ui.transform.is_some() { + crate::transform_tool::options_bar(app, ui); + return; + } + if crate::symmetry_ui::options_bar(app, ui) || crate::distort_ui::options_bar(app, ui) { + return; + } + let tool = app.ui.tool; + // The options bar shows the active tool's brush: switch it in before drawing the + // chip, so a tool change swaps the brush with it (Photoshop keeps one per tool). + crate::paint_mouse::sync_tool_brush(app); + // Brush edits here go through `tools.setBrush`, one journal entry per gesture (Rule 1). + if (tool.is_brushlike() && !matches!(tool, Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::Eraser)) + || tool == Tool::QuickSelection + { + brush_preset_chip(ui, &app.session.tools.brush, &mut app.ui); + crate::brush_picker::settings_toggle(app, ui); + widgets::vline(ui, 22.0); + } + if matches!(tool, Tool::CloneStamp | Tool::PatternStamp | Tool::HistoryBrush | Tool::Healing) { + let before = app.session.tools.brush.clone(); + let mut brush = before.clone(); + // Mode is the tool's own brush's, kept per tool like its size. + if let Some(modes) = crate::blend_keys::tool_modes(tool) { + opt_label(ui, tl!("Mode")); + if let Some(Some(m)) = + tool_mode_dropdown(ui, "retouch-mode", &modes, Some(crate::blend_keys::brush_tool_mode(tool, brush.mode))) + { + brush.mode = m; + } + } + if tool == Tool::CloneStamp { + let width = if t.pro { 62.0 } else { 66.0 }; + percent_field(ui, tl!("Opacity"), &mut brush.opacity, 1.0..=100.0, width); + percent_field(ui, tl!("Flow"), &mut brush.flow, 1.0..=100.0, width); + } + crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush); + widgets::vline(ui, 22.0); + } + if crate::eraser_ui::options_bar(app, ui, tool) + || crate::retouch_ui::options_bar(app, ui, tool) + || crate::vector_ui::options_bar(app, ui, tool) + || crate::analysis_ui::options_bar(app, ui, tool) + || crate::slice_ui::options_bar(app, ui, tool) + || crate::frame_tool::options_bar(app, ui, tool) + || crate::artboard_tool::options_bar(app, ui, tool) + { + return; + } + let brush_before = app.session.tools.brush.clone(); + let mut brush = brush_before.clone(); + let b = &mut brush; + match app.ui.tool { + Tool::Brush | Tool::Eraser if t.pro => { + // A Block-mode Eraser has a fixed size, opacity and flow (Photoshop, #2770). + let block = crate::eraser_ui::block_mode(app, app.ui.tool); + ui.add_enabled_ui(!block, |ui| { + brush_preset_chip(ui, b, &mut app.ui); + crate::brush_picker::settings_toggle(app, ui); + }); + widgets::vline(ui, 22.0); + // The Eraser has no blend mode: its Mode is Brush, Pencil or Block (#2662). + if app.ui.tool == Tool::Eraser { + crate::eraser_ui::mode_dropdown(ui, &mut app.ui.tool_options.eraser_mode); + } else { + opt_label(ui, tl!("Mode")); + let held = app.held_erase; + paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held); + } + ui.add_enabled_ui(!block, |ui| { + percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 62.0); + if icons::button(ui, "circle-dot", 24.0, b.pressure_opacity, tl!("Always use pressure for opacity")).clicked() { + b.pressure_opacity = !b.pressure_opacity; + } + }); + // 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| { + percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 62.0); + 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")); + smoothing_field(ui, b, 58.0); + smoothing_options(ui, b); + widgets::vline(ui, 22.0); + if icons::button(ui, "circle-dot", 24.0, b.pressure_size, tl!("Always use pressure for size")).clicked() { + b.pressure_size = !b.pressure_size; + } + } + // Pencil: Photoshop's options (no hardness or flow: the pencil is always hard). + Tool::Pencil => { + brush_preset_chip(ui, b, &mut app.ui); + crate::brush_picker::settings_toggle(app, ui); + widgets::vline(ui, 22.0); + if !t.pro { + opt_label(ui, tl!("Size")); + widgets::value_field(ui, &mut b.size, 1.0..=photocraft_engine::paint::MAX_BRUSH_SIZE, "px", 76.0); + widgets::vline(ui, 22.0); + } + opt_label(ui, tl!("Mode")); + let held = app.held_erase; + paint_mode_dropdown(ui, "pencil-mode", b, &mut app.ui.tool_options.pencil_clear, held); + percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, if t.pro { 62.0 } else { 66.0 }); + 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")); + } + Tool::Brush | Tool::Eraser => { + brush_preset_chip(ui, b, &mut app.ui); + crate::brush_picker::settings_toggle(app, ui); + widgets::vline(ui, 22.0); + // A Block-mode Eraser has a fixed size, opacity and flow (Photoshop, #2770). + let block = crate::eraser_ui::block_mode(app, app.ui.tool); + ui.add_enabled_ui(!block, |ui| { + opt_label(ui, tl!("Size")); + widgets::value_field(ui, &mut b.size, 1.0..=photocraft_engine::paint::MAX_BRUSH_SIZE, "px", 76.0); + }); + widgets::vline(ui, 22.0); + if app.ui.tool == Tool::Eraser { + crate::eraser_ui::mode_dropdown(ui, &mut app.ui.tool_options.eraser_mode); + } else { + opt_label(ui, tl!("Mode")); + let held = app.held_erase; + paint_mode_dropdown(ui, "brush-mode", b, &mut app.ui.tool_options.brush_clear, held); + } + // A Pencil-mode Eraser is always hard and at full flow (Photoshop). + let fixed = block || crate::eraser_ui::pencil_mode(app, app.ui.tool); + ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Hardness"), &mut b.hardness, 0.0..=100.0, 66.0)); + ui.add_enabled_ui(!block, |ui| percent_field(ui, tl!("Opacity"), &mut b.opacity, 0.0..=100.0, 66.0)); + ui.add_enabled_ui(!fixed, |ui| percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 66.0)); + opt_label(ui, tl!("Smoothing")); + smoothing_field(ui, b, 66.0); + widgets::vline(ui, 22.0); + widgets::toggle(ui, &mut b.pressure_size, tl!("Pressure for Size")); + widgets::toggle(ui, &mut b.pressure_opacity, tl!("Pressure for Opacity")); + } + Tool::MixerBrush => { + brush_preset_chip(ui, b, &mut app.ui); + crate::brush_picker::settings_toggle(app, ui); + widgets::vline(ui, 22.0); + mixer_load_swatch(app, ui); + let m = &mut b.mixer; + for (icon, on, tip) in [ + ("brush", &mut m.load_after_stroke, tl!("Load the brush after each stroke")), + ("brush-cleaning", &mut m.clean_after_stroke, tl!("Clean the brush after each stroke")), + ] { + if icons::button(ui, icon, 24.0, *on, tip).clicked() { + *on = !*on; + } + } + 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), + ] { + percent_field(ui, label, value, 0.0..=100.0, 62.0); + } + widgets::vline(ui, 22.0); + widgets::checkbox(ui, &mut b.mixer.sample_all_layers, tl!("Sample All Layers")); + } + Tool::RectMarquee | Tool::EllipseMarquee | Tool::SingleRowMarquee | Tool::SingleColumnMarquee => { + ui.spacing_mut().item_spacing.x = 2.0; + for (i, (icon, tip)) in [ + ("square", tl!("New selection").to_string()), + ("plus", crate::i18n::fmt(tl!("Add to selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift"))])), + ("minus", crate::i18n::fmt(tl!("Subtract from selection ({key})"), &[("key", &crate::shortcuts::pretty("Alt"))])), + ( + "squares-subtract", + crate::i18n::fmt(tl!("Intersect with selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift+Alt"))]), + ), + ] + .iter() + .enumerate() + { + if icons::button(ui, icon, 24.0, app.ui.selection_mode == i as u8, tip).clicked() { + app.ui.selection_mode = i as u8; + } + } + ui.spacing_mut().item_spacing.x = 8.0; + widgets::vline(ui, 22.0); + let (units, size) = fixed_size_units(app); + let o = &mut app.ui.tool_options; + opt_label(ui, tl!("Feather")); + widgets::value_field(ui, &mut o.feather, 0.0..=1000.0, "px", 62.0); + // Photoshop greys Anti-alias for the Rectangular Marquee (its edges are always hard). + ui.add_enabled_ui(app.ui.tool == Tool::EllipseMarquee, |ui| widgets::checkbox(ui, &mut o.anti_alias, tl!("Anti-alias"))); + widgets::vline(ui, 22.0); + // A single row or column has no style or size: Photoshop greys them. + let sized = matches!(app.ui.tool, Tool::RectMarquee | Tool::EllipseMarquee); + ui.add_enabled_ui(sized, |ui| opt_label(ui, tl!("Style"))); + let styles = [ + ("normal".to_string(), tl!("Normal")), + ("fixedRatio".to_string(), tl!("Fixed Ratio")), + ("fixedSize".to_string(), tl!("Fixed Size")), + ]; + if ui + .add_enabled_ui(sized, |ui| widgets::dropdown(ui, "marquee-style", tl!("Style"), &mut o.marquee_style, &styles, 96.0)) + .inner + { + (o.marquee_width, o.marquee_height) = if o.marquee_style == "fixedSize" { (64.0, 64.0) } else { (1.0, 1.0) }; + } + let fixed = sized && o.marquee_style != "normal"; + let fixed_size = o.marquee_style == "fixedSize"; + // Fixed Size shows its pixels in the unit picked by right-clicking Width or Height (#7910). + let units = widgets::FieldUnits { unit: photocraft_engine::prefs::Unit::parse(&o.marquee_unit).unwrap_or_default(), ..units }; + ui.add_enabled_ui(fixed, |ui| { + let mut picked = None; + opt_label(ui, tl!("Width")); + if fixed_size { + picked = fixed_size_field(ui, &mut o.marquee_width, units, size[0]); + } else { + widgets::value_field(ui, &mut o.marquee_width, crate::tool_memory::style_range(&o.marquee_style), "", 62.0); + } + if icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked() { + std::mem::swap(&mut o.marquee_width, &mut o.marquee_height); + } + opt_label(ui, tl!("Height")); + if fixed_size { + picked = fixed_size_field(ui, &mut o.marquee_height, units, size[1]).or(picked); + } else { + widgets::value_field(ui, &mut o.marquee_height, crate::tool_memory::style_range(&o.marquee_style), "", 62.0); + } + if let Some(name) = picked { + o.marquee_unit = name.into(); + } + }); + widgets::vline(ui, 22.0); + select_and_mask_button(app, ui); + } + Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso => { + selection_mode_buttons(app, ui); + widgets::vline(ui, 22.0); + opt_label(ui, tl!("Feather")); + widgets::value_field(ui, &mut app.ui.tool_options.feather, 0.0..=1000.0, "px", 62.0); + widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias")); + widgets::vline(ui, 22.0); + if app.ui.tool == Tool::MagneticLasso { + let o = &mut app.ui.tool_options; + opt_label(ui, tl!("Width")); + widgets::value_field(ui, &mut o.magnetic_width, 1.0..=256.0, "px", 58.0) + .on_hover_text(tl!("Follows only edges this close to the pointer ([ and ] change it)")); + opt_label(ui, tl!("Contrast")); + widgets::value_field(ui, &mut o.magnetic_contrast, 1.0..=100.0, "%", 58.0) + .on_hover_text(tl!("Higher values follow only edges that contrast sharply with their surroundings")); + opt_label(ui, tl!("Frequency")); + widgets::value_field(ui, &mut o.magnetic_frequency, 0.0..=100.0, "", 50.0) + .on_hover_text(tl!("How often fastening points are placed by themselves")); + if icons::button(ui, "circle-dot", 24.0, o.magnetic_pressure, tl!("Use tablet pressure to change pen width")).clicked() { + o.magnetic_pressure = !o.magnetic_pressure; + } + widgets::vline(ui, 22.0); + } + select_and_mask_button(app, ui); + if crate::lasso_ui::active(app) || (app.ui.tool == Tool::PolygonLasso && !app.ui.polygon.is_empty()) { + hint( + ui, + &crate::i18n::fmt( + tl!("Click the first point or press {key} to close · Esc cancels"), + &[("key", &crate::shortcuts::pretty("Enter"))], + ), + ); + } else if app.ui.tool == Tool::Lasso { + hint(ui, tl!("Hold Alt while drawing for straight segments")); + } + if app.ui.tool == Tool::MagneticLasso && app.ui.magnetic.active() { + hint( + ui, + &crate::i18n::fmt( + tl!("Click the first point or press {key} to close · {del} removes a point · Esc cancels"), + &[("key", &crate::shortcuts::pretty("Enter")), ("del", &crate::shortcuts::pretty("Backspace"))], + ), + ); + } + } + Tool::MagicWand => { + selection_mode_buttons(app, ui); + widgets::vline(ui, 22.0); + opt_label(ui, tl!("Tolerance")); + widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0); + widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias")); + widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous")); + widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.magic_wand, tl!("Sample All Layers")); + widgets::vline(ui, 22.0); + if widgets::secondary_button(ui, tl!("Select Subject"), 0.0).clicked() { + let r = app.run("select.subject", json!({})); + crate::retouch_ui::report_smart_result(app, r, tl!("No subject found — try Object Selection or the Lasso")); + } + select_and_mask_button(app, ui); + } + Tool::PaintBucket => { + opt_label(ui, tl!("Fill")); + let mut src = u8::from(app.ui.tool_options.bucket_fill_pattern); + if widgets::dropdown(ui, "bucket-src", tl!("Source"), &mut src, &[(0u8, tl!("Foreground")), (1, tl!("Pattern"))], 100.0) { + app.ui.tool_options.bucket_fill_pattern = src == 1; + } + opt_label(ui, tl!("Mode")); + if let Some(modes) = crate::blend_keys::tool_modes(tool) { + let o = &mut app.ui.tool_options; + let current = if o.bucket_clear { None } else { Some(o.bucket_blend_mode) }; + if let Some(m) = tool_mode_dropdown(ui, "bucket-mode", &modes, current) { + o.bucket_clear = m.is_none(); + if let Some(m) = m { + o.bucket_blend_mode = m; + } + } + } + opt_label(ui, tl!("Opacity")); + widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0); + opt_label(ui, tl!("Tolerance")); + widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0); + widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias")); + widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous")); + widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.paint_bucket, tl!("All Layers")); + } + Tool::Gradient => { + // Live "Gradient" (a Gradient Fill layer) or "Classic gradient" (pixels). + let mut classic = app.ui.tool_options.gradient_classic; + if widgets::dropdown(ui, "gradient-mode", tl!("Mode"), &mut classic, &[(false, "Gradient"), (true, "Classic gradient")], 118.0) + { + app.ui.tool_options.gradient_classic = classic; + } + // Live "Gradient" (a Gradient Fill layer) or "Classic gradient" (pixels): + // both paint with the same engine-owned preset (#1651), and either swatch + // click opens the Gradient Editor window, as in Photoshop. + if crate::gradient_ui::preset_swatch(app, ui) { + app.ui.panels.gradient_editor = true; + } + widgets::vline(ui, 22.0); + ui.spacing_mut().item_spacing.x = 2.0; + let before = app.ui.tool_options.clone(); + for (style, icon, tip) in [ + ("linear", "gradient", tl!("Linear Gradient")), + ("radial", "circle", tl!("Radial Gradient")), + ("angle", "rotate-cw", tl!("Angle Gradient")), + ("reflected", "arrow-left-right", tl!("Reflected Gradient")), + ("diamond", "diamond", tl!("Diamond Gradient")), + ] { + if icons::button(ui, icon, 24.0, app.ui.tool_options.gradient_style == style, tip).clicked() { + app.ui.tool_options.gradient_style = style.into(); + } + } + ui.spacing_mut().item_spacing.x = 8.0; + widgets::vline(ui, 22.0); + opt_label(ui, tl!("Mode")); + let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); + // The wheel over it steps the mode, as over the Layers panel's (#2061). + widgets::dropdown_wheel_hovered( + ui, + "gradient-blend-mode", + tl!("Blend Mode"), + &mut app.ui.tool_options.gradient_blend_mode, + &opts, + 96.0, + ); + opt_label(ui, tl!("Opacity")); + let r = widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0); + // Live while scrubbed, one undo step per scrub (#5012). + let drag_key = r.id.with("gradient-opacity-drag"); + if r.drag_started() { + let n = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|d| d.insert_temp(drag_key, n)); + } + if r.changed() { + let drag = if r.dragged() { ui.data(|d| d.get_temp::(drag_key)) } else { None }; + crate::gradient_ui::opacity_changed(app, drag); + } + widgets::checkbox(ui, &mut app.ui.tool_options.gradient_reverse, tl!("Reverse")); + widgets::checkbox(ui, &mut app.ui.tool_options.gradient_dither, tl!("Dither")); + // Live mode: the options also change a selected gradient fill layer. + crate::gradient_ui::options_changed(app, &before); + } + Tool::PerspectiveCrop => crate::perspective_crop_ui::options_bar(app, ui), + Tool::Crop => { + let before_ratio = crate::crop_ui::preset_ratio(app); + let doc_size = app.session.active().map_or((0.0, 0.0), |s| (f64::from(s.doc.size.width), f64::from(s.doc.size.height))); + // Ratios, sizes, saved presets, New / Delete Crop Preset… (#2443, #1919). + crate::crop_presets::dropdown(app, ui); + let o = &mut app.ui.tool_options; + let mut ratio_base = None; + if o.crop_ratio == crate::crop_size::WHR { + crate::crop_size::fields(o, ui); + } else { + // Keep partial edits in ToolOptions so the first side survives a frame; + // Original Ratio shows the document's numbers, as Photoshop does. + let (mut rw, mut rh) = crate::crop_size::custom_ratio_fields(o, doc_size); + let decimals = crate::crop_size::RATIO_DECIMALS; + let fw = widgets::value_field_prec(ui, &mut rw, 0.0..=99_999.0, "", 54.0, decimals); + let swap = icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked(); + let fh = widgets::value_field_prec(ui, &mut rh, 0.0..=99_999.0, "", 54.0, decimals); + let (cw, ch) = (fw.changed(), fh.changed()); + if swap { + std::mem::swap(&mut rw, &mut rh); + } + if cw || ch || swap { + crate::crop_size::set_custom_ratio_fields(o, rw, rh); + } + // Every ratio typed or scrubbed in one edit fits from the frame the edit + // started with: 1:3 on the way to 16:3 mustn't shrink it first (#7752). + let base_id = egui::Id::unique("crop-ratio-edit-base"); + if cw || ch { + ratio_base = ui.data(|d| d.get_temp::<[f64; 4]>(base_id)).or(app.ui.crop_rect); + } + if ![&fw, &fh].iter().any(|f| f.has_focus() || f.dragged()) { + ui.data_mut(|d| d.remove::<[f64; 4]>(base_id)); + } else if let Some(base) = ratio_base { + ui.data_mut(|d| d.insert_temp(base_id, base)); + } + } + widgets::vline(ui, 22.0); + if widgets::secondary_button(ui, tl!("Clear"), 0.0).clicked() { + crate::crop_size::clear_ratio(o); + } + crate::crop_straighten::options_button(&mut app.crop.straighten, ui); + crate::crop_overlay::options_button(o, ui); + let pick_shield_color = crate::crop_shield::options_button(&mut o.crop_shield, ui); + widgets::checkbox(ui, &mut o.crop_delete, tl!("Delete Cropped Pixels")); + // Fill: what a turned or extending crop puts where the image doesn't reach + // (#3823). Generative Expand is not offered. + ui.label(tl!("Fill:")); + widgets::dropdown( + ui, + "crop-fill", + tl!("Fill:"), + &mut o.crop_content_aware, + &[(false, tl!("Background (Default)")), (true, tl!("Content-Aware Fill"))], + 150.0, + ); + if crate::crop_ui::preset_ratio(app) != before_ratio { + match ratio_base { + Some(base) => crate::crop_ui::apply_ratio_from(app, base), + None => crate::crop_ui::apply_ratio(app), + } + } + if pick_shield_color { + crate::crop_shield::pick_custom_color(app); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if icons::button( + ui, + "check", + 26.0, + false, + &crate::i18n::fmt(tl!("Commit current crop operation ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]), + ) + .clicked() + { + crate::canvas::commit_crop(app); + } + if icons::button(ui, "ban", 26.0, false, tl!("Cancel current crop operation (Esc)")).clicked() { + crate::crop_ui::cancel(app); + } + }); + } + // Every theme gets the font, style and size controls (#1387), as with Auto-Select (#1275). + Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::options_bar(app, ui), + Tool::Move => { + let o = &mut app.ui.tool_options; + widgets::checkbox(ui, &mut o.move_auto_select, tl!("Auto-Select:")); + widgets::dropdown( + ui, + "move-target", + tl!("Auto-Select:"), + &mut o.move_target, + &[("layer".to_string(), tl!("Layer")), ("group".to_string(), tl!("Group"))], + 76.0, + ); + widgets::vline(ui, 22.0); + widgets::checkbox(ui, &mut o.move_show_transform, tl!("Show Transform Controls")); + widgets::vline(ui, 22.0); + crate::align_bar::options(app, ui); + } + Tool::Eyedropper => crate::eyedropper_ui::options(app, ui), + Tool::Zoom => { + // 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() { + 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() + && let Some(i) = app.session.active_index() + { + app.ui.views[i].zoom = 1.0; + 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; + app.ui.views[i].fill_pending = false; + } + } + Tool::RotateView => { + hint(ui, tl!("Drag around the centre to rotate the view · Shift constrains to 15°")); + if let Some(i) = app.session.active_index() { + ui.label(tl!("Angle")); + let mut angle = app.ui.views.get(i).map(|v| v.rotation).unwrap_or(0.0); + if widgets::value_field(ui, &mut angle, -180.0..=180.0, "°", 56.0).changed() + && let Some(v) = app.ui.views.get_mut(i) + { + v.rotation = crate::rotate_view::wrap_deg(angle); + } + if widgets::secondary_button(ui, tl!("Reset View"), 0.0).clicked() + && let Some(v) = app.ui.views.get_mut(i) + { + v.rotation = 0.0; + } + } + } + Tool::Hand => { + 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() + { + app.ui.views[i].zoom = 1.0; + 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; + app.ui.views[i].fill_pending = false; + } + 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; + app.ui.views[i].fill_pending = false; + } + if widgets::secondary_button(ui, tl!("Fill Screen"), 0.0).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; + } + } + // Retouching and smart-selection tools draw their bar in `retouch_ui::options_bar`. + _ => {} + } + // Painting symmetry is independent of visual theme. Keep the options-bar + // action available for Brush, Pencil and Eraser in every palette (#2659). + if matches!(tool, Tool::Brush | Tool::Pencil | Tool::Eraser) { + crate::symmetry_ui::menu(app, ui); + } + crate::brush_panel::commit_gesture(app, ui.ctx(), &brush_before, &brush); + }); + reveal_focused_control(ui); + }); + }); + }); +} + +/// 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; + +/// The `layer.setProps` edit of a Layers panel Opacity or Fill (`key`) field at `pct` percent. A +/// drag of the pop-up slider (`drag`) coalesces into one history step, as in Photoshop. +pub(super) fn pct_action(target: &Value, key: &str, pct: f32, drag: Option) -> (String, Value) { + let mut p = target.clone(); + p[key] = json!(pct / 100.0); + if let Some(n) = drag { + p["coalesce"] = json!(format!("layer-{key}-slider:{n}")); + } + ("layer.setProps".into(), p) +} + +/// Photoshop's scrubby Opacity/Fill labels: drag horizontally to change the percentage without +/// hitting the small number field. The unique drag ID coalesces every frame into one undo step. +pub(super) fn scrub_pct_label(ui: &mut egui::Ui, text: &str, percent: &mut f32, max_w: f32) -> widgets::PopupFieldResponse { + // Elide to the room left in the row (full text on hover): a longer translation shrinks here + // instead of running over the fixed controls beside it (#3580). + let resp = widgets::elided_label_sensed(ui, text, max_w, Sense::click_and_drag()).on_hover_cursor(egui::CursorIcon::ResizeHorizontal); + let key = resp.id.with("percent-label-drag"); + if resp.drag_started() { + let stamp = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|d| d.insert_temp(key, (*percent, stamp))); + } + let mut out = widgets::PopupFieldResponse::default(); + if resp.dragged() + && let Some((start, stamp)) = ui.data(|d| d.get_temp::<(f32, u64)>(key)) + && let (Some(origin), Some(pos)) = (ui.input(|i| i.pointer.press_origin()), resp.interact_pointer_pos()) + { + // Match DragValue's 0.5 percentage-point per screen point; do not jump on press. + let next = (start + (pos.x - origin.x) * 0.5).clamp(0.0, 100.0); + if next.is_finite() && next != *percent { + *percent = next; + out.changed = true; + out.drag = Some(stamp); + } + } + if resp.drag_stopped() { + ui.data_mut(|d| d.remove::<(f32, u64)>(key)); + } + out +} + +/// Width of `s` as [`label`] draws it (body text). +pub(super) fn body_text_width(ui: &egui::Ui, s: &str) -> f32 { + let font = egui::TextStyle::Body.resolve(ui.style()); + ui.painter().layout_no_wrap(s.to_string(), font, Color32::WHITE).size().x +} + +/// Options-bar label: Photoshop writes "Size:" with a colon. +/// An options-bar label; one right before a value field scrubs it when dragged (Photoshop). +pub(crate) fn opt_label(ui: &mut egui::Ui, s: &str) { + let t = Tokens::get(ui.ctx()); + let text = if t.pro && !s.ends_with(':') { format!("{s}:") } else { s.to_string() }; + let label = ui.add(egui::Label::new(RichText::new(tl!(&text)).color(t.text_dim)).selectable(false)); + widgets::scrub_option_label(ui, &label); +} + +/// The largest Fixed Size side, in pixels. +pub(crate) const FIXED_SIZE_MAX_PX: f64 = 300_000.0; + +/// The resolution Fixed Size's units convert at (the active document's, 72 ppi without one) and +/// the document's size in pixels, which a percentage is of. The unit is the caller's. +fn fixed_size_units(app: &PhotocraftApp) -> (widgets::FieldUnits, [f64; 2]) { + let ppi = app.session.prefs().units_and_rulers.point_size.per_inch(); + let (dpi, size) = app + .session + .active() + .map_or((72.0, [1.0, 1.0]), |d| (f64::from(d.doc.resolution_dpi.max(1.0)), [f64::from(d.doc.size.width), f64::from(d.doc.size.height)])); + (widgets::FieldUnits { unit: photocraft_engine::prefs::Unit::Pixels, dpi, ppi }, size) +} + +/// One of Fixed Size's Width and Height (#7910): `px` shown in `units.unit` (a typed unit converts), +/// still stored in pixels. A right-click lists the units, as on the rulers; returns the one picked. +fn fixed_size_field(ui: &mut egui::Ui, px: &mut f32, units: widgets::FieldUnits, extent: f64) -> Option<&'static str> { + let widgets::FieldUnits { unit, dpi, ppi } = units; + let to_unit = |px: f64| unit.from_px(px, dpi, extent, ppi) as f32; + let before = to_unit(f64::from(*px)); + let mut v = before; + let places = unit.decimals() as u32; + let resp = widgets::value_field_extent(ui, &mut v, to_unit(1.0)..=to_unit(FIXED_SIZE_MAX_PX), unit.suffix(), 62.0, places, units, extent); + // Leaving the field re-reads the rounded text it showed (100 px at 72 ppi reads back as + // 1.389 in); that isn't an edit, so the pixels stay exact. + let shown = |x: f32| (f64::from(x) * 10f64.powi(places as i32)).round(); + if resp.changed() && shown(v) != shown(before) { + *px = unit.to_px(f64::from(v), dpi, extent, ppi).clamp(1.0, FIXED_SIZE_MAX_PX) as f32; + } + let mut picked = None; + resp.context_menu(|ui| picked = crate::rulers::unit_menu(ui, unit)); + picked +} + +fn percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) { + opt_label(ui, label); + let mut percent = *value * 100.0; + if widgets::value_field_named(ui, label, &mut percent, range, "%", width).changed() { + *value = percent / 100.0; + } +} + +fn hint(ui: &mut egui::Ui, s: &str) { + let t = Tokens::get(ui.ctx()); + ui.label(RichText::new(s).color(t.text_faint)); +} diff --git a/crates/ui-egui/src/panels/panel_state.rs b/crates/ui-egui/src/panels/panel_state.rs new file mode 100644 index 0000000000..d384bbfa98 --- /dev/null +++ b/crates/ui-egui/src/panels/panel_state.rs @@ -0,0 +1,96 @@ +// ----------------------------------------------------------------------------- panel state + +/// The persisted [`egui::PanelState`] key for the panel named `salt` in this context's root UI. +/// +/// egui 0.37 derives a panel's id from its parent [`egui::Ui`]: +/// `panel_ui.scope_id().with_salt(salt)`. For the root Ui that is +/// `ctx.viewport_id().root_ui_id().with(salt)`, whereas 0.36 stored the same panels under +/// `Id::new(salt)` (`Id::unique(salt)` has the same hash). Use this in tests and migrations; never +/// substitute [`egui::Ui::unique_id`], which is unstable. +pub fn panel_state_id(ctx: &egui::Context, salt: impl egui::AsIdSalt) -> egui::Id { + ctx.viewport_id().root_ui_id().with(salt) +} + +/// The panels whose saved sizes moved to a parent-scoped key in 0.37. +const PANEL_STATE_KEYS: &[&str] = &["dock", "title_bar", "options_bar", "status_bar", "toolbar", "rail", "shared-panel-dock"]; + +/// What the two keys held when this build last looked at a panel, so a later startup can tell +/// which one a 0.36 rollback or a 0.37 session wrote last. +#[derive(Clone, Copy, serde::Serialize, serde::Deserialize)] +struct PanelStamp { + old: [f32; 4], + new: [f32; 4], +} + +fn rect_key(state: egui::containers::panel::PanelState) -> [f32; 4] { + let r = state.outer_rect; + [r.min.x, r.min.y, r.max.x, r.max.y] +} + +fn stamp_id(name: &str) -> egui::Id { + egui::Id::unique(format!("photocraft-panel-state-stamp:{name}")) +} + +/// Copy 0.36 `PanelState` entries to their 0.37 parent-scoped keys. +/// +/// The old `Id::unique(name)` entry is left in place so a 0.36 build still reads the same saved +/// widths. On a later startup, a stamp of both keys decides which one is newer: if a 0.36 build +/// resized the panel after the migration (the old key differs from the stamp, the new one does +/// not), the old key wins; a 0.37 resize (the new key differs) is kept. If both changed the order +/// is unknown; the new key is kept, so a 0.37 resize *after* a 0.36 rollback resize can still be +/// lost (documented in the plan's rollback section). Data-only: call it before any panel is shown. +pub fn migrate_panel_state(ctx: &egui::Context) { + use egui::containers::panel::PanelState; + let done = egui::Id::unique("photocraft-panel-state-migrated"); + if ctx.data(|d| d.get_temp::(done).unwrap_or(false)) { + return; + } + for name in PANEL_STATE_KEYS { + let old_id = egui::Id::unique(*name); + let new_id = panel_state_id(ctx, *name); + let id = stamp_id(name); + let old = PanelState::load(ctx, old_id); + let new = PanelState::load(ctx, new_id); + let stamp = ctx.data_mut(|d| d.get_persisted::(id)); + let Some(old) = old else { continue }; + let old_key = rect_key(old); + match (new, stamp) { + (None, _) => { + // First migration: copy, and remember what both keys held. + ctx.data_mut(|d| d.insert_persisted(new_id, old)); + ctx.data_mut(|d| d.insert_persisted(id, PanelStamp { old: old_key, new: old_key })); + } + (Some(new), None) => { + // A partial migration or a pre-existing 0.37 value: keep it and start stamping. + ctx.data_mut(|d| d.insert_persisted(id, PanelStamp { old: old_key, new: rect_key(new) })); + } + (Some(new), Some(stamp)) => { + let old_changed = old_key != stamp.old; + let new_changed = rect_key(new) != stamp.new; + if old_changed && !new_changed { + // A 0.36 rollback resized the panel after the migration: its key is newer. + ctx.data_mut(|d| d.insert_persisted(new_id, old)); + ctx.data_mut(|d| d.insert_persisted(id, PanelStamp { old: old_key, new: old_key })); + } else if new_changed { + ctx.data_mut(|d| d.insert_persisted(id, PanelStamp { old: old_key, new: rect_key(new) })); + } + } + } + } + ctx.data_mut(|d| d.insert_temp(done, true)); +} + +/// Remember the 0.37 panel sizes this session ends a pass with, so a later 0.36 rollback's newer +/// old-key values can be recognized. Cheap when nothing changed (no write). +pub fn remember_panel_state(ctx: &egui::Context) { + use egui::containers::panel::PanelState; + for name in PANEL_STATE_KEYS { + let Some(new) = PanelState::load(ctx, panel_state_id(ctx, *name)) else { continue }; + let id = stamp_id(name); + let Some(stamp) = ctx.data_mut(|d| d.get_persisted::(id)) else { continue }; + let new_key = rect_key(new); + if new_key != stamp.new { + ctx.data_mut(|d| d.insert_persisted(id, PanelStamp { old: stamp.old, new: new_key })); + } + } +} diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs new file mode 100644 index 0000000000..43400674bc --- /dev/null +++ b/crates/ui-egui/src/panels/properties.rs @@ -0,0 +1,273 @@ +use super::*; + +// ----------------------------------------------------------------------------- properties + +/// Floating Properties card anchored to the canvas' top-right corner. It has the docked group's +/// tabs: Properties (`properties_body`: document, layer, adjustment and mask properties) and +/// Adjustments (`adjustments_grid`). +pub fn properties_window(app: &mut PhotocraftApp, ctx: &egui::Context) { + if app.ui.docking.is_some() { + return; + } + // Pro (Photoshop) docks Properties; Studio floats it over the canvas. + if !app.ui.panels.properties || Tokens::get(ctx).pro { + return; + } + if app.session.active().is_none() { + return; + } + let t = Tokens::get(ctx); + let canvas = app.last_canvas_rect; + let width = 320.0; + let pos = pos2(canvas.right() - width - 12.0, canvas.top() + 44.0); + let frame = egui::Frame::NONE + .fill(t.card) + .stroke(Stroke::new(1.0, t.card_border)) + .corner_radius(CornerRadius::same(t.radius_lg as u8)) + .shadow(egui::Shadow { offset: [0, 12], blur: 36, spread: 0, color: t.shadow }) + .inner_margin(egui::Margin::same(14)); + // A floating panel (Order::Middle like other panels, so menus, popups and dialogs stay above + // it), anchored to the canvas corner and dragged by its title off the part being worked on. + let card_id = egui::Id::unique("properties-card"); + let offset: egui::Vec2 = ctx.data(|m| m.get_temp(card_id)).unwrap_or_default(); + let mut drag = egui::Vec2::ZERO; + let shown = egui::Area::new(card_id).order(egui::Order::Middle).fixed_pos(pos + offset).show(ctx, |ui| { + frame.show(ui, |ui| { + ui.set_width(width - 28.0); + // Properties | Adjustments, as on the docked group (#7265). + let group = crate::dock::Group::Properties; + let visible = app.ui.dock.visible_tabs(group, false); + let indices: Vec = visible.iter().map(|(i, _)| *i).collect(); + let tabs: Vec<&str> = visible.iter().map(|(_, name)| *name).collect(); + let mut sel = indices.iter().position(|i| *i == app.ui.dock_tabs.properties).unwrap_or(0); + let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::hover()); + let hide = Rect::from_min_max(pos2(row.right() - 22.0, row.top() + 1.0), pos2(row.right(), row.bottom() - 1.0)); + if icons::button(&mut ui.new_child(egui::UiBuilder::new().max_rect(hide)), "minus", 22.0, false, tl!("Hide Properties")).clicked() { + app.ui.panels.properties = false; + } + // The title bar drags the card; registered before the tabs so they keep their clicks. + let bar = Rect::from_min_max(row.min, pos2((hide.left() - 6.0).max(row.left()), row.bottom())); + let grip = ui.interact(bar, card_id.with("title"), Sense::drag()); + if grip.hovered() || grip.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); + } + drag = grip.drag_delta(); + let context = crate::tab_strip::pill_tabs(ui, card_id.with("tabs"), bar, &tabs, &mut sel); + if let Some(&picked) = indices.get(sel) { + app.ui.dock_tabs.properties = picked; + } + match context { + Some(crate::tab_strip::TabContextAction::Close(i)) => { + if let Some(&tab) = indices.get(i) { + crate::dock::close_tab(app, group, tab, false); + } + } + Some(crate::tab_strip::TabContextAction::CloseGroup) => app.ui.panels.properties = false, + None => {} + } + ui.add_space(6.0); + widgets::hairline(ui); + ui.add_space(8.0); + match indices.get(sel) { + Some(0) | None => properties_body(app, ui), + Some(_) => adjustments_grid(app, ui), + } + }); + }); + if drag != egui::Vec2::ZERO && canvas.is_positive() { + // Keep the title bar inside the canvas. + let r = shown.response.rect.translate(drag); + let dx = (canvas.left() - r.left()).max(0.0) - (r.right() - canvas.right()).max(0.0); + let dy = (canvas.top() - r.top()).max(0.0) - (r.top() + 40.0 - canvas.bottom()).max(0.0); + ctx.data_mut(|m| m.insert_temp(card_id, offset + drag + egui::vec2(dx, dy))); + } +} + +fn adjustment_controls(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj: &photocraft_doc::Adjustment) { + // Keep the scope reachable before tall editors and within a compact dock (#5231). + // Adjustment layers affect the stack by default; clipping limits them to their base. + if let Some(mut clip) = app.session.active().and_then(|s| s.doc.layer(id).map(|l| l.clipped)) + && widgets::toggle(ui, &mut clip, tl!("Clip to layer below")).changed() + { + let _ = app.run("layer.setProps", json!({"layer": id.0, "clipped": clip})); + } + ui.add_space(6.0); + crate::adjust_editors::layer_editor(app, ui, id, adj); + ui.add_space(6.0); + if let Some(mut vis) = app.session.active().and_then(|s| s.doc.layer(id).map(|l| l.visible)) + && widgets::toggle(ui, &mut vis, tl!("Adjustment visible")).changed() + { + let _ = app.run("layer.setProps", json!({"layer": id.0, "visible": vis})); + } + ui.add_space(6.0); + if widgets::secondary_button(ui, tl!("Reset to defaults"), ui.available_width()).clicked() { + let doc = app.session.active().map_or(0, |s| s.doc.id.0); + // Photoshop's two-step Reset where measured (Color Balance), else the defaults. + let params = crate::adjust_editors::properties_reset(ui.ctx(), doc, id, adj).unwrap_or_else(|| json!({"layer": id.0})); + let _ = app.run("layer.setAdjustment", params); + app.live_adjust = None; + } +} + +fn layer_controls(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) { + let t = Tokens::get(ui.ctx()); + if let Some(s) = layer.surface() { + let b = app.layer_frame_bounds(layer, s); + egui::Grid::new("props-grid").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { + for (k, v) in [("X", b.x0.to_string()), ("Y", b.y0.to_string()), ("W", b.width().to_string()), ("H", b.height().to_string())] { + ui.label(RichText::new(k).color(t.text_dim)); + ui.label(RichText::new(format!("{v} px")).font(theme::mono(12.0)).color(t.text)); + ui.end_row(); + } + }); + ui.add_space(6.0); + } + let mut o = layer.opacity * 100.0; + let r = widgets::slider_row(ui, tl!("Opacity"), &mut o, 0.0..=100.0, "%", None); + if r.drag_stopped() || (r.changed() && !r.dragged()) { + let _ = app.run("layer.setProps", json!({"layer": layer.id.0, "opacity": o / 100.0})); + } + let mut f = layer.fill_opacity * 100.0; + let r = widgets::slider_row(ui, crate::i18n::tr_ctx(crate::i18n::current(), "layers", "Fill"), &mut f, 0.0..=100.0, "%", None); + if r.drag_stopped() || (r.changed() && !r.dragged()) { + let _ = app.run("layer.setProps", json!({"layer": layer.id.0, "fill": f / 100.0})); + } +} + +/// Docked Properties body (Pro theme). +pub(super) fn properties_body(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let identity = app.session.active().map(|st| (st.doc.id, st.active_layer, app.ui.mask_target, app.ui.vector_mask_target, app.ui.properties_layer)); + ui.push_id(("properties-target", identity), |ui| properties_body_inner(app, ui)); +} + +fn properties_body_inner(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + let Some(st) = app.session.active() else { + empty(ui, tl!("No properties")); + return; + }; + let doc = st.doc.clone(); + if let Some(layer) = st.active_layer.and_then(|id| doc.layer(id)) + && crate::mask_props_ui::targeted(app, layer) + { + crate::props_layout::header(ui, layer); + crate::mask_props_ui::properties(app, ui, layer); + return; + } + // The vector mask's own controls, when its thumbnail is targeted. + if let Some(layer) = st.active_layer.and_then(|id| doc.layer(id)) + && crate::mask_props_ui::vector_targeted(app, layer) + { + crate::props_layout::header(ui, layer); + crate::mask_props_ui::vector_properties(app, ui, layer); + return; + } + // Photoshop shows the Document properties when nothing or the Background layer is selected, + // with Align and Distribute above them when the Background is one of several (#4608). + if crate::doc_props_ui::shows_document(&st.doc, st.active_layer) { + if t.pro && st.selected_layers().len() > 1 { + crate::layer_props_ui::selection_align(app, ui); + } + crate::doc_props_ui::properties(app, ui); + return; + } + let Some(id) = st.active_layer else { return }; + // Borrowed from the document snapshot: cloning the layer every frame copied whole groups. + let Some(layer) = doc.layer(id) else { return }; + // Header: kind icon, layer name and kind (#155); sections below draw their own separators. + crate::props_layout::header(ui, layer); + let is_adjustment = matches!(layer.content, LayerContent::Adjustment(_)); + if is_adjustment || layer.artboard().is_some() || !t.pro { + ui.add_space(4.0); + widgets::hairline(ui); + ui.add_space(6.0); + } + if let LayerContent::Adjustment(adj) = &layer.content { + adjustment_controls(app, ui, id, adj); + } else if layer.artboard().is_some() { + crate::artboard_ui::properties(app, ui, layer); + } else if t.pro { + // Transform, Align, the kind's sections and Quick Actions. + crate::layer_props_ui::properties(app, ui, layer); + } else { + if matches!(layer.content, LayerContent::Fill(photocraft_doc::Fill::Gradient { .. })) { + crate::gradient_ui::properties(app, ui, layer); + ui.add_space(6.0); + } + layer_controls(app, ui, layer); + if matches!(layer.content, LayerContent::Text(_)) { + crate::type_tool::type_properties(app, ui); + } + if matches!(layer.content, LayerContent::Shape(_)) { + crate::vector_ui::shape_properties(app, ui, id); + crate::mask_props_ui::shape_properties(app, ui, layer); + } + } +} + +/// Photoshop's Adjustments panel: a grid of one-click adjustment layers. +pub(super) fn adjustments_grid(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + ui.label(RichText::new(tl!("Add an adjustment")).color(t.text_dim)); + ui.add_space(4.0); + let items: [(&str, &str, &str); 16] = [ + ("brightnessContrast", "sun", tl!("Brightness/Contrast")), + ("levels", "gauge", tl!("Levels")), + ("curves", "pen-tool", tl!("Curves")), + ("exposure", "scan", tl!("Exposure")), + ("vibrance", "sparkles", tl!("Vibrance")), + ("hueSaturation", "droplet", tl!("Hue/Saturation")), + ("colorBalance", "blend", tl!("Color Balance")), + ("blackWhite", "contrast", tl!("Black & White")), + ("photoFilter", "circle-dot", tl!("Photo Filter")), + ("channelMixer", "sliders-horizontal", tl!("Channel Mixer")), + ("invert", "squares-subtract", tl!("Invert")), + ("posterize", "layers", tl!("Posterize")), + ("threshold", "square", tl!("Threshold")), + ("gradientMap", "palette", tl!("Gradient Map")), + ("selectiveColor", "swatch-book", tl!("Selective Color")), + ("colorLookup", "grid-3x3", tl!("Color Lookup")), + ]; + let mut run = None; + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(2.0, 2.0); + for (kind, icon, tip) in items { + if icons::button(ui, icon, 30.0, false, tip).clicked() { + run = Some(format!("layer.newAdjustmentLayer.{kind}")); + } + } + }); + if let Some(id) = run { + let _ = app.run(&id, json!({})); + app.ui.dock_tabs.properties = 0; + } +} + +/// The options bar's Select and Mask… button: greyed out, as the menu item is, until there is a +/// selection (or a layer mask) to refine (#7520). +pub(super) fn select_and_mask_button(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let enabled = crate::menus::is_enabled(app, "select.selectAndMask"); + let clicked = ui.add_enabled_ui(enabled, |ui| widgets::secondary_button(ui, tl!("Select and Mask…"), 0.0).clicked()).inner; + if clicked { + let _ = crate::menus::invoke(app, ui.ctx(), "select.selectAndMask", json!({})); + } +} + +/// New / add / subtract / intersect selection buttons (shared by selection tools). +pub(super) fn selection_mode_buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + ui.spacing_mut().item_spacing.x = 2.0; + for (i, (icon, tip)) in [ + ("square", tl!("New selection").to_string()), + ("plus", crate::i18n::fmt(tl!("Add to selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift"))])), + ("minus", crate::i18n::fmt(tl!("Subtract from selection ({key})"), &[("key", &crate::shortcuts::pretty("Alt"))])), + ("squares-subtract", crate::i18n::fmt(tl!("Intersect with selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift+Alt"))])), + ] + .iter() + .enumerate() + { + if icons::button(ui, icon, 24.0, app.ui.selection_mode == i as u8, tip).clicked() { + app.ui.selection_mode = i as u8; + } + } + ui.spacing_mut().item_spacing.x = 8.0; +} diff --git a/crates/ui-egui/src/panels/status_bar.rs b/crates/ui-egui/src/panels/status_bar.rs new file mode 100644 index 0000000000..007a5805a3 --- /dev/null +++ b/crates/ui-egui/src/panels/status_bar.rs @@ -0,0 +1,74 @@ +use super::*; + +// ----------------------------------------------------------------------------- status bar + +/// The status bar's height and the height of the controls in it (zoom field, Fit), which leaves +/// them an even margin above and below inside the bar (#2823). +pub fn status_bar_heights(t: &Tokens) -> (f32, f32) { + if t.pro { (24.0, 18.0) } else { (30.0, 22.0) } +} + +pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + egui::Panel::bottom("status_bar") + .exact_size(status_bar_heights(&t).0) + .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(10, 0))) + .show(ui, |ui| { + let control_h = status_bar_heights(&t).1; + // Read from the right in a right-to-left UI, with the trailing group at the left. + crate::direction::horizontal_centered(ui, |ui| { + if t.pro { + crate::chrome_ui::status_bar_pro(app, ui); + // Background job progress with Cancel, at the far end (#210). + ui.with_layout(crate::direction::trailing(), |ui| { + crate::jobs_ui::status_progress(app, ui); + crate::background_redraw::status(app, ui); + crate::chrome_ui::gpu_memory_status(app, ui); + }); + return; + } + if let (Some(st), Some(i)) = (app.session.active(), app.session.active_index()) { + let (w, h, mode, bits, layers) = + (st.doc.size.width, st.doc.size.height, crate::canvas::mode_label(&st.doc), st.doc.depth.bits(), st.doc.layer_count()); + let mut pct = app.ui.views[i].zoom * 100.0; + if widgets::compact_wrapping_value_field(ui, &mut pct, crate::zoom_levels::percent_range(&app.ui.views[i]), "%", vec2(78.0, control_h)) + .accessible_name(tl!("Zoom")) + .changed() + { + app.ui.views[i].zoom = crate::zoom_levels::clamp(pct / 100.0, app.ui.views[i].doc_size); + app.ui.views[i].zoom_animating = false; + app.ui.views[i].zoom_anchor = None; + app.ui.views[i].fit_pending = false; + } + widgets::vline(ui, 16.0); + label(ui, &crate::i18n::fmt(tl!("{mode} Color · {bits} bit"), &[("mode", mode), ("bits", &bits.to_string())])); + widgets::vline(ui, 16.0); + label(ui, &format!("{w} × {h} px")); + widgets::vline(ui, 16.0); + label(ui, &crate::i18n::trn(crate::i18n::current(), layers as u64, "{n} layer", "{n} layers")); + } else { + label(ui, tl!("No document")); + } + if !app.ui.status.is_empty() { + widgets::vline(ui, 16.0); + let is_err = app.ui.status_error || app.ui.status.starts_with("Couldn"); + ui.label(RichText::new(&app.ui.status).color(if is_err { t.warning } else { t.text_faint })); + } + ui.with_layout(crate::direction::trailing(), |ui| { + if app.session.active().is_some() + && !t.pro + && widgets::compact_button(ui, tl!("Fit"), control_h).clicked() + && let Some(i) = app.session.active_index() + { + app.ui.views[i].fit_pending = true; + } + if app.session.has_jobs() { + ui.add_space(6.0); + crate::jobs_ui::status_progress(app, ui); + } + crate::background_redraw::status(app, ui); + crate::chrome_ui::gpu_memory_status(app, ui); + }); + }); + }); +} diff --git a/crates/ui-egui/src/panels/title_bar.rs b/crates/ui-egui/src/panels/title_bar.rs new file mode 100644 index 0000000000..10c797eb20 --- /dev/null +++ b/crates/ui-egui/src/panels/title_bar.rs @@ -0,0 +1,208 @@ +use super::*; + +// ----------------------------------------------------------------------------- title bar + +/// The app's top bar: brand mark, menus, the document title and the workspace controls. With +/// [`PhotocraftApp::custom_titlebar`] (Windows and Linux) it is also the window's title bar, as in +/// Photoshop on Windows: the caption buttons take its ends (`titlebar`). With the system +/// title bar (Windows and Linux, `system_title_bar`) the OS draws its own icon and title, so the +/// in-app bar shows menus and workspace controls only: no brand mark, no centred title. +pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + let custom = app.custom_titlebar; + let system = system_title_bar(app); + // The caption buttons' room at each end (`titlebar`); a side with buttons has no margin. + let (caption_left, caption_right) = crate::titlebar::reserved(app, ui.ctx()); + let left = if cfg!(target_os = "macos") && app.integrated_titlebar { + 78 + } else if caption_left > 0.0 { + 0 + } else { + 10 + }; + let right = if caption_right > 0.0 { 0 } else { 10 }; + let bar = egui::Panel::top("title_bar") + .exact_size(crate::titlebar::bar_height(app, ui.ctx(), if t.pro { 32.0 } else { 38.0 })) + .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin { left, right, top: 0, bottom: 0 })) + .show(ui, |ui| { + let full = ui.max_rect(); + // Only the free gap between the menus and the far-end controls drags the window: a + // press on a menu title must open the menu, never move the window. The gap is last + // frame's, as the menus are laid out after this. + let span_id = ui.scope_id().with("titledrag-span"); + let (gap_l, gap_r) = ui.ctx().data(|d| d.get_temp::<(f32, f32)>(span_id)).unwrap_or((full.right(), full.right())); + let gap = egui::Rect::from_x_y_ranges(gap_l.max(full.left())..=gap_r.min(full.right()).max(gap_l), full.y_range()); + ui.ctx().data_mut(|d| d.insert_temp(crate::titlebar::modal_drag_area_id(), gap)); + let drag = ui.interact(gap, ui.scope_id().with("titledrag"), Sense::click_and_drag()); + if drag.drag_started_by(egui::PointerButton::Primary) { + crate::titlebar::start_os_move(ui.ctx()); + } + if drag.double_clicked() { + let max = ui.ctx().input(|i| i.viewport().maximized.unwrap_or(false)); + ui.ctx().send_viewport_cmd(egui::ViewportCommand::Maximized(!max)); + } + // Preferences › Interface › Show File Name In Title: with it off the bar keeps the + // app name and the unsaved dot, since the tabs already name the file (#5037). + let show_name = app.session.prefs().interface.show_file_name_in_title; + let title = app + .session + .active() + .map(|d| format!("{}{}", if show_name { d.doc.name.as_str() } else { "PhotoCraft" }, if d.is_dirty() { " •" } else { "" })) + .unwrap_or_else(|| "PhotoCraft".into()); + // The menus and the far-end controls are laid out first; the title is centred in + // whatever room is left between them (`free`, left to right: menus then controls, or + // controls then menus in a right-to-left UI), shortened or dropped rather than drawn + // over them. + let rtl = crate::direction::is_rtl(); + let mut free = (full.left(), full.right()); + crate::direction::horizontal_centered(ui, |ui| { + // The menus start beside the caption buttons at their end, if it has any. + let lead = if rtl { caption_right } else { caption_left }; + if lead > 0.0 { + ui.add_space(lead + 4.0); + } + if !system { + let side = if t.pro { 18.0 } else { 20.0 }; + let (mark, _) = ui.allocate_exact_size(vec2(side, side), Sense::hover()); + crate::brand::paint_mark(ui, mark); + ui.add_space(6.0); + } + // With the macOS menu bar the menus are at the top of the screen instead. Either way + // this is the menus' inner edge, facing the title. + let menus_end = if app.services.native_menu.is_some() { + if rtl { ui.cursor().right() } else { ui.cursor().left() } + } else { + crate::menus::menu_bar(app, ui) + }; + // The menu bar takes the whole row, so the far-end group gets its own rect: from + // the menus to the bar's end, or to the caption buttons. + let group = if rtl { + let left_edge = if caption_left > 0.0 { full.left() + caption_left + 4.0 } else { full.left() }; + egui::Rect::from_min_max(egui::pos2(left_edge, full.top()), egui::pos2((menus_end - TITLE_GAP).max(left_edge), full.bottom())) + } else { + let right_edge = if caption_right > 0.0 { full.right() - caption_right - 4.0 } else { full.right() }; + egui::Rect::from_min_max(egui::pos2((menus_end + TITLE_GAP).min(right_edge), full.top()), egui::pos2(right_edge, full.bottom())) + }; + let mut group_ui = ui.new_child(egui::UiBuilder::new().max_rect(group).layout(crate::direction::trailing())); + let controls_end = { + let ui = &mut group_ui; + ui.spacing_mut().item_spacing.x = 6.0; + let mut ws = app.ui.workspace.clone(); + let options = crate::workspace_ui::switcher_options(app); + let opts: Vec<(String, &str)> = options.iter().map(|(k, l)| (k.clone(), l.as_str())).collect(); + // A narrow bar drops what is also in a menu, the theme toggle first + // (Preferences), then search (Edit › Search), and narrows the switcher + // (Window › Workspace) before anything runs over. + let room = ui.available_width(); + let icons_shown: u8 = if room >= WORKSPACE_MIN + 2.0 * ICON_SLOT { + 2 + } else if room >= WORKSPACE_MIN + ICON_SLOT { + 1 + } else { + 0 + }; + let ws_width = (room - f32::from(icons_shown) * ICON_SLOT - 6.0).clamp(WORKSPACE_MIN, 130.0); + if room >= WORKSPACE_MIN && widgets::dropdown(ui, "workspace", tl!("Workspace"), &mut ws, &opts, ws_width) { + app.ui.workspace = ws; + crate::menus::apply_workspace(app); + } + if icons_shown >= 1 + && icons::button(ui, "search", 28.0, app.ui.palette_open, &crate::shortcuts::tip_label(app, "Search commands", "edit.search")).clicked() + { + app.ui.palette_open = !app.ui.palette_open; + } + let (theme_icon, appearance_label) = match app.session.prefs().interface.appearance_mode { + photocraft_engine::prefs::AppearanceMode::Auto => ("monitor", tl!("Auto")), + photocraft_engine::prefs::AppearanceMode::Dark => ("moon", tl!("Dark")), + photocraft_engine::prefs::AppearanceMode::Light => ("sun", tl!("Light")), + }; + let appearance_tip = format!("{}: {}", tl!("Appearance Mode"), appearance_label); + if icons_shown >= 2 { + let button = icons::button(ui, theme_icon, 28.0, false, &appearance_tip); + if button.clicked() { + crate::prefs_ui::cycle_appearance(app, ui.ctx()); + } + button.context_menu(|ui| crate::prefs_ui::appearance_context_menu(app, ui)); + } + if rtl { ui.min_rect().right() } else { ui.min_rect().left() } + }; + free = if rtl { (controls_end, menus_end) } else { (menus_end, controls_end) }; + }); + ui.ctx().data_mut(|d| d.insert_temp(span_id, free)); + if system { + return; + } + // A right-to-left document name in display order (the OS title keeps the logical text), + // in a left-to-right line: "— PhotoCraft" stays after the name, at the right. + let title = crate::bidi_text::visual_ltr(&title).into_owned(); + let font = theme::medium(13.0); + let galley = ui.painter().layout_no_wrap(title.clone(), font.clone(), t.text_dim); + if let Some(x) = title_x(full.center().x, free.0, free.1, galley.size().x) { + ui.painter().galley(egui::pos2(x, full.center().y - galley.size().y / 2.0), galley, t.text_dim); + } else if free.1 - free.0 > 80.0 { + // Too narrow for the whole name: show the start of it, elided, in the free gap + // next to the menus. + let avail = free.1 - free.0 - 2.0 * TITLE_GAP; + let mut job = egui::text::LayoutJob::simple_singleline(title, font, t.text_dim); + job.wrap = egui::text::TextWrapping::truncate_at_width(avail); + let g = ui.painter().layout_job(job); + let x = if rtl { free.1 - TITLE_GAP - g.size().x } else { free.0 + TITLE_GAP }; + ui.painter().galley(egui::pos2(x, full.center().y - g.size().y / 2.0), g, t.text_dim); + } + }); + if custom { + crate::titlebar::caption_buttons(app, ui, bar.response.rect); + } +} + +/// Whether the window shows the system's title bar instead of the app drawing its own: Windows +/// and Linux with Preferences › Interface › System Title Bar. macOS always has system decorations, +/// but keeps the in-app brand mark and centred title, so it never counts as system mode here; nor +/// does the web build (the browser tab has no document title), nor an embedder or the snapshot +/// example that never turned the preference on. +pub fn system_title_bar(app: &PhotocraftApp) -> bool { + !app.custom_titlebar && app.session.prefs().interface.system_title_bar && !cfg!(any(target_os = "macos", target_arch = "wasm32")) +} + +/// The OS window title: the active document's name suffixed with the app name (a `*` prefix +/// marks unsaved changes, like the `•` in the app-drawn title), or just the app name with no +/// document open. With Preferences › Interface › Show File Name In Title off, the file name +/// drops out and only the app name (and the `*`) remains (#5037). +pub fn window_title(app: &PhotocraftApp) -> String { + if !app.session.prefs().interface.show_file_name_in_title { + return format!("{}PhotoCraft", if app.session.active().is_some_and(|d| d.is_dirty()) { "*" } else { "" }); + } + app.session.active().map(|d| format!("{}{} \u{2014} PhotoCraft", if d.is_dirty() { "*" } else { "" }, d.doc.name)).unwrap_or_else(|| "PhotoCraft".into()) +} + +/// Keep the OS window title (and the taskbar / Alt-Tab entry) on the active file. Sends +/// `ViewportCommand::Title` only when the title changed since the last frame. +pub fn sync_window_title(app: &mut PhotocraftApp, ctx: &egui::Context) { + let want = window_title(app); + if app.last_window_title != want { + app.last_window_title = want.clone(); + ctx.send_viewport_cmd(egui::ViewportCommand::Title(want)); + } +} + +/// Minimum space kept between the window title and the menus or controls beside it. +const TITLE_GAP: f32 = 16.0; + +/// The workspace switcher's narrowest width, and one 28 pt title-bar icon with its spacing. +const WORKSPACE_MIN: f32 = 90.0; + +const ICON_SLOT: f32 = 34.0; + +/// Left edge for a title `width` wide: centred on `center` when it fits in the free gap from +/// `left` to `right` (the menus' and the controls' facing edges, whichever side each is on), +/// else slid into that gap; None when the gap is too small for the whole title. +pub(super) fn title_x(center: f32, left: f32, right: f32, width: f32) -> Option { + let (lo, hi) = (left + TITLE_GAP, right - TITLE_GAP - width); + if !(lo.is_finite() && hi.is_finite() && width.is_finite()) || hi < lo { + return None; + } + if !center.is_finite() { + return Some(lo); + } + Some((center - width / 2.0).clamp(lo, hi)) +} diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs new file mode 100644 index 0000000000..6fb61129b9 --- /dev/null +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -0,0 +1,571 @@ +use super::options_bar::reveal_focused_control; +use super::*; + +// ----------------------------------------------------------------------------- toolbar + +/// 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. +pub(super) const TOOL_SECTIONS: &[&[&[Tool]]] = &[ + &[&[Tool::Move, Tool::Artboard]], + &[ + &[Tool::RectMarquee, Tool::EllipseMarquee, Tool::SingleRowMarquee, Tool::SingleColumnMarquee], + &[Tool::Lasso, Tool::PolygonLasso, Tool::MagneticLasso], + &[Tool::ObjectSelection, Tool::QuickSelection, Tool::MagicWand], + &[Tool::Crop, Tool::PerspectiveCrop, Tool::Slice, Tool::SliceSelect], + &[Tool::Frame], + &[Tool::Eyedropper, Tool::ColorSampler, Tool::Ruler, Tool::Note, Tool::Count], + ], + &[ + &[Tool::Remove, Tool::SpotHealing, Tool::Healing, Tool::Patch, Tool::ContentAwareMove, Tool::RedEye], + &[Tool::Brush, Tool::Pencil, Tool::MixerBrush, Tool::ColorReplacement], + &[Tool::CloneStamp, Tool::PatternStamp], + &[Tool::HistoryBrush, Tool::ArtHistoryBrush], + &[Tool::Eraser, Tool::BackgroundEraser, Tool::MagicEraser], + &[Tool::Gradient, Tool::PaintBucket], + &[Tool::Blur, Tool::Sharpen, Tool::Smudge], + &[Tool::Dodge, Tool::Burn, Tool::Sponge], + ], + &[ + &[Tool::Pen, Tool::FreeformPen, Tool::CurvaturePen, Tool::AddAnchorPoint, Tool::DeleteAnchorPoint, Tool::ConvertPoint], + &[Tool::Type, Tool::VerticalType, Tool::VerticalTypeMask, Tool::HorizontalTypeMask], + &[Tool::PathSelection, Tool::DirectSelection], + &[Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line, Tool::CustomShape], + ], + &[&[Tool::Hand, Tool::RotateView], &[Tool::Zoom]], +]; + +/// The tool a slot shows: the current tool if it belongs to the slot, else the last one used. +fn slot_tool(ui: &egui::Ui, current: Tool, slot: &[Tool], key: egui::Id) -> Tool { + if slot.contains(¤t) { + ui.data_mut(|d| d.insert_temp(key, current)); + return current; + } + ui.data(|d| d.get_temp::(key)).filter(|t| slot.contains(t)).unwrap_or(slot[0]) +} + +/// [`TOOL_SECTIONS`] without the tools hidden in Edit › Toolbar (`hidden` holds tool names: the +/// dialog writes `Tool` debug names, `edit.toolbar` takes any name `Tool::from_name` reads). A +/// slot keeps only its visible tools, so its flyout lists just those; a slot with none left is +/// dropped, and so is a section with no slots. Each slot carries its index in `TOOL_SECTIONS`, +/// so its remembered tool and flyout stay put when other slots are hidden. +pub(super) fn visible_sections(hidden: &[String]) -> Vec)>> { + let hidden: Vec = hidden.iter().map(String::as_str).filter_map(Tool::from_name).collect(); + let mut index = 0usize; + let mut sections = Vec::new(); + for section in TOOL_SECTIONS { + let mut slots = Vec::new(); + for slot in section.iter() { + let tools: Vec = slot.iter().copied().filter(|tool| !hidden.contains(tool)).collect(); + if !tools.is_empty() { + slots.push((index, tools)); + } + index += 1; + } + if !slots.is_empty() { + sections.push(slots); + } + } + sections +} + +/// A primary-button gesture started on this tool; open only after it leaves its hit area. +/// Using pointer origin rather than `Response::dragged` also works for click-only icon buttons. +pub(super) fn tool_flyout_drag_open(button: Rect, origin: Option, pointer: Option, primary_down: bool) -> bool { + primary_down && origin.is_some_and(|p| button.contains(p)) && pointer.is_some_and(|p| !button.contains(p)) +} + +/// A toolbar press cannot click a flyout row in egui because the press began elsewhere. +pub(super) fn tool_flyout_release(row: Rect, pointer: Option, released: bool, from_button: bool) -> bool { + released && from_button && pointer.is_some_and(|p| row.contains(p)) +} + +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 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") }; + 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); + } + 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(ui, app.ui.tool, slot, key); + 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); + } + if resp.clicked() && ui.data(|d| d.get_temp::(held_id)) != Some(key) { + crate::tool_memory::select(app, tool); + } + // Double-clicking the Hand tool fits the image on screen (Photoshop). + if resp.double_clicked() && 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 resp.double_clicked() && tool == Tool::Zoom { + crate::tool_memory::select(app, tool); + let _ = app.run("view.actualPixels", json!({})); + } + // 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 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), + 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)) + }); + if pressed_outside || ui.input(|i| i.key_pressed(egui::Key::Escape)) { + ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id)); + } + } + } + }); + } + } + if icons::button(ui, "ellipsis", bx, false, tl!("Edit Toolbar…")).clicked() { + let _ = crate::menus::invoke(app, &ctx, "edit.toolbar", json!({})); + } + 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 _ = crate::menus::invoke(app, &ctx, "select.editInQuickMaskMode", json!({})); + } + let sm = icons::button_with_icon_size_tip(ui, "app-window", bx, (bx * 0.52).round(), false, tl!("Change Screen Mode (F)"), tool_tips); + paint_toolbar_flyout_indicator(ui, &t, &sm); + + // 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); + if ui.add(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 +/// toolbar glyphs (#2665); the other themes keep the general icon-button proportion. +pub(super) fn toolbar_icon_size(box_size: f32, pro: bool) -> f32 { + (box_size * if pro { 2.0 / 3.0 } else { 0.52 }).round() +} + +/// 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) { + let r = resp.rect; + let tri = if crate::direction::is_rtl() { + 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)] + }; + ui.painter().add(egui::Shape::convex_polygon(tri, tokens.text_faint, Stroke::NONE)); +} + +/// Colour chips: chip size and the background chip's offset (points). +fn chip_metrics(pro: bool) -> (f32, f32) { + if pro { (18.0, 10.0) } else { (21.0, 12.0) } +} + +/// Height of the default-colours and swap icons over the chips. +const CHIP_ICON: f32 = 13.0; + +/// Studio themes: round chip diameter and the background chip's vertical offset (points). +pub(super) const STUDIO_CHIP: (f32, f32) = (30.0, 19.0); + +/// Room under the round chips for the Default Colors and Switch Colors buttons. +const STUDIO_ROW: f32 = 15.0; + +/// Room above the stacked round chips so Default Colors, at their top-right, clears them. +const STUDIO_TOP: f32 = 6.0; + +/// Height of the colour chips block. +pub(super) fn chips_height(pro: bool, studio: bool, wide: bool) -> f32 { + if studio && wide { + return STUDIO_CHIP.0 + STUDIO_ROW; + } + if studio { + return STUDIO_TOP + STUDIO_CHIP.0 + STUDIO_CHIP.1 + STUDIO_ROW; + } + let (chip, step) = chip_metrics(pro); + CHIP_ICON + 3.0 + chip + step +} + +/// Photoshop's foreground / background colour chips: the Default Colors (D) and Switch Colors (X) +/// icons above them, the foreground chip over the background one, all centred in the toolbar +/// column and kept inside it. +pub(super) fn color_chips(app: &mut PhotocraftApp, ui: &mut egui::Ui, two_columns: bool, column: f32) { + let t = Tokens::get(ui.ctx()); + // Studio themes: round chips stacked vertically, the controls below them. + let studio = t.round_chips; + let (chip, step) = if studio { STUDIO_CHIP } else { chip_metrics(t.pro) }; + // With two tool columns (a short window) the round chips lie side by side, which saves height. + let wide = studio && two_columns; + let group = if studio && !wide { chip } else { chip + step }; + let w = column.max(group); + let (rect, _) = ui.allocate_exact_size(vec2(w, chips_height(t.pro, studio, wide)), Sense::hover()); + let left = (rect.left() + (w - group) / 2.0).round(); + let (fg, bg) = if wide { + let fg = Rect::from_min_size(pos2(left, rect.top()), vec2(chip, chip)); + (fg, fg.translate(vec2(step, 0.0))) + } else if studio { + let fg = Rect::from_min_size(pos2(left, rect.top() + STUDIO_TOP), vec2(chip, chip)); + (fg, fg.translate(vec2(0.0, step))) + } else { + let fg = Rect::from_min_size(pos2(left, rect.top() + CHIP_ICON + 3.0), vec2(chip, chip)); + (fg, fg.translate(vec2(step, step))) + }; + let radius = t.radius_sm.min(3.0); + let p = ui.painter(); + if studio { + let dot = |r: Rect, color: Color32| { + p.circle_filled(r.center(), r.width() / 2.0, color); + // A light line inside a dark one, so any colour reads against the toolbar. + p.circle_stroke(r.center(), r.width() / 2.0 - 0.5, Stroke::new(1.0, t.text.gamma_multiply(0.9))); + p.circle_stroke(r.center(), r.width() / 2.0 + 0.5, Stroke::new(1.0, t.field_border)); + }; + dot(bg, c32(app.session.tools.background)); + // The foreground chip sits on the background one, a toolbar-coloured gap between them. + p.circle_filled(fg.center(), fg.width() / 2.0 + 2.0, t.chrome); + dot(fg, c32(app.session.tools.foreground)); + } else { + let frame = |r: Rect| { + // A light line inside a dark one, so any colour reads against the toolbar. + p.rect_stroke(r, radius, Stroke::new(1.0, t.text.gamma_multiply(0.9)), StrokeKind::Inside); + p.rect_stroke(r, radius, Stroke::new(1.0, t.field_border), StrokeKind::Outside); + }; + p.rect_filled(bg, radius, c32(app.session.tools.background)); + frame(bg); + p.rect_filled(fg.expand(2.0), radius + 2.0, t.chrome); + p.rect_filled(fg, radius, c32(app.session.tools.foreground)); + frame(fg); + } + // Photoshop: clicking a chip opens the Color Picker for that colour. + let bg_resp = ui.interact(bg, ui.scope_id().with("bgchip"), Sense::click()); + let fg_resp = ui.interact(fg, ui.scope_id().with("fgchip"), Sense::click()); + if fg_resp.on_hover_text(tl!("Set foreground color")).clicked() { + crate::color_picker_ui::open(app, "foreground"); + } else if bg_resp.on_hover_text(tl!("Set background color")).clicked() { + crate::color_picker_ui::open(app, "background"); + } + // Default Colors at the left, Switch Colors at the right, over the chips. + let (dr, sr) = if studio { + // Switch Colors is a curve right under the chips, centred on them so its heads touch + // them. Default Colors never moves it: at the left edge beside it when the chips lie side + // by side, at the block's top-right corner when they are stacked. + let (cx, row) = ((fg.center().x + bg.center().x) / 2.0, fg.bottom().max(bg.bottom()) + 3.5); + let default = if wide { + Rect::from_center_size(pos2(rect.left() + CHIP_ICON / 2.0, row), vec2(CHIP_ICON, CHIP_ICON)) + } else { + // Just high enough that its bottom-left corner clears the foreground chip's outline. + let x = rect.right() - CHIP_ICON; + let (dx, r) = ((x - fg.center().x).max(0.0), fg.width() / 2.0 + 1.0); + let clear = if dx < r { (r * r - dx * dx).sqrt() } else { 0.0 }; + Rect::from_min_size(pos2(x, fg.center().y - clear - CHIP_ICON), vec2(CHIP_ICON, CHIP_ICON)) + }; + (Some(default), Rect::from_center_size(pos2(cx, row), vec2(20.0, 14.0))) + } else { + let icon = |x: f32| Rect::from_min_size(pos2(x, rect.top()), vec2(CHIP_ICON, CHIP_ICON)); + (Some(icon(left)), icon(left + group - CHIP_ICON)) + }; + let d = dr.map(|dr| ui.interact(dr, ui.scope_id().with("default-colors"), Sense::click())); + let s = ui.interact(sr, ui.scope_id().with("swap-colors"), Sense::click()); + let p = ui.painter(); + for (r, resp) in dr.into_iter().zip(d.iter()).chain([(sr, &s)]) { + if resp.hovered() && !studio { + p.rect_filled(r.expand(2.0), radius, t.hover); + } + } + let ink = |resp: &egui::Response| if resp.hovered() { t.text } else { t.icon }; + if studio { + // Switch Colors: a shallow curve hugging the bottom chip, with a filled head at each end. + // It glows on hover instead of getting a button box. + let hot = s.hovered(); + let stroke = Stroke::new(1.5, ink(&s)); + let (c, rad) = (pos2(sr.center().x, sr.center().y - 5.0), 9.0); + let (from, to) = (0.45, std::f32::consts::PI - 0.45); + let arc: Vec<_> = (0..=12) + .map(|i| { + let a = from + (to - from) * i as f32 / 12.0; + c + vec2(rad * a.cos(), rad * a.sin()) + }) + .collect(); + if hot { + p.add(egui::Shape::line(arc.clone(), Stroke::new(5.0, t.text.gamma_multiply(0.18)))); + } + let ends = [(arc[0], from, -1.0_f32), (arc[arc.len() - 1], to, 1.0)]; + p.add(egui::Shape::line(arc, stroke)); + // Each head points along the curve, away from its middle. + for (end, a, sign) in ends { + let dir = vec2(-a.sin(), a.cos()) * sign; + let side = vec2(-dir.y, dir.x); + let tip = end + dir * 2.5; + let base = tip - dir * 5.0; + p.add(egui::Shape::convex_polygon(vec![tip, base + side * 3.0, base - side * 3.0], ink(&s), Stroke::NONE)); + } + } else { + // Switch Colors: the compact clockwise bend has left- and down-pointing heads. + // swap_arrow.rs owns its geometry and the pixel-level render regression test. + crate::swap_arrow::paint(p, sr.min, ink(&s)); + } + // Default Colors: a small black chip over a small white one. + if let (Some(dr), Some(d)) = (dr, d.as_ref()) { + let small = 7.0; + let (b, w) = (Rect::from_min_size(dr.min + vec2(1.0, 1.0), vec2(small, small)), Rect::from_min_size(dr.min + vec2(5.0, 5.0), vec2(small, small))); + p.rect_filled(w, 1.0, Color32::WHITE); + p.rect_stroke(w, 1.0, Stroke::new(1.0, ink(d)), StrokeKind::Inside); + p.rect_filled(b.expand(1.0), 1.5, t.chrome); + p.rect_filled(b, 1.0, Color32::BLACK); + p.rect_stroke(b, 1.0, Stroke::new(1.0, ink(d)), StrokeKind::Inside); + } + if let Some(d) = &d { + d.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Default colours (D)"))); + } + s.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Swap colours (X)"))); + if s.on_hover_text(tl!("Swap colours (X)")).clicked() { + chip_command(app, "tools.swapColors"); + } + if d.is_some_and(|d| d.on_hover_text(tl!("Default colours (D)")).clicked()) { + chip_command(app, "tools.defaultColors"); + } +} + +/// Run Switch Colors or Default Colors from the chips. As in Photoshop, characters highlighted +/// in the type layer being edited take the new foreground colour, like picking one (#5690). +fn chip_command(app: &mut PhotocraftApp, id: &str) { + if app.run(id, json!({})).is_ok() { + crate::type_tool::foreground_changed(app); + } +} From 428414a61abf8a439243e760d58fdf5eb82f8bc5 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:09:44 +0000 Subject: [PATCH 216/259] refactor(ui-egui): split type_tool.rs into type_tool/ --- crates/ui-egui/src/type_tool.rs | 4093 +------------------ crates/ui-egui/src/type_tool/defaults.rs | 253 ++ crates/ui-egui/src/type_tool/editing.rs | 470 +++ crates/ui-egui/src/type_tool/fonts.rs | 559 +++ crates/ui-egui/src/type_tool/ime.rs | 452 ++ crates/ui-egui/src/type_tool/ime_edit.rs | 409 ++ crates/ui-egui/src/type_tool/keys.rs | 347 ++ crates/ui-egui/src/type_tool/layout.rs | 87 + crates/ui-egui/src/type_tool/options_bar.rs | 405 ++ crates/ui-egui/src/type_tool/overlay.rs | 214 + crates/ui-egui/src/type_tool/panel.rs | 441 ++ crates/ui-egui/src/type_tool/pointer.rs | 447 ++ 12 files changed, 4142 insertions(+), 4035 deletions(-) create mode 100644 crates/ui-egui/src/type_tool/defaults.rs create mode 100644 crates/ui-egui/src/type_tool/editing.rs create mode 100644 crates/ui-egui/src/type_tool/fonts.rs create mode 100644 crates/ui-egui/src/type_tool/ime.rs create mode 100644 crates/ui-egui/src/type_tool/ime_edit.rs create mode 100644 crates/ui-egui/src/type_tool/keys.rs create mode 100644 crates/ui-egui/src/type_tool/layout.rs create mode 100644 crates/ui-egui/src/type_tool/options_bar.rs create mode 100644 crates/ui-egui/src/type_tool/overlay.rs create mode 100644 crates/ui-egui/src/type_tool/panel.rs create mode 100644 crates/ui-egui/src/type_tool/pointer.rs diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/type_tool.rs index 219a71e9fb..8d46c71c03 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/type_tool.rs @@ -19,707 +19,66 @@ use crate::PhotocraftApp; use crate::canvas::ViewXform; use crate::state::{BoxResize, TextEdit}; +mod defaults; +mod editing; +mod fonts; +mod ime; +mod ime_edit; +mod keys; +mod layout; +mod options_bar; +mod overlay; +mod panel; +mod pointer; + +#[cfg(test)] +use defaults::{apply, default_style_params, default_styles, shown_scale}; +pub use defaults::{foreground_changed, open_color_picker}; +pub(crate) use defaults::{formatting_params, target, target_text, type_unit, with_target}; +#[cfg(test)] +use editing::{insert, insert_typed, smart_quotes}; +#[cfg(test)] +pub(crate) use editing::{CharToggle, step_char_metric, toggle_char_style, toggle_hyphenate}; +pub use editing::{cancel, commit, commit_with, edit_active, edit_at, end_if_left}; +pub(crate) use editing::{copy_selection, cut_selection, request_paste, select_all}; +#[cfg(test)] +use fonts::{font_labels_id, FONT_MENU_HEIGHT, font_menu_rows, font_picker_in, style_names, wheel_family_index}; +#[cfg(test)] +pub(crate) use fonts::{Axis, axis_value, slider_axes}; +pub use fonts::{families, style_label, styles, sync_font_names, warm_fonts}; +pub(crate) use fonts::{family_picker_in, fonts_ready, selected_style}; +#[cfg(test)] +use ime::{IncomingComposition, ResetPhase}; +pub(crate) use ime::{controls_only, finish_reset_logic, finish_reset_pass, ImeState, in_ui_pass, install_reset_hooks}; +#[cfg(test)] +use ime_edit::ime_update; +pub(crate) use ime_edit::sync_ime; +#[cfg(test)] +pub(crate) use keys::flow_key; +pub use keys::handle_keys; +pub use layout::layout; +pub(crate) use layout::{hit_layer, offset_at, shows_own_layout}; +#[cfg(test)] +use options_bar::num_field; +#[cfg(test)] +pub(crate) use options_bar::{kerning_label, parse_kerning}; +pub use options_bar::options_bar; +pub(crate) use options_bar::styles_at; +#[cfg(test)] +use overlay::CARET_STROKES; +pub use overlay::draw_overlay; +#[cfg(test)] +pub(crate) use panel::{OPENTYPE_BUTTONS, toggle_opentype}; +pub use panel::{character_panel, type_properties}; +#[cfg(test)] +use pointer::{handle_sides, MIN_BOX, word_boundary}; +#[cfg(test)] +pub(crate) use pointer::{box_shape, click_selection, next_click_count, path_target}; +pub use pointer::{multi_click, pointer_down, pointer_move, pointer_up}; +pub(crate) use pointer::{box_handle_at, hover_path_target, inside_box, PathClick}; + pub const PLACEHOLDER: &str = "Lorem Ipsum"; -/// Per-editor IME owner/generation bookkeeping for the custom Type tool. -/// -/// The tracker is shared by every viewport and keeps the context generation alive when this -/// editor is replaced. The overlay records the pass's canvas mapping and the pass end recomputes -/// the final geometry from the observed model, so an event-free or discarded pass never replays -/// stale text. -#[derive(Debug, Default)] -pub(crate) struct ImeState { - tracker: ImeContextTracker, - frame: Option, - /// The canvas mapping of the current pass, so the final descriptor geometry is recomputed - /// from the observed model rather than from an earlier point in the pass. - view: Option, - /// The last descriptor identity the platform actually received (a discarded pass did not - /// receive it, so its transition must still be reported by the final pass). - emitted: Option, - /// Ask the platform to cancel the native composition (owner/session transition or a stale - /// pre-edit). Stays set until a non-discarded descriptor carries it. - interrupt: bool, - /// Incoming composition provenance survives idle/discarded passes and an empty preedit. - /// A stale owner stays fenced until the exact host reset completion arrives. - incoming: Option, - /// The composition text was invalidated; this pass must report `Unavailable` rather than - /// presenting the orphaned composition as committed text. - stale: bool, - /// The exact composition written into the layer, used to check the stored range before any - /// replacement, deletion, underline or surrounding-text report. - preedit: Option, - /// A local fence is released only by its exact host completion, never by terminal text. - resets: HashMap, - context: Option, - needs_request: bool, - /// One exclusive event owner per actual UI pass; logic-only ticks never replay input. - raw_pass: HashMap, - custom_pass: HashMap)>, - last_custom: HashMap, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct ResetContext(egui::Id, u64, egui::IMEPurpose); - -impl From<&egui::output::IMEOutput> for ResetContext { - fn from(ime: &egui::output::IMEOutput) -> Self { - Self(ime.owner, ime.context_generation, ime.purpose) - } -} - -#[derive(Clone, Copy, Debug)] -enum ResetPhase { - NeedsRequest, - Awaiting { id: egui::ImeResetId, destination: IncomingSelection, context: Option }, - Suspended, - AllocationFailed { destination: IncomingSelection, context: Option }, -} - -#[derive(Clone, Copy, Debug)] -struct ImeFrame { - viewport: egui::ViewportId, - frame_nr: u64, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct ImeEmitted { - target: ImeTarget, - generation: u64, -} - -#[derive(Clone, Copy, Debug)] -struct ImeView { - viewport: egui::ViewportId, - pass_nr: u64, - xf: ViewXform, -} - -/// The composition text and the edit session that wrote it. A range that still lies inside the -/// text is not enough: an application edit can shift it onto committed characters. -#[derive(Clone, Debug, PartialEq, Eq)] -struct ImePreedit { - layer: u64, - session: String, - text: String, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct IncomingSelection { - target: ImeTarget, - caret: usize, - anchor: usize, - revision: u64, -} - -#[derive(Clone, Copy, Debug)] -enum IncomingComposition { - Active(IncomingSelection), - TerminalPending(IncomingSelection), - Stale, -} - -/// A bounded committed snapshot captured from the type layer. -/// -/// The snapshot owns at most `MAX_IME_SURROUNDING_TEXT_BYTES`; the layer's whole text is only -/// borrowed while it is built. The current pre-edit lives in the layer so it lays out like -/// typed text, and is removed from this value rather than reported as committed text. -struct ImeCommitted { - snapshot: egui::output::IMESurroundingText, -} - -impl ImeCommitted { - fn stamp(&self) -> ImeMutationStamp { - ImeMutationStamp::from_surrounding_text(self.snapshot.clone()) - } -} - -impl ImeState { - /// Remember the frame used by this pass's accepted IME receipts. - fn begin_frame(&mut self, ctx: &egui::Context) { - let viewport = ctx.viewport_id(); - self.frame = Some(ImeFrame { viewport, frame_nr: ctx.cumulative_frame_nr_for(viewport) }); - } - - /// Record the canvas mapping of this pass. `sync_ime` recomputes both rectangles from the - /// model after every panel has run. - fn note_view(&mut self, viewport: egui::ViewportId, pass_nr: u64, xf: &ViewXform) { - self.view = Some(ImeView { viewport, pass_nr, xf: *xf }); - } - - /// Request the native composition reset; incoming ownership is tracked separately. - fn request_interrupt(&mut self) { - self.interrupt = true; - if self.incoming.is_some() || !self.resets.is_empty() { - self.needs_request = true; - // Context-less commands must retire every old id synchronously. - for phase in self.resets.values_mut() { - *phase = ResetPhase::NeedsRequest; - } - } - } - - /// Forget a composition whose range no longer describes the recorded text. - fn invalidate_preedit(&mut self) { - self.preedit = None; - self.stale = true; - self.incoming = Some(IncomingComposition::Stale); - self.request_interrupt(); - } - - fn note_preedit(&mut self, ed: &TextEdit, text: &str) { - self.preedit = Some(ImePreedit { layer: ed.layer, session: ed.session.clone(), text: text.to_owned() }); - } - - fn clear_preedit(&mut self) { - self.preedit = None; - } -} - -/// The immutable owner of the Type tool's IME context. -/// -/// The document, layer and viewport identify the target; the edit session is the replacement -/// epoch, so committing and editing the same layer again cannot reuse the old generation. -fn ime_target(app: &PhotocraftApp, ed: &TextEdit, viewport: egui::ViewportId) -> Option { - let document = ed.document.or_else(|| active_doc_id(app))?; - // A Type Mask session is a distinct owner: its hidden working layer can have the same id as - // a regular type layer in another tool session. The session epoch replaces the context when - // an owner is recreated. - let owner = egui::Id::unique(("photocraft-type-ime", document, ed.layer, ed.mask, viewport.0.value())); - let epoch = egui::Id::unique(("photocraft-type-ime-session", &ed.session)).value().max(1); - Some(ImeTarget::new(owner, epoch)) -} - -fn incoming_selection(app: &PhotocraftApp, viewport: egui::ViewportId) -> Option { - let ed = app.ui.text_edit.as_ref()?; - Some(IncomingSelection { target: ime_target(app, ed, viewport)?, caret: ed.caret, anchor: ed.anchor, revision: app.session.active()?.revision }) -} - -/// Settle the already-visible preview where it was typed, never replay it at a moved caret. -fn interrupt_incoming(app: &mut PhotocraftApp) { - if !matches!(app.type_ime.incoming, Some(IncomingComposition::Active(_) | IncomingComposition::TerminalPending(_))) { - return; - } - app.type_ime.incoming = Some(IncomingComposition::Stale); - if let Some(ed) = &mut app.ui.text_edit { - ed.preedit = None; - } - app.type_ime.clear_preedit(); - app.type_ime.request_interrupt(); -} - -fn interrupt_action(app: &mut PhotocraftApp, viewport: egui::ViewportId) { - let guarded = reset_guarded(app, viewport); - interrupt_incoming(app); - if guarded { - app.type_ime.request_interrupt(); - } -} - -fn sync_incoming(app: &mut PhotocraftApp, viewport: egui::ViewportId) { - let destination = incoming_selection(app, viewport); - if app.type_ime.resets.get(&viewport).is_some_and(|phase| match phase { - ResetPhase::Awaiting { destination: old, .. } | ResetPhase::AllocationFailed { destination: old, .. } => Some(*old) != destination, - _ => false, - }) { - app.type_ime.request_interrupt(); - } - let expected = match app.type_ime.incoming { - Some(IncomingComposition::Active(expected) | IncomingComposition::TerminalPending(expected)) => expected, - _ => return, - }; - let lost_preview = matches!(app.type_ime.incoming, Some(IncomingComposition::Active(_))) && app.ui.text_edit.as_ref().is_none_or(|ed| ed.preedit.is_none()); - if incoming_selection(app, viewport) != Some(expected) || lost_preview { - // An external edit can move an in-bounds preview range onto committed characters. - // Validate it before interruption clears the metadata needed to detect that mismatch. - // A valid preview still settles normally; never inspect another document's layer here. - if let Some(ed) = app.ui.text_edit.clone() - && ed.preedit.is_some() - && ime_target(app, &ed, viewport) == Some(expected.target) - && let Some(active) = app.session.active_index() - && edit_home(app, &ed) == Some(active) - && let Some(text) = current_text(app, LayerId(ed.layer)) - && reconcile_preedit(app, &ed, &text) - { - return; - } - interrupt_incoming(app); - } -} - -/// Accepted IME mutations update provenance without canceling their own Delete→Commit chain. -fn remember_incoming(app: &mut PhotocraftApp, preedit_empty: Option) { - let viewport = app.type_ime.frame.map_or(egui::ViewportId::ROOT, |frame| frame.viewport); - let Some(expected) = incoming_selection(app, viewport) else { return }; - let next = match (preedit_empty, app.type_ime.incoming) { - (Some(false), _) | (None, Some(IncomingComposition::Active(_))) => IncomingComposition::Active(expected), - (Some(true), _) | (None, Some(IncomingComposition::TerminalPending(_))) => IncomingComposition::TerminalPending(expected), - _ => return, - }; - app.type_ime.incoming = Some(next); -} - -/// A host may recreate its Context while retaining the application. Old pass counters and -/// output keys are not evidence of publication in that new Context. -fn bind_reset_context(app: &mut PhotocraftApp, ctx: &egui::Context) { - // `on_begin_pass` callbacks registered during this pass cannot mark the pass already - // running. Reinstall here so a replacement Context is ready for its next pass, and rely on - // the host's creator/`setup_context` having installed before the very first `run_ui`. - install_reset_hooks(ctx); - if app.type_ime.context.as_ref().is_some_and(|previous| previous != ctx) { - interrupt_incoming(app); - for phase in app.type_ime.resets.values_mut() { - *phase = ResetPhase::Suspended; - } - app.type_ime.needs_request = false; - app.type_ime.raw_pass.clear(); - app.type_ime.custom_pass.clear(); - app.type_ime.last_custom.clear(); - app.type_ime.view = None; - app.type_ime.frame = None; - app.type_ime.tracker.observe(ctx.viewport_id(), None); - } - app.type_ime.context = Some(ctx.clone()); -} - -fn ui_mode_id(viewport: egui::ViewportId) -> egui::Id { - egui::Id::unique(("photocraft-type-reset-ui", viewport)) -} - -/// Install before the first UI pass on every Context, including a replacement. These callbacks -/// retain neither the app nor its Context. Calling this from inside a running pass only affects -/// subsequent passes: egui's begin-pass callback list is already being iterated. -pub(crate) fn install_reset_hooks(ctx: &egui::Context) { - let installed = egui::Id::unique("photocraft-type-reset-hooks"); - if ctx.data(|data| data.get_temp::(installed)).unwrap_or(false) { - return; - } - ctx.data_mut(|data| data.insert_temp(installed, true)); - ctx.on_begin_pass( - "photocraft type reset UI mode", - Arc::new(|ui| { - let key = ui_mode_id(ui.ctx().viewport_id()); - ui.ctx().data_mut(|data| data.insert_temp(key, true)); - }), - ); - ctx.on_end_pass( - "photocraft type reset UI mode end", - Arc::new(|ui| { - let key = ui_mode_id(ui.ctx().viewport_id()); - ui.ctx().data_mut(|data| data.insert_temp(key, false)); - }), - ); -} - -pub(crate) fn in_ui_pass(ctx: &egui::Context) -> bool { - let key = ui_mode_id(ctx.viewport_id()); - ctx.data(|data| data.get_temp::(key)).unwrap_or(false) -} - -fn reset_guarded(app: &PhotocraftApp, viewport: egui::ViewportId) -> bool { - app.type_ime.needs_request || app.type_ime.resets.contains_key(&viewport) || matches!(app.type_ime.incoming, Some(IncomingComposition::Stale)) -} - -fn reset_route_eligible(app: &PhotocraftApp, ctx: &egui::Context) -> bool { - // The actual app draws only after `logic_frame` marks fonts ready; `ui_frame` early-returns - // on the first frame. Direct handler tests that have not run the first logic frame use the - // pre-styled app state and are not an actual UI route. - (app.fonts_ready || !app.styled) - && app.ui.text_edit.is_some() - && app.ui.dialogs.is_empty() - && !crate::screen_picker::busy(ctx) - && ctx.input(|i| i.focused) - && !ctx.text_edit_focused() - && !ctx.egui_wants_keyboard_input() -} - -/// Whether this input can be attributed to a visible custom descriptor right now. Completion -/// arrives before the final descriptor exists, so use the last canvas mapping and the current -/// model: requiring this pass's final output here would deadlock the ordered suffix. -fn reset_geometry_available(app: &mut PhotocraftApp, viewport: egui::ViewportId) -> bool { - let Some(ed) = app.ui.text_edit.clone() else { return false }; - let Some(view) = app.type_ime.view.filter(|view| view.viewport == viewport) else { return false }; - ime_geometry(app, &ed, view.xf).is_some() -} - -fn suspend_reset(app: &mut PhotocraftApp, ctx: &egui::Context) { - let viewport = ctx.viewport_id(); - if reset_guarded(app, viewport) { - app.type_ime.resets.insert(viewport, ResetPhase::Suspended); - app.type_ime.needs_request = false; - } - app.type_ime.last_custom.remove(&viewport); -} - -fn allocate_reset(app: &mut PhotocraftApp, ctx: &egui::Context, destination: IncomingSelection, context: Option) { - let viewport = ctx.viewport_id(); - let phase = match ctx.request_ime_reset(viewport) { - Some(id) => ResetPhase::Awaiting { id, destination, context }, - None => ResetPhase::AllocationFailed { destination, context }, - }; - app.type_ime.resets.insert(viewport, phase); - app.type_ime.needs_request = false; -} - -/// Reconcile before the next raw element, not merely at descriptor publication. -fn prepare_reset(app: &mut PhotocraftApp, ctx: &egui::Context) { - let viewport = ctx.viewport_id(); - sync_incoming(app, viewport); - if app.type_ime.needs_request { - app.type_ime.resets.insert(viewport, ResetPhase::NeedsRequest); - app.type_ime.needs_request = false; - } - // Allocation belongs to the true UI tail: a stock field drawn later in this pass - // must never inherit a speculative custom-editor reset request. -} - -fn complete_reset(app: &mut PhotocraftApp, ctx: &egui::Context, request_id: egui::ImeResetId) { - let viewport = ctx.viewport_id(); - let Some(ResetPhase::Awaiting { id, destination, context }) = app.type_ime.resets.get(&viewport).copied() else { return }; - if request_id != id - || request_id.viewport_id() != viewport - || !reset_route_eligible(app, ctx) - || incoming_selection(app, viewport) != Some(destination) - || context != app.type_ime.last_custom.get(&viewport).copied() - { - return; - } - if !reset_geometry_available(app, viewport) { - // Retire the old id and keep the following preedit blocked before it can reach the - // editor. The UI tail may still rearm once this pass produces real custom output. - suspend_reset(app, ctx); - return; - } - app.type_ime.resets.remove(&viewport); - app.type_ime.incoming = None; - app.type_ime.preedit = None; - app.type_ime.stale = false; - app.type_ime.interrupt = false; - if let Some(ed) = app.ui.text_edit.as_mut() { - ed.preedit = None; - } -} - -fn claim_raw_pass(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { - let viewport = ctx.viewport_id(); - let pass = ctx.cumulative_pass_nr_for(viewport); - app.type_ime.raw_pass.insert(viewport, pass) != Some(pass) -} - -/// The exclusive route when no custom editor may mutate. Do not consume stock text/keys. -pub(crate) fn controls_only(app: &mut PhotocraftApp, ctx: &egui::Context) { - bind_reset_context(app, ctx); - if !claim_raw_pass(app, ctx) { - return; - } - if !reset_route_eligible(app, ctx) { - interrupt_incoming(app); - } - suspend_reset(app, ctx); // Retire an old id before visiting even the first marker. - for event in ctx.input(|i| i.events.clone()) { - if let egui::Event::ImeResetCompleted { request_id } = event { - complete_reset(app, ctx, request_id); - } - } -} - -/// True outer UI tail, including discarded/early-return passes and host-side mutations. -pub(crate) fn finish_reset_pass(app: &mut PhotocraftApp, ctx: &egui::Context) { - bind_reset_context(app, ctx); - let viewport = ctx.viewport_id(); - if app.type_ime.raw_pass.get(&viewport).copied() != Some(ctx.cumulative_pass_nr_for(viewport)) { - controls_only(app, ctx); - } - sync_incoming(app, viewport); - let produced = app.type_ime.custom_pass.get(&viewport).copied().filter(|(pass, _)| *pass == ctx.cumulative_pass_nr_for(viewport)).and_then(|(_, key)| key); - let actual = ctx.output(|o| o.ime.as_ref().map(ResetContext::from)); - let Some(context) = produced.filter(|key| Some(*key) == actual && reset_route_eligible(app, ctx)) else { - suspend_reset(app, ctx); - return; - }; - // Never allocate a request for output egui will throw away. Keep any existing guard and its - // queued R1 blocked; the final pass either publishes this context and reuses it or retires - // the old id through the ineligible branch above. - if ctx.will_discard() { - return; - } - app.type_ime.last_custom.insert(viewport, context); - if !reset_guarded(app, viewport) { - return; - } - let Some(destination) = incoming_selection(app, viewport) else { - suspend_reset(app, ctx); - return; - }; - let unchanged = app.type_ime.resets.get(&viewport).is_some_and(|phase| match phase { - ResetPhase::Awaiting { destination: old, context: old_context, .. } | ResetPhase::AllocationFailed { destination: old, context: old_context } => { - *old == destination && *old_context == Some(context) && !app.type_ime.needs_request - } - _ => false, - }); - if !unchanged { - allocate_reset(app, ctx, destination, Some(context)); - } -} - -pub(crate) fn finish_reset_logic(app: &mut PhotocraftApp, ctx: &egui::Context) { - bind_reset_context(app, ctx); - if !in_ui_pass(ctx) { - sync_incoming(app, ctx.viewport_id()); - suspend_reset(app, ctx); - } -} - -/// UTF-8 byte offsets of the caret, anchor and pre-edit, found in one traversal. -/// -/// The pre-edit is in characters in [`TextEdit`]; surround-text offsets are UTF-8 bytes. A range -/// that runs past the text is an explicit unavailable state, not a reason to report the -/// composition as committed. -struct ImeOffsets { - cursor: usize, - anchor: usize, - preedit: Option>, -} - -fn ime_offsets(text: &str, ed: &TextEdit) -> Option { - let (start, end) = match ed.preedit { - Some((start, len)) => (start, start.checked_add(len)?), - None => (0, 0), - }; - let wanted = [ed.caret, ed.anchor, start, end]; - let mut bytes = [usize::MAX; 4]; - let mut chars = 0usize; - for (index, (byte, _)) in text.char_indices().enumerate() { - for (slot, want) in bytes.iter_mut().zip(wanted) { - if *slot == usize::MAX && want == index { - *slot = byte; - } - } - chars = index.saturating_add(1); - } - // An index at (or past) the end clamps to the end, as before; a pre-edit past the end is a - // stale composition and makes the surrounding text unavailable. - for (slot, (index, want)) in bytes.iter_mut().zip(wanted.into_iter().enumerate()) { - if *slot == usize::MAX { - // The caret and anchor clamp after undo/redo; a pre-edit beyond the text is stale. - if index >= 2 && want > chars { - return None; - } - *slot = text.len(); - } - } - let preedit = match ed.preedit { - Some(_) if end > chars => return None, - Some(_) => Some(bytes[2]..bytes[3]), - None => None, - }; - Some(ImeOffsets { cursor: bytes[0], anchor: bytes[1], preedit }) -} - -/// Whether the stored character range still contains exactly the composition that wrote it. -fn ime_preedit_is_current(app: &PhotocraftApp, text: &str, ed: &TextEdit, offsets: &ImeOffsets) -> bool { - match (ed.preedit, offsets.preedit.as_ref()) { - (None, _) => true, - (Some(_), Some(range)) => { - app.type_ime.preedit.as_ref().is_some_and(|p| p.layer == ed.layer && p.session == ed.session && text.get(range.clone()) == Some(p.text.as_str())) - } - (Some(_), None) => false, - } -} - -/// Check the stored pre-edit against the live text, invalidating it (and the native composition) -/// when an application edit moved or replaced it. Returns true when it was stale. -fn reconcile_preedit(app: &mut PhotocraftApp, ed: &TextEdit, text: &str) -> bool { - if ed.preedit.is_none() { - return false; - } - let current = ime_offsets(text, ed).is_some_and(|offset| ime_preedit_is_current(app, text, ed, &offset)); - if current { - return false; - } - app.type_ime.invalidate_preedit(); - if let Some(e) = app.ui.text_edit.as_mut() { - e.preedit = None; - } - true -} - -/// A borrowed observation for the tracker. It copies only the bounded window. -fn committed_text<'a>(app: &PhotocraftApp, text: &'a str, ed: &TextEdit) -> Option> { - let offsets = ime_offsets(text, ed)?; - if !ime_preedit_is_current(app, text, ed, &offsets) { - return None; - } - let committed = CommittedText::new(text, offsets.cursor, offsets.anchor); - Some(match offsets.preedit { - Some(preedit) => committed.with_preedit(preedit), - None => committed, - }) -} - -/// The bounded committed snapshot of the edited layer, or `None` when it cannot be exposed. -fn ime_committed(app: &PhotocraftApp, ed: &TextEdit) -> Option { - let text = text_layer(&app.session.active()?.doc, LayerId(ed.layer))?.text.as_str(); - let offsets = ime_offsets(text, ed)?; - if !ime_preedit_is_current(app, text, ed, &offsets) { - return None; - } - Some(ImeCommitted { snapshot: egui::output::IMESurroundingText::from_text(text, offsets.cursor, offsets.anchor, offsets.preedit) }) -} - -/// Report an accepted IME commit/deletion. Call only after the engine accepted the mutation and -/// from the snapshots immediately around it. -fn note_ime_apply(app: &mut PhotocraftApp, ed: &TextEdit, before: &ImeCommitted, after: &ImeCommitted) -> bool { - let Some(frame) = app.type_ime.frame else { return false }; - let Some(target) = ime_target(app, ed, frame.viewport) else { return false }; - app.type_ime.tracker.note_input_method_apply(frame.viewport, frame.frame_nr, target, before.stamp(), after.stamp()) -} - -/// Report an application-origin edit (typing, paste, cut, deletion, undo or a toolbar action). -fn note_ime_application_change(app: &mut PhotocraftApp, ed: &TextEdit) -> bool { - let Some(frame) = app.type_ime.frame else { return false }; - let Some(target) = ime_target(app, ed, frame.viewport) else { return false }; - app.type_ime.tracker.note_application_change(frame.viewport, frame.frame_nr, target) -} - -/// Snapshot after the engine mutation and describe the current pass. -/// -/// Run once per UI pass, after the editor has drawn its caret, so the descriptor reflects this -/// pass's final model state. With no visible focused editor the context is ended; a moved focus -/// therefore cannot leave the previous owner's surrounding text latched. -pub(crate) fn sync_ime(app: &mut PhotocraftApp, ctx: &egui::Context) { - bind_reset_context(app, ctx); - let viewport = ctx.viewport_id(); - let frame_nr = ctx.cumulative_frame_nr_for(viewport); - let pass_nr = ctx.cumulative_pass_nr_for(viewport); - app.type_ime.custom_pass.insert(viewport, (pass_nr, None)); - sync_incoming(app, viewport); - let Some(mut ed) = app.ui.text_edit.clone() else { - app.type_ime.view = None; - app.type_ime.tracker.observe(viewport, None); - return; - }; - // An application edit (control channel, undo, a menu command) can move the stored composition - // range onto committed characters. Check the actual composition text before reporting it. - if ed.preedit.is_some() - && let Some(text) = current_text(app, LayerId(ed.layer)) - && reconcile_preedit(app, &ed, &text) - && let Some(current) = app.ui.text_edit.clone() - { - ed = current; - } - let view = app.type_ime.view.filter(|view| view.viewport == viewport && view.pass_nr == pass_nr); - let visible = view.is_some() && app.session.active_index().is_some() && edit_home(app, &ed) == app.session.active_index(); - let focused = visible && reset_route_eligible(app, ctx); - if !focused { - interrupt_incoming(app); - if let Some(current) = &app.ui.text_edit { - ed = current.clone(); - } - } - let Some(target) = ime_target(app, &ed, viewport) else { - app.type_ime.tracker.observe(viewport, None); - return; - }; - // The platform only resets the native composition from `should_interrupt_composition`; on - // X11, macOS, Windows and the web a changed owner/generation alone leaves it alive. Latch the - // last *delivered* target so a discarded pass does not lose the transition. - if app.type_ime.emitted.is_some_and(|last| last.target != target) { - app.type_ime.interrupt = true; - } - // Final geometry from this pass's model and canvas mapping: a later panel can move the caret - // after the overlay drew it, and `rect` is the edited layer's extent, not the caret. - let geometry = if focused { view.and_then(|view| ime_geometry(app, &ed, view.xf)) } else { None }; - // Borrow the layer's logical text for this observation; only the bounded window is copied. - let committed = if focused && !app.type_ime.stale { - app.session.active().and_then(|state| text_layer(&state.doc, LayerId(ed.layer))).and_then(|layer| committed_text(app, &layer.text, &ed)) - } else { - None - }; - let observation = ImeObservation::new(frame_nr, pass_nr, target).focused(focused).purpose(egui::IMEPurpose::Normal).committed(committed); - let update = app.type_ime.tracker.observe(viewport, Some(observation)); - // A generation change (focus/refocus, a pass gap, purpose or replacement) also needs the - // native reset; the tracker reports it only after observing. - let mut interrupt = app.type_ime.interrupt; - if let Some(update) = &update - && app.type_ime.emitted.is_some_and(|last| last.target != target || last.generation != update.context_generation) - { - app.type_ime.interrupt = true; - interrupt = true; - } - let mut sent = false; - let mut sent_generation = None; - if let (Some(update), Some((rect, cursor_rect))) = (update, geometry) { - let generation = update.context_generation; - // Owner and generation accompany even an Unavailable payload. The cause comes from the - // tracker's accepted-receipt chain, never from the event that happened to be last. - ctx.output_mut(|out| { - out.ime = Some(egui::output::IMEOutput { - owner: update.owner, - context_generation: update.context_generation, - purpose: update.purpose, - rect, - cursor_rect, - should_interrupt_composition: interrupt, - change_cause: update.change_cause, - surrounding_text: update.surrounding_text, - reset_request: None, - }); - }); - let key = ctx.output(|out| out.ime.as_ref().map(ResetContext::from)); - app.type_ime.custom_pass.insert(viewport, (pass_nr, key)); - sent = true; - sent_generation = Some(generation); - } - if sent && !ctx.will_discard() { - if let Some(generation) = sent_generation { - app.type_ime.emitted = Some(ImeEmitted { target, generation }); - } - app.type_ime.interrupt = false; - app.type_ime.stale = false; - } -} - -/// The final caret and layer rectangles for an IME descriptor, in screen points. -fn ime_geometry(app: &mut PhotocraftApp, ed: &TextEdit, xf: ViewXform) -> Option<(egui::Rect, egui::Rect)> { - let id = LayerId(ed.layer); - let (l, aff, text) = layout(app, id)?; - let shape = app.session.active().and_then(|s| text_layer(&s.doc, id).map(|t| t.shape.clone())); - let bend = shape.as_ref().and_then(photocraft_text::warp::Warp::on_path); - let scr_t = |x: f32, y: f32| -> Pos2 { - let p = aff.apply(Point::new(f64::from(x), f64::from(y))); - xf.to_screen(p.x as f32, p.y as f32) - }; - let scr = |x: f32, y: f32| -> Pos2 { - let (x, y) = l.to_text(x, y); - match &bend { - Some(w) => { - let (x, y) = w.apply(f64::from(x), f64::from(y)); - scr_t(x as f32, y as f32) - } - None => scr_t(x, y), - } - }; - let (x, top, bot) = l.caret(byte_of(&text, ed.caret)); - let (x, top, bot) = if l.lines.is_empty() { (0.0, -(12.0 * l.px_per_pt.max(1.0)), 3.0) } else { (x, top, bot) }; - let cursor = egui::Rect::from_two_pos(scr(x, top), scr(x, bot)).expand(1.0); - let doc_bounds = - app.session.active().and_then(|s| text_layer(&s.doc, id)).and_then(|t| t.cache.as_ref()).map(|c| c.content_bounds()).filter(|r| !r.is_empty()); - let rect = doc_bounds.map(|r| xf.doc_rect(r)).or_else(|| { - l.bounds().map(|b| { - let corners = [scr_t(b[0], b[1]), scr_t(b[2], b[1]), scr_t(b[2], b[3]), scr_t(b[0], b[3])]; - let mut min = corners[0]; - let mut max = corners[0]; - for p in corners { - min = min.min(p); - max = max.max(p); - } - egui::Rect::from_min_max(min, max) - }) - }); - Some((rect.unwrap_or(cursor).expand(1.0), cursor)) -} - fn text_layer(doc: &Document, id: LayerId) -> Option<&TextLayer> { match &doc.layer(id)?.content { LayerContent::Text(t) => Some(t), @@ -731,541 +90,11 @@ fn byte_of(text: &str, ci: usize) -> usize { photocraft_text::byte_index(text, ci) } -/// Layout of a type layer (cached per document revision) and its text → document transform. -pub fn layout(app: &mut PhotocraftApp, id: LayerId) -> Option<(Arc, Affine, String)> { - let dragged = crate::type_transform::current_transform(app, id); - // Borrows the document in place (no clone): the canvas hover hit-tests type every frame. - let st = app.session.active()?; - let t = text_layer(&st.doc, id)?; - let transform = dragged.unwrap_or(t.transform); - let key = (st.doc.id.0, st.revision, id.0); - if let Some((k, l)) = &app.type_layout - && *k == key - { - return Some((l.clone(), transform, t.text.clone())); - } - let l = Arc::new(photocraft_text::shared().lock().ok()?.layout(t, st.doc.resolution_dpi)); - app.type_layout = Some((key, l.clone())); - Some((l, transform, t.text.clone())) -} - -fn to_text(aff: &Affine, x: f64, y: f64) -> (f32, f32) { - let p = aff.inverse().unwrap_or(Affine::IDENTITY).apply(Point::new(x, y)); - (p.x as f32, p.y as f32) -} - -/// Topmost shown type layer (it and every group around it visible, #4320) whose laid-out text -/// contains the document point. The press and the canvas hover (`hover_path_target`) share it, so -/// the pointer never promises a path click that the press would turn into editing this layer. -pub(crate) fn hit_layer(app: &mut PhotocraftApp, x: f64, y: f64) -> Option { - let slop = 6.0 / app.point_zoom().max(0.01); - // A Type Mask session's text is a hidden layer; it is still the text being edited. - let editing = app.ui.text_edit.as_ref().filter(|ed| ed.mask).map(|ed| LayerId(ed.layer)); - let mut ids: Vec = { - let doc = &app.session.active()?.doc; - doc.walk() - .into_iter() - .filter(|(path, _, l)| matches!(l.content, LayerContent::Text(_)) && (editing == Some(l.id) || doc.shown_at(path))) - .map(|(_, _, l)| l.id) - .collect() - }; - ids.reverse(); // walk() is bottom-up; hit the topmost first - ids.into_iter().find(|id| { - // The pixels shown count too: a PSD's type keeps Photoshop's rendering until edited, - // which can sit off our layout when fonts are substituted (#123). - let shown = app.session.active().and_then(|st| text_layer(&st.doc, *id)).and_then(|t| t.cache.as_ref()).map(|c| c.content_bounds()).is_some_and(|r| { - let s = f64::from(slop); - !r.is_empty() && x >= f64::from(r.x0) - s && x <= f64::from(r.x1) + s && y >= f64::from(r.y0) - s && y <= f64::from(r.y1) + s - }); - // The hover calls this every frame: skip the layout when the pixels already answer. - if shown { - return true; - } - let Some((l, aff, _)) = layout(app, *id) else { return false }; - let (tx, ty) = to_text(&aff, x, y); - photocraft_text::text_point_inside(&l, tx, ty, slop) - }) -} - -/// True when the layer's pixels are what our engine draws for it. A PSD's type layer keeps -/// Photoshop's pixels until it is edited, and with substituted fonts or a different line layout -/// they sit somewhere else than the glyphs the caret and selection are placed on. -pub(crate) fn shows_own_layout(doc: &Document, t: &TextLayer) -> bool { - let Some(cache) = &t.cache else { return false }; - let mut eng = photocraft_text::shared().lock().unwrap_or_else(PoisonError::into_inner); - let ours = eng.render(t, doc.resolution_dpi, doc.pixel_format()).1.surface.content_bounds(); - let have = cache.content_bounds(); - [(ours.x0, have.x0), (ours.y0, have.y0), (ours.x1, have.x1), (ours.y1, have.y1)].iter().all(|(a, b)| (a - b).abs() <= 1) -} - -/// Start editing an existing type layer. Like Photoshop, editing shows the text as the type -/// engine lays it out, so a PSD layer is re-rendered first (inside the edit session's history -/// step, so Cancel brings Photoshop's pixels back). -fn begin_edit(app: &mut PhotocraftApp, id: LayerId, key: &str) -> Result<(), String> { - let st = app.session.active().ok_or("no document open")?; - let doc = st.doc.clone(); - if let Some(t) = text_layer(&doc, id) - && !shows_own_layout(&doc, t) - { - app.run("type.edit", json!({"layer": id.0, "coalesce": key}))?; - } - Ok(()) -} - -/// Edit the active type layer from its thumbnail, selecting all text like Photoshop. Reuse the -/// current session when already editing it, so Cancel and undo still cover the whole edit. -pub fn edit_active(app: &mut PhotocraftApp) -> Result<(), String> { - let st = app.session.active().ok_or("no document open")?; - let id = st.active_layer.ok_or("no active layer")?; - let n = text_layer(&st.doc, id).ok_or("active layer is not a type layer")?.text.chars().count(); - if app.ui.text_edit.as_ref().is_none_or(|ed| ed.layer != id.0) { - commit(app); - let key = session_key(app); - begin_edit(app, id, &key)?; - app.ui.text_edit = Some(TextEdit { - layer: id.0, - document: active_doc_id(app), - caret: n, - anchor: 0, - session: key, - created: false, - mask: false, - dragging: false, - resize: None, - preedit: None, - }); - } else { - let mut cancelled = false; - if let Some(ed) = app.ui.text_edit.as_mut() { - ed.anchor = 0; - ed.caret = n; - // Re-entering the same session moves the caret away from the composition: cancel it - // rather than reusing a range that no longer describes the text. - cancelled = ed.preedit.take().is_some(); - } - if cancelled { - app.type_ime.clear_preedit(); - interrupt_incoming(app); - app.type_ime.request_interrupt(); - } - } - let vertical = app.session.active().and_then(|st| text_layer(&st.doc, id)).is_some_and(|t| t.orientation == photocraft_doc::text::Orientation::Vertical); - app.ui.text_edit_return_tool = None; - app.ui.tool = if vertical { crate::state::Tool::VerticalType } else { crate::state::Tool::Type }; - app.ui.mask_target = false; - app.ui.vector_mask_target = false; - Ok(()) -} - -/// Double-click with the Move tool (Photoshop CC 2019+): edit the type layer under document -/// point (`x`, `y`) with the caret on the glyph there, switching to the Type tool. False when no -/// type is there. -pub fn edit_at(app: &mut PhotocraftApp, x: f64, y: f64) -> bool { - let Some(id) = hit_layer(app, x, y) else { return false }; - let previous_tool = app.ui.tool; - commit(app); - if app.session.select_layer(id).is_err() { - return false; - } - let key = session_key(app); - if begin_edit(app, id, &key).is_err() { - return false; - } - let off = hit_offset(app, id, x, y); - app.ui.text_edit = Some(TextEdit { - layer: id.0, - document: active_doc_id(app), - caret: off, - anchor: off, - session: key, - created: false, - mask: false, - dragging: false, - resize: None, - preedit: None, - }); - let vertical = app.session.active().and_then(|st| text_layer(&st.doc, id)).is_some_and(|t| t.orientation == photocraft_doc::text::Orientation::Vertical); - if !previous_tool.is_type() { - app.ui.text_edit_return_tool = Some(previous_tool); - } - app.ui.tool = if vertical { crate::state::Tool::VerticalType } else { crate::state::Tool::Type }; - app.ui.mask_target = false; - app.ui.vector_mask_target = false; - true -} - -fn hit_offset(app: &mut PhotocraftApp, id: LayerId, x: f64, y: f64) -> usize { - offset_at(app, id, x, y) -} - -/// The character offset of the caret position nearest document point (`x`, `y`) in layer `id`. -pub(crate) fn offset_at(app: &mut PhotocraftApp, id: LayerId, x: f64, y: f64) -> usize { - let Some((l, aff, text)) = layout(app, id) else { return 0 }; - let (tx, ty) = to_text(&aff, x, y); - // Type on a path: the point's place along the path is the position in the (single) line. - let shape = app.session.active().and_then(|s| text_layer(&s.doc, id).map(|t| t.shape.clone())); - let (tx, ty) = match shape { - Some(photocraft_doc::text::TextShape::Path { path, start, flip }) => { - photocraft_text::warp::arc_length_at(&path, flip, f64::from(tx), f64::from(ty)).map_or((tx, ty), |s| ((s - f64::from(start)) as f32, -1.0)) - } - _ => (tx, ty), - }; - photocraft_text::hit_char(&l, &text, tx, ty).0 -} - fn hex(c: [f32; 4]) -> String { let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; format!("#{:02x}{:02x}{:02x}", b(c[0]), b(c[1]), b(c[2])) } -/// Smallest paragraph box a handle drag leaves, in text-space px. -const MIN_BOX: f32 = 4.0; - -/// Which box edges handle `i` moves: (left, right, top, bottom). The order matches the overlay. -fn handle_sides(i: u8) -> (bool, bool, bool, bool) { - match i { - 0 => (true, false, true, false), - 1 => (false, true, true, false), - 2 => (false, true, false, true), - 3 => (true, false, false, true), - 4 => (false, false, true, false), - 5 => (false, true, false, false), - 6 => (false, false, false, true), - _ => (true, false, false, false), - } -} - -pub(crate) fn box_shape(app: &PhotocraftApp, id: LayerId) -> Option<(f32, f32, f32, f32)> { - match app.session.active().and_then(|s| text_layer(&s.doc, id).map(|t| t.shape.clone()))? { - photocraft_doc::text::TextShape::Box { x, y, width, height } => Some((x, y, width, height)), - _ => None, - } -} - -/// The paragraph-box handle under the document point, if the layer is paragraph text. -pub(crate) fn box_handle_at(app: &mut PhotocraftApp, id: LayerId, x: f64, y: f64) -> Option { - let (bx, by, w, h) = box_shape(app, id)?; - let (_, aff, _) = layout(app, id)?; - let (r, b) = (bx + w, by + h); - let (mx, my) = (bx + w / 2.0, by + h / 2.0); - let spots = [(bx, by), (r, by), (r, b), (bx, b), (mx, by), (r, my), (mx, b), (bx, my)]; - let tol = f64::from(6.0 / app.point_zoom().max(0.01)); - spots - .iter() - .position(|&(sx, sy)| { - let p = aff.apply(Point::new(f64::from(sx), f64::from(sy))); - (p.x - x).abs() <= tol && (p.y - y).abs() <= tol - }) - .map(|i| i as u8) -} - -/// Drag the handle of `r` (the box and transform snapshotted at the press) to the document -/// point: the dragged edges follow it, the others stay put. With ⌥ the opposite edges mirror -/// the drag about the centre the box started with, so the block grows symmetrically instead of -/// from one side — pressing or releasing ⌥ mid-drag switches that on and off as if it had been -/// held from the start. -fn resize_box(app: &mut PhotocraftApp, ed: &TextEdit, r: BoxResize, x: f64, y: f64, alt: bool) { - let (px, py) = to_text(&r.aff, x, y); - let (l, rw, t, b) = handle_sides(r.handle); - let (bx, by, w, h) = (r.shape[0], r.shape[1], r.shape[2], r.shape[3]); - let (mut x0, mut y0, mut x1, mut y1) = (bx, by, bx + w, by + h); - // The centre the ⌥ mirror turns about: the box as it stood at the press (every move - // recomputes from that snapshot, so the centre holds for the whole drag). - let (cx, cy) = (bx + w / 2.0, by + h / 2.0); - if l { - x0 = px.min(x1 - MIN_BOX); - } - if rw { - x1 = px.max(x0 + MIN_BOX); - } - if t { - y0 = py.min(y1 - MIN_BOX); - } - if b { - y1 = py.max(y0 + MIN_BOX); - } - if alt { - // The mirror keeps the centre fixed: the dragged edge clamps at MIN_BOX/2 from it, and - // the opposite edge follows, so the block never inverts below the minimum. - if l { - x0 = px.min(cx - MIN_BOX / 2.0); - x1 = 2.0 * cx - x0; - } - if rw { - x1 = px.max(cx + MIN_BOX / 2.0); - x0 = 2.0 * cx - x1; - } - if t { - y0 = py.min(cy - MIN_BOX / 2.0); - y1 = 2.0 * cy - y0; - } - if b { - y1 = py.max(cy + MIN_BOX / 2.0); - y0 = 2.0 * cy - y1; - } - } - // type.edit places the box's top-left at the given document point. - let o = r.aff.apply(Point::new(f64::from(x0), f64::from(y0))); - let _ = app.run("type.edit", json!({"layer": ed.layer, "box": [o.x, o.y, x1 - x0, y1 - y0], "coalesce": ed.session})); -} - -/// True when document point (`x`, `y`) lies inside the paragraph box of type layer `id` (false -/// for point text). -pub(crate) fn inside_box(app: &mut PhotocraftApp, id: LayerId, x: f64, y: f64) -> bool { - let Some((bx, by, w, h)) = box_shape(app, id) else { return false }; - let Some((_, aff, _)) = layout(app, id) else { return false }; - let (tx, ty) = to_text(&aff, x, y); - tx >= bx && tx <= bx + w && ty >= by && ty <= by + h -} - -/// Pointer down with the Type tool. Returns true when the press was consumed (no box drag). -pub fn pointer_down(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) -> bool { - if let Some(ed) = app.ui.text_edit.clone() { - let id = LayerId(ed.layer); - if let Some(i) = box_handle_at(app, id, x, y) { - // Snapshot the box and transform now: every move recomputes from them, so ⌥ held - // or released mid-drag mirrors about the centre the drag started with. - let snap = box_shape(app, id).zip(layout(app, id)).map(|((bx, by, w, h), (_, aff, _))| BoxResize { handle: i, shape: [bx, by, w, h], aff }); - if let (Some(snap), Some(e)) = (snap, app.ui.text_edit.as_mut()) { - e.resize = Some(snap); - } - return true; - } - // Photoshop: anywhere inside the paragraph box places the caret, even off the glyphs - // (left of a line's start, below the last line); only a click outside it commits. - if hit_layer(app, x, y) == Some(id) || inside_box(app, id, x, y) { - let off = hit_offset(app, id, x, y); - if let Some(e) = app.ui.text_edit.as_mut() { - e.caret = off; - if !mods.shift { - e.anchor = off; - } - e.dragging = true; - } - return true; - } - // ⇧/⌥ on that click combine a Type Mask with the selection. - commit_with(app, mods); - return true; // Photoshop: a click outside commits without starting new text - } - // The Type Mask tools always start new text: existing type layers are just pixels to them; - // so does a ⇧-click with the Type tool, as in Photoshop, to start new text over old. - if app.ui.tool.is_type_mask() || mods.shift { - return false; - } - if let Some(id) = hit_layer(app, x, y) { - let _ = app.session.select_layer(id); - let key = session_key(app); - if begin_edit(app, id, &key).is_err() { - return true; - } - let off = hit_offset(app, id, x, y); - app.ui.text_edit = Some(TextEdit { - layer: id.0, - document: active_doc_id(app), - caret: off, - anchor: off, - session: key, - created: false, - mask: false, - dragging: true, - resize: None, - preedit: None, - }); - app.ui.text_edit_return_tool = None; - return true; - } - false -} - -pub fn pointer_move(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { - let Some(ed) = app.ui.text_edit.clone() else { return }; - if let Some(r) = ed.resize { - resize_box(app, &ed, r, x, y, mods.alt); - return; - } - if ed.dragging { - let off = hit_offset(app, LayerId(ed.layer), x, y); - if let Some(e) = app.ui.text_edit.as_mut() { - e.caret = off; - } - } -} - -/// What a Type tool click on a path does, like Photoshop: inside a closed path, area type; -/// on a path's outline, type on the path from that point. -#[derive(Clone, Debug, PartialEq)] -pub(crate) enum PathClick { - Area { shape: Option }, - OnPath { shape: Option, subpath: usize, start: f64 }, -} - -/// Arc length (px) along `sub` from its first anchor to segment `seg` at curve parameter `t`. -fn arc_length_to(sub: &photocraft_doc::Subpath, seg: usize, t: f64) -> f64 { - const PIECES: usize = 32; - let eval = photocraft_vector::edit::eval; - let length = |s: &[Point; 4], upto: f64| { - (1..=PIECES) - .fold((0.0, eval(s, 0.0)), |(len, prev), j| { - let q = eval(s, upto * j as f64 / PIECES as f64); - (len + (q.x - prev.x).hypot(q.y - prev.y), q) - }) - .0 - }; - let segs = sub.segments(); - let whole: f64 = segs.iter().take(seg).map(|s| length(s, 1.0)).sum(); - whole + segs.get(seg).map_or(0.0, |s| length(s, t.clamp(0.0, 1.0))) -} - -/// The path a Type tool click at document `(x, y)` would use: on the outline (within 6 screen px) -/// of the active shape layer's path, else of the work path, type on that path; inside a closed -/// one, area type. The work path's inside counts only while the canvas draws it (selected in the -/// Paths panel, #6551): a hidden Work Path left after Load as Selection must not turn a plain -/// click into area type. None while View › Show › Target Path (or Extras) hides paths. -pub(crate) fn path_target(app: &PhotocraftApp, x: f64, y: f64) -> Option { - use photocraft_vector::edit::{Hit, hit}; - if !app.ui.view.shows(app.ui.view.show.target_path) { - return None; - } - let shape_path = crate::vector_ui::active_shape_path(app); - let work = app.session.active().and_then(|s| s.doc.work_path.clone()); - let work_shown = app.ui.selected_path.as_deref() == Some("work"); - // The canvas hover runs this every frame and `hit` samples every segment, so a path with more - // anchors than this is not a click target (the click and the pointer agree: plain point - // text). 4096 anchors is far beyond hand-drawn paths and shapes yet keeps a frame cheap, and - // it is the most `type.fillPath` accepts, so every area click target can be filled. - const MAX_TARGET_KNOTS: usize = photocraft_text::area::MAX_AREA_KNOTS; - let small = |path: &photocraft_doc::vector::Path| path.subpaths.iter().map(|s| s.knots.len()).fold(0usize, usize::saturating_add) <= MAX_TARGET_KNOTS; - let tol = 6.0 / app.point_zoom().max(0.01) as f64; - // Only the horizontal Type tool starts type on a path: vertical type on a path is not laid - // out yet. - let vertical = app.ui.tool.is_vertical_type(); - let outline = |path: &photocraft_doc::vector::Path, shape: Option| { - let on_path = |sp: usize, k: usize, t: f64| { - // Type on a path needs a segment to run along (`type.attachToPath` rejects one anchor). - let sub = path.subpaths.get(sp).filter(|s| !vertical && s.knots.len() >= 2)?; - Some(PathClick::OnPath { shape, subpath: sp, start: arc_length_to(sub, k, t) }) - }; - match hit(path, Point::new(x, y), tol, &[]) { - Some(Hit::Segment([sp, k], t)) => on_path(sp, k, t), - Some(Hit::Anchor([sp, k])) => on_path(sp, k, 0.0), - _ => None, - } - }; - let inside = |path: &photocraft_doc::vector::Path| photocraft_text::area::AreaShape::new(path, false).is_some_and(|a| a.contains(x as f32, y as f32)); - if let Some((id, p)) = shape_path.as_ref().filter(|(_, p)| small(p)) { - if let Some(c) = outline(p, Some(*id)) { - return Some(c); - } - if inside(p) { - return Some(PathClick::Area { shape: Some(*id) }); - } - } - let w = work.as_ref().filter(|w| small(w))?; - if let Some(c) = outline(w, None) { - return Some(c); - } - (work_shown && inside(w)).then_some(PathClick::Area { shape: None }) -} - -/// What the Type tool's pointer over document `(x, y)` shows (#218): the path click a press there -/// would make, unless the press edits the type layer under it instead (`pointer_down`: an -/// unshifted press on shown type), where Photoshop keeps the plain I-beam. The type hit is only -/// tested over a path, so a hover elsewhere lays out nothing. Nothing while a type edit is open -/// (a click then commits rather than starting new type). While the button is held it is what the -/// release makes (`pointer_up`): nothing once the drag is a text box, else the path click at the -/// press. -pub(crate) fn hover_path_target(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) -> Option { - if app.ui.text_edit.is_some() { - return None; - } - if let Some(start) = app.drag.as_ref().map(|d| d.start) { - // The press already passed over editing type (`pointer_down`), so no type hit test. - return if makes_box(app, start, [x, y]) { None } else { path_target(app, start[0], start[1]) }; - } - let target = path_target(app, x, y)?; - (shift || hit_layer(app, x, y).is_none()).then_some(target) -} - -/// Whether a press at `start` released at `end` drags out a paragraph box rather than clicking -/// (at least 4 screen pixels both ways). -fn makes_box(app: &PhotocraftApp, start: [f64; 2], end: [f64; 2]) -> bool { - let (w, h) = ((end[0] - start[0]).abs(), (end[1] - start[1]).abs()); - let min = 4.0 / app.point_zoom().max(0.01) as f64; - w >= min && h >= min -} - -/// Pointer up. `rect` is the dragged box (document px) when no edit session consumed the press. -pub fn pointer_up(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) { - if let Some(e) = app.ui.text_edit.as_mut() { - e.dragging = false; - e.resize = None; - app.ui.caret_blink_time = app.last_frame_time; - return; - } - let (w, h) = ((end[0] - start[0]).abs(), (end[1] - start[1]).abs()); - let min = 4.0 / app.point_zoom().max(0.01) as f64; - let o = app.ui.tool_options.clone(); - let mask = app.ui.tool.is_type_mask(); - // A click (not a drag) with the Type tool on a path: area type inside a closed path, type - // on the path on its outline. The Type Mask tools ignore paths. - let target = if !mask && !makes_box(app, start, end) { path_target(app, start[0], start[1]) } else { None }; - // Preferences ▸ Type: "Fill new type layers with placeholder text" (on by default). The Type - // Mask tools start empty, as Photoshop's do. - let text = if !mask && app.session.prefs().type_.fill_new_type_layers_with_placeholder { PLACEHOLDER } else { "" }; - let mut p = default_style_params(app); - p["text"] = json!(text); - p["orientation"] = json!(if app.ui.tool.is_vertical_type() { "vertical" } else { "horizontal" }); - if w >= min && h >= min { - p["box"] = json!([start[0].min(end[0]).round(), start[1].min(end[1]).round(), w.round(), h.round()]); - } else { - p["x"] = json!(start[0].round()); - p["y"] = json!(start[1].round()); - } - let key = session_key(app); - p["coalesce"] = json!(key); - if let Ok(v) = app.run("type.create", p) - && let Some(id) = v.get("layer").and_then(serde_json::Value::as_u64) - { - // A failed follow-up leaves point text; say why instead of passing over it. - let follow_up = match &target { - Some(PathClick::Area { shape }) => app.run("type.fillPath", json!({"layer": id, "shape": shape, "coalesce": key})), - Some(PathClick::OnPath { shape, subpath, start }) => { - app.run("type.attachToPath", json!({"layer": id, "shape": shape, "subpath": subpath, "start": start, "coalesce": key})) - } - None => Ok(serde_json::Value::Null), - }; - if let Err(e) = follow_up { - app.ui.status = e; - app.ui.status_error = true; - } - if o.type_aa != "sharp" { - let _ = app.run("type.edit", json!({"layer": id, "antialias": o.type_aa, "coalesce": key})); - } - // A Type Mask's text is a hidden working layer: the canvas shows the mask overlay - // instead, and committing turns it into the selection. - if mask { - let _ = app.run("layer.setProps", json!({"layer": id, "visible": false, "coalesce": key})); - } - // Like Photoshop: the placeholder is selected, so typing replaces it. - let n = text.chars().count(); - app.ui.caret_blink_time = app.last_frame_time; - app.ui.text_edit = Some(TextEdit { - layer: id, - document: active_doc_id(app), - caret: n, - anchor: 0, - session: key, - created: true, - mask, - dragging: false, - resize: None, - preedit: None, - }); - app.ui.text_edit_return_tool = None; - } -} - fn session_key(app: &mut PhotocraftApp) -> String { format!("type-{}", app.ui.alloc_id()) } @@ -1291,2818 +120,12 @@ pub(crate) fn selected_range(app: &PhotocraftApp) -> Option<[usize; 2]> { (a < b).then_some([a, b]) } -/// Copy the selected characters to the system clipboard. Returns the copied range. Shared by the -/// clipboard Copy event and Edit > Copy during a type edit. -pub(crate) fn copy_selection(app: &PhotocraftApp, ctx: &egui::Context) -> Option<[usize; 2]> { - let [a, b] = selected_range(app)?; - let ed = app.ui.text_edit.as_ref()?; - let text = text_layer(&app.session.active()?.doc, LayerId(ed.layer))?; - ctx.copy_text(text.text.chars().skip(a).take(b - a).collect()); - Some([a, b]) -} - -/// Edit > Paste during a type edit: ask the window for the clipboard text, which arrives as a -/// Paste event next frame and replaces the selection there (like ⌘V). -pub(crate) fn request_paste(ctx: &egui::Context) { - ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste); -} - -/// Select > All during a type edit selects every character (like ⌘A). -pub(crate) fn select_all(app: &mut PhotocraftApp) { - let Some(n) = app.ui.text_edit.as_ref().and_then(|ed| current_text(app, LayerId(ed.layer))).map(|t| t.chars().count()) else { return }; - if let Some(e) = app.ui.text_edit.as_mut() { - (e.anchor, e.caret) = (0, n); - } -} - -/// Shared by the clipboard Cut event and Edit > Cut during a type edit. -pub(crate) fn cut_selection(app: &mut PhotocraftApp, ctx: &egui::Context) { - let Some([a, b]) = copy_selection(app, ctx) else { return }; - if let Some(ed) = app.ui.text_edit.as_mut() { - ed.anchor = a; - ed.caret = b; - } - insert(app, ""); -} - -/// Replace the selection with `s`. -fn insert(app: &mut PhotocraftApp, s: &str) { - let Some(ed) = app.ui.text_edit.clone() else { return }; - let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor)); - let s = s.replace("\r\n", "\n").replace('\r', "\n"); - if a == b && s.is_empty() { - return; - } - crate::type_transform::finish(app); - let applied = app.run("type.edit", json!({"layer": ed.layer, "replace": {"start": a, "end": b, "text": s}, "coalesce": ed.session})).is_ok(); - if applied { - let mut cancelled = false; - if let Some(e) = app.ui.text_edit.as_mut() { - e.caret = a + s.chars().count(); - e.anchor = e.caret; - // An application edit invalidates a live composition: its recorded range no longer - // describes the text, and its pending native commit must not be applied here. - cancelled = e.preedit.take().is_some(); - } - if cancelled { - app.type_ime.clear_preedit(); - interrupt_incoming(app); - app.type_ime.request_interrupt(); - } - // Ordinary typing, paste, cut and deletion are application-origin, never IME receipts. - note_ime_application_change(app, &ed); - } -} - -/// Typed text (not a paste): with Preferences ▸ Type ▸ Use Smart Quotes, straight quotes become -/// typographic (Photoshop does not rewrite pasted text). -fn insert_typed(app: &mut PhotocraftApp, s: &str) { - if !app.session.prefs().type_.smart_quotes { - return insert(app, s); - } - let prev = app.ui.text_edit.clone().and_then(|ed| { - let at = ed.caret.min(ed.anchor); - let text = current_text(app, LayerId(ed.layer))?; - (at > 0).then(|| text.chars().nth(at - 1)).flatten() - }); - insert(app, &smart_quotes(s, prev)); -} - -/// Straight quotes become “ ” and ‘ ’: opening after whitespace, a bracket or a dash (or at the -/// start of the text), closing next to a letter or another quote. `prev` is the character before -/// the caret. -fn smart_quotes(s: &str, mut prev: Option) -> String { - let mut out = String::with_capacity(s.len()); - for c in s.chars() { - let c = match c { - '"' => { - if opens_quote(prev) { - '\u{201c}' - } else { - '\u{201d}' - } - } - '\'' => { - if opens_quote(prev) { - '\u{2018}' - } else { - '\u{2019}' - } - } - _ => c, - }; - out.push(c); - prev = Some(c); - } - out -} - -fn opens_quote(prev: Option) -> bool { - prev.is_none_or(|p| p.is_whitespace() || matches!(p, '(' | '[' | '{' | '-' | '\u{2013}' | '\u{2014}')) -} - -/// Alt+←/→: kern the pair before the caret by `by` (1/1000 em). No pair (caret at a text or line -/// edge): nothing happens, like Photoshop. Not coalesced: one history step per press. -fn kern_pair(app: &mut PhotocraftApp, id: LayerId, caret: usize, by: f32) { - let Some(text) = current_text(app, id) else { return }; - let before = caret.checked_sub(1).and_then(|i| text.chars().nth(i)); - let after = text.chars().nth(caret); - if before.is_none_or(|c| c == '\n') || after.is_none_or(|c| c == '\n') { - return; - } - crate::type_transform::finish(app); - let _ = app.run("type.edit", json!({"layer": id.0, "kernPair": {"at": caret, "by": by}})); -} - -/// A character style the type editor's ⇧⌘ keys toggle (Photoshop: ⇧⌘K All Caps, ⇧⌘U -/// Underline, ⇧⌘B Faux Bold, ⇧⌘I Faux Italic, ⇧⌘/ Strikethrough). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum CharToggle { - AllCaps, - Underline, - FauxBold, - FauxItalic, - Strikethrough, -} - -impl CharToggle { - fn is_on(self, st: &photocraft_doc::text::CharStyle) -> bool { - match self { - Self::AllCaps => st.caps == photocraft_doc::text::Caps::AllCaps, - Self::Underline => st.underline, - Self::FauxBold => st.faux_bold, - Self::FauxItalic => st.faux_italic, - Self::Strikethrough => st.strikethrough, - } - } - - fn param(self, on: bool) -> (&'static str, serde_json::Value) { - match self { - Self::AllCaps => ("caps", json!(if on { "all" } else { "normal" })), - Self::Underline => ("underline", json!(on)), - Self::FauxBold => ("fauxBold", json!(on)), - Self::FauxItalic => ("fauxItalic", json!(on)), - Self::Strikethrough => ("strikethrough", json!(on)), - } - } -} - /// The byte range of characters `a..b` of `text`. fn byte_range(text: &str, a: usize, b: usize) -> (usize, usize) { let at = |c: usize| text.char_indices().nth(c).map_or(text.len(), |(i, _)| i); (at(a.min(b)), at(a.max(b))) } -/// The character styles of the selection, or of the typing style when the text is empty. Empty -/// when nothing is selected in non-empty text. -fn selected_styles(t: &TextLayer, a: usize, b: usize) -> Vec { - let runs = t.char_runs(); - if t.text.is_empty() { - return runs.into_iter().take(1).map(|r| r.style).collect(); - } - let (ba, bb) = byte_range(&t.text, a, b); - let mut at = 0usize; - let mut out = Vec::new(); - for r in runs { - let (rs, re) = (at, at.saturating_add(r.len)); - at = re; - if rs < bb && re > ba { - out.push(r.style); - } - } - out -} - -/// The character range the type editor's formatting keys act on: the selection, or the empty -/// text's typing style. `None` for a collapsed caret in non-empty text: Photoshop would style the -/// next characters typed, which the document model can't hold apart from the text, so the keys -/// do nothing there (rather than restyle a word the user didn't select). -fn format_range(app: &PhotocraftApp, ed: &TextEdit) -> Option<(usize, usize)> { - let t = text_layer(&app.session.active()?.doc, LayerId(ed.layer))?; - let n = t.text.chars().count(); - let (a, b) = (ed.caret.min(ed.anchor).min(n), ed.caret.max(ed.anchor).min(n)); - (a < b || n == 0).then_some((a, b)) -} - -/// One `type.setStyle` step on the edited layer's `range`, kept apart from the typing session's -/// coalesced edit so Undo takes back one key press at a time (as with kerning). -fn set_style(app: &mut PhotocraftApp, ed: &TextEdit, range: (usize, usize), mut p: serde_json::Value) { - crate::type_transform::finish(app); - p["layer"] = json!(ed.layer); - p["range"] = json!([range.0, range.1]); - if let Err(e) = app.run("type.setStyle", p) { - app.ui.status = e; - app.ui.status_error = true; - } -} - -/// ⇧⌘K/U/B/I/: flips a character style over the selection: off when every selected character -/// already has it, else on. -pub(crate) fn toggle_char_style(app: &mut PhotocraftApp, which: CharToggle) { - let Some(ed) = app.ui.text_edit.clone() else { return }; - let Some(range) = format_range(app, &ed) else { return }; - let Some(styles) = app.session.active().and_then(|s| text_layer(&s.doc, LayerId(ed.layer))).map(|t| selected_styles(t, range.0, range.1)) else { - return; - }; - let on = !styles.iter().all(|st| which.is_on(st)); - let (key, value) = which.param(on); - set_style(app, &ed, range, json!({ key: value })); -} - -/// ⌥↑/↓ leading, ⇧⌥↑/↓ baseline shift and ⌥←/→ tracking: steps every selected character from its -/// own value (`key` is `leadingBy`, `baselineShiftBy` or `trackingBy`). -pub(crate) fn step_char_metric(app: &mut PhotocraftApp, key: &str, by: f32) { - let Some(ed) = app.ui.text_edit.clone() else { return }; - let Some(range) = format_range(app, &ed) else { return }; - // Leading steps in the points the Character panel shows for a scaled layer. - set_style(app, &ed, range, json!({ key: by, "metricsAsShown": key == "leadingBy" })); -} - -/// ⌥⇧⌘H: flips Hyphenate for the paragraphs the selection (or the caret) is in: off when all of -/// them hyphenate, else on. -pub(crate) fn toggle_hyphenate(app: &mut PhotocraftApp) { - let Some(ed) = app.ui.text_edit.clone() else { return }; - let Some(t) = app.session.active().and_then(|s| text_layer(&s.doc, LayerId(ed.layer))) else { return }; - let n = t.text.chars().count(); - let (a, b) = (ed.caret.min(ed.anchor).min(n), ed.caret.max(ed.anchor).min(n)); - let (ba, bb) = byte_range(&t.text, a, b); - let len = t.text.len(); - let mut at = 0usize; - let mut all = true; - let mut any = false; - for r in t.paragraph_runs() { - let (ps, pe) = (at, at.saturating_add(r.len)); - at = pe; - let touches = if ba == bb { ps <= ba && (ba < pe || pe >= len) } else { ps < bb && pe > ba }; - if touches { - any = true; - all &= r.style.hyphenate; - } - } - let on = !(any && all); - set_style(app, &ed, (a, b), json!({ "hyphenate": on })); -} - -/// IME composition. The preedit text is written into the layer (so it lays out and reflows like -/// typed text) and replaced by every update; `commit` makes the result final. -fn ime_update(app: &mut PhotocraftApp, s: &str, commit: bool) { - let Some(ed) = app.ui.text_edit.clone() else { return }; - // Validate the composition only while one exists: a plain preedit/commit otherwise needs no - // copy of the whole layer. - let n = if ed.preedit.is_some() { - let Some(text) = current_text(app, LayerId(ed.layer)) else { return }; - // A composition range that no longer holds the recorded composition belongs to an edit - // that was replaced under it: never use it to delete or replace text. - if reconcile_preedit(app, &ed, &text) { - return; - } - text.chars().count() - } else { - let Some(n) = text_char_count(app, LayerId(ed.layer)) else { return }; - n - }; - let s = s.replace("\r\n", "\n").replace('\r', "\n"); - // An empty preedit or commit while nothing is being composed changes nothing. Wayland input - // methods send one on every state change (the caret rectangle moving as a selection grows), - // and it used to replace the selection, deleting the text as it was selected (#1381). - if s.is_empty() && ed.preedit.is_none() { - return; - } - let (start, end) = match ed.preedit { - Some((p, l)) if p.saturating_add(l) <= n => (p, p + l), - _ => (ed.caret.min(ed.anchor).min(n), ed.caret.max(ed.anchor).min(n)), - }; - if start == end && s.is_empty() { - if let Some(e) = app.ui.text_edit.as_mut() { - e.preedit = None; - } - app.type_ime.clear_preedit(); - return; - } - // Capture the committed text *before* the engine runs. The pre-edit is excluded from this - // and from the after snapshot; only an accepted commit earns an IME receipt. - let before = if commit { ime_committed(app, &ed) } else { None }; - let len = s.chars().count(); - crate::type_transform::finish(app); - if app.run("type.edit", json!({"layer": ed.layer, "replace": {"start": start, "end": end, "text": s}, "coalesce": ed.session})).is_err() { - return; - } - let mut after_ed = ed.clone(); - after_ed.caret = start + len; - after_ed.anchor = after_ed.caret; - after_ed.preedit = if commit || len == 0 { None } else { Some((start, len)) }; - if let Some(e) = app.ui.text_edit.as_mut() { - *e = after_ed.clone(); - } - if after_ed.preedit.is_some() { - app.type_ime.note_preedit(&after_ed, &s); - } else { - app.type_ime.clear_preedit(); - } - if commit { - app.type_ime.incoming = None; - } else { - remember_incoming(app, Some(s.is_empty())); - } - if commit - && let Some(before) = before - && let Some(after) = ime_committed(app, &after_ed) - { - // A no-op commit (equal snapshots) is rejected by the tracker rather than fabricated. - note_ime_apply(app, &after_ed, &before, &after); - } -} - -/// The active range for an IME delete-surrounding batch: the pre-edit when composing, otherwise -/// the sorted selection. Returns `(start, end, length)` in character indices. -fn ime_active_range(app: &PhotocraftApp, ed: &TextEdit) -> Option<(usize, usize, usize)> { - let n = text_char_count(app, LayerId(ed.layer))?; - if let Some((start, len)) = ed.preedit { - let end = start.checked_add(len)?; - return (end <= n).then_some((start, end, n)); - } - let a = ed.caret.min(n); - let b = ed.anchor.min(n); - Some((a.min(b), a.max(b), n)) -} - -/// Delete characters around the selection/pre-edit, as one coalesced type edit. -fn ime_delete_chars(app: &mut PhotocraftApp, before_chars: usize, after_chars: usize) -> bool { - let Some(ed) = app.ui.text_edit.clone() else { return false }; - if ed.preedit.is_some() { - let Some(text) = current_text(app, LayerId(ed.layer)) else { return false }; - if reconcile_preedit(app, &ed, &text) { - return false; - } - } - let Some((start, end, n)) = ime_active_range(app, &ed) else { return false }; - let from = start.saturating_sub(before_chars); - let to = end.saturating_add(after_chars).min(n); - ime_delete_around(app, ed, from, start, end, to) -} - -/// `DeleteSurroundingBytes` counts UTF-8 bytes from the active range's edges. A byte count that -/// ends inside a character leaves that character, as the stock TextEdit does. -fn ime_delete_bytes(app: &mut PhotocraftApp, before_bytes: usize, after_bytes: usize) -> bool { - let Some(ed) = app.ui.text_edit.clone() else { return false }; - let Some(text) = current_text(app, LayerId(ed.layer)) else { return false }; - if reconcile_preedit(app, &ed, &text) { - return false; - } - let Some((start, end, n)) = ime_active_range(app, &ed) else { return false }; - let start_byte = byte_of(&text, start); - let end_byte = byte_of(&text, end); - let from_byte = start_byte.saturating_sub(before_bytes); - let before_chars = text.get(..start_byte).map_or(0, |before| before.char_indices().rev().take_while(|(index, _)| *index >= from_byte).count()); - let after_chars = - text.get(end_byte..).map_or(0, |after| after.char_indices().take_while(|(index, character)| index + character.len_utf8() <= after_bytes).count()); - let from = start.saturating_sub(before_chars); - let to = end.saturating_add(after_chars).min(n); - ime_delete_around(app, ed, from, start, end, to) -} - -/// Apply one accepted IME deletion and record its receipt from the snapshots around it. -/// -/// The active selection/pre-edit itself stays; only the requested runs before `start` and after -/// `end` are removed. They are two engine mutations with the same coalescing key (one history -/// step), and one receipt covers the whole batch. -fn ime_delete_around(app: &mut PhotocraftApp, ed: TextEdit, from: usize, start: usize, end: usize, to: usize) -> bool { - if from >= start && end >= to { - return false; - } - let before = ime_committed(app, &ed); - crate::type_transform::finish(app); - // Delete the trailing run first so the leading run's character indices stay valid. - if end < to && app.run("type.edit", json!({"layer": ed.layer, "replace": {"start": end, "end": to, "text": ""}, "coalesce": ed.session})).is_err() { - return false; - } - if from < start && app.run("type.edit", json!({"layer": ed.layer, "replace": {"start": from, "end": start, "text": ""}, "coalesce": ed.session})).is_err() { - return false; - } - let shift = start - from; - let mut after_ed = ed.clone(); - after_ed.caret = ed.caret.saturating_sub(shift); - after_ed.anchor = ed.anchor.saturating_sub(shift); - if let Some((preedit_start, preedit_len)) = ed.preedit { - after_ed.preedit = Some((preedit_start.saturating_sub(shift), preedit_len)); - } - if let Some(e) = app.ui.text_edit.as_mut() { - *e = after_ed.clone(); - } - if let (Some(before), Some(after)) = (before, ime_committed(app, &after_ed)) { - note_ime_apply(app, &after_ed, &before, &after); - } - remember_incoming(app, None); - true -} - -/// Character index of the previous / next word boundary (shared with `type.navigate`). -fn word_boundary(text: &str, from: usize, forward: bool) -> usize { - photocraft_text::word_boundary(text, from, forward) -} - -/// Most clicks in a run that select more: 2 a word, 3 a line, 4 a paragraph, 5 all text. The -/// next quick click starts over with a caret. -const MAX_CLICKS: u32 = 5; - -/// Count of this click in a run of clicks at one spot. `egui_count` is egui's own count for the -/// click (1 single, 2 double, 3 triple; it never goes past 3), which already applies the -/// double-click delay and distance; `prev` is our count for the previous click (0: none). A slow -/// or distant click (egui says 1) starts a new run; after five clicks the run starts over. -pub(crate) fn next_click_count(prev: u32, egui_count: u32) -> u32 { - match (egui_count, prev) { - (0 | 1, _) => 1, - (n, 0) => n.min(MAX_CLICKS), - (_, p) => p % MAX_CLICKS + 1, - } -} - -/// The selection (anchor, caret) a run of `count` clicks makes at character `caret`: 1 a caret, -/// 2 the word under it, 3 its visual line as laid out (a column in vertical type), 4 its -/// paragraph up to the hard return, 5 all text. `line` is the laid-out line the click hit; it -/// decides at a soft wrap, where one caret offset ends a line and starts the next. Without a -/// layout a line is its paragraph. Offsets past the text are clamped, so an empty layer or a -/// stale caret never panics. -pub(crate) fn click_selection(layout: Option<&TextLayout>, text: &str, caret: usize, line: Option, count: u32) -> (usize, usize) { - let n = text.chars().count(); - let c = caret.min(n); - match count { - 2 => { - let chars: Vec = text.chars().collect(); - let word = |i: usize| chars.get(i).is_some_and(|ch| ch.is_alphanumeric()); - let (mut a, mut b) = (c, c); - while a > 0 && word(a - 1) { - a -= 1; - } - while word(b) { - b += 1; - } - (a, b) - } - 3 => { - let Some(l) = layout else { return paragraph_of(text, c) }; - let ln = line.and_then(|i| l.lines.get(i)).or_else(|| l.lines.get(photocraft_text::line_index(l, byte_of(text, c)))); - ln.map_or((c, c), |ln| (photocraft_text::char_index(text, ln.range.start), photocraft_text::char_index(text, ln.range.end))) - } - 4 => paragraph_of(text, c), - 5 => (0, n), - _ => (c, c), - } -} - -/// Characters of the paragraph holding character `c`, without its hard return. -fn paragraph_of(text: &str, c: usize) -> (usize, usize) { - let b = byte_of(text, c); - let paras = photocraft_text::layout::split_paragraphs(text); - let Some(r) = paras.iter().find(|r| b >= r.start && b < r.end).or_else(|| paras.last()) else { return (c, c) }; - let body = text.get(r.clone()).unwrap_or("").trim_end_matches(['\r', '\n']); - let start = photocraft_text::char_index(text, r.start); - (start, start + body.chars().count()) -} - -/// A click while editing type at document point (`x`, `y`), after it placed the caret there. -/// `egui_count` is egui's count for the click (see [`next_click_count`]). Like Photoshop, two -/// clicks select a word, three the line, four the paragraph and five all text. -pub fn multi_click(app: &mut PhotocraftApp, egui_count: u32, x: f64, y: f64) { - let Some(ed) = app.ui.text_edit.clone() else { - app.type_clicks = None; - return; - }; - let prev = app.type_clicks.filter(|(layer, _)| *layer == ed.layer).map_or(0, |(_, n)| n); - let count = next_click_count(prev, egui_count); - app.type_clicks = Some((ed.layer, count)); - if count < 2 { - return; - } - let id = LayerId(ed.layer); - let Some(text) = current_text(app, id) else { return }; - let laid = layout(app, id); - let (caret, line) = match &laid { - Some((l, aff, t)) if *t == text && x.is_finite() && y.is_finite() => { - let (tx, ty) = to_text(aff, x, y); - let (ci, line) = photocraft_text::hit_char(l, t, tx, ty); - (ci, Some(line)) - } - _ => (ed.caret, None), - }; - let (a, b) = click_selection(laid.as_ref().map(|(l, _, _)| l.as_ref()), &text, caret, line, count); - if let Some(e) = app.ui.text_edit.as_mut() { - (e.anchor, e.caret) = (a, b); - } -} - -/// Caret on the neighbouring line (±1; a column in vertical type), keeping the position -/// along the line. Works in line space, so it serves both orientations. -fn line_step(app: &mut PhotocraftApp, id: LayerId, caret: usize, dir: i32) -> usize { - let Some((l, _, text)) = layout(app, id) else { return caret }; - let x = l.caret(byte_of(&text, caret)).0; - photocraft_text::line_step(&l, &text, caret, x, dir) -} - -fn is_vertical(app: &PhotocraftApp, id: LayerId) -> bool { - app.session.active().and_then(|s| text_layer(&s.doc, id)).is_some_and(|t| t.orientation == photocraft_doc::text::Orientation::Vertical) -} - -/// Arrow keys follow the text flow: in vertical type ↑/↓ move along the column (previous/next -/// character) and ←/→ move to the next/previous column (columns advance right to left). Returns -/// the horizontal-type key with the same meaning. -pub(crate) fn flow_key(key: egui::Key, vertical: bool) -> egui::Key { - use egui::Key; - if !vertical { - return key; - } - match key { - Key::ArrowUp => Key::ArrowLeft, - Key::ArrowDown => Key::ArrowRight, - Key::ArrowLeft => Key::ArrowDown, - Key::ArrowRight => Key::ArrowUp, - k => k, - } -} - -/// Line start / end for the caret's line. -fn line_edge(app: &mut PhotocraftApp, id: LayerId, caret: usize, end: bool) -> usize { - let Some((l, _, text)) = layout(app, id) else { return caret }; - photocraft_text::line_edge(&l, &text, caret, end) -} - -/// Keyboard input while editing. Returns true when a type edit session is active (single-key -/// tool shortcuts must then be skipped). Handled events are removed from the frame's input. -pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { - bind_reset_context(app, ctx); - // A receipt is only valid for the frame that produced it; never reuse last frame's. - app.type_ime.frame = None; - end_if_left(app); - sync_incoming(app, ctx.viewport_id()); - if !ctx.input(|i| i.focused) || ctx.text_edit_focused() || ctx.egui_wants_keyboard_input() { - interrupt_incoming(app); - } - crate::type_transform::cancel_stale(app); - if !ctx.input(|i| i.focused) { - crate::type_transform::cancel_drag(app); - } - let Some(ed) = app.ui.text_edit.clone() else { - controls_only(app, ctx); - return false; - }; - // The font picker (and other focused fields) owns keyboard input while it is open. - if !reset_route_eligible(app, ctx) { - controls_only(app, ctx); - return true; - } - let id = LayerId(ed.layer); - let Some(n) = text_char_count(app, id) else { - app.ui.text_edit = None; - app.ui.text_edit_return_tool = None; - app.type_ime.clear_preedit(); - controls_only(app, ctx); - return false; - }; - // Undo/redo can shorten the text under us. - if let Some(e) = app.ui.text_edit.as_mut() { - e.caret = e.caret.min(n); - e.anchor = e.anchor.min(n); - } - if !claim_raw_pass(app, ctx) { - return true; - } - app.type_ime.begin_frame(ctx); - prepare_reset(app, ctx); - // A target swap (session replacement, Type Mask, another layer) is known from the last - // descriptor the platform received. Cancel the native composition before any event in this - // pass can be applied to the new target. - if ime_target(app, &ed, ctx.viewport_id()).is_some_and(|target| app.type_ime.emitted.is_some_and(|last| last.target != target)) { - app.type_ime.interrupt = true; - } - let time = ctx.input(|i| i.time); - let elapsed = (time - app.ui.caret_blink_time).max(0.0); - let period = 0.530; - let remaining = period - (elapsed % period); - ctx.request_repaint_after(std::time::Duration::from_secs_f64(remaining.clamp(0.010, period))); - let events = ctx.input(|i| i.events.clone()); - let vertical_flow = is_vertical(app, id); - let mut handled = vec![false; events.len()]; - let mut primary_down = events - .iter() - .find_map(|event| match event { - egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed, .. } => Some(!pressed), - _ => None, - }) - .unwrap_or_else(|| ctx.input(|input| input.pointer.primary_down())); - let mut custom_mutations = true; - let mut deferred_custom = false; - for (k, ev) in events.iter().enumerate() { - if custom_mutations && !reset_route_eligible(app, ctx) { - custom_mutations = false; - suspend_reset(app, ctx); - } - if !custom_mutations { - if let egui::Event::ImeResetCompleted { request_id } = ev { - complete_reset(app, ctx, *request_id); - if let Some(slot) = handled.get_mut(k) { - *slot = true; - } - } else if deferred_custom - && matches!(ev, egui::Event::Text(_) | egui::Event::Paste(_) | egui::Event::Cut | egui::Event::Ime(_)) - && let Some(slot) = handled.get_mut(k) - { - *slot = true; - } - continue; - } - prepare_reset(app, ctx); - let Some(ed) = app.ui.text_edit.clone() else { continue }; - let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor)); - // Only key handling needs the text (word/line edges); pointer, clipboard and IME events - // do not clone the whole layer. - let is_key = matches!(ev, egui::Event::Key { .. }); - let text = if is_key { current_text(app, id).unwrap_or_default() } else { String::new() }; - let n = if is_key { text.chars().count() } else { 0 }; - let set = |app: &mut PhotocraftApp, caret: usize, extend: bool| { - if let Some(e) = app.ui.text_edit.as_mut() { - e.caret = caret.min(n); - if !extend { - e.anchor = e.caret; - } - } - }; - handled[k] = true; - match ev { - egui::Event::Text(s) => insert_typed(app, s), - egui::Event::Paste(s) => insert(app, s), - egui::Event::ImeResetCompleted { request_id } => complete_reset(app, ctx, *request_id), - egui::Event::Ime(ime_event) => { - // Untagged terminal payload cannot acknowledge a host reset. Only the exact - // current completion arm above may open admission for the following element. - if reset_guarded(app, ctx.viewport_id()) { - continue; - } - match ime_event { - // A bare line break from the IME is the Enter key, which the key arm handles. - egui::ImeEvent::Preedit { text: s, .. } | egui::ImeEvent::Commit(s) if s == "\n" || s == "\r" => handled[k] = false, - egui::ImeEvent::Preedit { text, .. } => ime_update(app, text, false), - egui::ImeEvent::Commit(s) => { - ime_update(app, s, true); - app.type_ime.incoming = None; - } - egui::ImeEvent::DeleteSurrounding { before_chars, after_chars } => { - ime_delete_chars(app, *before_chars, *after_chars); - } - egui::ImeEvent::DeleteSurroundingBytes { before_bytes, after_bytes } => { - ime_delete_bytes(app, *before_bytes, *after_bytes); - } - _ => {} - } - } - egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed, .. } => { - primary_down = *pressed; - if *pressed { - // The canvas destination handler runs after this pass; never apply a - // same-batch Text/Paste/Cut/IME suffix at the old caret just because no - // composition or reset guard existed yet. - interrupt_action(app, ctx.viewport_id()); - custom_mutations = false; - deferred_custom = true; - suspend_reset(app, ctx); - } - handled[k] = false; - } - egui::Event::PointerMoved(_) if primary_down => { - interrupt_action(app, ctx.viewport_id()); - custom_mutations = false; - deferred_custom = true; - suspend_reset(app, ctx); - handled[k] = false; - } - egui::Event::Copy => { - copy_selection(app, ctx); - } - egui::Event::Cut => cut_selection(app, ctx), - egui::Event::Key { key, pressed: true, modifiers: m, .. } => { - use egui::Key; - let key = &flow_key(*key, vertical_flow); - match key { - // Photoshop's type formatting keys act on the selected characters and win - // over the global ⇧⌘K/U/B/I (Color Settings, Desaturate, Auto Color, Inverse) - // while typing. Each press is one history step. - Key::K | Key::U | Key::B | Key::I | Key::Slash | Key::Questionmark if m.command && m.shift && !m.alt => { - let which = match key { - Key::K => CharToggle::AllCaps, - Key::U => CharToggle::Underline, - Key::B => CharToggle::FauxBold, - Key::I => CharToggle::FauxItalic, - _ => CharToggle::Strikethrough, - }; - toggle_char_style(app, which); - } - Key::H if m.command && m.shift && m.alt => toggle_hyphenate(app), - // ⌥↑/↓ leading -/+2 pt, ⇧⌥↑/↓ baseline shift +/-2 pt (10 with ⌘/Ctrl). - Key::ArrowUp | Key::ArrowDown if m.alt => { - let step = if m.command { 10.0 } else { 2.0 }; - let up = *key == Key::ArrowUp; - if m.shift { - step_char_metric(app, "baselineShiftBy", if up { step } else { -step }); - } else { - step_char_metric(app, "leadingBy", if up { -step } else { step }); - } - } - // ⌥←/→ over a selection tracks it by -/+20 (100 with ⌘/Ctrl). - Key::ArrowLeft | Key::ArrowRight if m.alt && !m.shift && a != b => { - let step = if m.command { 100.0 } else { 20.0 }; - step_char_metric(app, "trackingBy", if *key == Key::ArrowRight { step } else { -step }); - } - Key::Backspace | Key::Delete => { - if a == b { - let fwd = *key == Key::Delete; - let to = match (fwd, m.alt, m.command) { - (false, _, true) => line_edge(app, id, a, false), - (false, true, _) => word_boundary(&text, a, false), - (false, _, _) => a.saturating_sub(1), - (true, true, _) => word_boundary(&text, a, true), - (true, _, _) => (a + 1).min(n), - }; - if to != a { - if let Some(e) = app.ui.text_edit.as_mut() { - e.anchor = to; - } - insert(app, ""); - } - } else { - insert(app, ""); - } - } - // Photoshop: Alt/Option+←/→ at a collapsed caret kerns the pair before it by - // 20/1000 em (100 with ⌘/Ctrl), one history step per press. - Key::ArrowLeft | Key::ArrowRight if m.alt && !m.shift && a == b => { - let step = if m.command { 100.0 } else { 20.0 }; - kern_pair(app, id, ed.caret, if *key == Key::ArrowRight { step } else { -step }); - } - Key::ArrowLeft | Key::ArrowRight => { - let fwd = *key == Key::ArrowRight; - // Word movement: ⌘/Ctrl (Photoshop's; Alt is kerning), and Alt+Shift - // extends the selection by words; Home/End go to the line edges. - let to = if m.command || m.alt { - word_boundary(&text, ed.caret, fwd) - } else if a != b && !m.shift { - if fwd { b } else { a } - } else if fwd { - ed.caret + 1 - } else { - ed.caret.saturating_sub(1) - }; - set(app, to, m.shift); - } - Key::ArrowUp | Key::ArrowDown => { - let to = if m.command { - if *key == Key::ArrowUp { 0 } else { n } - } else { - line_step(app, id, ed.caret, if *key == Key::ArrowUp { -1 } else { 1 }) - }; - set(app, to, m.shift); - } - Key::Home | Key::End => { - let to = line_edge(app, id, ed.caret, *key == Key::End); - set(app, to, m.shift); - } - Key::Enter if m.command => commit_with(app, *m), - Key::Enter => insert(app, "\n"), - // Photoshop types a tab character; layout advances it to the next tab stop. - Key::Tab if !m.command && !m.alt && !m.shift => { - // egui queues focus navigation before this handler runs; consuming the - // key alone would let the menu bar take focus after the first tab (#8889). - ctx.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); - insert(app, "\t"); - } - Key::Escape if crate::type_transform::active(app) => crate::type_transform::cancel_drag(app), - // The Type Mask tools: Escape always cancels, leaving the selection as it was. - Key::Escape if ed.mask => cancel(app), - // Preferences ▸ Type: with "Use Escape to Commit" off, Escape cancels the - // session (undoes it, removing a just-created layer) like the Cancel button. - Key::Escape if app.session.prefs().type_.use_esc_to_commit => commit(app), - Key::Escape => cancel(app), - Key::A if m.command => { - if let Some(e) = app.ui.text_edit.as_mut() { - e.anchor = 0; - e.caret = n; - } - } - // Photoshop: while editing type, ⌘/Ctrl+T shows or hides the Character panel - // (Free Transform of the layer being typed into is not what it means here). - Key::T if m.command && !m.shift && !m.alt => { - let _ = crate::menus::invoke(app, ctx, "window.panel.character", json!({})); - } - // Other command shortcuts (⌘Z, ⌘S, …) pass through to the menus. - _ if m.command => { - if *key == Key::Z { - crate::type_transform::cancel_drag(app); - } - if reset_guarded(app, ctx.viewport_id()) || app.type_ime.incoming.is_some() { - interrupt_action(app, ctx.viewport_id()); - custom_mutations = false; - deferred_custom = true; - suspend_reset(app, ctx); - } - handled[k] = false; - } - _ => {} - } - } - egui::Event::Key { pressed: false, modifiers: m, .. } => handled[k] = !m.command, - _ => handled[k] = false, - } - } - prepare_reset(app, ctx); - if handled.iter().any(|h| *h) { - app.ui.caret_blink_time = ctx.input(|i| i.time); - let mut k = 0; - ctx.input_mut(|i| { - i.events.retain(|_| { - let keep = !handled.get(k).copied().unwrap_or(false); - k += 1; - keep - }) - }); - } - app.ui.text_edit.is_some() -} - -/// End the editing session. A new layer left empty is deleted; a new layer is named after its text. -pub fn commit(app: &mut PhotocraftApp) { - commit_with(app, egui::Modifiers::NONE); -} - -/// [`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) { - 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); - }; - 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); - if let Some(i) = current { - app.session.set_active(i); - } - } - Some(_) => commit_here(app, mods), - // Its document closed: there is nothing to commit into, and the layer id may name a - // layer of another document. - None => { - crate::type_transform::reset(app); - app.ui.text_edit = None; - app.ui.text_edit_return_tool = None; - app.type_ime.clear_preedit(); - } - } -} - -/// Index of the document an edit belongs to; `None` once it is closed. -fn edit_home(app: &PhotocraftApp, ed: &TextEdit) -> Option { - match ed.document { - Some(d) => app.session.documents().iter().position(|st| st.doc.id.0 == d), - None => app.session.active_index(), - } -} - -/// [`commit_with`] in the active document, which is the edit's own. -fn commit_here(app: &mut PhotocraftApp, mods: egui::Modifiers) { - if app.ui.tool.is_type() { - crate::type_transform::finish(app); - } - crate::type_transform::reset(app); - let Some(ed) = app.ui.text_edit.take() else { return }; - app.type_ime.clear_preedit(); - if let Some(tool) = app.ui.text_edit_return_tool.take() - && app.ui.tool.is_type() - { - app.ui.tool = tool; - } - 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); - if !text.trim().is_empty() - && let Err(e) = app.run("type.createSelection", json!({"layer": ed.layer, "removeLayer": true, "operation": operation, "coalesce": ed.session})) - { - app.ui.status = e; - app.ui.status_error = true; - } - if current_text(app, LayerId(ed.layer)).is_some() { - undo_session(app, &ed); - } - return; - } - if text.trim().is_empty() && ed.created { - let _ = app.run("layer.delete", json!({"layer": ed.layer})); - } else if ed.created { - let name = photocraft_engine::type_cmds::layer_name(&text); - let _ = app.run("type.edit", json!({"layer": ed.layer, "name": name, "coalesce": ed.session})); - } -} - -/// Commit the edit once its layer is no longer the one worked on (#6483): another layer became -/// active (a Layers panel menu, the canvas layer picker, automation) or another document did (a -/// tab, File ▸ New/Open). Photoshop commits then; left open, the session took single-key -/// shortcuts as typing and typed into whichever document was active. -pub fn end_if_left(app: &mut PhotocraftApp) { - let Some(ed) = app.ui.text_edit.as_ref() else { return }; - let layer = LayerId(ed.layer); - if edit_home(app, ed).is_none_or(|h| Some(h) != app.session.active_index()) { - return commit(app); - } - let Some(st) = app.session.active() else { return }; - if st.active_layer == Some(layer) { - return; - } - // The selection just made stands: ending an empty Type Mask undoes its session, and undo - // restores the selection from before it. - let chosen = (st.active_layer, st.selected_layers.clone(), st.layer_anchor); - commit(app); - let moved = app.session.active().is_some_and(|st| (st.active_layer, &st.selected_layers, st.layer_anchor) != (chosen.0, &chosen.1, chosen.2)); - if moved { - let _ = app.session.restore_layer_selection(chosen.0, &chosen.1, chosen.2); - } -} - -/// Selection highlight, caret and text frame over the canvas. -pub fn draw_overlay(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { - let Some(ed) = app.ui.text_edit.clone() else { return }; - // Until it commits, an edit in a document no longer active draws nothing over this one. - if edit_home(app, &ed) != app.session.active_index() { - return; - } - if ed.dragging { - app.ui.caret_blink_time = painter.ctx().input(|i| i.time); - } - let id = LayerId(ed.layer); - let Some((l, aff, text)) = layout(app, id) else { return }; - if ed.mask { - draw_mask_overlay(app, painter, xf, id); - } - let t = crate::theme::Tokens::get(painter.ctx()); - // Text space → screen. - let scr_t = |x: f32, y: f32| -> Pos2 { - let p = aff.apply(Point::new(x as f64, y as f64)); - xf.to_screen(p.x as f32, p.y as f32) - }; - let shape = app.session.active().and_then(|s| text_layer(&s.doc, id).map(|t| t.shape.clone())); - // Type on a path: the caret, selection and underline follow the curve the glyphs sit on. - let bend = shape.as_ref().and_then(photocraft_text::warp::Warp::on_path); - // Line space (lines, clusters, carets) → screen: vertical type turns it 90° clockwise. - let scr = |x: f32, y: f32| -> Pos2 { - let (x, y) = l.to_text(x, y); - match &bend { - Some(w) => { - let (x, y) = w.apply(f64::from(x), f64::from(y)); - scr_t(x as f32, y as f32) - } - None => scr_t(x, y), - } - }; - // A line-space run from `x0` to `x1` at height `y`: sampled, so it bends with path type. - let run = |x0: f32, x1: f32, y: f32| -> Vec { - let n = if bend.is_some() { ((x1 - x0) / 4.0).ceil().clamp(1.0, 512.0) as usize } else { 1 }; - (0..=n).map(|i| scr(x0 + (x1 - x0) * i as f32 / n as f32, y)).collect() - }; - // The IME descriptor is emitted once at pass end by `sync_ime`, from this pass's canvas - // mapping and the model as it stands after every panel has run. - let pass_nr = painter.ctx().cumulative_pass_nr_for(painter.ctx().viewport_id()); - app.type_ime.note_view(painter.ctx().viewport_id(), pass_nr, xf); - // Frame: paragraph text shows its box with handles; point text an underline per line. - let mods = crate::workspace_ui::sticky_mods(app, painter.ctx().input(|i| i.modifiers)); - let has_transform = crate::type_transform::draw(app, painter, xf, mods); - let frame = Stroke::new(1.0, t.accent); - match shape { - Some(photocraft_doc::text::TextShape::Box { x, y, width, height }) => { - if !has_transform { - let c = [scr_t(x, y), scr_t(x + width, y), scr_t(x + width, y + height), scr_t(x, y + height)]; - painter.add(egui::Shape::closed_line(c.to_vec(), frame)); - let mids = [c[0].lerp(c[1], 0.5), c[1].lerp(c[2], 0.5), c[2].lerp(c[3], 0.5), c[3].lerp(c[0], 0.5)]; - for p in c.iter().chain(mids.iter()) { - let r = egui::Rect::from_center_size(*p, egui::vec2(7.0, 7.0)); - painter.rect_filled(r, 0.0, Color32::WHITE); - painter.rect_stroke(r, 0.0, frame, egui::StrokeKind::Inside); - } - } - } - // Area type: the outline of the shape it wraps inside. - Some(photocraft_doc::text::TextShape::Area { path }) => { - if !has_transform { - for poly in photocraft_vector::flatten::flatten_path(&path, 0.5) { - let pts: Vec = poly.pts.iter().map(|&(x, y)| scr_t(x as f32, y as f32)).collect(); - if pts.len() >= 2 { - painter.add(egui::Shape::closed_line(pts, frame)); - } - } - } - } - _ => { - for ln in &l.lines { - // Horizontal: just under the baseline; vertical: the column's centre line. - let y = if l.vertical { ln.baseline } else { ln.baseline + ln.descent * 0.25 }; - painter.add(egui::Shape::line(run(ln.x0.min(0.0), ln.x1.max(ln.x0 + 1.0), y), Stroke::new(1.0, t.accent.gamma_multiply(0.8)))); - } - } - } - // Uncommitted IME text is underlined, but only while the stored range still holds exactly - // the composition: an application edit may have shifted it onto committed characters. - if let Some(offsets) = ime_offsets(&text, &ed) - && ime_preedit_is_current(app, &text, &ed, &offsets) - && let Some((a, b)) = offsets.preedit.map(|range| (range.start, range.end)) - { - for (li, ln) in l.lines.iter().enumerate() { - let xs: Vec<(f32, f32)> = - l.clusters.iter().filter(|c| c.line == li && c.range.start >= a && c.range.end <= b).map(|c| (c.x, c.x + c.advance)).collect(); - let (x0, x1) = xs.iter().fold((f32::MAX, f32::MIN), |(lo, hi), (p, q)| (lo.min(*p), hi.max(*q))); - if x0 < x1 { - let y = ln.baseline + ln.descent * 0.5; - painter.add(egui::Shape::line(run(x0, x1, y), Stroke::new(1.5, t.accent))); - } - } - } - // Selection: per line, the clusters inside [a, b). - let (a, b) = (byte_of(&text, ed.caret.min(ed.anchor)), byte_of(&text, ed.caret.max(ed.anchor))); - if a < b { - let fill = Color32::from_rgba_unmultiplied(t.accent.r(), t.accent.g(), t.accent.b(), 110); - for (li, ln) in l.lines.iter().enumerate() { - let xs: Vec<(f32, f32)> = - l.clusters.iter().filter(|c| c.line == li && c.range.start >= a && c.range.end <= b).map(|c| (c.x, c.x + c.advance)).collect(); - let (mut x0, mut x1) = xs.iter().fold((f32::MAX, f32::MIN), |(lo, hi), (p, q)| (lo.min(*p), hi.max(*q))); - // A selected line break shows as a small sliver past the line end. - if b > ln.range.end && a <= ln.range.end { - x1 = x1.max(ln.x1 + (ln.ascent + ln.descent) * 0.25); - x0 = x0.min(ln.x1); - } - let (top, bot) = (ln.baseline - ln.ascent, ln.baseline + ln.descent); - if bend.is_some() { - // On a path each glyph turns on its own, so each gets its own highlight. - // Glyphs past the end of the path are not drawn, so neither is their highlight. - let shown = |p: f32, q: f32| bend.as_ref().is_some_and(|w| w.place_glyph(f64::from(p + q) / 2.0) != photocraft_text::warp::Placement::Hidden); - for (p, q) in xs.into_iter().filter(|&(p, q)| shown(p, q)) { - painter.add(egui::Shape::convex_polygon(vec![scr(p, top), scr(q, top), scr(q, bot), scr(p, bot)], fill, Stroke::NONE)); - } - } else if x0 < x1 { - painter.add(egui::Shape::convex_polygon(vec![scr(x0, top), scr(x1, top), scr(x1, bot), scr(x0, bot)], fill, Stroke::NONE)); - } - } - } else { - // Blinking caret (Photoshop's ~0.53 s rhythm), solid while dragging or immediately after interaction. - let time = painter.ctx().input(|i| i.time); - let elapsed = (time - app.ui.caret_blink_time).max(0.0); - if ed.dragging || (elapsed * 1000.0 / 530.0) as i64 % 2 == 0 { - let (x, top, bot) = l.caret(a); - let (x, top, bot) = if l.lines.is_empty() { (0.0, -(12.0 * l.px_per_pt.max(1.0)), 3.0) } else { (x, top, bot) }; - for stroke in CARET_STROKES { - painter.line_segment([scr(x, top), scr(x, bot)], stroke); - } - } - } -} - -/// The text caret, drawn in order: a white halo, then a solid black line inside it, so it reads on -/// any background (#6085). The black line used to be a 0.75 pt hairline inside a white one, which -/// on a white background left only a faint grey line. -const CARET_STROKES: [Stroke; 2] = [Stroke { width: 3.0, color: Color32::WHITE }, Stroke { width: 1.0, color: Color32::BLACK }]; - -/// The Type Mask tools while typing: Quick Mask's colour over the canvas with the glyphs clear, -/// as Photoshop shows the selection-to-be. The glyphs come from the hidden working layer's pixels. -fn draw_mask_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, id: LayerId) { - let Some(st) = app.session.active() else { return }; - let canvas = st.doc.bounds(); - let opts = app.session.quick_mask_options; - let rgb = opts.color.to_rgb(); - let tint = |a: f32| { - let a = (a * opts.opacity).clamp(0.0, 1.0); - let q = |v: f32| (v.clamp(0.0, 1.0) * a * 255.0 + 0.5) as u8; - Color32::from_rgba_premultiplied(q(rgb[0]), q(rgb[1]), q(rgb[2]), (a * 255.0 + 0.5) as u8) - }; - let corners = |r: photocraft_geom::Rect| -> Vec { - let (x0, y0, x1, y1) = (r.x0 as f32, r.y0 as f32, r.x1 as f32, r.y1 as f32); - vec![xf.to_screen(x0, y0), xf.to_screen(x1, y0), xf.to_screen(x1, y1), xf.to_screen(x0, y1)] - }; - let surface = text_layer(&st.doc, id).and_then(|t| t.cache.as_ref()); - let area = surface.map(|s| s.content_bounds().intersect(&canvas)).unwrap_or(photocraft_geom::Rect::EMPTY); - // One unfeathered mesh, so the bands and the text's box meet without seams. - let mut bands = egui::Mesh::default(); - let mut band = |x0: i32, y0: i32, x1: i32, y1: i32| { - let r = photocraft_geom::Rect { x0, y0, x1, y1 }; - if !r.is_empty() { - let base = bands.vertices.len() as u32; - for p in corners(r) { - bands.colored_vertex(p, tint(1.0)); - } - bands.indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]); - } - }; - let Some(surface) = surface.filter(|_| !area.is_empty()) else { - band(canvas.x0, canvas.y0, canvas.x1, canvas.y1); - painter.add(egui::Shape::mesh(bands)); - return; - }; - band(canvas.x0, canvas.y0, canvas.x1, area.y0); - band(canvas.x0, area.y1, canvas.x1, canvas.y1); - band(canvas.x0, area.y0, area.x0, area.y1); - band(area.x1, area.y0, canvas.x1, area.y1); - painter.add(egui::Shape::mesh(bands)); - // The text's box: a texture of the tint where there is no glyph, cached per revision. - let ctx = painter.ctx(); - let key = (st.doc.id.0, st.revision, id.0); - let cache = egui::Id::unique("pc-type-mask-overlay"); - let tex = ctx.data(|d| d.get_temp::<((u64, u64, u64), egui::TextureHandle)>(cache)).filter(|(k, _)| *k == key).map(|(_, t)| t); - let tex = tex.unwrap_or_else(|| { - let max = (ctx.input(|i| i.max_texture_side) as u32).clamp(256, 4096); - let factor = area.width().max(area.height()).div_ceil(max).max(1); - let (w, h) = (area.width().div_ceil(factor) as usize, area.height().div_ceil(factor) as usize); - let mut row = vec![[0.0f32; 4]; area.width() as usize]; - let mut px = Vec::with_capacity(w * h); - for y in (area.y0..area.y1).step_by(factor as usize) { - surface.read_rgba_into(photocraft_geom::Rect { x0: area.x0, y0: y, x1: area.x1, y1: y + 1 }, &mut row); - px.extend(row.iter().step_by(factor as usize).take(w).map(|p| tint(1.0 - p[3]))); - } - px.resize(w * h, tint(1.0)); - let img = egui::ColorImage::new([w, h], px); - let t = ctx.load_texture("type-mask-overlay", img, egui::TextureOptions::LINEAR); - ctx.data_mut(|d| d.insert_temp(cache, (key, t.clone()))); - t - }); - let c = corners(area); - let mut mesh = egui::Mesh::with_texture(tex.id()); - for (p, uv) in c.iter().zip([egui::pos2(0.0, 0.0), egui::pos2(1.0, 0.0), egui::pos2(1.0, 1.0), egui::pos2(0.0, 1.0)]) { - mesh.vertices.push(egui::epaint::Vertex { pos: *p, uv, color: Color32::WHITE }); - } - mesh.indices.extend([0, 1, 2, 0, 2, 3]); - painter.add(egui::Shape::mesh(mesh)); -} - -/// Font families: bundled, system, and those the host serves (`photocraft_text::served`, fetched -/// when picked). Cached until the shared engine registers fonts or the served catalog changes. -pub fn families() -> Arc> { - type Cached = Option<((u64, u64), Arc>)>; - static FAMILIES: std::sync::Mutex = std::sync::Mutex::new(None); - let key = (photocraft_text::fonts::shared_generation(), photocraft_text::served::generation()); - let mut cached = FAMILIES.lock().unwrap_or_else(PoisonError::into_inner); - if let Some((k, v)) = cached.as_ref() - && *k == key - { - return v.clone(); - } - let mut v = photocraft_text::shared().lock().map(|mut e| e.fonts.families()).unwrap_or_default(); - for f in photocraft_text::served::families() { - if !v.contains(&f) { - v.push(f); - } - } - v.sort_by_key(|s| s.to_lowercase()); - let v = Arc::new(v); - *cached = Some((key, v.clone())); - v -} - -/// Where [`sync_font_names`] leaves the font menus' localized labels for this frame. -fn font_labels_id() -> egui::Id { - egui::Id::unique("photocraft-font-menu-localized-names") -} - -/// Preferences ▸ Type ▸ Show Font Names in English: when off, font menus list a family that has a -/// localized (native-language) name by that name, as Photoshop does ("MS Gothic" reads -/// "MS ゴシック"). Called once a frame; the menus read the labels from the context. -pub fn sync_font_names(ctx: &egui::Context, show_in_english: bool) { - let labels = (!show_in_english).then(localized_families); - ctx.data_mut(|d| { - if let Some(labels) = labels { - d.insert_temp(font_labels_id(), labels); - } else { - d.remove::>>(font_labels_id()); - } - }); -} - -/// The fonts' localized family names, keyed by family. Cached until the shared engine registers fonts. -fn localized_families() -> Arc> { - type Cached = Option<(u64, Arc>)>; - static LOCALIZED: std::sync::Mutex = std::sync::Mutex::new(None); - let key = photocraft_text::fonts::shared_generation(); - let mut cached = LOCALIZED.lock().unwrap_or_else(PoisonError::into_inner); - if let Some((k, v)) = cached.as_ref() - && *k == key - { - return v.clone(); - } - let v = Arc::new(photocraft_text::shared().lock().map(|mut e| e.fonts.localized_family_names()).unwrap_or_default()); - *cached = Some((key, v.clone())); - v -} - -/// The font menu's rows: each family with the label it shows (its localized name when `labels` -/// has one, else the family), matching `query` (lowercase) by either name. With localized labels -/// the rows sort by label, so the menu stays alphabetical as shown. As in Photoshop, recently -/// used families also head the menu in their own group, most recent first (Preferences ▸ Type ▸ -/// Recent Fonts), and keep their alphabetical place below it; a query shows each match once. -/// Returns the rows and how many of them form the recent group. -fn font_menu_rows<'a>( - families: &'a [String], - labels: Option<&'a HashMap>, - query: &str, - recents: &[String], -) -> (Vec<(&'a String, &'a str)>, usize) { - let label = |f: &'a String| labels.and_then(|l| l.get(f)).map_or(f.as_str(), String::as_str); - let mut rows: Vec<(&String, &str)> = families - .iter() - .map(|f| (f, label(f))) - .filter(|(f, l)| query.is_empty() || f.to_lowercase().contains(query) || l.to_lowercase().contains(query)) - .collect(); - if labels.is_some_and(|l| !l.is_empty()) { - rows.sort_by_cached_key(|(_, l)| l.to_lowercase()); - } - if !query.is_empty() { - return (rows, 0); - } - let recent: Vec<(&String, &str)> = recents.iter().filter_map(|r| rows.iter().find(|(f, _)| *f == r).copied()).collect(); - let n = recent.len(); - (recent.into_iter().chain(rows).collect(), n) -} - -fn weight_name(w: f32) -> &'static str { - match w.round() as i32 { - ..=150 => "Thin", - 151..=250 => "ExtraLight", - 251..=350 => "Light", - 351..=450 => "Regular", - 451..=550 => "Medium", - 551..=650 => "SemiBold", - 651..=750 => "Bold", - 751..=850 => "ExtraBold", - _ => "Black", - } -} - -/// Style names available for a family: each face's actual OpenType subfamily (including numeric -/// and nonstandard ones), plus the standard weights a variable face's `wght` axis covers. -pub fn styles(family: &str) -> Vec { - let faces = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).fonts.faces(family); - let v = style_names(&faces); - if v.is_empty() { vec!["Regular".into()] } else { v } -} - -/// [`styles`] of these faces, lightest first. A variable face reports only its default instance -/// (Montserrat's is Thin), yet the layout draws any weight its `wght` axis covers, so the standard -/// weights in that range are listed too. -fn style_names(faces: &[photocraft_text::FaceInfo]) -> Vec { - let label = |weight: f32, italic: bool| { - let name = match (weight_name(weight), italic) { - ("Regular", true) => "Italic".to_string(), - (w, true) => format!("{w} Italic"), - (w, false) => w.to_string(), - }; - (weight.round() as i32, italic, name) - }; - let mut v: Vec<(i32, bool, String)> = faces.iter().map(|f| (f.weight.round() as i32, f.italic, f.style.clone())).collect(); - for f in faces { - if let Some((_, min, _, max)) = f.axes.iter().find(|a| a.0 == "wght") { - v.extend((100..=900).step_by(100).map(|w| w as f32).filter(|w| (*min..=*max).contains(w)).map(|w| label(w, f.italic))); - } - } - v.sort(); - let mut names: Vec = Vec::new(); - for (_, _, name) in v { - if !names.contains(&name) { - names.push(name); - } - } - names -} - -/// A variable-font axis: (tag, min, default, max), as [`photocraft_text::FaceInfo::axes`]. -pub(crate) type Axis = (String, f32, f32, f32); - -/// The axes the Character section shows as sliders (#2985): those of the faces matching the -/// style's italic, else of any face. Optical size has none: it follows the type size. -pub(crate) fn slider_axes(faces: &[photocraft_text::FaceInfo], italic: bool) -> Vec { - let pick = |want: Option| { - let mut v: Vec = Vec::new(); - for f in faces.iter().filter(|f| want.is_none_or(|w| f.italic == w)) { - for a in &f.axes { - let usable = a.0 != "opsz" && a.1.is_finite() && a.3.is_finite() && a.1 < a.3; - if usable && !v.iter().any(|b| b.0 == a.0) { - v.push(a.clone()); - } - } - } - v - }; - let v = pick(Some(italic)); - if v.is_empty() { pick(None) } else { v } -} - -/// The value an axis slider shows: the style's own value for the axis, else what the layout -/// draws (the style's weight on `wght`, the axis default otherwise), within the axis range. -pub(crate) fn axis_value(c: &photocraft_doc::text::CharStyle, (tag, min, default, max): &Axis) -> f32 { - let v = c.variations.iter().find(|v| &v.axis == tag).map(|v| v.value).unwrap_or_else(|| match tag.as_str() { - "wght" => f32::from(c.weight), - "ital" if c.italic => *max, - _ => *default, - }); - let d = default.clamp(*min, *max); - if v.is_finite() { v.clamp(*min, *max) } else { d } -} - -/// Slider label for an axis: the registered axes by name, others by their tag (as the font -/// names them in its `fvar` table, e.g. `GRAD`). -fn axis_label(tag: &str) -> String { - match tag { - "wght" => tl!("Weight").to_string(), - "wdth" => tl!("Width").to_string(), - "slnt" => tl!("Slant").to_string(), - "ital" => tl!("Italic").to_string(), - _ => tag.to_string(), - } -} - -/// One slider row per variable-font axis of the style's font, below the font style (#2985). -fn axis_sliders(app: &mut PhotocraftApp, ui: &mut egui::Ui, c: &photocraft_doc::text::CharStyle) { - // Drawn every frame: no sliders until the background font scan is done (#3021). - let Some(engine) = photocraft_text::try_shared() else { return }; - let axes = { - let faces = engine.lock().unwrap_or_else(PoisonError::into_inner).fonts.faces(&c.font_family); - slider_axes(&faces, c.italic) - }; - let t = crate::theme::Tokens::get(ui.ctx()); - for axis in &axes { - let (min, max) = (axis.1, axis.3); - let mut v = axis_value(c, axis); - let mut changed = false; - ui.push_id(("type-axis", &axis.0), |ui| { - ui.horizontal(|ui| { - let axis_name = axis_label(&axis.0); - ui.label(egui::RichText::new(&axis_name).color(t.text_dim)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - changed |= crate::widgets::value_field(ui, &mut v, min..=max, "", 74.0).accessible_name(axis_name).changed(); - }); - }); - changed |= crate::widgets::slider(ui, &mut v, min..=max, None).changed(); - }); - ui.add_space(crate::theme::ROW_GAP); - if changed { - // Whole units on wide axes (weight 100–900), hundredths on narrow ones (ital 0–1). - let v = if max - min >= 10.0 { v.round() } else { (v * 100.0).round() / 100.0 }; - let mut m = serde_json::Map::new(); - m.insert(axis.0.clone(), json!(v)); - apply(app, ui.ctx(), json!({ "variations": m })); - } - } -} - -/// PSD text can identify a face only by its PostScript name. Show its real subfamily too. -pub(crate) fn selected_style(style: &photocraft_doc::text::CharStyle) -> String { - // Drawn every frame: while the font scan runs, the stored style name stands in. - if let Some(ps) = &style.postscript_name - && let Some(engine) = photocraft_text::try_shared() - { - let faces = engine.lock().unwrap_or_else(|e| e.into_inner()).fonts.faces(&style.font_family); - if let Some(face) = faces.into_iter().find(|f| f.postscript_name.as_ref() == Some(ps)) { - return face.style; - } - } - if style.font_style.is_empty() { if style.italic { "Italic".into() } else { "Regular".into() } } else { style.font_style.clone() } -} - -/// Localized style label for the dropdown. The raw string stays the engine's `fontStyle` key; -/// the words (weights and "Italic") are translated in the `fontWeight` context, where "Light" -/// means a weight — unlike the Camera Raw "Light" section. -pub fn style_label(style: &str) -> String { - style.split(' ').map(|w| crate::i18n::tr_ctx(crate::i18n::current(), "fontWeight", w)).collect::>().join(" ") -} - -/// Starts scanning the installed fonts on a background thread (desktop start-up), so choosing -/// the Type tool doesn't stall the UI while they are read (#3021). Does nothing on the web. -pub fn warm_fonts() { - photocraft_text::warm_shared(); -} - -/// Whether the font database is ready. The installed fonts are scanned on a background thread -/// from launch (`photocraft_text::warm_shared`); until that finishes, font menus draw this -/// disabled "Loading fonts…" box `width` wide instead of blocking the UI, and a repaint picks the -/// menus up once the scan is done. -pub(crate) fn fonts_ready(ui: &mut egui::Ui, width: f32) -> bool { - if photocraft_text::try_shared().is_some() { - return true; - } - let label = tl!("Loading fonts…").to_string(); - ui.add_enabled_ui(false, |ui| crate::widgets::dropdown(ui, "fonts-loading", tl!("Font"), &mut label.clone(), &[(label.clone(), label.as_str())], width)); - ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); - false -} - -/// Searchable font-family combo box. -fn font_picker(ui: &mut egui::Ui, current: &mut String, width: f32, preview: photocraft_engine::prefs::FontPreview, recents: &[String]) -> bool { - family_picker_in(ui, "type-font", current, width, &families(), preview, recents) -} - -/// Maximum height of the font menu. -const FONT_MENU_HEIGHT: f32 = 460.0; - -/// [`font_picker`] over a given family list (tests pass their own). -#[cfg(test)] -fn font_picker_in( - ui: &mut egui::Ui, - current: &mut String, - width: f32, - families: &[String], - preview: photocraft_engine::prefs::FontPreview, - recents: &[String], -) -> bool { - family_picker_in(ui, "type-font", current, width, families, preview, recents) -} - -/// Shared by the Type options, Character, style and Glyphs panels. Selection changes still -/// flow through each caller's existing engine command. -pub(crate) fn family_picker_in( - ui: &mut egui::Ui, - salt: &str, - current: &mut String, - width: f32, - families: &[String], - preview: photocraft_engine::prefs::FontPreview, - recents: &[String], -) -> bool { - let mut changed = false; - // A font picked from the open menu (click or Enter): the field keeps the focus afterwards. - let mut picked = false; - let search_id = ui.scope_id().with(("font-search", salt)); - let focus_id = search_id.with("focus"); - let recents_id = search_id.with("recents"); - let row_id = search_id.with("row"); - // The list opens on the press, so a press-drag-release picks a font too (#2735). - let (press, close) = crate::press_menu::PressCombo::before(ui, salt); - let labels: Option>> = ui.ctx().data(|d| d.get_temp(font_labels_id())); - let labels = labels.as_deref(); - let shown = labels.and_then(|l| l.get(current.as_str())).unwrap_or(current).clone(); - let combo = egui::ComboBox::from_id_salt(salt) - .selected_text(shown) - .width(width) - .height(FONT_MENU_HEIGHT) - .icon(crate::widgets::chevron_icon) - // Clicks inside the menu (the search field, the scroll bar) must not close it (#1369); - // picking a font closes it explicitly below. - .close_behavior(if matches!(close, egui::PopupCloseBehavior::IgnoreClicks) { close } else { egui::PopupCloseBehavior::CloseOnClickOutside }); - - let mut response = combo.show_ui(ui, |ui| { - let height_id = search_id.with("height"); - // Each opening focuses the search, including a reopen on the very next pass. Keep - // asking through the invisible sizing pass, until the field receives focus. - let mut focus = ui.data(|d| d.get_temp(focus_id)).unwrap_or(true); - let mut q: String = ui.data(|d| d.get_temp(search_id)).unwrap_or_default(); - // Consume these before TextEdit and the canvas can interpret them as caret movement. - let down = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown)); - let up = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp)); - let enter = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); - if focus { - ui.memory_mut(|m| m.request_focus(search_id.with("input"))); - } - let r = ui.add(egui::TextEdit::singleline(&mut q).id(search_id.with("input")).hint_text(tl!("Search fonts")).desired_width(200.0)); - if focus { - // The opening click can release after several focused frames. Keep the request - // pending through that release, which can hand focus back to the combo button. - focus = !r.has_focus() || ui.input(|i| i.pointer.primary_down() || i.pointer.primary_released()); - } - ui.data_mut(|d| { - d.insert_temp(focus_id, focus); - d.insert_temp(search_id, q.clone()); - }); - let ql = q.to_lowercase(); - // The recent group stays as it was when the menu opened: each arrow step applies (and so - // records) a family, and moving it to the top would send the next step back up. - let opening = ui.data(|d| d.get_temp::>(recents_id).is_none()); - let open_recents: Vec = ui.data_mut(|d| d.get_temp_mut_or_insert_with(recents_id, || recents.to_vec()).clone()); - let (rows, n_recent) = font_menu_rows(families, labels, &ql, &open_recents); - // A recent family is listed twice. The current family's row is the one the last arrow - // selected while it still shows that family, else its first copy: as in Photoshop, the - // one in the recent group when it has one (#9160), and the arrows walk on from there. - let mut selected = ui - .data(|d| d.get_temp::(row_id)) - .filter(|&i| rows.get(i).is_some_and(|(f, _)| *f == current)) - .or_else(|| rows.iter().position(|(f, _)| *f == current)); - // The menu opens on the current family, as Photoshop's does: with the recent group at the - // top of the view when the marked row fits below it, else the marked row itself, at the - // top of the view when it is not a recent one. Applied on the first laid-out pass (the - // popup's first pass only measures), whether or not a row matches, so a missing font or - // a filtered list never scrolls the menu later. - let reveal_id = search_id.with("reveal"); - if opening { - ui.data_mut(|d| d.insert_temp(reveal_id, true)); - } - let revealing = ui.data(|d| d.get_temp::(reveal_id)).unwrap_or(false) && !ui.is_sizing_pass(); - if revealing { - ui.data_mut(|d| d.remove::(reveal_id)); - } - let reveal = if revealing { selected } else { None }; - let reveal_from = reveal.map(|i| if i < n_recent { 0 } else { i }); - let mut stepped = None; - if down || up { - let next = match selected { - Some(i) if down => i.saturating_add(1).min(rows.len().saturating_sub(1)), - Some(i) => i.saturating_sub(1), - None if down => 0, - None => rows.len().saturating_sub(1), - }; - if let Some((f, _)) = rows.get(next) { - changed = **f != *current; - current.clone_from(f); - // A served family not fetched yet: start now, as a click does. - photocraft_text::served::request(f); - stepped = Some(next); - selected = Some(next); - ui.data_mut(|d| d.insert_temp(row_id, next)); - } - } - let accept = enter && rows.iter().any(|(f, _)| *f == current); - picked |= accept; - if accept { - ui.data_mut(|d| d.remove::(search_id)); - ui.close(); - } - let preview = crate::font_preview::sample(preview); - let row_h = preview.map_or(28.0, |(_, [_, h])| (h + 4.0).max(28.0)); - - // Wrap the font rows in a ScrollArea so only the list scrolls: the search field above - // stays fixed at the top of the popup. - let mut hovered: Option = None; - let reveal = if stepped.is_some() { None } else { reveal }; - let mut reveal_top: Option = None; - egui::ScrollArea::vertical().show(ui, |ui| { - for (i, (f, label)) in rows.into_iter().enumerate() { - if i == n_recent && n_recent > 0 { - ui.separator(); - } - // Highlighted by its fill alone, as Photoshop's font menu is. A selectable button lays - // out its frame's stroke only once hovered or selected, so with the theme's stroke the - // row under the pointer (and the selected one) grew and pushed the rows below down: - // the list jumped as the pointer moved (#7406). One row only, though a recent - // family is listed twice. - let mut button = egui::Button::selectable(selected == Some(i), label).truncate().stroke(egui::Stroke::NONE); - if let Some((size, [_, h])) = preview { - button = button.right_text(egui::Atom::custom( - egui::IdSalt::new(("font-sample", f)), - egui::vec2(crate::font_preview::slot_width(ui.ctx(), f, size), h), - )); - } - let response = ui.add_sized([330.0, row_h], button); - if stepped == Some(i) { - response.scroll_to_me(Some(egui::Align::Center)); - } else if reveal.is_some() { - if reveal_from == Some(i) { - reveal_top = Some(response.rect); - } - if reveal == Some(i) { - // Jump, not glide: the menu opens with its current family in view. Arrow - // steps above keep the animation. A recent row too far below the top of - // the group (large previews, many recents) is brought up to the bottom. - let top = reveal_top.unwrap_or(response.rect); - let (rect, align) = if response.rect.bottom() - top.top() <= ui.clip_rect().height() { - (top, egui::Align::Min) - } else { - (response.rect, egui::Align::Max) - }; - ui.scroll_to_rect_animation(rect, Some(align), egui::style::ScrollAnimation::none()); - } - } - if let Some((size, _)) = preview - && ui.is_rect_visible(response.rect) - { - crate::font_preview::paint(ui, f, response.rect, size); - } - if response.hovered() { - hovered = Some(f.clone()); - } - if press.chosen(ui, &response) { - *current = f.clone(); - // A served family not fetched yet: start now, before any text needs it. - photocraft_text::served::request(f); - changed = true; - picked = true; - ui.data_mut(|d| d.remove::(search_id)); - hovered = None; - ui.close(); - } - } - }); - // egui measures a popup only when it opens and never lets it grow back, so a filtered - // list would leave the menu short after the query is cleared (#1369). Keep the unfiltered - // height while searching. Measured after the rows: before them `min_rect` only holds the - // search field, and the cache would shrink the menu to it. - if ql.is_empty() { - let h = ui.min_rect().height(); - ui.data_mut(|d| d.insert_temp(height_id, h)); - } else if let Some(h) = ui.data(|d| d.get_temp::(height_id)) { - ui.set_min_height(h.min(FONT_MENU_HEIGHT)); - } - if accept { None } else { hovered } - }); - response.response = response.response.accessible_name(tl!("Font")); - press.after(&response.response); - if !egui::ComboBox::is_open(ui.ctx(), response.response.id) { - ui.data_mut(|d| { - d.remove::(focus_id); - d.remove::>(recents_id); - d.remove::(row_id); - d.remove::(search_id.with("reveal")); - }); - } - let hovered_font = response.inner.unwrap_or_default(); - - // As in Photoshop, the field keeps the keyboard focus once a font is picked, and ↑ / ↓ on the - // focused, closed field step to the previous / next family, applying each (#7407). The lock - // filter keeps egui from using those arrows to move the focus to another widget. - let field = response.response.id; - if picked { - ui.memory_mut(|m| m.request_focus(field)); - } - let open = egui::ComboBox::is_open(ui.ctx(), field); - if !open && ui.is_enabled() && ui.memory(|m| m.has_focus(field)) { - ui.memory_mut(|m| m.set_focus_lock_filter(field, egui::EventFilter { vertical_arrows: true, ..Default::default() })); - let down = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown)); - let up = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp)); - if down || up { - // The lock filter only holds from the frame after the field got the focus: an arrow - // right after a pick was already read by egui as a focus move, applied at the end of - // the frame. Cancel it, so the arrow only steps the font. - ui.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); - } - // The wheel's step: a negative notch is the next family. Steps use a stable order (no - // recent group), so recording the picked family cannot make the next step jump back. - let notches = f32::from(u8::from(up)) - f32::from(u8::from(down)); - let (rows, _) = font_menu_rows(families, labels, "", &[]); - if let Some(i) = rows.iter().position(|(f, _)| *f == current) - && let Some(n) = wheel_family_index(i, rows.len(), notches) - && let Some((f, _)) = rows.get(n) - && **f != *current - { - current.clone_from(f); - photocraft_text::served::request(f); - changed = true; - } - } - - // The wheel over the closed button steps through the families, a notch each, like Photoshop's - // options-bar font menu: no need to open the list (#3350). - if !egui::ComboBox::is_open(ui.ctx(), response.response.id) && ui.is_enabled() { - let hovered = response.response.hovered(); - if hovered { - ui.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO); - } - let notches = crate::widgets::wheel_notches_of(ui, response.response.id.with("family-wheel"), hovered, 1.0); - // The wheel steps in a stable order: a recent group holding the family it just picked - // would change the order between notches and can jump back to the previous family. - // The open menu still shows the recent families first. - let (rows, _) = font_menu_rows(families, labels, "", &[]); - if let Some(i) = rows.iter().position(|(f, _)| *f == current) - && let Some(n) = wheel_family_index(i, rows.len(), notches) - && let Some((f, _)) = rows.get(n) - && **f != *current - { - current.clone_from(f); - photocraft_text::served::request(f); - changed = true; - } - } - - if salt == "type-font" { - let hover_id = egui::Id::unique("type-font-hover"); - if let Some(f) = hovered_font { - ui.ctx().data_mut(|d| d.insert_temp(hover_id, f)); - } else if egui::ComboBox::is_open(ui.ctx(), response.response.id) { - // Only the open menu clears it: the options bar and the Character section both draw - // this picker, and the closed one must not wipe the other's hover (#5152). - ui.ctx().data_mut(|d| d.remove::(hover_id)); - } - } - - changed -} - -/// The row `notches` wheel notches from row `index` of `len` (down, negative, is the next one), -/// stopping at the ends; none when the wheel did not move. -fn wheel_family_index(index: usize, len: usize, notches: f32) -> Option { - let steps = notches.abs().min(len as f32) as usize; - if steps == 0 || len == 0 { - return None; - } - let last = len - 1; - Some(if notches < 0.0 { index.saturating_add(steps).min(last) } else { index.saturating_sub(steps) }) -} - -/// Representative for the displayed properties: the edit layer, else a selected type layer. -pub(crate) fn target(app: &PhotocraftApp) -> Option<(u64, Option<[usize; 2]>)> { - if let Some(ed) = &app.ui.text_edit { - let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor)); - return Some((ed.layer, (a < b).then_some([a, b]))); - } - let st = app.session.active()?; - let id = st - .active_layer - .filter(|id| text_layer(&st.doc, *id).is_some()) - .or_else(|| st.selected_layers().into_iter().find(|id| text_layer(&st.doc, *id).is_some()))?; - Some((id.0, None)) -} - -/// The type layer whose properties the Type controls and dialogs show (see [`target`]). -pub(crate) fn target_text(app: &PhotocraftApp) -> Option<&TextLayer> { - let (id, _) = target(app)?; - text_layer(&target_doc(app)?.doc, LayerId(id)) -} - -/// The document [`target`]'s layer is in: a text edit's own, which can stay in a background -/// document where the same layer id may name another layer, else the active one. -fn target_doc(app: &PhotocraftApp) -> Option<&photocraft_engine::DocState> { - match &app.ui.text_edit { - Some(ed) => app.session.documents().get(edit_home(app, ed)?), - None => app.session.active(), - } -} - -/// Snapshot the mutation scope separately from the representative used to display properties. -/// An inline edit remains on its layer/range; layer selection formats every selected type layer. -pub(crate) fn formatting_params(app: &PhotocraftApp) -> Option { - if let Some(ed) = &app.ui.text_edit { - let mut params = json!({"layer": ed.layer, "coalesce": ed.session}); - let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor)); - if a < b { - params["range"] = json!([a, b]); - } - return Some(params); - } - let st = app.session.active()?; - let layers: Vec = st.selected_layers().into_iter().filter(|id| text_layer(&st.doc, *id).is_some()).map(|id| id.0).collect(); - (!layers.is_empty()).then(|| json!({"layers": layers})) -} - -/// Scale of the target layer's transform. Like Photoshop, sizes show and edit as the layer -/// appears: a 12 pt layer scaled 200% (common in PSDs) reads 24 pt. -fn shown_scale(app: &PhotocraftApp) -> f32 { - let Some((id, _)) = target(app) else { return 1.0 }; - let Some(t) = app.session.active().and_then(|st| text_layer(&st.doc, LayerId(id))) else { return 1.0 }; - let m = t.transform.m; - let k = (m[0] * m[3] - m[1] * m[2]).abs().sqrt() as f32; - if k.is_finite() && k > 1e-3 { k } else { 1.0 } -} - -/// The display unit for type metrics (Preferences ▸ Units & Rulers ▸ Type): the multiplier from -/// the model's points to the unit, and its label. Pixels follow the document's resolution. -pub(crate) fn type_unit(app: &PhotocraftApp) -> (f32, &'static str) { - let dpi = app.session.active().map_or(72.0, |d| d.doc.resolution_dpi.max(1.0)); - match app.session.prefs().units_and_rulers.type_units { - photocraft_engine::prefs::TypeUnit::Points => (1.0, "pt"), - photocraft_engine::prefs::TypeUnit::Pixels => (dpi / 72.0, "px"), - photocraft_engine::prefs::TypeUnit::Millimeters => (25.4 / 72.0, "mm"), - } -} - -/// Coalesce key while a field is being scrubbed: every step of one drag shares one history step -/// (Photoshop's single step per scrub, #124). Unique per press, so two drags are two steps. -fn drag_key(ctx: &egui::Context) -> Option { - let id = ctx.dragged_id()?; - let t = ctx.input(|i| i.pointer.press_start_time())?; - Some(format!("type-drag-{}-{}", id.value(), t.to_bits())) -} - -/// The styles a new Type-tool layer will receive. Use the same command parameters for the -/// panels and creation so defaults also survive action recording/replay. The older options-bar -/// fields remain authoritative, and text colour continues to follow the foreground colour. -fn default_style_params(app: &PhotocraftApp) -> serde_json::Value { - let o = &app.ui.tool_options; - let mut p = json!({}); - // Settings are editable JSON: only recognized formatting keys may reach type.create. - // In particular a stray `text`, `box`, or `coalesce` key must not become a create parameter. - let (mut c, mut para) = (photocraft_doc::text::CharStyle::default(), photocraft_doc::text::ParagraphStyle::default()); - for (key, value) in &o.type_style_defaults { - // These belong to the existing options-bar fields. Apart from being redundant, - // parsing a saved font key here would wait for the background font scan. - if matches!(key.as_str(), "font" | "family" | "fontStyle" | "weight" | "italic" | "postscriptName") { - continue; - } - let one = json!({ (key): value }); - if !finite_style_value(value) - || photocraft_engine::type_cmds::check_size_tracking(&one).is_err() - || photocraft_engine::type_cmds::check_kerning(&one).is_err() - { - continue; - } - if photocraft_engine::type_cmds::apply_char_props(&mut c, &one) | photocraft_engine::type_cmds::apply_para_props(&mut para, &one) { - p[key] = value.clone(); - } - } - p["font"] = json!(o.type_font); - p["fontStyle"] = json!(o.type_style); - p["size"] = json!(o.type_size); - p["align"] = json!(o.type_align); - p["direction"] = json!(o.type_direction); - p["color"] = json!(hex(app.session.tools.foreground)); - p -} - -/// Style numbers become f32 in the engine. JSON itself permits finite f64 values too large -/// for that conversion; a hand-edited setting must not inject infinity into a new layer. -/// Style collections (features, axes, colour) contain only scalar values, so no recursion. -fn finite_style_value(value: &serde_json::Value) -> bool { - let scalar = |v: &serde_json::Value| match v { - serde_json::Value::Number(n) => n.as_f64().is_some_and(|n| (n as f32).is_finite()), - serde_json::Value::Array(_) | serde_json::Value::Object(_) => false, - _ => true, - }; - match value { - serde_json::Value::Array(v) => v.iter().all(scalar), - serde_json::Value::Object(v) => v.values().all(scalar), - v => scalar(v), - } -} - -fn default_styles(app: &PhotocraftApp) -> (photocraft_doc::text::CharStyle, photocraft_doc::text::ParagraphStyle) { - let (mut c, mut para) = app.session.type_defaults.clone().unwrap_or_default(); - let mut p = default_style_params(app); - // The saved panels can appear on the very first frame. Style parsing resolves the named - // font through shared(), which waits for the font scan; display the saved names meanwhile, - // and let fonts_ready/axis_sliders expose the font controls when try_shared is ready. - if photocraft_text::try_shared().is_none() { - c.font_family = app.ui.tool_options.type_font.clone(); - c.font_style = app.ui.tool_options.type_style.clone(); - c.postscript_name = None; - if let Some(p) = p.as_object_mut() { - p.remove("font"); - p.remove("fontStyle"); - } - } - photocraft_engine::type_cmds::apply_char_props(&mut c, &p); - photocraft_engine::type_cmds::apply_para_props(&mut para, &p); - (c, para) -} - -/// Change tool defaults without creating a document edit. The engine owns the style schema; -/// keep its property names rather than maintaining another style parser in the shell. -fn apply_defaults(app: &mut PhotocraftApp, props: &serde_json::Value) { - let Some(props) = props.as_object() else { return }; - let o = &mut app.ui.tool_options; - for (key, value) in props { - match key.as_str() { - "font" => { - if let Some(v) = value.as_str() { - o.type_font = v.into(); - } - } - "fontStyle" => { - if let Some(v) = value.as_str() { - o.type_style = v.into(); - // A newly chosen named style replaces a weight-axis setting, as it does - // in apply_char_props. Other axes retain their independently chosen values. - if let Some(axes) = o.type_style_defaults.get_mut("variations").and_then(serde_json::Value::as_object_mut) { - axes.remove("wght"); - } - } - } - "size" => { - if let Some(v) = value.as_f64() { - o.type_size = v as f32; - } - } - "align" => { - if let Some(v) = value.as_str() { - o.type_align = v.into(); - } - } - "direction" => { - if let Some(v) = value.as_str() { - o.type_direction = v.into(); - } - } - "metricsAsShown" => {} // Defaults have no layer transform. - "features" | "variations" => { - if let Some(patch) = value.as_object() { - let old = o.type_style_defaults.entry(key.clone()).or_insert_with(|| json!({})); - if let Some(old) = old.as_object_mut() { - old.extend(patch.clone()); - } else { - *old = value.clone(); - } - } - } - _ => { - o.type_style_defaults.insert(key.clone(), value.clone()); - } - } - } -} - -/// Apply only the supplied properties to the text-edit scope or selected type layers; without -/// a type target, prepare the defaults for the next layer instead. -fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, props: serde_json::Value) { - let Some(mut p) = formatting_params(app) else { - apply_defaults(app, &props); - return; - }; - if let Some(props) = props.as_object() { - for (key, value) in props { - p[key] = value.clone(); - } - } - if let Some(key) = app.ui.text_edit.as_ref().map(|ed| ed.session.clone()).or_else(|| drag_key(ctx)) { - p["coalesce"] = json!(key); - } - let _ = app.run("type.setStyle", p); -} - -/// `props` aimed at the type target: its layer, the selected characters while typing, and the -/// typing session's undo step. `None` without a type target. -pub(crate) fn with_target(app: &PhotocraftApp, mut props: serde_json::Value) -> Option { - let (layer, range) = target(app)?; - props["layer"] = json!(layer); - if let Some(r) = range { - props["range"] = json!(r); - } - if let Some(key) = app.ui.text_edit.as_ref().map(|ed| ed.session.clone()) { - props["coalesce"] = json!(key); - } - Some(props) -} - -/// Open the shared Color Picker with a snapshot of the text target. Sampling or cancelling -/// the dialog never changes the text selection, tool colours, or document history. -pub fn open_color_picker(app: &mut PhotocraftApp, rgb: [f32; 3]) -> u64 { - if let Some(params) = formatting_params(app) { - crate::color_picker_ui::open_for_command(app, "Color Picker (Text Color)", rgb, "type.setStyle", params) - } else { - crate::color_picker_ui::open(app, "foreground") - } -} - -/// While characters are selected in a type layer, a new foreground colour (Color and Swatches -/// panels, the Color Picker) recolours them, in the editing session's history step. -pub fn foreground_changed(app: &mut PhotocraftApp) { - let Some((layer, Some(range))) = target(app) else { return }; - let Some(ed) = app.ui.text_edit.as_ref() else { return }; - let p = json!({"layer": layer, "range": range, "color": hex(app.session.tools.foreground), "coalesce": ed.session}); - let _ = app.run("type.setStyle", p); -} - -/// Photoshop's Type options bar. -pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = crate::theme::Tokens::get(ui.ctx()); - // Show the target layer's (first-run) style, else the tool defaults. - let shown = target(app).and_then(|(id, _)| { - let st = app.session.active()?; - let tl = text_layer(&st.doc, LayerId(id))?; - let run = tl.char_runs().into_iter().next().map(|r| r.style); - // The size at the selection (else the first run), as the layer shows it (#124). - let size = styles_at(app).map_or(tl.size_pt, |(c, _)| c.size_pt) * shown_scale(app); - Some((tl.font_family.clone(), run.as_ref().map(selected_style).unwrap_or_default(), size, styles_at(app).map_or(tl.color, |(c, _)| c.color))) - }); - let o = app.ui.tool_options.clone(); - let (mut fam, mut style, size) = match &shown { - Some((f, s, z, _)) => (f.clone(), if s.is_empty() { "Regular".into() } else { s.clone() }, *z), - None => (o.type_font.clone(), o.type_style.clone(), o.type_size), - }; - if crate::icons::button(ui, "text-cursor", 24.0, false, tl!("Toggle text orientation")).clicked() - && let Some((layer, _)) = target(app) - && let Some(params) = formatting_params(app) - { - let to = if is_vertical(app, LayerId(layer)) { "horizontal" } else { "vertical" }; - if let Err(e) = app.run(&format!("type.orientation.{to}"), params) { - app.ui.status = e; - app.ui.status_error = true; - } - } - // Font family and style menus (one placeholder in their place while the fonts load). - if fonts_ready(ui, 170.0 + ui.spacing().item_spacing.x + 110.0) { - if font_picker(ui, &mut fam, 170.0, app.session.prefs().type_.font_preview, &app.ui.recent_fonts) { - app.note_recent_font(&fam); - app.ui.tool_options.type_font = fam.clone(); - let st = styles(&fam); - style = if st.contains(&style) { style } else { st.first().cloned().unwrap_or_else(|| "Regular".into()) }; - app.ui.tool_options.type_style = style.clone(); - apply(app, ui.ctx(), json!({"font": fam})); - } - let opts: Vec<(String, String)> = styles(&fam).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(); - if crate::widgets::dropdown(ui, "type-style", tl!("Style"), &mut style, &opts_ref, 110.0) { - app.ui.tool_options.type_style = style.clone(); - apply(app, ui.ctx(), json!({"fontStyle": 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")); - 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() { - let size = display / unit; - app.ui.tool_options.type_size = size; - apply(app, ui.ctx(), json!({"size": size, "metricsAsShown": true})); - } - let mut aa = target(app) - .and_then(|(id, _)| app.session.active().and_then(|st| text_layer(&st.doc, LayerId(id)))) - .map(|t| photocraft_engine::type_extra_cmds::aa_name(t.antialias).to_string()) - .unwrap_or_else(|| o.type_aa.clone()); - let aa_opts = [ - ("none".to_string(), tl!("None")), - ("sharp".to_string(), tl!("Sharp")), - ("crisp".to_string(), tl!("Crisp")), - ("strong".to_string(), tl!("Strong")), - ("smooth".to_string(), tl!("Smooth")), - ]; - if crate::widgets::dropdown(ui, "type-aa", tl!("Anti-aliasing method"), &mut aa, &aa_opts, 80.0) { - app.ui.tool_options.type_aa = aa.clone(); - if let Some(params) = formatting_params(app) { - let _ = app.run(&format!("type.antiAlias.{aa}"), params); - } - } - crate::widgets::vline(ui, 22.0); - ui.spacing_mut().item_spacing.x = 2.0; - // Alignment and direction show the target paragraph's, as Photoshop's bar follows the text - // being edited or the selected type layer; the tool defaults otherwise. A justified paragraph - // lights none of the three. - let para = styles_at(app).map(|(_, p)| p); - let shown_align = match ¶ { - Some(p) => match p.align { - photocraft_doc::text::TextAlign::Left => "left", - photocraft_doc::text::TextAlign::Center => "center", - photocraft_doc::text::TextAlign::Right => "right", - _ => "", - }, - None => o.type_align.as_str(), - }; - for (align, icon, tip) in - [("left", "align-left", tl!("Left align text")), ("center", "align-center", tl!("Center text")), ("right", "align-right", tl!("Right align text"))] - { - 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})); - } - } - ui.spacing_mut().item_spacing.x = 8.0; - crate::widgets::vline(ui, 22.0); - ui.spacing_mut().item_spacing.x = 2.0; - for (key, tip, d) in direction_items() { - let on = para.as_ref().map_or(o.type_direction == key, |p| p.direction == d); - if direction_button(ui, d, on, tip).clicked() { - app.ui.tool_options.type_direction = key.into(); - apply(app, ui.ctx(), json!({"direction": key})); - } - } - ui.spacing_mut().item_spacing.x = 8.0; - crate::widgets::vline(ui, 22.0); - // Text colour swatch with a picker popup. - let c = shown - .as_ref() - .map(|s| s.3) - .map(|c| { - let v = c.to_rgb(); - [v[0], v[1], v[2], 1.0] - }) - .unwrap_or(app.session.tools.foreground); - let (rect, resp) = ui.allocate_exact_size(egui::vec2(28.0, 18.0), egui::Sense::click()); - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - ui.painter().rect_filled(rect, 2.0, Color32::from_rgb(q(c[0]), q(c[1]), q(c[2]))); - ui.painter().rect_stroke(rect, 2.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside); - let resp = resp.on_hover_text(tl!("Set the 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]]); - } - // Create warped text, after the swatch as in Photoshop (#5911): the Type › Warp Text… dialog. - let can_warp = crate::menus::is_enabled(app, "type.warpText"); - if ui.add_enabled_ui(can_warp, |ui| crate::icons::button(ui, "text-warp", 24.0, false, tl!("Create warped text"))).inner.clicked() - && let Err(e) = crate::menus::invoke(app, &ui.ctx().clone(), "type.warpText", json!({})) - { - app.ui.status = e; - app.ui.status_error = true; - } - if app.ui.text_edit.is_some() { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.add_space(8.0); - if crate::icons::button( - ui, - "check", - 24.0, - false, - &crate::i18n::fmt(tl!("Commit any current edits ({key})"), &[("key", &crate::shortcuts::pretty("Cmd+Enter"))]), - ) - .clicked() - { - commit_with(app, ui.input(|i| i.modifiers)); - } - if crate::icons::button(ui, "ban", 24.0, false, tl!("Cancel any current edits (Esc)")).clicked() { - cancel(app); - } - }); - } -} - -/// Character and paragraph style at the target (selection start, else the layer's first run). -/// The paragraph at a collapsed caret is the caret's, as Photoshop's options bar and Paragraph -/// panel show it. -pub(crate) fn styles_at(app: &PhotocraftApp) -> Option<(photocraft_doc::text::CharStyle, photocraft_doc::text::ParagraphStyle)> { - let (layer, range) = target(app)?; - let t = text_layer(&target_doc(app)?.doc, LayerId(layer))?; - let at = range.map_or(0, |r| byte_of(&t.text, r[0])); - let para_at = match (range, &app.ui.text_edit) { - (None, Some(ed)) => byte_of(&t.text, ed.caret), - _ => at, - }; - let pick_at = |at: usize, lens: Vec| -> usize { - let mut acc = 0; - for (i, len) in lens.iter().enumerate() { - acc += len; - if at < acc { - return i; - } - } - lens.len().saturating_sub(1) - }; - let runs = t.char_runs(); - let paras = t.paragraph_runs(); - let c = runs.get(pick_at(at, runs.iter().map(|r| r.len).collect())).map(|r| r.style.clone())?; - let p = paras.get(pick_at(para_at, paras.iter().map(|r| r.len).collect())).map(|r| r.style.clone()).unwrap_or_default(); - Some((c, p)) -} - -/// Kerning shown for the target: at a collapsed caret, the pair before it (Photoshop's -/// Character panel); else the style at the selection. -fn kerning_at(app: &PhotocraftApp) -> Option<(photocraft_doc::text::Kerning, f32)> { - let ed = app.ui.text_edit.as_ref().filter(|e| e.caret == e.anchor && e.caret > 0)?; - let st = app.session.active()?; - let t = text_layer(&st.doc, LayerId(ed.layer))?; - let at = byte_of(&t.text, ed.caret - 1); - let mut end = 0; - t.char_runs() - .into_iter() - .find(|r| { - end += r.len; - at < end - }) - .map(|r| (r.style.kerning, r.style.kern)) -} - -/// The Character panel's kerning text: "Metrics", "Optical" or the manual value. -pub(crate) fn kerning_label((mode, kern): (photocraft_doc::text::Kerning, f32)) -> String { - use photocraft_doc::text::Kerning; - match mode { - _ if kern != 0.0 && kern.is_finite() => format!("{}", kern.round() as i64), - Kerning::Metrics => "Metrics".into(), - Kerning::Optical => "Optical".into(), - Kerning::Off => "0".into(), - } -} - -/// Parses a typed kerning value: Metrics / Optical (any case) or a number in 1/1000 em -/// (Photoshop's range, -1000..10000). `None` for anything else. -pub(crate) fn parse_kerning(s: &str) -> Option { - let s = s.trim(); - match s.to_ascii_lowercase().as_str() { - "metrics" => Some(json!("metrics")), - "optical" => Some(json!("optical")), - _ => crate::numeric_expression::parse(s).filter(|v| v.is_finite() && (-1000.0..=10000.0).contains(v)).map(|v| json!(v.round())), - } -} - -/// Photoshop's editable kerning combo: type a value or Metrics/Optical, or pick a preset. -fn kerning_field(ui: &mut egui::Ui, shown: &str, width: f32) -> Option { - let id = ui.make_persistent_id("props-kern-text"); - let mut buf: String = ui.data_mut(|d| d.get_temp::(id)).unwrap_or_else(|| shown.to_string()); - let mut out = None; - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 0.0; - let resp = ui.add(egui::TextEdit::singleline(&mut buf).desired_width((width - 40.0).max(24.0)).id(id.with("edit"))).accessible_name(tl!("Kerning")); - if resp.has_focus() { - ui.data_mut(|d| d.insert_temp(id, buf.clone())); - } else { - ui.data_mut(|d| d.remove::(id)); - } - if resp.lost_focus() && buf.trim() != shown { - out = parse_kerning(&buf); - } - 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 = egui::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); - } - } - }); - press.after(&combo.response); - let _ = combo.response.accessible_name(tl!("Kerning")); - }); - out -} - -/// Applies a kerning value: at a collapsed caret to the pair before it, else to the selection -/// (or the whole layer). -fn apply_kerning(app: &mut PhotocraftApp, ctx: &egui::Context, v: serde_json::Value) { - match app.ui.text_edit.clone().filter(|e| e.caret == e.anchor) { - Some(ed) if ed.caret > 0 => { - let _ = app.run("type.edit", json!({"layer": ed.layer, "range": [ed.caret - 1, ed.caret], "kerning": v})); - } - Some(_) => {} - None => apply(app, ctx, json!({ "kerning": v })), - } -} - -fn icon_label(ui: &mut egui::Ui, icon: &str, tip: &str) { - let t = crate::theme::Tokens::get(ui.ctx()); - let (r, resp) = ui.allocate_exact_size(egui::vec2(crate::props_layout::LABEL_W, 22.0), egui::Sense::hover()); - crate::icons::paint(ui, r, icon, 12.0, t.text_dim); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, ui.is_enabled(), tl!(tip))); - // Photoshop's Character panel icons scrub the field beside them. - crate::widgets::scrub_label(ui, &resp.on_hover_text(tl!(tip))); -} - -/// Labelled numeric field (Photoshop's icon + value pairs). Returns the new value when edited. -fn num_field(ui: &mut egui::Ui, label: &str, tip: &str, v: f32, range: std::ops::RangeInclusive, unit: &str, width: f32) -> Option { - let t = crate::theme::Tokens::get(ui.ctx()); - let mut v = v; - let mut out = None; - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - let (r, resp) = ui.allocate_exact_size(egui::vec2(22.0, 22.0), egui::Sense::hover()); - ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, label, crate::theme::semibold(10.0), t.text_dim); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, ui.is_enabled(), tl!(tip))); - crate::widgets::scrub_label(ui, &resp.on_hover_text(tl!(tip))); - let response = crate::widgets::value_field(ui, &mut v, range, unit, width); - response.widget_info(|| { - let mut info = egui::WidgetInfo::drag_value(ui.is_enabled(), f64::from(v)); - info.label = Some(tl!(tip).to_owned()); - info - }); - if response.changed() { - out = Some(v); - } - }); - out -} - -/// Photoshop's paragraph alignment glyphs: four text lines whose widths/offsets show the mode -/// (justify variants run full width, with the last line placed left/centre/right). -fn align_glyph(p: &egui::Painter, r: egui::Rect, a: photocraft_doc::text::TextAlign, c: Color32) { - use photocraft_doc::text::TextAlign as A; - let widths = [1.0, 0.62, 1.0, 0.62]; - for (i, w) in widths.iter().enumerate() { - let y = r.top() + i as f32 * r.height() / 3.0; - let full = r.width(); - let (len, x0) = match a { - A::Left => (full * w, r.left()), - A::Center => (full * w, r.center().x - full * w / 2.0), - A::Right => (full * w, r.right() - full * w), - A::JustifyAll => (full, r.left()), - _ if i < 3 => (full, r.left()), - A::JustifyLeft => (full * 0.55, r.left()), - A::JustifyCenter => (full * 0.55, r.center().x - full * 0.275), - _ => (full * 0.55, r.right() - full * 0.55), - }; - p.line_segment([egui::pos2(x0, y), egui::pos2(x0 + len, y)], Stroke::new(1.5, c)); - } -} - -/// Paragraph direction choices for the Paragraph panel and the options bar (TYPE-218-2): the -/// `direction` value `type.setStyle` takes, the tooltip, and the direction it sets. -fn direction_items() -> [(&'static str, &'static str, photocraft_doc::text::TextDirection); 3] { - use photocraft_doc::text::TextDirection as D; - [ - ("auto", tl!("Automatic paragraph direction"), D::Auto), - ("ltr", tl!("Left-to-right paragraph direction"), D::Ltr), - ("rtl", tl!("Right-to-left paragraph direction"), D::Rtl), - ] -} - -/// A pilcrow over an arrow pointing the way the paragraph runs; Auto points both ways. -fn direction_glyph(p: &egui::Painter, r: egui::Rect, d: photocraft_doc::text::TextDirection, c: Color32) { - use photocraft_doc::text::TextDirection as D; - let g = p.layout_no_wrap("¶".to_string(), egui::FontId::proportional(11.0), c); - p.galley(egui::pos2(r.center().x - g.size().x / 2.0, r.top() - 2.0), g, c); - let (y, s) = (r.bottom() - 1.5, Stroke::new(1.3, c)); - p.line_segment([egui::pos2(r.left(), y), egui::pos2(r.right(), y)], s); - let head = |x: f32, towards: f32| { - for dy in [-3.0, 3.0] { - p.line_segment([egui::pos2(x, y), egui::pos2(x - towards * 3.0, y + dy)], s); - } - }; - if d != D::Rtl { - head(r.right(), 1.0); - } - if d != D::Ltr { - head(r.left(), -1.0); - } -} - -/// The options bar's 24 px square button for one paragraph direction, styled like its icon buttons. -fn direction_button(ui: &mut egui::Ui, d: photocraft_doc::text::TextDirection, selected: bool, tip: &str) -> egui::Response { - let (r, resp) = ui.allocate_exact_size(egui::vec2(24.0, 24.0), egui::Sense::click()); - let tint = crate::icons::button_chrome(ui, r, selected, resp.hovered()); - direction_glyph(ui.painter(), egui::Rect::from_center_size(r.center(), egui::vec2(14.0, 16.0)), d, tint); - let tip = tip.to_string(); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &tip)); - resp.on_hover_text(tip) -} - -/// A toggle button (faux styles, paragraph alignment) of width `w`, painted by `paint`. -fn toggle_cell(ui: &mut egui::Ui, w: f32, on: bool, tip: &str, paint: impl FnOnce(&egui::Ui, egui::Rect, Color32)) -> bool { - let t = crate::theme::Tokens::get(ui.ctx()); - let (r, resp) = ui.allocate_exact_size(egui::vec2(w, 24.0), egui::Sense::click()); - let bg = if on { - t.accent_soft - } else if resp.hovered() { - t.hover - } else { - Color32::TRANSPARENT - }; - ui.painter().rect_filled(r, t.radius_sm, bg); - if on { - ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, t.accent_border), egui::StrokeKind::Inside); - } - let enabled = ui.is_enabled(); - paint( - ui, - r, - if !enabled { - t.text_faint - } else if on { - t.text - } else { - t.text_dim - }, - ); - let tip = tip.to_string(); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, enabled, on, &tip)); - resp.on_hover_text(tl!(&tip)).clicked() -} - -/// The Character panel's OpenType buttons, in Photoshop's order: (feature tag, command id, -/// tooltip). The tooltips are the Type › OpenType menu labels. -pub(crate) const OPENTYPE_BUTTONS: [(&str, &str, &str); 8] = [ - ("liga", "type.openType.standardLigatures", "Standard Ligatures"), - ("calt", "type.openType.contextualAlternates", "Contextual Alternates"), - ("dlig", "type.openType.discretionaryLigatures", "Discretionary Ligatures"), - ("swsh", "type.openType.swash", "Swash"), - ("salt", "type.openType.stylisticAlternates", "Stylistic Alternates"), - ("titl", "type.openType.titlingAlternates", "Titling Alternates"), - ("ordn", "type.openType.ordinals", "Ordinals"), - ("frac", "type.openType.fractions", "Fractions"), -]; - -/// Photoshop's OpenType button row: each shows pressed while its feature is on at the type -/// target (the selection start, else the layer) and toggles it through the Type › OpenType -/// command, on the same scope as the other Character controls. -fn opentype_row(app: &mut PhotocraftApp, ui: &mut egui::Ui, c: &photocraft_doc::text::CharStyle, full: f32) { - let cw = cell_width(full, OPENTYPE_BUTTONS.len()); - let mut clicked = None; - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - for (tag, id, tip) in OPENTYPE_BUTTONS { - let on = photocraft_engine::type_extra_cmds::feature_on(c, tag); - if toggle_cell(ui, cw, on, tip, |ui, r, col| opentype_glyph(ui.painter(), r, tag, col)) { - clicked = Some((id, on)); - } - } - }); - if let Some((id, on)) = clicked { - toggle_opentype(app, id, on); - } -} - -/// Runs an OpenType toggle command on the Character panel's scope: the edited layer's selected -/// characters (or its whole text) while typing, else every selected type layer. The new state -/// is explicit, so it follows the button the user saw rather than the layer's first run. -pub(crate) fn toggle_opentype(app: &mut PhotocraftApp, id: &str, shown_on: bool) { - let Some(mut p) = formatting_params(app) else { - if let Some((tag, _, _)) = OPENTYPE_BUTTONS.iter().find(|(_, command, _)| *command == id) { - let props = match *tag { - "liga" => json!({"ligatures": !shown_on}), - "dlig" => json!({"discretionaryLigatures": !shown_on}), - _ => json!({"features": { (*tag): !shown_on }}), - }; - apply_defaults(app, &props); - } - return; - }; - p["on"] = json!(!shown_on); - let _ = app.run(id, p); -} - -/// Small glyph labels for the OpenType buttons (drawn here, no Adobe artwork): fi, st, ct with -/// a ligature arc, a swash A, aa, T, 1st and ½. -fn opentype_glyph(p: &egui::Painter, r: egui::Rect, tag: &str, col: Color32) { - let font = egui::FontId::proportional(13.0); - let centred = |s: &str, font: egui::FontId| { - let g = p.layout_no_wrap(s.to_string(), font, col); - let pos = r.center() - g.size() / 2.0; - let gr = egui::Rect::from_min_size(pos, g.size()); - p.galley(pos, g, col); - gr - }; - match tag { - "liga" => { - centred("fi", font); - } - "calt" => { - centred("st", font); - } - "dlig" => { - let gr = centred("ct", font); - // The ligature's connecting arc from the c over to the t. - let a = egui::pos2(gr.left() + gr.width() * 0.3, gr.top() + gr.height() * 0.42); - let b = egui::pos2(gr.right() - gr.width() * 0.2, gr.top() + 4.0); - let mid = egui::pos2((a.x + b.x) / 2.0, gr.top() + 1.5); - p.line_segment([a, mid], Stroke::new(1.0, col)); - p.line_segment([mid, b], Stroke::new(1.0, col)); - } - "swsh" => { - let gr = centred("A", crate::theme::semibold(13.0)); - // A swash tail sweeping out under the letter. - let y = gr.bottom() - 3.0; - p.line_segment([egui::pos2(gr.left() - 3.0, y + 1.5), egui::pos2(gr.right() + 2.0, y - 0.5)], Stroke::new(1.0, col)); - } - "salt" => { - centred("aa", font); - } - "titl" => { - centred("T", crate::theme::semibold(13.0)); - } - "ordn" => { - let one = p.layout_no_wrap("1".into(), font, col); - let st = p.layout_no_wrap("st".into(), egui::FontId::proportional(9.0), col); - let left = r.center().x - (one.size().x + st.size().x) / 2.0; - let top = r.center().y - one.size().y / 2.0; - let st_x = left + one.size().x; - p.galley(egui::pos2(left, top), one, col); - p.galley(egui::pos2(st_x, top - 1.0), st, col); - } - _ => { - centred("½", font); - } - } -} - -/// Width of each of `n` equal cells filling `avail` with 2 pt gaps. -fn cell_width(avail: f32, n: usize) -> f32 { - let n = n.max(1) as f32; - ((avail - (n - 1.0) * 2.0) / n).floor().max(20.0) -} - -/// Properties panel sections for a type layer: Character, Paragraph and Type Options (#155). -pub fn type_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - type_sections(app, ui, true, true, false); - type_options(app, ui); -} - -/// Window › Character / Paragraph (#150): the same controls as Properties, in their own dock -/// group. Without a type target they edit the defaults for the next Type-tool layer. -pub fn character_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool) { - type_sections(app, ui, !paragraph, paragraph, true); -} - -/// The Character and/or Paragraph sections, with the shared collapsible headers and fields that -/// fill the panel width (#155). -fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, paragraph: bool, show_defaults: bool) { - use crate::props_layout::{COL_GAP, LABEL_GAP, LABEL_W, field_width, section}; - use crate::theme::ROW_GAP; - let Some((c, para)) = styles_at(app).or_else(|| show_defaults.then(|| default_styles(app))) else { return }; - // Preferences ▸ Units & Rulers ▸ Type, as in the options bar: the model keeps points. - let (u, unit) = type_unit(app); - let t = crate::theme::Tokens::get(ui.ctx()); - // Row helper: `ui.horizontal` with the column gap, then the shared row gap. - let row = |ui: &mut egui::Ui, add: &mut dyn FnMut(&mut egui::Ui)| { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = COL_GAP; - add(ui) - }); - ui.add_space(ROW_GAP); - }; - if character && section(ui, "character", tl!("Character")) { - let full = ui.available_width(); - let w = field_width(full, 2, LABEL_W); - let mut fam = c.font_family.clone(); - let mut ready = true; - row(ui, &mut |ui| { - ready = fonts_ready(ui, full); - if ready && font_picker(ui, &mut fam, full, app.session.prefs().type_.font_preview, &app.ui.recent_fonts) { - app.note_recent_font(&fam); - app.ui.tool_options.type_font = fam.clone(); - apply(app, ui.ctx(), json!({"font": fam})); - } - }); - row(ui, &mut |ui| { - if !ready { - return; - } - let mut style = selected_style(&c); - let opts: Vec<(String, String)> = styles(&fam).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(); - if crate::widgets::dropdown(ui, "props-type-style", tl!("Style"), &mut style, &opts_ref, full) { - apply(app, ui.ctx(), json!({"fontStyle": style})); - } - }); - axis_sliders(app, ui, &c); - row(ui, &mut |ui| { - let k = shown_scale(app); - // Hover tips stay English until wired through `tl!` in a multi-locale change - // (`every_tl_literal_is_translated` requires every complete catalog). - if let Some(v) = num_field(ui, "tT", "Font size", c.size_pt * k * u, 0.1 * u..=1296.0 * u, unit, w) { - app.ui.tool_options.type_size = v / u; - apply(app, ui.ctx(), json!({"size": v / u, "metricsAsShown": true})); - } - let lead = c.leading_pt.unwrap_or(c.size_pt * para.auto_leading.max(0.01)) * k; - if let Some(v) = num_field(ui, "A↕", "Leading (set to the font size × auto-leading when Auto)", lead * u, 0.1 * u..=5000.0 * u, unit, w) { - apply(app, ui.ctx(), json!({"leading": v / u, "metricsAsShown": true})); - } - }); - row(ui, &mut |ui| { - let shown = kerning_label(kerning_at(app).unwrap_or((c.kerning, c.kern))); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = LABEL_GAP; - icon_label(ui, "text-cursor", "Kerning: Metrics, Optical or a value in 1/1000 em (Alt+←/→ at the caret)"); - if let Some(v) = kerning_field(ui, &shown, w) { - apply_kerning(app, ui.ctx(), v); - } - }); - if let Some(v) = num_field(ui, "VA", "Tracking (1/1000 em)", c.tracking, -1000.0..=10000.0, "", w) { - apply(app, ui.ctx(), json!({"tracking": v})); - } - }); - row(ui, &mut |ui| { - if let Some(v) = num_field(ui, "↕T", "Vertical scale", c.vertical_scale * 100.0, 0.0..=1000.0, "%", w) { - apply(app, ui.ctx(), json!({"verticalScale": v})); - } - if let Some(v) = num_field(ui, "↔T", "Horizontal scale", c.horizontal_scale * 100.0, 0.0..=1000.0, "%", w) { - apply(app, ui.ctx(), json!({"horizontalScale": v})); - } - }); - row(ui, &mut |ui| { - if let Some(v) = num_field(ui, "Aª", "Baseline shift", c.baseline_shift_pt * u, -1296.0 * u..=1296.0 * u, unit, w) { - apply(app, ui.ctx(), json!({"baselineShift": v / u})); - } - // Colour: label + a swatch filling the rest of the second column. - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = LABEL_GAP; - let g = ui.painter().layout_no_wrap(tl!("Color").into(), egui::FontId::proportional(12.0), t.text_dim); - let lw = g.size().x.max(LABEL_W); - let (lr, _) = ui.allocate_exact_size(egui::vec2(lw, 22.0), egui::Sense::hover()); - ui.painter().galley(egui::pos2(lr.left(), lr.center().y - g.size().y / 2.0), g, t.text_dim); - let rgb = c.color.to_rgb(); - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - let sw = (LABEL_W + LABEL_GAP + w - lw - LABEL_GAP).max(24.0); - let (rect, resp) = ui.allocate_exact_size(egui::vec2(sw, 22.0), egui::Sense::click()); - ui.painter().rect_filled(rect, t.radius_sm, Color32::from_rgb(q(rgb[0]), q(rgb[1]), q(rgb[2]))); - ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); - let resp = resp.on_hover_text(tl!("Text color")); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Text color"))); - if resp.clicked() { - open_color_picker(app, rgb); - } - }); - }); - // Faux styles: T (bold) T (italic) TT Tᴛ T̲ T̶, sharing the row evenly. - let caps = c.caps; - // Tip strings are English keys; `toggle_cell` runs them through `tl!`. - let toggles: [(&str, &str, bool, serde_json::Value); 6] = [ - ("T", "Faux Bold", c.faux_bold, json!({"fauxBold": !c.faux_bold})), - ("T", "Faux Italic", c.faux_italic, json!({"fauxItalic": !c.faux_italic})), - ( - "TT", - "All Caps", - caps == photocraft_doc::text::Caps::AllCaps, - json!({"caps": if caps == photocraft_doc::text::Caps::AllCaps { "normal" } else { "allCaps" }}), - ), - ( - "Tᴛ", - "Small Caps", - caps == photocraft_doc::text::Caps::SmallCaps, - json!({"caps": if caps == photocraft_doc::text::Caps::SmallCaps { "normal" } else { "smallCaps" }}), - ), - ("T", "Underline", c.underline, json!({"underline": !c.underline})), - ("T", "Strikethrough", c.strikethrough, json!({"strikethrough": !c.strikethrough})), - ]; - let cw = cell_width(full, toggles.len()); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - for (i, (glyph, tip, on, props)) in toggles.into_iter().enumerate() { - let clicked = toggle_cell(ui, cw, on, tip, |ui, r, col| { - let font = if i == 0 { crate::theme::semibold(13.0) } else { egui::FontId::proportional(13.0) }; - let g = ui.painter().layout_no_wrap(glyph.to_string(), font, col); - let pos = r.center() - g.size() / 2.0; - let gr = egui::Rect::from_min_size(pos, g.size()); - if i == 1 { - // Faux italic: a slanted T drawn as strokes (no italic face is bundled). - let (top, bot, cx) = (gr.top() + 3.0, gr.bottom() - 3.0, gr.center().x); - let slant = (bot - top) * 0.25; - ui.painter().line_segment([egui::pos2(cx - 4.0 + slant / 2.0, top), egui::pos2(cx + 4.0 + slant / 2.0, top)], Stroke::new(1.3, col)); - ui.painter().line_segment([egui::pos2(cx + slant / 2.0, top), egui::pos2(cx - slant / 2.0, bot)], Stroke::new(1.3, col)); - } else { - ui.painter().galley(pos, g, col); - } - if i == 4 { - ui.painter().line_segment([egui::pos2(gr.left(), gr.bottom() - 2.0), egui::pos2(gr.right(), gr.bottom() - 2.0)], Stroke::new(1.0, col)); - } - if i == 5 { - ui.painter() - .line_segment([egui::pos2(gr.left() - 1.0, gr.center().y), egui::pos2(gr.right() + 1.0, gr.center().y)], Stroke::new(1.0, col)); - } - }); - if clicked { - apply(app, ui.ctx(), props); - } - } - }); - ui.add_space(ROW_GAP); - opentype_row(app, ui, &c, full); - ui.add_space(ROW_GAP); - } - if paragraph && section(ui, "paragraph", tl!("Paragraph")) { - use photocraft_doc::text::TextAlign as A; - let full = ui.available_width(); - let w = field_width(full, 2, LABEL_W); - let items = [ - ("left", tl!("Left align text"), A::Left), - ("center", tl!("Center text"), A::Center), - ("right", tl!("Right align text"), A::Right), - ("justifyLeft", tl!("Justify last left"), A::JustifyLeft), - ("justifyCenter", tl!("Justify last centered"), A::JustifyCenter), - ("justifyRight", tl!("Justify last right"), A::JustifyRight), - ("justifyAll", tl!("Justify all"), A::JustifyAll), - ]; - let cw = cell_width(full, items.len()); - // Justification needs a paragraph box or area type: on point text Photoshop greys the four - // justify buttons (#7713). - // The panel formats the layer being typed in, else every selected type layer. - let point = match formatting_params(app) { - Some(p) => p.get("layers").and_then(serde_json::Value::as_array).map_or_else( - || p.get("layer").and_then(serde_json::Value::as_u64).into_iter().collect::>(), - |ids| ids.iter().filter_map(serde_json::Value::as_u64).collect(), - ), - None => Vec::new(), - } - .into_iter() - .any(|layer| { - let shape = app.session.active().and_then(|s| text_layer(&s.doc, LayerId(layer)).map(|t| t.shape.clone())); - !matches!(shape, Some(photocraft_doc::text::TextShape::Box { .. } | photocraft_doc::text::TextShape::Area { .. })) - }); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - for (key, tip, a) in items { - let justify = !matches!(a, A::Left | A::Center | A::Right); - let clicked = ui - .add_enabled_ui(!(point && justify), |ui| { - toggle_cell(ui, cw, para.align == a, tip, |ui, r, col| { - // The glyph keeps its size; the cell grows around it. - let g = egui::Rect::from_center_size(r.center(), egui::vec2(12.0, 10.0)); - let col = if !ui.is_enabled() || para.align == a { col } else { t.icon }; - align_glyph(ui.painter(), g, a, col); - }) - }) - .inner; - if clicked { - apply(app, ui.ctx(), json!({"align": key})); - } - } - }); - ui.add_space(ROW_GAP); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - for (key, tip, d) in direction_items() { - let clicked = toggle_cell(ui, cw, para.direction == d, tip, |ui, r, col| { - let g = egui::Rect::from_center_size(r.center(), egui::vec2(14.0, 16.0)); - direction_glyph(ui.painter(), g, d, col); - }); - if clicked { - apply(app, ui.ctx(), json!({"direction": key})); - } - } - }); - ui.add_space(ROW_GAP); - row(ui, &mut |ui| { - if let Some(v) = num_field(ui, "→|", "Indent left margin", para.start_indent_pt * u, -1296.0 * u..=1296.0 * u, unit, w) { - apply(app, ui.ctx(), json!({"startIndent": v / u})); - } - if let Some(v) = num_field(ui, "|←", "Indent right margin", para.end_indent_pt * u, -1296.0 * u..=1296.0 * u, unit, w) { - apply(app, ui.ctx(), json!({"endIndent": v / u})); - } - }); - row(ui, &mut |ui| { - if let Some(v) = num_field(ui, "¶→", "Indent first line", para.first_line_indent_pt * u, -1296.0 * u..=1296.0 * u, unit, w) { - apply(app, ui.ctx(), json!({"firstLineIndent": v / u})); - } - }); - row(ui, &mut |ui| { - if let Some(v) = num_field(ui, "↑¶", "Add space before paragraph", para.space_before_pt * u, 0.0 * u..=1296.0 * u, unit, w) { - apply(app, ui.ctx(), json!({"spaceBefore": v / u})); - } - if let Some(v) = num_field(ui, "¶↓", "Add space after paragraph", para.space_after_pt * u, 0.0 * u..=1296.0 * u, unit, w) { - apply(app, ui.ctx(), json!({"spaceAfter": v / u})); - } - }); - // Hyphenate is stored (⌥⇧⌘H / PSD AutoHyphenate) but layout never breaks words (#6710). - ui.add_space(ROW_GAP); - } -} - -/// Type Options: anti-aliasing and orientation of the whole layer (the Type menu's commands). -fn type_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - use crate::props_layout::{COL_GAP, LABEL_GAP}; - let Some((layer, _)) = target(app) else { return }; - let Some((aa, vertical)) = app - .session - .active() - .and_then(|st| text_layer(&st.doc, LayerId(layer))) - .map(|t| (photocraft_engine::type_extra_cmds::aa_name(t.antialias).to_string(), t.orientation == photocraft_doc::text::Orientation::Vertical)) - else { - return; - }; - if !crate::props_layout::section(ui, "typeOptions", "Type Options") { - return; - } - let full = ui.available_width(); - let mut run: Option = None; - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = COL_GAP; - // Anti-aliasing dropdown (aₐ glyph label), then the two orientation toggles. - let orient_w = 2.0 * 28.0 + 2.0; - let dd_w = (full - crate::props_layout::LABEL_W - LABEL_GAP - COL_GAP - orient_w).max(60.0); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = LABEL_GAP; - let t = crate::theme::Tokens::get(ui.ctx()); - let (r, resp) = ui.allocate_exact_size(egui::vec2(crate::props_layout::LABEL_W, 22.0), egui::Sense::hover()); - ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, "aa", crate::theme::semibold(11.0), t.text_dim); - resp.on_hover_text(tl!("Anti-aliasing method")); - let mut cur = aa.clone(); - let opts: Vec<(String, &str)> = ["none", "sharp", "crisp", "strong", "smooth", "windowsLcd", "windows"] - .into_iter() - .filter_map(|k| photocraft_engine::commands::find(&format!("type.antiAlias.{k}")).map(|c| (k.to_string(), c.label))) - .collect(); - if crate::widgets::dropdown(ui, "props-type-aa", tl!("Anti-aliasing method"), &mut cur, &opts, dd_w) { - run = Some(format!("type.antiAlias.{cur}")); - } - }); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - for (key, tip, on) in [("horizontal", "Horizontal type", !vertical), ("vertical", "Vertical type", vertical)] { - let clicked = toggle_cell(ui, 28.0, on, tip, |ui, r, col| { - let g = egui::Rect::from_center_size(r.center(), egui::vec2(12.0, 12.0)); - let s = Stroke::new(1.3, col); - if key == "horizontal" { - ui.painter().line_segment([g.left_top(), g.right_top()], s); - ui.painter().line_segment([g.center_top(), g.center_bottom()], s); - } else { - ui.painter().line_segment([g.left_top(), g.left_bottom()], s); - ui.painter().line_segment([g.left_center(), g.right_center()], s); - } - }); - if clicked && !on { - run = Some(format!("type.orientation.{key}")); - } - } - }); - }); - ui.add_space(crate::theme::ROW_GAP); - if let Some(id) = run - && let Some(params) = formatting_params(app) - && let Err(e) = app.run(&id, params) - { - app.ui.status = e; - app.ui.status_error = true; - } -} - -/// Cancel the editing session: undo it back to where it started (removes a new layer). -pub fn cancel(app: &mut PhotocraftApp) { - crate::type_transform::reset(app); - let Some(ed) = app.ui.text_edit.take() else { return }; - app.type_ime.clear_preedit(); - if let Some(tool) = app.ui.text_edit_return_tool.take() - && app.ui.tool.is_type() - { - app.ui.tool = tool; - } - undo_session(app, &ed); -} - -/// Undo the session's history step, if it is still the latest. -fn undo_session(app: &mut PhotocraftApp, ed: &TextEdit) { - let coalesced = app.session.active().is_some_and(|s| s.coalesce.as_deref() == Some(ed.session.as_str())); - if coalesced { - let _ = app.run("edit.undo", json!({})); - } -} - #[cfg(test)] mod canvas_tests; diff --git a/crates/ui-egui/src/type_tool/defaults.rs b/crates/ui-egui/src/type_tool/defaults.rs new file mode 100644 index 0000000000..05fea9244c --- /dev/null +++ b/crates/ui-egui/src/type_tool/defaults.rs @@ -0,0 +1,253 @@ +use super::editing::edit_home; +use super::*; + +/// Representative for the displayed properties: the edit layer, else a selected type layer. +pub(crate) fn target(app: &PhotocraftApp) -> Option<(u64, Option<[usize; 2]>)> { + if let Some(ed) = &app.ui.text_edit { + let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor)); + return Some((ed.layer, (a < b).then_some([a, b]))); + } + let st = app.session.active()?; + let id = st + .active_layer + .filter(|id| text_layer(&st.doc, *id).is_some()) + .or_else(|| st.selected_layers().into_iter().find(|id| text_layer(&st.doc, *id).is_some()))?; + Some((id.0, None)) +} + +/// The type layer whose properties the Type controls and dialogs show (see [`target`]). +pub(crate) fn target_text(app: &PhotocraftApp) -> Option<&TextLayer> { + let (id, _) = target(app)?; + text_layer(&target_doc(app)?.doc, LayerId(id)) +} + +/// The document [`target`]'s layer is in: a text edit's own, which can stay in a background +/// document where the same layer id may name another layer, else the active one. +pub(super) fn target_doc(app: &PhotocraftApp) -> Option<&photocraft_engine::DocState> { + match &app.ui.text_edit { + Some(ed) => app.session.documents().get(edit_home(app, ed)?), + None => app.session.active(), + } +} + +/// Snapshot the mutation scope separately from the representative used to display properties. +/// An inline edit remains on its layer/range; layer selection formats every selected type layer. +pub(crate) fn formatting_params(app: &PhotocraftApp) -> Option { + if let Some(ed) = &app.ui.text_edit { + let mut params = json!({"layer": ed.layer, "coalesce": ed.session}); + let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor)); + if a < b { + params["range"] = json!([a, b]); + } + return Some(params); + } + let st = app.session.active()?; + let layers: Vec = st.selected_layers().into_iter().filter(|id| text_layer(&st.doc, *id).is_some()).map(|id| id.0).collect(); + (!layers.is_empty()).then(|| json!({"layers": layers})) +} + +/// Scale of the target layer's transform. Like Photoshop, sizes show and edit as the layer +/// appears: a 12 pt layer scaled 200% (common in PSDs) reads 24 pt. +pub(super) fn shown_scale(app: &PhotocraftApp) -> f32 { + let Some((id, _)) = target(app) else { return 1.0 }; + let Some(t) = app.session.active().and_then(|st| text_layer(&st.doc, LayerId(id))) else { return 1.0 }; + let m = t.transform.m; + let k = (m[0] * m[3] - m[1] * m[2]).abs().sqrt() as f32; + if k.is_finite() && k > 1e-3 { k } else { 1.0 } +} + +/// The display unit for type metrics (Preferences ▸ Units & Rulers ▸ Type): the multiplier from +/// the model's points to the unit, and its label. Pixels follow the document's resolution. +pub(crate) fn type_unit(app: &PhotocraftApp) -> (f32, &'static str) { + let dpi = app.session.active().map_or(72.0, |d| d.doc.resolution_dpi.max(1.0)); + match app.session.prefs().units_and_rulers.type_units { + photocraft_engine::prefs::TypeUnit::Points => (1.0, "pt"), + photocraft_engine::prefs::TypeUnit::Pixels => (dpi / 72.0, "px"), + photocraft_engine::prefs::TypeUnit::Millimeters => (25.4 / 72.0, "mm"), + } +} + +/// Coalesce key while a field is being scrubbed: every step of one drag shares one history step +/// (Photoshop's single step per scrub, #124). Unique per press, so two drags are two steps. +fn drag_key(ctx: &egui::Context) -> Option { + let id = ctx.dragged_id()?; + let t = ctx.input(|i| i.pointer.press_start_time())?; + Some(format!("type-drag-{}-{}", id.value(), t.to_bits())) +} + +/// The styles a new Type-tool layer will receive. Use the same command parameters for the +/// panels and creation so defaults also survive action recording/replay. The older options-bar +/// fields remain authoritative, and text colour continues to follow the foreground colour. +pub(super) fn default_style_params(app: &PhotocraftApp) -> serde_json::Value { + let o = &app.ui.tool_options; + let mut p = json!({}); + // Settings are editable JSON: only recognized formatting keys may reach type.create. + // In particular a stray `text`, `box`, or `coalesce` key must not become a create parameter. + let (mut c, mut para) = (photocraft_doc::text::CharStyle::default(), photocraft_doc::text::ParagraphStyle::default()); + for (key, value) in &o.type_style_defaults { + // These belong to the existing options-bar fields. Apart from being redundant, + // parsing a saved font key here would wait for the background font scan. + if matches!(key.as_str(), "font" | "family" | "fontStyle" | "weight" | "italic" | "postscriptName") { + continue; + } + let one = json!({ (key): value }); + if !finite_style_value(value) + || photocraft_engine::type_cmds::check_size_tracking(&one).is_err() + || photocraft_engine::type_cmds::check_kerning(&one).is_err() + { + continue; + } + if photocraft_engine::type_cmds::apply_char_props(&mut c, &one) | photocraft_engine::type_cmds::apply_para_props(&mut para, &one) { + p[key] = value.clone(); + } + } + p["font"] = json!(o.type_font); + p["fontStyle"] = json!(o.type_style); + p["size"] = json!(o.type_size); + p["align"] = json!(o.type_align); + p["direction"] = json!(o.type_direction); + p["color"] = json!(hex(app.session.tools.foreground)); + p +} + +/// Style numbers become f32 in the engine. JSON itself permits finite f64 values too large +/// for that conversion; a hand-edited setting must not inject infinity into a new layer. +/// Style collections (features, axes, colour) contain only scalar values, so no recursion. +fn finite_style_value(value: &serde_json::Value) -> bool { + let scalar = |v: &serde_json::Value| match v { + serde_json::Value::Number(n) => n.as_f64().is_some_and(|n| (n as f32).is_finite()), + serde_json::Value::Array(_) | serde_json::Value::Object(_) => false, + _ => true, + }; + match value { + serde_json::Value::Array(v) => v.iter().all(scalar), + serde_json::Value::Object(v) => v.values().all(scalar), + v => scalar(v), + } +} + +pub(super) fn default_styles(app: &PhotocraftApp) -> (photocraft_doc::text::CharStyle, photocraft_doc::text::ParagraphStyle) { + let (mut c, mut para) = app.session.type_defaults.clone().unwrap_or_default(); + let mut p = default_style_params(app); + // The saved panels can appear on the very first frame. Style parsing resolves the named + // font through shared(), which waits for the font scan; display the saved names meanwhile, + // and let fonts_ready/axis_sliders expose the font controls when try_shared is ready. + if photocraft_text::try_shared().is_none() { + c.font_family = app.ui.tool_options.type_font.clone(); + c.font_style = app.ui.tool_options.type_style.clone(); + c.postscript_name = None; + if let Some(p) = p.as_object_mut() { + p.remove("font"); + p.remove("fontStyle"); + } + } + photocraft_engine::type_cmds::apply_char_props(&mut c, &p); + photocraft_engine::type_cmds::apply_para_props(&mut para, &p); + (c, para) +} + +/// Change tool defaults without creating a document edit. The engine owns the style schema; +/// keep its property names rather than maintaining another style parser in the shell. +pub(super) fn apply_defaults(app: &mut PhotocraftApp, props: &serde_json::Value) { + let Some(props) = props.as_object() else { return }; + let o = &mut app.ui.tool_options; + for (key, value) in props { + match key.as_str() { + "font" => { + if let Some(v) = value.as_str() { + o.type_font = v.into(); + } + } + "fontStyle" => { + if let Some(v) = value.as_str() { + o.type_style = v.into(); + // A newly chosen named style replaces a weight-axis setting, as it does + // in apply_char_props. Other axes retain their independently chosen values. + if let Some(axes) = o.type_style_defaults.get_mut("variations").and_then(serde_json::Value::as_object_mut) { + axes.remove("wght"); + } + } + } + "size" => { + if let Some(v) = value.as_f64() { + o.type_size = v as f32; + } + } + "align" => { + if let Some(v) = value.as_str() { + o.type_align = v.into(); + } + } + "direction" => { + if let Some(v) = value.as_str() { + o.type_direction = v.into(); + } + } + "metricsAsShown" => {} // Defaults have no layer transform. + "features" | "variations" => { + if let Some(patch) = value.as_object() { + let old = o.type_style_defaults.entry(key.clone()).or_insert_with(|| json!({})); + if let Some(old) = old.as_object_mut() { + old.extend(patch.clone()); + } else { + *old = value.clone(); + } + } + } + _ => { + o.type_style_defaults.insert(key.clone(), value.clone()); + } + } + } +} + +/// Apply only the supplied properties to the text-edit scope or selected type layers; without +/// a type target, prepare the defaults for the next layer instead. +pub(super) fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, props: serde_json::Value) { + let Some(mut p) = formatting_params(app) else { + apply_defaults(app, &props); + return; + }; + if let Some(props) = props.as_object() { + for (key, value) in props { + p[key] = value.clone(); + } + } + if let Some(key) = app.ui.text_edit.as_ref().map(|ed| ed.session.clone()).or_else(|| drag_key(ctx)) { + p["coalesce"] = json!(key); + } + let _ = app.run("type.setStyle", p); +} + +/// `props` aimed at the type target: its layer, the selected characters while typing, and the +/// typing session's undo step. `None` without a type target. +pub(crate) fn with_target(app: &PhotocraftApp, mut props: serde_json::Value) -> Option { + let (layer, range) = target(app)?; + props["layer"] = json!(layer); + if let Some(r) = range { + props["range"] = json!(r); + } + if let Some(key) = app.ui.text_edit.as_ref().map(|ed| ed.session.clone()) { + props["coalesce"] = json!(key); + } + Some(props) +} + +/// Open the shared Color Picker with a snapshot of the text target. Sampling or cancelling +/// the dialog never changes the text selection, tool colours, or document history. +pub fn open_color_picker(app: &mut PhotocraftApp, rgb: [f32; 3]) -> u64 { + if let Some(params) = formatting_params(app) { + crate::color_picker_ui::open_for_command(app, "Color Picker (Text Color)", rgb, "type.setStyle", params) + } else { + crate::color_picker_ui::open(app, "foreground") + } +} + +/// While characters are selected in a type layer, a new foreground colour (Color and Swatches +/// panels, the Color Picker) recolours them, in the editing session's history step. +pub fn foreground_changed(app: &mut PhotocraftApp) { + let Some((layer, Some(range))) = target(app) else { return }; + let Some(ed) = app.ui.text_edit.as_ref() else { return }; + let p = json!({"layer": layer, "range": range, "color": hex(app.session.tools.foreground), "coalesce": ed.session}); + let _ = app.run("type.setStyle", p); +} diff --git a/crates/ui-egui/src/type_tool/editing.rs b/crates/ui-egui/src/type_tool/editing.rs new file mode 100644 index 0000000000..33d49ccf4c --- /dev/null +++ b/crates/ui-egui/src/type_tool/editing.rs @@ -0,0 +1,470 @@ +use super::ime::interrupt_incoming; +use super::ime_edit::note_ime_application_change; +use super::layout::{hit_layer, hit_offset, shows_own_layout}; +use super::*; + +/// Start editing an existing type layer. Like Photoshop, editing shows the text as the type +/// engine lays it out, so a PSD layer is re-rendered first (inside the edit session's history +/// step, so Cancel brings Photoshop's pixels back). +pub(super) fn begin_edit(app: &mut PhotocraftApp, id: LayerId, key: &str) -> Result<(), String> { + let st = app.session.active().ok_or("no document open")?; + let doc = st.doc.clone(); + if let Some(t) = text_layer(&doc, id) + && !shows_own_layout(&doc, t) + { + app.run("type.edit", json!({"layer": id.0, "coalesce": key}))?; + } + Ok(()) +} + +/// Edit the active type layer from its thumbnail, selecting all text like Photoshop. Reuse the +/// current session when already editing it, so Cancel and undo still cover the whole edit. +pub fn edit_active(app: &mut PhotocraftApp) -> Result<(), String> { + let st = app.session.active().ok_or("no document open")?; + let id = st.active_layer.ok_or("no active layer")?; + let n = text_layer(&st.doc, id).ok_or("active layer is not a type layer")?.text.chars().count(); + if app.ui.text_edit.as_ref().is_none_or(|ed| ed.layer != id.0) { + commit(app); + let key = session_key(app); + begin_edit(app, id, &key)?; + app.ui.text_edit = Some(TextEdit { + layer: id.0, + document: active_doc_id(app), + caret: n, + anchor: 0, + session: key, + created: false, + mask: false, + dragging: false, + resize: None, + preedit: None, + }); + } else { + let mut cancelled = false; + if let Some(ed) = app.ui.text_edit.as_mut() { + ed.anchor = 0; + ed.caret = n; + // Re-entering the same session moves the caret away from the composition: cancel it + // rather than reusing a range that no longer describes the text. + cancelled = ed.preedit.take().is_some(); + } + if cancelled { + app.type_ime.clear_preedit(); + interrupt_incoming(app); + app.type_ime.request_interrupt(); + } + } + let vertical = app.session.active().and_then(|st| text_layer(&st.doc, id)).is_some_and(|t| t.orientation == photocraft_doc::text::Orientation::Vertical); + app.ui.text_edit_return_tool = None; + app.ui.tool = if vertical { crate::state::Tool::VerticalType } else { crate::state::Tool::Type }; + app.ui.mask_target = false; + app.ui.vector_mask_target = false; + Ok(()) +} + +/// Double-click with the Move tool (Photoshop CC 2019+): edit the type layer under document +/// point (`x`, `y`) with the caret on the glyph there, switching to the Type tool. False when no +/// type is there. +pub fn edit_at(app: &mut PhotocraftApp, x: f64, y: f64) -> bool { + let Some(id) = hit_layer(app, x, y) else { return false }; + let previous_tool = app.ui.tool; + commit(app); + if app.session.select_layer(id).is_err() { + return false; + } + let key = session_key(app); + if begin_edit(app, id, &key).is_err() { + return false; + } + let off = hit_offset(app, id, x, y); + app.ui.text_edit = Some(TextEdit { + layer: id.0, + document: active_doc_id(app), + caret: off, + anchor: off, + session: key, + created: false, + mask: false, + dragging: false, + resize: None, + preedit: None, + }); + let vertical = app.session.active().and_then(|st| text_layer(&st.doc, id)).is_some_and(|t| t.orientation == photocraft_doc::text::Orientation::Vertical); + if !previous_tool.is_type() { + app.ui.text_edit_return_tool = Some(previous_tool); + } + app.ui.tool = if vertical { crate::state::Tool::VerticalType } else { crate::state::Tool::Type }; + app.ui.mask_target = false; + app.ui.vector_mask_target = false; + true +} + +/// Copy the selected characters to the system clipboard. Returns the copied range. Shared by the +/// clipboard Copy event and Edit > Copy during a type edit. +pub(crate) fn copy_selection(app: &PhotocraftApp, ctx: &egui::Context) -> Option<[usize; 2]> { + let [a, b] = selected_range(app)?; + let ed = app.ui.text_edit.as_ref()?; + let text = text_layer(&app.session.active()?.doc, LayerId(ed.layer))?; + ctx.copy_text(text.text.chars().skip(a).take(b - a).collect()); + Some([a, b]) +} + +/// Edit > Paste during a type edit: ask the window for the clipboard text, which arrives as a +/// Paste event next frame and replaces the selection there (like ⌘V). +pub(crate) fn request_paste(ctx: &egui::Context) { + ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste); +} + +/// Select > All during a type edit selects every character (like ⌘A). +pub(crate) fn select_all(app: &mut PhotocraftApp) { + let Some(n) = app.ui.text_edit.as_ref().and_then(|ed| current_text(app, LayerId(ed.layer))).map(|t| t.chars().count()) else { return }; + if let Some(e) = app.ui.text_edit.as_mut() { + (e.anchor, e.caret) = (0, n); + } +} + +/// Shared by the clipboard Cut event and Edit > Cut during a type edit. +pub(crate) fn cut_selection(app: &mut PhotocraftApp, ctx: &egui::Context) { + let Some([a, b]) = copy_selection(app, ctx) else { return }; + if let Some(ed) = app.ui.text_edit.as_mut() { + ed.anchor = a; + ed.caret = b; + } + insert(app, ""); +} + +/// Replace the selection with `s`. +pub(super) fn insert(app: &mut PhotocraftApp, s: &str) { + let Some(ed) = app.ui.text_edit.clone() else { return }; + let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor)); + let s = s.replace("\r\n", "\n").replace('\r', "\n"); + if a == b && s.is_empty() { + return; + } + crate::type_transform::finish(app); + let applied = app.run("type.edit", json!({"layer": ed.layer, "replace": {"start": a, "end": b, "text": s}, "coalesce": ed.session})).is_ok(); + if applied { + let mut cancelled = false; + if let Some(e) = app.ui.text_edit.as_mut() { + e.caret = a + s.chars().count(); + e.anchor = e.caret; + // An application edit invalidates a live composition: its recorded range no longer + // describes the text, and its pending native commit must not be applied here. + cancelled = e.preedit.take().is_some(); + } + if cancelled { + app.type_ime.clear_preedit(); + interrupt_incoming(app); + app.type_ime.request_interrupt(); + } + // Ordinary typing, paste, cut and deletion are application-origin, never IME receipts. + note_ime_application_change(app, &ed); + } +} + +/// Typed text (not a paste): with Preferences ▸ Type ▸ Use Smart Quotes, straight quotes become +/// typographic (Photoshop does not rewrite pasted text). +pub(super) fn insert_typed(app: &mut PhotocraftApp, s: &str) { + if !app.session.prefs().type_.smart_quotes { + return insert(app, s); + } + let prev = app.ui.text_edit.clone().and_then(|ed| { + let at = ed.caret.min(ed.anchor); + let text = current_text(app, LayerId(ed.layer))?; + (at > 0).then(|| text.chars().nth(at - 1)).flatten() + }); + insert(app, &smart_quotes(s, prev)); +} + +/// Straight quotes become “ ” and ‘ ’: opening after whitespace, a bracket or a dash (or at the +/// start of the text), closing next to a letter or another quote. `prev` is the character before +/// the caret. +pub(super) fn smart_quotes(s: &str, mut prev: Option) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + let c = match c { + '"' => { + if opens_quote(prev) { + '\u{201c}' + } else { + '\u{201d}' + } + } + '\'' => { + if opens_quote(prev) { + '\u{2018}' + } else { + '\u{2019}' + } + } + _ => c, + }; + out.push(c); + prev = Some(c); + } + out +} + +fn opens_quote(prev: Option) -> bool { + prev.is_none_or(|p| p.is_whitespace() || matches!(p, '(' | '[' | '{' | '-' | '\u{2013}' | '\u{2014}')) +} + +/// Alt+←/→: kern the pair before the caret by `by` (1/1000 em). No pair (caret at a text or line +/// edge): nothing happens, like Photoshop. Not coalesced: one history step per press. +pub(super) fn kern_pair(app: &mut PhotocraftApp, id: LayerId, caret: usize, by: f32) { + let Some(text) = current_text(app, id) else { return }; + let before = caret.checked_sub(1).and_then(|i| text.chars().nth(i)); + let after = text.chars().nth(caret); + if before.is_none_or(|c| c == '\n') || after.is_none_or(|c| c == '\n') { + return; + } + crate::type_transform::finish(app); + let _ = app.run("type.edit", json!({"layer": id.0, "kernPair": {"at": caret, "by": by}})); +} + +/// A character style the type editor's ⇧⌘ keys toggle (Photoshop: ⇧⌘K All Caps, ⇧⌘U +/// Underline, ⇧⌘B Faux Bold, ⇧⌘I Faux Italic, ⇧⌘/ Strikethrough). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CharToggle { + AllCaps, + Underline, + FauxBold, + FauxItalic, + Strikethrough, +} + +impl CharToggle { + fn is_on(self, st: &photocraft_doc::text::CharStyle) -> bool { + match self { + Self::AllCaps => st.caps == photocraft_doc::text::Caps::AllCaps, + Self::Underline => st.underline, + Self::FauxBold => st.faux_bold, + Self::FauxItalic => st.faux_italic, + Self::Strikethrough => st.strikethrough, + } + } + + fn param(self, on: bool) -> (&'static str, serde_json::Value) { + match self { + Self::AllCaps => ("caps", json!(if on { "all" } else { "normal" })), + Self::Underline => ("underline", json!(on)), + Self::FauxBold => ("fauxBold", json!(on)), + Self::FauxItalic => ("fauxItalic", json!(on)), + Self::Strikethrough => ("strikethrough", json!(on)), + } + } +} + +/// The character styles of the selection, or of the typing style when the text is empty. Empty +/// when nothing is selected in non-empty text. +fn selected_styles(t: &TextLayer, a: usize, b: usize) -> Vec { + let runs = t.char_runs(); + if t.text.is_empty() { + return runs.into_iter().take(1).map(|r| r.style).collect(); + } + let (ba, bb) = byte_range(&t.text, a, b); + let mut at = 0usize; + let mut out = Vec::new(); + for r in runs { + let (rs, re) = (at, at.saturating_add(r.len)); + at = re; + if rs < bb && re > ba { + out.push(r.style); + } + } + out +} + +/// The character range the type editor's formatting keys act on: the selection, or the empty +/// text's typing style. `None` for a collapsed caret in non-empty text: Photoshop would style the +/// next characters typed, which the document model can't hold apart from the text, so the keys +/// do nothing there (rather than restyle a word the user didn't select). +fn format_range(app: &PhotocraftApp, ed: &TextEdit) -> Option<(usize, usize)> { + let t = text_layer(&app.session.active()?.doc, LayerId(ed.layer))?; + let n = t.text.chars().count(); + let (a, b) = (ed.caret.min(ed.anchor).min(n), ed.caret.max(ed.anchor).min(n)); + (a < b || n == 0).then_some((a, b)) +} + +/// One `type.setStyle` step on the edited layer's `range`, kept apart from the typing session's +/// coalesced edit so Undo takes back one key press at a time (as with kerning). +fn set_style(app: &mut PhotocraftApp, ed: &TextEdit, range: (usize, usize), mut p: serde_json::Value) { + crate::type_transform::finish(app); + p["layer"] = json!(ed.layer); + p["range"] = json!([range.0, range.1]); + if let Err(e) = app.run("type.setStyle", p) { + app.ui.status = e; + app.ui.status_error = true; + } +} + +/// ⇧⌘K/U/B/I/: flips a character style over the selection: off when every selected character +/// already has it, else on. +pub(crate) fn toggle_char_style(app: &mut PhotocraftApp, which: CharToggle) { + let Some(ed) = app.ui.text_edit.clone() else { return }; + let Some(range) = format_range(app, &ed) else { return }; + let Some(styles) = app.session.active().and_then(|s| text_layer(&s.doc, LayerId(ed.layer))).map(|t| selected_styles(t, range.0, range.1)) else { + return; + }; + let on = !styles.iter().all(|st| which.is_on(st)); + let (key, value) = which.param(on); + set_style(app, &ed, range, json!({ key: value })); +} + +/// ⌥↑/↓ leading, ⇧⌥↑/↓ baseline shift and ⌥←/→ tracking: steps every selected character from its +/// own value (`key` is `leadingBy`, `baselineShiftBy` or `trackingBy`). +pub(crate) fn step_char_metric(app: &mut PhotocraftApp, key: &str, by: f32) { + let Some(ed) = app.ui.text_edit.clone() else { return }; + let Some(range) = format_range(app, &ed) else { return }; + // Leading steps in the points the Character panel shows for a scaled layer. + set_style(app, &ed, range, json!({ key: by, "metricsAsShown": key == "leadingBy" })); +} + +/// ⌥⇧⌘H: flips Hyphenate for the paragraphs the selection (or the caret) is in: off when all of +/// them hyphenate, else on. +pub(crate) fn toggle_hyphenate(app: &mut PhotocraftApp) { + let Some(ed) = app.ui.text_edit.clone() else { return }; + let Some(t) = app.session.active().and_then(|s| text_layer(&s.doc, LayerId(ed.layer))) else { return }; + let n = t.text.chars().count(); + let (a, b) = (ed.caret.min(ed.anchor).min(n), ed.caret.max(ed.anchor).min(n)); + let (ba, bb) = byte_range(&t.text, a, b); + let len = t.text.len(); + let mut at = 0usize; + let mut all = true; + let mut any = false; + for r in t.paragraph_runs() { + let (ps, pe) = (at, at.saturating_add(r.len)); + at = pe; + let touches = if ba == bb { ps <= ba && (ba < pe || pe >= len) } else { ps < bb && pe > ba }; + if touches { + any = true; + all &= r.style.hyphenate; + } + } + let on = !(any && all); + set_style(app, &ed, (a, b), json!({ "hyphenate": on })); +} + +/// End the editing session. A new layer left empty is deleted; a new layer is named after its text. +pub fn commit(app: &mut PhotocraftApp) { + commit_with(app, egui::Modifiers::NONE); +} + +/// [`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) { + 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); + }; + 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); + if let Some(i) = current { + app.session.set_active(i); + } + } + Some(_) => commit_here(app, mods), + // Its document closed: there is nothing to commit into, and the layer id may name a + // layer of another document. + None => { + crate::type_transform::reset(app); + app.ui.text_edit = None; + app.ui.text_edit_return_tool = None; + app.type_ime.clear_preedit(); + } + } +} + +/// Index of the document an edit belongs to; `None` once it is closed. +pub(super) fn edit_home(app: &PhotocraftApp, ed: &TextEdit) -> Option { + match ed.document { + Some(d) => app.session.documents().iter().position(|st| st.doc.id.0 == d), + None => app.session.active_index(), + } +} + +/// [`commit_with`] in the active document, which is the edit's own. +fn commit_here(app: &mut PhotocraftApp, mods: egui::Modifiers) { + if app.ui.tool.is_type() { + crate::type_transform::finish(app); + } + crate::type_transform::reset(app); + let Some(ed) = app.ui.text_edit.take() else { return }; + app.type_ime.clear_preedit(); + if let Some(tool) = app.ui.text_edit_return_tool.take() + && app.ui.tool.is_type() + { + app.ui.tool = tool; + } + 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); + if !text.trim().is_empty() + && let Err(e) = app.run("type.createSelection", json!({"layer": ed.layer, "removeLayer": true, "operation": operation, "coalesce": ed.session})) + { + app.ui.status = e; + app.ui.status_error = true; + } + if current_text(app, LayerId(ed.layer)).is_some() { + undo_session(app, &ed); + } + return; + } + if text.trim().is_empty() && ed.created { + let _ = app.run("layer.delete", json!({"layer": ed.layer})); + } else if ed.created { + let name = photocraft_engine::type_cmds::layer_name(&text); + let _ = app.run("type.edit", json!({"layer": ed.layer, "name": name, "coalesce": ed.session})); + } +} + +/// Commit the edit once its layer is no longer the one worked on (#6483): another layer became +/// active (a Layers panel menu, the canvas layer picker, automation) or another document did (a +/// tab, File ▸ New/Open). Photoshop commits then; left open, the session took single-key +/// shortcuts as typing and typed into whichever document was active. +pub fn end_if_left(app: &mut PhotocraftApp) { + let Some(ed) = app.ui.text_edit.as_ref() else { return }; + let layer = LayerId(ed.layer); + if edit_home(app, ed).is_none_or(|h| Some(h) != app.session.active_index()) { + return commit(app); + } + let Some(st) = app.session.active() else { return }; + if st.active_layer == Some(layer) { + return; + } + // The selection just made stands: ending an empty Type Mask undoes its session, and undo + // restores the selection from before it. + let chosen = (st.active_layer, st.selected_layers.clone(), st.layer_anchor); + commit(app); + let moved = app.session.active().is_some_and(|st| (st.active_layer, &st.selected_layers, st.layer_anchor) != (chosen.0, &chosen.1, chosen.2)); + if moved { + let _ = app.session.restore_layer_selection(chosen.0, &chosen.1, chosen.2); + } +} + +/// Cancel the editing session: undo it back to where it started (removes a new layer). +pub fn cancel(app: &mut PhotocraftApp) { + crate::type_transform::reset(app); + let Some(ed) = app.ui.text_edit.take() else { return }; + app.type_ime.clear_preedit(); + if let Some(tool) = app.ui.text_edit_return_tool.take() + && app.ui.tool.is_type() + { + app.ui.tool = tool; + } + undo_session(app, &ed); +} + +/// Undo the session's history step, if it is still the latest. +fn undo_session(app: &mut PhotocraftApp, ed: &TextEdit) { + let coalesced = app.session.active().is_some_and(|s| s.coalesce.as_deref() == Some(ed.session.as_str())); + if coalesced { + let _ = app.run("edit.undo", json!({})); + } +} diff --git a/crates/ui-egui/src/type_tool/fonts.rs b/crates/ui-egui/src/type_tool/fonts.rs new file mode 100644 index 0000000000..4bb5bf1970 --- /dev/null +++ b/crates/ui-egui/src/type_tool/fonts.rs @@ -0,0 +1,559 @@ +use super::defaults::apply; +use super::*; + +/// Font families: bundled, system, and those the host serves (`photocraft_text::served`, fetched +/// when picked). Cached until the shared engine registers fonts or the served catalog changes. +pub fn families() -> Arc> { + type Cached = Option<((u64, u64), Arc>)>; + static FAMILIES: std::sync::Mutex = std::sync::Mutex::new(None); + let key = (photocraft_text::fonts::shared_generation(), photocraft_text::served::generation()); + let mut cached = FAMILIES.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((k, v)) = cached.as_ref() + && *k == key + { + return v.clone(); + } + let mut v = photocraft_text::shared().lock().map(|mut e| e.fonts.families()).unwrap_or_default(); + for f in photocraft_text::served::families() { + if !v.contains(&f) { + v.push(f); + } + } + v.sort_by_key(|s| s.to_lowercase()); + let v = Arc::new(v); + *cached = Some((key, v.clone())); + v +} + +/// Where [`sync_font_names`] leaves the font menus' localized labels for this frame. +pub(super) fn font_labels_id() -> egui::Id { + egui::Id::unique("photocraft-font-menu-localized-names") +} + +/// Preferences ▸ Type ▸ Show Font Names in English: when off, font menus list a family that has a +/// localized (native-language) name by that name, as Photoshop does ("MS Gothic" reads +/// "MS ゴシック"). Called once a frame; the menus read the labels from the context. +pub fn sync_font_names(ctx: &egui::Context, show_in_english: bool) { + let labels = (!show_in_english).then(localized_families); + ctx.data_mut(|d| { + if let Some(labels) = labels { + d.insert_temp(font_labels_id(), labels); + } else { + d.remove::>>(font_labels_id()); + } + }); +} + +/// The fonts' localized family names, keyed by family. Cached until the shared engine registers fonts. +fn localized_families() -> Arc> { + type Cached = Option<(u64, Arc>)>; + static LOCALIZED: std::sync::Mutex = std::sync::Mutex::new(None); + let key = photocraft_text::fonts::shared_generation(); + let mut cached = LOCALIZED.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((k, v)) = cached.as_ref() + && *k == key + { + return v.clone(); + } + let v = Arc::new(photocraft_text::shared().lock().map(|mut e| e.fonts.localized_family_names()).unwrap_or_default()); + *cached = Some((key, v.clone())); + v +} + +/// The font menu's rows: each family with the label it shows (its localized name when `labels` +/// has one, else the family), matching `query` (lowercase) by either name. With localized labels +/// the rows sort by label, so the menu stays alphabetical as shown. As in Photoshop, recently +/// used families also head the menu in their own group, most recent first (Preferences ▸ Type ▸ +/// Recent Fonts), and keep their alphabetical place below it; a query shows each match once. +/// Returns the rows and how many of them form the recent group. +pub(super) fn font_menu_rows<'a>( + families: &'a [String], + labels: Option<&'a HashMap>, + query: &str, + recents: &[String], +) -> (Vec<(&'a String, &'a str)>, usize) { + let label = |f: &'a String| labels.and_then(|l| l.get(f)).map_or(f.as_str(), String::as_str); + let mut rows: Vec<(&String, &str)> = families + .iter() + .map(|f| (f, label(f))) + .filter(|(f, l)| query.is_empty() || f.to_lowercase().contains(query) || l.to_lowercase().contains(query)) + .collect(); + if labels.is_some_and(|l| !l.is_empty()) { + rows.sort_by_cached_key(|(_, l)| l.to_lowercase()); + } + if !query.is_empty() { + return (rows, 0); + } + let recent: Vec<(&String, &str)> = recents.iter().filter_map(|r| rows.iter().find(|(f, _)| *f == r).copied()).collect(); + let n = recent.len(); + (recent.into_iter().chain(rows).collect(), n) +} + +fn weight_name(w: f32) -> &'static str { + match w.round() as i32 { + ..=150 => "Thin", + 151..=250 => "ExtraLight", + 251..=350 => "Light", + 351..=450 => "Regular", + 451..=550 => "Medium", + 551..=650 => "SemiBold", + 651..=750 => "Bold", + 751..=850 => "ExtraBold", + _ => "Black", + } +} + +/// Style names available for a family: each face's actual OpenType subfamily (including numeric +/// and nonstandard ones), plus the standard weights a variable face's `wght` axis covers. +pub fn styles(family: &str) -> Vec { + let faces = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).fonts.faces(family); + let v = style_names(&faces); + if v.is_empty() { vec!["Regular".into()] } else { v } +} + +/// [`styles`] of these faces, lightest first. A variable face reports only its default instance +/// (Montserrat's is Thin), yet the layout draws any weight its `wght` axis covers, so the standard +/// weights in that range are listed too. +pub(super) fn style_names(faces: &[photocraft_text::FaceInfo]) -> Vec { + let label = |weight: f32, italic: bool| { + let name = match (weight_name(weight), italic) { + ("Regular", true) => "Italic".to_string(), + (w, true) => format!("{w} Italic"), + (w, false) => w.to_string(), + }; + (weight.round() as i32, italic, name) + }; + let mut v: Vec<(i32, bool, String)> = faces.iter().map(|f| (f.weight.round() as i32, f.italic, f.style.clone())).collect(); + for f in faces { + if let Some((_, min, _, max)) = f.axes.iter().find(|a| a.0 == "wght") { + v.extend((100..=900).step_by(100).map(|w| w as f32).filter(|w| (*min..=*max).contains(w)).map(|w| label(w, f.italic))); + } + } + v.sort(); + let mut names: Vec = Vec::new(); + for (_, _, name) in v { + if !names.contains(&name) { + names.push(name); + } + } + names +} + +/// A variable-font axis: (tag, min, default, max), as [`photocraft_text::FaceInfo::axes`]. +pub(crate) type Axis = (String, f32, f32, f32); + +/// The axes the Character section shows as sliders (#2985): those of the faces matching the +/// style's italic, else of any face. Optical size has none: it follows the type size. +pub(crate) fn slider_axes(faces: &[photocraft_text::FaceInfo], italic: bool) -> Vec { + let pick = |want: Option| { + let mut v: Vec = Vec::new(); + for f in faces.iter().filter(|f| want.is_none_or(|w| f.italic == w)) { + for a in &f.axes { + let usable = a.0 != "opsz" && a.1.is_finite() && a.3.is_finite() && a.1 < a.3; + if usable && !v.iter().any(|b| b.0 == a.0) { + v.push(a.clone()); + } + } + } + v + }; + let v = pick(Some(italic)); + if v.is_empty() { pick(None) } else { v } +} + +/// The value an axis slider shows: the style's own value for the axis, else what the layout +/// draws (the style's weight on `wght`, the axis default otherwise), within the axis range. +pub(crate) fn axis_value(c: &photocraft_doc::text::CharStyle, (tag, min, default, max): &Axis) -> f32 { + let v = c.variations.iter().find(|v| &v.axis == tag).map(|v| v.value).unwrap_or_else(|| match tag.as_str() { + "wght" => f32::from(c.weight), + "ital" if c.italic => *max, + _ => *default, + }); + let d = default.clamp(*min, *max); + if v.is_finite() { v.clamp(*min, *max) } else { d } +} + +/// Slider label for an axis: the registered axes by name, others by their tag (as the font +/// names them in its `fvar` table, e.g. `GRAD`). +fn axis_label(tag: &str) -> String { + match tag { + "wght" => tl!("Weight").to_string(), + "wdth" => tl!("Width").to_string(), + "slnt" => tl!("Slant").to_string(), + "ital" => tl!("Italic").to_string(), + _ => tag.to_string(), + } +} + +/// One slider row per variable-font axis of the style's font, below the font style (#2985). +pub(super) fn axis_sliders(app: &mut PhotocraftApp, ui: &mut egui::Ui, c: &photocraft_doc::text::CharStyle) { + // Drawn every frame: no sliders until the background font scan is done (#3021). + let Some(engine) = photocraft_text::try_shared() else { return }; + let axes = { + let faces = engine.lock().unwrap_or_else(PoisonError::into_inner).fonts.faces(&c.font_family); + slider_axes(&faces, c.italic) + }; + let t = crate::theme::Tokens::get(ui.ctx()); + for axis in &axes { + let (min, max) = (axis.1, axis.3); + let mut v = axis_value(c, axis); + let mut changed = false; + ui.push_id(("type-axis", &axis.0), |ui| { + ui.horizontal(|ui| { + let axis_name = axis_label(&axis.0); + ui.label(egui::RichText::new(&axis_name).color(t.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + changed |= crate::widgets::value_field(ui, &mut v, min..=max, "", 74.0).accessible_name(axis_name).changed(); + }); + }); + changed |= crate::widgets::slider(ui, &mut v, min..=max, None).changed(); + }); + ui.add_space(crate::theme::ROW_GAP); + if changed { + // Whole units on wide axes (weight 100–900), hundredths on narrow ones (ital 0–1). + let v = if max - min >= 10.0 { v.round() } else { (v * 100.0).round() / 100.0 }; + let mut m = serde_json::Map::new(); + m.insert(axis.0.clone(), json!(v)); + apply(app, ui.ctx(), json!({ "variations": m })); + } + } +} + +/// PSD text can identify a face only by its PostScript name. Show its real subfamily too. +pub(crate) fn selected_style(style: &photocraft_doc::text::CharStyle) -> String { + // Drawn every frame: while the font scan runs, the stored style name stands in. + if let Some(ps) = &style.postscript_name + && let Some(engine) = photocraft_text::try_shared() + { + let faces = engine.lock().unwrap_or_else(|e| e.into_inner()).fonts.faces(&style.font_family); + if let Some(face) = faces.into_iter().find(|f| f.postscript_name.as_ref() == Some(ps)) { + return face.style; + } + } + if style.font_style.is_empty() { if style.italic { "Italic".into() } else { "Regular".into() } } else { style.font_style.clone() } +} + +/// Localized style label for the dropdown. The raw string stays the engine's `fontStyle` key; +/// the words (weights and "Italic") are translated in the `fontWeight` context, where "Light" +/// means a weight — unlike the Camera Raw "Light" section. +pub fn style_label(style: &str) -> String { + style.split(' ').map(|w| crate::i18n::tr_ctx(crate::i18n::current(), "fontWeight", w)).collect::>().join(" ") +} + +/// Starts scanning the installed fonts on a background thread (desktop start-up), so choosing +/// the Type tool doesn't stall the UI while they are read (#3021). Does nothing on the web. +pub fn warm_fonts() { + photocraft_text::warm_shared(); +} + +/// Whether the font database is ready. The installed fonts are scanned on a background thread +/// from launch (`photocraft_text::warm_shared`); until that finishes, font menus draw this +/// disabled "Loading fonts…" box `width` wide instead of blocking the UI, and a repaint picks the +/// menus up once the scan is done. +pub(crate) fn fonts_ready(ui: &mut egui::Ui, width: f32) -> bool { + if photocraft_text::try_shared().is_some() { + return true; + } + let label = tl!("Loading fonts…").to_string(); + ui.add_enabled_ui(false, |ui| crate::widgets::dropdown(ui, "fonts-loading", tl!("Font"), &mut label.clone(), &[(label.clone(), label.as_str())], width)); + ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); + false +} + +/// Searchable font-family combo box. +pub(super) fn font_picker(ui: &mut egui::Ui, current: &mut String, width: f32, preview: photocraft_engine::prefs::FontPreview, recents: &[String]) -> bool { + family_picker_in(ui, "type-font", current, width, &families(), preview, recents) +} + +/// Maximum height of the font menu. +pub(super) const FONT_MENU_HEIGHT: f32 = 460.0; + +/// [`font_picker`] over a given family list (tests pass their own). +#[cfg(test)] +pub(super) fn font_picker_in( + ui: &mut egui::Ui, + current: &mut String, + width: f32, + families: &[String], + preview: photocraft_engine::prefs::FontPreview, + recents: &[String], +) -> bool { + family_picker_in(ui, "type-font", current, width, families, preview, recents) +} + +/// Shared by the Type options, Character, style and Glyphs panels. Selection changes still +/// flow through each caller's existing engine command. +pub(crate) fn family_picker_in( + ui: &mut egui::Ui, + salt: &str, + current: &mut String, + width: f32, + families: &[String], + preview: photocraft_engine::prefs::FontPreview, + recents: &[String], +) -> bool { + let mut changed = false; + // A font picked from the open menu (click or Enter): the field keeps the focus afterwards. + let mut picked = false; + let search_id = ui.scope_id().with(("font-search", salt)); + let focus_id = search_id.with("focus"); + let recents_id = search_id.with("recents"); + let row_id = search_id.with("row"); + // The list opens on the press, so a press-drag-release picks a font too (#2735). + let (press, close) = crate::press_menu::PressCombo::before(ui, salt); + let labels: Option>> = ui.ctx().data(|d| d.get_temp(font_labels_id())); + let labels = labels.as_deref(); + let shown = labels.and_then(|l| l.get(current.as_str())).unwrap_or(current).clone(); + let combo = egui::ComboBox::from_id_salt(salt) + .selected_text(shown) + .width(width) + .height(FONT_MENU_HEIGHT) + .icon(crate::widgets::chevron_icon) + // Clicks inside the menu (the search field, the scroll bar) must not close it (#1369); + // picking a font closes it explicitly below. + .close_behavior(if matches!(close, egui::PopupCloseBehavior::IgnoreClicks) { close } else { egui::PopupCloseBehavior::CloseOnClickOutside }); + + let mut response = combo.show_ui(ui, |ui| { + let height_id = search_id.with("height"); + // Each opening focuses the search, including a reopen on the very next pass. Keep + // asking through the invisible sizing pass, until the field receives focus. + let mut focus = ui.data(|d| d.get_temp(focus_id)).unwrap_or(true); + let mut q: String = ui.data(|d| d.get_temp(search_id)).unwrap_or_default(); + // Consume these before TextEdit and the canvas can interpret them as caret movement. + let down = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown)); + let up = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp)); + let enter = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); + if focus { + ui.memory_mut(|m| m.request_focus(search_id.with("input"))); + } + let r = ui.add(egui::TextEdit::singleline(&mut q).id(search_id.with("input")).hint_text(tl!("Search fonts")).desired_width(200.0)); + if focus { + // The opening click can release after several focused frames. Keep the request + // pending through that release, which can hand focus back to the combo button. + focus = !r.has_focus() || ui.input(|i| i.pointer.primary_down() || i.pointer.primary_released()); + } + ui.data_mut(|d| { + d.insert_temp(focus_id, focus); + d.insert_temp(search_id, q.clone()); + }); + let ql = q.to_lowercase(); + // The recent group stays as it was when the menu opened: each arrow step applies (and so + // records) a family, and moving it to the top would send the next step back up. + let opening = ui.data(|d| d.get_temp::>(recents_id).is_none()); + let open_recents: Vec = ui.data_mut(|d| d.get_temp_mut_or_insert_with(recents_id, || recents.to_vec()).clone()); + let (rows, n_recent) = font_menu_rows(families, labels, &ql, &open_recents); + // A recent family is listed twice. The current family's row is the one the last arrow + // selected while it still shows that family, else its first copy: as in Photoshop, the + // one in the recent group when it has one (#9160), and the arrows walk on from there. + let mut selected = ui + .data(|d| d.get_temp::(row_id)) + .filter(|&i| rows.get(i).is_some_and(|(f, _)| *f == current)) + .or_else(|| rows.iter().position(|(f, _)| *f == current)); + // The menu opens on the current family, as Photoshop's does: with the recent group at the + // top of the view when the marked row fits below it, else the marked row itself, at the + // top of the view when it is not a recent one. Applied on the first laid-out pass (the + // popup's first pass only measures), whether or not a row matches, so a missing font or + // a filtered list never scrolls the menu later. + let reveal_id = search_id.with("reveal"); + if opening { + ui.data_mut(|d| d.insert_temp(reveal_id, true)); + } + let revealing = ui.data(|d| d.get_temp::(reveal_id)).unwrap_or(false) && !ui.is_sizing_pass(); + if revealing { + ui.data_mut(|d| d.remove::(reveal_id)); + } + let reveal = if revealing { selected } else { None }; + let reveal_from = reveal.map(|i| if i < n_recent { 0 } else { i }); + let mut stepped = None; + if down || up { + let next = match selected { + Some(i) if down => i.saturating_add(1).min(rows.len().saturating_sub(1)), + Some(i) => i.saturating_sub(1), + None if down => 0, + None => rows.len().saturating_sub(1), + }; + if let Some((f, _)) = rows.get(next) { + changed = **f != *current; + current.clone_from(f); + // A served family not fetched yet: start now, as a click does. + photocraft_text::served::request(f); + stepped = Some(next); + selected = Some(next); + ui.data_mut(|d| d.insert_temp(row_id, next)); + } + } + let accept = enter && rows.iter().any(|(f, _)| *f == current); + picked |= accept; + if accept { + ui.data_mut(|d| d.remove::(search_id)); + ui.close(); + } + let preview = crate::font_preview::sample(preview); + let row_h = preview.map_or(28.0, |(_, [_, h])| (h + 4.0).max(28.0)); + + // Wrap the font rows in a ScrollArea so only the list scrolls: the search field above + // stays fixed at the top of the popup. + let mut hovered: Option = None; + let reveal = if stepped.is_some() { None } else { reveal }; + let mut reveal_top: Option = None; + egui::ScrollArea::vertical().show(ui, |ui| { + for (i, (f, label)) in rows.into_iter().enumerate() { + if i == n_recent && n_recent > 0 { + ui.separator(); + } + // Highlighted by its fill alone, as Photoshop's font menu is. A selectable button lays + // out its frame's stroke only once hovered or selected, so with the theme's stroke the + // row under the pointer (and the selected one) grew and pushed the rows below down: + // the list jumped as the pointer moved (#7406). One row only, though a recent + // family is listed twice. + let mut button = egui::Button::selectable(selected == Some(i), label).truncate().stroke(egui::Stroke::NONE); + if let Some((size, [_, h])) = preview { + button = button.right_text(egui::Atom::custom( + egui::IdSalt::new(("font-sample", f)), + egui::vec2(crate::font_preview::slot_width(ui.ctx(), f, size), h), + )); + } + let response = ui.add_sized([330.0, row_h], button); + if stepped == Some(i) { + response.scroll_to_me(Some(egui::Align::Center)); + } else if reveal.is_some() { + if reveal_from == Some(i) { + reveal_top = Some(response.rect); + } + if reveal == Some(i) { + // Jump, not glide: the menu opens with its current family in view. Arrow + // steps above keep the animation. A recent row too far below the top of + // the group (large previews, many recents) is brought up to the bottom. + let top = reveal_top.unwrap_or(response.rect); + let (rect, align) = if response.rect.bottom() - top.top() <= ui.clip_rect().height() { + (top, egui::Align::Min) + } else { + (response.rect, egui::Align::Max) + }; + ui.scroll_to_rect_animation(rect, Some(align), egui::style::ScrollAnimation::none()); + } + } + if let Some((size, _)) = preview + && ui.is_rect_visible(response.rect) + { + crate::font_preview::paint(ui, f, response.rect, size); + } + if response.hovered() { + hovered = Some(f.clone()); + } + if press.chosen(ui, &response) { + *current = f.clone(); + // A served family not fetched yet: start now, before any text needs it. + photocraft_text::served::request(f); + changed = true; + picked = true; + ui.data_mut(|d| d.remove::(search_id)); + hovered = None; + ui.close(); + } + } + }); + // egui measures a popup only when it opens and never lets it grow back, so a filtered + // list would leave the menu short after the query is cleared (#1369). Keep the unfiltered + // height while searching. Measured after the rows: before them `min_rect` only holds the + // search field, and the cache would shrink the menu to it. + if ql.is_empty() { + let h = ui.min_rect().height(); + ui.data_mut(|d| d.insert_temp(height_id, h)); + } else if let Some(h) = ui.data(|d| d.get_temp::(height_id)) { + ui.set_min_height(h.min(FONT_MENU_HEIGHT)); + } + if accept { None } else { hovered } + }); + response.response = response.response.accessible_name(tl!("Font")); + press.after(&response.response); + if !egui::ComboBox::is_open(ui.ctx(), response.response.id) { + ui.data_mut(|d| { + d.remove::(focus_id); + d.remove::>(recents_id); + d.remove::(row_id); + d.remove::(search_id.with("reveal")); + }); + } + let hovered_font = response.inner.unwrap_or_default(); + + // As in Photoshop, the field keeps the keyboard focus once a font is picked, and ↑ / ↓ on the + // focused, closed field step to the previous / next family, applying each (#7407). The lock + // filter keeps egui from using those arrows to move the focus to another widget. + let field = response.response.id; + if picked { + ui.memory_mut(|m| m.request_focus(field)); + } + let open = egui::ComboBox::is_open(ui.ctx(), field); + if !open && ui.is_enabled() && ui.memory(|m| m.has_focus(field)) { + ui.memory_mut(|m| m.set_focus_lock_filter(field, egui::EventFilter { vertical_arrows: true, ..Default::default() })); + let down = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown)); + let up = ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp)); + if down || up { + // The lock filter only holds from the frame after the field got the focus: an arrow + // right after a pick was already read by egui as a focus move, applied at the end of + // the frame. Cancel it, so the arrow only steps the font. + ui.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); + } + // The wheel's step: a negative notch is the next family. Steps use a stable order (no + // recent group), so recording the picked family cannot make the next step jump back. + let notches = f32::from(u8::from(up)) - f32::from(u8::from(down)); + let (rows, _) = font_menu_rows(families, labels, "", &[]); + if let Some(i) = rows.iter().position(|(f, _)| *f == current) + && let Some(n) = wheel_family_index(i, rows.len(), notches) + && let Some((f, _)) = rows.get(n) + && **f != *current + { + current.clone_from(f); + photocraft_text::served::request(f); + changed = true; + } + } + + // The wheel over the closed button steps through the families, a notch each, like Photoshop's + // options-bar font menu: no need to open the list (#3350). + if !egui::ComboBox::is_open(ui.ctx(), response.response.id) && ui.is_enabled() { + let hovered = response.response.hovered(); + if hovered { + ui.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO); + } + let notches = crate::widgets::wheel_notches_of(ui, response.response.id.with("family-wheel"), hovered, 1.0); + // The wheel steps in a stable order: a recent group holding the family it just picked + // would change the order between notches and can jump back to the previous family. + // The open menu still shows the recent families first. + let (rows, _) = font_menu_rows(families, labels, "", &[]); + if let Some(i) = rows.iter().position(|(f, _)| *f == current) + && let Some(n) = wheel_family_index(i, rows.len(), notches) + && let Some((f, _)) = rows.get(n) + && **f != *current + { + current.clone_from(f); + photocraft_text::served::request(f); + changed = true; + } + } + + if salt == "type-font" { + let hover_id = egui::Id::unique("type-font-hover"); + if let Some(f) = hovered_font { + ui.ctx().data_mut(|d| d.insert_temp(hover_id, f)); + } else if egui::ComboBox::is_open(ui.ctx(), response.response.id) { + // Only the open menu clears it: the options bar and the Character section both draw + // this picker, and the closed one must not wipe the other's hover (#5152). + ui.ctx().data_mut(|d| d.remove::(hover_id)); + } + } + + changed +} + +/// The row `notches` wheel notches from row `index` of `len` (down, negative, is the next one), +/// stopping at the ends; none when the wheel did not move. +pub(super) fn wheel_family_index(index: usize, len: usize, notches: f32) -> Option { + let steps = notches.abs().min(len as f32) as usize; + if steps == 0 || len == 0 { + return None; + } + let last = len - 1; + Some(if notches < 0.0 { index.saturating_add(steps).min(last) } else { index.saturating_sub(steps) }) +} diff --git a/crates/ui-egui/src/type_tool/ime.rs b/crates/ui-egui/src/type_tool/ime.rs new file mode 100644 index 0000000000..09994a338d --- /dev/null +++ b/crates/ui-egui/src/type_tool/ime.rs @@ -0,0 +1,452 @@ +use super::editing::edit_home; +use super::ime_edit::{ime_geometry, reconcile_preedit}; +use super::*; + +/// Per-editor IME owner/generation bookkeeping for the custom Type tool. +/// +/// The tracker is shared by every viewport and keeps the context generation alive when this +/// editor is replaced. The overlay records the pass's canvas mapping and the pass end recomputes +/// the final geometry from the observed model, so an event-free or discarded pass never replays +/// stale text. +#[derive(Debug, Default)] +pub(crate) struct ImeState { + pub(super) tracker: ImeContextTracker, + pub(super) frame: Option, + /// The canvas mapping of the current pass, so the final descriptor geometry is recomputed + /// from the observed model rather than from an earlier point in the pass. + pub(super) view: Option, + /// The last descriptor identity the platform actually received (a discarded pass did not + /// receive it, so its transition must still be reported by the final pass). + pub(super) emitted: Option, + /// Ask the platform to cancel the native composition (owner/session transition or a stale + /// pre-edit). Stays set until a non-discarded descriptor carries it. + pub(super) interrupt: bool, + /// Incoming composition provenance survives idle/discarded passes and an empty preedit. + /// A stale owner stays fenced until the exact host reset completion arrives. + pub(super) incoming: Option, + /// The composition text was invalidated; this pass must report `Unavailable` rather than + /// presenting the orphaned composition as committed text. + pub(super) stale: bool, + /// The exact composition written into the layer, used to check the stored range before any + /// replacement, deletion, underline or surrounding-text report. + pub(super) preedit: Option, + /// A local fence is released only by its exact host completion, never by terminal text. + pub(super) resets: HashMap, + context: Option, + needs_request: bool, + /// One exclusive event owner per actual UI pass; logic-only ticks never replay input. + raw_pass: HashMap, + pub(super) custom_pass: HashMap)>, + last_custom: HashMap, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct ResetContext(pub(super) egui::Id, pub(super) u64, pub(super) egui::IMEPurpose); + +impl From<&egui::output::IMEOutput> for ResetContext { + fn from(ime: &egui::output::IMEOutput) -> Self { + Self(ime.owner, ime.context_generation, ime.purpose) + } +} + +#[derive(Clone, Copy, Debug)] +pub(super) enum ResetPhase { + NeedsRequest, + Awaiting { id: egui::ImeResetId, destination: IncomingSelection, context: Option }, + Suspended, + AllocationFailed { destination: IncomingSelection, context: Option }, +} + +#[derive(Clone, Copy, Debug)] +pub(super) struct ImeFrame { + pub(super) viewport: egui::ViewportId, + pub(super) frame_nr: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct ImeEmitted { + pub(super) target: ImeTarget, + pub(super) generation: u64, +} + +#[derive(Clone, Copy, Debug)] +pub(super) struct ImeView { + pub(super) viewport: egui::ViewportId, + pub(super) pass_nr: u64, + pub(super) xf: ViewXform, +} + +/// The composition text and the edit session that wrote it. A range that still lies inside the +/// text is not enough: an application edit can shift it onto committed characters. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct ImePreedit { + pub(super) layer: u64, + pub(super) session: String, + pub(super) text: String, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct IncomingSelection { + target: ImeTarget, + caret: usize, + anchor: usize, + revision: u64, +} + +#[derive(Clone, Copy, Debug)] +pub(super) enum IncomingComposition { + Active(IncomingSelection), + TerminalPending(IncomingSelection), + Stale, +} + +/// A bounded committed snapshot captured from the type layer. +/// +/// The snapshot owns at most `MAX_IME_SURROUNDING_TEXT_BYTES`; the layer's whole text is only +/// borrowed while it is built. The current pre-edit lives in the layer so it lays out like +/// typed text, and is removed from this value rather than reported as committed text. +pub(super) struct ImeCommitted { + pub(super) snapshot: egui::output::IMESurroundingText, +} + +impl ImeCommitted { + pub(super) fn stamp(&self) -> ImeMutationStamp { + ImeMutationStamp::from_surrounding_text(self.snapshot.clone()) + } +} + +impl ImeState { + /// Remember the frame used by this pass's accepted IME receipts. + pub(super) fn begin_frame(&mut self, ctx: &egui::Context) { + let viewport = ctx.viewport_id(); + self.frame = Some(ImeFrame { viewport, frame_nr: ctx.cumulative_frame_nr_for(viewport) }); + } + + /// Record the canvas mapping of this pass. `sync_ime` recomputes both rectangles from the + /// model after every panel has run. + pub(super) fn note_view(&mut self, viewport: egui::ViewportId, pass_nr: u64, xf: &ViewXform) { + self.view = Some(ImeView { viewport, pass_nr, xf: *xf }); + } + + /// Request the native composition reset; incoming ownership is tracked separately. + pub(super) fn request_interrupt(&mut self) { + self.interrupt = true; + if self.incoming.is_some() || !self.resets.is_empty() { + self.needs_request = true; + // Context-less commands must retire every old id synchronously. + for phase in self.resets.values_mut() { + *phase = ResetPhase::NeedsRequest; + } + } + } + + /// Forget a composition whose range no longer describes the recorded text. + pub(super) fn invalidate_preedit(&mut self) { + self.preedit = None; + self.stale = true; + self.incoming = Some(IncomingComposition::Stale); + self.request_interrupt(); + } + + pub(super) fn note_preedit(&mut self, ed: &TextEdit, text: &str) { + self.preedit = Some(ImePreedit { layer: ed.layer, session: ed.session.clone(), text: text.to_owned() }); + } + + pub(super) fn clear_preedit(&mut self) { + self.preedit = None; + } +} + +/// The immutable owner of the Type tool's IME context. +/// +/// The document, layer and viewport identify the target; the edit session is the replacement +/// epoch, so committing and editing the same layer again cannot reuse the old generation. +pub(super) fn ime_target(app: &PhotocraftApp, ed: &TextEdit, viewport: egui::ViewportId) -> Option { + let document = ed.document.or_else(|| active_doc_id(app))?; + // A Type Mask session is a distinct owner: its hidden working layer can have the same id as + // a regular type layer in another tool session. The session epoch replaces the context when + // an owner is recreated. + let owner = egui::Id::unique(("photocraft-type-ime", document, ed.layer, ed.mask, viewport.0.value())); + let epoch = egui::Id::unique(("photocraft-type-ime-session", &ed.session)).value().max(1); + Some(ImeTarget::new(owner, epoch)) +} + +fn incoming_selection(app: &PhotocraftApp, viewport: egui::ViewportId) -> Option { + let ed = app.ui.text_edit.as_ref()?; + Some(IncomingSelection { target: ime_target(app, ed, viewport)?, caret: ed.caret, anchor: ed.anchor, revision: app.session.active()?.revision }) +} + +/// Settle the already-visible preview where it was typed, never replay it at a moved caret. +pub(super) fn interrupt_incoming(app: &mut PhotocraftApp) { + if !matches!(app.type_ime.incoming, Some(IncomingComposition::Active(_) | IncomingComposition::TerminalPending(_))) { + return; + } + app.type_ime.incoming = Some(IncomingComposition::Stale); + if let Some(ed) = &mut app.ui.text_edit { + ed.preedit = None; + } + app.type_ime.clear_preedit(); + app.type_ime.request_interrupt(); +} + +pub(super) fn interrupt_action(app: &mut PhotocraftApp, viewport: egui::ViewportId) { + let guarded = reset_guarded(app, viewport); + interrupt_incoming(app); + if guarded { + app.type_ime.request_interrupt(); + } +} + +pub(super) fn sync_incoming(app: &mut PhotocraftApp, viewport: egui::ViewportId) { + let destination = incoming_selection(app, viewport); + if app.type_ime.resets.get(&viewport).is_some_and(|phase| match phase { + ResetPhase::Awaiting { destination: old, .. } | ResetPhase::AllocationFailed { destination: old, .. } => Some(*old) != destination, + _ => false, + }) { + app.type_ime.request_interrupt(); + } + let expected = match app.type_ime.incoming { + Some(IncomingComposition::Active(expected) | IncomingComposition::TerminalPending(expected)) => expected, + _ => return, + }; + let lost_preview = matches!(app.type_ime.incoming, Some(IncomingComposition::Active(_))) && app.ui.text_edit.as_ref().is_none_or(|ed| ed.preedit.is_none()); + if incoming_selection(app, viewport) != Some(expected) || lost_preview { + // An external edit can move an in-bounds preview range onto committed characters. + // Validate it before interruption clears the metadata needed to detect that mismatch. + // A valid preview still settles normally; never inspect another document's layer here. + if let Some(ed) = app.ui.text_edit.clone() + && ed.preedit.is_some() + && ime_target(app, &ed, viewport) == Some(expected.target) + && let Some(active) = app.session.active_index() + && edit_home(app, &ed) == Some(active) + && let Some(text) = current_text(app, LayerId(ed.layer)) + && reconcile_preedit(app, &ed, &text) + { + return; + } + interrupt_incoming(app); + } +} + +/// Accepted IME mutations update provenance without canceling their own Delete→Commit chain. +pub(super) fn remember_incoming(app: &mut PhotocraftApp, preedit_empty: Option) { + let viewport = app.type_ime.frame.map_or(egui::ViewportId::ROOT, |frame| frame.viewport); + let Some(expected) = incoming_selection(app, viewport) else { return }; + let next = match (preedit_empty, app.type_ime.incoming) { + (Some(false), _) | (None, Some(IncomingComposition::Active(_))) => IncomingComposition::Active(expected), + (Some(true), _) | (None, Some(IncomingComposition::TerminalPending(_))) => IncomingComposition::TerminalPending(expected), + _ => return, + }; + app.type_ime.incoming = Some(next); +} + +/// A host may recreate its Context while retaining the application. Old pass counters and +/// output keys are not evidence of publication in that new Context. +pub(super) fn bind_reset_context(app: &mut PhotocraftApp, ctx: &egui::Context) { + // `on_begin_pass` callbacks registered during this pass cannot mark the pass already + // running. Reinstall here so a replacement Context is ready for its next pass, and rely on + // the host's creator/`setup_context` having installed before the very first `run_ui`. + install_reset_hooks(ctx); + if app.type_ime.context.as_ref().is_some_and(|previous| previous != ctx) { + interrupt_incoming(app); + for phase in app.type_ime.resets.values_mut() { + *phase = ResetPhase::Suspended; + } + app.type_ime.needs_request = false; + app.type_ime.raw_pass.clear(); + app.type_ime.custom_pass.clear(); + app.type_ime.last_custom.clear(); + app.type_ime.view = None; + app.type_ime.frame = None; + app.type_ime.tracker.observe(ctx.viewport_id(), None); + } + app.type_ime.context = Some(ctx.clone()); +} + +fn ui_mode_id(viewport: egui::ViewportId) -> egui::Id { + egui::Id::unique(("photocraft-type-reset-ui", viewport)) +} + +/// Install before the first UI pass on every Context, including a replacement. These callbacks +/// retain neither the app nor its Context. Calling this from inside a running pass only affects +/// subsequent passes: egui's begin-pass callback list is already being iterated. +pub(crate) fn install_reset_hooks(ctx: &egui::Context) { + let installed = egui::Id::unique("photocraft-type-reset-hooks"); + if ctx.data(|data| data.get_temp::(installed)).unwrap_or(false) { + return; + } + ctx.data_mut(|data| data.insert_temp(installed, true)); + ctx.on_begin_pass( + "photocraft type reset UI mode", + Arc::new(|ui| { + let key = ui_mode_id(ui.ctx().viewport_id()); + ui.ctx().data_mut(|data| data.insert_temp(key, true)); + }), + ); + ctx.on_end_pass( + "photocraft type reset UI mode end", + Arc::new(|ui| { + let key = ui_mode_id(ui.ctx().viewport_id()); + ui.ctx().data_mut(|data| data.insert_temp(key, false)); + }), + ); +} + +pub(crate) fn in_ui_pass(ctx: &egui::Context) -> bool { + let key = ui_mode_id(ctx.viewport_id()); + ctx.data(|data| data.get_temp::(key)).unwrap_or(false) +} + +pub(super) fn reset_guarded(app: &PhotocraftApp, viewport: egui::ViewportId) -> bool { + app.type_ime.needs_request || app.type_ime.resets.contains_key(&viewport) || matches!(app.type_ime.incoming, Some(IncomingComposition::Stale)) +} + +pub(super) fn reset_route_eligible(app: &PhotocraftApp, ctx: &egui::Context) -> bool { + // The actual app draws only after `logic_frame` marks fonts ready; `ui_frame` early-returns + // on the first frame. Direct handler tests that have not run the first logic frame use the + // pre-styled app state and are not an actual UI route. + (app.fonts_ready || !app.styled) + && app.ui.text_edit.is_some() + && app.ui.dialogs.is_empty() + && !crate::screen_picker::busy(ctx) + && ctx.input(|i| i.focused) + && !ctx.text_edit_focused() + && !ctx.egui_wants_keyboard_input() +} + +/// Whether this input can be attributed to a visible custom descriptor right now. Completion +/// arrives before the final descriptor exists, so use the last canvas mapping and the current +/// model: requiring this pass's final output here would deadlock the ordered suffix. +fn reset_geometry_available(app: &mut PhotocraftApp, viewport: egui::ViewportId) -> bool { + let Some(ed) = app.ui.text_edit.clone() else { return false }; + let Some(view) = app.type_ime.view.filter(|view| view.viewport == viewport) else { return false }; + ime_geometry(app, &ed, view.xf).is_some() +} + +pub(super) fn suspend_reset(app: &mut PhotocraftApp, ctx: &egui::Context) { + let viewport = ctx.viewport_id(); + if reset_guarded(app, viewport) { + app.type_ime.resets.insert(viewport, ResetPhase::Suspended); + app.type_ime.needs_request = false; + } + app.type_ime.last_custom.remove(&viewport); +} + +fn allocate_reset(app: &mut PhotocraftApp, ctx: &egui::Context, destination: IncomingSelection, context: Option) { + let viewport = ctx.viewport_id(); + let phase = match ctx.request_ime_reset(viewport) { + Some(id) => ResetPhase::Awaiting { id, destination, context }, + None => ResetPhase::AllocationFailed { destination, context }, + }; + app.type_ime.resets.insert(viewport, phase); + app.type_ime.needs_request = false; +} + +/// Reconcile before the next raw element, not merely at descriptor publication. +pub(super) fn prepare_reset(app: &mut PhotocraftApp, ctx: &egui::Context) { + let viewport = ctx.viewport_id(); + sync_incoming(app, viewport); + if app.type_ime.needs_request { + app.type_ime.resets.insert(viewport, ResetPhase::NeedsRequest); + app.type_ime.needs_request = false; + } + // Allocation belongs to the true UI tail: a stock field drawn later in this pass + // must never inherit a speculative custom-editor reset request. +} + +pub(super) fn complete_reset(app: &mut PhotocraftApp, ctx: &egui::Context, request_id: egui::ImeResetId) { + let viewport = ctx.viewport_id(); + let Some(ResetPhase::Awaiting { id, destination, context }) = app.type_ime.resets.get(&viewport).copied() else { return }; + if request_id != id + || request_id.viewport_id() != viewport + || !reset_route_eligible(app, ctx) + || incoming_selection(app, viewport) != Some(destination) + || context != app.type_ime.last_custom.get(&viewport).copied() + { + return; + } + if !reset_geometry_available(app, viewport) { + // Retire the old id and keep the following preedit blocked before it can reach the + // editor. The UI tail may still rearm once this pass produces real custom output. + suspend_reset(app, ctx); + return; + } + app.type_ime.resets.remove(&viewport); + app.type_ime.incoming = None; + app.type_ime.preedit = None; + app.type_ime.stale = false; + app.type_ime.interrupt = false; + if let Some(ed) = app.ui.text_edit.as_mut() { + ed.preedit = None; + } +} + +pub(super) fn claim_raw_pass(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { + let viewport = ctx.viewport_id(); + let pass = ctx.cumulative_pass_nr_for(viewport); + app.type_ime.raw_pass.insert(viewport, pass) != Some(pass) +} + +/// The exclusive route when no custom editor may mutate. Do not consume stock text/keys. +pub(crate) fn controls_only(app: &mut PhotocraftApp, ctx: &egui::Context) { + bind_reset_context(app, ctx); + if !claim_raw_pass(app, ctx) { + return; + } + if !reset_route_eligible(app, ctx) { + interrupt_incoming(app); + } + suspend_reset(app, ctx); // Retire an old id before visiting even the first marker. + for event in ctx.input(|i| i.events.clone()) { + if let egui::Event::ImeResetCompleted { request_id } = event { + complete_reset(app, ctx, request_id); + } + } +} + +/// True outer UI tail, including discarded/early-return passes and host-side mutations. +pub(crate) fn finish_reset_pass(app: &mut PhotocraftApp, ctx: &egui::Context) { + bind_reset_context(app, ctx); + let viewport = ctx.viewport_id(); + if app.type_ime.raw_pass.get(&viewport).copied() != Some(ctx.cumulative_pass_nr_for(viewport)) { + controls_only(app, ctx); + } + sync_incoming(app, viewport); + let produced = app.type_ime.custom_pass.get(&viewport).copied().filter(|(pass, _)| *pass == ctx.cumulative_pass_nr_for(viewport)).and_then(|(_, key)| key); + let actual = ctx.output(|o| o.ime.as_ref().map(ResetContext::from)); + let Some(context) = produced.filter(|key| Some(*key) == actual && reset_route_eligible(app, ctx)) else { + suspend_reset(app, ctx); + return; + }; + // Never allocate a request for output egui will throw away. Keep any existing guard and its + // queued R1 blocked; the final pass either publishes this context and reuses it or retires + // the old id through the ineligible branch above. + if ctx.will_discard() { + return; + } + app.type_ime.last_custom.insert(viewport, context); + if !reset_guarded(app, viewport) { + return; + } + let Some(destination) = incoming_selection(app, viewport) else { + suspend_reset(app, ctx); + return; + }; + let unchanged = app.type_ime.resets.get(&viewport).is_some_and(|phase| match phase { + ResetPhase::Awaiting { destination: old, context: old_context, .. } | ResetPhase::AllocationFailed { destination: old, context: old_context } => { + *old == destination && *old_context == Some(context) && !app.type_ime.needs_request + } + _ => false, + }); + if !unchanged { + allocate_reset(app, ctx, destination, Some(context)); + } +} + +pub(crate) fn finish_reset_logic(app: &mut PhotocraftApp, ctx: &egui::Context) { + bind_reset_context(app, ctx); + if !in_ui_pass(ctx) { + sync_incoming(app, ctx.viewport_id()); + suspend_reset(app, ctx); + } +} diff --git a/crates/ui-egui/src/type_tool/ime_edit.rs b/crates/ui-egui/src/type_tool/ime_edit.rs new file mode 100644 index 0000000000..c13abf716e --- /dev/null +++ b/crates/ui-egui/src/type_tool/ime_edit.rs @@ -0,0 +1,409 @@ +use super::editing::edit_home; +use super::ime::{ + ImeCommitted, ImeEmitted, ResetContext, bind_reset_context, ime_target, interrupt_incoming, remember_incoming, reset_route_eligible, sync_incoming, +}; +use super::layout::layout; +use super::*; + +/// UTF-8 byte offsets of the caret, anchor and pre-edit, found in one traversal. +/// +/// The pre-edit is in characters in [`TextEdit`]; surround-text offsets are UTF-8 bytes. A range +/// that runs past the text is an explicit unavailable state, not a reason to report the +/// composition as committed. +pub(super) struct ImeOffsets { + cursor: usize, + anchor: usize, + pub(super) preedit: Option>, +} + +pub(super) fn ime_offsets(text: &str, ed: &TextEdit) -> Option { + let (start, end) = match ed.preedit { + Some((start, len)) => (start, start.checked_add(len)?), + None => (0, 0), + }; + let wanted = [ed.caret, ed.anchor, start, end]; + let mut bytes = [usize::MAX; 4]; + let mut chars = 0usize; + for (index, (byte, _)) in text.char_indices().enumerate() { + for (slot, want) in bytes.iter_mut().zip(wanted) { + if *slot == usize::MAX && want == index { + *slot = byte; + } + } + chars = index.saturating_add(1); + } + // An index at (or past) the end clamps to the end, as before; a pre-edit past the end is a + // stale composition and makes the surrounding text unavailable. + for (slot, (index, want)) in bytes.iter_mut().zip(wanted.into_iter().enumerate()) { + if *slot == usize::MAX { + // The caret and anchor clamp after undo/redo; a pre-edit beyond the text is stale. + if index >= 2 && want > chars { + return None; + } + *slot = text.len(); + } + } + let preedit = match ed.preedit { + Some(_) if end > chars => return None, + Some(_) => Some(bytes[2]..bytes[3]), + None => None, + }; + Some(ImeOffsets { cursor: bytes[0], anchor: bytes[1], preedit }) +} + +/// Whether the stored character range still contains exactly the composition that wrote it. +pub(super) fn ime_preedit_is_current(app: &PhotocraftApp, text: &str, ed: &TextEdit, offsets: &ImeOffsets) -> bool { + match (ed.preedit, offsets.preedit.as_ref()) { + (None, _) => true, + (Some(_), Some(range)) => { + app.type_ime.preedit.as_ref().is_some_and(|p| p.layer == ed.layer && p.session == ed.session && text.get(range.clone()) == Some(p.text.as_str())) + } + (Some(_), None) => false, + } +} + +/// Check the stored pre-edit against the live text, invalidating it (and the native composition) +/// when an application edit moved or replaced it. Returns true when it was stale. +pub(super) fn reconcile_preedit(app: &mut PhotocraftApp, ed: &TextEdit, text: &str) -> bool { + if ed.preedit.is_none() { + return false; + } + let current = ime_offsets(text, ed).is_some_and(|offset| ime_preedit_is_current(app, text, ed, &offset)); + if current { + return false; + } + app.type_ime.invalidate_preedit(); + if let Some(e) = app.ui.text_edit.as_mut() { + e.preedit = None; + } + true +} + +/// A borrowed observation for the tracker. It copies only the bounded window. +fn committed_text<'a>(app: &PhotocraftApp, text: &'a str, ed: &TextEdit) -> Option> { + let offsets = ime_offsets(text, ed)?; + if !ime_preedit_is_current(app, text, ed, &offsets) { + return None; + } + let committed = CommittedText::new(text, offsets.cursor, offsets.anchor); + Some(match offsets.preedit { + Some(preedit) => committed.with_preedit(preedit), + None => committed, + }) +} + +/// The bounded committed snapshot of the edited layer, or `None` when it cannot be exposed. +fn ime_committed(app: &PhotocraftApp, ed: &TextEdit) -> Option { + let text = text_layer(&app.session.active()?.doc, LayerId(ed.layer))?.text.as_str(); + let offsets = ime_offsets(text, ed)?; + if !ime_preedit_is_current(app, text, ed, &offsets) { + return None; + } + Some(ImeCommitted { snapshot: egui::output::IMESurroundingText::from_text(text, offsets.cursor, offsets.anchor, offsets.preedit) }) +} + +/// Report an accepted IME commit/deletion. Call only after the engine accepted the mutation and +/// from the snapshots immediately around it. +fn note_ime_apply(app: &mut PhotocraftApp, ed: &TextEdit, before: &ImeCommitted, after: &ImeCommitted) -> bool { + let Some(frame) = app.type_ime.frame else { return false }; + let Some(target) = ime_target(app, ed, frame.viewport) else { return false }; + app.type_ime.tracker.note_input_method_apply(frame.viewport, frame.frame_nr, target, before.stamp(), after.stamp()) +} + +/// Report an application-origin edit (typing, paste, cut, deletion, undo or a toolbar action). +pub(super) fn note_ime_application_change(app: &mut PhotocraftApp, ed: &TextEdit) -> bool { + let Some(frame) = app.type_ime.frame else { return false }; + let Some(target) = ime_target(app, ed, frame.viewport) else { return false }; + app.type_ime.tracker.note_application_change(frame.viewport, frame.frame_nr, target) +} + +/// Snapshot after the engine mutation and describe the current pass. +/// +/// Run once per UI pass, after the editor has drawn its caret, so the descriptor reflects this +/// pass's final model state. With no visible focused editor the context is ended; a moved focus +/// therefore cannot leave the previous owner's surrounding text latched. +pub(crate) fn sync_ime(app: &mut PhotocraftApp, ctx: &egui::Context) { + bind_reset_context(app, ctx); + let viewport = ctx.viewport_id(); + let frame_nr = ctx.cumulative_frame_nr_for(viewport); + let pass_nr = ctx.cumulative_pass_nr_for(viewport); + app.type_ime.custom_pass.insert(viewport, (pass_nr, None)); + sync_incoming(app, viewport); + let Some(mut ed) = app.ui.text_edit.clone() else { + app.type_ime.view = None; + app.type_ime.tracker.observe(viewport, None); + return; + }; + // An application edit (control channel, undo, a menu command) can move the stored composition + // range onto committed characters. Check the actual composition text before reporting it. + if ed.preedit.is_some() + && let Some(text) = current_text(app, LayerId(ed.layer)) + && reconcile_preedit(app, &ed, &text) + && let Some(current) = app.ui.text_edit.clone() + { + ed = current; + } + let view = app.type_ime.view.filter(|view| view.viewport == viewport && view.pass_nr == pass_nr); + let visible = view.is_some() && app.session.active_index().is_some() && edit_home(app, &ed) == app.session.active_index(); + let focused = visible && reset_route_eligible(app, ctx); + if !focused { + interrupt_incoming(app); + if let Some(current) = &app.ui.text_edit { + ed = current.clone(); + } + } + let Some(target) = ime_target(app, &ed, viewport) else { + app.type_ime.tracker.observe(viewport, None); + return; + }; + // The platform only resets the native composition from `should_interrupt_composition`; on + // X11, macOS, Windows and the web a changed owner/generation alone leaves it alive. Latch the + // last *delivered* target so a discarded pass does not lose the transition. + if app.type_ime.emitted.is_some_and(|last| last.target != target) { + app.type_ime.interrupt = true; + } + // Final geometry from this pass's model and canvas mapping: a later panel can move the caret + // after the overlay drew it, and `rect` is the edited layer's extent, not the caret. + let geometry = if focused { view.and_then(|view| ime_geometry(app, &ed, view.xf)) } else { None }; + // Borrow the layer's logical text for this observation; only the bounded window is copied. + let committed = if focused && !app.type_ime.stale { + app.session.active().and_then(|state| text_layer(&state.doc, LayerId(ed.layer))).and_then(|layer| committed_text(app, &layer.text, &ed)) + } else { + None + }; + let observation = ImeObservation::new(frame_nr, pass_nr, target).focused(focused).purpose(egui::IMEPurpose::Normal).committed(committed); + let update = app.type_ime.tracker.observe(viewport, Some(observation)); + // A generation change (focus/refocus, a pass gap, purpose or replacement) also needs the + // native reset; the tracker reports it only after observing. + let mut interrupt = app.type_ime.interrupt; + if let Some(update) = &update + && app.type_ime.emitted.is_some_and(|last| last.target != target || last.generation != update.context_generation) + { + app.type_ime.interrupt = true; + interrupt = true; + } + let mut sent = false; + let mut sent_generation = None; + if let (Some(update), Some((rect, cursor_rect))) = (update, geometry) { + let generation = update.context_generation; + // Owner and generation accompany even an Unavailable payload. The cause comes from the + // tracker's accepted-receipt chain, never from the event that happened to be last. + ctx.output_mut(|out| { + out.ime = Some(egui::output::IMEOutput { + owner: update.owner, + context_generation: update.context_generation, + purpose: update.purpose, + rect, + cursor_rect, + should_interrupt_composition: interrupt, + change_cause: update.change_cause, + surrounding_text: update.surrounding_text, + reset_request: None, + }); + }); + let key = ctx.output(|out| out.ime.as_ref().map(ResetContext::from)); + app.type_ime.custom_pass.insert(viewport, (pass_nr, key)); + sent = true; + sent_generation = Some(generation); + } + if sent && !ctx.will_discard() { + if let Some(generation) = sent_generation { + app.type_ime.emitted = Some(ImeEmitted { target, generation }); + } + app.type_ime.interrupt = false; + app.type_ime.stale = false; + } +} + +/// The final caret and layer rectangles for an IME descriptor, in screen points. +pub(super) fn ime_geometry(app: &mut PhotocraftApp, ed: &TextEdit, xf: ViewXform) -> Option<(egui::Rect, egui::Rect)> { + let id = LayerId(ed.layer); + let (l, aff, text) = layout(app, id)?; + let shape = app.session.active().and_then(|s| text_layer(&s.doc, id).map(|t| t.shape.clone())); + let bend = shape.as_ref().and_then(photocraft_text::warp::Warp::on_path); + let scr_t = |x: f32, y: f32| -> Pos2 { + let p = aff.apply(Point::new(f64::from(x), f64::from(y))); + xf.to_screen(p.x as f32, p.y as f32) + }; + let scr = |x: f32, y: f32| -> Pos2 { + let (x, y) = l.to_text(x, y); + match &bend { + Some(w) => { + let (x, y) = w.apply(f64::from(x), f64::from(y)); + scr_t(x as f32, y as f32) + } + None => scr_t(x, y), + } + }; + let (x, top, bot) = l.caret(byte_of(&text, ed.caret)); + let (x, top, bot) = if l.lines.is_empty() { (0.0, -(12.0 * l.px_per_pt.max(1.0)), 3.0) } else { (x, top, bot) }; + let cursor = egui::Rect::from_two_pos(scr(x, top), scr(x, bot)).expand(1.0); + let doc_bounds = + app.session.active().and_then(|s| text_layer(&s.doc, id)).and_then(|t| t.cache.as_ref()).map(|c| c.content_bounds()).filter(|r| !r.is_empty()); + let rect = doc_bounds.map(|r| xf.doc_rect(r)).or_else(|| { + l.bounds().map(|b| { + let corners = [scr_t(b[0], b[1]), scr_t(b[2], b[1]), scr_t(b[2], b[3]), scr_t(b[0], b[3])]; + let mut min = corners[0]; + let mut max = corners[0]; + for p in corners { + min = min.min(p); + max = max.max(p); + } + egui::Rect::from_min_max(min, max) + }) + }); + Some((rect.unwrap_or(cursor).expand(1.0), cursor)) +} + +/// IME composition. The preedit text is written into the layer (so it lays out and reflows like +/// typed text) and replaced by every update; `commit` makes the result final. +pub(super) fn ime_update(app: &mut PhotocraftApp, s: &str, commit: bool) { + let Some(ed) = app.ui.text_edit.clone() else { return }; + // Validate the composition only while one exists: a plain preedit/commit otherwise needs no + // copy of the whole layer. + let n = if ed.preedit.is_some() { + let Some(text) = current_text(app, LayerId(ed.layer)) else { return }; + // A composition range that no longer holds the recorded composition belongs to an edit + // that was replaced under it: never use it to delete or replace text. + if reconcile_preedit(app, &ed, &text) { + return; + } + text.chars().count() + } else { + let Some(n) = text_char_count(app, LayerId(ed.layer)) else { return }; + n + }; + let s = s.replace("\r\n", "\n").replace('\r', "\n"); + // An empty preedit or commit while nothing is being composed changes nothing. Wayland input + // methods send one on every state change (the caret rectangle moving as a selection grows), + // and it used to replace the selection, deleting the text as it was selected (#1381). + if s.is_empty() && ed.preedit.is_none() { + return; + } + let (start, end) = match ed.preedit { + Some((p, l)) if p.saturating_add(l) <= n => (p, p + l), + _ => (ed.caret.min(ed.anchor).min(n), ed.caret.max(ed.anchor).min(n)), + }; + if start == end && s.is_empty() { + if let Some(e) = app.ui.text_edit.as_mut() { + e.preedit = None; + } + app.type_ime.clear_preedit(); + return; + } + // Capture the committed text *before* the engine runs. The pre-edit is excluded from this + // and from the after snapshot; only an accepted commit earns an IME receipt. + let before = if commit { ime_committed(app, &ed) } else { None }; + let len = s.chars().count(); + crate::type_transform::finish(app); + if app.run("type.edit", json!({"layer": ed.layer, "replace": {"start": start, "end": end, "text": s}, "coalesce": ed.session})).is_err() { + return; + } + let mut after_ed = ed.clone(); + after_ed.caret = start + len; + after_ed.anchor = after_ed.caret; + after_ed.preedit = if commit || len == 0 { None } else { Some((start, len)) }; + if let Some(e) = app.ui.text_edit.as_mut() { + *e = after_ed.clone(); + } + if after_ed.preedit.is_some() { + app.type_ime.note_preedit(&after_ed, &s); + } else { + app.type_ime.clear_preedit(); + } + if commit { + app.type_ime.incoming = None; + } else { + remember_incoming(app, Some(s.is_empty())); + } + if commit + && let Some(before) = before + && let Some(after) = ime_committed(app, &after_ed) + { + // A no-op commit (equal snapshots) is rejected by the tracker rather than fabricated. + note_ime_apply(app, &after_ed, &before, &after); + } +} + +/// The active range for an IME delete-surrounding batch: the pre-edit when composing, otherwise +/// the sorted selection. Returns `(start, end, length)` in character indices. +fn ime_active_range(app: &PhotocraftApp, ed: &TextEdit) -> Option<(usize, usize, usize)> { + let n = text_char_count(app, LayerId(ed.layer))?; + if let Some((start, len)) = ed.preedit { + let end = start.checked_add(len)?; + return (end <= n).then_some((start, end, n)); + } + let a = ed.caret.min(n); + let b = ed.anchor.min(n); + Some((a.min(b), a.max(b), n)) +} + +/// Delete characters around the selection/pre-edit, as one coalesced type edit. +pub(super) fn ime_delete_chars(app: &mut PhotocraftApp, before_chars: usize, after_chars: usize) -> bool { + let Some(ed) = app.ui.text_edit.clone() else { return false }; + if ed.preedit.is_some() { + let Some(text) = current_text(app, LayerId(ed.layer)) else { return false }; + if reconcile_preedit(app, &ed, &text) { + return false; + } + } + let Some((start, end, n)) = ime_active_range(app, &ed) else { return false }; + let from = start.saturating_sub(before_chars); + let to = end.saturating_add(after_chars).min(n); + ime_delete_around(app, ed, from, start, end, to) +} + +/// `DeleteSurroundingBytes` counts UTF-8 bytes from the active range's edges. A byte count that +/// ends inside a character leaves that character, as the stock TextEdit does. +pub(super) fn ime_delete_bytes(app: &mut PhotocraftApp, before_bytes: usize, after_bytes: usize) -> bool { + let Some(ed) = app.ui.text_edit.clone() else { return false }; + let Some(text) = current_text(app, LayerId(ed.layer)) else { return false }; + if reconcile_preedit(app, &ed, &text) { + return false; + } + let Some((start, end, n)) = ime_active_range(app, &ed) else { return false }; + let start_byte = byte_of(&text, start); + let end_byte = byte_of(&text, end); + let from_byte = start_byte.saturating_sub(before_bytes); + let before_chars = text.get(..start_byte).map_or(0, |before| before.char_indices().rev().take_while(|(index, _)| *index >= from_byte).count()); + let after_chars = + text.get(end_byte..).map_or(0, |after| after.char_indices().take_while(|(index, character)| index + character.len_utf8() <= after_bytes).count()); + let from = start.saturating_sub(before_chars); + let to = end.saturating_add(after_chars).min(n); + ime_delete_around(app, ed, from, start, end, to) +} + +/// Apply one accepted IME deletion and record its receipt from the snapshots around it. +/// +/// The active selection/pre-edit itself stays; only the requested runs before `start` and after +/// `end` are removed. They are two engine mutations with the same coalescing key (one history +/// step), and one receipt covers the whole batch. +fn ime_delete_around(app: &mut PhotocraftApp, ed: TextEdit, from: usize, start: usize, end: usize, to: usize) -> bool { + if from >= start && end >= to { + return false; + } + let before = ime_committed(app, &ed); + crate::type_transform::finish(app); + // Delete the trailing run first so the leading run's character indices stay valid. + if end < to && app.run("type.edit", json!({"layer": ed.layer, "replace": {"start": end, "end": to, "text": ""}, "coalesce": ed.session})).is_err() { + return false; + } + if from < start && app.run("type.edit", json!({"layer": ed.layer, "replace": {"start": from, "end": start, "text": ""}, "coalesce": ed.session})).is_err() { + return false; + } + let shift = start - from; + let mut after_ed = ed.clone(); + after_ed.caret = ed.caret.saturating_sub(shift); + after_ed.anchor = ed.anchor.saturating_sub(shift); + if let Some((preedit_start, preedit_len)) = ed.preedit { + after_ed.preedit = Some((preedit_start.saturating_sub(shift), preedit_len)); + } + if let Some(e) = app.ui.text_edit.as_mut() { + *e = after_ed.clone(); + } + if let (Some(before), Some(after)) = (before, ime_committed(app, &after_ed)) { + note_ime_apply(app, &after_ed, &before, &after); + } + remember_incoming(app, None); + true +} diff --git a/crates/ui-egui/src/type_tool/keys.rs b/crates/ui-egui/src/type_tool/keys.rs new file mode 100644 index 0000000000..98820ab0a5 --- /dev/null +++ b/crates/ui-egui/src/type_tool/keys.rs @@ -0,0 +1,347 @@ +use super::editing::{ + CharToggle, cancel, commit, commit_with, copy_selection, cut_selection, end_if_left, insert, insert_typed, kern_pair, step_char_metric, toggle_char_style, + toggle_hyphenate, +}; +use super::ime::{ + bind_reset_context, claim_raw_pass, complete_reset, controls_only, ime_target, interrupt_action, interrupt_incoming, prepare_reset, reset_guarded, + reset_route_eligible, suspend_reset, sync_incoming, +}; +use super::ime_edit::{ime_delete_bytes, ime_delete_chars, ime_update}; +use super::layout::layout; +use super::pointer::word_boundary; +use super::*; + +/// Caret on the neighbouring line (±1; a column in vertical type), keeping the position +/// along the line. Works in line space, so it serves both orientations. +fn line_step(app: &mut PhotocraftApp, id: LayerId, caret: usize, dir: i32) -> usize { + let Some((l, _, text)) = layout(app, id) else { return caret }; + let x = l.caret(byte_of(&text, caret)).0; + photocraft_text::line_step(&l, &text, caret, x, dir) +} + +pub(super) fn is_vertical(app: &PhotocraftApp, id: LayerId) -> bool { + app.session.active().and_then(|s| text_layer(&s.doc, id)).is_some_and(|t| t.orientation == photocraft_doc::text::Orientation::Vertical) +} + +/// Arrow keys follow the text flow: in vertical type ↑/↓ move along the column (previous/next +/// character) and ←/→ move to the next/previous column (columns advance right to left). Returns +/// the horizontal-type key with the same meaning. +pub(crate) fn flow_key(key: egui::Key, vertical: bool) -> egui::Key { + use egui::Key; + if !vertical { + return key; + } + match key { + Key::ArrowUp => Key::ArrowLeft, + Key::ArrowDown => Key::ArrowRight, + Key::ArrowLeft => Key::ArrowDown, + Key::ArrowRight => Key::ArrowUp, + k => k, + } +} + +/// Line start / end for the caret's line. +fn line_edge(app: &mut PhotocraftApp, id: LayerId, caret: usize, end: bool) -> usize { + let Some((l, _, text)) = layout(app, id) else { return caret }; + photocraft_text::line_edge(&l, &text, caret, end) +} + +/// Keyboard input while editing. Returns true when a type edit session is active (single-key +/// tool shortcuts must then be skipped). Handled events are removed from the frame's input. +pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { + bind_reset_context(app, ctx); + // A receipt is only valid for the frame that produced it; never reuse last frame's. + app.type_ime.frame = None; + end_if_left(app); + sync_incoming(app, ctx.viewport_id()); + if !ctx.input(|i| i.focused) || ctx.text_edit_focused() || ctx.egui_wants_keyboard_input() { + interrupt_incoming(app); + } + crate::type_transform::cancel_stale(app); + if !ctx.input(|i| i.focused) { + crate::type_transform::cancel_drag(app); + } + let Some(ed) = app.ui.text_edit.clone() else { + controls_only(app, ctx); + return false; + }; + // The font picker (and other focused fields) owns keyboard input while it is open. + if !reset_route_eligible(app, ctx) { + controls_only(app, ctx); + return true; + } + let id = LayerId(ed.layer); + let Some(n) = text_char_count(app, id) else { + app.ui.text_edit = None; + app.ui.text_edit_return_tool = None; + app.type_ime.clear_preedit(); + controls_only(app, ctx); + return false; + }; + // Undo/redo can shorten the text under us. + if let Some(e) = app.ui.text_edit.as_mut() { + e.caret = e.caret.min(n); + e.anchor = e.anchor.min(n); + } + if !claim_raw_pass(app, ctx) { + return true; + } + app.type_ime.begin_frame(ctx); + prepare_reset(app, ctx); + // A target swap (session replacement, Type Mask, another layer) is known from the last + // descriptor the platform received. Cancel the native composition before any event in this + // pass can be applied to the new target. + if ime_target(app, &ed, ctx.viewport_id()).is_some_and(|target| app.type_ime.emitted.is_some_and(|last| last.target != target)) { + app.type_ime.interrupt = true; + } + let time = ctx.input(|i| i.time); + let elapsed = (time - app.ui.caret_blink_time).max(0.0); + let period = 0.530; + let remaining = period - (elapsed % period); + ctx.request_repaint_after(std::time::Duration::from_secs_f64(remaining.clamp(0.010, period))); + let events = ctx.input(|i| i.events.clone()); + let vertical_flow = is_vertical(app, id); + let mut handled = vec![false; events.len()]; + let mut primary_down = events + .iter() + .find_map(|event| match event { + egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed, .. } => Some(!pressed), + _ => None, + }) + .unwrap_or_else(|| ctx.input(|input| input.pointer.primary_down())); + let mut custom_mutations = true; + let mut deferred_custom = false; + for (k, ev) in events.iter().enumerate() { + if custom_mutations && !reset_route_eligible(app, ctx) { + custom_mutations = false; + suspend_reset(app, ctx); + } + if !custom_mutations { + if let egui::Event::ImeResetCompleted { request_id } = ev { + complete_reset(app, ctx, *request_id); + if let Some(slot) = handled.get_mut(k) { + *slot = true; + } + } else if deferred_custom + && matches!(ev, egui::Event::Text(_) | egui::Event::Paste(_) | egui::Event::Cut | egui::Event::Ime(_)) + && let Some(slot) = handled.get_mut(k) + { + *slot = true; + } + continue; + } + prepare_reset(app, ctx); + let Some(ed) = app.ui.text_edit.clone() else { continue }; + let (a, b) = (ed.caret.min(ed.anchor), ed.caret.max(ed.anchor)); + // Only key handling needs the text (word/line edges); pointer, clipboard and IME events + // do not clone the whole layer. + let is_key = matches!(ev, egui::Event::Key { .. }); + let text = if is_key { current_text(app, id).unwrap_or_default() } else { String::new() }; + let n = if is_key { text.chars().count() } else { 0 }; + let set = |app: &mut PhotocraftApp, caret: usize, extend: bool| { + if let Some(e) = app.ui.text_edit.as_mut() { + e.caret = caret.min(n); + if !extend { + e.anchor = e.caret; + } + } + }; + handled[k] = true; + match ev { + egui::Event::Text(s) => insert_typed(app, s), + egui::Event::Paste(s) => insert(app, s), + egui::Event::ImeResetCompleted { request_id } => complete_reset(app, ctx, *request_id), + egui::Event::Ime(ime_event) => { + // Untagged terminal payload cannot acknowledge a host reset. Only the exact + // current completion arm above may open admission for the following element. + if reset_guarded(app, ctx.viewport_id()) { + continue; + } + match ime_event { + // A bare line break from the IME is the Enter key, which the key arm handles. + egui::ImeEvent::Preedit { text: s, .. } | egui::ImeEvent::Commit(s) if s == "\n" || s == "\r" => handled[k] = false, + egui::ImeEvent::Preedit { text, .. } => ime_update(app, text, false), + egui::ImeEvent::Commit(s) => { + ime_update(app, s, true); + app.type_ime.incoming = None; + } + egui::ImeEvent::DeleteSurrounding { before_chars, after_chars } => { + ime_delete_chars(app, *before_chars, *after_chars); + } + egui::ImeEvent::DeleteSurroundingBytes { before_bytes, after_bytes } => { + ime_delete_bytes(app, *before_bytes, *after_bytes); + } + _ => {} + } + } + egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed, .. } => { + primary_down = *pressed; + if *pressed { + // The canvas destination handler runs after this pass; never apply a + // same-batch Text/Paste/Cut/IME suffix at the old caret just because no + // composition or reset guard existed yet. + interrupt_action(app, ctx.viewport_id()); + custom_mutations = false; + deferred_custom = true; + suspend_reset(app, ctx); + } + handled[k] = false; + } + egui::Event::PointerMoved(_) if primary_down => { + interrupt_action(app, ctx.viewport_id()); + custom_mutations = false; + deferred_custom = true; + suspend_reset(app, ctx); + handled[k] = false; + } + egui::Event::Copy => { + copy_selection(app, ctx); + } + egui::Event::Cut => cut_selection(app, ctx), + egui::Event::Key { key, pressed: true, modifiers: m, .. } => { + use egui::Key; + let key = &flow_key(*key, vertical_flow); + match key { + // Photoshop's type formatting keys act on the selected characters and win + // over the global ⇧⌘K/U/B/I (Color Settings, Desaturate, Auto Color, Inverse) + // while typing. Each press is one history step. + Key::K | Key::U | Key::B | Key::I | Key::Slash | Key::Questionmark if m.command && m.shift && !m.alt => { + let which = match key { + Key::K => CharToggle::AllCaps, + Key::U => CharToggle::Underline, + Key::B => CharToggle::FauxBold, + Key::I => CharToggle::FauxItalic, + _ => CharToggle::Strikethrough, + }; + toggle_char_style(app, which); + } + Key::H if m.command && m.shift && m.alt => toggle_hyphenate(app), + // ⌥↑/↓ leading -/+2 pt, ⇧⌥↑/↓ baseline shift +/-2 pt (10 with ⌘/Ctrl). + Key::ArrowUp | Key::ArrowDown if m.alt => { + let step = if m.command { 10.0 } else { 2.0 }; + let up = *key == Key::ArrowUp; + if m.shift { + step_char_metric(app, "baselineShiftBy", if up { step } else { -step }); + } else { + step_char_metric(app, "leadingBy", if up { -step } else { step }); + } + } + // ⌥←/→ over a selection tracks it by -/+20 (100 with ⌘/Ctrl). + Key::ArrowLeft | Key::ArrowRight if m.alt && !m.shift && a != b => { + let step = if m.command { 100.0 } else { 20.0 }; + step_char_metric(app, "trackingBy", if *key == Key::ArrowRight { step } else { -step }); + } + Key::Backspace | Key::Delete => { + if a == b { + let fwd = *key == Key::Delete; + let to = match (fwd, m.alt, m.command) { + (false, _, true) => line_edge(app, id, a, false), + (false, true, _) => word_boundary(&text, a, false), + (false, _, _) => a.saturating_sub(1), + (true, true, _) => word_boundary(&text, a, true), + (true, _, _) => (a + 1).min(n), + }; + if to != a { + if let Some(e) = app.ui.text_edit.as_mut() { + e.anchor = to; + } + insert(app, ""); + } + } else { + insert(app, ""); + } + } + // Photoshop: Alt/Option+←/→ at a collapsed caret kerns the pair before it by + // 20/1000 em (100 with ⌘/Ctrl), one history step per press. + Key::ArrowLeft | Key::ArrowRight if m.alt && !m.shift && a == b => { + let step = if m.command { 100.0 } else { 20.0 }; + kern_pair(app, id, ed.caret, if *key == Key::ArrowRight { step } else { -step }); + } + Key::ArrowLeft | Key::ArrowRight => { + let fwd = *key == Key::ArrowRight; + // Word movement: ⌘/Ctrl (Photoshop's; Alt is kerning), and Alt+Shift + // extends the selection by words; Home/End go to the line edges. + let to = if m.command || m.alt { + word_boundary(&text, ed.caret, fwd) + } else if a != b && !m.shift { + if fwd { b } else { a } + } else if fwd { + ed.caret + 1 + } else { + ed.caret.saturating_sub(1) + }; + set(app, to, m.shift); + } + Key::ArrowUp | Key::ArrowDown => { + let to = if m.command { + if *key == Key::ArrowUp { 0 } else { n } + } else { + line_step(app, id, ed.caret, if *key == Key::ArrowUp { -1 } else { 1 }) + }; + set(app, to, m.shift); + } + Key::Home | Key::End => { + let to = line_edge(app, id, ed.caret, *key == Key::End); + set(app, to, m.shift); + } + Key::Enter if m.command => commit_with(app, *m), + Key::Enter => insert(app, "\n"), + // Photoshop types a tab character; layout advances it to the next tab stop. + Key::Tab if !m.command && !m.alt && !m.shift => { + // egui queues focus navigation before this handler runs; consuming the + // key alone would let the menu bar take focus after the first tab (#8889). + ctx.memory_mut(|m| m.move_focus(egui::FocusDirection::None)); + insert(app, "\t"); + } + Key::Escape if crate::type_transform::active(app) => crate::type_transform::cancel_drag(app), + // The Type Mask tools: Escape always cancels, leaving the selection as it was. + Key::Escape if ed.mask => cancel(app), + // Preferences ▸ Type: with "Use Escape to Commit" off, Escape cancels the + // session (undoes it, removing a just-created layer) like the Cancel button. + Key::Escape if app.session.prefs().type_.use_esc_to_commit => commit(app), + Key::Escape => cancel(app), + Key::A if m.command => { + if let Some(e) = app.ui.text_edit.as_mut() { + e.anchor = 0; + e.caret = n; + } + } + // Photoshop: while editing type, ⌘/Ctrl+T shows or hides the Character panel + // (Free Transform of the layer being typed into is not what it means here). + Key::T if m.command && !m.shift && !m.alt => { + let _ = crate::menus::invoke(app, ctx, "window.panel.character", json!({})); + } + // Other command shortcuts (⌘Z, ⌘S, …) pass through to the menus. + _ if m.command => { + if *key == Key::Z { + crate::type_transform::cancel_drag(app); + } + if reset_guarded(app, ctx.viewport_id()) || app.type_ime.incoming.is_some() { + interrupt_action(app, ctx.viewport_id()); + custom_mutations = false; + deferred_custom = true; + suspend_reset(app, ctx); + } + handled[k] = false; + } + _ => {} + } + } + egui::Event::Key { pressed: false, modifiers: m, .. } => handled[k] = !m.command, + _ => handled[k] = false, + } + } + prepare_reset(app, ctx); + if handled.iter().any(|h| *h) { + app.ui.caret_blink_time = ctx.input(|i| i.time); + let mut k = 0; + ctx.input_mut(|i| { + i.events.retain(|_| { + let keep = !handled.get(k).copied().unwrap_or(false); + k += 1; + keep + }) + }); + } + app.ui.text_edit.is_some() +} diff --git a/crates/ui-egui/src/type_tool/layout.rs b/crates/ui-egui/src/type_tool/layout.rs new file mode 100644 index 0000000000..adfb3e910d --- /dev/null +++ b/crates/ui-egui/src/type_tool/layout.rs @@ -0,0 +1,87 @@ +use super::*; + +/// Layout of a type layer (cached per document revision) and its text → document transform. +pub fn layout(app: &mut PhotocraftApp, id: LayerId) -> Option<(Arc, Affine, String)> { + let dragged = crate::type_transform::current_transform(app, id); + // Borrows the document in place (no clone): the canvas hover hit-tests type every frame. + let st = app.session.active()?; + let t = text_layer(&st.doc, id)?; + let transform = dragged.unwrap_or(t.transform); + let key = (st.doc.id.0, st.revision, id.0); + if let Some((k, l)) = &app.type_layout + && *k == key + { + return Some((l.clone(), transform, t.text.clone())); + } + let l = Arc::new(photocraft_text::shared().lock().ok()?.layout(t, st.doc.resolution_dpi)); + app.type_layout = Some((key, l.clone())); + Some((l, transform, t.text.clone())) +} + +pub(super) fn to_text(aff: &Affine, x: f64, y: f64) -> (f32, f32) { + let p = aff.inverse().unwrap_or(Affine::IDENTITY).apply(Point::new(x, y)); + (p.x as f32, p.y as f32) +} + +/// Topmost shown type layer (it and every group around it visible, #4320) whose laid-out text +/// contains the document point. The press and the canvas hover (`hover_path_target`) share it, so +/// the pointer never promises a path click that the press would turn into editing this layer. +pub(crate) fn hit_layer(app: &mut PhotocraftApp, x: f64, y: f64) -> Option { + let slop = 6.0 / app.point_zoom().max(0.01); + // A Type Mask session's text is a hidden layer; it is still the text being edited. + let editing = app.ui.text_edit.as_ref().filter(|ed| ed.mask).map(|ed| LayerId(ed.layer)); + let mut ids: Vec = { + let doc = &app.session.active()?.doc; + doc.walk() + .into_iter() + .filter(|(path, _, l)| matches!(l.content, LayerContent::Text(_)) && (editing == Some(l.id) || doc.shown_at(path))) + .map(|(_, _, l)| l.id) + .collect() + }; + ids.reverse(); // walk() is bottom-up; hit the topmost first + ids.into_iter().find(|id| { + // The pixels shown count too: a PSD's type keeps Photoshop's rendering until edited, + // which can sit off our layout when fonts are substituted (#123). + let shown = app.session.active().and_then(|st| text_layer(&st.doc, *id)).and_then(|t| t.cache.as_ref()).map(|c| c.content_bounds()).is_some_and(|r| { + let s = f64::from(slop); + !r.is_empty() && x >= f64::from(r.x0) - s && x <= f64::from(r.x1) + s && y >= f64::from(r.y0) - s && y <= f64::from(r.y1) + s + }); + // The hover calls this every frame: skip the layout when the pixels already answer. + if shown { + return true; + } + let Some((l, aff, _)) = layout(app, *id) else { return false }; + let (tx, ty) = to_text(&aff, x, y); + photocraft_text::text_point_inside(&l, tx, ty, slop) + }) +} + +/// True when the layer's pixels are what our engine draws for it. A PSD's type layer keeps +/// Photoshop's pixels until it is edited, and with substituted fonts or a different line layout +/// they sit somewhere else than the glyphs the caret and selection are placed on. +pub(crate) fn shows_own_layout(doc: &Document, t: &TextLayer) -> bool { + let Some(cache) = &t.cache else { return false }; + let mut eng = photocraft_text::shared().lock().unwrap_or_else(PoisonError::into_inner); + let ours = eng.render(t, doc.resolution_dpi, doc.pixel_format()).1.surface.content_bounds(); + let have = cache.content_bounds(); + [(ours.x0, have.x0), (ours.y0, have.y0), (ours.x1, have.x1), (ours.y1, have.y1)].iter().all(|(a, b)| (a - b).abs() <= 1) +} + +pub(super) fn hit_offset(app: &mut PhotocraftApp, id: LayerId, x: f64, y: f64) -> usize { + offset_at(app, id, x, y) +} + +/// The character offset of the caret position nearest document point (`x`, `y`) in layer `id`. +pub(crate) fn offset_at(app: &mut PhotocraftApp, id: LayerId, x: f64, y: f64) -> usize { + let Some((l, aff, text)) = layout(app, id) else { return 0 }; + let (tx, ty) = to_text(&aff, x, y); + // Type on a path: the point's place along the path is the position in the (single) line. + let shape = app.session.active().and_then(|s| text_layer(&s.doc, id).map(|t| t.shape.clone())); + let (tx, ty) = match shape { + Some(photocraft_doc::text::TextShape::Path { path, start, flip }) => { + photocraft_text::warp::arc_length_at(&path, flip, f64::from(tx), f64::from(ty)).map_or((tx, ty), |s| ((s - f64::from(start)) as f32, -1.0)) + } + _ => (tx, ty), + }; + photocraft_text::hit_char(&l, &text, tx, ty).0 +} diff --git a/crates/ui-egui/src/type_tool/options_bar.rs b/crates/ui-egui/src/type_tool/options_bar.rs new file mode 100644 index 0000000000..413cf58455 --- /dev/null +++ b/crates/ui-egui/src/type_tool/options_bar.rs @@ -0,0 +1,405 @@ +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::keys::is_vertical; +use super::*; + +/// Photoshop's Type options bar. +pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = crate::theme::Tokens::get(ui.ctx()); + // Show the target layer's (first-run) style, else the tool defaults. + let shown = target(app).and_then(|(id, _)| { + let st = app.session.active()?; + let tl = text_layer(&st.doc, LayerId(id))?; + let run = tl.char_runs().into_iter().next().map(|r| r.style); + // The size at the selection (else the first run), as the layer shows it (#124). + let size = styles_at(app).map_or(tl.size_pt, |(c, _)| c.size_pt) * shown_scale(app); + Some((tl.font_family.clone(), run.as_ref().map(selected_style).unwrap_or_default(), size, styles_at(app).map_or(tl.color, |(c, _)| c.color))) + }); + let o = app.ui.tool_options.clone(); + let (mut fam, mut style, size) = match &shown { + Some((f, s, z, _)) => (f.clone(), if s.is_empty() { "Regular".into() } else { s.clone() }, *z), + None => (o.type_font.clone(), o.type_style.clone(), o.type_size), + }; + if crate::icons::button(ui, "text-cursor", 24.0, false, tl!("Toggle text orientation")).clicked() + && let Some((layer, _)) = target(app) + && let Some(params) = formatting_params(app) + { + let to = if is_vertical(app, LayerId(layer)) { "horizontal" } else { "vertical" }; + if let Err(e) = app.run(&format!("type.orientation.{to}"), params) { + app.ui.status = e; + app.ui.status_error = true; + } + } + // Font family and style menus (one placeholder in their place while the fonts load). + if fonts_ready(ui, 170.0 + ui.spacing().item_spacing.x + 110.0) { + if font_picker(ui, &mut fam, 170.0, app.session.prefs().type_.font_preview, &app.ui.recent_fonts) { + app.note_recent_font(&fam); + app.ui.tool_options.type_font = fam.clone(); + let st = styles(&fam); + style = if st.contains(&style) { style } else { st.first().cloned().unwrap_or_else(|| "Regular".into()) }; + app.ui.tool_options.type_style = style.clone(); + apply(app, ui.ctx(), json!({"font": fam})); + } + let opts: Vec<(String, String)> = styles(&fam).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(); + if crate::widgets::dropdown(ui, "type-style", tl!("Style"), &mut style, &opts_ref, 110.0) { + app.ui.tool_options.type_style = style.clone(); + apply(app, ui.ctx(), json!({"fontStyle": 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")); + 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() { + let size = display / unit; + app.ui.tool_options.type_size = size; + apply(app, ui.ctx(), json!({"size": size, "metricsAsShown": true})); + } + let mut aa = target(app) + .and_then(|(id, _)| app.session.active().and_then(|st| text_layer(&st.doc, LayerId(id)))) + .map(|t| photocraft_engine::type_extra_cmds::aa_name(t.antialias).to_string()) + .unwrap_or_else(|| o.type_aa.clone()); + let aa_opts = [ + ("none".to_string(), tl!("None")), + ("sharp".to_string(), tl!("Sharp")), + ("crisp".to_string(), tl!("Crisp")), + ("strong".to_string(), tl!("Strong")), + ("smooth".to_string(), tl!("Smooth")), + ]; + if crate::widgets::dropdown(ui, "type-aa", tl!("Anti-aliasing method"), &mut aa, &aa_opts, 80.0) { + app.ui.tool_options.type_aa = aa.clone(); + if let Some(params) = formatting_params(app) { + let _ = app.run(&format!("type.antiAlias.{aa}"), params); + } + } + crate::widgets::vline(ui, 22.0); + ui.spacing_mut().item_spacing.x = 2.0; + // Alignment and direction show the target paragraph's, as Photoshop's bar follows the text + // being edited or the selected type layer; the tool defaults otherwise. A justified paragraph + // lights none of the three. + let para = styles_at(app).map(|(_, p)| p); + let shown_align = match ¶ { + Some(p) => match p.align { + photocraft_doc::text::TextAlign::Left => "left", + photocraft_doc::text::TextAlign::Center => "center", + photocraft_doc::text::TextAlign::Right => "right", + _ => "", + }, + None => o.type_align.as_str(), + }; + for (align, icon, tip) in + [("left", "align-left", tl!("Left align text")), ("center", "align-center", tl!("Center text")), ("right", "align-right", tl!("Right align text"))] + { + 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})); + } + } + ui.spacing_mut().item_spacing.x = 8.0; + crate::widgets::vline(ui, 22.0); + ui.spacing_mut().item_spacing.x = 2.0; + for (key, tip, d) in direction_items() { + let on = para.as_ref().map_or(o.type_direction == key, |p| p.direction == d); + if direction_button(ui, d, on, tip).clicked() { + app.ui.tool_options.type_direction = key.into(); + apply(app, ui.ctx(), json!({"direction": key})); + } + } + ui.spacing_mut().item_spacing.x = 8.0; + crate::widgets::vline(ui, 22.0); + // Text colour swatch with a picker popup. + let c = shown + .as_ref() + .map(|s| s.3) + .map(|c| { + let v = c.to_rgb(); + [v[0], v[1], v[2], 1.0] + }) + .unwrap_or(app.session.tools.foreground); + let (rect, resp) = ui.allocate_exact_size(egui::vec2(28.0, 18.0), egui::Sense::click()); + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + ui.painter().rect_filled(rect, 2.0, Color32::from_rgb(q(c[0]), q(c[1]), q(c[2]))); + ui.painter().rect_stroke(rect, 2.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside); + let resp = resp.on_hover_text(tl!("Set the 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]]); + } + // Create warped text, after the swatch as in Photoshop (#5911): the Type › Warp Text… dialog. + let can_warp = crate::menus::is_enabled(app, "type.warpText"); + if ui.add_enabled_ui(can_warp, |ui| crate::icons::button(ui, "text-warp", 24.0, false, tl!("Create warped text"))).inner.clicked() + && let Err(e) = crate::menus::invoke(app, &ui.ctx().clone(), "type.warpText", json!({})) + { + app.ui.status = e; + app.ui.status_error = true; + } + if app.ui.text_edit.is_some() { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_space(8.0); + if crate::icons::button( + ui, + "check", + 24.0, + false, + &crate::i18n::fmt(tl!("Commit any current edits ({key})"), &[("key", &crate::shortcuts::pretty("Cmd+Enter"))]), + ) + .clicked() + { + commit_with(app, ui.input(|i| i.modifiers)); + } + if crate::icons::button(ui, "ban", 24.0, false, tl!("Cancel any current edits (Esc)")).clicked() { + cancel(app); + } + }); + } +} + +/// Character and paragraph style at the target (selection start, else the layer's first run). +/// The paragraph at a collapsed caret is the caret's, as Photoshop's options bar and Paragraph +/// panel show it. +pub(crate) fn styles_at(app: &PhotocraftApp) -> Option<(photocraft_doc::text::CharStyle, photocraft_doc::text::ParagraphStyle)> { + let (layer, range) = target(app)?; + let t = text_layer(&target_doc(app)?.doc, LayerId(layer))?; + let at = range.map_or(0, |r| byte_of(&t.text, r[0])); + let para_at = match (range, &app.ui.text_edit) { + (None, Some(ed)) => byte_of(&t.text, ed.caret), + _ => at, + }; + let pick_at = |at: usize, lens: Vec| -> usize { + let mut acc = 0; + for (i, len) in lens.iter().enumerate() { + acc += len; + if at < acc { + return i; + } + } + lens.len().saturating_sub(1) + }; + let runs = t.char_runs(); + let paras = t.paragraph_runs(); + let c = runs.get(pick_at(at, runs.iter().map(|r| r.len).collect())).map(|r| r.style.clone())?; + let p = paras.get(pick_at(para_at, paras.iter().map(|r| r.len).collect())).map(|r| r.style.clone()).unwrap_or_default(); + Some((c, p)) +} + +/// Kerning shown for the target: at a collapsed caret, the pair before it (Photoshop's +/// Character panel); else the style at the selection. +pub(super) fn kerning_at(app: &PhotocraftApp) -> Option<(photocraft_doc::text::Kerning, f32)> { + let ed = app.ui.text_edit.as_ref().filter(|e| e.caret == e.anchor && e.caret > 0)?; + let st = app.session.active()?; + let t = text_layer(&st.doc, LayerId(ed.layer))?; + let at = byte_of(&t.text, ed.caret - 1); + let mut end = 0; + t.char_runs() + .into_iter() + .find(|r| { + end += r.len; + at < end + }) + .map(|r| (r.style.kerning, r.style.kern)) +} + +/// The Character panel's kerning text: "Metrics", "Optical" or the manual value. +pub(crate) fn kerning_label((mode, kern): (photocraft_doc::text::Kerning, f32)) -> String { + use photocraft_doc::text::Kerning; + match mode { + _ if kern != 0.0 && kern.is_finite() => format!("{}", kern.round() as i64), + Kerning::Metrics => "Metrics".into(), + Kerning::Optical => "Optical".into(), + Kerning::Off => "0".into(), + } +} + +/// Parses a typed kerning value: Metrics / Optical (any case) or a number in 1/1000 em +/// (Photoshop's range, -1000..10000). `None` for anything else. +pub(crate) fn parse_kerning(s: &str) -> Option { + let s = s.trim(); + match s.to_ascii_lowercase().as_str() { + "metrics" => Some(json!("metrics")), + "optical" => Some(json!("optical")), + _ => crate::numeric_expression::parse(s).filter(|v| v.is_finite() && (-1000.0..=10000.0).contains(v)).map(|v| json!(v.round())), + } +} + +/// Photoshop's editable kerning combo: type a value or Metrics/Optical, or pick a preset. +pub(super) fn kerning_field(ui: &mut egui::Ui, shown: &str, width: f32) -> Option { + let id = ui.make_persistent_id("props-kern-text"); + let mut buf: String = ui.data_mut(|d| d.get_temp::(id)).unwrap_or_else(|| shown.to_string()); + let mut out = None; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + let resp = ui.add(egui::TextEdit::singleline(&mut buf).desired_width((width - 40.0).max(24.0)).id(id.with("edit"))).accessible_name(tl!("Kerning")); + if resp.has_focus() { + ui.data_mut(|d| d.insert_temp(id, buf.clone())); + } else { + ui.data_mut(|d| d.remove::(id)); + } + if resp.lost_focus() && buf.trim() != shown { + out = parse_kerning(&buf); + } + 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 = egui::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); + } + } + }); + press.after(&combo.response); + let _ = combo.response.accessible_name(tl!("Kerning")); + }); + out +} + +/// Applies a kerning value: at a collapsed caret to the pair before it, else to the selection +/// (or the whole layer). +pub(super) fn apply_kerning(app: &mut PhotocraftApp, ctx: &egui::Context, v: serde_json::Value) { + match app.ui.text_edit.clone().filter(|e| e.caret == e.anchor) { + Some(ed) if ed.caret > 0 => { + let _ = app.run("type.edit", json!({"layer": ed.layer, "range": [ed.caret - 1, ed.caret], "kerning": v})); + } + Some(_) => {} + None => apply(app, ctx, json!({ "kerning": v })), + } +} + +pub(super) fn icon_label(ui: &mut egui::Ui, icon: &str, tip: &str) { + let t = crate::theme::Tokens::get(ui.ctx()); + let (r, resp) = ui.allocate_exact_size(egui::vec2(crate::props_layout::LABEL_W, 22.0), egui::Sense::hover()); + crate::icons::paint(ui, r, icon, 12.0, t.text_dim); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, ui.is_enabled(), tl!(tip))); + // Photoshop's Character panel icons scrub the field beside them. + crate::widgets::scrub_label(ui, &resp.on_hover_text(tl!(tip))); +} + +/// Labelled numeric field (Photoshop's icon + value pairs). Returns the new value when edited. +pub(super) fn num_field(ui: &mut egui::Ui, label: &str, tip: &str, v: f32, range: std::ops::RangeInclusive, unit: &str, width: f32) -> Option { + let t = crate::theme::Tokens::get(ui.ctx()); + let mut v = v; + let mut out = None; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let (r, resp) = ui.allocate_exact_size(egui::vec2(22.0, 22.0), egui::Sense::hover()); + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, label, crate::theme::semibold(10.0), t.text_dim); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, ui.is_enabled(), tl!(tip))); + crate::widgets::scrub_label(ui, &resp.on_hover_text(tl!(tip))); + let response = crate::widgets::value_field(ui, &mut v, range, unit, width); + response.widget_info(|| { + let mut info = egui::WidgetInfo::drag_value(ui.is_enabled(), f64::from(v)); + info.label = Some(tl!(tip).to_owned()); + info + }); + if response.changed() { + out = Some(v); + } + }); + out +} + +/// Photoshop's paragraph alignment glyphs: four text lines whose widths/offsets show the mode +/// (justify variants run full width, with the last line placed left/centre/right). +pub(super) fn align_glyph(p: &egui::Painter, r: egui::Rect, a: photocraft_doc::text::TextAlign, c: Color32) { + use photocraft_doc::text::TextAlign as A; + let widths = [1.0, 0.62, 1.0, 0.62]; + for (i, w) in widths.iter().enumerate() { + let y = r.top() + i as f32 * r.height() / 3.0; + let full = r.width(); + let (len, x0) = match a { + A::Left => (full * w, r.left()), + A::Center => (full * w, r.center().x - full * w / 2.0), + A::Right => (full * w, r.right() - full * w), + A::JustifyAll => (full, r.left()), + _ if i < 3 => (full, r.left()), + A::JustifyLeft => (full * 0.55, r.left()), + A::JustifyCenter => (full * 0.55, r.center().x - full * 0.275), + _ => (full * 0.55, r.right() - full * 0.55), + }; + p.line_segment([egui::pos2(x0, y), egui::pos2(x0 + len, y)], Stroke::new(1.5, c)); + } +} + +/// Paragraph direction choices for the Paragraph panel and the options bar (TYPE-218-2): the +/// `direction` value `type.setStyle` takes, the tooltip, and the direction it sets. +pub(super) fn direction_items() -> [(&'static str, &'static str, photocraft_doc::text::TextDirection); 3] { + use photocraft_doc::text::TextDirection as D; + [ + ("auto", tl!("Automatic paragraph direction"), D::Auto), + ("ltr", tl!("Left-to-right paragraph direction"), D::Ltr), + ("rtl", tl!("Right-to-left paragraph direction"), D::Rtl), + ] +} + +/// A pilcrow over an arrow pointing the way the paragraph runs; Auto points both ways. +pub(super) fn direction_glyph(p: &egui::Painter, r: egui::Rect, d: photocraft_doc::text::TextDirection, c: Color32) { + use photocraft_doc::text::TextDirection as D; + let g = p.layout_no_wrap("¶".to_string(), egui::FontId::proportional(11.0), c); + p.galley(egui::pos2(r.center().x - g.size().x / 2.0, r.top() - 2.0), g, c); + let (y, s) = (r.bottom() - 1.5, Stroke::new(1.3, c)); + p.line_segment([egui::pos2(r.left(), y), egui::pos2(r.right(), y)], s); + let head = |x: f32, towards: f32| { + for dy in [-3.0, 3.0] { + p.line_segment([egui::pos2(x, y), egui::pos2(x - towards * 3.0, y + dy)], s); + } + }; + if d != D::Rtl { + head(r.right(), 1.0); + } + if d != D::Ltr { + head(r.left(), -1.0); + } +} + +/// The options bar's 24 px square button for one paragraph direction, styled like its icon buttons. +fn direction_button(ui: &mut egui::Ui, d: photocraft_doc::text::TextDirection, selected: bool, tip: &str) -> egui::Response { + let (r, resp) = ui.allocate_exact_size(egui::vec2(24.0, 24.0), egui::Sense::click()); + let tint = crate::icons::button_chrome(ui, r, selected, resp.hovered()); + direction_glyph(ui.painter(), egui::Rect::from_center_size(r.center(), egui::vec2(14.0, 16.0)), d, tint); + let tip = tip.to_string(); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &tip)); + resp.on_hover_text(tip) +} + +/// A toggle button (faux styles, paragraph alignment) of width `w`, painted by `paint`. +pub(super) fn toggle_cell(ui: &mut egui::Ui, w: f32, on: bool, tip: &str, paint: impl FnOnce(&egui::Ui, egui::Rect, Color32)) -> bool { + let t = crate::theme::Tokens::get(ui.ctx()); + let (r, resp) = ui.allocate_exact_size(egui::vec2(w, 24.0), egui::Sense::click()); + let bg = if on { + t.accent_soft + } else if resp.hovered() { + t.hover + } else { + Color32::TRANSPARENT + }; + ui.painter().rect_filled(r, t.radius_sm, bg); + if on { + ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, t.accent_border), egui::StrokeKind::Inside); + } + let enabled = ui.is_enabled(); + paint( + ui, + r, + if !enabled { + t.text_faint + } else if on { + t.text + } else { + t.text_dim + }, + ); + let tip = tip.to_string(); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, enabled, on, &tip)); + resp.on_hover_text(tl!(&tip)).clicked() +} diff --git a/crates/ui-egui/src/type_tool/overlay.rs b/crates/ui-egui/src/type_tool/overlay.rs new file mode 100644 index 0000000000..31a6022df3 --- /dev/null +++ b/crates/ui-egui/src/type_tool/overlay.rs @@ -0,0 +1,214 @@ +use super::editing::edit_home; +use super::ime_edit::{ime_offsets, ime_preedit_is_current}; +use super::layout::layout; +use super::*; + +/// Selection highlight, caret and text frame over the canvas. +pub fn draw_overlay(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { + let Some(ed) = app.ui.text_edit.clone() else { return }; + // Until it commits, an edit in a document no longer active draws nothing over this one. + if edit_home(app, &ed) != app.session.active_index() { + return; + } + if ed.dragging { + app.ui.caret_blink_time = painter.ctx().input(|i| i.time); + } + let id = LayerId(ed.layer); + let Some((l, aff, text)) = layout(app, id) else { return }; + if ed.mask { + draw_mask_overlay(app, painter, xf, id); + } + let t = crate::theme::Tokens::get(painter.ctx()); + // Text space → screen. + let scr_t = |x: f32, y: f32| -> Pos2 { + let p = aff.apply(Point::new(x as f64, y as f64)); + xf.to_screen(p.x as f32, p.y as f32) + }; + let shape = app.session.active().and_then(|s| text_layer(&s.doc, id).map(|t| t.shape.clone())); + // Type on a path: the caret, selection and underline follow the curve the glyphs sit on. + let bend = shape.as_ref().and_then(photocraft_text::warp::Warp::on_path); + // Line space (lines, clusters, carets) → screen: vertical type turns it 90° clockwise. + let scr = |x: f32, y: f32| -> Pos2 { + let (x, y) = l.to_text(x, y); + match &bend { + Some(w) => { + let (x, y) = w.apply(f64::from(x), f64::from(y)); + scr_t(x as f32, y as f32) + } + None => scr_t(x, y), + } + }; + // A line-space run from `x0` to `x1` at height `y`: sampled, so it bends with path type. + let run = |x0: f32, x1: f32, y: f32| -> Vec { + let n = if bend.is_some() { ((x1 - x0) / 4.0).ceil().clamp(1.0, 512.0) as usize } else { 1 }; + (0..=n).map(|i| scr(x0 + (x1 - x0) * i as f32 / n as f32, y)).collect() + }; + // The IME descriptor is emitted once at pass end by `sync_ime`, from this pass's canvas + // mapping and the model as it stands after every panel has run. + let pass_nr = painter.ctx().cumulative_pass_nr_for(painter.ctx().viewport_id()); + app.type_ime.note_view(painter.ctx().viewport_id(), pass_nr, xf); + // Frame: paragraph text shows its box with handles; point text an underline per line. + let mods = crate::workspace_ui::sticky_mods(app, painter.ctx().input(|i| i.modifiers)); + let has_transform = crate::type_transform::draw(app, painter, xf, mods); + let frame = Stroke::new(1.0, t.accent); + match shape { + Some(photocraft_doc::text::TextShape::Box { x, y, width, height }) => { + if !has_transform { + let c = [scr_t(x, y), scr_t(x + width, y), scr_t(x + width, y + height), scr_t(x, y + height)]; + painter.add(egui::Shape::closed_line(c.to_vec(), frame)); + let mids = [c[0].lerp(c[1], 0.5), c[1].lerp(c[2], 0.5), c[2].lerp(c[3], 0.5), c[3].lerp(c[0], 0.5)]; + for p in c.iter().chain(mids.iter()) { + let r = egui::Rect::from_center_size(*p, egui::vec2(7.0, 7.0)); + painter.rect_filled(r, 0.0, Color32::WHITE); + painter.rect_stroke(r, 0.0, frame, egui::StrokeKind::Inside); + } + } + } + // Area type: the outline of the shape it wraps inside. + Some(photocraft_doc::text::TextShape::Area { path }) => { + if !has_transform { + for poly in photocraft_vector::flatten::flatten_path(&path, 0.5) { + let pts: Vec = poly.pts.iter().map(|&(x, y)| scr_t(x as f32, y as f32)).collect(); + if pts.len() >= 2 { + painter.add(egui::Shape::closed_line(pts, frame)); + } + } + } + } + _ => { + for ln in &l.lines { + // Horizontal: just under the baseline; vertical: the column's centre line. + let y = if l.vertical { ln.baseline } else { ln.baseline + ln.descent * 0.25 }; + painter.add(egui::Shape::line(run(ln.x0.min(0.0), ln.x1.max(ln.x0 + 1.0), y), Stroke::new(1.0, t.accent.gamma_multiply(0.8)))); + } + } + } + // Uncommitted IME text is underlined, but only while the stored range still holds exactly + // the composition: an application edit may have shifted it onto committed characters. + if let Some(offsets) = ime_offsets(&text, &ed) + && ime_preedit_is_current(app, &text, &ed, &offsets) + && let Some((a, b)) = offsets.preedit.map(|range| (range.start, range.end)) + { + for (li, ln) in l.lines.iter().enumerate() { + let xs: Vec<(f32, f32)> = + l.clusters.iter().filter(|c| c.line == li && c.range.start >= a && c.range.end <= b).map(|c| (c.x, c.x + c.advance)).collect(); + let (x0, x1) = xs.iter().fold((f32::MAX, f32::MIN), |(lo, hi), (p, q)| (lo.min(*p), hi.max(*q))); + if x0 < x1 { + let y = ln.baseline + ln.descent * 0.5; + painter.add(egui::Shape::line(run(x0, x1, y), Stroke::new(1.5, t.accent))); + } + } + } + // Selection: per line, the clusters inside [a, b). + let (a, b) = (byte_of(&text, ed.caret.min(ed.anchor)), byte_of(&text, ed.caret.max(ed.anchor))); + if a < b { + let fill = Color32::from_rgba_unmultiplied(t.accent.r(), t.accent.g(), t.accent.b(), 110); + for (li, ln) in l.lines.iter().enumerate() { + let xs: Vec<(f32, f32)> = + l.clusters.iter().filter(|c| c.line == li && c.range.start >= a && c.range.end <= b).map(|c| (c.x, c.x + c.advance)).collect(); + let (mut x0, mut x1) = xs.iter().fold((f32::MAX, f32::MIN), |(lo, hi), (p, q)| (lo.min(*p), hi.max(*q))); + // A selected line break shows as a small sliver past the line end. + if b > ln.range.end && a <= ln.range.end { + x1 = x1.max(ln.x1 + (ln.ascent + ln.descent) * 0.25); + x0 = x0.min(ln.x1); + } + let (top, bot) = (ln.baseline - ln.ascent, ln.baseline + ln.descent); + if bend.is_some() { + // On a path each glyph turns on its own, so each gets its own highlight. + // Glyphs past the end of the path are not drawn, so neither is their highlight. + let shown = |p: f32, q: f32| bend.as_ref().is_some_and(|w| w.place_glyph(f64::from(p + q) / 2.0) != photocraft_text::warp::Placement::Hidden); + for (p, q) in xs.into_iter().filter(|&(p, q)| shown(p, q)) { + painter.add(egui::Shape::convex_polygon(vec![scr(p, top), scr(q, top), scr(q, bot), scr(p, bot)], fill, Stroke::NONE)); + } + } else if x0 < x1 { + painter.add(egui::Shape::convex_polygon(vec![scr(x0, top), scr(x1, top), scr(x1, bot), scr(x0, bot)], fill, Stroke::NONE)); + } + } + } else { + // Blinking caret (Photoshop's ~0.53 s rhythm), solid while dragging or immediately after interaction. + let time = painter.ctx().input(|i| i.time); + let elapsed = (time - app.ui.caret_blink_time).max(0.0); + if ed.dragging || (elapsed * 1000.0 / 530.0) as i64 % 2 == 0 { + let (x, top, bot) = l.caret(a); + let (x, top, bot) = if l.lines.is_empty() { (0.0, -(12.0 * l.px_per_pt.max(1.0)), 3.0) } else { (x, top, bot) }; + for stroke in CARET_STROKES { + painter.line_segment([scr(x, top), scr(x, bot)], stroke); + } + } + } +} + +/// The text caret, drawn in order: a white halo, then a solid black line inside it, so it reads on +/// any background (#6085). The black line used to be a 0.75 pt hairline inside a white one, which +/// on a white background left only a faint grey line. +pub(super) const CARET_STROKES: [Stroke; 2] = [Stroke { width: 3.0, color: Color32::WHITE }, Stroke { width: 1.0, color: Color32::BLACK }]; + +/// The Type Mask tools while typing: Quick Mask's colour over the canvas with the glyphs clear, +/// as Photoshop shows the selection-to-be. The glyphs come from the hidden working layer's pixels. +fn draw_mask_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, id: LayerId) { + let Some(st) = app.session.active() else { return }; + let canvas = st.doc.bounds(); + let opts = app.session.quick_mask_options; + let rgb = opts.color.to_rgb(); + let tint = |a: f32| { + let a = (a * opts.opacity).clamp(0.0, 1.0); + let q = |v: f32| (v.clamp(0.0, 1.0) * a * 255.0 + 0.5) as u8; + Color32::from_rgba_premultiplied(q(rgb[0]), q(rgb[1]), q(rgb[2]), (a * 255.0 + 0.5) as u8) + }; + let corners = |r: photocraft_geom::Rect| -> Vec { + let (x0, y0, x1, y1) = (r.x0 as f32, r.y0 as f32, r.x1 as f32, r.y1 as f32); + vec![xf.to_screen(x0, y0), xf.to_screen(x1, y0), xf.to_screen(x1, y1), xf.to_screen(x0, y1)] + }; + let surface = text_layer(&st.doc, id).and_then(|t| t.cache.as_ref()); + let area = surface.map(|s| s.content_bounds().intersect(&canvas)).unwrap_or(photocraft_geom::Rect::EMPTY); + // One unfeathered mesh, so the bands and the text's box meet without seams. + let mut bands = egui::Mesh::default(); + let mut band = |x0: i32, y0: i32, x1: i32, y1: i32| { + let r = photocraft_geom::Rect { x0, y0, x1, y1 }; + if !r.is_empty() { + let base = bands.vertices.len() as u32; + for p in corners(r) { + bands.colored_vertex(p, tint(1.0)); + } + bands.indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]); + } + }; + let Some(surface) = surface.filter(|_| !area.is_empty()) else { + band(canvas.x0, canvas.y0, canvas.x1, canvas.y1); + painter.add(egui::Shape::mesh(bands)); + return; + }; + band(canvas.x0, canvas.y0, canvas.x1, area.y0); + band(canvas.x0, area.y1, canvas.x1, canvas.y1); + band(canvas.x0, area.y0, area.x0, area.y1); + band(area.x1, area.y0, canvas.x1, area.y1); + painter.add(egui::Shape::mesh(bands)); + // The text's box: a texture of the tint where there is no glyph, cached per revision. + let ctx = painter.ctx(); + let key = (st.doc.id.0, st.revision, id.0); + let cache = egui::Id::unique("pc-type-mask-overlay"); + let tex = ctx.data(|d| d.get_temp::<((u64, u64, u64), egui::TextureHandle)>(cache)).filter(|(k, _)| *k == key).map(|(_, t)| t); + let tex = tex.unwrap_or_else(|| { + let max = (ctx.input(|i| i.max_texture_side) as u32).clamp(256, 4096); + let factor = area.width().max(area.height()).div_ceil(max).max(1); + let (w, h) = (area.width().div_ceil(factor) as usize, area.height().div_ceil(factor) as usize); + let mut row = vec![[0.0f32; 4]; area.width() as usize]; + let mut px = Vec::with_capacity(w * h); + for y in (area.y0..area.y1).step_by(factor as usize) { + surface.read_rgba_into(photocraft_geom::Rect { x0: area.x0, y0: y, x1: area.x1, y1: y + 1 }, &mut row); + px.extend(row.iter().step_by(factor as usize).take(w).map(|p| tint(1.0 - p[3]))); + } + px.resize(w * h, tint(1.0)); + let img = egui::ColorImage::new([w, h], px); + let t = ctx.load_texture("type-mask-overlay", img, egui::TextureOptions::LINEAR); + ctx.data_mut(|d| d.insert_temp(cache, (key, t.clone()))); + t + }); + let c = corners(area); + let mut mesh = egui::Mesh::with_texture(tex.id()); + for (p, uv) in c.iter().zip([egui::pos2(0.0, 0.0), egui::pos2(1.0, 0.0), egui::pos2(1.0, 1.0), egui::pos2(0.0, 1.0)]) { + mesh.vertices.push(egui::epaint::Vertex { pos: *p, uv, color: Color32::WHITE }); + } + mesh.indices.extend([0, 1, 2, 0, 2, 3]); + painter.add(egui::Shape::mesh(mesh)); +} diff --git a/crates/ui-egui/src/type_tool/panel.rs b/crates/ui-egui/src/type_tool/panel.rs new file mode 100644 index 0000000000..53e1ed31d1 --- /dev/null +++ b/crates/ui-egui/src/type_tool/panel.rs @@ -0,0 +1,441 @@ +use super::defaults::{apply, apply_defaults, default_styles, formatting_params, open_color_picker, shown_scale, target, type_unit}; +use super::fonts::{axis_sliders, font_picker, fonts_ready, selected_style, style_label, styles}; +use super::options_bar::{ + align_glyph, apply_kerning, direction_glyph, direction_items, icon_label, kerning_at, kerning_field, kerning_label, num_field, styles_at, toggle_cell, +}; +use super::*; + +/// The Character panel's OpenType buttons, in Photoshop's order: (feature tag, command id, +/// tooltip). The tooltips are the Type › OpenType menu labels. +pub(crate) const OPENTYPE_BUTTONS: [(&str, &str, &str); 8] = [ + ("liga", "type.openType.standardLigatures", "Standard Ligatures"), + ("calt", "type.openType.contextualAlternates", "Contextual Alternates"), + ("dlig", "type.openType.discretionaryLigatures", "Discretionary Ligatures"), + ("swsh", "type.openType.swash", "Swash"), + ("salt", "type.openType.stylisticAlternates", "Stylistic Alternates"), + ("titl", "type.openType.titlingAlternates", "Titling Alternates"), + ("ordn", "type.openType.ordinals", "Ordinals"), + ("frac", "type.openType.fractions", "Fractions"), +]; + +/// Photoshop's OpenType button row: each shows pressed while its feature is on at the type +/// target (the selection start, else the layer) and toggles it through the Type › OpenType +/// command, on the same scope as the other Character controls. +fn opentype_row(app: &mut PhotocraftApp, ui: &mut egui::Ui, c: &photocraft_doc::text::CharStyle, full: f32) { + let cw = cell_width(full, OPENTYPE_BUTTONS.len()); + let mut clicked = None; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + for (tag, id, tip) in OPENTYPE_BUTTONS { + let on = photocraft_engine::type_extra_cmds::feature_on(c, tag); + if toggle_cell(ui, cw, on, tip, |ui, r, col| opentype_glyph(ui.painter(), r, tag, col)) { + clicked = Some((id, on)); + } + } + }); + if let Some((id, on)) = clicked { + toggle_opentype(app, id, on); + } +} + +/// Runs an OpenType toggle command on the Character panel's scope: the edited layer's selected +/// characters (or its whole text) while typing, else every selected type layer. The new state +/// is explicit, so it follows the button the user saw rather than the layer's first run. +pub(crate) fn toggle_opentype(app: &mut PhotocraftApp, id: &str, shown_on: bool) { + let Some(mut p) = formatting_params(app) else { + if let Some((tag, _, _)) = OPENTYPE_BUTTONS.iter().find(|(_, command, _)| *command == id) { + let props = match *tag { + "liga" => json!({"ligatures": !shown_on}), + "dlig" => json!({"discretionaryLigatures": !shown_on}), + _ => json!({"features": { (*tag): !shown_on }}), + }; + apply_defaults(app, &props); + } + return; + }; + p["on"] = json!(!shown_on); + let _ = app.run(id, p); +} + +/// Small glyph labels for the OpenType buttons (drawn here, no Adobe artwork): fi, st, ct with +/// a ligature arc, a swash A, aa, T, 1st and ½. +fn opentype_glyph(p: &egui::Painter, r: egui::Rect, tag: &str, col: Color32) { + let font = egui::FontId::proportional(13.0); + let centred = |s: &str, font: egui::FontId| { + let g = p.layout_no_wrap(s.to_string(), font, col); + let pos = r.center() - g.size() / 2.0; + let gr = egui::Rect::from_min_size(pos, g.size()); + p.galley(pos, g, col); + gr + }; + match tag { + "liga" => { + centred("fi", font); + } + "calt" => { + centred("st", font); + } + "dlig" => { + let gr = centred("ct", font); + // The ligature's connecting arc from the c over to the t. + let a = egui::pos2(gr.left() + gr.width() * 0.3, gr.top() + gr.height() * 0.42); + let b = egui::pos2(gr.right() - gr.width() * 0.2, gr.top() + 4.0); + let mid = egui::pos2((a.x + b.x) / 2.0, gr.top() + 1.5); + p.line_segment([a, mid], Stroke::new(1.0, col)); + p.line_segment([mid, b], Stroke::new(1.0, col)); + } + "swsh" => { + let gr = centred("A", crate::theme::semibold(13.0)); + // A swash tail sweeping out under the letter. + let y = gr.bottom() - 3.0; + p.line_segment([egui::pos2(gr.left() - 3.0, y + 1.5), egui::pos2(gr.right() + 2.0, y - 0.5)], Stroke::new(1.0, col)); + } + "salt" => { + centred("aa", font); + } + "titl" => { + centred("T", crate::theme::semibold(13.0)); + } + "ordn" => { + let one = p.layout_no_wrap("1".into(), font, col); + let st = p.layout_no_wrap("st".into(), egui::FontId::proportional(9.0), col); + let left = r.center().x - (one.size().x + st.size().x) / 2.0; + let top = r.center().y - one.size().y / 2.0; + let st_x = left + one.size().x; + p.galley(egui::pos2(left, top), one, col); + p.galley(egui::pos2(st_x, top - 1.0), st, col); + } + _ => { + centred("½", font); + } + } +} + +/// Width of each of `n` equal cells filling `avail` with 2 pt gaps. +fn cell_width(avail: f32, n: usize) -> f32 { + let n = n.max(1) as f32; + ((avail - (n - 1.0) * 2.0) / n).floor().max(20.0) +} + +/// Properties panel sections for a type layer: Character, Paragraph and Type Options (#155). +pub fn type_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + type_sections(app, ui, true, true, false); + type_options(app, ui); +} + +/// Window › Character / Paragraph (#150): the same controls as Properties, in their own dock +/// group. Without a type target they edit the defaults for the next Type-tool layer. +pub fn character_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool) { + type_sections(app, ui, !paragraph, paragraph, true); +} + +/// The Character and/or Paragraph sections, with the shared collapsible headers and fields that +/// fill the panel width (#155). +fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, paragraph: bool, show_defaults: bool) { + use crate::props_layout::{COL_GAP, LABEL_GAP, LABEL_W, field_width, section}; + use crate::theme::ROW_GAP; + let Some((c, para)) = styles_at(app).or_else(|| show_defaults.then(|| default_styles(app))) else { return }; + // Preferences ▸ Units & Rulers ▸ Type, as in the options bar: the model keeps points. + let (u, unit) = type_unit(app); + let t = crate::theme::Tokens::get(ui.ctx()); + // Row helper: `ui.horizontal` with the column gap, then the shared row gap. + let row = |ui: &mut egui::Ui, add: &mut dyn FnMut(&mut egui::Ui)| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = COL_GAP; + add(ui) + }); + ui.add_space(ROW_GAP); + }; + if character && section(ui, "character", tl!("Character")) { + let full = ui.available_width(); + let w = field_width(full, 2, LABEL_W); + let mut fam = c.font_family.clone(); + let mut ready = true; + row(ui, &mut |ui| { + ready = fonts_ready(ui, full); + if ready && font_picker(ui, &mut fam, full, app.session.prefs().type_.font_preview, &app.ui.recent_fonts) { + app.note_recent_font(&fam); + app.ui.tool_options.type_font = fam.clone(); + apply(app, ui.ctx(), json!({"font": fam})); + } + }); + row(ui, &mut |ui| { + if !ready { + return; + } + let mut style = selected_style(&c); + let opts: Vec<(String, String)> = styles(&fam).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(); + if crate::widgets::dropdown(ui, "props-type-style", tl!("Style"), &mut style, &opts_ref, full) { + apply(app, ui.ctx(), json!({"fontStyle": style})); + } + }); + axis_sliders(app, ui, &c); + row(ui, &mut |ui| { + let k = shown_scale(app); + // Hover tips stay English until wired through `tl!` in a multi-locale change + // (`every_tl_literal_is_translated` requires every complete catalog). + if let Some(v) = num_field(ui, "tT", "Font size", c.size_pt * k * u, 0.1 * u..=1296.0 * u, unit, w) { + app.ui.tool_options.type_size = v / u; + apply(app, ui.ctx(), json!({"size": v / u, "metricsAsShown": true})); + } + let lead = c.leading_pt.unwrap_or(c.size_pt * para.auto_leading.max(0.01)) * k; + if let Some(v) = num_field(ui, "A↕", "Leading (set to the font size × auto-leading when Auto)", lead * u, 0.1 * u..=5000.0 * u, unit, w) { + apply(app, ui.ctx(), json!({"leading": v / u, "metricsAsShown": true})); + } + }); + row(ui, &mut |ui| { + let shown = kerning_label(kerning_at(app).unwrap_or((c.kerning, c.kern))); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = LABEL_GAP; + icon_label(ui, "text-cursor", "Kerning: Metrics, Optical or a value in 1/1000 em (Alt+←/→ at the caret)"); + if let Some(v) = kerning_field(ui, &shown, w) { + apply_kerning(app, ui.ctx(), v); + } + }); + if let Some(v) = num_field(ui, "VA", "Tracking (1/1000 em)", c.tracking, -1000.0..=10000.0, "", w) { + apply(app, ui.ctx(), json!({"tracking": v})); + } + }); + row(ui, &mut |ui| { + if let Some(v) = num_field(ui, "↕T", "Vertical scale", c.vertical_scale * 100.0, 0.0..=1000.0, "%", w) { + apply(app, ui.ctx(), json!({"verticalScale": v})); + } + if let Some(v) = num_field(ui, "↔T", "Horizontal scale", c.horizontal_scale * 100.0, 0.0..=1000.0, "%", w) { + apply(app, ui.ctx(), json!({"horizontalScale": v})); + } + }); + row(ui, &mut |ui| { + if let Some(v) = num_field(ui, "Aª", "Baseline shift", c.baseline_shift_pt * u, -1296.0 * u..=1296.0 * u, unit, w) { + apply(app, ui.ctx(), json!({"baselineShift": v / u})); + } + // Colour: label + a swatch filling the rest of the second column. + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = LABEL_GAP; + let g = ui.painter().layout_no_wrap(tl!("Color").into(), egui::FontId::proportional(12.0), t.text_dim); + let lw = g.size().x.max(LABEL_W); + let (lr, _) = ui.allocate_exact_size(egui::vec2(lw, 22.0), egui::Sense::hover()); + ui.painter().galley(egui::pos2(lr.left(), lr.center().y - g.size().y / 2.0), g, t.text_dim); + let rgb = c.color.to_rgb(); + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + let sw = (LABEL_W + LABEL_GAP + w - lw - LABEL_GAP).max(24.0); + let (rect, resp) = ui.allocate_exact_size(egui::vec2(sw, 22.0), egui::Sense::click()); + ui.painter().rect_filled(rect, t.radius_sm, Color32::from_rgb(q(rgb[0]), q(rgb[1]), q(rgb[2]))); + ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); + let resp = resp.on_hover_text(tl!("Text color")); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Text color"))); + if resp.clicked() { + open_color_picker(app, rgb); + } + }); + }); + // Faux styles: T (bold) T (italic) TT Tᴛ T̲ T̶, sharing the row evenly. + let caps = c.caps; + // Tip strings are English keys; `toggle_cell` runs them through `tl!`. + let toggles: [(&str, &str, bool, serde_json::Value); 6] = [ + ("T", "Faux Bold", c.faux_bold, json!({"fauxBold": !c.faux_bold})), + ("T", "Faux Italic", c.faux_italic, json!({"fauxItalic": !c.faux_italic})), + ( + "TT", + "All Caps", + caps == photocraft_doc::text::Caps::AllCaps, + json!({"caps": if caps == photocraft_doc::text::Caps::AllCaps { "normal" } else { "allCaps" }}), + ), + ( + "Tᴛ", + "Small Caps", + caps == photocraft_doc::text::Caps::SmallCaps, + json!({"caps": if caps == photocraft_doc::text::Caps::SmallCaps { "normal" } else { "smallCaps" }}), + ), + ("T", "Underline", c.underline, json!({"underline": !c.underline})), + ("T", "Strikethrough", c.strikethrough, json!({"strikethrough": !c.strikethrough})), + ]; + let cw = cell_width(full, toggles.len()); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + for (i, (glyph, tip, on, props)) in toggles.into_iter().enumerate() { + let clicked = toggle_cell(ui, cw, on, tip, |ui, r, col| { + let font = if i == 0 { crate::theme::semibold(13.0) } else { egui::FontId::proportional(13.0) }; + let g = ui.painter().layout_no_wrap(glyph.to_string(), font, col); + let pos = r.center() - g.size() / 2.0; + let gr = egui::Rect::from_min_size(pos, g.size()); + if i == 1 { + // Faux italic: a slanted T drawn as strokes (no italic face is bundled). + let (top, bot, cx) = (gr.top() + 3.0, gr.bottom() - 3.0, gr.center().x); + let slant = (bot - top) * 0.25; + ui.painter().line_segment([egui::pos2(cx - 4.0 + slant / 2.0, top), egui::pos2(cx + 4.0 + slant / 2.0, top)], Stroke::new(1.3, col)); + ui.painter().line_segment([egui::pos2(cx + slant / 2.0, top), egui::pos2(cx - slant / 2.0, bot)], Stroke::new(1.3, col)); + } else { + ui.painter().galley(pos, g, col); + } + if i == 4 { + ui.painter().line_segment([egui::pos2(gr.left(), gr.bottom() - 2.0), egui::pos2(gr.right(), gr.bottom() - 2.0)], Stroke::new(1.0, col)); + } + if i == 5 { + ui.painter() + .line_segment([egui::pos2(gr.left() - 1.0, gr.center().y), egui::pos2(gr.right() + 1.0, gr.center().y)], Stroke::new(1.0, col)); + } + }); + if clicked { + apply(app, ui.ctx(), props); + } + } + }); + ui.add_space(ROW_GAP); + opentype_row(app, ui, &c, full); + ui.add_space(ROW_GAP); + } + if paragraph && section(ui, "paragraph", tl!("Paragraph")) { + use photocraft_doc::text::TextAlign as A; + let full = ui.available_width(); + let w = field_width(full, 2, LABEL_W); + let items = [ + ("left", tl!("Left align text"), A::Left), + ("center", tl!("Center text"), A::Center), + ("right", tl!("Right align text"), A::Right), + ("justifyLeft", tl!("Justify last left"), A::JustifyLeft), + ("justifyCenter", tl!("Justify last centered"), A::JustifyCenter), + ("justifyRight", tl!("Justify last right"), A::JustifyRight), + ("justifyAll", tl!("Justify all"), A::JustifyAll), + ]; + let cw = cell_width(full, items.len()); + // Justification needs a paragraph box or area type: on point text Photoshop greys the four + // justify buttons (#7713). + // The panel formats the layer being typed in, else every selected type layer. + let point = match formatting_params(app) { + Some(p) => p.get("layers").and_then(serde_json::Value::as_array).map_or_else( + || p.get("layer").and_then(serde_json::Value::as_u64).into_iter().collect::>(), + |ids| ids.iter().filter_map(serde_json::Value::as_u64).collect(), + ), + None => Vec::new(), + } + .into_iter() + .any(|layer| { + let shape = app.session.active().and_then(|s| text_layer(&s.doc, LayerId(layer)).map(|t| t.shape.clone())); + !matches!(shape, Some(photocraft_doc::text::TextShape::Box { .. } | photocraft_doc::text::TextShape::Area { .. })) + }); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + for (key, tip, a) in items { + let justify = !matches!(a, A::Left | A::Center | A::Right); + let clicked = ui + .add_enabled_ui(!(point && justify), |ui| { + toggle_cell(ui, cw, para.align == a, tip, |ui, r, col| { + // The glyph keeps its size; the cell grows around it. + let g = egui::Rect::from_center_size(r.center(), egui::vec2(12.0, 10.0)); + let col = if !ui.is_enabled() || para.align == a { col } else { t.icon }; + align_glyph(ui.painter(), g, a, col); + }) + }) + .inner; + if clicked { + apply(app, ui.ctx(), json!({"align": key})); + } + } + }); + ui.add_space(ROW_GAP); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + for (key, tip, d) in direction_items() { + let clicked = toggle_cell(ui, cw, para.direction == d, tip, |ui, r, col| { + let g = egui::Rect::from_center_size(r.center(), egui::vec2(14.0, 16.0)); + direction_glyph(ui.painter(), g, d, col); + }); + if clicked { + apply(app, ui.ctx(), json!({"direction": key})); + } + } + }); + ui.add_space(ROW_GAP); + row(ui, &mut |ui| { + if let Some(v) = num_field(ui, "→|", "Indent left margin", para.start_indent_pt * u, -1296.0 * u..=1296.0 * u, unit, w) { + apply(app, ui.ctx(), json!({"startIndent": v / u})); + } + if let Some(v) = num_field(ui, "|←", "Indent right margin", para.end_indent_pt * u, -1296.0 * u..=1296.0 * u, unit, w) { + apply(app, ui.ctx(), json!({"endIndent": v / u})); + } + }); + row(ui, &mut |ui| { + if let Some(v) = num_field(ui, "¶→", "Indent first line", para.first_line_indent_pt * u, -1296.0 * u..=1296.0 * u, unit, w) { + apply(app, ui.ctx(), json!({"firstLineIndent": v / u})); + } + }); + row(ui, &mut |ui| { + if let Some(v) = num_field(ui, "↑¶", "Add space before paragraph", para.space_before_pt * u, 0.0 * u..=1296.0 * u, unit, w) { + apply(app, ui.ctx(), json!({"spaceBefore": v / u})); + } + if let Some(v) = num_field(ui, "¶↓", "Add space after paragraph", para.space_after_pt * u, 0.0 * u..=1296.0 * u, unit, w) { + apply(app, ui.ctx(), json!({"spaceAfter": v / u})); + } + }); + // Hyphenate is stored (⌥⇧⌘H / PSD AutoHyphenate) but layout never breaks words (#6710). + ui.add_space(ROW_GAP); + } +} + +/// Type Options: anti-aliasing and orientation of the whole layer (the Type menu's commands). +fn type_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + use crate::props_layout::{COL_GAP, LABEL_GAP}; + let Some((layer, _)) = target(app) else { return }; + let Some((aa, vertical)) = app + .session + .active() + .and_then(|st| text_layer(&st.doc, LayerId(layer))) + .map(|t| (photocraft_engine::type_extra_cmds::aa_name(t.antialias).to_string(), t.orientation == photocraft_doc::text::Orientation::Vertical)) + else { + return; + }; + if !crate::props_layout::section(ui, "typeOptions", "Type Options") { + return; + } + let full = ui.available_width(); + let mut run: Option = None; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = COL_GAP; + // Anti-aliasing dropdown (aₐ glyph label), then the two orientation toggles. + let orient_w = 2.0 * 28.0 + 2.0; + let dd_w = (full - crate::props_layout::LABEL_W - LABEL_GAP - COL_GAP - orient_w).max(60.0); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = LABEL_GAP; + let t = crate::theme::Tokens::get(ui.ctx()); + let (r, resp) = ui.allocate_exact_size(egui::vec2(crate::props_layout::LABEL_W, 22.0), egui::Sense::hover()); + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, "aa", crate::theme::semibold(11.0), t.text_dim); + resp.on_hover_text(tl!("Anti-aliasing method")); + let mut cur = aa.clone(); + let opts: Vec<(String, &str)> = ["none", "sharp", "crisp", "strong", "smooth", "windowsLcd", "windows"] + .into_iter() + .filter_map(|k| photocraft_engine::commands::find(&format!("type.antiAlias.{k}")).map(|c| (k.to_string(), c.label))) + .collect(); + if crate::widgets::dropdown(ui, "props-type-aa", tl!("Anti-aliasing method"), &mut cur, &opts, dd_w) { + run = Some(format!("type.antiAlias.{cur}")); + } + }); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + for (key, tip, on) in [("horizontal", "Horizontal type", !vertical), ("vertical", "Vertical type", vertical)] { + let clicked = toggle_cell(ui, 28.0, on, tip, |ui, r, col| { + let g = egui::Rect::from_center_size(r.center(), egui::vec2(12.0, 12.0)); + let s = Stroke::new(1.3, col); + if key == "horizontal" { + ui.painter().line_segment([g.left_top(), g.right_top()], s); + ui.painter().line_segment([g.center_top(), g.center_bottom()], s); + } else { + ui.painter().line_segment([g.left_top(), g.left_bottom()], s); + ui.painter().line_segment([g.left_center(), g.right_center()], s); + } + }); + if clicked && !on { + run = Some(format!("type.orientation.{key}")); + } + } + }); + }); + ui.add_space(crate::theme::ROW_GAP); + if let Some(id) = run + && let Some(params) = formatting_params(app) + && let Err(e) = app.run(&id, params) + { + app.ui.status = e; + app.ui.status_error = true; + } +} diff --git a/crates/ui-egui/src/type_tool/pointer.rs b/crates/ui-egui/src/type_tool/pointer.rs new file mode 100644 index 0000000000..2249907954 --- /dev/null +++ b/crates/ui-egui/src/type_tool/pointer.rs @@ -0,0 +1,447 @@ +use super::defaults::default_style_params; +use super::editing::{begin_edit, commit_with}; +use super::layout::{hit_layer, hit_offset, layout, to_text}; +use super::*; + +/// Smallest paragraph box a handle drag leaves, in text-space px. +pub(super) const MIN_BOX: f32 = 4.0; + +/// Which box edges handle `i` moves: (left, right, top, bottom). The order matches the overlay. +pub(super) fn handle_sides(i: u8) -> (bool, bool, bool, bool) { + match i { + 0 => (true, false, true, false), + 1 => (false, true, true, false), + 2 => (false, true, false, true), + 3 => (true, false, false, true), + 4 => (false, false, true, false), + 5 => (false, true, false, false), + 6 => (false, false, false, true), + _ => (true, false, false, false), + } +} + +pub(crate) fn box_shape(app: &PhotocraftApp, id: LayerId) -> Option<(f32, f32, f32, f32)> { + match app.session.active().and_then(|s| text_layer(&s.doc, id).map(|t| t.shape.clone()))? { + photocraft_doc::text::TextShape::Box { x, y, width, height } => Some((x, y, width, height)), + _ => None, + } +} + +/// The paragraph-box handle under the document point, if the layer is paragraph text. +pub(crate) fn box_handle_at(app: &mut PhotocraftApp, id: LayerId, x: f64, y: f64) -> Option { + let (bx, by, w, h) = box_shape(app, id)?; + let (_, aff, _) = layout(app, id)?; + let (r, b) = (bx + w, by + h); + let (mx, my) = (bx + w / 2.0, by + h / 2.0); + let spots = [(bx, by), (r, by), (r, b), (bx, b), (mx, by), (r, my), (mx, b), (bx, my)]; + let tol = f64::from(6.0 / app.point_zoom().max(0.01)); + spots + .iter() + .position(|&(sx, sy)| { + let p = aff.apply(Point::new(f64::from(sx), f64::from(sy))); + (p.x - x).abs() <= tol && (p.y - y).abs() <= tol + }) + .map(|i| i as u8) +} + +/// Drag the handle of `r` (the box and transform snapshotted at the press) to the document +/// point: the dragged edges follow it, the others stay put. With ⌥ the opposite edges mirror +/// the drag about the centre the box started with, so the block grows symmetrically instead of +/// from one side — pressing or releasing ⌥ mid-drag switches that on and off as if it had been +/// held from the start. +fn resize_box(app: &mut PhotocraftApp, ed: &TextEdit, r: BoxResize, x: f64, y: f64, alt: bool) { + let (px, py) = to_text(&r.aff, x, y); + let (l, rw, t, b) = handle_sides(r.handle); + let (bx, by, w, h) = (r.shape[0], r.shape[1], r.shape[2], r.shape[3]); + let (mut x0, mut y0, mut x1, mut y1) = (bx, by, bx + w, by + h); + // The centre the ⌥ mirror turns about: the box as it stood at the press (every move + // recomputes from that snapshot, so the centre holds for the whole drag). + let (cx, cy) = (bx + w / 2.0, by + h / 2.0); + if l { + x0 = px.min(x1 - MIN_BOX); + } + if rw { + x1 = px.max(x0 + MIN_BOX); + } + if t { + y0 = py.min(y1 - MIN_BOX); + } + if b { + y1 = py.max(y0 + MIN_BOX); + } + if alt { + // The mirror keeps the centre fixed: the dragged edge clamps at MIN_BOX/2 from it, and + // the opposite edge follows, so the block never inverts below the minimum. + if l { + x0 = px.min(cx - MIN_BOX / 2.0); + x1 = 2.0 * cx - x0; + } + if rw { + x1 = px.max(cx + MIN_BOX / 2.0); + x0 = 2.0 * cx - x1; + } + if t { + y0 = py.min(cy - MIN_BOX / 2.0); + y1 = 2.0 * cy - y0; + } + if b { + y1 = py.max(cy + MIN_BOX / 2.0); + y0 = 2.0 * cy - y1; + } + } + // type.edit places the box's top-left at the given document point. + let o = r.aff.apply(Point::new(f64::from(x0), f64::from(y0))); + let _ = app.run("type.edit", json!({"layer": ed.layer, "box": [o.x, o.y, x1 - x0, y1 - y0], "coalesce": ed.session})); +} + +/// True when document point (`x`, `y`) lies inside the paragraph box of type layer `id` (false +/// for point text). +pub(crate) fn inside_box(app: &mut PhotocraftApp, id: LayerId, x: f64, y: f64) -> bool { + let Some((bx, by, w, h)) = box_shape(app, id) else { return false }; + let Some((_, aff, _)) = layout(app, id) else { return false }; + let (tx, ty) = to_text(&aff, x, y); + tx >= bx && tx <= bx + w && ty >= by && ty <= by + h +} + +/// Pointer down with the Type tool. Returns true when the press was consumed (no box drag). +pub fn pointer_down(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) -> bool { + if let Some(ed) = app.ui.text_edit.clone() { + let id = LayerId(ed.layer); + if let Some(i) = box_handle_at(app, id, x, y) { + // Snapshot the box and transform now: every move recomputes from them, so ⌥ held + // or released mid-drag mirrors about the centre the drag started with. + let snap = box_shape(app, id).zip(layout(app, id)).map(|((bx, by, w, h), (_, aff, _))| BoxResize { handle: i, shape: [bx, by, w, h], aff }); + if let (Some(snap), Some(e)) = (snap, app.ui.text_edit.as_mut()) { + e.resize = Some(snap); + } + return true; + } + // Photoshop: anywhere inside the paragraph box places the caret, even off the glyphs + // (left of a line's start, below the last line); only a click outside it commits. + if hit_layer(app, x, y) == Some(id) || inside_box(app, id, x, y) { + let off = hit_offset(app, id, x, y); + if let Some(e) = app.ui.text_edit.as_mut() { + e.caret = off; + if !mods.shift { + e.anchor = off; + } + e.dragging = true; + } + return true; + } + // ⇧/⌥ on that click combine a Type Mask with the selection. + commit_with(app, mods); + return true; // Photoshop: a click outside commits without starting new text + } + // The Type Mask tools always start new text: existing type layers are just pixels to them; + // so does a ⇧-click with the Type tool, as in Photoshop, to start new text over old. + if app.ui.tool.is_type_mask() || mods.shift { + return false; + } + if let Some(id) = hit_layer(app, x, y) { + let _ = app.session.select_layer(id); + let key = session_key(app); + if begin_edit(app, id, &key).is_err() { + return true; + } + let off = hit_offset(app, id, x, y); + app.ui.text_edit = Some(TextEdit { + layer: id.0, + document: active_doc_id(app), + caret: off, + anchor: off, + session: key, + created: false, + mask: false, + dragging: true, + resize: None, + preedit: None, + }); + app.ui.text_edit_return_tool = None; + return true; + } + false +} + +pub fn pointer_move(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { + let Some(ed) = app.ui.text_edit.clone() else { return }; + if let Some(r) = ed.resize { + resize_box(app, &ed, r, x, y, mods.alt); + return; + } + if ed.dragging { + let off = hit_offset(app, LayerId(ed.layer), x, y); + if let Some(e) = app.ui.text_edit.as_mut() { + e.caret = off; + } + } +} + +/// What a Type tool click on a path does, like Photoshop: inside a closed path, area type; +/// on a path's outline, type on the path from that point. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum PathClick { + Area { shape: Option }, + OnPath { shape: Option, subpath: usize, start: f64 }, +} + +/// Arc length (px) along `sub` from its first anchor to segment `seg` at curve parameter `t`. +fn arc_length_to(sub: &photocraft_doc::Subpath, seg: usize, t: f64) -> f64 { + const PIECES: usize = 32; + let eval = photocraft_vector::edit::eval; + let length = |s: &[Point; 4], upto: f64| { + (1..=PIECES) + .fold((0.0, eval(s, 0.0)), |(len, prev), j| { + let q = eval(s, upto * j as f64 / PIECES as f64); + (len + (q.x - prev.x).hypot(q.y - prev.y), q) + }) + .0 + }; + let segs = sub.segments(); + let whole: f64 = segs.iter().take(seg).map(|s| length(s, 1.0)).sum(); + whole + segs.get(seg).map_or(0.0, |s| length(s, t.clamp(0.0, 1.0))) +} + +/// The path a Type tool click at document `(x, y)` would use: on the outline (within 6 screen px) +/// of the active shape layer's path, else of the work path, type on that path; inside a closed +/// one, area type. The work path's inside counts only while the canvas draws it (selected in the +/// Paths panel, #6551): a hidden Work Path left after Load as Selection must not turn a plain +/// click into area type. None while View › Show › Target Path (or Extras) hides paths. +pub(crate) fn path_target(app: &PhotocraftApp, x: f64, y: f64) -> Option { + use photocraft_vector::edit::{Hit, hit}; + if !app.ui.view.shows(app.ui.view.show.target_path) { + return None; + } + let shape_path = crate::vector_ui::active_shape_path(app); + let work = app.session.active().and_then(|s| s.doc.work_path.clone()); + let work_shown = app.ui.selected_path.as_deref() == Some("work"); + // The canvas hover runs this every frame and `hit` samples every segment, so a path with more + // anchors than this is not a click target (the click and the pointer agree: plain point + // text). 4096 anchors is far beyond hand-drawn paths and shapes yet keeps a frame cheap, and + // it is the most `type.fillPath` accepts, so every area click target can be filled. + const MAX_TARGET_KNOTS: usize = photocraft_text::area::MAX_AREA_KNOTS; + let small = |path: &photocraft_doc::vector::Path| path.subpaths.iter().map(|s| s.knots.len()).fold(0usize, usize::saturating_add) <= MAX_TARGET_KNOTS; + let tol = 6.0 / app.point_zoom().max(0.01) as f64; + // Only the horizontal Type tool starts type on a path: vertical type on a path is not laid + // out yet. + let vertical = app.ui.tool.is_vertical_type(); + let outline = |path: &photocraft_doc::vector::Path, shape: Option| { + let on_path = |sp: usize, k: usize, t: f64| { + // Type on a path needs a segment to run along (`type.attachToPath` rejects one anchor). + let sub = path.subpaths.get(sp).filter(|s| !vertical && s.knots.len() >= 2)?; + Some(PathClick::OnPath { shape, subpath: sp, start: arc_length_to(sub, k, t) }) + }; + match hit(path, Point::new(x, y), tol, &[]) { + Some(Hit::Segment([sp, k], t)) => on_path(sp, k, t), + Some(Hit::Anchor([sp, k])) => on_path(sp, k, 0.0), + _ => None, + } + }; + let inside = |path: &photocraft_doc::vector::Path| photocraft_text::area::AreaShape::new(path, false).is_some_and(|a| a.contains(x as f32, y as f32)); + if let Some((id, p)) = shape_path.as_ref().filter(|(_, p)| small(p)) { + if let Some(c) = outline(p, Some(*id)) { + return Some(c); + } + if inside(p) { + return Some(PathClick::Area { shape: Some(*id) }); + } + } + let w = work.as_ref().filter(|w| small(w))?; + if let Some(c) = outline(w, None) { + return Some(c); + } + (work_shown && inside(w)).then_some(PathClick::Area { shape: None }) +} + +/// What the Type tool's pointer over document `(x, y)` shows (#218): the path click a press there +/// would make, unless the press edits the type layer under it instead (`pointer_down`: an +/// unshifted press on shown type), where Photoshop keeps the plain I-beam. The type hit is only +/// tested over a path, so a hover elsewhere lays out nothing. Nothing while a type edit is open +/// (a click then commits rather than starting new type). While the button is held it is what the +/// release makes (`pointer_up`): nothing once the drag is a text box, else the path click at the +/// press. +pub(crate) fn hover_path_target(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) -> Option { + if app.ui.text_edit.is_some() { + return None; + } + if let Some(start) = app.drag.as_ref().map(|d| d.start) { + // The press already passed over editing type (`pointer_down`), so no type hit test. + return if makes_box(app, start, [x, y]) { None } else { path_target(app, start[0], start[1]) }; + } + let target = path_target(app, x, y)?; + (shift || hit_layer(app, x, y).is_none()).then_some(target) +} + +/// Whether a press at `start` released at `end` drags out a paragraph box rather than clicking +/// (at least 4 screen pixels both ways). +fn makes_box(app: &PhotocraftApp, start: [f64; 2], end: [f64; 2]) -> bool { + let (w, h) = ((end[0] - start[0]).abs(), (end[1] - start[1]).abs()); + let min = 4.0 / app.point_zoom().max(0.01) as f64; + w >= min && h >= min +} + +/// Pointer up. `rect` is the dragged box (document px) when no edit session consumed the press. +pub fn pointer_up(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) { + if let Some(e) = app.ui.text_edit.as_mut() { + e.dragging = false; + e.resize = None; + app.ui.caret_blink_time = app.last_frame_time; + return; + } + let (w, h) = ((end[0] - start[0]).abs(), (end[1] - start[1]).abs()); + let min = 4.0 / app.point_zoom().max(0.01) as f64; + let o = app.ui.tool_options.clone(); + let mask = app.ui.tool.is_type_mask(); + // A click (not a drag) with the Type tool on a path: area type inside a closed path, type + // on the path on its outline. The Type Mask tools ignore paths. + let target = if !mask && !makes_box(app, start, end) { path_target(app, start[0], start[1]) } else { None }; + // Preferences ▸ Type: "Fill new type layers with placeholder text" (on by default). The Type + // Mask tools start empty, as Photoshop's do. + let text = if !mask && app.session.prefs().type_.fill_new_type_layers_with_placeholder { PLACEHOLDER } else { "" }; + let mut p = default_style_params(app); + p["text"] = json!(text); + p["orientation"] = json!(if app.ui.tool.is_vertical_type() { "vertical" } else { "horizontal" }); + if w >= min && h >= min { + p["box"] = json!([start[0].min(end[0]).round(), start[1].min(end[1]).round(), w.round(), h.round()]); + } else { + p["x"] = json!(start[0].round()); + p["y"] = json!(start[1].round()); + } + let key = session_key(app); + p["coalesce"] = json!(key); + if let Ok(v) = app.run("type.create", p) + && let Some(id) = v.get("layer").and_then(serde_json::Value::as_u64) + { + // A failed follow-up leaves point text; say why instead of passing over it. + let follow_up = match &target { + Some(PathClick::Area { shape }) => app.run("type.fillPath", json!({"layer": id, "shape": shape, "coalesce": key})), + Some(PathClick::OnPath { shape, subpath, start }) => { + app.run("type.attachToPath", json!({"layer": id, "shape": shape, "subpath": subpath, "start": start, "coalesce": key})) + } + None => Ok(serde_json::Value::Null), + }; + if let Err(e) = follow_up { + app.ui.status = e; + app.ui.status_error = true; + } + if o.type_aa != "sharp" { + let _ = app.run("type.edit", json!({"layer": id, "antialias": o.type_aa, "coalesce": key})); + } + // A Type Mask's text is a hidden working layer: the canvas shows the mask overlay + // instead, and committing turns it into the selection. + if mask { + let _ = app.run("layer.setProps", json!({"layer": id, "visible": false, "coalesce": key})); + } + // Like Photoshop: the placeholder is selected, so typing replaces it. + let n = text.chars().count(); + app.ui.caret_blink_time = app.last_frame_time; + app.ui.text_edit = Some(TextEdit { + layer: id, + document: active_doc_id(app), + caret: n, + anchor: 0, + session: key, + created: true, + mask, + dragging: false, + resize: None, + preedit: None, + }); + app.ui.text_edit_return_tool = None; + } +} + +/// Character index of the previous / next word boundary (shared with `type.navigate`). +pub(super) fn word_boundary(text: &str, from: usize, forward: bool) -> usize { + photocraft_text::word_boundary(text, from, forward) +} + +/// Most clicks in a run that select more: 2 a word, 3 a line, 4 a paragraph, 5 all text. The +/// next quick click starts over with a caret. +const MAX_CLICKS: u32 = 5; + +/// Count of this click in a run of clicks at one spot. `egui_count` is egui's own count for the +/// click (1 single, 2 double, 3 triple; it never goes past 3), which already applies the +/// double-click delay and distance; `prev` is our count for the previous click (0: none). A slow +/// or distant click (egui says 1) starts a new run; after five clicks the run starts over. +pub(crate) fn next_click_count(prev: u32, egui_count: u32) -> u32 { + match (egui_count, prev) { + (0 | 1, _) => 1, + (n, 0) => n.min(MAX_CLICKS), + (_, p) => p % MAX_CLICKS + 1, + } +} + +/// The selection (anchor, caret) a run of `count` clicks makes at character `caret`: 1 a caret, +/// 2 the word under it, 3 its visual line as laid out (a column in vertical type), 4 its +/// paragraph up to the hard return, 5 all text. `line` is the laid-out line the click hit; it +/// decides at a soft wrap, where one caret offset ends a line and starts the next. Without a +/// layout a line is its paragraph. Offsets past the text are clamped, so an empty layer or a +/// stale caret never panics. +pub(crate) fn click_selection(layout: Option<&TextLayout>, text: &str, caret: usize, line: Option, count: u32) -> (usize, usize) { + let n = text.chars().count(); + let c = caret.min(n); + match count { + 2 => { + let chars: Vec = text.chars().collect(); + let word = |i: usize| chars.get(i).is_some_and(|ch| ch.is_alphanumeric()); + let (mut a, mut b) = (c, c); + while a > 0 && word(a - 1) { + a -= 1; + } + while word(b) { + b += 1; + } + (a, b) + } + 3 => { + let Some(l) = layout else { return paragraph_of(text, c) }; + let ln = line.and_then(|i| l.lines.get(i)).or_else(|| l.lines.get(photocraft_text::line_index(l, byte_of(text, c)))); + ln.map_or((c, c), |ln| (photocraft_text::char_index(text, ln.range.start), photocraft_text::char_index(text, ln.range.end))) + } + 4 => paragraph_of(text, c), + 5 => (0, n), + _ => (c, c), + } +} + +/// Characters of the paragraph holding character `c`, without its hard return. +fn paragraph_of(text: &str, c: usize) -> (usize, usize) { + let b = byte_of(text, c); + let paras = photocraft_text::layout::split_paragraphs(text); + let Some(r) = paras.iter().find(|r| b >= r.start && b < r.end).or_else(|| paras.last()) else { return (c, c) }; + let body = text.get(r.clone()).unwrap_or("").trim_end_matches(['\r', '\n']); + let start = photocraft_text::char_index(text, r.start); + (start, start + body.chars().count()) +} + +/// A click while editing type at document point (`x`, `y`), after it placed the caret there. +/// `egui_count` is egui's count for the click (see [`next_click_count`]). Like Photoshop, two +/// clicks select a word, three the line, four the paragraph and five all text. +pub fn multi_click(app: &mut PhotocraftApp, egui_count: u32, x: f64, y: f64) { + let Some(ed) = app.ui.text_edit.clone() else { + app.type_clicks = None; + return; + }; + let prev = app.type_clicks.filter(|(layer, _)| *layer == ed.layer).map_or(0, |(_, n)| n); + let count = next_click_count(prev, egui_count); + app.type_clicks = Some((ed.layer, count)); + if count < 2 { + return; + } + let id = LayerId(ed.layer); + let Some(text) = current_text(app, id) else { return }; + let laid = layout(app, id); + let (caret, line) = match &laid { + Some((l, aff, t)) if *t == text && x.is_finite() && y.is_finite() => { + let (tx, ty) = to_text(aff, x, y); + let (ci, line) = photocraft_text::hit_char(l, t, tx, ty); + (ci, Some(line)) + } + _ => (ed.caret, None), + }; + let (a, b) = click_selection(laid.as_ref().map(|(l, _, _)| l.as_ref()), &text, caret, line, count); + if let Some(e) = app.ui.text_edit.as_mut() { + (e.anchor, e.caret) = (a, b); + } +} From 91d6c24807622a60c93367edd46d745e7a24ccdd Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:09:44 +0000 Subject: [PATCH 217/259] refactor(ui-egui): split control.rs into control/ --- crates/ui-egui/src/control.rs | 1367 +----------------------- crates/ui-egui/src/control/dispatch.rs | 1005 +++++++++++++++++ crates/ui-egui/src/control/inspect.rs | 136 +++ crates/ui-egui/src/control/params.rs | 234 ++++ 4 files changed, 1386 insertions(+), 1356 deletions(-) create mode 100644 crates/ui-egui/src/control/dispatch.rs create mode 100644 crates/ui-egui/src/control/inspect.rs create mode 100644 crates/ui-egui/src/control/params.rs diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index e5efe9af0a..aed074b11e 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -43,6 +43,17 @@ use crate::PhotocraftApp; use crate::canvas::{ToolEvent, tool_event}; use crate::state::{DialogKind, Tool}; +mod dispatch; +mod inspect; +mod params; + +use dispatch::dispatch; +pub use inspect::{inspect, save_screenshot, save_screenshot_rgba}; +#[cfg(test)] +use params::screen_point; +pub use params::{MAX_CLICKS, UI_SET_FIELDS}; +use params::{err, ok}; + pub type ControlResponse = Value; /// The control server's per-request reply deadline. @@ -129,198 +140,6 @@ pub enum Outcome { AfterJob(photocraft_engine::jobs::JobId), } -/// The fields `ui.set` reads. Anything else is rejected before a field is applied, and every -/// field's value is validated before the first one is applied, so a typo, an unknown field, a -/// bad value or a bad nested key can't reply with success while nothing — or only half of it — -/// changed (#412). -pub const UI_SET_FIELDS: [&str; 43] = [ - "updatesOpen", - "tool", - "strokeTrace", - "panels", - "dock", - "dockTabs", - "dockWidth", - "colorPanel", - "maskTarget", - "vectorMaskTarget", - "filterMaskTarget", - "selectionMode", - "zoom", - "center", - "rotation", - "fit", - "theme", - "brushSection", - "brushTab", - "brushesView", - "brushPicker", - "brushPickerName", - "brushPickerStroke", - "brushPickerTip", - "brushPickerScale", - "brushSize", - "gradientBlendMode", - "gradientClassic", - "eyedropperSampleSize", - "eyedropperSample", - "eyedropperRing", - "cropOverlay", - "cropOverlayShow", - "cropOverlayOrientation", - "cropShield", - "cropFill", - "shapeStroke", - "camTransformOnDrop", - "tileGrid", - "layerFilter", - "histogramPanel", - "histogramRange", - "histogramRefresh", -]; - -/// Most clicks one `ui.click` may queue (#982). Each click is a press and a release that the app -/// feeds in its own frame before replying, so `count` sizes both the input queue and the wait; -/// the same ceiling as the steps of one batch request. -pub const MAX_CLICKS: u64 = 256; - -fn ok(v: Value) -> Outcome { - Outcome::Done(json!({"ok": true, "result": v})) -} -fn err(e: impl std::fmt::Display) -> Outcome { - Outcome::Done(json!({"ok": false, "error": e.to_string()})) -} - -/// A `ui.set` boolean field: `Ok(None)` when absent, an error when present with another type. -fn bool_field(p: &Value, key: &str) -> std::result::Result, String> { - match p.get(key) { - None => Ok(None), - Some(v) => v.as_bool().map(Some).ok_or_else(|| format!("{key} must be a boolean")), - } -} - -/// A `ui.set` integer field: `Ok(None)` when absent; whole-number floats (`12.0`, as UIs send -/// them) are accepted, anything else is an error. -fn uint_field(p: &Value, key: &str) -> std::result::Result, String> { - match p.get(key) { - None => Ok(None), - Some(v) if v.is_u64() => Ok(v.as_u64()), - Some(v) => v.as_f64().filter(|f| f.fract() == 0.0 && *f >= 0.0).map(|f| Some(f as u64)).ok_or_else(|| format!("{key} must be a non-negative integer")), - } -} - -/// A `ui.set` numeric field: `Ok(None)` when absent, finite numbers only. -fn num_field(p: &Value, key: &str) -> std::result::Result, String> { - match p.get(key) { - None => Ok(None), - Some(v) => v.as_f64().filter(|f| f.is_finite()).map(Some).ok_or_else(|| format!("{key} must be a finite number")), - } -} - -/// A finite number that stays finite as `f32` (1e39 would turn into inf and silently reset -/// rotation to 0° or zoom to 100%). -fn f32_range(n: &f64) -> bool { - n.is_finite() && n.abs() <= f64::from(f32::MAX) -} - -/// A `ui.set` numeric field the view stores as `f32`: `Ok(None)` when absent, else within `f32` range. -fn f32_field(p: &Value, key: &str) -> std::result::Result, String> { - match p.get(key) { - None => Ok(None), - Some(v) => v.as_f64().filter(f32_range).map(Some).ok_or_else(|| format!("{key} must be a finite number within f32 range")), - } -} - -/// A `ui.set` object field merged into the current state (e.g. `panels`): the patch's keys are -/// merged into the serialized current value and parsed back, so a non-object value or an -/// unknown nested key is an error — a nested typo must not reply ok while changing nothing. -fn merged_object(current: &T, patch: Option<&Value>, field: &str) -> std::result::Result, String> { - let Some(patch) = patch else { return Ok(None) }; - let Some(patch) = patch.as_object() else { return Err(format!("{field} must be an object")) }; - let mut cur = serde_json::to_value(current).map_err(|e| e.to_string())?; - let known: std::collections::HashSet = cur.as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default(); - for (k, v) in patch { - if !known.contains(k) { - return Err(format!("unknown {field} field `{k}`")); - } - if let Some(c) = cur.as_object_mut() { - c.insert(k.clone(), v.clone()); - } - } - serde_json::from_value(cur).map(Some).map_err(|e| format!("{field}: {e}")) -} - -/// A `ui.set` object field applied by whole-value replacement (e.g. `dock`): -/// unknown nested keys are rejected like [`merged_object`] does, but the value replaces the -/// state instead of merging into it. -fn whole_object(current: &T, v: Option<&Value>, field: &str) -> std::result::Result, String> { - let Some(v) = v else { return Ok(None) }; - let Some(patch) = v.as_object() else { return Err(format!("{field} must be an object")) }; - let cur = serde_json::to_value(current).map_err(|e| e.to_string())?; - let known: std::collections::HashSet<&str> = cur.as_object().map(|o| o.keys().map(String::as_str).collect()).unwrap_or_default(); - for k in patch.keys() { - if !known.contains(k.as_str()) { - return Err(format!("unknown {field} field `{k}`")); - } - } - serde_json::from_value(v.clone()).map(Some).map_err(|e| format!("{field}: {e}")) -} - -/// The buttons `ui.pointer` and `ui.click` accept (`right` and `secondary` are the same one). -const BUTTONS: [&str; 4] = ["left", "right", "secondary", "middle"]; -/// The modifier flags `ui.key` reads, top-level or under `modifiers`; `ui.pointer` adds `space`. -const KEY_MODIFIERS: [&str; 4] = ["shift", "alt", "command", "ctrl"]; -const POINTER_MODIFIERS: [&str; 5] = ["shift", "alt", "command", "ctrl", "space"]; - -/// A synthetic input method's params (or one nested object, named `what`): an object whose keys -/// are all in `fields`, returned with its null fields dropped so they mean "omitted". A typo must -/// not reply ok after acting on a default (#2449), as `ui.set` already promises (#412). -fn input_object(v: &Value, what: Option<&str>, fields: &[&str]) -> std::result::Result { - let object = match (v, what) { - (Value::Null, None) => return Ok(json!({})), - (Value::Object(o), _) => o, - (_, what) => return Err(format!("{} must be an object", what.unwrap_or("params"))), - }; - if let Some(key) = object.keys().find(|k| !fields.contains(&k.as_str())) { - let field = what.map(|w| format!("{w} field")).unwrap_or_else(|| "field".into()); - return Err(format!("unknown {field} `{key}` (fields: {})", fields.join(", "))); - } - Ok(Value::Object(object.iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k.clone(), v.clone())).collect())) -} - -/// An optional finite number named `name` in errors, within `range` when given. -fn input_number(v: &Value, key: &str, name: &str, range: Option<(f64, f64)>) -> std::result::Result, String> { - let n = num_field(v, key).map_err(|_| format!("{name} must be a finite number"))?; - match (n, range) { - (Some(n), Some((lo, hi))) if !(lo..=hi).contains(&n) => Err(format!("{name} must be between {lo} and {hi} (got {n})")), - _ => Ok(n), - } -} - -/// An optional string named `name` in errors, one of `accepted` when given. -fn input_choice<'a>(v: &'a Value, key: &str, name: &str, accepted: &[&str]) -> std::result::Result, String> { - match v.get(key) { - None => Ok(None), - Some(Value::String(s)) if accepted.is_empty() || accepted.contains(&s.as_str()) => Ok(Some(s)), - Some(Value::String(s)) => Err(format!("unknown {name} `{s}` ({})", accepted.join(", "))), - Some(_) => Err(format!("{name} must be a string")), - } -} - -/// The modifier flags of `ui.pointer` / `ui.key`: grouped under `modifiers` when present (the -/// top-level flags are then ignored, but still type-checked), else top-level. -fn input_modifiers(p: &Value, flags: &[&str]) -> std::result::Result { - for flag in flags { - bool_field(p, flag)?; - } - let Some(m) = p.get("modifiers") else { return Ok(p.clone()) }; - let m = input_object(m, Some("modifiers"), flags)?; - for flag in flags { - bool_field(&m, flag).map_err(|e| format!("modifiers.{e}"))?; - } - Ok(m) -} - fn wrap(r: Result) -> Outcome { match r { Ok(v) => ok(v), @@ -347,36 +166,6 @@ fn run_waiting(app: &mut PhotocraftApp, wait: bool, run: impl FnOnce(&mut Photoc } } -/// Screen position of document point (x, y) on the main canvas, where a `ui.pointer` right-click -/// opens its menu (the mouse's opens at the pointer); the canvas centre when it can't be mapped. -fn screen_point(app: &PhotocraftApp, x: f64, y: f64) -> [f32; 2] { - let p = crate::canvas::ViewXform::active(app) - .map(|xf| xf.to_screen(x as f32, y as f32)) - .filter(|p| p.is_finite()) - .unwrap_or_else(|| app.last_canvas_rect.center()); - [p.x, p.y] -} - -/// Modifier flags of a request, top-level or grouped under `modifiers`. -/// -/// Off the Mac, Ctrl is the shortcut key, so egui wants `ctrl` and `command` to carry the same -/// value (`egui::Modifiers::command`: "On Windows and Linux, set this to the same value as -/// `ctrl`") and shortcuts are matched on `command`. A real Ctrl press arrives with both set, so -/// a request that sets only one of them gets both here and reaches the same shortcuts. On the Mac -/// they are different keys and stay apart: `command` is the ⌘ key, `ctrl` the Control key. -fn modifiers_from(p: &Value) -> egui::Modifiers { - let m = p.get("modifiers").unwrap_or(p); - let flag = |k: &str| m.get(k).and_then(Value::as_bool).unwrap_or(false); - let (ctrl, command) = (flag("ctrl"), flag("command")); - egui::Modifiers { - shift: flag("shift"), - alt: flag("alt"), - command: if cfg!(target_os = "macos") { command } else { command || ctrl }, - mac_cmd: cfg!(target_os = "macos") && command, - ctrl: if cfg!(target_os = "macos") { ctrl } else { command || ctrl }, - } -} - /// The `dialog` id of the shell's own dialog (`workspace_ui`) in `ui.inspect` and `ui.dialog.*`. const SHELL_DIALOG: &str = "shell"; @@ -390,1139 +179,5 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest outcome } -/// The open canvas context menu's rows for `ui.state`: the spelling suggestions first (type edit -/// menu over a misspelled word), then the menu's own rows. -fn context_entries(app: &PhotocraftApp, menu: &crate::canvas_tool_menu::CanvasToolMenu) -> Vec { - use crate::canvas_tool_menu::{crop_rows, entry_enabled, rows, spelling_rows}; - let spelling = spelling_rows(menu); - let mut entries: Vec = spelling.iter().map(|(label, id)| json!({"label": label, "id": id, "enabled": entry_enabled(app, menu, id)})).collect(); - if !spelling.is_empty() { - entries.push(json!({"separator": true})); - } - entries.extend(crop_rows(menu).iter().map(|row| match row { - Some((label, id)) => json!({"label": label, "id": id, "enabled": entry_enabled(app, menu, id)}), - None => json!({"separator": true}), - })); - entries.extend(rows(menu).iter().map(|row| match row { - Some((label, id)) => json!({"label": label, "id": id, "enabled": entry_enabled(app, menu, id)}), - None => json!({"separator": true}), - })); - entries -} - -fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { - let p = &req.params; - let s = |k: &str| p.get(k).and_then(Value::as_str); - let u = |k: &str| p.get(k).and_then(Value::as_u64); - let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(true); - match req.method.as_str() { - "ui.context.choose" => { - let Some(id) = s("id") else { return err("missing `id`") }; - let Some(menu) = app.ui.canvas_tool_menu.as_ref() else { return err("no canvas context menu is open") }; - if !crate::canvas_tool_menu::available(app, menu, id) { - return err("context action is unavailable"); - } - // A pasteboard row changes a preference: the policy sees the `prefs.set` it runs. - let (command, params) = crate::canvas_tool_menu::engine_call(app, menu, id); - if let Some(authorize) = app.services.automation_command.as_ref() - && let Err(error) = authorize(&command, ¶ms) - { - return err(error); - } - crate::canvas_tool_menu::choose(app, ctx, id); - ok(json!({"command": id, "dialog": app.ui.dialogs.last().map(|d| d.id)})) - } - "engine.execute" | "ui.menu.invoke" => { - let Some(id) = s("command").or(s("id")) else { return err("missing `command`") }; - let params = p.get("params").cloned().unwrap_or(json!({})); - // A control-channel menu click must respect the same modal gate as the native menu. - // The documented `ui` requests of Camera Raw and the full-window workspaces operate - // the already-open one rather than click a menu. Only that continuation may pass its - // own modal gate. engine.execute is deliberately not subject to the UI's menu-click semantics. - let open_modal = if app.camera_raw.is_some() { Some("filter.cameraRaw") } else { crate::distort_ui::modal_workspace(app) }; - let continuation = open_modal == Some(id) - && params.as_object().is_some_and(|fields| fields.len() == 1 && fields.get("ui").is_some_and(Value::is_object)) - && app.ui.dialogs.is_empty() - && app.discard.is_none() - && !crate::crop_ui::blocks(app, id); - if req.method == "ui.menu.invoke" && !continuation && !crate::menus::modal_allows(app, id) { - return err("menu command is unavailable while a modal dialog is open"); - } - if let Some(authorize) = app.services.automation_command.as_ref() - && let Err(error) = authorize(id, ¶ms) - { - return err(error); - } - // `engine.execute` is programmatic: engine commands run directly with their default - // params and never open a dialog (an agent would otherwise get a modal instead of a - // result). `ui.menu.invoke` behaves like a menu click, so it may open the dialog. - if req.method == "engine.execute" && photocraft_engine::commands::find(id).is_some() { - return run_waiting(app, wait, |app| app.run(id, params)); - } - run_waiting(app, wait, |app| crate::menus::invoke(app, ctx, id, params)) - } - "engine.commands" => wrap(app.run("command.list", json!({}))), - // Background jobs (#210): running ones with progress, then the last few that ended. - "jobs.list" => wrap(app.session.execute("jobs.list", json!({})).map_err(|e| e.to_string())), - "jobs.cancel" => { - let all = p.get("job").is_none_or(Value::is_null); - match p.get("job").and_then(Value::as_u64) { - Some(j) if app.session.job(photocraft_engine::jobs::JobId(j)).is_some() => { - let cancelled = crate::jobs_ui::cancel(app, photocraft_engine::jobs::JobId(j)); - ok(json!({"cancelled": usize::from(cancelled)})) - } - Some(j) => err(format!("no running job {j}")), - None if all => { - let ids: Vec<_> = app.session.jobs().into_iter().map(|j| j.id).collect(); - let cancelled = ids.into_iter().filter(|j| crate::jobs_ui::cancel(app, *j)).count(); - ok(json!({"cancelled": cancelled})) - } - None => err("`job` must be a job id"), - } - } - "ui.menu.list" => { - // Report the same enablement the native menu shows, so a listed item is invokable. - let mut items = crate::menus::menu_items(app); - for item in &mut items { - item.enabled &= crate::menus::modal_allows(app, &item.id); - } - ok(serde_json::to_value(items).unwrap_or_default()) - } - "ui.inspect" => ok(inspect(app, ctx)), - "ui.set" => { - if let Some(field) = p.as_object().and_then(|o| o.keys().find(|k| !UI_SET_FIELDS.contains(&k.as_str()))) { - return err(format!("unknown field `{field}` (fields: {})", UI_SET_FIELDS.join(", "))); - } - let gradient_blend = if let Some(value) = p.get("gradientBlendMode") { - let Some(name) = value.as_str() else { return err("gradientBlendMode must be a blend mode name") }; - let Some(mode) = photocraft_engine::commands::blend_from_str(name).filter(|m| photocraft_color::BlendMode::LAYER_MODES.contains(m)) else { - return err(format!("unknown gradient blend mode `{name}`")); - }; - Some(mode) - } else { - None - }; - // Everything is validated and materialized before the first field is applied, so a - // rejected call applies none of its fields (#412's guarantee, down to the values - // and nested keys). - let applied = (|| -> std::result::Result { - let shape_stroke = match p.get("shapeStroke") { - Some(v) => { - if let Some(object) = v.as_object() { - let keys = ["width", "opacity", "align", "cap", "join", "miterLimit", "dashes", "dashOffset"]; - if let Some(key) = object.keys().find(|key| !keys.contains(&key.as_str())) { - return Err(format!("unknown shapeStroke field `{key}`")); - } - } - let o = &app.ui.tool_options; - let base = o.shape_stroke.stroke(o.stroke_width, photocraft_doc::Fill::Solid(photocraft_doc::Color::BLACK)); - Some(photocraft_engine::vector_cmds::parse_stroke(v, Some(base), photocraft_doc::Color::BLACK)?) - } - None => None, - }; - let tool = match s("tool") { - Some(t) => Tool::from_name(t).map(Some).ok_or_else(|| format!("unknown tool `{t}`"))?, - None => None, - }; - let gradient_classic = bool_field(p, "gradientClassic")?; - // The stroke latency trace (`stroke_trace`), at runtime: on (stderr) or off. A CSV - // file is only for the user's own launch (`--stroke-trace `): a path over the - // control channel would write outside the automation write root. - let stroke_trace = match p.get("strokeTrace") { - None | Some(Value::Null) => None, - Some(Value::Bool(b)) => Some(if *b { "stderr" } else { "off" }), - Some(Value::String(v)) => match v.trim() { - "stderr" | "on" | "true" => Some("stderr"), - "off" | "false" => Some("off"), - _ => return Err("strokeTrace must be true, false, \"stderr\" or \"off\"; a CSV file is set at launch (--stroke-trace )".into()), - }, - Some(_) => return Err("strokeTrace must be true, false, \"stderr\" or \"off\"".into()), - }; - // The Eyedropper's options bar (#1649): Sample Size, Sample, Show Sampling Ring. - let eyedropper_size = match p.get("eyedropperSampleSize") { - Some(v) => Some( - photocraft_engine::sample_cmds::size_param("ui.set", &json!({"size": v})) - .map_err(|_| format!("eyedropperSampleSize must be \"point\" or one of {:?}", photocraft_engine::sample_cmds::SAMPLE_SIZES))?, - ), - None => None, - }; - let eyedropper_sample = match p.get("eyedropperSample") { - Some(v) => { - let ids: Vec<&str> = photocraft_engine::sample_cmds::SampleLayers::ALL.iter().map(|(_, n)| *n).collect(); - let id = v.as_str().filter(|id| ids.contains(id)).ok_or_else(|| format!("eyedropperSample must be one of {}", ids.join(", ")))?; - Some(id.to_string()) - } - None => None, - }; - let eyedropper_ring = bool_field(p, "eyedropperRing")?; - // Content-Aware Move's Transform On Drop checkbox. - let cam_transform_on_drop = bool_field(p, "camTransformOnDrop")?; - // Developer overlay of the active layer's storage tiles (tile_overlay.rs). - let tile_grid = bool_field(p, "tileGrid")?; - let layer_filter = p.get("layerFilter").map(|v| crate::layer_filter_ui::patched(&app.ui, v)).transpose()?; - // The Crop tool's overlay menu (#1919). - let crop_overlay = match p.get("cropOverlay") { - Some(v) => Some(v.as_str().and_then(crate::crop_overlay::CropOverlay::from_id).ok_or_else(|| { - let ids: Vec<&str> = crate::crop_overlay::CropOverlay::ALL.iter().map(|k| k.id()).collect(); - format!("cropOverlay must be one of {}", ids.join(", ")) - })?), - None => None, - }; - let crop_overlay_show = match p.get("cropOverlayShow") { - Some(v) => Some( - v.as_str() - .and_then(crate::crop_overlay::OverlayShow::from_id) - .ok_or_else(|| "cropOverlayShow must be one of auto, always, never".to_string())?, - ), - None => None, - }; - let crop_overlay_orientation = match uint_field(p, "cropOverlayOrientation")? { - Some(o) if o < 4 => Some(o as u8), - Some(_) => return Err("cropOverlayOrientation must be 0, 1, 2 or 3".into()), - None => None, - }; - // The Crop tool's Fill (#3823): "background" (Background (Default)) or "contentAware". - let crop_content_aware = match p.get("cropFill") { - Some(v) => Some(match v.as_str() { - Some("background") => false, - Some("contentAware") => true, - _ => return Err("cropFill must be \"background\" or \"contentAware\"".into()), - }), - None => None, - }; - // The Crop tool's gear menu: Show Cropped Area and the shield (#1919). - let crop_shield = merged_object(&app.ui.tool_options.crop_shield, p.get("cropShield"), "cropShield")?; - if crop_shield.as_ref().is_some_and(|s| !(0.0..=100.0).contains(&s.opacity)) { - return Err("cropShield.opacity must be 0..100".into()); - } - // The Histogram panel: its options, the dragged tonal range ([from, to] levels or - // null) and Uncached Refresh. - let histogram_panel = merged_object(&app.ui.histogram_panel, p.get("histogramPanel"), "histogramPanel")?; - let histogram_range = match p.get("histogramRange") { - Some(v) => Some( - serde_json::from_value::>(v.clone()) - .map_err(|_| "histogramRange must be [from, to] levels 0..255, or null".to_string())?, - ), - None => None, - }; - let histogram_refresh = bool_field(p, "histogramRefresh")?; - let panels = merged_object(&app.ui.panels, p.get("panels"), "panels")?; - let mask_target = bool_field(p, "maskTarget")?; - let updates_open = bool_field(p, "updatesOpen")?; - let vector_mask_target = bool_field(p, "vectorMaskTarget")?; - // Target the active smart object's filter mask (FILE-215-3): it needs smart filters. - let filter_mask_target = bool_field(p, "filterMaskTarget")?; - if filter_mask_target == Some(true) { - let st = app.session.active().ok_or("filterMaskTarget needs an open document")?; - let l = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or("filterMaskTarget needs an active layer")?; - if !matches!(&l.content, photocraft_doc::LayerContent::Smart(sm) if !sm.smart_filters.is_empty()) { - return Err("filterMaskTarget needs an active smart object with smart filters".into()); - } - use photocraft_engine::channel_cmds::ChannelTarget; - let composite = matches!(st.channel_view.target, ChannelTarget::Composite | ChannelTarget::LayerMask | ChannelTarget::VectorMask); - if !composite || st.doc.quick_mask.is_some() { - return Err("filterMaskTarget can't be set while a single channel or Quick Mask is targeted".into()); - } - } - let selection_mode = uint_field(p, "selectionMode")?; - let dock_tabs = merged_object(&app.ui.dock_tabs, p.get("dockTabs"), "dockTabs")?; - let dock = whole_object(&app.ui.dock, p.get("dock"), "dock")?; - // Which chip the Color panel edits. - let color_panel = merged_object(&app.ui.color_panel, p.get("colorPanel"), "colorPanel")?; - let dock_width = f32_field(p, "dockWidth")?; - let zoom = f32_field(p, "zoom")?; - let rotation = f32_field(p, "rotation")?; - if rotation.is_some() && app.session.active_index().is_none() { - return Err("no document open".into()); - } - let center = match p.get("center") { - Some(v) => { - let a = v.as_array().ok_or_else(|| "center must be [x, y]".to_string())?; - if a.len() != 2 { - return Err("center must be exactly [x, y]".into()); - } - let (Some(x), Some(y)) = (a.first().and_then(Value::as_f64), a.get(1).and_then(Value::as_f64)) else { - return Err("center must be [x, y] of two numbers".into()); - }; - if !f32_range(&x) || !f32_range(&y) { - return Err("center must be finite numbers within f32 range".into()); - } - Some([x as f32, y as f32]) - } - None => None, - }; - let fit = bool_field(p, "fit")? == Some(true); - let theme = match s("theme") { - Some(name) => { - let kind = crate::theme::ThemeKind::from_name(name).ok_or_else(|| { - let names: Vec<_> = crate::theme::ThemeKind::ALL.iter().map(|k| k.id()).collect(); - format!("unknown theme `{name}` ({})", names.join(", ")) - })?; - Some(kind) - } - None => None, - }; - let brush_section = uint_field(p, "brushSection")?; - let brush_tab = uint_field(p, "brushTab")?; - let brushes_view = match p.get("brushesView") { - Some(v) => serde_json::from_value(v.clone()).map(Some).map_err(|e| format!("brushesView: {e} (list, grid)"))?, - None => None, - }; - // The three parts of the picker's cards. At least one stays on (a rejected call - // leaves them all alone). - let brush_picker_name = bool_field(p, "brushPickerName")?; - let brush_picker_stroke = bool_field(p, "brushPickerStroke")?; - let brush_picker_tip = bool_field(p, "brushPickerTip")?; - if [brush_picker_name, brush_picker_stroke, brush_picker_tip].iter().any(Option::is_some) { - let on = [ - brush_picker_name.unwrap_or(app.ui.brush_picker_list.show_name), - brush_picker_stroke.unwrap_or(app.ui.brush_picker_list.show_stroke), - brush_picker_tip.unwrap_or(app.ui.brush_picker_list.show_tip), - ]; - if !on.iter().any(|b| *b) { - return Err("brushPickerName, brushPickerStroke and brushPickerTip: at least one must stay on".into()); - } - } - // The picker footer slider: the preset cards' size scale (1 standard; 0.30 and - // below the tips drop their size numbers). - let brush_picker_scale = match num_field(p, "brushPickerScale")? { - Some(s) if !(0.15..=2.0).contains(&s) => return Err("brushPickerScale must be between 0.15 and 2".into()), - Some(s) => Some(s as f32), - None => None, - }; - // `Some(None)` is an explicit null, which closes the picker (a missing field - // leaves it alone). - let brush_picker = match p.get("brushPicker") { - Some(v) => { - let at = serde_json::from_value::>(v.clone()) - .map_err(|_| "brushPicker must be [x, y] in screen points, or null to close it".to_string())?; - if at.is_some_and(|[x, y]| !x.is_finite() || !y.is_finite()) { - return Err("brushPicker must be [x, y] in screen points, or null to close it".into()); - } - Some(at) - } - None => None, - }; - // brushSize rides the journaled `tools.setBrush` command (#744). Numeric values - // are validated here so the command cannot fail after other fields were - // applied; non-numeric values keep the API's historical silent no-op. - let brush_size: Option = match p.get("brushSize").and_then(Value::as_f64) { - Some(size) => { - if !size.is_finite() || size > f64::from(photocraft_paint::MAX_BRUSH_SIZE) { - return Err(format!("brushSize must be finite and at most {} px", photocraft_paint::MAX_BRUSH_SIZE)); - } - Some(size) - } - None => None, - }; - - let bridge_pro = matches!(theme.unwrap_or(app.ui.theme), crate::theme::ThemeKind::Pro | crate::theme::ThemeKind::ProMedium); - let legacy_update = crate::panel_docking::prepare_legacy_update(app, p, panels.as_ref(), dock_tabs.as_ref(), dock.as_ref(), bridge_pro)?; - - // Apply (nothing below can fail). - if let Some(stroke) = shape_stroke { - if let Some(stroke) = stroke { - app.ui.tool_options.stroke_width = stroke.width; - app.ui.tool_options.shape_stroke = crate::shape_stroke_ui::StrokeOptions::from(&stroke); - } else { - app.ui.tool_options.stroke_width = 0.0; - } - } - if let Some(t) = tool { - crate::tool_memory::select(app, t); - // Each tool keeps its own brush (#218), so switch it in before `brushSize` - // below sets the new tool's size. - crate::paint_mouse::sync_tool_brush(app); - } - let gradient_before = app.ui.tool_options.clone(); - if let Some(mode) = gradient_blend { - app.ui.tool_options.gradient_blend_mode = mode; - } - if let Some(v) = &stroke_trace { - app.stroke_trace.set(v); - } - if let Some(classic) = gradient_classic { - app.ui.tool_options.gradient_classic = classic; - } - if gradient_blend.is_some() { - crate::gradient_ui::options_changed(app, &gradient_before); - } - if let Some(size) = eyedropper_size { - app.ui.tool_options.eyedropper_size = size; - } - if let Some(id) = eyedropper_sample { - app.ui.tool_options.eyedropper_sample = id; - } - if let Some(ring) = eyedropper_ring { - app.ui.tool_options.eyedropper_ring = ring; - } - if let Some(on) = cam_transform_on_drop { - app.ui.tool_options.cam_transform_on_drop = on; - } - if let Some(on) = tile_grid { - app.ui.view.tile_grid = on; - } - if let Some(f) = layer_filter { - crate::layer_filter_ui::apply(&mut app.ui, f); - } - if let Some(h) = histogram_panel { - app.ui.histogram_panel = h; - crate::histogram_panel::persist_options(app); - } - if let Some(r) = histogram_range { - app.ui.histogram_range = r; - } - if histogram_refresh == Some(true) { - crate::histogram_panel::uncached_refresh(app); - } - if let Some(k) = crop_overlay { - app.ui.tool_options.crop_overlay = k; - } - if let Some(on) = crop_content_aware { - app.ui.tool_options.crop_content_aware = on; - } - if let Some(v) = crop_overlay_show { - app.ui.tool_options.crop_overlay_show = v; - } - if let Some(o) = crop_overlay_orientation { - app.ui.tool_options.crop_overlay_orientation = o; - } - if let Some(s) = crop_shield { - app.ui.tool_options.crop_shield = s; - } - if let Some(v) = panels { - app.ui.panels = v; - } - if let Some(m) = mask_target { - app.end_filter_mask_view(); - app.ui.filter_mask_target = None; - app.ui.mask_target = m; - app.ui.properties_layer = None; - app.ui.vector_mask_target &= !m; - app.sync_mask_targets(); - } - if let Some(open) = updates_open { - app.ui.updates_open = open; - } - if let Some(m) = vector_mask_target { - app.end_filter_mask_view(); - app.ui.filter_mask_target = None; - app.ui.vector_mask_target = m; - app.ui.mask_target &= !m; - app.sync_mask_targets(); - } - if let Some(m) = filter_mask_target { - let layer = if m { app.session.active().and_then(|st| st.active_layer).map(|id| id.0) } else { None }; - app.select_filter_mask_target(layer); - } - // Selection tools' options-bar mode: 0 New, 1 Add, 2 Subtract, 3 Intersect. - if let Some(m) = selection_mode { - app.ui.selection_mode = m.min(3) as u8; - } - if let Some(k) = theme { - app.set_theme(ctx, k); - } - if let Some(v) = dock_tabs { - app.ui.dock_tabs = v; - } - // Dock group order, heights and collapsed groups (see `dock::DockLayout`). - if let Some(v) = dock { - app.ui.dock = v; - } - if let Some(update) = legacy_update { - crate::panel_docking::commit_legacy_update(app, update, p); - } - if let Some(v) = color_panel { - app.ui.color_panel = v; - } - // Right dock width in points (clamped to the dock's 250..=520 range), applied next frame. - if let Some(w) = dock_width { - crate::panels::request_dock_width(ctx, w as f32); - } - if let Some(i) = app.session.active_index() { - if zoom.is_some() || center.is_some() || rotation.is_some() || fit { - app.ui.views[i].zoom_animating = false; - app.ui.views[i].zoom_anchor = None; - } - if let Some(z) = zoom { - let size = app.session.documents().get(i).map_or([0, 0], |st| [st.doc.size.width, st.doc.size.height]); - app.ui.views[i].zoom = crate::zoom_levels::clamp(z as f32, size); - app.ui.views[i].fit_pending = false; - app.ui.views[i].fill_pending = false; - } - if let Some(c) = center { - app.ui.views[i].center = c; - app.ui.views[i].fit_pending = false; - app.ui.views[i].fill_pending = false; - } - if fit { - app.ui.views[i].fit_pending = true; - app.ui.views[i].fill_pending = false; - } - if let Some(r) = rotation { - app.ui.views[i].rotation = crate::rotate_view::wrap_deg(r as f32); - } - } - if let Some(i) = brush_section { - app.ui.brush_section = (i as usize).min(crate::brush_panel::SECTIONS.len() - 1); - } - if let Some(i) = brush_tab { - app.ui.brush_tab = (i as usize).min(1); - } - if let Some(v) = brushes_view { - app.ui.brushes_panel.view = v; - } - if let Some(v) = brush_picker_name { - app.ui.brush_picker_list.show_name = v; - } - if let Some(v) = brush_picker_stroke { - app.ui.brush_picker_list.show_stroke = v; - } - if let Some(v) = brush_picker_tip { - app.ui.brush_picker_list.show_tip = v; - } - if let Some(v) = brush_picker_scale { - app.ui.brush_picker_list.scale = v; - } - if let Some(at) = brush_picker { - app.ui.brush_picker = at; - } - // Which chip the Color panel edits. - if let Some(c) = color_panel { - app.ui.color_panel = c; - } - if let Some(size) = brush_size { - app.run("tools.setBrush", json!({"brush": {"size": size}})).map_err(|e| e.to_string())?; - } - Ok(Value::Null) - })(); - wrap(applied) - } - "ui.dialog.open" => { - let kind = match s("kind").unwrap_or("") { - "newDocument" | "NewDocument" => DialogKind::NewDocument, - "about" | "About" => DialogKind::About, - "layerStyle" | "LayerStyle" => { - return match crate::layer_style::open(app, s("effect")) { - Some(id) => ok(json!({"dialog": id})), - None => err("no active layer"), - }; - } - "colorPicker" | "ColorPicker" => { - if let Some(style) = p.get("textStyle") { - if ["parent", "effect", "field", "target"].iter().any(|key| p.get(*key).is_some()) { - return err("textStyle cannot be combined with another picker target"); - } - let Some(style) = style.as_object().filter(|s| s.keys().all(|k| k == "kind" || k == "id")) else { - return err("textStyle needs kind and id only"); - }; - let Some(kind) = style.get("kind").cloned().and_then(|v| serde_json::from_value::(v).ok()) - else { - return err("textStyle kind must be character or paragraph"); - }; - let Some(id) = style.get("id").and_then(Value::as_u64).and_then(|id| u32::try_from(id).ok()) else { - return err("textStyle id must be a u32 integer"); - }; - return match crate::type_panels_ui::color_picker::open(app, kind, id) { - Ok(id) => ok(json!({"dialog": id})), - Err(error) => err(error), - }; - } - if p.get("parent").is_some() { - let (Some(parent), Some(effect), Some(field)) = (u("parent"), s("effect"), s("field")) else { - return err("need integer `parent` and string `effect` and `field`"); - }; - return match crate::layer_style::color_picker::open(app, parent, effect, field) { - Ok(id) => ok(json!({"dialog": id})), - Err(error) => err(error), - }; - } - if p.get("effect").is_some() || p.get("field").is_some() { - return err("Layer Style color pickers need `parent`"); - } - let target = if s("target") == Some("background") { "background" } else { "foreground" }; - return ok(json!({"dialog": crate::color_picker_ui::open(app, target)})); - } - // The Crop tool's New / Delete Crop Preset… (#1919). - "newCropPreset" => { - return match crate::crop_presets::open_new(app) { - Some(id) => ok(json!({"dialog": id})), - None => err("nothing to save: set W and H (W x H x Resolution) or a ratio first"), - }; - } - "deleteCropPreset" => { - return match crate::crop_presets::open_delete(app) { - Some(id) => ok(json!({"dialog": id})), - None => err("no crop presets are saved"), - }; - } - "command" | "Command" => { - let Some(cmd) = s("command") else { return err("command dialogs need `command`") }; - let label = photocraft_engine::commands::find(cmd).map(|c| c.label).unwrap_or(cmd); - return ok(json!({"dialog": crate::dialogs::open_command_dialog(app, cmd, label)})); - } - other => return err(format!("unknown dialog kind `{other}`")), - }; - let mut fields = if kind == DialogKind::NewDocument { app.new_document_fields() } else { Default::default() }; - if let Some(f) = p.get("fields").and_then(Value::as_object) { - if let Some(marker) = f.keys().find(|k| crate::dialogs::is_route_marker(k)) { - return err(format!("`{marker}` is set only by the dialog it belongs to")); - } - fields.extend(f.clone()); - } - ok(json!({"dialog": app.ui.open_dialog(kind, fields)})) - } - // The shell's own dialog (Window › Workspace, View › Pixel Aspect Ratio › Custom, Show - // Extras Options, 32-bit Preview Options), listed by ui.inspect with the id "shell". - "ui.dialog.set" if s("dialog") == Some(SHELL_DIALOG) => { - let Some(field) = s("field") else { return err("need `dialog` and `field`") }; - let value = p.get("value").cloned().unwrap_or(Value::Null); - match app.ui.shell.dialog.as_mut() { - Some((_, fields)) => { - fields.insert(field.to_string(), value); - ok(Value::Null) - } - None => err("no shell dialog is open"), - } - } - "ui.dialog.confirm" if s("dialog") == Some(SHELL_DIALOG) => { - let Some((kind, fields)) = app.ui.shell.dialog.clone() else { return err("no shell dialog is open") }; - if let Some((command, params)) = crate::workspace_ui::dialog_command(&kind, &fields) - && let Some(authorize) = app.services.automation_command.as_ref() - && let Err(error) = authorize(command, ¶ms) - { - return err(error); - } - wrap(crate::workspace_ui::confirm(app, ctx)) - } - "ui.dialog.apply" if s("dialog") == Some(SHELL_DIALOG) => err("`ui.dialog.apply` is for Preferences; use `ui.dialog.confirm`"), - // The unsaved-changes prompt (closing, Revert, quitting), listed by ui.inspect with the - // id "discard" (#4920): confirm takes a `choice` (save, dontSave, cancel; default save). - "ui.dialog.confirm" if s("dialog") == Some(crate::discard_ui::CONTROL_ID) => { - let choice = s("choice").unwrap_or("save"); - if choice != "cancel" - && let Some((command, params)) = crate::discard_ui::pending_command(app) - && let Some(authorize) = app.services.automation_command.as_ref() - && let Err(error) = authorize(&command, ¶ms) - { - return err(error); - } - wrap(crate::discard_ui::answer_control(app, ctx, choice)) - } - "ui.dialog.cancel" if s("dialog") == Some(crate::discard_ui::CONTROL_ID) => wrap(crate::discard_ui::answer_control(app, ctx, "cancel")), - "ui.dialog.set" | "ui.dialog.apply" if s("dialog") == Some(crate::discard_ui::CONTROL_ID) => { - err("the unsaved-changes prompt has no fields; use `ui.dialog.confirm` with a `choice`") - } - "ui.dialog.cancel" if s("dialog") == Some(SHELL_DIALOG) => match app.ui.shell.dialog.take() { - Some(_) => ok(Value::Null), - None => err("no such dialog"), - }, - "ui.dialog.set" => { - let (Some(id), Some(field)) = (u("dialog"), s("field")) else { return err("need `dialog` and `field`") }; - let value = p.get("value").cloned().unwrap_or(Value::Null); - match app.ui.dialog_mut(id) { - // A continuation belongs to the dialog that paused it, even when another - // action has a valid token. Replacing it would resume or cancel that action. - Some(_) if field == crate::actions::RESUME => err("the paused action token is read-only"), - // A marker picks the handler OK runs: a dialog keeps the ones it was opened with. - Some(d) if !d.fields.contains_key(field) && crate::dialogs::is_route_marker(field) => { - err(format!("`{field}` is set only by the dialog it belongs to")) - } - Some(d) => { - d.fields.insert(field.to_string(), value); - ok(Value::Null) - } - None => err(format!("no dialog {id}")), - } - } - "ui.dialog.confirm" | "ui.dialog.apply" => match u("dialog") { - Some(id) => { - let command = app.ui.dialogs.iter().find(|dialog| dialog.id == id).and_then(|dialog| { - if req.method == "ui.dialog.apply" { - dialog.fields.get("values").map(|values| ("prefs.set".to_string(), json!({"path": "", "value": values}))) - } else { - dialog.fields.get("__command").and_then(Value::as_str).map(|command| (command.to_string(), Value::Object(dialog.fields.clone()))) - } - }); - if let Some((command, params)) = command - && let Some(authorize) = app.services.automation_command.as_ref() - && let Err(error) = authorize(&command, ¶ms) - { - return err(error); - } - let apply = req.method == "ui.dialog.apply"; - run_waiting(app, wait, |app| if apply { crate::prefs_ui::apply(app, id) } else { crate::dialogs::confirm(app, id) }) - } - None => err("missing `dialog`"), - }, - "ui.dialog.cancel" => match u("dialog") { - Some(id) => match crate::dialogs::cancel(app, id) { - Ok(value) => ok(value), - Err(error) => err(error), - }, - None => err("missing `dialog`"), - }, - "ui.window.open" => { - if let Some(d) = u("document") - && !app.session.set_active(d as usize) - { - return err(format!("no document {d}")); - } - wrap(crate::menus::invoke(app, ctx, "window.newWindowForDocument", json!({}))) - } - "ui.window.close" => { - let Some(id) = u("window") else { return err("missing `window`") }; - let before = app.ui.windows.len(); - app.ui.windows.retain(|w| w.id != id); - if app.ui.windows.len() < before { ok(Value::Null) } else { err(format!("no window {id}")) } - } - "ui.pointer" => { - // Every field and event is validated before the first event runs, so a rejected call - // changes nothing (#2449). - let parsed = (|| -> std::result::Result<_, String> { - let fields = ["events", "tool", "modifiers", "button", "shift", "alt", "command", "ctrl", "space"]; - let p = input_object(p, None, &fields)?; - let tool = match input_choice(&p, "tool", "tool", &[])? { - Some(t) => Some(Tool::from_name(t).ok_or_else(|| format!("unknown tool `{t}`"))?), - None => None, - }; - let button = input_choice(&p, "button", "button", &BUTTONS)?.unwrap_or("left").to_string(); - // Modifier flags may be top-level or grouped under "modifiers". - let m = input_modifiers(&p, &POINTER_MODIFIERS)?; - let Some(events) = p.get("events") else { return Err("missing `events`".into()) }; - let Some(events) = events.as_array() else { return Err("events must be an array".into()) }; - let mut parsed = Vec::with_capacity(events.len()); - for (i, e) in events.iter().enumerate() { - let name = format!("events[{i}]"); - let e = input_object(e, Some(&name), &["kind", "x", "y", "pressure", "tiltX", "tiltY", "rotation"])?; - let num = |k: &str, range| input_number(&e, k, &format!("{name}.{k}"), range); - let (x, y) = (num("x", None)?.unwrap_or(0.0), num("y", None)?.unwrap_or(0.0)); - let pr = num("pressure", Some((0.0, 1.0)))?.unwrap_or(1.0) as f32; - let ev = match input_choice(&e, "kind", &format!("{name}.kind"), &["down", "move", "up"])?.unwrap_or("move") { - "down" => ToolEvent::Down { x, y, pressure: pr }, - "up" => ToolEvent::Up { x, y }, - _ => ToolEvent::Move { x, y, pressure: pr }, - }; - let tilt = |k: &str, range| num(k, Some(range)).map(|v| v.map(|v| v as f32)); - let pen = (tilt("tiltX", (-90.0, 90.0))?, tilt("tiltY", (-90.0, 90.0))?, tilt("rotation", (0.0, 360.0))?); - parsed.push((ev, x, y, pr, pen)); - } - Ok((tool, button, m, parsed)) - })(); - let (tool, button, m, events) = match parsed { - Ok(parsed) => parsed, - Err(e) => return err(e), - }; - let secondary = matches!(button.as_str(), "secondary" | "right"); - let mods = modifiers_from(&m); - if let Some(t) = tool { - crate::tool_memory::select(app, t); - } - // Space held: the Crop tool moves the frame being drawn, a marquee, lasso or shape - // being drawn moves instead of growing (hold_keys.rs). Like a modifier flag, it may be - // top-level or grouped under "modifiers". - let space = p.get("modifiers").unwrap_or(p).get("space").and_then(Value::as_bool).unwrap_or(false); - crate::crop_ui::set_space(app, space); - for (ev, x, y, pr, pen) in events { - // With the Color Picker on top the image is its eyedropper, as for the mouse. - if crate::color_picker_ui::top(app).is_some() { - if !matches!(ev, ToolEvent::Up { .. }) { - crate::color_picker_ui::sample_at(app, x, y); - } - continue; - } - // Curves' modal eyedroppers use document coordinates here, matching the native - // canvas path after its ViewXform conversion. Sample on press only. - if !secondary && crate::adjust_dialog::picker_armed(app) { - if matches!(ev, ToolEvent::Down { .. }) { - crate::adjust_dialog::sample_at(app, x, y); - } - continue; - } - // ⌘/Ctrl-click with Curves open adds a point at the pixel's tone, on press only (#7325). - if !secondary && !space && button != "middle" && mods.command && crate::adjust_dialog::curves_on_top(app) { - if matches!(ev, ToolEvent::Down { .. }) { - crate::adjust_dialog::add_point_at(app, ctx, x, y, mods.shift); - } - continue; - } - // A Properties Levels/Curves eyedropper owns the primary button the same way. - if app.ui.dialogs.is_empty() && !matches!(s("button"), Some("secondary" | "right")) && crate::layer_picker::armed(app).is_some() { - if matches!(ev, ToolEvent::Down { .. }) { - crate::layer_picker::sample_at(app, x, y); - } - continue; - } - // The dialog owns all pointer events, including Up: no underlying brush stroke - // or context menu may leak through while inspecting a Color Range preview. - if app.ui.dialogs.last().is_some_and(|d| crate::color_range_ui::owns(&d.fields)) { - let down = matches!(ev, ToolEvent::Down { .. }); - let up = matches!(ev, ToolEvent::Up { .. }); - let held = app.ui.dialogs.last().and_then(|d| d.fields.get("__pointerDown")).and_then(Value::as_bool).unwrap_or(false); - if let Some(d) = app.ui.dialogs.last_mut() { - d.fields.insert("__pointerDown".into(), json!(!up && (down || held))); - } - if !up && (down || held) && !space && !secondary && button != "middle" { - crate::color_range_ui::pick_top(app, [x, y], mods); - } - continue; - } - if secondary { - let down = matches!(ev, ToolEvent::Down { .. }); - // Right-click while transforming: the box's menu, as on the canvas. - if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none()) { - if down { - crate::canvas_tool_menu::open_transform(app, ctx, screen_point(app, x, y)); - } - continue; - } - // Right-click with the Move tool, or ⌘/Ctrl+right-click: list the layers there. - if crate::layer_pick_ui::is_gesture(app.ui.tool, mods) { - if down { - app.ui.canvas_tool_menu = None; - crate::layer_pick_ui::open(app, ctx, screen_point(app, x, y), x, y); - } - continue; - } - // No menu over the agent's own crop frame or Straighten line still being - // dragged, also the first one on the default frame (nothing pending yet). - if app.ui.tool == crate::state::Tool::Crop && (app.crop.drag.is_some() || app.crop.straighten.line.is_some()) { - continue; - } - if app.ui.tool == crate::state::Tool::Crop && crate::crop_ui::pending(app) { - if down { - crate::canvas_tool_menu::open_crop(app, ctx, app.ui.tool, screen_point(app, x, y)); - } - continue; - } - if crate::canvas_tool_menu::pasteboard_at(app, app.ui.tool, [x, y]) { - if down { - crate::canvas_tool_menu::open_pasteboard(app, ctx, app.ui.tool, screen_point(app, x, y)); - } - continue; - } - if crate::canvas_tool_menu::is_view_tool(app.ui.tool) { - if down { - crate::canvas_tool_menu::open_view(app, ctx, app.ui.tool, screen_point(app, x, y), [x, y]); - } - continue; - } - if crate::canvas_tool_menu::applies(app.ui.tool) - || crate::canvas_tool_menu::editing_text(app, app.ui.tool) - || crate::canvas_tool_menu::type_layer_at(app, app.ui.tool, [x, y]).is_some() - { - if down { - crate::canvas_tool_menu::open_at(app, ctx, app.ui.tool, screen_point(app, x, y), Some([x, y])); - } - continue; - } - if !crate::paint_mouse::pointer_secondary(app, ctx, down, mods, screen_point(app, x, y)) { - continue; - } - } - // A simulated pen: tilt/rotation reach the stroke like a real stylus's (see `stylus`). - if pen != (None, None, None) { - let (tilt_x, tilt_y, rotation) = (pen.0.unwrap_or(0.0), pen.1.unwrap_or(0.0), pen.2.unwrap_or(0.0)); - app.stylus.feed.set(Some(crate::stylus::PenSample { pressure: pr, tilt_x, tilt_y, rotation, eraser: false })); - } - if let Some(d) = app.drag.as_mut().filter(|d| crate::hold_keys::repositions(d.tool)) { - d.reposition = space; - } - // A Crop drag in the default mode turns and pans the view with the image: its - // points are read as the view showed them at the press (`crop_mode`). - let ev = match ev { - ToolEvent::Move { x, y, pressure } => { - let [x, y] = crate::crop_mode::control_point(app, [x, y]); - ToolEvent::Move { x, y, pressure } - } - ToolEvent::Up { x, y } => { - let [x, y] = crate::crop_mode::control_point(app, [x, y]); - ToolEvent::Up { x, y } - } - down => down, - }; - tool_event(app, ev, mods); - } - app.stylus.feed.set(None); - ok(json!({"status": app.ui.status})) - } - "ui.click" | "ui.move" => { - let click = req.method == "ui.click"; - let fields: &[&str] = if click { &["x", "y", "button", "count"] } else { &["x", "y"] }; - let parsed = (|| -> std::result::Result<_, String> { - let p = input_object(p, None, fields)?; - // Screen coordinates in points (as reported by ui.inspect window size). - let x = input_number(&p, "x", "x", None)?.unwrap_or(0.0) as f32; - let y = input_number(&p, "y", "y", None)?.unwrap_or(0.0) as f32; - let button = match input_choice(&p, "button", "button", &BUTTONS)?.unwrap_or("left") { - "right" | "secondary" => egui::PointerButton::Secondary, - "middle" => egui::PointerButton::Middle, - _ => egui::PointerButton::Primary, - }; - let clicks = if click { uint_field(&p, "count")?.unwrap_or(1) } else { 0 }; - if clicks > MAX_CLICKS { - return Err(format!("`count` must be at most {MAX_CLICKS} (got {clicks})")); - } - Ok((egui::pos2(x, y), button, clicks)) - })(); - let (pos, button, clicks) = match parsed { - Ok(parsed) => parsed, - Err(e) => return err(e), - }; - app.synthetic.push(egui::Event::PointerMoved(pos)); - for _ in 0..clicks { - app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: true, modifiers: Default::default() }); - app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: false, modifiers: Default::default() }); - } - ctx.request_repaint(); - Outcome::AfterInput - } - "ui.key" => { - let parsed = (|| -> std::result::Result<_, String> { - let p = input_object(p, None, &["key", "modifiers", "shift", "alt", "command", "ctrl"])?; - let Some(name) = input_choice(&p, "key", "key", &[])? else { return Err("missing `key`".into()) }; - let key = egui::Key::from_name(name).ok_or_else(|| format!("unknown key `{name}`"))?; - // Modifier flags may be top-level or grouped under "modifiers". - Ok((key, input_modifiers(&p, &KEY_MODIFIERS)?)) - })(); - let (key, m) = match parsed { - Ok(parsed) => parsed, - Err(e) => return err(e), - }; - let modifiers = modifiers_from(&m); - app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }); - app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }); - ctx.request_repaint(); - Outcome::AfterInput - } - "ui.type" => { - let Some(text) = s("text") else { return err("missing `text`") }; - app.synthetic.push(egui::Event::Text(text.to_string())); - ctx.request_repaint(); - Outcome::AfterInput - } - "ui.resize" => { - let (w, h) = (p.get("width").and_then(Value::as_f64).unwrap_or(1280.0), p.get("height").and_then(Value::as_f64).unwrap_or(800.0)); - ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(w as f32, h as f32))); - ok(Value::Null) - } - "ui.gpu.simulateLoss" => { - if p.get("destroy").and_then(Value::as_bool).unwrap_or(false) { - let destroyed = app.destroy_window_device(); - ctx.request_repaint(); - return ok(json!({"destroyed": destroyed})); - } - let error = p.get("error").and_then(Value::as_bool).unwrap_or(false); - let fault = if error { - photocraft_gpu::Fault::Error("simulated error (ui.gpu.simulateLoss)".into()) - } else { - photocraft_gpu::Fault::Lost("simulated (ui.gpu.simulateLoss)".into()) - }; - let active = match app.gpu_health() { - Some(h) => { - h.mark(fault); - true - } - None => false, - }; - app.check_gpu(ctx); - ctx.request_repaint(); - ok(json!({"wasActive": active, "gpuInfo": app.perf.gpu_info})) - } - "ui.focus" => { - ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true)); - ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); - ctx.send_viewport_cmd(egui::ViewportCommand::Focus); - ctx.request_repaint(); - ok(Value::Null) - } - "ui.screenshot" => { - let parsed = input_object(p, None, &["path", "focus"]) - .and_then(|p| Ok((input_choice(&p, "path", "path", &[])?.map(str::to_string), bool_field(&p, "focus")?))); - let (path, focus) = match parsed { - Ok(parsed) => parsed, - Err(e) => return err(e), - }; - // Occluded windows don't render on macOS, so the screenshot would never arrive: raise first. - if focus.unwrap_or(true) { - ctx.send_viewport_cmd(egui::ViewportCommand::Focus); - } - // The capture itself is admitted by `PhotocraftApp::drain_control` (budget and - // geometry) and issued from a later `App::ui` pass once open/close animations - // (modals, popups) have settled (see `screenshot.rs`). - let token = app.ui.alloc_id(); - ctx.request_repaint(); - Outcome::Screenshot { token, path } - } - "app.open" => match s("path") { - Some(path) => { - // Directory .pcraft (the native on-disk form) loads through a capability-scoped - // source; the single-file (zip) form falls back to the bytes path, as do all - // other formats. - if path.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case(photocraft_format::EXTENSION)) - && let Some(open) = app.services.automation_open_pcraft.as_mut() - { - match open(path) { - Ok(Some((name, doc))) => { - app.session.add_document(doc, None); - // Recent files, but no save-back target: the capability writer - // replaces files, never directories. - app.push_recent(path); - app.sync_views(); - app.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", &name)]); - app.ui.status_error = false; - return ok(json!({"path": path, "name": name, "warnings": []})); - } - Ok(None) => {} // a regular file: the bytes path reads the zip form - Err(e) => return err(e), - } - } - let opened = match app.services.automation_read.as_mut() { - Some(read) => read(path), - None => Err("automation read authority is not configured".into()), - }; - wrap(opened.and_then(|(name, bytes)| { - let name = app.open_name(&name); - let warnings = app.open_automation_bytes(&name, &bytes)?; - // Brushes/gradients go to the preset libraries: no document, no Open Recent entry. - if !crate::preset_files_ui::is_preset_file(&name) { - app.opened_from(path); - } - Ok(json!({"path": path, "name": name, "warnings": warnings})) - })) - } - None => err("missing `path`"), - }, - "app.save" => match crate::FormatChoices::from_params(p, "app.save") { - Ok(choices) => { - let path = s("path").map(str::to_string); - run_waiting(app, p.get("wait").and_then(Value::as_bool).unwrap_or(true), move |app| app.save_automation_with(path, choices)) - } - Err(e) => err(e), - }, - "app.quit" => { - app.allow_close = true; - ctx.send_viewport_cmd(egui::ViewportCommand::Close); - ok(Value::Null) - } - other => err(format!("unknown method `{other}`")), - } -} - -/// Snapshot of everything on screen, addressable by id. -pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { - let screen = ctx.content_rect(); - let mut dialogs: Vec = - app.ui.dialogs.iter().map(|d| json!({"id": d.id, "kind": d.kind, "title": crate::dialogs::title(d), "fields": d.fields})).collect(); - if let Some((kind, fields)) = &app.ui.shell.dialog { - dialogs.push(json!({"id": SHELL_DIALOG, "kind": kind, "title": crate::workspace_ui::title(kind), "fields": fields})); - } - dialogs.extend(crate::discard_ui::inspect(app)); - json!({ - "window": {"width": screen.width(), "height": screen.height(), "pixelsPerPoint": ctx.pixels_per_point()}, - "tool": app.ui.tool, - "toolOptions": app.ui.tool_options, - "perspectiveCrop": app.ui.perspective_crop, - "strokeEditor": app.ui.stroke_editor, - "magnetic": app.ui.magnetic, - "textEdit": app.ui.text_edit, - "typeTransform": app.ui.type_transform, - "camTransform": app.ui.cam_transform, - "layerMenu": app.ui.layer_menu, - "layerPicker": app.ui.layer_picker, - "brushPicker": app.ui.brush_picker.map(|pos| json!({ - "pos": pos, - // The picker's content size once its corner grip was dragged (null: the default). - "size": app.ui.brush_picker_size, - "list": { - "collapsed": app.ui.brush_picker_list.collapsed, - "filter": app.ui.brush_picker_list.filter, - "renaming": app.ui.brush_picker_list.renaming, - // The card's parts (`view` is the Brushes panel's listing and doesn't apply). - "showName": app.ui.brush_picker_list.show_name, - "showStroke": app.ui.brush_picker_list.show_stroke, - "showTip": app.ui.brush_picker_list.show_tip, - // The footer slider: the cards' width scale. - "scale": app.ui.brush_picker_list.scale, - }, - })), - "canvasToolMenu": app.ui.canvas_tool_menu.as_ref().map(|menu| { - json!({ - "pos": menu.pos, - "tool": menu.tool, - "pasteboard": menu.pasteboard, - "guide": menu.guide, - "crop": menu.crop.is_some(), - "entries": context_entries(app, menu) - }) - }), - "panels": app.ui.panels, - "dockTabs": app.ui.dock_tabs, - "dock": app.ui.dock, - "docking": app.ui.docking, - "dockingReturns": app.ui.docking_returns, - "dockingCollapsed": app.ui.docking_collapsed, - "view": app.ui.view, - "views": app.ui.views, - "dialogs": dialogs, - "windows": app.ui.windows, - "theme": app.ui.theme, - "status": app.ui.status, - "statusError": app.ui.status_error, - "notices": app.ui.notices, - "updatesOpen": app.ui.updates_open, - "updates": {"supported": app.session.updates.check.is_some(), "currentVersion": photocraft_engine::build_info::VERSION, "result": app.session.updates.status}, - "gpuFallbackNotice": app.ui.gpu_fallback_notice, - "kysOffer": app.ui.kys_offer, - "frame": app.frame, - "session": photocraft_engine::inspect::session(&app.session), - "document": app.session.active().map(photocraft_engine::inspect::document), - "perf": {"fps": app.fps, "timings": app.perf, "strokeTrace": app.stroke_trace.last}, - "brush": {"size": app.session.tools.brush.size, "hardness": app.session.tools.brush.hardness, "opacity": app.session.tools.brush.opacity}, - "distort": app.distort.describe(), - "jobs": crate::jobs_ui::inspect(app), - "histogram": crate::histogram_panel::inspect(app), - "cameraRaw": app.camera_raw.as_ref().map(|d| d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)), - }) -} - -pub fn save_screenshot(app: &mut PhotocraftApp, image: &egui::ColorImage, path: Option<&str>) -> Value { - let [w, h] = image.size; - let rgba: Vec = image.pixels.iter().flat_map(|c| c.to_array()).collect(); - save_screenshot_rgba(app, w, h, &rgba, path) -} - -/// Encode already-flattened RGBA pixels. The capture lifecycle uses this after dropping the -/// retained [`egui::ColorImage`], so the encoder's input copy and the retained image do not -/// overlap in memory (see `PhotocraftApp::finish_captures`). -pub fn save_screenshot_rgba(app: &mut PhotocraftApp, w: usize, h: usize, rgba: &[u8], path: Option<&str>) -> Value { - let png = match app.services.encode_png.as_ref() { - Some(enc) => enc(w as u32, h as u32, rgba), - None => Err("no PNG encoder configured".into()), - }; - let Some(path) = path else { - return match png { - Ok(bytes) => json!({ - "ok": true, - "result": { - "base64": base64::engine::general_purpose::STANDARD.encode(bytes), - "mime": "image/png", - "width": w, - "height": h, - } - }), - Err(error) => json!({"ok": false, "error": error}), - }; - }; - let result = png.and_then(|bytes| match app.services.automation_write.as_mut() { - Some(write) => write(path, &bytes), - None => Err("automation write authority is not configured".into()), - }); - match result { - Ok(()) => json!({"ok": true, "result": {"path": path, "width": w, "height": h}}), - Err(e) => json!({"ok": false, "error": e}), - } -} - #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs new file mode 100644 index 0000000000..7057d35f55 --- /dev/null +++ b/crates/ui-egui/src/control/dispatch.rs @@ -0,0 +1,1005 @@ +use super::inspect::inspect; +use super::params::{ + BUTTONS, KEY_MODIFIERS, MAX_CLICKS, POINTER_MODIFIERS, UI_SET_FIELDS, bool_field, err, f32_field, f32_range, input_choice, input_modifiers, input_number, + input_object, merged_object, modifiers_from, num_field, ok, screen_point, uint_field, whole_object, +}; +use super::*; + +pub(super) fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome { + let p = &req.params; + let s = |k: &str| p.get(k).and_then(Value::as_str); + let u = |k: &str| p.get(k).and_then(Value::as_u64); + let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(true); + match req.method.as_str() { + "ui.context.choose" => { + let Some(id) = s("id") else { return err("missing `id`") }; + let Some(menu) = app.ui.canvas_tool_menu.as_ref() else { return err("no canvas context menu is open") }; + if !crate::canvas_tool_menu::available(app, menu, id) { + return err("context action is unavailable"); + } + // A pasteboard row changes a preference: the policy sees the `prefs.set` it runs. + let (command, params) = crate::canvas_tool_menu::engine_call(app, menu, id); + if let Some(authorize) = app.services.automation_command.as_ref() + && let Err(error) = authorize(&command, ¶ms) + { + return err(error); + } + crate::canvas_tool_menu::choose(app, ctx, id); + ok(json!({"command": id, "dialog": app.ui.dialogs.last().map(|d| d.id)})) + } + "engine.execute" | "ui.menu.invoke" => { + let Some(id) = s("command").or(s("id")) else { return err("missing `command`") }; + let params = p.get("params").cloned().unwrap_or(json!({})); + // A control-channel menu click must respect the same modal gate as the native menu. + // The documented `ui` requests of Camera Raw and the full-window workspaces operate + // the already-open one rather than click a menu. Only that continuation may pass its + // own modal gate. engine.execute is deliberately not subject to the UI's menu-click semantics. + let open_modal = if app.camera_raw.is_some() { Some("filter.cameraRaw") } else { crate::distort_ui::modal_workspace(app) }; + let continuation = open_modal == Some(id) + && params.as_object().is_some_and(|fields| fields.len() == 1 && fields.get("ui").is_some_and(Value::is_object)) + && app.ui.dialogs.is_empty() + && app.discard.is_none() + && !crate::crop_ui::blocks(app, id); + if req.method == "ui.menu.invoke" && !continuation && !crate::menus::modal_allows(app, id) { + return err("menu command is unavailable while a modal dialog is open"); + } + if let Some(authorize) = app.services.automation_command.as_ref() + && let Err(error) = authorize(id, ¶ms) + { + return err(error); + } + // `engine.execute` is programmatic: engine commands run directly with their default + // params and never open a dialog (an agent would otherwise get a modal instead of a + // result). `ui.menu.invoke` behaves like a menu click, so it may open the dialog. + if req.method == "engine.execute" && photocraft_engine::commands::find(id).is_some() { + return run_waiting(app, wait, |app| app.run(id, params)); + } + run_waiting(app, wait, |app| crate::menus::invoke(app, ctx, id, params)) + } + "engine.commands" => wrap(app.run("command.list", json!({}))), + // Background jobs (#210): running ones with progress, then the last few that ended. + "jobs.list" => wrap(app.session.execute("jobs.list", json!({})).map_err(|e| e.to_string())), + "jobs.cancel" => { + let all = p.get("job").is_none_or(Value::is_null); + match p.get("job").and_then(Value::as_u64) { + Some(j) if app.session.job(photocraft_engine::jobs::JobId(j)).is_some() => { + let cancelled = crate::jobs_ui::cancel(app, photocraft_engine::jobs::JobId(j)); + ok(json!({"cancelled": usize::from(cancelled)})) + } + Some(j) => err(format!("no running job {j}")), + None if all => { + let ids: Vec<_> = app.session.jobs().into_iter().map(|j| j.id).collect(); + let cancelled = ids.into_iter().filter(|j| crate::jobs_ui::cancel(app, *j)).count(); + ok(json!({"cancelled": cancelled})) + } + None => err("`job` must be a job id"), + } + } + "ui.menu.list" => { + // Report the same enablement the native menu shows, so a listed item is invokable. + let mut items = crate::menus::menu_items(app); + for item in &mut items { + item.enabled &= crate::menus::modal_allows(app, &item.id); + } + ok(serde_json::to_value(items).unwrap_or_default()) + } + "ui.inspect" => ok(inspect(app, ctx)), + "ui.set" => { + if let Some(field) = p.as_object().and_then(|o| o.keys().find(|k| !UI_SET_FIELDS.contains(&k.as_str()))) { + return err(format!("unknown field `{field}` (fields: {})", UI_SET_FIELDS.join(", "))); + } + let gradient_blend = if let Some(value) = p.get("gradientBlendMode") { + let Some(name) = value.as_str() else { return err("gradientBlendMode must be a blend mode name") }; + let Some(mode) = photocraft_engine::commands::blend_from_str(name).filter(|m| photocraft_color::BlendMode::LAYER_MODES.contains(m)) else { + return err(format!("unknown gradient blend mode `{name}`")); + }; + Some(mode) + } else { + None + }; + // Everything is validated and materialized before the first field is applied, so a + // rejected call applies none of its fields (#412's guarantee, down to the values + // and nested keys). + let applied = (|| -> std::result::Result { + let shape_stroke = match p.get("shapeStroke") { + Some(v) => { + if let Some(object) = v.as_object() { + let keys = ["width", "opacity", "align", "cap", "join", "miterLimit", "dashes", "dashOffset"]; + if let Some(key) = object.keys().find(|key| !keys.contains(&key.as_str())) { + return Err(format!("unknown shapeStroke field `{key}`")); + } + } + let o = &app.ui.tool_options; + let base = o.shape_stroke.stroke(o.stroke_width, photocraft_doc::Fill::Solid(photocraft_doc::Color::BLACK)); + Some(photocraft_engine::vector_cmds::parse_stroke(v, Some(base), photocraft_doc::Color::BLACK)?) + } + None => None, + }; + let tool = match s("tool") { + Some(t) => Tool::from_name(t).map(Some).ok_or_else(|| format!("unknown tool `{t}`"))?, + None => None, + }; + let gradient_classic = bool_field(p, "gradientClassic")?; + // The stroke latency trace (`stroke_trace`), at runtime: on (stderr) or off. A CSV + // file is only for the user's own launch (`--stroke-trace `): a path over the + // control channel would write outside the automation write root. + let stroke_trace = match p.get("strokeTrace") { + None | Some(Value::Null) => None, + Some(Value::Bool(b)) => Some(if *b { "stderr" } else { "off" }), + Some(Value::String(v)) => match v.trim() { + "stderr" | "on" | "true" => Some("stderr"), + "off" | "false" => Some("off"), + _ => return Err("strokeTrace must be true, false, \"stderr\" or \"off\"; a CSV file is set at launch (--stroke-trace )".into()), + }, + Some(_) => return Err("strokeTrace must be true, false, \"stderr\" or \"off\"".into()), + }; + // The Eyedropper's options bar (#1649): Sample Size, Sample, Show Sampling Ring. + let eyedropper_size = match p.get("eyedropperSampleSize") { + Some(v) => Some( + photocraft_engine::sample_cmds::size_param("ui.set", &json!({"size": v})) + .map_err(|_| format!("eyedropperSampleSize must be \"point\" or one of {:?}", photocraft_engine::sample_cmds::SAMPLE_SIZES))?, + ), + None => None, + }; + let eyedropper_sample = match p.get("eyedropperSample") { + Some(v) => { + let ids: Vec<&str> = photocraft_engine::sample_cmds::SampleLayers::ALL.iter().map(|(_, n)| *n).collect(); + let id = v.as_str().filter(|id| ids.contains(id)).ok_or_else(|| format!("eyedropperSample must be one of {}", ids.join(", ")))?; + Some(id.to_string()) + } + None => None, + }; + let eyedropper_ring = bool_field(p, "eyedropperRing")?; + // Content-Aware Move's Transform On Drop checkbox. + let cam_transform_on_drop = bool_field(p, "camTransformOnDrop")?; + // Developer overlay of the active layer's storage tiles (tile_overlay.rs). + let tile_grid = bool_field(p, "tileGrid")?; + let layer_filter = p.get("layerFilter").map(|v| crate::layer_filter_ui::patched(&app.ui, v)).transpose()?; + // The Crop tool's overlay menu (#1919). + let crop_overlay = match p.get("cropOverlay") { + Some(v) => Some(v.as_str().and_then(crate::crop_overlay::CropOverlay::from_id).ok_or_else(|| { + let ids: Vec<&str> = crate::crop_overlay::CropOverlay::ALL.iter().map(|k| k.id()).collect(); + format!("cropOverlay must be one of {}", ids.join(", ")) + })?), + None => None, + }; + let crop_overlay_show = match p.get("cropOverlayShow") { + Some(v) => Some( + v.as_str() + .and_then(crate::crop_overlay::OverlayShow::from_id) + .ok_or_else(|| "cropOverlayShow must be one of auto, always, never".to_string())?, + ), + None => None, + }; + let crop_overlay_orientation = match uint_field(p, "cropOverlayOrientation")? { + Some(o) if o < 4 => Some(o as u8), + Some(_) => return Err("cropOverlayOrientation must be 0, 1, 2 or 3".into()), + None => None, + }; + // The Crop tool's Fill (#3823): "background" (Background (Default)) or "contentAware". + let crop_content_aware = match p.get("cropFill") { + Some(v) => Some(match v.as_str() { + Some("background") => false, + Some("contentAware") => true, + _ => return Err("cropFill must be \"background\" or \"contentAware\"".into()), + }), + None => None, + }; + // The Crop tool's gear menu: Show Cropped Area and the shield (#1919). + let crop_shield = merged_object(&app.ui.tool_options.crop_shield, p.get("cropShield"), "cropShield")?; + if crop_shield.as_ref().is_some_and(|s| !(0.0..=100.0).contains(&s.opacity)) { + return Err("cropShield.opacity must be 0..100".into()); + } + // The Histogram panel: its options, the dragged tonal range ([from, to] levels or + // null) and Uncached Refresh. + let histogram_panel = merged_object(&app.ui.histogram_panel, p.get("histogramPanel"), "histogramPanel")?; + let histogram_range = match p.get("histogramRange") { + Some(v) => Some( + serde_json::from_value::>(v.clone()) + .map_err(|_| "histogramRange must be [from, to] levels 0..255, or null".to_string())?, + ), + None => None, + }; + let histogram_refresh = bool_field(p, "histogramRefresh")?; + let panels = merged_object(&app.ui.panels, p.get("panels"), "panels")?; + let mask_target = bool_field(p, "maskTarget")?; + let updates_open = bool_field(p, "updatesOpen")?; + let vector_mask_target = bool_field(p, "vectorMaskTarget")?; + // Target the active smart object's filter mask (FILE-215-3): it needs smart filters. + let filter_mask_target = bool_field(p, "filterMaskTarget")?; + if filter_mask_target == Some(true) { + let st = app.session.active().ok_or("filterMaskTarget needs an open document")?; + let l = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or("filterMaskTarget needs an active layer")?; + if !matches!(&l.content, photocraft_doc::LayerContent::Smart(sm) if !sm.smart_filters.is_empty()) { + return Err("filterMaskTarget needs an active smart object with smart filters".into()); + } + use photocraft_engine::channel_cmds::ChannelTarget; + let composite = matches!(st.channel_view.target, ChannelTarget::Composite | ChannelTarget::LayerMask | ChannelTarget::VectorMask); + if !composite || st.doc.quick_mask.is_some() { + return Err("filterMaskTarget can't be set while a single channel or Quick Mask is targeted".into()); + } + } + let selection_mode = uint_field(p, "selectionMode")?; + let dock_tabs = merged_object(&app.ui.dock_tabs, p.get("dockTabs"), "dockTabs")?; + let dock = whole_object(&app.ui.dock, p.get("dock"), "dock")?; + // Which chip the Color panel edits. + let color_panel = merged_object(&app.ui.color_panel, p.get("colorPanel"), "colorPanel")?; + let dock_width = f32_field(p, "dockWidth")?; + let zoom = f32_field(p, "zoom")?; + let rotation = f32_field(p, "rotation")?; + if rotation.is_some() && app.session.active_index().is_none() { + return Err("no document open".into()); + } + let center = match p.get("center") { + Some(v) => { + let a = v.as_array().ok_or_else(|| "center must be [x, y]".to_string())?; + if a.len() != 2 { + return Err("center must be exactly [x, y]".into()); + } + let (Some(x), Some(y)) = (a.first().and_then(Value::as_f64), a.get(1).and_then(Value::as_f64)) else { + return Err("center must be [x, y] of two numbers".into()); + }; + if !f32_range(&x) || !f32_range(&y) { + return Err("center must be finite numbers within f32 range".into()); + } + Some([x as f32, y as f32]) + } + None => None, + }; + let fit = bool_field(p, "fit")? == Some(true); + let theme = match s("theme") { + Some(name) => { + let kind = crate::theme::ThemeKind::from_name(name).ok_or_else(|| { + let names: Vec<_> = crate::theme::ThemeKind::ALL.iter().map(|k| k.id()).collect(); + format!("unknown theme `{name}` ({})", names.join(", ")) + })?; + Some(kind) + } + None => None, + }; + let brush_section = uint_field(p, "brushSection")?; + let brush_tab = uint_field(p, "brushTab")?; + let brushes_view = match p.get("brushesView") { + Some(v) => serde_json::from_value(v.clone()).map(Some).map_err(|e| format!("brushesView: {e} (list, grid)"))?, + None => None, + }; + // The three parts of the picker's cards. At least one stays on (a rejected call + // leaves them all alone). + let brush_picker_name = bool_field(p, "brushPickerName")?; + let brush_picker_stroke = bool_field(p, "brushPickerStroke")?; + let brush_picker_tip = bool_field(p, "brushPickerTip")?; + if [brush_picker_name, brush_picker_stroke, brush_picker_tip].iter().any(Option::is_some) { + let on = [ + brush_picker_name.unwrap_or(app.ui.brush_picker_list.show_name), + brush_picker_stroke.unwrap_or(app.ui.brush_picker_list.show_stroke), + brush_picker_tip.unwrap_or(app.ui.brush_picker_list.show_tip), + ]; + if !on.iter().any(|b| *b) { + return Err("brushPickerName, brushPickerStroke and brushPickerTip: at least one must stay on".into()); + } + } + // The picker footer slider: the preset cards' size scale (1 standard; 0.30 and + // below the tips drop their size numbers). + let brush_picker_scale = match num_field(p, "brushPickerScale")? { + Some(s) if !(0.15..=2.0).contains(&s) => return Err("brushPickerScale must be between 0.15 and 2".into()), + Some(s) => Some(s as f32), + None => None, + }; + // `Some(None)` is an explicit null, which closes the picker (a missing field + // leaves it alone). + let brush_picker = match p.get("brushPicker") { + Some(v) => { + let at = serde_json::from_value::>(v.clone()) + .map_err(|_| "brushPicker must be [x, y] in screen points, or null to close it".to_string())?; + if at.is_some_and(|[x, y]| !x.is_finite() || !y.is_finite()) { + return Err("brushPicker must be [x, y] in screen points, or null to close it".into()); + } + Some(at) + } + None => None, + }; + // brushSize rides the journaled `tools.setBrush` command (#744). Numeric values + // are validated here so the command cannot fail after other fields were + // applied; non-numeric values keep the API's historical silent no-op. + let brush_size: Option = match p.get("brushSize").and_then(Value::as_f64) { + Some(size) => { + if !size.is_finite() || size > f64::from(photocraft_paint::MAX_BRUSH_SIZE) { + return Err(format!("brushSize must be finite and at most {} px", photocraft_paint::MAX_BRUSH_SIZE)); + } + Some(size) + } + None => None, + }; + + let bridge_pro = matches!(theme.unwrap_or(app.ui.theme), crate::theme::ThemeKind::Pro | crate::theme::ThemeKind::ProMedium); + let legacy_update = crate::panel_docking::prepare_legacy_update(app, p, panels.as_ref(), dock_tabs.as_ref(), dock.as_ref(), bridge_pro)?; + + // Apply (nothing below can fail). + if let Some(stroke) = shape_stroke { + if let Some(stroke) = stroke { + app.ui.tool_options.stroke_width = stroke.width; + app.ui.tool_options.shape_stroke = crate::shape_stroke_ui::StrokeOptions::from(&stroke); + } else { + app.ui.tool_options.stroke_width = 0.0; + } + } + if let Some(t) = tool { + crate::tool_memory::select(app, t); + // Each tool keeps its own brush (#218), so switch it in before `brushSize` + // below sets the new tool's size. + crate::paint_mouse::sync_tool_brush(app); + } + let gradient_before = app.ui.tool_options.clone(); + if let Some(mode) = gradient_blend { + app.ui.tool_options.gradient_blend_mode = mode; + } + if let Some(v) = &stroke_trace { + app.stroke_trace.set(v); + } + if let Some(classic) = gradient_classic { + app.ui.tool_options.gradient_classic = classic; + } + if gradient_blend.is_some() { + crate::gradient_ui::options_changed(app, &gradient_before); + } + if let Some(size) = eyedropper_size { + app.ui.tool_options.eyedropper_size = size; + } + if let Some(id) = eyedropper_sample { + app.ui.tool_options.eyedropper_sample = id; + } + if let Some(ring) = eyedropper_ring { + app.ui.tool_options.eyedropper_ring = ring; + } + if let Some(on) = cam_transform_on_drop { + app.ui.tool_options.cam_transform_on_drop = on; + } + if let Some(on) = tile_grid { + app.ui.view.tile_grid = on; + } + if let Some(f) = layer_filter { + crate::layer_filter_ui::apply(&mut app.ui, f); + } + if let Some(h) = histogram_panel { + app.ui.histogram_panel = h; + crate::histogram_panel::persist_options(app); + } + if let Some(r) = histogram_range { + app.ui.histogram_range = r; + } + if histogram_refresh == Some(true) { + crate::histogram_panel::uncached_refresh(app); + } + if let Some(k) = crop_overlay { + app.ui.tool_options.crop_overlay = k; + } + if let Some(on) = crop_content_aware { + app.ui.tool_options.crop_content_aware = on; + } + if let Some(v) = crop_overlay_show { + app.ui.tool_options.crop_overlay_show = v; + } + if let Some(o) = crop_overlay_orientation { + app.ui.tool_options.crop_overlay_orientation = o; + } + if let Some(s) = crop_shield { + app.ui.tool_options.crop_shield = s; + } + if let Some(v) = panels { + app.ui.panels = v; + } + if let Some(m) = mask_target { + app.end_filter_mask_view(); + app.ui.filter_mask_target = None; + app.ui.mask_target = m; + app.ui.properties_layer = None; + app.ui.vector_mask_target &= !m; + app.sync_mask_targets(); + } + if let Some(open) = updates_open { + app.ui.updates_open = open; + } + if let Some(m) = vector_mask_target { + app.end_filter_mask_view(); + app.ui.filter_mask_target = None; + app.ui.vector_mask_target = m; + app.ui.mask_target &= !m; + app.sync_mask_targets(); + } + if let Some(m) = filter_mask_target { + let layer = if m { app.session.active().and_then(|st| st.active_layer).map(|id| id.0) } else { None }; + app.select_filter_mask_target(layer); + } + // Selection tools' options-bar mode: 0 New, 1 Add, 2 Subtract, 3 Intersect. + if let Some(m) = selection_mode { + app.ui.selection_mode = m.min(3) as u8; + } + if let Some(k) = theme { + app.set_theme(ctx, k); + } + if let Some(v) = dock_tabs { + app.ui.dock_tabs = v; + } + // Dock group order, heights and collapsed groups (see `dock::DockLayout`). + if let Some(v) = dock { + app.ui.dock = v; + } + if let Some(update) = legacy_update { + crate::panel_docking::commit_legacy_update(app, update, p); + } + if let Some(v) = color_panel { + app.ui.color_panel = v; + } + // Right dock width in points (clamped to the dock's 250..=520 range), applied next frame. + if let Some(w) = dock_width { + crate::panels::request_dock_width(ctx, w as f32); + } + if let Some(i) = app.session.active_index() { + if zoom.is_some() || center.is_some() || rotation.is_some() || fit { + app.ui.views[i].zoom_animating = false; + app.ui.views[i].zoom_anchor = None; + } + if let Some(z) = zoom { + let size = app.session.documents().get(i).map_or([0, 0], |st| [st.doc.size.width, st.doc.size.height]); + app.ui.views[i].zoom = crate::zoom_levels::clamp(z as f32, size); + app.ui.views[i].fit_pending = false; + app.ui.views[i].fill_pending = false; + } + if let Some(c) = center { + app.ui.views[i].center = c; + app.ui.views[i].fit_pending = false; + app.ui.views[i].fill_pending = false; + } + if fit { + app.ui.views[i].fit_pending = true; + app.ui.views[i].fill_pending = false; + } + if let Some(r) = rotation { + app.ui.views[i].rotation = crate::rotate_view::wrap_deg(r as f32); + } + } + if let Some(i) = brush_section { + app.ui.brush_section = (i as usize).min(crate::brush_panel::SECTIONS.len() - 1); + } + if let Some(i) = brush_tab { + app.ui.brush_tab = (i as usize).min(1); + } + if let Some(v) = brushes_view { + app.ui.brushes_panel.view = v; + } + if let Some(v) = brush_picker_name { + app.ui.brush_picker_list.show_name = v; + } + if let Some(v) = brush_picker_stroke { + app.ui.brush_picker_list.show_stroke = v; + } + if let Some(v) = brush_picker_tip { + app.ui.brush_picker_list.show_tip = v; + } + if let Some(v) = brush_picker_scale { + app.ui.brush_picker_list.scale = v; + } + if let Some(at) = brush_picker { + app.ui.brush_picker = at; + } + // Which chip the Color panel edits. + if let Some(c) = color_panel { + app.ui.color_panel = c; + } + if let Some(size) = brush_size { + app.run("tools.setBrush", json!({"brush": {"size": size}})).map_err(|e| e.to_string())?; + } + Ok(Value::Null) + })(); + wrap(applied) + } + "ui.dialog.open" => { + let kind = match s("kind").unwrap_or("") { + "newDocument" | "NewDocument" => DialogKind::NewDocument, + "about" | "About" => DialogKind::About, + "layerStyle" | "LayerStyle" => { + return match crate::layer_style::open(app, s("effect")) { + Some(id) => ok(json!({"dialog": id})), + None => err("no active layer"), + }; + } + "colorPicker" | "ColorPicker" => { + if let Some(style) = p.get("textStyle") { + if ["parent", "effect", "field", "target"].iter().any(|key| p.get(*key).is_some()) { + return err("textStyle cannot be combined with another picker target"); + } + let Some(style) = style.as_object().filter(|s| s.keys().all(|k| k == "kind" || k == "id")) else { + return err("textStyle needs kind and id only"); + }; + let Some(kind) = style.get("kind").cloned().and_then(|v| serde_json::from_value::(v).ok()) + else { + return err("textStyle kind must be character or paragraph"); + }; + let Some(id) = style.get("id").and_then(Value::as_u64).and_then(|id| u32::try_from(id).ok()) else { + return err("textStyle id must be a u32 integer"); + }; + return match crate::type_panels_ui::color_picker::open(app, kind, id) { + Ok(id) => ok(json!({"dialog": id})), + Err(error) => err(error), + }; + } + if p.get("parent").is_some() { + let (Some(parent), Some(effect), Some(field)) = (u("parent"), s("effect"), s("field")) else { + return err("need integer `parent` and string `effect` and `field`"); + }; + return match crate::layer_style::color_picker::open(app, parent, effect, field) { + Ok(id) => ok(json!({"dialog": id})), + Err(error) => err(error), + }; + } + if p.get("effect").is_some() || p.get("field").is_some() { + return err("Layer Style color pickers need `parent`"); + } + let target = if s("target") == Some("background") { "background" } else { "foreground" }; + return ok(json!({"dialog": crate::color_picker_ui::open(app, target)})); + } + // The Crop tool's New / Delete Crop Preset… (#1919). + "newCropPreset" => { + return match crate::crop_presets::open_new(app) { + Some(id) => ok(json!({"dialog": id})), + None => err("nothing to save: set W and H (W x H x Resolution) or a ratio first"), + }; + } + "deleteCropPreset" => { + return match crate::crop_presets::open_delete(app) { + Some(id) => ok(json!({"dialog": id})), + None => err("no crop presets are saved"), + }; + } + "command" | "Command" => { + let Some(cmd) = s("command") else { return err("command dialogs need `command`") }; + let label = photocraft_engine::commands::find(cmd).map(|c| c.label).unwrap_or(cmd); + return ok(json!({"dialog": crate::dialogs::open_command_dialog(app, cmd, label)})); + } + other => return err(format!("unknown dialog kind `{other}`")), + }; + let mut fields = if kind == DialogKind::NewDocument { app.new_document_fields() } else { Default::default() }; + if let Some(f) = p.get("fields").and_then(Value::as_object) { + if let Some(marker) = f.keys().find(|k| crate::dialogs::is_route_marker(k)) { + return err(format!("`{marker}` is set only by the dialog it belongs to")); + } + fields.extend(f.clone()); + } + ok(json!({"dialog": app.ui.open_dialog(kind, fields)})) + } + // The shell's own dialog (Window › Workspace, View › Pixel Aspect Ratio › Custom, Show + // Extras Options, 32-bit Preview Options), listed by ui.inspect with the id "shell". + "ui.dialog.set" if s("dialog") == Some(SHELL_DIALOG) => { + let Some(field) = s("field") else { return err("need `dialog` and `field`") }; + let value = p.get("value").cloned().unwrap_or(Value::Null); + match app.ui.shell.dialog.as_mut() { + Some((_, fields)) => { + fields.insert(field.to_string(), value); + ok(Value::Null) + } + None => err("no shell dialog is open"), + } + } + "ui.dialog.confirm" if s("dialog") == Some(SHELL_DIALOG) => { + let Some((kind, fields)) = app.ui.shell.dialog.clone() else { return err("no shell dialog is open") }; + if let Some((command, params)) = crate::workspace_ui::dialog_command(&kind, &fields) + && let Some(authorize) = app.services.automation_command.as_ref() + && let Err(error) = authorize(command, ¶ms) + { + return err(error); + } + wrap(crate::workspace_ui::confirm(app, ctx)) + } + "ui.dialog.apply" if s("dialog") == Some(SHELL_DIALOG) => err("`ui.dialog.apply` is for Preferences; use `ui.dialog.confirm`"), + // The unsaved-changes prompt (closing, Revert, quitting), listed by ui.inspect with the + // id "discard" (#4920): confirm takes a `choice` (save, dontSave, cancel; default save). + "ui.dialog.confirm" if s("dialog") == Some(crate::discard_ui::CONTROL_ID) => { + let choice = s("choice").unwrap_or("save"); + if choice != "cancel" + && let Some((command, params)) = crate::discard_ui::pending_command(app) + && let Some(authorize) = app.services.automation_command.as_ref() + && let Err(error) = authorize(&command, ¶ms) + { + return err(error); + } + wrap(crate::discard_ui::answer_control(app, ctx, choice)) + } + "ui.dialog.cancel" if s("dialog") == Some(crate::discard_ui::CONTROL_ID) => wrap(crate::discard_ui::answer_control(app, ctx, "cancel")), + "ui.dialog.set" | "ui.dialog.apply" if s("dialog") == Some(crate::discard_ui::CONTROL_ID) => { + err("the unsaved-changes prompt has no fields; use `ui.dialog.confirm` with a `choice`") + } + "ui.dialog.cancel" if s("dialog") == Some(SHELL_DIALOG) => match app.ui.shell.dialog.take() { + Some(_) => ok(Value::Null), + None => err("no such dialog"), + }, + "ui.dialog.set" => { + let (Some(id), Some(field)) = (u("dialog"), s("field")) else { return err("need `dialog` and `field`") }; + let value = p.get("value").cloned().unwrap_or(Value::Null); + match app.ui.dialog_mut(id) { + // A continuation belongs to the dialog that paused it, even when another + // action has a valid token. Replacing it would resume or cancel that action. + Some(_) if field == crate::actions::RESUME => err("the paused action token is read-only"), + // A marker picks the handler OK runs: a dialog keeps the ones it was opened with. + Some(d) if !d.fields.contains_key(field) && crate::dialogs::is_route_marker(field) => { + err(format!("`{field}` is set only by the dialog it belongs to")) + } + Some(d) => { + d.fields.insert(field.to_string(), value); + ok(Value::Null) + } + None => err(format!("no dialog {id}")), + } + } + "ui.dialog.confirm" | "ui.dialog.apply" => match u("dialog") { + Some(id) => { + let command = app.ui.dialogs.iter().find(|dialog| dialog.id == id).and_then(|dialog| { + if req.method == "ui.dialog.apply" { + dialog.fields.get("values").map(|values| ("prefs.set".to_string(), json!({"path": "", "value": values}))) + } else { + dialog.fields.get("__command").and_then(Value::as_str).map(|command| (command.to_string(), Value::Object(dialog.fields.clone()))) + } + }); + if let Some((command, params)) = command + && let Some(authorize) = app.services.automation_command.as_ref() + && let Err(error) = authorize(&command, ¶ms) + { + return err(error); + } + let apply = req.method == "ui.dialog.apply"; + run_waiting(app, wait, |app| if apply { crate::prefs_ui::apply(app, id) } else { crate::dialogs::confirm(app, id) }) + } + None => err("missing `dialog`"), + }, + "ui.dialog.cancel" => match u("dialog") { + Some(id) => match crate::dialogs::cancel(app, id) { + Ok(value) => ok(value), + Err(error) => err(error), + }, + None => err("missing `dialog`"), + }, + "ui.window.open" => { + if let Some(d) = u("document") + && !app.session.set_active(d as usize) + { + return err(format!("no document {d}")); + } + wrap(crate::menus::invoke(app, ctx, "window.newWindowForDocument", json!({}))) + } + "ui.window.close" => { + let Some(id) = u("window") else { return err("missing `window`") }; + let before = app.ui.windows.len(); + app.ui.windows.retain(|w| w.id != id); + if app.ui.windows.len() < before { ok(Value::Null) } else { err(format!("no window {id}")) } + } + "ui.pointer" => { + // Every field and event is validated before the first event runs, so a rejected call + // changes nothing (#2449). + let parsed = (|| -> std::result::Result<_, String> { + let fields = ["events", "tool", "modifiers", "button", "shift", "alt", "command", "ctrl", "space"]; + let p = input_object(p, None, &fields)?; + let tool = match input_choice(&p, "tool", "tool", &[])? { + Some(t) => Some(Tool::from_name(t).ok_or_else(|| format!("unknown tool `{t}`"))?), + None => None, + }; + let button = input_choice(&p, "button", "button", &BUTTONS)?.unwrap_or("left").to_string(); + // Modifier flags may be top-level or grouped under "modifiers". + let m = input_modifiers(&p, &POINTER_MODIFIERS)?; + let Some(events) = p.get("events") else { return Err("missing `events`".into()) }; + let Some(events) = events.as_array() else { return Err("events must be an array".into()) }; + let mut parsed = Vec::with_capacity(events.len()); + for (i, e) in events.iter().enumerate() { + let name = format!("events[{i}]"); + let e = input_object(e, Some(&name), &["kind", "x", "y", "pressure", "tiltX", "tiltY", "rotation"])?; + let num = |k: &str, range| input_number(&e, k, &format!("{name}.{k}"), range); + let (x, y) = (num("x", None)?.unwrap_or(0.0), num("y", None)?.unwrap_or(0.0)); + let pr = num("pressure", Some((0.0, 1.0)))?.unwrap_or(1.0) as f32; + let ev = match input_choice(&e, "kind", &format!("{name}.kind"), &["down", "move", "up"])?.unwrap_or("move") { + "down" => ToolEvent::Down { x, y, pressure: pr }, + "up" => ToolEvent::Up { x, y }, + _ => ToolEvent::Move { x, y, pressure: pr }, + }; + let tilt = |k: &str, range| num(k, Some(range)).map(|v| v.map(|v| v as f32)); + let pen = (tilt("tiltX", (-90.0, 90.0))?, tilt("tiltY", (-90.0, 90.0))?, tilt("rotation", (0.0, 360.0))?); + parsed.push((ev, x, y, pr, pen)); + } + Ok((tool, button, m, parsed)) + })(); + let (tool, button, m, events) = match parsed { + Ok(parsed) => parsed, + Err(e) => return err(e), + }; + let secondary = matches!(button.as_str(), "secondary" | "right"); + let mods = modifiers_from(&m); + if let Some(t) = tool { + crate::tool_memory::select(app, t); + } + // Space held: the Crop tool moves the frame being drawn, a marquee, lasso or shape + // being drawn moves instead of growing (hold_keys.rs). Like a modifier flag, it may be + // top-level or grouped under "modifiers". + let space = p.get("modifiers").unwrap_or(p).get("space").and_then(Value::as_bool).unwrap_or(false); + crate::crop_ui::set_space(app, space); + for (ev, x, y, pr, pen) in events { + // With the Color Picker on top the image is its eyedropper, as for the mouse. + if crate::color_picker_ui::top(app).is_some() { + if !matches!(ev, ToolEvent::Up { .. }) { + crate::color_picker_ui::sample_at(app, x, y); + } + continue; + } + // Curves' modal eyedroppers use document coordinates here, matching the native + // canvas path after its ViewXform conversion. Sample on press only. + if !secondary && crate::adjust_dialog::picker_armed(app) { + if matches!(ev, ToolEvent::Down { .. }) { + crate::adjust_dialog::sample_at(app, x, y); + } + continue; + } + // ⌘/Ctrl-click with Curves open adds a point at the pixel's tone, on press only (#7325). + if !secondary && !space && button != "middle" && mods.command && crate::adjust_dialog::curves_on_top(app) { + if matches!(ev, ToolEvent::Down { .. }) { + crate::adjust_dialog::add_point_at(app, ctx, x, y, mods.shift); + } + continue; + } + // A Properties Levels/Curves eyedropper owns the primary button the same way. + if app.ui.dialogs.is_empty() && !matches!(s("button"), Some("secondary" | "right")) && crate::layer_picker::armed(app).is_some() { + if matches!(ev, ToolEvent::Down { .. }) { + crate::layer_picker::sample_at(app, x, y); + } + continue; + } + // The dialog owns all pointer events, including Up: no underlying brush stroke + // or context menu may leak through while inspecting a Color Range preview. + if app.ui.dialogs.last().is_some_and(|d| crate::color_range_ui::owns(&d.fields)) { + let down = matches!(ev, ToolEvent::Down { .. }); + let up = matches!(ev, ToolEvent::Up { .. }); + let held = app.ui.dialogs.last().and_then(|d| d.fields.get("__pointerDown")).and_then(Value::as_bool).unwrap_or(false); + if let Some(d) = app.ui.dialogs.last_mut() { + d.fields.insert("__pointerDown".into(), json!(!up && (down || held))); + } + if !up && (down || held) && !space && !secondary && button != "middle" { + crate::color_range_ui::pick_top(app, [x, y], mods); + } + continue; + } + if secondary { + let down = matches!(ev, ToolEvent::Down { .. }); + // Right-click while transforming: the box's menu, as on the canvas. + if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none()) { + if down { + crate::canvas_tool_menu::open_transform(app, ctx, screen_point(app, x, y)); + } + continue; + } + // Right-click with the Move tool, or ⌘/Ctrl+right-click: list the layers there. + if crate::layer_pick_ui::is_gesture(app.ui.tool, mods) { + if down { + app.ui.canvas_tool_menu = None; + crate::layer_pick_ui::open(app, ctx, screen_point(app, x, y), x, y); + } + continue; + } + // No menu over the agent's own crop frame or Straighten line still being + // dragged, also the first one on the default frame (nothing pending yet). + if app.ui.tool == crate::state::Tool::Crop && (app.crop.drag.is_some() || app.crop.straighten.line.is_some()) { + continue; + } + if app.ui.tool == crate::state::Tool::Crop && crate::crop_ui::pending(app) { + if down { + crate::canvas_tool_menu::open_crop(app, ctx, app.ui.tool, screen_point(app, x, y)); + } + continue; + } + if crate::canvas_tool_menu::pasteboard_at(app, app.ui.tool, [x, y]) { + if down { + crate::canvas_tool_menu::open_pasteboard(app, ctx, app.ui.tool, screen_point(app, x, y)); + } + continue; + } + if crate::canvas_tool_menu::is_view_tool(app.ui.tool) { + if down { + crate::canvas_tool_menu::open_view(app, ctx, app.ui.tool, screen_point(app, x, y), [x, y]); + } + continue; + } + if crate::canvas_tool_menu::applies(app.ui.tool) + || crate::canvas_tool_menu::editing_text(app, app.ui.tool) + || crate::canvas_tool_menu::type_layer_at(app, app.ui.tool, [x, y]).is_some() + { + if down { + crate::canvas_tool_menu::open_at(app, ctx, app.ui.tool, screen_point(app, x, y), Some([x, y])); + } + continue; + } + if !crate::paint_mouse::pointer_secondary(app, ctx, down, mods, screen_point(app, x, y)) { + continue; + } + } + // A simulated pen: tilt/rotation reach the stroke like a real stylus's (see `stylus`). + if pen != (None, None, None) { + let (tilt_x, tilt_y, rotation) = (pen.0.unwrap_or(0.0), pen.1.unwrap_or(0.0), pen.2.unwrap_or(0.0)); + app.stylus.feed.set(Some(crate::stylus::PenSample { pressure: pr, tilt_x, tilt_y, rotation, eraser: false })); + } + if let Some(d) = app.drag.as_mut().filter(|d| crate::hold_keys::repositions(d.tool)) { + d.reposition = space; + } + // A Crop drag in the default mode turns and pans the view with the image: its + // points are read as the view showed them at the press (`crop_mode`). + let ev = match ev { + ToolEvent::Move { x, y, pressure } => { + let [x, y] = crate::crop_mode::control_point(app, [x, y]); + ToolEvent::Move { x, y, pressure } + } + ToolEvent::Up { x, y } => { + let [x, y] = crate::crop_mode::control_point(app, [x, y]); + ToolEvent::Up { x, y } + } + down => down, + }; + tool_event(app, ev, mods); + } + app.stylus.feed.set(None); + ok(json!({"status": app.ui.status})) + } + "ui.click" | "ui.move" => { + let click = req.method == "ui.click"; + let fields: &[&str] = if click { &["x", "y", "button", "count"] } else { &["x", "y"] }; + let parsed = (|| -> std::result::Result<_, String> { + let p = input_object(p, None, fields)?; + // Screen coordinates in points (as reported by ui.inspect window size). + let x = input_number(&p, "x", "x", None)?.unwrap_or(0.0) as f32; + let y = input_number(&p, "y", "y", None)?.unwrap_or(0.0) as f32; + let button = match input_choice(&p, "button", "button", &BUTTONS)?.unwrap_or("left") { + "right" | "secondary" => egui::PointerButton::Secondary, + "middle" => egui::PointerButton::Middle, + _ => egui::PointerButton::Primary, + }; + let clicks = if click { uint_field(&p, "count")?.unwrap_or(1) } else { 0 }; + if clicks > MAX_CLICKS { + return Err(format!("`count` must be at most {MAX_CLICKS} (got {clicks})")); + } + Ok((egui::pos2(x, y), button, clicks)) + })(); + let (pos, button, clicks) = match parsed { + Ok(parsed) => parsed, + Err(e) => return err(e), + }; + app.synthetic.push(egui::Event::PointerMoved(pos)); + for _ in 0..clicks { + app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: true, modifiers: Default::default() }); + app.synthetic.push(egui::Event::PointerButton { pos, button, pressed: false, modifiers: Default::default() }); + } + ctx.request_repaint(); + Outcome::AfterInput + } + "ui.key" => { + let parsed = (|| -> std::result::Result<_, String> { + let p = input_object(p, None, &["key", "modifiers", "shift", "alt", "command", "ctrl"])?; + let Some(name) = input_choice(&p, "key", "key", &[])? else { return Err("missing `key`".into()) }; + let key = egui::Key::from_name(name).ok_or_else(|| format!("unknown key `{name}`"))?; + // Modifier flags may be top-level or grouped under "modifiers". + Ok((key, input_modifiers(&p, &KEY_MODIFIERS)?)) + })(); + let (key, m) = match parsed { + Ok(parsed) => parsed, + Err(e) => return err(e), + }; + let modifiers = modifiers_from(&m); + app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }); + app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }); + ctx.request_repaint(); + Outcome::AfterInput + } + "ui.type" => { + let Some(text) = s("text") else { return err("missing `text`") }; + app.synthetic.push(egui::Event::Text(text.to_string())); + ctx.request_repaint(); + Outcome::AfterInput + } + "ui.resize" => { + let (w, h) = (p.get("width").and_then(Value::as_f64).unwrap_or(1280.0), p.get("height").and_then(Value::as_f64).unwrap_or(800.0)); + ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(w as f32, h as f32))); + ok(Value::Null) + } + "ui.gpu.simulateLoss" => { + if p.get("destroy").and_then(Value::as_bool).unwrap_or(false) { + let destroyed = app.destroy_window_device(); + ctx.request_repaint(); + return ok(json!({"destroyed": destroyed})); + } + let error = p.get("error").and_then(Value::as_bool).unwrap_or(false); + let fault = if error { + photocraft_gpu::Fault::Error("simulated error (ui.gpu.simulateLoss)".into()) + } else { + photocraft_gpu::Fault::Lost("simulated (ui.gpu.simulateLoss)".into()) + }; + let active = match app.gpu_health() { + Some(h) => { + h.mark(fault); + true + } + None => false, + }; + app.check_gpu(ctx); + ctx.request_repaint(); + ok(json!({"wasActive": active, "gpuInfo": app.perf.gpu_info})) + } + "ui.focus" => { + ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true)); + ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + ctx.request_repaint(); + ok(Value::Null) + } + "ui.screenshot" => { + let parsed = input_object(p, None, &["path", "focus"]) + .and_then(|p| Ok((input_choice(&p, "path", "path", &[])?.map(str::to_string), bool_field(&p, "focus")?))); + let (path, focus) = match parsed { + Ok(parsed) => parsed, + Err(e) => return err(e), + }; + // Occluded windows don't render on macOS, so the screenshot would never arrive: raise first. + if focus.unwrap_or(true) { + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + } + // The capture itself is admitted by `PhotocraftApp::drain_control` (budget and + // geometry) and issued from a later `App::ui` pass once open/close animations + // (modals, popups) have settled (see `screenshot.rs`). + let token = app.ui.alloc_id(); + ctx.request_repaint(); + Outcome::Screenshot { token, path } + } + "app.open" => match s("path") { + Some(path) => { + // Directory .pcraft (the native on-disk form) loads through a capability-scoped + // source; the single-file (zip) form falls back to the bytes path, as do all + // other formats. + if path.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case(photocraft_format::EXTENSION)) + && let Some(open) = app.services.automation_open_pcraft.as_mut() + { + match open(path) { + Ok(Some((name, doc))) => { + app.session.add_document(doc, None); + // Recent files, but no save-back target: the capability writer + // replaces files, never directories. + app.push_recent(path); + app.sync_views(); + app.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", &name)]); + app.ui.status_error = false; + return ok(json!({"path": path, "name": name, "warnings": []})); + } + Ok(None) => {} // a regular file: the bytes path reads the zip form + Err(e) => return err(e), + } + } + let opened = match app.services.automation_read.as_mut() { + Some(read) => read(path), + None => Err("automation read authority is not configured".into()), + }; + wrap(opened.and_then(|(name, bytes)| { + let name = app.open_name(&name); + let warnings = app.open_automation_bytes(&name, &bytes)?; + // Brushes/gradients go to the preset libraries: no document, no Open Recent entry. + if !crate::preset_files_ui::is_preset_file(&name) { + app.opened_from(path); + } + Ok(json!({"path": path, "name": name, "warnings": warnings})) + })) + } + None => err("missing `path`"), + }, + "app.save" => match crate::FormatChoices::from_params(p, "app.save") { + Ok(choices) => { + let path = s("path").map(str::to_string); + run_waiting(app, p.get("wait").and_then(Value::as_bool).unwrap_or(true), move |app| app.save_automation_with(path, choices)) + } + Err(e) => err(e), + }, + "app.quit" => { + app.allow_close = true; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + ok(Value::Null) + } + other => err(format!("unknown method `{other}`")), + } +} diff --git a/crates/ui-egui/src/control/inspect.rs b/crates/ui-egui/src/control/inspect.rs new file mode 100644 index 0000000000..cae7b358cb --- /dev/null +++ b/crates/ui-egui/src/control/inspect.rs @@ -0,0 +1,136 @@ +use super::*; + +/// The open canvas context menu's rows for `ui.state`: the spelling suggestions first (type edit +/// menu over a misspelled word), then the menu's own rows. +fn context_entries(app: &PhotocraftApp, menu: &crate::canvas_tool_menu::CanvasToolMenu) -> Vec { + use crate::canvas_tool_menu::{crop_rows, entry_enabled, rows, spelling_rows}; + let spelling = spelling_rows(menu); + let mut entries: Vec = spelling.iter().map(|(label, id)| json!({"label": label, "id": id, "enabled": entry_enabled(app, menu, id)})).collect(); + if !spelling.is_empty() { + entries.push(json!({"separator": true})); + } + entries.extend(crop_rows(menu).iter().map(|row| match row { + Some((label, id)) => json!({"label": label, "id": id, "enabled": entry_enabled(app, menu, id)}), + None => json!({"separator": true}), + })); + entries.extend(rows(menu).iter().map(|row| match row { + Some((label, id)) => json!({"label": label, "id": id, "enabled": entry_enabled(app, menu, id)}), + None => json!({"separator": true}), + })); + entries +} + +/// Snapshot of everything on screen, addressable by id. +pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { + let screen = ctx.content_rect(); + let mut dialogs: Vec = + app.ui.dialogs.iter().map(|d| json!({"id": d.id, "kind": d.kind, "title": crate::dialogs::title(d), "fields": d.fields})).collect(); + if let Some((kind, fields)) = &app.ui.shell.dialog { + dialogs.push(json!({"id": SHELL_DIALOG, "kind": kind, "title": crate::workspace_ui::title(kind), "fields": fields})); + } + dialogs.extend(crate::discard_ui::inspect(app)); + json!({ + "window": {"width": screen.width(), "height": screen.height(), "pixelsPerPoint": ctx.pixels_per_point()}, + "tool": app.ui.tool, + "toolOptions": app.ui.tool_options, + "perspectiveCrop": app.ui.perspective_crop, + "strokeEditor": app.ui.stroke_editor, + "magnetic": app.ui.magnetic, + "textEdit": app.ui.text_edit, + "typeTransform": app.ui.type_transform, + "camTransform": app.ui.cam_transform, + "layerMenu": app.ui.layer_menu, + "layerPicker": app.ui.layer_picker, + "brushPicker": app.ui.brush_picker.map(|pos| json!({ + "pos": pos, + // The picker's content size once its corner grip was dragged (null: the default). + "size": app.ui.brush_picker_size, + "list": { + "collapsed": app.ui.brush_picker_list.collapsed, + "filter": app.ui.brush_picker_list.filter, + "renaming": app.ui.brush_picker_list.renaming, + // The card's parts (`view` is the Brushes panel's listing and doesn't apply). + "showName": app.ui.brush_picker_list.show_name, + "showStroke": app.ui.brush_picker_list.show_stroke, + "showTip": app.ui.brush_picker_list.show_tip, + // The footer slider: the cards' width scale. + "scale": app.ui.brush_picker_list.scale, + }, + })), + "canvasToolMenu": app.ui.canvas_tool_menu.as_ref().map(|menu| { + json!({ + "pos": menu.pos, + "tool": menu.tool, + "pasteboard": menu.pasteboard, + "guide": menu.guide, + "crop": menu.crop.is_some(), + "entries": context_entries(app, menu) + }) + }), + "panels": app.ui.panels, + "dockTabs": app.ui.dock_tabs, + "dock": app.ui.dock, + "docking": app.ui.docking, + "dockingReturns": app.ui.docking_returns, + "dockingCollapsed": app.ui.docking_collapsed, + "view": app.ui.view, + "views": app.ui.views, + "dialogs": dialogs, + "windows": app.ui.windows, + "theme": app.ui.theme, + "status": app.ui.status, + "statusError": app.ui.status_error, + "notices": app.ui.notices, + "updatesOpen": app.ui.updates_open, + "updates": {"supported": app.session.updates.check.is_some(), "currentVersion": photocraft_engine::build_info::VERSION, "result": app.session.updates.status}, + "gpuFallbackNotice": app.ui.gpu_fallback_notice, + "kysOffer": app.ui.kys_offer, + "frame": app.frame, + "session": photocraft_engine::inspect::session(&app.session), + "document": app.session.active().map(photocraft_engine::inspect::document), + "perf": {"fps": app.fps, "timings": app.perf, "strokeTrace": app.stroke_trace.last}, + "brush": {"size": app.session.tools.brush.size, "hardness": app.session.tools.brush.hardness, "opacity": app.session.tools.brush.opacity}, + "distort": app.distort.describe(), + "jobs": crate::jobs_ui::inspect(app), + "histogram": crate::histogram_panel::inspect(app), + "cameraRaw": app.camera_raw.as_ref().map(|d| d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)), + }) +} + +pub fn save_screenshot(app: &mut PhotocraftApp, image: &egui::ColorImage, path: Option<&str>) -> Value { + let [w, h] = image.size; + let rgba: Vec = image.pixels.iter().flat_map(|c| c.to_array()).collect(); + save_screenshot_rgba(app, w, h, &rgba, path) +} + +/// Encode already-flattened RGBA pixels. The capture lifecycle uses this after dropping the +/// retained [`egui::ColorImage`], so the encoder's input copy and the retained image do not +/// overlap in memory (see `PhotocraftApp::finish_captures`). +pub fn save_screenshot_rgba(app: &mut PhotocraftApp, w: usize, h: usize, rgba: &[u8], path: Option<&str>) -> Value { + let png = match app.services.encode_png.as_ref() { + Some(enc) => enc(w as u32, h as u32, rgba), + None => Err("no PNG encoder configured".into()), + }; + let Some(path) = path else { + return match png { + Ok(bytes) => json!({ + "ok": true, + "result": { + "base64": base64::engine::general_purpose::STANDARD.encode(bytes), + "mime": "image/png", + "width": w, + "height": h, + } + }), + Err(error) => json!({"ok": false, "error": error}), + }; + }; + let result = png.and_then(|bytes| match app.services.automation_write.as_mut() { + Some(write) => write(path, &bytes), + None => Err("automation write authority is not configured".into()), + }); + match result { + Ok(()) => json!({"ok": true, "result": {"path": path, "width": w, "height": h}}), + Err(e) => json!({"ok": false, "error": e}), + } +} diff --git a/crates/ui-egui/src/control/params.rs b/crates/ui-egui/src/control/params.rs new file mode 100644 index 0000000000..0d9fbd6a49 --- /dev/null +++ b/crates/ui-egui/src/control/params.rs @@ -0,0 +1,234 @@ +use super::*; + +/// The fields `ui.set` reads. Anything else is rejected before a field is applied, and every +/// field's value is validated before the first one is applied, so a typo, an unknown field, a +/// bad value or a bad nested key can't reply with success while nothing — or only half of it — +/// changed (#412). +pub const UI_SET_FIELDS: [&str; 43] = [ + "updatesOpen", + "tool", + "strokeTrace", + "panels", + "dock", + "dockTabs", + "dockWidth", + "colorPanel", + "maskTarget", + "vectorMaskTarget", + "filterMaskTarget", + "selectionMode", + "zoom", + "center", + "rotation", + "fit", + "theme", + "brushSection", + "brushTab", + "brushesView", + "brushPicker", + "brushPickerName", + "brushPickerStroke", + "brushPickerTip", + "brushPickerScale", + "brushSize", + "gradientBlendMode", + "gradientClassic", + "eyedropperSampleSize", + "eyedropperSample", + "eyedropperRing", + "cropOverlay", + "cropOverlayShow", + "cropOverlayOrientation", + "cropShield", + "cropFill", + "shapeStroke", + "camTransformOnDrop", + "tileGrid", + "layerFilter", + "histogramPanel", + "histogramRange", + "histogramRefresh", +]; + +/// Most clicks one `ui.click` may queue (#982). Each click is a press and a release that the app +/// feeds in its own frame before replying, so `count` sizes both the input queue and the wait; +/// the same ceiling as the steps of one batch request. +pub const MAX_CLICKS: u64 = 256; + +pub(super) fn ok(v: Value) -> Outcome { + Outcome::Done(json!({"ok": true, "result": v})) +} + +pub(super) fn err(e: impl std::fmt::Display) -> Outcome { + Outcome::Done(json!({"ok": false, "error": e.to_string()})) +} + +/// A `ui.set` boolean field: `Ok(None)` when absent, an error when present with another type. +pub(super) fn bool_field(p: &Value, key: &str) -> std::result::Result, String> { + match p.get(key) { + None => Ok(None), + Some(v) => v.as_bool().map(Some).ok_or_else(|| format!("{key} must be a boolean")), + } +} + +/// A `ui.set` integer field: `Ok(None)` when absent; whole-number floats (`12.0`, as UIs send +/// them) are accepted, anything else is an error. +pub(super) fn uint_field(p: &Value, key: &str) -> std::result::Result, String> { + match p.get(key) { + None => Ok(None), + Some(v) if v.is_u64() => Ok(v.as_u64()), + Some(v) => v.as_f64().filter(|f| f.fract() == 0.0 && *f >= 0.0).map(|f| Some(f as u64)).ok_or_else(|| format!("{key} must be a non-negative integer")), + } +} + +/// A `ui.set` numeric field: `Ok(None)` when absent, finite numbers only. +pub(super) fn num_field(p: &Value, key: &str) -> std::result::Result, String> { + match p.get(key) { + None => Ok(None), + Some(v) => v.as_f64().filter(|f| f.is_finite()).map(Some).ok_or_else(|| format!("{key} must be a finite number")), + } +} + +/// A finite number that stays finite as `f32` (1e39 would turn into inf and silently reset +/// rotation to 0° or zoom to 100%). +pub(super) fn f32_range(n: &f64) -> bool { + n.is_finite() && n.abs() <= f64::from(f32::MAX) +} + +/// A `ui.set` numeric field the view stores as `f32`: `Ok(None)` when absent, else within `f32` range. +pub(super) fn f32_field(p: &Value, key: &str) -> std::result::Result, String> { + match p.get(key) { + None => Ok(None), + Some(v) => v.as_f64().filter(f32_range).map(Some).ok_or_else(|| format!("{key} must be a finite number within f32 range")), + } +} + +/// A `ui.set` object field merged into the current state (e.g. `panels`): the patch's keys are +/// merged into the serialized current value and parsed back, so a non-object value or an +/// unknown nested key is an error — a nested typo must not reply ok while changing nothing. +pub(super) fn merged_object( + current: &T, + patch: Option<&Value>, + field: &str, +) -> std::result::Result, String> { + let Some(patch) = patch else { return Ok(None) }; + let Some(patch) = patch.as_object() else { return Err(format!("{field} must be an object")) }; + let mut cur = serde_json::to_value(current).map_err(|e| e.to_string())?; + let known: std::collections::HashSet = cur.as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default(); + for (k, v) in patch { + if !known.contains(k) { + return Err(format!("unknown {field} field `{k}`")); + } + if let Some(c) = cur.as_object_mut() { + c.insert(k.clone(), v.clone()); + } + } + serde_json::from_value(cur).map(Some).map_err(|e| format!("{field}: {e}")) +} + +/// A `ui.set` object field applied by whole-value replacement (e.g. `dock`): +/// unknown nested keys are rejected like [`merged_object`] does, but the value replaces the +/// state instead of merging into it. +pub(super) fn whole_object( + current: &T, + v: Option<&Value>, + field: &str, +) -> std::result::Result, String> { + let Some(v) = v else { return Ok(None) }; + let Some(patch) = v.as_object() else { return Err(format!("{field} must be an object")) }; + let cur = serde_json::to_value(current).map_err(|e| e.to_string())?; + let known: std::collections::HashSet<&str> = cur.as_object().map(|o| o.keys().map(String::as_str).collect()).unwrap_or_default(); + for k in patch.keys() { + if !known.contains(k.as_str()) { + return Err(format!("unknown {field} field `{k}`")); + } + } + serde_json::from_value(v.clone()).map(Some).map_err(|e| format!("{field}: {e}")) +} + +/// The buttons `ui.pointer` and `ui.click` accept (`right` and `secondary` are the same one). +pub(super) const BUTTONS: [&str; 4] = ["left", "right", "secondary", "middle"]; + +/// The modifier flags `ui.key` reads, top-level or under `modifiers`; `ui.pointer` adds `space`. +pub(super) const KEY_MODIFIERS: [&str; 4] = ["shift", "alt", "command", "ctrl"]; + +pub(super) const POINTER_MODIFIERS: [&str; 5] = ["shift", "alt", "command", "ctrl", "space"]; + +/// A synthetic input method's params (or one nested object, named `what`): an object whose keys +/// are all in `fields`, returned with its null fields dropped so they mean "omitted". A typo must +/// not reply ok after acting on a default (#2449), as `ui.set` already promises (#412). +pub(super) fn input_object(v: &Value, what: Option<&str>, fields: &[&str]) -> std::result::Result { + let object = match (v, what) { + (Value::Null, None) => return Ok(json!({})), + (Value::Object(o), _) => o, + (_, what) => return Err(format!("{} must be an object", what.unwrap_or("params"))), + }; + if let Some(key) = object.keys().find(|k| !fields.contains(&k.as_str())) { + let field = what.map(|w| format!("{w} field")).unwrap_or_else(|| "field".into()); + return Err(format!("unknown {field} `{key}` (fields: {})", fields.join(", "))); + } + Ok(Value::Object(object.iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k.clone(), v.clone())).collect())) +} + +/// An optional finite number named `name` in errors, within `range` when given. +pub(super) fn input_number(v: &Value, key: &str, name: &str, range: Option<(f64, f64)>) -> std::result::Result, String> { + let n = num_field(v, key).map_err(|_| format!("{name} must be a finite number"))?; + match (n, range) { + (Some(n), Some((lo, hi))) if !(lo..=hi).contains(&n) => Err(format!("{name} must be between {lo} and {hi} (got {n})")), + _ => Ok(n), + } +} + +/// An optional string named `name` in errors, one of `accepted` when given. +pub(super) fn input_choice<'a>(v: &'a Value, key: &str, name: &str, accepted: &[&str]) -> std::result::Result, String> { + match v.get(key) { + None => Ok(None), + Some(Value::String(s)) if accepted.is_empty() || accepted.contains(&s.as_str()) => Ok(Some(s)), + Some(Value::String(s)) => Err(format!("unknown {name} `{s}` ({})", accepted.join(", "))), + Some(_) => Err(format!("{name} must be a string")), + } +} + +/// The modifier flags of `ui.pointer` / `ui.key`: grouped under `modifiers` when present (the +/// top-level flags are then ignored, but still type-checked), else top-level. +pub(super) fn input_modifiers(p: &Value, flags: &[&str]) -> std::result::Result { + for flag in flags { + bool_field(p, flag)?; + } + let Some(m) = p.get("modifiers") else { return Ok(p.clone()) }; + let m = input_object(m, Some("modifiers"), flags)?; + for flag in flags { + bool_field(&m, flag).map_err(|e| format!("modifiers.{e}"))?; + } + Ok(m) +} + +/// Screen position of document point (x, y) on the main canvas, where a `ui.pointer` right-click +/// opens its menu (the mouse's opens at the pointer); the canvas centre when it can't be mapped. +pub(super) fn screen_point(app: &PhotocraftApp, x: f64, y: f64) -> [f32; 2] { + let p = crate::canvas::ViewXform::active(app) + .map(|xf| xf.to_screen(x as f32, y as f32)) + .filter(|p| p.is_finite()) + .unwrap_or_else(|| app.last_canvas_rect.center()); + [p.x, p.y] +} + +/// Modifier flags of a request, top-level or grouped under `modifiers`. +/// +/// Off the Mac, Ctrl is the shortcut key, so egui wants `ctrl` and `command` to carry the same +/// value (`egui::Modifiers::command`: "On Windows and Linux, set this to the same value as +/// `ctrl`") and shortcuts are matched on `command`. A real Ctrl press arrives with both set, so +/// a request that sets only one of them gets both here and reaches the same shortcuts. On the Mac +/// they are different keys and stay apart: `command` is the ⌘ key, `ctrl` the Control key. +pub(super) fn modifiers_from(p: &Value) -> egui::Modifiers { + let m = p.get("modifiers").unwrap_or(p); + let flag = |k: &str| m.get(k).and_then(Value::as_bool).unwrap_or(false); + let (ctrl, command) = (flag("ctrl"), flag("command")); + egui::Modifiers { + shift: flag("shift"), + alt: flag("alt"), + command: if cfg!(target_os = "macos") { command } else { command || ctrl }, + mac_cmd: cfg!(target_os = "macos") && command, + ctrl: if cfg!(target_os = "macos") { ctrl } else { command || ctrl }, + } +} From f07a484fb73b21da22ff96eb30fb2a5d02fb88de Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 22:54:35 +0000 Subject: [PATCH 218/259] test(automation): read UI_SET_FIELDS from control/params.rs The ui-egui control.rs split moved the UI_SET_FIELDS declaration to control/params.rs; the MCP test reads it from source by path. --- crates/automation/tests/it/mcp.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/automation/tests/it/mcp.rs b/crates/automation/tests/it/mcp.rs index fe44d0be6b..0ac5c17a5f 100644 --- a/crates/automation/tests/it/mcp.rs +++ b/crates/automation/tests/it/mcp.rs @@ -273,12 +273,13 @@ async fn command_ids_in_tool_schemas_exist() { client.cancel().await.unwrap(); } -/// `UI_SET_FIELDS` in `crates/ui-egui/src/control.rs`, read from source. The desktop shell owns the +/// `UI_SET_FIELDS` in `crates/ui-egui/src/control/params.rs`, read from source. The desktop shell owns the /// list; this crate describes it over MCP without depending on the UI crate (both are L6). /// Anchored on the declaration, not on the doc comment that mentions it first, and checked against /// the declared array length so a mis-parse fails loudly instead of testing the wrong names. fn ui_set_fields() -> Vec { - let src = std::fs::read_to_string(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../ui-egui/src/control.rs")).expect("ui-egui control.rs"); + let src = + std::fs::read_to_string(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../ui-egui/src/control/params.rs")).expect("ui-egui control/params.rs"); let (_, rest) = src.split_once("UI_SET_FIELDS: [&str; ").expect("UI_SET_FIELDS is declared"); let declared: usize = rest.split_once(']').expect("declared length").0.parse().expect("declared length"); let body = rest.split_once('[').expect("field array").1.split_once("];").expect("terminated array").0; From 9900b7fba6a8f572bd72126ebb91dfdf949c4523 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:09:44 +0000 Subject: [PATCH 219/259] refactor(ui-egui): split menus.rs into menus/ --- crates/ui-egui/src/menus.rs | 1673 +--------------------------- crates/ui-egui/src/menus/bar.rs | 213 ++++ crates/ui-egui/src/menus/invoke.rs | 698 ++++++++++++ crates/ui-egui/src/menus/items.rs | 275 +++++ crates/ui-egui/src/menus/render.rs | 152 +++ crates/ui-egui/src/menus/search.rs | 98 ++ crates/ui-egui/src/menus/state.rs | 230 ++++ 7 files changed, 1691 insertions(+), 1648 deletions(-) create mode 100644 crates/ui-egui/src/menus/bar.rs create mode 100644 crates/ui-egui/src/menus/invoke.rs create mode 100644 crates/ui-egui/src/menus/items.rs create mode 100644 crates/ui-egui/src/menus/render.rs create mode 100644 crates/ui-egui/src/menus/search.rs create mode 100644 crates/ui-egui/src/menus/state.rs diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 3179a81422..84d607aeff 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -5,6 +5,31 @@ use serde_json::{Value, json}; use crate::PhotocraftApp; use crate::state::DialogKind; +mod bar; +mod invoke; +mod items; +mod render; +mod search; +mod state; + +#[cfg(test)] +use bar::pointer_reaches_title; +pub use bar::menu_bar; +pub use invoke::{apply_workspace, invoke}; +pub(crate) use invoke::{invoke_unguarded, panel_alias}; +pub use items::{is_live, menu_items, MenuItem}; +pub(crate) use items::ItemCache; +#[cfg(test)] +use render::submenu_enabled; +pub use render::alt_click; +#[cfg(test)] +use search::HELP_SEARCH_MAX; +pub use search::{search_items, search_rank}; +#[cfg(test)] +use state::{checked, translated_menu_label}; +pub use state::is_enabled; +pub(crate) use state::reveal_label; + /// Shared gate for native menu clicks and control-channel `ui.menu.invoke`. /// Dialogs and unsaved-changes prompts block edits, but allow the four view-navigation /// commands also usable through shortcuts. Camera Raw and the full-window workspaces @@ -29,1654 +54,6 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = photocraft_engin /// The id ends in the document's index, which is its tab's position. pub(crate) const DOCUMENT_ITEM: &str = "window.document."; -/// Photoshop's Window › ids for the panels the shell already has, as `window.toggle.*`. -pub(crate) fn panel_alias(id: &str) -> Option<&'static str> { - Some(match id.strip_prefix("window.panel.")? { - "layers" => "window.toggle.layers", - "history" => "window.toggle.history", - "properties" | "adjustments" => "window.toggle.properties", - "color" | "swatches" => "window.toggle.color", - "navigator" | "info" | "histogram" => "window.toggle.navigator", - "tools" => "window.toggle.toolbar", - "options" => "window.toggle.options", - "brushSettings" => "window.toggle.brushSettings", - "brushes" => "window.toggle.brushes", - _ => return None, - }) -} - -/// View › Proof Setup presets we can simulate, as `view.proofSetup` profiles. -fn proof_preset(id: &str) -> Option<&'static str> { - Some(match id.strip_prefix("view.proofSetup.")? { - "workingCmyk" => "working-cmyk", - "internetStandardRgb" | "monitorRgb" => "srgb", - _ => return None, - }) -} - -/// Window › Workspace presets by id. -fn workspace_name(id: &str) -> Option<&'static str> { - Some(match id.strip_prefix("window.workspace.")? { - "essentials" | "resetWorkspace" => "", - "photography" => "Photography", - "painting" => "Painting", - "graphicAndWeb" => "Graphic and Web", - "pixelArt" => "Pixel Art", - "motion" => "Motion", - _ => return None, - }) -} - -/// Run a command id from any source (menu, shortcut, palette, automation). -pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result { - if app.automation_input - && let Some(authorize) = app.services.automation_command.as_ref() - { - authorize(id, ¶ms)?; - } - if crate::discard_ui::intercept(app, id, ¶ms) { - return Ok(Value::Null); - } - let r = invoke_unguarded(app, ctx, id, params)?; - // The palette's empty-query list (UI-217-7); opening the palette isn't a command to recall. - if id != "edit.search" { - crate::palette::note_recent(ctx, id); - } - Ok(r) -} - -/// [`invoke`] without the unsaved-changes prompt, for once the user has already answered it. -pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result { - if let Some(tool) = crate::tool_shortcuts::tool(id) { - crate::tool_memory::select(app, tool); - return Ok(json!({"tool": tool})); - } - if id == "help.checkForUpdates" { - return crate::updates_ui::check(app, ctx, params); - } - if id == "ui.symmetryTransform" { - return crate::symmetry_ui::begin(app).map(|_| Value::Null); - } - if let Some(r) = crate::tool_reset::invoke(app, id, ¶ms) { - return r; - } - // A filter on a type layer asks to rasterize it first (#4303). - if let Some(r) = crate::rasterize_prompt::intercept_filter(app, id, ¶ms) { - return r; - } - // A pending Pen anchor is gesture state; Edit › Undo must match the keyboard. - if id == "edit.undo" && crate::vector_ui::pen_undo_last_point(app) { - return Ok(Value::Null); - } - // Image › Crop while the Crop tool has a pending frame commits that frame (#1918). - if id == "image.crop" && crate::crop_ui::pending(app) { - crate::canvas::commit_crop(app); - return Ok(json!({"committed": true})); - } - if let Some(result) = crate::panel_docking::command(app, id, ¶ms) { - return result; - } - // Help › Discord, website, GitHub, Report an Issue. - if let Some(url) = crate::links::url_for(id) { - return Ok(crate::links::open(app, ctx, url)); - } - if id == "view.proofSetup.custom" { - return Ok(json!({"dialog": crate::filter_dialog::open(app, "view.proofSetup")})); - } - // Image › Analysis tools/dialogs, Measurement Log and Notes panels, File › Import › Notes. - if let Some(r) = crate::analysis_ui::menu(app, id, ¶ms) { - return r; - } - // Workspace New/Delete/Lock, Modifier Keys, custom pixel aspect, Extras/32-bit options. - if let Some(r) = crate::workspace_ui::menu(app, id, ¶ms) { - return r; - } - // Window › Gradients, Patterns, Styles, Shapes, Tool Presets, Clone Source. - if let Some(r) = crate::preset_panels::menu(app, id, ¶ms) { - return r; - } - // Character/Paragraph Styles, Glyphs, Edit › Check Spelling dialog. - if let Some(r) = crate::type_panels_ui::menu(app, id, ¶ms) { - return r; - } - // Image > Variables (Define / Data Sets), Apply Data Set. - if let Some(r) = crate::variables_ui::menu(app, id, ¶ms) { - return r; - } - // Window > Timeline panel. - if let Some(r) = crate::timeline_ui::menu(app, id, ¶ms) { - return r; - } - // Filter › Plug-ins (installed WebAssembly plug-ins, Install Plug-in…). - if let Some(r) = crate::plugin_ui::menu(app, id, ¶ms) { - return r; - } - if id == "window.panel.brushSettings" { - app.ui.brush_tab = 0; - } - // View/Window/Type shell items, and dialogs/pickers in front of File commands. - // Edit › Preferences, Keyboard Shortcuts, Color Settings and other Edit dialogs. - if let Some(r) = crate::prefs_ui::invoke(app, ctx, id, ¶ms) { - return r; - } - // Save for Web's dialog would export the committed document, not the open Free Transform (#6737). - if id == crate::transform_tool::SAVE_FOR_WEB - && let Some(r) = crate::transform_tool::intercept(app, id) - { - return r; - } - // Save for Web, Print and the other File-menu dialogs added with slices. - if let Some(r) = crate::file_ui::invoke(app, ctx, id, ¶ms) { - return r; - } - if let Some(r) = crate::view_cmds::invoke(app, ctx, id, ¶ms) { - return r; - } - // Liquify dialog, Puppet Warp and Perspective Warp modes (and their control params). - if let Some(r) = crate::distort_ui::menu(app, ctx, id, ¶ms) { - return r; - } - // Camera Raw Filter dialog (and its control params). - if let Some(r) = crate::camera_raw_ui::menu(app, ctx, id, ¶ms) { - return r; - } - if let Some(r) = crate::wide_angle_ui::menu(app, ctx, id, ¶ms) { - return r; - } - if let Some(profile) = proof_preset(id) { - // View › Proof Setup presets: set the proof profile and turn Proof Colors on. - app.run("view.proofSetup", json!({"profile": profile}))?; - return app.run("view.proofColors", json!({"on": true})); - } - if let Some(alias) = panel_alias(id) { - return invoke(app, ctx, alias, params); - } - if let Some(ws) = workspace_name(id) { - // Reset re-applies the current workspace; Essentials is the default layout. - match (ws, id) { - (_, "window.workspace.resetWorkspace") => {} - ("", _) => app.ui.workspace = "Essentials".into(), - (name, _) => app.ui.workspace = name.into(), - } - apply_workspace(app); - return Ok(json!({"workspace": app.ui.workspace})); - } - match id { - // ⌘↩ / Ctrl+Enter (#306): load the path selected in the Paths panel (or the one being - // drawn) as a selection. - "path.toSelection" if params.get("name").is_none() => crate::vector_ui::path_to_selection(app, params), - // Layer › Rename Layer from a menu starts in-place renaming in the Layers panel. - "layer.renameLayer" if params.get("name").is_none() => { - let st = app.session.active().ok_or("no document")?; - let id = params.get("layer").and_then(Value::as_u64).or(st.active_layer.map(|l| l.0)).ok_or("no active layer")?; - let name = st.doc.layer(photocraft_doc::LayerId(id)).map(|l| l.name.clone()).ok_or("no such layer")?; - // Another rename in progress is committed first (#314). - if let Some((cmd, p)) = crate::layer_row_ui::start_rename(ctx, id, &name) { - app.run(&cmd, p)?; - } - Ok(Value::Null) - } - "layer.duplicate" if params.as_object().is_none_or(|o| o.is_empty()) => crate::duplicate_layer_ui::open(app), - "file.new" if params.as_object().is_none_or(|o| o.is_empty()) => { - let fields = app.new_document_fields(); - let d = app.ui.open_dialog(DialogKind::NewDocument, fields); - Ok(json!({"dialog": d})) - } - "file.open" => { - if let Some(path) = params.get("path").and_then(Value::as_str) { - open_path(app, path) - } else { - app.open_dialog_file() - } - } - "file.import.videoFramesToLayers" if params.get("path").and_then(Value::as_str).is_none() => { - app.ask_folder(|app, path| app.run("file.import.videoFramesToLayers", json!({"path": path})).map_err(|e| e.to_string())) - } - "file.save" => { - // Writes back only to a layered file that holds the whole document; anything else - // goes through Save As, so the original is never overwritten with less (#3806). - let choices = crate::FormatChoices::from_params(¶ms, id)?; - match params.get("path").and_then(Value::as_str) { - Some(path) => app.save_as_with(Some(path.to_string()), choices), - None => { - let own = app.session.active().and_then(|d| d.path.clone().map(|p| (photocraft_engine::file_cmds::holds_at(&d.doc, &p), p, d))); - match own { - Some((true, path, d)) => { - // Another app changed the file since it was opened or saved: ask first (#6596). - let doc = d.doc.id; - crate::disk_change_prompt::intercept(app, doc, &path, false, crate::FormatChoices::default()) - .unwrap_or_else(|| app.save_in_place(path, crate::FormatChoices::default())) - } - Some((false, path, d)) if photocraft_engine::file_cmds::saves_in_place(&path) => { - // Its own file is layered but can't hold what the document has now. - let losses = photocraft_engine::file_cmds::losses_at(&d.doc, &path); - let name = crate::file_open::display_name(&path); - let title = crate::i18n::fmt(tl!("{name} can't keep everything in this document"), &[("name", name.as_str())]); - let mut lines = losses; - lines.push(tl!("Choose a format that keeps it, such as Photoshop (PSD), or save a copy.").to_string()); - crate::notices::post(app, title, lines, false, None); - app.save_as_with(None, choices) - } - // A flat file asks for its name; confirming its own file records a - // plain Save that writes the file an action is played on (#3531). - _ => app.save_dialog_flow(None, choices, true), - } - } - } - } - "file.exit" => { - ctx.send_viewport_cmd(egui::ViewportCommand::Close); - Ok(Value::Null) - } - "file.clearRecent" => { - app.clear_recent(); - Ok(Value::Null) - } - "file.removeRecent" => { - let path = params.get("path").and_then(Value::as_str).ok_or("file.removeRecent needs a \"path\"")?; - app.remove_recent(path); - Ok(Value::Null) - } - id if id.starts_with("file.openRecent.") => { - #[cfg(not(target_arch = "wasm32"))] - { - match id.rsplit('.').next().and_then(|s| s.parse::().ok()).and_then(|i| app.ui.recent_files.get(i).cloned()) { - Some(p) => open_path(app, &p), - None => Err("no such recent file".to_string()), - } - } - #[cfg(target_arch = "wasm32")] - { - let _ = app; - let message = "Open Recent is unavailable on the web"; - Err(tl!(message).to_string()) - } - } - "file.saveAs" => { - let choices = crate::FormatChoices::from_params(¶ms, id)?; - app.save_as_with(params.get("path").and_then(Value::as_str).map(str::to_string), choices) - } - "view.zoomIn" | "view.zoomOut" | "view.fitOnScreen" | "view.actualPixels" => app.run(id, params), - "window.newWindowForDocument" => { - let doc = app.session.active_index().ok_or("no document")?; - let wid = app.ui.alloc_id(); - let view = app.ui.views[doc].clone(); - app.ui.windows.push(crate::state::DocWindow { id: wid, document: doc, view, open: true, position: None }); - Ok(json!({"window": wid})) - } - "window.theme.toggle" => { - crate::prefs_ui::cycle_appearance(app, ctx); - Ok(Value::Null) - } - "view.darkenInterface" | "view.lightenInterface" => { - crate::prefs_ui::step_brightness(app, ctx, id == "view.lightenInterface")?; - Ok(json!({"theme": app.ui.theme.id()})) - } - "window.theme.system" => { - app.run("prefs.set", json!({"path": "interface.appearanceMode", "value": "auto"}))?; - crate::prefs_ui::sync_appearance(app, ctx); - Ok(Value::Null) - } - "window.theme.pro" - | "window.theme.proMedium" - | "window.theme.proLightGray" - | "window.theme.proLight" - | "window.theme.studio" - | "window.theme.studioLight" - | "window.theme.classic" - | "window.theme.solarizedDark" - | "window.theme.adwaita" - | "window.theme.adwaitaDark" - | "window.theme.breezeLight" - | "window.theme.breezeDark" - | "window.theme.softLight" - | "window.theme.softDark" => { - let k = crate::theme::ThemeKind::from_name(&id["window.theme.".len()..]).unwrap_or_default(); - app.set_theme(ctx, k); - Ok(Value::Null) - } - // The macOS app menu's Language (`native_menu::language_node`). - i if i.starts_with(crate::native_menu::LANGUAGE_PREFIX) => { - let code = &i[crate::native_menu::LANGUAGE_PREFIX.len()..]; - if code != "auto" && !crate::i18n::Lang::all().any(|l| l.code() == code) { - return Err(format!("unknown UI language `{code}`")); - } - app.run("prefs.set", json!({"values": {"interface.language": code}})) - } - "edit.search" => { - app.ui.palette_open = !app.ui.palette_open; - Ok(Value::Null) - } - "help.about" => Ok(json!({"dialog": app.ui.open_dialog(DialogKind::About, Default::default())})), - "help.systemInfo" => { - let mut fields = serde_json::Map::new(); - fields.insert("systemInfo".into(), json!(true)); - let dialog = app.ui.open_dialog(DialogKind::About, fields); - Ok(json!({"dialog": dialog, "info": crate::gpu_status::system_info_json(app)})) - } - "file.export.exportAs" => Ok(json!({"dialog": crate::export_dialog::open(app)?})), - "file.export.quickExportAsPng" => crate::export_dialog::quick_export_png(app), - // Render Video exports a sequence of frames into a folder, not a named file. - // Keep explicit directory arguments from automation and the control channel unchanged. - "file.export.renderVideo" if params.get("dir").is_none() => { - #[cfg(target_arch = "wasm32")] - { - Err("Render Video to a local directory is unavailable on the web".into()) - } - #[cfg(not(target_arch = "wasm32"))] - { - let doc = app.session.active().ok_or("no document")?.doc.id; - let mut render_params = params.as_object().cloned().unwrap_or_default(); - app.ask_folder(move |app, dir| { - render_params.insert("dir".into(), json!(dir)); - app.with_document(doc, |app| app.run("file.export.renderVideo", Value::Object(render_params))) - }) - } - } - // Layer › Export As… / Quick Export as PNG: the export pipeline on just the active layer. - l if matches!(l, "layer.exportAs" | "layer.quickExportAsPng") && params.as_object().is_none_or(|o| o.is_empty()) => { - let layer = app.session.active().and_then(|d| d.active_layer).ok_or("no active layer")?; - if l == "layer.exportAs" { - // Several layers (artboards, say) selected: one file each (#3629). - let layers = app.session.active().map(|d| d.selected_layers()).unwrap_or_default(); - if layers.len() > 1 { - return Ok(json!({"dialog": crate::export_dialog::open_layers(app, &layers)?})); - } - Ok(json!({"dialog": crate::export_dialog::open_layer(app, layer)?})) - } else { - crate::export_dialog::quick_export_selected_layers_png(app) - } - } - "layer.smartFilter.blendingOptions" if params.get("blend").is_none() && params.get("opacity").is_none() => { - let st = app.session.active().ok_or("no document open")?; - let layer = params.get("layer").and_then(Value::as_u64).map(photocraft_doc::LayerId).or(st.active_layer).ok_or("no layer selected")?; - let Some(photocraft_doc::LayerContent::Smart(sm)) = st.doc.layer(layer).map(|l| &l.content) else { - return Err("the layer is not a Smart Object".into()); - }; - let index = match params.get("index") { - Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or("invalid Smart Filter index")?, - None => sm.smart_filters.len().checked_sub(1).ok_or("the Smart Object has no Smart Filters")?, - }; - crate::smart_filter_dialog::open(app, layer, index).map(|id| json!({"dialog": id})) - } - "layer.layerStyle.blendingOptions" if params.as_object().is_none_or(|o| o.is_empty()) => { - crate::layer_style::open(app, Some(crate::layer_style::BLENDING)).map(|d| json!({"dialog": d})).ok_or_else(|| "no active layer".to_string()) - } - // ⇧⌘> / ⇧⌘<: the selected characters while typing, else the whole type layer. - "type.increaseSize" | "type.decreaseSize" | "type.increaseSizeMore" | "type.decreaseSizeMore" if params.as_object().is_none_or(|o| o.is_empty()) => { - let p = crate::type_tool::with_target(app, json!({})).ok_or("the active layer is not a type layer")?; - app.run(id, p) - } - // Formatting menus follow an inline text selection when editing. Outside an edit, - // snapshot the selected type layers; explicit automation targets retain their scope. - t if (t.starts_with("type.antiAlias.") - || t.starts_with("type.orientation.") - || t.starts_with("type.openType.") - || matches!(t, "type.warpText" | "type.loadDefaultTypeStyles")) - && params.get("layer").is_none() - && params.get("layers").is_none() - && params.get("range").is_none() => - { - let Some(mut p) = crate::type_tool::formatting_params(app) else { return app.run(id, params) }; - if let Some(props) = params.as_object() { - for (key, value) in props { - p[key] = value.clone(); - } - } - app.run(id, p) - } - "type.editText" => { - crate::type_tool::edit_active(app)?; - if let Some(focus) = ctx.memory(|m| m.focused()) { - ctx.memory_mut(|m| m.surrender_focus(focus)); - } - Ok(Value::Null) - } - // Only interactive creation opens the Color Picker; it creates the layer on OK, - // so Cancel leaves neither an orphan layer nor an undo/redo history entry. - // Explicit parameters continue straight to the engine. - "layer.newFillLayer.solidColor" if params.as_object().is_none_or(|o| o.is_empty()) => { - let dialog = crate::solid_fill_ui::open_new(app).ok_or("no document is open")?; - Ok(json!({"dialog": dialog})) - } - // Solid Color fills and solid-colour shapes use the Color Picker, Pattern fills the Pattern - // Fill dialog; other adjustment / fill / shape controls use Properties. - "layer.layerContentOptions" => { - if let Some(dialog) = crate::solid_fill_ui::open(app).or_else(|| crate::shape_fill_ui::open(app)) { - return Ok(json!({"dialog": dialog})); - } - if let Some(dialog) = crate::pattern_fill_ui::open(app) { - return Ok(json!({"dialog": dialog})); - } - let r = app.run(id, params)?; - app.ui.panels.properties = true; - app.ui.dock_tabs.properties = 0; - Ok(r) - } - // Edit › Stroke…: open its full options dialog when called from menus/context - // menus. Explicit params from Actions, CLI, MCP and control channel execute directly. - crate::stroke_ui::COMMAND if params.as_object().is_none_or(|o| o.is_empty()) => { - if let Some(Err(why)) = photocraft_engine::commands::find(id).map(|c| (c.enabled)(&app.session)) { - return Err(why); - } - Ok(json!({"dialog": crate::stroke_ui::open(app)})) - } - // Channels › Channel Options… without params: the dialog on the targeted alpha/spot - // channel, Layer Mask Display Options on a targeted layer mask, or Quick Mask Options while - // in Quick Mask (with params: the engine directly). - crate::channel_options_ui::COMMAND if params.as_object().is_none_or(|o| o.is_empty()) => { - let mask = app.layer_mask_targeted(); - let st = app.session.active().ok_or("no document is open")?; - let channel = match st.channel_view.target { - _ if st.doc.quick_mask.is_some() => json!("quickMask"), - photocraft_engine::channel_cmds::ChannelTarget::Alpha(i) => json!(i), - _ if mask => json!("mask"), - _ => return Err("target an alpha or spot channel, or a layer mask, first".into()), - }; - let dialog = crate::channel_options_ui::open(app, &channel).ok_or("no such channel")?; - Ok(json!({"dialog": dialog})) - } - // Channels › New Spot Channel… without params: its dialog (with params: the engine). - crate::channel_options_ui::NEW_SPOT if params.as_object().is_none_or(|o| o.is_empty()) => { - let dialog = crate::channel_options_ui::open_new_spot(app).ok_or("no document is open")?; - Ok(json!({"dialog": dialog})) - } - // Photoshop's "Select and Mask…" is the engine's select.refineEdge. - // Select › Color Range… from the menu: the dialog (with params: the engine directly). - "select.colorRange" if params.as_object().is_none_or(|o| o.is_empty()) => Ok(json!({"dialog": crate::color_range_ui::open(app)})), - // Layer › New Fill Layer › Pattern… from the menu: the Pattern Fill dialog (with params: - // the engine directly). - photocraft_engine::pattern_fill_cmds::CREATE if params.as_object().is_none_or(|o| o.is_empty()) => { - Ok(json!({"dialog": crate::pattern_fill_ui::open_new(app)?})) - } - // Edit › Fill… from the menu or its shortcuts: the Fill dialog (with params: the engine). - crate::fill_ui::COMMAND if params.as_object().is_none_or(|o| o.is_empty()) => { - if let Some(Err(why)) = photocraft_engine::commands::find(id).map(|c| (c.enabled)(&app.session)) { - return Err(why); - } - Ok(json!({"dialog": crate::fill_ui::open(app)})) - } - "select.selectAndMask" => Ok(json!({"dialog": crate::filter_dialog::open(app, "select.refineEdge")})), - // Select › Transform Selection from the menu: the interactive box (with params: the engine). - "select.transformSelection" if params.as_object().is_none_or(|o| o.is_empty()) => { - crate::transform_tool::begin_selection(app, ctx).map(|_| json!({"transform": app.ui.transform})) - } - // While editing type, the clipboard rows and Select > All work on the text (#1355, #2893). - "edit.cut" if app.ui.text_edit.is_some() => { - crate::type_tool::cut_selection(app, ctx); - Ok(Value::Null) - } - "edit.copy" if app.ui.text_edit.is_some() => { - crate::type_tool::copy_selection(app, ctx); - Ok(Value::Null) - } - "edit.paste" if app.ui.text_edit.is_some() => { - crate::type_tool::request_paste(ctx); - Ok(Value::Null) - } - "select.all" if app.ui.text_edit.is_some() => { - crate::type_tool::select_all(app); - Ok(Value::Null) - } - "edit.paste" if params.as_object().is_none_or(|o| o.is_empty()) => { - // Photoshop: paste in place when the copied area is visible, else centred in the view; - // images from other apps are always centred. - app.import_os_clipboard()?; - app.clip_read_for_paste = true; - let external = app.clip_external; - let visible = !external - && app.session.active_index().zip(app.session.clipboard.as_ref()).is_some_and(|(i, clip)| { - let v = &app.ui.views[i]; - let pz = app.point_zoom(); - let (hw, hh) = (app.last_canvas_rect.width() / 2.0 / pz / app.ui.view.display_aspect(), app.last_canvas_rect.height() / 2.0 / pz); - let r = - photocraft_geom::Rect::new((v.center[0] - hw) as i32, (v.center[1] - hh) as i32, (v.center[0] + hw) as i32, (v.center[1] + hh) as i32); - !clip.bounds.intersect(&r).is_empty() - }); - let p = match app.session.active_index() { - Some(i) if !visible => json!({"center": app.ui.views[i].center}), - _ => json!({}), - }; - app.run("edit.paste", p) - } - "view.rulers" | "view.show.grid" | "view.show.guides" | "view.snap" | "view.lockGuides" => { - let e = &mut app.ui.extras; - let slot = match id { - "view.rulers" => &mut e.rulers, - "view.show.grid" => &mut e.grid, - "view.show.guides" => &mut e.guides, - "view.snap" => &mut e.snap, - _ => &mut e.lock_guides, - }; - *slot = !*slot; - let on = *slot; - if id == "view.show.grid" && on { - // Like the other Show items, enabling Grid also restores hidden Extras. - app.ui.view.extras = true; - } - if id == "view.rulers" { - crate::prefs_ui::remember_rulers(app, on); - } - Ok(json!(on)) - } - "edit.freeTransform" - | "edit.transform.scale" - | "edit.transform.rotate" - | "edit.transform.skew" - | "edit.transform.distort" - | "edit.transform.perspective" => { - // While a box is up, Scale / Rotate / Skew / Distort / Perspective (and Free Transform) - // switch its mode; otherwise they start one in that mode. - if app.ui.transform.as_ref().is_some_and(|t| t.content_aware.is_some()) { - return Err(crate::transform_tool::CAS_ONLY_SCALES.into()); - } - if app.ui.transform.is_none() { - crate::transform_tool::begin(app, ctx)?; - } - if let Some(t) = app.ui.transform.as_mut() { - t.mode = crate::state::TransformMode::for_command(id); - } - Ok(json!({"transform": app.ui.transform})) - } - "edit.freeTransformCopy" => crate::transform_tool::begin_copy(app, ctx).map(|_| json!({"transform": app.ui.transform})), - // Edit › Transform › Warp from the menu: interactive Warp mode (with params: the engine). - "edit.transform.warp" | "layer.smartObjects.warp" if params.as_object().is_none_or(|o| o.is_empty()) => { - crate::transform_tool::begin_warp(app, ctx).map(|_| json!({"transform": app.ui.transform})) - } - // Split warps edit the mesh of an active Warp session. - "edit.transform.splitWarpCrosswise" - | "edit.transform.splitWarpHorizontally" - | "edit.transform.splitWarpVertically" - | "edit.transform.removeWarpSplit" - if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_some()) && params.get("warp").is_none() => - { - let at = params.get("at").and_then(Value::as_array).and_then(|a| Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?])); - crate::transform_tool::split(app, id, at).map(|_| json!({"transform": app.ui.transform})) - } - "edit.transform.warpGrid" if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_some()) && params.get("warp").is_none() => { - crate::transform_tool::edit_session_warp(app, id, ¶ms).map(|_| json!({"transform": app.ui.transform})) - } - // Layer › New › Layer… (⇧⌘N) asks first, as in Photoshop; with params it runs as is. - crate::new_layer_ui::COMMAND if params.as_object().is_none_or(|o| o.is_empty()) => Ok(json!({"dialog": crate::new_layer_ui::open(app)?})), - sz if crate::sizing::is_sizing(sz) && params.as_object().is_none_or(|o| o.is_empty()) => { - Ok(json!({"dialog": crate::sizing::open(app, sz).ok_or("no document")?})) - } - "view.newGuide" if params.as_object().is_none_or(|o| o.is_empty()) => Ok(json!({"dialog": crate::new_guide_ui::open(app)})), - fl if crate::filter_dialog::has_dialog(fl) && params.as_object().is_none_or(|o| o.is_empty()) => { - Ok(json!({"dialog": crate::filter_dialog::open(app, fl)})) - } - a if crate::adjust_dialog::has_dialog(a) && params.as_object().is_none_or(|o| o.is_empty()) => { - Ok(json!({"dialog": crate::adjust_dialog::open(app, a).ok_or("no document")?})) - } - "window.togglePanels" => { - // Tab hides the Tools panel, the options bar and the dock; Tab again shows what it hid. - if app.ui.view.hides_chrome() { - // Full Screen Mode: Tab only shows or hides the chrome for now (#6760); the panels' - // own state, `hidden_by_tab` included, stays as it was before entering. - app.ui.panels.full_screen_chrome = !app.ui.panels.full_screen_chrome; - return Ok(Value::Null); - } - let p = &mut app.ui.panels; - match p.hidden_by_tab.take() { - Some([toolbar, options, dock]) if !(p.toolbar || p.options_bar || p.dock) => { - (p.toolbar, p.options_bar, p.dock) = (toolbar, options, dock); - } - _ if p.toolbar || p.options_bar || p.dock => { - p.hidden_by_tab = Some([p.toolbar, p.options_bar, p.dock]); - (p.toolbar, p.options_bar, p.dock) = (false, false, false); - } - _ => (p.toolbar, p.options_bar, p.dock) = (true, true, true), - } - Ok(Value::Null) - } - "window.nextDocument" | "window.previousDocument" => { - // Tabs are in document order, so the next tab is the next document, wrapping around. - let n = app.session.documents().len(); - let at = app.session.active_index().ok_or("no document open")?; - let to = if id == "window.nextDocument" { (at + 1) % n } else { (at + n - 1) % n }; - app.session.set_active(to); - app.jobs.focus = None; - Ok(json!({"document": to})) - } - id if let Some(index) = id.strip_prefix(DOCUMENT_ITEM) => { - let n = app.session.documents().len(); - let to = index.parse::().ok().filter(|i| *i < n).ok_or("no such document")?; - app.session.set_active(to); - app.jobs.focus = None; - Ok(json!({"document": to})) - } - t if t.starts_with("window.toggle.") => { - // A shown but collapsed dock group is expanded rather than hidden (#129). - if let Some(g) = crate::dock::Group::from_key(&t["window.toggle.".len()..]).filter(|g| g.shown(&app.ui.panels) && app.ui.dock.is_collapsed(*g)) { - crate::dock::reveal(app, g); - return Ok(Value::Null); - } - let p = &mut app.ui.panels; - let slot = match &t["window.toggle.".len()..] { - "layers" => &mut p.layers, - "history" => &mut p.history, - "properties" => &mut p.properties, - "color" => &mut p.color, - "navigator" => &mut p.navigator, - "toolbar" => &mut p.toolbar, - "options" => &mut p.options_bar, - "brushSettings" => &mut p.brush_settings, - "brushes" => &mut p.brushes, - "dock" => &mut p.dock, - _ => return Err(format!("unknown panel in {t}")), - }; - *slot = !*slot; - if let Some(g) = crate::dock::Group::from_key(&t["window.toggle.".len()..]).filter(|g| g.shown(&app.ui.panels)) { - crate::dock::reveal(app, g); - } - Ok(Value::Null) - } - // Layer › Layer Style › … opens the Layer Style dialog on that effect. - ls if params.as_object().is_none_or(|o| o.is_empty()) - && ls.strip_prefix("layer.layerStyle.").is_some_and(|k| crate::layer_style::KINDS.iter().any(|(kind, _)| *kind == k)) => - { - let kind = &ls["layer.layerStyle.".len()..]; - crate::layer_style::open(app, Some(kind)).map(|d| json!({"dialog": d})).ok_or_else(|| "no active layer".to_string()) - } - _ => app.run(id, params), - } -} - -fn open_path(app: &mut PhotocraftApp, path: &str) -> Result { - app.open_path(path).map(|w| json!({"warnings": w})) -} - -pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { - if crate::tool_shortcuts::tool(id).is_some() { - return true; - } - if id == "ui.symmetryTransform" { - return crate::symmetry_ui::can_transform(app); - } - // Draft Pen points can be undone even when the document has no History entries. - if id == "edit.undo" && app.ui.pen.as_ref().is_some_and(|pen| !pen.knots.is_empty()) { - return true; - } - // Photoshop greys these for the Background layer, other layer kinds or single-layer documents. - if crate::enable_rules::disabled(app, id) { - return false; - } - // A pending crop greys what Photoshop greys during one (#1918). - if crate::crop_ui::blocks(app, id) { - return false; - } - // Filters stay live on a type layer: choosing one asks to rasterize it (#4303). - if crate::rasterize_prompt::filter_needs(app, id).is_some() { - return true; - } - if let Some(e) = crate::workspace_ui::is_enabled(app, id) { - return e; - } - if crate::analysis_ui::handles(id) { - return true; - } - if crate::preset_panels::handles(id) || crate::type_panels_ui::handles(id) || crate::timeline_ui::handles(id) { - return true; - } - if let Some(e) = crate::view_cmds::is_enabled(app, id) { - return e; - } - if let Some(e) = crate::plugin_ui::is_enabled(app, id) { - return e; - } - if let Some(e) = crate::transform_tool::is_enabled(app, id) { - return e; - } - if let Some(e) = crate::crop_ui::is_enabled(app, id) { - return e; - } - match id { - "window.panel.activate" | "window.panel.layout" | "ui.dock" => true, - "window.panel.group" - | "window.panel.move" - | "window.panel.float" - | "window.panel.window" - | "window.panel.dock" - | "window.panel.close" - | "window.panel.closeGroup" - | "window.panel.closeOthers" - | "window.panel.minimize" - | "window.panel.iconic" => !app.session.prefs().workspace_locked, - "file.open" | "file.exit" | "file.clearRecent" | "file.removeRecent" | "help.about" | "help.systemInfo" | "edit.search" => true, - i if i.starts_with("file.openRecent.") => true, - i if i.starts_with(DOCUMENT_ITEM) => true, - i if crate::links::url_for(i).is_some() => true, - i if i.starts_with("window.theme.") => true, - // Interface brightness works with or without a document, as in Photoshop. - "view.darkenInterface" | "view.lightenInterface" => true, - "file.save" | "file.saveAs" | "file.export.exportAs" | "file.export.quickExportAsPng" => { - app.session.active().is_some() && app.services.export.is_some() - } - i if i.starts_with("window.toggle.") => true, - "window.togglePanels" => true, - // With one document open the key stays quiet, as in Photoshop, rather than reporting why. - "window.nextDocument" | "window.previousDocument" => app.session.active().is_some(), - i if panel_alias(i).is_some() || workspace_name(i).is_some() => true, - i if proof_preset(i).is_some() => app.session.active().is_some(), - // "Custom…" is the full Proof Setup dialog. - "view.proofSetup.custom" => app.session.active().is_some(), - "view.rulers" | "view.show.grid" | "view.show.guides" | "view.snap" | "view.lockGuides" => true, - "edit.cut" | "edit.copy" if app.ui.text_edit.is_some() => crate::type_tool::selected_range(app).is_some(), - "edit.paste" | "select.all" if app.ui.text_edit.is_some() => true, - // An image copied in another app can only be seen by reading the OS clipboard, which happens - // on an explicit paste: with a clipboard service these stay enabled. Paste and New from - // Clipboard need no document (with none open, Paste makes one); Paste in Place does. - "edit.paste" | "file.newFromClipboard" => app.session.is_enabled(id) || app.services.clipboard_get_image.is_some(), - "edit.pasteSpecial.pasteInPlace" => app.session.is_enabled(id) || (app.services.clipboard_get_image.is_some() && app.session.active().is_some()), - "select.selectAndMask" => app.session.is_enabled("select.refineEdge"), - "type.editText" => app - .session - .active() - .and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id))) - .is_some_and(|l| matches!(l.content, photocraft_doc::LayerContent::Text(_))), - "select.transformSelection" => app.ui.transform.is_none() && app.session.is_enabled("select.transformSelection"), - // ⇧[ / ⇧] only step the hardness of a tool that paints with the brush tip, as in Photoshop. - "tools.decreaseBrushHardness" | "tools.increaseBrushHardness" => app.ui.tool.is_brushlike(), - i if (i.starts_with("view.zoom") || i == "view.fitOnScreen" || i == "view.actualPixels") || i == "window.newWindowForDocument" => { - app.session.active().is_some() - } - "edit.freeTransformCopy" => app.ui.transform.is_none() && app.session.active().and_then(|s| s.active_layer).is_some(), - "edit.freeTransform" - | "edit.transform.scale" - | "edit.transform.rotate" - | "edit.transform.skew" - | "edit.transform.distort" - | "edit.transform.perspective" => match &app.ui.transform { - Some(t) => t.warp.is_none(), - None => app.session.active().and_then(|s| s.active_layer).is_some(), - }, - // A targeted layer mask enables what edits it (Invert on an adjustment layer's mask). - i => app.session.is_enabled_with(i, &app.with_mask_target(i, Value::Null)), - } -} - -/// Image › Mode items that carry a checkmark. -const MODE_CHECKS: [&str; 11] = ["rgb", "grayscale", "cmyk", "lab", "multichannel", "indexedColor", "bitmap", "duotone", "bits8", "bits16", "bits32"]; - -/// Is a UI-level panel toggle currently on (for checkmarks)? -fn checked(app: &PhotocraftApp, id: &str) -> Option { - if let Some(checked) = crate::panel_docking::checked(app, id) { - return Some(checked); - } - use photocraft_doc::{ColorMode, SampleType}; - if let Some(name) = id.strip_prefix("window.theme.").filter(|n| *n != "toggle") { - let auto = app.session.prefs().interface.appearance_mode == photocraft_engine::prefs::AppearanceMode::Auto; - return Some(if name == "system" { auto } else { !auto && crate::theme::ThemeKind::from_name(name) == Some(app.ui.theme) }); - } - if let Some(c) = crate::view_cmds::checked(app, id) { - return Some(c); - } - if let Some(c) = crate::analysis_ui::checked(app, id).or_else(|| crate::workspace_ui::checked(app, id)).or_else(|| crate::file_ui::checked(app, id)) { - return Some(c); - } - if let Some(c) = crate::preset_panels::checked(app, id) { - return Some(c); - } - if let Some(c) = crate::timeline_ui::checked(app, id) { - return Some(c); - } - if let Some(c) = crate::type_panels_ui::checked(app, id) { - return Some(c); - } - if let Some(alias) = panel_alias(id) { - return checked(app, alias); - } - // Check items stay check items with no document open (`Some(false)`, not `None`): a native - // menu can't change an item's kind in place, so a change would rebuild the whole menu. - if id == "select.isolateLayers" { - return Some(app.session.active().is_some_and(|d| !d.isolated_layers.is_empty())); - } - 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); - return Some(if id == "view.proofColors" { pv.enabled } else { pv.gamut_warning }); - } - if id.starts_with("window.workspace.") && id != "window.workspace.resetWorkspace" { - let want = workspace_name(id)?; - return Some(app.ui.workspace == if want.is_empty() { "Essentials" } else { want }); - } - if let Some(m) = id.strip_prefix("image.mode.") { - let Some(d) = app.session.active().map(|s| &s.doc) else { - return MODE_CHECKS.contains(&m).then_some(false); - }; - return match m { - "rgb" => Some(d.mode == ColorMode::Rgb), - "grayscale" => Some(d.mode == ColorMode::Grayscale), - "cmyk" => Some(d.mode == ColorMode::Cmyk), - "lab" => Some(d.mode == ColorMode::Lab), - "multichannel" => Some(d.mode == ColorMode::Multichannel), - "indexedColor" => Some(d.mode == ColorMode::Indexed), - "bitmap" => Some(d.mode == ColorMode::Bitmap), - "duotone" => Some(d.mode == ColorMode::Duotone), - "bits8" => Some(d.depth == SampleType::U8), - "bits16" => Some(d.depth == SampleType::U16), - "bits32" => Some(d.depth == SampleType::F32), - _ => None, - }; - } - let e = &app.ui.extras; - match id { - "view.rulers" => return Some(e.rulers), - "view.show.grid" => return Some(e.grid), - "view.show.guides" => return Some(e.guides), - "view.snap" => return Some(e.snap), - "view.lockGuides" => return Some(e.lock_guides), - _ => {} - } - let p = &app.ui.panels; - Some(match id { - "window.toggle.layers" => p.layers, - "window.toggle.history" => p.history, - "window.toggle.properties" => p.properties, - "window.toggle.color" => p.color, - "window.toggle.navigator" => p.navigator, - "window.toggle.toolbar" => p.toolbar, - "window.toggle.dock" => p.dock, - "window.togglePanels" => p.toolbar || p.options_bar || p.dock, - "window.toggle.options" => p.options_bar, - "window.toggle.brushSettings" => p.brush_settings, - "window.toggle.brushes" => p.brushes, - _ => return None, - }) -} - -/// "Reveal in Finder" named after the file manager the engine opens on this platform (UI-217-19): -/// Explorer on Windows, a plain folder elsewhere (xdg-open, the web). English action key; each -/// display translates it. -pub(crate) fn reveal_label() -> &'static str { - if cfg!(target_os = "macos") { - "Reveal in Finder" - } else if cfg!(windows) { - "Show in Explorer" - } else { - "Show in Folder" - } -} - -/// Translate the fixed command label and substitute the currently configured export format. -/// Reuse the existing translated PNG sentence, so dynamic formats work in every UI language. -fn translated_menu_label(lang: crate::i18n::Lang, item: &MenuItem) -> String { - // A document's name is shown as it is. - if item.id.starts_with(DOCUMENT_ITEM) { - return item.label.clone(); - } - if item.id == "file.export.quickExportAsPng" - && let Some(fmt) = item.label.strip_prefix("Quick Export as ") - { - return crate::i18n::tr_id(lang, &item.id, "Quick Export as PNG").replace("PNG", fmt); - } - crate::i18n::tr_id(lang, &item.id, &item.label).to_string() -} - -/// Menu tree entry for rendering and for `ui.inspect`. -#[derive(Clone, Debug, serde::Serialize)] -pub struct MenuItem { - pub id: String, - pub label: String, - pub path: Vec, - pub shortcut: Option, - pub enabled: bool, - pub checked: Option, - /// Edit › Menus colour (red, orange, …). - #[serde(skip_serializing_if = "Option::is_none")] - pub color: Option, -} - -/// Is `id` implemented by the engine or the shell (a live menu item)? Shared by the menus and -/// the parity report ([`crate::parity`]). -pub fn is_live(id: &str) -> bool { - static UI_IDS: std::sync::OnceLock> = std::sync::OnceLock::new(); - photocraft_engine::commands::find(id).is_some() - || crate::tool_shortcuts::tool(id).is_some() - || UI_IDS.get_or_init(|| UI_COMMANDS.iter().map(|c| c.0).collect()).contains(id) - || panel_alias(id).is_some() - || workspace_name(id).is_some() - || proof_preset(id).is_some() - || id == "view.proofSetup.custom" - || crate::view_cmds::handles(id) - || crate::analysis_ui::handles(id) - || crate::workspace_ui::handles(id) - || crate::preset_panels::handles(id) - || crate::type_panels_ui::handles(id) - || crate::timeline_ui::handles(id) -} - -/// Commands outside the catalogue that belong right after a catalogue item: `(id, after)`. -/// The command takes that item's submenu path, so it joins Photoshop's submenu even where the -/// catalogue spells it differently (Filter › "Other…"). -const PLACE_AFTER: &[(&str, &str)] = &[ - ("file.newFromClipboard", "file.new"), - ("filter.render.relight", "filter.render.lightingEffects"), - ("view.resetView", "view.flipHorizontal"), - ("filter.other.colorToAlpha", "filter.other.offset"), -]; - -pub fn menu_items(app: &PhotocraftApp) -> Vec { - // 1) Photoshop's full menu tree, in Photoshop order; live where we implement the command. - let known = is_live; - let mut items: Vec = crate::menu_catalog::CATALOG - .iter() - .map(|&(path, label, sc, id)| MenuItem { - id: id.to_string(), - label: label.to_string(), - path: path.iter().map(|s| s.to_string()).collect(), - // A live item shows the shortcut that runs it ([`crate::shortcut_dispatch::bindings`] - // prefers the command's own over the catalogue's): Undo ⌘Z, Copy ⌘C, Hide Layers ⌘,. - shortcut: if known(id) { crate::shortcuts::default_shortcut(id) } else { sc.map(Into::into) }, - enabled: known(id) && is_enabled(app, id), - checked: checked(app, id), - color: None, - }) - .collect(); - // 2) Our commands that Photoshop's tree doesn't list (or lists under another id). - let mut extra: Vec = Vec::new(); - for &(id, label, path, sc) in UI_COMMANDS { - extra.push(MenuItem { - id: id.into(), - label: label.into(), - path: path.iter().map(|s| s.to_string()).collect(), - shortcut: sc.map(Into::into), - enabled: is_enabled(app, id), - checked: checked(app, id), - color: None, - }); - } - for c in photocraft_engine::command_specs().iter().filter(|c| !c.menu.is_empty()) { - extra.push(MenuItem { - id: c.id.into(), - label: c.label.into(), - path: c.menu.iter().map(|s| s.to_string()).collect(), - shortcut: c.shortcut.map(Into::into), - enabled: is_enabled(app, c.id), - checked: None, - color: None, - }); - } - for mut e in extra { - let dup = items.iter().any(|i| i.id == e.id || (i.path == e.path && i.label.trim_end_matches('…') == e.label.trim_end_matches('…'))); - if !dup { - // Insert after the item it belongs next to, else after the last item of the same - // top-level menu, keeping menus contiguous. - let top = e.path.first().cloned(); - let after = PLACE_AFTER.iter().find(|(id, _)| *id == e.id).and_then(|(_, a)| items.iter().position(|i| i.id == *a)); - if let Some(path) = after.and_then(|a| items.get(a)).map(|i| i.path.clone()) { - e.path = path; - } - let at = after.or_else(|| items.iter().rposition(|i| i.path.first() == top.as_ref())).map_or(items.len(), |p| p + 1); - items.insert(at, e); - } - } - crate::plugin_ui::insert_menu_items(app, &mut items); - if let Some(mask) = app.session.active().and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id))).and_then(|l| l.mask.as_ref()) - && let Some(item) = items.iter_mut().find(|i| i.id == "layer.layerMask.enabled") - { - item.label = crate::layer_menu_ui::mask_toggle_label(mask.enabled).into(); - } - // Layer › Merge Layers reads Merge Group with just a group selected, as in Photoshop (#3832). - if let Some(st) = app.session.active() - && st.selected_layers().len() <= 1 - && st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| matches!(l.content, photocraft_doc::LayerContent::Group(_))) - && let Some(item) = items.iter_mut().find(|i| i.id == "layer.mergeLayers") - { - item.label = "Merge Group".into(); - } - // The File quick-export command uses the format selected in Export Preferences. - // On the web it intentionally downloads PNG until the quick-export service supports - // the other formats; the Layer quick-export command also always produces PNG. - if let Some(item) = items.iter_mut().find(|i| i.id == "file.export.quickExportAsPng") { - use photocraft_engine::prefs::QuickExportFormat; - let format = if cfg!(target_arch = "wasm32") { - "PNG" - } else { - match app.session.prefs().export.quick_export_format { - QuickExportFormat::Png => "PNG", - QuickExportFormat::Jpg => "JPG", - QuickExportFormat::Gif => "GIF", - QuickExportFormat::Webp => "WebP", - QuickExportFormat::Exr => "EXR", - } - }; - item.label = format!("Quick Export as {format}"); - } - // Smart Objects › Reveal in Finder names this platform's file manager (UI-217-19). - if let Some(item) = items.iter_mut().find(|i| i.id == "layer.smartObjects.revealInFinder") { - item.label = reveal_label().into(); - } - // File › Open Recent: a dynamic submenu of recently opened files (inserted after "Open As…"). - if let Some(after) = items.iter().position(|i| i.id == "file.openAs") { - let rp: Vec = vec!["File".into(), "Open Recent".into()]; - let mut recent: Vec = app - .ui - .recent_files - .iter() - .enumerate() - .map(|(i, p)| { - let label = std::path::Path::new(p).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.clone()); - MenuItem { id: format!("file.openRecent.{i}"), label, path: rp.clone(), shortcut: None, enabled: true, checked: None, color: None } - }) - .collect(); - if !recent.is_empty() { - recent.push(MenuItem { id: "---".into(), label: "---".into(), path: rp.clone(), shortcut: None, enabled: false, checked: None, color: None }); - } - recent.push(MenuItem { - id: "file.clearRecent".into(), - label: "Clear Recent Files".into(), - path: rp.clone(), - shortcut: None, - enabled: !app.ui.recent_files.is_empty(), - checked: None, - color: None, - }); - for (k, it) in recent.into_iter().enumerate() { - items.insert(after + 1 + k, it); - } - } - // Window › Workspace: saved workspaces follow the presets, checked while current. - let saved = crate::workspace_ui::saved_names(app); - if !saved.is_empty() - && let Some(after) = items.iter().position(|i| i.id == "window.workspace.motion") - { - let wp: Vec = vec!["Window".into(), "Workspace".into()]; - let separator = MenuItem { id: "---".into(), label: "---".into(), path: wp.clone(), shortcut: None, enabled: false, checked: None, color: None }; - let entries = saved.into_iter().enumerate().map(|(i, name)| { - let id = format!("{}{i}", crate::workspace_ui::SAVED); - let checked = checked(app, &id); - MenuItem { id, label: name, path: wp.clone(), shortcut: None, enabled: true, checked, color: None } - }); - for (k, it) in std::iter::once(separator).chain(entries).enumerate() { - items.insert(after + 1 + k, it); - } - } - // Keep the update command with the links, ahead of System Info and About. - if let Some(at) = items.iter().position(|i| i.id == "help.checkForUpdates") { - let update = items.remove(at); - let before = items.iter().position(|i| i.id == "help.systemInfo" || i.id == "help.about").unwrap_or(items.len()); - items.insert(before, update); - } - // Help: the link items and update check, a separator, then System Info and About. - if let Some(at) = items.iter().position(|i| i.id == "help.systemInfo" || i.id == "help.about") { - items.insert( - at, - MenuItem { id: "---".into(), label: "---".into(), path: vec!["Help".into()], shortcut: None, enabled: false, checked: None, color: None }, - ); - } - // Window: the open documents in tab order, after a separator, the active one checked. - if let Some(last) = items.iter().rposition(|i| i.path.first().map(String::as_str) == Some("Window")) { - let window = || vec!["Window".to_string()]; - let active = app.session.active_index(); - let docs = app.session.documents().iter().enumerate().map(|(i, st)| MenuItem { - id: format!("{DOCUMENT_ITEM}{i}"), - label: st.doc.name.clone(), - path: window(), - shortcut: None, - enabled: true, - checked: Some(active == Some(i)), - color: None, - }); - let separator = MenuItem { id: "---".into(), label: "---".into(), path: window(), shortcut: None, enabled: false, checked: None, color: None }; - let rows: Vec = std::iter::once(separator).chain(docs).collect(); - if rows.len() > 1 { - items.splice(last + 1..last + 1, rows); - } - } - // Edit › Keyboard Shortcuts overrides, Edit › Menus hidden items and colours. - let prefs = app.session.prefs(); - if !prefs.shortcuts.is_empty() { - for it in &mut items { - if prefs.shortcuts.contains_key(&it.id) { - it.shortcut = prefs.shortcut(&it.id, None).map(str::to_string); - } - } - } - if !prefs.menus.hidden.is_empty() { - items.retain(|i| !prefs.menus.is_hidden(&i.id)); - } - if prefs.interface.show_menu_colors { - for it in &mut items { - it.color = prefs.menus.colors.get(&it.id).cloned(); - } - } - // Layer › Create Clipping Mask is Photoshop's one Create / Release item: when its shortcut - // would release ([`crate::shortcut_dispatch::clip_key_releases`]) it reads Release Clipping - // Mask and runs it, keeping that shortcut. The engine's own Release item lives in that slot. - items.retain(|i| i.id != "layer.releaseClippingMask"); - if crate::shortcut_dispatch::clip_key_releases(app) - && let Some(item) = items.iter_mut().find(|i| i.id == "layer.createClippingMask") - { - item.id = "layer.releaseClippingMask".into(); - item.label = "Release Clipping Mask".into(); - item.enabled = is_enabled(app, &item.id); - } - items -} - -/// Background tint of an Edit › Menus colour name. -fn menu_tint(name: &str) -> Option { - Some(match name { - "red" => egui::Color32::from_rgb(190, 60, 60), - "orange" => egui::Color32::from_rgb(200, 120, 40), - "yellow" => egui::Color32::from_rgb(190, 170, 40), - "green" => egui::Color32::from_rgb(60, 150, 70), - "blue" => egui::Color32::from_rgb(50, 110, 200), - "violet" => egui::Color32::from_rgb(130, 80, 190), - "gray" => egui::Color32::from_rgb(120, 120, 120), - _ => return None, - }) -} - -/// The open menus' items, kept between frames: building them asks every command whether it can -/// run, which on a document with thousands of layers costs far more than a frame. -pub(crate) struct ItemCache { - /// [`crate::native_menu::state_hash`] of the state the items were built from. - state: u64, - items: Vec, -} - -impl ItemCache { - /// The items, while they still describe `state`. A frame with a click or key press rebuilds - /// them, which covers state the hash doesn't list. - fn reuse(self, state: u64, input: bool) -> Option> { - (!input && self.state == state).then_some(self.items) - } -} - -/// Draws the menu bar; returns the inner edge of the menu titles, facing the rest of the title bar -/// (the right edge of the last title, or its left edge in a right-to-left UI, where File is at the -/// right). The bar itself fills the row. -pub fn menu_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> f32 { - // Built only while a menu is open: every item's enabled/checked state scales with the - // document (layer lookups), which cost milliseconds per frame on large layouts (#125). While - // one stays open, the items are reused until what they depend on changes. - let kept = std::cell::Cell::new(app.menu_cache.take()); - let built: std::cell::OnceCell = std::cell::OnceCell::new(); - let app_ref: &PhotocraftApp = app; - let rtl = crate::direction::is_rtl(); - let mut edge = if rtl { ui.cursor().right() } else { ui.cursor().left() }; - let lang = crate::i18n::current(); - let mut clicked: Option = None; - let t = crate::theme::Tokens::get(ui.ctx()); - let mut nav = crate::menu_nav::Nav::load(ui.ctx()); - // The keyboard on the bar (#4988): Alt / F10 focus, Alt+letter, mnemonics. - let mut keys = crate::menu_keys::Keys::load(ui.ctx()); - keys.take_first_row(&mut nav); - nav.underline = keys.show_underlines(ui.ctx()); - let translated: Vec = TOP_MENUS.iter().map(|top| crate::i18n::tr(lang, top).to_string()).collect(); - let preferred: Vec> = TOP_MENUS.iter().map(|top| crate::menu_keys::TOP_PREFERRED.iter().find(|(t, _)| t == top).map(|(_, c)| *c)).collect(); - // A title with no Latin letter shows its English key: "文件(F)" (#5863). - let (top_labels, top_mnemonics) = crate::menu_keys::localized(&translated, &TOP_MENUS, &preferred); - ui.scope(|ui| { - ui.spacing_mut().item_spacing.x = 0.0; - let v = &mut ui.style_mut().visuals; - v.widgets.inactive.weak_bg_fill = egui::Color32::TRANSPARENT; - v.widgets.inactive.bg_stroke = egui::Stroke::NONE; - v.widgets.inactive.fg_stroke = egui::Stroke::new(1.0, t.text_dim); - v.widgets.hovered.bg_stroke = egui::Stroke::NONE; - egui::MenuBar::new().ui(ui, |ui| { - // egui lays the bar out left to right; a right-to-left UI starts it at the right. - let mut mirrored = rtl.then(|| ui.new_child(egui::UiBuilder::new().layout(crate::direction::row()))); - let ui = mirrored.as_mut().unwrap_or(ui); - ui.spacing_mut().button_padding = egui::vec2(6.0, 3.0); - nav.bar_bottom = Some(ui.max_rect().bottom()); - let mut buttons = Vec::with_capacity(TOP_MENUS.len()); - for (k, top) in TOP_MENUS.iter().enumerate() { - // egui's menu_button toggles on release; these titles open on the press (one - // gesture can press, drag to an item and release), so each drives its popup. - // The title the keyboard is on (Alt / F10) is lit like a hovered one. - let focused = keys.focus == Some(if rtl { TOP_MENUS.len() - 1 - k } else { k }); - let label = if nav.underline { - crate::menu_keys::mnemonic_text(ui, "", &top_labels[k], top_mnemonics[k], Some(t.text_dim)) - } else { - egui::RichText::new(top_labels[k].as_str()).color(t.text_dim).into() - }; - let mut button = egui::Button::new(label); - if focused { - button = button.fill(ui.visuals().widgets.hovered.weak_bg_fill); - } - let title = ui.add(button); - // The bar's close behaviour and style, as a menu (not bar) config so submenus inside - // render as submenus. - let bar = egui::containers::menu::MenuConfig::find(ui); - let config = egui::containers::menu::MenuConfig::new().close_behavior(bar.close_behavior).style(bar.style.clone()); - let open = title_press(ui.ctx(), &title); - // The release ending the press that opened this menu is a click "outside" the - // popup: it must not close it again. - let opening = title.clicked() && ui.ctx().data(|d| d.get_temp::(press_gesture_id())).unwrap_or(false); - let close = if opening { - egui::PopupCloseBehavior::IgnoreClicks - } else if *top == "Help" { - // Menus close on any click, inside them too; a click in Help's search field - // must keep it open. Its items close it themselves when chosen. - egui::PopupCloseBehavior::CloseOnClickOutside - } else { - config.close_behavior - }; - egui::Popup::menu(&title) - .align(crate::direction::below()) - .open_memory(open) - .close_behavior(close) - .style(config.style.clone()) - .info(egui::UiStackInfo::new(egui::UiKind::Menu).with_tag_value(egui::containers::menu::MenuConfig::MENU_CONFIG_TAG, config)) - .show(|ui| { - let items = &built - .get_or_init(|| { - let state = crate::native_menu::state_hash(app_ref, None); - let input = crate::native_menu::had_input(ui.ctx()); - let items = kept.take().and_then(|c| c.reuse(state, input)).unwrap_or_else(|| menu_items(app_ref)); - ItemCache { state, items } - }) - .items; - let mine: Vec<&MenuItem> = items.iter().filter(|i| i.path.first().map(String::as_str) == Some(*top)).collect(); - ui.set_min_width(220.0); - if mine.is_empty() { - ui.weak(crate::i18n::tr(lang, "(coming soon)")); - } - if *top == "Help" { - // The search field scrolls with the rows, as part of the menu's content. - crate::menu_nav::level(ui, 1, &mut nav, |ui, nav| { - help_search(ui, items, opening, &mut clicked, nav); - render_level_rows(ui, &mine, 1, &mut clicked, nav); - }); - } else { - render_level(ui, &mine, 1, &mut clicked, &mut nav); - } - }); - buttons.push(title); - } - edge = if rtl { buttons.iter().map(|b| b.rect.left()).fold(edge, f32::min) } else { buttons.iter().map(|b| b.rect.right()).fold(edge, f32::max) }; - switch_on_hover(ui.ctx(), &buttons); - // ← and → step to the menu on that side, so in screen order. - let mut tops: Vec = buttons.iter().map(egui::Popup::default_response_id).collect(); - if rtl { - tops.reverse(); - } - nav.keys(ui.ctx(), &tops, &mut clicked); - let mut mnemonics = top_mnemonics.clone(); - if rtl { - mnemonics.reverse(); - } - keys.keys(ui.ctx(), &tops, &mnemonics, &mut nav, &mut clicked); - }); - }); - keys.store(ui.ctx()); - nav.store(ui.ctx()); - // No menu open this frame: nothing is kept. - app.menu_cache = built.into_inner(); - // The press-drag gesture ends with the button (its release was handled by the rows above). - if ui.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) { - ui.ctx().data_mut(|d| d.remove::(press_gesture_id())); - } - if let Some(id) = clicked { - let ctx = ui.ctx().clone(); - let alt = ctx.input(|i| i.modifiers.alt); - // ⌥ while choosing an Image › Adjustments item opens it at its last settings (#8900). - let r = if alt && crate::adjust_dialog::has_dialog(&id) { - let opened = crate::adjust_dialog::open_last(app, &id).map(|_| Value::Null).ok_or_else(|| "no document".to_string()); - // Edit › Search's recents, as `invoke` notes a plain click. - if opened.is_ok() { - crate::palette::note_recent(&ctx, &id); - } - opened - } else { - invoke(app, &ctx, &alt_click(id, alt), json!({})) - }; - if let Err(e) = r { - app.ui.status = e; - app.ui.status_error = true; - } - } - edge -} - -fn press_gesture_id() -> egui::Id { - egui::Id::unique("menu-press-gesture") -} - -/// A menu title's open/close command this frame, the press opens a closed menu (and -/// starts a press-drag gesture: releasing on an item runs it) or closes an open one; the release -/// never toggles, so the menu doesn't blink. -fn title_press(ctx: &egui::Context, title: &egui::Response) -> Option { - // A press this frame on the title (still down, or a whole click within one frame). - let pressed = ctx.input(|i| i.pointer.primary_pressed()) && (title.is_pointer_button_down_on() || title.clicked()); - if !pressed { - return None; - } - let open = egui::Popup::is_id_open(ctx, egui::Popup::default_response_id(title)); - if !open { - ctx.data_mut(|d| d.insert_temp(press_gesture_id(), true)); - } - Some(egui::SetOpenCommand::Bool(!open)) -} - -/// Did the press-drag gesture that opened the menus end over `item` (released on it)? -fn released_on(ui: &egui::Ui, item: &egui::Response) -> bool { - item.enabled() - && item.contains_pointer() - && ui.input(|i| i.pointer.primary_released()) - && ui.ctx().data(|d| d.get_temp::(press_gesture_id())).unwrap_or(false) -} - -/// True only when the pointer can actually reach a menu title. A tall submenu can be -/// repositioned upward by egui and overlap the menu bar; in that case the popup's layer is -/// top-most and hovering it must not switch the open top-level menu. -/// -/// The title's column extends up to the top of the window: egui lights a widget up to -/// `interact_radius` away, so with the window maximized a pointer pushed against the screen edge -/// (above the title's own rect) highlights it and must switch to it too (#7702). -fn pointer_reaches_title(ctx: &egui::Context, response: &egui::Response, p: egui::Pos2) -> bool { - let r = response.interact_rect; - let column = egui::Rect::from_min_max(egui::pos2(r.left(), f32::NEG_INFINITY), r.max); - column.contains(p) && ctx.layer_id_at(p) == Some(response.layer_id) -} - -/// Like a native menu bar (Windows, macOS): while one top-level menu is open, hovering another -/// top-level title opens that menu instead. -fn switch_on_hover(ctx: &egui::Context, buttons: &[egui::Response]) { - let ids: Vec = buttons.iter().map(egui::Popup::default_response_id).collect(); - let Some(open) = ids.iter().position(|id| egui::Popup::is_id_open(ctx, *id)) else { return }; - // `Response::hovered` is false while the menu's popup layer is open. Hit-test the title - // rect manually, but only when its own layer is top-most at the pointer. - let Some(p) = ctx.pointer_hover_pos() else { return }; - // Only a moving pointer switches: a pointer resting on a title must not undo ← / → . - if ctx.input(|i| i.pointer.delta() == egui::Vec2::ZERO) { - return; - } - if let Some(i) = buttons.iter().position(|b| pointer_reaches_title(ctx, b, p)) - && i != open - { - egui::Popup::open_id(ctx, ids[i]); - ctx.request_repaint(); - } -} - -/// Most results the Help menu search lists. -const HELP_SEARCH_MAX: usize = 15; - -/// How well `query` (lowercase) matches a menu item: its label starting with it, then a word of -/// the label starting with it, then anywhere in the label, then anywhere in its menu path. -/// `None` when it doesn't match at all. -pub fn search_rank(query: &str, label: &str, path: &[String]) -> Option { - let l = label.to_lowercase(); - if l.starts_with(query) { - Some(0) - } else if l.split(|c: char| !c.is_alphanumeric()).any(|w| w.starts_with(query)) { - Some(1) - } else if l.contains(query) { - Some(2) - } else if path.iter().any(|p| p.to_lowercase().contains(query)) { - Some(3) - } else { - None - } -} - -/// Menu items matching `query`, best first (Photoshop order within a rank). Both the English -/// labels and their `lang` translations match, so a search works in the UI language and in -/// English; untranslated strings are simply their English text. -pub fn search_items<'a>(items: &'a [MenuItem], query: &str, lang: crate::i18n::Lang) -> Vec<&'a MenuItem> { - let q = query.trim().to_lowercase(); - if q.is_empty() { - return Vec::new(); - } - let rank = |it: &MenuItem| { - let english = search_rank(&q, &it.label, &it.path); - let path: Vec = it.path.iter().map(|p| crate::i18n::tr(lang, p).to_string()).collect(); - let local = search_rank(&q, &translated_menu_label(lang, it), &path); - english.into_iter().chain(local).min() - }; - let mut hits: Vec<(u8, usize, &MenuItem)> = - items.iter().enumerate().filter(|(_, it)| it.label != "---").filter_map(|(i, it)| rank(it).map(|r| (r, i, it))).collect(); - hits.sort_by_key(|(r, i, _)| (*r, *i)); - let mut seen = std::collections::HashSet::new(); - hits.into_iter().filter(|(_, _, it)| seen.insert(it.id.as_str())).take(HELP_SEARCH_MAX).map(|(_, _, it)| it).collect() -} - -/// Help › Search : a field at the top of the Help menu that finds any menu command -/// by name. Results show their menu path; click, ↓ then ↩, or ↩ in the field runs one. -/// `opening`: this frame's release ends the click on the Help title that opened the menu. -fn help_search(ui: &mut egui::Ui, items: &[MenuItem], opening: bool, clicked: &mut Option, nav: &mut crate::menu_nav::Nav) { - let ctx = ui.ctx().clone(); - let lang = crate::i18n::current(); - let text_id = egui::Id::unique("help-menu-search"); - let pass_id = text_id.with("pass"); - // A fresh opening of the Help menu starts empty, with the field focused. - let pass = ctx.cumulative_pass_nr(); - let reopened = ctx.data(|d| d.get_temp::(pass_id)).is_none_or(|p| p + 1 < pass); - ctx.data_mut(|d| d.insert_temp(pass_id, pass)); - let mut query: String = if reopened { String::new() } else { ctx.data(|d| d.get_temp(text_id)).unwrap_or_default() }; - let field = ui.add(egui::TextEdit::singleline(&mut query).id(text_id.with("field")).hint_text(crate::i18n::tr(lang, "Search menus")).desired_width(220.0)); - // The menu opens on the press; the release a frame later completes a click on the title, - // outside the field, and egui takes the focus away from it again (#1447, #1438). - if reopened || opening { - field.request_focus(); - } - let results = search_items(items, &query, lang); - if field.lost_focus() - && ui.input(|i| i.key_pressed(egui::Key::Enter)) - && let Some(it) = results.iter().find(|it| it.enabled) - { - *clicked = Some(it.id.clone()); - ui.close(); - } - ctx.data_mut(|d| d.insert_temp(text_id, query.clone())); - if !query.trim().is_empty() { - if results.is_empty() { - ui.weak(crate::i18n::tr(lang, "No matching commands")); - } - for it in results { - let mut trail: Vec = it.path.iter().map(|p| crate::i18n::tr(lang, p).to_string()).collect(); - trail.push(translated_menu_label(lang, it)); - let mut b = egui::Button::new(trail.join(" › ")); - if let Some(sc) = &it.shortcut { - b = b.shortcut_text(crate::shortcuts::pretty(sc)); - } - let hit = nav.row(ui, 0, it.enabled, Some(&it.id), None, |ui, _| { - let r = ui.add_enabled(it.enabled, b); - let hit = r.clicked() || released_on(ui, &r); - (r, hit) - }); - if hit { - *clicked = Some(it.id.clone()); - ui.close(); - } - } - } - ui.separator(); -} - -fn render_level(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, clicked: &mut Option, nav: &mut crate::menu_nav::Nav) { - // Menu popups can be taller than the window: each level stays on screen and scrolls (wheel, - // scroll arrows, keyboard), like a native menu on a small display. - crate::menu_nav::level(ui, depth, nav, |ui, nav| render_level_rows(ui, items, depth, clicked, nav)); -} - -/// Height of a menu separator: a line with room above and below, as in native menus. -const MENU_SEPARATOR: f32 = 9.0; - -fn render_level_rows(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, clicked: &mut Option, nav: &mut crate::menu_nav::Nav) { - let lang = crate::i18n::current(); - // Items never wrap: the menu widens to its longest label plus shortcut (translations can be - // longer than the English). - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); - // Rows touch, as in native menus: the dialog spacing between them made long menus a fifth - // taller than they need to be (#402). - ui.spacing_mut().item_spacing.y = 0.0; - // Secondary menus use the exact same Spectrum hover contrast and spacing. - crate::widgets::style_spectrum_popup_menu(ui); - // Walk in Photoshop order: leaves and separators at this depth; a submenu appears at the position - // of its first child. - // Each row's mnemonic (#4988), unique within this level, in display order: the leaves' labels - // and the submenus' names as shown. - // A label with no Latin letter shows its English label's key after it: "新建(N)…" (#5863). - let (translated, english): (Vec, Vec<&str>) = { - let mut subs: Vec<&str> = Vec::new(); - items - .iter() - .filter_map(|it| { - if it.path.len() == depth { - (it.label != "---").then(|| (translated_menu_label(lang, it), it.label.as_str())) - } else { - let name = it.path.get(depth).map(String::as_str)?; - (!subs.contains(&name)).then(|| { - subs.push(name); - (crate::i18n::tr(lang, name).to_string(), name) - }) - } - }) - .unzip() - }; - let (shown_labels, mnemonics) = crate::menu_keys::localized(&translated, &english, &[]); - let mut next_row = 0usize; - let mut shown_subs: Vec<&str> = Vec::new(); - let mut last_was_sep = true; - for (i, it) in items.iter().enumerate() { - if it.path.len() == depth { - if it.label == "---" { - if !last_was_sep && i + 1 < items.len() { - ui.add(egui::Separator::default().spacing(MENU_SEPARATOR)); - last_was_sep = true; - } - continue; - } - let label = shown_labels.get(next_row).cloned().unwrap_or_else(|| translated_menu_label(lang, it)); - let mnemonic = mnemonics.get(next_row).copied().flatten(); - next_row += 1; - // Checked, unchecked and plain rows share one checkmark column (#5705). - let text = crate::menu_keys::menu_row_text(ui, it.checked == Some(true), &label, mnemonic.filter(|_| nav.underline)); - let mut b = egui::Button::new(text); - if let Some(tint) = it.color.as_deref().and_then(menu_tint) { - b = b.fill(tint.gamma_multiply(0.55)); - } - if let Some(sc) = &it.shortcut { - b = b.shortcut_text(crate::shortcuts::pretty(sc)); - } - let hit = nav.row(ui, depth - 1, it.enabled, Some(&it.id), mnemonic, |ui, _| { - let r = ui.add_enabled(it.enabled, b); - let r = match it.id.as_str() { - "image.mode.bits8" | "image.mode.bits16" => r.on_hover_text(crate::i18n::tr(lang, "Integer")), - "image.mode.bits32" => r.on_hover_text(crate::i18n::tr(lang, "Floating point")), - _ => r, - }; - let hit = r.clicked() || released_on(ui, &r); - (r, hit) - }); - if hit { - *clicked = Some(it.id.clone()); - ui.close(); - } - last_was_sep = false; - } else if it.path.len() > depth { - let name = it.path[depth].as_str(); - if shown_subs.contains(&name) { - continue; - } - shown_subs.push(name); - let child: Vec<&MenuItem> = items.iter().copied().filter(|c| c.path.len() > depth && c.path[depth] == name).collect(); - let enabled = submenu_enabled(&child); - let mnemonic = mnemonics.get(next_row).copied().flatten(); - let shown = shown_labels.get(next_row).cloned().unwrap_or_else(|| crate::i18n::tr(lang, name).to_string()); - next_row += 1; - let title = crate::menu_keys::menu_row_text(ui, false, &shown, mnemonic.filter(|_| nav.underline)); - ui.add_enabled_ui(enabled, |ui| { - nav.row(ui, depth - 1, enabled, None, mnemonic, |ui, nav| { - let (response, inner) = submenu_row(ui, title, |ui| render_level(ui, &child, depth + 1, clicked, nav)); - if inner.is_some() { - // Where the submenu hangs from, to keep it below the menu bar (#319). - nav.set_anchor(depth, response.rect); - } - (response, ()) - }); - }); - last_was_sep = false; - } - } -} - -/// A submenu row, drawn as `ui.menu_button` draws it, except that a row scrolled out of view -/// doesn't open its submenu. egui opens a submenu whenever the pointer is over its row, clipped -/// or not: a menu reopened scrolled down (after Edit › Preferences or Window › Theme) has rows -/// hidden above its view, over the menu bar, and the hidden one under the title opened on the -/// press; the release on the title then counted as a click outside that submenu and closed the -/// whole menu (#5896, #6225). An open submenu (e.g. opened from the keyboard) is drawn as usual. -fn submenu_row(ui: &mut egui::Ui, title: egui::WidgetText, content: impl FnOnce(&mut egui::Ui) -> R) -> (egui::Response, Option) { - use egui::containers::menu::{MenuState, SubMenu, SubMenuButton}; - let sub = SubMenu::id_from_widget_id(ui.next_auto_id()); - let open = MenuState::from_ui(ui, |state, _| state.open_item == Some(sub)); - let inactive = ui.style().visuals.widgets.inactive; - if open { - ui.style_mut().visuals.widgets.inactive = ui.style().visuals.widgets.open; - } - let response = ui.add(egui::Button::new(title).right_text(SubMenuButton::arrow_atom(None))); - ui.style_mut().visuals.widgets.inactive = inactive; - // The rect egui tests the pointer against (`SubMenu::show`), against the part that can be seen. - let reach = response.rect.expand2(ui.spacing().item_spacing / 2.0); - let hidden = ui.ctx().pointer_hover_pos().is_some_and(|p| reach.contains(p) && !ui.clip_rect().contains(p)); - if hidden && !open { - return (response, None); - } - let inner = SubMenu::new().show(ui, &response, content); - (response, inner.map(|r| r.inner)) -} - -/// A submenu header is enabled only while some item under it (at any depth) can run, so a -/// submenu of greyed items is greyed too instead of opening onto them (#1976). -fn submenu_enabled(children: &[&MenuItem]) -> bool { - children.iter().any(|c| c.enabled && c.label != "---") -} - -/// The command a menu click runs: ⌥ + Merge Down / Merge Layers / Merge Visible keep the -/// originals, running Stamp Down / Stamp Visible instead (#217). -pub fn alt_click(id: String, alt: bool) -> String { - match photocraft_engine::stamp_cmds::alt_variant(&id) { - Some(stamp) if alt => stamp.to_string(), - _ => id, - } -} - -/// Workspace presets (Window → Workspace): which panels are visible. -pub fn apply_workspace(app: &mut PhotocraftApp) { - // Saved workspaces (Window › Workspace › New Workspace…) restore their own layout. - if crate::workspace_ui::apply_custom(app) { - return; - } - // Presets use the default group order, heights and tabs (Reset brings everything back). - app.ui.dock = Default::default(); - app.ui.docking_reveal = None; - app.ui.docking_generation = app.ui.docking_generation.wrapping_add(1); - app.ui.docking = None; - app.ui.docking_kept = None; - app.ui.docking_returns.clear(); - app.ui.docking_collapsed.clear(); - app.ui.dock_tabs = Default::default(); - let p = &mut app.ui.panels; - let (nav, color, layers, history, props) = match app.ui.workspace.as_str() { - "Photography" => (true, false, true, true, true), - "Painting" => (false, true, true, false, false), - // Leave room for typography alongside Properties and Layers. - "Graphic and Web" => (false, false, true, false, true), - // Color includes Swatches; Navigator keeps the pixel canvas easy to inspect. - "Pixel Art" => (true, true, true, false, false), - "Motion" => (false, false, true, false, true), - _ => (false, true, true, false, true), - }; - p.navigator = nav; - p.color = color; - p.layers = layers; - p.history = history; - p.properties = props; - p.character = app.ui.workspace == "Graphic and Web"; - // Timeline is a floating panel, not a dock group. Showing it does not create or edit - // a document timeline; changing away from Motion closes it just like its Close button. - app.ui.timeline.open = app.ui.workspace == "Motion"; - if !app.ui.timeline.open { - app.ui.timeline.playing = false; - } -} - #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/menus/bar.rs b/crates/ui-egui/src/menus/bar.rs new file mode 100644 index 0000000000..f146390e06 --- /dev/null +++ b/crates/ui-egui/src/menus/bar.rs @@ -0,0 +1,213 @@ +use super::invoke::invoke; +use super::items::{ItemCache, MenuItem, menu_items}; +use super::render::{alt_click, render_level, render_level_rows}; +use super::search::help_search; +use super::*; + +/// Draws the menu bar; returns the inner edge of the menu titles, facing the rest of the title bar +/// (the right edge of the last title, or its left edge in a right-to-left UI, where File is at the +/// right). The bar itself fills the row. +pub fn menu_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> f32 { + // Built only while a menu is open: every item's enabled/checked state scales with the + // document (layer lookups), which cost milliseconds per frame on large layouts (#125). While + // one stays open, the items are reused until what they depend on changes. + let kept = std::cell::Cell::new(app.menu_cache.take()); + let built: std::cell::OnceCell = std::cell::OnceCell::new(); + let app_ref: &PhotocraftApp = app; + let rtl = crate::direction::is_rtl(); + let mut edge = if rtl { ui.cursor().right() } else { ui.cursor().left() }; + let lang = crate::i18n::current(); + let mut clicked: Option = None; + let t = crate::theme::Tokens::get(ui.ctx()); + let mut nav = crate::menu_nav::Nav::load(ui.ctx()); + // The keyboard on the bar (#4988): Alt / F10 focus, Alt+letter, mnemonics. + let mut keys = crate::menu_keys::Keys::load(ui.ctx()); + keys.take_first_row(&mut nav); + nav.underline = keys.show_underlines(ui.ctx()); + let translated: Vec = TOP_MENUS.iter().map(|top| crate::i18n::tr(lang, top).to_string()).collect(); + let preferred: Vec> = TOP_MENUS.iter().map(|top| crate::menu_keys::TOP_PREFERRED.iter().find(|(t, _)| t == top).map(|(_, c)| *c)).collect(); + // A title with no Latin letter shows its English key: "文件(F)" (#5863). + let (top_labels, top_mnemonics) = crate::menu_keys::localized(&translated, &TOP_MENUS, &preferred); + ui.scope(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + let v = &mut ui.style_mut().visuals; + v.widgets.inactive.weak_bg_fill = egui::Color32::TRANSPARENT; + v.widgets.inactive.bg_stroke = egui::Stroke::NONE; + v.widgets.inactive.fg_stroke = egui::Stroke::new(1.0, t.text_dim); + v.widgets.hovered.bg_stroke = egui::Stroke::NONE; + egui::MenuBar::new().ui(ui, |ui| { + // egui lays the bar out left to right; a right-to-left UI starts it at the right. + let mut mirrored = rtl.then(|| ui.new_child(egui::UiBuilder::new().layout(crate::direction::row()))); + let ui = mirrored.as_mut().unwrap_or(ui); + ui.spacing_mut().button_padding = egui::vec2(6.0, 3.0); + nav.bar_bottom = Some(ui.max_rect().bottom()); + let mut buttons = Vec::with_capacity(TOP_MENUS.len()); + for (k, top) in TOP_MENUS.iter().enumerate() { + // egui's menu_button toggles on release; these titles open on the press (one + // gesture can press, drag to an item and release), so each drives its popup. + // The title the keyboard is on (Alt / F10) is lit like a hovered one. + let focused = keys.focus == Some(if rtl { TOP_MENUS.len() - 1 - k } else { k }); + let label = if nav.underline { + crate::menu_keys::mnemonic_text(ui, "", &top_labels[k], top_mnemonics[k], Some(t.text_dim)) + } else { + egui::RichText::new(top_labels[k].as_str()).color(t.text_dim).into() + }; + let mut button = egui::Button::new(label); + if focused { + button = button.fill(ui.visuals().widgets.hovered.weak_bg_fill); + } + let title = ui.add(button); + // The bar's close behaviour and style, as a menu (not bar) config so submenus inside + // render as submenus. + let bar = egui::containers::menu::MenuConfig::find(ui); + let config = egui::containers::menu::MenuConfig::new().close_behavior(bar.close_behavior).style(bar.style.clone()); + let open = title_press(ui.ctx(), &title); + // The release ending the press that opened this menu is a click "outside" the + // popup: it must not close it again. + let opening = title.clicked() && ui.ctx().data(|d| d.get_temp::(press_gesture_id())).unwrap_or(false); + let close = if opening { + egui::PopupCloseBehavior::IgnoreClicks + } else if *top == "Help" { + // Menus close on any click, inside them too; a click in Help's search field + // must keep it open. Its items close it themselves when chosen. + egui::PopupCloseBehavior::CloseOnClickOutside + } else { + config.close_behavior + }; + egui::Popup::menu(&title) + .align(crate::direction::below()) + .open_memory(open) + .close_behavior(close) + .style(config.style.clone()) + .info(egui::UiStackInfo::new(egui::UiKind::Menu).with_tag_value(egui::containers::menu::MenuConfig::MENU_CONFIG_TAG, config)) + .show(|ui| { + let items = &built + .get_or_init(|| { + let state = crate::native_menu::state_hash(app_ref, None); + let input = crate::native_menu::had_input(ui.ctx()); + let items = kept.take().and_then(|c| c.reuse(state, input)).unwrap_or_else(|| menu_items(app_ref)); + ItemCache { state, items } + }) + .items; + let mine: Vec<&MenuItem> = items.iter().filter(|i| i.path.first().map(String::as_str) == Some(*top)).collect(); + ui.set_min_width(220.0); + if mine.is_empty() { + ui.weak(crate::i18n::tr(lang, "(coming soon)")); + } + if *top == "Help" { + // The search field scrolls with the rows, as part of the menu's content. + crate::menu_nav::level(ui, 1, &mut nav, |ui, nav| { + help_search(ui, items, opening, &mut clicked, nav); + render_level_rows(ui, &mine, 1, &mut clicked, nav); + }); + } else { + render_level(ui, &mine, 1, &mut clicked, &mut nav); + } + }); + buttons.push(title); + } + edge = if rtl { buttons.iter().map(|b| b.rect.left()).fold(edge, f32::min) } else { buttons.iter().map(|b| b.rect.right()).fold(edge, f32::max) }; + switch_on_hover(ui.ctx(), &buttons); + // ← and → step to the menu on that side, so in screen order. + let mut tops: Vec = buttons.iter().map(egui::Popup::default_response_id).collect(); + if rtl { + tops.reverse(); + } + nav.keys(ui.ctx(), &tops, &mut clicked); + let mut mnemonics = top_mnemonics.clone(); + if rtl { + mnemonics.reverse(); + } + keys.keys(ui.ctx(), &tops, &mnemonics, &mut nav, &mut clicked); + }); + }); + keys.store(ui.ctx()); + nav.store(ui.ctx()); + // No menu open this frame: nothing is kept. + app.menu_cache = built.into_inner(); + // The press-drag gesture ends with the button (its release was handled by the rows above). + if ui.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) { + ui.ctx().data_mut(|d| d.remove::(press_gesture_id())); + } + if let Some(id) = clicked { + let ctx = ui.ctx().clone(); + let alt = ctx.input(|i| i.modifiers.alt); + // ⌥ while choosing an Image › Adjustments item opens it at its last settings (#8900). + let r = if alt && crate::adjust_dialog::has_dialog(&id) { + let opened = crate::adjust_dialog::open_last(app, &id).map(|_| Value::Null).ok_or_else(|| "no document".to_string()); + // Edit › Search's recents, as `invoke` notes a plain click. + if opened.is_ok() { + crate::palette::note_recent(&ctx, &id); + } + opened + } else { + invoke(app, &ctx, &alt_click(id, alt), json!({})) + }; + if let Err(e) = r { + app.ui.status = e; + app.ui.status_error = true; + } + } + edge +} + +fn press_gesture_id() -> egui::Id { + egui::Id::unique("menu-press-gesture") +} + +/// A menu title's open/close command this frame, the press opens a closed menu (and +/// starts a press-drag gesture: releasing on an item runs it) or closes an open one; the release +/// never toggles, so the menu doesn't blink. +fn title_press(ctx: &egui::Context, title: &egui::Response) -> Option { + // A press this frame on the title (still down, or a whole click within one frame). + let pressed = ctx.input(|i| i.pointer.primary_pressed()) && (title.is_pointer_button_down_on() || title.clicked()); + if !pressed { + return None; + } + let open = egui::Popup::is_id_open(ctx, egui::Popup::default_response_id(title)); + if !open { + ctx.data_mut(|d| d.insert_temp(press_gesture_id(), true)); + } + Some(egui::SetOpenCommand::Bool(!open)) +} + +/// Did the press-drag gesture that opened the menus end over `item` (released on it)? +pub(super) fn released_on(ui: &egui::Ui, item: &egui::Response) -> bool { + item.enabled() + && item.contains_pointer() + && ui.input(|i| i.pointer.primary_released()) + && ui.ctx().data(|d| d.get_temp::(press_gesture_id())).unwrap_or(false) +} + +/// True only when the pointer can actually reach a menu title. A tall submenu can be +/// repositioned upward by egui and overlap the menu bar; in that case the popup's layer is +/// top-most and hovering it must not switch the open top-level menu. +/// +/// The title's column extends up to the top of the window: egui lights a widget up to +/// `interact_radius` away, so with the window maximized a pointer pushed against the screen edge +/// (above the title's own rect) highlights it and must switch to it too (#7702). +pub(super) fn pointer_reaches_title(ctx: &egui::Context, response: &egui::Response, p: egui::Pos2) -> bool { + let r = response.interact_rect; + let column = egui::Rect::from_min_max(egui::pos2(r.left(), f32::NEG_INFINITY), r.max); + column.contains(p) && ctx.layer_id_at(p) == Some(response.layer_id) +} + +/// Like a native menu bar (Windows, macOS): while one top-level menu is open, hovering another +/// top-level title opens that menu instead. +fn switch_on_hover(ctx: &egui::Context, buttons: &[egui::Response]) { + let ids: Vec = buttons.iter().map(egui::Popup::default_response_id).collect(); + let Some(open) = ids.iter().position(|id| egui::Popup::is_id_open(ctx, *id)) else { return }; + // `Response::hovered` is false while the menu's popup layer is open. Hit-test the title + // rect manually, but only when its own layer is top-most at the pointer. + let Some(p) = ctx.pointer_hover_pos() else { return }; + // Only a moving pointer switches: a pointer resting on a title must not undo ← / → . + if ctx.input(|i| i.pointer.delta() == egui::Vec2::ZERO) { + return; + } + if let Some(i) = buttons.iter().position(|b| pointer_reaches_title(ctx, b, p)) + && i != open + { + egui::Popup::open_id(ctx, ids[i]); + ctx.request_repaint(); + } +} diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs new file mode 100644 index 0000000000..09640f6e27 --- /dev/null +++ b/crates/ui-egui/src/menus/invoke.rs @@ -0,0 +1,698 @@ +use super::*; + +/// Photoshop's Window › ids for the panels the shell already has, as `window.toggle.*`. +pub(crate) fn panel_alias(id: &str) -> Option<&'static str> { + Some(match id.strip_prefix("window.panel.")? { + "layers" => "window.toggle.layers", + "history" => "window.toggle.history", + "properties" | "adjustments" => "window.toggle.properties", + "color" | "swatches" => "window.toggle.color", + "navigator" | "info" | "histogram" => "window.toggle.navigator", + "tools" => "window.toggle.toolbar", + "options" => "window.toggle.options", + "brushSettings" => "window.toggle.brushSettings", + "brushes" => "window.toggle.brushes", + _ => return None, + }) +} + +/// View › Proof Setup presets we can simulate, as `view.proofSetup` profiles. +pub(super) fn proof_preset(id: &str) -> Option<&'static str> { + Some(match id.strip_prefix("view.proofSetup.")? { + "workingCmyk" => "working-cmyk", + "internetStandardRgb" | "monitorRgb" => "srgb", + _ => return None, + }) +} + +/// Window › Workspace presets by id. +pub(super) fn workspace_name(id: &str) -> Option<&'static str> { + Some(match id.strip_prefix("window.workspace.")? { + "essentials" | "resetWorkspace" => "", + "photography" => "Photography", + "painting" => "Painting", + "graphicAndWeb" => "Graphic and Web", + "pixelArt" => "Pixel Art", + "motion" => "Motion", + _ => return None, + }) +} + +/// Run a command id from any source (menu, shortcut, palette, automation). +pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result { + if app.automation_input + && let Some(authorize) = app.services.automation_command.as_ref() + { + authorize(id, ¶ms)?; + } + if crate::discard_ui::intercept(app, id, ¶ms) { + return Ok(Value::Null); + } + let r = invoke_unguarded(app, ctx, id, params)?; + // The palette's empty-query list (UI-217-7); opening the palette isn't a command to recall. + if id != "edit.search" { + crate::palette::note_recent(ctx, id); + } + Ok(r) +} + +/// [`invoke`] without the unsaved-changes prompt, for once the user has already answered it. +pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result { + if let Some(tool) = crate::tool_shortcuts::tool(id) { + crate::tool_memory::select(app, tool); + return Ok(json!({"tool": tool})); + } + if id == "help.checkForUpdates" { + return crate::updates_ui::check(app, ctx, params); + } + if id == "ui.symmetryTransform" { + return crate::symmetry_ui::begin(app).map(|_| Value::Null); + } + if let Some(r) = crate::tool_reset::invoke(app, id, ¶ms) { + return r; + } + // A filter on a type layer asks to rasterize it first (#4303). + if let Some(r) = crate::rasterize_prompt::intercept_filter(app, id, ¶ms) { + return r; + } + // A pending Pen anchor is gesture state; Edit › Undo must match the keyboard. + if id == "edit.undo" && crate::vector_ui::pen_undo_last_point(app) { + return Ok(Value::Null); + } + // Image › Crop while the Crop tool has a pending frame commits that frame (#1918). + if id == "image.crop" && crate::crop_ui::pending(app) { + crate::canvas::commit_crop(app); + return Ok(json!({"committed": true})); + } + if let Some(result) = crate::panel_docking::command(app, id, ¶ms) { + return result; + } + // Help › Discord, website, GitHub, Report an Issue. + if let Some(url) = crate::links::url_for(id) { + return Ok(crate::links::open(app, ctx, url)); + } + if id == "view.proofSetup.custom" { + return Ok(json!({"dialog": crate::filter_dialog::open(app, "view.proofSetup")})); + } + // Image › Analysis tools/dialogs, Measurement Log and Notes panels, File › Import › Notes. + if let Some(r) = crate::analysis_ui::menu(app, id, ¶ms) { + return r; + } + // Workspace New/Delete/Lock, Modifier Keys, custom pixel aspect, Extras/32-bit options. + if let Some(r) = crate::workspace_ui::menu(app, id, ¶ms) { + return r; + } + // Window › Gradients, Patterns, Styles, Shapes, Tool Presets, Clone Source. + if let Some(r) = crate::preset_panels::menu(app, id, ¶ms) { + return r; + } + // Character/Paragraph Styles, Glyphs, Edit › Check Spelling dialog. + if let Some(r) = crate::type_panels_ui::menu(app, id, ¶ms) { + return r; + } + // Image > Variables (Define / Data Sets), Apply Data Set. + if let Some(r) = crate::variables_ui::menu(app, id, ¶ms) { + return r; + } + // Window > Timeline panel. + if let Some(r) = crate::timeline_ui::menu(app, id, ¶ms) { + return r; + } + // Filter › Plug-ins (installed WebAssembly plug-ins, Install Plug-in…). + if let Some(r) = crate::plugin_ui::menu(app, id, ¶ms) { + return r; + } + if id == "window.panel.brushSettings" { + app.ui.brush_tab = 0; + } + // View/Window/Type shell items, and dialogs/pickers in front of File commands. + // Edit › Preferences, Keyboard Shortcuts, Color Settings and other Edit dialogs. + if let Some(r) = crate::prefs_ui::invoke(app, ctx, id, ¶ms) { + return r; + } + // Save for Web's dialog would export the committed document, not the open Free Transform (#6737). + if id == crate::transform_tool::SAVE_FOR_WEB + && let Some(r) = crate::transform_tool::intercept(app, id) + { + return r; + } + // Save for Web, Print and the other File-menu dialogs added with slices. + if let Some(r) = crate::file_ui::invoke(app, ctx, id, ¶ms) { + return r; + } + if let Some(r) = crate::view_cmds::invoke(app, ctx, id, ¶ms) { + return r; + } + // Liquify dialog, Puppet Warp and Perspective Warp modes (and their control params). + if let Some(r) = crate::distort_ui::menu(app, ctx, id, ¶ms) { + return r; + } + // Camera Raw Filter dialog (and its control params). + if let Some(r) = crate::camera_raw_ui::menu(app, ctx, id, ¶ms) { + return r; + } + if let Some(r) = crate::wide_angle_ui::menu(app, ctx, id, ¶ms) { + return r; + } + if let Some(profile) = proof_preset(id) { + // View › Proof Setup presets: set the proof profile and turn Proof Colors on. + app.run("view.proofSetup", json!({"profile": profile}))?; + return app.run("view.proofColors", json!({"on": true})); + } + if let Some(alias) = panel_alias(id) { + return invoke(app, ctx, alias, params); + } + if let Some(ws) = workspace_name(id) { + // Reset re-applies the current workspace; Essentials is the default layout. + match (ws, id) { + (_, "window.workspace.resetWorkspace") => {} + ("", _) => app.ui.workspace = "Essentials".into(), + (name, _) => app.ui.workspace = name.into(), + } + apply_workspace(app); + return Ok(json!({"workspace": app.ui.workspace})); + } + match id { + // ⌘↩ / Ctrl+Enter (#306): load the path selected in the Paths panel (or the one being + // drawn) as a selection. + "path.toSelection" if params.get("name").is_none() => crate::vector_ui::path_to_selection(app, params), + // Layer › Rename Layer from a menu starts in-place renaming in the Layers panel. + "layer.renameLayer" if params.get("name").is_none() => { + let st = app.session.active().ok_or("no document")?; + let id = params.get("layer").and_then(Value::as_u64).or(st.active_layer.map(|l| l.0)).ok_or("no active layer")?; + let name = st.doc.layer(photocraft_doc::LayerId(id)).map(|l| l.name.clone()).ok_or("no such layer")?; + // Another rename in progress is committed first (#314). + if let Some((cmd, p)) = crate::layer_row_ui::start_rename(ctx, id, &name) { + app.run(&cmd, p)?; + } + Ok(Value::Null) + } + "layer.duplicate" if params.as_object().is_none_or(|o| o.is_empty()) => crate::duplicate_layer_ui::open(app), + "file.new" if params.as_object().is_none_or(|o| o.is_empty()) => { + let fields = app.new_document_fields(); + let d = app.ui.open_dialog(DialogKind::NewDocument, fields); + Ok(json!({"dialog": d})) + } + "file.open" => { + if let Some(path) = params.get("path").and_then(Value::as_str) { + open_path(app, path) + } else { + app.open_dialog_file() + } + } + "file.import.videoFramesToLayers" if params.get("path").and_then(Value::as_str).is_none() => { + app.ask_folder(|app, path| app.run("file.import.videoFramesToLayers", json!({"path": path})).map_err(|e| e.to_string())) + } + "file.save" => { + // Writes back only to a layered file that holds the whole document; anything else + // goes through Save As, so the original is never overwritten with less (#3806). + let choices = crate::FormatChoices::from_params(¶ms, id)?; + match params.get("path").and_then(Value::as_str) { + Some(path) => app.save_as_with(Some(path.to_string()), choices), + None => { + let own = app.session.active().and_then(|d| d.path.clone().map(|p| (photocraft_engine::file_cmds::holds_at(&d.doc, &p), p, d))); + match own { + Some((true, path, d)) => { + // Another app changed the file since it was opened or saved: ask first (#6596). + let doc = d.doc.id; + crate::disk_change_prompt::intercept(app, doc, &path, false, crate::FormatChoices::default()) + .unwrap_or_else(|| app.save_in_place(path, crate::FormatChoices::default())) + } + Some((false, path, d)) if photocraft_engine::file_cmds::saves_in_place(&path) => { + // Its own file is layered but can't hold what the document has now. + let losses = photocraft_engine::file_cmds::losses_at(&d.doc, &path); + let name = crate::file_open::display_name(&path); + let title = crate::i18n::fmt(tl!("{name} can't keep everything in this document"), &[("name", name.as_str())]); + let mut lines = losses; + lines.push(tl!("Choose a format that keeps it, such as Photoshop (PSD), or save a copy.").to_string()); + crate::notices::post(app, title, lines, false, None); + app.save_as_with(None, choices) + } + // A flat file asks for its name; confirming its own file records a + // plain Save that writes the file an action is played on (#3531). + _ => app.save_dialog_flow(None, choices, true), + } + } + } + } + "file.exit" => { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + Ok(Value::Null) + } + "file.clearRecent" => { + app.clear_recent(); + Ok(Value::Null) + } + "file.removeRecent" => { + let path = params.get("path").and_then(Value::as_str).ok_or("file.removeRecent needs a \"path\"")?; + app.remove_recent(path); + Ok(Value::Null) + } + id if id.starts_with("file.openRecent.") => { + #[cfg(not(target_arch = "wasm32"))] + { + match id.rsplit('.').next().and_then(|s| s.parse::().ok()).and_then(|i| app.ui.recent_files.get(i).cloned()) { + Some(p) => open_path(app, &p), + None => Err("no such recent file".to_string()), + } + } + #[cfg(target_arch = "wasm32")] + { + let _ = app; + let message = "Open Recent is unavailable on the web"; + Err(tl!(message).to_string()) + } + } + "file.saveAs" => { + let choices = crate::FormatChoices::from_params(¶ms, id)?; + app.save_as_with(params.get("path").and_then(Value::as_str).map(str::to_string), choices) + } + "view.zoomIn" | "view.zoomOut" | "view.fitOnScreen" | "view.actualPixels" => app.run(id, params), + "window.newWindowForDocument" => { + let doc = app.session.active_index().ok_or("no document")?; + let wid = app.ui.alloc_id(); + let view = app.ui.views[doc].clone(); + app.ui.windows.push(crate::state::DocWindow { id: wid, document: doc, view, open: true, position: None }); + Ok(json!({"window": wid})) + } + "window.theme.toggle" => { + crate::prefs_ui::cycle_appearance(app, ctx); + Ok(Value::Null) + } + "view.darkenInterface" | "view.lightenInterface" => { + crate::prefs_ui::step_brightness(app, ctx, id == "view.lightenInterface")?; + Ok(json!({"theme": app.ui.theme.id()})) + } + "window.theme.system" => { + app.run("prefs.set", json!({"path": "interface.appearanceMode", "value": "auto"}))?; + crate::prefs_ui::sync_appearance(app, ctx); + Ok(Value::Null) + } + "window.theme.pro" + | "window.theme.proMedium" + | "window.theme.proLightGray" + | "window.theme.proLight" + | "window.theme.studio" + | "window.theme.studioLight" + | "window.theme.classic" + | "window.theme.solarizedDark" + | "window.theme.adwaita" + | "window.theme.adwaitaDark" + | "window.theme.breezeLight" + | "window.theme.breezeDark" + | "window.theme.softLight" + | "window.theme.softDark" => { + let k = crate::theme::ThemeKind::from_name(&id["window.theme.".len()..]).unwrap_or_default(); + app.set_theme(ctx, k); + Ok(Value::Null) + } + // The macOS app menu's Language (`native_menu::language_node`). + i if i.starts_with(crate::native_menu::LANGUAGE_PREFIX) => { + let code = &i[crate::native_menu::LANGUAGE_PREFIX.len()..]; + if code != "auto" && !crate::i18n::Lang::all().any(|l| l.code() == code) { + return Err(format!("unknown UI language `{code}`")); + } + app.run("prefs.set", json!({"values": {"interface.language": code}})) + } + "edit.search" => { + app.ui.palette_open = !app.ui.palette_open; + Ok(Value::Null) + } + "help.about" => Ok(json!({"dialog": app.ui.open_dialog(DialogKind::About, Default::default())})), + "help.systemInfo" => { + let mut fields = serde_json::Map::new(); + fields.insert("systemInfo".into(), json!(true)); + let dialog = app.ui.open_dialog(DialogKind::About, fields); + Ok(json!({"dialog": dialog, "info": crate::gpu_status::system_info_json(app)})) + } + "file.export.exportAs" => Ok(json!({"dialog": crate::export_dialog::open(app)?})), + "file.export.quickExportAsPng" => crate::export_dialog::quick_export_png(app), + // Render Video exports a sequence of frames into a folder, not a named file. + // Keep explicit directory arguments from automation and the control channel unchanged. + "file.export.renderVideo" if params.get("dir").is_none() => { + #[cfg(target_arch = "wasm32")] + { + Err("Render Video to a local directory is unavailable on the web".into()) + } + #[cfg(not(target_arch = "wasm32"))] + { + let doc = app.session.active().ok_or("no document")?.doc.id; + let mut render_params = params.as_object().cloned().unwrap_or_default(); + app.ask_folder(move |app, dir| { + render_params.insert("dir".into(), json!(dir)); + app.with_document(doc, |app| app.run("file.export.renderVideo", Value::Object(render_params))) + }) + } + } + // Layer › Export As… / Quick Export as PNG: the export pipeline on just the active layer. + l if matches!(l, "layer.exportAs" | "layer.quickExportAsPng") && params.as_object().is_none_or(|o| o.is_empty()) => { + let layer = app.session.active().and_then(|d| d.active_layer).ok_or("no active layer")?; + if l == "layer.exportAs" { + // Several layers (artboards, say) selected: one file each (#3629). + let layers = app.session.active().map(|d| d.selected_layers()).unwrap_or_default(); + if layers.len() > 1 { + return Ok(json!({"dialog": crate::export_dialog::open_layers(app, &layers)?})); + } + Ok(json!({"dialog": crate::export_dialog::open_layer(app, layer)?})) + } else { + crate::export_dialog::quick_export_selected_layers_png(app) + } + } + "layer.smartFilter.blendingOptions" if params.get("blend").is_none() && params.get("opacity").is_none() => { + let st = app.session.active().ok_or("no document open")?; + let layer = params.get("layer").and_then(Value::as_u64).map(photocraft_doc::LayerId).or(st.active_layer).ok_or("no layer selected")?; + let Some(photocraft_doc::LayerContent::Smart(sm)) = st.doc.layer(layer).map(|l| &l.content) else { + return Err("the layer is not a Smart Object".into()); + }; + let index = match params.get("index") { + Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or("invalid Smart Filter index")?, + None => sm.smart_filters.len().checked_sub(1).ok_or("the Smart Object has no Smart Filters")?, + }; + crate::smart_filter_dialog::open(app, layer, index).map(|id| json!({"dialog": id})) + } + "layer.layerStyle.blendingOptions" if params.as_object().is_none_or(|o| o.is_empty()) => { + crate::layer_style::open(app, Some(crate::layer_style::BLENDING)).map(|d| json!({"dialog": d})).ok_or_else(|| "no active layer".to_string()) + } + // ⇧⌘> / ⇧⌘<: the selected characters while typing, else the whole type layer. + "type.increaseSize" | "type.decreaseSize" | "type.increaseSizeMore" | "type.decreaseSizeMore" if params.as_object().is_none_or(|o| o.is_empty()) => { + let p = crate::type_tool::with_target(app, json!({})).ok_or("the active layer is not a type layer")?; + app.run(id, p) + } + // Formatting menus follow an inline text selection when editing. Outside an edit, + // snapshot the selected type layers; explicit automation targets retain their scope. + t if (t.starts_with("type.antiAlias.") + || t.starts_with("type.orientation.") + || t.starts_with("type.openType.") + || matches!(t, "type.warpText" | "type.loadDefaultTypeStyles")) + && params.get("layer").is_none() + && params.get("layers").is_none() + && params.get("range").is_none() => + { + let Some(mut p) = crate::type_tool::formatting_params(app) else { return app.run(id, params) }; + if let Some(props) = params.as_object() { + for (key, value) in props { + p[key] = value.clone(); + } + } + app.run(id, p) + } + "type.editText" => { + crate::type_tool::edit_active(app)?; + if let Some(focus) = ctx.memory(|m| m.focused()) { + ctx.memory_mut(|m| m.surrender_focus(focus)); + } + Ok(Value::Null) + } + // Only interactive creation opens the Color Picker; it creates the layer on OK, + // so Cancel leaves neither an orphan layer nor an undo/redo history entry. + // Explicit parameters continue straight to the engine. + "layer.newFillLayer.solidColor" if params.as_object().is_none_or(|o| o.is_empty()) => { + let dialog = crate::solid_fill_ui::open_new(app).ok_or("no document is open")?; + Ok(json!({"dialog": dialog})) + } + // Solid Color fills and solid-colour shapes use the Color Picker, Pattern fills the Pattern + // Fill dialog; other adjustment / fill / shape controls use Properties. + "layer.layerContentOptions" => { + if let Some(dialog) = crate::solid_fill_ui::open(app).or_else(|| crate::shape_fill_ui::open(app)) { + return Ok(json!({"dialog": dialog})); + } + if let Some(dialog) = crate::pattern_fill_ui::open(app) { + return Ok(json!({"dialog": dialog})); + } + let r = app.run(id, params)?; + app.ui.panels.properties = true; + app.ui.dock_tabs.properties = 0; + Ok(r) + } + // Edit › Stroke…: open its full options dialog when called from menus/context + // menus. Explicit params from Actions, CLI, MCP and control channel execute directly. + crate::stroke_ui::COMMAND if params.as_object().is_none_or(|o| o.is_empty()) => { + if let Some(Err(why)) = photocraft_engine::commands::find(id).map(|c| (c.enabled)(&app.session)) { + return Err(why); + } + Ok(json!({"dialog": crate::stroke_ui::open(app)})) + } + // Channels › Channel Options… without params: the dialog on the targeted alpha/spot + // channel, Layer Mask Display Options on a targeted layer mask, or Quick Mask Options while + // in Quick Mask (with params: the engine directly). + crate::channel_options_ui::COMMAND if params.as_object().is_none_or(|o| o.is_empty()) => { + let mask = app.layer_mask_targeted(); + let st = app.session.active().ok_or("no document is open")?; + let channel = match st.channel_view.target { + _ if st.doc.quick_mask.is_some() => json!("quickMask"), + photocraft_engine::channel_cmds::ChannelTarget::Alpha(i) => json!(i), + _ if mask => json!("mask"), + _ => return Err("target an alpha or spot channel, or a layer mask, first".into()), + }; + let dialog = crate::channel_options_ui::open(app, &channel).ok_or("no such channel")?; + Ok(json!({"dialog": dialog})) + } + // Channels › New Spot Channel… without params: its dialog (with params: the engine). + crate::channel_options_ui::NEW_SPOT if params.as_object().is_none_or(|o| o.is_empty()) => { + let dialog = crate::channel_options_ui::open_new_spot(app).ok_or("no document is open")?; + Ok(json!({"dialog": dialog})) + } + // Photoshop's "Select and Mask…" is the engine's select.refineEdge. + // Select › Color Range… from the menu: the dialog (with params: the engine directly). + "select.colorRange" if params.as_object().is_none_or(|o| o.is_empty()) => Ok(json!({"dialog": crate::color_range_ui::open(app)})), + // Layer › New Fill Layer › Pattern… from the menu: the Pattern Fill dialog (with params: + // the engine directly). + photocraft_engine::pattern_fill_cmds::CREATE if params.as_object().is_none_or(|o| o.is_empty()) => { + Ok(json!({"dialog": crate::pattern_fill_ui::open_new(app)?})) + } + // Edit › Fill… from the menu or its shortcuts: the Fill dialog (with params: the engine). + crate::fill_ui::COMMAND if params.as_object().is_none_or(|o| o.is_empty()) => { + if let Some(Err(why)) = photocraft_engine::commands::find(id).map(|c| (c.enabled)(&app.session)) { + return Err(why); + } + Ok(json!({"dialog": crate::fill_ui::open(app)})) + } + "select.selectAndMask" => Ok(json!({"dialog": crate::filter_dialog::open(app, "select.refineEdge")})), + // Select › Transform Selection from the menu: the interactive box (with params: the engine). + "select.transformSelection" if params.as_object().is_none_or(|o| o.is_empty()) => { + crate::transform_tool::begin_selection(app, ctx).map(|_| json!({"transform": app.ui.transform})) + } + // While editing type, the clipboard rows and Select > All work on the text (#1355, #2893). + "edit.cut" if app.ui.text_edit.is_some() => { + crate::type_tool::cut_selection(app, ctx); + Ok(Value::Null) + } + "edit.copy" if app.ui.text_edit.is_some() => { + crate::type_tool::copy_selection(app, ctx); + Ok(Value::Null) + } + "edit.paste" if app.ui.text_edit.is_some() => { + crate::type_tool::request_paste(ctx); + Ok(Value::Null) + } + "select.all" if app.ui.text_edit.is_some() => { + crate::type_tool::select_all(app); + Ok(Value::Null) + } + "edit.paste" if params.as_object().is_none_or(|o| o.is_empty()) => { + // Photoshop: paste in place when the copied area is visible, else centred in the view; + // images from other apps are always centred. + app.import_os_clipboard()?; + app.clip_read_for_paste = true; + let external = app.clip_external; + let visible = !external + && app.session.active_index().zip(app.session.clipboard.as_ref()).is_some_and(|(i, clip)| { + let v = &app.ui.views[i]; + let pz = app.point_zoom(); + let (hw, hh) = (app.last_canvas_rect.width() / 2.0 / pz / app.ui.view.display_aspect(), app.last_canvas_rect.height() / 2.0 / pz); + let r = + photocraft_geom::Rect::new((v.center[0] - hw) as i32, (v.center[1] - hh) as i32, (v.center[0] + hw) as i32, (v.center[1] + hh) as i32); + !clip.bounds.intersect(&r).is_empty() + }); + let p = match app.session.active_index() { + Some(i) if !visible => json!({"center": app.ui.views[i].center}), + _ => json!({}), + }; + app.run("edit.paste", p) + } + "view.rulers" | "view.show.grid" | "view.show.guides" | "view.snap" | "view.lockGuides" => { + let e = &mut app.ui.extras; + let slot = match id { + "view.rulers" => &mut e.rulers, + "view.show.grid" => &mut e.grid, + "view.show.guides" => &mut e.guides, + "view.snap" => &mut e.snap, + _ => &mut e.lock_guides, + }; + *slot = !*slot; + let on = *slot; + if id == "view.show.grid" && on { + // Like the other Show items, enabling Grid also restores hidden Extras. + app.ui.view.extras = true; + } + if id == "view.rulers" { + crate::prefs_ui::remember_rulers(app, on); + } + Ok(json!(on)) + } + "edit.freeTransform" + | "edit.transform.scale" + | "edit.transform.rotate" + | "edit.transform.skew" + | "edit.transform.distort" + | "edit.transform.perspective" => { + // While a box is up, Scale / Rotate / Skew / Distort / Perspective (and Free Transform) + // switch its mode; otherwise they start one in that mode. + if app.ui.transform.as_ref().is_some_and(|t| t.content_aware.is_some()) { + return Err(crate::transform_tool::CAS_ONLY_SCALES.into()); + } + if app.ui.transform.is_none() { + crate::transform_tool::begin(app, ctx)?; + } + if let Some(t) = app.ui.transform.as_mut() { + t.mode = crate::state::TransformMode::for_command(id); + } + Ok(json!({"transform": app.ui.transform})) + } + "edit.freeTransformCopy" => crate::transform_tool::begin_copy(app, ctx).map(|_| json!({"transform": app.ui.transform})), + // Edit › Transform › Warp from the menu: interactive Warp mode (with params: the engine). + "edit.transform.warp" | "layer.smartObjects.warp" if params.as_object().is_none_or(|o| o.is_empty()) => { + crate::transform_tool::begin_warp(app, ctx).map(|_| json!({"transform": app.ui.transform})) + } + // Split warps edit the mesh of an active Warp session. + "edit.transform.splitWarpCrosswise" + | "edit.transform.splitWarpHorizontally" + | "edit.transform.splitWarpVertically" + | "edit.transform.removeWarpSplit" + if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_some()) && params.get("warp").is_none() => + { + let at = params.get("at").and_then(Value::as_array).and_then(|a| Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?])); + crate::transform_tool::split(app, id, at).map(|_| json!({"transform": app.ui.transform})) + } + "edit.transform.warpGrid" if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_some()) && params.get("warp").is_none() => { + crate::transform_tool::edit_session_warp(app, id, ¶ms).map(|_| json!({"transform": app.ui.transform})) + } + // Layer › New › Layer… (⇧⌘N) asks first, as in Photoshop; with params it runs as is. + crate::new_layer_ui::COMMAND if params.as_object().is_none_or(|o| o.is_empty()) => Ok(json!({"dialog": crate::new_layer_ui::open(app)?})), + sz if crate::sizing::is_sizing(sz) && params.as_object().is_none_or(|o| o.is_empty()) => { + Ok(json!({"dialog": crate::sizing::open(app, sz).ok_or("no document")?})) + } + "view.newGuide" if params.as_object().is_none_or(|o| o.is_empty()) => Ok(json!({"dialog": crate::new_guide_ui::open(app)})), + fl if crate::filter_dialog::has_dialog(fl) && params.as_object().is_none_or(|o| o.is_empty()) => { + Ok(json!({"dialog": crate::filter_dialog::open(app, fl)})) + } + a if crate::adjust_dialog::has_dialog(a) && params.as_object().is_none_or(|o| o.is_empty()) => { + Ok(json!({"dialog": crate::adjust_dialog::open(app, a).ok_or("no document")?})) + } + "window.togglePanels" => { + // Tab hides the Tools panel, the options bar and the dock; Tab again shows what it hid. + if app.ui.view.hides_chrome() { + // Full Screen Mode: Tab only shows or hides the chrome for now (#6760); the panels' + // own state, `hidden_by_tab` included, stays as it was before entering. + app.ui.panels.full_screen_chrome = !app.ui.panels.full_screen_chrome; + return Ok(Value::Null); + } + let p = &mut app.ui.panels; + match p.hidden_by_tab.take() { + Some([toolbar, options, dock]) if !(p.toolbar || p.options_bar || p.dock) => { + (p.toolbar, p.options_bar, p.dock) = (toolbar, options, dock); + } + _ if p.toolbar || p.options_bar || p.dock => { + p.hidden_by_tab = Some([p.toolbar, p.options_bar, p.dock]); + (p.toolbar, p.options_bar, p.dock) = (false, false, false); + } + _ => (p.toolbar, p.options_bar, p.dock) = (true, true, true), + } + Ok(Value::Null) + } + "window.nextDocument" | "window.previousDocument" => { + // Tabs are in document order, so the next tab is the next document, wrapping around. + let n = app.session.documents().len(); + let at = app.session.active_index().ok_or("no document open")?; + let to = if id == "window.nextDocument" { (at + 1) % n } else { (at + n - 1) % n }; + app.session.set_active(to); + app.jobs.focus = None; + Ok(json!({"document": to})) + } + id if let Some(index) = id.strip_prefix(DOCUMENT_ITEM) => { + let n = app.session.documents().len(); + let to = index.parse::().ok().filter(|i| *i < n).ok_or("no such document")?; + app.session.set_active(to); + app.jobs.focus = None; + Ok(json!({"document": to})) + } + t if t.starts_with("window.toggle.") => { + // A shown but collapsed dock group is expanded rather than hidden (#129). + if let Some(g) = crate::dock::Group::from_key(&t["window.toggle.".len()..]).filter(|g| g.shown(&app.ui.panels) && app.ui.dock.is_collapsed(*g)) { + crate::dock::reveal(app, g); + return Ok(Value::Null); + } + let p = &mut app.ui.panels; + let slot = match &t["window.toggle.".len()..] { + "layers" => &mut p.layers, + "history" => &mut p.history, + "properties" => &mut p.properties, + "color" => &mut p.color, + "navigator" => &mut p.navigator, + "toolbar" => &mut p.toolbar, + "options" => &mut p.options_bar, + "brushSettings" => &mut p.brush_settings, + "brushes" => &mut p.brushes, + "dock" => &mut p.dock, + _ => return Err(format!("unknown panel in {t}")), + }; + *slot = !*slot; + if let Some(g) = crate::dock::Group::from_key(&t["window.toggle.".len()..]).filter(|g| g.shown(&app.ui.panels)) { + crate::dock::reveal(app, g); + } + Ok(Value::Null) + } + // Layer › Layer Style › … opens the Layer Style dialog on that effect. + ls if params.as_object().is_none_or(|o| o.is_empty()) + && ls.strip_prefix("layer.layerStyle.").is_some_and(|k| crate::layer_style::KINDS.iter().any(|(kind, _)| *kind == k)) => + { + let kind = &ls["layer.layerStyle.".len()..]; + crate::layer_style::open(app, Some(kind)).map(|d| json!({"dialog": d})).ok_or_else(|| "no active layer".to_string()) + } + _ => app.run(id, params), + } +} + +fn open_path(app: &mut PhotocraftApp, path: &str) -> Result { + app.open_path(path).map(|w| json!({"warnings": w})) +} + +/// Workspace presets (Window → Workspace): which panels are visible. +pub fn apply_workspace(app: &mut PhotocraftApp) { + // Saved workspaces (Window › Workspace › New Workspace…) restore their own layout. + if crate::workspace_ui::apply_custom(app) { + return; + } + // Presets use the default group order, heights and tabs (Reset brings everything back). + app.ui.dock = Default::default(); + app.ui.docking_reveal = None; + app.ui.docking_generation = app.ui.docking_generation.wrapping_add(1); + app.ui.docking = None; + app.ui.docking_kept = None; + app.ui.docking_returns.clear(); + app.ui.docking_collapsed.clear(); + app.ui.dock_tabs = Default::default(); + let p = &mut app.ui.panels; + let (nav, color, layers, history, props) = match app.ui.workspace.as_str() { + "Photography" => (true, false, true, true, true), + "Painting" => (false, true, true, false, false), + // Leave room for typography alongside Properties and Layers. + "Graphic and Web" => (false, false, true, false, true), + // Color includes Swatches; Navigator keeps the pixel canvas easy to inspect. + "Pixel Art" => (true, true, true, false, false), + "Motion" => (false, false, true, false, true), + _ => (false, true, true, false, true), + }; + p.navigator = nav; + p.color = color; + p.layers = layers; + p.history = history; + p.properties = props; + p.character = app.ui.workspace == "Graphic and Web"; + // Timeline is a floating panel, not a dock group. Showing it does not create or edit + // a document timeline; changing away from Motion closes it just like its Close button. + app.ui.timeline.open = app.ui.workspace == "Motion"; + if !app.ui.timeline.open { + app.ui.timeline.playing = false; + } +} diff --git a/crates/ui-egui/src/menus/items.rs b/crates/ui-egui/src/menus/items.rs new file mode 100644 index 0000000000..e5b029136d --- /dev/null +++ b/crates/ui-egui/src/menus/items.rs @@ -0,0 +1,275 @@ +use super::invoke::{panel_alias, proof_preset, workspace_name}; +use super::state::{checked, is_enabled, reveal_label}; +use super::*; + +/// Menu tree entry for rendering and for `ui.inspect`. +#[derive(Clone, Debug, serde::Serialize)] +pub struct MenuItem { + pub id: String, + pub label: String, + pub path: Vec, + pub shortcut: Option, + pub enabled: bool, + pub checked: Option, + /// Edit › Menus colour (red, orange, …). + #[serde(skip_serializing_if = "Option::is_none")] + pub color: Option, +} + +/// Is `id` implemented by the engine or the shell (a live menu item)? Shared by the menus and +/// the parity report ([`crate::parity`]). +pub fn is_live(id: &str) -> bool { + static UI_IDS: std::sync::OnceLock> = std::sync::OnceLock::new(); + photocraft_engine::commands::find(id).is_some() + || crate::tool_shortcuts::tool(id).is_some() + || UI_IDS.get_or_init(|| UI_COMMANDS.iter().map(|c| c.0).collect()).contains(id) + || panel_alias(id).is_some() + || workspace_name(id).is_some() + || proof_preset(id).is_some() + || id == "view.proofSetup.custom" + || crate::view_cmds::handles(id) + || crate::analysis_ui::handles(id) + || crate::workspace_ui::handles(id) + || crate::preset_panels::handles(id) + || crate::type_panels_ui::handles(id) + || crate::timeline_ui::handles(id) +} + +/// Commands outside the catalogue that belong right after a catalogue item: `(id, after)`. +/// The command takes that item's submenu path, so it joins Photoshop's submenu even where the +/// catalogue spells it differently (Filter › "Other…"). +const PLACE_AFTER: &[(&str, &str)] = &[ + ("file.newFromClipboard", "file.new"), + ("filter.render.relight", "filter.render.lightingEffects"), + ("view.resetView", "view.flipHorizontal"), + ("filter.other.colorToAlpha", "filter.other.offset"), +]; + +pub fn menu_items(app: &PhotocraftApp) -> Vec { + // 1) Photoshop's full menu tree, in Photoshop order; live where we implement the command. + let known = is_live; + let mut items: Vec = crate::menu_catalog::CATALOG + .iter() + .map(|&(path, label, sc, id)| MenuItem { + id: id.to_string(), + label: label.to_string(), + path: path.iter().map(|s| s.to_string()).collect(), + // A live item shows the shortcut that runs it ([`crate::shortcut_dispatch::bindings`] + // prefers the command's own over the catalogue's): Undo ⌘Z, Copy ⌘C, Hide Layers ⌘,. + shortcut: if known(id) { crate::shortcuts::default_shortcut(id) } else { sc.map(Into::into) }, + enabled: known(id) && is_enabled(app, id), + checked: checked(app, id), + color: None, + }) + .collect(); + // 2) Our commands that Photoshop's tree doesn't list (or lists under another id). + let mut extra: Vec = Vec::new(); + for &(id, label, path, sc) in UI_COMMANDS { + extra.push(MenuItem { + id: id.into(), + label: label.into(), + path: path.iter().map(|s| s.to_string()).collect(), + shortcut: sc.map(Into::into), + enabled: is_enabled(app, id), + checked: checked(app, id), + color: None, + }); + } + for c in photocraft_engine::command_specs().iter().filter(|c| !c.menu.is_empty()) { + extra.push(MenuItem { + id: c.id.into(), + label: c.label.into(), + path: c.menu.iter().map(|s| s.to_string()).collect(), + shortcut: c.shortcut.map(Into::into), + enabled: is_enabled(app, c.id), + checked: None, + color: None, + }); + } + for mut e in extra { + let dup = items.iter().any(|i| i.id == e.id || (i.path == e.path && i.label.trim_end_matches('…') == e.label.trim_end_matches('…'))); + if !dup { + // Insert after the item it belongs next to, else after the last item of the same + // top-level menu, keeping menus contiguous. + let top = e.path.first().cloned(); + let after = PLACE_AFTER.iter().find(|(id, _)| *id == e.id).and_then(|(_, a)| items.iter().position(|i| i.id == *a)); + if let Some(path) = after.and_then(|a| items.get(a)).map(|i| i.path.clone()) { + e.path = path; + } + let at = after.or_else(|| items.iter().rposition(|i| i.path.first() == top.as_ref())).map_or(items.len(), |p| p + 1); + items.insert(at, e); + } + } + crate::plugin_ui::insert_menu_items(app, &mut items); + if let Some(mask) = app.session.active().and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id))).and_then(|l| l.mask.as_ref()) + && let Some(item) = items.iter_mut().find(|i| i.id == "layer.layerMask.enabled") + { + item.label = crate::layer_menu_ui::mask_toggle_label(mask.enabled).into(); + } + // Layer › Merge Layers reads Merge Group with just a group selected, as in Photoshop (#3832). + if let Some(st) = app.session.active() + && st.selected_layers().len() <= 1 + && st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| matches!(l.content, photocraft_doc::LayerContent::Group(_))) + && let Some(item) = items.iter_mut().find(|i| i.id == "layer.mergeLayers") + { + item.label = "Merge Group".into(); + } + // The File quick-export command uses the format selected in Export Preferences. + // On the web it intentionally downloads PNG until the quick-export service supports + // the other formats; the Layer quick-export command also always produces PNG. + if let Some(item) = items.iter_mut().find(|i| i.id == "file.export.quickExportAsPng") { + use photocraft_engine::prefs::QuickExportFormat; + let format = if cfg!(target_arch = "wasm32") { + "PNG" + } else { + match app.session.prefs().export.quick_export_format { + QuickExportFormat::Png => "PNG", + QuickExportFormat::Jpg => "JPG", + QuickExportFormat::Gif => "GIF", + QuickExportFormat::Webp => "WebP", + QuickExportFormat::Exr => "EXR", + } + }; + item.label = format!("Quick Export as {format}"); + } + // Smart Objects › Reveal in Finder names this platform's file manager (UI-217-19). + if let Some(item) = items.iter_mut().find(|i| i.id == "layer.smartObjects.revealInFinder") { + item.label = reveal_label().into(); + } + // File › Open Recent: a dynamic submenu of recently opened files (inserted after "Open As…"). + if let Some(after) = items.iter().position(|i| i.id == "file.openAs") { + let rp: Vec = vec!["File".into(), "Open Recent".into()]; + let mut recent: Vec = app + .ui + .recent_files + .iter() + .enumerate() + .map(|(i, p)| { + let label = std::path::Path::new(p).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.clone()); + MenuItem { id: format!("file.openRecent.{i}"), label, path: rp.clone(), shortcut: None, enabled: true, checked: None, color: None } + }) + .collect(); + if !recent.is_empty() { + recent.push(MenuItem { id: "---".into(), label: "---".into(), path: rp.clone(), shortcut: None, enabled: false, checked: None, color: None }); + } + recent.push(MenuItem { + id: "file.clearRecent".into(), + label: "Clear Recent Files".into(), + path: rp.clone(), + shortcut: None, + enabled: !app.ui.recent_files.is_empty(), + checked: None, + color: None, + }); + for (k, it) in recent.into_iter().enumerate() { + items.insert(after + 1 + k, it); + } + } + // Window › Workspace: saved workspaces follow the presets, checked while current. + let saved = crate::workspace_ui::saved_names(app); + if !saved.is_empty() + && let Some(after) = items.iter().position(|i| i.id == "window.workspace.motion") + { + let wp: Vec = vec!["Window".into(), "Workspace".into()]; + let separator = MenuItem { id: "---".into(), label: "---".into(), path: wp.clone(), shortcut: None, enabled: false, checked: None, color: None }; + let entries = saved.into_iter().enumerate().map(|(i, name)| { + let id = format!("{}{i}", crate::workspace_ui::SAVED); + let checked = checked(app, &id); + MenuItem { id, label: name, path: wp.clone(), shortcut: None, enabled: true, checked, color: None } + }); + for (k, it) in std::iter::once(separator).chain(entries).enumerate() { + items.insert(after + 1 + k, it); + } + } + // Keep the update command with the links, ahead of System Info and About. + if let Some(at) = items.iter().position(|i| i.id == "help.checkForUpdates") { + let update = items.remove(at); + let before = items.iter().position(|i| i.id == "help.systemInfo" || i.id == "help.about").unwrap_or(items.len()); + items.insert(before, update); + } + // Help: the link items and update check, a separator, then System Info and About. + if let Some(at) = items.iter().position(|i| i.id == "help.systemInfo" || i.id == "help.about") { + items.insert( + at, + MenuItem { id: "---".into(), label: "---".into(), path: vec!["Help".into()], shortcut: None, enabled: false, checked: None, color: None }, + ); + } + // Window: the open documents in tab order, after a separator, the active one checked. + if let Some(last) = items.iter().rposition(|i| i.path.first().map(String::as_str) == Some("Window")) { + let window = || vec!["Window".to_string()]; + let active = app.session.active_index(); + let docs = app.session.documents().iter().enumerate().map(|(i, st)| MenuItem { + id: format!("{DOCUMENT_ITEM}{i}"), + label: st.doc.name.clone(), + path: window(), + shortcut: None, + enabled: true, + checked: Some(active == Some(i)), + color: None, + }); + let separator = MenuItem { id: "---".into(), label: "---".into(), path: window(), shortcut: None, enabled: false, checked: None, color: None }; + let rows: Vec = std::iter::once(separator).chain(docs).collect(); + if rows.len() > 1 { + items.splice(last + 1..last + 1, rows); + } + } + // Edit › Keyboard Shortcuts overrides, Edit › Menus hidden items and colours. + let prefs = app.session.prefs(); + if !prefs.shortcuts.is_empty() { + for it in &mut items { + if prefs.shortcuts.contains_key(&it.id) { + it.shortcut = prefs.shortcut(&it.id, None).map(str::to_string); + } + } + } + if !prefs.menus.hidden.is_empty() { + items.retain(|i| !prefs.menus.is_hidden(&i.id)); + } + if prefs.interface.show_menu_colors { + for it in &mut items { + it.color = prefs.menus.colors.get(&it.id).cloned(); + } + } + // Layer › Create Clipping Mask is Photoshop's one Create / Release item: when its shortcut + // would release ([`crate::shortcut_dispatch::clip_key_releases`]) it reads Release Clipping + // Mask and runs it, keeping that shortcut. The engine's own Release item lives in that slot. + items.retain(|i| i.id != "layer.releaseClippingMask"); + if crate::shortcut_dispatch::clip_key_releases(app) + && let Some(item) = items.iter_mut().find(|i| i.id == "layer.createClippingMask") + { + item.id = "layer.releaseClippingMask".into(); + item.label = "Release Clipping Mask".into(); + item.enabled = is_enabled(app, &item.id); + } + items +} + +/// Background tint of an Edit › Menus colour name. +pub(super) fn menu_tint(name: &str) -> Option { + Some(match name { + "red" => egui::Color32::from_rgb(190, 60, 60), + "orange" => egui::Color32::from_rgb(200, 120, 40), + "yellow" => egui::Color32::from_rgb(190, 170, 40), + "green" => egui::Color32::from_rgb(60, 150, 70), + "blue" => egui::Color32::from_rgb(50, 110, 200), + "violet" => egui::Color32::from_rgb(130, 80, 190), + "gray" => egui::Color32::from_rgb(120, 120, 120), + _ => return None, + }) +} + +/// The open menus' items, kept between frames: building them asks every command whether it can +/// run, which on a document with thousands of layers costs far more than a frame. +pub(crate) struct ItemCache { + /// [`crate::native_menu::state_hash`] of the state the items were built from. + pub(super) state: u64, + pub(super) items: Vec, +} + +impl ItemCache { + /// The items, while they still describe `state`. A frame with a click or key press rebuilds + /// them, which covers state the hash doesn't list. + pub(super) fn reuse(self, state: u64, input: bool) -> Option> { + (!input && self.state == state).then_some(self.items) + } +} diff --git a/crates/ui-egui/src/menus/render.rs b/crates/ui-egui/src/menus/render.rs new file mode 100644 index 0000000000..82a824cf48 --- /dev/null +++ b/crates/ui-egui/src/menus/render.rs @@ -0,0 +1,152 @@ +use super::bar::released_on; +use super::items::{MenuItem, menu_tint}; +use super::state::translated_menu_label; + +pub(super) fn render_level(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, clicked: &mut Option, nav: &mut crate::menu_nav::Nav) { + // Menu popups can be taller than the window: each level stays on screen and scrolls (wheel, + // scroll arrows, keyboard), like a native menu on a small display. + crate::menu_nav::level(ui, depth, nav, |ui, nav| render_level_rows(ui, items, depth, clicked, nav)); +} + +/// Height of a menu separator: a line with room above and below, as in native menus. +const MENU_SEPARATOR: f32 = 9.0; + +pub(super) fn render_level_rows(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, clicked: &mut Option, nav: &mut crate::menu_nav::Nav) { + let lang = crate::i18n::current(); + // Items never wrap: the menu widens to its longest label plus shortcut (translations can be + // longer than the English). + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + // Rows touch, as in native menus: the dialog spacing between them made long menus a fifth + // taller than they need to be (#402). + ui.spacing_mut().item_spacing.y = 0.0; + // Secondary menus use the exact same Spectrum hover contrast and spacing. + crate::widgets::style_spectrum_popup_menu(ui); + // Walk in Photoshop order: leaves and separators at this depth; a submenu appears at the position + // of its first child. + // Each row's mnemonic (#4988), unique within this level, in display order: the leaves' labels + // and the submenus' names as shown. + // A label with no Latin letter shows its English label's key after it: "新建(N)…" (#5863). + let (translated, english): (Vec, Vec<&str>) = { + let mut subs: Vec<&str> = Vec::new(); + items + .iter() + .filter_map(|it| { + if it.path.len() == depth { + (it.label != "---").then(|| (translated_menu_label(lang, it), it.label.as_str())) + } else { + let name = it.path.get(depth).map(String::as_str)?; + (!subs.contains(&name)).then(|| { + subs.push(name); + (crate::i18n::tr(lang, name).to_string(), name) + }) + } + }) + .unzip() + }; + let (shown_labels, mnemonics) = crate::menu_keys::localized(&translated, &english, &[]); + let mut next_row = 0usize; + let mut shown_subs: Vec<&str> = Vec::new(); + let mut last_was_sep = true; + for (i, it) in items.iter().enumerate() { + if it.path.len() == depth { + if it.label == "---" { + if !last_was_sep && i + 1 < items.len() { + ui.add(egui::Separator::default().spacing(MENU_SEPARATOR)); + last_was_sep = true; + } + continue; + } + let label = shown_labels.get(next_row).cloned().unwrap_or_else(|| translated_menu_label(lang, it)); + let mnemonic = mnemonics.get(next_row).copied().flatten(); + next_row += 1; + // Checked, unchecked and plain rows share one checkmark column (#5705). + let text = crate::menu_keys::menu_row_text(ui, it.checked == Some(true), &label, mnemonic.filter(|_| nav.underline)); + let mut b = egui::Button::new(text); + if let Some(tint) = it.color.as_deref().and_then(menu_tint) { + b = b.fill(tint.gamma_multiply(0.55)); + } + if let Some(sc) = &it.shortcut { + b = b.shortcut_text(crate::shortcuts::pretty(sc)); + } + let hit = nav.row(ui, depth - 1, it.enabled, Some(&it.id), mnemonic, |ui, _| { + let r = ui.add_enabled(it.enabled, b); + let r = match it.id.as_str() { + "image.mode.bits8" | "image.mode.bits16" => r.on_hover_text(crate::i18n::tr(lang, "Integer")), + "image.mode.bits32" => r.on_hover_text(crate::i18n::tr(lang, "Floating point")), + _ => r, + }; + let hit = r.clicked() || released_on(ui, &r); + (r, hit) + }); + if hit { + *clicked = Some(it.id.clone()); + ui.close(); + } + last_was_sep = false; + } else if it.path.len() > depth { + let name = it.path[depth].as_str(); + if shown_subs.contains(&name) { + continue; + } + shown_subs.push(name); + let child: Vec<&MenuItem> = items.iter().copied().filter(|c| c.path.len() > depth && c.path[depth] == name).collect(); + let enabled = submenu_enabled(&child); + let mnemonic = mnemonics.get(next_row).copied().flatten(); + let shown = shown_labels.get(next_row).cloned().unwrap_or_else(|| crate::i18n::tr(lang, name).to_string()); + next_row += 1; + let title = crate::menu_keys::menu_row_text(ui, false, &shown, mnemonic.filter(|_| nav.underline)); + ui.add_enabled_ui(enabled, |ui| { + nav.row(ui, depth - 1, enabled, None, mnemonic, |ui, nav| { + let (response, inner) = submenu_row(ui, title, |ui| render_level(ui, &child, depth + 1, clicked, nav)); + if inner.is_some() { + // Where the submenu hangs from, to keep it below the menu bar (#319). + nav.set_anchor(depth, response.rect); + } + (response, ()) + }); + }); + last_was_sep = false; + } + } +} + +/// A submenu row, drawn as `ui.menu_button` draws it, except that a row scrolled out of view +/// doesn't open its submenu. egui opens a submenu whenever the pointer is over its row, clipped +/// or not: a menu reopened scrolled down (after Edit › Preferences or Window › Theme) has rows +/// hidden above its view, over the menu bar, and the hidden one under the title opened on the +/// press; the release on the title then counted as a click outside that submenu and closed the +/// whole menu (#5896, #6225). An open submenu (e.g. opened from the keyboard) is drawn as usual. +fn submenu_row(ui: &mut egui::Ui, title: egui::WidgetText, content: impl FnOnce(&mut egui::Ui) -> R) -> (egui::Response, Option) { + use egui::containers::menu::{MenuState, SubMenu, SubMenuButton}; + let sub = SubMenu::id_from_widget_id(ui.next_auto_id()); + let open = MenuState::from_ui(ui, |state, _| state.open_item == Some(sub)); + let inactive = ui.style().visuals.widgets.inactive; + if open { + ui.style_mut().visuals.widgets.inactive = ui.style().visuals.widgets.open; + } + let response = ui.add(egui::Button::new(title).right_text(SubMenuButton::arrow_atom(None))); + ui.style_mut().visuals.widgets.inactive = inactive; + // The rect egui tests the pointer against (`SubMenu::show`), against the part that can be seen. + let reach = response.rect.expand2(ui.spacing().item_spacing / 2.0); + let hidden = ui.ctx().pointer_hover_pos().is_some_and(|p| reach.contains(p) && !ui.clip_rect().contains(p)); + if hidden && !open { + return (response, None); + } + let inner = SubMenu::new().show(ui, &response, content); + (response, inner.map(|r| r.inner)) +} + +/// A submenu header is enabled only while some item under it (at any depth) can run, so a +/// submenu of greyed items is greyed too instead of opening onto them (#1976). +pub(super) fn submenu_enabled(children: &[&MenuItem]) -> bool { + children.iter().any(|c| c.enabled && c.label != "---") +} + +/// The command a menu click runs: ⌥ + Merge Down / Merge Layers / Merge Visible keep the +/// originals, running Stamp Down / Stamp Visible instead (#217). +pub fn alt_click(id: String, alt: bool) -> String { + match photocraft_engine::stamp_cmds::alt_variant(&id) { + Some(stamp) if alt => stamp.to_string(), + _ => id, + } +} diff --git a/crates/ui-egui/src/menus/search.rs b/crates/ui-egui/src/menus/search.rs new file mode 100644 index 0000000000..a1eed7981c --- /dev/null +++ b/crates/ui-egui/src/menus/search.rs @@ -0,0 +1,98 @@ +use super::bar::released_on; +use super::items::MenuItem; +use super::state::translated_menu_label; + +/// Most results the Help menu search lists. +pub(super) const HELP_SEARCH_MAX: usize = 15; + +/// How well `query` (lowercase) matches a menu item: its label starting with it, then a word of +/// the label starting with it, then anywhere in the label, then anywhere in its menu path. +/// `None` when it doesn't match at all. +pub fn search_rank(query: &str, label: &str, path: &[String]) -> Option { + let l = label.to_lowercase(); + if l.starts_with(query) { + Some(0) + } else if l.split(|c: char| !c.is_alphanumeric()).any(|w| w.starts_with(query)) { + Some(1) + } else if l.contains(query) { + Some(2) + } else if path.iter().any(|p| p.to_lowercase().contains(query)) { + Some(3) + } else { + None + } +} + +/// Menu items matching `query`, best first (Photoshop order within a rank). Both the English +/// labels and their `lang` translations match, so a search works in the UI language and in +/// English; untranslated strings are simply their English text. +pub fn search_items<'a>(items: &'a [MenuItem], query: &str, lang: crate::i18n::Lang) -> Vec<&'a MenuItem> { + let q = query.trim().to_lowercase(); + if q.is_empty() { + return Vec::new(); + } + let rank = |it: &MenuItem| { + let english = search_rank(&q, &it.label, &it.path); + let path: Vec = it.path.iter().map(|p| crate::i18n::tr(lang, p).to_string()).collect(); + let local = search_rank(&q, &translated_menu_label(lang, it), &path); + english.into_iter().chain(local).min() + }; + let mut hits: Vec<(u8, usize, &MenuItem)> = + items.iter().enumerate().filter(|(_, it)| it.label != "---").filter_map(|(i, it)| rank(it).map(|r| (r, i, it))).collect(); + hits.sort_by_key(|(r, i, _)| (*r, *i)); + let mut seen = std::collections::HashSet::new(); + hits.into_iter().filter(|(_, _, it)| seen.insert(it.id.as_str())).take(HELP_SEARCH_MAX).map(|(_, _, it)| it).collect() +} + +/// Help › Search : a field at the top of the Help menu that finds any menu command +/// by name. Results show their menu path; click, ↓ then ↩, or ↩ in the field runs one. +/// `opening`: this frame's release ends the click on the Help title that opened the menu. +pub(super) fn help_search(ui: &mut egui::Ui, items: &[MenuItem], opening: bool, clicked: &mut Option, nav: &mut crate::menu_nav::Nav) { + let ctx = ui.ctx().clone(); + let lang = crate::i18n::current(); + let text_id = egui::Id::unique("help-menu-search"); + let pass_id = text_id.with("pass"); + // A fresh opening of the Help menu starts empty, with the field focused. + let pass = ctx.cumulative_pass_nr(); + let reopened = ctx.data(|d| d.get_temp::(pass_id)).is_none_or(|p| p + 1 < pass); + ctx.data_mut(|d| d.insert_temp(pass_id, pass)); + let mut query: String = if reopened { String::new() } else { ctx.data(|d| d.get_temp(text_id)).unwrap_or_default() }; + let field = ui.add(egui::TextEdit::singleline(&mut query).id(text_id.with("field")).hint_text(crate::i18n::tr(lang, "Search menus")).desired_width(220.0)); + // The menu opens on the press; the release a frame later completes a click on the title, + // outside the field, and egui takes the focus away from it again (#1447, #1438). + if reopened || opening { + field.request_focus(); + } + let results = search_items(items, &query, lang); + if field.lost_focus() + && ui.input(|i| i.key_pressed(egui::Key::Enter)) + && let Some(it) = results.iter().find(|it| it.enabled) + { + *clicked = Some(it.id.clone()); + ui.close(); + } + ctx.data_mut(|d| d.insert_temp(text_id, query.clone())); + if !query.trim().is_empty() { + if results.is_empty() { + ui.weak(crate::i18n::tr(lang, "No matching commands")); + } + for it in results { + let mut trail: Vec = it.path.iter().map(|p| crate::i18n::tr(lang, p).to_string()).collect(); + trail.push(translated_menu_label(lang, it)); + let mut b = egui::Button::new(trail.join(" › ")); + if let Some(sc) = &it.shortcut { + b = b.shortcut_text(crate::shortcuts::pretty(sc)); + } + let hit = nav.row(ui, 0, it.enabled, Some(&it.id), None, |ui, _| { + let r = ui.add_enabled(it.enabled, b); + let hit = r.clicked() || released_on(ui, &r); + (r, hit) + }); + if hit { + *clicked = Some(it.id.clone()); + ui.close(); + } + } + } + ui.separator(); +} diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs new file mode 100644 index 0000000000..754f14d8ce --- /dev/null +++ b/crates/ui-egui/src/menus/state.rs @@ -0,0 +1,230 @@ +use super::invoke::{panel_alias, proof_preset, workspace_name}; +use super::items::MenuItem; +use super::*; + +pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { + if crate::tool_shortcuts::tool(id).is_some() { + return true; + } + if id == "ui.symmetryTransform" { + return crate::symmetry_ui::can_transform(app); + } + // Draft Pen points can be undone even when the document has no History entries. + if id == "edit.undo" && app.ui.pen.as_ref().is_some_and(|pen| !pen.knots.is_empty()) { + return true; + } + // Photoshop greys these for the Background layer, other layer kinds or single-layer documents. + if crate::enable_rules::disabled(app, id) { + return false; + } + // A pending crop greys what Photoshop greys during one (#1918). + if crate::crop_ui::blocks(app, id) { + return false; + } + // Filters stay live on a type layer: choosing one asks to rasterize it (#4303). + if crate::rasterize_prompt::filter_needs(app, id).is_some() { + return true; + } + if let Some(e) = crate::workspace_ui::is_enabled(app, id) { + return e; + } + if crate::analysis_ui::handles(id) { + return true; + } + if crate::preset_panels::handles(id) || crate::type_panels_ui::handles(id) || crate::timeline_ui::handles(id) { + return true; + } + if let Some(e) = crate::view_cmds::is_enabled(app, id) { + return e; + } + if let Some(e) = crate::plugin_ui::is_enabled(app, id) { + return e; + } + if let Some(e) = crate::transform_tool::is_enabled(app, id) { + return e; + } + if let Some(e) = crate::crop_ui::is_enabled(app, id) { + return e; + } + match id { + "window.panel.activate" | "window.panel.layout" | "ui.dock" => true, + "window.panel.group" + | "window.panel.move" + | "window.panel.float" + | "window.panel.window" + | "window.panel.dock" + | "window.panel.close" + | "window.panel.closeGroup" + | "window.panel.closeOthers" + | "window.panel.minimize" + | "window.panel.iconic" => !app.session.prefs().workspace_locked, + "file.open" | "file.exit" | "file.clearRecent" | "file.removeRecent" | "help.about" | "help.systemInfo" | "edit.search" => true, + i if i.starts_with("file.openRecent.") => true, + i if i.starts_with(DOCUMENT_ITEM) => true, + i if crate::links::url_for(i).is_some() => true, + i if i.starts_with("window.theme.") => true, + // Interface brightness works with or without a document, as in Photoshop. + "view.darkenInterface" | "view.lightenInterface" => true, + "file.save" | "file.saveAs" | "file.export.exportAs" | "file.export.quickExportAsPng" => { + app.session.active().is_some() && app.services.export.is_some() + } + i if i.starts_with("window.toggle.") => true, + "window.togglePanels" => true, + // With one document open the key stays quiet, as in Photoshop, rather than reporting why. + "window.nextDocument" | "window.previousDocument" => app.session.active().is_some(), + i if panel_alias(i).is_some() || workspace_name(i).is_some() => true, + i if proof_preset(i).is_some() => app.session.active().is_some(), + // "Custom…" is the full Proof Setup dialog. + "view.proofSetup.custom" => app.session.active().is_some(), + "view.rulers" | "view.show.grid" | "view.show.guides" | "view.snap" | "view.lockGuides" => true, + "edit.cut" | "edit.copy" if app.ui.text_edit.is_some() => crate::type_tool::selected_range(app).is_some(), + "edit.paste" | "select.all" if app.ui.text_edit.is_some() => true, + // An image copied in another app can only be seen by reading the OS clipboard, which happens + // on an explicit paste: with a clipboard service these stay enabled. Paste and New from + // Clipboard need no document (with none open, Paste makes one); Paste in Place does. + "edit.paste" | "file.newFromClipboard" => app.session.is_enabled(id) || app.services.clipboard_get_image.is_some(), + "edit.pasteSpecial.pasteInPlace" => app.session.is_enabled(id) || (app.services.clipboard_get_image.is_some() && app.session.active().is_some()), + "select.selectAndMask" => app.session.is_enabled("select.refineEdge"), + "type.editText" => app + .session + .active() + .and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id))) + .is_some_and(|l| matches!(l.content, photocraft_doc::LayerContent::Text(_))), + "select.transformSelection" => app.ui.transform.is_none() && app.session.is_enabled("select.transformSelection"), + // ⇧[ / ⇧] only step the hardness of a tool that paints with the brush tip, as in Photoshop. + "tools.decreaseBrushHardness" | "tools.increaseBrushHardness" => app.ui.tool.is_brushlike(), + i if (i.starts_with("view.zoom") || i == "view.fitOnScreen" || i == "view.actualPixels") || i == "window.newWindowForDocument" => { + app.session.active().is_some() + } + "edit.freeTransformCopy" => app.ui.transform.is_none() && app.session.active().and_then(|s| s.active_layer).is_some(), + "edit.freeTransform" + | "edit.transform.scale" + | "edit.transform.rotate" + | "edit.transform.skew" + | "edit.transform.distort" + | "edit.transform.perspective" => match &app.ui.transform { + Some(t) => t.warp.is_none(), + None => app.session.active().and_then(|s| s.active_layer).is_some(), + }, + // A targeted layer mask enables what edits it (Invert on an adjustment layer's mask). + i => app.session.is_enabled_with(i, &app.with_mask_target(i, Value::Null)), + } +} + +/// Image › Mode items that carry a checkmark. +const MODE_CHECKS: [&str; 11] = ["rgb", "grayscale", "cmyk", "lab", "multichannel", "indexedColor", "bitmap", "duotone", "bits8", "bits16", "bits32"]; + +/// Is a UI-level panel toggle currently on (for checkmarks)? +pub(super) fn checked(app: &PhotocraftApp, id: &str) -> Option { + if let Some(checked) = crate::panel_docking::checked(app, id) { + return Some(checked); + } + use photocraft_doc::{ColorMode, SampleType}; + if let Some(name) = id.strip_prefix("window.theme.").filter(|n| *n != "toggle") { + let auto = app.session.prefs().interface.appearance_mode == photocraft_engine::prefs::AppearanceMode::Auto; + return Some(if name == "system" { auto } else { !auto && crate::theme::ThemeKind::from_name(name) == Some(app.ui.theme) }); + } + if let Some(c) = crate::view_cmds::checked(app, id) { + return Some(c); + } + if let Some(c) = crate::analysis_ui::checked(app, id).or_else(|| crate::workspace_ui::checked(app, id)).or_else(|| crate::file_ui::checked(app, id)) { + return Some(c); + } + if let Some(c) = crate::preset_panels::checked(app, id) { + return Some(c); + } + if let Some(c) = crate::timeline_ui::checked(app, id) { + return Some(c); + } + if let Some(c) = crate::type_panels_ui::checked(app, id) { + return Some(c); + } + if let Some(alias) = panel_alias(id) { + return checked(app, alias); + } + // Check items stay check items with no document open (`Some(false)`, not `None`): a native + // menu can't change an item's kind in place, so a change would rebuild the whole menu. + if id == "select.isolateLayers" { + return Some(app.session.active().is_some_and(|d| !d.isolated_layers.is_empty())); + } + 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); + return Some(if id == "view.proofColors" { pv.enabled } else { pv.gamut_warning }); + } + if id.starts_with("window.workspace.") && id != "window.workspace.resetWorkspace" { + let want = workspace_name(id)?; + return Some(app.ui.workspace == if want.is_empty() { "Essentials" } else { want }); + } + if let Some(m) = id.strip_prefix("image.mode.") { + let Some(d) = app.session.active().map(|s| &s.doc) else { + return MODE_CHECKS.contains(&m).then_some(false); + }; + return match m { + "rgb" => Some(d.mode == ColorMode::Rgb), + "grayscale" => Some(d.mode == ColorMode::Grayscale), + "cmyk" => Some(d.mode == ColorMode::Cmyk), + "lab" => Some(d.mode == ColorMode::Lab), + "multichannel" => Some(d.mode == ColorMode::Multichannel), + "indexedColor" => Some(d.mode == ColorMode::Indexed), + "bitmap" => Some(d.mode == ColorMode::Bitmap), + "duotone" => Some(d.mode == ColorMode::Duotone), + "bits8" => Some(d.depth == SampleType::U8), + "bits16" => Some(d.depth == SampleType::U16), + "bits32" => Some(d.depth == SampleType::F32), + _ => None, + }; + } + let e = &app.ui.extras; + match id { + "view.rulers" => return Some(e.rulers), + "view.show.grid" => return Some(e.grid), + "view.show.guides" => return Some(e.guides), + "view.snap" => return Some(e.snap), + "view.lockGuides" => return Some(e.lock_guides), + _ => {} + } + let p = &app.ui.panels; + Some(match id { + "window.toggle.layers" => p.layers, + "window.toggle.history" => p.history, + "window.toggle.properties" => p.properties, + "window.toggle.color" => p.color, + "window.toggle.navigator" => p.navigator, + "window.toggle.toolbar" => p.toolbar, + "window.toggle.dock" => p.dock, + "window.togglePanels" => p.toolbar || p.options_bar || p.dock, + "window.toggle.options" => p.options_bar, + "window.toggle.brushSettings" => p.brush_settings, + "window.toggle.brushes" => p.brushes, + _ => return None, + }) +} + +/// "Reveal in Finder" named after the file manager the engine opens on this platform (UI-217-19): +/// Explorer on Windows, a plain folder elsewhere (xdg-open, the web). English action key; each +/// display translates it. +pub(crate) fn reveal_label() -> &'static str { + if cfg!(target_os = "macos") { + "Reveal in Finder" + } else if cfg!(windows) { + "Show in Explorer" + } else { + "Show in Folder" + } +} + +/// Translate the fixed command label and substitute the currently configured export format. +/// Reuse the existing translated PNG sentence, so dynamic formats work in every UI language. +pub(super) fn translated_menu_label(lang: crate::i18n::Lang, item: &MenuItem) -> String { + // A document's name is shown as it is. + if item.id.starts_with(DOCUMENT_ITEM) { + return item.label.clone(); + } + if item.id == "file.export.quickExportAsPng" + && let Some(fmt) = item.label.strip_prefix("Quick Export as ") + { + return crate::i18n::tr_id(lang, &item.id, "Quick Export as PNG").replace("PNG", fmt); + } + crate::i18n::tr_id(lang, &item.id, &item.label).to_string() +} From 41bbcd58e33731a216ae714884e15b6e9b1d07d8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:09:44 +0000 Subject: [PATCH 220/259] refactor(ui-egui): split state.rs into state/ --- crates/ui-egui/src/state.rs | 1223 +--------------------- crates/ui-egui/src/state/color_panel.rs | 120 +++ crates/ui-egui/src/state/panel_state.rs | 126 +++ crates/ui-egui/src/state/tool.rs | 321 ++++++ crates/ui-egui/src/state/tool_options.rs | 468 +++++++++ crates/ui-egui/src/state/transform.rs | 182 ++++ 6 files changed, 1231 insertions(+), 1209 deletions(-) create mode 100644 crates/ui-egui/src/state/color_panel.rs create mode 100644 crates/ui-egui/src/state/panel_state.rs create mode 100644 crates/ui-egui/src/state/tool.rs create mode 100644 crates/ui-egui/src/state/tool_options.rs create mode 100644 crates/ui-egui/src/state/transform.rs diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d9bad0e07c..ef587063cb 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -3,450 +3,21 @@ use serde::{Deserialize, Serialize}; -/// Photoshop-style Layers panel display preferences; part of serialized UI state. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum LayerThumbnailSize { - None, - Small, - #[default] - Medium, - Large, -} +mod color_panel; +mod panel_state; +mod tool; +mod tool_options; +mod transform; -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "camelCase")] -pub enum LayerThumbnailContents { - LayerBounds, - #[default] - EntireDocument, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct LayersPanelOptions { - pub thumbnail_size: LayerThumbnailSize, - /// Thumbnail Contents in the Panel Options dialog. Not saved with these options: the dialog - /// shows and sets `interface.clipThumbnailsToLayerBounds` (Layer Bounds = clipped, #4281), - /// which the panel menu's Clip Thumbnails to Layer Bounds toggles too. - #[serde(skip)] - pub thumbnail_contents: LayerThumbnailContents, - pub show_filters: bool, - pub use_default_masks_on_fill_layers: bool, - pub expand_new_effects: bool, - pub add_copy_to_copied_layers_and_groups: bool, - pub preview_on_canvas_when_reordering_layers: bool, - pub show_layer_mask_badges: bool, -} - -impl LayersPanelOptions { - /// Every option at the Photoshop default: Medium thumbnails, filters shown, new effects expanded, no mask badges. - pub fn defaults() -> Self { - Self { - thumbnail_size: LayerThumbnailSize::Medium, - thumbnail_contents: LayerThumbnailContents::EntireDocument, - show_filters: true, - use_default_masks_on_fill_layers: true, - expand_new_effects: true, - add_copy_to_copied_layers_and_groups: true, - preview_on_canvas_when_reordering_layers: true, - show_layer_mask_badges: false, - } - } -} - -impl Default for LayersPanelOptions { - /// Same as [`LayersPanelOptions::defaults`], so serde fills missing fields with the Photoshop defaults. - fn default() -> Self { - Self::defaults() - } -} - -/// Pending dialog data is transient: Cancel never changes persisted options. -#[derive(Clone, Debug, PartialEq)] -pub enum LayersPanelDialog { - PanelOptions(LayersPanelOptions), - NewLayer(String), - NewGroup(String), - LockLayers { transparency: bool, pixels: bool, position: bool, artboard: bool, all: bool }, -} - -/// Shared selection and capture for a point curve; document parameters remain with the host. -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", default)] -pub struct PointCurveState { - pub selected: Option, - /// Captured point (None while removed outside), grab offset, and re-entry eligibility. - pub drag: Option, -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", default)] -pub struct PointCurveDrag { - pub index: Option, - pub offset: [f32; 2], - pub removed: bool, -} - -/// Curves editor memory (egui temp data): the edited channel and the point gesture. -#[derive(Clone, Copy, Debug, Default)] -pub struct CurvesEditorState { - pub channel: usize, - pub gesture: PointCurveState, -} - -/// Camera Raw scope preferences are view state, never filter parameters or document history. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", default)] -pub struct CameraRawScopeState { - pub shadows: bool, - pub highlights: bool, - pub lab: bool, - pub sampler_tool: bool, - pub samplers: Vec<[f32; 2]>, - pub vectorscope: bool, - pub selected_region: bool, - pub red_right: bool, - pub hide_skin_line: bool, - pub floating: bool, - pub floating_rect: Option<[f32; 4]>, -} - -/// Camera Raw navigation, separate from filter settings. Reset for each opened image. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", default)] -pub struct CameraRawPreviewState { - /// None fits the image; Some is physical display pixels per source pixel. - pub zoom: Option, - pub center: [f32; 2], - pub hand: bool, -} - -impl Default for CameraRawPreviewState { - fn default() -> Self { - Self { zoom: None, center: [0.5, 0.5], hand: false } - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum Tool { - Move, - Artboard, - RectMarquee, - EllipseMarquee, - /// Selects one pixel row across the whole canvas at the clicked y (Photoshop's flyout only: - /// no key, not in the ⇧M cycle). - SingleRowMarquee, - /// Selects one pixel column down the whole canvas at the clicked x. - SingleColumnMarquee, - Lasso, - PolygonLasso, - MagneticLasso, - MagicWand, - Crop, - PerspectiveCrop, - Eyedropper, - ColorSampler, - Ruler, - Note, - Count, - Brush, - Pencil, - MixerBrush, - ColorReplacement, - Eraser, - BackgroundEraser, - MagicEraser, - Gradient, - PaintBucket, - Type, - VerticalType, - /// Horizontal Type Mask: types a selection in the shape of the glyphs, no type layer. - HorizontalTypeMask, - VerticalTypeMask, - Hand, - RotateView, - Zoom, - Remove, - SpotHealing, - Healing, - Patch, - ContentAwareMove, - RedEye, - CloneStamp, - PatternStamp, - HistoryBrush, - ArtHistoryBrush, - Blur, - Sharpen, - Smudge, - Dodge, - Burn, - Sponge, - QuickSelection, - ObjectSelection, - Pen, - FreeformPen, - CurvaturePen, - AddAnchorPoint, - DeleteAnchorPoint, - /// Converts an anchor between smooth and corner, and pulls handles out of a corner - /// (Photoshop's Convert Point tool; also the Pen's ⌥ mode, `direct_select.rs`). - ConvertPoint, - PathSelection, - DirectSelection, - Rectangle, - EllipseShape, - Triangle, - Polygon, - Line, - CustomShape, - Slice, - SliceSelect, - Frame, -} - -impl Tool { - pub const ALL: [Tool; 68] = [ - Tool::Move, - Tool::Artboard, - Tool::RectMarquee, - Tool::EllipseMarquee, - Tool::SingleRowMarquee, - Tool::SingleColumnMarquee, - Tool::Lasso, - Tool::PolygonLasso, - Tool::MagneticLasso, - Tool::MagicWand, - Tool::Crop, - Tool::PerspectiveCrop, - Tool::Eyedropper, - Tool::ColorSampler, - Tool::Ruler, - Tool::Note, - Tool::Count, - Tool::Brush, - Tool::Pencil, - Tool::MixerBrush, - Tool::ColorReplacement, - Tool::Eraser, - Tool::BackgroundEraser, - Tool::MagicEraser, - Tool::Gradient, - Tool::PaintBucket, - Tool::Type, - Tool::VerticalType, - Tool::HorizontalTypeMask, - Tool::VerticalTypeMask, - Tool::Hand, - Tool::RotateView, - Tool::Zoom, - Tool::Remove, - Tool::SpotHealing, - Tool::Healing, - Tool::Patch, - Tool::ContentAwareMove, - Tool::RedEye, - Tool::CloneStamp, - Tool::PatternStamp, - Tool::HistoryBrush, - Tool::ArtHistoryBrush, - Tool::Blur, - Tool::Sharpen, - Tool::Smudge, - Tool::Dodge, - Tool::Burn, - Tool::Sponge, - Tool::QuickSelection, - Tool::ObjectSelection, - Tool::Pen, - Tool::FreeformPen, - Tool::CurvaturePen, - Tool::AddAnchorPoint, - Tool::DeleteAnchorPoint, - Tool::ConvertPoint, - Tool::PathSelection, - Tool::DirectSelection, - Tool::Rectangle, - Tool::EllipseShape, - Tool::Triangle, - Tool::Polygon, - Tool::Line, - Tool::CustomShape, - Tool::Slice, - Tool::SliceSelect, - Tool::Frame, - ]; - - pub fn label(self) -> &'static str { - match self { - Tool::Move => "Move Tool", - Tool::Artboard => "Artboard Tool", - Tool::RectMarquee => "Rectangular Marquee Tool", - Tool::EllipseMarquee => "Elliptical Marquee Tool", - Tool::SingleRowMarquee => "Single Row Marquee Tool", - Tool::SingleColumnMarquee => "Single Column Marquee Tool", - Tool::Brush => "Brush Tool", - Tool::Pencil => "Pencil Tool", - Tool::MixerBrush => "Mixer Brush Tool", - Tool::ColorReplacement => "Color Replacement Tool", - Tool::Eraser => "Eraser Tool", - Tool::BackgroundEraser => "Background Eraser Tool", - Tool::MagicEraser => "Magic Eraser Tool", - Tool::Eyedropper => "Eyedropper Tool", - Tool::ColorSampler => "Color Sampler Tool", - Tool::Ruler => "Ruler Tool", - Tool::Note => "Note Tool", - Tool::Count => "Count Tool", - Tool::Lasso => "Lasso Tool", - Tool::PolygonLasso => "Polygonal Lasso Tool", - Tool::MagneticLasso => "Magnetic Lasso Tool", - Tool::MagicWand => "Magic Wand Tool", - Tool::Crop => "Crop Tool", - Tool::PerspectiveCrop => "Perspective Crop Tool", - Tool::Slice => "Slice Tool", - Tool::SliceSelect => "Slice Select Tool", - Tool::Frame => "Frame Tool", - Tool::Gradient => "Gradient Tool", - Tool::PaintBucket => "Paint Bucket Tool", - Tool::Type => "Horizontal Type Tool", - Tool::VerticalType => "Vertical Type Tool", - Tool::HorizontalTypeMask => "Horizontal Type Mask Tool", - Tool::VerticalTypeMask => "Vertical Type Mask Tool", - Tool::Hand => "Hand Tool", - Tool::RotateView => "Rotate View Tool", - Tool::Zoom => "Zoom Tool", - Tool::Remove => "Remove Tool", - Tool::SpotHealing => "Spot Healing Brush Tool", - Tool::Healing => "Healing Brush Tool", - Tool::Patch => "Patch Tool", - Tool::ContentAwareMove => "Content-Aware Move Tool", - Tool::RedEye => "Red Eye Tool", - Tool::CloneStamp => "Clone Stamp Tool", - Tool::PatternStamp => "Pattern Stamp Tool", - Tool::HistoryBrush => "History Brush Tool", - Tool::ArtHistoryBrush => "Art History Brush Tool", - Tool::Blur => "Blur Tool", - Tool::Sharpen => "Sharpen Tool", - Tool::Smudge => "Smudge Tool", - Tool::Dodge => "Dodge Tool", - Tool::Burn => "Burn Tool", - Tool::Sponge => "Sponge Tool", - Tool::QuickSelection => "Quick Selection Tool", - Tool::ObjectSelection => "Object Selection Tool", - Tool::Pen => "Pen Tool", - Tool::FreeformPen => "Freeform Pen Tool", - Tool::CurvaturePen => "Curvature Pen Tool", - Tool::AddAnchorPoint => "Add Anchor Point Tool", - Tool::DeleteAnchorPoint => "Delete Anchor Point Tool", - Tool::ConvertPoint => "Convert Point Tool", - Tool::PathSelection => "Path Selection Tool", - Tool::DirectSelection => "Direct Selection Tool", - Tool::Rectangle => "Rectangle Tool", - Tool::EllipseShape => "Ellipse Tool", - Tool::Triangle => "Triangle Tool", - Tool::Polygon => "Polygon Tool", - Tool::Line => "Line Tool", - Tool::CustomShape => "Custom Shape Tool", - } - } - pub fn is_type(self) -> bool { - matches!(self, Self::Type | Self::VerticalType | Self::HorizontalTypeMask | Self::VerticalTypeMask) - } - /// The Type Mask tools: their text becomes a selection on commit. - pub fn is_type_mask(self) -> bool { - matches!(self, Self::HorizontalTypeMask | Self::VerticalTypeMask) - } - /// Type tools that lay text out vertically. - pub fn is_vertical_type(self) -> bool { - matches!(self, Self::VerticalType | Self::VerticalTypeMask) - } - - /// Retouching and painting tools that stroke with the brush (share the brush cursor and chip). - pub fn is_brushlike(self) -> bool { - matches!( - self, - Tool::Brush - | Tool::Pencil - | Tool::MixerBrush - | Tool::ColorReplacement - | Tool::Eraser - | Tool::BackgroundEraser - | Tool::Remove - | Tool::SpotHealing - | Tool::Healing - | Tool::CloneStamp - | Tool::PatternStamp - | Tool::HistoryBrush - | Tool::ArtHistoryBrush - | Tool::Blur - | Tool::Sharpen - | Tool::Smudge - | Tool::Dodge - | Tool::Burn - | Tool::Sponge - ) - } - /// Photoshop default single-key shortcut (`'\0'` = none, e.g. the Blur group). - pub fn key(self) -> char { - match self { - Tool::Move | Tool::Artboard => 'V', - Tool::RectMarquee | Tool::EllipseMarquee => 'M', - Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::ColorReplacement => 'B', - Tool::Eraser | Tool::BackgroundEraser | Tool::MagicEraser => 'E', - Tool::Eyedropper | Tool::ColorSampler | Tool::Ruler | Tool::Note | Tool::Count => 'I', - Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso => 'L', - Tool::MagicWand => 'W', - Tool::Crop | Tool::PerspectiveCrop | Tool::Slice | Tool::SliceSelect => 'C', - Tool::Frame => 'K', - Tool::Gradient | Tool::PaintBucket => 'G', - Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => 'T', - Tool::Hand => 'H', - Tool::RotateView => 'R', - Tool::Zoom => 'Z', - Tool::Remove | Tool::SpotHealing | Tool::Healing | Tool::Patch | Tool::ContentAwareMove | Tool::RedEye => 'J', - Tool::CloneStamp | Tool::PatternStamp => 'S', - Tool::HistoryBrush | Tool::ArtHistoryBrush => 'Y', - Tool::Blur | Tool::Sharpen | Tool::Smudge => '\0', - // In the Marquee flyout, but M cycles only the Rectangular and Elliptical Marquee. - Tool::SingleRowMarquee | Tool::SingleColumnMarquee => '\0', - Tool::Dodge | Tool::Burn | Tool::Sponge => 'O', - Tool::QuickSelection | Tool::ObjectSelection => 'W', - Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint => 'P', - Tool::PathSelection | Tool::DirectSelection => 'A', - Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line | Tool::CustomShape => 'U', - } - } - /// Glyph drawn in the toolbar (vector icons come later). - pub fn glyph(self) -> &'static str { - match self { - Tool::Move => "✥", - Tool::RectMarquee => "⬚", - Tool::EllipseMarquee => "◌", - Tool::Brush => "🖌", - Tool::MixerBrush => "🖌", - Tool::Eraser => "⌫", - Tool::Eyedropper => "💧", - Tool::ColorSampler => "◎", - Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso => "L", - Tool::MagicWand => "W", - Tool::Crop => "C", - Tool::Gradient | Tool::PaintBucket => "G", - Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => "T", - Tool::Hand => "✋", - Tool::RotateView => "🧭", - Tool::Zoom => "🔍", - _ => "•", - } - } - pub fn from_name(s: &str) -> Option { - let n = s.to_ascii_lowercase().replace([' ', '_', '-'], ""); - Tool::ALL.into_iter().find(|t| { - let a = format!("{t:?}").to_ascii_lowercase(); - n == a || n == a.replace("marquee", "") || n == t.label().to_ascii_lowercase().replace(' ', "") - }) - } -} +pub use color_panel::{ColorPanelMode, ColorPanelState, ColorRamp, DockTabs}; +pub use panel_state::{ + CameraRawPreviewState, CameraRawScopeState, CurvesEditorState, LayerThumbnailContents, LayerThumbnailSize, LayersPanelDialog, LayersPanelOptions, + PointCurveDrag, PointCurveState, +}; +pub use tool::Tool; +pub use tool_options::{SampleAllLayers, ToolOptions}; +use tool_options::{default_brush_tool, default_layer_filter_mode, yes}; +pub use transform::{BoxResize, CamTransform, ContentAwareOptions, Extras, MadeLayer, TextEdit, TransformMode, TransformSession, TypeTransform}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Panels { @@ -623,772 +194,6 @@ pub struct DocWindow { pub position: Option<[f32; 2]>, } -/// Options-bar state for tools (Photoshop keeps these per tool). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct ToolOptions { - pub tolerance: f32, - pub contiguous: bool, - pub anti_alias: bool, - /// Sample All Layers, kept per tool as in Photoshop (#5524). Stored under a new key, so the - /// single shared `sample_all_layers` of older preferences is ignored on load. - pub sample_all: SampleAllLayers, - /// Object Selection › Object Finder: hovering highlights the object a click selects (#4087). - pub object_finder: bool, - /// Remove tool: the fill goes to a new layer above the target (Photoshop's Create a new layer). - pub remove_new_layer: bool, - /// Remove tool: each stroke is filled when released (Photoshop's default). Off, the strokes - /// collect as a tint on the canvas and ↩ applies them together (Esc drops them). - pub remove_after_each_stroke: bool, - pub feather: f32, - /// linear | radial | angle | reflected | diamond - pub gradient_style: String, - pub gradient_reverse: bool, - /// Gradient tool: dither to reduce 8-bit banding (Photoshop default on). - pub gradient_dither: bool, - /// Gradient tool mode: false = "Gradient" (live: a Gradient Fill layer, editable on canvas), - /// true = "Classic gradient" (paints the pixels). - pub gradient_classic: bool, - /// Blend mode used by both live and classic gradient drags. - pub gradient_blend_mode: photocraft_color::BlendMode, - pub fill_opacity: f32, - /// Paint Bucket fill source: false = Foreground colour, true = Pattern (Patterns panel selection). - pub bucket_fill_pattern: bool, - /// Paint Bucket › Mode (any layer mode; Clear is `bucket_clear`). - pub bucket_blend_mode: photocraft_color::BlendMode, - /// Paint Bucket › Mode: Clear, which erases the filled area (see `brush_clear`). - pub bucket_clear: bool, - /// Type tool: family, style name, size (pt), anti-aliasing and paragraph alignment. - pub type_font: String, - pub type_style: String, - pub type_size: f32, - pub type_aa: String, - pub type_align: String, - /// Character/Paragraph panel defaults beyond the options bar, in `type.setStyle`'s - /// parameter format. Kept as overrides so saved engine defaults still supply unset fields. - /// OpenType features and variable-font axes are merged per tag/axis. - #[serde(default)] - pub type_style_defaults: serde_json::Map, - /// Type tool: paragraph direction of new type, "auto" (from the first strong character), - /// "ltr" or "rtl" (TYPE-218-2). - pub type_direction: String, - /// Clone Stamp / Healing Brush. - pub clone_aligned: bool, - /// Pattern Stamp: lock the tile origin in document space across strokes. - pub pattern_stamp_aligned: bool, - /// Pattern Stamp: jitter each dab's phase (seeded, replayable). - pub pattern_stamp_impressionist: bool, - /// Pattern Stamp scale %, 1..1000 (100 = the tile's native size). - pub pattern_stamp_scale: f32, - /// Pattern Stamp rotation in degrees (counter-clockwise). - pub pattern_stamp_angle: f32, - /// current | currentAndBelow | all - pub clone_sample: String, - /// Spot Healing: contentAware | createTexture | proximityMatch - pub spot_type: String, - /// Patch: source (repair the selection) | destination (repair where it is dragged). - pub patch_mode: String, - /// Patch: Content-Aware instead of Normal, with its Structure 1..7 and Color 0..10. - pub patch_content_aware: bool, - pub patch_structure: f32, - pub patch_color: f32, - /// Content-Aware Move: move | extend, Structure 1..7, Color 0..10. - 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). - pub cam_transform_on_drop: bool, - /// Dodge/Burn: shadows | midtones | highlights, exposure %, protect tones. - pub tone_range: String, - pub exposure: f32, - pub protect_tones: bool, - /// Sponge: desaturate | saturate, vibrance. - pub sponge_mode: String, - pub vibrance: bool, - /// Blur/Sharpen/Smudge strength %, Sharpen protect detail, Smudge finger painting. - pub strength: f32, - pub protect_detail: bool, - pub finger_painting: bool, - /// Quick Selection enhance edge. - pub enhance_edge: bool, - /// Pen: "path" (work path) or "shape" (shape layer). - pub vector_mode: String, - /// Shape tools: fill with the foreground colour, stroke width (0 = none), rectangle corner - /// radius, polygon sides, line weight. - pub shape_fill: bool, - pub stroke_width: f32, - #[serde(default)] - pub shape_stroke: crate::shape_stroke_ui::StrokeOptions, - /// Shape tools: the gradient the next shape's fill / stroke takes (the swatches' Gradient - /// tab) instead of the foreground / background colour; `None` = the colour. - pub shape_fill_gradient: Option, - pub shape_stroke_gradient: Option, - pub corner_radius: f32, - pub polygon_sides: u32, - pub line_weight: f32, - /// Freeform Pen › Curve Fit: how far (px) the fitted path may stray from the pointer trace. - #[serde(default = "default_curve_fit")] - pub curve_fit: f32, - /// Pen › Auto Add/Delete: a Pen click on a segment of the active path adds an anchor there, - /// on one of its anchors deletes it (#4144). - #[serde(default = "yes")] - pub pen_auto_add_delete: bool, - /// Marquee options bar: "normal" | "fixedRatio" | "fixedSize", with the ratio or size. - #[serde(default = "default_marquee_style")] - pub marquee_style: String, - #[serde(default = "one")] - pub marquee_width: f32, - #[serde(default = "one")] - pub marquee_height: f32, - /// The unit Fixed Size's Width and Height show (a [`photocraft_engine::prefs::Unit`] name, - /// picked by right-clicking them); the size itself stays in pixels (#7910). - #[serde(default = "default_marquee_unit")] - pub marquee_unit: String, - /// Slice tool options bar: the same Styles as the marquee's, with the ratio or the size in px - /// (#8360). - #[serde(default = "default_marquee_style")] - pub slice_style: String, - #[serde(default = "one")] - pub slice_width: f32, - #[serde(default = "one")] - pub slice_height: f32, - /// Move tool: Auto-Select (with "layer" or "group" target) and Show Transform Controls. - /// Auto-Select is on with the "group" target by default, as in current Photoshop; - /// ⌘/Ctrl-click inverts it. - #[serde(default = "yes")] - pub move_auto_select: bool, - #[serde(default = "default_move_target")] - pub move_target: String, - #[serde(default)] - pub move_show_transform: bool, - /// Crop options bar: aspect ratio ("" = Ratio/unconstrained, "w:h", or "original") and - /// Delete Cropped Pixels. - #[serde(default)] - pub crop_ratio: String, - /// In-progress custom crop ratio fields. Kept separately because entering one side before the - /// other must survive a frame while the ratio itself remains unconstrained. - #[serde(default)] - pub crop_custom_ratio_width: f32, - #[serde(default)] - pub crop_custom_ratio_height: f32, - #[serde(default = "yes")] - pub crop_delete: bool, - /// Crop options bar › Fill: false = Background (Default), true = Content-Aware Fill (the area a - /// rotated or extending crop uncovers is filled from its surroundings, #3823). - #[serde(default)] - pub crop_content_aware: bool, - /// Crop W x H x Resolution (`crop_ratio` = "whr", #2443): width and height as typed lengths - /// with their unit ("4 in", "1024 px"; empty = unset), the resolution ("" = the document's) - /// and its unit ("px/in" or "px/cm"). See `crop_size`. - #[serde(default)] - pub crop_width: String, - #[serde(default)] - pub crop_height: String, - #[serde(default)] - pub crop_resolution: String, - #[serde(default = "default_crop_resolution_unit")] - pub crop_resolution_unit: String, - /// Perspective Crop's Show Grid (`perspective_crop_ui`); it shares W, H and the resolution above. - #[serde(default = "yes")] - pub perspective_crop_grid: bool, - /// Crop overlay (#1919): the guide in the crop box, when it shows and its orientation - /// (Photoshop's defaults: Rule of Thirds, Auto Show Overlay). See `crop_overlay`. - #[serde(default)] - pub crop_overlay: crate::crop_overlay::CropOverlay, - #[serde(default)] - pub crop_overlay_show: crate::crop_overlay::OverlayShow, - #[serde(default)] - pub crop_overlay_orientation: u8, - /// Crop gear menu (#1919): Show Cropped Area and the crop shield. See `crop_shield`. - #[serde(default)] - pub crop_shield: crate::crop_shield::CropShield, - /// Magic Eraser opacity % (tolerance, anti-alias and contiguous are shared with the Magic Wand - /// and Paint Bucket). - pub magic_eraser_opacity: f32, - /// Background Eraser: sampling (continuous | once | backgroundSwatch), limits (discontiguous | - /// contiguous | findEdges), tolerance % and Protect Foreground Color. - pub bg_sampling: String, - pub bg_limits: String, - pub bg_tolerance: f32, - pub bg_protect_fg: bool, - /// Color Replacement: mode (hue | saturation | color | luminosity), sampling (continuous | - /// once | backgroundSwatch), limits (discontiguous | contiguous | findEdges), tolerance % and - /// anti-alias, as `paint.colorReplacement` takes them. - pub cr_mode: String, - pub cr_sampling: String, - pub cr_limits: String, - pub cr_tolerance: f32, - pub cr_anti_alias: bool, - /// Zoom tool › Scrubby Zoom: dragging left/right zooms continuously (else a zoom rectangle). - #[serde(default = "yes")] - pub zoom_scrubby: bool, - /// Pencil › Auto Erase: a stroke that starts on the foreground colour paints the background colour. - #[serde(default)] - pub pencil_auto_erase: bool, - /// Brush › Mode: Clear, which erases with the Brush (Photoshop's painting-only mode, #3439). - /// Not a blend mode, so it is kept beside the brush's `mode` rather than in it. - #[serde(default)] - pub brush_clear: bool, - /// Pencil › Mode: Clear (see `brush_clear`). - #[serde(default)] - pub pencil_clear: bool, - /// Eraser › Mode: `brush` (soft, anti-aliased) or `pencil` (hard, aliased pixels, through - /// `paint.pencil`), as in Photoshop's options bar (#2662). - #[serde(default = "default_eraser_mode")] - pub eraser_mode: String, - /// 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, - pub magnetic_contrast: f32, - pub magnetic_frequency: f32, - pub magnetic_pressure: bool, - /// Red Eye: pupil search size (1–100) and how far corrected pixels darken (0–100). - #[serde(default = "fifty")] - pub red_eye_pupil_size: f32, - #[serde(default = "fifty")] - pub red_eye_darken: f32, - /// Eyedropper › Sample Size: 1 = Point Sample, else the side of the averaged square (3, 5, - /// 11, 31, 51, 101; `photocraft_engine::sample_cmds::SAMPLE_SIZES`). Shared, as in Photoshop, - /// with the ⌥-click eyedropper of the painting tools, the dialog eyedroppers and the Info panel. - #[serde(default = "one_u32")] - pub eyedropper_size: u32, - /// Eyedropper › Sample: current | currentAndBelow | all | allNoAdjustments | - /// currentAndBelowNoAdjustments (`document.sampleColor`'s `sampleLayer`). - #[serde(default = "default_eyedropper_sample")] - pub eyedropper_sample: String, - /// Eyedropper › Show Sampling Ring. - #[serde(default = "yes")] - pub eyedropper_ring: bool, - /// Art History Brush: dab layout, Area (0–100), Tolerance (0–100). - #[serde(default = "default_art_history_style")] - pub art_history_style: String, - #[serde(default = "fifty")] - pub art_history_area: f32, - #[serde(default)] - pub art_history_tolerance: f32, -} - -fn default_art_history_style() -> String { - "tightMedium".into() -} - -fn yes() -> bool { - true -} - -fn default_crop_resolution_unit() -> String { - crate::crop_size::PX_PER_IN.into() -} - -fn default_move_target() -> String { - "group".into() -} - -fn default_curve_fit() -> f32 { - 2.0 -} - -fn default_eraser_mode() -> String { - "brush".into() -} - -fn default_marquee_style() -> String { - "normal".into() -} - -fn default_marquee_unit() -> String { - "pixels".into() -} - -fn one() -> f32 { - 1.0 -} - -fn fifty() -> f32 { - 50.0 -} - -/// The session brush starts out as the Brush's (the tool the app opens with). -fn default_brush_tool() -> Tool { - Tool::Brush -} - -fn default_layer_filter_mode() -> photocraft_color::BlendMode { - photocraft_color::BlendMode::Normal -} - -fn one_u32() -> u32 { - 1 -} - -fn default_eyedropper_sample() -> String { - "all".into() -} - -/// Each tool's Sample All Layers (the Paint Bucket calls it All Layers). Photoshop keeps one per -/// tool, all off by default: turning it on for the Magic Wand must not leave Blur or Smudge -/// copying the composite onto the active layer (#5524). The Mixer Brush keeps its own with the -/// brush (`MixerSettings`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default)] -pub struct SampleAllLayers { - pub magic_wand: bool, - pub quick_selection: bool, - pub object_selection: bool, - pub paint_bucket: bool, - pub magic_eraser: bool, - pub spot_healing: bool, - pub patch: bool, - pub content_aware_move: bool, - pub remove: bool, - pub blur: bool, - pub sharpen: bool, - pub smudge: bool, -} - -impl SampleAllLayers { - /// `tool`'s setting; false for a tool without the option. - pub fn get(mut self, tool: Tool) -> bool { - self.slot(tool).is_some_and(|v| *v) - } - - /// `tool`'s setting, or `None` for a tool without the option. - pub fn slot(&mut self, tool: Tool) -> Option<&mut bool> { - Some(match tool { - Tool::MagicWand => &mut self.magic_wand, - Tool::QuickSelection => &mut self.quick_selection, - Tool::ObjectSelection => &mut self.object_selection, - Tool::PaintBucket => &mut self.paint_bucket, - Tool::MagicEraser => &mut self.magic_eraser, - Tool::SpotHealing => &mut self.spot_healing, - Tool::Patch => &mut self.patch, - Tool::ContentAwareMove => &mut self.content_aware_move, - Tool::Remove => &mut self.remove, - Tool::Blur => &mut self.blur, - Tool::Sharpen => &mut self.sharpen, - Tool::Smudge => &mut self.smudge, - _ => return None, - }) - } -} - -impl Default for ToolOptions { - fn default() -> Self { - Self { - tolerance: 32.0, - contiguous: true, - anti_alias: true, - sample_all: SampleAllLayers::default(), - object_finder: true, - remove_new_layer: false, - remove_after_each_stroke: true, - feather: 0.0, - gradient_style: "linear".into(), - gradient_reverse: false, - gradient_dither: true, - gradient_classic: false, - gradient_blend_mode: photocraft_color::BlendMode::Normal, - fill_opacity: 100.0, - bucket_fill_pattern: false, - bucket_blend_mode: photocraft_color::BlendMode::Normal, - bucket_clear: false, - type_font: "Inter".into(), - type_style: "Regular".into(), - type_size: 48.0, - type_aa: "sharp".into(), - type_align: "left".into(), - type_style_defaults: serde_json::Map::new(), - type_direction: "auto".into(), - clone_aligned: true, - pattern_stamp_aligned: true, - pattern_stamp_impressionist: false, - pattern_stamp_scale: 100.0, - pattern_stamp_angle: 0.0, - clone_sample: "current".into(), - spot_type: "contentAware".into(), - patch_mode: "source".into(), - patch_content_aware: false, - patch_structure: 4.0, - patch_color: 0.0, - cam_mode: "move".into(), - cam_structure: 4.0, - cam_color: 0.0, - cam_transform_on_drop: false, - tone_range: "midtones".into(), - exposure: 50.0, - protect_tones: true, - sponge_mode: "desaturate".into(), - vibrance: true, - strength: 50.0, - protect_detail: true, - finger_painting: false, - enhance_edge: false, - vector_mode: "path".into(), - shape_fill: true, - stroke_width: 0.0, - shape_stroke: Default::default(), - shape_fill_gradient: None, - shape_stroke_gradient: None, - corner_radius: 0.0, - polygon_sides: 5, - line_weight: 3.0, - curve_fit: default_curve_fit(), - pen_auto_add_delete: true, - marquee_style: default_marquee_style(), - marquee_width: 1.0, - marquee_height: 1.0, - marquee_unit: default_marquee_unit(), - slice_style: default_marquee_style(), - slice_width: 1.0, - slice_height: 1.0, - move_auto_select: true, - move_target: default_move_target(), - move_show_transform: false, - crop_ratio: String::new(), - crop_custom_ratio_width: 0.0, - crop_custom_ratio_height: 0.0, - crop_delete: true, - crop_content_aware: false, - crop_width: String::new(), - crop_height: String::new(), - crop_resolution: String::new(), - crop_resolution_unit: default_crop_resolution_unit(), - perspective_crop_grid: true, - crop_overlay: Default::default(), - crop_overlay_show: Default::default(), - crop_overlay_orientation: 0, - crop_shield: Default::default(), - magic_eraser_opacity: 100.0, - bg_sampling: "continuous".into(), - bg_limits: "contiguous".into(), - bg_tolerance: 50.0, - bg_protect_fg: false, - cr_mode: "color".into(), - cr_sampling: "continuous".into(), - cr_limits: "contiguous".into(), - cr_tolerance: 30.0, - cr_anti_alias: true, - zoom_scrubby: true, - pencil_auto_erase: false, - brush_clear: false, - pencil_clear: false, - eraser_mode: default_eraser_mode(), - magnetic_width: 10.0, - magnetic_contrast: 10.0, - magnetic_frequency: 57.0, - magnetic_pressure: false, - red_eye_pupil_size: 50.0, - red_eye_darken: 50.0, - eyedropper_size: 1, - eyedropper_sample: default_eyedropper_sample(), - eyedropper_ring: true, - art_history_style: default_art_history_style(), - art_history_area: 50.0, - art_history_tolerance: 0.0, - } - } -} - -/// Edit › Transform's mode: what a handle drag does with no modifier keys held. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum TransformMode { - /// Free Transform and Scale: handles scale, drag outside rotates. - #[default] - Free, - /// Edit › Transform › Rotate: handle drags rotate about the reference point (#3941). - Rotate, - /// Edge and corner handles skew: each moves along one axis. - Skew, - /// Corner handles move freely, one at a time; nothing else moves them (no rotating, no - /// edges) and nothing snaps. - Distort, - /// Corner handles move in pairs, mirrored (one-point perspective). - Perspective, -} - -impl TransformMode { - /// The mode an `edit.transform.*` / `edit.freeTransform` menu id starts. - pub fn for_command(id: &str) -> Self { - match id { - "edit.transform.rotate" => Self::Rotate, - "edit.transform.skew" => Self::Skew, - "edit.transform.distort" => Self::Distort, - "edit.transform.perspective" => Self::Perspective, - _ => Self::Free, - } - } -} - -/// Free Transform in progress: the source frame `rect` and where its corners currently are. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct TransformSession { - pub session: u64, - pub layer: u64, - pub rect: [f64; 4], - /// Corners clockwise from top-left (document px). - pub quad: [[f64; 2]; 4], - /// Reference point (rotation / ⌥-scale centre). - pub pivot: [f64; 2], - pub interpolation: String, - /// Warp mode (Edit › Transform › Warp): the warp being edited over `rect`, in document px. - #[serde(default)] - pub warp: Option, - /// Select › Transform Selection: the box transforms the selection outline, not pixels. - #[serde(default)] - pub selection: bool, - /// `edit.transform`'s `"target"` when the box moves an unlinked layer mask, an alpha channel or - /// the Quick Mask by itself (`None`: the layer, with its linked masks). - #[serde(default)] - pub target: Option, - /// Free Transform Path: `path.transform`'s `name` (and `layer`) when the box moves a - /// path's anchors and handles instead of pixels. - #[serde(default)] - pub path: Option, - /// The layer was made for this session (⌥⌘T's copy, #352; a file dropped on the canvas), so - /// Cancel takes it back and OK folds it into one history step with the transform. - #[serde(default)] - pub made: Option, - /// Edit › Transform › Rotate / Skew / Distort / Perspective (`Free` for Free Transform and Scale). - #[serde(default)] - pub mode: TransformMode, - /// Edit › Content-Aware Scale (#3096): the box only scales and moves, and OK runs - /// `edit.contentAwareScale` with these options instead of `edit.transform`. - #[serde(default)] - pub content_aware: Option, - /// The options bar's V (vertical skew, degrees) last typed. Any box can be read as scale, - /// skew and rotation with any vertical skew, so the bar keeps showing the typed one. - #[serde(default)] - pub skew_v: f64, -} - -/// Content-Aware Scale's options bar: Amount, Protect and Protect Skin Tones. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ContentAwareOptions { - /// How much is content-aware, 0..100 % (the rest is a plain resample). - pub amount: f32, - /// The alpha channel whose white areas keep their shape (`None`: no protection). - #[serde(default)] - pub protect: Option, - #[serde(default)] - pub protect_skin_tones: bool, -} - -impl Default for ContentAwareOptions { - fn default() -> Self { - Self { amount: 100.0, protect: None, protect_skin_tones: false } - } -} - -/// Why a Free Transform session's layer was made for it. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum MadeLayer { - /// Free Transform on a copy (⌥⌘T): OK makes the copy and the transform one Free Transform step. - Copy, - /// A file dropped on the canvas: OK makes the place and the transform one Place Embedded step. - Place, -} - -/// A paragraph-box handle drag: the handle, and the box (text-space) and layer transform as -/// they were at the press. Every move recomputes from this snapshot, so ⌥ pressed or released -/// mid-drag mirrors about the centre the box started with — as if it had been held from the -/// start. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct BoxResize { - pub handle: u8, - pub shape: [f32; 4], - pub aff: photocraft_geom::Affine, -} - -/// In-progress inline type editing (Type tool). Offsets are character indices. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct TextEdit { - pub layer: u64, - /// Id of the document being edited (layer ids can repeat across documents, e.g. one .pcraft - /// opened twice). `None`: the active document. - #[serde(default)] - pub document: Option, - pub caret: usize, - pub anchor: usize, - /// History coalescing key: the whole editing session is one "Edit Type Layer" step. - pub session: String, - /// The layer was created by this session (its name follows the text; empty on commit = delete). - pub created: bool, - /// A Type Mask tool session: the layer is temporary and commits as a selection. - #[serde(default)] - pub mask: bool, - #[serde(skip)] - pub dragging: bool, - /// Paragraph-box handle being dragged (0-3 corners from top-left clockwise, 4-7 top/right/bottom/left edges). - #[serde(skip)] - pub resize: Option, - /// IME composition in progress: (start, length) in characters. The preedit text lives in the - /// layer so it lays out like typed text; each IME update replaces it. - #[serde(skip)] - pub preedit: Option<(usize, usize)>, -} - -/// Temporary Type-tool drag. The document is unchanged until release; this frame is view state. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct TypeTransform { - pub document: u64, - pub revision: u64, - pub original: photocraft_geom::Affine, - pub frame: TransformSession, - pub(crate) gesture: crate::transform_tool::Gesture, -} - -/// Content-Aware Move with Transform On Drop: the box on the dropped patch. The document is -/// unchanged until it is committed; this is view state. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct CamTransform { - pub document: u64, - pub revision: u64, - /// How far the selection was dragged; the box's `rect` is the selection's bounds there. - pub offset: [i32; 2], - pub frame: TransformSession, - #[serde(skip)] - pub(crate) gesture: Option, -} - -/// View-menu overlays. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default)] -pub struct Extras { - pub rulers: bool, - pub grid: bool, - pub guides: bool, - pub snap: bool, - pub lock_guides: bool, -} - -impl Default for Extras { - fn default() -> Self { - Self { rulers: false, grid: false, guides: true, snap: true, lock_guides: false } - } -} - -/// Selected tab per dock card. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default)] -pub struct DockTabs { - pub properties: usize, - pub color: usize, - pub layers: usize, - /// Navigator | Histogram | Info. - pub navigator: usize, - /// History | Actions. - pub history: usize, - /// Character | Paragraph. - pub character: usize, - /// Brushes presets. - pub brushes: usize, -} - -/// Color panel state. -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", default)] -pub struct ColorPanelState { - /// The panel edits the background colour (its chip was clicked), not the foreground. - pub background: bool, - /// Color Picker › Only Web Colors, kept across opens like Photoshop (#4995). `web_only` is - /// its name before the camelCase rename (#6000). - #[serde(default, alias = "web_only")] - pub web_only: bool, - /// What the panel shows, picked from its panel menu as in Photoshop (#6000). - pub mode: ColorPanelMode, - /// The colour ramp under the sliders. - pub ramp: ColorRamp, - /// Make Ramp Web Safe: the ramp shows (and picks) web colours only. - pub web_safe_ramp: bool, -} - -/// The Color panel's display, Photoshop's panel menu choices in its order. Hue Cube is -/// Photoshop's default; the theme never changes it (#6000). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum ColorPanelMode { - #[default] - HueCube, - BrightnessCube, - ColorWheel, - GrayscaleSlider, - RgbSliders, - HsbSliders, - CmykSliders, - LabSliders, - WebColorSliders, -} - -impl ColorPanelMode { - /// Every mode, in Photoshop's panel menu order. - pub const ALL: [ColorPanelMode; 9] = [ - ColorPanelMode::HueCube, - ColorPanelMode::BrightnessCube, - ColorPanelMode::ColorWheel, - ColorPanelMode::GrayscaleSlider, - ColorPanelMode::RgbSliders, - ColorPanelMode::HsbSliders, - ColorPanelMode::CmykSliders, - ColorPanelMode::LabSliders, - ColorPanelMode::WebColorSliders, - ]; - - /// The panel menu item. - pub fn label(self) -> &'static str { - match self { - ColorPanelMode::HueCube => "Hue Cube", - ColorPanelMode::BrightnessCube => "Brightness Cube", - ColorPanelMode::ColorWheel => "Color Wheel", - ColorPanelMode::GrayscaleSlider => "Grayscale Slider", - ColorPanelMode::RgbSliders => "RGB Sliders", - ColorPanelMode::HsbSliders => "HSB Sliders", - ColorPanelMode::CmykSliders => "CMYK Sliders", - ColorPanelMode::LabSliders => "Lab Sliders", - ColorPanelMode::WebColorSliders => "Web Color Sliders", - } - } - - /// The slider modes, which show the colour ramp under their sliders. - pub fn is_sliders(self) -> bool { - !matches!(self, ColorPanelMode::HueCube | ColorPanelMode::BrightnessCube | ColorPanelMode::ColorWheel) - } -} - -/// The Color panel's colour ramp, from its panel menu (or Shift-click on the ramp to cycle). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum ColorRamp { - #[default] - RgbSpectrum, - CmykSpectrum, - GrayscaleRamp, - CurrentColors, -} - -impl ColorRamp { - /// Every ramp, in Photoshop's panel menu order (also the Shift-click cycle). - pub const ALL: [ColorRamp; 4] = [ColorRamp::RgbSpectrum, ColorRamp::CmykSpectrum, ColorRamp::GrayscaleRamp, ColorRamp::CurrentColors]; - - /// The panel menu item. - pub fn label(self) -> &'static str { - match self { - ColorRamp::RgbSpectrum => "RGB Spectrum", - ColorRamp::CmykSpectrum => "CMYK Spectrum", - ColorRamp::GrayscaleRamp => "Grayscale Ramp", - ColorRamp::CurrentColors => "Current Colors", - } - } - - /// The next ramp in the Shift-click cycle. - pub fn next(self) -> ColorRamp { - let i = ColorRamp::ALL.iter().position(|r| *r == self).unwrap_or(0); - ColorRamp::ALL.get(i + 1).copied().unwrap_or(ColorRamp::RgbSpectrum) - } -} - #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UiState { pub tool: Tool, diff --git a/crates/ui-egui/src/state/color_panel.rs b/crates/ui-egui/src/state/color_panel.rs new file mode 100644 index 0000000000..4b1ac89ee8 --- /dev/null +++ b/crates/ui-egui/src/state/color_panel.rs @@ -0,0 +1,120 @@ +use super::*; + +/// Selected tab per dock card. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct DockTabs { + pub properties: usize, + pub color: usize, + pub layers: usize, + /// Navigator | Histogram | Info. + pub navigator: usize, + /// History | Actions. + pub history: usize, + /// Character | Paragraph. + pub character: usize, + /// Brushes presets. + pub brushes: usize, +} + +/// Color panel state. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct ColorPanelState { + /// The panel edits the background colour (its chip was clicked), not the foreground. + pub background: bool, + /// Color Picker › Only Web Colors, kept across opens like Photoshop (#4995). `web_only` is + /// its name before the camelCase rename (#6000). + #[serde(default, alias = "web_only")] + pub web_only: bool, + /// What the panel shows, picked from its panel menu as in Photoshop (#6000). + pub mode: ColorPanelMode, + /// The colour ramp under the sliders. + pub ramp: ColorRamp, + /// Make Ramp Web Safe: the ramp shows (and picks) web colours only. + pub web_safe_ramp: bool, +} + +/// The Color panel's display, Photoshop's panel menu choices in its order. Hue Cube is +/// Photoshop's default; the theme never changes it (#6000). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ColorPanelMode { + #[default] + HueCube, + BrightnessCube, + ColorWheel, + GrayscaleSlider, + RgbSliders, + HsbSliders, + CmykSliders, + LabSliders, + WebColorSliders, +} + +impl ColorPanelMode { + /// Every mode, in Photoshop's panel menu order. + pub const ALL: [ColorPanelMode; 9] = [ + ColorPanelMode::HueCube, + ColorPanelMode::BrightnessCube, + ColorPanelMode::ColorWheel, + ColorPanelMode::GrayscaleSlider, + ColorPanelMode::RgbSliders, + ColorPanelMode::HsbSliders, + ColorPanelMode::CmykSliders, + ColorPanelMode::LabSliders, + ColorPanelMode::WebColorSliders, + ]; + + /// The panel menu item. + pub fn label(self) -> &'static str { + match self { + ColorPanelMode::HueCube => "Hue Cube", + ColorPanelMode::BrightnessCube => "Brightness Cube", + ColorPanelMode::ColorWheel => "Color Wheel", + ColorPanelMode::GrayscaleSlider => "Grayscale Slider", + ColorPanelMode::RgbSliders => "RGB Sliders", + ColorPanelMode::HsbSliders => "HSB Sliders", + ColorPanelMode::CmykSliders => "CMYK Sliders", + ColorPanelMode::LabSliders => "Lab Sliders", + ColorPanelMode::WebColorSliders => "Web Color Sliders", + } + } + + /// The slider modes, which show the colour ramp under their sliders. + pub fn is_sliders(self) -> bool { + !matches!(self, ColorPanelMode::HueCube | ColorPanelMode::BrightnessCube | ColorPanelMode::ColorWheel) + } +} + +/// The Color panel's colour ramp, from its panel menu (or Shift-click on the ramp to cycle). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ColorRamp { + #[default] + RgbSpectrum, + CmykSpectrum, + GrayscaleRamp, + CurrentColors, +} + +impl ColorRamp { + /// Every ramp, in Photoshop's panel menu order (also the Shift-click cycle). + pub const ALL: [ColorRamp; 4] = [ColorRamp::RgbSpectrum, ColorRamp::CmykSpectrum, ColorRamp::GrayscaleRamp, ColorRamp::CurrentColors]; + + /// The panel menu item. + pub fn label(self) -> &'static str { + match self { + ColorRamp::RgbSpectrum => "RGB Spectrum", + ColorRamp::CmykSpectrum => "CMYK Spectrum", + ColorRamp::GrayscaleRamp => "Grayscale Ramp", + ColorRamp::CurrentColors => "Current Colors", + } + } + + /// The next ramp in the Shift-click cycle. + pub fn next(self) -> ColorRamp { + let i = ColorRamp::ALL.iter().position(|r| *r == self).unwrap_or(0); + ColorRamp::ALL.get(i + 1).copied().unwrap_or(ColorRamp::RgbSpectrum) + } +} diff --git a/crates/ui-egui/src/state/panel_state.rs b/crates/ui-egui/src/state/panel_state.rs new file mode 100644 index 0000000000..4cc2d67184 --- /dev/null +++ b/crates/ui-egui/src/state/panel_state.rs @@ -0,0 +1,126 @@ +use super::*; + +/// Photoshop-style Layers panel display preferences; part of serialized UI state. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum LayerThumbnailSize { + None, + Small, + #[default] + Medium, + Large, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum LayerThumbnailContents { + LayerBounds, + #[default] + EntireDocument, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct LayersPanelOptions { + pub thumbnail_size: LayerThumbnailSize, + /// Thumbnail Contents in the Panel Options dialog. Not saved with these options: the dialog + /// shows and sets `interface.clipThumbnailsToLayerBounds` (Layer Bounds = clipped, #4281), + /// which the panel menu's Clip Thumbnails to Layer Bounds toggles too. + #[serde(skip)] + pub thumbnail_contents: LayerThumbnailContents, + pub show_filters: bool, + pub use_default_masks_on_fill_layers: bool, + pub expand_new_effects: bool, + pub add_copy_to_copied_layers_and_groups: bool, + pub preview_on_canvas_when_reordering_layers: bool, + pub show_layer_mask_badges: bool, +} + +impl LayersPanelOptions { + /// Every option at the Photoshop default: Medium thumbnails, filters shown, new effects expanded, no mask badges. + pub fn defaults() -> Self { + Self { + thumbnail_size: LayerThumbnailSize::Medium, + thumbnail_contents: LayerThumbnailContents::EntireDocument, + show_filters: true, + use_default_masks_on_fill_layers: true, + expand_new_effects: true, + add_copy_to_copied_layers_and_groups: true, + preview_on_canvas_when_reordering_layers: true, + show_layer_mask_badges: false, + } + } +} + +impl Default for LayersPanelOptions { + /// Same as [`LayersPanelOptions::defaults`], so serde fills missing fields with the Photoshop defaults. + fn default() -> Self { + Self::defaults() + } +} + +/// Pending dialog data is transient: Cancel never changes persisted options. +#[derive(Clone, Debug, PartialEq)] +pub enum LayersPanelDialog { + PanelOptions(LayersPanelOptions), + NewLayer(String), + NewGroup(String), + LockLayers { transparency: bool, pixels: bool, position: bool, artboard: bool, all: bool }, +} + +/// Shared selection and capture for a point curve; document parameters remain with the host. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct PointCurveState { + pub selected: Option, + /// Captured point (None while removed outside), grab offset, and re-entry eligibility. + pub drag: Option, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct PointCurveDrag { + pub index: Option, + pub offset: [f32; 2], + pub removed: bool, +} + +/// Curves editor memory (egui temp data): the edited channel and the point gesture. +#[derive(Clone, Copy, Debug, Default)] +pub struct CurvesEditorState { + pub channel: usize, + pub gesture: PointCurveState, +} + +/// Camera Raw scope preferences are view state, never filter parameters or document history. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct CameraRawScopeState { + pub shadows: bool, + pub highlights: bool, + pub lab: bool, + pub sampler_tool: bool, + pub samplers: Vec<[f32; 2]>, + pub vectorscope: bool, + pub selected_region: bool, + pub red_right: bool, + pub hide_skin_line: bool, + pub floating: bool, + pub floating_rect: Option<[f32; 4]>, +} + +/// Camera Raw navigation, separate from filter settings. Reset for each opened image. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct CameraRawPreviewState { + /// None fits the image; Some is physical display pixels per source pixel. + pub zoom: Option, + pub center: [f32; 2], + pub hand: bool, +} + +impl Default for CameraRawPreviewState { + fn default() -> Self { + Self { zoom: None, center: [0.5, 0.5], hand: false } + } +} diff --git a/crates/ui-egui/src/state/tool.rs b/crates/ui-egui/src/state/tool.rs new file mode 100644 index 0000000000..2b6702f317 --- /dev/null +++ b/crates/ui-egui/src/state/tool.rs @@ -0,0 +1,321 @@ +use super::*; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Tool { + Move, + Artboard, + RectMarquee, + EllipseMarquee, + /// Selects one pixel row across the whole canvas at the clicked y (Photoshop's flyout only: + /// no key, not in the ⇧M cycle). + SingleRowMarquee, + /// Selects one pixel column down the whole canvas at the clicked x. + SingleColumnMarquee, + Lasso, + PolygonLasso, + MagneticLasso, + MagicWand, + Crop, + PerspectiveCrop, + Eyedropper, + ColorSampler, + Ruler, + Note, + Count, + Brush, + Pencil, + MixerBrush, + ColorReplacement, + Eraser, + BackgroundEraser, + MagicEraser, + Gradient, + PaintBucket, + Type, + VerticalType, + /// Horizontal Type Mask: types a selection in the shape of the glyphs, no type layer. + HorizontalTypeMask, + VerticalTypeMask, + Hand, + RotateView, + Zoom, + Remove, + SpotHealing, + Healing, + Patch, + ContentAwareMove, + RedEye, + CloneStamp, + PatternStamp, + HistoryBrush, + ArtHistoryBrush, + Blur, + Sharpen, + Smudge, + Dodge, + Burn, + Sponge, + QuickSelection, + ObjectSelection, + Pen, + FreeformPen, + CurvaturePen, + AddAnchorPoint, + DeleteAnchorPoint, + /// Converts an anchor between smooth and corner, and pulls handles out of a corner + /// (Photoshop's Convert Point tool; also the Pen's ⌥ mode, `direct_select.rs`). + ConvertPoint, + PathSelection, + DirectSelection, + Rectangle, + EllipseShape, + Triangle, + Polygon, + Line, + CustomShape, + Slice, + SliceSelect, + Frame, +} + +impl Tool { + pub const ALL: [Tool; 68] = [ + Tool::Move, + Tool::Artboard, + Tool::RectMarquee, + Tool::EllipseMarquee, + Tool::SingleRowMarquee, + Tool::SingleColumnMarquee, + Tool::Lasso, + Tool::PolygonLasso, + Tool::MagneticLasso, + Tool::MagicWand, + Tool::Crop, + Tool::PerspectiveCrop, + Tool::Eyedropper, + Tool::ColorSampler, + Tool::Ruler, + Tool::Note, + Tool::Count, + Tool::Brush, + Tool::Pencil, + Tool::MixerBrush, + Tool::ColorReplacement, + Tool::Eraser, + Tool::BackgroundEraser, + Tool::MagicEraser, + Tool::Gradient, + Tool::PaintBucket, + Tool::Type, + Tool::VerticalType, + Tool::HorizontalTypeMask, + Tool::VerticalTypeMask, + Tool::Hand, + Tool::RotateView, + Tool::Zoom, + Tool::Remove, + Tool::SpotHealing, + Tool::Healing, + Tool::Patch, + Tool::ContentAwareMove, + Tool::RedEye, + Tool::CloneStamp, + Tool::PatternStamp, + Tool::HistoryBrush, + Tool::ArtHistoryBrush, + Tool::Blur, + Tool::Sharpen, + Tool::Smudge, + Tool::Dodge, + Tool::Burn, + Tool::Sponge, + Tool::QuickSelection, + Tool::ObjectSelection, + Tool::Pen, + Tool::FreeformPen, + Tool::CurvaturePen, + Tool::AddAnchorPoint, + Tool::DeleteAnchorPoint, + Tool::ConvertPoint, + Tool::PathSelection, + Tool::DirectSelection, + Tool::Rectangle, + Tool::EllipseShape, + Tool::Triangle, + Tool::Polygon, + Tool::Line, + Tool::CustomShape, + Tool::Slice, + Tool::SliceSelect, + Tool::Frame, + ]; + + pub fn label(self) -> &'static str { + match self { + Tool::Move => "Move Tool", + Tool::Artboard => "Artboard Tool", + Tool::RectMarquee => "Rectangular Marquee Tool", + Tool::EllipseMarquee => "Elliptical Marquee Tool", + Tool::SingleRowMarquee => "Single Row Marquee Tool", + Tool::SingleColumnMarquee => "Single Column Marquee Tool", + Tool::Brush => "Brush Tool", + Tool::Pencil => "Pencil Tool", + Tool::MixerBrush => "Mixer Brush Tool", + Tool::ColorReplacement => "Color Replacement Tool", + Tool::Eraser => "Eraser Tool", + Tool::BackgroundEraser => "Background Eraser Tool", + Tool::MagicEraser => "Magic Eraser Tool", + Tool::Eyedropper => "Eyedropper Tool", + Tool::ColorSampler => "Color Sampler Tool", + Tool::Ruler => "Ruler Tool", + Tool::Note => "Note Tool", + Tool::Count => "Count Tool", + Tool::Lasso => "Lasso Tool", + Tool::PolygonLasso => "Polygonal Lasso Tool", + Tool::MagneticLasso => "Magnetic Lasso Tool", + Tool::MagicWand => "Magic Wand Tool", + Tool::Crop => "Crop Tool", + Tool::PerspectiveCrop => "Perspective Crop Tool", + Tool::Slice => "Slice Tool", + Tool::SliceSelect => "Slice Select Tool", + Tool::Frame => "Frame Tool", + Tool::Gradient => "Gradient Tool", + Tool::PaintBucket => "Paint Bucket Tool", + Tool::Type => "Horizontal Type Tool", + Tool::VerticalType => "Vertical Type Tool", + Tool::HorizontalTypeMask => "Horizontal Type Mask Tool", + Tool::VerticalTypeMask => "Vertical Type Mask Tool", + Tool::Hand => "Hand Tool", + Tool::RotateView => "Rotate View Tool", + Tool::Zoom => "Zoom Tool", + Tool::Remove => "Remove Tool", + Tool::SpotHealing => "Spot Healing Brush Tool", + Tool::Healing => "Healing Brush Tool", + Tool::Patch => "Patch Tool", + Tool::ContentAwareMove => "Content-Aware Move Tool", + Tool::RedEye => "Red Eye Tool", + Tool::CloneStamp => "Clone Stamp Tool", + Tool::PatternStamp => "Pattern Stamp Tool", + Tool::HistoryBrush => "History Brush Tool", + Tool::ArtHistoryBrush => "Art History Brush Tool", + Tool::Blur => "Blur Tool", + Tool::Sharpen => "Sharpen Tool", + Tool::Smudge => "Smudge Tool", + Tool::Dodge => "Dodge Tool", + Tool::Burn => "Burn Tool", + Tool::Sponge => "Sponge Tool", + Tool::QuickSelection => "Quick Selection Tool", + Tool::ObjectSelection => "Object Selection Tool", + Tool::Pen => "Pen Tool", + Tool::FreeformPen => "Freeform Pen Tool", + Tool::CurvaturePen => "Curvature Pen Tool", + Tool::AddAnchorPoint => "Add Anchor Point Tool", + Tool::DeleteAnchorPoint => "Delete Anchor Point Tool", + Tool::ConvertPoint => "Convert Point Tool", + Tool::PathSelection => "Path Selection Tool", + Tool::DirectSelection => "Direct Selection Tool", + Tool::Rectangle => "Rectangle Tool", + Tool::EllipseShape => "Ellipse Tool", + Tool::Triangle => "Triangle Tool", + Tool::Polygon => "Polygon Tool", + Tool::Line => "Line Tool", + Tool::CustomShape => "Custom Shape Tool", + } + } + pub fn is_type(self) -> bool { + matches!(self, Self::Type | Self::VerticalType | Self::HorizontalTypeMask | Self::VerticalTypeMask) + } + /// The Type Mask tools: their text becomes a selection on commit. + pub fn is_type_mask(self) -> bool { + matches!(self, Self::HorizontalTypeMask | Self::VerticalTypeMask) + } + /// Type tools that lay text out vertically. + pub fn is_vertical_type(self) -> bool { + matches!(self, Self::VerticalType | Self::VerticalTypeMask) + } + + /// Retouching and painting tools that stroke with the brush (share the brush cursor and chip). + pub fn is_brushlike(self) -> bool { + matches!( + self, + Tool::Brush + | Tool::Pencil + | Tool::MixerBrush + | Tool::ColorReplacement + | Tool::Eraser + | Tool::BackgroundEraser + | Tool::Remove + | Tool::SpotHealing + | Tool::Healing + | Tool::CloneStamp + | Tool::PatternStamp + | Tool::HistoryBrush + | Tool::ArtHistoryBrush + | Tool::Blur + | Tool::Sharpen + | Tool::Smudge + | Tool::Dodge + | Tool::Burn + | Tool::Sponge + ) + } + /// Photoshop default single-key shortcut (`'\0'` = none, e.g. the Blur group). + pub fn key(self) -> char { + match self { + Tool::Move | Tool::Artboard => 'V', + Tool::RectMarquee | Tool::EllipseMarquee => 'M', + Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::ColorReplacement => 'B', + Tool::Eraser | Tool::BackgroundEraser | Tool::MagicEraser => 'E', + Tool::Eyedropper | Tool::ColorSampler | Tool::Ruler | Tool::Note | Tool::Count => 'I', + Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso => 'L', + Tool::MagicWand => 'W', + Tool::Crop | Tool::PerspectiveCrop | Tool::Slice | Tool::SliceSelect => 'C', + Tool::Frame => 'K', + Tool::Gradient | Tool::PaintBucket => 'G', + Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => 'T', + Tool::Hand => 'H', + Tool::RotateView => 'R', + Tool::Zoom => 'Z', + Tool::Remove | Tool::SpotHealing | Tool::Healing | Tool::Patch | Tool::ContentAwareMove | Tool::RedEye => 'J', + Tool::CloneStamp | Tool::PatternStamp => 'S', + Tool::HistoryBrush | Tool::ArtHistoryBrush => 'Y', + Tool::Blur | Tool::Sharpen | Tool::Smudge => '\0', + // In the Marquee flyout, but M cycles only the Rectangular and Elliptical Marquee. + Tool::SingleRowMarquee | Tool::SingleColumnMarquee => '\0', + Tool::Dodge | Tool::Burn | Tool::Sponge => 'O', + Tool::QuickSelection | Tool::ObjectSelection => 'W', + Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint => 'P', + Tool::PathSelection | Tool::DirectSelection => 'A', + Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line | Tool::CustomShape => 'U', + } + } + /// Glyph drawn in the toolbar (vector icons come later). + pub fn glyph(self) -> &'static str { + match self { + Tool::Move => "✥", + Tool::RectMarquee => "⬚", + Tool::EllipseMarquee => "◌", + Tool::Brush => "🖌", + Tool::MixerBrush => "🖌", + Tool::Eraser => "⌫", + Tool::Eyedropper => "💧", + Tool::ColorSampler => "◎", + Tool::Lasso | Tool::PolygonLasso | Tool::MagneticLasso => "L", + Tool::MagicWand => "W", + Tool::Crop => "C", + Tool::Gradient | Tool::PaintBucket => "G", + Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => "T", + Tool::Hand => "✋", + Tool::RotateView => "🧭", + Tool::Zoom => "🔍", + _ => "•", + } + } + pub fn from_name(s: &str) -> Option { + let n = s.to_ascii_lowercase().replace([' ', '_', '-'], ""); + Tool::ALL.into_iter().find(|t| { + let a = format!("{t:?}").to_ascii_lowercase(); + n == a || n == a.replace("marquee", "") || n == t.label().to_ascii_lowercase().replace(' ', "") + }) + } +} diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs new file mode 100644 index 0000000000..6855ddeb12 --- /dev/null +++ b/crates/ui-egui/src/state/tool_options.rs @@ -0,0 +1,468 @@ +use super::tool::Tool; +use super::*; + +/// Options-bar state for tools (Photoshop keeps these per tool). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ToolOptions { + pub tolerance: f32, + pub contiguous: bool, + pub anti_alias: bool, + /// Sample All Layers, kept per tool as in Photoshop (#5524). Stored under a new key, so the + /// single shared `sample_all_layers` of older preferences is ignored on load. + pub sample_all: SampleAllLayers, + /// Object Selection › Object Finder: hovering highlights the object a click selects (#4087). + pub object_finder: bool, + /// Remove tool: the fill goes to a new layer above the target (Photoshop's Create a new layer). + pub remove_new_layer: bool, + /// Remove tool: each stroke is filled when released (Photoshop's default). Off, the strokes + /// collect as a tint on the canvas and ↩ applies them together (Esc drops them). + pub remove_after_each_stroke: bool, + pub feather: f32, + /// linear | radial | angle | reflected | diamond + pub gradient_style: String, + pub gradient_reverse: bool, + /// Gradient tool: dither to reduce 8-bit banding (Photoshop default on). + pub gradient_dither: bool, + /// Gradient tool mode: false = "Gradient" (live: a Gradient Fill layer, editable on canvas), + /// true = "Classic gradient" (paints the pixels). + pub gradient_classic: bool, + /// Blend mode used by both live and classic gradient drags. + pub gradient_blend_mode: photocraft_color::BlendMode, + pub fill_opacity: f32, + /// Paint Bucket fill source: false = Foreground colour, true = Pattern (Patterns panel selection). + pub bucket_fill_pattern: bool, + /// Paint Bucket › Mode (any layer mode; Clear is `bucket_clear`). + pub bucket_blend_mode: photocraft_color::BlendMode, + /// Paint Bucket › Mode: Clear, which erases the filled area (see `brush_clear`). + pub bucket_clear: bool, + /// Type tool: family, style name, size (pt), anti-aliasing and paragraph alignment. + pub type_font: String, + pub type_style: String, + pub type_size: f32, + pub type_aa: String, + pub type_align: String, + /// Character/Paragraph panel defaults beyond the options bar, in `type.setStyle`'s + /// parameter format. Kept as overrides so saved engine defaults still supply unset fields. + /// OpenType features and variable-font axes are merged per tag/axis. + #[serde(default)] + pub type_style_defaults: serde_json::Map, + /// Type tool: paragraph direction of new type, "auto" (from the first strong character), + /// "ltr" or "rtl" (TYPE-218-2). + pub type_direction: String, + /// Clone Stamp / Healing Brush. + pub clone_aligned: bool, + /// Pattern Stamp: lock the tile origin in document space across strokes. + pub pattern_stamp_aligned: bool, + /// Pattern Stamp: jitter each dab's phase (seeded, replayable). + pub pattern_stamp_impressionist: bool, + /// Pattern Stamp scale %, 1..1000 (100 = the tile's native size). + pub pattern_stamp_scale: f32, + /// Pattern Stamp rotation in degrees (counter-clockwise). + pub pattern_stamp_angle: f32, + /// current | currentAndBelow | all + pub clone_sample: String, + /// Spot Healing: contentAware | createTexture | proximityMatch + pub spot_type: String, + /// Patch: source (repair the selection) | destination (repair where it is dragged). + pub patch_mode: String, + /// Patch: Content-Aware instead of Normal, with its Structure 1..7 and Color 0..10. + pub patch_content_aware: bool, + pub patch_structure: f32, + pub patch_color: f32, + /// Content-Aware Move: move | extend, Structure 1..7, Color 0..10. + 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). + pub cam_transform_on_drop: bool, + /// Dodge/Burn: shadows | midtones | highlights, exposure %, protect tones. + pub tone_range: String, + pub exposure: f32, + pub protect_tones: bool, + /// Sponge: desaturate | saturate, vibrance. + pub sponge_mode: String, + pub vibrance: bool, + /// Blur/Sharpen/Smudge strength %, Sharpen protect detail, Smudge finger painting. + pub strength: f32, + pub protect_detail: bool, + pub finger_painting: bool, + /// Quick Selection enhance edge. + pub enhance_edge: bool, + /// Pen: "path" (work path) or "shape" (shape layer). + pub vector_mode: String, + /// Shape tools: fill with the foreground colour, stroke width (0 = none), rectangle corner + /// radius, polygon sides, line weight. + pub shape_fill: bool, + pub stroke_width: f32, + #[serde(default)] + pub shape_stroke: crate::shape_stroke_ui::StrokeOptions, + /// Shape tools: the gradient the next shape's fill / stroke takes (the swatches' Gradient + /// tab) instead of the foreground / background colour; `None` = the colour. + pub shape_fill_gradient: Option, + pub shape_stroke_gradient: Option, + pub corner_radius: f32, + pub polygon_sides: u32, + pub line_weight: f32, + /// Freeform Pen › Curve Fit: how far (px) the fitted path may stray from the pointer trace. + #[serde(default = "default_curve_fit")] + pub curve_fit: f32, + /// Pen › Auto Add/Delete: a Pen click on a segment of the active path adds an anchor there, + /// on one of its anchors deletes it (#4144). + #[serde(default = "yes")] + pub pen_auto_add_delete: bool, + /// Marquee options bar: "normal" | "fixedRatio" | "fixedSize", with the ratio or size. + #[serde(default = "default_marquee_style")] + pub marquee_style: String, + #[serde(default = "one")] + pub marquee_width: f32, + #[serde(default = "one")] + pub marquee_height: f32, + /// The unit Fixed Size's Width and Height show (a [`photocraft_engine::prefs::Unit`] name, + /// picked by right-clicking them); the size itself stays in pixels (#7910). + #[serde(default = "default_marquee_unit")] + pub marquee_unit: String, + /// Slice tool options bar: the same Styles as the marquee's, with the ratio or the size in px + /// (#8360). + #[serde(default = "default_marquee_style")] + pub slice_style: String, + #[serde(default = "one")] + pub slice_width: f32, + #[serde(default = "one")] + pub slice_height: f32, + /// Move tool: Auto-Select (with "layer" or "group" target) and Show Transform Controls. + /// Auto-Select is on with the "group" target by default, as in current Photoshop; + /// ⌘/Ctrl-click inverts it. + #[serde(default = "yes")] + pub move_auto_select: bool, + #[serde(default = "default_move_target")] + pub move_target: String, + #[serde(default)] + pub move_show_transform: bool, + /// Crop options bar: aspect ratio ("" = Ratio/unconstrained, "w:h", or "original") and + /// Delete Cropped Pixels. + #[serde(default)] + pub crop_ratio: String, + /// In-progress custom crop ratio fields. Kept separately because entering one side before the + /// other must survive a frame while the ratio itself remains unconstrained. + #[serde(default)] + pub crop_custom_ratio_width: f32, + #[serde(default)] + pub crop_custom_ratio_height: f32, + #[serde(default = "yes")] + pub crop_delete: bool, + /// Crop options bar › Fill: false = Background (Default), true = Content-Aware Fill (the area a + /// rotated or extending crop uncovers is filled from its surroundings, #3823). + #[serde(default)] + pub crop_content_aware: bool, + /// Crop W x H x Resolution (`crop_ratio` = "whr", #2443): width and height as typed lengths + /// with their unit ("4 in", "1024 px"; empty = unset), the resolution ("" = the document's) + /// and its unit ("px/in" or "px/cm"). See `crop_size`. + #[serde(default)] + pub crop_width: String, + #[serde(default)] + pub crop_height: String, + #[serde(default)] + pub crop_resolution: String, + #[serde(default = "default_crop_resolution_unit")] + pub crop_resolution_unit: String, + /// Perspective Crop's Show Grid (`perspective_crop_ui`); it shares W, H and the resolution above. + #[serde(default = "yes")] + pub perspective_crop_grid: bool, + /// Crop overlay (#1919): the guide in the crop box, when it shows and its orientation + /// (Photoshop's defaults: Rule of Thirds, Auto Show Overlay). See `crop_overlay`. + #[serde(default)] + pub crop_overlay: crate::crop_overlay::CropOverlay, + #[serde(default)] + pub crop_overlay_show: crate::crop_overlay::OverlayShow, + #[serde(default)] + pub crop_overlay_orientation: u8, + /// Crop gear menu (#1919): Show Cropped Area and the crop shield. See `crop_shield`. + #[serde(default)] + pub crop_shield: crate::crop_shield::CropShield, + /// Magic Eraser opacity % (tolerance, anti-alias and contiguous are shared with the Magic Wand + /// and Paint Bucket). + pub magic_eraser_opacity: f32, + /// Background Eraser: sampling (continuous | once | backgroundSwatch), limits (discontiguous | + /// contiguous | findEdges), tolerance % and Protect Foreground Color. + pub bg_sampling: String, + pub bg_limits: String, + pub bg_tolerance: f32, + pub bg_protect_fg: bool, + /// Color Replacement: mode (hue | saturation | color | luminosity), sampling (continuous | + /// once | backgroundSwatch), limits (discontiguous | contiguous | findEdges), tolerance % and + /// anti-alias, as `paint.colorReplacement` takes them. + pub cr_mode: String, + pub cr_sampling: String, + pub cr_limits: String, + pub cr_tolerance: f32, + pub cr_anti_alias: bool, + /// Zoom tool › Scrubby Zoom: dragging left/right zooms continuously (else a zoom rectangle). + #[serde(default = "yes")] + pub zoom_scrubby: bool, + /// Pencil › Auto Erase: a stroke that starts on the foreground colour paints the background colour. + #[serde(default)] + pub pencil_auto_erase: bool, + /// Brush › Mode: Clear, which erases with the Brush (Photoshop's painting-only mode, #3439). + /// Not a blend mode, so it is kept beside the brush's `mode` rather than in it. + #[serde(default)] + pub brush_clear: bool, + /// Pencil › Mode: Clear (see `brush_clear`). + #[serde(default)] + pub pencil_clear: bool, + /// Eraser › Mode: `brush` (soft, anti-aliased) or `pencil` (hard, aliased pixels, through + /// `paint.pencil`), as in Photoshop's options bar (#2662). + #[serde(default = "default_eraser_mode")] + pub eraser_mode: String, + /// 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, + pub magnetic_contrast: f32, + pub magnetic_frequency: f32, + pub magnetic_pressure: bool, + /// Red Eye: pupil search size (1–100) and how far corrected pixels darken (0–100). + #[serde(default = "fifty")] + pub red_eye_pupil_size: f32, + #[serde(default = "fifty")] + pub red_eye_darken: f32, + /// Eyedropper › Sample Size: 1 = Point Sample, else the side of the averaged square (3, 5, + /// 11, 31, 51, 101; `photocraft_engine::sample_cmds::SAMPLE_SIZES`). Shared, as in Photoshop, + /// with the ⌥-click eyedropper of the painting tools, the dialog eyedroppers and the Info panel. + #[serde(default = "one_u32")] + pub eyedropper_size: u32, + /// Eyedropper › Sample: current | currentAndBelow | all | allNoAdjustments | + /// currentAndBelowNoAdjustments (`document.sampleColor`'s `sampleLayer`). + #[serde(default = "default_eyedropper_sample")] + pub eyedropper_sample: String, + /// Eyedropper › Show Sampling Ring. + #[serde(default = "yes")] + pub eyedropper_ring: bool, + /// Art History Brush: dab layout, Area (0–100), Tolerance (0–100). + #[serde(default = "default_art_history_style")] + pub art_history_style: String, + #[serde(default = "fifty")] + pub art_history_area: f32, + #[serde(default)] + pub art_history_tolerance: f32, +} + +fn default_art_history_style() -> String { + "tightMedium".into() +} + +pub(super) fn yes() -> bool { + true +} + +fn default_crop_resolution_unit() -> String { + crate::crop_size::PX_PER_IN.into() +} + +fn default_move_target() -> String { + "group".into() +} + +fn default_curve_fit() -> f32 { + 2.0 +} + +fn default_eraser_mode() -> String { + "brush".into() +} + +fn default_marquee_style() -> String { + "normal".into() +} + +fn default_marquee_unit() -> String { + "pixels".into() +} + +fn one() -> f32 { + 1.0 +} + +fn fifty() -> f32 { + 50.0 +} + +/// The session brush starts out as the Brush's (the tool the app opens with). +pub(super) fn default_brush_tool() -> Tool { + Tool::Brush +} + +pub(super) fn default_layer_filter_mode() -> photocraft_color::BlendMode { + photocraft_color::BlendMode::Normal +} + +fn one_u32() -> u32 { + 1 +} + +fn default_eyedropper_sample() -> String { + "all".into() +} + +/// Each tool's Sample All Layers (the Paint Bucket calls it All Layers). Photoshop keeps one per +/// tool, all off by default: turning it on for the Magic Wand must not leave Blur or Smudge +/// copying the composite onto the active layer (#5524). The Mixer Brush keeps its own with the +/// brush (`MixerSettings`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct SampleAllLayers { + pub magic_wand: bool, + pub quick_selection: bool, + pub object_selection: bool, + pub paint_bucket: bool, + pub magic_eraser: bool, + pub spot_healing: bool, + pub patch: bool, + pub content_aware_move: bool, + pub remove: bool, + pub blur: bool, + pub sharpen: bool, + pub smudge: bool, +} + +impl SampleAllLayers { + /// `tool`'s setting; false for a tool without the option. + pub fn get(mut self, tool: Tool) -> bool { + self.slot(tool).is_some_and(|v| *v) + } + + /// `tool`'s setting, or `None` for a tool without the option. + pub fn slot(&mut self, tool: Tool) -> Option<&mut bool> { + Some(match tool { + Tool::MagicWand => &mut self.magic_wand, + Tool::QuickSelection => &mut self.quick_selection, + Tool::ObjectSelection => &mut self.object_selection, + Tool::PaintBucket => &mut self.paint_bucket, + Tool::MagicEraser => &mut self.magic_eraser, + Tool::SpotHealing => &mut self.spot_healing, + Tool::Patch => &mut self.patch, + Tool::ContentAwareMove => &mut self.content_aware_move, + Tool::Remove => &mut self.remove, + Tool::Blur => &mut self.blur, + Tool::Sharpen => &mut self.sharpen, + Tool::Smudge => &mut self.smudge, + _ => return None, + }) + } +} + +impl Default for ToolOptions { + fn default() -> Self { + Self { + tolerance: 32.0, + contiguous: true, + anti_alias: true, + sample_all: SampleAllLayers::default(), + object_finder: true, + remove_new_layer: false, + remove_after_each_stroke: true, + feather: 0.0, + gradient_style: "linear".into(), + gradient_reverse: false, + gradient_dither: true, + gradient_classic: false, + gradient_blend_mode: photocraft_color::BlendMode::Normal, + fill_opacity: 100.0, + bucket_fill_pattern: false, + bucket_blend_mode: photocraft_color::BlendMode::Normal, + bucket_clear: false, + type_font: "Inter".into(), + type_style: "Regular".into(), + type_size: 48.0, + type_aa: "sharp".into(), + type_align: "left".into(), + type_style_defaults: serde_json::Map::new(), + type_direction: "auto".into(), + clone_aligned: true, + pattern_stamp_aligned: true, + pattern_stamp_impressionist: false, + pattern_stamp_scale: 100.0, + pattern_stamp_angle: 0.0, + clone_sample: "current".into(), + spot_type: "contentAware".into(), + patch_mode: "source".into(), + patch_content_aware: false, + patch_structure: 4.0, + patch_color: 0.0, + cam_mode: "move".into(), + cam_structure: 4.0, + cam_color: 0.0, + cam_transform_on_drop: false, + tone_range: "midtones".into(), + exposure: 50.0, + protect_tones: true, + sponge_mode: "desaturate".into(), + vibrance: true, + strength: 50.0, + protect_detail: true, + finger_painting: false, + enhance_edge: false, + vector_mode: "path".into(), + shape_fill: true, + stroke_width: 0.0, + shape_stroke: Default::default(), + shape_fill_gradient: None, + shape_stroke_gradient: None, + corner_radius: 0.0, + polygon_sides: 5, + line_weight: 3.0, + curve_fit: default_curve_fit(), + pen_auto_add_delete: true, + marquee_style: default_marquee_style(), + marquee_width: 1.0, + marquee_height: 1.0, + marquee_unit: default_marquee_unit(), + slice_style: default_marquee_style(), + slice_width: 1.0, + slice_height: 1.0, + move_auto_select: true, + move_target: default_move_target(), + move_show_transform: false, + crop_ratio: String::new(), + crop_custom_ratio_width: 0.0, + crop_custom_ratio_height: 0.0, + crop_delete: true, + crop_content_aware: false, + crop_width: String::new(), + crop_height: String::new(), + crop_resolution: String::new(), + crop_resolution_unit: default_crop_resolution_unit(), + perspective_crop_grid: true, + crop_overlay: Default::default(), + crop_overlay_show: Default::default(), + crop_overlay_orientation: 0, + crop_shield: Default::default(), + magic_eraser_opacity: 100.0, + bg_sampling: "continuous".into(), + bg_limits: "contiguous".into(), + bg_tolerance: 50.0, + bg_protect_fg: false, + cr_mode: "color".into(), + cr_sampling: "continuous".into(), + cr_limits: "contiguous".into(), + cr_tolerance: 30.0, + cr_anti_alias: true, + zoom_scrubby: true, + pencil_auto_erase: false, + brush_clear: false, + pencil_clear: false, + eraser_mode: default_eraser_mode(), + magnetic_width: 10.0, + magnetic_contrast: 10.0, + magnetic_frequency: 57.0, + magnetic_pressure: false, + red_eye_pupil_size: 50.0, + red_eye_darken: 50.0, + eyedropper_size: 1, + eyedropper_sample: default_eyedropper_sample(), + eyedropper_ring: true, + art_history_style: default_art_history_style(), + art_history_area: 50.0, + art_history_tolerance: 0.0, + } + } +} diff --git a/crates/ui-egui/src/state/transform.rs b/crates/ui-egui/src/state/transform.rs new file mode 100644 index 0000000000..ed14318721 --- /dev/null +++ b/crates/ui-egui/src/state/transform.rs @@ -0,0 +1,182 @@ +use super::*; + +/// Edit › Transform's mode: what a handle drag does with no modifier keys held. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum TransformMode { + /// Free Transform and Scale: handles scale, drag outside rotates. + #[default] + Free, + /// Edit › Transform › Rotate: handle drags rotate about the reference point (#3941). + Rotate, + /// Edge and corner handles skew: each moves along one axis. + Skew, + /// Corner handles move freely, one at a time; nothing else moves them (no rotating, no + /// edges) and nothing snaps. + Distort, + /// Corner handles move in pairs, mirrored (one-point perspective). + Perspective, +} + +impl TransformMode { + /// The mode an `edit.transform.*` / `edit.freeTransform` menu id starts. + pub fn for_command(id: &str) -> Self { + match id { + "edit.transform.rotate" => Self::Rotate, + "edit.transform.skew" => Self::Skew, + "edit.transform.distort" => Self::Distort, + "edit.transform.perspective" => Self::Perspective, + _ => Self::Free, + } + } +} + +/// Free Transform in progress: the source frame `rect` and where its corners currently are. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TransformSession { + pub session: u64, + pub layer: u64, + pub rect: [f64; 4], + /// Corners clockwise from top-left (document px). + pub quad: [[f64; 2]; 4], + /// Reference point (rotation / ⌥-scale centre). + pub pivot: [f64; 2], + pub interpolation: String, + /// Warp mode (Edit › Transform › Warp): the warp being edited over `rect`, in document px. + #[serde(default)] + pub warp: Option, + /// Select › Transform Selection: the box transforms the selection outline, not pixels. + #[serde(default)] + pub selection: bool, + /// `edit.transform`'s `"target"` when the box moves an unlinked layer mask, an alpha channel or + /// the Quick Mask by itself (`None`: the layer, with its linked masks). + #[serde(default)] + pub target: Option, + /// Free Transform Path: `path.transform`'s `name` (and `layer`) when the box moves a + /// path's anchors and handles instead of pixels. + #[serde(default)] + pub path: Option, + /// The layer was made for this session (⌥⌘T's copy, #352; a file dropped on the canvas), so + /// Cancel takes it back and OK folds it into one history step with the transform. + #[serde(default)] + pub made: Option, + /// Edit › Transform › Rotate / Skew / Distort / Perspective (`Free` for Free Transform and Scale). + #[serde(default)] + pub mode: TransformMode, + /// Edit › Content-Aware Scale (#3096): the box only scales and moves, and OK runs + /// `edit.contentAwareScale` with these options instead of `edit.transform`. + #[serde(default)] + pub content_aware: Option, + /// The options bar's V (vertical skew, degrees) last typed. Any box can be read as scale, + /// skew and rotation with any vertical skew, so the bar keeps showing the typed one. + #[serde(default)] + pub skew_v: f64, +} + +/// Content-Aware Scale's options bar: Amount, Protect and Protect Skin Tones. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ContentAwareOptions { + /// How much is content-aware, 0..100 % (the rest is a plain resample). + pub amount: f32, + /// The alpha channel whose white areas keep their shape (`None`: no protection). + #[serde(default)] + pub protect: Option, + #[serde(default)] + pub protect_skin_tones: bool, +} + +impl Default for ContentAwareOptions { + fn default() -> Self { + Self { amount: 100.0, protect: None, protect_skin_tones: false } + } +} + +/// Why a Free Transform session's layer was made for it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum MadeLayer { + /// Free Transform on a copy (⌥⌘T): OK makes the copy and the transform one Free Transform step. + Copy, + /// A file dropped on the canvas: OK makes the place and the transform one Place Embedded step. + Place, +} + +/// A paragraph-box handle drag: the handle, and the box (text-space) and layer transform as +/// they were at the press. Every move recomputes from this snapshot, so ⌥ pressed or released +/// mid-drag mirrors about the centre the box started with — as if it had been held from the +/// start. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BoxResize { + pub handle: u8, + pub shape: [f32; 4], + pub aff: photocraft_geom::Affine, +} + +/// In-progress inline type editing (Type tool). Offsets are character indices. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TextEdit { + pub layer: u64, + /// Id of the document being edited (layer ids can repeat across documents, e.g. one .pcraft + /// opened twice). `None`: the active document. + #[serde(default)] + pub document: Option, + pub caret: usize, + pub anchor: usize, + /// History coalescing key: the whole editing session is one "Edit Type Layer" step. + pub session: String, + /// The layer was created by this session (its name follows the text; empty on commit = delete). + pub created: bool, + /// A Type Mask tool session: the layer is temporary and commits as a selection. + #[serde(default)] + pub mask: bool, + #[serde(skip)] + pub dragging: bool, + /// Paragraph-box handle being dragged (0-3 corners from top-left clockwise, 4-7 top/right/bottom/left edges). + #[serde(skip)] + pub resize: Option, + /// IME composition in progress: (start, length) in characters. The preedit text lives in the + /// layer so it lays out like typed text; each IME update replaces it. + #[serde(skip)] + pub preedit: Option<(usize, usize)>, +} + +/// Temporary Type-tool drag. The document is unchanged until release; this frame is view state. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct TypeTransform { + pub document: u64, + pub revision: u64, + pub original: photocraft_geom::Affine, + pub frame: TransformSession, + pub(crate) gesture: crate::transform_tool::Gesture, +} + +/// Content-Aware Move with Transform On Drop: the box on the dropped patch. The document is +/// unchanged until it is committed; this is view state. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CamTransform { + pub document: u64, + pub revision: u64, + /// How far the selection was dragged; the box's `rect` is the selection's bounds there. + pub offset: [i32; 2], + pub frame: TransformSession, + #[serde(skip)] + pub(crate) gesture: Option, +} + +/// View-menu overlays. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Extras { + pub rulers: bool, + pub grid: bool, + pub guides: bool, + pub snap: bool, + pub lock_guides: bool, +} + +impl Default for Extras { + fn default() -> Self { + Self { rulers: false, grid: false, guides: true, snap: true, lock_guides: false } + } +} From 5b8e05d57ac6d025d9fd5800be4d15c19b659645 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:09:44 +0000 Subject: [PATCH 221/259] refactor(ui-egui): split view_cmds.rs into view_cmds/ --- crates/ui-egui/src/view_cmds.rs | 1426 +--------------------- crates/ui-egui/src/view_cmds/arrange.rs | 163 +++ crates/ui-egui/src/view_cmds/dialogs.rs | 630 ++++++++++ crates/ui-egui/src/view_cmds/dispatch.rs | 397 ++++++ crates/ui-egui/src/view_cmds/options.rs | 233 ++++ 5 files changed, 1441 insertions(+), 1408 deletions(-) create mode 100644 crates/ui-egui/src/view_cmds/arrange.rs create mode 100644 crates/ui-egui/src/view_cmds/dialogs.rs create mode 100644 crates/ui-egui/src/view_cmds/dispatch.rs create mode 100644 crates/ui-egui/src/view_cmds/options.rs diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs index 4eb811b290..afe640cc3f 100644 --- a/crates/ui-egui/src/view_cmds.rs +++ b/crates/ui-egui/src/view_cmds.rs @@ -13,6 +13,24 @@ use serde_json::{Map, Value, json}; use crate::PhotocraftApp; use crate::state::DialogKind; +mod arrange; +mod dialogs; +mod dispatch; +mod options; + +pub use arrange::cells; +pub(crate) use arrange::float_window; +#[cfg(test)] +use dialogs::{form, front, label_of}; +pub use dialogs::{form_body, form_keys, reset_form}; +pub(crate) use dialogs::write_copy; +#[cfg(test)] +use dispatch::is_enabled_with_engine; +pub use dispatch::{checked, handles, invoke, is_enabled}; +#[cfg(test)] +use options::screen_mode_commands; +pub use options::{persist, pixel_aspect_ratio, restore}; + /// View › Show flags (Photoshop defaults). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] @@ -171,898 +189,6 @@ const LAYOUTS: [&str; 10] = [ "tile", ]; -/// Whether the window was maximized when a screen mode took it full screen (egui temp data). -fn was_maximized_id() -> egui::Id { - egui::Id::unique("pc-full-screen-was-maximized") -} - -/// The window commands for switching to screen mode `next`, and whether the window should be -/// maximized again when it leaves full screen. With `keep_apart` (Windows), full screen and -/// maximized never overlap: a maximized window is un-maximized before it goes full screen and -/// maximized again after it leaves. Why: winit on Windows keeps the maximized style on a window -/// that goes full screen from maximized, and the shell then draws the taskbar black instead of -/// hiding it; on the way out the window stays maximized at the monitor's full size, over the -/// taskbar (#3550, #4018, #4230). [OBSERVED 2026-10-12, Windows 11, eframe 0.36.2, winit 0.30.13, -/// a minimal eframe window; un-maximizing first gave a clean full screen and a work-area maximize.] -/// -/// WORKAROUND(winit#4756): remove `keep_apart` once the winit in Cargo.lock (0.30.13 today) has -/// the fix; check first with https://gist.github.com/aweussom/3f80ffb82df7f0102341858afbbffd9b -/// (`--max`, no `--fix`: full screen must have no WS_MAXIMIZE and hide the taskbar). -fn screen_mode_commands(keep_apart: bool, full_screen: bool, maximized: bool, was_maximized: bool, next: &str) -> (Vec, bool) { - let want = next != "standard"; - let mut commands = Vec::new(); - let mut remember = was_maximized; - if keep_apart && want && !full_screen && maximized { - commands.push(egui::ViewportCommand::Maximized(false)); - remember = true; - } - commands.push(egui::ViewportCommand::Fullscreen(want)); - if !want { - if keep_apart && full_screen && remember { - commands.push(egui::ViewportCommand::Maximized(true)); - } - remember = false; - } - (commands, remember) -} - -/// Pixel aspect ratio (width / height of a pixel) of a preset id. -pub fn pixel_aspect_ratio(id: &str) -> f32 { - // View › Pixel Aspect Ratio › Custom: `custom::` (see `workspace_ui`). - if let Some(r) = id.strip_prefix("custom:").and_then(|r| r.split(':').next()?.parse::().ok()) { - return r; - } - match id { - "d1DvNtsc" => 0.91, - "d1DvPal" => 1.09, - "d1DvNtscWidescreen" => 1.21, - "hdv1080" => 1.33, - "d1DvPalWidescreen" => 1.46, - "dvcproHd1080" => 1.5, - "anamorphic2To1" => 2.0, - _ => 1.0, - } -} - -fn show_slot<'a>(s: &'a mut Show, key: &str) -> Option<&'a mut bool> { - Some(match key { - "layerEdges" => &mut s.layer_edges, - "selectionEdges" => &mut s.selection_edges, - "targetPath" => &mut s.target_path, - "pixelGrid" => &mut s.pixel_grid, - "smartGuides" => &mut s.smart_guides, - "brushPreview" => &mut s.brush_preview, - "slices" => &mut s.slices, - "notes" => &mut s.notes, - "mesh" => &mut s.mesh, - "editPins" => &mut s.edit_pins, - "count" => &mut s.count, - "canvasGuides" => &mut s.canvas_guides, - "artboardGuides" => &mut s.artboard_guides, - _ => return None, - }) -} - -fn snap_slot<'a>(s: &'a mut SnapTo, key: &str) -> Option<&'a mut bool> { - Some(match key { - "guides" => &mut s.guides, - "grid" => &mut s.grid, - "layers" => &mut s.layers, - "slices" => &mut s.slices, - "documentBounds" => &mut s.document_bounds, - _ => return None, - }) -} - -/// Every [`show_slot`] key. -const SHOW_KEYS: [&str; 13] = [ - "layerEdges", - "selectionEdges", - "targetPath", - "pixelGrid", - "smartGuides", - "brushPreview", - "slices", - "notes", - "mesh", - "editPins", - "count", - "canvasGuides", - "artboardGuides", -]; -/// Every [`snap_slot`] key. -const SNAP_KEYS: [&str; 5] = ["guides", "grid", "layers", "slices", "documentBounds"]; - -/// The flags of `now` that differ from `def`, by key (`None` when none do). -fn changed_flags(now: T, def: T, keys: &[&str], slot: impl for<'a> Fn(&'a mut T, &str) -> Option<&'a mut bool>) -> Option { - let (mut now, mut def) = (now, def); - let diff: Map = keys - .iter() - .filter_map(|k| { - let v = *slot(&mut now, k)?; - (Some(v) != slot(&mut def, k).copied()).then(|| ((*k).to_string(), Value::Bool(v))) - }) - .collect(); - (!diff.is_empty()).then_some(Value::Object(diff)) -} - -/// View › Extras, Show and Snap To as remembered across restarts (`Preferences::view_extras`): -/// only what differs from the defaults, so a default changed in a later release still reaches -/// users who never touched that item. `Null` when nothing differs. -fn remembered(app: &PhotocraftApp) -> Value { - let (v, e, def) = (&app.ui.view, &app.ui.extras, crate::state::Extras::default()); - let mut m = Map::new(); - if v.extras != ViewOptions::default().extras { - m.insert("extras".into(), Value::Bool(v.extras)); - } - // View › Show › Grid and Guides live in `UiState::extras` beside the rulers and snapping. - if e.grid != def.grid { - m.insert("grid".into(), Value::Bool(e.grid)); - } - if e.guides != def.guides { - m.insert("guides".into(), Value::Bool(e.guides)); - } - if e.snap != def.snap { - m.insert("snap".into(), Value::Bool(e.snap)); - } - if let Some(show) = changed_flags(v.show, Show::default(), &SHOW_KEYS, show_slot) { - m.insert("show".into(), show); - } - if let Some(snap) = changed_flags(v.snap_to, SnapTo::default(), &SNAP_KEYS, snap_slot) { - m.insert("snapTo".into(), snap); - } - if m.is_empty() { Value::Null } else { Value::Object(m) } -} - -/// Remember View › Extras, Show and Snap To in the preferences once the user lets go of the -/// pointer (#3762). Cheap: a small JSON compare per frame. Run every frame, so items set by the -/// control channel or the Show Extras Options dialog are remembered too. -pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { - if ctx.input(|i| i.pointer.any_down()) { - return; - } - let now = remembered(app); - if app.session.prefs().view_extras != now { - app.session.prefs.edit(|p| p.view_extras = now); - } -} - -/// Restore the remembered View › Extras, Show and Snap To items at launch. A hand-edited file -/// can't break them: an unknown key or a value that isn't a boolean keeps its default. -pub fn restore(app: &mut PhotocraftApp) { - let saved = app.session.prefs().view_extras.clone(); - if !saved.is_null() && !saved.is_object() { - log::warn!("Preferences: the remembered View › Show items are not an object; using the defaults"); - return; - } - let flag = |k: &str| saved.get(k).and_then(Value::as_bool); - if let Some(on) = flag("extras") { - app.ui.view.extras = on; - } - if let Some(on) = flag("grid") { - app.ui.extras.grid = on; - } - if let Some(on) = flag("guides") { - app.ui.extras.guides = on; - } - if let Some(on) = flag("snap") { - app.ui.extras.snap = on; - } - for (k, v) in saved.get("show").and_then(Value::as_object).into_iter().flatten() { - if let (Some(slot), Some(on)) = (show_slot(&mut app.ui.view.show, k), v.as_bool()) { - *slot = on; - } - } - for (k, v) in saved.get("snapTo").and_then(Value::as_object).into_iter().flatten() { - if let (Some(slot), Some(on)) = (snap_slot(&mut app.ui.view.snap_to, k), v.as_bool()) { - *slot = on; - } - } -} - -/// Window › : (panel, dock tab) for panels that live as tabs of a dock card. -fn panel_tab(app: &PhotocraftApp, id: &str) -> Option<(&'static str, usize)> { - let pro = app.ui.theme.is_pro(); - Some(match id { - "window.panel.info" => ("navigator", 2), - "window.panel.histogram" => ("navigator", 1), - "window.panel.navigator" => ("navigator", 0), - "window.panel.actions" => ("history", 1), - "window.panel.layerComps" => ("history", 2), - "window.panel.history" => ("history", 0), - "window.panel.channels" => ("layers", 1), - "window.panel.paths" => ("layers", 2), - "window.panel.layers" => ("layers", 0), - "window.panel.adjustments" => ("properties", 1), - "window.panel.properties" => ("properties", 0), - // Their own Character | Paragraph group, so Properties stays open (#150). - "window.panel.character" | "type.panels.character" => ("character", 0), - "window.panel.paragraph" | "type.panels.paragraph" => ("character", 1), - "window.panel.swatches" => ("color", usize::from(pro)), - "window.panel.color" => ("color", usize::from(!pro)), - _ => return None, - }) -} - -fn panel_state<'a>(app: &'a mut PhotocraftApp, panel: &str) -> (&'a mut bool, &'a mut usize) { - let (p, t) = (&mut app.ui.panels, &mut app.ui.dock_tabs); - match panel { - "navigator" => (&mut p.navigator, &mut t.navigator), - "history" => (&mut p.history, &mut t.history), - "layers" => (&mut p.layers, &mut t.layers), - "color" => (&mut p.color, &mut t.color), - "character" => (&mut p.character, &mut t.character), - _ => (&mut p.properties, &mut t.properties), - } -} - -/// Ids handled here (live menu items). -pub fn handles(id: &str) -> bool { - if let Some(k) = id.strip_prefix("view.show.") { - return show_slot(&mut Show::default(), k).is_some() || k == "all"; - } - if let Some(k) = id.strip_prefix("view.snapTo.") { - return snap_slot(&mut SnapTo::default(), k).is_some() || k == "all" || k == "none"; - } - if let Some(k) = id.strip_prefix("view.screenMode.") { - return SCREEN_MODES.contains(&k) || k == "cycle"; - } - if let Some(k) = id.strip_prefix("view.pixelAspectRatio.") { - return PIXEL_ASPECTS.contains(&k); - } - if let Some(k) = id.strip_prefix("type.fontPreviewSize.") { - return FONT_PREVIEW.contains(&k); - } - if let Some(k) = id.strip_prefix("type.languageOptions.") { - return LANGUAGE.contains(&k) || k == "middleEasternAndSouthAsianComposer"; - } - if let Some(k) = id.strip_prefix("window.arrange.") { - return LAYOUTS.contains(&k) - || matches!( - k, - "consolidateAllToTabs" - | "cascade" - | "floatInWindow" - | "floatAllInWindows" - | "newWindowForDocument" - | "matchZoom" - | "matchLocation" - | "matchRotation" - | "matchAll" - ); - } - matches!( - id, - "view.extras" - | "view.twoHundredPercent" - | "view.printSize" - | "view.fitLayersOnScreen" - | "view.fitArtboardOnScreen" - | "window.panel.layerComps" - | "view.flipHorizontal" - | "view.pixelAspectRatioCorrection" - | "view.patternPreview" - | "view.pixelArtPreview" - | "view.rotateView" - | "view.resetView" - | "window.panel.layers" - | "window.panel.history" - | "window.panel.navigator" - | "window.panel.properties" - | "window.panel.color" - | "window.panel.actions" - | "window.panel.channels" - | "window.panel.paths" - | "window.panel.character" - | "window.panel.paragraph" - | "window.panel.info" - | "window.panel.histogram" - | "window.panel.swatches" - | "window.panel.adjustments" - | "type.panels.character" - | "type.panels.paragraph" - ) -} - -pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option { - is_enabled_with_engine(app, id, || app.session.is_enabled(id)) -} - -/// Keep picker enablement testable with the engine's native filesystem check disabled. -fn is_enabled_with_engine(app: &PhotocraftApp, id: &str, engine_enabled: impl FnOnce() -> bool) -> Option { - if !handles(id) && !wraps(id) { - return None; - } - let doc = app.session.active().is_some(); - Some(match id { - "view.screenMode.cycle" => app.ui.text_edit.is_none(), - "view.twoHundredPercent" | "view.printSize" | "view.fitLayersOnScreen" | "view.rotateView" | "view.resetView" => doc, - "view.fitArtboardOnScreen" => app.session.active().is_some_and(|d| d.doc.has_artboards()), - i if i.starts_with("window.arrange.") => match &i["window.arrange.".len()..] { - "consolidateAllToTabs" => true, - "floatInWindow" | "newWindowForDocument" => doc, - "matchZoom" | "matchLocation" | "matchRotation" | "matchAll" => app.session.documents().len() > 1 || !app.ui.windows.is_empty(), - _ => { - app.session.documents().len() > 1 - || (doc && matches!(&i["window.arrange.".len()..], "floatAllInWindows" | "cascade" | "tile" | "tileAllVertically" | "tileAllHorizontally")) - } - }, - // Embedded placement reads the picker's bytes on every platform. Linked placement keeps - // the engine's native filesystem guard because its source must remain reachable. - "file.placeEmbedded" => doc && app.services.file_dialog.is_some(), - // Batch's dialog is built from an Actions-panel action. Keep it disabled until one - // exists instead of opening a menu item that can only report "record an action". - "file.automate.batch" => crate::actions::selected_action(app).is_some() && engine_enabled(), - i if wraps(i) => engine_enabled(), - _ => true, - }) -} - -pub fn checked(app: &PhotocraftApp, id: &str) -> Option { - let o = &app.ui.view; - if let Some(k) = id.strip_prefix("view.show.") { - let mut s = o.show; - return show_slot(&mut s, k).map(|b| *b); - } - if let Some(k) = id.strip_prefix("view.snapTo.") { - let mut s = o.snap_to; - return snap_slot(&mut s, k).map(|b| *b); - } - if let Some(k) = id.strip_prefix("view.screenMode.") { - return SCREEN_MODES.contains(&k).then(|| o.screen_mode == k); - } - if let Some(k) = id.strip_prefix("view.pixelAspectRatio.") { - return PIXEL_ASPECTS.contains(&k).then(|| o.pixel_aspect == k); - } - if let Some(k) = id.strip_prefix("type.fontPreviewSize.") { - return FONT_PREVIEW.contains(&k).then(|| o.font_preview_size == k); - } - if let Some(k) = id.strip_prefix("type.languageOptions.") { - return if k == "middleEasternAndSouthAsianComposer" { - Some(o.middle_eastern_composer) - } else { - LANGUAGE.contains(&k).then(|| o.language_features == k) - }; - } - if let Some(k) = id.strip_prefix("window.arrange.") - && LAYOUTS.contains(&k) - { - return Some(o.arrange == k); - } - if let Some((panel, tab)) = panel_tab(app, id) { - let (p, t) = (&app.ui.panels, &app.ui.dock_tabs); - let (vis, cur) = match panel { - "navigator" => (p.navigator, t.navigator), - "history" => (p.history, t.history), - "layers" => (p.layers, t.layers), - "color" => (p.color, t.color), - "character" => (p.character, t.character), - _ => (p.properties, t.properties), - }; - return Some(vis && cur == tab); - } - if let Some(c) = type_checked(app, id) { - return Some(c); - } - Some(match id { - "view.extras" => o.extras, - "view.flipHorizontal" => o.flip_horizontal, - "view.pixelAspectRatioCorrection" => o.pixel_aspect_correction, - "view.patternPreview" => o.pattern_preview, - "view.pixelArtPreview" => o.pixel_art_preview, - _ => return None, - }) -} - -/// Checkmarks of the Type menu's anti-aliasing, orientation and OpenType items, for the layer the -/// options bar and Properties show: the one being edited, else the active or a selected type layer. -/// Anti-aliasing and orientation stay check items (`Some(false)`) without a type layer: a native -/// menu can't change an item's kind in place. -fn type_checked(app: &PhotocraftApp, id: &str) -> Option { - let t = crate::type_tool::target_text(app); - if let Some(k) = id.strip_prefix("type.antiAlias.") { - return Some(t.is_some_and(|t| photocraft_engine::type_extra_cmds::aa_name(t.antialias) == k)); - } - if let Some(k) = id.strip_prefix("type.orientation.") { - return Some(t.is_some_and(|t| (t.orientation == photocraft_doc::text::Orientation::Vertical) == (k == "vertical"))); - } - let t = t?; - let tag = match id.strip_prefix("type.openType.")? { - "standardLigatures" => "liga", - "contextualAlternates" => "calt", - "discretionaryLigatures" => "dlig", - "swash" => "swsh", - "oldstyle" => "onum", - "stylisticAlternates" => "salt", - "titlingAlternates" => "titl", - "ornaments" => "ornm", - "ordinals" => "ordn", - "fractions" => "frac", - _ => return None, - }; - Some(t.char_runs().first().is_some_and(|r| photocraft_engine::type_extra_cmds::feature_on(&r.style, tag))) -} - -/// Engine commands that get a dialog or file picker here when invoked without parameters. -fn wraps(id: &str) -> bool { - matches!( - id, - "file.openAs" - | "file.openExrParts" - | "file.saveACopy" - | "file.placeEmbedded" - | "file.placeLinked" - | "layer.smartObjects.replaceContents" - | "layer.smartObjects.exportContents" - | "layer.smartObjects.relinkToFile" - | "layer.smartObjects.convertToLinked" - | "file.closeAll" - | "file.closeOthers" - | "file.fileInfo" - | "file.automate.fitImage" - | "file.automate.conditionalModeChange" - | "file.automate.batch" - | "file.scripts.imageProcessor" - | "file.scripts.loadFilesIntoStack" - | "file.automate.photomerge" - | "file.automate.mergeToHdrPro" - | "file.automate.lensCorrection" - | "file.export.layersToFiles" - | "file.export.layerCompsToFiles" - | "file.export.artboardsToFiles" - | "file.export.artboardsToPdf" - | "layer.new.artboard" - | "file.export.colorLookupTables" - | "view.newGuideLayout" - | "type.warpText" - | "type.pasteLoremIpsum" - | "image.applyImage" - | "image.calculations" - | "select.saveSelection" - | "select.loadSelection" - | "layer.videoLayers.newVideoLayerFromFile" - | "layer.videoLayers.replaceFootage" - | "layer.videoLayers.interpretFootage" - ) -} - -fn no_params(p: &Value) -> bool { - p.as_object().is_none_or(|o| o.is_empty()) -} - -/// Run a View/Window/Type shell command, or front an engine command with its dialog. `None` when -/// `id` isn't ours. -pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { - if wraps(id) { - return front(app, ctx, id, params); - } - if !handles(id) { - return None; - } - Some(run(app, ctx, id, params)) -} - -fn flag_param(p: &Value, cur: bool) -> bool { - p.get("on").and_then(Value::as_bool).unwrap_or(!cur) -} - -fn run(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, p: &Value) -> Result { - if let Some((panel, tab)) = panel_tab(app, id) { - let group = crate::dock::Group::from_key(panel); - let collapsed = group.is_some_and(|g| app.ui.dock.is_collapsed(g)); - let (vis, cur) = panel_state(app, panel); - let requested = match p.get("show").or_else(|| p.get("on")) { - None => None, - Some(value) => Some(value.as_bool().ok_or("show must be a boolean")?), - }; - if let Some(show) = requested { - *vis = show; - if show { - *cur = tab; - } - } else { - // Like Photoshop: choosing a visible panel's menu item again hides it. A collapsed - // group is expanded instead, so the menu item always brings the panel back (#129). - if *vis && *cur == tab && !collapsed && !id.starts_with("type.panels.") { - *vis = false; - } else { - *vis = true; - *cur = tab; - } - } - let visible = *vis; - if let Some(g) = group.filter(|_| visible) { - crate::dock::reveal(app, g); - } - return Ok(json!({"panel": panel, "tab": tab, "visible": visible})); - } - if id == "view.rotateView" { - return crate::rotate_view::command(app, p); - } - if id == "view.resetView" { - return crate::rotate_view::reset(app); - } - let o = &mut app.ui.view; - if let Some(k) = id.strip_prefix("view.show.") { - if k == "all" { - o.show = Show { layer_edges: true, mesh: true, ..Show::default() }; - o.extras = true; - app.ui.extras.grid = true; - app.ui.extras.guides = true; - return Ok(json!(true)); - } - let slot = show_slot(&mut o.show, k).ok_or("unknown Show item")?; - *slot = flag_param(p, *slot); - let v = *slot; - if v { - // Showing an item turns Extras back on, as in Photoshop. - o.extras = true; - } - return Ok(json!(v)); - } - if let Some(k) = id.strip_prefix("view.snapTo.") { - if k == "all" || k == "none" { - let on = k == "all"; - o.snap_to = SnapTo { guides: on, grid: on, layers: on, slices: on, document_bounds: on }; - return Ok(json!(on)); - } - let slot = snap_slot(&mut o.snap_to, k).ok_or("unknown Snap To item")?; - *slot = flag_param(p, *slot); - return Ok(json!(*slot)); - } - if let Some(k) = id.strip_prefix("view.screenMode.") { - let next = if k == "cycle" { - let i = SCREEN_MODES.iter().position(|m| *m == o.screen_mode).unwrap_or(0); - SCREEN_MODES[(i + 1) % SCREEN_MODES.len()] - } else { - k - }; - o.screen_mode = next.to_string(); - // Tab's view of the chrome (#6760) lasts only while in Full Screen Mode. - app.ui.panels.full_screen_chrome = false; - // Both full-screen modes take the whole display; the menu bar stays in the first. - let (full_screen, maximized) = ctx.input(|i| (i.viewport().fullscreen.unwrap_or(false), i.viewport().maximized.unwrap_or(false))); - let was_maximized = ctx.data(|d| d.get_temp::(was_maximized_id())).unwrap_or(false); - let (commands, was_maximized) = screen_mode_commands(cfg!(target_os = "windows"), full_screen, maximized, was_maximized, next); - ctx.data_mut(|d| d.insert_temp(was_maximized_id(), was_maximized)); - for command in commands { - ctx.send_viewport_cmd(command); - } - return Ok(json!({"screenMode": next})); - } - if let Some(k) = id.strip_prefix("view.pixelAspectRatio.") { - o.pixel_aspect = k.to_string(); - return Ok(json!({"pixelAspectRatio": pixel_aspect_ratio(k)})); - } - if let Some(k) = id.strip_prefix("type.fontPreviewSize.") { - o.font_preview_size = k.to_string(); - return Ok(json!(k)); - } - if let Some(k) = id.strip_prefix("type.languageOptions.") { - if k == "middleEasternAndSouthAsianComposer" { - o.middle_eastern_composer = flag_param(p, o.middle_eastern_composer); - return Ok(json!(o.middle_eastern_composer)); - } - o.language_features = k.to_string(); - return Ok(json!(k)); - } - if let Some(k) = id.strip_prefix("window.arrange.") { - return arrange(app, k, p); - } - match id { - "view.extras" => { - o.extras = flag_param(p, o.extras); - Ok(json!(o.extras)) - } - "view.flipHorizontal" => { - o.flip_horizontal = flag_param(p, o.flip_horizontal); - Ok(json!(o.flip_horizontal)) - } - "view.pixelAspectRatioCorrection" => { - o.pixel_aspect_correction = flag_param(p, o.pixel_aspect_correction); - Ok(json!(o.pixel_aspect_correction)) - } - "view.patternPreview" => { - o.pattern_preview = flag_param(p, o.pattern_preview); - Ok(json!(o.pattern_preview)) - } - "view.pixelArtPreview" => { - o.pixel_art_preview = flag_param(p, o.pixel_art_preview); - Ok(json!(o.pixel_art_preview)) - } - "view.twoHundredPercent" | "view.printSize" => { - let i = app.session.active_index().ok_or("no document")?; - // Print Size shows the document at its print size for the screen resolution - // (Preferences ▸ Units & Rulers: Screen Resolution, 72 ppi by default). - let dpi = app.session.active().map_or(72.0, |d| d.doc.resolution_dpi.max(1.0)); - let size = app.session.active().map_or([0, 0], |d| [d.doc.size.width, d.doc.size.height]); - let screen = app.session.prefs().units_and_rulers.screen_resolution.max(1.0) as f32; - let z = if id == "view.twoHundredPercent" { 2.0 } else { screen / dpi }; - app.ui.views[i].zoom = crate::zoom_levels::clamp(z, size); - app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); - app.ui.views[i].zoom_anchor = None; - Ok(json!({"zoom": app.ui.views[i].zoom})) - } - "view.fitLayersOnScreen" => fit_layers(app), - "view.fitArtboardOnScreen" => crate::artboard_ui::fit_artboard(app), - _ => Err(format!("unhandled {id}")), - } -} - -/// View › Fit Layer(s) on Screen: zoom and centre on the selected layers' bounds. -fn fit_layers(app: &mut PhotocraftApp) -> Result { - let i = app.session.active_index().ok_or("no document")?; - let st = app.session.active().ok_or("no document")?; - let mut b = photocraft_geom::Rect::EMPTY; - for id in st.selected_layers() { - if let Some(r) = st.doc.layer(id).and_then(|l| l.surface()).map(|s| s.content_bounds()) { - b = if b.is_empty() { r } else { b.union(&r) }; - } - } - if b.is_empty() { - b = st.doc.bounds(); - } - let size = [st.doc.size.width, st.doc.size.height]; - let area = app.last_canvas_rect.size(); - let area = if area.x > 50.0 { area } else { egui::vec2(1200.0, 800.0) }; - // The area is in egui points; the stored zoom is device pixels per document pixel. - let ppp = app.canvas_ppp(); - let points = ((area.x - 40.0) / b.width().max(1) as f32).min((area.y - 40.0) / b.height().max(1) as f32); - let v = &mut app.ui.views[i]; - v.zoom = crate::zoom_levels::clamp(points * ppp, size); - v.center = [(b.x0 + b.x1) as f32 / 2.0, (b.y0 + b.y1) as f32 / 2.0]; - v.fit_pending = false; - v.request_zoom_animation(app.session.prefs().general.animated_zoom); - v.zoom_anchor = None; - Ok(json!({"zoom": v.zoom, "bounds": [b.x0, b.y0, b.x1, b.y1]})) -} - -/// A finite `[x, y]` screen position within a sane range (window systems reject wild values). -fn screen_position(v: &Value) -> Option<[f32; 2]> { - const LIMIT: f64 = 1.0e6; - let a = v.as_array().filter(|a| a.len() == 2)?; - let n = |i: usize| a.get(i).and_then(Value::as_f64).filter(|x| x.is_finite() && x.abs() <= LIMIT).map(|x| x as f32); - Some([n(0)?, n(1)?]) -} - -pub(crate) fn float_window(app: &mut PhotocraftApp, doc: usize, offset: usize) -> u64 { - let wid = app.ui.alloc_id(); - let mut view = app.ui.views.get(doc).cloned().unwrap_or_default(); - view.zoom_animating = false; - view.zoom_anchor = None; - view.zoom_transition = None; - view.display_camera = None; - view.fit_pending = offset > 0 || view.fit_pending; - app.ui.windows.push(crate::state::DocWindow { id: wid, document: doc, view, open: true, position: None }); - wid -} - -fn arrange(app: &mut PhotocraftApp, k: &str, p: &Value) -> Result { - if LAYOUTS.contains(&k) { - app.ui.view.arrange = k.to_string(); - // Each document fits its new cell. - app.ui.views.iter_mut().for_each(|v| v.fit_pending = true); - return Ok(json!({"arrange": k})); - } - match k { - "consolidateAllToTabs" => { - app.ui.view.arrange = "tabs".into(); - app.ui.windows.clear(); - Ok(json!({"arrange": "tabs"})) - } - "newWindowForDocument" => { - let doc = app.session.active_index().ok_or("no document")?; - Ok(json!({"window": float_window(app, doc, 0)})) - } - // Optional `document` (index; default the active one) and `position` (`[x, y]`, the - // window's screen position in points): dragging a tab off the tab strip uses both (#3733). - "floatInWindow" => { - let doc = match p.get("document") { - None | Some(Value::Null) => app.session.active_index().ok_or("no document")?, - Some(v) => { - let i = v.as_u64().ok_or("document must be a document index")?; - usize::try_from(i).ok().filter(|&i| i < app.session.documents().len()).ok_or(format!("no document {i}"))? - } - }; - let position = match p.get("position") { - None | Some(Value::Null) => None, - Some(v) => Some(screen_position(v).ok_or("position must be [x, y] in points")?), - }; - let wid = float_window(app, doc, 0); - if let Some(w) = app.ui.windows.iter_mut().find(|w| w.id == wid) { - w.position = position; - } - app.session.set_active(doc); - Ok(json!({"window": wid})) - } - "floatAllInWindows" | "cascade" => { - let n = app.session.documents().len(); - let ids: Vec = (0..n).map(|d| float_window(app, d, d)).collect(); - Ok(json!({"windows": ids})) - } - "matchZoom" | "matchLocation" | "matchRotation" | "matchAll" => { - let i = app.session.active_index().ok_or("no document")?; - let src = app.ui.views.get(i).cloned().ok_or("no document")?; - let (zoom, loc, rot) = - (matches!(k, "matchZoom" | "matchAll"), matches!(k, "matchLocation" | "matchAll"), matches!(k, "matchRotation" | "matchAll")); - let animated_zoom = app.session.prefs().general.animated_zoom; - // Each view stays within its own document's zoom range (a view not drawn yet has no - // `doc_size`, so the size comes from the document). - let sizes: Vec<[u32; 2]> = app.session.documents().iter().map(|d| [d.doc.size.width, d.doc.size.height]).collect(); - let apply = |v: &mut crate::state::View, doc: usize| { - if zoom { - v.zoom = crate::zoom_levels::clamp(src.zoom, sizes.get(doc).copied().unwrap_or(v.doc_size)); - v.request_zoom_animation(animated_zoom); - } - if loc { - v.center = src.center; - } - if rot { - v.rotation = src.rotation; - } - v.fit_pending = false; - }; - app.ui.views.iter_mut().enumerate().for_each(|(d, v)| apply(v, d)); - app.ui.windows.iter_mut().for_each(|w| apply(&mut w.view, w.document)); - Ok(json!({"zoom": src.zoom, "center": src.center, "rotation": src.rotation})) - } - _ => Err(format!("unknown arrangement {k}")), - } -} - -/// Screen rectangles for `n` documents in an arrangement (`None` = tabs). The active document -/// always gets a cell; n-up layouts show that many documents starting from the active one. -pub fn cells(layout: &str, rect: egui::Rect, n: usize) -> Option> { - use craft_ui::layout::{SplitAxis, SplitSize, split_rect}; - - if n < 2 || !LAYOUTS.contains(&layout) { - return None; - } - let grid = |cols: usize, rows: usize, count: usize| -> Vec { - let (w, h) = (rect.width() / cols as f32, rect.height() / rows as f32); - (0..count.min(cols * rows)) - .map(|i| egui::Rect::from_min_size(rect.min + egui::vec2((i % cols) as f32 * w, (i / cols) as f32 * h), egui::vec2(w, h))) - .collect() - }; - Some(match layout { - "tileAllVertically" => grid(n, 1, n), - "tileAllHorizontally" => grid(1, n, n), - "twoUpVertical" => { - let panes = split_rect(rect, SplitAxis::Horizontal, SplitSize::Ratio(0.5), 0.0, 0.0)?; - vec![panes.first, panes.second] - } - "twoUpHorizontal" => { - let panes = split_rect(rect, SplitAxis::Vertical, SplitSize::Ratio(0.5), 0.0, 0.0)?; - vec![panes.first, panes.second] - } - "threeUpVertical" => grid(3, 1, 3), - "threeUpHorizontal" => grid(1, 3, 3), - "threeUpStacked" => { - let columns = split_rect(rect, SplitAxis::Horizontal, SplitSize::Ratio(0.5), 0.0, 0.0)?; - let rows = split_rect(columns.second, SplitAxis::Vertical, SplitSize::Ratio(0.5), 0.0, 0.0)?; - vec![columns.first, rows.first, rows.second] - } - "fourUp" => grid(2, 2, 4), - "sixUp" => grid(3, 2, 6), - _ => { - let cols = (n as f32).sqrt().ceil() as usize; - grid(cols, n.div_ceil(cols), n) - } - }) -} - -// ---------- dialogs and pickers in front of engine commands ---------- - -/// A generic form dialog that runs `command` with its fields on OK (rendered by [`form_body`]). -/// File › Open EXR Parts…: pick an EXR, then choose the parts and channel groups that become -/// the layers of one document (a Maya/Arnold render writes one part per AOV). The dialog is -/// a plain command form, so the control channel can drive the same selection headlessly. -fn open_exr_parts_dialog(app: &mut PhotocraftApp) -> Option> { - Some(app.pick_file_bytes_filtered(&["exr"], |app, name, _bytes| { - let info = app.run("file.exrParts", json!({"path": name})).map_err(|e| e.to_string())?; - let entries = info.as_array().cloned().unwrap_or_default(); - let mut fields = Map::new(); - fields.insert("path".into(), json!(name)); - fields.insert("view".into(), json!("both")); - fields.insert("precomp".into(), json!(false)); - let mut labels = Map::new(); - // The path field shows the picked file's name (data, verbatim); the rest translate. - if let Some(file) = name.rsplit(['/', '\\']).next() { - labels.insert("path".into(), json!(file)); - } - labels.insert("view".into(), json!(crate::i18n::t("View"))); - labels.insert("both".into(), json!(crate::i18n::t("Both"))); - labels.insert("left".into(), json!(crate::i18n::t("Left"))); - labels.insert("right".into(), json!(crate::i18n::t("Right"))); - labels.insert("precomp".into(), json!(crate::i18n::t("Add beauty precomp from the AOVs"))); - let mut any = false; - for e in &entries { - let kind = e["kind"].as_str().unwrap_or_default().to_string(); - let ename = e["name"].as_str().unwrap_or_default().to_string(); - let channels = e["channels"].as_u64().unwrap_or(0); - let key = format!("{kind}/{ename}"); - match kind.as_str() { - "part" => { - labels.insert(key.clone(), json!(format!("{ename} ({}×{}, {channels} ch)", e["width"], e["height"]))); - let on = !any && channels >= 3; - any |= on; - fields.insert(key, json!(on)); - } - "group" => { - labels.insert(key.clone(), json!(format!("{ename} ({channels} ch)"))); - fields.insert(key, json!(false)); - } - _ => {} - } - } - // Cryptomatte layers are information here (the picker comes separately); the array is - // not rendered but rides along for the control channel. - let crypto: Vec = entries.iter().filter(|e| e["kind"] == "cryptomatte").cloned().collect(); - if !crypto.is_empty() { - fields.insert("cryptomatte".into(), Value::Array(crypto)); - } - fields.insert("__labels".into(), Value::Object(labels)); - let choices = json!({"view": ["both", "left", "right"]}); - Ok(json!({"dialog": form(app, "file.openExrParts", "Open EXR Parts…", Value::Object(fields), choices)})) - })) -} - -fn form(app: &mut PhotocraftApp, command: &str, label: &str, fields: Value, choices: Value) -> u64 { - let mut f = Map::new(); - f.insert("__command".into(), json!(command)); - f.insert("__label".into(), json!(label)); - f.insert("__form".into(), json!(true)); - f.insert("__choices".into(), choices); - if let Value::Object(m) = fields { - f.extend(m); - } - // Snapshot user-facing params at open so Alt+Reset can restore them. - let orig: Map = f.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); - f.insert("__formOrig".into(), Value::Object(orig)); - app.ui.open_dialog(DialogKind::Command, f) -} - -/// The Batch and Image Processor dialogs' "Include All Subfolders" checkbox reads as Photoshop's. -fn subfolders_label() -> Value { - json!({"includeSubfolders": tl!("Include All Subfolders")}) -} - -/// Alt+Cancel (Reset): restore the `__form` params captured at open. -pub fn reset_form(f: &mut Map) { - if !f.contains_key("__form") { - return; - } - let Some(Value::Object(orig)) = f.get("__formOrig").cloned() else { return }; - f.retain(|k, _| k.starts_with("__")); - f.extend(orig); -} - -fn label_of(key: &str) -> String { - // A name that already reads as text ("iPhone 14 Pro Max", "Web 1920") is not camelCase. - if key.contains(' ') { - return tl!(key).to_owned(); - } - let mut out = String::new(); - for (i, c) in key.chars().enumerate() { - if i == 0 { - out.extend(c.to_uppercase()); - } else if c.is_uppercase() { - out.push(' '); - out.extend(c.to_lowercase()); - } else { - out.push(c); - } - } - let translated = tl!(&out); - if translated != out { - return translated.to_owned(); - } - // Fall back to the Title Case filter label's translation, but keep the sentence-case - // English when that is untranslated too (English and partial catalogs read as before). - let title = crate::filter_dialog::label(key); - if title == crate::filter_dialog::source_label(key) { out } else { title } -} - #[cfg(test)] mod label_tests { use super::label_of; @@ -1096,522 +222,6 @@ mod form_reset_tests { } } -/// Display order of a `__form` dialog's field keys. `__order` lists them the way Photoshop -/// shows them (e.g. File Info); keys it omits keep their catalogue order after it. -pub fn form_keys(f: &Map) -> Vec { - let mut keys: Vec = f - .get("__order") - .and_then(Value::as_array) - .into_iter() - .flatten() - .filter_map(Value::as_str) - .filter(|k| !k.starts_with("__") && f.contains_key(*k)) - .map(str::to_string) - .collect(); - let rest: Vec = f.keys().filter(|k| !k.starts_with("__") && !keys.contains(k)).cloned().collect(); - keys.extend(rest); - keys -} - -/// Body of a `__form` dialog: text fields, number fields, checkboxes and `__choices` dropdowns. -pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { - let choices = f.get("__choices").cloned().unwrap_or(Value::Null); - // Data-driven labels (a per-part checkbox shows the part's name, not a catalogue entry) - // come from `__labels` verbatim; everything else goes through the catalogue. - let labels = f.get("__labels").cloned().unwrap_or(Value::Null); - let label = |k: &str| labels.get(k).and_then(Value::as_str).map_or_else(|| label_of(k), str::to_string); - let keys = form_keys(f); - let mut browse: Option = None; - egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { - for k in keys { - let v = f.get(&k).cloned().unwrap_or(Value::Null); - if k == "naming" && f.get("__command").and_then(Value::as_str) == Some("file.automate.batch") { - let label = ui.label(tl!("File Naming")); - let mut naming = v.as_str().unwrap_or_default().to_owned(); - ui.add(egui::TextEdit::singleline(&mut naming).desired_width(260.0).hint_text("{name}")) - .labelled_by(label.id) - .on_hover_text("{name} · {serial} · {date} (UTC)"); - f.insert(k, json!(naming)); - ui.end_row(); - continue; - } - if k == "quality" && f.get("__command").and_then(Value::as_str) == Some("file.automate.batch") { - ui.label(label(&k)); - let mut custom = v.as_f64().is_some(); - let mut quality = v.as_f64().or_else(|| f.get("__batchQuality").and_then(Value::as_f64)).unwrap_or(8.0).clamp(0.0, 12.0) as f32; - ui.horizontal(|ui| { - crate::widgets::checkbox(ui, &mut custom, tl!("Custom")); - ui.add_enabled_ui(custom, |ui| crate::widgets::value_field(ui, &mut quality, 0.0..=12.0, "", 74.0).accessible_name(tl!("Quality"))); - }); - // None preserves the command's existing JPEG and lossless WebP defaults. - // The inactive custom value is shell state, never a command parameter. - f.insert("__batchQuality".into(), json!(quality)); - f.insert(k, if custom { json!(quality) } else { Value::Null }); - ui.end_row(); - continue; - } - let new = match &v { - Value::Array(_) | Value::Object(_) | Value::Null => continue, - Value::Bool(b) => { - ui.label(""); - let mut b = *b; - ui.checkbox(&mut b, label(&k)); - json!(b) - } - Value::String(s) => { - ui.label(label(&k)); - let mut s = s.clone(); - match choices.get(&k).and_then(Value::as_array) { - Some(opts) => { - let opts: Vec<(String, String)> = opts.iter().filter_map(Value::as_str).map(|o| (o.to_string(), label(o))).collect(); - let refs: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect(); - crate::widgets::dropdown(ui, &format!("form-{k}"), &label(&k), &mut s, &refs, 200.0); - } - None => { - ui.horizontal(|ui| { - ui.add(egui::TextEdit::singleline(&mut s).desired_width(260.0)).accessible_name(label(&k)); - // A folder field gets the system folder picker (#7942, #9357). - if crate::dialogs::is_folder_field(&k) && crate::widgets::secondary_button(ui, tl!("Browse…"), 0.0).clicked() { - browse = Some(k.clone()); - } - }); - } - } - json!(s) - } - Value::Number(n) => { - ui.label(label(&k)); - if let Some(mut i) = n.as_i64() { - ui.add(egui::DragValue::new(&mut i).custom_parser(crate::widgets::parse_num)).accessible_name(label(&k)); - json!(i) - } else { - let mut x = n.as_f64().unwrap_or(0.0); - ui.add(egui::DragValue::new(&mut x).speed(0.5).custom_parser(crate::widgets::parse_num)).accessible_name(label(&k)); - json!(x) - } - } - }; - f.insert(k, new); - ui.end_row(); - } - }); - if let Some(key) = browse { - f.insert(crate::dialogs::BROWSE_FIELD.into(), json!(key)); - } - camera_data(ui, f); -} - -/// File Info's read-only Camera Data section (`__camera`, from the document's EXIF/XMP). -fn camera_data(ui: &mut egui::Ui, f: &Map) { - let Some(camera) = f.get("__camera").and_then(Value::as_object).filter(|c| !c.is_empty()) else { return }; - ui.add_space(10.0); - ui.label(egui::RichText::new(tl!("Camera Data")).font(crate::theme::semibold(13.0))); - ui.add_space(4.0); - egui::Grid::new("form-camera-data").num_columns(2).spacing([12.0, 4.0]).show(ui, |ui| { - for (key, label) in photocraft_engine::file_cmds::CAMERA_FIELDS { - if let Some(v) = camera.get(key).and_then(Value::as_str) { - ui.label(crate::i18n::tr_ctx(crate::i18n::current(), "cameraData", label)); - ui.add(egui::Label::new(v).selectable(true)); - ui.end_row(); - } - } - }); -} - -/// Folder the batch dialogs start from: next to the active document, else the working directory. -fn default_dir(app: &PhotocraftApp) -> String { - app.session.active().and_then(|d| d.path.as_deref()).and_then(|p| p.rfind(['/', '\\']).map(|i| p[..i].to_string())).unwrap_or_else(|| ".".into()) -} - -fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { - if id == "file.closeAll" || id == "file.closeOthers" { - // Keep the remaining document's view (views are index-aligned with documents). - let keep = app.session.active_index().and_then(|i| app.ui.views.get(i).cloned()); - let r = app.run(id, params.clone()); - if r.is_ok() { - app.ui.views = if id == "file.closeAll" { Vec::new() } else { keep.into_iter().collect() }; - app.ui.windows.clear(); - app.sync_views(); - } - return Some(r); - } - if id == "type.pasteLoremIpsum" && no_params(params) { - // While typing, paste at the caret. - if let Some(te) = app.ui.text_edit.clone() { - let r = app.run(id, json!({"layer": te.layer, "at": te.caret, "coalesce": te.session})); - if let (Ok(v), Some(te)) = (&r, app.ui.text_edit.as_mut()) - && let Some(c) = v.get("caret").and_then(Value::as_u64) - { - te.caret = c as usize; - te.anchor = c as usize; - } - return Some(r); - } - return None; - } - if !no_params(params) { - return None; - } - let doc = app.session.active().map(|d| (d.doc.size.width, d.doc.size.height, d.doc.name.clone())); - let dir = default_dir(app); - let label = photocraft_engine::commands::find(id).map_or(id, |c| c.label); - let dialog = |app: &mut PhotocraftApp, fields: Value, choices: Value| Some(Ok(json!({"dialog": form(app, id, label, fields, choices)}))); - match id { - "file.openAs" => Some(app.open_dialog_file()), - "file.openExrParts" => open_exr_parts_dialog(app), - "file.saveACopy" => Some(save_a_copy(app)), - "file.placeEmbedded" | "file.placeLinked" => { - if app.ui.transform.is_some() { - return Some(Err("Commit or cancel the transform first".into())); - } - let doc = match app.active_doc_id() { - Ok(doc) => doc, - Err(e) => return Some(Err(e)), - }; - let linked = id == "file.placeLinked"; - let ctx = ctx.clone(); - Some(app.pick_file_bytes(move |app, name, bytes| { - if app.ui.transform.is_some() { - return Err("Commit or cancel the transform first".into()); - } - app.refocus(doc)?; - let linked = linked.then(|| name.clone()); - let result = app.place_bytes(&name, bytes, linked)?; - crate::transform_tool::begin_placed(app, &ctx)?; - Ok(result) - })) - } - "layer.smartObjects.replaceContents" => { - let st = app.session.active()?; - let (doc, layer) = (st.doc.id, st.active_layer?); - Some(app.pick_file_bytes(move |app, name, bytes| { - app.with_document(doc, |app| { - let r = photocraft_engine::smart_cmds::replace_contents_bytes(&mut app.session, layer, &name, bytes).map_err(|e| e.to_string()); - app.sync_views(); - r - }) - })) - } - "layer.smartObjects.exportContents" => Some(export_contents(app)), - "layer.smartObjects.relinkToFile" => { - let st = app.session.active()?; - let (doc, layer) = (st.doc.id, st.active_layer?); - // A link needs a file on disk: the desktop picker answers its full path, the web - // picker only a name and the bytes, which can't be linked to. - Some(app.pick_file_bytes(move |app, path, _| { - if !std::path::Path::new(&path).is_absolute() { - return Err(format!("{path}: Relink to File needs a file on disk")); - } - app.with_document(doc, |app| app.run("layer.smartObjects.relinkToFile", json!({"layer": layer.0, "path": path}))) - })) - } - "layer.smartObjects.convertToLinked" => { - let st = app.session.active()?; - let (doc, layer) = (st.doc.id, st.active_layer?); - let (name, _) = match photocraft_engine::smart_cmds::contents_of(&st.doc, layer) { - Ok(c) => c, - Err(e) => return Some(Err(e.to_string())), - }; - Some(app.pick_save(&name, move |app, path| { - app.with_document(doc, |app| app.run("layer.smartObjects.convertToLinked", json!({"layer": layer.0, "path": path}))) - })) - } - "layer.videoLayers.newVideoLayerFromFile" | "layer.videoLayers.replaceFootage" => { - let doc = match app.active_doc_id() { - Ok(doc) => doc, - Err(e) => return Some(Err(e)), - }; - let cmd = id.to_string(); - Some(app.pick_file_bytes(move |app, path, _bytes| { - app.with_document(doc, |app| { - let r = app.run(&cmd, json!({"path": path})); - if r.is_ok() && app.session.active().is_some_and(|d| d.doc.timeline.is_some()) { - app.ui.timeline.open = true; - } - app.sync_views(); - r - }) - })) - } - "layer.videoLayers.interpretFootage" => { - let st = app.session.active()?; - let id_layer = st.active_layer?; - let fps = st.doc.layer(id_layer).and_then(|l| l.video.as_ref()).map_or(30.0, |v| v.fps); - dialog(app, json!({"fps": fps}), json!({})) - } - "file.fileInfo" => { - let info = app.session.execute("file.fileInfo", json!({})).ok()?; - let kw = info["keywords"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::>().join("; ")).unwrap_or_default(); - dialog( - app, - json!({ - "title": info["title"], - "author": info["author"], - "authorTitle": info["authorTitle"], - "description": info["description"], - "keywords": kw, - "copyrightStatus": info["copyrightStatus"], - "copyright": info["copyright"], - "copyrightUrl": info["copyrightUrl"], - "__order": ["title", "author", "authorTitle", "description", "keywords", "copyrightStatus", "copyright", "copyrightUrl"], - "__labels": { - "title": tl!("Document Title"), - "copyright": tl!("Copyright Notice"), - "copyrightUrl": tl!("Copyright Info URL"), - }, - "__camera": info["camera"] - }), - json!({"copyrightStatus": ["unknown", "copyrighted", "publicDomain"]}), - ) - } - "file.automate.fitImage" => { - let (w, h, _) = doc?; - dialog(app, json!({"width": w, "height": h, "dontEnlarge": false, "__compact": true}), json!({})) - } - "file.automate.conditionalModeChange" => dialog( - app, - json!({"from": "any", "to": "rgb"}), - json!({"from": ["any", "rgb", "grayscale", "cmyk", "lab", "indexed", "bitmap", "duotone", "multichannel"], "to": ["rgb", "grayscale", "cmyk", "lab"]}), - ), - "view.newGuideLayout" => Some(Ok(json!({"dialog": crate::guide_layout_ui::open(app)}))), - "type.warpText" => Some(Ok(json!({"dialog": crate::dialogs::open_command_dialog(app, id, label)}))), - "file.export.layersToFiles" => { - let (_, _, name) = doc?; - dialog( - app, - json!({"dir": dir, "prefix": name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a), "format": "png", "visibleOnly": true}), - json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]}), - ) - } - "file.export.layerCompsToFiles" | "file.export.artboardsToFiles" => { - let (_, _, name) = doc?; - let prefix = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); - let fields = if id == "file.export.layerCompsToFiles" { - json!({"dir": dir, "prefix": prefix, "format": "png", "selectedOnly": false}) - } else { - json!({"dir": dir, "prefix": prefix, "format": "png"}) - }; - dialog(app, fields, json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]})) - } - "file.export.artboardsToPdf" => { - let (_, _, name) = doc?; - let stem = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); - dialog(app, json!({"path": format!("{dir}/{stem}.pdf"), "quality": 10}), json!({})) - } - "layer.new.artboard" => { - let (w, h, _) = doc?; - let presets: Vec<&str> = std::iter::once("").chain(photocraft_engine::artboard_cmds::PRESETS.iter().map(|p| p.0)).collect(); - dialog( - app, - json!({"name": "", "preset": "", "width": w, "height": h, "background": "white"}), - json!({"preset": presets, "background": ["white", "black", "transparent"]}), - ) - } - "file.export.colorLookupTables" => { - let (_, _, name) = doc?; - let stem = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); - // A selected adjustment is a common use case, but existing no-selection exports - // continue to bake the entire visible stack. The scope remains explicit in the UI. - let selected_adjustments = app.session.active().is_some_and(|st| { - let chosen = st.selected_layers(); - !chosen.is_empty() - && chosen.iter().all(|id| { - st.doc.layers.iter().any(|root| root.id == *id) - && st.doc.layer(*id).is_some_and(|layer| layer.visible && matches!(layer.content, photocraft_doc::LayerContent::Adjustment(_))) - }) - }); - let scope = if selected_adjustments { "selected" } else { "all" }; - dialog(app, json!({"path": format!("{dir}/{stem}.cube"), "size": 33, "title": stem, "scope": scope}), json!({"scope": ["all", "selected"]})) - } - "file.scripts.loadFilesIntoStack" => Some(Ok(json!({"dialog": crate::stack_dialog::open(app)}))), - // Photography automation (photo_cmds / lens_cmds): a folder (or the open documents). - "file.automate.photomerge" => dialog( - app, - json!({"paths": dir, "useOpenDocuments": false, "layout": "auto", "blend": true, "vignetteRemoval": false, "geometricCorrection": false, "contentAwareFill": false}), - json!({"layout": ["auto", "perspective", "cylindrical", "spherical", "collage", "reposition"]}), - ), - "file.automate.mergeToHdrPro" => dialog( - app, - json!({"paths": dir, "useOpenDocuments": false, "align": true, "removeGhosts": false, "mode": "32", "method": "localAdaptation", "radius": 7.0, "strength": 0.52, "gamma": 1.0, "exposure": 0.0, "detail": 30.0, "saturation": 20.0}), - json!({"mode": ["32", "16", "8"], "method": ["localAdaptation", "exposureGamma", "highlightCompression", "equalizeHistogram"]}), - ), - "file.automate.lensCorrection" => dialog( - app, - json!({"input": dir, "output": format!("{dir}/corrected"), "format": "same", "profile": "auto", "correctDistortion": true, "correctVignette": true, "correctCA": true, "autoScale": true, "edge": "transparency"}), - json!({"format": ["same", "png", "jpg", "psd", "tiff"], "profile": ["auto", "generic", "none"], "edge": ["transparency", "edgeExtension", "black", "white"]}), - ), - "file.scripts.imageProcessor" => dialog( - app, - json!({"input": dir, "includeSubfolders": false, "__labels": subfolders_label(), "output": format!("{dir}/processed"), "format": "jpg", "quality": 8, "width": 0, "height": 0, "convertToSrgb": true}), - json!({"format": ["jpg", "png", "psd", "tiff", "webp"]}), - ), - "file.automate.batch" => { - let Some(action) = crate::actions::selected_action(app) else { - return Some(Err("record an action in the Actions panel first".into())); - }; - let steps = crate::actions::action_steps(action); - let name = action.name.clone(); - dialog( - app, - json!({"action": name, "steps": steps, "input": dir, "includeSubfolders": false, "__labels": subfolders_label(), "output": format!("{dir}/batch"), "format": "same", "quality": null, "__batchQuality": 8, "naming": "", "startingSerial": 1}), - json!({"format": ["same", "png", "jpg", "psd", "tiff", "webp"]}), - ) - } - // Channel workflow dialogs (see channels_panel.rs for the channel references). - "select.saveSelection" | "select.loadSelection" | "image.applyImage" | "image.calculations" => { - let st = app.session.active()?; - let d = &st.doc; - let mode = d.pixel_format().mode; - let mut chans: Vec = vec![photocraft_engine::channel_cmds::composite_name(mode).to_string()]; - if mode.color_channels() > 1 { - chans.extend(photocraft_engine::channel_cmds::color_names(mode).iter().map(|n| n.to_string())); - } - chans.extend(d.channels.iter().map(|c| c.name.clone())); - let alphas: Vec = std::iter::once("new".to_string()).chain(d.channels.iter().map(|c| c.name.clone())).collect(); - let blends = [ - "multiply", - "screen", - "normal", - "overlay", - "softLight", - "hardLight", - "darken", - "lighten", - "colorDodge", - "colorBurn", - "linearBurn", - "linearDodge", - "difference", - "exclusion", - "add", - "subtract", - ]; - // The active layer's transparency, and its mask only when it has one. - let layer = st.active_layer.and_then(|l| d.layer(l)); - let mut load = chans.clone(); - if layer.is_some() { - load.push("transparency".into()); - } - if layer.is_some_and(|l| l.mask.is_some()) { - load.push("mask".into()); - } - load.push("selection".into()); - match id { - "select.saveSelection" => dialog( - app, - json!({"channel": "new", "name": "", "operation": "new"}), - json!({"channel": alphas, "operation": ["new", "replace", "add", "subtract", "intersect"]}), - ), - "select.loadSelection" => { - let first = d.channels.first().map_or_else(|| chans[0].clone(), |c| c.name.clone()); - dialog( - app, - json!({"channel": first, "invert": false, "operation": "new"}), - json!({"channel": load, "operation": ["new", "add", "subtract", "intersect"]}), - ) - } - "image.applyImage" => { - let mut masks = vec!["none".to_string()]; - masks.extend(load.iter().cloned()); - // Source layer: Merged, then the pixel layers top to bottom (the engine takes - // the topmost layer of a name), shown by their own names. - let mut layers = vec!["merged".to_string()]; - for (_, _, l) in d.walk().into_iter().rev() { - if l.surface().is_some() && !layers.contains(&l.name) { - layers.push(l.name.clone()); - } - } - let names: Map = layers.iter().skip(1).map(|n| (n.clone(), json!(n))).collect(); - // Scale and Offset only affect Add and Subtract. - dialog( - app, - json!({"sourceLayer": "merged", "sourceChannel": chans[0], "sourceInvert": false, "blending": "multiply", "opacity": 100.0, "scale": 1.0, "offset": 0, "preserveTransparency": false, "maskChannel": "none", "__labels": names}), - json!({"sourceLayer": layers, "sourceChannel": load, "blending": blends, "maskChannel": masks}), - ) - } - _ => dialog( - app, - json!({"source1Channel": chans[0], "source1Invert": false, "source2Channel": chans[0], "source2Invert": false, "blending": "multiply", "opacity": 100.0, "result": "newChannel"}), - json!({"source1Channel": load.clone(), "source2Channel": load, "blending": blends, "result": ["newChannel", "newDocument", "selection"]}), - ), - } - } - _ => None, - } -} - -/// File › Save a Copy: pick a name, encode with the export service, write; the document's path -/// and saved state are untouched. An action being recorded keeps it as a `file.saveACopy` step -/// with its path (#4373). -fn save_a_copy(app: &mut PhotocraftApp) -> Result { - let doc = app.session.active().ok_or("no document")?.doc.clone(); - let stem = doc.name.rsplit_once('.').map_or(doc.name.as_str(), |(a, _)| a); - // " copy.psd", or with Preferences › File Handling › Do not append "copy" to filename - // when saving a copy the document's own name (only the extension may change), as in - // Photoshop (#8080). - let suggested = format!("{stem}{}.psd", app.session.prefs().file_handling.copy_suffix()); - // The copy is of the document as it was when asked. - app.pick_save(&suggested, move |app, path| { - // An RGB Targa asks for its bits per pixel first, a DDS texture for its compression, and - // a JPEG for its JPEG Options; the copy is written from the prompt. - let parked = app.with_document(doc.id, |app| { - if crate::targa_options_ui::wants_prompt(app, &path) { - crate::targa_options_ui::park(app, path.clone(), true, "file.saveACopy")?; - return Ok(true); - } - if crate::dds_options_ui::wants_prompt(&path) { - crate::dds_options_ui::park(app, path.clone(), true, "file.saveACopy")?; - return Ok(true); - } - if crate::jpeg_options_ui::wants_prompt(app, &path) { - crate::jpeg_options_ui::park(app, path.clone(), true, "file.saveACopy")?; - return Ok(true); - } - Ok(false) - })?; - if parked { - return Ok(json!({"path": path, "warnings": []})); - } - let r = write_copy(app, &doc, &path, crate::FormatChoices::default())?; - app.session.journal.push(("file.saveACopy".into(), json!({"path": path}))); - Ok(r) - }) -} - -/// Writes `doc` to `path` as a copy (Save a Copy, and its replayed action step): the document's -/// path and saved state are untouched. `choices` are the Targa, DDS and JPEG answers, when there -/// are any. -pub(crate) fn write_copy(app: &mut PhotocraftApp, doc: &photocraft_doc::Document, path: &str, choices: crate::FormatChoices) -> Result { - let settings = choices.apply(app.save_settings()); - let export = app.services.export.as_ref().ok_or("no exporter configured")?; - let (bytes, warnings) = export(doc, path, &settings)?; - let write = app.services.write.as_mut().ok_or("no writer configured")?; - write(path, &bytes)?; - app.detach_others_from_file(path, doc.id); - let template = "Saved a copy as {path}"; - app.ui.status = crate::i18n::fmt(tl!(template), &[("path", path)]); - app.ui.status_error = false; - let what = crate::i18n::fmt(tl!(template), &[("path", &crate::file_open::display_name(path))]); - crate::notices::io_warnings(app, &what, &warnings); - Ok(json!({"path": path, "warnings": warnings})) -} - -/// Layer › Smart Objects › Export Contents: saves the contents file under its own name by default. -fn export_contents(app: &mut PhotocraftApp) -> Result { - let st = app.session.active().ok_or("no document")?; - let layer = st.active_layer.ok_or("no layer selected")?; - // The contents as they were when asked, like Save a Copy. - let (name, bytes) = photocraft_engine::smart_cmds::contents_of(&st.doc, layer).map_err(|e| e.to_string())?; - app.pick_save(&name.clone(), move |app, path| { - let write = app.services.write.as_mut().ok_or("no writer configured")?; - write(&path, &bytes)?; - let template = "Exported contents to {path}"; - app.ui.status = crate::i18n::fmt(tl!(template), &[("path", &path)]); - app.ui.status_error = false; - Ok(json!({"path": path, "fileName": name, "bytes": bytes.len()})) - }) -} - #[cfg(test)] #[path = "view_cmds/tests.rs"] mod tests; diff --git a/crates/ui-egui/src/view_cmds/arrange.rs b/crates/ui-egui/src/view_cmds/arrange.rs new file mode 100644 index 0000000000..209d743252 --- /dev/null +++ b/crates/ui-egui/src/view_cmds/arrange.rs @@ -0,0 +1,163 @@ +use super::*; + +/// View › Fit Layer(s) on Screen: zoom and centre on the selected layers' bounds. +pub(super) fn fit_layers(app: &mut PhotocraftApp) -> Result { + let i = app.session.active_index().ok_or("no document")?; + let st = app.session.active().ok_or("no document")?; + let mut b = photocraft_geom::Rect::EMPTY; + for id in st.selected_layers() { + if let Some(r) = st.doc.layer(id).and_then(|l| l.surface()).map(|s| s.content_bounds()) { + b = if b.is_empty() { r } else { b.union(&r) }; + } + } + if b.is_empty() { + b = st.doc.bounds(); + } + let size = [st.doc.size.width, st.doc.size.height]; + let area = app.last_canvas_rect.size(); + let area = if area.x > 50.0 { area } else { egui::vec2(1200.0, 800.0) }; + // The area is in egui points; the stored zoom is device pixels per document pixel. + let ppp = app.canvas_ppp(); + let points = ((area.x - 40.0) / b.width().max(1) as f32).min((area.y - 40.0) / b.height().max(1) as f32); + let v = &mut app.ui.views[i]; + v.zoom = crate::zoom_levels::clamp(points * ppp, size); + v.center = [(b.x0 + b.x1) as f32 / 2.0, (b.y0 + b.y1) as f32 / 2.0]; + v.fit_pending = false; + v.request_zoom_animation(app.session.prefs().general.animated_zoom); + v.zoom_anchor = None; + Ok(json!({"zoom": v.zoom, "bounds": [b.x0, b.y0, b.x1, b.y1]})) +} + +/// A finite `[x, y]` screen position within a sane range (window systems reject wild values). +fn screen_position(v: &Value) -> Option<[f32; 2]> { + const LIMIT: f64 = 1.0e6; + let a = v.as_array().filter(|a| a.len() == 2)?; + let n = |i: usize| a.get(i).and_then(Value::as_f64).filter(|x| x.is_finite() && x.abs() <= LIMIT).map(|x| x as f32); + Some([n(0)?, n(1)?]) +} + +pub(crate) fn float_window(app: &mut PhotocraftApp, doc: usize, offset: usize) -> u64 { + let wid = app.ui.alloc_id(); + let mut view = app.ui.views.get(doc).cloned().unwrap_or_default(); + view.zoom_animating = false; + view.zoom_anchor = None; + view.zoom_transition = None; + view.display_camera = None; + view.fit_pending = offset > 0 || view.fit_pending; + app.ui.windows.push(crate::state::DocWindow { id: wid, document: doc, view, open: true, position: None }); + wid +} + +pub(super) fn arrange(app: &mut PhotocraftApp, k: &str, p: &Value) -> Result { + if LAYOUTS.contains(&k) { + app.ui.view.arrange = k.to_string(); + // Each document fits its new cell. + app.ui.views.iter_mut().for_each(|v| v.fit_pending = true); + return Ok(json!({"arrange": k})); + } + match k { + "consolidateAllToTabs" => { + app.ui.view.arrange = "tabs".into(); + app.ui.windows.clear(); + Ok(json!({"arrange": "tabs"})) + } + "newWindowForDocument" => { + let doc = app.session.active_index().ok_or("no document")?; + Ok(json!({"window": float_window(app, doc, 0)})) + } + // Optional `document` (index; default the active one) and `position` (`[x, y]`, the + // window's screen position in points): dragging a tab off the tab strip uses both (#3733). + "floatInWindow" => { + let doc = match p.get("document") { + None | Some(Value::Null) => app.session.active_index().ok_or("no document")?, + Some(v) => { + let i = v.as_u64().ok_or("document must be a document index")?; + usize::try_from(i).ok().filter(|&i| i < app.session.documents().len()).ok_or(format!("no document {i}"))? + } + }; + let position = match p.get("position") { + None | Some(Value::Null) => None, + Some(v) => Some(screen_position(v).ok_or("position must be [x, y] in points")?), + }; + let wid = float_window(app, doc, 0); + if let Some(w) = app.ui.windows.iter_mut().find(|w| w.id == wid) { + w.position = position; + } + app.session.set_active(doc); + Ok(json!({"window": wid})) + } + "floatAllInWindows" | "cascade" => { + let n = app.session.documents().len(); + let ids: Vec = (0..n).map(|d| float_window(app, d, d)).collect(); + Ok(json!({"windows": ids})) + } + "matchZoom" | "matchLocation" | "matchRotation" | "matchAll" => { + let i = app.session.active_index().ok_or("no document")?; + let src = app.ui.views.get(i).cloned().ok_or("no document")?; + let (zoom, loc, rot) = + (matches!(k, "matchZoom" | "matchAll"), matches!(k, "matchLocation" | "matchAll"), matches!(k, "matchRotation" | "matchAll")); + let animated_zoom = app.session.prefs().general.animated_zoom; + // Each view stays within its own document's zoom range (a view not drawn yet has no + // `doc_size`, so the size comes from the document). + let sizes: Vec<[u32; 2]> = app.session.documents().iter().map(|d| [d.doc.size.width, d.doc.size.height]).collect(); + let apply = |v: &mut crate::state::View, doc: usize| { + if zoom { + v.zoom = crate::zoom_levels::clamp(src.zoom, sizes.get(doc).copied().unwrap_or(v.doc_size)); + v.request_zoom_animation(animated_zoom); + } + if loc { + v.center = src.center; + } + if rot { + v.rotation = src.rotation; + } + v.fit_pending = false; + }; + app.ui.views.iter_mut().enumerate().for_each(|(d, v)| apply(v, d)); + app.ui.windows.iter_mut().for_each(|w| apply(&mut w.view, w.document)); + Ok(json!({"zoom": src.zoom, "center": src.center, "rotation": src.rotation})) + } + _ => Err(format!("unknown arrangement {k}")), + } +} + +/// Screen rectangles for `n` documents in an arrangement (`None` = tabs). The active document +/// always gets a cell; n-up layouts show that many documents starting from the active one. +pub fn cells(layout: &str, rect: egui::Rect, n: usize) -> Option> { + use craft_ui::layout::{SplitAxis, SplitSize, split_rect}; + + if n < 2 || !LAYOUTS.contains(&layout) { + return None; + } + let grid = |cols: usize, rows: usize, count: usize| -> Vec { + let (w, h) = (rect.width() / cols as f32, rect.height() / rows as f32); + (0..count.min(cols * rows)) + .map(|i| egui::Rect::from_min_size(rect.min + egui::vec2((i % cols) as f32 * w, (i / cols) as f32 * h), egui::vec2(w, h))) + .collect() + }; + Some(match layout { + "tileAllVertically" => grid(n, 1, n), + "tileAllHorizontally" => grid(1, n, n), + "twoUpVertical" => { + let panes = split_rect(rect, SplitAxis::Horizontal, SplitSize::Ratio(0.5), 0.0, 0.0)?; + vec![panes.first, panes.second] + } + "twoUpHorizontal" => { + let panes = split_rect(rect, SplitAxis::Vertical, SplitSize::Ratio(0.5), 0.0, 0.0)?; + vec![panes.first, panes.second] + } + "threeUpVertical" => grid(3, 1, 3), + "threeUpHorizontal" => grid(1, 3, 3), + "threeUpStacked" => { + let columns = split_rect(rect, SplitAxis::Horizontal, SplitSize::Ratio(0.5), 0.0, 0.0)?; + let rows = split_rect(columns.second, SplitAxis::Vertical, SplitSize::Ratio(0.5), 0.0, 0.0)?; + vec![columns.first, rows.first, rows.second] + } + "fourUp" => grid(2, 2, 4), + "sixUp" => grid(3, 2, 6), + _ => { + let cols = (n as f32).sqrt().ceil() as usize; + grid(cols, n.div_ceil(cols), n) + } + }) +} diff --git a/crates/ui-egui/src/view_cmds/dialogs.rs b/crates/ui-egui/src/view_cmds/dialogs.rs new file mode 100644 index 0000000000..dd280efed0 --- /dev/null +++ b/crates/ui-egui/src/view_cmds/dialogs.rs @@ -0,0 +1,630 @@ +use super::dispatch::no_params; +use super::*; + +// ---------- dialogs and pickers in front of engine commands ---------- + +/// A generic form dialog that runs `command` with its fields on OK (rendered by [`form_body`]). +/// File › Open EXR Parts…: pick an EXR, then choose the parts and channel groups that become +/// the layers of one document (a Maya/Arnold render writes one part per AOV). The dialog is +/// a plain command form, so the control channel can drive the same selection headlessly. +fn open_exr_parts_dialog(app: &mut PhotocraftApp) -> Option> { + Some(app.pick_file_bytes_filtered(&["exr"], |app, name, _bytes| { + let info = app.run("file.exrParts", json!({"path": name})).map_err(|e| e.to_string())?; + let entries = info.as_array().cloned().unwrap_or_default(); + let mut fields = Map::new(); + fields.insert("path".into(), json!(name)); + fields.insert("view".into(), json!("both")); + fields.insert("precomp".into(), json!(false)); + let mut labels = Map::new(); + // The path field shows the picked file's name (data, verbatim); the rest translate. + if let Some(file) = name.rsplit(['/', '\\']).next() { + labels.insert("path".into(), json!(file)); + } + labels.insert("view".into(), json!(crate::i18n::t("View"))); + labels.insert("both".into(), json!(crate::i18n::t("Both"))); + labels.insert("left".into(), json!(crate::i18n::t("Left"))); + labels.insert("right".into(), json!(crate::i18n::t("Right"))); + labels.insert("precomp".into(), json!(crate::i18n::t("Add beauty precomp from the AOVs"))); + let mut any = false; + for e in &entries { + let kind = e["kind"].as_str().unwrap_or_default().to_string(); + let ename = e["name"].as_str().unwrap_or_default().to_string(); + let channels = e["channels"].as_u64().unwrap_or(0); + let key = format!("{kind}/{ename}"); + match kind.as_str() { + "part" => { + labels.insert(key.clone(), json!(format!("{ename} ({}×{}, {channels} ch)", e["width"], e["height"]))); + let on = !any && channels >= 3; + any |= on; + fields.insert(key, json!(on)); + } + "group" => { + labels.insert(key.clone(), json!(format!("{ename} ({channels} ch)"))); + fields.insert(key, json!(false)); + } + _ => {} + } + } + // Cryptomatte layers are information here (the picker comes separately); the array is + // not rendered but rides along for the control channel. + let crypto: Vec = entries.iter().filter(|e| e["kind"] == "cryptomatte").cloned().collect(); + if !crypto.is_empty() { + fields.insert("cryptomatte".into(), Value::Array(crypto)); + } + fields.insert("__labels".into(), Value::Object(labels)); + let choices = json!({"view": ["both", "left", "right"]}); + Ok(json!({"dialog": form(app, "file.openExrParts", "Open EXR Parts…", Value::Object(fields), choices)})) + })) +} + +pub(super) fn form(app: &mut PhotocraftApp, command: &str, label: &str, fields: Value, choices: Value) -> u64 { + let mut f = Map::new(); + f.insert("__command".into(), json!(command)); + f.insert("__label".into(), json!(label)); + f.insert("__form".into(), json!(true)); + f.insert("__choices".into(), choices); + if let Value::Object(m) = fields { + f.extend(m); + } + // Snapshot user-facing params at open so Alt+Reset can restore them. + let orig: Map = f.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); + f.insert("__formOrig".into(), Value::Object(orig)); + app.ui.open_dialog(DialogKind::Command, f) +} + +/// The Batch and Image Processor dialogs' "Include All Subfolders" checkbox reads as Photoshop's. +fn subfolders_label() -> Value { + json!({"includeSubfolders": tl!("Include All Subfolders")}) +} + +/// Alt+Cancel (Reset): restore the `__form` params captured at open. +pub fn reset_form(f: &mut Map) { + if !f.contains_key("__form") { + return; + } + let Some(Value::Object(orig)) = f.get("__formOrig").cloned() else { return }; + f.retain(|k, _| k.starts_with("__")); + f.extend(orig); +} + +pub(super) fn label_of(key: &str) -> String { + // A name that already reads as text ("iPhone 14 Pro Max", "Web 1920") is not camelCase. + if key.contains(' ') { + return tl!(key).to_owned(); + } + let mut out = String::new(); + for (i, c) in key.chars().enumerate() { + if i == 0 { + out.extend(c.to_uppercase()); + } else if c.is_uppercase() { + out.push(' '); + out.extend(c.to_lowercase()); + } else { + out.push(c); + } + } + let translated = tl!(&out); + if translated != out { + return translated.to_owned(); + } + // Fall back to the Title Case filter label's translation, but keep the sentence-case + // English when that is untranslated too (English and partial catalogs read as before). + let title = crate::filter_dialog::label(key); + if title == crate::filter_dialog::source_label(key) { out } else { title } +} + +/// Display order of a `__form` dialog's field keys. `__order` lists them the way Photoshop +/// shows them (e.g. File Info); keys it omits keep their catalogue order after it. +pub fn form_keys(f: &Map) -> Vec { + let mut keys: Vec = f + .get("__order") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .filter(|k| !k.starts_with("__") && f.contains_key(*k)) + .map(str::to_string) + .collect(); + let rest: Vec = f.keys().filter(|k| !k.starts_with("__") && !keys.contains(k)).cloned().collect(); + keys.extend(rest); + keys +} + +/// Body of a `__form` dialog: text fields, number fields, checkboxes and `__choices` dropdowns. +pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { + let choices = f.get("__choices").cloned().unwrap_or(Value::Null); + // Data-driven labels (a per-part checkbox shows the part's name, not a catalogue entry) + // come from `__labels` verbatim; everything else goes through the catalogue. + let labels = f.get("__labels").cloned().unwrap_or(Value::Null); + let label = |k: &str| labels.get(k).and_then(Value::as_str).map_or_else(|| label_of(k), str::to_string); + let keys = form_keys(f); + let mut browse: Option = None; + egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { + for k in keys { + let v = f.get(&k).cloned().unwrap_or(Value::Null); + if k == "naming" && f.get("__command").and_then(Value::as_str) == Some("file.automate.batch") { + let label = ui.label(tl!("File Naming")); + let mut naming = v.as_str().unwrap_or_default().to_owned(); + ui.add(egui::TextEdit::singleline(&mut naming).desired_width(260.0).hint_text("{name}")) + .labelled_by(label.id) + .on_hover_text("{name} · {serial} · {date} (UTC)"); + f.insert(k, json!(naming)); + ui.end_row(); + continue; + } + if k == "quality" && f.get("__command").and_then(Value::as_str) == Some("file.automate.batch") { + ui.label(label(&k)); + let mut custom = v.as_f64().is_some(); + let mut quality = v.as_f64().or_else(|| f.get("__batchQuality").and_then(Value::as_f64)).unwrap_or(8.0).clamp(0.0, 12.0) as f32; + ui.horizontal(|ui| { + crate::widgets::checkbox(ui, &mut custom, tl!("Custom")); + ui.add_enabled_ui(custom, |ui| crate::widgets::value_field(ui, &mut quality, 0.0..=12.0, "", 74.0).accessible_name(tl!("Quality"))); + }); + // None preserves the command's existing JPEG and lossless WebP defaults. + // The inactive custom value is shell state, never a command parameter. + f.insert("__batchQuality".into(), json!(quality)); + f.insert(k, if custom { json!(quality) } else { Value::Null }); + ui.end_row(); + continue; + } + let new = match &v { + Value::Array(_) | Value::Object(_) | Value::Null => continue, + Value::Bool(b) => { + ui.label(""); + let mut b = *b; + ui.checkbox(&mut b, label(&k)); + json!(b) + } + Value::String(s) => { + ui.label(label(&k)); + let mut s = s.clone(); + match choices.get(&k).and_then(Value::as_array) { + Some(opts) => { + let opts: Vec<(String, String)> = opts.iter().filter_map(Value::as_str).map(|o| (o.to_string(), label(o))).collect(); + let refs: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect(); + crate::widgets::dropdown(ui, &format!("form-{k}"), &label(&k), &mut s, &refs, 200.0); + } + None => { + ui.horizontal(|ui| { + ui.add(egui::TextEdit::singleline(&mut s).desired_width(260.0)).accessible_name(label(&k)); + // A folder field gets the system folder picker (#7942, #9357). + if crate::dialogs::is_folder_field(&k) && crate::widgets::secondary_button(ui, tl!("Browse…"), 0.0).clicked() { + browse = Some(k.clone()); + } + }); + } + } + json!(s) + } + Value::Number(n) => { + ui.label(label(&k)); + if let Some(mut i) = n.as_i64() { + ui.add(egui::DragValue::new(&mut i).custom_parser(crate::widgets::parse_num)).accessible_name(label(&k)); + json!(i) + } else { + let mut x = n.as_f64().unwrap_or(0.0); + ui.add(egui::DragValue::new(&mut x).speed(0.5).custom_parser(crate::widgets::parse_num)).accessible_name(label(&k)); + json!(x) + } + } + }; + f.insert(k, new); + ui.end_row(); + } + }); + if let Some(key) = browse { + f.insert(crate::dialogs::BROWSE_FIELD.into(), json!(key)); + } + camera_data(ui, f); +} + +/// File Info's read-only Camera Data section (`__camera`, from the document's EXIF/XMP). +fn camera_data(ui: &mut egui::Ui, f: &Map) { + let Some(camera) = f.get("__camera").and_then(Value::as_object).filter(|c| !c.is_empty()) else { return }; + ui.add_space(10.0); + ui.label(egui::RichText::new(tl!("Camera Data")).font(crate::theme::semibold(13.0))); + ui.add_space(4.0); + egui::Grid::new("form-camera-data").num_columns(2).spacing([12.0, 4.0]).show(ui, |ui| { + for (key, label) in photocraft_engine::file_cmds::CAMERA_FIELDS { + if let Some(v) = camera.get(key).and_then(Value::as_str) { + ui.label(crate::i18n::tr_ctx(crate::i18n::current(), "cameraData", label)); + ui.add(egui::Label::new(v).selectable(true)); + ui.end_row(); + } + } + }); +} + +/// Folder the batch dialogs start from: next to the active document, else the working directory. +fn default_dir(app: &PhotocraftApp) -> String { + app.session.active().and_then(|d| d.path.as_deref()).and_then(|p| p.rfind(['/', '\\']).map(|i| p[..i].to_string())).unwrap_or_else(|| ".".into()) +} + +pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { + if id == "file.closeAll" || id == "file.closeOthers" { + // Keep the remaining document's view (views are index-aligned with documents). + let keep = app.session.active_index().and_then(|i| app.ui.views.get(i).cloned()); + let r = app.run(id, params.clone()); + if r.is_ok() { + app.ui.views = if id == "file.closeAll" { Vec::new() } else { keep.into_iter().collect() }; + app.ui.windows.clear(); + app.sync_views(); + } + return Some(r); + } + if id == "type.pasteLoremIpsum" && no_params(params) { + // While typing, paste at the caret. + if let Some(te) = app.ui.text_edit.clone() { + let r = app.run(id, json!({"layer": te.layer, "at": te.caret, "coalesce": te.session})); + if let (Ok(v), Some(te)) = (&r, app.ui.text_edit.as_mut()) + && let Some(c) = v.get("caret").and_then(Value::as_u64) + { + te.caret = c as usize; + te.anchor = c as usize; + } + return Some(r); + } + return None; + } + if !no_params(params) { + return None; + } + let doc = app.session.active().map(|d| (d.doc.size.width, d.doc.size.height, d.doc.name.clone())); + let dir = default_dir(app); + let label = photocraft_engine::commands::find(id).map_or(id, |c| c.label); + let dialog = |app: &mut PhotocraftApp, fields: Value, choices: Value| Some(Ok(json!({"dialog": form(app, id, label, fields, choices)}))); + match id { + "file.openAs" => Some(app.open_dialog_file()), + "file.openExrParts" => open_exr_parts_dialog(app), + "file.saveACopy" => Some(save_a_copy(app)), + "file.placeEmbedded" | "file.placeLinked" => { + if app.ui.transform.is_some() { + return Some(Err("Commit or cancel the transform first".into())); + } + let doc = match app.active_doc_id() { + Ok(doc) => doc, + Err(e) => return Some(Err(e)), + }; + let linked = id == "file.placeLinked"; + let ctx = ctx.clone(); + Some(app.pick_file_bytes(move |app, name, bytes| { + if app.ui.transform.is_some() { + return Err("Commit or cancel the transform first".into()); + } + app.refocus(doc)?; + let linked = linked.then(|| name.clone()); + let result = app.place_bytes(&name, bytes, linked)?; + crate::transform_tool::begin_placed(app, &ctx)?; + Ok(result) + })) + } + "layer.smartObjects.replaceContents" => { + let st = app.session.active()?; + let (doc, layer) = (st.doc.id, st.active_layer?); + Some(app.pick_file_bytes(move |app, name, bytes| { + app.with_document(doc, |app| { + let r = photocraft_engine::smart_cmds::replace_contents_bytes(&mut app.session, layer, &name, bytes).map_err(|e| e.to_string()); + app.sync_views(); + r + }) + })) + } + "layer.smartObjects.exportContents" => Some(export_contents(app)), + "layer.smartObjects.relinkToFile" => { + let st = app.session.active()?; + let (doc, layer) = (st.doc.id, st.active_layer?); + // A link needs a file on disk: the desktop picker answers its full path, the web + // picker only a name and the bytes, which can't be linked to. + Some(app.pick_file_bytes(move |app, path, _| { + if !std::path::Path::new(&path).is_absolute() { + return Err(format!("{path}: Relink to File needs a file on disk")); + } + app.with_document(doc, |app| app.run("layer.smartObjects.relinkToFile", json!({"layer": layer.0, "path": path}))) + })) + } + "layer.smartObjects.convertToLinked" => { + let st = app.session.active()?; + let (doc, layer) = (st.doc.id, st.active_layer?); + let (name, _) = match photocraft_engine::smart_cmds::contents_of(&st.doc, layer) { + Ok(c) => c, + Err(e) => return Some(Err(e.to_string())), + }; + Some(app.pick_save(&name, move |app, path| { + app.with_document(doc, |app| app.run("layer.smartObjects.convertToLinked", json!({"layer": layer.0, "path": path}))) + })) + } + "layer.videoLayers.newVideoLayerFromFile" | "layer.videoLayers.replaceFootage" => { + let doc = match app.active_doc_id() { + Ok(doc) => doc, + Err(e) => return Some(Err(e)), + }; + let cmd = id.to_string(); + Some(app.pick_file_bytes(move |app, path, _bytes| { + app.with_document(doc, |app| { + let r = app.run(&cmd, json!({"path": path})); + if r.is_ok() && app.session.active().is_some_and(|d| d.doc.timeline.is_some()) { + app.ui.timeline.open = true; + } + app.sync_views(); + r + }) + })) + } + "layer.videoLayers.interpretFootage" => { + let st = app.session.active()?; + let id_layer = st.active_layer?; + let fps = st.doc.layer(id_layer).and_then(|l| l.video.as_ref()).map_or(30.0, |v| v.fps); + dialog(app, json!({"fps": fps}), json!({})) + } + "file.fileInfo" => { + let info = app.session.execute("file.fileInfo", json!({})).ok()?; + let kw = info["keywords"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::>().join("; ")).unwrap_or_default(); + dialog( + app, + json!({ + "title": info["title"], + "author": info["author"], + "authorTitle": info["authorTitle"], + "description": info["description"], + "keywords": kw, + "copyrightStatus": info["copyrightStatus"], + "copyright": info["copyright"], + "copyrightUrl": info["copyrightUrl"], + "__order": ["title", "author", "authorTitle", "description", "keywords", "copyrightStatus", "copyright", "copyrightUrl"], + "__labels": { + "title": tl!("Document Title"), + "copyright": tl!("Copyright Notice"), + "copyrightUrl": tl!("Copyright Info URL"), + }, + "__camera": info["camera"] + }), + json!({"copyrightStatus": ["unknown", "copyrighted", "publicDomain"]}), + ) + } + "file.automate.fitImage" => { + let (w, h, _) = doc?; + dialog(app, json!({"width": w, "height": h, "dontEnlarge": false, "__compact": true}), json!({})) + } + "file.automate.conditionalModeChange" => dialog( + app, + json!({"from": "any", "to": "rgb"}), + json!({"from": ["any", "rgb", "grayscale", "cmyk", "lab", "indexed", "bitmap", "duotone", "multichannel"], "to": ["rgb", "grayscale", "cmyk", "lab"]}), + ), + "view.newGuideLayout" => Some(Ok(json!({"dialog": crate::guide_layout_ui::open(app)}))), + "type.warpText" => Some(Ok(json!({"dialog": crate::dialogs::open_command_dialog(app, id, label)}))), + "file.export.layersToFiles" => { + let (_, _, name) = doc?; + dialog( + app, + json!({"dir": dir, "prefix": name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a), "format": "png", "visibleOnly": true}), + json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]}), + ) + } + "file.export.layerCompsToFiles" | "file.export.artboardsToFiles" => { + let (_, _, name) = doc?; + let prefix = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); + let fields = if id == "file.export.layerCompsToFiles" { + json!({"dir": dir, "prefix": prefix, "format": "png", "selectedOnly": false}) + } else { + json!({"dir": dir, "prefix": prefix, "format": "png"}) + }; + dialog(app, fields, json!({"format": ["png", "jpg", "psd", "tiff", "webp", "bmp"]})) + } + "file.export.artboardsToPdf" => { + let (_, _, name) = doc?; + let stem = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); + dialog(app, json!({"path": format!("{dir}/{stem}.pdf"), "quality": 10}), json!({})) + } + "layer.new.artboard" => { + let (w, h, _) = doc?; + let presets: Vec<&str> = std::iter::once("").chain(photocraft_engine::artboard_cmds::PRESETS.iter().map(|p| p.0)).collect(); + dialog( + app, + json!({"name": "", "preset": "", "width": w, "height": h, "background": "white"}), + json!({"preset": presets, "background": ["white", "black", "transparent"]}), + ) + } + "file.export.colorLookupTables" => { + let (_, _, name) = doc?; + let stem = name.rsplit_once('.').map_or(name.as_str(), |(a, _)| a).to_string(); + // A selected adjustment is a common use case, but existing no-selection exports + // continue to bake the entire visible stack. The scope remains explicit in the UI. + let selected_adjustments = app.session.active().is_some_and(|st| { + let chosen = st.selected_layers(); + !chosen.is_empty() + && chosen.iter().all(|id| { + st.doc.layers.iter().any(|root| root.id == *id) + && st.doc.layer(*id).is_some_and(|layer| layer.visible && matches!(layer.content, photocraft_doc::LayerContent::Adjustment(_))) + }) + }); + let scope = if selected_adjustments { "selected" } else { "all" }; + dialog(app, json!({"path": format!("{dir}/{stem}.cube"), "size": 33, "title": stem, "scope": scope}), json!({"scope": ["all", "selected"]})) + } + "file.scripts.loadFilesIntoStack" => Some(Ok(json!({"dialog": crate::stack_dialog::open(app)}))), + // Photography automation (photo_cmds / lens_cmds): a folder (or the open documents). + "file.automate.photomerge" => dialog( + app, + json!({"paths": dir, "useOpenDocuments": false, "layout": "auto", "blend": true, "vignetteRemoval": false, "geometricCorrection": false, "contentAwareFill": false}), + json!({"layout": ["auto", "perspective", "cylindrical", "spherical", "collage", "reposition"]}), + ), + "file.automate.mergeToHdrPro" => dialog( + app, + json!({"paths": dir, "useOpenDocuments": false, "align": true, "removeGhosts": false, "mode": "32", "method": "localAdaptation", "radius": 7.0, "strength": 0.52, "gamma": 1.0, "exposure": 0.0, "detail": 30.0, "saturation": 20.0}), + json!({"mode": ["32", "16", "8"], "method": ["localAdaptation", "exposureGamma", "highlightCompression", "equalizeHistogram"]}), + ), + "file.automate.lensCorrection" => dialog( + app, + json!({"input": dir, "output": format!("{dir}/corrected"), "format": "same", "profile": "auto", "correctDistortion": true, "correctVignette": true, "correctCA": true, "autoScale": true, "edge": "transparency"}), + json!({"format": ["same", "png", "jpg", "psd", "tiff"], "profile": ["auto", "generic", "none"], "edge": ["transparency", "edgeExtension", "black", "white"]}), + ), + "file.scripts.imageProcessor" => dialog( + app, + json!({"input": dir, "includeSubfolders": false, "__labels": subfolders_label(), "output": format!("{dir}/processed"), "format": "jpg", "quality": 8, "width": 0, "height": 0, "convertToSrgb": true}), + json!({"format": ["jpg", "png", "psd", "tiff", "webp"]}), + ), + "file.automate.batch" => { + let Some(action) = crate::actions::selected_action(app) else { + return Some(Err("record an action in the Actions panel first".into())); + }; + let steps = crate::actions::action_steps(action); + let name = action.name.clone(); + dialog( + app, + json!({"action": name, "steps": steps, "input": dir, "includeSubfolders": false, "__labels": subfolders_label(), "output": format!("{dir}/batch"), "format": "same", "quality": null, "__batchQuality": 8, "naming": "", "startingSerial": 1}), + json!({"format": ["same", "png", "jpg", "psd", "tiff", "webp"]}), + ) + } + // Channel workflow dialogs (see channels_panel.rs for the channel references). + "select.saveSelection" | "select.loadSelection" | "image.applyImage" | "image.calculations" => { + let st = app.session.active()?; + let d = &st.doc; + let mode = d.pixel_format().mode; + let mut chans: Vec = vec![photocraft_engine::channel_cmds::composite_name(mode).to_string()]; + if mode.color_channels() > 1 { + chans.extend(photocraft_engine::channel_cmds::color_names(mode).iter().map(|n| n.to_string())); + } + chans.extend(d.channels.iter().map(|c| c.name.clone())); + let alphas: Vec = std::iter::once("new".to_string()).chain(d.channels.iter().map(|c| c.name.clone())).collect(); + let blends = [ + "multiply", + "screen", + "normal", + "overlay", + "softLight", + "hardLight", + "darken", + "lighten", + "colorDodge", + "colorBurn", + "linearBurn", + "linearDodge", + "difference", + "exclusion", + "add", + "subtract", + ]; + // The active layer's transparency, and its mask only when it has one. + let layer = st.active_layer.and_then(|l| d.layer(l)); + let mut load = chans.clone(); + if layer.is_some() { + load.push("transparency".into()); + } + if layer.is_some_and(|l| l.mask.is_some()) { + load.push("mask".into()); + } + load.push("selection".into()); + match id { + "select.saveSelection" => dialog( + app, + json!({"channel": "new", "name": "", "operation": "new"}), + json!({"channel": alphas, "operation": ["new", "replace", "add", "subtract", "intersect"]}), + ), + "select.loadSelection" => { + let first = d.channels.first().map_or_else(|| chans[0].clone(), |c| c.name.clone()); + dialog( + app, + json!({"channel": first, "invert": false, "operation": "new"}), + json!({"channel": load, "operation": ["new", "add", "subtract", "intersect"]}), + ) + } + "image.applyImage" => { + let mut masks = vec!["none".to_string()]; + masks.extend(load.iter().cloned()); + // Source layer: Merged, then the pixel layers top to bottom (the engine takes + // the topmost layer of a name), shown by their own names. + let mut layers = vec!["merged".to_string()]; + for (_, _, l) in d.walk().into_iter().rev() { + if l.surface().is_some() && !layers.contains(&l.name) { + layers.push(l.name.clone()); + } + } + let names: Map = layers.iter().skip(1).map(|n| (n.clone(), json!(n))).collect(); + // Scale and Offset only affect Add and Subtract. + dialog( + app, + json!({"sourceLayer": "merged", "sourceChannel": chans[0], "sourceInvert": false, "blending": "multiply", "opacity": 100.0, "scale": 1.0, "offset": 0, "preserveTransparency": false, "maskChannel": "none", "__labels": names}), + json!({"sourceLayer": layers, "sourceChannel": load, "blending": blends, "maskChannel": masks}), + ) + } + _ => dialog( + app, + json!({"source1Channel": chans[0], "source1Invert": false, "source2Channel": chans[0], "source2Invert": false, "blending": "multiply", "opacity": 100.0, "result": "newChannel"}), + json!({"source1Channel": load.clone(), "source2Channel": load, "blending": blends, "result": ["newChannel", "newDocument", "selection"]}), + ), + } + } + _ => None, + } +} + +/// File › Save a Copy: pick a name, encode with the export service, write; the document's path +/// and saved state are untouched. An action being recorded keeps it as a `file.saveACopy` step +/// with its path (#4373). +fn save_a_copy(app: &mut PhotocraftApp) -> Result { + let doc = app.session.active().ok_or("no document")?.doc.clone(); + let stem = doc.name.rsplit_once('.').map_or(doc.name.as_str(), |(a, _)| a); + // " copy.psd", or with Preferences › File Handling › Do not append "copy" to filename + // when saving a copy the document's own name (only the extension may change), as in + // Photoshop (#8080). + let suggested = format!("{stem}{}.psd", app.session.prefs().file_handling.copy_suffix()); + // The copy is of the document as it was when asked. + app.pick_save(&suggested, move |app, path| { + // An RGB Targa asks for its bits per pixel first, a DDS texture for its compression, and + // a JPEG for its JPEG Options; the copy is written from the prompt. + let parked = app.with_document(doc.id, |app| { + if crate::targa_options_ui::wants_prompt(app, &path) { + crate::targa_options_ui::park(app, path.clone(), true, "file.saveACopy")?; + return Ok(true); + } + if crate::dds_options_ui::wants_prompt(&path) { + crate::dds_options_ui::park(app, path.clone(), true, "file.saveACopy")?; + return Ok(true); + } + if crate::jpeg_options_ui::wants_prompt(app, &path) { + crate::jpeg_options_ui::park(app, path.clone(), true, "file.saveACopy")?; + return Ok(true); + } + Ok(false) + })?; + if parked { + return Ok(json!({"path": path, "warnings": []})); + } + let r = write_copy(app, &doc, &path, crate::FormatChoices::default())?; + app.session.journal.push(("file.saveACopy".into(), json!({"path": path}))); + Ok(r) + }) +} + +/// Writes `doc` to `path` as a copy (Save a Copy, and its replayed action step): the document's +/// path and saved state are untouched. `choices` are the Targa, DDS and JPEG answers, when there +/// are any. +pub(crate) fn write_copy(app: &mut PhotocraftApp, doc: &photocraft_doc::Document, path: &str, choices: crate::FormatChoices) -> Result { + let settings = choices.apply(app.save_settings()); + let export = app.services.export.as_ref().ok_or("no exporter configured")?; + let (bytes, warnings) = export(doc, path, &settings)?; + let write = app.services.write.as_mut().ok_or("no writer configured")?; + write(path, &bytes)?; + app.detach_others_from_file(path, doc.id); + let template = "Saved a copy as {path}"; + app.ui.status = crate::i18n::fmt(tl!(template), &[("path", path)]); + app.ui.status_error = false; + let what = crate::i18n::fmt(tl!(template), &[("path", &crate::file_open::display_name(path))]); + crate::notices::io_warnings(app, &what, &warnings); + Ok(json!({"path": path, "warnings": warnings})) +} + +/// Layer › Smart Objects › Export Contents: saves the contents file under its own name by default. +fn export_contents(app: &mut PhotocraftApp) -> Result { + let st = app.session.active().ok_or("no document")?; + let layer = st.active_layer.ok_or("no layer selected")?; + // The contents as they were when asked, like Save a Copy. + let (name, bytes) = photocraft_engine::smart_cmds::contents_of(&st.doc, layer).map_err(|e| e.to_string())?; + app.pick_save(&name.clone(), move |app, path| { + let write = app.services.write.as_mut().ok_or("no writer configured")?; + write(&path, &bytes)?; + let template = "Exported contents to {path}"; + app.ui.status = crate::i18n::fmt(tl!(template), &[("path", &path)]); + app.ui.status_error = false; + Ok(json!({"path": path, "fileName": name, "bytes": bytes.len()})) + }) +} diff --git a/crates/ui-egui/src/view_cmds/dispatch.rs b/crates/ui-egui/src/view_cmds/dispatch.rs new file mode 100644 index 0000000000..6667f83283 --- /dev/null +++ b/crates/ui-egui/src/view_cmds/dispatch.rs @@ -0,0 +1,397 @@ +use super::arrange::{arrange, fit_layers}; +use super::dialogs::front; +use super::options::{panel_state, panel_tab, pixel_aspect_ratio, screen_mode_commands, show_slot, snap_slot, was_maximized_id}; +use super::*; + +/// Ids handled here (live menu items). +pub fn handles(id: &str) -> bool { + if let Some(k) = id.strip_prefix("view.show.") { + return show_slot(&mut Show::default(), k).is_some() || k == "all"; + } + if let Some(k) = id.strip_prefix("view.snapTo.") { + return snap_slot(&mut SnapTo::default(), k).is_some() || k == "all" || k == "none"; + } + if let Some(k) = id.strip_prefix("view.screenMode.") { + return SCREEN_MODES.contains(&k) || k == "cycle"; + } + if let Some(k) = id.strip_prefix("view.pixelAspectRatio.") { + return PIXEL_ASPECTS.contains(&k); + } + if let Some(k) = id.strip_prefix("type.fontPreviewSize.") { + return FONT_PREVIEW.contains(&k); + } + if let Some(k) = id.strip_prefix("type.languageOptions.") { + return LANGUAGE.contains(&k) || k == "middleEasternAndSouthAsianComposer"; + } + if let Some(k) = id.strip_prefix("window.arrange.") { + return LAYOUTS.contains(&k) + || matches!( + k, + "consolidateAllToTabs" + | "cascade" + | "floatInWindow" + | "floatAllInWindows" + | "newWindowForDocument" + | "matchZoom" + | "matchLocation" + | "matchRotation" + | "matchAll" + ); + } + matches!( + id, + "view.extras" + | "view.twoHundredPercent" + | "view.printSize" + | "view.fitLayersOnScreen" + | "view.fitArtboardOnScreen" + | "window.panel.layerComps" + | "view.flipHorizontal" + | "view.pixelAspectRatioCorrection" + | "view.patternPreview" + | "view.pixelArtPreview" + | "view.rotateView" + | "view.resetView" + | "window.panel.layers" + | "window.panel.history" + | "window.panel.navigator" + | "window.panel.properties" + | "window.panel.color" + | "window.panel.actions" + | "window.panel.channels" + | "window.panel.paths" + | "window.panel.character" + | "window.panel.paragraph" + | "window.panel.info" + | "window.panel.histogram" + | "window.panel.swatches" + | "window.panel.adjustments" + | "type.panels.character" + | "type.panels.paragraph" + ) +} + +pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option { + is_enabled_with_engine(app, id, || app.session.is_enabled(id)) +} + +/// Keep picker enablement testable with the engine's native filesystem check disabled. +pub(super) fn is_enabled_with_engine(app: &PhotocraftApp, id: &str, engine_enabled: impl FnOnce() -> bool) -> Option { + if !handles(id) && !wraps(id) { + return None; + } + let doc = app.session.active().is_some(); + Some(match id { + "view.screenMode.cycle" => app.ui.text_edit.is_none(), + "view.twoHundredPercent" | "view.printSize" | "view.fitLayersOnScreen" | "view.rotateView" | "view.resetView" => doc, + "view.fitArtboardOnScreen" => app.session.active().is_some_and(|d| d.doc.has_artboards()), + i if i.starts_with("window.arrange.") => match &i["window.arrange.".len()..] { + "consolidateAllToTabs" => true, + "floatInWindow" | "newWindowForDocument" => doc, + "matchZoom" | "matchLocation" | "matchRotation" | "matchAll" => app.session.documents().len() > 1 || !app.ui.windows.is_empty(), + _ => { + app.session.documents().len() > 1 + || (doc && matches!(&i["window.arrange.".len()..], "floatAllInWindows" | "cascade" | "tile" | "tileAllVertically" | "tileAllHorizontally")) + } + }, + // Embedded placement reads the picker's bytes on every platform. Linked placement keeps + // the engine's native filesystem guard because its source must remain reachable. + "file.placeEmbedded" => doc && app.services.file_dialog.is_some(), + // Batch's dialog is built from an Actions-panel action. Keep it disabled until one + // exists instead of opening a menu item that can only report "record an action". + "file.automate.batch" => crate::actions::selected_action(app).is_some() && engine_enabled(), + i if wraps(i) => engine_enabled(), + _ => true, + }) +} + +pub fn checked(app: &PhotocraftApp, id: &str) -> Option { + let o = &app.ui.view; + if let Some(k) = id.strip_prefix("view.show.") { + let mut s = o.show; + return show_slot(&mut s, k).map(|b| *b); + } + if let Some(k) = id.strip_prefix("view.snapTo.") { + let mut s = o.snap_to; + return snap_slot(&mut s, k).map(|b| *b); + } + if let Some(k) = id.strip_prefix("view.screenMode.") { + return SCREEN_MODES.contains(&k).then(|| o.screen_mode == k); + } + if let Some(k) = id.strip_prefix("view.pixelAspectRatio.") { + return PIXEL_ASPECTS.contains(&k).then(|| o.pixel_aspect == k); + } + if let Some(k) = id.strip_prefix("type.fontPreviewSize.") { + return FONT_PREVIEW.contains(&k).then(|| o.font_preview_size == k); + } + if let Some(k) = id.strip_prefix("type.languageOptions.") { + return if k == "middleEasternAndSouthAsianComposer" { + Some(o.middle_eastern_composer) + } else { + LANGUAGE.contains(&k).then(|| o.language_features == k) + }; + } + if let Some(k) = id.strip_prefix("window.arrange.") + && LAYOUTS.contains(&k) + { + return Some(o.arrange == k); + } + if let Some((panel, tab)) = panel_tab(app, id) { + let (p, t) = (&app.ui.panels, &app.ui.dock_tabs); + let (vis, cur) = match panel { + "navigator" => (p.navigator, t.navigator), + "history" => (p.history, t.history), + "layers" => (p.layers, t.layers), + "color" => (p.color, t.color), + "character" => (p.character, t.character), + _ => (p.properties, t.properties), + }; + return Some(vis && cur == tab); + } + if let Some(c) = type_checked(app, id) { + return Some(c); + } + Some(match id { + "view.extras" => o.extras, + "view.flipHorizontal" => o.flip_horizontal, + "view.pixelAspectRatioCorrection" => o.pixel_aspect_correction, + "view.patternPreview" => o.pattern_preview, + "view.pixelArtPreview" => o.pixel_art_preview, + _ => return None, + }) +} + +/// Checkmarks of the Type menu's anti-aliasing, orientation and OpenType items, for the layer the +/// options bar and Properties show: the one being edited, else the active or a selected type layer. +/// Anti-aliasing and orientation stay check items (`Some(false)`) without a type layer: a native +/// menu can't change an item's kind in place. +fn type_checked(app: &PhotocraftApp, id: &str) -> Option { + let t = crate::type_tool::target_text(app); + if let Some(k) = id.strip_prefix("type.antiAlias.") { + return Some(t.is_some_and(|t| photocraft_engine::type_extra_cmds::aa_name(t.antialias) == k)); + } + if let Some(k) = id.strip_prefix("type.orientation.") { + return Some(t.is_some_and(|t| (t.orientation == photocraft_doc::text::Orientation::Vertical) == (k == "vertical"))); + } + let t = t?; + let tag = match id.strip_prefix("type.openType.")? { + "standardLigatures" => "liga", + "contextualAlternates" => "calt", + "discretionaryLigatures" => "dlig", + "swash" => "swsh", + "oldstyle" => "onum", + "stylisticAlternates" => "salt", + "titlingAlternates" => "titl", + "ornaments" => "ornm", + "ordinals" => "ordn", + "fractions" => "frac", + _ => return None, + }; + Some(t.char_runs().first().is_some_and(|r| photocraft_engine::type_extra_cmds::feature_on(&r.style, tag))) +} + +/// Engine commands that get a dialog or file picker here when invoked without parameters. +fn wraps(id: &str) -> bool { + matches!( + id, + "file.openAs" + | "file.openExrParts" + | "file.saveACopy" + | "file.placeEmbedded" + | "file.placeLinked" + | "layer.smartObjects.replaceContents" + | "layer.smartObjects.exportContents" + | "layer.smartObjects.relinkToFile" + | "layer.smartObjects.convertToLinked" + | "file.closeAll" + | "file.closeOthers" + | "file.fileInfo" + | "file.automate.fitImage" + | "file.automate.conditionalModeChange" + | "file.automate.batch" + | "file.scripts.imageProcessor" + | "file.scripts.loadFilesIntoStack" + | "file.automate.photomerge" + | "file.automate.mergeToHdrPro" + | "file.automate.lensCorrection" + | "file.export.layersToFiles" + | "file.export.layerCompsToFiles" + | "file.export.artboardsToFiles" + | "file.export.artboardsToPdf" + | "layer.new.artboard" + | "file.export.colorLookupTables" + | "view.newGuideLayout" + | "type.warpText" + | "type.pasteLoremIpsum" + | "image.applyImage" + | "image.calculations" + | "select.saveSelection" + | "select.loadSelection" + | "layer.videoLayers.newVideoLayerFromFile" + | "layer.videoLayers.replaceFootage" + | "layer.videoLayers.interpretFootage" + ) +} + +pub(super) fn no_params(p: &Value) -> bool { + p.as_object().is_none_or(|o| o.is_empty()) +} + +/// Run a View/Window/Type shell command, or front an engine command with its dialog. `None` when +/// `id` isn't ours. +pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { + if wraps(id) { + return front(app, ctx, id, params); + } + if !handles(id) { + return None; + } + Some(run(app, ctx, id, params)) +} + +fn flag_param(p: &Value, cur: bool) -> bool { + p.get("on").and_then(Value::as_bool).unwrap_or(!cur) +} + +fn run(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, p: &Value) -> Result { + if let Some((panel, tab)) = panel_tab(app, id) { + let group = crate::dock::Group::from_key(panel); + let collapsed = group.is_some_and(|g| app.ui.dock.is_collapsed(g)); + let (vis, cur) = panel_state(app, panel); + let requested = match p.get("show").or_else(|| p.get("on")) { + None => None, + Some(value) => Some(value.as_bool().ok_or("show must be a boolean")?), + }; + if let Some(show) = requested { + *vis = show; + if show { + *cur = tab; + } + } else { + // Like Photoshop: choosing a visible panel's menu item again hides it. A collapsed + // group is expanded instead, so the menu item always brings the panel back (#129). + if *vis && *cur == tab && !collapsed && !id.starts_with("type.panels.") { + *vis = false; + } else { + *vis = true; + *cur = tab; + } + } + let visible = *vis; + if let Some(g) = group.filter(|_| visible) { + crate::dock::reveal(app, g); + } + return Ok(json!({"panel": panel, "tab": tab, "visible": visible})); + } + if id == "view.rotateView" { + return crate::rotate_view::command(app, p); + } + if id == "view.resetView" { + return crate::rotate_view::reset(app); + } + let o = &mut app.ui.view; + if let Some(k) = id.strip_prefix("view.show.") { + if k == "all" { + o.show = Show { layer_edges: true, mesh: true, ..Show::default() }; + o.extras = true; + app.ui.extras.grid = true; + app.ui.extras.guides = true; + return Ok(json!(true)); + } + let slot = show_slot(&mut o.show, k).ok_or("unknown Show item")?; + *slot = flag_param(p, *slot); + let v = *slot; + if v { + // Showing an item turns Extras back on, as in Photoshop. + o.extras = true; + } + return Ok(json!(v)); + } + if let Some(k) = id.strip_prefix("view.snapTo.") { + if k == "all" || k == "none" { + let on = k == "all"; + o.snap_to = SnapTo { guides: on, grid: on, layers: on, slices: on, document_bounds: on }; + return Ok(json!(on)); + } + let slot = snap_slot(&mut o.snap_to, k).ok_or("unknown Snap To item")?; + *slot = flag_param(p, *slot); + return Ok(json!(*slot)); + } + if let Some(k) = id.strip_prefix("view.screenMode.") { + let next = if k == "cycle" { + let i = SCREEN_MODES.iter().position(|m| *m == o.screen_mode).unwrap_or(0); + SCREEN_MODES[(i + 1) % SCREEN_MODES.len()] + } else { + k + }; + o.screen_mode = next.to_string(); + // Tab's view of the chrome (#6760) lasts only while in Full Screen Mode. + app.ui.panels.full_screen_chrome = false; + // Both full-screen modes take the whole display; the menu bar stays in the first. + let (full_screen, maximized) = ctx.input(|i| (i.viewport().fullscreen.unwrap_or(false), i.viewport().maximized.unwrap_or(false))); + let was_maximized = ctx.data(|d| d.get_temp::(was_maximized_id())).unwrap_or(false); + let (commands, was_maximized) = screen_mode_commands(cfg!(target_os = "windows"), full_screen, maximized, was_maximized, next); + ctx.data_mut(|d| d.insert_temp(was_maximized_id(), was_maximized)); + for command in commands { + ctx.send_viewport_cmd(command); + } + return Ok(json!({"screenMode": next})); + } + if let Some(k) = id.strip_prefix("view.pixelAspectRatio.") { + o.pixel_aspect = k.to_string(); + return Ok(json!({"pixelAspectRatio": pixel_aspect_ratio(k)})); + } + if let Some(k) = id.strip_prefix("type.fontPreviewSize.") { + o.font_preview_size = k.to_string(); + return Ok(json!(k)); + } + if let Some(k) = id.strip_prefix("type.languageOptions.") { + if k == "middleEasternAndSouthAsianComposer" { + o.middle_eastern_composer = flag_param(p, o.middle_eastern_composer); + return Ok(json!(o.middle_eastern_composer)); + } + o.language_features = k.to_string(); + return Ok(json!(k)); + } + if let Some(k) = id.strip_prefix("window.arrange.") { + return arrange(app, k, p); + } + match id { + "view.extras" => { + o.extras = flag_param(p, o.extras); + Ok(json!(o.extras)) + } + "view.flipHorizontal" => { + o.flip_horizontal = flag_param(p, o.flip_horizontal); + Ok(json!(o.flip_horizontal)) + } + "view.pixelAspectRatioCorrection" => { + o.pixel_aspect_correction = flag_param(p, o.pixel_aspect_correction); + Ok(json!(o.pixel_aspect_correction)) + } + "view.patternPreview" => { + o.pattern_preview = flag_param(p, o.pattern_preview); + Ok(json!(o.pattern_preview)) + } + "view.pixelArtPreview" => { + o.pixel_art_preview = flag_param(p, o.pixel_art_preview); + Ok(json!(o.pixel_art_preview)) + } + "view.twoHundredPercent" | "view.printSize" => { + let i = app.session.active_index().ok_or("no document")?; + // Print Size shows the document at its print size for the screen resolution + // (Preferences ▸ Units & Rulers: Screen Resolution, 72 ppi by default). + let dpi = app.session.active().map_or(72.0, |d| d.doc.resolution_dpi.max(1.0)); + let size = app.session.active().map_or([0, 0], |d| [d.doc.size.width, d.doc.size.height]); + let screen = app.session.prefs().units_and_rulers.screen_resolution.max(1.0) as f32; + let z = if id == "view.twoHundredPercent" { 2.0 } else { screen / dpi }; + app.ui.views[i].zoom = crate::zoom_levels::clamp(z, size); + app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); + app.ui.views[i].zoom_anchor = None; + Ok(json!({"zoom": app.ui.views[i].zoom})) + } + "view.fitLayersOnScreen" => fit_layers(app), + "view.fitArtboardOnScreen" => crate::artboard_ui::fit_artboard(app), + _ => Err(format!("unhandled {id}")), + } +} diff --git a/crates/ui-egui/src/view_cmds/options.rs b/crates/ui-egui/src/view_cmds/options.rs new file mode 100644 index 0000000000..07aefac75b --- /dev/null +++ b/crates/ui-egui/src/view_cmds/options.rs @@ -0,0 +1,233 @@ +use super::*; + +/// Whether the window was maximized when a screen mode took it full screen (egui temp data). +pub(super) fn was_maximized_id() -> egui::Id { + egui::Id::unique("pc-full-screen-was-maximized") +} + +/// The window commands for switching to screen mode `next`, and whether the window should be +/// maximized again when it leaves full screen. With `keep_apart` (Windows), full screen and +/// maximized never overlap: a maximized window is un-maximized before it goes full screen and +/// maximized again after it leaves. Why: winit on Windows keeps the maximized style on a window +/// that goes full screen from maximized, and the shell then draws the taskbar black instead of +/// hiding it; on the way out the window stays maximized at the monitor's full size, over the +/// taskbar (#3550, #4018, #4230). [OBSERVED 2026-10-12, Windows 11, eframe 0.36.2, winit 0.30.13, +/// a minimal eframe window; un-maximizing first gave a clean full screen and a work-area maximize.] +/// +/// WORKAROUND(winit#4756): remove `keep_apart` once the winit in Cargo.lock (0.30.13 today) has +/// the fix; check first with https://gist.github.com/aweussom/3f80ffb82df7f0102341858afbbffd9b +/// (`--max`, no `--fix`: full screen must have no WS_MAXIMIZE and hide the taskbar). +pub(super) fn screen_mode_commands( + keep_apart: bool, + full_screen: bool, + maximized: bool, + was_maximized: bool, + next: &str, +) -> (Vec, bool) { + let want = next != "standard"; + let mut commands = Vec::new(); + let mut remember = was_maximized; + if keep_apart && want && !full_screen && maximized { + commands.push(egui::ViewportCommand::Maximized(false)); + remember = true; + } + commands.push(egui::ViewportCommand::Fullscreen(want)); + if !want { + if keep_apart && full_screen && remember { + commands.push(egui::ViewportCommand::Maximized(true)); + } + remember = false; + } + (commands, remember) +} + +/// Pixel aspect ratio (width / height of a pixel) of a preset id. +pub fn pixel_aspect_ratio(id: &str) -> f32 { + // View › Pixel Aspect Ratio › Custom: `custom::` (see `workspace_ui`). + if let Some(r) = id.strip_prefix("custom:").and_then(|r| r.split(':').next()?.parse::().ok()) { + return r; + } + match id { + "d1DvNtsc" => 0.91, + "d1DvPal" => 1.09, + "d1DvNtscWidescreen" => 1.21, + "hdv1080" => 1.33, + "d1DvPalWidescreen" => 1.46, + "dvcproHd1080" => 1.5, + "anamorphic2To1" => 2.0, + _ => 1.0, + } +} + +pub(super) fn show_slot<'a>(s: &'a mut Show, key: &str) -> Option<&'a mut bool> { + Some(match key { + "layerEdges" => &mut s.layer_edges, + "selectionEdges" => &mut s.selection_edges, + "targetPath" => &mut s.target_path, + "pixelGrid" => &mut s.pixel_grid, + "smartGuides" => &mut s.smart_guides, + "brushPreview" => &mut s.brush_preview, + "slices" => &mut s.slices, + "notes" => &mut s.notes, + "mesh" => &mut s.mesh, + "editPins" => &mut s.edit_pins, + "count" => &mut s.count, + "canvasGuides" => &mut s.canvas_guides, + "artboardGuides" => &mut s.artboard_guides, + _ => return None, + }) +} + +pub(super) fn snap_slot<'a>(s: &'a mut SnapTo, key: &str) -> Option<&'a mut bool> { + Some(match key { + "guides" => &mut s.guides, + "grid" => &mut s.grid, + "layers" => &mut s.layers, + "slices" => &mut s.slices, + "documentBounds" => &mut s.document_bounds, + _ => return None, + }) +} + +/// Every [`show_slot`] key. +const SHOW_KEYS: [&str; 13] = [ + "layerEdges", + "selectionEdges", + "targetPath", + "pixelGrid", + "smartGuides", + "brushPreview", + "slices", + "notes", + "mesh", + "editPins", + "count", + "canvasGuides", + "artboardGuides", +]; + +/// Every [`snap_slot`] key. +const SNAP_KEYS: [&str; 5] = ["guides", "grid", "layers", "slices", "documentBounds"]; + +/// The flags of `now` that differ from `def`, by key (`None` when none do). +fn changed_flags(now: T, def: T, keys: &[&str], slot: impl for<'a> Fn(&'a mut T, &str) -> Option<&'a mut bool>) -> Option { + let (mut now, mut def) = (now, def); + let diff: Map = keys + .iter() + .filter_map(|k| { + let v = *slot(&mut now, k)?; + (Some(v) != slot(&mut def, k).copied()).then(|| ((*k).to_string(), Value::Bool(v))) + }) + .collect(); + (!diff.is_empty()).then_some(Value::Object(diff)) +} + +/// View › Extras, Show and Snap To as remembered across restarts (`Preferences::view_extras`): +/// only what differs from the defaults, so a default changed in a later release still reaches +/// users who never touched that item. `Null` when nothing differs. +fn remembered(app: &PhotocraftApp) -> Value { + let (v, e, def) = (&app.ui.view, &app.ui.extras, crate::state::Extras::default()); + let mut m = Map::new(); + if v.extras != ViewOptions::default().extras { + m.insert("extras".into(), Value::Bool(v.extras)); + } + // View › Show › Grid and Guides live in `UiState::extras` beside the rulers and snapping. + if e.grid != def.grid { + m.insert("grid".into(), Value::Bool(e.grid)); + } + if e.guides != def.guides { + m.insert("guides".into(), Value::Bool(e.guides)); + } + if e.snap != def.snap { + m.insert("snap".into(), Value::Bool(e.snap)); + } + if let Some(show) = changed_flags(v.show, Show::default(), &SHOW_KEYS, show_slot) { + m.insert("show".into(), show); + } + if let Some(snap) = changed_flags(v.snap_to, SnapTo::default(), &SNAP_KEYS, snap_slot) { + m.insert("snapTo".into(), snap); + } + if m.is_empty() { Value::Null } else { Value::Object(m) } +} + +/// Remember View › Extras, Show and Snap To in the preferences once the user lets go of the +/// pointer (#3762). Cheap: a small JSON compare per frame. Run every frame, so items set by the +/// control channel or the Show Extras Options dialog are remembered too. +pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { + if ctx.input(|i| i.pointer.any_down()) { + return; + } + let now = remembered(app); + if app.session.prefs().view_extras != now { + app.session.prefs.edit(|p| p.view_extras = now); + } +} + +/// Restore the remembered View › Extras, Show and Snap To items at launch. A hand-edited file +/// can't break them: an unknown key or a value that isn't a boolean keeps its default. +pub fn restore(app: &mut PhotocraftApp) { + let saved = app.session.prefs().view_extras.clone(); + if !saved.is_null() && !saved.is_object() { + log::warn!("Preferences: the remembered View › Show items are not an object; using the defaults"); + return; + } + let flag = |k: &str| saved.get(k).and_then(Value::as_bool); + if let Some(on) = flag("extras") { + app.ui.view.extras = on; + } + if let Some(on) = flag("grid") { + app.ui.extras.grid = on; + } + if let Some(on) = flag("guides") { + app.ui.extras.guides = on; + } + if let Some(on) = flag("snap") { + app.ui.extras.snap = on; + } + for (k, v) in saved.get("show").and_then(Value::as_object).into_iter().flatten() { + if let (Some(slot), Some(on)) = (show_slot(&mut app.ui.view.show, k), v.as_bool()) { + *slot = on; + } + } + for (k, v) in saved.get("snapTo").and_then(Value::as_object).into_iter().flatten() { + if let (Some(slot), Some(on)) = (snap_slot(&mut app.ui.view.snap_to, k), v.as_bool()) { + *slot = on; + } + } +} + +/// Window › : (panel, dock tab) for panels that live as tabs of a dock card. +pub(super) fn panel_tab(app: &PhotocraftApp, id: &str) -> Option<(&'static str, usize)> { + let pro = app.ui.theme.is_pro(); + Some(match id { + "window.panel.info" => ("navigator", 2), + "window.panel.histogram" => ("navigator", 1), + "window.panel.navigator" => ("navigator", 0), + "window.panel.actions" => ("history", 1), + "window.panel.layerComps" => ("history", 2), + "window.panel.history" => ("history", 0), + "window.panel.channels" => ("layers", 1), + "window.panel.paths" => ("layers", 2), + "window.panel.layers" => ("layers", 0), + "window.panel.adjustments" => ("properties", 1), + "window.panel.properties" => ("properties", 0), + // Their own Character | Paragraph group, so Properties stays open (#150). + "window.panel.character" | "type.panels.character" => ("character", 0), + "window.panel.paragraph" | "type.panels.paragraph" => ("character", 1), + "window.panel.swatches" => ("color", usize::from(pro)), + "window.panel.color" => ("color", usize::from(!pro)), + _ => return None, + }) +} + +pub(super) fn panel_state<'a>(app: &'a mut PhotocraftApp, panel: &str) -> (&'a mut bool, &'a mut usize) { + let (p, t) = (&mut app.ui.panels, &mut app.ui.dock_tabs); + match panel { + "navigator" => (&mut p.navigator, &mut t.navigator), + "history" => (&mut p.history, &mut t.history), + "layers" => (&mut p.layers, &mut t.layers), + "color" => (&mut p.color, &mut t.color), + "character" => (&mut p.character, &mut t.character), + _ => (&mut p.properties, &mut t.properties), + } +} From df8e481a944894b8522f93f8f2e34cab1e546a67 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:34:35 +0000 Subject: [PATCH 222/259] refactor(ui-egui): split file_ui.rs into file_ui/ --- crates/ui-egui/src/file_ui.rs | 1215 +-------------------------- crates/ui-egui/src/file_ui/print.rs | 645 ++++++++++++++ crates/ui-egui/src/file_ui/web.rs | 568 +++++++++++++ 3 files changed, 1226 insertions(+), 1202 deletions(-) create mode 100644 crates/ui-egui/src/file_ui/print.rs create mode 100644 crates/ui-egui/src/file_ui/web.rs diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index f79de746d3..16f1e613bf 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -14,6 +14,19 @@ use crate::PhotocraftApp; use crate::state::DialogKind; use crate::theme::Tokens; +mod print; +mod web; + +use print::{print_body, print_confirm}; +#[cfg(test)] +use print::{drag_print_position, driver_paper_is_wide, print_params, print_preview_image, printer_options, take_turned_page, turn_driver}; +pub use print::open_print; +pub(crate) use print::print_status; +use web::{web_body, web_confirm}; +#[cfg(test)] +use web::{advance_preview, download_for_web, WEB_COMMAND, web_frame_document, WebCache, WebProxy}; +pub use web::open_web; + fn no_params(p: &Value) -> bool { p.as_object().is_none_or(|o| o.is_empty()) } @@ -200,202 +213,6 @@ fn b(f: &Map, k: &str, d: bool) -> bool { #[path = "file_ui/web_preview.rs"] mod web_preview; -const WEB_FORMATS: [(&str, &str); 5] = [("gif", "GIF"), ("png8", "PNG-8"), ("png24", "PNG-24"), ("jpeg", "JPEG"), ("wbmp", "WBMP")]; -const WEB_COMMAND: &str = "file.export.saveForWebLegacy"; -/// Save for Web's preview tabs: the `__view` field's values and their labels. -const WEB_VIEWS: [(&str, &str); 4] = [("original", "Original"), ("optimized", "Optimized"), ("2up", "2-Up"), ("4up", "4-Up")]; - -pub fn open_web(app: &mut PhotocraftApp) -> u64 { - let mut f = Map::new(); - f.insert("__web".into(), json!(true)); - f.insert("__command".into(), json!(WEB_COMMAND)); - f.insert("__label".into(), json!("Save for Web (Legacy)")); - // The preview tab chosen last time, 2-Up at first (#9174). - let view = app.ui.web_view.as_deref().filter(|v| WEB_VIEWS.iter().any(|(k, _)| k == v)).unwrap_or("2up"); - f.insert("__view".into(), json!(view)); - // Remember encoding choices, but each document starts at its own full size. This session's - // last export lives in `file_menu`; the last one before a restart comes from the - // preferences' remembered dialog settings (`web_cmds::remember_web_settings`). - let last = app - .session - .file_menu - .last_web - .clone() - .or_else(|| app.session.prefs().dialogs.get(WEB_COMMAND).cloned()) - .unwrap_or_else(|| json!({"format": "jpeg", "quality": 60})); - if let Value::Object(m) = last { - for (k, v) in m { - if !matches!(k.as_str(), "path" | "dir" | "width" | "height" | "percent" | "colorTable" | "colorTableEdits") { - f.insert(k, v); - } - } - } - for (k, v) in [ - ("format", json!("jpeg")), - ("quality", json!(60)), - ("palette", json!("selective")), - ("colors", json!(128)), - ("dither", json!("diffusion")), - ("ditherAmount", json!(88)), - ("transparency", json!(true)), - ("matte", json!("#ffffff")), - ("interlaced", json!(false)), - ("progressive", json!(false)), - ("optimized", json!(true)), - ("embedIcc", json!(false)), - ("convertToSrgb", json!(true)), - ("metadata", json!("copyright")), - ("percent", json!(100.0)), - ("resample", json!("bicubic")), - ("webSnap", json!(0)), - ] { - f.entry(k.to_string()).or_insert(v); - } - app.ui.open_dialog(DialogKind::Command, f) -} - -/// Settings variants shown in 4-Up (current, then two smaller alternatives). -fn variants(p: &Value) -> Vec { - let mut out = vec![p.clone()]; - let fmt = p["format"].as_str().unwrap_or("jpeg"); - for k in [2.0, 4.0] { - let mut v = p.clone(); - if let Some(m) = v.as_object_mut() { - m.remove("colorTable"); - m.remove("colorTableEdits"); - } - if fmt == "jpeg" { - v["quality"] = json!((p["quality"].as_f64().unwrap_or(60.0) / k).round().max(1.0)); - } else if fmt == "gif" || fmt == "png8" { - v["colors"] = json!((p["colors"].as_f64().unwrap_or(128.0) / k).round().max(2.0)); - } else { - v["format"] = json!(if k == 2.0 { "png8" } else { "gif" }); - v["colors"] = json!(256 / k as u32); - } - out.push(v); - } - out -} - -/// The flattened preview image: pixels, width, height, full-size / proxy pixel ratio. -type WebProxy = (Arc>, u32, u32, f64, egui::Vec2); -type WebCache = (String, Arc, Option<(usize, Option, &'static str)>); - -/// Renders one preview pane: the original (`None`) or an optimised variant. -fn web_pane(app: &PhotocraftApp, ui: &mut egui::Ui, size: egui::Vec2, p: Option<&Value>, f: &mut Map, pane: usize, frame: Option) { - let t = Tokens::get(ui.ctx()); - let Some(st) = app.session.active() else { return }; - let doc = st.doc.clone(); - let rev = st.revision; - // A bounded proxy; navigation never recomposites or re-encodes it. - let base = p.cloned().unwrap_or_else(|| json!({})); - let size_sig = format!("{}|{}|{}|{}|{}", base["percent"], base["width"], base["height"], base["resample"], base["convertToSrgb"]); - let wkey = egui::Id::unique(("web-proxy", doc.id.0, pane)); - let proxy_sig = format!("{rev}|{frame:?}|{size_sig}"); - let cached_proxy: Option<(String, WebProxy)> = ui.data(|d| d.get_temp(wkey)); - let proxy = cached_proxy.filter(|(sig, _)| sig == &proxy_sig).map(|(_, proxy)| proxy); - let (px, w, h, ratio, source_size) = match proxy { - Some(v) => v, - None => { - let (fw, fh) = match web_preview::dimensions(&doc, &base) { - Ok(size) => size, - Err(error) => { - ui.label(error); - return; - } - }; - let k = (2048.0 / fw.max(fh)).min(1.0); - let st = WebSettings::from_params(&base, "preview").unwrap_or_default(); - let Ok(doc) = web_frame_document(&doc, frame) else { return }; - let resample = web_preview::proxy_resample(&base, k); - let Ok((wd, _, _)) = - web_cmds::web_document(&doc, &json!({"width": (fw * k).round().max(1.0), "height": (fh * k).round().max(1.0), "resample": resample}), &st) - else { - return; - }; - let buf = photocraft_compose::flatten(&wd); - let v = ( - Arc::new(buf.px), - wd.size.width, - wd.size.height, - (fw * fh) / (f64::from(wd.size.width) * f64::from(wd.size.height)).max(1.0), - egui::vec2(fw as f32, fh as f32), - ); - ui.data_mut(|d| d.insert_temp(wkey, (proxy_sig, v.clone()))); - v - } - }; - let sig = format!("{}|{rev}|{frame:?}|{size_sig}|{}", doc.id.0, p.map(|v| v.to_string()).unwrap_or_else(|| "original".into())); - let key = egui::Id::unique(("web-pane", doc.id.0, pane)); - let cached: Option = ui.data(|d| d.get_temp(key)); - let (tex, info) = match cached.filter(|c| c.0 == sig) { - Some((_, tex, info)) => (tex, info), - None => { - let (rgba, info) = match p { - None => (px.iter().flat_map(|q| q.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)).collect::>(), None), - Some(p) => match web_preview::optimized(ui, key, &format!("{}|{rev}|{frame:?}|{size_sig}", doc.id.0), p, &px, w, h) { - Ok((preview, bytes, colors, ext)) => (preview, Some(((bytes as f64 * ratio) as usize, colors, ext))), - Err(error) => { - ui.label(error); - (vec![0; (w * h * 4) as usize], None) - } - }, - }; - let img = egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &rgba); - let tex = Arc::new(ui.ctx().load_texture("web-pane", img, egui::TextureOptions::LINEAR)); - ui.data_mut(|d| d.insert_temp(key, (sig, tex.clone(), info))); - (tex, info) - } - }; - ui.vertical(|ui| { - ui.set_width(size.x); - let (r, response) = ui.allocate_exact_size((size - egui::vec2(0.0, 42.0)).max(egui::vec2(1.0, 1.0)), egui::Sense::drag()); - let response = response.on_hover_cursor(egui::CursorIcon::Grab); - if let Some(rects) = f.get_mut("__previewRects").and_then(Value::as_array_mut) { - rects.push(json!([r.left(), r.top(), r.right(), r.bottom()])); - } - crate::widgets::checker(ui.painter(), r, 8.0); - web_preview::paint(ui, r, &response, &tex, source_size, f); - ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Inside); - let (l1, l2) = match (p, info) { - (None, _) => ("Original".to_string(), format!("{} · {} × {} px", doc.name, doc.size.width, doc.size.height)), - (Some(_), Some((bytes, colors, ext))) => { - // Photoshop's download estimate at 56.6 Kbps. - let secs = (bytes as f64 * 8.0 / 56_600.0).ceil(); - ( - format!("{} {}", ext.to_uppercase(), crate::sizing::human_bytes(bytes as f64)), - format!("{secs} sec @ 56.6 Kbps{}", colors.map(|c| format!(" · {c} colors")).unwrap_or_default()), - ) - } - (Some(_), None) => ("—".into(), String::new()), - }; - let l1 = if ratio > 1.001 { format!("{l1} · Proxy preview") } else { l1 }; - ui.add(egui::Label::new(egui::RichText::new(l1).color(t.text).size(11.5)).truncate()); - ui.add(egui::Label::new(egui::RichText::new(l2).color(t.text_dim).size(11.0)).truncate()); - }); -} - -/// Print's Printer menu: the default printer (value ""), then every printer `file.printers` -/// listed. A saved name the spooler no longer lists stays selectable rather than vanishing. -/// CUPS queue names stand in for spaces with `_`; the labels show the spaces. -fn printer_options(list: Option<&Value>, current: &str) -> Vec<(String, String)> { - let printers: Vec<(&str, bool)> = list - .and_then(Value::as_array) - .map(|a| a.iter().filter_map(|p| Some((p.get("name")?.as_str()?, p.get("default").and_then(Value::as_bool).unwrap_or(false)))).collect()) - .unwrap_or_default(); - let pretty = |n: &str| n.replace('_', " "); - let default = match printers.iter().find(|p| p.1) { - Some((n, _)) => format!("{} ({})", tl!("Default printer"), pretty(n)), - None => tl!("Default printer").to_string(), - }; - let mut opts = vec![(String::new(), default)]; - opts.extend(printers.iter().map(|(n, _)| (n.to_string(), pretty(n)))); - if !current.is_empty() && !printers.iter().any(|p| p.0 == current) { - opts.push((current.to_string(), pretty(current))); - } - opts -} - fn dropdown_str(ui: &mut egui::Ui, id: &str, name: &str, f: &mut Map, key: &str, opts: &[(&str, &str)], w: f32) { let mut v = s(f, key, opts.first().map_or("", |o| o.0)); let o: Vec<(String, &str)> = opts.iter().map(|(k, l)| (k.to_string(), *l)).collect(); @@ -420,1012 +237,6 @@ fn number(ui: &mut egui::Ui, f: &mut Map, key: &str, label: &str, }); } -/// Advance a preview clock by whole elapsed frames, retaining fractional time. -/// The caller resets `last` on Play so paused wall time never advances the preview. -fn advance_preview(frame: usize, duration: usize, fps: f32, last: f64, now: f64) -> (usize, f64) { - let duration = duration.max(1); - let frame = frame.min(duration - 1); - if !now.is_finite() { - return (frame, last); - } - if !last.is_finite() || now < last { - return (frame, now); - } - let fps = if fps.is_finite() && fps > 0.0 { f64::from(fps) } else { 30.0 }; - let elapsed_frames = (now - last) * fps; - if !elapsed_frames.is_finite() { - return (frame, now); - } - let steps = elapsed_frames.floor(); - if steps < 1.0 { - return (frame, last); - } - let delta = (steps % duration as f64) as usize % duration; - let remaining = duration - frame; - let next = if delta >= remaining { delta - remaining } else { frame + delta }; - (next, now - (elapsed_frames - steps) / fps) -} - -fn web_playback(ui: &mut egui::Ui, f: &mut Map, doc: &photocraft_doc::Document) -> Option { - let mut timeline = doc.timeline.clone()?; - timeline.clamp(); - if timeline.duration < 2 { - return None; - } - let now = ui.input(|i| i.time); - let mut frame = f.get("__web_frame").and_then(Value::as_u64).and_then(|v| usize::try_from(v).ok()).unwrap_or(timeline.current).min(timeline.duration - 1); - let mut last = n(f, "__web_time", now); - let mut playing = b(f, "__web_playing", false); - if playing { - (frame, last) = advance_preview(frame, timeline.duration, timeline.fps, last, now); - } - ui.horizontal(|ui| { - if crate::icons::button(ui, if playing { "pause" } else { "play" }, 22.0, playing, if playing { tl!("Pause") } else { tl!("Play") }).clicked() { - playing = !playing; - last = now; - } - ui.label(format!("{} / {}", frame + 1, timeline.duration)); - }); - f.insert("__web_frame".into(), json!(frame)); - f.insert("__web_time".into(), json!(last)); - f.insert("__web_playing".into(), json!(playing)); - if playing { - let remaining = (1.0 / f64::from(timeline.fps) - (now - last)).clamp(0.0, 1.0); - ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(remaining)); - } - Some(frame) -} - -/// Seek a preview copy, preserving any edits to the source's currently displayed frame. -fn web_frame_document(doc: &photocraft_doc::Document, frame: Option) -> Result { - let Some(frame) = frame else { return Ok(doc.clone()) }; - let mut preview = photocraft_engine::Session::new(); - preview.add_document(doc.clone(), None); - preview.execute("timeline.setFrame", json!({"frame": frame}))?; - Ok((*preview.active().ok_or(photocraft_engine::EngineError::NoDocument)?.doc).clone()) -} -fn web_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { - let t = Tokens::get(ui.ctx()); - let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return }; - ui.horizontal(|ui| { - let mut view = s(f, "__view", "2up"); - for (k, l) in WEB_VIEWS { - if ui.selectable_label(view == k, tl!(l)).clicked() { - view = k.into(); - // The next Save for Web opens on this tab, as Photoshop's does. - app.ui.web_view = Some(view.clone()); - } - } - f.insert("__view".into(), json!(view)); - }); - ui.add_space(4.0); - let frame = web_playback(ui, f, &doc); - web_preview::controls(ui, f); - if let Err(error) = web_preview::prepare_table(app, f) { - ui.colored_label(t.text_dim, error); - } - let p = params(f); - f.insert("__previewRects".into(), json!([])); - let area = egui::vec2((ui.available_width() - 270.0 - ui.spacing().item_spacing.x).max(260.0), (ui.available_height() - 48.0).max(180.0)); - ui.horizontal_top(|ui| { - // Previews grow with the dialog; settings retain their compact width. - ui.vertical(|ui| { - ui.set_width(area.x); - match s(f, "__view", "2up").as_str() { - "original" => web_pane(app, ui, area, None, f, 0, frame), - "optimized" => web_pane(app, ui, area, Some(&p), f, 1, frame), - "2up" => { - ui.horizontal(|ui| { - web_pane(app, ui, egui::vec2(area.x / 2.0 - 4.0, area.y), None, f, 0, frame); - web_pane(app, ui, egui::vec2(area.x / 2.0 - 4.0, area.y), Some(&p), f, 1, frame); - }); - } - _ => { - let v = variants(&p); - let cell = egui::vec2(area.x / 2.0 - 4.0, area.y / 2.0 - 4.0); - ui.horizontal(|ui| { - web_pane(app, ui, cell, None, f, 0, frame); - web_pane(app, ui, cell, Some(&v[0]), f, 1, frame); - }); - ui.horizontal(|ui| { - web_pane(app, ui, cell, Some(&v[1]), f, 2, frame); - web_pane(app, ui, cell, Some(&v[2]), f, 3, frame); - }); - } - } - }); - ui.add_space(10.0); - // Settings scroll independently on smaller windows. - ui.vertical(|ui| { - ui.set_width(250.0); - egui::ScrollArea::vertical().id_salt("web-settings").max_height(area.y).show(ui, |ui| { - ui.label(egui::RichText::new(tl!("Preset")).color(t.text_dim)); - let mut preset = s(f, "__preset", ""); - let mut opts: Vec<(String, &str)> = vec![("".into(), "[Unnamed]")]; - opts.extend(web_cmds::PRESETS.iter().map(|p| (p.to_string(), *p))); - if crate::widgets::dropdown(ui, "web-preset", tl!("Preset"), &mut preset, &opts, 230.0) && !preset.is_empty() { - if let Some(Value::Object(m)) = web_cmds::preset_settings(&preset).map(|st| st.to_params()) { - f.extend(m); - } - f.insert("__preset".into(), json!(preset)); - } - ui.add_space(4.0); - dropdown_str(ui, "web-format", tl!("Format"), f, "format", &WEB_FORMATS, 230.0); - ui.add_space(4.0); - let fmt = s(f, "format", "jpeg"); - match fmt.as_str() { - "gif" | "png8" => { - dropdown_str( - ui, - "web-palette", - tl!("Color Table"), - f, - "palette", - &[ - ("perceptual", tl!("Perceptual")), - ("selective", tl!("Selective")), - ("adaptive", tl!("Adaptive")), - ("restrictive", tl!("Restrictive (Web)")), - ("exact", tl!("Exact")), - ], - 150.0, - ); - number(ui, f, "colors", tl!("Colors"), 2.0..=256.0, "", 128.0); - dropdown_str( - ui, - "web-dither", - tl!("Dither"), - f, - "dither", - &[("none", tl!("No Dither")), ("diffusion", tl!("Diffusion")), ("pattern", tl!("Pattern")), ("noise", tl!("Noise"))], - 150.0, - ); - number(ui, f, "ditherAmount", tl!("Dither"), 0.0..=100.0, "%", 88.0); - check(ui, f, "transparency", tl!("Transparency"), true); - check(ui, f, "interlaced", tl!("Interlaced"), false); - number(ui, f, "webSnap", tl!("Web Snap"), 0.0..=100.0, "%", 0.0); - } - "jpeg" => { - number(ui, f, "quality", tl!("Quality"), 0.0..=100.0, "", 60.0); - check(ui, f, "progressive", tl!("Progressive"), false); - check(ui, f, "optimized", tl!("Optimized"), true); - check(ui, f, "embedIcc", tl!("Embed Color Profile"), false); - } - "wbmp" => { - dropdown_str( - ui, - "web-dither", - tl!("Dither"), - f, - "dither", - &[("none", tl!("No Dither")), ("diffusion", tl!("Diffusion")), ("pattern", tl!("Pattern"))], - 150.0, - ); - } - _ => { - check(ui, f, "transparency", tl!("Transparency"), true); - check(ui, f, "interlaced", tl!("Interlaced"), false); - } - } - if fmt != "png24" || !b(f, "transparency", true) { - ui.horizontal(|ui| { - let matte_label = ui.label(egui::RichText::new(tl!("Matte")).color(t.text_dim)); - let mut m = s(f, "matte", "#ffffff"); - if ui.add(egui::TextEdit::singleline(&mut m).desired_width(80.0)).labelled_by(matte_label.id).changed() { - f.insert("matte".into(), json!(m)); - } - }); - } - ui.add_space(6.0); - check(ui, f, "convertToSrgb", tl!("Convert to sRGB"), true); - ui.horizontal(|ui| { - ui.label(egui::RichText::new(tl!("Metadata")).color(t.text_dim)); - dropdown_str( - ui, - "web-meta", - tl!("Metadata"), - f, - "metadata", - &[ - ("none", tl!("None")), - ("copyright", tl!("Copyright")), - ("copyrightAndContact", tl!("Copyright and Contact Info")), - ("all", tl!("All")), - ], - 160.0, - ); - }); - if matches!(fmt.as_str(), "gif" | "png8") { - web_preview::table(ui, f); - } - ui.add_space(8.0); - ui.label(egui::RichText::new(tl!("Image Size")).font(crate::theme::semibold(12.0)).color(t.text)); - web_size(ui, f, &doc); - let nslices = photocraft_doc::slices::resolve(&doc).len(); - if !doc.slices.is_empty() { - ui.add_space(6.0); - ui.label(egui::RichText::new(crate::i18n::trn(crate::i18n::current(), nslices as u64, "{n} slice", "{n} slices")).color(t.text_dim)); - check(ui, f, "html", tl!("Save HTML and Images"), true); - dropdown_str(ui, "web-slices", tl!("Slices"), f, "slices", &[("all", tl!("All Slices")), ("user", tl!("All User Slices"))], 150.0); - } - }); - }); - }); -} - -/// A size row in a two-column grid: the label, then a field showing `shown`. Returns the typed -/// value when it changed, compared with the value the widget was given so a field that only -/// clamps does not count as an edit. -fn size_field(ui: &mut egui::Ui, label: &str, shown: f64, range: std::ops::RangeInclusive, unit: &str, decimals: u32) -> Option { - let t = Tokens::get(ui.ctx()); - let passed = (shown as f32).clamp(*range.start(), *range.end()); - let mut v = passed; - ui.label(egui::RichText::new(label).color(t.text_dim)); - crate::widgets::value_field_prec(ui, &mut v, range, unit, 90.0, decimals).accessible_name(tl!(&label)); - ui.end_row(); - (v != passed).then_some(f64::from(v)) -} - -/// Image Size, as in Photoshop's Save for Web: Width and Height linked in proportion (on at -/// each opening), Percent and the resampling method. A side edit sets exact pixels and drops -/// `percent`, which the engine would otherwise apply first; a Percent edit sets both sides. -fn web_size(ui: &mut egui::Ui, f: &mut Map, doc: &photocraft_doc::Document) { - use crate::export_dialog::{MAX_PX, resize_from_scale, resize_from_side}; - let (w0, h0) = (f64::from(doc.size.width).max(1.0), f64::from(doc.size.height).max(1.0)); - let (w, h) = web_preview::dimensions(doc, ¶ms(f)).unwrap_or((w0, h0)); - let lock = b(f, "__constrain", true); - let pct = n(f, "percent", w / w0 * 100.0); - let write = |f: &mut Map, width: f64, height: f64| { - f.insert("width".into(), json!(width)); - f.insert("height".into(), json!(height)); - }; - let max = MAX_PX as f32; - let (width, height, percent) = egui::Grid::new("web-size") - .num_columns(2) - .show(ui, |ui| { - ( - size_field(ui, tl!("Width"), w, 1.0..=max, "px", 0), - size_field(ui, tl!("Height"), h, 1.0..=max, "px", 0), - size_field(ui, tl!("Percent"), pct, 1.0..=1000.0, "%", 2), - ) - }) - .inner; - let side = match (width, height) { - (Some(v), _) => resize_from_side(w0, h0, v.round(), h, lock, true).ok(), - (_, Some(v)) => resize_from_side(w0, h0, w, v.round(), lock, false).ok(), - _ => None, - }; - if let Some(size) = side { - f.remove("percent"); - write(f, size.width, size.height); - } else if let Some(v) = percent - && let Ok(size) = resize_from_scale(w0, h0, v) - { - f.insert("percent".into(), json!(size.scale)); - write(f, size.width, size.height); - } - let mut linked = lock; - if crate::widgets::checkbox(ui, &mut linked, tl!("Constrain proportions")).changed() { - f.insert("__constrain".into(), json!(linked)); - // Linked again, the height follows the width in the document's proportions. - if linked && let Ok(size) = resize_from_side(w0, h0, w, h, true, true) { - f.remove("percent"); - write(f, size.width, size.height); - } - } - ui.horizontal(|ui| { - ui.label(egui::RichText::new(tl!("Resample")).color(Tokens::get(ui.ctx()).text_dim)); - // Photoshop's Save for Web list, in its order. - dropdown_str( - ui, - "web-resample", - tl!("Resample"), - f, - "resample", - &[ - ("nearest", tl!("Nearest Neighbor (hard edges)")), - ("bilinear", tl!("Bilinear")), - ("bicubic", tl!("Bicubic (smooth gradients)")), - ("bicubicSmoother", tl!("Bicubic Smoother (enlargement)")), - ("bicubicSharper", tl!("Bicubic Sharper (reduction)")), - ], - 170.0, - ); - }); -} - -fn web_confirm(app: &mut PhotocraftApp, f: &Map) -> Result { - // Check while the control/input policy is still installed, before an asynchronous picker - // can outlive the request. A browser download uses the interactive platform writer. - let authorize = |p: &Value| -> Result<(), String> { - if let Some(authorize) = app.session.authorize.or(if app.automation_input { app.services.automation_authorize } else { None }) { - authorize(WEB_COMMAND, p).map_err(|e| e.to_string())?; - } - if app.automation_input - && let Some(authorize) = app.services.automation_command.as_ref() - { - authorize(WEB_COMMAND, p)?; - } - Ok(()) - }; - let mut p = params(f); - authorize(&p)?; - // Confirmation may follow a field edit without an intervening frame (Enter or automation). - let mut fields = f.clone(); - web_preview::prepare_table(app, &mut fields)?; - let prepared = params(&fields); - if prepared != p { - // The policy must also approve the actual palette-bearing export parameters. - authorize(&prepared)?; - p = prepared; - } - if p.get("path").is_some() || p.get("dir").is_some() { - return save_for_web(app, p); - } - let doc = app.session.active().ok_or("no document")?.doc.clone(); - let has_slices = !doc.slices.is_empty(); - let html = b(f, "html", true); - let st = WebSettings::from_params(&p, "file.export.saveForWebLegacy").map_err(|e| e.to_string())?; - let base = photocraft_doc::slices::base_name(&doc); - let suggested = if has_slices && html { format!("{base}.html") } else { format!("{base}.{}", st.format.ext()) }; - app.pick_save(&suggested, move |app, path| { - app.refocus(doc.id)?; - if has_slices { - let dir = path.rfind(['/', '\\']).map(|i| path[..i].to_string()).unwrap_or_else(|| ".".into()); - p["dir"] = json!(dir); - p["html"] = json!(html); - } else { - p["path"] = json!(path); - } - save_for_web(app, p) - }) -} - -/// Runs Save for Web with `p`, which says where to write. -fn save_for_web(app: &mut PhotocraftApp, p: Value) -> Result { - #[cfg(target_arch = "wasm32")] - let result = download_for_web(app, p); - #[cfg(not(target_arch = "wasm32"))] - let result = app.run(WEB_COMMAND, p); - let r = result.inspect_err(|error| { - app.ui.status = error.clone(); - app.ui.status_error = true; - })?; - app.sync_views(); - app.ui.status = - crate::i18n::trn(crate::i18n::current(), r["files"].as_array().map_or(0, Vec::len) as u64, "Saved for Web: {n} file", "Saved for Web: {n} files"); - app.ui.status_error = false; - Ok(r) -} - -#[cfg(any(test, target_arch = "wasm32"))] -fn download_for_web(app: &mut PhotocraftApp, mut p: Value) -> Result { - // Browser downloads have no directory hierarchy. Keep the HTML's image and spacer URLs - // beside the downloaded page, matching the names handed to the platform service. - p["imagesFolder"] = json!(""); - let write = app.services.write.as_mut().ok_or("no download service")?; - web_cmds::save_for_web_with_writer(&mut app.session, &p, &mut |path, bytes| write(path, bytes).map_err(photocraft_engine::EngineError::Other)) - .map_err(|e| e.to_string()) -} - -// ---------- Print ---------- - -/// Opens a Print dialog seeded from the last print, filling missing fields with defaults. -/// Refreshes the printer list on each opening; when native driver enumeration succeeds, -/// an unavailable saved printer is replaced and its stale driver settings are discarded. -/// Returns the dialog ID without submitting a print job. -pub fn open_print(app: &mut PhotocraftApp) -> u64 { - let mut f = Map::new(); - f.insert("__print".into(), json!(true)); - f.insert("__label".into(), json!("PhotoCraft Print Settings")); - // Asked once per opening: the Printer menu lists what the spooler knows now. - let printers = app.session.execute("file.printers", json!({})).unwrap_or_default(); - f.insert("__systemPrinters".into(), printers["printers"].clone()); - // The settings of the last print, also from an earlier session (#7410). - if let Some(Value::Object(m)) = photocraft_engine::print_cmds::last_print(&app.session) { - f.extend(m); - } - for (k, v) in [ - ("printer", json!("")), - ("copies", json!(1)), - ("paper", json!("letter")), - ("orientation", json!("portrait")), - ("colorHandling", json!("printerManages")), - ("printerProfile", json!("coated-cmyk")), - ("intent", json!("relative")), - ("bpc", json!(true)), - ("center", json!(true)), - ("top", json!(0.0)), - ("left", json!(0.0)), - ("scale", json!(100.0)), - ("scaleToFit", json!(false)), - ("cornerCropMarks", json!(false)), - ("centerCropMarks", json!(false)), - ("registrationMarks", json!(false)), - ("description", json!(false)), - ("labels", json!(false)), - ("emulsionDown", json!(false)), - ("units", json!("cm")), - ("output", json!("")), - ] { - f.entry(k.to_string()).or_insert(v); - } - // Windows: the system's printers, and the paper from the chosen printer's driver settings. - if let Ok(list) = craft_print::rgb::printers() { - f.insert("__printers".into(), json!(list.iter().map(|p| p.name.clone()).collect::>())); - let known = |n: &str| list.iter().any(|p| p.name == n); - if !known(&s(&f, "printer", "")) { - let fallback = list.iter().find(|p| p.default).or(list.first()).map(|p| p.name.clone()).unwrap_or_default(); - f.insert("printer".into(), json!(fallback)); - f.remove("printerSettings"); - } - } - app.ui.open_dialog(DialogKind::Command, f) -} - -/// Whether the driver's paper, as `driver_page` took it, is wider than tall: the Orientation -/// buttons show landscape then. -fn driver_paper_is_wide(f: &Map) -> bool { - let side = |i: usize| f.get("paper").and_then(Value::as_array).and_then(|a| a.get(i)).and_then(Value::as_f64); - matches!((side(0), side(1)), (Some(w), Some(h)) if w > h) -} - -/// The Orientation buttons: the driver settings (or the printer's own) turned portrait or -/// landscape through `file.print.page`. An error stays on the dialog, with the settings left as -/// they were. -fn turn_driver(app: &mut PhotocraftApp, f: &mut Map, landscape: bool) { - let mut q = json!({"printer": s(f, "printer", ""), "orientation": if landscape { "landscape" } else { "portrait" }}); - if let (Some(h), Some(o)) = (f.get("printerSettings").cloned(), q.as_object_mut()) { - o.insert("printerSettings".into(), h); - } - match app.session.execute("file.print.page", q) { - Ok(r) => take_turned_page(f, &r), - Err(e) => { - f.insert("__pageError".into(), json!(e.to_string())); - } - } -} - -/// The turned settings and the paper they give, both from the one `file.print.page` answer, as -/// `driver_page` takes a page: asking the driver again could fail and leave new settings with the -/// old paper. An answer without both leaves the dialog as it was, with the reason shown. -fn take_turned_page(f: &mut Map, r: &Value) { - let paper = r.get("paper").and_then(Value::as_array).and_then(|a| Some((a.first()?.as_f64()?, a.get(1)?.as_f64()?))); - let (Some(settings), Some((w, h))) = (r.get("printerSettings").and_then(Value::as_str), paper) else { - f.insert("__pageError".into(), json!("the printer did not report the turned page")); - return; - }; - f.insert("printerSettings".into(), json!(settings)); - f.insert("paper".into(), json!([w, h])); - f.insert("orientation".into(), json!("portrait")); - f.remove("__pageError"); -} - -/// Takes the paper from the printer's driver settings (Windows), as Photoshop does. -fn driver_page(f: &mut Map) { - let printer = s(f, "printer", ""); - let settings = f.get("printerSettings").and_then(Value::as_str).and_then(|h| craft_print::rgb::DevMode::from_hex(h).ok()); - match craft_print::rgb::page(&printer, settings.as_ref()) { - Ok(pg) => { - f.insert("paper".into(), json!([pg.paper.0, pg.paper.1])); - f.insert("printable".into(), json!([pg.printable.0, pg.printable.1, pg.printable.2, pg.printable.3])); - f.insert("orientation".into(), json!("portrait")); - f.remove("__pageError"); - } - Err(e) => { - f.remove("printable"); - f.insert("__pageError".into(), json!(e.to_string())); - } - } -} - -/// Points per unit for the Position and Size fields. -fn unit_pt(units: &str) -> f64 { - match units { - "mm" => 72.0 / 25.4, - "in" => 72.0, - _ => 72.0 / 2.54, - } -} - -/// A number field in `units` for a value kept in points; true when edited. -fn length_field(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str) -> bool { - length_field_prec(ui, label, pt, units, 0) -} - -/// Edits a point-valued length in the selected units, with the requested decimal precision. -/// Retains the nonnegative 0..=10000 display-unit range used by existing size fields. -fn length_field_prec(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str, decimals: u32) -> bool { - length_field_range(ui, label, pt, units, decimals, 0.0..=10000.0) -} - -/// Edits a length stored in print points (72 per inch), returning true for a finite edit. -/// `range` is in the displayed `units`; a signed range permits negative Top/Left offsets. -fn length_field_range(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str, decimals: u32, range: std::ops::RangeInclusive) -> bool { - let t = Tokens::get(ui.ctx()); - let k = unit_pt(units); - let mut v = (*pt / k) as f32; - let mut changed = false; - ui.horizontal(|ui| { - ui.label(egui::RichText::new(label).color(t.text_dim)); - let before = v; - crate::widgets::value_field_prec(ui, &mut v, range, units, 70.0, decimals).accessible_name(tl!(&label)); - if (v - before).abs() > 1e-4 && v.is_finite() { - *pt = f64::from(v) * k; - changed = true; - } - }); - changed -} - -/// Unrotated paper dimensions in points, for either the current preset or a custom array. -fn print_paper_size(value: Option<&Value>) -> (f64, f64) { - let default = (612.0, 792.0); - match value { - Some(Value::Array(a)) => (a.first().and_then(Value::as_f64).unwrap_or(default.0), a.get(1).and_then(Value::as_f64).unwrap_or(default.1)), - Some(Value::String(name)) => photocraft_engine::print_cmds::PAPERS.iter().find(|p| p.0.eq_ignore_ascii_case(name)).map_or(default, |p| (p.1, p.2)), - _ => default, - } -} - -/// Edits the paper preset, orientation and custom dimensions, remembering custom sizes -/// across preset switches. Dimensions are displayed in the selected units but stored as -/// unrotated print points; the engine applies orientation and validates the final size. -fn print_paper_controls(ui: &mut egui::Ui, f: &mut Map) { - let previous = f.get("paper").cloned(); - let mut selected = if previous.as_ref().is_some_and(Value::is_array) { "custom".to_string() } else { s(f, "paper", "letter") }; - ui.horizontal(|ui| { - let mut papers: Vec<_> = photocraft_engine::print_cmds::PAPERS.iter().map(|p| (p.0.to_string(), p.0)).collect(); - papers.push(("custom".to_string(), tl!("Custom"))); - if crate::widgets::dropdown(ui, "print-paper", tl!("Paper"), &mut selected, &papers, 110.0) { - if selected == "custom" { - let (w, h) = print_paper_size(f.get("__customPaper").or(previous.as_ref())); - f.insert("paper".into(), json!([w, h])); - } else { - if let Some(paper @ Value::Array(_)) = previous { - f.insert("__customPaper".into(), paper); - } - f.insert("paper".into(), json!(selected)); - } - } - dropdown_str(ui, "print-orient", tl!("Orientation"), f, "orientation", &[("portrait", tl!("Portrait")), ("landscape", tl!("Landscape"))], 110.0); - }); - if f.get("paper").is_some_and(Value::is_array) { - let (mut w, mut h) = print_paper_size(f.get("paper")); - let units = s(f, "units", "cm"); - let changed = ui - .horizontal(|ui| { - let wc = length_field_prec(ui, tl!("Paper Width"), &mut w, &units, 2); - let hc = length_field_prec(ui, tl!("Paper Height"), &mut h, &units, 2); - wc || hc - }) - .inner; - if changed { - // Keep points in the command, and let the engine apply orientation and validation. - f.insert("paper".into(), json!([w, h])); - f.insert("__customPaper".into(), json!([w, h])); - } - } -} - -/// Save as PDF › Browse…: where to write the PDF, into Print dialog `id` once the file dialog -/// answers. Without it the only way to save a PDF was to type a full path (#5328). -fn browse_pdf(app: &mut PhotocraftApp, id: u64, suggested: &str) { - let r = app.pick_save(suggested, move |app, path| { - let d = app.ui.dialog_mut(id).ok_or("the dialog was closed")?; - d.fields.insert("output".into(), json!(path)); - Ok(Value::Null) - }); - if let Err(e) = r - && e != crate::file_dialog::CANCELLED - { - app.ui.status = e; - } -} - -/// Converts total displacement from a fixed drag-start layout into manual inch offsets. -/// Resolving Center before the drag avoids a jump; each update replaces the offsets rather -/// than accumulating movement. Emulsion Down reverses horizontal layout-space movement. -/// -/// `delta` and the painter use egui points, including on Retina displays; the scale is egui -/// points per print point (1/72 inch). Applying pixels_per_point would count HiDPI twice. -/// Invalid scales or nonfinite displacement/offsets return false without changing fields. -/// Accepted offsets are clamped to the engine's safety bound and Center is disabled. -fn drag_print_position(f: &mut Map, start: photocraft_engine::print_cmds::PrintLayout, delta: egui::Vec2, points_per_print_point: f32) -> bool { - if !points_per_print_point.is_finite() || points_per_print_point <= 0.0 || !delta.is_finite() { - return false; - } - let (x, y, _, h) = start.rect; - let direction = if start.emulsion_down { -1.0 } else { 1.0 }; - let left = (x + direction * f64::from(delta.x) / f64::from(points_per_print_point)) / 72.0; - let top = (start.paper.1 - y - h + f64::from(delta.y) / f64::from(points_per_print_point)) / 72.0; - if !left.is_finite() || !top.is_finite() { - return false; - } - let limit = photocraft_engine::print_cmds::MAX_POSITION_INCHES; - f.insert("center".into(), json!(false)); - f.insert("left".into(), json!(left.clamp(-limit, limit))); - f.insert("top".into(), json!(top.clamp(-limit, limit))); - true -} - -/// Maps the engine's bottom-left print-point rectangle into top-left egui coordinates. -/// `k` is egui points per print point; Emulsion Down mirrors placement across the page, -/// matching the PDF page transform. Returns the full image bounds for the caller to clip. -fn print_preview_image(l: photocraft_engine::print_cmds::PrintLayout, page: egui::Rect, k: f32) -> egui::Rect { - let (x, y, w, h) = l.rect; - let x = if l.emulsion_down { l.paper.0 - x - w } else { x }; - egui::Rect::from_min_size(egui::pos2(page.left() + x as f32 * k, page.bottom() - (y + h) as f32 * k), egui::vec2(w as f32 * k, h as f32 * k)) -} - -/// Draws the print controls and paper-clipped preview using the engine's shared layout. -/// Dragging the visible image updates dialog offsets live from a fixed gesture origin; -/// the position row stays present while centered so switching to manual cannot move the page. -fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, id: u64) { - let t = Tokens::get(ui.ctx()); - let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return }; - // PDF exports and previews retain editable paper on Windows too. Only a real native - // submission takes its media from the printer; entering that mode refreshes the driver - // geometry after any export-only paper edits. - let printers: Option> = if !b(f, "dryRun", false) && s(f, "output", "").is_empty() { - f.get("__printers").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()) - } else { - None - }; - if printers.is_some() { - if !b(f, "__driverPageInitialized", false) { - driver_page(f); - f.insert("__driverPageInitialized".into(), json!(true)); - } - } else { - // PDF output and previews have no driver page: Scale to Fit Media uses the paper. - f.remove("__driverPageInitialized"); - f.remove("printable"); - } - let p = params(f); - let mut browse = false; - ui.horizontal_top(|ui| { - // Page preview. - ui.vertical(|ui| { - let (area, _) = ui.allocate_exact_size(egui::vec2(330.0, 400.0), egui::Sense::hover()); - ui.painter().rect_filled(area, 0.0, t.canvas); - match photocraft_engine::print_cmds::layout(&doc, &p, "file.print") { - Ok(mut l) => { - let (pw, ph) = l.paper; - let k = ((area.width() - 20.0) / pw as f32).min((area.height() - 20.0) / ph as f32); - let page = egui::Rect::from_center_size(area.center(), egui::vec2(pw as f32 * k, ph as f32 * k)); - ui.painter().rect_filled(page, 0.0, egui::Color32::WHITE); - ui.painter().rect_stroke(page, 0.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Outside); - let mut img = print_preview_image(l, page, k); - let drag_id = ui.scope_id().with(("print-position", id)); - let visible = img.intersect(page).intersect(ui.clip_rect()); - let response = ui.interact(visible, drag_id, egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Print preview image"))); - // Keep a fixed layout and press origin for the whole gesture: rounding and - // the transition from Center must never accumulate or move the grab point. - if response.drag_started_by(egui::PointerButton::Primary) - && let Some(origin) = ui.input(|i| i.pointer.press_origin()) - { - ui.data_mut(|d| d.insert_temp(drag_id, (l, origin, k))); - } - if (response.dragged_by(egui::PointerButton::Primary) || response.drag_stopped_by(egui::PointerButton::Primary)) - && let Some((start, origin, scale)) = ui.data(|d| d.get_temp::<(photocraft_engine::print_cmds::PrintLayout, egui::Pos2, f32)>(drag_id)) - && let Some(pointer) = response.interact_pointer_pos() - && drag_print_position(f, start, pointer - origin, scale) - { - if let Ok(updated) = photocraft_engine::print_cmds::layout(&doc, ¶ms(f), "file.print") { - l = updated; - img = print_preview_image(l, page, k); - } - ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - } - if !ui.input(|i| i.pointer.primary_down()) { - ui.data_mut(|d| d.remove::<(photocraft_engine::print_cmds::PrintLayout, egui::Pos2, f32)>(drag_id)); - } - let (x, y, w, h) = l.rect; - let key = egui::Id::unique(("print-thumb", doc.id.0, app.session.active().map_or(0, |d| d.revision))); - let tex: Option> = ui.data(|d| d.get_temp(key)); - let tex = tex.unwrap_or_else(|| { - let th = photocraft_compose::thumbnail(&doc, 400); - let ci = egui::ColorImage::from_rgba_unmultiplied([th.width as usize, th.height as usize], &th.pixels); - let tx = Arc::new(ui.ctx().load_texture("print-thumb", ci, egui::TextureOptions::LINEAR)); - ui.data_mut(|d| d.insert_temp(key, tx.clone())); - tx - }); - let clip = ui.painter().with_clip_rect(page); - let uv = if l.emulsion_down { - egui::Rect::from_min_max(egui::pos2(1.0, 0.0), egui::pos2(0.0, 1.0)) - } else { - egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)) - }; - clip.image(tex.id(), img, uv, egui::Color32::WHITE); - let mark = egui::Stroke::new(1.0, egui::Color32::BLACK); - if l.marks.corner_crop { - // Bleed puts the marks on the trim line, inside the image edge. - let b = l.marks.bleed as f32 * k; - for (c, dx, dy) in - [(img.left_top(), -1.0, -1.0), (img.right_top(), 1.0, -1.0), (img.left_bottom(), -1.0, 1.0), (img.right_bottom(), 1.0, 1.0)] - { - clip.line_segment([c + egui::vec2(dx * 3.0, -dy * b), c + egui::vec2(dx * 12.0, -dy * b)], mark); - clip.line_segment([c + egui::vec2(-dx * b, dy * 3.0), c + egui::vec2(-dx * b, dy * 12.0)], mark); - } - } - if l.marks.registration { - for c in [ - img.center_top() - egui::vec2(0.0, 9.0), - img.center_bottom() + egui::vec2(0.0, 9.0), - img.left_center() - egui::vec2(9.0, 0.0), - img.right_center() + egui::vec2(9.0, 0.0), - ] { - clip.circle_stroke(c, 3.5, mark); - } - } - let fits = x >= 0.0 && y >= 0.0 && x + w <= pw && y + h <= ph; - let note = if fits { String::new() } else { " · larger than the paper".to_string() }; - ui.label( - egui::RichText::new(format!("Scale {:.1}% · {:.2} × {:.2} in{note}", l.scale * 100.0, w / 72.0, h / 72.0)) - .color(if fits { t.text_dim } else { t.warning }) - .size(11.0), - ); - } - Err(e) => { - ui.painter().text(area.center(), egui::Align2::CENTER_CENTER, e.to_string(), egui::FontId::proportional(12.0), t.text_dim); - } - } - }); - ui.add_space(12.0); - ui.vertical(|ui| { - ui.set_width(340.0); - let head = |ui: &mut egui::Ui, s: &str| { - ui.add_space(4.0); - ui.label(egui::RichText::new(s).font(crate::theme::semibold(12.0)).color(t.text)); - }; - head(ui, tl!("Printer Setup")); - if let Some(printers) = &printers { - // Windows: Photoshop's Printer menu and Print Settings… (the driver's own dialog). - ui.horizontal(|ui| { - ui.label(egui::RichText::new(tl!("Printer")).color(t.text_dim)); - let before = s(f, "printer", ""); - let opts: Vec<(&str, &str)> = printers.iter().map(|n| (n.as_str(), n.as_str())).collect(); - dropdown_str(ui, "print-printer", tl!("Printer"), f, "printer", &opts, 220.0); - if s(f, "printer", "") != before { - f.remove("printerSettings"); - driver_page(f); - } - }); - ui.horizontal(|ui| { - number(ui, f, "copies", tl!("Copies"), 1.0..=999.0, "", 1.0); - if ui.button(tl!("Print Settings…")).clicked() { - let printer = s(f, "printer", ""); - let current = f.get("printerSettings").and_then(Value::as_str).and_then(|h| craft_print::rgb::DevMode::from_hex(h).ok()); - match craft_print::rgb::settings_dialog(&printer, current.as_ref(), None) { - Ok(Some(dm)) => { - f.insert("printerSettings".into(), json!(dm.to_hex())); - driver_page(f); - } - Ok(None) => {} - Err(e) => { - f.insert("__pageError".into(), json!(e.to_string())); - } - } - } - }); - // Photoshop's Layout: Portrait / Landscape turn the driver settings, so the paper - // and the preview turn with them without opening Print Settings…. - ui.horizontal(|ui| { - ui.label(egui::RichText::new(tl!("Orientation")).color(t.text_dim)); - let wide = driver_paper_is_wide(f); - for (landscape, label) in [(false, "Portrait"), (true, "Landscape")] { - if crate::widgets::pill_tab(ui, label, wide == landscape).clicked() && wide != landscape { - turn_driver(app, f, landscape); - } - } - }); - let paper = p.get("paper").and_then(Value::as_array).map(|a| (a.first().and_then(Value::as_f64), a.get(1).and_then(Value::as_f64))); - let text = match paper { - Some((Some(w), Some(h))) => format!("{:.0} × {:.0} mm · {}", w / 72.0 * 25.4, h / 72.0 * 25.4, tl!("set in Print Settings…")), - _ => String::new(), - }; - ui.label(egui::RichText::new(text).color(t.text_dim).size(11.0)); - if let Some(e) = f.get("__pageError").and_then(Value::as_str) { - ui.label(egui::RichText::new(e).color(t.warning).size(11.0)); - } - } else { - ui.horizontal(|ui| { - ui.label(egui::RichText::new(tl!("Printer")).color(t.text_dim)); - let mut pr = s(f, "printer", ""); - let opts = printer_options(f.get("__systemPrinters"), &pr); - let o: Vec<(String, &str)> = opts.iter().map(|(k, l)| (k.clone(), l.as_str())).collect(); - if crate::widgets::dropdown(ui, "print-printer", tl!("Printer"), &mut pr, &o, 240.0) { - f.insert("printer".into(), json!(pr)); - } - }); - number(ui, f, "copies", tl!("Copies"), 1.0..=999.0, "", 1.0); - print_paper_controls(ui, f); - } - head(ui, tl!("Color Management")); - dropdown_str( - ui, - "print-color", - tl!("Color Management"), - f, - "colorHandling", - &[ - ("printerManages", tl!("Printer Manages Colors")), - ("photocraftManages", tl!("PhotoCraft Manages Colors")), - ("noColorManagement", tl!("No Color Management")), - ], - 240.0, - ); - if s(f, "colorHandling", "") == "photocraftManages" { - // Photoshop's Printer Profile menu: the built-ins, then every installed printer - // (output class) profile by its description. - let installed: Vec<_> = photocraft_engine::installed_profiles::installed() - .into_iter() - .filter(|p| p.is_destination() && p.class == photocraft_cms::ProfileClass::Output) - .collect(); - let mut profiles: Vec<(&str, &str)> = vec![ - ("coated-cmyk", tl!("Coated CMYK")), - ("srgb", "sRGB IEC61966-2.1"), - ("adobe-rgb-compat", tl!("Adobe RGB (1998) compatible")), - ("display-p3", tl!("Display P3")), - ("gray-gamma-2.2", tl!("Gray Gamma 2.2")), - ]; - profiles.extend(installed.iter().map(|p| (p.path.as_str(), p.description.as_str()))); - // A remembered profile that is no longer installed still shows, by its file name. - let cur = s(f, "printerProfile", "coated-cmyk"); - let stem = std::path::Path::new(&cur).file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - if !profiles.iter().any(|(v, _)| *v == cur) { - profiles.push((cur.as_str(), stem.as_str())); - } - dropdown_str(ui, "print-profile", tl!("Profile"), f, "printerProfile", &profiles, 240.0); - ui.horizontal(|ui| { - dropdown_str( - ui, - "print-intent", - tl!("Mode"), - f, - "intent", - &[ - ("perceptual", tl!("Perceptual")), - ("relative", tl!("Relative Colorimetric")), - ("saturation", tl!("Saturation")), - ("absolute", tl!("Absolute Colorimetric")), - ], - 170.0, - ); - check(ui, f, "bpc", tl!("Black Point Compensation"), true); - }); - if printers.is_some() { - ui.label( - egui::RichText::new(tl!("Remember to turn off the printer's own colour management in Print Settings…")).color(t.warning).size(11.0), - ); - } - } - head(ui, tl!("Position and Size")); - dropdown_str(ui, "print-units", tl!("Units"), f, "units", &[("cm", tl!("Centimeters")), ("mm", tl!("Millimeters")), ("in", tl!("Inches"))], 130.0); - let units = s(f, "units", "cm"); - check(ui, f, "center", tl!("Center"), true); - let centered = b(f, "center", true); - let centered_layout = centered.then(|| photocraft_engine::print_cmds::layout(&doc, ¶ms(f), "file.print").ok()).flatten(); - // Revealing this row during a drag resizes the centered modal and moves the paper. - // Keep it present, showing the resolved position while Center owns the offsets. - ui.add_enabled_ui(!centered, |ui| { - ui.horizontal(|ui| { - // Kept in inches (Photoshop's Position fields), shown in the chosen units. - for (key, label) in [("top", tl!("Top")), ("left", tl!("Left"))] { - let mut pt = - centered_layout.map_or_else(|| n(f, key, 0.0) * 72.0, |l| if key == "top" { l.paper.1 - l.rect.1 - l.rect.3 } else { l.rect.0 }); - let limit = (photocraft_engine::print_cmds::MAX_POSITION_INCHES * 72.0 / unit_pt(&units)) as f32; - if length_field_range(ui, label, &mut pt, &units, 2, -limit..=limit) { - let limit = photocraft_engine::print_cmds::MAX_POSITION_INCHES; - f.insert(key.into(), json!((pt / 72.0).clamp(-limit, limit))); - } - } - }); - }); - check(ui, f, "scaleToFit", tl!("Scale to Fit Media"), false); - // Scaled Print Size: Scale, Height and Width move together; Print Resolution follows. - if let Ok(l) = photocraft_engine::print_cmds::layout(&doc, ¶ms(f), "file.print") { - let (_, _, w, h) = l.rect; - let (mut w2, mut h2) = (w, h); - let fit = b(f, "scaleToFit", false); - if !fit { - // Two decimals: Height and Width set fractional scales. - ui.horizontal(|ui| { - ui.label(egui::RichText::new(tl!("Scale")).color(t.text_dim)); - let mut v = n(f, "scale", 100.0) as f32; - crate::widgets::value_field(ui, &mut v, 1.0..=1000.0, "%", 64.0).accessible_name(tl!("Scale")); - f.insert("scale".into(), json!((f64::from(v) * 100.0).round() / 100.0)); - }); - } - ui.horizontal(|ui| { - let hc = length_field(ui, tl!("Height"), &mut h2, &units); - let wc = length_field(ui, tl!("Width"), &mut w2, &units); - let k = if wc && w > 0.0 { - Some(w2 / w) - } else if hc && h > 0.0 { - Some(h2 / h) - } else { - None - }; - if let Some(k) = k.filter(|k| k.is_finite() && *k > 0.0) { - f.insert("scale".into(), json!(((l.scale * k * 100.0) * 100.0).round() / 100.0)); - f.insert("scaleToFit".into(), json!(false)); - } - }); - if w > 0.0 { - let ppi = f64::from(doc.size.width) / (w / 72.0); - ui.label(egui::RichText::new(format!("{} {ppi:.0} PPI", tl!("Print Resolution:"))).color(t.text_dim).size(11.0)); - } - } - head(ui, tl!("Printing Marks")); - ui.horizontal(|ui| { - check(ui, f, "cornerCropMarks", tl!("Corner Crop Marks"), false); - check(ui, f, "centerCropMarks", tl!("Center Crop Marks"), false); - }); - ui.horizontal(|ui| { - check(ui, f, "registrationMarks", tl!("Registration Marks"), false); - check(ui, f, "description", tl!("Description"), false); - check(ui, f, "labels", tl!("Labels"), false); - }); - head(ui, tl!("Functions")); - check(ui, f, "emulsionDown", tl!("Emulsion Down"), false); - if b(f, "emulsionDown", false) && printers.is_some() { - ui.label(egui::RichText::new(tl!("Don't also tick Mirror Image in Print Settings…: the two flips cancel out.")).color(t.text_dim).size(11.0)); - } - head(ui, tl!("Save as PDF")); - ui.horizontal(|ui| { - let mut out = s(f, "output", ""); - if ui.add(egui::TextEdit::singleline(&mut out).hint_text(tl!("(print to the printer)")).desired_width(240.0)).changed() { - f.insert("output".into(), json!(out)); - } - browse = ui.button(tl!("Browse…")).clicked(); - }); - }); - }); - if browse { - let current = s(f, "output", ""); - let suggested = if current.is_empty() { std::path::Path::new(&doc.name).with_extension("pdf").to_string_lossy().into_owned() } else { current }; - browse_pdf(app, id, &suggested); - } -} - -/// `file.print`'s params. The driver's printable area only goes with a print to the printer: -/// an output path or a preview set in the same frame as the confirm still drops it. -fn print_params(f: &Map) -> Value { - let mut p = params(f); - if (b(f, "dryRun", false) || !s(f, "output", "").is_empty()) - && let Some(o) = p.as_object_mut() - { - o.remove("printable"); - } - p -} - -/// Submits the dialog parameters to `file.print`, propagating command errors unchanged. -/// Updates the status for completed results only; pending jobs report completion later. -fn print_confirm(app: &mut PhotocraftApp, f: &Map) -> Result { - let r = app.run("file.print", print_params(f))?; - if r["pending"] != json!(true) { - print_status(app, &r); - } - Ok(r) -} - -pub(crate) fn print_status(app: &mut PhotocraftApp, r: &Value) { - app.ui.status = if let Some(printer) = r["spooler"]["printer"].as_str() { - crate::i18n::fmt(tl!("Sent to {printer}"), &[("printer", printer)]) - } else if r["sent"] == json!(true) { - let template = "Sent to the printer ({spooler})"; - crate::i18n::fmt(tl!(template), &[("spooler", r["spooler"].as_str().unwrap_or(""))]) - } else { - let template = "Printed to {path}"; - crate::i18n::fmt(tl!(template), &[("path", r["pdf"].as_str().unwrap_or(""))]) - }; - app.ui.status_error = false; -} - #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/file_ui/print.rs b/crates/ui-egui/src/file_ui/print.rs new file mode 100644 index 0000000000..8ed54e6644 --- /dev/null +++ b/crates/ui-egui/src/file_ui/print.rs @@ -0,0 +1,645 @@ +use super::*; + +/// Print's Printer menu: the default printer (value ""), then every printer `file.printers` +/// listed. A saved name the spooler no longer lists stays selectable rather than vanishing. +/// CUPS queue names stand in for spaces with `_`; the labels show the spaces. +pub(super) fn printer_options(list: Option<&Value>, current: &str) -> Vec<(String, String)> { + let printers: Vec<(&str, bool)> = list + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|p| Some((p.get("name")?.as_str()?, p.get("default").and_then(Value::as_bool).unwrap_or(false)))).collect()) + .unwrap_or_default(); + let pretty = |n: &str| n.replace('_', " "); + let default = match printers.iter().find(|p| p.1) { + Some((n, _)) => format!("{} ({})", tl!("Default printer"), pretty(n)), + None => tl!("Default printer").to_string(), + }; + let mut opts = vec![(String::new(), default)]; + opts.extend(printers.iter().map(|(n, _)| (n.to_string(), pretty(n)))); + if !current.is_empty() && !printers.iter().any(|p| p.0 == current) { + opts.push((current.to_string(), pretty(current))); + } + opts +} + +// ---------- Print ---------- + +/// Opens a Print dialog seeded from the last print, filling missing fields with defaults. +/// Refreshes the printer list on each opening; when native driver enumeration succeeds, +/// an unavailable saved printer is replaced and its stale driver settings are discarded. +/// Returns the dialog ID without submitting a print job. +pub fn open_print(app: &mut PhotocraftApp) -> u64 { + let mut f = Map::new(); + f.insert("__print".into(), json!(true)); + f.insert("__label".into(), json!("PhotoCraft Print Settings")); + // Asked once per opening: the Printer menu lists what the spooler knows now. + let printers = app.session.execute("file.printers", json!({})).unwrap_or_default(); + f.insert("__systemPrinters".into(), printers["printers"].clone()); + // The settings of the last print, also from an earlier session (#7410). + if let Some(Value::Object(m)) = photocraft_engine::print_cmds::last_print(&app.session) { + f.extend(m); + } + for (k, v) in [ + ("printer", json!("")), + ("copies", json!(1)), + ("paper", json!("letter")), + ("orientation", json!("portrait")), + ("colorHandling", json!("printerManages")), + ("printerProfile", json!("coated-cmyk")), + ("intent", json!("relative")), + ("bpc", json!(true)), + ("center", json!(true)), + ("top", json!(0.0)), + ("left", json!(0.0)), + ("scale", json!(100.0)), + ("scaleToFit", json!(false)), + ("cornerCropMarks", json!(false)), + ("centerCropMarks", json!(false)), + ("registrationMarks", json!(false)), + ("description", json!(false)), + ("labels", json!(false)), + ("emulsionDown", json!(false)), + ("units", json!("cm")), + ("output", json!("")), + ] { + f.entry(k.to_string()).or_insert(v); + } + // Windows: the system's printers, and the paper from the chosen printer's driver settings. + if let Ok(list) = craft_print::rgb::printers() { + f.insert("__printers".into(), json!(list.iter().map(|p| p.name.clone()).collect::>())); + let known = |n: &str| list.iter().any(|p| p.name == n); + if !known(&s(&f, "printer", "")) { + let fallback = list.iter().find(|p| p.default).or(list.first()).map(|p| p.name.clone()).unwrap_or_default(); + f.insert("printer".into(), json!(fallback)); + f.remove("printerSettings"); + } + } + app.ui.open_dialog(DialogKind::Command, f) +} + +/// Whether the driver's paper, as `driver_page` took it, is wider than tall: the Orientation +/// buttons show landscape then. +pub(super) fn driver_paper_is_wide(f: &Map) -> bool { + let side = |i: usize| f.get("paper").and_then(Value::as_array).and_then(|a| a.get(i)).and_then(Value::as_f64); + matches!((side(0), side(1)), (Some(w), Some(h)) if w > h) +} + +/// The Orientation buttons: the driver settings (or the printer's own) turned portrait or +/// landscape through `file.print.page`. An error stays on the dialog, with the settings left as +/// they were. +pub(super) fn turn_driver(app: &mut PhotocraftApp, f: &mut Map, landscape: bool) { + let mut q = json!({"printer": s(f, "printer", ""), "orientation": if landscape { "landscape" } else { "portrait" }}); + if let (Some(h), Some(o)) = (f.get("printerSettings").cloned(), q.as_object_mut()) { + o.insert("printerSettings".into(), h); + } + match app.session.execute("file.print.page", q) { + Ok(r) => take_turned_page(f, &r), + Err(e) => { + f.insert("__pageError".into(), json!(e.to_string())); + } + } +} + +/// The turned settings and the paper they give, both from the one `file.print.page` answer, as +/// `driver_page` takes a page: asking the driver again could fail and leave new settings with the +/// old paper. An answer without both leaves the dialog as it was, with the reason shown. +pub(super) fn take_turned_page(f: &mut Map, r: &Value) { + let paper = r.get("paper").and_then(Value::as_array).and_then(|a| Some((a.first()?.as_f64()?, a.get(1)?.as_f64()?))); + let (Some(settings), Some((w, h))) = (r.get("printerSettings").and_then(Value::as_str), paper) else { + f.insert("__pageError".into(), json!("the printer did not report the turned page")); + return; + }; + f.insert("printerSettings".into(), json!(settings)); + f.insert("paper".into(), json!([w, h])); + f.insert("orientation".into(), json!("portrait")); + f.remove("__pageError"); +} + +/// Takes the paper from the printer's driver settings (Windows), as Photoshop does. +fn driver_page(f: &mut Map) { + let printer = s(f, "printer", ""); + let settings = f.get("printerSettings").and_then(Value::as_str).and_then(|h| craft_print::rgb::DevMode::from_hex(h).ok()); + match craft_print::rgb::page(&printer, settings.as_ref()) { + Ok(pg) => { + f.insert("paper".into(), json!([pg.paper.0, pg.paper.1])); + f.insert("printable".into(), json!([pg.printable.0, pg.printable.1, pg.printable.2, pg.printable.3])); + f.insert("orientation".into(), json!("portrait")); + f.remove("__pageError"); + } + Err(e) => { + f.remove("printable"); + f.insert("__pageError".into(), json!(e.to_string())); + } + } +} + +/// Points per unit for the Position and Size fields. +fn unit_pt(units: &str) -> f64 { + match units { + "mm" => 72.0 / 25.4, + "in" => 72.0, + _ => 72.0 / 2.54, + } +} + +/// A number field in `units` for a value kept in points; true when edited. +fn length_field(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str) -> bool { + length_field_prec(ui, label, pt, units, 0) +} + +/// Edits a point-valued length in the selected units, with the requested decimal precision. +/// Retains the nonnegative 0..=10000 display-unit range used by existing size fields. +fn length_field_prec(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str, decimals: u32) -> bool { + length_field_range(ui, label, pt, units, decimals, 0.0..=10000.0) +} + +/// Edits a length stored in print points (72 per inch), returning true for a finite edit. +/// `range` is in the displayed `units`; a signed range permits negative Top/Left offsets. +fn length_field_range(ui: &mut egui::Ui, label: &str, pt: &mut f64, units: &str, decimals: u32, range: std::ops::RangeInclusive) -> bool { + let t = Tokens::get(ui.ctx()); + let k = unit_pt(units); + let mut v = (*pt / k) as f32; + let mut changed = false; + ui.horizontal(|ui| { + ui.label(egui::RichText::new(label).color(t.text_dim)); + let before = v; + crate::widgets::value_field_prec(ui, &mut v, range, units, 70.0, decimals).accessible_name(tl!(&label)); + if (v - before).abs() > 1e-4 && v.is_finite() { + *pt = f64::from(v) * k; + changed = true; + } + }); + changed +} + +/// Unrotated paper dimensions in points, for either the current preset or a custom array. +fn print_paper_size(value: Option<&Value>) -> (f64, f64) { + let default = (612.0, 792.0); + match value { + Some(Value::Array(a)) => (a.first().and_then(Value::as_f64).unwrap_or(default.0), a.get(1).and_then(Value::as_f64).unwrap_or(default.1)), + Some(Value::String(name)) => photocraft_engine::print_cmds::PAPERS.iter().find(|p| p.0.eq_ignore_ascii_case(name)).map_or(default, |p| (p.1, p.2)), + _ => default, + } +} + +/// Edits the paper preset, orientation and custom dimensions, remembering custom sizes +/// across preset switches. Dimensions are displayed in the selected units but stored as +/// unrotated print points; the engine applies orientation and validates the final size. +fn print_paper_controls(ui: &mut egui::Ui, f: &mut Map) { + let previous = f.get("paper").cloned(); + let mut selected = if previous.as_ref().is_some_and(Value::is_array) { "custom".to_string() } else { s(f, "paper", "letter") }; + ui.horizontal(|ui| { + let mut papers: Vec<_> = photocraft_engine::print_cmds::PAPERS.iter().map(|p| (p.0.to_string(), p.0)).collect(); + papers.push(("custom".to_string(), tl!("Custom"))); + if crate::widgets::dropdown(ui, "print-paper", tl!("Paper"), &mut selected, &papers, 110.0) { + if selected == "custom" { + let (w, h) = print_paper_size(f.get("__customPaper").or(previous.as_ref())); + f.insert("paper".into(), json!([w, h])); + } else { + if let Some(paper @ Value::Array(_)) = previous { + f.insert("__customPaper".into(), paper); + } + f.insert("paper".into(), json!(selected)); + } + } + dropdown_str(ui, "print-orient", tl!("Orientation"), f, "orientation", &[("portrait", tl!("Portrait")), ("landscape", tl!("Landscape"))], 110.0); + }); + if f.get("paper").is_some_and(Value::is_array) { + let (mut w, mut h) = print_paper_size(f.get("paper")); + let units = s(f, "units", "cm"); + let changed = ui + .horizontal(|ui| { + let wc = length_field_prec(ui, tl!("Paper Width"), &mut w, &units, 2); + let hc = length_field_prec(ui, tl!("Paper Height"), &mut h, &units, 2); + wc || hc + }) + .inner; + if changed { + // Keep points in the command, and let the engine apply orientation and validation. + f.insert("paper".into(), json!([w, h])); + f.insert("__customPaper".into(), json!([w, h])); + } + } +} + +/// Save as PDF › Browse…: where to write the PDF, into Print dialog `id` once the file dialog +/// answers. Without it the only way to save a PDF was to type a full path (#5328). +fn browse_pdf(app: &mut PhotocraftApp, id: u64, suggested: &str) { + let r = app.pick_save(suggested, move |app, path| { + let d = app.ui.dialog_mut(id).ok_or("the dialog was closed")?; + d.fields.insert("output".into(), json!(path)); + Ok(Value::Null) + }); + if let Err(e) = r + && e != crate::file_dialog::CANCELLED + { + app.ui.status = e; + } +} + +/// Converts total displacement from a fixed drag-start layout into manual inch offsets. +/// Resolving Center before the drag avoids a jump; each update replaces the offsets rather +/// than accumulating movement. Emulsion Down reverses horizontal layout-space movement. +/// +/// `delta` and the painter use egui points, including on Retina displays; the scale is egui +/// points per print point (1/72 inch). Applying pixels_per_point would count HiDPI twice. +/// Invalid scales or nonfinite displacement/offsets return false without changing fields. +/// Accepted offsets are clamped to the engine's safety bound and Center is disabled. +pub(super) fn drag_print_position( + f: &mut Map, + start: photocraft_engine::print_cmds::PrintLayout, + delta: egui::Vec2, + points_per_print_point: f32, +) -> bool { + if !points_per_print_point.is_finite() || points_per_print_point <= 0.0 || !delta.is_finite() { + return false; + } + let (x, y, _, h) = start.rect; + let direction = if start.emulsion_down { -1.0 } else { 1.0 }; + let left = (x + direction * f64::from(delta.x) / f64::from(points_per_print_point)) / 72.0; + let top = (start.paper.1 - y - h + f64::from(delta.y) / f64::from(points_per_print_point)) / 72.0; + if !left.is_finite() || !top.is_finite() { + return false; + } + let limit = photocraft_engine::print_cmds::MAX_POSITION_INCHES; + f.insert("center".into(), json!(false)); + f.insert("left".into(), json!(left.clamp(-limit, limit))); + f.insert("top".into(), json!(top.clamp(-limit, limit))); + true +} + +/// Maps the engine's bottom-left print-point rectangle into top-left egui coordinates. +/// `k` is egui points per print point; Emulsion Down mirrors placement across the page, +/// matching the PDF page transform. Returns the full image bounds for the caller to clip. +pub(super) fn print_preview_image(l: photocraft_engine::print_cmds::PrintLayout, page: egui::Rect, k: f32) -> egui::Rect { + let (x, y, w, h) = l.rect; + let x = if l.emulsion_down { l.paper.0 - x - w } else { x }; + egui::Rect::from_min_size(egui::pos2(page.left() + x as f32 * k, page.bottom() - (y + h) as f32 * k), egui::vec2(w as f32 * k, h as f32 * k)) +} + +/// Draws the print controls and paper-clipped preview using the engine's shared layout. +/// Dragging the visible image updates dialog offsets live from a fixed gesture origin; +/// the position row stays present while centered so switching to manual cannot move the page. +pub(super) fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, id: u64) { + let t = Tokens::get(ui.ctx()); + let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return }; + // PDF exports and previews retain editable paper on Windows too. Only a real native + // submission takes its media from the printer; entering that mode refreshes the driver + // geometry after any export-only paper edits. + let printers: Option> = if !b(f, "dryRun", false) && s(f, "output", "").is_empty() { + f.get("__printers").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()) + } else { + None + }; + if printers.is_some() { + if !b(f, "__driverPageInitialized", false) { + driver_page(f); + f.insert("__driverPageInitialized".into(), json!(true)); + } + } else { + // PDF output and previews have no driver page: Scale to Fit Media uses the paper. + f.remove("__driverPageInitialized"); + f.remove("printable"); + } + let p = params(f); + let mut browse = false; + ui.horizontal_top(|ui| { + // Page preview. + ui.vertical(|ui| { + let (area, _) = ui.allocate_exact_size(egui::vec2(330.0, 400.0), egui::Sense::hover()); + ui.painter().rect_filled(area, 0.0, t.canvas); + match photocraft_engine::print_cmds::layout(&doc, &p, "file.print") { + Ok(mut l) => { + let (pw, ph) = l.paper; + let k = ((area.width() - 20.0) / pw as f32).min((area.height() - 20.0) / ph as f32); + let page = egui::Rect::from_center_size(area.center(), egui::vec2(pw as f32 * k, ph as f32 * k)); + ui.painter().rect_filled(page, 0.0, egui::Color32::WHITE); + ui.painter().rect_stroke(page, 0.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Outside); + let mut img = print_preview_image(l, page, k); + let drag_id = ui.scope_id().with(("print-position", id)); + let visible = img.intersect(page).intersect(ui.clip_rect()); + let response = ui.interact(visible, drag_id, egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Print preview image"))); + // Keep a fixed layout and press origin for the whole gesture: rounding and + // the transition from Center must never accumulate or move the grab point. + if response.drag_started_by(egui::PointerButton::Primary) + && let Some(origin) = ui.input(|i| i.pointer.press_origin()) + { + ui.data_mut(|d| d.insert_temp(drag_id, (l, origin, k))); + } + if (response.dragged_by(egui::PointerButton::Primary) || response.drag_stopped_by(egui::PointerButton::Primary)) + && let Some((start, origin, scale)) = ui.data(|d| d.get_temp::<(photocraft_engine::print_cmds::PrintLayout, egui::Pos2, f32)>(drag_id)) + && let Some(pointer) = response.interact_pointer_pos() + && drag_print_position(f, start, pointer - origin, scale) + { + if let Ok(updated) = photocraft_engine::print_cmds::layout(&doc, ¶ms(f), "file.print") { + l = updated; + img = print_preview_image(l, page, k); + } + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + } + if !ui.input(|i| i.pointer.primary_down()) { + ui.data_mut(|d| d.remove::<(photocraft_engine::print_cmds::PrintLayout, egui::Pos2, f32)>(drag_id)); + } + let (x, y, w, h) = l.rect; + let key = egui::Id::unique(("print-thumb", doc.id.0, app.session.active().map_or(0, |d| d.revision))); + let tex: Option> = ui.data(|d| d.get_temp(key)); + let tex = tex.unwrap_or_else(|| { + let th = photocraft_compose::thumbnail(&doc, 400); + let ci = egui::ColorImage::from_rgba_unmultiplied([th.width as usize, th.height as usize], &th.pixels); + let tx = Arc::new(ui.ctx().load_texture("print-thumb", ci, egui::TextureOptions::LINEAR)); + ui.data_mut(|d| d.insert_temp(key, tx.clone())); + tx + }); + let clip = ui.painter().with_clip_rect(page); + let uv = if l.emulsion_down { + egui::Rect::from_min_max(egui::pos2(1.0, 0.0), egui::pos2(0.0, 1.0)) + } else { + egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)) + }; + clip.image(tex.id(), img, uv, egui::Color32::WHITE); + let mark = egui::Stroke::new(1.0, egui::Color32::BLACK); + if l.marks.corner_crop { + // Bleed puts the marks on the trim line, inside the image edge. + let b = l.marks.bleed as f32 * k; + for (c, dx, dy) in + [(img.left_top(), -1.0, -1.0), (img.right_top(), 1.0, -1.0), (img.left_bottom(), -1.0, 1.0), (img.right_bottom(), 1.0, 1.0)] + { + clip.line_segment([c + egui::vec2(dx * 3.0, -dy * b), c + egui::vec2(dx * 12.0, -dy * b)], mark); + clip.line_segment([c + egui::vec2(-dx * b, dy * 3.0), c + egui::vec2(-dx * b, dy * 12.0)], mark); + } + } + if l.marks.registration { + for c in [ + img.center_top() - egui::vec2(0.0, 9.0), + img.center_bottom() + egui::vec2(0.0, 9.0), + img.left_center() - egui::vec2(9.0, 0.0), + img.right_center() + egui::vec2(9.0, 0.0), + ] { + clip.circle_stroke(c, 3.5, mark); + } + } + let fits = x >= 0.0 && y >= 0.0 && x + w <= pw && y + h <= ph; + let note = if fits { String::new() } else { " · larger than the paper".to_string() }; + ui.label( + egui::RichText::new(format!("Scale {:.1}% · {:.2} × {:.2} in{note}", l.scale * 100.0, w / 72.0, h / 72.0)) + .color(if fits { t.text_dim } else { t.warning }) + .size(11.0), + ); + } + Err(e) => { + ui.painter().text(area.center(), egui::Align2::CENTER_CENTER, e.to_string(), egui::FontId::proportional(12.0), t.text_dim); + } + } + }); + ui.add_space(12.0); + ui.vertical(|ui| { + ui.set_width(340.0); + let head = |ui: &mut egui::Ui, s: &str| { + ui.add_space(4.0); + ui.label(egui::RichText::new(s).font(crate::theme::semibold(12.0)).color(t.text)); + }; + head(ui, tl!("Printer Setup")); + if let Some(printers) = &printers { + // Windows: Photoshop's Printer menu and Print Settings… (the driver's own dialog). + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Printer")).color(t.text_dim)); + let before = s(f, "printer", ""); + let opts: Vec<(&str, &str)> = printers.iter().map(|n| (n.as_str(), n.as_str())).collect(); + dropdown_str(ui, "print-printer", tl!("Printer"), f, "printer", &opts, 220.0); + if s(f, "printer", "") != before { + f.remove("printerSettings"); + driver_page(f); + } + }); + ui.horizontal(|ui| { + number(ui, f, "copies", tl!("Copies"), 1.0..=999.0, "", 1.0); + if ui.button(tl!("Print Settings…")).clicked() { + let printer = s(f, "printer", ""); + let current = f.get("printerSettings").and_then(Value::as_str).and_then(|h| craft_print::rgb::DevMode::from_hex(h).ok()); + match craft_print::rgb::settings_dialog(&printer, current.as_ref(), None) { + Ok(Some(dm)) => { + f.insert("printerSettings".into(), json!(dm.to_hex())); + driver_page(f); + } + Ok(None) => {} + Err(e) => { + f.insert("__pageError".into(), json!(e.to_string())); + } + } + } + }); + // Photoshop's Layout: Portrait / Landscape turn the driver settings, so the paper + // and the preview turn with them without opening Print Settings…. + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Orientation")).color(t.text_dim)); + let wide = driver_paper_is_wide(f); + for (landscape, label) in [(false, "Portrait"), (true, "Landscape")] { + if crate::widgets::pill_tab(ui, label, wide == landscape).clicked() && wide != landscape { + turn_driver(app, f, landscape); + } + } + }); + let paper = p.get("paper").and_then(Value::as_array).map(|a| (a.first().and_then(Value::as_f64), a.get(1).and_then(Value::as_f64))); + let text = match paper { + Some((Some(w), Some(h))) => format!("{:.0} × {:.0} mm · {}", w / 72.0 * 25.4, h / 72.0 * 25.4, tl!("set in Print Settings…")), + _ => String::new(), + }; + ui.label(egui::RichText::new(text).color(t.text_dim).size(11.0)); + if let Some(e) = f.get("__pageError").and_then(Value::as_str) { + ui.label(egui::RichText::new(e).color(t.warning).size(11.0)); + } + } else { + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Printer")).color(t.text_dim)); + let mut pr = s(f, "printer", ""); + let opts = printer_options(f.get("__systemPrinters"), &pr); + let o: Vec<(String, &str)> = opts.iter().map(|(k, l)| (k.clone(), l.as_str())).collect(); + if crate::widgets::dropdown(ui, "print-printer", tl!("Printer"), &mut pr, &o, 240.0) { + f.insert("printer".into(), json!(pr)); + } + }); + number(ui, f, "copies", tl!("Copies"), 1.0..=999.0, "", 1.0); + print_paper_controls(ui, f); + } + head(ui, tl!("Color Management")); + dropdown_str( + ui, + "print-color", + tl!("Color Management"), + f, + "colorHandling", + &[ + ("printerManages", tl!("Printer Manages Colors")), + ("photocraftManages", tl!("PhotoCraft Manages Colors")), + ("noColorManagement", tl!("No Color Management")), + ], + 240.0, + ); + if s(f, "colorHandling", "") == "photocraftManages" { + // Photoshop's Printer Profile menu: the built-ins, then every installed printer + // (output class) profile by its description. + let installed: Vec<_> = photocraft_engine::installed_profiles::installed() + .into_iter() + .filter(|p| p.is_destination() && p.class == photocraft_cms::ProfileClass::Output) + .collect(); + let mut profiles: Vec<(&str, &str)> = vec![ + ("coated-cmyk", tl!("Coated CMYK")), + ("srgb", "sRGB IEC61966-2.1"), + ("adobe-rgb-compat", tl!("Adobe RGB (1998) compatible")), + ("display-p3", tl!("Display P3")), + ("gray-gamma-2.2", tl!("Gray Gamma 2.2")), + ]; + profiles.extend(installed.iter().map(|p| (p.path.as_str(), p.description.as_str()))); + // A remembered profile that is no longer installed still shows, by its file name. + let cur = s(f, "printerProfile", "coated-cmyk"); + let stem = std::path::Path::new(&cur).file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + if !profiles.iter().any(|(v, _)| *v == cur) { + profiles.push((cur.as_str(), stem.as_str())); + } + dropdown_str(ui, "print-profile", tl!("Profile"), f, "printerProfile", &profiles, 240.0); + ui.horizontal(|ui| { + dropdown_str( + ui, + "print-intent", + tl!("Mode"), + f, + "intent", + &[ + ("perceptual", tl!("Perceptual")), + ("relative", tl!("Relative Colorimetric")), + ("saturation", tl!("Saturation")), + ("absolute", tl!("Absolute Colorimetric")), + ], + 170.0, + ); + check(ui, f, "bpc", tl!("Black Point Compensation"), true); + }); + if printers.is_some() { + ui.label( + egui::RichText::new(tl!("Remember to turn off the printer's own colour management in Print Settings…")).color(t.warning).size(11.0), + ); + } + } + head(ui, tl!("Position and Size")); + dropdown_str(ui, "print-units", tl!("Units"), f, "units", &[("cm", tl!("Centimeters")), ("mm", tl!("Millimeters")), ("in", tl!("Inches"))], 130.0); + let units = s(f, "units", "cm"); + check(ui, f, "center", tl!("Center"), true); + let centered = b(f, "center", true); + let centered_layout = centered.then(|| photocraft_engine::print_cmds::layout(&doc, ¶ms(f), "file.print").ok()).flatten(); + // Revealing this row during a drag resizes the centered modal and moves the paper. + // Keep it present, showing the resolved position while Center owns the offsets. + ui.add_enabled_ui(!centered, |ui| { + ui.horizontal(|ui| { + // Kept in inches (Photoshop's Position fields), shown in the chosen units. + for (key, label) in [("top", tl!("Top")), ("left", tl!("Left"))] { + let mut pt = + centered_layout.map_or_else(|| n(f, key, 0.0) * 72.0, |l| if key == "top" { l.paper.1 - l.rect.1 - l.rect.3 } else { l.rect.0 }); + let limit = (photocraft_engine::print_cmds::MAX_POSITION_INCHES * 72.0 / unit_pt(&units)) as f32; + if length_field_range(ui, label, &mut pt, &units, 2, -limit..=limit) { + let limit = photocraft_engine::print_cmds::MAX_POSITION_INCHES; + f.insert(key.into(), json!((pt / 72.0).clamp(-limit, limit))); + } + } + }); + }); + check(ui, f, "scaleToFit", tl!("Scale to Fit Media"), false); + // Scaled Print Size: Scale, Height and Width move together; Print Resolution follows. + if let Ok(l) = photocraft_engine::print_cmds::layout(&doc, ¶ms(f), "file.print") { + let (_, _, w, h) = l.rect; + let (mut w2, mut h2) = (w, h); + let fit = b(f, "scaleToFit", false); + if !fit { + // Two decimals: Height and Width set fractional scales. + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Scale")).color(t.text_dim)); + let mut v = n(f, "scale", 100.0) as f32; + crate::widgets::value_field(ui, &mut v, 1.0..=1000.0, "%", 64.0).accessible_name(tl!("Scale")); + f.insert("scale".into(), json!((f64::from(v) * 100.0).round() / 100.0)); + }); + } + ui.horizontal(|ui| { + let hc = length_field(ui, tl!("Height"), &mut h2, &units); + let wc = length_field(ui, tl!("Width"), &mut w2, &units); + let k = if wc && w > 0.0 { + Some(w2 / w) + } else if hc && h > 0.0 { + Some(h2 / h) + } else { + None + }; + if let Some(k) = k.filter(|k| k.is_finite() && *k > 0.0) { + f.insert("scale".into(), json!(((l.scale * k * 100.0) * 100.0).round() / 100.0)); + f.insert("scaleToFit".into(), json!(false)); + } + }); + if w > 0.0 { + let ppi = f64::from(doc.size.width) / (w / 72.0); + ui.label(egui::RichText::new(format!("{} {ppi:.0} PPI", tl!("Print Resolution:"))).color(t.text_dim).size(11.0)); + } + } + head(ui, tl!("Printing Marks")); + ui.horizontal(|ui| { + check(ui, f, "cornerCropMarks", tl!("Corner Crop Marks"), false); + check(ui, f, "centerCropMarks", tl!("Center Crop Marks"), false); + }); + ui.horizontal(|ui| { + check(ui, f, "registrationMarks", tl!("Registration Marks"), false); + check(ui, f, "description", tl!("Description"), false); + check(ui, f, "labels", tl!("Labels"), false); + }); + head(ui, tl!("Functions")); + check(ui, f, "emulsionDown", tl!("Emulsion Down"), false); + if b(f, "emulsionDown", false) && printers.is_some() { + ui.label(egui::RichText::new(tl!("Don't also tick Mirror Image in Print Settings…: the two flips cancel out.")).color(t.text_dim).size(11.0)); + } + head(ui, tl!("Save as PDF")); + ui.horizontal(|ui| { + let mut out = s(f, "output", ""); + if ui.add(egui::TextEdit::singleline(&mut out).hint_text(tl!("(print to the printer)")).desired_width(240.0)).changed() { + f.insert("output".into(), json!(out)); + } + browse = ui.button(tl!("Browse…")).clicked(); + }); + }); + }); + if browse { + let current = s(f, "output", ""); + let suggested = if current.is_empty() { std::path::Path::new(&doc.name).with_extension("pdf").to_string_lossy().into_owned() } else { current }; + browse_pdf(app, id, &suggested); + } +} + +/// `file.print`'s params. The driver's printable area only goes with a print to the printer: +/// an output path or a preview set in the same frame as the confirm still drops it. +pub(super) fn print_params(f: &Map) -> Value { + let mut p = params(f); + if (b(f, "dryRun", false) || !s(f, "output", "").is_empty()) + && let Some(o) = p.as_object_mut() + { + o.remove("printable"); + } + p +} + +/// Submits the dialog parameters to `file.print`, propagating command errors unchanged. +/// Updates the status for completed results only; pending jobs report completion later. +pub(super) fn print_confirm(app: &mut PhotocraftApp, f: &Map) -> Result { + let r = app.run("file.print", print_params(f))?; + if r["pending"] != json!(true) { + print_status(app, &r); + } + Ok(r) +} + +pub(crate) fn print_status(app: &mut PhotocraftApp, r: &Value) { + app.ui.status = if let Some(printer) = r["spooler"]["printer"].as_str() { + crate::i18n::fmt(tl!("Sent to {printer}"), &[("printer", printer)]) + } else if r["sent"] == json!(true) { + let template = "Sent to the printer ({spooler})"; + crate::i18n::fmt(tl!(template), &[("spooler", r["spooler"].as_str().unwrap_or(""))]) + } else { + let template = "Printed to {path}"; + crate::i18n::fmt(tl!(template), &[("path", r["pdf"].as_str().unwrap_or(""))]) + }; + app.ui.status_error = false; +} diff --git a/crates/ui-egui/src/file_ui/web.rs b/crates/ui-egui/src/file_ui/web.rs new file mode 100644 index 0000000000..a2d45fa2f3 --- /dev/null +++ b/crates/ui-egui/src/file_ui/web.rs @@ -0,0 +1,568 @@ +use super::*; + +const WEB_FORMATS: [(&str, &str); 5] = [("gif", "GIF"), ("png8", "PNG-8"), ("png24", "PNG-24"), ("jpeg", "JPEG"), ("wbmp", "WBMP")]; + +pub(super) const WEB_COMMAND: &str = "file.export.saveForWebLegacy"; + +/// Save for Web's preview tabs: the `__view` field's values and their labels. +const WEB_VIEWS: [(&str, &str); 4] = [("original", "Original"), ("optimized", "Optimized"), ("2up", "2-Up"), ("4up", "4-Up")]; + +pub fn open_web(app: &mut PhotocraftApp) -> u64 { + let mut f = Map::new(); + f.insert("__web".into(), json!(true)); + f.insert("__command".into(), json!(WEB_COMMAND)); + f.insert("__label".into(), json!("Save for Web (Legacy)")); + // The preview tab chosen last time, 2-Up at first (#9174). + let view = app.ui.web_view.as_deref().filter(|v| WEB_VIEWS.iter().any(|(k, _)| k == v)).unwrap_or("2up"); + f.insert("__view".into(), json!(view)); + // Remember encoding choices, but each document starts at its own full size. This session's + // last export lives in `file_menu`; the last one before a restart comes from the + // preferences' remembered dialog settings (`web_cmds::remember_web_settings`). + let last = app + .session + .file_menu + .last_web + .clone() + .or_else(|| app.session.prefs().dialogs.get(WEB_COMMAND).cloned()) + .unwrap_or_else(|| json!({"format": "jpeg", "quality": 60})); + if let Value::Object(m) = last { + for (k, v) in m { + if !matches!(k.as_str(), "path" | "dir" | "width" | "height" | "percent" | "colorTable" | "colorTableEdits") { + f.insert(k, v); + } + } + } + for (k, v) in [ + ("format", json!("jpeg")), + ("quality", json!(60)), + ("palette", json!("selective")), + ("colors", json!(128)), + ("dither", json!("diffusion")), + ("ditherAmount", json!(88)), + ("transparency", json!(true)), + ("matte", json!("#ffffff")), + ("interlaced", json!(false)), + ("progressive", json!(false)), + ("optimized", json!(true)), + ("embedIcc", json!(false)), + ("convertToSrgb", json!(true)), + ("metadata", json!("copyright")), + ("percent", json!(100.0)), + ("resample", json!("bicubic")), + ("webSnap", json!(0)), + ] { + f.entry(k.to_string()).or_insert(v); + } + app.ui.open_dialog(DialogKind::Command, f) +} + +/// Settings variants shown in 4-Up (current, then two smaller alternatives). +fn variants(p: &Value) -> Vec { + let mut out = vec![p.clone()]; + let fmt = p["format"].as_str().unwrap_or("jpeg"); + for k in [2.0, 4.0] { + let mut v = p.clone(); + if let Some(m) = v.as_object_mut() { + m.remove("colorTable"); + m.remove("colorTableEdits"); + } + if fmt == "jpeg" { + v["quality"] = json!((p["quality"].as_f64().unwrap_or(60.0) / k).round().max(1.0)); + } else if fmt == "gif" || fmt == "png8" { + v["colors"] = json!((p["colors"].as_f64().unwrap_or(128.0) / k).round().max(2.0)); + } else { + v["format"] = json!(if k == 2.0 { "png8" } else { "gif" }); + v["colors"] = json!(256 / k as u32); + } + out.push(v); + } + out +} + +/// The flattened preview image: pixels, width, height, full-size / proxy pixel ratio. +pub(super) type WebProxy = (Arc>, u32, u32, f64, egui::Vec2); + +pub(super) type WebCache = (String, Arc, Option<(usize, Option, &'static str)>); + +/// Renders one preview pane: the original (`None`) or an optimised variant. +fn web_pane(app: &PhotocraftApp, ui: &mut egui::Ui, size: egui::Vec2, p: Option<&Value>, f: &mut Map, pane: usize, frame: Option) { + let t = Tokens::get(ui.ctx()); + let Some(st) = app.session.active() else { return }; + let doc = st.doc.clone(); + let rev = st.revision; + // A bounded proxy; navigation never recomposites or re-encodes it. + let base = p.cloned().unwrap_or_else(|| json!({})); + let size_sig = format!("{}|{}|{}|{}|{}", base["percent"], base["width"], base["height"], base["resample"], base["convertToSrgb"]); + let wkey = egui::Id::unique(("web-proxy", doc.id.0, pane)); + let proxy_sig = format!("{rev}|{frame:?}|{size_sig}"); + let cached_proxy: Option<(String, WebProxy)> = ui.data(|d| d.get_temp(wkey)); + let proxy = cached_proxy.filter(|(sig, _)| sig == &proxy_sig).map(|(_, proxy)| proxy); + let (px, w, h, ratio, source_size) = match proxy { + Some(v) => v, + None => { + let (fw, fh) = match web_preview::dimensions(&doc, &base) { + Ok(size) => size, + Err(error) => { + ui.label(error); + return; + } + }; + let k = (2048.0 / fw.max(fh)).min(1.0); + let st = WebSettings::from_params(&base, "preview").unwrap_or_default(); + let Ok(doc) = web_frame_document(&doc, frame) else { return }; + let resample = web_preview::proxy_resample(&base, k); + let Ok((wd, _, _)) = + web_cmds::web_document(&doc, &json!({"width": (fw * k).round().max(1.0), "height": (fh * k).round().max(1.0), "resample": resample}), &st) + else { + return; + }; + let buf = photocraft_compose::flatten(&wd); + let v = ( + Arc::new(buf.px), + wd.size.width, + wd.size.height, + (fw * fh) / (f64::from(wd.size.width) * f64::from(wd.size.height)).max(1.0), + egui::vec2(fw as f32, fh as f32), + ); + ui.data_mut(|d| d.insert_temp(wkey, (proxy_sig, v.clone()))); + v + } + }; + let sig = format!("{}|{rev}|{frame:?}|{size_sig}|{}", doc.id.0, p.map(|v| v.to_string()).unwrap_or_else(|| "original".into())); + let key = egui::Id::unique(("web-pane", doc.id.0, pane)); + let cached: Option = ui.data(|d| d.get_temp(key)); + let (tex, info) = match cached.filter(|c| c.0 == sig) { + Some((_, tex, info)) => (tex, info), + None => { + let (rgba, info) = match p { + None => (px.iter().flat_map(|q| q.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)).collect::>(), None), + Some(p) => match web_preview::optimized(ui, key, &format!("{}|{rev}|{frame:?}|{size_sig}", doc.id.0), p, &px, w, h) { + Ok((preview, bytes, colors, ext)) => (preview, Some(((bytes as f64 * ratio) as usize, colors, ext))), + Err(error) => { + ui.label(error); + (vec![0; (w * h * 4) as usize], None) + } + }, + }; + let img = egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &rgba); + let tex = Arc::new(ui.ctx().load_texture("web-pane", img, egui::TextureOptions::LINEAR)); + ui.data_mut(|d| d.insert_temp(key, (sig, tex.clone(), info))); + (tex, info) + } + }; + ui.vertical(|ui| { + ui.set_width(size.x); + let (r, response) = ui.allocate_exact_size((size - egui::vec2(0.0, 42.0)).max(egui::vec2(1.0, 1.0)), egui::Sense::drag()); + let response = response.on_hover_cursor(egui::CursorIcon::Grab); + if let Some(rects) = f.get_mut("__previewRects").and_then(Value::as_array_mut) { + rects.push(json!([r.left(), r.top(), r.right(), r.bottom()])); + } + crate::widgets::checker(ui.painter(), r, 8.0); + web_preview::paint(ui, r, &response, &tex, source_size, f); + ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.separator), egui::StrokeKind::Inside); + let (l1, l2) = match (p, info) { + (None, _) => ("Original".to_string(), format!("{} · {} × {} px", doc.name, doc.size.width, doc.size.height)), + (Some(_), Some((bytes, colors, ext))) => { + // Photoshop's download estimate at 56.6 Kbps. + let secs = (bytes as f64 * 8.0 / 56_600.0).ceil(); + ( + format!("{} {}", ext.to_uppercase(), crate::sizing::human_bytes(bytes as f64)), + format!("{secs} sec @ 56.6 Kbps{}", colors.map(|c| format!(" · {c} colors")).unwrap_or_default()), + ) + } + (Some(_), None) => ("—".into(), String::new()), + }; + let l1 = if ratio > 1.001 { format!("{l1} · Proxy preview") } else { l1 }; + ui.add(egui::Label::new(egui::RichText::new(l1).color(t.text).size(11.5)).truncate()); + ui.add(egui::Label::new(egui::RichText::new(l2).color(t.text_dim).size(11.0)).truncate()); + }); +} + +/// Advance a preview clock by whole elapsed frames, retaining fractional time. +/// The caller resets `last` on Play so paused wall time never advances the preview. +pub(super) fn advance_preview(frame: usize, duration: usize, fps: f32, last: f64, now: f64) -> (usize, f64) { + let duration = duration.max(1); + let frame = frame.min(duration - 1); + if !now.is_finite() { + return (frame, last); + } + if !last.is_finite() || now < last { + return (frame, now); + } + let fps = if fps.is_finite() && fps > 0.0 { f64::from(fps) } else { 30.0 }; + let elapsed_frames = (now - last) * fps; + if !elapsed_frames.is_finite() { + return (frame, now); + } + let steps = elapsed_frames.floor(); + if steps < 1.0 { + return (frame, last); + } + let delta = (steps % duration as f64) as usize % duration; + let remaining = duration - frame; + let next = if delta >= remaining { delta - remaining } else { frame + delta }; + (next, now - (elapsed_frames - steps) / fps) +} + +fn web_playback(ui: &mut egui::Ui, f: &mut Map, doc: &photocraft_doc::Document) -> Option { + let mut timeline = doc.timeline.clone()?; + timeline.clamp(); + if timeline.duration < 2 { + return None; + } + let now = ui.input(|i| i.time); + let mut frame = f.get("__web_frame").and_then(Value::as_u64).and_then(|v| usize::try_from(v).ok()).unwrap_or(timeline.current).min(timeline.duration - 1); + let mut last = n(f, "__web_time", now); + let mut playing = b(f, "__web_playing", false); + if playing { + (frame, last) = advance_preview(frame, timeline.duration, timeline.fps, last, now); + } + ui.horizontal(|ui| { + if crate::icons::button(ui, if playing { "pause" } else { "play" }, 22.0, playing, if playing { tl!("Pause") } else { tl!("Play") }).clicked() { + playing = !playing; + last = now; + } + ui.label(format!("{} / {}", frame + 1, timeline.duration)); + }); + f.insert("__web_frame".into(), json!(frame)); + f.insert("__web_time".into(), json!(last)); + f.insert("__web_playing".into(), json!(playing)); + if playing { + let remaining = (1.0 / f64::from(timeline.fps) - (now - last)).clamp(0.0, 1.0); + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(remaining)); + } + Some(frame) +} + +/// Seek a preview copy, preserving any edits to the source's currently displayed frame. +pub(super) fn web_frame_document(doc: &photocraft_doc::Document, frame: Option) -> Result { + let Some(frame) = frame else { return Ok(doc.clone()) }; + let mut preview = photocraft_engine::Session::new(); + preview.add_document(doc.clone(), None); + preview.execute("timeline.setFrame", json!({"frame": frame}))?; + Ok((*preview.active().ok_or(photocraft_engine::EngineError::NoDocument)?.doc).clone()) +} + +pub(super) fn web_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { + let t = Tokens::get(ui.ctx()); + let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return }; + ui.horizontal(|ui| { + let mut view = s(f, "__view", "2up"); + for (k, l) in WEB_VIEWS { + if ui.selectable_label(view == k, tl!(l)).clicked() { + view = k.into(); + // The next Save for Web opens on this tab, as Photoshop's does. + app.ui.web_view = Some(view.clone()); + } + } + f.insert("__view".into(), json!(view)); + }); + ui.add_space(4.0); + let frame = web_playback(ui, f, &doc); + web_preview::controls(ui, f); + if let Err(error) = web_preview::prepare_table(app, f) { + ui.colored_label(t.text_dim, error); + } + let p = params(f); + f.insert("__previewRects".into(), json!([])); + let area = egui::vec2((ui.available_width() - 270.0 - ui.spacing().item_spacing.x).max(260.0), (ui.available_height() - 48.0).max(180.0)); + ui.horizontal_top(|ui| { + // Previews grow with the dialog; settings retain their compact width. + ui.vertical(|ui| { + ui.set_width(area.x); + match s(f, "__view", "2up").as_str() { + "original" => web_pane(app, ui, area, None, f, 0, frame), + "optimized" => web_pane(app, ui, area, Some(&p), f, 1, frame), + "2up" => { + ui.horizontal(|ui| { + web_pane(app, ui, egui::vec2(area.x / 2.0 - 4.0, area.y), None, f, 0, frame); + web_pane(app, ui, egui::vec2(area.x / 2.0 - 4.0, area.y), Some(&p), f, 1, frame); + }); + } + _ => { + let v = variants(&p); + let cell = egui::vec2(area.x / 2.0 - 4.0, area.y / 2.0 - 4.0); + ui.horizontal(|ui| { + web_pane(app, ui, cell, None, f, 0, frame); + web_pane(app, ui, cell, Some(&v[0]), f, 1, frame); + }); + ui.horizontal(|ui| { + web_pane(app, ui, cell, Some(&v[1]), f, 2, frame); + web_pane(app, ui, cell, Some(&v[2]), f, 3, frame); + }); + } + } + }); + ui.add_space(10.0); + // Settings scroll independently on smaller windows. + ui.vertical(|ui| { + ui.set_width(250.0); + egui::ScrollArea::vertical().id_salt("web-settings").max_height(area.y).show(ui, |ui| { + ui.label(egui::RichText::new(tl!("Preset")).color(t.text_dim)); + let mut preset = s(f, "__preset", ""); + let mut opts: Vec<(String, &str)> = vec![("".into(), "[Unnamed]")]; + opts.extend(web_cmds::PRESETS.iter().map(|p| (p.to_string(), *p))); + if crate::widgets::dropdown(ui, "web-preset", tl!("Preset"), &mut preset, &opts, 230.0) && !preset.is_empty() { + if let Some(Value::Object(m)) = web_cmds::preset_settings(&preset).map(|st| st.to_params()) { + f.extend(m); + } + f.insert("__preset".into(), json!(preset)); + } + ui.add_space(4.0); + dropdown_str(ui, "web-format", tl!("Format"), f, "format", &WEB_FORMATS, 230.0); + ui.add_space(4.0); + let fmt = s(f, "format", "jpeg"); + match fmt.as_str() { + "gif" | "png8" => { + dropdown_str( + ui, + "web-palette", + tl!("Color Table"), + f, + "palette", + &[ + ("perceptual", tl!("Perceptual")), + ("selective", tl!("Selective")), + ("adaptive", tl!("Adaptive")), + ("restrictive", tl!("Restrictive (Web)")), + ("exact", tl!("Exact")), + ], + 150.0, + ); + number(ui, f, "colors", tl!("Colors"), 2.0..=256.0, "", 128.0); + dropdown_str( + ui, + "web-dither", + tl!("Dither"), + f, + "dither", + &[("none", tl!("No Dither")), ("diffusion", tl!("Diffusion")), ("pattern", tl!("Pattern")), ("noise", tl!("Noise"))], + 150.0, + ); + number(ui, f, "ditherAmount", tl!("Dither"), 0.0..=100.0, "%", 88.0); + check(ui, f, "transparency", tl!("Transparency"), true); + check(ui, f, "interlaced", tl!("Interlaced"), false); + number(ui, f, "webSnap", tl!("Web Snap"), 0.0..=100.0, "%", 0.0); + } + "jpeg" => { + number(ui, f, "quality", tl!("Quality"), 0.0..=100.0, "", 60.0); + check(ui, f, "progressive", tl!("Progressive"), false); + check(ui, f, "optimized", tl!("Optimized"), true); + check(ui, f, "embedIcc", tl!("Embed Color Profile"), false); + } + "wbmp" => { + dropdown_str( + ui, + "web-dither", + tl!("Dither"), + f, + "dither", + &[("none", tl!("No Dither")), ("diffusion", tl!("Diffusion")), ("pattern", tl!("Pattern"))], + 150.0, + ); + } + _ => { + check(ui, f, "transparency", tl!("Transparency"), true); + check(ui, f, "interlaced", tl!("Interlaced"), false); + } + } + if fmt != "png24" || !b(f, "transparency", true) { + ui.horizontal(|ui| { + let matte_label = ui.label(egui::RichText::new(tl!("Matte")).color(t.text_dim)); + let mut m = s(f, "matte", "#ffffff"); + if ui.add(egui::TextEdit::singleline(&mut m).desired_width(80.0)).labelled_by(matte_label.id).changed() { + f.insert("matte".into(), json!(m)); + } + }); + } + ui.add_space(6.0); + check(ui, f, "convertToSrgb", tl!("Convert to sRGB"), true); + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Metadata")).color(t.text_dim)); + dropdown_str( + ui, + "web-meta", + tl!("Metadata"), + f, + "metadata", + &[ + ("none", tl!("None")), + ("copyright", tl!("Copyright")), + ("copyrightAndContact", tl!("Copyright and Contact Info")), + ("all", tl!("All")), + ], + 160.0, + ); + }); + if matches!(fmt.as_str(), "gif" | "png8") { + web_preview::table(ui, f); + } + ui.add_space(8.0); + ui.label(egui::RichText::new(tl!("Image Size")).font(crate::theme::semibold(12.0)).color(t.text)); + web_size(ui, f, &doc); + let nslices = photocraft_doc::slices::resolve(&doc).len(); + if !doc.slices.is_empty() { + ui.add_space(6.0); + ui.label(egui::RichText::new(crate::i18n::trn(crate::i18n::current(), nslices as u64, "{n} slice", "{n} slices")).color(t.text_dim)); + check(ui, f, "html", tl!("Save HTML and Images"), true); + dropdown_str(ui, "web-slices", tl!("Slices"), f, "slices", &[("all", tl!("All Slices")), ("user", tl!("All User Slices"))], 150.0); + } + }); + }); + }); +} + +/// A size row in a two-column grid: the label, then a field showing `shown`. Returns the typed +/// value when it changed, compared with the value the widget was given so a field that only +/// clamps does not count as an edit. +fn size_field(ui: &mut egui::Ui, label: &str, shown: f64, range: std::ops::RangeInclusive, unit: &str, decimals: u32) -> Option { + let t = Tokens::get(ui.ctx()); + let passed = (shown as f32).clamp(*range.start(), *range.end()); + let mut v = passed; + ui.label(egui::RichText::new(label).color(t.text_dim)); + crate::widgets::value_field_prec(ui, &mut v, range, unit, 90.0, decimals).accessible_name(tl!(&label)); + ui.end_row(); + (v != passed).then_some(f64::from(v)) +} + +/// Image Size, as in Photoshop's Save for Web: Width and Height linked in proportion (on at +/// each opening), Percent and the resampling method. A side edit sets exact pixels and drops +/// `percent`, which the engine would otherwise apply first; a Percent edit sets both sides. +fn web_size(ui: &mut egui::Ui, f: &mut Map, doc: &photocraft_doc::Document) { + use crate::export_dialog::{MAX_PX, resize_from_scale, resize_from_side}; + let (w0, h0) = (f64::from(doc.size.width).max(1.0), f64::from(doc.size.height).max(1.0)); + let (w, h) = web_preview::dimensions(doc, ¶ms(f)).unwrap_or((w0, h0)); + let lock = b(f, "__constrain", true); + let pct = n(f, "percent", w / w0 * 100.0); + let write = |f: &mut Map, width: f64, height: f64| { + f.insert("width".into(), json!(width)); + f.insert("height".into(), json!(height)); + }; + let max = MAX_PX as f32; + let (width, height, percent) = egui::Grid::new("web-size") + .num_columns(2) + .show(ui, |ui| { + ( + size_field(ui, tl!("Width"), w, 1.0..=max, "px", 0), + size_field(ui, tl!("Height"), h, 1.0..=max, "px", 0), + size_field(ui, tl!("Percent"), pct, 1.0..=1000.0, "%", 2), + ) + }) + .inner; + let side = match (width, height) { + (Some(v), _) => resize_from_side(w0, h0, v.round(), h, lock, true).ok(), + (_, Some(v)) => resize_from_side(w0, h0, w, v.round(), lock, false).ok(), + _ => None, + }; + if let Some(size) = side { + f.remove("percent"); + write(f, size.width, size.height); + } else if let Some(v) = percent + && let Ok(size) = resize_from_scale(w0, h0, v) + { + f.insert("percent".into(), json!(size.scale)); + write(f, size.width, size.height); + } + let mut linked = lock; + if crate::widgets::checkbox(ui, &mut linked, tl!("Constrain proportions")).changed() { + f.insert("__constrain".into(), json!(linked)); + // Linked again, the height follows the width in the document's proportions. + if linked && let Ok(size) = resize_from_side(w0, h0, w, h, true, true) { + f.remove("percent"); + write(f, size.width, size.height); + } + } + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Resample")).color(Tokens::get(ui.ctx()).text_dim)); + // Photoshop's Save for Web list, in its order. + dropdown_str( + ui, + "web-resample", + tl!("Resample"), + f, + "resample", + &[ + ("nearest", tl!("Nearest Neighbor (hard edges)")), + ("bilinear", tl!("Bilinear")), + ("bicubic", tl!("Bicubic (smooth gradients)")), + ("bicubicSmoother", tl!("Bicubic Smoother (enlargement)")), + ("bicubicSharper", tl!("Bicubic Sharper (reduction)")), + ], + 170.0, + ); + }); +} + +pub(super) fn web_confirm(app: &mut PhotocraftApp, f: &Map) -> Result { + // Check while the control/input policy is still installed, before an asynchronous picker + // can outlive the request. A browser download uses the interactive platform writer. + let authorize = |p: &Value| -> Result<(), String> { + if let Some(authorize) = app.session.authorize.or(if app.automation_input { app.services.automation_authorize } else { None }) { + authorize(WEB_COMMAND, p).map_err(|e| e.to_string())?; + } + if app.automation_input + && let Some(authorize) = app.services.automation_command.as_ref() + { + authorize(WEB_COMMAND, p)?; + } + Ok(()) + }; + let mut p = params(f); + authorize(&p)?; + // Confirmation may follow a field edit without an intervening frame (Enter or automation). + let mut fields = f.clone(); + web_preview::prepare_table(app, &mut fields)?; + let prepared = params(&fields); + if prepared != p { + // The policy must also approve the actual palette-bearing export parameters. + authorize(&prepared)?; + p = prepared; + } + if p.get("path").is_some() || p.get("dir").is_some() { + return save_for_web(app, p); + } + let doc = app.session.active().ok_or("no document")?.doc.clone(); + let has_slices = !doc.slices.is_empty(); + let html = b(f, "html", true); + let st = WebSettings::from_params(&p, "file.export.saveForWebLegacy").map_err(|e| e.to_string())?; + let base = photocraft_doc::slices::base_name(&doc); + let suggested = if has_slices && html { format!("{base}.html") } else { format!("{base}.{}", st.format.ext()) }; + app.pick_save(&suggested, move |app, path| { + app.refocus(doc.id)?; + if has_slices { + let dir = path.rfind(['/', '\\']).map(|i| path[..i].to_string()).unwrap_or_else(|| ".".into()); + p["dir"] = json!(dir); + p["html"] = json!(html); + } else { + p["path"] = json!(path); + } + save_for_web(app, p) + }) +} + +/// Runs Save for Web with `p`, which says where to write. +fn save_for_web(app: &mut PhotocraftApp, p: Value) -> Result { + #[cfg(target_arch = "wasm32")] + let result = download_for_web(app, p); + #[cfg(not(target_arch = "wasm32"))] + let result = app.run(WEB_COMMAND, p); + let r = result.inspect_err(|error| { + app.ui.status = error.clone(); + app.ui.status_error = true; + })?; + app.sync_views(); + app.ui.status = + crate::i18n::trn(crate::i18n::current(), r["files"].as_array().map_or(0, Vec::len) as u64, "Saved for Web: {n} file", "Saved for Web: {n} files"); + app.ui.status_error = false; + Ok(r) +} + +#[cfg(any(test, target_arch = "wasm32"))] +pub(super) fn download_for_web(app: &mut PhotocraftApp, mut p: Value) -> Result { + // Browser downloads have no directory hierarchy. Keep the HTML's image and spacer URLs + // beside the downloaded page, matching the names handed to the platform service. + p["imagesFolder"] = json!(""); + let write = app.services.write.as_mut().ok_or("no download service")?; + web_cmds::save_for_web_with_writer(&mut app.session, &p, &mut |path, bytes| write(path, bytes).map_err(photocraft_engine::EngineError::Other)) + .map_err(|e| e.to_string()) +} From cc46a4f3a28e66d891d07212acd5b07761419442 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:34:35 +0000 Subject: [PATCH 223/259] refactor(ui-egui): split preset_panels.rs into preset_panels/ --- crates/ui-egui/src/preset_panels.rs | 690 +-------------------- crates/ui-egui/src/preset_panels/panels.rs | 685 ++++++++++++++++++++ 2 files changed, 691 insertions(+), 684 deletions(-) create mode 100644 crates/ui-egui/src/preset_panels/panels.rs diff --git a/crates/ui-egui/src/preset_panels.rs b/crates/ui-egui/src/preset_panels.rs index 1542c914dd..b624e53bdd 100644 --- a/crates/ui-egui/src/preset_panels.rs +++ b/crates/ui-egui/src/preset_panels.rs @@ -18,6 +18,12 @@ use crate::PhotocraftApp; use crate::state::Tool; use crate::theme::Tokens; +mod panels; + +#[cfg(test)] +use panels::{new_tool_preset_params, tool_id}; +pub use panels::{clone_sample_point, clone_source_panel, finish_custom_shape, gradients_panel, patterns_panel, select_tool_preset, shape_picker, shapes_panel, styles_panel, tool_presets_panel, windows}; + /// Panel state (serde, so the control channel can read and drive it). #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default)] @@ -677,690 +683,6 @@ fn canvas_drop_rect(app: &PhotocraftApp) -> egui::Rect { crate::rulers::content_rect(app, app.last_canvas_rect) } -// ------------------------------------------------------------------ Gradients - -pub fn gradients_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); - let groups_src = app.session.presets.gradients.clone(); - // Current gradient (what the Gradient tool paints), like the panel's top "recent" row. - let cur = app.session.presets.gradient.clone(); - let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 18.0), Sense::hover()); - paint_gradient(ui, r, &cur.resolve(fg, bg)); - ui.painter().rect_stroke(r, 2.0, Stroke::new(1.0, Tokens::get(ui.ctx()).card_border), egui::StrokeKind::Inside); - ui.add_space(4.0); - let groups: Vec = groups_src - .iter() - .map(|g| GroupView { name: g.name.clone(), items: g.items.iter().map(|i| ItemView { key: i.name.clone(), name: i.name.clone() }).collect() }) - .collect(); - let canvas = canvas_drop_rect(app); - let mut st = std::mem::take(&mut app.ui.presets_ui); - let max_h = (ui.available_height() - 40.0).clamp(90.0, 260.0); - let events = - browser(ui, &mut st, "gradients", &groups, Place { canvas, max_h, new_tip: tl!("Create new gradient"), flush: false }, &mut |ui, r, gi, ii| { - let stops = groups_src[gi].items[ii].resolve(fg, bg); - paint_gradient(ui, r, &stops); - }); - app.ui.presets_ui = st; - for e in events { - match &e { - Ev::Select(k) => { - app.ui.presets_ui.selected.insert("gradients".into(), k.clone()); - run(app, "gradient.presets.select", json!({"preset": k})); - } - Ev::Activate(k) | Ev::Drop(k, _) => { - app.ui.presets_ui.selected.insert("gradients".into(), k.clone()); - run(app, "gradient.presets.apply", json!({"preset": k})); - } - _ => { - generic(app, "gradients", "gradient.presets", &e, json!({"name": "Custom"})); - } - } - } -} - -// ------------------------------------------------------------------ Patterns - -pub fn patterns_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - photocraft_engine::presets::patterns::sync(&mut app.session); - let lib = app.session.patterns.items.clone(); - let groups: Vec = app - .session - .presets - .pattern_groups - .iter() - .map(|g| GroupView { - name: g.name.clone(), - items: g - .items - .iter() - .filter_map(|id| lib.iter().find(|p| &p.id == id)) - .map(|p| ItemView { key: p.id.clone(), name: p.display_name().to_string() }) - .collect(), - }) - .collect(); - let pats: Vec> = - app.session.presets.pattern_groups.iter().map(|g| g.items.iter().filter_map(|id| lib.iter().find(|p| &p.id == id).cloned()).collect()).collect(); - let canvas = canvas_drop_rect(app); - let mut st = std::mem::take(&mut app.ui.presets_ui); - let max_h = (ui.available_height() - 40.0).clamp(90.0, 280.0); - let ctx = ui.ctx().clone(); - let events = browser( - ui, - &mut st, - "patterns", - &groups, - Place { canvas, max_h, new_tip: tl!("Create new pattern from the selection"), flush: false }, - &mut |ui, r, gi, ii| { - let tex = pattern_texture(&ctx, &pats[gi][ii]); - ui.painter().image(tex.id(), r, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE); - }, - ); - app.ui.presets_ui = st; - for e in events { - match &e { - Ev::Select(k) => { - app.ui.presets_ui.selected.insert("patterns".into(), k.clone()); - run(app, "pattern.presets.select", json!({"pattern": k})); - } - Ev::Activate(k) | Ev::Drop(k, _) => { - app.ui.presets_ui.selected.insert("patterns".into(), k.clone()); - run(app, "pattern.presets.apply", json!({"pattern": k})); - } - _ => { - generic(app, "patterns", "pattern.presets", &e, json!({})); - } - } - } -} - -// ------------------------------------------------------------------ floating panels - -fn float_window( - app: &mut PhotocraftApp, - ctx: &egui::Context, - key: &str, - title: &str, - width: f32, - offset: f32, - body: impl FnOnce(&mut PhotocraftApp, &mut egui::Ui), -) -> bool { - let t = Tokens::get(ctx); - let frame = egui::Frame::NONE - .fill(t.card) - .stroke(Stroke::new(1.0, t.card_border)) - .corner_radius(CornerRadius::same(t.radius_lg as u8)) - .shadow(egui::Shadow { offset: [0, 10], blur: 30, spread: 0, color: t.shadow }) - .inner_margin(egui::Margin::same(8)); - let canvas = canvas_drop_rect(app); - let mut close = false; - egui::Window::new(title) - .id(egui::Id::unique(("preset-window", key))) - .title_bar(false) - .resizable(false) - .frame(frame) - .default_pos(pos2((canvas.right() - width - 16.0 - offset).max(canvas.left() + 8.0), canvas.top() + 40.0)) - .show(ctx, |ui| { - ui.set_width(width); - // Photoshop-style tab header with a close box. - ui.horizontal(|ui| { - ui.label(egui::RichText::new(tl!(&title)).color(t.text).size(12.0).strong()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::icons::button(ui, "x", 20.0, false, tl!("Close")).clicked() { - close = true; - } - if key == "styles" { - let resp = crate::icons::button(ui, "ellipsis", 20.0, false, tl!("Panel menu")); - egui::Popup::menu(&resp).show(|ui| { - crate::widgets::style_spectrum_popup_menu(ui); - ui.set_min_width(180.0); - styles_menu(app, ui); - }); - } - }); - }); - crate::widgets::hairline(ui); - ui.add_space(4.0); - body(app, ui); - }); - close -} - -/// Draws the open floating panels (Styles, Shapes, Tool Presets, Clone Source). -pub fn windows(app: &mut PhotocraftApp, ctx: &egui::Context) { - let p = app.ui.presets_ui.clone(); - if p.styles && float_window(app, ctx, "styles", tl!("Styles"), 250.0, 0.0, styles_panel) { - app.ui.presets_ui.styles = false; - } - if p.shapes && float_window(app, ctx, "shapes", tl!("Shapes"), 250.0, 280.0, shapes_panel) { - app.ui.presets_ui.shapes = false; - } - if p.tool_presets && float_window(app, ctx, "toolPresets", tl!("Tool Presets"), 250.0, 560.0, tool_presets_panel) { - app.ui.presets_ui.tool_presets = false; - } - if p.clone_source && float_window(app, ctx, "cloneSource", tl!("Clone Source"), 270.0, 840.0, clone_source_panel) { - app.ui.presets_ui.clone_source = false; - } -} - -// ------------------------------------------------------------------ Styles - -pub fn styles_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let src = app.session.presets.styles.clone(); - let groups: Vec = src - .iter() - .map(|g| GroupView { name: g.name.clone(), items: g.items.iter().map(|i| ItemView { key: i.name.clone(), name: i.name.clone() }).collect() }) - .collect(); - let canvas = canvas_drop_rect(app); - let mut st = std::mem::take(&mut app.ui.presets_ui); - let ctx = ui.ctx().clone(); - let t = Tokens::get(&ctx); - let mut texes: Vec> = Vec::new(); - for g in &src { - texes.push(g.items.iter().map(|s| style_texture(app, &ctx, s)).collect()); - } - let events = browser( - ui, - &mut st, - "styles", - &groups, - Place { canvas, max_h: 300.0, new_tip: tl!("Create new style from the selected layer"), flush: false }, - &mut |ui, r, gi, ii| { - ui.painter().rect_filled(r, 2.0, t.field); - ui.painter().image(texes[gi][ii].id(), r, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE); - }, - ); - app.ui.presets_ui = st; - let shift = ui.input(|i| i.modifiers.shift); - for e in events { - match &e { - Ev::Select(k) | Ev::Activate(k) => { - app.ui.presets_ui.selected.insert("styles".into(), k.clone()); - // Clicking applies to the selected layers (⇧ adds to their effects). - run(app, "style.presets.apply", json!({"preset": k, "add": shift})); - } - Ev::Drop(k, pos) => { - // Dropping on the canvas styles the layer under the pointer's selection: the active layer. - let _ = pos; - run(app, "style.presets.apply", json!({"preset": k})); - } - _ => { - generic(app, "styles", "style.presets", &e, json!({"name": "Style"})); - } - } - } -} - -/// The Styles panel menu ("…"): Import Styles… / Export Selected Styles… / Export Styles… -/// (Photoshop layer style libraries, `.asl`). -fn styles_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let any = app.session.presets.styles.iter().any(|g| !g.items.is_empty()); - let selected = app.ui.presets_ui.selected.get("styles").cloned(); - let mut act: Option<&str> = None; - if ui.button(tl!("Import Styles…")).clicked() { - act = Some("import"); - } - if ui.add_enabled(selected.is_some(), egui::Button::new(tl!("Export Selected Styles…"))).clicked() { - act = Some("selected"); - } - if ui.add_enabled(any, egui::Button::new(tl!("Export Styles…"))).clicked() { - act = Some("all"); - } - let Some(a) = act else { return }; - ui.close(); - let r = match a { - "import" => app.pick_file_bytes_filtered(&["asl"], |app, name, bytes| match crate::preset_files_ui::open(app, &name, &bytes) { - Some(r) => r.map(|()| Value::Null), - None => Err(crate::i18n::fmt(tl!("{file} is not a style library (.asl)"), &[("file", &crate::file_open::display_name(&name))])), - }), - "selected" => match selected { - Some(name) => export_styles(app, json!({"styles": [name.clone()]}), &name), - None => Ok(Value::Null), - }, - _ => export_styles(app, json!({}), "Styles"), - }; - if let Err(e) = r - && e != "cancelled" - { - app.ui.status = e; - app.ui.status_error = true; - } -} - -/// Builds the `.asl` through `style.presets.exportAsl`, then asks where to save it. -fn export_styles(app: &mut PhotocraftApp, params: Value, suggested: &str) -> Result { - let r = app.run("style.presets.exportAsl", params)?; - let bytes = r["data"].as_str().and_then(photocraft_engine::paint::tile::b64_decode).ok_or("the export returned no data")?; - let n = r["count"].as_u64().unwrap_or(0); - let stem: String = suggested.chars().filter(|c| !matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')).collect(); - let stem = if stem.trim().is_empty() { "Styles".to_string() } else { stem.trim().to_string() }; - app.pick_save(&format!("{stem}.asl"), move |app, path| { - let write = app.services.write.as_mut().ok_or("no writer configured")?; - write(&path, &bytes)?; - app.ui.status_error = false; - app.ui.status = crate::i18n::fmt( - &crate::i18n::trn(crate::i18n::current(), n, "Exported {n} style to {file}", "Exported {n} styles to {file}"), - &[("file", &crate::file_open::display_name(&path))], - ); - Ok(json!({"path": path, "count": n})) - }) -} - -// ------------------------------------------------------------------ Shapes - -pub fn shapes_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let src = photocraft_engine::presets::shapes::all_groups(&app.session); - let groups: Vec = src - .iter() - .map(|g| GroupView { name: g.name.clone(), items: g.items.iter().map(|i| ItemView { key: i.name.clone(), name: i.name.clone() }).collect() }) - .collect(); - let canvas = canvas_drop_rect(app); - let mut st = std::mem::take(&mut app.ui.presets_ui); - let ctx = ui.ctx().clone(); - let t = Tokens::get(&ctx); - let events = browser( - ui, - &mut st, - "shapes", - &groups, - Place { canvas, max_h: 300.0, new_tip: tl!("Create new shape from the current path"), flush: false }, - &mut |ui, r, gi, ii| { - let tex = shape_texture(&ctx, &src[gi].items[ii]); - ui.painter().image(tex.id(), r.shrink(2.0), Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), t.text); - }, - ); - app.ui.presets_ui = st; - let fill = shape_fill(app); - for e in events { - match &e { - Ev::Select(k) => { - // Selecting a shape picks it for the Custom Shape tool (and switches to it). - app.ui.presets_ui.selected.insert("shapes".into(), k.clone()); - app.ui.presets_ui.custom_shape = k.clone(); - app.ui.tool = Tool::CustomShape; - } - Ev::Activate(k) => { - app.ui.presets_ui.custom_shape = k.clone(); - run(app, "shape.presets.place", json!({"preset": k, "fill": fill})); - } - Ev::Drop(k, pos) => { - app.ui.presets_ui.custom_shape = k.clone(); - let mut p = json!({"preset": k, "fill": fill}); - if let (Some(c), Some(d)) = (crate::canvas::doc_point_at(app, *pos), app.session.active()) { - let side = (d.doc.size.width.min(d.doc.size.height) as f64 * 0.3).max(8.0); - p["rect"] = json!([c[0] - side / 2.0, c[1] - side / 2.0, side, side]); - } - run(app, "shape.presets.place", p); - } - _ => { - generic(app, "shapes", "shape.presets", &e, json!({"name": "Shape"})); - } - } - } -} - -fn shape_fill(app: &PhotocraftApp) -> Value { - let f = app.session.tools.foreground; - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - if app.ui.tool_options.shape_fill { json!(format!("#{:02x}{:02x}{:02x}", q(f[0]), q(f[1]), q(f[2]))) } else { Value::Null } -} - -/// Options-bar shape picker for the Custom Shape tool. -pub fn shape_picker(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - ui.label(egui::RichText::new(tl!("Shape:")).color(t.text_dim).size(12.0)); - let groups = photocraft_engine::presets::shapes::all_groups(&app.session); - let cur = app.ui.presets_ui.shape().to_string(); - let ctx = ui.ctx().clone(); - let (r, resp) = ui.allocate_exact_size(vec2(36.0, 22.0), Sense::click()); - ui.painter().rect_filled(r, 3.0, t.field); - ui.painter().rect_stroke(r, 3.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); - if let Some(sh) = groups.iter().flat_map(|g| g.items.iter()).find(|s| s.name == cur) { - let tex = shape_texture(&ctx, sh); - ui.painter().image( - tex.id(), - Rect::from_center_size(r.center() - vec2(5.0, 0.0), vec2(18.0, 18.0)), - Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), - t.text, - ); - } - crate::icons::paint(ui, Rect::from_center_size(pos2(r.right() - 8.0, r.center().y), vec2(10.0, 10.0)), "chevron-down", 9.0, t.text_dim); - let resp = resp.on_hover_text(&cur); - egui::Popup::menu(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - ui.set_width(232.0); - egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { - for g in &groups { - ui.label(egui::RichText::new(&g.name).color(t.text_dim).size(11.0)); - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing = vec2(3.0, 3.0); - for sh in &g.items { - let (cr, cresp) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::click()); - let on = sh.name == cur; - ui.painter().rect_filled( - cr, - 2.0, - if on { - t.accent_soft - } else if cresp.hovered() { - t.hover - } else { - t.field - }, - ); - let tex = shape_texture(&ctx, sh); - ui.painter().image(tex.id(), cr.shrink(4.0), Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), t.text); - if cresp.on_hover_text(&sh.name).clicked() { - app.ui.presets_ui.custom_shape = sh.name.clone(); - ui.close(); - } - } - }); - } - }); - }); -} - -/// Custom Shape tool drag: places the selected shape in the dragged rect (⇧ keeps proportions). -pub fn finish_custom_shape(app: &mut PhotocraftApp, rect: [f64; 4], keep: bool, fill: Value, stroke: Value) { - let name = app.ui.presets_ui.shape().to_string(); - let r = run(app, "shape.presets.place", json!({"preset": name, "rect": rect, "keepAspect": keep, "fill": fill, "stroke": stroke})); - if r.is_none() && !photocraft_engine::presets::shapes::all_groups(&app.session).iter().any(|g| g.items.iter().any(|s| s.name == name)) { - let template = "No custom shape \"{name}\": pick one in the options bar or Window › Shapes"; - app.ui.status = crate::i18n::fmt(tl!(template), &[("name", &name)]); - } -} - -// ------------------------------------------------------------------ Tool Presets - -fn tool_id(t: Tool) -> String { - let s = format!("{t:?}"); - let mut c = s.chars(); - c.next().map(|f| f.to_ascii_lowercase().to_string() + c.as_str()).unwrap_or_default() -} - -/// Apply a tool preset: the engine sets the brush/colour, the shell switches tool and options. -pub fn select_tool_preset(app: &mut PhotocraftApp, name: &str) { - let before_ratio = crate::crop_ui::preset_ratio(app); - let Some(r) = run(app, "tool.presets.select", json!({"preset": name})) else { return }; - if let Some(tool) = r["tool"].as_str().and_then(Tool::from_name) { - crate::tool_memory::select(app, tool); - // Each tool keeps its own brush (#218), so switch it in before the preset's brush lands - // on it, and re-apply the brush the command just set for the old tool. - crate::paint_mouse::sync_tool_brush(app); - if let Some(b) = r["options"].get("brush").filter(|b| b.is_object()) { - let _ = app.run("tools.setBrush", json!({"brush": b})); - } - } - if let Some(o) = r["options"].get("toolOptions").and_then(Value::as_object) { - let mut cur = serde_json::to_value(&app.ui.tool_options).unwrap_or_default(); - if let Some(c) = cur.as_object_mut() { - for (k, v) in o { - // An object option (`sample_all`, one per tool) takes only the entries the - // preset stored, so the other tools' keep theirs (#5524). - match (c.get_mut(k), v) { - (Some(Value::Object(have)), Value::Object(set)) => have.extend(set.clone()), - _ => { - c.insert(k.clone(), v.clone()); - } - } - } - } - if let Ok(opts) = serde_json::from_value(cur) { - app.ui.tool_options = opts; - } - } - // As the options bar does: a crop preset's ratio (or W x H) fits the frame at once. - if crate::crop_ui::preset_ratio(app) != before_ratio { - crate::crop_ui::apply_ratio(app); - } -} - -/// The `tool.presets.new` params for the + button: `tool`'s own options only, so choosing the -/// preset later leaves the other tools' settings alone. -fn new_tool_preset_params(app: &PhotocraftApp, tool: Tool) -> Value { - let all = serde_json::to_value(&app.ui.tool_options).unwrap_or_default(); - let mut own: serde_json::Map = - crate::tool_reset::option_keys(tool).iter().filter_map(|k| Some(((*k).to_string(), all.get(*k)?.clone()))).collect(); - // Sample All Layers is each tool's own (#5524): store `tool`'s alone. - if let Some(k) = crate::tool_reset::sample_all_key(tool) - && let Some(v) = all.get("sample_all").and_then(|m| m.get(&k)) - { - own.insert("sample_all".into(), json!({ k: v })); - } - json!({"name": tool.label(), "tool": tool_id(tool), "options": {"toolOptions": own}}) -} - -pub fn tool_presets_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - let only = app.ui.presets_ui.current_tool_only; - let cur = app.ui.tool; - let items: Vec<(String, String)> = - app.session.presets.tool_presets.iter().filter(|p| !only || Tool::from_name(&p.tool) == Some(cur)).map(|p| (p.name.clone(), p.tool.clone())).collect(); - let selected = app.ui.presets_ui.selected.get("toolPresets").cloned(); - let mut action: Option<(String, Value)> = None; - let mut pick: Option = None; - // Rename field. - if let Some((_, key, mut text)) = app.ui.presets_ui.renaming.clone().filter(|r| r.0 == "toolPresets") { - ui.horizontal(|ui| { - let name_label = ui.label(egui::RichText::new(tl!("Name:")).color(t.text_dim).size(11.5)); - let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(ui.available_width() - 4.0)).labelled_by(name_label.id); - if !r.has_focus() && !r.lost_focus() { - r.request_focus(); - } - if r.lost_focus() { - app.ui.presets_ui.renaming = None; - if ui.input(|i| i.key_pressed(egui::Key::Enter)) && !text.trim().is_empty() { - action = Some(("tool.presets.edit".into(), json!({"action": "rename", "preset": key, "name": text.trim()}))); - } - } else { - app.ui.presets_ui.renaming = Some(("toolPresets".into(), key.clone(), text.clone())); - } - }); - } - egui::ScrollArea::vertical().id_salt("tool-presets").max_height(260.0).auto_shrink([false, true]).show(ui, |ui| { - ui.spacing_mut().item_spacing.y = 0.0; - if items.is_empty() { - empty(ui, if only { tl!("No presets for the current tool.") } else { tl!("No tool presets.") }); - } - for (name, tool) in &items { - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click()); - if selected.as_deref() == Some(name) { - ui.painter().rect_filled(r, 0.0, t.row_selected); - } else if resp.hovered() { - ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.5)); - } - let icon = Tool::from_name(tool).map(crate::icons::tool_icon).unwrap_or("settings"); - crate::icons::paint(ui, Rect::from_center_size(pos2(r.left() + 14.0, r.center().y), vec2(16.0, 16.0)), icon, 13.0, t.icon); - ui.painter().text(pos2(r.left() + 30.0, r.center().y), Align2::LEFT_CENTER, name, FontId::proportional(11.5), t.text); - if resp.clicked() { - pick = Some(name.clone()); - } - resp.context_menu(|ui| { - if ui.button(tl!("Rename Tool Preset…")).clicked() { - app.ui.presets_ui.renaming = Some(("toolPresets".into(), name.clone(), name.clone())); - ui.close(); - } - if ui.button(tl!("Delete Tool Preset")).clicked() { - action = Some(("tool.presets.edit".into(), json!({"action": "delete", "preset": name}))); - ui.close(); - } - }); - } - }); - ui.add_space(4.0); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - crate::widgets::checkbox(ui, &mut app.ui.presets_ui.current_tool_only, tl!("Current Tool Only")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::icons::button(ui, "trash", 24.0, false, tl!("Delete tool preset")).clicked() - && let Some(n) = selected.clone() - { - action = Some(("tool.presets.edit".into(), json!({"action": "delete", "preset": n}))); - } - if crate::icons::button(ui, "plus", 24.0, false, tl!("Create new tool preset")).clicked() { - action = Some(("tool.presets.new".into(), new_tool_preset_params(app, cur))); - } - }); - }); - if let Some(n) = pick { - app.ui.presets_ui.selected.insert("toolPresets".into(), n.clone()); - select_tool_preset(app, &n); - } - if let Some((cmd, p)) = action { - let created = cmd == "tool.presets.new"; - if let Some(r) = run(app, &cmd, p) - && created - { - let n = r["name"].as_str().unwrap_or_default().to_string(); - app.ui.presets_ui.selected.insert("toolPresets".into(), n.clone()); - app.ui.presets_ui.renaming = Some(("toolPresets".into(), n.clone(), n)); - } - } -} - -// ------------------------------------------------------------------ Clone Source - -pub fn clone_source_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - let cs = app.session.presets.clone.clone(); - let slot = cs.active().clone(); - let mut action: Option = None; - // The five source buttons. - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - for i in 0..photocraft_engine::presets::clone_source::SLOTS { - let set = cs.slots[i].source.is_some(); - let tip = match cs.slots[i].source { - Some(s) => format!("Clone source {}: {:.0}, {:.0}", i + 1, s[0], s[1]), - None => crate::i18n::fmt( - tl!("Clone source {n} ({key}-click with Clone Stamp to set)"), - &[("n", &(i + 1).to_string()), ("key", &crate::shortcuts::pretty("Alt"))], - ), - }; - let r = crate::icons::button(ui, "stamp", 30.0, cs.active == i, &tip); - if set { - let d = r.rect.right_bottom() - vec2(6.0, 6.0); - ui.painter().circle_filled(d, 2.5, t.accent); - } - if r.clicked() { - run(app, "cloneSource.select", json!({"index": i})); - } - } - }); - ui.add_space(4.0); - let src_line = - match (slot.source, slot.layer.and_then(|l| app.session.active().and_then(|d| d.doc.layer(photocraft_doc::LayerId(l)).map(|x| x.name.clone())))) { - (Some(_), Some(l)) => format!("Source: {} : {l}", app.session.active().map(|d| d.doc.name.clone()).unwrap_or_default()), - (Some(_), None) => "Source: set".to_string(), - _ => crate::i18n::fmt(tl!("Source: not set ({key}-click with Clone Stamp)"), &[("key", &crate::shortcuts::pretty("Alt"))]), - }; - ui.label(egui::RichText::new(src_line).color(t.text_dim).size(11.0)); - ui.add_space(4.0); - let lbl = |ui: &mut egui::Ui, s: &str| { - let label = ui.add_sized(vec2(18.0, 18.0), egui::Label::new(egui::RichText::new(s).color(t.text_dim).size(11.5))); - crate::widgets::scrub_option_label(ui, &label); - }; - let off = slot.offset().unwrap_or([0.0, 0.0]); - let (mut ox, mut oy) = (off[0] as f32, off[1] as f32); - let (mut w, mut h) = (slot.scale[0] as f32, slot.scale[1] as f32); - let mut rot = slot.rotation as f32; - egui::Grid::new("clone-src-grid").num_columns(5).spacing(vec2(6.0, 4.0)).show(ui, |ui| { - lbl(ui, "X:"); - if crate::widgets::value_field(ui, &mut ox, -30000.0..=30000.0, "px", 72.0).changed() && slot.source.is_some() { - action = Some(json!({"offset": [ox, oy]})); - } - lbl(ui, "W:"); - if crate::widgets::value_field(ui, &mut w, -1000.0..=1000.0, "%", 64.0).changed() { - action = Some(json!({"width": w})); - } - // The W/H chain: with it on, a new W or H scales the other by the same factor. - let icon = if slot.linked { "link" } else { "unlink" }; - if crate::icons::button(ui, icon, 22.0, slot.linked, tl!("Maintain aspect ratio")).clicked() { - action = Some(json!({"linked": !slot.linked})); - } - ui.end_row(); - lbl(ui, "Y:"); - if crate::widgets::value_field(ui, &mut oy, -30000.0..=30000.0, "px", 72.0).changed() && slot.source.is_some() { - action = Some(json!({"offset": [ox, oy]})); - } - lbl(ui, "H:"); - if crate::widgets::value_field(ui, &mut h, -1000.0..=1000.0, "%", 64.0).changed() { - action = Some(json!({"height": h})); - } - ui.end_row(); - lbl(ui, "A:"); - if crate::widgets::value_field(ui, &mut rot, -180.0..=180.0, "°", 72.0).changed() { - action = Some(json!({"rotation": rot})); - } - ui.horizontal(|ui| { - if crate::icons::button(ui, "arrow-left-right", 22.0, slot.flip_h, tl!("Flip Horizontal")).clicked() { - action = Some(json!({"flipH": !slot.flip_h})); - } - if crate::icons::button(ui, "rotate-cw", 22.0, false, tl!("Reset Transform")).clicked() { - run(app, "cloneSource.resetTransform", json!({})); - } - }); - ui.horizontal(|ui| { - if crate::icons::button(ui, "scaling", 22.0, slot.flip_v, tl!("Flip Vertical")).clicked() { - action = Some(json!({"flipV": !slot.flip_v})); - } - }); - ui.end_row(); - }); - if let Some(p) = action { - run(app, "cloneSource.set", p); - } - ui.add_space(6.0); - crate::widgets::hairline(ui); - ui.add_space(4.0); - // Overlay options. - let mut o = cs.overlay.clone(); - let before = o.clone(); - crate::widgets::checkbox(ui, &mut o.show, tl!("Show Overlay")); - ui.horizontal(|ui| { - ui.add_space(18.0); - ui.label(egui::RichText::new(tl!("Opacity:")).color(t.text_dim).size(11.5)); - crate::widgets::value_field(ui, &mut o.opacity, 0.0..=100.0, "%", 56.0).accessible_name(tl!("Opacity:")); - let opts = [ - ("normal".to_string(), tl!("Normal")), - ("darken".to_string(), tl!("Darken")), - ("lighten".to_string(), tl!("Lighten")), - ("difference".to_string(), tl!("Difference")), - ]; - crate::widgets::dropdown(ui, "clone-overlay-mode", tl!("Blend Mode"), &mut o.blend, &opts, 90.0); - }); - ui.horizontal(|ui| { - ui.add_space(18.0); - crate::widgets::checkbox(ui, &mut o.clipped, tl!("Clipped")); - crate::widgets::checkbox(ui, &mut o.auto_hide, tl!("Auto Hide")); - crate::widgets::checkbox(ui, &mut o.invert, tl!("Invert")); - }); - if o != before { - run( - app, - "cloneSource.overlay", - json!({"show": o.show, "opacity": o.opacity, "clipped": o.clipped, "autoHide": o.auto_hide, "invert": o.invert, "blend": o.blend}), - ); - } -} - -/// Where the active clone source samples for document point `at` (for the canvas marker). -/// The first stroke anchors at its press, so the marker follows before the stroke commits. -pub fn clone_sample_point(app: &PhotocraftApp, at: Option<[f64; 2]>) -> Option<[f64; 2]> { - use photocraft_engine::presets::clone_source::{Mapping, transform_matrix}; - let s = app.session.presets.clone.active(); - let src = s.source?; - let stroking = app.drag.as_ref().filter(|d| matches!(d.tool, Tool::CloneStamp | Tool::Healing)).map(|d| d.start); - let anchor = if app.ui.tool_options.clone_aligned { s.anchor.or(stroking) } else { stroking }; - match (anchor, at) { - (Some(a), Some(h)) => { - let m = Mapping { source: (src[0], src[1]), anchor: (a[0], a[1]), m: transform_matrix(s.scale, s.rotation, s.flip_h, s.flip_v) }; - let (x, y) = m.map(h[0], h[1]); - Some([x, y]) - } - _ => Some(src), - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/preset_panels/panels.rs b/crates/ui-egui/src/preset_panels/panels.rs new file mode 100644 index 0000000000..27a441fa5f --- /dev/null +++ b/crates/ui-egui/src/preset_panels/panels.rs @@ -0,0 +1,685 @@ +use super::*; + +// ------------------------------------------------------------------ Gradients + +pub fn gradients_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); + let groups_src = app.session.presets.gradients.clone(); + // Current gradient (what the Gradient tool paints), like the panel's top "recent" row. + let cur = app.session.presets.gradient.clone(); + let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 18.0), Sense::hover()); + paint_gradient(ui, r, &cur.resolve(fg, bg)); + ui.painter().rect_stroke(r, 2.0, Stroke::new(1.0, Tokens::get(ui.ctx()).card_border), egui::StrokeKind::Inside); + ui.add_space(4.0); + let groups: Vec = groups_src + .iter() + .map(|g| GroupView { name: g.name.clone(), items: g.items.iter().map(|i| ItemView { key: i.name.clone(), name: i.name.clone() }).collect() }) + .collect(); + let canvas = canvas_drop_rect(app); + let mut st = std::mem::take(&mut app.ui.presets_ui); + let max_h = (ui.available_height() - 40.0).clamp(90.0, 260.0); + let events = + browser(ui, &mut st, "gradients", &groups, Place { canvas, max_h, new_tip: tl!("Create new gradient"), flush: false }, &mut |ui, r, gi, ii| { + let stops = groups_src[gi].items[ii].resolve(fg, bg); + paint_gradient(ui, r, &stops); + }); + app.ui.presets_ui = st; + for e in events { + match &e { + Ev::Select(k) => { + app.ui.presets_ui.selected.insert("gradients".into(), k.clone()); + run(app, "gradient.presets.select", json!({"preset": k})); + } + Ev::Activate(k) | Ev::Drop(k, _) => { + app.ui.presets_ui.selected.insert("gradients".into(), k.clone()); + run(app, "gradient.presets.apply", json!({"preset": k})); + } + _ => { + generic(app, "gradients", "gradient.presets", &e, json!({"name": "Custom"})); + } + } + } +} + +// ------------------------------------------------------------------ Patterns + +pub fn patterns_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + photocraft_engine::presets::patterns::sync(&mut app.session); + let lib = app.session.patterns.items.clone(); + let groups: Vec = app + .session + .presets + .pattern_groups + .iter() + .map(|g| GroupView { + name: g.name.clone(), + items: g + .items + .iter() + .filter_map(|id| lib.iter().find(|p| &p.id == id)) + .map(|p| ItemView { key: p.id.clone(), name: p.display_name().to_string() }) + .collect(), + }) + .collect(); + let pats: Vec> = + app.session.presets.pattern_groups.iter().map(|g| g.items.iter().filter_map(|id| lib.iter().find(|p| &p.id == id).cloned()).collect()).collect(); + let canvas = canvas_drop_rect(app); + let mut st = std::mem::take(&mut app.ui.presets_ui); + let max_h = (ui.available_height() - 40.0).clamp(90.0, 280.0); + let ctx = ui.ctx().clone(); + let events = browser( + ui, + &mut st, + "patterns", + &groups, + Place { canvas, max_h, new_tip: tl!("Create new pattern from the selection"), flush: false }, + &mut |ui, r, gi, ii| { + let tex = pattern_texture(&ctx, &pats[gi][ii]); + ui.painter().image(tex.id(), r, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE); + }, + ); + app.ui.presets_ui = st; + for e in events { + match &e { + Ev::Select(k) => { + app.ui.presets_ui.selected.insert("patterns".into(), k.clone()); + run(app, "pattern.presets.select", json!({"pattern": k})); + } + Ev::Activate(k) | Ev::Drop(k, _) => { + app.ui.presets_ui.selected.insert("patterns".into(), k.clone()); + run(app, "pattern.presets.apply", json!({"pattern": k})); + } + _ => { + generic(app, "patterns", "pattern.presets", &e, json!({})); + } + } + } +} + +// ------------------------------------------------------------------ floating panels + +fn float_window( + app: &mut PhotocraftApp, + ctx: &egui::Context, + key: &str, + title: &str, + width: f32, + offset: f32, + body: impl FnOnce(&mut PhotocraftApp, &mut egui::Ui), +) -> bool { + let t = Tokens::get(ctx); + let frame = egui::Frame::NONE + .fill(t.card) + .stroke(Stroke::new(1.0, t.card_border)) + .corner_radius(CornerRadius::same(t.radius_lg as u8)) + .shadow(egui::Shadow { offset: [0, 10], blur: 30, spread: 0, color: t.shadow }) + .inner_margin(egui::Margin::same(8)); + let canvas = canvas_drop_rect(app); + let mut close = false; + egui::Window::new(title) + .id(egui::Id::unique(("preset-window", key))) + .title_bar(false) + .resizable(false) + .frame(frame) + .default_pos(pos2((canvas.right() - width - 16.0 - offset).max(canvas.left() + 8.0), canvas.top() + 40.0)) + .show(ctx, |ui| { + ui.set_width(width); + // Photoshop-style tab header with a close box. + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!(&title)).color(t.text).size(12.0).strong()); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::icons::button(ui, "x", 20.0, false, tl!("Close")).clicked() { + close = true; + } + if key == "styles" { + let resp = crate::icons::button(ui, "ellipsis", 20.0, false, tl!("Panel menu")); + egui::Popup::menu(&resp).show(|ui| { + crate::widgets::style_spectrum_popup_menu(ui); + ui.set_min_width(180.0); + styles_menu(app, ui); + }); + } + }); + }); + crate::widgets::hairline(ui); + ui.add_space(4.0); + body(app, ui); + }); + close +} + +/// Draws the open floating panels (Styles, Shapes, Tool Presets, Clone Source). +pub fn windows(app: &mut PhotocraftApp, ctx: &egui::Context) { + let p = app.ui.presets_ui.clone(); + if p.styles && float_window(app, ctx, "styles", tl!("Styles"), 250.0, 0.0, styles_panel) { + app.ui.presets_ui.styles = false; + } + if p.shapes && float_window(app, ctx, "shapes", tl!("Shapes"), 250.0, 280.0, shapes_panel) { + app.ui.presets_ui.shapes = false; + } + if p.tool_presets && float_window(app, ctx, "toolPresets", tl!("Tool Presets"), 250.0, 560.0, tool_presets_panel) { + app.ui.presets_ui.tool_presets = false; + } + if p.clone_source && float_window(app, ctx, "cloneSource", tl!("Clone Source"), 270.0, 840.0, clone_source_panel) { + app.ui.presets_ui.clone_source = false; + } +} + +// ------------------------------------------------------------------ Styles + +pub fn styles_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let src = app.session.presets.styles.clone(); + let groups: Vec = src + .iter() + .map(|g| GroupView { name: g.name.clone(), items: g.items.iter().map(|i| ItemView { key: i.name.clone(), name: i.name.clone() }).collect() }) + .collect(); + let canvas = canvas_drop_rect(app); + let mut st = std::mem::take(&mut app.ui.presets_ui); + let ctx = ui.ctx().clone(); + let t = Tokens::get(&ctx); + let mut texes: Vec> = Vec::new(); + for g in &src { + texes.push(g.items.iter().map(|s| style_texture(app, &ctx, s)).collect()); + } + let events = browser( + ui, + &mut st, + "styles", + &groups, + Place { canvas, max_h: 300.0, new_tip: tl!("Create new style from the selected layer"), flush: false }, + &mut |ui, r, gi, ii| { + ui.painter().rect_filled(r, 2.0, t.field); + ui.painter().image(texes[gi][ii].id(), r, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE); + }, + ); + app.ui.presets_ui = st; + let shift = ui.input(|i| i.modifiers.shift); + for e in events { + match &e { + Ev::Select(k) | Ev::Activate(k) => { + app.ui.presets_ui.selected.insert("styles".into(), k.clone()); + // Clicking applies to the selected layers (⇧ adds to their effects). + run(app, "style.presets.apply", json!({"preset": k, "add": shift})); + } + Ev::Drop(k, pos) => { + // Dropping on the canvas styles the layer under the pointer's selection: the active layer. + let _ = pos; + run(app, "style.presets.apply", json!({"preset": k})); + } + _ => { + generic(app, "styles", "style.presets", &e, json!({"name": "Style"})); + } + } + } +} + +/// The Styles panel menu ("…"): Import Styles… / Export Selected Styles… / Export Styles… +/// (Photoshop layer style libraries, `.asl`). +fn styles_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let any = app.session.presets.styles.iter().any(|g| !g.items.is_empty()); + let selected = app.ui.presets_ui.selected.get("styles").cloned(); + let mut act: Option<&str> = None; + if ui.button(tl!("Import Styles…")).clicked() { + act = Some("import"); + } + if ui.add_enabled(selected.is_some(), egui::Button::new(tl!("Export Selected Styles…"))).clicked() { + act = Some("selected"); + } + if ui.add_enabled(any, egui::Button::new(tl!("Export Styles…"))).clicked() { + act = Some("all"); + } + let Some(a) = act else { return }; + ui.close(); + let r = match a { + "import" => app.pick_file_bytes_filtered(&["asl"], |app, name, bytes| match crate::preset_files_ui::open(app, &name, &bytes) { + Some(r) => r.map(|()| Value::Null), + None => Err(crate::i18n::fmt(tl!("{file} is not a style library (.asl)"), &[("file", &crate::file_open::display_name(&name))])), + }), + "selected" => match selected { + Some(name) => export_styles(app, json!({"styles": [name.clone()]}), &name), + None => Ok(Value::Null), + }, + _ => export_styles(app, json!({}), "Styles"), + }; + if let Err(e) = r + && e != "cancelled" + { + app.ui.status = e; + app.ui.status_error = true; + } +} + +/// Builds the `.asl` through `style.presets.exportAsl`, then asks where to save it. +fn export_styles(app: &mut PhotocraftApp, params: Value, suggested: &str) -> Result { + let r = app.run("style.presets.exportAsl", params)?; + let bytes = r["data"].as_str().and_then(photocraft_engine::paint::tile::b64_decode).ok_or("the export returned no data")?; + let n = r["count"].as_u64().unwrap_or(0); + let stem: String = suggested.chars().filter(|c| !matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')).collect(); + let stem = if stem.trim().is_empty() { "Styles".to_string() } else { stem.trim().to_string() }; + app.pick_save(&format!("{stem}.asl"), move |app, path| { + let write = app.services.write.as_mut().ok_or("no writer configured")?; + write(&path, &bytes)?; + app.ui.status_error = false; + app.ui.status = crate::i18n::fmt( + &crate::i18n::trn(crate::i18n::current(), n, "Exported {n} style to {file}", "Exported {n} styles to {file}"), + &[("file", &crate::file_open::display_name(&path))], + ); + Ok(json!({"path": path, "count": n})) + }) +} + +// ------------------------------------------------------------------ Shapes + +pub fn shapes_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let src = photocraft_engine::presets::shapes::all_groups(&app.session); + let groups: Vec = src + .iter() + .map(|g| GroupView { name: g.name.clone(), items: g.items.iter().map(|i| ItemView { key: i.name.clone(), name: i.name.clone() }).collect() }) + .collect(); + let canvas = canvas_drop_rect(app); + let mut st = std::mem::take(&mut app.ui.presets_ui); + let ctx = ui.ctx().clone(); + let t = Tokens::get(&ctx); + let events = browser( + ui, + &mut st, + "shapes", + &groups, + Place { canvas, max_h: 300.0, new_tip: tl!("Create new shape from the current path"), flush: false }, + &mut |ui, r, gi, ii| { + let tex = shape_texture(&ctx, &src[gi].items[ii]); + ui.painter().image(tex.id(), r.shrink(2.0), Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), t.text); + }, + ); + app.ui.presets_ui = st; + let fill = shape_fill(app); + for e in events { + match &e { + Ev::Select(k) => { + // Selecting a shape picks it for the Custom Shape tool (and switches to it). + app.ui.presets_ui.selected.insert("shapes".into(), k.clone()); + app.ui.presets_ui.custom_shape = k.clone(); + app.ui.tool = Tool::CustomShape; + } + Ev::Activate(k) => { + app.ui.presets_ui.custom_shape = k.clone(); + run(app, "shape.presets.place", json!({"preset": k, "fill": fill})); + } + Ev::Drop(k, pos) => { + app.ui.presets_ui.custom_shape = k.clone(); + let mut p = json!({"preset": k, "fill": fill}); + if let (Some(c), Some(d)) = (crate::canvas::doc_point_at(app, *pos), app.session.active()) { + let side = (d.doc.size.width.min(d.doc.size.height) as f64 * 0.3).max(8.0); + p["rect"] = json!([c[0] - side / 2.0, c[1] - side / 2.0, side, side]); + } + run(app, "shape.presets.place", p); + } + _ => { + generic(app, "shapes", "shape.presets", &e, json!({"name": "Shape"})); + } + } + } +} + +fn shape_fill(app: &PhotocraftApp) -> Value { + let f = app.session.tools.foreground; + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + if app.ui.tool_options.shape_fill { json!(format!("#{:02x}{:02x}{:02x}", q(f[0]), q(f[1]), q(f[2]))) } else { Value::Null } +} + +/// Options-bar shape picker for the Custom Shape tool. +pub fn shape_picker(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + ui.label(egui::RichText::new(tl!("Shape:")).color(t.text_dim).size(12.0)); + let groups = photocraft_engine::presets::shapes::all_groups(&app.session); + let cur = app.ui.presets_ui.shape().to_string(); + let ctx = ui.ctx().clone(); + let (r, resp) = ui.allocate_exact_size(vec2(36.0, 22.0), Sense::click()); + ui.painter().rect_filled(r, 3.0, t.field); + ui.painter().rect_stroke(r, 3.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); + if let Some(sh) = groups.iter().flat_map(|g| g.items.iter()).find(|s| s.name == cur) { + let tex = shape_texture(&ctx, sh); + ui.painter().image( + tex.id(), + Rect::from_center_size(r.center() - vec2(5.0, 0.0), vec2(18.0, 18.0)), + Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), + t.text, + ); + } + crate::icons::paint(ui, Rect::from_center_size(pos2(r.right() - 8.0, r.center().y), vec2(10.0, 10.0)), "chevron-down", 9.0, t.text_dim); + let resp = resp.on_hover_text(&cur); + egui::Popup::menu(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.set_width(232.0); + egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { + for g in &groups { + ui.label(egui::RichText::new(&g.name).color(t.text_dim).size(11.0)); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(3.0, 3.0); + for sh in &g.items { + let (cr, cresp) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::click()); + let on = sh.name == cur; + ui.painter().rect_filled( + cr, + 2.0, + if on { + t.accent_soft + } else if cresp.hovered() { + t.hover + } else { + t.field + }, + ); + let tex = shape_texture(&ctx, sh); + ui.painter().image(tex.id(), cr.shrink(4.0), Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), t.text); + if cresp.on_hover_text(&sh.name).clicked() { + app.ui.presets_ui.custom_shape = sh.name.clone(); + ui.close(); + } + } + }); + } + }); + }); +} + +/// Custom Shape tool drag: places the selected shape in the dragged rect (⇧ keeps proportions). +pub fn finish_custom_shape(app: &mut PhotocraftApp, rect: [f64; 4], keep: bool, fill: Value, stroke: Value) { + let name = app.ui.presets_ui.shape().to_string(); + let r = run(app, "shape.presets.place", json!({"preset": name, "rect": rect, "keepAspect": keep, "fill": fill, "stroke": stroke})); + if r.is_none() && !photocraft_engine::presets::shapes::all_groups(&app.session).iter().any(|g| g.items.iter().any(|s| s.name == name)) { + let template = "No custom shape \"{name}\": pick one in the options bar or Window › Shapes"; + app.ui.status = crate::i18n::fmt(tl!(template), &[("name", &name)]); + } +} + +// ------------------------------------------------------------------ Tool Presets + +pub(super) fn tool_id(t: Tool) -> String { + let s = format!("{t:?}"); + let mut c = s.chars(); + c.next().map(|f| f.to_ascii_lowercase().to_string() + c.as_str()).unwrap_or_default() +} + +/// Apply a tool preset: the engine sets the brush/colour, the shell switches tool and options. +pub fn select_tool_preset(app: &mut PhotocraftApp, name: &str) { + let before_ratio = crate::crop_ui::preset_ratio(app); + let Some(r) = run(app, "tool.presets.select", json!({"preset": name})) else { return }; + if let Some(tool) = r["tool"].as_str().and_then(Tool::from_name) { + crate::tool_memory::select(app, tool); + // Each tool keeps its own brush (#218), so switch it in before the preset's brush lands + // on it, and re-apply the brush the command just set for the old tool. + crate::paint_mouse::sync_tool_brush(app); + if let Some(b) = r["options"].get("brush").filter(|b| b.is_object()) { + let _ = app.run("tools.setBrush", json!({"brush": b})); + } + } + if let Some(o) = r["options"].get("toolOptions").and_then(Value::as_object) { + let mut cur = serde_json::to_value(&app.ui.tool_options).unwrap_or_default(); + if let Some(c) = cur.as_object_mut() { + for (k, v) in o { + // An object option (`sample_all`, one per tool) takes only the entries the + // preset stored, so the other tools' keep theirs (#5524). + match (c.get_mut(k), v) { + (Some(Value::Object(have)), Value::Object(set)) => have.extend(set.clone()), + _ => { + c.insert(k.clone(), v.clone()); + } + } + } + } + if let Ok(opts) = serde_json::from_value(cur) { + app.ui.tool_options = opts; + } + } + // As the options bar does: a crop preset's ratio (or W x H) fits the frame at once. + if crate::crop_ui::preset_ratio(app) != before_ratio { + crate::crop_ui::apply_ratio(app); + } +} + +/// The `tool.presets.new` params for the + button: `tool`'s own options only, so choosing the +/// preset later leaves the other tools' settings alone. +pub(super) fn new_tool_preset_params(app: &PhotocraftApp, tool: Tool) -> Value { + let all = serde_json::to_value(&app.ui.tool_options).unwrap_or_default(); + let mut own: serde_json::Map = + crate::tool_reset::option_keys(tool).iter().filter_map(|k| Some(((*k).to_string(), all.get(*k)?.clone()))).collect(); + // Sample All Layers is each tool's own (#5524): store `tool`'s alone. + if let Some(k) = crate::tool_reset::sample_all_key(tool) + && let Some(v) = all.get("sample_all").and_then(|m| m.get(&k)) + { + own.insert("sample_all".into(), json!({ k: v })); + } + json!({"name": tool.label(), "tool": tool_id(tool), "options": {"toolOptions": own}}) +} + +pub fn tool_presets_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + let only = app.ui.presets_ui.current_tool_only; + let cur = app.ui.tool; + let items: Vec<(String, String)> = + app.session.presets.tool_presets.iter().filter(|p| !only || Tool::from_name(&p.tool) == Some(cur)).map(|p| (p.name.clone(), p.tool.clone())).collect(); + let selected = app.ui.presets_ui.selected.get("toolPresets").cloned(); + let mut action: Option<(String, Value)> = None; + let mut pick: Option = None; + // Rename field. + if let Some((_, key, mut text)) = app.ui.presets_ui.renaming.clone().filter(|r| r.0 == "toolPresets") { + ui.horizontal(|ui| { + let name_label = ui.label(egui::RichText::new(tl!("Name:")).color(t.text_dim).size(11.5)); + let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(ui.available_width() - 4.0)).labelled_by(name_label.id); + if !r.has_focus() && !r.lost_focus() { + r.request_focus(); + } + if r.lost_focus() { + app.ui.presets_ui.renaming = None; + if ui.input(|i| i.key_pressed(egui::Key::Enter)) && !text.trim().is_empty() { + action = Some(("tool.presets.edit".into(), json!({"action": "rename", "preset": key, "name": text.trim()}))); + } + } else { + app.ui.presets_ui.renaming = Some(("toolPresets".into(), key.clone(), text.clone())); + } + }); + } + egui::ScrollArea::vertical().id_salt("tool-presets").max_height(260.0).auto_shrink([false, true]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + if items.is_empty() { + empty(ui, if only { tl!("No presets for the current tool.") } else { tl!("No tool presets.") }); + } + for (name, tool) in &items { + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click()); + if selected.as_deref() == Some(name) { + ui.painter().rect_filled(r, 0.0, t.row_selected); + } else if resp.hovered() { + ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.5)); + } + let icon = Tool::from_name(tool).map(crate::icons::tool_icon).unwrap_or("settings"); + crate::icons::paint(ui, Rect::from_center_size(pos2(r.left() + 14.0, r.center().y), vec2(16.0, 16.0)), icon, 13.0, t.icon); + ui.painter().text(pos2(r.left() + 30.0, r.center().y), Align2::LEFT_CENTER, name, FontId::proportional(11.5), t.text); + if resp.clicked() { + pick = Some(name.clone()); + } + resp.context_menu(|ui| { + if ui.button(tl!("Rename Tool Preset…")).clicked() { + app.ui.presets_ui.renaming = Some(("toolPresets".into(), name.clone(), name.clone())); + ui.close(); + } + if ui.button(tl!("Delete Tool Preset")).clicked() { + action = Some(("tool.presets.edit".into(), json!({"action": "delete", "preset": name}))); + ui.close(); + } + }); + } + }); + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + crate::widgets::checkbox(ui, &mut app.ui.presets_ui.current_tool_only, tl!("Current Tool Only")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::icons::button(ui, "trash", 24.0, false, tl!("Delete tool preset")).clicked() + && let Some(n) = selected.clone() + { + action = Some(("tool.presets.edit".into(), json!({"action": "delete", "preset": n}))); + } + if crate::icons::button(ui, "plus", 24.0, false, tl!("Create new tool preset")).clicked() { + action = Some(("tool.presets.new".into(), new_tool_preset_params(app, cur))); + } + }); + }); + if let Some(n) = pick { + app.ui.presets_ui.selected.insert("toolPresets".into(), n.clone()); + select_tool_preset(app, &n); + } + if let Some((cmd, p)) = action { + let created = cmd == "tool.presets.new"; + if let Some(r) = run(app, &cmd, p) + && created + { + let n = r["name"].as_str().unwrap_or_default().to_string(); + app.ui.presets_ui.selected.insert("toolPresets".into(), n.clone()); + app.ui.presets_ui.renaming = Some(("toolPresets".into(), n.clone(), n)); + } + } +} + +// ------------------------------------------------------------------ Clone Source + +pub fn clone_source_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + let cs = app.session.presets.clone.clone(); + let slot = cs.active().clone(); + let mut action: Option = None; + // The five source buttons. + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + for i in 0..photocraft_engine::presets::clone_source::SLOTS { + let set = cs.slots[i].source.is_some(); + let tip = match cs.slots[i].source { + Some(s) => format!("Clone source {}: {:.0}, {:.0}", i + 1, s[0], s[1]), + None => crate::i18n::fmt( + tl!("Clone source {n} ({key}-click with Clone Stamp to set)"), + &[("n", &(i + 1).to_string()), ("key", &crate::shortcuts::pretty("Alt"))], + ), + }; + let r = crate::icons::button(ui, "stamp", 30.0, cs.active == i, &tip); + if set { + let d = r.rect.right_bottom() - vec2(6.0, 6.0); + ui.painter().circle_filled(d, 2.5, t.accent); + } + if r.clicked() { + run(app, "cloneSource.select", json!({"index": i})); + } + } + }); + ui.add_space(4.0); + let src_line = + match (slot.source, slot.layer.and_then(|l| app.session.active().and_then(|d| d.doc.layer(photocraft_doc::LayerId(l)).map(|x| x.name.clone())))) { + (Some(_), Some(l)) => format!("Source: {} : {l}", app.session.active().map(|d| d.doc.name.clone()).unwrap_or_default()), + (Some(_), None) => "Source: set".to_string(), + _ => crate::i18n::fmt(tl!("Source: not set ({key}-click with Clone Stamp)"), &[("key", &crate::shortcuts::pretty("Alt"))]), + }; + ui.label(egui::RichText::new(src_line).color(t.text_dim).size(11.0)); + ui.add_space(4.0); + let lbl = |ui: &mut egui::Ui, s: &str| { + let label = ui.add_sized(vec2(18.0, 18.0), egui::Label::new(egui::RichText::new(s).color(t.text_dim).size(11.5))); + crate::widgets::scrub_option_label(ui, &label); + }; + let off = slot.offset().unwrap_or([0.0, 0.0]); + let (mut ox, mut oy) = (off[0] as f32, off[1] as f32); + let (mut w, mut h) = (slot.scale[0] as f32, slot.scale[1] as f32); + let mut rot = slot.rotation as f32; + egui::Grid::new("clone-src-grid").num_columns(5).spacing(vec2(6.0, 4.0)).show(ui, |ui| { + lbl(ui, "X:"); + if crate::widgets::value_field(ui, &mut ox, -30000.0..=30000.0, "px", 72.0).changed() && slot.source.is_some() { + action = Some(json!({"offset": [ox, oy]})); + } + lbl(ui, "W:"); + if crate::widgets::value_field(ui, &mut w, -1000.0..=1000.0, "%", 64.0).changed() { + action = Some(json!({"width": w})); + } + // The W/H chain: with it on, a new W or H scales the other by the same factor. + let icon = if slot.linked { "link" } else { "unlink" }; + if crate::icons::button(ui, icon, 22.0, slot.linked, tl!("Maintain aspect ratio")).clicked() { + action = Some(json!({"linked": !slot.linked})); + } + ui.end_row(); + lbl(ui, "Y:"); + if crate::widgets::value_field(ui, &mut oy, -30000.0..=30000.0, "px", 72.0).changed() && slot.source.is_some() { + action = Some(json!({"offset": [ox, oy]})); + } + lbl(ui, "H:"); + if crate::widgets::value_field(ui, &mut h, -1000.0..=1000.0, "%", 64.0).changed() { + action = Some(json!({"height": h})); + } + ui.end_row(); + lbl(ui, "A:"); + if crate::widgets::value_field(ui, &mut rot, -180.0..=180.0, "°", 72.0).changed() { + action = Some(json!({"rotation": rot})); + } + ui.horizontal(|ui| { + if crate::icons::button(ui, "arrow-left-right", 22.0, slot.flip_h, tl!("Flip Horizontal")).clicked() { + action = Some(json!({"flipH": !slot.flip_h})); + } + if crate::icons::button(ui, "rotate-cw", 22.0, false, tl!("Reset Transform")).clicked() { + run(app, "cloneSource.resetTransform", json!({})); + } + }); + ui.horizontal(|ui| { + if crate::icons::button(ui, "scaling", 22.0, slot.flip_v, tl!("Flip Vertical")).clicked() { + action = Some(json!({"flipV": !slot.flip_v})); + } + }); + ui.end_row(); + }); + if let Some(p) = action { + run(app, "cloneSource.set", p); + } + ui.add_space(6.0); + crate::widgets::hairline(ui); + ui.add_space(4.0); + // Overlay options. + let mut o = cs.overlay.clone(); + let before = o.clone(); + crate::widgets::checkbox(ui, &mut o.show, tl!("Show Overlay")); + ui.horizontal(|ui| { + ui.add_space(18.0); + ui.label(egui::RichText::new(tl!("Opacity:")).color(t.text_dim).size(11.5)); + crate::widgets::value_field(ui, &mut o.opacity, 0.0..=100.0, "%", 56.0).accessible_name(tl!("Opacity:")); + let opts = [ + ("normal".to_string(), tl!("Normal")), + ("darken".to_string(), tl!("Darken")), + ("lighten".to_string(), tl!("Lighten")), + ("difference".to_string(), tl!("Difference")), + ]; + crate::widgets::dropdown(ui, "clone-overlay-mode", tl!("Blend Mode"), &mut o.blend, &opts, 90.0); + }); + ui.horizontal(|ui| { + ui.add_space(18.0); + crate::widgets::checkbox(ui, &mut o.clipped, tl!("Clipped")); + crate::widgets::checkbox(ui, &mut o.auto_hide, tl!("Auto Hide")); + crate::widgets::checkbox(ui, &mut o.invert, tl!("Invert")); + }); + if o != before { + run( + app, + "cloneSource.overlay", + json!({"show": o.show, "opacity": o.opacity, "clipped": o.clipped, "autoHide": o.auto_hide, "invert": o.invert, "blend": o.blend}), + ); + } +} + +/// Where the active clone source samples for document point `at` (for the canvas marker). +/// The first stroke anchors at its press, so the marker follows before the stroke commits. +pub fn clone_sample_point(app: &PhotocraftApp, at: Option<[f64; 2]>) -> Option<[f64; 2]> { + use photocraft_engine::presets::clone_source::{Mapping, transform_matrix}; + let s = app.session.presets.clone.active(); + let src = s.source?; + let stroking = app.drag.as_ref().filter(|d| matches!(d.tool, Tool::CloneStamp | Tool::Healing)).map(|d| d.start); + let anchor = if app.ui.tool_options.clone_aligned { s.anchor.or(stroking) } else { stroking }; + match (anchor, at) { + (Some(a), Some(h)) => { + let m = Mapping { source: (src[0], src[1]), anchor: (a[0], a[1]), m: transform_matrix(s.scale, s.rotation, s.flip_h, s.flip_v) }; + let (x, y) = m.map(h[0], h[1]); + Some([x, y]) + } + _ => Some(src), + } +} From 94acf1700b4c883a3173bec821bd37fdaf614905 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:55:00 +0000 Subject: [PATCH 224/259] refactor(ui-egui): split canvas.rs into canvas/ --- crates/ui-egui/src/canvas.rs | 5581 +---------------- crates/ui-egui/src/canvas/cursors.rs | 209 + crates/ui-egui/src/canvas/display.rs | 300 + crates/ui-egui/src/canvas/drag.rs | 328 + crates/ui-egui/src/canvas/filter_preview.rs | 308 + crates/ui-egui/src/canvas/gesture.rs | 286 + crates/ui-egui/src/canvas/navigator.rs | 138 + crates/ui-egui/src/canvas/paint.rs | 610 ++ crates/ui-egui/src/canvas/selection.rs | 105 + crates/ui-egui/src/canvas/start_screen.rs | 177 + crates/ui-egui/src/canvas/strokes.rs | 655 ++ crates/ui-egui/src/canvas/tabs.rs | 732 +++ crates/ui-egui/src/canvas/tests.rs | 45 +- crates/ui-egui/src/canvas/textures.rs | 681 ++ crates/ui-egui/src/canvas/tool_input.rs | 626 ++ .../ui-egui/src/canvas/transform_controls.rs | 151 + crates/ui-egui/src/canvas/view_xform.rs | 262 + 17 files changed, 5659 insertions(+), 5535 deletions(-) create mode 100644 crates/ui-egui/src/canvas/cursors.rs create mode 100644 crates/ui-egui/src/canvas/display.rs create mode 100644 crates/ui-egui/src/canvas/drag.rs create mode 100644 crates/ui-egui/src/canvas/filter_preview.rs create mode 100644 crates/ui-egui/src/canvas/gesture.rs create mode 100644 crates/ui-egui/src/canvas/navigator.rs create mode 100644 crates/ui-egui/src/canvas/paint.rs create mode 100644 crates/ui-egui/src/canvas/selection.rs create mode 100644 crates/ui-egui/src/canvas/start_screen.rs create mode 100644 crates/ui-egui/src/canvas/strokes.rs create mode 100644 crates/ui-egui/src/canvas/tabs.rs create mode 100644 crates/ui-egui/src/canvas/textures.rs create mode 100644 crates/ui-egui/src/canvas/tool_input.rs create mode 100644 crates/ui-egui/src/canvas/transform_controls.rs create mode 100644 crates/ui-egui/src/canvas/view_xform.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index aaff7f5cad..1afc46a3b6 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -12,182 +12,87 @@ use serde_json::json; use crate::PhotocraftApp; use crate::state::{Tool, View}; -/// Largest texture side we upload; bigger documents are uploaded downsampled, with the part in -/// view added at the screen's resolution when zoomed in (`detail_plan`). -pub const MAX_TEXTURE: u32 = 4096; +mod cursors; +mod display; +mod drag; +mod filter_preview; +mod gesture; +mod navigator; +mod paint; +mod selection; +mod start_screen; +mod strokes; +mod tabs; +mod textures; +mod tool_input; +mod transform_controls; +mod view_xform; -/// The largest texture side to upload on this device: [`MAX_TEXTURE`], or less where the GPU -/// allows less (2048 on some older or low-end GPUs and WebGL contexts). Past the device's limit -/// egui asserts and the backend fails to create the texture. -fn texture_side(ctx: &egui::Context) -> u32 { - clamp_texture_side(ctx.input(|i| i.max_texture_side)) -} - -/// [`texture_side`] for a device whose largest texture side is `max_texture_side`. -fn clamp_texture_side(max_texture_side: usize) -> u32 { - u32::try_from(max_texture_side).unwrap_or(MAX_TEXTURE).clamp(1, MAX_TEXTURE) -} - -/// How many document pixels per side one texel of the CPU canvas texture of a `size` document -/// holds when textures are at most `side` texels per side: 1 (full resolution) when it fits. -fn texture_factor(size: [u32; 2], side: u32) -> u32 { - size[0].max(size[1]).div_ceil(side.max(1)).max(1) -} - -/// What the CPU canvas draws over its reduced texture so a large document shows its own pixels -/// at 100 % (#7568): the part of the document in view (`region`, document pixels) composited at -/// one texel per `factor` pixels, a power of two no coarser than the screen. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct DetailPlan { - pub factor: u32, - pub region: DRect, -} - -/// The detail region snaps outward to multiples of this many texels, so a small pan reuses it. -const DETAIL_QUANTUM: i32 = 256; - -/// The detail texture a CPU canvas view of a `size` document needs, at `zoom` physical pixels -/// per document pixel over `visible` (document pixels), with textures at most `side` texels per -/// side: `None` when the whole-document texture is already as fine as the screen (a document -/// that fits, or a view zoomed out far enough), or nothing of the document is in view. -/// -/// A document over `side` (4096 px, or the device's smaller limit) is uploaded reduced, so at -/// 100 % it was drawn magnified and blurred. The detail costs what the window shows, not what the -/// document holds: its side is capped by `side` like any texture, coarsening by powers of two. -pub(crate) fn detail_plan(size: [u32; 2], side: u32, zoom: f32, visible: DRect) -> Option { - if !zoom.is_finite() || zoom <= 0.0 { - return None; - } - let base = texture_factor(size, side); - let mut factor = crate::adjust_preview::proxy_factor(zoom); - let bounds = DRect::new(0, 0, i32::try_from(size[0]).ok()?, i32::try_from(size[1]).ok()?); - let v = visible.intersect(&bounds); - if v.is_empty() { - return None; - } - while factor < base { - let q = DETAIL_QUANTUM.saturating_mul(i32::try_from(factor).unwrap_or(i32::MAX)); - let up = |x: i32| x.div_euclid(q).saturating_add(i32::from(x.rem_euclid(q) != 0)).saturating_mul(q); - let region = DRect::new(v.x0.div_euclid(q).saturating_mul(q), v.y0.div_euclid(q).saturating_mul(q), up(v.x1), up(v.y1)).intersect(&bounds); - // A reduced region's texel count can round one up (`render_reduced_damage`'s cells). - let fits = |n: u32| n.div_ceil(factor).saturating_add(1) <= side; - // Snapped when that fits, else just what is in view (a window near the device's limit). - for region in [region, v] { - if !region.is_empty() && fits(region.width()) && fits(region.height()) { - return Some(DetailPlan { factor, region }); - } - } - factor = factor.saturating_mul(2); - } - None -} - -pub(crate) struct ClonePreviewCache { - key: String, - texture: egui::TextureHandle, -} - -/// A transient source image beneath the brush outline; never part of the document render. -fn draw_clone_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, at: [f64; 2], output: Option) { - use photocraft_engine::presets::clone_source::{Mapping, overlay_blend, transform_matrix}; - let overlay = app.session.presets.clone.overlay.clone(); - if app.ui.tool != Tool::CloneStamp || !overlay.show || (overlay.auto_hide && app.drag.is_some()) { - return; - } - let slot = app.session.presets.clone.active().clone(); - let Some(source) = slot.source else { return }; - let radius = f64::from(app.session.tools.brush.size) / 2.0; - if !radius.is_finite() || radius <= 0.0 || radius > 500.0 || !at.iter().all(|v| v.is_finite() && v.abs() < 1_000_000.0) { - return; - } - let stroke_start = app.drag.as_ref().map(|d| d.start); - let anchor = if app.ui.tool_options.clone_aligned { slot.anchor.or(stroke_start) } else { stroke_start }.unwrap_or(at); - let map = - Mapping { source: (source[0], source[1]), anchor: (anchor[0], anchor[1]), m: transform_matrix(slot.scale, slot.rotation, slot.flip_h, slot.flip_v) }; - let rect = DRect::new((at[0] - radius).floor() as i32, (at[1] - radius).floor() as i32, (at[0] + radius).ceil() as i32, (at[1] + radius).ceil() as i32); - let Some(st) = app.session.active() else { return }; - let (display, display_key) = canvas_display(app, &st.doc, output); - // A shaped tip (sampled bitmap, or a rotated / flattened round one) clips the overlay to its - // outline instead of a circle, as Photoshop does with Clipped on. - let tip_rings = if overlay.clipped { crate::brush_cursor::rings(painter.ctx(), &app.session.tools.brush, true) } else { None }; - let tip_key = tip_rings.as_ref().map(|r| { - use std::hash::{Hash, Hasher}; - let mut h = std::collections::hash_map::DefaultHasher::new(); - r.iter().flatten().for_each(|p| (p[0].to_bits(), p[1].to_bits()).hash(&mut h)); - (h.finish(), radius.to_bits(), at.map(f64::to_bits)) - }); - let key = format!( - "{:?}:{}:{:?}:{rect:?}:{map:?}:{}:{}:{}:{}:{}:{tip_key:?}", - st.doc.id, st.revision, st.active_layer, app.ui.tool_options.clone_sample, display_key, overlay.invert, overlay.blend, app.ui.view.pattern_preview - ); - if app.clone_preview.as_ref().is_none_or(|c| c.key != key) { - let Ok(mut buf) = - photocraft_engine::retouch_cmds::clone_preview_periodic(&app.session, rect, &map, &app.ui.tool_options.clone_sample, app.ui.view.pattern_preview) - else { - return; - }; - if overlay.invert { - for px in &mut buf.px { - for c in px.iter_mut().take(3) { - *c = 1.0 - *c; - } - } - } - // Darken, Lighten and Difference mix the source with the image under the brush (the - // composite, whatever Sample reads), so Difference turns black where they line up. - if overlay.blend != "normal" { - let here = Mapping { source: (0.0, 0.0), anchor: (0.0, 0.0), m: [1.0, 0.0, 0.0, 1.0] }; - let Ok(under) = photocraft_engine::retouch_cmds::clone_preview_periodic(&app.session, rect, &here, "all", app.ui.view.pattern_preview) else { - return; - }; - for (px, d) in buf.px.iter_mut().zip(&under.px) { - *px = overlay_blend(&overlay.blend, *px, *d); - } - } - if let Some(rings) = &tip_rings { - let mask = crate::brush_cursor::tip_mask(rings, at, radius, [rect.x0, rect.y0, rect.x1, rect.y1]); - for (px, inside) in buf.px.iter_mut().zip(mask) { - if !inside { - *px = [0.0; 4]; - } - } - } - let image = display_image(display.as_deref(), &buf); - match app.clone_preview.as_mut() { - Some(cache) => { - cache.texture.set(image, canvas_texture_options(1)); - cache.key = key; - } - None => app.clone_preview = Some(ClonePreviewCache { key, texture: painter.ctx().load_texture("clone-preview", image, canvas_texture_options(1)) }), - } - } - let Some(cache) = &app.clone_preview else { return }; - let tint = Color32::from_white_alpha((overlay.opacity.clamp(0.0, 100.0) * 2.55).round() as u8); - // A textured triangle fan provides a circular clip, including mirrored canvas views. - let mut mesh = egui::Mesh::with_texture(cache.texture.id()); - let vertex = |x: f64, y: f64| egui::epaint::Vertex { - pos: xf.to_screen(x as f32, y as f32), - uv: pos2((x - f64::from(rect.x0)) as f32 / rect.width() as f32, (y - f64::from(rect.y0)) as f32 / rect.height() as f32), - color: tint, - }; - if !overlay.clipped || tip_rings.is_some() { - for (x, y) in [(rect.x0, rect.y0), (rect.x1, rect.y0), (rect.x1, rect.y1), (rect.x0, rect.y1)] { - mesh.vertices.push(vertex(f64::from(x), f64::from(y))); - } - mesh.indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]); - painter.add(egui::Shape::mesh(mesh)); - return; - } - mesh.vertices.push(vertex(at[0], at[1])); - for i in 0..=64 { - let angle = f64::from(i) * std::f64::consts::TAU / 64.0; - mesh.vertices.push(vertex(at[0] + radius * angle.cos(), at[1] + radius * angle.sin())); - } - for i in 1..=64 { - mesh.indices.extend_from_slice(&[0, i, i + 1]); - } - painter.add(egui::Shape::mesh(mesh)); -} +#[cfg(test)] +pub(crate) use cursors::eyedropper_ring_colors; +pub(crate) use cursors::{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}; +#[cfg(test)] +pub(crate) use display::GPU_OUTPUT; +#[cfg(test)] +use display::texture_key; +pub(crate) use display::{cache_key, canvas_display, display_doc, display_image}; +use display::{checker, hdr_preview, sync_display_lut}; +pub use drag::{Drag, fixed_size_px, marquee_corners, marquee_px, marquee_readout, readout_in, size_readout, square_px}; +pub(crate) use drag::{angle_readout, draw_readout, draw_value_readout}; +#[cfg(test)] +pub(crate) use drag::{marquee_drag_ants, marquee_preview_px}; +#[cfg(test)] +pub(crate) use filter_preview::committed_filter_preview; +use filter_preview::{ensure_adjust_proxy, ensure_proxy_preview, filter_preview_display_doc}; +pub(crate) use filter_preview::{ensure_filter_preview, filter_channel_preview, filter_preview_factor}; +#[cfg(test)] +pub(crate) use gesture::constrained_polygon_point; +pub use gesture::{commit_crop, commit_polygon, polygon_cancel_stale, polygon_replaces_selection, polygon_retract}; +pub(crate) use gesture::{finish_gesture, selection_mode}; +pub(crate) use navigator::NavigatorCache; +#[cfg(test)] +use navigator::navigator_waits_for_drag; +pub use navigator::{NAVIGATOR_SIDE, navigator_gpu_view, navigator_texture, navigator_waits_for_gpu}; +#[cfg(test)] +use paint::draw_tool_state; +pub(crate) use paint::{clip_line, marching_ants_lines, marching_ants_mapped}; +use paint::{ + draw_beyond_canvas, draw_drag_preview, marching_ants_segments, paint_cpu_detail, paint_cpu_document, paint_gpu_view, paint_mapped_image_at, pattern_xf, +}; +use selection::selection_shown_offset; +pub use selection::{SelCursor, selection_cursor}; +pub(crate) use selection::{floating_outline, selection_drag_delta}; +#[cfg(test)] +use start_screen::start_screen_drop_hint; +pub use strokes::paint_target; +pub(crate) use strokes::{ClonePreviewCache, CommittedStroke, LiveStroke, cancel_mixer_on_context_change, freehand_tool, spread_ms, strokes_live}; +use strokes::{HOLD_REPEAT_MS, draw_clone_preview, feed_live_stroke, pointer_button_modifiers, pointer_moves, stroke_wants_time, tap_at_peak_pressure}; +#[cfg(test)] +pub(crate) use strokes::{SPOT_HEALING_TRAIL, live_retouch_points}; +pub(crate) use tabs::arranged_cells; +#[cfg(test)] +use tabs::{TEAR_OFF, pro_tab_title, tab_context_items, tab_drop_index, tab_move_target, tabs, torn_off}; +pub use tabs::{TabStrip, document_area, extra_windows}; +use tabs::{dots, paint_dots}; +#[cfg(test)] +pub(crate) use textures::detail_plan; +pub(crate) use textures::{DetailPlan, damage_since, effect_reach, ensure_texture_in_view, retain_gpu_documents, shown_as_document}; +pub use textures::{MAX_TEXTURE, ensure_texture}; +#[cfg(test)] +use textures::{clamp_texture_side, preview_bounds, texture_factor}; +use textures::{ensure_gpu, redraw_focus, visible_doc_rect}; +pub use tool_input::{ToolEvent, selection_drag_kind, tool_event}; +pub(crate) use tool_input::{command_guide_at, command_moves_layer, event_tool}; +pub(crate) use transform_controls::{LAYER_EDGES, layer_edges_rect}; +use transform_controls::{ + begin_transform_controls_at, draw_transform_controls, transform_controls_cursor, transform_controls_rect, transform_controls_several, + transform_controls_turn, +}; +#[cfg(test)] +use transform_controls::{transform_controls_hit, transform_controls_layers}; +pub use view_xform::{ViewXform, doc_point_at, fill_view, fit_view}; +use view_xform::{animated_view, wheel_anchor, zoom_about}; pub struct CanvasCache { pub revision: u64, @@ -247,3098 +152,11 @@ pub(crate) struct InView { pub key: u64, } -/// An in-progress pointer gesture on the canvas. -#[derive(Clone, Debug)] -pub struct Drag { - pub tool: Tool, - pub start: [f64; 2], - pub points: Vec<[f64; 3]>, - pub modifiers: egui::Modifiers, - /// A Brush/Eraser stroke that erases: the Eraser, or a right-button Brush drag with - /// Preferences › Tools › Right-click with painting tools set to Erase. - pub erase: bool, - /// A Brush or Pencil stroke in Photoshop's Clear mode (`paint_mouse::clears`, #3439): it - /// erases, sent as `"mode": "clear"` so History names the tool rather than the Eraser. - pub clear: bool, - /// ⇧ constraint of a painting stroke (stroke_constraint.rs). - pub constrain: Option, - /// Modifiers held now (updated on every pointer event of the gesture). - pub live: egui::Modifiers, - /// Which of the modifiers held at the press have been released since. - pub released: egui::Modifiers, - /// The reposition key (Space) is held: pointer moves move the whole gesture instead of - /// sizing it (marquees, lasso, shapes; `hold_keys`). - pub reposition: bool, - /// A marquee or lasso drag that started inside the selection moves it instead of drawing: - /// `Some(false)` moves the outline, `Some(true)` moves the floating piece (`select.float`), as - /// every Move-tool drag with a selection does (`move_ui::moves_selected_pixels_with`). - pub sel_move: Option, - /// The last ⇧-locked offset of a selection-tool drag of the selection (`move_mods`, #6231); - /// keeps the locked direction stable between events. The Move tool's own drags use `move_mods`. - pub sel_axis: Option<[f64; 2]>, - pub lasso: Option, -} - -impl Drag { - pub fn new(tool: Tool, start: [f64; 2], points: Vec<[f64; 3]>, modifiers: egui::Modifiers, erase: bool) -> Self { - Self { - tool, - start, - points, - modifiers, - erase, - clear: false, - constrain: None, - live: modifiers, - released: egui::Modifiers::NONE, - reposition: false, - sel_move: None, - sel_axis: None, - lasso: None, - } - } - - /// Reposition: move the start and every point so the last one lands on `to` (same size). - pub fn shift_to(&mut self, to: [f64; 2]) { - let last = self.points.last().map_or(self.start, |p| [p[0], p[1]]); - let (dx, dy) = (to[0] - last[0], to[1] - last[1]); - if !(dx.is_finite() && dy.is_finite()) { - return; - } - self.start = [self.start[0] + dx, self.start[1] + dy]; - for p in &mut self.points { - p[0] += dx; - p[1] += dy; - } - if self.points.is_empty() { - self.points.push([to[0], to[1], 1.0]); - } - } - - /// Record the modifiers of a pointer event. - pub(crate) fn track(&mut self, mods: egui::Modifiers) { - self.live = mods; - self.released.shift |= !mods.shift; - self.released.alt |= !mods.alt; - } - - /// ⇧ (square / circle) and ⌥ (from the centre) for a marquee drag. A modifier held at the press - /// picks the selection mode instead (add / subtract, #188) until it is released and pressed - /// again, as in Photoshop. - pub fn marquee_mods(&self) -> (bool, bool) { - let fresh = |now: bool, at_press: bool, released: bool| now && (!at_press || released); - (fresh(self.live.shift, self.modifiers.shift, self.released.shift), fresh(self.live.alt, self.modifiers.alt, self.released.alt)) - } -} - -/// The marquee dragged from `d.start` to `end` as two document-space corners: the options-bar -/// style (fixed ratio / fixed size), ⇧ for a square or circle, ⌥ to draw from the centre. -pub fn marquee_corners(o: &crate::state::ToolOptions, d: &Drag, end: [f64; 2]) -> ([f64; 2], [f64; 2]) { - let (shift, alt) = d.marquee_mods(); - if o.marquee_style == "fixedSize" { - // A fixed box is positioned, not sized, by the drag. Using the press plus the drag's - // sign pinned it there and flipped it by its full width/height when the pointer crossed - // the press. The preview and release both follow the current pointer instead. - let (w, h) = (f64::from(o.marquee_width).max(1.0), f64::from(o.marquee_height).max(1.0)); - let a = if alt { [end[0] - w / 2.0, end[1] - h / 2.0] } else { end }; - return (a, [a[0] + w, a[1] + h]); - } - let e = crate::chrome_ui::marquee_end(&o.marquee_style, o.marquee_width as f64, o.marquee_height as f64, shift, d.start, end); - if !alt { - return (d.start, e); - } - let (dx, dy) = (e[0] - d.start[0], e[1] - d.start[1]); - // For a sized marquee the drag is the half extent when drawing from the centre. - ([d.start[0] - dx, d.start[1] - dy], [d.start[0] + dx, d.start[1] + dy]) -} - -/// The pixel rectangle a Rectangular/Elliptical Marquee drag selects so far: shown live (ants -/// and readout) exactly as the release commits it, on whole pixel edges as in Photoshop. `None` -/// while the gesture is still a click (it never left the press point by more than a few screen -/// pixels at `zoom`, points per document pixel) or the rectangle has no area: a release then -/// deselects. A one-pixel row or column is a selection (#2391). With the Fixed Size style a -/// click places the selection, as in Photoshop. -pub(crate) fn marquee_preview_px(o: &crate::state::ToolOptions, d: &Drag, zoom: f32) -> Option<[f64; 4]> { - let fixed = o.marquee_style == "fixedSize"; - if !matches!(d.tool, Tool::RectMarquee | Tool::EllipseMarquee) || (!fixed && crate::shape_dialog::is_click(d.start, &d.points, zoom)) { - return None; - } - let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); - let (a, b) = marquee_corners(o, d, last); - let mut r = if fixed { fixed_size_px(a, b, o.marquee_width, o.marquee_height) } else { marquee_px(a, b) }; - if marquee_is_square(o, d) { - r = square_px(r, d.start, last); - } - (r[2] > r[0] && r[3] > r[1]).then_some(r) -} - -/// The pixel rectangle `[x0, y0, x1, y1]` a marquee between two corners selects. -pub fn marquee_px(a: [f64; 2], b: [f64; 2]) -> [f64; 4] { - [a[0].min(b[0]).floor(), a[1].min(b[1]).floor(), a[0].max(b[0]).ceil(), a[1].max(b[1]).ceil()] -} - -/// The pixel rectangle of a Fixed Size marquee between the corners `a` and `b`: exactly `w` × `h` -/// whole pixels. Snapping both edges outwards (`marquee_px`) added a pixel to each side whenever -/// the press point sat between pixels, so 10 × 10 selected 11 × 11 (#6015). The near edge goes -/// to the closest pixel edge and the far one is the size away. -pub fn fixed_size_px(a: [f64; 2], b: [f64; 2], w: f32, h: f32) -> [f64; 4] { - let (w, h) = (f64::from(w).round().max(1.0), f64::from(h).round().max(1.0)); - let (x0, y0) = (a[0].min(b[0]).round(), a[1].min(b[1]).round()); - [x0, y0, x0 + w, y0 + h] -} - -/// Whether the marquee drag `d` is constrained to a square (or circle): ⇧ during the drag with -/// the Normal style, or a Fixed Ratio of 1:1. Mirrors the branches of `chrome_ui::marquee_end`. -fn marquee_is_square(o: &crate::state::ToolOptions, d: &Drag) -> bool { - let (w, h) = (f64::from(o.marquee_width), f64::from(o.marquee_height)); - match o.marquee_style.as_str() { - "fixedSize" => false, - "fixedRatio" if w > 0.0 && h > 0.0 => w == h, - _ => d.marquee_mods().0, - } -} - -/// A constrained square `r` (`marquee_px` of its corners) with equal sides on whole pixels. -/// -/// The square is built in continuous coordinates, and snapping each axis to the pixel grid on -/// its own (floor the near edge, ceil the far one) made one side a pixel longer than the other -/// whenever the press point sat between pixels: a ⇧ drag read 101 × 102 (#5472). The shorter -/// side grows to the longer one, away from the press point (`start`, towards `end`), so the -/// square still covers every pixel the drag touched. -pub fn square_px(r: [f64; 4], start: [f64; 2], end: [f64; 2]) -> [f64; 4] { - let [x0, y0, x1, y1] = r; - let (w, h) = (x1 - x0, y1 - y0); - let n = w.max(h); - let grow = |lo: f64, hi: f64, extent: f64, from: f64, to: f64| { - let d = (n - extent).max(0.0); - if to < from { (lo - d, hi) } else { (lo, hi + d) } - }; - let (x0, x1) = grow(x0, x1, w, start[0], end[0]); - let (y0, y1) = grow(y0, y1, h, start[1], end[1]); - [x0, y0, x1, y1] -} - -/// The one-pixel line `[x0, y0, x1, y1]` a Single Row (Single Column) Marquee at `p` selects: the -/// pixel row (column) under `p`, kept on the canvas, across the whole `size`. `None` for other -/// tools, an empty canvas or a point that is not a number. -pub(crate) fn single_line_px(tool: Tool, size: [u32; 2], p: [f64; 2]) -> Option<[f64; 4]> { - let [w, h] = size.map(f64::from); - if w < 1.0 || h < 1.0 || !p[0].is_finite() || !p[1].is_finite() { - return None; - } - match tool { - Tool::SingleRowMarquee => { - let y = p[1].floor().clamp(0.0, h - 1.0); - Some([0.0, y, w, y + 1.0]) - } - Tool::SingleColumnMarquee => { - let x = p[0].floor().clamp(0.0, w - 1.0); - Some([x, 0.0, x + 1.0, h]) - } - _ => None, - } -} - -/// The line a Single Row / Single Column Marquee gesture `d` selects so far: it follows the -/// pointer until the release. -fn single_line_drag_px(app: &PhotocraftApp, d: &Drag) -> Option<[f64; 4]> { - let st = app.session.active()?; - let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); - single_line_px(d.tool, [st.doc.size.width, st.doc.size.height], last) -} - -/// The marching ants of a marquee drag: its rectangle, or the ellipse inscribed in it, built in -/// document space and mapped point by point through the view, so the hinting lands where the -/// release commits the selection. -/// -/// A rotated view projects the rectangle onto a rotated one, and an axis-aligned screen box -/// through two of its corners is a different shape in a different place: the commit was always -/// right, only the hinting was drawn elsewhere (#2512). The points are not snapped: the ants snap -/// straight edges to device pixels as they draw them (`crate::ants`), like every other outline, so -/// the lines stay crisp at any zoom (#172) and display scale (#7489). -pub(crate) fn marquee_ants(xf: &ViewXform, tool: Tool, a: [f64; 2], b: [f64; 2]) -> Vec { - let (x0, x1) = (a[0].min(b[0]), a[0].max(b[0])); - let (y0, y1) = (a[1].min(b[1]), a[1].max(b[1])); - let at = |x: f64, y: f64| xf.to_screen(x as f32, y as f32); - if tool != Tool::EllipseMarquee { - return vec![at(x0, y0), at(x1, y0), at(x1, y1), at(x0, y1)]; - } - // An axis-aligned view (rotation a multiple of 90 degrees) maps the ellipse onto the one - // inscribed in the screen box of two opposite corners. The ants draw its vertices where they - // are: snapping each on its own turns the nearly flat arcs at the edge midpoints into 1 px - // stairs, whose antialiased steps wash the ants out to grey on white and black. - let quarter = xf.rotation.rem_euclid(90.0); - if quarter < 1e-4 || 90.0 - quarter < 1e-4 { - let r = Rect::from_two_pos(at(x0, y0), at(x1, y1)); - return crate::tool_feedback::ellipse_points(r); - } - // As many vertices as the same ellipse would get drawn on screen (`ellipse_points`). - let scr = Rect::from_points(&[xf.to_screen(x0 as f32, y0 as f32), xf.to_screen(x1 as f32, y1 as f32)]); - let n = (((scr.width() + scr.height()) * 0.25) as usize).clamp(16, 256); - let (cx, cy, rx, ry) = ((x0 + x1) * 0.5, (y0 + y1) * 0.5, (x1 - x0) * 0.5, (y1 - y0) * 0.5); - (0..n) - .map(|i| { - let t = i as f64 / n as f64 * std::f64::consts::TAU; - at(cx + rx * t.cos(), cy + ry * t.sin()) - }) - .collect() -} - -/// The ants of the marquee being drawn: `marquee` when the drag has one (the options-bar style -/// and the modifiers applied), the raw press and pointer corners otherwise. This is the whole of -/// what the hinting draws for the selection tools, so the test in `marquee_tests` checks it -/// against the selection the release commits (#2512). -pub(crate) fn marquee_drag_ants(d: &Drag, xf: &ViewXform, marquee: Option<[f64; 4]>) -> Vec { - let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); - let (a, b) = marquee.map_or((d.start, last), |[x0, y0, x1, y1]| ([x0, y0], [x1, y1])); - marquee_ants(xf, d.tool, a, b) -} - -/// The size readout shown beside the cursor while dragging a marquee: the width and height values. -pub fn marquee_readout(r: [f64; 4]) -> [String; 2] { - [format!("{} px", r[2] - r[0]), format!("{} px", r[3] - r[1])] -} - -/// [`marquee_readout`] in the Units & Rulers unit, as Photoshop shows it (cm when the rulers are in -/// centimeters), from the active document's resolution; pixels without a document. -pub fn size_readout(app: &PhotocraftApp, r: [f64; 4]) -> [String; 2] { - let Some(d) = app.session.active() else { return marquee_readout(r) }; - let (dpi, size) = (f64::from(d.doc.resolution_dpi), d.doc.size); - readout_in(&app.session.prefs().units_and_rulers, dpi, [size.width as f64, size.height as f64], r) -} - -/// `r`'s width and height formatted in `ur`'s ruler unit at `dpi` (percent of `extent`). -pub fn readout_in(ur: &photocraft_engine::prefs::UnitsAndRulers, dpi: f64, extent: [f64; 2], r: [f64; 4]) -> [String; 2] { - let s = ur.rulers.suffix(); - [format!("{} {s}", ur.format(r[2] - r[0], dpi, extent[0])), format!("{} {s}", ur.format(r[3] - r[1], dpi, extent[1]))] -} - -/// Draw the marquee size readout below-right of the cursor (kept on screen), like Photoshop's: -/// two rows, `W:` / `H:` labels on the left and the values right-aligned. -fn draw_marquee_readout(app: &PhotocraftApp, ctx: &egui::Context, cursor: Pos2, values: [String; 2]) { - draw_value_readout(app, ctx, "marquee-readout", cursor, ["W:", "H:"], values); -} - -/// A turn of `deg` degrees as the readout beside the pointer shows it, to 0.1° in (-180, 180]. -/// Rounded first so a hair below zero never reads "-0.0°" and a hair above -180 reads "180.0°". -pub(crate) fn angle_readout(deg: f64) -> String { - let d = (deg * 10.0).round() / 10.0; - let d = if d == 0.0 { - 0.0 - } else if d == -180.0 { - 180.0 - } else { - d - }; - format!("{d:.1}°") -} - -/// A transformation-values readout beside the pointer (a marquee's or the crop frame's size, an -/// angle), unless Preferences › Tools › Show Transformation Values is off, as in Photoshop (#204). -/// The brush HUD isn't one: Show Transformation Values doesn't hide it, so it calls [`draw_readout`]. -pub(crate) fn draw_value_readout(app: &PhotocraftApp, ctx: &egui::Context, id: &str, cursor: Pos2, labels: [&str; N], values: [String; N]) { - if app.session.prefs().tools.show_transformation_values { - draw_readout(ctx, id, cursor, labels, values); - } -} - -/// A readout of `N` rows beside the pointer (labels left, values right-aligned), above everything. -pub(crate) fn draw_readout(ctx: &egui::Context, id: &str, cursor: Pos2, labels: [&str; N], values: [String; N]) { - let t = crate::theme::Tokens::get(ctx); - let font = egui::FontId::proportional(11.5); - let width = |text: &str| ctx.fonts_mut(|f| f.layout_no_wrap(text.to_owned(), font.clone(), t.text).size().x); - let labels = labels.map(|label| tl!(label)); - let (lw, vw) = (labels.map(width), values.each_ref().map(|v| width(v))); - let (label_col, value_col) = (lw.iter().fold(0.0f32, |a, &b| a.max(b)), vw.iter().fold(0.0f32, |a, &b| a.max(b))); - egui::Area::new(egui::Id::unique(id)).order(egui::Order::Tooltip).fixed_pos(cursor + vec2(16.0, 18.0)).interactable(false).constrain(true).show( - ctx, - |ui| { - egui::Frame::new() - .fill(t.card) - .stroke(Stroke::new(1.0, t.card_border)) - .corner_radius(t.radius_sm) - .inner_margin(egui::Margin::symmetric(7, 4)) - .show(ui, |ui| { - ui.spacing_mut().item_spacing = vec2(0.0, 1.0); - for (i, value) in values.into_iter().enumerate() { - // Labels left, values right-aligned on one edge, sharing a baseline. - ui.horizontal(|ui| { - ui.add(egui::Label::new(egui::RichText::new(labels[i]).font(font.clone()).color(t.text_dim)).extend()); - ui.add_space(label_col - lw[i] + 12.0 + value_col - vw[i]); - ui.add(egui::Label::new(egui::RichText::new(value).font(font.clone()).color(t.text)).extend()); - }); - } - }); - }, - ); -} - -/// The engine's live stroke of a tool: the Brush, Pencil and Eraser paint dabs; the Clone Stamp, -/// Healing Brush and History Brush composite their source. -enum EngineStroke { - Brush(Box), - Retouch(photocraft_engine::retouch_cmds::LiveRetouch), - Dab(photocraft_engine::retouch_cmds::LiveDab), - Mixer(Box), -} - -impl EngineStroke { - /// The brush engine's strokes can change while the pointer is held still (see - /// `LiveStroke::wants_time`); the retouch strokes don't. - fn wants_time(&self) -> bool { - match self { - EngineStroke::Brush(l) => l.wants_time(), - EngineStroke::Mixer(l) => l.wants_time(), - EngineStroke::Retouch(_) | EngineStroke::Dab(_) => false, - } - } - - fn doc(&self) -> &std::sync::Arc { - match self { - Self::Brush(s) => &s.doc, - Self::Retouch(s) => &s.doc, - Self::Dab(s) => &s.doc, - Self::Mixer(s) => &s.doc, - } - } - fn bounds(&self) -> DRect { - match self { - Self::Brush(s) => s.bounds(), - Self::Retouch(s) => s.bounds(), - Self::Dab(s) => s.bounds(), - Self::Mixer(s) => s.bounds(), - } - } - fn push(&mut self, pts: &[photocraft_engine::paint::StrokePoint]) -> photocraft_engine::Result { - match self { - Self::Brush(s) => s.push(pts), - Self::Retouch(s) => s.push(pts), - Self::Dab(s) => s.push(pts), - Self::Mixer(s) => s.push(pts), - } - } - /// The jitter seed the commit must reuse (the Clone Stamp's comes from the session brush). - fn seed(&self) -> Option { - match self { - Self::Brush(s) => Some(s.seed), - Self::Mixer(s) => Some(s.seed), - Self::Retouch(_) => None, - Self::Dab(_) => None, - } - } -} - -/// A stroke shown while it is drawn: the engine renders the real result onto a copy of the -/// document, and the canvas redraws only what each step changed. -pub(crate) struct LiveStroke { - preview_failed: bool, - stroke: EngineStroke, - doc: photocraft_doc::DocId, - revision: u64, - /// Preview key of the stroke; step `n` displays as `key + n`. - key: u64, - /// Damage of each step (step 0 = the document before the stroke). - damage: Vec, - /// Drag points rendered so far. - fed: usize, -} - -impl LiveStroke { - fn display_key(&self) -> u64 { - self.key + self.damage.len() as u64 - } - - /// What changed since the canvas showed preview `key` (0 = the document before the stroke). - fn since(&self, key: u64) -> Option { - let seen = if key == 0 { 0 } else { usize::try_from(key.checked_sub(self.key)?).ok()? }; - Some(self.damage.get(seen..)?.iter().fold(DRect::EMPTY, |a, r| a.union(r))) - } -} - -/// A live stroke whose pixels its commit took over (`"fromLive"`): document `doc` at `revision` -/// holds exactly the live stroke's last step, so a cache that showed step `n` of it only misses -/// the steps after `n` (step 0 = the document before the stroke: everything). -pub(crate) struct CommittedStroke { - pub(crate) doc: photocraft_doc::DocId, - pub(crate) revision: u64, - key: u64, - damage: Vec, - /// What the commit repaints beyond the stroke whatever a cache showed: the layer's whole - /// composite when effects laid out over its frame moved with it (a Gradient Overlay spans the - /// grown layer, #4053; `photocraft_compose::relayout_damage`). - relayout: DRect, -} - -impl CommittedStroke { - #[cfg(test)] - pub(crate) fn for_test(key: u64, damage: Vec) -> Self { - Self { doc: photocraft_doc::DocId(0), revision: 0, key, damage, relayout: DRect::EMPTY } - } - - /// The raw preview key of the live stroke's last step: what a cache showed at release. - #[cfg(test)] - pub(crate) fn last_key(&self) -> u64 { - self.key + self.damage.len() as u64 - } - - /// What a cache that showed raw preview `key` of this stroke at the revision before misses. - pub(crate) fn since(&self, key: u64) -> Option { - let seen = if key == 0 { 0 } else { usize::try_from(key.checked_sub(self.key)?).ok()? }; - Some(self.damage.get(seen..)?.iter().fold(DRect::EMPTY, |a, r| a.union(r))) - } -} - -/// The live stroke on document `idx`, while it is current. -fn live_stroke(app: &PhotocraftApp, idx: usize) -> Option<&LiveStroke> { - let st = app.session.documents().get(idx)?; - app.live_stroke.as_ref().filter(|l| app.drag.is_some() && l.doc == st.doc.id && l.revision == st.revision) -} - -/// `paint.stroke` params for a Brush/Eraser drag (shared by the live preview and the commit). The -/// stroke smoothing is the session brush's (the options bar's Smoothing %). -fn stroke_params(app: &PhotocraftApp, d: &Drag, points: &[Vec]) -> serde_json::Value { - let tool = d.tool; - let mut p = json!({ "points": points, "erase": d.erase, "zoom": app.point_zoom(), "target": paint_target(app) }); - if d.clear { - p["mode"] = json!("clear"); - } - if tool == Tool::Pencil { - p["autoErase"] = json!(app.ui.tool_options.pencil_auto_erase); - } - // Block mode: the engine sizes the square from the stroke's zoom (16 / zoom px, #2770). - if crate::eraser_ui::block_mode(app, tool) { - p["block"] = json!(true); - } - p -} - -/// Tools whose strokes the engine renders while they are drawn (`LiveStroke`). -pub(crate) fn strokes_live(tool: Tool) -> bool { - matches!( - tool, - Tool::Brush - | Tool::Pencil - | Tool::MixerBrush - | Tool::Eraser - | Tool::ColorReplacement - | Tool::Blur - | Tool::Sharpen - | Tool::Smudge - | Tool::Dodge - | Tool::Burn - | Tool::Sponge - ) || live_retouch_command(tool).is_some() -} - -/// The Spot Healing Brush's stroke while dragging: Photoshop shows the area it will heal as a -/// semi-opaque dark overlay (an image overlay, the same in every UI theme) and heals on release. -pub(crate) const SPOT_HEALING_TRAIL: Color32 = Color32::from_black_alpha(128); - -/// The retouching tools drawn live (`LiveRetouch`; the Background Eraser's and an Impressionist -/// Pattern Stamp's dabs are laid one by one, `LiveDab`), by the command their live stroke -/// previews. The Healing Brush shows its texture while drawing; the blend comes on release. -fn live_retouch_command(tool: Tool) -> Option<&'static str> { - match tool { - Tool::CloneStamp => Some("paint.cloneStamp"), - Tool::Healing => Some("paint.healingBrush"), - Tool::HistoryBrush => Some("paint.historyBrush"), - Tool::PatternStamp => Some("paint.patternStamp"), - Tool::BackgroundEraser => Some("paint.backgroundEraser"), - _ => None, - } -} - -/// The command a live-stroking tool commits: the Pencil's (and the Pencil- or Block-mode -/// Eraser's) `paint.pencil`, else `paint.stroke`. -pub(crate) fn stroke_command(app: &PhotocraftApp, tool: Tool) -> &'static str { - if tool == Tool::Pencil || crate::eraser_ui::pencil_mode(app, tool) || crate::eraser_ui::block_mode(app, tool) { "paint.pencil" } else { "paint.stroke" } -} - -/// Windows' crosshair cursor inverts the pixels under it, so over mid-grey (the pasteboard, many -/// photos) it vanishes (#737), and the Linux themes' and macOS's differ. Use the same black-and-white -/// bitmap on every desktop platform, carried by the OS so its movement does not wait for the canvas -/// to render (#1343). -fn visible_crosshair(icon: egui::CursorIcon, painter: &egui::Painter, p: Pos2, draw: bool) -> egui::CursorIcon { - if !draw || icon != egui::CursorIcon::Crosshair { - return icon; - } - crate::tool_cursor::crosshair(painter, p, 8.0, 2.0) -} - -/// The Pencil's cursor at `doc` (document pixels): the whole-pixel square its dab fills -/// (`paint::grid_square`), in screen points with its edges on physical pixels (`ppp` = pixels -/// per point), so it lines up with the pixel grid at any zoom. -pub(crate) fn pencil_cursor_rect(xf: &ViewXform, doc: [f64; 2], size: f32, ppp: f32) -> Rect { - let [x0, y0, x1, y1] = photocraft_engine::paint::grid_square(doc[0], doc[1], size); - let r = Rect::from_two_pos(xf.to_screen(x0 as f32, y0 as f32), xf.to_screen(x1 as f32, y1 as f32)); - let ppp = if ppp.is_finite() && ppp > 0.0 { ppp } else { 1.0 }; - let snap = |v: f32| (v * ppp).round() / ppp; - Rect::from_min_max(pos2(snap(r.min.x), snap(r.min.y)), pos2(snap(r.max.x), snap(r.max.y))) -} - -/// Whether an aliased (Pencil) dab of `size` pixels is round rather than its whole -/// [`pencil_cursor_rect`] square. The dab fills the pixels whose centres lie within its radius of -/// the grid centre (`paint::grid_center`), so up to 3 px the corner pixels are in and the dab is -/// a square; from 4 px on they fall outside and it is a disc (#2662). -pub(crate) fn pencil_tip_is_round(size: f32) -> bool { - let n = if size.is_finite() { size.round().clamp(1.0, 100_000.0) } else { 1.0 }; - let h = n / 2.0; - (h - 0.5) * std::f32::consts::SQRT_2 > h -} - -/// Whether a brush-tip circle draws its centre mark. -/// Clone Stamp and Healing Brush stay an empty circle until Option is held, the source-point -/// cursor. Other brushes follow Preferences › Cursors › Show Crosshair in Brush Tip, as in -/// Photoshop; the Background Eraser always shows its sampling hotspot. -fn brush_tip_centre(tool: Tool, option: bool, show_crosshair: bool) -> bool { - if tool == Tool::QuickSelection { - return false; - } - if matches!(tool, Tool::CloneStamp | Tool::Healing) { - return option || show_crosshair; - } - show_crosshair || tool == Tool::BackgroundEraser -} - -/// The display colour of an RGB triple (0..1 per channel) as an egui colour. -fn display_color(c: [f32; 3]) -> Color32 { - let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - Color32::from_rgb(b(c[0]), b(c[1]), b(c[2])) -} - -/// The Eyedropper ring's two colours at document point (x, y): the colour under the pointer -/// (what a click would pick) and the current foreground, or `None` where there is no colour -/// to sample (#213). -pub(crate) fn eyedropper_ring_colors(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<(Color32, Color32)> { - let new = eyedropper_color(app, x, y)?; - let fg = app.session.tools.foreground; - Some((display_color(new), display_color([fg[0], fg[1], fg[2]]))) -} - -/// Draw the Eyedropper's comparison ring at `p`: an opaque neutral grey band around the -/// pointer with the sampled colour on its upper half and the current one on the lower, -/// framed by thin dark and light hairlines so every edge reads on any image, and the -/// pipette at its centre marking the sampled pixel (#213, #6973). Like Photoshop it shows -/// only while the mouse button is held (`held`): hovering shows the plain pipette and -/// samples nothing. `None` when not held, there is nothing to sample, or the Precise-cursor -/// preference wants the plain crosshair. -fn eyedropper_ring(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, p: Pos2, held: bool) -> Option { - // The options bar's Show Sampling Ring turns it off (#1649). - if !held || !app.ui.tool_options.eyedropper_ring || app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise { - return None; - } - let [x, y] = xf.to_doc(p); - let (new, current) = eyedropper_ring_colors(app, x, y)?; - // Photoshop's proportions (#6973): a ring about 210 pt across whose opaque grey outer - // band and coloured inner band are each about 17 pt wide, over a transparent centre. - // In points, so the ring scales with Interface › UI Scale like the rest of the cursor. - let (r_out, band) = (105.0_f32, 17.0_f32); - let r_in = r_out - 2.0 * band; - // Screen y grows down, so PI..TAU is the upper half (the sampled colour) and 0..PI the - // lower (the current one); the halves meet at 3 and 9 o'clock, as in Photoshop. - use std::f32::consts::{PI, TAU}; - let upper: Vec = (0..=48) - .map(|i| { - let a = PI + (TAU - PI) * i as f32 / 48.0; - p + vec2(a.cos(), a.sin()) * (r_in + band / 2.0) - }) - .collect(); - // `circle_stroke` paints its stroke outside the radius, `Shape::line` centres it. - painter.circle_stroke(p, r_in, Stroke::new(band, current)); - painter.add(egui::Shape::line(upper, Stroke::new(band, new))); - painter.circle_stroke(p, r_in + band, Stroke::new(band, RING_GREY)); - // Thin dark and light hairlines on the ring's two edges, one physical pixel wide, so it - // reads on any colour including a flat mid-grey that matches the band itself (#6973). - let px = 1.0 / painter.ctx().pixels_per_point().max(1.0); - let (dark, light) = (Stroke::new(px, Color32::from_black_alpha(160)), Stroke::new(px, Color32::from_white_alpha(160))); - painter.circle_stroke(p, r_out, dark); - painter.circle_stroke(p, r_out + px, light); - painter.circle_stroke(p, r_in - px, dark); - painter.circle_stroke(p, r_in - 2.0 * px, light); - // Photoshop keeps the pipette visible at the centre, its tip on the sampled pixel; a - // ring this size says nothing about where it samples without it. - Some(pipette_cursor(painter.ctx(), p)) -} - -/// The Eyedropper ring's opaque neutral grey, as Photoshop measures it (#6973). -const RING_GREY: Color32 = Color32::from_gray(127); - -fn begin_live_stroke(app: &PhotocraftApp) -> Option { - static STROKES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let st = app.session.active()?; - let d = app.drag.as_ref()?; - let stroke = if d.tool == Tool::MixerBrush { - let points = app.stylus.stroke_points(&d.points); - let p = stroke_params(app, d, points.get(..1)?); - EngineStroke::Mixer(Box::new(photocraft_engine::brush_cmds::mixer_live::LiveMixer::begin(&app.session, &p).ok()?)) - } else if d.tool == Tool::ColorReplacement { - // The params `retouch_ui::finish_stroke` commits. - let mut p = crate::retouch_ui::color_replacement_params(app); - p["points"] = json!(d.points); - EngineStroke::Dab(photocraft_engine::brush_cmds::live_color_replacement(&app.session, &p).ok()?) - } else if let Some((cmd, mut p)) = crate::retouch_ui::dab_params(app, d.tool) { - // The params `retouch_ui::finish_stroke` commits; Sample All Layers isn't previewed. - p["points"] = json!(d.points); - p["target"] = paint_target(app); - EngineStroke::Dab(photocraft_engine::retouch_cmds::LiveDab::begin(&app.session, cmd, &p).ok()?) - } else if d.tool == Tool::PatternStamp { - // The params `retouch_ui::finish_stroke` commits. - let mut p = crate::retouch_ui::pattern_stamp_params(app, &d.points); - p["points"] = json!(d.points); - p["target"] = paint_target(app); - if app.ui.tool_options.pattern_stamp_impressionist { - EngineStroke::Dab(photocraft_engine::retouch_cmds::live_pattern_impressionist(&app.session, &p).ok()?) - } else { - EngineStroke::Retouch(photocraft_engine::retouch_cmds::LiveRetouch::begin(&app.session, "paint.patternStamp", &p).ok()?) - } - } else if d.tool == Tool::BackgroundEraser { - // The params `eraser_ui::finish_stroke` commits (layer pixels only). - let p = crate::eraser_ui::background_eraser_params(app, &d.points); - EngineStroke::Dab(photocraft_engine::eraser_cmds::live_background_eraser(&app.session, &p).ok()?) - } else if let Some(cmd) = live_retouch_command(d.tool) { - // The params `retouch_ui::finish_stroke` commits. - let mut p = if d.tool == Tool::HistoryBrush { crate::retouch_ui::history_brush_params(app) } else { crate::retouch_ui::clone_params(app)? }; - p["points"] = json!(d.points); - p["target"] = paint_target(app); - EngineStroke::Retouch(photocraft_engine::retouch_cmds::LiveRetouch::begin(&app.session, cmd, &p).ok()?) - } else { - let p = stroke_params(app, d, &app.stylus.stroke_points(&d.points)); - EngineStroke::Brush(Box::new(photocraft_engine::brush_cmds::LiveStroke::begin_with(&app.session, stroke_command(app, d.tool), &p).ok()?)) - }; - let n = STROKES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) & 0xff_ffff; - let damage = vec![stroke.bounds()]; - Some(LiveStroke { - stroke, - doc: st.doc.id, - revision: st.revision, - key: (1 << 44) | (n << 20), - damage, - fed: if d.tool == Tool::MixerBrush { 1 } else { d.points.len() }, - preview_failed: false, - }) -} - -/// Cancel uncommitted mixer paint when its document, tool or input context goes away. -pub(crate) fn cancel_mixer_on_context_change(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { - if !app.drag.as_ref().is_some_and(|drag| drag.tool == Tool::MixerBrush) { - return false; - } - let changed = app.ui.tool != Tool::MixerBrush - || app.live_stroke.as_ref().is_some_and(|live| !app.session.active().is_some_and(|st| st.doc.id == live.doc && st.revision == live.revision)); - if changed || ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { - app.drag = None; - app.live_stroke = None; - return true; - } - false -} - -/// Render the drag points the live stroke hasn't seen yet, with the pen pressure, tilt and -/// rotation the commit's `paint.stroke` gets for them. -fn feed_live_stroke(app: &mut PhotocraftApp) { - // A batched move replays several samples in one frame and calls this once at the end, so the - // per-sample calls from `tool_event` are skipped (see `canvas_view`). - if app.defer_live_stroke { - return; - } - let (Some(l), Some(d)) = (app.live_stroke.as_mut(), app.drag.as_ref()) else { return }; - if l.preview_failed { - return; - } - let pose = &app.stylus.stroke; - // The same times `stroke_points` gives the commit (from the drag's first point). - let t0 = app.stylus.point_ms(0); - let pts: Vec<_> = (l.fed..d.points.len()) - .filter_map(|i| { - let p = d.points.get(i)?; - let t = pose.get(i).or(pose.last()).copied().unwrap_or_default(); - let mut sp = photocraft_engine::paint::StrokePoint::new(p[0], p[1], p[2] as f32); - (sp.tilt_x, sp.tilt_y, sp.rotation) = (t[0], t[1], t[2]); - sp.time = app.stylus.point_ms(i) - t0; - Some(sp) - }) - .collect(); - if pts.is_empty() { - return; - } - l.fed = d.points.len(); - let started = crate::gpu_canvas::now_ms(); - match l.stroke.push(&pts) { - Ok(r) => l.damage.push(r), - Err(e) => { - if d.tool == Tool::MixerBrush { - // Keep the last valid preview and its document/revision guard. All input - // stays in the drag; release replays it without the preview tile budget. - l.preview_failed = true; - app.ui.status = e.to_string(); - app.ui.status_error = true; - } else { - app.live_stroke = None; - } - } - } - app.stroke_trace.stroke(crate::gpu_canvas::now_ms() - started); -} - -/// The points the live retouching stroke has rendered. -#[cfg(test)] -pub(crate) fn live_retouch_points(app: &PhotocraftApp) -> Option> { - match &app.live_stroke.as_ref()?.stroke { - EngineStroke::Retouch(l) => Some(l.points().to_vec()), - _ => None, - } -} - -/// Offer the Clone Stamp's or History Brush's live stroke, or a Dodge, Burn, Sponge, Blur, Sharpen -/// or Smudge one, with the drag points it hasn't rendered yet, to the command -/// `retouch_ui::finish_stroke` commits, which then takes its pixels instead of rendering the -/// stroke again. -fn offer_live_retouch(app: &mut PhotocraftApp, d: &Drag) { - let dab = crate::retouch_ui::dab_params(app, d.tool).is_some(); - if !dab && !matches!(d.tool, Tool::CloneStamp | Tool::HistoryBrush) { - return; - } - let Some(LiveStroke { stroke, fed, .. }) = app.live_stroke.take() else { return }; - let rest: Vec<_> = d.points.get(fed..).unwrap_or_default().iter().map(|q| photocraft_engine::paint::StrokePoint::new(q[0], q[1], q[2] as f32)).collect(); - // A refused offer (the brush changed mid-stroke, say) leaves the commit to render the stroke. - match stroke { - EngineStroke::Retouch(mut live) if !dab => { - if rest.is_empty() || live.push(&rest).is_ok() { - let _ = app.session.offer_live_retouch(live); - } - } - EngineStroke::Dab(mut live) if dab => { - if rest.is_empty() || live.push(&rest).is_ok() { - let _ = app.session.offer_live_dab(live); - } - } - _ => {} - } -} - -/// A pen tap (a drag still at its one press point when released) paints its dab at the highest -/// pressure the pen reached during the contact, not just the first sample's (#1798). A mouse is -/// unchanged at full pressure. -fn tap_at_peak_pressure(app: &mut PhotocraftApp) { - if app.stylus.sample().is_none() { - return; - } - let peak = f64::from(app.stylus.tap_pressure()); - let mut refresh_mixer = false; - if let Some(d) = app.drag.as_mut().filter(|d| d.points.len() == 1) - && let Some(p) = d.points.first_mut() - { - refresh_mixer = d.tool == Tool::MixerBrush && peak > p[2]; - p[2] = p[2].max(peak); - } - if refresh_mixer { - app.live_stroke = begin_live_stroke(app); - } -} - -/// While a stroke is held still, its point repeats this often (in ms) so time-based brush -/// features (airbrush build-up, smoothing catch-up) keep going, as when the pen moves. -const HOLD_REPEAT_MS: f64 = 16.0; - -/// Is the live stroke one that changes while the pointer is held still (airbrush Build-up, or -/// smoothing catching up)? Only then does a held pointer repeat its point and keep repainting. -fn stroke_wants_time(app: &PhotocraftApp) -> bool { - app.live_stroke.as_ref().is_some_and(|l| l.stroke.wants_time()) -} - -/// Time of sample `k` of the `n` samples a frame delivered, spread evenly after `base` (the -/// previous point) up to `now` (this frame): egui's pointer events carry no timestamps. -pub(crate) fn spread_ms(base: f64, now: f64, k: usize, n: usize) -> f64 { - // Not after `base` (or not comparable, NaN): every sample takes the frame time. - if n == 0 || now.partial_cmp(&base) != Some(std::cmp::Ordering::Greater) { - return now; - } - base + (now - base) * (k + 1) as f64 / n as f64 -} - -/// Tools whose gesture follows a freehand path (a polyline of the input points), so every pointer -/// sample the OS delivered improves the result. Other tools are driven by the pointer's latest -/// position (endpoints, anchors, guides), so feeding them a whole frame's moves only repeats work. -pub(crate) fn freehand_tool(tool: Tool) -> bool { - matches!( - tool, - Tool::Brush - | Tool::Pencil - | Tool::MixerBrush - | Tool::ColorReplacement - | Tool::Eraser - | Tool::BackgroundEraser - | Tool::HistoryBrush - | Tool::Remove - | Tool::ArtHistoryBrush - | Tool::SpotHealing - | Tool::Healing - | Tool::CloneStamp - | Tool::PatternStamp - | Tool::Blur - | Tool::Sharpen - | Tool::Smudge - | Tool::Dodge - | Tool::Burn - | Tool::Sponge - | Tool::Lasso - | Tool::MagneticLasso - | Tool::Patch - | Tool::ContentAwareMove - | Tool::QuickSelection - | Tool::FreeformPen - ) -} - -/// The pointer moves this frame delivered while `button` was held, in order. `down_at_start` is -/// whether the button was already down when the frame began. A move before a press or after a -/// release in the same frame is dropped, so a gesture never picks up input from outside its own -/// press..release interval. -fn pointer_moves(events: &[egui::Event], button: egui::PointerButton, down_at_start: bool) -> Vec { - let mut down = down_at_start; - let mut out = Vec::new(); - for e in events { - match e { - egui::Event::PointerButton { button: b, pressed, .. } if *b == button => down = *pressed, - egui::Event::PointerMoved(p) if down => out.push(*p), - _ => {} - } - } - out -} - -/// Modifiers attached to the pointer event itself. Some input sources provide these without a -/// separate `ModifiersChanged` event, so use them for click gestures before falling back to the -/// frame-wide modifier state. -fn pointer_button_modifiers(events: &[egui::Event], button: egui::PointerButton) -> Option { - events.iter().rev().find_map(|e| match e { - egui::Event::PointerButton { button: b, modifiers, .. } if *b == button => Some(*modifiers), - _ => None, - }) -} - -/// Abstract tool event, produced by the mouse or by automation (`ui.pointer`). -#[derive(Clone, Copy, Debug, PartialEq)] -pub enum ToolEvent { - Down { x: f64, y: f64, pressure: f32 }, - Move { x: f64, y: f64, pressure: f32 }, - Up { x: f64, y: f64 }, -} - -/// View › Show › Layer Edges: the colour of the active layer's outline. -pub(crate) const LAYER_EDGES: Color32 = Color32::from_rgb(0x2d, 0x8c, 0xeb); - -/// Document ↔ screen mapping for a canvas rect and a view. -#[derive(Clone, Copy, Debug)] -pub struct ViewXform { - pub rect: Rect, - pub zoom: f32, - pub center: [f32; 2], - /// View › Flip Horizontal: the view is mirrored left-right (the document is not). - pub flip: bool, - /// Camera rotation in degrees around [`Self::center`]. Clockwise (Y-down) is positive; applied - /// before flip. - pub rotation: f32, - /// View › Pixel Aspect Ratio Correction: a document pixel is drawn this many times wider than - /// tall (1 = square). Applied in document space, before rotation, so a rotated view still - /// shows the stretched image turned as a whole. - pub aspect: f32, -} - -impl ViewXform { - /// The main canvas's mapping for the active document as last laid out (inside the rulers). - pub fn active(app: &PhotocraftApp) -> Option { - let v = app.ui.views.get(app.session.active_index()?)?; - let (zoom, center) = - if v.zoom_animating && app.session.prefs().general.animated_zoom { v.display_camera.unwrap_or((v.zoom, v.center)) } else { (v.zoom, v.center) }; - Some( - Self { - rect: crate::rulers::content_rect(app, app.last_canvas_rect), - zoom: zoom / app.canvas_ppp(), - center, - flip: app.ui.view.flip_horizontal, - rotation: v.rotation, - aspect: app.ui.view.display_aspect(), - } - .pixel_aligned_for(app, app.canvas_ppp()), - ) - } - - fn pixel_aligned_for(self, app: &PhotocraftApp, ppp: f32) -> Self { - // Default Crop counter-moves the frame and camera with fractional pointer deltas. - // Preserve that continuous mapping so its fixed frame does not wobble during a drag. - if crate::crop_mode::moves_image(app) { self } else { self.pixel_aligned(ppp) } - } - - /// At integer physical magnifications, texel edges must land on display pixel edges. - /// Keep this derived camera shared by images, overlays and input without changing the saved pan. - fn pixel_aligned(mut self, ppp: f32) -> Self { - if !ppp.is_finite() || ppp <= 0.0 || !self.zoom.is_finite() || self.zoom <= 0.0 || !self.rotation.is_finite() || self.rotation.abs() >= 1e-8 { - return self; - } - let scale = vec2(self.zoom_x(), self.zoom) * ppp; - if !scale.is_finite() - || scale.x.round() < 1.0 - || scale.y.round() < 1.0 - || (scale.x - scale.x.round()).abs() > 1e-5 - || (scale.y - scale.y.round()).abs() > 1e-5 - { - return self; - } - let origin = self.to_screen(0.0, 0.0); - let physical = origin * ppp; - if !physical.is_finite() { - return self; - } - let aligned = pos2(physical.x.round(), physical.y.round()) / ppp; - let offset = self.unmap_vec((aligned - origin) / self.zoom); - let center = [self.center[0] - offset.x, self.center[1] - offset.y]; - if center.iter().all(|v| v.is_finite()) { - self.center = center; - } - self - } - - fn sincos(self) -> (f32, f32) { - if self.rotation.abs() < 1e-8 { - (1.0, 0.0) - } else { - let r = self.rotation.to_radians(); - (r.cos(), r.sin()) - } - } - - /// Document pixel width over height on screen: [`Self::aspect`], or 1 when it is unusable. - fn sx(self) -> f32 { - if self.aspect.is_finite() && self.aspect > 0.0 { self.aspect } else { 1.0 } - } - - /// Screen points per document pixel along the document's x axis. - pub fn zoom_x(&self) -> f32 { - self.zoom * self.sx() - } - - /// Unflip, unrotate and unstretch a screen-space vector (no zoom). Hand pan and zoom-about - /// use this. - pub fn unmap_vec(self, d: Vec2) -> Vec2 { - let d = if self.flip { vec2(-d.x, d.y) } else { d }; - let (c, s) = self.sincos(); - vec2((d.x * c + d.y * s) / self.sx(), -d.x * s + d.y * c) - } - - /// A document-space vector on screen: stretched, rotated, flipped and zoomed as the view - /// draws it (the inverse of [`Self::unmap_vec`], with the zoom). - pub fn map_vec(self, d: Vec2) -> Vec2 { - let (c, s) = self.sincos(); - let dx = d.x * self.sx(); - let v = vec2(dx * c - d.y * s, dx * s + d.y * c) * self.zoom; - if self.flip { vec2(-v.x, v.y) } else { v } - } - - pub fn to_screen(&self, x: f32, y: f32) -> Pos2 { - let (c, s) = self.sincos(); - let dx = (x - self.center[0]) * self.sx(); - let dy = y - self.center[1]; - let rx = dx * c - dy * s; - let ry = dx * s + dy * c; - let sx = if self.flip { -1.0 } else { 1.0 }; - self.rect.center() + vec2(rx * self.zoom * sx, ry * self.zoom) - } - pub fn to_doc(&self, p: Pos2) -> [f64; 2] { - let d = (p - self.rect.center()) / self.zoom; - let u = self.unmap_vec(d); - [(u.x + self.center[0]) as f64, (u.y + self.center[1]) as f64] - } - /// On-screen bounds of the image, including camera rotation and pixel aspect correction. - pub fn image_bounds(self, size: [u32; 2]) -> Rect { - let (c, s) = self.sincos(); - let w = size[0] as f32 * self.sx() * self.zoom; - let h = size[1] as f32 * self.zoom; - let center = self.to_screen(size[0] as f32 / 2.0, size[1] as f32 / 2.0); - Rect::from_center_size(center, vec2(c.abs() * w + s.abs() * h, s.abs() * w + c.abs() * h)) - } - pub fn doc_rect(&self, r: DRect) -> Rect { - let pts = [ - self.to_screen(r.x0 as f32, r.y0 as f32), - self.to_screen(r.x1 as f32, r.y0 as f32), - self.to_screen(r.x1 as f32, r.y1 as f32), - self.to_screen(r.x0 as f32, r.y1 as f32), - ]; - let mut min = pts[0]; - let mut max = pts[0]; - for p in pts { - min = min.min(p); - max = max.max(p); - } - Rect::from_min_max(min, max) - } -} - -/// Document point under a screen position on the main canvas, or `None` when the position is -/// outside it: the rulers are not part of the canvas, so drops on the ruler strip are not -/// canvas drops. Preset-panel drops and drag-and-drop placement share this so both land exactly -/// where the canvas draws. -pub fn doc_point_at(app: &PhotocraftApp, pos: Pos2) -> Option<[f64; 2]> { - let xf = ViewXform::active(app)?; - xf.rect.contains(pos).then(|| xf.to_doc(pos)) -} - -/// Fit the document into `area` (egui points) for a display with `ppp` physical pixels per -/// point; `View::zoom` is stored in physical pixels per document pixel. `aspect` is the -/// displayed pixel aspect ratio ([`ViewXform::aspect`]): the image is that much wider on screen. -pub fn fit_view(view: &mut View, doc: &Document, area: Vec2, ppp: f32, aspect: f32) { - let (w, h) = (doc.size.width as f32, doc.size.height as f32); - let shown_w = w * if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 }; - // Fit never magnifies past 100%: one image pixel per *physical* pixel, so the cap applies - // after the points → device pixels conversion (a 150% display would otherwise open at 150%). - let fit = ((area.x - 40.0) / shown_w).min((area.y - 40.0) / h) * ppp; - let zoom = crate::zoom_levels::clamp(fit.min(1.0), [doc.size.width, doc.size.height]); - view.zoom = zoom; - view.center = [w / 2.0, h / 2.0]; - view.fit_pending = false; - view.fill_pending = false; -} - -/// Ease a transient presentation camera over 220 ms without changing the requested camera. -fn animated_view(view: &mut View, xf: ViewXform, ppp: f32, animated_zoom: bool, time: f64) -> View { - if !animated_zoom { - view.request_zoom_animation(false); - } - let target = (view.zoom, view.center); - // Clamping, a canvas resize, or another camera command can make the original anchor - // incompatible with the requested camera. The target must always win. - if let Some((doc, screen)) = view.zoom_anchor { - let offset = xf.unmap_vec((pos2(screen[0], screen[1]) - xf.rect.center()) / (view.zoom / ppp)); - if (doc[0] as f32 - offset.x - view.center[0]).abs() > 0.01 || (doc[1] as f32 - offset.y - view.center[1]).abs() > 0.01 { - view.zoom_anchor = None; - } - } - let mut shown = view.clone(); - if view.zoom_animating { - if view.zoom_transition.is_none_or(|a| a.target != target) { - view.zoom_transition = Some(crate::state::ZoomTransition { from: view.display_camera.unwrap_or(target), target, started: time }); - } - if let Some(a) = view.zoom_transition { - let elapsed = (time - a.started) / 0.22; - let t = if elapsed.is_finite() { elapsed.clamp(0.0, 1.0) as f32 } else { 1.0 }; - let ease = t * t * (3.0 - 2.0 * t); - let lerp = |from: f32, to: f32| from + (to - from) * ease; - shown.zoom = lerp(a.from.0, target.0); - shown.center = [lerp(a.from.1[0], target.1[0]), lerp(a.from.1[1], target.1[1])]; - if let Some((doc, screen)) = view.zoom_anchor { - let zoom = shown.zoom / ppp; - if zoom.is_finite() && zoom > 0.0 { - let offset = xf.unmap_vec((pos2(screen[0], screen[1]) - xf.rect.center()) / zoom); - shown.center = [doc[0] as f32 - offset.x, doc[1] as f32 - offset.y]; - } - } - if t >= 1.0 { - view.zoom_animating = false; - } - } - } - if !view.zoom_animating { - shown.zoom = target.0; - shown.center = target.1; - view.zoom_anchor = None; - view.zoom_transition = None; - } - view.display_camera = Some((shown.zoom, shown.center)); - shown -} - -/// Centre the document and zoom until it fills the canvas. One axis can extend beyond the -/// viewport, matching the Hand tool's Fill Screen action. -pub fn fill_view(view: &mut View, doc: &Document, area: Vec2, ppp: f32, aspect: f32) { - let (w, h) = (doc.size.width as f32, doc.size.height as f32); - let shown_w = w * if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 }; - let points = (area.x / shown_w).max(area.y / h); - let zoom = crate::zoom_levels::clamp(points * ppp, [doc.size.width, doc.size.height]); - view.zoom = zoom; - view.center = [w / 2.0, h / 2.0]; - view.fit_pending = false; - view.fill_pending = false; -} - -fn checker(app: &mut PhotocraftApp, ctx: &egui::Context) -> egui::TextureId { - // Preferences › Transparency & Gamut colours (the texture is rebuilt when they change). - let [ca, cb] = app.session.prefs().transparency_and_gamut.colors(); - if app.prefs_rt.checker_key != Some([ca, cb]) { - app.prefs_rt.checker_key = Some([ca, cb]); - app.checker = None; - } - app.checker - .get_or_insert_with(|| { - let (a, b) = (Color32::from_rgb(ca[0], ca[1], ca[2]), Color32::from_rgb(cb[0], cb[1], cb[2])); - let img = egui::ColorImage::new([2, 2], vec![a, b, b, a]); - let opts = TextureOptions { - magnification: egui::TextureFilter::Nearest, - minification: egui::TextureFilter::Nearest, - wrap_mode: egui::TextureWrapMode::Repeat, - mipmap_mode: None, - }; - ctx.load_texture("checker", img, opts) - }) - .id() -} - -fn buffer_to_image(buf: &photocraft_compose::Buffer) -> egui::ColorImage { - // `buf.to_rgba8()` then `color_image`, fused: one parallel pass, no intermediate image. - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - let mut pixels = vec![egui::Color32::TRANSPARENT; buf.px.len()]; - let convert = |out: &mut [egui::Color32], src: &[[f32; 4]]| { - for (o, p) in out.iter_mut().zip(src) { - *o = egui::Color32::from_rgba_unmultiplied(q(p[0]), q(p[1]), q(p[2]), q(p[3])); - } - }; - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - pixels.par_chunks_mut(16 * 1024).zip(buf.px.par_chunks(16 * 1024)).for_each(|(o, s)| convert(o, s)); - } - #[cfg(target_arch = "wasm32")] - convert(&mut pixels, &buf.px); - egui::ColorImage::new([buf.rect.width() as usize, buf.rect.height() as usize], pixels) -} - -/// `img` as an egui image: `ColorImage::from_rgba_unmultiplied`, in parallel off wasm. egui's own -/// conversion runs on one thread and took 37 ms of a 24 MP canvas or preview update, three times -/// the quantize before it. -fn color_image(img: &photocraft_raster::Rgba8Image) -> egui::ColorImage { - let size = [img.width as usize, img.height as usize]; - let src = img.pixels.as_chunks::<4>().0; - let mut pixels = vec![egui::Color32::TRANSPARENT; src.len()]; - let convert = |out: &mut [egui::Color32], src: &[[u8; 4]]| { - for (o, &[r, g, b, a]) in out.iter_mut().zip(src) { - *o = egui::Color32::from_rgba_unmultiplied(r, g, b, a); - } - }; - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - pixels.par_chunks_mut(16 * 1024).zip(src.par_chunks(16 * 1024)).for_each(|(o, s)| convert(o, s)); - } - #[cfg(target_arch = "wasm32")] - convert(&mut pixels, src); - egui::ColorImage::new(size, pixels) -} - -/// A composite as monitor pixels: document profile → monitor profile (nothing to do in the -/// common sRGB-on-sRGB case). -pub(crate) fn display_image(display: Option<&photocraft_engine::display_color::CanvasDisplay>, buf: &photocraft_compose::Buffer) -> egui::ColorImage { - match display { - Some(d) if !d.is_identity() => color_image(&d.to_rgba8(buf)), - _ => buffer_to_image(buf), - } -} - -/// The canvas display of `doc` on `display` (`None`: the main window's) and a key that changes -/// with it (folded into the canvas caches' preview keys, so a monitor or profile change -/// re-renders). -pub(crate) fn canvas_display( - app: &PhotocraftApp, - doc: &Document, - display: Option, -) -> (Option>, u64) { - match app.session.color.canvas_display_for(doc, display.or(app.session.color.main_display)) { - Ok(d) => { - let k = d.key; - (Some(d), k) - } - Err(_) => (None, 0), - } -} - -/// [`canvas_display`]'s key for the GPU canvas texture: what the texture stores, the same on -/// every display (the display LUT holds the monitor profile). -fn texture_key(display: Option<&photocraft_engine::display_color::CanvasDisplay>) -> u64 { - display.map_or(0, |d| d.texture_key) -} - -/// `app.canvases` key: CPU canvas textures are per document and display (they hold monitor -/// values); the GPU canvas state uses [`GPU_OUTPUT`]. -pub(crate) fn cache_key(doc: photocraft_doc::DocId, display: Option) -> (photocraft_doc::DocId, u32) { - (doc, display.unwrap_or(0)) -} - -/// `app.canvases` output of the GPU canvas state (one texture per document for all displays). -pub(crate) const GPU_OUTPUT: u32 = u32::MAX; - -/// The document to render: the committed one, or a clone with the live adjustment preview applied. -pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Arc, u64) { - if let Some(shown) = crate::type_panels_ui::color_picker::display_doc(app, idx) { - return shown; - } - if let Some(shown) = crate::solid_fill_ui::display_doc(app, idx) { - return shown; - } - if let Some(shown) = crate::pattern_fill_ui::display_doc(app, idx) { - return shown; - } - if let Some(shown) = crate::shape_fill_ui::display_doc(app, idx) { - return shown; - } - if let Some(shown) = crate::type_transform::display_doc(app, idx) { - return shown; - } - if let Some(shown) = crate::type_font_preview::display_doc(app, idx) { - return shown; - } - // Vanishing Point's strokes over the document as it is now (the Layers panel may have - // changed it since the options bar synced them this frame). - crate::vp_ui::sync_preview(app); - // Puppet / Perspective Warp previews hide the layer they draw on a mesh. - if let Some(shown) = crate::distort_ui::display_doc(app, idx) { - return shown; - } - // Image › Adjustments dialog: a temporary adjustment layer clipped to the target. - if let Some(shown) = crate::adjust_preview::display_doc(app, idx) { - return shown; - } - // Gradient tool (live) drag, or a stop dragged in the Properties panel. - if let Some(shown) = crate::gradient_ui::display_doc(app, idx) { - return shown; - } - // Move tool drag: the moving layers at the pointer. - if let Some(shown) = crate::move_ui::display_doc(app, idx) { - return shown; - } - // Patch Tool drag: the selection healed from where the pointer is. - if let Some(shown) = crate::patch_preview::display_doc(app, idx) { - return shown; - } - // Content-Aware Move drag or box: the result, once computed in the background. It comes - // before the reorder preview, which is built from the session document and would drop it. - if let Some(shown) = crate::cam_preview::display_doc(app, idx) { - return shown; - } - // Live Layers-panel reorder previews the actual composite before mouse release. - if let Some(shown) = crate::layers_panel_ui::display_reorder(app, idx) { - return shown; - } - // A blend mode hovered in the Layers panel. - if let Some(shown) = crate::blend_preview::display_doc(app, idx) { - return shown; - } - crate::transform_tool::follow_edits(app); - let st = &app.session.documents()[idx]; - if let Some(l) = live_stroke(app, idx) { - return (l.stroke.doc().clone(), l.display_key()); - } - if let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) - && app.session.active_index() == Some(idx) - && pv.doc.id == st.doc.id - && st.doc.layer(photocraft_doc::LayerId(t.layer)).is_some() - { - return (pv.doc.clone(), (1 << 40) + 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); - // The Preview checkbox off shows the document as it was when the dialog opened; - // edits still land in the dialog state and OK applies them whatever it says. - let preview_on = style.and_then(|d| d.fields.get("preview")).and_then(serde_json::Value::as_bool).unwrap_or(true); - if style.is_none() || !preview_on { - app.style_preview = None; - } - if let Some(d) = style.filter(|_| preview_on) - && app.session.active_index() == Some(idx) - { - let fields = crate::layer_style::color_picker::preview_fields(app, d.id, &d.fields); - let key = (crate::layer_style::preview_hash(&fields) ^ st.revision.wrapping_mul(0x9e37_79b9_7f4a_7c15)) | 1 << 63; - if app.style_preview.as_ref().map(|p| p.0) != Some(key) { - let shown = crate::layer_style::preview_document(&st.doc, &app.session.patterns, &fields).map(std::sync::Arc::new); - if let Err(error) = &shown { - log::warn!("Layer Style preview: {error}"); - } - app.style_preview = Some((key, shown)); - } - if let Some((_, Ok(doc))) = &app.style_preview { - return (doc.clone(), key); - } - } - let revision = st.revision; - let snapshot = st.doc.clone(); - if let Some((layer, params)) = app.live_adjust.clone() - && let Some(l) = snapshot.layer(layer) - && let LayerContent::Adjustment(a) = &l.content - { - let key = crate::adjust_preview::live_key(app, &snapshot, revision, layer, ¶ms); - let shown = memo_display(app, &snapshot, key, || { - let kind = photocraft_engine::commands::adjustment_kind(a); - let preview = photocraft_engine::adjust_params::from_params(kind, ¶ms, Some(a), snapshot.mode).unwrap_or_else(|_| a.clone()); - let mut doc = (*snapshot).clone(); - if let Some(lm) = doc.layer_mut(layer) { - lm.content = LayerContent::Adjustment(preview); - } - Some(doc) - }); - if let Some(doc) = shown { - return (doc, key); - } - } - // Duotone documents display through their inks. - if let Some(shown) = memo_display(app, &snapshot, 1 << 41, || photocraft_engine::mode_cmds::display_document(&snapshot)) { - return (shown, 1 << 41); - } - (snapshot, 0) -} - -/// `display_doc`'s live-adjust and Duotone documents, built once per document snapshot and key -/// rather than on each of its 3–4 calls a frame (#4527): each build clones the whole document. -fn memo_display( - app: &mut PhotocraftApp, - snapshot: &std::sync::Arc, - key: u64, - build: impl FnOnce() -> Option, -) -> Option> { - let id = snapshot.id; - if let Some((doc, k, shown)) = app.display_memo.get(&id) - && *k == key - && doc.ptr_eq(&std::sync::Arc::downgrade(snapshot)) - { - return Some(shown.clone()); - } - let Some(shown) = build().map(std::sync::Arc::new) else { - app.display_memo.remove(&id); - return None; - }; - // Entries of closed documents go when another is stored. - app.display_memo.retain(|_, (doc, _, _)| doc.strong_count() > 0); - app.display_memo.insert(id, (std::sync::Arc::downgrade(snapshot), key, shown.clone())); - Some(shown) -} - -/// Longest side of the Navigator panel's image (about twice the panel's width, for HiDPI). -pub const NAVIGATOR_SIDE: u32 = 512; -/// The navigator image of a document: its snapshot, preview key and revision, and the texture. -pub(crate) type NavigatorCache = (std::sync::Weak, u64, u64, egui::TextureHandle); -/// How long adjustment-dialog settings must stay unchanged before the navigator shows them. -const NAVIGATOR_SETTLE_MS: f64 = 200.0; - -/// While a Move or Patch drag or a live paint stroke is under way, the navigator keeps its image -/// of document `idx` and catches up on release: each step of the drag is a new preview, and a -/// thumbnail composite of the whole document per step makes painting lag on large images. -fn navigator_waits_for_drag(app: &PhotocraftApp, idx: usize) -> bool { - crate::move_ui::showing(app) || crate::patch_preview::showing(app) || crate::cam_preview::showing(app) || live_stroke(app, idx).is_some() -} - -/// The Navigator panel's image of document `idx`. With the CPU canvas that is the canvas texture -/// itself; with the GPU canvas a thumbnail cached per revision, so an edit to a huge document -/// doesn't also pay a full-resolution CPU composite for the navigator. -/// The Navigator's preview from the GPU canvas (#4518): the main canvas's texture of the -/// document, drawn at `rect` with its own mip chain, so an edit costs no CPU composite. `None` -/// while the canvas isn't showing the plain document on the GPU (the CPU thumbnail then). -pub fn navigator_gpu_view(app: &PhotocraftApp, idx: usize, rect: Rect, ctx: &egui::Context) -> Option { - app.gpu.as_ref()?; - let st = app.session.documents().get(idx)?; - let params = *app.navigator_gpu.get(&st.doc.id)?; - let [w, h] = params.doc_size; - if w == 0 || h == 0 || !rect.is_positive() || [st.doc.size.width, st.doc.size.height] != params.doc_size { - return None; - } - Some(crate::gpu_canvas::ViewParams { - zoom: rect.width() / w as f32, - center: [w as f32 / 2.0, h as f32 / 2.0], - rotation: 0.0, - shadow: false, - pixel_grid: false, - view_key: egui::Id::unique(("pc-navigator", ctx.viewport_id(), idx)).value(), - offset: [0.0, 0.0], - ..params - }) -} - -/// Frames the Navigator waits for the GPU canvas to draw a document it hasn't drawn yet, rather -/// than build a CPU thumbnail it would only use once (a full composite on a large document). -const NAVIGATOR_WAIT_FRAMES: u32 = 3; - -/// Whether the Navigator should wait a frame for the GPU canvas (#4518): the GPU canvas is on but -/// hasn't drawn document `idx` yet (the Navigator can draw before the canvas in a frame). After -/// [`NAVIGATOR_WAIT_FRAMES`] it stops waiting, so it never stays empty. -pub fn navigator_waits_for_gpu(app: &PhotocraftApp, idx: usize, ctx: &egui::Context) -> bool { - if app.gpu.is_none() { - return false; - } - let Some(id) = app.session.documents().get(idx).map(|st| st.doc.id) else { return false }; - if app.canvases.keys().any(|(d, _)| *d == id) { - return false; - } - let key = egui::Id::unique(("navigator-waits", id.0)); - let waited = ctx.data(|d| d.get_temp::(key)).unwrap_or(0); - if waited >= NAVIGATOR_WAIT_FRAMES { - return false; - } - ctx.data_mut(|d| d.insert_temp(key, waited + 1)); - ctx.request_repaint(); - true -} - -pub fn navigator_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize) -> Option { - if app.gpu.is_none() { - 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 (doc, preview_key) = display_doc(app, idx); - let (display, display_key) = canvas_display(app, &doc, None); - let preview_key = preview_key ^ display_key; - let cached = app.navigator_textures.get(&id).cloned(); - if let Some((r, p, _, t)) = &cached - && r.ptr_eq(&snapshot) - && *p == preview_key - { - return Some(t.id()); - } - if let Some((_, _, _, t)) = &cached - && navigator_waits_for_drag(app, idx) - { - return Some(t.id()); - } - // While an adjustment dialog's settings are changing, the navigator keeps its image and - // catches up once they settle (a thumbnail composite per change would cost more than the canvas). - if let Some((r, _, _, t)) = &cached - && r.ptr_eq(&snapshot) - && crate::adjust_preview::settling(app, NAVIGATOR_SETTLE_MS) - { - ctx.request_repaint_after(std::time::Duration::from_millis(NAVIGATOR_SETTLE_MS as u64)); - 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 - // 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) - && let Some(d) = last_damage - && t.size() == [size.0 as usize, size.1 as usize] - { - let mut t = t.clone(); - if !d.is_empty() { - let buf = photocraft_compose::render_reduced_damage(&doc, size.0, size.1, d.inflate(effect_reach(&doc.layers))); - let r = buf.rect; - if !r.is_empty() { - t.set_partial([r.x0 as usize, r.y0 as usize], display_image(display.as_deref(), &buf), TextureOptions::LINEAR); - } - } - app.perf.span("navigator", crate::gpu_canvas::now_ms() - t0); - app.navigator_textures.insert(id, (snapshot, preview_key, revision, t.clone())); - return Some(t.id()); - } - let image = display_image(display.as_deref(), &photocraft_compose::thumbnail_buffer(&doc, NAVIGATOR_SIDE)); - let tex = match cached { - Some((_, _, _, mut t)) => { - t.set(image, TextureOptions::LINEAR); - t - } - None => ctx.load_texture(format!("navigator-{}", id.0), image, TextureOptions::LINEAR), - }; - app.perf.span("navigator", crate::gpu_canvas::now_ms() - t0); - app.navigator_textures.insert(id, (snapshot, preview_key, revision, tex.clone())); - Some(tex.id()) -} - -/// The CPU canvas texture's sampling (#4810). Zoomed in, a full-resolution texture shows each -/// document pixel as a crisp square, as the GPU canvas's sharp nearest filter and Photoshop do; -/// zoomed out it is still filtered. A reduced texture (`factor` > 1) stays bilinear: its texels -/// are averages of several pixels, and squares of them would be blocks the image doesn't have. -fn canvas_texture_options(factor: u32) -> TextureOptions { - if factor > 1 { TextureOptions::LINEAR } else { TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR } } -} - -/// Make sure the canvas texture for document `idx` on `display` is current; returns (texture -/// id, scale). -pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, display: Option) -> Option<(egui::TextureId, f32)> { - ensure_texture_in_view(app, ctx, idx, display, None).map(|t| (t.texture, t.scale)) -} - -/// The document area a filter preview of `preview` size covers, for a `doc` sized document -/// previewed at proxy factor `k`: the document's bounds when it is the document's size (reduced by -/// `k`), else its own size (times `k`) centred on the document's centre, as the GPU canvas centres -/// a size-changing preview (Image › Rotation). -fn preview_bounds(doc: photocraft_geom::Size, preview: photocraft_geom::Size, k: u32) -> DRect { - let k = k.max(1); - let full = DRect::from_size(doc); - if doc.width.div_ceil(k) == preview.width && doc.height.div_ceil(k) == preview.height { - return full; - } - let side = |p: u32, d: u32| { - let covered = i64::from(p) * i64::from(k); - let x0 = (i64::from(d) - covered).div_euclid(2); - let clamp = |v: i64| v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32; - (clamp(x0), clamp(x0 + covered)) - }; - let (x0, x1) = side(preview.width, doc.width); - let (y0, y1) = side(preview.height, doc.height); - DRect::new(x0, y0, x1, y1) -} - -/// [`ensure_texture`], and for a canvas showing `view` of a document too large for one -/// full-resolution texture, the detail texture of the part in view ([`detail_plan`], #7568). -pub(crate) fn ensure_texture_in_view( - app: &mut PhotocraftApp, - ctx: &egui::Context, - idx: usize, - display: Option, - view: Option, -) -> Option { - 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) - }; - 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 - // canvas (no usable GPU, a flipped or pixel-aspect-corrected view, a GPU fallback) showed the - // document unfiltered. Its result is drawn here instead, as the channel views draw it. - // A preview reduced for a zoomed-out view (a proxy, factor `k`) covers the whole document at - // its own size. One whose dimensions change otherwise (Image › Rotation) covers its own area, - // centred on the document's, as the GPU canvas draws it (`preview_bounds`). - let committed = app.session.documents().get(idx).map(|st| st.doc.bounds()).unwrap_or(doc.bounds()); - let mut bounds = committed; - let mut reduced = false; - if let Some((preview, key)) = filter_channel_preview(app, idx, ctx) { - let k = app.filter_preview.as_ref().map_or(1, |p| p.key.k.max(1)); - bounds = preview_bounds(committed.size(), preview.size, k); - (doc, preview_key, reduced) = (preview, key, k > 1); - } - // Detail textures and partial redraws work in the document's own pixels. - let reduced = reduced || bounds != committed; - let view = view.filter(|_| !reduced); - // A flipped view draws a GPU machine's canvas through here: an adjustment dialog's preview of - // a large document (taken by the GPU path) would cost a full-size CPU composite per change. - if crate::adjust_preview::shown_key(app) == Some(preview_key) - && let Some(st) = app.session.documents().get(idx) - && crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(app)) > 1 - { - (doc, preview_key) = (st.doc.clone(), 0); - } - let (display, display_key) = canvas_display(app, &doc, output); - let seen = app.canvases.get(&cache_key(id, output)).map(|c| (c.tex_revision, c.tex_preview_key)); - let damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, preview_key), display_key, last_damage)).filter(|_| !reduced); - // The detail texture can lag the whole-document one (made or moved later): its own damage. - let detail_seen = view.and_then(|v| { - let c = app.canvases.get(&cache_key(id, output))?; - c.detail.iter().find(|(k, _)| *k == v.key).map(|(_, d)| (d.revision, d.preview_key)) - }); - let detail_damage = match detail_seen { - Some(s) if Some(s) == seen => damage, - Some(s) => damage_since(app, idx, s, (revision, preview_key), display_key, last_damage), - None => None, - }; - let preview_key = preview_key ^ display_key; - let cache = app.canvases.entry(cache_key(id, output)).or_insert(CanvasCache { - revision: 0, - texture: None, - scale: 1.0, - preview_key: 0, - on_gpu: false, - tex_revision: 0, - tex_preview_key: 0, - texture_opaque: false, - grid: None, - detail: Vec::new(), - }); - if cache.tex_revision != revision || cache.texture.is_none() || cache.tex_preview_key != preview_key { - let t0 = crate::gpu_canvas::now_ms(); - let factor = texture_factor([doc.size.width, doc.size.height], texture_side(ctx)); - let (w, h) = ((doc.size.width / factor).max(1), (doc.size.height / factor).max(1)); - let current = cache.texture.as_mut().filter(|t| t.size() == [w as usize, h as usize]); - if let (Some(d), Some(t)) = (damage, current) { - // Only what the edit or stroke touched: the reduced texture's pixels over it, with the - // values the whole reduction gives them (factor 1 is the plain composite of `d`). - let buf = photocraft_compose::render_reduced_damage(&doc, w, h, d); - let r = buf.rect; - if !r.is_empty() { - let t1 = crate::gpu_canvas::now_ms(); - let image = display_image(display.as_deref(), &buf); - // Partial uploads can disprove opacity. Once transparent, conservatively keep - // the checker until a full upload proves the whole texture opaque again. - cache.texture_opaque &= image.pixels.iter().all(|p| p.is_opaque()); - t.set_partial([r.x0 as usize, r.y0 as usize], image, canvas_texture_options(factor)); - let px = (r.width() as u64 * r.height() as u64).saturating_mul(u64::from(factor).pow(2)); - app.perf.record("rect", px, t1 - t0, crate::gpu_canvas::now_ms() - t1); - } - } else { - // Reduced in bands straight from the compositor: no full-size composite in memory. - let full = photocraft_compose::render_reduced(&doc, w, h); - let t1 = crate::gpu_canvas::now_ms(); - let (img, scale) = (display_image(display.as_deref(), &full), 1.0 / factor as f32); - cache.texture_opaque = img.pixels.iter().all(|p| p.is_opaque()); - match cache.texture.as_mut() { - Some(t) if t.size() == img.size => t.set(img, canvas_texture_options(factor)), - _ => cache.texture = Some(ctx.load_texture(format!("canvas-{}-{}", id.0, cache_key(id, output).1), img, canvas_texture_options(factor))), - } - cache.scale = scale; - app.perf.record("full", doc.size.width as u64 * doc.size.height as u64, t1 - t0, crate::gpu_canvas::now_ms() - t1); - } - cache.tex_revision = revision; - cache.tex_preview_key = preview_key; - } - let texture = cache.texture.as_ref()?.id(); - let scale = cache.scale; - // Without a view (the Navigator's call) the views' detail textures stay as they are. - let Some(view) = view else { return Some(CpuTextures { texture, scale, bounds, detail: None }) }; - let old = cache.detail.iter().position(|(k, _)| *k == view.key).map(|i| cache.detail.remove(i).1); - let Some(plan) = detail_plan([doc.size.width, doc.size.height], texture_side(ctx), view.zoom, view.visible) else { - return Some(CpuTextures { texture, scale, bounds, detail: None }); - }; - let t0 = crate::gpu_canvas::now_ms(); - let name = format!("canvas-detail-{}-{}", id.0, cache_key(id, output).1); - let detail = update_detail(ctx, &doc, display.as_deref(), name, plan, old, detail_damage, (revision, preview_key)); - if detail.as_ref().is_some_and(|d| d.rendered) { - app.perf.span("canvas detail", crate::gpu_canvas::now_ms() - t0); - } - let Some(mut detail) = detail else { return Some(CpuTextures { texture, scale, bounds, detail: None }) }; - detail.rendered = false; - // Where its texels lie in the document: reduced texel t covers [t·W/w, (t+1)·W/w). - let (w, h) = ((doc.size.width / plan.factor).max(1), (doc.size.height / plan.factor).max(1)); - let (sx, sy) = (doc.size.width as f32 / w as f32, doc.size.height as f32 / h as f32); - let out = detail.out; - let shown = (detail.texture.id(), [out.x0 as f32 * sx, out.y0 as f32 * sy, out.x1 as f32 * sx, out.y1 as f32 * sy]); - cache.detail.push((view.key, detail)); - // Views that stopped asking (a closed window, a zoom out) give theirs up past a few. - if cache.detail.len() > MAX_DETAIL_VIEWS { - cache.detail.remove(0); - } - Some(CpuTextures { texture, scale, bounds, detail: Some(shown) }) -} - -/// Most CPU canvas views of one document on one display that keep a detail texture. -const MAX_DETAIL_VIEWS: usize = 4; - -/// The detail texture for `plan` at document state `now` (revision, preview key with the display -/// key folded in): `old` as it is when current, updated over `damage` when only that changed -/// within the same region, or rendered again. `None` when the region holds no texels. -#[allow(clippy::too_many_arguments)] -fn update_detail( - ctx: &egui::Context, - doc: &Document, - display: Option<&photocraft_engine::display_color::CanvasDisplay>, - name: String, - plan: DetailPlan, - old: Option, - damage: Option, - now: (u64, u64), -) -> Option { - let (w, h) = ((doc.size.width / plan.factor).max(1), (doc.size.height / plan.factor).max(1)); - let options = canvas_texture_options(plan.factor); - let (kept, spare) = match old { - Some(d) if d.plan == plan => (Some(d), None), - d => (None, d.map(|d| d.texture)), - }; - if let Some(mut d) = kept { - if (d.revision, d.preview_key) == now { - return Some(d); - } - // An edit or a stroke step in view: only the texels it touched. - if let Some(dmg) = damage { - let dmg = dmg.intersect(&plan.region); - let buf = (!dmg.is_empty()).then(|| photocraft_compose::render_reduced_damage(doc, w, h, dmg)); - let fits = buf.as_ref().is_none_or(|b| d.out.contains_rect(&b.rect)); - if fits { - if let Some(b) = buf.filter(|b| !b.rect.is_empty()) { - let at = [b.rect.x0.abs_diff(d.out.x0) as usize, b.rect.y0.abs_diff(d.out.y0) as usize]; - d.texture.set_partial(at, display_image(display, &b), options); - d.rendered = true; - } - (d.revision, d.preview_key) = now; - return Some(d); - } - } - return render_detail(ctx, doc, display, name, plan, Some(d.texture), now); - } - render_detail(ctx, doc, display, name, plan, spare, now) -} - -/// [`update_detail`]'s whole render of `plan`'s region, into `texture` when it is the same size. -fn render_detail( - ctx: &egui::Context, - doc: &Document, - display: Option<&photocraft_engine::display_color::CanvasDisplay>, - name: String, - plan: DetailPlan, - texture: Option, - now: (u64, u64), -) -> Option { - let (w, h) = ((doc.size.width / plan.factor).max(1), (doc.size.height / plan.factor).max(1)); - let options = canvas_texture_options(plan.factor); - let buf = photocraft_compose::render_reduced_damage(doc, w, h, plan.region); - let out = buf.rect; - if out.is_empty() { - return None; - } - let img = display_image(display, &buf); - let texture = match texture { - Some(mut t) if t.size() == img.size => { - t.set(img, options); - t - } - _ => ctx.load_texture(name, img, options), - }; - Some(DetailTexture { texture, plan, out, revision: now.0, preview_key: now.1, rendered: true }) -} - -/// 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 { - // 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 - && let Some(st) = app.session.documents().get(idx) - && let Some(c) = app.committed_stroke.as_ref().filter(|c| c.doc == st.doc.id && c.revision == now.0) - && let Some(r) = c.since(seen.1 ^ display_key) - { - let r = if c.relayout.is_empty() { - r - } else if r.is_empty() { - c.relayout - } else { - r.union(&c.relayout) - }; - 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 { - return last_damage; - } - 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) - { - return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); - } - // Between an adjustment dialog's previews (and the document): the target's area. - if seen.0 == now.0 - && let Some(st) = app.session.documents().get(idx) - && let Some(r) = crate::adjust_preview::switch_region(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) - { - return Some(r); - } - // Between a Properties-panel adjustment-layer drag's previews (and the document): the - // layer's area. Without this every parameter value recomposited the whole document (#6839). - if seen.0 == now.0 - && let Some(st) = app.session.documents().get(idx) - && let Some(r) = crate::adjust_preview::live_switch_region(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) - { - 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()))) - && 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) - { - return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); - } - // Between a Patch drag's previews: the areas they healed. - if seen.0 == now.0 - && let Some(st) = app.session.documents().get(idx) - && let Some(r) = crate::patch_preview::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) - { - return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); - } - // Between Vanishing Point stamp previews (and the document): the areas the strokes painted. - if seen.0 == now.0 - && let Some(st) = app.session.documents().get(idx) - && let Some(r) = crate::vp_ui::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) - { - return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); - } - // Between hovered blend modes (and the document): where the layer's blending shows. - if seen.0 == now.0 - && let Some(st) = app.session.documents().get(idx) - && let Some(r) = crate::blend_preview::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) - { - return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); - } - // Between hovered fonts (and the document): the text layer's old/new ink bounds. - if seen.0 == now.0 - && let Some(st) = app.session.documents().get(idx) - && let Some(r) = crate::type_font_preview::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) - { - return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); - } - let l = live_stroke(app, idx).filter(|l| seen.0 == now.0 && l.display_key() == now.1)?; - let r = l.since(seen.1 ^ display_key)?; - Some(if r.is_empty() { r } else { r.inflate(effect_reach(&l.stroke.doc().layers)) }) -} - -/// Document `doc`'s canvas caches showed a preview that the edit just committed reproduces -/// (`was_preview` tells its keys): count it as the document itself, so the commit's damage rect -/// refreshes only that area instead of everything. -pub(crate) fn shown_as_document(app: &mut PhotocraftApp, doc: photocraft_doc::DocId, was_preview: impl Fn(u64) -> bool) { - let Some(d) = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| st.doc.clone()) else { return }; - if let Some(c) = app.channel_views.get_mut(&doc.0) - && was_preview(c.preview_key) - { - c.preview_key = 0; - } - // Every display's cache of the document: the GPU state folds in the texture key, CPU - // textures their display's key. - let outputs: Vec = app.canvases.keys().filter(|k| k.0 == doc).map(|k| k.1).collect(); - for out in outputs { - let (display, key) = canvas_display(app, &d, (out != 0 && out != GPU_OUTPUT).then_some(out)); - let gpu_key = texture_key(display.as_deref()); - let Some(c) = app.canvases.get_mut(&(doc, out)) else { continue }; - if was_preview(c.preview_key ^ gpu_key) { - c.preview_key = gpu_key; - } - if was_preview(c.tex_preview_key ^ key) { - c.tex_preview_key = key; - } - } -} - -/// How far beyond an edit's damage rect the composite can change: layer effects (shadows, glows, -/// strokes, …) on the edited layer and on the groups around it reach that far. -pub(crate) fn effect_reach(layers: &[photocraft_doc::Layer]) -> i32 { - layers - .iter() - .filter(|l| l.visible) - .map(|l| { - let own = if photocraft_compose::effects::has_effects(l) { photocraft_compose::effects::margin(l) } else { 0 }; - let inner = match &l.content { - LayerContent::Group(g) => effect_reach(&g.children), - _ => 0, - }; - own + inner - }) - .max() - .unwrap_or(0) -} - -/// GPU path: make sure document `idx` is current in the GPU canvas. Edits draw their damage; -/// unchanged lower-stack composites can be reused by the compositor inside that region. -/// Returns false if there is no GPU canvas. -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)) - else { - return false; - }; - let (doc, raw_key) = display_doc(app, idx); - let (display, _) = canvas_display(app, &doc, None); - // Repeated pattern tiles sample the same texture, including pixels outside the unwrapped - // viewport. Refresh the affected document region while Pattern Preview is enabled. - let blend_visible = if app.ui.view.pattern_preview { doc.bounds() } else { visible }; - // The texture is shared by every display: only what it stores counts, not the monitor. - let display_key = texture_key(display.as_deref()); - let seen = app.canvases.get(&(id, GPU_OUTPUT)).map(|c| (c.revision, c.preview_key)); - let mut damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, raw_key), display_key, last_damage)); - if let Some(region) = damage { - damage = Some(crate::blend_preview::clip_damage(app, id, revision, raw_key, region, blend_visible)); - } - // To an adjustment dialog's preview: only what the view shows now (the rest as it moves there). - if damage.is_some() - && let Some(r) = seen.filter(|s| s.0 == revision).and_then(|s| crate::adjust_preview::switch_region(app, id, revision, s.1 ^ display_key, raw_key)) - { - damage = Some(crate::adjust_preview::switch_damage(app, raw_key, r, visible)); - } - // The same for a Properties-panel drag's previews. - if damage.is_some() - && let Some(r) = seen.filter(|s| s.0 == revision).and_then(|s| crate::adjust_preview::live_switch_region(app, id, revision, s.1 ^ display_key, raw_key)) - { - damage = Some(crate::adjust_preview::live_switch_damage(app, raw_key, r, visible)); - } - let preview_key = raw_key ^ display_key; - // The Navigator may draw this texture while it holds the plain document or a drag preview - // that updates the full texture (not an adjustment preview composited only where the view is). - if raw_key == 0 || navigator_waits_for_drag(app, idx) { - app.navigator_plain.insert(id); - } else { - app.navigator_plain.remove(&id); - app.navigator_gpu.remove(&id); - } - let size = [doc.size.width, doc.size.height]; - // A full CPU redraw running in the background: show the blocks it has finished. - crate::background_redraw::poll(app, &gpu, id); - let cache = app.canvases.entry((id, GPU_OUTPUT)).or_insert(CanvasCache { - revision: 0, - texture: None, - scale: 1.0, - preview_key: 0, - on_gpu: false, - tex_revision: 0, - tex_preview_key: 0, - texture_opaque: false, - grid: None, - detail: Vec::new(), - }); - let present = cache.on_gpu && gpu.has(id.0, size); - let current = cache.revision == revision && cache.preview_key == preview_key; - // GPU Memory or Memory Usage changed with nothing to redraw: the new budget, and whether the - // layers fit it, show at once (the status bar's GPU Memory Full). - if present && app.perf.gpu_budget_allowance != budget_allowance(app) { - gpu_budget(app, &gpu, idx, false, visible); - } - // Switched to a document whose canvas is already current: size the budget for it and measure - // whether its layers fit, so GPU Memory Full shows (or clears) at once rather than at its - // next full refresh. Once per switch: the fit then names this document. - if present && app.perf.gpu_layer_fit.is_none_or(|f| f.doc != id.0) { - gpu_budget(app, &gpu, idx, false, visible); - let fit = gpu.measure_fit(&doc).unwrap_or(crate::gpu_canvas::LayerFit { doc: id.0, needed: 0, budget: 0 }); - app.perf.gpu_layer_fit = Some(fit); - } - if present && current { - // An adjustment preview composited where the view was: catch up where it moved to. - if let Some(r) = crate::adjust_preview::uncovered(app, id, raw_key, visible) { - let r = gpu.refresh(id.0, &doc, Some(r), display.as_deref()); - app.perf.record_refresh(&r); - } - if let Some(r) = crate::adjust_preview::live_uncovered(app, id, raw_key, visible) { - let r = gpu.refresh(id.0, &doc, Some(r), display.as_deref()); - app.perf.record_refresh(&r); - } - // Blend previews keep offscreen pixels untouched until the view reaches them. - // Use the normal refresh path so CPU fallback and pending redraws stay synchronized. - damage = crate::blend_preview::uncovered(app, id, revision, raw_key, blend_visible); - if damage.is_none() { - return true; - } - } - // Display textures for a canvas this large would not fit the GPU: the reduced CPU canvas - // draws it (checked before the memory budget, which walks the history, every frame). - if !gpu.fits_canvas(&doc) { - crate::background_redraw::cancel(app, id); - // Drawn on the CPU canvas: no layer budget applies to it. - if app.perf.gpu_layer_fit.is_some_and(|f| f.doc == id.0) { - app.perf.gpu_layer_fit = None; - } - return false; - } - let partial = present && damage.is_some(); - gpu_budget(app, &gpu, idx, partial, visible); - let defer = crate::background_redraw::enabled(app); - let r = gpu.refresh_with(id.0, &doc, if partial { damage } else { None }, display.as_deref(), defer); - app.perf.gpu_layer_fit = gpu.layer_fit(); - if r.kind == "lost" || r.kind == crate::gpu_canvas::REFRESH_OVER_BUDGET { - // The device is gone (`gpu_status` then drops the GPU canvas) or the canvas is over the - // texture budget: draw this frame on the CPU path. - crate::background_redraw::cancel(app, id); - return false; - } - if r.kind == crate::gpu_canvas::REFRESH_DEFERRED { - // Composited off the UI thread, the visible part first (#4024). - let region = if partial { damage.unwrap_or(doc.bounds()) } else { doc.bounds() }; - crate::background_redraw::start(app, ctx, &gpu, doc.clone(), display.clone(), visible, region, r.fallback.clone()); - } else if partial { - // The edit drew its damage; blocks of a running redraw still to come follow the edit. - crate::background_redraw::restart(app, ctx, &gpu, doc.clone(), display.clone(), visible); - } else { - crate::background_redraw::cancel(app, id); - } - if let Some(e) = &r.fallback - && app.perf.gpu_fallback.as_deref() != Some(e.as_str()) - { - log::info!("{e}; using the CPU compositor"); - } - if r.kind != crate::gpu_canvas::REFRESH_DEFERRED { - app.perf.record_refresh(&r); - } - if r.kind == "full" { - crate::notices::slow_cpu_refresh(app, id.0, r.composite_ms + r.upload_ms, r.fallback.as_deref()); - } - if r.kind.starts_with("gpu") { - app.perf.gpu_uploads = r.uploads; - } else { - app.perf.gpu_fallback = r.fallback; - } - let Some(cache) = app.canvases.get_mut(&(id, GPU_OUTPUT)) else { return true }; - cache.revision = revision; - cache.preview_key = preview_key; - cache.on_gpu = true; - cache.texture = None; - true -} - -/// Point the wgpu compositor at what the view shows, and size its memory budget from GPU Memory, -/// or Memory Usage, the document's pixels and History (charged where the GPU shares the system's -/// memory), physical memory and the GPU's own: on full refreshes (pixels counted once per -/// structural change, not per brush dab) and whenever either preference changes. -fn gpu_budget(app: &mut PhotocraftApp, gpu: &crate::gpu_canvas::GpuCanvas, idx: usize, partial: bool, visible: DRect) { - gpu.set_focus(Some(visible)); - let allowance = budget_allowance(app); - let changed = app.perf.gpu_budget_allowance != allowance; - if partial && !changed && gpu.memory_budget().is_some() { - return; - } - let Some(st) = app.session.documents().get(idx) else { return }; - let pixels = st.memory_bytes() as u64; - let budget = crate::gpu_canvas::memory_budget(allowance.0, pixels, crate::gpu_canvas::physical_memory(), gpu.video_memory(), allowance.1); - gpu.set_memory_budget(budget); - app.perf.gpu_budget_mb = budget >> 20; - app.perf.gpu_budget_allowance = allowance; - if changed && let Some(fit) = gpu.measure_fit(&st.doc) { - app.perf.gpu_layer_fit = Some(fit); - } -} - -/// Memory Usage and GPU Memory (Preferences › Performance), in bytes. -fn budget_allowance(app: &PhotocraftApp) -> (u64, u64) { - let performance = &app.session.prefs().performance; - (u64::from(performance.memory_usage_mb).saturating_mul(1 << 20), u64::from(performance.gpu_memory_mb).saturating_mul(1 << 20)) -} - -/// The proxy factor of a live preview of filter `cmd` with `params` on `doc`, the active document: -/// reduced on a large document (Preferences › Performance › Low Resolution Previews), except for -/// filters whose features don't scale with a proxy (#2063), and never coarser than the active view, -/// so at 100 % the preview shows every pixel instead of k-pixel blocks (#6326, as adjustment -/// previews have since #5764). Zoomed out, the proxy keeps previews of large documents fast. -/// -/// The in-dialog preview window ([`crate::filter_preview_ui`]) sizes its own textures from this -/// too, so the canvas and the window never disagree about the factor. -/// -/// Full resolution costs a whole filter per parameter change, which only the background worker -/// absorbs. The web build has no worker and computes the preview inline on the UI thread (#1676), -/// where that would freeze the page: there the document's proxy stands. The test and -/// `PHOTOCRAFT_INLINE_JOBS` inline paths keep the cap deliberately, because `background_jobs` is -/// flipped mid-session (a shell save during `actions.play`): a factor that followed it would change -/// [`crate::filter_dialog::FilterPreviewKey`] under a finished preview and recompute it inline, -/// the very stall this avoids. -pub(crate) fn filter_preview_factor(app: &PhotocraftApp, doc: &Document, cmd: &str, params: &serde_json::Value) -> u32 { - // A smart filter edit re-renders the whole stack: every stage constrains the factor. - let k = crate::filter_dialog::smart_preview_factor(doc, cmd, params, crate::proxy::preview_factor(doc, crate::proxy::reduced_previews(app))); - if cfg!(target_arch = "wasm32") { k } else { crate::proxy::view_factor(k, app.current_zoom()) } -} - -/// Live preview for an open filter dialog: run the filter on the proxy and upload it. With -/// background jobs (the desktop app) it computes on one background worker -/// (`filter_preview_worker`); otherwise (web, tests, `PHOTOCRAFT_INLINE_JOBS`) it keeps the -/// deterministic inline path (#1676), which also lets headless/CPU tests inspect previews -/// without a GPU texture. -pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &egui::Context) -> Option<(u32, u64, [u32; 2])> { - if let Some(held) = committed_filter_preview(app, idx) { - return held; - } - // Command dialogs always edit the active document. Never show their preview in another tab. - if app.session.active_index() != Some(idx) { - return None; - } - if crate::adjust_preview::on_layer(app, idx) { - return None; - } - let d = app.ui.dialogs.iter().find(|d| d.fields.contains_key("__filter"))?; - if d.fields.get("__preview").and_then(serde_json::Value::as_bool) != Some(true) { - return None; - } - let cmd = d.fields.get("__command")?.as_str()?.to_string(); - // Previews edit what the command will: a targeted layer mask included (#780). - let (cmd, mut params) = if d.fields.contains_key("__smartFilter") { - crate::smart_filter_dialog::edit_command(app, &d.fields).ok()? - } else { - (cmd.clone(), app.with_mask_target(&cmd, crate::filter_dialog::params_of(&d.fields))) - }; - // Select and Mask previews in its view mode; holding X shows the image without one. - if crate::select_mask_view::owns(&d.fields) { - if crate::select_mask_view::hides_view(&d.fields) { - return None; - } - params = crate::select_mask_view::request_params(&d.fields, params); - } - let st = app.session.documents().get(idx)?; - let k = filter_preview_factor(app, &st.doc, &cmd, ¶ms); - let request = crate::filter_dialog::FilterPreviewKey { - doc: st.doc.id, - revision: st.revision, - dialog: d.id, - active: st.active_layer, - target: st.channel_view.target, - command: cmd, - params, - k, - }; - let key = request.doc.0 ^ (1u64 << 61); - // Every filter's preview computes off the UI thread in the desktop app: Gaussian Blur at - // 1000 px takes long enough to freeze the window. Once the slider settles, a preview still - // running for an older value is cancelled. - #[cfg(not(target_arch = "wasm32"))] - if app.background_jobs { - app.filter_preview_worker.supersede(&request, crate::gpu_canvas::now_ms()); - if let Some((finished, computed)) = app.filter_preview_worker.poll() { - match computed { - // The dialog still holds these exact parameters. Publish as before, including an - // empty result: that is how a filter which no longer applies clears the canvas. - Ok(computed) if finished == request => publish_filter_preview(app, idx, finished, computed.result, computed.ms), - // Mid-drag, a frame for the value the pointer has just left is what makes the - // canvas follow the drag. Three things have to hold for it: it belongs to this - // preview, it has a frame to show (an empty one would blank a good preview), and - // it must not displace a frame that is already exact for the dialog, which is - // what a slider dragged out and back would otherwise make the canvas do. - Ok(computed) - if finished.same_target(&request) && computed.result.is_some() && !app.filter_preview.as_ref().is_some_and(|p| p.key == request) => - { - publish_filter_preview(app, idx, finished, computed.result, computed.ms); - } - Ok(_) => {} - // Errors stay on the exact request: a value the pointer has already dragged past - // must not raise a notice, and a still one will raise it when it is recomputed. - Err(error) if finished == request => { - app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: finished, result: None, committing: false }); - crate::notices::error(app, error); - } - Err(_) => {} - } - } - let fresh = app.filter_preview.as_ref().is_some_and(|p| p.key == request); - if !fresh && !app.filter_preview_worker.busy() { - let doc = app.session.documents().get(idx)?.doc.clone(); - let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); - let color = app.session.color.settings.clone(); - let task = request.clone(); - if let Err(error) = app.filter_preview_worker.start(request.clone(), ctx.clone(), move |cancel| { - let t0 = crate::gpu_canvas::now_ms(); - let result = crate::filter_dialog::preview_document_for_target( - &doc, - task.active, - &task.command, - &task.params, - task.k, - Some(cancel), - task.target, - &documents, - &color, - ) - .map(|doc| { - let buffer = photocraft_compose::flatten(&doc); - (std::sync::Arc::new(doc), buffer) - }); - crate::filter_preview_worker::Computed { result, ms: crate::gpu_canvas::now_ms() - t0 } - }) { - app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: request.clone(), result: None, committing: false }); - crate::notices::error(app, error); - } - } - if app.filter_preview_worker.busy() { - ctx.request_repaint_after(std::time::Duration::from_millis(16)); - } - let preview = app.filter_preview.as_ref()?; - // Keep the last preview during a drag, but never one from another source or dialog. - if !preview.key.same_target(&request) { - return None; - } - let result = preview.result.as_ref()?; - return Some((preview.key.k, key, [result.size.width, result.size.height])); - } - // Web and explicitly inline sessions keep the deterministic synchronous path (#1676): - // computed inline, uploaded when a GPU texture exists, still inspectable without one. - // Flattened once, as the background worker does; `publish_filter_preview` uploads it (#7490). - let _ = ctx; - if app.filter_preview.as_ref().is_none_or(|p| p.key != request) { - let doc = app.session.documents().get(idx)?.doc.clone(); - let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); - let t0 = crate::gpu_canvas::now_ms(); - let computed = crate::filter_dialog::preview_document_for_target( - &doc, - request.active, - &request.command, - &request.params, - request.k, - None, - request.target, - &documents, - &app.session.color.settings, - ) - .map(|doc| { - let buffer = photocraft_compose::flatten(&doc); - (std::sync::Arc::new(doc), buffer) - }); - publish_filter_preview(app, idx, request, computed, crate::gpu_canvas::now_ms() - t0); - } - let preview = app.filter_preview.as_ref()?; - let result = preview.result.as_ref()?; - Some((preview.key.k, key, [result.size.width, result.size.height])) -} - -/// Channel overlays must use the filter's current proxy too, including on the CPU canvas. -/// The cache key changes with the completed request; unchanged frames reuse the overlay texture. -pub(crate) fn filter_channel_preview(app: &mut PhotocraftApp, idx: usize, ctx: &egui::Context) -> Option<(std::sync::Arc, u64)> { - use std::hash::{Hash, Hasher}; - ensure_filter_preview(app, idx, ctx)?; - let preview = app.filter_preview.as_ref()?; - let doc = preview.result.as_ref()?.clone(); - let mut key = std::collections::hash_map::DefaultHasher::new(); - format!("{:?}", preview.key).hash(&mut key); - Some((doc, key.finish() | (1 << 59))) -} - -fn publish_filter_preview( - app: &mut PhotocraftApp, - idx: usize, - request: crate::filter_dialog::FilterPreviewKey, - computed: Option<(std::sync::Arc, photocraft_compose::Buffer)>, - ms: f64, -) { - let result = computed.and_then(|(result, buffer)| { - let t0 = crate::gpu_canvas::now_ms(); - let doc = app.session.documents().get(idx)?.doc.clone(); - // Shown through the preview's own colour management, as the result will be: Assign and - // Convert to Profile change the profile (and Convert the mode), not just the pixels. - let (display, _) = canvas_display(app, &result, None); - // A GPU texture is an optimisation: headless/CPU tests must still see the preview. - if let Some(gpu) = app.gpu.as_ref() { - gpu.upload_buffer_full(request.doc.0 ^ (1u64 << 61), &texture_buffer(display.as_deref(), &buffer), doc.depth); - } - app.perf.record("filter-preview", result.size.area(), ms, crate::gpu_canvas::now_ms() - t0); - Some(result) - }); - app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: request, result, committing: false }); -} - -/// The document whose colour management the canvas texture under `key` is shown through: a filter -/// preview's own result (it keeps the document's id, so Proof Colors still apply), else `doc`. -/// Assign Profile changes only the profile, so through `doc`'s its preview looked unchanged. -fn filter_preview_display_doc(app: &PhotocraftApp, doc: &std::sync::Arc, key: u64) -> std::sync::Arc { - if key != doc.id.0 ^ (1u64 << 61) { - return doc.clone(); - } - app.filter_preview.as_ref().and_then(|p| p.result.clone()).filter(|r| r.id == doc.id).unwrap_or_else(|| doc.clone()) -} - -/// After a filter dialog's OK: `Some(shown)` while its preview stands in for the background job -/// that commits it (the document unchanged and the job still running, for this document's views), -/// `None` otherwise (other documents' views included). A job that lands, fails or is cancelled -/// drops it. -pub(crate) fn committed_filter_preview(app: &mut PhotocraftApp, idx: usize) -> Option> { - let p = app.filter_preview.as_ref().filter(|p| p.committing)?; - let st = app.session.documents().get(idx)?; - if st.doc.id != p.key.doc { - return None; - } - let size = p.result.as_ref().map(|r| [r.size.width, r.size.height]); - if let Some(size) = size - && st.revision == p.key.revision - && app.session.job_on(p.key.doc).is_some() - { - return Some(Some((p.key.k, p.key.doc.0 ^ (1u64 << 61), size))); - } - app.filter_preview = None; - Some(None) -} - -/// The document pixels a view shows, with a margin for filtering. Uses all four canvas corners -/// so a rotated camera still covers the visible tiles. -fn visible_doc_rect(xf: &ViewXform) -> DRect { - let r = xf.rect; - let docs = [xf.to_doc(r.min), xf.to_doc(pos2(r.max.x, r.min.y)), xf.to_doc(r.max), xf.to_doc(pos2(r.min.x, r.max.y))]; - let mut x0 = docs[0][0]; - let mut y0 = docs[0][1]; - let mut x1 = x0; - let mut y1 = y0; - for d in docs { - x0 = x0.min(d[0]); - y0 = y0.min(d[1]); - x1 = x1.max(d[0]); - y1 = y1.max(d[1]); - } - let c = |v: f64| v.clamp(-1e9, 1e9) as i32; - DRect::new(c(x0.floor()) - 2, c(y0.floor()) - 2, c(x1.ceil()) + 2, c(y1.ceil()) + 2) -} - -/// Prioritize deferred redraw blocks visible at either the target or the animated display camera. -/// The displayed camera may still show old texture contents outside the target's visible area. -fn redraw_focus(target: &ViewXform, displayed: &ViewXform) -> DRect { - visible_doc_rect(target).union(&visible_doc_rect(displayed)) -} - -/// Zoomed-out Image › Adjustments preview on a large document: the wgpu compositor renders the -/// reduced preview document (`adjust_preview::gpu_proxy`) into its own texture, over the target's -/// area after the first frame. Returns (factor, gpu key, dimensions) to draw. -fn ensure_adjust_proxy(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option<(u32, u64, [u32; 2])> { - let frame = crate::adjust_preview::gpu_proxy(app, idx, zoom)?; - let key = frame.doc.id.0; - let size = [frame.doc.size.width, frame.doc.size.height]; - let gpu = app.gpu.clone()?; - if frame.stale || !gpu.has(key, size) { - let doc = app.session.documents().get(idx)?.doc.clone(); - let (display, _) = canvas_display(app, &doc, None); - let r = gpu.refresh(key, &frame.doc, frame.damage, display.as_deref()); - app.perf.record(if r.kind.starts_with("gpu") { "gpu-adjust-proxy" } else { "adjust-proxy" }, r.px, r.composite_ms, r.upload_ms); - if let Some(t) = r.gpu { - app.perf.record_gpu(t); - } - crate::adjust_preview::proxy_drawn(app, &frame); - } - Some((frame.k, key, size)) -} - -/// If a live adjustment preview is active on a large document, composite it on the proxy and upload -/// it under its own GPU key. Returns (factor, gpu key, dimensions) when the proxy should be drawn. -/// `zoom` is the view's (physical screen pixels per document pixel). -fn ensure_proxy_preview(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option<(u32, u64, [u32; 2])> { - let (layer, params) = app.live_adjust.clone()?; - let (doc_id, revision, doc) = { - let st = app.session.documents().get(idx)?; - (st.doc.id, st.revision, st.doc.clone()) - }; - // Low-resolution previews off: k is 1 and the canvas shows `display_doc` (full size). - let mut k = crate::proxy::preview_factor(&doc, crate::proxy::reduced_previews(app)); - // Zoomed in, a proxy coarser than the screen showed the drag in k-pixel blocks (#5764): when - // the wgpu compositor draws the full-size document, use a proxy only as coarse as the screen - // (none at 50 % and closer). Otherwise the full size would be a CPU composite per change. - let fine = crate::proxy::view_factor(k, zoom); - if fine < k && app.gpu.as_ref().is_some_and(|g| g.supports(&doc)) { - k = fine; - } - if k <= 1 { - return None; - } - let fresh = matches!(&app.proxy, Some((d, r, kk, _)) if *d == doc_id && *r == revision && *kk == k); - if !fresh { - app.proxy = Some((doc_id, revision, k, std::sync::Arc::new(crate::proxy::proxy_document(&doc, k)))); - } - let proxy = app.proxy.as_ref()?.3.clone(); - let key = doc_id.0 ^ (1u64 << 62); - let hash = params.to_string().bytes().fold(k as u64, |h, b| h.wrapping_mul(31).wrapping_add(b as u64)); - if app.proxy_uploaded != Some((doc_id, hash)) { - let l = proxy.layer(layer)?; - let LayerContent::Adjustment(a) = &l.content else { return None }; - let kind = photocraft_engine::commands::adjustment_kind(a); - let preview = photocraft_engine::adjust_params::from_params(kind, ¶ms, Some(a), proxy.mode).unwrap_or_else(|_| a.clone()); - let mut p = (*proxy).clone(); - if let Some(lm) = p.layer_mut(layer) { - lm.content = LayerContent::Adjustment(preview); - } - let t0 = crate::gpu_canvas::now_ms(); - let buf = photocraft_compose::flatten(&p); - let t1 = crate::gpu_canvas::now_ms(); - let (display, _) = canvas_display(app, &doc, None); - app.gpu.as_ref()?.upload_buffer_full(key, &texture_buffer(display.as_deref(), &buf), doc.depth); - app.perf.record("proxy", p.size.area(), t1 - t0, crate::gpu_canvas::now_ms() - t1); - app.proxy_uploaded = Some((doc_id, hash)); - } - Some((k, key, [proxy.size.width, proxy.size.height])) -} - -/// A CPU composite as the GPU canvas texture stores it (sRGB-encoded for linear documents). -fn texture_buffer<'a>( - display: Option<&photocraft_engine::display_color::CanvasDisplay>, - buf: &'a photocraft_compose::Buffer, -) -> std::borrow::Cow<'a, photocraft_compose::Buffer> { - match display { - Some(d) => d.texture_buffer(buf), - None => std::borrow::Cow::Borrowed(buf), - } -} - -pub(crate) fn retain_gpu_documents(app: &mut PhotocraftApp) { - // Remove a closed adjustment owner's proxy before collecting its live GPU keys. - crate::adjust_preview::retain_documents(app); - if let Some(gpu) = &app.gpu { - // Keep each document's texture plus its preview textures (filter preview, adjustment proxy); - // retaining only document ids freed the previews every frame (blank canvas while previewing). - let mut live: Vec = app.session.documents().iter().flat_map(|st| [st.doc.id.0, st.doc.id.0 ^ (1u64 << 61), st.doc.id.0 ^ (1u64 << 62)]).collect(); - live.extend(crate::adjust_preview::gpu_keys(app)); - gpu.retain(&live); - } - crate::background_redraw::retain(app); - // Upload markers must not outlive the resources they describe: native reopen can reuse - // both the document ID and revision before the next frame while a preview dialog stays open. - let documents = app.session.documents(); - if app.filter_preview.as_ref().is_some_and(|preview| !documents.iter().any(|st| st.doc.id == preview.key.doc)) { - app.filter_preview = None; - } - if app.proxy_uploaded.is_some_and(|(doc, _)| !documents.iter().any(|st| st.doc.id == doc)) { - app.proxy_uploaded = None; - app.proxy = None; - } -} - -/// Tabs + canvas for the active document, or the start screen; then drops layers dragged onto -/// another document (`layer_transfer`). -pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - crate::distort_ui::drop_foreign(app); - documents(app, ui); - crate::layer_transfer::finish(app, ui.ctx()); - // Once a frame, not per document view: the right-click or options-bar Brush Preset picker. - crate::paint_mouse::show_picker(app, ui.ctx()); -} - -/// Window › Arrange tiles: each document shown with its tile in `rect`, or `None` when the -/// active document fills the area. -pub(crate) fn arranged_cells(app: &PhotocraftApp, rect: Rect) -> Option> { - let idx = app.session.active_index()?; - let n = app.session.documents().len(); - let cells = crate::view_cmds::cells(&app.ui.view.arrange, rect, n)?; - // Each document keeps its tile: a click into another one activates it where it is (#6017; it - // used to move to the first tile). With more documents than tiles, the shown run stays put - // while the active document is in it, and otherwise slides only as far as it must. - let start = app.arrange_start.min(n.saturating_sub(cells.len())); - let start = if idx < start { idx } else { start.max((idx + 1).saturating_sub(cells.len())) }; - Some((start..n).zip(cells).collect()) -} - -fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - app.drop_canvas_rect = None; - app.tab_strip = None; - retain_gpu_documents(app); - crate::transform_tool::track_steps(app, ui.ctx()); - crate::cas_transform::tick(app, ui.ctx()); - crate::symmetry_ui::track(app, ui.ctx()); - let n = app.session.documents().len(); - // Files opening in the background (#210) have tabs before they have documents. - let opening = !app.jobs.opens.is_empty(); - if !opening && app.ui.chrome.shows_home(n, app.session.prefs().general.auto_show_home_screen) { - start_screen(app, ui); - return; - } - if n == 0 && !opening { - // Auto show the Home Screen is off: an empty workspace, like Photoshop. - let area = ui.available_rect_before_wrap(); - paint_dots(ui, area, app.session.prefs().interface.show_canvas_dots); - open_on_double_click(app, ui, area); - return; - } - if !app.ui.view.hides_tabs() || opening { - // Flat Spectrum tabs sit directly against the canvas. The parent's default vertical - // item spacing would otherwise leave a visible gap below the tab strip (#2188). - let spacing = ui.spacing().item_spacing.y; - if crate::theme::Tokens::get(ui.ctx()).pro { - ui.spacing_mut().item_spacing.y = 0.0; - } - app.tab_strip = Some(tabs(app, ui)); - ui.spacing_mut().item_spacing.y = spacing; - drop_slot_line(app, ui); - } - if let Some(job) = app.jobs.focus.or_else(|| (n == 0).then(|| app.jobs.opens.last().map(|o| o.job)).flatten()) { - crate::jobs_ui::open_card(app, ui, job); - return; - } - let Some(idx) = app.session.active_index() else { return }; - let rect = ui.available_rect_before_wrap(); - app.last_canvas_rect = rect; - app.drop_canvas_rect = Some(rect); - // Window › Arrange: tiled / n-up layouts show several documents side by side; the active one - // takes input, a click elsewhere activates that document. - if let Some(shown) = arranged_cells(app, rect) { - app.arrange_start = shown.first().map_or(0, |(d, _)| *d); - let t = crate::theme::Tokens::get(ui.ctx()); - for (d, cell) in shown { - let cell = cell.shrink(1.0); - let view = app.ui.views[d].clone(); - let v = canvas_view(app, ui, d, cell, view, d == idx); - if d != idx { - app.ui.views[d] = v; - if ui.input(|i| i.pointer.primary_pressed() && i.pointer.interact_pos().is_some_and(|p| cell.contains(p))) { - app.session.set_active(d); - } - } - let stroke = if d == idx { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, Color32::from_black_alpha(160)) }; - ui.painter().rect_stroke(cell, 0, stroke, egui::StrokeKind::Inside); - } - return; - } - let view = app.ui.views[idx].clone(); - canvas_view(app, ui, idx, rect, view, true); -} - -/// The tab strip; returns where its document tabs are. -fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { - let t = crate::theme::Tokens::get(ui.ctx()); - if t.pro { - return pro_tabs(app, ui); - } - let active = app.session.active_index(); - let tab_count = app.session.documents().len(); - let mut doc_tabs = Vec::with_capacity(tab_count); - let mut activate = None; - let mut close = None; - let mut tab_action = None; - let mut tab_move = None; - let mut tear_off = None; - let (mut focus_open, mut cancel_open) = (None, None); - let focused_open = app.jobs.focus.is_some(); - // Layers dragged over a tab show its document (`layer_transfer`). - let dragging = crate::layer_transfer::pointer_if_armed(app, ui.ctx()); - let mut drag_over = None; - let large_tabs = app.session.prefs().workspace.large_tabs; - let tab_h = if large_tabs { 34.0 } else { 26.0 }; - let font = crate::theme::medium(if large_tabs { 14.0 } else { 12.5 }); - let meta_font = egui::FontId::proportional(if large_tabs { 12.0 } else { 10.5 }); - // Files opening in the background (#210) are tabs too; they share the fit's index space, - // after the documents. - let opening = crate::jobs_ui::open_tabs(app); - // Every tab's natural width, whether or not it stays on the strip. - let natural: Vec = app - .session - .documents() - .iter() - .map(|st| { - let name = studio_tab_name(app, st); - ui.painter().layout_no_wrap(name, font.clone(), t.text).size().x - + ui.painter().layout_no_wrap(format!("{}/{}", mode_label(&st.doc), st.doc.depth.bits()), meta_font.clone(), t.text_faint).size().x - + STUDIO_TAB_PAD - }) - .chain(opening.iter().map(|(_, name, frac)| { - ui.painter().layout_no_wrap(name.clone(), font.clone(), t.text).size().x - + ui.painter().layout_no_wrap(format!("{:.0}%", frac * 100.0), meta_font.clone(), t.text_faint).size().x - + STUDIO_TAB_PAD - })) - .collect(); - let selected = app - .jobs - .focus - .and_then(|job| opening.iter().position(|(open, _, _)| *open == job)) - .map_or_else(|| app.session.active_index().unwrap_or(0), |p| tab_count + p); - let frame = egui::Frame::NONE.fill(t.canvas).inner_margin(egui::Margin { left: 8, right: 8, top: 6, bottom: 4 }).show(ui, |ui| { - let (row, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), tab_h), Sense::hover()); - let f = fit_doc_tabs(&natural, selected, row.width()); - let mut x = row.left(); - let mut placed: Vec<(usize, Rect)> = Vec::with_capacity(f.shown.len()); - for &(i, w) in &f.shown { - // The old horizontal layout put 4 pt between tabs; `w` carries it, the tab doesn't. - let r = Rect::from_min_size(egui::pos2(x, row.top()), egui::vec2((w - STUDIO_TAB_GAP).max(8.0), row.height())); - placed.push((i, r)); - x = r.right() + STUDIO_TAB_GAP; - } - for &(i, r) in placed.iter().filter(|(i, _)| *i < tab_count) { - let Some(st) = app.session.documents().get(i) else { continue }; - let sel = Some(i) == active && !focused_open; - let name = studio_tab_name(app, st); - let meta = format!("{}/{}", mode_label(&st.doc), st.doc.depth.bits()); - let natural_w = natural.get(i).copied().unwrap_or(0.0); - let meta_g = ui.painter().layout_no_wrap(meta, meta_font.clone(), t.text_faint); - let name_max = (r.width() - STUDIO_TAB_PAD + STUDIO_TAB_GAP - meta_g.size().x).max(1.0); - let name_g = crate::tab_strip::elided(ui, &name, font.clone(), t.text, name_max); - // The title was cut: the tooltip has the rest of it. - let cut = name_g.size().x + 0.5 < natural_w - STUDIO_TAB_PAD + STUDIO_TAB_GAP - meta_g.size().x; - let resp = ui.interact(r, ui.scope_id().with(("dtab", i)), Sense::click_and_drag()); - let saving = crate::jobs_ui::save_progress(app, st.doc.id); - resp.widget_info(|| { - let label = saving.as_ref().map_or_else(|| st.doc.name.clone(), |s| format!("{} - {s}", st.doc.name)); - egui::WidgetInfo::selected(egui::Role::Button, true, sel, label) - }); - doc_tabs.push((i, r)); - if sel { - ui.painter().rect_filled(r, t.radius_sm, t.card); - ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); - } else if resp.hovered() { - ui.painter().rect_filled(r, t.radius_sm, t.hover.gamma_multiply(0.5)); - } - if dragging.is_some_and(|p| r.contains(p)) { - drag_over = Some(i); - ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); - } - let color = if sel { t.text } else { t.text_dim }; - let ny = r.center().y - name_g.size().y / 2.0; - ui.painter().galley_with_override_text_color(egui::pos2(r.left() + 10.0, ny), name_g.clone(), color); - ui.painter().galley(egui::pos2(r.left() + 16.0 + name_g.size().x, r.center().y - meta_g.size().y / 2.0), meta_g, t.text_faint); - let xr = Rect::from_center_size(egui::pos2(r.right() - 12.0, r.center().y), egui::vec2(16.0, 16.0)); - let xresp = ui.interact(xr, ui.scope_id().with(("dtabx", i)), Sense::click()); - if xresp.hovered() { - ui.painter().rect_filled(xr, 4.0, t.hover); - } - crate::icons::paint(ui, xr, "x", 11.0, if xresp.hovered() { t.text } else { t.text_faint }); - let resp = if cut { resp.on_hover_text(name) } else { resp }; - if tab_close_clicked(&resp, &xresp) { - close = Some(i); - } else if resp.clicked() { - activate = Some(i); - } - match tab_drag(ui, &resp, i, r, row, &placed, &t) { - Some(TabDrop::Move(to)) => tab_move = Some((i, to)), - Some(TabDrop::Float(at)) => tear_off = Some((i, at)), - None => {} - } - let has_path = st.path.is_some(); - resp.context_menu(|ui| { - tab_action = tab_context_menu(ui, i, tab_count, has_path); - }); - } - // Files opening in the background: a tab with a progress underline; × cancels. - for &(i, r) in placed.iter().filter(|(i, _)| *i >= tab_count) { - let Some((job, name, frac)) = opening.get(i - tab_count) else { continue }; - let sel = app.jobs.focus == Some(*job); - let meta_g = ui.painter().layout_no_wrap(format!("{:.0}%", frac * 100.0), meta_font.clone(), t.text_faint); - let name_g = crate::tab_strip::elided(ui, name, font.clone(), t.text, (r.width() - STUDIO_TAB_PAD + STUDIO_TAB_GAP - meta_g.size().x).max(1.0)); - let resp = ui.interact(r, ui.scope_id().with(("dtabjob", job.0)), Sense::click()); - if sel { - ui.painter().rect_filled(r, t.radius_sm, t.card); - ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); - } else if resp.hovered() { - ui.painter().rect_filled(r, t.radius_sm, t.hover.gamma_multiply(0.5)); - } - let ny = r.center().y - name_g.size().y / 2.0; - ui.painter().galley_with_override_text_color(egui::pos2(r.left() + 10.0, ny), name_g.clone(), if sel { t.text } else { t.text_dim }); - ui.painter().galley(egui::pos2(r.left() + 16.0 + name_g.size().x, r.center().y - meta_g.size().y / 2.0), meta_g, t.text_faint); - crate::jobs_ui::tab_underline(ui, r, *frac, &t); - let xr = Rect::from_center_size(egui::pos2(r.right() - 12.0, r.center().y), egui::vec2(16.0, 16.0)); - let xresp = ui.interact(xr, ui.scope_id().with(("dtabjobx", job.0)), Sense::click()); - if xresp.hovered() { - ui.painter().rect_filled(xr, 4.0, t.hover); - } - crate::icons::paint(ui, xr, "x", 11.0, if xresp.hovered() { t.text } else { t.text_faint }); - if xresp.on_hover_text(tl!("Cancel opening")).clicked() { - cancel_open = Some(*job); - } else if resp.clicked() { - focus_open = Some(*job); - } - } - if !f.overflow.is_empty() { - // Pinned to the strip's right end, as Photoshop's is, not after the last tab (#8290). - let left = (row.right() - crate::tab_strip::CHEVRON_W).max(row.left()); - let r = Rect::from_min_size(egui::pos2(left, row.top()), egui::vec2(crate::tab_strip::CHEVRON_W, row.height())); - let labels: Vec<&str> = - app.session.documents().iter().map(|st| st.doc.name.as_str()).chain(opening.iter().map(|(_, name, _)| name.as_str())).collect(); - let mut picked = None; - // Like Photoshop's, the menu lists every open document, not only the hidden ones, and checks - // the active one (#4487). - let every: Vec = (0..labels.len()).collect(); - crate::tab_strip::overflow_button(ui, ui.scope_id().with("dtab-overflow"), r, tl!("More documents"), &labels, &every, Some(selected), &mut picked); - match picked { - Some(i) if i < tab_count => activate = Some(i), - Some(i) => focus_open = opening.get(i - tab_count).map(|(job, _, _)| *job).or(focus_open), - None => {} - } - } - }); - open_tab_clicks(app, activate, focus_open, cancel_open); - if let Some(i) = drag_over { - crate::layer_transfer::over_tab(app, ui.ctx(), i); - } - if let Some(i) = close { - let _ = crate::menus::invoke(app, ui.ctx(), "file.close", json!({"document": i})); - } - if let Some((from, to)) = tab_move - && let Err(e) = crate::menus::invoke(app, ui.ctx(), "document.move", json!({"document": from, "to": to})) - { - app.ui.status = e; - app.ui.status_error = true; - } - float_torn_off(app, ui.ctx(), tear_off); - if let Some((id, params)) = tab_action - && let Err(e) = crate::menus::invoke(app, ui.ctx(), id, params) - { - app.ui.status = e; - app.ui.status_error = true; - } - TabStrip { rect: frame.response.rect, tabs: doc_tabs } -} - -/// Whether a document tab was asked to close: its × was clicked (#619), or the tab was clicked -/// with the middle button (#2570), as in a browser. A middle click over the × counts too, so the -/// whole tab behaves the same way. Both strips share this rule; the caller routes it through the -/// guarded `file.close`, so a document with unsaved changes still gets the save prompt. -fn tab_close_clicked(resp: &egui::Response, xresp: &egui::Response) -> bool { - xresp.clicked() || xresp.middle_clicked() || resp.middle_clicked() -} - -/// All tab actions go through the same guarded File commands as the menu bar, including the -/// unsaved-changes prompt. The clicked tab is explicit even when another document is active. -fn tab_context_items(index: usize, count: usize, has_path: bool) -> [(&'static str, &'static str, serde_json::Value, bool); 4] { - [ - ("Close", "file.close", json!({"document": index}), true), - ("Close Others", "file.closeOthers", json!({"document": index}), count > 1), - ("Close All", "file.closeAll", json!({}), true), - (crate::menus::reveal_label(), "file.revealInFinder", json!({"document": index}), has_path), - ] -} - -fn tab_context_menu(ui: &mut egui::Ui, index: usize, count: usize, has_path: bool) -> Option<(&'static str, serde_json::Value)> { - crate::widgets::menu_scroll(ui, |ui| { - ui.set_min_width(170.0); - for (label, id, params, enabled) in tab_context_items(index, count, has_path) { - if ui.add_enabled(enabled, egui::Button::new(tl!(label))).clicked() { - ui.close(); - return Some((id, params)); - } - } - None - }) -} - -/// Where a tab dragged to `x` would land: before the first shown tab whose middle is right of -/// `x`, else after the last shown tab (its document index + 1), like [`TabStrip::slot`]. -/// How far (points) above or below the tab strip a dragged tab must be to tear off (#3733). -const TEAR_OFF: f32 = 24.0; - -/// Whether a tab dragged to `p` has left the strip and floats into its own window, as in -/// Photoshop; sideways drags along the strip still reorder (#217). -fn torn_off(strip: Rect, p: egui::Pos2) -> bool { - p.y > strip.bottom() + TEAR_OFF || p.y < strip.top() - TEAR_OFF -} - -/// What a finished document-tab drag asks for. -#[derive(Clone, Copy, Debug, PartialEq)] -enum TabDrop { - /// Reorder the tab to this index. - Move(usize), - /// Float the document in its own OS window at this screen position (points), when known. - Float(Option<[f32; 2]>), -} - -/// Drag a document tab: along the strip it reorders (a line shows where it will land); off the -/// strip it tears off into a floating window that can go anywhere, other screens included -/// (an outline under the pointer shows it). Returns the drop once the drag ends. -fn tab_drag(ui: &egui::Ui, resp: &egui::Response, i: usize, r: Rect, strip: Rect, placed: &[(usize, Rect)], t: &crate::theme::Tokens) -> Option { - if resp.dragged() - && let Some(p) = resp.interact_pointer_pos() - { - if torn_off(strip, p) { - let ghost = Rect::from_min_size(p - egui::vec2(40.0, 12.0), egui::vec2(240.0, 160.0)); - let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, ui.scope_id().with("tab-tear-off"))); - painter.rect_filled(ghost, t.radius_sm, t.accent.gamma_multiply(0.12)); - painter.rect_stroke(ghost, t.radius_sm, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); - } else { - tab_drop_line(ui, placed, p.x, t); - } - } - if !resp.drag_stopped() { - return None; - } - let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.interact_pos())); - if let Some(p) = p.filter(|&p| torn_off(strip, p)) { - // The pointer is in this window's points; the OS wants screen coordinates. Keep the new - // window's title bar under the pointer, as the ghost showed. - let at = ui.ctx().input(|i| i.viewport().inner_rect).map(|inner| { - let s = inner.min + p.to_vec2() - egui::vec2(40.0, 12.0); - [s.x, s.y] - }); - return Some(TabDrop::Float(at)); - } - let to = tab_move_target(i, tab_drop_index(placed, p.map_or(r.center().x, |p| p.x))); - (to != i).then_some(TabDrop::Move(to)) -} - -/// Float a torn-off tab's document in its own window (`window.arrange.floatInWindow`). -fn float_torn_off(app: &mut PhotocraftApp, ctx: &egui::Context, tear_off: Option<(usize, Option<[f32; 2]>)>) { - let Some((doc, at)) = tear_off else { return }; - let params = match at { - Some(at) => json!({"document": doc, "position": at}), - None => json!({"document": doc}), - }; - if let Err(e) = crate::menus::invoke(app, ctx, "window.arrange.floatInWindow", params) { - app.ui.status = e; - app.ui.status_error = true; - } -} - -fn tab_drop_index(placed: &[(usize, Rect)], x: f32) -> usize { - match placed.iter().find(|(_, r)| r.center().x >= x) { - Some(&(i, _)) => i, - None => placed.last().map_or(0, |&(i, _)| i.saturating_add(1)), - } -} - -/// The `document.move` target for dropping the tab at `from` at insertion index `k`: the slot -/// shifts down when the dragged tab itself is removed first; next to itself it stays put. -fn tab_move_target(from: usize, k: usize) -> usize { - if k > from { k - 1 } else { k } -} - -/// The insertion line shown while a tab is dragged to reorder it. -fn tab_drop_line(ui: &egui::Ui, placed: &[(usize, Rect)], x: f32, t: &crate::theme::Tokens) { - match placed.iter().find(|(_, r)| r.center().x >= x) { - Some(&(_, r)) => crate::widgets::drop_line(ui, r, false, true, t), - None => { - if let Some(&(_, r)) = placed.last() { - crate::widgets::drop_line(ui, r, true, true, t); - } - } - } -} - -/// Apply tab-strip clicks: a document tab shows that document, an opening tab its progress, and -/// an opening tab's × cancels the open (closing the half-open tab). -fn open_tab_clicks( - app: &mut PhotocraftApp, - activate: Option, - focus_open: Option, - cancel_open: Option, -) { - if let Some(i) = activate { - app.session.set_active(i); - app.jobs.focus = None; - } - if let Some(job) = focus_open { - app.jobs.focus = Some(job); - } - if let Some(job) = cancel_open { - crate::jobs_ui::cancel(app, job); - } -} - -/// Document tabs: the chrome around a title (the × and its gaps). -const DOC_TAB_PAD: f32 = 42.0; -/// The Studio strip's tabs carried 4 pt of spacing between them and 44 pt of chrome; `fit` sees -/// one number per tab, so the gap rides in the natural width and comes back out when painted. -const STUDIO_TAB_PAD: f32 = 48.0; -const STUDIO_TAB_GAP: f32 = 4.0; - -/// Fit document tabs as Photoshop does (#4487): a tab never shrinks below its whole title, so the -/// tabs that don't fit move into the » menu instead. Only the active tab, when it alone is wider -/// than the strip, is cut. -fn fit_doc_tabs(natural: &[f32], selected: usize, avail: f32) -> crate::tab_strip::TabFit { - let widest = natural.iter().copied().filter(|w| w.is_finite()).fold(0.0, f32::max); - crate::tab_strip::fit(natural, selected, avail, widest, crate::tab_strip::CHEVRON_W) -} - -/// Photoshop's tab title: "name @ 50% (Layer 1, RGB/8)", "(Layer 1, Layer Mask/8)" when the mask -/// is targeted, "(Quick Mask/8)" in Quick Mask mode; the Background layer's name is omitted. -fn pro_tab_title(app: &PhotocraftApp, i: usize) -> String { - use photocraft_engine::channel_cmds::ChannelTarget; - let Some(st) = app.session.documents().get(i) else { return String::new() }; - let zoom = app.ui.views.get(i).map_or(100.0, |v| v.zoom * 100.0); - // Quick Mask mode targets the mask, not the layer (see `paint_target`): painting and Free - // Transform change the red overlay, so the tab says so, as Photoshop's does. - let quick_mask = st.doc.quick_mask.is_some() && st.channel_view.target == ChannelTarget::Composite; - let active_layer = st.active_layer.and_then(|id| st.doc.layer(id)).filter(|l| !quick_mask && !st.doc.is_background(l.id)); - let mask = app.session.active_index() == Some(i) && app.ui.mask_target && active_layer.is_some_and(|l| l.mask.is_some()); - let model = if quick_mask { - tl!("Quick Mask").to_string() - } else if mask { - tl!("Layer Mask").to_string() - } else { - mode_label(&st.doc).to_string() - }; - let layer = active_layer.map(|l| format!("{}, ", l.name)).unwrap_or_default(); - // A save in progress: "name @ 100% (Layer 1, RGB/16) - Saving 45%", as Photoshop does (#3389). - let saving = crate::jobs_ui::save_progress(app, st.doc.id).map(|s| format!(" - {s}")).unwrap_or_default(); - format!("{} @ {}% ({layer}{model}/{}){}{saving}", st.doc.name, fmt_zoom(zoom), st.doc.depth.bits(), if st.is_dirty() { "*" } else { "" }) -} - -/// The Studio strip's tab name: "name *" when unsaved, "name * - Saving 45%" while it saves (#3389). -fn studio_tab_name(app: &PhotocraftApp, st: &photocraft_engine::DocState) -> String { - let saving = crate::jobs_ui::save_progress(app, st.doc.id).map(|s| format!(" - {s}")).unwrap_or_default(); - format!("{}{}{saving}", st.doc.name, if st.is_dirty() { " *" } else { "" }) -} - -/// Photoshop document tabs: "name @ 33.3% (RGB/8)" on a dark strip; active tab matches panels. -/// Tabs keep their whole titles, and the ones that don't fit move into a » menu at the end of the -/// strip; the active document's tab always stays on the strip (#1276, #4487). -fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { - let t = crate::theme::Tokens::get(ui.ctx()); - let active = app.session.active_index().filter(|_| app.jobs.focus.is_none()); - let (mut activate, mut close) = (None, None); - let mut tab_action = None; - let mut tab_move = None; - let mut tear_off = None; - let tab_count = app.session.documents().len(); - let dragging = crate::layer_transfer::pointer_if_armed(app, ui.ctx()); - let mut drag_over = None; - let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac; - let large_tabs = app.session.prefs().workspace.large_tabs; - let font = egui::FontId::proportional(if large_tabs { 13.0 } else { 11.5 }); - let tab_h = if large_tabs { 34.0 } else { 26.0 }; - let (strip, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), tab_h), Sense::hover()); - ui.painter().rect_filled(strip, 0.0, t.tab_strip); - // Files opening in the background (#210) are tabs too ("name (Opening… 45%)" with a progress - // underline); they share the fit's index space, after the documents. - let opening = crate::jobs_ui::open_tabs(app); - let mut titles: Vec = (0..tab_count).map(|i| pro_tab_title(app, i)).collect(); - titles.extend(opening.iter().map(|(_, name, frac)| format!("{name} ({} {:.0}%)", tl!("Opening…"), frac * 100.0))); - // Every tab's natural width, whether or not it stays on the strip. - let natural: Vec = titles.iter().map(|title| ui.painter().layout_no_wrap(title.clone(), font.clone(), t.text).size().x + DOC_TAB_PAD).collect(); - let selected = app - .jobs - .focus - .and_then(|job| opening.iter().position(|(open, _, _)| *open == job)) - .map_or_else(|| app.session.active_index().unwrap_or(0), |p| tab_count + p); - let f = fit_doc_tabs(&natural, selected, strip.width()); - let mut x = strip.left(); - let mut placed: Vec<(usize, Rect)> = Vec::with_capacity(f.shown.len()); - for &(i, w) in &f.shown { - let r = Rect::from_min_size(egui::pos2(x, strip.top()), egui::vec2(w, strip.height())); - placed.push((i, r)); - x = r.right(); - } - let mut doc_tabs = Vec::with_capacity(tab_count); - let (mut focus_open, mut cancel_open) = (None, None); - for &(i, r) in placed.iter().filter(|(i, _)| *i < tab_count) { - let Some(title) = titles.get(i) else { continue }; - let g = crate::tab_strip::elided(ui, title, font.clone(), t.text, (r.width() - DOC_TAB_PAD).max(1.0)); - let resp = ui.interact(r, ui.scope_id().with(("ptab", i)), Sense::click_and_drag()); - let sel = Some(i) == active; - if sel { - ui.painter().rect_filled(r, 0.0, t.chrome); - } else if resp.hovered() { - ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.35)); - } - if dragging.is_some_and(|p| r.contains(p)) { - drag_over = Some(i); - ui.painter().rect_stroke(r, 0.0, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); - } - ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.0, t.separator)); - let (xr, at) = pro_tab_layout(r, g.size().y, mac); - let xresp = ui.interact(xr, ui.scope_id().with(("ptabx", i)), Sense::click()); - // Painted: name the tab and its × for accessibility (and so tests and agents can find them). - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, sel, g.text())); - xresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Close"))); - crate::icons::paint(ui, xr, "x", 10.0, if xresp.hovered() { t.text } else { t.text_faint }); - ui.painter().galley_with_override_text_color(at, g, if sel { t.text } else { t.text_faint }); - let cut = natural.get(i).copied().unwrap_or(0.0) > r.width() + 0.5; - let resp = if cut { resp.on_hover_text(title.as_str()) } else { resp }; - if tab_close_clicked(&resp, &xresp) { - close = Some(i); - } else if resp.clicked() { - activate = Some(i); - } - match tab_drag(ui, &resp, i, r, strip, &placed, &t) { - Some(TabDrop::Move(to)) => tab_move = Some((i, to)), - Some(TabDrop::Float(at)) => tear_off = Some((i, at)), - None => {} - } - let has_path = app.session.documents().get(i).is_some_and(|d| d.path.is_some()); - resp.context_menu(|ui| { - tab_action = tab_context_menu(ui, i, tab_count, has_path); - }); - doc_tabs.push((i, r)); - } - for &(i, r) in placed.iter().filter(|(i, _)| *i >= tab_count) { - let Some((job, _, frac)) = opening.get(i - tab_count) else { continue }; - let Some(title) = titles.get(i) else { continue }; - let g = crate::tab_strip::elided(ui, title, font.clone(), t.text, (r.width() - DOC_TAB_PAD).max(1.0)); - let resp = ui.interact(r, ui.scope_id().with(("ptabjob", job.0)), Sense::click()); - let sel = app.jobs.focus == Some(*job); - if sel { - ui.painter().rect_filled(r, 0.0, t.chrome); - } else if resp.hovered() { - ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.35)); - } - ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.0, t.separator)); - crate::jobs_ui::tab_underline(ui, r, *frac, &t); - let (xr, at) = pro_tab_layout(r, g.size().y, mac); - let xresp = ui.interact(xr, ui.scope_id().with(("ptabjobx", job.0)), Sense::click()); - xresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Close"))); - crate::icons::paint(ui, xr, "x", 10.0, if xresp.hovered() { t.text } else { t.text_faint }); - ui.painter().galley_with_override_text_color(at, g, if sel { t.text } else { t.text_faint }); - if xresp.on_hover_text(tl!("Cancel opening")).clicked() { - cancel_open = Some(*job); - } else if resp.clicked() { - focus_open = Some(*job); - } - } - if !f.overflow.is_empty() { - // Pinned to the strip's right end, as Photoshop's is, not after the last tab (#8290). - let left = (strip.right() - crate::tab_strip::CHEVRON_W).max(strip.left()); - let r = Rect::from_min_size(egui::pos2(left, strip.top()), egui::vec2(crate::tab_strip::CHEVRON_W, strip.height())); - let labels: Vec<&str> = titles.iter().map(String::as_str).collect(); - let mut picked = None; - // Like Photoshop's, the menu lists every open document, not only the hidden ones, and checks - // the active one (#4487). - let every: Vec = (0..labels.len()).collect(); - crate::tab_strip::overflow_button(ui, ui.scope_id().with("ptab-overflow"), r, tl!("More documents"), &labels, &every, Some(selected), &mut picked); - match picked { - Some(i) if i < tab_count => activate = Some(i), - Some(i) => focus_open = opening.get(i - tab_count).map(|(job, _, _)| *job).or(focus_open), - None => {} - } - } - open_tab_clicks(app, activate, focus_open, cancel_open); - if let Some(i) = drag_over { - crate::layer_transfer::over_tab(app, ui.ctx(), i); - } - if let Some(i) = close { - let _ = crate::menus::invoke(app, ui.ctx(), "file.close", json!({"document": i})); - } - if let Some((from, to)) = tab_move - && let Err(e) = crate::menus::invoke(app, ui.ctx(), "document.move", json!({"document": from, "to": to})) - { - app.ui.status = e; - app.ui.status_error = true; - } - float_torn_off(app, ui.ctx(), tear_off); - if let Some((id, params)) = tab_action - && let Err(e) = crate::menus::invoke(app, ui.ctx(), id, params) - { - app.ui.status = e; - app.ui.status_error = true; - } - TabStrip { rect: strip, tabs: doc_tabs } -} - -/// Where the document tabs were drawn (opening files' tabs aren't slots): a file dropped on the -/// strip opens at the slot under the pointer. -#[derive(Clone, Debug, PartialEq)] -pub struct TabStrip { - pub rect: Rect, - /// The document tabs shown, left to right, with their document index. When the tabs overflow - /// into the » menu, some documents have no tab here. - pub tabs: Vec<(usize, Rect)>, -} - -impl TabStrip { - /// The document position a drop at `x` opens at: before the first shown tab whose middle is - /// right of it, else after the last shown tab. - pub fn slot(&self, x: f32) -> usize { - match self.tabs.iter().find(|(_, r)| r.center().x >= x) { - Some(&(i, _)) => i, - None => self.tabs.last().map_or(0, |&(i, _)| i.saturating_add(1)), - } - } -} - -/// While files are dragged over the tab strip, an insertion line where they would open. -fn drop_slot_line(app: &mut PhotocraftApp, ui: &egui::Ui) { - if ui.input(|i| i.raw.hovered_files.is_empty()) { - return; - } - let at = app.services.cursor_pos.as_mut().and_then(|f| f(ui.ctx())); - let crate::file_open::DropTarget::Tabs(slot) = app.drop_target(ui.ctx(), at) else { return }; - let Some(tabs) = app.tab_strip.as_ref().map(|s| &s.tabs) else { return }; - let Some((r, after)) = tabs.iter().find(|(i, _)| *i == slot).map(|&(_, r)| (r, false)).or_else(|| tabs.last().map(|&(_, r)| (r, true))) else { - return; - }; - crate::widgets::drop_line(ui, r, after, true, &crate::theme::Tokens::get(ui.ctx())); -} - -/// A Photoshop-style tab's close button and where its title starts. Photoshop puts the × after the -/// title on Windows (and so Linux) and before it on macOS (#619). -fn pro_tab_layout(tab: Rect, title_height: f32, mac: bool) -> (Rect, egui::Pos2) { - let (x, title) = if mac { (tab.left() + 13.0, tab.left() + 26.0) } else { (tab.right() - 13.0, tab.left() + 16.0) }; - (Rect::from_center_size(egui::pos2(x, tab.center().y), egui::vec2(14.0, 14.0)), egui::pos2(title, tab.center().y - title_height / 2.0)) -} - /// Photoshop-style zoom label: "33.3", "100", "12.5". pub fn fmt_zoom(pct: f32) -> String { if (pct - pct.round()).abs() < 0.05 { format!("{}", pct.round() as i64) } else { format!("{pct:.1}") } } -/// Repeating dot-grid texture for the canvas surround. A theme whose dots are its canvas colour -/// has no pattern to show, so it gets no texture at all rather than an invisible one (#4542). -fn dots(ctx: &egui::Context, t: &crate::theme::Tokens) -> Option { - if t.bevel || t.canvas_dot == t.canvas { - return None; - } - let key = egui::Id::unique(("canvas-dots", format!("{:?}", t.kind))); - if let Some(tex) = ctx.data(|d| d.get_temp::(key)) { - return Some(tex.id()); - } - let n = 22usize; - let mut px = vec![Color32::TRANSPARENT; n * n]; - for (dx, dy, a) in [(0usize, 0usize, 255u8), (1, 0, 110), (0, 1, 110), (1, 1, 60)] { - let c = t.canvas_dot; - px[(n / 2 + dy) * n + n / 2 + dx] = Color32::from_rgba_unmultiplied(c.r(), c.g(), c.b(), a); - } - let opts = TextureOptions { - magnification: egui::TextureFilter::Linear, - minification: egui::TextureFilter::Linear, - wrap_mode: egui::TextureWrapMode::Repeat, - mipmap_mode: None, - }; - let tex = ctx.load_texture("canvas-dots", egui::ColorImage::new([n, n], px), opts); - let id = tex.id(); - ctx.data_mut(|d| d.insert_temp(key, tex)); - Some(id) -} - -fn paint_dots(ui: &egui::Ui, rect: Rect, enabled: bool) { - if !enabled { - return; - } - let t = crate::theme::Tokens::get(ui.ctx()); - if let Some(id) = dots(ui.ctx(), &t) { - let uv = Rect::from_min_max(Pos2::ZERO, pos2(rect.width() / 22.0, rect.height() / 22.0)); - ui.painter_at(rect).image(id, rect, uv, Color32::WHITE); - } -} - pub fn mode_label(doc: &Document) -> &'static str { match doc.mode { photocraft_doc::ColorMode::Rgb => "RGB", @@ -3352,237 +170,6 @@ pub fn mode_label(doc: &Document) -> &'static str { } } -/// With no document open, double-clicking the empty workspace shows File › Open, as in Photoshop -/// (#5367), and so does the Home screen's blank background. Registered before anything drawn over -/// `area`, so the buttons and links there keep their own clicks; not a keyboard focus stop. -fn open_on_double_click(app: &mut PhotocraftApp, ui: &egui::Ui, area: Rect) { - if app.session.documents().is_empty() && ui.interact(area, ui.scope_id().with("empty-workspace"), Sense::CLICK).double_clicked() { - let _ = app.open_dialog_file(); - } -} - -/// The Home screen's card is this wide when the canvas has room, and as wide as the canvas when it doesn't. -const HOME_CARD_WIDTH: f32 = 460.0; -/// Least width of each of the Home screen's New document and Open buttons. -const HOME_BUTTON_WIDTH: f32 = 190.0; -/// Space between the Home screen's two buttons. -const HOME_BUTTON_GAP: f32 = 12.0; - -fn start_screen(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = crate::theme::Tokens::get(ui.ctx()); - let area = ui.available_rect_before_wrap(); - paint_dots(ui, area, app.session.prefs().interface.show_canvas_dots); - open_on_double_click(app, ui, area); - // File › Open Recent, newest first (on the web there are no paths to reopen). - let show_recent = app.session.prefs().interface.show_home_recent_files; - let recent: Vec = - if cfg!(target_arch = "wasm32") || !show_recent { Vec::new() } else { app.ui.recent_files.iter().take(HOME_RECENT).cloned().collect() }; - let recent_h = if recent.is_empty() { 0.0 } else { 34.0 + recent.len() as f32 * HOME_RECENT_ROW }; - // A tiling window manager can give the canvas less room than the card wants: shrink the card - // to fit, and stack the buttons when they don't fit side by side. - let new_label = crate::shortcuts::command_label(app, "New document…", "file.new"); - let open_label = crate::shortcuts::command_label(app, "Open…", "file.open"); - let card_width = HOME_CARD_WIDTH.min(area.width()); - let button_width = HOME_BUTTON_WIDTH.max(crate::widgets::button_width(ui, &[&new_label, &open_label])); - let side_by_side = 2.0 * button_width + HOME_BUTTON_GAP <= card_width; - // Stacked buttons take one more row. - let stacked_h = if side_by_side { 0.0 } else { 44.0 }; - let card = Rect::from_center_size(area.center(), egui::vec2(card_width, 330.0 + recent_h + stacked_h)); - ui.scope_builder(egui::UiBuilder::new().max_rect(card), |ui| { - ui.vertical_centered(|ui| { - ui.horizontal(|ui| { - let title = ui.painter().layout_no_wrap(tl!("PhotoCraft").into(), crate::theme::semibold(38.0), t.text); - let by = ui.painter().layout_no_wrap(tl!("open source").into(), egui::FontId::proportional(13.0), t.text_faint); - let total = title.size().x + by.size().x + 10.0; - ui.add_space(((card.width() - total) / 2.0).max(0.0)); - let (r, _) = ui.allocate_exact_size(title.size(), Sense::hover()); - ui.painter().galley(r.min, title, t.text); - let (r2, _) = ui.allocate_exact_size(egui::vec2(by.size().x + 10.0, r.height()), Sense::hover()); - ui.painter().galley(egui::pos2(r2.left() + 10.0, r.bottom() - by.size().y - 8.0), by, t.text_faint); - }); - ui.add_space(6.0); - ui.label(egui::RichText::new(tl!("Create a new document or open an existing file.")).color(t.text_dim).size(14.0)); - ui.add_space(22.0); - let (mut new_clicked, mut open_clicked) = (false, false); - if side_by_side { - ui.horizontal(|ui| { - ui.add_space(((card.width() - 2.0 * button_width - HOME_BUTTON_GAP) / 2.0).max(0.0)); - ui.spacing_mut().item_spacing.x = HOME_BUTTON_GAP; - new_clicked = crate::widgets::primary_button(ui, &new_label, button_width).clicked(); - open_clicked = crate::widgets::secondary_button(ui, &open_label, button_width).clicked(); - }); - } else { - new_clicked = crate::widgets::primary_button(ui, &new_label, button_width).clicked(); - ui.add_space(HOME_BUTTON_GAP); - open_clicked = crate::widgets::secondary_button(ui, &open_label, button_width).clicked(); - } - if new_clicked { - let fields = app.new_document_fields(); - app.ui.open_dialog(crate::state::DialogKind::NewDocument, fields); - } - if open_clicked { - let _ = app.open_dialog_file(); - } - ui.add_space(22.0); - ui.horizontal(|ui| { - let msg = start_screen_drop_hint(app); - let g = ui.painter().layout_no_wrap(msg.to_string(), egui::FontId::proportional(12.5), t.text_faint); - ui.add_space(((card.width() - g.size().x - 24.0) / 2.0).max(0.0)); - let (r, _) = ui.allocate_exact_size(egui::vec2(18.0, 18.0), Sense::hover()); - crate::icons::paint(ui, r, "image", 15.0, t.text_faint); - ui.label(egui::RichText::new(msg).color(t.text_faint)); - }); - if !recent.is_empty() { - ui.add_space(22.0); - home_recent(app, ui, &recent); - } - ui.add_space(26.0); - crate::links::discord_button(app, ui, 190.0); - ui.add_space(10.0); - crate::links::link_row(app, ui); - }); - }); -} - -/// Wayland has no native file drops (winit 0.30, #386), so the hint offers File › Open and paste. -fn start_screen_drop_hint(app: &PhotocraftApp) -> std::borrow::Cow<'static, str> { - if app.services.is_wayland { - crate::i18n::fmt(tl!("Use File › Open, or paste a copied image with {paste}."), &[("paste", &crate::notices::paste_hint(app))]).into() - } else { - tl!("Drop an image or PSD anywhere to open it.").into() - } -} - -/// Recent files listed on the Home screen. -const HOME_RECENT: usize = 6; -/// Height of one Home-screen recent-file row. -const HOME_RECENT_ROW: f32 = 30.0; - -/// The Home screen's "Recent" list: file name, its folder on the right, click to open. The -/// hovered row shows a × that takes it off the list, and right-click offers Remove from Recent -/// and Clear Recent Files (#2691). -fn home_recent(app: &mut PhotocraftApp, ui: &mut egui::Ui, recent: &[String]) { - let t = crate::theme::Tokens::get(ui.ctx()); - let width = 380.0; - ui.horizontal(|ui| { - // Line the heading up with the file icons. - ui.add_space(((ui.available_width() - width) / 2.0).max(0.0) + 8.0); - ui.label(egui::RichText::new(tl!("Recent")).font(crate::theme::semibold(12.5)).color(t.text_dim)); - }); - ui.add_space(4.0); - let mut open = None; - let mut remove = None; - let mut clear = false; - for path in recent { - let name = crate::file_open::display_name(path); - let folder = std::path::Path::new(path).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(); - let (row, resp) = ui.allocate_exact_size(egui::vec2(width, HOME_RECENT_ROW), Sense::click()); - // The × sits on top of the row, so the row counts as hovered while the pointer is on it. - let hovered = ui.rect_contains_pointer(row); - if hovered { - ui.painter().rect_filled(row, t.radius_sm, t.hover); - } - let close = Rect::from_center_size(egui::pos2(row.right() - 16.0, row.center().y), egui::vec2(22.0, 22.0)); - let right = if hovered { close.left() - 4.0 } else { row.right() - 10.0 }; - let icon = Rect::from_center_size(egui::pos2(row.left() + 16.0, row.center().y), egui::vec2(16.0, 16.0)); - crate::icons::paint(ui, icon, "file", 14.0, t.text_dim); - let x = row.left() + 32.0; - let name_g = crate::tab_strip::elided(ui, &name, egui::FontId::proportional(12.5), t.text, 170.0); - let name_w = name_g.size().x; - ui.painter().galley(egui::pos2(x, row.center().y - name_g.size().y / 2.0), name_g, t.text); - let folder_max = (right - (x + name_w + 14.0)).max(0.0); - if folder_max > 20.0 && !folder.is_empty() { - let fg = crate::tab_strip::elided(ui, &folder, egui::FontId::proportional(11.5), t.text_faint, folder_max); - ui.painter().galley(egui::pos2(right - fg.size().x, row.center().y - fg.size().y / 2.0), fg, t.text_faint); - } - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name)); - let resp = resp.on_hover_text(path).on_hover_cursor(egui::CursorIcon::PointingHand); - if hovered { - let x = ui.interact(close, resp.id.with("remove"), Sense::click()); - let label = crate::i18n::fmt(tl!("Remove {name} from Recent"), &[("name", &name)]); - x.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &label)); - let color = crate::icons::button_chrome(ui, close, false, x.hovered()); - crate::icons::paint(ui, close, "x", 12.0, color); - if x.on_hover_text(tl!("Remove from Recent")).clicked() { - remove = Some(path.clone()); - } - } - if resp.clicked() && remove.is_none() { - open = Some(path.clone()); - } - resp.context_menu(|ui| { - if ui.button(tl!("Remove from Recent")).clicked() { - remove = Some(path.clone()); - ui.close(); - } - if ui.button(tl!("Clear Recent Files")).clicked() { - clear = true; - ui.close(); - } - }); - } - if clear { - app.clear_recent(); - } else if let Some(path) = remove { - app.remove_recent(&path); - } - if let Some(path) = open - && let Err(e) = app.open_path(&path) - { - app.open_failed(&crate::file_open::display_name(&path), &e); - } -} - -/// Lattice size of the canvas display LUT (colour management, Proof Colors, Gamut Warning). -const DISPLAY_LUT: usize = 33; - -/// Keep the GPU display LUT under `key` (the document's texture or a preview of it) in step with -/// `doc`'s colour management: document → monitor profile and View › Proof Colors / Gamut -/// Warning (the 32-bit preview is applied by the canvas shader, see [`hdr_preview`]). Returns the canvas `display` mode (0 none — the identity, e.g. sRGB on -/// an sRGB monitor —, 1 LUT, 2 LUT + gamut warning, 3 matrix/shaper). -fn sync_display_lut(app: &mut PhotocraftApp, doc: &photocraft_doc::Document, key: u64, display: Option) -> u8 { - let Some(gpu) = app.gpu.clone() else { return 0 }; - let output = display.unwrap_or(0); - // Rebuild only when anything feeding the LUT changes. - let sig = app.session.color.display_signature_for(doc, display); - if let Some((s, mode)) = gpu.display_lut_signature(key, output) - && s == sig - { - return mode; - } - // Keep the curve/matrix/curve stages separate: interpolating a finished display - // transform on a 33³ lattice crushes shadows when the monitor curve is steep near zero. - if let Ok(Some(shaper)) = app.session.color.gpu_canvas_matrix_shaper_for(doc, display) { - gpu.set_display_matrix_shaper(key, output, &shaper); - gpu.cache_display_lut_signature(key, output, sig, 3); - return 3; - } - let gamut = app.session.color.proof(doc.id).gamut_warning; - let mode = match app.session.color.gpu_canvas_lut_for(doc, DISPLAY_LUT, display) { - Ok(Some(bytes)) => { - gpu.set_display_lut(key, output, DISPLAY_LUT as u32, Some(&bytes)); - if gamut { 2 } else { 1 } - } - Ok(None) => { - gpu.set_display_lut(key, output, DISPLAY_LUT as u32, None); - 0 - } - Err(e) => { - let template = "Color management: {error}"; - app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e.to_string())]); - gpu.set_display_lut(key, output, DISPLAY_LUT as u32, None); - 0 - } - }; - gpu.cache_display_lut_signature(key, output, sig, mode); - mode -} - -/// View › 32-bit Preview Options for the GPU canvas shader: (exposure, gamma) when active. -fn hdr_preview(app: &PhotocraftApp, doc: &photocraft_doc::Document) -> Option<[f32; 2]> { - app.session.color.hdr_preview(doc).map(|h| [h.exposure, h.gamma]) -} - /// Draw one canvas view and handle its input. `primary` = main window (tools active). pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: Rect, mut view: View, primary: bool) -> View { let ctx = ui.ctx().clone(); @@ -5046,198 +1633,6 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: view } -/// Where a wheel or pinch zoom anchors for a pointer at `p`: the pointer itself over the image, -/// otherwise the nearest point of the image (#3720). Anchoring on a pointer out on the gray -/// pasteboard slid the image away from it, out of the window after a few notches; Photoshop keeps -/// the image in view. Clamped in document space, so a rotated or flipped view behaves the same. -fn wheel_anchor(xf: &ViewXform, p: Pos2, doc_size: [u32; 2]) -> Pos2 { - let [w, h] = doc_size; - let d = xf.to_doc(p); - if w == 0 || h == 0 || !(d[0].is_finite() && d[1].is_finite()) { - return p; - } - let c = [d[0].clamp(0.0, f64::from(w)), d[1].clamp(0.0, f64::from(h))]; - if c == d { p } else { xf.to_screen(c[0] as f32, c[1] as f32) } -} - -/// Zoom to `new_zoom` about `p`: keep its document point under the pointer, or move it to the -/// view centre when Zoom Clicked Point to Center (`center_on_point`) is enabled. -fn zoom_about(view: &mut View, xf: &ViewXform, p: Pos2, new_zoom: f32, center_on_point: bool, ppp: f32) { - let before = xf.to_doc(p); - view.zoom = new_zoom; - if center_on_point { - view.center = [before[0] as f32, before[1] as f32]; - return; - } - // `new_zoom` is device px per document pixel; the pointer vector is in egui points. - let ppp = if ppp.is_finite() && ppp > 0.0 { ppp } else { 1.0 }; - let u = xf.unmap_vec((p - xf.rect.center()) / (new_zoom / ppp)); - view.center = [before[0] as f32 - u.x, before[1] as f32 - u.y]; -} - -/// A texture mapped over the `size` document area starting at `origin` (follows a rotated view). -fn paint_mapped_image_at(painter: &egui::Painter, xf: &ViewXform, tex: egui::TextureId, uv: Rect, origin: [f32; 2], size: [f32; 2], tint: Color32) { - let ([x, y], [w, h]) = (origin, size); - let pts = [xf.to_screen(x, y), xf.to_screen(x + w, y), xf.to_screen(x + w, y + h), xf.to_screen(x, y + h)]; - let uvs = [uv.min, pos2(uv.max.x, uv.min.y), uv.max, pos2(uv.min.x, uv.max.y)]; - let mut mesh = Mesh::with_texture(tex); - for i in 0..4 { - mesh.vertices.push(egui::epaint::Vertex { pos: pts[i], uv: uvs[i], color: tint }); - } - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(0, 2, 3); - painter.add(egui::Shape::mesh(mesh)); -} - -/// The GPU canvas view, then its View › Pattern Preview copies (#1067): the same texture drawn -/// again whole document sizes away, each with its own view uniform and no shadow. -fn paint_gpu_view(painter: &egui::Painter, rect: Rect, params: crate::gpu_canvas::ViewParams, copies: &[[i32; 2]]) { - crate::gpu_canvas::GpuCanvas::paint(painter, rect, params); - for (k, &c) in copies.iter().enumerate() { - let copy = crate::gpu_canvas::ViewParams { - offset: crate::pattern_preview::offset(c, params.doc_size), - shadow: false, - // Keyed by slot, not by tile index, so panning reuses the same few uniform buffers. - view_key: egui::Id::unique((params.view_key, "pattern", k)).value(), - ..params - }; - crate::gpu_canvas::GpuCanvas::paint(painter, rect, copy); - } -} - -/// The mapping that draws Pattern Preview copy `c` of a `size` document where it sits next to -/// the document: the same view, looking the matching number of document sizes back. -fn pattern_xf(xf: &ViewXform, c: [i32; 2], size: [u32; 2]) -> ViewXform { - let [ox, oy] = crate::pattern_preview::offset(c, size); - ViewXform { center: [xf.center[0] - ox, xf.center[1] - oy], ..*xf } -} - -/// CPU canvas: the transparency checkerboard (or white) and the display texture, for the -/// document or one of its Pattern Preview copies (`xf` from [`pattern_xf`]). -fn paint_cpu_document( - painter: &egui::Painter, - xf: &ViewXform, - bounds: DRect, - rotated: bool, - checker: Option<(egui::TextureId, f32)>, - tex: Option, - opaque: bool, -) { - let size = [bounds.width() as f32, bounds.height() as f32]; - let origin = [bounds.x0 as f32, bounds.y0 as f32]; - let img_rect = xf.doc_rect(bounds); - match checker { - Some((checker_id, square)) if !opaque || tex.is_none() => { - if rotated { - let tiles = vec2(size[0], size[1]) / (2.0 * square); - paint_mapped_image_at(painter, xf, checker_id, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), origin, size, Color32::WHITE); - } else { - let tiles = img_rect.size() / (2.0 * square); - painter.image(checker_id, img_rect, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), Color32::WHITE); - } - } - // On software window adapters this hidden full-canvas pass is CPU rasterization too. - // Keep the white-background branch unchanged (its antialiased outer edge is visible). - Some(_) => {} - None => { - if rotated { - paint_mapped_quad(painter, xf, origin, size, Color32::WHITE); - } else { - painter.rect_filled(img_rect, 0.0, Color32::WHITE); - } - } - } - if let Some(tex) = tex { - if rotated { - paint_mapped_image_at(painter, xf, tex, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), origin, size, Color32::WHITE); - } else { - let uv = if xf.flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) }; - painter.image(tex, img_rect, uv, Color32::WHITE); - } - } -} - -/// [`ensure_texture_in_view`]'s detail texture over document area `area` (x0, y0, x1, y1), on its -/// own checkerboard (or white), so the reduced texture under it doesn't show through where the -/// image is transparent. The checkerboard keeps [`paint_cpu_document`]'s phase. -fn paint_cpu_detail( - painter: &egui::Painter, - xf: &ViewXform, - bounds: DRect, - rotated: bool, - checker: Option<(egui::TextureId, f32)>, - tex: egui::TextureId, - area: [f32; 4], -) { - let [x0, y0, x1, y1] = area; - let corners = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]]; - let pts = corners.map(|[x, y]| xf.to_screen(x, y)); - let quad = |tex: egui::TextureId, uvs: [Pos2; 4]| { - let mut mesh = Mesh::with_texture(tex); - for (pos, uv) in pts.into_iter().zip(uvs) { - mesh.vertices.push(egui::epaint::Vertex { pos, uv, color: Color32::WHITE }); - } - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(0, 2, 3); - painter.add(egui::Shape::mesh(mesh)); - }; - match checker { - Some((checker_id, square)) => { - let tile = 2.0 * square; - let uvs = if rotated { - corners.map(|[x, y]| pos2(x / tile, y / tile)) - } else { - let min = xf.doc_rect(bounds).min; - pts.map(|p| ((p - min) / tile).to_pos2()) - }; - quad(checker_id, uvs); - } - None => { - painter.add(egui::Shape::convex_polygon(pts.to_vec(), Color32::WHITE, Stroke::NONE)); - } - } - quad(tex, [pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)]); -} - -fn paint_mapped_quad(painter: &egui::Painter, xf: &ViewXform, origin: [f32; 2], size: [f32; 2], color: Color32) { - let ([x, y], [w, h]) = (origin, size); - let pts = vec![xf.to_screen(x, y), xf.to_screen(x + w, y), xf.to_screen(x + w, y + h), xf.to_screen(x, y + h)]; - painter.add(egui::Shape::convex_polygon(pts, color, Stroke::NONE)); -} - -/// Draw boundary segments as marching ants: white base, black dashes phased along x + y. -fn marching_ants_segments(painter: &egui::Painter, xf: &ViewXform, segs: &[crate::outline::Segment], time: f64) { - marching_ants_mapped(painter, segs, time, |p| xf.to_screen(p[0] as f32, p[1] as f32)); -} - -/// [`marching_ants_segments`] with each outline point placed on screen by `to_screen` (a -/// transformed outline: Content-Aware Move's Transform On Drop). -pub(crate) fn marching_ants_mapped(painter: &egui::Painter, segs: &[crate::outline::Segment], time: f64, to_screen: impl Fn([i32; 2]) -> Pos2) { - marching_ants_lines(painter, segs.iter().map(|(a, b)| (to_screen(*a), to_screen(*b))), time); -} - -/// The part of the line `a`–`b` inside `r` (Liang–Barsky), if any. -pub(crate) fn clip_line(r: Rect, a: Pos2, b: Pos2) -> Option<(Pos2, Pos2)> { - // Perspective can put endpoints billions of pixels away. f32 subtraction/interpolation - // loses viewport-sized differences there, clipping visible ants to the wrong endpoints. - let (ax, ay) = (f64::from(a.x), f64::from(a.y)); - let (dx, dy) = (f64::from(b.x) - ax, f64::from(b.y) - ay); - let (mut t0, mut t1) = (0.0f64, 1.0f64); - for (p, q) in [(-dx, ax - f64::from(r.min.x)), (dx, f64::from(r.max.x) - ax), (-dy, ay - f64::from(r.min.y)), (dy, f64::from(r.max.y) - ay)] { - if p == 0.0 { - if q < 0.0 { - return None; - } - } else if p < 0.0 { - t0 = t0.max(q / p); - } else { - t1 = t1.min(q / p); - } - } - let at = |t: f64| pos2((ax + dx * t) as f32, (ay + dy * t) as f32); - (t0 <= t1).then(|| (at(t0), at(t1))) -} - #[cfg(test)] mod transform_outline_clip_tests { use super::*; @@ -5257,1822 +1652,6 @@ mod transform_outline_clip_tests { } } -/// Marching ants along lines already placed on screen (a warped outline is a run of short ones), -/// in device pixels like Photoshop's (`crate::ants`, #7489). -pub(crate) fn marching_ants_lines(painter: &egui::Painter, lines: impl Iterator, time: f64) { - crate::ants::draw(painter, lines, time, true); -} - -/// Photoshop crop overlay: the `shield` outside (`crop_shield::fill`; none when disabled), bright -/// frame, the composition `guides` (unit-square polylines, `crop_overlay::guides`), corner and -/// edge handles. -fn crop_overlay(painter: &egui::Painter, r: Rect, shield: Option, guides: &[crate::crop_overlay::Polyline]) { - let clip = painter.clip_rect(); - if let Some(dim) = shield { - for band in [ - Rect::from_min_max(clip.min, egui::pos2(clip.max.x, r.min.y)), - Rect::from_min_max(egui::pos2(clip.min.x, r.max.y), clip.max), - Rect::from_min_max(egui::pos2(clip.min.x, r.min.y), egui::pos2(r.min.x, r.max.y)), - Rect::from_min_max(egui::pos2(r.max.x, r.min.y), egui::pos2(clip.max.x, r.max.y)), - ] { - painter.rect_filled(band, 0.0, dim); - } - } - painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Middle); - draw_crop_guides(painter, guides, |a, b| r.min + r.size() * vec2(a, b)); - let h = Stroke::new(3.0, Color32::WHITE); - let l = 14.0f32.min(r.width() / 3.0).min(r.height() / 3.0); - for (c, dx, dy) in [(r.left_top(), 1.0, 1.0), (r.right_top(), -1.0, 1.0), (r.left_bottom(), 1.0, -1.0), (r.right_bottom(), -1.0, -1.0)] { - painter.line_segment([c, c + vec2(l * dx, 0.0)], h); - painter.line_segment([c, c + vec2(0.0, l * dy)], h); - } - // Edge handles: short bars at the middle of each side. - let (lx, ly) = (l.min(r.width() / 4.0) / 2.0, l.min(r.height() / 4.0) / 2.0); - for (c, horizontal) in [(r.center_top(), true), (r.center_bottom(), true), (r.left_center(), false), (r.right_center(), false)] { - let e = if horizontal { vec2(lx, 0.0) } else { vec2(0.0, ly) }; - painter.line_segment([c - e, c + e], h); - } -} - -/// [`crop_overlay`] for a turned frame (or a rotated view): `q` is the frame's top-left, top-right, -/// bottom-right and bottom-left corner on screen, a parallelogram. -fn crop_overlay_turned(painter: &egui::Painter, q: [Pos2; 4], shield: Option, guides: &[crate::crop_overlay::Polyline]) { - let (u, v) = (q[1] - q[0], q[3] - q[0]); - let (lu, lv) = (u.length(), v.length()); - if !(lu.is_finite() && lv.is_finite()) || lu < 1e-3 || lv < 1e-3 { - return; - } - let at = |a: f32, b: f32| q[0] + u * a + v * b; - // The shield: four trapezoids from the frame out to the frame grown past the whole view. - let clip = painter.clip_rect(); - let reach = clip.size().length() + (clip.center() - at(0.5, 0.5)).length(); - let (eu, ev) = (reach / lu, reach / lv); - let outer = [at(-eu, -ev), at(1.0 + eu, -ev), at(1.0 + eu, 1.0 + ev), at(-eu, 1.0 + ev)]; - if let Some(dim) = shield { - let mut mesh = egui::Mesh::default(); - for p in q.iter().chain(outer.iter()) { - mesh.colored_vertex(*p, dim); - } - for i in 0..4u32 { - let j = (i + 1) % 4; - mesh.add_triangle(i, j, 4 + j); - mesh.add_triangle(i, 4 + j, 4 + i); - } - painter.add(egui::Shape::mesh(mesh)); - } - painter.add(egui::Shape::closed_line(q.to_vec(), Stroke::new(1.0, Color32::WHITE))); - draw_crop_guides(painter, guides, at); - let h = Stroke::new(3.0, Color32::WHITE); - let l = 14.0f32.min(lu / 3.0).min(lv / 3.0); - let (du, dv) = (u / lu, v / lv); - for (c, su, sv) in [(q[0], 1.0, 1.0), (q[1], -1.0, 1.0), (q[3], 1.0, -1.0), (q[2], -1.0, -1.0)] { - painter.line_segment([c, c + du * (l * su)], h); - painter.line_segment([c, c + dv * (l * sv)], h); - } - // Edge handles: short bars at the middle of each side, along it. - let (lx, ly) = (l.min(lu / 4.0) / 2.0, l.min(lv / 4.0) / 2.0); - for (c, e) in [(at(0.5, 0.0), du * lx), (at(0.5, 1.0), du * lx), (at(0.0, 0.5), dv * ly), (at(1.0, 0.5), dv * ly)] { - painter.line_segment([c - e, c + e], h); - } -} - -/// The crop overlay's guides, each unit-square point placed on screen by `at`. -fn draw_crop_guides(painter: &egui::Painter, guides: &[crate::crop_overlay::Polyline], at: impl Fn(f32, f32) -> Pos2) { - let thin = Stroke::new(1.0, Color32::from_white_alpha(90)); - for l in guides { - painter.add(egui::Shape::line(l.iter().map(|p| at(p[0], p[1])).collect(), thin)); - } -} - -/// What the Crop tool shows past the canvas, cached per document state ([`draw_beyond_canvas`]). -#[derive(Clone)] -struct BeyondCanvas { - snapshot: std::sync::Weak, - key: u64, - /// Every layer's pixels and the canvas (`extra_cmds::reveal_all_bounds`). - extent: DRect, - /// The composite around the canvas: each band, the area its texture covers, the texture. - bands: Vec<(DRect, DRect, egui::TextureHandle)>, -} - -/// Band `r` around the canvas `c` (on screen) pushed a point under the canvas's edge, so that the -/// edge's anti-aliased pixels blend with the band rather than with the pasteboard. -fn under_canvas(mut r: Rect, c: Rect) -> Rect { - let near = |a: f32, b: f32| (a - b).abs() < 0.01; - if near(r.max.y, c.min.y) { - r.max.y += 1.0; - } - if near(r.min.y, c.max.y) { - r.min.y -= 1.0; - } - if near(r.max.x, c.min.x) { - r.max.x += 1.0; - } - if near(r.min.x, c.max.x) { - r.min.x -= 1.0; - } - r -} - -/// `outer` minus `inner`: the bands above, below, left and right of it (empty ones dropped). -fn ring(outer: DRect, inner: DRect) -> Vec { - let i = inner.intersect(&outer); - if i.is_empty() { - return if outer.is_empty() { Vec::new() } else { vec![outer] }; - } - [ - DRect::new(outer.x0, outer.y0, outer.x1, i.y0), - DRect::new(outer.x0, i.y1, outer.x1, outer.y1), - DRect::new(outer.x0, i.y0, i.x0, i.y1), - DRect::new(i.x1, i.y0, outer.x1, i.y1), - ] - .into_iter() - .filter(|r| !r.is_empty()) - .collect() -} - -/// Crop tool, while a frame is edited (`crop_ui::shows_beyond_canvas`): like Photoshop's crop -/// preview, the canvas grows to every layer's pixels (a crop with Delete Cropped Pixels off keeps -/// them; a moved layer reaches past the edges) and to the frame, transparency drawn as the -/// checkerboard, all under the shield `crop_overlay` adds. Only the ring around the canvas is -/// composited, on the CPU, once per document state: at most `MAX_TEXTURE` texels per side, from a -/// downsampled proxy past that (so a far-off layer costs no more than a 16 MP composite). -/// Drawn before the canvas, each band reaching a point under its edge. Returns whether anything -/// past the canvas was drawn. -fn draw_beyond_canvas(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, idx: usize, output: Option) -> bool { - let ctx = painter.ctx().clone(); - let Some((snapshot, id)) = app.session.documents().get(idx).map(|st| (std::sync::Arc::downgrade(&st.doc), st.doc.id)) else { return false }; - let key = egui::Id::unique(("crop-beyond-canvas", id.0, output)); - let frame = - app.ui.crop_rect.filter(|f| f.iter().all(|v| v.is_finite()) && app.session.active_index() == Some(idx) && crate::crop_ui::shows_beyond_canvas(app)); - let Some(f) = frame else { - ctx.data_mut(|d| d.remove::(key)); - return false; - }; - let (doc, preview_key) = display_doc(app, idx); - if doc.has_artboards() { - return false; - } - let (display, display_key) = canvas_display(app, &doc, output); - let doc_key = preview_key ^ display_key; - let cached: Option = ctx.data(|d| d.get_temp(key)); - let c = match cached.filter(|c| c.snapshot.ptr_eq(&snapshot) && c.key == doc_key) { - Some(c) => c, - None => { - let t0 = crate::gpu_canvas::now_ms(); - let extent = photocraft_engine::extra_cmds::reveal_all_bounds(&doc); - // One texel per `k` document pixels keeps every texture within the device's side. - let k = extent.width().max(extent.height()).div_ceil(texture_side(&ctx)).max(1); - let proxy = (k > 1).then(|| photocraft_compose::proxy::proxy_document(&doc, k)); - let src = proxy.as_ref().unwrap_or(&*doc); - let k = k as i32; - let opts = TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR }; - let bands = ring(extent, doc.bounds()) - .into_iter() - .map(|b| { - // The proxy pixels over `b`: document pixels / k, rounded outwards. - let up = |v: i32| v.div_euclid(k) + i32::from(v.rem_euclid(k) != 0); - let p = DRect::new(b.x0.div_euclid(k), b.y0.div_euclid(k), up(b.x1), up(b.y1)); - let buf = photocraft_compose::render_reduced_rect(src, p, p.width(), p.height()); - let tex = ctx.load_texture("crop-beyond-canvas", display_image(display.as_deref(), &buf), opts); - (b, DRect::new(p.x0.saturating_mul(k), p.y0.saturating_mul(k), p.x1.saturating_mul(k), p.y1.saturating_mul(k)), tex) - }) - .collect(); - app.perf.span("crop-beyond-canvas", crate::gpu_canvas::now_ms() - t0); - let c = BeyondCanvas { snapshot, key: doc_key, extent, bands }; - ctx.data_mut(|d| d.insert_temp(key, c.clone())); - c - } - }; - // Transparency out to the frame, in phase with the canvas's own checkerboard. - let canvas = xf.doc_rect(doc.bounds()); - // A turned frame reaches as far as its corners. - let f = crate::crop_ui::turned_bounds(f, crate::crop_ui::angle(app)); - let fr = DRect::new(f[0].floor() as i32, f[1].floor() as i32, f[2].ceil() as i32, f[3].ceil() as i32); - let square = app.session.prefs().transparency_and_gamut.square(); - let checker_id = square.map(|_| checker(app, &ctx)); - let around = ring(c.extent.union(&fr), doc.bounds()); - // A turned view (Rotate View, or the Crop tool's default mode turning the image behind its - // box) draws each band as its turned quad: its screen bounding box would stretch the band's - // texture and spread the checkerboard past the band. - let turned = xf.rotation != 0.0; - let checker_uv = |p: Pos2, sq: f32| ((p - canvas.min) / (2.0 * sq)).to_pos2(); - for &b in &around { - if turned { - let q = doc_quad(xf, b); - match square.zip(checker_id) { - Some((sq, id)) => textured_quad(painter, id, q, q.map(|p| checker_uv(p, sq))), - None => { - painter.add(egui::Shape::convex_polygon(q.to_vec(), Color32::WHITE, Stroke::NONE)); - } - } - continue; - } - let r = under_canvas(xf.doc_rect(b), canvas); - match square.zip(checker_id) { - Some((sq, id)) => { - let uv = Rect::from_min_max(checker_uv(r.min, sq), checker_uv(r.max, sq)); - painter.image(id, r, uv, Color32::WHITE); - } - None => { - painter.rect_filled(r, 0.0, Color32::WHITE); - } - } - } - for (b, t, tex) in &c.bands { - let part = |a: i32, o: i32, len: u32| (i64::from(a) - i64::from(o)) as f32 / len.max(1) as f32; - let (mut u0, mut u1) = (part(b.x0, t.x0, t.width()), part(b.x1, t.x0, t.width())); - if turned { - // The quad's corners are the band's own (flip included), so no swap. - let (v0, v1) = (part(b.y0, t.y0, t.height()), part(b.y1, t.y0, t.height())); - textured_quad(painter, tex.id(), doc_quad(xf, *b), [pos2(u0, v0), pos2(u1, v0), pos2(u1, v1), pos2(u0, v1)]); - continue; - } - if xf.flip { - (u0, u1) = (u1, u0); - } - let uv = Rect::from_min_max(pos2(u0, part(b.y0, t.y0, t.height())), pos2(u1, part(b.y1, t.y0, t.height()))); - // The texture's edge texels stretch over the point under the canvas. - let (r, e) = (xf.doc_rect(*b), under_canvas(xf.doc_rect(*b), canvas)); - let at = |p: Pos2| uv.min + (p - r.min) / r.size() * uv.size(); - painter.image(tex.id(), e, Rect::from_min_max(at(e.min), at(e.max)), Color32::WHITE); - } - !around.is_empty() -} - -/// Document rect `b`'s corners on screen, clockwise from its top-left (a parallelogram in a turned -/// view). -fn doc_quad(xf: &ViewXform, b: DRect) -> [Pos2; 4] { - [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| xf.to_screen(x as f32, y as f32)) -} - -/// Texture `tex` drawn over the quad `q`, `uv` at its corners. -fn textured_quad(painter: &egui::Painter, tex: egui::TextureId, q: [Pos2; 4], uv: [Pos2; 4]) { - if !q.iter().chain(uv.iter()).all(|p| p.x.is_finite() && p.y.is_finite()) { - return; - } - let mut mesh = egui::Mesh::with_texture(tex); - for (pos, uv) in q.into_iter().zip(uv) { - mesh.vertices.push(egui::epaint::Vertex { pos, uv, color: Color32::WHITE }); - } - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(0, 2, 3); - painter.add(egui::Shape::mesh(mesh)); -} - -/// Overlays that persist between gestures: polygonal or magnetic lasso in progress, pending crop box. -fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, hover: Option) { - crate::magnetic_lasso_ui::draw(app, painter, xf, hover); - if !app.ui.polygon.is_empty() { - let mut pts: Vec = app.ui.polygon.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect(); - if let Some(h) = hover { - // The rubber-band preview must use the same constrained point as the click, - // including when the canvas is zoomed, rotated or flipped. - let mods = painter.ctx().input(|i| i.modifiers); - if app.ui.tool == Tool::PolygonLasso && mods.shift && !mods.alt { - let raw = xf.to_doc(h); - let last = app.ui.polygon.last().copied().unwrap_or(raw); - let snapped = constrained_polygon_point(last, raw); - pts.push(xf.to_screen(snapped[0] as f32, snapped[1] as f32)); - } else { - pts.push(h); - } - } - // Just the outline and its rubber band (the vertices aren't handles to grab), solid until - // the selection is made (#7495). - crate::tool_feedback::draw_solid_path(painter, &pts, false); - } - crate::crop_straighten::draw(app, painter, |p| xf.to_screen(p[0] as f32, p[1] as f32), hover); - crate::blur_pins::draw(app, painter, xf); - if let Some(c) = app.ui.crop_rect { - let deg = crate::crop_ui::angle(app); - let shield = crate::crop_shield::current(app, painter.ctx()); - if deg == 0.0 && xf.rotation == 0.0 { - let r = Rect::from_two_pos(xf.to_screen(c[0] as f32, c[1] as f32), xf.to_screen(c[2] as f32, c[3] as f32)); - crop_overlay(painter, r, shield, &crate::crop_overlay::current_guides(app, r.width(), r.height())); - } else { - let q = crate::crop_ui::corners(c, deg).map(|p| xf.to_screen(p[0] as f32, p[1] as f32)); - crop_overlay_turned(painter, q, shield, &crate::crop_overlay::current_guides(app, q[0].distance(q[1]), q[0].distance(q[3]))); - } - // The frame's angle beside the pointer while it turns (#1792). - if let (Some(a), Some(h)) = (crate::crop_ui::turning(app), hover) { - draw_value_readout(app, painter.ctx(), "crop-angle-readout", h, ["Angle:"], [angle_readout(a)]); - } else if let (Some([w, h]), Some(at)) = (crate::crop_ui::sizing(app), hover) { - // Its W × H while it is drawn or resized (#1919), like the marquee's. - draw_marquee_readout(app, painter.ctx(), at, size_readout(app, [0.0, 0.0, w, h])); - } - } -} - -/// View › Show › Layer Edges: the active layer's content bounds (cached per tile) where the canvas -/// shows them. During a Move drag that is at the offset the image was drawn with this frame, so -/// the outline moves in lockstep with the layer's pixels (#2413). -pub(crate) fn layer_edges_rect(app: &PhotocraftApp, idx: usize) -> Option { - if !app.ui.view.shows(app.ui.view.show.layer_edges) { - return None; - } - let st = app.session.documents().get(idx)?; - let id = st.active_layer?; - let b = st.doc.layer(id)?.surface().map(photocraft_compose::bounds::content_bounds)?; - if b.is_empty() { - return None; - } - let (dx, dy) = crate::move_ui::shown_layer_offset(app, st.doc.id, st.revision, id).unwrap_or((0, 0)); - Some(b.translate(dx, dy)) -} - -/// The layers Move › Show Transform Controls frames: every selected layer but the Background. -/// A corner radius drag hides the box, as in Photoshop. So does View › Extras (⌘H, #6699): the -/// controls are an Extra, hidden and inert until Extras comes back, while Show Transform Controls -/// keeps its setting. -fn transform_controls_layers(app: &PhotocraftApp) -> Vec<&photocraft_doc::Layer> { - if app.ui.tool != Tool::Move - || !app.ui.tool_options.move_show_transform - || !app.ui.view.extras - || app.ui.transform.is_some() - || app.drag.is_some() - || app.ui.corner_radius.is_some() - { - return Vec::new(); - } - let Some(st) = app.session.active() else { return Vec::new() }; - st.selected_layers().into_iter().filter_map(|id| st.doc.layer(id)).filter(|l| !crate::doc_props_ui::is_background(&st.doc, l)).collect() -} - -/// Several layers are selected: Show Transform Controls frames them all, as Photoshop does, but -/// Free Transform works on one layer, so the frame has no handles to scale or rotate them. -fn transform_controls_several(app: &PhotocraftApp) -> bool { - transform_controls_layers(app).len() > 1 -} - -/// Move tool › Show Transform Controls: the boxes Free Transform would open on the selected -/// layers, joined into one. -fn transform_controls_rect(app: &PhotocraftApp, xf: &ViewXform) -> Option { - let st = app.session.active()?; - let layers = transform_controls_layers(app); - let b = layers.iter().map(|l| photocraft_engine::transform_cmds::transform_frame(&st.doc, l)).filter(|b| !b.is_empty()).reduce(|a, b| a.union(&b))?; - // Floating selected pixels are framed by their outline, as their ants are (#7538), not by the - // selection they were cut with; a frame round other selected layers too keeps them all. - let alone = matches!(layers.as_slice(), [l] if photocraft_engine::float_cmds::floating(st).is_some_and(|f| f.layer == l.id)); - let b = app.session.active_index().filter(|_| alone).and_then(|idx| floating_outline(app, idx)).map_or(b, |o| o.content_bounds()); - let (dx, dy) = crate::move_ui::floating_offset(app).unwrap_or((0, 0)); - let b = b.translate(dx, dy); - if b.is_empty() { - return None; - } - Some(Rect::from_two_pos(xf.to_screen(b.x0 as f32, b.y0 as f32), xf.to_screen(b.x1 as f32, b.y1 as f32))) -} - -/// The Move tool shows transform handles even before a Free Transform session exists. -/// Use the same hit areas for pointer-down and hover, so a control never behaves like -/// resize/rotate while showing the ordinary four-arrow Move cursor (#2871). -fn transform_controls_cursor(r: Rect, p: Pos2) -> Option { - let handles = [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()]; - let grab = crate::transform_tool::HANDLE_PX as f32; - for (i, handle) in handles.into_iter().enumerate() { - if handle.distance(p) <= grab { - return Some(match i { - 0 | 4 => egui::CursorIcon::ResizeNwSe, - 2 | 6 => egui::CursorIcon::ResizeNeSw, - 1 | 5 => egui::CursorIcon::ResizeVertical, - _ => egui::CursorIcon::ResizeHorizontal, - }); - } - } - // The rotation band: the pointer gives way to the curved rotate arrow (`transform_controls_turn`). - in_rotation_band(r, p).then_some(egui::CursorIcon::None) -} - -fn in_rotation_band(r: Rect, p: Pos2) -> bool { - r.expand(18.0).contains(p) && !r.expand(5.0).contains(p) -} - -/// In the rotation band just outside the Move tool's transform controls, the screen direction the -/// curved rotate arrow bends round: into the box along the nearest corner's bisector, as Free -/// Transform draws it (#4658). Before, the band showed a plain alias pointer, so nothing said a -/// drag there rotates. -fn transform_controls_turn(r: Rect, p: Pos2) -> Option { - if !in_rotation_band(r, p) - || [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()] - .into_iter() - .any(|h| h.distance(p) <= crate::transform_tool::HANDLE_PX as f32) - { - return None; - } - let corner = pos2(if p.x < r.center().x { r.left() } else { r.right() }, if p.y < r.center().y { r.top() } else { r.bottom() }); - Some(vec2((r.center().x - corner.x).signum(), (r.center().y - corner.y).signum()).normalized() * 16.0) -} - -/// A visible handle starts scaling; the narrow band just outside the box starts rotation. -/// The interior stays the normal Move-tool drag target. -fn transform_controls_hit(r: Rect, p: Pos2) -> bool { - transform_controls_cursor(r, p).is_some() -} - -/// Enter the existing Free Transform session when a Move-tool transform control is pressed. -fn begin_transform_controls_at(app: &mut PhotocraftApp, ctx: &egui::Context, xf: &ViewXform, p: Pos2) -> bool { - if transform_controls_several(app) { - return false; - } - let Some(r) = transform_controls_rect(app, xf) else { return false }; - if !transform_controls_hit(r, p) { - return false; - } - match crate::transform_tool::begin(app, ctx) { - Ok(()) => true, - Err(e) => { - app.ui.status = e; - false - } - } -} - -/// Move tool › Show Transform Controls: the selected layers' bounding box, with its eight handles -/// for one layer, and the outline of every selected shape layer, as in Photoshop. -fn draw_transform_controls(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { - let Some(r) = transform_controls_rect(app, xf) else { return }; - let accent = crate::theme::Tokens::get(painter.ctx()).accent; - let to_scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32); - for l in transform_controls_layers(app) { - if let LayerContent::Shape(sh) = &l.content { - crate::vector_ui::draw_outline(painter, &sh.path, &to_scr, accent); - } - } - painter.rect_stroke(r, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Middle); - if transform_controls_several(app) { - return; - } - for p in [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()] { - let h = Rect::from_center_size(p, vec2(7.0, 7.0)); - painter.rect_filled(h, 0.0, Color32::WHITE); - painter.rect_stroke(h, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside); - } -} - -/// The line from the brush to the pointer while stroke smoothing lags (Pulled String Mode and -/// Stroke Catch-up, #3479): a dark underlay and a light line stay visible on any pixels, and a dot -/// marks the brush end. -fn draw_smoothing_string(painter: &egui::Painter, xf: &ViewXform, (brush, pointer): ([f64; 2], [f64; 2])) { - let (a, b) = (xf.to_screen(brush[0] as f32, brush[1] as f32), xf.to_screen(pointer[0] as f32, pointer[1] as f32)); - if a.distance(b) < 2.0 { - return; - } - painter.line_segment([a, b], Stroke::new(3.0, Color32::from_black_alpha(110))); - painter.line_segment([a, b], Stroke::new(1.0, Color32::WHITE)); - painter.circle_filled(a, 2.5, Color32::WHITE); -} - -fn draw_drag_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { - draw_tool_state(app, painter, xf, painter.ctx().input(|i| i.pointer.hover_pos())); - // Remove strokes waiting for ↩ stay tinted between drags. - crate::retouch_ui::draw_remove_pending(app, painter, xf); - let Some(d) = &app.drag else { - app.trail = None; - return; - }; - // The Move tool's ΔX/ΔY beside the pointer, for layers and selected pixels alike (#5727). - if let Some(values) = crate::move_ui::offset_readout(app) { - let at = d.points.last().map_or(d.start, |p| [p[0], p[1]]); - draw_value_readout(app, painter.ctx(), "move-readout", xf.to_screen(at[0] as f32, at[1] as f32), ["ΔX:", "ΔY:"], values); - } - // Dragging the selection: its own ants follow the pointer (`selection_shown_offset`). - if d.sel_move.is_some() { - return; - } - let last = d.points.last().map(|p| [p[0], p[1]]).unwrap_or(d.start); - let marquee = marquee_preview_px(&app.ui.tool_options, d, app.point_zoom()); - if let Some(r) = marquee { - draw_marquee_readout(app, painter.ctx(), xf.to_screen(last[0] as f32, last[1] as f32), size_readout(app, r)); - } - match d.tool { - // The canvas shows the live stroke itself (`LiveStroke`); a stroke that couldn't start one - // (Sample All Layers, say) keeps the trail. - t if strokes_live(t) && app.live_stroke.is_some() => { - // Smoothing holds the brush back from the pointer: draw the string between them. - if let Some(EngineStroke::Brush(l)) = app.live_stroke.as_ref().map(|l| &l.stroke) - && let Some(s) = l.smoothing_string() - { - draw_smoothing_string(painter, xf, s); - } - } - t if t.is_brushlike() || t == Tool::QuickSelection => { - // Retouching strokes preview as a translucent trail of the brush footprint: a mask, - // not a brush-wide egui polyline (which zoomed in tessellates into wedges, #189). - let col = match t { - Tool::QuickSelection => Color32::from_white_alpha(40), - // The Remove Tool tints what it will remove, like Photoshop's. - Tool::Remove => crate::theme::Tokens::get(painter.ctx()).danger.gamma_multiply(0.45), - // Photoshop paints the area to heal in half-opaque dark grey while dragging; a faint - // white trail barely showed on light pixels (#7342). The heal itself is computed on - // release. - Tool::SpotHealing => SPOT_HEALING_TRAIL, - _ => Color32::from_white_alpha(60), - }; - let Some(st) = app.session.active() else { return }; - let size = [st.doc.size.width, st.doc.size.height]; - let doc_rect = xf.doc_rect(st.doc.bounds()); - let trail = app.trail.get_or_insert_with(|| crate::stroke_trail::Trail::new(size)); - if t == Tool::SpotHealing { - // What the heal covers, dab by dab: soft edges, pressure and shape dynamics (#2364). - trail.feed_dabs(&d.points, || photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &json!({}))); - } else { - trail.feed(&d.points, app.session.tools.brush.size); - } - trail.draw(painter, doc_rect, xf.flip, col); - } - t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::draw_shape_preview(app, painter, xf, t, d.start, last, d.live), - Tool::SingleRowMarquee | Tool::SingleColumnMarquee => { - // Mapped corner by corner like the other marquees, so a rotated view shows the line - // where the release commits it (#2512). - if let Some([x0, y0, x1, y1]) = single_line_drag_px(app, d) { - crate::tool_feedback::draw_ants(painter, &marquee_ants(xf, d.tool, [x0, y0], [x1, y1]), true); - } - } - // Nothing selected yet: no outline, as the release would deselect. - Tool::RectMarquee | Tool::EllipseMarquee if marquee.is_none() => {} - Tool::RectMarquee | Tool::EllipseMarquee | Tool::ObjectSelection => { - // Marching ants, visible on any pixels (#172): built in document space and mapped - // corner by corner, so a rotated view shows them where the release commits (#2512). - let pts = marquee_drag_ants(d, xf, marquee); - crate::tool_feedback::draw_ants(painter, &pts, true); - } - // 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); - 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)); - } - } - Tool::FreeformPen => { - let mut pts: Vec = d.points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect(); - // Between ⌥-clicks: the straight segment the next click makes. - if let Some(lasso) = &d.lasso { - pts.push(xf.to_screen(lasso.cursor[0] as f32, lasso.cursor[1] as f32)); - } - painter.add(egui::Shape::line(pts, Stroke::new(1.5, crate::theme::Tokens::get(painter.ctx()).accent))); - } - Tool::Lasso | Tool::Patch | Tool::ContentAwareMove => { - let mut pts: Vec = d.points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect(); - if let Some(lasso) = &d.lasso { - pts.push(xf.to_screen(lasso.cursor[0] as f32, lasso.cursor[1] as f32)); - } - // The Lasso's outline is solid until the release makes the selection (#7495); a Patch - // or Content-Aware Move area keeps its ants. - if d.tool == Tool::Lasso { - // On pixel centres, so a 1 pt line stays crisp wherever the canvas sits (a pixel - // edge would blur it to grey). - let pts: Vec = pts.into_iter().map(|p| p.round() + vec2(0.5, 0.5)).collect(); - crate::tool_feedback::draw_solid_path(painter, &pts, false); - } else { - crate::tool_feedback::draw_ants(painter, &pts, false); - } - } - Tool::Gradient => { - let a = xf.to_screen(d.start[0] as f32, d.start[1] as f32); - let b = xf.to_screen(last[0] as f32, last[1] as f32); - painter.line_segment([a, b], Stroke::new(3.0, Color32::from_black_alpha(140))); - painter.line_segment([a, b], Stroke::new(1.0, Color32::WHITE)); - painter.circle_filled(a, 3.0, Color32::WHITE); - painter.circle_filled(b, 3.0, Color32::WHITE); - } - Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => { - let r = Rect::from_two_pos(xf.to_screen(d.start[0] as f32, d.start[1] as f32), xf.to_screen(last[0] as f32, last[1] as f32)); - let pts = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom(), r.left_top()]; - painter.add(egui::Shape::line(pts.to_vec(), Stroke::new(1.0, Color32::WHITE))); - painter.add(egui::Shape::dashed_line(&pts, Stroke::new(1.0, Color32::BLACK), 3.0, 3.0)); - } - // The layers themselves follow the pointer (`move_ui`); the arrow only when they can't. - Tool::Move if !crate::move_ui::showing(app) => { - let from = xf.to_screen(d.start[0] as f32, d.start[1] as f32); - let off = xf.to_screen(last[0] as f32, last[1] as f32) - from; - painter.arrow(from, off, Stroke::new(2.0, crate::theme::Tokens::get(painter.ctx()).accent)); - } - _ => {} - } -} - -/// Tools on which holding ⌥ (Alt) switches to the Eyedropper: a click or drag sets the -/// foreground colour, as with the Eyedropper itself (#417). -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) -} - -/// Preferences › Cursors › Other Cursors asks for the precise crosshair, or Caps Lock swaps the -/// standard cursor for it (and back), as in Photoshop (#4639). -fn precise_other_cursor(app: &PhotocraftApp) -> bool { - (app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise) != app.caps_lock -} - -/// A pen tool's standard cursor: its toolbar icon with the nib (the Convert Point tool: the -/// anchor) on `p`. Draws it at `p` and returns the OS cursor to set (hidden). -pub(crate) fn pen_cursor(ctx: &egui::Context, tool: Tool, p: Pos2) -> egui::CursorIcon { - // Where each icon's point is in its 24-unit box: the full-size pen's nib at (2.3, 2.3); the - // Freeform and Curvature pens draw it at 0.68 × from (7, 7); Convert Point's apex anchor. - let hot = match tool { - Tool::FreeformPen | Tool::CurvaturePen => vec2(8.56, 8.56), - Tool::ConvertPoint => vec2(12.0, 7.0), - _ => vec2(2.3, 2.3), - }; - crate::icons::cursor(ctx, crate::icons::tool_icon(tool), p, hot / 24.0, 22.0); - egui::CursorIcon::None -} - -/// The sampling cursor: a pipette whose tip is the sampled pixel. Draws it at `p` and returns the -/// OS cursor to set (hidden). -pub(crate) fn pipette_cursor(ctx: &egui::Context, p: Pos2) -> egui::CursorIcon { - // The tip of the icon's pipette is at (2, 22) of its 24-unit box. - crate::icons::cursor(ctx, "pipette", p, vec2(2.0, 22.0) / 24.0, 20.0); - egui::CursorIcon::None -} - -/// The Paint Bucket's cursor: a bucket whose pouring corner is the filled pixel. Draws it at `p` -/// and returns the OS cursor to set (hidden). -pub(crate) fn paint_bucket_cursor(ctx: &egui::Context, p: Pos2) -> egui::CursorIcon { - // The left corner of the icon's bucket is at (2, 12) of its 24-unit box. - crate::icons::cursor(ctx, "paint-bucket", p, vec2(2.0, 12.0) / 24.0, 22.0); - egui::CursorIcon::None -} - -/// Decided when the press starts, so ⌥ pressed or released mid-stroke never switches between -/// painting and sampling. -fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { - if matches!(ev, ToolEvent::Down { .. }) { - let physical_right = app.services.right_button_down.as_ref().is_some_and(|f| f()); - app.alt_sampling = !physical_right && alt_samples(app.active_tool(), mods); - } - if !app.alt_sampling { - return false; - } - match ev { - // Without ⌥: the sample sets the foreground colour, whatever the Eyedropper would do. - ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } => sample_eyedropper(app, x, y, egui::Modifiers::NONE), - ToolEvent::Up { .. } => app.alt_sampling = false, - } - true -} - -fn sample_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { - if let Some([r, g, b]) = eyedropper_color(app, x, y) { - let key = if mods.alt { "background" } else { "foreground" }; - let _ = app.run("tools.setColors", json!({ key: [r, g, b, 1.0] })); - } -} - -/// The colour at document point (x, y) with the Eyedropper's Sample Size (the composite pixel, -/// or the average of the square around it) from the layers `sample_layer` names (`document.sampleColor`). -/// `None` off the image or over transparency. -fn sample_color(app: &mut PhotocraftApp, x: f64, y: f64, sample_layer: &str) -> Option<[f32; 3]> { - if !(x.is_finite() && y.is_finite()) { - return None; - } - let size = app.ui.tool_options.eyedropper_size; - let v = app.run("document.sampleColor", json!({"x": x, "y": y, "size": size, "sampleLayer": sample_layer})).ok()?; - match serde_json::from_value::>(v).ok()?[..] { - [r, g, b, a] if a > 0.0 => Some([r, g, b]), - _ => None, - } -} - -/// What the Eyedropper tool (and a painting tool's ⌥-click) picks at document point (x, y): its -/// options bar's Sample Size and Sample (#1649). -pub(crate) fn eyedropper_color(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<[f32; 3]> { - let layers = app.ui.tool_options.eyedropper_sample.clone(); - sample_color(app, x, y, &layers) -} - -/// The active document's composite colour at document point (x, y), averaged over the -/// Eyedropper's Sample Size as Photoshop's dialog eyedroppers (Curves, Color Picker) do. -/// `None` off the image or over transparency. -pub(crate) fn composite_color(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<[f32; 3]> { - sample_color(app, x, y, "all") -} - -/// The body of a `Move` for every tool: tracked position, ⇧ constraint, the moving layer, and so -/// on. It does not feed the live stroke, so the canvas can push a whole frame's recovered samples -/// and update the live stroke once (see `canvas_view`). -fn tool_move(app: &mut PhotocraftApp, x: f64, y: f64, pressure: f32, mods: egui::Modifiers) { - let tool = app.active_tool(); - if tool.is_type() && app.drag.is_none() { - crate::type_tool::pointer_move(app, x, y, mods); - } - if tool == Tool::Pen && mods.alt { - crate::vector_ui::pen_break_handle(app); - } - if tool == Tool::Pen { - crate::vector_ui::pen_move(app, x, y, mods.shift); - } else if tool == Tool::CurvaturePen { - crate::vector_ui::curvature_move(app, x, y); - } - let zoom = app.point_zoom(); - if let Some(d) = app.drag.as_mut().filter(|d| d.reposition) { - d.track(mods); - d.shift_to([x, y]); - } else if let Some(d) = &mut app.drag { - d.track(mods); - // ⇧: straight 0/45/90° strokes, 45° gradient angles (stroke_constraint.rs). - let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); - let [x, y] = crate::stroke_constraint::constrain(d.tool, &mut d.constrain, d.start, last, [x, y], mods.shift, zoom); - // ⇧: a selection-tool drag of the selection locks to multiples of 45° (#6231). The Move - // tool's own drags were already locked by `move_mods::filter_event`. - let [x, y] = crate::move_mods::selection_drag_to(d, [x, y], mods.shift && tool != Tool::Move); - let moved = d.points.last().is_none_or(|p| (p[0] - x).abs() + (p[1] - y).abs() > 0.25); - // A held pen repeats its point now and then, so the stroke's time keeps advancing. - let held = app.stylus.last_point_ms().is_some_and(|t| app.stylus.clock_ms - t >= HOLD_REPEAT_MS) - && app.live_stroke.as_ref().is_some_and(|l| l.stroke.wants_time()); - if moved || held { - d.points.push([x, y, pressure as f64]); - app.stylus.record_point(); - } - } -} - -/// Tool state machine. Shared by mouse input and automation. -pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { - // A press anywhere but on a guide deselects the selected guide (`guide_select`). - if let ToolEvent::Down { x, y, .. } = ev - && app.ui.selected_guide.is_some() - && crate::rulers::guide_at(app, x, y).is_none() - { - crate::guide_select::clear(app); - } - if crate::symmetry_ui::pointer(app, ev, crate::workspace_ui::sticky_mods(app, mods)) { - return; - } - // An Alt+right-drag armed for this press (`paint_mouse`): taken before anything else can - // consume the event, so it never outlives the press it was armed for (#297). - let armed = std::mem::take(&mut app.brush_resize_armed); - crate::transform_tool::end_if_left(app); - let mods = crate::workspace_ui::sticky_mods(app, mods); - if app.ui.transform.is_none() && crate::type_transform::pointer(app, ev, mods) { - return; - } - // Content-Aware Move's Transform On Drop box takes every press until ↩ or Esc. - if crate::cam_transform::pointer(app, ev, mods) { - return; - } - // A Mixer Brush press that loaded paint stays a sample press until it is released, with ⌥ - // let go or not (`mixer_sampling`; `canvas_view` holds back egui's later drag start too). - match ev { - ToolEvent::Down { .. } => app.mixer_sampling = false, - ToolEvent::Up { .. } if app.mixer_sampling => { - app.mixer_sampling = false; - return; - } - _ if app.mixer_sampling => return, - _ => {} - } - // The tool in use, so a held temporary tool (⌘ = Move) with ⌥ doesn't load paint. - if app.active_tool() == Tool::MixerBrush && mods.alt && !mods.ctrl && app.drag.is_none() && !armed && app.brush_resize.is_none() { - if let ToolEvent::Down { x, y, pressure } = ev { - app.mixer_sampling = true; - let pen = app.stylus.sample().unwrap_or_default(); - let p = json!({"points":[[x,y,pressure,pen.tilt_x,pen.tilt_y,pen.rotation]],"target":paint_target(app)}); - if let Err(e) = app.run("brush.mixer.sample", p) { - app.ui.status = e; - app.ui.status_error = true; - } - } - return; - } - // View › Snap / Snap To and smart guides (snap_ui.rs). - let raw = ev; - // The Move tool's marquee selecting layers takes its moves and release unsnapped (move_box.rs). - if crate::move_box::pointer(app, raw) { - return; - } - // A press anywhere but on the floating piece (or with ⇧ / ⌥, to draw) drops it first; the - // Move tool (⌘ with a painting tool too, `event_tool`) drags it from anywhere. - if let ToolEvent::Down { x, y, .. } = raw - && app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some()) - && !crate::move_ui::moves_selected_pixels_with(app, event_tool(app, mods)) - && selection_drag_kind(app, app.ui.tool, [x, y], mods) != Some(true) - { - let _ = app.run("select.drop", json!({})); - } - let ev = crate::snap_ui::filter_event(app, ev, mods); - // Free Transform picks the handle under the press where the user clicked: the snapped press - // can land outside the corner's grab area and turn a corner drag into a move of the whole box. - let transform_ev = if matches!(raw, ToolEvent::Down { .. }) { raw } else { ev }; - if crate::transform_tool::pointer(app, transform_ev, mods) { - return; - } - if crate::distort_ui::pointer(app, ev, mods) { - return; - } - if crate::perspective_crop_ui::pointer(app, ev) { - return; - } - // Window › Modifier Keys: sticky Shift/⌘/⌥ act as held keys. - let mods = crate::workspace_ui::sticky_mods(app, mods); - // ⌘⌥⌃-click with any tool selects the topmost layer with pixels there (quick_pick.rs); it - // must run before the ⌃⌥ brush resize below, which the same keys would trigger. - if crate::quick_pick::pointer(app, ev, mods) { - return; - } - // Control+Alt-drag or Alt+right-drag with a painting tool resizes the brush instead of - // painting (#231, #297). - if crate::brush_resize::pointer(app, ev, mods, armed) { - return; - } - // ⌥ (Alt) with a painting tool is the Eyedropper for that press. - if alt_eyedropper(app, ev, mods) { - return; - } - // Move tool: ⇧ locks the axis, ⌥ duplicates (move_mods.rs). - let ev = crate::move_mods::filter_event(app, ev, mods); - // A live shape's corner radius widgets (Path Selection, the shape tools, Move with its - // transform controls). Unsnapped, as Free Transform's handles: snapping would pull the press - // off a widget onto a nearby vertex or guide, and the shape tool would draw a new shape. - if crate::corner_radius::pointer(app, raw, mods) { - return; - } - // Direct Selection, and the Pen's ⌘ (Direct Selection) and ⌥ (Convert Point) modes (#790). - if crate::direct_select::pointer(app, ev, mods) { - return; - } - // Add / Delete Anchor Point tools (#1044). - if crate::anchor_tools::pointer(app, ev, mods) { - return; - } - // Ruler, Count and Note tools. - if crate::analysis_ui::pointer(app, ev, mods) { - return; - } - // Slice and Slice Select tools. - if crate::slice_ui::pointer(app, ev, mods) { - return; - } - // Frame tool: draw rectangular and elliptical frames. - if crate::frame_tool::pointer(app, ev, mods) { - return; - } - // Artboard tool: draw, select, move and resize boards. - if crate::artboard_tool::pointer(app, ev, mods) { - return; - } - // Crop tool: draw, move and resize the frame. - if crate::crop_ui::pointer(app, ev, mods) { - return; - } - // Gradient tool, live mode: draw and edit Gradient Fill layers. - if crate::gradient_ui::pointer(app, ev, mods) { - return; - } - // ⌘ over a guide takes the guide (#2690, #6288); the guide drag below moves it. - if let ToolEvent::Down { x, y, .. } = raw - && let Some((vertical, i)) = command_guide_at(app, app.active_tool(), [x, y], mods) - { - app.guide_drag = Some(crate::rulers::GuideDrag::existing(vertical, i, [x, y])); - crate::snap_ui::begin_guide(app, [x, y]); - return; - } - if crate::lasso_ui::pointer(app, ev, mods) { - return; - } - // Magnetic Lasso: fastening points and the border following the pointer. - if crate::magnetic_lasso_ui::pointer(app, ev, mods) { - return; - } - let tool = event_tool(app, mods); - if tool == Tool::Eyedropper { - match ev { - ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } => { - sample_eyedropper(app, x, y, mods); - return; - } - ToolEvent::Up { .. } => return, - } - } - // A locked layer (the Background without a selection, say): no drag, and Photoshop's message - // once the pointer moves (a click says nothing). ⌘ with a selection tool here (#896); the Move - // tool below, once Auto-Select has picked the layer. - match ev { - ToolEvent::Down { x, y, .. } if tool != Tool::Move && app.ui.transform.is_none() && crate::move_lock::blocked(app, tool, [x, y], mods) => { - app.move_blocked = true; - return; - } - ToolEvent::Move { .. } if app.move_blocked => { - app.move_blocked = false; - crate::move_lock::prompt(app); - return; - } - ToolEvent::Up { .. } if app.move_blocked => { - app.move_blocked = false; - return; - } - _ => {} - } - // Move tool over a guide drags the guide (off the canvas deletes it). - match ev { - ToolEvent::Down { x, y, pressure } if tool == Tool::Move => { - if let Some((vertical, i)) = crate::rulers::guide_at(app, x, y) { - // ⌥-click turns the guide, through the point clicked, as in Photoshop. - if mods.alt && !mods.shift && !mods.command { - crate::guide_select::flip(app, vertical, i, [x, y]); - return; - } - app.guide_drag = Some(crate::rulers::GuideDrag::existing(vertical, i, [x, y])); - return; - } - // Auto-Select (or ⌘-click while it is off) picks the layer under the pointer first - // (not when the selected pixels move: those are the active layer's). - if !crate::move_ui::moves_selected_pixels_with(app, tool) && app.ui.tool_options.move_auto_select != mods.command { - let target = app.ui.tool_options.move_target.clone(); - let mode = if mods.shift { "add" } else { "replace" }; - let before = app.session.active().map(|st| st.selected_layers()); - // A locked layer under the pointer (the Background) can't move. Photoshop draws - // the layer marquee instead of reporting the lock (#4058). Probe without - // selecting so a locked hit doesn't become the selection first. - let probe = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "select": false})); - let locked_hit = probe.as_ref().ok().and_then(|v| v["layer"].as_u64()).is_some_and(|id| { - app.session.active().is_some_and(|st| { - let id = photocraft_doc::LayerId(id); - let locks = st.doc.effective_locks(id); - locks.position || locks.all || st.doc.is_background(id) - }) - }); - if locked_hit || (probe.as_ref().is_ok_and(|v| v["layer"].is_null()) && crate::move_box::empty_at(app, [x, y])) { - if locked_hit { - // A click still selects the locked layer, as in Photoshop; a drag's - // marquee then replaces that selection on release. - let _ = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "mode": mode})); - } - crate::move_box::begin(app, [x, y], mods.shift); - return; - } - let picked = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "mode": mode})); - // No pixels there at all (an empty spot, or off the canvas): drag a marquee that - // selects the layers it touches instead (move_box.rs). - if picked.is_ok_and(|v| v["layer"].is_null()) && crate::move_box::empty_at(app, [x, y]) { - crate::move_box::begin(app, [x, y], mods.shift); - return; - } - // Snapping (and the drag's box) started before the pick: point it at what moves. - if app.session.active().map(|st| st.selected_layers()) != before { - crate::snap_ui::retarget_move(app, [x, y], mods); - } - } - // A locked layer: no drag, and Photoshop's message once the pointer moves (`move_lock`). - if crate::move_lock::blocked(app, tool, [x, y], mods) { - app.move_blocked = true; - return; - } - // With a selection: cut the selected pixels (⌥ copies them) and drag them as a floating - // piece, from anywhere, as a marquee ⌘-drag does. - if crate::move_ui::moves_selected_pixels_with(app, tool) { - if crate::move_ui::float_selected(app, mods.alt, 0.0, 0.0) { - let mut d = Drag::new(tool, [x, y], vec![[x, y, pressure as f64]], mods, false); - d.sel_move = Some(true); - app.drag = Some(d); - } - return; - } - } - ToolEvent::Move { x, y, .. } => { - if let Some(d) = app.guide_drag.as_mut().filter(|d| d.index.is_some()) { - d.pos = if d.vertical { x } else { y }; - return; - } - } - ToolEvent::Up { x, y } => { - if let Some(mut d) = app.guide_drag.filter(|d| d.index.is_some()) { - app.guide_drag = None; - d.pos = if d.vertical { x } else { y }; - crate::rulers::finish_drag(app, d); - return; - } - } - _ => {} - } - match ev { - ToolEvent::Down { x, y, pressure } => { - // Painting a type, shape, Smart Object or fill layer asks to rasterize it first - // (⌥-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; - return; - } - if !sets_source && crate::rasterize_prompt::intercept(app, tool, x, y, pressure) { - return; - } - // ⌘ with a selection tool is the Move tool for the drag: outside the selection (or - // without one) it moves the whole layer, ⌘⌥ a duplicate of it. It never combines - // selections. - if command_moves_layer(app, tool, [x, y], mods) { - if mods.alt - && let Err(e) = app.run("layer.duplicate", json!({"inPlace": true})) - { - app.ui.status = e; - app.ui.status_error = true; - return; - } - app.drag = Some(Drag::new(Tool::Move, [x, y], vec![[x, y, pressure as f64]], mods, false)); - return; - } - // Marquee / lasso inside the selection: drag the outline, or ⌘-drag to cut the selected - // pixels into a floating piece (`select.float`) and drag that. - if let Some(cut) = selection_drag_kind(app, tool, [x, y], mods) { - // ⌘⌥ on a floating piece leaves it where it is and drags a copy of it. - if cut - && mods.alt - && mods.command - && app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some()) - && let Err(e) = app.run("select.drop", json!({})) - { - app.ui.status = e; - app.ui.status_error = true; - return; - } - if cut - && app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_none()) - && let Err(e) = app.run("select.float", json!({"dx": 0, "dy": 0, "copy": mods.alt})) - { - app.ui.status = e; - app.ui.status_error = true; - return; - } - crate::snap_ui::follow_cut(app); - let mut d = Drag::new(tool, [x, y], vec![[x, y, pressure as f64]], mods, false); - d.sel_move = Some(cut); - app.drag = Some(d); - return; - } - match tool { - Tool::PathSelection => { - let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); - if let Some(st) = app.session.active() - && let Some(id) = crate::vector_ui::pick_shape_at(&st.doc, [x, y], tol) - { - let _ = app.run("layer.select", json!({"layer": id.0})); - } - } - Tool::Pen => { - if !(mods.alt && crate::vector_ui::pen_grab_handle(app, x, y)) { - crate::vector_ui::pen_down(app, x, y, mods.shift); - } - return; - } - Tool::CurvaturePen => { - crate::vector_ui::curvature_down(app, x, y); - return; - } - Tool::CloneStamp | Tool::Healing if mods.alt => { - crate::retouch_ui::set_source(app, x, y); - return; - } - Tool::MagicWand => { - let o = app.ui.tool_options.clone(); - let mode = selection_mode(app, mods); - let _ = app.run("select.magicWand", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "sampleAllLayers": o.sample_all.magic_wand, "mode": mode})); - return; - } - Tool::MagicEraser => { - crate::eraser_ui::click(app, tool, x, y); - return; - } - Tool::PaintBucket => { - let o = app.ui.tool_options.clone(); - let contents = if o.bucket_fill_pattern { "pattern" } else { "foreground" }; - let mode = if o.bucket_clear { "clear" } else { o.bucket_blend_mode.label() }; - let _ = app.run("paint.bucket", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "sampleAllLayers": o.sample_all.paint_bucket, "opacity": o.fill_opacity, "contents": contents, "mode": mode, "target": paint_target(app)})); - return; - } - Tool::RedEye => { - let o = app.ui.tool_options.clone(); - let _ = app.run( - "paint.redEye", - json!({ - "x": x.floor(), - "y": y.floor(), - "pupilSize": o.red_eye_pupil_size.clamp(1.0, 100.0), - "darken": o.red_eye_darken.clamp(0.0, 100.0), - "target": paint_target(app), - }), - ); - return; - } - Tool::PolygonLasso => { - polygon_click(app, x, y, mods); - return; - } - // The Type tools pick the box handle or glyph under the press where the user - // clicked: the snapped press can land off an edge handle's grab area (#6819). - Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask - if { - let [px, py] = if let ToolEvent::Down { x, y, .. } = raw { [x, y] } else { [x, y] }; - crate::type_tool::pointer_down(app, px, py, mods) - } => - { - return; - } - _ => {} - } - crate::paint_mouse::sync_tool_brush(app); - // 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; - // A 1 px pencil line depends on the pixels, not where inside the pixel the click - // landed (#4071). Snap both ends of the stroke to the aliased tip's grid. - let (x, y) = snap_aliased_tip(app, tool, x, y); - // ⇧-click connects to the last endpoint, including its pen pressure (#2827), so - // the renderer interpolates size and opacity across the segment. - let active = app.session.active().map(|st| st.doc.id); - let from = app.last_stroke_end.filter(|(doc, _)| mods.shift && crate::stroke_constraint::connects(tool) && Some(*doc) == active).map(|(_, p)| { - let (sx, sy) = snap_aliased_tip(app, tool, p[0], p[1]); - [sx, sy, p[2]] - }); - let mut points = vec![[x, y, pressure as f64]]; - if let Some(p) = from { - points.insert(0, p); - } - // ⌥ flips Dodge/Burn and Blur/Sharpen for this stroke. - let tool = crate::retouch_ui::alt_flipped(tool, mods.alt); - app.drag = Some(Drag { clear, ..Drag::new(tool, from.map_or([x, y], |p| [p[0], p[1]]), points, mods, erase) }); - app.trail = None; - app.stylus.begin_stroke(); - if from.is_some() { - app.stylus.record_point(); - } - app.live_stroke = if strokes_live(tool) { begin_live_stroke(app) } else { None }; - if tool == Tool::MixerBrush && app.live_stroke.is_none() { - use photocraft_engine::brush_cmds::mixer_live::LiveMixer; - let p = app.drag.as_ref().map(|d| stroke_params(app, d, &app.stylus.stroke_points(&d.points))); - // A tip above the preview size keeps the drag: `finish_gesture` renders it on release. - // Otherwise the first dab itself is invalid. Do not queue an unexpected release edit. - if let Some(p) = p - && !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; - } - app.drag = None; - } - } else if tool == Tool::MixerBrush { - feed_live_stroke(app); - } - } - ToolEvent::Move { x, y, pressure } => { - // Polygonal Lasso: ⌥ held while the button is down draws freehand into the polygon; - // releasing ⌥ goes back to straight segments (the polygon stays open). - if tool == Tool::PolygonLasso && mods.alt && app.drag.is_none() && !app.ui.polygon.is_empty() { - if app.ui.polygon.last().is_none_or(|l| (l[0] - x).hypot(l[1] - y) >= 1.0) { - app.ui.polygon.push([x, y]); - } - return; - } - tool_move(app, x, y, pressure, mods); - feed_live_stroke(app); - } - ToolEvent::Up { x, y } => { - if tool.is_type() - && let Some(e) = app.ui.text_edit.as_mut() - { - e.dragging = false; - e.resize = None; - app.ui.caret_blink_time = app.last_frame_time; - } - if tool == Tool::Pen { - crate::vector_ui::pen_up(app); - } else if tool == Tool::CurvaturePen { - crate::vector_ui::curvature_up(app); - } - let zoom = app.point_zoom(); - let Some(mut d) = app.drag.take() else { return }; - d.track(mods); - if d.reposition { - d.shift_to([x, y]); - } - let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); - let [x, y] = crate::stroke_constraint::constrain(d.tool, &mut d.constrain, d.start, last, [x, y], mods.shift, zoom); - let [x, y] = crate::move_mods::selection_drag_to(&mut d, [x, y], mods.shift && app.active_tool() != Tool::Move); - // A Move-tool click (released where it was pressed) selects, it never moves: snapping - // the release point would otherwise nudge the layer onto a nearby edge. - if d.tool == Tool::Move && d.points.len() < 2 && matches!(raw, ToolEvent::Up { x, y } if [x, y] == d.start) { - app.move_preview = None; - crate::move_mods::finish(app); - if d.sel_move.is_some() { - finish_selection_drag(app, true, d.start, d.start); - } - return; - } - if d.points.last().is_none_or(|p| p[0] != x || p[1] != y) { - d.points.push([x, y, d.points.last().map_or(1.0, |p| p[2])]); - app.stylus.record_point(); - } - finish_gesture(app, d); - crate::move_mods::finish(app); - } - } -} - -/// Why a press with `tool` must not start: it would paint on or move a hidden target layer (the -/// engine refuses the command; refusing the press keeps the live stroke from drawing first). -fn hidden_target(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { - let cmd = match tool { - Tool::Move => "layer.translate", - // The live Gradient makes a new Gradient Fill layer above the target, which Photoshop - // allows over a hidden layer; only the classic one paints the target itself. - Tool::Gradient if !app.ui.tool_options.gradient_classic => return None, - // Every painting command follows the same target (layer, mask or channel) as a stroke. - t if t.is_brushlike() || matches!(t, Tool::Gradient | Tool::PaintBucket | Tool::MagicEraser) => "paint.stroke", - _ => return None, - }; - photocraft_engine::hidden_target::refusal(&app.session, cmd, &json!({})) -} - -/// 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)) -} - -/// Does selection surface `sel` cover document point `p`? -fn covers(sel: &photocraft_raster::Surface, p: [f64; 2]) -> bool { - let mut v = [0.0f32]; - sel.read_pixel(p[0].floor() as i32, p[1].floor() as i32, &mut v); - v[0] > 0.0 -} - -/// Does a press with `tool` at `p` drag the selection rather than draw a new one? `Some(true)` -/// moves the floating piece (⌘ cuts one first, ⌘⌥ copies; a floating piece moves with a plain -/// drag; the Polygonal Lasso and Magic Wand need ⌘, as a plain press there places or samples), -/// `Some(false)` just the outline (no ⇧ / ⌥ and the options bar on New Selection, so a combining -/// drag still draws). -pub fn selection_drag_kind(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> Option { - // Click-driven selection tools (a press places a point or samples): only ⌘ drags the - // selection, and not while a polygon is being drawn. - let clicky = matches!(tool, Tool::PolygonLasso | Tool::MagicWand); - if !(clicky || matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso)) || (clicky && !app.ui.polygon.is_empty()) { - return None; - } - // ⌘ cuts, ⌘⌥ copies (`select.float`'s `copy`). - let cut = mods.command && !mods.shift; - if let Some(f) = app.session.active().and_then(photocraft_engine::float_cmds::floating) { - // A press on the piece's outline (where its ants are) drags it; one in the margin the cut - // left of the selection starts a new selection (#7538). - let at = [p[0] - f64::from(f.offset.0), p[1] - f64::from(f.offset.1)]; - let on = f.parts.outline().map_or_else(|| inside_selection(app, at), |o| covers(o, at)); - return (on && !mods.shift && (!mods.alt || mods.command) && (cut || !clicky)).then_some(true); - } - if !inside_selection(app, p) { - return None; - } - if cut { - return Some(true); - } - (!clicky && !mods.command && selection_mode(app, mods) == "replace").then_some(false) -} - -/// The tool a pointer event with `mods` goes to: ⌘ held is the Move tool (`hold_keys::cmd_moves`). -/// The canvas resolves the held key before the event (`tool_override`); automation and tests send -/// the modifier with the event. -pub(crate) fn event_tool(app: &PhotocraftApp, mods: egui::Modifiers) -> Tool { - match app.active_tool() { - t if app.tool_override.is_none() && mods.command && crate::hold_keys::cmd_moves(t) && app.ui.transform.is_none() && app.ui.text_edit.is_none() => { - Tool::Move - } - t => t, - } -} - -/// Does a ⌘ (⌘⌥) press with selection tool `tool` at `p` move the whole layer (a duplicate with -/// ⌥), as the Move tool would? Outside the selection or without one; inside it, ⌘ drags the -/// selected pixels instead (`selection_drag_kind`). -pub(crate) fn command_moves_layer(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> bool { - let selection_tool = matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso | Tool::PolygonLasso | Tool::MagicWand); - let floating = app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some()); - selection_tool && mods.command && !mods.shift && !floating && app.ui.polygon.is_empty() && !inside_selection(app, p) -} - -/// The guide a ⌘ press with `tool` at `p` drags (vertical?, index), as the Move tool's press -/// would (#2690): ⌘ is the Move tool, and a guide under the pointer comes before the layer or the -/// selected pixels. The selection tools, and every tool on which ⌘ is the Move tool -/// (`hold_keys::cmd_moves`, #6288); the canvas shows the guide cursor where this finds a guide. -/// Not while a polygon or lasso outline, a stroke, Free Transform or type editing is under way. -pub(crate) fn command_guide_at(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> Option<(bool, usize)> { - let selection_tool = matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso | Tool::PolygonLasso | Tool::MagicWand); - let moves = selection_tool || crate::hold_keys::cmd_moves(tool); - let idle = app.ui.polygon.is_empty() && !crate::lasso_ui::active(app) && app.ui.transform.is_none() && app.ui.text_edit.is_none() && app.drag.is_none(); - (moves && mods.command && idle).then(|| crate::rulers::guide_at(app, p[0], p[1])).flatten() -} - -/// Photoshop's cursor over a selection: what a press (or the drag under way) would do. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum SelCursor { - /// A marquee or lasso inside the selection moves the outline (the move cursor, #1428), also - /// while it is being dragged. - Outline, - /// Arrow with scissors: the Move tool (⌘ with a marquee) cuts and moves the selected pixels. - Cut, - /// Arrow with a second arrow: ⌥ lifts a copy of them instead. - Copy, - /// Plain arrow: a floating piece, moved again by a plain drag until it is dropped. - Piece, - /// Hollow arrowhead: the selected pixels are being dragged. - Dragging, -} - -/// The cursor at document point `p` with `tool` in effect and `mods` held (`None`: not over a -/// selection the press would move). The Move tool moves the selected pixels from anywhere -/// (`move_ui::moves_selected_pixels_with`); a selection tool from inside the selection, or on the -/// floating piece (`selection_drag_kind`). -pub fn selection_cursor(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> Option { - if let Some(d) = &app.drag { - return match d.sel_move { - Some(true) => Some(SelCursor::Dragging), - Some(false) => Some(SelCursor::Outline), - None => None, - }; - } - let floating = app.session.active().and_then(photocraft_engine::float_cmds::floating).is_some(); - let pixels = if tool == Tool::Move { - crate::move_ui::moves_selected_pixels_with(app, tool) - } else { - match selection_drag_kind(app, tool, p, mods)? { - false => return Some(SelCursor::Outline), - true => true, - } - }; - if !pixels { - return None; - } - // ⌥ (⌘⌥ with a selection tool) floats a copy, of the layer's pixels or of the piece. - let copy = mods.alt && (tool == Tool::Move || mods.command); - Some(match (floating, copy) { - (_, true) => SelCursor::Copy, - (true, false) => SelCursor::Piece, - (false, false) => SelCursor::Cut, - }) -} - -/// Whole-pixel offset of a selection drag in progress (`Drag::sel_move`). -pub(crate) fn selection_drag_delta(app: &PhotocraftApp) -> Option<(i32, i32)> { - let d = app.drag.as_ref().filter(|d| d.sel_move.is_some())?; - let end = d.points.last().map_or(d.start, |p| [p[0], p[1]]); - Some(((end[0] - d.start[0]).round().clamp(-1e7, 1e7) as i32, (end[1] - d.start[1]).round().clamp(-1e7, 1e7) as i32)) -} - -/// The selection a floating piece on document `idx` shows its ants for, before its offset: the -/// moved pixels' outline, as in Photoshop (#7538); `None` outlines the document's selection. The -/// surface's tiles are shared, so the clone is cheap. -pub(crate) fn floating_outline(app: &PhotocraftApp, idx: usize) -> Option { - if app.session.active_index() != Some(idx) { - return None; - } - photocraft_engine::float_cmds::floating(app.session.active()?)?.parts.outline().cloned() -} - -/// Where the selection is drawn relative to where it is: a floating piece's offset plus a drag -/// in progress. -fn selection_shown_offset(app: &PhotocraftApp) -> Option<(i32, i32)> { - crate::move_ui::floating_offset(app).or_else(|| selection_drag_delta(app)).or_else(|| carried_selection_delta(app)) -} - -/// Whole-pixel offset of a Move drag of several layers, which carries the selection along -/// (`move_ui::carries_selection`): their ants follow the layers while they move (#7538). -fn carried_selection_delta(app: &PhotocraftApp) -> Option<(i32, i32)> { - let d = app.drag.as_ref().filter(|d| d.tool == Tool::Move && d.sel_move.is_none())?; - if !crate::move_ui::carries_selection(app) { - return None; - } - let end = d.points.last().map_or(d.start, |p| [p[0], p[1]]); - Some(((end[0] - d.start[0]).round().clamp(-1e7, 1e7) as i32, (end[1] - d.start[1]).round().clamp(-1e7, 1e7) as i32)) -} - -/// End of a selection drag: move the outline, or the floating piece. A click without moving -/// deselects, like a marquee click (a click on a floating piece leaves it floating, unless it never -/// moved: then it is put back, so Undo isn't spent on it). -fn finish_selection_drag(app: &mut PhotocraftApp, floating: bool, start: [f64; 2], end: [f64; 2]) { - let (dx, dy) = ((end[0] - start[0]).round(), (end[1] - start[1]).round()); - let unmoved = app.session.active().and_then(photocraft_engine::float_cmds::floating).is_some_and(|f| f.offset == (0, 0)); - let r = match (floating, dx == 0.0 && dy == 0.0) { - (true, true) if unmoved => app.run("select.drop", json!({})), - (true, true) => return, - (false, true) if app.session.is_enabled("select.deselect") => app.run("select.deselect", json!({})), - (false, true) => return, - (true, false) => app.run("select.float", json!({"dx": dx, "dy": dy})), - (false, false) => app.run("select.transformSelection", json!({"dx": dx, "dy": dy})), - }; - if let Err(e) = r { - app.ui.status = e; - app.ui.status_error = true; - } -} - -/// Commit a Brush, Pencil or Eraser drag. The live stroke already rendered it: its pixels are -/// offered to the commit (`Session::offer_live_stroke`), so release costs no second render, and -/// the canvas then refreshes only what it hadn't shown yet (`CommittedStroke`). -fn commit_brush_stroke(app: &mut PhotocraftApp, d: &Drag) { - let live = app.live_stroke.take(); - let mut p = stroke_params(app, d, &app.stylus.stroke_points(&d.points)); - if let Some(seed) = live.as_ref().and_then(|l| l.stroke.seed()) { - p["seed"] = json!(seed); - } - let Some(mut l) = live else { - let _ = app.run(stroke_command(app, d.tool), p); - return; - }; - // Points the live stroke hasn't rendered yet (the release frame's last moves). - let t0 = app.stylus.point_ms(0); - let rest: Vec<_> = (l.fed..d.points.len()) - .filter_map(|i| { - let q = d.points.get(i)?; - let t = app.stylus.stroke.get(i).or(app.stylus.stroke.last()).copied().unwrap_or_default(); - let mut sp = photocraft_engine::paint::StrokePoint::new(q[0], q[1], q[2] as f32); - (sp.tilt_x, sp.tilt_y, sp.rotation) = (t[0], t[1], t[2]); - sp.time = app.stylus.point_ms(i) - t0; - Some(sp) - }) - .collect(); - if !rest.is_empty() { - match l.stroke.push(&rest) { - Ok(r) => l.damage.push(r), - // The live stroke can't show these points: the commit renders the stroke itself. - Err(_) => { - let _ = app.run(stroke_command(app, d.tool), p); - return; - } - } - } - let LiveStroke { stroke, doc, key, damage, .. } = l; - let before = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| st.doc.clone()); - if let EngineStroke::Brush(stroke) = stroke - && app.session.offer_live_stroke(*stroke).is_err() - { - app.session.clear_live_stroke(); - } - let started = crate::gpu_canvas::now_ms(); - let result = app.run(stroke_command(app, d.tool), p); - app.stroke_trace.stroke(crate::gpu_canvas::now_ms() - started); - app.session.clear_live_stroke(); - let Ok(r) = result else { return }; - let after = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| (st.revision, st.doc.clone())); - if r.get("fromLive").and_then(serde_json::Value::as_bool) == Some(true) - && let Some((revision, after)) = after - { - let relayout = before.map_or(DRect::EMPTY, |b| photocraft_compose::relayout_damage(&b, &after)); - app.committed_stroke = Some(CommittedStroke { doc, revision, key, damage, relayout }); - } else { - // Rendered again from scratch: the commit's damage rect refreshes the stroke. - let shown = CommittedStroke { doc, revision: 0, key, damage, relayout: DRect::EMPTY }; - // Raw preview key 0 = the document itself (its colour display folded in). - shown_as_document(app, doc, |k| shown.since(k).is_some()); - } -} - -/// Pencil (and a Pencil-mode Eraser) dabs sit on the pixel grid. Clicks anywhere inside one -/// pixel must produce the same point, or a ⇧-click line changes with the sub-pixel position. -fn snap_aliased_tip(app: &PhotocraftApp, tool: Tool, x: f64, y: f64) -> (f64, f64) { - let pencil = tool == Tool::Pencil || crate::eraser_ui::pencil_mode(app, tool); - if !pencil { - return (x, y); - } - let (cx, cy) = photocraft_engine::paint::grid_center(x, y, app.session.tools.brush.size); - (f64::from(cx), f64::from(cy)) -} - -pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) { - // Control can select a different tool and release before the next frame cancels the drag. - // Cancel before even recording a Shift-stroke anchor, including the preview fallback paths. - if d.tool == Tool::MixerBrush && app.ui.tool != Tool::MixerBrush { - app.live_stroke = None; - return; - } - let mut end = d.points.last().copied().unwrap_or([d.start[0], d.start[1], 1.0]); - let (sx, sy) = snap_aliased_tip(app, d.tool, end[0], end[1]); - end[0] = sx; - end[1] = sy; - if let Some(floating) = d.sel_move { - finish_selection_drag(app, floating, d.start, [end[0], end[1]]); - return; - } - // Where the next ⇧-click line starts. - if crate::stroke_constraint::connects(d.tool) - && let Some(st) = app.session.active() - { - app.last_stroke_end = Some((st.doc.id, end)); - } - if d.tool == Tool::MixerBrush { - // The release can carry a new endpoint, including moves deferred in this frame. - // Feed those samples before offering the already-rendered document for commit. - app.drag = Some(d); - let deferred = std::mem::replace(&mut app.defer_live_stroke, false); - feed_live_stroke(app); - app.defer_live_stroke = deferred; - let Some(d) = app.drag.take() else { return }; - let live = app.live_stroke.take(); - if let Some(l) = live { - let (doc, key, steps) = (l.doc, l.key, l.damage.len() as u64); - if let EngineStroke::Mixer(mixer) = l.stroke { - if l.preview_failed { - let mut p = stroke_params(app, &d, &app.stylus.stroke_points(&d.points)); - p["seed"] = json!(mixer.seed); - drop(mixer); - let _ = app.run("paint.mixerBrush", p); - return; - } - match mixer.prepare_commit(&mut app.session) { - Ok(p) => { - if app.run("paint.mixerBrush", p).is_ok() { - shown_as_document(app, doc, |k| k == 0 || (key..=key + steps).contains(&k)); - } - } - Err(e) => { - app.ui.status = e.to_string(); - app.ui.status_error = true; - } - } - } - } else { - // No preview (a tip above its size): render the whole stroke now. - let p = stroke_params(app, &d, &app.stylus.stroke_points(&d.points)); - let _ = app.run("paint.mixerBrush", p); - } - return; - } - // A live retouching preview ends here; the commit below replaces it (the Clone Stamp's, - // History Brush's and sequential-dab tools' with the pixels it already drew). - offer_live_retouch(app, &d); - if live_retouch_command(d.tool).is_some() || crate::retouch_ui::dab_params(app, d.tool).is_some() || d.tool == Tool::ColorReplacement { - app.live_stroke = None; - } - let finished = crate::eraser_ui::finish_stroke(app, d.tool, &d.points) || crate::retouch_ui::finish_stroke(app, d.tool, &d.points, d.modifiers); - app.session.clear_live_stroke(); - if finished { - return; - } - match d.tool { - Tool::ObjectSelection => crate::retouch_ui::finish_object_selection(app, d.start, [end[0], end[1]], d.modifiers), - Tool::FreeformPen => crate::vector_ui::freeform_finish(app, &d.points, d.lasso.as_ref().map_or(&[], |l| l.straight())), - // Photoshop: a click without dragging opens Create Rectangle / Ellipse / … instead. - t if crate::vector_ui::is_shape_tool(t) - && crate::shape_dialog::is_click(d.start, &d.points, app.point_zoom()) - && crate::shape_dialog::open(app, t, d.start).is_some() => {} - t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::finish_shape(app, t, d.start, [end[0], end[1]], d.live), - Tool::PathSelection => crate::vector_ui::path_selection_finish(app, d.start, [end[0], end[1]]), - Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::pointer_up(app, d.start, [end[0], end[1]]), - Tool::Brush | Tool::Pencil | Tool::Eraser => commit_brush_stroke(app, &d), - Tool::RectMarquee | Tool::EllipseMarquee => { - // Exactly what the drag showed (`marquee_preview_px`); a click deselects. - let Some([x0, y0, x1, y1]) = marquee_preview_px(&app.ui.tool_options, &d, app.point_zoom()) else { - if app.session.is_enabled("select.deselect") { - let _ = app.run("select.deselect", json!({})); - } - return; - }; - let mode = selection_mode(app, d.modifiers); - let (aa, feather) = (app.ui.tool_options.anti_alias, app.ui.tool_options.feather); - let _ = app.run("select.rect", json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0, "mode": mode, "ellipse": d.tool == Tool::EllipseMarquee, "antiAlias": aa, "feather": feather})); - } - // A click (or the end of a drag) selects the line under the pointer, never deselects. - Tool::SingleRowMarquee | Tool::SingleColumnMarquee => { - let Some([x0, y0, x1, y1]) = single_line_drag_px(app, &d) else { return }; - let mode = selection_mode(app, d.modifiers); - let feather = app.ui.tool_options.feather; - // `line` names the History step after the tool (Single Row / Single Column Marquee). - let line = if d.tool == Tool::SingleRowMarquee { "row" } else { "column" }; - let _ = app.run( - "select.rect", - 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::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(); - 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})); - // 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); - } - } else if app.session.is_enabled("select.deselect") { - let _ = app.run("select.deselect", json!({})); - } - } - Tool::Gradient if (end[0] - d.start[0]).abs() + (end[1] - d.start[1]).abs() >= 2.0 => { - let o = app.ui.tool_options.clone(); - let _ = app.run( - "paint.gradient", - json!({"from": [d.start[0], d.start[1]], "to": [end[0], end[1]], "style": o.gradient_style, "reverse": o.gradient_reverse, "dither": o.gradient_dither, "opacity": o.fill_opacity, "mode": o.gradient_blend_mode.label(), "target": paint_target(app)}), - ); - } - Tool::Move => { - let (dx, dy) = ((end[0] - d.start[0]).round(), (end[1] - d.start[1]).round()); - crate::move_ui::finish(app, dx, dy); - } - _ => {} - } -} - -/// Extra OS windows showing documents (multi-window / multi-monitor). -pub fn extra_windows(app: &mut PhotocraftApp, ctx: &egui::Context) { - let wins = app.ui.windows.clone(); - for w in wins.into_iter().filter(|w| w.open) { - let Some(st) = app.session.documents().get(w.document) else { continue }; - let title = format!("{} — window {}", st.doc.name, w.id); - let vid = egui::ViewportId::from_hash_of(("docwin", w.id)); - let mut builder = egui::ViewportBuilder::default().with_title(title).with_inner_size([800.0, 600.0]); - if let Some([x, y]) = w.position { - builder = builder.with_position([x, y]); - } - let mut view = w.view.clone(); - let mut close = false; - ctx.show_viewport_immediate(vid, builder, |ui, class| { - if ui.ctx().input(|i| i.viewport().close_requested()) { - close = true; - } - 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(); - view = canvas_view(app, ui, w.document, rect, view.clone(), false); - // 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); - }); - }); - if let Some(win) = app.ui.windows.iter_mut().find(|x| x.id == w.id) { - win.view = view; - if close { - win.open = false; - } - } - } - app.ui.windows.retain(|w| w.open); -} - -/// Selection mode from the options bar, overridden by modifier keys (⇧ add, ⌥ subtract, ⇧⌥ intersect). -/// The cursor badge announces the same mode (`tool_feedback`). -pub(crate) fn selection_mode(app: &PhotocraftApp, m: egui::Modifiers) -> &'static str { - crate::tool_feedback::document_selection_mode(app, Tool::Lasso, m) -} - -/// Shift constrains a Polygonal Lasso segment to Photoshop's 45° directions. -/// Work in document coordinates so zoom, view rotation and mirroring cannot skew it. -pub(crate) fn constrained_polygon_point(from: [f64; 2], point: [f64; 2]) -> [f64; 2] { - let dx = point[0] - from[0]; - let dy = point[1] - from[1]; - if !dx.is_finite() || !dy.is_finite() { - return point; - } - let length = dx.hypot(dy); - if length == 0.0 { - return point; - } - let angle = (dy.atan2(dx) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4; - [from[0] + length * angle.cos(), from[1] + length * angle.sin()] -} - -/// A polygonal lasso click adds a vertex; clicking near the first vertex closes the polygon. The -/// first click fixes the selection mode; a new-selection polygon hides the old outline while it is -/// drawn, and replaces it in one history step when it closes. -fn polygon_click(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { - let close = app - .ui - .polygon - .first() - .is_some_and(|p0| app.ui.polygon.len() >= 3 && ((p0[0] - x).powi(2) + (p0[1] - y).powi(2)).sqrt() < 8.0 / app.point_zoom().max(0.01) as f64); - if close { - commit_polygon(app); - return; - } - if app.ui.polygon.is_empty() { - app.ui.polygon_doc = app.session.active().map(|st| st.doc.id); - // ⌥ with nothing selected draws freehand; there is nothing to subtract from. - let nothing_selected = app.session.active().is_none_or(|st| st.doc.selection.is_none()); - let intent = if nothing_selected { egui::Modifiers { alt: false, ..mods } } else { mods }; - app.ui.polygon_mode = selection_mode(app, intent).into(); - } - // Only constrain segments after the first vertex; the first click still sets selection intent. - // Alt-drag is freehand and must not snap to an angle. - let point = if mods.shift && !mods.alt { app.ui.polygon.last().copied().map_or([x, y], |last| constrained_polygon_point(last, [x, y])) } else { [x, y] }; - app.ui.polygon.push(point); -} - -/// Remove the Polygonal Lasso's last vertex (⌫, Delete or a right-click while drawing, #1229); -/// removing the only one cancels the polygon. False when no polygon is being drawn. -pub fn polygon_retract(app: &mut PhotocraftApp) -> bool { - if app.ui.polygon.pop().is_none() { - return false; - } - if app.ui.polygon.is_empty() { - app.ui.polygon_mode.clear(); - } - true -} - -/// The polygon in progress belongs to the document it was started on (`UiState::polygon_doc`): -/// once another document becomes active it is dropped, so its outline doesn't show on (or get -/// committed to) the other document, and the selection it would have replaced is shown again. -/// Switching tools is handled in `PhotocraftApp::sync_views`. Like the Lasso's -/// ([`crate::lasso_ui::cancel_stale`]) and the Magnetic Lasso's ([`crate::magnetic_lasso_ui::frame`]). -pub fn polygon_cancel_stale(app: &mut PhotocraftApp) { - let active = app.session.active().map(|st| st.doc.id); - if app.ui.polygon.is_empty() { - app.ui.polygon_doc = None; - } else if app.ui.polygon_doc.is_some_and(|d| Some(d) != active) { - app.ui.polygon.clear(); - app.ui.polygon_mode.clear(); - app.ui.polygon_doc = None; - } -} - -/// A new-selection polygonal (or magnetic) lasso is being drawn, so the selection it will replace -/// is hidden. -pub fn polygon_replaces_selection(app: &PhotocraftApp) -> bool { - (!app.ui.polygon.is_empty() && app.ui.polygon_mode == "replace") || crate::magnetic_lasso_ui::replaces_selection(app) -} - -/// Close the polygonal lasso and make the selection in the mode it started in. -pub fn commit_polygon(app: &mut PhotocraftApp) { - let pts = std::mem::take(&mut app.ui.polygon); - let mode = std::mem::take(&mut app.ui.polygon_mode); - if pts.len() >= 3 { - let mode = if mode.is_empty() { selection_mode(app, egui::Modifiers::NONE).to_owned() } else { mode }; - let o = &app.ui.tool_options; - let _ = app.run("select.lasso", json!({"points": pts, "mode": mode, "antiAlias": o.anti_alias, "feather": o.feather})); - } -} - -/// Apply the crop tool's rectangle. When `image.crop` refuses it (the error is in the status bar), -/// the frame, its turn and its box Undo stay for fixing. -pub fn commit_crop(app: &mut PhotocraftApp) { - // Never another document's frame (#1918). - crate::crop_ui::cancel_stale(app); - let kept = crate::crop_ui::keep(app); - // Committing ends the box's own Undo/Redo: from here Edit › Undo reverts the document. - crate::crop_ui::clear_history(app); - // ↵ during a drag ends it: the release must not bring back the old document's frame. - app.crop.drag = None; - let Some(r) = app.ui.crop_rect.take() else { return }; - // The crop's default mode leaves the view upright (`crop_mode`). - crate::crop_mode::upright(app); - // The untouched default frame around the whole canvas crops nothing (Photoshop's ↵ on it does - // nothing); one framing the selection's bounds crops to them (#1789). - if std::mem::take(&mut app.crop.default_frame) { - let whole = app.session.active().map(|st| st.doc.bounds()).map(|b| [f64::from(b.x0), f64::from(b.y0), f64::from(b.x1), f64::from(b.y1)]); - if whole.is_none_or(|b| b == r) { - return; - } - } - let (x, y) = (r[0].round(), r[1].round()); - let (w, h) = ((r[2] - r[0]).round().max(1.0), (r[3] - r[1]).round().max(1.0)); - let delete = app.ui.tool_options.crop_delete; - let mut p = json!({"x": x, "y": y, "width": w, "height": h, "deleteCroppedPixels": delete}); - // Fill › Content-Aware Fill (#3823): what a turned or extending frame uncovers is filled from - // its surroundings instead of the background colour. - if app.ui.tool_options.crop_content_aware { - p["contentAware"] = json!(true); - } - // A turned frame (#1792): the document turns with it, then is cropped to it. (The untouched - // default frame above is never turned: turning it makes it a real frame.) - let angle = crate::crop_ui::angle(app); - app.ui.crop_angle = 0.0; - if angle != 0.0 { - p["angle"] = json!(angle); - } - // W x H x Resolution (#2443): resample to that size and set the resolution. - crate::crop_size::commit_params(app, &mut p); - if app.run("image.crop", p).is_err() { - crate::crop_ui::restore(app, kept); - } else if let Some(i) = app.session.active_index() { - app.ui.views[i].fit_pending = true; - } -} - -/// "mask" when the Layers panel targets (or the canvas shows) the active layer's mask, or the layer -/// is an adjustment layer with one (it has no pixels: #4298), else "pixels". -pub fn paint_target(app: &PhotocraftApp) -> serde_json::Value { - use photocraft_engine::channel_cmds::ChannelTarget; - let Some(st) = app.session.active() else { return json!("pixels") }; - // A targeted alpha channel (Channels panel) or Quick Mask mode wins over the layer. - match st.channel_view.target { - ChannelTarget::Alpha(i) if i < st.doc.channels.len() => return json!({ "channel": i }), - ChannelTarget::Composite if st.doc.quick_mask.is_some() => return json!("quickMask"), - ChannelTarget::LayerMask => return json!("mask"), - _ => {} - } - // A smart object's targeted (or shown) filter mask takes the paint (FILE-215-3). - if app.filter_mask_targeted() { - return json!("filterMask"); - } - let has_mask = st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.mask.is_some()); - // Viewing the mask (⌥-click its thumbnail, #196) paints the mask. - let viewing = photocraft_engine::mask_view_cmds::current(st).is_some_and(|v| !v.filter); - let mask = app.ui.mask_target || viewing || crate::adjustment_layer_active(st); - json!(if mask && has_mask { "mask" } else { "pixels" }) -} - #[cfg(test)] mod tap_pressure_tests { #[test] diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs new file mode 100644 index 0000000000..a7048ea3c5 --- /dev/null +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -0,0 +1,209 @@ +use super::tool_input::ToolEvent; +use super::view_xform::ViewXform; +use super::*; + +/// Windows' crosshair cursor inverts the pixels under it, so over mid-grey (the pasteboard, many +/// photos) it vanishes (#737), and the Linux themes' and macOS's differ. Use the same black-and-white +/// bitmap on every desktop platform, carried by the OS so its movement does not wait for the canvas +/// to render (#1343). +pub(super) fn visible_crosshair(icon: egui::CursorIcon, painter: &egui::Painter, p: Pos2, draw: bool) -> egui::CursorIcon { + if !draw || icon != egui::CursorIcon::Crosshair { + return icon; + } + crate::tool_cursor::crosshair(painter, p, 8.0, 2.0) +} + +/// The Pencil's cursor at `doc` (document pixels): the whole-pixel square its dab fills +/// (`paint::grid_square`), in screen points with its edges on physical pixels (`ppp` = pixels +/// per point), so it lines up with the pixel grid at any zoom. +pub(crate) fn pencil_cursor_rect(xf: &ViewXform, doc: [f64; 2], size: f32, ppp: f32) -> Rect { + let [x0, y0, x1, y1] = photocraft_engine::paint::grid_square(doc[0], doc[1], size); + let r = Rect::from_two_pos(xf.to_screen(x0 as f32, y0 as f32), xf.to_screen(x1 as f32, y1 as f32)); + let ppp = if ppp.is_finite() && ppp > 0.0 { ppp } else { 1.0 }; + let snap = |v: f32| (v * ppp).round() / ppp; + Rect::from_min_max(pos2(snap(r.min.x), snap(r.min.y)), pos2(snap(r.max.x), snap(r.max.y))) +} + +/// Whether an aliased (Pencil) dab of `size` pixels is round rather than its whole +/// [`pencil_cursor_rect`] square. The dab fills the pixels whose centres lie within its radius of +/// the grid centre (`paint::grid_center`), so up to 3 px the corner pixels are in and the dab is +/// a square; from 4 px on they fall outside and it is a disc (#2662). +pub(crate) fn pencil_tip_is_round(size: f32) -> bool { + let n = if size.is_finite() { size.round().clamp(1.0, 100_000.0) } else { 1.0 }; + let h = n / 2.0; + (h - 0.5) * std::f32::consts::SQRT_2 > h +} + +/// Whether a brush-tip circle draws its centre mark. +/// Clone Stamp and Healing Brush stay an empty circle until Option is held, the source-point +/// cursor. Other brushes follow Preferences › Cursors › Show Crosshair in Brush Tip, as in +/// Photoshop; the Background Eraser always shows its sampling hotspot. +pub(super) fn brush_tip_centre(tool: Tool, option: bool, show_crosshair: bool) -> bool { + if tool == Tool::QuickSelection { + return false; + } + if matches!(tool, Tool::CloneStamp | Tool::Healing) { + return option || show_crosshair; + } + show_crosshair || tool == Tool::BackgroundEraser +} + +/// The display colour of an RGB triple (0..1 per channel) as an egui colour. +fn display_color(c: [f32; 3]) -> Color32 { + let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + Color32::from_rgb(b(c[0]), b(c[1]), b(c[2])) +} + +/// The Eyedropper ring's two colours at document point (x, y): the colour under the pointer +/// (what a click would pick) and the current foreground, or `None` where there is no colour +/// to sample (#213). +pub(crate) fn eyedropper_ring_colors(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<(Color32, Color32)> { + let new = eyedropper_color(app, x, y)?; + let fg = app.session.tools.foreground; + Some((display_color(new), display_color([fg[0], fg[1], fg[2]]))) +} + +/// Draw the Eyedropper's comparison ring at `p`: an opaque neutral grey band around the +/// pointer with the sampled colour on its upper half and the current one on the lower, +/// framed by thin dark and light hairlines so every edge reads on any image, and the +/// pipette at its centre marking the sampled pixel (#213, #6973). Like Photoshop it shows +/// only while the mouse button is held (`held`): hovering shows the plain pipette and +/// samples nothing. `None` when not held, there is nothing to sample, or the Precise-cursor +/// preference wants the plain crosshair. +pub(super) fn eyedropper_ring(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, p: Pos2, held: bool) -> Option { + // The options bar's Show Sampling Ring turns it off (#1649). + if !held || !app.ui.tool_options.eyedropper_ring || app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise { + return None; + } + let [x, y] = xf.to_doc(p); + let (new, current) = eyedropper_ring_colors(app, x, y)?; + // Photoshop's proportions (#6973): a ring about 210 pt across whose opaque grey outer + // band and coloured inner band are each about 17 pt wide, over a transparent centre. + // In points, so the ring scales with Interface › UI Scale like the rest of the cursor. + let (r_out, band) = (105.0_f32, 17.0_f32); + let r_in = r_out - 2.0 * band; + // Screen y grows down, so PI..TAU is the upper half (the sampled colour) and 0..PI the + // lower (the current one); the halves meet at 3 and 9 o'clock, as in Photoshop. + use std::f32::consts::{PI, TAU}; + let upper: Vec = (0..=48) + .map(|i| { + let a = PI + (TAU - PI) * i as f32 / 48.0; + p + vec2(a.cos(), a.sin()) * (r_in + band / 2.0) + }) + .collect(); + // `circle_stroke` paints its stroke outside the radius, `Shape::line` centres it. + painter.circle_stroke(p, r_in, Stroke::new(band, current)); + painter.add(egui::Shape::line(upper, Stroke::new(band, new))); + painter.circle_stroke(p, r_in + band, Stroke::new(band, RING_GREY)); + // Thin dark and light hairlines on the ring's two edges, one physical pixel wide, so it + // reads on any colour including a flat mid-grey that matches the band itself (#6973). + let px = 1.0 / painter.ctx().pixels_per_point().max(1.0); + let (dark, light) = (Stroke::new(px, Color32::from_black_alpha(160)), Stroke::new(px, Color32::from_white_alpha(160))); + painter.circle_stroke(p, r_out, dark); + painter.circle_stroke(p, r_out + px, light); + painter.circle_stroke(p, r_in - px, dark); + painter.circle_stroke(p, r_in - 2.0 * px, light); + // Photoshop keeps the pipette visible at the centre, its tip on the sampled pixel; a + // ring this size says nothing about where it samples without it. + Some(pipette_cursor(painter.ctx(), p)) +} + +/// The Eyedropper ring's opaque neutral grey, as Photoshop measures it (#6973). +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). +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) +} + +/// 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 { + (app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise) != app.caps_lock +} + +/// A pen tool's standard cursor: its toolbar icon with the nib (the Convert Point tool: the +/// anchor) on `p`. Draws it at `p` and returns the OS cursor to set (hidden). +pub(crate) fn pen_cursor(ctx: &egui::Context, tool: Tool, p: Pos2) -> egui::CursorIcon { + // Where each icon's point is in its 24-unit box: the full-size pen's nib at (2.3, 2.3); the + // Freeform and Curvature pens draw it at 0.68 × from (7, 7); Convert Point's apex anchor. + let hot = match tool { + Tool::FreeformPen | Tool::CurvaturePen => vec2(8.56, 8.56), + Tool::ConvertPoint => vec2(12.0, 7.0), + _ => vec2(2.3, 2.3), + }; + crate::icons::cursor(ctx, crate::icons::tool_icon(tool), p, hot / 24.0, 22.0); + egui::CursorIcon::None +} + +/// The sampling cursor: a pipette whose tip is the sampled pixel. Draws it at `p` and returns the +/// OS cursor to set (hidden). +pub(crate) fn pipette_cursor(ctx: &egui::Context, p: Pos2) -> egui::CursorIcon { + // The tip of the icon's pipette is at (2, 22) of its 24-unit box. + crate::icons::cursor(ctx, "pipette", p, vec2(2.0, 22.0) / 24.0, 20.0); + egui::CursorIcon::None +} + +/// The Paint Bucket's cursor: a bucket whose pouring corner is the filled pixel. Draws it at `p` +/// and returns the OS cursor to set (hidden). +pub(crate) fn paint_bucket_cursor(ctx: &egui::Context, p: Pos2) -> egui::CursorIcon { + // The left corner of the icon's bucket is at (2, 12) of its 24-unit box. + crate::icons::cursor(ctx, "paint-bucket", p, vec2(2.0, 12.0) / 24.0, 22.0); + egui::CursorIcon::None +} + +/// Decided when the press starts, so ⌥ pressed or released mid-stroke never switches between +/// painting and sampling. +pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { + if matches!(ev, ToolEvent::Down { .. }) { + let physical_right = app.services.right_button_down.as_ref().is_some_and(|f| f()); + app.alt_sampling = !physical_right && alt_samples(app.active_tool(), mods); + } + if !app.alt_sampling { + return false; + } + match ev { + // Without ⌥: the sample sets the foreground colour, whatever the Eyedropper would do. + ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } => sample_eyedropper(app, x, y, egui::Modifiers::NONE), + ToolEvent::Up { .. } => app.alt_sampling = false, + } + true +} + +pub(super) fn sample_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { + if let Some([r, g, b]) = eyedropper_color(app, x, y) { + let key = if mods.alt { "background" } else { "foreground" }; + let _ = app.run("tools.setColors", json!({ key: [r, g, b, 1.0] })); + } +} + +/// The colour at document point (x, y) with the Eyedropper's Sample Size (the composite pixel, +/// or the average of the square around it) from the layers `sample_layer` names (`document.sampleColor`). +/// `None` off the image or over transparency. +fn sample_color(app: &mut PhotocraftApp, x: f64, y: f64, sample_layer: &str) -> Option<[f32; 3]> { + if !(x.is_finite() && y.is_finite()) { + return None; + } + let size = app.ui.tool_options.eyedropper_size; + let v = app.run("document.sampleColor", json!({"x": x, "y": y, "size": size, "sampleLayer": sample_layer})).ok()?; + match serde_json::from_value::>(v).ok()?[..] { + [r, g, b, a] if a > 0.0 => Some([r, g, b]), + _ => None, + } +} + +/// What the Eyedropper tool (and a painting tool's ⌥-click) picks at document point (x, y): its +/// options bar's Sample Size and Sample (#1649). +pub(crate) fn eyedropper_color(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<[f32; 3]> { + let layers = app.ui.tool_options.eyedropper_sample.clone(); + sample_color(app, x, y, &layers) +} + +/// The active document's composite colour at document point (x, y), averaged over the +/// Eyedropper's Sample Size as Photoshop's dialog eyedroppers (Curves, Color Picker) do. +/// `None` off the image or over transparency. +pub(crate) fn composite_color(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<[f32; 3]> { + sample_color(app, x, y, "all") +} diff --git a/crates/ui-egui/src/canvas/display.rs b/crates/ui-egui/src/canvas/display.rs new file mode 100644 index 0000000000..1cfae7a46d --- /dev/null +++ b/crates/ui-egui/src/canvas/display.rs @@ -0,0 +1,300 @@ +use super::strokes::live_stroke; +use super::*; + +pub(super) fn checker(app: &mut PhotocraftApp, ctx: &egui::Context) -> egui::TextureId { + // Preferences › Transparency & Gamut colours (the texture is rebuilt when they change). + let [ca, cb] = app.session.prefs().transparency_and_gamut.colors(); + if app.prefs_rt.checker_key != Some([ca, cb]) { + app.prefs_rt.checker_key = Some([ca, cb]); + app.checker = None; + } + app.checker + .get_or_insert_with(|| { + let (a, b) = (Color32::from_rgb(ca[0], ca[1], ca[2]), Color32::from_rgb(cb[0], cb[1], cb[2])); + let img = egui::ColorImage::new([2, 2], vec![a, b, b, a]); + let opts = TextureOptions { + magnification: egui::TextureFilter::Nearest, + minification: egui::TextureFilter::Nearest, + wrap_mode: egui::TextureWrapMode::Repeat, + mipmap_mode: None, + }; + ctx.load_texture("checker", img, opts) + }) + .id() +} + +fn buffer_to_image(buf: &photocraft_compose::Buffer) -> egui::ColorImage { + // `buf.to_rgba8()` then `color_image`, fused: one parallel pass, no intermediate image. + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let mut pixels = vec![egui::Color32::TRANSPARENT; buf.px.len()]; + let convert = |out: &mut [egui::Color32], src: &[[f32; 4]]| { + for (o, p) in out.iter_mut().zip(src) { + *o = egui::Color32::from_rgba_unmultiplied(q(p[0]), q(p[1]), q(p[2]), q(p[3])); + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + pixels.par_chunks_mut(16 * 1024).zip(buf.px.par_chunks(16 * 1024)).for_each(|(o, s)| convert(o, s)); + } + #[cfg(target_arch = "wasm32")] + convert(&mut pixels, &buf.px); + egui::ColorImage::new([buf.rect.width() as usize, buf.rect.height() as usize], pixels) +} + +/// `img` as an egui image: `ColorImage::from_rgba_unmultiplied`, in parallel off wasm. egui's own +/// conversion runs on one thread and took 37 ms of a 24 MP canvas or preview update, three times +/// the quantize before it. +fn color_image(img: &photocraft_raster::Rgba8Image) -> egui::ColorImage { + let size = [img.width as usize, img.height as usize]; + let src = img.pixels.as_chunks::<4>().0; + let mut pixels = vec![egui::Color32::TRANSPARENT; src.len()]; + let convert = |out: &mut [egui::Color32], src: &[[u8; 4]]| { + for (o, &[r, g, b, a]) in out.iter_mut().zip(src) { + *o = egui::Color32::from_rgba_unmultiplied(r, g, b, a); + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + pixels.par_chunks_mut(16 * 1024).zip(src.par_chunks(16 * 1024)).for_each(|(o, s)| convert(o, s)); + } + #[cfg(target_arch = "wasm32")] + convert(&mut pixels, src); + egui::ColorImage::new(size, pixels) +} + +/// A composite as monitor pixels: document profile → monitor profile (nothing to do in the +/// common sRGB-on-sRGB case). +pub(crate) fn display_image(display: Option<&photocraft_engine::display_color::CanvasDisplay>, buf: &photocraft_compose::Buffer) -> egui::ColorImage { + match display { + Some(d) if !d.is_identity() => color_image(&d.to_rgba8(buf)), + _ => buffer_to_image(buf), + } +} + +/// The canvas display of `doc` on `display` (`None`: the main window's) and a key that changes +/// with it (folded into the canvas caches' preview keys, so a monitor or profile change +/// re-renders). +pub(crate) fn canvas_display( + app: &PhotocraftApp, + doc: &Document, + display: Option, +) -> (Option>, u64) { + match app.session.color.canvas_display_for(doc, display.or(app.session.color.main_display)) { + Ok(d) => { + let k = d.key; + (Some(d), k) + } + Err(_) => (None, 0), + } +} + +/// [`canvas_display`]'s key for the GPU canvas texture: what the texture stores, the same on +/// every display (the display LUT holds the monitor profile). +pub(super) fn texture_key(display: Option<&photocraft_engine::display_color::CanvasDisplay>) -> u64 { + display.map_or(0, |d| d.texture_key) +} + +/// `app.canvases` key: CPU canvas textures are per document and display (they hold monitor +/// values); the GPU canvas state uses [`GPU_OUTPUT`]. +pub(crate) fn cache_key(doc: photocraft_doc::DocId, display: Option) -> (photocraft_doc::DocId, u32) { + (doc, display.unwrap_or(0)) +} + +/// `app.canvases` output of the GPU canvas state (one texture per document for all displays). +pub(crate) const GPU_OUTPUT: u32 = u32::MAX; + +/// The document to render: the committed one, or a clone with the live adjustment preview applied. +pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Arc, u64) { + if let Some(shown) = crate::type_panels_ui::color_picker::display_doc(app, idx) { + return shown; + } + if let Some(shown) = crate::solid_fill_ui::display_doc(app, idx) { + return shown; + } + if let Some(shown) = crate::pattern_fill_ui::display_doc(app, idx) { + return shown; + } + if let Some(shown) = crate::shape_fill_ui::display_doc(app, idx) { + return shown; + } + if let Some(shown) = crate::type_transform::display_doc(app, idx) { + return shown; + } + if let Some(shown) = crate::type_font_preview::display_doc(app, idx) { + return shown; + } + // Vanishing Point's strokes over the document as it is now (the Layers panel may have + // changed it since the options bar synced them this frame). + crate::vp_ui::sync_preview(app); + // Puppet / Perspective Warp previews hide the layer they draw on a mesh. + if let Some(shown) = crate::distort_ui::display_doc(app, idx) { + return shown; + } + // Image › Adjustments dialog: a temporary adjustment layer clipped to the target. + if let Some(shown) = crate::adjust_preview::display_doc(app, idx) { + return shown; + } + // Gradient tool (live) drag, or a stop dragged in the Properties panel. + if let Some(shown) = crate::gradient_ui::display_doc(app, idx) { + return shown; + } + // Move tool drag: the moving layers at the pointer. + if let Some(shown) = crate::move_ui::display_doc(app, idx) { + return shown; + } + // Patch Tool drag: the selection healed from where the pointer is. + if let Some(shown) = crate::patch_preview::display_doc(app, idx) { + return shown; + } + // Content-Aware Move drag or box: the result, once computed in the background. It comes + // before the reorder preview, which is built from the session document and would drop it. + if let Some(shown) = crate::cam_preview::display_doc(app, idx) { + return shown; + } + // Live Layers-panel reorder previews the actual composite before mouse release. + if let Some(shown) = crate::layers_panel_ui::display_reorder(app, idx) { + return shown; + } + // A blend mode hovered in the Layers panel. + if let Some(shown) = crate::blend_preview::display_doc(app, idx) { + return shown; + } + crate::transform_tool::follow_edits(app); + let st = &app.session.documents()[idx]; + if let Some(l) = live_stroke(app, idx) { + return (l.stroke.doc().clone(), l.display_key()); + } + if let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) + && app.session.active_index() == Some(idx) + && pv.doc.id == st.doc.id + && st.doc.layer(photocraft_doc::LayerId(t.layer)).is_some() + { + return (pv.doc.clone(), (1 << 40) + 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); + // The Preview checkbox off shows the document as it was when the dialog opened; + // edits still land in the dialog state and OK applies them whatever it says. + let preview_on = style.and_then(|d| d.fields.get("preview")).and_then(serde_json::Value::as_bool).unwrap_or(true); + if style.is_none() || !preview_on { + app.style_preview = None; + } + if let Some(d) = style.filter(|_| preview_on) + && app.session.active_index() == Some(idx) + { + let fields = crate::layer_style::color_picker::preview_fields(app, d.id, &d.fields); + let key = (crate::layer_style::preview_hash(&fields) ^ st.revision.wrapping_mul(0x9e37_79b9_7f4a_7c15)) | 1 << 63; + if app.style_preview.as_ref().map(|p| p.0) != Some(key) { + let shown = crate::layer_style::preview_document(&st.doc, &app.session.patterns, &fields).map(std::sync::Arc::new); + if let Err(error) = &shown { + log::warn!("Layer Style preview: {error}"); + } + app.style_preview = Some((key, shown)); + } + if let Some((_, Ok(doc))) = &app.style_preview { + return (doc.clone(), key); + } + } + let revision = st.revision; + let snapshot = st.doc.clone(); + if let Some((layer, params)) = app.live_adjust.clone() + && let Some(l) = snapshot.layer(layer) + && let LayerContent::Adjustment(a) = &l.content + { + let key = crate::adjust_preview::live_key(app, &snapshot, revision, layer, ¶ms); + let shown = memo_display(app, &snapshot, key, || { + let kind = photocraft_engine::commands::adjustment_kind(a); + let preview = photocraft_engine::adjust_params::from_params(kind, ¶ms, Some(a), snapshot.mode).unwrap_or_else(|_| a.clone()); + let mut doc = (*snapshot).clone(); + if let Some(lm) = doc.layer_mut(layer) { + lm.content = LayerContent::Adjustment(preview); + } + Some(doc) + }); + if let Some(doc) = shown { + return (doc, key); + } + } + // Duotone documents display through their inks. + if let Some(shown) = memo_display(app, &snapshot, 1 << 41, || photocraft_engine::mode_cmds::display_document(&snapshot)) { + return (shown, 1 << 41); + } + (snapshot, 0) +} + +/// `display_doc`'s live-adjust and Duotone documents, built once per document snapshot and key +/// rather than on each of its 3–4 calls a frame (#4527): each build clones the whole document. +fn memo_display( + app: &mut PhotocraftApp, + snapshot: &std::sync::Arc, + key: u64, + build: impl FnOnce() -> Option, +) -> Option> { + let id = snapshot.id; + if let Some((doc, k, shown)) = app.display_memo.get(&id) + && *k == key + && doc.ptr_eq(&std::sync::Arc::downgrade(snapshot)) + { + return Some(shown.clone()); + } + let Some(shown) = build().map(std::sync::Arc::new) else { + app.display_memo.remove(&id); + return None; + }; + // Entries of closed documents go when another is stored. + app.display_memo.retain(|_, (doc, _, _)| doc.strong_count() > 0); + app.display_memo.insert(id, (std::sync::Arc::downgrade(snapshot), key, shown.clone())); + Some(shown) +} + +/// Lattice size of the canvas display LUT (colour management, Proof Colors, Gamut Warning). +const DISPLAY_LUT: usize = 33; + +/// Keep the GPU display LUT under `key` (the document's texture or a preview of it) in step with +/// `doc`'s colour management: document → monitor profile and View › Proof Colors / Gamut +/// Warning (the 32-bit preview is applied by the canvas shader, see [`hdr_preview`]). Returns the canvas `display` mode (0 none — the identity, e.g. sRGB on +/// an sRGB monitor —, 1 LUT, 2 LUT + gamut warning, 3 matrix/shaper). +pub(super) fn sync_display_lut(app: &mut PhotocraftApp, doc: &photocraft_doc::Document, key: u64, display: Option) -> u8 { + let Some(gpu) = app.gpu.clone() else { return 0 }; + let output = display.unwrap_or(0); + // Rebuild only when anything feeding the LUT changes. + let sig = app.session.color.display_signature_for(doc, display); + if let Some((s, mode)) = gpu.display_lut_signature(key, output) + && s == sig + { + return mode; + } + // Keep the curve/matrix/curve stages separate: interpolating a finished display + // transform on a 33³ lattice crushes shadows when the monitor curve is steep near zero. + if let Ok(Some(shaper)) = app.session.color.gpu_canvas_matrix_shaper_for(doc, display) { + gpu.set_display_matrix_shaper(key, output, &shaper); + gpu.cache_display_lut_signature(key, output, sig, 3); + return 3; + } + let gamut = app.session.color.proof(doc.id).gamut_warning; + let mode = match app.session.color.gpu_canvas_lut_for(doc, DISPLAY_LUT, display) { + Ok(Some(bytes)) => { + gpu.set_display_lut(key, output, DISPLAY_LUT as u32, Some(&bytes)); + if gamut { 2 } else { 1 } + } + Ok(None) => { + gpu.set_display_lut(key, output, DISPLAY_LUT as u32, None); + 0 + } + Err(e) => { + let template = "Color management: {error}"; + app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e.to_string())]); + gpu.set_display_lut(key, output, DISPLAY_LUT as u32, None); + 0 + } + }; + gpu.cache_display_lut_signature(key, output, sig, mode); + mode +} + +/// View › 32-bit Preview Options for the GPU canvas shader: (exposure, gamma) when active. +pub(super) fn hdr_preview(app: &PhotocraftApp, doc: &photocraft_doc::Document) -> Option<[f32; 2]> { + app.session.color.hdr_preview(doc).map(|h| [h.exposure, h.gamma]) +} diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs new file mode 100644 index 0000000000..a58e8db11b --- /dev/null +++ b/crates/ui-egui/src/canvas/drag.rs @@ -0,0 +1,328 @@ +use super::view_xform::ViewXform; +use super::*; + +/// An in-progress pointer gesture on the canvas. +#[derive(Clone, Debug)] +pub struct Drag { + pub tool: Tool, + pub start: [f64; 2], + pub points: Vec<[f64; 3]>, + pub modifiers: egui::Modifiers, + /// A Brush/Eraser stroke that erases: the Eraser, or a right-button Brush drag with + /// Preferences › Tools › Right-click with painting tools set to Erase. + pub erase: bool, + /// A Brush or Pencil stroke in Photoshop's Clear mode (`paint_mouse::clears`, #3439): it + /// erases, sent as `"mode": "clear"` so History names the tool rather than the Eraser. + pub clear: bool, + /// ⇧ constraint of a painting stroke (stroke_constraint.rs). + pub constrain: Option, + /// Modifiers held now (updated on every pointer event of the gesture). + pub live: egui::Modifiers, + /// Which of the modifiers held at the press have been released since. + pub released: egui::Modifiers, + /// The reposition key (Space) is held: pointer moves move the whole gesture instead of + /// sizing it (marquees, lasso, shapes; `hold_keys`). + pub reposition: bool, + /// A marquee or lasso drag that started inside the selection moves it instead of drawing: + /// `Some(false)` moves the outline, `Some(true)` moves the floating piece (`select.float`), as + /// every Move-tool drag with a selection does (`move_ui::moves_selected_pixels_with`). + pub sel_move: Option, + /// The last ⇧-locked offset of a selection-tool drag of the selection (`move_mods`, #6231); + /// keeps the locked direction stable between events. The Move tool's own drags use `move_mods`. + pub sel_axis: Option<[f64; 2]>, + pub lasso: Option, +} + +impl Drag { + pub fn new(tool: Tool, start: [f64; 2], points: Vec<[f64; 3]>, modifiers: egui::Modifiers, erase: bool) -> Self { + Self { + tool, + start, + points, + modifiers, + erase, + clear: false, + constrain: None, + live: modifiers, + released: egui::Modifiers::NONE, + reposition: false, + sel_move: None, + sel_axis: None, + lasso: None, + } + } + + /// Reposition: move the start and every point so the last one lands on `to` (same size). + pub fn shift_to(&mut self, to: [f64; 2]) { + let last = self.points.last().map_or(self.start, |p| [p[0], p[1]]); + let (dx, dy) = (to[0] - last[0], to[1] - last[1]); + if !(dx.is_finite() && dy.is_finite()) { + return; + } + self.start = [self.start[0] + dx, self.start[1] + dy]; + for p in &mut self.points { + p[0] += dx; + p[1] += dy; + } + if self.points.is_empty() { + self.points.push([to[0], to[1], 1.0]); + } + } + + /// Record the modifiers of a pointer event. + pub(crate) fn track(&mut self, mods: egui::Modifiers) { + self.live = mods; + self.released.shift |= !mods.shift; + self.released.alt |= !mods.alt; + } + + /// ⇧ (square / circle) and ⌥ (from the centre) for a marquee drag. A modifier held at the press + /// picks the selection mode instead (add / subtract, #188) until it is released and pressed + /// again, as in Photoshop. + pub fn marquee_mods(&self) -> (bool, bool) { + let fresh = |now: bool, at_press: bool, released: bool| now && (!at_press || released); + (fresh(self.live.shift, self.modifiers.shift, self.released.shift), fresh(self.live.alt, self.modifiers.alt, self.released.alt)) + } +} + +/// The marquee dragged from `d.start` to `end` as two document-space corners: the options-bar +/// style (fixed ratio / fixed size), ⇧ for a square or circle, ⌥ to draw from the centre. +pub fn marquee_corners(o: &crate::state::ToolOptions, d: &Drag, end: [f64; 2]) -> ([f64; 2], [f64; 2]) { + let (shift, alt) = d.marquee_mods(); + if o.marquee_style == "fixedSize" { + // A fixed box is positioned, not sized, by the drag. Using the press plus the drag's + // sign pinned it there and flipped it by its full width/height when the pointer crossed + // the press. The preview and release both follow the current pointer instead. + let (w, h) = (f64::from(o.marquee_width).max(1.0), f64::from(o.marquee_height).max(1.0)); + let a = if alt { [end[0] - w / 2.0, end[1] - h / 2.0] } else { end }; + return (a, [a[0] + w, a[1] + h]); + } + let e = crate::chrome_ui::marquee_end(&o.marquee_style, o.marquee_width as f64, o.marquee_height as f64, shift, d.start, end); + if !alt { + return (d.start, e); + } + let (dx, dy) = (e[0] - d.start[0], e[1] - d.start[1]); + // For a sized marquee the drag is the half extent when drawing from the centre. + ([d.start[0] - dx, d.start[1] - dy], [d.start[0] + dx, d.start[1] + dy]) +} + +/// The pixel rectangle a Rectangular/Elliptical Marquee drag selects so far: shown live (ants +/// and readout) exactly as the release commits it, on whole pixel edges as in Photoshop. `None` +/// while the gesture is still a click (it never left the press point by more than a few screen +/// pixels at `zoom`, points per document pixel) or the rectangle has no area: a release then +/// deselects. A one-pixel row or column is a selection (#2391). With the Fixed Size style a +/// click places the selection, as in Photoshop. +pub(crate) fn marquee_preview_px(o: &crate::state::ToolOptions, d: &Drag, zoom: f32) -> Option<[f64; 4]> { + let fixed = o.marquee_style == "fixedSize"; + if !matches!(d.tool, Tool::RectMarquee | Tool::EllipseMarquee) || (!fixed && crate::shape_dialog::is_click(d.start, &d.points, zoom)) { + return None; + } + let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + let (a, b) = marquee_corners(o, d, last); + let mut r = if fixed { fixed_size_px(a, b, o.marquee_width, o.marquee_height) } else { marquee_px(a, b) }; + if marquee_is_square(o, d) { + r = square_px(r, d.start, last); + } + (r[2] > r[0] && r[3] > r[1]).then_some(r) +} + +/// The pixel rectangle `[x0, y0, x1, y1]` a marquee between two corners selects. +pub fn marquee_px(a: [f64; 2], b: [f64; 2]) -> [f64; 4] { + [a[0].min(b[0]).floor(), a[1].min(b[1]).floor(), a[0].max(b[0]).ceil(), a[1].max(b[1]).ceil()] +} + +/// The pixel rectangle of a Fixed Size marquee between the corners `a` and `b`: exactly `w` × `h` +/// whole pixels. Snapping both edges outwards (`marquee_px`) added a pixel to each side whenever +/// the press point sat between pixels, so 10 × 10 selected 11 × 11 (#6015). The near edge goes +/// to the closest pixel edge and the far one is the size away. +pub fn fixed_size_px(a: [f64; 2], b: [f64; 2], w: f32, h: f32) -> [f64; 4] { + let (w, h) = (f64::from(w).round().max(1.0), f64::from(h).round().max(1.0)); + let (x0, y0) = (a[0].min(b[0]).round(), a[1].min(b[1]).round()); + [x0, y0, x0 + w, y0 + h] +} + +/// Whether the marquee drag `d` is constrained to a square (or circle): ⇧ during the drag with +/// the Normal style, or a Fixed Ratio of 1:1. Mirrors the branches of `chrome_ui::marquee_end`. +fn marquee_is_square(o: &crate::state::ToolOptions, d: &Drag) -> bool { + let (w, h) = (f64::from(o.marquee_width), f64::from(o.marquee_height)); + match o.marquee_style.as_str() { + "fixedSize" => false, + "fixedRatio" if w > 0.0 && h > 0.0 => w == h, + _ => d.marquee_mods().0, + } +} + +/// A constrained square `r` (`marquee_px` of its corners) with equal sides on whole pixels. +/// +/// The square is built in continuous coordinates, and snapping each axis to the pixel grid on +/// its own (floor the near edge, ceil the far one) made one side a pixel longer than the other +/// whenever the press point sat between pixels: a ⇧ drag read 101 × 102 (#5472). The shorter +/// side grows to the longer one, away from the press point (`start`, towards `end`), so the +/// square still covers every pixel the drag touched. +pub fn square_px(r: [f64; 4], start: [f64; 2], end: [f64; 2]) -> [f64; 4] { + let [x0, y0, x1, y1] = r; + let (w, h) = (x1 - x0, y1 - y0); + let n = w.max(h); + let grow = |lo: f64, hi: f64, extent: f64, from: f64, to: f64| { + let d = (n - extent).max(0.0); + if to < from { (lo - d, hi) } else { (lo, hi + d) } + }; + let (x0, x1) = grow(x0, x1, w, start[0], end[0]); + let (y0, y1) = grow(y0, y1, h, start[1], end[1]); + [x0, y0, x1, y1] +} + +/// The one-pixel line `[x0, y0, x1, y1]` a Single Row (Single Column) Marquee at `p` selects: the +/// pixel row (column) under `p`, kept on the canvas, across the whole `size`. `None` for other +/// tools, an empty canvas or a point that is not a number. +pub(crate) fn single_line_px(tool: Tool, size: [u32; 2], p: [f64; 2]) -> Option<[f64; 4]> { + let [w, h] = size.map(f64::from); + if w < 1.0 || h < 1.0 || !p[0].is_finite() || !p[1].is_finite() { + return None; + } + match tool { + Tool::SingleRowMarquee => { + let y = p[1].floor().clamp(0.0, h - 1.0); + Some([0.0, y, w, y + 1.0]) + } + Tool::SingleColumnMarquee => { + let x = p[0].floor().clamp(0.0, w - 1.0); + Some([x, 0.0, x + 1.0, h]) + } + _ => None, + } +} + +/// The line a Single Row / Single Column Marquee gesture `d` selects so far: it follows the +/// pointer until the release. +pub(super) fn single_line_drag_px(app: &PhotocraftApp, d: &Drag) -> Option<[f64; 4]> { + let st = app.session.active()?; + let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + single_line_px(d.tool, [st.doc.size.width, st.doc.size.height], last) +} + +/// The marching ants of a marquee drag: its rectangle, or the ellipse inscribed in it, built in +/// document space and mapped point by point through the view, so the hinting lands where the +/// release commits the selection. +/// +/// A rotated view projects the rectangle onto a rotated one, and an axis-aligned screen box +/// through two of its corners is a different shape in a different place: the commit was always +/// right, only the hinting was drawn elsewhere (#2512). The points are not snapped: the ants snap +/// straight edges to device pixels as they draw them (`crate::ants`), like every other outline, so +/// the lines stay crisp at any zoom (#172) and display scale (#7489). +pub(crate) fn marquee_ants(xf: &ViewXform, tool: Tool, a: [f64; 2], b: [f64; 2]) -> Vec { + let (x0, x1) = (a[0].min(b[0]), a[0].max(b[0])); + let (y0, y1) = (a[1].min(b[1]), a[1].max(b[1])); + let at = |x: f64, y: f64| xf.to_screen(x as f32, y as f32); + if tool != Tool::EllipseMarquee { + return vec![at(x0, y0), at(x1, y0), at(x1, y1), at(x0, y1)]; + } + // An axis-aligned view (rotation a multiple of 90 degrees) maps the ellipse onto the one + // inscribed in the screen box of two opposite corners. The ants draw its vertices where they + // are: snapping each on its own turns the nearly flat arcs at the edge midpoints into 1 px + // stairs, whose antialiased steps wash the ants out to grey on white and black. + let quarter = xf.rotation.rem_euclid(90.0); + if quarter < 1e-4 || 90.0 - quarter < 1e-4 { + let r = Rect::from_two_pos(at(x0, y0), at(x1, y1)); + return crate::tool_feedback::ellipse_points(r); + } + // As many vertices as the same ellipse would get drawn on screen (`ellipse_points`). + let scr = Rect::from_points(&[xf.to_screen(x0 as f32, y0 as f32), xf.to_screen(x1 as f32, y1 as f32)]); + let n = (((scr.width() + scr.height()) * 0.25) as usize).clamp(16, 256); + let (cx, cy, rx, ry) = ((x0 + x1) * 0.5, (y0 + y1) * 0.5, (x1 - x0) * 0.5, (y1 - y0) * 0.5); + (0..n) + .map(|i| { + let t = i as f64 / n as f64 * std::f64::consts::TAU; + at(cx + rx * t.cos(), cy + ry * t.sin()) + }) + .collect() +} + +/// The ants of the marquee being drawn: `marquee` when the drag has one (the options-bar style +/// and the modifiers applied), the raw press and pointer corners otherwise. This is the whole of +/// what the hinting draws for the selection tools, so the test in `marquee_tests` checks it +/// against the selection the release commits (#2512). +pub(crate) fn marquee_drag_ants(d: &Drag, xf: &ViewXform, marquee: Option<[f64; 4]>) -> Vec { + let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + let (a, b) = marquee.map_or((d.start, last), |[x0, y0, x1, y1]| ([x0, y0], [x1, y1])); + marquee_ants(xf, d.tool, a, b) +} + +/// The size readout shown beside the cursor while dragging a marquee: the width and height values. +pub fn marquee_readout(r: [f64; 4]) -> [String; 2] { + [format!("{} px", r[2] - r[0]), format!("{} px", r[3] - r[1])] +} + +/// [`marquee_readout`] in the Units & Rulers unit, as Photoshop shows it (cm when the rulers are in +/// centimeters), from the active document's resolution; pixels without a document. +pub fn size_readout(app: &PhotocraftApp, r: [f64; 4]) -> [String; 2] { + let Some(d) = app.session.active() else { return marquee_readout(r) }; + let (dpi, size) = (f64::from(d.doc.resolution_dpi), d.doc.size); + readout_in(&app.session.prefs().units_and_rulers, dpi, [size.width as f64, size.height as f64], r) +} + +/// `r`'s width and height formatted in `ur`'s ruler unit at `dpi` (percent of `extent`). +pub fn readout_in(ur: &photocraft_engine::prefs::UnitsAndRulers, dpi: f64, extent: [f64; 2], r: [f64; 4]) -> [String; 2] { + let s = ur.rulers.suffix(); + [format!("{} {s}", ur.format(r[2] - r[0], dpi, extent[0])), format!("{} {s}", ur.format(r[3] - r[1], dpi, extent[1]))] +} + +/// Draw the marquee size readout below-right of the cursor (kept on screen), like Photoshop's: +/// two rows, `W:` / `H:` labels on the left and the values right-aligned. +pub(super) fn draw_marquee_readout(app: &PhotocraftApp, ctx: &egui::Context, cursor: Pos2, values: [String; 2]) { + draw_value_readout(app, ctx, "marquee-readout", cursor, ["W:", "H:"], values); +} + +/// A turn of `deg` degrees as the readout beside the pointer shows it, to 0.1° in (-180, 180]. +/// Rounded first so a hair below zero never reads "-0.0°" and a hair above -180 reads "180.0°". +pub(crate) fn angle_readout(deg: f64) -> String { + let d = (deg * 10.0).round() / 10.0; + let d = if d == 0.0 { + 0.0 + } else if d == -180.0 { + 180.0 + } else { + d + }; + format!("{d:.1}°") +} + +/// A transformation-values readout beside the pointer (a marquee's or the crop frame's size, an +/// angle), unless Preferences › Tools › Show Transformation Values is off, as in Photoshop (#204). +/// The brush HUD isn't one: Show Transformation Values doesn't hide it, so it calls [`draw_readout`]. +pub(crate) fn draw_value_readout(app: &PhotocraftApp, ctx: &egui::Context, id: &str, cursor: Pos2, labels: [&str; N], values: [String; N]) { + if app.session.prefs().tools.show_transformation_values { + draw_readout(ctx, id, cursor, labels, values); + } +} + +/// A readout of `N` rows beside the pointer (labels left, values right-aligned), above everything. +pub(crate) fn draw_readout(ctx: &egui::Context, id: &str, cursor: Pos2, labels: [&str; N], values: [String; N]) { + let t = crate::theme::Tokens::get(ctx); + let font = egui::FontId::proportional(11.5); + let width = |text: &str| ctx.fonts_mut(|f| f.layout_no_wrap(text.to_owned(), font.clone(), t.text).size().x); + let labels = labels.map(|label| tl!(label)); + let (lw, vw) = (labels.map(width), values.each_ref().map(|v| width(v))); + let (label_col, value_col) = (lw.iter().fold(0.0f32, |a, &b| a.max(b)), vw.iter().fold(0.0f32, |a, &b| a.max(b))); + egui::Area::new(egui::Id::unique(id)).order(egui::Order::Tooltip).fixed_pos(cursor + vec2(16.0, 18.0)).interactable(false).constrain(true).show( + ctx, + |ui| { + egui::Frame::new() + .fill(t.card) + .stroke(Stroke::new(1.0, t.card_border)) + .corner_radius(t.radius_sm) + .inner_margin(egui::Margin::symmetric(7, 4)) + .show(ui, |ui| { + ui.spacing_mut().item_spacing = vec2(0.0, 1.0); + for (i, value) in values.into_iter().enumerate() { + // Labels left, values right-aligned on one edge, sharing a baseline. + ui.horizontal(|ui| { + ui.add(egui::Label::new(egui::RichText::new(labels[i]).font(font.clone()).color(t.text_dim)).extend()); + ui.add_space(label_col - lw[i] + 12.0 + value_col - vw[i]); + ui.add(egui::Label::new(egui::RichText::new(value).font(font.clone()).color(t.text)).extend()); + }); + } + }); + }, + ); +} diff --git a/crates/ui-egui/src/canvas/filter_preview.rs b/crates/ui-egui/src/canvas/filter_preview.rs new file mode 100644 index 0000000000..6940b7b720 --- /dev/null +++ b/crates/ui-egui/src/canvas/filter_preview.rs @@ -0,0 +1,308 @@ +use super::display::canvas_display; +use super::textures::texture_buffer; +use super::*; + +/// The proxy factor of a live preview of filter `cmd` with `params` on `doc`, the active document: +/// reduced on a large document (Preferences › Performance › Low Resolution Previews), except for +/// filters whose features don't scale with a proxy (#2063), and never coarser than the active view, +/// so at 100 % the preview shows every pixel instead of k-pixel blocks (#6326, as adjustment +/// previews have since #5764). Zoomed out, the proxy keeps previews of large documents fast. +/// +/// The in-dialog preview window ([`crate::filter_preview_ui`]) sizes its own textures from this +/// too, so the canvas and the window never disagree about the factor. +/// +/// Full resolution costs a whole filter per parameter change, which only the background worker +/// absorbs. The web build has no worker and computes the preview inline on the UI thread (#1676), +/// where that would freeze the page: there the document's proxy stands. The test and +/// `PHOTOCRAFT_INLINE_JOBS` inline paths keep the cap deliberately, because `background_jobs` is +/// flipped mid-session (a shell save during `actions.play`): a factor that followed it would change +/// [`crate::filter_dialog::FilterPreviewKey`] under a finished preview and recompute it inline, +/// the very stall this avoids. +pub(crate) fn filter_preview_factor(app: &PhotocraftApp, doc: &Document, cmd: &str, params: &serde_json::Value) -> u32 { + // A smart filter edit re-renders the whole stack: every stage constrains the factor. + let k = crate::filter_dialog::smart_preview_factor(doc, cmd, params, crate::proxy::preview_factor(doc, crate::proxy::reduced_previews(app))); + if cfg!(target_arch = "wasm32") { k } else { crate::proxy::view_factor(k, app.current_zoom()) } +} + +/// Live preview for an open filter dialog: run the filter on the proxy and upload it. With +/// background jobs (the desktop app) it computes on one background worker +/// (`filter_preview_worker`); otherwise (web, tests, `PHOTOCRAFT_INLINE_JOBS`) it keeps the +/// deterministic inline path (#1676), which also lets headless/CPU tests inspect previews +/// without a GPU texture. +pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &egui::Context) -> Option<(u32, u64, [u32; 2])> { + if let Some(held) = committed_filter_preview(app, idx) { + return held; + } + // Command dialogs always edit the active document. Never show their preview in another tab. + if app.session.active_index() != Some(idx) { + return None; + } + if crate::adjust_preview::on_layer(app, idx) { + return None; + } + let d = app.ui.dialogs.iter().find(|d| d.fields.contains_key("__filter"))?; + if d.fields.get("__preview").and_then(serde_json::Value::as_bool) != Some(true) { + return None; + } + let cmd = d.fields.get("__command")?.as_str()?.to_string(); + // Previews edit what the command will: a targeted layer mask included (#780). + let (cmd, mut params) = if d.fields.contains_key("__smartFilter") { + crate::smart_filter_dialog::edit_command(app, &d.fields).ok()? + } else { + (cmd.clone(), app.with_mask_target(&cmd, crate::filter_dialog::params_of(&d.fields))) + }; + // Select and Mask previews in its view mode; holding X shows the image without one. + if crate::select_mask_view::owns(&d.fields) { + if crate::select_mask_view::hides_view(&d.fields) { + return None; + } + params = crate::select_mask_view::request_params(&d.fields, params); + } + let st = app.session.documents().get(idx)?; + let k = filter_preview_factor(app, &st.doc, &cmd, ¶ms); + let request = crate::filter_dialog::FilterPreviewKey { + doc: st.doc.id, + revision: st.revision, + dialog: d.id, + active: st.active_layer, + target: st.channel_view.target, + command: cmd, + params, + k, + }; + let key = request.doc.0 ^ (1u64 << 61); + // Every filter's preview computes off the UI thread in the desktop app: Gaussian Blur at + // 1000 px takes long enough to freeze the window. Once the slider settles, a preview still + // running for an older value is cancelled. + #[cfg(not(target_arch = "wasm32"))] + if app.background_jobs { + app.filter_preview_worker.supersede(&request, crate::gpu_canvas::now_ms()); + if let Some((finished, computed)) = app.filter_preview_worker.poll() { + match computed { + // The dialog still holds these exact parameters. Publish as before, including an + // empty result: that is how a filter which no longer applies clears the canvas. + Ok(computed) if finished == request => publish_filter_preview(app, idx, finished, computed.result, computed.ms), + // Mid-drag, a frame for the value the pointer has just left is what makes the + // canvas follow the drag. Three things have to hold for it: it belongs to this + // preview, it has a frame to show (an empty one would blank a good preview), and + // it must not displace a frame that is already exact for the dialog, which is + // what a slider dragged out and back would otherwise make the canvas do. + Ok(computed) + if finished.same_target(&request) && computed.result.is_some() && !app.filter_preview.as_ref().is_some_and(|p| p.key == request) => + { + publish_filter_preview(app, idx, finished, computed.result, computed.ms); + } + Ok(_) => {} + // Errors stay on the exact request: a value the pointer has already dragged past + // must not raise a notice, and a still one will raise it when it is recomputed. + Err(error) if finished == request => { + app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: finished, result: None, committing: false }); + crate::notices::error(app, error); + } + Err(_) => {} + } + } + let fresh = app.filter_preview.as_ref().is_some_and(|p| p.key == request); + if !fresh && !app.filter_preview_worker.busy() { + let doc = app.session.documents().get(idx)?.doc.clone(); + let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); + let color = app.session.color.settings.clone(); + let task = request.clone(); + if let Err(error) = app.filter_preview_worker.start(request.clone(), ctx.clone(), move |cancel| { + let t0 = crate::gpu_canvas::now_ms(); + let result = crate::filter_dialog::preview_document_for_target( + &doc, + task.active, + &task.command, + &task.params, + task.k, + Some(cancel), + task.target, + &documents, + &color, + ) + .map(|doc| { + let buffer = photocraft_compose::flatten(&doc); + (std::sync::Arc::new(doc), buffer) + }); + crate::filter_preview_worker::Computed { result, ms: crate::gpu_canvas::now_ms() - t0 } + }) { + app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: request.clone(), result: None, committing: false }); + crate::notices::error(app, error); + } + } + if app.filter_preview_worker.busy() { + ctx.request_repaint_after(std::time::Duration::from_millis(16)); + } + let preview = app.filter_preview.as_ref()?; + // Keep the last preview during a drag, but never one from another source or dialog. + if !preview.key.same_target(&request) { + return None; + } + let result = preview.result.as_ref()?; + return Some((preview.key.k, key, [result.size.width, result.size.height])); + } + // Web and explicitly inline sessions keep the deterministic synchronous path (#1676): + // computed inline, uploaded when a GPU texture exists, still inspectable without one. + // Flattened once, as the background worker does; `publish_filter_preview` uploads it (#7490). + let _ = ctx; + if app.filter_preview.as_ref().is_none_or(|p| p.key != request) { + let doc = app.session.documents().get(idx)?.doc.clone(); + let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); + let t0 = crate::gpu_canvas::now_ms(); + let computed = crate::filter_dialog::preview_document_for_target( + &doc, + request.active, + &request.command, + &request.params, + request.k, + None, + request.target, + &documents, + &app.session.color.settings, + ) + .map(|doc| { + let buffer = photocraft_compose::flatten(&doc); + (std::sync::Arc::new(doc), buffer) + }); + publish_filter_preview(app, idx, request, computed, crate::gpu_canvas::now_ms() - t0); + } + let preview = app.filter_preview.as_ref()?; + let result = preview.result.as_ref()?; + Some((preview.key.k, key, [result.size.width, result.size.height])) +} + +/// Channel overlays must use the filter's current proxy too, including on the CPU canvas. +/// The cache key changes with the completed request; unchanged frames reuse the overlay texture. +pub(crate) fn filter_channel_preview(app: &mut PhotocraftApp, idx: usize, ctx: &egui::Context) -> Option<(std::sync::Arc, u64)> { + use std::hash::{Hash, Hasher}; + ensure_filter_preview(app, idx, ctx)?; + let preview = app.filter_preview.as_ref()?; + let doc = preview.result.as_ref()?.clone(); + let mut key = std::collections::hash_map::DefaultHasher::new(); + format!("{:?}", preview.key).hash(&mut key); + Some((doc, key.finish() | (1 << 59))) +} + +fn publish_filter_preview( + app: &mut PhotocraftApp, + idx: usize, + request: crate::filter_dialog::FilterPreviewKey, + computed: Option<(std::sync::Arc, photocraft_compose::Buffer)>, + ms: f64, +) { + let result = computed.and_then(|(result, buffer)| { + let t0 = crate::gpu_canvas::now_ms(); + let doc = app.session.documents().get(idx)?.doc.clone(); + // Shown through the preview's own colour management, as the result will be: Assign and + // Convert to Profile change the profile (and Convert the mode), not just the pixels. + let (display, _) = canvas_display(app, &result, None); + // A GPU texture is an optimisation: headless/CPU tests must still see the preview. + if let Some(gpu) = app.gpu.as_ref() { + gpu.upload_buffer_full(request.doc.0 ^ (1u64 << 61), &texture_buffer(display.as_deref(), &buffer), doc.depth); + } + app.perf.record("filter-preview", result.size.area(), ms, crate::gpu_canvas::now_ms() - t0); + Some(result) + }); + app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: request, result, committing: false }); +} + +/// The document whose colour management the canvas texture under `key` is shown through: a filter +/// preview's own result (it keeps the document's id, so Proof Colors still apply), else `doc`. +/// Assign Profile changes only the profile, so through `doc`'s its preview looked unchanged. +pub(super) fn filter_preview_display_doc(app: &PhotocraftApp, doc: &std::sync::Arc, key: u64) -> std::sync::Arc { + if key != doc.id.0 ^ (1u64 << 61) { + return doc.clone(); + } + app.filter_preview.as_ref().and_then(|p| p.result.clone()).filter(|r| r.id == doc.id).unwrap_or_else(|| doc.clone()) +} + +/// After a filter dialog's OK: `Some(shown)` while its preview stands in for the background job +/// that commits it (the document unchanged and the job still running, for this document's views), +/// `None` otherwise (other documents' views included). A job that lands, fails or is cancelled +/// drops it. +pub(crate) fn committed_filter_preview(app: &mut PhotocraftApp, idx: usize) -> Option> { + let p = app.filter_preview.as_ref().filter(|p| p.committing)?; + let st = app.session.documents().get(idx)?; + if st.doc.id != p.key.doc { + return None; + } + let size = p.result.as_ref().map(|r| [r.size.width, r.size.height]); + if let Some(size) = size + && st.revision == p.key.revision + && app.session.job_on(p.key.doc).is_some() + { + return Some(Some((p.key.k, p.key.doc.0 ^ (1u64 << 61), size))); + } + app.filter_preview = None; + Some(None) +} + +/// Zoomed-out Image › Adjustments preview on a large document: the wgpu compositor renders the +/// reduced preview document (`adjust_preview::gpu_proxy`) into its own texture, over the target's +/// area after the first frame. Returns (factor, gpu key, dimensions) to draw. +pub(super) fn ensure_adjust_proxy(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option<(u32, u64, [u32; 2])> { + let frame = crate::adjust_preview::gpu_proxy(app, idx, zoom)?; + let key = frame.doc.id.0; + let size = [frame.doc.size.width, frame.doc.size.height]; + let gpu = app.gpu.clone()?; + if frame.stale || !gpu.has(key, size) { + let doc = app.session.documents().get(idx)?.doc.clone(); + let (display, _) = canvas_display(app, &doc, None); + let r = gpu.refresh(key, &frame.doc, frame.damage, display.as_deref()); + app.perf.record(if r.kind.starts_with("gpu") { "gpu-adjust-proxy" } else { "adjust-proxy" }, r.px, r.composite_ms, r.upload_ms); + if let Some(t) = r.gpu { + app.perf.record_gpu(t); + } + crate::adjust_preview::proxy_drawn(app, &frame); + } + Some((frame.k, key, size)) +} + +/// If a live adjustment preview is active on a large document, composite it on the proxy and upload +/// it under its own GPU key. Returns (factor, gpu key, dimensions) when the proxy should be drawn. +/// `zoom` is the view's (physical screen pixels per document pixel). +pub(super) fn ensure_proxy_preview(app: &mut PhotocraftApp, idx: usize, zoom: f32) -> Option<(u32, u64, [u32; 2])> { + let (layer, params) = app.live_adjust.clone()?; + let (doc_id, revision, doc) = { + let st = app.session.documents().get(idx)?; + (st.doc.id, st.revision, st.doc.clone()) + }; + // Low-resolution previews off: k is 1 and the canvas shows `display_doc` (full size). + let mut k = crate::proxy::preview_factor(&doc, crate::proxy::reduced_previews(app)); + // Zoomed in, a proxy coarser than the screen showed the drag in k-pixel blocks (#5764): when + // the wgpu compositor draws the full-size document, use a proxy only as coarse as the screen + // (none at 50 % and closer). Otherwise the full size would be a CPU composite per change. + let fine = crate::proxy::view_factor(k, zoom); + if fine < k && app.gpu.as_ref().is_some_and(|g| g.supports(&doc)) { + k = fine; + } + if k <= 1 { + return None; + } + let fresh = matches!(&app.proxy, Some((d, r, kk, _)) if *d == doc_id && *r == revision && *kk == k); + if !fresh { + app.proxy = Some((doc_id, revision, k, std::sync::Arc::new(crate::proxy::proxy_document(&doc, k)))); + } + let proxy = app.proxy.as_ref()?.3.clone(); + let key = doc_id.0 ^ (1u64 << 62); + let hash = params.to_string().bytes().fold(k as u64, |h, b| h.wrapping_mul(31).wrapping_add(b as u64)); + if app.proxy_uploaded != Some((doc_id, hash)) { + let l = proxy.layer(layer)?; + let LayerContent::Adjustment(a) = &l.content else { return None }; + let kind = photocraft_engine::commands::adjustment_kind(a); + let preview = photocraft_engine::adjust_params::from_params(kind, ¶ms, Some(a), proxy.mode).unwrap_or_else(|_| a.clone()); + let mut p = (*proxy).clone(); + if let Some(lm) = p.layer_mut(layer) { + lm.content = LayerContent::Adjustment(preview); + } + let t0 = crate::gpu_canvas::now_ms(); + let buf = photocraft_compose::flatten(&p); + let t1 = crate::gpu_canvas::now_ms(); + let (display, _) = canvas_display(app, &doc, None); + app.gpu.as_ref()?.upload_buffer_full(key, &texture_buffer(display.as_deref(), &buf), doc.depth); + app.perf.record("proxy", p.size.area(), t1 - t0, crate::gpu_canvas::now_ms() - t1); + app.proxy_uploaded = Some((doc_id, hash)); + } + Some((k, key, [proxy.size.width, proxy.size.height])) +} diff --git a/crates/ui-egui/src/canvas/gesture.rs b/crates/ui-egui/src/canvas/gesture.rs new file mode 100644 index 0000000000..81c0b231a4 --- /dev/null +++ b/crates/ui-egui/src/canvas/gesture.rs @@ -0,0 +1,286 @@ +use super::drag::{Drag, marquee_preview_px, single_line_drag_px}; +use super::selection::finish_selection_drag; +use super::strokes::{ + EngineStroke, commit_brush_stroke, feed_live_stroke, live_retouch_command, offer_live_retouch, paint_target, snap_aliased_tip, stroke_params, +}; +use super::textures::shown_as_document; +use super::*; + +pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) { + // Control can select a different tool and release before the next frame cancels the drag. + // Cancel before even recording a Shift-stroke anchor, including the preview fallback paths. + if d.tool == Tool::MixerBrush && app.ui.tool != Tool::MixerBrush { + app.live_stroke = None; + return; + } + let mut end = d.points.last().copied().unwrap_or([d.start[0], d.start[1], 1.0]); + let (sx, sy) = snap_aliased_tip(app, d.tool, end[0], end[1]); + end[0] = sx; + end[1] = sy; + if let Some(floating) = d.sel_move { + finish_selection_drag(app, floating, d.start, [end[0], end[1]]); + return; + } + // Where the next ⇧-click line starts. + if crate::stroke_constraint::connects(d.tool) + && let Some(st) = app.session.active() + { + app.last_stroke_end = Some((st.doc.id, end)); + } + if d.tool == Tool::MixerBrush { + // The release can carry a new endpoint, including moves deferred in this frame. + // Feed those samples before offering the already-rendered document for commit. + app.drag = Some(d); + let deferred = std::mem::replace(&mut app.defer_live_stroke, false); + feed_live_stroke(app); + app.defer_live_stroke = deferred; + let Some(d) = app.drag.take() else { return }; + let live = app.live_stroke.take(); + if let Some(l) = live { + let (doc, key, steps) = (l.doc, l.key, l.damage.len() as u64); + if let EngineStroke::Mixer(mixer) = l.stroke { + if l.preview_failed { + let mut p = stroke_params(app, &d, &app.stylus.stroke_points(&d.points)); + p["seed"] = json!(mixer.seed); + drop(mixer); + let _ = app.run("paint.mixerBrush", p); + return; + } + match mixer.prepare_commit(&mut app.session) { + Ok(p) => { + if app.run("paint.mixerBrush", p).is_ok() { + shown_as_document(app, doc, |k| k == 0 || (key..=key + steps).contains(&k)); + } + } + Err(e) => { + app.ui.status = e.to_string(); + app.ui.status_error = true; + } + } + } + } else { + // No preview (a tip above its size): render the whole stroke now. + let p = stroke_params(app, &d, &app.stylus.stroke_points(&d.points)); + let _ = app.run("paint.mixerBrush", p); + } + return; + } + // A live retouching preview ends here; the commit below replaces it (the Clone Stamp's, + // History Brush's and sequential-dab tools' with the pixels it already drew). + offer_live_retouch(app, &d); + if live_retouch_command(d.tool).is_some() || crate::retouch_ui::dab_params(app, d.tool).is_some() || d.tool == Tool::ColorReplacement { + app.live_stroke = None; + } + let finished = crate::eraser_ui::finish_stroke(app, d.tool, &d.points) || crate::retouch_ui::finish_stroke(app, d.tool, &d.points, d.modifiers); + app.session.clear_live_stroke(); + if finished { + return; + } + match d.tool { + Tool::ObjectSelection => crate::retouch_ui::finish_object_selection(app, d.start, [end[0], end[1]], d.modifiers), + Tool::FreeformPen => crate::vector_ui::freeform_finish(app, &d.points, d.lasso.as_ref().map_or(&[], |l| l.straight())), + // Photoshop: a click without dragging opens Create Rectangle / Ellipse / … instead. + t if crate::vector_ui::is_shape_tool(t) + && crate::shape_dialog::is_click(d.start, &d.points, app.point_zoom()) + && crate::shape_dialog::open(app, t, d.start).is_some() => {} + t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::finish_shape(app, t, d.start, [end[0], end[1]], d.live), + Tool::PathSelection => crate::vector_ui::path_selection_finish(app, d.start, [end[0], end[1]]), + Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::pointer_up(app, d.start, [end[0], end[1]]), + Tool::Brush | Tool::Pencil | Tool::Eraser => commit_brush_stroke(app, &d), + Tool::RectMarquee | Tool::EllipseMarquee => { + // Exactly what the drag showed (`marquee_preview_px`); a click deselects. + let Some([x0, y0, x1, y1]) = marquee_preview_px(&app.ui.tool_options, &d, app.point_zoom()) else { + if app.session.is_enabled("select.deselect") { + let _ = app.run("select.deselect", json!({})); + } + return; + }; + let mode = selection_mode(app, d.modifiers); + let (aa, feather) = (app.ui.tool_options.anti_alias, app.ui.tool_options.feather); + let _ = app.run("select.rect", json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0, "mode": mode, "ellipse": d.tool == Tool::EllipseMarquee, "antiAlias": aa, "feather": feather})); + } + // A click (or the end of a drag) selects the line under the pointer, never deselects. + Tool::SingleRowMarquee | Tool::SingleColumnMarquee => { + let Some([x0, y0, x1, y1]) = single_line_drag_px(app, &d) else { return }; + let mode = selection_mode(app, d.modifiers); + let feather = app.ui.tool_options.feather; + // `line` names the History step after the tool (Single Row / Single Column Marquee). + let line = if d.tool == Tool::SingleRowMarquee { "row" } else { "column" }; + let _ = app.run( + "select.rect", + 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::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(); + 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})); + // 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); + } + } else if app.session.is_enabled("select.deselect") { + let _ = app.run("select.deselect", json!({})); + } + } + Tool::Gradient if (end[0] - d.start[0]).abs() + (end[1] - d.start[1]).abs() >= 2.0 => { + let o = app.ui.tool_options.clone(); + let _ = app.run( + "paint.gradient", + json!({"from": [d.start[0], d.start[1]], "to": [end[0], end[1]], "style": o.gradient_style, "reverse": o.gradient_reverse, "dither": o.gradient_dither, "opacity": o.fill_opacity, "mode": o.gradient_blend_mode.label(), "target": paint_target(app)}), + ); + } + Tool::Move => { + let (dx, dy) = ((end[0] - d.start[0]).round(), (end[1] - d.start[1]).round()); + crate::move_ui::finish(app, dx, dy); + } + _ => {} + } +} + +/// Selection mode from the options bar, overridden by modifier keys (⇧ add, ⌥ subtract, ⇧⌥ intersect). +/// The cursor badge announces the same mode (`tool_feedback`). +pub(crate) fn selection_mode(app: &PhotocraftApp, m: egui::Modifiers) -> &'static str { + crate::tool_feedback::document_selection_mode(app, Tool::Lasso, m) +} + +/// Shift constrains a Polygonal Lasso segment to Photoshop's 45° directions. +/// Work in document coordinates so zoom, view rotation and mirroring cannot skew it. +pub(crate) fn constrained_polygon_point(from: [f64; 2], point: [f64; 2]) -> [f64; 2] { + let dx = point[0] - from[0]; + let dy = point[1] - from[1]; + if !dx.is_finite() || !dy.is_finite() { + return point; + } + let length = dx.hypot(dy); + if length == 0.0 { + return point; + } + let angle = (dy.atan2(dx) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4; + [from[0] + length * angle.cos(), from[1] + length * angle.sin()] +} + +/// A polygonal lasso click adds a vertex; clicking near the first vertex closes the polygon. The +/// first click fixes the selection mode; a new-selection polygon hides the old outline while it is +/// drawn, and replaces it in one history step when it closes. +pub(super) fn polygon_click(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { + let close = app + .ui + .polygon + .first() + .is_some_and(|p0| app.ui.polygon.len() >= 3 && ((p0[0] - x).powi(2) + (p0[1] - y).powi(2)).sqrt() < 8.0 / app.point_zoom().max(0.01) as f64); + if close { + commit_polygon(app); + return; + } + if app.ui.polygon.is_empty() { + app.ui.polygon_doc = app.session.active().map(|st| st.doc.id); + // ⌥ with nothing selected draws freehand; there is nothing to subtract from. + let nothing_selected = app.session.active().is_none_or(|st| st.doc.selection.is_none()); + let intent = if nothing_selected { egui::Modifiers { alt: false, ..mods } } else { mods }; + app.ui.polygon_mode = selection_mode(app, intent).into(); + } + // Only constrain segments after the first vertex; the first click still sets selection intent. + // Alt-drag is freehand and must not snap to an angle. + let point = if mods.shift && !mods.alt { app.ui.polygon.last().copied().map_or([x, y], |last| constrained_polygon_point(last, [x, y])) } else { [x, y] }; + app.ui.polygon.push(point); +} + +/// Remove the Polygonal Lasso's last vertex (⌫, Delete or a right-click while drawing, #1229); +/// removing the only one cancels the polygon. False when no polygon is being drawn. +pub fn polygon_retract(app: &mut PhotocraftApp) -> bool { + if app.ui.polygon.pop().is_none() { + return false; + } + if app.ui.polygon.is_empty() { + app.ui.polygon_mode.clear(); + } + true +} + +/// The polygon in progress belongs to the document it was started on (`UiState::polygon_doc`): +/// once another document becomes active it is dropped, so its outline doesn't show on (or get +/// committed to) the other document, and the selection it would have replaced is shown again. +/// Switching tools is handled in `PhotocraftApp::sync_views`. Like the Lasso's +/// ([`crate::lasso_ui::cancel_stale`]) and the Magnetic Lasso's ([`crate::magnetic_lasso_ui::frame`]). +pub fn polygon_cancel_stale(app: &mut PhotocraftApp) { + let active = app.session.active().map(|st| st.doc.id); + if app.ui.polygon.is_empty() { + app.ui.polygon_doc = None; + } else if app.ui.polygon_doc.is_some_and(|d| Some(d) != active) { + app.ui.polygon.clear(); + app.ui.polygon_mode.clear(); + app.ui.polygon_doc = None; + } +} + +/// A new-selection polygonal (or magnetic) lasso is being drawn, so the selection it will replace +/// is hidden. +pub fn polygon_replaces_selection(app: &PhotocraftApp) -> bool { + (!app.ui.polygon.is_empty() && app.ui.polygon_mode == "replace") || crate::magnetic_lasso_ui::replaces_selection(app) +} + +/// Close the polygonal lasso and make the selection in the mode it started in. +pub fn commit_polygon(app: &mut PhotocraftApp) { + let pts = std::mem::take(&mut app.ui.polygon); + let mode = std::mem::take(&mut app.ui.polygon_mode); + if pts.len() >= 3 { + let mode = if mode.is_empty() { selection_mode(app, egui::Modifiers::NONE).to_owned() } else { mode }; + let o = &app.ui.tool_options; + let _ = app.run("select.lasso", json!({"points": pts, "mode": mode, "antiAlias": o.anti_alias, "feather": o.feather})); + } +} + +/// Apply the crop tool's rectangle. When `image.crop` refuses it (the error is in the status bar), +/// the frame, its turn and its box Undo stay for fixing. +pub fn commit_crop(app: &mut PhotocraftApp) { + // Never another document's frame (#1918). + crate::crop_ui::cancel_stale(app); + let kept = crate::crop_ui::keep(app); + // Committing ends the box's own Undo/Redo: from here Edit › Undo reverts the document. + crate::crop_ui::clear_history(app); + // ↵ during a drag ends it: the release must not bring back the old document's frame. + app.crop.drag = None; + let Some(r) = app.ui.crop_rect.take() else { return }; + // The crop's default mode leaves the view upright (`crop_mode`). + crate::crop_mode::upright(app); + // The untouched default frame around the whole canvas crops nothing (Photoshop's ↵ on it does + // nothing); one framing the selection's bounds crops to them (#1789). + if std::mem::take(&mut app.crop.default_frame) { + let whole = app.session.active().map(|st| st.doc.bounds()).map(|b| [f64::from(b.x0), f64::from(b.y0), f64::from(b.x1), f64::from(b.y1)]); + if whole.is_none_or(|b| b == r) { + return; + } + } + let (x, y) = (r[0].round(), r[1].round()); + let (w, h) = ((r[2] - r[0]).round().max(1.0), (r[3] - r[1]).round().max(1.0)); + let delete = app.ui.tool_options.crop_delete; + let mut p = json!({"x": x, "y": y, "width": w, "height": h, "deleteCroppedPixels": delete}); + // Fill › Content-Aware Fill (#3823): what a turned or extending frame uncovers is filled from + // its surroundings instead of the background colour. + if app.ui.tool_options.crop_content_aware { + p["contentAware"] = json!(true); + } + // A turned frame (#1792): the document turns with it, then is cropped to it. (The untouched + // default frame above is never turned: turning it makes it a real frame.) + let angle = crate::crop_ui::angle(app); + app.ui.crop_angle = 0.0; + if angle != 0.0 { + p["angle"] = json!(angle); + } + // W x H x Resolution (#2443): resample to that size and set the resolution. + crate::crop_size::commit_params(app, &mut p); + if app.run("image.crop", p).is_err() { + crate::crop_ui::restore(app, kept); + } else if let Some(i) = app.session.active_index() { + app.ui.views[i].fit_pending = true; + } +} diff --git a/crates/ui-egui/src/canvas/navigator.rs b/crates/ui-egui/src/canvas/navigator.rs new file mode 100644 index 0000000000..d95c9a20ec --- /dev/null +++ b/crates/ui-egui/src/canvas/navigator.rs @@ -0,0 +1,138 @@ +use super::display::{canvas_display, display_doc, display_image}; +use super::strokes::live_stroke; +use super::textures::{effect_reach, ensure_texture}; +use super::*; + +/// Longest side of the Navigator panel's image (about twice the panel's width, for HiDPI). +pub const NAVIGATOR_SIDE: u32 = 512; + +/// The navigator image of a document: its snapshot, preview key and revision, and the texture. +pub(crate) type NavigatorCache = (std::sync::Weak, u64, u64, egui::TextureHandle); + +/// How long adjustment-dialog settings must stay unchanged before the navigator shows them. +const NAVIGATOR_SETTLE_MS: f64 = 200.0; + +/// While a Move or Patch drag or a live paint stroke is under way, the navigator keeps its image +/// of document `idx` and catches up on release: each step of the drag is a new preview, and a +/// thumbnail composite of the whole document per step makes painting lag on large images. +pub(super) fn navigator_waits_for_drag(app: &PhotocraftApp, idx: usize) -> bool { + crate::move_ui::showing(app) || crate::patch_preview::showing(app) || crate::cam_preview::showing(app) || live_stroke(app, idx).is_some() +} + +/// The Navigator panel's image of document `idx`. With the CPU canvas that is the canvas texture +/// itself; with the GPU canvas a thumbnail cached per revision, so an edit to a huge document +/// doesn't also pay a full-resolution CPU composite for the navigator. +/// The Navigator's preview from the GPU canvas (#4518): the main canvas's texture of the +/// document, drawn at `rect` with its own mip chain, so an edit costs no CPU composite. `None` +/// while the canvas isn't showing the plain document on the GPU (the CPU thumbnail then). +pub fn navigator_gpu_view(app: &PhotocraftApp, idx: usize, rect: Rect, ctx: &egui::Context) -> Option { + app.gpu.as_ref()?; + let st = app.session.documents().get(idx)?; + let params = *app.navigator_gpu.get(&st.doc.id)?; + let [w, h] = params.doc_size; + if w == 0 || h == 0 || !rect.is_positive() || [st.doc.size.width, st.doc.size.height] != params.doc_size { + return None; + } + Some(crate::gpu_canvas::ViewParams { + zoom: rect.width() / w as f32, + center: [w as f32 / 2.0, h as f32 / 2.0], + rotation: 0.0, + shadow: false, + pixel_grid: false, + view_key: egui::Id::unique(("pc-navigator", ctx.viewport_id(), idx)).value(), + offset: [0.0, 0.0], + ..params + }) +} + +/// Frames the Navigator waits for the GPU canvas to draw a document it hasn't drawn yet, rather +/// than build a CPU thumbnail it would only use once (a full composite on a large document). +const NAVIGATOR_WAIT_FRAMES: u32 = 3; + +/// Whether the Navigator should wait a frame for the GPU canvas (#4518): the GPU canvas is on but +/// hasn't drawn document `idx` yet (the Navigator can draw before the canvas in a frame). After +/// [`NAVIGATOR_WAIT_FRAMES`] it stops waiting, so it never stays empty. +pub fn navigator_waits_for_gpu(app: &PhotocraftApp, idx: usize, ctx: &egui::Context) -> bool { + if app.gpu.is_none() { + return false; + } + let Some(id) = app.session.documents().get(idx).map(|st| st.doc.id) else { return false }; + if app.canvases.keys().any(|(d, _)| *d == id) { + return false; + } + let key = egui::Id::unique(("navigator-waits", id.0)); + let waited = ctx.data(|d| d.get_temp::(key)).unwrap_or(0); + if waited >= NAVIGATOR_WAIT_FRAMES { + return false; + } + ctx.data_mut(|d| d.insert_temp(key, waited + 1)); + ctx.request_repaint(); + true +} + +pub fn navigator_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize) -> Option { + if app.gpu.is_none() { + 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 (doc, preview_key) = display_doc(app, idx); + let (display, display_key) = canvas_display(app, &doc, None); + let preview_key = preview_key ^ display_key; + let cached = app.navigator_textures.get(&id).cloned(); + if let Some((r, p, _, t)) = &cached + && r.ptr_eq(&snapshot) + && *p == preview_key + { + return Some(t.id()); + } + if let Some((_, _, _, t)) = &cached + && navigator_waits_for_drag(app, idx) + { + return Some(t.id()); + } + // While an adjustment dialog's settings are changing, the navigator keeps its image and + // catches up once they settle (a thumbnail composite per change would cost more than the canvas). + if let Some((r, _, _, t)) = &cached + && r.ptr_eq(&snapshot) + && crate::adjust_preview::settling(app, NAVIGATOR_SETTLE_MS) + { + ctx.request_repaint_after(std::time::Duration::from_millis(NAVIGATOR_SETTLE_MS as u64)); + 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 + // 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) + && let Some(d) = last_damage + && t.size() == [size.0 as usize, size.1 as usize] + { + let mut t = t.clone(); + if !d.is_empty() { + let buf = photocraft_compose::render_reduced_damage(&doc, size.0, size.1, d.inflate(effect_reach(&doc.layers))); + let r = buf.rect; + if !r.is_empty() { + t.set_partial([r.x0 as usize, r.y0 as usize], display_image(display.as_deref(), &buf), TextureOptions::LINEAR); + } + } + app.perf.span("navigator", crate::gpu_canvas::now_ms() - t0); + app.navigator_textures.insert(id, (snapshot, preview_key, revision, t.clone())); + return Some(t.id()); + } + let image = display_image(display.as_deref(), &photocraft_compose::thumbnail_buffer(&doc, NAVIGATOR_SIDE)); + let tex = match cached { + Some((_, _, _, mut t)) => { + t.set(image, TextureOptions::LINEAR); + t + } + None => ctx.load_texture(format!("navigator-{}", id.0), image, TextureOptions::LINEAR), + }; + app.perf.span("navigator", crate::gpu_canvas::now_ms() - t0); + app.navigator_textures.insert(id, (snapshot, preview_key, revision, tex.clone())); + Some(tex.id()) +} diff --git a/crates/ui-egui/src/canvas/paint.rs b/crates/ui-egui/src/canvas/paint.rs new file mode 100644 index 0000000000..bcec552b4d --- /dev/null +++ b/crates/ui-egui/src/canvas/paint.rs @@ -0,0 +1,610 @@ +use super::display::{canvas_display, checker, display_doc, display_image}; +use super::drag::{ + angle_readout, draw_marquee_readout, draw_value_readout, marquee_ants, marquee_drag_ants, marquee_preview_px, single_line_drag_px, size_readout, +}; +use super::gesture::constrained_polygon_point; +use super::strokes::{EngineStroke, SPOT_HEALING_TRAIL, draw_smoothing_string, strokes_live}; +use super::textures::texture_side; +use super::view_xform::ViewXform; +use super::*; + +/// A texture mapped over the `size` document area starting at `origin` (follows a rotated view). +pub(super) fn paint_mapped_image_at(painter: &egui::Painter, xf: &ViewXform, tex: egui::TextureId, uv: Rect, origin: [f32; 2], size: [f32; 2], tint: Color32) { + let ([x, y], [w, h]) = (origin, size); + let pts = [xf.to_screen(x, y), xf.to_screen(x + w, y), xf.to_screen(x + w, y + h), xf.to_screen(x, y + h)]; + let uvs = [uv.min, pos2(uv.max.x, uv.min.y), uv.max, pos2(uv.min.x, uv.max.y)]; + let mut mesh = Mesh::with_texture(tex); + for i in 0..4 { + mesh.vertices.push(egui::epaint::Vertex { pos: pts[i], uv: uvs[i], color: tint }); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(egui::Shape::mesh(mesh)); +} + +/// The GPU canvas view, then its View › Pattern Preview copies (#1067): the same texture drawn +/// again whole document sizes away, each with its own view uniform and no shadow. +pub(super) fn paint_gpu_view(painter: &egui::Painter, rect: Rect, params: crate::gpu_canvas::ViewParams, copies: &[[i32; 2]]) { + crate::gpu_canvas::GpuCanvas::paint(painter, rect, params); + for (k, &c) in copies.iter().enumerate() { + let copy = crate::gpu_canvas::ViewParams { + offset: crate::pattern_preview::offset(c, params.doc_size), + shadow: false, + // Keyed by slot, not by tile index, so panning reuses the same few uniform buffers. + view_key: egui::Id::unique((params.view_key, "pattern", k)).value(), + ..params + }; + crate::gpu_canvas::GpuCanvas::paint(painter, rect, copy); + } +} + +/// The mapping that draws Pattern Preview copy `c` of a `size` document where it sits next to +/// the document: the same view, looking the matching number of document sizes back. +pub(super) fn pattern_xf(xf: &ViewXform, c: [i32; 2], size: [u32; 2]) -> ViewXform { + let [ox, oy] = crate::pattern_preview::offset(c, size); + ViewXform { center: [xf.center[0] - ox, xf.center[1] - oy], ..*xf } +} + +/// CPU canvas: the transparency checkerboard (or white) and the display texture, for the +/// document or one of its Pattern Preview copies (`xf` from [`pattern_xf`]). +pub(super) fn paint_cpu_document( + painter: &egui::Painter, + xf: &ViewXform, + bounds: DRect, + rotated: bool, + checker: Option<(egui::TextureId, f32)>, + tex: Option, + opaque: bool, +) { + let size = [bounds.width() as f32, bounds.height() as f32]; + let origin = [bounds.x0 as f32, bounds.y0 as f32]; + let img_rect = xf.doc_rect(bounds); + match checker { + Some((checker_id, square)) if !opaque || tex.is_none() => { + if rotated { + let tiles = vec2(size[0], size[1]) / (2.0 * square); + paint_mapped_image_at(painter, xf, checker_id, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), origin, size, Color32::WHITE); + } else { + let tiles = img_rect.size() / (2.0 * square); + painter.image(checker_id, img_rect, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), Color32::WHITE); + } + } + // On software window adapters this hidden full-canvas pass is CPU rasterization too. + // Keep the white-background branch unchanged (its antialiased outer edge is visible). + Some(_) => {} + None => { + if rotated { + paint_mapped_quad(painter, xf, origin, size, Color32::WHITE); + } else { + painter.rect_filled(img_rect, 0.0, Color32::WHITE); + } + } + } + if let Some(tex) = tex { + if rotated { + paint_mapped_image_at(painter, xf, tex, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), origin, size, Color32::WHITE); + } else { + let uv = if xf.flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) }; + painter.image(tex, img_rect, uv, Color32::WHITE); + } + } +} + +/// [`ensure_texture_in_view`]'s detail texture over document area `area` (x0, y0, x1, y1), on its +/// own checkerboard (or white), so the reduced texture under it doesn't show through where the +/// image is transparent. The checkerboard keeps [`paint_cpu_document`]'s phase. +pub(super) fn paint_cpu_detail( + painter: &egui::Painter, + xf: &ViewXform, + bounds: DRect, + rotated: bool, + checker: Option<(egui::TextureId, f32)>, + tex: egui::TextureId, + area: [f32; 4], +) { + let [x0, y0, x1, y1] = area; + let corners = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]]; + let pts = corners.map(|[x, y]| xf.to_screen(x, y)); + let quad = |tex: egui::TextureId, uvs: [Pos2; 4]| { + let mut mesh = Mesh::with_texture(tex); + for (pos, uv) in pts.into_iter().zip(uvs) { + mesh.vertices.push(egui::epaint::Vertex { pos, uv, color: Color32::WHITE }); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(egui::Shape::mesh(mesh)); + }; + match checker { + Some((checker_id, square)) => { + let tile = 2.0 * square; + let uvs = if rotated { + corners.map(|[x, y]| pos2(x / tile, y / tile)) + } else { + let min = xf.doc_rect(bounds).min; + pts.map(|p| ((p - min) / tile).to_pos2()) + }; + quad(checker_id, uvs); + } + None => { + painter.add(egui::Shape::convex_polygon(pts.to_vec(), Color32::WHITE, Stroke::NONE)); + } + } + quad(tex, [pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)]); +} + +fn paint_mapped_quad(painter: &egui::Painter, xf: &ViewXform, origin: [f32; 2], size: [f32; 2], color: Color32) { + let ([x, y], [w, h]) = (origin, size); + let pts = vec![xf.to_screen(x, y), xf.to_screen(x + w, y), xf.to_screen(x + w, y + h), xf.to_screen(x, y + h)]; + painter.add(egui::Shape::convex_polygon(pts, color, Stroke::NONE)); +} + +/// Draw boundary segments as marching ants: white base, black dashes phased along x + y. +pub(super) fn marching_ants_segments(painter: &egui::Painter, xf: &ViewXform, segs: &[crate::outline::Segment], time: f64) { + marching_ants_mapped(painter, segs, time, |p| xf.to_screen(p[0] as f32, p[1] as f32)); +} + +/// [`marching_ants_segments`] with each outline point placed on screen by `to_screen` (a +/// transformed outline: Content-Aware Move's Transform On Drop). +pub(crate) fn marching_ants_mapped(painter: &egui::Painter, segs: &[crate::outline::Segment], time: f64, to_screen: impl Fn([i32; 2]) -> Pos2) { + marching_ants_lines(painter, segs.iter().map(|(a, b)| (to_screen(*a), to_screen(*b))), time); +} + +/// The part of the line `a`–`b` inside `r` (Liang–Barsky), if any. +pub(crate) fn clip_line(r: Rect, a: Pos2, b: Pos2) -> Option<(Pos2, Pos2)> { + // Perspective can put endpoints billions of pixels away. f32 subtraction/interpolation + // loses viewport-sized differences there, clipping visible ants to the wrong endpoints. + let (ax, ay) = (f64::from(a.x), f64::from(a.y)); + let (dx, dy) = (f64::from(b.x) - ax, f64::from(b.y) - ay); + let (mut t0, mut t1) = (0.0f64, 1.0f64); + for (p, q) in [(-dx, ax - f64::from(r.min.x)), (dx, f64::from(r.max.x) - ax), (-dy, ay - f64::from(r.min.y)), (dy, f64::from(r.max.y) - ay)] { + if p == 0.0 { + if q < 0.0 { + return None; + } + } else if p < 0.0 { + t0 = t0.max(q / p); + } else { + t1 = t1.min(q / p); + } + } + let at = |t: f64| pos2((ax + dx * t) as f32, (ay + dy * t) as f32); + (t0 <= t1).then(|| (at(t0), at(t1))) +} + +/// Marching ants along lines already placed on screen (a warped outline is a run of short ones), +/// in device pixels like Photoshop's (`crate::ants`, #7489). +pub(crate) fn marching_ants_lines(painter: &egui::Painter, lines: impl Iterator, time: f64) { + crate::ants::draw(painter, lines, time, true); +} + +/// Photoshop crop overlay: the `shield` outside (`crop_shield::fill`; none when disabled), bright +/// frame, the composition `guides` (unit-square polylines, `crop_overlay::guides`), corner and +/// edge handles. +fn crop_overlay(painter: &egui::Painter, r: Rect, shield: Option, guides: &[crate::crop_overlay::Polyline]) { + let clip = painter.clip_rect(); + if let Some(dim) = shield { + for band in [ + Rect::from_min_max(clip.min, egui::pos2(clip.max.x, r.min.y)), + Rect::from_min_max(egui::pos2(clip.min.x, r.max.y), clip.max), + Rect::from_min_max(egui::pos2(clip.min.x, r.min.y), egui::pos2(r.min.x, r.max.y)), + Rect::from_min_max(egui::pos2(r.max.x, r.min.y), egui::pos2(clip.max.x, r.max.y)), + ] { + painter.rect_filled(band, 0.0, dim); + } + } + painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Middle); + draw_crop_guides(painter, guides, |a, b| r.min + r.size() * vec2(a, b)); + let h = Stroke::new(3.0, Color32::WHITE); + let l = 14.0f32.min(r.width() / 3.0).min(r.height() / 3.0); + for (c, dx, dy) in [(r.left_top(), 1.0, 1.0), (r.right_top(), -1.0, 1.0), (r.left_bottom(), 1.0, -1.0), (r.right_bottom(), -1.0, -1.0)] { + painter.line_segment([c, c + vec2(l * dx, 0.0)], h); + painter.line_segment([c, c + vec2(0.0, l * dy)], h); + } + // Edge handles: short bars at the middle of each side. + let (lx, ly) = (l.min(r.width() / 4.0) / 2.0, l.min(r.height() / 4.0) / 2.0); + for (c, horizontal) in [(r.center_top(), true), (r.center_bottom(), true), (r.left_center(), false), (r.right_center(), false)] { + let e = if horizontal { vec2(lx, 0.0) } else { vec2(0.0, ly) }; + painter.line_segment([c - e, c + e], h); + } +} + +/// [`crop_overlay`] for a turned frame (or a rotated view): `q` is the frame's top-left, top-right, +/// bottom-right and bottom-left corner on screen, a parallelogram. +fn crop_overlay_turned(painter: &egui::Painter, q: [Pos2; 4], shield: Option, guides: &[crate::crop_overlay::Polyline]) { + let (u, v) = (q[1] - q[0], q[3] - q[0]); + let (lu, lv) = (u.length(), v.length()); + if !(lu.is_finite() && lv.is_finite()) || lu < 1e-3 || lv < 1e-3 { + return; + } + let at = |a: f32, b: f32| q[0] + u * a + v * b; + // The shield: four trapezoids from the frame out to the frame grown past the whole view. + let clip = painter.clip_rect(); + let reach = clip.size().length() + (clip.center() - at(0.5, 0.5)).length(); + let (eu, ev) = (reach / lu, reach / lv); + let outer = [at(-eu, -ev), at(1.0 + eu, -ev), at(1.0 + eu, 1.0 + ev), at(-eu, 1.0 + ev)]; + if let Some(dim) = shield { + let mut mesh = egui::Mesh::default(); + for p in q.iter().chain(outer.iter()) { + mesh.colored_vertex(*p, dim); + } + for i in 0..4u32 { + let j = (i + 1) % 4; + mesh.add_triangle(i, j, 4 + j); + mesh.add_triangle(i, 4 + j, 4 + i); + } + painter.add(egui::Shape::mesh(mesh)); + } + painter.add(egui::Shape::closed_line(q.to_vec(), Stroke::new(1.0, Color32::WHITE))); + draw_crop_guides(painter, guides, at); + let h = Stroke::new(3.0, Color32::WHITE); + let l = 14.0f32.min(lu / 3.0).min(lv / 3.0); + let (du, dv) = (u / lu, v / lv); + for (c, su, sv) in [(q[0], 1.0, 1.0), (q[1], -1.0, 1.0), (q[3], 1.0, -1.0), (q[2], -1.0, -1.0)] { + painter.line_segment([c, c + du * (l * su)], h); + painter.line_segment([c, c + dv * (l * sv)], h); + } + // Edge handles: short bars at the middle of each side, along it. + let (lx, ly) = (l.min(lu / 4.0) / 2.0, l.min(lv / 4.0) / 2.0); + for (c, e) in [(at(0.5, 0.0), du * lx), (at(0.5, 1.0), du * lx), (at(0.0, 0.5), dv * ly), (at(1.0, 0.5), dv * ly)] { + painter.line_segment([c - e, c + e], h); + } +} + +/// The crop overlay's guides, each unit-square point placed on screen by `at`. +fn draw_crop_guides(painter: &egui::Painter, guides: &[crate::crop_overlay::Polyline], at: impl Fn(f32, f32) -> Pos2) { + let thin = Stroke::new(1.0, Color32::from_white_alpha(90)); + for l in guides { + painter.add(egui::Shape::line(l.iter().map(|p| at(p[0], p[1])).collect(), thin)); + } +} + +/// What the Crop tool shows past the canvas, cached per document state ([`draw_beyond_canvas`]). +#[derive(Clone)] +struct BeyondCanvas { + snapshot: std::sync::Weak, + key: u64, + /// Every layer's pixels and the canvas (`extra_cmds::reveal_all_bounds`). + extent: DRect, + /// The composite around the canvas: each band, the area its texture covers, the texture. + bands: Vec<(DRect, DRect, egui::TextureHandle)>, +} + +/// Band `r` around the canvas `c` (on screen) pushed a point under the canvas's edge, so that the +/// edge's anti-aliased pixels blend with the band rather than with the pasteboard. +fn under_canvas(mut r: Rect, c: Rect) -> Rect { + let near = |a: f32, b: f32| (a - b).abs() < 0.01; + if near(r.max.y, c.min.y) { + r.max.y += 1.0; + } + if near(r.min.y, c.max.y) { + r.min.y -= 1.0; + } + if near(r.max.x, c.min.x) { + r.max.x += 1.0; + } + if near(r.min.x, c.max.x) { + r.min.x -= 1.0; + } + r +} + +/// `outer` minus `inner`: the bands above, below, left and right of it (empty ones dropped). +fn ring(outer: DRect, inner: DRect) -> Vec { + let i = inner.intersect(&outer); + if i.is_empty() { + return if outer.is_empty() { Vec::new() } else { vec![outer] }; + } + [ + DRect::new(outer.x0, outer.y0, outer.x1, i.y0), + DRect::new(outer.x0, i.y1, outer.x1, outer.y1), + DRect::new(outer.x0, i.y0, i.x0, i.y1), + DRect::new(i.x1, i.y0, outer.x1, i.y1), + ] + .into_iter() + .filter(|r| !r.is_empty()) + .collect() +} + +/// Crop tool, while a frame is edited (`crop_ui::shows_beyond_canvas`): like Photoshop's crop +/// preview, the canvas grows to every layer's pixels (a crop with Delete Cropped Pixels off keeps +/// them; a moved layer reaches past the edges) and to the frame, transparency drawn as the +/// checkerboard, all under the shield `crop_overlay` adds. Only the ring around the canvas is +/// composited, on the CPU, once per document state: at most `MAX_TEXTURE` texels per side, from a +/// downsampled proxy past that (so a far-off layer costs no more than a 16 MP composite). +/// Drawn before the canvas, each band reaching a point under its edge. Returns whether anything +/// past the canvas was drawn. +pub(super) fn draw_beyond_canvas(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, idx: usize, output: Option) -> bool { + let ctx = painter.ctx().clone(); + let Some((snapshot, id)) = app.session.documents().get(idx).map(|st| (std::sync::Arc::downgrade(&st.doc), st.doc.id)) else { return false }; + let key = egui::Id::unique(("crop-beyond-canvas", id.0, output)); + let frame = + app.ui.crop_rect.filter(|f| f.iter().all(|v| v.is_finite()) && app.session.active_index() == Some(idx) && crate::crop_ui::shows_beyond_canvas(app)); + let Some(f) = frame else { + ctx.data_mut(|d| d.remove::(key)); + return false; + }; + let (doc, preview_key) = display_doc(app, idx); + if doc.has_artboards() { + return false; + } + let (display, display_key) = canvas_display(app, &doc, output); + let doc_key = preview_key ^ display_key; + let cached: Option = ctx.data(|d| d.get_temp(key)); + let c = match cached.filter(|c| c.snapshot.ptr_eq(&snapshot) && c.key == doc_key) { + Some(c) => c, + None => { + let t0 = crate::gpu_canvas::now_ms(); + let extent = photocraft_engine::extra_cmds::reveal_all_bounds(&doc); + // One texel per `k` document pixels keeps every texture within the device's side. + let k = extent.width().max(extent.height()).div_ceil(texture_side(&ctx)).max(1); + let proxy = (k > 1).then(|| photocraft_compose::proxy::proxy_document(&doc, k)); + let src = proxy.as_ref().unwrap_or(&*doc); + let k = k as i32; + let opts = TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR }; + let bands = ring(extent, doc.bounds()) + .into_iter() + .map(|b| { + // The proxy pixels over `b`: document pixels / k, rounded outwards. + let up = |v: i32| v.div_euclid(k) + i32::from(v.rem_euclid(k) != 0); + let p = DRect::new(b.x0.div_euclid(k), b.y0.div_euclid(k), up(b.x1), up(b.y1)); + let buf = photocraft_compose::render_reduced_rect(src, p, p.width(), p.height()); + let tex = ctx.load_texture("crop-beyond-canvas", display_image(display.as_deref(), &buf), opts); + (b, DRect::new(p.x0.saturating_mul(k), p.y0.saturating_mul(k), p.x1.saturating_mul(k), p.y1.saturating_mul(k)), tex) + }) + .collect(); + app.perf.span("crop-beyond-canvas", crate::gpu_canvas::now_ms() - t0); + let c = BeyondCanvas { snapshot, key: doc_key, extent, bands }; + ctx.data_mut(|d| d.insert_temp(key, c.clone())); + c + } + }; + // Transparency out to the frame, in phase with the canvas's own checkerboard. + let canvas = xf.doc_rect(doc.bounds()); + // A turned frame reaches as far as its corners. + let f = crate::crop_ui::turned_bounds(f, crate::crop_ui::angle(app)); + let fr = DRect::new(f[0].floor() as i32, f[1].floor() as i32, f[2].ceil() as i32, f[3].ceil() as i32); + let square = app.session.prefs().transparency_and_gamut.square(); + let checker_id = square.map(|_| checker(app, &ctx)); + let around = ring(c.extent.union(&fr), doc.bounds()); + // A turned view (Rotate View, or the Crop tool's default mode turning the image behind its + // box) draws each band as its turned quad: its screen bounding box would stretch the band's + // texture and spread the checkerboard past the band. + let turned = xf.rotation != 0.0; + let checker_uv = |p: Pos2, sq: f32| ((p - canvas.min) / (2.0 * sq)).to_pos2(); + for &b in &around { + if turned { + let q = doc_quad(xf, b); + match square.zip(checker_id) { + Some((sq, id)) => textured_quad(painter, id, q, q.map(|p| checker_uv(p, sq))), + None => { + painter.add(egui::Shape::convex_polygon(q.to_vec(), Color32::WHITE, Stroke::NONE)); + } + } + continue; + } + let r = under_canvas(xf.doc_rect(b), canvas); + match square.zip(checker_id) { + Some((sq, id)) => { + let uv = Rect::from_min_max(checker_uv(r.min, sq), checker_uv(r.max, sq)); + painter.image(id, r, uv, Color32::WHITE); + } + None => { + painter.rect_filled(r, 0.0, Color32::WHITE); + } + } + } + for (b, t, tex) in &c.bands { + let part = |a: i32, o: i32, len: u32| (i64::from(a) - i64::from(o)) as f32 / len.max(1) as f32; + let (mut u0, mut u1) = (part(b.x0, t.x0, t.width()), part(b.x1, t.x0, t.width())); + if turned { + // The quad's corners are the band's own (flip included), so no swap. + let (v0, v1) = (part(b.y0, t.y0, t.height()), part(b.y1, t.y0, t.height())); + textured_quad(painter, tex.id(), doc_quad(xf, *b), [pos2(u0, v0), pos2(u1, v0), pos2(u1, v1), pos2(u0, v1)]); + continue; + } + if xf.flip { + (u0, u1) = (u1, u0); + } + let uv = Rect::from_min_max(pos2(u0, part(b.y0, t.y0, t.height())), pos2(u1, part(b.y1, t.y0, t.height()))); + // The texture's edge texels stretch over the point under the canvas. + let (r, e) = (xf.doc_rect(*b), under_canvas(xf.doc_rect(*b), canvas)); + let at = |p: Pos2| uv.min + (p - r.min) / r.size() * uv.size(); + painter.image(tex.id(), e, Rect::from_min_max(at(e.min), at(e.max)), Color32::WHITE); + } + !around.is_empty() +} + +/// Document rect `b`'s corners on screen, clockwise from its top-left (a parallelogram in a turned +/// view). +fn doc_quad(xf: &ViewXform, b: DRect) -> [Pos2; 4] { + [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| xf.to_screen(x as f32, y as f32)) +} + +/// Texture `tex` drawn over the quad `q`, `uv` at its corners. +fn textured_quad(painter: &egui::Painter, tex: egui::TextureId, q: [Pos2; 4], uv: [Pos2; 4]) { + if !q.iter().chain(uv.iter()).all(|p| p.x.is_finite() && p.y.is_finite()) { + return; + } + let mut mesh = egui::Mesh::with_texture(tex); + for (pos, uv) in q.into_iter().zip(uv) { + mesh.vertices.push(egui::epaint::Vertex { pos, uv, color: Color32::WHITE }); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(egui::Shape::mesh(mesh)); +} + +/// Overlays that persist between gestures: polygonal or magnetic lasso in progress, pending crop box. +pub(super) fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, hover: Option) { + crate::magnetic_lasso_ui::draw(app, painter, xf, hover); + if !app.ui.polygon.is_empty() { + let mut pts: Vec = app.ui.polygon.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect(); + if let Some(h) = hover { + // The rubber-band preview must use the same constrained point as the click, + // including when the canvas is zoomed, rotated or flipped. + let mods = painter.ctx().input(|i| i.modifiers); + if app.ui.tool == Tool::PolygonLasso && mods.shift && !mods.alt { + let raw = xf.to_doc(h); + let last = app.ui.polygon.last().copied().unwrap_or(raw); + let snapped = constrained_polygon_point(last, raw); + pts.push(xf.to_screen(snapped[0] as f32, snapped[1] as f32)); + } else { + pts.push(h); + } + } + // Just the outline and its rubber band (the vertices aren't handles to grab), solid until + // the selection is made (#7495). + crate::tool_feedback::draw_solid_path(painter, &pts, false); + } + crate::crop_straighten::draw(app, painter, |p| xf.to_screen(p[0] as f32, p[1] as f32), hover); + crate::blur_pins::draw(app, painter, xf); + if let Some(c) = app.ui.crop_rect { + let deg = crate::crop_ui::angle(app); + let shield = crate::crop_shield::current(app, painter.ctx()); + if deg == 0.0 && xf.rotation == 0.0 { + let r = Rect::from_two_pos(xf.to_screen(c[0] as f32, c[1] as f32), xf.to_screen(c[2] as f32, c[3] as f32)); + crop_overlay(painter, r, shield, &crate::crop_overlay::current_guides(app, r.width(), r.height())); + } else { + let q = crate::crop_ui::corners(c, deg).map(|p| xf.to_screen(p[0] as f32, p[1] as f32)); + crop_overlay_turned(painter, q, shield, &crate::crop_overlay::current_guides(app, q[0].distance(q[1]), q[0].distance(q[3]))); + } + // The frame's angle beside the pointer while it turns (#1792). + if let (Some(a), Some(h)) = (crate::crop_ui::turning(app), hover) { + draw_value_readout(app, painter.ctx(), "crop-angle-readout", h, ["Angle:"], [angle_readout(a)]); + } else if let (Some([w, h]), Some(at)) = (crate::crop_ui::sizing(app), hover) { + // Its W × H while it is drawn or resized (#1919), like the marquee's. + draw_marquee_readout(app, painter.ctx(), at, size_readout(app, [0.0, 0.0, w, h])); + } + } +} + +pub(super) fn draw_drag_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { + draw_tool_state(app, painter, xf, painter.ctx().input(|i| i.pointer.hover_pos())); + // Remove strokes waiting for ↩ stay tinted between drags. + crate::retouch_ui::draw_remove_pending(app, painter, xf); + let Some(d) = &app.drag else { + app.trail = None; + return; + }; + // The Move tool's ΔX/ΔY beside the pointer, for layers and selected pixels alike (#5727). + if let Some(values) = crate::move_ui::offset_readout(app) { + let at = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + draw_value_readout(app, painter.ctx(), "move-readout", xf.to_screen(at[0] as f32, at[1] as f32), ["ΔX:", "ΔY:"], values); + } + // Dragging the selection: its own ants follow the pointer (`selection_shown_offset`). + if d.sel_move.is_some() { + return; + } + let last = d.points.last().map(|p| [p[0], p[1]]).unwrap_or(d.start); + let marquee = marquee_preview_px(&app.ui.tool_options, d, app.point_zoom()); + if let Some(r) = marquee { + draw_marquee_readout(app, painter.ctx(), xf.to_screen(last[0] as f32, last[1] as f32), size_readout(app, r)); + } + match d.tool { + // The canvas shows the live stroke itself (`LiveStroke`); a stroke that couldn't start one + // (Sample All Layers, say) keeps the trail. + t if strokes_live(t) && app.live_stroke.is_some() => { + // Smoothing holds the brush back from the pointer: draw the string between them. + if let Some(EngineStroke::Brush(l)) = app.live_stroke.as_ref().map(|l| &l.stroke) + && let Some(s) = l.smoothing_string() + { + draw_smoothing_string(painter, xf, s); + } + } + t if t.is_brushlike() || t == Tool::QuickSelection => { + // Retouching strokes preview as a translucent trail of the brush footprint: a mask, + // not a brush-wide egui polyline (which zoomed in tessellates into wedges, #189). + let col = match t { + Tool::QuickSelection => Color32::from_white_alpha(40), + // The Remove Tool tints what it will remove, like Photoshop's. + Tool::Remove => crate::theme::Tokens::get(painter.ctx()).danger.gamma_multiply(0.45), + // Photoshop paints the area to heal in half-opaque dark grey while dragging; a faint + // white trail barely showed on light pixels (#7342). The heal itself is computed on + // release. + Tool::SpotHealing => SPOT_HEALING_TRAIL, + _ => Color32::from_white_alpha(60), + }; + let Some(st) = app.session.active() else { return }; + let size = [st.doc.size.width, st.doc.size.height]; + let doc_rect = xf.doc_rect(st.doc.bounds()); + let trail = app.trail.get_or_insert_with(|| crate::stroke_trail::Trail::new(size)); + if t == Tool::SpotHealing { + // What the heal covers, dab by dab: soft edges, pressure and shape dynamics (#2364). + trail.feed_dabs(&d.points, || photocraft_engine::retouch_cmds::stroke_brush(&app.session.tools.brush, &json!({}))); + } else { + trail.feed(&d.points, app.session.tools.brush.size); + } + trail.draw(painter, doc_rect, xf.flip, col); + } + t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::draw_shape_preview(app, painter, xf, t, d.start, last, d.live), + Tool::SingleRowMarquee | Tool::SingleColumnMarquee => { + // Mapped corner by corner like the other marquees, so a rotated view shows the line + // where the release commits it (#2512). + if let Some([x0, y0, x1, y1]) = single_line_drag_px(app, d) { + crate::tool_feedback::draw_ants(painter, &marquee_ants(xf, d.tool, [x0, y0], [x1, y1]), true); + } + } + // Nothing selected yet: no outline, as the release would deselect. + Tool::RectMarquee | Tool::EllipseMarquee if marquee.is_none() => {} + Tool::RectMarquee | Tool::EllipseMarquee | Tool::ObjectSelection => { + // Marching ants, visible on any pixels (#172): built in document space and mapped + // corner by corner, so a rotated view shows them where the release commits (#2512). + let pts = marquee_drag_ants(d, xf, marquee); + crate::tool_feedback::draw_ants(painter, &pts, true); + } + // 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); + 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)); + } + } + Tool::FreeformPen => { + let mut pts: Vec = d.points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect(); + // Between ⌥-clicks: the straight segment the next click makes. + if let Some(lasso) = &d.lasso { + pts.push(xf.to_screen(lasso.cursor[0] as f32, lasso.cursor[1] as f32)); + } + painter.add(egui::Shape::line(pts, Stroke::new(1.5, crate::theme::Tokens::get(painter.ctx()).accent))); + } + Tool::Lasso | Tool::Patch | Tool::ContentAwareMove => { + let mut pts: Vec = d.points.iter().map(|p| xf.to_screen(p[0] as f32, p[1] as f32)).collect(); + if let Some(lasso) = &d.lasso { + pts.push(xf.to_screen(lasso.cursor[0] as f32, lasso.cursor[1] as f32)); + } + // The Lasso's outline is solid until the release makes the selection (#7495); a Patch + // or Content-Aware Move area keeps its ants. + if d.tool == Tool::Lasso { + // On pixel centres, so a 1 pt line stays crisp wherever the canvas sits (a pixel + // edge would blur it to grey). + let pts: Vec = pts.into_iter().map(|p| p.round() + vec2(0.5, 0.5)).collect(); + crate::tool_feedback::draw_solid_path(painter, &pts, false); + } else { + crate::tool_feedback::draw_ants(painter, &pts, false); + } + } + Tool::Gradient => { + let a = xf.to_screen(d.start[0] as f32, d.start[1] as f32); + let b = xf.to_screen(last[0] as f32, last[1] as f32); + painter.line_segment([a, b], Stroke::new(3.0, Color32::from_black_alpha(140))); + painter.line_segment([a, b], Stroke::new(1.0, Color32::WHITE)); + painter.circle_filled(a, 3.0, Color32::WHITE); + painter.circle_filled(b, 3.0, Color32::WHITE); + } + Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => { + let r = Rect::from_two_pos(xf.to_screen(d.start[0] as f32, d.start[1] as f32), xf.to_screen(last[0] as f32, last[1] as f32)); + let pts = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom(), r.left_top()]; + painter.add(egui::Shape::line(pts.to_vec(), Stroke::new(1.0, Color32::WHITE))); + painter.add(egui::Shape::dashed_line(&pts, Stroke::new(1.0, Color32::BLACK), 3.0, 3.0)); + } + // The layers themselves follow the pointer (`move_ui`); the arrow only when they can't. + Tool::Move if !crate::move_ui::showing(app) => { + let from = xf.to_screen(d.start[0] as f32, d.start[1] as f32); + let off = xf.to_screen(last[0] as f32, last[1] as f32) - from; + painter.arrow(from, off, Stroke::new(2.0, crate::theme::Tokens::get(painter.ctx()).accent)); + } + _ => {} + } +} diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs new file mode 100644 index 0000000000..fe096f1159 --- /dev/null +++ b/crates/ui-egui/src/canvas/selection.rs @@ -0,0 +1,105 @@ +use super::tool_input::selection_drag_kind; +use super::*; + +/// Photoshop's cursor over a selection: what a press (or the drag under way) would do. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SelCursor { + /// A marquee or lasso inside the selection moves the outline (the move cursor, #1428), also + /// while it is being dragged. + Outline, + /// Arrow with scissors: the Move tool (⌘ with a marquee) cuts and moves the selected pixels. + Cut, + /// Arrow with a second arrow: ⌥ lifts a copy of them instead. + Copy, + /// Plain arrow: a floating piece, moved again by a plain drag until it is dropped. + Piece, + /// Hollow arrowhead: the selected pixels are being dragged. + Dragging, +} + +/// The cursor at document point `p` with `tool` in effect and `mods` held (`None`: not over a +/// selection the press would move). The Move tool moves the selected pixels from anywhere +/// (`move_ui::moves_selected_pixels_with`); a selection tool from inside the selection, or on the +/// floating piece (`selection_drag_kind`). +pub fn selection_cursor(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> Option { + if let Some(d) = &app.drag { + return match d.sel_move { + Some(true) => Some(SelCursor::Dragging), + Some(false) => Some(SelCursor::Outline), + None => None, + }; + } + let floating = app.session.active().and_then(photocraft_engine::float_cmds::floating).is_some(); + let pixels = if tool == Tool::Move { + crate::move_ui::moves_selected_pixels_with(app, tool) + } else { + match selection_drag_kind(app, tool, p, mods)? { + false => return Some(SelCursor::Outline), + true => true, + } + }; + if !pixels { + return None; + } + // ⌥ (⌘⌥ with a selection tool) floats a copy, of the layer's pixels or of the piece. + let copy = mods.alt && (tool == Tool::Move || mods.command); + Some(match (floating, copy) { + (_, true) => SelCursor::Copy, + (true, false) => SelCursor::Piece, + (false, false) => SelCursor::Cut, + }) +} + +/// Whole-pixel offset of a selection drag in progress (`Drag::sel_move`). +pub(crate) fn selection_drag_delta(app: &PhotocraftApp) -> Option<(i32, i32)> { + let d = app.drag.as_ref().filter(|d| d.sel_move.is_some())?; + let end = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + Some(((end[0] - d.start[0]).round().clamp(-1e7, 1e7) as i32, (end[1] - d.start[1]).round().clamp(-1e7, 1e7) as i32)) +} + +/// The selection a floating piece on document `idx` shows its ants for, before its offset: the +/// moved pixels' outline, as in Photoshop (#7538); `None` outlines the document's selection. The +/// surface's tiles are shared, so the clone is cheap. +pub(crate) fn floating_outline(app: &PhotocraftApp, idx: usize) -> Option { + if app.session.active_index() != Some(idx) { + return None; + } + photocraft_engine::float_cmds::floating(app.session.active()?)?.parts.outline().cloned() +} + +/// Where the selection is drawn relative to where it is: a floating piece's offset plus a drag +/// in progress. +pub(super) fn selection_shown_offset(app: &PhotocraftApp) -> Option<(i32, i32)> { + crate::move_ui::floating_offset(app).or_else(|| selection_drag_delta(app)).or_else(|| carried_selection_delta(app)) +} + +/// Whole-pixel offset of a Move drag of several layers, which carries the selection along +/// (`move_ui::carries_selection`): their ants follow the layers while they move (#7538). +fn carried_selection_delta(app: &PhotocraftApp) -> Option<(i32, i32)> { + let d = app.drag.as_ref().filter(|d| d.tool == Tool::Move && d.sel_move.is_none())?; + if !crate::move_ui::carries_selection(app) { + return None; + } + let end = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + Some(((end[0] - d.start[0]).round().clamp(-1e7, 1e7) as i32, (end[1] - d.start[1]).round().clamp(-1e7, 1e7) as i32)) +} + +/// End of a selection drag: move the outline, or the floating piece. A click without moving +/// deselects, like a marquee click (a click on a floating piece leaves it floating, unless it never +/// moved: then it is put back, so Undo isn't spent on it). +pub(super) fn finish_selection_drag(app: &mut PhotocraftApp, floating: bool, start: [f64; 2], end: [f64; 2]) { + let (dx, dy) = ((end[0] - start[0]).round(), (end[1] - start[1]).round()); + let unmoved = app.session.active().and_then(photocraft_engine::float_cmds::floating).is_some_and(|f| f.offset == (0, 0)); + let r = match (floating, dx == 0.0 && dy == 0.0) { + (true, true) if unmoved => app.run("select.drop", json!({})), + (true, true) => return, + (false, true) if app.session.is_enabled("select.deselect") => app.run("select.deselect", json!({})), + (false, true) => return, + (true, false) => app.run("select.float", json!({"dx": dx, "dy": dy})), + (false, false) => app.run("select.transformSelection", json!({"dx": dx, "dy": dy})), + }; + if let Err(e) = r { + app.ui.status = e; + app.ui.status_error = true; + } +} diff --git a/crates/ui-egui/src/canvas/start_screen.rs b/crates/ui-egui/src/canvas/start_screen.rs new file mode 100644 index 0000000000..d22295886c --- /dev/null +++ b/crates/ui-egui/src/canvas/start_screen.rs @@ -0,0 +1,177 @@ +use super::tabs::{open_on_double_click, paint_dots}; +use super::*; + +/// The Home screen's card is this wide when the canvas has room, and as wide as the canvas when it doesn't. +const HOME_CARD_WIDTH: f32 = 460.0; + +/// Least width of each of the Home screen's New document and Open buttons. +const HOME_BUTTON_WIDTH: f32 = 190.0; + +/// Space between the Home screen's two buttons. +const HOME_BUTTON_GAP: f32 = 12.0; + +pub(super) fn start_screen(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = crate::theme::Tokens::get(ui.ctx()); + let area = ui.available_rect_before_wrap(); + paint_dots(ui, area, app.session.prefs().interface.show_canvas_dots); + open_on_double_click(app, ui, area); + // File › Open Recent, newest first (on the web there are no paths to reopen). + let show_recent = app.session.prefs().interface.show_home_recent_files; + let recent: Vec = + if cfg!(target_arch = "wasm32") || !show_recent { Vec::new() } else { app.ui.recent_files.iter().take(HOME_RECENT).cloned().collect() }; + let recent_h = if recent.is_empty() { 0.0 } else { 34.0 + recent.len() as f32 * HOME_RECENT_ROW }; + // A tiling window manager can give the canvas less room than the card wants: shrink the card + // to fit, and stack the buttons when they don't fit side by side. + let new_label = crate::shortcuts::command_label(app, "New document…", "file.new"); + let open_label = crate::shortcuts::command_label(app, "Open…", "file.open"); + let card_width = HOME_CARD_WIDTH.min(area.width()); + let button_width = HOME_BUTTON_WIDTH.max(crate::widgets::button_width(ui, &[&new_label, &open_label])); + let side_by_side = 2.0 * button_width + HOME_BUTTON_GAP <= card_width; + // Stacked buttons take one more row. + let stacked_h = if side_by_side { 0.0 } else { 44.0 }; + let card = Rect::from_center_size(area.center(), egui::vec2(card_width, 330.0 + recent_h + stacked_h)); + ui.scope_builder(egui::UiBuilder::new().max_rect(card), |ui| { + ui.vertical_centered(|ui| { + ui.horizontal(|ui| { + let title = ui.painter().layout_no_wrap(tl!("PhotoCraft").into(), crate::theme::semibold(38.0), t.text); + let by = ui.painter().layout_no_wrap(tl!("open source").into(), egui::FontId::proportional(13.0), t.text_faint); + let total = title.size().x + by.size().x + 10.0; + ui.add_space(((card.width() - total) / 2.0).max(0.0)); + let (r, _) = ui.allocate_exact_size(title.size(), Sense::hover()); + ui.painter().galley(r.min, title, t.text); + let (r2, _) = ui.allocate_exact_size(egui::vec2(by.size().x + 10.0, r.height()), Sense::hover()); + ui.painter().galley(egui::pos2(r2.left() + 10.0, r.bottom() - by.size().y - 8.0), by, t.text_faint); + }); + ui.add_space(6.0); + ui.label(egui::RichText::new(tl!("Create a new document or open an existing file.")).color(t.text_dim).size(14.0)); + ui.add_space(22.0); + let (mut new_clicked, mut open_clicked) = (false, false); + if side_by_side { + ui.horizontal(|ui| { + ui.add_space(((card.width() - 2.0 * button_width - HOME_BUTTON_GAP) / 2.0).max(0.0)); + ui.spacing_mut().item_spacing.x = HOME_BUTTON_GAP; + new_clicked = crate::widgets::primary_button(ui, &new_label, button_width).clicked(); + open_clicked = crate::widgets::secondary_button(ui, &open_label, button_width).clicked(); + }); + } else { + new_clicked = crate::widgets::primary_button(ui, &new_label, button_width).clicked(); + ui.add_space(HOME_BUTTON_GAP); + open_clicked = crate::widgets::secondary_button(ui, &open_label, button_width).clicked(); + } + if new_clicked { + let fields = app.new_document_fields(); + app.ui.open_dialog(crate::state::DialogKind::NewDocument, fields); + } + if open_clicked { + let _ = app.open_dialog_file(); + } + ui.add_space(22.0); + ui.horizontal(|ui| { + let msg = start_screen_drop_hint(app); + let g = ui.painter().layout_no_wrap(msg.to_string(), egui::FontId::proportional(12.5), t.text_faint); + ui.add_space(((card.width() - g.size().x - 24.0) / 2.0).max(0.0)); + let (r, _) = ui.allocate_exact_size(egui::vec2(18.0, 18.0), Sense::hover()); + crate::icons::paint(ui, r, "image", 15.0, t.text_faint); + ui.label(egui::RichText::new(msg).color(t.text_faint)); + }); + if !recent.is_empty() { + ui.add_space(22.0); + home_recent(app, ui, &recent); + } + ui.add_space(26.0); + crate::links::discord_button(app, ui, 190.0); + ui.add_space(10.0); + crate::links::link_row(app, ui); + }); + }); +} + +/// Wayland has no native file drops (winit 0.30, #386), so the hint offers File › Open and paste. +pub(super) fn start_screen_drop_hint(app: &PhotocraftApp) -> std::borrow::Cow<'static, str> { + if app.services.is_wayland { + crate::i18n::fmt(tl!("Use File › Open, or paste a copied image with {paste}."), &[("paste", &crate::notices::paste_hint(app))]).into() + } else { + tl!("Drop an image or PSD anywhere to open it.").into() + } +} + +/// Recent files listed on the Home screen. +const HOME_RECENT: usize = 6; + +/// Height of one Home-screen recent-file row. +const HOME_RECENT_ROW: f32 = 30.0; + +/// The Home screen's "Recent" list: file name, its folder on the right, click to open. The +/// hovered row shows a × that takes it off the list, and right-click offers Remove from Recent +/// and Clear Recent Files (#2691). +fn home_recent(app: &mut PhotocraftApp, ui: &mut egui::Ui, recent: &[String]) { + let t = crate::theme::Tokens::get(ui.ctx()); + let width = 380.0; + ui.horizontal(|ui| { + // Line the heading up with the file icons. + ui.add_space(((ui.available_width() - width) / 2.0).max(0.0) + 8.0); + ui.label(egui::RichText::new(tl!("Recent")).font(crate::theme::semibold(12.5)).color(t.text_dim)); + }); + ui.add_space(4.0); + let mut open = None; + let mut remove = None; + let mut clear = false; + for path in recent { + let name = crate::file_open::display_name(path); + let folder = std::path::Path::new(path).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(); + let (row, resp) = ui.allocate_exact_size(egui::vec2(width, HOME_RECENT_ROW), Sense::click()); + // The × sits on top of the row, so the row counts as hovered while the pointer is on it. + let hovered = ui.rect_contains_pointer(row); + if hovered { + ui.painter().rect_filled(row, t.radius_sm, t.hover); + } + let close = Rect::from_center_size(egui::pos2(row.right() - 16.0, row.center().y), egui::vec2(22.0, 22.0)); + let right = if hovered { close.left() - 4.0 } else { row.right() - 10.0 }; + let icon = Rect::from_center_size(egui::pos2(row.left() + 16.0, row.center().y), egui::vec2(16.0, 16.0)); + crate::icons::paint(ui, icon, "file", 14.0, t.text_dim); + let x = row.left() + 32.0; + let name_g = crate::tab_strip::elided(ui, &name, egui::FontId::proportional(12.5), t.text, 170.0); + let name_w = name_g.size().x; + ui.painter().galley(egui::pos2(x, row.center().y - name_g.size().y / 2.0), name_g, t.text); + let folder_max = (right - (x + name_w + 14.0)).max(0.0); + if folder_max > 20.0 && !folder.is_empty() { + let fg = crate::tab_strip::elided(ui, &folder, egui::FontId::proportional(11.5), t.text_faint, folder_max); + ui.painter().galley(egui::pos2(right - fg.size().x, row.center().y - fg.size().y / 2.0), fg, t.text_faint); + } + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name)); + let resp = resp.on_hover_text(path).on_hover_cursor(egui::CursorIcon::PointingHand); + if hovered { + let x = ui.interact(close, resp.id.with("remove"), Sense::click()); + let label = crate::i18n::fmt(tl!("Remove {name} from Recent"), &[("name", &name)]); + x.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &label)); + let color = crate::icons::button_chrome(ui, close, false, x.hovered()); + crate::icons::paint(ui, close, "x", 12.0, color); + if x.on_hover_text(tl!("Remove from Recent")).clicked() { + remove = Some(path.clone()); + } + } + if resp.clicked() && remove.is_none() { + open = Some(path.clone()); + } + resp.context_menu(|ui| { + if ui.button(tl!("Remove from Recent")).clicked() { + remove = Some(path.clone()); + ui.close(); + } + if ui.button(tl!("Clear Recent Files")).clicked() { + clear = true; + ui.close(); + } + }); + } + if clear { + app.clear_recent(); + } else if let Some(path) = remove { + app.remove_recent(&path); + } + if let Some(path) = open + && let Err(e) = app.open_path(&path) + { + app.open_failed(&crate::file_open::display_name(&path), &e); + } +} diff --git a/crates/ui-egui/src/canvas/strokes.rs b/crates/ui-egui/src/canvas/strokes.rs new file mode 100644 index 0000000000..c970c39a20 --- /dev/null +++ b/crates/ui-egui/src/canvas/strokes.rs @@ -0,0 +1,655 @@ +use super::display::{canvas_display, display_image}; +use super::drag::Drag; +use super::textures::{canvas_texture_options, shown_as_document}; +use super::view_xform::ViewXform; +use super::*; + +pub(crate) struct ClonePreviewCache { + pub(super) key: String, + texture: egui::TextureHandle, +} + +/// A transient source image beneath the brush outline; never part of the document render. +pub(super) fn draw_clone_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, at: [f64; 2], output: Option) { + use photocraft_engine::presets::clone_source::{Mapping, overlay_blend, transform_matrix}; + let overlay = app.session.presets.clone.overlay.clone(); + if app.ui.tool != Tool::CloneStamp || !overlay.show || (overlay.auto_hide && app.drag.is_some()) { + return; + } + let slot = app.session.presets.clone.active().clone(); + let Some(source) = slot.source else { return }; + let radius = f64::from(app.session.tools.brush.size) / 2.0; + if !radius.is_finite() || radius <= 0.0 || radius > 500.0 || !at.iter().all(|v| v.is_finite() && v.abs() < 1_000_000.0) { + return; + } + let stroke_start = app.drag.as_ref().map(|d| d.start); + let anchor = if app.ui.tool_options.clone_aligned { slot.anchor.or(stroke_start) } else { stroke_start }.unwrap_or(at); + let map = + Mapping { source: (source[0], source[1]), anchor: (anchor[0], anchor[1]), m: transform_matrix(slot.scale, slot.rotation, slot.flip_h, slot.flip_v) }; + let rect = DRect::new((at[0] - radius).floor() as i32, (at[1] - radius).floor() as i32, (at[0] + radius).ceil() as i32, (at[1] + radius).ceil() as i32); + let Some(st) = app.session.active() else { return }; + let (display, display_key) = canvas_display(app, &st.doc, output); + // A shaped tip (sampled bitmap, or a rotated / flattened round one) clips the overlay to its + // outline instead of a circle, as Photoshop does with Clipped on. + let tip_rings = if overlay.clipped { crate::brush_cursor::rings(painter.ctx(), &app.session.tools.brush, true) } else { None }; + let tip_key = tip_rings.as_ref().map(|r| { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + r.iter().flatten().for_each(|p| (p[0].to_bits(), p[1].to_bits()).hash(&mut h)); + (h.finish(), radius.to_bits(), at.map(f64::to_bits)) + }); + let key = format!( + "{:?}:{}:{:?}:{rect:?}:{map:?}:{}:{}:{}:{}:{}:{tip_key:?}", + st.doc.id, st.revision, st.active_layer, app.ui.tool_options.clone_sample, display_key, overlay.invert, overlay.blend, app.ui.view.pattern_preview + ); + if app.clone_preview.as_ref().is_none_or(|c| c.key != key) { + let Ok(mut buf) = + photocraft_engine::retouch_cmds::clone_preview_periodic(&app.session, rect, &map, &app.ui.tool_options.clone_sample, app.ui.view.pattern_preview) + else { + return; + }; + if overlay.invert { + for px in &mut buf.px { + for c in px.iter_mut().take(3) { + *c = 1.0 - *c; + } + } + } + // Darken, Lighten and Difference mix the source with the image under the brush (the + // composite, whatever Sample reads), so Difference turns black where they line up. + if overlay.blend != "normal" { + let here = Mapping { source: (0.0, 0.0), anchor: (0.0, 0.0), m: [1.0, 0.0, 0.0, 1.0] }; + let Ok(under) = photocraft_engine::retouch_cmds::clone_preview_periodic(&app.session, rect, &here, "all", app.ui.view.pattern_preview) else { + return; + }; + for (px, d) in buf.px.iter_mut().zip(&under.px) { + *px = overlay_blend(&overlay.blend, *px, *d); + } + } + if let Some(rings) = &tip_rings { + let mask = crate::brush_cursor::tip_mask(rings, at, radius, [rect.x0, rect.y0, rect.x1, rect.y1]); + for (px, inside) in buf.px.iter_mut().zip(mask) { + if !inside { + *px = [0.0; 4]; + } + } + } + let image = display_image(display.as_deref(), &buf); + match app.clone_preview.as_mut() { + Some(cache) => { + cache.texture.set(image, canvas_texture_options(1)); + cache.key = key; + } + None => app.clone_preview = Some(ClonePreviewCache { key, texture: painter.ctx().load_texture("clone-preview", image, canvas_texture_options(1)) }), + } + } + let Some(cache) = &app.clone_preview else { return }; + let tint = Color32::from_white_alpha((overlay.opacity.clamp(0.0, 100.0) * 2.55).round() as u8); + // A textured triangle fan provides a circular clip, including mirrored canvas views. + let mut mesh = egui::Mesh::with_texture(cache.texture.id()); + let vertex = |x: f64, y: f64| egui::epaint::Vertex { + pos: xf.to_screen(x as f32, y as f32), + uv: pos2((x - f64::from(rect.x0)) as f32 / rect.width() as f32, (y - f64::from(rect.y0)) as f32 / rect.height() as f32), + color: tint, + }; + if !overlay.clipped || tip_rings.is_some() { + for (x, y) in [(rect.x0, rect.y0), (rect.x1, rect.y0), (rect.x1, rect.y1), (rect.x0, rect.y1)] { + mesh.vertices.push(vertex(f64::from(x), f64::from(y))); + } + mesh.indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]); + painter.add(egui::Shape::mesh(mesh)); + return; + } + mesh.vertices.push(vertex(at[0], at[1])); + for i in 0..=64 { + let angle = f64::from(i) * std::f64::consts::TAU / 64.0; + mesh.vertices.push(vertex(at[0] + radius * angle.cos(), at[1] + radius * angle.sin())); + } + for i in 1..=64 { + mesh.indices.extend_from_slice(&[0, i, i + 1]); + } + painter.add(egui::Shape::mesh(mesh)); +} + +/// The engine's live stroke of a tool: the Brush, Pencil and Eraser paint dabs; the Clone Stamp, +/// Healing Brush and History Brush composite their source. +pub(super) enum EngineStroke { + Brush(Box), + Retouch(photocraft_engine::retouch_cmds::LiveRetouch), + Dab(photocraft_engine::retouch_cmds::LiveDab), + Mixer(Box), +} + +impl EngineStroke { + /// The brush engine's strokes can change while the pointer is held still (see + /// `LiveStroke::wants_time`); the retouch strokes don't. + pub(super) fn wants_time(&self) -> bool { + match self { + EngineStroke::Brush(l) => l.wants_time(), + EngineStroke::Mixer(l) => l.wants_time(), + EngineStroke::Retouch(_) | EngineStroke::Dab(_) => false, + } + } + + pub(super) fn doc(&self) -> &std::sync::Arc { + match self { + Self::Brush(s) => &s.doc, + Self::Retouch(s) => &s.doc, + Self::Dab(s) => &s.doc, + Self::Mixer(s) => &s.doc, + } + } + fn bounds(&self) -> DRect { + match self { + Self::Brush(s) => s.bounds(), + Self::Retouch(s) => s.bounds(), + Self::Dab(s) => s.bounds(), + Self::Mixer(s) => s.bounds(), + } + } + fn push(&mut self, pts: &[photocraft_engine::paint::StrokePoint]) -> photocraft_engine::Result { + match self { + Self::Brush(s) => s.push(pts), + Self::Retouch(s) => s.push(pts), + Self::Dab(s) => s.push(pts), + Self::Mixer(s) => s.push(pts), + } + } + /// The jitter seed the commit must reuse (the Clone Stamp's comes from the session brush). + fn seed(&self) -> Option { + match self { + Self::Brush(s) => Some(s.seed), + Self::Mixer(s) => Some(s.seed), + Self::Retouch(_) => None, + Self::Dab(_) => None, + } + } +} + +/// A stroke shown while it is drawn: the engine renders the real result onto a copy of the +/// document, and the canvas redraws only what each step changed. +pub(crate) struct LiveStroke { + pub(super) preview_failed: bool, + pub(super) stroke: EngineStroke, + pub(super) doc: photocraft_doc::DocId, + revision: u64, + /// Preview key of the stroke; step `n` displays as `key + n`. + pub(super) key: u64, + /// Damage of each step (step 0 = the document before the stroke). + pub(super) damage: Vec, + /// Drag points rendered so far. + fed: usize, +} + +impl LiveStroke { + pub(super) fn display_key(&self) -> u64 { + self.key + self.damage.len() as u64 + } + + /// What changed since the canvas showed preview `key` (0 = the document before the stroke). + pub(super) fn since(&self, key: u64) -> Option { + let seen = if key == 0 { 0 } else { usize::try_from(key.checked_sub(self.key)?).ok()? }; + Some(self.damage.get(seen..)?.iter().fold(DRect::EMPTY, |a, r| a.union(r))) + } +} + +/// A live stroke whose pixels its commit took over (`"fromLive"`): document `doc` at `revision` +/// holds exactly the live stroke's last step, so a cache that showed step `n` of it only misses +/// the steps after `n` (step 0 = the document before the stroke: everything). +pub(crate) struct CommittedStroke { + pub(crate) doc: photocraft_doc::DocId, + pub(crate) revision: u64, + key: u64, + damage: Vec, + /// What the commit repaints beyond the stroke whatever a cache showed: the layer's whole + /// composite when effects laid out over its frame moved with it (a Gradient Overlay spans the + /// grown layer, #4053; `photocraft_compose::relayout_damage`). + pub(super) relayout: DRect, +} + +impl CommittedStroke { + #[cfg(test)] + pub(crate) fn for_test(key: u64, damage: Vec) -> Self { + Self { doc: photocraft_doc::DocId(0), revision: 0, key, damage, relayout: DRect::EMPTY } + } + + /// The raw preview key of the live stroke's last step: what a cache showed at release. + #[cfg(test)] + pub(crate) fn last_key(&self) -> u64 { + self.key + self.damage.len() as u64 + } + + /// What a cache that showed raw preview `key` of this stroke at the revision before misses. + pub(crate) fn since(&self, key: u64) -> Option { + let seen = if key == 0 { 0 } else { usize::try_from(key.checked_sub(self.key)?).ok()? }; + Some(self.damage.get(seen..)?.iter().fold(DRect::EMPTY, |a, r| a.union(r))) + } +} + +/// The live stroke on document `idx`, while it is current. +pub(super) fn live_stroke(app: &PhotocraftApp, idx: usize) -> Option<&LiveStroke> { + let st = app.session.documents().get(idx)?; + app.live_stroke.as_ref().filter(|l| app.drag.is_some() && l.doc == st.doc.id && l.revision == st.revision) +} + +/// `paint.stroke` params for a Brush/Eraser drag (shared by the live preview and the commit). The +/// stroke smoothing is the session brush's (the options bar's Smoothing %). +pub(super) fn stroke_params(app: &PhotocraftApp, d: &Drag, points: &[Vec]) -> serde_json::Value { + let tool = d.tool; + let mut p = json!({ "points": points, "erase": d.erase, "zoom": app.point_zoom(), "target": paint_target(app) }); + if d.clear { + p["mode"] = json!("clear"); + } + if tool == Tool::Pencil { + p["autoErase"] = json!(app.ui.tool_options.pencil_auto_erase); + } + // Block mode: the engine sizes the square from the stroke's zoom (16 / zoom px, #2770). + if crate::eraser_ui::block_mode(app, tool) { + p["block"] = json!(true); + } + p +} + +/// Tools whose strokes the engine renders while they are drawn (`LiveStroke`). +pub(crate) fn strokes_live(tool: Tool) -> bool { + matches!( + tool, + Tool::Brush + | Tool::Pencil + | Tool::MixerBrush + | Tool::Eraser + | Tool::ColorReplacement + | Tool::Blur + | Tool::Sharpen + | Tool::Smudge + | Tool::Dodge + | Tool::Burn + | Tool::Sponge + ) || live_retouch_command(tool).is_some() +} + +/// The Spot Healing Brush's stroke while dragging: Photoshop shows the area it will heal as a +/// semi-opaque dark overlay (an image overlay, the same in every UI theme) and heals on release. +pub(crate) const SPOT_HEALING_TRAIL: Color32 = Color32::from_black_alpha(128); + +/// The retouching tools drawn live (`LiveRetouch`; the Background Eraser's and an Impressionist +/// Pattern Stamp's dabs are laid one by one, `LiveDab`), by the command their live stroke +/// previews. The Healing Brush shows its texture while drawing; the blend comes on release. +pub(super) fn live_retouch_command(tool: Tool) -> Option<&'static str> { + match tool { + Tool::CloneStamp => Some("paint.cloneStamp"), + Tool::Healing => Some("paint.healingBrush"), + Tool::HistoryBrush => Some("paint.historyBrush"), + Tool::PatternStamp => Some("paint.patternStamp"), + Tool::BackgroundEraser => Some("paint.backgroundEraser"), + _ => None, + } +} + +/// The command a live-stroking tool commits: the Pencil's (and the Pencil- or Block-mode +/// Eraser's) `paint.pencil`, else `paint.stroke`. +pub(crate) fn stroke_command(app: &PhotocraftApp, tool: Tool) -> &'static str { + if tool == Tool::Pencil || crate::eraser_ui::pencil_mode(app, tool) || crate::eraser_ui::block_mode(app, tool) { "paint.pencil" } else { "paint.stroke" } +} + +pub(super) fn begin_live_stroke(app: &PhotocraftApp) -> Option { + static STROKES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let st = app.session.active()?; + let d = app.drag.as_ref()?; + let stroke = if d.tool == Tool::MixerBrush { + let points = app.stylus.stroke_points(&d.points); + let p = stroke_params(app, d, points.get(..1)?); + EngineStroke::Mixer(Box::new(photocraft_engine::brush_cmds::mixer_live::LiveMixer::begin(&app.session, &p).ok()?)) + } else if d.tool == Tool::ColorReplacement { + // The params `retouch_ui::finish_stroke` commits. + let mut p = crate::retouch_ui::color_replacement_params(app); + p["points"] = json!(d.points); + EngineStroke::Dab(photocraft_engine::brush_cmds::live_color_replacement(&app.session, &p).ok()?) + } else if let Some((cmd, mut p)) = crate::retouch_ui::dab_params(app, d.tool) { + // The params `retouch_ui::finish_stroke` commits; Sample All Layers isn't previewed. + p["points"] = json!(d.points); + p["target"] = paint_target(app); + EngineStroke::Dab(photocraft_engine::retouch_cmds::LiveDab::begin(&app.session, cmd, &p).ok()?) + } else if d.tool == Tool::PatternStamp { + // The params `retouch_ui::finish_stroke` commits. + let mut p = crate::retouch_ui::pattern_stamp_params(app, &d.points); + p["points"] = json!(d.points); + p["target"] = paint_target(app); + if app.ui.tool_options.pattern_stamp_impressionist { + EngineStroke::Dab(photocraft_engine::retouch_cmds::live_pattern_impressionist(&app.session, &p).ok()?) + } else { + EngineStroke::Retouch(photocraft_engine::retouch_cmds::LiveRetouch::begin(&app.session, "paint.patternStamp", &p).ok()?) + } + } else if d.tool == Tool::BackgroundEraser { + // The params `eraser_ui::finish_stroke` commits (layer pixels only). + let p = crate::eraser_ui::background_eraser_params(app, &d.points); + EngineStroke::Dab(photocraft_engine::eraser_cmds::live_background_eraser(&app.session, &p).ok()?) + } else if let Some(cmd) = live_retouch_command(d.tool) { + // The params `retouch_ui::finish_stroke` commits. + let mut p = if d.tool == Tool::HistoryBrush { crate::retouch_ui::history_brush_params(app) } else { crate::retouch_ui::clone_params(app)? }; + p["points"] = json!(d.points); + p["target"] = paint_target(app); + EngineStroke::Retouch(photocraft_engine::retouch_cmds::LiveRetouch::begin(&app.session, cmd, &p).ok()?) + } else { + let p = stroke_params(app, d, &app.stylus.stroke_points(&d.points)); + EngineStroke::Brush(Box::new(photocraft_engine::brush_cmds::LiveStroke::begin_with(&app.session, stroke_command(app, d.tool), &p).ok()?)) + }; + let n = STROKES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) & 0xff_ffff; + let damage = vec![stroke.bounds()]; + Some(LiveStroke { + stroke, + doc: st.doc.id, + revision: st.revision, + key: (1 << 44) | (n << 20), + damage, + fed: if d.tool == Tool::MixerBrush { 1 } else { d.points.len() }, + preview_failed: false, + }) +} + +/// Cancel uncommitted mixer paint when its document, tool or input context goes away. +pub(crate) fn cancel_mixer_on_context_change(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { + if !app.drag.as_ref().is_some_and(|drag| drag.tool == Tool::MixerBrush) { + return false; + } + let changed = app.ui.tool != Tool::MixerBrush + || app.live_stroke.as_ref().is_some_and(|live| !app.session.active().is_some_and(|st| st.doc.id == live.doc && st.revision == live.revision)); + if changed || ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + app.drag = None; + app.live_stroke = None; + return true; + } + false +} + +/// Render the drag points the live stroke hasn't seen yet, with the pen pressure, tilt and +/// rotation the commit's `paint.stroke` gets for them. +pub(super) fn feed_live_stroke(app: &mut PhotocraftApp) { + // A batched move replays several samples in one frame and calls this once at the end, so the + // per-sample calls from `tool_event` are skipped (see `canvas_view`). + if app.defer_live_stroke { + return; + } + let (Some(l), Some(d)) = (app.live_stroke.as_mut(), app.drag.as_ref()) else { return }; + if l.preview_failed { + return; + } + let pose = &app.stylus.stroke; + // The same times `stroke_points` gives the commit (from the drag's first point). + let t0 = app.stylus.point_ms(0); + let pts: Vec<_> = (l.fed..d.points.len()) + .filter_map(|i| { + let p = d.points.get(i)?; + let t = pose.get(i).or(pose.last()).copied().unwrap_or_default(); + let mut sp = photocraft_engine::paint::StrokePoint::new(p[0], p[1], p[2] as f32); + (sp.tilt_x, sp.tilt_y, sp.rotation) = (t[0], t[1], t[2]); + sp.time = app.stylus.point_ms(i) - t0; + Some(sp) + }) + .collect(); + if pts.is_empty() { + return; + } + l.fed = d.points.len(); + let started = crate::gpu_canvas::now_ms(); + match l.stroke.push(&pts) { + Ok(r) => l.damage.push(r), + Err(e) => { + if d.tool == Tool::MixerBrush { + // Keep the last valid preview and its document/revision guard. All input + // stays in the drag; release replays it without the preview tile budget. + l.preview_failed = true; + app.ui.status = e.to_string(); + app.ui.status_error = true; + } else { + app.live_stroke = None; + } + } + } + app.stroke_trace.stroke(crate::gpu_canvas::now_ms() - started); +} + +/// The points the live retouching stroke has rendered. +#[cfg(test)] +pub(crate) fn live_retouch_points(app: &PhotocraftApp) -> Option> { + match &app.live_stroke.as_ref()?.stroke { + EngineStroke::Retouch(l) => Some(l.points().to_vec()), + _ => None, + } +} + +/// Offer the Clone Stamp's or History Brush's live stroke, or a Dodge, Burn, Sponge, Blur, Sharpen +/// or Smudge one, with the drag points it hasn't rendered yet, to the command +/// `retouch_ui::finish_stroke` commits, which then takes its pixels instead of rendering the +/// stroke again. +pub(super) fn offer_live_retouch(app: &mut PhotocraftApp, d: &Drag) { + let dab = crate::retouch_ui::dab_params(app, d.tool).is_some(); + if !dab && !matches!(d.tool, Tool::CloneStamp | Tool::HistoryBrush) { + return; + } + let Some(LiveStroke { stroke, fed, .. }) = app.live_stroke.take() else { return }; + let rest: Vec<_> = d.points.get(fed..).unwrap_or_default().iter().map(|q| photocraft_engine::paint::StrokePoint::new(q[0], q[1], q[2] as f32)).collect(); + // A refused offer (the brush changed mid-stroke, say) leaves the commit to render the stroke. + match stroke { + EngineStroke::Retouch(mut live) if !dab => { + if rest.is_empty() || live.push(&rest).is_ok() { + let _ = app.session.offer_live_retouch(live); + } + } + EngineStroke::Dab(mut live) if dab => { + if rest.is_empty() || live.push(&rest).is_ok() { + let _ = app.session.offer_live_dab(live); + } + } + _ => {} + } +} + +/// A pen tap (a drag still at its one press point when released) paints its dab at the highest +/// pressure the pen reached during the contact, not just the first sample's (#1798). A mouse is +/// unchanged at full pressure. +pub(super) fn tap_at_peak_pressure(app: &mut PhotocraftApp) { + if app.stylus.sample().is_none() { + return; + } + let peak = f64::from(app.stylus.tap_pressure()); + let mut refresh_mixer = false; + if let Some(d) = app.drag.as_mut().filter(|d| d.points.len() == 1) + && let Some(p) = d.points.first_mut() + { + refresh_mixer = d.tool == Tool::MixerBrush && peak > p[2]; + p[2] = p[2].max(peak); + } + if refresh_mixer { + app.live_stroke = begin_live_stroke(app); + } +} + +/// While a stroke is held still, its point repeats this often (in ms) so time-based brush +/// features (airbrush build-up, smoothing catch-up) keep going, as when the pen moves. +pub(super) const HOLD_REPEAT_MS: f64 = 16.0; + +/// Is the live stroke one that changes while the pointer is held still (airbrush Build-up, or +/// smoothing catching up)? Only then does a held pointer repeat its point and keep repainting. +pub(super) fn stroke_wants_time(app: &PhotocraftApp) -> bool { + app.live_stroke.as_ref().is_some_and(|l| l.stroke.wants_time()) +} + +/// Time of sample `k` of the `n` samples a frame delivered, spread evenly after `base` (the +/// previous point) up to `now` (this frame): egui's pointer events carry no timestamps. +pub(crate) fn spread_ms(base: f64, now: f64, k: usize, n: usize) -> f64 { + // Not after `base` (or not comparable, NaN): every sample takes the frame time. + if n == 0 || now.partial_cmp(&base) != Some(std::cmp::Ordering::Greater) { + return now; + } + base + (now - base) * (k + 1) as f64 / n as f64 +} + +/// Tools whose gesture follows a freehand path (a polyline of the input points), so every pointer +/// sample the OS delivered improves the result. Other tools are driven by the pointer's latest +/// position (endpoints, anchors, guides), so feeding them a whole frame's moves only repeats work. +pub(crate) fn freehand_tool(tool: Tool) -> bool { + matches!( + tool, + Tool::Brush + | Tool::Pencil + | Tool::MixerBrush + | Tool::ColorReplacement + | Tool::Eraser + | Tool::BackgroundEraser + | Tool::HistoryBrush + | Tool::Remove + | Tool::ArtHistoryBrush + | Tool::SpotHealing + | Tool::Healing + | Tool::CloneStamp + | Tool::PatternStamp + | Tool::Blur + | Tool::Sharpen + | Tool::Smudge + | Tool::Dodge + | Tool::Burn + | Tool::Sponge + | Tool::Lasso + | Tool::MagneticLasso + | Tool::Patch + | Tool::ContentAwareMove + | Tool::QuickSelection + | Tool::FreeformPen + ) +} + +/// The pointer moves this frame delivered while `button` was held, in order. `down_at_start` is +/// whether the button was already down when the frame began. A move before a press or after a +/// release in the same frame is dropped, so a gesture never picks up input from outside its own +/// press..release interval. +pub(super) fn pointer_moves(events: &[egui::Event], button: egui::PointerButton, down_at_start: bool) -> Vec { + let mut down = down_at_start; + let mut out = Vec::new(); + for e in events { + match e { + egui::Event::PointerButton { button: b, pressed, .. } if *b == button => down = *pressed, + egui::Event::PointerMoved(p) if down => out.push(*p), + _ => {} + } + } + out +} + +/// Modifiers attached to the pointer event itself. Some input sources provide these without a +/// separate `ModifiersChanged` event, so use them for click gestures before falling back to the +/// frame-wide modifier state. +pub(super) fn pointer_button_modifiers(events: &[egui::Event], button: egui::PointerButton) -> Option { + events.iter().rev().find_map(|e| match e { + egui::Event::PointerButton { button: b, modifiers, .. } if *b == button => Some(*modifiers), + _ => None, + }) +} + +/// The line from the brush to the pointer while stroke smoothing lags (Pulled String Mode and +/// Stroke Catch-up, #3479): a dark underlay and a light line stay visible on any pixels, and a dot +/// marks the brush end. +pub(super) fn draw_smoothing_string(painter: &egui::Painter, xf: &ViewXform, (brush, pointer): ([f64; 2], [f64; 2])) { + let (a, b) = (xf.to_screen(brush[0] as f32, brush[1] as f32), xf.to_screen(pointer[0] as f32, pointer[1] as f32)); + if a.distance(b) < 2.0 { + return; + } + painter.line_segment([a, b], Stroke::new(3.0, Color32::from_black_alpha(110))); + painter.line_segment([a, b], Stroke::new(1.0, Color32::WHITE)); + painter.circle_filled(a, 2.5, Color32::WHITE); +} + +/// Commit a Brush, Pencil or Eraser drag. The live stroke already rendered it: its pixels are +/// offered to the commit (`Session::offer_live_stroke`), so release costs no second render, and +/// the canvas then refreshes only what it hadn't shown yet (`CommittedStroke`). +pub(super) fn commit_brush_stroke(app: &mut PhotocraftApp, d: &Drag) { + let live = app.live_stroke.take(); + let mut p = stroke_params(app, d, &app.stylus.stroke_points(&d.points)); + if let Some(seed) = live.as_ref().and_then(|l| l.stroke.seed()) { + p["seed"] = json!(seed); + } + let Some(mut l) = live else { + let _ = app.run(stroke_command(app, d.tool), p); + return; + }; + // Points the live stroke hasn't rendered yet (the release frame's last moves). + let t0 = app.stylus.point_ms(0); + let rest: Vec<_> = (l.fed..d.points.len()) + .filter_map(|i| { + let q = d.points.get(i)?; + let t = app.stylus.stroke.get(i).or(app.stylus.stroke.last()).copied().unwrap_or_default(); + let mut sp = photocraft_engine::paint::StrokePoint::new(q[0], q[1], q[2] as f32); + (sp.tilt_x, sp.tilt_y, sp.rotation) = (t[0], t[1], t[2]); + sp.time = app.stylus.point_ms(i) - t0; + Some(sp) + }) + .collect(); + if !rest.is_empty() { + match l.stroke.push(&rest) { + Ok(r) => l.damage.push(r), + // The live stroke can't show these points: the commit renders the stroke itself. + Err(_) => { + let _ = app.run(stroke_command(app, d.tool), p); + return; + } + } + } + let LiveStroke { stroke, doc, key, damage, .. } = l; + let before = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| st.doc.clone()); + if let EngineStroke::Brush(stroke) = stroke + && app.session.offer_live_stroke(*stroke).is_err() + { + app.session.clear_live_stroke(); + } + let started = crate::gpu_canvas::now_ms(); + let result = app.run(stroke_command(app, d.tool), p); + app.stroke_trace.stroke(crate::gpu_canvas::now_ms() - started); + app.session.clear_live_stroke(); + let Ok(r) = result else { return }; + let after = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| (st.revision, st.doc.clone())); + if r.get("fromLive").and_then(serde_json::Value::as_bool) == Some(true) + && let Some((revision, after)) = after + { + let relayout = before.map_or(DRect::EMPTY, |b| photocraft_compose::relayout_damage(&b, &after)); + app.committed_stroke = Some(CommittedStroke { doc, revision, key, damage, relayout }); + } else { + // Rendered again from scratch: the commit's damage rect refreshes the stroke. + let shown = CommittedStroke { doc, revision: 0, key, damage, relayout: DRect::EMPTY }; + // Raw preview key 0 = the document itself (its colour display folded in). + shown_as_document(app, doc, |k| shown.since(k).is_some()); + } +} + +/// Pencil (and a Pencil-mode Eraser) dabs sit on the pixel grid. Clicks anywhere inside one +/// pixel must produce the same point, or a ⇧-click line changes with the sub-pixel position. +pub(super) fn snap_aliased_tip(app: &PhotocraftApp, tool: Tool, x: f64, y: f64) -> (f64, f64) { + let pencil = tool == Tool::Pencil || crate::eraser_ui::pencil_mode(app, tool); + if !pencil { + return (x, y); + } + let (cx, cy) = photocraft_engine::paint::grid_center(x, y, app.session.tools.brush.size); + (f64::from(cx), f64::from(cy)) +} + +/// "mask" when the Layers panel targets (or the canvas shows) the active layer's mask, or the layer +/// is an adjustment layer with one (it has no pixels: #4298), else "pixels". +pub fn paint_target(app: &PhotocraftApp) -> serde_json::Value { + use photocraft_engine::channel_cmds::ChannelTarget; + let Some(st) = app.session.active() else { return json!("pixels") }; + // A targeted alpha channel (Channels panel) or Quick Mask mode wins over the layer. + match st.channel_view.target { + ChannelTarget::Alpha(i) if i < st.doc.channels.len() => return json!({ "channel": i }), + ChannelTarget::Composite if st.doc.quick_mask.is_some() => return json!("quickMask"), + ChannelTarget::LayerMask => return json!("mask"), + _ => {} + } + // A smart object's targeted (or shown) filter mask takes the paint (FILE-215-3). + if app.filter_mask_targeted() { + return json!("filterMask"); + } + let has_mask = st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.mask.is_some()); + // Viewing the mask (⌥-click its thumbnail, #196) paints the mask. + let viewing = photocraft_engine::mask_view_cmds::current(st).is_some_and(|v| !v.filter); + let mask = app.ui.mask_target || viewing || crate::adjustment_layer_active(st); + json!(if mask && has_mask { "mask" } else { "pixels" }) +} diff --git a/crates/ui-egui/src/canvas/tabs.rs b/crates/ui-egui/src/canvas/tabs.rs new file mode 100644 index 0000000000..5f59f3c028 --- /dev/null +++ b/crates/ui-egui/src/canvas/tabs.rs @@ -0,0 +1,732 @@ +use super::start_screen::start_screen; +use super::textures::retain_gpu_documents; +use super::*; + +/// Tabs + canvas for the active document, or the start screen; then drops layers dragged onto +/// another document (`layer_transfer`). +pub fn document_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + crate::distort_ui::drop_foreign(app); + documents(app, ui); + crate::layer_transfer::finish(app, ui.ctx()); + // Once a frame, not per document view: the right-click or options-bar Brush Preset picker. + crate::paint_mouse::show_picker(app, ui.ctx()); +} + +/// Window › Arrange tiles: each document shown with its tile in `rect`, or `None` when the +/// active document fills the area. +pub(crate) fn arranged_cells(app: &PhotocraftApp, rect: Rect) -> Option> { + let idx = app.session.active_index()?; + let n = app.session.documents().len(); + let cells = crate::view_cmds::cells(&app.ui.view.arrange, rect, n)?; + // Each document keeps its tile: a click into another one activates it where it is (#6017; it + // used to move to the first tile). With more documents than tiles, the shown run stays put + // while the active document is in it, and otherwise slides only as far as it must. + let start = app.arrange_start.min(n.saturating_sub(cells.len())); + let start = if idx < start { idx } else { start.max((idx + 1).saturating_sub(cells.len())) }; + Some((start..n).zip(cells).collect()) +} + +fn documents(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + app.drop_canvas_rect = None; + app.tab_strip = None; + retain_gpu_documents(app); + crate::transform_tool::track_steps(app, ui.ctx()); + crate::cas_transform::tick(app, ui.ctx()); + crate::symmetry_ui::track(app, ui.ctx()); + let n = app.session.documents().len(); + // Files opening in the background (#210) have tabs before they have documents. + let opening = !app.jobs.opens.is_empty(); + if !opening && app.ui.chrome.shows_home(n, app.session.prefs().general.auto_show_home_screen) { + start_screen(app, ui); + return; + } + if n == 0 && !opening { + // Auto show the Home Screen is off: an empty workspace, like Photoshop. + let area = ui.available_rect_before_wrap(); + paint_dots(ui, area, app.session.prefs().interface.show_canvas_dots); + open_on_double_click(app, ui, area); + return; + } + if !app.ui.view.hides_tabs() || opening { + // Flat Spectrum tabs sit directly against the canvas. The parent's default vertical + // item spacing would otherwise leave a visible gap below the tab strip (#2188). + let spacing = ui.spacing().item_spacing.y; + if crate::theme::Tokens::get(ui.ctx()).pro { + ui.spacing_mut().item_spacing.y = 0.0; + } + app.tab_strip = Some(tabs(app, ui)); + ui.spacing_mut().item_spacing.y = spacing; + drop_slot_line(app, ui); + } + if let Some(job) = app.jobs.focus.or_else(|| (n == 0).then(|| app.jobs.opens.last().map(|o| o.job)).flatten()) { + crate::jobs_ui::open_card(app, ui, job); + return; + } + let Some(idx) = app.session.active_index() else { return }; + let rect = ui.available_rect_before_wrap(); + app.last_canvas_rect = rect; + app.drop_canvas_rect = Some(rect); + // Window › Arrange: tiled / n-up layouts show several documents side by side; the active one + // takes input, a click elsewhere activates that document. + if let Some(shown) = arranged_cells(app, rect) { + app.arrange_start = shown.first().map_or(0, |(d, _)| *d); + let t = crate::theme::Tokens::get(ui.ctx()); + for (d, cell) in shown { + let cell = cell.shrink(1.0); + let view = app.ui.views[d].clone(); + let v = canvas_view(app, ui, d, cell, view, d == idx); + if d != idx { + app.ui.views[d] = v; + if ui.input(|i| i.pointer.primary_pressed() && i.pointer.interact_pos().is_some_and(|p| cell.contains(p))) { + app.session.set_active(d); + } + } + let stroke = if d == idx { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, Color32::from_black_alpha(160)) }; + ui.painter().rect_stroke(cell, 0, stroke, egui::StrokeKind::Inside); + } + return; + } + let view = app.ui.views[idx].clone(); + canvas_view(app, ui, idx, rect, view, true); +} + +/// The tab strip; returns where its document tabs are. +pub(super) fn tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { + let t = crate::theme::Tokens::get(ui.ctx()); + if t.pro { + return pro_tabs(app, ui); + } + let active = app.session.active_index(); + let tab_count = app.session.documents().len(); + let mut doc_tabs = Vec::with_capacity(tab_count); + let mut activate = None; + let mut close = None; + let mut tab_action = None; + let mut tab_move = None; + let mut tear_off = None; + let (mut focus_open, mut cancel_open) = (None, None); + let focused_open = app.jobs.focus.is_some(); + // Layers dragged over a tab show its document (`layer_transfer`). + let dragging = crate::layer_transfer::pointer_if_armed(app, ui.ctx()); + let mut drag_over = None; + let large_tabs = app.session.prefs().workspace.large_tabs; + let tab_h = if large_tabs { 34.0 } else { 26.0 }; + let font = crate::theme::medium(if large_tabs { 14.0 } else { 12.5 }); + let meta_font = egui::FontId::proportional(if large_tabs { 12.0 } else { 10.5 }); + // Files opening in the background (#210) are tabs too; they share the fit's index space, + // after the documents. + let opening = crate::jobs_ui::open_tabs(app); + // Every tab's natural width, whether or not it stays on the strip. + let natural: Vec = app + .session + .documents() + .iter() + .map(|st| { + let name = studio_tab_name(app, st); + ui.painter().layout_no_wrap(name, font.clone(), t.text).size().x + + ui.painter().layout_no_wrap(format!("{}/{}", mode_label(&st.doc), st.doc.depth.bits()), meta_font.clone(), t.text_faint).size().x + + STUDIO_TAB_PAD + }) + .chain(opening.iter().map(|(_, name, frac)| { + ui.painter().layout_no_wrap(name.clone(), font.clone(), t.text).size().x + + ui.painter().layout_no_wrap(format!("{:.0}%", frac * 100.0), meta_font.clone(), t.text_faint).size().x + + STUDIO_TAB_PAD + })) + .collect(); + let selected = app + .jobs + .focus + .and_then(|job| opening.iter().position(|(open, _, _)| *open == job)) + .map_or_else(|| app.session.active_index().unwrap_or(0), |p| tab_count + p); + let frame = egui::Frame::NONE.fill(t.canvas).inner_margin(egui::Margin { left: 8, right: 8, top: 6, bottom: 4 }).show(ui, |ui| { + let (row, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), tab_h), Sense::hover()); + let f = fit_doc_tabs(&natural, selected, row.width()); + let mut x = row.left(); + let mut placed: Vec<(usize, Rect)> = Vec::with_capacity(f.shown.len()); + for &(i, w) in &f.shown { + // The old horizontal layout put 4 pt between tabs; `w` carries it, the tab doesn't. + let r = Rect::from_min_size(egui::pos2(x, row.top()), egui::vec2((w - STUDIO_TAB_GAP).max(8.0), row.height())); + placed.push((i, r)); + x = r.right() + STUDIO_TAB_GAP; + } + for &(i, r) in placed.iter().filter(|(i, _)| *i < tab_count) { + let Some(st) = app.session.documents().get(i) else { continue }; + let sel = Some(i) == active && !focused_open; + let name = studio_tab_name(app, st); + let meta = format!("{}/{}", mode_label(&st.doc), st.doc.depth.bits()); + let natural_w = natural.get(i).copied().unwrap_or(0.0); + let meta_g = ui.painter().layout_no_wrap(meta, meta_font.clone(), t.text_faint); + let name_max = (r.width() - STUDIO_TAB_PAD + STUDIO_TAB_GAP - meta_g.size().x).max(1.0); + let name_g = crate::tab_strip::elided(ui, &name, font.clone(), t.text, name_max); + // The title was cut: the tooltip has the rest of it. + let cut = name_g.size().x + 0.5 < natural_w - STUDIO_TAB_PAD + STUDIO_TAB_GAP - meta_g.size().x; + let resp = ui.interact(r, ui.scope_id().with(("dtab", i)), Sense::click_and_drag()); + let saving = crate::jobs_ui::save_progress(app, st.doc.id); + resp.widget_info(|| { + let label = saving.as_ref().map_or_else(|| st.doc.name.clone(), |s| format!("{} - {s}", st.doc.name)); + egui::WidgetInfo::selected(egui::Role::Button, true, sel, label) + }); + doc_tabs.push((i, r)); + if sel { + ui.painter().rect_filled(r, t.radius_sm, t.card); + ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); + } else if resp.hovered() { + ui.painter().rect_filled(r, t.radius_sm, t.hover.gamma_multiply(0.5)); + } + if dragging.is_some_and(|p| r.contains(p)) { + drag_over = Some(i); + ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); + } + let color = if sel { t.text } else { t.text_dim }; + let ny = r.center().y - name_g.size().y / 2.0; + ui.painter().galley_with_override_text_color(egui::pos2(r.left() + 10.0, ny), name_g.clone(), color); + ui.painter().galley(egui::pos2(r.left() + 16.0 + name_g.size().x, r.center().y - meta_g.size().y / 2.0), meta_g, t.text_faint); + let xr = Rect::from_center_size(egui::pos2(r.right() - 12.0, r.center().y), egui::vec2(16.0, 16.0)); + let xresp = ui.interact(xr, ui.scope_id().with(("dtabx", i)), Sense::click()); + if xresp.hovered() { + ui.painter().rect_filled(xr, 4.0, t.hover); + } + crate::icons::paint(ui, xr, "x", 11.0, if xresp.hovered() { t.text } else { t.text_faint }); + let resp = if cut { resp.on_hover_text(name) } else { resp }; + if tab_close_clicked(&resp, &xresp) { + close = Some(i); + } else if resp.clicked() { + activate = Some(i); + } + match tab_drag(ui, &resp, i, r, row, &placed, &t) { + Some(TabDrop::Move(to)) => tab_move = Some((i, to)), + Some(TabDrop::Float(at)) => tear_off = Some((i, at)), + None => {} + } + let has_path = st.path.is_some(); + resp.context_menu(|ui| { + tab_action = tab_context_menu(ui, i, tab_count, has_path); + }); + } + // Files opening in the background: a tab with a progress underline; × cancels. + for &(i, r) in placed.iter().filter(|(i, _)| *i >= tab_count) { + let Some((job, name, frac)) = opening.get(i - tab_count) else { continue }; + let sel = app.jobs.focus == Some(*job); + let meta_g = ui.painter().layout_no_wrap(format!("{:.0}%", frac * 100.0), meta_font.clone(), t.text_faint); + let name_g = crate::tab_strip::elided(ui, name, font.clone(), t.text, (r.width() - STUDIO_TAB_PAD + STUDIO_TAB_GAP - meta_g.size().x).max(1.0)); + let resp = ui.interact(r, ui.scope_id().with(("dtabjob", job.0)), Sense::click()); + if sel { + ui.painter().rect_filled(r, t.radius_sm, t.card); + ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside); + } else if resp.hovered() { + ui.painter().rect_filled(r, t.radius_sm, t.hover.gamma_multiply(0.5)); + } + let ny = r.center().y - name_g.size().y / 2.0; + ui.painter().galley_with_override_text_color(egui::pos2(r.left() + 10.0, ny), name_g.clone(), if sel { t.text } else { t.text_dim }); + ui.painter().galley(egui::pos2(r.left() + 16.0 + name_g.size().x, r.center().y - meta_g.size().y / 2.0), meta_g, t.text_faint); + crate::jobs_ui::tab_underline(ui, r, *frac, &t); + let xr = Rect::from_center_size(egui::pos2(r.right() - 12.0, r.center().y), egui::vec2(16.0, 16.0)); + let xresp = ui.interact(xr, ui.scope_id().with(("dtabjobx", job.0)), Sense::click()); + if xresp.hovered() { + ui.painter().rect_filled(xr, 4.0, t.hover); + } + crate::icons::paint(ui, xr, "x", 11.0, if xresp.hovered() { t.text } else { t.text_faint }); + if xresp.on_hover_text(tl!("Cancel opening")).clicked() { + cancel_open = Some(*job); + } else if resp.clicked() { + focus_open = Some(*job); + } + } + if !f.overflow.is_empty() { + // Pinned to the strip's right end, as Photoshop's is, not after the last tab (#8290). + let left = (row.right() - crate::tab_strip::CHEVRON_W).max(row.left()); + let r = Rect::from_min_size(egui::pos2(left, row.top()), egui::vec2(crate::tab_strip::CHEVRON_W, row.height())); + let labels: Vec<&str> = + app.session.documents().iter().map(|st| st.doc.name.as_str()).chain(opening.iter().map(|(_, name, _)| name.as_str())).collect(); + let mut picked = None; + // Like Photoshop's, the menu lists every open document, not only the hidden ones, and checks + // the active one (#4487). + let every: Vec = (0..labels.len()).collect(); + crate::tab_strip::overflow_button(ui, ui.scope_id().with("dtab-overflow"), r, tl!("More documents"), &labels, &every, Some(selected), &mut picked); + match picked { + Some(i) if i < tab_count => activate = Some(i), + Some(i) => focus_open = opening.get(i - tab_count).map(|(job, _, _)| *job).or(focus_open), + None => {} + } + } + }); + open_tab_clicks(app, activate, focus_open, cancel_open); + if let Some(i) = drag_over { + crate::layer_transfer::over_tab(app, ui.ctx(), i); + } + if let Some(i) = close { + let _ = crate::menus::invoke(app, ui.ctx(), "file.close", json!({"document": i})); + } + if let Some((from, to)) = tab_move + && let Err(e) = crate::menus::invoke(app, ui.ctx(), "document.move", json!({"document": from, "to": to})) + { + app.ui.status = e; + app.ui.status_error = true; + } + float_torn_off(app, ui.ctx(), tear_off); + if let Some((id, params)) = tab_action + && let Err(e) = crate::menus::invoke(app, ui.ctx(), id, params) + { + app.ui.status = e; + app.ui.status_error = true; + } + TabStrip { rect: frame.response.rect, tabs: doc_tabs } +} + +/// Whether a document tab was asked to close: its × was clicked (#619), or the tab was clicked +/// with the middle button (#2570), as in a browser. A middle click over the × counts too, so the +/// whole tab behaves the same way. Both strips share this rule; the caller routes it through the +/// guarded `file.close`, so a document with unsaved changes still gets the save prompt. +fn tab_close_clicked(resp: &egui::Response, xresp: &egui::Response) -> bool { + xresp.clicked() || xresp.middle_clicked() || resp.middle_clicked() +} + +/// All tab actions go through the same guarded File commands as the menu bar, including the +/// unsaved-changes prompt. The clicked tab is explicit even when another document is active. +pub(super) fn tab_context_items(index: usize, count: usize, has_path: bool) -> [(&'static str, &'static str, serde_json::Value, bool); 4] { + [ + ("Close", "file.close", json!({"document": index}), true), + ("Close Others", "file.closeOthers", json!({"document": index}), count > 1), + ("Close All", "file.closeAll", json!({}), true), + (crate::menus::reveal_label(), "file.revealInFinder", json!({"document": index}), has_path), + ] +} + +fn tab_context_menu(ui: &mut egui::Ui, index: usize, count: usize, has_path: bool) -> Option<(&'static str, serde_json::Value)> { + crate::widgets::menu_scroll(ui, |ui| { + ui.set_min_width(170.0); + for (label, id, params, enabled) in tab_context_items(index, count, has_path) { + if ui.add_enabled(enabled, egui::Button::new(tl!(label))).clicked() { + ui.close(); + return Some((id, params)); + } + } + None + }) +} + +/// Where a tab dragged to `x` would land: before the first shown tab whose middle is right of +/// `x`, else after the last shown tab (its document index + 1), like [`TabStrip::slot`]. +/// How far (points) above or below the tab strip a dragged tab must be to tear off (#3733). +pub(super) const TEAR_OFF: f32 = 24.0; + +/// Whether a tab dragged to `p` has left the strip and floats into its own window, as in +/// Photoshop; sideways drags along the strip still reorder (#217). +pub(super) fn torn_off(strip: Rect, p: egui::Pos2) -> bool { + p.y > strip.bottom() + TEAR_OFF || p.y < strip.top() - TEAR_OFF +} + +/// What a finished document-tab drag asks for. +#[derive(Clone, Copy, Debug, PartialEq)] +enum TabDrop { + /// Reorder the tab to this index. + Move(usize), + /// Float the document in its own OS window at this screen position (points), when known. + Float(Option<[f32; 2]>), +} + +/// Drag a document tab: along the strip it reorders (a line shows where it will land); off the +/// strip it tears off into a floating window that can go anywhere, other screens included +/// (an outline under the pointer shows it). Returns the drop once the drag ends. +fn tab_drag(ui: &egui::Ui, resp: &egui::Response, i: usize, r: Rect, strip: Rect, placed: &[(usize, Rect)], t: &crate::theme::Tokens) -> Option { + if resp.dragged() + && let Some(p) = resp.interact_pointer_pos() + { + if torn_off(strip, p) { + let ghost = Rect::from_min_size(p - egui::vec2(40.0, 12.0), egui::vec2(240.0, 160.0)); + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, ui.scope_id().with("tab-tear-off"))); + painter.rect_filled(ghost, t.radius_sm, t.accent.gamma_multiply(0.12)); + painter.rect_stroke(ghost, t.radius_sm, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); + } else { + tab_drop_line(ui, placed, p.x, t); + } + } + if !resp.drag_stopped() { + return None; + } + let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.interact_pos())); + if let Some(p) = p.filter(|&p| torn_off(strip, p)) { + // The pointer is in this window's points; the OS wants screen coordinates. Keep the new + // window's title bar under the pointer, as the ghost showed. + let at = ui.ctx().input(|i| i.viewport().inner_rect).map(|inner| { + let s = inner.min + p.to_vec2() - egui::vec2(40.0, 12.0); + [s.x, s.y] + }); + return Some(TabDrop::Float(at)); + } + let to = tab_move_target(i, tab_drop_index(placed, p.map_or(r.center().x, |p| p.x))); + (to != i).then_some(TabDrop::Move(to)) +} + +/// Float a torn-off tab's document in its own window (`window.arrange.floatInWindow`). +fn float_torn_off(app: &mut PhotocraftApp, ctx: &egui::Context, tear_off: Option<(usize, Option<[f32; 2]>)>) { + let Some((doc, at)) = tear_off else { return }; + let params = match at { + Some(at) => json!({"document": doc, "position": at}), + None => json!({"document": doc}), + }; + if let Err(e) = crate::menus::invoke(app, ctx, "window.arrange.floatInWindow", params) { + app.ui.status = e; + app.ui.status_error = true; + } +} + +pub(super) fn tab_drop_index(placed: &[(usize, Rect)], x: f32) -> usize { + match placed.iter().find(|(_, r)| r.center().x >= x) { + Some(&(i, _)) => i, + None => placed.last().map_or(0, |&(i, _)| i.saturating_add(1)), + } +} + +/// The `document.move` target for dropping the tab at `from` at insertion index `k`: the slot +/// shifts down when the dragged tab itself is removed first; next to itself it stays put. +pub(super) fn tab_move_target(from: usize, k: usize) -> usize { + if k > from { k - 1 } else { k } +} + +/// The insertion line shown while a tab is dragged to reorder it. +fn tab_drop_line(ui: &egui::Ui, placed: &[(usize, Rect)], x: f32, t: &crate::theme::Tokens) { + match placed.iter().find(|(_, r)| r.center().x >= x) { + Some(&(_, r)) => crate::widgets::drop_line(ui, r, false, true, t), + None => { + if let Some(&(_, r)) = placed.last() { + crate::widgets::drop_line(ui, r, true, true, t); + } + } + } +} + +/// Apply tab-strip clicks: a document tab shows that document, an opening tab its progress, and +/// an opening tab's × cancels the open (closing the half-open tab). +fn open_tab_clicks( + app: &mut PhotocraftApp, + activate: Option, + focus_open: Option, + cancel_open: Option, +) { + if let Some(i) = activate { + app.session.set_active(i); + app.jobs.focus = None; + } + if let Some(job) = focus_open { + app.jobs.focus = Some(job); + } + if let Some(job) = cancel_open { + crate::jobs_ui::cancel(app, job); + } +} + +/// Document tabs: the chrome around a title (the × and its gaps). +const DOC_TAB_PAD: f32 = 42.0; + +/// The Studio strip's tabs carried 4 pt of spacing between them and 44 pt of chrome; `fit` sees +/// one number per tab, so the gap rides in the natural width and comes back out when painted. +const STUDIO_TAB_PAD: f32 = 48.0; + +const STUDIO_TAB_GAP: f32 = 4.0; + +/// Fit document tabs as Photoshop does (#4487): a tab never shrinks below its whole title, so the +/// tabs that don't fit move into the » menu instead. Only the active tab, when it alone is wider +/// than the strip, is cut. +fn fit_doc_tabs(natural: &[f32], selected: usize, avail: f32) -> crate::tab_strip::TabFit { + let widest = natural.iter().copied().filter(|w| w.is_finite()).fold(0.0, f32::max); + crate::tab_strip::fit(natural, selected, avail, widest, crate::tab_strip::CHEVRON_W) +} + +/// Photoshop's tab title: "name @ 50% (Layer 1, RGB/8)", "(Layer 1, Layer Mask/8)" when the mask +/// is targeted, "(Quick Mask/8)" in Quick Mask mode; the Background layer's name is omitted. +pub(super) fn pro_tab_title(app: &PhotocraftApp, i: usize) -> String { + use photocraft_engine::channel_cmds::ChannelTarget; + let Some(st) = app.session.documents().get(i) else { return String::new() }; + let zoom = app.ui.views.get(i).map_or(100.0, |v| v.zoom * 100.0); + // Quick Mask mode targets the mask, not the layer (see `paint_target`): painting and Free + // Transform change the red overlay, so the tab says so, as Photoshop's does. + let quick_mask = st.doc.quick_mask.is_some() && st.channel_view.target == ChannelTarget::Composite; + let active_layer = st.active_layer.and_then(|id| st.doc.layer(id)).filter(|l| !quick_mask && !st.doc.is_background(l.id)); + let mask = app.session.active_index() == Some(i) && app.ui.mask_target && active_layer.is_some_and(|l| l.mask.is_some()); + let model = if quick_mask { + tl!("Quick Mask").to_string() + } else if mask { + tl!("Layer Mask").to_string() + } else { + mode_label(&st.doc).to_string() + }; + let layer = active_layer.map(|l| format!("{}, ", l.name)).unwrap_or_default(); + // A save in progress: "name @ 100% (Layer 1, RGB/16) - Saving 45%", as Photoshop does (#3389). + let saving = crate::jobs_ui::save_progress(app, st.doc.id).map(|s| format!(" - {s}")).unwrap_or_default(); + format!("{} @ {}% ({layer}{model}/{}){}{saving}", st.doc.name, fmt_zoom(zoom), st.doc.depth.bits(), if st.is_dirty() { "*" } else { "" }) +} + +/// The Studio strip's tab name: "name *" when unsaved, "name * - Saving 45%" while it saves (#3389). +fn studio_tab_name(app: &PhotocraftApp, st: &photocraft_engine::DocState) -> String { + let saving = crate::jobs_ui::save_progress(app, st.doc.id).map(|s| format!(" - {s}")).unwrap_or_default(); + format!("{}{}{saving}", st.doc.name, if st.is_dirty() { " *" } else { "" }) +} + +/// Photoshop document tabs: "name @ 33.3% (RGB/8)" on a dark strip; active tab matches panels. +/// Tabs keep their whole titles, and the ones that don't fit move into a » menu at the end of the +/// strip; the active document's tab always stays on the strip (#1276, #4487). +fn pro_tabs(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> TabStrip { + let t = crate::theme::Tokens::get(ui.ctx()); + let active = app.session.active_index().filter(|_| app.jobs.focus.is_none()); + let (mut activate, mut close) = (None, None); + let mut tab_action = None; + let mut tab_move = None; + let mut tear_off = None; + let tab_count = app.session.documents().len(); + let dragging = crate::layer_transfer::pointer_if_armed(app, ui.ctx()); + let mut drag_over = None; + let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac; + let large_tabs = app.session.prefs().workspace.large_tabs; + let font = egui::FontId::proportional(if large_tabs { 13.0 } else { 11.5 }); + let tab_h = if large_tabs { 34.0 } else { 26.0 }; + let (strip, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), tab_h), Sense::hover()); + ui.painter().rect_filled(strip, 0.0, t.tab_strip); + // Files opening in the background (#210) are tabs too ("name (Opening… 45%)" with a progress + // underline); they share the fit's index space, after the documents. + let opening = crate::jobs_ui::open_tabs(app); + let mut titles: Vec = (0..tab_count).map(|i| pro_tab_title(app, i)).collect(); + titles.extend(opening.iter().map(|(_, name, frac)| format!("{name} ({} {:.0}%)", tl!("Opening…"), frac * 100.0))); + // Every tab's natural width, whether or not it stays on the strip. + let natural: Vec = titles.iter().map(|title| ui.painter().layout_no_wrap(title.clone(), font.clone(), t.text).size().x + DOC_TAB_PAD).collect(); + let selected = app + .jobs + .focus + .and_then(|job| opening.iter().position(|(open, _, _)| *open == job)) + .map_or_else(|| app.session.active_index().unwrap_or(0), |p| tab_count + p); + let f = fit_doc_tabs(&natural, selected, strip.width()); + let mut x = strip.left(); + let mut placed: Vec<(usize, Rect)> = Vec::with_capacity(f.shown.len()); + for &(i, w) in &f.shown { + let r = Rect::from_min_size(egui::pos2(x, strip.top()), egui::vec2(w, strip.height())); + placed.push((i, r)); + x = r.right(); + } + let mut doc_tabs = Vec::with_capacity(tab_count); + let (mut focus_open, mut cancel_open) = (None, None); + for &(i, r) in placed.iter().filter(|(i, _)| *i < tab_count) { + let Some(title) = titles.get(i) else { continue }; + let g = crate::tab_strip::elided(ui, title, font.clone(), t.text, (r.width() - DOC_TAB_PAD).max(1.0)); + let resp = ui.interact(r, ui.scope_id().with(("ptab", i)), Sense::click_and_drag()); + let sel = Some(i) == active; + if sel { + ui.painter().rect_filled(r, 0.0, t.chrome); + } else if resp.hovered() { + ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.35)); + } + if dragging.is_some_and(|p| r.contains(p)) { + drag_over = Some(i); + ui.painter().rect_stroke(r, 0.0, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); + } + ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.0, t.separator)); + let (xr, at) = pro_tab_layout(r, g.size().y, mac); + let xresp = ui.interact(xr, ui.scope_id().with(("ptabx", i)), Sense::click()); + // Painted: name the tab and its × for accessibility (and so tests and agents can find them). + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, sel, g.text())); + xresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Close"))); + crate::icons::paint(ui, xr, "x", 10.0, if xresp.hovered() { t.text } else { t.text_faint }); + ui.painter().galley_with_override_text_color(at, g, if sel { t.text } else { t.text_faint }); + let cut = natural.get(i).copied().unwrap_or(0.0) > r.width() + 0.5; + let resp = if cut { resp.on_hover_text(title.as_str()) } else { resp }; + if tab_close_clicked(&resp, &xresp) { + close = Some(i); + } else if resp.clicked() { + activate = Some(i); + } + match tab_drag(ui, &resp, i, r, strip, &placed, &t) { + Some(TabDrop::Move(to)) => tab_move = Some((i, to)), + Some(TabDrop::Float(at)) => tear_off = Some((i, at)), + None => {} + } + let has_path = app.session.documents().get(i).is_some_and(|d| d.path.is_some()); + resp.context_menu(|ui| { + tab_action = tab_context_menu(ui, i, tab_count, has_path); + }); + doc_tabs.push((i, r)); + } + for &(i, r) in placed.iter().filter(|(i, _)| *i >= tab_count) { + let Some((job, _, frac)) = opening.get(i - tab_count) else { continue }; + let Some(title) = titles.get(i) else { continue }; + let g = crate::tab_strip::elided(ui, title, font.clone(), t.text, (r.width() - DOC_TAB_PAD).max(1.0)); + let resp = ui.interact(r, ui.scope_id().with(("ptabjob", job.0)), Sense::click()); + let sel = app.jobs.focus == Some(*job); + if sel { + ui.painter().rect_filled(r, 0.0, t.chrome); + } else if resp.hovered() { + ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.35)); + } + ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.0, t.separator)); + crate::jobs_ui::tab_underline(ui, r, *frac, &t); + let (xr, at) = pro_tab_layout(r, g.size().y, mac); + let xresp = ui.interact(xr, ui.scope_id().with(("ptabjobx", job.0)), Sense::click()); + xresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Close"))); + crate::icons::paint(ui, xr, "x", 10.0, if xresp.hovered() { t.text } else { t.text_faint }); + ui.painter().galley_with_override_text_color(at, g, if sel { t.text } else { t.text_faint }); + if xresp.on_hover_text(tl!("Cancel opening")).clicked() { + cancel_open = Some(*job); + } else if resp.clicked() { + focus_open = Some(*job); + } + } + if !f.overflow.is_empty() { + // Pinned to the strip's right end, as Photoshop's is, not after the last tab (#8290). + let left = (strip.right() - crate::tab_strip::CHEVRON_W).max(strip.left()); + let r = Rect::from_min_size(egui::pos2(left, strip.top()), egui::vec2(crate::tab_strip::CHEVRON_W, strip.height())); + let labels: Vec<&str> = titles.iter().map(String::as_str).collect(); + let mut picked = None; + // Like Photoshop's, the menu lists every open document, not only the hidden ones, and checks + // the active one (#4487). + let every: Vec = (0..labels.len()).collect(); + crate::tab_strip::overflow_button(ui, ui.scope_id().with("ptab-overflow"), r, tl!("More documents"), &labels, &every, Some(selected), &mut picked); + match picked { + Some(i) if i < tab_count => activate = Some(i), + Some(i) => focus_open = opening.get(i - tab_count).map(|(job, _, _)| *job).or(focus_open), + None => {} + } + } + open_tab_clicks(app, activate, focus_open, cancel_open); + if let Some(i) = drag_over { + crate::layer_transfer::over_tab(app, ui.ctx(), i); + } + if let Some(i) = close { + let _ = crate::menus::invoke(app, ui.ctx(), "file.close", json!({"document": i})); + } + if let Some((from, to)) = tab_move + && let Err(e) = crate::menus::invoke(app, ui.ctx(), "document.move", json!({"document": from, "to": to})) + { + app.ui.status = e; + app.ui.status_error = true; + } + float_torn_off(app, ui.ctx(), tear_off); + if let Some((id, params)) = tab_action + && let Err(e) = crate::menus::invoke(app, ui.ctx(), id, params) + { + app.ui.status = e; + app.ui.status_error = true; + } + TabStrip { rect: strip, tabs: doc_tabs } +} + +/// Where the document tabs were drawn (opening files' tabs aren't slots): a file dropped on the +/// strip opens at the slot under the pointer. +#[derive(Clone, Debug, PartialEq)] +pub struct TabStrip { + pub rect: Rect, + /// The document tabs shown, left to right, with their document index. When the tabs overflow + /// into the » menu, some documents have no tab here. + pub tabs: Vec<(usize, Rect)>, +} + +impl TabStrip { + /// The document position a drop at `x` opens at: before the first shown tab whose middle is + /// right of it, else after the last shown tab. + pub fn slot(&self, x: f32) -> usize { + match self.tabs.iter().find(|(_, r)| r.center().x >= x) { + Some(&(i, _)) => i, + None => self.tabs.last().map_or(0, |&(i, _)| i.saturating_add(1)), + } + } +} + +/// While files are dragged over the tab strip, an insertion line where they would open. +fn drop_slot_line(app: &mut PhotocraftApp, ui: &egui::Ui) { + if ui.input(|i| i.raw.hovered_files.is_empty()) { + return; + } + let at = app.services.cursor_pos.as_mut().and_then(|f| f(ui.ctx())); + let crate::file_open::DropTarget::Tabs(slot) = app.drop_target(ui.ctx(), at) else { return }; + let Some(tabs) = app.tab_strip.as_ref().map(|s| &s.tabs) else { return }; + let Some((r, after)) = tabs.iter().find(|(i, _)| *i == slot).map(|&(_, r)| (r, false)).or_else(|| tabs.last().map(|&(_, r)| (r, true))) else { + return; + }; + crate::widgets::drop_line(ui, r, after, true, &crate::theme::Tokens::get(ui.ctx())); +} + +/// A Photoshop-style tab's close button and where its title starts. Photoshop puts the × after the +/// title on Windows (and so Linux) and before it on macOS (#619). +fn pro_tab_layout(tab: Rect, title_height: f32, mac: bool) -> (Rect, egui::Pos2) { + let (x, title) = if mac { (tab.left() + 13.0, tab.left() + 26.0) } else { (tab.right() - 13.0, tab.left() + 16.0) }; + (Rect::from_center_size(egui::pos2(x, tab.center().y), egui::vec2(14.0, 14.0)), egui::pos2(title, tab.center().y - title_height / 2.0)) +} + +/// Repeating dot-grid texture for the canvas surround. A theme whose dots are its canvas colour +/// has no pattern to show, so it gets no texture at all rather than an invisible one (#4542). +pub(super) fn dots(ctx: &egui::Context, t: &crate::theme::Tokens) -> Option { + if t.bevel || t.canvas_dot == t.canvas { + return None; + } + let key = egui::Id::unique(("canvas-dots", format!("{:?}", t.kind))); + if let Some(tex) = ctx.data(|d| d.get_temp::(key)) { + return Some(tex.id()); + } + let n = 22usize; + let mut px = vec![Color32::TRANSPARENT; n * n]; + for (dx, dy, a) in [(0usize, 0usize, 255u8), (1, 0, 110), (0, 1, 110), (1, 1, 60)] { + let c = t.canvas_dot; + px[(n / 2 + dy) * n + n / 2 + dx] = Color32::from_rgba_unmultiplied(c.r(), c.g(), c.b(), a); + } + let opts = TextureOptions { + magnification: egui::TextureFilter::Linear, + minification: egui::TextureFilter::Linear, + wrap_mode: egui::TextureWrapMode::Repeat, + mipmap_mode: None, + }; + let tex = ctx.load_texture("canvas-dots", egui::ColorImage::new([n, n], px), opts); + let id = tex.id(); + ctx.data_mut(|d| d.insert_temp(key, tex)); + Some(id) +} + +pub(super) fn paint_dots(ui: &egui::Ui, rect: Rect, enabled: bool) { + if !enabled { + return; + } + let t = crate::theme::Tokens::get(ui.ctx()); + if let Some(id) = dots(ui.ctx(), &t) { + let uv = Rect::from_min_max(Pos2::ZERO, pos2(rect.width() / 22.0, rect.height() / 22.0)); + ui.painter_at(rect).image(id, rect, uv, Color32::WHITE); + } +} + +/// With no document open, double-clicking the empty workspace shows File › Open, as in Photoshop +/// (#5367), and so does the Home screen's blank background. Registered before anything drawn over +/// `area`, so the buttons and links there keep their own clicks; not a keyboard focus stop. +pub(super) fn open_on_double_click(app: &mut PhotocraftApp, ui: &egui::Ui, area: Rect) { + if app.session.documents().is_empty() && ui.interact(area, ui.scope_id().with("empty-workspace"), Sense::CLICK).double_clicked() { + let _ = app.open_dialog_file(); + } +} + +/// Extra OS windows showing documents (multi-window / multi-monitor). +pub fn extra_windows(app: &mut PhotocraftApp, ctx: &egui::Context) { + let wins = app.ui.windows.clone(); + for w in wins.into_iter().filter(|w| w.open) { + let Some(st) = app.session.documents().get(w.document) else { continue }; + let title = format!("{} — window {}", st.doc.name, w.id); + let vid = egui::ViewportId::from_hash_of(("docwin", w.id)); + let mut builder = egui::ViewportBuilder::default().with_title(title).with_inner_size([800.0, 600.0]); + if let Some([x, y]) = w.position { + builder = builder.with_position([x, y]); + } + let mut view = w.view.clone(); + let mut close = false; + ctx.show_viewport_immediate(vid, builder, |ui, class| { + if ui.ctx().input(|i| i.viewport().close_requested()) { + close = true; + } + 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(); + view = canvas_view(app, ui, w.document, rect, view.clone(), false); + // 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); + }); + }); + if let Some(win) = app.ui.windows.iter_mut().find(|x| x.id == w.id) { + win.view = view; + if close { + win.open = false; + } + } + } + app.ui.windows.retain(|w| w.open); +} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 1036161ad5..a2ec365f80 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1183,8 +1183,7 @@ fn clone_overlay_is_circular_and_respects_visibility() { app.run("cloneSource.set", json!({"source": [16,16]})).unwrap(); app.ui.tool = Tool::CloneStamp; app.session.tools.brush.size = 20.0; - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; let revision = app.session.active().unwrap().revision; let mut output = ctx.run_ui(Default::default(), |ui| { let ctx = ui.ctx(); @@ -1233,8 +1232,7 @@ fn clone_overlay_keeps_magnified_pixels_crisp_on_upload_and_refresh() { app.run("cloneSource.set", json!({"source": [16, 16]})).unwrap(); app.ui.tool = Tool::CloneStamp; app.session.tools.brush.size = 20.0; - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 4.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), zoom: 4.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; for invert in [false, true] { app.session.presets.clone.overlay.invert = invert; let mut output = ctx.run_ui(Default::default(), |ui| { @@ -1256,8 +1254,7 @@ fn clone_overlay_blend_mode_mixes_with_the_image_under_the_brush() { app.run("cloneSource.set", json!({"source": [16,16]})).unwrap(); app.ui.tool = Tool::CloneStamp; app.session.tools.brush.size = 20.0; - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; // The centre texel of the overlay texture uploaded for `mode`. let mut centre = |mode: &str| { app.run("cloneSource.overlay", json!({"blend": mode})).unwrap(); @@ -1290,8 +1287,7 @@ fn clone_overlay_is_clipped_to_a_shaped_tip() { app.ui.tool = Tool::CloneStamp; app.session.tools.brush.size = 20.0; app.session.tools.brush.roundness = 0.25; - let xf = - ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 }; let mut output = ctx.run_ui(Default::default(), |ui| { let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("clone-test"))); draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None); @@ -1490,14 +1486,8 @@ fn brush_tip_centre_follows_the_crosshair_preference_at_any_size() { #[test] fn view_transform_roundtrip() { for flip in [false, true] { - let xf = ViewXform { - rect: Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0)), - zoom: 2.5, - center: [320.0, 240.0], - flip, - rotation: 0.0, - aspect: 1.0, - }; + let xf = + ViewXform { rect: Rect::from_min_size(pos2(100.0, 50.0), vec2(800.0, 600.0)), zoom: 2.5, center: [320.0, 240.0], flip, rotation: 0.0, aspect: 1.0 }; let s = xf.to_screen(10.0, 20.0); let d = xf.to_doc(s); assert!((d[0] - 10.0).abs() < 1e-3 && (d[1] - 20.0).abs() < 1e-3); @@ -1913,13 +1903,7 @@ fn mixer_escape_and_tool_switch_cancel_without_an_edit() { let ctx = egui::Context::default(); let mut raw = egui::RawInput { focused: true, ..Default::default() }; if mode == 0 { - raw.events.push(egui::Event::Key { - key: egui::Key::Escape, - physical_key: None, - pressed: true, - repeat: false, - modifiers: egui::Modifiers::NONE, - }); + raw.events.push(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); } if mode == 1 { app.ui.tool = Tool::Brush; @@ -1944,10 +1928,8 @@ fn mixer_background_window_keeps_and_commits_control_strokes() { let steps = app.session.active().unwrap().history.past_len(); let ctx = egui::Context::default(); ctx.begin_pass(egui::RawInput { focused: false, ..Default::default() }); - let (request, _reply) = crate::control::ControlRequest::new( - "ui.pointer", - json!({"tool":"mixerBrush","events":[{"kind":"down","x":20,"y":30},{"kind":"move","x":60,"y":30}]}), - ); + let (request, _reply) = + crate::control::ControlRequest::new("ui.pointer", json!({"tool":"mixerBrush","events":[{"kind":"down","x":20,"y":30},{"kind":"move","x":60,"y":30}]})); let _ = crate::control::handle(&mut app, &ctx, &request); assert!(!cancel_mixer_on_context_change(&mut app, &ctx)); assert!(app.drag.is_some()); @@ -2361,8 +2343,7 @@ fn a_secondary_canvas_hand_pans_while_a_transform_is_open() { seen }; 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 }; + 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)]); for dx in [10.0, 20.0, 40.0] { @@ -2577,11 +2558,7 @@ fn guides_draw_over_the_puppet_perspective_and_vanishing_point_previews() { let preview = shapes.iter().position(|s| match s { egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => { let r = m.calc_bounds(); - if command == photocraft_engine::vp_cmds::VP { - r.width() > 10.0 && r.width() < 300.0 && r.min.x < 150.0 && r.max.x > 150.0 - } else { - near(r) - } + if command == photocraft_engine::vp_cmds::VP { r.width() > 10.0 && r.width() < 300.0 && r.min.x < 150.0 && r.max.x > 150.0 } else { near(r) } } _ => false, }); diff --git a/crates/ui-egui/src/canvas/textures.rs b/crates/ui-egui/src/canvas/textures.rs new file mode 100644 index 0000000000..17b6f1bf26 --- /dev/null +++ b/crates/ui-egui/src/canvas/textures.rs @@ -0,0 +1,681 @@ +use super::display::{GPU_OUTPUT, cache_key, canvas_display, display_doc, display_image, texture_key}; +use super::filter_preview::filter_channel_preview; +use super::navigator::navigator_waits_for_drag; +use super::strokes::live_stroke; +use super::view_xform::ViewXform; +use super::*; + +/// Largest texture side we upload; bigger documents are uploaded downsampled, with the part in +/// view added at the screen's resolution when zoomed in (`detail_plan`). +pub const MAX_TEXTURE: u32 = 4096; + +/// The largest texture side to upload on this device: [`MAX_TEXTURE`], or less where the GPU +/// allows less (2048 on some older or low-end GPUs and WebGL contexts). Past the device's limit +/// egui asserts and the backend fails to create the texture. +pub(super) fn texture_side(ctx: &egui::Context) -> u32 { + clamp_texture_side(ctx.input(|i| i.max_texture_side)) +} + +/// [`texture_side`] for a device whose largest texture side is `max_texture_side`. +pub(super) fn clamp_texture_side(max_texture_side: usize) -> u32 { + u32::try_from(max_texture_side).unwrap_or(MAX_TEXTURE).clamp(1, MAX_TEXTURE) +} + +/// How many document pixels per side one texel of the CPU canvas texture of a `size` document +/// holds when textures are at most `side` texels per side: 1 (full resolution) when it fits. +pub(super) fn texture_factor(size: [u32; 2], side: u32) -> u32 { + size[0].max(size[1]).div_ceil(side.max(1)).max(1) +} + +/// What the CPU canvas draws over its reduced texture so a large document shows its own pixels +/// at 100 % (#7568): the part of the document in view (`region`, document pixels) composited at +/// one texel per `factor` pixels, a power of two no coarser than the screen. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct DetailPlan { + pub factor: u32, + pub region: DRect, +} + +/// The detail region snaps outward to multiples of this many texels, so a small pan reuses it. +const DETAIL_QUANTUM: i32 = 256; + +/// The detail texture a CPU canvas view of a `size` document needs, at `zoom` physical pixels +/// per document pixel over `visible` (document pixels), with textures at most `side` texels per +/// side: `None` when the whole-document texture is already as fine as the screen (a document +/// that fits, or a view zoomed out far enough), or nothing of the document is in view. +/// +/// A document over `side` (4096 px, or the device's smaller limit) is uploaded reduced, so at +/// 100 % it was drawn magnified and blurred. The detail costs what the window shows, not what the +/// document holds: its side is capped by `side` like any texture, coarsening by powers of two. +pub(crate) fn detail_plan(size: [u32; 2], side: u32, zoom: f32, visible: DRect) -> Option { + if !zoom.is_finite() || zoom <= 0.0 { + return None; + } + let base = texture_factor(size, side); + let mut factor = crate::adjust_preview::proxy_factor(zoom); + let bounds = DRect::new(0, 0, i32::try_from(size[0]).ok()?, i32::try_from(size[1]).ok()?); + let v = visible.intersect(&bounds); + if v.is_empty() { + return None; + } + while factor < base { + let q = DETAIL_QUANTUM.saturating_mul(i32::try_from(factor).unwrap_or(i32::MAX)); + let up = |x: i32| x.div_euclid(q).saturating_add(i32::from(x.rem_euclid(q) != 0)).saturating_mul(q); + let region = DRect::new(v.x0.div_euclid(q).saturating_mul(q), v.y0.div_euclid(q).saturating_mul(q), up(v.x1), up(v.y1)).intersect(&bounds); + // A reduced region's texel count can round one up (`render_reduced_damage`'s cells). + let fits = |n: u32| n.div_ceil(factor).saturating_add(1) <= side; + // Snapped when that fits, else just what is in view (a window near the device's limit). + for region in [region, v] { + if !region.is_empty() && fits(region.width()) && fits(region.height()) { + return Some(DetailPlan { factor, region }); + } + } + factor = factor.saturating_mul(2); + } + None +} + +/// The CPU canvas texture's sampling (#4810). Zoomed in, a full-resolution texture shows each +/// document pixel as a crisp square, as the GPU canvas's sharp nearest filter and Photoshop do; +/// zoomed out it is still filtered. A reduced texture (`factor` > 1) stays bilinear: its texels +/// are averages of several pixels, and squares of them would be blocks the image doesn't have. +pub(super) fn canvas_texture_options(factor: u32) -> TextureOptions { + if factor > 1 { TextureOptions::LINEAR } else { TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR } } +} + +/// Make sure the canvas texture for document `idx` on `display` is current; returns (texture +/// id, scale). +pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, display: Option) -> Option<(egui::TextureId, f32)> { + ensure_texture_in_view(app, ctx, idx, display, None).map(|t| (t.texture, t.scale)) +} + +/// The document area a filter preview of `preview` size covers, for a `doc` sized document +/// previewed at proxy factor `k`: the document's bounds when it is the document's size (reduced by +/// `k`), else its own size (times `k`) centred on the document's centre, as the GPU canvas centres +/// a size-changing preview (Image › Rotation). +pub(super) fn preview_bounds(doc: photocraft_geom::Size, preview: photocraft_geom::Size, k: u32) -> DRect { + let k = k.max(1); + let full = DRect::from_size(doc); + if doc.width.div_ceil(k) == preview.width && doc.height.div_ceil(k) == preview.height { + return full; + } + let side = |p: u32, d: u32| { + let covered = i64::from(p) * i64::from(k); + let x0 = (i64::from(d) - covered).div_euclid(2); + let clamp = |v: i64| v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32; + (clamp(x0), clamp(x0 + covered)) + }; + let (x0, x1) = side(preview.width, doc.width); + let (y0, y1) = side(preview.height, doc.height); + DRect::new(x0, y0, x1, y1) +} + +/// [`ensure_texture`], and for a canvas showing `view` of a document too large for one +/// full-resolution texture, the detail texture of the part in view ([`detail_plan`], #7568). +pub(crate) fn ensure_texture_in_view( + app: &mut PhotocraftApp, + ctx: &egui::Context, + idx: usize, + display: Option, + view: Option, +) -> Option { + 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) + }; + 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 + // canvas (no usable GPU, a flipped or pixel-aspect-corrected view, a GPU fallback) showed the + // document unfiltered. Its result is drawn here instead, as the channel views draw it. + // A preview reduced for a zoomed-out view (a proxy, factor `k`) covers the whole document at + // its own size. One whose dimensions change otherwise (Image › Rotation) covers its own area, + // centred on the document's, as the GPU canvas draws it (`preview_bounds`). + let committed = app.session.documents().get(idx).map(|st| st.doc.bounds()).unwrap_or(doc.bounds()); + let mut bounds = committed; + let mut reduced = false; + if let Some((preview, key)) = filter_channel_preview(app, idx, ctx) { + let k = app.filter_preview.as_ref().map_or(1, |p| p.key.k.max(1)); + bounds = preview_bounds(committed.size(), preview.size, k); + (doc, preview_key, reduced) = (preview, key, k > 1); + } + // Detail textures and partial redraws work in the document's own pixels. + let reduced = reduced || bounds != committed; + let view = view.filter(|_| !reduced); + // A flipped view draws a GPU machine's canvas through here: an adjustment dialog's preview of + // a large document (taken by the GPU path) would cost a full-size CPU composite per change. + if crate::adjust_preview::shown_key(app) == Some(preview_key) + && let Some(st) = app.session.documents().get(idx) + && crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(app)) > 1 + { + (doc, preview_key) = (st.doc.clone(), 0); + } + let (display, display_key) = canvas_display(app, &doc, output); + let seen = app.canvases.get(&cache_key(id, output)).map(|c| (c.tex_revision, c.tex_preview_key)); + let damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, preview_key), display_key, last_damage)).filter(|_| !reduced); + // The detail texture can lag the whole-document one (made or moved later): its own damage. + let detail_seen = view.and_then(|v| { + let c = app.canvases.get(&cache_key(id, output))?; + c.detail.iter().find(|(k, _)| *k == v.key).map(|(_, d)| (d.revision, d.preview_key)) + }); + let detail_damage = match detail_seen { + Some(s) if Some(s) == seen => damage, + Some(s) => damage_since(app, idx, s, (revision, preview_key), display_key, last_damage), + None => None, + }; + let preview_key = preview_key ^ display_key; + let cache = app.canvases.entry(cache_key(id, output)).or_insert(CanvasCache { + revision: 0, + texture: None, + scale: 1.0, + preview_key: 0, + on_gpu: false, + tex_revision: 0, + tex_preview_key: 0, + texture_opaque: false, + grid: None, + detail: Vec::new(), + }); + if cache.tex_revision != revision || cache.texture.is_none() || cache.tex_preview_key != preview_key { + let t0 = crate::gpu_canvas::now_ms(); + let factor = texture_factor([doc.size.width, doc.size.height], texture_side(ctx)); + let (w, h) = ((doc.size.width / factor).max(1), (doc.size.height / factor).max(1)); + let current = cache.texture.as_mut().filter(|t| t.size() == [w as usize, h as usize]); + if let (Some(d), Some(t)) = (damage, current) { + // Only what the edit or stroke touched: the reduced texture's pixels over it, with the + // values the whole reduction gives them (factor 1 is the plain composite of `d`). + let buf = photocraft_compose::render_reduced_damage(&doc, w, h, d); + let r = buf.rect; + if !r.is_empty() { + let t1 = crate::gpu_canvas::now_ms(); + let image = display_image(display.as_deref(), &buf); + // Partial uploads can disprove opacity. Once transparent, conservatively keep + // the checker until a full upload proves the whole texture opaque again. + cache.texture_opaque &= image.pixels.iter().all(|p| p.is_opaque()); + t.set_partial([r.x0 as usize, r.y0 as usize], image, canvas_texture_options(factor)); + let px = (r.width() as u64 * r.height() as u64).saturating_mul(u64::from(factor).pow(2)); + app.perf.record("rect", px, t1 - t0, crate::gpu_canvas::now_ms() - t1); + } + } else { + // Reduced in bands straight from the compositor: no full-size composite in memory. + let full = photocraft_compose::render_reduced(&doc, w, h); + let t1 = crate::gpu_canvas::now_ms(); + let (img, scale) = (display_image(display.as_deref(), &full), 1.0 / factor as f32); + cache.texture_opaque = img.pixels.iter().all(|p| p.is_opaque()); + match cache.texture.as_mut() { + Some(t) if t.size() == img.size => t.set(img, canvas_texture_options(factor)), + _ => cache.texture = Some(ctx.load_texture(format!("canvas-{}-{}", id.0, cache_key(id, output).1), img, canvas_texture_options(factor))), + } + cache.scale = scale; + app.perf.record("full", doc.size.width as u64 * doc.size.height as u64, t1 - t0, crate::gpu_canvas::now_ms() - t1); + } + cache.tex_revision = revision; + cache.tex_preview_key = preview_key; + } + let texture = cache.texture.as_ref()?.id(); + let scale = cache.scale; + // Without a view (the Navigator's call) the views' detail textures stay as they are. + let Some(view) = view else { return Some(CpuTextures { texture, scale, bounds, detail: None }) }; + let old = cache.detail.iter().position(|(k, _)| *k == view.key).map(|i| cache.detail.remove(i).1); + let Some(plan) = detail_plan([doc.size.width, doc.size.height], texture_side(ctx), view.zoom, view.visible) else { + return Some(CpuTextures { texture, scale, bounds, detail: None }); + }; + let t0 = crate::gpu_canvas::now_ms(); + let name = format!("canvas-detail-{}-{}", id.0, cache_key(id, output).1); + let detail = update_detail(ctx, &doc, display.as_deref(), name, plan, old, detail_damage, (revision, preview_key)); + if detail.as_ref().is_some_and(|d| d.rendered) { + app.perf.span("canvas detail", crate::gpu_canvas::now_ms() - t0); + } + let Some(mut detail) = detail else { return Some(CpuTextures { texture, scale, bounds, detail: None }) }; + detail.rendered = false; + // Where its texels lie in the document: reduced texel t covers [t·W/w, (t+1)·W/w). + let (w, h) = ((doc.size.width / plan.factor).max(1), (doc.size.height / plan.factor).max(1)); + let (sx, sy) = (doc.size.width as f32 / w as f32, doc.size.height as f32 / h as f32); + let out = detail.out; + let shown = (detail.texture.id(), [out.x0 as f32 * sx, out.y0 as f32 * sy, out.x1 as f32 * sx, out.y1 as f32 * sy]); + cache.detail.push((view.key, detail)); + // Views that stopped asking (a closed window, a zoom out) give theirs up past a few. + if cache.detail.len() > MAX_DETAIL_VIEWS { + cache.detail.remove(0); + } + Some(CpuTextures { texture, scale, bounds, detail: Some(shown) }) +} + +/// Most CPU canvas views of one document on one display that keep a detail texture. +const MAX_DETAIL_VIEWS: usize = 4; + +/// The detail texture for `plan` at document state `now` (revision, preview key with the display +/// key folded in): `old` as it is when current, updated over `damage` when only that changed +/// within the same region, or rendered again. `None` when the region holds no texels. +#[allow(clippy::too_many_arguments)] +fn update_detail( + ctx: &egui::Context, + doc: &Document, + display: Option<&photocraft_engine::display_color::CanvasDisplay>, + name: String, + plan: DetailPlan, + old: Option, + damage: Option, + now: (u64, u64), +) -> Option { + let (w, h) = ((doc.size.width / plan.factor).max(1), (doc.size.height / plan.factor).max(1)); + let options = canvas_texture_options(plan.factor); + let (kept, spare) = match old { + Some(d) if d.plan == plan => (Some(d), None), + d => (None, d.map(|d| d.texture)), + }; + if let Some(mut d) = kept { + if (d.revision, d.preview_key) == now { + return Some(d); + } + // An edit or a stroke step in view: only the texels it touched. + if let Some(dmg) = damage { + let dmg = dmg.intersect(&plan.region); + let buf = (!dmg.is_empty()).then(|| photocraft_compose::render_reduced_damage(doc, w, h, dmg)); + let fits = buf.as_ref().is_none_or(|b| d.out.contains_rect(&b.rect)); + if fits { + if let Some(b) = buf.filter(|b| !b.rect.is_empty()) { + let at = [b.rect.x0.abs_diff(d.out.x0) as usize, b.rect.y0.abs_diff(d.out.y0) as usize]; + d.texture.set_partial(at, display_image(display, &b), options); + d.rendered = true; + } + (d.revision, d.preview_key) = now; + return Some(d); + } + } + return render_detail(ctx, doc, display, name, plan, Some(d.texture), now); + } + render_detail(ctx, doc, display, name, plan, spare, now) +} + +/// [`update_detail`]'s whole render of `plan`'s region, into `texture` when it is the same size. +fn render_detail( + ctx: &egui::Context, + doc: &Document, + display: Option<&photocraft_engine::display_color::CanvasDisplay>, + name: String, + plan: DetailPlan, + texture: Option, + now: (u64, u64), +) -> Option { + let (w, h) = ((doc.size.width / plan.factor).max(1), (doc.size.height / plan.factor).max(1)); + let options = canvas_texture_options(plan.factor); + let buf = photocraft_compose::render_reduced_damage(doc, w, h, plan.region); + let out = buf.rect; + if out.is_empty() { + return None; + } + let img = display_image(display, &buf); + let texture = match texture { + Some(mut t) if t.size() == img.size => { + t.set(img, options); + t + } + _ => ctx.load_texture(name, img, options), + }; + Some(DetailTexture { texture, plan, out, revision: now.0, preview_key: now.1, rendered: true }) +} + +/// 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 { + // 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 + && let Some(st) = app.session.documents().get(idx) + && let Some(c) = app.committed_stroke.as_ref().filter(|c| c.doc == st.doc.id && c.revision == now.0) + && let Some(r) = c.since(seen.1 ^ display_key) + { + let r = if c.relayout.is_empty() { + r + } else if r.is_empty() { + c.relayout + } else { + r.union(&c.relayout) + }; + 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 { + return last_damage; + } + 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) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } + // Between an adjustment dialog's previews (and the document): the target's area. + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::adjust_preview::switch_region(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(r); + } + // Between a Properties-panel adjustment-layer drag's previews (and the document): the + // layer's area. Without this every parameter value recomposited the whole document (#6839). + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::adjust_preview::live_switch_region(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + 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()))) + && 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) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } + // Between a Patch drag's previews: the areas they healed. + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::patch_preview::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } + // Between Vanishing Point stamp previews (and the document): the areas the strokes painted. + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::vp_ui::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } + // Between hovered blend modes (and the document): where the layer's blending shows. + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::blend_preview::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } + // Between hovered fonts (and the document): the text layer's old/new ink bounds. + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::type_font_preview::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } + let l = live_stroke(app, idx).filter(|l| seen.0 == now.0 && l.display_key() == now.1)?; + let r = l.since(seen.1 ^ display_key)?; + Some(if r.is_empty() { r } else { r.inflate(effect_reach(&l.stroke.doc().layers)) }) +} + +/// Document `doc`'s canvas caches showed a preview that the edit just committed reproduces +/// (`was_preview` tells its keys): count it as the document itself, so the commit's damage rect +/// refreshes only that area instead of everything. +pub(crate) fn shown_as_document(app: &mut PhotocraftApp, doc: photocraft_doc::DocId, was_preview: impl Fn(u64) -> bool) { + let Some(d) = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| st.doc.clone()) else { return }; + if let Some(c) = app.channel_views.get_mut(&doc.0) + && was_preview(c.preview_key) + { + c.preview_key = 0; + } + // Every display's cache of the document: the GPU state folds in the texture key, CPU + // textures their display's key. + let outputs: Vec = app.canvases.keys().filter(|k| k.0 == doc).map(|k| k.1).collect(); + for out in outputs { + let (display, key) = canvas_display(app, &d, (out != 0 && out != GPU_OUTPUT).then_some(out)); + let gpu_key = texture_key(display.as_deref()); + let Some(c) = app.canvases.get_mut(&(doc, out)) else { continue }; + if was_preview(c.preview_key ^ gpu_key) { + c.preview_key = gpu_key; + } + if was_preview(c.tex_preview_key ^ key) { + c.tex_preview_key = key; + } + } +} + +/// How far beyond an edit's damage rect the composite can change: layer effects (shadows, glows, +/// strokes, …) on the edited layer and on the groups around it reach that far. +pub(crate) fn effect_reach(layers: &[photocraft_doc::Layer]) -> i32 { + layers + .iter() + .filter(|l| l.visible) + .map(|l| { + let own = if photocraft_compose::effects::has_effects(l) { photocraft_compose::effects::margin(l) } else { 0 }; + let inner = match &l.content { + LayerContent::Group(g) => effect_reach(&g.children), + _ => 0, + }; + own + inner + }) + .max() + .unwrap_or(0) +} + +/// GPU path: make sure document `idx` is current in the GPU canvas. Edits draw their damage; +/// unchanged lower-stack composites can be reused by the compositor inside that region. +/// 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)) + else { + return false; + }; + let (doc, raw_key) = display_doc(app, idx); + let (display, _) = canvas_display(app, &doc, None); + // Repeated pattern tiles sample the same texture, including pixels outside the unwrapped + // viewport. Refresh the affected document region while Pattern Preview is enabled. + let blend_visible = if app.ui.view.pattern_preview { doc.bounds() } else { visible }; + // The texture is shared by every display: only what it stores counts, not the monitor. + let display_key = texture_key(display.as_deref()); + let seen = app.canvases.get(&(id, GPU_OUTPUT)).map(|c| (c.revision, c.preview_key)); + let mut damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, raw_key), display_key, last_damage)); + if let Some(region) = damage { + damage = Some(crate::blend_preview::clip_damage(app, id, revision, raw_key, region, blend_visible)); + } + // To an adjustment dialog's preview: only what the view shows now (the rest as it moves there). + if damage.is_some() + && let Some(r) = seen.filter(|s| s.0 == revision).and_then(|s| crate::adjust_preview::switch_region(app, id, revision, s.1 ^ display_key, raw_key)) + { + damage = Some(crate::adjust_preview::switch_damage(app, raw_key, r, visible)); + } + // The same for a Properties-panel drag's previews. + if damage.is_some() + && let Some(r) = seen.filter(|s| s.0 == revision).and_then(|s| crate::adjust_preview::live_switch_region(app, id, revision, s.1 ^ display_key, raw_key)) + { + damage = Some(crate::adjust_preview::live_switch_damage(app, raw_key, r, visible)); + } + let preview_key = raw_key ^ display_key; + // The Navigator may draw this texture while it holds the plain document or a drag preview + // that updates the full texture (not an adjustment preview composited only where the view is). + if raw_key == 0 || navigator_waits_for_drag(app, idx) { + app.navigator_plain.insert(id); + } else { + app.navigator_plain.remove(&id); + app.navigator_gpu.remove(&id); + } + let size = [doc.size.width, doc.size.height]; + // A full CPU redraw running in the background: show the blocks it has finished. + crate::background_redraw::poll(app, &gpu, id); + let cache = app.canvases.entry((id, GPU_OUTPUT)).or_insert(CanvasCache { + revision: 0, + texture: None, + scale: 1.0, + preview_key: 0, + on_gpu: false, + tex_revision: 0, + tex_preview_key: 0, + texture_opaque: false, + grid: None, + detail: Vec::new(), + }); + let present = cache.on_gpu && gpu.has(id.0, size); + let current = cache.revision == revision && cache.preview_key == preview_key; + // GPU Memory or Memory Usage changed with nothing to redraw: the new budget, and whether the + // layers fit it, show at once (the status bar's GPU Memory Full). + if present && app.perf.gpu_budget_allowance != budget_allowance(app) { + gpu_budget(app, &gpu, idx, false, visible); + } + // Switched to a document whose canvas is already current: size the budget for it and measure + // whether its layers fit, so GPU Memory Full shows (or clears) at once rather than at its + // next full refresh. Once per switch: the fit then names this document. + if present && app.perf.gpu_layer_fit.is_none_or(|f| f.doc != id.0) { + gpu_budget(app, &gpu, idx, false, visible); + let fit = gpu.measure_fit(&doc).unwrap_or(crate::gpu_canvas::LayerFit { doc: id.0, needed: 0, budget: 0 }); + app.perf.gpu_layer_fit = Some(fit); + } + if present && current { + // An adjustment preview composited where the view was: catch up where it moved to. + if let Some(r) = crate::adjust_preview::uncovered(app, id, raw_key, visible) { + let r = gpu.refresh(id.0, &doc, Some(r), display.as_deref()); + app.perf.record_refresh(&r); + } + if let Some(r) = crate::adjust_preview::live_uncovered(app, id, raw_key, visible) { + let r = gpu.refresh(id.0, &doc, Some(r), display.as_deref()); + app.perf.record_refresh(&r); + } + // Blend previews keep offscreen pixels untouched until the view reaches them. + // Use the normal refresh path so CPU fallback and pending redraws stay synchronized. + damage = crate::blend_preview::uncovered(app, id, revision, raw_key, blend_visible); + if damage.is_none() { + return true; + } + } + // Display textures for a canvas this large would not fit the GPU: the reduced CPU canvas + // draws it (checked before the memory budget, which walks the history, every frame). + if !gpu.fits_canvas(&doc) { + crate::background_redraw::cancel(app, id); + // Drawn on the CPU canvas: no layer budget applies to it. + if app.perf.gpu_layer_fit.is_some_and(|f| f.doc == id.0) { + app.perf.gpu_layer_fit = None; + } + return false; + } + let partial = present && damage.is_some(); + gpu_budget(app, &gpu, idx, partial, visible); + let defer = crate::background_redraw::enabled(app); + let r = gpu.refresh_with(id.0, &doc, if partial { damage } else { None }, display.as_deref(), defer); + app.perf.gpu_layer_fit = gpu.layer_fit(); + if r.kind == "lost" || r.kind == crate::gpu_canvas::REFRESH_OVER_BUDGET { + // The device is gone (`gpu_status` then drops the GPU canvas) or the canvas is over the + // texture budget: draw this frame on the CPU path. + crate::background_redraw::cancel(app, id); + return false; + } + if r.kind == crate::gpu_canvas::REFRESH_DEFERRED { + // Composited off the UI thread, the visible part first (#4024). + let region = if partial { damage.unwrap_or(doc.bounds()) } else { doc.bounds() }; + crate::background_redraw::start(app, ctx, &gpu, doc.clone(), display.clone(), visible, region, r.fallback.clone()); + } else if partial { + // The edit drew its damage; blocks of a running redraw still to come follow the edit. + crate::background_redraw::restart(app, ctx, &gpu, doc.clone(), display.clone(), visible); + } else { + crate::background_redraw::cancel(app, id); + } + if let Some(e) = &r.fallback + && app.perf.gpu_fallback.as_deref() != Some(e.as_str()) + { + log::info!("{e}; using the CPU compositor"); + } + if r.kind != crate::gpu_canvas::REFRESH_DEFERRED { + app.perf.record_refresh(&r); + } + if r.kind == "full" { + crate::notices::slow_cpu_refresh(app, id.0, r.composite_ms + r.upload_ms, r.fallback.as_deref()); + } + if r.kind.starts_with("gpu") { + app.perf.gpu_uploads = r.uploads; + } else { + app.perf.gpu_fallback = r.fallback; + } + let Some(cache) = app.canvases.get_mut(&(id, GPU_OUTPUT)) else { return true }; + cache.revision = revision; + cache.preview_key = preview_key; + cache.on_gpu = true; + cache.texture = None; + true +} + +/// Point the wgpu compositor at what the view shows, and size its memory budget from GPU Memory, +/// or Memory Usage, the document's pixels and History (charged where the GPU shares the system's +/// memory), physical memory and the GPU's own: on full refreshes (pixels counted once per +/// structural change, not per brush dab) and whenever either preference changes. +fn gpu_budget(app: &mut PhotocraftApp, gpu: &crate::gpu_canvas::GpuCanvas, idx: usize, partial: bool, visible: DRect) { + gpu.set_focus(Some(visible)); + let allowance = budget_allowance(app); + let changed = app.perf.gpu_budget_allowance != allowance; + if partial && !changed && gpu.memory_budget().is_some() { + return; + } + let Some(st) = app.session.documents().get(idx) else { return }; + let pixels = st.memory_bytes() as u64; + let budget = crate::gpu_canvas::memory_budget(allowance.0, pixels, crate::gpu_canvas::physical_memory(), gpu.video_memory(), allowance.1); + gpu.set_memory_budget(budget); + app.perf.gpu_budget_mb = budget >> 20; + app.perf.gpu_budget_allowance = allowance; + if changed && let Some(fit) = gpu.measure_fit(&st.doc) { + app.perf.gpu_layer_fit = Some(fit); + } +} + +/// Memory Usage and GPU Memory (Preferences › Performance), in bytes. +fn budget_allowance(app: &PhotocraftApp) -> (u64, u64) { + let performance = &app.session.prefs().performance; + (u64::from(performance.memory_usage_mb).saturating_mul(1 << 20), u64::from(performance.gpu_memory_mb).saturating_mul(1 << 20)) +} + +/// The document pixels a view shows, with a margin for filtering. Uses all four canvas corners +/// so a rotated camera still covers the visible tiles. +pub(super) fn visible_doc_rect(xf: &ViewXform) -> DRect { + let r = xf.rect; + let docs = [xf.to_doc(r.min), xf.to_doc(pos2(r.max.x, r.min.y)), xf.to_doc(r.max), xf.to_doc(pos2(r.min.x, r.max.y))]; + let mut x0 = docs[0][0]; + let mut y0 = docs[0][1]; + let mut x1 = x0; + let mut y1 = y0; + for d in docs { + x0 = x0.min(d[0]); + y0 = y0.min(d[1]); + x1 = x1.max(d[0]); + y1 = y1.max(d[1]); + } + let c = |v: f64| v.clamp(-1e9, 1e9) as i32; + DRect::new(c(x0.floor()) - 2, c(y0.floor()) - 2, c(x1.ceil()) + 2, c(y1.ceil()) + 2) +} + +/// Prioritize deferred redraw blocks visible at either the target or the animated display camera. +/// The displayed camera may still show old texture contents outside the target's visible area. +pub(super) fn redraw_focus(target: &ViewXform, displayed: &ViewXform) -> DRect { + visible_doc_rect(target).union(&visible_doc_rect(displayed)) +} + +/// A CPU composite as the GPU canvas texture stores it (sRGB-encoded for linear documents). +pub(super) fn texture_buffer<'a>( + display: Option<&photocraft_engine::display_color::CanvasDisplay>, + buf: &'a photocraft_compose::Buffer, +) -> std::borrow::Cow<'a, photocraft_compose::Buffer> { + match display { + Some(d) => d.texture_buffer(buf), + None => std::borrow::Cow::Borrowed(buf), + } +} + +pub(crate) fn retain_gpu_documents(app: &mut PhotocraftApp) { + // Remove a closed adjustment owner's proxy before collecting its live GPU keys. + crate::adjust_preview::retain_documents(app); + if let Some(gpu) = &app.gpu { + // Keep each document's texture plus its preview textures (filter preview, adjustment proxy); + // retaining only document ids freed the previews every frame (blank canvas while previewing). + let mut live: Vec = app.session.documents().iter().flat_map(|st| [st.doc.id.0, st.doc.id.0 ^ (1u64 << 61), st.doc.id.0 ^ (1u64 << 62)]).collect(); + live.extend(crate::adjust_preview::gpu_keys(app)); + gpu.retain(&live); + } + crate::background_redraw::retain(app); + // Upload markers must not outlive the resources they describe: native reopen can reuse + // both the document ID and revision before the next frame while a preview dialog stays open. + let documents = app.session.documents(); + if app.filter_preview.as_ref().is_some_and(|preview| !documents.iter().any(|st| st.doc.id == preview.key.doc)) { + app.filter_preview = None; + } + if app.proxy_uploaded.is_some_and(|(doc, _)| !documents.iter().any(|st| st.doc.id == doc)) { + app.proxy_uploaded = None; + app.proxy = None; + } +} diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs new file mode 100644 index 0000000000..a58555037a --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -0,0 +1,626 @@ +use super::cursors::{alt_eyedropper, sample_eyedropper}; +use super::drag::Drag; +use super::gesture::{finish_gesture, polygon_click, selection_mode}; +use super::selection::finish_selection_drag; +use super::strokes::{HOLD_REPEAT_MS, begin_live_stroke, feed_live_stroke, paint_target, snap_aliased_tip, stroke_params, strokes_live}; +use super::*; + +/// Abstract tool event, produced by the mouse or by automation (`ui.pointer`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ToolEvent { + Down { x: f64, y: f64, pressure: f32 }, + Move { x: f64, y: f64, pressure: f32 }, + Up { x: f64, y: f64 }, +} + +/// The body of a `Move` for every tool: tracked position, ⇧ constraint, the moving layer, and so +/// on. It does not feed the live stroke, so the canvas can push a whole frame's recovered samples +/// and update the live stroke once (see `canvas_view`). +fn tool_move(app: &mut PhotocraftApp, x: f64, y: f64, pressure: f32, mods: egui::Modifiers) { + let tool = app.active_tool(); + if tool.is_type() && app.drag.is_none() { + crate::type_tool::pointer_move(app, x, y, mods); + } + if tool == Tool::Pen && mods.alt { + crate::vector_ui::pen_break_handle(app); + } + if tool == Tool::Pen { + crate::vector_ui::pen_move(app, x, y, mods.shift); + } else if tool == Tool::CurvaturePen { + crate::vector_ui::curvature_move(app, x, y); + } + let zoom = app.point_zoom(); + if let Some(d) = app.drag.as_mut().filter(|d| d.reposition) { + d.track(mods); + d.shift_to([x, y]); + } else if let Some(d) = &mut app.drag { + d.track(mods); + // ⇧: straight 0/45/90° strokes, 45° gradient angles (stroke_constraint.rs). + let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + let [x, y] = crate::stroke_constraint::constrain(d.tool, &mut d.constrain, d.start, last, [x, y], mods.shift, zoom); + // ⇧: a selection-tool drag of the selection locks to multiples of 45° (#6231). The Move + // tool's own drags were already locked by `move_mods::filter_event`. + let [x, y] = crate::move_mods::selection_drag_to(d, [x, y], mods.shift && tool != Tool::Move); + let moved = d.points.last().is_none_or(|p| (p[0] - x).abs() + (p[1] - y).abs() > 0.25); + // A held pen repeats its point now and then, so the stroke's time keeps advancing. + let held = app.stylus.last_point_ms().is_some_and(|t| app.stylus.clock_ms - t >= HOLD_REPEAT_MS) + && app.live_stroke.as_ref().is_some_and(|l| l.stroke.wants_time()); + if moved || held { + d.points.push([x, y, pressure as f64]); + app.stylus.record_point(); + } + } +} + +/// Tool state machine. Shared by mouse input and automation. +pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { + // A press anywhere but on a guide deselects the selected guide (`guide_select`). + if let ToolEvent::Down { x, y, .. } = ev + && app.ui.selected_guide.is_some() + && crate::rulers::guide_at(app, x, y).is_none() + { + crate::guide_select::clear(app); + } + if crate::symmetry_ui::pointer(app, ev, crate::workspace_ui::sticky_mods(app, mods)) { + return; + } + // An Alt+right-drag armed for this press (`paint_mouse`): taken before anything else can + // consume the event, so it never outlives the press it was armed for (#297). + let armed = std::mem::take(&mut app.brush_resize_armed); + crate::transform_tool::end_if_left(app); + let mods = crate::workspace_ui::sticky_mods(app, mods); + if app.ui.transform.is_none() && crate::type_transform::pointer(app, ev, mods) { + return; + } + // Content-Aware Move's Transform On Drop box takes every press until ↩ or Esc. + if crate::cam_transform::pointer(app, ev, mods) { + return; + } + // A Mixer Brush press that loaded paint stays a sample press until it is released, with ⌥ + // let go or not (`mixer_sampling`; `canvas_view` holds back egui's later drag start too). + match ev { + ToolEvent::Down { .. } => app.mixer_sampling = false, + ToolEvent::Up { .. } if app.mixer_sampling => { + app.mixer_sampling = false; + return; + } + _ if app.mixer_sampling => return, + _ => {} + } + // The tool in use, so a held temporary tool (⌘ = Move) with ⌥ doesn't load paint. + if app.active_tool() == Tool::MixerBrush && mods.alt && !mods.ctrl && app.drag.is_none() && !armed && app.brush_resize.is_none() { + if let ToolEvent::Down { x, y, pressure } = ev { + app.mixer_sampling = true; + let pen = app.stylus.sample().unwrap_or_default(); + let p = json!({"points":[[x,y,pressure,pen.tilt_x,pen.tilt_y,pen.rotation]],"target":paint_target(app)}); + if let Err(e) = app.run("brush.mixer.sample", p) { + app.ui.status = e; + app.ui.status_error = true; + } + } + return; + } + // View › Snap / Snap To and smart guides (snap_ui.rs). + let raw = ev; + // The Move tool's marquee selecting layers takes its moves and release unsnapped (move_box.rs). + if crate::move_box::pointer(app, raw) { + return; + } + // A press anywhere but on the floating piece (or with ⇧ / ⌥, to draw) drops it first; the + // Move tool (⌘ with a painting tool too, `event_tool`) drags it from anywhere. + if let ToolEvent::Down { x, y, .. } = raw + && app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some()) + && !crate::move_ui::moves_selected_pixels_with(app, event_tool(app, mods)) + && selection_drag_kind(app, app.ui.tool, [x, y], mods) != Some(true) + { + let _ = app.run("select.drop", json!({})); + } + let ev = crate::snap_ui::filter_event(app, ev, mods); + // Free Transform picks the handle under the press where the user clicked: the snapped press + // can land outside the corner's grab area and turn a corner drag into a move of the whole box. + let transform_ev = if matches!(raw, ToolEvent::Down { .. }) { raw } else { ev }; + if crate::transform_tool::pointer(app, transform_ev, mods) { + return; + } + if crate::distort_ui::pointer(app, ev, mods) { + return; + } + if crate::perspective_crop_ui::pointer(app, ev) { + return; + } + // Window › Modifier Keys: sticky Shift/⌘/⌥ act as held keys. + let mods = crate::workspace_ui::sticky_mods(app, mods); + // ⌘⌥⌃-click with any tool selects the topmost layer with pixels there (quick_pick.rs); it + // must run before the ⌃⌥ brush resize below, which the same keys would trigger. + if crate::quick_pick::pointer(app, ev, mods) { + return; + } + // Control+Alt-drag or Alt+right-drag with a painting tool resizes the brush instead of + // painting (#231, #297). + if crate::brush_resize::pointer(app, ev, mods, armed) { + return; + } + // ⌥ (Alt) with a painting tool is the Eyedropper for that press. + if alt_eyedropper(app, ev, mods) { + return; + } + // Move tool: ⇧ locks the axis, ⌥ duplicates (move_mods.rs). + let ev = crate::move_mods::filter_event(app, ev, mods); + // A live shape's corner radius widgets (Path Selection, the shape tools, Move with its + // transform controls). Unsnapped, as Free Transform's handles: snapping would pull the press + // off a widget onto a nearby vertex or guide, and the shape tool would draw a new shape. + if crate::corner_radius::pointer(app, raw, mods) { + return; + } + // Direct Selection, and the Pen's ⌘ (Direct Selection) and ⌥ (Convert Point) modes (#790). + if crate::direct_select::pointer(app, ev, mods) { + return; + } + // Add / Delete Anchor Point tools (#1044). + if crate::anchor_tools::pointer(app, ev, mods) { + return; + } + // Ruler, Count and Note tools. + if crate::analysis_ui::pointer(app, ev, mods) { + return; + } + // Slice and Slice Select tools. + if crate::slice_ui::pointer(app, ev, mods) { + return; + } + // Frame tool: draw rectangular and elliptical frames. + if crate::frame_tool::pointer(app, ev, mods) { + return; + } + // Artboard tool: draw, select, move and resize boards. + if crate::artboard_tool::pointer(app, ev, mods) { + return; + } + // Crop tool: draw, move and resize the frame. + if crate::crop_ui::pointer(app, ev, mods) { + return; + } + // Gradient tool, live mode: draw and edit Gradient Fill layers. + if crate::gradient_ui::pointer(app, ev, mods) { + return; + } + // ⌘ over a guide takes the guide (#2690, #6288); the guide drag below moves it. + if let ToolEvent::Down { x, y, .. } = raw + && let Some((vertical, i)) = command_guide_at(app, app.active_tool(), [x, y], mods) + { + app.guide_drag = Some(crate::rulers::GuideDrag::existing(vertical, i, [x, y])); + crate::snap_ui::begin_guide(app, [x, y]); + return; + } + if crate::lasso_ui::pointer(app, ev, mods) { + return; + } + // Magnetic Lasso: fastening points and the border following the pointer. + if crate::magnetic_lasso_ui::pointer(app, ev, mods) { + return; + } + let tool = event_tool(app, mods); + if tool == Tool::Eyedropper { + match ev { + ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } => { + sample_eyedropper(app, x, y, mods); + return; + } + ToolEvent::Up { .. } => return, + } + } + // A locked layer (the Background without a selection, say): no drag, and Photoshop's message + // once the pointer moves (a click says nothing). ⌘ with a selection tool here (#896); the Move + // tool below, once Auto-Select has picked the layer. + match ev { + ToolEvent::Down { x, y, .. } if tool != Tool::Move && app.ui.transform.is_none() && crate::move_lock::blocked(app, tool, [x, y], mods) => { + app.move_blocked = true; + return; + } + ToolEvent::Move { .. } if app.move_blocked => { + app.move_blocked = false; + crate::move_lock::prompt(app); + return; + } + ToolEvent::Up { .. } if app.move_blocked => { + app.move_blocked = false; + return; + } + _ => {} + } + // Move tool over a guide drags the guide (off the canvas deletes it). + match ev { + ToolEvent::Down { x, y, pressure } if tool == Tool::Move => { + if let Some((vertical, i)) = crate::rulers::guide_at(app, x, y) { + // ⌥-click turns the guide, through the point clicked, as in Photoshop. + if mods.alt && !mods.shift && !mods.command { + crate::guide_select::flip(app, vertical, i, [x, y]); + return; + } + app.guide_drag = Some(crate::rulers::GuideDrag::existing(vertical, i, [x, y])); + return; + } + // Auto-Select (or ⌘-click while it is off) picks the layer under the pointer first + // (not when the selected pixels move: those are the active layer's). + if !crate::move_ui::moves_selected_pixels_with(app, tool) && app.ui.tool_options.move_auto_select != mods.command { + let target = app.ui.tool_options.move_target.clone(); + let mode = if mods.shift { "add" } else { "replace" }; + let before = app.session.active().map(|st| st.selected_layers()); + // A locked layer under the pointer (the Background) can't move. Photoshop draws + // the layer marquee instead of reporting the lock (#4058). Probe without + // selecting so a locked hit doesn't become the selection first. + let probe = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "select": false})); + let locked_hit = probe.as_ref().ok().and_then(|v| v["layer"].as_u64()).is_some_and(|id| { + app.session.active().is_some_and(|st| { + let id = photocraft_doc::LayerId(id); + let locks = st.doc.effective_locks(id); + locks.position || locks.all || st.doc.is_background(id) + }) + }); + if locked_hit || (probe.as_ref().is_ok_and(|v| v["layer"].is_null()) && crate::move_box::empty_at(app, [x, y])) { + if locked_hit { + // A click still selects the locked layer, as in Photoshop; a drag's + // marquee then replaces that selection on release. + let _ = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "mode": mode})); + } + crate::move_box::begin(app, [x, y], mods.shift); + return; + } + let picked = app.run("layer.pickAt", json!({"x": x, "y": y, "target": target, "mode": mode})); + // No pixels there at all (an empty spot, or off the canvas): drag a marquee that + // selects the layers it touches instead (move_box.rs). + if picked.is_ok_and(|v| v["layer"].is_null()) && crate::move_box::empty_at(app, [x, y]) { + crate::move_box::begin(app, [x, y], mods.shift); + return; + } + // Snapping (and the drag's box) started before the pick: point it at what moves. + if app.session.active().map(|st| st.selected_layers()) != before { + crate::snap_ui::retarget_move(app, [x, y], mods); + } + } + // A locked layer: no drag, and Photoshop's message once the pointer moves (`move_lock`). + if crate::move_lock::blocked(app, tool, [x, y], mods) { + app.move_blocked = true; + return; + } + // With a selection: cut the selected pixels (⌥ copies them) and drag them as a floating + // piece, from anywhere, as a marquee ⌘-drag does. + if crate::move_ui::moves_selected_pixels_with(app, tool) { + if crate::move_ui::float_selected(app, mods.alt, 0.0, 0.0) { + let mut d = Drag::new(tool, [x, y], vec![[x, y, pressure as f64]], mods, false); + d.sel_move = Some(true); + app.drag = Some(d); + } + return; + } + } + ToolEvent::Move { x, y, .. } => { + if let Some(d) = app.guide_drag.as_mut().filter(|d| d.index.is_some()) { + d.pos = if d.vertical { x } else { y }; + return; + } + } + ToolEvent::Up { x, y } => { + if let Some(mut d) = app.guide_drag.filter(|d| d.index.is_some()) { + app.guide_drag = None; + d.pos = if d.vertical { x } else { y }; + crate::rulers::finish_drag(app, d); + return; + } + } + _ => {} + } + match ev { + ToolEvent::Down { x, y, pressure } => { + // Painting a type, shape, Smart Object or fill layer asks to rasterize it first + // (⌥-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; + return; + } + if !sets_source && crate::rasterize_prompt::intercept(app, tool, x, y, pressure) { + return; + } + // ⌘ with a selection tool is the Move tool for the drag: outside the selection (or + // without one) it moves the whole layer, ⌘⌥ a duplicate of it. It never combines + // selections. + if command_moves_layer(app, tool, [x, y], mods) { + if mods.alt + && let Err(e) = app.run("layer.duplicate", json!({"inPlace": true})) + { + app.ui.status = e; + app.ui.status_error = true; + return; + } + app.drag = Some(Drag::new(Tool::Move, [x, y], vec![[x, y, pressure as f64]], mods, false)); + return; + } + // Marquee / lasso inside the selection: drag the outline, or ⌘-drag to cut the selected + // pixels into a floating piece (`select.float`) and drag that. + if let Some(cut) = selection_drag_kind(app, tool, [x, y], mods) { + // ⌘⌥ on a floating piece leaves it where it is and drags a copy of it. + if cut + && mods.alt + && mods.command + && app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some()) + && let Err(e) = app.run("select.drop", json!({})) + { + app.ui.status = e; + app.ui.status_error = true; + return; + } + if cut + && app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_none()) + && let Err(e) = app.run("select.float", json!({"dx": 0, "dy": 0, "copy": mods.alt})) + { + app.ui.status = e; + app.ui.status_error = true; + return; + } + crate::snap_ui::follow_cut(app); + let mut d = Drag::new(tool, [x, y], vec![[x, y, pressure as f64]], mods, false); + d.sel_move = Some(cut); + app.drag = Some(d); + return; + } + match tool { + Tool::PathSelection => { + let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); + if let Some(st) = app.session.active() + && let Some(id) = crate::vector_ui::pick_shape_at(&st.doc, [x, y], tol) + { + let _ = app.run("layer.select", json!({"layer": id.0})); + } + } + Tool::Pen => { + if !(mods.alt && crate::vector_ui::pen_grab_handle(app, x, y)) { + crate::vector_ui::pen_down(app, x, y, mods.shift); + } + return; + } + Tool::CurvaturePen => { + crate::vector_ui::curvature_down(app, x, y); + return; + } + Tool::CloneStamp | Tool::Healing if mods.alt => { + crate::retouch_ui::set_source(app, x, y); + return; + } + Tool::MagicWand => { + let o = app.ui.tool_options.clone(); + let mode = selection_mode(app, mods); + let _ = app.run("select.magicWand", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "sampleAllLayers": o.sample_all.magic_wand, "mode": mode})); + return; + } + Tool::MagicEraser => { + crate::eraser_ui::click(app, tool, x, y); + return; + } + Tool::PaintBucket => { + let o = app.ui.tool_options.clone(); + let contents = if o.bucket_fill_pattern { "pattern" } else { "foreground" }; + let mode = if o.bucket_clear { "clear" } else { o.bucket_blend_mode.label() }; + let _ = app.run("paint.bucket", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "sampleAllLayers": o.sample_all.paint_bucket, "opacity": o.fill_opacity, "contents": contents, "mode": mode, "target": paint_target(app)})); + return; + } + Tool::RedEye => { + let o = app.ui.tool_options.clone(); + let _ = app.run( + "paint.redEye", + json!({ + "x": x.floor(), + "y": y.floor(), + "pupilSize": o.red_eye_pupil_size.clamp(1.0, 100.0), + "darken": o.red_eye_darken.clamp(0.0, 100.0), + "target": paint_target(app), + }), + ); + return; + } + Tool::PolygonLasso => { + polygon_click(app, x, y, mods); + return; + } + // The Type tools pick the box handle or glyph under the press where the user + // clicked: the snapped press can land off an edge handle's grab area (#6819). + Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask + if { + let [px, py] = if let ToolEvent::Down { x, y, .. } = raw { [x, y] } else { [x, y] }; + crate::type_tool::pointer_down(app, px, py, mods) + } => + { + return; + } + _ => {} + } + crate::paint_mouse::sync_tool_brush(app); + // 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; + // A 1 px pencil line depends on the pixels, not where inside the pixel the click + // landed (#4071). Snap both ends of the stroke to the aliased tip's grid. + let (x, y) = snap_aliased_tip(app, tool, x, y); + // ⇧-click connects to the last endpoint, including its pen pressure (#2827), so + // the renderer interpolates size and opacity across the segment. + let active = app.session.active().map(|st| st.doc.id); + let from = app.last_stroke_end.filter(|(doc, _)| mods.shift && crate::stroke_constraint::connects(tool) && Some(*doc) == active).map(|(_, p)| { + let (sx, sy) = snap_aliased_tip(app, tool, p[0], p[1]); + [sx, sy, p[2]] + }); + let mut points = vec![[x, y, pressure as f64]]; + if let Some(p) = from { + points.insert(0, p); + } + // ⌥ flips Dodge/Burn and Blur/Sharpen for this stroke. + let tool = crate::retouch_ui::alt_flipped(tool, mods.alt); + app.drag = Some(Drag { clear, ..Drag::new(tool, from.map_or([x, y], |p| [p[0], p[1]]), points, mods, erase) }); + app.trail = None; + app.stylus.begin_stroke(); + if from.is_some() { + app.stylus.record_point(); + } + app.live_stroke = if strokes_live(tool) { begin_live_stroke(app) } else { None }; + if tool == Tool::MixerBrush && app.live_stroke.is_none() { + use photocraft_engine::brush_cmds::mixer_live::LiveMixer; + let p = app.drag.as_ref().map(|d| stroke_params(app, d, &app.stylus.stroke_points(&d.points))); + // A tip above the preview size keeps the drag: `finish_gesture` renders it on release. + // Otherwise the first dab itself is invalid. Do not queue an unexpected release edit. + if let Some(p) = p + && !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; + } + app.drag = None; + } + } else if tool == Tool::MixerBrush { + feed_live_stroke(app); + } + } + ToolEvent::Move { x, y, pressure } => { + // Polygonal Lasso: ⌥ held while the button is down draws freehand into the polygon; + // releasing ⌥ goes back to straight segments (the polygon stays open). + if tool == Tool::PolygonLasso && mods.alt && app.drag.is_none() && !app.ui.polygon.is_empty() { + if app.ui.polygon.last().is_none_or(|l| (l[0] - x).hypot(l[1] - y) >= 1.0) { + app.ui.polygon.push([x, y]); + } + return; + } + tool_move(app, x, y, pressure, mods); + feed_live_stroke(app); + } + ToolEvent::Up { x, y } => { + if tool.is_type() + && let Some(e) = app.ui.text_edit.as_mut() + { + e.dragging = false; + e.resize = None; + app.ui.caret_blink_time = app.last_frame_time; + } + if tool == Tool::Pen { + crate::vector_ui::pen_up(app); + } else if tool == Tool::CurvaturePen { + crate::vector_ui::curvature_up(app); + } + let zoom = app.point_zoom(); + let Some(mut d) = app.drag.take() else { return }; + d.track(mods); + if d.reposition { + d.shift_to([x, y]); + } + let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]); + let [x, y] = crate::stroke_constraint::constrain(d.tool, &mut d.constrain, d.start, last, [x, y], mods.shift, zoom); + let [x, y] = crate::move_mods::selection_drag_to(&mut d, [x, y], mods.shift && app.active_tool() != Tool::Move); + // A Move-tool click (released where it was pressed) selects, it never moves: snapping + // the release point would otherwise nudge the layer onto a nearby edge. + if d.tool == Tool::Move && d.points.len() < 2 && matches!(raw, ToolEvent::Up { x, y } if [x, y] == d.start) { + app.move_preview = None; + crate::move_mods::finish(app); + if d.sel_move.is_some() { + finish_selection_drag(app, true, d.start, d.start); + } + return; + } + if d.points.last().is_none_or(|p| p[0] != x || p[1] != y) { + d.points.push([x, y, d.points.last().map_or(1.0, |p| p[2])]); + app.stylus.record_point(); + } + finish_gesture(app, d); + crate::move_mods::finish(app); + } + } +} + +/// Why a press with `tool` must not start: it would paint on or move a hidden target layer (the +/// engine refuses the command; refusing the press keeps the live stroke from drawing first). +fn hidden_target(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { + let cmd = match tool { + Tool::Move => "layer.translate", + // The live Gradient makes a new Gradient Fill layer above the target, which Photoshop + // allows over a hidden layer; only the classic one paints the target itself. + Tool::Gradient if !app.ui.tool_options.gradient_classic => return None, + // Every painting command follows the same target (layer, mask or channel) as a stroke. + t if t.is_brushlike() || matches!(t, Tool::Gradient | Tool::PaintBucket | Tool::MagicEraser) => "paint.stroke", + _ => return None, + }; + photocraft_engine::hidden_target::refusal(&app.session, cmd, &json!({})) +} + +/// 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)) +} + +/// Does selection surface `sel` cover document point `p`? +fn covers(sel: &photocraft_raster::Surface, p: [f64; 2]) -> bool { + let mut v = [0.0f32]; + sel.read_pixel(p[0].floor() as i32, p[1].floor() as i32, &mut v); + v[0] > 0.0 +} + +/// Does a press with `tool` at `p` drag the selection rather than draw a new one? `Some(true)` +/// moves the floating piece (⌘ cuts one first, ⌘⌥ copies; a floating piece moves with a plain +/// drag; the Polygonal Lasso and Magic Wand need ⌘, as a plain press there places or samples), +/// `Some(false)` just the outline (no ⇧ / ⌥ and the options bar on New Selection, so a combining +/// drag still draws). +pub fn selection_drag_kind(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> Option { + // Click-driven selection tools (a press places a point or samples): only ⌘ drags the + // selection, and not while a polygon is being drawn. + let clicky = matches!(tool, Tool::PolygonLasso | Tool::MagicWand); + if !(clicky || matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso)) || (clicky && !app.ui.polygon.is_empty()) { + return None; + } + // ⌘ cuts, ⌘⌥ copies (`select.float`'s `copy`). + let cut = mods.command && !mods.shift; + if let Some(f) = app.session.active().and_then(photocraft_engine::float_cmds::floating) { + // A press on the piece's outline (where its ants are) drags it; one in the margin the cut + // left of the selection starts a new selection (#7538). + let at = [p[0] - f64::from(f.offset.0), p[1] - f64::from(f.offset.1)]; + let on = f.parts.outline().map_or_else(|| inside_selection(app, at), |o| covers(o, at)); + return (on && !mods.shift && (!mods.alt || mods.command) && (cut || !clicky)).then_some(true); + } + if !inside_selection(app, p) { + return None; + } + if cut { + return Some(true); + } + (!clicky && !mods.command && selection_mode(app, mods) == "replace").then_some(false) +} + +/// The tool a pointer event with `mods` goes to: ⌘ held is the Move tool (`hold_keys::cmd_moves`). +/// The canvas resolves the held key before the event (`tool_override`); automation and tests send +/// the modifier with the event. +pub(crate) fn event_tool(app: &PhotocraftApp, mods: egui::Modifiers) -> Tool { + match app.active_tool() { + t if app.tool_override.is_none() && mods.command && crate::hold_keys::cmd_moves(t) && app.ui.transform.is_none() && app.ui.text_edit.is_none() => { + Tool::Move + } + t => t, + } +} + +/// Does a ⌘ (⌘⌥) press with selection tool `tool` at `p` move the whole layer (a duplicate with +/// ⌥), as the Move tool would? Outside the selection or without one; inside it, ⌘ drags the +/// selected pixels instead (`selection_drag_kind`). +pub(crate) fn command_moves_layer(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> bool { + let selection_tool = matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso | Tool::PolygonLasso | Tool::MagicWand); + let floating = app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some()); + selection_tool && mods.command && !mods.shift && !floating && app.ui.polygon.is_empty() && !inside_selection(app, p) +} + +/// The guide a ⌘ press with `tool` at `p` drags (vertical?, index), as the Move tool's press +/// would (#2690): ⌘ is the Move tool, and a guide under the pointer comes before the layer or the +/// selected pixels. The selection tools, and every tool on which ⌘ is the Move tool +/// (`hold_keys::cmd_moves`, #6288); the canvas shows the guide cursor where this finds a guide. +/// Not while a polygon or lasso outline, a stroke, Free Transform or type editing is under way. +pub(crate) fn command_guide_at(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> Option<(bool, usize)> { + let selection_tool = matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso | Tool::PolygonLasso | Tool::MagicWand); + let moves = selection_tool || crate::hold_keys::cmd_moves(tool); + let idle = app.ui.polygon.is_empty() && !crate::lasso_ui::active(app) && app.ui.transform.is_none() && app.ui.text_edit.is_none() && app.drag.is_none(); + (moves && mods.command && idle).then(|| crate::rulers::guide_at(app, p[0], p[1])).flatten() +} diff --git a/crates/ui-egui/src/canvas/transform_controls.rs b/crates/ui-egui/src/canvas/transform_controls.rs new file mode 100644 index 0000000000..9d583cd604 --- /dev/null +++ b/crates/ui-egui/src/canvas/transform_controls.rs @@ -0,0 +1,151 @@ +use super::selection::floating_outline; +use super::view_xform::ViewXform; +use super::*; + +/// View › Show › Layer Edges: the colour of the active layer's outline. +pub(crate) const LAYER_EDGES: Color32 = Color32::from_rgb(0x2d, 0x8c, 0xeb); + +/// View › Show › Layer Edges: the active layer's content bounds (cached per tile) where the canvas +/// shows them. During a Move drag that is at the offset the image was drawn with this frame, so +/// the outline moves in lockstep with the layer's pixels (#2413). +pub(crate) fn layer_edges_rect(app: &PhotocraftApp, idx: usize) -> Option { + if !app.ui.view.shows(app.ui.view.show.layer_edges) { + return None; + } + let st = app.session.documents().get(idx)?; + let id = st.active_layer?; + let b = st.doc.layer(id)?.surface().map(photocraft_compose::bounds::content_bounds)?; + if b.is_empty() { + return None; + } + let (dx, dy) = crate::move_ui::shown_layer_offset(app, st.doc.id, st.revision, id).unwrap_or((0, 0)); + Some(b.translate(dx, dy)) +} + +/// The layers Move › Show Transform Controls frames: every selected layer but the Background. +/// A corner radius drag hides the box, as in Photoshop. So does View › Extras (⌘H, #6699): the +/// controls are an Extra, hidden and inert until Extras comes back, while Show Transform Controls +/// keeps its setting. +pub(super) fn transform_controls_layers(app: &PhotocraftApp) -> Vec<&photocraft_doc::Layer> { + if app.ui.tool != Tool::Move + || !app.ui.tool_options.move_show_transform + || !app.ui.view.extras + || app.ui.transform.is_some() + || app.drag.is_some() + || app.ui.corner_radius.is_some() + { + return Vec::new(); + } + let Some(st) = app.session.active() else { return Vec::new() }; + st.selected_layers().into_iter().filter_map(|id| st.doc.layer(id)).filter(|l| !crate::doc_props_ui::is_background(&st.doc, l)).collect() +} + +/// Several layers are selected: Show Transform Controls frames them all, as Photoshop does, but +/// Free Transform works on one layer, so the frame has no handles to scale or rotate them. +pub(super) fn transform_controls_several(app: &PhotocraftApp) -> bool { + transform_controls_layers(app).len() > 1 +} + +/// Move tool › Show Transform Controls: the boxes Free Transform would open on the selected +/// layers, joined into one. +pub(super) fn transform_controls_rect(app: &PhotocraftApp, xf: &ViewXform) -> Option { + let st = app.session.active()?; + let layers = transform_controls_layers(app); + let b = layers.iter().map(|l| photocraft_engine::transform_cmds::transform_frame(&st.doc, l)).filter(|b| !b.is_empty()).reduce(|a, b| a.union(&b))?; + // Floating selected pixels are framed by their outline, as their ants are (#7538), not by the + // selection they were cut with; a frame round other selected layers too keeps them all. + let alone = matches!(layers.as_slice(), [l] if photocraft_engine::float_cmds::floating(st).is_some_and(|f| f.layer == l.id)); + let b = app.session.active_index().filter(|_| alone).and_then(|idx| floating_outline(app, idx)).map_or(b, |o| o.content_bounds()); + let (dx, dy) = crate::move_ui::floating_offset(app).unwrap_or((0, 0)); + let b = b.translate(dx, dy); + if b.is_empty() { + return None; + } + Some(Rect::from_two_pos(xf.to_screen(b.x0 as f32, b.y0 as f32), xf.to_screen(b.x1 as f32, b.y1 as f32))) +} + +/// The Move tool shows transform handles even before a Free Transform session exists. +/// Use the same hit areas for pointer-down and hover, so a control never behaves like +/// resize/rotate while showing the ordinary four-arrow Move cursor (#2871). +pub(super) fn transform_controls_cursor(r: Rect, p: Pos2) -> Option { + let handles = [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()]; + let grab = crate::transform_tool::HANDLE_PX as f32; + for (i, handle) in handles.into_iter().enumerate() { + if handle.distance(p) <= grab { + return Some(match i { + 0 | 4 => egui::CursorIcon::ResizeNwSe, + 2 | 6 => egui::CursorIcon::ResizeNeSw, + 1 | 5 => egui::CursorIcon::ResizeVertical, + _ => egui::CursorIcon::ResizeHorizontal, + }); + } + } + // The rotation band: the pointer gives way to the curved rotate arrow (`transform_controls_turn`). + in_rotation_band(r, p).then_some(egui::CursorIcon::None) +} + +fn in_rotation_band(r: Rect, p: Pos2) -> bool { + r.expand(18.0).contains(p) && !r.expand(5.0).contains(p) +} + +/// In the rotation band just outside the Move tool's transform controls, the screen direction the +/// curved rotate arrow bends round: into the box along the nearest corner's bisector, as Free +/// Transform draws it (#4658). Before, the band showed a plain alias pointer, so nothing said a +/// drag there rotates. +pub(super) fn transform_controls_turn(r: Rect, p: Pos2) -> Option { + if !in_rotation_band(r, p) + || [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()] + .into_iter() + .any(|h| h.distance(p) <= crate::transform_tool::HANDLE_PX as f32) + { + return None; + } + let corner = pos2(if p.x < r.center().x { r.left() } else { r.right() }, if p.y < r.center().y { r.top() } else { r.bottom() }); + Some(vec2((r.center().x - corner.x).signum(), (r.center().y - corner.y).signum()).normalized() * 16.0) +} + +/// A visible handle starts scaling; the narrow band just outside the box starts rotation. +/// The interior stays the normal Move-tool drag target. +pub(super) fn transform_controls_hit(r: Rect, p: Pos2) -> bool { + transform_controls_cursor(r, p).is_some() +} + +/// Enter the existing Free Transform session when a Move-tool transform control is pressed. +pub(super) fn begin_transform_controls_at(app: &mut PhotocraftApp, ctx: &egui::Context, xf: &ViewXform, p: Pos2) -> bool { + if transform_controls_several(app) { + return false; + } + let Some(r) = transform_controls_rect(app, xf) else { return false }; + if !transform_controls_hit(r, p) { + return false; + } + match crate::transform_tool::begin(app, ctx) { + Ok(()) => true, + Err(e) => { + app.ui.status = e; + false + } + } +} + +/// Move tool › Show Transform Controls: the selected layers' bounding box, with its eight handles +/// for one layer, and the outline of every selected shape layer, as in Photoshop. +pub(super) fn draw_transform_controls(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { + let Some(r) = transform_controls_rect(app, xf) else { return }; + let accent = crate::theme::Tokens::get(painter.ctx()).accent; + let to_scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32); + for l in transform_controls_layers(app) { + if let LayerContent::Shape(sh) = &l.content { + crate::vector_ui::draw_outline(painter, &sh.path, &to_scr, accent); + } + } + painter.rect_stroke(r, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Middle); + if transform_controls_several(app) { + return; + } + for p in [r.left_top(), r.center_top(), r.right_top(), r.right_center(), r.right_bottom(), r.center_bottom(), r.left_bottom(), r.left_center()] { + let h = Rect::from_center_size(p, vec2(7.0, 7.0)); + painter.rect_filled(h, 0.0, Color32::WHITE); + painter.rect_stroke(h, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside); + } +} diff --git a/crates/ui-egui/src/canvas/view_xform.rs b/crates/ui-egui/src/canvas/view_xform.rs new file mode 100644 index 0000000000..ec3df91d13 --- /dev/null +++ b/crates/ui-egui/src/canvas/view_xform.rs @@ -0,0 +1,262 @@ +use super::*; + +/// Document ↔ screen mapping for a canvas rect and a view. +#[derive(Clone, Copy, Debug)] +pub struct ViewXform { + pub rect: Rect, + pub zoom: f32, + pub center: [f32; 2], + /// View › Flip Horizontal: the view is mirrored left-right (the document is not). + pub flip: bool, + /// Camera rotation in degrees around [`Self::center`]. Clockwise (Y-down) is positive; applied + /// before flip. + pub rotation: f32, + /// View › Pixel Aspect Ratio Correction: a document pixel is drawn this many times wider than + /// tall (1 = square). Applied in document space, before rotation, so a rotated view still + /// shows the stretched image turned as a whole. + pub aspect: f32, +} + +impl ViewXform { + /// The main canvas's mapping for the active document as last laid out (inside the rulers). + pub fn active(app: &PhotocraftApp) -> Option { + let v = app.ui.views.get(app.session.active_index()?)?; + let (zoom, center) = + if v.zoom_animating && app.session.prefs().general.animated_zoom { v.display_camera.unwrap_or((v.zoom, v.center)) } else { (v.zoom, v.center) }; + Some( + Self { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: zoom / app.canvas_ppp(), + center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + aspect: app.ui.view.display_aspect(), + } + .pixel_aligned_for(app, app.canvas_ppp()), + ) + } + + pub(super) fn pixel_aligned_for(self, app: &PhotocraftApp, ppp: f32) -> Self { + // Default Crop counter-moves the frame and camera with fractional pointer deltas. + // Preserve that continuous mapping so its fixed frame does not wobble during a drag. + if crate::crop_mode::moves_image(app) { self } else { self.pixel_aligned(ppp) } + } + + /// At integer physical magnifications, texel edges must land on display pixel edges. + /// Keep this derived camera shared by images, overlays and input without changing the saved pan. + pub(super) fn pixel_aligned(mut self, ppp: f32) -> Self { + if !ppp.is_finite() || ppp <= 0.0 || !self.zoom.is_finite() || self.zoom <= 0.0 || !self.rotation.is_finite() || self.rotation.abs() >= 1e-8 { + return self; + } + let scale = vec2(self.zoom_x(), self.zoom) * ppp; + if !scale.is_finite() + || scale.x.round() < 1.0 + || scale.y.round() < 1.0 + || (scale.x - scale.x.round()).abs() > 1e-5 + || (scale.y - scale.y.round()).abs() > 1e-5 + { + return self; + } + let origin = self.to_screen(0.0, 0.0); + let physical = origin * ppp; + if !physical.is_finite() { + return self; + } + let aligned = pos2(physical.x.round(), physical.y.round()) / ppp; + let offset = self.unmap_vec((aligned - origin) / self.zoom); + let center = [self.center[0] - offset.x, self.center[1] - offset.y]; + if center.iter().all(|v| v.is_finite()) { + self.center = center; + } + self + } + + fn sincos(self) -> (f32, f32) { + if self.rotation.abs() < 1e-8 { + (1.0, 0.0) + } else { + let r = self.rotation.to_radians(); + (r.cos(), r.sin()) + } + } + + /// Document pixel width over height on screen: [`Self::aspect`], or 1 when it is unusable. + fn sx(self) -> f32 { + if self.aspect.is_finite() && self.aspect > 0.0 { self.aspect } else { 1.0 } + } + + /// Screen points per document pixel along the document's x axis. + pub fn zoom_x(&self) -> f32 { + self.zoom * self.sx() + } + + /// Unflip, unrotate and unstretch a screen-space vector (no zoom). Hand pan and zoom-about + /// use this. + pub fn unmap_vec(self, d: Vec2) -> Vec2 { + let d = if self.flip { vec2(-d.x, d.y) } else { d }; + let (c, s) = self.sincos(); + vec2((d.x * c + d.y * s) / self.sx(), -d.x * s + d.y * c) + } + + /// A document-space vector on screen: stretched, rotated, flipped and zoomed as the view + /// draws it (the inverse of [`Self::unmap_vec`], with the zoom). + pub fn map_vec(self, d: Vec2) -> Vec2 { + let (c, s) = self.sincos(); + let dx = d.x * self.sx(); + let v = vec2(dx * c - d.y * s, dx * s + d.y * c) * self.zoom; + if self.flip { vec2(-v.x, v.y) } else { v } + } + + pub fn to_screen(&self, x: f32, y: f32) -> Pos2 { + let (c, s) = self.sincos(); + let dx = (x - self.center[0]) * self.sx(); + let dy = y - self.center[1]; + let rx = dx * c - dy * s; + let ry = dx * s + dy * c; + let sx = if self.flip { -1.0 } else { 1.0 }; + self.rect.center() + vec2(rx * self.zoom * sx, ry * self.zoom) + } + pub fn to_doc(&self, p: Pos2) -> [f64; 2] { + let d = (p - self.rect.center()) / self.zoom; + let u = self.unmap_vec(d); + [(u.x + self.center[0]) as f64, (u.y + self.center[1]) as f64] + } + /// On-screen bounds of the image, including camera rotation and pixel aspect correction. + pub fn image_bounds(self, size: [u32; 2]) -> Rect { + let (c, s) = self.sincos(); + let w = size[0] as f32 * self.sx() * self.zoom; + let h = size[1] as f32 * self.zoom; + let center = self.to_screen(size[0] as f32 / 2.0, size[1] as f32 / 2.0); + Rect::from_center_size(center, vec2(c.abs() * w + s.abs() * h, s.abs() * w + c.abs() * h)) + } + pub fn doc_rect(&self, r: DRect) -> Rect { + let pts = [ + self.to_screen(r.x0 as f32, r.y0 as f32), + self.to_screen(r.x1 as f32, r.y0 as f32), + self.to_screen(r.x1 as f32, r.y1 as f32), + self.to_screen(r.x0 as f32, r.y1 as f32), + ]; + let mut min = pts[0]; + let mut max = pts[0]; + for p in pts { + min = min.min(p); + max = max.max(p); + } + Rect::from_min_max(min, max) + } +} + +/// Document point under a screen position on the main canvas, or `None` when the position is +/// outside it: the rulers are not part of the canvas, so drops on the ruler strip are not +/// canvas drops. Preset-panel drops and drag-and-drop placement share this so both land exactly +/// where the canvas draws. +pub fn doc_point_at(app: &PhotocraftApp, pos: Pos2) -> Option<[f64; 2]> { + let xf = ViewXform::active(app)?; + xf.rect.contains(pos).then(|| xf.to_doc(pos)) +} + +/// Fit the document into `area` (egui points) for a display with `ppp` physical pixels per +/// point; `View::zoom` is stored in physical pixels per document pixel. `aspect` is the +/// displayed pixel aspect ratio ([`ViewXform::aspect`]): the image is that much wider on screen. +pub fn fit_view(view: &mut View, doc: &Document, area: Vec2, ppp: f32, aspect: f32) { + let (w, h) = (doc.size.width as f32, doc.size.height as f32); + let shown_w = w * if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 }; + // Fit never magnifies past 100%: one image pixel per *physical* pixel, so the cap applies + // after the points → device pixels conversion (a 150% display would otherwise open at 150%). + let fit = ((area.x - 40.0) / shown_w).min((area.y - 40.0) / h) * ppp; + let zoom = crate::zoom_levels::clamp(fit.min(1.0), [doc.size.width, doc.size.height]); + view.zoom = zoom; + view.center = [w / 2.0, h / 2.0]; + view.fit_pending = false; + view.fill_pending = false; +} + +/// Ease a transient presentation camera over 220 ms without changing the requested camera. +pub(super) fn animated_view(view: &mut View, xf: ViewXform, ppp: f32, animated_zoom: bool, time: f64) -> View { + if !animated_zoom { + view.request_zoom_animation(false); + } + let target = (view.zoom, view.center); + // Clamping, a canvas resize, or another camera command can make the original anchor + // incompatible with the requested camera. The target must always win. + if let Some((doc, screen)) = view.zoom_anchor { + let offset = xf.unmap_vec((pos2(screen[0], screen[1]) - xf.rect.center()) / (view.zoom / ppp)); + if (doc[0] as f32 - offset.x - view.center[0]).abs() > 0.01 || (doc[1] as f32 - offset.y - view.center[1]).abs() > 0.01 { + view.zoom_anchor = None; + } + } + let mut shown = view.clone(); + if view.zoom_animating { + if view.zoom_transition.is_none_or(|a| a.target != target) { + view.zoom_transition = Some(crate::state::ZoomTransition { from: view.display_camera.unwrap_or(target), target, started: time }); + } + if let Some(a) = view.zoom_transition { + let elapsed = (time - a.started) / 0.22; + let t = if elapsed.is_finite() { elapsed.clamp(0.0, 1.0) as f32 } else { 1.0 }; + let ease = t * t * (3.0 - 2.0 * t); + let lerp = |from: f32, to: f32| from + (to - from) * ease; + shown.zoom = lerp(a.from.0, target.0); + shown.center = [lerp(a.from.1[0], target.1[0]), lerp(a.from.1[1], target.1[1])]; + if let Some((doc, screen)) = view.zoom_anchor { + let zoom = shown.zoom / ppp; + if zoom.is_finite() && zoom > 0.0 { + let offset = xf.unmap_vec((pos2(screen[0], screen[1]) - xf.rect.center()) / zoom); + shown.center = [doc[0] as f32 - offset.x, doc[1] as f32 - offset.y]; + } + } + if t >= 1.0 { + view.zoom_animating = false; + } + } + } + if !view.zoom_animating { + shown.zoom = target.0; + shown.center = target.1; + view.zoom_anchor = None; + view.zoom_transition = None; + } + view.display_camera = Some((shown.zoom, shown.center)); + shown +} + +/// Centre the document and zoom until it fills the canvas. One axis can extend beyond the +/// viewport, matching the Hand tool's Fill Screen action. +pub fn fill_view(view: &mut View, doc: &Document, area: Vec2, ppp: f32, aspect: f32) { + let (w, h) = (doc.size.width as f32, doc.size.height as f32); + let shown_w = w * if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 }; + let points = (area.x / shown_w).max(area.y / h); + let zoom = crate::zoom_levels::clamp(points * ppp, [doc.size.width, doc.size.height]); + view.zoom = zoom; + view.center = [w / 2.0, h / 2.0]; + view.fit_pending = false; + view.fill_pending = false; +} + +/// Where a wheel or pinch zoom anchors for a pointer at `p`: the pointer itself over the image, +/// otherwise the nearest point of the image (#3720). Anchoring on a pointer out on the gray +/// pasteboard slid the image away from it, out of the window after a few notches; Photoshop keeps +/// the image in view. Clamped in document space, so a rotated or flipped view behaves the same. +pub(super) fn wheel_anchor(xf: &ViewXform, p: Pos2, doc_size: [u32; 2]) -> Pos2 { + let [w, h] = doc_size; + let d = xf.to_doc(p); + if w == 0 || h == 0 || !(d[0].is_finite() && d[1].is_finite()) { + return p; + } + let c = [d[0].clamp(0.0, f64::from(w)), d[1].clamp(0.0, f64::from(h))]; + if c == d { p } else { xf.to_screen(c[0] as f32, c[1] as f32) } +} + +/// Zoom to `new_zoom` about `p`: keep its document point under the pointer, or move it to the +/// view centre when Zoom Clicked Point to Center (`center_on_point`) is enabled. +pub(super) fn zoom_about(view: &mut View, xf: &ViewXform, p: Pos2, new_zoom: f32, center_on_point: bool, ppp: f32) { + let before = xf.to_doc(p); + view.zoom = new_zoom; + if center_on_point { + view.center = [before[0] as f32, before[1] as f32]; + return; + } + // `new_zoom` is device px per document pixel; the pointer vector is in egui points. + let ppp = if ppp.is_finite() && ppp > 0.0 { ppp } else { 1.0 }; + let u = xf.unmap_vec((p - xf.rect.center()) / (new_zoom / ppp)); + view.center = [before[0] as f32 - u.x, before[1] as f32 - u.y]; +} From 3b2887fee1e1520544be61bd8dbcedf4b985813c Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:58:55 +0000 Subject: [PATCH 225/259] refactor(ui-egui): split transform_tool.rs into transform_tool/ --- crates/ui-egui/src/transform_tool.rs | 3133 +---------------- crates/ui-egui/src/transform_tool/begin.rs | 590 ++++ crates/ui-egui/src/transform_tool/commit.rs | 358 ++ .../ui-egui/src/transform_tool/drag_modes.rs | 334 ++ crates/ui-egui/src/transform_tool/draw.rs | 498 +++ .../ui-egui/src/transform_tool/options_bar.rs | 595 ++++ crates/ui-egui/src/transform_tool/pointer.rs | 304 ++ crates/ui-egui/src/transform_tool/preview.rs | 255 ++ crates/ui-egui/src/transform_tool/tests.rs | 24 +- crates/ui-egui/src/transform_tool/warp.rs | 186 + 10 files changed, 3168 insertions(+), 3109 deletions(-) create mode 100644 crates/ui-egui/src/transform_tool/begin.rs create mode 100644 crates/ui-egui/src/transform_tool/commit.rs create mode 100644 crates/ui-egui/src/transform_tool/drag_modes.rs create mode 100644 crates/ui-egui/src/transform_tool/draw.rs create mode 100644 crates/ui-egui/src/transform_tool/options_bar.rs create mode 100644 crates/ui-egui/src/transform_tool/pointer.rs create mode 100644 crates/ui-egui/src/transform_tool/preview.rs create mode 100644 crates/ui-egui/src/transform_tool/warp.rs diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index 58e412d784..1aac4e1854 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -22,6 +22,49 @@ use crate::PhotocraftApp; use crate::canvas::{ToolEvent, ViewXform}; use crate::state::{MadeLayer, Tool, TransformMode, TransformSession}; +mod begin; +mod commit; +mod drag_modes; +mod draw; +mod options_bar; +mod pointer; +mod preview; +mod warp; + +pub(crate) use begin::begin_content_aware; +pub use begin::{begin, begin_copy, begin_placed, begin_selection, begin_warp, enter_warp, leave_warp, 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}; +pub(crate) use drag_modes::{apply_drag, corner_distorts, legacy_mods}; +#[cfg(test)] +pub(crate) use drag_modes::{apply_mode_drag, unlinked_mods}; +#[cfg(test)] +use drag_modes::{keep_convex, turns}; +#[cfg(test)] +pub(crate) use draw::{Readout, live_readout, styled_frame}; +pub(crate) use draw::{carries_selection_of, draw_selection}; +pub use draw::{draw_content, draw_overlay}; +#[cfg(test)] +use draw::{front_vertices, handle_anchor}; +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, +}; +pub use options_bar::{options_bar, reset_warp}; +pub(crate) use pointer::{Gesture, Hit, hit, rotate_cursor_dir}; +#[cfg(test)] +use pointer::{accepts_outside_click, carry_pivot, near_rotate_corner, point_on_quad, rotation_degrees}; +pub use pointer::{cursor, pointer}; +use preview::Above; +pub(crate) use preview::solo_layer; +#[cfg(test)] +use preview::{covering, preview_image, show_only}; +pub use warp::{edit_session_warp, split}; +#[cfg(test)] +use warp::{on_section_edge, single_patch, split_cursor, surface_at, warp_hit, warp_pointer}; + /// Which Split button is armed. The guide follows the pointer and the split is added on release. #[derive(Clone, Copy, PartialEq, Eq)] enum SplitTool { @@ -187,3095 +230,5 @@ fn corners(r: [f64; 4]) -> [[f64; 2]; 4] { [[r[0], r[1]], [r[2], r[1]], [r[2], r[3]], [r[0], r[3]]] } -/// Start Free Transform on the active layer (or its selected pixels), or on the targeted unlinked -/// layer mask, alpha channel or Quick Mask. -pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { - if let Some((params, path)) = crate::vector_ui::free_transform_path(app) { - return begin_path(app, ctx, params, path); - } - if app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some()) { - app.run("select.drop", json!({}))?; - } - let target = crate::canvas::paint_target(app); - let st = app.session.active().ok_or("no document")?; - let (doc, revision) = (st.doc.clone(), st.revision); - let lone = photocraft_engine::transform_cmds::lone_target(&doc, st.active_layer, &json!({ "target": target })).map_err(|e| e.to_string())?.cloned(); - if let Some(surf) = lone { - return begin_lone(app, ctx, doc, surf, target); - } - let id = st.active_layer.ok_or("no active layer")?; - let layer = doc.layer(id).ok_or("no layer")?; - if photocraft_engine::transform_cmds::locked_for_transform(&doc, id) { - // Photoshop refuses before the box opens rather than when it is committed (#2585). - app.ui.open_dialog(crate::state::DialogKind::Error, json!({"message": tl!(LOCKED)}).as_object().cloned().unwrap_or_default()); - return Err(LOCKED.into()); - } - if matches!(layer.content, LayerContent::Adjustment(_)) && layer.mask.is_none() { - return Err("Adjustment layers have nothing to transform".into()); - } - // With a selection the box is the selection's (#5297). - let b = photocraft_engine::transform_cmds::transform_frame(&doc, layer); - if b.is_empty() { - return Err("Could not transform: the layer is empty".into()); - } - crate::type_tool::commit(app); - let rect = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64]; - let session = app.ui.alloc_id(); - // Preview document: the moving pixels removed (layer hidden, or the selection lifted out). - let mut pd = (*doc).clone(); - let mut lifted = None; - // Type, shapes and smart objects move whole, selection or not (#2630): only pixels are lifted. - if let Some(sel) = doc.selection.clone().filter(|_| !photocraft_engine::transform_cmds::moves_whole(layer) && layer.surface().is_some()) { - if let Some(surf) = pd.layer_mut(id).and_then(|l| l.surface_mut()) { - let (l, rest) = photocraft_engine::transform_cmds::split_selected(surf, &sel).map_err(|e| e.to_string())?; - *surf = rest; - lifted = Some(l); - } - } else if let Some(l) = pd.layer_mut(id) { - l.visible = false; - } - // 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); - // 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: Arc::new(pd), - texture, - opacity: layer.opacity * layer.fill_opacity, - above: Some(above), - styled: styled.then(|| crate::transform_fx::StyledPreview::new(format!("transform-{session}-styled"))), - follow: Some(Follow { revision, hidden: lifted.is_none() }), - 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, - }); - app.ui.transform = Some(TransformSession { - session, - layer: id.0, - rect, - quad: corners(rect), - pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], - interpolation: "bicubic".into(), - warp: None, - selection: false, - target: None, - path: None, - made: None, - mode: Default::default(), - content_aware: None, - skew_v: 0.0, - }); - start_steps(app); - Ok(()) -} - -/// Free Transform on a copy (⌥⌘T, no menu item): duplicates the active layer (with a selection, -/// its selected pixels, as Layer via Copy) and transforms the copy (#352). -pub fn begin_copy(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { - let selection = app.session.active().is_some_and(|d| d.doc.selection.is_some()); - let params = if selection { json!({}) } else { json!({"inPlace": true}) }; - app.run(if selection { "layer.new.layerViaCopy" } else { "layer.duplicate" }, params)?; - let made = app.session.active().and_then(|st| st.active_layer.map(|layer| (st.doc.id, layer))); - if let Err(e) = begin(app, ctx) { - if let Some((document, layer)) = made { - take_back_made(app, document, layer); - } - return Err(e); - } - if let Some(t) = app.ui.transform.as_mut() { - t.made = Some(MadeLayer::Copy); - } - Ok(()) -} - -/// Free Transform on the layer a file dropped on the canvas just placed, like the reference app's -/// Place: Esc takes the place back, ↩ makes the place and the transform one Place Embedded step. -pub fn begin_placed(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { - begin(app, ctx)?; - if let Some(t) = app.ui.transform.as_mut() { - t.made = Some(MadeLayer::Place); - } - Ok(()) -} - -/// Edit › Content-Aware Scale (#3096): a scale-only box over `region` of the active pixel layer -/// (the selection's bounds, else the layer's content), cleared under the box as the command -/// clears it. OK runs `edit.contentAwareScale` (cas_transform.rs) instead of `edit.transform`. -pub(crate) fn begin_content_aware( - app: &mut PhotocraftApp, - ctx: &egui::Context, - region: photocraft_geom::Rect, - live: crate::cas_transform::Live, -) -> Result<(), String> { - let st = app.session.active().ok_or("no document")?; - let (doc, revision) = (st.doc.clone(), st.revision); - let id = st.active_layer.ok_or("no active layer")?; - let layer = doc.layer(id).ok_or("no layer")?; - let surf = layer.surface().ok_or("Content-Aware Scale needs a pixel layer")?; - if region.is_empty() { - return Err("Could not scale: the layer is empty".into()); - } - crate::type_tool::commit(app); - let rect = [region.x0 as f64, region.y0 as f64, region.x1 as f64, region.y1 as f64]; - let session = app.ui.alloc_id(); - // The command clears the area before writing the result (a layer without transparency keeps it). - let mut pd = (*doc).clone(); - if let Some(s) = pd.layer_mut(id).and_then(|l| l.surface_mut()).filter(|s| s.format().alpha) { - let clear = vec![0.0; s.format().channels()]; - s.fill_rect(region, &clear); - s.prune(); - } - let max_side = ctx.input(|i| i.max_texture_side).max(app.gpu.as_ref().map_or(1, |g| g.max_texture_side())); - let above = Above::new(ctx, format!("transform-{session}-above"), &doc, id, max_side); - above.hide_in(&mut pd.layers); - let (image, uv) = crate::transform_tex::read_surface(surf, None, region, max_side); - let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), image, uv); - app.transform_preview = Some(TransformPreview { - session, - doc: Arc::new(pd), - texture, - opacity: layer.opacity * layer.fill_opacity, - above: Some(above), - follow: Some(Follow { revision, hidden: false }), - 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: Some(live), - styled: None, - }); - app.ui.transform = Some(TransformSession { - session, - layer: id.0, - rect, - quad: corners(rect), - pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], - interpolation: "bicubic".into(), - warp: None, - selection: false, - target: None, - path: None, - made: None, - mode: Default::default(), - content_aware: Some(Default::default()), - skew_v: 0.0, - }); - start_steps(app); - Ok(()) -} - -/// Undoes the layer a cancelled or failed session made (⌥⌘T's copy, a placed file), leaving -/// nothing to redo. -fn take_back_made(app: &mut PhotocraftApp, document: DocId, layer: LayerId) { - // Tabs can move or close while transforming. Only undo the creation in its own document, - // and only while it is still the latest step (it may already have been undone). - let Some(index) = app.session.documents().iter().position(|st| { - st.doc.id == document - && st.doc.layer(layer).is_some() - && st.history.past_len().checked_sub(1).and_then(|i| st.history.state(i)).is_some_and(|before| before.layer(layer).is_none()) - }) else { - return; - }; - let active = app.session.active_index(); - app.session.set_active(index); - if app.session.undo() - && let Some(st) = app.session.active_mut() - { - st.history.clear_redo(); - } - if let Some(active) = active { - app.session.set_active(active); - } - app.sync_views(); -} - -/// After the transform: the step that made the layer and the transform become one history step, -/// the transform's for a copy and Place Embedded for a placed file. -fn fold_made(app: &mut PhotocraftApp, document: DocId, layer: LayerId, made: MadeLayer) { - // A background commit lands in its own document, which need not be the active one by then. - let Some(index) = app.session.documents().iter().position(|st| st.doc.id == document) else { return }; - let active = app.session.active_index(); - app.session.set_active(index); - // Only when the step before the transform made the layer: a step taken while the box was - // open (New Layer, which also ends the box, #5667) stays its own, as does the made layer's. - if let Some(st) = app.session.active_mut() - && st.history.past_len().checked_sub(2).and_then(|i| st.history.state(i)).is_some_and(|before| before.layer(layer).is_none()) - { - st.history.purge_last(); - if made == MadeLayer::Place { - st.history.set_current_label(photocraft_engine::file_cmds::PLACE_EMBEDDED); - } - } - if let Some(active) = active { - app.session.set_active(active); - } -} - -/// Free Transform of a targeted unlinked layer mask, alpha channel or Quick Mask by itself: the -/// box frames its content (or the selection) and previews the moving values in grey over the -/// document with them vacated. -fn begin_lone( - app: &mut PhotocraftApp, - ctx: &egui::Context, - doc: Arc, - surf: photocraft_raster::Surface, - target: serde_json::Value, -) -> Result<(), String> { - use photocraft_engine::transform_cmds as tc; - let b = tc::target_frame(&doc, &surf); - if b.is_empty() { - return Err("Could not transform: nothing is selected".into()); - } - let whole; - let sel = match &doc.selection { - Some(s) => s, - None => { - let mut s = photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8); - s.fill_rect(b, &[1.0]); - whole = s; - &whole - } - }; - let (lifted, rest) = tc::split_gray_selected(&surf, sel).map_err(|e| e.to_string())?.ok_or("this channel can't be transformed")?; - crate::type_tool::commit(app); - let layer = app.session.active().and_then(|st| st.active_layer).map_or(0, |l| l.0); - let mut pd = (*doc).clone(); - let tp = json!({ "target": target }); - if let Ok(Some(s)) = tc::lone_target_mut(&mut pd, Some(LayerId(layer)), &tp) { - *s = rest; - } - let rect = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64]; - let session = app.ui.alloc_id(); - let max_side = ctx.input(|i| i.max_texture_side).max(app.gpu.as_ref().map_or(1, |g| g.max_texture_side())); - let (image, uv) = crate::transform_tex::read_surface(&lifted, None, b, max_side); - let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), image, uv); - app.transform_preview = Some(TransformPreview { - session, - doc: Arc::new(pd), - texture, - opacity: 0.6, - above: None, - styled: None, - follow: None, - 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, - }); - app.ui.transform = Some(TransformSession { - session, - layer, - rect, - quad: corners(rect), - pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], - interpolation: "bicubic".into(), - warp: None, - selection: false, - target: Some(target), - path: None, - made: None, - mode: Default::default(), - content_aware: None, - skew_v: 0.0, - }); - start_steps(app); - Ok(()) -} - -/// Edit › Free Transform Path: the box frames the path's anchors and handles and draws the -/// path through it; OK commits one `path.transform` step. -fn begin_path(app: &mut PhotocraftApp, ctx: &egui::Context, params: serde_json::Value, path: photocraft_doc::vector::Path) -> Result<(), String> { - let (x0, y0, x1, y1) = path.control_bounds().ok_or("the path has no points to transform")?; - let st = app.session.active().ok_or("no document")?; - let doc = st.doc.clone(); - let layer = st.active_layer.or_else(|| doc.layers.first().map(|l| l.id)).ok_or("no layer")?; - crate::type_tool::commit(app); - // A straight horizontal or vertical path still gets a box to turn. - let rect = [x0, y0, x1.max(x0 + 1.0), y1.max(y0 + 1.0)]; - let session = app.ui.alloc_id(); - let texture = - crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), egui::ColorImage::new([1, 1], vec![Color32::TRANSPARENT]), [1.0, 1.0]); - app.transform_preview = Some(TransformPreview { - session, - doc, - texture, - opacity: 1.0, - styled: 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: Some(path), - content_aware: None, - above: None, - follow: None, - committing: None, - }); - app.ui.transform = Some(TransformSession { - session, - layer: layer.0, - rect, - quad: corners(rect), - pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], - interpolation: "bicubic".into(), - warp: None, - selection: false, - target: None, - path: Some(params), - made: None, - mode: Default::default(), - content_aware: None, - skew_v: 0.0, - }); - start_steps(app); - Ok(()) -} - -/// The affine map taking `rect`'s corners to `quad`'s; `None` when the box was distorted out of a -/// parallelogram (Distort, Perspective): the path then goes as a `quad`. -fn rect_to_quad_affine(r: [f64; 4], q: [[f64; 2]; 4]) -> Option { - let (w, h) = (r[2] - r[0], r[3] - r[1]); - if w <= 0.0 || h <= 0.0 { - return None; - } - let tol = 1e-3 * (1.0 + w.max(h)); - if (q[0][0] + q[2][0] - q[1][0] - q[3][0]).abs() > tol || (q[0][1] + q[2][1] - q[1][1] - q[3][1]).abs() > tol { - return None; - } - let (a, b) = ((q[1][0] - q[0][0]) / w, (q[1][1] - q[0][1]) / w); - let (c, d) = ((q[3][0] - q[0][0]) / h, (q[3][1] - q[0][1]) / h); - let m = [a, b, c, d, q[0][0] - a * r[0] - c * r[1], q[0][1] - b * r[0] - d * r[1]]; - m.iter().all(|v| v.is_finite()).then_some(photocraft_geom::Affine { m }) -} - -/// Start Select › Transform Selection: the same box over the selection's bounds, previewing the -/// selection mask (the marching ants are hidden meanwhile); commits `select.transformSelection`. -pub fn begin_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { - let st = app.session.active().ok_or("no document")?; - let doc = st.doc.clone(); - let sel = doc.selection.clone().ok_or("no selection")?; - let b = sel.content_bounds(); - if b.is_empty() { - return Err("no selection".into()); - } - let layer = st.active_layer.or_else(|| doc.layers.first().map(|l| l.id)).ok_or("no layer")?; - crate::type_tool::commit(app); - let rect = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64]; - let session = app.ui.alloc_id(); - let (w, h) = (b.width() as usize, b.height() as usize); - let k = w.max(h).div_ceil(2048).max(1); - let (tw, th) = (w.div_ceil(k), h.div_ceil(k)); - let mut px = vec![Color32::TRANSPARENT; tw * th]; - for ty in 0..th { - for tx in 0..tw { - let m = sel.sample_channel(b.x0 + (tx * k) as i32, b.y0 + (ty * k) as i32, 0).clamp(0.0, 1.0); - px[ty * tw + tx] = Color32::from_rgba_unmultiplied(120, 170, 255, (m * 110.0) as u8); - } - } - let uv = [w as f32 / (tw * k) as f32, h as f32 / (th * k) as f32]; - let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), egui::ColorImage::new([tw, th], px), uv); - let mut pd = (*doc).clone(); - pd.selection = None; - app.transform_preview = Some(TransformPreview { - session, - doc: Arc::new(pd), - texture, - opacity: 1.0, - above: None, - styled: None, - follow: None, - 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, - }); - app.ui.transform = Some(TransformSession { - session, - layer: layer.0, - rect, - quad: corners(rect), - pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], - interpolation: "bilinear".into(), - warp: None, - selection: true, - target: None, - path: None, - made: None, - mode: Default::default(), - content_aware: None, - skew_v: 0.0, - }); - start_steps(app); - Ok(()) -} - -/// Start (or switch an active Free Transform into) Warp mode. -pub fn begin_warp(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { - if app.ui.transform.as_ref().is_some_and(|t| t.content_aware.is_some()) { - return Err(CAS_ONLY_SCALES.into()); - } - let fresh = app.ui.transform.is_none(); - if fresh { - begin(app, ctx)?; - } - enter_warp(app, ctx); - // Started in Warp: that is where Undo stops. Switching an open transform to Warp is a step. - if fresh { - start_steps(app); - } - Ok(()) -} - -/// Switch to Warp mode: a smart object's existing warp (when the box is untouched), else a -/// custom mesh following the current box (so a transform made first carries over). Editable type -/// gets its own Warp Text style instead ([`enter_type_warp`]). -pub fn enter_warp(app: &mut PhotocraftApp, ctx: &egui::Context) { - if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none()) && warps_type(app) { - return enter_type_warp(app, ctx); - } - let existing = - app.session.active().and_then(|d| d.doc.layer(LayerId(app.ui.transform.as_ref()?.layer)).and_then(photocraft_engine::warp_cmds::smart_warp_doc_space)); - let Some(t) = app.ui.transform.as_mut() else { return }; - // Warp moves layers and paths (#3027): a lone mask or channel keeps the box. - if t.warp.is_some() || t.target.is_some() { - return; - } - if t.quad == corners(t.rect) - && !t.selection - && t.path.is_none() - && let Some(w) = existing - { - t.rect = w.bounds; - t.quad = corners(w.bounds); - t.warp = Some(w); - return; - } - let h = Homography::rect_to_quad(t.rect, t.quad).unwrap_or(Homography::IDENTITY); - let mesh = BezierMesh::identity(t.rect, 1, 1).map_points(|p| { - let (x, y) = h.apply(p[0], p[1]); - [x, y] - }); - t.warp = Some(Warp::custom(mesh, t.rect)); -} - -/// 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 { - let Some(t) = &app.ui.transform else { return false }; - if t.selection || t.target.is_some() || t.path.is_some() { - return false; - } - app.session.active().and_then(|st| st.doc.layer(LayerId(t.layer))).is_some_and(|l| matches!(l.content, LayerContent::Text(_))) -} - -/// Warp on editable type, as in Photoshop: no rasterizing, no mesh to drag, just the warp styles -/// of the options bar (Warp Text's). A box scaled or rotated first is applied first (that keeps -/// type editable). The preview shows the type without its current Warp Text, under that style. -fn enter_type_warp(app: &mut PhotocraftApp, ctx: &egui::Context) { - if app.ui.transform.as_ref().is_some_and(|t| t.quad != corners(t.rect)) { - commit(app); - if app.ui.transform.is_some() { - return; // refused: the box stays as it was - } - if let Err(e) = begin(app, ctx) { - app.ui.status = e; - return; - } - } - let (Some(t), Some(st)) = (app.ui.transform.as_ref(), app.session.active()) else { return }; - let (id, session) = (LayerId(t.layer), t.session); - let doc = st.doc.clone(); - let Some(LayerContent::Text(text)) = doc.layer(id).map(|l| &l.content) else { return }; - let current = text.warp.clone(); - let mut plain = (*doc).clone(); - if let Some(LayerContent::Text(tt)) = plain.layer_mut(id).map(|l| &mut l.content) - && current.is_some() - { - tt.warp = None; - photocraft_engine::type_cmds::refresh(&doc, tt); - } - let Some(b) = plain.layer(id).map(|l| photocraft_engine::transform_cmds::transform_bounds(&plain, l)).filter(|b| !b.is_empty()) else { return }; - let rect = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64]; - if current.is_some() - && let Some(pv) = app.transform_preview.as_mut() - { - let max_side = ctx.input(|i| i.max_texture_side).max(app.gpu.as_ref().map_or(1, |g| g.max_texture_side())); - // Read as the session's texels were: without the style when the box draws it itself. - let (image, uv) = preview_image(&plain, id, None, b, max_side, pv.styled.is_some()); - pv.texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), image, uv); - } - let warp = - current.as_ref().and_then(|w| WarpStyle::parse(&w.style).filter(|s| s.is_preset()).map(|s| (w, s))).map_or(Warp::none(rect), |(w, style)| Warp { - style, - bend: f64::from(w.value), - h_distort: f64::from(w.horizontal_distortion), - v_distort: f64::from(w.vertical_distortion), - vertical: !w.horizontal, - ..Warp::none(rect) - }); - if let Some(t) = app.ui.transform.as_mut() { - t.rect = rect; - t.quad = corners(rect); - t.pivot = [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0]; - t.warp = Some(warp); - } -} - -/// Leave Warp mode (back to the box; warp edits are dropped, like Photoshop's mode toggle on an -/// untouched warp). -pub fn leave_warp(app: &mut PhotocraftApp) { - if let Some(t) = app.ui.transform.as_mut() { - t.warp = None; - } - if let Some(pv) = app.transform_preview.as_mut() { - pv.split_tool = None; - pv.split_pointer = None; - pv.split_placing = false; - pv.split_quick = false; - } -} - -/// Texels of the moving pixels over `b`: full resolution unless the long side exceeds the GPU's -/// `max_side` (#91: this used to be capped at 2048 px, so big layers previewed blurry), plus the -/// uv extent covering `b`. `bare` leaves the layer's own style, opacity and fill out of a -/// flattened render: the styled preview applies them to the moved pixels itself. -fn preview_image( - doc: &Document, - id: LayerId, - lifted: Option<&photocraft_raster::Surface>, - b: photocraft_geom::Rect, - max_side: usize, - bare: bool, -) -> (egui::ColorImage, [f32; 2]) { - let layer = doc.layer(id); - // Linked masks move with the pixels, so the moving texels carry them (#205). - let mask = layer.and_then(|l| preview_mask(l, b)); - // Groups and type/fill layers preview from a flattened render of just that layer. - let rendered; - let surf: Option<&photocraft_raster::Surface> = match (lifted, layer.and_then(|l| l.surface())) { - (Some(s), _) => Some(s), - (None, Some(s)) if layer.is_some_and(|l| matches!(l.content, LayerContent::Raster(_))) => Some(s), - _ => { - let mut solo = doc.clone(); - if layer.is_some() { - solo_layer(&mut solo.layers, id); - } else { - // Keep the previous fallback for an invalid id: render the document, with only - // top-level clipping disabled. Production callers get ids from this document. - for l in &mut solo.layers { - l.clipped = false; - } - } - if let Some(l) = solo.layer_mut(id).filter(|_| bare) { - l.effects.enabled = false; - l.opacity = 1.0; - l.fill_opacity = 1.0; - } - let buf = photocraft_compose::render(&solo, b); - let mut s = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); - let flat: Vec = buf.px.iter().flat_map(|p| *p).collect(); - s.write_region(b, &flat); - rendered = s; - Some(&rendered) - } - }; - let Some(surf) = surf else { return (egui::ColorImage::new([1, 1], vec![Color32::TRANSPARENT]), [1.0, 1.0]) }; - // A flattened render already has the masks applied. - let raw = lifted.is_some() || layer.is_some_and(|l| matches!(l.content, LayerContent::Raster(_))); - crate::transform_tex::read_surface(surf, mask.as_ref().filter(|_| raw), b, max_side) -} - -/// The layer's masks as the moving texels carry them: the enabled masks when all of them are linked -/// (the vector mask and feathering folded in as the compositor applies them), else the linked -/// pixel mask alone. `None` when no enabled mask moves with the pixels. -fn preview_mask(l: &photocraft_doc::Layer, b: photocraft_geom::Rect) -> Option { - use crate::transform_tex::PreviewMask; - let pixel = l.mask.as_ref().filter(|m| m.enabled); - let vector = l.vector_mask.as_ref().filter(|v| v.enabled); - let linked_pixel = pixel.filter(|m| m.linked); - if pixel.is_none_or(|m| m.linked) - && vector.is_none_or(|v| v.linked) - && let Some(surface) = photocraft_compose::masks::combined_mask(l, b) - { - return Some(PreviewMask { surface, density: 1.0 }); - } - linked_pixel.map(|m| PreviewMask { surface: m.surface.clone(), density: m.density }) -} - -/// The layers covering the moving one ([`covering`]), composited on their own and drawn over its -/// preview, so the layer keeps its place in the stack while the box is open (#2439): they cover -/// it, as in Photoshop, instead of the moving pixels covering the whole document. The canvas -/// under the box leaves them out ([`Above::hide_in`]). Built when the session starts and again -/// when an edit changes the document; the box itself moves without re-compositing. -struct Above { - ctx: egui::Context, - name: String, - max_side: usize, - /// The covering layers (whole layers or groups, at any depth). - ids: Vec, - /// Their composite and the canvas area it covers; `None` when nothing visible covers the layer. - shown: Option<(crate::transform_tex::PreviewTextures, photocraft_geom::Rect)>, -} - -impl Above { - 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(), shown: None }; - a.rebuild(doc, id); - a - } - - /// Composite what covers layer `id` of `doc` (the live document) again. - fn rebuild(&mut self, doc: &Document, id: LayerId) { - self.ids.clear(); - covering(&doc.layers, id, &mut self.ids); - let mut up = doc.clone(); - show_only(&mut up.layers, &self.ids); - let canvas = up.bounds(); - let rect = up - .layers - .iter() - .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) - }); - } - - /// Leave the covering layers out of `layers` (the document under the box). - 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); - } - } - } - - /// Draw the composite over the moving pixels. - fn draw(&self, painter: &egui::Painter, xf: &ViewXform, display: Option<&photocraft_engine::display_color::CanvasDisplay>) { - let Some((texture, r)) = &self.shown else { return }; - let (tex, uv) = texture.pick_display(painter.ctx(), xf.zoom * painter.ctx().pixels_per_point(), 1.0, false, display); - let mut mesh = egui::Mesh::with_texture(tex); - let corners = [(r.x0, r.y0, 0.0, 0.0), (r.x1, r.y0, uv[0], 0.0), (r.x1, r.y1, uv[0], uv[1]), (r.x0, r.y1, 0.0, uv[1])]; - for (x, y, u, v) in corners { - mesh.vertices.push(egui::epaint::Vertex { pos: xf.to_screen(x as f32, y as f32), uv: pos2(u, v), color: Color32::WHITE }); - } - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(0, 2, 3); - painter.add(mesh); - } -} - -/// `rect` of `doc`'s composite as premultiplied texels: full resolution when it fits in -/// `max_side`, composited in bands (no full-size float copy), else area-averaged down to fit. -fn composite_image(doc: &Document, rect: photocraft_geom::Rect, max_side: usize) -> (egui::ColorImage, [f32; 2]) { - let (w, h) = (rect.width() as usize, rect.height() as usize); - let to_color = |p: &[u8; 4]| Color32::from_rgba_unmultiplied(p[0], p[1], p[2], p[3]); - if w.max(h) <= max_side.max(1) { - let mut px = Vec::with_capacity(w * h); - let _ = photocraft_compose::render_bands(doc, rect, 0, |band| { - px.extend(band.to_rgba8().pixels.as_chunks::<4>().0.iter().map(to_color)); - Ok::<(), ()>(()) - }); - px.resize(w * h, Color32::TRANSPARENT); - return (egui::ColorImage::new([w, h], px), [1.0, 1.0]); - } - let k = w.max(h).div_ceil(max_side.max(1)); - let (tw, th) = (w.div_ceil(k).max(1), h.div_ceil(k).max(1)); - let buf = photocraft_compose::render_reduced_rect(doc, rect, tw as u32, th as u32); - let px: Vec = buf.to_rgba8().pixels.as_chunks::<4>().0.iter().map(to_color).collect(); - let [bw, bh] = [buf.rect.width() as usize, buf.rect.height() as usize]; - if px.len() != bw * bh || bw == 0 || bh == 0 { - return (egui::ColorImage::new([1, 1], vec![Color32::TRANSPARENT]), [1.0, 1.0]); - } - (egui::ColorImage::new([bw, bh], px), [1.0, 1.0]) -} - -/// A layer that composites over anything the same as over transparency, so it can be drawn over -/// the moving pixels on its own: a Normal layer that isn't an adjustment, or a Normal or Pass -/// Through group of such layers (hidden layers count, they draw nothing). Adjustment layers and -/// the other blend modes depend on what is under them. -fn plain(l: &photocraft_doc::Layer) -> bool { - use photocraft_color::BlendMode; - !l.visible - || match &l.content { - LayerContent::Adjustment(_) => false, - LayerContent::Group(g) => matches!(l.blend, BlendMode::Normal | BlendMode::PassThrough) && g.children.iter().all(plain), - _ => l.blend == BlendMode::Normal, - } -} - -/// The layers over `id` in `layers` (bottom to top, groups holding `id` searched too) that cover -/// it in the preview: from the top down, while they are [`plain`]. The first layer that isn't -/// stops the search, so it and everything under it stay in the document under the box as before -/// (an adjustment there keeps applying to the layers under it). A clipping group goes as a whole, -/// and the layers clipped to `id` (or to the group holding it) stay with it. -fn covering(layers: &[photocraft_doc::Layer], id: LayerId, out: &mut Vec) { - let mut end = layers.len(); - while end > 0 { - // The clipping group ending at `end`: its base and the layers clipped to it. - let mut start = end - 1; - while start > 0 && layers.get(start).is_some_and(|l| l.clipped) { - start -= 1; - } - let unit = layers.get(start..end).unwrap_or_default(); - if unit.iter().any(|l| contains(l, id)) { - // A group holding `id` with nothing clipped to it: go on inside it. - if let [g] = unit - && g.id != id - && let LayerContent::Group(group) = &g.content - && matches!(g.blend, photocraft_color::BlendMode::Normal | photocraft_color::BlendMode::PassThrough) - { - covering(&group.children, id, out); - } - return; - } - if !unit.iter().all(plain) { - return; - } - out.extend(unit.iter().map(|l| l.id)); - end = start; - } -} - -/// Hide everything in `layers` but the `keep` layers and the groups holding them. -fn show_only(layers: &mut [photocraft_doc::Layer], keep: &[LayerId]) { - for l in layers.iter_mut() { - if keep.contains(&l.id) { - continue; - } - match &mut l.content { - LayerContent::Group(g) if g.children.iter().any(|c| keep.iter().any(|k| contains(c, *k))) => { - // This ancestor only clips the covering children. Its background is already - // on the base canvas; drawing it again would cover the moving layer in white. - if let Some(board) = &mut g.artboard { - board.background = photocraft_doc::ArtboardBackground::Transparent; - } - show_only(&mut g.children, keep); - } - _ => l.visible = false, - } - } -} - -/// Leave only `id`, its descendants and the groups holding it visible. Every layer on that path -/// is detached from its clipping base because the base is hidden in this isolated render (#5239). -/// Hide every layer but `id` and the groups holding it, and unclip those, so a render shows that -/// layer alone (the Free Transform preview, Liquify's one-layer backdrop). -pub(crate) fn solo_layer(layers: &mut [photocraft_doc::Layer], id: LayerId) { - for l in layers { - if l.id == id { - l.clipped = false; - continue; - } - match &mut l.content { - LayerContent::Group(g) if g.children.iter().any(|c| contains(c, id)) => { - l.clipped = false; - // Isolate the child, not the artboard's paper. Keep the board for clipping. - if let Some(board) = &mut g.artboard { - board.background = photocraft_doc::ArtboardBackground::Transparent; - } - solo_layer(&mut g.children, id); - } - _ => l.visible = false, - } - } -} - -fn contains(l: &photocraft_doc::Layer, id: LayerId) -> bool { - l.id == id || matches!(&l.content, LayerContent::Group(g) if g.children.iter().any(|c| contains(c, id))) -} - -/// Undo and Redo while the commit runs in the background (Free Transform, or Warp). -const STILL_APPLYING: &str = "Free Transform is still being applied"; -const STILL_WARPING: &str = "Warp is still being applied"; - -pub fn commit(app: &mut PhotocraftApp) { - if committing(app).is_some() { - return; - } - let document = app.transform_preview.as_ref().map(|pv| pv.doc.id); - if document.is_some_and(|id| app.session.active().is_none_or(|st| st.doc.id != id)) { - cancel(app); - return; - } - let type_layer = warps_type(app); - let Some(t) = app.ui.transform.take() else { return }; - let mut preview = app.transform_preview.take(); - if let Some(options) = &t.content_aware { - crate::cas_transform::commit(app, &t, options); - return; - } - if t.selection { - let mut p = json!({"rect": t.rect, "interpolation": t.interpolation}); - match &t.warp { - Some(w) if !w.is_identity() => p["warp"] = json!(w), - Some(_) => return, - None if t.quad == corners(t.rect) => return, - None => p["quad"] = json!(t.quad), - } - if let Err(e) = app.run("select.transformSelection", p) { - keep_open(app, t, preview, e); - } - return; - } - if let Some(target) = &t.path { - let mut p = target.clone(); - match &t.warp { - Some(w) if w.is_identity() => return, - Some(w) => p["warp"] = json!(w), - None if t.quad == corners(t.rect) => return, - // Distort and Perspective map the path through the box (#3027). - None => match rect_to_quad_affine(t.rect, t.quad) { - Some(a) => p["matrix"] = json!(a.m), - None => { - p["rect"] = json!(t.rect); - p["quad"] = json!(t.quad); - } - }, - } - if let Err(e) = app.run("path.transform", p) { - keep_open(app, t, preview, e); - } - return; - } - let made = t.made; - let r = if let Some(w) = &t.warp { - // Type with a Warp Text can be warped back to None; the engine skips an unchanged style. - if w.is_identity() && !type_layer { - return; - } - app.run("edit.transform.warp", json!({"layer": t.layer, "rect": t.rect, "warp": w, "interpolation": t.interpolation})) - } else { - if t.quad == corners(t.rect) { - return; // untouched: nothing to do and no history step; a ⌥⌘T copy or a place stays - } - let mut p = json!({"layer": t.layer, "rect": t.rect, "quad": t.quad, "interpolation": t.interpolation}); - if let Some(target) = &t.target { - p["target"] = target.clone(); - } - app.run("edit.transform", p) - }; - // A large layer's warp runs in the background: the session stays until the job ends. - if let Ok(v) = &r - && let Some(job) = v.get("pending").and_then(serde_json::Value::as_bool).filter(|p| *p).and(v.get("job")).and_then(serde_json::Value::as_u64) - && let Some(pv) = preview.as_mut() - { - pv.committing = Some(JobId(job)); - app.ui.transform = Some(t); - app.transform_preview = preview; - return; - } - match r { - // Nothing changed (an untouched cylinder or Warp Text): no step to fold a copy into, so - // it stays its own step, as for an untouched box. - Ok(v) if v.get("changed") == Some(&json!(false)) => {} - Ok(_) => finish(app, document, LayerId(t.layer), made, true), - Err(e) => keep_open(app, t, preview, e), - } -} - -/// After the transform landed or not: fold the layer the session made into its step, or take it -/// back. -fn finish(app: &mut PhotocraftApp, document: Option, layer: LayerId, made: Option, landed: bool) { - let (Some(made), Some(document)) = (made, document) else { return }; - if landed { - fold_made(app, document, layer, made); - } else { - take_back_made(app, document, layer); - } -} - -/// The job applying the transform, while it runs. -pub(crate) fn committing(app: &PhotocraftApp) -> Option { - app.transform_preview.as_ref().and_then(|pv| pv.committing) -} - -/// 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 committing(app) != Some(e.id) { - return; - } - let (Some(t), Some(mut pv)) = (app.ui.transform.take(), app.transform_preview.take()) else { return }; - // A refused commit (a result over the pixel budget, #3773) keeps the box open, as inline, - // unless picking another tool or layer started it: then the box ends, as Esc would. - if let JobOutcome::Failed(msg) = &e.outcome { - pv.committing = None; - keep_open(app, t, Some(pv), msg.clone()); - if switched_away(app) { - cancel(app); - } - return; - } - finish(app, Some(pv.doc.id), LayerId(t.layer), t.made, matches!(e.outcome, JobOutcome::Done(_))); -} - -/// A commit the engine refused (a result over the pixel budget, #3773): the box stays open as it -/// was, with the reason in the status bar, so the transform can be changed or cancelled. A copy or -/// a placed layer it made goes only when it is cancelled. -fn keep_open(app: &mut PhotocraftApp, t: TransformSession, preview: Option, e: String) { - app.ui.transform = Some(t); - app.transform_preview = preview; - app.ui.status = e; -} - -/// A transform whose layer or document went away (undo, close) ends silently; picking another tool -/// or selecting another layer (Layers panel, ⌘-click, the control channel) applies it, so the box -/// never stays on a layer that is no longer the active one (#1400). Checked every frame and before -/// each pointer event, so a press with a tool chosen just before it (`ui.pointer`'s `tool`) goes to -/// that tool. -pub fn end_if_left(app: &mut PhotocraftApp) { - let Some(t) = &app.ui.transform else { return }; - if committing(app).is_some() { - return; - } - let Some(st) = app.session.active() else { return cancel(app) }; - - let layer = LayerId(t.layer); - let made = t.made; - let preview_doc_id = app.transform_preview.as_ref().map(|pv| pv.doc.id); - let switched_document = preview_doc_id.is_some_and(|id| id != st.doc.id); - - let editing_placed_smart_object = switched_document - && made == Some(MadeLayer::Place) - && preview_doc_id - .is_some_and(|parent_id| app.session.smart_links.iter().any(|link| link.parent == parent_id && link.child == st.doc.id && link.layer == layer)); - - if editing_placed_smart_object { - app.ui.transform = None; - app.transform_preview = None; - } else if switched_document || st.doc.layer(layer).is_none() { - cancel(app); - } else if switched_away(app) { - commit(app); - // Picking another tool or layer can't leave a refused transform open: it ends, as Esc would. - // A commit still running in the background isn't refused: cancelling it would throw the - // transform away (and a dropped file with it, #5665). It ends the session when it lands, - // or ends it as Esc would if it is refused then (`on_job_event`). - if app.ui.transform.is_some() && committing(app).is_none() { - cancel(app); - } - } -} - -/// Another tool picked, or (outside Transform Selection) another layer selected, since the box -/// opened: the session ends ([`end_if_left`], #1400). -fn switched_away(app: &PhotocraftApp) -> bool { - let (Some(t), Some(st)) = (&app.ui.transform, app.session.active()) else { return false }; - app.transform_preview.as_ref().is_some_and(|pv| pv.tool != app.ui.tool) || (!t.selection && st.active_layer.is_some_and(|active| active.0 != t.layer)) -} - -/// Edits made while the box is open show in the preview at once, not only after the commit -/// (#1384): the moving layer's opacity, fill and visibility tint the moving pixels, and the -/// document under them (other layers, and the part of the layer a selection leaves behind) is -/// rebuilt from the current one. The moving pixels keep the session's. Called before the canvas -/// reads the preview, so it never caches a revision with the old preview. -pub fn follow_edits(app: &mut PhotocraftApp) { - let (Some(t), Some(pv)) = (&app.ui.transform, app.transform_preview.as_mut()) else { return }; - let Some(follow) = pv.follow.as_mut() else { return }; - let Some(st) = app.session.active().filter(|st| st.doc.id == pv.doc.id && st.revision != follow.revision) else { return }; - let id = LayerId(t.layer); - let (Some(live), Some(moving)) = (st.doc.layer(id), pv.doc.layer(id)) else { return }; - let mut pd = (*st.doc).clone(); - if let Some(l) = pd.layer_mut(id) { - l.content = moving.content.clone(); - l.visible = l.visible && !follow.hidden; - } - if let Some(a) = pv.above.as_mut() { - a.rebuild(&st.doc, id); - a.hide_in(&mut pd.layers); - } - pv.opacity = if live.visible { live.opacity * live.fill_opacity } else { 0.0 }; - follow.revision = st.revision; - pv.doc = Arc::new(pd); -} - -pub fn cancel(app: &mut PhotocraftApp) { - // Esc while the commit runs cancels the job; the session ends when it does. - if let Some(job) = committing(app) { - crate::jobs_ui::cancel(app, job); - return; - } - let transform = app.ui.transform.take(); - let preview = app.transform_preview.take(); - if let (Some(t), Some(pv)) = (transform, preview) - && t.made.is_some() - { - take_back_made(app, pv.doc.id, LayerId(t.layer)); - } -} - -/// The session's starting box: where Undo stops. -fn start_steps(app: &mut PhotocraftApp) { - if let (Some(t), Some(pv)) = (&app.ui.transform, app.transform_preview.as_mut()) { - pv.steps = Steps { settled: Some(Step::of(t)), ..Steps::default() }; - } -} - -/// Record the box as an undo step whenever it comes to rest in a new state: once per drag (on -/// release), nudge or option edit (once typing in its field ends). Call once per frame. -pub fn track_steps(app: &mut PhotocraftApp, ctx: &egui::Context) { - let (Some(t), Some(pv)) = (&app.ui.transform, app.transform_preview.as_mut()) else { return }; - if pv.gesture.is_some() || pv.warp_drag.is_some() || ctx.input(|i| i.pointer.any_down()) || ctx.text_edit_focused() { - // Whatever comes to rest after this is more than the nudge. - pv.steps.fold = false; - return; - } - pv.steps.settle(Step::of(t)); -} - -/// Arrow keys while Free Transform is active: move the box (and its pivot) by `(dx, dy)`. -/// Nudges that follow each other closely are one Undo step of the session (`nudge_bundle`). -pub(crate) fn nudge(app: &mut PhotocraftApp, dx: f64, dy: f64) { - let (pause, now) = (crate::nudge_bundle::pause(app), app.nudge_bundle.now); - let Some(t) = app.ui.transform.as_mut().filter(|t| t.warp.is_none()) else { return }; - let before = Step::of(t); - t.quad = t.quad.map(|q| [q[0] + dx, q[1] + dy]); - t.pivot = [t.pivot[0] + dx, t.pivot[1] + dy]; - if let Some(pv) = app.transform_preview.as_mut() { - pv.steps.nudged(&before, Step::of(t), now, pause); - } -} - -/// 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"; - -/// 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 { - let t = app.ui.transform.as_ref()?; - if committing(app).is_some() { - return box_command(id).then_some(false); - } - let steps = app.transform_preview.as_ref().map(|pv| &pv.steps); - match id { - // Content-Aware Scale's box only scales: no switching it to another transform or Warp. - "edit.freeTransform" | "edit.freeTransformCopy" if t.content_aware.is_some() => Some(false), - i if i.starts_with("edit.transform.") && t.content_aware.is_some() => Some(false), - "edit.undo" => Some(steps.is_some_and(|s| s.can_undo(&Step::of(t)))), - "edit.redo" => Some(steps.is_some_and(|s| !s.redo.is_empty())), - // 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), - // 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()), - // Editable type can't be distorted (#2630, as #2701 rules for the menus outside a box). - "edit.transform.distort" | "edit.transform.perspective" if moves_type(app, t) => Some(false), - _ => None, - } -} - -/// Does the box move an editable type layer (not its selection outline, a lone mask or a path)? -fn moves_type(app: &PhotocraftApp, t: &TransformSession) -> bool { - !t.selection - && t.target.is_none() - && t.path.is_none() - && app.session.active().and_then(|st| st.doc.layer(LayerId(t.layer))).is_some_and(|l| matches!(l.content, LayerContent::Text(_))) -} - -/// Edit › Transform's Rotate and Flip presets while a box is open: what they do to the box, as -/// `(kx, ky, angle)`: a scale along the box's own axes, then a rotation (radians, clockwise on -/// screen), both about the reference point. -fn box_preset(id: &str) -> Option<(f64, f64, f64)> { - use std::f64::consts::{FRAC_PI_2, PI}; - Some(match id { - "edit.transform.rotate180" => (1.0, 1.0, PI), - "edit.transform.rotate90Cw" => (1.0, 1.0, FRAC_PI_2), - "edit.transform.rotate90Ccw" => (1.0, 1.0, -FRAC_PI_2), - "edit.transform.flipHorizontal" => (-1.0, 1.0, 0.0), - "edit.transform.flipVertical" => (1.0, -1.0, 0.0), - _ => return None, - }) -} - -/// While transforming, the box owns the history for every caller (menus, shortcuts, the control -/// channel, MCP): Undo and Redo step through it, and Toggle Last State and History state jumps, -/// which would change the document under the box, are refused. Edit › Transform's Rotate and -/// Flip turn the box itself, as in Photoshop, instead of the layer under it; committing stays -/// with ↩ and the options bar. -/// `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() -} - -pub fn intercept(app: &mut PhotocraftApp, id: &str) -> Option> { - let warping = app.ui.transform.as_ref()?.warp.is_some(); - if committing(app).is_some() { - return box_command(id).then(|| Err(if warping { STILL_WARPING } else { STILL_APPLYING }.into())); - } - match id { - "edit.undo" => Some(Ok(step(app, false))), - "edit.redo" => Some(Ok(step(app, true))), - "edit.toggleLastState" | "history.selectState" | "edit.contentAwareScale" | "edit.puppetWarp" | SAVE_FOR_WEB => { - Some(Err("Commit or cancel the transform first".into())) - } - _ => { - let (kx, ky, angle) = box_preset(id)?; - if warping { - return Some(Err("Commit or cancel the transform first".into())); - } - scale_about_pivot(app, kx, ky); - rotate_about_pivot(app, angle); - Some(Ok(json!({"transform": app.ui.transform}))) - } - } -} - -/// Undo (or redo) one step of the open session; nothing mid-drag or with no step to take. -fn step(app: &mut PhotocraftApp, redo: bool) -> serde_json::Value { - let Some(t) = app.ui.transform.as_mut() else { return serde_json::Value::Null }; - let Some(pv) = app.transform_preview.as_mut().filter(|pv| pv.gesture.is_none() && pv.warp_drag.is_none()) else { - return serde_json::Value::Null; - }; - let s = &mut pv.steps; - s.settle(Step::of(t)); - let (from, to) = if redo { (&mut s.redo, &mut s.undo) } else { (&mut s.undo, &mut s.redo) }; - let Some(step) = from.pop() else { return serde_json::Value::Null }; - to.push(Step::of(t)); - s.settled = Some(step.clone()); - step.restore(t); - json!({"transform": t}) -} - -/// Which part of the box a document point hits. -#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] -pub(crate) enum Hit { - Corner(usize), - Edge(usize), - Pivot, - Inside, - Outside, -} - -/// The nearest handle within `tol` (on a small box their grab areas overlap), else inside or -/// outside the box. -pub(crate) fn hit(t: &TransformSession, p: [f64; 2], tol: f64) -> Hit { - let d = |a: [f64; 2]| ((a[0] - p[0]).powi(2) + (a[1] - p[1]).powi(2)).sqrt(); - let mid = |i: usize| { - let (a, b) = (t.quad[i], t.quad[(i + 1) % 4]); - [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0] - }; - let handles = (0..4).map(|i| (t.quad[i], Hit::Corner(i))).chain((0..4).map(|i| (mid(i), Hit::Edge(i)))).chain([(t.pivot, Hit::Pivot)]); - let nearest = handles.map(|(q, h)| (d(q), h)).filter(|(dist, _)| *dist < tol).min_by(|a, b| a.0.total_cmp(&b.0)); - match nearest { - Some((_, h)) => h, - None if inside(&t.quad, p) => Hit::Inside, - None => Hit::Outside, - } -} - -fn inside(q: &[[f64; 2]; 4], p: [f64; 2]) -> bool { - let mut c = false; - for i in 0..4 { - let (a, b) = (q[i], q[(i + 3) % 4]); - if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0] { - c = !c; - } - } - c -} - -/// Transient drag state (kept in egui memory; not part of the serialised session). -#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] -pub(crate) struct Gesture { - pub(crate) hit: Hit, - pub(crate) start: [f64; 2], - pub(crate) quad0: [[f64; 2]; 4], - pub(crate) pivot0: [f64; 2], -} - -/// A click outside the box accepts the transform; a drag outside still rotates it. -/// Decide on release, so the rotation zone keeps working for drags. The screen-sized -/// click tolerance absorbs pointer jitter without accepting a real rotation gesture. -fn accepts_outside_click(g: Gesture, end: [f64; 2], tol: f64) -> bool { - g.hit == Hit::Outside && (end[0] - g.start[0]).hypot(end[1] - g.start[1]) <= 2.0 * tol / HANDLE_PX -} - -/// Pointer input while transforming. Returns false when no transform is active. -pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { - let Some(t) = app.ui.transform.clone() else { return false }; - if committing(app).is_some() { - return true; - } - let tol = handle_tolerance(app); - if t.warp.is_some() { - warp_pointer(app, ev, tol, mods); - return true; - } - let Some(pv) = app.transform_preview.as_mut() else { return false }; - match ev { - ToolEvent::Down { x, y, .. } => { - let mut h = hit(&t, [x, y], tol); - // ⌥-click away from the handles moves the reference point there (and drags it). - if mods.alt - && matches!(h, Hit::Inside | Hit::Outside) - && let Some(s) = app.ui.transform.as_mut() - { - s.pivot = [x, y]; - h = Hit::Pivot; - } - // Distort only moves corners (and the whole box from inside): no rotating, no edges. - // Even in Distort mode, remember an outside press so a plain click can - // accept the transform. A drag outside remains inert in that mode, in Skew, and in - // Content-Aware Scale, which only scales and moves. - pv.gesture = (mode_allows(t.mode, h) || h == Hit::Outside).then_some(Gesture { hit: h, start: [x, y], quad0: t.quad, pivot0: t.pivot }); - } - ToolEvent::Move { x, y, .. } | ToolEvent::Up { x, y } => { - let g = pv.gesture; - if matches!(ev, ToolEvent::Up { .. }) { - pv.gesture = None; - } - // Clicking an empty spot commits instead of silently arming rotation (#2851). - // Dragging the rotation zone and Option-clicking to move the pivot - // keep their existing behavior. - if matches!(ev, ToolEvent::Up { .. }) && g.is_some_and(|g| accepts_outside_click(g, [x, y], tol)) { - commit(app); - return true; - } - let type_layer = moves_type(app, &t); - let adjusted = g.map(|g| drag_mods(app, &t, g.hit, mods)); - if let (Some(g), Some((mode, mods)), Some(s)) = (g, adjusted, app.ui.transform.as_mut()) - && mode_allows(t.mode, g.hit) - && (t.content_aware.is_none() || g.hit != Hit::Outside) - { - if t.content_aware.is_some() { - let mut mods = mode_mods(mode, g.hit, mods); - // Content-Aware Scale: ⌘ neither skews nor distorts. - mods.command = false; - apply_drag(s, g, [x, y], mods); - } else { - apply_mode_drag(s, g, [x, y], mode, type_layer, mods); - } - round_to_pixel_grid(app); - } - } - } - crate::snap_ui::retain_transform_lines(app, mods); - true -} - -/// Preferences › Tools › Snap Vector Tools and Transforms to Pixel Grid (#5751): while a shape -/// layer or a path is moved or scaled (the box still an upright rectangle), its edges stay on -/// whole pixels, whatever the tool. Rounding the pointer alone left the edges off by the grab -/// offset, and a proportional scale off by its ratio: a shape dragged to 540 px came out 539.6. -/// Rotated, skewed and distorted boxes are left as dragged. -fn round_to_pixel_grid(app: &mut PhotocraftApp) { - if !app.session.prefs().tools.snap_vector_tools_and_transforms_to_pixel_grid { - return; - } - let Some(t) = app.ui.transform.as_ref() else { return }; - if t.selection || t.warp.is_some() || t.content_aware.is_some() || t.target.is_some() { - return; - } - let vector = - t.path.is_some() || app.session.active().and_then(|st| st.doc.layer(LayerId(t.layer))).is_some_and(|l| matches!(l.content, LayerContent::Shape(_))); - if !vector || !upright(&t.quad) { - return; - } - let q = t.quad.map(|p| p.map(f64::round)); - // A box narrower than a pixel keeps its size rather than collapsing. - if (q[1][0] - q[0][0]).abs() < 1.0 || (q[3][1] - q[0][1]).abs() < 1.0 || q.iter().flatten().any(|v| !v.is_finite()) { - return; - } - if let Some(s) = app.ui.transform.as_mut() { - s.quad = q; - } -} - -/// Whether corners clockwise from top-left form an axis-aligned rectangle (flips included). -fn upright(q: &[[f64; 2]; 4]) -> bool { - let near = |a: f64, b: f64| (a - b).abs() < 1e-6; - near(q[0][1], q[1][1]) && near(q[2][1], q[3][1]) && near(q[0][0], q[3][0]) && near(q[1][0], q[2][0]) -} - -/// The same effective modifiers drive the geometry and decide whether Ctrl is a distortion -/// gesture rather than the ordinary snap override. Keep type and Content-Aware Scale refusals. -fn drag_mods(app: &PhotocraftApp, t: &TransformSession, hit: Hit, mods: egui::Modifiers) -> (TransformMode, egui::Modifiers) { - let (mode, mods) = if distort_refused(app, t) { scale_not_distort(t.mode, hit, mods) } else { (t.mode, mods) }; - let legacy = app.session.prefs().general.use_legacy_free_transform; - (mode, legacy_mods(legacy, hit, unlinked_mods(app.ui.transform_unlinked, legacy, hit, mods))) -} - -/// Only a freely distorted corner can snap its proposed position. Perspective moves paired -/// corners on one axis; Skew, Warp and Content-Aware Scale have their own constrained geometry. -pub(crate) fn corner_distorts(app: &PhotocraftApp, index: usize, mods: egui::Modifiers) -> bool { - let Some(t) = app.ui.transform.as_ref() else { return false }; - if t.quad.get(index).is_none() || t.warp.is_some() || t.content_aware.is_some() || t.mode == TransformMode::Skew { - return false; - } - let (mode, mods) = drag_mods(app, t, Hit::Corner(index), mods); - let mods = mode_mods(mode, Hit::Corner(index), mods); - mods.command && !(mods.alt && mods.shift) -} - -/// Editable type can be scaled, rotated and skewed but not distorted (#2630): the rule that greys -/// Distort and Perspective in `enable_rules::disabled`, for the box's own layer. A box on a path, -/// on the selection outline or on a lone mask or channel moves no type. -fn distort_refused(app: &PhotocraftApp, t: &TransformSession) -> bool { - t.path.is_none() - && !t.selection - && t.target.is_none() - && app.session.active().and_then(|st| st.doc.layer(LayerId(t.layer))).is_some_and(|l| matches!(l.content, LayerContent::Text(_))) -} - -/// Where Distort and Perspective are refused ([`distort_refused`]), ⌘-drag and ⌘⌥⇧-drag of a -/// corner scale like a plain corner drag (with ⌥ and ⇧ keeping their meaning), so the box never -/// takes a shape the commit would refuse (#3010). -fn scale_not_distort(mode: TransformMode, hit: Hit, mut mods: egui::Modifiers) -> (TransformMode, egui::Modifiers) { - if matches!(hit, Hit::Corner(_)) { - mods.command = false; - } - let mode = if matches!(mode, TransformMode::Distort | TransformMode::Perspective) { TransformMode::Free } else { mode }; - (mode, mods) -} - -/// Preferences › General › Use Legacy Free Transform, Photoshop's scaling before CC 2019: corner -/// drags stretch freely and ⇧ keeps the proportions, edge drags stretch their one axis whatever -/// the keys. The default is proportional for both, with ⇧ freeing them. -pub(crate) fn legacy_mods(legacy: bool, hit: Hit, mut mods: egui::Modifiers) -> egui::Modifiers { - if legacy && !mods.command { - match hit { - Hit::Corner(_) => mods.shift = !mods.shift, - Hit::Edge(_) => mods.shift = true, - _ => {} - } - } - mods -} - -/// The options bar's Maintain Aspect Ratio link turned off: corner and edge drags stretch freely -/// and ⇧ keeps the proportions, as in Photoshop CC 2019 and later (#4174). The legacy preference -/// already works that way, so it is left alone there. -pub(crate) fn unlinked_mods(unlinked: bool, legacy: bool, hit: Hit, mut mods: egui::Modifiers) -> egui::Modifiers { - if unlinked && !legacy && !mods.command && matches!(hit, Hit::Corner(_) | Hit::Edge(_)) { - mods.shift = !mods.shift; - } - mods -} - -/// Distort / Perspective modes: a corner drag acts as if that gesture's keys were held (⌘-drag a -/// corner distorts, ⌘⌥⇧-drag a corner adds perspective). Skew has its own ([`apply_mode_drag`]). -fn mode_mods(mode: TransformMode, hit: Hit, mut mods: egui::Modifiers) -> egui::Modifiers { - match (mode, hit) { - (TransformMode::Distort, Hit::Corner(_)) => mods.command = true, - (TransformMode::Perspective, Hit::Corner(_)) => { - mods.command = true; - mods.alt = true; - mods.shift = true; - } - _ => {} - } - mods -} - -/// A handle drag in Edit › Transform `mode` (`Free` for Free Transform). `type_layer`: the box -/// moves editable type, which only takes affine transforms. -pub(crate) fn apply_mode_drag(s: &mut TransformSession, g: Gesture, p: [f64; 2], mode: TransformMode, type_layer: bool, mut mods: egui::Modifiers) { - if !mode_allows(mode, g.hit) { - return; - } - match (mode, g.hit) { - // Skew, as in Photoshop (#3437): a corner moves alone along one of its two edges, - // whichever the drag mostly follows; ⌥ moves the opposite corner the other way. - (TransformMode::Skew, Hit::Corner(i)) if i < 4 => { - let (d, q0) = ([p[0] - g.start[0], p[1] - g.start[1]], g.quad0); - // Corners 0..3 = TL, TR, BR, BL: the neighbour along the top/bottom edge, and along - // the left/right one. - let along = |j: usize| { - let e = [q0[i][0] - q0[j][0], q0[i][1] - q0[j][1]]; - let l = e[0].hypot(e[1]); - let u = if l > 0.0 { [e[0] / l, e[1] / l] } else { [0.0, 0.0] }; - let t = d[0] * u[0] + d[1] * u[1]; - [t * u[0], t * u[1]] - }; - let (hn, vn) = ([1, 0, 3, 2][i], [3, 2, 1, 0][i]); - let (h, v) = (along(hn), along(vn)); - let (m, partner) = if h[0].hypot(h[1]) >= v[0].hypot(v[1]) { (h, hn) } else { (v, vn) }; - // Editable type stays a parallelogram: the corner's whole edge slides with it. - let moved: &[usize] = if type_layer { &[i, partner] } else { &[i] }; - let mut q = q0; - for k in 0..4 { - let sign = if moved.contains(&k) { - 1.0 - } else if mods.alt && (if type_layer { true } else { k == (i + 2) % 4 }) { - // ⌥: the opposite corner (on type, the opposite edge) the other way. - -1.0 - } else { - continue; - }; - if let (Some(dst), Some(src)) = (q.get_mut(k), q0.get(k)) { - *dst = [src[0] + sign * m[0], src[1] + sign * m[1]]; - } - } - s.quad = keep_convex(q0, q); - s.pivot = carry_pivot(q0, s.quad, g.pivot0); - } - // Rotate (#3941): a corner or edge turns about the reference point, the same drag as the - // zone just outside the box. Free Transform still scales from those handles. - (TransformMode::Rotate, Hit::Corner(_) | Hit::Edge(_)) => { - let mut g = g; - g.hit = Hit::Outside; - apply_drag(s, g, p, mods); - } - // Skew: an edge slides only along itself (⌘⇧ in Free Transform). - (TransformMode::Skew, Hit::Edge(_)) => { - mods.command = true; - mods.shift = true; - apply_drag(s, g, p, mods); - } - _ => apply_drag(s, g, p, mode_mods(mode, g.hit, mods)), - } -} - -/// What a drag can do in each Edit › Transform mode: in Distort only the corners (and moving the -/// box from inside); in Skew everything but rotating from outside the box (#3437). A click -/// outside still commits. -fn mode_allows(mode: TransformMode, h: Hit) -> bool { - match mode { - TransformMode::Distort => !matches!(h, Hit::Outside | Hit::Edge(_)), - TransformMode::Skew => h != Hit::Outside, - _ => true, - } -} - -/// The turn at each corner of a quad (cross products of consecutive edges): all the same sign -/// for a convex quad, mixed for a concave or self-intersecting one. -fn turns(q: &[[f64; 2]; 4]) -> [f64; 4] { - std::array::from_fn(|k| { - let (a, b, c) = (q[k], q[(k + 1) % 4], q[(k + 2) % 4]); - (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) - }) -} - -/// Is `q` convex with the orientation `sign`, every corner turning by more than a sliver? -fn convex(q: &[[f64; 2]; 4], sign: f64, min_turn: f64) -> bool { - turns(q).iter().all(|t| t * sign > min_turn) -} - -/// Distort and Perspective stop a corner where the box would turn concave or fold over itself, -/// as Photoshop does (#1323): the result moves from `from` towards `to` as far as the quad stays -/// convex. A box that is not convex to begin with is left free. -fn keep_convex(from: [[f64; 2]; 4], to: [[f64; 2]; 4]) -> [[f64; 2]; 4] { - let t0 = turns(&from); - let sign = t0[0].signum(); - // A sliver: a thousandth of the starting box's smallest turn, so the stop is short of flat. - let min_turn = t0.iter().map(|t| t.abs()).fold(f64::INFINITY, f64::min) * 1e-3; - if !(min_turn.is_finite() && min_turn > 0.0 && convex(&from, sign, 0.0)) || convex(&to, sign, min_turn) { - return to; - } - let lerp = |t: f64| -> [[f64; 2]; 4] { std::array::from_fn(|k| [from[k][0] + (to[k][0] - from[k][0]) * t, from[k][1] + (to[k][1] - from[k][1]) * t]) }; - let (mut lo, mut hi) = (0.0f64, 1.0f64); - for _ in 0..40 { - let mid = (lo + hi) / 2.0; - if convex(&lerp(mid), sign, min_turn) { lo = mid } else { hi = mid } - } - lerp(lo) -} - -pub(crate) fn apply_drag(s: &mut TransformSession, g: Gesture, p: [f64; 2], mods: egui::Modifiers) { - let (dx, dy) = (p[0] - g.start[0], p[1] - g.start[1]); - match g.hit { - Hit::Inside => { - // ⇧ locks the move to the axes and diagonals; the current offset keeps the lock stable. - let (dx, dy) = if mods.shift { - let prev = [s.quad[0][0] - g.quad0[0][0], s.quad[0][1] - g.quad0[0][1]]; - let d = crate::move_mods::constrain([dx, dy], Some(prev), crate::move_mods::TRANSFORM_DIRECTIONS); - (d[0], d[1]) - } else { - (dx, dy) - }; - s.quad = g.quad0.map(|q| [q[0] + dx, q[1] + dy]); - s.pivot = [g.pivot0[0] + dx, g.pivot0[1] + dy]; - } - Hit::Pivot => s.pivot = p, - Hit::Outside => { - let a0 = (g.start[1] - g.pivot0[1]).atan2(g.start[0] - g.pivot0[0]); - let a1 = (p[1] - g.pivot0[1]).atan2(p[0] - g.pivot0[0]); - let mut da = a1 - a0; - if mods.shift { - // Snap the resulting angle to 15° steps. - let base = (g.quad0[1][1] - g.quad0[0][1]).atan2(g.quad0[1][0] - g.quad0[0][0]); - let step = 15f64.to_radians(); - da = ((base + da) / step).round() * step - base; - } - let (sn, cs) = da.sin_cos(); - let c = g.pivot0; - s.quad = g.quad0.map(|q| { - let (x, y) = (q[0] - c[0], q[1] - c[1]); - [c[0] + x * cs - y * sn, c[1] + x * sn + y * cs] - }); - } - Hit::Corner(i) if mods.command && mods.alt && mods.shift => { - // Perspective: the corner moves along the dominant axis and the corner sharing that - // side moves the opposite way. - s.quad = g.quad0; - let horizontal = dx.abs() >= dy.abs(); - // Corners 0..3 = TL, TR, BR, BL: horizontal drags pair along the top/bottom edge, - // vertical ones along the left/right edge. - let j = match (i, horizontal) { - (0, true) => 1, - (1, true) => 0, - (2, true) => 3, - (3, true) => 2, - (0, false) => 3, - (3, false) => 0, - (1, false) => 2, - _ => 1, - }; - let (mx, my) = if horizontal { (dx, 0.0) } else { (0.0, dy) }; - let mut q = g.quad0; - q[i] = [g.quad0[i][0] + mx, g.quad0[i][1] + my]; - q[j] = [g.quad0[j][0] - mx, g.quad0[j][1] - my]; - s.quad = keep_convex(g.quad0, q); - s.pivot = carry_pivot(g.quad0, s.quad, g.pivot0); - } - Hit::Corner(i) if mods.command => { - // Distort: move the corner freely, up to where the box would fold over (#1323). - let mut q = g.quad0; - q[i] = [g.quad0[i][0] + dx, g.quad0[i][1] + dy]; - s.quad = keep_convex(g.quad0, q); - s.pivot = carry_pivot(g.quad0, s.quad, g.pivot0); - } - Hit::Edge(i) if mods.command => { - // Skew: the edge's two corners move together (⇧: only along the edge). - let (a, b) = (i, (i + 1) % 4); - let (mut mx, mut my) = (dx, dy); - if mods.shift { - let e = [g.quad0[b][0] - g.quad0[a][0], g.quad0[b][1] - g.quad0[a][1]]; - let l2 = e[0] * e[0] + e[1] * e[1]; - let t = if l2 > 0.0 { (dx * e[0] + dy * e[1]) / l2 } else { 0.0 }; - (mx, my) = (t * e[0], t * e[1]); - } - s.quad = g.quad0; - s.quad[a] = [g.quad0[a][0] + mx, g.quad0[a][1] + my]; - s.quad[b] = [g.quad0[b][0] + mx, g.quad0[b][1] + my]; - if mods.alt { - // ⌥: the opposite edge skews the other way (about the centre). - let (c, d) = ((i + 2) % 4, (i + 3) % 4); - s.quad[c] = [g.quad0[c][0] - mx, g.quad0[c][1] - my]; - s.quad[d] = [g.quad0[d][0] - mx, g.quad0[d][1] - my]; - } - s.pivot = carry_pivot(g.quad0, s.quad, g.pivot0); - } - Hit::Corner(_) | Hit::Edge(_) => { - // Work in the box's own (unit) frame so rotated/skewed boxes scale along their axes. - let Some(h) = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], g.quad0) else { return }; - let Some(inv) = h.inverse() else { return }; - let (u, v) = inv.apply(p[0], p[1]); - let (pu, pv) = inv.apply(g.pivot0[0], g.pivot0[1]); - // Which sides of the unit box move: (u = 0, u = 1) and (v = 0, v = 1). - let (mu, mv) = match g.hit { - Hit::Corner(0) => ((true, false), (true, false)), - Hit::Corner(1) => ((false, true), (true, false)), - Hit::Corner(2) => ((false, true), (false, true)), - Hit::Corner(3) => ((true, false), (false, true)), - Hit::Edge(0) => ((false, false), (true, false)), - Hit::Edge(1) => ((false, true), (false, false)), - Hit::Edge(2) => ((false, false), (false, true)), - _ => ((true, false), (false, false)), - }; - // Each axis scales by a factor `k` about an anchor: the opposite side, or with ⌥ the - // reference point, wherever it was set (#1329). The dragged handle follows the cursor. - let axis = |moving: (bool, bool), at: f64, pivot: f64| -> (f64, f64) { - if !moving.0 && !moving.1 { - return (0.5, 1.0); - } - let handle = if moving.0 { 0.0 } else { 1.0 }; - let anchor = if mods.alt { pivot } else { 1.0 - handle }; - let d = handle - anchor; - // A reference point on the dragged side leaves nothing to scale against. - let k = if d.abs() > 1e-9 { (at - anchor) / d } else { 1.0 }; - (anchor, if k.is_finite() { k } else { 1.0 }) - }; - let (mut au, mut ku) = axis(mu, u, pu); - let (mut av, mut kv) = axis(mv, v, pv); - // Corners and edges scale proportionally by default; ⇧ frees them (the legacy - // preference swaps the two for corners and always stretches edges, `legacy_mods`). - let corner = matches!(g.hit, Hit::Corner(_)); - if !corner && !mods.shift { - // An edge sets the scale of its own axis, and the other axis follows by the same - // factor about the middle of the box (⌥: about the reference point, as for - // corners), so the opposite edge's handle stays put. Past the opposite edge only - // the dragged axis flips. - if mu.0 || mu.1 { - (av, kv) = (if mods.alt { pv } else { 0.5 }, ku.abs()); - } else { - (au, ku) = (if mods.alt { pu } else { 0.5 }, kv.abs()); - } - } - if corner && !mods.shift { - let k = ku.abs().max(kv.abs()); - (ku, kv) = (k * ku.signum(), k * kv.signum()); - } - let r = [au - au * ku, av - av * kv, au + (1.0 - au) * ku, av + (1.0 - av) * kv]; - let map = |a: f64, b: f64| { - let (x, y) = h.apply(a, b); - [x, y] - }; - s.quad = [map(r[0], r[1]), map(r[2], r[1]), map(r[2], r[3]), map(r[0], r[3])]; - // ⌥ scales about the reference point, so it stays put; otherwise it rides along with - // the box, keeping its place in it (#1329). - s.pivot = if mods.alt { g.pivot0 } else { carry_pivot(g.quad0, s.quad, g.pivot0) }; - } - } -} - -fn anchor_uv(anchor: usize) -> (f64, f64) { - match anchor { - 0 => (0.0, 0.0), - 1 => (0.5, 0.0), - 2 => (1.0, 0.0), - 3 => (0.0, 0.5), - 4 => (0.5, 0.5), - 5 => (1.0, 0.5), - 6 => (0.0, 1.0), - 7 => (0.5, 1.0), - 8 => (1.0, 1.0), - _ => (0.5, 0.5), - } -} - -fn point_on_quad(quad: [[f64; 2]; 4], anchor: usize) -> [f64; 2] { - let (u, v) = anchor_uv(anchor); - if let Some(h) = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], quad) { - let (x, y) = h.apply(u, v); - if x.is_finite() && y.is_finite() { - return [x, y]; - } - } - match anchor { - 0 => quad[0], - 1 => [(quad[0][0] + quad[1][0]) / 2.0, (quad[0][1] + quad[1][1]) / 2.0], - 2 => quad[1], - 3 => [(quad[0][0] + quad[3][0]) / 2.0, (quad[0][1] + quad[3][1]) / 2.0], - 4 => [(quad[0][0] + quad[1][0] + quad[2][0] + quad[3][0]) / 4.0, (quad[0][1] + quad[1][1] + quad[2][1] + quad[3][1]) / 4.0], - 5 => [(quad[1][0] + quad[2][0]) / 2.0, (quad[1][1] + quad[2][1]) / 2.0], - 6 => quad[3], - 7 => [(quad[2][0] + quad[3][0]) / 2.0, (quad[2][1] + quad[3][1]) / 2.0], - 8 => quad[2], - _ => [(quad[0][0] + quad[1][0] + quad[2][0] + quad[3][0]) / 4.0, (quad[0][1] + quad[1][1] + quad[2][1] + quad[3][1]) / 4.0], - } -} - -/// Where the reference point lands when the box goes from `quad0` to `quad`: the same place -/// within the box, as in Photoshop, where it is attached to the bounding box (#1329). A box -/// that has collapsed leaves it where it was. -fn carry_pivot(quad0: [[f64; 2]; 4], quad: [[f64; 2]; 4], pivot0: [f64; 2]) -> [f64; 2] { - let unit = [0.0, 0.0, 1.0, 1.0]; - let (Some(h0), Some(h1)) = (Homography::rect_to_quad(unit, quad0), Homography::rect_to_quad(unit, quad)) else { return pivot0 }; - let Some(inv) = h0.inverse() else { return pivot0 }; - let (u, v) = inv.apply(pivot0[0], pivot0[1]); - let (x, y) = h1.apply(u, v); - if x.is_finite() && y.is_finite() { [x, y] } else { pivot0 } -} - -/// An anchor or a handle on a section line. The inner control points of a patch are not shown. -fn on_section_edge(i: usize, j: usize) -> bool { - i.is_multiple_of(3) || j.is_multiple_of(3) -} - -/// Index of the warp control point within `tol` of `p` (nearest anchor or handle). -fn warp_hit(w: &Warp, p: [f64; 2], tol: f64) -> Option { - let m = w.mesh.as_ref()?; - let nx = m.nx(); - m.points - .iter() - .enumerate() - .filter(|(i, _)| on_section_edge(i % nx, i / nx)) - .map(|(i, q)| (i, ((q[0] - p[0]).powi(2) + (q[1] - p[1]).powi(2)).sqrt())) - .filter(|(_, d)| *d < tol) - .min_by(|a, b| a.1.total_cmp(&b.1)) - .map(|(i, _)| i) -} - -/// A 1×1 mesh (Grid › Default) draws rule-of-thirds guides. Denser presets are real patch -/// boundaries only — a 3×3 is three cells, not a third-line lattice inside every cell. -fn single_patch(mesh: &BezierMesh) -> bool { - mesh.us.len() == 2 && mesh.vs.len() == 2 -} - -/// The surface parameters under `p` when it is inside the warped mesh, else None. -fn surface_at(mesh: &BezierMesh, p: [f64; 2]) -> Option<(f64, f64)> { - let (s, t) = mesh.param_at(p); - let q = mesh.eval(s, t); - ((q[0] - p[0]).hypot(q[1] - p[1]) < 1.0).then_some((s, t)) -} - -/// Ctrl-click (or Option-click) picks the split: crosswise in the open, and the perpendicular -/// split when the pointer's grid position `(s, t)` is close to an existing grid line. -fn quick_split_kind(mesh: &BezierMesh, bounds: [f64; 4], (s, t): (f64, f64)) -> SplitTool { - let w = (bounds[2] - bounds[0]).abs().max(1.0); - let h = (bounds[3] - bounds[1]).abs().max(1.0); - let su = (8.0 / w).clamp(0.02, 0.12); - let sv = (8.0 / h).clamp(0.02, 0.12); - let thirds = single_patch(mesh); - let near = |knots: &[f64], v: f64, tol: f64| { - knots.iter().any(|k| *k > 0.0 && *k < 1.0 && (k - v).abs() < tol) || (thirds && [1.0 / 3.0, 2.0 / 3.0].iter().any(|k| (k - v).abs() < tol)) - }; - match (near(&mesh.us, s, su), near(&mesh.vs, t, sv)) { - (true, false) => SplitTool::Horizontal, - (false, true) => SplitTool::Vertical, - _ => SplitTool::Cross, - } -} - -/// The cursor for a split armed at grid position `(s, t)` of warp grid `m`: the arrow across the -/// split line as it looks on screen. A vertical split line runs along the grid's columns and is -/// placed by moving across them, in the grid's own direction there, so the arrow turns with a -/// turned or bent grid and with the view. -fn split_cursor(m: &BezierMesh, tool: SplitTool, (s, t): (f64, f64), xf: &ViewXform) -> CursorIcon { - let e = 1e-3; - let (a, b) = match tool { - SplitTool::Vertical => (m.eval((s - e).max(0.0), t), m.eval((s + e).min(1.0), t)), - SplitTool::Horizontal => (m.eval(s, (t - e).max(0.0)), m.eval(s, (t + e).min(1.0))), - SplitTool::Cross => return CursorIcon::Crosshair, - }; - crate::tool_cursor::resize([b[0] - a[0], b[1] - a[1]], xf) -} - -/// Armed split tool, or Option held: the guide tracks the pointer and the split lands on release. -/// Returns false when this event is an ordinary control-point drag. -fn split_gesture(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { - let armed = app.transform_preview.as_ref().and_then(|p| p.split_tool); - let placing = app.transform_preview.as_ref().is_some_and(|p| p.split_placing); - match ev { - ToolEvent::Down { x, y, .. } if armed.is_some() || mods.alt || mods.command => { - if let Some(pv) = app.transform_preview.as_mut() { - pv.split_placing = true; - pv.split_pointer = Some([x, y]); - pv.split_quick = armed.is_none(); - } - true - } - ToolEvent::Move { x, y, .. } if placing => { - if let Some(pv) = app.transform_preview.as_mut() { - pv.split_pointer = Some([x, y]); - } - true - } - ToolEvent::Up { x, y } if placing => { - let quick = app.transform_preview.as_ref().is_some_and(|p| p.split_quick); - if let Some(pv) = app.transform_preview.as_mut() { - pv.split_placing = false; - pv.split_pointer = None; - pv.split_quick = false; - } - let kind = if let Some(tool) = armed { - Some(tool) - } else if quick { - app.ui.transform.as_ref().and_then(|t| t.warp.as_ref()).map(|w| { - let m = w.to_mesh(1, 1); - quick_split_kind(&m, w.bounds, m.param_at([x, y])) - }) - } else { - None - }; - if let Some(kind) = kind { - // On an existing line, or a click the drag path also delivers, this is a no-op. - let _ = split(app, kind.command(), Some([x, y])); - } - true - } - _ => false, - } -} - -/// Drags the warp grid. A press on an anchor or handle moves that point (an anchor carries its -/// handles along); a press anywhere else inside the grid pulls the surface under the pointer. -/// Preset warps turn into a custom mesh when the press grabs something. An armed split tool, or -/// Ctrl / Option held, places a split where the pointer is released instead. -fn warp_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tol: f64, mods: egui::Modifiers) { - // Type takes only the warp styles: nothing on the canvas to drag or split (#3004). - if warps_type(app) { - return; - } - if split_gesture(app, ev, mods) { - return; - } - 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, .. } => { - // A preset warp becomes a custom mesh only when the press grabs one of its points. - let custom = if w.mesh.is_none() || w.style != WarpStyle::Custom { Warp::custom(w.to_mesh(1, 1), w.bounds) } else { w.clone() }; - let pts0 = custom.mesh.as_ref().map(|m| m.points.clone()).unwrap_or_default(); - pv.warp_drag = warp_hit(&custom, [x, y], tol).map(|index| WarpDrag::Point { index, start: [x, y], pts0: pts0.clone() }).or_else(|| { - let (s, t) = surface_at(custom.mesh.as_ref()?, [x, y])?; - Some(WarpDrag::Surface { s, t, start: [x, y], pts0 }) - }); - if pv.warp_drag.is_some() { - *w = custom; - } - } - ToolEvent::Move { x, y, .. } | ToolEvent::Up { x, y } => { - match (&pv.warp_drag, w.mesh.as_mut()) { - (Some(WarpDrag::Point { index, start, pts0 }), Some(m)) => m.drag_point(pts0, *index, [x - start[0], y - start[1]]), - (Some(WarpDrag::Surface { s, t, start, pts0 }), Some(m)) => m.pull(pts0, *s, *t, [x - start[0], y - start[1]]), - _ => {} - } - if matches!(ev, ToolEvent::Up { .. }) { - pv.warp_drag = None; - } - } - } -} - -/// Runs a warp-edit command against the mesh in the open Warp session and writes the mesh back. -pub fn edit_session_warp(app: &mut PhotocraftApp, id: &str, params: &serde_json::Value) -> Result<(), String> { - let Some(w) = app.ui.transform.as_ref().and_then(|t| t.warp.clone()) else { return Err("not warping".into()) }; - if warps_type(app) { - return Err("Warp on type takes only the warp styles".into()); - } - let mut p = if params.is_object() { params.clone() } else { json!({}) }; - if p.get("warp").is_none() { - p["warp"] = serde_json::to_value(&w).map_err(|e| e.to_string())?; - } - let r = app.session.execute(id, p).map_err(|e| e.to_string())?; - let raw = r.get("warp").cloned().ok_or_else(|| "warp command returned no mesh".to_string())?; - let nw: Warp = serde_json::from_value(raw).map_err(|e| e.to_string())?; - // A warp-edit command can replace the mesh while pointer input is split across control - // requests. Any drag index captured from the old mesh is invalid once that happens. - if let Some(pv) = app.transform_preview.as_mut() { - pv.warp_drag = None; - } - if let Some(t) = app.ui.transform.as_mut() { - t.warp = Some(nw); - } - Ok(()) -} - -/// Applies a split-warp command to the mesh being edited (at the box centre unless `at`). -pub fn split(app: &mut PhotocraftApp, id: &str, at: Option<[f64; 2]>) -> Result<(), String> { - let mut p = json!({}); - if let Some(a) = at { - p["at"] = json!(a); - } - edit_session_warp(app, id, &p) -} - -/// True just outside a corner: rotate handle feedback lives here, not over the entire -/// empty canvas. The actual rotation gesture continues to work farther away. -fn near_rotate_corner(t: &TransformSession, p: [f64; 2], tol: f64) -> bool { - t.warp.is_none() - && t.mode != TransformMode::Distort - && { - let h = hit(t, p, tol); - h == Hit::Outside || (t.mode == TransformMode::Rotate && matches!(h, Hit::Corner(_) | Hit::Edge(_))) - } - && t.quad.iter().any(|q| (p[0] - q[0]).hypot(p[1] - q[1]) <= tol * 3.0) -} - -/// Clockwise degrees in canvas coordinates (positive Y points down). -fn rotation_degrees(quad: [[f64; 2]; 4]) -> f64 { - let dx = quad[1][0] - quad[0][0]; - let dy = quad[1][1] - quad[0][1]; - if dx.is_finite() && dy.is_finite() && dx.hypot(dy) > 1e-9 { dy.atan2(dx).to_degrees() } else { 0.0 } -} - -/// Where the rotate cursor's arc bends at document point `p`, or `None` outside the rotate zone: -/// just outside a corner, or anywhere while a rotate drag is on. It points into the box along the -/// bisector of the nearest corner, so each corner gets its own arrow and they turn with the box. -pub(crate) fn rotate_cursor_dir(app: &PhotocraftApp, p: [f64; 2]) -> Option<[f64; 2]> { - rotate_dir(app.ui.transform.as_ref()?, app.transform_preview.as_ref(), p, handle_tolerance(app)) -} - -fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: [f64; 2], tol: f64) -> Option<[f64; 2]> { - // Content-Aware Scale's box only scales, and Skew doesn't rotate: no rotate arrow. - if !(p[0].is_finite() && p[1].is_finite()) - || t.warp.is_some() - || t.content_aware.is_some() - || matches!(t.mode, TransformMode::Distort | TransformMode::Skew) - { - return None; - } - let rotating = pv.is_some_and(|pv| pv.gesture.is_some_and(|g| g.hit == Hit::Outside)); - if !rotating && !near_rotate_corner(t, p, tol) { - return None; - } - let dist = |q: [f64; 2]| (p[0] - q[0]).hypot(p[1] - q[1]); - let i = (0..4).min_by(|&a, &b| dist(t.quad[a]).total_cmp(&dist(t.quad[b])))?; - let unit = |to: [f64; 2]| { - let d = [to[0] - t.quad[i][0], to[1] - t.quad[i][1]]; - let l = d[0].hypot(d[1]); - (l.is_finite() && l > 1e-9).then(|| [d[0] / l, d[1] / l]) - }; - let (a, b) = (unit(t.quad[(i + 1) % 4])?, unit(t.quad[(i + 3) % 4])?); - let s = [a[0] + b[0], a[1] + b[1]]; - let l = s[0].hypot(s[1]); - (l.is_finite() && l > 1e-9).then(|| [s[0] / l, s[1] / l]) -} - -/// Cursor for hovering a document point while transforming. `xf` is the canvas's view; -/// `quick_split` is Ctrl or Option, which arms a quick split while a warp is active. -pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2], quick_split: bool) -> Option { - let t = app.ui.transform.as_ref()?; - let tol = handle_tolerance(app); - if let Some(w) = &t.warp { - if warps_type(app) { - return Some(CursorIcon::Default); - } - let armed = app.transform_preview.as_ref().and_then(|pv| pv.split_tool); - if armed.is_some() || quick_split { - // One search for the grid position under the pointer, for both the kind and the arrow. - let m = w.to_mesh(1, 1); - let at = m.param_at(p); - let tool = armed.unwrap_or_else(|| quick_split_kind(&m, w.bounds, at)); - return Some(split_cursor(&m, tool, at, xf)); - } - if w.style != WarpStyle::Custom || warp_hit(w, p, tol).is_some() { - return Some(CursorIcon::Crosshair); - } - return Some(if w.mesh.as_ref().and_then(|m| surface_at(m, p)).is_some() { CursorIcon::Grab } else { CursorIcon::Default }); - } - let h = hit(t, p, tol); - if !mode_allows(t.mode, h) || (t.content_aware.is_some() && h == Hit::Outside) { - return Some(CursorIcon::Default); - } - if rotate_cursor_dir(app, p).is_some() { - // The overlay draws the curved rotate arrow (`rotate_cursor_dir`), also during the drag. - return Some(CursorIcon::None); - } - // The box's corners run clockwise from the top-left; edge k joins corners k and k + 1. - let corner = |k: usize| t.quad[k % 4]; - let edge_mid = |k: usize| { - let (a, b) = (corner(k), corner(k + 1)); - [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0] - }; - // A handle resizes the box away from the opposite handle. - let resize = |from: [f64; 2], to: [f64; 2]| crate::tool_cursor::resize([to[0] - from[0], to[1] - from[1]], xf); - Some(match h { - Hit::Corner(i) => crate::tool_cursor::corner_resize(&t.quad, i, xf), - Hit::Edge(i) => resize(edge_mid(i + 2), edge_mid(i)), - Hit::Pivot => CursorIcon::Crosshair, - Hit::Inside => CursorIcon::Move, - Hit::Outside => CursorIcon::Alias, - }) -} - -/// For each vertex of the preview's `n` × `n` grid over the unit square (row by row), whether it -/// maps to the front side of `h`'s horizon. A Distort dragged past the horizon sends the rest of -/// the image to the far side, where its cells would wrap round infinity; the preview leaves them -/// out, as the committed warp does (#4863). -fn front_vertices(h: &Homography, n: usize) -> Vec { - let front = h.front_side([0.0, 0.0, 1.0, 1.0]); - (0..=n).flat_map(|j| (0..=n).map(move |i| (i as f64 / n as f64, j as f64 / n as f64))).map(|(u, v)| front * h.w(u, v) > 1e-9).collect() -} - -/// The moving pixels as the box shows them (warped, skewed or styled), plus the layers above -/// them. This is image content: the canvas draws it right after the document, under the grid -/// and guides, so a guide stays visible across a layer being transformed (#5086), as in -/// Photoshop. The box, handles and reference point are [`draw_overlay`], drawn over the guides. -pub fn draw_content(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { - let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) else { return }; - let output = crate::monitor_status::view_display(app, painter.ctx()); - let (display, _) = crate::canvas::canvas_display(app, &pv.doc, output); - // Selection tint and lone mask/channel values are UI diagnostics, not document colors. - let display = display.as_deref().filter(|_| !t.selection && t.target.is_none() && t.path.is_none()); - if let Some(w) = &t.warp { - draw_warp_content(painter, xf, t, w, pv, display); - return; - } - let ctx = painter.ctx(); - let styled = - styled_frame(app, xf.zoom * ctx.pixels_per_point(), ctx.input(|i| i.pointer.any_down())).and_then(|(s, frame)| s.texture(ctx, &frame, display)); - if let Some((tex, r)) = styled { - let mut mesh = egui::Mesh::with_texture(tex); - for (x, y, u, v) in [(r[0], r[1], 0.0, 0.0), (r[2], r[1], 1.0, 0.0), (r[2], r[3], 1.0, 1.0), (r[0], r[3], 0.0, 1.0)] { - mesh.vertices.push(egui::epaint::Vertex { pos: pos2(x, y), uv: pos2(u, v), color: Color32::WHITE }); - } - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(0, 2, 3); - painter.add(clip_to_canvas(mesh, canvas_size(pv), |p| xf.to_screen(p.x, p.y))); - } else if let Some(h) = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], t.quad) { - // A 24×24 grid keeps perspective previews straight. - let n = 24; - let zoom = xf.zoom * painter.ctx().pixels_per_point(); - // Content-Aware Scale shows its latest live result once there is one. - let (tex, uv) = match pv.content_aware.as_ref().and_then(|l| l.shown(t)) { - Some((texture, texel)) => texture.pick_display(painter.ctx(), zoom, texel, false, display), - None => pv.texture.pick_display(painter.ctx(), zoom, quad_scale(t), t.interpolation == "nearest", display), - }; - let mut mesh = egui::Mesh::with_texture(tex); - let tint = Color32::from_white_alpha((pv.opacity.clamp(0.0, 1.0) * 255.0) as u8); - let ahead = front_vertices(&h, n); - for j in 0..=n { - for i in 0..=n { - let (u, v) = (i as f64 / n as f64, j as f64 / n as f64); - let (x, y) = h.apply(u, v); - mesh.vertices.push(egui::epaint::Vertex { pos: pos2(x as f32, y as f32), uv: pos2(u as f32 * uv[0], v as f32 * uv[1]), color: tint }); - } - } - for j in 0..n { - for i in 0..n { - let a = (j * (n + 1) + i) as u32; - for tri in [[a, a + 1, a + n as u32 + 2], [a, a + n as u32 + 2, a + n as u32 + 1]] { - // A cell with a corner past the horizon would stretch across the canvas (#4863). - if tri.iter().all(|&k| ahead[k as usize]) { - mesh.add_triangle(tri[0], tri[1], tri[2]); - } - } - } - } - painter.add(clip_to_canvas(mesh, canvas_size(pv), |p| xf.to_screen(p.x, p.y))); - } - if let Some(a) = &pv.above { - a.draw(painter, xf, display); - } -} - -/// The box, handles, reference point and path outline over the preview that [`draw_content`] -/// drew; the warp grid and its split guides for a warp. -pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { - let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) else { return }; - let scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32); - if let Some(w) = &t.warp { - let over_canvas = painter.ctx().input(|i| i.pointer.hover_pos()).filter(|p| xf.rect.contains(*p)).map(|p| xf.to_doc(p)); - let at = pv.split_pointer.or(over_canvas); - let alt = painter.ctx().input(|i| i.modifiers.alt || i.modifiers.command); - let guide = at.filter(|_| !warps_type(app)).and_then(|p| { - let tool = pv.split_tool.or_else(|| { - (alt || pv.split_quick).then(|| { - let m = w.to_mesh(1, 1); - quick_split_kind(&m, w.bounds, m.param_at(p)) - }) - }); - tool.map(|tool| (tool, p)) - }); - draw_warp_overlay(painter, xf, w, pv, guide); - return; - } - if pv.committing.is_some() { - return; - } - let accent = crate::theme::Tokens::get(painter.ctx()).accent; - if let (Some(path), Some(h)) = (&pv.path, Homography::rect_to_quad(t.rect, t.quad)) { - crate::vector_ui::draw_outline( - painter, - path, - &|q| { - let (x, y) = h.apply(q[0], q[1]); - xf.to_screen(x as f32, y as f32) - }, - accent, - ); - } - let pts: Vec = t.quad.iter().map(|q| scr(*q)).collect(); - painter.add(egui::Shape::closed_line(pts.clone(), Stroke::new(1.0, accent))); - let mids: Vec = (0..4).map(|i| pts[i].lerp(pts[(i + 1) % 4], 0.5)).collect(); - for p in pts.iter().chain(mids.iter()) { - let r = egui::Rect::from_center_size(*p, vec2(7.0, 7.0)); - painter.rect_filled(r, 0.0, Color32::WHITE); - painter.rect_stroke(r, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside); - } - // Reference point (Photoshop's crosshair circle). - let c = scr(t.pivot); - painter.circle_stroke(c, 5.0, Stroke::new(1.0, Color32::WHITE)); - painter.circle_stroke(c, 5.0, Stroke::new(0.5, Color32::BLACK)); - painter.line_segment([c - vec2(8.0, 0.0), c + vec2(8.0, 0.0)], Stroke::new(1.0, Color32::WHITE)); - painter.line_segment([c - vec2(0.0, 8.0), c + vec2(0.0, 8.0)], Stroke::new(1.0, Color32::WHITE)); - if let Some(at) = painter.ctx().pointer_hover_pos().filter(|p| xf.rect.contains(*p)) { - let p = xf.to_doc(at); - let tol = HANDLE_PX / f64::from(xf.zoom.max(0.01)); - if let Some(k) = rotate_dir(t, Some(pv), p, tol) { - // Through the view, so the arc bends round the corner as it shows under a turned or - // flipped view. - let toward = xf.to_screen((p[0] + k[0] * 16.0) as f32, (p[1] + k[1] * 16.0) as f32) - at; - crate::crop_ui::draw_turn_cursor(painter.ctx(), at, toward); - } - // Preferences › Tools › Show Transformation Values off hides it, as in Photoshop (#204). - if let Some(r) = live_readout(app).filter(|_| app.session.prefs().tools.show_transformation_values) { - draw_live_readout(painter.ctx(), at, r); - } - } -} - -/// Applying the open box moves the selection outline with it: `edit.transform` and -/// `edit.transform.warp` map it like the pixels. Not Transform Selection (its ants are hidden), a -/// path, Content-Aware Scale or a type layer's Warp Text, which leave the selection alone. -fn carries_selection(app: &PhotocraftApp, t: &TransformSession) -> bool { - !t.selection && t.path.is_none() && t.content_aware.is_none() && !(t.warp.is_some() && warps_type(app)) -} - -/// A transform of `document` is open that carries its selection along (#5297): the canvas traces -/// the whole outline, not only the part in view where it started, for [`draw_selection`]. -pub(crate) fn carries_selection_of(app: &PhotocraftApp, document: DocId) -> bool { - matches!((&app.ui.transform, &app.transform_preview), (Some(t), Some(pv)) if pv.doc.id == document && carries_selection(app, t)) -} - -/// The marching ants where the open box puts them (#5297): the selection follows a move, scale, -/// rotation, skew, distort, perspective or warp while it is made, to where applying it leaves it. -/// `segs` is the outline of `document`'s selection at rest. False when no open transform carries -/// that selection: the caller draws it where it is. -pub(crate) fn draw_selection( - app: &PhotocraftApp, - painter: &egui::Painter, - xf: &ViewXform, - document: DocId, - segs: &[crate::outline::Segment], - time: f64, -) -> bool { - let Some(t) = app.ui.transform.as_ref().filter(|_| carries_selection_of(app, document)) else { return false }; - let scr = |(x, y): (f64, f64)| xf.to_screen(x as f32, y as f32); - let doc = |p: [i32; 2]| [f64::from(p[0]), f64::from(p[1])]; - let along = |a: [f64; 2], b: [f64; 2], k: f64| [a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k]; - if let Some(w) = &t.warp { - // A warp bends the outline's straight runs: each is drawn in pieces about 8 points long. - let piece = (8.0 / f64::from(xf.zoom.max(1e-3))).max(1.0); - let lines = segs.iter().flat_map(|(a, b)| { - let (a, b) = (doc(*a), doc(*b)); - let n = (((b[0] - a[0]).abs() + (b[1] - a[1]).abs()) / piece).ceil().clamp(1.0, 256.0) as usize; - let at = move |i: usize| { - let p = along(a, b, i as f64 / n as f64); - scr(w.map(p[0], p[1])) - }; - (0..n).map(move |i| (at(i), at(i + 1))) - }); - crate::canvas::marching_ants_lines(painter, lines, time); - } else if let Some(h) = Homography::rect_to_quad(t.rect, t.quad) { - // Past a Distort's horizon the outline has no place, like the pixels (#4863): a run that - // crosses it stops short of it, where its points are still a finite way off. - let front = h.front_side(t.rect); - let depth = |p: [f64; 2]| front * h.w(p[0], p[1]); - let near = corners(t.rect).iter().map(|c| depth(*c)).fold(0.0, f64::max) * 1e-3; - let lines = segs.iter().filter_map(|(a, b)| { - let (mut a, mut b) = (doc(*a), doc(*b)); - let (da, db) = (depth(a), depth(b)); - if da < near && db < near { - return None; - } - if da < near { - a = along(a, b, (near - da) / (db - da)); - } else if db < near { - b = along(b, a, (near - db) / (da - db)); - } - Some((scr(h.apply(a[0], a[1])), scr(h.apply(b[0], b[1])))) - }); - crate::canvas::marching_ants_lines(painter, lines, time); - } - true -} - -/// What the styled preview of the moving layer is drawn from (transform_fx.rs), at `zoom` screen -/// pixels per document pixel. `None` for a layer without a style (also once it is switched off -/// while the box is open) or a hidden one: the bare pixels are drawn instead. The style, opacity -/// and fill are the layer's as they are now, so edits made while the box is open show. -pub(crate) fn styled_frame(app: &PhotocraftApp, zoom: f32, dragging: bool) -> Option<(&crate::transform_fx::StyledPreview, crate::transform_fx::Frame<'_>)> { - let (t, pv) = (app.ui.transform.as_ref()?, app.transform_preview.as_ref()?); - let styled = pv.styled.as_ref().filter(|_| t.warp.is_none())?; - let st = app.session.active().filter(|st| st.doc.id == pv.doc.id)?; - let layer = st.doc.layer(LayerId(t.layer)).filter(|l| l.visible && photocraft_compose::effects::has_effects(l))?; - let frame = crate::transform_fx::Frame { - doc: &st.doc, - layer, - revision: st.revision, - texels: &pv.texture, - quad: t.quad, - quad_scale: quad_scale(t), - nearest: t.interpolation == "nearest", - zoom, - dragging, - }; - Some((styled, frame)) -} - -/// The value shown beside the pointer while the box is dragged, like Photoshop's Show -/// Transformation Values: the box's angle while rotating, its scale while resizing, the offset -/// while moving. -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) enum Readout { - /// Clockwise degrees in document space (`rotation_degrees`), whatever the view's turn or flip. - Angle(f64), - /// Width and height in percent of the original box. - Scale([f64; 2]), - /// Document pixels moved since the press. - Offset([f64; 2]), -} - -/// The readout for the drag in progress, or `None` when nothing is dragged (or the drag is the -/// reference point, a warp, or a distortion that has no single scale). -pub(crate) fn live_readout(app: &PhotocraftApp) -> Option { - let t = app.ui.transform.as_ref().filter(|t| t.warp.is_none())?; - let g = app.transform_preview.as_ref()?.gesture?; - match g.hit { - Hit::Outside => Some(Readout::Angle(rotation_degrees(t.quad))), - Hit::Inside => Some(Readout::Offset([t.quad[0][0] - g.quad0[0][0], t.quad[0][1] - g.quad0[0][1]])), - Hit::Corner(_) | Hit::Edge(_) if parallelogram(&t.quad) => { - let (w, h, _, _) = readout(t); - (w.is_finite() && h.is_finite()).then_some(Readout::Scale([w, h])) - } - Hit::Corner(_) | Hit::Edge(_) | Hit::Pivot => None, - } -} - -/// True when `q` is still an affine image of the box (opposite sides parallel), so a W/H scale -/// describes it; a distorted or perspective box has none. -fn parallelogram(q: &[[f64; 2]; 4]) -> bool { - let scale = q.iter().flatten().fold(1.0f64, |m, v| m.max(v.abs())); - (0..2).all(|k| ((q[0][k] + q[2][k]) - (q[1][k] + q[3][k])).abs() <= scale * 1e-9) -} - -/// [`live_readout`] as the rounded label beside the pointer (the marquee's and Crop's readout). -fn draw_live_readout(ctx: &egui::Context, at: Pos2, r: Readout) { - // Round first so a hair below zero never reads "-0". - let fixed = |v: f64, places: i32| { - let k = 10f64.powi(places); - let v = (v * k).round() / k; - if v == 0.0 { 0.0 } else { v } - }; - let id = "transform-readout"; - match r { - Readout::Angle(a) => crate::canvas::draw_readout(ctx, id, at, ["Angle:"], [format!("{:.1}°", fixed(a, 1))]), - Readout::Scale([w, h]) => crate::canvas::draw_readout(ctx, id, at, ["W:", "H:"], [w, h].map(|v| format!("{:.1}%", fixed(v, 1)))), - Readout::Offset([dx, dy]) => crate::canvas::draw_readout(ctx, id, at, ["ΔX:", "ΔY:"], [dx, dy].map(|v| format!("{:.0} px", fixed(v, 0)))), - } -} - -/// Width and height of the document being transformed, in document pixels. -fn canvas_size(pv: &TransformPreview) -> [f32; 2] { - [pv.doc.size.width as f32, pv.doc.size.height as f32] -} - -/// Clips `mesh` (positions in document pixels) to the canvas `[0, 0, size]` and maps it to the -/// screen. Pixels past the canvas edge are never shown, also not while transforming (Photoshop; -/// #2027): only the box and its handles reach over the pasteboard. Clipping in document space -/// stays exact under a rotated or flipped view, where a screen clip rectangle would not. -fn clip_to_canvas(mut mesh: egui::Mesh, size: [f32; 2], to_screen: impl Fn(Pos2) -> Pos2) -> egui::Mesh { - let inside = |p: Pos2| p.x >= 0.0 && p.y >= 0.0 && p.x <= size[0] && p.y <= size[1]; - if mesh.vertices.iter().all(|v| inside(v.pos)) { - for v in &mut mesh.vertices { - v.pos = to_screen(v.pos); - } - return mesh; - } - let mut out = egui::Mesh::with_texture(mesh.texture_id); - for tri in mesh.indices.as_chunks::<3>().0 { - let mut poly: Vec = tri.iter().filter_map(|i| mesh.vertices.get(*i as usize).copied()).collect(); - // Sutherland–Hodgman against the four canvas edges (`dist` >= 0 is the canvas side). - for edge in 0..4 { - let dist = |v: &egui::epaint::Vertex| match edge { - 0 => v.pos.x, - 1 => size[0] - v.pos.x, - 2 => v.pos.y, - _ => size[1] - v.pos.y, - }; - let mut next = Vec::with_capacity(poly.len() + 2); - for (k, a) in poly.iter().enumerate() { - let Some(b) = poly.get((k + 1) % poly.len()) else { continue }; - let (da, db) = (dist(a), dist(b)); - if da >= 0.0 { - next.push(*a); - } - if (da >= 0.0) != (db >= 0.0) && da != db { - let t = da / (da - db); - next.push(egui::epaint::Vertex { pos: a.pos.lerp(b.pos, t), uv: a.uv.lerp(b.uv, t), color: a.color }); - } - } - poly = next; - } - if poly.len() < 3 { - continue; - } - let base = out.vertices.len() as u32; - out.vertices.extend(poly.iter().map(|v| egui::epaint::Vertex { pos: to_screen(v.pos), ..*v })); - for k in 1..poly.len() as u32 - 1 { - out.add_triangle(base, base + k, base + k + 1); - } - } - out -} - -/// Warp preview (the moving pixels on a fine textured mesh) plus the control mesh. Patch -/// boundaries are solid. A single patch (Grid › Default) also draws its rule-of-thirds guides; -/// 3×3, 4×4 and 5×5 are just those even cells, with an anchor at every intersection. `guide` is -/// the split line following the pointer. -/// How near the pointer (screen px) a handle's anchor or the handle itself must be for the -/// handle to show. Everything else stays out of the way: only anchors are always drawn. -const HANDLE_REVEAL_PX: f32 = 56.0; - -/// The anchor a handle belongs to, as `(i, j)` in the control grid (an anchor is its own). -fn handle_anchor(i: usize, j: usize) -> (usize, usize) { - if i.is_multiple_of(3) { - let aj = match j % 3 { - 0 => j, - 1 => j - 1, - _ => j + 1, - }; - (i, aj) - } else { - (if i % 3 == 1 { i - 1 } else { i + 1 }, j) - } -} -/// Anchors always, small and quiet. A handle and its arm show only while the pointer is close to -/// them or they are being dragged, so a dense grid does not bury the picture in dots. -fn draw_warp_points(painter: &egui::Painter, m: &BezierMesh, scr: impl Fn([f64; 2]) -> Pos2, pv: &TransformPreview, line: Stroke) { - let (nx, ny) = (m.nx(), m.ny()); - let hover = painter.ctx().input(|i| i.pointer.hover_pos()); - let dragged = match &pv.warp_drag { - Some(WarpDrag::Point { index, .. }) => Some(handle_anchor(index % nx, index / nx)), - _ => None, - }; - let near = |p: Pos2| hover.is_some_and(|h| h.distance(p) <= HANDLE_REVEAL_PX); - let faint = Stroke::new(0.75, line.color.gamma_multiply(0.8)); - for j in 0..ny { - for i in 0..nx { - if !on_section_edge(i, j) { - continue; - } - let p = scr(m.point(i, j)); - if i.is_multiple_of(3) && j.is_multiple_of(3) { - let r = egui::Rect::from_center_size(p, vec2(5.0, 5.0)); - painter.rect_filled(r, 0.0, Color32::WHITE); - painter.rect_stroke(r, 0.0, faint, egui::StrokeKind::Inside); - continue; - } - let (ai, aj) = handle_anchor(i, j); - let a = scr(m.point(ai, aj)); - if !(near(p) || near(a) || dragged == Some((ai, aj))) { - continue; - } - painter.line_segment([a, p], faint); - painter.circle_filled(p, 2.75, Color32::WHITE); - painter.circle_stroke(p, 2.75, faint); - } - } -} - -/// The warped pixels and the layers above them ([`draw_content`] for a warp). -fn draw_warp_content( - painter: &egui::Painter, - xf: &ViewXform, - t: &TransformSession, - w: &Warp, - pv: &TransformPreview, - display: Option<&photocraft_engine::display_color::CanvasDisplay>, -) { - let r = t.rect; - let m = w.to_mesh(1, 1); - let (us, vs) = crate::warp_preview::samples(&m, xf.zoom as f64); - let (tex, uv) = pv.texture.pick_display(painter.ctx(), xf.zoom * painter.ctx().pixels_per_point(), 1.0, t.interpolation == "nearest", display); - let mut mesh = egui::Mesh::with_texture(tex); - let tint = Color32::from_white_alpha((pv.opacity.clamp(0.0, 1.0) * 255.0) as u8); - for v in &vs { - for u in &us { - let (x, y) = w.map(r[0] + u * (r[2] - r[0]), r[1] + v * (r[3] - r[1])); - mesh.vertices.push(egui::epaint::Vertex { pos: pos2(x as f32, y as f32), uv: pos2(*u as f32 * uv[0], *v as f32 * uv[1]), color: tint }); - } - } - let pos: Vec<[f32; 2]> = mesh.vertices.iter().map(|v| [v.pos.x, v.pos.y]).collect(); - let rest: Vec<[f32; 2]> = vs.iter().flat_map(|v| us.iter().map(move |u| [(r[0] + u * (r[2] - r[0])) as f32, (r[1] + v * (r[3] - r[1])) as f32])).collect(); - mesh.indices = crate::warp_preview::triangle_order(&pos, &rest, us.len()); - painter.add(clip_to_canvas(mesh, canvas_size(pv), |p| xf.to_screen(p.x, p.y))); - if let Some(a) = &pv.above { - a.draw(painter, xf, display); - } -} - -/// The warp grid, its control points and split guides ([`draw_overlay`] for a warp). -fn draw_warp_overlay(painter: &egui::Painter, xf: &ViewXform, w: &Warp, pv: &TransformPreview, guide: Option<(SplitTool, [f64; 2])>) { - let scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32); - let m = w.to_mesh(1, 1); - let accent = crate::theme::Tokens::get(painter.ctx()).accent; - // Transform Path › Warp: the path drawn through the warp. - if let Some(path) = &pv.path { - crate::vector_ui::draw_outline( - painter, - path, - &|q| { - let (x, y) = w.map(q[0], q[1]); - xf.to_screen(x as f32, y as f32) - }, - accent, - ); - } - let line = Stroke::new(1.0, accent); - let thin = Stroke::new(0.75, accent.gamma_multiply(0.7)); - let curve = |fixed_u: Option, fixed_v: Option| -> Vec { - (0..=40) - .map(|k| { - let s = k as f64 / 40.0; - let p = m.eval(fixed_u.unwrap_or(s), fixed_v.unwrap_or(s)); - scr(p) - }) - .collect() - }; - // Patch boundaries 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); - for (k, win) in m.us.windows(2).enumerate() { - if thirds { - for third in [1.0, 2.0] { - painter.add(egui::Shape::line(curve(Some(win[0] + (win[1] - win[0]) * third / 3.0), None), thin)); - } - } - if k == 0 { - painter.add(egui::Shape::line(curve(Some(win[0]), None), line)); - } - painter.add(egui::Shape::line(curve(Some(win[1]), None), line)); - } - for (k, win) in m.vs.windows(2).enumerate() { - if thirds { - for third in [1.0, 2.0] { - painter.add(egui::Shape::line(curve(None, Some(win[0] + (win[1] - win[0]) * third / 3.0)), thin)); - } - } - if k == 0 { - painter.add(egui::Shape::line(curve(None, Some(win[0])), line)); - } - painter.add(egui::Shape::line(curve(None, Some(win[1])), line)); - } - if w.style == WarpStyle::Custom { - draw_warp_points(painter, &m, scr, pv, line); - } - if let Some((tool, p)) = guide { - let (s, t) = m.param_at(p); - let under = Stroke::new(3.0, Color32::BLACK); - let over = Stroke::new(1.25, Color32::WHITE); - let mut strokes = Vec::new(); - if matches!(tool, SplitTool::Vertical | SplitTool::Cross) { - strokes.push(curve(Some(s), None)); - } - if matches!(tool, SplitTool::Horizontal | SplitTool::Cross) { - strokes.push(curve(None, Some(t))); - } - for pts in strokes { - painter.add(egui::Shape::line(pts.clone(), under)); - painter.add(egui::Shape::line(pts, over)); - } - } -} - -/// How much the box enlarges its pixels: the longest edge relative to the original (picks the -/// preview's texture level and filter). -fn quad_scale(t: &TransformSession) -> f32 { - let (w0, h0) = ((t.rect[2] - t.rect[0]).max(1e-9), (t.rect[3] - t.rect[1]).max(1e-9)); - let len = |a: [f64; 2], b: [f64; 2]| (b[0] - a[0]).hypot(b[1] - a[1]); - let q = &t.quad; - let s = (len(q[0], q[1]) / w0).max(len(q[3], q[2]) / w0).max(len(q[0], q[3]) / h0).max(len(q[1], q[2]) / h0); - if s.is_finite() { s as f32 } else { 1.0 } -} - -/// W and H (%), the angle (°) and the horizontal skew (°) the options bar shows for the box. -/// A mirrored box reads as a negative W or H, whichever keeps the angle nearer 0 (Photoshop: -/// Flip Horizontal is W -100 % at 0°, Flip Vertical H -100 % at 0°). Both are the same box: -/// negating W and H and turning by a half turn cancel out. -fn readout(t: &TransformSession) -> (f64, f64, f64, f64) { - let p = Parts::of(t); - let wrap = |a: f64| { - let a = a.rem_euclid(std::f64::consts::TAU); - if a > std::f64::consts::PI { a - std::f64::consts::TAU } else { a } - }; - let turned = wrap(p.angle + std::f64::consts::PI); - let (sx, sy, angle) = if p.sy < 0.0 && turned.abs() < wrap(p.angle).abs() { (-p.sx, -p.sy, turned) } else { (p.sx, p.sy, p.angle) }; - (sx * 100.0, sy * 100.0, angle.to_degrees(), p.skew_h.to_degrees()) -} - -/// `v`, kept off zero with its sign: a divisor for a W or H scale that may be negative. -fn nonzero(v: f64) -> f64 { - if v.abs() < 1e-9 { 1e-9f64.copysign(v) } else { v } -} - -/// The box's affine part read as Photoshop's options bar does: the frame scaled (W, H), skewed -/// (H, V) and then rotated about the reference point. Angles are radians; positive turns -/// clockwise on screen, so a positive H skew leans the box's sides like the angle field would -/// turn them, and a positive V skew its top and bottom. -#[derive(Clone, Copy, Debug, PartialEq)] -struct Parts { - sx: f64, - /// Negative when the box is flipped vertically relative to its rotation. - sy: f64, - angle: f64, - skew_h: f64, - skew_v: f64, -} - -/// The skew fields' reach: a skew of ±90° would flatten the box. -const SKEW_LIMIT_DEG: f32 = 89.0; - -impl Parts { - /// The box's columns: where the frame's unit X and Y edges went (from the top-left corner). - fn columns(t: &TransformSession) -> Option<[[f64; 2]; 2]> { - let (w0, h0) = (t.rect[2] - t.rect[0], t.rect[3] - t.rect[1]); - if w0.abs() < 1e-9 || h0.abs() < 1e-9 { - return None; - } - let q = &t.quad; - let m = [[(q[1][0] - q[0][0]) / w0, (q[1][1] - q[0][1]) / w0], [(q[3][0] - q[0][0]) / h0, (q[3][1] - q[0][1]) / h0]]; - m.iter().flatten().all(|v| v.is_finite()).then_some(m) - } - - /// The box as scale, skew and rotation, keeping the session's typed V skew (any box can be - /// written with any V skew short of ±90°). - fn of(t: &TransformSession) -> Parts { - let skew_v = t.skew_v.to_radians(); - let none = Parts { sx: 1.0, sy: 1.0, angle: 0.0, skew_h: 0.0, skew_v }; - Parts::columns(t).map_or(none, |m| Parts::from_columns(m, skew_v)) - } - - fn from_columns([c0, c1]: [[f64; 2]; 2], skew_v: f64) -> Parts { - // X edge = sx · R(angle) · (1, tan v): its direction is the angle plus v. - let angle = c0[1].atan2(c0[0]) - skew_v; - let sx = c0[0].hypot(c0[1]) * skew_v.cos(); - // Y edge = sy · R(angle) · (−tan h, 1). - let (gx, gy) = unturn(c1, angle); - let skew_h = if gy.abs() < 1e-12 { 0.0 } else { (-gx / gy).atan() }; - Parts { sx, sy: gy, angle, skew_h, skew_v } - } - - fn columns_of(self) -> [[f64; 2]; 2] { - let (sn, cs) = self.angle.sin_cos(); - let rot = |x: f64, y: f64| [x * cs - y * sn, x * sn + y * cs]; - let c0 = rot(self.sx, self.sx * self.skew_v.tan()); - let c1 = rot(-self.sy * self.skew_h.tan(), self.sy); - [c0, c1] - } -} - -/// `c` turned back by `angle` (radians). -fn unturn(c: [f64; 2], angle: f64) -> (f64, f64) { - let (sn, cs) = angle.sin_cos(); - (c[0] * cs + c[1] * sn, -c[0] * sn + c[1] * cs) -} - -/// Sets the box's H and V skew (degrees), keeping its scale, angle and reference point: the -/// options bar's skew fields. -fn skew_about_pivot(app: &mut PhotocraftApp, skew_h: f64, skew_v: f64) { - let Some(s) = app.ui.transform.as_mut() else { return }; - let Some(m) = Parts::columns(s) else { return }; - let limit = f64::from(SKEW_LIMIT_DEG); - let (skew_h, skew_v) = (skew_h.clamp(-limit, limit), skew_v.clamp(-limit, limit)); - let from = Parts::from_columns(m, s.skew_v.to_radians()); - let to = Parts { skew_h: skew_h.to_radians(), skew_v: skew_v.to_radians(), ..from }.columns_of(); - // The map from the old box to the new one: to · m⁻¹. - let det = m[0][0] * m[1][1] - m[1][0] * m[0][1]; - if det.abs() < 1e-12 { - return; - } - let inv = [[m[1][1] / det, -m[0][1] / det], [-m[1][0] / det, m[0][0] / det]]; - let l = |x: f64, y: f64| { - let (u, v) = (inv[0][0] * x + inv[1][0] * y, inv[0][1] * x + inv[1][1] * y); - [to[0][0] * u + to[1][0] * v, to[0][1] * u + to[1][1] * v] - }; - let c = s.pivot; - let quad = s.quad.map(|q| { - let d = l(q[0] - c[0], q[1] - c[1]); - [c[0] + d[0], c[1] + d[1]] - }); - if quad.iter().flatten().all(|v| v.is_finite()) { - s.quad = quad; - s.skew_v = skew_v; - } -} - -/// Width of the mode, cancel and commit cluster kept on the right of the options bar. -const ACTIONS_W: f32 = 140.0; -/// Width of the action buttons when they follow the Warp fields (one more than the box bar: Reset). -const WARP_ACTIONS_W: f32 = 176.0; - -/// Reach of the reference point X/Y fields: the largest document side (`image.canvasSize`'s limit). -const POSITION_LIMIT_PX: f32 = 300_000.0; -/// Reach of the W/H fields. The engine takes any scale; this lets a 30 px layer span the largest -/// document (#1267). -const SCALE_LIMIT_PCT: f32 = 1_000_000.0; - -/// The W or H field's limit for a box side of `side` px: as far as the result stays within the -/// largest document side, so a typed scale can't ask for an image too large to allocate. -fn scale_limit_pct(side: f64) -> f32 { - let side = side.abs(); - if !side.is_finite() || side < 1e-6 { - return SCALE_LIMIT_PCT; - } - ((f64::from(POSITION_LIMIT_PX) / side * 100.0) as f32).clamp(100.0, SCALE_LIMIT_PCT) -} - -/// Where Free Transform remembers the unit of its W and H fields, picked by right-clicking either -/// of them as in Photoshop (Percent until another is picked). -const SIZE_UNIT_KEY: &str = "edit.freeTransform"; - -/// The W/H unit, with the document's resolution and the points per inch it converts with. -fn size_unit(app: &PhotocraftApp) -> crate::layer_props_ui::LenUnit { - use photocraft_engine::prefs::Unit; - let unit = app.session.prefs().dialogs.get(SIZE_UNIT_KEY).and_then(|v| v.get("sizeUnit")).and_then(serde_json::Value::as_str).and_then(Unit::parse); - crate::layer_props_ui::LenUnit { unit: unit.unwrap_or(Unit::Percent), ..crate::layer_props_ui::LenUnit::of(app) } -} - -fn set_size_unit(app: &mut PhotocraftApp, name: &str) { - app.session.prefs.edit(|p| { - let entry = p.dialogs.entry(SIZE_UNIT_KEY.to_string()).or_insert_with(|| json!({})); - if !entry.is_object() { - *entry = json!({}); - } - entry["sizeUnit"] = json!(name); - }); -} - -/// A W or H value shown in `u`: the box side `side` px wide at the original size, scaled by `pct`. -/// Percent stays the scale itself (100 % is the original size), lengths are the side's length. -fn size_shown(u: &crate::layer_props_ui::LenUnit, pct: f64, side: f64) -> f32 { - u.shown(pct / 100.0 * side, side) -} - -/// The scale (%) a W or H value typed in `u` asks for, for a box side `side` px wide originally. -fn size_pct(u: &crate::layer_props_ui::LenUnit, v: f32, side: f64) -> f64 { - let side = side.abs().max(1e-9); - u.px(v, side) / side * 100.0 -} - -/// Options bar while transforming: the fields (reference point X/Y, W/H %, angle, interpolation, -/// or the warp controls), then the mode switch, cancel and commit right after them. A bar too -/// narrow for both pins the buttons to the right edge and clips the fields, so Commit and Cancel -/// are always reachable. -pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let Some(t) = app.ui.transform.clone() else { return }; - let bar = ui.available_rect_before_wrap(); - let warping = t.warp.is_some(); - let buttons_w = if warping { WARP_ACTIONS_W } else { ACTIONS_W }; - let split = (bar.right() - buttons_w).max(bar.left()); - let fields = egui::Rect::from_min_max(bar.min, egui::pos2(split, bar.bottom())); - let mut row = ui.new_child(egui::UiBuilder::new().id_salt("transform-fields").max_rect(fields).layout(egui::Layout::left_to_right(egui::Align::Center))); - row.set_clip_rect(fields); - if let Some(w) = t.warp.clone() { - warp_fields(app, &mut row, &w); - } else if t.content_aware.is_some() { - crate::cas_transform::fields(app, &mut row, &t); - } else { - transform_fields(app, &mut row, &t); - } - crate::widgets::vline(&mut row, 22.0); - let start = row.min_rect().right().min(split); - let actions = egui::Rect::from_min_max(egui::pos2(start, bar.top()), egui::pos2(start + buttons_w, bar.bottom())); - let mut btns = ui.new_child(egui::UiBuilder::new().id_salt("transform-actions").max_rect(actions).layout(egui::Layout::right_to_left(egui::Align::Center))); - transform_actions(app, &mut btns, warping, t.content_aware.is_none()); -} - -fn transform_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &TransformSession) { - let tk = crate::theme::Tokens::get(ui.ctx()); - let (_, _, angle, skew_h) = readout(t); - let lbl = |ui: &mut egui::Ui, s: &str| { - ui.label(egui::RichText::new(s).color(tk.text_dim).size(12.0)); - }; - position_size_fields(app, ui, t); - crate::widgets::vline(ui, 22.0); - let mut a = angle as f32; - let (r, resp) = ui.allocate_exact_size(vec2(18.0, 22.0), egui::Sense::hover()); - crate::icons::paint(ui, r, "rotate-cw", 13.0, tk.text_dim); - resp.on_hover_text(tl!("Rotate")); - if crate::widgets::value_field(ui, &mut a, -180.0..=180.0, "°", 60.0).accessible_name(tl!("Rotate")).changed() { - rotate_about_pivot(app, (a as f64 - angle).to_radians()); - } - // Photoshop's H and V skew fields: the box's sides lean by H, its top and bottom by V. - let (mut h, mut v) = (skew_h as f32, t.skew_v as f32); - let lim = -SKEW_LIMIT_DEG..=SKEW_LIMIT_DEG; - lbl(ui, "H:"); - let rh = - crate::widgets::value_field(ui, &mut h, lim.clone(), "°", 56.0).accessible_name(tl!("Set horizontal skew")).on_hover_text(tl!("Set horizontal skew")); - lbl(ui, "V:"); - let rv = crate::widgets::value_field(ui, &mut v, lim, "°", 56.0).accessible_name(tl!("Set vertical skew")).on_hover_text(tl!("Set vertical skew")); - if rh.changed() || rv.changed() { - skew_about_pivot(app, f64::from(h), f64::from(v)); - } - crate::widgets::vline(ui, 22.0); - lbl(ui, tl!("Interpolation:")); - let mut interp = t.interpolation.clone(); - let opts = [("bicubic".to_string(), tl!("Bicubic")), ("bilinear".to_string(), tl!("Bilinear")), ("nearest".to_string(), tl!("Nearest Neighbor"))]; - if crate::widgets::dropdown(ui, "transform-interp", tl!("Interpolation"), &mut interp, &opts, 130.0) - && let Some(s) = app.ui.transform.as_mut() - { - s.interpolation = interp; - } -} - -fn matching_anchor(quad: [[f64; 2]; 4], pivot: [f64; 2]) -> Option { - (0..9).find(|&i| { - let p = point_on_quad(quad, i); - (p[0] - pivot[0]).abs() <= 0.05 && (p[1] - pivot[1]).abs() <= 0.05 - }) -} - -fn anchor_grid_widget(ui: &mut egui::Ui, current_anchor: Option) -> Option { - let size = egui::vec2(16.0, 16.0); - let (rect, resp) = ui.allocate_exact_size(size, egui::Sense::click()); - let tk = crate::theme::Tokens::get(ui.ctx()); - let painter = ui.painter(); - painter.rect_stroke(rect, 1.0, egui::Stroke::new(1.0, tk.card_border), egui::StrokeKind::Inside); - let mut clicked = None; - let pointer = resp.interact_pointer_pos(); - for row in 0..3 { - for col in 0..3 { - let idx = row * 3 + col; - let cx = rect.min.x + (col as f32 + 0.5) * (rect.width() / 3.0); - let cy = rect.min.y + (row as f32 + 0.5) * (rect.height() / 3.0); - let pt_rect = egui::Rect::from_center_size(egui::pos2(cx, cy), egui::vec2(3.5, 3.5)); - if resp.clicked() && pointer.is_some_and(|p| (p.x - cx).abs() <= 3.0 && (p.y - cy).abs() <= 3.0) { - clicked = Some(idx); - } - if current_anchor == Some(idx) { - painter.rect_filled(pt_rect, 0.5, tk.accent); - } else { - painter.rect_filled(pt_rect, 0.5, tk.text_dim); - } - } - } - resp.on_hover_text(tl!("Reference point location")); - clicked -} - -/// The reference point's X/Y and the W/H scale fields (with the aspect link) of the options bar. -pub(crate) fn position_size_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &TransformSession) { - let tk = crate::theme::Tokens::get(ui.ctx()); - let (sx, sy, _, _) = readout(t); - let lbl = |ui: &mut egui::Ui, s: &str| { - ui.label(egui::RichText::new(s).color(tk.text_dim).size(12.0)); - }; - let current_anchor = matching_anchor(t.quad, t.pivot); - let mut pivot = t.pivot; - if let Some(new_anchor) = anchor_grid_widget(ui, current_anchor) { - let new_p = point_on_quad(t.quad, new_anchor); - if let Some(s) = app.ui.transform.as_mut() { - s.pivot = new_p; - } - pivot = new_p; - } - ui.add_space(4.0); - let mut px = pivot[0] as f32; - let mut py = pivot[1] as f32; - lbl(ui, "X:"); - let rx = crate::widgets::value_field(ui, &mut px, -POSITION_LIMIT_PX..=POSITION_LIMIT_PX, "px", 72.0).accessible_name("X"); - lbl(ui, "Y:"); - let ry = crate::widgets::value_field(ui, &mut py, -POSITION_LIMIT_PX..=POSITION_LIMIT_PX, "px", 72.0).accessible_name("Y"); - if (rx.changed() || ry.changed()) - && let Some(s) = app.ui.transform.as_mut() - { - let (dx, dy) = (px as f64 - s.pivot[0], py as f64 - s.pivot[1]); - s.quad = s.quad.map(|q| [q[0] + dx, q[1] + dy]); - s.pivot = [px as f64, py as f64]; - } - crate::widgets::vline(ui, 22.0); - // W and H in the unit picked from their right-click menu: the scale in percent, or the box's - // length (Photoshop's units, at the document's resolution). - let u = size_unit(app); - let (side_w, side_h) = (t.rect[2] - t.rect[0], t.rect[3] - t.rect[1]); - let (wlim, hlim) = (scale_limit_pct(side_w), scale_limit_pct(side_h)); - let (wlim_u, hlim_u) = (size_shown(&u, f64::from(wlim), side_w), size_shown(&u, f64::from(hlim), side_h)); - let (mut w, mut h) = (size_shown(&u, sx, side_w), size_shown(&u, sy, side_h)); - let (suffix, places) = (u.unit.suffix(), u.unit.decimals() as u32); - // Lengths need more room than a percentage ("2116.67 mm"). - let size_w = if u.unit == photocraft_engine::prefs::Unit::Percent { 66.0 } else { 84.0 }; - // Whatever their unit, W and H take any other typed in (`500 px` or `2 in` in percent, `50%` - // in a length), converted at the document's resolution against the box's original side (#6284). - let units = crate::widgets::FieldUnits { unit: u.unit, dpi: u.dpi, ppi: u.ppi }; - lbl(ui, "W:"); - let rw = crate::widgets::value_field_extent(ui, &mut w, -wlim_u..=wlim_u, suffix, size_w, places, units, side_w).accessible_name(tl!("Width")); - let link = !app.ui.transform_unlinked; - if crate::icons::button(ui, if link { "link" } else { "unlink" }, 22.0, link, tl!("Maintain aspect ratio")).clicked() { - app.ui.transform_unlinked = link; - } - lbl(ui, "H:"); - let rh = crate::widgets::value_field_extent(ui, &mut h, -hlim_u..=hlim_u, suffix, size_w, places, units, side_h).accessible_name(tl!("Height")); - for r in [&rw, &rh] { - r.context_menu(|ui| { - if let Some(name) = crate::rulers::unit_menu(ui, u.unit) { - set_size_unit(app, name); - } - }); - } - let (w, h) = (size_pct(&u, w, side_w) as f32, size_pct(&u, h, side_h) as f32); - if rw.changed() || rh.changed() { - let (kx, ky) = if link { - let k = if rw.changed() { w as f64 / nonzero(sx) } else { h as f64 / nonzero(sy) }; - // Linked, the other side follows: keep it within its own limit too. - let k = k.min(f64::from(wlim) / sx.abs().max(1e-9)).min(f64::from(hlim) / sy.abs().max(1e-9)); - (k, k) - } else { - (w as f64 / nonzero(sx), h as f64 / nonzero(sy)) - }; - scale_about_pivot(app, kx, ky); - } -} - -/// Options bar fields in Warp mode: style, bend, the split icons and the grid menu. -fn warp_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, w: &Warp) { - let tk = crate::theme::Tokens::get(ui.ctx()); - let lbl = |ui: &mut egui::Ui, s: &str| { - ui.label(egui::RichText::new(s).color(tk.text_dim).size(12.0)); - }; - // Type takes only the styles (#3004): Split and Grid are greyed, and there is no Custom. - let on_type = warps_type(app); - // Split, Grid, then the warp style with its bend fields. - ui.add_enabled_ui(!on_type, |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(); - if crate::widgets::dropdown(ui, "warp-style", tl!("Warp"), &mut style, &opts, 120.0) - && let Some(t) = app.ui.transform.as_mut() - { - let b = t.rect; - t.warp = Some(match style { - WarpStyle::Custom => Warp::custom(w.to_mesh(1, 1), b), - WarpStyle::None if on_type => Warp::none(b), - WarpStyle::None => Warp::custom(BezierMesh::identity(b, 1, 1), b), - s => Warp { style: s, bend: if w.style.is_preset() { w.bend } else { 50.0 }, ..Warp::none(b) }, - }); - } - // Orientation and the bend fields are always there, and only act on a preset style. - 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")); - orient.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, preset, "Change warp orientation")); - if orient.clicked() - && let Some(Some(cur)) = app.ui.transform.as_mut().map(|t| t.warp.as_mut()) - { - cur.vertical = !cur.vertical; - } - let fields: [(&str, f64); 3] = [(tl!("Bend:"), w.bend), ("H:", w.h_distort), ("V:", w.v_distort)]; - for (k, (name, v)) in fields.iter().enumerate() { - lbl(ui, name); - let mut f = *v as f32; - if crate::widgets::value_field(ui, &mut f, -100.0..=100.0, "%", 58.0).accessible_name(*name).changed() - && let Some(Some(cur)) = app.ui.transform.as_mut().map(|t| t.warp.as_mut()) - { - match k { - 0 => cur.bend = f64::from(f), - 1 => cur.h_distort = f64::from(f), - _ => cur.v_distort = f64::from(f), - } - } - } - }); -} - -/// 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()); - let lbl = |ui: &mut egui::Ui, s: &str| { - ui.label(egui::RichText::new(s).color(tk.text_dim).size(12.0)); - }; - lbl(ui, tl!("Split:")); - let armed = app.transform_preview.as_ref().and_then(|p| p.split_tool); - for (tool, tip) in [ - (SplitTool::Cross, tl!("Split Warp Crosswise")), - (SplitTool::Vertical, tl!("Split Warp Vertically")), - (SplitTool::Horizontal, tl!("Split Warp Horizontally")), - ] { - let on = armed == Some(tool); - if split_icon(ui, tool.icon(), tip, on).clicked() - && let Some(pv) = app.transform_preview.as_mut() - { - pv.split_tool = if on { None } else { Some(tool) }; - pv.split_placing = false; - pv.split_pointer = None; - pv.split_quick = false; - } - } - crate::widgets::vline(ui, 22.0); - lbl(ui, tl!("Grid:")); - let mesh = w.mesh.clone().unwrap_or_else(|| BezierMesh::identity(w.bounds, 1, 1)); - let mut grid = warp_grid_id(&mesh).to_string(); - let opts = [ - ("custom".to_string(), tl!("Custom")), - ("default".to_string(), tl!("Default")), - ("3".to_string(), tl!("3 x 3")), - ("4".to_string(), tl!("4 x 4")), - ("5".to_string(), tl!("5 x 5")), - ]; - if crate::widgets::dropdown(ui, "warp-grid", tl!("Grid"), &mut grid, &opts, 92.0) - && let Some(n) = match grid.as_str() { - "default" => Some(1), - "3" => Some(3), - "4" => Some(4), - "5" => Some(5), - _ => None, - } - { - let _ = edit_session_warp(app, "edit.transform.warpGrid", &json!({ "size": n })); - } -} - -/// Back to the untouched box: the default one-patch grid over the box, no bend. -pub fn reset_warp(app: &mut PhotocraftApp) { - let Some(t) = app.ui.transform.as_mut() else { return }; - if t.warp.is_none() { - return; - } - let b = t.rect; - t.warp = Some(Warp::custom(BezierMesh::identity(b, 1, 1), b)); - if warps_type(app) - && let Some(t) = app.ui.transform.as_mut() - { - t.warp = Some(Warp::none(b)); - } - if let Some(pv) = app.transform_preview.as_mut() { - pv.warp_drag = None; - pv.split_tool = None; - pv.split_pointer = None; - pv.split_placing = false; - pv.split_quick = false; - } -} - -/// Grid menu readout: Default is 1×1, the numbered entries are uniform n×n patches, and anything -/// split by hand reads as Custom. -fn warp_grid_id(mesh: &BezierMesh) -> &'static str { - let cols = mesh.us.len().saturating_sub(1); - let rows = mesh.vs.len().saturating_sub(1); - let even = |k: &[f64]| { - let n = k.len().saturating_sub(1); - n > 0 && k.iter().enumerate().all(|(i, v)| (v - i as f64 / n as f64).abs() < 1e-4) - }; - if cols == rows && even(&mesh.us) && even(&mesh.vs) { - match cols { - 1 => "default", - 3 => "3", - 4 => "4", - 5 => "5", - _ => "custom", - } - } else { - "custom" - } -} - -/// One of the three Split icons. `on` is the armed tool: the line then follows the pointer. -fn split_icon(ui: &mut egui::Ui, kind: &str, tip: &str, on: bool) -> egui::Response { - let (rect, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), egui::Sense::click()); - let ink = crate::icons::button_chrome(ui, rect, on, resp.hovered()); - let c = rect.center(); - let stroke = Stroke::new(1.15, ink); - let box_r = egui::Rect::from_center_size(c, vec2(13.0, 13.0)); - ui.painter().rect_stroke(box_r, 2.0, stroke, egui::StrokeKind::Inside); - let h = 5.2; - match kind { - "vertical" => { - ui.painter().line_segment([c - vec2(0.0, h), c + vec2(0.0, h)], stroke); - } - "horizontal" => { - ui.painter().line_segment([c - vec2(h, 0.0), c + vec2(h, 0.0)], stroke); - } - _ => { - ui.painter().line_segment([c - vec2(h, 0.0), c + vec2(h, 0.0)], stroke); - ui.painter().line_segment([c - vec2(0.0, h), c + vec2(0.0, h)], stroke); - } - } - if kind == "cross" { - ui.painter().circle_filled(c, 1.5, ink); - } else { - ui.painter().circle_stroke(c, 2.1, stroke); - } - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); - resp.on_hover_text(tip) -} - -/// Warp switch, cancel and commit, kept on the right of the options bar. -/// `mode_switch`: the Free Transform / Warp switch (not for Content-Aware Scale, which only scales). -fn transform_actions(app: &mut PhotocraftApp, ui: &mut egui::Ui, warping: bool, mode_switch: bool) { - ui.add_space(8.0); - let commit_tip = if warping { - crate::i18n::fmt(tl!("Commit warp ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]) - } else { - crate::i18n::fmt(tl!("Commit transform ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]) - }; - let commit_btn = crate::icons::button(ui, "check", 26.0, false, &commit_tip); - let label = "Commit transform"; - commit_btn.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(label))); - if commit_btn.clicked() { - commit(app); - } - let cancel_tip = if warping { tl!("Cancel warp (Esc)") } else { tl!("Cancel transform (Esc)") }; - let cancel_btn = crate::icons::button(ui, "ban", 26.0, false, cancel_tip); - let label = "Cancel transform"; - cancel_btn.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(label))); - if cancel_btn.clicked() { - cancel(app); - } - if warping { - let reset = crate::icons::button(ui, "undo-2", 26.0, false, tl!("Reset")); - reset.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Reset warp")); - if reset.clicked() { - reset_warp(app); - } - } - if !mode_switch { - return; - } - crate::widgets::vline(ui, 22.0); - let mode = crate::icons::button(ui, "grid-3x3", 26.0, warping, tl!("Switch between free transform and warp modes")); - mode.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Switch between free transform and warp modes")); - if mode.clicked() { - if warping { - leave_warp(app); - } else { - enter_warp(app, &ui.ctx().clone()); - } - } -} - -/// Scale the box along its own axes about the reference point. -fn scale_about_pivot(app: &mut PhotocraftApp, kx: f64, ky: f64) { - let Some(s) = app.ui.transform.as_mut() else { return }; - let Some(h) = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], s.quad) else { return }; - let Some(inv) = h.inverse() else { return }; - let (pu, pv) = inv.apply(s.pivot[0], s.pivot[1]); - let m = |u: f64, v: f64| { - let (x, y) = h.apply(pu + (u - pu) * kx, pv + (v - pv) * ky); - [x, y] - }; - s.quad = [m(0.0, 0.0), m(1.0, 0.0), m(1.0, 1.0), m(0.0, 1.0)]; -} - -fn rotate_about_pivot(app: &mut PhotocraftApp, da: f64) { - let Some(s) = app.ui.transform.as_mut() else { return }; - let (sn, cs) = da.sin_cos(); - let c = s.pivot; - s.quad = s.quad.map(|q| { - let (x, y) = (q[0] - c[0], q[1] - c[1]); - [c[0] + x * cs - y * sn, c[1] + x * sn + y * cs] - }); -} - #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/transform_tool/begin.rs b/crates/ui-egui/src/transform_tool/begin.rs new file mode 100644 index 0000000000..e4ec2b8691 --- /dev/null +++ b/crates/ui-egui/src/transform_tool/begin.rs @@ -0,0 +1,590 @@ +use super::commit::{commit, start_steps}; +use super::preview::{Above, preview_image}; +use super::*; + +/// 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 let Some((params, path)) = crate::vector_ui::free_transform_path(app) { + return begin_path(app, ctx, params, path); + } + if app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some()) { + app.run("select.drop", json!({}))?; + } + let target = crate::canvas::paint_target(app); + let st = app.session.active().ok_or("no document")?; + let (doc, revision) = (st.doc.clone(), st.revision); + let lone = photocraft_engine::transform_cmds::lone_target(&doc, st.active_layer, &json!({ "target": target })).map_err(|e| e.to_string())?.cloned(); + if let Some(surf) = lone { + return begin_lone(app, ctx, doc, surf, target); + } + let id = st.active_layer.ok_or("no active layer")?; + let layer = doc.layer(id).ok_or("no layer")?; + if photocraft_engine::transform_cmds::locked_for_transform(&doc, id) { + // Photoshop refuses before the box opens rather than when it is committed (#2585). + app.ui.open_dialog(crate::state::DialogKind::Error, json!({"message": tl!(LOCKED)}).as_object().cloned().unwrap_or_default()); + return Err(LOCKED.into()); + } + if matches!(layer.content, LayerContent::Adjustment(_)) && layer.mask.is_none() { + return Err("Adjustment layers have nothing to transform".into()); + } + // With a selection the box is the selection's (#5297). + let b = photocraft_engine::transform_cmds::transform_frame(&doc, layer); + if b.is_empty() { + return Err("Could not transform: the layer is empty".into()); + } + crate::type_tool::commit(app); + let rect = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64]; + let session = app.ui.alloc_id(); + // Preview document: the moving pixels removed (layer hidden, or the selection lifted out). + let mut pd = (*doc).clone(); + let mut lifted = None; + // Type, shapes and smart objects move whole, selection or not (#2630): only pixels are lifted. + if let Some(sel) = doc.selection.clone().filter(|_| !photocraft_engine::transform_cmds::moves_whole(layer) && layer.surface().is_some()) { + if let Some(surf) = pd.layer_mut(id).and_then(|l| l.surface_mut()) { + let (l, rest) = photocraft_engine::transform_cmds::split_selected(surf, &sel).map_err(|e| e.to_string())?; + *surf = rest; + lifted = Some(l); + } + } else if let Some(l) = pd.layer_mut(id) { + l.visible = false; + } + // 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); + // 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: Arc::new(pd), + texture, + opacity: layer.opacity * layer.fill_opacity, + above: Some(above), + styled: styled.then(|| crate::transform_fx::StyledPreview::new(format!("transform-{session}-styled"))), + follow: Some(Follow { revision, hidden: lifted.is_none() }), + 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, + }); + app.ui.transform = Some(TransformSession { + session, + layer: id.0, + rect, + quad: corners(rect), + pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], + interpolation: "bicubic".into(), + warp: None, + selection: false, + target: None, + path: None, + made: None, + mode: Default::default(), + content_aware: None, + skew_v: 0.0, + }); + start_steps(app); + Ok(()) +} + +/// Free Transform on a copy (⌥⌘T, no menu item): duplicates the active layer (with a selection, +/// its selected pixels, as Layer via Copy) and transforms the copy (#352). +pub fn begin_copy(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { + let selection = app.session.active().is_some_and(|d| d.doc.selection.is_some()); + let params = if selection { json!({}) } else { json!({"inPlace": true}) }; + app.run(if selection { "layer.new.layerViaCopy" } else { "layer.duplicate" }, params)?; + let made = app.session.active().and_then(|st| st.active_layer.map(|layer| (st.doc.id, layer))); + if let Err(e) = begin(app, ctx) { + if let Some((document, layer)) = made { + take_back_made(app, document, layer); + } + return Err(e); + } + if let Some(t) = app.ui.transform.as_mut() { + t.made = Some(MadeLayer::Copy); + } + Ok(()) +} + +/// Free Transform on the layer a file dropped on the canvas just placed, like the reference app's +/// Place: Esc takes the place back, ↩ makes the place and the transform one Place Embedded step. +pub fn begin_placed(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { + begin(app, ctx)?; + if let Some(t) = app.ui.transform.as_mut() { + t.made = Some(MadeLayer::Place); + } + Ok(()) +} + +/// Edit › Content-Aware Scale (#3096): a scale-only box over `region` of the active pixel layer +/// (the selection's bounds, else the layer's content), cleared under the box as the command +/// clears it. OK runs `edit.contentAwareScale` (cas_transform.rs) instead of `edit.transform`. +pub(crate) fn begin_content_aware( + app: &mut PhotocraftApp, + ctx: &egui::Context, + region: photocraft_geom::Rect, + live: crate::cas_transform::Live, +) -> Result<(), String> { + let st = app.session.active().ok_or("no document")?; + let (doc, revision) = (st.doc.clone(), st.revision); + let id = st.active_layer.ok_or("no active layer")?; + let layer = doc.layer(id).ok_or("no layer")?; + let surf = layer.surface().ok_or("Content-Aware Scale needs a pixel layer")?; + if region.is_empty() { + return Err("Could not scale: the layer is empty".into()); + } + crate::type_tool::commit(app); + let rect = [region.x0 as f64, region.y0 as f64, region.x1 as f64, region.y1 as f64]; + let session = app.ui.alloc_id(); + // The command clears the area before writing the result (a layer without transparency keeps it). + let mut pd = (*doc).clone(); + if let Some(s) = pd.layer_mut(id).and_then(|l| l.surface_mut()).filter(|s| s.format().alpha) { + let clear = vec![0.0; s.format().channels()]; + s.fill_rect(region, &clear); + s.prune(); + } + let max_side = ctx.input(|i| i.max_texture_side).max(app.gpu.as_ref().map_or(1, |g| g.max_texture_side())); + let above = Above::new(ctx, format!("transform-{session}-above"), &doc, id, max_side); + above.hide_in(&mut pd.layers); + let (image, uv) = crate::transform_tex::read_surface(surf, None, region, max_side); + let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), image, uv); + app.transform_preview = Some(TransformPreview { + session, + doc: Arc::new(pd), + texture, + opacity: layer.opacity * layer.fill_opacity, + above: Some(above), + follow: Some(Follow { revision, hidden: false }), + 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: Some(live), + styled: None, + }); + app.ui.transform = Some(TransformSession { + session, + layer: id.0, + rect, + quad: corners(rect), + pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], + interpolation: "bicubic".into(), + warp: None, + selection: false, + target: None, + path: None, + made: None, + mode: Default::default(), + content_aware: Some(Default::default()), + skew_v: 0.0, + }); + start_steps(app); + Ok(()) +} + +/// Undoes the layer a cancelled or failed session made (⌥⌘T's copy, a placed file), leaving +/// nothing to redo. +pub(super) fn take_back_made(app: &mut PhotocraftApp, document: DocId, layer: LayerId) { + // Tabs can move or close while transforming. Only undo the creation in its own document, + // and only while it is still the latest step (it may already have been undone). + let Some(index) = app.session.documents().iter().position(|st| { + st.doc.id == document + && st.doc.layer(layer).is_some() + && st.history.past_len().checked_sub(1).and_then(|i| st.history.state(i)).is_some_and(|before| before.layer(layer).is_none()) + }) else { + return; + }; + let active = app.session.active_index(); + app.session.set_active(index); + if app.session.undo() + && let Some(st) = app.session.active_mut() + { + st.history.clear_redo(); + } + if let Some(active) = active { + app.session.set_active(active); + } + app.sync_views(); +} + +/// After the transform: the step that made the layer and the transform become one history step, +/// the transform's for a copy and Place Embedded for a placed file. +pub(super) fn fold_made(app: &mut PhotocraftApp, document: DocId, layer: LayerId, made: MadeLayer) { + // A background commit lands in its own document, which need not be the active one by then. + let Some(index) = app.session.documents().iter().position(|st| st.doc.id == document) else { return }; + let active = app.session.active_index(); + app.session.set_active(index); + // Only when the step before the transform made the layer: a step taken while the box was + // open (New Layer, which also ends the box, #5667) stays its own, as does the made layer's. + if let Some(st) = app.session.active_mut() + && st.history.past_len().checked_sub(2).and_then(|i| st.history.state(i)).is_some_and(|before| before.layer(layer).is_none()) + { + st.history.purge_last(); + if made == MadeLayer::Place { + st.history.set_current_label(photocraft_engine::file_cmds::PLACE_EMBEDDED); + } + } + if let Some(active) = active { + app.session.set_active(active); + } +} + +/// Free Transform of a targeted unlinked layer mask, alpha channel or Quick Mask by itself: the +/// box frames its content (or the selection) and previews the moving values in grey over the +/// document with them vacated. +fn begin_lone( + app: &mut PhotocraftApp, + ctx: &egui::Context, + doc: Arc, + surf: photocraft_raster::Surface, + target: serde_json::Value, +) -> Result<(), String> { + use photocraft_engine::transform_cmds as tc; + let b = tc::target_frame(&doc, &surf); + if b.is_empty() { + return Err("Could not transform: nothing is selected".into()); + } + let whole; + let sel = match &doc.selection { + Some(s) => s, + None => { + let mut s = photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8); + s.fill_rect(b, &[1.0]); + whole = s; + &whole + } + }; + let (lifted, rest) = tc::split_gray_selected(&surf, sel).map_err(|e| e.to_string())?.ok_or("this channel can't be transformed")?; + crate::type_tool::commit(app); + let layer = app.session.active().and_then(|st| st.active_layer).map_or(0, |l| l.0); + let mut pd = (*doc).clone(); + let tp = json!({ "target": target }); + if let Ok(Some(s)) = tc::lone_target_mut(&mut pd, Some(LayerId(layer)), &tp) { + *s = rest; + } + let rect = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64]; + let session = app.ui.alloc_id(); + let max_side = ctx.input(|i| i.max_texture_side).max(app.gpu.as_ref().map_or(1, |g| g.max_texture_side())); + let (image, uv) = crate::transform_tex::read_surface(&lifted, None, b, max_side); + let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), image, uv); + app.transform_preview = Some(TransformPreview { + session, + doc: Arc::new(pd), + texture, + opacity: 0.6, + above: None, + styled: None, + follow: None, + 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, + }); + app.ui.transform = Some(TransformSession { + session, + layer, + rect, + quad: corners(rect), + pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], + interpolation: "bicubic".into(), + warp: None, + selection: false, + target: Some(target), + path: None, + made: None, + mode: Default::default(), + content_aware: None, + skew_v: 0.0, + }); + start_steps(app); + Ok(()) +} + +/// Edit › Free Transform Path: the box frames the path's anchors and handles and draws the +/// path through it; OK commits one `path.transform` step. +fn begin_path(app: &mut PhotocraftApp, ctx: &egui::Context, params: serde_json::Value, path: photocraft_doc::vector::Path) -> Result<(), String> { + let (x0, y0, x1, y1) = path.control_bounds().ok_or("the path has no points to transform")?; + let st = app.session.active().ok_or("no document")?; + let doc = st.doc.clone(); + let layer = st.active_layer.or_else(|| doc.layers.first().map(|l| l.id)).ok_or("no layer")?; + crate::type_tool::commit(app); + // A straight horizontal or vertical path still gets a box to turn. + let rect = [x0, y0, x1.max(x0 + 1.0), y1.max(y0 + 1.0)]; + let session = app.ui.alloc_id(); + let texture = + crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), egui::ColorImage::new([1, 1], vec![Color32::TRANSPARENT]), [1.0, 1.0]); + app.transform_preview = Some(TransformPreview { + session, + doc, + texture, + opacity: 1.0, + styled: 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: Some(path), + content_aware: None, + above: None, + follow: None, + committing: None, + }); + app.ui.transform = Some(TransformSession { + session, + layer: layer.0, + rect, + quad: corners(rect), + pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], + interpolation: "bicubic".into(), + warp: None, + selection: false, + target: None, + path: Some(params), + made: None, + mode: Default::default(), + content_aware: None, + skew_v: 0.0, + }); + start_steps(app); + Ok(()) +} + +/// The affine map taking `rect`'s corners to `quad`'s; `None` when the box was distorted out of a +/// parallelogram (Distort, Perspective): the path then goes as a `quad`. +pub(super) fn rect_to_quad_affine(r: [f64; 4], q: [[f64; 2]; 4]) -> Option { + let (w, h) = (r[2] - r[0], r[3] - r[1]); + if w <= 0.0 || h <= 0.0 { + return None; + } + let tol = 1e-3 * (1.0 + w.max(h)); + if (q[0][0] + q[2][0] - q[1][0] - q[3][0]).abs() > tol || (q[0][1] + q[2][1] - q[1][1] - q[3][1]).abs() > tol { + return None; + } + let (a, b) = ((q[1][0] - q[0][0]) / w, (q[1][1] - q[0][1]) / w); + let (c, d) = ((q[3][0] - q[0][0]) / h, (q[3][1] - q[0][1]) / h); + let m = [a, b, c, d, q[0][0] - a * r[0] - c * r[1], q[0][1] - b * r[0] - d * r[1]]; + m.iter().all(|v| v.is_finite()).then_some(photocraft_geom::Affine { m }) +} + +/// Start Select › Transform Selection: the same box over the selection's bounds, previewing the +/// selection mask (the marching ants are hidden meanwhile); commits `select.transformSelection`. +pub fn begin_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { + let st = app.session.active().ok_or("no document")?; + let doc = st.doc.clone(); + let sel = doc.selection.clone().ok_or("no selection")?; + let b = sel.content_bounds(); + if b.is_empty() { + return Err("no selection".into()); + } + let layer = st.active_layer.or_else(|| doc.layers.first().map(|l| l.id)).ok_or("no layer")?; + crate::type_tool::commit(app); + let rect = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64]; + let session = app.ui.alloc_id(); + let (w, h) = (b.width() as usize, b.height() as usize); + let k = w.max(h).div_ceil(2048).max(1); + let (tw, th) = (w.div_ceil(k), h.div_ceil(k)); + let mut px = vec![Color32::TRANSPARENT; tw * th]; + for ty in 0..th { + for tx in 0..tw { + let m = sel.sample_channel(b.x0 + (tx * k) as i32, b.y0 + (ty * k) as i32, 0).clamp(0.0, 1.0); + px[ty * tw + tx] = Color32::from_rgba_unmultiplied(120, 170, 255, (m * 110.0) as u8); + } + } + let uv = [w as f32 / (tw * k) as f32, h as f32 / (th * k) as f32]; + let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), egui::ColorImage::new([tw, th], px), uv); + let mut pd = (*doc).clone(); + pd.selection = None; + app.transform_preview = Some(TransformPreview { + session, + doc: Arc::new(pd), + texture, + opacity: 1.0, + above: None, + styled: None, + follow: None, + 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, + }); + app.ui.transform = Some(TransformSession { + session, + layer: layer.0, + rect, + quad: corners(rect), + pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], + interpolation: "bilinear".into(), + warp: None, + selection: true, + target: None, + path: None, + made: None, + mode: Default::default(), + content_aware: None, + skew_v: 0.0, + }); + start_steps(app); + Ok(()) +} + +/// Start (or switch an active Free Transform into) Warp mode. +pub fn begin_warp(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { + if app.ui.transform.as_ref().is_some_and(|t| t.content_aware.is_some()) { + return Err(CAS_ONLY_SCALES.into()); + } + let fresh = app.ui.transform.is_none(); + if fresh { + begin(app, ctx)?; + } + enter_warp(app, ctx); + // Started in Warp: that is where Undo stops. Switching an open transform to Warp is a step. + if fresh { + start_steps(app); + } + Ok(()) +} + +/// Switch to Warp mode: a smart object's existing warp (when the box is untouched), else a +/// custom mesh following the current box (so a transform made first carries over). Editable type +/// gets its own Warp Text style instead ([`enter_type_warp`]). +pub fn enter_warp(app: &mut PhotocraftApp, ctx: &egui::Context) { + if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none()) && warps_type(app) { + return enter_type_warp(app, ctx); + } + let existing = + app.session.active().and_then(|d| d.doc.layer(LayerId(app.ui.transform.as_ref()?.layer)).and_then(photocraft_engine::warp_cmds::smart_warp_doc_space)); + let Some(t) = app.ui.transform.as_mut() else { return }; + // Warp moves layers and paths (#3027): a lone mask or channel keeps the box. + if t.warp.is_some() || t.target.is_some() { + return; + } + if t.quad == corners(t.rect) + && !t.selection + && t.path.is_none() + && let Some(w) = existing + { + t.rect = w.bounds; + t.quad = corners(w.bounds); + t.warp = Some(w); + return; + } + let h = Homography::rect_to_quad(t.rect, t.quad).unwrap_or(Homography::IDENTITY); + let mesh = BezierMesh::identity(t.rect, 1, 1).map_points(|p| { + let (x, y) = h.apply(p[0], p[1]); + [x, y] + }); + t.warp = Some(Warp::custom(mesh, t.rect)); +} + +/// 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 { + let Some(t) = &app.ui.transform else { return false }; + if t.selection || t.target.is_some() || t.path.is_some() { + return false; + } + app.session.active().and_then(|st| st.doc.layer(LayerId(t.layer))).is_some_and(|l| matches!(l.content, LayerContent::Text(_))) +} + +/// Warp on editable type, as in Photoshop: no rasterizing, no mesh to drag, just the warp styles +/// of the options bar (Warp Text's). A box scaled or rotated first is applied first (that keeps +/// type editable). The preview shows the type without its current Warp Text, under that style. +fn enter_type_warp(app: &mut PhotocraftApp, ctx: &egui::Context) { + if app.ui.transform.as_ref().is_some_and(|t| t.quad != corners(t.rect)) { + commit(app); + if app.ui.transform.is_some() { + return; // refused: the box stays as it was + } + if let Err(e) = begin(app, ctx) { + app.ui.status = e; + return; + } + } + let (Some(t), Some(st)) = (app.ui.transform.as_ref(), app.session.active()) else { return }; + let (id, session) = (LayerId(t.layer), t.session); + let doc = st.doc.clone(); + let Some(LayerContent::Text(text)) = doc.layer(id).map(|l| &l.content) else { return }; + let current = text.warp.clone(); + let mut plain = (*doc).clone(); + if let Some(LayerContent::Text(tt)) = plain.layer_mut(id).map(|l| &mut l.content) + && current.is_some() + { + tt.warp = None; + photocraft_engine::type_cmds::refresh(&doc, tt); + } + let Some(b) = plain.layer(id).map(|l| photocraft_engine::transform_cmds::transform_bounds(&plain, l)).filter(|b| !b.is_empty()) else { return }; + let rect = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64]; + if current.is_some() + && let Some(pv) = app.transform_preview.as_mut() + { + let max_side = ctx.input(|i| i.max_texture_side).max(app.gpu.as_ref().map_or(1, |g| g.max_texture_side())); + // Read as the session's texels were: without the style when the box draws it itself. + let (image, uv) = preview_image(&plain, id, None, b, max_side, pv.styled.is_some()); + pv.texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), image, uv); + } + let warp = + current.as_ref().and_then(|w| WarpStyle::parse(&w.style).filter(|s| s.is_preset()).map(|s| (w, s))).map_or(Warp::none(rect), |(w, style)| Warp { + style, + bend: f64::from(w.value), + h_distort: f64::from(w.horizontal_distortion), + v_distort: f64::from(w.vertical_distortion), + vertical: !w.horizontal, + ..Warp::none(rect) + }); + if let Some(t) = app.ui.transform.as_mut() { + t.rect = rect; + t.quad = corners(rect); + t.pivot = [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0]; + t.warp = Some(warp); + } +} + +/// Leave Warp mode (back to the box; warp edits are dropped, like Photoshop's mode toggle on an +/// untouched warp). +pub fn leave_warp(app: &mut PhotocraftApp) { + if let Some(t) = app.ui.transform.as_mut() { + t.warp = None; + } + if let Some(pv) = app.transform_preview.as_mut() { + pv.split_tool = None; + pv.split_pointer = None; + pv.split_placing = false; + pv.split_quick = false; + } +} diff --git a/crates/ui-egui/src/transform_tool/commit.rs b/crates/ui-egui/src/transform_tool/commit.rs new file mode 100644 index 0000000000..23ab10e429 --- /dev/null +++ b/crates/ui-egui/src/transform_tool/commit.rs @@ -0,0 +1,358 @@ +use super::begin::{fold_made, rect_to_quad_affine, take_back_made, warps_type}; +use super::options_bar::{rotate_about_pivot, scale_about_pivot}; +use super::*; + +/// Undo and Redo while the commit runs in the background (Free Transform, or Warp). +const STILL_APPLYING: &str = "Free Transform is still being applied"; + +const STILL_WARPING: &str = "Warp is still being applied"; + +pub fn commit(app: &mut PhotocraftApp) { + if committing(app).is_some() { + return; + } + let document = app.transform_preview.as_ref().map(|pv| pv.doc.id); + if document.is_some_and(|id| app.session.active().is_none_or(|st| st.doc.id != id)) { + cancel(app); + return; + } + let type_layer = warps_type(app); + let Some(t) = app.ui.transform.take() else { return }; + let mut preview = app.transform_preview.take(); + if let Some(options) = &t.content_aware { + crate::cas_transform::commit(app, &t, options); + return; + } + if t.selection { + let mut p = json!({"rect": t.rect, "interpolation": t.interpolation}); + match &t.warp { + Some(w) if !w.is_identity() => p["warp"] = json!(w), + Some(_) => return, + None if t.quad == corners(t.rect) => return, + None => p["quad"] = json!(t.quad), + } + if let Err(e) = app.run("select.transformSelection", p) { + keep_open(app, t, preview, e); + } + return; + } + if let Some(target) = &t.path { + let mut p = target.clone(); + match &t.warp { + Some(w) if w.is_identity() => return, + Some(w) => p["warp"] = json!(w), + None if t.quad == corners(t.rect) => return, + // Distort and Perspective map the path through the box (#3027). + None => match rect_to_quad_affine(t.rect, t.quad) { + Some(a) => p["matrix"] = json!(a.m), + None => { + p["rect"] = json!(t.rect); + p["quad"] = json!(t.quad); + } + }, + } + if let Err(e) = app.run("path.transform", p) { + keep_open(app, t, preview, e); + } + return; + } + let made = t.made; + let r = if let Some(w) = &t.warp { + // Type with a Warp Text can be warped back to None; the engine skips an unchanged style. + if w.is_identity() && !type_layer { + return; + } + app.run("edit.transform.warp", json!({"layer": t.layer, "rect": t.rect, "warp": w, "interpolation": t.interpolation})) + } else { + if t.quad == corners(t.rect) { + return; // untouched: nothing to do and no history step; a ⌥⌘T copy or a place stays + } + let mut p = json!({"layer": t.layer, "rect": t.rect, "quad": t.quad, "interpolation": t.interpolation}); + if let Some(target) = &t.target { + p["target"] = target.clone(); + } + app.run("edit.transform", p) + }; + // A large layer's warp runs in the background: the session stays until the job ends. + if let Ok(v) = &r + && let Some(job) = v.get("pending").and_then(serde_json::Value::as_bool).filter(|p| *p).and(v.get("job")).and_then(serde_json::Value::as_u64) + && let Some(pv) = preview.as_mut() + { + pv.committing = Some(JobId(job)); + app.ui.transform = Some(t); + app.transform_preview = preview; + return; + } + match r { + // Nothing changed (an untouched cylinder or Warp Text): no step to fold a copy into, so + // it stays its own step, as for an untouched box. + Ok(v) if v.get("changed") == Some(&json!(false)) => {} + Ok(_) => finish(app, document, LayerId(t.layer), made, true), + Err(e) => keep_open(app, t, preview, e), + } +} + +/// After the transform landed or not: fold the layer the session made into its step, or take it +/// back. +fn finish(app: &mut PhotocraftApp, document: Option, layer: LayerId, made: Option, landed: bool) { + let (Some(made), Some(document)) = (made, document) else { return }; + if landed { + fold_made(app, document, layer, made); + } else { + take_back_made(app, document, layer); + } +} + +/// The job applying the transform, while it runs. +pub(crate) fn committing(app: &PhotocraftApp) -> Option { + app.transform_preview.as_ref().and_then(|pv| pv.committing) +} + +/// 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 committing(app) != Some(e.id) { + return; + } + let (Some(t), Some(mut pv)) = (app.ui.transform.take(), app.transform_preview.take()) else { return }; + // A refused commit (a result over the pixel budget, #3773) keeps the box open, as inline, + // unless picking another tool or layer started it: then the box ends, as Esc would. + if let JobOutcome::Failed(msg) = &e.outcome { + pv.committing = None; + keep_open(app, t, Some(pv), msg.clone()); + if switched_away(app) { + cancel(app); + } + return; + } + finish(app, Some(pv.doc.id), LayerId(t.layer), t.made, matches!(e.outcome, JobOutcome::Done(_))); +} + +/// A commit the engine refused (a result over the pixel budget, #3773): the box stays open as it +/// was, with the reason in the status bar, so the transform can be changed or cancelled. A copy or +/// a placed layer it made goes only when it is cancelled. +fn keep_open(app: &mut PhotocraftApp, t: TransformSession, preview: Option, e: String) { + app.ui.transform = Some(t); + app.transform_preview = preview; + app.ui.status = e; +} + +/// A transform whose layer or document went away (undo, close) ends silently; picking another tool +/// or selecting another layer (Layers panel, ⌘-click, the control channel) applies it, so the box +/// never stays on a layer that is no longer the active one (#1400). Checked every frame and before +/// each pointer event, so a press with a tool chosen just before it (`ui.pointer`'s `tool`) goes to +/// that tool. +pub fn end_if_left(app: &mut PhotocraftApp) { + let Some(t) = &app.ui.transform else { return }; + if committing(app).is_some() { + return; + } + let Some(st) = app.session.active() else { return cancel(app) }; + + let layer = LayerId(t.layer); + let made = t.made; + let preview_doc_id = app.transform_preview.as_ref().map(|pv| pv.doc.id); + let switched_document = preview_doc_id.is_some_and(|id| id != st.doc.id); + + let editing_placed_smart_object = switched_document + && made == Some(MadeLayer::Place) + && preview_doc_id + .is_some_and(|parent_id| app.session.smart_links.iter().any(|link| link.parent == parent_id && link.child == st.doc.id && link.layer == layer)); + + if editing_placed_smart_object { + app.ui.transform = None; + app.transform_preview = None; + } else if switched_document || st.doc.layer(layer).is_none() { + cancel(app); + } else if switched_away(app) { + commit(app); + // Picking another tool or layer can't leave a refused transform open: it ends, as Esc would. + // A commit still running in the background isn't refused: cancelling it would throw the + // transform away (and a dropped file with it, #5665). It ends the session when it lands, + // or ends it as Esc would if it is refused then (`on_job_event`). + if app.ui.transform.is_some() && committing(app).is_none() { + cancel(app); + } + } +} + +/// Another tool picked, or (outside Transform Selection) another layer selected, since the box +/// opened: the session ends ([`end_if_left`], #1400). +fn switched_away(app: &PhotocraftApp) -> bool { + let (Some(t), Some(st)) = (&app.ui.transform, app.session.active()) else { return false }; + app.transform_preview.as_ref().is_some_and(|pv| pv.tool != app.ui.tool) || (!t.selection && st.active_layer.is_some_and(|active| active.0 != t.layer)) +} + +/// Edits made while the box is open show in the preview at once, not only after the commit +/// (#1384): the moving layer's opacity, fill and visibility tint the moving pixels, and the +/// document under them (other layers, and the part of the layer a selection leaves behind) is +/// rebuilt from the current one. The moving pixels keep the session's. Called before the canvas +/// reads the preview, so it never caches a revision with the old preview. +pub fn follow_edits(app: &mut PhotocraftApp) { + let (Some(t), Some(pv)) = (&app.ui.transform, app.transform_preview.as_mut()) else { return }; + let Some(follow) = pv.follow.as_mut() else { return }; + let Some(st) = app.session.active().filter(|st| st.doc.id == pv.doc.id && st.revision != follow.revision) else { return }; + let id = LayerId(t.layer); + let (Some(live), Some(moving)) = (st.doc.layer(id), pv.doc.layer(id)) else { return }; + let mut pd = (*st.doc).clone(); + if let Some(l) = pd.layer_mut(id) { + l.content = moving.content.clone(); + l.visible = l.visible && !follow.hidden; + } + if let Some(a) = pv.above.as_mut() { + a.rebuild(&st.doc, id); + a.hide_in(&mut pd.layers); + } + pv.opacity = if live.visible { live.opacity * live.fill_opacity } else { 0.0 }; + follow.revision = st.revision; + pv.doc = Arc::new(pd); +} + +pub fn cancel(app: &mut PhotocraftApp) { + // Esc while the commit runs cancels the job; the session ends when it does. + if let Some(job) = committing(app) { + crate::jobs_ui::cancel(app, job); + return; + } + let transform = app.ui.transform.take(); + let preview = app.transform_preview.take(); + if let (Some(t), Some(pv)) = (transform, preview) + && t.made.is_some() + { + take_back_made(app, pv.doc.id, LayerId(t.layer)); + } +} + +/// The session's starting box: where Undo stops. +pub(super) fn start_steps(app: &mut PhotocraftApp) { + if let (Some(t), Some(pv)) = (&app.ui.transform, app.transform_preview.as_mut()) { + pv.steps = Steps { settled: Some(Step::of(t)), ..Steps::default() }; + } +} + +/// Record the box as an undo step whenever it comes to rest in a new state: once per drag (on +/// release), nudge or option edit (once typing in its field ends). Call once per frame. +pub fn track_steps(app: &mut PhotocraftApp, ctx: &egui::Context) { + let (Some(t), Some(pv)) = (&app.ui.transform, app.transform_preview.as_mut()) else { return }; + if pv.gesture.is_some() || pv.warp_drag.is_some() || ctx.input(|i| i.pointer.any_down()) || ctx.text_edit_focused() { + // Whatever comes to rest after this is more than the nudge. + pv.steps.fold = false; + return; + } + pv.steps.settle(Step::of(t)); +} + +/// Arrow keys while Free Transform is active: move the box (and its pivot) by `(dx, dy)`. +/// Nudges that follow each other closely are one Undo step of the session (`nudge_bundle`). +pub(crate) fn nudge(app: &mut PhotocraftApp, dx: f64, dy: f64) { + let (pause, now) = (crate::nudge_bundle::pause(app), app.nudge_bundle.now); + let Some(t) = app.ui.transform.as_mut().filter(|t| t.warp.is_none()) else { return }; + let before = Step::of(t); + t.quad = t.quad.map(|q| [q[0] + dx, q[1] + dy]); + t.pivot = [t.pivot[0] + dx, t.pivot[1] + dy]; + if let Some(pv) = app.transform_preview.as_mut() { + pv.steps.nudged(&before, Step::of(t), now, pause); + } +} + +/// 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"; + +/// 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 { + let t = app.ui.transform.as_ref()?; + if committing(app).is_some() { + return box_command(id).then_some(false); + } + let steps = app.transform_preview.as_ref().map(|pv| &pv.steps); + match id { + // Content-Aware Scale's box only scales: no switching it to another transform or Warp. + "edit.freeTransform" | "edit.freeTransformCopy" if t.content_aware.is_some() => Some(false), + i if i.starts_with("edit.transform.") && t.content_aware.is_some() => Some(false), + "edit.undo" => Some(steps.is_some_and(|s| s.can_undo(&Step::of(t)))), + "edit.redo" => Some(steps.is_some_and(|s| !s.redo.is_empty())), + // 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), + // 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()), + // Editable type can't be distorted (#2630, as #2701 rules for the menus outside a box). + "edit.transform.distort" | "edit.transform.perspective" if moves_type(app, t) => Some(false), + _ => None, + } +} + +/// Does the box move an editable type layer (not its selection outline, a lone mask or a path)? +pub(super) fn moves_type(app: &PhotocraftApp, t: &TransformSession) -> bool { + !t.selection + && t.target.is_none() + && t.path.is_none() + && app.session.active().and_then(|st| st.doc.layer(LayerId(t.layer))).is_some_and(|l| matches!(l.content, LayerContent::Text(_))) +} + +/// Edit › Transform's Rotate and Flip presets while a box is open: what they do to the box, as +/// `(kx, ky, angle)`: a scale along the box's own axes, then a rotation (radians, clockwise on +/// screen), both about the reference point. +fn box_preset(id: &str) -> Option<(f64, f64, f64)> { + use std::f64::consts::{FRAC_PI_2, PI}; + Some(match id { + "edit.transform.rotate180" => (1.0, 1.0, PI), + "edit.transform.rotate90Cw" => (1.0, 1.0, FRAC_PI_2), + "edit.transform.rotate90Ccw" => (1.0, 1.0, -FRAC_PI_2), + "edit.transform.flipHorizontal" => (-1.0, 1.0, 0.0), + "edit.transform.flipVertical" => (1.0, -1.0, 0.0), + _ => return None, + }) +} + +/// While transforming, the box owns the history for every caller (menus, shortcuts, the control +/// channel, MCP): Undo and Redo step through it, and Toggle Last State and History state jumps, +/// which would change the document under the box, are refused. Edit › Transform's Rotate and +/// Flip turn the box itself, as in Photoshop, instead of the layer under it; committing stays +/// with ↩ and the options bar. +/// `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() +} + +pub fn intercept(app: &mut PhotocraftApp, id: &str) -> Option> { + let warping = app.ui.transform.as_ref()?.warp.is_some(); + if committing(app).is_some() { + return box_command(id).then(|| Err(if warping { STILL_WARPING } else { STILL_APPLYING }.into())); + } + match id { + "edit.undo" => Some(Ok(step(app, false))), + "edit.redo" => Some(Ok(step(app, true))), + "edit.toggleLastState" | "history.selectState" | "edit.contentAwareScale" | "edit.puppetWarp" | SAVE_FOR_WEB => { + Some(Err("Commit or cancel the transform first".into())) + } + _ => { + let (kx, ky, angle) = box_preset(id)?; + if warping { + return Some(Err("Commit or cancel the transform first".into())); + } + scale_about_pivot(app, kx, ky); + rotate_about_pivot(app, angle); + Some(Ok(json!({"transform": app.ui.transform}))) + } + } +} + +/// Undo (or redo) one step of the open session; nothing mid-drag or with no step to take. +fn step(app: &mut PhotocraftApp, redo: bool) -> serde_json::Value { + let Some(t) = app.ui.transform.as_mut() else { return serde_json::Value::Null }; + let Some(pv) = app.transform_preview.as_mut().filter(|pv| pv.gesture.is_none() && pv.warp_drag.is_none()) else { + return serde_json::Value::Null; + }; + let s = &mut pv.steps; + s.settle(Step::of(t)); + let (from, to) = if redo { (&mut s.redo, &mut s.undo) } else { (&mut s.undo, &mut s.redo) }; + let Some(step) = from.pop() else { return serde_json::Value::Null }; + to.push(Step::of(t)); + s.settled = Some(step.clone()); + step.restore(t); + json!({"transform": t}) +} diff --git a/crates/ui-egui/src/transform_tool/drag_modes.rs b/crates/ui-egui/src/transform_tool/drag_modes.rs new file mode 100644 index 0000000000..8800df7e04 --- /dev/null +++ b/crates/ui-egui/src/transform_tool/drag_modes.rs @@ -0,0 +1,334 @@ +use super::pointer::{Gesture, Hit, carry_pivot}; +use super::*; + +/// The same effective modifiers drive the geometry and decide whether Ctrl is a distortion +/// gesture rather than the ordinary snap override. Keep type and Content-Aware Scale refusals. +pub(super) fn drag_mods(app: &PhotocraftApp, t: &TransformSession, hit: Hit, mods: egui::Modifiers) -> (TransformMode, egui::Modifiers) { + let (mode, mods) = if distort_refused(app, t) { scale_not_distort(t.mode, hit, mods) } else { (t.mode, mods) }; + let legacy = app.session.prefs().general.use_legacy_free_transform; + (mode, legacy_mods(legacy, hit, unlinked_mods(app.ui.transform_unlinked, legacy, hit, mods))) +} + +/// Only a freely distorted corner can snap its proposed position. Perspective moves paired +/// corners on one axis; Skew, Warp and Content-Aware Scale have their own constrained geometry. +pub(crate) fn corner_distorts(app: &PhotocraftApp, index: usize, mods: egui::Modifiers) -> bool { + let Some(t) = app.ui.transform.as_ref() else { return false }; + if t.quad.get(index).is_none() || t.warp.is_some() || t.content_aware.is_some() || t.mode == TransformMode::Skew { + return false; + } + let (mode, mods) = drag_mods(app, t, Hit::Corner(index), mods); + let mods = mode_mods(mode, Hit::Corner(index), mods); + mods.command && !(mods.alt && mods.shift) +} + +/// Editable type can be scaled, rotated and skewed but not distorted (#2630): the rule that greys +/// Distort and Perspective in `enable_rules::disabled`, for the box's own layer. A box on a path, +/// on the selection outline or on a lone mask or channel moves no type. +fn distort_refused(app: &PhotocraftApp, t: &TransformSession) -> bool { + t.path.is_none() + && !t.selection + && t.target.is_none() + && app.session.active().and_then(|st| st.doc.layer(LayerId(t.layer))).is_some_and(|l| matches!(l.content, LayerContent::Text(_))) +} + +/// Where Distort and Perspective are refused ([`distort_refused`]), ⌘-drag and ⌘⌥⇧-drag of a +/// corner scale like a plain corner drag (with ⌥ and ⇧ keeping their meaning), so the box never +/// takes a shape the commit would refuse (#3010). +fn scale_not_distort(mode: TransformMode, hit: Hit, mut mods: egui::Modifiers) -> (TransformMode, egui::Modifiers) { + if matches!(hit, Hit::Corner(_)) { + mods.command = false; + } + let mode = if matches!(mode, TransformMode::Distort | TransformMode::Perspective) { TransformMode::Free } else { mode }; + (mode, mods) +} + +/// Preferences › General › Use Legacy Free Transform, Photoshop's scaling before CC 2019: corner +/// drags stretch freely and ⇧ keeps the proportions, edge drags stretch their one axis whatever +/// the keys. The default is proportional for both, with ⇧ freeing them. +pub(crate) fn legacy_mods(legacy: bool, hit: Hit, mut mods: egui::Modifiers) -> egui::Modifiers { + if legacy && !mods.command { + match hit { + Hit::Corner(_) => mods.shift = !mods.shift, + Hit::Edge(_) => mods.shift = true, + _ => {} + } + } + mods +} + +/// The options bar's Maintain Aspect Ratio link turned off: corner and edge drags stretch freely +/// and ⇧ keeps the proportions, as in Photoshop CC 2019 and later (#4174). The legacy preference +/// already works that way, so it is left alone there. +pub(crate) fn unlinked_mods(unlinked: bool, legacy: bool, hit: Hit, mut mods: egui::Modifiers) -> egui::Modifiers { + if unlinked && !legacy && !mods.command && matches!(hit, Hit::Corner(_) | Hit::Edge(_)) { + mods.shift = !mods.shift; + } + mods +} + +/// Distort / Perspective modes: a corner drag acts as if that gesture's keys were held (⌘-drag a +/// corner distorts, ⌘⌥⇧-drag a corner adds perspective). Skew has its own ([`apply_mode_drag`]). +pub(super) fn mode_mods(mode: TransformMode, hit: Hit, mut mods: egui::Modifiers) -> egui::Modifiers { + match (mode, hit) { + (TransformMode::Distort, Hit::Corner(_)) => mods.command = true, + (TransformMode::Perspective, Hit::Corner(_)) => { + mods.command = true; + mods.alt = true; + mods.shift = true; + } + _ => {} + } + mods +} + +/// A handle drag in Edit › Transform `mode` (`Free` for Free Transform). `type_layer`: the box +/// moves editable type, which only takes affine transforms. +pub(crate) fn apply_mode_drag(s: &mut TransformSession, g: Gesture, p: [f64; 2], mode: TransformMode, type_layer: bool, mut mods: egui::Modifiers) { + if !mode_allows(mode, g.hit) { + return; + } + match (mode, g.hit) { + // Skew, as in Photoshop (#3437): a corner moves alone along one of its two edges, + // whichever the drag mostly follows; ⌥ moves the opposite corner the other way. + (TransformMode::Skew, Hit::Corner(i)) if i < 4 => { + let (d, q0) = ([p[0] - g.start[0], p[1] - g.start[1]], g.quad0); + // Corners 0..3 = TL, TR, BR, BL: the neighbour along the top/bottom edge, and along + // the left/right one. + let along = |j: usize| { + let e = [q0[i][0] - q0[j][0], q0[i][1] - q0[j][1]]; + let l = e[0].hypot(e[1]); + let u = if l > 0.0 { [e[0] / l, e[1] / l] } else { [0.0, 0.0] }; + let t = d[0] * u[0] + d[1] * u[1]; + [t * u[0], t * u[1]] + }; + let (hn, vn) = ([1, 0, 3, 2][i], [3, 2, 1, 0][i]); + let (h, v) = (along(hn), along(vn)); + let (m, partner) = if h[0].hypot(h[1]) >= v[0].hypot(v[1]) { (h, hn) } else { (v, vn) }; + // Editable type stays a parallelogram: the corner's whole edge slides with it. + let moved: &[usize] = if type_layer { &[i, partner] } else { &[i] }; + let mut q = q0; + for k in 0..4 { + let sign = if moved.contains(&k) { + 1.0 + } else if mods.alt && (if type_layer { true } else { k == (i + 2) % 4 }) { + // ⌥: the opposite corner (on type, the opposite edge) the other way. + -1.0 + } else { + continue; + }; + if let (Some(dst), Some(src)) = (q.get_mut(k), q0.get(k)) { + *dst = [src[0] + sign * m[0], src[1] + sign * m[1]]; + } + } + s.quad = keep_convex(q0, q); + s.pivot = carry_pivot(q0, s.quad, g.pivot0); + } + // Rotate (#3941): a corner or edge turns about the reference point, the same drag as the + // zone just outside the box. Free Transform still scales from those handles. + (TransformMode::Rotate, Hit::Corner(_) | Hit::Edge(_)) => { + let mut g = g; + g.hit = Hit::Outside; + apply_drag(s, g, p, mods); + } + // Skew: an edge slides only along itself (⌘⇧ in Free Transform). + (TransformMode::Skew, Hit::Edge(_)) => { + mods.command = true; + mods.shift = true; + apply_drag(s, g, p, mods); + } + _ => apply_drag(s, g, p, mode_mods(mode, g.hit, mods)), + } +} + +/// What a drag can do in each Edit › Transform mode: in Distort only the corners (and moving the +/// box from inside); in Skew everything but rotating from outside the box (#3437). A click +/// outside still commits. +pub(super) fn mode_allows(mode: TransformMode, h: Hit) -> bool { + match mode { + TransformMode::Distort => !matches!(h, Hit::Outside | Hit::Edge(_)), + TransformMode::Skew => h != Hit::Outside, + _ => true, + } +} + +/// The turn at each corner of a quad (cross products of consecutive edges): all the same sign +/// for a convex quad, mixed for a concave or self-intersecting one. +pub(super) fn turns(q: &[[f64; 2]; 4]) -> [f64; 4] { + std::array::from_fn(|k| { + let (a, b, c) = (q[k], q[(k + 1) % 4], q[(k + 2) % 4]); + (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) + }) +} + +/// Is `q` convex with the orientation `sign`, every corner turning by more than a sliver? +fn convex(q: &[[f64; 2]; 4], sign: f64, min_turn: f64) -> bool { + turns(q).iter().all(|t| t * sign > min_turn) +} + +/// Distort and Perspective stop a corner where the box would turn concave or fold over itself, +/// as Photoshop does (#1323): the result moves from `from` towards `to` as far as the quad stays +/// convex. A box that is not convex to begin with is left free. +pub(super) fn keep_convex(from: [[f64; 2]; 4], to: [[f64; 2]; 4]) -> [[f64; 2]; 4] { + let t0 = turns(&from); + let sign = t0[0].signum(); + // A sliver: a thousandth of the starting box's smallest turn, so the stop is short of flat. + let min_turn = t0.iter().map(|t| t.abs()).fold(f64::INFINITY, f64::min) * 1e-3; + if !(min_turn.is_finite() && min_turn > 0.0 && convex(&from, sign, 0.0)) || convex(&to, sign, min_turn) { + return to; + } + let lerp = |t: f64| -> [[f64; 2]; 4] { std::array::from_fn(|k| [from[k][0] + (to[k][0] - from[k][0]) * t, from[k][1] + (to[k][1] - from[k][1]) * t]) }; + let (mut lo, mut hi) = (0.0f64, 1.0f64); + for _ in 0..40 { + let mid = (lo + hi) / 2.0; + if convex(&lerp(mid), sign, min_turn) { lo = mid } else { hi = mid } + } + lerp(lo) +} + +pub(crate) fn apply_drag(s: &mut TransformSession, g: Gesture, p: [f64; 2], mods: egui::Modifiers) { + let (dx, dy) = (p[0] - g.start[0], p[1] - g.start[1]); + match g.hit { + Hit::Inside => { + // ⇧ locks the move to the axes and diagonals; the current offset keeps the lock stable. + let (dx, dy) = if mods.shift { + let prev = [s.quad[0][0] - g.quad0[0][0], s.quad[0][1] - g.quad0[0][1]]; + let d = crate::move_mods::constrain([dx, dy], Some(prev), crate::move_mods::TRANSFORM_DIRECTIONS); + (d[0], d[1]) + } else { + (dx, dy) + }; + s.quad = g.quad0.map(|q| [q[0] + dx, q[1] + dy]); + s.pivot = [g.pivot0[0] + dx, g.pivot0[1] + dy]; + } + Hit::Pivot => s.pivot = p, + Hit::Outside => { + let a0 = (g.start[1] - g.pivot0[1]).atan2(g.start[0] - g.pivot0[0]); + let a1 = (p[1] - g.pivot0[1]).atan2(p[0] - g.pivot0[0]); + let mut da = a1 - a0; + if mods.shift { + // Snap the resulting angle to 15° steps. + let base = (g.quad0[1][1] - g.quad0[0][1]).atan2(g.quad0[1][0] - g.quad0[0][0]); + let step = 15f64.to_radians(); + da = ((base + da) / step).round() * step - base; + } + let (sn, cs) = da.sin_cos(); + let c = g.pivot0; + s.quad = g.quad0.map(|q| { + let (x, y) = (q[0] - c[0], q[1] - c[1]); + [c[0] + x * cs - y * sn, c[1] + x * sn + y * cs] + }); + } + Hit::Corner(i) if mods.command && mods.alt && mods.shift => { + // Perspective: the corner moves along the dominant axis and the corner sharing that + // side moves the opposite way. + s.quad = g.quad0; + let horizontal = dx.abs() >= dy.abs(); + // Corners 0..3 = TL, TR, BR, BL: horizontal drags pair along the top/bottom edge, + // vertical ones along the left/right edge. + let j = match (i, horizontal) { + (0, true) => 1, + (1, true) => 0, + (2, true) => 3, + (3, true) => 2, + (0, false) => 3, + (3, false) => 0, + (1, false) => 2, + _ => 1, + }; + let (mx, my) = if horizontal { (dx, 0.0) } else { (0.0, dy) }; + let mut q = g.quad0; + q[i] = [g.quad0[i][0] + mx, g.quad0[i][1] + my]; + q[j] = [g.quad0[j][0] - mx, g.quad0[j][1] - my]; + s.quad = keep_convex(g.quad0, q); + s.pivot = carry_pivot(g.quad0, s.quad, g.pivot0); + } + Hit::Corner(i) if mods.command => { + // Distort: move the corner freely, up to where the box would fold over (#1323). + let mut q = g.quad0; + q[i] = [g.quad0[i][0] + dx, g.quad0[i][1] + dy]; + s.quad = keep_convex(g.quad0, q); + s.pivot = carry_pivot(g.quad0, s.quad, g.pivot0); + } + Hit::Edge(i) if mods.command => { + // Skew: the edge's two corners move together (⇧: only along the edge). + let (a, b) = (i, (i + 1) % 4); + let (mut mx, mut my) = (dx, dy); + if mods.shift { + let e = [g.quad0[b][0] - g.quad0[a][0], g.quad0[b][1] - g.quad0[a][1]]; + let l2 = e[0] * e[0] + e[1] * e[1]; + let t = if l2 > 0.0 { (dx * e[0] + dy * e[1]) / l2 } else { 0.0 }; + (mx, my) = (t * e[0], t * e[1]); + } + s.quad = g.quad0; + s.quad[a] = [g.quad0[a][0] + mx, g.quad0[a][1] + my]; + s.quad[b] = [g.quad0[b][0] + mx, g.quad0[b][1] + my]; + if mods.alt { + // ⌥: the opposite edge skews the other way (about the centre). + let (c, d) = ((i + 2) % 4, (i + 3) % 4); + s.quad[c] = [g.quad0[c][0] - mx, g.quad0[c][1] - my]; + s.quad[d] = [g.quad0[d][0] - mx, g.quad0[d][1] - my]; + } + s.pivot = carry_pivot(g.quad0, s.quad, g.pivot0); + } + Hit::Corner(_) | Hit::Edge(_) => { + // Work in the box's own (unit) frame so rotated/skewed boxes scale along their axes. + let Some(h) = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], g.quad0) else { return }; + let Some(inv) = h.inverse() else { return }; + let (u, v) = inv.apply(p[0], p[1]); + let (pu, pv) = inv.apply(g.pivot0[0], g.pivot0[1]); + // Which sides of the unit box move: (u = 0, u = 1) and (v = 0, v = 1). + let (mu, mv) = match g.hit { + Hit::Corner(0) => ((true, false), (true, false)), + Hit::Corner(1) => ((false, true), (true, false)), + Hit::Corner(2) => ((false, true), (false, true)), + Hit::Corner(3) => ((true, false), (false, true)), + Hit::Edge(0) => ((false, false), (true, false)), + Hit::Edge(1) => ((false, true), (false, false)), + Hit::Edge(2) => ((false, false), (false, true)), + _ => ((true, false), (false, false)), + }; + // Each axis scales by a factor `k` about an anchor: the opposite side, or with ⌥ the + // reference point, wherever it was set (#1329). The dragged handle follows the cursor. + let axis = |moving: (bool, bool), at: f64, pivot: f64| -> (f64, f64) { + if !moving.0 && !moving.1 { + return (0.5, 1.0); + } + let handle = if moving.0 { 0.0 } else { 1.0 }; + let anchor = if mods.alt { pivot } else { 1.0 - handle }; + let d = handle - anchor; + // A reference point on the dragged side leaves nothing to scale against. + let k = if d.abs() > 1e-9 { (at - anchor) / d } else { 1.0 }; + (anchor, if k.is_finite() { k } else { 1.0 }) + }; + let (mut au, mut ku) = axis(mu, u, pu); + let (mut av, mut kv) = axis(mv, v, pv); + // Corners and edges scale proportionally by default; ⇧ frees them (the legacy + // preference swaps the two for corners and always stretches edges, `legacy_mods`). + let corner = matches!(g.hit, Hit::Corner(_)); + if !corner && !mods.shift { + // An edge sets the scale of its own axis, and the other axis follows by the same + // factor about the middle of the box (⌥: about the reference point, as for + // corners), so the opposite edge's handle stays put. Past the opposite edge only + // the dragged axis flips. + if mu.0 || mu.1 { + (av, kv) = (if mods.alt { pv } else { 0.5 }, ku.abs()); + } else { + (au, ku) = (if mods.alt { pu } else { 0.5 }, kv.abs()); + } + } + if corner && !mods.shift { + let k = ku.abs().max(kv.abs()); + (ku, kv) = (k * ku.signum(), k * kv.signum()); + } + let r = [au - au * ku, av - av * kv, au + (1.0 - au) * ku, av + (1.0 - av) * kv]; + let map = |a: f64, b: f64| { + let (x, y) = h.apply(a, b); + [x, y] + }; + s.quad = [map(r[0], r[1]), map(r[2], r[1]), map(r[2], r[3]), map(r[0], r[3])]; + // ⌥ scales about the reference point, so it stays put; otherwise it rides along with + // the box, keeping its place in it (#1329). + s.pivot = if mods.alt { g.pivot0 } else { carry_pivot(g.quad0, s.quad, g.pivot0) }; + } + } +} diff --git a/crates/ui-egui/src/transform_tool/draw.rs b/crates/ui-egui/src/transform_tool/draw.rs new file mode 100644 index 0000000000..2dce211108 --- /dev/null +++ b/crates/ui-egui/src/transform_tool/draw.rs @@ -0,0 +1,498 @@ +use super::begin::warps_type; +use super::options_bar::{quad_scale, readout}; +use super::pointer::{Hit, rotate_dir, rotation_degrees}; +use super::warp::{on_section_edge, quick_split_kind, single_patch}; +use super::*; + +/// For each vertex of the preview's `n` × `n` grid over the unit square (row by row), whether it +/// maps to the front side of `h`'s horizon. A Distort dragged past the horizon sends the rest of +/// the image to the far side, where its cells would wrap round infinity; the preview leaves them +/// out, as the committed warp does (#4863). +pub(super) fn front_vertices(h: &Homography, n: usize) -> Vec { + let front = h.front_side([0.0, 0.0, 1.0, 1.0]); + (0..=n).flat_map(|j| (0..=n).map(move |i| (i as f64 / n as f64, j as f64 / n as f64))).map(|(u, v)| front * h.w(u, v) > 1e-9).collect() +} + +/// The moving pixels as the box shows them (warped, skewed or styled), plus the layers above +/// them. This is image content: the canvas draws it right after the document, under the grid +/// and guides, so a guide stays visible across a layer being transformed (#5086), as in +/// Photoshop. The box, handles and reference point are [`draw_overlay`], drawn over the guides. +pub fn draw_content(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { + let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) else { return }; + let output = crate::monitor_status::view_display(app, painter.ctx()); + let (display, _) = crate::canvas::canvas_display(app, &pv.doc, output); + // Selection tint and lone mask/channel values are UI diagnostics, not document colors. + let display = display.as_deref().filter(|_| !t.selection && t.target.is_none() && t.path.is_none()); + if let Some(w) = &t.warp { + draw_warp_content(painter, xf, t, w, pv, display); + return; + } + let ctx = painter.ctx(); + let styled = + styled_frame(app, xf.zoom * ctx.pixels_per_point(), ctx.input(|i| i.pointer.any_down())).and_then(|(s, frame)| s.texture(ctx, &frame, display)); + if let Some((tex, r)) = styled { + let mut mesh = egui::Mesh::with_texture(tex); + for (x, y, u, v) in [(r[0], r[1], 0.0, 0.0), (r[2], r[1], 1.0, 0.0), (r[2], r[3], 1.0, 1.0), (r[0], r[3], 0.0, 1.0)] { + mesh.vertices.push(egui::epaint::Vertex { pos: pos2(x, y), uv: pos2(u, v), color: Color32::WHITE }); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(clip_to_canvas(mesh, canvas_size(pv), |p| xf.to_screen(p.x, p.y))); + } else if let Some(h) = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], t.quad) { + // A 24×24 grid keeps perspective previews straight. + let n = 24; + let zoom = xf.zoom * painter.ctx().pixels_per_point(); + // Content-Aware Scale shows its latest live result once there is one. + let (tex, uv) = match pv.content_aware.as_ref().and_then(|l| l.shown(t)) { + Some((texture, texel)) => texture.pick_display(painter.ctx(), zoom, texel, false, display), + None => pv.texture.pick_display(painter.ctx(), zoom, quad_scale(t), t.interpolation == "nearest", display), + }; + let mut mesh = egui::Mesh::with_texture(tex); + let tint = Color32::from_white_alpha((pv.opacity.clamp(0.0, 1.0) * 255.0) as u8); + let ahead = front_vertices(&h, n); + for j in 0..=n { + for i in 0..=n { + let (u, v) = (i as f64 / n as f64, j as f64 / n as f64); + let (x, y) = h.apply(u, v); + mesh.vertices.push(egui::epaint::Vertex { pos: pos2(x as f32, y as f32), uv: pos2(u as f32 * uv[0], v as f32 * uv[1]), color: tint }); + } + } + for j in 0..n { + for i in 0..n { + let a = (j * (n + 1) + i) as u32; + for tri in [[a, a + 1, a + n as u32 + 2], [a, a + n as u32 + 2, a + n as u32 + 1]] { + // A cell with a corner past the horizon would stretch across the canvas (#4863). + if tri.iter().all(|&k| ahead[k as usize]) { + mesh.add_triangle(tri[0], tri[1], tri[2]); + } + } + } + } + painter.add(clip_to_canvas(mesh, canvas_size(pv), |p| xf.to_screen(p.x, p.y))); + } + if let Some(a) = &pv.above { + a.draw(painter, xf, display); + } +} + +/// The box, handles, reference point and path outline over the preview that [`draw_content`] +/// drew; the warp grid and its split guides for a warp. +pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { + let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) else { return }; + let scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32); + if let Some(w) = &t.warp { + let over_canvas = painter.ctx().input(|i| i.pointer.hover_pos()).filter(|p| xf.rect.contains(*p)).map(|p| xf.to_doc(p)); + let at = pv.split_pointer.or(over_canvas); + let alt = painter.ctx().input(|i| i.modifiers.alt || i.modifiers.command); + let guide = at.filter(|_| !warps_type(app)).and_then(|p| { + let tool = pv.split_tool.or_else(|| { + (alt || pv.split_quick).then(|| { + let m = w.to_mesh(1, 1); + quick_split_kind(&m, w.bounds, m.param_at(p)) + }) + }); + tool.map(|tool| (tool, p)) + }); + draw_warp_overlay(painter, xf, w, pv, guide); + return; + } + if pv.committing.is_some() { + return; + } + let accent = crate::theme::Tokens::get(painter.ctx()).accent; + if let (Some(path), Some(h)) = (&pv.path, Homography::rect_to_quad(t.rect, t.quad)) { + crate::vector_ui::draw_outline( + painter, + path, + &|q| { + let (x, y) = h.apply(q[0], q[1]); + xf.to_screen(x as f32, y as f32) + }, + accent, + ); + } + let pts: Vec = t.quad.iter().map(|q| scr(*q)).collect(); + painter.add(egui::Shape::closed_line(pts.clone(), Stroke::new(1.0, accent))); + let mids: Vec = (0..4).map(|i| pts[i].lerp(pts[(i + 1) % 4], 0.5)).collect(); + for p in pts.iter().chain(mids.iter()) { + let r = egui::Rect::from_center_size(*p, vec2(7.0, 7.0)); + painter.rect_filled(r, 0.0, Color32::WHITE); + painter.rect_stroke(r, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside); + } + // Reference point (Photoshop's crosshair circle). + let c = scr(t.pivot); + painter.circle_stroke(c, 5.0, Stroke::new(1.0, Color32::WHITE)); + painter.circle_stroke(c, 5.0, Stroke::new(0.5, Color32::BLACK)); + painter.line_segment([c - vec2(8.0, 0.0), c + vec2(8.0, 0.0)], Stroke::new(1.0, Color32::WHITE)); + painter.line_segment([c - vec2(0.0, 8.0), c + vec2(0.0, 8.0)], Stroke::new(1.0, Color32::WHITE)); + if let Some(at) = painter.ctx().pointer_hover_pos().filter(|p| xf.rect.contains(*p)) { + let p = xf.to_doc(at); + let tol = HANDLE_PX / f64::from(xf.zoom.max(0.01)); + if let Some(k) = rotate_dir(t, Some(pv), p, tol) { + // Through the view, so the arc bends round the corner as it shows under a turned or + // flipped view. + let toward = xf.to_screen((p[0] + k[0] * 16.0) as f32, (p[1] + k[1] * 16.0) as f32) - at; + crate::crop_ui::draw_turn_cursor(painter.ctx(), at, toward); + } + // Preferences › Tools › Show Transformation Values off hides it, as in Photoshop (#204). + if let Some(r) = live_readout(app).filter(|_| app.session.prefs().tools.show_transformation_values) { + draw_live_readout(painter.ctx(), at, r); + } + } +} + +/// Applying the open box moves the selection outline with it: `edit.transform` and +/// `edit.transform.warp` map it like the pixels. Not Transform Selection (its ants are hidden), a +/// path, Content-Aware Scale or a type layer's Warp Text, which leave the selection alone. +fn carries_selection(app: &PhotocraftApp, t: &TransformSession) -> bool { + !t.selection && t.path.is_none() && t.content_aware.is_none() && !(t.warp.is_some() && warps_type(app)) +} + +/// A transform of `document` is open that carries its selection along (#5297): the canvas traces +/// the whole outline, not only the part in view where it started, for [`draw_selection`]. +pub(crate) fn carries_selection_of(app: &PhotocraftApp, document: DocId) -> bool { + matches!((&app.ui.transform, &app.transform_preview), (Some(t), Some(pv)) if pv.doc.id == document && carries_selection(app, t)) +} + +/// The marching ants where the open box puts them (#5297): the selection follows a move, scale, +/// rotation, skew, distort, perspective or warp while it is made, to where applying it leaves it. +/// `segs` is the outline of `document`'s selection at rest. False when no open transform carries +/// that selection: the caller draws it where it is. +pub(crate) fn draw_selection( + app: &PhotocraftApp, + painter: &egui::Painter, + xf: &ViewXform, + document: DocId, + segs: &[crate::outline::Segment], + time: f64, +) -> bool { + let Some(t) = app.ui.transform.as_ref().filter(|_| carries_selection_of(app, document)) else { return false }; + let scr = |(x, y): (f64, f64)| xf.to_screen(x as f32, y as f32); + let doc = |p: [i32; 2]| [f64::from(p[0]), f64::from(p[1])]; + let along = |a: [f64; 2], b: [f64; 2], k: f64| [a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k]; + if let Some(w) = &t.warp { + // A warp bends the outline's straight runs: each is drawn in pieces about 8 points long. + let piece = (8.0 / f64::from(xf.zoom.max(1e-3))).max(1.0); + let lines = segs.iter().flat_map(|(a, b)| { + let (a, b) = (doc(*a), doc(*b)); + let n = (((b[0] - a[0]).abs() + (b[1] - a[1]).abs()) / piece).ceil().clamp(1.0, 256.0) as usize; + let at = move |i: usize| { + let p = along(a, b, i as f64 / n as f64); + scr(w.map(p[0], p[1])) + }; + (0..n).map(move |i| (at(i), at(i + 1))) + }); + crate::canvas::marching_ants_lines(painter, lines, time); + } else if let Some(h) = Homography::rect_to_quad(t.rect, t.quad) { + // Past a Distort's horizon the outline has no place, like the pixels (#4863): a run that + // crosses it stops short of it, where its points are still a finite way off. + let front = h.front_side(t.rect); + let depth = |p: [f64; 2]| front * h.w(p[0], p[1]); + let near = corners(t.rect).iter().map(|c| depth(*c)).fold(0.0, f64::max) * 1e-3; + let lines = segs.iter().filter_map(|(a, b)| { + let (mut a, mut b) = (doc(*a), doc(*b)); + let (da, db) = (depth(a), depth(b)); + if da < near && db < near { + return None; + } + if da < near { + a = along(a, b, (near - da) / (db - da)); + } else if db < near { + b = along(b, a, (near - db) / (da - db)); + } + Some((scr(h.apply(a[0], a[1])), scr(h.apply(b[0], b[1])))) + }); + crate::canvas::marching_ants_lines(painter, lines, time); + } + true +} + +/// What the styled preview of the moving layer is drawn from (transform_fx.rs), at `zoom` screen +/// pixels per document pixel. `None` for a layer without a style (also once it is switched off +/// while the box is open) or a hidden one: the bare pixels are drawn instead. The style, opacity +/// and fill are the layer's as they are now, so edits made while the box is open show. +pub(crate) fn styled_frame(app: &PhotocraftApp, zoom: f32, dragging: bool) -> Option<(&crate::transform_fx::StyledPreview, crate::transform_fx::Frame<'_>)> { + let (t, pv) = (app.ui.transform.as_ref()?, app.transform_preview.as_ref()?); + let styled = pv.styled.as_ref().filter(|_| t.warp.is_none())?; + let st = app.session.active().filter(|st| st.doc.id == pv.doc.id)?; + let layer = st.doc.layer(LayerId(t.layer)).filter(|l| l.visible && photocraft_compose::effects::has_effects(l))?; + let frame = crate::transform_fx::Frame { + doc: &st.doc, + layer, + revision: st.revision, + texels: &pv.texture, + quad: t.quad, + quad_scale: quad_scale(t), + nearest: t.interpolation == "nearest", + zoom, + dragging, + }; + Some((styled, frame)) +} + +/// The value shown beside the pointer while the box is dragged, like Photoshop's Show +/// Transformation Values: the box's angle while rotating, its scale while resizing, the offset +/// while moving. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Readout { + /// Clockwise degrees in document space (`rotation_degrees`), whatever the view's turn or flip. + Angle(f64), + /// Width and height in percent of the original box. + Scale([f64; 2]), + /// Document pixels moved since the press. + Offset([f64; 2]), +} + +/// The readout for the drag in progress, or `None` when nothing is dragged (or the drag is the +/// reference point, a warp, or a distortion that has no single scale). +pub(crate) fn live_readout(app: &PhotocraftApp) -> Option { + let t = app.ui.transform.as_ref().filter(|t| t.warp.is_none())?; + let g = app.transform_preview.as_ref()?.gesture?; + match g.hit { + Hit::Outside => Some(Readout::Angle(rotation_degrees(t.quad))), + Hit::Inside => Some(Readout::Offset([t.quad[0][0] - g.quad0[0][0], t.quad[0][1] - g.quad0[0][1]])), + Hit::Corner(_) | Hit::Edge(_) if parallelogram(&t.quad) => { + let (w, h, _, _) = readout(t); + (w.is_finite() && h.is_finite()).then_some(Readout::Scale([w, h])) + } + Hit::Corner(_) | Hit::Edge(_) | Hit::Pivot => None, + } +} + +/// True when `q` is still an affine image of the box (opposite sides parallel), so a W/H scale +/// describes it; a distorted or perspective box has none. +fn parallelogram(q: &[[f64; 2]; 4]) -> bool { + let scale = q.iter().flatten().fold(1.0f64, |m, v| m.max(v.abs())); + (0..2).all(|k| ((q[0][k] + q[2][k]) - (q[1][k] + q[3][k])).abs() <= scale * 1e-9) +} + +/// [`live_readout`] as the rounded label beside the pointer (the marquee's and Crop's readout). +fn draw_live_readout(ctx: &egui::Context, at: Pos2, r: Readout) { + // Round first so a hair below zero never reads "-0". + let fixed = |v: f64, places: i32| { + let k = 10f64.powi(places); + let v = (v * k).round() / k; + if v == 0.0 { 0.0 } else { v } + }; + let id = "transform-readout"; + match r { + Readout::Angle(a) => crate::canvas::draw_readout(ctx, id, at, ["Angle:"], [format!("{:.1}°", fixed(a, 1))]), + Readout::Scale([w, h]) => crate::canvas::draw_readout(ctx, id, at, ["W:", "H:"], [w, h].map(|v| format!("{:.1}%", fixed(v, 1)))), + Readout::Offset([dx, dy]) => crate::canvas::draw_readout(ctx, id, at, ["ΔX:", "ΔY:"], [dx, dy].map(|v| format!("{:.0} px", fixed(v, 0)))), + } +} + +/// Width and height of the document being transformed, in document pixels. +fn canvas_size(pv: &TransformPreview) -> [f32; 2] { + [pv.doc.size.width as f32, pv.doc.size.height as f32] +} + +/// Clips `mesh` (positions in document pixels) to the canvas `[0, 0, size]` and maps it to the +/// screen. Pixels past the canvas edge are never shown, also not while transforming (Photoshop; +/// #2027): only the box and its handles reach over the pasteboard. Clipping in document space +/// stays exact under a rotated or flipped view, where a screen clip rectangle would not. +fn clip_to_canvas(mut mesh: egui::Mesh, size: [f32; 2], to_screen: impl Fn(Pos2) -> Pos2) -> egui::Mesh { + let inside = |p: Pos2| p.x >= 0.0 && p.y >= 0.0 && p.x <= size[0] && p.y <= size[1]; + if mesh.vertices.iter().all(|v| inside(v.pos)) { + for v in &mut mesh.vertices { + v.pos = to_screen(v.pos); + } + return mesh; + } + let mut out = egui::Mesh::with_texture(mesh.texture_id); + for tri in mesh.indices.as_chunks::<3>().0 { + let mut poly: Vec = tri.iter().filter_map(|i| mesh.vertices.get(*i as usize).copied()).collect(); + // Sutherland–Hodgman against the four canvas edges (`dist` >= 0 is the canvas side). + for edge in 0..4 { + let dist = |v: &egui::epaint::Vertex| match edge { + 0 => v.pos.x, + 1 => size[0] - v.pos.x, + 2 => v.pos.y, + _ => size[1] - v.pos.y, + }; + let mut next = Vec::with_capacity(poly.len() + 2); + for (k, a) in poly.iter().enumerate() { + let Some(b) = poly.get((k + 1) % poly.len()) else { continue }; + let (da, db) = (dist(a), dist(b)); + if da >= 0.0 { + next.push(*a); + } + if (da >= 0.0) != (db >= 0.0) && da != db { + let t = da / (da - db); + next.push(egui::epaint::Vertex { pos: a.pos.lerp(b.pos, t), uv: a.uv.lerp(b.uv, t), color: a.color }); + } + } + poly = next; + } + if poly.len() < 3 { + continue; + } + let base = out.vertices.len() as u32; + out.vertices.extend(poly.iter().map(|v| egui::epaint::Vertex { pos: to_screen(v.pos), ..*v })); + for k in 1..poly.len() as u32 - 1 { + out.add_triangle(base, base + k, base + k + 1); + } + } + out +} + +/// Warp preview (the moving pixels on a fine textured mesh) plus the control mesh. Patch +/// boundaries are solid. A single patch (Grid › Default) also draws its rule-of-thirds guides; +/// 3×3, 4×4 and 5×5 are just those even cells, with an anchor at every intersection. `guide` is +/// the split line following the pointer. +/// How near the pointer (screen px) a handle's anchor or the handle itself must be for the +/// handle to show. Everything else stays out of the way: only anchors are always drawn. +const HANDLE_REVEAL_PX: f32 = 56.0; + +/// The anchor a handle belongs to, as `(i, j)` in the control grid (an anchor is its own). +pub(super) fn handle_anchor(i: usize, j: usize) -> (usize, usize) { + if i.is_multiple_of(3) { + let aj = match j % 3 { + 0 => j, + 1 => j - 1, + _ => j + 1, + }; + (i, aj) + } else { + (if i % 3 == 1 { i - 1 } else { i + 1 }, j) + } +} + +/// Anchors always, small and quiet. A handle and its arm show only while the pointer is close to +/// them or they are being dragged, so a dense grid does not bury the picture in dots. +fn draw_warp_points(painter: &egui::Painter, m: &BezierMesh, scr: impl Fn([f64; 2]) -> Pos2, pv: &TransformPreview, line: Stroke) { + let (nx, ny) = (m.nx(), m.ny()); + let hover = painter.ctx().input(|i| i.pointer.hover_pos()); + let dragged = match &pv.warp_drag { + Some(WarpDrag::Point { index, .. }) => Some(handle_anchor(index % nx, index / nx)), + _ => None, + }; + let near = |p: Pos2| hover.is_some_and(|h| h.distance(p) <= HANDLE_REVEAL_PX); + let faint = Stroke::new(0.75, line.color.gamma_multiply(0.8)); + for j in 0..ny { + for i in 0..nx { + if !on_section_edge(i, j) { + continue; + } + let p = scr(m.point(i, j)); + if i.is_multiple_of(3) && j.is_multiple_of(3) { + let r = egui::Rect::from_center_size(p, vec2(5.0, 5.0)); + painter.rect_filled(r, 0.0, Color32::WHITE); + painter.rect_stroke(r, 0.0, faint, egui::StrokeKind::Inside); + continue; + } + let (ai, aj) = handle_anchor(i, j); + let a = scr(m.point(ai, aj)); + if !(near(p) || near(a) || dragged == Some((ai, aj))) { + continue; + } + painter.line_segment([a, p], faint); + painter.circle_filled(p, 2.75, Color32::WHITE); + painter.circle_stroke(p, 2.75, faint); + } + } +} + +/// The warped pixels and the layers above them ([`draw_content`] for a warp). +fn draw_warp_content( + painter: &egui::Painter, + xf: &ViewXform, + t: &TransformSession, + w: &Warp, + pv: &TransformPreview, + display: Option<&photocraft_engine::display_color::CanvasDisplay>, +) { + let r = t.rect; + let m = w.to_mesh(1, 1); + let (us, vs) = crate::warp_preview::samples(&m, xf.zoom as f64); + let (tex, uv) = pv.texture.pick_display(painter.ctx(), xf.zoom * painter.ctx().pixels_per_point(), 1.0, t.interpolation == "nearest", display); + let mut mesh = egui::Mesh::with_texture(tex); + let tint = Color32::from_white_alpha((pv.opacity.clamp(0.0, 1.0) * 255.0) as u8); + for v in &vs { + for u in &us { + let (x, y) = w.map(r[0] + u * (r[2] - r[0]), r[1] + v * (r[3] - r[1])); + mesh.vertices.push(egui::epaint::Vertex { pos: pos2(x as f32, y as f32), uv: pos2(*u as f32 * uv[0], *v as f32 * uv[1]), color: tint }); + } + } + let pos: Vec<[f32; 2]> = mesh.vertices.iter().map(|v| [v.pos.x, v.pos.y]).collect(); + let rest: Vec<[f32; 2]> = vs.iter().flat_map(|v| us.iter().map(move |u| [(r[0] + u * (r[2] - r[0])) as f32, (r[1] + v * (r[3] - r[1])) as f32])).collect(); + mesh.indices = crate::warp_preview::triangle_order(&pos, &rest, us.len()); + painter.add(clip_to_canvas(mesh, canvas_size(pv), |p| xf.to_screen(p.x, p.y))); + if let Some(a) = &pv.above { + a.draw(painter, xf, display); + } +} + +/// The warp grid, its control points and split guides ([`draw_overlay`] for a warp). +fn draw_warp_overlay(painter: &egui::Painter, xf: &ViewXform, w: &Warp, pv: &TransformPreview, guide: Option<(SplitTool, [f64; 2])>) { + let scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32); + let m = w.to_mesh(1, 1); + let accent = crate::theme::Tokens::get(painter.ctx()).accent; + // Transform Path › Warp: the path drawn through the warp. + if let Some(path) = &pv.path { + crate::vector_ui::draw_outline( + painter, + path, + &|q| { + let (x, y) = w.map(q[0], q[1]); + xf.to_screen(x as f32, y as f32) + }, + accent, + ); + } + let line = Stroke::new(1.0, accent); + let thin = Stroke::new(0.75, accent.gamma_multiply(0.7)); + let curve = |fixed_u: Option, fixed_v: Option| -> Vec { + (0..=40) + .map(|k| { + let s = k as f64 / 40.0; + let p = m.eval(fixed_u.unwrap_or(s), fixed_v.unwrap_or(s)); + scr(p) + }) + .collect() + }; + // Patch boundaries 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); + for (k, win) in m.us.windows(2).enumerate() { + if thirds { + for third in [1.0, 2.0] { + painter.add(egui::Shape::line(curve(Some(win[0] + (win[1] - win[0]) * third / 3.0), None), thin)); + } + } + if k == 0 { + painter.add(egui::Shape::line(curve(Some(win[0]), None), line)); + } + painter.add(egui::Shape::line(curve(Some(win[1]), None), line)); + } + for (k, win) in m.vs.windows(2).enumerate() { + if thirds { + for third in [1.0, 2.0] { + painter.add(egui::Shape::line(curve(None, Some(win[0] + (win[1] - win[0]) * third / 3.0)), thin)); + } + } + if k == 0 { + painter.add(egui::Shape::line(curve(None, Some(win[0])), line)); + } + painter.add(egui::Shape::line(curve(None, Some(win[1])), line)); + } + if w.style == WarpStyle::Custom { + draw_warp_points(painter, &m, scr, pv, line); + } + if let Some((tool, p)) = guide { + let (s, t) = m.param_at(p); + let under = Stroke::new(3.0, Color32::BLACK); + let over = Stroke::new(1.25, Color32::WHITE); + let mut strokes = Vec::new(); + if matches!(tool, SplitTool::Vertical | SplitTool::Cross) { + strokes.push(curve(Some(s), None)); + } + if matches!(tool, SplitTool::Horizontal | SplitTool::Cross) { + strokes.push(curve(None, Some(t))); + } + for pts in strokes { + painter.add(egui::Shape::line(pts.clone(), under)); + painter.add(egui::Shape::line(pts, over)); + } + } +} diff --git a/crates/ui-egui/src/transform_tool/options_bar.rs b/crates/ui-egui/src/transform_tool/options_bar.rs new file mode 100644 index 0000000000..e2f1ad20ac --- /dev/null +++ b/crates/ui-egui/src/transform_tool/options_bar.rs @@ -0,0 +1,595 @@ +use super::begin::{enter_warp, leave_warp, warps_type}; +use super::commit::{cancel, commit}; +use super::pointer::point_on_quad; +use super::warp::edit_session_warp; +use super::*; + +/// How much the box enlarges its pixels: the longest edge relative to the original (picks the +/// preview's texture level and filter). +pub(super) fn quad_scale(t: &TransformSession) -> f32 { + let (w0, h0) = ((t.rect[2] - t.rect[0]).max(1e-9), (t.rect[3] - t.rect[1]).max(1e-9)); + let len = |a: [f64; 2], b: [f64; 2]| (b[0] - a[0]).hypot(b[1] - a[1]); + let q = &t.quad; + let s = (len(q[0], q[1]) / w0).max(len(q[3], q[2]) / w0).max(len(q[0], q[3]) / h0).max(len(q[1], q[2]) / h0); + if s.is_finite() { s as f32 } else { 1.0 } +} + +/// W and H (%), the angle (°) and the horizontal skew (°) the options bar shows for the box. +/// A mirrored box reads as a negative W or H, whichever keeps the angle nearer 0 (Photoshop: +/// Flip Horizontal is W -100 % at 0°, Flip Vertical H -100 % at 0°). Both are the same box: +/// negating W and H and turning by a half turn cancel out. +pub(super) fn readout(t: &TransformSession) -> (f64, f64, f64, f64) { + let p = Parts::of(t); + let wrap = |a: f64| { + let a = a.rem_euclid(std::f64::consts::TAU); + if a > std::f64::consts::PI { a - std::f64::consts::TAU } else { a } + }; + let turned = wrap(p.angle + std::f64::consts::PI); + let (sx, sy, angle) = if p.sy < 0.0 && turned.abs() < wrap(p.angle).abs() { (-p.sx, -p.sy, turned) } else { (p.sx, p.sy, p.angle) }; + (sx * 100.0, sy * 100.0, angle.to_degrees(), p.skew_h.to_degrees()) +} + +/// `v`, kept off zero with its sign: a divisor for a W or H scale that may be negative. +fn nonzero(v: f64) -> f64 { + if v.abs() < 1e-9 { 1e-9f64.copysign(v) } else { v } +} + +/// The box's affine part read as Photoshop's options bar does: the frame scaled (W, H), skewed +/// (H, V) and then rotated about the reference point. Angles are radians; positive turns +/// clockwise on screen, so a positive H skew leans the box's sides like the angle field would +/// turn them, and a positive V skew its top and bottom. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct Parts { + pub(super) sx: f64, + /// Negative when the box is flipped vertically relative to its rotation. + pub(super) sy: f64, + pub(super) angle: f64, + pub(super) skew_h: f64, + pub(super) skew_v: f64, +} + +/// The skew fields' reach: a skew of ±90° would flatten the box. +pub(super) const SKEW_LIMIT_DEG: f32 = 89.0; + +impl Parts { + /// The box's columns: where the frame's unit X and Y edges went (from the top-left corner). + fn columns(t: &TransformSession) -> Option<[[f64; 2]; 2]> { + let (w0, h0) = (t.rect[2] - t.rect[0], t.rect[3] - t.rect[1]); + if w0.abs() < 1e-9 || h0.abs() < 1e-9 { + return None; + } + let q = &t.quad; + let m = [[(q[1][0] - q[0][0]) / w0, (q[1][1] - q[0][1]) / w0], [(q[3][0] - q[0][0]) / h0, (q[3][1] - q[0][1]) / h0]]; + m.iter().flatten().all(|v| v.is_finite()).then_some(m) + } + + /// The box as scale, skew and rotation, keeping the session's typed V skew (any box can be + /// written with any V skew short of ±90°). + fn of(t: &TransformSession) -> Parts { + let skew_v = t.skew_v.to_radians(); + let none = Parts { sx: 1.0, sy: 1.0, angle: 0.0, skew_h: 0.0, skew_v }; + Parts::columns(t).map_or(none, |m| Parts::from_columns(m, skew_v)) + } + + pub(super) fn from_columns([c0, c1]: [[f64; 2]; 2], skew_v: f64) -> Parts { + // X edge = sx · R(angle) · (1, tan v): its direction is the angle plus v. + let angle = c0[1].atan2(c0[0]) - skew_v; + let sx = c0[0].hypot(c0[1]) * skew_v.cos(); + // Y edge = sy · R(angle) · (−tan h, 1). + let (gx, gy) = unturn(c1, angle); + let skew_h = if gy.abs() < 1e-12 { 0.0 } else { (-gx / gy).atan() }; + Parts { sx, sy: gy, angle, skew_h, skew_v } + } + + pub(super) fn columns_of(self) -> [[f64; 2]; 2] { + let (sn, cs) = self.angle.sin_cos(); + let rot = |x: f64, y: f64| [x * cs - y * sn, x * sn + y * cs]; + let c0 = rot(self.sx, self.sx * self.skew_v.tan()); + let c1 = rot(-self.sy * self.skew_h.tan(), self.sy); + [c0, c1] + } +} + +/// `c` turned back by `angle` (radians). +fn unturn(c: [f64; 2], angle: f64) -> (f64, f64) { + let (sn, cs) = angle.sin_cos(); + (c[0] * cs + c[1] * sn, -c[0] * sn + c[1] * cs) +} + +/// Sets the box's H and V skew (degrees), keeping its scale, angle and reference point: the +/// options bar's skew fields. +fn skew_about_pivot(app: &mut PhotocraftApp, skew_h: f64, skew_v: f64) { + let Some(s) = app.ui.transform.as_mut() else { return }; + let Some(m) = Parts::columns(s) else { return }; + let limit = f64::from(SKEW_LIMIT_DEG); + let (skew_h, skew_v) = (skew_h.clamp(-limit, limit), skew_v.clamp(-limit, limit)); + let from = Parts::from_columns(m, s.skew_v.to_radians()); + let to = Parts { skew_h: skew_h.to_radians(), skew_v: skew_v.to_radians(), ..from }.columns_of(); + // The map from the old box to the new one: to · m⁻¹. + let det = m[0][0] * m[1][1] - m[1][0] * m[0][1]; + if det.abs() < 1e-12 { + return; + } + let inv = [[m[1][1] / det, -m[0][1] / det], [-m[1][0] / det, m[0][0] / det]]; + let l = |x: f64, y: f64| { + let (u, v) = (inv[0][0] * x + inv[1][0] * y, inv[0][1] * x + inv[1][1] * y); + [to[0][0] * u + to[1][0] * v, to[0][1] * u + to[1][1] * v] + }; + let c = s.pivot; + let quad = s.quad.map(|q| { + let d = l(q[0] - c[0], q[1] - c[1]); + [c[0] + d[0], c[1] + d[1]] + }); + if quad.iter().flatten().all(|v| v.is_finite()) { + s.quad = quad; + s.skew_v = skew_v; + } +} + +/// Width of the mode, cancel and commit cluster kept on the right of the options bar. +const ACTIONS_W: f32 = 140.0; + +/// Width of the action buttons when they follow the Warp fields (one more than the box bar: Reset). +const WARP_ACTIONS_W: f32 = 176.0; + +/// Reach of the reference point X/Y fields: the largest document side (`image.canvasSize`'s limit). +pub(super) const POSITION_LIMIT_PX: f32 = 300_000.0; + +/// Reach of the W/H fields. The engine takes any scale; this lets a 30 px layer span the largest +/// document (#1267). +pub(super) const SCALE_LIMIT_PCT: f32 = 1_000_000.0; + +/// The W or H field's limit for a box side of `side` px: as far as the result stays within the +/// largest document side, so a typed scale can't ask for an image too large to allocate. +pub(super) fn scale_limit_pct(side: f64) -> f32 { + let side = side.abs(); + if !side.is_finite() || side < 1e-6 { + return SCALE_LIMIT_PCT; + } + ((f64::from(POSITION_LIMIT_PX) / side * 100.0) as f32).clamp(100.0, SCALE_LIMIT_PCT) +} + +/// Where Free Transform remembers the unit of its W and H fields, picked by right-clicking either +/// of them as in Photoshop (Percent until another is picked). +pub(super) const SIZE_UNIT_KEY: &str = "edit.freeTransform"; + +/// The W/H unit, with the document's resolution and the points per inch it converts with. +pub(super) fn size_unit(app: &PhotocraftApp) -> crate::layer_props_ui::LenUnit { + use photocraft_engine::prefs::Unit; + let unit = app.session.prefs().dialogs.get(SIZE_UNIT_KEY).and_then(|v| v.get("sizeUnit")).and_then(serde_json::Value::as_str).and_then(Unit::parse); + crate::layer_props_ui::LenUnit { unit: unit.unwrap_or(Unit::Percent), ..crate::layer_props_ui::LenUnit::of(app) } +} + +pub(super) fn set_size_unit(app: &mut PhotocraftApp, name: &str) { + app.session.prefs.edit(|p| { + let entry = p.dialogs.entry(SIZE_UNIT_KEY.to_string()).or_insert_with(|| json!({})); + if !entry.is_object() { + *entry = json!({}); + } + entry["sizeUnit"] = json!(name); + }); +} + +/// A W or H value shown in `u`: the box side `side` px wide at the original size, scaled by `pct`. +/// Percent stays the scale itself (100 % is the original size), lengths are the side's length. +pub(super) fn size_shown(u: &crate::layer_props_ui::LenUnit, pct: f64, side: f64) -> f32 { + u.shown(pct / 100.0 * side, side) +} + +/// The scale (%) a W or H value typed in `u` asks for, for a box side `side` px wide originally. +pub(super) fn size_pct(u: &crate::layer_props_ui::LenUnit, v: f32, side: f64) -> f64 { + let side = side.abs().max(1e-9); + u.px(v, side) / side * 100.0 +} + +/// Options bar while transforming: the fields (reference point X/Y, W/H %, angle, interpolation, +/// or the warp controls), then the mode switch, cancel and commit right after them. A bar too +/// narrow for both pins the buttons to the right edge and clips the fields, so Commit and Cancel +/// are always reachable. +pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let Some(t) = app.ui.transform.clone() else { return }; + let bar = ui.available_rect_before_wrap(); + let warping = t.warp.is_some(); + let buttons_w = if warping { WARP_ACTIONS_W } else { ACTIONS_W }; + let split = (bar.right() - buttons_w).max(bar.left()); + let fields = egui::Rect::from_min_max(bar.min, egui::pos2(split, bar.bottom())); + let mut row = ui.new_child(egui::UiBuilder::new().id_salt("transform-fields").max_rect(fields).layout(egui::Layout::left_to_right(egui::Align::Center))); + row.set_clip_rect(fields); + if let Some(w) = t.warp.clone() { + warp_fields(app, &mut row, &w); + } else if t.content_aware.is_some() { + crate::cas_transform::fields(app, &mut row, &t); + } else { + transform_fields(app, &mut row, &t); + } + crate::widgets::vline(&mut row, 22.0); + let start = row.min_rect().right().min(split); + let actions = egui::Rect::from_min_max(egui::pos2(start, bar.top()), egui::pos2(start + buttons_w, bar.bottom())); + let mut btns = ui.new_child(egui::UiBuilder::new().id_salt("transform-actions").max_rect(actions).layout(egui::Layout::right_to_left(egui::Align::Center))); + transform_actions(app, &mut btns, warping, t.content_aware.is_none()); +} + +fn transform_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &TransformSession) { + let tk = crate::theme::Tokens::get(ui.ctx()); + let (_, _, angle, skew_h) = readout(t); + let lbl = |ui: &mut egui::Ui, s: &str| { + ui.label(egui::RichText::new(s).color(tk.text_dim).size(12.0)); + }; + position_size_fields(app, ui, t); + crate::widgets::vline(ui, 22.0); + let mut a = angle as f32; + let (r, resp) = ui.allocate_exact_size(vec2(18.0, 22.0), egui::Sense::hover()); + crate::icons::paint(ui, r, "rotate-cw", 13.0, tk.text_dim); + resp.on_hover_text(tl!("Rotate")); + if crate::widgets::value_field(ui, &mut a, -180.0..=180.0, "°", 60.0).accessible_name(tl!("Rotate")).changed() { + rotate_about_pivot(app, (a as f64 - angle).to_radians()); + } + // Photoshop's H and V skew fields: the box's sides lean by H, its top and bottom by V. + let (mut h, mut v) = (skew_h as f32, t.skew_v as f32); + let lim = -SKEW_LIMIT_DEG..=SKEW_LIMIT_DEG; + lbl(ui, "H:"); + let rh = + crate::widgets::value_field(ui, &mut h, lim.clone(), "°", 56.0).accessible_name(tl!("Set horizontal skew")).on_hover_text(tl!("Set horizontal skew")); + lbl(ui, "V:"); + let rv = crate::widgets::value_field(ui, &mut v, lim, "°", 56.0).accessible_name(tl!("Set vertical skew")).on_hover_text(tl!("Set vertical skew")); + if rh.changed() || rv.changed() { + skew_about_pivot(app, f64::from(h), f64::from(v)); + } + crate::widgets::vline(ui, 22.0); + lbl(ui, tl!("Interpolation:")); + let mut interp = t.interpolation.clone(); + let opts = [("bicubic".to_string(), tl!("Bicubic")), ("bilinear".to_string(), tl!("Bilinear")), ("nearest".to_string(), tl!("Nearest Neighbor"))]; + if crate::widgets::dropdown(ui, "transform-interp", tl!("Interpolation"), &mut interp, &opts, 130.0) + && let Some(s) = app.ui.transform.as_mut() + { + s.interpolation = interp; + } +} + +pub(super) fn matching_anchor(quad: [[f64; 2]; 4], pivot: [f64; 2]) -> Option { + (0..9).find(|&i| { + let p = point_on_quad(quad, i); + (p[0] - pivot[0]).abs() <= 0.05 && (p[1] - pivot[1]).abs() <= 0.05 + }) +} + +fn anchor_grid_widget(ui: &mut egui::Ui, current_anchor: Option) -> Option { + let size = egui::vec2(16.0, 16.0); + let (rect, resp) = ui.allocate_exact_size(size, egui::Sense::click()); + let tk = crate::theme::Tokens::get(ui.ctx()); + let painter = ui.painter(); + painter.rect_stroke(rect, 1.0, egui::Stroke::new(1.0, tk.card_border), egui::StrokeKind::Inside); + let mut clicked = None; + let pointer = resp.interact_pointer_pos(); + for row in 0..3 { + for col in 0..3 { + let idx = row * 3 + col; + let cx = rect.min.x + (col as f32 + 0.5) * (rect.width() / 3.0); + let cy = rect.min.y + (row as f32 + 0.5) * (rect.height() / 3.0); + let pt_rect = egui::Rect::from_center_size(egui::pos2(cx, cy), egui::vec2(3.5, 3.5)); + if resp.clicked() && pointer.is_some_and(|p| (p.x - cx).abs() <= 3.0 && (p.y - cy).abs() <= 3.0) { + clicked = Some(idx); + } + if current_anchor == Some(idx) { + painter.rect_filled(pt_rect, 0.5, tk.accent); + } else { + painter.rect_filled(pt_rect, 0.5, tk.text_dim); + } + } + } + resp.on_hover_text(tl!("Reference point location")); + clicked +} + +/// The reference point's X/Y and the W/H scale fields (with the aspect link) of the options bar. +pub(crate) fn position_size_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &TransformSession) { + let tk = crate::theme::Tokens::get(ui.ctx()); + let (sx, sy, _, _) = readout(t); + let lbl = |ui: &mut egui::Ui, s: &str| { + ui.label(egui::RichText::new(s).color(tk.text_dim).size(12.0)); + }; + let current_anchor = matching_anchor(t.quad, t.pivot); + let mut pivot = t.pivot; + if let Some(new_anchor) = anchor_grid_widget(ui, current_anchor) { + let new_p = point_on_quad(t.quad, new_anchor); + if let Some(s) = app.ui.transform.as_mut() { + s.pivot = new_p; + } + pivot = new_p; + } + ui.add_space(4.0); + let mut px = pivot[0] as f32; + let mut py = pivot[1] as f32; + lbl(ui, "X:"); + let rx = crate::widgets::value_field(ui, &mut px, -POSITION_LIMIT_PX..=POSITION_LIMIT_PX, "px", 72.0).accessible_name("X"); + lbl(ui, "Y:"); + let ry = crate::widgets::value_field(ui, &mut py, -POSITION_LIMIT_PX..=POSITION_LIMIT_PX, "px", 72.0).accessible_name("Y"); + if (rx.changed() || ry.changed()) + && let Some(s) = app.ui.transform.as_mut() + { + let (dx, dy) = (px as f64 - s.pivot[0], py as f64 - s.pivot[1]); + s.quad = s.quad.map(|q| [q[0] + dx, q[1] + dy]); + s.pivot = [px as f64, py as f64]; + } + crate::widgets::vline(ui, 22.0); + // W and H in the unit picked from their right-click menu: the scale in percent, or the box's + // length (Photoshop's units, at the document's resolution). + let u = size_unit(app); + let (side_w, side_h) = (t.rect[2] - t.rect[0], t.rect[3] - t.rect[1]); + let (wlim, hlim) = (scale_limit_pct(side_w), scale_limit_pct(side_h)); + let (wlim_u, hlim_u) = (size_shown(&u, f64::from(wlim), side_w), size_shown(&u, f64::from(hlim), side_h)); + let (mut w, mut h) = (size_shown(&u, sx, side_w), size_shown(&u, sy, side_h)); + let (suffix, places) = (u.unit.suffix(), u.unit.decimals() as u32); + // Lengths need more room than a percentage ("2116.67 mm"). + let size_w = if u.unit == photocraft_engine::prefs::Unit::Percent { 66.0 } else { 84.0 }; + // Whatever their unit, W and H take any other typed in (`500 px` or `2 in` in percent, `50%` + // in a length), converted at the document's resolution against the box's original side (#6284). + let units = crate::widgets::FieldUnits { unit: u.unit, dpi: u.dpi, ppi: u.ppi }; + lbl(ui, "W:"); + let rw = crate::widgets::value_field_extent(ui, &mut w, -wlim_u..=wlim_u, suffix, size_w, places, units, side_w).accessible_name(tl!("Width")); + let link = !app.ui.transform_unlinked; + if crate::icons::button(ui, if link { "link" } else { "unlink" }, 22.0, link, tl!("Maintain aspect ratio")).clicked() { + app.ui.transform_unlinked = link; + } + lbl(ui, "H:"); + let rh = crate::widgets::value_field_extent(ui, &mut h, -hlim_u..=hlim_u, suffix, size_w, places, units, side_h).accessible_name(tl!("Height")); + for r in [&rw, &rh] { + r.context_menu(|ui| { + if let Some(name) = crate::rulers::unit_menu(ui, u.unit) { + set_size_unit(app, name); + } + }); + } + let (w, h) = (size_pct(&u, w, side_w) as f32, size_pct(&u, h, side_h) as f32); + if rw.changed() || rh.changed() { + let (kx, ky) = if link { + let k = if rw.changed() { w as f64 / nonzero(sx) } else { h as f64 / nonzero(sy) }; + // Linked, the other side follows: keep it within its own limit too. + let k = k.min(f64::from(wlim) / sx.abs().max(1e-9)).min(f64::from(hlim) / sy.abs().max(1e-9)); + (k, k) + } else { + (w as f64 / nonzero(sx), h as f64 / nonzero(sy)) + }; + scale_about_pivot(app, kx, ky); + } +} + +/// Options bar fields in Warp mode: style, bend, the split icons and the grid menu. +fn warp_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, w: &Warp) { + let tk = crate::theme::Tokens::get(ui.ctx()); + let lbl = |ui: &mut egui::Ui, s: &str| { + ui.label(egui::RichText::new(s).color(tk.text_dim).size(12.0)); + }; + // Type takes only the styles (#3004): Split and Grid are greyed, and there is no Custom. + let on_type = warps_type(app); + // Split, Grid, then the warp style with its bend fields. + ui.add_enabled_ui(!on_type, |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(); + if crate::widgets::dropdown(ui, "warp-style", tl!("Warp"), &mut style, &opts, 120.0) + && let Some(t) = app.ui.transform.as_mut() + { + let b = t.rect; + t.warp = Some(match style { + WarpStyle::Custom => Warp::custom(w.to_mesh(1, 1), b), + WarpStyle::None if on_type => Warp::none(b), + WarpStyle::None => Warp::custom(BezierMesh::identity(b, 1, 1), b), + s => Warp { style: s, bend: if w.style.is_preset() { w.bend } else { 50.0 }, ..Warp::none(b) }, + }); + } + // Orientation and the bend fields are always there, and only act on a preset style. + 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")); + orient.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, preset, "Change warp orientation")); + if orient.clicked() + && let Some(Some(cur)) = app.ui.transform.as_mut().map(|t| t.warp.as_mut()) + { + cur.vertical = !cur.vertical; + } + let fields: [(&str, f64); 3] = [(tl!("Bend:"), w.bend), ("H:", w.h_distort), ("V:", w.v_distort)]; + for (k, (name, v)) in fields.iter().enumerate() { + lbl(ui, name); + let mut f = *v as f32; + if crate::widgets::value_field(ui, &mut f, -100.0..=100.0, "%", 58.0).accessible_name(*name).changed() + && let Some(Some(cur)) = app.ui.transform.as_mut().map(|t| t.warp.as_mut()) + { + match k { + 0 => cur.bend = f64::from(f), + 1 => cur.h_distort = f64::from(f), + _ => cur.v_distort = f64::from(f), + } + } + } + }); +} + +/// 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()); + let lbl = |ui: &mut egui::Ui, s: &str| { + ui.label(egui::RichText::new(s).color(tk.text_dim).size(12.0)); + }; + lbl(ui, tl!("Split:")); + let armed = app.transform_preview.as_ref().and_then(|p| p.split_tool); + for (tool, tip) in [ + (SplitTool::Cross, tl!("Split Warp Crosswise")), + (SplitTool::Vertical, tl!("Split Warp Vertically")), + (SplitTool::Horizontal, tl!("Split Warp Horizontally")), + ] { + let on = armed == Some(tool); + if split_icon(ui, tool.icon(), tip, on).clicked() + && let Some(pv) = app.transform_preview.as_mut() + { + pv.split_tool = if on { None } else { Some(tool) }; + pv.split_placing = false; + pv.split_pointer = None; + pv.split_quick = false; + } + } + crate::widgets::vline(ui, 22.0); + lbl(ui, tl!("Grid:")); + let mesh = w.mesh.clone().unwrap_or_else(|| BezierMesh::identity(w.bounds, 1, 1)); + let mut grid = warp_grid_id(&mesh).to_string(); + let opts = [ + ("custom".to_string(), tl!("Custom")), + ("default".to_string(), tl!("Default")), + ("3".to_string(), tl!("3 x 3")), + ("4".to_string(), tl!("4 x 4")), + ("5".to_string(), tl!("5 x 5")), + ]; + if crate::widgets::dropdown(ui, "warp-grid", tl!("Grid"), &mut grid, &opts, 92.0) + && let Some(n) = match grid.as_str() { + "default" => Some(1), + "3" => Some(3), + "4" => Some(4), + "5" => Some(5), + _ => None, + } + { + let _ = edit_session_warp(app, "edit.transform.warpGrid", &json!({ "size": n })); + } +} + +/// Back to the untouched box: the default one-patch grid over the box, no bend. +pub fn reset_warp(app: &mut PhotocraftApp) { + let Some(t) = app.ui.transform.as_mut() else { return }; + if t.warp.is_none() { + return; + } + let b = t.rect; + t.warp = Some(Warp::custom(BezierMesh::identity(b, 1, 1), b)); + if warps_type(app) + && let Some(t) = app.ui.transform.as_mut() + { + t.warp = Some(Warp::none(b)); + } + if let Some(pv) = app.transform_preview.as_mut() { + pv.warp_drag = None; + pv.split_tool = None; + pv.split_pointer = None; + pv.split_placing = false; + pv.split_quick = false; + } +} + +/// Grid menu readout: Default is 1×1, the numbered entries are uniform n×n patches, and anything +/// split by hand reads as Custom. +pub(super) fn warp_grid_id(mesh: &BezierMesh) -> &'static str { + let cols = mesh.us.len().saturating_sub(1); + let rows = mesh.vs.len().saturating_sub(1); + let even = |k: &[f64]| { + let n = k.len().saturating_sub(1); + n > 0 && k.iter().enumerate().all(|(i, v)| (v - i as f64 / n as f64).abs() < 1e-4) + }; + if cols == rows && even(&mesh.us) && even(&mesh.vs) { + match cols { + 1 => "default", + 3 => "3", + 4 => "4", + 5 => "5", + _ => "custom", + } + } else { + "custom" + } +} + +/// One of the three Split icons. `on` is the armed tool: the line then follows the pointer. +fn split_icon(ui: &mut egui::Ui, kind: &str, tip: &str, on: bool) -> egui::Response { + let (rect, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), egui::Sense::click()); + let ink = crate::icons::button_chrome(ui, rect, on, resp.hovered()); + let c = rect.center(); + let stroke = Stroke::new(1.15, ink); + let box_r = egui::Rect::from_center_size(c, vec2(13.0, 13.0)); + ui.painter().rect_stroke(box_r, 2.0, stroke, egui::StrokeKind::Inside); + let h = 5.2; + match kind { + "vertical" => { + ui.painter().line_segment([c - vec2(0.0, h), c + vec2(0.0, h)], stroke); + } + "horizontal" => { + ui.painter().line_segment([c - vec2(h, 0.0), c + vec2(h, 0.0)], stroke); + } + _ => { + ui.painter().line_segment([c - vec2(h, 0.0), c + vec2(h, 0.0)], stroke); + ui.painter().line_segment([c - vec2(0.0, h), c + vec2(0.0, h)], stroke); + } + } + if kind == "cross" { + ui.painter().circle_filled(c, 1.5, ink); + } else { + ui.painter().circle_stroke(c, 2.1, stroke); + } + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); + resp.on_hover_text(tip) +} + +/// Warp switch, cancel and commit, kept on the right of the options bar. +/// `mode_switch`: the Free Transform / Warp switch (not for Content-Aware Scale, which only scales). +fn transform_actions(app: &mut PhotocraftApp, ui: &mut egui::Ui, warping: bool, mode_switch: bool) { + ui.add_space(8.0); + let commit_tip = if warping { + crate::i18n::fmt(tl!("Commit warp ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]) + } else { + crate::i18n::fmt(tl!("Commit transform ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]) + }; + let commit_btn = crate::icons::button(ui, "check", 26.0, false, &commit_tip); + let label = "Commit transform"; + commit_btn.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(label))); + if commit_btn.clicked() { + commit(app); + } + let cancel_tip = if warping { tl!("Cancel warp (Esc)") } else { tl!("Cancel transform (Esc)") }; + let cancel_btn = crate::icons::button(ui, "ban", 26.0, false, cancel_tip); + let label = "Cancel transform"; + cancel_btn.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(label))); + if cancel_btn.clicked() { + cancel(app); + } + if warping { + let reset = crate::icons::button(ui, "undo-2", 26.0, false, tl!("Reset")); + reset.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Reset warp")); + if reset.clicked() { + reset_warp(app); + } + } + if !mode_switch { + return; + } + crate::widgets::vline(ui, 22.0); + let mode = crate::icons::button(ui, "grid-3x3", 26.0, warping, tl!("Switch between free transform and warp modes")); + mode.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Switch between free transform and warp modes")); + if mode.clicked() { + if warping { + leave_warp(app); + } else { + enter_warp(app, &ui.ctx().clone()); + } + } +} + +/// Scale the box along its own axes about the reference point. +pub(super) fn scale_about_pivot(app: &mut PhotocraftApp, kx: f64, ky: f64) { + let Some(s) = app.ui.transform.as_mut() else { return }; + let Some(h) = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], s.quad) else { return }; + let Some(inv) = h.inverse() else { return }; + let (pu, pv) = inv.apply(s.pivot[0], s.pivot[1]); + let m = |u: f64, v: f64| { + let (x, y) = h.apply(pu + (u - pu) * kx, pv + (v - pv) * ky); + [x, y] + }; + s.quad = [m(0.0, 0.0), m(1.0, 0.0), m(1.0, 1.0), m(0.0, 1.0)]; +} + +pub(super) fn rotate_about_pivot(app: &mut PhotocraftApp, da: f64) { + let Some(s) = app.ui.transform.as_mut() else { return }; + let (sn, cs) = da.sin_cos(); + let c = s.pivot; + s.quad = s.quad.map(|q| { + let (x, y) = (q[0] - c[0], q[1] - c[1]); + [c[0] + x * cs - y * sn, c[1] + x * sn + y * cs] + }); +} diff --git a/crates/ui-egui/src/transform_tool/pointer.rs b/crates/ui-egui/src/transform_tool/pointer.rs new file mode 100644 index 0000000000..7df9bfa6f1 --- /dev/null +++ b/crates/ui-egui/src/transform_tool/pointer.rs @@ -0,0 +1,304 @@ +use super::begin::warps_type; +use super::commit::{commit, committing, moves_type}; +use super::drag_modes::{apply_drag, apply_mode_drag, drag_mods, mode_allows, mode_mods}; +use super::warp::{quick_split_kind, split_cursor, surface_at, warp_hit, warp_pointer}; +use super::*; + +/// Which part of the box a document point hits. +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub(crate) enum Hit { + Corner(usize), + Edge(usize), + Pivot, + Inside, + Outside, +} + +/// The nearest handle within `tol` (on a small box their grab areas overlap), else inside or +/// outside the box. +pub(crate) fn hit(t: &TransformSession, p: [f64; 2], tol: f64) -> Hit { + let d = |a: [f64; 2]| ((a[0] - p[0]).powi(2) + (a[1] - p[1]).powi(2)).sqrt(); + let mid = |i: usize| { + let (a, b) = (t.quad[i], t.quad[(i + 1) % 4]); + [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0] + }; + let handles = (0..4).map(|i| (t.quad[i], Hit::Corner(i))).chain((0..4).map(|i| (mid(i), Hit::Edge(i)))).chain([(t.pivot, Hit::Pivot)]); + let nearest = handles.map(|(q, h)| (d(q), h)).filter(|(dist, _)| *dist < tol).min_by(|a, b| a.0.total_cmp(&b.0)); + match nearest { + Some((_, h)) => h, + None if inside(&t.quad, p) => Hit::Inside, + None => Hit::Outside, + } +} + +fn inside(q: &[[f64; 2]; 4], p: [f64; 2]) -> bool { + let mut c = false; + for i in 0..4 { + let (a, b) = (q[i], q[(i + 3) % 4]); + if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0] { + c = !c; + } + } + c +} + +/// Transient drag state (kept in egui memory; not part of the serialised session). +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub(crate) struct Gesture { + pub(crate) hit: Hit, + pub(crate) start: [f64; 2], + pub(crate) quad0: [[f64; 2]; 4], + pub(crate) pivot0: [f64; 2], +} + +/// A click outside the box accepts the transform; a drag outside still rotates it. +/// Decide on release, so the rotation zone keeps working for drags. The screen-sized +/// click tolerance absorbs pointer jitter without accepting a real rotation gesture. +pub(super) fn accepts_outside_click(g: Gesture, end: [f64; 2], tol: f64) -> bool { + g.hit == Hit::Outside && (end[0] - g.start[0]).hypot(end[1] - g.start[1]) <= 2.0 * tol / HANDLE_PX +} + +/// Pointer input while transforming. Returns false when no transform is active. +pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { + let Some(t) = app.ui.transform.clone() else { return false }; + if committing(app).is_some() { + return true; + } + let tol = handle_tolerance(app); + if t.warp.is_some() { + warp_pointer(app, ev, tol, mods); + return true; + } + let Some(pv) = app.transform_preview.as_mut() else { return false }; + match ev { + ToolEvent::Down { x, y, .. } => { + let mut h = hit(&t, [x, y], tol); + // ⌥-click away from the handles moves the reference point there (and drags it). + if mods.alt + && matches!(h, Hit::Inside | Hit::Outside) + && let Some(s) = app.ui.transform.as_mut() + { + s.pivot = [x, y]; + h = Hit::Pivot; + } + // Distort only moves corners (and the whole box from inside): no rotating, no edges. + // Even in Distort mode, remember an outside press so a plain click can + // accept the transform. A drag outside remains inert in that mode, in Skew, and in + // Content-Aware Scale, which only scales and moves. + pv.gesture = (mode_allows(t.mode, h) || h == Hit::Outside).then_some(Gesture { hit: h, start: [x, y], quad0: t.quad, pivot0: t.pivot }); + } + ToolEvent::Move { x, y, .. } | ToolEvent::Up { x, y } => { + let g = pv.gesture; + if matches!(ev, ToolEvent::Up { .. }) { + pv.gesture = None; + } + // Clicking an empty spot commits instead of silently arming rotation (#2851). + // Dragging the rotation zone and Option-clicking to move the pivot + // keep their existing behavior. + if matches!(ev, ToolEvent::Up { .. }) && g.is_some_and(|g| accepts_outside_click(g, [x, y], tol)) { + commit(app); + return true; + } + let type_layer = moves_type(app, &t); + let adjusted = g.map(|g| drag_mods(app, &t, g.hit, mods)); + if let (Some(g), Some((mode, mods)), Some(s)) = (g, adjusted, app.ui.transform.as_mut()) + && mode_allows(t.mode, g.hit) + && (t.content_aware.is_none() || g.hit != Hit::Outside) + { + if t.content_aware.is_some() { + let mut mods = mode_mods(mode, g.hit, mods); + // Content-Aware Scale: ⌘ neither skews nor distorts. + mods.command = false; + apply_drag(s, g, [x, y], mods); + } else { + apply_mode_drag(s, g, [x, y], mode, type_layer, mods); + } + round_to_pixel_grid(app); + } + } + } + crate::snap_ui::retain_transform_lines(app, mods); + true +} + +/// Preferences › Tools › Snap Vector Tools and Transforms to Pixel Grid (#5751): while a shape +/// layer or a path is moved or scaled (the box still an upright rectangle), its edges stay on +/// whole pixels, whatever the tool. Rounding the pointer alone left the edges off by the grab +/// offset, and a proportional scale off by its ratio: a shape dragged to 540 px came out 539.6. +/// Rotated, skewed and distorted boxes are left as dragged. +fn round_to_pixel_grid(app: &mut PhotocraftApp) { + if !app.session.prefs().tools.snap_vector_tools_and_transforms_to_pixel_grid { + return; + } + let Some(t) = app.ui.transform.as_ref() else { return }; + if t.selection || t.warp.is_some() || t.content_aware.is_some() || t.target.is_some() { + return; + } + let vector = + t.path.is_some() || app.session.active().and_then(|st| st.doc.layer(LayerId(t.layer))).is_some_and(|l| matches!(l.content, LayerContent::Shape(_))); + if !vector || !upright(&t.quad) { + return; + } + let q = t.quad.map(|p| p.map(f64::round)); + // A box narrower than a pixel keeps its size rather than collapsing. + if (q[1][0] - q[0][0]).abs() < 1.0 || (q[3][1] - q[0][1]).abs() < 1.0 || q.iter().flatten().any(|v| !v.is_finite()) { + return; + } + if let Some(s) = app.ui.transform.as_mut() { + s.quad = q; + } +} + +/// Whether corners clockwise from top-left form an axis-aligned rectangle (flips included). +fn upright(q: &[[f64; 2]; 4]) -> bool { + let near = |a: f64, b: f64| (a - b).abs() < 1e-6; + near(q[0][1], q[1][1]) && near(q[2][1], q[3][1]) && near(q[0][0], q[3][0]) && near(q[1][0], q[2][0]) +} + +fn anchor_uv(anchor: usize) -> (f64, f64) { + match anchor { + 0 => (0.0, 0.0), + 1 => (0.5, 0.0), + 2 => (1.0, 0.0), + 3 => (0.0, 0.5), + 4 => (0.5, 0.5), + 5 => (1.0, 0.5), + 6 => (0.0, 1.0), + 7 => (0.5, 1.0), + 8 => (1.0, 1.0), + _ => (0.5, 0.5), + } +} + +pub(super) fn point_on_quad(quad: [[f64; 2]; 4], anchor: usize) -> [f64; 2] { + let (u, v) = anchor_uv(anchor); + if let Some(h) = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], quad) { + let (x, y) = h.apply(u, v); + if x.is_finite() && y.is_finite() { + return [x, y]; + } + } + match anchor { + 0 => quad[0], + 1 => [(quad[0][0] + quad[1][0]) / 2.0, (quad[0][1] + quad[1][1]) / 2.0], + 2 => quad[1], + 3 => [(quad[0][0] + quad[3][0]) / 2.0, (quad[0][1] + quad[3][1]) / 2.0], + 4 => [(quad[0][0] + quad[1][0] + quad[2][0] + quad[3][0]) / 4.0, (quad[0][1] + quad[1][1] + quad[2][1] + quad[3][1]) / 4.0], + 5 => [(quad[1][0] + quad[2][0]) / 2.0, (quad[1][1] + quad[2][1]) / 2.0], + 6 => quad[3], + 7 => [(quad[2][0] + quad[3][0]) / 2.0, (quad[2][1] + quad[3][1]) / 2.0], + 8 => quad[2], + _ => [(quad[0][0] + quad[1][0] + quad[2][0] + quad[3][0]) / 4.0, (quad[0][1] + quad[1][1] + quad[2][1] + quad[3][1]) / 4.0], + } +} + +/// Where the reference point lands when the box goes from `quad0` to `quad`: the same place +/// within the box, as in Photoshop, where it is attached to the bounding box (#1329). A box +/// that has collapsed leaves it where it was. +pub(super) fn carry_pivot(quad0: [[f64; 2]; 4], quad: [[f64; 2]; 4], pivot0: [f64; 2]) -> [f64; 2] { + let unit = [0.0, 0.0, 1.0, 1.0]; + let (Some(h0), Some(h1)) = (Homography::rect_to_quad(unit, quad0), Homography::rect_to_quad(unit, quad)) else { return pivot0 }; + let Some(inv) = h0.inverse() else { return pivot0 }; + let (u, v) = inv.apply(pivot0[0], pivot0[1]); + let (x, y) = h1.apply(u, v); + if x.is_finite() && y.is_finite() { [x, y] } else { pivot0 } +} + +/// True just outside a corner: rotate handle feedback lives here, not over the entire +/// empty canvas. The actual rotation gesture continues to work farther away. +pub(super) fn near_rotate_corner(t: &TransformSession, p: [f64; 2], tol: f64) -> bool { + t.warp.is_none() + && t.mode != TransformMode::Distort + && { + let h = hit(t, p, tol); + h == Hit::Outside || (t.mode == TransformMode::Rotate && matches!(h, Hit::Corner(_) | Hit::Edge(_))) + } + && t.quad.iter().any(|q| (p[0] - q[0]).hypot(p[1] - q[1]) <= tol * 3.0) +} + +/// Clockwise degrees in canvas coordinates (positive Y points down). +pub(super) fn rotation_degrees(quad: [[f64; 2]; 4]) -> f64 { + let dx = quad[1][0] - quad[0][0]; + let dy = quad[1][1] - quad[0][1]; + if dx.is_finite() && dy.is_finite() && dx.hypot(dy) > 1e-9 { dy.atan2(dx).to_degrees() } else { 0.0 } +} + +/// Where the rotate cursor's arc bends at document point `p`, or `None` outside the rotate zone: +/// just outside a corner, or anywhere while a rotate drag is on. It points into the box along the +/// bisector of the nearest corner, so each corner gets its own arrow and they turn with the box. +pub(crate) fn rotate_cursor_dir(app: &PhotocraftApp, p: [f64; 2]) -> Option<[f64; 2]> { + rotate_dir(app.ui.transform.as_ref()?, app.transform_preview.as_ref(), p, handle_tolerance(app)) +} + +pub(super) fn rotate_dir(t: &TransformSession, pv: Option<&TransformPreview>, p: [f64; 2], tol: f64) -> Option<[f64; 2]> { + // Content-Aware Scale's box only scales, and Skew doesn't rotate: no rotate arrow. + if !(p[0].is_finite() && p[1].is_finite()) + || t.warp.is_some() + || t.content_aware.is_some() + || matches!(t.mode, TransformMode::Distort | TransformMode::Skew) + { + return None; + } + let rotating = pv.is_some_and(|pv| pv.gesture.is_some_and(|g| g.hit == Hit::Outside)); + if !rotating && !near_rotate_corner(t, p, tol) { + return None; + } + let dist = |q: [f64; 2]| (p[0] - q[0]).hypot(p[1] - q[1]); + let i = (0..4).min_by(|&a, &b| dist(t.quad[a]).total_cmp(&dist(t.quad[b])))?; + let unit = |to: [f64; 2]| { + let d = [to[0] - t.quad[i][0], to[1] - t.quad[i][1]]; + let l = d[0].hypot(d[1]); + (l.is_finite() && l > 1e-9).then(|| [d[0] / l, d[1] / l]) + }; + let (a, b) = (unit(t.quad[(i + 1) % 4])?, unit(t.quad[(i + 3) % 4])?); + let s = [a[0] + b[0], a[1] + b[1]]; + let l = s[0].hypot(s[1]); + (l.is_finite() && l > 1e-9).then(|| [s[0] / l, s[1] / l]) +} + +/// Cursor for hovering a document point while transforming. `xf` is the canvas's view; +/// `quick_split` is Ctrl or Option, which arms a quick split while a warp is active. +pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2], quick_split: bool) -> Option { + let t = app.ui.transform.as_ref()?; + let tol = handle_tolerance(app); + if let Some(w) = &t.warp { + if warps_type(app) { + return Some(CursorIcon::Default); + } + let armed = app.transform_preview.as_ref().and_then(|pv| pv.split_tool); + if armed.is_some() || quick_split { + // One search for the grid position under the pointer, for both the kind and the arrow. + let m = w.to_mesh(1, 1); + let at = m.param_at(p); + let tool = armed.unwrap_or_else(|| quick_split_kind(&m, w.bounds, at)); + return Some(split_cursor(&m, tool, at, xf)); + } + if w.style != WarpStyle::Custom || warp_hit(w, p, tol).is_some() { + return Some(CursorIcon::Crosshair); + } + return Some(if w.mesh.as_ref().and_then(|m| surface_at(m, p)).is_some() { CursorIcon::Grab } else { CursorIcon::Default }); + } + let h = hit(t, p, tol); + if !mode_allows(t.mode, h) || (t.content_aware.is_some() && h == Hit::Outside) { + return Some(CursorIcon::Default); + } + if rotate_cursor_dir(app, p).is_some() { + // The overlay draws the curved rotate arrow (`rotate_cursor_dir`), also during the drag. + return Some(CursorIcon::None); + } + // The box's corners run clockwise from the top-left; edge k joins corners k and k + 1. + let corner = |k: usize| t.quad[k % 4]; + let edge_mid = |k: usize| { + let (a, b) = (corner(k), corner(k + 1)); + [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0] + }; + // A handle resizes the box away from the opposite handle. + let resize = |from: [f64; 2], to: [f64; 2]| crate::tool_cursor::resize([to[0] - from[0], to[1] - from[1]], xf); + Some(match h { + Hit::Corner(i) => crate::tool_cursor::corner_resize(&t.quad, i, xf), + Hit::Edge(i) => resize(edge_mid(i + 2), edge_mid(i)), + Hit::Pivot => CursorIcon::Crosshair, + Hit::Inside => CursorIcon::Move, + Hit::Outside => CursorIcon::Alias, + }) +} diff --git a/crates/ui-egui/src/transform_tool/preview.rs b/crates/ui-egui/src/transform_tool/preview.rs new file mode 100644 index 0000000000..d39d6575f3 --- /dev/null +++ b/crates/ui-egui/src/transform_tool/preview.rs @@ -0,0 +1,255 @@ +use super::*; + +/// Texels of the moving pixels over `b`: full resolution unless the long side exceeds the GPU's +/// `max_side` (#91: this used to be capped at 2048 px, so big layers previewed blurry), plus the +/// uv extent covering `b`. `bare` leaves the layer's own style, opacity and fill out of a +/// flattened render: the styled preview applies them to the moved pixels itself. +pub(super) fn preview_image( + doc: &Document, + id: LayerId, + lifted: Option<&photocraft_raster::Surface>, + b: photocraft_geom::Rect, + max_side: usize, + bare: bool, +) -> (egui::ColorImage, [f32; 2]) { + let layer = doc.layer(id); + // Linked masks move with the pixels, so the moving texels carry them (#205). + let mask = layer.and_then(|l| preview_mask(l, b)); + // Groups and type/fill layers preview from a flattened render of just that layer. + let rendered; + let surf: Option<&photocraft_raster::Surface> = match (lifted, layer.and_then(|l| l.surface())) { + (Some(s), _) => Some(s), + (None, Some(s)) if layer.is_some_and(|l| matches!(l.content, LayerContent::Raster(_))) => Some(s), + _ => { + let mut solo = doc.clone(); + if layer.is_some() { + solo_layer(&mut solo.layers, id); + } else { + // Keep the previous fallback for an invalid id: render the document, with only + // top-level clipping disabled. Production callers get ids from this document. + for l in &mut solo.layers { + l.clipped = false; + } + } + if let Some(l) = solo.layer_mut(id).filter(|_| bare) { + l.effects.enabled = false; + l.opacity = 1.0; + l.fill_opacity = 1.0; + } + let buf = photocraft_compose::render(&solo, b); + let mut s = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); + let flat: Vec = buf.px.iter().flat_map(|p| *p).collect(); + s.write_region(b, &flat); + rendered = s; + Some(&rendered) + } + }; + let Some(surf) = surf else { return (egui::ColorImage::new([1, 1], vec![Color32::TRANSPARENT]), [1.0, 1.0]) }; + // A flattened render already has the masks applied. + let raw = lifted.is_some() || layer.is_some_and(|l| matches!(l.content, LayerContent::Raster(_))); + crate::transform_tex::read_surface(surf, mask.as_ref().filter(|_| raw), b, max_side) +} + +/// The layer's masks as the moving texels carry them: the enabled masks when all of them are linked +/// (the vector mask and feathering folded in as the compositor applies them), else the linked +/// pixel mask alone. `None` when no enabled mask moves with the pixels. +fn preview_mask(l: &photocraft_doc::Layer, b: photocraft_geom::Rect) -> Option { + use crate::transform_tex::PreviewMask; + let pixel = l.mask.as_ref().filter(|m| m.enabled); + let vector = l.vector_mask.as_ref().filter(|v| v.enabled); + let linked_pixel = pixel.filter(|m| m.linked); + if pixel.is_none_or(|m| m.linked) + && vector.is_none_or(|v| v.linked) + && let Some(surface) = photocraft_compose::masks::combined_mask(l, b) + { + return Some(PreviewMask { surface, density: 1.0 }); + } + linked_pixel.map(|m| PreviewMask { surface: m.surface.clone(), density: m.density }) +} + +/// The layers covering the moving one ([`covering`]), composited on their own and drawn over its +/// preview, so the layer keeps its place in the stack while the box is open (#2439): they cover +/// it, as in Photoshop, instead of the moving pixels covering the whole document. The canvas +/// under the box leaves them out ([`Above::hide_in`]). Built when the session starts and again +/// when an edit changes the document; the box itself moves without re-compositing. +pub(super) struct Above { + pub(super) ctx: egui::Context, + pub(super) name: String, + pub(super) max_side: usize, + /// The covering layers (whole layers or groups, at any depth). + pub(super) ids: 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(), shown: None }; + a.rebuild(doc, id); + a + } + + /// Composite what covers layer `id` of `doc` (the live document) again. + pub(super) fn rebuild(&mut self, doc: &Document, id: LayerId) { + self.ids.clear(); + covering(&doc.layers, id, &mut self.ids); + let mut up = doc.clone(); + show_only(&mut up.layers, &self.ids); + let canvas = up.bounds(); + let rect = up + .layers + .iter() + .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) + }); + } + + /// 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); + } + } + } + + /// Draw the composite over the moving pixels. + pub(super) fn draw(&self, painter: &egui::Painter, xf: &ViewXform, display: Option<&photocraft_engine::display_color::CanvasDisplay>) { + let Some((texture, r)) = &self.shown else { return }; + let (tex, uv) = texture.pick_display(painter.ctx(), xf.zoom * painter.ctx().pixels_per_point(), 1.0, false, display); + let mut mesh = egui::Mesh::with_texture(tex); + let corners = [(r.x0, r.y0, 0.0, 0.0), (r.x1, r.y0, uv[0], 0.0), (r.x1, r.y1, uv[0], uv[1]), (r.x0, r.y1, 0.0, uv[1])]; + for (x, y, u, v) in corners { + mesh.vertices.push(egui::epaint::Vertex { pos: xf.to_screen(x as f32, y as f32), uv: pos2(u, v), color: Color32::WHITE }); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(mesh); + } +} + +/// `rect` of `doc`'s composite as premultiplied texels: full resolution when it fits in +/// `max_side`, composited in bands (no full-size float copy), else area-averaged down to fit. +fn composite_image(doc: &Document, rect: photocraft_geom::Rect, max_side: usize) -> (egui::ColorImage, [f32; 2]) { + let (w, h) = (rect.width() as usize, rect.height() as usize); + let to_color = |p: &[u8; 4]| Color32::from_rgba_unmultiplied(p[0], p[1], p[2], p[3]); + if w.max(h) <= max_side.max(1) { + let mut px = Vec::with_capacity(w * h); + let _ = photocraft_compose::render_bands(doc, rect, 0, |band| { + px.extend(band.to_rgba8().pixels.as_chunks::<4>().0.iter().map(to_color)); + Ok::<(), ()>(()) + }); + px.resize(w * h, Color32::TRANSPARENT); + return (egui::ColorImage::new([w, h], px), [1.0, 1.0]); + } + let k = w.max(h).div_ceil(max_side.max(1)); + let (tw, th) = (w.div_ceil(k).max(1), h.div_ceil(k).max(1)); + let buf = photocraft_compose::render_reduced_rect(doc, rect, tw as u32, th as u32); + let px: Vec = buf.to_rgba8().pixels.as_chunks::<4>().0.iter().map(to_color).collect(); + let [bw, bh] = [buf.rect.width() as usize, buf.rect.height() as usize]; + if px.len() != bw * bh || bw == 0 || bh == 0 { + return (egui::ColorImage::new([1, 1], vec![Color32::TRANSPARENT]), [1.0, 1.0]); + } + (egui::ColorImage::new([bw, bh], px), [1.0, 1.0]) +} + +/// A layer that composites over anything the same as over transparency, so it can be drawn over +/// the moving pixels on its own: a Normal layer that isn't an adjustment, or a Normal or Pass +/// Through group of such layers (hidden layers count, they draw nothing). Adjustment layers and +/// the other blend modes depend on what is under them. +fn plain(l: &photocraft_doc::Layer) -> bool { + use photocraft_color::BlendMode; + !l.visible + || match &l.content { + LayerContent::Adjustment(_) => false, + LayerContent::Group(g) => matches!(l.blend, BlendMode::Normal | BlendMode::PassThrough) && g.children.iter().all(plain), + _ => l.blend == BlendMode::Normal, + } +} + +/// The layers over `id` in `layers` (bottom to top, groups holding `id` searched too) that cover +/// it in the preview: from the top down, while they are [`plain`]. The first layer that isn't +/// stops the search, so it and everything under it stay in the document under the box as before +/// (an adjustment there keeps applying to the layers under it). A clipping group goes as a whole, +/// and the layers clipped to `id` (or to the group holding it) stay with it. +pub(super) fn covering(layers: &[photocraft_doc::Layer], id: LayerId, out: &mut Vec) { + let mut end = layers.len(); + while end > 0 { + // The clipping group ending at `end`: its base and the layers clipped to it. + let mut start = end - 1; + while start > 0 && layers.get(start).is_some_and(|l| l.clipped) { + start -= 1; + } + let unit = layers.get(start..end).unwrap_or_default(); + if unit.iter().any(|l| contains(l, id)) { + // A group holding `id` with nothing clipped to it: go on inside it. + if let [g] = unit + && g.id != id + && let LayerContent::Group(group) = &g.content + && matches!(g.blend, photocraft_color::BlendMode::Normal | photocraft_color::BlendMode::PassThrough) + { + covering(&group.children, id, out); + } + return; + } + if !unit.iter().all(plain) { + return; + } + out.extend(unit.iter().map(|l| l.id)); + end = start; + } +} + +/// Hide everything in `layers` but the `keep` layers and the groups holding them. +pub(super) fn show_only(layers: &mut [photocraft_doc::Layer], keep: &[LayerId]) { + for l in layers.iter_mut() { + if keep.contains(&l.id) { + continue; + } + match &mut l.content { + LayerContent::Group(g) if g.children.iter().any(|c| keep.iter().any(|k| contains(c, *k))) => { + // This ancestor only clips the covering children. Its background is already + // on the base canvas; drawing it again would cover the moving layer in white. + if let Some(board) = &mut g.artboard { + board.background = photocraft_doc::ArtboardBackground::Transparent; + } + show_only(&mut g.children, keep); + } + _ => l.visible = false, + } + } +} + +/// Leave only `id`, its descendants and the groups holding it visible. Every layer on that path +/// is detached from its clipping base because the base is hidden in this isolated render (#5239). +/// Hide every layer but `id` and the groups holding it, and unclip those, so a render shows that +/// layer alone (the Free Transform preview, Liquify's one-layer backdrop). +pub(crate) fn solo_layer(layers: &mut [photocraft_doc::Layer], id: LayerId) { + for l in layers { + if l.id == id { + l.clipped = false; + continue; + } + match &mut l.content { + LayerContent::Group(g) if g.children.iter().any(|c| contains(c, id)) => { + l.clipped = false; + // Isolate the child, not the artboard's paper. Keep the board for clipping. + if let Some(board) = &mut g.artboard { + board.background = photocraft_doc::ArtboardBackground::Transparent; + } + solo_layer(&mut g.children, id); + } + _ => l.visible = false, + } + } +} + +fn contains(l: &photocraft_doc::Layer, id: LayerId) -> bool { + l.id == id || matches!(&l.content, LayerContent::Group(g) if g.children.iter().any(|c| contains(c, id))) +} diff --git a/crates/ui-egui/src/transform_tool/tests.rs b/crates/ui-egui/src/transform_tool/tests.rs index d4f2de642a..57d323b84a 100644 --- a/crates/ui-egui/src/transform_tool/tests.rs +++ b/crates/ui-egui/src/transform_tool/tests.rs @@ -612,12 +612,8 @@ fn clicking_another_layer_row_applies_the_transform() { t.quad = t.quad.map(|[x, y]| [x + 8.0, y]); h.state_mut().background_jobs = true; h.run_steps(2); - let row = h - .query_all_by_label("Background") - .find(|n| n.accesskit_node().role() == egui::accesskit::Role::Button) - .expect("the Background row") - .rect() - .center(); + let row = + h.query_all_by_label("Background").find(|n| n.accesskit_node().role() == egui::accesskit::Role::Button).expect("the Background row").rect().center(); h.hover_at(row); h.run_steps(1); h.drag_at(row); @@ -2013,11 +2009,7 @@ fn nested_group_preview_excludes_its_siblings() { doc.layers.push(Layer::group("parent", vec![target, sibling])); let (image, _) = preview_image(&st.doc, target_id, None, photocraft_geom::Rect::new(8, 8, 24, 24), 4096, false); - assert_eq!( - image.pixels[8 * image.size[0] + 8], - Color32::from_rgb(255, 0, 0), - "a sibling in the parent group must not be baked into the moving texture" - ); + assert_eq!(image.pixels[8 * image.size[0] + 8], Color32::from_rgb(255, 0, 0), "a sibling in the parent group must not be baked into the moving texture"); } fn artboard_preview_app(background: photocraft_doc::ArtboardBackground) -> (PhotocraftApp, LayerId, LayerId) { @@ -2152,14 +2144,8 @@ fn preview_pixels_past_the_canvas_are_hidden() { assert!(q[0][0] < -10.0 && q[2][1] > 74.0, "the box reaches past the canvas: {q:?}"); let tol = 1e-3; for (rotation, flip) in [(0.0, false), (30.0, false), (-75.0, true)] { - let xf = ViewXform { - rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0)), - zoom: 2.0, - center: [32.0, 32.0], - flip, - rotation, - aspect: 1.0, - }; + let xf = + ViewXform { rect: egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0)), zoom: 2.0, center: [32.0, 32.0], flip, rotation, aspect: 1.0 }; let meshes = preview_meshes(&app, &xf); let verts: Vec<[f64; 2]> = meshes.iter().flat_map(|m| m.vertices.iter().map(|v| xf.to_doc(v.pos))).collect(); assert!(!verts.is_empty(), "the preview still draws (rotation {rotation})"); diff --git a/crates/ui-egui/src/transform_tool/warp.rs b/crates/ui-egui/src/transform_tool/warp.rs new file mode 100644 index 0000000000..90b372a36f --- /dev/null +++ b/crates/ui-egui/src/transform_tool/warp.rs @@ -0,0 +1,186 @@ +use super::begin::warps_type; +use super::*; + +/// An anchor or a handle on a section line. The inner control points of a patch are not shown. +pub(super) fn on_section_edge(i: usize, j: usize) -> bool { + i.is_multiple_of(3) || j.is_multiple_of(3) +} + +/// Index of the warp control point within `tol` of `p` (nearest anchor or handle). +pub(super) fn warp_hit(w: &Warp, p: [f64; 2], tol: f64) -> Option { + let m = w.mesh.as_ref()?; + let nx = m.nx(); + m.points + .iter() + .enumerate() + .filter(|(i, _)| on_section_edge(i % nx, i / nx)) + .map(|(i, q)| (i, ((q[0] - p[0]).powi(2) + (q[1] - p[1]).powi(2)).sqrt())) + .filter(|(_, d)| *d < tol) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(i, _)| i) +} + +/// A 1×1 mesh (Grid › Default) draws rule-of-thirds guides. Denser presets are real patch +/// boundaries only — a 3×3 is three cells, not a third-line lattice inside every cell. +pub(super) fn single_patch(mesh: &BezierMesh) -> bool { + mesh.us.len() == 2 && mesh.vs.len() == 2 +} + +/// The surface parameters under `p` when it is inside the warped mesh, else None. +pub(super) fn surface_at(mesh: &BezierMesh, p: [f64; 2]) -> Option<(f64, f64)> { + let (s, t) = mesh.param_at(p); + let q = mesh.eval(s, t); + ((q[0] - p[0]).hypot(q[1] - p[1]) < 1.0).then_some((s, t)) +} + +/// Ctrl-click (or Option-click) picks the split: crosswise in the open, and the perpendicular +/// split when the pointer's grid position `(s, t)` is close to an existing grid line. +pub(super) fn quick_split_kind(mesh: &BezierMesh, bounds: [f64; 4], (s, t): (f64, f64)) -> SplitTool { + let w = (bounds[2] - bounds[0]).abs().max(1.0); + let h = (bounds[3] - bounds[1]).abs().max(1.0); + let su = (8.0 / w).clamp(0.02, 0.12); + let sv = (8.0 / h).clamp(0.02, 0.12); + let thirds = single_patch(mesh); + let near = |knots: &[f64], v: f64, tol: f64| { + knots.iter().any(|k| *k > 0.0 && *k < 1.0 && (k - v).abs() < tol) || (thirds && [1.0 / 3.0, 2.0 / 3.0].iter().any(|k| (k - v).abs() < tol)) + }; + match (near(&mesh.us, s, su), near(&mesh.vs, t, sv)) { + (true, false) => SplitTool::Horizontal, + (false, true) => SplitTool::Vertical, + _ => SplitTool::Cross, + } +} + +/// The cursor for a split armed at grid position `(s, t)` of warp grid `m`: the arrow across the +/// split line as it looks on screen. A vertical split line runs along the grid's columns and is +/// placed by moving across them, in the grid's own direction there, so the arrow turns with a +/// turned or bent grid and with the view. +pub(super) fn split_cursor(m: &BezierMesh, tool: SplitTool, (s, t): (f64, f64), xf: &ViewXform) -> CursorIcon { + let e = 1e-3; + let (a, b) = match tool { + SplitTool::Vertical => (m.eval((s - e).max(0.0), t), m.eval((s + e).min(1.0), t)), + SplitTool::Horizontal => (m.eval(s, (t - e).max(0.0)), m.eval(s, (t + e).min(1.0))), + SplitTool::Cross => return CursorIcon::Crosshair, + }; + crate::tool_cursor::resize([b[0] - a[0], b[1] - a[1]], xf) +} + +/// Armed split tool, or Option held: the guide tracks the pointer and the split lands on release. +/// Returns false when this event is an ordinary control-point drag. +fn split_gesture(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { + let armed = app.transform_preview.as_ref().and_then(|p| p.split_tool); + let placing = app.transform_preview.as_ref().is_some_and(|p| p.split_placing); + match ev { + ToolEvent::Down { x, y, .. } if armed.is_some() || mods.alt || mods.command => { + if let Some(pv) = app.transform_preview.as_mut() { + pv.split_placing = true; + pv.split_pointer = Some([x, y]); + pv.split_quick = armed.is_none(); + } + true + } + ToolEvent::Move { x, y, .. } if placing => { + if let Some(pv) = app.transform_preview.as_mut() { + pv.split_pointer = Some([x, y]); + } + true + } + ToolEvent::Up { x, y } if placing => { + let quick = app.transform_preview.as_ref().is_some_and(|p| p.split_quick); + if let Some(pv) = app.transform_preview.as_mut() { + pv.split_placing = false; + pv.split_pointer = None; + pv.split_quick = false; + } + let kind = if let Some(tool) = armed { + Some(tool) + } else if quick { + app.ui.transform.as_ref().and_then(|t| t.warp.as_ref()).map(|w| { + let m = w.to_mesh(1, 1); + quick_split_kind(&m, w.bounds, m.param_at([x, y])) + }) + } else { + None + }; + if let Some(kind) = kind { + // On an existing line, or a click the drag path also delivers, this is a no-op. + let _ = split(app, kind.command(), Some([x, y])); + } + true + } + _ => false, + } +} + +/// Drags the warp grid. A press on an anchor or handle moves that point (an anchor carries its +/// handles along); a press anywhere else inside the grid pulls the surface under the pointer. +/// Preset warps turn into a custom mesh when the press grabs something. An armed split tool, or +/// Ctrl / Option held, places a split where the pointer is released instead. +pub(super) fn warp_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tol: f64, mods: egui::Modifiers) { + // Type takes only the warp styles: nothing on the canvas to drag or split (#3004). + if warps_type(app) { + return; + } + if split_gesture(app, ev, mods) { + return; + } + 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, .. } => { + // A preset warp becomes a custom mesh only when the press grabs one of its points. + let custom = if w.mesh.is_none() || w.style != WarpStyle::Custom { Warp::custom(w.to_mesh(1, 1), w.bounds) } else { w.clone() }; + let pts0 = custom.mesh.as_ref().map(|m| m.points.clone()).unwrap_or_default(); + pv.warp_drag = warp_hit(&custom, [x, y], tol).map(|index| WarpDrag::Point { index, start: [x, y], pts0: pts0.clone() }).or_else(|| { + let (s, t) = surface_at(custom.mesh.as_ref()?, [x, y])?; + Some(WarpDrag::Surface { s, t, start: [x, y], pts0 }) + }); + if pv.warp_drag.is_some() { + *w = custom; + } + } + ToolEvent::Move { x, y, .. } | ToolEvent::Up { x, y } => { + match (&pv.warp_drag, w.mesh.as_mut()) { + (Some(WarpDrag::Point { index, start, pts0 }), Some(m)) => m.drag_point(pts0, *index, [x - start[0], y - start[1]]), + (Some(WarpDrag::Surface { s, t, start, pts0 }), Some(m)) => m.pull(pts0, *s, *t, [x - start[0], y - start[1]]), + _ => {} + } + if matches!(ev, ToolEvent::Up { .. }) { + pv.warp_drag = None; + } + } + } +} + +/// Runs a warp-edit command against the mesh in the open Warp session and writes the mesh back. +pub fn edit_session_warp(app: &mut PhotocraftApp, id: &str, params: &serde_json::Value) -> Result<(), String> { + let Some(w) = app.ui.transform.as_ref().and_then(|t| t.warp.clone()) else { return Err("not warping".into()) }; + if warps_type(app) { + return Err("Warp on type takes only the warp styles".into()); + } + let mut p = if params.is_object() { params.clone() } else { json!({}) }; + if p.get("warp").is_none() { + p["warp"] = serde_json::to_value(&w).map_err(|e| e.to_string())?; + } + let r = app.session.execute(id, p).map_err(|e| e.to_string())?; + let raw = r.get("warp").cloned().ok_or_else(|| "warp command returned no mesh".to_string())?; + let nw: Warp = serde_json::from_value(raw).map_err(|e| e.to_string())?; + // A warp-edit command can replace the mesh while pointer input is split across control + // requests. Any drag index captured from the old mesh is invalid once that happens. + if let Some(pv) = app.transform_preview.as_mut() { + pv.warp_drag = None; + } + if let Some(t) = app.ui.transform.as_mut() { + t.warp = Some(nw); + } + Ok(()) +} + +/// Applies a split-warp command to the mesh being edited (at the box centre unless `at`). +pub fn split(app: &mut PhotocraftApp, id: &str, at: Option<[f64; 2]>) -> Result<(), String> { + let mut p = json!({}); + if let Some(a) = at { + p["at"] = json!(a); + } + edit_session_warp(app, id, &p) +} From 093c008d687d3ecad08b5983f305f2c8f9804853 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:04:39 +0000 Subject: [PATCH 226/259] refactor(ui-egui): split prefs_ui.rs into prefs_ui/ --- crates/ui-egui/src/prefs_ui.rs | 2705 +-------------------- crates/ui-egui/src/prefs_ui/appearance.rs | 330 +++ crates/ui-egui/src/prefs_ui/dialogs.rs | 431 ++++ crates/ui-egui/src/prefs_ui/fields.rs | 508 ++++ crates/ui-egui/src/prefs_ui/graphics.rs | 141 ++ crates/ui-egui/src/prefs_ui/save.rs | 342 +++ crates/ui-egui/src/prefs_ui/shortcuts.rs | 698 ++++++ crates/ui-egui/src/prefs_ui/startup.rs | 243 ++ 8 files changed, 2727 insertions(+), 2671 deletions(-) create mode 100644 crates/ui-egui/src/prefs_ui/appearance.rs create mode 100644 crates/ui-egui/src/prefs_ui/dialogs.rs create mode 100644 crates/ui-egui/src/prefs_ui/fields.rs create mode 100644 crates/ui-egui/src/prefs_ui/graphics.rs create mode 100644 crates/ui-egui/src/prefs_ui/save.rs create mode 100644 crates/ui-egui/src/prefs_ui/shortcuts.rs create mode 100644 crates/ui-egui/src/prefs_ui/startup.rs diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index f5a37134dc..e37efea17f 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -57,2681 +57,44 @@ pub struct Runtime { pub(crate) tool_brushes: Option, } -/// The GPU canvas colours from Preferences › Transparency & Gamut. -pub fn canvas_style(app: &PhotocraftApp) -> crate::gpu_canvas::CanvasStyle { - let t = &app.session.prefs().transparency_and_gamut; - let [l, d] = t.colors(); - let f = |c: [u8; 3]| c.map(|v| v as f32 / 255.0); - let g = prefs::parse_hex(&t.gamut_warning_color).unwrap_or([128; 3]); - crate::gpu_canvas::CanvasStyle { - checker_square: t.square().unwrap_or(0.0), - checker_light: f(l), - checker_dark: f(d), - gamut_color: f(g), - gamut_opacity: t.gamut_warning_opacity as f32 / 100.0, - } -} - -/// Pasteboard colour from Preferences › Interface (`None` = the theme's default canvas). -pub fn pasteboard_color(app: &PhotocraftApp) -> Option { - use prefs::CanvasColor; - let i = &app.session.prefs().interface; - Some(match i.canvas_color { - CanvasColor::Default => return None, - CanvasColor::Black => Color32::BLACK, - CanvasColor::DarkGray => Color32::from_gray(40), - CanvasColor::MediumGray => Color32::from_gray(83), - CanvasColor::LightGray => Color32::from_gray(184), - CanvasColor::Custom => color_of(&i.canvas_custom_color), - }) -} - -fn selected_theme(interface: &prefs::Interface, system: Option) -> ThemeKind { - let light = match interface.appearance_mode { - AppearanceMode::Light => true, - AppearanceMode::Dark => false, - AppearanceMode::Auto => system == Some(egui::Theme::Light), - }; - if light { - match interface.light_theme { - LightTheme::StudioLight => ThemeKind::StudioLight, - LightTheme::ProLightGray => ThemeKind::ProLightGray, - LightTheme::ProLight => ThemeKind::ProLight, - LightTheme::Classic => ThemeKind::Classic, - LightTheme::Adwaita => ThemeKind::Adwaita, - LightTheme::BreezeLight => ThemeKind::BreezeLight, - LightTheme::SoftLight => ThemeKind::SoftLight, - } - } else { - match interface.dark_theme { - DarkTheme::Pro => ThemeKind::Pro, - DarkTheme::ProMedium => ThemeKind::ProMedium, - DarkTheme::Studio => ThemeKind::Studio, - DarkTheme::SolarizedDark => ThemeKind::SolarizedDark, - DarkTheme::AdwaitaDark => ThemeKind::AdwaitaDark, - DarkTheme::BreezeDark => ThemeKind::BreezeDark, - DarkTheme::SoftDark => ThemeKind::SoftDark, - } - } -} - -pub(crate) fn cycle_appearance(app: &mut PhotocraftApp, ctx: &egui::Context) { - let next = match app.session.prefs().interface.appearance_mode { - AppearanceMode::Auto => AppearanceMode::Light, - AppearanceMode::Light => AppearanceMode::Dark, - AppearanceMode::Dark => AppearanceMode::Auto, - }; - if let Err(e) = app.run("prefs.set", json!({"path": "interface.appearanceMode", "value": next.name()})) { - app.ui.status = e; - return; - } - let selected = selected_theme(&app.session.prefs().interface, system_theme(app, ctx)); - if app.ui.theme != selected { - app.apply_theme(ctx, selected); - } -} - -/// Photoshop's four interface brightnesses, darkest first. -const BRIGHTNESSES: [ThemeKind; 4] = [ThemeKind::Pro, ThemeKind::ProMedium, ThemeKind::ProLightGray, ThemeKind::ProLight]; - -/// Darken Interface (⇧⌘F1, `lighter` false) and Lighten Interface (⇧⌘F2): the next of -/// Photoshop's four brightnesses from the theme on screen, stopping at either end, as in -/// Photoshop. Another theme steps from the nearest brightness: Medium Gray for a dark one, Light -/// Gray for a light one. The choice is saved like picking it in Preferences › Interface. -pub(crate) fn step_brightness(app: &mut PhotocraftApp, ctx: &egui::Context, lighter: bool) -> Result<(), String> { - let current = app.ui.theme; - let at = BRIGHTNESSES.iter().position(|k| *k == current).unwrap_or(if crate::theme::Tokens::for_kind(current).dark() { 1 } else { 2 }); - let next = if lighter { (at + 1).min(BRIGHTNESSES.len() - 1) } else { at.saturating_sub(1) }; - let Some(&kind) = BRIGHTNESSES.get(next) else { return Ok(()) }; - if kind == current { - return Ok(()); - } - app.run("prefs.set", json!({"path": "interface.theme", "value": kind.id()}))?; - sync_appearance(app, ctx); - Ok(()) -} - -const LIGHT_THEME_OPTIONS: &[(&str, ThemeKind)] = &[ - ("proLight", ThemeKind::ProLight), - ("proLightGray", ThemeKind::ProLightGray), - ("studioLight", ThemeKind::StudioLight), - ("classic", ThemeKind::Classic), - ("adwaita", ThemeKind::Adwaita), - ("breezeLight", ThemeKind::BreezeLight), - ("softLight", ThemeKind::SoftLight), -]; -const DARK_THEME_OPTIONS: &[(&str, ThemeKind)] = &[ - ("proMedium", ThemeKind::ProMedium), - ("pro", ThemeKind::Pro), - ("studio", ThemeKind::Studio), - ("solarizedDark", ThemeKind::SolarizedDark), - ("adwaitaDark", ThemeKind::AdwaitaDark), - ("breezeDark", ThemeKind::BreezeDark), - ("softDark", ThemeKind::SoftDark), -]; - -fn favorite_theme_groups(favorites: &[SavedTheme]) -> (Vec, Vec) { - let group = |options: &[(&str, ThemeKind)]| { - options.iter().filter_map(|(id, kind)| SavedTheme::parse(id).filter(|theme| favorites.contains(theme)).map(|_| *kind)).collect() - }; - (group(LIGHT_THEME_OPTIONS), group(DARK_THEME_OPTIONS)) -} - -/// Right-click menu on the top-right appearance button. A plain click still cycles modes. -pub(crate) fn appearance_context_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - if ui.button(tl!("Appearance Settings…")).clicked() { - open_preferences(app, "interface"); - ui.close(); - } - let (light, dark) = favorite_theme_groups(&app.session.prefs().interface.favorite_themes); - let has_light = !light.is_empty(); - if !light.is_empty() || !dark.is_empty() { - ui.separator(); - } - for kind in light { - if ui.selectable_label(app.ui.theme == kind, tl!(kind.label())).clicked() { - app.set_theme(ui.ctx(), kind); - ui.close(); - } - } - if has_light && !dark.is_empty() { - ui.separator(); - } - for kind in dark { - if ui.selectable_label(app.ui.theme == kind, tl!(kind.label())).clicked() { - app.set_theme(ui.ctx(), kind); - ui.close(); - } - } -} - -fn system_theme(app: &PhotocraftApp, ctx: &egui::Context) -> Option { - app.services.system_theme.as_ref().and_then(|read| read(ctx)).or_else(|| ctx.system_theme()) -} - -/// View › Rulers follows `unitsAndRulers.showRulers` when the preference changes (at launch, from -/// `prefs.set` or a reset), so documents open with the rulers as last set. -fn sync_rulers(app: &mut PhotocraftApp) { - let want = app.session.prefs().units_and_rulers.show_rulers; - if app.prefs_rt.show_rulers != Some(want) { - app.ui.extras.rulers = want; - app.prefs_rt.show_rulers = Some(want); - } -} - -/// View › Rulers was toggled: remember it for the next launch (Photoshop keeps the last state). -pub(crate) fn remember_rulers(app: &mut PhotocraftApp, on: bool) { - if app.session.prefs().units_and_rulers.show_rulers != on { - app.session.prefs.edit(|p| p.units_and_rulers.show_rulers = on); - } - app.prefs_rt.show_rulers = Some(on); -} - -// ------------------------------------------------------------------ lifecycle - -/// Load saved preferences once, when the app is created. Recovery starts during frame upkeep. -pub fn load(app: &mut PhotocraftApp) { - if app.prefs_rt.loaded { - return; - } - app.prefs_rt.loaded = true; - let mut invalid = Vec::new(); - let mut stored = None; - if let Some(text) = app.services.load_prefs.as_mut().and_then(|f| f()) { - match app.session.load_prefs_json(&text) { - Ok(found) => { - invalid = found; - stored = serde_json::from_str::(&text).ok(); - } - Err(e) => { - let template = "Preferences were reset: {error}"; - app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]); - } - } - } - crate::dock::restore(app); - crate::brush_picker::restore(app); - crate::last_brush::restore(app); - sync_rulers(app); - crate::tool_memory::restore(app); - crate::view_cmds::restore(app); - app.sync_recent(); - app.prefs_rt.saved_rev = app.session.prefs.rev(); - let loaded = app.session.prefs_value(); - app.prefs_rt.saved_value = Some(match stored { - Some(stored) => stored_base(&loaded, &stored), - None => loaded, - }); - if !invalid.is_empty() { - repair_invalid(app, &invalid); - } -} - -/// The save base after loading `stored`: what was loaded, with the keys the shift tool switch -/// migration may change (#5647) put back as the file had them, the way [`repair_invalid`] puts -/// back unreadable values. The migrated value and the new version then differ from the base, so -/// the next save writes them rather than keeping the old value under a newer version. Every other -/// key keeps its loaded value, so the three-way merge leaves another instance's changes alone, -/// also for keys the file doesn't have yet. A file from a newer version keeps its version. -fn stored_base(loaded: &Value, stored: &Value) -> Value { - let mut base = loaded.clone(); - let Some(obj) = base.as_object_mut() else { - return base; - }; - match stored.get("version") { - Some(v) if v.as_u64().is_some_and(|v| v > prefs::PREFS_VERSION) => {} - Some(v) => { - obj.insert("version".into(), v.clone()); - } - None => { - obj.remove("version"); - } - } - if let (Some(v), Some(tools)) = (stored.pointer("/tools/useShiftKeyForToolSwitch"), obj.get_mut("tools").and_then(Value::as_object_mut)) { - tools.insert("useShiftKeyForToolSwitch".into(), v.clone()); - } - base -} - -/// Some saved values couldn't be read and took their defaults (#6611): say which, and write -/// the defaults over them on the next save so the next launch reads a clean file. The save -/// base holds the unreadable values, so the three-way merge sees them as changed here and -/// replaces (or removes) exactly those, keeping everything else in the stored file. -fn repair_invalid(app: &mut PhotocraftApp, invalid: &[prefs::InvalidPref]) { - if let Some(base) = app.prefs_rt.saved_value.as_mut() { - for bad in invalid { - let Some((key, parent)) = bad.keys.split_last() else { - continue; - }; - if let Some(obj) = parent.iter().try_fold(&mut *base, |cur, k| cur.get_mut(k.as_str())).and_then(Value::as_object_mut) { - obj.insert(key.clone(), bad.value.clone()); - } - } - } - app.session.prefs.edit(|_| ()); - let paths = invalid.iter().map(prefs::InvalidPref::path).collect::>().join(", "); - let (title, line) = ( - "Some preferences were reset", - "The preferences file held values PhotoCraft can't read for {paths}. Those settings are back to their defaults; the rest of your preferences loaded.", - ); - // Notices keep their English source and are translated when drawn. - let id = crate::notices::post(app, title, vec![line.into()], false, None); - if let Some(notice) = app.ui.notices.iter_mut().find(|n| n.id == id) { - notice.args.push(("paths".into(), paths)); - } -} - -/// Discover recovery entries after construction, then decode one at a time without blocking -/// the window. Only the completed job's apply step touches the session. -fn recovery(app: &mut PhotocraftApp) { - if !app.prefs_rt.recovery_started { - app.prefs_rt.recovery_started = true; - if app.session.prefs().file_handling.recover_on_launch - && let Some(recover) = app.services.recover.as_mut() - { - app.prefs_rt.recovery_queue.extend(recover()); - } - } - start_next_recovery(app); -} - -fn start_next_recovery(app: &mut PhotocraftApp) { - while app.prefs_rt.recovery_pending.is_none() { - let Some(r) = app.prefs_rt.recovery_queue.pop_front() else { return }; - let label = format!("Recovering {}", r.name); - let started = app.session.start_job( - "file.recover", - json!({}), - &label, - false, - move |ctx| { - ctx.check()?; - ctx.progress(0.0, "Loading recovery data"); - let doc = (r.load)().map_err(photocraft_engine::EngineError::Other)?; - ctx.check()?; - Ok(doc) - }, - move |s, doc| { - let active = s.active().map(|st| st.doc.id); - let first = s.documents().is_empty(); - s.add_document(doc, r.path); - let st = s.active_mut().ok_or(photocraft_engine::EngineError::NoDocument)?; - st.saved_revision = 0; - let (id, revision) = (st.doc.id, st.revision); - if let Some(index) = active.and_then(|id| s.documents().iter().position(|st| st.doc.id == id)) { - s.set_active(index); - } - Ok(json!({"documentId": id.0, "revision": revision, "firstDocument": first})) - }, - ); - match started { - Ok(Started::Job(job)) => app.prefs_rt.recovery_pending = Some((job, r.key)), - Ok(Started::Done(v)) => finish_recovery(app, &r.key, &v), - Err(e) => crate::notices::error(app, format!("{label}: {e}")), - } - } -} - -fn finish_recovery(app: &mut PhotocraftApp, key: &str, v: &Value) { - let recovered = v - .get("documentId") - .and_then(Value::as_u64) - .zip(v.get("revision").and_then(Value::as_u64)) - .and_then(|(id, revision)| app.session.documents().iter().find(|st| st.doc.id.0 == id).map(|st| (st.doc.id, revision, st.doc.name.clone()))); - let Some((id, revision, name)) = recovered else { - crate::notices::error(app, "The recovered document is no longer open".into()); - return; - }; - // Track the admitted snapshot's revision, even if another job has already edited it. - app.prefs_rt.autosaved.insert(id, revision); - if let Some(adopt) = app.services.adopt_autosave.as_mut() { - adopt(id.0, key); - } - if v.get("firstDocument").and_then(Value::as_bool) == Some(true) { - app.ui.chrome.home = None; - } - app.sync_views(); - let template = "Recovered {name}"; - app.ui.status = crate::i18n::fmt(tl!(template), &[("name", &name)]); - app.ui.status_error = false; -} - -/// Recovery uses the existing job polling/progress/cancel path. Its successful result adopts -/// the original entry on the UI thread, using identity rather than a mutable tab position. -pub(crate) fn on_recovery_event(app: &mut PhotocraftApp, e: &JobEvent) -> bool { - if !app.prefs_rt.recovery_pending.as_ref().is_some_and(|(job, _)| *job == e.id) { - return false; - } - let Some((_, key)) = app.prefs_rt.recovery_pending.take() else { return false }; - match &e.outcome { - JobOutcome::Done(v) => finish_recovery(app, &key, v), - JobOutcome::Failed(err) => crate::notices::error(app, format!("{}: {err}", e.label)), - JobOutcome::Cancelled => { - // Native bundle decoding cannot stop midway. Cancel admission and the rest of the - // batch so another large decoder isn't started while this worker finishes. - app.prefs_rt.recovery_queue.clear(); - app.ui.status = crate::i18n::fmt(tl!("Cancelled {label}"), &[("label", tl!(&e.label))]); - app.ui.status_error = false; - } - } - start_next_recovery(app); - true -} - -/// Attach the brush preset store once its background load finishes, and surface write -/// failures in the status bar. -fn presets_store(app: &mut PhotocraftApp) { - if let Some(rx) = &app.services.preset_store { - match rx.try_recv() { - Ok(opened) => { - app.services.preset_store = None; - let warnings = app.session.attach_preset_store(opened); - if let Some(w) = warnings.first() { - app.ui.status = if warnings.len() == 1 { - w.clone() - } else { - crate::i18n::fmt( - &crate::i18n::trn( - crate::i18n::current(), - (warnings.len() - 1) as u64, - "{warning} (+{n} more brush preset warning)", - "{warning} (+{n} more brush preset warnings)", - ), - &[("warning", w)], - ) - }; - } - } - Err(std::sync::mpsc::TryRecvError::Empty) => {} - Err(std::sync::mpsc::TryRecvError::Disconnected) => app.services.preset_store = None, - } - } - if let Some(w) = app.session.preset_store.as_mut().map(|s| s.take_warnings()).and_then(|w| w.into_iter().next()) { - app.ui.status = w; - } -} - -/// Resolve an absolute pixels-per-point preference without multiplying the OS DPI twice. -/// Monitor dimensions are physical pixels, independent of window size and UI zoom. -fn display_scale(pref: prefs::UiScale, native: Option) -> f32 { - let native = native.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(1.0); - match pref { - // The system's scale, fractional ones included (125%, 150%, 175%: #1072), and 100% on a - // large 4K display run unscaled (#1278); 200% there is a fixed choice. - prefs::UiScale::Auto => native, - fixed => fixed.name().parse::().map_or(1.0, |pct| pct / 100.0), - } -} - -fn sync_display_scale(app: &PhotocraftApp, ctx: &egui::Context) { - let native = ctx.native_pixels_per_point(); - let native_scale = native.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(1.0); - let scale = display_scale(app.session.prefs().interface.ui_scale, native); - ctx.set_zoom_factor(scale / native_scale); -} - -/// Interface › Show Tooltips and Tools › Show Tooltips (either one off hides them): egui never -/// shows a tooltip whose delay is infinite. Re-checked every frame because a theme change -/// rebuilds the style; that's one style read, and a write only when it differs. -fn sync_tooltips(app: &PhotocraftApp, ctx: &egui::Context) { - let p = app.session.prefs(); - let delay = if p.interface.show_tooltips && p.tools.show_tooltips { crate::theme::TOOLTIP_DELAY } else { f32::INFINITY }; - if ctx.global_style().interaction.tooltip_delay != delay { - ctx.global_style_mut(|s| s.interaction.tooltip_delay = delay); - } -} - -/// Interface › Enable Animations: off, egui's fades and slides take no time and scroll areas jump -/// straight to their target (#3273). Re-checked every frame because a theme change rebuilds the -/// style; both the dark and light styles are set, so a system appearance switch keeps it. -fn sync_animations(app: &PhotocraftApp, ctx: &egui::Context) { - let on = app.session.prefs().interface.enable_animations; - let time = if on { egui::Style::default().animation_time } else { 0.0 }; - if ctx.global_style().animation_time != time { - let scroll = if on { egui::style::ScrollAnimation::default() } else { egui::style::ScrollAnimation::none() }; - ctx.all_styles_mut(|s| { - s.animation_time = time; - s.scroll_animation = scroll; - }); - } -} - -/// Resolve the saved appearance mode without changing it or either theme slot. -pub(crate) fn sync_appearance(app: &mut PhotocraftApp, ctx: &egui::Context) { - // A restored or embedding-supplied pin must not suppress native appearance events. - ctx.set_theme(egui::ThemePreference::System); - // The native service also covers Wayland sessions where winit has no system theme. - let selected = selected_theme(&app.session.prefs().interface, system_theme(app, ctx)); - if app.ui.theme != selected { - app.apply_theme(ctx, selected); - } -} - -/// Per-frame upkeep: theme sync, persistence, autosave and the history log. -pub fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) { - if !app.prefs_rt.loaded { - load(app); - } - recovery(app); - sync_rulers(app); - sync_display_scale(app, ctx); - sync_appearance(app, ctx); - crate::theme::set_ui_font_size(ctx, app.session.prefs().interface.ui_font_size); - presets_store(app); - sync_tooltips(app, ctx); - sync_animations(app, ctx); - app.sync_recent(); - // Monotonic, not `ctx.input(|i| i.time)`: logic also runs on hidden ticks, where egui's input - // time is that of the last UI pass. - if let Some(wait) = persist(app, crate::gpu_canvas::now_ms() / 1000.0) { - ctx.request_repaint_after(std::time::Duration::try_from_secs_f64(wait).unwrap_or_default()); - } - let style = canvas_style(app); - if let Some(gpu) = app.gpu.as_ref() - && app.prefs_rt.gpu_style != Some(style) - { - gpu.set_style(style); - app.prefs_rt.gpu_style = Some(style); - } - autosave(app); - #[cfg(not(target_arch = "wasm32"))] - link_updates(app, ctx); - history_log(app); -} - -/// First retry delay after a failed preferences write, in seconds; it doubles with every further -/// failure up to [`SAVE_RETRY_MAX_S`]. A new change retries sooner, but no sooner than this. -const SAVE_RETRY_S: f64 = 2.0; -const SAVE_RETRY_MAX_S: f64 = 30.0; -/// Failed writes in a row before a notice says preferences aren't being saved. -const SAVE_NOTICE_AFTER: u32 = 3; - -/// Retry state of a failed preferences write (times are egui input time, in seconds). -#[derive(Default)] -struct SaveRetry { - failures: u32, - /// When the next retry is due. - at: f64, - /// When the last write was tried, and the revision it carried. - tried_at: f64, - tried_rev: u64, - /// The "not saved" notice, while it's shown. - notice: Option, -} - -/// Save changed preferences. A failed write stays pending and is retried with a backoff (a newer -/// change retries sooner); the status bar reports the first failure and a notice a persistent -/// one. Returns the seconds until the next retry while one is pending. -fn persist(app: &mut PhotocraftApp, now: f64) -> Option { - let rev = app.session.prefs.rev(); - if rev == app.prefs_rt.saved_rev { - return None; - } - let r = &app.prefs_rt.save_retry; - if r.failures > 0 { - let due = if rev == r.tried_rev { r.at } else { r.at.min(r.tried_at + SAVE_RETRY_S) }; - if now < due { - return Some(due - now); - } - } - let ours = app.session.prefs_value(); - // A change that was undone (or set a value to what it already was) leaves nothing to write. - let written = if app.prefs_rt.saved_value.as_ref() == Some(&ours) { Ok(()) } else { write_prefs(app, &ours) }; - match written { - Ok(()) => { - app.prefs_rt.saved_rev = rev; - app.prefs_rt.saved_value = Some(ours); - let r = std::mem::take(&mut app.prefs_rt.save_retry); - if r.failures > 0 { - let message = "Preferences saved"; - app.ui.status = tl!(message).into(); - app.ui.status_error = false; - if let Some(id) = r.notice { - app.ui.notices.retain(|n| n.id != id); - } - } - None - } - Err(e) => { - let r = &mut app.prefs_rt.save_retry; - r.failures = r.failures.saturating_add(1); - (r.tried_at, r.tried_rev) = (now, rev); - let delay = (SAVE_RETRY_S * 2f64.powi(r.failures.min(16) as i32 - 1)).min(SAVE_RETRY_MAX_S); - r.at = now + delay; - let failures = r.failures; - if failures == 1 { - let template = "Couldn't save preferences: {error}. Retrying…"; - app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]); - app.ui.status_error = true; - } else if failures == SAVE_NOTICE_AFTER { - let lines = vec![e, "PhotoCraft keeps retrying; until a save succeeds, preference changes are lost when it closes.".into()]; - let id = crate::notices::post(app, "Preferences can't be saved", lines, true, None); - app.prefs_rt.save_retry.notice = Some(id); - } - Some(delay) - } - } -} - -/// Write `ours` over the stored preferences, keeping what another instance (a second browser -/// tab, another app window) changed there since this one last loaded or saved them. -fn write_prefs(app: &mut PhotocraftApp, ours: &Value) -> Result<(), String> { - let Some(save) = app.services.save_prefs.as_mut() else { return Ok(()) }; - let stored = app.services.load_prefs.as_mut().and_then(|load| load()).and_then(|t| serde_json::from_str::(&t).ok()); - let text = match (stored, &app.prefs_rt.saved_value) { - (Some(mut theirs @ Value::Object(_)), Some(base)) => { - let base = &without_stale_migration(base, &theirs); - merge_changes(base, ours, &mut theirs); - serde_json::to_string_pretty(&theirs) - } - _ => serde_json::to_string_pretty(ours), - } - .map_err(|e| e.to_string())?; - save(&text) -} - -/// The save base without the shift tool switch migration (#5647) once storage already holds a -/// version 2 file: another instance wrote it, so its Use Shift Key for Tool Switch is a choice, -/// not the old default this instance migrated. The base then holds the migrated value (on) instead -/// of the old file's off, so only a change made here since loading is written over that choice. -fn without_stale_migration(base: &Value, theirs: &Value) -> Value { - let mut base = base.clone(); - let new_file = |v: &Value| v.get("version").and_then(Value::as_u64).is_some_and(|v| v >= 2); - if new_file(theirs) && !new_file(&base) { - let key = "useShiftKeyForToolSwitch"; - if let Some(tools) = base.get_mut("tools").and_then(Value::as_object_mut) - && tools.get(key) == Some(&Value::Bool(false)) - { - tools.insert(key.into(), Value::Bool(true)); - } - } - base -} - -/// Three-way merge of preference trees: whatever `ours` changed since `base` goes over `theirs` -/// (what storage holds now) and the rest of `theirs` is kept. Objects merge key by key; any -/// other value, arrays included, is replaced whole. -fn merge_changes(base: &Value, ours: &Value, theirs: &mut Value) { - if ours == base { - return; - } - match (base, ours, theirs) { - (Value::Object(b), Value::Object(o), Value::Object(t)) => { - for (k, ov) in o { - match (b.get(k), t.get_mut(k)) { - (Some(bv), Some(tv)) => merge_changes(bv, ov, tv), - // Removed there, unchanged here: it stays removed. - (Some(bv), None) if bv == ov => {} - _ => { - t.insert(k.clone(), ov.clone()); - } - } - } - for k in b.keys().filter(|k| !o.contains_key(*k)) { - t.remove(k); - } - } - (_, _, theirs) => *theirs = ours.clone(), - } -} - -/// Write the preferences now, through the same merge as [`persist`], for recovery choices that -/// need the result immediately. The pending revision stays unsaved when the write fails. -pub(crate) fn save_preferences(app: &mut PhotocraftApp) -> Result<(), String> { - let rev = app.session.prefs.rev(); - let ours = app.session.prefs_value(); - write_prefs(app, &ours)?; - app.prefs_rt.saved_rev = rev; - app.prefs_rt.saved_value = Some(ours); - if let Some(id) = std::mem::take(&mut app.prefs_rt.save_retry).notice { - app.ui.notices.retain(|n| n.id != id); - } - Ok(()) -} - -/// Linked smart objects follow their files while the document is open, as in Photoshop: every two -/// seconds, and as soon as the window comes back to the front (after saving in another app), stamp -/// the active document's linked files on a worker thread and re-render the layers of the ones that -/// changed ([`photocraft_engine::link_watch`]). -#[cfg(not(target_arch = "wasm32"))] -fn link_updates(app: &mut PhotocraftApp, ctx: &egui::Context) { - match app.session.poll_link_scan() { - Some(Ok(r)) => { - if let Some(n) = r["updated"].as_array().map(Vec::len).filter(|n| *n > 0) { - app.ui.status = crate::i18n::trn( - crate::i18n::current(), - n as u64, - "Updated {n} linked smart object changed on disk", - "Updated {n} linked smart objects changed on disk", - ); - } - } - Some(Err(e)) => app.ui.status = e.to_string(), - None => {} - } - let (last_key, focus_key) = (egui::Id::unique("linkWatch.lastScan"), egui::Id::unique("linkWatch.focused")); - let now = crate::gpu_canvas::now_ms() / 1000.0; - let focused = ctx.input(|i| i.focused); - let was_focused: bool = ctx.data(|d| d.get_temp(focus_key)).unwrap_or(focused); - ctx.data_mut(|d| d.insert_temp(focus_key, focused)); - let has_links = app.session.active().is_some_and(|d| !photocraft_engine::link_watch::linked_files(&d.doc).is_empty()); - if !has_links { - return; - } - let last: f64 = ctx.data(|d| d.get_temp(last_key)).unwrap_or(f64::NEG_INFINITY); - if now - last >= 2.0 || (focused && !was_focused) { - ctx.data_mut(|d| d.insert_temp(last_key, now)); - app.session.start_link_scan(); - } - let wait = if app.session.link_scan.is_some() { 100 } else { 2000 }; - ctx.request_repaint_after(std::time::Duration::from_millis(wait)); -} - -/// Background autosave of documents with unsaved changes every N minutes (File Handling). -fn autosave(app: &mut PhotocraftApp) { - let fh = &app.session.prefs().file_handling; - let (on, minutes) = (fh.autosave, fh.autosave_minutes.max(1)); - if app.services.autosave.is_none() { - return; - } - // A successful queue operation is not a successful disk write. Poll each frame, - // including frames before the next autosave interval, so failures are visible. - if let Some(results) = app.services.autosave_results.as_mut() { - for (raw_id, revision, result) in results() { - let id = DocId(raw_id); - if app.prefs_rt.autosave_pending.get(&id) != Some(&revision) { - continue; - } - app.prefs_rt.autosave_pending.remove(&id); - match result { - Ok(()) => { - app.prefs_rt.autosaved.insert(id, revision); - } - Err(e) => { - let template = "Autosave failed: {error}"; - app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]); - app.ui.status_error = true; - } - } - } - } - let now = crate::gpu_canvas::now_ms(); - // Saved or closed documents drop their recovery data. - let live: HashMap = app.session.documents().iter().map(|d| (d.doc.id, d.is_dirty())).collect(); - let mut stale: Vec = app.prefs_rt.autosaved.keys().filter(|id| live.get(id) != Some(&true)).copied().collect(); - stale.extend(app.prefs_rt.autosave_pending.keys().filter(|id| live.get(*id) != Some(&true) && !app.prefs_rt.autosaved.contains_key(*id)).copied()); - for id in stale { - app.prefs_rt.autosaved.remove(&id); - app.prefs_rt.autosave_pending.remove(&id); - if let Some(d) = app.services.discard_autosave.as_mut() { - d(id.0); - } - } - if !on { - return; - } - let interval = minutes as f64 * 60_000.0; - if app.prefs_rt.next_autosave_ms == 0.0 || app.prefs_rt.next_autosave_ms > now + interval { - app.prefs_rt.next_autosave_ms = now + interval; - return; - } - if now < app.prefs_rt.next_autosave_ms { - return; - } - app.prefs_rt.next_autosave_ms = now + interval; - let jobs: Vec<_> = app - .session - .documents() - .iter() - .filter(|d| d.is_dirty() && app.prefs_rt.autosaved.get(&d.doc.id) != Some(&d.revision) && !app.prefs_rt.autosave_pending.contains_key(&d.doc.id)) - .map(|d| (d.doc.clone(), d.revision, d.path.clone())) - .collect(); - for (doc, rev, path) in jobs { - if let Some(save) = app.services.autosave.as_mut() { - match save(&doc, rev, path.as_deref()) { - Ok(()) => { - if app.services.autosave_results.is_some() { - app.prefs_rt.autosave_pending.insert(doc.id, rev); - } else { - // Synchronous or mocked services report completion on return. - app.prefs_rt.autosaved.insert(doc.id, rev); - } - } - Err(e) => { - let template = "Autosave failed: {error}"; - app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]); - app.ui.status_error = true; - } - } - } - } -} - -/// Force the autosave timer to fire on the next tick (tests, `prefs` changes). -pub fn autosave_now(app: &mut PhotocraftApp) { - app.prefs_rt.next_autosave_ms = f64::MIN_POSITIVE; -} - -/// History Log preference: append executed commands to a text file. -fn history_log(app: &mut PhotocraftApp) { - let n = app.session.journal.len(); - if n <= app.prefs_rt.log_len { - app.prefs_rt.log_len = n; - return; - } - let hl = app.session.prefs().history_log.clone(); - let start = app.prefs_rt.log_len; - app.prefs_rt.log_len = n; - if !hl.enabled || hl.file_path.is_empty() || hl.destination == prefs::LogDestination::Metadata { - return; - } - let Some(append) = app.services.append_text.as_mut() else { return }; - let mut text = String::new(); - for (id, params) in &app.session.journal[start..] { - let label = photocraft_engine::commands::find(id).map_or(id.as_str(), |c| c.label).trim_end_matches('…'); - match hl.detail { - prefs::LogDetail::SessionsOnly => { - if matches!(id.as_str(), "file.new" | "file.open" | "file.close" | "file.openAs") { - text.push_str(&format!("{label}\n")); - } - } - prefs::LogDetail::Concise => text.push_str(&format!("{label}\n")), - prefs::LogDetail::Detailed => text.push_str(&format!("{label} {id} {params}\n")), - } - } - if !text.is_empty() { - let _ = append(&hl.file_path, &text); - } -} - // ------------------------------------------------------------------ shortcuts pub use crate::shortcuts::{default_shortcut, effective_shortcut}; -/// Every shortcut-bearing command (engine registry plus shell commands): (id, label, menu path, -/// default shortcut), menu items first in Photoshop order. -pub fn shortcut_items(app: &PhotocraftApp) -> Vec<(String, String, Vec, Option)> { - let mut out: Vec<(String, String, Vec, Option)> = Vec::new(); - let mut seen = std::collections::HashSet::new(); - for it in crate::menus::menu_items(app) { - if it.label == "---" || !seen.insert(it.id.clone()) { - continue; - } - let default = default_shortcut(&it.id).or(it.shortcut.clone().filter(|_| !app.session.prefs().shortcuts.contains_key(&it.id))); - out.push((it.id, it.label, it.path, default)); - } - // Commands without a menu item: the colour and fill keys (D, X, ⌥⌫…) sit under Tools, as - // Photoshop lists its colour keys in the Tools shortcut set, after the rest; then the held - // temporary tools (#249). - let tools_key = |id: &str| id.starts_with("tools.") || photocraft_engine::fill_key_cmds::IDS.contains(&id); - let mut tools = Vec::new(); - let mut layer = Vec::new(); - for c in photocraft_engine::command_specs() { - if seen.insert(c.id.to_string()) && c.shortcut.is_some() { - let item = (c.id.to_string(), c.label.to_string(), c.menu.iter().map(|s| s.to_string()).collect::>(), c.shortcut.map(Into::into)); - if c.menu.is_empty() && tools_key(c.id) { - tools.push((item.0, item.1, vec!["Tools".to_string()], item.3)); - } else if c.menu.is_empty() && c.id.starts_with("layer.") { - // Stamp Visible / Stamp Down (#217): no menu item in Photoshop; listed at the end - // of the Layer section. - layer.push((item.0, item.1, vec!["Layer".to_string()], item.3)); - } else { - out.push(item); - } - } - } - let at = out.iter().rposition(|i| i.2.first().map(String::as_str) == Some("Layer")).map_or(out.len(), |i| i + 1); - out.splice(at..at, layer); - out.extend(tools); - out.extend( - crate::state::Tool::ALL - .into_iter() - .map(|tool| (crate::tool_shortcuts::id(tool), tool.label().to_string(), vec!["Tools".into()], crate::tool_shortcuts::default(tool))), - ); - for (id, label, def) in prefs::TEMPORARY_TOOLS { - if seen.insert(id.to_string()) { - out.push((id.to_string(), label.to_string(), vec!["Tools".into(), "Temporary".into()], Some(def.to_string()))); - } - } - out -} - -/// A fingerprint of the bindings a shortcut conflict describes. -fn conflict_state(overrides: &BTreeMap, alternates: &BTreeMap>, selected: &str, set: Option<&Value>) -> u64 { - use std::hash::{Hash, Hasher}; - let mut h = std::collections::hash_map::DefaultHasher::new(); - (overrides, alternates, selected, set.map(Value::to_string)).hash(&mut h); - h.finish() -} - -/// Keys the system takes before the app sees them (switching apps, closing the window, force -/// quit): Edit › Keyboard Shortcuts won't assign them, as Photoshop won't. `sc` is in our -/// notation, where `Cmd` is Ctrl off the Mac. -pub fn reserved_shortcut(sc: &str) -> bool { - prefs::reserved_shortcut(sc) -} - -/// Text of a key press for the shortcut editor (`Cmd+Shift+K`), `None` for bare modifiers. -pub fn shortcut_text(key: egui::Key, m: egui::Modifiers) -> Option { - if is_modifier_key(key) { - return None; - } - let mut parts = Vec::new(); - if m.command || m.mac_cmd { - parts.push(tl!("Cmd").to_string()); - } - if m.ctrl && !m.command { - parts.push(tl!("Ctrl").into()); - } - if m.alt { - parts.push(tl!("Alt").into()); - } - if m.shift { - parts.push(tl!("Shift").into()); - } - let name = match key { - egui::Key::Equals => "=", - egui::Key::Minus => "-", - egui::Key::OpenBracket => "[", - egui::Key::CloseBracket => "]", - egui::Key::Semicolon => ";", - egui::Key::Quote => "'", - egui::Key::Plus => "", - k => k.name(), - }; - parts.push(name.to_string()); - prefs::normalize_shortcut(&parts.join("+")) -} - -/// A modifier key on its own. egui reports Ctrl, Shift, Alt and ⌘ presses as key events too -/// (`ControlLeft`…), before the key pressed with them: they are never a shortcut's key, so -/// shortcut capture waits for the real key (#292: Ctrl+F was recorded as "Ctrl+ControlLeft"). -pub fn is_modifier_key(key: egui::Key) -> bool { - use egui::Key::*; - matches!(key, ShiftLeft | ShiftRight | ControlLeft | ControlRight | AltLeft | AltRight | SuperLeft | SuperRight) -} - -/// Modifier bits a physical modifier-key press contributes when egui leaves them out of -/// [`Modifiers`] on the key event (#7190). -fn modifier_key_modifiers(key: egui::Key) -> egui::Modifiers { - use egui::Key::*; - match key { - ShiftLeft | ShiftRight => egui::Modifiers::SHIFT, - ControlLeft | ControlRight => egui::Modifiers::CTRL, - AltLeft | AltRight => egui::Modifiers::ALT, - SuperLeft | SuperRight => egui::Modifiers::COMMAND, - _ => egui::Modifiers::NONE, - } -} - -fn capture_mods_field(v: Option<&Value>) -> egui::Modifiers { - let o = v.and_then(Value::as_object); - egui::Modifiers { - shift: o.and_then(|o| o.get("shift")).and_then(Value::as_bool).unwrap_or(false), - ctrl: o.and_then(|o| o.get("ctrl")).and_then(Value::as_bool).unwrap_or(false), - alt: o.and_then(|o| o.get("alt")).and_then(Value::as_bool).unwrap_or(false), - command: o.and_then(|o| o.get("command")).and_then(Value::as_bool).unwrap_or(false), - mac_cmd: o.and_then(|o| o.get("mac_cmd")).and_then(Value::as_bool).unwrap_or(false), - } -} - -fn capture_mods_json(m: egui::Modifiers) -> Value { - json!({ - "shift": m.shift, - "ctrl": m.ctrl, - "alt": m.alt, - "command": m.command, - "mac_cmd": m.mac_cmd, - }) -} - -/// While capture is active: refresh held modifiers (including across frames via dialog -/// `captureMods`) and, if a non-modifier key was pressed this frame, return it with the -/// modifiers held with it. -/// -/// #7190 root cause: capture used to [`find_map`](Iterator::find_map) the first non-modifier -/// [`Event::Key`] and pass only that event's `modifiers` into [`shortcut_text`]. On Linux and -/// Windows, winit/egui often reports `ShiftLeft`/`ShiftRight` (and sometimes the letter key) with -/// [`Modifiers::NONE`], and the modifier down and the letter down often land in separate UI -/// frames. Shift was then missing from the stored binding (`F6` instead of `Shift+F6`). Like #292 -/// for `ControlLeft`, we walk the frame's events, OR in [`modifier_key_modifiers`] for modifier -/// keys, and persist accumulated modifiers in `captureMods` until capture ends. -pub(crate) fn capture_key_press(capture_mods: egui::Modifiers, i: &egui::InputState) -> (egui::Modifiers, Option<(egui::Key, egui::Modifiers)>) { - let mut mods = capture_mods | i.modifiers; - let mut pressed = None; - for e in &i.events { - if let egui::Event::ModifiersChanged(m) = e { - mods = *m; - } - if let egui::Event::Key { key, pressed: true, modifiers, .. } = e { - if is_modifier_key(*key) { - mods = *modifiers | modifier_key_modifiers(*key); - continue; - } - pressed = Some((*key, mods | *modifiers)); - break; - } - if let egui::Event::Key { key, pressed: false, modifiers, .. } = e - && is_modifier_key(*key) - { - mods = *modifiers; - } - } - (mods, pressed) -} - -// ------------------------------------------------------------------ menu routing - -/// Shell front ends for Edit-menu commands invoked without parameters (dialogs, pickers). -/// `None` when `id` isn't handled here. -pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { - let empty = params.as_object().is_none_or(|o| o.is_empty()); - if !empty { - return None; - } - if let Some(section) = id.strip_prefix("edit.preferences.") { - return Some(Ok(json!({"dialog": open_preferences(app, section)}))); - } - let dialog = |d: Option| Some(d.map(|d| json!({"dialog": d})).ok_or_else(|| "not available".to_string())); - match id { - "edit.keyboardShortcuts" => Some(Ok(json!({"dialog": open_shortcuts(app, 0)}))), - "edit.menus" => Some(Ok(json!({"dialog": open_shortcuts(app, 1)}))), - "edit.toolbar" => Some(Ok(json!({"dialog": open_shortcuts(app, 2)}))), - "edit.colorSettings" => { - let d = crate::filter_dialog::open(app, "edit.colorSettings"); - let cur = serde_json::to_value(&app.session.color.settings).unwrap_or_default(); - // What Monitor Profile resolves to, so a fallback to sRGB is visible (#569): read the - // displays again now, and the dialog refreshes this line as it draws. - crate::monitor_status::read_now(app); - let note = crate::monitor_status::note(app); - if let Some(dm) = d.and_then(|d| app.ui.dialog_mut(d)) { - for (k, v) in cur.as_object().into_iter().flatten() { - if dm.fields.contains_key(k) { - dm.fields.insert(k.clone(), v.clone()); - } - } - dm.fields.insert("__note".into(), json!(note)); - } - dialog(d) - } - "edit.fade" | "edit.findAndReplaceText" | "edit.defineBrushPreset" | "edit.defineCustomShape" | "edit.autoAlignLayers" | "edit.autoBlendLayers" => { - if !app.session.is_enabled(id) { - return Some(Err(photocraft_engine::commands::find(id) - .map_or("not available".into(), |c| format!("{} is not available right now", c.label.trim_end_matches('…'))))); - } - let d = crate::filter_dialog::open(app, id); - if let Some(dm) = d.and_then(|d| app.ui.dialog_mut(d)) { - // Optional parameters the generic dialog can't express keep their defaults. - for k in ["reference", "path"] { - dm.fields.remove(k); - } - } - dialog(d) - } - // Photoshop's Content-Aware Fill workspace (caf_ui); the engine command with params - // still runs directly. - "edit.contentAwareFill" => Some(crate::caf_ui::open(app).map(|_| json!({"contentAwareFill": app.distort.describe()["contentAwareFill"]}))), - // Photoshop has no dialog: the menu opens the scale box (with params: the engine). - crate::cas_transform::COMMAND => Some(crate::cas_transform::begin(app, ctx)), - "edit.presets.presetManager" => { - Some(Ok(json!({"dialog": open_kind(app, "presets", "Preset Manager", json!({"kind": "brushes", "selected": 0, "newName": ""}))}))) - } - "edit.presets.exportImportPresets" => Some(Ok( - json!({"dialog": open_kind(app, "presetsIO", "Export/Import Presets", json!({"action": "export", "brushes": true, "customShapes": true, "tools": true}))}), - )), - _ => None, - } -} - -fn open_kind(app: &mut PhotocraftApp, kind: &str, label: &str, fields: Value) -> u64 { - let mut f = Map::new(); - f.insert("__prefsui".into(), json!(kind)); - f.insert("__label".into(), json!(label)); - if let Value::Object(m) = fields { - f.extend(m); - } - app.ui.open_dialog(DialogKind::Command, f) -} - -/// Is this a dialog rendered by this module? -pub fn owns(fields: &Map) -> bool { - fields.contains_key("__prefsui") -} - -/// Only Preferences supports applying changes without closing the dialog. -pub fn is_preferences(fields: &Map) -> bool { - fields.get("__prefsui").and_then(Value::as_str) == Some("prefs") -} - -fn preference_values(p: &prefs::Preferences) -> Map { - let values = p.to_json(); - SECTIONS.iter().filter_map(|(id, _)| Some((id.to_string(), values.get(id)?.clone()))).collect() -} - -/// Compare the editable sections, excluding settings managed outside Preferences. -pub fn preferences_changed(app: &PhotocraftApp, fields: &Map) -> bool { - is_preferences(fields) && fields.get("values").and_then(Value::as_object).is_some_and(|values| *values != preference_values(app.session.prefs())) -} - -/// Commit the working copy and keep the current section open. Failure leaves the draft intact. -pub fn apply(app: &mut PhotocraftApp, id: u64) -> Result { - let d = app.ui.dialogs.iter().find(|d| d.id == id).ok_or_else(|| format!("no dialog {id}"))?; - if d.kind != DialogKind::Command || !is_preferences(&d.fields) { - return Err("Apply is only available for Preferences".into()); - } - let fields = d.fields.clone(); - let result = confirm(app, &fields)?; - let values = Value::Object(preference_values(app.session.prefs())); - if let Some(d) = app.ui.dialog_mut(id) { - // Use the validated values as the next draft, including any normalisation by prefs.set. - d.fields.insert("values".into(), values); - } - Ok(result) -} - -/// The size Preferences opens at: room for the widest section and about 30 settings rows. The -/// dialog's resize grip changes it, and its contents follow (#7420). -pub const PREFERENCES_SIZE: egui::Vec2 = egui::vec2(1040.0, 800.0); - -/// The height of the settings area (section list and fields) when `available` is left below the -/// search field: everything but the dialog's button row (`item_spacing` + 8 pt + the buttons) and -/// a little slack, never less than a few rows. -fn settings_height(available: f32, item_spacing: f32, button_height: f32) -> f32 { - (available - (item_spacing + 8.0 + button_height + 4.0)).max(160.0) -} - -/// Max dialog width for our dialogs. Preferences fills the width it is given (`available`, its -/// resizable area). -pub fn width(fields: &Map, available: f32) -> Option { - match fields.get("__prefsui").and_then(Value::as_str)? { - "prefs" => Some(available.max(380.0)), - "shortcuts" => Some(720.0), - _ => Some(460.0), - } -} - -/// Open Edit › Preferences on `section`. -pub fn open_preferences(app: &mut PhotocraftApp, section: &str) -> u64 { - let section = if SECTIONS.iter().any(|(id, _)| *id == section) { section } else { "general" }; - let working = preference_values(app.session.prefs()); - let order = field_order(app.session.prefs(), &working); - open_kind(app, "prefs", "Preferences", json!({"section": section, "values": working, "__order": order})) -} - -/// Each section's keys in declaration order (JSON objects sort their keys; the serialised text -/// keeps the struct's order, which groups related settings like Photoshop's dialog). -fn field_order(p: &prefs::Preferences, sections: &Map) -> Value { - let text = serde_json::to_string(p).unwrap_or_default(); - let mut out = Map::new(); - for (id, v) in sections { - let Some(start) = text.find(&format!("\"{id}\":{{")) else { continue }; - let body = &text[start..]; - let end = body.find('}').unwrap_or(body.len()); - let region = &body[..end]; - let mut keys: Vec<(usize, String)> = - v.as_object().into_iter().flatten().map(|(k, _)| (region.find(&format!("\"{k}\":")).unwrap_or(usize::MAX), k.clone())).collect(); - keys.sort(); - out.insert(id.clone(), json!(keys.into_iter().map(|(_, k)| k).collect::>())); - } - Value::Object(out) -} - -/// Open Keyboard Shortcuts and Menus on a tab (0 shortcuts, 1 menus, 2 toolbar). -pub fn open_shortcuts(app: &mut PhotocraftApp, tab: u64) -> u64 { - let p = app.session.prefs(); - let fields = json!({ - "tab": tab, - "filter": "", - "overrides": p.shortcuts, - "alternates": p.alternate_shortcuts, - "sets": p.shortcut_sets, - "activeSet": p.shortcut_set, - "hidden": p.menus.hidden, - "colors": p.menus.colors, - "toolbarHidden": p.toolbar.hidden, - "selected": "", - "capture": false, - "message": "", - }); - open_kind(app, "shortcuts", tl!("Keyboard Shortcuts and Menus"), fields) -} - -/// Open the Embedded Profile Mismatch prompt for a file waiting to open (`open_prompt`): its -/// `message`, the answer selected first (`action`), and `marker`, the field that routes OK and -/// Cancel back to `open_prompt`. -/// `names` carries the embedded and working profile names and the Color Settings policy a -/// remembered choice is saved to (`policyKey`, null for a mode without one). -pub fn open_mismatch(app: &mut PhotocraftApp, message: &str, action: &str, missing: bool, marker: &str, names: Value) -> u64 { - let mut fields = json!({"message": message, "action": action, "missing": missing, "remember": false}); - if let (Some(f), Value::Object(n)) = (fields.as_object_mut(), names) { - f.extend(n); - } - fields[marker] = json!(true); - open_kind(app, "mismatch", tl!("Embedded Profile Mismatch"), fields) -} - -// ------------------------------------------------------------------ bodies - -/// Render one of our dialogs' bodies. -pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { - match f.get("__prefsui").and_then(Value::as_str).unwrap_or("") { - "prefs" => { - let mut info = app.perf.gpu_info.lines(); - info.extend(gpu_memory_lines(app)); - f.insert("__gpuInfo".into(), json!(info)); - f.insert("__gpuAdapters".into(), json!(app.perf.gpu_info.adapters)); - let system = system_theme(app, ui.ctx()); - prefs_body(ui, f, system); - } - "shortcuts" => shortcuts_body(app, ui, f), - "presets" => presets_body(app, ui, f), - "presetsIO" => presets_io_body(ui, f), - "mismatch" => mismatch_body(ui, f), - _ => {} - } -} - -/// Performance › Graphics: the compositor's GPU memory budget and whether the active document's -/// layers fit it (the GPU Memory preference sets it). -fn gpu_memory_lines(app: &PhotocraftApp) -> Vec { - let mut v = Vec::new(); - if app.perf.gpu_budget_mb > 0 { - let budget = crate::chrome_ui::fmt_bytes(app.perf.gpu_budget_mb.saturating_mul(1 << 20)); - v.push(crate::i18n::fmt(tl!("GPU memory budget: {budget}"), &[("budget", &budget)])); - } - let doc = app.session.active().map(|st| st.doc.id.0); - if let Some(fit) = app.perf.gpu_layer_fit.filter(|f| Some(f.doc) == doc) { - let args = [("needed", crate::chrome_ui::fmt_bytes(fit.needed)), ("budget", crate::chrome_ui::fmt_bytes(fit.budget))]; - let args: Vec<(&str, &str)> = args.iter().map(|(k, v)| (*k, v.as_str())).collect(); - v.push(if fit.fits() { - crate::i18n::fmt(tl!("This document's layers: {needed} of {budget} for layers"), &args) - } else { - crate::i18n::fmt(tl!("This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU"), &args) - }); - } - v -} - -/// The label a preference key shows in the dialog: a few keys have their own wording, the rest -/// split camelCase into words (`convertToSrgb` → "Convert to srgb"). -fn humanize(key: &str) -> String { - match key { - "appearanceMode" => return "Appearance Mode".into(), - "exrAcesCg" => return "Open color-less EXR as ACEScg".into(), - "darkTheme" => return "Dark Theme".into(), - "lightTheme" => return "Light Theme".into(), - "automaticallyCheckUpdates" => return "Automatically Check for Updates".into(), - _ => {} - } - // These controls appear only for WebP, so reuse the existing translated labels. - if key == "webpLossless" { - return "Lossless".into(); - } - if key == "webpQuality" { - return "Quality".into(); - } - // The auto-hide notice settings read best with their own labels (Interface › Notification, #2022). - if key == "notificationAutoHide" { - return "Auto Hide Notifications".into(); - } - if key == "notificationDurationSeconds" { - return "Notification Duration (seconds)".into(); - } - // Tools: arrow-key nudges bundle into one History state (#2259). - if key == "bundleNudges" { - return "Bundle Arrow-Key Nudges".into(); - } - if key == "nudgeBundlePauseMs" { - return "Nudge Bundle Pause (ms)".into(); - } - // Performance: presentation without vsync (#1343); like the other graphics settings, it - // takes effect when the window next opens. - // File Handling: Photoshop's wording (#8080). - if key == "doNotAppendCopy" { - return "Do not append \"copy\" to filename when saving a copy".into(); - } - if key == "lowLatencyDrawing" { - return "Low-Latency Drawing (vsync off, applies at next launch)".into(); - } - // Performance: the canvas compositor's GPU memory, 0 for the automatic budget (L3). - if key == "gpuMemoryMb" { - return "GPU Memory (MB, 0 = Automatic)".into(); - } - let mut s = String::new(); - for (i, ch) in key.chars().enumerate() { - if i == 0 { - s.extend(ch.to_uppercase()); - } else if ch.is_uppercase() { - s.push(' '); - s.extend(ch.to_lowercase()); - } else { - s.push(ch); - } - } - s.replace("Psd", "PSD") - .replace("Gpu", "GPU") - .replace("Ui ", "UI ") - .replace("Mb", "(MB)") - .replace("Exif", "EXIF") - .replace("Hud", "HUD") - .replace("Lut ", "LUT ") -} - -fn choice_label(v: &str) -> String { - match v { - "exr" => "EXR".into(), - "cm" => "Centimeters".into(), - "mm" => "Millimeters".into(), - "75" | "80" | "85" | "90" | "95" | "100" | "105" | "110" | "115" | "120" | "125" | "150" | "175" | "200" | "250" | "300" => format!("{v}%"), - "8" => "8 Bits/Channel".into(), - "16" => "16 Bits/Channel".into(), - "postScript" => "PostScript (72 points/inch)".into(), - "traditional" => "Traditional (72.27 points/inch)".into(), - "vulkan" => "Vulkan".into(), - "dx12" => "DirectX 12".into(), - "metal" => "Metal".into(), - "gl" => "OpenGL".into(), - "ahd" => "AHD (adaptive homogeneity)".into(), - "mhc" => "Malvar–He–Cutler".into(), - "cpu" => "CPU (no GPU acceleration)".into(), - v => humanize(v), - } -} - -/// An editable `#rrggbb` field beside a colour swatch (#668): typing a valid value sets the -/// colour; while it's being typed a partial value is kept, and it shows the colour otherwise. -fn hex_field(ui: &mut egui::Ui, key: &str, rgb: &mut [u8; 3]) { - let id = egui::Id::unique(("pref-hex", key)); - let shown = format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]); - let mut text = ui.data(|d| d.get_temp::(id)).unwrap_or_else(|| shown.clone()); - let r = crate::widgets::text_field_ex(ui, id, &mut text, "", 72.0, true, Some(7)).accessible_name(tl!("Color")); - if r.changed() - && let Some(c) = prefs::parse_hex(&text) - { - *rgb = c; - } - if r.has_focus() { - ui.data_mut(|d| d.insert_temp(id, text)); - } else { - ui.data_mut(|d| d.remove::(id)); - } -} - -fn color_of(s: &str) -> Color32 { - prefs::parse_hex(s).map_or(Color32::GRAY, |c| Color32::from_rgb(c[0], c[1], c[2])) -} - -/// Search the same visible, editable preference labels used in the dialog. -fn preference_matches(section: &str, key: &str, query: &str) -> bool { - let label = humanize(key); - format!("{section}.{key}").to_lowercase().contains(query) || label.to_lowercase().contains(query) || tl!(&label).to_lowercase().contains(query) -} - -fn preference_sections(values: &Value, search: &str) -> Vec<(&'static str, &'static str)> { - let query = search.trim().to_lowercase(); - SECTIONS - .iter() - .copied() - .filter(|(id, title)| { - query.is_empty() - || title.to_lowercase().contains(&query) - || tl!(title).to_lowercase().contains(&query) - || values - .get(*id) - .and_then(Value::as_object) - .is_some_and(|fields| fields.keys().any(|key| !prefs::is_hidden(&format!("{id}.{key}")) && preference_matches(id, key, &query))) - }) - .collect() -} - -/// Preferences: section list on the left, the section's settings on the right. -fn prefs_body(ui: &mut egui::Ui, f: &mut Map, system: Option) { - let t = Tokens::get(ui.ctx()); - let mut section = f.get("section").and_then(Value::as_str).unwrap_or("general").to_string(); - let mut values = f.get("values").cloned().unwrap_or(Value::Null); - // The dialog follows the language being edited, so a change shows before OK. - let lang = crate::i18n::Lang::from_pref(values.pointer("/interface/language").and_then(Value::as_str).unwrap_or("auto")); - let mut search = f.get("__search").and_then(Value::as_str).unwrap_or("").to_string(); - crate::widgets::text_field(ui, ui.scope_id().with("prefs-search"), &mut search, tl!("Search settings…"), ui.available_width(), false); - let found = preference_sections(&values, &search); - if !found.iter().any(|(id, _)| *id == section) - && let Some((first, _)) = found.first() - { - section = (*first).to_string(); - } - ui.add_space(6.0); - ui.horizontal_top(|ui| { - // Section list. - ui.vertical(|ui| { - ui.set_width(170.0); - if found.is_empty() { - ui.label(RichText::new(tl!("No matching settings")).color(t.text_dim)); - } - for &(id, title) in &found { - let sel = section == id; - let empty = !has_visible_fields(&values, id); - let (rect, resp) = ui.allocate_exact_size(vec2(170.0, 22.0), Sense::click()); - if sel { - ui.painter().rect_filled(rect, t.radius_sm, t.row_selected); - } else if resp.hovered() { - ui.painter().rect_filled(rect, t.radius_sm, t.hover); - } - let color = if sel { - t.text - } else if empty { - t.text_faint - } else { - t.text_dim - }; - // Translated section names can be longer than the column: elide them (the full - // name is the tooltip) instead of drawing over the settings. - let mut job = egui::text::LayoutJob::simple_singleline(tl!(title).to_string(), crate::theme::medium(12.5), color); - job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width() - 12.0); - let galley = ui.painter().layout_job(job); - let elided = galley.elided; - ui.painter().galley(rect.left_center() + vec2(8.0, -galley.size().y / 2.0), galley, color); - let resp = if elided { resp.on_hover_text(tl!(title)) } else { resp }; - if resp.clicked() { - section = id.to_string(); - } - } - }); - // The settings fill the dialog's resizable area down to the button row (#7420). Sizing them - // from the window instead left a resized dialog with empty space and the buttons mid-way. - // The area grows to fit its content, so this must never ask for more than it was given. - let content_height = settings_height(ui.available_height(), ui.spacing().item_spacing.y, crate::widgets::button_height(ui.ctx())); - crate::widgets::vline(ui, content_height); - ui.vertical(|ui| { - ui.set_width((ui.available_width() - 12.0).max(340.0)); - let title = SECTIONS.iter().find(|(id, _)| *id == section).map_or("General", |(_, t)| *t); - ui.label(RichText::new(tl!(&title)).font(crate::theme::semibold(14.0)).color(t.text)); - let show_all = search.trim().is_empty() - || title.to_lowercase().contains(&search.trim().to_lowercase()) - || tl!(&title).to_lowercase().contains(&search.trim().to_lowercase()); - let filter = if show_all { "" } else { search.trim() }; - ui.add_space(6.0); - egui::ScrollArea::vertical().max_height(content_height - 30.0).id_salt("prefs-scroll").show(ui, |ui| { - let order: Vec = - f.get("__order").and_then(|o| o.get(§ion)).and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); - if !has_visible_fields(&values, §ion) { - ui.add_space(4.0); - ui.label(RichText::new(tl!("These settings aren't available in PhotoCraft yet.")).color(t.text_faint)); - } else if let Some(obj) = values.get_mut(§ion).and_then(Value::as_object_mut) { - section_fields(ui, §ion, obj, &order, lang, system, filter); - if section == "fileHandling" { - ui.label( - RichText::new(tl!("0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized.")) - .color(t.text_faint), - ); - } - if section == "performance" { - gpu_status_rows(ui, f.get("__gpuInfo"), f.get("__gpuAdapters"), obj); - } - ui.add_space(8.0); - } - if search.trim().is_empty() - && has_visible_fields(&values, §ion) - && crate::widgets::secondary_button(ui, tl!("Reset Section"), 110.0).clicked() - && let Some(def) = prefs::Preferences::default().get(§ion) - { - values[§ion] = def; - } - }); - }); - }); - f.insert("section".into(), json!(section)); - f.insert("__search".into(), json!(search)); - f.insert("values".into(), values); - // A colour swatch was clicked: open the Color Picker on that value (#2144). - if let Some((path, name)) = ctx_take_pick(ui) { - crate::color_picker_ui::request_field(f, &format!("/values/{}", path.replace('.', "/")), &crate::color_picker_ui::title_for(&name)); - } -} - -/// Preferences › Performance: what the app renders with now, and a reset of the GPU backend -/// (a crashed start may have moved it to a safer choice). -fn gpu_status_rows(ui: &mut egui::Ui, info: Option<&Value>, adapters: Option<&Value>, obj: &mut Map) { - let t = Tokens::get(ui.ctx()); - ui.add_space(10.0); - ui.label(RichText::new(tl!("Graphics")).font(crate::theme::semibold(12.5)).color(t.text)); - for line in info.and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { - ui.label(RichText::new(line).color(t.text_dim)); - } - ui.add_space(4.0); - ui.label(RichText::new(tl!("Applies at next launch.")).color(t.text_faint)); - ui.collapsing(tl!("Advanced"), |ui| { - ui.horizontal(|ui| { - ui.label(tl!("GPU Backend")); - let mut current = obj.get("gpuBackend").and_then(Value::as_str).unwrap_or("auto").to_string(); - let options = prefs::choices("performance.gpuBackend").unwrap_or(&[]); - let labels: Vec = options.iter().map(|o| choice_label(o)).collect(); - let pairs: Vec<(String, &str)> = options.iter().map(|o| o.to_string()).zip(labels.iter().map(String::as_str)).collect(); - crate::widgets::dropdown(ui, "graphics-backend", tl!("GPU Backend"), &mut current, &pairs, 220.0); - obj.insert("gpuBackend".into(), json!(current)); - }); - if !prefs::is_hidden("performance.gpuAdapter") { - graphics_adapter_row(ui, adapters, obj); - } - }); -} - -/// Preferences › Performance › Graphics Adapter: which GPU draws on a machine with several. The -/// value is the adapter's name; empty is automatic. A saved adapter that isn't present now (an -/// unplugged eGPU) stays listed, marked ⚠, so opening the dialog doesn't silently change the choice. -fn graphics_adapter_row(ui: &mut egui::Ui, adapters: Option<&Value>, obj: &mut Map) { - let mut current = obj.get("gpuAdapter").and_then(Value::as_str).unwrap_or("").to_string(); - let mut names: Vec = adapters.and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); - // A saved name fragment ("nvidia") isn't an adapter's full name but still selects one; only a - // value no listed adapter matches is marked. - let kept = !current.is_empty() && !names.contains(¤t); - let missing = kept && !names.iter().any(|n| prefs::gpu_adapter_matches(n, ¤t)); - if kept { - names.push(current.clone()); - } - let automatic = tl!("Automatic"); - let labels: Vec = names.iter().map(|n| if missing && *n == current { format!("⚠ {n}") } else { n.clone() }).collect(); - let mut pairs: Vec<(String, &str)> = vec![(String::new(), automatic)]; - pairs.extend(names.iter().cloned().zip(labels.iter().map(String::as_str))); - ui.horizontal(|ui| { - ui.label(tl!("GPU adapter")); - crate::widgets::dropdown_literal(ui, "graphics-adapter", tl!("GPU adapter"), &mut current, &pairs, 320.0); - }); - ui.label(RichText::new(tl!("Applies at next launch.")).color(Tokens::get(ui.ctx()).text_faint)); - obj.insert("gpuAdapter".into(), json!(current)); -} - -/// One user-facing choice; legacy flags remain compatible with older settings. -fn rendering_mode_row(ui: &mut egui::Ui, obj: &mut Map) { - let mut current = rendering_mode_value(obj); - ui.horizontal(|ui| { - ui.label(tl!("Rendering Mode")); - let pairs = - vec![("auto".to_string(), tl!("Automatic (recommended)")), ("gpu".to_string(), tl!("GPU")), ("cpu".to_string(), tl!("CPU / Compatibility"))]; - let previous = current.clone(); - crate::widgets::dropdown(ui, "rendering-mode", tl!("Rendering Mode"), &mut current, &pairs, 240.0); - if current != previous { - obj.insert("renderingMode".into(), json!(current)); - obj.insert("useGpu".into(), json!(current != "cpu")); - } - }); - ui.label(tl!("Automatic uses GPU acceleration when available and falls back to CPU rendering on errors.")); - // Next to the setting, as for System Title Bar (#1677): the renderer is picked when the - // window opens, so a change otherwise looks like it did nothing (#7939). - ui.label(RichText::new(tl!("Applies at next launch.")).color(Tokens::get(ui.ctx()).text_dim)); - ui.add_space(8.0); -} - -fn rendering_mode_value(obj: &Map) -> String { - obj.get("renderingMode").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| { - if obj.get("useGpu").and_then(Value::as_bool) == Some(false) || obj.get("gpuBackend").and_then(Value::as_str) == Some("cpu") { - "cpu".into() - } else { - "auto".into() - } - }) -} - -/// Does `section` have any setting the dialog shows (see [`prefs::HIDDEN_UNTIL_IMPLEMENTED`])? -fn has_visible_fields(values: &Value, section: &str) -> bool { - values.get(section).and_then(Value::as_object).is_some_and(|o| o.keys().any(|k| !prefs::is_hidden(&format!("{section}.{k}")))) -} - -/// JPEG and WebP have independent settings; unrelated format controls stay out of view. -fn export_field_visible(obj: &Map, key: &str) -> bool { - let format = obj.get("quickExportFormat").and_then(Value::as_str).unwrap_or("png"); - match key { - "convertToSrgb" | "metadata" => format != "exr", - "jpegQuality" => format == "jpg", - "webpLossless" => format == "webp", - "webpQuality" => format == "webp" && obj.get("webpLossless").and_then(Value::as_bool) != Some(true), - _ => true, - } -} - -/// The pause that bundles arrow-key nudges means nothing with Bundle Arrow-Key Nudges off (#2259). -fn tools_field_visible(obj: &Map, key: &str) -> bool { - key != "nudgeBundlePauseMs" || obj.get("bundleNudges").and_then(Value::as_bool) != Some(false) -} - -/// One theme as a Color Theme swatch: its panel colour under a chrome strip with an accent dot, -/// outlined when chosen. The name is the tooltip and the accessible label. A star badge on its -/// corner adds the theme to (or removes it from) the favourites listed by the appearance -/// button's menu; it shows while the swatch is hovered, and stays for a favourite. -fn theme_swatch(ui: &mut egui::Ui, kind: ThemeKind, id: &str, selected: &mut String, favorites: &mut Vec) { - const BADGE: f32 = 7.0; - let t = Tokens::get(ui.ctx()); - let p = Tokens::for_kind(kind); - let label = tl!(&choice_label(id)).to_string(); - let on = selected.as_str() == id; - let (rect, resp) = ui.allocate_exact_size(vec2(30.0, 26.0), Sense::click()); - let painter = ui.painter(); - let inner = rect.shrink(3.0); - painter.rect_filled(inner, 2.0, p.dock); - painter.rect_filled(egui::Rect::from_min_size(inner.min, vec2(inner.width(), 5.0)), 0.0, p.chrome); - painter.circle_filled(inner.right_bottom() - vec2(6.0, 6.0), 2.5, p.accent); - let stroke = if on { - egui::Stroke::new(2.0, t.accent) - } else if resp.hovered() { - egui::Stroke::new(1.0, t.text_dim) - } else { - egui::Stroke::new(1.0, t.card_border) - }; - painter.rect_stroke(rect.shrink(1.0), 3.0, stroke, egui::StrokeKind::Inside); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, on, &label)); - if resp.on_hover_text(&label).clicked() { - *selected = id.to_string(); - } - let Some(theme) = SavedTheme::parse(id) else { return }; - let favorite = favorites.contains(&theme); - let center = rect.right_top() + vec2(-3.0, 3.0); - let badge = egui::Rect::from_center_size(center, vec2(BADGE * 2.0, BADGE * 2.0)); - if !(favorite || ui.rect_contains_pointer(rect.union(badge))) { - return; - } - ui.painter().circle(center, BADGE, t.card, egui::Stroke::new(1.0, t.card_border)); - let (icon, tint) = if favorite { ("star-filled", t.accent) } else { ("star", t.text_dim) }; - let action = if favorite { tl!("Remove from favorites") } else { tl!("Add to favorites") }; - // Interact and paint without allocating: a widget placed at `badge` would grow the row by the - // 4 px the badge overhangs the swatch, re-centring the swatches after this one whenever the - // pointer arrives, and oscillating when that moves the swatch out from under it. - let response = ui.interact(badge, ui.scope_id().with((id, "favorite")), Sense::click()).on_hover_text(action); - crate::icons::paint(ui, badge, icon, 10.0, tint); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{action}: {label}"))); - if response.clicked() { - if favorite { - favorites.retain(|saved| *saved != theme); - } else { - favorites.push(theme); - } - } -} - -/// A grid row of theme swatches, marked Active when the appearance mode shows this family. -fn theme_row(ui: &mut egui::Ui, title: &str, active: bool, selected: &mut String, favorites: &mut Vec, options: &[(&str, ThemeKind)]) { - let t = Tokens::get(ui.ctx()); - ui.label(RichText::new(tl!(title)).color(t.text_dim)); - ui.horizontal(|ui| { - // Room for the favourite star badges on the swatch corners. - ui.spacing_mut().item_spacing.x = 6.0; - for (id, kind) in options { - theme_swatch(ui, *kind, id, selected, favorites); - } - if active { - ui.add_space(6.0); - ui.label(RichText::new(tl!("Active")).color(t.accent_text).small()); - } - }); - ui.end_row(); -} - -/// Which of the Appearance rows drawn by `appearance_rows` a search shows. -#[derive(Clone, Copy)] -struct AppearanceRows { - mode: bool, - light: bool, - dark: bool, -} - -impl AppearanceRows { - /// `query` is lowercased; empty shows every row. - fn matching(query: &str) -> Self { - let shown = |key: &str| query.is_empty() || preference_matches("interface", key, query); - Self { mode: shown("appearanceMode"), light: shown("lightTheme"), dark: shown("darkTheme") } - } - - fn any(self) -> bool { - self.mode || self.light || self.dark - } -} - -/// Appearance Mode and the light and dark Color Theme swatches, as rows of the Appearance grid. -fn appearance_rows(ui: &mut egui::Ui, obj: &mut Map, system: Option, rows: AppearanceRows) { - let t = Tokens::get(ui.ctx()); - let mut mode = obj.get("appearanceMode").and_then(Value::as_str).unwrap_or("auto").to_string(); - if rows.mode { - ui.label(RichText::new(tl!("Appearance Mode")).color(t.text_dim)); - let choices: [(String, &str); 3] = [("auto".into(), tl!("Sync with system")), ("dark".into(), tl!("Dark")), ("light".into(), tl!("Light"))]; - let pairs: Vec<(String, &str)> = choices.iter().map(|(id, label)| (id.clone(), *label)).collect(); - crate::widgets::dropdown(ui, "appearance-mode", tl!("Appearance Mode"), &mut mode, &pairs, 220.0); - ui.end_row(); - } - let light_active = mode == "light" || (mode == "auto" && system == Some(egui::Theme::Light)); - obj.insert("appearanceMode".into(), json!(mode)); - let mut light = obj.get("lightTheme").and_then(Value::as_str).unwrap_or("studioLight").to_string(); - let mut dark = obj.get("darkTheme").and_then(Value::as_str).unwrap_or("proMedium").to_string(); - let mut favorites: Vec = obj.get("favoriteThemes").cloned().and_then(|v| serde_json::from_value(v).ok()).unwrap_or_default(); - if rows.light { - theme_row(ui, "Light Theme", light_active, &mut light, &mut favorites, LIGHT_THEME_OPTIONS); - } - if rows.dark { - theme_row(ui, "Dark Theme", !light_active, &mut dark, &mut favorites, DARK_THEME_OPTIONS); - } - obj.insert("lightTheme".into(), json!(light)); - obj.insert("darkTheme".into(), json!(dark)); - obj.insert("favoriteThemes".into(), json!(favorites)); -} - -/// A titled, outlined group of settings (Photoshop's Interface page has Appearance, -/// Presentation and Options). -fn pref_group(ui: &mut egui::Ui, title: &str, add: impl FnOnce(&mut egui::Ui)) { - let t = Tokens::get(ui.ctx()); - egui::Frame::new().stroke(egui::Stroke::new(1.0, t.card_border)).corner_radius(t.radius).inner_margin(10.0).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label(RichText::new(tl!(title)).strong().color(t.text)); - ui.add_space(4.0); - add(ui); - }); - ui.add_space(8.0); -} - -/// Preferences › Interface laid out like Photoshop's: the theme and canvas settings, then UI -/// language, font size and scaling, then everything else. Compact enough that the language -/// shows without scrolling in a small window (#2532). A search (`query`, lowercased) hides the -/// rows that don't match and skips a group left empty. -fn interface_groups(ui: &mut egui::Ui, obj: &mut Map, keys: &[String], lang: crate::i18n::Lang, system: Option, query: &str) { - const APPEARANCE: [&str; 3] = ["canvasColor", "canvasCustomColor", "canvasBorder"]; - const PRESENTATION: [&str; 3] = ["language", "uiFontSize", "uiScale"]; - let shown = |k: &str| keys.iter().any(|key| key == k) && field_visible("interface", obj, k, query); - // In Photoshop's order, not the stored one. - let pick = |names: &[&str]| names.iter().filter(|n| shown(n)).map(|n| n.to_string()).collect::>(); - let appearance = pick(&APPEARANCE); - let presentation = pick(&PRESENTATION); - let rest = keys.iter().filter(|k| !APPEARANCE.contains(&k.as_str()) && !PRESENTATION.contains(&k.as_str()) && shown(k)); - // Checkboxes line up at the left edge, as in Photoshop; the other options keep a label column. - let (checks, other): (Vec, Vec) = rest.cloned().partition(|k| obj.get(k).is_some_and(Value::is_boolean)); - let rows = AppearanceRows::matching(query); - let grid = |id: &str| egui::Grid::new(("prefs-grid", id.to_string())).num_columns(2).spacing([14.0, 7.0]).min_col_width(150.0); - if rows.any() || !appearance.is_empty() { - pref_group(ui, "Appearance", |ui| { - grid("interface-appearance").show(ui, |ui| { - appearance_rows(ui, obj, system, rows); - field_rows(ui, "interface", obj, appearance, lang); - }); - }); - } - if !presentation.is_empty() { - pref_group(ui, "Presentation", |ui| { - grid("interface-presentation").show(ui, |ui| field_rows(ui, "interface", obj, presentation, lang)); - }); - } - if !checks.is_empty() || !other.is_empty() { - pref_group(ui, "Options", |ui| { - egui::Grid::new("prefs-grid-interface-checks").num_columns(2).spacing([0.0, 7.0]).show(ui, |ui| field_rows(ui, "interface", obj, checks, lang)); - grid("interface-options").show(ui, |ui| field_rows(ui, "interface", obj, other, lang)); - }); - } -} - -/// Where a clicked colour swatch leaves its preference path and label for the dialog body, which -/// holds the fields the Color Picker request goes in. -const PICK_ID: &str = "prefs-pick-color"; - -/// The colour swatch clicked this frame, if any: (preference path, label). -fn ctx_take_pick(ui: &egui::Ui) -> Option<(String, String)> { - ui.ctx().data_mut(|d| d.remove_temp::<(String, String)>(egui::Id::unique(PICK_ID))) -} - -/// Whether `section.key` gets a generic row for this search (`query`, lowercased; empty matches -/// everything). Settings nothing reads yet stay out of the dialog (issue #204), as do those drawn -/// by their own widgets; their stored values pass through untouched. -fn field_visible(section: &str, obj: &Map, k: &str, query: &str) -> bool { - let path = format!("{section}.{k}"); - let drawn_elsewhere = (section == "interface" && matches!(k, "theme" | "appearanceMode" | "darkTheme" | "lightTheme" | "favoriteThemes")) - // View › Rulers (⌘R) sets it, as in Photoshop. - || path == "unitsAndRulers.showRulers" - || (section == "performance" && matches!(k, "useGpu" | "gpuBackend" | "gpuAdapter" | "renderingMode" | "memoryUsageMb")) - // The browser presents frames itself: Low-Latency Drawing does nothing there. - || (cfg!(target_arch = "wasm32") && path == "performance.lowLatencyDrawing") - || (section == "export" && !export_field_visible(obj, k)) - || (section == "tools" && !tools_field_visible(obj, k)); - (query.is_empty() || preference_matches(section, k, query)) - && !drawn_elsewhere - && !prefs::is_hidden(&path) - && obj.get(k).is_some_and(|v| !matches!(v, Value::Null | Value::Object(_))) -} - -/// Generic editor for a section's fields: checkboxes, dropdowns for choices, colour swatches, -/// number fields with the preference's range, text fields. -fn section_fields( - ui: &mut egui::Ui, - section: &str, - obj: &mut Map, - order: &[String], - lang: crate::i18n::Lang, - system: Option, - search: &str, -) { - let query = search.to_lowercase(); - let mut keys: Vec = order.iter().filter(|k| obj.contains_key(*k)).cloned().collect(); - keys.extend(obj.keys().filter(|k| !order.contains(k)).cloned()); - if section == "interface" { - interface_groups(ui, obj, &keys, lang, system, &query); - return; - } - if section == "performance" && (query.is_empty() || preference_matches(section, "renderingMode", &query)) { - rendering_mode_row(ui, obj); - } - if section == "performance" && (query.is_empty() || preference_matches(section, "memoryUsageMb", &query)) { - memory_usage_row(ui, obj); - } - keys.retain(|k| field_visible(section, obj, k, &query)); - egui::Grid::new(("prefs-grid", section)).num_columns(2).spacing([14.0, 7.0]).show(ui, |ui| field_rows(ui, section, obj, keys, lang)); -} - -/// Explain the per-document RAM limit separately from the graphics-memory preference. -fn memory_usage_row(ui: &mut egui::Ui, obj: &mut Map) { - let t = Tokens::get(ui.ctx()); - ui.group(|ui| { - ui.label(RichText::new(tl!("Memory Usage")).strong()); - let mut mb = obj.get("memoryUsageMb").and_then(Value::as_u64).unwrap_or(8192); - ui.horizontal(|ui| { - let limit_label = ui.label(tl!("Per-document RAM limit (MB)")); - if ui.add(egui::DragValue::new(&mut mb).range(256..=1_048_576).suffix(" MB")).labelled_by(limit_label.id).changed() { - obj.insert("memoryUsageMb".into(), json!(mb)); - } - }); - if let Some(ram) = crate::gpu_canvas::physical_memory().filter(|n| *n > 0) { - let installed = ram / (1 << 20); - let percent = mb as f64 * 100.0 / (ram as f64 / (1 << 20) as f64); - ui.label(crate::i18n::fmt(tl!("Installed RAM: {ram} MB; this limit: {percent}%"), &[("ram", &installed.to_string()), ("percent", &format!("{percent:.1}"))])); - } - ui.label(RichText::new(tl!("Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded.")).color(t.text_dim)); - ui.label(RichText::new(tl!("Applies immediately when saved. Memory is not reserved in advance.")).color(t.text_dim)); - ui.label(RichText::new(tl!("With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget.")).color(t.text_dim)); - }); - ui.add_space(8.0); -} - -/// Settings read only when the app starts, which say "Applies at next launch." under their row. -fn read_at_launch(path: &str) -> bool { - match path { - // Only Windows and Linux draw their own title bar. - "interface.systemTitleBar" => cfg!(all(not(target_arch = "wasm32"), not(target_os = "macos"))), - // The desktop app decides on the control server before its window opens. - "integrations.allowAgentControl" | "integrations.controlPort" => cfg!(not(target_arch = "wasm32")), - _ => false, - } -} - -/// One grid row per setting in `keys` (already filtered by `field_visible`). -fn field_rows(ui: &mut egui::Ui, section: &str, obj: &mut Map, keys: Vec, lang: crate::i18n::Lang) { - let t = Tokens::get(ui.ctx()); - for k in keys { - let path = format!("{section}.{k}"); - let v = obj.get(&k).cloned().unwrap_or(Value::Null); - let human = humanize(&k); - let label = tl!(&human).to_string(); - match &v { - Value::Bool(b) => { - ui.label(""); - let mut b = *b; - if read_at_launch(&path) { - ui.vertical(|ui| { - crate::widgets::checkbox(ui, &mut b, &label); - ui.label(RichText::new(tl!("Applies at next launch.")).color(t.text_dim)); - }); - } else { - crate::widgets::checkbox(ui, &mut b, &label); - } - obj.insert(k, json!(b)); - } - Value::String(s) if path == "interface.language" => { - ui.label(RichText::new(tl!(&label)).color(t.text_dim)); - let mut pairs: Vec<(String, &str)> = vec![("auto".into(), tl!("Auto"))]; - pairs.extend(crate::i18n::Lang::for_picker().into_iter().map(|l| (l.code().to_string(), l.name()))); - let mut cur = s.clone(); - crate::widgets::dropdown(ui, &format!("pref-{path}"), tl!(&label), &mut cur, &pairs, 220.0); - obj.insert(k, json!(cur)); - } - Value::String(s) if prefs::choices(&path).is_some() => { - ui.label(RichText::new(tl!(&label)).color(t.text_dim)); - let opts = prefs::choices(&path).unwrap_or(&[]); - let labels: Vec = opts.iter().map(|o| choice_label(o)).collect(); - let pairs: Vec<(String, &str)> = opts.iter().map(|o| o.to_string()).zip(labels.iter().map(String::as_str)).collect(); - let mut cur = s.clone(); - crate::widgets::dropdown(ui, &format!("pref-{path}"), tl!(&label), &mut cur, &pairs, 220.0); - obj.insert(k, json!(cur)); - } - Value::String(s) if prefs::is_color(&path) => { - ui.label(RichText::new(tl!(&label)).color(t.text_dim)); - let c = prefs::parse_hex(s).unwrap_or([128, 128, 128]); - let mut rgb = c; - ui.horizontal(|ui| { - // PhotoCraft's Color Picker, as everywhere else (#2144). - if crate::widgets::color_swatch_button(ui, egui::Color32::from_rgb(rgb[0], rgb[1], rgb[2]), &label).clicked() { - ui.ctx().data_mut(|d| d.insert_temp(egui::Id::unique(PICK_ID), (path.clone(), label.clone()))); - } - hex_field(ui, &path, &mut rgb); - }); - obj.insert(k, json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]))); - let _ = color_of(s); - } - Value::String(s) => { - ui.label(RichText::new(tl!(&label)).color(t.text_dim)); - let mut s = s.clone(); - ui.add(egui::TextEdit::singleline(&mut s).desired_width(260.0)).accessible_name(tl!(&label)); - obj.insert(k, json!(s)); - } - Value::Number(n) => { - let value_label = ui.label(RichText::new(tl!(&label)).color(t.text_dim)); - let (lo, hi) = prefs::range(&path).unwrap_or((-1e9, 1e9)); - if n.is_u64() || n.is_i64() { - let mut x = n.as_i64().unwrap_or(0); - ui.add(egui::DragValue::new(&mut x).range(lo as i64..=hi as i64).custom_parser(crate::widgets::parse_num)).labelled_by(value_label.id); - obj.insert(k, json!(x)); - // A row of its own, so the label stays level with its field. - if read_at_launch(&path) { - ui.end_row(); - ui.label(""); - ui.label(RichText::new(tl!("Applies at next launch.")).color(t.text_dim)); - } - } else { - let mut x = n.as_f64().unwrap_or(0.0); - ui.add(egui::DragValue::new(&mut x).range(lo..=hi).speed(0.1).max_decimals(3).custom_parser(crate::widgets::parse_num)) - .labelled_by(value_label.id); - obj.insert(k, json!(x)); - } - } - Value::Array(_) if path == "tools.pressureCurve" => { - ui.label(RichText::new(tl!(&label)).color(t.text_dim)); - if let Some(next) = crate::pressure_curve_ui::editor(ui, &v) { - obj.insert(k, next); - } - } - Value::Array(items) if k == "disks" => { - ui.label(RichText::new(tl!("Scratch disks")).color(t.text_dim)); - let mut items = items.clone(); - ui.vertical(|ui| { - for d in &mut items { - ui.horizontal(|ui| { - let mut on = d.get("enabled").and_then(Value::as_bool).unwrap_or(false); - let mut path = d.get("path").and_then(Value::as_str).unwrap_or("").to_string(); - crate::widgets::checkbox(ui, &mut on, tl!("Enabled")); - ui.add(egui::TextEdit::singleline(&mut path).desired_width(240.0)).accessible_name(tl!("Path")); - *d = json!({"enabled": on, "path": path}); - }); - } - if ui.small_button(tl!("Add disk")).clicked() { - items.push(json!({"enabled": true, "path": ""})); - } - }); - obj.insert(k, Value::Array(items)); - } - Value::Array(items) => { - ui.label(RichText::new(tl!(&label)).color(t.text_dim)); - ui.label(RichText::new(crate::i18n::trn(lang, items.len() as u64, "{n} item", "{n} items")).color(t.text_faint)); - if !items.is_empty() && ui.small_button(tl!("Clear")).clicked() { - obj.insert(k, json!([])); - } - } - _ => continue, - } - ui.end_row(); - } -} - -/// Keyboard Shortcuts and Menus: a searchable list of commands by menu with editable shortcuts -/// (click a shortcut, press keys; ⌫ removes it), menu visibility and colours, toolbar tools. -fn shortcuts_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { - let t = Tokens::get(ui.ctx()); - let mut tab = f.get("tab").and_then(Value::as_u64).unwrap_or(0); - ui.horizontal(|ui| { - for (i, name) in [tl!("Keyboard Shortcuts"), tl!("Menus"), tl!("Toolbar")].iter().enumerate() { - if crate::widgets::pill_tab(ui, name, tab == i as u64).clicked() { - tab = i as u64; - f.insert("capture".into(), json!(false)); - } - } - }); - f.insert("tab".into(), json!(tab)); - ui.add_space(6.0); - if tab == 2 { - toolbar_tab(ui, f); - return; - } - // A malformed map (set over automation) is left as it is, so OK rejects it instead of - // saving the empty map drawn in its place. - let parsed = f.get("overrides").map(|v| serde_json::from_value::>(v.clone())); - let overrides_ok = parsed.as_ref().is_none_or(Result::is_ok); - let mut overrides = parsed.and_then(Result::ok).unwrap_or_default(); - // A command's further keys (#3665): id → keys, replacing its default alternates. - let parsed_alts = f.get("alternates").map(|v| serde_json::from_value::>>(v.clone())); - let alternates_ok = parsed_alts.as_ref().is_none_or(Result::is_ok); - let mut alt_overrides = parsed_alts.and_then(Result::ok).unwrap_or_default(); - let mut capture_alt = f.get("captureAlt").and_then(Value::as_bool).unwrap_or(false); - // A key just assigned that another command holds: Photoshop's Accept and Go to Conflict / - // Undo Changes (an object: the key, the other command, and this one's keys before). - let mut conflict: Option = f.get("conflict").filter(|c| c.is_object()).cloned(); - let mut hidden: Vec = f.get("hidden").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); - let mut colors: BTreeMap = f.get("colors").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); - let mut selected = f.get("selected").and_then(Value::as_str).unwrap_or("").to_string(); - let mut capture = f.get("capture").and_then(Value::as_bool).unwrap_or(false); - let mut message = f.get("message").and_then(Value::as_str).unwrap_or("").to_string(); - let mut message_warning = f.get("messageWarning").and_then(Value::as_bool).unwrap_or(false); - let items = shortcut_items(app); - // The Set row, then the search (the Menus tab searches too). - if tab == 0 { - set_row(app, ui, f, &mut overrides, &mut alt_overrides, &items, &mut message, &mut message_warning); - ui.add_space(4.0); - } - let mut filter = f.get("filter").and_then(Value::as_str).unwrap_or("").to_string(); - ui.horizontal(|ui| { - ui.label(RichText::new(tl!("Search")).color(t.text_dim)); - ui.add(egui::TextEdit::singleline(&mut filter).desired_width(260.0).hint_text(tl!("command or shortcut"))); - }); - f.insert("filter".into(), json!(filter)); - // Menu path and command label as shown in the menus, in the UI language. - let shown = |id: &str, label: &str, path: &[String]| -> (Vec, String) { - let lang = crate::i18n::current(); - (path.iter().map(|p| crate::i18n::tr(lang, p).to_string()).collect(), crate::i18n::tr_id(lang, id, label).to_string()) - }; - let eff = |overrides: &BTreeMap, id: &str, def: &Option| -> Option { - match overrides.get(id) { - Some(s) if s.is_empty() => None, - Some(s) => Some(s.clone()), - None => def.clone(), - } - }; - // A command's further keys as the dialog stands: its edited list, else its defaults. - let eff_alts = |alts: &BTreeMap>, id: &str, main: Option<&str>| -> Vec { - let mut p = prefs::Preferences::default(); - if let Some(list) = alts.get(id) { - p.alternate_shortcuts.insert(id.to_string(), list.clone()); - } - p.alternates(id, main) - }; - let mut capture_mods = capture_mods_field(f.get("captureMods")); - // Key capture for the selected command: its main key, or (Add Shortcut) one more key. - if capture && tab == 0 && !selected.is_empty() { - let (next_mods, pressed) = ui.input(|i| capture_key_press(capture_mods, i)); - capture_mods = next_mods; - if let Some((key, m)) = pressed { - ui.input_mut(|i| { - i.consume_key(m, key); - }); - if key == egui::Key::Escape { - capture = false; - conflict = None; - } else if matches!(key, egui::Key::Backspace | egui::Key::Delete) && m.is_none() { - if capture_alt { - alt_overrides.insert(selected.clone(), Vec::new()); - } else { - overrides.insert(selected.clone(), String::new()); - } - capture = false; - message = tl!("Shortcut removed.").into(); - message_warning = false; - } else if let Some(sc) = shortcut_text(key, m).filter(|sc| reserved_shortcut(sc)) { - message = crate::i18n::fmt(tl!("{shortcut} is reserved by the system and can't be assigned."), &[("shortcut", &crate::shortcuts::pretty(&sc))]); - message_warning = true; - capture = false; - } else if let Some(sc) = shortcut_text(key, m) { - let clash_ids: Vec<&str> = items - .iter() - .filter(|(id, _, _, def)| { - let cur = eff(&overrides, id, def); - *id != selected - && (cur.as_deref().and_then(prefs::normalize_shortcut) == Some(sc.clone()) - || eff_alts(&alt_overrides, id, cur.as_deref()).contains(&sc)) - }) - .map(|(id, ..)| id.as_str()) - .collect(); - let clash: Vec = items - .iter() - .filter(|(id, ..)| clash_ids.contains(&id.as_str())) - .map(|(id, label, path, _)| { - let (path, label) = shown(id, label, path); - format!("{} › {}", path.join(" › "), label.trim_end_matches('…')) - }) - .collect(); - // What Undo Changes puts back: the command's main key and further keys as they were. - if let Some(first) = clash_ids.first() { - conflict = Some(json!({ - "shortcut": sc, - "with": first, - // Every command holding the key: Accept takes it from all of them. - "holders": clash_ids, - "command": selected, - "main": overrides.get(&selected), - "alternates": alt_overrides.get(&selected), - })); - } else { - conflict = None; - } - if capture_alt { - let def = items.iter().find(|i| i.0 == selected).and_then(|i| i.3.clone()); - let cur = eff(&overrides, &selected, &def); - let mut keys = eff_alts(&alt_overrides, &selected, cur.as_deref()); - if cur.as_deref().and_then(prefs::normalize_shortcut) != Some(sc.clone()) && !keys.contains(&sc) && keys.len() < prefs::MAX_ALTERNATES { - keys.push(sc.clone()); - } - alt_overrides.insert(selected.clone(), keys); - } else { - overrides.insert(selected.clone(), sc.clone()); - } - message_warning = !clash.is_empty(); - message = if clash.is_empty() { - let template = "{shortcut} assigned."; - crate::i18n::fmt(tl!(template), &[("shortcut", &crate::shortcuts::pretty(&sc))]) - } else { - let template = "{shortcut} is already in use by {commands} and will be removed from it when you click OK."; - crate::i18n::fmt(tl!(template), &[("shortcut", &crate::shortcuts::pretty(&sc)), ("commands", &clash.join(", "))]) - }; - capture = false; - } - } - } - let needle = filter.to_ascii_lowercase(); - egui::ScrollArea::vertical().max_height(420.0).id_salt("shortcuts-scroll").show(ui, |ui| { - let mut last_top = String::new(); - egui::Grid::new("shortcut-grid").num_columns(3).spacing([12.0, 3.0]).striped(true).show(ui, |ui| { - for (id, label, path, def) in &items { - if tab == 1 && crate::tool_shortcuts::tool(id).is_some() { - continue; - } - let cur = eff(&overrides, id, def); - let alts = eff_alts(&alt_overrides, id, cur.as_deref()); - let (shown_path, shown_label) = shown(id, label, path); - // Match what is shown and the English name (commands are documented in English). - let hay = - format!("{} {} {} {} {} {}", shown_path.join(" "), shown_label, path.join(" "), label, cur.clone().unwrap_or_default(), alts.join(" ")) - .to_lowercase(); - if !needle.is_empty() && !hay.contains(&needle) && !id.to_ascii_lowercase().contains(&needle) { - continue; - } - if tab == 0 && path.is_empty() && def.is_none() && cur.is_none() && alts.is_empty() { - continue; - } - let top = shown_path.first().cloned().unwrap_or_else(|| tl!("Other").into()); - if top != last_top { - ui.label(RichText::new(&top).font(crate::theme::semibold(12.5)).color(t.text)); - ui.label(""); - ui.label(""); - ui.end_row(); - last_top = top; - } - let name = match shown_path.get(1..) { - Some(rest) if !rest.is_empty() => format!("{} › {}", rest.join(" › "), shown_label), - _ => shown_label, - }; - let sel = selected == *id; - let name_row = ui.selectable_label(sel, RichText::new(format!(" {name}")).color(t.text_dim)); - if name_row.clicked() { - selected = id.clone(); - } - if tab == 0 { - let text = if sel && capture && !capture_alt { - tl!("Press keys…").to_string() - } else { - cur.as_deref().map(crate::shortcuts::pretty).unwrap_or_default() - }; - let changed = overrides.contains_key(id) || alt_overrides.contains_key(id); - let r = ui.add( - egui::Button::new(RichText::new(tl!(&text)).size(12.0).color(if changed { t.accent_text } else { t.text })).min_size(vec2(120.0, 18.0)), - ); - // An unassigned shortcut shows no text: name it by the command it binds. - let r = if text.is_empty() { r.labelled_by(name_row.id) } else { r }; - if r.clicked() { - selected = id.clone(); - capture = true; - capture_alt = false; - message.clear(); - message_warning = false; - } - // The further keys (F3 beside ⌘C), each removable on its own, as Photoshop - // lists them as rows of their own (#3665). - ui.horizontal(|ui| { - for k in &alts { - let b = egui::Button::new(RichText::new(format!("{} ×", crate::shortcuts::pretty(k))).size(11.0).color(t.text)).small(); - if ui.add(b).on_hover_text(tl!("Delete Shortcut")).clicked() { - alt_overrides.insert(id.clone(), alts.iter().filter(|x| *x != k).cloned().collect()); - selected = id.clone(); - message = tl!("Shortcut removed.").into(); - message_warning = false; - } - } - if sel && capture && capture_alt { - ui.label(RichText::new(tl!("Press keys…")).size(11.0).color(t.accent_text)); - } - if changed { - ui.label(RichText::new(tl!("modified")).color(t.text_faint).size(10.5)); - } - }); - } else { - // Edit › Menus, Keyboard Shortcuts, Preferences, Save and Exit always stay (#5096). - let hideable = photocraft_engine::prefs::MenuCustomization::hideable(id); - let mut visible = !hideable || !hidden.contains(id); - ui.add_enabled_ui(hideable, |ui| crate::widgets::checkbox(ui, &mut visible, tl!("Visible"))); - if visible { - hidden.retain(|h| h != id); - } else if !hidden.contains(id) { - hidden.push(id.clone()); - } - let mut col = colors.get(id).cloned().unwrap_or_else(|| "none".into()); - let opts: Vec<(String, &str)> = - ["none", "red", "orange", "yellow", "green", "blue", "violet", "gray"].iter().map(|c| (c.to_string(), *c)).collect(); - crate::widgets::dropdown(ui, &format!("menu-color-{id}"), tl!("Color"), &mut col, &opts, 90.0); - if col == "none" { - colors.remove(id); - } else { - colors.insert(id.clone(), col); - } - } - ui.end_row(); - } - }); - }); - ui.add_space(6.0); - if tab == 0 { - ui.horizontal(|ui| { - let has_sel = !selected.is_empty(); - if ui.add_enabled(has_sel, egui::Button::new(tl!("Add Shortcut"))).clicked() { - capture = true; - capture_alt = true; - message.clear(); - message_warning = false; - } - if ui.add_enabled(has_sel, egui::Button::new(tl!("Use Default"))).clicked() { - overrides.remove(&selected); - alt_overrides.remove(&selected); - message = tl!("Default restored.").into(); - message_warning = false; - } - if ui.add_enabled(has_sel, egui::Button::new(tl!("Delete Shortcut"))).clicked() { - overrides.insert(selected.clone(), String::new()); - message = tl!("Shortcut removed.").into(); - message_warning = false; - } - if ui.button(tl!("Reset All to Defaults")).clicked() { - overrides.clear(); - alt_overrides.clear(); - message = tl!("All shortcuts reset to PhotoCraft defaults.").into(); - message_warning = false; - } - // A Photoshop set (`.kys`) fills the overrides; the file arrives after this frame - // and `kys_import` writes the dialog's fields then (#1163). - if ui.button(tl!("Import Shortcuts…")).on_hover_text(tl!("Load a keyboard shortcut set saved as .kys")).clicked() - && let Err(e) = crate::kys_import::import_dialog(app) - { - message = e; - message_warning = false; - } - }); - } else if ui.button(tl!("Show All Menu Items")).clicked() { - hidden.clear(); - colors.clear(); - } - if !message.is_empty() { - ui.label(RichText::new(&message).color(if message_warning { t.warning } else { t.text_dim })); - } - // The conflict describes the bindings as the capture left them: any later change (Use - // Default, Delete, ×, Reset All, another command or set) makes it stale, and it goes. - let state = conflict_state(&overrides, &alt_overrides, &selected, f.get("activeSet")); - if conflict.as_ref().and_then(|c| c.get("state")).is_some_and(|s| s.as_u64() != Some(state)) { - conflict = None; - } - if tab == 0 - && let Some(c) = conflict.clone() - { - let (key, with, command) = - (c["shortcut"].as_str().unwrap_or_default(), c["with"].as_str().unwrap_or_default(), c["command"].as_str().unwrap_or_default()); - ui.horizontal(|ui| { - if ui.button(tl!("Accept and Go to Conflict")).on_hover_text(tl!("Take the shortcut from the other command and select it")).clicked() { - let holders: Vec = serde_json::from_value(c["holders"].clone()).unwrap_or_else(|_| vec![with.to_string()]); - for holder in &holders { - let def = items.iter().find(|i| i.0 == *holder).and_then(|i| i.3.clone()); - let cur = eff(&overrides, holder, &def); - if cur.as_deref().and_then(prefs::normalize_shortcut).as_deref() == Some(key) { - overrides.insert(holder.clone(), String::new()); - } - let keys = eff_alts(&alt_overrides, holder, eff(&overrides, holder, &def).as_deref()); - if keys.iter().any(|k| k == key) { - alt_overrides.insert(holder.clone(), keys.into_iter().filter(|k| k != key).collect()); - } - } - selected = with.to_string(); - filter.clear(); - message = tl!("Choose a new shortcut for this command, or leave it without one.").into(); - message_warning = false; - conflict = None; - } - if ui.button(tl!("Undo Changes")).on_hover_text(tl!("Put this command's shortcuts back as they were")).clicked() { - match c["main"].as_str() { - Some(m) => overrides.insert(command.to_string(), m.to_string()), - None => overrides.remove(command), - }; - match serde_json::from_value::>(c["alternates"].clone()) { - Ok(list) => alt_overrides.insert(command.to_string(), list), - Err(_) => alt_overrides.remove(command), - }; - selected = command.to_string(); - message = tl!("Changes undone.").into(); - message_warning = false; - conflict = None; - } - }); - } - if overrides_ok { - f.insert("overrides".into(), json!(overrides)); - } - if alternates_ok { - f.insert("alternates".into(), json!(alt_overrides)); - } - f.insert("captureAlt".into(), json!(capture && capture_alt)); - // A conflict just found is stamped with the bindings it describes. - if let Some(c) = conflict.as_mut().filter(|c| c.get("state").is_none()) { - c["state"] = json!(conflict_state(&overrides, &alt_overrides, &selected, f.get("activeSet"))); - } - f.insert("conflict".into(), conflict.unwrap_or(Value::Null)); - f.insert("hidden".into(), json!(hidden)); - f.insert("colors".into(), json!(colors)); - f.insert("selected".into(), json!(selected)); - f.insert("capture".into(), json!(capture)); - if capture { - f.insert("captureMods".into(), capture_mods_json(capture_mods)); - } else { - f.remove("captureMods"); - } - f.insert("message".into(), json!(message)); - f.insert("messageWarning".into(), json!(message_warning)); -} - -/// A command's keys as the dialog stands, main key first: the edited main key (or its default) -/// and its further keys. -fn dialog_keys(overrides: &BTreeMap, alternates: &BTreeMap>, id: &str, default: Option<&str>) -> Vec { - let main = match overrides.get(id) { - Some(s) if s.is_empty() => None, - Some(s) => Some(s.as_str()), - None => default, - }; - let mut p = prefs::Preferences::default(); - if let Some(list) = alternates.get(id) { - p.alternate_shortcuts.insert(id.to_string(), list.clone()); - } - let mut keys: Vec = main.and_then(prefs::normalize_shortcut).into_iter().collect(); - keys.extend(p.alternates(id, main)); - keys -} - -/// Edit › Keyboard Shortcuts › Set, as in Photoshop: choose a saved set (its bindings replace -/// the dialog's), save the bindings as a new set or over the one in use, delete it, export it as -/// a `.kys` file or summarize it as an HTML page. Everything but Export and Summarize waits for -/// OK, like the rest of the dialog. -#[allow(clippy::too_many_arguments)] -fn set_row( - app: &mut PhotocraftApp, - ui: &mut egui::Ui, - f: &mut Map, - overrides: &mut BTreeMap, - alternates: &mut BTreeMap>, - items: &[(String, String, Vec, Option)], - message: &mut String, - warning: &mut bool, -) { - use photocraft_engine::shortcut_sets::{self, ShortcutSet}; - let mut sets: BTreeMap = f.get("sets").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); - let mut active = f.get("activeSet").and_then(Value::as_str).unwrap_or("").to_string(); - if !active.is_empty() && !sets.contains_key(&active) { - active.clear(); - } - // The engine decides what a set holds and when it is modified (not the actions' F-keys). - let now = ShortcutSet::from_bindings(overrides, alternates); - let modified = shortcut_sets::differs(&sets, &active, overrides, alternates); - let defaults = tl!("PhotoCraft Defaults").to_string(); - let shown = |name: &str| -> String { - let base = if name.is_empty() { defaults.clone() } else { name.to_string() }; - if name == active && modified { crate::i18n::fmt(tl!("{set} (modified)"), &[("set", &base)]) } else { base } - }; - let names: Vec<(String, String)> = std::iter::once(String::new()).chain(sets.keys().cloned()).map(|n| (n.clone(), shown(&n))).collect(); - let mut new_name: Option = f.get("newSetName").and_then(Value::as_str).map(str::to_string); - let set_label = if active.is_empty() { defaults.clone() } else { active.clone() }; - let mut export = false; - let mut summarize = false; - ui.horizontal(|ui| { - ui.label(tl!("Set:")); - let mut chosen = active.clone(); - let pairs: Vec<(String, &str)> = names.iter().map(|(n, l)| (n.clone(), l.as_str())).collect(); - if crate::widgets::dropdown(ui, "shortcut-set", tl!("Set:"), &mut chosen, &pairs, 220.0) && chosen != active { - // As `useSet`: the set's bindings, keeping the actions' F-keys. - sets.get(&chosen).cloned().unwrap_or_default().apply(overrides, alternates); - active = chosen; - message.clear(); - } - if ui.button(tl!("New Set…")).on_hover_text(tl!("Save these shortcuts as a new set")).clicked() { - new_name = Some(String::new()); - } - if ui.add_enabled(!active.is_empty() && modified, egui::Button::new(tl!("Save"))).on_hover_text(tl!("Save the changes to this set")).clicked() { - sets.insert(active.clone(), now.clone()); - *message = tl!("Set saved.").into(); - *warning = false; - } - if ui.add_enabled(!active.is_empty(), egui::Button::new(tl!("Delete"))).on_hover_text(tl!("Delete this set")).clicked() { - sets.remove(&active); - active.clear(); - *message = tl!("Set deleted.").into(); - *warning = false; - } - export = ui.button(tl!("Export…")).on_hover_text(tl!("Save these shortcuts as a .kys file")).clicked(); - summarize = ui.button(tl!("Summarize…")).on_hover_text(tl!("Save a list of these shortcuts as a web page")).clicked(); - }); - if let Some(name) = new_name.as_mut() { - let mut create = false; - let mut cancel = false; - ui.horizontal(|ui| { - ui.label(tl!("Name:")); - let r = ui.add(egui::TextEdit::singleline(name).desired_width(220.0).hint_text(tl!("set name"))); - create = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); - create |= ui.button(tl!("Create")).clicked(); - cancel = ui.button(tl!("Cancel")).clicked(); - }); - if create { - match shortcut_sets::set_name(name) { - Ok(n) if !sets.contains_key(&n) && sets.len() >= shortcut_sets::MAX_SETS => { - *message = tl!("There are too many sets: delete one first.").into(); - *warning = true; - } - Ok(n) => { - sets.insert(n.clone(), now.clone()); - active = n; - new_name = None; - *message = tl!("Set saved.").into(); - *warning = false; - } - Err(e) => { - *message = e; - *warning = true; - } - } - } else if cancel { - new_name = None; - } - } - if export || summarize { - let result = if export { - let entries: Vec = items - .iter() - .map(|(id, label, _, def)| photocraft_engine::kys::Entry { - id: id.clone(), - label: label.clone(), - tool: id.starts_with("tools.select."), - keys: dialog_keys(overrides, alternates, id, def.as_deref()), - }) - .collect(); - let text = photocraft_engine::kys::write(&set_label, &entries); - save_text(app, &format!("{set_label}.kys"), text) - } else { - let mut sections: Vec = Vec::new(); - for (id, label, path, def) in items { - let section = path.first().cloned().unwrap_or_else(|| tl!("Other").to_string()); - let name = path.iter().skip(1).chain(std::iter::once(label)).cloned().collect::>().join(" › "); - let row = (name, dialog_keys(overrides, alternates, id, def.as_deref())); - match sections.iter_mut().find(|(s, _)| *s == section) { - Some((_, rows)) => rows.push(row), - None => sections.push((section, vec![row])), - } - } - let html = shortcut_sets::summarize(&set_label, §ions, cfg!(target_os = "macos")); - save_text(app, &format!("{set_label}.html"), html) - }; - if let Err(e) = result { - *message = e; - *warning = true; - } - } - f.insert("sets".into(), json!(sets)); - f.insert("activeSet".into(), json!(active)); - f.insert("newSetName".into(), new_name.map_or(Value::Null, Value::String)); -} - -/// Save `text` through the save dialog under the suggested file name. -fn save_text(app: &mut PhotocraftApp, suggested: &str, text: String) -> Result { - // A set name can hold characters a file name can't. - let name: String = suggested.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c }).collect(); - app.pick_save(&name, move |app, path| { - let write = app.services.write.as_mut().ok_or("no writer configured")?; - write(&path, text.as_bytes())?; - Ok(json!({"path": path})) - }) -} - -fn toolbar_tab(ui: &mut egui::Ui, f: &mut Map) { - let mut hidden: Vec = f.get("toolbarHidden").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); - egui::ScrollArea::vertical().max_height(380.0).id_salt("toolbar-scroll").show(ui, |ui| { - egui::Grid::new("toolbar-grid").num_columns(2).spacing([16.0, 4.0]).show(ui, |ui| { - for tool in crate::state::Tool::ALL { - let name = format!("{tool:?}"); - let mut on = !hidden.contains(&name); - crate::widgets::checkbox(ui, &mut on, tl!(tool.label())); - if on { - hidden.retain(|h| *h != name); - } else if !hidden.contains(&name) { - hidden.push(name); - } - let k = tool.key(); - ui.label(if k == '\0' { String::new() } else { k.to_string() }); - ui.end_row(); - } - }); - }); - if ui.button(tl!("Restore Defaults")).clicked() { - hidden.clear(); - } - f.insert("toolbarHidden".into(), json!(hidden)); -} - -fn presets_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { - let t = Tokens::get(ui.ctx()); - let mut kind = f.get("kind").and_then(Value::as_str).unwrap_or("brushes").to_string(); - ui.horizontal(|ui| { - ui.label(RichText::new(tl!("Preset Type")).color(t.text_dim)); - let opts = [("brushes".to_string(), tl!("Brushes")), ("customShapes".to_string(), tl!("Custom Shapes")), ("patterns".to_string(), tl!("Patterns"))]; - crate::widgets::dropdown(ui, "preset-kind", tl!("Type"), &mut kind, &opts, 180.0); - }); - let list = app - .session - .execute("edit.presets.presetManager", json!({"kind": kind})) - .ok() - .and_then(|v| v.get(&kind).cloned()) - .and_then(|v| serde_json::from_value::>(v).ok()) - .unwrap_or_default(); - let mut selected = f.get("selected").and_then(Value::as_u64).unwrap_or(0) as usize; - egui::ScrollArea::vertical().max_height(260.0).id_salt("preset-list").show(ui, |ui| { - for (i, name) in list.iter().enumerate() { - if ui.selectable_label(i == selected, name).clicked() { - selected = i; - f.insert("newName".into(), json!(name)); - } - } - if list.is_empty() { - ui.label(RichText::new(tl!("No presets of this type.")).color(t.text_faint)); - } - }); - let mut new_name = f.get("newName").and_then(Value::as_str).unwrap_or("").to_string(); - ui.horizontal(|ui| { - ui.add(egui::TextEdit::singleline(&mut new_name).desired_width(200.0)).accessible_name(tl!("Name")); - if ui.add_enabled(selected < list.len() && !new_name.trim().is_empty(), egui::Button::new(tl!("Rename"))).clicked() { - let _ = app.run("edit.presets.presetManager", json!({"action": "rename", "kind": kind, "index": selected, "newName": new_name})); - } - if ui.add_enabled(selected < list.len(), egui::Button::new(tl!("Delete"))).clicked() { - let _ = app.run("edit.presets.presetManager", json!({"action": "delete", "kind": kind, "index": selected})); - } - // Load Photoshop brushes (.abr) into the library. - if kind == "brushes" && ui.button(tl!("Load…")).on_hover_text(tl!("Import brushes (.abr)")).clicked() { - let _ = app.open_dialog_file(); - } - }); - f.insert("kind".into(), json!(kind)); - f.insert("selected".into(), json!(selected)); - f.insert("newName".into(), json!(new_name)); -} - -fn presets_io_body(ui: &mut egui::Ui, f: &mut Map) { - let t = Tokens::get(ui.ctx()); - let mut action = f.get("action").and_then(Value::as_str).unwrap_or("export").to_string(); - ui.horizontal(|ui| { - ui.label(RichText::new(tl!("Action")).color(t.text_dim)); - crate::widgets::dropdown( - ui, - "presets-io", - tl!("Action"), - &mut action, - &[("export".to_string(), tl!("Export Presets")), ("import".to_string(), tl!("Import Presets"))], - 180.0, - ); - }); - for (k, label) in [("brushes", tl!("Brushes")), ("customShapes", tl!("Custom Shapes")), ("tools", tl!("Tool Presets"))] { - let mut on = f.get(k).and_then(Value::as_bool).unwrap_or(true); - crate::widgets::checkbox(ui, &mut on, label); - f.insert(k.into(), json!(on)); - } - f.insert("action".into(), json!(action)); -} - -fn mismatch_body(ui: &mut egui::Ui, f: &mut Map) { - let t = Tokens::get(ui.ctx()); - ui.label(RichText::new(f.get("message").and_then(Value::as_str).unwrap_or("")).color(t.text)); - ui.add_space(6.0); - let mut action = f.get("action").and_then(Value::as_str).unwrap_or("preserve").to_string(); - let missing = f.get("missing").and_then(Value::as_bool).unwrap_or(false); - let name = |k: &str| f.get(k).and_then(Value::as_str).unwrap_or("?").to_string(); - let opts: Vec<(&str, String)> = if missing { - vec![("preserve", tl!("Leave as is (don't color manage)").into()), ("assignWorking", tl!("Assign working space").into())] - } else { - vec![ - ("preserve", crate::i18n::fmt(tl!("Use the embedded profile ({profile})"), &[("profile", &name("embedded"))])), - ("convert", crate::i18n::fmt(tl!("Convert to the working space ({profile})"), &[("profile", &name("working"))])), - ("discard", tl!("Discard the embedded profile (don't color manage)").into()), - ] - }; - for (v, label) in opts { - ui.radio_value(&mut action, v.to_string(), label); - } - f.insert("action".into(), json!(action)); - // Remembering sets the Color Settings policy and stops asking, so it needs a mode with a policy. - if !missing && f.get("policyKey").is_some_and(Value::is_string) { - ui.add_space(8.0); - let mut remember = f.get("remember").and_then(Value::as_bool).unwrap_or(false); - crate::widgets::checkbox(ui, &mut remember, tl!("Remember this choice for future images")) - .on_hover_text(tl!("Turn the prompt back on with Ask On Mismatch in Edit › Color Settings.")); - f.insert("remember".into(), json!(remember)); - } -} - -// ------------------------------------------------------------------ confirm - -/// OK on one of our dialogs. -pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { - match f.get("__prefsui").and_then(Value::as_str).unwrap_or("") { - "prefs" => { - let values = f.get("values").cloned().unwrap_or(Value::Null); - app.run("prefs.set", json!({"path": "", "value": values})) - } - "shortcuts" => { - let overrides = f.get("overrides").cloned().unwrap_or(json!({})); - // Shortcuts moved to another command are taken from their old owner (shell - // commands included, which the engine doesn't know). - // The map replaces every stored override, so a malformed one is an error, not "none". - let mut ov: BTreeMap = - serde_json::from_value(overrides).map_err(|e| format!("overrides must map command IDs to shortcut strings: {e}"))?; - let alternates = f.get("alternates").cloned().unwrap_or(json!({})); - let mut alt: BTreeMap> = - serde_json::from_value(alternates).map_err(|e| format!("alternates must map command IDs to lists of shortcuts: {e}"))?; - let items = shortcut_items(app); - // Newly assigned shortcuts are checked first and take theirs from any holder, custom - // overrides included; unchanged overrides only take theirs from defaults. A - // command's further keys (#3665) take and lose keys the same way. - let before = &app.session.prefs().shortcuts; - let before_alt = &app.session.prefs().alternate_shortcuts; - let mut todo: Vec<(String, String, bool, bool)> = - ov.iter().filter(|(_, s)| !s.is_empty()).map(|(k, s)| (k.clone(), s.clone(), before.get(k) != Some(s), false)).collect(); - for (k, keys) in &alt { - let new = before_alt.get(k) != Some(keys); - todo.extend(keys.iter().map(|s| (k.clone(), s.clone(), new, true))); - } - todo.sort_by_key(|(_, _, new, _)| !new); - let main_of = |ov: &BTreeMap, id: &str, def: Option<&str>| -> Option { - match ov.get(id) { - Some(s) if s.is_empty() => None, - Some(s) => Some(s.clone()), - None => def.map(str::to_string), - } - }; - for (id, sc, new, is_alt) in todo { - let norm = prefs::normalize_shortcut(&sc); - let Some(norm) = norm else { continue }; - // Taken by a newer assignment? - if (!is_alt && ov.get(&id).is_some_and(String::is_empty)) || (is_alt && alt.get(&id).is_some_and(|k| !k.contains(&norm))) { - continue; - } - for (other, _, _, def) in &items { - if *other == id { - continue; - } - let held = match ov.get(other) { - Some(s) if new => Some(s.as_str()), - Some(_) => None, - None => def.as_deref(), - }; - if held.and_then(prefs::normalize_shortcut).as_deref() == Some(norm.as_str()) { - ov.insert(other.clone(), String::new()); - } - // Its further keys: the edited list when this assignment is new, else only - // the defaults. - if alt.contains_key(other) && !new { - continue; - } - let mut p = prefs::Preferences::default(); - if let Some(list) = alt.get(other) { - p.alternate_shortcuts.insert(other.clone(), list.clone()); - } - let keys = p.alternates(other, main_of(&ov, other, def.as_deref()).as_deref()); - if keys.contains(&norm) { - alt.insert(other.clone(), keys.into_iter().filter(|k| *k != norm).collect()); - } - } - } - let hidden = f.get("hidden").cloned().unwrap_or(json!([])); - let colors = f.get("colors").cloned().unwrap_or(json!({})); - let toolbar = f.get("toolbarHidden").cloned().unwrap_or(json!([])); - let sets = f.get("sets").cloned().unwrap_or(json!({})); - let active = f.get("activeSet").cloned().unwrap_or(json!("")); - app.run( - "edit.keyboardShortcuts", - json!({"reset": true, "set": ov, "alternates": alt, "allowUnknown": true, "removeConflicts": false, "sets": sets, "activeSet": active}), - )?; - app.run("prefs.set", json!({"values": {"menus": {"hidden": hidden, "colors": colors}, "toolbar": {"hidden": toolbar}}})) - } - "presets" => Ok(Value::Null), - "presetsIO" => { - let kinds: Vec<&str> = ["brushes", "customShapes", "tools"].into_iter().filter(|k| f.get(*k).and_then(Value::as_bool).unwrap_or(true)).collect(); - if f.get("action").and_then(Value::as_str) == Some("import") { - app.pick_file_bytes(move |app, name, bytes| { - let text = String::from_utf8(bytes).map_err(|_| format!("{name} is not a preset file"))?; - app.run("edit.presets.exportImportPresets", json!({"action": "import", "kinds": kinds, "data": text})) - }) - } else { - let out = app.run("edit.presets.exportImportPresets", json!({"action": "export", "kinds": kinds}))?; - let text = serde_json::to_string_pretty(&out["data"]).map_err(|e| e.to_string())?; - app.pick_save("Presets.pcpresets", move |app, path| { - let write = app.services.write.as_mut().ok_or("no writer configured")?; - write(&path, text.as_bytes())?; - let template = "Exported presets to {path}"; - app.ui.status = crate::i18n::fmt(tl!(template), &[("path", &path)]); - Ok(json!({"path": path})) - }) - } - } - // The file it asks about opens with this answer (`open_prompt`). - "mismatch" => { - let action = f.get("action").and_then(Value::as_str).unwrap_or("preserve"); - if f.get("remember").and_then(Value::as_bool) == Some(true) { - return crate::open_prompt::answer_remembering(app, action); - } - crate::open_prompt::answer(app, Some(action)) - } - _ => Err("unknown dialog".into()), - } -} +mod appearance; +mod dialogs; +mod fields; +mod graphics; +mod save; +mod shortcuts; +mod startup; + +#[cfg(test)] +use appearance::{DARK_THEME_OPTIONS, LIGHT_THEME_OPTIONS, display_scale, favorite_theme_groups, selected_theme}; +pub(crate) use appearance::{appearance_context_menu, cycle_appearance, step_brightness, sync_appearance}; +pub use appearance::{canvas_style, pasteboard_color}; +pub use dialogs::{ + PREFERENCES_SIZE, apply, confirm, invoke, is_preferences, open_mismatch, open_preferences, open_shortcuts, owns, preferences_changed, width, +}; +#[cfg(test)] +use dialogs::{preference_values, presets_io_body, settings_height}; +pub use fields::body; +#[cfg(test)] +use fields::{ + choice_label, export_field_visible, field_visible, has_visible_fields, hex_field, humanize, preference_sections, section_fields, tools_field_visible, +}; +#[cfg(test)] +use graphics::{gpu_status_rows, rendering_mode_value}; +use save::SaveRetry; +pub(crate) use save::save_preferences; +#[cfg(test)] +use save::{SAVE_RETRY_MAX_S, SAVE_RETRY_S, merge_changes, persist}; +pub use save::{autosave_now, tick}; +#[cfg(test)] +pub(crate) use shortcuts::capture_key_press; +pub use shortcuts::{is_modifier_key, reserved_shortcut, shortcut_items, shortcut_text}; +pub use startup::load; +pub(crate) use startup::{on_recovery_event, remember_rulers}; // Test modules stay after the production code: the prefs_usage test reads each file up to // its first `#[cfg(test)] mod`. diff --git a/crates/ui-egui/src/prefs_ui/appearance.rs b/crates/ui-egui/src/prefs_ui/appearance.rs new file mode 100644 index 0000000000..bf08302397 --- /dev/null +++ b/crates/ui-egui/src/prefs_ui/appearance.rs @@ -0,0 +1,330 @@ +use super::dialogs::open_preferences; +use super::fields::{choice_label, color_of, preference_matches}; +use super::*; + +/// The GPU canvas colours from Preferences › Transparency & Gamut. +pub fn canvas_style(app: &PhotocraftApp) -> crate::gpu_canvas::CanvasStyle { + let t = &app.session.prefs().transparency_and_gamut; + let [l, d] = t.colors(); + let f = |c: [u8; 3]| c.map(|v| v as f32 / 255.0); + let g = prefs::parse_hex(&t.gamut_warning_color).unwrap_or([128; 3]); + crate::gpu_canvas::CanvasStyle { + checker_square: t.square().unwrap_or(0.0), + checker_light: f(l), + checker_dark: f(d), + gamut_color: f(g), + gamut_opacity: t.gamut_warning_opacity as f32 / 100.0, + } +} + +/// Pasteboard colour from Preferences › Interface (`None` = the theme's default canvas). +pub fn pasteboard_color(app: &PhotocraftApp) -> Option { + use prefs::CanvasColor; + let i = &app.session.prefs().interface; + Some(match i.canvas_color { + CanvasColor::Default => return None, + CanvasColor::Black => Color32::BLACK, + CanvasColor::DarkGray => Color32::from_gray(40), + CanvasColor::MediumGray => Color32::from_gray(83), + CanvasColor::LightGray => Color32::from_gray(184), + CanvasColor::Custom => color_of(&i.canvas_custom_color), + }) +} + +pub(super) fn selected_theme(interface: &prefs::Interface, system: Option) -> ThemeKind { + let light = match interface.appearance_mode { + AppearanceMode::Light => true, + AppearanceMode::Dark => false, + AppearanceMode::Auto => system == Some(egui::Theme::Light), + }; + if light { + match interface.light_theme { + LightTheme::StudioLight => ThemeKind::StudioLight, + LightTheme::ProLightGray => ThemeKind::ProLightGray, + LightTheme::ProLight => ThemeKind::ProLight, + LightTheme::Classic => ThemeKind::Classic, + LightTheme::Adwaita => ThemeKind::Adwaita, + LightTheme::BreezeLight => ThemeKind::BreezeLight, + LightTheme::SoftLight => ThemeKind::SoftLight, + } + } else { + match interface.dark_theme { + DarkTheme::Pro => ThemeKind::Pro, + DarkTheme::ProMedium => ThemeKind::ProMedium, + DarkTheme::Studio => ThemeKind::Studio, + DarkTheme::SolarizedDark => ThemeKind::SolarizedDark, + DarkTheme::AdwaitaDark => ThemeKind::AdwaitaDark, + DarkTheme::BreezeDark => ThemeKind::BreezeDark, + DarkTheme::SoftDark => ThemeKind::SoftDark, + } + } +} + +pub(crate) fn cycle_appearance(app: &mut PhotocraftApp, ctx: &egui::Context) { + let next = match app.session.prefs().interface.appearance_mode { + AppearanceMode::Auto => AppearanceMode::Light, + AppearanceMode::Light => AppearanceMode::Dark, + AppearanceMode::Dark => AppearanceMode::Auto, + }; + if let Err(e) = app.run("prefs.set", json!({"path": "interface.appearanceMode", "value": next.name()})) { + app.ui.status = e; + return; + } + let selected = selected_theme(&app.session.prefs().interface, system_theme(app, ctx)); + if app.ui.theme != selected { + app.apply_theme(ctx, selected); + } +} + +/// Photoshop's four interface brightnesses, darkest first. +const BRIGHTNESSES: [ThemeKind; 4] = [ThemeKind::Pro, ThemeKind::ProMedium, ThemeKind::ProLightGray, ThemeKind::ProLight]; + +/// Darken Interface (⇧⌘F1, `lighter` false) and Lighten Interface (⇧⌘F2): the next of +/// Photoshop's four brightnesses from the theme on screen, stopping at either end, as in +/// Photoshop. Another theme steps from the nearest brightness: Medium Gray for a dark one, Light +/// Gray for a light one. The choice is saved like picking it in Preferences › Interface. +pub(crate) fn step_brightness(app: &mut PhotocraftApp, ctx: &egui::Context, lighter: bool) -> Result<(), String> { + let current = app.ui.theme; + let at = BRIGHTNESSES.iter().position(|k| *k == current).unwrap_or(if crate::theme::Tokens::for_kind(current).dark() { 1 } else { 2 }); + let next = if lighter { (at + 1).min(BRIGHTNESSES.len() - 1) } else { at.saturating_sub(1) }; + let Some(&kind) = BRIGHTNESSES.get(next) else { return Ok(()) }; + if kind == current { + return Ok(()); + } + app.run("prefs.set", json!({"path": "interface.theme", "value": kind.id()}))?; + sync_appearance(app, ctx); + Ok(()) +} + +pub(super) const LIGHT_THEME_OPTIONS: &[(&str, ThemeKind)] = &[ + ("proLight", ThemeKind::ProLight), + ("proLightGray", ThemeKind::ProLightGray), + ("studioLight", ThemeKind::StudioLight), + ("classic", ThemeKind::Classic), + ("adwaita", ThemeKind::Adwaita), + ("breezeLight", ThemeKind::BreezeLight), + ("softLight", ThemeKind::SoftLight), +]; + +pub(super) const DARK_THEME_OPTIONS: &[(&str, ThemeKind)] = &[ + ("proMedium", ThemeKind::ProMedium), + ("pro", ThemeKind::Pro), + ("studio", ThemeKind::Studio), + ("solarizedDark", ThemeKind::SolarizedDark), + ("adwaitaDark", ThemeKind::AdwaitaDark), + ("breezeDark", ThemeKind::BreezeDark), + ("softDark", ThemeKind::SoftDark), +]; + +pub(super) fn favorite_theme_groups(favorites: &[SavedTheme]) -> (Vec, Vec) { + let group = |options: &[(&str, ThemeKind)]| { + options.iter().filter_map(|(id, kind)| SavedTheme::parse(id).filter(|theme| favorites.contains(theme)).map(|_| *kind)).collect() + }; + (group(LIGHT_THEME_OPTIONS), group(DARK_THEME_OPTIONS)) +} + +/// Right-click menu on the top-right appearance button. A plain click still cycles modes. +pub(crate) fn appearance_context_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + if ui.button(tl!("Appearance Settings…")).clicked() { + open_preferences(app, "interface"); + ui.close(); + } + let (light, dark) = favorite_theme_groups(&app.session.prefs().interface.favorite_themes); + let has_light = !light.is_empty(); + if !light.is_empty() || !dark.is_empty() { + ui.separator(); + } + for kind in light { + if ui.selectable_label(app.ui.theme == kind, tl!(kind.label())).clicked() { + app.set_theme(ui.ctx(), kind); + ui.close(); + } + } + if has_light && !dark.is_empty() { + ui.separator(); + } + for kind in dark { + if ui.selectable_label(app.ui.theme == kind, tl!(kind.label())).clicked() { + app.set_theme(ui.ctx(), kind); + ui.close(); + } + } +} + +pub(super) fn system_theme(app: &PhotocraftApp, ctx: &egui::Context) -> Option { + app.services.system_theme.as_ref().and_then(|read| read(ctx)).or_else(|| ctx.system_theme()) +} + +/// Resolve an absolute pixels-per-point preference without multiplying the OS DPI twice. +/// Monitor dimensions are physical pixels, independent of window size and UI zoom. +pub(super) fn display_scale(pref: prefs::UiScale, native: Option) -> f32 { + let native = native.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(1.0); + match pref { + // The system's scale, fractional ones included (125%, 150%, 175%: #1072), and 100% on a + // large 4K display run unscaled (#1278); 200% there is a fixed choice. + prefs::UiScale::Auto => native, + fixed => fixed.name().parse::().map_or(1.0, |pct| pct / 100.0), + } +} + +pub(super) fn sync_display_scale(app: &PhotocraftApp, ctx: &egui::Context) { + let native = ctx.native_pixels_per_point(); + let native_scale = native.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(1.0); + let scale = display_scale(app.session.prefs().interface.ui_scale, native); + ctx.set_zoom_factor(scale / native_scale); +} + +/// Interface › Show Tooltips and Tools › Show Tooltips (either one off hides them): egui never +/// shows a tooltip whose delay is infinite. Re-checked every frame because a theme change +/// rebuilds the style; that's one style read, and a write only when it differs. +pub(super) fn sync_tooltips(app: &PhotocraftApp, ctx: &egui::Context) { + let p = app.session.prefs(); + let delay = if p.interface.show_tooltips && p.tools.show_tooltips { crate::theme::TOOLTIP_DELAY } else { f32::INFINITY }; + if ctx.global_style().interaction.tooltip_delay != delay { + ctx.global_style_mut(|s| s.interaction.tooltip_delay = delay); + } +} + +/// Interface › Enable Animations: off, egui's fades and slides take no time and scroll areas jump +/// straight to their target (#3273). Re-checked every frame because a theme change rebuilds the +/// style; both the dark and light styles are set, so a system appearance switch keeps it. +pub(super) fn sync_animations(app: &PhotocraftApp, ctx: &egui::Context) { + let on = app.session.prefs().interface.enable_animations; + let time = if on { egui::Style::default().animation_time } else { 0.0 }; + if ctx.global_style().animation_time != time { + let scroll = if on { egui::style::ScrollAnimation::default() } else { egui::style::ScrollAnimation::none() }; + ctx.all_styles_mut(|s| { + s.animation_time = time; + s.scroll_animation = scroll; + }); + } +} + +/// Resolve the saved appearance mode without changing it or either theme slot. +pub(crate) fn sync_appearance(app: &mut PhotocraftApp, ctx: &egui::Context) { + // A restored or embedding-supplied pin must not suppress native appearance events. + ctx.set_theme(egui::ThemePreference::System); + // The native service also covers Wayland sessions where winit has no system theme. + let selected = selected_theme(&app.session.prefs().interface, system_theme(app, ctx)); + if app.ui.theme != selected { + app.apply_theme(ctx, selected); + } +} + +/// One theme as a Color Theme swatch: its panel colour under a chrome strip with an accent dot, +/// outlined when chosen. The name is the tooltip and the accessible label. A star badge on its +/// corner adds the theme to (or removes it from) the favourites listed by the appearance +/// button's menu; it shows while the swatch is hovered, and stays for a favourite. +fn theme_swatch(ui: &mut egui::Ui, kind: ThemeKind, id: &str, selected: &mut String, favorites: &mut Vec) { + const BADGE: f32 = 7.0; + let t = Tokens::get(ui.ctx()); + let p = Tokens::for_kind(kind); + let label = tl!(&choice_label(id)).to_string(); + let on = selected.as_str() == id; + let (rect, resp) = ui.allocate_exact_size(vec2(30.0, 26.0), Sense::click()); + let painter = ui.painter(); + let inner = rect.shrink(3.0); + painter.rect_filled(inner, 2.0, p.dock); + painter.rect_filled(egui::Rect::from_min_size(inner.min, vec2(inner.width(), 5.0)), 0.0, p.chrome); + painter.circle_filled(inner.right_bottom() - vec2(6.0, 6.0), 2.5, p.accent); + let stroke = if on { + egui::Stroke::new(2.0, t.accent) + } else if resp.hovered() { + egui::Stroke::new(1.0, t.text_dim) + } else { + egui::Stroke::new(1.0, t.card_border) + }; + painter.rect_stroke(rect.shrink(1.0), 3.0, stroke, egui::StrokeKind::Inside); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, on, &label)); + if resp.on_hover_text(&label).clicked() { + *selected = id.to_string(); + } + let Some(theme) = SavedTheme::parse(id) else { return }; + let favorite = favorites.contains(&theme); + let center = rect.right_top() + vec2(-3.0, 3.0); + let badge = egui::Rect::from_center_size(center, vec2(BADGE * 2.0, BADGE * 2.0)); + if !(favorite || ui.rect_contains_pointer(rect.union(badge))) { + return; + } + ui.painter().circle(center, BADGE, t.card, egui::Stroke::new(1.0, t.card_border)); + let (icon, tint) = if favorite { ("star-filled", t.accent) } else { ("star", t.text_dim) }; + let action = if favorite { tl!("Remove from favorites") } else { tl!("Add to favorites") }; + // Interact and paint without allocating: a widget placed at `badge` would grow the row by the + // 4 px the badge overhangs the swatch, re-centring the swatches after this one whenever the + // pointer arrives, and oscillating when that moves the swatch out from under it. + let response = ui.interact(badge, ui.scope_id().with((id, "favorite")), Sense::click()).on_hover_text(action); + crate::icons::paint(ui, badge, icon, 10.0, tint); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{action}: {label}"))); + if response.clicked() { + if favorite { + favorites.retain(|saved| *saved != theme); + } else { + favorites.push(theme); + } + } +} + +/// A grid row of theme swatches, marked Active when the appearance mode shows this family. +fn theme_row(ui: &mut egui::Ui, title: &str, active: bool, selected: &mut String, favorites: &mut Vec, options: &[(&str, ThemeKind)]) { + let t = Tokens::get(ui.ctx()); + ui.label(RichText::new(tl!(title)).color(t.text_dim)); + ui.horizontal(|ui| { + // Room for the favourite star badges on the swatch corners. + ui.spacing_mut().item_spacing.x = 6.0; + for (id, kind) in options { + theme_swatch(ui, *kind, id, selected, favorites); + } + if active { + ui.add_space(6.0); + ui.label(RichText::new(tl!("Active")).color(t.accent_text).small()); + } + }); + ui.end_row(); +} + +/// Which of the Appearance rows drawn by `appearance_rows` a search shows. +#[derive(Clone, Copy)] +pub(super) struct AppearanceRows { + mode: bool, + light: bool, + dark: bool, +} + +impl AppearanceRows { + /// `query` is lowercased; empty shows every row. + pub(super) fn matching(query: &str) -> Self { + let shown = |key: &str| query.is_empty() || preference_matches("interface", key, query); + Self { mode: shown("appearanceMode"), light: shown("lightTheme"), dark: shown("darkTheme") } + } + + pub(super) fn any(self) -> bool { + self.mode || self.light || self.dark + } +} + +/// Appearance Mode and the light and dark Color Theme swatches, as rows of the Appearance grid. +pub(super) fn appearance_rows(ui: &mut egui::Ui, obj: &mut Map, system: Option, rows: AppearanceRows) { + let t = Tokens::get(ui.ctx()); + let mut mode = obj.get("appearanceMode").and_then(Value::as_str).unwrap_or("auto").to_string(); + if rows.mode { + ui.label(RichText::new(tl!("Appearance Mode")).color(t.text_dim)); + let choices: [(String, &str); 3] = [("auto".into(), tl!("Sync with system")), ("dark".into(), tl!("Dark")), ("light".into(), tl!("Light"))]; + let pairs: Vec<(String, &str)> = choices.iter().map(|(id, label)| (id.clone(), *label)).collect(); + crate::widgets::dropdown(ui, "appearance-mode", tl!("Appearance Mode"), &mut mode, &pairs, 220.0); + ui.end_row(); + } + let light_active = mode == "light" || (mode == "auto" && system == Some(egui::Theme::Light)); + obj.insert("appearanceMode".into(), json!(mode)); + let mut light = obj.get("lightTheme").and_then(Value::as_str).unwrap_or("studioLight").to_string(); + let mut dark = obj.get("darkTheme").and_then(Value::as_str).unwrap_or("proMedium").to_string(); + let mut favorites: Vec = obj.get("favoriteThemes").cloned().and_then(|v| serde_json::from_value(v).ok()).unwrap_or_default(); + if rows.light { + theme_row(ui, "Light Theme", light_active, &mut light, &mut favorites, LIGHT_THEME_OPTIONS); + } + if rows.dark { + theme_row(ui, "Dark Theme", !light_active, &mut dark, &mut favorites, DARK_THEME_OPTIONS); + } + obj.insert("lightTheme".into(), json!(light)); + obj.insert("darkTheme".into(), json!(dark)); + obj.insert("favoriteThemes".into(), json!(favorites)); +} diff --git a/crates/ui-egui/src/prefs_ui/dialogs.rs b/crates/ui-egui/src/prefs_ui/dialogs.rs new file mode 100644 index 0000000000..8a1b298100 --- /dev/null +++ b/crates/ui-egui/src/prefs_ui/dialogs.rs @@ -0,0 +1,431 @@ +use super::shortcuts::shortcut_items; +use super::*; + +// ------------------------------------------------------------------ menu routing + +/// Shell front ends for Edit-menu commands invoked without parameters (dialogs, pickers). +/// `None` when `id` isn't handled here. +pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { + let empty = params.as_object().is_none_or(|o| o.is_empty()); + if !empty { + return None; + } + if let Some(section) = id.strip_prefix("edit.preferences.") { + return Some(Ok(json!({"dialog": open_preferences(app, section)}))); + } + let dialog = |d: Option| Some(d.map(|d| json!({"dialog": d})).ok_or_else(|| "not available".to_string())); + match id { + "edit.keyboardShortcuts" => Some(Ok(json!({"dialog": open_shortcuts(app, 0)}))), + "edit.menus" => Some(Ok(json!({"dialog": open_shortcuts(app, 1)}))), + "edit.toolbar" => Some(Ok(json!({"dialog": open_shortcuts(app, 2)}))), + "edit.colorSettings" => { + let d = crate::filter_dialog::open(app, "edit.colorSettings"); + let cur = serde_json::to_value(&app.session.color.settings).unwrap_or_default(); + // What Monitor Profile resolves to, so a fallback to sRGB is visible (#569): read the + // displays again now, and the dialog refreshes this line as it draws. + crate::monitor_status::read_now(app); + let note = crate::monitor_status::note(app); + if let Some(dm) = d.and_then(|d| app.ui.dialog_mut(d)) { + for (k, v) in cur.as_object().into_iter().flatten() { + if dm.fields.contains_key(k) { + dm.fields.insert(k.clone(), v.clone()); + } + } + dm.fields.insert("__note".into(), json!(note)); + } + dialog(d) + } + "edit.fade" | "edit.findAndReplaceText" | "edit.defineBrushPreset" | "edit.defineCustomShape" | "edit.autoAlignLayers" | "edit.autoBlendLayers" => { + if !app.session.is_enabled(id) { + return Some(Err(photocraft_engine::commands::find(id) + .map_or("not available".into(), |c| format!("{} is not available right now", c.label.trim_end_matches('…'))))); + } + let d = crate::filter_dialog::open(app, id); + if let Some(dm) = d.and_then(|d| app.ui.dialog_mut(d)) { + // Optional parameters the generic dialog can't express keep their defaults. + for k in ["reference", "path"] { + dm.fields.remove(k); + } + } + dialog(d) + } + // Photoshop's Content-Aware Fill workspace (caf_ui); the engine command with params + // still runs directly. + "edit.contentAwareFill" => Some(crate::caf_ui::open(app).map(|_| json!({"contentAwareFill": app.distort.describe()["contentAwareFill"]}))), + // Photoshop has no dialog: the menu opens the scale box (with params: the engine). + crate::cas_transform::COMMAND => Some(crate::cas_transform::begin(app, ctx)), + "edit.presets.presetManager" => { + Some(Ok(json!({"dialog": open_kind(app, "presets", "Preset Manager", json!({"kind": "brushes", "selected": 0, "newName": ""}))}))) + } + "edit.presets.exportImportPresets" => Some(Ok( + json!({"dialog": open_kind(app, "presetsIO", "Export/Import Presets", json!({"action": "export", "brushes": true, "customShapes": true, "tools": true}))}), + )), + _ => None, + } +} + +fn open_kind(app: &mut PhotocraftApp, kind: &str, label: &str, fields: Value) -> u64 { + let mut f = Map::new(); + f.insert("__prefsui".into(), json!(kind)); + f.insert("__label".into(), json!(label)); + if let Value::Object(m) = fields { + f.extend(m); + } + app.ui.open_dialog(DialogKind::Command, f) +} + +/// Is this a dialog rendered by this module? +pub fn owns(fields: &Map) -> bool { + fields.contains_key("__prefsui") +} + +/// Only Preferences supports applying changes without closing the dialog. +pub fn is_preferences(fields: &Map) -> bool { + fields.get("__prefsui").and_then(Value::as_str) == Some("prefs") +} + +pub(super) fn preference_values(p: &prefs::Preferences) -> Map { + let values = p.to_json(); + SECTIONS.iter().filter_map(|(id, _)| Some((id.to_string(), values.get(id)?.clone()))).collect() +} + +/// Compare the editable sections, excluding settings managed outside Preferences. +pub fn preferences_changed(app: &PhotocraftApp, fields: &Map) -> bool { + is_preferences(fields) && fields.get("values").and_then(Value::as_object).is_some_and(|values| *values != preference_values(app.session.prefs())) +} + +/// Commit the working copy and keep the current section open. Failure leaves the draft intact. +pub fn apply(app: &mut PhotocraftApp, id: u64) -> Result { + let d = app.ui.dialogs.iter().find(|d| d.id == id).ok_or_else(|| format!("no dialog {id}"))?; + if d.kind != DialogKind::Command || !is_preferences(&d.fields) { + return Err("Apply is only available for Preferences".into()); + } + let fields = d.fields.clone(); + let result = confirm(app, &fields)?; + let values = Value::Object(preference_values(app.session.prefs())); + if let Some(d) = app.ui.dialog_mut(id) { + // Use the validated values as the next draft, including any normalisation by prefs.set. + d.fields.insert("values".into(), values); + } + Ok(result) +} + +/// The size Preferences opens at: room for the widest section and about 30 settings rows. The +/// dialog's resize grip changes it, and its contents follow (#7420). +pub const PREFERENCES_SIZE: egui::Vec2 = egui::vec2(1040.0, 800.0); + +/// The height of the settings area (section list and fields) when `available` is left below the +/// search field: everything but the dialog's button row (`item_spacing` + 8 pt + the buttons) and +/// a little slack, never less than a few rows. +pub(super) fn settings_height(available: f32, item_spacing: f32, button_height: f32) -> f32 { + (available - (item_spacing + 8.0 + button_height + 4.0)).max(160.0) +} + +/// Max dialog width for our dialogs. Preferences fills the width it is given (`available`, its +/// resizable area). +pub fn width(fields: &Map, available: f32) -> Option { + match fields.get("__prefsui").and_then(Value::as_str)? { + "prefs" => Some(available.max(380.0)), + "shortcuts" => Some(720.0), + _ => Some(460.0), + } +} + +/// Open Edit › Preferences on `section`. +pub fn open_preferences(app: &mut PhotocraftApp, section: &str) -> u64 { + let section = if SECTIONS.iter().any(|(id, _)| *id == section) { section } else { "general" }; + let working = preference_values(app.session.prefs()); + let order = field_order(app.session.prefs(), &working); + open_kind(app, "prefs", "Preferences", json!({"section": section, "values": working, "__order": order})) +} + +/// Each section's keys in declaration order (JSON objects sort their keys; the serialised text +/// keeps the struct's order, which groups related settings like Photoshop's dialog). +fn field_order(p: &prefs::Preferences, sections: &Map) -> Value { + let text = serde_json::to_string(p).unwrap_or_default(); + let mut out = Map::new(); + for (id, v) in sections { + let Some(start) = text.find(&format!("\"{id}\":{{")) else { continue }; + let body = &text[start..]; + let end = body.find('}').unwrap_or(body.len()); + let region = &body[..end]; + let mut keys: Vec<(usize, String)> = + v.as_object().into_iter().flatten().map(|(k, _)| (region.find(&format!("\"{k}\":")).unwrap_or(usize::MAX), k.clone())).collect(); + keys.sort(); + out.insert(id.clone(), json!(keys.into_iter().map(|(_, k)| k).collect::>())); + } + Value::Object(out) +} + +/// Open Keyboard Shortcuts and Menus on a tab (0 shortcuts, 1 menus, 2 toolbar). +pub fn open_shortcuts(app: &mut PhotocraftApp, tab: u64) -> u64 { + let p = app.session.prefs(); + let fields = json!({ + "tab": tab, + "filter": "", + "overrides": p.shortcuts, + "alternates": p.alternate_shortcuts, + "sets": p.shortcut_sets, + "activeSet": p.shortcut_set, + "hidden": p.menus.hidden, + "colors": p.menus.colors, + "toolbarHidden": p.toolbar.hidden, + "selected": "", + "capture": false, + "message": "", + }); + open_kind(app, "shortcuts", tl!("Keyboard Shortcuts and Menus"), fields) +} + +/// Open the Embedded Profile Mismatch prompt for a file waiting to open (`open_prompt`): its +/// `message`, the answer selected first (`action`), and `marker`, the field that routes OK and +/// Cancel back to `open_prompt`. +/// `names` carries the embedded and working profile names and the Color Settings policy a +/// remembered choice is saved to (`policyKey`, null for a mode without one). +pub fn open_mismatch(app: &mut PhotocraftApp, message: &str, action: &str, missing: bool, marker: &str, names: Value) -> u64 { + let mut fields = json!({"message": message, "action": action, "missing": missing, "remember": false}); + if let (Some(f), Value::Object(n)) = (fields.as_object_mut(), names) { + f.extend(n); + } + fields[marker] = json!(true); + open_kind(app, "mismatch", tl!("Embedded Profile Mismatch"), fields) +} + +pub(super) fn toolbar_tab(ui: &mut egui::Ui, f: &mut Map) { + let mut hidden: Vec = f.get("toolbarHidden").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); + egui::ScrollArea::vertical().max_height(380.0).id_salt("toolbar-scroll").show(ui, |ui| { + egui::Grid::new("toolbar-grid").num_columns(2).spacing([16.0, 4.0]).show(ui, |ui| { + for tool in crate::state::Tool::ALL { + let name = format!("{tool:?}"); + let mut on = !hidden.contains(&name); + crate::widgets::checkbox(ui, &mut on, tl!(tool.label())); + if on { + hidden.retain(|h| *h != name); + } else if !hidden.contains(&name) { + hidden.push(name); + } + let k = tool.key(); + ui.label(if k == '\0' { String::new() } else { k.to_string() }); + ui.end_row(); + } + }); + }); + if ui.button(tl!("Restore Defaults")).clicked() { + hidden.clear(); + } + f.insert("toolbarHidden".into(), json!(hidden)); +} + +pub(super) fn presets_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { + let t = Tokens::get(ui.ctx()); + let mut kind = f.get("kind").and_then(Value::as_str).unwrap_or("brushes").to_string(); + ui.horizontal(|ui| { + ui.label(RichText::new(tl!("Preset Type")).color(t.text_dim)); + let opts = [("brushes".to_string(), tl!("Brushes")), ("customShapes".to_string(), tl!("Custom Shapes")), ("patterns".to_string(), tl!("Patterns"))]; + crate::widgets::dropdown(ui, "preset-kind", tl!("Type"), &mut kind, &opts, 180.0); + }); + let list = app + .session + .execute("edit.presets.presetManager", json!({"kind": kind})) + .ok() + .and_then(|v| v.get(&kind).cloned()) + .and_then(|v| serde_json::from_value::>(v).ok()) + .unwrap_or_default(); + let mut selected = f.get("selected").and_then(Value::as_u64).unwrap_or(0) as usize; + egui::ScrollArea::vertical().max_height(260.0).id_salt("preset-list").show(ui, |ui| { + for (i, name) in list.iter().enumerate() { + if ui.selectable_label(i == selected, name).clicked() { + selected = i; + f.insert("newName".into(), json!(name)); + } + } + if list.is_empty() { + ui.label(RichText::new(tl!("No presets of this type.")).color(t.text_faint)); + } + }); + let mut new_name = f.get("newName").and_then(Value::as_str).unwrap_or("").to_string(); + ui.horizontal(|ui| { + ui.add(egui::TextEdit::singleline(&mut new_name).desired_width(200.0)).accessible_name(tl!("Name")); + if ui.add_enabled(selected < list.len() && !new_name.trim().is_empty(), egui::Button::new(tl!("Rename"))).clicked() { + let _ = app.run("edit.presets.presetManager", json!({"action": "rename", "kind": kind, "index": selected, "newName": new_name})); + } + if ui.add_enabled(selected < list.len(), egui::Button::new(tl!("Delete"))).clicked() { + let _ = app.run("edit.presets.presetManager", json!({"action": "delete", "kind": kind, "index": selected})); + } + // Load Photoshop brushes (.abr) into the library. + if kind == "brushes" && ui.button(tl!("Load…")).on_hover_text(tl!("Import brushes (.abr)")).clicked() { + let _ = app.open_dialog_file(); + } + }); + f.insert("kind".into(), json!(kind)); + f.insert("selected".into(), json!(selected)); + f.insert("newName".into(), json!(new_name)); +} + +pub(super) fn presets_io_body(ui: &mut egui::Ui, f: &mut Map) { + let t = Tokens::get(ui.ctx()); + let mut action = f.get("action").and_then(Value::as_str).unwrap_or("export").to_string(); + ui.horizontal(|ui| { + ui.label(RichText::new(tl!("Action")).color(t.text_dim)); + crate::widgets::dropdown( + ui, + "presets-io", + tl!("Action"), + &mut action, + &[("export".to_string(), tl!("Export Presets")), ("import".to_string(), tl!("Import Presets"))], + 180.0, + ); + }); + for (k, label) in [("brushes", tl!("Brushes")), ("customShapes", tl!("Custom Shapes")), ("tools", tl!("Tool Presets"))] { + let mut on = f.get(k).and_then(Value::as_bool).unwrap_or(true); + crate::widgets::checkbox(ui, &mut on, label); + f.insert(k.into(), json!(on)); + } + f.insert("action".into(), json!(action)); +} + +pub(super) fn mismatch_body(ui: &mut egui::Ui, f: &mut Map) { + let t = Tokens::get(ui.ctx()); + ui.label(RichText::new(f.get("message").and_then(Value::as_str).unwrap_or("")).color(t.text)); + ui.add_space(6.0); + let mut action = f.get("action").and_then(Value::as_str).unwrap_or("preserve").to_string(); + let missing = f.get("missing").and_then(Value::as_bool).unwrap_or(false); + let name = |k: &str| f.get(k).and_then(Value::as_str).unwrap_or("?").to_string(); + let opts: Vec<(&str, String)> = if missing { + vec![("preserve", tl!("Leave as is (don't color manage)").into()), ("assignWorking", tl!("Assign working space").into())] + } else { + vec![ + ("preserve", crate::i18n::fmt(tl!("Use the embedded profile ({profile})"), &[("profile", &name("embedded"))])), + ("convert", crate::i18n::fmt(tl!("Convert to the working space ({profile})"), &[("profile", &name("working"))])), + ("discard", tl!("Discard the embedded profile (don't color manage)").into()), + ] + }; + for (v, label) in opts { + ui.radio_value(&mut action, v.to_string(), label); + } + f.insert("action".into(), json!(action)); + // Remembering sets the Color Settings policy and stops asking, so it needs a mode with a policy. + if !missing && f.get("policyKey").is_some_and(Value::is_string) { + ui.add_space(8.0); + let mut remember = f.get("remember").and_then(Value::as_bool).unwrap_or(false); + crate::widgets::checkbox(ui, &mut remember, tl!("Remember this choice for future images")) + .on_hover_text(tl!("Turn the prompt back on with Ask On Mismatch in Edit › Color Settings.")); + f.insert("remember".into(), json!(remember)); + } +} + +// ------------------------------------------------------------------ confirm + +/// OK on one of our dialogs. +pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { + match f.get("__prefsui").and_then(Value::as_str).unwrap_or("") { + "prefs" => { + let values = f.get("values").cloned().unwrap_or(Value::Null); + app.run("prefs.set", json!({"path": "", "value": values})) + } + "shortcuts" => { + let overrides = f.get("overrides").cloned().unwrap_or(json!({})); + // Shortcuts moved to another command are taken from their old owner (shell + // commands included, which the engine doesn't know). + // The map replaces every stored override, so a malformed one is an error, not "none". + let mut ov: BTreeMap = + serde_json::from_value(overrides).map_err(|e| format!("overrides must map command IDs to shortcut strings: {e}"))?; + let alternates = f.get("alternates").cloned().unwrap_or(json!({})); + let mut alt: BTreeMap> = + serde_json::from_value(alternates).map_err(|e| format!("alternates must map command IDs to lists of shortcuts: {e}"))?; + let items = shortcut_items(app); + // Newly assigned shortcuts are checked first and take theirs from any holder, custom + // overrides included; unchanged overrides only take theirs from defaults. A + // command's further keys (#3665) take and lose keys the same way. + let before = &app.session.prefs().shortcuts; + let before_alt = &app.session.prefs().alternate_shortcuts; + let mut todo: Vec<(String, String, bool, bool)> = + ov.iter().filter(|(_, s)| !s.is_empty()).map(|(k, s)| (k.clone(), s.clone(), before.get(k) != Some(s), false)).collect(); + for (k, keys) in &alt { + let new = before_alt.get(k) != Some(keys); + todo.extend(keys.iter().map(|s| (k.clone(), s.clone(), new, true))); + } + todo.sort_by_key(|(_, _, new, _)| !new); + let main_of = |ov: &BTreeMap, id: &str, def: Option<&str>| -> Option { + match ov.get(id) { + Some(s) if s.is_empty() => None, + Some(s) => Some(s.clone()), + None => def.map(str::to_string), + } + }; + for (id, sc, new, is_alt) in todo { + let norm = prefs::normalize_shortcut(&sc); + let Some(norm) = norm else { continue }; + // Taken by a newer assignment? + if (!is_alt && ov.get(&id).is_some_and(String::is_empty)) || (is_alt && alt.get(&id).is_some_and(|k| !k.contains(&norm))) { + continue; + } + for (other, _, _, def) in &items { + if *other == id { + continue; + } + let held = match ov.get(other) { + Some(s) if new => Some(s.as_str()), + Some(_) => None, + None => def.as_deref(), + }; + if held.and_then(prefs::normalize_shortcut).as_deref() == Some(norm.as_str()) { + ov.insert(other.clone(), String::new()); + } + // Its further keys: the edited list when this assignment is new, else only + // the defaults. + if alt.contains_key(other) && !new { + continue; + } + let mut p = prefs::Preferences::default(); + if let Some(list) = alt.get(other) { + p.alternate_shortcuts.insert(other.clone(), list.clone()); + } + let keys = p.alternates(other, main_of(&ov, other, def.as_deref()).as_deref()); + if keys.contains(&norm) { + alt.insert(other.clone(), keys.into_iter().filter(|k| *k != norm).collect()); + } + } + } + let hidden = f.get("hidden").cloned().unwrap_or(json!([])); + let colors = f.get("colors").cloned().unwrap_or(json!({})); + let toolbar = f.get("toolbarHidden").cloned().unwrap_or(json!([])); + let sets = f.get("sets").cloned().unwrap_or(json!({})); + let active = f.get("activeSet").cloned().unwrap_or(json!("")); + app.run( + "edit.keyboardShortcuts", + json!({"reset": true, "set": ov, "alternates": alt, "allowUnknown": true, "removeConflicts": false, "sets": sets, "activeSet": active}), + )?; + app.run("prefs.set", json!({"values": {"menus": {"hidden": hidden, "colors": colors}, "toolbar": {"hidden": toolbar}}})) + } + "presets" => Ok(Value::Null), + "presetsIO" => { + let kinds: Vec<&str> = ["brushes", "customShapes", "tools"].into_iter().filter(|k| f.get(*k).and_then(Value::as_bool).unwrap_or(true)).collect(); + if f.get("action").and_then(Value::as_str) == Some("import") { + app.pick_file_bytes(move |app, name, bytes| { + let text = String::from_utf8(bytes).map_err(|_| format!("{name} is not a preset file"))?; + app.run("edit.presets.exportImportPresets", json!({"action": "import", "kinds": kinds, "data": text})) + }) + } else { + let out = app.run("edit.presets.exportImportPresets", json!({"action": "export", "kinds": kinds}))?; + let text = serde_json::to_string_pretty(&out["data"]).map_err(|e| e.to_string())?; + app.pick_save("Presets.pcpresets", move |app, path| { + let write = app.services.write.as_mut().ok_or("no writer configured")?; + write(&path, text.as_bytes())?; + let template = "Exported presets to {path}"; + app.ui.status = crate::i18n::fmt(tl!(template), &[("path", &path)]); + Ok(json!({"path": path})) + }) + } + } + // The file it asks about opens with this answer (`open_prompt`). + "mismatch" => { + let action = f.get("action").and_then(Value::as_str).unwrap_or("preserve"); + if f.get("remember").and_then(Value::as_bool) == Some(true) { + return crate::open_prompt::answer_remembering(app, action); + } + crate::open_prompt::answer(app, Some(action)) + } + _ => Err("unknown dialog".into()), + } +} diff --git a/crates/ui-egui/src/prefs_ui/fields.rs b/crates/ui-egui/src/prefs_ui/fields.rs new file mode 100644 index 0000000000..f4141464d0 --- /dev/null +++ b/crates/ui-egui/src/prefs_ui/fields.rs @@ -0,0 +1,508 @@ +use super::appearance::{AppearanceRows, appearance_rows, system_theme}; +use super::dialogs::{mismatch_body, presets_body, presets_io_body, settings_height}; +use super::graphics::{gpu_memory_lines, gpu_status_rows, memory_usage_row, read_at_launch, rendering_mode_row}; +use super::shortcuts::shortcuts_body; +use super::*; + +// ------------------------------------------------------------------ bodies + +/// Render one of our dialogs' bodies. +pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { + match f.get("__prefsui").and_then(Value::as_str).unwrap_or("") { + "prefs" => { + let mut info = app.perf.gpu_info.lines(); + info.extend(gpu_memory_lines(app)); + f.insert("__gpuInfo".into(), json!(info)); + f.insert("__gpuAdapters".into(), json!(app.perf.gpu_info.adapters)); + let system = system_theme(app, ui.ctx()); + prefs_body(ui, f, system); + } + "shortcuts" => shortcuts_body(app, ui, f), + "presets" => presets_body(app, ui, f), + "presetsIO" => presets_io_body(ui, f), + "mismatch" => mismatch_body(ui, f), + _ => {} + } +} + +/// The label a preference key shows in the dialog: a few keys have their own wording, the rest +/// split camelCase into words (`convertToSrgb` → "Convert to srgb"). +pub(super) fn humanize(key: &str) -> String { + match key { + "appearanceMode" => return "Appearance Mode".into(), + "exrAcesCg" => return "Open color-less EXR as ACEScg".into(), + "darkTheme" => return "Dark Theme".into(), + "lightTheme" => return "Light Theme".into(), + "automaticallyCheckUpdates" => return "Automatically Check for Updates".into(), + _ => {} + } + // These controls appear only for WebP, so reuse the existing translated labels. + if key == "webpLossless" { + return "Lossless".into(); + } + if key == "webpQuality" { + return "Quality".into(); + } + // The auto-hide notice settings read best with their own labels (Interface › Notification, #2022). + if key == "notificationAutoHide" { + return "Auto Hide Notifications".into(); + } + if key == "notificationDurationSeconds" { + return "Notification Duration (seconds)".into(); + } + // Tools: arrow-key nudges bundle into one History state (#2259). + if key == "bundleNudges" { + return "Bundle Arrow-Key Nudges".into(); + } + if key == "nudgeBundlePauseMs" { + return "Nudge Bundle Pause (ms)".into(); + } + // Performance: presentation without vsync (#1343); like the other graphics settings, it + // takes effect when the window next opens. + // File Handling: Photoshop's wording (#8080). + if key == "doNotAppendCopy" { + return "Do not append \"copy\" to filename when saving a copy".into(); + } + if key == "lowLatencyDrawing" { + return "Low-Latency Drawing (vsync off, applies at next launch)".into(); + } + // Performance: the canvas compositor's GPU memory, 0 for the automatic budget (L3). + if key == "gpuMemoryMb" { + return "GPU Memory (MB, 0 = Automatic)".into(); + } + let mut s = String::new(); + for (i, ch) in key.chars().enumerate() { + if i == 0 { + s.extend(ch.to_uppercase()); + } else if ch.is_uppercase() { + s.push(' '); + s.extend(ch.to_lowercase()); + } else { + s.push(ch); + } + } + s.replace("Psd", "PSD") + .replace("Gpu", "GPU") + .replace("Ui ", "UI ") + .replace("Mb", "(MB)") + .replace("Exif", "EXIF") + .replace("Hud", "HUD") + .replace("Lut ", "LUT ") +} + +pub(super) fn choice_label(v: &str) -> String { + match v { + "exr" => "EXR".into(), + "cm" => "Centimeters".into(), + "mm" => "Millimeters".into(), + "75" | "80" | "85" | "90" | "95" | "100" | "105" | "110" | "115" | "120" | "125" | "150" | "175" | "200" | "250" | "300" => format!("{v}%"), + "8" => "8 Bits/Channel".into(), + "16" => "16 Bits/Channel".into(), + "postScript" => "PostScript (72 points/inch)".into(), + "traditional" => "Traditional (72.27 points/inch)".into(), + "vulkan" => "Vulkan".into(), + "dx12" => "DirectX 12".into(), + "metal" => "Metal".into(), + "gl" => "OpenGL".into(), + "ahd" => "AHD (adaptive homogeneity)".into(), + "mhc" => "Malvar–He–Cutler".into(), + "cpu" => "CPU (no GPU acceleration)".into(), + v => humanize(v), + } +} + +/// An editable `#rrggbb` field beside a colour swatch (#668): typing a valid value sets the +/// colour; while it's being typed a partial value is kept, and it shows the colour otherwise. +pub(super) fn hex_field(ui: &mut egui::Ui, key: &str, rgb: &mut [u8; 3]) { + let id = egui::Id::unique(("pref-hex", key)); + let shown = format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]); + let mut text = ui.data(|d| d.get_temp::(id)).unwrap_or_else(|| shown.clone()); + let r = crate::widgets::text_field_ex(ui, id, &mut text, "", 72.0, true, Some(7)).accessible_name(tl!("Color")); + if r.changed() + && let Some(c) = prefs::parse_hex(&text) + { + *rgb = c; + } + if r.has_focus() { + ui.data_mut(|d| d.insert_temp(id, text)); + } else { + ui.data_mut(|d| d.remove::(id)); + } +} + +pub(super) fn color_of(s: &str) -> Color32 { + prefs::parse_hex(s).map_or(Color32::GRAY, |c| Color32::from_rgb(c[0], c[1], c[2])) +} + +/// Search the same visible, editable preference labels used in the dialog. +pub(super) fn preference_matches(section: &str, key: &str, query: &str) -> bool { + let label = humanize(key); + format!("{section}.{key}").to_lowercase().contains(query) || label.to_lowercase().contains(query) || tl!(&label).to_lowercase().contains(query) +} + +pub(super) fn preference_sections(values: &Value, search: &str) -> Vec<(&'static str, &'static str)> { + let query = search.trim().to_lowercase(); + SECTIONS + .iter() + .copied() + .filter(|(id, title)| { + query.is_empty() + || title.to_lowercase().contains(&query) + || tl!(title).to_lowercase().contains(&query) + || values + .get(*id) + .and_then(Value::as_object) + .is_some_and(|fields| fields.keys().any(|key| !prefs::is_hidden(&format!("{id}.{key}")) && preference_matches(id, key, &query))) + }) + .collect() +} + +/// Preferences: section list on the left, the section's settings on the right. +fn prefs_body(ui: &mut egui::Ui, f: &mut Map, system: Option) { + let t = Tokens::get(ui.ctx()); + let mut section = f.get("section").and_then(Value::as_str).unwrap_or("general").to_string(); + let mut values = f.get("values").cloned().unwrap_or(Value::Null); + // The dialog follows the language being edited, so a change shows before OK. + let lang = crate::i18n::Lang::from_pref(values.pointer("/interface/language").and_then(Value::as_str).unwrap_or("auto")); + let mut search = f.get("__search").and_then(Value::as_str).unwrap_or("").to_string(); + crate::widgets::text_field(ui, ui.scope_id().with("prefs-search"), &mut search, tl!("Search settings…"), ui.available_width(), false); + let found = preference_sections(&values, &search); + if !found.iter().any(|(id, _)| *id == section) + && let Some((first, _)) = found.first() + { + section = (*first).to_string(); + } + ui.add_space(6.0); + ui.horizontal_top(|ui| { + // Section list. + ui.vertical(|ui| { + ui.set_width(170.0); + if found.is_empty() { + ui.label(RichText::new(tl!("No matching settings")).color(t.text_dim)); + } + for &(id, title) in &found { + let sel = section == id; + let empty = !has_visible_fields(&values, id); + let (rect, resp) = ui.allocate_exact_size(vec2(170.0, 22.0), Sense::click()); + if sel { + ui.painter().rect_filled(rect, t.radius_sm, t.row_selected); + } else if resp.hovered() { + ui.painter().rect_filled(rect, t.radius_sm, t.hover); + } + let color = if sel { + t.text + } else if empty { + t.text_faint + } else { + t.text_dim + }; + // Translated section names can be longer than the column: elide them (the full + // name is the tooltip) instead of drawing over the settings. + let mut job = egui::text::LayoutJob::simple_singleline(tl!(title).to_string(), crate::theme::medium(12.5), color); + job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width() - 12.0); + let galley = ui.painter().layout_job(job); + let elided = galley.elided; + ui.painter().galley(rect.left_center() + vec2(8.0, -galley.size().y / 2.0), galley, color); + let resp = if elided { resp.on_hover_text(tl!(title)) } else { resp }; + if resp.clicked() { + section = id.to_string(); + } + } + }); + // The settings fill the dialog's resizable area down to the button row (#7420). Sizing them + // from the window instead left a resized dialog with empty space and the buttons mid-way. + // The area grows to fit its content, so this must never ask for more than it was given. + let content_height = settings_height(ui.available_height(), ui.spacing().item_spacing.y, crate::widgets::button_height(ui.ctx())); + crate::widgets::vline(ui, content_height); + ui.vertical(|ui| { + ui.set_width((ui.available_width() - 12.0).max(340.0)); + let title = SECTIONS.iter().find(|(id, _)| *id == section).map_or("General", |(_, t)| *t); + ui.label(RichText::new(tl!(&title)).font(crate::theme::semibold(14.0)).color(t.text)); + let show_all = search.trim().is_empty() + || title.to_lowercase().contains(&search.trim().to_lowercase()) + || tl!(&title).to_lowercase().contains(&search.trim().to_lowercase()); + let filter = if show_all { "" } else { search.trim() }; + ui.add_space(6.0); + egui::ScrollArea::vertical().max_height(content_height - 30.0).id_salt("prefs-scroll").show(ui, |ui| { + let order: Vec = + f.get("__order").and_then(|o| o.get(§ion)).and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); + if !has_visible_fields(&values, §ion) { + ui.add_space(4.0); + ui.label(RichText::new(tl!("These settings aren't available in PhotoCraft yet.")).color(t.text_faint)); + } else if let Some(obj) = values.get_mut(§ion).and_then(Value::as_object_mut) { + section_fields(ui, §ion, obj, &order, lang, system, filter); + if section == "fileHandling" { + ui.label( + RichText::new(tl!("0 turns this threshold off; SVG groups nested deeper than 100 levels are always rasterized.")) + .color(t.text_faint), + ); + } + if section == "performance" { + gpu_status_rows(ui, f.get("__gpuInfo"), f.get("__gpuAdapters"), obj); + } + ui.add_space(8.0); + } + if search.trim().is_empty() + && has_visible_fields(&values, §ion) + && crate::widgets::secondary_button(ui, tl!("Reset Section"), 110.0).clicked() + && let Some(def) = prefs::Preferences::default().get(§ion) + { + values[§ion] = def; + } + }); + }); + }); + f.insert("section".into(), json!(section)); + f.insert("__search".into(), json!(search)); + f.insert("values".into(), values); + // A colour swatch was clicked: open the Color Picker on that value (#2144). + if let Some((path, name)) = ctx_take_pick(ui) { + crate::color_picker_ui::request_field(f, &format!("/values/{}", path.replace('.', "/")), &crate::color_picker_ui::title_for(&name)); + } +} + +/// Does `section` have any setting the dialog shows (see [`prefs::HIDDEN_UNTIL_IMPLEMENTED`])? +pub(super) fn has_visible_fields(values: &Value, section: &str) -> bool { + values.get(section).and_then(Value::as_object).is_some_and(|o| o.keys().any(|k| !prefs::is_hidden(&format!("{section}.{k}")))) +} + +/// JPEG and WebP have independent settings; unrelated format controls stay out of view. +pub(super) fn export_field_visible(obj: &Map, key: &str) -> bool { + let format = obj.get("quickExportFormat").and_then(Value::as_str).unwrap_or("png"); + match key { + "convertToSrgb" | "metadata" => format != "exr", + "jpegQuality" => format == "jpg", + "webpLossless" => format == "webp", + "webpQuality" => format == "webp" && obj.get("webpLossless").and_then(Value::as_bool) != Some(true), + _ => true, + } +} + +/// The pause that bundles arrow-key nudges means nothing with Bundle Arrow-Key Nudges off (#2259). +pub(super) fn tools_field_visible(obj: &Map, key: &str) -> bool { + key != "nudgeBundlePauseMs" || obj.get("bundleNudges").and_then(Value::as_bool) != Some(false) +} + +/// A titled, outlined group of settings (Photoshop's Interface page has Appearance, +/// Presentation and Options). +fn pref_group(ui: &mut egui::Ui, title: &str, add: impl FnOnce(&mut egui::Ui)) { + let t = Tokens::get(ui.ctx()); + egui::Frame::new().stroke(egui::Stroke::new(1.0, t.card_border)).corner_radius(t.radius).inner_margin(10.0).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label(RichText::new(tl!(title)).strong().color(t.text)); + ui.add_space(4.0); + add(ui); + }); + ui.add_space(8.0); +} + +/// Preferences › Interface laid out like Photoshop's: the theme and canvas settings, then UI +/// language, font size and scaling, then everything else. Compact enough that the language +/// shows without scrolling in a small window (#2532). A search (`query`, lowercased) hides the +/// rows that don't match and skips a group left empty. +fn interface_groups(ui: &mut egui::Ui, obj: &mut Map, keys: &[String], lang: crate::i18n::Lang, system: Option, query: &str) { + const APPEARANCE: [&str; 3] = ["canvasColor", "canvasCustomColor", "canvasBorder"]; + const PRESENTATION: [&str; 3] = ["language", "uiFontSize", "uiScale"]; + let shown = |k: &str| keys.iter().any(|key| key == k) && field_visible("interface", obj, k, query); + // In Photoshop's order, not the stored one. + let pick = |names: &[&str]| names.iter().filter(|n| shown(n)).map(|n| n.to_string()).collect::>(); + let appearance = pick(&APPEARANCE); + let presentation = pick(&PRESENTATION); + let rest = keys.iter().filter(|k| !APPEARANCE.contains(&k.as_str()) && !PRESENTATION.contains(&k.as_str()) && shown(k)); + // Checkboxes line up at the left edge, as in Photoshop; the other options keep a label column. + let (checks, other): (Vec, Vec) = rest.cloned().partition(|k| obj.get(k).is_some_and(Value::is_boolean)); + let rows = AppearanceRows::matching(query); + let grid = |id: &str| egui::Grid::new(("prefs-grid", id.to_string())).num_columns(2).spacing([14.0, 7.0]).min_col_width(150.0); + if rows.any() || !appearance.is_empty() { + pref_group(ui, "Appearance", |ui| { + grid("interface-appearance").show(ui, |ui| { + appearance_rows(ui, obj, system, rows); + field_rows(ui, "interface", obj, appearance, lang); + }); + }); + } + if !presentation.is_empty() { + pref_group(ui, "Presentation", |ui| { + grid("interface-presentation").show(ui, |ui| field_rows(ui, "interface", obj, presentation, lang)); + }); + } + if !checks.is_empty() || !other.is_empty() { + pref_group(ui, "Options", |ui| { + egui::Grid::new("prefs-grid-interface-checks").num_columns(2).spacing([0.0, 7.0]).show(ui, |ui| field_rows(ui, "interface", obj, checks, lang)); + grid("interface-options").show(ui, |ui| field_rows(ui, "interface", obj, other, lang)); + }); + } +} + +/// Where a clicked colour swatch leaves its preference path and label for the dialog body, which +/// holds the fields the Color Picker request goes in. +const PICK_ID: &str = "prefs-pick-color"; + +/// The colour swatch clicked this frame, if any: (preference path, label). +fn ctx_take_pick(ui: &egui::Ui) -> Option<(String, String)> { + ui.ctx().data_mut(|d| d.remove_temp::<(String, String)>(egui::Id::unique(PICK_ID))) +} + +/// Whether `section.key` gets a generic row for this search (`query`, lowercased; empty matches +/// everything). Settings nothing reads yet stay out of the dialog (issue #204), as do those drawn +/// by their own widgets; their stored values pass through untouched. +pub(super) fn field_visible(section: &str, obj: &Map, k: &str, query: &str) -> bool { + let path = format!("{section}.{k}"); + let drawn_elsewhere = (section == "interface" && matches!(k, "theme" | "appearanceMode" | "darkTheme" | "lightTheme" | "favoriteThemes")) + // View › Rulers (⌘R) sets it, as in Photoshop. + || path == "unitsAndRulers.showRulers" + || (section == "performance" && matches!(k, "useGpu" | "gpuBackend" | "gpuAdapter" | "renderingMode" | "memoryUsageMb")) + // The browser presents frames itself: Low-Latency Drawing does nothing there. + || (cfg!(target_arch = "wasm32") && path == "performance.lowLatencyDrawing") + || (section == "export" && !export_field_visible(obj, k)) + || (section == "tools" && !tools_field_visible(obj, k)); + (query.is_empty() || preference_matches(section, k, query)) + && !drawn_elsewhere + && !prefs::is_hidden(&path) + && obj.get(k).is_some_and(|v| !matches!(v, Value::Null | Value::Object(_))) +} + +/// Generic editor for a section's fields: checkboxes, dropdowns for choices, colour swatches, +/// number fields with the preference's range, text fields. +pub(super) fn section_fields( + ui: &mut egui::Ui, + section: &str, + obj: &mut Map, + order: &[String], + lang: crate::i18n::Lang, + system: Option, + search: &str, +) { + let query = search.to_lowercase(); + let mut keys: Vec = order.iter().filter(|k| obj.contains_key(*k)).cloned().collect(); + keys.extend(obj.keys().filter(|k| !order.contains(k)).cloned()); + if section == "interface" { + interface_groups(ui, obj, &keys, lang, system, &query); + return; + } + if section == "performance" && (query.is_empty() || preference_matches(section, "renderingMode", &query)) { + rendering_mode_row(ui, obj); + } + if section == "performance" && (query.is_empty() || preference_matches(section, "memoryUsageMb", &query)) { + memory_usage_row(ui, obj); + } + keys.retain(|k| field_visible(section, obj, k, &query)); + egui::Grid::new(("prefs-grid", section)).num_columns(2).spacing([14.0, 7.0]).show(ui, |ui| field_rows(ui, section, obj, keys, lang)); +} + +/// One grid row per setting in `keys` (already filtered by `field_visible`). +fn field_rows(ui: &mut egui::Ui, section: &str, obj: &mut Map, keys: Vec, lang: crate::i18n::Lang) { + let t = Tokens::get(ui.ctx()); + for k in keys { + let path = format!("{section}.{k}"); + let v = obj.get(&k).cloned().unwrap_or(Value::Null); + let human = humanize(&k); + let label = tl!(&human).to_string(); + match &v { + Value::Bool(b) => { + ui.label(""); + let mut b = *b; + if read_at_launch(&path) { + ui.vertical(|ui| { + crate::widgets::checkbox(ui, &mut b, &label); + ui.label(RichText::new(tl!("Applies at next launch.")).color(t.text_dim)); + }); + } else { + crate::widgets::checkbox(ui, &mut b, &label); + } + obj.insert(k, json!(b)); + } + Value::String(s) if path == "interface.language" => { + ui.label(RichText::new(tl!(&label)).color(t.text_dim)); + let mut pairs: Vec<(String, &str)> = vec![("auto".into(), tl!("Auto"))]; + pairs.extend(crate::i18n::Lang::for_picker().into_iter().map(|l| (l.code().to_string(), l.name()))); + let mut cur = s.clone(); + crate::widgets::dropdown(ui, &format!("pref-{path}"), tl!(&label), &mut cur, &pairs, 220.0); + obj.insert(k, json!(cur)); + } + Value::String(s) if prefs::choices(&path).is_some() => { + ui.label(RichText::new(tl!(&label)).color(t.text_dim)); + let opts = prefs::choices(&path).unwrap_or(&[]); + let labels: Vec = opts.iter().map(|o| choice_label(o)).collect(); + let pairs: Vec<(String, &str)> = opts.iter().map(|o| o.to_string()).zip(labels.iter().map(String::as_str)).collect(); + let mut cur = s.clone(); + crate::widgets::dropdown(ui, &format!("pref-{path}"), tl!(&label), &mut cur, &pairs, 220.0); + obj.insert(k, json!(cur)); + } + Value::String(s) if prefs::is_color(&path) => { + ui.label(RichText::new(tl!(&label)).color(t.text_dim)); + let c = prefs::parse_hex(s).unwrap_or([128, 128, 128]); + let mut rgb = c; + ui.horizontal(|ui| { + // PhotoCraft's Color Picker, as everywhere else (#2144). + if crate::widgets::color_swatch_button(ui, egui::Color32::from_rgb(rgb[0], rgb[1], rgb[2]), &label).clicked() { + ui.ctx().data_mut(|d| d.insert_temp(egui::Id::unique(PICK_ID), (path.clone(), label.clone()))); + } + hex_field(ui, &path, &mut rgb); + }); + obj.insert(k, json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]))); + let _ = color_of(s); + } + Value::String(s) => { + ui.label(RichText::new(tl!(&label)).color(t.text_dim)); + let mut s = s.clone(); + ui.add(egui::TextEdit::singleline(&mut s).desired_width(260.0)).accessible_name(tl!(&label)); + obj.insert(k, json!(s)); + } + Value::Number(n) => { + let value_label = ui.label(RichText::new(tl!(&label)).color(t.text_dim)); + let (lo, hi) = prefs::range(&path).unwrap_or((-1e9, 1e9)); + if n.is_u64() || n.is_i64() { + let mut x = n.as_i64().unwrap_or(0); + ui.add(egui::DragValue::new(&mut x).range(lo as i64..=hi as i64).custom_parser(crate::widgets::parse_num)).labelled_by(value_label.id); + obj.insert(k, json!(x)); + // A row of its own, so the label stays level with its field. + if read_at_launch(&path) { + ui.end_row(); + ui.label(""); + ui.label(RichText::new(tl!("Applies at next launch.")).color(t.text_dim)); + } + } else { + let mut x = n.as_f64().unwrap_or(0.0); + ui.add(egui::DragValue::new(&mut x).range(lo..=hi).speed(0.1).max_decimals(3).custom_parser(crate::widgets::parse_num)) + .labelled_by(value_label.id); + obj.insert(k, json!(x)); + } + } + Value::Array(_) if path == "tools.pressureCurve" => { + ui.label(RichText::new(tl!(&label)).color(t.text_dim)); + if let Some(next) = crate::pressure_curve_ui::editor(ui, &v) { + obj.insert(k, next); + } + } + Value::Array(items) if k == "disks" => { + ui.label(RichText::new(tl!("Scratch disks")).color(t.text_dim)); + let mut items = items.clone(); + ui.vertical(|ui| { + for d in &mut items { + ui.horizontal(|ui| { + let mut on = d.get("enabled").and_then(Value::as_bool).unwrap_or(false); + let mut path = d.get("path").and_then(Value::as_str).unwrap_or("").to_string(); + crate::widgets::checkbox(ui, &mut on, tl!("Enabled")); + ui.add(egui::TextEdit::singleline(&mut path).desired_width(240.0)).accessible_name(tl!("Path")); + *d = json!({"enabled": on, "path": path}); + }); + } + if ui.small_button(tl!("Add disk")).clicked() { + items.push(json!({"enabled": true, "path": ""})); + } + }); + obj.insert(k, Value::Array(items)); + } + Value::Array(items) => { + ui.label(RichText::new(tl!(&label)).color(t.text_dim)); + ui.label(RichText::new(crate::i18n::trn(lang, items.len() as u64, "{n} item", "{n} items")).color(t.text_faint)); + if !items.is_empty() && ui.small_button(tl!("Clear")).clicked() { + obj.insert(k, json!([])); + } + } + _ => continue, + } + ui.end_row(); + } +} diff --git a/crates/ui-egui/src/prefs_ui/graphics.rs b/crates/ui-egui/src/prefs_ui/graphics.rs new file mode 100644 index 0000000000..63930425ea --- /dev/null +++ b/crates/ui-egui/src/prefs_ui/graphics.rs @@ -0,0 +1,141 @@ +use super::fields::choice_label; +use super::*; + +/// Performance › Graphics: the compositor's GPU memory budget and whether the active document's +/// layers fit it (the GPU Memory preference sets it). +pub(super) fn gpu_memory_lines(app: &PhotocraftApp) -> Vec { + let mut v = Vec::new(); + if app.perf.gpu_budget_mb > 0 { + let budget = crate::chrome_ui::fmt_bytes(app.perf.gpu_budget_mb.saturating_mul(1 << 20)); + v.push(crate::i18n::fmt(tl!("GPU memory budget: {budget}"), &[("budget", &budget)])); + } + let doc = app.session.active().map(|st| st.doc.id.0); + if let Some(fit) = app.perf.gpu_layer_fit.filter(|f| Some(f.doc) == doc) { + let args = [("needed", crate::chrome_ui::fmt_bytes(fit.needed)), ("budget", crate::chrome_ui::fmt_bytes(fit.budget))]; + let args: Vec<(&str, &str)> = args.iter().map(|(k, v)| (*k, v.as_str())).collect(); + v.push(if fit.fits() { + crate::i18n::fmt(tl!("This document's layers: {needed} of {budget} for layers"), &args) + } else { + crate::i18n::fmt(tl!("This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU"), &args) + }); + } + v +} + +/// Preferences › Performance: what the app renders with now, and a reset of the GPU backend +/// (a crashed start may have moved it to a safer choice). +pub(super) fn gpu_status_rows(ui: &mut egui::Ui, info: Option<&Value>, adapters: Option<&Value>, obj: &mut Map) { + let t = Tokens::get(ui.ctx()); + ui.add_space(10.0); + ui.label(RichText::new(tl!("Graphics")).font(crate::theme::semibold(12.5)).color(t.text)); + for line in info.and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + ui.label(RichText::new(line).color(t.text_dim)); + } + ui.add_space(4.0); + ui.label(RichText::new(tl!("Applies at next launch.")).color(t.text_faint)); + ui.collapsing(tl!("Advanced"), |ui| { + ui.horizontal(|ui| { + ui.label(tl!("GPU Backend")); + let mut current = obj.get("gpuBackend").and_then(Value::as_str).unwrap_or("auto").to_string(); + let options = prefs::choices("performance.gpuBackend").unwrap_or(&[]); + let labels: Vec = options.iter().map(|o| choice_label(o)).collect(); + let pairs: Vec<(String, &str)> = options.iter().map(|o| o.to_string()).zip(labels.iter().map(String::as_str)).collect(); + crate::widgets::dropdown(ui, "graphics-backend", tl!("GPU Backend"), &mut current, &pairs, 220.0); + obj.insert("gpuBackend".into(), json!(current)); + }); + if !prefs::is_hidden("performance.gpuAdapter") { + graphics_adapter_row(ui, adapters, obj); + } + }); +} + +/// Preferences › Performance › Graphics Adapter: which GPU draws on a machine with several. The +/// value is the adapter's name; empty is automatic. A saved adapter that isn't present now (an +/// unplugged eGPU) stays listed, marked ⚠, so opening the dialog doesn't silently change the choice. +fn graphics_adapter_row(ui: &mut egui::Ui, adapters: Option<&Value>, obj: &mut Map) { + let mut current = obj.get("gpuAdapter").and_then(Value::as_str).unwrap_or("").to_string(); + let mut names: Vec = adapters.and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); + // A saved name fragment ("nvidia") isn't an adapter's full name but still selects one; only a + // value no listed adapter matches is marked. + let kept = !current.is_empty() && !names.contains(¤t); + let missing = kept && !names.iter().any(|n| prefs::gpu_adapter_matches(n, ¤t)); + if kept { + names.push(current.clone()); + } + let automatic = tl!("Automatic"); + let labels: Vec = names.iter().map(|n| if missing && *n == current { format!("⚠ {n}") } else { n.clone() }).collect(); + let mut pairs: Vec<(String, &str)> = vec![(String::new(), automatic)]; + pairs.extend(names.iter().cloned().zip(labels.iter().map(String::as_str))); + ui.horizontal(|ui| { + ui.label(tl!("GPU adapter")); + crate::widgets::dropdown_literal(ui, "graphics-adapter", tl!("GPU adapter"), &mut current, &pairs, 320.0); + }); + ui.label(RichText::new(tl!("Applies at next launch.")).color(Tokens::get(ui.ctx()).text_faint)); + obj.insert("gpuAdapter".into(), json!(current)); +} + +/// One user-facing choice; legacy flags remain compatible with older settings. +pub(super) fn rendering_mode_row(ui: &mut egui::Ui, obj: &mut Map) { + let mut current = rendering_mode_value(obj); + ui.horizontal(|ui| { + ui.label(tl!("Rendering Mode")); + let pairs = + vec![("auto".to_string(), tl!("Automatic (recommended)")), ("gpu".to_string(), tl!("GPU")), ("cpu".to_string(), tl!("CPU / Compatibility"))]; + let previous = current.clone(); + crate::widgets::dropdown(ui, "rendering-mode", tl!("Rendering Mode"), &mut current, &pairs, 240.0); + if current != previous { + obj.insert("renderingMode".into(), json!(current)); + obj.insert("useGpu".into(), json!(current != "cpu")); + } + }); + ui.label(tl!("Automatic uses GPU acceleration when available and falls back to CPU rendering on errors.")); + // Next to the setting, as for System Title Bar (#1677): the renderer is picked when the + // window opens, so a change otherwise looks like it did nothing (#7939). + ui.label(RichText::new(tl!("Applies at next launch.")).color(Tokens::get(ui.ctx()).text_dim)); + ui.add_space(8.0); +} + +pub(super) fn rendering_mode_value(obj: &Map) -> String { + obj.get("renderingMode").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| { + if obj.get("useGpu").and_then(Value::as_bool) == Some(false) || obj.get("gpuBackend").and_then(Value::as_str) == Some("cpu") { + "cpu".into() + } else { + "auto".into() + } + }) +} + +/// Explain the per-document RAM limit separately from the graphics-memory preference. +pub(super) fn memory_usage_row(ui: &mut egui::Ui, obj: &mut Map) { + let t = Tokens::get(ui.ctx()); + ui.group(|ui| { + ui.label(RichText::new(tl!("Memory Usage")).strong()); + let mut mb = obj.get("memoryUsageMb").and_then(Value::as_u64).unwrap_or(8192); + ui.horizontal(|ui| { + let limit_label = ui.label(tl!("Per-document RAM limit (MB)")); + if ui.add(egui::DragValue::new(&mut mb).range(256..=1_048_576).suffix(" MB")).labelled_by(limit_label.id).changed() { + obj.insert("memoryUsageMb".into(), json!(mb)); + } + }); + if let Some(ram) = crate::gpu_canvas::physical_memory().filter(|n| *n > 0) { + let installed = ram / (1 << 20); + let percent = mb as f64 * 100.0 / (ram as f64 / (1 << 20) as f64); + ui.label(crate::i18n::fmt(tl!("Installed RAM: {ram} MB; this limit: {percent}%"), &[("ram", &installed.to_string()), ("percent", &format!("{percent:.1}"))])); + } + ui.label(RichText::new(tl!("Limits each open document's pixels plus History. Oldest undo states are discarded when the limit is exceeded.")).color(t.text_dim)); + ui.label(RichText::new(tl!("Applies immediately when saved. Memory is not reserved in advance.")).color(t.text_dim)); + ui.label(RichText::new(tl!("With GPU Memory set to Automatic, this also limits the GPU layer budget. That budget is capped at one quarter of installed RAM and, when known, three eighths of the graphics card's memory, with a 512 MB minimum. Raising this limit beyond those caps does not increase the GPU budget.")).color(t.text_dim)); + }); + ui.add_space(8.0); +} + +/// Settings read only when the app starts, which say "Applies at next launch." under their row. +pub(super) fn read_at_launch(path: &str) -> bool { + match path { + // Only Windows and Linux draw their own title bar. + "interface.systemTitleBar" => cfg!(all(not(target_arch = "wasm32"), not(target_os = "macos"))), + // The desktop app decides on the control server before its window opens. + "integrations.allowAgentControl" | "integrations.controlPort" => cfg!(not(target_arch = "wasm32")), + _ => false, + } +} diff --git a/crates/ui-egui/src/prefs_ui/save.rs b/crates/ui-egui/src/prefs_ui/save.rs new file mode 100644 index 0000000000..78408b5e1f --- /dev/null +++ b/crates/ui-egui/src/prefs_ui/save.rs @@ -0,0 +1,342 @@ +use super::appearance::{canvas_style, sync_animations, sync_appearance, sync_display_scale, sync_tooltips}; +use super::startup::{load, presets_store, recovery, sync_rulers}; +use super::*; + +/// Per-frame upkeep: theme sync, persistence, autosave and the history log. +pub fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) { + if !app.prefs_rt.loaded { + load(app); + } + recovery(app); + sync_rulers(app); + sync_display_scale(app, ctx); + sync_appearance(app, ctx); + crate::theme::set_ui_font_size(ctx, app.session.prefs().interface.ui_font_size); + presets_store(app); + sync_tooltips(app, ctx); + sync_animations(app, ctx); + app.sync_recent(); + // Monotonic, not `ctx.input(|i| i.time)`: logic also runs on hidden ticks, where egui's input + // time is that of the last UI pass. + if let Some(wait) = persist(app, crate::gpu_canvas::now_ms() / 1000.0) { + ctx.request_repaint_after(std::time::Duration::try_from_secs_f64(wait).unwrap_or_default()); + } + let style = canvas_style(app); + if let Some(gpu) = app.gpu.as_ref() + && app.prefs_rt.gpu_style != Some(style) + { + gpu.set_style(style); + app.prefs_rt.gpu_style = Some(style); + } + autosave(app); + #[cfg(not(target_arch = "wasm32"))] + link_updates(app, ctx); + history_log(app); +} + +/// First retry delay after a failed preferences write, in seconds; it doubles with every further +/// failure up to [`SAVE_RETRY_MAX_S`]. A new change retries sooner, but no sooner than this. +pub(super) const SAVE_RETRY_S: f64 = 2.0; + +pub(super) const SAVE_RETRY_MAX_S: f64 = 30.0; + +/// Failed writes in a row before a notice says preferences aren't being saved. +const SAVE_NOTICE_AFTER: u32 = 3; + +/// Retry state of a failed preferences write (times are egui input time, in seconds). +#[derive(Default)] +pub(super) struct SaveRetry { + failures: u32, + /// When the next retry is due. + at: f64, + /// When the last write was tried, and the revision it carried. + tried_at: f64, + tried_rev: u64, + /// The "not saved" notice, while it's shown. + notice: Option, +} + +/// Save changed preferences. A failed write stays pending and is retried with a backoff (a newer +/// change retries sooner); the status bar reports the first failure and a notice a persistent +/// one. Returns the seconds until the next retry while one is pending. +pub(super) fn persist(app: &mut PhotocraftApp, now: f64) -> Option { + let rev = app.session.prefs.rev(); + if rev == app.prefs_rt.saved_rev { + return None; + } + let r = &app.prefs_rt.save_retry; + if r.failures > 0 { + let due = if rev == r.tried_rev { r.at } else { r.at.min(r.tried_at + SAVE_RETRY_S) }; + if now < due { + return Some(due - now); + } + } + let ours = app.session.prefs_value(); + // A change that was undone (or set a value to what it already was) leaves nothing to write. + let written = if app.prefs_rt.saved_value.as_ref() == Some(&ours) { Ok(()) } else { write_prefs(app, &ours) }; + match written { + Ok(()) => { + app.prefs_rt.saved_rev = rev; + app.prefs_rt.saved_value = Some(ours); + let r = std::mem::take(&mut app.prefs_rt.save_retry); + if r.failures > 0 { + let message = "Preferences saved"; + app.ui.status = tl!(message).into(); + app.ui.status_error = false; + if let Some(id) = r.notice { + app.ui.notices.retain(|n| n.id != id); + } + } + None + } + Err(e) => { + let r = &mut app.prefs_rt.save_retry; + r.failures = r.failures.saturating_add(1); + (r.tried_at, r.tried_rev) = (now, rev); + let delay = (SAVE_RETRY_S * 2f64.powi(r.failures.min(16) as i32 - 1)).min(SAVE_RETRY_MAX_S); + r.at = now + delay; + let failures = r.failures; + if failures == 1 { + let template = "Couldn't save preferences: {error}. Retrying…"; + app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]); + app.ui.status_error = true; + } else if failures == SAVE_NOTICE_AFTER { + let lines = vec![e, "PhotoCraft keeps retrying; until a save succeeds, preference changes are lost when it closes.".into()]; + let id = crate::notices::post(app, "Preferences can't be saved", lines, true, None); + app.prefs_rt.save_retry.notice = Some(id); + } + Some(delay) + } + } +} + +/// Write `ours` over the stored preferences, keeping what another instance (a second browser +/// tab, another app window) changed there since this one last loaded or saved them. +fn write_prefs(app: &mut PhotocraftApp, ours: &Value) -> Result<(), String> { + let Some(save) = app.services.save_prefs.as_mut() else { return Ok(()) }; + let stored = app.services.load_prefs.as_mut().and_then(|load| load()).and_then(|t| serde_json::from_str::(&t).ok()); + let text = match (stored, &app.prefs_rt.saved_value) { + (Some(mut theirs @ Value::Object(_)), Some(base)) => { + let base = &without_stale_migration(base, &theirs); + merge_changes(base, ours, &mut theirs); + serde_json::to_string_pretty(&theirs) + } + _ => serde_json::to_string_pretty(ours), + } + .map_err(|e| e.to_string())?; + save(&text) +} + +/// The save base without the shift tool switch migration (#5647) once storage already holds a +/// version 2 file: another instance wrote it, so its Use Shift Key for Tool Switch is a choice, +/// not the old default this instance migrated. The base then holds the migrated value (on) instead +/// of the old file's off, so only a change made here since loading is written over that choice. +fn without_stale_migration(base: &Value, theirs: &Value) -> Value { + let mut base = base.clone(); + let new_file = |v: &Value| v.get("version").and_then(Value::as_u64).is_some_and(|v| v >= 2); + if new_file(theirs) && !new_file(&base) { + let key = "useShiftKeyForToolSwitch"; + if let Some(tools) = base.get_mut("tools").and_then(Value::as_object_mut) + && tools.get(key) == Some(&Value::Bool(false)) + { + tools.insert(key.into(), Value::Bool(true)); + } + } + base +} + +/// Three-way merge of preference trees: whatever `ours` changed since `base` goes over `theirs` +/// (what storage holds now) and the rest of `theirs` is kept. Objects merge key by key; any +/// other value, arrays included, is replaced whole. +pub(super) fn merge_changes(base: &Value, ours: &Value, theirs: &mut Value) { + if ours == base { + return; + } + match (base, ours, theirs) { + (Value::Object(b), Value::Object(o), Value::Object(t)) => { + for (k, ov) in o { + match (b.get(k), t.get_mut(k)) { + (Some(bv), Some(tv)) => merge_changes(bv, ov, tv), + // Removed there, unchanged here: it stays removed. + (Some(bv), None) if bv == ov => {} + _ => { + t.insert(k.clone(), ov.clone()); + } + } + } + for k in b.keys().filter(|k| !o.contains_key(*k)) { + t.remove(k); + } + } + (_, _, theirs) => *theirs = ours.clone(), + } +} + +/// Write the preferences now, through the same merge as [`persist`], for recovery choices that +/// need the result immediately. The pending revision stays unsaved when the write fails. +pub(crate) fn save_preferences(app: &mut PhotocraftApp) -> Result<(), String> { + let rev = app.session.prefs.rev(); + let ours = app.session.prefs_value(); + write_prefs(app, &ours)?; + app.prefs_rt.saved_rev = rev; + app.prefs_rt.saved_value = Some(ours); + if let Some(id) = std::mem::take(&mut app.prefs_rt.save_retry).notice { + app.ui.notices.retain(|n| n.id != id); + } + Ok(()) +} + +/// Linked smart objects follow their files while the document is open, as in Photoshop: every two +/// seconds, and as soon as the window comes back to the front (after saving in another app), stamp +/// the active document's linked files on a worker thread and re-render the layers of the ones that +/// changed ([`photocraft_engine::link_watch`]). +#[cfg(not(target_arch = "wasm32"))] +fn link_updates(app: &mut PhotocraftApp, ctx: &egui::Context) { + match app.session.poll_link_scan() { + Some(Ok(r)) => { + if let Some(n) = r["updated"].as_array().map(Vec::len).filter(|n| *n > 0) { + app.ui.status = crate::i18n::trn( + crate::i18n::current(), + n as u64, + "Updated {n} linked smart object changed on disk", + "Updated {n} linked smart objects changed on disk", + ); + } + } + Some(Err(e)) => app.ui.status = e.to_string(), + None => {} + } + let (last_key, focus_key) = (egui::Id::unique("linkWatch.lastScan"), egui::Id::unique("linkWatch.focused")); + let now = crate::gpu_canvas::now_ms() / 1000.0; + let focused = ctx.input(|i| i.focused); + let was_focused: bool = ctx.data(|d| d.get_temp(focus_key)).unwrap_or(focused); + ctx.data_mut(|d| d.insert_temp(focus_key, focused)); + let has_links = app.session.active().is_some_and(|d| !photocraft_engine::link_watch::linked_files(&d.doc).is_empty()); + if !has_links { + return; + } + let last: f64 = ctx.data(|d| d.get_temp(last_key)).unwrap_or(f64::NEG_INFINITY); + if now - last >= 2.0 || (focused && !was_focused) { + ctx.data_mut(|d| d.insert_temp(last_key, now)); + app.session.start_link_scan(); + } + let wait = if app.session.link_scan.is_some() { 100 } else { 2000 }; + ctx.request_repaint_after(std::time::Duration::from_millis(wait)); +} + +/// Background autosave of documents with unsaved changes every N minutes (File Handling). +fn autosave(app: &mut PhotocraftApp) { + let fh = &app.session.prefs().file_handling; + let (on, minutes) = (fh.autosave, fh.autosave_minutes.max(1)); + if app.services.autosave.is_none() { + return; + } + // A successful queue operation is not a successful disk write. Poll each frame, + // including frames before the next autosave interval, so failures are visible. + if let Some(results) = app.services.autosave_results.as_mut() { + for (raw_id, revision, result) in results() { + let id = DocId(raw_id); + if app.prefs_rt.autosave_pending.get(&id) != Some(&revision) { + continue; + } + app.prefs_rt.autosave_pending.remove(&id); + match result { + Ok(()) => { + app.prefs_rt.autosaved.insert(id, revision); + } + Err(e) => { + let template = "Autosave failed: {error}"; + app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]); + app.ui.status_error = true; + } + } + } + } + let now = crate::gpu_canvas::now_ms(); + // Saved or closed documents drop their recovery data. + let live: HashMap = app.session.documents().iter().map(|d| (d.doc.id, d.is_dirty())).collect(); + let mut stale: Vec = app.prefs_rt.autosaved.keys().filter(|id| live.get(id) != Some(&true)).copied().collect(); + stale.extend(app.prefs_rt.autosave_pending.keys().filter(|id| live.get(*id) != Some(&true) && !app.prefs_rt.autosaved.contains_key(*id)).copied()); + for id in stale { + app.prefs_rt.autosaved.remove(&id); + app.prefs_rt.autosave_pending.remove(&id); + if let Some(d) = app.services.discard_autosave.as_mut() { + d(id.0); + } + } + if !on { + return; + } + let interval = minutes as f64 * 60_000.0; + if app.prefs_rt.next_autosave_ms == 0.0 || app.prefs_rt.next_autosave_ms > now + interval { + app.prefs_rt.next_autosave_ms = now + interval; + return; + } + if now < app.prefs_rt.next_autosave_ms { + return; + } + app.prefs_rt.next_autosave_ms = now + interval; + let jobs: Vec<_> = app + .session + .documents() + .iter() + .filter(|d| d.is_dirty() && app.prefs_rt.autosaved.get(&d.doc.id) != Some(&d.revision) && !app.prefs_rt.autosave_pending.contains_key(&d.doc.id)) + .map(|d| (d.doc.clone(), d.revision, d.path.clone())) + .collect(); + for (doc, rev, path) in jobs { + if let Some(save) = app.services.autosave.as_mut() { + match save(&doc, rev, path.as_deref()) { + Ok(()) => { + if app.services.autosave_results.is_some() { + app.prefs_rt.autosave_pending.insert(doc.id, rev); + } else { + // Synchronous or mocked services report completion on return. + app.prefs_rt.autosaved.insert(doc.id, rev); + } + } + Err(e) => { + let template = "Autosave failed: {error}"; + app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]); + app.ui.status_error = true; + } + } + } + } +} + +/// Force the autosave timer to fire on the next tick (tests, `prefs` changes). +pub fn autosave_now(app: &mut PhotocraftApp) { + app.prefs_rt.next_autosave_ms = f64::MIN_POSITIVE; +} + +/// History Log preference: append executed commands to a text file. +fn history_log(app: &mut PhotocraftApp) { + let n = app.session.journal.len(); + if n <= app.prefs_rt.log_len { + app.prefs_rt.log_len = n; + return; + } + let hl = app.session.prefs().history_log.clone(); + let start = app.prefs_rt.log_len; + app.prefs_rt.log_len = n; + if !hl.enabled || hl.file_path.is_empty() || hl.destination == prefs::LogDestination::Metadata { + return; + } + let Some(append) = app.services.append_text.as_mut() else { return }; + let mut text = String::new(); + for (id, params) in &app.session.journal[start..] { + let label = photocraft_engine::commands::find(id).map_or(id.as_str(), |c| c.label).trim_end_matches('…'); + match hl.detail { + prefs::LogDetail::SessionsOnly => { + if matches!(id.as_str(), "file.new" | "file.open" | "file.close" | "file.openAs") { + text.push_str(&format!("{label}\n")); + } + } + prefs::LogDetail::Concise => text.push_str(&format!("{label}\n")), + prefs::LogDetail::Detailed => text.push_str(&format!("{label} {id} {params}\n")), + } + } + if !text.is_empty() { + let _ = append(&hl.file_path, &text); + } +} diff --git a/crates/ui-egui/src/prefs_ui/shortcuts.rs b/crates/ui-egui/src/prefs_ui/shortcuts.rs new file mode 100644 index 0000000000..73b7d475d9 --- /dev/null +++ b/crates/ui-egui/src/prefs_ui/shortcuts.rs @@ -0,0 +1,698 @@ +use super::dialogs::toolbar_tab; +use super::*; + +/// Every shortcut-bearing command (engine registry plus shell commands): (id, label, menu path, +/// default shortcut), menu items first in Photoshop order. +pub fn shortcut_items(app: &PhotocraftApp) -> Vec<(String, String, Vec, Option)> { + let mut out: Vec<(String, String, Vec, Option)> = Vec::new(); + let mut seen = std::collections::HashSet::new(); + for it in crate::menus::menu_items(app) { + if it.label == "---" || !seen.insert(it.id.clone()) { + continue; + } + let default = default_shortcut(&it.id).or(it.shortcut.clone().filter(|_| !app.session.prefs().shortcuts.contains_key(&it.id))); + out.push((it.id, it.label, it.path, default)); + } + // Commands without a menu item: the colour and fill keys (D, X, ⌥⌫…) sit under Tools, as + // Photoshop lists its colour keys in the Tools shortcut set, after the rest; then the held + // temporary tools (#249). + let tools_key = |id: &str| id.starts_with("tools.") || photocraft_engine::fill_key_cmds::IDS.contains(&id); + let mut tools = Vec::new(); + let mut layer = Vec::new(); + for c in photocraft_engine::command_specs() { + if seen.insert(c.id.to_string()) && c.shortcut.is_some() { + let item = (c.id.to_string(), c.label.to_string(), c.menu.iter().map(|s| s.to_string()).collect::>(), c.shortcut.map(Into::into)); + if c.menu.is_empty() && tools_key(c.id) { + tools.push((item.0, item.1, vec!["Tools".to_string()], item.3)); + } else if c.menu.is_empty() && c.id.starts_with("layer.") { + // Stamp Visible / Stamp Down (#217): no menu item in Photoshop; listed at the end + // of the Layer section. + layer.push((item.0, item.1, vec!["Layer".to_string()], item.3)); + } else { + out.push(item); + } + } + } + let at = out.iter().rposition(|i| i.2.first().map(String::as_str) == Some("Layer")).map_or(out.len(), |i| i + 1); + out.splice(at..at, layer); + out.extend(tools); + out.extend( + crate::state::Tool::ALL + .into_iter() + .map(|tool| (crate::tool_shortcuts::id(tool), tool.label().to_string(), vec!["Tools".into()], crate::tool_shortcuts::default(tool))), + ); + for (id, label, def) in prefs::TEMPORARY_TOOLS { + if seen.insert(id.to_string()) { + out.push((id.to_string(), label.to_string(), vec!["Tools".into(), "Temporary".into()], Some(def.to_string()))); + } + } + out +} + +/// A fingerprint of the bindings a shortcut conflict describes. +fn conflict_state(overrides: &BTreeMap, alternates: &BTreeMap>, selected: &str, set: Option<&Value>) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + (overrides, alternates, selected, set.map(Value::to_string)).hash(&mut h); + h.finish() +} + +/// Keys the system takes before the app sees them (switching apps, closing the window, force +/// quit): Edit › Keyboard Shortcuts won't assign them, as Photoshop won't. `sc` is in our +/// notation, where `Cmd` is Ctrl off the Mac. +pub fn reserved_shortcut(sc: &str) -> bool { + prefs::reserved_shortcut(sc) +} + +/// Text of a key press for the shortcut editor (`Cmd+Shift+K`), `None` for bare modifiers. +pub fn shortcut_text(key: egui::Key, m: egui::Modifiers) -> Option { + if is_modifier_key(key) { + return None; + } + let mut parts = Vec::new(); + if m.command || m.mac_cmd { + parts.push(tl!("Cmd").to_string()); + } + if m.ctrl && !m.command { + parts.push(tl!("Ctrl").into()); + } + if m.alt { + parts.push(tl!("Alt").into()); + } + if m.shift { + parts.push(tl!("Shift").into()); + } + let name = match key { + egui::Key::Equals => "=", + egui::Key::Minus => "-", + egui::Key::OpenBracket => "[", + egui::Key::CloseBracket => "]", + egui::Key::Semicolon => ";", + egui::Key::Quote => "'", + egui::Key::Plus => "", + k => k.name(), + }; + parts.push(name.to_string()); + prefs::normalize_shortcut(&parts.join("+")) +} + +/// A modifier key on its own. egui reports Ctrl, Shift, Alt and ⌘ presses as key events too +/// (`ControlLeft`…), before the key pressed with them: they are never a shortcut's key, so +/// shortcut capture waits for the real key (#292: Ctrl+F was recorded as "Ctrl+ControlLeft"). +pub fn is_modifier_key(key: egui::Key) -> bool { + use egui::Key::*; + matches!(key, ShiftLeft | ShiftRight | ControlLeft | ControlRight | AltLeft | AltRight | SuperLeft | SuperRight) +} + +/// Modifier bits a physical modifier-key press contributes when egui leaves them out of +/// [`Modifiers`] on the key event (#7190). +fn modifier_key_modifiers(key: egui::Key) -> egui::Modifiers { + use egui::Key::*; + match key { + ShiftLeft | ShiftRight => egui::Modifiers::SHIFT, + ControlLeft | ControlRight => egui::Modifiers::CTRL, + AltLeft | AltRight => egui::Modifiers::ALT, + SuperLeft | SuperRight => egui::Modifiers::COMMAND, + _ => egui::Modifiers::NONE, + } +} + +fn capture_mods_field(v: Option<&Value>) -> egui::Modifiers { + let o = v.and_then(Value::as_object); + egui::Modifiers { + shift: o.and_then(|o| o.get("shift")).and_then(Value::as_bool).unwrap_or(false), + ctrl: o.and_then(|o| o.get("ctrl")).and_then(Value::as_bool).unwrap_or(false), + alt: o.and_then(|o| o.get("alt")).and_then(Value::as_bool).unwrap_or(false), + command: o.and_then(|o| o.get("command")).and_then(Value::as_bool).unwrap_or(false), + mac_cmd: o.and_then(|o| o.get("mac_cmd")).and_then(Value::as_bool).unwrap_or(false), + } +} + +fn capture_mods_json(m: egui::Modifiers) -> Value { + json!({ + "shift": m.shift, + "ctrl": m.ctrl, + "alt": m.alt, + "command": m.command, + "mac_cmd": m.mac_cmd, + }) +} + +/// While capture is active: refresh held modifiers (including across frames via dialog +/// `captureMods`) and, if a non-modifier key was pressed this frame, return it with the +/// modifiers held with it. +/// +/// #7190 root cause: capture used to [`find_map`](Iterator::find_map) the first non-modifier +/// [`Event::Key`] and pass only that event's `modifiers` into [`shortcut_text`]. On Linux and +/// Windows, winit/egui often reports `ShiftLeft`/`ShiftRight` (and sometimes the letter key) with +/// [`Modifiers::NONE`], and the modifier down and the letter down often land in separate UI +/// frames. Shift was then missing from the stored binding (`F6` instead of `Shift+F6`). Like #292 +/// for `ControlLeft`, we walk the frame's events, OR in [`modifier_key_modifiers`] for modifier +/// keys, and persist accumulated modifiers in `captureMods` until capture ends. +pub(crate) fn capture_key_press(capture_mods: egui::Modifiers, i: &egui::InputState) -> (egui::Modifiers, Option<(egui::Key, egui::Modifiers)>) { + let mut mods = capture_mods | i.modifiers; + let mut pressed = None; + for e in &i.events { + if let egui::Event::ModifiersChanged(m) = e { + mods = *m; + } + if let egui::Event::Key { key, pressed: true, modifiers, .. } = e { + if is_modifier_key(*key) { + mods = *modifiers | modifier_key_modifiers(*key); + continue; + } + pressed = Some((*key, mods | *modifiers)); + break; + } + if let egui::Event::Key { key, pressed: false, modifiers, .. } = e + && is_modifier_key(*key) + { + mods = *modifiers; + } + } + (mods, pressed) +} + +/// Keyboard Shortcuts and Menus: a searchable list of commands by menu with editable shortcuts +/// (click a shortcut, press keys; ⌫ removes it), menu visibility and colours, toolbar tools. +pub(super) fn shortcuts_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { + let t = Tokens::get(ui.ctx()); + let mut tab = f.get("tab").and_then(Value::as_u64).unwrap_or(0); + ui.horizontal(|ui| { + for (i, name) in [tl!("Keyboard Shortcuts"), tl!("Menus"), tl!("Toolbar")].iter().enumerate() { + if crate::widgets::pill_tab(ui, name, tab == i as u64).clicked() { + tab = i as u64; + f.insert("capture".into(), json!(false)); + } + } + }); + f.insert("tab".into(), json!(tab)); + ui.add_space(6.0); + if tab == 2 { + toolbar_tab(ui, f); + return; + } + // A malformed map (set over automation) is left as it is, so OK rejects it instead of + // saving the empty map drawn in its place. + let parsed = f.get("overrides").map(|v| serde_json::from_value::>(v.clone())); + let overrides_ok = parsed.as_ref().is_none_or(Result::is_ok); + let mut overrides = parsed.and_then(Result::ok).unwrap_or_default(); + // A command's further keys (#3665): id → keys, replacing its default alternates. + let parsed_alts = f.get("alternates").map(|v| serde_json::from_value::>>(v.clone())); + let alternates_ok = parsed_alts.as_ref().is_none_or(Result::is_ok); + let mut alt_overrides = parsed_alts.and_then(Result::ok).unwrap_or_default(); + let mut capture_alt = f.get("captureAlt").and_then(Value::as_bool).unwrap_or(false); + // A key just assigned that another command holds: Photoshop's Accept and Go to Conflict / + // Undo Changes (an object: the key, the other command, and this one's keys before). + let mut conflict: Option = f.get("conflict").filter(|c| c.is_object()).cloned(); + let mut hidden: Vec = f.get("hidden").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); + let mut colors: BTreeMap = f.get("colors").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); + let mut selected = f.get("selected").and_then(Value::as_str).unwrap_or("").to_string(); + let mut capture = f.get("capture").and_then(Value::as_bool).unwrap_or(false); + let mut message = f.get("message").and_then(Value::as_str).unwrap_or("").to_string(); + let mut message_warning = f.get("messageWarning").and_then(Value::as_bool).unwrap_or(false); + let items = shortcut_items(app); + // The Set row, then the search (the Menus tab searches too). + if tab == 0 { + set_row(app, ui, f, &mut overrides, &mut alt_overrides, &items, &mut message, &mut message_warning); + ui.add_space(4.0); + } + let mut filter = f.get("filter").and_then(Value::as_str).unwrap_or("").to_string(); + ui.horizontal(|ui| { + ui.label(RichText::new(tl!("Search")).color(t.text_dim)); + ui.add(egui::TextEdit::singleline(&mut filter).desired_width(260.0).hint_text(tl!("command or shortcut"))); + }); + f.insert("filter".into(), json!(filter)); + // Menu path and command label as shown in the menus, in the UI language. + let shown = |id: &str, label: &str, path: &[String]| -> (Vec, String) { + let lang = crate::i18n::current(); + (path.iter().map(|p| crate::i18n::tr(lang, p).to_string()).collect(), crate::i18n::tr_id(lang, id, label).to_string()) + }; + let eff = |overrides: &BTreeMap, id: &str, def: &Option| -> Option { + match overrides.get(id) { + Some(s) if s.is_empty() => None, + Some(s) => Some(s.clone()), + None => def.clone(), + } + }; + // A command's further keys as the dialog stands: its edited list, else its defaults. + let eff_alts = |alts: &BTreeMap>, id: &str, main: Option<&str>| -> Vec { + let mut p = prefs::Preferences::default(); + if let Some(list) = alts.get(id) { + p.alternate_shortcuts.insert(id.to_string(), list.clone()); + } + p.alternates(id, main) + }; + let mut capture_mods = capture_mods_field(f.get("captureMods")); + // Key capture for the selected command: its main key, or (Add Shortcut) one more key. + if capture && tab == 0 && !selected.is_empty() { + let (next_mods, pressed) = ui.input(|i| capture_key_press(capture_mods, i)); + capture_mods = next_mods; + if let Some((key, m)) = pressed { + ui.input_mut(|i| { + i.consume_key(m, key); + }); + if key == egui::Key::Escape { + capture = false; + conflict = None; + } else if matches!(key, egui::Key::Backspace | egui::Key::Delete) && m.is_none() { + if capture_alt { + alt_overrides.insert(selected.clone(), Vec::new()); + } else { + overrides.insert(selected.clone(), String::new()); + } + capture = false; + message = tl!("Shortcut removed.").into(); + message_warning = false; + } else if let Some(sc) = shortcut_text(key, m).filter(|sc| reserved_shortcut(sc)) { + message = crate::i18n::fmt(tl!("{shortcut} is reserved by the system and can't be assigned."), &[("shortcut", &crate::shortcuts::pretty(&sc))]); + message_warning = true; + capture = false; + } else if let Some(sc) = shortcut_text(key, m) { + let clash_ids: Vec<&str> = items + .iter() + .filter(|(id, _, _, def)| { + let cur = eff(&overrides, id, def); + *id != selected + && (cur.as_deref().and_then(prefs::normalize_shortcut) == Some(sc.clone()) + || eff_alts(&alt_overrides, id, cur.as_deref()).contains(&sc)) + }) + .map(|(id, ..)| id.as_str()) + .collect(); + let clash: Vec = items + .iter() + .filter(|(id, ..)| clash_ids.contains(&id.as_str())) + .map(|(id, label, path, _)| { + let (path, label) = shown(id, label, path); + format!("{} › {}", path.join(" › "), label.trim_end_matches('…')) + }) + .collect(); + // What Undo Changes puts back: the command's main key and further keys as they were. + if let Some(first) = clash_ids.first() { + conflict = Some(json!({ + "shortcut": sc, + "with": first, + // Every command holding the key: Accept takes it from all of them. + "holders": clash_ids, + "command": selected, + "main": overrides.get(&selected), + "alternates": alt_overrides.get(&selected), + })); + } else { + conflict = None; + } + if capture_alt { + let def = items.iter().find(|i| i.0 == selected).and_then(|i| i.3.clone()); + let cur = eff(&overrides, &selected, &def); + let mut keys = eff_alts(&alt_overrides, &selected, cur.as_deref()); + if cur.as_deref().and_then(prefs::normalize_shortcut) != Some(sc.clone()) && !keys.contains(&sc) && keys.len() < prefs::MAX_ALTERNATES { + keys.push(sc.clone()); + } + alt_overrides.insert(selected.clone(), keys); + } else { + overrides.insert(selected.clone(), sc.clone()); + } + message_warning = !clash.is_empty(); + message = if clash.is_empty() { + let template = "{shortcut} assigned."; + crate::i18n::fmt(tl!(template), &[("shortcut", &crate::shortcuts::pretty(&sc))]) + } else { + let template = "{shortcut} is already in use by {commands} and will be removed from it when you click OK."; + crate::i18n::fmt(tl!(template), &[("shortcut", &crate::shortcuts::pretty(&sc)), ("commands", &clash.join(", "))]) + }; + capture = false; + } + } + } + let needle = filter.to_ascii_lowercase(); + egui::ScrollArea::vertical().max_height(420.0).id_salt("shortcuts-scroll").show(ui, |ui| { + let mut last_top = String::new(); + egui::Grid::new("shortcut-grid").num_columns(3).spacing([12.0, 3.0]).striped(true).show(ui, |ui| { + for (id, label, path, def) in &items { + if tab == 1 && crate::tool_shortcuts::tool(id).is_some() { + continue; + } + let cur = eff(&overrides, id, def); + let alts = eff_alts(&alt_overrides, id, cur.as_deref()); + let (shown_path, shown_label) = shown(id, label, path); + // Match what is shown and the English name (commands are documented in English). + let hay = + format!("{} {} {} {} {} {}", shown_path.join(" "), shown_label, path.join(" "), label, cur.clone().unwrap_or_default(), alts.join(" ")) + .to_lowercase(); + if !needle.is_empty() && !hay.contains(&needle) && !id.to_ascii_lowercase().contains(&needle) { + continue; + } + if tab == 0 && path.is_empty() && def.is_none() && cur.is_none() && alts.is_empty() { + continue; + } + let top = shown_path.first().cloned().unwrap_or_else(|| tl!("Other").into()); + if top != last_top { + ui.label(RichText::new(&top).font(crate::theme::semibold(12.5)).color(t.text)); + ui.label(""); + ui.label(""); + ui.end_row(); + last_top = top; + } + let name = match shown_path.get(1..) { + Some(rest) if !rest.is_empty() => format!("{} › {}", rest.join(" › "), shown_label), + _ => shown_label, + }; + let sel = selected == *id; + let name_row = ui.selectable_label(sel, RichText::new(format!(" {name}")).color(t.text_dim)); + if name_row.clicked() { + selected = id.clone(); + } + if tab == 0 { + let text = if sel && capture && !capture_alt { + tl!("Press keys…").to_string() + } else { + cur.as_deref().map(crate::shortcuts::pretty).unwrap_or_default() + }; + let changed = overrides.contains_key(id) || alt_overrides.contains_key(id); + let r = ui.add( + egui::Button::new(RichText::new(tl!(&text)).size(12.0).color(if changed { t.accent_text } else { t.text })).min_size(vec2(120.0, 18.0)), + ); + // An unassigned shortcut shows no text: name it by the command it binds. + let r = if text.is_empty() { r.labelled_by(name_row.id) } else { r }; + if r.clicked() { + selected = id.clone(); + capture = true; + capture_alt = false; + message.clear(); + message_warning = false; + } + // The further keys (F3 beside ⌘C), each removable on its own, as Photoshop + // lists them as rows of their own (#3665). + ui.horizontal(|ui| { + for k in &alts { + let b = egui::Button::new(RichText::new(format!("{} ×", crate::shortcuts::pretty(k))).size(11.0).color(t.text)).small(); + if ui.add(b).on_hover_text(tl!("Delete Shortcut")).clicked() { + alt_overrides.insert(id.clone(), alts.iter().filter(|x| *x != k).cloned().collect()); + selected = id.clone(); + message = tl!("Shortcut removed.").into(); + message_warning = false; + } + } + if sel && capture && capture_alt { + ui.label(RichText::new(tl!("Press keys…")).size(11.0).color(t.accent_text)); + } + if changed { + ui.label(RichText::new(tl!("modified")).color(t.text_faint).size(10.5)); + } + }); + } else { + // Edit › Menus, Keyboard Shortcuts, Preferences, Save and Exit always stay (#5096). + let hideable = photocraft_engine::prefs::MenuCustomization::hideable(id); + let mut visible = !hideable || !hidden.contains(id); + ui.add_enabled_ui(hideable, |ui| crate::widgets::checkbox(ui, &mut visible, tl!("Visible"))); + if visible { + hidden.retain(|h| h != id); + } else if !hidden.contains(id) { + hidden.push(id.clone()); + } + let mut col = colors.get(id).cloned().unwrap_or_else(|| "none".into()); + let opts: Vec<(String, &str)> = + ["none", "red", "orange", "yellow", "green", "blue", "violet", "gray"].iter().map(|c| (c.to_string(), *c)).collect(); + crate::widgets::dropdown(ui, &format!("menu-color-{id}"), tl!("Color"), &mut col, &opts, 90.0); + if col == "none" { + colors.remove(id); + } else { + colors.insert(id.clone(), col); + } + } + ui.end_row(); + } + }); + }); + ui.add_space(6.0); + if tab == 0 { + ui.horizontal(|ui| { + let has_sel = !selected.is_empty(); + if ui.add_enabled(has_sel, egui::Button::new(tl!("Add Shortcut"))).clicked() { + capture = true; + capture_alt = true; + message.clear(); + message_warning = false; + } + if ui.add_enabled(has_sel, egui::Button::new(tl!("Use Default"))).clicked() { + overrides.remove(&selected); + alt_overrides.remove(&selected); + message = tl!("Default restored.").into(); + message_warning = false; + } + if ui.add_enabled(has_sel, egui::Button::new(tl!("Delete Shortcut"))).clicked() { + overrides.insert(selected.clone(), String::new()); + message = tl!("Shortcut removed.").into(); + message_warning = false; + } + if ui.button(tl!("Reset All to Defaults")).clicked() { + overrides.clear(); + alt_overrides.clear(); + message = tl!("All shortcuts reset to PhotoCraft defaults.").into(); + message_warning = false; + } + // A Photoshop set (`.kys`) fills the overrides; the file arrives after this frame + // and `kys_import` writes the dialog's fields then (#1163). + if ui.button(tl!("Import Shortcuts…")).on_hover_text(tl!("Load a keyboard shortcut set saved as .kys")).clicked() + && let Err(e) = crate::kys_import::import_dialog(app) + { + message = e; + message_warning = false; + } + }); + } else if ui.button(tl!("Show All Menu Items")).clicked() { + hidden.clear(); + colors.clear(); + } + if !message.is_empty() { + ui.label(RichText::new(&message).color(if message_warning { t.warning } else { t.text_dim })); + } + // The conflict describes the bindings as the capture left them: any later change (Use + // Default, Delete, ×, Reset All, another command or set) makes it stale, and it goes. + let state = conflict_state(&overrides, &alt_overrides, &selected, f.get("activeSet")); + if conflict.as_ref().and_then(|c| c.get("state")).is_some_and(|s| s.as_u64() != Some(state)) { + conflict = None; + } + if tab == 0 + && let Some(c) = conflict.clone() + { + let (key, with, command) = + (c["shortcut"].as_str().unwrap_or_default(), c["with"].as_str().unwrap_or_default(), c["command"].as_str().unwrap_or_default()); + ui.horizontal(|ui| { + if ui.button(tl!("Accept and Go to Conflict")).on_hover_text(tl!("Take the shortcut from the other command and select it")).clicked() { + let holders: Vec = serde_json::from_value(c["holders"].clone()).unwrap_or_else(|_| vec![with.to_string()]); + for holder in &holders { + let def = items.iter().find(|i| i.0 == *holder).and_then(|i| i.3.clone()); + let cur = eff(&overrides, holder, &def); + if cur.as_deref().and_then(prefs::normalize_shortcut).as_deref() == Some(key) { + overrides.insert(holder.clone(), String::new()); + } + let keys = eff_alts(&alt_overrides, holder, eff(&overrides, holder, &def).as_deref()); + if keys.iter().any(|k| k == key) { + alt_overrides.insert(holder.clone(), keys.into_iter().filter(|k| k != key).collect()); + } + } + selected = with.to_string(); + filter.clear(); + message = tl!("Choose a new shortcut for this command, or leave it without one.").into(); + message_warning = false; + conflict = None; + } + if ui.button(tl!("Undo Changes")).on_hover_text(tl!("Put this command's shortcuts back as they were")).clicked() { + match c["main"].as_str() { + Some(m) => overrides.insert(command.to_string(), m.to_string()), + None => overrides.remove(command), + }; + match serde_json::from_value::>(c["alternates"].clone()) { + Ok(list) => alt_overrides.insert(command.to_string(), list), + Err(_) => alt_overrides.remove(command), + }; + selected = command.to_string(); + message = tl!("Changes undone.").into(); + message_warning = false; + conflict = None; + } + }); + } + if overrides_ok { + f.insert("overrides".into(), json!(overrides)); + } + if alternates_ok { + f.insert("alternates".into(), json!(alt_overrides)); + } + f.insert("captureAlt".into(), json!(capture && capture_alt)); + // A conflict just found is stamped with the bindings it describes. + if let Some(c) = conflict.as_mut().filter(|c| c.get("state").is_none()) { + c["state"] = json!(conflict_state(&overrides, &alt_overrides, &selected, f.get("activeSet"))); + } + f.insert("conflict".into(), conflict.unwrap_or(Value::Null)); + f.insert("hidden".into(), json!(hidden)); + f.insert("colors".into(), json!(colors)); + f.insert("selected".into(), json!(selected)); + f.insert("capture".into(), json!(capture)); + if capture { + f.insert("captureMods".into(), capture_mods_json(capture_mods)); + } else { + f.remove("captureMods"); + } + f.insert("message".into(), json!(message)); + f.insert("messageWarning".into(), json!(message_warning)); +} + +/// A command's keys as the dialog stands, main key first: the edited main key (or its default) +/// and its further keys. +fn dialog_keys(overrides: &BTreeMap, alternates: &BTreeMap>, id: &str, default: Option<&str>) -> Vec { + let main = match overrides.get(id) { + Some(s) if s.is_empty() => None, + Some(s) => Some(s.as_str()), + None => default, + }; + let mut p = prefs::Preferences::default(); + if let Some(list) = alternates.get(id) { + p.alternate_shortcuts.insert(id.to_string(), list.clone()); + } + let mut keys: Vec = main.and_then(prefs::normalize_shortcut).into_iter().collect(); + keys.extend(p.alternates(id, main)); + keys +} + +/// Edit › Keyboard Shortcuts › Set, as in Photoshop: choose a saved set (its bindings replace +/// the dialog's), save the bindings as a new set or over the one in use, delete it, export it as +/// a `.kys` file or summarize it as an HTML page. Everything but Export and Summarize waits for +/// OK, like the rest of the dialog. +#[allow(clippy::too_many_arguments)] +fn set_row( + app: &mut PhotocraftApp, + ui: &mut egui::Ui, + f: &mut Map, + overrides: &mut BTreeMap, + alternates: &mut BTreeMap>, + items: &[(String, String, Vec, Option)], + message: &mut String, + warning: &mut bool, +) { + use photocraft_engine::shortcut_sets::{self, ShortcutSet}; + let mut sets: BTreeMap = f.get("sets").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); + let mut active = f.get("activeSet").and_then(Value::as_str).unwrap_or("").to_string(); + if !active.is_empty() && !sets.contains_key(&active) { + active.clear(); + } + // The engine decides what a set holds and when it is modified (not the actions' F-keys). + let now = ShortcutSet::from_bindings(overrides, alternates); + let modified = shortcut_sets::differs(&sets, &active, overrides, alternates); + let defaults = tl!("PhotoCraft Defaults").to_string(); + let shown = |name: &str| -> String { + let base = if name.is_empty() { defaults.clone() } else { name.to_string() }; + if name == active && modified { crate::i18n::fmt(tl!("{set} (modified)"), &[("set", &base)]) } else { base } + }; + let names: Vec<(String, String)> = std::iter::once(String::new()).chain(sets.keys().cloned()).map(|n| (n.clone(), shown(&n))).collect(); + let mut new_name: Option = f.get("newSetName").and_then(Value::as_str).map(str::to_string); + let set_label = if active.is_empty() { defaults.clone() } else { active.clone() }; + let mut export = false; + let mut summarize = false; + ui.horizontal(|ui| { + ui.label(tl!("Set:")); + let mut chosen = active.clone(); + let pairs: Vec<(String, &str)> = names.iter().map(|(n, l)| (n.clone(), l.as_str())).collect(); + if crate::widgets::dropdown(ui, "shortcut-set", tl!("Set:"), &mut chosen, &pairs, 220.0) && chosen != active { + // As `useSet`: the set's bindings, keeping the actions' F-keys. + sets.get(&chosen).cloned().unwrap_or_default().apply(overrides, alternates); + active = chosen; + message.clear(); + } + if ui.button(tl!("New Set…")).on_hover_text(tl!("Save these shortcuts as a new set")).clicked() { + new_name = Some(String::new()); + } + if ui.add_enabled(!active.is_empty() && modified, egui::Button::new(tl!("Save"))).on_hover_text(tl!("Save the changes to this set")).clicked() { + sets.insert(active.clone(), now.clone()); + *message = tl!("Set saved.").into(); + *warning = false; + } + if ui.add_enabled(!active.is_empty(), egui::Button::new(tl!("Delete"))).on_hover_text(tl!("Delete this set")).clicked() { + sets.remove(&active); + active.clear(); + *message = tl!("Set deleted.").into(); + *warning = false; + } + export = ui.button(tl!("Export…")).on_hover_text(tl!("Save these shortcuts as a .kys file")).clicked(); + summarize = ui.button(tl!("Summarize…")).on_hover_text(tl!("Save a list of these shortcuts as a web page")).clicked(); + }); + if let Some(name) = new_name.as_mut() { + let mut create = false; + let mut cancel = false; + ui.horizontal(|ui| { + ui.label(tl!("Name:")); + let r = ui.add(egui::TextEdit::singleline(name).desired_width(220.0).hint_text(tl!("set name"))); + create = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + create |= ui.button(tl!("Create")).clicked(); + cancel = ui.button(tl!("Cancel")).clicked(); + }); + if create { + match shortcut_sets::set_name(name) { + Ok(n) if !sets.contains_key(&n) && sets.len() >= shortcut_sets::MAX_SETS => { + *message = tl!("There are too many sets: delete one first.").into(); + *warning = true; + } + Ok(n) => { + sets.insert(n.clone(), now.clone()); + active = n; + new_name = None; + *message = tl!("Set saved.").into(); + *warning = false; + } + Err(e) => { + *message = e; + *warning = true; + } + } + } else if cancel { + new_name = None; + } + } + if export || summarize { + let result = if export { + let entries: Vec = items + .iter() + .map(|(id, label, _, def)| photocraft_engine::kys::Entry { + id: id.clone(), + label: label.clone(), + tool: id.starts_with("tools.select."), + keys: dialog_keys(overrides, alternates, id, def.as_deref()), + }) + .collect(); + let text = photocraft_engine::kys::write(&set_label, &entries); + save_text(app, &format!("{set_label}.kys"), text) + } else { + let mut sections: Vec = Vec::new(); + for (id, label, path, def) in items { + let section = path.first().cloned().unwrap_or_else(|| tl!("Other").to_string()); + let name = path.iter().skip(1).chain(std::iter::once(label)).cloned().collect::>().join(" › "); + let row = (name, dialog_keys(overrides, alternates, id, def.as_deref())); + match sections.iter_mut().find(|(s, _)| *s == section) { + Some((_, rows)) => rows.push(row), + None => sections.push((section, vec![row])), + } + } + let html = shortcut_sets::summarize(&set_label, §ions, cfg!(target_os = "macos")); + save_text(app, &format!("{set_label}.html"), html) + }; + if let Err(e) = result { + *message = e; + *warning = true; + } + } + f.insert("sets".into(), json!(sets)); + f.insert("activeSet".into(), json!(active)); + f.insert("newSetName".into(), new_name.map_or(Value::Null, Value::String)); +} + +/// Save `text` through the save dialog under the suggested file name. +fn save_text(app: &mut PhotocraftApp, suggested: &str, text: String) -> Result { + // A set name can hold characters a file name can't. + let name: String = suggested.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c }).collect(); + app.pick_save(&name, move |app, path| { + let write = app.services.write.as_mut().ok_or("no writer configured")?; + write(&path, text.as_bytes())?; + Ok(json!({"path": path})) + }) +} diff --git a/crates/ui-egui/src/prefs_ui/startup.rs b/crates/ui-egui/src/prefs_ui/startup.rs new file mode 100644 index 0000000000..30da36a2a3 --- /dev/null +++ b/crates/ui-egui/src/prefs_ui/startup.rs @@ -0,0 +1,243 @@ +use super::*; + +/// View › Rulers follows `unitsAndRulers.showRulers` when the preference changes (at launch, from +/// `prefs.set` or a reset), so documents open with the rulers as last set. +pub(super) fn sync_rulers(app: &mut PhotocraftApp) { + let want = app.session.prefs().units_and_rulers.show_rulers; + if app.prefs_rt.show_rulers != Some(want) { + app.ui.extras.rulers = want; + app.prefs_rt.show_rulers = Some(want); + } +} + +/// View › Rulers was toggled: remember it for the next launch (Photoshop keeps the last state). +pub(crate) fn remember_rulers(app: &mut PhotocraftApp, on: bool) { + if app.session.prefs().units_and_rulers.show_rulers != on { + app.session.prefs.edit(|p| p.units_and_rulers.show_rulers = on); + } + app.prefs_rt.show_rulers = Some(on); +} + +// ------------------------------------------------------------------ lifecycle + +/// Load saved preferences once, when the app is created. Recovery starts during frame upkeep. +pub fn load(app: &mut PhotocraftApp) { + if app.prefs_rt.loaded { + return; + } + app.prefs_rt.loaded = true; + let mut invalid = Vec::new(); + let mut stored = None; + if let Some(text) = app.services.load_prefs.as_mut().and_then(|f| f()) { + match app.session.load_prefs_json(&text) { + Ok(found) => { + invalid = found; + stored = serde_json::from_str::(&text).ok(); + } + Err(e) => { + let template = "Preferences were reset: {error}"; + app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]); + } + } + } + crate::dock::restore(app); + crate::brush_picker::restore(app); + crate::last_brush::restore(app); + sync_rulers(app); + crate::tool_memory::restore(app); + crate::view_cmds::restore(app); + app.sync_recent(); + app.prefs_rt.saved_rev = app.session.prefs.rev(); + let loaded = app.session.prefs_value(); + app.prefs_rt.saved_value = Some(match stored { + Some(stored) => stored_base(&loaded, &stored), + None => loaded, + }); + if !invalid.is_empty() { + repair_invalid(app, &invalid); + } +} + +/// The save base after loading `stored`: what was loaded, with the keys the shift tool switch +/// migration may change (#5647) put back as the file had them, the way [`repair_invalid`] puts +/// back unreadable values. The migrated value and the new version then differ from the base, so +/// the next save writes them rather than keeping the old value under a newer version. Every other +/// key keeps its loaded value, so the three-way merge leaves another instance's changes alone, +/// also for keys the file doesn't have yet. A file from a newer version keeps its version. +fn stored_base(loaded: &Value, stored: &Value) -> Value { + let mut base = loaded.clone(); + let Some(obj) = base.as_object_mut() else { + return base; + }; + match stored.get("version") { + Some(v) if v.as_u64().is_some_and(|v| v > prefs::PREFS_VERSION) => {} + Some(v) => { + obj.insert("version".into(), v.clone()); + } + None => { + obj.remove("version"); + } + } + if let (Some(v), Some(tools)) = (stored.pointer("/tools/useShiftKeyForToolSwitch"), obj.get_mut("tools").and_then(Value::as_object_mut)) { + tools.insert("useShiftKeyForToolSwitch".into(), v.clone()); + } + base +} + +/// Some saved values couldn't be read and took their defaults (#6611): say which, and write +/// the defaults over them on the next save so the next launch reads a clean file. The save +/// base holds the unreadable values, so the three-way merge sees them as changed here and +/// replaces (or removes) exactly those, keeping everything else in the stored file. +fn repair_invalid(app: &mut PhotocraftApp, invalid: &[prefs::InvalidPref]) { + if let Some(base) = app.prefs_rt.saved_value.as_mut() { + for bad in invalid { + let Some((key, parent)) = bad.keys.split_last() else { + continue; + }; + if let Some(obj) = parent.iter().try_fold(&mut *base, |cur, k| cur.get_mut(k.as_str())).and_then(Value::as_object_mut) { + obj.insert(key.clone(), bad.value.clone()); + } + } + } + app.session.prefs.edit(|_| ()); + let paths = invalid.iter().map(prefs::InvalidPref::path).collect::>().join(", "); + let (title, line) = ( + "Some preferences were reset", + "The preferences file held values PhotoCraft can't read for {paths}. Those settings are back to their defaults; the rest of your preferences loaded.", + ); + // Notices keep their English source and are translated when drawn. + let id = crate::notices::post(app, title, vec![line.into()], false, None); + if let Some(notice) = app.ui.notices.iter_mut().find(|n| n.id == id) { + notice.args.push(("paths".into(), paths)); + } +} + +/// Discover recovery entries after construction, then decode one at a time without blocking +/// the window. Only the completed job's apply step touches the session. +pub(super) fn recovery(app: &mut PhotocraftApp) { + if !app.prefs_rt.recovery_started { + app.prefs_rt.recovery_started = true; + if app.session.prefs().file_handling.recover_on_launch + && let Some(recover) = app.services.recover.as_mut() + { + app.prefs_rt.recovery_queue.extend(recover()); + } + } + start_next_recovery(app); +} + +fn start_next_recovery(app: &mut PhotocraftApp) { + while app.prefs_rt.recovery_pending.is_none() { + let Some(r) = app.prefs_rt.recovery_queue.pop_front() else { return }; + let label = format!("Recovering {}", r.name); + let started = app.session.start_job( + "file.recover", + json!({}), + &label, + false, + move |ctx| { + ctx.check()?; + ctx.progress(0.0, "Loading recovery data"); + let doc = (r.load)().map_err(photocraft_engine::EngineError::Other)?; + ctx.check()?; + Ok(doc) + }, + move |s, doc| { + let active = s.active().map(|st| st.doc.id); + let first = s.documents().is_empty(); + s.add_document(doc, r.path); + let st = s.active_mut().ok_or(photocraft_engine::EngineError::NoDocument)?; + st.saved_revision = 0; + let (id, revision) = (st.doc.id, st.revision); + if let Some(index) = active.and_then(|id| s.documents().iter().position(|st| st.doc.id == id)) { + s.set_active(index); + } + Ok(json!({"documentId": id.0, "revision": revision, "firstDocument": first})) + }, + ); + match started { + Ok(Started::Job(job)) => app.prefs_rt.recovery_pending = Some((job, r.key)), + Ok(Started::Done(v)) => finish_recovery(app, &r.key, &v), + Err(e) => crate::notices::error(app, format!("{label}: {e}")), + } + } +} + +fn finish_recovery(app: &mut PhotocraftApp, key: &str, v: &Value) { + let recovered = v + .get("documentId") + .and_then(Value::as_u64) + .zip(v.get("revision").and_then(Value::as_u64)) + .and_then(|(id, revision)| app.session.documents().iter().find(|st| st.doc.id.0 == id).map(|st| (st.doc.id, revision, st.doc.name.clone()))); + let Some((id, revision, name)) = recovered else { + crate::notices::error(app, "The recovered document is no longer open".into()); + return; + }; + // Track the admitted snapshot's revision, even if another job has already edited it. + app.prefs_rt.autosaved.insert(id, revision); + if let Some(adopt) = app.services.adopt_autosave.as_mut() { + adopt(id.0, key); + } + if v.get("firstDocument").and_then(Value::as_bool) == Some(true) { + app.ui.chrome.home = None; + } + app.sync_views(); + let template = "Recovered {name}"; + app.ui.status = crate::i18n::fmt(tl!(template), &[("name", &name)]); + app.ui.status_error = false; +} + +/// Recovery uses the existing job polling/progress/cancel path. Its successful result adopts +/// the original entry on the UI thread, using identity rather than a mutable tab position. +pub(crate) fn on_recovery_event(app: &mut PhotocraftApp, e: &JobEvent) -> bool { + if !app.prefs_rt.recovery_pending.as_ref().is_some_and(|(job, _)| *job == e.id) { + return false; + } + let Some((_, key)) = app.prefs_rt.recovery_pending.take() else { return false }; + match &e.outcome { + JobOutcome::Done(v) => finish_recovery(app, &key, v), + JobOutcome::Failed(err) => crate::notices::error(app, format!("{}: {err}", e.label)), + JobOutcome::Cancelled => { + // Native bundle decoding cannot stop midway. Cancel admission and the rest of the + // batch so another large decoder isn't started while this worker finishes. + app.prefs_rt.recovery_queue.clear(); + app.ui.status = crate::i18n::fmt(tl!("Cancelled {label}"), &[("label", tl!(&e.label))]); + app.ui.status_error = false; + } + } + start_next_recovery(app); + true +} + +/// Attach the brush preset store once its background load finishes, and surface write +/// failures in the status bar. +pub(super) fn presets_store(app: &mut PhotocraftApp) { + if let Some(rx) = &app.services.preset_store { + match rx.try_recv() { + Ok(opened) => { + app.services.preset_store = None; + let warnings = app.session.attach_preset_store(opened); + if let Some(w) = warnings.first() { + app.ui.status = if warnings.len() == 1 { + w.clone() + } else { + crate::i18n::fmt( + &crate::i18n::trn( + crate::i18n::current(), + (warnings.len() - 1) as u64, + "{warning} (+{n} more brush preset warning)", + "{warning} (+{n} more brush preset warnings)", + ), + &[("warning", w)], + ) + }; + } + } + Err(std::sync::mpsc::TryRecvError::Empty) => {} + Err(std::sync::mpsc::TryRecvError::Disconnected) => app.services.preset_store = None, + } + } + if let Some(w) = app.session.preset_store.as_mut().map(|s| s.take_warnings()).and_then(|w| w.into_iter().next()) { + app.ui.status = w; + } +} From fa061e9255a8b4406996b64cf22a320e6e13d5d9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:08:42 +0000 Subject: [PATCH 227/259] refactor(ui-egui): split widgets.rs into widgets/ --- crates/ui-egui/src/widgets.rs | 2094 +--------------------- crates/ui-egui/src/widgets/buttons.rs | 267 +++ crates/ui-egui/src/widgets/color.rs | 193 ++ crates/ui-egui/src/widgets/dropdown.rs | 296 +++ crates/ui-egui/src/widgets/fields.rs | 483 +++++ crates/ui-egui/src/widgets/panel.rs | 152 ++ crates/ui-egui/src/widgets/scrub.rs | 153 ++ crates/ui-egui/src/widgets/slider.rs | 289 +++ crates/ui-egui/src/widgets/tests.rs | 5 +- crates/ui-egui/src/widgets/text_field.rs | 116 ++ crates/ui-egui/src/widgets/units.rs | 133 ++ 11 files changed, 2129 insertions(+), 2052 deletions(-) create mode 100644 crates/ui-egui/src/widgets/buttons.rs create mode 100644 crates/ui-egui/src/widgets/color.rs create mode 100644 crates/ui-egui/src/widgets/dropdown.rs create mode 100644 crates/ui-egui/src/widgets/fields.rs create mode 100644 crates/ui-egui/src/widgets/panel.rs create mode 100644 crates/ui-egui/src/widgets/scrub.rs create mode 100644 crates/ui-egui/src/widgets/slider.rs create mode 100644 crates/ui-egui/src/widgets/text_field.rs create mode 100644 crates/ui-egui/src/widgets/units.rs diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 24e0713e2f..55463ddcf8 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -12,2059 +12,55 @@ pub use color_count::color_count_row; mod type_ahead; pub use type_ahead::list_open as dropdown_list_open; -/// Match the Spectrum application-menu padding and blue/white hover state in -/// secondary menus (status bar, dock hamburger, layer context menus; #2187). -/// The setting is local to this popup's Ui and leaves other themes unchanged. -pub fn style_spectrum_popup_menu(ui: &mut Ui) { - let t = Tokens::get(ui.ctx()); - // The 6 pt gap between rows was outside both buttons, so a drag across a menu - // dropped the highlight (#4602). Padding stays inside the row, which is the hit target. - ui.spacing_mut().item_spacing.y = 0.0; - if !t.pro { - return; - } - ui.spacing_mut().button_padding = vec2(10.0, 4.0); - let v = &mut ui.style_mut().visuals; - v.widgets.hovered.weak_bg_fill = t.accent; - v.widgets.hovered.bg_fill = t.accent; - v.widgets.hovered.fg_stroke = Stroke::new(1.0, Color32::WHITE); - v.widgets.hovered.bg_stroke = Stroke::NONE; - v.widgets.inactive.corner_radius = CornerRadius::ZERO; - v.widgets.hovered.corner_radius = CornerRadius::ZERO; - v.widgets.active.corner_radius = CornerRadius::ZERO; -} - -/// An accent insertion line on one edge of `r` while a drag hovers it (vertical: on its left or, -/// `after`, right edge; else on its top or bottom). -pub fn drop_line(ui: &Ui, r: Rect, after: bool, vertical: bool, t: &Tokens) { - let s = Stroke::new(2.0, t.accent); - if vertical { - let x = if after { r.right() } else { r.left() }; - ui.painter().line_segment([pos2(x, r.top() + 2.0), pos2(x, r.bottom() - 2.0)], s); - } else { - let y = if after { r.bottom() } else { r.top() }; - ui.painter().line_segment([pos2(r.left() + 4.0, y), pos2(r.right() - 4.0, y)], s); - } -} - -/// Draw a bevelled box (Classic theme) or a flat rounded box. -pub fn surface(ui: &Ui, rect: Rect, fill: Color32, raised: bool) { - let t = Tokens::get(ui.ctx()); - let p = ui.painter(); - p.rect_filled(rect, t.radius_sm, fill); - if t.bevel { - let (hi, lo) = if raised { (Color32::WHITE, Color32::from_gray(64)) } else { (Color32::from_gray(64), Color32::WHITE) }; - p.line_segment([rect.left_bottom(), rect.left_top()], Stroke::new(1.0, hi)); - p.line_segment([rect.left_top(), rect.right_top()], Stroke::new(1.0, hi)); - p.line_segment([rect.right_top(), rect.right_bottom()], Stroke::new(1.0, lo)); - p.line_segment([rect.right_bottom(), rect.left_bottom()], Stroke::new(1.0, lo)); - } -} - -/// Inner margin of a dock panel's body: a Pro panel's, or a Studio card's below its tab strip. -pub(crate) fn body_margin(pro: bool) -> egui::Margin { - if pro { egui::Margin::same(8) } else { egui::Margin { left: 8, right: 8, top: 6, bottom: 10 } } -} - -/// Height of a panel footer's bar ([`panel_footer`]), under its 1 px line. -pub const FOOTER_BAR: f32 = 30.0; - -/// The height a [`panel_footer`] takes from the panel body: its line, and its bar down to the -/// body's bottom margin (the bar runs on over the margin). -pub fn footer_height(ui: &Ui) -> f32 { - 1.0 + FOOTER_BAR - body_margin(Tokens::get(ui.ctx()).pro).bottom as f32 -} - -/// A panel footer as in Photoshop's Layers and History panels: a bar of buttons under a line that -/// runs from edge to edge of the panel, the buttons centred in the bar's height and laid out from -/// the right. Drawn last in a body that fills its group (leave it [`footer_height`]), the bar ends -/// at the panel's bottom edge. -pub fn panel_footer(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { - let t = Tokens::get(ui.ctx()); - let m = body_margin(t.pro); - let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), footer_height(ui)), Sense::hover()); - let y = r.top() + 0.5; - ui.painter().line_segment([pos2(r.left() - m.left as f32, y), pos2(r.right() + m.right as f32, y)], Stroke::new(1.0, t.separator)); - let bar = Rect::from_min_size(pos2(r.left(), r.top() + 1.0), vec2(r.width(), FOOTER_BAR)); - let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center))); - // The bar runs on over the body's bottom margin, past where the body's own clip ends: without - // this its buttons were cut off there, a 26 px hover highlight drawn about 21 px tall. - bar_ui.set_clip_rect(bar_ui.clip_rect().union(bar)); - bar_ui.spacing_mut().item_spacing.x = 2.0; - add(&mut bar_ui) -} - -/// The panel menu button (hamburger in Pro, ellipsis in Studio), matching the dock and cards. -pub fn panel_menu_button(ui: &mut Ui) -> Response { - let t = Tokens::get(ui.ctx()); - let size = vec2(20.0, 20.0); - let (rect, resp) = ui.allocate_exact_size(size, Sense::click()); - let tint = crate::icons::button_chrome(ui, rect, false, resp.hovered()); - if t.pro { - for k in 0..3 { - let y = rect.center().y - 3.5 + k as f32 * 3.5; - ui.painter().line_segment([pos2(rect.center().x - 5.0, y), pos2(rect.center().x + 5.0, y)], Stroke::new(1.0, tint)); - } - } else { - crate::icons::paint(ui, rect, "ellipsis", 14.0, tint); - } - let tip = tl!("Panel menu"); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); - resp.on_hover_text(tip) -} - -pub fn pill_tab(ui: &mut Ui, label: &str, selected: bool) -> Response { - let t = Tokens::get(ui.ctx()); - let translated = tl!(label); - let font = theme::medium(12.5); - let galley = ui.painter().layout_no_wrap(translated.to_string(), font, t.text); - let size = vec2(galley.size().x + 20.0, 24.0); - let (rect, resp) = ui.allocate_exact_size(size, Sense::click()); - if selected { - surface(ui, rect, t.hover, true); - if !t.bevel { - ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); - } - } else if resp.hovered() { - ui.painter().rect_filled(rect, t.radius_sm, t.hover.gamma_multiply(0.6)); - } - let color = if selected { t.text } else { t.text_dim }; - ui.painter().galley_with_override_text_color(rect.center() - galley.size() / 2.0, galley, color); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, translated)); - resp -} - -/// Monospace numeric field with a dimmed unit suffix, Photoshop style. Drag to scrub. Typed -/// arithmetic (`1920/2`) applies on Enter, Tab or click-away, and a unit after a number converts -/// into the field's unit (`1in` in a px field, at the resolution [`set_field_resolution`] gave). -pub fn value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, width: f32) -> Response { - value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts::default(), None).0 -} - -/// 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 { - value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts::default(), Some(name)).0 -} - -/// A single-line label for a row that also holds fixed-width controls: laid out no wider than -/// `max_w`, cut with '…' when the text (often a longer translation) does not fit, with the full -/// string on hover. Fixed chrome must never let a label overrun its row (#3580), so an *essential* -/// label beside a fixed control should use this rather than a show/hide fit check; a *redundant* -/// label (one whose control already carries the meaning, e.g. an icon row's caption) may be dropped. -pub fn elided_label_sensed(ui: &mut Ui, text: &str, max_w: f32, sense: Sense) -> Response { - let t = Tokens::get(ui.ctx()); - let font = egui::TextStyle::Body.resolve(ui.style()); - let galley = crate::tab_strip::elided(ui, text, font, t.text_dim, max_w); - let elided = galley.elided; - let (rect, resp) = ui.allocate_exact_size(galley.size(), sense); - ui.painter().galley(rect.min, galley, t.text_dim); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, ui.is_enabled(), text)); - if elided { resp.on_hover_text(text) } else { resp } -} - -/// [`elided_label_sensed`] with hover only (a plain, non-interactive label). -pub fn elided_label(ui: &mut Ui, text: &str, max_w: f32) -> Response { - elided_label_sensed(ui, text, max_w, Sense::hover()) -} - -/// Height of a [`value_field`]'s box. -pub const VALUE_FIELD_H: f32 = 24.0; - -/// A [`value_field`] `height` points tall instead of [`VALUE_FIELD_H`], for slim bars such as -/// the status bar (#2823). -pub fn compact_value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, width: f32, height: f32) -> Response { - value_field_box(ui, value, range, suffix, vec2(width, height), 0.0, FieldOpts::default(), None).0 -} - -/// A compact field whose mouse scrub wraps at the native fullscreen viewport's horizontal edges. -pub(crate) fn compact_wrapping_value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, size: Vec2) -> Response { - value_field_box(ui, value, range, suffix, size, 0.0, FieldOpts { wrap_drag: true, ..Default::default() }, None).0 -} - -/// A size dialog's unit key (`px`, `in`, `cm`, `mm`, `pt`, `pica`, `percent`) as a unit. -pub fn unit_of_key(key: &str) -> photocraft_engine::prefs::Unit { - use photocraft_engine::prefs::Unit; - match key { - "in" => Unit::Inches, - "cm" => Unit::Centimeters, - "mm" => Unit::Millimeters, - "pt" => Unit::Points, - "pica" => Unit::Picas, - "percent" => Unit::Percent, - _ => Unit::Pixels, - } -} - -/// Decimal places for a size dialog's unit key (`px`, `in`, `cm`, `mm`, `pt`, `pica`, `percent`). -/// The places themselves live on [`photocraft_engine::prefs::Unit`], so the dialogs, the Info -/// panel and the rulers agree (#2434). -pub fn unit_decimals(key: &str) -> u32 { - unit_of_key(key).decimals() as u32 -} - -/// A [`value_field`] showing `decimals` decimal places instead of the one (or two, for a small -/// range) it picks itself: the ruler units need their own precision (#2434). -pub fn value_field_prec(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, width: f32, decimals: u32) -> Response { - value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts { decimals: Some(decimals), ..Default::default() }, None).0 -} - -/// A field's unit and the resolution a typed unit converts at (`1in` in a px field). -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct FieldUnits { - pub unit: photocraft_engine::prefs::Unit, - /// Pixels per inch. - pub dpi: f64, - /// Points per inch (72 PostScript, 72.27 traditional). - pub ppi: f64, -} - -/// A [`value_field_prec`] without a suffix, whose unit is chosen beside it (Image Size and New -/// Document's unit menus) and converts typed units at that dialog's own resolution. -pub fn value_field_units(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, width: f32, decimals: u32, units: FieldUnits) -> Response { - value_field_in(ui, value, range, "", width, 0.0, FieldOpts { decimals: Some(decimals), units: Some(units), ..Default::default() }, None).0 -} - -/// A [`value_field_prec`] in `units` whose 100 % is a length of `extent` px (Free Transform's W -/// and H): a length typed while it shows percent becomes that share of `extent` (`40px`, `2in`), -/// and a percentage typed while it shows a length becomes that share of `extent` (`50%`), at -/// `units`' resolution (#6284). The field keeps its own unit. -#[allow(clippy::too_many_arguments)] -pub fn value_field_extent( - ui: &mut Ui, - value: &mut f32, - range: std::ops::RangeInclusive, - suffix: &str, - width: f32, - decimals: u32, - units: FieldUnits, - extent: f64, -) -> Response { - let opts = FieldOpts { decimals: Some(decimals), units: Some(units), extent: Some(extent), ..Default::default() }; - value_field_in(ui, value, range, suffix, width, 0.0, opts, None).0 -} - -fn field_resolution_id() -> egui::Id { - egui::Id::unique("pc-field-resolution") -} - -/// The resolution (pixels per inch) and point size (points per inch) a unit typed into a value -/// field converts at: the active document's. The app sets it each frame; 72 / 72 without it. -pub fn set_field_resolution(ctx: &egui::Context, dpi: f64, ppi: f64) { - ctx.data_mut(|d| d.insert_temp(field_resolution_id(), (dpi, ppi))); -} - -/// The unit a field's suffix names (`px`, `in`, `cm`, `mm`, `pt`, `pica`/`pc`, `%`), if any. -fn unit_of_suffix(suffix: &str) -> Option { - use photocraft_engine::prefs::Unit; - Some(match suffix { - "px" => Unit::Pixels, - "in" => Unit::Inches, - "cm" => Unit::Centimeters, - "mm" => Unit::Millimeters, - "pt" => Unit::Points, - "pica" | "pc" => Unit::Picas, - "%" => Unit::Percent, - _ => return None, - }) -} - -/// A drag on a value field's label this frame, for the value field drawn next on the label's row -/// (Photoshop's scrubby labels). Left by [`scrub_label`], taken by that field. -#[derive(Clone, Copy, Debug)] -struct LabelScrub { - pass: u64, - /// The id whose drags move the field (the label itself, or an options caption's hit area). - label: egui::Id, - /// The visible label's own id, which names the field it scrubs. - name: Option, - rect: Rect, - /// How far right of the label the field may start (the whole row for a slider row). - max_gap: f32, - /// Options captions defer interaction until the adjacent field bounds are known. - option_area: bool, - /// An options icon's tooltip, shown by the drag area laid over it (which takes its hover). - tip: Option<&'static str>, - /// Whole steps to move the value (left negative; Shift ×10, Alt a tenth as fast). - steps: f32, - started: bool, - dragging: bool, - stopped: bool, -} - -fn label_scrub_id() -> egui::Id { - egui::Id::unique("pc-label-scrub") -} - -/// Makes `label` scrubby: dragging it left or right moves the value field drawn right after it on -/// the same row (one step a point, ×10 with Shift, a tenth as fast with Alt), with Photoshop's -/// scrubby cursor. A label with no value field right after it stays a plain label. -pub fn scrub_label(ui: &Ui, label: &Response) -> Response { - scrub_label_within(ui, label, 24.0) -} - -/// A tool-options caption whose scrub target includes the adjacent field's outer box. -/// Keep the original label bounds for linking; register the hit area before the numeric editor. -pub fn scrub_option_label(ui: &Ui, label: &Response) { - scrub_option_area(ui, label, None); -} - -/// [`scrub_option_label`] for an icon with tooltip `tip`. The field's drag area is laid over the -/// icon after it, so egui hovers the area and not the icon: `on_hover_text` on the icon never shows. -pub fn scrub_option_icon(ui: &Ui, icon: &Response, tip: &'static str) { - scrub_option_area(ui, icon, Some(tip)); -} - -fn scrub_option_area(ui: &Ui, label: &Response, tip: Option<&'static str>) { - let scrub = LabelScrub { - pass: ui.ctx().cumulative_pass_nr(), - label: label.id.with("pc-option-scrub"), - name: Some(label.id), - rect: label.rect, - max_gap: 24.0, - option_area: true, - tip, - steps: 0.0, - started: false, - dragging: false, - stopped: false, - }; - ui.data_mut(|d| d.insert_temp(label_scrub_id(), scrub)); -} - -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)); - ui.data_mut(|d| { - d.insert_temp(label_scrub_id(), scrub); - d.insert_temp(resp.id.with("pc-scrub-linked"), false); - }); - resp -} - -fn label_scrub_response(ui: &Ui, resp: &Response, original_rect: Rect, max_gap: f32, name: Option) -> LabelScrub { - // Whether a field took this label's drags last frame: only then is it scrubby. - let linked = ui.data(|d| d.get_temp::(resp.id.with("pc-scrub-linked"))).unwrap_or(false); - if linked && resp.enabled() && (resp.hovered() || resp.dragged()) { - ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); - } - let acc_id = resp.id.with("pc-scrub-acc"); - let mut steps = 0.0; - if resp.dragged() || resp.drag_stopped() { - let mut acc: f32 = if resp.drag_started() { 0.0 } else { ui.data(|d| d.get_temp(acc_id)).unwrap_or(0.0) }; - let mods = ui.input(|i| i.modifiers); - let rate = if mods.shift { - 10.0 - } else if mods.alt { - 0.1 - } else { - 1.0 - }; - // The drag starts once the pointer has moved a few points: count those too. - let dx = match (resp.drag_started(), ui.input(|i| i.pointer.press_origin()), resp.interact_pointer_pos()) { - (true, Some(origin), Some(pos)) => pos.x - origin.x, - _ => resp.drag_delta().x, - }; - acc += dx * rate; - if !acc.is_finite() { - acc = 0.0; - } - steps = acc.trunc(); - ui.data_mut(|d| d.insert_temp(acc_id, acc - steps)); - } - LabelScrub { - pass: ui.ctx().cumulative_pass_nr(), - label: resp.id, - name, - rect: original_rect, - max_gap, - option_area: false, - tip: None, - steps, - started: resp.drag_started(), - dragging: resp.dragged(), - stopped: resp.drag_stopped(), - } -} - -/// The label drag left for the field at `rect` this frame, if its label is just left of it on -/// its row. Taken either way: a label only scrubs the next field drawn. -fn take_label_scrub(ui: &Ui, rect: Rect) -> Option { - let s = ui.data_mut(|d| { - let s = d.get_temp::(label_scrub_id()); - d.remove::(label_scrub_id()); - s - })?; - let same_row = rect.top() < s.rect.bottom() && rect.bottom() > s.rect.top(); - let gap = rect.left() - s.rect.right(); - let linked = s.pass == ui.ctx().cumulative_pass_nr() && same_row && gap >= -1.0 && gap <= s.max_gap; - if linked { - ui.data_mut(|d| d.insert_temp(s.label.with("pc-scrub-linked"), true)); - } - linked.then_some(s) -} - -/// The visible caption left for the control drawn next this frame, if any, consumed so that a -/// non-scrubbing control (a dropdown) can still take its name and the caption cannot leak on. -fn take_label_scrub_name(ui: &Ui, rect: Rect) -> Option { - let s = ui.data_mut(|d| { - let s = d.get_temp::(label_scrub_id()); - d.remove::(label_scrub_id()); - s - })?; - if s.pass != ui.ctx().cumulative_pass_nr() { - return None; - } - // Only a caption on the control's own row names it; one left over from an earlier row does not. - let same_row = rect.top() < s.rect.bottom() && rect.bottom() > s.rect.top(); - same_row.then_some(s.name).flatten() -} - -/// How a [`value_field_in`] shows and reads its number, beyond its suffix. -#[derive(Clone, Copy, Debug, Default)] -struct FieldOpts { - /// Decimal places shown (default: one, or two for a small range). - decimals: Option, - /// Arrow-key and scrub step follow `decimals` (adjustment rows via [`slider_row_prec`], #5914). - step_from_decimals: bool, - /// The unit typed units convert into (default: the suffix's, at [`set_field_resolution`]). - units: Option, - /// The length (px) 100 % stands for, so lengths and percentages convert into each other. - extent: Option, - wrap_drag: bool, -} - -/// Arrow-key and drag step for a value field: [`FieldOpts::step_from_decimals`] uses `decimals`; -/// otherwise the range width picks 0.01 (≤10) or 1.0. -fn field_step(range: &std::ops::RangeInclusive, decimals: Option, step_from_decimals: bool) -> f32 { - if step_from_decimals && let Some(d) = decimals { - return 10f32.powi(-(d.min(6) as i32)); - } - if *range.end() - *range.start() <= 10.0 { 0.01 } else { 1.0 } -} - -fn field_fine(range: &std::ops::RangeInclusive, decimals: Option, step_from_decimals: bool) -> bool { - if step_from_decimals { decimals.is_some_and(|d| d > 0) || *range.end() - *range.start() <= 10.0 } else { *range.end() - *range.start() <= 10.0 } -} - -/// A [`value_field`] that leaves `trailing` points free inside its box, right of the suffix, and -/// returns the box with the number's response. -// The explicit accessible name accompanies the existing numeric-field parameters. -#[expect(clippy::too_many_arguments)] -fn value_field_in( - ui: &mut Ui, - value: &mut f32, - range: std::ops::RangeInclusive, - suffix: &str, - width: f32, - trailing: f32, - opts: FieldOpts, - name: Option<&str>, -) -> (Response, Rect) { - value_field_box(ui, value, range, suffix, vec2(width, VALUE_FIELD_H), trailing, opts, name) -} - -/// [`value_field_in`] with a box of any `size`. -// The explicit accessible name accompanies the existing numeric-field parameters. -#[expect(clippy::too_many_arguments)] -fn value_field_box( - ui: &mut Ui, - value: &mut f32, - range: std::ops::RangeInclusive, - suffix: &str, - size: Vec2, - trailing: f32, - opts: FieldOpts, - name: Option<&str>, -) -> (Response, Rect) { - let FieldOpts { decimals, step_from_decimals, units, extent, wrap_drag } = opts; - let t = Tokens::get(ui.ctx()); - let (rect, slot) = ui.allocate_exact_size(size, Sense::hover()); - let last_editor = ui.data(|d| d.get_temp::(slot.id)); - let mut option_click = false; - let scrub = take_label_scrub(ui, rect).map(|s| { - if !s.option_area { - return s; - } - // A direct click+drag target avoids egui snapping the padding/suffix to the nearby - // numeric button. It is not focusable; the editor drawn next wins inside its bounds. - // Preserve a popup field's trailing arrow, and never extend outside the UI clip. - let hit = Rect::from_min_max(pos2(s.rect.left(), rect.top()), pos2(rect.right() - trailing, rect.bottom())).intersect(ui.clip_rect()); - let mut resp = ui.interact(hit, s.label, Sense::CLICK | Sense::DRAG); - option_click = resp.clicked(); - if let Some(tip) = s.tip - && resp.hover_pos().is_some_and(|p| s.rect.contains(p)) - { - resp = resp.on_hover_text(tip); - } - label_scrub_response(ui, &resp, s.rect, s.max_gap, s.name) - }); - let (dpi, ppi) = ui.data(|d| d.get_temp::<(f64, f64)>(field_resolution_id())).unwrap_or((72.0, 72.0)); - // Typed text loses its spaces before parsing, so a " pt" suffix reads as "pt". - let typed_suffix = suffix.trim(); - let units = match units { - Some(u) => crate::numeric_expression::Units { unit: Some(u.unit), suffix: typed_suffix, dpi: u.dpi, ppi: u.ppi, extent }, - None => crate::numeric_expression::Units { unit: unit_of_suffix(typed_suffix), suffix: typed_suffix, dpi, ppi, extent }, - }; - surface(ui, rect, t.field, false); - if !t.bevel { - ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); - } - // The number's slot ends 1 pt left of the suffix, by its measured width (the suffix is drawn - // 6 pt from the right edge), so a one-character unit like `%` leaves the number room (#3040). - let suffix_font = theme::mono(11.0); - let suffix_w = if suffix.is_empty() { 0.0 } else { ui.painter().layout_no_wrap(suffix.to_owned(), suffix_font.clone(), t.text_faint).size().x + 3.0 }; - // Centred: the digits' ink then sits within 0.2 pt of the box's centre, where a 1 pt lift - // (#1322) put it 0.9 pt high and the focus outline off-centre (#5150). The slot is at least - // one text row tall, so a slim box's number isn't pushed out of it (#2823). - let font = theme::mono(12.0); - let row_h = ui.painter().layout_no_wrap("0".into(), font.clone(), t.text).size().y; - let slot_h = (rect.height() - 4.0).max(row_h).min(rect.height() - 2.0); - let cy = rect.center().y; - let field = Rect::from_min_max(pos2(rect.left() + 4.0, cy - slot_h / 2.0), pos2(rect.right() - 4.0 - suffix_w - trailing, cy + slot_h / 2.0)); - // Small ranges (gamma 0.01–9.99, 0–1 centres) need two decimals and a finer drag, like Photoshop. - let fine = field_fine(&range, decimals, step_from_decimals); - let unit = field_step(&range, decimals, step_from_decimals); - let (lo, hi) = (*range.start(), *range.end()); - // The field's id is only known once it's drawn: last frame's, saved under `slot` below. - let focused = ui.data(|d| d.get_temp::(slot.id)).filter(|id| ui.memory(|m| m.has_focus(*id))); - let (step, grid) = arrow_step(ui, slot.id, unit); - // The wheel steps it as the arrow keys do (#5473), focused or under the pointer. - let notches = crate::field_wheel::notches(ui, slot.id, focused.is_some(), rect); - if notches != 0.0 - && let Some(id) = focused - && ui.data(|d| d.get_temp(id.with("arithmetic"))).unwrap_or(false) - { - // A typed sum works itself out first, as before an arrow step. - ui.memory_mut(|m| m.surrender_focus(id)); - } - let step = step + notches * unit; - // new_child (not scope_builder): a scope would move the parent cursor back to the child rect. - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(field)); - let mut resp = { - let ui = &mut child; - { - ui.style_mut().visuals.widgets.inactive.bg_fill = Color32::TRANSPARENT; - ui.style_mut().visuals.widgets.inactive.weak_bg_fill = Color32::TRANSPARENT; - ui.style_mut().visuals.widgets.inactive.bg_stroke = Stroke::NONE; - ui.style_mut().visuals.widgets.hovered.bg_stroke = Stroke::NONE; - ui.style_mut().visuals.widgets.hovered.weak_bg_fill = Color32::TRANSPARENT; - ui.style_mut().override_font_id = Some(font); - // The theme's interact height (24) is taller than the number's slot: the DragValue - // would grow past the slot's bottom and sit low, or spill out of a slim box (#2823). - // Its horizontal padding would push a long number out of the box's left edge. - ui.spacing_mut().interact_size.y = field.height(); - ui.spacing_mut().button_padding = Vec2::ZERO; - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let layout = egui::Layout::centered_and_justified(ui.layout().main_dir()); - ui.allocate_ui_with_layout(field.size(), layout, |ui| number_edit(ui, value, range, fine, decimals, units, wrap_drag)).inner - }) - .inner - } - }; - ui.data_mut(|d| d.insert_temp(slot.id, resp.id)); - // A click on the caption's expanded hit area (outside the editor) is not an edit: keep the - // number's keyboard focus, but never take it for a field that did not have it. - if option_click - && let Some(id) = last_editor - && ui.memory(|m| m.had_focus_last_frame(id)) - { - ui.memory_mut(|m| m.request_focus(id)); - } - // A scrubby caption is also the field's visible label, so it names the number for screen readers. - if let Some(id) = scrub.as_ref().and_then(|s| s.name) { - resp = resp.labelled_by(id); - } else if let Some(name) = name { - // The caption drew in another Ui (or row), so it could not name the number itself. - resp = resp.accessible_name(name); - } - if let Some(s) = scrub { - if s.started && ui.memory(|m| m.has_focus(resp.id)) { - ui.memory_mut(|m| m.surrender_focus(resp.id)); - } - if s.steps != 0.0 { - // Onto the step grid first, so a whole-number field drops its decimals (55.4 + 1 = 56). - let v = ((*value / unit).round() + s.steps) * unit; - let v = (v * 1e4).round() / 1e4; - // `f32::clamp` panics on a reversed or NaN range, which `DragValue::range` accepts. - let v = if lo <= hi { v.clamp(lo, hi) } else { v }; - if v.is_finite() && v != *value { - *value = v; - resp.mark_changed(); - } - } - // Callers coalesce a drag into one history step; the label's drag is the field's. - use egui::response::Flags; - resp.flags.set(Flags::DRAG_STARTED, resp.flags.contains(Flags::DRAG_STARTED) || s.started); - resp.flags.set(Flags::DRAGGED, resp.flags.contains(Flags::DRAGGED) || s.dragging); - resp.flags.set(Flags::DRAG_STOPPED, resp.flags.contains(Flags::DRAG_STOPPED) || s.stopped); - } - if !suffix.is_empty() { - ui.painter().text(pos2(rect.right() - 6.0 - trailing, rect.center().y), Align2::RIGHT_CENTER, suffix, suffix_font, t.text_faint); - } - if step != 0.0 { - // Round to the step before adding it, so whole-number fields drop decimals (55.4 + 1 = 56). - let v = (*value / grid).round() * grid + step; - // Round to 4 decimal places, so repeated 0.1 steps don't leave float errors. - let v = (v * 1e4).round() / 1e4; - // `f32::clamp` panics on a reversed or NaN range, which `DragValue::range` accepts. - let v = if lo <= hi { v.clamp(lo, hi) } else { v }; - // A wild wheel delta must not leave infinity in the field. - if v.is_finite() { - *value = v; - } - // A wheel step over a field without focus leaves the focus where it is. - if focused.is_some() { - // Only take focus back after a typed sum gave it up: re-requesting it while held resets - // the field's arrow-key filter next frame, and a held arrow then moves focus away (#5474). - if !ui.memory(|m| m.has_focus(resp.id)) { - ui.memory_mut(|m| m.request_focus(resp.id)); - } - // The text stays selected, as in Photoshop: typing after a step replaces the value. - crate::field_tab::select_all(ui.ctx(), resp.id, &if fine { fmt_num2(f64::from(*value)) } else { fmt_num(f64::from(*value)) }); - } - resp.mark_changed(); - } - if ui.memory(|m| m.has_focus(resp.id)) { - crate::field_wheel::set_focused(ui.ctx(), resp.id, slot.id); - } - (resp, rect) -} - -/// Width of the ▾ that opens a [`popup_value_field`]'s slider, inside the field's box. -pub const POPUP_ARROW_W: f32 = 14.0; - -/// Width of a [`popup_value_field`]'s pop-up slider. -const POPUP_SLIDER_W: f32 = 160.0; - -/// What a [`popup_value_field`] did this frame. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct PopupFieldResponse { - /// The value changed (typed, scrubbed, stepped with the arrow keys, or set on the slider). - pub changed: bool, - /// While the value is dragged (on the slider, from the ▾, or scrubbing the number): a number - /// for that drag, the same on every frame of it, for the caller to coalesce the drag's edits - /// into one history step. - pub drag: Option, -} - -/// A [`value_field`] with Photoshop's pop-up slider (the Layers panel's Opacity and Fill): a click -/// on the ▾ inside the field's right edge opens a slider below it, a click outside closes it. -/// Pressing the ▾ and dragging moves the value straight away, as far as the slider would, and -/// closes the slider on release. The number can still be typed, scrubbed and stepped like any -/// value field. `name` (already translated) names the ▾ for its tooltip and for accessibility. -pub fn popup_value_field(ui: &mut Ui, name: &str, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, width: f32) -> PopupFieldResponse { - let t = Tokens::get(ui.ctx()); - let (lo, hi) = (*range.start(), *range.end()); - let (mut field, rect) = value_field_in(ui, value, range.clone(), suffix, width, POPUP_ARROW_W, FieldOpts::default(), None); - let arrow = Rect::from_min_max(pos2(rect.right() - POPUP_ARROW_W - 2.0, rect.top() + 2.0), rect.max - vec2(2.0, 2.0)); - let resp = ui.interact(arrow, field.id.with("popup-slider"), Sense::click_and_drag()); - let name = name.trim_end_matches([':', ':']).to_string(); - // Both the number and its ▾ are named by the control's own semantic name. - field = field.accessible_name(name.clone()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &name)); - let resp = resp.on_hover_text(&name); - let drag_key = resp.id.with("drag"); - // Every drag gets a new number when it starts, even if its first frame changes nothing. - let gesture = |ui: &Ui, started: bool| { - if started { - let n = ui.ctx().cumulative_pass_nr(); - ui.data_mut(|d| d.insert_temp(drag_key, n)); - } - ui.data(|d| d.get_temp::(drag_key)) - }; - let mut out = PopupFieldResponse { changed: field.changed(), drag: None }; - let scrub = gesture(ui, field.drag_started()); - if field.changed() && field.dragged() { - out.drag = scrub; - } - - let popup_id = egui::Popup::default_response_id(&resp); - let start_key = resp.id.with("start"); - if resp.drag_started() { - egui::Popup::open_id(ui.ctx(), popup_id); - ui.data_mut(|d| d.insert_temp(start_key, *value)); - gesture(ui, true); - } - if resp.dragged() - && let (Some(start), Some(origin), Some(pos)) = - (ui.data(|d| d.get_temp::(start_key)), ui.input(|i| i.pointer.press_origin()), resp.interact_pointer_pos()) - { - // The pointer moves the value as much as it would move the slider's knob. - let track = POPUP_SLIDER_W - 14.0; - let v = start + (pos.x - origin.x) / track * (hi - lo); - let v = if lo <= hi && v.is_finite() { v.clamp(lo, hi) } else { start }; - if v != *value { - *value = v; - out.changed = true; - } - out.drag = gesture(ui, false); - } - if resp.drag_stopped() { - egui::Popup::close_id(ui.ctx(), popup_id); - } - - let popup = egui::Popup::from_toggle_button_response(&resp) - .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) - .anchor(rect) - .align(egui::RectAlign::BOTTOM_END) - .align_alternatives(&[egui::RectAlign::TOP_END]); - let open = popup.is_open(); - if resp.hovered() || resp.dragged() || open { - ui.painter().rect_filled(arrow, t.radius_sm, t.field_border.gamma_multiply(0.6)); - } - chevron_icon(ui, arrow, 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_width(POPUP_SLIDER_W); - let s = slider(ui, value, range, None); - s.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(*value), &name)); - let key = gesture(ui, s.drag_started()); - if s.changed() { - out.changed = true; - // A click on the track is one edit of its own; a drag is one edit however long. - if s.dragged() { - out.drag = key; - } - } - }); - out -} - -/// The most characters a [`text_field`] holds unless its caller sets a limit: far beyond any -/// search, name or hex value, yet a pasted multi-gigabyte string is cut at the field instead of -/// being laid out every frame (#2150). -pub const TEXT_FIELD_LIMIT: usize = 1024; - -/// The most characters one typed, pasted or IME-committed text event carries into the app -/// ([`cap_text_events`]): a megabyte of text, more than any field or text layer is pasted. -pub const INPUT_EVENT_LIMIT: usize = 1 << 20; - -/// Cuts every text, paste and IME event to [`INPUT_EVENT_LIMIT`] characters (at a character -/// boundary) before any widget sees it, so no text field -- whatever its own limit -- has to -/// lay out an 8 GB paste (#2150). -pub fn cap_text_events(events: &mut [egui::Event]) { - fn cut(text: &mut String) -> bool { - let Some((end, _)) = text.char_indices().nth(INPUT_EVENT_LIMIT) else { return false }; - text.truncate(end); - true - } - for event in events { - match event { - egui::Event::Text(text) | egui::Event::Paste(text) | egui::Event::Ime(egui::ImeEvent::Commit(text)) => { - cut(text); - } - // The highlighted range indexes the old text; past the cut it would point nowhere. - egui::Event::Ime(egui::ImeEvent::Preedit { text, active_range_chars }) => { - if cut(text) && active_range_chars.as_ref().is_some_and(|r| r.end > INPUT_EVENT_LIMIT) { - *active_range_chars = None; - } - } - _ => {} - } - } -} - -/// Height of a [`text_field`]'s box, matching a [`value_field`]. -pub const TEXT_FIELD_H: f32 = 24.0; - -/// Inner padding of a [`text_field`]'s box: 6 pt either side, 2 pt above and below. -const TEXT_FIELD_PAD: Vec2 = vec2(6.0, 2.0); - -/// A single-line text field in PhotoCraft's shared field style (#3789): the same box as a -/// [`value_field`] -- the theme's field fill and `field_border`, rounded by `radius_sm` -- with a -/// consistent inner padding and no focus outline. egui's default white focus ring (its -/// `selection.stroke`) is what made the Preferences search field look different from the Color -/// Picker's hex field, so every plain, non-numeric input (search, hex, name, filter) is drawn -/// through here to look and behave the same. `id` carries the field's text and focus across -/// frames; `hint` shows while it is empty; `mono` picks the monospaced face for hex and other -/// code-like values. -pub fn text_field(ui: &mut Ui, id: egui::Id, text: &mut String, hint: &str, width: f32, mono: bool) -> Response { - text_field_ex(ui, id, text, hint, width, mono, None) -} - -/// [`text_field`] limited to `char_limit` characters (a hex field's six digits, say), or to -/// [`TEXT_FIELD_LIMIT`] without one. -pub fn text_field_ex(ui: &mut Ui, id: egui::Id, text: &mut String, hint: &str, width: f32, mono: bool, char_limit: Option) -> Response { - let t = Tokens::get(ui.ctx()); - let (rect, _) = ui.allocate_exact_size(vec2(width.max(16.0), TEXT_FIELD_H), Sense::hover()); - surface(ui, rect, t.field, false); - if !t.bevel { - ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); - } - let font = if mono { theme::mono(12.0) } else { egui::FontId::proportional(12.5) }; - let inner = rect.shrink2(TEXT_FIELD_PAD); - let limit = char_limit.unwrap_or(TEXT_FIELD_LIMIT); - // A value already past the limit (restored from a state file, set by automation) is shown and - // edited as its first `limit` characters, so it is never laid out whole; the caller's string - // changes only when that copy is edited. - let mut bounded = text.char_indices().nth(limit).map(|(end, _)| text[..end].to_string()); - let shown = match bounded.as_mut() { - Some(b) => b, - None => &mut *text, - }; - // TextEdit draws its text at the top of its rect; fill the box and centre the line in it, so - // the text sits on the field's middle like a dropdown's or value field's. - let edit = egui::TextEdit::singleline(shown) - .id(id) - .hint_text(hint.to_owned()) - .frame(egui::Frame::NONE) - .font(font) - .min_size(inner.size()) - .align(egui::Align2::LEFT_CENTER) - .char_limit(limit); - // A child Ui keeps the field's selection colour local: `Visuals::selection` also fills selected - // list rows and slider trails, which must keep the theme's. - let layout = egui::Layout::centered_and_justified(egui::Direction::TopDown); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(inner).layout(layout)); - // The theme's 24 pt interact height would make the edit taller than the box's inside. - child.spacing_mut().interact_size.y = inner.height(); - child.style_mut().visuals.selection.bg_fill = t.field_selection(); - let response = child.add(edit); - if let Some(b) = bounded - && response.changed() - { - *text = b; - } - response -} - -fn first_field_id() -> egui::Id { - egui::Id::unique("pc-focus-first-field") -} - -/// While `on`, the next number field drawn takes the keyboard focus with its text selected (a -/// dialog opening on its first value, as in Photoshop). Turn it off once the body is laid out. -pub fn focus_first_field(ctx: &egui::Context, on: bool) { - ctx.data_mut(|d| { - if on { - d.insert_temp(first_field_id(), true); - } else { - d.remove::(first_field_id()); - } - }); -} - -const NUMERIC_INPUT_LIMIT: usize = 128; - -/// The number in a [`value_field`]. A typed number applies as it's typed; arithmetic waits for -/// Enter, Tab or click-away, because per keystroke `5/2` would land first and a caller that -/// rounds it would cut `5/2*2` short. `changed()` means a new value, not just a keystroke. -fn number_edit( - ui: &mut Ui, - value: &mut f32, - range: std::ops::RangeInclusive, - fine: bool, - decimals: Option, - units: crate::numeric_expression::Units, - wrap_drag: bool, -) -> Response { - let (id, ctx) = (ui.next_auto_id(), ui.ctx().clone()); - // Focused before the DragValue is drawn, so it gains focus this frame and selects its text. - if ui.data_mut(|d| d.remove_temp::(first_field_id())).unwrap_or(false) { - ui.memory_mut(|m| m.request_focus(id)); - } - // Tab in a dialog goes from one of these to the next (field_tab.rs). - if ui.is_enabled() { - crate::field_tab::register(&ctx, id); - } - // Use DragValue's focus check before it builds its TextEdit: oversized events must never - // reach text layout. Registering interest also handles focus arriving by Tab this frame. - let editing = ui.is_enabled() - && ui.memory_mut(|m| { - m.interested_in_focus(id, ui.layer_id()); - m.has_focus(id) - }); - if editing { - ui.input_mut(|input| { - input.events.retain(|event| { - let text = match event { - egui::Event::Text(text) | egui::Event::Paste(text) | egui::Event::Ime(egui::ImeEvent::Commit(text)) => text, - egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) => text, - _ => return true, - }; - text.chars().nth(NUMERIC_INPUT_LIMIT).is_none() - }); - }); - } - let held = id.with("arithmetic"); - let math = ui.memory(|m| m.has_focus(id)) && ui.data(|d| d.get_temp(held)).unwrap_or(false); - ui.data_mut(|d| d.insert_temp(held, math)); - let before = *value; - let speed = if fine { 0.01 } else { 0.5 }; - let wrapping = wrap_drag && crate::scrub_wrap::active(ui); - let wrapped_drag = wrapping && ui.input(|i| i.pointer.primary_down()); - let mut resp = ui.add( - egui::DragValue::new(value) - .range(range.clone()) - // Only edits are clamped (below): showing a value past the range, such as a type layer - // scaled to 2400 pt in a 1296 pt field, must not change it (#5717). - .clamp_existing_to_range(false) - // A warp is an absolute-position jump. The scoped scrub below removes that jump. - .speed(if wrapped_drag { 0.0 } else { speed }) - .custom_formatter(move |v, _| match decimals { - Some(d) => fmt_num_prec(v, d), - None if fine => fmt_num2(v), - None => fmt_num(v), - }) - .update_while_editing(!math) - // Focus is read when parsing, not above: Tab hands it on inside `ui.add`. - .custom_parser(move |s| { - // Short events can accumulate: reject before either parser normalizes the text. - if s.chars().nth(NUMERIC_INPUT_LIMIT).is_some() { - return None; - } - let v = parse_num_in(s, units); - if ctx.memory(|m| m.has_focus(id)) && plain(s).is_none() { - // Still typing arithmetic: hold it, and stop applying keystrokes once it parses. - ctx.data_mut(|d| d.insert_temp(held, v.is_some())); - return None; - } - v - }), - ); - if wrap_drag { - crate::scrub_wrap::update(ui, &resp, value, before, range.clone(), speed, wrapping); - } - let (lo, hi) = (*range.start(), *range.end()); - // `f32::clamp` panics on a reversed or NaN range, which `DragValue::range` accepts. - if *value != before && lo <= hi { - *value = value.clamp(lo, hi); - } - resp.flags.set(egui::response::Flags::CHANGED, *value != before); - resp -} - -/// Increments a numerical field with the up/down arrow keys. Increments by 1 by default, 10 with shift, and 0.1 with ctrl/cmd. -/// Returns the amount to add, and what to round the value to first. -fn arrow_step(ui: &mut Ui, slot: egui::Id, step: f32) -> (f32, f32) { - use egui::{Key, Modifiers}; - // The field's id is only known once it's drawn, so `value_field` saves it under `slot` for the next frame. - let Some(id) = ui.data(|d| d.get_temp::(slot)).filter(|id| ui.memory(|m| m.has_focus(*id))) else { - return (0.0, step); - }; - let (n, grid) = ui.input_mut(|i| { - let (mut n, mut grid) = (0.0, step); - // egui ignores an extra shift when matching, so shift is checked before the plain arrows to get its larger step. - for (mods, k) in [(Modifiers::COMMAND, (step / 10.0).max(0.01)), (Modifiers::SHIFT, 10.0 * step), (Modifiers::NONE, step)] { - let presses = i.count_and_consume_key(mods, Key::ArrowUp) as f32 - i.count_and_consume_key(mods, Key::ArrowDown) as f32; - if presses != 0.0 && mods == Modifiers::COMMAND { - grid = k; - } - n += k * presses; - } - (n, grid) - }); - // If a sum like 5+5 has been typed, unfocus the field so it calculates it (as Enter would) before we step. - if n != 0.0 && ui.data(|d| d.get_temp(id.with("arithmetic"))).unwrap_or(false) { - ui.memory_mut(|m| m.surrender_focus(id)); - } - (n, grid) -} - -/// Thin-track slider with a round knob. `gradient` paints the track (e.g. hue spectrum). -pub fn slider(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, gradient: Option<&[Color32]>) -> Response { - slider_with(ui, value, range, gradient, RowGestures::default()) -} - -/// Photoshop's gestures on a slider row beyond click and drag, as measured on Color Balance in -/// Photoshop 25.4 (Image › Adjustments dialog and the adjustment layer's Properties). Shift, Ctrl -/// and Alt change nothing about clicks, double-clicks or drags; the wheel takes ten steps with -/// Shift. (Up/Down in the field are every value field's, see [`value_field`].) -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct RowGestures { - /// A double-click on the slider (knob or track; not the label or field) sets this value. - pub reset: Option, - /// Each wheel notch over the slider moves the value by this step (up = higher; ×10 with - /// Shift). Photoshop does this in dialogs, not in the Properties panel. - pub wheel_step: Option, - /// A curved track: the knob at fraction f of the track is `lo + (hi - lo) * f^k`, so small - /// values get fine steps (Photoshop's mask Feather, #6545). Typed, scrubbed and stepped - /// values stay linear; only the track maps through the curve. - pub curve: Option, -} - -/// The value at fraction `f` of a track over `lo..=hi`, through `curve` (see [`RowGestures`]). -pub(crate) fn curve_value(f: f32, lo: f32, hi: f32, curve: Option) -> f32 { - match curve { - Some(k) if k.is_finite() && k > 0.0 => lo + f.clamp(0.0, 1.0).powf(k) * (hi - lo), - _ => lo + f * (hi - lo), - } -} - -/// Where `v` sits on a track over `lo..=hi`, as a fraction: the inverse of [`curve_value`]. -pub(crate) fn curve_fraction(v: f32, lo: f32, hi: f32, curve: Option) -> f32 { - let f = ((v - lo) / (hi - lo)).clamp(0.0, 1.0); - match curve { - // An unset (NaN) value draws the knob at the start rather than nowhere. - Some(k) if k.is_finite() && k > 0.0 => { - if f.is_finite() { - f.powf(1.0 / k) - } else { - 0.0 - } - } - _ => f, - } -} - -/// Wheel notches this frame while the pointer is over `resp` (Shift ×10). Wheel lines add up in -/// egui memory until they make whole notches (high-resolution wheels report fractions of one); -/// smooth (point) deltas count `line_scroll_speed` points per notch, like the canvas wheel. -fn wheel_notches(ui: &Ui, resp: &Response) -> f32 { - wheel_notches_of(ui, resp.id, resp.hovered(), 10.0) -} - -/// [`wheel_notches`] of widget `id` while `hovered`, a notch with Shift counting `shift_notches`. -pub(crate) fn wheel_notches_of(ui: &Ui, id: egui::Id, hovered: bool, shift_notches: f32) -> f32 { - if !hovered { - return 0.0; - } - let wheel: Vec<(egui::MouseWheelUnit, Vec2, bool)> = ui.input(|i| { - i.events - .iter() - .filter_map(|e| match e { - egui::Event::MouseWheel { unit, delta, modifiers, .. } => Some((*unit, *delta, modifiers.shift)), - _ => None, - }) - .collect() - }); - count_notches(ui, id.with("wheel-acc"), &wheel, shift_notches) -} - -/// Whole notches in `wheel` (unit, delta, Shift held), a notch with Shift counting -/// `shift_notches`; fractions carry over in egui memory under `acc_id`. -pub(crate) fn count_notches(ui: &Ui, acc_id: egui::Id, wheel: &[(egui::MouseWheelUnit, Vec2, bool)], shift_notches: f32) -> f32 { - let mut acc: f32 = ui.data(|d| d.get_temp(acc_id)).unwrap_or(0.0); - let per_line = ui.ctx().options(|o| o.input_options.line_scroll_speed); - let per_line = if per_line.is_finite() && per_line > 0.0 { per_line } else { 40.0 }; - let mut notches = 0.0; - for &(unit, delta, shift) in wheel { - // Some systems turn Shift+wheel into a horizontal scroll. - let d = if delta.y != 0.0 { delta.y } else { delta.x }; - acc += match unit { - egui::MouseWheelUnit::Point => d / per_line, - _ => d, - }; - let whole = acc.trunc(); - acc -= whole; - notches += if shift { whole * shift_notches } else { whole }; - } - if !acc.is_finite() { - acc = 0.0; - } - ui.data_mut(|d| d.insert_temp(acc_id, acc)); - if notches.is_finite() { notches } else { 0.0 } -} - -/// Windows' default double-click time (Photoshop's; egui's own default is 0.3 s). -const DOUBLE_CLICK_S: f64 = 0.5; - -/// Finger jitter between taps easily exceeds egui's 6 px `max_click_dist`; 64 px is about two-thirds of an inch at 96 DPI (roughly a fingertip pad). 32 px still rejected casual Framework double-taps; Windows' mouse SM_CXDOUBLECLK is only 4 px and is not used for touch. -const TOUCH_MAX_CLICK_DIST: f32 = 64.0; - -/// True when this frame's pointer work came from a touch contact (still down, or a Touch event including End on the click frame). -fn pointer_from_touch(ui: &Ui) -> bool { - ui.input(|i| i.any_touches() || i.events.iter().any(|e| matches!(e, egui::Event::Touch { .. }))) -} - -/// Whether this click on `resp` completes a double-click / double-tap, counted the Windows way (Photoshop): a click soon after a lone click near the same spot; the click after a double starts over. -/// -/// Time window is 0.5 s (Windows / Photoshop; egui's default is 0.3 s). Mouse uses egui's `max_click_dist` (6 px); touch uses [`TOUCH_MAX_CLICK_DIST`] so finger jitter between taps still counts. Call on every click for that widget so the first tap is remembered. -pub fn second_click(ui: &Ui, resp: &Response) -> bool { - if !resp.clicked() { - return false; - } - let key = resp.id.with("pc-last-click"); - // Prefer the response's hit pos: raw `pointer.interact_pos` can be unset on a release-only frame. - let pos = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.interact_pos())); - let time = ui.input(|i| i.time); - let touch = pointer_from_touch(ui); - let mouse_dist = ui.ctx().options(|o| o.input_options.max_click_dist); - let last: Option<(f64, Pos2, bool)> = ui.data(|d| d.get_temp(key)); - // Looser distance if either tap in the pair was touch (End clears `any_touches` but leaves Touch in `events`). - let dist = if touch || last.is_some_and(|(_, _, t)| t) { TOUCH_MAX_CLICK_DIST.max(mouse_dist) } else { mouse_dist }; - let double = match (last, pos) { - (Some((t, p, _)), Some(q)) => time - t < DOUBLE_CLICK_S && p.distance(q) < dist, - _ => false, - }; - ui.data_mut(|d| { - if let (false, Some(q)) = (double, pos) { - d.insert_temp(key, (time, q, touch)); - } else { - d.remove::<(f64, Pos2, bool)>(key); - } - }); - double -} - -fn slider_with(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, gradient: Option<&[Color32]>, g: RowGestures) -> Response { - let t = Tokens::get(ui.ctx()); - let width = ui.available_width().max(60.0); - let (rect, mut resp) = ui.allocate_exact_size(vec2(width, 18.0), Sense::click_and_drag()); - let (lo, hi) = (*range.start(), *range.end()); - let track = Rect::from_center_size(rect.center(), vec2(rect.width() - 14.0, if gradient.is_some() { 5.0 } else { 3.0 })); - if let Some(p) = resp.interact_pointer_pos() - && (resp.dragged() || resp.clicked()) - { - let f = ((p.x - track.left()) / track.width()).clamp(0.0, 1.0); - let nv = curve_value(f, lo, hi, g.curve); - if (nv - *value).abs() > f32::EPSILON { - *value = nv; - resp.mark_changed(); - } - } - // The double-click's first click has moved the knob to the pointer; the second resets. - if let Some(reset) = g.reset - && second_click(ui, &resp) - { - *value = reset; - resp.mark_changed(); - } - if let Some(step) = g.wheel_step { - let n = wheel_notches(ui, &resp); - if n != 0.0 { - let nv = (*value + n * step).clamp(lo, hi); - if nv != *value { - *value = nv; - resp.mark_changed(); - } - } - } - let f = curve_fraction(*value, lo, hi, g.curve); - let knob_x = track.left() + f * track.width(); - let painter = ui.painter(); - match gradient { - Some(colors) if colors.len() >= 2 => { - let n = colors.len() - 1; - for (i, w) in colors.windows(2).enumerate() { - let x0 = track.left() + track.width() * i as f32 / n as f32; - let x1 = track.left() + track.width() * (i + 1) as f32 / n as f32; - let mut mesh = egui::Mesh::default(); - let r = Rect::from_min_max(pos2(x0, track.top()), pos2(x1, track.bottom())); - mesh.colored_vertex(r.left_top(), w[0]); - mesh.colored_vertex(r.right_top(), w[1]); - mesh.colored_vertex(r.right_bottom(), w[1]); - mesh.colored_vertex(r.left_bottom(), w[0]); - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(0, 2, 3); - painter.add(mesh); - } - } - _ => { - painter.rect_filled(track, 2.0, t.field_border); - let filled = Rect::from_min_max(track.min, pos2(knob_x, track.max.y)); - painter.rect_filled(filled, 2.0, if t.bevel { t.accent } else { t.text_dim }); - } - } - let knob = pos2(knob_x, rect.center().y); - if t.bevel { - let kr = Rect::from_center_size(knob, vec2(10.0, 16.0)); - surface(ui, kr, t.card, true); - } else { - let kr = if t.pro { 6.0 } else { 7.0 }; - painter.circle_filled(knob + vec2(0.0, 1.0), kr + 0.5, Color32::from_black_alpha(90)); - painter.circle_filled(knob, kr, if t.pro { Color32::from_gray(236) } else { Color32::WHITE }); - if let Some(outline) = t.knob_outline() { - painter.circle_stroke(knob, kr, Stroke::new(1.0, outline)); - } - if resp.hovered() || resp.dragged() { - painter.circle_stroke(knob, 9.5, Stroke::new(2.0, t.accent_soft)); - } - } - resp -} - -/// Labelled slider row: `Label ........ [value field]` above a full-width thin slider. -pub fn slider_row(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, gradient: Option<&[Color32]>) -> Response { - slider_row_with(ui, label, value, range, suffix, gradient, RowGestures::default()) -} - -/// [`slider_row`] with Photoshop's extra gestures ([`RowGestures`]). -pub fn slider_row_with( - ui: &mut Ui, - label: &str, - value: &mut f32, - range: std::ops::RangeInclusive, - suffix: &str, - gradient: Option<&[Color32]>, - g: RowGestures, -) -> Response { - slider_row_prec(ui, label, value, range, suffix, gradient, g, None) -} - -/// [`slider_row_with`] whose field shows `decimals` places instead of the one (or two, for a -/// small range) it picks itself: Exposure's ±20 stops show two, its Offset four (#4164). -#[allow(clippy::too_many_arguments)] -pub fn slider_row_prec( - ui: &mut Ui, - label: &str, - value: &mut f32, - range: std::ops::RangeInclusive, - suffix: &str, - gradient: Option<&[Color32]>, - g: RowGestures, - decimals: Option, -) -> Response { - let t = Tokens::get(ui.ctx()); - let mut changed_resp = None; - // The row's caption names both its number (through the scrub link) and its slider. - let mut label_id = None; - ui.horizontal(|ui| { - // The label scrubs the row's field, across the row (Photoshop's scrubby labels). - let l = ui.label(egui::RichText::new(tl!(label)).color(t.text_dim)); - label_id = Some(l.id); - scrub_label_within(ui, &l, f32::INFINITY); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - changed_resp = Some( - value_field_in( - ui, - value, - range.clone(), - suffix, - 74.0, - 0.0, - FieldOpts { decimals, step_from_decimals: decimals.is_some(), ..Default::default() }, - None, - ) - .0, - ); - }); - }); - let s = slider_with(ui, value, range, gradient, g); - s.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(*value), tl!(label))); - let s = if let Some(id) = label_id { s.labelled_by(id) } else { s }; - let mut r = s.clone(); - if let Some(v) = changed_resp { - if v.changed() { - r.mark_changed(); - } - // A scrub of the field or its label is one drag, like the slider's, for history. - use egui::response::Flags; - r.flags |= v.flags & (Flags::DRAG_STARTED | Flags::DRAGGED | Flags::DRAG_STOPPED); - } - ui.add_space(4.0); - r -} - -/// iOS-style toggle switch. -pub fn toggle(ui: &mut Ui, on: &mut bool, label: &str) -> Response { - let t = Tokens::get(ui.ctx()); - if t.pro { - return checkbox(ui, on, label); - } - let mut resp = ui - .horizontal(|ui| { - let (rect, resp) = ui.allocate_exact_size(vec2(30.0, 17.0), Sense::click()); - let how_on = ui.ctx().animate_bool(resp.id, *on); - let bg = if *on { t.accent } else { t.field_border }; - if t.bevel { - surface(ui, rect, if *on { t.accent } else { t.field }, false); - } else { - ui.painter().rect_filled(rect, 8.5, bg); - } - let x = egui::lerp((rect.left() + 8.5)..=(rect.right() - 8.5), how_on); - ui.painter().circle_filled(pos2(x, rect.center().y), 6.5, Color32::WHITE); - ui.label(egui::RichText::new(tl!(label)).color(if *on { t.text } else { t.text_dim })); - resp - }) - .inner; - if resp.clicked() { - *on = !*on; - resp.mark_changed(); - } - resp -} - -/// Big white primary button. -pub fn primary_button(ui: &mut Ui, label: &str, min_width: f32) -> Response { - let t = Tokens::get(ui.ctx()); - button_impl(ui, label, min_width, t.primary_bg, t.primary_text, true) -} - -/// The width of the widest of `labels` as a button, for a column of equal-width buttons. -pub fn button_width(ui: &Ui, labels: &[&str]) -> f32 { - let fg = Tokens::get(ui.ctx()).text; - labels.iter().map(|l| button_layout(ui, l, 0.0, None, fg).1.x).fold(0.0, f32::max) -} - -pub fn secondary_button(ui: &mut Ui, label: &str, min_width: f32) -> Response { - let t = Tokens::get(ui.ctx()); - button_impl(ui, label, min_width, t.field, t.text, false) -} - -/// A [`secondary_button`] `height` points tall, for slim bars such as the status bar (#2823). -pub fn compact_button(ui: &mut Ui, label: &str, height: f32) -> Response { - let t = Tokens::get(ui.ctx()); - button_impl_h(ui, label, 0.0, Some(height), t.field, t.text, false) -} - -/// What a dialog button does, which decides where the platform's button order puts it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum ButtonRole { - /// The default answer (OK, Save, Yes), drawn as the primary button. - Default, - /// Another answer that closes the dialog (Don't Save, No). - Alternate, - /// Closes the dialog without acting. - Cancel, - /// Acts but keeps the dialog open (Apply). - Apply, -} - -impl ButtonRole { - /// Position from the left in the platform's order. Windows and Linux put the default action - /// first (OK Cancel Apply, Yes No Cancel); macOS puts it last, in the corner, with Cancel beside - /// it and the other answers further left (Don't Save, Cancel, Save). - fn slot(self, mac: bool) -> u8 { - match (self, mac) { - (Self::Default, false) | (Self::Alternate, true) => 0, - (Self::Alternate, false) | (Self::Cancel, true) => 1, - (Self::Cancel, false) | (Self::Apply, true) => 2, - (Self::Apply, false) | (Self::Default, true) => 3, - } - } -} - -/// One button of a [`dialog_buttons`] row. -#[derive(Clone, Copy)] -pub struct DialogButton<'a> { - pub role: ButtonRole, - pub label: &'a str, - pub min_width: f32, - pub enabled: bool, - /// Take keyboard focus this frame (see [`DialogButton::focus`]). - pub focus: bool, -} - -impl<'a> DialogButton<'a> { - pub fn new(role: ButtonRole, label: &'a str, min_width: f32) -> Self { - Self { role, label, min_width, enabled: true, focus: false } - } - - pub fn enabled(self, enabled: bool) -> Self { - Self { enabled, ..self } - } - - /// Asks for keyboard focus for this button: from there the arrow keys move between the row's - /// buttons and Enter or Space presses the focused one. - pub fn focus(self, focus: bool) -> Self { - Self { focus, ..self } - } -} - -/// A dialog's button row at the cursor, in the platform's order (see [`ButtonRole`]): every modal -/// draws its buttons through this, so they all agree. Inside a right-to-left row it sits at the -/// right edge. The buttons are laid out left to right, so Tab walks them in reading order. -/// Returns the role of the button clicked this frame. -pub fn dialog_buttons(ui: &mut Ui, buttons: &[DialogButton]) -> Option { - let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac; - let gap = ui.spacing().item_spacing.x; - let size = buttons.iter().fold(Vec2::ZERO, |acc, b| { - let s = button_size(ui, b.label, b.min_width); - vec2(acc.x + s.x, acc.y.max(s.y)) - }) + vec2(gap * buttons.len().saturating_sub(1) as f32, 0.0); - ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { - let mut hit = None; - for slot in 0..4 { - for b in buttons.iter().filter(|b| b.role.slot(mac) == slot) { - let r = ui - .add_enabled_ui(b.enabled, |ui| { - if b.role == ButtonRole::Default { primary_button(ui, b.label, b.min_width) } else { secondary_button(ui, b.label, b.min_width) } - }) - .inner; - if b.focus && b.enabled { - r.request_focus(); - } - if r.clicked() { - hit = Some(b.role); - } - } - } - hit - }) - .inner -} - -/// The size of a primary or secondary button: its label plus padding, at least `min_width` wide. -fn button_size(ui: &Ui, label: &str, min_width: f32) -> Vec2 { - button_layout(ui, label, min_width, None, Tokens::get(ui.ctx()).text).1 -} - -/// The height of a primary or secondary button (and so of a dialog's button row). -pub fn button_height(ctx: &egui::Context) -> f32 { - if Tokens::get(ctx).pro { 28.0 } else { 30.0 } -} - -fn button_layout(ui: &Ui, label: &str, min_width: f32, height: Option, fg: Color32) -> (std::sync::Arc, Vec2) { - let galley = ui.painter().layout_no_wrap(tl!(label).to_owned(), theme::medium(13.0), fg); - let h = height.unwrap_or(button_height(ui.ctx())); - let size = vec2((galley.size().x + 28.0).max(min_width), h); - (galley, size) -} - -fn button_impl(ui: &mut Ui, label: &str, min_width: f32, bg: Color32, fg: Color32, primary: bool) -> Response { - button_impl_h(ui, label, min_width, None, bg, fg, primary) -} - -/// [`button_impl`] with an explicit `height` (`None`: the theme's button height). -fn button_impl_h(ui: &mut Ui, label: &str, min_width: f32, height: Option, bg: Color32, fg: Color32, primary: bool) -> Response { - let t = Tokens::get(ui.ctx()); - let (galley, size) = button_layout(ui, label, min_width, height, fg); - let h = size.y; - let (rect, resp) = ui.allocate_exact_size(size, Sense::click()); - // Painted text: name the button for accessibility (and so tests and agents can find it). - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label)); - if resp.has_focus() { - // Keyboard focus (Tab); clicks don't focus egui buttons. - let r = if t.pro { h / 2.0 } else { t.radius_sm } + 2.0; - ui.painter().rect_stroke(rect.expand(2.0), r, Stroke::new(2.0, t.accent), StrokeKind::Outside); - } - if t.pro { - // Spectrum buttons: fully rounded; primary = filled accent, secondary = outline. - let down = resp.is_pointer_button_down_on(); - let r = h / 2.0; - if primary { - let fill = if down { - bg.gamma_multiply(0.8) - } else if resp.hovered() { - bg.gamma_multiply(0.9) - } else { - bg - }; - ui.painter().rect_filled(rect, r, fill); - } else { - if resp.hovered() || down { - ui.painter().rect_filled(rect, r, t.hover); - } - ui.painter().rect_stroke(rect, r, Stroke::new(1.5, if resp.hovered() { t.text } else { t.text_dim }), StrokeKind::Inside); - } - ui.painter().galley(rect.center() - galley.size() / 2.0, galley, fg); - return resp; - } - let fill = if resp.is_pointer_button_down_on() { - bg.gamma_multiply(0.85) - } else if resp.hovered() { - if primary { bg.gamma_multiply(0.93) } else { t.hover } - } else { - bg - }; - surface(ui, rect, fill, !resp.is_pointer_button_down_on()); - if !t.bevel && !primary { - ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); - } - ui.painter().galley(rect.center() - galley.size() / 2.0, galley, fg); - resp -} - -/// Cached RGB data; drawing work is bounded by the 256 display bins, never the image size. -pub fn rgb_histogram(ui: &mut Ui, histogram: &photocraft_algo::histogram::RgbHistogram, height: f32) -> egui::Response { - let t = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(egui::vec2(ui.available_width().max(1.0), height.max(1.0)), egui::Sense::hover()); - ui.painter().rect_filled(rect, t.radius_sm, t.histogram_background()); - let plot = rect.shrink(4.0); - crate::rgb_histogram::paint(ui.painter(), plot, histogram, &t); - ui.painter().rect_stroke(rect, t.radius_sm, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); - response -} - -/// Small caps section label. -pub fn section_label(ui: &mut Ui, text: &str) { - let t = Tokens::get(ui.ctx()); - ui.label(egui::RichText::new(tl!(text)).font(theme::medium(11.5)).color(t.text_faint)); -} - -/// Hairline separator. -pub fn hairline(ui: &mut Ui) { - let t = Tokens::get(ui.ctx()); - let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 1.0), Sense::hover()); - ui.painter().line_segment([r.left_center(), r.right_center()], Stroke::new(1.0, t.separator)); -} - -/// Vertical hairline for horizontal layouts. -pub fn vline(ui: &mut Ui, height: f32) { - let t = Tokens::get(ui.ctx()); - let (r, _) = ui.allocate_exact_size(vec2(9.0, height), Sense::hover()); - ui.painter().line_segment([r.center_top(), r.center_bottom()], Stroke::new(1.0, t.separator)); -} - -/// The fully saturated colour at hue `deg` (degrees), built on sRGB values as Photoshop's hue -/// tracks are: 0 is (255,0,0), 60 is (255,255,0), 120 is (0,255,0) and so on (#6540). -pub fn hue_color(deg: f32) -> Color32 { - let [r, g, b] = photocraft_color::convert::hsb_to_rgb([deg, 1.0, 1.0]); - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - Color32::from_rgb(q(r), q(g), q(b)) -} - -/// Hue spectrum stops for colour sliders: red, yellow, green, cyan, blue, magenta, red. -pub fn hue_stops() -> Vec { - (0..=12).map(|i| hue_color(i as f32 * 30.0)).collect() -} - -/// 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 { - dropdown_hovered(ui, id, name, current, options, width).0 -} - -/// [`dropdown`] whose option labels are shown exactly as given: names the user typed (a channel -/// or layer name) must not be translated, unlike the built-in labels [`dropdown`] translates (#5335). -pub fn dropdown_literal(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool { - let (chosen, _) = dropdown_with(ui, id, name, current, options, width, false, false); - !chosen.is_empty() -} - -/// [`dropdown`], also returning the option under the pointer in its open list (live previews). -pub fn dropdown_hovered(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> (bool, Option) { - let (chosen, hovered) = dropdown_with(ui, id, name, current, options, width, false, true); - (!chosen.is_empty(), hovered) -} - -/// [`dropdown_hovered`] whose value also steps with the wheel over its button or open list: down -/// picks the next option, up the previous one, one per notch (Shift too), stopping at the ends -/// (Photoshop's Layers panel blend modes, #1747). The wheel then scrolls neither the list, which -/// follows the value instead, nor what the dropdown is in. Returns every option chosen this frame -/// in order (one per notch; the last is `current`) and the option under the pointer in the open -/// list, none while the pointer rests where the wheel last stepped. -pub fn dropdown_wheel_hovered( - ui: &mut Ui, - id: &str, - name: &str, - current: &mut T, - options: &[(T, &str)], - width: f32, -) -> (Vec, Option) { - dropdown_with(ui, id, name, current, options, width, true, true) -} - -#[allow(clippy::too_many_arguments)] -fn dropdown_with( - ui: &mut Ui, - id: &str, - name: &str, - current: &mut T, - options: &[(T, &str)], - width: f32, - wheel: bool, - translate: bool, -) -> (Vec, Option) { - let shown = |l: &str| if translate { tl!(l).to_string() } else { l.to_string() }; - let label = options.iter().find(|(v, _)| v == current).map(|(_, l)| shown(l)).unwrap_or_else(|| "—".into()); - let (mut chosen, mut hovered) = (Vec::new(), None); - // The wheel's notches add up over the button and the open list alike. - let wheel_id = ui.make_persistent_id(id).with("wheel"); - let wheel = wheel && ui.is_enabled(); - let (mut over_list, mut wheeled, mut keyed) = (false, false, false); - // A wheel step scrolls the open list to the new value: at once over the list, the next frame - // after a step over the button. - let reveal_id = wheel_id.with("reveal"); - let mut reveal = wheel && ui.data_mut(|d| d.remove_temp::(reveal_id)).unwrap_or(false); - // 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 = - egui::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)) { - *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 ((v, _), text) in options.iter().zip(texts.iter()) { - 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()); - } - }); - // 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), - None => response.response.accessible_name(name), - }; - press.after(&response); - if combo_box_arrow_keys(ui, &response, current, options) { - chosen.push(current.clone()); - } - if wheel && !over_list { - let stepped = wheel_steps(ui, wheel_id, response.hovered(), current, options); - wheeled = !stepped.is_empty(); - if wheeled && egui::ComboBox::is_open(ui.ctx(), response.id) { - ui.data_mut(|d| d.insert_temp(reveal_id, true)); - } - chosen.extend(stepped); - } - // Nor is the option under a pointer resting where the keyboard picked another. - if wheel_rests(ui, wheel_id, wheeled || keyed) { - hovered = None; - } - (chosen, hovered) -} - -/// Makes an open dropdown list as wide as its widest option is when hovered, from the start. egui -/// takes a plain row's frame stroke off its padding but draws a hovered row with the stroke, so a -/// row grows by two stroke widths under the pointer, and the list never shrinks back: scrolling -/// the widest option under the pointer widened the list (#2607). -fn fit_widest_option<'a>(ui: &mut Ui, labels: impl Iterator) { - let extend = Some(egui::TextWrapMode::Extend); - let widest = labels.map(|l| egui::WidgetText::from(l).into_galley(ui, extend, f32::INFINITY, egui::FontSelection::Default).size().x).fold(0.0, f32::max); - ui.set_min_width(widest + 2.0 * ui.spacing().button_padding.x); -} - -/// Whether the pointer still rests where the wheel last stepped dropdown `id` (`wheeled`: it did -/// this frame). The option under it then isn't the one to preview: the value moved on without it. -fn wheel_rests(ui: &Ui, id: egui::Id, wheeled: bool) -> bool { - let key = id.with("at"); - let pointer = ui.input(|i| i.pointer.hover_pos()); - if wheeled && let Some(p) = pointer { - ui.data_mut(|d| d.insert_temp(key, p)); - } - let rests = pointer.is_some() && ui.data(|d| d.get_temp::(key)) == pointer; - if !rests { - ui.data_mut(|d| d.remove::(key)); - } - rests -} - -/// The options the wheel over dropdown `id` (while `hovered`) steps `current` through this frame, -/// one per notch, in order; the last is the new `current`. While the pointer is over it the wheel -/// scrolls nothing else. -fn wheel_steps(ui: &mut Ui, id: egui::Id, hovered: bool, current: &mut T, options: &[(T, &str)]) -> Vec { - if hovered { - ui.input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO); - } - let notches = wheel_notches_of(ui, id, hovered, 1.0); - let Some(mut index) = options.iter().position(|(v, _)| v == current) else { return Vec::new() }; - let mut chosen = Vec::new(); - // Down (negative) is the next option. No more steps than there are options. - for _ in 0..(notches.abs().min(options.len() as f32) as usize) { - let next = if notches < 0.0 { index.checked_add(1) } else { index.checked_sub(1) }; - let Some((next, (v, _))) = next.and_then(|i| options.get(i).map(|o| (i, o))) else { break }; - index = next; - chosen.push(v.clone()); - } - if let Some(v) = chosen.last() { - *current = v.clone(); - } - chosen -} - -/// Give a dropdown keyboard focus when it opens, then use the arrow keys to move through its -/// choices. `egui::ComboBox` opens a popup but leaves focus on the canvas by default, which makes -/// controls such as the Layers panel's Blend Mode dropdown unreachable from the keyboard. -fn combo_box_arrow_keys(ui: &mut Ui, response: &Response, current: &mut T, options: &[(T, &str)]) -> bool { - if response.clicked() { - response.request_focus(); - } - // The popup, rather than its button, becomes the focused egui layer after it opens. While it - // is open it owns its navigation keys, even though `response.has_focus()` is then false. - if !egui::ComboBox::is_open(ui.ctx(), response.id) || options.is_empty() { - return false; - } - let step = if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown)) { - 1 - } else if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp)) { - -1 - } else { - return false; - }; - let index = options.iter().position(|(value, _)| value == current).unwrap_or(0); - let next = if step > 0 { (index + 1).min(options.len() - 1) } else { index.saturating_sub(1) }; - match options.get(next) { - Some((value, _)) if next != index => { - *current = value.clone(); - true - } - _ => false, - } -} - -/// The body of a right-click menu: as tall as its items up to the part of the window that can be -/// seen (clear of a taskbar a too-tall window runs under, #315), scrolling past that, so long -/// context menus (a layer's, the canvas tools') stay reachable on small windows instead of running -/// off the bottom. egui moves a popup up to keep it in the window, so a menu opened low on the -/// screen first shifts up and only scrolls when it is taller than the window. -pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R { - // The popup frame's margin and stroke, and a small gap to the window's edges. - let frame = ui.spacing().menu_margin.sum().y + 2.0 + 2.0 * MENU_EDGE; - let room = (crate::work_area::visible_rect(ui.ctx()).height() - frame).max(MENU_MIN_HEIGHT); - // 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. - egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room).show(ui, add_contents).inner -} - -/// Gap kept between a context menu and the window's edges, and the shortest it gets. -const MENU_EDGE: f32 = 4.0; -const MENU_MIN_HEIGHT: f32 = 120.0; - -/// The colour picker popup of a colour swatch: a click on `swatch` toggles it, a click outside -/// closes it. While open, its left edge stays where it first showed (at the swatch, or further -/// left when the window edge needs it), below the swatch or above it as room allows. The picker's -/// width follows its value readouts, and placing it anew every frame moved it under the pointer, -/// flipping it from side to side near the right edge of the window (#534). -pub fn swatch_popup(swatch: &Response) -> egui::Popup<'static> { - // Room for the readouts to widen after the picker opened. - const SLACK: f32 = 32.0; - let popup = egui::Popup::from_toggle_button_response(swatch).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); - let ctx = &swatch.ctx; - let key = popup.get_id().with("left"); - if !popup.is_open() { - ctx.data_mut(|d| d.remove::(key)); - return popup; - } - crate::press_menu::above_parent(ctx, swatch.layer_id, egui::LayerId::new(egui::Order::Foreground, popup.get_id())); - // Its width is known from the frame after it opened (egui sizes it unseen first). - let left = ctx.data(|d| d.get_temp::(key)).or_else(|| { - let width = popup.get_expected_size()?.x; - let screen = ctx.content_rect(); - let left = swatch.rect.left().min(screen.right() - width - SLACK).max(screen.left()); - ctx.data_mut(|d| d.insert_temp(key, left)); - Some(left) - }); - let Some(left) = left else { return popup }; - popup - .anchor(Rect::from_x_y_ranges(left..=left, swatch.rect.y_range())) - .align(egui::RectAlign::BOTTOM_START) - .align_alternatives(&[egui::RectAlign::TOP_START]) -} - -pub fn dropdown_with_tooltips(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str, &str)], width: f32) -> bool { - 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 = - egui::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)) { - *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), - }; - press.after(&response); - if let Some((_, _, tip)) = options.iter().find(|(v, _, _)| v == current) { - response.on_hover_text(tl!(tip)); - } - changed -} - -/// Paint a small checkerboard (transparency) in `rect`. -pub fn checker(painter: &egui::Painter, rect: Rect, cell: f32) { - painter.rect_filled(rect, 0.0, Color32::from_gray(250)); - let nx = (rect.width() / cell).ceil() as i32; - let ny = (rect.height() / cell).ceil() as i32; - for j in 0..ny { - for i in 0..nx { - if (i + j) % 2 == 1 { - let r = Rect::from_min_size(Pos2::new(rect.left() + i as f32 * cell, rect.top() + j as f32 * cell), Vec2::splat(cell)).intersect(rect); - painter.rect_filled(r, 0.0, Color32::from_gray(214)); - } - } - } -} - -/// A transparency checkerboard of `cell`-point squares clipped to `rect` with `radius` corners, -/// for rounded swatches (#3208): [`checker`] paints square cells, which showed past a rounded -/// fill's corners. This one is a repeating two-by-two tile textured onto the rounded rect. -pub fn checker_rounded(painter: &egui::Painter, rect: Rect, cell: f32, radius: impl Into) { - let tile = checker_tile(painter.ctx()); - painter.add(egui::epaint::RectShape::filled(rect, radius, Color32::WHITE).with_texture(tile.id(), checker_uv(rect, cell))); -} - -/// The texture range that tiles `rect` with `cell`-point squares: the tile holds two cells a side. -fn checker_uv(rect: Rect, cell: f32) -> Rect { - let cell = if cell.is_finite() && cell > 0.0 { cell } else { 4.0 }; - Rect::from_min_max(Pos2::ZERO, pos2(rect.width() / (2.0 * cell), rect.height() / (2.0 * cell))) -} - -fn checker_tile_id() -> egui::Id { - egui::Id::unique("transparency-checker-tile") -} - -/// The checker's two-by-two tile (light, dark / dark, light), loaded once per context and shared -/// by every rounded checker; it repeats and never blurs. -fn checker_tile(ctx: &egui::Context) -> egui::TextureHandle { - if let Some(tile) = ctx.data(|d| d.get_temp::(checker_tile_id())) { - return tile; - } - let (light, dark) = (Color32::from_gray(250), Color32::from_gray(214)); - let image = egui::ColorImage::new([2, 2], vec![light, dark, dark, light]); - let options = egui::TextureOptions { - magnification: egui::TextureFilter::Nearest, - minification: egui::TextureFilter::Nearest, - wrap_mode: egui::TextureWrapMode::Repeat, - mipmap_mode: None, - }; - let tile = ctx.load_texture("transparency-checker-tile", image, options); - ctx.data_mut(|d| d.insert_temp(checker_tile_id(), tile.clone())); - tile -} - -/// Spectrum-style checkbox (blue when checked). -pub fn checkbox(ui: &mut Ui, on: &mut bool, label: &str) -> Response { - let t = Tokens::get(ui.ctx()); - let (mut resp, label_resp) = ui - .horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 6.0; - let (rect, resp) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::CLICK); - let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand); - let l = ui - .add(egui::Label::new(egui::RichText::new(tl!(label)).color(t.text_dim)).selectable(false).sense(Sense::click())) - .on_hover_cursor(egui::CursorIcon::PointingHand); - // Pressing the label presses the box (#4476). - let pressed = resp.is_pointer_button_down_on() || l.is_pointer_button_down_on(); - check_box(ui.painter(), rect, *on, resp.hovered() || l.hovered(), pressed, &t); - (resp.union(l.clone()), l) - }) - .inner; - if resp.clicked() { - *on = !*on; - resp.mark_changed(); - } - // The label is the single named, focusable checkbox; the box is a mouse target. - // Override Label's metadata instead of creating a second node with the same name. - label_resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, ui.is_enabled(), *on, tl!(label))); - resp -} - -/// The fill of a check box: the accent when `on`, else the field colour. While it's pressed -/// (the mouse is down on it or on its label) Photoshop shows that a release will act: an -/// unchecked box darkens a little and a checked one turns a little less opaque (#4476). -pub fn check_box_fill(on: bool, pressed: bool, t: &Tokens) -> Color32 { - match (on, pressed) { - (true, false) => t.accent, - (true, true) => t.accent.gamma_multiply(0.75), - (false, false) => t.field, - (false, true) => t.field.lerp_to_gamma(Color32::BLACK, 0.18), - } -} - -/// Paint a check box in `rect`: [`check_box_fill`] with a white tick when `on`, else an -/// outline that brightens while `hovered` or `pressed`. -pub fn check_box(p: &egui::Painter, rect: Rect, on: bool, hovered: bool, pressed: bool, t: &Tokens) { - p.rect_filled(rect, 2.0, check_box_fill(on, pressed, t)); - if on { - let a = rect.left_center() + vec2(3.0, 0.5); - let b = rect.center_bottom() + vec2(-1.0, -3.5); - let c = rect.right_top() + vec2(-3.0, 3.5); - let tick = Stroke::new(rect.width() * 0.125, Color32::WHITE); - p.line_segment([a, b], tick); - p.line_segment([b, c], tick); - } else { - p.rect_stroke(rect, 2.0, Stroke::new(1.5, if hovered || pressed { t.text_dim } else { t.text_faint }), StrokeKind::Inside); - } -} - -/// Small chevron for dropdowns (replaces egui's filled triangle). -pub fn chevron_icon(ui: &Ui, rect: Rect, visuals: &egui::style::WidgetVisuals, _open: bool) { - let c = rect.center(); - let s = 3.2; - let stroke = Stroke::new(1.3, visuals.fg_stroke.color.gamma_multiply(0.8)); - ui.painter().line_segment([c + vec2(-s, -s * 0.5), c + vec2(0.0, s * 0.5)], stroke); - ui.painter().line_segment([c + vec2(0.0, s * 0.5), c + vec2(s, -s * 0.5)], stroke); -} - -/// Photoshop-style numbers: "100", "12.5" (never "100.0"). -pub fn fmt_num(v: f64) -> String { - fmt_num_prec(v, 1) -} - -/// Rounds `v` to `decimals` places (half away from zero) and drops trailing zeros, so a value is -/// never shown with more precision than it has: `0.7995` at three places is `0.8`, `2.0` is `2` -/// (#2434). [`photocraft_engine::prefs::Unit::decimals`] gives each ruler unit's places. -pub fn fmt_num_prec(v: f64, decimals: u32) -> String { - photocraft_engine::prefs::fmt_decimals(v, decimals as usize) -} - -/// Two-decimal variant of [`fmt_num`] for small ranges: `1.05`, `0.78`, `2`. -pub fn fmt_num2(v: f64) -> String { - fmt_num_prec(v, 2) -} - -/// Parses a typed number or bounded arithmetic, including parentheses and powers. -/// Preserves egui-compatible whitespace and Unicode minus handling. -pub fn parse_num(text: &str) -> Option { - if text.len() > 1024 { - return None; - } - crate::numeric_expression::parse(&clean(text)) -} - -/// [`parse_num`] in a field with `units`: a number may carry a unit (`2in`, `5mm`, `50%`), -/// converted into the field's unit; one that can't convert makes the text invalid. -pub(crate) fn parse_num_in(text: &str, units: crate::numeric_expression::Units) -> Option { - if text.len() > 1024 { - return None; - } - crate::numeric_expression::parse_with_units(&clean(text), Some(units)) -} - -/// A plain typed number, no arithmetic. -fn plain(text: &str) -> Option { - clean(text).parse().ok() -} - -fn clean(text: &str) -> String { - text.chars().filter(|c| !c.is_whitespace()).map(|c| if c == '−' { '-' } else { c }).collect() -} +mod buttons; +mod color; +mod dropdown; +mod fields; +mod panel; +mod scrub; +mod slider; +mod text_field; +mod units; + +pub use buttons::{ + ButtonRole, DialogButton, button_height, button_width, check_box, check_box_fill, checkbox, compact_button, dialog_buttons, primary_button, + secondary_button, toggle, +}; +pub(crate) use color::color_swatch; +pub use color::{ + checker, checker_rounded, color_edit_button_rgb, color_edit_button_srgb, color_edit_button_srgba, color_swatch_button, hue_color, hue_stops, pick_pos, + rgb_histogram, +}; +#[cfg(test)] +use color::{checker_tile_id, checker_uv}; +pub use dropdown::{dropdown, dropdown_hovered, dropdown_literal, 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, +}; +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 use scrub::{scrub_label, scrub_option_icon, scrub_option_label}; +#[cfg(test)] +use slider::DOUBLE_CLICK_S; +pub use slider::{RowGestures, second_click, slider, slider_row, slider_row_prec, slider_row_with}; +pub(crate) use slider::{count_notches, wheel_notches_of}; +#[cfg(test)] +pub(crate) use slider::{curve_fraction, curve_value}; +pub use text_field::{INPUT_EVENT_LIMIT, TEXT_FIELD_H, TEXT_FIELD_LIMIT, cap_text_events, focus_first_field, text_field, text_field_ex}; +pub use units::{ + FieldUnits, fmt_num, fmt_num_prec, fmt_num2, parse_num, set_field_resolution, unit_decimals, unit_of_key, value_field_extent, value_field_prec, + value_field_units, +}; #[cfg(test)] mod tests; -/// A compact colour popup with the shared desktop eyedropper. Keep egui's colour cache so hue -/// survives black/white and alpha edits, and keep linear and encoded call sites distinct. -pub fn color_edit_button_srgba(ui: &mut Ui, color: &mut Color32) -> Response { - color_edit_button(ui, color, egui::color_picker::Alpha::BlendOrAdditive) -} -pub(crate) fn color_swatch(ui: &mut Ui, color: Color32) -> Response { - let t = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(ui.spacing().interact_size, Sense::click()); - // A swatch's meaning is the colour it edits; callers with a more specific caption use - // `color_swatch_button` or add `labelled_by`. - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ColorWell, ui.is_enabled(), tl!("Color"))); - checker_rounded(ui.painter(), rect, 4.0, t.radius_sm); - ui.painter().rect_filled(rect.shrink(1.0), t.radius_sm, color); - ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); - response -} -/// Where a press or drag on a picking surface (a colour field, a hue strip) points, from the -/// frame the button goes down and on every move after it. `dragged()` waits for egui's click -/// threshold (a few points of travel, or a long hold), so a press picked nothing until the -/// pointer had moved away and fine adjustments jumped (#7793). Only the primary button picks: -/// `is_pointer_button_down_on` is true for any button, so a right or middle press is ignored. -pub fn pick_pos(resp: &Response) -> Option { - let held = resp.is_pointer_button_down_on() - && resp.ctx.input(|i| i.pointer.primary_down() && !i.pointer.button_down(egui::PointerButton::Secondary) && !i.pointer.middle_down()); - if held || resp.clicked() { resp.interact_pointer_pos() } else { None } -} -/// A colour swatch that only reports clicks (no popup): for colours edited in PhotoCraft's own -/// Color Picker dialog. `label` names it for hover text and accessibility. -pub fn color_swatch_button(ui: &mut Ui, color: Color32, label: &str) -> Response { - let t = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(ui.spacing().interact_size, Sense::click()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ColorWell, true, label)); - checker_rounded(ui.painter(), rect, 4.0, t.radius_sm); - ui.painter().rect_filled(rect.shrink(1.0), t.radius_sm, color); - ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); - response.on_hover_text(label) -} -fn color_edit_button(ui: &mut Ui, color: &mut Color32, alpha: egui::color_picker::Alpha) -> Response { - let mut response = color_swatch(ui, *color); - let id = response.id.with("screen-color"); - if let Some(rgb) = crate::screen_picker::take(ui.ctx(), id) { - *color = sampled_color(rgb, *color, alpha); - response.mark_changed(); - } - swatch_popup(&response).show(|ui| { - if egui::color_picker::color_picker_color32(ui, color, alpha) { - response.mark_changed(); - } - if let Some(rgb) = crate::screen_picker::button(ui, id) { - *color = sampled_color(rgb, *color, alpha); - response.mark_changed(); - } - }); - response -} -fn sampled_color(rgb: [f32; 3], original: Color32, alpha: egui::color_picker::Alpha) -> Color32 { - let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - if matches!(alpha, egui::color_picker::Alpha::BlendOrAdditive) && original.is_additive() { - return Color32::from_rgb_additive(byte(rgb[0]), byte(rgb[1]), byte(rgb[2])); - } - Color32::from_rgba_unmultiplied( - byte(rgb[0]), - byte(rgb[1]), - byte(rgb[2]), - if matches!(alpha, egui::color_picker::Alpha::Opaque) { 255 } else { original.a() }, - ) -} -pub fn color_edit_button_srgb(ui: &mut Ui, rgb: &mut [u8; 3]) -> Response { - let mut color = Color32::from_rgb(rgb[0], rgb[1], rgb[2]); - let response = color_edit_button(ui, &mut color, egui::color_picker::Alpha::Opaque); - if response.changed() { - *rgb = [color.r(), color.g(), color.b()]; - } - response -} -/// Like egui's float RGB widget, this entry point stores linear RGB (not encoded hex values). -pub fn color_edit_button_rgb(ui: &mut Ui, rgb: &mut [f32; 3]) -> Response { - let mut response = color_swatch(ui, Color32::from(egui::Rgba::from_rgb(rgb[0], rgb[1], rgb[2]))); - let id = response.id.with("screen-color"); - let to_linear = |color: [f32; 3]| color.map(egui::ecolor::linear_from_gamma); - if let Some(color) = crate::screen_picker::take(ui.ctx(), id) { - *rgb = to_linear(color); - response.mark_changed(); - } - let rgba = egui::Rgba::from_rgb(rgb[0], rgb[1], rgb[2]); - let cache = response.id.with("linear-hsva"); - let mut hsva = ui - .ctx() - .data(|d| d.get_temp::<(egui::Rgba, egui::ecolor::Hsva)>(cache)) - .filter(|(previous, _)| *previous == rgba) - .map(|(_, hsva)| hsva) - .unwrap_or_else(|| egui::ecolor::Hsva::from(rgba)); - swatch_popup(&response).show(|ui| { - if egui::color_picker::color_picker_hsva_2d(ui, &mut hsva, egui::color_picker::Alpha::Opaque) { - let color = egui::Rgba::from(hsva); - *rgb = [color.r(), color.g(), color.b()]; - response.mark_changed(); - } - if let Some(color) = crate::screen_picker::button(ui, id) { - *rgb = to_linear(color); - hsva = egui::ecolor::Hsva::from(egui::Rgba::from_rgb(rgb[0], rgb[1], rgb[2])); - response.mark_changed(); - } - }); - ui.ctx().data_mut(|d| d.insert_temp(cache, (egui::Rgba::from_rgb(rgb[0], rgb[1], rgb[2]), hsva))); - response -} - #[cfg(test)] mod screen_color_tests { use super::*; diff --git a/crates/ui-egui/src/widgets/buttons.rs b/crates/ui-egui/src/widgets/buttons.rs new file mode 100644 index 0000000000..c6ac810d23 --- /dev/null +++ b/crates/ui-egui/src/widgets/buttons.rs @@ -0,0 +1,267 @@ +use super::panel::surface; +use super::*; + +/// iOS-style toggle switch. +pub fn toggle(ui: &mut Ui, on: &mut bool, label: &str) -> Response { + let t = Tokens::get(ui.ctx()); + if t.pro { + return checkbox(ui, on, label); + } + let mut resp = ui + .horizontal(|ui| { + let (rect, resp) = ui.allocate_exact_size(vec2(30.0, 17.0), Sense::click()); + let how_on = ui.ctx().animate_bool(resp.id, *on); + let bg = if *on { t.accent } else { t.field_border }; + if t.bevel { + surface(ui, rect, if *on { t.accent } else { t.field }, false); + } else { + ui.painter().rect_filled(rect, 8.5, bg); + } + let x = egui::lerp((rect.left() + 8.5)..=(rect.right() - 8.5), how_on); + ui.painter().circle_filled(pos2(x, rect.center().y), 6.5, Color32::WHITE); + ui.label(egui::RichText::new(tl!(label)).color(if *on { t.text } else { t.text_dim })); + resp + }) + .inner; + if resp.clicked() { + *on = !*on; + resp.mark_changed(); + } + resp +} + +/// Big white primary button. +pub fn primary_button(ui: &mut Ui, label: &str, min_width: f32) -> Response { + let t = Tokens::get(ui.ctx()); + button_impl(ui, label, min_width, t.primary_bg, t.primary_text, true) +} + +/// The width of the widest of `labels` as a button, for a column of equal-width buttons. +pub fn button_width(ui: &Ui, labels: &[&str]) -> f32 { + let fg = Tokens::get(ui.ctx()).text; + labels.iter().map(|l| button_layout(ui, l, 0.0, None, fg).1.x).fold(0.0, f32::max) +} + +pub fn secondary_button(ui: &mut Ui, label: &str, min_width: f32) -> Response { + let t = Tokens::get(ui.ctx()); + button_impl(ui, label, min_width, t.field, t.text, false) +} + +/// A [`secondary_button`] `height` points tall, for slim bars such as the status bar (#2823). +pub fn compact_button(ui: &mut Ui, label: &str, height: f32) -> Response { + let t = Tokens::get(ui.ctx()); + button_impl_h(ui, label, 0.0, Some(height), t.field, t.text, false) +} + +/// What a dialog button does, which decides where the platform's button order puts it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ButtonRole { + /// The default answer (OK, Save, Yes), drawn as the primary button. + Default, + /// Another answer that closes the dialog (Don't Save, No). + Alternate, + /// Closes the dialog without acting. + Cancel, + /// Acts but keeps the dialog open (Apply). + Apply, +} + +impl ButtonRole { + /// Position from the left in the platform's order. Windows and Linux put the default action + /// first (OK Cancel Apply, Yes No Cancel); macOS puts it last, in the corner, with Cancel beside + /// it and the other answers further left (Don't Save, Cancel, Save). + fn slot(self, mac: bool) -> u8 { + match (self, mac) { + (Self::Default, false) | (Self::Alternate, true) => 0, + (Self::Alternate, false) | (Self::Cancel, true) => 1, + (Self::Cancel, false) | (Self::Apply, true) => 2, + (Self::Apply, false) | (Self::Default, true) => 3, + } + } +} + +/// One button of a [`dialog_buttons`] row. +#[derive(Clone, Copy)] +pub struct DialogButton<'a> { + pub role: ButtonRole, + pub label: &'a str, + pub min_width: f32, + pub enabled: bool, + /// Take keyboard focus this frame (see [`DialogButton::focus`]). + pub focus: bool, +} + +impl<'a> DialogButton<'a> { + pub fn new(role: ButtonRole, label: &'a str, min_width: f32) -> Self { + Self { role, label, min_width, enabled: true, focus: false } + } + + pub fn enabled(self, enabled: bool) -> Self { + Self { enabled, ..self } + } + + /// Asks for keyboard focus for this button: from there the arrow keys move between the row's + /// buttons and Enter or Space presses the focused one. + pub fn focus(self, focus: bool) -> Self { + Self { focus, ..self } + } +} + +/// A dialog's button row at the cursor, in the platform's order (see [`ButtonRole`]): every modal +/// draws its buttons through this, so they all agree. Inside a right-to-left row it sits at the +/// right edge. The buttons are laid out left to right, so Tab walks them in reading order. +/// Returns the role of the button clicked this frame. +pub fn dialog_buttons(ui: &mut Ui, buttons: &[DialogButton]) -> Option { + let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac; + let gap = ui.spacing().item_spacing.x; + let size = buttons.iter().fold(Vec2::ZERO, |acc, b| { + let s = button_size(ui, b.label, b.min_width); + vec2(acc.x + s.x, acc.y.max(s.y)) + }) + vec2(gap * buttons.len().saturating_sub(1) as f32, 0.0); + ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center), |ui| { + let mut hit = None; + for slot in 0..4 { + for b in buttons.iter().filter(|b| b.role.slot(mac) == slot) { + let r = ui + .add_enabled_ui(b.enabled, |ui| { + if b.role == ButtonRole::Default { primary_button(ui, b.label, b.min_width) } else { secondary_button(ui, b.label, b.min_width) } + }) + .inner; + if b.focus && b.enabled { + r.request_focus(); + } + if r.clicked() { + hit = Some(b.role); + } + } + } + hit + }) + .inner +} + +/// The size of a primary or secondary button: its label plus padding, at least `min_width` wide. +fn button_size(ui: &Ui, label: &str, min_width: f32) -> Vec2 { + button_layout(ui, label, min_width, None, Tokens::get(ui.ctx()).text).1 +} + +/// The height of a primary or secondary button (and so of a dialog's button row). +pub fn button_height(ctx: &egui::Context) -> f32 { + if Tokens::get(ctx).pro { 28.0 } else { 30.0 } +} + +fn button_layout(ui: &Ui, label: &str, min_width: f32, height: Option, fg: Color32) -> (std::sync::Arc, Vec2) { + let galley = ui.painter().layout_no_wrap(tl!(label).to_owned(), theme::medium(13.0), fg); + let h = height.unwrap_or(button_height(ui.ctx())); + let size = vec2((galley.size().x + 28.0).max(min_width), h); + (galley, size) +} + +fn button_impl(ui: &mut Ui, label: &str, min_width: f32, bg: Color32, fg: Color32, primary: bool) -> Response { + button_impl_h(ui, label, min_width, None, bg, fg, primary) +} + +/// [`button_impl`] with an explicit `height` (`None`: the theme's button height). +fn button_impl_h(ui: &mut Ui, label: &str, min_width: f32, height: Option, bg: Color32, fg: Color32, primary: bool) -> Response { + let t = Tokens::get(ui.ctx()); + let (galley, size) = button_layout(ui, label, min_width, height, fg); + let h = size.y; + let (rect, resp) = ui.allocate_exact_size(size, Sense::click()); + // Painted text: name the button for accessibility (and so tests and agents can find it). + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label)); + if resp.has_focus() { + // Keyboard focus (Tab); clicks don't focus egui buttons. + let r = if t.pro { h / 2.0 } else { t.radius_sm } + 2.0; + ui.painter().rect_stroke(rect.expand(2.0), r, Stroke::new(2.0, t.accent), StrokeKind::Outside); + } + if t.pro { + // Spectrum buttons: fully rounded; primary = filled accent, secondary = outline. + let down = resp.is_pointer_button_down_on(); + let r = h / 2.0; + if primary { + let fill = if down { + bg.gamma_multiply(0.8) + } else if resp.hovered() { + bg.gamma_multiply(0.9) + } else { + bg + }; + ui.painter().rect_filled(rect, r, fill); + } else { + if resp.hovered() || down { + ui.painter().rect_filled(rect, r, t.hover); + } + ui.painter().rect_stroke(rect, r, Stroke::new(1.5, if resp.hovered() { t.text } else { t.text_dim }), StrokeKind::Inside); + } + ui.painter().galley(rect.center() - galley.size() / 2.0, galley, fg); + return resp; + } + let fill = if resp.is_pointer_button_down_on() { + bg.gamma_multiply(0.85) + } else if resp.hovered() { + if primary { bg.gamma_multiply(0.93) } else { t.hover } + } else { + bg + }; + surface(ui, rect, fill, !resp.is_pointer_button_down_on()); + if !t.bevel && !primary { + ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); + } + ui.painter().galley(rect.center() - galley.size() / 2.0, galley, fg); + resp +} + +/// Spectrum-style checkbox (blue when checked). +pub fn checkbox(ui: &mut Ui, on: &mut bool, label: &str) -> Response { + let t = Tokens::get(ui.ctx()); + let (mut resp, label_resp) = ui + .horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + let (rect, resp) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::CLICK); + let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand); + let l = ui + .add(egui::Label::new(egui::RichText::new(tl!(label)).color(t.text_dim)).selectable(false).sense(Sense::click())) + .on_hover_cursor(egui::CursorIcon::PointingHand); + // Pressing the label presses the box (#4476). + let pressed = resp.is_pointer_button_down_on() || l.is_pointer_button_down_on(); + check_box(ui.painter(), rect, *on, resp.hovered() || l.hovered(), pressed, &t); + (resp.union(l.clone()), l) + }) + .inner; + if resp.clicked() { + *on = !*on; + resp.mark_changed(); + } + // The label is the single named, focusable checkbox; the box is a mouse target. + // Override Label's metadata instead of creating a second node with the same name. + label_resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, ui.is_enabled(), *on, tl!(label))); + resp +} + +/// The fill of a check box: the accent when `on`, else the field colour. While it's pressed +/// (the mouse is down on it or on its label) Photoshop shows that a release will act: an +/// unchecked box darkens a little and a checked one turns a little less opaque (#4476). +pub fn check_box_fill(on: bool, pressed: bool, t: &Tokens) -> Color32 { + match (on, pressed) { + (true, false) => t.accent, + (true, true) => t.accent.gamma_multiply(0.75), + (false, false) => t.field, + (false, true) => t.field.lerp_to_gamma(Color32::BLACK, 0.18), + } +} + +/// Paint a check box in `rect`: [`check_box_fill`] with a white tick when `on`, else an +/// outline that brightens while `hovered` or `pressed`. +pub fn check_box(p: &egui::Painter, rect: Rect, on: bool, hovered: bool, pressed: bool, t: &Tokens) { + p.rect_filled(rect, 2.0, check_box_fill(on, pressed, t)); + if on { + let a = rect.left_center() + vec2(3.0, 0.5); + let b = rect.center_bottom() + vec2(-1.0, -3.5); + let c = rect.right_top() + vec2(-3.0, 3.5); + let tick = Stroke::new(rect.width() * 0.125, Color32::WHITE); + p.line_segment([a, b], tick); + p.line_segment([b, c], tick); + } else { + p.rect_stroke(rect, 2.0, Stroke::new(1.5, if hovered || pressed { t.text_dim } else { t.text_faint }), StrokeKind::Inside); + } +} diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs new file mode 100644 index 0000000000..0c71e0746a --- /dev/null +++ b/crates/ui-egui/src/widgets/color.rs @@ -0,0 +1,193 @@ +use super::dropdown::swatch_popup; +use super::*; + +/// Cached RGB data; drawing work is bounded by the 256 display bins, never the image size. +pub fn rgb_histogram(ui: &mut Ui, histogram: &photocraft_algo::histogram::RgbHistogram, height: f32) -> egui::Response { + let t = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(egui::vec2(ui.available_width().max(1.0), height.max(1.0)), egui::Sense::hover()); + ui.painter().rect_filled(rect, t.radius_sm, t.histogram_background()); + let plot = rect.shrink(4.0); + crate::rgb_histogram::paint(ui.painter(), plot, histogram, &t); + ui.painter().rect_stroke(rect, t.radius_sm, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); + response +} + +/// The fully saturated colour at hue `deg` (degrees), built on sRGB values as Photoshop's hue +/// tracks are: 0 is (255,0,0), 60 is (255,255,0), 120 is (0,255,0) and so on (#6540). +pub fn hue_color(deg: f32) -> Color32 { + let [r, g, b] = photocraft_color::convert::hsb_to_rgb([deg, 1.0, 1.0]); + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + Color32::from_rgb(q(r), q(g), q(b)) +} + +/// Hue spectrum stops for colour sliders: red, yellow, green, cyan, blue, magenta, red. +pub fn hue_stops() -> Vec { + (0..=12).map(|i| hue_color(i as f32 * 30.0)).collect() +} + +/// Paint a small checkerboard (transparency) in `rect`. +pub fn checker(painter: &egui::Painter, rect: Rect, cell: f32) { + painter.rect_filled(rect, 0.0, Color32::from_gray(250)); + let nx = (rect.width() / cell).ceil() as i32; + let ny = (rect.height() / cell).ceil() as i32; + for j in 0..ny { + for i in 0..nx { + if (i + j) % 2 == 1 { + let r = Rect::from_min_size(Pos2::new(rect.left() + i as f32 * cell, rect.top() + j as f32 * cell), Vec2::splat(cell)).intersect(rect); + painter.rect_filled(r, 0.0, Color32::from_gray(214)); + } + } + } +} + +/// A transparency checkerboard of `cell`-point squares clipped to `rect` with `radius` corners, +/// for rounded swatches (#3208): [`checker`] paints square cells, which showed past a rounded +/// fill's corners. This one is a repeating two-by-two tile textured onto the rounded rect. +pub fn checker_rounded(painter: &egui::Painter, rect: Rect, cell: f32, radius: impl Into) { + let tile = checker_tile(painter.ctx()); + painter.add(egui::epaint::RectShape::filled(rect, radius, Color32::WHITE).with_texture(tile.id(), checker_uv(rect, cell))); +} + +/// The texture range that tiles `rect` with `cell`-point squares: the tile holds two cells a side. +pub(super) fn checker_uv(rect: Rect, cell: f32) -> Rect { + let cell = if cell.is_finite() && cell > 0.0 { cell } else { 4.0 }; + Rect::from_min_max(Pos2::ZERO, pos2(rect.width() / (2.0 * cell), rect.height() / (2.0 * cell))) +} + +pub(super) fn checker_tile_id() -> egui::Id { + egui::Id::unique("transparency-checker-tile") +} + +/// The checker's two-by-two tile (light, dark / dark, light), loaded once per context and shared +/// by every rounded checker; it repeats and never blurs. +fn checker_tile(ctx: &egui::Context) -> egui::TextureHandle { + if let Some(tile) = ctx.data(|d| d.get_temp::(checker_tile_id())) { + return tile; + } + let (light, dark) = (Color32::from_gray(250), Color32::from_gray(214)); + let image = egui::ColorImage::new([2, 2], vec![light, dark, dark, light]); + let options = egui::TextureOptions { + magnification: egui::TextureFilter::Nearest, + minification: egui::TextureFilter::Nearest, + wrap_mode: egui::TextureWrapMode::Repeat, + mipmap_mode: None, + }; + let tile = ctx.load_texture("transparency-checker-tile", image, options); + ctx.data_mut(|d| d.insert_temp(checker_tile_id(), tile.clone())); + tile +} + +/// A compact colour popup with the shared desktop eyedropper. Keep egui's colour cache so hue +/// survives black/white and alpha edits, and keep linear and encoded call sites distinct. +pub fn color_edit_button_srgba(ui: &mut Ui, color: &mut Color32) -> Response { + color_edit_button(ui, color, egui::color_picker::Alpha::BlendOrAdditive) +} + +pub(crate) fn color_swatch(ui: &mut Ui, color: Color32) -> Response { + let t = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(ui.spacing().interact_size, Sense::click()); + // A swatch's meaning is the colour it edits; callers with a more specific caption use + // `color_swatch_button` or add `labelled_by`. + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ColorWell, ui.is_enabled(), tl!("Color"))); + checker_rounded(ui.painter(), rect, 4.0, t.radius_sm); + ui.painter().rect_filled(rect.shrink(1.0), t.radius_sm, color); + ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); + response +} + +/// Where a press or drag on a picking surface (a colour field, a hue strip) points, from the +/// frame the button goes down and on every move after it. `dragged()` waits for egui's click +/// threshold (a few points of travel, or a long hold), so a press picked nothing until the +/// pointer had moved away and fine adjustments jumped (#7793). Only the primary button picks: +/// `is_pointer_button_down_on` is true for any button, so a right or middle press is ignored. +pub fn pick_pos(resp: &Response) -> Option { + let held = resp.is_pointer_button_down_on() + && resp.ctx.input(|i| i.pointer.primary_down() && !i.pointer.button_down(egui::PointerButton::Secondary) && !i.pointer.middle_down()); + if held || resp.clicked() { resp.interact_pointer_pos() } else { None } +} + +/// A colour swatch that only reports clicks (no popup): for colours edited in PhotoCraft's own +/// Color Picker dialog. `label` names it for hover text and accessibility. +pub fn color_swatch_button(ui: &mut Ui, color: Color32, label: &str) -> Response { + let t = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(ui.spacing().interact_size, Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ColorWell, true, label)); + checker_rounded(ui.painter(), rect, 4.0, t.radius_sm); + ui.painter().rect_filled(rect.shrink(1.0), t.radius_sm, color); + ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); + response.on_hover_text(label) +} + +fn color_edit_button(ui: &mut Ui, color: &mut Color32, alpha: egui::color_picker::Alpha) -> Response { + let mut response = color_swatch(ui, *color); + let id = response.id.with("screen-color"); + if let Some(rgb) = crate::screen_picker::take(ui.ctx(), id) { + *color = sampled_color(rgb, *color, alpha); + response.mark_changed(); + } + swatch_popup(&response).show(|ui| { + if egui::color_picker::color_picker_color32(ui, color, alpha) { + response.mark_changed(); + } + if let Some(rgb) = crate::screen_picker::button(ui, id) { + *color = sampled_color(rgb, *color, alpha); + response.mark_changed(); + } + }); + response +} + +fn sampled_color(rgb: [f32; 3], original: Color32, alpha: egui::color_picker::Alpha) -> Color32 { + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + if matches!(alpha, egui::color_picker::Alpha::BlendOrAdditive) && original.is_additive() { + return Color32::from_rgb_additive(byte(rgb[0]), byte(rgb[1]), byte(rgb[2])); + } + Color32::from_rgba_unmultiplied( + byte(rgb[0]), + byte(rgb[1]), + byte(rgb[2]), + if matches!(alpha, egui::color_picker::Alpha::Opaque) { 255 } else { original.a() }, + ) +} + +pub fn color_edit_button_srgb(ui: &mut Ui, rgb: &mut [u8; 3]) -> Response { + let mut color = Color32::from_rgb(rgb[0], rgb[1], rgb[2]); + let response = color_edit_button(ui, &mut color, egui::color_picker::Alpha::Opaque); + if response.changed() { + *rgb = [color.r(), color.g(), color.b()]; + } + response +} + +/// Like egui's float RGB widget, this entry point stores linear RGB (not encoded hex values). +pub fn color_edit_button_rgb(ui: &mut Ui, rgb: &mut [f32; 3]) -> Response { + let mut response = color_swatch(ui, Color32::from(egui::Rgba::from_rgb(rgb[0], rgb[1], rgb[2]))); + let id = response.id.with("screen-color"); + let to_linear = |color: [f32; 3]| color.map(egui::ecolor::linear_from_gamma); + if let Some(color) = crate::screen_picker::take(ui.ctx(), id) { + *rgb = to_linear(color); + response.mark_changed(); + } + let rgba = egui::Rgba::from_rgb(rgb[0], rgb[1], rgb[2]); + let cache = response.id.with("linear-hsva"); + let mut hsva = ui + .ctx() + .data(|d| d.get_temp::<(egui::Rgba, egui::ecolor::Hsva)>(cache)) + .filter(|(previous, _)| *previous == rgba) + .map(|(_, hsva)| hsva) + .unwrap_or_else(|| egui::ecolor::Hsva::from(rgba)); + swatch_popup(&response).show(|ui| { + if egui::color_picker::color_picker_hsva_2d(ui, &mut hsva, egui::color_picker::Alpha::Opaque) { + let color = egui::Rgba::from(hsva); + *rgb = [color.r(), color.g(), color.b()]; + response.mark_changed(); + } + if let Some(color) = crate::screen_picker::button(ui, id) { + *rgb = to_linear(color); + hsva = egui::ecolor::Hsva::from(egui::Rgba::from_rgb(rgb[0], rgb[1], rgb[2])); + response.mark_changed(); + } + }); + ui.ctx().data_mut(|d| d.insert_temp(cache, (egui::Rgba::from_rgb(rgb[0], rgb[1], rgb[2]), hsva))); + response +} diff --git a/crates/ui-egui/src/widgets/dropdown.rs b/crates/ui-egui/src/widgets/dropdown.rs new file mode 100644 index 0000000000..877e5f7c61 --- /dev/null +++ b/crates/ui-egui/src/widgets/dropdown.rs @@ -0,0 +1,296 @@ +use super::panel::chevron_icon; +use super::scrub::take_label_scrub_name; +use super::slider::wheel_notches_of; +use super::*; + +/// 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 { + dropdown_hovered(ui, id, name, current, options, width).0 +} + +/// [`dropdown`] whose option labels are shown exactly as given: names the user typed (a channel +/// or layer name) must not be translated, unlike the built-in labels [`dropdown`] translates (#5335). +pub fn dropdown_literal(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool { + let (chosen, _) = dropdown_with(ui, id, name, current, options, width, false, false); + !chosen.is_empty() +} + +/// [`dropdown`], also returning the option under the pointer in its open list (live previews). +pub fn dropdown_hovered(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> (bool, Option) { + let (chosen, hovered) = dropdown_with(ui, id, name, current, options, width, false, true); + (!chosen.is_empty(), hovered) +} + +/// [`dropdown_hovered`] whose value also steps with the wheel over its button or open list: down +/// picks the next option, up the previous one, one per notch (Shift too), stopping at the ends +/// (Photoshop's Layers panel blend modes, #1747). The wheel then scrolls neither the list, which +/// follows the value instead, nor what the dropdown is in. Returns every option chosen this frame +/// in order (one per notch; the last is `current`) and the option under the pointer in the open +/// list, none while the pointer rests where the wheel last stepped. +pub fn dropdown_wheel_hovered( + ui: &mut Ui, + id: &str, + name: &str, + current: &mut T, + options: &[(T, &str)], + width: f32, +) -> (Vec, Option) { + dropdown_with(ui, id, name, current, options, width, true, true) +} + +#[allow(clippy::too_many_arguments)] +fn dropdown_with( + ui: &mut Ui, + id: &str, + name: &str, + current: &mut T, + options: &[(T, &str)], + width: f32, + wheel: bool, + translate: bool, +) -> (Vec, Option) { + let shown = |l: &str| if translate { tl!(l).to_string() } else { l.to_string() }; + let label = options.iter().find(|(v, _)| v == current).map(|(_, l)| shown(l)).unwrap_or_else(|| "—".into()); + let (mut chosen, mut hovered) = (Vec::new(), None); + // The wheel's notches add up over the button and the open list alike. + let wheel_id = ui.make_persistent_id(id).with("wheel"); + let wheel = wheel && ui.is_enabled(); + let (mut over_list, mut wheeled, mut keyed) = (false, false, false); + // A wheel step scrolls the open list to the new value: at once over the list, the next frame + // after a step over the button. + let reveal_id = wheel_id.with("reveal"); + let mut reveal = wheel && ui.data_mut(|d| d.remove_temp::(reveal_id)).unwrap_or(false); + // 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 = + egui::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)) { + *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 ((v, _), text) in options.iter().zip(texts.iter()) { + 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()); + } + }); + // 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), + None => response.response.accessible_name(name), + }; + press.after(&response); + if combo_box_arrow_keys(ui, &response, current, options) { + chosen.push(current.clone()); + } + if wheel && !over_list { + let stepped = wheel_steps(ui, wheel_id, response.hovered(), current, options); + wheeled = !stepped.is_empty(); + if wheeled && egui::ComboBox::is_open(ui.ctx(), response.id) { + ui.data_mut(|d| d.insert_temp(reveal_id, true)); + } + chosen.extend(stepped); + } + // Nor is the option under a pointer resting where the keyboard picked another. + if wheel_rests(ui, wheel_id, wheeled || keyed) { + hovered = None; + } + (chosen, hovered) +} + +/// Makes an open dropdown list as wide as its widest option is when hovered, from the start. egui +/// takes a plain row's frame stroke off its padding but draws a hovered row with the stroke, so a +/// row grows by two stroke widths under the pointer, and the list never shrinks back: scrolling +/// the widest option under the pointer widened the list (#2607). +fn fit_widest_option<'a>(ui: &mut Ui, labels: impl Iterator) { + let extend = Some(egui::TextWrapMode::Extend); + let widest = labels.map(|l| egui::WidgetText::from(l).into_galley(ui, extend, f32::INFINITY, egui::FontSelection::Default).size().x).fold(0.0, f32::max); + ui.set_min_width(widest + 2.0 * ui.spacing().button_padding.x); +} + +/// Whether the pointer still rests where the wheel last stepped dropdown `id` (`wheeled`: it did +/// this frame). The option under it then isn't the one to preview: the value moved on without it. +fn wheel_rests(ui: &Ui, id: egui::Id, wheeled: bool) -> bool { + let key = id.with("at"); + let pointer = ui.input(|i| i.pointer.hover_pos()); + if wheeled && let Some(p) = pointer { + ui.data_mut(|d| d.insert_temp(key, p)); + } + let rests = pointer.is_some() && ui.data(|d| d.get_temp::(key)) == pointer; + if !rests { + ui.data_mut(|d| d.remove::(key)); + } + rests +} + +/// The options the wheel over dropdown `id` (while `hovered`) steps `current` through this frame, +/// one per notch, in order; the last is the new `current`. While the pointer is over it the wheel +/// scrolls nothing else. +fn wheel_steps(ui: &mut Ui, id: egui::Id, hovered: bool, current: &mut T, options: &[(T, &str)]) -> Vec { + if hovered { + ui.input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO); + } + let notches = wheel_notches_of(ui, id, hovered, 1.0); + let Some(mut index) = options.iter().position(|(v, _)| v == current) else { return Vec::new() }; + let mut chosen = Vec::new(); + // Down (negative) is the next option. No more steps than there are options. + for _ in 0..(notches.abs().min(options.len() as f32) as usize) { + let next = if notches < 0.0 { index.checked_add(1) } else { index.checked_sub(1) }; + let Some((next, (v, _))) = next.and_then(|i| options.get(i).map(|o| (i, o))) else { break }; + index = next; + chosen.push(v.clone()); + } + if let Some(v) = chosen.last() { + *current = v.clone(); + } + chosen +} + +/// Give a dropdown keyboard focus when it opens, then use the arrow keys to move through its +/// choices. `egui::ComboBox` opens a popup but leaves focus on the canvas by default, which makes +/// controls such as the Layers panel's Blend Mode dropdown unreachable from the keyboard. +fn combo_box_arrow_keys(ui: &mut Ui, response: &Response, current: &mut T, options: &[(T, &str)]) -> bool { + if response.clicked() { + response.request_focus(); + } + // The popup, rather than its button, becomes the focused egui layer after it opens. While it + // is open it owns its navigation keys, even though `response.has_focus()` is then false. + if !egui::ComboBox::is_open(ui.ctx(), response.id) || options.is_empty() { + return false; + } + let step = if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown)) { + 1 + } else if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp)) { + -1 + } else { + return false; + }; + let index = options.iter().position(|(value, _)| value == current).unwrap_or(0); + let next = if step > 0 { (index + 1).min(options.len() - 1) } else { index.saturating_sub(1) }; + match options.get(next) { + Some((value, _)) if next != index => { + *current = value.clone(); + true + } + _ => false, + } +} + +/// The body of a right-click menu: as tall as its items up to the part of the window that can be +/// seen (clear of a taskbar a too-tall window runs under, #315), scrolling past that, so long +/// context menus (a layer's, the canvas tools') stay reachable on small windows instead of running +/// off the bottom. egui moves a popup up to keep it in the window, so a menu opened low on the +/// screen first shifts up and only scrolls when it is taller than the window. +pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R { + // The popup frame's margin and stroke, and a small gap to the window's edges. + let frame = ui.spacing().menu_margin.sum().y + 2.0 + 2.0 * MENU_EDGE; + let room = (crate::work_area::visible_rect(ui.ctx()).height() - frame).max(MENU_MIN_HEIGHT); + // 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. + egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room).show(ui, add_contents).inner +} + +/// Gap kept between a context menu and the window's edges, and the shortest it gets. +const MENU_EDGE: f32 = 4.0; + +const MENU_MIN_HEIGHT: f32 = 120.0; + +/// The colour picker popup of a colour swatch: a click on `swatch` toggles it, a click outside +/// closes it. While open, its left edge stays where it first showed (at the swatch, or further +/// left when the window edge needs it), below the swatch or above it as room allows. The picker's +/// width follows its value readouts, and placing it anew every frame moved it under the pointer, +/// flipping it from side to side near the right edge of the window (#534). +pub fn swatch_popup(swatch: &Response) -> egui::Popup<'static> { + // Room for the readouts to widen after the picker opened. + const SLACK: f32 = 32.0; + let popup = egui::Popup::from_toggle_button_response(swatch).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + let ctx = &swatch.ctx; + let key = popup.get_id().with("left"); + if !popup.is_open() { + ctx.data_mut(|d| d.remove::(key)); + return popup; + } + crate::press_menu::above_parent(ctx, swatch.layer_id, egui::LayerId::new(egui::Order::Foreground, popup.get_id())); + // Its width is known from the frame after it opened (egui sizes it unseen first). + let left = ctx.data(|d| d.get_temp::(key)).or_else(|| { + let width = popup.get_expected_size()?.x; + let screen = ctx.content_rect(); + let left = swatch.rect.left().min(screen.right() - width - SLACK).max(screen.left()); + ctx.data_mut(|d| d.insert_temp(key, left)); + Some(left) + }); + let Some(left) = left else { return popup }; + popup + .anchor(Rect::from_x_y_ranges(left..=left, swatch.rect.y_range())) + .align(egui::RectAlign::BOTTOM_START) + .align_alternatives(&[egui::RectAlign::TOP_START]) +} + +pub fn dropdown_with_tooltips(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str, &str)], width: f32) -> bool { + 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 = + egui::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)) { + *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), + }; + press.after(&response); + if let Some((_, _, tip)) = options.iter().find(|(v, _, _)| v == current) { + response.on_hover_text(tl!(tip)); + } + changed +} diff --git a/crates/ui-egui/src/widgets/fields.rs b/crates/ui-egui/src/widgets/fields.rs new file mode 100644 index 0000000000..143320e330 --- /dev/null +++ b/crates/ui-egui/src/widgets/fields.rs @@ -0,0 +1,483 @@ +use super::panel::{chevron_icon, surface}; +use super::scrub::{label_scrub_response, take_label_scrub}; +use super::slider::slider; +use super::text_field::first_field_id; +use super::units::{FieldUnits, field_resolution_id, fmt_num, fmt_num_prec, fmt_num2, parse_num_in, plain, unit_of_suffix}; +use super::*; + +/// Monospace numeric field with a dimmed unit suffix, Photoshop style. Drag to scrub. Typed +/// arithmetic (`1920/2`) applies on Enter, Tab or click-away, and a unit after a number converts +/// into the field's unit (`1in` in a px field, at the resolution [`set_field_resolution`] gave). +pub fn value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, width: f32) -> Response { + value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts::default(), None).0 +} + +/// 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 { + value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts::default(), Some(name)).0 +} + +/// A single-line label for a row that also holds fixed-width controls: laid out no wider than +/// `max_w`, cut with '…' when the text (often a longer translation) does not fit, with the full +/// string on hover. Fixed chrome must never let a label overrun its row (#3580), so an *essential* +/// label beside a fixed control should use this rather than a show/hide fit check; a *redundant* +/// label (one whose control already carries the meaning, e.g. an icon row's caption) may be dropped. +pub fn elided_label_sensed(ui: &mut Ui, text: &str, max_w: f32, sense: Sense) -> Response { + let t = Tokens::get(ui.ctx()); + let font = egui::TextStyle::Body.resolve(ui.style()); + let galley = crate::tab_strip::elided(ui, text, font, t.text_dim, max_w); + let elided = galley.elided; + let (rect, resp) = ui.allocate_exact_size(galley.size(), sense); + ui.painter().galley(rect.min, galley, t.text_dim); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, ui.is_enabled(), text)); + if elided { resp.on_hover_text(text) } else { resp } +} + +/// [`elided_label_sensed`] with hover only (a plain, non-interactive label). +pub fn elided_label(ui: &mut Ui, text: &str, max_w: f32) -> Response { + elided_label_sensed(ui, text, max_w, Sense::hover()) +} + +/// Height of a [`value_field`]'s box. +pub const VALUE_FIELD_H: f32 = 24.0; + +/// A [`value_field`] `height` points tall instead of [`VALUE_FIELD_H`], for slim bars such as +/// the status bar (#2823). +pub fn compact_value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, width: f32, height: f32) -> Response { + value_field_box(ui, value, range, suffix, vec2(width, height), 0.0, FieldOpts::default(), None).0 +} + +/// A compact field whose mouse scrub wraps at the native fullscreen viewport's horizontal edges. +pub(crate) fn compact_wrapping_value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, size: Vec2) -> Response { + value_field_box(ui, value, range, suffix, size, 0.0, FieldOpts { wrap_drag: true, ..Default::default() }, None).0 +} + +/// How a [`value_field_in`] shows and reads its number, beyond its suffix. +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct FieldOpts { + /// Decimal places shown (default: one, or two for a small range). + pub(super) decimals: Option, + /// Arrow-key and scrub step follow `decimals` (adjustment rows via [`slider_row_prec`], #5914). + pub(super) step_from_decimals: bool, + /// The unit typed units convert into (default: the suffix's, at [`set_field_resolution`]). + pub(super) units: Option, + /// The length (px) 100 % stands for, so lengths and percentages convert into each other. + pub(super) extent: Option, + pub(super) wrap_drag: bool, +} + +/// Arrow-key and drag step for a value field: [`FieldOpts::step_from_decimals`] uses `decimals`; +/// otherwise the range width picks 0.01 (≤10) or 1.0. +fn field_step(range: &std::ops::RangeInclusive, decimals: Option, step_from_decimals: bool) -> f32 { + if step_from_decimals && let Some(d) = decimals { + return 10f32.powi(-(d.min(6) as i32)); + } + if *range.end() - *range.start() <= 10.0 { 0.01 } else { 1.0 } +} + +fn field_fine(range: &std::ops::RangeInclusive, decimals: Option, step_from_decimals: bool) -> bool { + if step_from_decimals { decimals.is_some_and(|d| d > 0) || *range.end() - *range.start() <= 10.0 } else { *range.end() - *range.start() <= 10.0 } +} + +/// A [`value_field`] that leaves `trailing` points free inside its box, right of the suffix, and +/// returns the box with the number's response. +// The explicit accessible name accompanies the existing numeric-field parameters. +#[expect(clippy::too_many_arguments)] +pub(super) fn value_field_in( + ui: &mut Ui, + value: &mut f32, + range: std::ops::RangeInclusive, + suffix: &str, + width: f32, + trailing: f32, + opts: FieldOpts, + name: Option<&str>, +) -> (Response, Rect) { + value_field_box(ui, value, range, suffix, vec2(width, VALUE_FIELD_H), trailing, opts, name) +} + +/// [`value_field_in`] with a box of any `size`. +// The explicit accessible name accompanies the existing numeric-field parameters. +#[expect(clippy::too_many_arguments)] +fn value_field_box( + ui: &mut Ui, + value: &mut f32, + range: std::ops::RangeInclusive, + suffix: &str, + size: Vec2, + trailing: f32, + opts: FieldOpts, + name: Option<&str>, +) -> (Response, Rect) { + let FieldOpts { decimals, step_from_decimals, units, extent, wrap_drag } = opts; + let t = Tokens::get(ui.ctx()); + let (rect, slot) = ui.allocate_exact_size(size, Sense::hover()); + let last_editor = ui.data(|d| d.get_temp::(slot.id)); + let mut option_click = false; + let scrub = take_label_scrub(ui, rect).map(|s| { + if !s.option_area { + return s; + } + // A direct click+drag target avoids egui snapping the padding/suffix to the nearby + // numeric button. It is not focusable; the editor drawn next wins inside its bounds. + // Preserve a popup field's trailing arrow, and never extend outside the UI clip. + let hit = Rect::from_min_max(pos2(s.rect.left(), rect.top()), pos2(rect.right() - trailing, rect.bottom())).intersect(ui.clip_rect()); + let mut resp = ui.interact(hit, s.label, Sense::CLICK | Sense::DRAG); + option_click = resp.clicked(); + if let Some(tip) = s.tip + && resp.hover_pos().is_some_and(|p| s.rect.contains(p)) + { + resp = resp.on_hover_text(tip); + } + label_scrub_response(ui, &resp, s.rect, s.max_gap, s.name) + }); + let (dpi, ppi) = ui.data(|d| d.get_temp::<(f64, f64)>(field_resolution_id())).unwrap_or((72.0, 72.0)); + // Typed text loses its spaces before parsing, so a " pt" suffix reads as "pt". + let typed_suffix = suffix.trim(); + let units = match units { + Some(u) => crate::numeric_expression::Units { unit: Some(u.unit), suffix: typed_suffix, dpi: u.dpi, ppi: u.ppi, extent }, + None => crate::numeric_expression::Units { unit: unit_of_suffix(typed_suffix), suffix: typed_suffix, dpi, ppi, extent }, + }; + surface(ui, rect, t.field, false); + if !t.bevel { + ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); + } + // The number's slot ends 1 pt left of the suffix, by its measured width (the suffix is drawn + // 6 pt from the right edge), so a one-character unit like `%` leaves the number room (#3040). + let suffix_font = theme::mono(11.0); + let suffix_w = if suffix.is_empty() { 0.0 } else { ui.painter().layout_no_wrap(suffix.to_owned(), suffix_font.clone(), t.text_faint).size().x + 3.0 }; + // Centred: the digits' ink then sits within 0.2 pt of the box's centre, where a 1 pt lift + // (#1322) put it 0.9 pt high and the focus outline off-centre (#5150). The slot is at least + // one text row tall, so a slim box's number isn't pushed out of it (#2823). + let font = theme::mono(12.0); + let row_h = ui.painter().layout_no_wrap("0".into(), font.clone(), t.text).size().y; + let slot_h = (rect.height() - 4.0).max(row_h).min(rect.height() - 2.0); + let cy = rect.center().y; + let field = Rect::from_min_max(pos2(rect.left() + 4.0, cy - slot_h / 2.0), pos2(rect.right() - 4.0 - suffix_w - trailing, cy + slot_h / 2.0)); + // Small ranges (gamma 0.01–9.99, 0–1 centres) need two decimals and a finer drag, like Photoshop. + let fine = field_fine(&range, decimals, step_from_decimals); + let unit = field_step(&range, decimals, step_from_decimals); + let (lo, hi) = (*range.start(), *range.end()); + // The field's id is only known once it's drawn: last frame's, saved under `slot` below. + let focused = ui.data(|d| d.get_temp::(slot.id)).filter(|id| ui.memory(|m| m.has_focus(*id))); + let (step, grid) = arrow_step(ui, slot.id, unit); + // The wheel steps it as the arrow keys do (#5473), focused or under the pointer. + let notches = crate::field_wheel::notches(ui, slot.id, focused.is_some(), rect); + if notches != 0.0 + && let Some(id) = focused + && ui.data(|d| d.get_temp(id.with("arithmetic"))).unwrap_or(false) + { + // A typed sum works itself out first, as before an arrow step. + ui.memory_mut(|m| m.surrender_focus(id)); + } + let step = step + notches * unit; + // new_child (not scope_builder): a scope would move the parent cursor back to the child rect. + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(field)); + let mut resp = { + let ui = &mut child; + { + ui.style_mut().visuals.widgets.inactive.bg_fill = Color32::TRANSPARENT; + ui.style_mut().visuals.widgets.inactive.weak_bg_fill = Color32::TRANSPARENT; + ui.style_mut().visuals.widgets.inactive.bg_stroke = Stroke::NONE; + ui.style_mut().visuals.widgets.hovered.bg_stroke = Stroke::NONE; + ui.style_mut().visuals.widgets.hovered.weak_bg_fill = Color32::TRANSPARENT; + ui.style_mut().override_font_id = Some(font); + // The theme's interact height (24) is taller than the number's slot: the DragValue + // would grow past the slot's bottom and sit low, or spill out of a slim box (#2823). + // Its horizontal padding would push a long number out of the box's left edge. + ui.spacing_mut().interact_size.y = field.height(); + ui.spacing_mut().button_padding = Vec2::ZERO; + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let layout = egui::Layout::centered_and_justified(ui.layout().main_dir()); + ui.allocate_ui_with_layout(field.size(), layout, |ui| number_edit(ui, value, range, fine, decimals, units, wrap_drag)).inner + }) + .inner + } + }; + ui.data_mut(|d| d.insert_temp(slot.id, resp.id)); + // A click on the caption's expanded hit area (outside the editor) is not an edit: keep the + // number's keyboard focus, but never take it for a field that did not have it. + if option_click + && let Some(id) = last_editor + && ui.memory(|m| m.had_focus_last_frame(id)) + { + ui.memory_mut(|m| m.request_focus(id)); + } + // A scrubby caption is also the field's visible label, so it names the number for screen readers. + if let Some(id) = scrub.as_ref().and_then(|s| s.name) { + resp = resp.labelled_by(id); + } else if let Some(name) = name { + // The caption drew in another Ui (or row), so it could not name the number itself. + resp = resp.accessible_name(name); + } + if let Some(s) = scrub { + if s.started && ui.memory(|m| m.has_focus(resp.id)) { + ui.memory_mut(|m| m.surrender_focus(resp.id)); + } + if s.steps != 0.0 { + // Onto the step grid first, so a whole-number field drops its decimals (55.4 + 1 = 56). + let v = ((*value / unit).round() + s.steps) * unit; + let v = (v * 1e4).round() / 1e4; + // `f32::clamp` panics on a reversed or NaN range, which `DragValue::range` accepts. + let v = if lo <= hi { v.clamp(lo, hi) } else { v }; + if v.is_finite() && v != *value { + *value = v; + resp.mark_changed(); + } + } + // Callers coalesce a drag into one history step; the label's drag is the field's. + use egui::response::Flags; + resp.flags.set(Flags::DRAG_STARTED, resp.flags.contains(Flags::DRAG_STARTED) || s.started); + resp.flags.set(Flags::DRAGGED, resp.flags.contains(Flags::DRAGGED) || s.dragging); + resp.flags.set(Flags::DRAG_STOPPED, resp.flags.contains(Flags::DRAG_STOPPED) || s.stopped); + } + if !suffix.is_empty() { + ui.painter().text(pos2(rect.right() - 6.0 - trailing, rect.center().y), Align2::RIGHT_CENTER, suffix, suffix_font, t.text_faint); + } + if step != 0.0 { + // Round to the step before adding it, so whole-number fields drop decimals (55.4 + 1 = 56). + let v = (*value / grid).round() * grid + step; + // Round to 4 decimal places, so repeated 0.1 steps don't leave float errors. + let v = (v * 1e4).round() / 1e4; + // `f32::clamp` panics on a reversed or NaN range, which `DragValue::range` accepts. + let v = if lo <= hi { v.clamp(lo, hi) } else { v }; + // A wild wheel delta must not leave infinity in the field. + if v.is_finite() { + *value = v; + } + // A wheel step over a field without focus leaves the focus where it is. + if focused.is_some() { + // Only take focus back after a typed sum gave it up: re-requesting it while held resets + // the field's arrow-key filter next frame, and a held arrow then moves focus away (#5474). + if !ui.memory(|m| m.has_focus(resp.id)) { + ui.memory_mut(|m| m.request_focus(resp.id)); + } + // The text stays selected, as in Photoshop: typing after a step replaces the value. + crate::field_tab::select_all(ui.ctx(), resp.id, &if fine { fmt_num2(f64::from(*value)) } else { fmt_num(f64::from(*value)) }); + } + resp.mark_changed(); + } + if ui.memory(|m| m.has_focus(resp.id)) { + crate::field_wheel::set_focused(ui.ctx(), resp.id, slot.id); + } + (resp, rect) +} + +/// Width of the ▾ that opens a [`popup_value_field`]'s slider, inside the field's box. +pub const POPUP_ARROW_W: f32 = 14.0; + +/// Width of a [`popup_value_field`]'s pop-up slider. +const POPUP_SLIDER_W: f32 = 160.0; + +/// What a [`popup_value_field`] did this frame. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct PopupFieldResponse { + /// The value changed (typed, scrubbed, stepped with the arrow keys, or set on the slider). + pub changed: bool, + /// While the value is dragged (on the slider, from the ▾, or scrubbing the number): a number + /// for that drag, the same on every frame of it, for the caller to coalesce the drag's edits + /// into one history step. + pub drag: Option, +} + +/// A [`value_field`] with Photoshop's pop-up slider (the Layers panel's Opacity and Fill): a click +/// on the ▾ inside the field's right edge opens a slider below it, a click outside closes it. +/// Pressing the ▾ and dragging moves the value straight away, as far as the slider would, and +/// closes the slider on release. The number can still be typed, scrubbed and stepped like any +/// value field. `name` (already translated) names the ▾ for its tooltip and for accessibility. +pub fn popup_value_field(ui: &mut Ui, name: &str, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, width: f32) -> PopupFieldResponse { + let t = Tokens::get(ui.ctx()); + let (lo, hi) = (*range.start(), *range.end()); + let (mut field, rect) = value_field_in(ui, value, range.clone(), suffix, width, POPUP_ARROW_W, FieldOpts::default(), None); + let arrow = Rect::from_min_max(pos2(rect.right() - POPUP_ARROW_W - 2.0, rect.top() + 2.0), rect.max - vec2(2.0, 2.0)); + let resp = ui.interact(arrow, field.id.with("popup-slider"), Sense::click_and_drag()); + let name = name.trim_end_matches([':', ':']).to_string(); + // Both the number and its ▾ are named by the control's own semantic name. + field = field.accessible_name(name.clone()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &name)); + let resp = resp.on_hover_text(&name); + let drag_key = resp.id.with("drag"); + // Every drag gets a new number when it starts, even if its first frame changes nothing. + let gesture = |ui: &Ui, started: bool| { + if started { + let n = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|d| d.insert_temp(drag_key, n)); + } + ui.data(|d| d.get_temp::(drag_key)) + }; + let mut out = PopupFieldResponse { changed: field.changed(), drag: None }; + let scrub = gesture(ui, field.drag_started()); + if field.changed() && field.dragged() { + out.drag = scrub; + } + + let popup_id = egui::Popup::default_response_id(&resp); + let start_key = resp.id.with("start"); + if resp.drag_started() { + egui::Popup::open_id(ui.ctx(), popup_id); + ui.data_mut(|d| d.insert_temp(start_key, *value)); + gesture(ui, true); + } + if resp.dragged() + && let (Some(start), Some(origin), Some(pos)) = + (ui.data(|d| d.get_temp::(start_key)), ui.input(|i| i.pointer.press_origin()), resp.interact_pointer_pos()) + { + // The pointer moves the value as much as it would move the slider's knob. + let track = POPUP_SLIDER_W - 14.0; + let v = start + (pos.x - origin.x) / track * (hi - lo); + let v = if lo <= hi && v.is_finite() { v.clamp(lo, hi) } else { start }; + if v != *value { + *value = v; + out.changed = true; + } + out.drag = gesture(ui, false); + } + if resp.drag_stopped() { + egui::Popup::close_id(ui.ctx(), popup_id); + } + + let popup = egui::Popup::from_toggle_button_response(&resp) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .anchor(rect) + .align(egui::RectAlign::BOTTOM_END) + .align_alternatives(&[egui::RectAlign::TOP_END]); + let open = popup.is_open(); + if resp.hovered() || resp.dragged() || open { + ui.painter().rect_filled(arrow, t.radius_sm, t.field_border.gamma_multiply(0.6)); + } + chevron_icon(ui, arrow, 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_width(POPUP_SLIDER_W); + let s = slider(ui, value, range, None); + s.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(*value), &name)); + let key = gesture(ui, s.drag_started()); + if s.changed() { + out.changed = true; + // A click on the track is one edit of its own; a drag is one edit however long. + if s.dragged() { + out.drag = key; + } + } + }); + out +} + +pub(super) const NUMERIC_INPUT_LIMIT: usize = 128; + +/// The number in a [`value_field`]. A typed number applies as it's typed; arithmetic waits for +/// Enter, Tab or click-away, because per keystroke `5/2` would land first and a caller that +/// rounds it would cut `5/2*2` short. `changed()` means a new value, not just a keystroke. +fn number_edit( + ui: &mut Ui, + value: &mut f32, + range: std::ops::RangeInclusive, + fine: bool, + decimals: Option, + units: crate::numeric_expression::Units, + wrap_drag: bool, +) -> Response { + let (id, ctx) = (ui.next_auto_id(), ui.ctx().clone()); + // Focused before the DragValue is drawn, so it gains focus this frame and selects its text. + if ui.data_mut(|d| d.remove_temp::(first_field_id())).unwrap_or(false) { + ui.memory_mut(|m| m.request_focus(id)); + } + // Tab in a dialog goes from one of these to the next (field_tab.rs). + if ui.is_enabled() { + crate::field_tab::register(&ctx, id); + } + // Use DragValue's focus check before it builds its TextEdit: oversized events must never + // reach text layout. Registering interest also handles focus arriving by Tab this frame. + let editing = ui.is_enabled() + && ui.memory_mut(|m| { + m.interested_in_focus(id, ui.layer_id()); + m.has_focus(id) + }); + if editing { + ui.input_mut(|input| { + input.events.retain(|event| { + let text = match event { + egui::Event::Text(text) | egui::Event::Paste(text) | egui::Event::Ime(egui::ImeEvent::Commit(text)) => text, + egui::Event::Ime(egui::ImeEvent::Preedit { text, .. }) => text, + _ => return true, + }; + text.chars().nth(NUMERIC_INPUT_LIMIT).is_none() + }); + }); + } + let held = id.with("arithmetic"); + let math = ui.memory(|m| m.has_focus(id)) && ui.data(|d| d.get_temp(held)).unwrap_or(false); + ui.data_mut(|d| d.insert_temp(held, math)); + let before = *value; + let speed = if fine { 0.01 } else { 0.5 }; + let wrapping = wrap_drag && crate::scrub_wrap::active(ui); + let wrapped_drag = wrapping && ui.input(|i| i.pointer.primary_down()); + let mut resp = ui.add( + egui::DragValue::new(value) + .range(range.clone()) + // Only edits are clamped (below): showing a value past the range, such as a type layer + // scaled to 2400 pt in a 1296 pt field, must not change it (#5717). + .clamp_existing_to_range(false) + // A warp is an absolute-position jump. The scoped scrub below removes that jump. + .speed(if wrapped_drag { 0.0 } else { speed }) + .custom_formatter(move |v, _| match decimals { + Some(d) => fmt_num_prec(v, d), + None if fine => fmt_num2(v), + None => fmt_num(v), + }) + .update_while_editing(!math) + // Focus is read when parsing, not above: Tab hands it on inside `ui.add`. + .custom_parser(move |s| { + // Short events can accumulate: reject before either parser normalizes the text. + if s.chars().nth(NUMERIC_INPUT_LIMIT).is_some() { + return None; + } + let v = parse_num_in(s, units); + if ctx.memory(|m| m.has_focus(id)) && plain(s).is_none() { + // Still typing arithmetic: hold it, and stop applying keystrokes once it parses. + ctx.data_mut(|d| d.insert_temp(held, v.is_some())); + return None; + } + v + }), + ); + if wrap_drag { + crate::scrub_wrap::update(ui, &resp, value, before, range.clone(), speed, wrapping); + } + let (lo, hi) = (*range.start(), *range.end()); + // `f32::clamp` panics on a reversed or NaN range, which `DragValue::range` accepts. + if *value != before && lo <= hi { + *value = value.clamp(lo, hi); + } + resp.flags.set(egui::response::Flags::CHANGED, *value != before); + resp +} + +/// Increments a numerical field with the up/down arrow keys. Increments by 1 by default, 10 with shift, and 0.1 with ctrl/cmd. +/// Returns the amount to add, and what to round the value to first. +fn arrow_step(ui: &mut Ui, slot: egui::Id, step: f32) -> (f32, f32) { + use egui::{Key, Modifiers}; + // The field's id is only known once it's drawn, so `value_field` saves it under `slot` for the next frame. + let Some(id) = ui.data(|d| d.get_temp::(slot)).filter(|id| ui.memory(|m| m.has_focus(*id))) else { + return (0.0, step); + }; + let (n, grid) = ui.input_mut(|i| { + let (mut n, mut grid) = (0.0, step); + // egui ignores an extra shift when matching, so shift is checked before the plain arrows to get its larger step. + for (mods, k) in [(Modifiers::COMMAND, (step / 10.0).max(0.01)), (Modifiers::SHIFT, 10.0 * step), (Modifiers::NONE, step)] { + let presses = i.count_and_consume_key(mods, Key::ArrowUp) as f32 - i.count_and_consume_key(mods, Key::ArrowDown) as f32; + if presses != 0.0 && mods == Modifiers::COMMAND { + grid = k; + } + n += k * presses; + } + (n, grid) + }); + // If a sum like 5+5 has been typed, unfocus the field so it calculates it (as Enter would) before we step. + if n != 0.0 && ui.data(|d| d.get_temp(id.with("arithmetic"))).unwrap_or(false) { + ui.memory_mut(|m| m.surrender_focus(id)); + } + (n, grid) +} diff --git a/crates/ui-egui/src/widgets/panel.rs b/crates/ui-egui/src/widgets/panel.rs new file mode 100644 index 0000000000..43c52b1cf4 --- /dev/null +++ b/crates/ui-egui/src/widgets/panel.rs @@ -0,0 +1,152 @@ +use super::*; + +/// Match the Spectrum application-menu padding and blue/white hover state in +/// secondary menus (status bar, dock hamburger, layer context menus; #2187). +/// The setting is local to this popup's Ui and leaves other themes unchanged. +pub fn style_spectrum_popup_menu(ui: &mut Ui) { + let t = Tokens::get(ui.ctx()); + // The 6 pt gap between rows was outside both buttons, so a drag across a menu + // dropped the highlight (#4602). Padding stays inside the row, which is the hit target. + ui.spacing_mut().item_spacing.y = 0.0; + if !t.pro { + return; + } + ui.spacing_mut().button_padding = vec2(10.0, 4.0); + let v = &mut ui.style_mut().visuals; + v.widgets.hovered.weak_bg_fill = t.accent; + v.widgets.hovered.bg_fill = t.accent; + v.widgets.hovered.fg_stroke = Stroke::new(1.0, Color32::WHITE); + v.widgets.hovered.bg_stroke = Stroke::NONE; + v.widgets.inactive.corner_radius = CornerRadius::ZERO; + v.widgets.hovered.corner_radius = CornerRadius::ZERO; + v.widgets.active.corner_radius = CornerRadius::ZERO; +} + +/// An accent insertion line on one edge of `r` while a drag hovers it (vertical: on its left or, +/// `after`, right edge; else on its top or bottom). +pub fn drop_line(ui: &Ui, r: Rect, after: bool, vertical: bool, t: &Tokens) { + let s = Stroke::new(2.0, t.accent); + if vertical { + let x = if after { r.right() } else { r.left() }; + ui.painter().line_segment([pos2(x, r.top() + 2.0), pos2(x, r.bottom() - 2.0)], s); + } else { + let y = if after { r.bottom() } else { r.top() }; + ui.painter().line_segment([pos2(r.left() + 4.0, y), pos2(r.right() - 4.0, y)], s); + } +} + +/// Draw a bevelled box (Classic theme) or a flat rounded box. +pub fn surface(ui: &Ui, rect: Rect, fill: Color32, raised: bool) { + let t = Tokens::get(ui.ctx()); + let p = ui.painter(); + p.rect_filled(rect, t.radius_sm, fill); + if t.bevel { + let (hi, lo) = if raised { (Color32::WHITE, Color32::from_gray(64)) } else { (Color32::from_gray(64), Color32::WHITE) }; + p.line_segment([rect.left_bottom(), rect.left_top()], Stroke::new(1.0, hi)); + p.line_segment([rect.left_top(), rect.right_top()], Stroke::new(1.0, hi)); + p.line_segment([rect.right_top(), rect.right_bottom()], Stroke::new(1.0, lo)); + p.line_segment([rect.right_bottom(), rect.left_bottom()], Stroke::new(1.0, lo)); + } +} + +/// Inner margin of a dock panel's body: a Pro panel's, or a Studio card's below its tab strip. +pub(crate) fn body_margin(pro: bool) -> egui::Margin { + if pro { egui::Margin::same(8) } else { egui::Margin { left: 8, right: 8, top: 6, bottom: 10 } } +} + +/// Height of a panel footer's bar ([`panel_footer`]), under its 1 px line. +pub const FOOTER_BAR: f32 = 30.0; + +/// The height a [`panel_footer`] takes from the panel body: its line, and its bar down to the +/// body's bottom margin (the bar runs on over the margin). +pub fn footer_height(ui: &Ui) -> f32 { + 1.0 + FOOTER_BAR - body_margin(Tokens::get(ui.ctx()).pro).bottom as f32 +} + +/// A panel footer as in Photoshop's Layers and History panels: a bar of buttons under a line that +/// runs from edge to edge of the panel, the buttons centred in the bar's height and laid out from +/// the right. Drawn last in a body that fills its group (leave it [`footer_height`]), the bar ends +/// at the panel's bottom edge. +pub fn panel_footer(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { + let t = Tokens::get(ui.ctx()); + let m = body_margin(t.pro); + let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), footer_height(ui)), Sense::hover()); + let y = r.top() + 0.5; + ui.painter().line_segment([pos2(r.left() - m.left as f32, y), pos2(r.right() + m.right as f32, y)], Stroke::new(1.0, t.separator)); + let bar = Rect::from_min_size(pos2(r.left(), r.top() + 1.0), vec2(r.width(), FOOTER_BAR)); + let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center))); + // The bar runs on over the body's bottom margin, past where the body's own clip ends: without + // this its buttons were cut off there, a 26 px hover highlight drawn about 21 px tall. + bar_ui.set_clip_rect(bar_ui.clip_rect().union(bar)); + bar_ui.spacing_mut().item_spacing.x = 2.0; + add(&mut bar_ui) +} + +/// The panel menu button (hamburger in Pro, ellipsis in Studio), matching the dock and cards. +pub fn panel_menu_button(ui: &mut Ui) -> Response { + let t = Tokens::get(ui.ctx()); + let size = vec2(20.0, 20.0); + let (rect, resp) = ui.allocate_exact_size(size, Sense::click()); + let tint = crate::icons::button_chrome(ui, rect, false, resp.hovered()); + if t.pro { + for k in 0..3 { + let y = rect.center().y - 3.5 + k as f32 * 3.5; + ui.painter().line_segment([pos2(rect.center().x - 5.0, y), pos2(rect.center().x + 5.0, y)], Stroke::new(1.0, tint)); + } + } else { + crate::icons::paint(ui, rect, "ellipsis", 14.0, tint); + } + let tip = tl!("Panel menu"); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); + resp.on_hover_text(tip) +} + +pub fn pill_tab(ui: &mut Ui, label: &str, selected: bool) -> Response { + let t = Tokens::get(ui.ctx()); + let translated = tl!(label); + let font = theme::medium(12.5); + let galley = ui.painter().layout_no_wrap(translated.to_string(), font, t.text); + let size = vec2(galley.size().x + 20.0, 24.0); + let (rect, resp) = ui.allocate_exact_size(size, Sense::click()); + if selected { + surface(ui, rect, t.hover, true); + if !t.bevel { + ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); + } + } else if resp.hovered() { + ui.painter().rect_filled(rect, t.radius_sm, t.hover.gamma_multiply(0.6)); + } + let color = if selected { t.text } else { t.text_dim }; + ui.painter().galley_with_override_text_color(rect.center() - galley.size() / 2.0, galley, color); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, translated)); + resp +} + +/// Small caps section label. +pub fn section_label(ui: &mut Ui, text: &str) { + let t = Tokens::get(ui.ctx()); + ui.label(egui::RichText::new(tl!(text)).font(theme::medium(11.5)).color(t.text_faint)); +} + +/// Hairline separator. +pub fn hairline(ui: &mut Ui) { + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 1.0), Sense::hover()); + ui.painter().line_segment([r.left_center(), r.right_center()], Stroke::new(1.0, t.separator)); +} + +/// Vertical hairline for horizontal layouts. +pub fn vline(ui: &mut Ui, height: f32) { + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(9.0, height), Sense::hover()); + ui.painter().line_segment([r.center_top(), r.center_bottom()], Stroke::new(1.0, t.separator)); +} + +/// Small chevron for dropdowns (replaces egui's filled triangle). +pub fn chevron_icon(ui: &Ui, rect: Rect, visuals: &egui::style::WidgetVisuals, _open: bool) { + let c = rect.center(); + let s = 3.2; + let stroke = Stroke::new(1.3, visuals.fg_stroke.color.gamma_multiply(0.8)); + ui.painter().line_segment([c + vec2(-s, -s * 0.5), c + vec2(0.0, s * 0.5)], stroke); + ui.painter().line_segment([c + vec2(0.0, s * 0.5), c + vec2(s, -s * 0.5)], stroke); +} diff --git a/crates/ui-egui/src/widgets/scrub.rs b/crates/ui-egui/src/widgets/scrub.rs new file mode 100644 index 0000000000..45056106bb --- /dev/null +++ b/crates/ui-egui/src/widgets/scrub.rs @@ -0,0 +1,153 @@ +use super::*; + +/// A drag on a value field's label this frame, for the value field drawn next on the label's row +/// (Photoshop's scrubby labels). Left by [`scrub_label`], taken by that field. +#[derive(Clone, Copy, Debug)] +pub(super) struct LabelScrub { + pass: u64, + /// The id whose drags move the field (the label itself, or an options caption's hit area). + pub(super) label: egui::Id, + /// The visible label's own id, which names the field it scrubs. + pub(super) name: Option, + pub(super) rect: Rect, + /// How far right of the label the field may start (the whole row for a slider row). + pub(super) max_gap: f32, + /// Options captions defer interaction until the adjacent field bounds are known. + pub(super) option_area: bool, + /// An options icon's tooltip, shown by the drag area laid over it (which takes its hover). + pub(super) tip: Option<&'static str>, + /// Whole steps to move the value (left negative; Shift ×10, Alt a tenth as fast). + pub(super) steps: f32, + pub(super) started: bool, + pub(super) dragging: bool, + pub(super) stopped: bool, +} + +fn label_scrub_id() -> egui::Id { + egui::Id::unique("pc-label-scrub") +} + +/// Makes `label` scrubby: dragging it left or right moves the value field drawn right after it on +/// the same row (one step a point, ×10 with Shift, a tenth as fast with Alt), with Photoshop's +/// scrubby cursor. A label with no value field right after it stays a plain label. +pub fn scrub_label(ui: &Ui, label: &Response) -> Response { + scrub_label_within(ui, label, 24.0) +} + +/// A tool-options caption whose scrub target includes the adjacent field's outer box. +/// Keep the original label bounds for linking; register the hit area before the numeric editor. +pub fn scrub_option_label(ui: &Ui, label: &Response) { + scrub_option_area(ui, label, None); +} + +/// [`scrub_option_label`] for an icon with tooltip `tip`. The field's drag area is laid over the +/// icon after it, so egui hovers the area and not the icon: `on_hover_text` on the icon never shows. +pub fn scrub_option_icon(ui: &Ui, icon: &Response, tip: &'static str) { + scrub_option_area(ui, icon, Some(tip)); +} + +fn scrub_option_area(ui: &Ui, label: &Response, tip: Option<&'static str>) { + let scrub = LabelScrub { + pass: ui.ctx().cumulative_pass_nr(), + label: label.id.with("pc-option-scrub"), + name: Some(label.id), + rect: label.rect, + max_gap: 24.0, + option_area: true, + tip, + steps: 0.0, + started: false, + dragging: false, + stopped: false, + }; + 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 { + // 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)); + ui.data_mut(|d| { + d.insert_temp(label_scrub_id(), scrub); + d.insert_temp(resp.id.with("pc-scrub-linked"), false); + }); + resp +} + +pub(super) fn label_scrub_response(ui: &Ui, resp: &Response, original_rect: Rect, max_gap: f32, name: Option) -> LabelScrub { + // Whether a field took this label's drags last frame: only then is it scrubby. + let linked = ui.data(|d| d.get_temp::(resp.id.with("pc-scrub-linked"))).unwrap_or(false); + if linked && resp.enabled() && (resp.hovered() || resp.dragged()) { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); + } + let acc_id = resp.id.with("pc-scrub-acc"); + let mut steps = 0.0; + if resp.dragged() || resp.drag_stopped() { + let mut acc: f32 = if resp.drag_started() { 0.0 } else { ui.data(|d| d.get_temp(acc_id)).unwrap_or(0.0) }; + let mods = ui.input(|i| i.modifiers); + let rate = if mods.shift { + 10.0 + } else if mods.alt { + 0.1 + } else { + 1.0 + }; + // The drag starts once the pointer has moved a few points: count those too. + let dx = match (resp.drag_started(), ui.input(|i| i.pointer.press_origin()), resp.interact_pointer_pos()) { + (true, Some(origin), Some(pos)) => pos.x - origin.x, + _ => resp.drag_delta().x, + }; + acc += dx * rate; + if !acc.is_finite() { + acc = 0.0; + } + steps = acc.trunc(); + ui.data_mut(|d| d.insert_temp(acc_id, acc - steps)); + } + LabelScrub { + pass: ui.ctx().cumulative_pass_nr(), + label: resp.id, + name, + rect: original_rect, + max_gap, + option_area: false, + tip: None, + steps, + started: resp.drag_started(), + dragging: resp.dragged(), + stopped: resp.drag_stopped(), + } +} + +/// The label drag left for the field at `rect` this frame, if its label is just left of it on +/// its row. Taken either way: a label only scrubs the next field drawn. +pub(super) fn take_label_scrub(ui: &Ui, rect: Rect) -> Option { + let s = ui.data_mut(|d| { + let s = d.get_temp::(label_scrub_id()); + d.remove::(label_scrub_id()); + s + })?; + let same_row = rect.top() < s.rect.bottom() && rect.bottom() > s.rect.top(); + let gap = rect.left() - s.rect.right(); + let linked = s.pass == ui.ctx().cumulative_pass_nr() && same_row && gap >= -1.0 && gap <= s.max_gap; + if linked { + ui.data_mut(|d| d.insert_temp(s.label.with("pc-scrub-linked"), true)); + } + linked.then_some(s) +} + +/// The visible caption left for the control drawn next this frame, if any, consumed so that a +/// non-scrubbing control (a dropdown) can still take its name and the caption cannot leak on. +pub(super) fn take_label_scrub_name(ui: &Ui, rect: Rect) -> Option { + let s = ui.data_mut(|d| { + let s = d.get_temp::(label_scrub_id()); + d.remove::(label_scrub_id()); + s + })?; + if s.pass != ui.ctx().cumulative_pass_nr() { + return None; + } + // Only a caption on the control's own row names it; one left over from an earlier row does not. + let same_row = rect.top() < s.rect.bottom() && rect.bottom() > s.rect.top(); + same_row.then_some(s.name).flatten() +} diff --git a/crates/ui-egui/src/widgets/slider.rs b/crates/ui-egui/src/widgets/slider.rs new file mode 100644 index 0000000000..49363da87e --- /dev/null +++ b/crates/ui-egui/src/widgets/slider.rs @@ -0,0 +1,289 @@ +use super::fields::{FieldOpts, value_field_in}; +use super::panel::surface; +use super::scrub::scrub_label_within; +use super::*; + +/// Thin-track slider with a round knob. `gradient` paints the track (e.g. hue spectrum). +pub fn slider(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, gradient: Option<&[Color32]>) -> Response { + slider_with(ui, value, range, gradient, RowGestures::default()) +} + +/// Photoshop's gestures on a slider row beyond click and drag, as measured on Color Balance in +/// Photoshop 25.4 (Image › Adjustments dialog and the adjustment layer's Properties). Shift, Ctrl +/// and Alt change nothing about clicks, double-clicks or drags; the wheel takes ten steps with +/// Shift. (Up/Down in the field are every value field's, see [`value_field`].) +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct RowGestures { + /// A double-click on the slider (knob or track; not the label or field) sets this value. + pub reset: Option, + /// Each wheel notch over the slider moves the value by this step (up = higher; ×10 with + /// Shift). Photoshop does this in dialogs, not in the Properties panel. + pub wheel_step: Option, + /// A curved track: the knob at fraction f of the track is `lo + (hi - lo) * f^k`, so small + /// values get fine steps (Photoshop's mask Feather, #6545). Typed, scrubbed and stepped + /// values stay linear; only the track maps through the curve. + pub curve: Option, +} + +/// The value at fraction `f` of a track over `lo..=hi`, through `curve` (see [`RowGestures`]). +pub(crate) fn curve_value(f: f32, lo: f32, hi: f32, curve: Option) -> f32 { + match curve { + Some(k) if k.is_finite() && k > 0.0 => lo + f.clamp(0.0, 1.0).powf(k) * (hi - lo), + _ => lo + f * (hi - lo), + } +} + +/// Where `v` sits on a track over `lo..=hi`, as a fraction: the inverse of [`curve_value`]. +pub(crate) fn curve_fraction(v: f32, lo: f32, hi: f32, curve: Option) -> f32 { + let f = ((v - lo) / (hi - lo)).clamp(0.0, 1.0); + match curve { + // An unset (NaN) value draws the knob at the start rather than nowhere. + Some(k) if k.is_finite() && k > 0.0 => { + if f.is_finite() { + f.powf(1.0 / k) + } else { + 0.0 + } + } + _ => f, + } +} + +/// Wheel notches this frame while the pointer is over `resp` (Shift ×10). Wheel lines add up in +/// egui memory until they make whole notches (high-resolution wheels report fractions of one); +/// smooth (point) deltas count `line_scroll_speed` points per notch, like the canvas wheel. +fn wheel_notches(ui: &Ui, resp: &Response) -> f32 { + wheel_notches_of(ui, resp.id, resp.hovered(), 10.0) +} + +/// [`wheel_notches`] of widget `id` while `hovered`, a notch with Shift counting `shift_notches`. +pub(crate) fn wheel_notches_of(ui: &Ui, id: egui::Id, hovered: bool, shift_notches: f32) -> f32 { + if !hovered { + return 0.0; + } + let wheel: Vec<(egui::MouseWheelUnit, Vec2, bool)> = ui.input(|i| { + i.events + .iter() + .filter_map(|e| match e { + egui::Event::MouseWheel { unit, delta, modifiers, .. } => Some((*unit, *delta, modifiers.shift)), + _ => None, + }) + .collect() + }); + count_notches(ui, id.with("wheel-acc"), &wheel, shift_notches) +} + +/// Whole notches in `wheel` (unit, delta, Shift held), a notch with Shift counting +/// `shift_notches`; fractions carry over in egui memory under `acc_id`. +pub(crate) fn count_notches(ui: &Ui, acc_id: egui::Id, wheel: &[(egui::MouseWheelUnit, Vec2, bool)], shift_notches: f32) -> f32 { + let mut acc: f32 = ui.data(|d| d.get_temp(acc_id)).unwrap_or(0.0); + let per_line = ui.ctx().options(|o| o.input_options.line_scroll_speed); + let per_line = if per_line.is_finite() && per_line > 0.0 { per_line } else { 40.0 }; + let mut notches = 0.0; + for &(unit, delta, shift) in wheel { + // Some systems turn Shift+wheel into a horizontal scroll. + let d = if delta.y != 0.0 { delta.y } else { delta.x }; + acc += match unit { + egui::MouseWheelUnit::Point => d / per_line, + _ => d, + }; + let whole = acc.trunc(); + acc -= whole; + notches += if shift { whole * shift_notches } else { whole }; + } + if !acc.is_finite() { + acc = 0.0; + } + ui.data_mut(|d| d.insert_temp(acc_id, acc)); + if notches.is_finite() { notches } else { 0.0 } +} + +/// Windows' default double-click time (Photoshop's; egui's own default is 0.3 s). +pub(super) const DOUBLE_CLICK_S: f64 = 0.5; + +/// Finger jitter between taps easily exceeds egui's 6 px `max_click_dist`; 64 px is about two-thirds of an inch at 96 DPI (roughly a fingertip pad). 32 px still rejected casual Framework double-taps; Windows' mouse SM_CXDOUBLECLK is only 4 px and is not used for touch. +const TOUCH_MAX_CLICK_DIST: f32 = 64.0; + +/// True when this frame's pointer work came from a touch contact (still down, or a Touch event including End on the click frame). +fn pointer_from_touch(ui: &Ui) -> bool { + ui.input(|i| i.any_touches() || i.events.iter().any(|e| matches!(e, egui::Event::Touch { .. }))) +} + +/// Whether this click on `resp` completes a double-click / double-tap, counted the Windows way (Photoshop): a click soon after a lone click near the same spot; the click after a double starts over. +/// +/// Time window is 0.5 s (Windows / Photoshop; egui's default is 0.3 s). Mouse uses egui's `max_click_dist` (6 px); touch uses [`TOUCH_MAX_CLICK_DIST`] so finger jitter between taps still counts. Call on every click for that widget so the first tap is remembered. +pub fn second_click(ui: &Ui, resp: &Response) -> bool { + if !resp.clicked() { + return false; + } + let key = resp.id.with("pc-last-click"); + // Prefer the response's hit pos: raw `pointer.interact_pos` can be unset on a release-only frame. + let pos = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.interact_pos())); + let time = ui.input(|i| i.time); + let touch = pointer_from_touch(ui); + let mouse_dist = ui.ctx().options(|o| o.input_options.max_click_dist); + let last: Option<(f64, Pos2, bool)> = ui.data(|d| d.get_temp(key)); + // Looser distance if either tap in the pair was touch (End clears `any_touches` but leaves Touch in `events`). + let dist = if touch || last.is_some_and(|(_, _, t)| t) { TOUCH_MAX_CLICK_DIST.max(mouse_dist) } else { mouse_dist }; + let double = match (last, pos) { + (Some((t, p, _)), Some(q)) => time - t < DOUBLE_CLICK_S && p.distance(q) < dist, + _ => false, + }; + ui.data_mut(|d| { + if let (false, Some(q)) = (double, pos) { + d.insert_temp(key, (time, q, touch)); + } else { + d.remove::<(f64, Pos2, bool)>(key); + } + }); + double +} + +fn slider_with(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, gradient: Option<&[Color32]>, g: RowGestures) -> Response { + let t = Tokens::get(ui.ctx()); + let width = ui.available_width().max(60.0); + let (rect, mut resp) = ui.allocate_exact_size(vec2(width, 18.0), Sense::click_and_drag()); + let (lo, hi) = (*range.start(), *range.end()); + let track = Rect::from_center_size(rect.center(), vec2(rect.width() - 14.0, if gradient.is_some() { 5.0 } else { 3.0 })); + if let Some(p) = resp.interact_pointer_pos() + && (resp.dragged() || resp.clicked()) + { + let f = ((p.x - track.left()) / track.width()).clamp(0.0, 1.0); + let nv = curve_value(f, lo, hi, g.curve); + if (nv - *value).abs() > f32::EPSILON { + *value = nv; + resp.mark_changed(); + } + } + // The double-click's first click has moved the knob to the pointer; the second resets. + if let Some(reset) = g.reset + && second_click(ui, &resp) + { + *value = reset; + resp.mark_changed(); + } + if let Some(step) = g.wheel_step { + let n = wheel_notches(ui, &resp); + if n != 0.0 { + let nv = (*value + n * step).clamp(lo, hi); + if nv != *value { + *value = nv; + resp.mark_changed(); + } + } + } + let f = curve_fraction(*value, lo, hi, g.curve); + let knob_x = track.left() + f * track.width(); + let painter = ui.painter(); + match gradient { + Some(colors) if colors.len() >= 2 => { + let n = colors.len() - 1; + for (i, w) in colors.windows(2).enumerate() { + let x0 = track.left() + track.width() * i as f32 / n as f32; + let x1 = track.left() + track.width() * (i + 1) as f32 / n as f32; + let mut mesh = egui::Mesh::default(); + let r = Rect::from_min_max(pos2(x0, track.top()), pos2(x1, track.bottom())); + mesh.colored_vertex(r.left_top(), w[0]); + mesh.colored_vertex(r.right_top(), w[1]); + mesh.colored_vertex(r.right_bottom(), w[1]); + mesh.colored_vertex(r.left_bottom(), w[0]); + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(mesh); + } + } + _ => { + painter.rect_filled(track, 2.0, t.field_border); + let filled = Rect::from_min_max(track.min, pos2(knob_x, track.max.y)); + painter.rect_filled(filled, 2.0, if t.bevel { t.accent } else { t.text_dim }); + } + } + let knob = pos2(knob_x, rect.center().y); + if t.bevel { + let kr = Rect::from_center_size(knob, vec2(10.0, 16.0)); + surface(ui, kr, t.card, true); + } else { + let kr = if t.pro { 6.0 } else { 7.0 }; + painter.circle_filled(knob + vec2(0.0, 1.0), kr + 0.5, Color32::from_black_alpha(90)); + painter.circle_filled(knob, kr, if t.pro { Color32::from_gray(236) } else { Color32::WHITE }); + if let Some(outline) = t.knob_outline() { + painter.circle_stroke(knob, kr, Stroke::new(1.0, outline)); + } + if resp.hovered() || resp.dragged() { + painter.circle_stroke(knob, 9.5, Stroke::new(2.0, t.accent_soft)); + } + } + resp +} + +/// Labelled slider row: `Label ........ [value field]` above a full-width thin slider. +pub fn slider_row(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, gradient: Option<&[Color32]>) -> Response { + slider_row_with(ui, label, value, range, suffix, gradient, RowGestures::default()) +} + +/// [`slider_row`] with Photoshop's extra gestures ([`RowGestures`]). +pub fn slider_row_with( + ui: &mut Ui, + label: &str, + value: &mut f32, + range: std::ops::RangeInclusive, + suffix: &str, + gradient: Option<&[Color32]>, + g: RowGestures, +) -> Response { + slider_row_prec(ui, label, value, range, suffix, gradient, g, None) +} + +/// [`slider_row_with`] whose field shows `decimals` places instead of the one (or two, for a +/// small range) it picks itself: Exposure's ±20 stops show two, its Offset four (#4164). +#[allow(clippy::too_many_arguments)] +pub fn slider_row_prec( + ui: &mut Ui, + label: &str, + value: &mut f32, + range: std::ops::RangeInclusive, + suffix: &str, + gradient: Option<&[Color32]>, + g: RowGestures, + decimals: Option, +) -> Response { + let t = Tokens::get(ui.ctx()); + let mut changed_resp = None; + // The row's caption names both its number (through the scrub link) and its slider. + let mut label_id = None; + ui.horizontal(|ui| { + // The label scrubs the row's field, across the row (Photoshop's scrubby labels). + let l = ui.label(egui::RichText::new(tl!(label)).color(t.text_dim)); + label_id = Some(l.id); + scrub_label_within(ui, &l, f32::INFINITY); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + changed_resp = Some( + value_field_in( + ui, + value, + range.clone(), + suffix, + 74.0, + 0.0, + FieldOpts { decimals, step_from_decimals: decimals.is_some(), ..Default::default() }, + None, + ) + .0, + ); + }); + }); + let s = slider_with(ui, value, range, gradient, g); + s.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(*value), tl!(label))); + let s = if let Some(id) = label_id { s.labelled_by(id) } else { s }; + let mut r = s.clone(); + if let Some(v) = changed_resp { + if v.changed() { + r.mark_changed(); + } + // A scrub of the field or its label is one drag, like the slider's, for history. + use egui::response::Flags; + r.flags |= v.flags & (Flags::DRAG_STARTED | Flags::DRAGGED | Flags::DRAG_STOPPED); + } + ui.add_space(4.0); + r +} diff --git a/crates/ui-egui/src/widgets/tests.rs b/crates/ui-egui/src/widgets/tests.rs index dd5a5da53f..f0971e053d 100644 --- a/crates/ui-egui/src/widgets/tests.rs +++ b/crates/ui-egui/src/widgets/tests.rs @@ -452,9 +452,8 @@ fn value_field_digits_ink_is_centred_and_level_with_the_unit() { let lum = |p: [u8; 4]| u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2]); // Top and bottom of the ink (pt) between x0 and x1. let ink = |x0: f32, x1: f32| { - let rows: Vec = (px(field.top() + 2.0)..px(field.bottom() - 2.0)) - .filter(|&y| (px(x0)..px(x1)).any(|x| lum(image.get_pixel(x, y).0) > lum(bg) + 150)) - .collect(); + let rows: Vec = + (px(field.top() + 2.0)..px(field.bottom() - 2.0)).filter(|&y| (px(x0)..px(x1)).any(|x| lum(image.get_pixel(x, y).0) > lum(bg) + 150)).collect(); let (top, bottom) = (rows.first().copied().unwrap_or(0), rows.last().copied().unwrap_or(0) + 1); (top as f32 / scale, bottom as f32 / scale) }; diff --git a/crates/ui-egui/src/widgets/text_field.rs b/crates/ui-egui/src/widgets/text_field.rs new file mode 100644 index 0000000000..3a009d3635 --- /dev/null +++ b/crates/ui-egui/src/widgets/text_field.rs @@ -0,0 +1,116 @@ +use super::panel::surface; +use super::*; + +/// The most characters a [`text_field`] holds unless its caller sets a limit: far beyond any +/// search, name or hex value, yet a pasted multi-gigabyte string is cut at the field instead of +/// being laid out every frame (#2150). +pub const TEXT_FIELD_LIMIT: usize = 1024; + +/// The most characters one typed, pasted or IME-committed text event carries into the app +/// ([`cap_text_events`]): a megabyte of text, more than any field or text layer is pasted. +pub const INPUT_EVENT_LIMIT: usize = 1 << 20; + +/// Cuts every text, paste and IME event to [`INPUT_EVENT_LIMIT`] characters (at a character +/// boundary) before any widget sees it, so no text field -- whatever its own limit -- has to +/// lay out an 8 GB paste (#2150). +pub fn cap_text_events(events: &mut [egui::Event]) { + fn cut(text: &mut String) -> bool { + let Some((end, _)) = text.char_indices().nth(INPUT_EVENT_LIMIT) else { return false }; + text.truncate(end); + true + } + for event in events { + match event { + egui::Event::Text(text) | egui::Event::Paste(text) | egui::Event::Ime(egui::ImeEvent::Commit(text)) => { + cut(text); + } + // The highlighted range indexes the old text; past the cut it would point nowhere. + egui::Event::Ime(egui::ImeEvent::Preedit { text, active_range_chars }) => { + if cut(text) && active_range_chars.as_ref().is_some_and(|r| r.end > INPUT_EVENT_LIMIT) { + *active_range_chars = None; + } + } + _ => {} + } + } +} + +/// Height of a [`text_field`]'s box, matching a [`value_field`]. +pub const TEXT_FIELD_H: f32 = 24.0; + +/// Inner padding of a [`text_field`]'s box: 6 pt either side, 2 pt above and below. +const TEXT_FIELD_PAD: Vec2 = vec2(6.0, 2.0); + +/// A single-line text field in PhotoCraft's shared field style (#3789): the same box as a +/// [`value_field`] -- the theme's field fill and `field_border`, rounded by `radius_sm` -- with a +/// consistent inner padding and no focus outline. egui's default white focus ring (its +/// `selection.stroke`) is what made the Preferences search field look different from the Color +/// Picker's hex field, so every plain, non-numeric input (search, hex, name, filter) is drawn +/// through here to look and behave the same. `id` carries the field's text and focus across +/// frames; `hint` shows while it is empty; `mono` picks the monospaced face for hex and other +/// code-like values. +pub fn text_field(ui: &mut Ui, id: egui::Id, text: &mut String, hint: &str, width: f32, mono: bool) -> Response { + text_field_ex(ui, id, text, hint, width, mono, None) +} + +/// [`text_field`] limited to `char_limit` characters (a hex field's six digits, say), or to +/// [`TEXT_FIELD_LIMIT`] without one. +pub fn text_field_ex(ui: &mut Ui, id: egui::Id, text: &mut String, hint: &str, width: f32, mono: bool, char_limit: Option) -> Response { + let t = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(vec2(width.max(16.0), TEXT_FIELD_H), Sense::hover()); + surface(ui, rect, t.field, false); + if !t.bevel { + ui.painter().rect_stroke(rect, t.radius_sm, Stroke::new(1.0, t.field_border), StrokeKind::Inside); + } + let font = if mono { theme::mono(12.0) } else { egui::FontId::proportional(12.5) }; + let inner = rect.shrink2(TEXT_FIELD_PAD); + let limit = char_limit.unwrap_or(TEXT_FIELD_LIMIT); + // A value already past the limit (restored from a state file, set by automation) is shown and + // edited as its first `limit` characters, so it is never laid out whole; the caller's string + // changes only when that copy is edited. + let mut bounded = text.char_indices().nth(limit).map(|(end, _)| text[..end].to_string()); + let shown = match bounded.as_mut() { + Some(b) => b, + None => &mut *text, + }; + // TextEdit draws its text at the top of its rect; fill the box and centre the line in it, so + // the text sits on the field's middle like a dropdown's or value field's. + let edit = egui::TextEdit::singleline(shown) + .id(id) + .hint_text(hint.to_owned()) + .frame(egui::Frame::NONE) + .font(font) + .min_size(inner.size()) + .align(egui::Align2::LEFT_CENTER) + .char_limit(limit); + // A child Ui keeps the field's selection colour local: `Visuals::selection` also fills selected + // list rows and slider trails, which must keep the theme's. + let layout = egui::Layout::centered_and_justified(egui::Direction::TopDown); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(inner).layout(layout)); + // The theme's 24 pt interact height would make the edit taller than the box's inside. + child.spacing_mut().interact_size.y = inner.height(); + child.style_mut().visuals.selection.bg_fill = t.field_selection(); + let response = child.add(edit); + if let Some(b) = bounded + && response.changed() + { + *text = b; + } + response +} + +pub(super) fn first_field_id() -> egui::Id { + egui::Id::unique("pc-focus-first-field") +} + +/// While `on`, the next number field drawn takes the keyboard focus with its text selected (a +/// dialog opening on its first value, as in Photoshop). Turn it off once the body is laid out. +pub fn focus_first_field(ctx: &egui::Context, on: bool) { + ctx.data_mut(|d| { + if on { + d.insert_temp(first_field_id(), true); + } else { + d.remove::(first_field_id()); + } + }); +} diff --git a/crates/ui-egui/src/widgets/units.rs b/crates/ui-egui/src/widgets/units.rs new file mode 100644 index 0000000000..388dddf26c --- /dev/null +++ b/crates/ui-egui/src/widgets/units.rs @@ -0,0 +1,133 @@ +use super::fields::{FieldOpts, value_field_in}; +use super::*; + +/// A size dialog's unit key (`px`, `in`, `cm`, `mm`, `pt`, `pica`, `percent`) as a unit. +pub fn unit_of_key(key: &str) -> photocraft_engine::prefs::Unit { + use photocraft_engine::prefs::Unit; + match key { + "in" => Unit::Inches, + "cm" => Unit::Centimeters, + "mm" => Unit::Millimeters, + "pt" => Unit::Points, + "pica" => Unit::Picas, + "percent" => Unit::Percent, + _ => Unit::Pixels, + } +} + +/// Decimal places for a size dialog's unit key (`px`, `in`, `cm`, `mm`, `pt`, `pica`, `percent`). +/// The places themselves live on [`photocraft_engine::prefs::Unit`], so the dialogs, the Info +/// panel and the rulers agree (#2434). +pub fn unit_decimals(key: &str) -> u32 { + unit_of_key(key).decimals() as u32 +} + +/// A [`value_field`] showing `decimals` decimal places instead of the one (or two, for a small +/// range) it picks itself: the ruler units need their own precision (#2434). +pub fn value_field_prec(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, width: f32, decimals: u32) -> Response { + value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts { decimals: Some(decimals), ..Default::default() }, None).0 +} + +/// A field's unit and the resolution a typed unit converts at (`1in` in a px field). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FieldUnits { + pub unit: photocraft_engine::prefs::Unit, + /// Pixels per inch. + pub dpi: f64, + /// Points per inch (72 PostScript, 72.27 traditional). + pub ppi: f64, +} + +/// A [`value_field_prec`] without a suffix, whose unit is chosen beside it (Image Size and New +/// Document's unit menus) and converts typed units at that dialog's own resolution. +pub fn value_field_units(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, width: f32, decimals: u32, units: FieldUnits) -> Response { + value_field_in(ui, value, range, "", width, 0.0, FieldOpts { decimals: Some(decimals), units: Some(units), ..Default::default() }, None).0 +} + +/// A [`value_field_prec`] in `units` whose 100 % is a length of `extent` px (Free Transform's W +/// and H): a length typed while it shows percent becomes that share of `extent` (`40px`, `2in`), +/// and a percentage typed while it shows a length becomes that share of `extent` (`50%`), at +/// `units`' resolution (#6284). The field keeps its own unit. +#[allow(clippy::too_many_arguments)] +pub fn value_field_extent( + ui: &mut Ui, + value: &mut f32, + range: std::ops::RangeInclusive, + suffix: &str, + width: f32, + decimals: u32, + units: FieldUnits, + extent: f64, +) -> Response { + let opts = FieldOpts { decimals: Some(decimals), units: Some(units), extent: Some(extent), ..Default::default() }; + value_field_in(ui, value, range, suffix, width, 0.0, opts, None).0 +} + +pub(super) fn field_resolution_id() -> egui::Id { + egui::Id::unique("pc-field-resolution") +} + +/// The resolution (pixels per inch) and point size (points per inch) a unit typed into a value +/// field converts at: the active document's. The app sets it each frame; 72 / 72 without it. +pub fn set_field_resolution(ctx: &egui::Context, dpi: f64, ppi: f64) { + ctx.data_mut(|d| d.insert_temp(field_resolution_id(), (dpi, ppi))); +} + +/// The unit a field's suffix names (`px`, `in`, `cm`, `mm`, `pt`, `pica`/`pc`, `%`), if any. +pub(super) fn unit_of_suffix(suffix: &str) -> Option { + use photocraft_engine::prefs::Unit; + Some(match suffix { + "px" => Unit::Pixels, + "in" => Unit::Inches, + "cm" => Unit::Centimeters, + "mm" => Unit::Millimeters, + "pt" => Unit::Points, + "pica" | "pc" => Unit::Picas, + "%" => Unit::Percent, + _ => return None, + }) +} + +/// Photoshop-style numbers: "100", "12.5" (never "100.0"). +pub fn fmt_num(v: f64) -> String { + fmt_num_prec(v, 1) +} + +/// Rounds `v` to `decimals` places (half away from zero) and drops trailing zeros, so a value is +/// never shown with more precision than it has: `0.7995` at three places is `0.8`, `2.0` is `2` +/// (#2434). [`photocraft_engine::prefs::Unit::decimals`] gives each ruler unit's places. +pub fn fmt_num_prec(v: f64, decimals: u32) -> String { + photocraft_engine::prefs::fmt_decimals(v, decimals as usize) +} + +/// Two-decimal variant of [`fmt_num`] for small ranges: `1.05`, `0.78`, `2`. +pub fn fmt_num2(v: f64) -> String { + fmt_num_prec(v, 2) +} + +/// Parses a typed number or bounded arithmetic, including parentheses and powers. +/// Preserves egui-compatible whitespace and Unicode minus handling. +pub fn parse_num(text: &str) -> Option { + if text.len() > 1024 { + return None; + } + crate::numeric_expression::parse(&clean(text)) +} + +/// [`parse_num`] in a field with `units`: a number may carry a unit (`2in`, `5mm`, `50%`), +/// converted into the field's unit; one that can't convert makes the text invalid. +pub(crate) fn parse_num_in(text: &str, units: crate::numeric_expression::Units) -> Option { + if text.len() > 1024 { + return None; + } + crate::numeric_expression::parse_with_units(&clean(text), Some(units)) +} + +/// A plain typed number, no arithmetic. +pub(super) fn plain(text: &str) -> Option { + clean(text).parse().ok() +} + +fn clean(text: &str) -> String { + text.chars().filter(|c| !c.is_whitespace()).map(|c| if c == '−' { '-' } else { c }).collect() +} From e10abdb0bb4a9cc3cca99f94cab2fee3c3e0fd44 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:09:42 +0000 Subject: [PATCH 228/259] refactor(ui-egui): split vector_ui.rs into vector_ui/ --- crates/ui-egui/src/vector_ui.rs | 1988 +------------------ crates/ui-egui/src/vector_ui/curvature.rs | 86 + crates/ui-egui/src/vector_ui/options.rs | 321 +++ crates/ui-egui/src/vector_ui/overlay.rs | 239 +++ crates/ui-egui/src/vector_ui/path_ops.rs | 245 +++ crates/ui-egui/src/vector_ui/paths_panel.rs | 390 ++++ crates/ui-egui/src/vector_ui/pen.rs | 528 +++++ crates/ui-egui/src/vector_ui/shapes.rs | 167 ++ crates/ui-egui/src/vector_ui/tests.rs | 9 +- 9 files changed, 2014 insertions(+), 1959 deletions(-) create mode 100644 crates/ui-egui/src/vector_ui/curvature.rs create mode 100644 crates/ui-egui/src/vector_ui/options.rs create mode 100644 crates/ui-egui/src/vector_ui/overlay.rs create mode 100644 crates/ui-egui/src/vector_ui/path_ops.rs create mode 100644 crates/ui-egui/src/vector_ui/paths_panel.rs create mode 100644 crates/ui-egui/src/vector_ui/pen.rs create mode 100644 crates/ui-egui/src/vector_ui/shapes.rs diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index 93e88676aa..60ee51c676 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -16,6 +16,41 @@ use crate::shape_paint_ui::{PaintChange, paint_param, swatch}; use crate::state::{Tool, ToolOptions}; use crate::theme::Tokens; +mod curvature; +mod options; +mod overlay; +mod path_ops; +mod paths_panel; +mod pen; +mod shapes; + +pub(crate) use curvature::curvature_anchor_at; +pub use curvature::{curvature_down, curvature_move, curvature_toggle, curvature_up}; +#[cfg(test)] +use options::{corner_radii_patch, solid_paint}; +pub(crate) use options::{enabled_stroke_width, paint_gesture}; +pub use options::{options_bar, shape_properties}; +pub use overlay::draw_overlay; +#[cfg(test)] +use overlay::{MAX_CURVE_PIECES, bezier}; +#[cfg(test)] +pub(crate) use overlay::{curve_points, path_lines, selected_saved_path, shows_anchors}; +pub(crate) use overlay::{draw_anchor, draw_handle, draw_outline}; +pub use path_ops::{active_path_name, path_selection_finish, path_to_selection, pick_shape_at, selected_document_path, takes_path_mask, with_active_path}; +pub(crate) use path_ops::{active_shape_path, delete_key_deletes_work_path, free_transform_path, targeted_vector_mask}; +#[cfg(test)] +use paths_panel::path_context_actions; +pub use paths_panel::{PathEntry, PathRow, path_rows, paths_footer, paths_panel}; +#[cfg(test)] +pub(crate) use pen::over_first_anchor; +#[cfg(test)] +use pen::pen_to_json; +pub use pen::{cancel_stale, closes_path_at, freeform_finish, pen_break_handle, pen_commit, pen_down, pen_grab_handle, pen_move, pen_undo_last_point, pen_up}; +pub(crate) use pen::{pen_path, pen_replace}; +pub use shapes::{create_shape, draw_shape_preview, finish_shape, is_shape_tool, shape_bounds}; +#[cfg(test)] +use shapes::{shape_geometry, shape_preview}; + /// Pen tool path under construction: knots as [anchor, in, out] (document px). #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct PenPath { @@ -62,1959 +97,6 @@ impl PenPath { } } -pub fn is_shape_tool(t: Tool) -> bool { - matches!(t, Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line | Tool::CustomShape) -} - -fn rgb32(c: [f32; 4]) -> Color32 { - let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - Color32::from_rgb(b(c[0]), b(c[1]), b(c[2])) -} - -fn hex(c: [f32; 4]) -> String { - let c = rgb32(c); - format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b()) -} - -fn stroke_param(app: &PhotocraftApp) -> Value { - let o = &app.ui.tool_options; - if o.stroke_width <= 0.0 { - return Value::Null; - } - let mut p = o.shape_stroke.params(); - p["width"] = json!(o.stroke_width); - p["color"] = tool_paint_param(app, true); - p -} - -/// The paint the next shape's fill (`stroke` false) or stroke takes: the options bar's gradient, -/// else the foreground / background colour. -fn tool_paint(app: &PhotocraftApp, stroke: bool) -> photocraft_doc::Fill { - let (gradient, color) = tool_paint_source(app, stroke); - gradient.clone().unwrap_or_else(|| solid_paint(color)) -} - -/// [`tool_paint`] as `shape.create` takes it. -fn tool_paint_param(app: &PhotocraftApp, stroke: bool) -> Value { - let (gradient, color) = tool_paint_source(app, stroke); - gradient.as_ref().map_or_else(|| json!(color), paint_param) -} - -fn tool_paint_source(app: &PhotocraftApp, stroke: bool) -> (&Option, [f32; 4]) { - let o = &app.ui.tool_options; - if stroke { (&o.shape_stroke_gradient, app.session.tools.background) } else { (&o.shape_fill_gradient, app.session.tools.foreground) } -} - -/// Geometry of a Shape-tool drag as `shape.create` params, without fill and stroke (None when too -/// small): ⇧ constrains proportions, ⌥ draws from the centre. Custom shapes give their box as a `rect`. -fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) -> Option { - Some(if tool == Tool::Line { - let (mut dx, mut dy) = (end[0] - start[0], end[1] - start[1]); - if mods.shift { - // Snap to 45°. - let a = (dy.atan2(dx) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4; - let len = dx.hypot(dy); - (dx, dy) = (len * a.cos(), len * a.sin()); - } - if dx.hypot(dy) < 1.0 { - return None; - } - json!({"kind": "line", "from": start, "to": [start[0] + dx, start[1] + dy], "weight": o.line_weight.max(1.0)}) - } else { - let (mut w, mut h) = (end[0] - start[0], end[1] - start[1]); - if mods.shift { - let m = w.abs().max(h.abs()); - (w, h) = (m * w.signum(), m * h.signum()); - } - let (x0, y0) = if mods.alt { (start[0] - w, start[1] - h) } else { (start[0], start[1]) }; - let (w, h) = if mods.alt { (w * 2.0, h * 2.0) } else { (w, h) }; - let rect = [x0.min(x0 + w).round(), y0.min(y0 + h).round(), w.abs().round(), h.abs().round()]; - if rect[2] < 1.0 || rect[3] < 1.0 { - return None; - } - match tool { - Tool::Rectangle if o.corner_radius > 0.0 => json!({"kind": "roundedRect", "rect": rect, "radii": vec![o.corner_radius; 4]}), - Tool::Rectangle | Tool::CustomShape => json!({"kind": "rect", "rect": rect}), - Tool::EllipseShape => json!({"kind": "ellipse", "rect": rect}), - Tool::Triangle => json!({"kind": "polygon", "rect": rect, "sides": 3}), - _ => json!({"kind": "polygon", "rect": rect, "sides": o.polygon_sides.max(3)}), - } - }) -} - -/// The box `[x0, y0, x1, y1]` a Shape-tool drag draws (a line's: its ends'), which snaps while -/// Space repositions it (`snap_ui`). None when too small to draw. -pub fn shape_bounds(o: &ToolOptions, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) -> Option<[f64; 4]> { - let g = shape_geometry(o, tool, start, end, mods)?; - if tool == Tool::Line { - let a: [f64; 2] = serde_json::from_value(g["from"].clone()).ok()?; - let b: [f64; 2] = serde_json::from_value(g["to"].clone()).ok()?; - return Some([a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]); - } - let [x, y, w, h]: [f64; 4] = serde_json::from_value(g["rect"].clone()).ok()?; - Some([x, y, x + w, y + h]) -} - -/// Finish a Shape-tool drag: ⇧ constrains proportions, ⌥ draws from the centre. -pub fn finish_shape(app: &mut PhotocraftApp, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) { - let Some(mut p) = shape_geometry(&app.ui.tool_options, tool, start, end, mods) else { return }; - if tool == Tool::CustomShape { - // ⇧ keeps the shape's proportions (the rect is already squared). - if let Ok(rect) = serde_json::from_value(p["rect"].take()) { - let (fill, stroke) = (fill_param(app), stroke_param(app)); - crate::preset_panels::finish_custom_shape(app, rect, mods.shift, fill, stroke); - } - return; - } - if let Err(e) = create_shape(app, p) { - app.ui.status = e; - app.ui.status_error = true; - } -} - -fn fill_param(app: &PhotocraftApp) -> Value { - if app.ui.tool_options.shape_fill { tool_paint_param(app, false) } else { Value::Null } -} - -/// Create a shape layer from `shape.create` geometry with the options bar's fill and stroke: the -/// end of a drag, and the Create Rectangle / Ellipse / … dialogs (`shape_dialog`). -pub fn create_shape(app: &mut PhotocraftApp, mut geometry: Value) -> Result { - geometry["fill"] = fill_param(app); - geometry["stroke"] = stroke_param(app); - app.run("shape.create", geometry) -} - -/// The preview and command both use the full float tool colours, including transparent paint. -fn shape_preview(app: &PhotocraftApp, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) -> Option { - let o = &app.ui.tool_options; - let geometry = shape_geometry(o, tool, start, end, mods)?; - let path = if tool == Tool::CustomShape { - let rect = geometry.get("rect").and_then(|r| serde_json::from_value::<[f64; 4]>(r.clone()).ok())?; - let groups = photocraft_engine::presets::shapes::all_groups(&app.session); - let shape = groups.iter().flat_map(|g| &g.items).find(|s| s.name == app.ui.presets_ui.shape())?; - photocraft_engine::presets::shapes::fit(&shape.path, rect, mods.shift) - } else { - photocraft_engine::vector_cmds::shape_path(&geometry).ok()? - }; - Some(photocraft_doc::ShapeLayer { - path, - fill: o.shape_fill.then(|| tool_paint(app, false)), - stroke: (o.stroke_width > 0.0).then(|| o.shape_stroke.stroke(o.stroke_width, tool_paint(app, true))), - ..Default::default() - }) -} - -/// Shape-tool drag preview using the same path and vector stroke geometry as the commit. -pub fn draw_shape_preview(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) { - let Some(mut shape) = shape_preview(app, tool, start, end, mods) else { return }; - let path = shape.path.clone(); - let origin = xf.to_screen(0.0, 0.0); - let x = xf.to_screen(1.0, 0.0) - origin; - let y = xf.to_screen(0.0, 1.0) - origin; - let transform = Affine { m: [x.x as f64, x.y as f64, y.x as f64, y.y as f64, origin.x as f64, origin.y as f64] }; - shape.path = shape.path.transform(&transform); - if let Some(stroke) = &mut shape.stroke { - stroke.width *= xf.zoom; - } - // This lightweight screen overlay retains the existing display-colour behaviour; document - // rendering still goes through its format/profile path when the shape is committed. - crate::shape_stroke_ui::paint_shape_preview(painter, &shape); - let accent = Tokens::get(painter.ctx()).accent; - for (pts, _) in path_lines(&path, &|q| xf.to_screen(q[0] as f32, q[1] as f32)) { - // The accent path over a dark halo: visible on any pixels (#172). - painter.extend(crate::tool_feedback::contrast_path(pts, true, accent)); - } -} - -// --------------------------------------------------------------------------------------------- -// Pen - -fn pen_to_json(pen: &PenPath, closed: bool) -> Value { - let folded = fold_close(pen); - let (pen, closed) = match &folded { - Some(p) => (p, true), - None => (pen, closed), - }; - json!({"subpaths": [{"closed": closed, "knots": pen.knots.iter().enumerate().map(|(i, k)| json!({"anchor": k[0], "in": k[1], "out": k[2], "smooth": !pen.unlinked.contains(&i) && (k[1] != k[0] || k[2] != k[0])})).collect::>()}]}) -} - -/// Is `(x, y)` on the first anchor of a Pen path that a click there would close (two anchors or -/// more)? `tol` is the anchors' hit radius in document pixels. -fn on_closing_anchor(pen: &PenPath, x: f64, y: f64, tol: f64) -> bool { - pen.knots.len() >= 2 && pen.knots.first().is_some_and(|k| (k[0][0] - x).hypot(k[0][1] - y) < tol) -} - -/// Would a click at `(x, y)` with `tool` close the path being drawn: the Pen over the first -/// anchor, or the Curvature Pen over the first of three anchors or more? The canvas shows the -/// close-path pointer there, as Photoshop does (#4596). -pub fn closes_path_at(app: &PhotocraftApp, tool: Tool, x: f64, y: f64) -> bool { - let Some(pen) = app.ui.pen.as_ref().filter(|p| !p.dragging && p.moving.is_none()) else { return false }; - match tool { - Tool::Pen => !pen.curvature && on_closing_anchor(pen, x, y, 6.0 / app.point_zoom().max(0.01) as f64), - Tool::CurvaturePen => pen.curvature && pen.knots.len() >= 3 && curvature_hit(app, x, y) == Some(0), - _ => false, - } -} - -/// 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. -pub fn pen_down(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) { - if !cancel_stale(app) { - return; - } - let tol = 6.0 / app.point_zoom().max(0.01) as f64; - if app.ui.pen.is_none() { - app.ui.pen_doc = app.session.active().map(|st| st.doc.id); - } - // 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. - 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); - } - let pen = app.ui.pen.get_or_insert_with(PenPath::default); - pen.adjusting_in = false; - if let Some(first) = pen.knots.first().map(|k| k[0]) - && on_closing_anchor(pen, x, y, tol) - { - // Pressing the first anchor closes the path on release. Until then a stand-in for it - // takes the drag, which pulls out that anchor's handles (close-drag, #3306). - pen.knots.push([first; 3]); - pen.dragging = true; - pen.adjusting_last = false; - return; - } - // Clicking the last anchor breaks its outgoing handle without throwing away the incoming - // curve. Dragging from that anchor then sets the outgoing handle independently (#1482). - // This must precede adding a point, or a re-click creates a zero-length segment. - if let Some((i, last)) = pen.knots.len().checked_sub(1).zip(pen.knots.last_mut()) - && (last[0][0] - x).hypot(last[0][1] - y) < tol - { - last[2] = last[0]; - if !pen.unlinked.contains(&i) { - pen.unlinked.push(i); - } - pen.dragging = true; - pen.adjusting_last = true; - return; - } - let p = match pen.knots.last() { - Some(prev) => shift_45(prev[0], [x, y], shift), - None => [x, y], - }; - pen.knots.push([p; 3]); - pen.dragging = true; - pen.adjusting_last = false; -} - -/// Pen drag: pull out the handles of the anchor just placed. ⇧ (read live, as it is held) -/// turns the handle to the nearest 45° direction from its anchor. -pub fn pen_move(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) { - if let Some(pen) = app.ui.pen.as_mut() - && pen.dragging - { - let (adjusting_last, adjusting_in) = (pen.adjusting_last, pen.adjusting_in); - if let Some(k) = pen.knots.last_mut() { - let a = k[0]; - let [x, y] = shift_45(a, [x, y], shift); - if adjusting_in { - k[1] = [x, y]; - return; - } - k[2] = [x, y]; - if !adjusting_last { - k[1] = [2.0 * a[0] - x, 2.0 * a[1] - y]; - } - } - } -} - -/// `p`, or with ⇧ `p` projected onto the nearest 45° ray from `origin` (Pen tool constraint). -fn shift_45(origin: [f64; 2], p: [f64; 2], shift: bool) -> [f64; 2] { - if shift { crate::stroke_constraint::snap45(origin, p) } else { p } -} - -/// Undo the most recently placed Pen anchor while its path is still in progress. -/// These knots are editor-only gesture state, not document history until Enter or -/// clicking the first anchor commits the path. Therefore Cmd/Ctrl+Z must consume one -/// knot rather than undoing an unrelated, already committed document operation. -pub fn pen_undo_last_point(app: &mut PhotocraftApp) -> bool { - if !cancel_stale(app) { - return false; - } - let Some(pen) = app.ui.pen.as_mut() else { return false }; - // A resumed path's own anchors are not the draft's to take back: undoing past the ones added - // since it resumed drops the draft and leaves the path as it was (#6593). - if pen.resumes.as_ref().is_some_and(|r| pen.knots.len() <= r.was.knots.len()) { - // A ⌘/Ctrl selection on the draft goes with it. - if app.ui.direct_selection.target == Some(crate::direct_select::PathRef::Pen) { - app.ui.direct_selection = Default::default(); - } - app.ui.pen = None; - return true; - } - if pen.knots.pop().is_none() { - return false; - } - let n = pen.knots.len(); - let ds = &mut app.ui.direct_selection; - if ds.target == Some(crate::direct_select::PathRef::Pen) { - // A ⌘/Ctrl selection on the path being drawn loses the removed anchor. - ds.anchors.retain(|a| a[1] < n); - ds.segment = ds.segment.filter(|s| s[1] + 1 < n); - } - pen.unlinked.retain(|&i| i < pen.knots.len()); - if pen.curvature { - pen.moving = None; - curvature_refresh(pen, false); - } - pen.dragging = false; - if pen.knots.is_empty() { - app.ui.pen = None; - } - true -} - -pub fn pen_up(app: &mut PhotocraftApp) { - let jitter = 2.0 / f64::from(app.point_zoom().max(0.01)); - let Some(pen) = app.ui.pen.as_mut() else { return }; - pen.dragging = false; - pen.adjusting_last = false; - pen.adjusting_in = false; - if closing(pen) { - // A click on the first anchor closes the path and leaves that anchor's handles alone. - if let Some(k) = pen.knots.last_mut() - && (k[2][0] - k[0][0]).hypot(k[2][1] - k[0][1]) < jitter - { - k[1] = k[0]; - k[2] = k[0]; - } - pen_commit(app, true); - } -} - -/// ⌥/Alt during a Pen drag breaks the pair of handles being pulled out: from then on only the -/// outgoing handle follows the pointer and the incoming curve stays as it is (#3306). -pub fn pen_break_handle(app: &mut PhotocraftApp) { - let Some(pen) = app.ui.pen.as_mut().filter(|p| p.dragging && !p.adjusting_last) else { return }; - let Some(i) = pen.knots.len().checked_sub(1) else { return }; - if !pen.unlinked.contains(&i) { - pen.unlinked.push(i); - } - pen.adjusting_last = true; -} - -/// ⌥/Alt-press on one of the last anchor's handles while drawing grabs that handle alone: the -/// drag turns it and the other handle stays put (#3306, #6077). False when the press misses both. -pub fn pen_grab_handle(app: &mut PhotocraftApp, x: f64, y: f64) -> bool { - let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); - let Some(pen) = app.ui.pen.as_mut() else { return false }; - let Some((i, k)) = pen.knots.len().checked_sub(1).zip(pen.knots.last()) else { return false }; - let dist = |p: [f64; 2]| (p[0] - x).hypot(p[1] - y); - // Both handles show only while the outgoing one is pulled out (`draw_overlay`). - if k[2] == k[0] { - return false; - } - let grabbed = |h: [f64; 2]| h != k[0] && dist(h) < tol && dist(h) < dist(k[0]); - let incoming = if grabbed(k[2]) && dist(k[2]) <= dist(k[1]) { - false - } else if grabbed(k[1]) { - true - } else { - return false; - }; - if !pen.unlinked.contains(&i) { - pen.unlinked.push(i); - } - pen.dragging = true; - pen.adjusting_last = true; - pen.adjusting_in = incoming; - true -} - -/// Would a press at `at` close the Pen path: is the pointer on the first anchor of a path that -/// already has a segment, and no drag is under way? The canvas then shows the close cue (#4193). -pub(crate) fn over_first_anchor(pen: &PenPath, at: [f64; 2], tol: f64) -> bool { - !pen.dragging && pen.moving.is_none() && pen.knots.len() >= 2 && pen.knots.first().is_some_and(|k| (k[0][0] - at[0]).hypot(k[0][1] - at[1]) < tol) -} - -/// Is a close-drag in progress: does the path end in the stand-in for its first anchor? -fn closing(pen: &PenPath) -> bool { - pen.knots.len() >= 3 && pen.knots.first().map(|k| k[0]) == pen.knots.last().map(|k| k[0]) -} - -/// The path with a close-drag's stand-in folded into the first knot, which takes the dragged -/// handles (smooth, or a cusp after ⌥/Alt); `None` when no close-drag is in progress. -fn fold_close(pen: &PenPath) -> Option { - if !closing(pen) { - return None; - } - let mut p = pen.clone(); - let stand_in = p.knots.pop()?; - let broken = p.unlinked.contains(&p.knots.len()); - p.unlinked.retain(|&i| i < p.knots.len()); - if stand_in[1] != stand_in[0] || stand_in[2] != stand_in[0] { - let first = p.knots.first_mut()?; - first[1] = stand_in[1]; - first[2] = stand_in[2]; - p.unlinked.retain(|&i| i != 0); - if broken { - p.unlinked.push(0); - } - } - Some(p) -} - -/// The Pen path being drawn as a document path (one open subpath), so ⌘/Ctrl (Direct Selection) -/// can edit it in place while drawing (#4022). -pub(crate) fn pen_path(pen: &PenPath) -> Path { - let pt = |q: [f64; 2]| photocraft_geom::Point::new(q[0], q[1]); - let knots = pen - .knots - .iter() - .enumerate() - .map(|(i, k)| photocraft_doc::Knot { - anchor: pt(k[0]), - in_ctrl: pt(k[1]), - out_ctrl: pt(k[2]), - smooth: !pen.unlinked.contains(&i) && (k[1] != k[0] || k[2] != k[0]), - }) - .collect(); - Path::new(vec![photocraft_doc::vector::Subpath { closed: false, knots, op: Default::default() }]) -} - -/// The Pen path being drawn becomes `path`'s first subpath, edited with ⌘/Ctrl (Direct Selection); -/// drawing carries on from its last anchor. A Curvature Pen path keeps following its anchors. -pub(crate) fn pen_replace(app: &mut PhotocraftApp, path: &Path) { - let Some(pen) = app.ui.pen.as_mut() else { return }; - let knots = path.subpaths.first().map(|s| s.knots.as_slice()).unwrap_or_default(); - pen.knots = knots.iter().map(knot_points).collect(); - pen.unlinked = knots.iter().enumerate().filter(|(_, k)| !k.smooth).map(|(i, _)| i).collect(); - pen.dragging = false; - pen.adjusting_last = false; - pen.adjusting_in = false; - pen.moving = None; - if pen.curvature { - curvature_refresh(pen, false); - } - if pen.knots.is_empty() { - app.ui.pen = None; - } -} - -/// Preserve a foreign document's draft as its Work Path before another document can edit it. -/// A failed commit retains the draft and blocks the caller until it can be retried. -pub fn cancel_stale(app: &mut PhotocraftApp) -> bool { - let active = app.session.active().map(|st| st.doc.id); - if app.ui.pen.is_none() { - app.ui.pen_doc = None; - return true; - } - let Some(owner) = app.ui.pen_doc.filter(|d| Some(*d) != active) else { return true }; - if let Some(index) = app.session.documents().iter().position(|d| d.doc.id == owner) { - let Some(mut pen) = app.ui.pen.clone() else { return true }; - if pen.curvature { - curvature_refresh(&mut pen, false); - } - let active = app.session.active_index(); - app.session.set_active(index); - // Bypass shell targets and sync_views: both belong to the newly active document. - let result = app.session.execute("path.set", json!({"name": "work", "op": "combine", "path": pen_to_json(&pen, false)})); - if let Some(index) = active { - app.session.set_active(index); - } - if let Err(e) = result { - app.ui.status = e.to_string(); - app.ui.status_error = true; - return false; - } - } - app.ui.pen = None; - app.ui.pen_doc = None; - if app.ui.direct_selection.target == Some(crate::direct_select::PathRef::Pen) { - app.ui.direct_selection = Default::default(); - } - true -} - -/// Finish the pen path: a work path (Path mode) or a new shape layer (Shape mode). -pub fn pen_commit(app: &mut PhotocraftApp, closed: bool) { - // The control channel is drained after `sync_views`, so a document switch in this frame has - // not been seen yet: never commit the path into the document it was not drawn on. - if !cancel_stale(app) { - return; - } - let Some(mut pen) = app.ui.pen.take() else { return }; - app.ui.pen_doc = None; - if app.ui.direct_selection.target == Some(crate::direct_select::PathRef::Pen) { - // Its anchors are no longer the Pen's: the committed path is another path. - app.ui.direct_selection = Default::default(); - } - if pen.curvature { - curvature_refresh(&mut pen, closed); - } - commit_path(app, &pen, closed); -} - -/// Commit a finished Pen, Freeform Pen or Curvature Pen path, as one History step: a new shape -/// layer (Shape mode), else a subpath of the targeted vector mask, else the work path. -fn commit_path(app: &mut PhotocraftApp, pen: &PenPath, closed: bool) { - if pen.knots.len() < 2 { - return; - } - let path = pen_to_json(pen, closed); - let r = if app.ui.tool_options.vector_mode == "shape" { - let fill = if closed { fill_param(app) } else { Value::Null }; - let stroke = if closed { - stroke_param(app) - } else { - let mut stroke = app.ui.tool_options.shape_stroke.params(); - stroke["width"] = json!(app.ui.tool_options.stroke_width.max(1.0)); - stroke["color"] = json!(app.session.tools.foreground); - stroke - }; - app.run("shape.create", json!({"kind": "path", "path": path, "fill": fill, "stroke": stroke})) - } else if let Some((name, p)) = - pen.resumes.as_ref().and_then(|r| app.session.active().and_then(|st| with_resumed_subpath(&st.doc, r, &path)).map(|p| (r.path.clone(), p))) - { - // The resumed subpath, carried on, takes its old place: one step, no second subpath. - app.run("path.set", json!({"name": name, "path": p})).inspect(|_| app.ui.selected_path = Some(name)) - } else if let Some((id, existing)) = targeted_vector_mask(app) { - // A targeted vector mask takes the new subpath (#196), as in Photoshop. - let mut p = photocraft_engine::vector_cmds::path_json(&existing); - if let (Some(subs), Some(new)) = (p.get_mut("subpaths").and_then(Value::as_array_mut), path.get("subpaths").and_then(Value::as_array)) { - subs.extend(new.iter().cloned()); - } - app.run("layer.vectorMask.edit", json!({"layer": id, "path": p})) - } else { - // Photoshop adds the new subpath to the path selected in the Paths panel, which is the - // Work Path right after drawing one, so path after path builds up there (#4721). With no - // path selected, a new Work Path replaces the old one. The drawn path ends up selected. - // A resumed draft whose subpath changed meanwhile joins the path it came from, as a new - // subpath, even with nothing selected in the Paths panel. - let exists = |n: &String| app.session.active().is_some_and(|st| path_exists(&st.doc, n)); - let resumed_from = pen.resumes.as_ref().filter(|r| app.session.active().is_some_and(|st| st.doc.id.0 == r.doc)).map(|r| r.path.clone()); - let target = resumed_from.filter(exists).or_else(|| app.ui.selected_path.clone().filter(exists)); - let name = target.clone().unwrap_or_else(|| "work".into()); - let mut params = json!({"name": name, "path": path}); - if target.is_some() { - params["op"] = json!("combine"); - } - app.run("path.set", params).inspect(|_| app.ui.selected_path = Some(name)) - }; - if let Err(e) = r { - app.ui.status = e; - app.ui.status_error = true; - } -} - -/// Does `doc` have the path the Paths panel calls `name`: "work", or a saved path's name? -fn path_exists(doc: &Document, name: &str) -> bool { - doc_path(doc, name).is_some() -} - -/// The path the Paths panel calls `name`: "work", or a saved path's name. -fn doc_path<'a>(doc: &'a Document, name: &str) -> Option<&'a Path> { - if name == "work" { doc.work_path.as_ref() } else { doc.paths.iter().find(|p| p.name == name).map(|p| &p.path) } -} - -/// The open subpath of the path a new Pen path would join (the one selected in the Paths panel, -/// else the work path) that has its first or last anchor at `(x, y)`, as a Pen path to carry on -/// drawing from there (#6593). Its knots run towards that anchor: reversed, handles swapped, when -/// it is the first. Shape mode and a targeted vector mask take new paths, so they resume nothing. -fn resume_at(app: &PhotocraftApp, x: f64, y: f64, tol: f64) -> Option { - if app.ui.tool_options.vector_mode == "shape" || targeted_vector_mask(app).is_some() { - return None; - } - let st = app.session.active()?; - let doc = st.doc.id.0; - let name = app.ui.selected_path.clone().filter(|n| path_exists(&st.doc, n)).unwrap_or_else(|| "work".into()); - let near = |k: &photocraft_doc::Knot| (k.anchor.x - x).hypot(k.anchor.y - y) < tol; - doc_path(&st.doc, &name)?.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; - }; - let mut knots: Vec<_> = s.knots.iter().map(|k| (knot_points(k), k.smooth)).collect(); - if reversed { - knots.reverse(); - for (k, _) in &mut knots { - k.swap(1, 2); - } - } - let unlinked = knots.iter().enumerate().filter(|(_, (_, smooth))| !smooth).map(|(i, _)| i).collect(); - let resumes = Resumed { doc, path: name.clone(), index: i, was: s.clone() }; - Some(PenPath { knots: knots.into_iter().map(|(k, _)| k).collect(), unlinked, resumes: Some(resumes), ..Default::default() }) - }) -} - -/// The resumed path with its subpath carried on: the one subpath of `drawn` takes the old one's -/// anchors and closing, which keeps its other settings (its path operation). `None` when the -/// subpath is no longer the one drawing resumed (another document, or the path changed). -fn with_resumed_subpath(doc: &Document, r: &Resumed, drawn: &Value) -> Option { - let path = doc_path(doc, &r.path).filter(|_| doc.id.0 == r.doc)?; - if path.subpaths.get(r.index) != Some(&r.was) { - return None; - } - let mut p = photocraft_engine::vector_cmds::path_json(path); - let slot = p.get_mut("subpaths")?.as_array_mut()?.get_mut(r.index)?.as_object_mut()?; - let new = drawn.get("subpaths")?.get(0)?; - for key in ["closed", "knots"] { - slot.insert(key.into(), new.get(key)?.clone()); - } - Some(p) -} - -// --------------------------------------------------------------------------------------------- -// Freeform Pen and Curvature Pen - -/// Freeform Pen release: fit the drag's trace within the options bar's Curve Fit and commit it -/// as the Pen does. Releasing on the start point closes the path; a click draws nothing. The -/// points at indices `straight` were ⌥-clicked: the segment into each one stays straight. -pub fn freeform_finish(app: &mut PhotocraftApp, points: &[[f64; 3]], straight: &[usize]) { - let trace: Vec<[f64; 2]> = points.iter().map(|p| [p[0], p[1]]).collect(); - let (Some(first), Some(last)) = (trace.first(), trace.last()) else { return }; - let tol = 6.0 / app.point_zoom().max(0.01) as f64; - let length: f64 = trace.windows(2).map(|w| (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1])).sum(); - let closed = (first[0] - last[0]).hypot(first[1] - last[1]) < tol && length > 4.0 * tol; - let fit = f64::from(app.ui.tool_options.curve_fit); - let pen = if straight.is_empty() { - let Some(sub) = photocraft_vector::trace::fit_trace(&trace, fit, closed) else { return }; - let knots = sub.knots.iter().map(knot_points).collect(); - let unlinked = sub.knots.iter().enumerate().filter(|(_, k)| !k.smooth).map(|(i, _)| i).collect(); - (PenPath { knots, unlinked, ..Default::default() }, sub.closed) - } else { - fit_with_straight_segments(&trace, straight, fit, closed.then_some(tol)) - }; - commit_path(app, &pen.0, pen.1); -} - -fn knot_points(k: &photocraft_doc::Knot) -> [[f64; 2]; 3] { - [[k.anchor.x, k.anchor.y], [k.in_ctrl.x, k.in_ctrl.y], [k.out_ctrl.x, k.out_ctrl.y]] -} - -/// A Freeform Pen trace with ⌥-clicked straight segments (into the points at `straight`): each -/// freehand run between them is fitted on its own, and the runs are joined by straight lines -/// between corner anchors. `close` (a reach) closes the path when it ends on its start point. -fn fit_with_straight_segments(trace: &[[f64; 2]], straight: &[usize], fit: f64, close: Option) -> (PenPath, bool) { - let mut cuts: Vec = straight.iter().copied().filter(|&i| i > 0 && i < trace.len()).collect(); - cuts.sort_unstable(); - cuts.dedup(); - cuts.push(trace.len()); - let (mut knots, mut corners): (Vec<[[f64; 2]; 3]>, Vec) = (Vec::new(), Vec::new()); - let mut start = 0; - for end in cuts { - let run = trace.get(start..end).unwrap_or_default(); - let first = knots.len(); - match photocraft_vector::trace::fit_trace(run, fit, false) { - Some(sub) => { - corners.extend(sub.knots.iter().enumerate().filter(|(_, k)| !k.smooth).map(|(i, _)| first + i)); - knots.extend(sub.knots.iter().map(knot_points)); - } - // A single click (or a run that never moved): one corner anchor. - None => knots.extend(run.first().map(|p| [*p; 3])), - } - // Where a straight segment meets the run: a corner with no handle on that side. - if let Some(k) = knots.get_mut(first).filter(|_| first > 0) { - k[1] = k[0]; - corners.push(first); - } - if end < trace.len() - && let Some(k) = knots.last_mut() - { - k[2] = k[0]; - corners.push(knots.len() - 1); - } - start = end; - } - // Ended on the start point: the last anchor is the first one. - let ends_on_start = |k: &[[[f64; 2]; 3]], reach: f64| match (k.first(), k.last()) { - (Some(a), Some(b)) => k.len() > 3 && (a[0][0] - b[0][0]).hypot(a[0][1] - b[0][1]) < reach, - _ => false, - }; - let closed = close.is_some_and(|reach| ends_on_start(&knots, reach)); - if closed && let Some(last) = knots.pop() { - if let Some(k) = knots.first_mut() { - k[1] = [last[1][0] - last[0][0] + k[0][0], last[1][1] - last[0][1] + k[0][1]]; - } - corners.retain(|&i| i < knots.len()); - corners.push(0); - } - corners.sort_unstable(); - corners.dedup(); - (PenPath { knots, unlinked: corners, ..Default::default() }, closed) -} - -/// Recompute a Curvature Pen path's handles from its anchors and corner points. -fn curvature_refresh(pen: &mut PenPath, closed: bool) { - let anchors: Vec<[f64; 2]> = pen.knots.iter().map(|k| k[0]).collect(); - let corners: Vec = (0..anchors.len()).map(|i| pen.unlinked.contains(&i)).collect(); - pen.knots = photocraft_vector::edit::curvature_knots(&anchors, &corners, closed); -} - -/// The anchor of the Curvature Pen path being drawn under (x, y), for the cursor. -pub(crate) fn curvature_anchor_at(app: &PhotocraftApp, x: f64, y: f64) -> Option { - curvature_hit(app, x, y) -} - -/// The Curvature Pen's anchor within a few screen pixels of (x, y). -fn curvature_hit(app: &PhotocraftApp, x: f64, y: f64) -> Option { - let tol = 6.0 / app.point_zoom().max(0.01) as f64; - let pen = app.ui.pen.as_ref().filter(|p| p.curvature)?; - pen.knots - .iter() - .enumerate() - .map(|(i, k)| (i, (k[0][0] - x).hypot(k[0][1] - y))) - .filter(|(_, d)| *d < tol) - .min_by(|a, b| a.1.total_cmp(&b.1)) - .map(|(i, _)| i) -} - -/// Curvature Pen press: clicking the first anchor closes the path, pressing another anchor -/// grabs it to move, anywhere else adds a smooth anchor (still draggable until the release). -pub fn curvature_down(app: &mut PhotocraftApp, x: f64, y: f64) { - if !cancel_stale(app) { - return; - } - if app.ui.pen.as_ref().is_some_and(|p| !p.curvature) { - pen_commit(app, false); - } - let hit = curvature_hit(app, x, y); - if hit == Some(0) && app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 3) { - pen_commit(app, true); - return; - } - if app.ui.pen.is_none() { - app.ui.pen_doc = app.session.active().map(|st| st.doc.id); - } - let pen = app.ui.pen.get_or_insert_with(|| PenPath { curvature: true, ..Default::default() }); - if hit.is_none() { - pen.knots.push([[x, y]; 3]); - } - pen.moving = hit.or(pen.knots.len().checked_sub(1)); - curvature_refresh(pen, false); -} - -pub fn curvature_move(app: &mut PhotocraftApp, x: f64, y: f64) { - if let Some(pen) = app.ui.pen.as_mut().filter(|p| p.curvature) - && let Some(k) = pen.moving.and_then(|i| pen.knots.get_mut(i)) - { - k[0] = [x, y]; - curvature_refresh(pen, false); - } -} - -pub fn curvature_up(app: &mut PhotocraftApp) { - if let Some(pen) = app.ui.pen.as_mut() { - pen.moving = None; - } -} - -/// Curvature Pen double-click: toggle the anchor under the pointer between smooth and corner -/// (double-clicking empty canvas therefore places a corner point, as in Photoshop). With no path -/// being drawn, an anchor of the active path toggles the same way and its subpath reflows -/// (`path.convertPoint` with `curvature`), so a Pen-drawn corner rounds off. -pub fn curvature_toggle(app: &mut PhotocraftApp, x: f64, y: f64) { - if app.ui.pen.as_ref().is_none_or(|p| p.knots.is_empty()) { - crate::direct_select::curvature_toggle_active(app, [x, y]); - return; - } - let Some(i) = curvature_hit(app, x, y) else { return }; - let Some(pen) = app.ui.pen.as_mut() else { return }; - if let Some(at) = pen.unlinked.iter().position(|&c| c == i) { - pen.unlinked.remove(at); - } else { - pen.unlinked.push(i); - } - curvature_refresh(pen, false); -} - -/// The path that path commands act on without a name: the one selected in the Paths panel, else -/// the work path, else the selected layer's shape path or vector mask; `None` when there's none. -pub fn active_path_name(app: &PhotocraftApp) -> Option { - let st = app.session.active()?; - let rows = path_rows(&st.doc, st.active_layer); - let key = |r: &PathEntry| match r.kind { - PathRow::Work => "work".to_string(), - PathRow::Layer => "layer".to_string(), - PathRow::Saved => r.name.clone(), - }; - let selected = app.ui.selected_path.as_deref().filter(|s| rows.iter().any(|r| key(r) == *s)).map(str::to_string); - selected.or_else(|| rows.iter().find(|r| r.kind == PathRow::Work).map(key)).or_else(|| rows.iter().find(|r| r.kind == PathRow::Layer).map(key)) -} - -/// The commands that create a fill or adjustment layer and take a `"path"` as its vector mask. -pub fn takes_path_mask(id: &str) -> bool { - id.starts_with("layer.newFillLayer.") || id.starts_with("layer.newAdjustmentLayer.") -} - -/// The work or saved path explicitly selected in the Paths panel (not a layer's own path). -pub fn selected_document_path(app: &PhotocraftApp) -> Option { - let st = app.session.active()?; - let sel = app.ui.selected_path.as_deref()?; - let listed = path_rows(&st.doc, st.active_layer).iter().any(|r| match r.kind { - PathRow::Work => sel == "work", - PathRow::Saved => r.name == sel, - PathRow::Layer => false, - }); - listed.then(|| sel.to_string()) -} - -/// New fill and adjustment layers take the path selected in the Paths panel as their vector mask, -/// as in Photoshop (#1419): the command gets it as `"path"` unless the caller set one (`null` -/// opts out). Only an explicitly selected work or saved path counts; deselect it by clicking the -/// panel's empty area. -pub fn with_active_path(app: &PhotocraftApp, id: &str, params: Value) -> Value { - if !takes_path_mask(id) || params.get("path").is_some() { - return params; - } - let Some(sel) = selected_document_path(app) else { return params }; - match params { - Value::Object(mut m) => { - m.insert("path".into(), json!(sel)); - Value::Object(m) - } - _ => json!({ "path": sel }), - } -} - -/// ⌘↩ / Ctrl+Enter (#306): load a path as a selection, like Photoshop with a Pen or Path -/// Selection tool or a path selected in the Paths panel. A path being drawn with the Pen is -/// finished first and loads; otherwise [`active_path_name`]. `params` may set feather, mode… -pub fn path_to_selection(app: &mut PhotocraftApp, params: Value) -> Result { - if app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2) { - // The finished path becomes the work path, or a shape layer's path or a vector mask. - let on_layer = app.ui.tool_options.vector_mode == "shape" || targeted_vector_mask(app).is_some(); - pen_commit(app, false); - app.ui.selected_path = Some(if on_layer { "layer" } else { "work" }.into()); - } - let name = active_path_name(app) - .ok_or_else(|| tl!("No path to make a selection from: draw one with the Pen tool or select one in the Paths panel.").to_string())?; - let mut p = params.as_object().cloned().unwrap_or_default(); - p.insert("name".into(), json!(name)); - app.run("path.toSelection", Value::Object(p)) -} - -// --------------------------------------------------------------------------------------------- -// Path Selection - -/// What Path Selection edits. -enum PathTarget { - Shape(u64), - /// The active layer's vector mask, when its Layers thumbnail is targeted (#196). - VectorMask(u64), - Work, -} - -/// The targeted vector mask of the active layer, if the Layers panel targets it. -pub(crate) fn targeted_vector_mask(app: &PhotocraftApp) -> Option<(u64, Path)> { - let st = app.session.active()?; - let l = st.active_layer.and_then(|id| st.doc.layer(id))?; - let targeted = app.ui.vector_mask_target || st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::VectorMask; - (targeted && !matches!(l.content, LayerContent::Shape(_))).then_some(())?; - l.vector_mask.as_ref().map(|m| (l.id.0, m.path.clone())) -} - -/// The active shape layer's path, if the active layer is a shape layer. -pub(crate) fn active_shape_path(app: &PhotocraftApp) -> Option<(u64, Path)> { - let st = app.session.active()?; - let l = st.active_layer.and_then(|id| st.doc.layer(id))?; - match &l.content { - LayerContent::Shape(sh) => Some((l.id.0, sh.path.clone())), - _ => None, - } -} - -/// Does ⌫ / Delete delete the work path? With the Pen, Freeform Pen or Path Selection tool, no -/// path being drawn and the work path the one these tools show and edit (no shape layer or -/// targeted vector mask in front of it), as in Photoshop (#5702). It was drawn whenever one of -/// these tools was active, but the key reached Edit › Clear, so it looked impossible to delete. -/// Direct Selection and the Curvature Pen delete selected anchors in Photoshop, not the path. -pub(crate) fn delete_key_deletes_work_path(app: &PhotocraftApp) -> bool { - matches!(app.ui.tool, Tool::Pen | Tool::FreeformPen | Tool::PathSelection) - && app.ui.pen.is_none() - && app.ui.transform.is_none() - && app.ui.view.shows(app.ui.view.show.target_path) - && matches!(target_path(app), Some((PathTarget::Work, _))) -} - -/// The path Path Selection edits: the targeted vector mask, the active shape layer's path, else -/// the work path. -fn target_path(app: &PhotocraftApp) -> Option<(PathTarget, Path)> { - if let Some((id, p)) = targeted_vector_mask(app) { - return Some((PathTarget::VectorMask(id), p)); - } - if let Some((id, p)) = active_shape_path(app) { - return Some((PathTarget::Shape(id), p)); - } - app.session.active()?.doc.work_path.clone().map(|p| (PathTarget::Work, p)) -} - -/// Edit › Free Transform Path (⌘T with Path Selection or Direct Selection): the path the -/// box transforms (the one Path Selection edits) and `path.transform`'s params that name it. -pub(crate) fn free_transform_path(app: &PhotocraftApp) -> Option<(Value, Path)> { - if !matches!(app.ui.tool, Tool::PathSelection | Tool::DirectSelection) { - return None; - } - let (target, path) = target_path(app)?; - path.control_bounds()?; - let params = match target { - PathTarget::Shape(id) | PathTarget::VectorMask(id) => json!({"name": "layer", "layer": id}), - PathTarget::Work => json!({"name": "work"}), - }; - Some((params, path)) -} - -fn point_in_subpath(sp: &photocraft_doc::vector::Subpath, pt: [f64; 2]) -> bool { - if !sp.closed || sp.knots.len() < 3 { - return false; - } - let mut inside = false; - let n = sp.knots.len(); - for i in 0..n { - let j = (i + 1) % n; - let xi = sp.knots[i].anchor.x; - let yi = sp.knots[i].anchor.y; - let xj = sp.knots[j].anchor.x; - let yj = sp.knots[j].anchor.y; - let intersect = ((yi > pt[1]) != (yj > pt[1])) && (pt[0] < (xj - xi) * (pt[1] - yi) / (yj - yi) + xi); - if intersect { - inside = !inside; - } - } - inside -} - -/// The topmost visible shape layer under `at` (document coordinates): -/// hits the shape path or anchor within `tol`, or any non-transparent pixel of the shape's raster surface, -/// or point inside the shape's filled geometry. -pub fn pick_shape_at(doc: &Document, at: [f64; 2], tol: f64) -> Option { - let (x, y) = (at[0].floor() as i32, at[1].floor() as i32); - for (path, _, l) in doc.walk().iter().rev() { - if !l.visible || !(1..=path.len()).all(|n| doc.layer_at(&path[..n]).is_some_and(|a| a.visible)) { - continue; - } - let board = path.first().and_then(|i| doc.layers.get(*i)).and_then(|t| t.artboard()); - if board.is_some_and(|a| !a.rect.contains(x, y)) { - continue; - } - if let LayerContent::Shape(sh) = &l.content { - if photocraft_vector::edit::hit(&sh.path, photocraft_geom::Point::new(at[0], at[1]), tol, &[]).is_some() { - return Some(l.id); - } - if sh.fill.is_some() { - if let Some(surf) = l.surface() { - let mut px = [[0.0f32; 4]; 1]; - surf.read_rgba_into(photocraft_doc::Rect::from_xywh(x, y, 1, 1), &mut px); - if px[0][3] > 0.0 { - return Some(l.id); - } - } - if let Some(photocraft_doc::LiveShape::Rect { rect, .. }) = &sh.live { - let x0 = rect[0].min(rect[0] + rect[2]); - let x1 = rect[0].max(rect[0] + rect[2]); - let y0 = rect[1].min(rect[1] + rect[3]); - let y1 = rect[1].max(rect[1] + rect[3]); - if at[0] >= x0 && at[0] <= x1 && at[1] >= y0 && at[1] <= y1 { - return Some(l.id); - } - } - if let Some(photocraft_doc::LiveShape::Ellipse { rect }) = &sh.live { - let rx = rect[2].abs() / 2.0; - let ry = rect[3].abs() / 2.0; - if rx > 1e-6 && ry > 1e-6 { - let cx = rect[0] + rect[2] / 2.0; - let cy = rect[1] + rect[3] / 2.0; - let dx = (at[0] - cx) / rx; - let dy = (at[1] - cy) / ry; - if dx * dx + dy * dy <= 1.0 { - return Some(l.id); - } - } - } - if sh.path.subpaths.iter().any(|sp| point_in_subpath(sp, at)) { - return Some(l.id); - } - } - } - } - None -} - -pub fn path_selection_finish(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) { - let (dx, dy) = (end[0] - start[0], end[1] - start[1]); - let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); - if dx.abs() + dy.abs() < 0.5 { - let Some(st) = app.session.active() else { return }; - if let Some(id) = pick_shape_at(&st.doc, start, tol) { - let _ = app.run("layer.select", json!({"layer": id.0})); - } - return; - } - if target_path(app).is_none() { - let Some(st) = app.session.active() else { return }; - if let Some(id) = pick_shape_at(&st.doc, start, tol) { - let _ = app.run("layer.select", json!({"layer": id.0})); - } - } - let Some((target, path)) = target_path(app) else { return }; - let _ = match target { - PathTarget::Shape(id) => app.run("shape.edit", json!({"layer": id, "move": [dx.round(), dy.round()]})), - PathTarget::VectorMask(id) => { - let moved = path.transform(&Affine::translate(dx.round(), dy.round())); - app.run("layer.vectorMask.edit", json!({"layer": id, "path": photocraft_engine::vector_cmds::path_json(&moved)})) - } - PathTarget::Work => { - let moved = path.transform(&Affine::translate(dx.round(), dy.round())); - app.run("path.set", json!({"name": "work", "path": photocraft_engine::vector_cmds::path_json(&moved)})) - } - }; -} - -// --------------------------------------------------------------------------------------------- -// Drawing - -fn bezier(p0: [f64; 2], c0: [f64; 2], c1: [f64; 2], p1: [f64; 2], t: f64) -> [f64; 2] { - let u = 1.0 - t; - let f = |a: f64, b: f64, c: f64, d: f64| u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d; - [f(p0[0], c0[0], c1[0], p1[0]), f(p0[1], c0[1], c1[1], p1[1])] -} - -/// `q` lies on the chord from `a` to `d` (within a thousandth of a pixel). -fn on_chord(a: [f64; 2], q: [f64; 2], d: [f64; 2]) -> bool { - let (dx, dy, vx, vy) = (d[0] - a[0], d[1] - a[1], q[0] - a[0], q[1] - a[1]); - let len = dx.hypot(dy); - if len < 1e-9 { - return vx.hypot(vy) < 1e-3; - } - let t = (vx * dx + vy * dy) / (len * len); - (vx * dy - vy * dx).abs() / len < 1e-3 && (-1e-9..=1.0 + 1e-9).contains(&t) -} - -/// How far (in screen pixels) a drawn chord may stray from the true curve. -const CURVE_TOLERANCE: f64 = 0.3; -/// Pieces per segment at most: 0.3 px holds for curves bending up to about 1.4 million px on screen. -const MAX_CURVE_PIECES: usize = 1024; - -/// Screen points along one cubic segment (both ends included). The control points are mapped to -/// the screen first (`xf` is affine, so the curve maps exactly), and the number of chords follows -/// how much the curve bends there: a straight segment is one chord, and a curve zoomed in stays -/// smooth instead of showing a fixed 16 chords (#4084). Uses the bound -/// `max|B''| / 8n² <= tol` with `max|B''| <= 6·max(|p0−2c0+c1|, |c0−2c1+p1|)`. -pub(crate) fn curve_points(p0: [f64; 2], c0: [f64; 2], c1: [f64; 2], p1: [f64; 2], xf: &dyn Fn([f64; 2]) -> Pos2) -> Vec { - let [a, b, c, d] = [p0, c0, c1, p1].map(|q| { - let s = xf(q); - [f64::from(s.x), f64::from(s.y)] - }); - let second = |p: [f64; 2], q: [f64; 2], r: [f64; 2]| (p[0] - 2.0 * q[0] + r[0]).hypot(p[1] - 2.0 * q[1] + r[1]); - let n = (0.75 * second(a, b, c).max(second(b, c, d)) / CURVE_TOLERANCE).sqrt().ceil(); - // A straight segment (controls on the chord, like the Pen's retracted handles) is one chord; - // NaN (a non-finite point) falls back to one too. - let n = if n.is_finite() && !(on_chord(a, b, d) && on_chord(a, c, d)) { (n as usize).clamp(1, MAX_CURVE_PIECES) } else { 1 }; - (0..=n) - .map(|k| { - let q = bezier(a, b, c, d, k as f64 / n as f64); - pos2(q[0] as f32, q[1] as f32) - }) - .collect() -} - -/// Screen polylines for a path (one per subpath). -pub(crate) fn path_lines(path: &Path, xf: &dyn Fn([f64; 2]) -> Pos2) -> Vec<(Vec, bool)> { - path.subpaths - .iter() - .map(|s| { - let n = s.knots.len(); - let mut pts = Vec::new(); - let segs = if s.closed { n } else { n.saturating_sub(1) }; - for i in 0..segs { - let (a, b) = (&s.knots[i], &s.knots[(i + 1) % n]); - pts.extend(curve_points([a.anchor.x, a.anchor.y], [a.out_ctrl.x, a.out_ctrl.y], [b.in_ctrl.x, b.in_ctrl.y], [b.anchor.x, b.anchor.y], xf)); - } - if pts.is_empty() - && let Some(k) = s.knots.first() - { - pts.push(xf([k.anchor.x, k.anchor.y])); - } - (pts, s.closed) - }) - .collect() -} - -/// A path's outline in the accent colour. -pub(crate) fn draw_outline(painter: &egui::Painter, p: &Path, to_scr: &dyn Fn([f64; 2]) -> Pos2, accent: Color32) { - for (pts, closed) in path_lines(p, to_scr) { - if closed { - painter.add(egui::Shape::closed_line(pts, Stroke::new(1.0, accent))); - } else { - painter.add(egui::Shape::line(pts, Stroke::new(1.0, accent))); - } - } -} - -/// An anchor point's square: filled with the accent when selected, else hollow (white). -pub(crate) fn draw_anchor(painter: &egui::Painter, c: Pos2, selected: bool, accent: Color32) { - let r = Rect::from_center_size(c, vec2(6.0, 6.0)); - painter.rect_filled(r, 0.0, if selected { accent } else { Color32::WHITE }); - painter.rect_stroke(r, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside); -} - -/// A direction handle: the line from its anchor and the round handle end. -pub(crate) fn draw_handle(painter: &egui::Painter, anchor: Pos2, handle: Pos2, accent: Color32) { - painter.line_segment([anchor, handle], Stroke::new(1.0, accent)); - painter.circle_filled(handle, 3.0, accent); -} - -/// Does `tool` draw the anchor squares of the paths it can edit? Path Selection does, and so do -/// the Pen tools: as in Photoshop, a path finished with Enter or by closing it keeps its anchors -/// on screen, so it can still be edited (⌘/Ctrl-drag, Auto Add/Delete) (#6884, #4716). -pub(crate) fn shows_anchors(tool: Tool) -> bool { - // Add/Delete Anchor Point and Convert Point draw Direct Selection's overlay instead. - matches!(tool, Tool::PathSelection | Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen) -} - -/// The saved path selected in the Paths panel: Photoshop's target path, drawn on the canvas with -/// any tool (#6550). `None` when the panel selects the work path, a layer's path or nothing. -pub(crate) fn selected_saved_path(app: &PhotocraftApp) -> Option<&Path> { - let sel = app.ui.selected_path.as_deref().filter(|s| !matches!(*s, "work" | "layer"))?; - app.session.active()?.doc.paths.iter().find(|p| p.name == sel).map(|p| &p.path) -} - -/// Work path / active shape path / selected saved path outlines, anchors, and the pen path in -/// progress. -pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, doc: &Document) { - let tool = app.ui.tool; - let accent = Tokens::get(painter.ctx()).accent; - let to_scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32); - let draw_path = |p: &Path, anchors: bool| { - draw_outline(painter, p, &to_scr, accent); - if anchors { - for k in p.subpaths.iter().flat_map(|s| &s.knots) { - draw_anchor(painter, to_scr([k.anchor.x, k.anchor.y]), false, accent); - } - } - }; - // View › Show › Target Path (under Extras) hides the paths; the Pen's path in progress stays. - // Free Transform Path draws the path through its box instead (transform_tool). - let paths = app.ui.view.shows(app.ui.view.show.target_path) && app.ui.transform.as_ref().is_none_or(|t| t.path.is_none()); - if app.session.active().is_some_and(|st| st.doc.id == doc.id) && crate::direct_select::shows(app, painter.ctx().input(|i| i.modifiers)) { - // Direct Selection (or the Pen with ⌘/Ctrl held) draws the paths it edits (#790). - crate::direct_select::draw_overlay(app, painter, &to_scr, accent, paths); - if paths { - // The selected saved path shows too, though Direct Selection doesn't edit it yet. - if let Some(p) = selected_saved_path(app) { - draw_path(p, true); - } - crate::anchor_tools::draw_hover(app, painter, &to_scr, accent, painter.ctx().input(|i| i.modifiers)); - } - } else if paths { - // The shape's or vector mask's path stays visible as an outline with any tool. Path - // Selection and the Pen tools add anchor squares; Direct Selection has its own overlay - // above. The Work Path is drawn only while it is the path selected in the Paths panel or - // a path tool is active, as in Photoshop: a Work Path left unselected (one a PSD arrived - // with, or after Ctrl-click Load as Selection) would otherwise cover the marching ants (#6551). - let anchors = shows_anchors(tool); - if let Some(wp) = &doc.work_path - && (anchors || app.ui.selected_path.as_deref() == Some("work")) - { - draw_path(wp, anchors); - } - // The saved path selected in the Paths panel is the target path (#6550). - if let Some(p) = selected_saved_path(app) { - draw_path(p, anchors); - } - let st = app.session.active(); - if let Some(l) = st.and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id))) - && let LayerContent::Shape(sh) = &l.content - { - draw_path(&sh.path, anchors); - } - // A targeted vector mask shows its path with any tool (#196). - if let Some((_, p)) = targeted_vector_mask(app) { - draw_path(&p, anchors); - } - crate::corner_radius::draw(app, painter, &to_scr, accent); - } - // Pen path in progress, with handles of the last knot and a rubber band to the pointer. While - // ⌘/Ctrl drags it, Direct Selection draws its preview instead. - let edited = matches!(&app.ui.direct_selection.drag, Some(crate::direct_select::Drag::Edit { target: crate::direct_select::PathRef::Pen, .. })); - // Only on the document it is drawn on: a view of another document never shows it (#5373). - if let Some(pen) = app.ui.pen.as_ref().filter(|_| !edited).filter(|_| app.ui.pen_doc.is_none_or(|d| d == doc.id)) { - let mut pts = Vec::new(); - // A close-drag shows the first segment bending with the handle being pulled out. - let mut knots = pen.knots.clone(); - if closing(pen) - && let Some(&[a, _, out]) = pen.knots.last() - && out != a - && let Some(first) = knots.first_mut() - { - first[2] = out; - } - for w in knots.windows(2) { - pts.extend(curve_points(w[0][0], w[0][2], w[1][1], w[1][0], &to_scr)); - } - painter.add(egui::Shape::line(pts, Stroke::new(1.5, accent))); - // No rubber band where a click adds or deletes an anchor of this path instead (#6140). - let auto = app.hover_doc.is_some_and(|h| crate::anchor_tools::pen_auto(app, tool, painter.ctx().input(|i| i.modifiers), h).is_some()); - if let (Some(last), Some(h)) = (pen.knots.last(), app.hover_doc) - && !pen.dragging - && pen.moving.is_none() - && !auto - { - if pen.curvature && pen.knots.len() >= 2 { - // The Curvature Pen previews the curve the next click makes through the pointer. - let mut next = pen.clone(); - next.knots.push([h; 3]); - curvature_refresh(&mut next, false); - if let [.., a, b] = next.knots.as_slice() { - let pts = curve_points(a[0], a[2], b[1], b[0], &to_scr); - painter.add(egui::Shape::dashed_line(&pts, Stroke::new(1.0, accent), 4.0, 3.0)); - } - } else { - // The rubber band ends where a ⇧-click would put the next anchor. - let shift = painter.ctx().input(|i| i.modifiers.shift); - let h = if pen.curvature { h } else { shift_45(last[0], h, shift) }; - painter.add(egui::Shape::dashed_line(&[to_scr(last[0]), to_scr(h)], Stroke::new(1.0, accent), 4.0, 3.0)); - } - } - for (i, k) in pen.knots.iter().enumerate() { - let c = to_scr(k[0]); - let last = i + 1 == pen.knots.len(); - if last && k[2] != k[0] && !pen.curvature { - for hnd in [k[1], k[2]] { - draw_handle(painter, c, to_scr(hnd), accent); - } - } - draw_anchor(painter, c, last, accent); - } - // Hovering the first anchor: Photoshop's close cue, a small ring beside the pointer. - let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); - if let Some(h) = app.hover_doc - && over_first_anchor(pen, h, tol) - && let Some(first) = pen.knots.first() - { - let c = to_scr(first[0]); - painter.rect_filled(Rect::from_center_size(c, vec2(8.0, 8.0)), 0.0, accent); - painter.circle_stroke(c + vec2(11.0, 11.0), 3.5, Stroke::new(1.5, accent)); - } - } - // The segment the Pen's Auto Add/Delete would add an anchor to, or the anchor it would delete, - // over the path being drawn. While drawing, the other paths can be hidden: it edits none of them. - if paths || app.ui.pen.is_some() { - crate::anchor_tools::draw_pen_hover(app, painter, &to_scr, accent, painter.ctx().input(|i| i.modifiers)); - } -} - -// --------------------------------------------------------------------------------------------- -// Options bars - -/// Options bar for vector tools; false for other tools. -pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool { - if !(is_shape_tool(tool) - || matches!( - tool, - Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::PathSelection | Tool::DirectSelection - )) - { - return false; - } - let t = Tokens::get(ui.ctx()); - let lbl = |ui: &mut egui::Ui, s: &str| { - let label = ui.label(egui::RichText::new(s).color(t.text_dim).size(12.0)); - // The caption scrubs and names the control drawn right after it. - crate::widgets::scrub_option_label(ui, &label); - }; - let o = &mut app.ui.tool_options; - let target = selected_shape(&app.session); - if tool == Tool::PathSelection && target.is_none() { - lbl(ui, if app.ui.vector_mask_target { "Drag to move the targeted vector mask" } else { tl!("Drag to move the active shape's path or the Work Path") }); - return true; - } - if tool == Tool::DirectSelection && target.is_none() { - let (shift, alt) = (crate::shortcuts::pretty("Shift"), crate::shortcuts::pretty("Alt")); - lbl( - ui, - &crate::i18n::fmt( - tl!("Click: select anchor · Drag: move anchor, handle or segment · {shift}-click: add · {alt}-click: whole subpath"), - &[("shift", &shift), ("alt", &alt)], - ), - ); - return true; - } - if matches!(tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint) { - let hint = if tool == Tool::AddAnchorPoint { - tl!("Click a segment to add an anchor point · {alt}-click an anchor to delete it") - } else { - tl!("Click an anchor point to delete it · {alt}-click a segment to add one") - }; - lbl(ui, &crate::i18n::fmt(hint, &[("alt", &crate::shortcuts::pretty("Alt"))])); - return true; - } - if matches!(tool, Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen) { - let opts = [("path".to_string(), tl!("Path")), ("shape".to_string(), tl!("Shape"))]; - crate::widgets::dropdown(ui, "pen-mode", tl!("Mode"), &mut o.vector_mode, &opts, 80.0); - crate::widgets::vline(ui, 22.0); - if o.vector_mode == "shape" { - crate::widgets::value_field(ui, &mut o.stroke_width, 0.0..=288.0, "px", 58.0).accessible_name(tl!("Stroke:")); - if let Some(change) = - crate::shape_stroke_ui::button(ui, "pen-stroke", &o.shape_stroke, &mut app.ui.stroke_editor, false, true, None, o.stroke_width > 0.0) - { - o.shape_stroke = change.options; - o.stroke_width = enabled_stroke_width(o.stroke_width); - } - } - if tool == Tool::Pen { - crate::widgets::vline(ui, 22.0); - crate::widgets::checkbox(ui, &mut o.pen_auto_add_delete, tl!("Auto Add/Delete")); - } - let enter = crate::shortcuts::pretty("Enter"); - match tool { - Tool::FreeformPen => { - crate::widgets::vline(ui, 22.0); - lbl(ui, tl!("Curve Fit:")); - crate::widgets::value_field(ui, &mut o.curve_fit, 0.5..=10.0, "px", 58.0); - let alt = crate::shortcuts::pretty("Alt"); - lbl(ui, &crate::i18n::fmt(tl!("Drag: draw freehand · {alt}-click: straight segment · Release on the start point: close"), &[("alt", &alt)])); - } - Tool::CurvaturePen => lbl( - ui, - &crate::i18n::fmt( - tl!("Click: smooth point · Double-click: corner · Drag a point: move · Click first point: close · {key} finish"), - &[("key", &enter)], - ), - ), - _ => lbl( - ui, - &crate::i18n::fmt( - tl!("Click: corner · Drag: smooth · {alt}-drag: break handle · Click or drag first point: close · {key} finish · Esc cancel"), - &[("alt", &crate::shortcuts::pretty("Alt")), ("key", &enter)], - ), - ), - } - // Path mode: Make Selection from the path being drawn or the active path, as Photoshop's - // options bar's "Make: Selection…" does (#5703). - if app.ui.tool_options.vector_mode == "path" { - crate::widgets::vline(ui, 22.0); - let has_path = active_path_name(app).is_some() || app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); - if ui.add_enabled(has_path, egui::Button::new(tl!("Make Selection"))).clicked() - && let Err(e) = crate::canvas_tool_menu::make_selection(app) - { - app.ui.status = e; - app.ui.status_error = true; - } - } - return true; - } - let mut mode = "shape".to_string(); - crate::widgets::dropdown(ui, "shape-mode", tl!("Mode"), &mut mode, &[("shape".to_string(), tl!("Shape"))], 80.0); - crate::widgets::vline(ui, 22.0); - crate::shape_options::options_bar(app, ui, tool); - true -} - -/// Whether the active layer supplies the selected-shape options. -fn selected_shape(session: &photocraft_engine::Session) -> Option { - let st = session.active()?; - let layer = st.active_layer?; - matches!(st.doc.layer(layer)?.content, LayerContent::Shape(_)).then_some(layer) -} - -// --------------------------------------------------------------------------------------------- -// Properties (shape layers) - -fn solid_paint(c: [f32; 4]) -> photocraft_doc::Fill { - photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(c[0], c[1], c[2], c[3])) -} - -pub(crate) fn enabled_stroke_width(width: f32) -> f32 { - if width.is_finite() && width > 0.0 { width } else { 3.0 } -} - -/// One corner of the live rectangle, preserving the other three radii. -/// The engine takes the full [top-left, top-right, bottom-right, bottom-left] array. -fn corner_radii_patch(radii: [f64; 4], corner: usize, radius: f32) -> Value { - let mut next = radii; - if let Some(r) = next.get_mut(corner) { - *r = f64::from(radius.max(0.0)); - } - json!({"radii": next}) -} - -/// Follow the existing brush/mask continuous-edit convention: one history state per press or -/// keyboard edit, with every value tick of a held-pointer gesture sharing its key. -pub(crate) fn paint_gesture(ui: &egui::Ui, key: egui::Id) -> u64 { - let pass = ui.ctx().cumulative_pass_nr(); - let pressed = ui.input(|i| i.pointer.any_pressed()); - ui.data_mut(|d| { - let gesture = d.get_temp_mut_or_default::<(u64, u64)>(key); - if pressed && gesture.1 != pass { - gesture.0 = gesture.0.wrapping_add(1); - gesture.1 = pass; - } - gesture.0 - }) -} - -/// Properties panel for a shape layer: Appearance (fill, stroke) and live shape geometry. -pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocraft_doc::LayerId) { - if app.session.active().is_some_and(|st| { - let locks = st.doc.effective_locks(id); - locks.all || locks.pixels - }) { - ui.disable(); - } - let Some(sh) = app.session.active().and_then(|s| s.doc.layer(id)).and_then(|l| match &l.content { - LayerContent::Shape(sh) => Some(sh.clone()), - _ => None, - }) else { - return; - }; - let t = Tokens::get(ui.ctx()); - let mut edit: Option = None; - let doc_id = app.session.active().map(|st| st.doc.id); - let key = |k: &str| format!("shape-{doc_id:?}-{}-{k}", id.0); - let gesture_key = ui.scope_id().with(key("paint-gesture")); - let gesture = paint_gesture(ui, gesture_key); - let coalesce = |field: &str| format!("{}:{}:{gesture}", key(field), gesture_key.value()); - // The shared collapsible section headers (#155). - // Prefs "Appearance" is theme chrome (Giao diện); shape fill/stroke is Diện mạo. - if crate::props_layout::section(ui, "appearance", crate::i18n::tr_ctx(crate::i18n::current(), "shape", "Appearance")) { - ui.horizontal(|ui| { - ui.label(egui::RichText::new(tl!("Fill")).color(t.text_dim).size(12.0)); - let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); - let mut gradients = GradientChoices { - presets: &app.session.presets.gradients, - current: &app.session.presets.gradient, - recent: &mut app.ui.recent_gradients, - fg, - bg, - }; - if let Some(change) = swatch(ui, sh.fill.as_ref(), fg, tl!("Set shape fill type"), &mut gradients) { - let fill = match change { - PaintChange::None => Value::Null, - PaintChange::Color(color) => json!(color), - PaintChange::Gradient(g) => paint_param(&g), - }; - edit = Some(json!({"fill": fill, "coalesce": coalesce("fill")})); - } - ui.add_space(12.0); - ui.label(egui::RichText::new(tl!("Stroke")).color(t.text_dim).size(12.0)); - if let Some(change) = swatch(ui, sh.stroke.as_ref().map(|s| &s.paint), fg, tl!("Set shape stroke type"), &mut gradients) { - let width = enabled_stroke_width(sh.stroke.as_ref().map_or(0.0, |s| s.width)); - let stroke = match change { - PaintChange::None => Value::Null, - PaintChange::Color(color) => json!({"color": color, "width": width}), - PaintChange::Gradient(g) => json!({"color": paint_param(&g), "width": width}), - }; - edit = Some(json!({"stroke": stroke, "coalesce": coalesce("stroke")})); - } - let mut w = sh.stroke.as_ref().map_or(0.0, |s| s.width); - if crate::widgets::value_field(ui, &mut w, 0.0..=288.0, "px", 60.0).accessible_name(tl!("Stroke:")).changed() && (sh.stroke.is_some() || w > 0.0) { - edit = Some(json!({"stroke": {"width": w}, "coalesce": coalesce("stroke-w")})); - } - }); - let style = sh.stroke.as_ref().map(crate::shape_stroke_ui::StrokeOptions::from).unwrap_or_default(); - let stroke_enabled = sh.stroke.as_ref().is_some_and(|stroke| stroke.width > 0.0); - if let Some(change) = crate::shape_stroke_ui::button( - ui, - &key("style"), - &style, - &mut app.ui.stroke_editor, - sh.path.subpaths.iter().all(|s| s.closed), - !matches!(sh.live, Some(photocraft_doc::LiveShape::Ellipse { .. })), - app.session.active().map(|st| (st.doc.id, id)), - stroke_enabled, - ) { - let mut stroke = change.options.params(); - if !stroke_enabled { - stroke["width"] = json!(3.0); - } - edit = Some(json!({"stroke": stroke, "coalesce": change.coalesce})); - } - } - if let Some(live) = &sh.live - && crate::props_layout::section(ui, "liveShape", tl!("Shape")) - { - let num = |ui: &mut egui::Ui, label: &str, v: &mut f32, range: std::ops::RangeInclusive, unit: &str| -> bool { - ui.label(egui::RichText::new(tl!(&label)).color(t.text_dim).size(12.0)); - crate::widgets::value_field(ui, v, range, unit, 64.0).accessible_name(tl!(&label)).changed() - }; - match live { - photocraft_doc::vector::LiveShape::Rect { rect, .. } - | photocraft_doc::vector::LiveShape::Ellipse { rect } - | photocraft_doc::vector::LiveShape::Polygon { rect, .. } => { - ui.horizontal(|ui| { - let (mut w, mut h) = (rect[2] as f32, rect[3] as f32); - let cw = num(ui, "W", &mut w, 1.0..=300000.0, "px"); - let ch = num(ui, "H", &mut h, 1.0..=300000.0, "px"); - if cw || ch { - edit = Some(json!({"rect": [rect[0], rect[1], w.round(), h.round()], "coalesce": key("wh")})); - } - }); - } - photocraft_doc::vector::LiveShape::Line { .. } => {} - } - ui.vertical(|ui| match live { - photocraft_doc::vector::LiveShape::Rect { radii, .. } => { - // Keep the uniform workflow available after independent corner edits too. - ui.horizontal(|ui| { - let mut all = radii[0] as f32; - if num(ui, tl!("Corner radius"), &mut all, 0.0..=100000.0, "px") { - edit = Some(json!({"radii": all, "coalesce": key("radius-all")})); - } - }); - // Separate rows also fit the narrow Properties dock. The labels use the - // localized corner names, rather than untranslated abbreviations. - for (index, label) in [(0, tl!("Top Left")), (1, tl!("Top Right")), (3, tl!("Bottom Left")), (2, tl!("Bottom Right"))] { - ui.horizontal(|ui| { - let mut radius = radii[index] as f32; - if num(ui, label, &mut radius, 0.0..=100000.0, "px") { - let mut patch = corner_radii_patch(*radii, index, radius); - patch["coalesce"] = json!(key(&format!("radius-{index}"))); - edit = Some(patch); - } - }); - } - } - photocraft_doc::vector::LiveShape::Polygon { sides, star_ratio, corner_radius, .. } => { - // One radius rounds every vertex of a triangle, polygon or star, as in Photoshop. - ui.horizontal(|ui| { - let mut r = *corner_radius as f32; - if num(ui, tl!("Corner radius"), &mut r, 0.0..=100000.0, "px") { - edit = Some(json!({"cornerRadius": r, "coalesce": key("corner-radius")})); - } - }); - ui.horizontal(|ui| { - let mut n = *sides as f32; - if num(ui, tl!("Sides"), &mut n, 3.0..=100.0, "") { - edit = Some(json!({"sides": n.round() as u32, "coalesce": key("sides")})); - } - let mut sr = (*star_ratio * 100.0) as f32; - if num(ui, tl!("Star ratio"), &mut sr, 1.0..=100.0, "%") { - edit = Some(json!({"starRatio": sr as f64 / 100.0, "coalesce": key("star")})); - } - }) - .inner - } - photocraft_doc::vector::LiveShape::Line { weight, .. } => { - ui.horizontal(|ui| { - let mut w = *weight as f32; - if num(ui, tl!("Weight"), &mut w, 1.0..=10000.0, "px") { - edit = Some(json!({"weight": w, "coalesce": key("weight")})); - } - }) - .inner - } - _ => {} - }); - } - if let Some(mut p) = edit { - p["layer"] = json!(id.0); - if let Err(e) = app.run("shape.edit", p) { - app.ui.status = e; - app.ui.status_error = true; - } - if !ui.input(|i| i.pointer.any_down()) { - ui.data_mut(|d| { - let gesture = d.get_temp_mut_or_default::<(u64, u64)>(gesture_key); - gesture.0 = gesture.0.wrapping_add(1); - }); - } - } -} - -// --------------------------------------------------------------------------------------------- -// Paths panel - -fn thumb(ui: &egui::Ui, r: Rect, path: &Path, doc: &Document) { - let t = Tokens::get(ui.ctx()); - // At the document's aspect ratio, like the Channels thumbnails. - let r = crate::channels_panel::fit_thumb(r, doc.size.width, doc.size.height).0; - ui.painter().rect_filled(r, 0.0, Color32::from_gray(if t.pro { 222 } else { 240 })); - let (w, h) = (doc.size.width.max(1) as f64, doc.size.height.max(1) as f64); - let s = (r.width() as f64 / w).min(r.height() as f64 / h); - let off = r.center() - vec2((w * s) as f32 / 2.0, (h * s) as f32 / 2.0); - let map = |q: [f64; 2]| pos2(off.x + (q[0] * s) as f32, off.y + (q[1] * s) as f32); - for (pts, closed) in path_lines(path, &map) { - if closed && pts.len() >= 3 { - ui.painter().add(egui::Shape::closed_line(pts, Stroke::new(1.0, Color32::from_gray(40)))); - } else { - ui.painter().add(egui::Shape::line(pts, Stroke::new(1.0, Color32::from_gray(40)))); - } - } -} - -/// What a Paths panel row is. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum PathRow { - Saved, - Work, - /// The selected layer's shape path or vector mask (temporary, italic). - Layer, -} - -/// A Paths panel row. -#[derive(Clone, Debug)] -pub struct PathEntry { - pub name: String, - pub path: Path, - pub kind: PathRow, -} - -/// The Paths panel's rows, top to bottom: saved paths, the work path, then the selected layer's -/// shape path (" Shape Path") or vector mask (" Vector Mask"), like Photoshop. -pub fn path_rows(doc: &Document, active: Option) -> Vec { - let mut rows: Vec<_> = doc.paths.iter().map(|p| PathEntry { name: p.name.clone(), path: p.path.clone(), kind: PathRow::Saved }).collect(); - if let Some(wp) = &doc.work_path { - rows.push(PathEntry { name: "Work Path".into(), path: wp.clone(), kind: PathRow::Work }); - } - if let Some(l) = active.and_then(|id| doc.layer(id)) { - let layer_path = match &l.content { - LayerContent::Shape(sh) => Some((format!("{} Shape Path", l.name), sh.path.clone())), - _ => l.vector_mask.as_ref().map(|v| (format!("{} Vector Mask", l.name), v.path.clone())), - }; - if let Some((name, path)) = layer_path { - rows.push(PathEntry { name, path, kind: PathRow::Layer }); - } - } - rows -} - -fn footer_id() -> egui::Id { - egui::Id::unique("paths-footer") -} - -/// A Paths panel row being dragged, for a drop on the trash (#6553): its name and the command -/// that deletes it. -#[derive(Clone, Debug)] -struct PathDrag { - name: String, - cmd: &'static str, - params: Value, -} - -fn path_drag_key() -> egui::Id { - egui::Id::unique("paths-drag") -} - -fn ctx_data_footer(ctx: &egui::Context, r: Rect) { - ctx.data_mut(|d| d.insert_temp(footer_id(), r)); -} - -/// Where the Paths panel's footer buttons were drawn last frame (the rect around them all). -pub fn paths_footer(ctx: &egui::Context) -> Option { - ctx.data(|d| d.get_temp(footer_id())) -} - -/// Photoshop's default name for a saved path: the first free "Path N", counting from the number of -/// saved paths. -fn free_path_name(doc: &Document) -> String { - let mut n = doc.paths.len().saturating_add(1); - while doc.paths.iter().any(|p| p.name == format!("Path {n}")) { - n = n.saturating_add(1); - if n == usize::MAX { - break; - } - } - format!("Path {n}") -} - -/// A Paths panel name being typed in place: the row's key ("work" or the saved path's name) and -/// the text so far. It lives in egui's temp data, like the Channels panel's rename field. -#[derive(Clone)] -struct PathRename { - key: String, - text: String, - focused: bool, -} - -fn rename_id(doc: &Document) -> egui::Id { - egui::Id::unique(("path-rename", doc.id.0)) -} - -/// Commands offered by a Paths row's context menu. The row's path is passed explicitly so a -/// right-click acts on that row even when another path is selected in the panel. `layer` is the -/// layer a `PathRow::Layer` row belongs to (the active layer). -fn path_context_actions(entry: &PathEntry, doc: &Document, layer: Option) -> Vec<(&'static str, &'static str, Value)> { - let key = match entry.kind { - PathRow::Work => "work".to_string(), - PathRow::Layer => "layer".to_string(), - PathRow::Saved => entry.name.clone(), - }; - let mut actions = vec![ - ("Make Selection", "path.toSelection", json!({"name": key})), - ("Fill Path", "path.fill", json!({"name": key})), - ("Stroke Path…", "path.stroke", json!({"name": key})), - ]; - if entry.kind == PathRow::Work { - actions.push(("Save Path", "path.rename", json!({"name": "work", "to": free_path_name(doc)}))); - } else { - let mut n = 1usize; - while doc.paths.iter().any(|p| p.name == format!("{} copy {n}", entry.name)) { - n = n.saturating_add(1); - if n == usize::MAX { - break; - } - } - let copy_name = format!("{} copy {n}", entry.name); - actions.push(("Duplicate Path", "path.set", json!({"name": copy_name, "path": photocraft_engine::vector_cmds::path_json(&entry.path)}))); - } - if entry.kind == PathRow::Saved { - // No `to`: the panel asks for the new name in place. - actions.push(("Rename Path…", "path.rename", json!({"name": key}))); - } - if entry.kind != PathRow::Layer { - actions.push(("Delete Path", "path.delete", json!({"name": key}))); - } else if entry.name.ends_with(" Vector Mask") { - actions.push(("Delete Vector Mask", "layer.vectorMask.delete", json!({}))); - } else if let Some(id) = layer { - // A shape layer's path is the shape: Photoshop's Delete Path deletes the layer (#6552). - actions.push(("Delete Path", "layer.delete", json!({"layer": id.0}))); - } - actions -} - -pub fn paths_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - let Some(st) = app.session.active() else { - ui.label(egui::RichText::new(tl!("No document")).color(t.text_faint)); - return; - }; - let doc = st.doc.clone(); - let st_layer = st.active_layer; - let rows = path_rows(&doc, st_layer); - let has_layer_path = rows.iter().any(|r| r.kind == PathRow::Layer); - let mut action: Option<(&str, Value)> = None; - let mut stroke_dialog: Option = None; - // A row dragged onto the trash is deleted (#6553); a drag that never saw its release must not - // outlive it. - let ctx = ui.ctx().clone(); - if !ctx.input(|i| i.pointer.primary_down() || i.pointer.any_released()) { - ctx.data_mut(|d| d.remove::(path_drag_key())); - } - let drag = ctx.data(|d| d.get_temp::(path_drag_key())); - let rename_id = rename_id(&doc); - // The buttons sit in a footer at the panel's bottom, like Photoshop's. - let footer = crate::widgets::footer_height(ui) + ui.spacing().item_spacing.y; - let fill = ui.available_height() > footer + 60.0; - let rows_h = if fill { ui.available_height() - footer } else { f32::INFINITY }; - egui::ScrollArea::vertical().id_salt("path-rows").max_height(rows_h).min_scrolled_height(if fill { rows_h } else { 0.0 }).auto_shrink([false, !fill]).show( - ui, - |ui| { - if rows.is_empty() { - ui.label(egui::RichText::new(tl!("Draw with the Pen tool (P) or make a work path from a selection.")).color(t.text_faint).size(11.5)); - } - for PathEntry { name, path, kind } in &rows { - // What dropping the row on the trash runs; a shape layer's path is not dragged. - let delete = match kind { - PathRow::Work => Some(("path.delete", json!({"name": "work"}))), - PathRow::Saved => Some(("path.delete", json!({"name": name}))), - PathRow::Layer if name.ends_with(" Vector Mask") => Some(("layer.vectorMask.delete", json!({}))), - PathRow::Layer => None, - }; - let sense = if delete.is_some() { Sense::click_and_drag() } else { Sense::click() }; - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), sense); - let key = match kind { - PathRow::Work => "work".to_string(), - PathRow::Layer => "layer".to_string(), - PathRow::Saved => name.clone(), - }; - if resp.drag_started() - && let Some((cmd, params)) = delete - { - let name = if *kind == PathRow::Work { tl!(name).to_string() } else { name.clone() }; - ui.ctx().data_mut(|d| d.insert_temp(path_drag_key(), PathDrag { name, cmd, params })); - } - // Rows are painted: name them for screen readers and UI tests. - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name)); - let sel = app.ui.selected_path.as_deref() == Some(key.as_str()); - if sel { - ui.painter().rect_filled(r, 0.0, t.row_selected); - } else if resp.hovered() { - ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.5)); - } - let thumbnail = Rect::from_min_size(pos2(r.left() + 8.0, r.top() + 4.0), vec2(28.0, 28.0)); - thumb(ui, thumbnail, path, &doc); - let mut job = egui::text::LayoutJob::default(); - // Temporary paths (the work path, the selected layer's shape path or vector mask) are italic. - let italics = *kind != PathRow::Saved; - job.append( - if *kind == PathRow::Work { tl!(name) } else { name }, - 0.0, - egui::TextFormat { font_id: egui::FontId::proportional(12.0), color: t.text, italics, ..Default::default() }, - ); - let renaming = ui.ctx().data(|d| d.get_temp::(rename_id)).filter(|e| e.key == key); - if let Some(mut edit) = renaming { - let field = Rect::from_min_max(pos2(r.left() + 43.0, r.center().y - 11.0), pos2(r.right() - 8.0, r.center().y + 11.0)); - let id = rename_id.with("field"); - let te = - ui.put(field, egui::TextEdit::singleline(&mut edit.text).id(id).font(egui::FontId::proportional(12.0))).accessible_name(tl!("Name")); - let (enter, esc) = ui.input(|i| (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape))); - if !edit.focused { - te.request_focus(); - // Like Photoshop, the whole name starts selected so typing replaces it. - if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), id) { - let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(edit.text.chars().count())); - state.cursor.set_char_range(Some(all)); - state.store(ui.ctx(), id); - } - edit.focused = true; - ui.ctx().data_mut(|d| d.insert_temp(rename_id, edit)); - } else if esc { - ui.ctx().data_mut(|d| d.remove::(rename_id)); - } else if enter || te.lost_focus() || !te.has_focus() { - ui.ctx().data_mut(|d| d.remove::(rename_id)); - let to = edit.text.trim(); - // The Work Path is saved even under its proposed name; an unchanged saved name is left alone. - if !to.is_empty() && (*kind == PathRow::Work || to != name) { - action = Some(("path.rename", json!({"name": key, "to": to}))); - } - } else { - ui.ctx().data_mut(|d| d.insert_temp(rename_id, edit)); - } - } else { - let g = ui.painter().layout_job(job); - ui.painter().galley(pos2(r.left() + 46.0, r.center().y - g.size().y / 2.0), g, t.text); - } - // Ctrl/Cmd-click loads only the thumbnail's path, without changing the panel target. - let modifiers = ui.input(|i| i.modifiers); - let load = resp.clicked() && modifiers.command && resp.interact_pointer_pos().is_some_and(|p| thumbnail.contains(p)); - if load { - let mode = match crate::channels_panel::load_operation(modifiers) { - "new" => "replace", - mode => mode, - }; - action = Some(("path.toSelection", json!({"name": key, "mode": mode}))); - } else if resp.clicked() { - app.ui.selected_path = Some(key.clone()); - } - // As in Photoshop, double-clicking a saved path's name renames it, and double-clicking - // the Work Path asks for the name to save it under (#6238). - let proposed = match kind { - PathRow::Work => Some(free_path_name(&doc)), - PathRow::Saved => Some(name.clone()), - PathRow::Layer => None, - }; - if !load - && resp.double_clicked() - && let Some(text) = proposed - { - ui.ctx().data_mut(|d| d.insert_temp(rename_id, PathRename { key: key.clone(), text, focused: false })); - } - resp.context_menu(|ui| { - crate::widgets::menu_scroll(ui, |ui| { - ui.set_min_width(190.0); - let entry = PathEntry { name: name.clone(), path: path.clone(), kind: *kind }; - let can_paint = app.session.active().and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id))).is_some_and(|l| l.surface().is_some()); - for (label, cmd, params) in path_context_actions(&entry, &doc, st_layer) { - let enabled = !matches!(cmd, "path.fill" | "path.stroke") || can_paint; - if ui.add_enabled(enabled, egui::Button::new(tl!(label))).clicked() { - if cmd == "path.stroke" { - // Stroke Path… asks for the tool first, as in Photoshop (#2978). - stroke_dialog = Some(params.get("name").and_then(Value::as_str).unwrap_or("work").to_string()); - } else if cmd == "path.rename" && params.get("to").is_none() { - let edit = PathRename { key: key.clone(), text: name.clone(), focused: false }; - ui.ctx().data_mut(|d| d.insert_temp(rename_id, edit)); - } else { - action = Some((cmd, params)); - } - ui.close(); - } - } - }); - }); - ui.painter().line_segment([r.left_bottom(), r.right_bottom()], Stroke::new(1.0, t.separator)); - } - // Clicking the empty area deselects the path, as in Photoshop: new fill and - // adjustment layers then take the selection as their mask instead (#1419). - let rest = ui.available_rect_before_wrap(); - let rest = rest.intersect(Rect::from_min_size(rest.min, vec2(rest.width(), rest.height().min(4000.0)))); - if rest.is_positive() && ui.interact(rest, ui.scope_id().with("paths-empty"), Sense::click()).clicked() { - app.ui.selected_path = None; - } - }, - ); - // The dragged row follows the cursor. - if let Some(drag) = &drag - && let Some(p) = ctx.input(|i| i.pointer.interact_pos()) - { - crate::layer_transfer::ghost(&ctx, p, &drag.name); - } - let sel = app.ui.selected_path.clone().filter(|s| s != "layer" || has_layer_path).unwrap_or_else(|| "work".into()); - let buttons = crate::widgets::panel_footer(ui, |ui| { - let fg = hex(app.session.tools.foreground); - let mut n = doc.paths.len() + 1; - while doc.paths.iter().any(|p| p.name == format!("Path {n}")) { - n += 1; - } - let items: [(&str, &str, &str, Value); 7] = [ - ("paint-bucket", "Fill path with foreground color", "path.fill", json!({"name": sel, "color": fg})), - ("circle", "Stroke path with brush", "path.stroke", json!({"name": sel, "tool": "brush"})), - ("square-dashed", "Load path as a selection", "path.toSelection", json!({"name": sel})), - ("spline", "Make work path from selection", "select.toWorkPath", json!({"tolerance": 2.0})), - ("square", "Add vector mask", "layer.vectorMask.fromPath", json!({"name": sel})), - ("square-plus", "Create new path", "path.set", json!({"name": format!("Path {n}"), "path": {"subpaths": []}})), - ("trash", "Delete path", "path.delete", json!({"name": sel})), - ]; - // The layer's own path: deleting it deletes the vector mask (a shape keeps its path). - let shape = rows.iter().any(|r| r.kind == PathRow::Layer && r.name.ends_with(" Shape Path")); - let delete_layer_path = sel == "layer" && !shape; - let items = items.map(|(icon, tip, cmd, p)| { - if cmd == "path.delete" && delete_layer_path { (icon, "Delete vector mask", "layer.vectorMask.delete", json!({})) } else { (icon, tip, cmd, p) } - }); - // Laid out from the right, so the last button goes first. - let mut buttons = Rect::NOTHING; - for (icon, tip, cmd, p) in items.into_iter().rev() { - let icon = if crate::icons::exists(icon) { icon } else { "square" }; - let b = crate::icons::button(ui, icon, 26.0, false, tip); - if b.clicked() { - if cmd == "path.stroke" && ui.input(|i| i.modifiers.alt) { - // Alt-click opens the Stroke Path dialog, as in Photoshop (#2978). - stroke_dialog = Some(sel.clone()); - } else { - action = Some((cmd, p)); - } - } - // A row dropped on the trash deletes that row's path, selected or not (#6553). - if matches!(cmd, "path.delete" | "layer.vectorMask.delete") - && let Some(drag) = &drag - && crate::panels::dropped_on(ui, &b) - { - action = Some((drag.cmd, drag.params.clone())); - } - buttons = buttons.union(b.rect); - } - buttons - }); - ctx_data_footer(ui.ctx(), buttons); - if ctx.input(|i| i.pointer.any_released()) { - ctx.data_mut(|d| d.remove::(path_drag_key())); - } - if let Some(name) = stroke_dialog { - crate::canvas_tool_menu::stroke_path_dialog(app, &name); - } - if let Some((cmd, p)) = action { - let renamed = if cmd == "path.rename" { p.get("to").and_then(Value::as_str).map(str::to_string) } else { None }; - match app.run(cmd, p) { - // The renamed (or just saved) path stays the panel's target. - Ok(_) => { - if renamed.is_some() { - app.ui.selected_path = renamed; - } - } - Err(e) => { - app.ui.status = e; - app.ui.status_error = true; - } - } - } -} - #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/vector_ui/curvature.rs b/crates/ui-egui/src/vector_ui/curvature.rs new file mode 100644 index 0000000000..097ad9d207 --- /dev/null +++ b/crates/ui-egui/src/vector_ui/curvature.rs @@ -0,0 +1,86 @@ +use super::pen::{cancel_stale, pen_commit}; +use super::*; + +/// Recompute a Curvature Pen path's handles from its anchors and corner points. +pub(super) fn curvature_refresh(pen: &mut PenPath, closed: bool) { + let anchors: Vec<[f64; 2]> = pen.knots.iter().map(|k| k[0]).collect(); + let corners: Vec = (0..anchors.len()).map(|i| pen.unlinked.contains(&i)).collect(); + pen.knots = photocraft_vector::edit::curvature_knots(&anchors, &corners, closed); +} + +/// The anchor of the Curvature Pen path being drawn under (x, y), for the cursor. +pub(crate) fn curvature_anchor_at(app: &PhotocraftApp, x: f64, y: f64) -> Option { + curvature_hit(app, x, y) +} + +/// The Curvature Pen's anchor within a few screen pixels of (x, y). +pub(super) fn curvature_hit(app: &PhotocraftApp, x: f64, y: f64) -> Option { + let tol = 6.0 / app.point_zoom().max(0.01) as f64; + let pen = app.ui.pen.as_ref().filter(|p| p.curvature)?; + pen.knots + .iter() + .enumerate() + .map(|(i, k)| (i, (k[0][0] - x).hypot(k[0][1] - y))) + .filter(|(_, d)| *d < tol) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(i, _)| i) +} + +/// Curvature Pen press: clicking the first anchor closes the path, pressing another anchor +/// grabs it to move, anywhere else adds a smooth anchor (still draggable until the release). +pub fn curvature_down(app: &mut PhotocraftApp, x: f64, y: f64) { + if !cancel_stale(app) { + return; + } + if app.ui.pen.as_ref().is_some_and(|p| !p.curvature) { + pen_commit(app, false); + } + let hit = curvature_hit(app, x, y); + if hit == Some(0) && app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 3) { + pen_commit(app, true); + return; + } + if app.ui.pen.is_none() { + app.ui.pen_doc = app.session.active().map(|st| st.doc.id); + } + let pen = app.ui.pen.get_or_insert_with(|| PenPath { curvature: true, ..Default::default() }); + if hit.is_none() { + pen.knots.push([[x, y]; 3]); + } + pen.moving = hit.or(pen.knots.len().checked_sub(1)); + curvature_refresh(pen, false); +} + +pub fn curvature_move(app: &mut PhotocraftApp, x: f64, y: f64) { + if let Some(pen) = app.ui.pen.as_mut().filter(|p| p.curvature) + && let Some(k) = pen.moving.and_then(|i| pen.knots.get_mut(i)) + { + k[0] = [x, y]; + curvature_refresh(pen, false); + } +} + +pub fn curvature_up(app: &mut PhotocraftApp) { + if let Some(pen) = app.ui.pen.as_mut() { + pen.moving = None; + } +} + +/// Curvature Pen double-click: toggle the anchor under the pointer between smooth and corner +/// (double-clicking empty canvas therefore places a corner point, as in Photoshop). With no path +/// being drawn, an anchor of the active path toggles the same way and its subpath reflows +/// (`path.convertPoint` with `curvature`), so a Pen-drawn corner rounds off. +pub fn curvature_toggle(app: &mut PhotocraftApp, x: f64, y: f64) { + if app.ui.pen.as_ref().is_none_or(|p| p.knots.is_empty()) { + crate::direct_select::curvature_toggle_active(app, [x, y]); + return; + } + let Some(i) = curvature_hit(app, x, y) else { return }; + let Some(pen) = app.ui.pen.as_mut() else { return }; + if let Some(at) = pen.unlinked.iter().position(|&c| c == i) { + pen.unlinked.remove(at); + } else { + pen.unlinked.push(i); + } + curvature_refresh(pen, false); +} diff --git a/crates/ui-egui/src/vector_ui/options.rs b/crates/ui-egui/src/vector_ui/options.rs new file mode 100644 index 0000000000..1147810733 --- /dev/null +++ b/crates/ui-egui/src/vector_ui/options.rs @@ -0,0 +1,321 @@ +use super::path_ops::active_path_name; +use super::shapes::is_shape_tool; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Options bars + +/// Options bar for vector tools; false for other tools. +pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool { + if !(is_shape_tool(tool) + || matches!( + tool, + Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::PathSelection | Tool::DirectSelection + )) + { + return false; + } + let t = Tokens::get(ui.ctx()); + let lbl = |ui: &mut egui::Ui, s: &str| { + let label = ui.label(egui::RichText::new(s).color(t.text_dim).size(12.0)); + // The caption scrubs and names the control drawn right after it. + crate::widgets::scrub_option_label(ui, &label); + }; + let o = &mut app.ui.tool_options; + let target = selected_shape(&app.session); + if tool == Tool::PathSelection && target.is_none() { + lbl(ui, if app.ui.vector_mask_target { "Drag to move the targeted vector mask" } else { tl!("Drag to move the active shape's path or the Work Path") }); + return true; + } + if tool == Tool::DirectSelection && target.is_none() { + let (shift, alt) = (crate::shortcuts::pretty("Shift"), crate::shortcuts::pretty("Alt")); + lbl( + ui, + &crate::i18n::fmt( + tl!("Click: select anchor · Drag: move anchor, handle or segment · {shift}-click: add · {alt}-click: whole subpath"), + &[("shift", &shift), ("alt", &alt)], + ), + ); + return true; + } + if matches!(tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint) { + let hint = if tool == Tool::AddAnchorPoint { + tl!("Click a segment to add an anchor point · {alt}-click an anchor to delete it") + } else { + tl!("Click an anchor point to delete it · {alt}-click a segment to add one") + }; + lbl(ui, &crate::i18n::fmt(hint, &[("alt", &crate::shortcuts::pretty("Alt"))])); + return true; + } + if matches!(tool, Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen) { + let opts = [("path".to_string(), tl!("Path")), ("shape".to_string(), tl!("Shape"))]; + crate::widgets::dropdown(ui, "pen-mode", tl!("Mode"), &mut o.vector_mode, &opts, 80.0); + crate::widgets::vline(ui, 22.0); + if o.vector_mode == "shape" { + crate::widgets::value_field(ui, &mut o.stroke_width, 0.0..=288.0, "px", 58.0).accessible_name(tl!("Stroke:")); + if let Some(change) = + crate::shape_stroke_ui::button(ui, "pen-stroke", &o.shape_stroke, &mut app.ui.stroke_editor, false, true, None, o.stroke_width > 0.0) + { + o.shape_stroke = change.options; + o.stroke_width = enabled_stroke_width(o.stroke_width); + } + } + if tool == Tool::Pen { + crate::widgets::vline(ui, 22.0); + crate::widgets::checkbox(ui, &mut o.pen_auto_add_delete, tl!("Auto Add/Delete")); + } + let enter = crate::shortcuts::pretty("Enter"); + match tool { + Tool::FreeformPen => { + crate::widgets::vline(ui, 22.0); + lbl(ui, tl!("Curve Fit:")); + crate::widgets::value_field(ui, &mut o.curve_fit, 0.5..=10.0, "px", 58.0); + let alt = crate::shortcuts::pretty("Alt"); + lbl(ui, &crate::i18n::fmt(tl!("Drag: draw freehand · {alt}-click: straight segment · Release on the start point: close"), &[("alt", &alt)])); + } + Tool::CurvaturePen => lbl( + ui, + &crate::i18n::fmt( + tl!("Click: smooth point · Double-click: corner · Drag a point: move · Click first point: close · {key} finish"), + &[("key", &enter)], + ), + ), + _ => lbl( + ui, + &crate::i18n::fmt( + tl!("Click: corner · Drag: smooth · {alt}-drag: break handle · Click or drag first point: close · {key} finish · Esc cancel"), + &[("alt", &crate::shortcuts::pretty("Alt")), ("key", &enter)], + ), + ), + } + // Path mode: Make Selection from the path being drawn or the active path, as Photoshop's + // options bar's "Make: Selection…" does (#5703). + if app.ui.tool_options.vector_mode == "path" { + crate::widgets::vline(ui, 22.0); + let has_path = active_path_name(app).is_some() || app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); + if ui.add_enabled(has_path, egui::Button::new(tl!("Make Selection"))).clicked() + && let Err(e) = crate::canvas_tool_menu::make_selection(app) + { + app.ui.status = e; + app.ui.status_error = true; + } + } + return true; + } + let mut mode = "shape".to_string(); + crate::widgets::dropdown(ui, "shape-mode", tl!("Mode"), &mut mode, &[("shape".to_string(), tl!("Shape"))], 80.0); + crate::widgets::vline(ui, 22.0); + crate::shape_options::options_bar(app, ui, tool); + true +} + +/// Whether the active layer supplies the selected-shape options. +fn selected_shape(session: &photocraft_engine::Session) -> Option { + let st = session.active()?; + let layer = st.active_layer?; + matches!(st.doc.layer(layer)?.content, LayerContent::Shape(_)).then_some(layer) +} + +// --------------------------------------------------------------------------------------------- +// Properties (shape layers) + +pub(super) fn solid_paint(c: [f32; 4]) -> photocraft_doc::Fill { + photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(c[0], c[1], c[2], c[3])) +} + +pub(crate) fn enabled_stroke_width(width: f32) -> f32 { + if width.is_finite() && width > 0.0 { width } else { 3.0 } +} + +/// One corner of the live rectangle, preserving the other three radii. +/// The engine takes the full [top-left, top-right, bottom-right, bottom-left] array. +pub(super) fn corner_radii_patch(radii: [f64; 4], corner: usize, radius: f32) -> Value { + let mut next = radii; + if let Some(r) = next.get_mut(corner) { + *r = f64::from(radius.max(0.0)); + } + json!({"radii": next}) +} + +/// Follow the existing brush/mask continuous-edit convention: one history state per press or +/// keyboard edit, with every value tick of a held-pointer gesture sharing its key. +pub(crate) fn paint_gesture(ui: &egui::Ui, key: egui::Id) -> u64 { + let pass = ui.ctx().cumulative_pass_nr(); + let pressed = ui.input(|i| i.pointer.any_pressed()); + ui.data_mut(|d| { + let gesture = d.get_temp_mut_or_default::<(u64, u64)>(key); + if pressed && gesture.1 != pass { + gesture.0 = gesture.0.wrapping_add(1); + gesture.1 = pass; + } + gesture.0 + }) +} + +/// Properties panel for a shape layer: Appearance (fill, stroke) and live shape geometry. +pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocraft_doc::LayerId) { + if app.session.active().is_some_and(|st| { + let locks = st.doc.effective_locks(id); + locks.all || locks.pixels + }) { + ui.disable(); + } + let Some(sh) = app.session.active().and_then(|s| s.doc.layer(id)).and_then(|l| match &l.content { + LayerContent::Shape(sh) => Some(sh.clone()), + _ => None, + }) else { + return; + }; + let t = Tokens::get(ui.ctx()); + let mut edit: Option = None; + let doc_id = app.session.active().map(|st| st.doc.id); + let key = |k: &str| format!("shape-{doc_id:?}-{}-{k}", id.0); + let gesture_key = ui.scope_id().with(key("paint-gesture")); + let gesture = paint_gesture(ui, gesture_key); + let coalesce = |field: &str| format!("{}:{}:{gesture}", key(field), gesture_key.value()); + // The shared collapsible section headers (#155). + // Prefs "Appearance" is theme chrome (Giao diện); shape fill/stroke is Diện mạo. + if crate::props_layout::section(ui, "appearance", crate::i18n::tr_ctx(crate::i18n::current(), "shape", "Appearance")) { + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Fill")).color(t.text_dim).size(12.0)); + let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); + let mut gradients = GradientChoices { + presets: &app.session.presets.gradients, + current: &app.session.presets.gradient, + recent: &mut app.ui.recent_gradients, + fg, + bg, + }; + if let Some(change) = swatch(ui, sh.fill.as_ref(), fg, tl!("Set shape fill type"), &mut gradients) { + let fill = match change { + PaintChange::None => Value::Null, + PaintChange::Color(color) => json!(color), + PaintChange::Gradient(g) => paint_param(&g), + }; + edit = Some(json!({"fill": fill, "coalesce": coalesce("fill")})); + } + ui.add_space(12.0); + ui.label(egui::RichText::new(tl!("Stroke")).color(t.text_dim).size(12.0)); + if let Some(change) = swatch(ui, sh.stroke.as_ref().map(|s| &s.paint), fg, tl!("Set shape stroke type"), &mut gradients) { + let width = enabled_stroke_width(sh.stroke.as_ref().map_or(0.0, |s| s.width)); + let stroke = match change { + PaintChange::None => Value::Null, + PaintChange::Color(color) => json!({"color": color, "width": width}), + PaintChange::Gradient(g) => json!({"color": paint_param(&g), "width": width}), + }; + edit = Some(json!({"stroke": stroke, "coalesce": coalesce("stroke")})); + } + let mut w = sh.stroke.as_ref().map_or(0.0, |s| s.width); + if crate::widgets::value_field(ui, &mut w, 0.0..=288.0, "px", 60.0).accessible_name(tl!("Stroke:")).changed() && (sh.stroke.is_some() || w > 0.0) { + edit = Some(json!({"stroke": {"width": w}, "coalesce": coalesce("stroke-w")})); + } + }); + let style = sh.stroke.as_ref().map(crate::shape_stroke_ui::StrokeOptions::from).unwrap_or_default(); + let stroke_enabled = sh.stroke.as_ref().is_some_and(|stroke| stroke.width > 0.0); + if let Some(change) = crate::shape_stroke_ui::button( + ui, + &key("style"), + &style, + &mut app.ui.stroke_editor, + sh.path.subpaths.iter().all(|s| s.closed), + !matches!(sh.live, Some(photocraft_doc::LiveShape::Ellipse { .. })), + app.session.active().map(|st| (st.doc.id, id)), + stroke_enabled, + ) { + let mut stroke = change.options.params(); + if !stroke_enabled { + stroke["width"] = json!(3.0); + } + edit = Some(json!({"stroke": stroke, "coalesce": change.coalesce})); + } + } + if let Some(live) = &sh.live + && crate::props_layout::section(ui, "liveShape", tl!("Shape")) + { + let num = |ui: &mut egui::Ui, label: &str, v: &mut f32, range: std::ops::RangeInclusive, unit: &str| -> bool { + ui.label(egui::RichText::new(tl!(&label)).color(t.text_dim).size(12.0)); + crate::widgets::value_field(ui, v, range, unit, 64.0).accessible_name(tl!(&label)).changed() + }; + match live { + photocraft_doc::vector::LiveShape::Rect { rect, .. } + | photocraft_doc::vector::LiveShape::Ellipse { rect } + | photocraft_doc::vector::LiveShape::Polygon { rect, .. } => { + ui.horizontal(|ui| { + let (mut w, mut h) = (rect[2] as f32, rect[3] as f32); + let cw = num(ui, "W", &mut w, 1.0..=300000.0, "px"); + let ch = num(ui, "H", &mut h, 1.0..=300000.0, "px"); + if cw || ch { + edit = Some(json!({"rect": [rect[0], rect[1], w.round(), h.round()], "coalesce": key("wh")})); + } + }); + } + photocraft_doc::vector::LiveShape::Line { .. } => {} + } + ui.vertical(|ui| match live { + photocraft_doc::vector::LiveShape::Rect { radii, .. } => { + // Keep the uniform workflow available after independent corner edits too. + ui.horizontal(|ui| { + let mut all = radii[0] as f32; + if num(ui, tl!("Corner radius"), &mut all, 0.0..=100000.0, "px") { + edit = Some(json!({"radii": all, "coalesce": key("radius-all")})); + } + }); + // Separate rows also fit the narrow Properties dock. The labels use the + // localized corner names, rather than untranslated abbreviations. + for (index, label) in [(0, tl!("Top Left")), (1, tl!("Top Right")), (3, tl!("Bottom Left")), (2, tl!("Bottom Right"))] { + ui.horizontal(|ui| { + let mut radius = radii[index] as f32; + if num(ui, label, &mut radius, 0.0..=100000.0, "px") { + let mut patch = corner_radii_patch(*radii, index, radius); + patch["coalesce"] = json!(key(&format!("radius-{index}"))); + edit = Some(patch); + } + }); + } + } + photocraft_doc::vector::LiveShape::Polygon { sides, star_ratio, corner_radius, .. } => { + // One radius rounds every vertex of a triangle, polygon or star, as in Photoshop. + ui.horizontal(|ui| { + let mut r = *corner_radius as f32; + if num(ui, tl!("Corner radius"), &mut r, 0.0..=100000.0, "px") { + edit = Some(json!({"cornerRadius": r, "coalesce": key("corner-radius")})); + } + }); + ui.horizontal(|ui| { + let mut n = *sides as f32; + if num(ui, tl!("Sides"), &mut n, 3.0..=100.0, "") { + edit = Some(json!({"sides": n.round() as u32, "coalesce": key("sides")})); + } + let mut sr = (*star_ratio * 100.0) as f32; + if num(ui, tl!("Star ratio"), &mut sr, 1.0..=100.0, "%") { + edit = Some(json!({"starRatio": sr as f64 / 100.0, "coalesce": key("star")})); + } + }) + .inner + } + photocraft_doc::vector::LiveShape::Line { weight, .. } => { + ui.horizontal(|ui| { + let mut w = *weight as f32; + if num(ui, tl!("Weight"), &mut w, 1.0..=10000.0, "px") { + edit = Some(json!({"weight": w, "coalesce": key("weight")})); + } + }) + .inner + } + _ => {} + }); + } + if let Some(mut p) = edit { + p["layer"] = json!(id.0); + if let Err(e) = app.run("shape.edit", p) { + app.ui.status = e; + app.ui.status_error = true; + } + if !ui.input(|i| i.pointer.any_down()) { + ui.data_mut(|d| { + let gesture = d.get_temp_mut_or_default::<(u64, u64)>(gesture_key); + gesture.0 = gesture.0.wrapping_add(1); + }); + } + } +} diff --git a/crates/ui-egui/src/vector_ui/overlay.rs b/crates/ui-egui/src/vector_ui/overlay.rs new file mode 100644 index 0000000000..b0bdbe3221 --- /dev/null +++ b/crates/ui-egui/src/vector_ui/overlay.rs @@ -0,0 +1,239 @@ +use super::curvature::curvature_refresh; +use super::path_ops::targeted_vector_mask; +use super::pen::{closing, over_first_anchor, shift_45}; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Drawing + +pub(super) fn bezier(p0: [f64; 2], c0: [f64; 2], c1: [f64; 2], p1: [f64; 2], t: f64) -> [f64; 2] { + let u = 1.0 - t; + let f = |a: f64, b: f64, c: f64, d: f64| u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d; + [f(p0[0], c0[0], c1[0], p1[0]), f(p0[1], c0[1], c1[1], p1[1])] +} + +/// `q` lies on the chord from `a` to `d` (within a thousandth of a pixel). +fn on_chord(a: [f64; 2], q: [f64; 2], d: [f64; 2]) -> bool { + let (dx, dy, vx, vy) = (d[0] - a[0], d[1] - a[1], q[0] - a[0], q[1] - a[1]); + let len = dx.hypot(dy); + if len < 1e-9 { + return vx.hypot(vy) < 1e-3; + } + let t = (vx * dx + vy * dy) / (len * len); + (vx * dy - vy * dx).abs() / len < 1e-3 && (-1e-9..=1.0 + 1e-9).contains(&t) +} + +/// How far (in screen pixels) a drawn chord may stray from the true curve. +const CURVE_TOLERANCE: f64 = 0.3; + +/// Pieces per segment at most: 0.3 px holds for curves bending up to about 1.4 million px on screen. +pub(super) const MAX_CURVE_PIECES: usize = 1024; + +/// Screen points along one cubic segment (both ends included). The control points are mapped to +/// the screen first (`xf` is affine, so the curve maps exactly), and the number of chords follows +/// how much the curve bends there: a straight segment is one chord, and a curve zoomed in stays +/// smooth instead of showing a fixed 16 chords (#4084). Uses the bound +/// `max|B''| / 8n² <= tol` with `max|B''| <= 6·max(|p0−2c0+c1|, |c0−2c1+p1|)`. +pub(crate) fn curve_points(p0: [f64; 2], c0: [f64; 2], c1: [f64; 2], p1: [f64; 2], xf: &dyn Fn([f64; 2]) -> Pos2) -> Vec { + let [a, b, c, d] = [p0, c0, c1, p1].map(|q| { + let s = xf(q); + [f64::from(s.x), f64::from(s.y)] + }); + let second = |p: [f64; 2], q: [f64; 2], r: [f64; 2]| (p[0] - 2.0 * q[0] + r[0]).hypot(p[1] - 2.0 * q[1] + r[1]); + let n = (0.75 * second(a, b, c).max(second(b, c, d)) / CURVE_TOLERANCE).sqrt().ceil(); + // A straight segment (controls on the chord, like the Pen's retracted handles) is one chord; + // NaN (a non-finite point) falls back to one too. + let n = if n.is_finite() && !(on_chord(a, b, d) && on_chord(a, c, d)) { (n as usize).clamp(1, MAX_CURVE_PIECES) } else { 1 }; + (0..=n) + .map(|k| { + let q = bezier(a, b, c, d, k as f64 / n as f64); + pos2(q[0] as f32, q[1] as f32) + }) + .collect() +} + +/// Screen polylines for a path (one per subpath). +pub(crate) fn path_lines(path: &Path, xf: &dyn Fn([f64; 2]) -> Pos2) -> Vec<(Vec, bool)> { + path.subpaths + .iter() + .map(|s| { + let n = s.knots.len(); + let mut pts = Vec::new(); + let segs = if s.closed { n } else { n.saturating_sub(1) }; + for i in 0..segs { + let (a, b) = (&s.knots[i], &s.knots[(i + 1) % n]); + pts.extend(curve_points([a.anchor.x, a.anchor.y], [a.out_ctrl.x, a.out_ctrl.y], [b.in_ctrl.x, b.in_ctrl.y], [b.anchor.x, b.anchor.y], xf)); + } + if pts.is_empty() + && let Some(k) = s.knots.first() + { + pts.push(xf([k.anchor.x, k.anchor.y])); + } + (pts, s.closed) + }) + .collect() +} + +/// A path's outline in the accent colour. +pub(crate) fn draw_outline(painter: &egui::Painter, p: &Path, to_scr: &dyn Fn([f64; 2]) -> Pos2, accent: Color32) { + for (pts, closed) in path_lines(p, to_scr) { + if closed { + painter.add(egui::Shape::closed_line(pts, Stroke::new(1.0, accent))); + } else { + painter.add(egui::Shape::line(pts, Stroke::new(1.0, accent))); + } + } +} + +/// An anchor point's square: filled with the accent when selected, else hollow (white). +pub(crate) fn draw_anchor(painter: &egui::Painter, c: Pos2, selected: bool, accent: Color32) { + let r = Rect::from_center_size(c, vec2(6.0, 6.0)); + painter.rect_filled(r, 0.0, if selected { accent } else { Color32::WHITE }); + painter.rect_stroke(r, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside); +} + +/// A direction handle: the line from its anchor and the round handle end. +pub(crate) fn draw_handle(painter: &egui::Painter, anchor: Pos2, handle: Pos2, accent: Color32) { + painter.line_segment([anchor, handle], Stroke::new(1.0, accent)); + painter.circle_filled(handle, 3.0, accent); +} + +/// Does `tool` draw the anchor squares of the paths it can edit? Path Selection does, and so do +/// the Pen tools: as in Photoshop, a path finished with Enter or by closing it keeps its anchors +/// on screen, so it can still be edited (⌘/Ctrl-drag, Auto Add/Delete) (#6884, #4716). +pub(crate) fn shows_anchors(tool: Tool) -> bool { + // Add/Delete Anchor Point and Convert Point draw Direct Selection's overlay instead. + matches!(tool, Tool::PathSelection | Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen) +} + +/// The saved path selected in the Paths panel: Photoshop's target path, drawn on the canvas with +/// any tool (#6550). `None` when the panel selects the work path, a layer's path or nothing. +pub(crate) fn selected_saved_path(app: &PhotocraftApp) -> Option<&Path> { + let sel = app.ui.selected_path.as_deref().filter(|s| !matches!(*s, "work" | "layer"))?; + app.session.active()?.doc.paths.iter().find(|p| p.name == sel).map(|p| &p.path) +} + +/// Work path / active shape path / selected saved path outlines, anchors, and the pen path in +/// progress. +pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, doc: &Document) { + let tool = app.ui.tool; + let accent = Tokens::get(painter.ctx()).accent; + let to_scr = |q: [f64; 2]| xf.to_screen(q[0] as f32, q[1] as f32); + let draw_path = |p: &Path, anchors: bool| { + draw_outline(painter, p, &to_scr, accent); + if anchors { + for k in p.subpaths.iter().flat_map(|s| &s.knots) { + draw_anchor(painter, to_scr([k.anchor.x, k.anchor.y]), false, accent); + } + } + }; + // View › Show › Target Path (under Extras) hides the paths; the Pen's path in progress stays. + // Free Transform Path draws the path through its box instead (transform_tool). + let paths = app.ui.view.shows(app.ui.view.show.target_path) && app.ui.transform.as_ref().is_none_or(|t| t.path.is_none()); + if app.session.active().is_some_and(|st| st.doc.id == doc.id) && crate::direct_select::shows(app, painter.ctx().input(|i| i.modifiers)) { + // Direct Selection (or the Pen with ⌘/Ctrl held) draws the paths it edits (#790). + crate::direct_select::draw_overlay(app, painter, &to_scr, accent, paths); + if paths { + // The selected saved path shows too, though Direct Selection doesn't edit it yet. + if let Some(p) = selected_saved_path(app) { + draw_path(p, true); + } + crate::anchor_tools::draw_hover(app, painter, &to_scr, accent, painter.ctx().input(|i| i.modifiers)); + } + } else if paths { + // The shape's or vector mask's path stays visible as an outline with any tool. Path + // Selection and the Pen tools add anchor squares; Direct Selection has its own overlay + // above. The Work Path is drawn only while it is the path selected in the Paths panel or + // a path tool is active, as in Photoshop: a Work Path left unselected (one a PSD arrived + // with, or after Ctrl-click Load as Selection) would otherwise cover the marching ants (#6551). + let anchors = shows_anchors(tool); + if let Some(wp) = &doc.work_path + && (anchors || app.ui.selected_path.as_deref() == Some("work")) + { + draw_path(wp, anchors); + } + // The saved path selected in the Paths panel is the target path (#6550). + if let Some(p) = selected_saved_path(app) { + draw_path(p, anchors); + } + let st = app.session.active(); + if let Some(l) = st.and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id))) + && let LayerContent::Shape(sh) = &l.content + { + draw_path(&sh.path, anchors); + } + // A targeted vector mask shows its path with any tool (#196). + if let Some((_, p)) = targeted_vector_mask(app) { + draw_path(&p, anchors); + } + crate::corner_radius::draw(app, painter, &to_scr, accent); + } + // Pen path in progress, with handles of the last knot and a rubber band to the pointer. While + // ⌘/Ctrl drags it, Direct Selection draws its preview instead. + let edited = matches!(&app.ui.direct_selection.drag, Some(crate::direct_select::Drag::Edit { target: crate::direct_select::PathRef::Pen, .. })); + // Only on the document it is drawn on: a view of another document never shows it (#5373). + if let Some(pen) = app.ui.pen.as_ref().filter(|_| !edited).filter(|_| app.ui.pen_doc.is_none_or(|d| d == doc.id)) { + let mut pts = Vec::new(); + // A close-drag shows the first segment bending with the handle being pulled out. + let mut knots = pen.knots.clone(); + if closing(pen) + && let Some(&[a, _, out]) = pen.knots.last() + && out != a + && let Some(first) = knots.first_mut() + { + first[2] = out; + } + for w in knots.windows(2) { + pts.extend(curve_points(w[0][0], w[0][2], w[1][1], w[1][0], &to_scr)); + } + painter.add(egui::Shape::line(pts, Stroke::new(1.5, accent))); + // No rubber band where a click adds or deletes an anchor of this path instead (#6140). + let auto = app.hover_doc.is_some_and(|h| crate::anchor_tools::pen_auto(app, tool, painter.ctx().input(|i| i.modifiers), h).is_some()); + if let (Some(last), Some(h)) = (pen.knots.last(), app.hover_doc) + && !pen.dragging + && pen.moving.is_none() + && !auto + { + if pen.curvature && pen.knots.len() >= 2 { + // The Curvature Pen previews the curve the next click makes through the pointer. + let mut next = pen.clone(); + next.knots.push([h; 3]); + curvature_refresh(&mut next, false); + if let [.., a, b] = next.knots.as_slice() { + let pts = curve_points(a[0], a[2], b[1], b[0], &to_scr); + painter.add(egui::Shape::dashed_line(&pts, Stroke::new(1.0, accent), 4.0, 3.0)); + } + } else { + // The rubber band ends where a ⇧-click would put the next anchor. + let shift = painter.ctx().input(|i| i.modifiers.shift); + let h = if pen.curvature { h } else { shift_45(last[0], h, shift) }; + painter.add(egui::Shape::dashed_line(&[to_scr(last[0]), to_scr(h)], Stroke::new(1.0, accent), 4.0, 3.0)); + } + } + for (i, k) in pen.knots.iter().enumerate() { + let c = to_scr(k[0]); + let last = i + 1 == pen.knots.len(); + if last && k[2] != k[0] && !pen.curvature { + for hnd in [k[1], k[2]] { + draw_handle(painter, c, to_scr(hnd), accent); + } + } + draw_anchor(painter, c, last, accent); + } + // Hovering the first anchor: Photoshop's close cue, a small ring beside the pointer. + let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); + if let Some(h) = app.hover_doc + && over_first_anchor(pen, h, tol) + && let Some(first) = pen.knots.first() + { + let c = to_scr(first[0]); + painter.rect_filled(Rect::from_center_size(c, vec2(8.0, 8.0)), 0.0, accent); + painter.circle_stroke(c + vec2(11.0, 11.0), 3.5, Stroke::new(1.5, accent)); + } + } + // The segment the Pen's Auto Add/Delete would add an anchor to, or the anchor it would delete, + // over the path being drawn. While drawing, the other paths can be hidden: it edits none of them. + if paths || app.ui.pen.is_some() { + crate::anchor_tools::draw_pen_hover(app, painter, &to_scr, accent, painter.ctx().input(|i| i.modifiers)); + } +} diff --git a/crates/ui-egui/src/vector_ui/path_ops.rs b/crates/ui-egui/src/vector_ui/path_ops.rs new file mode 100644 index 0000000000..db9847aeca --- /dev/null +++ b/crates/ui-egui/src/vector_ui/path_ops.rs @@ -0,0 +1,245 @@ +use super::paths_panel::{PathEntry, PathRow, path_rows}; +use super::pen::pen_commit; +use super::*; + +/// The path that path commands act on without a name: the one selected in the Paths panel, else +/// the work path, else the selected layer's shape path or vector mask; `None` when there's none. +pub fn active_path_name(app: &PhotocraftApp) -> Option { + let st = app.session.active()?; + let rows = path_rows(&st.doc, st.active_layer); + let key = |r: &PathEntry| match r.kind { + PathRow::Work => "work".to_string(), + PathRow::Layer => "layer".to_string(), + PathRow::Saved => r.name.clone(), + }; + let selected = app.ui.selected_path.as_deref().filter(|s| rows.iter().any(|r| key(r) == *s)).map(str::to_string); + selected.or_else(|| rows.iter().find(|r| r.kind == PathRow::Work).map(key)).or_else(|| rows.iter().find(|r| r.kind == PathRow::Layer).map(key)) +} + +/// The commands that create a fill or adjustment layer and take a `"path"` as its vector mask. +pub fn takes_path_mask(id: &str) -> bool { + id.starts_with("layer.newFillLayer.") || id.starts_with("layer.newAdjustmentLayer.") +} + +/// The work or saved path explicitly selected in the Paths panel (not a layer's own path). +pub fn selected_document_path(app: &PhotocraftApp) -> Option { + let st = app.session.active()?; + let sel = app.ui.selected_path.as_deref()?; + let listed = path_rows(&st.doc, st.active_layer).iter().any(|r| match r.kind { + PathRow::Work => sel == "work", + PathRow::Saved => r.name == sel, + PathRow::Layer => false, + }); + listed.then(|| sel.to_string()) +} + +/// New fill and adjustment layers take the path selected in the Paths panel as their vector mask, +/// as in Photoshop (#1419): the command gets it as `"path"` unless the caller set one (`null` +/// opts out). Only an explicitly selected work or saved path counts; deselect it by clicking the +/// panel's empty area. +pub fn with_active_path(app: &PhotocraftApp, id: &str, params: Value) -> Value { + if !takes_path_mask(id) || params.get("path").is_some() { + return params; + } + let Some(sel) = selected_document_path(app) else { return params }; + match params { + Value::Object(mut m) => { + m.insert("path".into(), json!(sel)); + Value::Object(m) + } + _ => json!({ "path": sel }), + } +} + +/// ⌘↩ / Ctrl+Enter (#306): load a path as a selection, like Photoshop with a Pen or Path +/// Selection tool or a path selected in the Paths panel. A path being drawn with the Pen is +/// finished first and loads; otherwise [`active_path_name`]. `params` may set feather, mode… +pub fn path_to_selection(app: &mut PhotocraftApp, params: Value) -> Result { + if app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2) { + // The finished path becomes the work path, or a shape layer's path or a vector mask. + let on_layer = app.ui.tool_options.vector_mode == "shape" || targeted_vector_mask(app).is_some(); + pen_commit(app, false); + app.ui.selected_path = Some(if on_layer { "layer" } else { "work" }.into()); + } + let name = active_path_name(app) + .ok_or_else(|| tl!("No path to make a selection from: draw one with the Pen tool or select one in the Paths panel.").to_string())?; + let mut p = params.as_object().cloned().unwrap_or_default(); + p.insert("name".into(), json!(name)); + app.run("path.toSelection", Value::Object(p)) +} + +// --------------------------------------------------------------------------------------------- +// Path Selection + +/// What Path Selection edits. +enum PathTarget { + Shape(u64), + /// The active layer's vector mask, when its Layers thumbnail is targeted (#196). + VectorMask(u64), + Work, +} + +/// The targeted vector mask of the active layer, if the Layers panel targets it. +pub(crate) fn targeted_vector_mask(app: &PhotocraftApp) -> Option<(u64, Path)> { + let st = app.session.active()?; + let l = st.active_layer.and_then(|id| st.doc.layer(id))?; + let targeted = app.ui.vector_mask_target || st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::VectorMask; + (targeted && !matches!(l.content, LayerContent::Shape(_))).then_some(())?; + l.vector_mask.as_ref().map(|m| (l.id.0, m.path.clone())) +} + +/// The active shape layer's path, if the active layer is a shape layer. +pub(crate) fn active_shape_path(app: &PhotocraftApp) -> Option<(u64, Path)> { + let st = app.session.active()?; + let l = st.active_layer.and_then(|id| st.doc.layer(id))?; + match &l.content { + LayerContent::Shape(sh) => Some((l.id.0, sh.path.clone())), + _ => None, + } +} + +/// Does ⌫ / Delete delete the work path? With the Pen, Freeform Pen or Path Selection tool, no +/// path being drawn and the work path the one these tools show and edit (no shape layer or +/// targeted vector mask in front of it), as in Photoshop (#5702). It was drawn whenever one of +/// these tools was active, but the key reached Edit › Clear, so it looked impossible to delete. +/// Direct Selection and the Curvature Pen delete selected anchors in Photoshop, not the path. +pub(crate) fn delete_key_deletes_work_path(app: &PhotocraftApp) -> bool { + matches!(app.ui.tool, Tool::Pen | Tool::FreeformPen | Tool::PathSelection) + && app.ui.pen.is_none() + && app.ui.transform.is_none() + && app.ui.view.shows(app.ui.view.show.target_path) + && matches!(target_path(app), Some((PathTarget::Work, _))) +} + +/// The path Path Selection edits: the targeted vector mask, the active shape layer's path, else +/// the work path. +fn target_path(app: &PhotocraftApp) -> Option<(PathTarget, Path)> { + if let Some((id, p)) = targeted_vector_mask(app) { + return Some((PathTarget::VectorMask(id), p)); + } + if let Some((id, p)) = active_shape_path(app) { + return Some((PathTarget::Shape(id), p)); + } + app.session.active()?.doc.work_path.clone().map(|p| (PathTarget::Work, p)) +} + +/// Edit › Free Transform Path (⌘T with Path Selection or Direct Selection): the path the +/// box transforms (the one Path Selection edits) and `path.transform`'s params that name it. +pub(crate) fn free_transform_path(app: &PhotocraftApp) -> Option<(Value, Path)> { + if !matches!(app.ui.tool, Tool::PathSelection | Tool::DirectSelection) { + return None; + } + let (target, path) = target_path(app)?; + path.control_bounds()?; + let params = match target { + PathTarget::Shape(id) | PathTarget::VectorMask(id) => json!({"name": "layer", "layer": id}), + PathTarget::Work => json!({"name": "work"}), + }; + Some((params, path)) +} + +fn point_in_subpath(sp: &photocraft_doc::vector::Subpath, pt: [f64; 2]) -> bool { + if !sp.closed || sp.knots.len() < 3 { + return false; + } + let mut inside = false; + let n = sp.knots.len(); + for i in 0..n { + let j = (i + 1) % n; + let xi = sp.knots[i].anchor.x; + let yi = sp.knots[i].anchor.y; + let xj = sp.knots[j].anchor.x; + let yj = sp.knots[j].anchor.y; + let intersect = ((yi > pt[1]) != (yj > pt[1])) && (pt[0] < (xj - xi) * (pt[1] - yi) / (yj - yi) + xi); + if intersect { + inside = !inside; + } + } + inside +} + +/// The topmost visible shape layer under `at` (document coordinates): +/// hits the shape path or anchor within `tol`, or any non-transparent pixel of the shape's raster surface, +/// or point inside the shape's filled geometry. +pub fn pick_shape_at(doc: &Document, at: [f64; 2], tol: f64) -> Option { + let (x, y) = (at[0].floor() as i32, at[1].floor() as i32); + for (path, _, l) in doc.walk().iter().rev() { + if !l.visible || !(1..=path.len()).all(|n| doc.layer_at(&path[..n]).is_some_and(|a| a.visible)) { + continue; + } + let board = path.first().and_then(|i| doc.layers.get(*i)).and_then(|t| t.artboard()); + if board.is_some_and(|a| !a.rect.contains(x, y)) { + continue; + } + if let LayerContent::Shape(sh) = &l.content { + if photocraft_vector::edit::hit(&sh.path, photocraft_geom::Point::new(at[0], at[1]), tol, &[]).is_some() { + return Some(l.id); + } + if sh.fill.is_some() { + if let Some(surf) = l.surface() { + let mut px = [[0.0f32; 4]; 1]; + surf.read_rgba_into(photocraft_doc::Rect::from_xywh(x, y, 1, 1), &mut px); + if px[0][3] > 0.0 { + return Some(l.id); + } + } + if let Some(photocraft_doc::LiveShape::Rect { rect, .. }) = &sh.live { + let x0 = rect[0].min(rect[0] + rect[2]); + let x1 = rect[0].max(rect[0] + rect[2]); + let y0 = rect[1].min(rect[1] + rect[3]); + let y1 = rect[1].max(rect[1] + rect[3]); + if at[0] >= x0 && at[0] <= x1 && at[1] >= y0 && at[1] <= y1 { + return Some(l.id); + } + } + if let Some(photocraft_doc::LiveShape::Ellipse { rect }) = &sh.live { + let rx = rect[2].abs() / 2.0; + let ry = rect[3].abs() / 2.0; + if rx > 1e-6 && ry > 1e-6 { + let cx = rect[0] + rect[2] / 2.0; + let cy = rect[1] + rect[3] / 2.0; + let dx = (at[0] - cx) / rx; + let dy = (at[1] - cy) / ry; + if dx * dx + dy * dy <= 1.0 { + return Some(l.id); + } + } + } + if sh.path.subpaths.iter().any(|sp| point_in_subpath(sp, at)) { + return Some(l.id); + } + } + } + } + None +} + +pub fn path_selection_finish(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) { + let (dx, dy) = (end[0] - start[0], end[1] - start[1]); + let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); + if dx.abs() + dy.abs() < 0.5 { + let Some(st) = app.session.active() else { return }; + if let Some(id) = pick_shape_at(&st.doc, start, tol) { + let _ = app.run("layer.select", json!({"layer": id.0})); + } + return; + } + if target_path(app).is_none() { + let Some(st) = app.session.active() else { return }; + if let Some(id) = pick_shape_at(&st.doc, start, tol) { + let _ = app.run("layer.select", json!({"layer": id.0})); + } + } + let Some((target, path)) = target_path(app) else { return }; + let _ = match target { + PathTarget::Shape(id) => app.run("shape.edit", json!({"layer": id, "move": [dx.round(), dy.round()]})), + PathTarget::VectorMask(id) => { + let moved = path.transform(&Affine::translate(dx.round(), dy.round())); + app.run("layer.vectorMask.edit", json!({"layer": id, "path": photocraft_engine::vector_cmds::path_json(&moved)})) + } + PathTarget::Work => { + let moved = path.transform(&Affine::translate(dx.round(), dy.round())); + app.run("path.set", json!({"name": "work", "path": photocraft_engine::vector_cmds::path_json(&moved)})) + } + }; +} diff --git a/crates/ui-egui/src/vector_ui/paths_panel.rs b/crates/ui-egui/src/vector_ui/paths_panel.rs new file mode 100644 index 0000000000..09daf57dba --- /dev/null +++ b/crates/ui-egui/src/vector_ui/paths_panel.rs @@ -0,0 +1,390 @@ +use super::overlay::path_lines; +use super::shapes::hex; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Paths panel + +fn thumb(ui: &egui::Ui, r: Rect, path: &Path, doc: &Document) { + let t = Tokens::get(ui.ctx()); + // At the document's aspect ratio, like the Channels thumbnails. + let r = crate::channels_panel::fit_thumb(r, doc.size.width, doc.size.height).0; + ui.painter().rect_filled(r, 0.0, Color32::from_gray(if t.pro { 222 } else { 240 })); + let (w, h) = (doc.size.width.max(1) as f64, doc.size.height.max(1) as f64); + let s = (r.width() as f64 / w).min(r.height() as f64 / h); + let off = r.center() - vec2((w * s) as f32 / 2.0, (h * s) as f32 / 2.0); + let map = |q: [f64; 2]| pos2(off.x + (q[0] * s) as f32, off.y + (q[1] * s) as f32); + for (pts, closed) in path_lines(path, &map) { + if closed && pts.len() >= 3 { + ui.painter().add(egui::Shape::closed_line(pts, Stroke::new(1.0, Color32::from_gray(40)))); + } else { + ui.painter().add(egui::Shape::line(pts, Stroke::new(1.0, Color32::from_gray(40)))); + } + } +} + +/// What a Paths panel row is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PathRow { + Saved, + Work, + /// The selected layer's shape path or vector mask (temporary, italic). + Layer, +} + +/// A Paths panel row. +#[derive(Clone, Debug)] +pub struct PathEntry { + pub name: String, + pub path: Path, + pub kind: PathRow, +} + +/// The Paths panel's rows, top to bottom: saved paths, the work path, then the selected layer's +/// shape path (" Shape Path") or vector mask (" Vector Mask"), like Photoshop. +pub fn path_rows(doc: &Document, active: Option) -> Vec { + let mut rows: Vec<_> = doc.paths.iter().map(|p| PathEntry { name: p.name.clone(), path: p.path.clone(), kind: PathRow::Saved }).collect(); + if let Some(wp) = &doc.work_path { + rows.push(PathEntry { name: "Work Path".into(), path: wp.clone(), kind: PathRow::Work }); + } + if let Some(l) = active.and_then(|id| doc.layer(id)) { + let layer_path = match &l.content { + LayerContent::Shape(sh) => Some((format!("{} Shape Path", l.name), sh.path.clone())), + _ => l.vector_mask.as_ref().map(|v| (format!("{} Vector Mask", l.name), v.path.clone())), + }; + if let Some((name, path)) = layer_path { + rows.push(PathEntry { name, path, kind: PathRow::Layer }); + } + } + rows +} + +fn footer_id() -> egui::Id { + egui::Id::unique("paths-footer") +} + +/// A Paths panel row being dragged, for a drop on the trash (#6553): its name and the command +/// that deletes it. +#[derive(Clone, Debug)] +struct PathDrag { + name: String, + cmd: &'static str, + params: Value, +} + +fn path_drag_key() -> egui::Id { + egui::Id::unique("paths-drag") +} + +fn ctx_data_footer(ctx: &egui::Context, r: Rect) { + ctx.data_mut(|d| d.insert_temp(footer_id(), r)); +} + +/// Where the Paths panel's footer buttons were drawn last frame (the rect around them all). +pub fn paths_footer(ctx: &egui::Context) -> Option { + ctx.data(|d| d.get_temp(footer_id())) +} + +/// Photoshop's default name for a saved path: the first free "Path N", counting from the number of +/// saved paths. +fn free_path_name(doc: &Document) -> String { + let mut n = doc.paths.len().saturating_add(1); + while doc.paths.iter().any(|p| p.name == format!("Path {n}")) { + n = n.saturating_add(1); + if n == usize::MAX { + break; + } + } + format!("Path {n}") +} + +/// A Paths panel name being typed in place: the row's key ("work" or the saved path's name) and +/// the text so far. It lives in egui's temp data, like the Channels panel's rename field. +#[derive(Clone)] +struct PathRename { + key: String, + text: String, + focused: bool, +} + +fn rename_id(doc: &Document) -> egui::Id { + egui::Id::unique(("path-rename", doc.id.0)) +} + +/// Commands offered by a Paths row's context menu. The row's path is passed explicitly so a +/// right-click acts on that row even when another path is selected in the panel. `layer` is the +/// layer a `PathRow::Layer` row belongs to (the active layer). +pub(super) fn path_context_actions(entry: &PathEntry, doc: &Document, layer: Option) -> Vec<(&'static str, &'static str, Value)> { + let key = match entry.kind { + PathRow::Work => "work".to_string(), + PathRow::Layer => "layer".to_string(), + PathRow::Saved => entry.name.clone(), + }; + let mut actions = vec![ + ("Make Selection", "path.toSelection", json!({"name": key})), + ("Fill Path", "path.fill", json!({"name": key})), + ("Stroke Path…", "path.stroke", json!({"name": key})), + ]; + if entry.kind == PathRow::Work { + actions.push(("Save Path", "path.rename", json!({"name": "work", "to": free_path_name(doc)}))); + } else { + let mut n = 1usize; + while doc.paths.iter().any(|p| p.name == format!("{} copy {n}", entry.name)) { + n = n.saturating_add(1); + if n == usize::MAX { + break; + } + } + let copy_name = format!("{} copy {n}", entry.name); + actions.push(("Duplicate Path", "path.set", json!({"name": copy_name, "path": photocraft_engine::vector_cmds::path_json(&entry.path)}))); + } + if entry.kind == PathRow::Saved { + // No `to`: the panel asks for the new name in place. + actions.push(("Rename Path…", "path.rename", json!({"name": key}))); + } + if entry.kind != PathRow::Layer { + actions.push(("Delete Path", "path.delete", json!({"name": key}))); + } else if entry.name.ends_with(" Vector Mask") { + actions.push(("Delete Vector Mask", "layer.vectorMask.delete", json!({}))); + } else if let Some(id) = layer { + // A shape layer's path is the shape: Photoshop's Delete Path deletes the layer (#6552). + actions.push(("Delete Path", "layer.delete", json!({"layer": id.0}))); + } + actions +} + +pub fn paths_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + let Some(st) = app.session.active() else { + ui.label(egui::RichText::new(tl!("No document")).color(t.text_faint)); + return; + }; + let doc = st.doc.clone(); + let st_layer = st.active_layer; + let rows = path_rows(&doc, st_layer); + let has_layer_path = rows.iter().any(|r| r.kind == PathRow::Layer); + let mut action: Option<(&str, Value)> = None; + let mut stroke_dialog: Option = None; + // A row dragged onto the trash is deleted (#6553); a drag that never saw its release must not + // outlive it. + let ctx = ui.ctx().clone(); + if !ctx.input(|i| i.pointer.primary_down() || i.pointer.any_released()) { + ctx.data_mut(|d| d.remove::(path_drag_key())); + } + let drag = ctx.data(|d| d.get_temp::(path_drag_key())); + let rename_id = rename_id(&doc); + // The buttons sit in a footer at the panel's bottom, like Photoshop's. + let footer = crate::widgets::footer_height(ui) + ui.spacing().item_spacing.y; + let fill = ui.available_height() > footer + 60.0; + let rows_h = if fill { ui.available_height() - footer } else { f32::INFINITY }; + egui::ScrollArea::vertical().id_salt("path-rows").max_height(rows_h).min_scrolled_height(if fill { rows_h } else { 0.0 }).auto_shrink([false, !fill]).show( + ui, + |ui| { + if rows.is_empty() { + ui.label(egui::RichText::new(tl!("Draw with the Pen tool (P) or make a work path from a selection.")).color(t.text_faint).size(11.5)); + } + for PathEntry { name, path, kind } in &rows { + // What dropping the row on the trash runs; a shape layer's path is not dragged. + let delete = match kind { + PathRow::Work => Some(("path.delete", json!({"name": "work"}))), + PathRow::Saved => Some(("path.delete", json!({"name": name}))), + PathRow::Layer if name.ends_with(" Vector Mask") => Some(("layer.vectorMask.delete", json!({}))), + PathRow::Layer => None, + }; + let sense = if delete.is_some() { Sense::click_and_drag() } else { Sense::click() }; + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), sense); + let key = match kind { + PathRow::Work => "work".to_string(), + PathRow::Layer => "layer".to_string(), + PathRow::Saved => name.clone(), + }; + if resp.drag_started() + && let Some((cmd, params)) = delete + { + let name = if *kind == PathRow::Work { tl!(name).to_string() } else { name.clone() }; + ui.ctx().data_mut(|d| d.insert_temp(path_drag_key(), PathDrag { name, cmd, params })); + } + // Rows are painted: name them for screen readers and UI tests. + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name)); + let sel = app.ui.selected_path.as_deref() == Some(key.as_str()); + if sel { + ui.painter().rect_filled(r, 0.0, t.row_selected); + } else if resp.hovered() { + ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.5)); + } + let thumbnail = Rect::from_min_size(pos2(r.left() + 8.0, r.top() + 4.0), vec2(28.0, 28.0)); + thumb(ui, thumbnail, path, &doc); + let mut job = egui::text::LayoutJob::default(); + // Temporary paths (the work path, the selected layer's shape path or vector mask) are italic. + let italics = *kind != PathRow::Saved; + job.append( + if *kind == PathRow::Work { tl!(name) } else { name }, + 0.0, + egui::TextFormat { font_id: egui::FontId::proportional(12.0), color: t.text, italics, ..Default::default() }, + ); + let renaming = ui.ctx().data(|d| d.get_temp::(rename_id)).filter(|e| e.key == key); + if let Some(mut edit) = renaming { + let field = Rect::from_min_max(pos2(r.left() + 43.0, r.center().y - 11.0), pos2(r.right() - 8.0, r.center().y + 11.0)); + let id = rename_id.with("field"); + let te = + ui.put(field, egui::TextEdit::singleline(&mut edit.text).id(id).font(egui::FontId::proportional(12.0))).accessible_name(tl!("Name")); + let (enter, esc) = ui.input(|i| (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Escape))); + if !edit.focused { + te.request_focus(); + // Like Photoshop, the whole name starts selected so typing replaces it. + if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), id) { + let all = egui::text::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(edit.text.chars().count())); + state.cursor.set_char_range(Some(all)); + state.store(ui.ctx(), id); + } + edit.focused = true; + ui.ctx().data_mut(|d| d.insert_temp(rename_id, edit)); + } else if esc { + ui.ctx().data_mut(|d| d.remove::(rename_id)); + } else if enter || te.lost_focus() || !te.has_focus() { + ui.ctx().data_mut(|d| d.remove::(rename_id)); + let to = edit.text.trim(); + // The Work Path is saved even under its proposed name; an unchanged saved name is left alone. + if !to.is_empty() && (*kind == PathRow::Work || to != name) { + action = Some(("path.rename", json!({"name": key, "to": to}))); + } + } else { + ui.ctx().data_mut(|d| d.insert_temp(rename_id, edit)); + } + } else { + let g = ui.painter().layout_job(job); + ui.painter().galley(pos2(r.left() + 46.0, r.center().y - g.size().y / 2.0), g, t.text); + } + // Ctrl/Cmd-click loads only the thumbnail's path, without changing the panel target. + let modifiers = ui.input(|i| i.modifiers); + let load = resp.clicked() && modifiers.command && resp.interact_pointer_pos().is_some_and(|p| thumbnail.contains(p)); + if load { + let mode = match crate::channels_panel::load_operation(modifiers) { + "new" => "replace", + mode => mode, + }; + action = Some(("path.toSelection", json!({"name": key, "mode": mode}))); + } else if resp.clicked() { + app.ui.selected_path = Some(key.clone()); + } + // As in Photoshop, double-clicking a saved path's name renames it, and double-clicking + // the Work Path asks for the name to save it under (#6238). + let proposed = match kind { + PathRow::Work => Some(free_path_name(&doc)), + PathRow::Saved => Some(name.clone()), + PathRow::Layer => None, + }; + if !load + && resp.double_clicked() + && let Some(text) = proposed + { + ui.ctx().data_mut(|d| d.insert_temp(rename_id, PathRename { key: key.clone(), text, focused: false })); + } + resp.context_menu(|ui| { + crate::widgets::menu_scroll(ui, |ui| { + ui.set_min_width(190.0); + let entry = PathEntry { name: name.clone(), path: path.clone(), kind: *kind }; + let can_paint = app.session.active().and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id))).is_some_and(|l| l.surface().is_some()); + for (label, cmd, params) in path_context_actions(&entry, &doc, st_layer) { + let enabled = !matches!(cmd, "path.fill" | "path.stroke") || can_paint; + if ui.add_enabled(enabled, egui::Button::new(tl!(label))).clicked() { + if cmd == "path.stroke" { + // Stroke Path… asks for the tool first, as in Photoshop (#2978). + stroke_dialog = Some(params.get("name").and_then(Value::as_str).unwrap_or("work").to_string()); + } else if cmd == "path.rename" && params.get("to").is_none() { + let edit = PathRename { key: key.clone(), text: name.clone(), focused: false }; + ui.ctx().data_mut(|d| d.insert_temp(rename_id, edit)); + } else { + action = Some((cmd, params)); + } + ui.close(); + } + } + }); + }); + ui.painter().line_segment([r.left_bottom(), r.right_bottom()], Stroke::new(1.0, t.separator)); + } + // Clicking the empty area deselects the path, as in Photoshop: new fill and + // adjustment layers then take the selection as their mask instead (#1419). + let rest = ui.available_rect_before_wrap(); + let rest = rest.intersect(Rect::from_min_size(rest.min, vec2(rest.width(), rest.height().min(4000.0)))); + if rest.is_positive() && ui.interact(rest, ui.scope_id().with("paths-empty"), Sense::click()).clicked() { + app.ui.selected_path = None; + } + }, + ); + // The dragged row follows the cursor. + if let Some(drag) = &drag + && let Some(p) = ctx.input(|i| i.pointer.interact_pos()) + { + crate::layer_transfer::ghost(&ctx, p, &drag.name); + } + let sel = app.ui.selected_path.clone().filter(|s| s != "layer" || has_layer_path).unwrap_or_else(|| "work".into()); + let buttons = crate::widgets::panel_footer(ui, |ui| { + let fg = hex(app.session.tools.foreground); + let mut n = doc.paths.len() + 1; + while doc.paths.iter().any(|p| p.name == format!("Path {n}")) { + n += 1; + } + let items: [(&str, &str, &str, Value); 7] = [ + ("paint-bucket", "Fill path with foreground color", "path.fill", json!({"name": sel, "color": fg})), + ("circle", "Stroke path with brush", "path.stroke", json!({"name": sel, "tool": "brush"})), + ("square-dashed", "Load path as a selection", "path.toSelection", json!({"name": sel})), + ("spline", "Make work path from selection", "select.toWorkPath", json!({"tolerance": 2.0})), + ("square", "Add vector mask", "layer.vectorMask.fromPath", json!({"name": sel})), + ("square-plus", "Create new path", "path.set", json!({"name": format!("Path {n}"), "path": {"subpaths": []}})), + ("trash", "Delete path", "path.delete", json!({"name": sel})), + ]; + // The layer's own path: deleting it deletes the vector mask (a shape keeps its path). + let shape = rows.iter().any(|r| r.kind == PathRow::Layer && r.name.ends_with(" Shape Path")); + let delete_layer_path = sel == "layer" && !shape; + let items = items.map(|(icon, tip, cmd, p)| { + if cmd == "path.delete" && delete_layer_path { (icon, "Delete vector mask", "layer.vectorMask.delete", json!({})) } else { (icon, tip, cmd, p) } + }); + // Laid out from the right, so the last button goes first. + let mut buttons = Rect::NOTHING; + for (icon, tip, cmd, p) in items.into_iter().rev() { + let icon = if crate::icons::exists(icon) { icon } else { "square" }; + let b = crate::icons::button(ui, icon, 26.0, false, tip); + if b.clicked() { + if cmd == "path.stroke" && ui.input(|i| i.modifiers.alt) { + // Alt-click opens the Stroke Path dialog, as in Photoshop (#2978). + stroke_dialog = Some(sel.clone()); + } else { + action = Some((cmd, p)); + } + } + // A row dropped on the trash deletes that row's path, selected or not (#6553). + if matches!(cmd, "path.delete" | "layer.vectorMask.delete") + && let Some(drag) = &drag + && crate::panels::dropped_on(ui, &b) + { + action = Some((drag.cmd, drag.params.clone())); + } + buttons = buttons.union(b.rect); + } + buttons + }); + ctx_data_footer(ui.ctx(), buttons); + if ctx.input(|i| i.pointer.any_released()) { + ctx.data_mut(|d| d.remove::(path_drag_key())); + } + if let Some(name) = stroke_dialog { + crate::canvas_tool_menu::stroke_path_dialog(app, &name); + } + if let Some((cmd, p)) = action { + let renamed = if cmd == "path.rename" { p.get("to").and_then(Value::as_str).map(str::to_string) } else { None }; + match app.run(cmd, p) { + // The renamed (or just saved) path stays the panel's target. + Ok(_) => { + if renamed.is_some() { + app.ui.selected_path = renamed; + } + } + Err(e) => { + app.ui.status = e; + app.ui.status_error = true; + } + } + } +} diff --git a/crates/ui-egui/src/vector_ui/pen.rs b/crates/ui-egui/src/vector_ui/pen.rs new file mode 100644 index 0000000000..dfecf1330a --- /dev/null +++ b/crates/ui-egui/src/vector_ui/pen.rs @@ -0,0 +1,528 @@ +use super::curvature::{curvature_hit, curvature_refresh}; +use super::path_ops::targeted_vector_mask; +use super::shapes::{fill_param, stroke_param}; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Pen + +pub(super) fn pen_to_json(pen: &PenPath, closed: bool) -> Value { + let folded = fold_close(pen); + let (pen, closed) = match &folded { + Some(p) => (p, true), + None => (pen, closed), + }; + json!({"subpaths": [{"closed": closed, "knots": pen.knots.iter().enumerate().map(|(i, k)| json!({"anchor": k[0], "in": k[1], "out": k[2], "smooth": !pen.unlinked.contains(&i) && (k[1] != k[0] || k[2] != k[0])})).collect::>()}]}) +} + +/// Is `(x, y)` on the first anchor of a Pen path that a click there would close (two anchors or +/// more)? `tol` is the anchors' hit radius in document pixels. +fn on_closing_anchor(pen: &PenPath, x: f64, y: f64, tol: f64) -> bool { + pen.knots.len() >= 2 && pen.knots.first().is_some_and(|k| (k[0][0] - x).hypot(k[0][1] - y) < tol) +} + +/// Would a click at `(x, y)` with `tool` close the path being drawn: the Pen over the first +/// anchor, or the Curvature Pen over the first of three anchors or more? The canvas shows the +/// close-path pointer there, as Photoshop does (#4596). +pub fn closes_path_at(app: &PhotocraftApp, tool: Tool, x: f64, y: f64) -> bool { + let Some(pen) = app.ui.pen.as_ref().filter(|p| !p.dragging && p.moving.is_none()) else { return false }; + match tool { + Tool::Pen => !pen.curvature && on_closing_anchor(pen, x, y, 6.0 / app.point_zoom().max(0.01) as f64), + Tool::CurvaturePen => pen.curvature && pen.knots.len() >= 3 && curvature_hit(app, x, y) == Some(0), + _ => false, + } +} + +/// 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. +pub fn pen_down(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) { + if !cancel_stale(app) { + return; + } + let tol = 6.0 / app.point_zoom().max(0.01) as f64; + if app.ui.pen.is_none() { + app.ui.pen_doc = app.session.active().map(|st| st.doc.id); + } + // 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. + 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); + } + let pen = app.ui.pen.get_or_insert_with(PenPath::default); + pen.adjusting_in = false; + if let Some(first) = pen.knots.first().map(|k| k[0]) + && on_closing_anchor(pen, x, y, tol) + { + // Pressing the first anchor closes the path on release. Until then a stand-in for it + // takes the drag, which pulls out that anchor's handles (close-drag, #3306). + pen.knots.push([first; 3]); + pen.dragging = true; + pen.adjusting_last = false; + return; + } + // Clicking the last anchor breaks its outgoing handle without throwing away the incoming + // curve. Dragging from that anchor then sets the outgoing handle independently (#1482). + // This must precede adding a point, or a re-click creates a zero-length segment. + if let Some((i, last)) = pen.knots.len().checked_sub(1).zip(pen.knots.last_mut()) + && (last[0][0] - x).hypot(last[0][1] - y) < tol + { + last[2] = last[0]; + if !pen.unlinked.contains(&i) { + pen.unlinked.push(i); + } + pen.dragging = true; + pen.adjusting_last = true; + return; + } + let p = match pen.knots.last() { + Some(prev) => shift_45(prev[0], [x, y], shift), + None => [x, y], + }; + pen.knots.push([p; 3]); + pen.dragging = true; + pen.adjusting_last = false; +} + +/// Pen drag: pull out the handles of the anchor just placed. ⇧ (read live, as it is held) +/// turns the handle to the nearest 45° direction from its anchor. +pub fn pen_move(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) { + if let Some(pen) = app.ui.pen.as_mut() + && pen.dragging + { + let (adjusting_last, adjusting_in) = (pen.adjusting_last, pen.adjusting_in); + if let Some(k) = pen.knots.last_mut() { + let a = k[0]; + let [x, y] = shift_45(a, [x, y], shift); + if adjusting_in { + k[1] = [x, y]; + return; + } + k[2] = [x, y]; + if !adjusting_last { + k[1] = [2.0 * a[0] - x, 2.0 * a[1] - y]; + } + } + } +} + +/// `p`, or with ⇧ `p` projected onto the nearest 45° ray from `origin` (Pen tool constraint). +pub(super) fn shift_45(origin: [f64; 2], p: [f64; 2], shift: bool) -> [f64; 2] { + if shift { crate::stroke_constraint::snap45(origin, p) } else { p } +} + +/// Undo the most recently placed Pen anchor while its path is still in progress. +/// These knots are editor-only gesture state, not document history until Enter or +/// clicking the first anchor commits the path. Therefore Cmd/Ctrl+Z must consume one +/// knot rather than undoing an unrelated, already committed document operation. +pub fn pen_undo_last_point(app: &mut PhotocraftApp) -> bool { + if !cancel_stale(app) { + return false; + } + let Some(pen) = app.ui.pen.as_mut() else { return false }; + // A resumed path's own anchors are not the draft's to take back: undoing past the ones added + // since it resumed drops the draft and leaves the path as it was (#6593). + if pen.resumes.as_ref().is_some_and(|r| pen.knots.len() <= r.was.knots.len()) { + // A ⌘/Ctrl selection on the draft goes with it. + if app.ui.direct_selection.target == Some(crate::direct_select::PathRef::Pen) { + app.ui.direct_selection = Default::default(); + } + app.ui.pen = None; + return true; + } + if pen.knots.pop().is_none() { + return false; + } + let n = pen.knots.len(); + let ds = &mut app.ui.direct_selection; + if ds.target == Some(crate::direct_select::PathRef::Pen) { + // A ⌘/Ctrl selection on the path being drawn loses the removed anchor. + ds.anchors.retain(|a| a[1] < n); + ds.segment = ds.segment.filter(|s| s[1] + 1 < n); + } + pen.unlinked.retain(|&i| i < pen.knots.len()); + if pen.curvature { + pen.moving = None; + curvature_refresh(pen, false); + } + pen.dragging = false; + if pen.knots.is_empty() { + app.ui.pen = None; + } + true +} + +pub fn pen_up(app: &mut PhotocraftApp) { + let jitter = 2.0 / f64::from(app.point_zoom().max(0.01)); + let Some(pen) = app.ui.pen.as_mut() else { return }; + pen.dragging = false; + pen.adjusting_last = false; + pen.adjusting_in = false; + if closing(pen) { + // A click on the first anchor closes the path and leaves that anchor's handles alone. + if let Some(k) = pen.knots.last_mut() + && (k[2][0] - k[0][0]).hypot(k[2][1] - k[0][1]) < jitter + { + k[1] = k[0]; + k[2] = k[0]; + } + pen_commit(app, true); + } +} + +/// ⌥/Alt during a Pen drag breaks the pair of handles being pulled out: from then on only the +/// outgoing handle follows the pointer and the incoming curve stays as it is (#3306). +pub fn pen_break_handle(app: &mut PhotocraftApp) { + let Some(pen) = app.ui.pen.as_mut().filter(|p| p.dragging && !p.adjusting_last) else { return }; + let Some(i) = pen.knots.len().checked_sub(1) else { return }; + if !pen.unlinked.contains(&i) { + pen.unlinked.push(i); + } + pen.adjusting_last = true; +} + +/// ⌥/Alt-press on one of the last anchor's handles while drawing grabs that handle alone: the +/// drag turns it and the other handle stays put (#3306, #6077). False when the press misses both. +pub fn pen_grab_handle(app: &mut PhotocraftApp, x: f64, y: f64) -> bool { + let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); + let Some(pen) = app.ui.pen.as_mut() else { return false }; + let Some((i, k)) = pen.knots.len().checked_sub(1).zip(pen.knots.last()) else { return false }; + let dist = |p: [f64; 2]| (p[0] - x).hypot(p[1] - y); + // Both handles show only while the outgoing one is pulled out (`draw_overlay`). + if k[2] == k[0] { + return false; + } + let grabbed = |h: [f64; 2]| h != k[0] && dist(h) < tol && dist(h) < dist(k[0]); + let incoming = if grabbed(k[2]) && dist(k[2]) <= dist(k[1]) { + false + } else if grabbed(k[1]) { + true + } else { + return false; + }; + if !pen.unlinked.contains(&i) { + pen.unlinked.push(i); + } + pen.dragging = true; + pen.adjusting_last = true; + pen.adjusting_in = incoming; + true +} + +/// Would a press at `at` close the Pen path: is the pointer on the first anchor of a path that +/// already has a segment, and no drag is under way? The canvas then shows the close cue (#4193). +pub(crate) fn over_first_anchor(pen: &PenPath, at: [f64; 2], tol: f64) -> bool { + !pen.dragging && pen.moving.is_none() && pen.knots.len() >= 2 && pen.knots.first().is_some_and(|k| (k[0][0] - at[0]).hypot(k[0][1] - at[1]) < tol) +} + +/// Is a close-drag in progress: does the path end in the stand-in for its first anchor? +pub(super) fn closing(pen: &PenPath) -> bool { + pen.knots.len() >= 3 && pen.knots.first().map(|k| k[0]) == pen.knots.last().map(|k| k[0]) +} + +/// The path with a close-drag's stand-in folded into the first knot, which takes the dragged +/// handles (smooth, or a cusp after ⌥/Alt); `None` when no close-drag is in progress. +fn fold_close(pen: &PenPath) -> Option { + if !closing(pen) { + return None; + } + let mut p = pen.clone(); + let stand_in = p.knots.pop()?; + let broken = p.unlinked.contains(&p.knots.len()); + p.unlinked.retain(|&i| i < p.knots.len()); + if stand_in[1] != stand_in[0] || stand_in[2] != stand_in[0] { + let first = p.knots.first_mut()?; + first[1] = stand_in[1]; + first[2] = stand_in[2]; + p.unlinked.retain(|&i| i != 0); + if broken { + p.unlinked.push(0); + } + } + Some(p) +} + +/// The Pen path being drawn as a document path (one open subpath), so ⌘/Ctrl (Direct Selection) +/// can edit it in place while drawing (#4022). +pub(crate) fn pen_path(pen: &PenPath) -> Path { + let pt = |q: [f64; 2]| photocraft_geom::Point::new(q[0], q[1]); + let knots = pen + .knots + .iter() + .enumerate() + .map(|(i, k)| photocraft_doc::Knot { + anchor: pt(k[0]), + in_ctrl: pt(k[1]), + out_ctrl: pt(k[2]), + smooth: !pen.unlinked.contains(&i) && (k[1] != k[0] || k[2] != k[0]), + }) + .collect(); + Path::new(vec![photocraft_doc::vector::Subpath { closed: false, knots, op: Default::default() }]) +} + +/// The Pen path being drawn becomes `path`'s first subpath, edited with ⌘/Ctrl (Direct Selection); +/// drawing carries on from its last anchor. A Curvature Pen path keeps following its anchors. +pub(crate) fn pen_replace(app: &mut PhotocraftApp, path: &Path) { + let Some(pen) = app.ui.pen.as_mut() else { return }; + let knots = path.subpaths.first().map(|s| s.knots.as_slice()).unwrap_or_default(); + pen.knots = knots.iter().map(knot_points).collect(); + pen.unlinked = knots.iter().enumerate().filter(|(_, k)| !k.smooth).map(|(i, _)| i).collect(); + pen.dragging = false; + pen.adjusting_last = false; + pen.adjusting_in = false; + pen.moving = None; + if pen.curvature { + curvature_refresh(pen, false); + } + if pen.knots.is_empty() { + app.ui.pen = None; + } +} + +/// Preserve a foreign document's draft as its Work Path before another document can edit it. +/// A failed commit retains the draft and blocks the caller until it can be retried. +pub fn cancel_stale(app: &mut PhotocraftApp) -> bool { + let active = app.session.active().map(|st| st.doc.id); + if app.ui.pen.is_none() { + app.ui.pen_doc = None; + return true; + } + let Some(owner) = app.ui.pen_doc.filter(|d| Some(*d) != active) else { return true }; + if let Some(index) = app.session.documents().iter().position(|d| d.doc.id == owner) { + let Some(mut pen) = app.ui.pen.clone() else { return true }; + if pen.curvature { + curvature_refresh(&mut pen, false); + } + let active = app.session.active_index(); + app.session.set_active(index); + // Bypass shell targets and sync_views: both belong to the newly active document. + let result = app.session.execute("path.set", json!({"name": "work", "op": "combine", "path": pen_to_json(&pen, false)})); + if let Some(index) = active { + app.session.set_active(index); + } + if let Err(e) = result { + app.ui.status = e.to_string(); + app.ui.status_error = true; + return false; + } + } + app.ui.pen = None; + app.ui.pen_doc = None; + if app.ui.direct_selection.target == Some(crate::direct_select::PathRef::Pen) { + app.ui.direct_selection = Default::default(); + } + true +} + +/// Finish the pen path: a work path (Path mode) or a new shape layer (Shape mode). +pub fn pen_commit(app: &mut PhotocraftApp, closed: bool) { + // The control channel is drained after `sync_views`, so a document switch in this frame has + // not been seen yet: never commit the path into the document it was not drawn on. + if !cancel_stale(app) { + return; + } + let Some(mut pen) = app.ui.pen.take() else { return }; + app.ui.pen_doc = None; + if app.ui.direct_selection.target == Some(crate::direct_select::PathRef::Pen) { + // Its anchors are no longer the Pen's: the committed path is another path. + app.ui.direct_selection = Default::default(); + } + if pen.curvature { + curvature_refresh(&mut pen, closed); + } + commit_path(app, &pen, closed); +} + +/// Commit a finished Pen, Freeform Pen or Curvature Pen path, as one History step: a new shape +/// layer (Shape mode), else a subpath of the targeted vector mask, else the work path. +fn commit_path(app: &mut PhotocraftApp, pen: &PenPath, closed: bool) { + if pen.knots.len() < 2 { + return; + } + let path = pen_to_json(pen, closed); + let r = if app.ui.tool_options.vector_mode == "shape" { + let fill = if closed { fill_param(app) } else { Value::Null }; + let stroke = if closed { + stroke_param(app) + } else { + let mut stroke = app.ui.tool_options.shape_stroke.params(); + stroke["width"] = json!(app.ui.tool_options.stroke_width.max(1.0)); + stroke["color"] = json!(app.session.tools.foreground); + stroke + }; + app.run("shape.create", json!({"kind": "path", "path": path, "fill": fill, "stroke": stroke})) + } else if let Some((name, p)) = + pen.resumes.as_ref().and_then(|r| app.session.active().and_then(|st| with_resumed_subpath(&st.doc, r, &path)).map(|p| (r.path.clone(), p))) + { + // The resumed subpath, carried on, takes its old place: one step, no second subpath. + app.run("path.set", json!({"name": name, "path": p})).inspect(|_| app.ui.selected_path = Some(name)) + } else if let Some((id, existing)) = targeted_vector_mask(app) { + // A targeted vector mask takes the new subpath (#196), as in Photoshop. + let mut p = photocraft_engine::vector_cmds::path_json(&existing); + if let (Some(subs), Some(new)) = (p.get_mut("subpaths").and_then(Value::as_array_mut), path.get("subpaths").and_then(Value::as_array)) { + subs.extend(new.iter().cloned()); + } + app.run("layer.vectorMask.edit", json!({"layer": id, "path": p})) + } else { + // Photoshop adds the new subpath to the path selected in the Paths panel, which is the + // Work Path right after drawing one, so path after path builds up there (#4721). With no + // path selected, a new Work Path replaces the old one. The drawn path ends up selected. + // A resumed draft whose subpath changed meanwhile joins the path it came from, as a new + // subpath, even with nothing selected in the Paths panel. + let exists = |n: &String| app.session.active().is_some_and(|st| path_exists(&st.doc, n)); + let resumed_from = pen.resumes.as_ref().filter(|r| app.session.active().is_some_and(|st| st.doc.id.0 == r.doc)).map(|r| r.path.clone()); + let target = resumed_from.filter(exists).or_else(|| app.ui.selected_path.clone().filter(exists)); + let name = target.clone().unwrap_or_else(|| "work".into()); + let mut params = json!({"name": name, "path": path}); + if target.is_some() { + params["op"] = json!("combine"); + } + app.run("path.set", params).inspect(|_| app.ui.selected_path = Some(name)) + }; + if let Err(e) = r { + app.ui.status = e; + app.ui.status_error = true; + } +} + +/// Does `doc` have the path the Paths panel calls `name`: "work", or a saved path's name? +fn path_exists(doc: &Document, name: &str) -> bool { + doc_path(doc, name).is_some() +} + +/// The path the Paths panel calls `name`: "work", or a saved path's name. +fn doc_path<'a>(doc: &'a Document, name: &str) -> Option<&'a Path> { + if name == "work" { doc.work_path.as_ref() } else { doc.paths.iter().find(|p| p.name == name).map(|p| &p.path) } +} + +/// The open subpath of the path a new Pen path would join (the one selected in the Paths panel, +/// else the work path) that has its first or last anchor at `(x, y)`, as a Pen path to carry on +/// drawing from there (#6593). Its knots run towards that anchor: reversed, handles swapped, when +/// it is the first. Shape mode and a targeted vector mask take new paths, so they resume nothing. +fn resume_at(app: &PhotocraftApp, x: f64, y: f64, tol: f64) -> Option { + if app.ui.tool_options.vector_mode == "shape" || targeted_vector_mask(app).is_some() { + return None; + } + let st = app.session.active()?; + let doc = st.doc.id.0; + let name = app.ui.selected_path.clone().filter(|n| path_exists(&st.doc, n)).unwrap_or_else(|| "work".into()); + let near = |k: &photocraft_doc::Knot| (k.anchor.x - x).hypot(k.anchor.y - y) < tol; + doc_path(&st.doc, &name)?.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; + }; + let mut knots: Vec<_> = s.knots.iter().map(|k| (knot_points(k), k.smooth)).collect(); + if reversed { + knots.reverse(); + for (k, _) in &mut knots { + k.swap(1, 2); + } + } + let unlinked = knots.iter().enumerate().filter(|(_, (_, smooth))| !smooth).map(|(i, _)| i).collect(); + let resumes = Resumed { doc, path: name.clone(), index: i, was: s.clone() }; + Some(PenPath { knots: knots.into_iter().map(|(k, _)| k).collect(), unlinked, resumes: Some(resumes), ..Default::default() }) + }) +} + +/// The resumed path with its subpath carried on: the one subpath of `drawn` takes the old one's +/// anchors and closing, which keeps its other settings (its path operation). `None` when the +/// subpath is no longer the one drawing resumed (another document, or the path changed). +fn with_resumed_subpath(doc: &Document, r: &Resumed, drawn: &Value) -> Option { + let path = doc_path(doc, &r.path).filter(|_| doc.id.0 == r.doc)?; + if path.subpaths.get(r.index) != Some(&r.was) { + return None; + } + let mut p = photocraft_engine::vector_cmds::path_json(path); + let slot = p.get_mut("subpaths")?.as_array_mut()?.get_mut(r.index)?.as_object_mut()?; + let new = drawn.get("subpaths")?.get(0)?; + for key in ["closed", "knots"] { + slot.insert(key.into(), new.get(key)?.clone()); + } + Some(p) +} + +// --------------------------------------------------------------------------------------------- +// Freeform Pen and Curvature Pen + +/// Freeform Pen release: fit the drag's trace within the options bar's Curve Fit and commit it +/// as the Pen does. Releasing on the start point closes the path; a click draws nothing. The +/// points at indices `straight` were ⌥-clicked: the segment into each one stays straight. +pub fn freeform_finish(app: &mut PhotocraftApp, points: &[[f64; 3]], straight: &[usize]) { + let trace: Vec<[f64; 2]> = points.iter().map(|p| [p[0], p[1]]).collect(); + let (Some(first), Some(last)) = (trace.first(), trace.last()) else { return }; + let tol = 6.0 / app.point_zoom().max(0.01) as f64; + let length: f64 = trace.windows(2).map(|w| (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1])).sum(); + let closed = (first[0] - last[0]).hypot(first[1] - last[1]) < tol && length > 4.0 * tol; + let fit = f64::from(app.ui.tool_options.curve_fit); + let pen = if straight.is_empty() { + let Some(sub) = photocraft_vector::trace::fit_trace(&trace, fit, closed) else { return }; + let knots = sub.knots.iter().map(knot_points).collect(); + let unlinked = sub.knots.iter().enumerate().filter(|(_, k)| !k.smooth).map(|(i, _)| i).collect(); + (PenPath { knots, unlinked, ..Default::default() }, sub.closed) + } else { + fit_with_straight_segments(&trace, straight, fit, closed.then_some(tol)) + }; + commit_path(app, &pen.0, pen.1); +} + +fn knot_points(k: &photocraft_doc::Knot) -> [[f64; 2]; 3] { + [[k.anchor.x, k.anchor.y], [k.in_ctrl.x, k.in_ctrl.y], [k.out_ctrl.x, k.out_ctrl.y]] +} + +/// A Freeform Pen trace with ⌥-clicked straight segments (into the points at `straight`): each +/// freehand run between them is fitted on its own, and the runs are joined by straight lines +/// between corner anchors. `close` (a reach) closes the path when it ends on its start point. +fn fit_with_straight_segments(trace: &[[f64; 2]], straight: &[usize], fit: f64, close: Option) -> (PenPath, bool) { + let mut cuts: Vec = straight.iter().copied().filter(|&i| i > 0 && i < trace.len()).collect(); + cuts.sort_unstable(); + cuts.dedup(); + cuts.push(trace.len()); + let (mut knots, mut corners): (Vec<[[f64; 2]; 3]>, Vec) = (Vec::new(), Vec::new()); + let mut start = 0; + for end in cuts { + let run = trace.get(start..end).unwrap_or_default(); + let first = knots.len(); + match photocraft_vector::trace::fit_trace(run, fit, false) { + Some(sub) => { + corners.extend(sub.knots.iter().enumerate().filter(|(_, k)| !k.smooth).map(|(i, _)| first + i)); + knots.extend(sub.knots.iter().map(knot_points)); + } + // A single click (or a run that never moved): one corner anchor. + None => knots.extend(run.first().map(|p| [*p; 3])), + } + // Where a straight segment meets the run: a corner with no handle on that side. + if let Some(k) = knots.get_mut(first).filter(|_| first > 0) { + k[1] = k[0]; + corners.push(first); + } + if end < trace.len() + && let Some(k) = knots.last_mut() + { + k[2] = k[0]; + corners.push(knots.len() - 1); + } + start = end; + } + // Ended on the start point: the last anchor is the first one. + let ends_on_start = |k: &[[[f64; 2]; 3]], reach: f64| match (k.first(), k.last()) { + (Some(a), Some(b)) => k.len() > 3 && (a[0][0] - b[0][0]).hypot(a[0][1] - b[0][1]) < reach, + _ => false, + }; + let closed = close.is_some_and(|reach| ends_on_start(&knots, reach)); + if closed && let Some(last) = knots.pop() { + if let Some(k) = knots.first_mut() { + k[1] = [last[1][0] - last[0][0] + k[0][0], last[1][1] - last[0][1] + k[0][1]]; + } + corners.retain(|&i| i < knots.len()); + corners.push(0); + } + corners.sort_unstable(); + corners.dedup(); + (PenPath { knots, unlinked: corners, ..Default::default() }, closed) +} diff --git a/crates/ui-egui/src/vector_ui/shapes.rs b/crates/ui-egui/src/vector_ui/shapes.rs new file mode 100644 index 0000000000..d931d1ca5b --- /dev/null +++ b/crates/ui-egui/src/vector_ui/shapes.rs @@ -0,0 +1,167 @@ +use super::options::solid_paint; +use super::overlay::path_lines; +use super::*; + +pub fn is_shape_tool(t: Tool) -> bool { + matches!(t, Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line | Tool::CustomShape) +} + +fn rgb32(c: [f32; 4]) -> Color32 { + let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + Color32::from_rgb(b(c[0]), b(c[1]), b(c[2])) +} + +pub(super) fn hex(c: [f32; 4]) -> String { + let c = rgb32(c); + format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b()) +} + +pub(super) fn stroke_param(app: &PhotocraftApp) -> Value { + let o = &app.ui.tool_options; + if o.stroke_width <= 0.0 { + return Value::Null; + } + let mut p = o.shape_stroke.params(); + p["width"] = json!(o.stroke_width); + p["color"] = tool_paint_param(app, true); + p +} + +/// The paint the next shape's fill (`stroke` false) or stroke takes: the options bar's gradient, +/// else the foreground / background colour. +fn tool_paint(app: &PhotocraftApp, stroke: bool) -> photocraft_doc::Fill { + let (gradient, color) = tool_paint_source(app, stroke); + gradient.clone().unwrap_or_else(|| solid_paint(color)) +} + +/// [`tool_paint`] as `shape.create` takes it. +fn tool_paint_param(app: &PhotocraftApp, stroke: bool) -> Value { + let (gradient, color) = tool_paint_source(app, stroke); + gradient.as_ref().map_or_else(|| json!(color), paint_param) +} + +fn tool_paint_source(app: &PhotocraftApp, stroke: bool) -> (&Option, [f32; 4]) { + let o = &app.ui.tool_options; + if stroke { (&o.shape_stroke_gradient, app.session.tools.background) } else { (&o.shape_fill_gradient, app.session.tools.foreground) } +} + +/// Geometry of a Shape-tool drag as `shape.create` params, without fill and stroke (None when too +/// small): ⇧ constrains proportions, ⌥ draws from the centre. Custom shapes give their box as a `rect`. +pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) -> Option { + Some(if tool == Tool::Line { + let (mut dx, mut dy) = (end[0] - start[0], end[1] - start[1]); + if mods.shift { + // Snap to 45°. + let a = (dy.atan2(dx) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4; + let len = dx.hypot(dy); + (dx, dy) = (len * a.cos(), len * a.sin()); + } + if dx.hypot(dy) < 1.0 { + return None; + } + json!({"kind": "line", "from": start, "to": [start[0] + dx, start[1] + dy], "weight": o.line_weight.max(1.0)}) + } else { + let (mut w, mut h) = (end[0] - start[0], end[1] - start[1]); + if mods.shift { + let m = w.abs().max(h.abs()); + (w, h) = (m * w.signum(), m * h.signum()); + } + let (x0, y0) = if mods.alt { (start[0] - w, start[1] - h) } else { (start[0], start[1]) }; + let (w, h) = if mods.alt { (w * 2.0, h * 2.0) } else { (w, h) }; + let rect = [x0.min(x0 + w).round(), y0.min(y0 + h).round(), w.abs().round(), h.abs().round()]; + if rect[2] < 1.0 || rect[3] < 1.0 { + return None; + } + match tool { + Tool::Rectangle if o.corner_radius > 0.0 => json!({"kind": "roundedRect", "rect": rect, "radii": vec![o.corner_radius; 4]}), + Tool::Rectangle | Tool::CustomShape => json!({"kind": "rect", "rect": rect}), + Tool::EllipseShape => json!({"kind": "ellipse", "rect": rect}), + Tool::Triangle => json!({"kind": "polygon", "rect": rect, "sides": 3}), + _ => json!({"kind": "polygon", "rect": rect, "sides": o.polygon_sides.max(3)}), + } + }) +} + +/// The box `[x0, y0, x1, y1]` a Shape-tool drag draws (a line's: its ends'), which snaps while +/// Space repositions it (`snap_ui`). None when too small to draw. +pub fn shape_bounds(o: &ToolOptions, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) -> Option<[f64; 4]> { + let g = shape_geometry(o, tool, start, end, mods)?; + if tool == Tool::Line { + let a: [f64; 2] = serde_json::from_value(g["from"].clone()).ok()?; + let b: [f64; 2] = serde_json::from_value(g["to"].clone()).ok()?; + return Some([a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]); + } + let [x, y, w, h]: [f64; 4] = serde_json::from_value(g["rect"].clone()).ok()?; + Some([x, y, x + w, y + h]) +} + +/// Finish a Shape-tool drag: ⇧ constrains proportions, ⌥ draws from the centre. +pub fn finish_shape(app: &mut PhotocraftApp, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) { + let Some(mut p) = shape_geometry(&app.ui.tool_options, tool, start, end, mods) else { return }; + if tool == Tool::CustomShape { + // ⇧ keeps the shape's proportions (the rect is already squared). + if let Ok(rect) = serde_json::from_value(p["rect"].take()) { + let (fill, stroke) = (fill_param(app), stroke_param(app)); + crate::preset_panels::finish_custom_shape(app, rect, mods.shift, fill, stroke); + } + return; + } + if let Err(e) = create_shape(app, p) { + app.ui.status = e; + app.ui.status_error = true; + } +} + +pub(super) fn fill_param(app: &PhotocraftApp) -> Value { + if app.ui.tool_options.shape_fill { tool_paint_param(app, false) } else { Value::Null } +} + +/// Create a shape layer from `shape.create` geometry with the options bar's fill and stroke: the +/// end of a drag, and the Create Rectangle / Ellipse / … dialogs (`shape_dialog`). +pub fn create_shape(app: &mut PhotocraftApp, mut geometry: Value) -> Result { + geometry["fill"] = fill_param(app); + geometry["stroke"] = stroke_param(app); + app.run("shape.create", geometry) +} + +/// The preview and command both use the full float tool colours, including transparent paint. +pub(super) fn shape_preview(app: &PhotocraftApp, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) -> Option { + let o = &app.ui.tool_options; + let geometry = shape_geometry(o, tool, start, end, mods)?; + let path = if tool == Tool::CustomShape { + let rect = geometry.get("rect").and_then(|r| serde_json::from_value::<[f64; 4]>(r.clone()).ok())?; + let groups = photocraft_engine::presets::shapes::all_groups(&app.session); + let shape = groups.iter().flat_map(|g| &g.items).find(|s| s.name == app.ui.presets_ui.shape())?; + photocraft_engine::presets::shapes::fit(&shape.path, rect, mods.shift) + } else { + photocraft_engine::vector_cmds::shape_path(&geometry).ok()? + }; + Some(photocraft_doc::ShapeLayer { + path, + fill: o.shape_fill.then(|| tool_paint(app, false)), + stroke: (o.stroke_width > 0.0).then(|| o.shape_stroke.stroke(o.stroke_width, tool_paint(app, true))), + ..Default::default() + }) +} + +/// Shape-tool drag preview using the same path and vector stroke geometry as the commit. +pub fn draw_shape_preview(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) { + let Some(mut shape) = shape_preview(app, tool, start, end, mods) else { return }; + let path = shape.path.clone(); + let origin = xf.to_screen(0.0, 0.0); + let x = xf.to_screen(1.0, 0.0) - origin; + let y = xf.to_screen(0.0, 1.0) - origin; + let transform = Affine { m: [x.x as f64, x.y as f64, y.x as f64, y.y as f64, origin.x as f64, origin.y as f64] }; + shape.path = shape.path.transform(&transform); + if let Some(stroke) = &mut shape.stroke { + stroke.width *= xf.zoom; + } + // This lightweight screen overlay retains the existing display-colour behaviour; document + // rendering still goes through its format/profile path when the shape is committed. + crate::shape_stroke_ui::paint_shape_preview(painter, &shape); + let accent = Tokens::get(painter.ctx()).accent; + for (pts, _) in path_lines(&path, &|q| xf.to_screen(q[0] as f32, q[1] as f32)) { + // The accent path over a dark halo: visible on any pixels (#172). + painter.extend(crate::tool_feedback::contrast_path(pts, true, accent)); + } +} diff --git a/crates/ui-egui/src/vector_ui/tests.rs b/crates/ui-egui/src/vector_ui/tests.rs index 85935eff16..4c12b05401 100644 --- a/crates/ui-egui/src/vector_ui/tests.rs +++ b/crates/ui-egui/src/vector_ui/tests.rs @@ -147,8 +147,7 @@ fn shape_path_row_delete_path_deletes_the_shape_layer() { let layers = doc.layers.len(); let row = path_rows(&doc, shape).into_iter().find(|r| r.kind == PathRow::Layer).unwrap(); assert!(row.name.ends_with(" Shape Path"), "{}", row.name); - let (_, id, params) = - path_context_actions(&row, &doc, shape).into_iter().find(|(label, _, _)| *label == "Delete Path").expect("Delete Path is offered"); + let (_, id, params) = path_context_actions(&row, &doc, shape).into_iter().find(|(label, _, _)| *label == "Delete Path").expect("Delete Path is offered"); app.run(id, params).unwrap(); let doc = &app.session.active().unwrap().doc; assert_eq!(doc.layers.len(), layers - 1); @@ -406,8 +405,7 @@ fn shape_preview_is_the_committed_path() { let mut app = app(); app.ui.tool_options.corner_radius = 8.0; let preview = |app: &PhotocraftApp, tool, end| { - shape_geometry(&app.ui.tool_options, tool, [10.0, 10.0], end, egui::Modifiers::ALT) - .and_then(|p| photocraft_engine::vector_cmds::shape_path(&p).ok()) + shape_geometry(&app.ui.tool_options, tool, [10.0, 10.0], end, egui::Modifiers::ALT).and_then(|p| photocraft_engine::vector_cmds::shape_path(&p).ok()) }; for tool in [Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line] { let shown = preview(&app, tool, [60.0, 30.0]).unwrap(); @@ -778,8 +776,7 @@ fn stale_pen_commits_to_its_owner_across_document_changes() { assert!(app.session.set_active(0)); match action { "open" => { - app.services.import = - Some(Box::new(|name, _, _| Ok((Document::new(name, Size::new(4, 4), ColorMode::Rgb, SampleType::U8), Vec::new())))); + app.services.import = Some(Box::new(|name, _, _| Ok((Document::new(name, Size::new(4, 4), ColorMode::Rgb, SampleType::U8), Vec::new())))); app.open_file("synthetic.png", &[]).unwrap(); } "closeOther" => { From 0a45d8d79b6aa57d27b728c9208358a141f21ff1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:16:33 +0000 Subject: [PATCH 229/259] refactor(ui-egui): split gpu_canvas.rs into gpu_canvas/ --- crates/ui-egui/src/gpu_canvas.rs | 1789 +---------------- crates/ui-egui/src/gpu_canvas/budget.rs | 184 ++ crates/ui-egui/src/gpu_canvas/callback.rs | 207 ++ crates/ui-egui/src/gpu_canvas/doc_textures.rs | 206 ++ crates/ui-egui/src/gpu_canvas/perf.rs | 256 +++ crates/ui-egui/src/gpu_canvas/resources.rs | 383 ++++ crates/ui-egui/src/gpu_canvas/setup.rs | 117 ++ crates/ui-egui/src/gpu_canvas/shaders.rs | 273 +++ crates/ui-egui/src/gpu_canvas/texels.rs | 145 ++ 9 files changed, 1810 insertions(+), 1750 deletions(-) create mode 100644 crates/ui-egui/src/gpu_canvas/budget.rs create mode 100644 crates/ui-egui/src/gpu_canvas/callback.rs create mode 100644 crates/ui-egui/src/gpu_canvas/doc_textures.rs create mode 100644 crates/ui-egui/src/gpu_canvas/perf.rs create mode 100644 crates/ui-egui/src/gpu_canvas/resources.rs create mode 100644 crates/ui-egui/src/gpu_canvas/setup.rs create mode 100644 crates/ui-egui/src/gpu_canvas/shaders.rs create mode 100644 crates/ui-egui/src/gpu_canvas/texels.rs diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rs index 3d5bd18c65..d96eae7dde 100644 --- a/crates/ui-egui/src/gpu_canvas.rs +++ b/crates/ui-egui/src/gpu_canvas.rs @@ -34,6 +34,45 @@ use eframe::wgpu; pub use photocraft_gpu::{DeviceHealth, Fault}; +mod budget; +mod callback; +mod doc_textures; +mod perf; +mod resources; +mod setup; +mod shaders; +mod texels; + +pub use budget::{ + DEFER_PX, MIN_GPU_BUDGET, OVER_BUDGET, OVER_CANVAS_BUDGET, REFRESH_DEFERRED, REFRESH_OVER_BUDGET, canvas_budget, canvas_texture_bytes, memory_budget, + physical_memory, video_memory, vram_share, +}; +#[cfg(test)] +use budget::drm_video_memory; +#[cfg(all(test, windows))] +use budget::{detect_physical_memory, detect_video_memory}; +use callback::CanvasCallback; +#[cfg(test)] +use callback::{filter_mode, map_doc_px, tile_screen_aabb}; +use doc_textures::init_buffer; +#[cfg(test)] +use doc_textures::{mip_count, mip_damage}; +pub use perf::{GpuInfo, Perf, backend_name, now_ms}; +pub use resources::CanvasStyle; +use resources::{DocTextures, Resources, identity_lut_bytes, lut_bind_group}; +#[cfg(test)] +use setup::device_limits_for; +use setup::texture_buffer; +pub use setup::{Refresh, device_descriptor, device_limits, display_texels, timing_features, use_adapter_limits, use_adapter_limits_with, wgpu_setup}; +#[cfg(test)] +use shaders::{CANVAS_WGSL, ENCODE_WGSL, MIP_WGSL}; +pub use texels::{LayerFit, premultiply_rgba8, premultiply_rgba16f}; +#[cfg(test)] +use texels::{f16_to_f32, f32_to_f16}; +#[cfg(not(target_arch = "wasm32"))] +use texels::texel_to_f32; +use texels::{texel_bytes, texels, texels_into}; + /// Default tile side; documents up to this size (and the device limit) use a single texture. pub const DEFAULT_TILE: u32 = 8192; /// Mip levels no larger than this on either side are redrawn whole on every edit rather than @@ -914,1756 +953,6 @@ impl GpuCanvas { } } -/// A CPU composite as the canvas texture stores it (`display`'s encoding; as is without one). -fn texture_buffer<'a>( - display: Option<&photocraft_engine::display_color::CanvasDisplay>, - buf: &'a photocraft_compose::Buffer, -) -> std::borrow::Cow<'a, photocraft_compose::Buffer> { - match display { - Some(d) => d.texture_buffer(buf), - None => std::borrow::Cow::Borrowed(buf), - } -} - -/// A CPU composite `buf` as texels of a `format` canvas texture, in `display`'s encoding: what -/// [`GpuCanvas::upload_rect`] takes. Runs anywhere (a redraw's worker converts its own pieces). -pub fn display_texels( - format: wgpu::TextureFormat, - display: Option<&photocraft_engine::display_color::CanvasDisplay>, - buf: &photocraft_compose::Buffer, -) -> Vec { - texels(format, &texture_buffer(display, buf).px) -} - -/// What a [`GpuCanvas::refresh`] did. -#[derive(Clone, Debug, Default)] -pub struct Refresh { - /// "gpu-rect", "gpu-full" (wgpu compositor), "rect" or "full" (CPU compositor); "lost" or - /// [`REFRESH_OVER_BUDGET`] when nothing was drawn and the caller should use the CPU canvas. - pub kind: &'static str, - /// Pixels refreshed. - pub px: u64, - pub composite_ms: f64, - pub upload_ms: f64, - /// Layer tiles the wgpu compositor uploaded. - pub uploads: u64, - /// How long the GPU spent executing a recent wgpu composite, once its timestamps came back - /// (a frame or two after that refresh, so usually an earlier one than this). It carries its - /// own pixel count and is never this refresh's unless they match. `None` when the device has - /// no timestamp queries, on the CPU compositor, and on wasm: no number at all is reported - /// rather than `composite_ms`, which measures encoding and submitting, not executing. It - /// leaves out layer-tile uploads (`uploads` above counts them), so a first refresh of a - /// document under-reports by more than the few per cent of a warm one. - pub gpu: Option, - /// Why the wgpu compositor wasn't used. - pub fallback: Option, -} - -/// How the app creates its wgpu device: egui's defaults clamped to the adapter's supported limits, -/// with the adapter's own texture and buffer sizes rather than egui's 8192 px cap, so large -/// documents stay on the GPU compositor. -pub fn wgpu_setup() -> egui_wgpu::WgpuSetup { - let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); - use_adapter_limits(&mut setup); - setup -} - -/// Make `setup` request the adapter's own texture and buffer size limits instead of egui's -/// default 8192 px cap (which sent every document wider or taller than 8192 px to the CPU -/// compositor). Other limits use egui's defaults (WebGL2's on GL), clamped to adapter support; -/// features stay egui's default. -pub fn use_adapter_limits(setup: &mut egui_wgpu::WgpuSetup) { - use_adapter_limits_with(setup, |_| {}); -} - -/// [`use_adapter_limits`], calling `on_adapter` with the chosen adapter just before the device -/// is requested (the desktop app records it in its crash-safe startup marker). -pub fn use_adapter_limits_with(setup: &mut egui_wgpu::WgpuSetup, on_adapter: impl Fn(&wgpu::Adapter) + Send + Sync + 'static) { - if let egui_wgpu::WgpuSetup::CreateNew(create) = setup { - create.device_descriptor = std::sync::Arc::new(move |adapter| { - on_adapter(adapter); - device_descriptor(adapter) - }); - } -} - -/// How the app asks for its device: egui's defaults, the adapter's texture and buffer size -/// limits ([`device_limits`]), and timestamp queries where the adapter has them, so the canvas -/// can report how long the GPU actually spends compositing ([`photocraft_gpu::GpuTimer`]). -/// A bench or test that builds its own device should use this rather than [`device_limits`] -/// alone, or it measures a device the app never creates. (`bevel_bench`, `fx_bench` and -/// `interactive_bench` still call [`device_limits`] directly and so report no GPU time.) -pub fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> { - wgpu::DeviceDescriptor { - label: Some("photocraft wgpu device"), - required_limits: device_limits(adapter), - required_features: timing_features(adapter), - ..Default::default() - } -} - -/// The timestamp-query features when the adapter supports all of them, else none: asking for a -/// feature an adapter lacks fails device creation, and a canvas without GPU timing is far better -/// than no canvas. -/// -/// `PHOTOCRAFT_NO_GPU_TIMING` suppresses the request as well as the timer -/// ([`photocraft_gpu::Compositor::measure_gpu_time`]), so the variable also rescues a driver -/// that advertises the features and then fails or misbehaves on device creation — not only one -/// whose timestamps come back wrong. -pub fn timing_features(adapter: &wgpu::Adapter) -> wgpu::Features { - let want = photocraft_gpu::timing::FEATURES; - if std::env::var_os("PHOTOCRAFT_NO_GPU_TIMING").is_some() { - return wgpu::Features::empty(); - } - if adapter.features().contains(want) { want } else { wgpu::Features::empty() } -} - -/// egui's base limits (WebGL2's on GL), clamped to adapter support, with its maximum texture and buffer sizes. -pub fn device_limits(adapter: &wgpu::Adapter) -> wgpu::Limits { - device_limits_for(adapter.get_info().backend, adapter.limits()) -} - -fn device_limits_for(backend: wgpu::Backend, supported: wgpu::Limits) -> wgpu::Limits { - let base = if backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { wgpu::Limits::default() }; - let base = base.or_worse_values_from(&supported); - wgpu::Limits { max_texture_dimension_2d: supported.max_texture_dimension_2d, max_buffer_size: supported.max_buffer_size, ..base } -} - -/// Milliseconds since the process (or page) started, from a monotonic clock. -/// -/// `web_time::Instant` is `std::time::Instant` natively and `performance.now()` on wasm, so frame -/// caps, autosave intervals, preference retry backoff, stroke traces and screenshot deadlines all -/// measure durations the same way on both. The old wasm value was a constant 0, which made every -/// interval comparison (`now >= deadline`) permanently false on the web. -pub fn now_ms() -> f64 { - static START: std::sync::OnceLock = std::sync::OnceLock::new(); - START.get_or_init(web_time::Instant::now).elapsed().as_secs_f64() * 1000.0 -} - -/// UI-thread timings (CPU side), exponentially smoothed. -#[derive(Clone, Debug, Default, serde::Serialize)] -#[serde(rename_all = "camelCase")] -pub struct Perf { - /// Average CPU time building the UI per frame (ms). - pub ui_ms: f64, - /// Worst UI frame of the last ~second (ms). - pub ui_max_ms: f64, - /// Last canvas refresh, CPU side (ms): the CPU composite on the CPU path, and on the GPU - /// path the cost of *encoding and submitting* the composite — not of running it, which is - /// `gpu_ms`. - pub composite_ms: f64, - /// Last canvas refresh: conversion + upload (ms). - pub upload_ms: f64, - /// Last canvas refresh kind: "full", "rect" or "none". - pub last_refresh: &'static str, - /// Pixels in the last refresh. - pub last_refresh_px: u64, - /// Whether the GPU canvas path is active. - pub gpu: bool, - /// Layer tiles uploaded by the last GPU composite. - pub gpu_uploads: u64, - /// How long the GPU spent executing a recent composite (ms), from timestamp queries read - /// back after the fact. `None` on the CPU compositor, on a device without timestamp queries - /// and on wasm — there is then no honest number to report, and `composite_ms` is not one. - /// Excludes layer-tile uploads and end-of-batch work (see `photocraft_gpu::timing`), so it - /// is a few per cent under the GPU's full share of a warm refresh and further under a cold - /// one. - pub gpu_ms: Option, - /// Pixels of the refresh `gpu_ms` measured, which is a frame or two behind - /// `last_refresh_px` and may be a different size. - pub gpu_ms_px: u64, - /// Why the last refresh fell back to the CPU compositor (None = GPU composited). - pub gpu_fallback: Option, - /// Adapter, backend, driver and fallback state (Help › System Info). - pub gpu_info: GpuInfo, - /// GPU memory the compositor may hold for layer pages and effect maps (MB; see - /// [`memory_budget`]). - pub gpu_budget_mb: u64, - /// The Memory Usage allowance and the GPU Memory preference (bytes) `gpu_budget_mb` was - /// computed from. - #[serde(skip)] - pub gpu_budget_allowance: (u64, u64), - /// The layer pages the last full refresh needed against the part of the budget they may - /// hold; when they don't fit, edits that redraw the whole document do it on the CPU. - pub gpu_layer_fit: Option, - /// Last command run through the app and its duration (ms). - pub last_command: String, - pub command_ms: f64, - /// Most recent cost of occasional UI work (outline tracing, thumbnails, …), in ms. - pub spans: std::collections::BTreeMap<&'static str, f64>, - #[serde(skip)] - max_decay: f64, - /// Composite and upload time of this frame's canvas refreshes, in ms (the stroke trace). - #[serde(skip)] - pub(crate) frame_refresh_ms: f64, -} - -/// What the app renders with and why (Help › System Info, Preferences › Performance, the `perf` -/// control-channel output). -#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)] -#[serde(rename_all = "camelCase")] -pub struct GpuInfo { - /// Adapter name ("" before the window opens). - pub adapter: String, - /// wgpu backend of the window's device ("vulkan", "dx12", "metal", "gl", …). - pub backend: String, - /// Device type ("discreteGpu", "integratedGpu", "cpu", …). - pub device_type: String, - /// Driver name and version as the driver reports them. - pub driver: String, - /// The adapter's own memory in MB ([`video_memory`]): discrete GPUs where the platform - /// reports it. It caps the GPU memory budgets. - pub video_memory_mb: Option, - /// `performance.gpuBackend` at launch. - pub preference: String, - /// Every graphics adapter the window could have used, by name (Preferences › Performance › - /// Graphics Adapter lists them). Empty in hosts that don't set it. - pub adapters: Vec, - /// The backend startup chose ("auto", "dx12", "cpu", …, or "env" for `WGPU_BACKEND`). - pub selected: String, - /// Why startup didn't use the preference as is (previous start crashed, `--safe-gpu`, - /// `WGPU_BACKEND`, Intel on Windows). - pub fallback: Option, - /// "gpu" (wgpu canvas and compositor) or "cpu" (CPU compositor, egui textures). - pub canvas: String, - /// Why the GPU canvas was dropped during this session (device lost or a GPU error). - pub lost: Option, - /// Present mode and frame latency ("fifo, latency 2"; launch overrides marked, see the - /// app's `presentation`). Empty in hosts that don't set it. - pub present: String, -} - -impl GpuInfo { - /// Record the adapters the instance found, without duplicates (one GPU shows up once per backend). - pub fn set_available(&mut self, adapters: &[wgpu::Adapter]) { - self.adapters.clear(); - for a in adapters { - let name = a.get_info().name; - if !name.is_empty() && !self.adapters.contains(&name) { - self.adapters.push(name); - } - } - } - - /// Fill the adapter fields from `info`. - pub fn set_adapter(&mut self, info: &wgpu::AdapterInfo) { - self.adapter = info.name.clone(); - self.backend = backend_name(info.backend).to_string(); - self.device_type = match info.device_type { - wgpu::DeviceType::DiscreteGpu => "discreteGpu", - wgpu::DeviceType::IntegratedGpu => "integratedGpu", - wgpu::DeviceType::VirtualGpu => "virtualGpu", - wgpu::DeviceType::Cpu => "cpu", - wgpu::DeviceType::Other => "other", - } - .to_string(); - self.driver = [info.driver.as_str(), info.driver_info.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::>().join(" "); - self.video_memory_mb = video_memory(info).map(|b| b >> 20); - } - - /// Human-readable lines for Help › System Info. - pub fn lines(&self) -> Vec { - let or = |s: &str, d: &str| if s.is_empty() || (s == "auto" && d == "auto") { tl!(d).to_string() } else { s.to_string() }; - let mut v = vec![ - { - let template = "Graphics adapter: {adapter}"; - crate::i18n::fmt(tl!(template), &[("adapter", &or(&self.adapter, "unknown"))]) - }, - { - let template = "Backend: {backend} ({type})"; - crate::i18n::fmt(tl!(template), &[("backend", &or(&self.backend, "unknown")), ("type", &or(&self.device_type, "unknown type"))]) - }, - { - let template = "Driver: {driver}"; - crate::i18n::fmt(tl!(template), &[("driver", &or(&self.driver, "unknown"))]) - }, - ]; - // The card's own memory caps the GPU budgets, so it explains a huge canvas falling back - // to the CPU. Only discrete cards report one (integrated GPUs share system memory). - if let Some(mb) = self.video_memory_mb { - let template = "Graphics memory: {size}"; - v.push(crate::i18n::fmt(tl!(template), &[("size", &crate::chrome_ui::fmt_bytes(mb.saturating_mul(1 << 20)))])); - } - v.extend([ - { - let template = "GPU backend preference: {backend}"; - crate::i18n::fmt(tl!(template), &[("backend", &or(&self.preference, "auto"))]) - }, - { - let template = "Selected at launch: {backend}"; - crate::i18n::fmt(tl!(template), &[("backend", &or(&self.selected, "auto"))]) - }, - { - let template = "Image compositor: {processor}"; - crate::i18n::fmt(tl!(template), &[("processor", if self.canvas == "gpu" { "GPU" } else { "CPU" })]) - }, - { - let template = "Window renderer: {renderer}"; - let renderer = if self.device_type == "cpu" { - "Software adapter" - } else if self.adapter.is_empty() { - "Unknown" - } else { - "Graphics adapter" - }; - crate::i18n::fmt(tl!(template), &[("renderer", tl!(renderer))]) - }, - ]); - if let Some(f) = &self.fallback { - v.push({ - let template = "Fallback: {reason}"; - crate::i18n::fmt(tl!(template), &[("reason", f)]) - }); - } - if let Some(l) = &self.lost { - v.push({ - let template = "This session: {reason}"; - crate::i18n::fmt(tl!(template), &[("reason", l)]) - }); - } - v - } -} - -/// The preference name of a wgpu backend. -pub fn backend_name(b: wgpu::Backend) -> &'static str { - match b { - wgpu::Backend::Vulkan => "vulkan", - wgpu::Backend::Dx12 => "dx12", - wgpu::Backend::Metal => "metal", - wgpu::Backend::Gl => "gl", - wgpu::Backend::BrowserWebGpu => "webgpu", - wgpu::Backend::Noop => "noop", - } -} - -impl Perf { - pub fn record(&mut self, kind: &'static str, px: u64, composite_ms: f64, upload_ms: f64) { - self.frame_refresh_ms += composite_ms + upload_ms; - self.last_refresh = kind; - self.last_refresh_px = px; - self.composite_ms = composite_ms; - self.upload_ms = upload_ms; - if !kind.starts_with("gpu") { - self.gpu_uploads = 0; - // The CPU compositor did this one: there is no GPU time, and the last GPU - // refresh's would be read as this refresh's. - self.gpu_ms = None; - self.gpu_ms_px = 0; - } else { - self.gpu_fallback = None; - } - } - - /// Record a canvas refresh and any GPU measurement that came back with it. - pub fn record_refresh(&mut self, r: &Refresh) { - self.record(r.kind, r.px, r.composite_ms, r.upload_ms); - if let Some(t) = r.gpu { - self.record_gpu(t); - } - } - - /// Record a GPU composite measurement that came back (see [`photocraft_gpu::GpuTiming`]). - pub fn record_gpu(&mut self, t: photocraft_gpu::GpuTiming) { - self.gpu_ms = Some(t.ms); - self.gpu_ms_px = t.px; - } - pub fn span(&mut self, name: &'static str, ms: f64) { - self.spans.insert(name, (ms * 100.0).round() / 100.0); - } - pub fn frame(&mut self, ms: f64) { - self.ui_ms = if self.ui_ms == 0.0 { ms } else { self.ui_ms * 0.9 + ms * 0.1 }; - self.max_decay += 1.0; - if ms > self.ui_max_ms || self.max_decay > 60.0 { - self.ui_max_ms = ms; - self.max_decay = 0.0; - } - } -} - -/// Straight-alpha f32 RGBA (sRGB-encoded) → premultiplied RGBA8, split across threads on native. -pub fn premultiply_rgba8(px: &[[f32; 4]]) -> Vec { - let mut out = Vec::new(); - texels_into(FORMAT, px, &mut out); - out -} - -/// Straight-alpha f32 RGBA (sRGB-encoded) → premultiplied RGBA16F (little-endian), split across -/// threads on native. Colour values above 1.0 are kept (32-bit documents); negatives and NaN -/// become 0. -pub fn premultiply_rgba16f(px: &[[f32; 4]]) -> Vec { - let mut out = Vec::new(); - texels_into(FORMAT_HIGH, px, &mut out); - out -} - -/// Bytes per texel of a canvas texture format. -fn texel_bytes(format: wgpu::TextureFormat) -> u64 { - if format == FORMAT_HIGH { 8 } else { 4 } -} - -/// Straight-alpha f32 RGBA → premultiplied texels of `format`. -fn texels(format: wgpu::TextureFormat, px: &[[f32; 4]]) -> Vec { - let mut out = Vec::new(); - texels_into(format, px, &mut out); - out -} - -/// [`texels`] into `out` (resized; reusing it across bands saves page-faulting a fresh buffer). -fn texels_into(format: wgpu::TextureFormat, px: &[[f32; 4]], out: &mut Vec) { - fn rgba8(src: &[[f32; 4]], dst: &mut [u8]) { - for (o, p) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src) { - let a = p[3].clamp(0.0, 1.0); - o[0] = (p[0].clamp(0.0, 1.0) * a * 255.0 + 0.5) as u8; - o[1] = (p[1].clamp(0.0, 1.0) * a * 255.0 + 0.5) as u8; - o[2] = (p[2].clamp(0.0, 1.0) * a * 255.0 + 0.5) as u8; - o[3] = (a * 255.0 + 0.5) as u8; - } - } - fn rgba16f(src: &[[f32; 4]], dst: &mut [u8]) { - for (o, p) in dst.as_chunks_mut::<8>().0.iter_mut().zip(src) { - let a = if p[3].is_nan() { 0.0 } else { p[3].clamp(0.0, 1.0) }; - let [r, g, b, a] = [p[0].max(0.0) * a, p[1].max(0.0) * a, p[2].max(0.0) * a, a].map(|v| f32_to_f16(v).to_le_bytes()); - *o = [r[0], r[1], g[0], g[1], b[0], b[1], a[0], a[1]]; - } - } - let bpp = texel_bytes(format) as usize; - let convert = if format == FORMAT_HIGH { rgba16f } else { rgba8 }; - out.clear(); - out.resize(px.len() * bpp, 0); - #[cfg(not(target_arch = "wasm32"))] - if px.len() > 1 << 18 { - let threads = std::thread::available_parallelism().map_or(4, |n| n.get()).min(16); - let chunk = px.len().div_ceil(threads); - std::thread::scope(|s| { - for (src, dst) in px.chunks(chunk).zip(out.chunks_mut(chunk * bpp)) { - s.spawn(move || convert(src, dst)); - } - }); - return; - } - convert(px, out); -} - -/// IEEE 754 binary32 → binary16, round to nearest even; overflow saturates to the largest -/// finite half (65504) so HDR values never become infinite, NaN becomes 0. Branch-light: the -/// rounding is done with integer adds on the f32 bits (and an f32 add for subnormals). -fn f32_to_f16(v: f32) -> u16 { - // 2^-14: the smallest normal half; below it the result is subnormal (or zero). - const MIN_NORMAL: u32 = 113 << 23; - // 2^16: halves overflow from here (65520 and up round to infinity; saturate instead). - const OVERFLOW: u32 = 143 << 23; - // Adding 0.5 (as f32) shifts a subnormal half's bits to the bottom of the mantissa. - const DENORM_MAGIC: u32 = 126 << 23; - let bits = v.to_bits(); - let sign = ((bits >> 16) & 0x8000) as u16; - let a = bits & 0x7fff_ffff; - if a > 0x7f80_0000 { - return 0; - } - let h = if a >= OVERFLOW { - 0x7bff - } else if a < MIN_NORMAL { - (f32::from_bits(a) + f32::from_bits(DENORM_MAGIC)).to_bits().wrapping_sub(DENORM_MAGIC) as u16 - } else { - // Rebias the exponent and round the 13 dropped mantissa bits to nearest even. - let odd = (a >> 13) & 1; - (((a.wrapping_add(0xc800_0fff).wrapping_add(odd)) >> 13).min(0x7bff)) as u16 - }; - sign | h -} - -/// IEEE 754 binary16 → binary32. -#[cfg(not(target_arch = "wasm32"))] -fn f16_to_f32(h: u16) -> f32 { - let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; - let exp = i32::from((h >> 10) & 0x1f); - let man = f32::from(h & 0x3ff); - sign * match exp { - 0 => man * 2f32.powi(-24), - 0x1f => { - if man == 0.0 { - f32::INFINITY - } else { - f32::NAN - } - } - e => (1.0 + man / 1024.0) * 2f32.powi(e - 15), - } -} - -/// One stored texel of `format` as f32 RGBA. -#[cfg(not(target_arch = "wasm32"))] -fn texel_to_f32(format: wgpu::TextureFormat, b: &[u8]) -> [f32; 4] { - let mut o = [0.0f32; 4]; - for (i, v) in o.iter_mut().enumerate() { - *v = if format == FORMAT_HIGH { - f16_to_f32(u16::from_le_bytes([b.get(i * 2).copied().unwrap_or(0), b.get(i * 2 + 1).copied().unwrap_or(0)])) - } else { - f32::from(b.get(i).copied().unwrap_or(0)) / 255.0 - }; - } - o -} - -// --------------------------------------------------------------------------------------------- -// GPU resources - -/// The GPU memory a refresh's layer pages need against what they may hold (bytes). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] -#[serde(rename_all = "camelCase")] -pub struct LayerFit { - /// The document refreshed. - pub doc: u64, - pub needed: u64, - pub budget: u64, -} - -impl LayerFit { - pub fn fits(&self) -> bool { - self.needed <= self.budget - } -} - -/// Floor of the compositor's memory budget: enough for a viewport's pages of a dozen layers. -pub const MIN_GPU_BUDGET: u64 = 512 << 20; - -/// Why a full refresh whose layer pages don't fit [`memory_budget`] (or GPU memory) goes to the -/// CPU compositor. -pub const OVER_BUDGET: &str = photocraft_gpu::OVER_BUDGET; - -/// GPU memory the wgpu compositor may hold for layer pages and effect maps. -/// -/// `fixed` (Preferences › Performance › GPU Memory, bytes) sets it when it isn't 0, within -/// [`vram_share`] of a discrete GPU's own memory (`vram`, from [`video_memory`]). Otherwise it is -/// Memory Usage (`allowance`) within a quarter of physical memory (`ram`; 16 GB assumed when -/// unknown) and the VRAM share. The document's pixels and History (`pixels`) come off Memory Usage -/// unless the card's own memory is known: a discrete card doesn't hold them, while integrated and -/// software adapters (and a card whose memory can't be read) share the system's. Never below -/// [`MIN_GPU_BUDGET`]. Layers beyond it redraw full refreshes on the CPU ([`OVER_BUDGET`]). -pub fn memory_budget(allowance: u64, pixels: u64, ram: Option, vram: Option, fixed: u64) -> u64 { - let card = vram.map_or(u64::MAX, vram_share); - if fixed > 0 { - return fixed.min(card).max(MIN_GPU_BUDGET); - } - let ram = ram.unwrap_or(16 << 30); - let charged = if vram.is_some() { 0 } else { pixels }; - allowance.saturating_sub(charged).min(ram / 4).min(card).max(MIN_GPU_BUDGET) -} - -/// The share of a discrete GPU's memory each of [`memory_budget`] and [`canvas_budget`] may -/// plan for: three eighths, so the two together leave a quarter of the card to the window's -/// swapchain, egui and other applications instead of over-committing it and letting the driver -/// page (#4536). -pub fn vram_share(vram: u64) -> u64 { - vram / 8 * 3 -} - -/// Why a document whose display textures don't fit [`canvas_budget`] is drawn on the CPU canvas. -pub const OVER_CANVAS_BUDGET: &str = "the canvas exceeds the GPU texture budget; drawing it on the CPU canvas"; - -/// [`Refresh::kind`] when the document's display textures don't fit [`canvas_budget`]: nothing -/// was created, and the caller draws the CPU canvas instead. -pub const REFRESH_OVER_BUDGET: &str = "over-budget"; - -/// [`Refresh::kind`] of a CPU refresh left to the caller ([`GpuCanvas::refresh_with`]). -pub const REFRESH_DEFERRED: &str = "deferred"; - -/// The smallest CPU refresh (pixels) [`GpuCanvas::refresh_with`] defers: below it, the -/// synchronous composite takes a fraction of a second even with many layers. -pub const DEFER_PX: u64 = 1 << 22; - -/// GPU bytes one document's display texture set (every tile and mip level) may take: a quarter -/// of physical memory (`ram`; 16 GB assumed when unknown) and at most [`vram_share`] of a -/// discrete GPU's own memory (`vram`), at least [`MIN_GPU_BUDGET`]. The set covers the whole -/// canvas at full resolution, so its size follows the declared canvas, not the layer pixels; a -/// larger canvas is drawn on the (reduced) CPU canvas instead (#2934). -pub fn canvas_budget(ram: Option, vram: Option) -> u64 { - (ram.unwrap_or(16 << 30) / 4).min(vram.map_or(u64::MAX, vram_share)).max(MIN_GPU_BUDGET) -} - -/// GPU bytes of a display texture set for a `size` canvas in `tile`-sided tiles of `bpp` bytes -/// per texel, with every mip level (what [`GpuCanvas::texture_info`] reports once it exists). -/// Closed form over the (at most four) distinct tile shapes, so any size is cheap to price. -pub fn canvas_texture_bytes(size: [u32; 2], tile: u32, bpp: u64) -> u64 { - let tile = tile.max(1); - // (how many tiles, their side) along one axis: whole tiles, then the remainder. - let spans = |n: u32| [(n / tile, tile), (u32::from(!n.is_multiple_of(tile)), n % tile)]; - let mut total = 0u64; - for (nx, w) in spans(size[0]) { - for (ny, h) in spans(size[1]) { - if nx == 0 || ny == 0 { - continue; - } - let one = (0..mip_count(w, h)).map(|l| u64::from((w >> l).max(1)) * u64::from((h >> l).max(1)) * bpp).fold(0, u64::saturating_add); - total = total.saturating_add(one.saturating_mul(u64::from(nx) * u64::from(ny))); - } - } - total -} - -/// Physical memory of this machine in bytes, if known. `PHOTOCRAFT_RAM_MB` overrides it (to -/// simulate a smaller machine). -pub fn physical_memory() -> Option { - static RAM: std::sync::OnceLock> = std::sync::OnceLock::new(); - *RAM.get_or_init(|| { - if let Some(mb) = std::env::var("PHOTOCRAFT_RAM_MB").ok().and_then(|v| v.trim().parse::().ok()) { - return mb.checked_mul(1 << 20); - } - detect_physical_memory() - }) -} - -#[cfg(target_os = "macos")] -fn detect_physical_memory() -> Option { - let out = std::process::Command::new("/usr/sbin/sysctl").args(["-n", "hw.memsize"]).output().ok()?; - String::from_utf8(out.stdout).ok()?.trim().parse().ok() -} - -#[cfg(target_os = "linux")] -fn detect_physical_memory() -> Option { - let info = std::fs::read_to_string("/proc/meminfo").ok()?; - let kb: u64 = info.lines().find_map(|l| l.strip_prefix("MemTotal:"))?.trim().trim_end_matches("kB").trim().parse().ok()?; - kb.checked_mul(1024) -} - -#[cfg(target_os = "freebsd")] -fn detect_physical_memory() -> Option { - let out = std::process::Command::new("/sbin/sysctl").args(["-n", "hw.physmem"]).output().ok()?; - String::from_utf8(out.stdout).ok()?.trim().parse().ok() -} - -#[cfg(windows)] -fn detect_physical_memory() -> Option { - winsafe::GlobalMemoryStatusEx().map(|m| m.ullTotalPhys).ok().filter(|b| *b > 0) -} - -#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "freebsd", windows)))] -fn detect_physical_memory() -> Option { - None -} - -/// The memory of `adapter` itself, in bytes, when it is a discrete GPU and the platform reports -/// it: DXGI's dedicated video memory on Windows, amdgpu's VRAM size on Linux. `None` for -/// integrated and software adapters, whose textures live in system memory (the RAM-based -/// budgets already cover them), and where nothing reports it. `PHOTOCRAFT_VRAM_MB` overrides it -/// for any adapter, simulating a discrete card of that size: on an integrated GPU the budget then -/// stops charging the document's pixels too, as for a real card (a development switch). -pub fn video_memory(adapter: &wgpu::AdapterInfo) -> Option { - if let Some(mb) = std::env::var("PHOTOCRAFT_VRAM_MB").ok().and_then(|v| v.trim().parse::().ok()) { - return mb.checked_mul(1 << 20).filter(|b| *b > 0); - } - if adapter.device_type != wgpu::DeviceType::DiscreteGpu { - return None; - } - // Detected once per adapter, as `physical_memory` is: on Windows each detection builds a - // DXGI factory, and startup asks three times. Keyed by the adapter, since a GPU retry can - // pick another one. - /// (vendor, device) ids and the memory found for them. - type Seen = Vec<((u32, u32), Option)>; - static SEEN: std::sync::Mutex = std::sync::Mutex::new(Vec::new()); - let key = (adapter.vendor, adapter.device); - let mut seen = SEEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some((_, bytes)) = seen.iter().find(|(k, _)| *k == key) { - return *bytes; - } - let bytes = detect_video_memory(key.0, key.1).filter(|b| *b > 0); - seen.push((key, bytes)); - bytes -} - -#[cfg(windows)] -fn detect_video_memory(vendor: u32, device: u32) -> Option { - use winsafe::prelude::*; - let factory = winsafe::CreateDXGIFactory1().ok()?; - factory - .EnumAdapters1() - .filter_map(|a| a.ok()?.GetDesc1().ok()) - .find(|d| d.VendorId == vendor && d.DeviceId == device) - .and_then(|d| u64::try_from(d.DedicatedVideoMemory).ok()) -} - -#[cfg(target_os = "linux")] -fn detect_video_memory(vendor: u32, device: u32) -> Option { - drm_video_memory(std::path::Path::new("/sys/class/drm"), vendor, device) -} - -/// amdgpu's VRAM size (`/device/mem_info_vram_total`, bytes) of the card under `drm` (the -/// sysfs `/sys/class/drm` folder) whose PCI `vendor` and `device` ids (hex files beside it) match. -#[cfg(any(target_os = "linux", test))] -fn drm_video_memory(drm: &std::path::Path, vendor: u32, device: u32) -> Option { - let hex = |p: std::path::PathBuf| u32::from_str_radix(std::fs::read_to_string(p).ok()?.trim().trim_start_matches("0x"), 16).ok(); - std::fs::read_dir(drm).ok()?.flatten().find_map(|card| { - let dev = card.path().join("device"); - if hex(dev.join("vendor"))? != vendor || hex(dev.join("device"))? != device { - return None; - } - std::fs::read_to_string(dev.join("mem_info_vram_total")).ok()?.trim().parse().ok() - }) -} - -#[cfg(not(any(target_os = "linux", windows)))] -fn detect_video_memory(_vendor: u32, _device: u32) -> Option { - None -} - -struct Resources { - view_bgl: wgpu::BindGroupLayout, - tile_bgl: wgpu::BindGroupLayout, - shadow_pipeline: wgpu::RenderPipeline, - tile_pipeline: wgpu::RenderPipeline, - sampler: wgpu::Sampler, - mip_bgl: wgpu::BindGroupLayout, - mip_pipeline: wgpu::RenderPipeline, - /// `mip_pipeline` and `encode_pipeline` for `Rgba16Float` tiles (when the adapter supports them). - mip_pipeline_high: Option, - encode_pipeline_high: Option, - mip_sampler: wgpu::Sampler, - docs: HashMap, - views: HashMap, - out_linear: bool, - /// Build each mip level in a scratch texture and copy it back instead of rendering into - /// the level directly (see [`separate_mip_targets`]). - separate_mip_targets: bool, - /// The wgpu layer compositor (created on first use). - compositor: Option, - /// Why the wgpu compositor couldn't be created (then the CPU compositor is used). - compositor_failed: Option, - /// The device's health: the paint callback issues no GPU work once it's lost. - health: photocraft_gpu::DeviceHealth, - /// GPU memory the compositor may hold (`None`: its default), and the document area the - /// view shows; applied before every composite. - compositor_budget: Option, - /// The layer pages the last full (or large) refresh needed and the budget they had to fit - /// (bytes): when they don't fit, full refreshes go to the CPU ([`OVER_BUDGET`]). - layer_fit: Option, - compositor_cache_budget: Option, - compositor_focus: Option, - /// GPU bytes one document's display texture set may take (see [`canvas_budget`]). - canvas_budget: std::sync::Arc, - encode_bgl: wgpu::BindGroupLayout, - encode_pipeline: wgpu::RenderPipeline, - lut_bgl: wgpu::BindGroupLayout, - /// Display LUTs per (document, display) (monitor profile, Proof Colors / Gamut Warning); - /// `identity_lut` otherwise. - luts: HashMap<(u64, u32), wgpu::BindGroup>, - /// Signatures belong to their renderer resources, including identity transforms (mode 0). - display_lut_signatures: HashMap<(u64, u32), (u64, u8)>, - identity_lut: wgpu::BindGroup, - /// Transparency checkerboard and gamut warning colours (Preferences › Transparency & Gamut). - style: CanvasStyle, -} - -/// Canvas colours from Preferences › Transparency & Gamut. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct CanvasStyle { - /// Checker square side in points (0 = no checkerboard: transparency shows white). - pub checker_square: f32, - pub checker_light: [f32; 3], - pub checker_dark: [f32; 3], - pub gamut_color: [f32; 3], - /// Gamut warning opacity 0..1. - pub gamut_opacity: f32, -} - -impl Default for CanvasStyle { - fn default() -> Self { - Self { checker_square: 8.0, checker_light: [1.0; 3], checker_dark: [0.8; 3], gamut_color: [0.5; 3], gamut_opacity: 1.0 } - } -} - -/// A display transform: either the existing 3D LUT or separate full-float shapers and -/// matrix. Pack curves into short rows to stay within WebGL2's texture-size limits. -fn lut_bind_group( - device: &wgpu::Device, - queue: &wgpu::Queue, - bgl: &wgpu::BindGroupLayout, - size: u32, - bytes: &[u8], - shaper: Option<&photocraft_cms::GpuMatrixShaper>, -) -> wgpu::BindGroup { - let extent = wgpu::Extent3d { width: size, height: size, depth_or_array_layers: size }; - let texture = device.create_texture(&wgpu::TextureDescriptor { - label: Some("pc_display_lut"), - size: extent, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D3, - format: FORMAT, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - queue.write_texture( - wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size * 4), rows_per_image: Some(size) }, - extent, - ); - let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); - let (width, height, curves, matrix) = if let Some(s) = shaper { - let width = 1024usize; - let count = s.input_table().len() + s.output_table().len(); - let height = count.div_ceil(width); - let mut curves = Vec::with_capacity(width * height * 16); - for value in s.input_table().iter().chain(s.output_table()).flatten() { - curves.extend_from_slice(&value.to_le_bytes()); - } - curves.resize(width * height * 16, 0); - (width as u32, height as u32, curves, s.matrix_rows()) - } else { - (1, 1, vec![0; 16], [[0.0; 4]; 3]) - }; - let extent = wgpu::Extent3d { width, height, depth_or_array_layers: 1 }; - let curves_texture = device.create_texture(&wgpu::TextureDescriptor { - label: Some("pc_display_shapers"), - size: extent, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - // textureLoad + explicit interpolation needs no optional float-filtering feature. - format: wgpu::TextureFormat::Rgba32Float, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - queue.write_texture( - wgpu::TexelCopyTextureInfo { texture: &curves_texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - &curves, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(width * 16), rows_per_image: Some(height) }, - extent, - ); - let curves_view = curves_texture.create_view(&wgpu::TextureViewDescriptor::default()); - let matrix_bytes: Vec = matrix.iter().flatten().flat_map(|v| v.to_le_bytes()).collect(); - let matrix_buffer = init_buffer(device, "pc_display_matrix", &matrix_bytes, wgpu::BufferUsages::UNIFORM); - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("pc_display_lut"), - layout: bgl, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&curves_view) }, - wgpu::BindGroupEntry { binding: 2, resource: matrix_buffer.as_entire_binding() }, - ], - }) -} - -/// The 2³ identity LUT (unused unless a document has none and `display` is set). -fn identity_lut_bytes() -> Vec { - (0..8).flat_map(|i| [if i & 1 != 0 { 255 } else { 0 }, if i & 2 != 0 { 255 } else { 0 }, if i & 4 != 0 { 255 } else { 0 }, 0]).collect() -} - -struct ViewGpu { - buffer: wgpu::Buffer, - bind_group: wgpu::BindGroup, - frame_data: [f32; VIEW_FLOATS], -} - -struct DocTextures { - size: [u32; 2], - format: wgpu::TextureFormat, - tiles: Vec, -} - -struct Tile { - /// Document-pixel rect: x, y, w, h. - rect: [u32; 4], - texture: wgpu::Texture, - levels: Vec, - bind_group: wgpu::BindGroup, - _uniform: wgpu::Buffer, -} - -fn uniform_entry(binding: u32, size: u64, vis: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry { - wgpu::BindGroupLayoutEntry { - binding, - visibility: vis, - ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: NonZeroU64::new(size) }, - count: None, - } -} -fn texture_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { - wgpu::BindGroupLayoutEntry { - binding, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - multisampled: false, - sample_type: wgpu::TextureSampleType::Float { filterable: true }, - view_dimension: wgpu::TextureViewDimension::D2, - }, - count: None, - } -} -fn sampler_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { - wgpu::BindGroupLayoutEntry { - binding, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), - count: None, - } -} - -fn f32_bytes(v: &[f32]) -> Vec { - v.iter().flat_map(|f| f.to_ne_bytes()).collect() -} - -fn pipeline( - device: &wgpu::Device, - label: &str, - layout: &wgpu::PipelineLayout, - module: &wgpu::ShaderModule, - (vs, fs): (&str, &str), - format: wgpu::TextureFormat, - blend: Option, -) -> wgpu::RenderPipeline { - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(label), - layout: Some(layout), - vertex: wgpu::VertexState { module, entry_point: Some(vs), buffers: &[], compilation_options: Default::default() }, - primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, - depth_stencil: None, - multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false }, - fragment: Some(wgpu::FragmentState { - module, - entry_point: Some(fs), - targets: &[Some(wgpu::ColorTargetState { format, blend, write_mask: wgpu::ColorWrites::ALL })], - compilation_options: Default::default(), - }), - multiview_mask: None, - cache: None, - }) -} - -impl Resources { - fn new(device: &wgpu::Device, queue: &wgpu::Queue, target: wgpu::TextureFormat, high: bool) -> Self { - let module = - device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_canvas"), source: wgpu::ShaderSource::Wgsl(CANVAS_WGSL.into()) }); - let vis = wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT; - let view_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("pc_canvas_view"), - entries: &[uniform_entry(0, VIEW_UNIFORM_SIZE, vis), sampler_entry(1)], - }); - let tile_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("pc_canvas_tile"), - entries: &[texture_entry(0), uniform_entry(1, TILE_UNIFORM_SIZE, vis)], - }); - let lut_entry = wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - multisampled: false, - sample_type: wgpu::TextureSampleType::Float { filterable: true }, - view_dimension: wgpu::TextureViewDimension::D3, - }, - count: None, - }; - let curves_entry = wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - multisampled: false, - sample_type: wgpu::TextureSampleType::Float { filterable: false }, - view_dimension: wgpu::TextureViewDimension::D2, - }, - count: None, - }; - let lut_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("pc_display_lut"), - entries: &[lut_entry, curves_entry, uniform_entry(2, 48, wgpu::ShaderStages::FRAGMENT)], - }); - let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("pc_canvas"), - bind_group_layouts: &[Some(&view_bgl), Some(&tile_bgl), Some(&lut_bgl)], - immediate_size: 0, - }); - let shadow_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("pc_canvas_shadow"), - bind_group_layouts: &[Some(&view_bgl)], - immediate_size: 0, - }); - // Premultiplied "over", with egui's alpha rule (keeps a transparent window's alpha sane). - let blend = wgpu::BlendState { - color: wgpu::BlendComponent { - src_factor: wgpu::BlendFactor::One, - dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, - operation: wgpu::BlendOperation::Add, - }, - alpha: wgpu::BlendComponent { - src_factor: wgpu::BlendFactor::OneMinusDstAlpha, - dst_factor: wgpu::BlendFactor::One, - operation: wgpu::BlendOperation::Add, - }, - }; - let shadow_pipeline = pipeline(device, "pc_canvas_shadow", &shadow_layout, &module, ("vs_shadow", "fs_shadow"), target, Some(blend)); - let tile_pipeline = pipeline(device, "pc_canvas_tile", &layout, &module, ("vs_tile", "fs_tile"), target, Some(blend)); - let sampler = device.create_sampler(&wgpu::SamplerDescriptor { - label: Some("pc_canvas_trilinear"), - mag_filter: wgpu::FilterMode::Linear, - min_filter: wgpu::FilterMode::Linear, - mipmap_filter: wgpu::MipmapFilterMode::Linear, - ..Default::default() - }); - - let mip_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_mip"), source: wgpu::ShaderSource::Wgsl(MIP_WGSL.into()) }); - let mip_bgl = - device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_mip"), entries: &[texture_entry(0), sampler_entry(1)] }); - let mip_layout = - device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pc_mip"), bind_group_layouts: &[Some(&mip_bgl)], immediate_size: 0 }); - let mip_pipeline = pipeline(device, "pc_mip", &mip_layout, &mip_module, ("vs", "fs"), FORMAT, None); - let mip_pipeline_high = high.then(|| pipeline(device, "pc_mip_16f", &mip_layout, &mip_module, ("vs", "fs"), FORMAT_HIGH, None)); - let mip_sampler = device.create_sampler(&wgpu::SamplerDescriptor { - label: Some("pc_mip"), - mag_filter: wgpu::FilterMode::Linear, - min_filter: wgpu::FilterMode::Linear, - ..Default::default() - }); - // Compositor output (straight RGBA32F chunk) -> premultiplied RGBA8 display tile. - let encode_module = - device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_encode"), source: wgpu::ShaderSource::Wgsl(ENCODE_WGSL.into()) }); - let unfilterable = wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - multisampled: false, - sample_type: wgpu::TextureSampleType::Float { filterable: false }, - view_dimension: wgpu::TextureViewDimension::D2, - }, - count: None, - }; - let encode_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("pc_encode"), - entries: &[unfilterable, uniform_entry(1, 16, wgpu::ShaderStages::FRAGMENT)], - }); - let encode_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("pc_encode"), - bind_group_layouts: &[Some(&encode_bgl)], - immediate_size: 0, - }); - let encode_pipeline = pipeline(device, "pc_encode", &encode_layout, &encode_module, ("vs", "fs"), FORMAT, None); - let encode_pipeline_high = high.then(|| pipeline(device, "pc_encode_16f", &encode_layout, &encode_module, ("vs", "fs"), FORMAT_HIGH, None)); - let identity_lut = lut_bind_group(device, queue, &lut_bgl, 2, &identity_lut_bytes(), None); - Self { - lut_bgl, - luts: HashMap::new(), - display_lut_signatures: HashMap::new(), - identity_lut, - style: CanvasStyle::default(), - view_bgl, - tile_bgl, - shadow_pipeline, - tile_pipeline, - sampler, - mip_bgl, - mip_pipeline, - mip_pipeline_high, - encode_pipeline_high, - mip_sampler, - docs: HashMap::new(), - views: HashMap::new(), - out_linear: target.is_srgb(), - separate_mip_targets: false, - compositor: None, - compositor_failed: None, - health: photocraft_gpu::DeviceHealth::new(), - compositor_budget: None, - layer_fit: None, - compositor_cache_budget: None, - compositor_focus: None, - canvas_budget: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(canvas_budget(physical_memory(), None))), - encode_bgl, - encode_pipeline, - } - } - - /// The pipeline encoding compositor output into a `format` tile. - fn encode_pipeline(&self, format: wgpu::TextureFormat) -> Option<&wgpu::RenderPipeline> { - if format == FORMAT_HIGH { self.encode_pipeline_high.as_ref() } else { Some(&self.encode_pipeline) } - } - - /// The mip-chain pipeline for `format` tiles. - fn mip_pipeline(&self, format: wgpu::TextureFormat) -> Option<&wgpu::RenderPipeline> { - if format == FORMAT_HIGH { self.mip_pipeline_high.as_ref() } else { Some(&self.mip_pipeline) } - } -} - -fn mip_count(w: u32, h: u32) -> u32 { - 32 - w.max(h).max(1).leading_zeros() -} - -/// The rect (x0, y0, x1, y1) of a `lw`×`lh` mip level to redraw when `prev` changed in the level -/// above: that damage halved and padded by one texel for odd-size rounding, or the whole level -/// when it is at most [`WHOLE_MIP_SIDE`] on either side. On AMD's Vulkan driver a pass that draws -/// only part of a level of 64 px or less corrupts texels outside its scissor, at the level's -/// top-left (#6418: RX 6900 XT, driver 26.8.1; DX12 on the same card is fine). Such a level costs -/// next to nothing to redraw, so this holds for every adapter; the levels after it are smaller -/// still, so the rest of the chain is redrawn whole too. -fn mip_damage([x0, y0, x1, y1]: [u32; 4], lw: u32, lh: u32) -> [u32; 4] { - if lw.max(lh) <= WHOLE_MIP_SIDE { - return [0, 0, lw, lh]; - } - [(x0 / 2).saturating_sub(1), (y0 / 2).saturating_sub(1), (x1.div_ceil(2) + 1).min(lw), (y1.div_ceil(2) + 1).min(lh)] -} - -/// A buffer holding `contents`, like `DeviceExt::create_buffer_init` but without its panic when -/// the device was lost (an invalid buffer has no mapped range): the buffer is then just invalid. -fn init_buffer(device: &wgpu::Device, label: &str, contents: &[u8], usage: wgpu::BufferUsages) -> wgpu::Buffer { - let size = (contents.len() as u64).next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT).max(wgpu::COPY_BUFFER_ALIGNMENT); - let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage, mapped_at_creation: true }); - if let Ok(mut view) = buffer.slice(..).get_mapped_range_mut() - && view.len() >= contents.len() - { - view.slice(..contents.len()).copy_from_slice(contents); - } - buffer.unmap(); - buffer -} - -impl DocTextures { - /// The texture set for a `size` canvas, or `None` (nothing created) when it doesn't fit - /// the canvas budget or the GPU's memory. A set the GPU can't hold (a 3 GP canvas is 16 GB - /// of textures, #4017) lowers the budget below it, so that canvas and larger ones are drawn - /// on the CPU canvas instead of the out-of-memory error disabling the GPU for the session. - fn new(device: &wgpu::Device, res: &Resources, size: [u32; 2], tile: u32, format: wgpu::TextureFormat) -> Option { - let bytes = canvas_texture_bytes(size, tile, texel_bytes(format)); - if bytes > res.canvas_budget.load(Ordering::Relaxed) { - return None; - } - let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); - let memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); - let set = Self::create(device, res, size, tile, format); - // Native wgpu reports these synchronously; where they arrive later (WebGPU) none is seen. - let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); - let mut error = None; - for pop in [memory.pop(), validation.pop()] { - if let std::task::Poll::Ready(Some(e)) = std::pin::pin!(pop).poll(&mut cx) { - error.get_or_insert(e); - } - } - if let Some(e) = error { - log::warn!("{} MB of canvas textures failed ({e}); larger canvases are drawn on the CPU", bytes >> 20); - res.canvas_budget.fetch_min(bytes.saturating_sub(1), Ordering::Relaxed); - return None; - } - Some(set) - } - - fn create(device: &wgpu::Device, res: &Resources, size: [u32; 2], tile: u32, format: wgpu::TextureFormat) -> Self { - let mut tiles = Vec::new(); - for ty in (0..size[1]).step_by(tile as usize) { - for tx in (0..size[0]).step_by(tile as usize) { - let (w, h) = (tile.min(size[0] - tx), tile.min(size[1] - ty)); - let levels_n = mip_count(w, h); - let texture = device.create_texture(&wgpu::TextureDescriptor { - label: Some("pc_canvas_tile"), - size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, - mip_level_count: levels_n, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format, - usage: wgpu::TextureUsages::TEXTURE_BINDING - | wgpu::TextureUsages::COPY_DST - | wgpu::TextureUsages::COPY_SRC - | wgpu::TextureUsages::RENDER_ATTACHMENT, - view_formats: &[], - }); - let levels = (0..levels_n) - .map(|l| texture.create_view(&wgpu::TextureViewDescriptor { base_mip_level: l, mip_level_count: Some(1), ..Default::default() })) - .collect(); - let full = texture.create_view(&wgpu::TextureViewDescriptor::default()); - let uniform = init_buffer(device, "pc_canvas_tile", &f32_bytes(&[tx as f32, ty as f32, w as f32, h as f32]), wgpu::BufferUsages::UNIFORM); - let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("pc_canvas_tile"), - layout: &res.tile_bgl, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&full) }, - wgpu::BindGroupEntry { binding: 1, resource: uniform.as_entire_binding() }, - ], - }); - tiles.push(Tile { rect: [tx, ty, w, h], texture, levels, bind_group, _uniform: uniform }); - } - } - Self { size, format, tiles } - } - - /// Write `size` pixels at document `origin` from `texels` (in the texture format, row stride - /// `stride` pixels) into every overlapping tile's level 0. - fn write(&self, queue: &wgpu::Queue, origin: [u32; 2], size: [u32; 2], stride: u32, texels: &[u8]) { - let bpp = texel_bytes(self.format); - let (x0, y0, x1, y1) = (origin[0], origin[1], origin[0] + size[0], origin[1] + size[1]); - for t in &self.tiles { - let [tx, ty, tw, th] = t.rect; - let (ix0, iy0, ix1, iy1) = (x0.max(tx), y0.max(ty), x1.min(tx + tw), y1.min(ty + th)); - if ix0 >= ix1 || iy0 >= iy1 { - continue; - } - let offset = ((iy0 - y0) as u64 * stride as u64 + (ix0 - x0) as u64) * bpp; - queue.write_texture( - wgpu::TexelCopyTextureInfo { - texture: &t.texture, - mip_level: 0, - origin: wgpu::Origin3d { x: ix0 - tx, y: iy0 - ty, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - texels, - wgpu::TexelCopyBufferLayout { offset, bytes_per_row: Some(stride * bpp as u32), rows_per_image: Some(iy1 - iy0) }, - wgpu::Extent3d { width: ix1 - ix0, height: iy1 - iy0, depth_or_array_layers: 1 }, - ); - } - } - - /// Rebuild the mip chain inside document rect `r` (x0, y0, x1, y1) with 2×2 box filtering. - fn regenerate_mips(&self, device: &wgpu::Device, queue: &wgpu::Queue, res: &Resources, r: [u32; 4]) { - let Some(mip_pipeline) = res.mip_pipeline(self.format) else { return }; - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_mips") }); - for t in &self.tiles { - let [tx, ty, tw, th] = t.rect; - let (mut x0, mut y0, mut x1, mut y1) = (r[0].max(tx), r[1].max(ty), r[2].min(tx + tw), r[3].min(ty + th)); - if x0 >= x1 || y0 >= y1 { - continue; - } - (x0, y0, x1, y1) = (x0 - tx, y0 - ty, x1 - tx, y1 - ty); - for level in 1..t.levels.len() { - let (lw, lh) = ((tw >> level).max(1), (th >> level).max(1)); - [x0, y0, x1, y1] = mip_damage([x0, y0, x1, y1], lw, lh); - let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("pc_mip"), - layout: &res.mip_bgl, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&t.levels[level - 1]) }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&res.mip_sampler) }, - ], - }); - // Keep the sampled source and render attachment in separate resources on Intel - // DX12 adapters ([`separate_mip_targets`]): some of their drivers corrupt reduced - // previews when both are mip levels of the same texture, even though the - // subresources do not overlap. Elsewhere render straight into the level, which - // spares a scratch texture and a copy per level on every edit. - let scratch = res.separate_mip_targets.then(|| { - let scratch = device.create_texture(&wgpu::TextureDescriptor { - label: Some("pc_mip_scratch"), - size: wgpu::Extent3d { width: lw, height: lh, depth_or_array_layers: 1 }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: self.format, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, - view_formats: &[], - }); - let view = scratch.create_view(&Default::default()); - (scratch, view) - }); - let (target, load) = match &scratch { - Some((_, view)) => (view, wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)), - None => (&t.levels[level], wgpu::LoadOp::Load), - }; - let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("pc_mip"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: target, - resolve_target: None, - depth_slice: None, - ops: wgpu::Operations { load, store: wgpu::StoreOp::Store }, - })], - depth_stencil_attachment: None, - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); - pass.set_pipeline(mip_pipeline); - pass.set_bind_group(0, &bg, &[]); - pass.set_scissor_rect(x0, y0, x1 - x0, y1 - y0); - pass.draw(0..3, 0..1); - drop(pass); - if let Some((scratch, _)) = &scratch { - let origin = wgpu::Origin3d { x: x0, y: y0, z: 0 }; - encoder.copy_texture_to_texture( - wgpu::TexelCopyTextureInfo { texture: scratch, mip_level: 0, origin, aspect: wgpu::TextureAspect::All }, - wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: level as u32, origin, aspect: wgpu::TextureAspect::All }, - wgpu::Extent3d { width: x1 - x0, height: y1 - y0, depth_or_array_layers: 1 }, - ); - } - } - } - queue.submit([encoder.finish()]); - } -} - -// --------------------------------------------------------------------------------------------- -// Per-frame callback - -struct CanvasCallback { - rect: egui::Rect, - params: ViewParams, -} - -/// Sampling mode: 0 trilinear, 1 bilinear, 2 anti-aliased nearest. -fn filter_mode(scale: f32) -> (f32, f32) { - if scale < 0.999 { - (0.0, (-scale.log2()).max(0.0)) - } else if (scale - scale.round()).abs() < 1e-3 || scale >= 2.0 { - (2.0, 0.0) - } else { - (1.0, 0.0) - } -} - -fn map_doc_px(origin: [f32; 2], scale: f32, center: [f32; 2], cos: f32, sin: f32, x: f32, y: f32) -> [f32; 2] { - let dx = x - center[0]; - let dy = y - center[1]; - let rx = dx * cos - dy * sin; - let ry = dx * sin + dy * cos; - [origin[0] + center[0] * scale + rx * scale, origin[1] + center[1] * scale + ry * scale] -} - -fn tile_screen_aabb(origin: [f32; 2], scale: f32, center: [f32; 2], cos: f32, sin: f32, tile: [f32; 4]) -> (f32, f32, f32, f32) { - let [tx, ty, tw, th] = tile; - if sin.abs() < 1e-8 && (cos - 1.0).abs() < 1e-8 { - let x0 = origin[0] + tx * scale; - let y0 = origin[1] + ty * scale; - return (x0, y0, x0 + tw * scale, y0 + th * scale); - } - let pts = [ - map_doc_px(origin, scale, center, cos, sin, tx, ty), - map_doc_px(origin, scale, center, cos, sin, tx + tw, ty), - map_doc_px(origin, scale, center, cos, sin, tx + tw, ty + th), - map_doc_px(origin, scale, center, cos, sin, tx, ty + th), - ]; - let mut x0 = pts[0][0]; - let mut y0 = pts[0][1]; - let mut x1 = x0; - let mut y1 = y0; - for p in pts { - x0 = x0.min(p[0]); - y0 = y0.min(p[1]); - x1 = x1.max(p[0]); - y1 = y1.max(p[1]); - } - (x0, y0, x1, y1) -} - -impl CanvasCallback { - /// Screen-pixel origin of document (0, 0) (snapped to whole pixels) and device px per doc px. - fn placement(&self, ppp: f32) -> ([f32; 2], f32) { - let p = &self.params; - let scale = p.zoom * ppp; - let c = self.rect.center(); - let ox = (c.x * ppp - p.center[0] * scale).round(); - let oy = (c.y * ppp - p.center[1] * scale).round(); - ([ox, oy], scale) - } - - fn uniforms(&self, screen: [u32; 2], ppp: f32, out_linear: bool, style: &CanvasStyle) -> [f32; VIEW_FLOATS] { - let p = &self.params; - let (origin, scale) = self.placement(ppp); - let (mode, lod) = filter_mode(scale); - // The pixel grid shows above 500% (the constants are shared with the CPU path, - // pixel_grid.rs). `p.zoom` is screen points per document pixel; the shared threshold is - // in device pixels, so scale by the display's pixels per point. - let grid = if p.pixel_grid && crate::pixel_grid::shows_at(p.zoom * ppp) { crate::pixel_grid::STRENGTH } else { 0.0 }; - let square = if style.checker_square > 0.0 { (style.checker_square * ppp).round().max(1.0) } else { 0.0 }; - let (l, d, g) = (style.checker_light, style.checker_dark, style.gamut_color); - // 32-bit preview: linear-light gain 2^exposure (0 = off) and 1 / gamma. - let (gain, inv_gamma) = match p.hdr { - Some([e, gm]) if e.is_finite() && gm.is_finite() && gm > 0.0 => (2f32.powf(e.clamp(-20.0, 20.0)), 1.0 / gm.max(0.01)), - _ => (0.0, 1.0), - }; - [ - screen[0] as f32, - screen[1] as f32, - scale, - ppp, - origin[0], - origin[1], - p.doc_size[0] as f32, - p.doc_size[1] as f32, - mode, - lod, - grid, - square, - if p.offset[0].is_finite() { p.offset[0] } else { 0.0 }, - if p.offset[1].is_finite() { p.offset[1] } else { 0.0 }, - p.display as f32, - if out_linear { 1.0 } else { 0.0 }, - l[0], - l[1], - l[2], - style.gamut_opacity, - d[0], - d[1], - d[2], - gain, - g[0], - g[1], - g[2], - inv_gamma, - { - let r = if p.rotation.is_finite() { p.rotation } else { 0.0 }; - if r.abs() < 1e-8 { 1.0 } else { r.cos() } - }, - { - let r = if p.rotation.is_finite() { p.rotation } else { 0.0 }; - if r.abs() < 1e-8 { 0.0 } else { r.sin() } - }, - p.center[0], - p.center[1], - ] - } -} - -impl CallbackTrait for CanvasCallback { - fn prepare( - &self, - device: &wgpu::Device, - queue: &wgpu::Queue, - screen: &ScreenDescriptor, - _encoder: &mut wgpu::CommandEncoder, - resources: &mut CallbackResources, - ) -> Vec { - let Some(res) = resources.get_mut::() else { return Vec::new() }; - if !res.health.is_ok() { - return Vec::new(); - } - let data = self.uniforms(screen.size_in_pixels, screen.pixels_per_point, res.out_linear, &res.style); - let (bgl, sampler) = (&res.view_bgl, &res.sampler); - let v = res.views.entry(self.params.view_key).or_insert_with(|| { - let buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("pc_canvas_view"), - size: VIEW_UNIFORM_SIZE, - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("pc_canvas_view"), - layout: bgl, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: buffer.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(sampler) }, - ], - }); - ViewGpu { buffer, bind_group, frame_data: [f32::NAN; VIEW_FLOATS] } - }); - if v.frame_data != data { - queue.write_buffer(&v.buffer, 0, &f32_bytes(&data)); - v.frame_data = data; - } - Vec::new() - } - - fn paint(&self, info: egui::PaintCallbackInfo, pass: &mut wgpu::RenderPass<'static>, resources: &CallbackResources) { - let Some(res) = resources.get::() else { return }; - if !res.health.is_ok() { - return; - } - let Some(view) = res.views.get(&self.params.view_key) else { return }; - let [sw, sh] = info.screen_size_px; - let clip = info.clip_rect_in_pixels(); - if clip.width_px <= 0 || clip.height_px <= 0 || sw == 0 || sh == 0 { - return; - } - // Work in whole-screen pixel coordinates; the scissor does the clipping. - pass.set_viewport(0.0, 0.0, sw as f32, sh as f32, 0.0, 1.0); - pass.set_scissor_rect(clip.left_px.max(0) as u32, clip.top_px.max(0) as u32, clip.width_px as u32, clip.height_px as u32); - pass.set_bind_group(0, &view.bind_group, &[]); - if self.params.shadow { - pass.set_pipeline(&res.shadow_pipeline); - pass.draw(0..6, 0..1); - } - let Some(doc) = res.docs.get(&self.params.doc) else { return }; - if doc.size != self.params.doc_size { - return; - } - let (origin, scale) = self.placement(info.pixels_per_point); - let (cx0, cy0) = (clip.left_px as f32, clip.top_px as f32); - let (cx1, cy1) = (cx0 + clip.width_px as f32, cy0 + clip.height_px as f32); - let rot = if self.params.rotation.is_finite() { self.params.rotation } else { 0.0 }; - let (cos, sin) = if rot.abs() < 1e-8 { (1.0, 0.0) } else { (rot.cos(), rot.sin()) }; - let cen = self.params.center; - let [ox, oy] = self.params.offset.map(|v| if v.is_finite() { v } else { 0.0 }); - pass.set_pipeline(&res.tile_pipeline); - pass.set_bind_group(2, res.luts.get(&(self.params.doc, self.params.output)).unwrap_or(&res.identity_lut), &[]); - for t in &doc.tiles { - let [tx, ty, tw, th] = t.rect.map(|v| v as f32); - let (x0, y0, x1, y1) = tile_screen_aabb(origin, scale, cen, cos, sin, [tx + ox, ty + oy, tw, th]); - if x1 < cx0 || y1 < cy0 || x0 > cx1 || y0 > cy1 { - continue; - } - pass.set_bind_group(1, &t.bind_group, &[]); - pass.draw(0..6, 0..1); - } - } -} - -const CANVAS_WGSL: &str = r#" -struct View { - a: vec4, // screen_w, screen_h, scale (device px per doc px), pixels_per_point - b: vec4, // doc origin x, y (device px), doc w, h (doc px) - c: vec4, // filter mode, lod, grid alpha, checker square (device px) - d: vec4, // pattern preview offset x, y (doc px), display (0 none, 1 LUT, 2 LUT + gamut, 3 matrix/shaper), output linear - e: vec4, // checker light rgb, gamut warning opacity - f: vec4, // checker dark rgb, 32-bit preview gain (2^exposure; 0 = off) - g: vec4, // gamut warning rgb, 32-bit preview 1 / gamma - h: vec4, // cos, sin, center_doc_x, center_doc_y -}; -struct Tile { r: vec4 }; // x, y, w, h in doc px - -@group(0) @binding(0) var view: View; -@group(0) @binding(1) var samp: sampler; -@group(1) @binding(0) var tex: texture_2d; -@group(1) @binding(1) var tile: Tile; -@group(2) @binding(0) var lut: texture_3d; -@group(2) @binding(1) var display_curves: texture_2d; -struct DisplayMatrix { r: vec4, g: vec4, b: vec4 }; -@group(2) @binding(2) var display_matrix: DisplayMatrix; - -fn curve_entry(index: u32) -> vec3 { - let width = textureDimensions(display_curves).x; - return textureLoad(display_curves, vec2(i32(index % width), i32(index / width)), 0).rgb; -} - -fn display_curve(c: vec3, offset: u32, intervals: f32) -> vec3 { - let p = clamp(c, vec3(0.0), vec3(1.0)) * intervals; - let lo = vec3(floor(p)); - let hi = min(lo + vec3(1u), vec3(u32(intervals))); - let f = fract(p); - return vec3( - mix(curve_entry(offset + lo.r).r, curve_entry(offset + hi.r).r, f.r), - mix(curve_entry(offset + lo.g).g, curve_entry(offset + hi.g).g, f.g), - mix(curve_entry(offset + lo.b).b, curve_entry(offset + hi.b).b, f.b) - ); -} - -fn matrix_display(c: vec3) -> vec3 { - // Layout matches cms::GpuMatrixShaper: 4097 input entries, then 4096 inverse-curve - // entries indexed by the fourth root. This preserves near-black precision without - // interpolating across clipped corners of a coarse RGB cube. - let v = vec4(display_curve(c, 0u, 4096.0), 1.0); - let linear = vec3(dot(display_matrix.r, v), dot(display_matrix.g, v), dot(display_matrix.b, v)); - let u = sqrt(sqrt(clamp(linear, vec3(0.0), vec3(1.0)))); - return display_curve(u, 4097u, 4095.0); -} - -struct VOut { @builtin(position) pos: vec4 }; - -fn corner(i: u32) -> vec2 { - var c = array, 6>(vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(0.0, 1.0), vec2(1.0, 0.0), vec2(1.0, 1.0)); - return c[i]; -} - -fn px_to_clip(p: vec2) -> vec4 { - let n = p / view.a.xy * 2.0 - 1.0; - return vec4(n.x, -n.y, 0.0, 1.0); -} - -fn screen_center() -> vec2 { - return view.b.xy + view.h.zw * view.a.z; -} - -fn doc_to_px(d: vec2) -> vec2 { - let cs = view.h.xy; - let q = d - view.h.zw; - let r = vec2(q.x * cs.x - q.y * cs.y, q.x * cs.y + q.y * cs.x); - return screen_center() + r * view.a.z; -} - -fn px_to_doc(p: vec2) -> vec2 { - let cs = view.h.xy; - let q = (p - screen_center()) / view.a.z; - return vec2(q.x * cs.x + q.y * cs.y, -q.x * cs.y + q.y * cs.x) + view.h.zw; -} - -fn doc_min() -> vec2 { return view.b.xy; } -fn doc_max() -> vec2 { return view.b.xy + view.b.zw * view.a.z; } - -fn srgb_to_linear(c: vec3) -> vec3 { - let lo = c / 12.92; - let hi = pow((c + 0.055) / 1.055, vec3(2.4)); - return select(hi, lo, c <= vec3(0.04045)); -} - -fn linear_to_srgb(c: vec3) -> vec3 { - let hi = 1.055 * pow(max(c, vec3(1e-12)), vec3(1.0 / 2.4)) - 0.055; - return select(hi, c * 12.92, c <= vec3(0.0031308)); -} - -// --- drop shadow --------------------------------------------------------------------------- - -fn erf2(x: vec2) -> vec2 { - let s = sign(x); - let a = abs(x); - var t = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a; - t = t * t; - return s - s / (t * t); -} - -// Coverage of the box [lo, hi] blurred by a Gaussian of std-dev `sigma`, at point p. -fn box_blur(p: vec2, lo: vec2, hi: vec2, sigma: f32) -> f32 { - let k = 0.70710678 / sigma; - let q = (erf2((p - lo) * k) - erf2((p - hi) * k)) * 0.5; - return q.x * q.y; -} - -@vertex -fn vs_shadow(@builtin(vertex_index) vi: u32) -> VOut { - let pad = 64.0 * view.a.w; - let c0 = doc_to_px(vec2(0.0, 0.0)); - let c1 = doc_to_px(vec2(view.b.z, 0.0)); - let c2 = doc_to_px(vec2(view.b.z, view.b.w)); - let c3 = doc_to_px(vec2(0.0, view.b.w)); - let lo = min(min(c0, c1), min(c2, c3)) - vec2(pad); - let hi = max(max(c0, c1), max(c2, c3)) + vec2(pad); - let p = mix(lo, hi, corner(vi)); - return VOut(px_to_clip(p)); -} - -@fragment -fn fs_shadow(in: VOut) -> @location(0) vec4 { - let p = in.pos.xy; - let d = px_to_doc(p); - if (all(d >= vec2(0.0)) && all(d < view.b.zw)) { - discard; - } - let p_align = view.b.xy + d * view.a.z; - let lo = doc_min(); - let hi = doc_max(); - let u = view.a.w; - let ambient = box_blur(p_align - vec2(0.0, 7.0 * u), lo, hi, 16.0 * u) * 0.40; - let contact = box_blur(p_align - vec2(0.0, 0.75 * u), lo, hi, 1.25 * u) * 0.30; - let a = 1.0 - (1.0 - ambient) * (1.0 - contact); - return vec4(0.0, 0.0, 0.0, a); -} - -// --- document tiles ------------------------------------------------------------------------ - -@vertex -fn vs_tile(@builtin(vertex_index) vi: u32) -> VOut { - // A View › Pattern Preview copy sits a whole number of document sizes away (view.d.xy). - let p = doc_to_px(view.d.xy + tile.r.xy + tile.r.zw * corner(vi)); - return VOut(px_to_clip(p)); -} - -// Cells are screen-sized (view.c.w device px) but anchored to the document's top-left corner, so -// the pattern moves with the image as it is panned or zoomed. `d` is in document pixels (each -// Pattern Preview copy has the same cells). -fn checker(d: vec2) -> vec3 { - if (view.c.w <= 0.0) { - return vec3(1.0); - } - let c = floor(d * view.a.z / view.c.w); - let odd = fract((c.x + c.y) * 0.5) > 0.25; - return select(view.e.xyz, view.f.xyz, odd); -} - -@fragment -fn fs_tile(in: VOut) -> @location(0) vec4 { - let p = in.pos.xy; - let scale = view.a.z; - let d = px_to_doc(p) - view.d.xy; // document pixel coordinates (within this copy) - let size = tile.r.zw; - let t = d - tile.r.xy; // texel coordinates within this tile - let mode = view.c.x; - var col: vec4; - if (mode < 0.5) { - // Zoomed out: trilinear through the mip chain. - col = textureSampleLevel(tex, samp, t / size, view.c.y); - } else if (mode < 1.5) { - col = textureSampleLevel(tex, samp, t / size, 0.0); - } else { - // Crisp texels with a one-device-pixel anti-aliased edge ("sharp bilinear"). - let tt = t - 0.5; - let i = floor(tt); - let f = clamp((tt - i - 0.5) * scale + 0.5, vec2(0.0), vec2(1.0)); - col = textureSampleLevel(tex, samp, (i + 0.5 + f) / size, 0.0); - } - if (view.f.w > 0.0 && col.a > 0.0) { - // View › 32-bit Preview Options: exposure and gamma in linear light on the sRGB-encoded - // texture value, before the display LUT. A float canvas keeps values above 1.0, so they - // are brought into range by the exposure instead of clipped. - let lin = srgb_to_linear(max(col.rgb / col.a, vec3(0.0))) * view.f.w; - let v = linear_to_srgb(min(pow(max(lin, vec3(1e-12)), vec3(view.g.w)), vec3(1.0))); - col = vec4(v * col.a, col.a); - } - if (view.d.z > 0.5 && col.a > 0.0) { - // Colour management, Proof Colors, Gamut Warning: the document's display LUT (alpha flags - // out-of-gamut colours). - let c = clamp(col.rgb / col.a, vec3(0.0), vec3(1.0)); - var shown: vec3; - if (view.d.z > 2.5) { - shown = matrix_display(c); - } else { - let n = f32(textureDimensions(lut).x); - let l = textureSampleLevel(lut, samp, (c * (n - 1.0) + 0.5) / n, 0.0); - shown = select(l.rgb, mix(l.rgb, view.g.xyz, view.e.w), view.d.z > 1.5 && l.a > 0.5); - } - col = vec4(shown * col.a, col.a); - } - var rgb = col.rgb + checker(d) * (1.0 - col.a); - // The pixel grid is drawn over pixels with content, not over empty checker. - let grid = view.c.z * col.a; - if (grid > 0.0) { - let e = fract(d) * scale; - if (e.x < 1.0 || e.y < 1.0) { - // White over dark pixels, a weaker black over light ones, cross-faded by luma so a - // mid-tone image never flips line colour from one cell to the next (pixel_grid.rs - // `light_share`: same band, same numbers). - let t = smoothstep(0.35, 0.75, dot(rgb, vec3(0.299, 0.587, 0.114))); - let white = grid * (1.0 - t); - let black = grid * 0.64 * t; - rgb = rgb * (1.0 - white - black) + vec3(white); - } - } - if (view.d.w > 0.5) { - rgb = srgb_to_linear(rgb); - } - return vec4(rgb, 1.0); -} -"#; - -const ENCODE_WGSL: &str = r#" -@group(0) @binding(0) var acc: texture_2d; -@group(0) @binding(1) var offset: vec4; // x, y, encode sRGB, keep values above 1.0 - -@vertex -fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { - let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u)); - return vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0); -} - -fn srgb_encode(c: vec3) -> vec3 { - return select(1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, c * 12.92, c <= vec3(0.0031308)); -} - -@fragment -fn fs(@builtin(position) pos: vec4) -> @location(0) vec4 { - let c = textureLoad(acc, vec2(floor(pos.xy)) - offset.xy, 0); - let a = clamp(c.a, 0.0, 1.0); - var rgb = max(c.rgb, vec3(0.0)); - if (offset.w == 0) { - rgb = min(rgb, vec3(1.0)); - } - if (offset.z != 0) { - // Linear composite: store its sRGB encoding (8-bit precision where it matters). - rgb = srgb_encode(rgb); - } - return vec4(rgb * a, a); -} -"#; - -const MIP_WGSL: &str = r#" -@group(0) @binding(0) var src: texture_2d; -@group(0) @binding(1) var samp: sampler; - -struct V { @builtin(position) pos: vec4, @location(0) uv: vec2 }; - -@vertex -fn vs(@builtin(vertex_index) vi: u32) -> V { - let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u)); - return V(vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0), uv); -} - -@fragment -fn fs(in: V) -> @location(0) vec4 { - // A bilinear tap at the destination texel centre averages the 2×2 source block. - return textureSampleLevel(src, samp, in.uv, 0.0); -} -"#; - #[cfg(test)] mod mip_tests; diff --git a/crates/ui-egui/src/gpu_canvas/budget.rs b/crates/ui-egui/src/gpu_canvas/budget.rs new file mode 100644 index 0000000000..c98870130f --- /dev/null +++ b/crates/ui-egui/src/gpu_canvas/budget.rs @@ -0,0 +1,184 @@ +use super::doc_textures::mip_count; +use super::*; + +/// Floor of the compositor's memory budget: enough for a viewport's pages of a dozen layers. +pub const MIN_GPU_BUDGET: u64 = 512 << 20; + +/// Why a full refresh whose layer pages don't fit [`memory_budget`] (or GPU memory) goes to the +/// CPU compositor. +pub const OVER_BUDGET: &str = photocraft_gpu::OVER_BUDGET; + +/// GPU memory the wgpu compositor may hold for layer pages and effect maps. +/// +/// `fixed` (Preferences › Performance › GPU Memory, bytes) sets it when it isn't 0, within +/// [`vram_share`] of a discrete GPU's own memory (`vram`, from [`video_memory`]). Otherwise it is +/// Memory Usage (`allowance`) within a quarter of physical memory (`ram`; 16 GB assumed when +/// unknown) and the VRAM share. The document's pixels and History (`pixels`) come off Memory Usage +/// unless the card's own memory is known: a discrete card doesn't hold them, while integrated and +/// software adapters (and a card whose memory can't be read) share the system's. Never below +/// [`MIN_GPU_BUDGET`]. Layers beyond it redraw full refreshes on the CPU ([`OVER_BUDGET`]). +pub fn memory_budget(allowance: u64, pixels: u64, ram: Option, vram: Option, fixed: u64) -> u64 { + let card = vram.map_or(u64::MAX, vram_share); + if fixed > 0 { + return fixed.min(card).max(MIN_GPU_BUDGET); + } + let ram = ram.unwrap_or(16 << 30); + let charged = if vram.is_some() { 0 } else { pixels }; + allowance.saturating_sub(charged).min(ram / 4).min(card).max(MIN_GPU_BUDGET) +} + +/// The share of a discrete GPU's memory each of [`memory_budget`] and [`canvas_budget`] may +/// plan for: three eighths, so the two together leave a quarter of the card to the window's +/// swapchain, egui and other applications instead of over-committing it and letting the driver +/// page (#4536). +pub fn vram_share(vram: u64) -> u64 { + vram / 8 * 3 +} + +/// Why a document whose display textures don't fit [`canvas_budget`] is drawn on the CPU canvas. +pub const OVER_CANVAS_BUDGET: &str = "the canvas exceeds the GPU texture budget; drawing it on the CPU canvas"; + +/// [`Refresh::kind`] when the document's display textures don't fit [`canvas_budget`]: nothing +/// was created, and the caller draws the CPU canvas instead. +pub const REFRESH_OVER_BUDGET: &str = "over-budget"; + +/// [`Refresh::kind`] of a CPU refresh left to the caller ([`GpuCanvas::refresh_with`]). +pub const REFRESH_DEFERRED: &str = "deferred"; + +/// The smallest CPU refresh (pixels) [`GpuCanvas::refresh_with`] defers: below it, the +/// synchronous composite takes a fraction of a second even with many layers. +pub const DEFER_PX: u64 = 1 << 22; + +/// GPU bytes one document's display texture set (every tile and mip level) may take: a quarter +/// of physical memory (`ram`; 16 GB assumed when unknown) and at most [`vram_share`] of a +/// discrete GPU's own memory (`vram`), at least [`MIN_GPU_BUDGET`]. The set covers the whole +/// canvas at full resolution, so its size follows the declared canvas, not the layer pixels; a +/// larger canvas is drawn on the (reduced) CPU canvas instead (#2934). +pub fn canvas_budget(ram: Option, vram: Option) -> u64 { + (ram.unwrap_or(16 << 30) / 4).min(vram.map_or(u64::MAX, vram_share)).max(MIN_GPU_BUDGET) +} + +/// GPU bytes of a display texture set for a `size` canvas in `tile`-sided tiles of `bpp` bytes +/// per texel, with every mip level (what [`GpuCanvas::texture_info`] reports once it exists). +/// Closed form over the (at most four) distinct tile shapes, so any size is cheap to price. +pub fn canvas_texture_bytes(size: [u32; 2], tile: u32, bpp: u64) -> u64 { + let tile = tile.max(1); + // (how many tiles, their side) along one axis: whole tiles, then the remainder. + let spans = |n: u32| [(n / tile, tile), (u32::from(!n.is_multiple_of(tile)), n % tile)]; + let mut total = 0u64; + for (nx, w) in spans(size[0]) { + for (ny, h) in spans(size[1]) { + if nx == 0 || ny == 0 { + continue; + } + let one = (0..mip_count(w, h)).map(|l| u64::from((w >> l).max(1)) * u64::from((h >> l).max(1)) * bpp).fold(0, u64::saturating_add); + total = total.saturating_add(one.saturating_mul(u64::from(nx) * u64::from(ny))); + } + } + total +} + +/// Physical memory of this machine in bytes, if known. `PHOTOCRAFT_RAM_MB` overrides it (to +/// simulate a smaller machine). +pub fn physical_memory() -> Option { + static RAM: std::sync::OnceLock> = std::sync::OnceLock::new(); + *RAM.get_or_init(|| { + if let Some(mb) = std::env::var("PHOTOCRAFT_RAM_MB").ok().and_then(|v| v.trim().parse::().ok()) { + return mb.checked_mul(1 << 20); + } + detect_physical_memory() + }) +} + +#[cfg(target_os = "macos")] +fn detect_physical_memory() -> Option { + let out = std::process::Command::new("/usr/sbin/sysctl").args(["-n", "hw.memsize"]).output().ok()?; + String::from_utf8(out.stdout).ok()?.trim().parse().ok() +} + +#[cfg(target_os = "linux")] +fn detect_physical_memory() -> Option { + let info = std::fs::read_to_string("/proc/meminfo").ok()?; + let kb: u64 = info.lines().find_map(|l| l.strip_prefix("MemTotal:"))?.trim().trim_end_matches("kB").trim().parse().ok()?; + kb.checked_mul(1024) +} + +#[cfg(target_os = "freebsd")] +fn detect_physical_memory() -> Option { + let out = std::process::Command::new("/sbin/sysctl").args(["-n", "hw.physmem"]).output().ok()?; + String::from_utf8(out.stdout).ok()?.trim().parse().ok() +} + +#[cfg(windows)] +pub(super) fn detect_physical_memory() -> Option { + winsafe::GlobalMemoryStatusEx().map(|m| m.ullTotalPhys).ok().filter(|b| *b > 0) +} + +#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "freebsd", windows)))] +fn detect_physical_memory() -> Option { + None +} + +/// The memory of `adapter` itself, in bytes, when it is a discrete GPU and the platform reports +/// it: DXGI's dedicated video memory on Windows, amdgpu's VRAM size on Linux. `None` for +/// integrated and software adapters, whose textures live in system memory (the RAM-based +/// budgets already cover them), and where nothing reports it. `PHOTOCRAFT_VRAM_MB` overrides it +/// for any adapter, simulating a discrete card of that size: on an integrated GPU the budget then +/// stops charging the document's pixels too, as for a real card (a development switch). +pub fn video_memory(adapter: &wgpu::AdapterInfo) -> Option { + if let Some(mb) = std::env::var("PHOTOCRAFT_VRAM_MB").ok().and_then(|v| v.trim().parse::().ok()) { + return mb.checked_mul(1 << 20).filter(|b| *b > 0); + } + if adapter.device_type != wgpu::DeviceType::DiscreteGpu { + return None; + } + // Detected once per adapter, as `physical_memory` is: on Windows each detection builds a + // DXGI factory, and startup asks three times. Keyed by the adapter, since a GPU retry can + // pick another one. + /// (vendor, device) ids and the memory found for them. + type Seen = Vec<((u32, u32), Option)>; + static SEEN: std::sync::Mutex = std::sync::Mutex::new(Vec::new()); + let key = (adapter.vendor, adapter.device); + let mut seen = SEEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some((_, bytes)) = seen.iter().find(|(k, _)| *k == key) { + return *bytes; + } + let bytes = detect_video_memory(key.0, key.1).filter(|b| *b > 0); + seen.push((key, bytes)); + bytes +} + +#[cfg(windows)] +pub(super) fn detect_video_memory(vendor: u32, device: u32) -> Option { + use winsafe::prelude::*; + let factory = winsafe::CreateDXGIFactory1().ok()?; + factory + .EnumAdapters1() + .filter_map(|a| a.ok()?.GetDesc1().ok()) + .find(|d| d.VendorId == vendor && d.DeviceId == device) + .and_then(|d| u64::try_from(d.DedicatedVideoMemory).ok()) +} + +#[cfg(target_os = "linux")] +fn detect_video_memory(vendor: u32, device: u32) -> Option { + drm_video_memory(std::path::Path::new("/sys/class/drm"), vendor, device) +} + +/// amdgpu's VRAM size (`/device/mem_info_vram_total`, bytes) of the card under `drm` (the +/// sysfs `/sys/class/drm` folder) whose PCI `vendor` and `device` ids (hex files beside it) match. +#[cfg(any(target_os = "linux", test))] +pub(super) fn drm_video_memory(drm: &std::path::Path, vendor: u32, device: u32) -> Option { + let hex = |p: std::path::PathBuf| u32::from_str_radix(std::fs::read_to_string(p).ok()?.trim().trim_start_matches("0x"), 16).ok(); + std::fs::read_dir(drm).ok()?.flatten().find_map(|card| { + let dev = card.path().join("device"); + if hex(dev.join("vendor"))? != vendor || hex(dev.join("device"))? != device { + return None; + } + std::fs::read_to_string(dev.join("mem_info_vram_total")).ok()?.trim().parse().ok() + }) +} + +#[cfg(not(any(target_os = "linux", windows)))] +fn detect_video_memory(_vendor: u32, _device: u32) -> Option { + None +} diff --git a/crates/ui-egui/src/gpu_canvas/callback.rs b/crates/ui-egui/src/gpu_canvas/callback.rs new file mode 100644 index 0000000000..c128a8f297 --- /dev/null +++ b/crates/ui-egui/src/gpu_canvas/callback.rs @@ -0,0 +1,207 @@ +use super::resources::{CanvasStyle, Resources, ViewGpu, f32_bytes}; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Per-frame callback + +pub(super) struct CanvasCallback { + pub(super) rect: egui::Rect, + pub(super) params: ViewParams, +} + +/// Sampling mode: 0 trilinear, 1 bilinear, 2 anti-aliased nearest. +pub(super) fn filter_mode(scale: f32) -> (f32, f32) { + if scale < 0.999 { + (0.0, (-scale.log2()).max(0.0)) + } else if (scale - scale.round()).abs() < 1e-3 || scale >= 2.0 { + (2.0, 0.0) + } else { + (1.0, 0.0) + } +} + +pub(super) fn map_doc_px(origin: [f32; 2], scale: f32, center: [f32; 2], cos: f32, sin: f32, x: f32, y: f32) -> [f32; 2] { + let dx = x - center[0]; + let dy = y - center[1]; + let rx = dx * cos - dy * sin; + let ry = dx * sin + dy * cos; + [origin[0] + center[0] * scale + rx * scale, origin[1] + center[1] * scale + ry * scale] +} + +pub(super) fn tile_screen_aabb(origin: [f32; 2], scale: f32, center: [f32; 2], cos: f32, sin: f32, tile: [f32; 4]) -> (f32, f32, f32, f32) { + let [tx, ty, tw, th] = tile; + if sin.abs() < 1e-8 && (cos - 1.0).abs() < 1e-8 { + let x0 = origin[0] + tx * scale; + let y0 = origin[1] + ty * scale; + return (x0, y0, x0 + tw * scale, y0 + th * scale); + } + let pts = [ + map_doc_px(origin, scale, center, cos, sin, tx, ty), + map_doc_px(origin, scale, center, cos, sin, tx + tw, ty), + map_doc_px(origin, scale, center, cos, sin, tx + tw, ty + th), + map_doc_px(origin, scale, center, cos, sin, tx, ty + th), + ]; + let mut x0 = pts[0][0]; + let mut y0 = pts[0][1]; + let mut x1 = x0; + let mut y1 = y0; + for p in pts { + x0 = x0.min(p[0]); + y0 = y0.min(p[1]); + x1 = x1.max(p[0]); + y1 = y1.max(p[1]); + } + (x0, y0, x1, y1) +} + +impl CanvasCallback { + /// Screen-pixel origin of document (0, 0) (snapped to whole pixels) and device px per doc px. + fn placement(&self, ppp: f32) -> ([f32; 2], f32) { + let p = &self.params; + let scale = p.zoom * ppp; + let c = self.rect.center(); + let ox = (c.x * ppp - p.center[0] * scale).round(); + let oy = (c.y * ppp - p.center[1] * scale).round(); + ([ox, oy], scale) + } + + fn uniforms(&self, screen: [u32; 2], ppp: f32, out_linear: bool, style: &CanvasStyle) -> [f32; VIEW_FLOATS] { + let p = &self.params; + let (origin, scale) = self.placement(ppp); + let (mode, lod) = filter_mode(scale); + // The pixel grid shows above 500% (the constants are shared with the CPU path, + // pixel_grid.rs). `p.zoom` is screen points per document pixel; the shared threshold is + // in device pixels, so scale by the display's pixels per point. + let grid = if p.pixel_grid && crate::pixel_grid::shows_at(p.zoom * ppp) { crate::pixel_grid::STRENGTH } else { 0.0 }; + let square = if style.checker_square > 0.0 { (style.checker_square * ppp).round().max(1.0) } else { 0.0 }; + let (l, d, g) = (style.checker_light, style.checker_dark, style.gamut_color); + // 32-bit preview: linear-light gain 2^exposure (0 = off) and 1 / gamma. + let (gain, inv_gamma) = match p.hdr { + Some([e, gm]) if e.is_finite() && gm.is_finite() && gm > 0.0 => (2f32.powf(e.clamp(-20.0, 20.0)), 1.0 / gm.max(0.01)), + _ => (0.0, 1.0), + }; + [ + screen[0] as f32, + screen[1] as f32, + scale, + ppp, + origin[0], + origin[1], + p.doc_size[0] as f32, + p.doc_size[1] as f32, + mode, + lod, + grid, + square, + if p.offset[0].is_finite() { p.offset[0] } else { 0.0 }, + if p.offset[1].is_finite() { p.offset[1] } else { 0.0 }, + p.display as f32, + if out_linear { 1.0 } else { 0.0 }, + l[0], + l[1], + l[2], + style.gamut_opacity, + d[0], + d[1], + d[2], + gain, + g[0], + g[1], + g[2], + inv_gamma, + { + let r = if p.rotation.is_finite() { p.rotation } else { 0.0 }; + if r.abs() < 1e-8 { 1.0 } else { r.cos() } + }, + { + let r = if p.rotation.is_finite() { p.rotation } else { 0.0 }; + if r.abs() < 1e-8 { 0.0 } else { r.sin() } + }, + p.center[0], + p.center[1], + ] + } +} + +impl CallbackTrait for CanvasCallback { + fn prepare( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + screen: &ScreenDescriptor, + _encoder: &mut wgpu::CommandEncoder, + resources: &mut CallbackResources, + ) -> Vec { + let Some(res) = resources.get_mut::() else { return Vec::new() }; + if !res.health.is_ok() { + return Vec::new(); + } + let data = self.uniforms(screen.size_in_pixels, screen.pixels_per_point, res.out_linear, &res.style); + let (bgl, sampler) = (&res.view_bgl, &res.sampler); + let v = res.views.entry(self.params.view_key).or_insert_with(|| { + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("pc_canvas_view"), + size: VIEW_UNIFORM_SIZE, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("pc_canvas_view"), + layout: bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: buffer.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(sampler) }, + ], + }); + ViewGpu { buffer, bind_group, frame_data: [f32::NAN; VIEW_FLOATS] } + }); + if v.frame_data != data { + queue.write_buffer(&v.buffer, 0, &f32_bytes(&data)); + v.frame_data = data; + } + Vec::new() + } + + fn paint(&self, info: egui::PaintCallbackInfo, pass: &mut wgpu::RenderPass<'static>, resources: &CallbackResources) { + let Some(res) = resources.get::() else { return }; + if !res.health.is_ok() { + return; + } + let Some(view) = res.views.get(&self.params.view_key) else { return }; + let [sw, sh] = info.screen_size_px; + let clip = info.clip_rect_in_pixels(); + if clip.width_px <= 0 || clip.height_px <= 0 || sw == 0 || sh == 0 { + return; + } + // Work in whole-screen pixel coordinates; the scissor does the clipping. + pass.set_viewport(0.0, 0.0, sw as f32, sh as f32, 0.0, 1.0); + pass.set_scissor_rect(clip.left_px.max(0) as u32, clip.top_px.max(0) as u32, clip.width_px as u32, clip.height_px as u32); + pass.set_bind_group(0, &view.bind_group, &[]); + if self.params.shadow { + pass.set_pipeline(&res.shadow_pipeline); + pass.draw(0..6, 0..1); + } + let Some(doc) = res.docs.get(&self.params.doc) else { return }; + if doc.size != self.params.doc_size { + return; + } + let (origin, scale) = self.placement(info.pixels_per_point); + let (cx0, cy0) = (clip.left_px as f32, clip.top_px as f32); + let (cx1, cy1) = (cx0 + clip.width_px as f32, cy0 + clip.height_px as f32); + let rot = if self.params.rotation.is_finite() { self.params.rotation } else { 0.0 }; + let (cos, sin) = if rot.abs() < 1e-8 { (1.0, 0.0) } else { (rot.cos(), rot.sin()) }; + let cen = self.params.center; + let [ox, oy] = self.params.offset.map(|v| if v.is_finite() { v } else { 0.0 }); + pass.set_pipeline(&res.tile_pipeline); + pass.set_bind_group(2, res.luts.get(&(self.params.doc, self.params.output)).unwrap_or(&res.identity_lut), &[]); + for t in &doc.tiles { + let [tx, ty, tw, th] = t.rect.map(|v| v as f32); + let (x0, y0, x1, y1) = tile_screen_aabb(origin, scale, cen, cos, sin, [tx + ox, ty + oy, tw, th]); + if x1 < cx0 || y1 < cy0 || x0 > cx1 || y0 > cy1 { + continue; + } + pass.set_bind_group(1, &t.bind_group, &[]); + pass.draw(0..6, 0..1); + } + } +} diff --git a/crates/ui-egui/src/gpu_canvas/doc_textures.rs b/crates/ui-egui/src/gpu_canvas/doc_textures.rs new file mode 100644 index 0000000000..05a40faa1a --- /dev/null +++ b/crates/ui-egui/src/gpu_canvas/doc_textures.rs @@ -0,0 +1,206 @@ +use super::budget::canvas_texture_bytes; +use super::resources::{DocTextures, Resources, Tile, f32_bytes}; +use super::texels::texel_bytes; +use super::*; + +pub(super) fn mip_count(w: u32, h: u32) -> u32 { + 32 - w.max(h).max(1).leading_zeros() +} + +/// The rect (x0, y0, x1, y1) of a `lw`×`lh` mip level to redraw when `prev` changed in the level +/// above: that damage halved and padded by one texel for odd-size rounding, or the whole level +/// when it is at most [`WHOLE_MIP_SIDE`] on either side. On AMD's Vulkan driver a pass that draws +/// only part of a level of 64 px or less corrupts texels outside its scissor, at the level's +/// top-left (#6418: RX 6900 XT, driver 26.8.1; DX12 on the same card is fine). Such a level costs +/// next to nothing to redraw, so this holds for every adapter; the levels after it are smaller +/// still, so the rest of the chain is redrawn whole too. +pub(super) fn mip_damage([x0, y0, x1, y1]: [u32; 4], lw: u32, lh: u32) -> [u32; 4] { + if lw.max(lh) <= WHOLE_MIP_SIDE { + return [0, 0, lw, lh]; + } + [(x0 / 2).saturating_sub(1), (y0 / 2).saturating_sub(1), (x1.div_ceil(2) + 1).min(lw), (y1.div_ceil(2) + 1).min(lh)] +} + +/// A buffer holding `contents`, like `DeviceExt::create_buffer_init` but without its panic when +/// the device was lost (an invalid buffer has no mapped range): the buffer is then just invalid. +pub(super) fn init_buffer(device: &wgpu::Device, label: &str, contents: &[u8], usage: wgpu::BufferUsages) -> wgpu::Buffer { + let size = (contents.len() as u64).next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT).max(wgpu::COPY_BUFFER_ALIGNMENT); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage, mapped_at_creation: true }); + if let Ok(mut view) = buffer.slice(..).get_mapped_range_mut() + && view.len() >= contents.len() + { + view.slice(..contents.len()).copy_from_slice(contents); + } + buffer.unmap(); + buffer +} + +impl DocTextures { + /// The texture set for a `size` canvas, or `None` (nothing created) when it doesn't fit + /// the canvas budget or the GPU's memory. A set the GPU can't hold (a 3 GP canvas is 16 GB + /// of textures, #4017) lowers the budget below it, so that canvas and larger ones are drawn + /// on the CPU canvas instead of the out-of-memory error disabling the GPU for the session. + pub(super) fn new(device: &wgpu::Device, res: &Resources, size: [u32; 2], tile: u32, format: wgpu::TextureFormat) -> Option { + let bytes = canvas_texture_bytes(size, tile, texel_bytes(format)); + if bytes > res.canvas_budget.load(Ordering::Relaxed) { + return None; + } + let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); + let memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let set = Self::create(device, res, size, tile, format); + // Native wgpu reports these synchronously; where they arrive later (WebGPU) none is seen. + let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); + let mut error = None; + for pop in [memory.pop(), validation.pop()] { + if let std::task::Poll::Ready(Some(e)) = std::pin::pin!(pop).poll(&mut cx) { + error.get_or_insert(e); + } + } + if let Some(e) = error { + log::warn!("{} MB of canvas textures failed ({e}); larger canvases are drawn on the CPU", bytes >> 20); + res.canvas_budget.fetch_min(bytes.saturating_sub(1), Ordering::Relaxed); + return None; + } + Some(set) + } + + fn create(device: &wgpu::Device, res: &Resources, size: [u32; 2], tile: u32, format: wgpu::TextureFormat) -> Self { + let mut tiles = Vec::new(); + for ty in (0..size[1]).step_by(tile as usize) { + for tx in (0..size[0]).step_by(tile as usize) { + let (w, h) = (tile.min(size[0] - tx), tile.min(size[1] - ty)); + let levels_n = mip_count(w, h); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_canvas_tile"), + size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + mip_level_count: levels_n, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_DST + | wgpu::TextureUsages::COPY_SRC + | wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + let levels = (0..levels_n) + .map(|l| texture.create_view(&wgpu::TextureViewDescriptor { base_mip_level: l, mip_level_count: Some(1), ..Default::default() })) + .collect(); + let full = texture.create_view(&wgpu::TextureViewDescriptor::default()); + let uniform = init_buffer(device, "pc_canvas_tile", &f32_bytes(&[tx as f32, ty as f32, w as f32, h as f32]), wgpu::BufferUsages::UNIFORM); + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("pc_canvas_tile"), + layout: &res.tile_bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&full) }, + wgpu::BindGroupEntry { binding: 1, resource: uniform.as_entire_binding() }, + ], + }); + tiles.push(Tile { rect: [tx, ty, w, h], texture, levels, bind_group, _uniform: uniform }); + } + } + Self { size, format, tiles } + } + + /// Write `size` pixels at document `origin` from `texels` (in the texture format, row stride + /// `stride` pixels) into every overlapping tile's level 0. + pub(super) fn write(&self, queue: &wgpu::Queue, origin: [u32; 2], size: [u32; 2], stride: u32, texels: &[u8]) { + let bpp = texel_bytes(self.format); + let (x0, y0, x1, y1) = (origin[0], origin[1], origin[0] + size[0], origin[1] + size[1]); + for t in &self.tiles { + let [tx, ty, tw, th] = t.rect; + let (ix0, iy0, ix1, iy1) = (x0.max(tx), y0.max(ty), x1.min(tx + tw), y1.min(ty + th)); + if ix0 >= ix1 || iy0 >= iy1 { + continue; + } + let offset = ((iy0 - y0) as u64 * stride as u64 + (ix0 - x0) as u64) * bpp; + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &t.texture, + mip_level: 0, + origin: wgpu::Origin3d { x: ix0 - tx, y: iy0 - ty, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + texels, + wgpu::TexelCopyBufferLayout { offset, bytes_per_row: Some(stride * bpp as u32), rows_per_image: Some(iy1 - iy0) }, + wgpu::Extent3d { width: ix1 - ix0, height: iy1 - iy0, depth_or_array_layers: 1 }, + ); + } + } + + /// Rebuild the mip chain inside document rect `r` (x0, y0, x1, y1) with 2×2 box filtering. + pub(super) fn regenerate_mips(&self, device: &wgpu::Device, queue: &wgpu::Queue, res: &Resources, r: [u32; 4]) { + let Some(mip_pipeline) = res.mip_pipeline(self.format) else { return }; + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_mips") }); + for t in &self.tiles { + let [tx, ty, tw, th] = t.rect; + let (mut x0, mut y0, mut x1, mut y1) = (r[0].max(tx), r[1].max(ty), r[2].min(tx + tw), r[3].min(ty + th)); + if x0 >= x1 || y0 >= y1 { + continue; + } + (x0, y0, x1, y1) = (x0 - tx, y0 - ty, x1 - tx, y1 - ty); + for level in 1..t.levels.len() { + let (lw, lh) = ((tw >> level).max(1), (th >> level).max(1)); + [x0, y0, x1, y1] = mip_damage([x0, y0, x1, y1], lw, lh); + let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("pc_mip"), + layout: &res.mip_bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&t.levels[level - 1]) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&res.mip_sampler) }, + ], + }); + // Keep the sampled source and render attachment in separate resources on Intel + // DX12 adapters ([`separate_mip_targets`]): some of their drivers corrupt reduced + // previews when both are mip levels of the same texture, even though the + // subresources do not overlap. Elsewhere render straight into the level, which + // spares a scratch texture and a copy per level on every edit. + let scratch = res.separate_mip_targets.then(|| { + let scratch = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_mip_scratch"), + size: wgpu::Extent3d { width: lw, height: lh, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: self.format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let view = scratch.create_view(&Default::default()); + (scratch, view) + }); + let (target, load) = match &scratch { + Some((_, view)) => (view, wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)), + None => (&t.levels[level], wgpu::LoadOp::Load), + }; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("pc_mip"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: target, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(mip_pipeline); + pass.set_bind_group(0, &bg, &[]); + pass.set_scissor_rect(x0, y0, x1 - x0, y1 - y0); + pass.draw(0..3, 0..1); + drop(pass); + if let Some((scratch, _)) = &scratch { + let origin = wgpu::Origin3d { x: x0, y: y0, z: 0 }; + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { texture: scratch, mip_level: 0, origin, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: level as u32, origin, aspect: wgpu::TextureAspect::All }, + wgpu::Extent3d { width: x1 - x0, height: y1 - y0, depth_or_array_layers: 1 }, + ); + } + } + } + queue.submit([encoder.finish()]); + } +} diff --git a/crates/ui-egui/src/gpu_canvas/perf.rs b/crates/ui-egui/src/gpu_canvas/perf.rs new file mode 100644 index 0000000000..8c22dfbf89 --- /dev/null +++ b/crates/ui-egui/src/gpu_canvas/perf.rs @@ -0,0 +1,256 @@ +use super::budget::video_memory; +use super::setup::Refresh; +use super::texels::LayerFit; +use super::*; + +/// Milliseconds since the process (or page) started, from a monotonic clock. +/// +/// `web_time::Instant` is `std::time::Instant` natively and `performance.now()` on wasm, so frame +/// caps, autosave intervals, preference retry backoff, stroke traces and screenshot deadlines all +/// measure durations the same way on both. The old wasm value was a constant 0, which made every +/// interval comparison (`now >= deadline`) permanently false on the web. +pub fn now_ms() -> f64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + START.get_or_init(web_time::Instant::now).elapsed().as_secs_f64() * 1000.0 +} + +/// UI-thread timings (CPU side), exponentially smoothed. +#[derive(Clone, Debug, Default, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Perf { + /// Average CPU time building the UI per frame (ms). + pub ui_ms: f64, + /// Worst UI frame of the last ~second (ms). + pub ui_max_ms: f64, + /// Last canvas refresh, CPU side (ms): the CPU composite on the CPU path, and on the GPU + /// path the cost of *encoding and submitting* the composite — not of running it, which is + /// `gpu_ms`. + pub composite_ms: f64, + /// Last canvas refresh: conversion + upload (ms). + pub upload_ms: f64, + /// Last canvas refresh kind: "full", "rect" or "none". + pub last_refresh: &'static str, + /// Pixels in the last refresh. + pub last_refresh_px: u64, + /// Whether the GPU canvas path is active. + pub gpu: bool, + /// Layer tiles uploaded by the last GPU composite. + pub gpu_uploads: u64, + /// How long the GPU spent executing a recent composite (ms), from timestamp queries read + /// back after the fact. `None` on the CPU compositor, on a device without timestamp queries + /// and on wasm — there is then no honest number to report, and `composite_ms` is not one. + /// Excludes layer-tile uploads and end-of-batch work (see `photocraft_gpu::timing`), so it + /// is a few per cent under the GPU's full share of a warm refresh and further under a cold + /// one. + pub gpu_ms: Option, + /// Pixels of the refresh `gpu_ms` measured, which is a frame or two behind + /// `last_refresh_px` and may be a different size. + pub gpu_ms_px: u64, + /// Why the last refresh fell back to the CPU compositor (None = GPU composited). + pub gpu_fallback: Option, + /// Adapter, backend, driver and fallback state (Help › System Info). + pub gpu_info: GpuInfo, + /// GPU memory the compositor may hold for layer pages and effect maps (MB; see + /// [`memory_budget`]). + pub gpu_budget_mb: u64, + /// The Memory Usage allowance and the GPU Memory preference (bytes) `gpu_budget_mb` was + /// computed from. + #[serde(skip)] + pub gpu_budget_allowance: (u64, u64), + /// The layer pages the last full refresh needed against the part of the budget they may + /// hold; when they don't fit, edits that redraw the whole document do it on the CPU. + pub gpu_layer_fit: Option, + /// Last command run through the app and its duration (ms). + pub last_command: String, + pub command_ms: f64, + /// Most recent cost of occasional UI work (outline tracing, thumbnails, …), in ms. + pub spans: std::collections::BTreeMap<&'static str, f64>, + #[serde(skip)] + max_decay: f64, + /// Composite and upload time of this frame's canvas refreshes, in ms (the stroke trace). + #[serde(skip)] + pub(crate) frame_refresh_ms: f64, +} + +/// What the app renders with and why (Help › System Info, Preferences › Performance, the `perf` +/// control-channel output). +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GpuInfo { + /// Adapter name ("" before the window opens). + pub adapter: String, + /// wgpu backend of the window's device ("vulkan", "dx12", "metal", "gl", …). + pub backend: String, + /// Device type ("discreteGpu", "integratedGpu", "cpu", …). + pub device_type: String, + /// Driver name and version as the driver reports them. + pub driver: String, + /// The adapter's own memory in MB ([`video_memory`]): discrete GPUs where the platform + /// reports it. It caps the GPU memory budgets. + pub video_memory_mb: Option, + /// `performance.gpuBackend` at launch. + pub preference: String, + /// Every graphics adapter the window could have used, by name (Preferences › Performance › + /// Graphics Adapter lists them). Empty in hosts that don't set it. + pub adapters: Vec, + /// The backend startup chose ("auto", "dx12", "cpu", …, or "env" for `WGPU_BACKEND`). + pub selected: String, + /// Why startup didn't use the preference as is (previous start crashed, `--safe-gpu`, + /// `WGPU_BACKEND`, Intel on Windows). + pub fallback: Option, + /// "gpu" (wgpu canvas and compositor) or "cpu" (CPU compositor, egui textures). + pub canvas: String, + /// Why the GPU canvas was dropped during this session (device lost or a GPU error). + pub lost: Option, + /// Present mode and frame latency ("fifo, latency 2"; launch overrides marked, see the + /// app's `presentation`). Empty in hosts that don't set it. + pub present: String, +} + +impl GpuInfo { + /// Record the adapters the instance found, without duplicates (one GPU shows up once per backend). + pub fn set_available(&mut self, adapters: &[wgpu::Adapter]) { + self.adapters.clear(); + for a in adapters { + let name = a.get_info().name; + if !name.is_empty() && !self.adapters.contains(&name) { + self.adapters.push(name); + } + } + } + + /// Fill the adapter fields from `info`. + pub fn set_adapter(&mut self, info: &wgpu::AdapterInfo) { + self.adapter = info.name.clone(); + self.backend = backend_name(info.backend).to_string(); + self.device_type = match info.device_type { + wgpu::DeviceType::DiscreteGpu => "discreteGpu", + wgpu::DeviceType::IntegratedGpu => "integratedGpu", + wgpu::DeviceType::VirtualGpu => "virtualGpu", + wgpu::DeviceType::Cpu => "cpu", + wgpu::DeviceType::Other => "other", + } + .to_string(); + self.driver = [info.driver.as_str(), info.driver_info.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::>().join(" "); + self.video_memory_mb = video_memory(info).map(|b| b >> 20); + } + + /// Human-readable lines for Help › System Info. + pub fn lines(&self) -> Vec { + let or = |s: &str, d: &str| if s.is_empty() || (s == "auto" && d == "auto") { tl!(d).to_string() } else { s.to_string() }; + let mut v = vec![ + { + let template = "Graphics adapter: {adapter}"; + crate::i18n::fmt(tl!(template), &[("adapter", &or(&self.adapter, "unknown"))]) + }, + { + let template = "Backend: {backend} ({type})"; + crate::i18n::fmt(tl!(template), &[("backend", &or(&self.backend, "unknown")), ("type", &or(&self.device_type, "unknown type"))]) + }, + { + let template = "Driver: {driver}"; + crate::i18n::fmt(tl!(template), &[("driver", &or(&self.driver, "unknown"))]) + }, + ]; + // The card's own memory caps the GPU budgets, so it explains a huge canvas falling back + // to the CPU. Only discrete cards report one (integrated GPUs share system memory). + if let Some(mb) = self.video_memory_mb { + let template = "Graphics memory: {size}"; + v.push(crate::i18n::fmt(tl!(template), &[("size", &crate::chrome_ui::fmt_bytes(mb.saturating_mul(1 << 20)))])); + } + v.extend([ + { + let template = "GPU backend preference: {backend}"; + crate::i18n::fmt(tl!(template), &[("backend", &or(&self.preference, "auto"))]) + }, + { + let template = "Selected at launch: {backend}"; + crate::i18n::fmt(tl!(template), &[("backend", &or(&self.selected, "auto"))]) + }, + { + let template = "Image compositor: {processor}"; + crate::i18n::fmt(tl!(template), &[("processor", if self.canvas == "gpu" { "GPU" } else { "CPU" })]) + }, + { + let template = "Window renderer: {renderer}"; + let renderer = if self.device_type == "cpu" { + "Software adapter" + } else if self.adapter.is_empty() { + "Unknown" + } else { + "Graphics adapter" + }; + crate::i18n::fmt(tl!(template), &[("renderer", tl!(renderer))]) + }, + ]); + if let Some(f) = &self.fallback { + v.push({ + let template = "Fallback: {reason}"; + crate::i18n::fmt(tl!(template), &[("reason", f)]) + }); + } + if let Some(l) = &self.lost { + v.push({ + let template = "This session: {reason}"; + crate::i18n::fmt(tl!(template), &[("reason", l)]) + }); + } + v + } +} + +/// The preference name of a wgpu backend. +pub fn backend_name(b: wgpu::Backend) -> &'static str { + match b { + wgpu::Backend::Vulkan => "vulkan", + wgpu::Backend::Dx12 => "dx12", + wgpu::Backend::Metal => "metal", + wgpu::Backend::Gl => "gl", + wgpu::Backend::BrowserWebGpu => "webgpu", + wgpu::Backend::Noop => "noop", + } +} + +impl Perf { + pub fn record(&mut self, kind: &'static str, px: u64, composite_ms: f64, upload_ms: f64) { + self.frame_refresh_ms += composite_ms + upload_ms; + self.last_refresh = kind; + self.last_refresh_px = px; + self.composite_ms = composite_ms; + self.upload_ms = upload_ms; + if !kind.starts_with("gpu") { + self.gpu_uploads = 0; + // The CPU compositor did this one: there is no GPU time, and the last GPU + // refresh's would be read as this refresh's. + self.gpu_ms = None; + self.gpu_ms_px = 0; + } else { + self.gpu_fallback = None; + } + } + + /// Record a canvas refresh and any GPU measurement that came back with it. + pub fn record_refresh(&mut self, r: &Refresh) { + self.record(r.kind, r.px, r.composite_ms, r.upload_ms); + if let Some(t) = r.gpu { + self.record_gpu(t); + } + } + + /// Record a GPU composite measurement that came back (see [`photocraft_gpu::GpuTiming`]). + pub fn record_gpu(&mut self, t: photocraft_gpu::GpuTiming) { + self.gpu_ms = Some(t.ms); + self.gpu_ms_px = t.px; + } + pub fn span(&mut self, name: &'static str, ms: f64) { + self.spans.insert(name, (ms * 100.0).round() / 100.0); + } + pub fn frame(&mut self, ms: f64) { + self.ui_ms = if self.ui_ms == 0.0 { ms } else { self.ui_ms * 0.9 + ms * 0.1 }; + self.max_decay += 1.0; + if ms > self.ui_max_ms || self.max_decay > 60.0 { + self.ui_max_ms = ms; + self.max_decay = 0.0; + } + } +} diff --git a/crates/ui-egui/src/gpu_canvas/resources.rs b/crates/ui-egui/src/gpu_canvas/resources.rs new file mode 100644 index 0000000000..27606b7c05 --- /dev/null +++ b/crates/ui-egui/src/gpu_canvas/resources.rs @@ -0,0 +1,383 @@ +use super::budget::{canvas_budget, physical_memory}; +use super::doc_textures::init_buffer; +use super::shaders::{CANVAS_WGSL, ENCODE_WGSL, MIP_WGSL}; +use super::texels::LayerFit; +use super::*; + +pub(super) struct Resources { + pub(super) view_bgl: wgpu::BindGroupLayout, + pub(super) tile_bgl: wgpu::BindGroupLayout, + pub(super) shadow_pipeline: wgpu::RenderPipeline, + pub(super) tile_pipeline: wgpu::RenderPipeline, + pub(super) sampler: wgpu::Sampler, + pub(super) mip_bgl: wgpu::BindGroupLayout, + mip_pipeline: wgpu::RenderPipeline, + /// `mip_pipeline` and `encode_pipeline` for `Rgba16Float` tiles (when the adapter supports them). + mip_pipeline_high: Option, + encode_pipeline_high: Option, + pub(super) mip_sampler: wgpu::Sampler, + pub(super) docs: HashMap, + pub(super) views: HashMap, + pub(super) out_linear: bool, + /// Build each mip level in a scratch texture and copy it back instead of rendering into + /// the level directly (see [`separate_mip_targets`]). + pub(super) separate_mip_targets: bool, + /// The wgpu layer compositor (created on first use). + pub(super) compositor: Option, + /// Why the wgpu compositor couldn't be created (then the CPU compositor is used). + pub(super) compositor_failed: Option, + /// The device's health: the paint callback issues no GPU work once it's lost. + pub(super) health: photocraft_gpu::DeviceHealth, + /// GPU memory the compositor may hold (`None`: its default), and the document area the + /// view shows; applied before every composite. + pub(super) compositor_budget: Option, + /// The layer pages the last full (or large) refresh needed and the budget they had to fit + /// (bytes): when they don't fit, full refreshes go to the CPU ([`OVER_BUDGET`]). + pub(super) layer_fit: Option, + pub(super) compositor_cache_budget: Option, + pub(super) compositor_focus: Option, + /// GPU bytes one document's display texture set may take (see [`canvas_budget`]). + pub(super) canvas_budget: std::sync::Arc, + pub(super) encode_bgl: wgpu::BindGroupLayout, + encode_pipeline: wgpu::RenderPipeline, + pub(super) lut_bgl: wgpu::BindGroupLayout, + /// Display LUTs per (document, display) (monitor profile, Proof Colors / Gamut Warning); + /// `identity_lut` otherwise. + pub(super) luts: HashMap<(u64, u32), wgpu::BindGroup>, + /// Signatures belong to their renderer resources, including identity transforms (mode 0). + pub(super) display_lut_signatures: HashMap<(u64, u32), (u64, u8)>, + pub(super) identity_lut: wgpu::BindGroup, + /// Transparency checkerboard and gamut warning colours (Preferences › Transparency & Gamut). + pub(super) style: CanvasStyle, +} + +/// Canvas colours from Preferences › Transparency & Gamut. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CanvasStyle { + /// Checker square side in points (0 = no checkerboard: transparency shows white). + pub checker_square: f32, + pub checker_light: [f32; 3], + pub checker_dark: [f32; 3], + pub gamut_color: [f32; 3], + /// Gamut warning opacity 0..1. + pub gamut_opacity: f32, +} + +impl Default for CanvasStyle { + fn default() -> Self { + Self { checker_square: 8.0, checker_light: [1.0; 3], checker_dark: [0.8; 3], gamut_color: [0.5; 3], gamut_opacity: 1.0 } + } +} + +/// A display transform: either the existing 3D LUT or separate full-float shapers and +/// matrix. Pack curves into short rows to stay within WebGL2's texture-size limits. +pub(super) fn lut_bind_group( + device: &wgpu::Device, + queue: &wgpu::Queue, + bgl: &wgpu::BindGroupLayout, + size: u32, + bytes: &[u8], + shaper: Option<&photocraft_cms::GpuMatrixShaper>, +) -> wgpu::BindGroup { + let extent = wgpu::Extent3d { width: size, height: size, depth_or_array_layers: size }; + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_display_lut"), + size: extent, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D3, + format: FORMAT, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size * 4), rows_per_image: Some(size) }, + extent, + ); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + let (width, height, curves, matrix) = if let Some(s) = shaper { + let width = 1024usize; + let count = s.input_table().len() + s.output_table().len(); + let height = count.div_ceil(width); + let mut curves = Vec::with_capacity(width * height * 16); + for value in s.input_table().iter().chain(s.output_table()).flatten() { + curves.extend_from_slice(&value.to_le_bytes()); + } + curves.resize(width * height * 16, 0); + (width as u32, height as u32, curves, s.matrix_rows()) + } else { + (1, 1, vec![0; 16], [[0.0; 4]; 3]) + }; + let extent = wgpu::Extent3d { width, height, depth_or_array_layers: 1 }; + let curves_texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_display_shapers"), + size: extent, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + // textureLoad + explicit interpolation needs no optional float-filtering feature. + format: wgpu::TextureFormat::Rgba32Float, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &curves_texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + &curves, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(width * 16), rows_per_image: Some(height) }, + extent, + ); + let curves_view = curves_texture.create_view(&wgpu::TextureViewDescriptor::default()); + let matrix_bytes: Vec = matrix.iter().flatten().flat_map(|v| v.to_le_bytes()).collect(); + let matrix_buffer = init_buffer(device, "pc_display_matrix", &matrix_bytes, wgpu::BufferUsages::UNIFORM); + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("pc_display_lut"), + layout: bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&curves_view) }, + wgpu::BindGroupEntry { binding: 2, resource: matrix_buffer.as_entire_binding() }, + ], + }) +} + +/// The 2³ identity LUT (unused unless a document has none and `display` is set). +pub(super) fn identity_lut_bytes() -> Vec { + (0..8).flat_map(|i| [if i & 1 != 0 { 255 } else { 0 }, if i & 2 != 0 { 255 } else { 0 }, if i & 4 != 0 { 255 } else { 0 }, 0]).collect() +} + +pub(super) struct ViewGpu { + pub(super) buffer: wgpu::Buffer, + pub(super) bind_group: wgpu::BindGroup, + pub(super) frame_data: [f32; VIEW_FLOATS], +} + +pub(super) struct DocTextures { + pub(super) size: [u32; 2], + pub(super) format: wgpu::TextureFormat, + pub(super) tiles: Vec, +} + +pub(super) struct Tile { + /// Document-pixel rect: x, y, w, h. + pub(super) rect: [u32; 4], + pub(super) texture: wgpu::Texture, + pub(super) levels: Vec, + pub(super) bind_group: wgpu::BindGroup, + pub(super) _uniform: wgpu::Buffer, +} + +fn uniform_entry(binding: u32, size: u64, vis: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: vis, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: NonZeroU64::new(size) }, + count: None, + } +} + +fn texture_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + } +} + +fn sampler_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + } +} + +pub(super) fn f32_bytes(v: &[f32]) -> Vec { + v.iter().flat_map(|f| f.to_ne_bytes()).collect() +} + +fn pipeline( + device: &wgpu::Device, + label: &str, + layout: &wgpu::PipelineLayout, + module: &wgpu::ShaderModule, + (vs, fs): (&str, &str), + format: wgpu::TextureFormat, + blend: Option, +) -> wgpu::RenderPipeline { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(layout), + vertex: wgpu::VertexState { module, entry_point: Some(vs), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() }, + depth_stencil: None, + multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false }, + fragment: Some(wgpu::FragmentState { + module, + entry_point: Some(fs), + targets: &[Some(wgpu::ColorTargetState { format, blend, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + }) +} + +impl Resources { + pub(super) fn new(device: &wgpu::Device, queue: &wgpu::Queue, target: wgpu::TextureFormat, high: bool) -> Self { + let module = + device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_canvas"), source: wgpu::ShaderSource::Wgsl(CANVAS_WGSL.into()) }); + let vis = wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT; + let view_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("pc_canvas_view"), + entries: &[uniform_entry(0, VIEW_UNIFORM_SIZE, vis), sampler_entry(1)], + }); + let tile_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("pc_canvas_tile"), + entries: &[texture_entry(0), uniform_entry(1, TILE_UNIFORM_SIZE, vis)], + }); + let lut_entry = wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D3, + }, + count: None, + }; + let curves_entry = wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }; + let lut_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("pc_display_lut"), + entries: &[lut_entry, curves_entry, uniform_entry(2, 48, wgpu::ShaderStages::FRAGMENT)], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("pc_canvas"), + bind_group_layouts: &[Some(&view_bgl), Some(&tile_bgl), Some(&lut_bgl)], + immediate_size: 0, + }); + let shadow_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("pc_canvas_shadow"), + bind_group_layouts: &[Some(&view_bgl)], + immediate_size: 0, + }); + // Premultiplied "over", with egui's alpha rule (keeps a transparent window's alpha sane). + let blend = wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::OneMinusDstAlpha, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }, + }; + let shadow_pipeline = pipeline(device, "pc_canvas_shadow", &shadow_layout, &module, ("vs_shadow", "fs_shadow"), target, Some(blend)); + let tile_pipeline = pipeline(device, "pc_canvas_tile", &layout, &module, ("vs_tile", "fs_tile"), target, Some(blend)); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("pc_canvas_trilinear"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::MipmapFilterMode::Linear, + ..Default::default() + }); + + let mip_module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_mip"), source: wgpu::ShaderSource::Wgsl(MIP_WGSL.into()) }); + let mip_bgl = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("pc_mip"), entries: &[texture_entry(0), sampler_entry(1)] }); + let mip_layout = + device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("pc_mip"), bind_group_layouts: &[Some(&mip_bgl)], immediate_size: 0 }); + let mip_pipeline = pipeline(device, "pc_mip", &mip_layout, &mip_module, ("vs", "fs"), FORMAT, None); + let mip_pipeline_high = high.then(|| pipeline(device, "pc_mip_16f", &mip_layout, &mip_module, ("vs", "fs"), FORMAT_HIGH, None)); + let mip_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("pc_mip"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + // Compositor output (straight RGBA32F chunk) -> premultiplied RGBA8 display tile. + let encode_module = + device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_encode"), source: wgpu::ShaderSource::Wgsl(ENCODE_WGSL.into()) }); + let unfilterable = wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }; + let encode_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("pc_encode"), + entries: &[unfilterable, uniform_entry(1, 16, wgpu::ShaderStages::FRAGMENT)], + }); + let encode_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("pc_encode"), + bind_group_layouts: &[Some(&encode_bgl)], + immediate_size: 0, + }); + let encode_pipeline = pipeline(device, "pc_encode", &encode_layout, &encode_module, ("vs", "fs"), FORMAT, None); + let encode_pipeline_high = high.then(|| pipeline(device, "pc_encode_16f", &encode_layout, &encode_module, ("vs", "fs"), FORMAT_HIGH, None)); + let identity_lut = lut_bind_group(device, queue, &lut_bgl, 2, &identity_lut_bytes(), None); + Self { + lut_bgl, + luts: HashMap::new(), + display_lut_signatures: HashMap::new(), + identity_lut, + style: CanvasStyle::default(), + view_bgl, + tile_bgl, + shadow_pipeline, + tile_pipeline, + sampler, + mip_bgl, + mip_pipeline, + mip_pipeline_high, + encode_pipeline_high, + mip_sampler, + docs: HashMap::new(), + views: HashMap::new(), + out_linear: target.is_srgb(), + separate_mip_targets: false, + compositor: None, + compositor_failed: None, + health: photocraft_gpu::DeviceHealth::new(), + compositor_budget: None, + layer_fit: None, + compositor_cache_budget: None, + compositor_focus: None, + canvas_budget: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(canvas_budget(physical_memory(), None))), + encode_bgl, + encode_pipeline, + } + } + + /// The pipeline encoding compositor output into a `format` tile. + pub(super) fn encode_pipeline(&self, format: wgpu::TextureFormat) -> Option<&wgpu::RenderPipeline> { + if format == FORMAT_HIGH { self.encode_pipeline_high.as_ref() } else { Some(&self.encode_pipeline) } + } + + /// The mip-chain pipeline for `format` tiles. + pub(super) fn mip_pipeline(&self, format: wgpu::TextureFormat) -> Option<&wgpu::RenderPipeline> { + if format == FORMAT_HIGH { self.mip_pipeline_high.as_ref() } else { Some(&self.mip_pipeline) } + } +} diff --git a/crates/ui-egui/src/gpu_canvas/setup.rs b/crates/ui-egui/src/gpu_canvas/setup.rs new file mode 100644 index 0000000000..8195148a45 --- /dev/null +++ b/crates/ui-egui/src/gpu_canvas/setup.rs @@ -0,0 +1,117 @@ +use super::texels::texels; +use super::*; + +/// A CPU composite as the canvas texture stores it (`display`'s encoding; as is without one). +pub(super) fn texture_buffer<'a>( + display: Option<&photocraft_engine::display_color::CanvasDisplay>, + buf: &'a photocraft_compose::Buffer, +) -> std::borrow::Cow<'a, photocraft_compose::Buffer> { + match display { + Some(d) => d.texture_buffer(buf), + None => std::borrow::Cow::Borrowed(buf), + } +} + +/// A CPU composite `buf` as texels of a `format` canvas texture, in `display`'s encoding: what +/// [`GpuCanvas::upload_rect`] takes. Runs anywhere (a redraw's worker converts its own pieces). +pub fn display_texels( + format: wgpu::TextureFormat, + display: Option<&photocraft_engine::display_color::CanvasDisplay>, + buf: &photocraft_compose::Buffer, +) -> Vec { + texels(format, &texture_buffer(display, buf).px) +} + +/// What a [`GpuCanvas::refresh`] did. +#[derive(Clone, Debug, Default)] +pub struct Refresh { + /// "gpu-rect", "gpu-full" (wgpu compositor), "rect" or "full" (CPU compositor); "lost" or + /// [`REFRESH_OVER_BUDGET`] when nothing was drawn and the caller should use the CPU canvas. + pub kind: &'static str, + /// Pixels refreshed. + pub px: u64, + pub composite_ms: f64, + pub upload_ms: f64, + /// Layer tiles the wgpu compositor uploaded. + pub uploads: u64, + /// How long the GPU spent executing a recent wgpu composite, once its timestamps came back + /// (a frame or two after that refresh, so usually an earlier one than this). It carries its + /// own pixel count and is never this refresh's unless they match. `None` when the device has + /// no timestamp queries, on the CPU compositor, and on wasm: no number at all is reported + /// rather than `composite_ms`, which measures encoding and submitting, not executing. It + /// leaves out layer-tile uploads (`uploads` above counts them), so a first refresh of a + /// document under-reports by more than the few per cent of a warm one. + pub gpu: Option, + /// Why the wgpu compositor wasn't used. + pub fallback: Option, +} + +/// How the app creates its wgpu device: egui's defaults clamped to the adapter's supported limits, +/// with the adapter's own texture and buffer sizes rather than egui's 8192 px cap, so large +/// documents stay on the GPU compositor. +pub fn wgpu_setup() -> egui_wgpu::WgpuSetup { + let mut setup = egui_wgpu::WgpuSetup::without_display_handle(); + use_adapter_limits(&mut setup); + setup +} + +/// Make `setup` request the adapter's own texture and buffer size limits instead of egui's +/// default 8192 px cap (which sent every document wider or taller than 8192 px to the CPU +/// compositor). Other limits use egui's defaults (WebGL2's on GL), clamped to adapter support; +/// features stay egui's default. +pub fn use_adapter_limits(setup: &mut egui_wgpu::WgpuSetup) { + use_adapter_limits_with(setup, |_| {}); +} + +/// [`use_adapter_limits`], calling `on_adapter` with the chosen adapter just before the device +/// is requested (the desktop app records it in its crash-safe startup marker). +pub fn use_adapter_limits_with(setup: &mut egui_wgpu::WgpuSetup, on_adapter: impl Fn(&wgpu::Adapter) + Send + Sync + 'static) { + if let egui_wgpu::WgpuSetup::CreateNew(create) = setup { + create.device_descriptor = std::sync::Arc::new(move |adapter| { + on_adapter(adapter); + device_descriptor(adapter) + }); + } +} + +/// How the app asks for its device: egui's defaults, the adapter's texture and buffer size +/// limits ([`device_limits`]), and timestamp queries where the adapter has them, so the canvas +/// can report how long the GPU actually spends compositing ([`photocraft_gpu::GpuTimer`]). +/// A bench or test that builds its own device should use this rather than [`device_limits`] +/// alone, or it measures a device the app never creates. (`bevel_bench`, `fx_bench` and +/// `interactive_bench` still call [`device_limits`] directly and so report no GPU time.) +pub fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> { + wgpu::DeviceDescriptor { + label: Some("photocraft wgpu device"), + required_limits: device_limits(adapter), + required_features: timing_features(adapter), + ..Default::default() + } +} + +/// The timestamp-query features when the adapter supports all of them, else none: asking for a +/// feature an adapter lacks fails device creation, and a canvas without GPU timing is far better +/// than no canvas. +/// +/// `PHOTOCRAFT_NO_GPU_TIMING` suppresses the request as well as the timer +/// ([`photocraft_gpu::Compositor::measure_gpu_time`]), so the variable also rescues a driver +/// that advertises the features and then fails or misbehaves on device creation — not only one +/// whose timestamps come back wrong. +pub fn timing_features(adapter: &wgpu::Adapter) -> wgpu::Features { + let want = photocraft_gpu::timing::FEATURES; + if std::env::var_os("PHOTOCRAFT_NO_GPU_TIMING").is_some() { + return wgpu::Features::empty(); + } + if adapter.features().contains(want) { want } else { wgpu::Features::empty() } +} + +/// egui's base limits (WebGL2's on GL), clamped to adapter support, with its maximum texture and buffer sizes. +pub fn device_limits(adapter: &wgpu::Adapter) -> wgpu::Limits { + device_limits_for(adapter.get_info().backend, adapter.limits()) +} + +pub(super) fn device_limits_for(backend: wgpu::Backend, supported: wgpu::Limits) -> wgpu::Limits { + let base = if backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { wgpu::Limits::default() }; + let base = base.or_worse_values_from(&supported); + wgpu::Limits { max_texture_dimension_2d: supported.max_texture_dimension_2d, max_buffer_size: supported.max_buffer_size, ..base } +} diff --git a/crates/ui-egui/src/gpu_canvas/shaders.rs b/crates/ui-egui/src/gpu_canvas/shaders.rs new file mode 100644 index 0000000000..c29376a936 --- /dev/null +++ b/crates/ui-egui/src/gpu_canvas/shaders.rs @@ -0,0 +1,273 @@ +pub(super) const CANVAS_WGSL: &str = r#" +struct View { + a: vec4, // screen_w, screen_h, scale (device px per doc px), pixels_per_point + b: vec4, // doc origin x, y (device px), doc w, h (doc px) + c: vec4, // filter mode, lod, grid alpha, checker square (device px) + d: vec4, // pattern preview offset x, y (doc px), display (0 none, 1 LUT, 2 LUT + gamut, 3 matrix/shaper), output linear + e: vec4, // checker light rgb, gamut warning opacity + f: vec4, // checker dark rgb, 32-bit preview gain (2^exposure; 0 = off) + g: vec4, // gamut warning rgb, 32-bit preview 1 / gamma + h: vec4, // cos, sin, center_doc_x, center_doc_y +}; +struct Tile { r: vec4 }; // x, y, w, h in doc px + +@group(0) @binding(0) var view: View; +@group(0) @binding(1) var samp: sampler; +@group(1) @binding(0) var tex: texture_2d; +@group(1) @binding(1) var tile: Tile; +@group(2) @binding(0) var lut: texture_3d; +@group(2) @binding(1) var display_curves: texture_2d; +struct DisplayMatrix { r: vec4, g: vec4, b: vec4 }; +@group(2) @binding(2) var display_matrix: DisplayMatrix; + +fn curve_entry(index: u32) -> vec3 { + let width = textureDimensions(display_curves).x; + return textureLoad(display_curves, vec2(i32(index % width), i32(index / width)), 0).rgb; +} + +fn display_curve(c: vec3, offset: u32, intervals: f32) -> vec3 { + let p = clamp(c, vec3(0.0), vec3(1.0)) * intervals; + let lo = vec3(floor(p)); + let hi = min(lo + vec3(1u), vec3(u32(intervals))); + let f = fract(p); + return vec3( + mix(curve_entry(offset + lo.r).r, curve_entry(offset + hi.r).r, f.r), + mix(curve_entry(offset + lo.g).g, curve_entry(offset + hi.g).g, f.g), + mix(curve_entry(offset + lo.b).b, curve_entry(offset + hi.b).b, f.b) + ); +} + +fn matrix_display(c: vec3) -> vec3 { + // Layout matches cms::GpuMatrixShaper: 4097 input entries, then 4096 inverse-curve + // entries indexed by the fourth root. This preserves near-black precision without + // interpolating across clipped corners of a coarse RGB cube. + let v = vec4(display_curve(c, 0u, 4096.0), 1.0); + let linear = vec3(dot(display_matrix.r, v), dot(display_matrix.g, v), dot(display_matrix.b, v)); + let u = sqrt(sqrt(clamp(linear, vec3(0.0), vec3(1.0)))); + return display_curve(u, 4097u, 4095.0); +} + +struct VOut { @builtin(position) pos: vec4 }; + +fn corner(i: u32) -> vec2 { + var c = array, 6>(vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(0.0, 1.0), vec2(1.0, 0.0), vec2(1.0, 1.0)); + return c[i]; +} + +fn px_to_clip(p: vec2) -> vec4 { + let n = p / view.a.xy * 2.0 - 1.0; + return vec4(n.x, -n.y, 0.0, 1.0); +} + +fn screen_center() -> vec2 { + return view.b.xy + view.h.zw * view.a.z; +} + +fn doc_to_px(d: vec2) -> vec2 { + let cs = view.h.xy; + let q = d - view.h.zw; + let r = vec2(q.x * cs.x - q.y * cs.y, q.x * cs.y + q.y * cs.x); + return screen_center() + r * view.a.z; +} + +fn px_to_doc(p: vec2) -> vec2 { + let cs = view.h.xy; + let q = (p - screen_center()) / view.a.z; + return vec2(q.x * cs.x + q.y * cs.y, -q.x * cs.y + q.y * cs.x) + view.h.zw; +} + +fn doc_min() -> vec2 { return view.b.xy; } +fn doc_max() -> vec2 { return view.b.xy + view.b.zw * view.a.z; } + +fn srgb_to_linear(c: vec3) -> vec3 { + let lo = c / 12.92; + let hi = pow((c + 0.055) / 1.055, vec3(2.4)); + return select(hi, lo, c <= vec3(0.04045)); +} + +fn linear_to_srgb(c: vec3) -> vec3 { + let hi = 1.055 * pow(max(c, vec3(1e-12)), vec3(1.0 / 2.4)) - 0.055; + return select(hi, c * 12.92, c <= vec3(0.0031308)); +} + +// --- drop shadow --------------------------------------------------------------------------- + +fn erf2(x: vec2) -> vec2 { + let s = sign(x); + let a = abs(x); + var t = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a; + t = t * t; + return s - s / (t * t); +} + +// Coverage of the box [lo, hi] blurred by a Gaussian of std-dev `sigma`, at point p. +fn box_blur(p: vec2, lo: vec2, hi: vec2, sigma: f32) -> f32 { + let k = 0.70710678 / sigma; + let q = (erf2((p - lo) * k) - erf2((p - hi) * k)) * 0.5; + return q.x * q.y; +} + +@vertex +fn vs_shadow(@builtin(vertex_index) vi: u32) -> VOut { + let pad = 64.0 * view.a.w; + let c0 = doc_to_px(vec2(0.0, 0.0)); + let c1 = doc_to_px(vec2(view.b.z, 0.0)); + let c2 = doc_to_px(vec2(view.b.z, view.b.w)); + let c3 = doc_to_px(vec2(0.0, view.b.w)); + let lo = min(min(c0, c1), min(c2, c3)) - vec2(pad); + let hi = max(max(c0, c1), max(c2, c3)) + vec2(pad); + let p = mix(lo, hi, corner(vi)); + return VOut(px_to_clip(p)); +} + +@fragment +fn fs_shadow(in: VOut) -> @location(0) vec4 { + let p = in.pos.xy; + let d = px_to_doc(p); + if (all(d >= vec2(0.0)) && all(d < view.b.zw)) { + discard; + } + let p_align = view.b.xy + d * view.a.z; + let lo = doc_min(); + let hi = doc_max(); + let u = view.a.w; + let ambient = box_blur(p_align - vec2(0.0, 7.0 * u), lo, hi, 16.0 * u) * 0.40; + let contact = box_blur(p_align - vec2(0.0, 0.75 * u), lo, hi, 1.25 * u) * 0.30; + let a = 1.0 - (1.0 - ambient) * (1.0 - contact); + return vec4(0.0, 0.0, 0.0, a); +} + +// --- document tiles ------------------------------------------------------------------------ + +@vertex +fn vs_tile(@builtin(vertex_index) vi: u32) -> VOut { + // A View › Pattern Preview copy sits a whole number of document sizes away (view.d.xy). + let p = doc_to_px(view.d.xy + tile.r.xy + tile.r.zw * corner(vi)); + return VOut(px_to_clip(p)); +} + +// Cells are screen-sized (view.c.w device px) but anchored to the document's top-left corner, so +// the pattern moves with the image as it is panned or zoomed. `d` is in document pixels (each +// Pattern Preview copy has the same cells). +fn checker(d: vec2) -> vec3 { + if (view.c.w <= 0.0) { + return vec3(1.0); + } + let c = floor(d * view.a.z / view.c.w); + let odd = fract((c.x + c.y) * 0.5) > 0.25; + return select(view.e.xyz, view.f.xyz, odd); +} + +@fragment +fn fs_tile(in: VOut) -> @location(0) vec4 { + let p = in.pos.xy; + let scale = view.a.z; + let d = px_to_doc(p) - view.d.xy; // document pixel coordinates (within this copy) + let size = tile.r.zw; + let t = d - tile.r.xy; // texel coordinates within this tile + let mode = view.c.x; + var col: vec4; + if (mode < 0.5) { + // Zoomed out: trilinear through the mip chain. + col = textureSampleLevel(tex, samp, t / size, view.c.y); + } else if (mode < 1.5) { + col = textureSampleLevel(tex, samp, t / size, 0.0); + } else { + // Crisp texels with a one-device-pixel anti-aliased edge ("sharp bilinear"). + let tt = t - 0.5; + let i = floor(tt); + let f = clamp((tt - i - 0.5) * scale + 0.5, vec2(0.0), vec2(1.0)); + col = textureSampleLevel(tex, samp, (i + 0.5 + f) / size, 0.0); + } + if (view.f.w > 0.0 && col.a > 0.0) { + // View › 32-bit Preview Options: exposure and gamma in linear light on the sRGB-encoded + // texture value, before the display LUT. A float canvas keeps values above 1.0, so they + // are brought into range by the exposure instead of clipped. + let lin = srgb_to_linear(max(col.rgb / col.a, vec3(0.0))) * view.f.w; + let v = linear_to_srgb(min(pow(max(lin, vec3(1e-12)), vec3(view.g.w)), vec3(1.0))); + col = vec4(v * col.a, col.a); + } + if (view.d.z > 0.5 && col.a > 0.0) { + // Colour management, Proof Colors, Gamut Warning: the document's display LUT (alpha flags + // out-of-gamut colours). + let c = clamp(col.rgb / col.a, vec3(0.0), vec3(1.0)); + var shown: vec3; + if (view.d.z > 2.5) { + shown = matrix_display(c); + } else { + let n = f32(textureDimensions(lut).x); + let l = textureSampleLevel(lut, samp, (c * (n - 1.0) + 0.5) / n, 0.0); + shown = select(l.rgb, mix(l.rgb, view.g.xyz, view.e.w), view.d.z > 1.5 && l.a > 0.5); + } + col = vec4(shown * col.a, col.a); + } + var rgb = col.rgb + checker(d) * (1.0 - col.a); + // The pixel grid is drawn over pixels with content, not over empty checker. + let grid = view.c.z * col.a; + if (grid > 0.0) { + let e = fract(d) * scale; + if (e.x < 1.0 || e.y < 1.0) { + // White over dark pixels, a weaker black over light ones, cross-faded by luma so a + // mid-tone image never flips line colour from one cell to the next (pixel_grid.rs + // `light_share`: same band, same numbers). + let t = smoothstep(0.35, 0.75, dot(rgb, vec3(0.299, 0.587, 0.114))); + let white = grid * (1.0 - t); + let black = grid * 0.64 * t; + rgb = rgb * (1.0 - white - black) + vec3(white); + } + } + if (view.d.w > 0.5) { + rgb = srgb_to_linear(rgb); + } + return vec4(rgb, 1.0); +} +"#; + +pub(super) const ENCODE_WGSL: &str = r#" +@group(0) @binding(0) var acc: texture_2d; +@group(0) @binding(1) var offset: vec4; // x, y, encode sRGB, keep values above 1.0 + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { + let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u)); + return vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0); +} + +fn srgb_encode(c: vec3) -> vec3 { + return select(1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, c * 12.92, c <= vec3(0.0031308)); +} + +@fragment +fn fs(@builtin(position) pos: vec4) -> @location(0) vec4 { + let c = textureLoad(acc, vec2(floor(pos.xy)) - offset.xy, 0); + let a = clamp(c.a, 0.0, 1.0); + var rgb = max(c.rgb, vec3(0.0)); + if (offset.w == 0) { + rgb = min(rgb, vec3(1.0)); + } + if (offset.z != 0) { + // Linear composite: store its sRGB encoding (8-bit precision where it matters). + rgb = srgb_encode(rgb); + } + return vec4(rgb * a, a); +} +"#; + +pub(super) const MIP_WGSL: &str = r#" +@group(0) @binding(0) var src: texture_2d; +@group(0) @binding(1) var samp: sampler; + +struct V { @builtin(position) pos: vec4, @location(0) uv: vec2 }; + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> V { + let uv = vec2(f32((vi << 1u) & 2u), f32(vi & 2u)); + return V(vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0), uv); +} + +@fragment +fn fs(in: V) -> @location(0) vec4 { + // A bilinear tap at the destination texel centre averages the 2×2 source block. + return textureSampleLevel(src, samp, in.uv, 0.0); +} +"#; diff --git a/crates/ui-egui/src/gpu_canvas/texels.rs b/crates/ui-egui/src/gpu_canvas/texels.rs new file mode 100644 index 0000000000..966b23c40c --- /dev/null +++ b/crates/ui-egui/src/gpu_canvas/texels.rs @@ -0,0 +1,145 @@ +use super::*; + +/// Straight-alpha f32 RGBA (sRGB-encoded) → premultiplied RGBA8, split across threads on native. +pub fn premultiply_rgba8(px: &[[f32; 4]]) -> Vec { + let mut out = Vec::new(); + texels_into(FORMAT, px, &mut out); + out +} + +/// Straight-alpha f32 RGBA (sRGB-encoded) → premultiplied RGBA16F (little-endian), split across +/// threads on native. Colour values above 1.0 are kept (32-bit documents); negatives and NaN +/// become 0. +pub fn premultiply_rgba16f(px: &[[f32; 4]]) -> Vec { + let mut out = Vec::new(); + texels_into(FORMAT_HIGH, px, &mut out); + out +} + +/// Bytes per texel of a canvas texture format. +pub(super) fn texel_bytes(format: wgpu::TextureFormat) -> u64 { + if format == FORMAT_HIGH { 8 } else { 4 } +} + +/// Straight-alpha f32 RGBA → premultiplied texels of `format`. +pub(super) fn texels(format: wgpu::TextureFormat, px: &[[f32; 4]]) -> Vec { + let mut out = Vec::new(); + texels_into(format, px, &mut out); + out +} + +/// [`texels`] into `out` (resized; reusing it across bands saves page-faulting a fresh buffer). +pub(super) fn texels_into(format: wgpu::TextureFormat, px: &[[f32; 4]], out: &mut Vec) { + fn rgba8(src: &[[f32; 4]], dst: &mut [u8]) { + for (o, p) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src) { + let a = p[3].clamp(0.0, 1.0); + o[0] = (p[0].clamp(0.0, 1.0) * a * 255.0 + 0.5) as u8; + o[1] = (p[1].clamp(0.0, 1.0) * a * 255.0 + 0.5) as u8; + o[2] = (p[2].clamp(0.0, 1.0) * a * 255.0 + 0.5) as u8; + o[3] = (a * 255.0 + 0.5) as u8; + } + } + fn rgba16f(src: &[[f32; 4]], dst: &mut [u8]) { + for (o, p) in dst.as_chunks_mut::<8>().0.iter_mut().zip(src) { + let a = if p[3].is_nan() { 0.0 } else { p[3].clamp(0.0, 1.0) }; + let [r, g, b, a] = [p[0].max(0.0) * a, p[1].max(0.0) * a, p[2].max(0.0) * a, a].map(|v| f32_to_f16(v).to_le_bytes()); + *o = [r[0], r[1], g[0], g[1], b[0], b[1], a[0], a[1]]; + } + } + let bpp = texel_bytes(format) as usize; + let convert = if format == FORMAT_HIGH { rgba16f } else { rgba8 }; + out.clear(); + out.resize(px.len() * bpp, 0); + #[cfg(not(target_arch = "wasm32"))] + if px.len() > 1 << 18 { + let threads = std::thread::available_parallelism().map_or(4, |n| n.get()).min(16); + let chunk = px.len().div_ceil(threads); + std::thread::scope(|s| { + for (src, dst) in px.chunks(chunk).zip(out.chunks_mut(chunk * bpp)) { + s.spawn(move || convert(src, dst)); + } + }); + return; + } + convert(px, out); +} + +/// IEEE 754 binary32 → binary16, round to nearest even; overflow saturates to the largest +/// finite half (65504) so HDR values never become infinite, NaN becomes 0. Branch-light: the +/// rounding is done with integer adds on the f32 bits (and an f32 add for subnormals). +pub(super) fn f32_to_f16(v: f32) -> u16 { + // 2^-14: the smallest normal half; below it the result is subnormal (or zero). + const MIN_NORMAL: u32 = 113 << 23; + // 2^16: halves overflow from here (65520 and up round to infinity; saturate instead). + const OVERFLOW: u32 = 143 << 23; + // Adding 0.5 (as f32) shifts a subnormal half's bits to the bottom of the mantissa. + const DENORM_MAGIC: u32 = 126 << 23; + let bits = v.to_bits(); + let sign = ((bits >> 16) & 0x8000) as u16; + let a = bits & 0x7fff_ffff; + if a > 0x7f80_0000 { + return 0; + } + let h = if a >= OVERFLOW { + 0x7bff + } else if a < MIN_NORMAL { + (f32::from_bits(a) + f32::from_bits(DENORM_MAGIC)).to_bits().wrapping_sub(DENORM_MAGIC) as u16 + } else { + // Rebias the exponent and round the 13 dropped mantissa bits to nearest even. + let odd = (a >> 13) & 1; + (((a.wrapping_add(0xc800_0fff).wrapping_add(odd)) >> 13).min(0x7bff)) as u16 + }; + sign | h +} + +/// IEEE 754 binary16 → binary32. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn f16_to_f32(h: u16) -> f32 { + let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; + let exp = i32::from((h >> 10) & 0x1f); + let man = f32::from(h & 0x3ff); + sign * match exp { + 0 => man * 2f32.powi(-24), + 0x1f => { + if man == 0.0 { + f32::INFINITY + } else { + f32::NAN + } + } + e => (1.0 + man / 1024.0) * 2f32.powi(e - 15), + } +} + +/// One stored texel of `format` as f32 RGBA. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn texel_to_f32(format: wgpu::TextureFormat, b: &[u8]) -> [f32; 4] { + let mut o = [0.0f32; 4]; + for (i, v) in o.iter_mut().enumerate() { + *v = if format == FORMAT_HIGH { + f16_to_f32(u16::from_le_bytes([b.get(i * 2).copied().unwrap_or(0), b.get(i * 2 + 1).copied().unwrap_or(0)])) + } else { + f32::from(b.get(i).copied().unwrap_or(0)) / 255.0 + }; + } + o +} + +// --------------------------------------------------------------------------------------------- +// GPU resources + +/// The GPU memory a refresh's layer pages need against what they may hold (bytes). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LayerFit { + /// The document refreshed. + pub doc: u64, + pub needed: u64, + pub budget: u64, +} + +impl LayerFit { + pub fn fits(&self) -> bool { + self.needed <= self.budget + } +} From 17a3dd32043e6994a1e7bf14fcf841bcd2dfe5c2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:17:03 +0000 Subject: [PATCH 230/259] refactor(ui-egui): split adjust_editors.rs into adjust_editors/ --- crates/ui-egui/src/adjust_editors.rs | 1530 +---------------- crates/ui-egui/src/adjust_editors/basic.rs | 287 ++++ crates/ui-egui/src/adjust_editors/curves.rs | 385 +++++ .../src/adjust_editors/gradient_map.rs | 284 +++ .../src/adjust_editors/hue_saturation.rs | 207 +++ crates/ui-egui/src/adjust_editors/levels.rs | 208 +++ crates/ui-egui/src/adjust_editors/session.rs | 148 ++ 7 files changed, 1546 insertions(+), 1503 deletions(-) create mode 100644 crates/ui-egui/src/adjust_editors/basic.rs create mode 100644 crates/ui-egui/src/adjust_editors/curves.rs create mode 100644 crates/ui-egui/src/adjust_editors/gradient_map.rs create mode 100644 crates/ui-egui/src/adjust_editors/hue_saturation.rs create mode 100644 crates/ui-egui/src/adjust_editors/levels.rs create mode 100644 crates/ui-egui/src/adjust_editors/session.rs diff --git a/crates/ui-egui/src/adjust_editors.rs b/crates/ui-egui/src/adjust_editors.rs index 099ced0a43..cdee0d6502 100644 --- a/crates/ui-egui/src/adjust_editors.rs +++ b/crates/ui-egui/src/adjust_editors.rs @@ -23,6 +23,33 @@ use crate::theme::Tokens; use crate::tone::{self, HistSource, Histograms}; use crate::widgets::{self, hue_color}; +mod basic; +mod curves; +mod gradient_map; +mod hue_saturation; +mod levels; +mod session; + +#[cfg(test)] +pub(crate) use basic::row_value; +#[cfg(test)] +use basic::track_stops; +use basic::{black_white, brightness_contrast, channel_mixer, color_balance, photo_filter, sliders, threshold}; +pub use basic::{reset_adjustment_editor, reset_color_balance}; +use curves::curves; +#[cfg(test)] +use curves::{CURVE_HANDLE_SIZE, curve_graph}; +pub use curves::{ToneChannel, tone_channels}; +pub(crate) use curves::{curve_side_max, read_curve}; +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 levels::levels; +pub use levels::{auto_levels, gamma_from_pos, gamma_pos}; +pub use session::{layer_editor, layer_mem, properties_coalesce, properties_reset, session_start}; + /// Kinds edited here (Selective Color and Color Lookup have their own editors; Invert has none). pub const KINDS: [&str; 13] = [ "brightnessContrast", @@ -194,1509 +221,6 @@ fn label(ui: &mut egui::Ui, text: &str) { ui.label(RichText::new(tl!(&text)).color(t.text_dim).size(12.0)); } -/// Labelled slider rows over top-level keys: (key, label, min, max, default, unit). -/// A row of [`sliders`]: params key, label, range, default, unit, and its decimal places (None: -/// two for a range of 10 or less, else whole numbers). -type SliderRow<'a> = (&'a str, &'a str, f32, f32, f32, &'a str, Option); - -/// The value a [`sliders`] row stores for `x`: rounded to `decimals` places, or by its range. -pub(crate) fn row_value(x: f32, min: f32, max: f32, decimals: Option) -> f32 { - match decimals { - Some(d) => { - let scale = 10f32.powi(d.min(6) as i32); - (x * scale).round() / scale - } - None if max - min <= 10.0 => round(x, 0.01), - None => x.round(), - } -} - -fn sliders(ui: &mut egui::Ui, v: &mut Value, rows: &[SliderRow]) -> Edit { - let mut e = Edit::default(); - for &(key, text, min, max, default, unit, decimals) in rows { - let mut x = num(v, key, default).clamp(min, max); - // A double-click on the slider puts it back to its default (Photoshop). - let gestures = widgets::RowGestures { reset: Some(default), wheel_step: None, ..Default::default() }; - let r = widgets::slider_row_prec(ui, text, &mut x, min..=max, unit, None, gestures, decimals); - if r.changed() { - v[key] = json!(row_value(x, min, max, decimals)); - } - e.add(Edit::of(&r)); - } - e -} - -fn gradient_slider(ui: &mut egui::Ui, text: &str, x: &mut f32, range: std::ops::RangeInclusive, unit: &str, stops: [Color32; 2], dynamic: bool) -> Edit { - let r = widgets::slider_row(ui, text, x, range, unit, dynamic.then_some(&stops)); - Edit::of(&r) -} - -/// Preferences ▸ Interface ▸ Dynamic Color Sliders: the colour track for a slider, or the plain -/// track when it is off. -fn track_stops<'a>(cx: &EditorCx, stops: &'a [Color32]) -> Option<&'a [Color32]> { - cx.dynamic_color_sliders.then_some(stops) -} - -// --------------------------------------------------------------------------------------------- -// Brightness/Contrast - -fn brightness_contrast(ui: &mut egui::Ui, v: &mut Value) -> Edit { - let legacy = flag(v, "legacy", false); - let lo = if legacy { -100.0 } else { -50.0 }; - let mut e = sliders(ui, v, &[("brightness", tl!("Brightness"), -150.0, 150.0, 0.0, "", None), ("contrast", tl!("Contrast"), lo, 100.0, 0.0, "", None)]); - let mut l = legacy; - if widgets::checkbox(ui, &mut l, tl!("Use Legacy")).changed() { - v["legacy"] = json!(l); - if !l { - v["contrast"] = json!(num(v, "contrast", 0.0).max(-50.0)); - } - e.add(Edit::discrete(true)); - } - e -} - -// --------------------------------------------------------------------------------------------- -// Channels of Levels / Curves - -/// A channel of a tone editor: the params key (None = the top-level / composite keys for Levels; -/// Curves uses "points"), its label, and its colour name. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct ToneChannel { - pub key: &'static str, - pub label: &'static str, -} - -/// The channels a tone editor lists for `space` (histogram index = position). -pub fn tone_channels(space: ToneSpace, gray: bool) -> &'static [ToneChannel] { - const RGB: [ToneChannel; 4] = [ - ToneChannel { key: "", label: "RGB" }, - ToneChannel { key: "red", label: "Red" }, - ToneChannel { key: "green", label: "Green" }, - ToneChannel { key: "blue", label: "Blue" }, - ]; - const GRAY: [ToneChannel; 1] = [ToneChannel { key: "", label: "Gray" }]; - const CMYK: [ToneChannel; 5] = [ - ToneChannel { key: "", label: "CMYK" }, - ToneChannel { key: "cyan", label: "Cyan" }, - ToneChannel { key: "magenta", label: "Magenta" }, - ToneChannel { key: "yellow", label: "Yellow" }, - ToneChannel { key: "black", label: "Black" }, - ]; - const LAB: [ToneChannel; 3] = - [ToneChannel { key: "lightness", label: "Lightness" }, ToneChannel { key: "a", label: "a" }, ToneChannel { key: "b", label: "b" }]; - match space { - ToneSpace::Rgb if gray => &GRAY, - ToneSpace::Rgb => &RGB, - ToneSpace::Cmyk => &CMYK, - ToneSpace::Lab => &LAB, - } -} - -fn channel_picker(ui: &mut egui::Ui, id: egui::Id, chans: &[ToneChannel], text: &str) -> usize { - let opts: Vec<(usize, &str)> = chans.iter().enumerate().map(|(i, c)| (i, c.label)).collect(); - channel_picker_opts(ui, id, &opts, text, true) -} - -/// The popup, with `translate` for whether the built-in labels follow the interface language; -/// a user-typed channel name is shown exactly as entered (#5335). -fn channel_picker_opts(ui: &mut egui::Ui, id: egui::Id, opts: &[(usize, &str)], text: &str, translate: bool) -> usize { - let mut ch: usize = ui.data(|d| d.get_temp(id)).unwrap_or(0); - if ch >= opts.len() { - ch = 0; - } - ui.horizontal(|ui| { - label(ui, text); - let width = if opts.len() == 1 { 160.0 } else { 110.0 }; - let key = format!("{id:?}-ch"); - if translate { - widgets::dropdown(ui, &key, text, &mut ch, opts, width); - } else { - widgets::dropdown_literal(ui, &key, text, &mut ch, opts, width); - } - }); - ui.data_mut(|d| d.insert_temp(id, ch)); - ch -} - -fn hist_color(ch: &ToneChannel, t: &Tokens) -> Color32 { - match ch.key { - "" | "lightness" | "black" => Color32::from_gray(if t.pro { 150 } else { 110 }), - k => tone::channel_color(k, t), - } -} - -fn bar_color(ch: &ToneChannel, t: &Tokens) -> Color32 { - match ch.key { - "" | "lightness" | "black" => Color32::WHITE, - k => tone::channel_color(k, t), - } -} - -/// Horizontal (or vertical) black → `to` gradient bar. -fn gradient_bar(p: &egui::Painter, r: Rect, from: Color32, to: Color32, vertical: bool) { - let mut mesh = egui::Mesh::default(); - let (a, b, c, d) = if vertical { - (r.left_bottom(), r.right_bottom(), r.right_top(), r.left_top()) - } else { - (r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()) - }; - let (ca, cb) = if vertical { (from, from) } else { (from, to) }; - let (cc, cd) = if vertical { (to, to) } else { (to, from) }; - mesh.colored_vertex(a, ca); - mesh.colored_vertex(b, cb); - mesh.colored_vertex(c, cc); - mesh.colored_vertex(d, cd); - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(0, 2, 3); - p.add(mesh); -} - -// --------------------------------------------------------------------------------------------- -// Curves - -const CURVE_HANDLE_SIZE: f32 = 7.0; -const CURVE_GRAPH_PADDING: f32 = 5.0; - -/// The room left on screen for the Curves dialog's other rows (title, channel and mode, Input and -/// Output, eyedroppers, buttons) when its graph is as tall as it can be. -const CURVES_CHROME: f32 = 360.0; -/// The smallest and the default largest side of the Curves graph: 300 points was the fixed -/// size until #8984. -const CURVE_SIDE: (f32, f32) = (120.0, 300.0); - -/// The Curves graph's side (#8984): the width it is given, in the Properties panel and in the -/// resizable dialog, and no taller than the window leaves room for beside the other rows. -fn curve_side(ui: &egui::Ui) -> f32 { - let tallest = curve_side_max(ui.ctx()); - let width = ui.available_width(); - if width.is_finite() { width.clamp(CURVE_SIDE.0, tallest) } else { CURVE_SIDE.1 } -} - -/// The largest the Curves graph gets in this window: as tall as the window leaves room for beside -/// the dialog's other rows, and never under the old 300 points. The Curves dialog is no wider. -pub(crate) fn curve_side_max(ctx: &egui::Context) -> f32 { - (ctx.content_rect().height() - CURVES_CHROME).max(CURVE_SIDE.1) -} - -fn curve_graph(full: Rect, side: f32) -> Rect { - let base = Rect::from_min_size(full.min + vec2(14.0, 0.0), vec2(side - 14.0, side - 14.0)); - Rect::from_min_max(base.min + vec2(CURVE_GRAPH_PADDING, CURVE_GRAPH_PADDING), base.max - vec2(CURVE_GRAPH_PADDING, CURVE_GRAPH_PADDING)) -} - -pub(crate) fn read_curve(v: &Value, key: &str) -> Vec<[f32; 2]> { - let pts: Vec<[f32; 2]> = v - .get(key) - .and_then(Value::as_array) - .map(|a| { - a.iter() - .filter_map(|q| { - let q = q.as_array()?; - Some([q.first()?.as_f64()? as f32, q.get(1)?.as_f64()? as f32]) - }) - .collect() - }) - .unwrap_or_default(); - if pts.len() < 2 { vec![[0.0, 0.0], [255.0, 255.0]] } else { pts } -} - -fn curve_key(ch: &ToneChannel) -> &'static str { - if ch.key.is_empty() { "points" } else { ch.key } -} - -/// A pencil-drawn channel: its 256 output levels (identity when absent or not a map). -fn read_map(v: &Value, key: &str) -> Vec { - let map: Option> = v - .get(key) - .and_then(Value::as_array) - .filter(|a| a.len() == photocraft_doc::adjust::CURVE_MAP_LEN) - .and_then(|a| a.iter().map(|o| o.as_f64().map(|o| o as f32)).collect()); - map.unwrap_or_else(|| (0..photocraft_doc::adjust::CURVE_MAP_LEN).map(|k| k as f32).collect()) -} - -fn write_map(v: &mut Value, key: &str, map: &[f32]) { - v[key] = json!(map.iter().map(|o| (o * 100.0).round() / 100.0).collect::>()); -} - -/// Switches the Curves values between point editing and the pencil: the engine draws the point -/// curves into maps, or fits points to the drawn maps (Photoshop's two curve buttons). -fn set_pencil(v: &mut Value, pencil: bool, gray: bool) -> bool { - let mut p = v.clone(); - p["pencil"] = json!(pencil); - let mode = if gray { photocraft_doc::ColorMode::Grayscale } else { photocraft_doc::ColorMode::Rgb }; - let Ok(a) = adjust_params::from_params("curves", &p, None, mode) else { return false }; - *v = adjust_params::to_params(&a); - // Explicit, so an update over a pencil-drawn layer leaves the pencil. - v["pencil"] = json!(pencil); - true -} - -/// Mode buttons above the graph: points, pencil, and Smooth for the shown channel's drawing. -fn curves_mode_row(ui: &mut egui::Ui, v: &mut Value, key: &str, gray: bool) -> Edit { - let pencil = v.get("pencil").and_then(Value::as_bool).unwrap_or(false); - let mut e = Edit::default(); - ui.horizontal(|ui| { - if crate::icons::button(ui, "spline", 24.0, !pencil, tl!("Edit points to modify the curve")).clicked() && pencil { - e.add(Edit::discrete(set_pencil(v, false, gray))); - } - if crate::icons::button(ui, "pencil", 24.0, pencil, tl!("Draw to modify the curve")).clicked() && !pencil { - e.add(Edit::discrete(set_pencil(v, true, gray))); - } - let label = crate::i18n::tr_ctx(crate::i18n::current(), "curves", "Smooth"); - let smooth = ui - .add_enabled_ui(pencil, |ui| widgets::secondary_button(ui, label, 0.0)) - .inner - .on_hover_text(tl!("Smooth the curve values")) - .on_disabled_hover_text(tl!("Smooth the curve values")); - if smooth.clicked() { - let mut map = read_map(v, key); - adjust_params::smooth_curve_map(&mut map); - write_map(v, key, &map); - e.add(Edit::discrete(true)); - } - }); - e -} - -fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { - let t = Tokens::get(ui.ctx()); - let space = space_of(v); - let chans = tone_channels(space, cx.gray); - let state_id = cx.mem.with("curves"); - let mut st: CurveUi = ui.data(|d| d.get_temp(state_id)).unwrap_or_default(); - let isolated = cx.isolated_curve.as_ref(); - let ch = if let Some(iso) = isolated { - channel_picker_opts(ui, cx.mem.with("curves-ch"), &[(0, iso.name.as_str())], tl!("Channel:"), iso.translate) - } else { - channel_picker(ui, cx.mem.with("curves-ch"), chans, tl!("Channel:")) - }; - if ch != st.channel { - st = CurveUi { channel: ch, ..Default::default() }; - } - let chan = - if let Some(iso) = isolated { ToneChannel { key: iso.key, label: "" } } else { chans.get(ch).copied().unwrap_or(ToneChannel { key: "", label: "" }) }; - let overlay_others = isolated.is_none(); - let tinted = isolated.is_some_and(|c| c.tint) || (isolated.is_none() && ch != 0); - let hist_i = isolated.map_or(ch, |c| c.hist); - let key = curve_key(&chan); - let mut e = curves_mode_row(ui, v, key, cx.gray); - let pencil = v.get("pencil").and_then(Value::as_bool).unwrap_or(false); - let mut pts = read_curve(v, key); - let mut map = read_map(v, key); - let side = curve_side(ui); - ui.add_space(4.0); - let (full, resp) = ui.allocate_exact_size(vec2(side, side + 14.0), Sense::click_and_drag()); - let graph = curve_graph(full, side); - ui.data_mut(|d| d.insert_temp(cx.mem.with("curves-graph"), graph)); - let to_scr = |q: [f32; 2]| pos2(graph.left() + q[0] / 255.0 * graph.width(), graph.bottom() - q[1] / 255.0 * graph.height()); - let mut changed = false; - let mut drawn = false; - if pencil { - // Pencil: a stroke draws while the button is down and commits on release; Shift - // continues from the previous stroke's end in a straight line. - let stroke_id = cx.mem.with("curves-pencil"); - let (mut active, mut last): (bool, Option<[f32; 2]>) = ui.data(|d| d.get_temp(stroke_id)).unwrap_or_default(); - if resp.is_pointer_button_down_on() - && let Some(pos) = resp.interact_pointer_pos() - { - let q = [ - ((pos.x - graph.left()) / graph.width().max(1.0) * 255.0).clamp(0.0, 255.0), - ((graph.bottom() - pos.y) / graph.height().max(1.0) * 255.0).clamp(0.0, 255.0), - ]; - let from = if active || ui.input(|i| i.modifiers.shift) { last.unwrap_or(q) } else { q }; - drawn = curve_edit::pencil_line(&mut map, from, q); - active = true; - last = Some(q); - } else if active { - active = false; - e.commit = true; - } - ui.data_mut(|d| d.insert_temp(stroke_id, (active, last))); - } else { - let interaction = crate::point_curve::interact(ui, &resp, graph, &mut pts, &mut st.gesture); - changed = interaction.changed; - e.commit |= interaction.commit; - } - - // Draw: histogram, quarter grid, baseline, gradient bars, other channels, the curve, points. - let p = ui.painter_at(full.expand(2.0)); - p.rect_filled(graph, 0.0, t.field); - if let Some(h) = &cx.hist { - tone::draw_histogram(&p, graph, &h[hist_i], Color32::from_gray(if t.pro { 88 } else { 190 }).gamma_multiply(0.75)); - } - for i in 1..4 { - let f = i as f32 / 4.0; - let g = Stroke::new(1.0, t.separator); - p.line_segment([pos2(graph.left() + f * graph.width(), graph.top()), pos2(graph.left() + f * graph.width(), graph.bottom())], g); - p.line_segment([pos2(graph.left(), graph.top() + f * graph.height()), pos2(graph.right(), graph.top() + f * graph.height())], g); - } - p.line_segment([graph.left_bottom(), graph.right_top()], Stroke::new(1.0, t.separator.gamma_multiply(1.6))); - p.rect_stroke( - graph, - 0.0, - Stroke::new(if resp.has_focus() { 1.5 } else { 1.0 }, if resp.has_focus() { t.accent } else { t.field_border }), - StrokeKind::Outside, - ); - let hbar = Rect::from_min_max(pos2(graph.left(), graph.bottom() + 4.0), pos2(graph.right(), graph.bottom() + 12.0)); - let vbar = Rect::from_min_max(pos2(full.left(), graph.top()), pos2(full.left() + 8.0, graph.bottom())); - gradient_bar(&p, hbar, Color32::BLACK, bar_color(&chan, &t), false); - gradient_bar(&p, vbar, Color32::BLACK, bar_color(&chan, &t), true); - let draw_curve = |pts: &[[f32; 2]], color: Color32, width: f32| { - let cp: Vec = - pts.iter().map(|q| photocraft_doc::adjust::CurvePoint { input: q[0] / 255.0, output: q[1] / 255.0 }).collect(); - let lut = photocraft_compose::adjust::curve_lut(&cp); - let n = lut.len().max(2); - let line: Vec = - (0..n).step_by((n / 256).max(1)).map(|i| to_scr([i as f32 / (n - 1) as f32 * 255.0, lut.get(i).copied().unwrap_or(0.0) * 255.0])).collect(); - p.add(egui::Shape::line(line, Stroke::new(width, color))); - }; - let draw_map = |map: &[f32], color: Color32, width: f32| { - let last = map.len().saturating_sub(1).max(1) as f32; - let line: Vec = map.iter().enumerate().map(|(k, o)| to_scr([k as f32 / last * 255.0, *o])).collect(); - p.add(egui::Shape::line(line, Stroke::new(width, color))); - }; - if overlay_others && ch == 0 { - // Photoshop overlays the edited channel curves on the composite. - for c in chans.iter().skip(1) { - if pencil { - let m = read_map(v, c.key); - if m.iter().enumerate().any(|(k, o)| (o - k as f32).abs() > 0.5) { - draw_map(&m, bar_color(c, &t).gamma_multiply(0.8), 1.0); - } - continue; - } - let cp = read_curve(v, c.key); - if cp.len() > 2 || cp.first().is_some_and(|q| q[1] != 0.0) || cp.last().is_some_and(|q| q[1] != 255.0) { - draw_curve(&cp, bar_color(c, &t).gamma_multiply(0.8), 1.0); - } - } - } - let color = if tinted { bar_color(&chan, &t) } else { t.text }; - if pencil { - draw_map(&map, color, 1.5); - } else { - draw_curve(&pts, color, 1.5); - } - for (i, q) in pts.iter().enumerate().filter(|_| !pencil) { - let r = Rect::from_center_size(to_scr(*q), vec2(CURVE_HANDLE_SIZE, CURVE_HANDLE_SIZE)); - if Some(i) == st.gesture.selected { - p.rect_filled(r, 0.0, t.text); - p.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::BLACK), StrokeKind::Outside); - } else { - p.rect_filled(r, 0.0, t.field); - p.rect_stroke(r, 0.0, Stroke::new(1.0, t.text), StrokeKind::Inside); - } - } - - // Input / Output of the selected point. - ui.add_space(6.0); - ui.horizontal(|ui| { - let i = st.gesture.selected.filter(|i| *i < pts.len() && !pencil); - let (mut vi, mut vo) = i.map_or((0.0, 0.0), |i| (pts[i][0], pts[i][1])); - label(ui, tl!("Input:")); - let ri = ui.add_enabled_ui(i.is_some(), |ui| widgets::value_field(ui, &mut vi, 0.0..=255.0, "", 52.0).accessible_name(tl!("Input:"))).inner; - label(ui, tl!("Output:")); - let ro = ui.add_enabled_ui(i.is_some(), |ui| widgets::value_field(ui, &mut vo, 0.0..=255.0, "", 52.0).accessible_name(tl!("Output:"))).inner; - if let Some(i) = i - && (ri.changed() || ro.changed()) - && curve_edit::move_to(&mut pts, i, [vi, vo]) - { - changed = true; - e.commit |= !(ri.dragged() || ro.dragged()); - } - if ri.drag_stopped() || ro.drag_stopped() { - e.commit = true; - } - }); - let t2 = Tokens::get(ui.ctx()); - let hint = if pencil { - crate::i18n::fmt(tl!("Drag to draw the curve · {key}-click draws a straight line"), &[("key", &crate::shortcuts::pretty("Shift"))]) - } else { - crate::i18n::fmt(tl!("Click to add a point · drag off or {key}-click or Delete to remove"), &[("key", &crate::shortcuts::pretty("Cmd"))]) - }; - ui.label(RichText::new(hint).color(t2.text_faint).size(11.0)); - ui.data_mut(|d| d.insert_temp(state_id, st)); - if drawn { - write_map(v, key, &map); - if space == ToneSpace::Lab - && let Some(o) = v.as_object_mut() - { - o.remove("points"); - } - e.changed = true; - } - if changed && !pencil { - v[key] = json!(pts.iter().map(|q| [q[0].round(), q[1].round()]).collect::>()); - if space == ToneSpace::Lab { - // Lab has no composite: "points" would alias lightness. - if let Some(o) = v.as_object_mut() { - o.remove("points"); - } - } - e.changed = true; - } - e -} - -// --------------------------------------------------------------------------------------------- -// Levels - -type Lv = [f32; 5]; // in_black, gamma, in_white, out_black, out_white (0–255, gamma as is) - -fn read_levels(v: &Value, key: &str) -> Lv { - let o = if key.is_empty() { Some(v) } else { v.get(key) }; - let g = |k: &str, d: f32| o.and_then(|o| o.get(k)).and_then(Value::as_f64).map_or(d, |x| x as f32); - [g("inBlack", 0.0), g("gamma", 1.0), g("inWhite", 255.0), g("outBlack", 0.0), g("outWhite", 255.0)] -} - -fn write_levels(v: &mut Value, key: &str, l: &Lv) { - let obj = json!({"inBlack": l[0].round(), "gamma": round(l[1], 0.01), "inWhite": l[2].round(), "outBlack": l[3].round(), "outWhite": l[4].round()}); - if key.is_empty() { - if let (Some(dst), Value::Object(src)) = (v.as_object_mut(), obj) { - dst.extend(src); - } - } else { - v[key] = obj; - } -} - -/// A triangular slider handle below a bar. -fn handle(p: &egui::Painter, x: f32, y: f32, fill: Color32, stroke: Color32) { - p.add(egui::Shape::convex_polygon(vec![pos2(x, y), pos2(x + 5.5, y + 9.0), pos2(x - 5.5, y + 9.0)], fill, Stroke::new(1.0, stroke))); -} - -/// Input level (0–255) where the gamma slider sits: the input that maps to 50% grey. -pub fn gamma_pos(black: f32, white: f32, gamma: f32) -> f32 { - black + (white - black) * 0.5f32.powf(gamma) -} - -pub fn gamma_from_pos(black: f32, white: f32, x: f32) -> f32 { - let t = ((x - black) / (white - black).max(1.0)).clamp(0.01, 0.99); - (t.ln() / 0.5f32.ln()).clamp(0.01, 9.99) -} - -/// Black and white input levels clipping 0.1 % at each end of `h` (Photoshop's Auto). -pub fn auto_levels(h: &[u32; 256]) -> (f32, f32) { - let total: u64 = h.iter().map(|x| u64::from(*x)).sum(); - let clip = total / 1000; - let (mut acc, mut lo) = (0u64, 0usize); - while lo < 253 && acc + u64::from(h[lo]) <= clip { - acc += u64::from(h[lo]); - lo += 1; - } - let (mut acc, mut hi) = (0u64, 255usize); - while hi > lo + 2 && acc + u64::from(h[hi]) <= clip { - acc += u64::from(h[hi]); - hi -= 1; - } - (lo as f32, hi as f32) -} - -/// Which handle of a slider row a press at `x` grabs (nearest), among `xs`. -fn nearest(xs: &[f32], x: f32) -> Option { - xs.iter().enumerate().min_by(|a, b| (a.1 - x).abs().total_cmp(&(b.1 - x).abs())).map(|(i, _)| i as u8) -} - -fn levels(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { - let t = Tokens::get(ui.ctx()); - let chans = tone_channels(space_of(v), cx.gray); - let mut ch = 0; - let mut auto = false; - ui.horizontal(|ui| { - ch = channel_picker(ui, cx.mem.with("levels-ch"), chans, tl!("Channel:")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - auto = widgets::secondary_button(ui, tl!("Auto"), 0.0).clicked(); - }); - }); - let chan = chans.get(ch).copied().unwrap_or(ToneChannel { key: "", label: "" }); - let mut l = read_levels(v, chan.key); - let mut e = Edit::default(); - let mut changed = false; - if auto && let Some(h) = &cx.hist { - let (lo, hi) = auto_levels(&h[ch]); - l[0] = lo; - l[2] = hi; - l[1] = 1.0; - changed = true; - e.commit = true; - } - let w = ui.available_width().min(300.0); - // Histogram. - let (hr, _) = ui.allocate_exact_size(vec2(w, 110.0), Sense::hover()); - let hr = hr.shrink2(vec2(6.0, 0.0)); - let p = ui.painter_at(hr.expand(1.0)); - p.rect_filled(hr, 0.0, t.field); - if let Some(h) = &cx.hist { - tone::draw_histogram(&p, hr, &h[ch], hist_color(&chan, &t)); - } - p.rect_stroke(hr, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside); - // Input sliders: black, gamma, white. - let (sr, sresp) = ui.allocate_exact_size(vec2(w, 14.0), Sense::click_and_drag()); - let track = sr.shrink2(vec2(6.0, 0.0)); - let xpos = |val: f32| track.left() + val / 255.0 * track.width(); - let xval = |x: f32| ((x - track.left()) / track.width() * 255.0).clamp(0.0, 255.0); - let drag_id = cx.mem.with("levels-drag"); - let mut which: Option = ui.data(|d| d.get_temp(drag_id)).flatten(); - let ctx = ui.ctx().clone(); - let pressed = |r: &egui::Response| r.is_pointer_button_down_on() && ctx.input(|i| i.pointer.primary_pressed()); - if pressed(&sresp) - && let Some(pos) = ui.input(|i| i.pointer.press_origin()) - { - which = nearest(&[xpos(l[0]), xpos(gamma_pos(l[0], l[2], l[1])), xpos(l[2])], pos.x); - } - if sresp.is_pointer_button_down_on() - && let (Some(k), Some(pos)) = (which, ui.input(|i| i.pointer.interact_pos())) - { - let x = xval(pos.x); - let before = l; - match k { - 0 => l[0] = x.min(l[2] - 2.0).round(), - 2 => l[2] = x.max(l[0] + 2.0).round(), - _ => l[1] = round(gamma_from_pos(l[0], l[2], x), 0.01), - } - changed |= l != before; - } - if which.is_some() && !sresp.is_pointer_button_down_on() { - which = None; - e.commit = true; - } - ui.data_mut(|d| d.insert_temp(drag_id, which)); - let sp = ui.painter_at(sr.expand(6.0)); - handle(&sp, xpos(l[0]), sr.top() + 2.0, Color32::BLACK, t.text_dim); - handle(&sp, xpos(gamma_pos(l[0], l[2], l[1])), sr.top() + 2.0, Color32::from_gray(128), t.text_dim); - handle(&sp, xpos(l[2]), sr.top() + 2.0, Color32::WHITE, t.text_dim); - ui.horizontal(|ui| { - let fw = ((w - 16.0) / 3.0).min(70.0); - let (mut nb, mut ng, mut nw) = (l[0], l[1], l[2]); - let gap = ((w - 3.0 * fw) / 2.0 - 12.0).max(0.0); - let r0 = widgets::value_field(ui, &mut nb, 0.0..=253.0, "", fw).accessible_name(tl!("Black")); - ui.add_space(gap); - let r1 = widgets::value_field(ui, &mut ng, 0.01..=9.99, "", fw).accessible_name(tl!("Gamma")); - ui.add_space(gap); - let r2 = widgets::value_field(ui, &mut nw, 2.0..=255.0, "", fw).accessible_name(tl!("White")); - if r0.changed() { - l[0] = nb.round().min(l[2] - 2.0); - } - if r1.changed() { - l[1] = round(ng.clamp(0.01, 9.99), 0.01); - } - if r2.changed() { - l[2] = nw.round().max(l[0] + 2.0); - } - for r in [&r0, &r1, &r2] { - changed |= r.changed(); - e.add(Edit::of(r)); - } - }); - // Output levels. - ui.add_space(6.0); - label(ui, tl!("Output Levels:")); - let (ob_r, _) = ui.allocate_exact_size(vec2(w, 10.0), Sense::hover()); - gradient_bar(ui.painter(), ob_r.shrink2(vec2(6.0, 0.0)), Color32::BLACK, bar_color(&chan, &t), false); - let (or, oresp) = ui.allocate_exact_size(vec2(w, 14.0), Sense::click_and_drag()); - let otrack = or.shrink2(vec2(6.0, 0.0)); - let oxpos = |val: f32| otrack.left() + val / 255.0 * otrack.width(); - let oval = |x: f32| ((x - otrack.left()) / otrack.width() * 255.0).clamp(0.0, 255.0); - let odrag_id = cx.mem.with("levels-odrag"); - let mut owhich: Option = ui.data(|d| d.get_temp(odrag_id)).flatten(); - if pressed(&oresp) - && let Some(pos) = ui.input(|i| i.pointer.press_origin()) - { - owhich = nearest(&[oxpos(l[3]), oxpos(l[4])], pos.x); - } - if oresp.is_pointer_button_down_on() - && let (Some(k), Some(pos)) = (owhich, ui.input(|i| i.pointer.interact_pos())) - { - let slot = if k == 0 { 3 } else { 4 }; - let nv = oval(pos.x).round(); - changed |= l[slot] != nv; - l[slot] = nv; - } - if owhich.is_some() && !oresp.is_pointer_button_down_on() { - owhich = None; - e.commit = true; - } - ui.data_mut(|d| d.insert_temp(odrag_id, owhich)); - let op = ui.painter_at(or.expand(6.0)); - handle(&op, oxpos(l[3]), or.top() + 2.0, Color32::BLACK, t.text_dim); - handle(&op, oxpos(l[4]), or.top() + 2.0, Color32::WHITE, t.text_dim); - ui.horizontal(|ui| { - let fw = ((w - 16.0) / 3.0).min(70.0); - let (mut a, mut c) = (l[3], l[4]); - let ra = widgets::value_field(ui, &mut a, 0.0..=255.0, "", fw).accessible_name(tl!("Black")); - ui.add_space((w - 2.0 * fw - 16.0).max(0.0)); - let rc = widgets::value_field(ui, &mut c, 0.0..=255.0, "", fw).accessible_name(tl!("White")); - if ra.changed() { - l[3] = a.round(); - } - if rc.changed() { - l[4] = c.round(); - } - for r in [&ra, &rc] { - changed |= r.changed(); - e.add(Edit::of(r)); - } - }); - if changed { - write_levels(v, chan.key, &l); - e.changed = true; - } - e -} - -// --------------------------------------------------------------------------------------------- -// Threshold - -fn threshold(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { - let t = Tokens::get(ui.ctx()); - let w = ui.available_width().min(300.0); - let (hr, _) = ui.allocate_exact_size(vec2(w, 90.0), Sense::hover()); - let hr = hr.shrink2(vec2(6.0, 0.0)); - let p = ui.painter_at(hr.expand(1.0)); - p.rect_filled(hr, 0.0, t.field); - if let Some(h) = &cx.hist { - tone::draw_histogram(&p, hr, &h[0], Color32::from_gray(if t.pro { 150 } else { 110 })); - } - let level = num(v, "level", 128.0); - let x = hr.left() + level / 255.0 * hr.width(); - p.line_segment([pos2(x, hr.top()), pos2(x, hr.bottom())], Stroke::new(1.0, t.accent)); - p.rect_stroke(hr, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside); - ui.add_space(4.0); - sliders(ui, v, &[("level", tl!("Threshold Level"), 1.0, 255.0, 128.0, "", None)]) -} - -// --------------------------------------------------------------------------------------------- -// Hue/Saturation - -const RANGE_LABELS: [&str; 6] = ["Reds", "Yellows", "Greens", "Cyans", "Blues", "Magentas"]; - -/// The Saturation slider's track: grey to the hue at full saturation (UI-217-16). -fn saturation_track(hue_deg: f32) -> [Color32; 2] { - [Color32::from_gray(128), hue_color(hue_deg)] -} - -/// The Lightness slider's track: black, mid grey, white, whatever the hue, as in Photoshop -/// (UI-217-16, #6539). -fn lightness_track() -> [Color32; 3] { - [Color32::BLACK, Color32::from_gray(128), Color32::WHITE] -} - -fn move_hue_range_handle(bounds: [f32; 4], k: usize, deg: f32) -> [f32; 4] { - let mut b = HueRange::canonical_bounds(bounds); - if k >= b.len() { - return b; - } - if k == 0 { - let delta = (deg - b[0] + 180.0).rem_euclid(360.0) - 180.0; - b[0] = (b[0] + delta).min(b[1]).max(b[1] - 180.0); - } else { - let rel = (deg - b[0]).rem_euclid(360.0); - let hi = if k == 3 { b[0] + 359.0 } else { b[k + 1] }; - b[k] = (b[0] + rel).clamp(b[k - 1], hi); - } - b -} - -/// 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); - let rect = photocraft_geom::Rect::new(0, 0, n as i32, 1); - let px = (0..n) - .map(|i| { - let c = photocraft_color::convert::hsb_to_rgb([i as f32 / (n - 1).max(1) as f32 * 360.0, 1.0, 1.0]); - [c[0], c[1], c[2], 1.0] - }) - .collect(); - let mut buf = photocraft_compose::Buffer { rect, px }; - photocraft_compose::adjust::apply(&adj, &mut buf); - buf.px.iter().map(|p| color32([p[0], p[1], p[2]])).collect() -} - -fn spectrum_bar(p: &egui::Painter, r: Rect, colors: &[Color32]) { - let n = colors.len().saturating_sub(1).max(1); - for (i, w) in colors.windows(2).enumerate() { - let x0 = r.left() + r.width() * i as f32 / n as f32; - let x1 = r.left() + r.width() * (i + 1) as f32 / n as f32; - gradient_bar(p, Rect::from_min_max(pos2(x0, r.top()), pos2(x1, r.bottom())), w[0], w[1], false); - } -} - -fn hue_saturation(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { - let t = Tokens::get(ui.ctx()); - let range_id = cx.mem.with("hs-range"); - let mut range: usize = ui.data(|d| d.get_temp(range_id)).unwrap_or(0); - let colorize = flag(v, "colorize", false); - if colorize { - range = 0; - } - ui.horizontal(|ui| { - let opts: Vec<(usize, &str)> = std::iter::once((0, tl!("Master"))).chain(RANGE_LABELS.iter().enumerate().map(|(i, l)| (i + 1, *l))).collect(); - ui.add_enabled_ui(!colorize, |ui| widgets::dropdown(ui, &format!("{range_id:?}"), tl!("Range"), &mut range, &opts, 120.0)); - }); - ui.data_mut(|d| d.insert_temp(range_id, range)); - let mut e = Edit::default(); - let hue_grad = widgets::hue_stops(); - if range == 0 { - let (hlo, hhi, slo) = if colorize { (0.0, 360.0, 0.0) } else { (-180.0, 180.0, -100.0) }; - let mut h = num(v, "hue", 0.0).clamp(hlo, hhi); - let r = widgets::slider_row(ui, tl!("Hue"), &mut h, hlo..=hhi, "°", track_stops(cx, &hue_grad)); - if r.changed() { - v["hue"] = json!(h.round()); - } - e.add(Edit::of(&r)); - // The Saturation track follows the current hue; the Lightness track is a fixed - // black-grey-white ramp, as in Photoshop (UI-217-16). - let sat_track = saturation_track(h); - let mut s = num(v, "saturation", 0.0).clamp(slo, 100.0); - let r = widgets::slider_row(ui, tl!("Saturation"), &mut s, slo..=100.0, "%", track_stops(cx, &sat_track)); - if r.changed() { - v["saturation"] = json!(s.round()); - } - e.add(Edit::of(&r)); - let light_track = lightness_track(); - let mut l = num(v, "lightness", 0.0).clamp(-100.0, 100.0); - let r = widgets::slider_row(ui, tl!("Lightness"), &mut l, -100.0..=100.0, "%", track_stops(cx, &light_track)); - if r.changed() { - v["lightness"] = json!(l.round()); - } - e.add(Edit::of(&r)); - } else { - let key = HUE_RANGES[range - 1]; - if !v.get(key).is_some_and(Value::is_object) { - v[key] = json!({}); - } - let mut o = v[key].clone(); - let mut sub = Edit::default(); - let mut h = num(&o, "hue", 0.0); - let r = widgets::slider_row(ui, tl!("Hue"), &mut h, -180.0..=180.0, "°", track_stops(cx, &hue_grad)); - if r.changed() { - o["hue"] = json!(h.round()); - } - sub.add(Edit::of(&r)); - sub.add(sliders( - ui, - &mut o, - &[("saturation", tl!("Saturation"), -100.0, 100.0, 0.0, "%", None), ("lightness", tl!("Lightness"), -100.0, 100.0, 0.0, "%", None)], - )); - if sub.changed { - v[key] = o; - } - e.add(sub); - } - let mut c = colorize; - if widgets::checkbox(ui, &mut c, tl!("Colorize")).changed() { - v["colorize"] = json!(c); - let h = num(v, "hue", 0.0); - v["hue"] = json!(if c { - h.rem_euclid(360.0) - } else if h > 180.0 { - h - 360.0 - } else { - h - }); - if c { - v["saturation"] = json!(num(v, "saturation", 25.0).max(0.0).max(25.0)); - } - e.add(Edit::discrete(true)); - } - // Spectrum bars: input hues above, adjusted below; the selected range's sliders between. - ui.add_space(6.0); - // As wide as the sliders above, whatever the panel's width (#9242). - let w = ui.available_width(); - let (bars, bresp) = ui.allocate_exact_size(vec2(w, 40.0), Sense::click_and_drag()); - ui.data_mut(|d| d.insert_temp(cx.mem.with("hs-bars"), bars)); - let top = Rect::from_min_size(bars.min, vec2(w, 10.0)); - let bottom = Rect::from_min_size(pos2(bars.left(), bars.bottom() - 10.0), vec2(w, 10.0)); - let p = ui.painter_at(bars.expand(4.0)); - let input: Vec = (0..=36).map(|i| hue_color(i as f32 * 10.0)).collect(); - spectrum_bar(&p, top, &input); - spectrum_bar(&p, bottom, &adjusted_spectrum(v, 37)); - if range > 0 { - let key = HUE_RANGES[range - 1]; - let neutral = photocraft_doc::adjust::HueRange::neutral(range - 1).bounds; - let mut b = HueRange::canonical_bounds(nums(&v[key], "range", neutral)); - let xof = |deg: f32| bars.left() + deg.rem_euclid(360.0) / 360.0 * w; - let deg_of = |x: f32| ((x - bars.left()) / w * 360.0).clamp(0.0, 360.0); - let mid = bars.center().y; - // Range band (fully affected) and fall-off. - let band = |a: f32, z: f32, color: Color32| { - let (xa, xz) = (xof(a), xof(z)); - if xa <= xz { - p.rect_filled(Rect::from_min_max(pos2(xa, mid - 3.0), pos2(xz, mid + 3.0)), 0.0, color); - } else { - p.rect_filled(Rect::from_min_max(pos2(xa, mid - 3.0), pos2(bars.right(), mid + 3.0)), 0.0, color); - p.rect_filled(Rect::from_min_max(pos2(bars.left(), mid - 3.0), pos2(xz, mid + 3.0)), 0.0, color); - } - }; - band(b[0], b[3], t.text_faint); - band(b[1], b[2], t.text_dim); - for (k, d) in b.iter().enumerate() { - let x = xof(*d); - let fill = if k == 1 || k == 2 { t.text } else { t.field }; - 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); - } - let drag_id = cx.mem.with("hs-range-drag"); - let mut which: Option = ui.data(|d| d.get_temp(drag_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); - } - if bresp.is_pointer_button_down_on() - && let (Some(k), Some(pos)) = (which, ui.input(|i| i.pointer.interact_pos())) - { - let k = k as usize; - let deg = deg_of(pos.x); - let before = b; - b = move_hue_range_handle(b, k, deg); - if b != before { - v[key]["range"] = json!(b.map(|x| x.round())); - e.changed = true; - } - } - if which.is_some() && !bresp.is_pointer_button_down_on() { - which = None; - e.commit = true; - } - ui.data_mut(|d| d.insert_temp(drag_id, which)); - let lab = - format!("{:.0}° / {:.0}° · {:.0}° \\ {:.0}°", b[0].rem_euclid(360.0), b[1].rem_euclid(360.0), b[2].rem_euclid(360.0), b[3].rem_euclid(360.0)); - ui.label(RichText::new(lab).font(crate::theme::mono(11.0)).color(t.text_faint)); - } - e -} - -// --------------------------------------------------------------------------------------------- -// Color Balance - -/// Where the Color Balance editor rooted at `mem` keeps its Tone choice. -fn color_balance_tone_id(mem: egui::Id) -> egui::Id { - mem.with("cb-tone") -} - -/// Photoshop's Color Balance reset to defaults (Alt+Cancel in the dialog; the Properties panel's -/// Reset once the layer is as the panel found it): every tone back to 0 and the Tone choice back -/// to Midtones; Preserve Luminosity stays as it is. -pub fn reset_color_balance(ctx: &egui::Context, mem: egui::Id, v: &mut Value) { - for key in ["shadows", "midtones", "highlights"] { - v[key] = json!([0.0, 0.0, 0.0]); - } - ctx.data_mut(|d| d.insert_temp(color_balance_tone_id(mem), 1usize)); -} - -/// Kind-specific editor memory after Alt+Reset (or Properties Reset to defaults). Color Balance -/// shows Midtones; other kinds have no dialog-local temp to clear yet. -pub fn reset_adjustment_editor(ctx: &egui::Context, kind: &str, mem: egui::Id, v: &mut Value) { - if kind == "colorBalance" { - reset_color_balance(ctx, mem, v); - } -} - -fn color_balance(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { - let tone_id = color_balance_tone_id(cx.mem); - let mut tone_ix: usize = ui.data(|d| d.get_temp(tone_id)).unwrap_or(1); - ui.horizontal(|ui| { - label(ui, tl!("Tone:")); - for (i, l) in [tl!("Shadows"), tl!("Midtones"), tl!("Highlights")].iter().enumerate() { - if ui.radio(tone_ix == i, *l).clicked() { - tone_ix = i; - } - } - }); - ui.data_mut(|d| d.insert_temp(tone_id, tone_ix)); - let key = ["shadows", "midtones", "highlights"][tone_ix.min(2)]; - let mut vals = nums(v, key, [0.0; 3]); - let mut e = Edit::default(); - let rows = [ - (tl!("Cyan · Red"), Color32::from_rgb(0, 190, 210), Color32::from_rgb(225, 40, 40)), - (tl!("Magenta · Green"), Color32::from_rgb(210, 40, 190), Color32::from_rgb(40, 190, 60)), - (tl!("Yellow · Blue"), Color32::from_rgb(230, 210, 30), Color32::from_rgb(40, 80, 230)), - ]; - // Photoshop: a double-click on a slider zeroes it (this tone only); the dialog's sliders step - // with the wheel; Up/Down step the fields; Shift makes those steps 10. - let gestures = widgets::RowGestures { reset: Some(0.0), wheel_step: cx.dialog.then_some(1.0), ..Default::default() }; - let mut changed = false; - for (i, (text, a, b)) in rows.iter().enumerate() { - let r = Edit::of(&widgets::slider_row_with(ui, text, &mut vals[i], -100.0..=100.0, "", Some(&[*a, *b]), gestures)); - changed |= r.changed; - e.add(r); - } - if changed { - v[key] = json!(vals.map(f32::round)); - } - let mut pl = flag(v, "preserveLuminosity", true); - if widgets::checkbox(ui, &mut pl, tl!("Preserve Luminosity")).changed() { - v["preserveLuminosity"] = json!(pl); - e.add(Edit::discrete(true)); - } - e -} - -// --------------------------------------------------------------------------------------------- -// Black & White - -fn black_white(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { - let mut e = Edit::default(); - let colors = [[230, 50, 50], [235, 215, 40], [50, 200, 70], [40, 200, 220], [50, 90, 235], [220, 50, 210]]; - for (i, key) in HUE_RANGES.iter().enumerate() { - let mut x = num(v, key, adjust_params::BW_DEFAULTS[i]).clamp(-200.0, 300.0); - let c = colors[i]; - let r = - gradient_slider(ui, RANGE_LABELS[i], &mut x, -200.0..=300.0, "%", [Color32::BLACK, Color32::from_rgb(c[0], c[1], c[2])], cx.dynamic_color_sliders); - if r.changed { - v[*key] = json!(x.round()); - } - e.add(r); - } - ui.add_space(2.0); - ui.horizontal(|ui| { - let mut on = flag(v, "tint", false); - if widgets::checkbox(ui, &mut on, tl!("Tint")).changed() { - v["tint"] = json!(on); - e.add(Edit::discrete(true)); - } - let mut c = rgb_of(v, "tintColor", [0.882, 0.827, 0.702]); - let r = ui.add_enabled_ui(on, |ui| color_button(ui, &mut c)).inner; - if r.changed { - v["tintColor"] = json!(adjust_params::hex(c)); - } - e.add(r); - if widgets::secondary_button(ui, tl!("Default"), 0.0).clicked() { - for (i, key) in HUE_RANGES.iter().enumerate() { - v[*key] = json!(adjust_params::BW_DEFAULTS[i]); - } - e.add(Edit::discrete(true)); - } - }); - e -} - -// --------------------------------------------------------------------------------------------- -// Photo Filter - -fn photo_filter(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { - let mut e = Edit::default(); - let mut c = rgb_of(v, "color", [236.0 / 255.0, 138.0 / 255.0, 0.0]); - let hex = adjust_params::hex(c); - let preset = PHOTO_FILTERS.iter().find(|f| adjust_params::hex(f.2.map(|x| f32::from(x) / 255.0)) == hex).map(|f| f.0); - let mode_id = cx.mem.with("pf-mode"); - let mut use_color: bool = ui.data(|d| d.get_temp(mode_id)).unwrap_or(preset.is_none()); - ui.horizontal(|ui| { - if ui.radio(!use_color, tl!("Filter:")).clicked() { - use_color = false; - } - let mut sel = preset.unwrap_or("custom").to_string(); - let mut opts: Vec<(String, &str)> = PHOTO_FILTERS.iter().map(|f| (f.0.to_string(), f.1)).collect(); - if preset.is_none() { - opts.insert(0, ("custom".into(), "Custom")); - } - let changed = ui.add_enabled_ui(!use_color, |ui| widgets::dropdown(ui, &format!("{mode_id:?}-filter"), tl!("Filter:"), &mut sel, &opts, 170.0)).inner; - if changed && let Some(f) = PHOTO_FILTERS.iter().find(|f| f.0 == sel) { - c = f.2.map(|x| f32::from(x) / 255.0); - v["color"] = json!(adjust_params::hex(c)); - e.add(Edit::discrete(true)); - } - }); - ui.horizontal(|ui| { - if ui.radio(use_color, tl!("Color:")).clicked() { - use_color = true; - } - let r = ui.add_enabled_ui(use_color, |ui| color_button(ui, &mut c)).inner; - if r.changed { - v["color"] = json!(adjust_params::hex(c)); - } - e.add(r); - }); - ui.data_mut(|d| d.insert_temp(mode_id, use_color)); - e.add(sliders(ui, v, &[("density", tl!("Density"), 0.0, 100.0, 25.0, "%", None)])); - let mut pl = flag(v, "preserveLuminosity", true); - if widgets::checkbox(ui, &mut pl, tl!("Preserve Luminosity")).changed() { - v["preserveLuminosity"] = json!(pl); - e.add(Edit::discrete(true)); - } - e -} - -// --------------------------------------------------------------------------------------------- -// Channel Mixer - -fn channel_mixer(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { - let t = Tokens::get(ui.ctx()); - let mono = flag(v, "monochrome", false); - let out_id = cx.mem.with("cm-out"); - let mut out: usize = ui.data(|d| d.get_temp(out_id)).unwrap_or(0); - let outs: &[(usize, &str)] = if mono { &[(0, tl!("Gray"))] } else { &[(0, tl!("Red")), (1, tl!("Green")), (2, tl!("Blue"))] }; - if out >= outs.len() { - out = 0; - } - ui.horizontal(|ui| { - label(ui, tl!("Output Channel:")); - widgets::dropdown(ui, &format!("{out_id:?}"), tl!("Output Channel:"), &mut out, outs, 110.0); - }); - ui.data_mut(|d| d.insert_temp(out_id, out)); - let key = if mono { "gray" } else { ["red", "green", "blue"][out] }; - let identity: [f32; 4] = if mono { [40.0, 40.0, 20.0, 0.0] } else { std::array::from_fn(|i| if i == out { 100.0 } else { 0.0 }) }; - let mut row = nums(v, key, if mono { nums(v, "red", identity) } else { identity }); - let mut e = Edit::default(); - let mut changed = false; - for (i, (text, c)) in [(tl!("Red"), [225, 50, 50]), (tl!("Green"), [50, 190, 70]), (tl!("Blue"), [60, 100, 235])].iter().enumerate() { - let r = gradient_slider(ui, text, &mut row[i], -200.0..=200.0, "%", [Color32::BLACK, Color32::from_rgb(c[0], c[1], c[2])], cx.dynamic_color_sliders); - changed |= r.changed; - e.add(r); - } - let total = row[0] + row[1] + row[2]; - ui.horizontal(|ui| { - label(ui, tl!("Total:")); - let warn = total > 100.0; - ui.label(RichText::new(format!("{total:+.0}%")).font(crate::theme::mono(12.0)).color(if warn { t.warning } else { t.text })); - }); - let r = widgets::slider_row(ui, tl!("Constant"), &mut row[3], -200.0..=200.0, "%", None); - changed |= r.changed(); - e.add(Edit::of(&r)); - if changed { - v[key] = json!(row.map(f32::round)); - } - let mut m = mono; - if widgets::checkbox(ui, &mut m, tl!("Monochrome")).changed() { - v["monochrome"] = json!(m); - if m { - v["gray"] = json!([40.0, 40.0, 20.0, 0.0]); - } else if let Some(o) = v.as_object_mut() { - o.remove("gray"); - } - e.add(Edit::discrete(true)); - } - e -} - -// --------------------------------------------------------------------------------------------- -// Gradient Map - -type Stop = (f32, [f32; 3]); - -fn read_stops(v: &Value) -> Vec { - let mut s: Vec = v - .get("stops") - .and_then(Value::as_array) - .map(|a| { - a.iter() - .filter_map(|s| { - let p = s.as_array()?; - let t = p.first()?.as_f64()? as f32; - let c = rgb_of(&json!({"c": p.get(1)?.clone()}), "c", [0.0; 3]); - Some((t.clamp(0.0, 1.0), c)) - }) - .collect() - }) - .unwrap_or_default(); - if s.len() < 2 { - s = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]; - } - s -} - -fn write_stops(v: &mut Value, s: &[Stop]) { - let mut s = s.to_vec(); - s.sort_by(|a, b| a.0.total_cmp(&b.0)); - v["stops"] = json!(s.iter().map(|(t, c)| json!([round(*t, 0.001), adjust_params::hex(*c)])).collect::>()); -} - -fn sample_stops(s: &[Stop], t: f32) -> [f32; 3] { - let mut sorted = s.to_vec(); - sorted.sort_by(|a, b| a.0.total_cmp(&b.0)); - let Some(first) = sorted.first() else { return [t; 3] }; - if t <= first.0 { - return first.1; - } - for w in sorted.windows(2) { - if t <= w[1].0 { - let k = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 }; - return std::array::from_fn(|i| w[0].1[i] + (w[1].1[i] - w[0].1[i]) * k); - } - } - sorted.last().map_or([t; 3], |l| l.1) -} - -#[derive(Clone, Copy)] -struct MapStopDrag { - index: usize, - offset: f32, - changed: bool, -} - -/// Keep selection on the same stop when it crosses another stop (including coincident stops). -fn move_map_stop(stops: &mut [Stop], index: usize, location: f32) -> Option { - let stop = stops.get_mut(index)?; - stop.0 = round(location.clamp(0.0, 1.0), 0.001); - let location = stop.0; - let rank = stops.iter().enumerate().filter(|(i, s)| *i != index && (s.0 < location || (s.0 == location && *i < index))).count(); - stops.sort_by(|a, b| a.0.total_cmp(&b.0)); - Some(rank) -} - -fn gradient_map_strip(ui: &mut egui::Ui, stops: &mut Vec, cx: &EditorCx, selected: &mut usize) -> Edit { - let t = Tokens::get(ui.ctx()); - let key = cx.mem.with("gm-stop-drag"); - let mut edit = Edit::default(); - let w = ui.available_width().min(300.0); - let (outer, resp) = ui.allocate_exact_size(vec2(w, 44.0), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Gradient stops"))); - let bar = Rect::from_min_max(outer.min + vec2(8.0, 2.0), pos2(outer.right() - 8.0, outer.top() + 26.0)); - let x_of = |loc: f32| bar.left() + loc * bar.width(); - let loc_of = |x: f32| ((x - bar.left()) / bar.width().max(1.0)).clamp(0.0, 1.0); - let hit = - |pos: Pos2, stops: &[Stop]| stops.iter().enumerate().rev().find(|(_, s)| pos.y >= bar.bottom() && (x_of(s.0) - pos.x).abs() <= 6.0).map(|(i, _)| i); - if resp.drag_started() - && let Some(pos) = ui.input(|i| i.pointer.press_origin()) - && let Some(index) = hit(pos, stops) - { - *selected = index; - let offset = stops.get(index).map_or(0.0, |s| pos.x - x_of(s.0)); - ui.data_mut(|d| d.insert_temp(key, MapStopDrag { index, offset, changed: false })); - } - if let Some(mut drag) = ui.data(|d| d.get_temp::(key)) { - if (resp.dragged() || resp.drag_stopped()) - && let Some(pos) = resp.interact_pointer_pos() - { - let location = round(loc_of(pos.x - drag.offset), 0.001); - let changed = stops.get(drag.index).is_some_and(|s| s.0 != location); - if let Some(index) = move_map_stop(stops, drag.index, location) { - drag.index = index; - drag.changed |= changed; - *selected = index; - edit.changed |= changed; - } - } - if resp.drag_stopped() { - edit.commit = drag.changed; - ui.data_mut(|d| d.remove::(key)); - } else if ui.input(|i| i.pointer.primary_down()) { - ui.data_mut(|d| d.insert_temp(key, drag)); - } else { - ui.data_mut(|d| d.remove::(key)); - } - } - if resp.clicked() - && let Some(pos) = resp.interact_pointer_pos() - { - resp.request_focus(); - if let Some(index) = hit(pos, stops) { - *selected = index; - } else if stops.len() < 64 { - let at = round(loc_of(pos.x), 0.001); - let color = sample_stops(stops, at); - stops.push((at, color)); - let index = stops.len() - 1; - *selected = move_map_stop(stops, index, at).unwrap_or(0); - edit.add(Edit::discrete(true)); - } - } - if resp.hovered() && ui.input(|i| i.pointer.hover_pos()).is_some_and(|pos| hit(pos, stops).is_some()) || resp.dragged() { - ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); - } - // Markers address un-reversed locations, as in the Gradient Tool; Reverse changes the image. - let cols: Vec = (0..=48).map(|i| color32(sample_stops(stops, i as f32 / 48.0))).collect(); - spectrum_bar(ui.painter(), bar, &cols); - ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside); - for (i, (at, color)) in stops.iter().enumerate() { - let x = x_of(*at); - let border = if i == *selected { t.accent } else { t.text_dim }; - let body = Rect::from_center_size(pos2(x, bar.bottom() + 10.0), vec2(10.0, 10.0)); - ui.painter().add(egui::Shape::convex_polygon( - vec![pos2(x, bar.bottom() + 1.0), pos2(x + 5.0, body.top()), pos2(x - 5.0, body.top())], - border, - Stroke::NONE, - )); - ui.painter().rect_filled(body, 1.0, color32(*color)); - ui.painter().rect_stroke(body, 1.0, Stroke::new(1.0, border), StrokeKind::Outside); - } - edit -} - -fn gradient_map(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { - let t = Tokens::get(ui.ctx()); - let mut e = Edit::default(); - let mut stops = read_stops(v); - let selection = cx.mem.with("gm-stop-selection"); - let mut selected = ui.data(|d| d.get_temp::(selection)).unwrap_or(0).min(stops.len().saturating_sub(1)); - // Photoshop's gradient picker: the same library as the Gradient tool and Gradients panel - // (built-in groups and the user's own), Foreground/Background resolved to the current colours. - let [fg, bg] = cx.swatches.map(|c| [c[0], c[1], c[2], 1.0]); - ui.horizontal(|ui| { - label(ui, tl!("Preset:")); - let mut picked = None; - let (press, close) = crate::press_menu::PressCombo::before(ui, cx.mem.with("gm-preset")); - let combo = egui::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::>()); - } - }); - } - } - }); - press.after(&combo.response); - let _ = combo.response.accessible_name(tl!("Preset:")); - if let Some(p) = picked { - stops = p; - selected = 0; - ui.data_mut(|d| d.remove::(cx.mem.with("gm-stop-drag"))); - write_stops(v, &stops); - e.add(Edit::discrete(true)); - } - }); - let strip = gradient_map_strip(ui, &mut stops, cx, &mut selected); - let mut changed = strip.changed; - e.add(strip); - // The selected stop's colour and location, like the Gradient Tool's compact stop editor. - let mut location = None; - let mut remove = false; - let can_remove = stops.len() > 2; - if let Some(s) = stops.get_mut(selected) { - ui.horizontal(|ui| { - label(ui, tl!("Color:")); - let r = color_button(ui, &mut s.1); - changed |= r.changed; - e.add(r); - ui.add_enabled_ui(can_remove, |ui| { - remove = crate::icons::button(ui, "x", 20.0, false, tl!("Remove stop")).clicked(); - }); - }); - ui.horizontal(|ui| { - label(ui, tl!("Location:")); - let mut loc = s.0 * 100.0; - let rl = widgets::value_field(ui, &mut loc, 0.0..=100.0, "%", 70.0).accessible_name(tl!("Location:")); - if rl.changed() { - location = Some(loc / 100.0); - changed = true; - } - e.add(Edit::of(&rl)); - }); - } - if let Some(loc) = location { - selected = move_map_stop(&mut stops, selected, loc).unwrap_or(0); - } - if remove && can_remove { - stops.remove(selected); - selected = selected.min(stops.len() - 1); - changed = true; - e.add(Edit::discrete(true)); - } - if stops.len() < 64 && widgets::secondary_button(ui, tl!("Add Stop"), 0.0).clicked() { - // Halfway along the widest gap, in the gradient's colour there. - let mut sorted = stops.clone(); - sorted.sort_by(|a, b| a.0.total_cmp(&b.0)); - let at = sorted.windows(2).max_by(|a, b| (a[1].0 - a[0].0).total_cmp(&(b[1].0 - b[0].0))).map_or(0.5, |w| (w[0].0 + w[1].0) / 2.0); - stops.push((at, sample_stops(&stops, at))); - let index = stops.len() - 1; - selected = move_map_stop(&mut stops, index, at).unwrap_or(0); - changed = true; - e.add(Edit::discrete(true)); - } - if changed { - write_stops(v, &stops); - e.changed = true; - } - ui.data_mut(|d| d.insert_temp(selection, selected)); - ui.horizontal(|ui| { - for (key, text) in [("reverse", tl!("Reverse")), ("dither", tl!("Dither"))] { - let mut b = flag(v, key, false); - if widgets::checkbox(ui, &mut b, text).changed() { - v[key] = json!(b); - e.add(Edit::discrete(true)); - } - } - }); - e -} - -// --------------------------------------------------------------------------------------------- -// Hosts - -/// Whether a document of this mode edits Levels/Curves through a single Gray channel. -pub fn is_gray(mode: photocraft_doc::ColorMode) -> bool { - matches!(mode, photocraft_doc::ColorMode::Grayscale | photocraft_doc::ColorMode::Duotone | photocraft_doc::ColorMode::Bitmap) -} - -/// The gradient preset library for a `kind` editor's picker (Gradient Map only; empty otherwise). -pub fn gradient_presets(app: &PhotocraftApp, kind: &str) -> Vec> { - if kind == "gradientMap" { app.session.presets.gradients.clone() } else { Vec::new() } -} - -pub fn swatches(app: &PhotocraftApp) -> [[f32; 3]; 2] { - let c = |x: [f32; 4]| [x[0], x[1], x[2]]; - [c(app.session.tools.foreground), c(app.session.tools.background)] -} - -/// Root of an adjustment layer's Properties editor view state in egui memory. -pub fn layer_mem(id: LayerId) -> egui::Id { - egui::Id::unique(("adjust-layer", id.0)) -} - -/// Kinds whose Properties edits follow Photoshop's history and Reset (measured for Color Balance, -/// Photoshop 25.4): consecutive edits of the layer make one history step, and Reset first returns -/// to the settings the layer had when the panel started showing it. -fn photoshop_session(kind: &str) -> bool { - kind == "colorBalance" -} - -/// The `coalesce` key of a layer's Properties edits (one history step while they follow each -/// other, like Photoshop's "Modify … Layer"). -pub fn properties_coalesce(id: LayerId) -> String { - format!("properties-adjustment:{}", id.0) -} - -/// A layer's Properties session: document, last pass drawn, the settings the panel found, and -/// whether the panel edited them since (or since the last Reset). -type Session = (u64, u64, Value, bool); - -fn session_key(id: LayerId) -> egui::Id { - layer_mem(id).with("session") -} - -/// Remember the settings `id` (in document `doc`) had when the panel started showing it: kept -/// while it is drawn pass after pass, taken anew after a pass without it (another layer, -/// document or panel state shown). -fn track_session(ctx: &egui::Context, doc: u64, id: LayerId, committed: &Value) { - let pass = ctx.cumulative_pass_nr(); - let kept: Option = ctx.data(|d| d.get_temp(session_key(id))); - let (start, edited) = match kept { - Some((d, last, v, e)) if d == doc && last.saturating_add(1) >= pass => (v, e), - _ => (committed.clone(), false), - }; - ctx.data_mut(|d| d.insert_temp(session_key(id), (doc, pass, start, edited))); -} - -fn set_edited(ctx: &egui::Context, id: LayerId, edited: bool) { - let kept: Option = ctx.data(|d| d.get_temp(session_key(id))); - if let Some((doc, pass, start, _)) = kept { - ctx.data_mut(|d| d.insert_temp(session_key(id), (doc, pass, start, edited))); - } -} - -/// The settings layer `id` of document `doc` had when the Properties panel started showing it, -/// if the panel has edited them since (or since the last Reset). -pub fn session_start(ctx: &egui::Context, doc: u64, id: LayerId) -> Option { - let kept: Option = ctx.data(|d| d.get_temp(session_key(id))); - kept.filter(|k| k.0 == doc && k.3).map(|k| k.2) -} - -/// The Properties panel's Reset for an adjustment layer whose kind follows Photoshop's session -/// ([`photoshop_session`]): the `layer.setAdjustment` params, or None for other kinds. Edited in -/// the panel since it started showing the layer (or since the last Reset): back to the settings it -/// found (Tone choice kept); otherwise the defaults (Color Balance: [`reset_color_balance`]). -/// Either way part of the layer's edit step. -pub fn properties_reset(ctx: &egui::Context, doc: u64, id: LayerId, adj: &Adjustment) -> Option { - let kind = photocraft_engine::commands::adjustment_kind(adj); - if !photoshop_session(kind) { - return None; - } - let mut v = match session_start(ctx, doc, id) { - Some(start) => start, - None => { - let mut v = adjust_params::to_params(adj); - reset_color_balance(ctx, layer_mem(id), &mut v); - v - } - }; - set_edited(ctx, id, false); - v["layer"] = json!(id.0); - v["coalesce"] = json!(properties_coalesce(id)); - Some(v) -} - -/// The Properties-panel editor of an adjustment layer: previews live (`app.live_adjust`) while a -/// control moves and commits one `layer.setAdjustment` per gesture. -pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj: &Adjustment) { - let t = Tokens::get(ui.ctx()); - let kind = photocraft_engine::commands::adjustment_kind(adj); - match adj { - Adjustment::SelectiveColor { .. } => return crate::adjust_ui::selective_color_editor(app, ui, id, adj), - Adjustment::ColorLookup { .. } => return crate::adjust_ui::color_lookup_editor(app, ui, id, adj), - Adjustment::Invert => { - ui.label(RichText::new(tl!("Invert has no settings.")).color(t.text_faint)); - return; - } - Adjustment::Unsupported { psd_key, .. } => { - let template = "This adjustment ({key}) is kept as imported and can't be edited yet."; - ui.label(RichText::new(crate::i18n::fmt(tl!(template), &[("key", psd_key)])).color(t.text_faint)); - return; - } - _ => {} - } - let committed = adjust_params::to_params(adj); - let session = photoshop_session(kind); - if session && let Some(doc) = app.session.active().map(|s| s.doc.id.0) { - track_session(ui.ctx(), doc, id, &committed); - } - let mut values = match &app.live_adjust { - Some((l, v)) if *l == id => v.clone(), - _ => committed.clone(), - }; - let gray = app.session.active().is_some_and(|s| is_gray(s.doc.mode)); - let hist = needs_histogram(kind).then(|| tone::histograms(app, HistSource::BelowLayer(id), space_of(&values))); - let cx = EditorCx { - mem: layer_mem(id), - hist, - gray, - swatches: swatches(app), - gradients: gradient_presets(app, kind), - dialog: false, - dynamic_color_sliders: app.session.prefs().interface.dynamic_color_sliders, - isolated_curve: None, - }; - if matches!(kind, "levels" | "curves") { - crate::layer_picker::controls(app, ui, id); - } - let e = editor(ui, kind, &mut values, &cx); - if e.import_gradients { - crate::preset_files_ui::import_gradients_dialog(app); - } - if e.changed { - app.live_adjust = Some((id, values.clone())); - } - if e.commit { - if values != committed { - let rev = app.session.active().map(|s| s.revision); - let mut p = values; - p["layer"] = json!(id.0); - if session { - p["coalesce"] = json!(properties_coalesce(id)); - set_edited(ui.ctx(), id, true); - } - if let Err(err) = app.run("layer.setAdjustment", p) { - app.ui.status = err; - } - tone::keep_after_commit(app, id, rev); - } - app.live_adjust = None; - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/adjust_editors/basic.rs b/crates/ui-egui/src/adjust_editors/basic.rs new file mode 100644 index 0000000000..00b940cdbd --- /dev/null +++ b/crates/ui-egui/src/adjust_editors/basic.rs @@ -0,0 +1,287 @@ +use super::hue_saturation::RANGE_LABELS; +use super::*; + +/// Labelled slider rows over top-level keys: (key, label, min, max, default, unit). +/// A row of [`sliders`]: params key, label, range, default, unit, and its decimal places (None: +/// two for a range of 10 or less, else whole numbers). +type SliderRow<'a> = (&'a str, &'a str, f32, f32, f32, &'a str, Option); + +/// The value a [`sliders`] row stores for `x`: rounded to `decimals` places, or by its range. +pub(crate) fn row_value(x: f32, min: f32, max: f32, decimals: Option) -> f32 { + match decimals { + Some(d) => { + let scale = 10f32.powi(d.min(6) as i32); + (x * scale).round() / scale + } + None if max - min <= 10.0 => round(x, 0.01), + None => x.round(), + } +} + +pub(super) fn sliders(ui: &mut egui::Ui, v: &mut Value, rows: &[SliderRow]) -> Edit { + let mut e = Edit::default(); + for &(key, text, min, max, default, unit, decimals) in rows { + let mut x = num(v, key, default).clamp(min, max); + // A double-click on the slider puts it back to its default (Photoshop). + let gestures = widgets::RowGestures { reset: Some(default), wheel_step: None, ..Default::default() }; + let r = widgets::slider_row_prec(ui, text, &mut x, min..=max, unit, None, gestures, decimals); + if r.changed() { + v[key] = json!(row_value(x, min, max, decimals)); + } + e.add(Edit::of(&r)); + } + e +} + +fn gradient_slider(ui: &mut egui::Ui, text: &str, x: &mut f32, range: std::ops::RangeInclusive, unit: &str, stops: [Color32; 2], dynamic: bool) -> Edit { + let r = widgets::slider_row(ui, text, x, range, unit, dynamic.then_some(&stops)); + Edit::of(&r) +} + +/// Preferences ▸ Interface ▸ Dynamic Color Sliders: the colour track for a slider, or the plain +/// track when it is off. +pub(super) fn track_stops<'a>(cx: &EditorCx, stops: &'a [Color32]) -> Option<&'a [Color32]> { + cx.dynamic_color_sliders.then_some(stops) +} + +// --------------------------------------------------------------------------------------------- +// Brightness/Contrast + +pub(super) fn brightness_contrast(ui: &mut egui::Ui, v: &mut Value) -> Edit { + let legacy = flag(v, "legacy", false); + let lo = if legacy { -100.0 } else { -50.0 }; + let mut e = sliders(ui, v, &[("brightness", tl!("Brightness"), -150.0, 150.0, 0.0, "", None), ("contrast", tl!("Contrast"), lo, 100.0, 0.0, "", None)]); + let mut l = legacy; + if widgets::checkbox(ui, &mut l, tl!("Use Legacy")).changed() { + v["legacy"] = json!(l); + if !l { + v["contrast"] = json!(num(v, "contrast", 0.0).max(-50.0)); + } + e.add(Edit::discrete(true)); + } + e +} + +// --------------------------------------------------------------------------------------------- +// Threshold + +pub(super) fn threshold(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { + let t = Tokens::get(ui.ctx()); + let w = ui.available_width().min(300.0); + let (hr, _) = ui.allocate_exact_size(vec2(w, 90.0), Sense::hover()); + let hr = hr.shrink2(vec2(6.0, 0.0)); + let p = ui.painter_at(hr.expand(1.0)); + p.rect_filled(hr, 0.0, t.field); + if let Some(h) = &cx.hist { + tone::draw_histogram(&p, hr, &h[0], Color32::from_gray(if t.pro { 150 } else { 110 })); + } + let level = num(v, "level", 128.0); + let x = hr.left() + level / 255.0 * hr.width(); + p.line_segment([pos2(x, hr.top()), pos2(x, hr.bottom())], Stroke::new(1.0, t.accent)); + p.rect_stroke(hr, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside); + ui.add_space(4.0); + sliders(ui, v, &[("level", tl!("Threshold Level"), 1.0, 255.0, 128.0, "", None)]) +} + +// --------------------------------------------------------------------------------------------- +// Color Balance + +/// Where the Color Balance editor rooted at `mem` keeps its Tone choice. +fn color_balance_tone_id(mem: egui::Id) -> egui::Id { + mem.with("cb-tone") +} + +/// Photoshop's Color Balance reset to defaults (Alt+Cancel in the dialog; the Properties panel's +/// Reset once the layer is as the panel found it): every tone back to 0 and the Tone choice back +/// to Midtones; Preserve Luminosity stays as it is. +pub fn reset_color_balance(ctx: &egui::Context, mem: egui::Id, v: &mut Value) { + for key in ["shadows", "midtones", "highlights"] { + v[key] = json!([0.0, 0.0, 0.0]); + } + ctx.data_mut(|d| d.insert_temp(color_balance_tone_id(mem), 1usize)); +} + +/// Kind-specific editor memory after Alt+Reset (or Properties Reset to defaults). Color Balance +/// shows Midtones; other kinds have no dialog-local temp to clear yet. +pub fn reset_adjustment_editor(ctx: &egui::Context, kind: &str, mem: egui::Id, v: &mut Value) { + if kind == "colorBalance" { + reset_color_balance(ctx, mem, v); + } +} + +pub(super) fn color_balance(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { + let tone_id = color_balance_tone_id(cx.mem); + let mut tone_ix: usize = ui.data(|d| d.get_temp(tone_id)).unwrap_or(1); + ui.horizontal(|ui| { + label(ui, tl!("Tone:")); + for (i, l) in [tl!("Shadows"), tl!("Midtones"), tl!("Highlights")].iter().enumerate() { + if ui.radio(tone_ix == i, *l).clicked() { + tone_ix = i; + } + } + }); + ui.data_mut(|d| d.insert_temp(tone_id, tone_ix)); + let key = ["shadows", "midtones", "highlights"][tone_ix.min(2)]; + let mut vals = nums(v, key, [0.0; 3]); + let mut e = Edit::default(); + let rows = [ + (tl!("Cyan · Red"), Color32::from_rgb(0, 190, 210), Color32::from_rgb(225, 40, 40)), + (tl!("Magenta · Green"), Color32::from_rgb(210, 40, 190), Color32::from_rgb(40, 190, 60)), + (tl!("Yellow · Blue"), Color32::from_rgb(230, 210, 30), Color32::from_rgb(40, 80, 230)), + ]; + // Photoshop: a double-click on a slider zeroes it (this tone only); the dialog's sliders step + // with the wheel; Up/Down step the fields; Shift makes those steps 10. + let gestures = widgets::RowGestures { reset: Some(0.0), wheel_step: cx.dialog.then_some(1.0), ..Default::default() }; + let mut changed = false; + for (i, (text, a, b)) in rows.iter().enumerate() { + let r = Edit::of(&widgets::slider_row_with(ui, text, &mut vals[i], -100.0..=100.0, "", Some(&[*a, *b]), gestures)); + changed |= r.changed; + e.add(r); + } + if changed { + v[key] = json!(vals.map(f32::round)); + } + let mut pl = flag(v, "preserveLuminosity", true); + if widgets::checkbox(ui, &mut pl, tl!("Preserve Luminosity")).changed() { + v["preserveLuminosity"] = json!(pl); + e.add(Edit::discrete(true)); + } + e +} + +// --------------------------------------------------------------------------------------------- +// Black & White + +pub(super) fn black_white(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { + let mut e = Edit::default(); + let colors = [[230, 50, 50], [235, 215, 40], [50, 200, 70], [40, 200, 220], [50, 90, 235], [220, 50, 210]]; + for (i, key) in HUE_RANGES.iter().enumerate() { + let mut x = num(v, key, adjust_params::BW_DEFAULTS[i]).clamp(-200.0, 300.0); + let c = colors[i]; + let r = + gradient_slider(ui, RANGE_LABELS[i], &mut x, -200.0..=300.0, "%", [Color32::BLACK, Color32::from_rgb(c[0], c[1], c[2])], cx.dynamic_color_sliders); + if r.changed { + v[*key] = json!(x.round()); + } + e.add(r); + } + ui.add_space(2.0); + ui.horizontal(|ui| { + let mut on = flag(v, "tint", false); + if widgets::checkbox(ui, &mut on, tl!("Tint")).changed() { + v["tint"] = json!(on); + e.add(Edit::discrete(true)); + } + let mut c = rgb_of(v, "tintColor", [0.882, 0.827, 0.702]); + let r = ui.add_enabled_ui(on, |ui| color_button(ui, &mut c)).inner; + if r.changed { + v["tintColor"] = json!(adjust_params::hex(c)); + } + e.add(r); + if widgets::secondary_button(ui, tl!("Default"), 0.0).clicked() { + for (i, key) in HUE_RANGES.iter().enumerate() { + v[*key] = json!(adjust_params::BW_DEFAULTS[i]); + } + e.add(Edit::discrete(true)); + } + }); + e +} + +// --------------------------------------------------------------------------------------------- +// Photo Filter + +pub(super) fn photo_filter(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { + let mut e = Edit::default(); + let mut c = rgb_of(v, "color", [236.0 / 255.0, 138.0 / 255.0, 0.0]); + let hex = adjust_params::hex(c); + let preset = PHOTO_FILTERS.iter().find(|f| adjust_params::hex(f.2.map(|x| f32::from(x) / 255.0)) == hex).map(|f| f.0); + let mode_id = cx.mem.with("pf-mode"); + let mut use_color: bool = ui.data(|d| d.get_temp(mode_id)).unwrap_or(preset.is_none()); + ui.horizontal(|ui| { + if ui.radio(!use_color, tl!("Filter:")).clicked() { + use_color = false; + } + let mut sel = preset.unwrap_or("custom").to_string(); + let mut opts: Vec<(String, &str)> = PHOTO_FILTERS.iter().map(|f| (f.0.to_string(), f.1)).collect(); + if preset.is_none() { + opts.insert(0, ("custom".into(), "Custom")); + } + let changed = ui.add_enabled_ui(!use_color, |ui| widgets::dropdown(ui, &format!("{mode_id:?}-filter"), tl!("Filter:"), &mut sel, &opts, 170.0)).inner; + if changed && let Some(f) = PHOTO_FILTERS.iter().find(|f| f.0 == sel) { + c = f.2.map(|x| f32::from(x) / 255.0); + v["color"] = json!(adjust_params::hex(c)); + e.add(Edit::discrete(true)); + } + }); + ui.horizontal(|ui| { + if ui.radio(use_color, tl!("Color:")).clicked() { + use_color = true; + } + let r = ui.add_enabled_ui(use_color, |ui| color_button(ui, &mut c)).inner; + if r.changed { + v["color"] = json!(adjust_params::hex(c)); + } + e.add(r); + }); + ui.data_mut(|d| d.insert_temp(mode_id, use_color)); + e.add(sliders(ui, v, &[("density", tl!("Density"), 0.0, 100.0, 25.0, "%", None)])); + let mut pl = flag(v, "preserveLuminosity", true); + if widgets::checkbox(ui, &mut pl, tl!("Preserve Luminosity")).changed() { + v["preserveLuminosity"] = json!(pl); + e.add(Edit::discrete(true)); + } + e +} + +// --------------------------------------------------------------------------------------------- +// Channel Mixer + +pub(super) fn channel_mixer(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { + let t = Tokens::get(ui.ctx()); + let mono = flag(v, "monochrome", false); + let out_id = cx.mem.with("cm-out"); + let mut out: usize = ui.data(|d| d.get_temp(out_id)).unwrap_or(0); + let outs: &[(usize, &str)] = if mono { &[(0, tl!("Gray"))] } else { &[(0, tl!("Red")), (1, tl!("Green")), (2, tl!("Blue"))] }; + if out >= outs.len() { + out = 0; + } + ui.horizontal(|ui| { + label(ui, tl!("Output Channel:")); + widgets::dropdown(ui, &format!("{out_id:?}"), tl!("Output Channel:"), &mut out, outs, 110.0); + }); + ui.data_mut(|d| d.insert_temp(out_id, out)); + let key = if mono { "gray" } else { ["red", "green", "blue"][out] }; + let identity: [f32; 4] = if mono { [40.0, 40.0, 20.0, 0.0] } else { std::array::from_fn(|i| if i == out { 100.0 } else { 0.0 }) }; + let mut row = nums(v, key, if mono { nums(v, "red", identity) } else { identity }); + let mut e = Edit::default(); + let mut changed = false; + for (i, (text, c)) in [(tl!("Red"), [225, 50, 50]), (tl!("Green"), [50, 190, 70]), (tl!("Blue"), [60, 100, 235])].iter().enumerate() { + let r = gradient_slider(ui, text, &mut row[i], -200.0..=200.0, "%", [Color32::BLACK, Color32::from_rgb(c[0], c[1], c[2])], cx.dynamic_color_sliders); + changed |= r.changed; + e.add(r); + } + let total = row[0] + row[1] + row[2]; + ui.horizontal(|ui| { + label(ui, tl!("Total:")); + let warn = total > 100.0; + ui.label(RichText::new(format!("{total:+.0}%")).font(crate::theme::mono(12.0)).color(if warn { t.warning } else { t.text })); + }); + let r = widgets::slider_row(ui, tl!("Constant"), &mut row[3], -200.0..=200.0, "%", None); + changed |= r.changed(); + e.add(Edit::of(&r)); + if changed { + v[key] = json!(row.map(f32::round)); + } + let mut m = mono; + if widgets::checkbox(ui, &mut m, tl!("Monochrome")).changed() { + v["monochrome"] = json!(m); + if m { + v["gray"] = json!([40.0, 40.0, 20.0, 0.0]); + } else if let Some(o) = v.as_object_mut() { + o.remove("gray"); + } + e.add(Edit::discrete(true)); + } + e +} diff --git a/crates/ui-egui/src/adjust_editors/curves.rs b/crates/ui-egui/src/adjust_editors/curves.rs new file mode 100644 index 0000000000..7a3f4ea510 --- /dev/null +++ b/crates/ui-egui/src/adjust_editors/curves.rs @@ -0,0 +1,385 @@ +use super::*; + +// --------------------------------------------------------------------------------------------- +// Channels of Levels / Curves + +/// A channel of a tone editor: the params key (None = the top-level / composite keys for Levels; +/// Curves uses "points"), its label, and its colour name. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ToneChannel { + pub key: &'static str, + pub label: &'static str, +} + +/// The channels a tone editor lists for `space` (histogram index = position). +pub fn tone_channels(space: ToneSpace, gray: bool) -> &'static [ToneChannel] { + const RGB: [ToneChannel; 4] = [ + ToneChannel { key: "", label: "RGB" }, + ToneChannel { key: "red", label: "Red" }, + ToneChannel { key: "green", label: "Green" }, + ToneChannel { key: "blue", label: "Blue" }, + ]; + const GRAY: [ToneChannel; 1] = [ToneChannel { key: "", label: "Gray" }]; + const CMYK: [ToneChannel; 5] = [ + ToneChannel { key: "", label: "CMYK" }, + ToneChannel { key: "cyan", label: "Cyan" }, + ToneChannel { key: "magenta", label: "Magenta" }, + ToneChannel { key: "yellow", label: "Yellow" }, + ToneChannel { key: "black", label: "Black" }, + ]; + const LAB: [ToneChannel; 3] = + [ToneChannel { key: "lightness", label: "Lightness" }, ToneChannel { key: "a", label: "a" }, ToneChannel { key: "b", label: "b" }]; + match space { + ToneSpace::Rgb if gray => &GRAY, + ToneSpace::Rgb => &RGB, + ToneSpace::Cmyk => &CMYK, + ToneSpace::Lab => &LAB, + } +} + +pub(super) fn channel_picker(ui: &mut egui::Ui, id: egui::Id, chans: &[ToneChannel], text: &str) -> usize { + let opts: Vec<(usize, &str)> = chans.iter().enumerate().map(|(i, c)| (i, c.label)).collect(); + channel_picker_opts(ui, id, &opts, text, true) +} + +/// The popup, with `translate` for whether the built-in labels follow the interface language; +/// a user-typed channel name is shown exactly as entered (#5335). +fn channel_picker_opts(ui: &mut egui::Ui, id: egui::Id, opts: &[(usize, &str)], text: &str, translate: bool) -> usize { + let mut ch: usize = ui.data(|d| d.get_temp(id)).unwrap_or(0); + if ch >= opts.len() { + ch = 0; + } + ui.horizontal(|ui| { + label(ui, text); + let width = if opts.len() == 1 { 160.0 } else { 110.0 }; + let key = format!("{id:?}-ch"); + if translate { + widgets::dropdown(ui, &key, text, &mut ch, opts, width); + } else { + widgets::dropdown_literal(ui, &key, text, &mut ch, opts, width); + } + }); + ui.data_mut(|d| d.insert_temp(id, ch)); + ch +} + +pub(super) fn hist_color(ch: &ToneChannel, t: &Tokens) -> Color32 { + match ch.key { + "" | "lightness" | "black" => Color32::from_gray(if t.pro { 150 } else { 110 }), + k => tone::channel_color(k, t), + } +} + +pub(super) fn bar_color(ch: &ToneChannel, t: &Tokens) -> Color32 { + match ch.key { + "" | "lightness" | "black" => Color32::WHITE, + k => tone::channel_color(k, t), + } +} + +/// Horizontal (or vertical) black → `to` gradient bar. +pub(super) fn gradient_bar(p: &egui::Painter, r: Rect, from: Color32, to: Color32, vertical: bool) { + let mut mesh = egui::Mesh::default(); + let (a, b, c, d) = if vertical { + (r.left_bottom(), r.right_bottom(), r.right_top(), r.left_top()) + } else { + (r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()) + }; + let (ca, cb) = if vertical { (from, from) } else { (from, to) }; + let (cc, cd) = if vertical { (to, to) } else { (to, from) }; + mesh.colored_vertex(a, ca); + mesh.colored_vertex(b, cb); + mesh.colored_vertex(c, cc); + mesh.colored_vertex(d, cd); + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + p.add(mesh); +} + +// --------------------------------------------------------------------------------------------- +// Curves + +pub(super) const CURVE_HANDLE_SIZE: f32 = 7.0; + +const CURVE_GRAPH_PADDING: f32 = 5.0; + +/// The room left on screen for the Curves dialog's other rows (title, channel and mode, Input and +/// Output, eyedroppers, buttons) when its graph is as tall as it can be. +const CURVES_CHROME: f32 = 360.0; + +/// The smallest and the default largest side of the Curves graph: 300 points was the fixed +/// size until #8984. +const CURVE_SIDE: (f32, f32) = (120.0, 300.0); + +/// The Curves graph's side (#8984): the width it is given, in the Properties panel and in the +/// resizable dialog, and no taller than the window leaves room for beside the other rows. +fn curve_side(ui: &egui::Ui) -> f32 { + let tallest = curve_side_max(ui.ctx()); + let width = ui.available_width(); + if width.is_finite() { width.clamp(CURVE_SIDE.0, tallest) } else { CURVE_SIDE.1 } +} + +/// The largest the Curves graph gets in this window: as tall as the window leaves room for beside +/// the dialog's other rows, and never under the old 300 points. The Curves dialog is no wider. +pub(crate) fn curve_side_max(ctx: &egui::Context) -> f32 { + (ctx.content_rect().height() - CURVES_CHROME).max(CURVE_SIDE.1) +} + +pub(super) fn curve_graph(full: Rect, side: f32) -> Rect { + let base = Rect::from_min_size(full.min + vec2(14.0, 0.0), vec2(side - 14.0, side - 14.0)); + Rect::from_min_max(base.min + vec2(CURVE_GRAPH_PADDING, CURVE_GRAPH_PADDING), base.max - vec2(CURVE_GRAPH_PADDING, CURVE_GRAPH_PADDING)) +} + +pub(crate) fn read_curve(v: &Value, key: &str) -> Vec<[f32; 2]> { + let pts: Vec<[f32; 2]> = v + .get(key) + .and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(|q| { + let q = q.as_array()?; + Some([q.first()?.as_f64()? as f32, q.get(1)?.as_f64()? as f32]) + }) + .collect() + }) + .unwrap_or_default(); + if pts.len() < 2 { vec![[0.0, 0.0], [255.0, 255.0]] } else { pts } +} + +fn curve_key(ch: &ToneChannel) -> &'static str { + if ch.key.is_empty() { "points" } else { ch.key } +} + +/// A pencil-drawn channel: its 256 output levels (identity when absent or not a map). +fn read_map(v: &Value, key: &str) -> Vec { + let map: Option> = v + .get(key) + .and_then(Value::as_array) + .filter(|a| a.len() == photocraft_doc::adjust::CURVE_MAP_LEN) + .and_then(|a| a.iter().map(|o| o.as_f64().map(|o| o as f32)).collect()); + map.unwrap_or_else(|| (0..photocraft_doc::adjust::CURVE_MAP_LEN).map(|k| k as f32).collect()) +} + +fn write_map(v: &mut Value, key: &str, map: &[f32]) { + v[key] = json!(map.iter().map(|o| (o * 100.0).round() / 100.0).collect::>()); +} + +/// Switches the Curves values between point editing and the pencil: the engine draws the point +/// curves into maps, or fits points to the drawn maps (Photoshop's two curve buttons). +fn set_pencil(v: &mut Value, pencil: bool, gray: bool) -> bool { + let mut p = v.clone(); + p["pencil"] = json!(pencil); + let mode = if gray { photocraft_doc::ColorMode::Grayscale } else { photocraft_doc::ColorMode::Rgb }; + let Ok(a) = adjust_params::from_params("curves", &p, None, mode) else { return false }; + *v = adjust_params::to_params(&a); + // Explicit, so an update over a pencil-drawn layer leaves the pencil. + v["pencil"] = json!(pencil); + true +} + +/// Mode buttons above the graph: points, pencil, and Smooth for the shown channel's drawing. +fn curves_mode_row(ui: &mut egui::Ui, v: &mut Value, key: &str, gray: bool) -> Edit { + let pencil = v.get("pencil").and_then(Value::as_bool).unwrap_or(false); + let mut e = Edit::default(); + ui.horizontal(|ui| { + if crate::icons::button(ui, "spline", 24.0, !pencil, tl!("Edit points to modify the curve")).clicked() && pencil { + e.add(Edit::discrete(set_pencil(v, false, gray))); + } + if crate::icons::button(ui, "pencil", 24.0, pencil, tl!("Draw to modify the curve")).clicked() && !pencil { + e.add(Edit::discrete(set_pencil(v, true, gray))); + } + let label = crate::i18n::tr_ctx(crate::i18n::current(), "curves", "Smooth"); + let smooth = ui + .add_enabled_ui(pencil, |ui| widgets::secondary_button(ui, label, 0.0)) + .inner + .on_hover_text(tl!("Smooth the curve values")) + .on_disabled_hover_text(tl!("Smooth the curve values")); + if smooth.clicked() { + let mut map = read_map(v, key); + adjust_params::smooth_curve_map(&mut map); + write_map(v, key, &map); + e.add(Edit::discrete(true)); + } + }); + e +} + +pub(super) fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { + let t = Tokens::get(ui.ctx()); + let space = space_of(v); + let chans = tone_channels(space, cx.gray); + let state_id = cx.mem.with("curves"); + let mut st: CurveUi = ui.data(|d| d.get_temp(state_id)).unwrap_or_default(); + let isolated = cx.isolated_curve.as_ref(); + let ch = if let Some(iso) = isolated { + channel_picker_opts(ui, cx.mem.with("curves-ch"), &[(0, iso.name.as_str())], tl!("Channel:"), iso.translate) + } else { + channel_picker(ui, cx.mem.with("curves-ch"), chans, tl!("Channel:")) + }; + if ch != st.channel { + st = CurveUi { channel: ch, ..Default::default() }; + } + let chan = + if let Some(iso) = isolated { ToneChannel { key: iso.key, label: "" } } else { chans.get(ch).copied().unwrap_or(ToneChannel { key: "", label: "" }) }; + let overlay_others = isolated.is_none(); + let tinted = isolated.is_some_and(|c| c.tint) || (isolated.is_none() && ch != 0); + let hist_i = isolated.map_or(ch, |c| c.hist); + let key = curve_key(&chan); + let mut e = curves_mode_row(ui, v, key, cx.gray); + let pencil = v.get("pencil").and_then(Value::as_bool).unwrap_or(false); + let mut pts = read_curve(v, key); + let mut map = read_map(v, key); + let side = curve_side(ui); + ui.add_space(4.0); + let (full, resp) = ui.allocate_exact_size(vec2(side, side + 14.0), Sense::click_and_drag()); + let graph = curve_graph(full, side); + ui.data_mut(|d| d.insert_temp(cx.mem.with("curves-graph"), graph)); + let to_scr = |q: [f32; 2]| pos2(graph.left() + q[0] / 255.0 * graph.width(), graph.bottom() - q[1] / 255.0 * graph.height()); + let mut changed = false; + let mut drawn = false; + if pencil { + // Pencil: a stroke draws while the button is down and commits on release; Shift + // continues from the previous stroke's end in a straight line. + let stroke_id = cx.mem.with("curves-pencil"); + let (mut active, mut last): (bool, Option<[f32; 2]>) = ui.data(|d| d.get_temp(stroke_id)).unwrap_or_default(); + if resp.is_pointer_button_down_on() + && let Some(pos) = resp.interact_pointer_pos() + { + let q = [ + ((pos.x - graph.left()) / graph.width().max(1.0) * 255.0).clamp(0.0, 255.0), + ((graph.bottom() - pos.y) / graph.height().max(1.0) * 255.0).clamp(0.0, 255.0), + ]; + let from = if active || ui.input(|i| i.modifiers.shift) { last.unwrap_or(q) } else { q }; + drawn = curve_edit::pencil_line(&mut map, from, q); + active = true; + last = Some(q); + } else if active { + active = false; + e.commit = true; + } + ui.data_mut(|d| d.insert_temp(stroke_id, (active, last))); + } else { + let interaction = crate::point_curve::interact(ui, &resp, graph, &mut pts, &mut st.gesture); + changed = interaction.changed; + e.commit |= interaction.commit; + } + + // Draw: histogram, quarter grid, baseline, gradient bars, other channels, the curve, points. + let p = ui.painter_at(full.expand(2.0)); + p.rect_filled(graph, 0.0, t.field); + if let Some(h) = &cx.hist { + tone::draw_histogram(&p, graph, &h[hist_i], Color32::from_gray(if t.pro { 88 } else { 190 }).gamma_multiply(0.75)); + } + for i in 1..4 { + let f = i as f32 / 4.0; + let g = Stroke::new(1.0, t.separator); + p.line_segment([pos2(graph.left() + f * graph.width(), graph.top()), pos2(graph.left() + f * graph.width(), graph.bottom())], g); + p.line_segment([pos2(graph.left(), graph.top() + f * graph.height()), pos2(graph.right(), graph.top() + f * graph.height())], g); + } + p.line_segment([graph.left_bottom(), graph.right_top()], Stroke::new(1.0, t.separator.gamma_multiply(1.6))); + p.rect_stroke( + graph, + 0.0, + Stroke::new(if resp.has_focus() { 1.5 } else { 1.0 }, if resp.has_focus() { t.accent } else { t.field_border }), + StrokeKind::Outside, + ); + let hbar = Rect::from_min_max(pos2(graph.left(), graph.bottom() + 4.0), pos2(graph.right(), graph.bottom() + 12.0)); + let vbar = Rect::from_min_max(pos2(full.left(), graph.top()), pos2(full.left() + 8.0, graph.bottom())); + gradient_bar(&p, hbar, Color32::BLACK, bar_color(&chan, &t), false); + gradient_bar(&p, vbar, Color32::BLACK, bar_color(&chan, &t), true); + let draw_curve = |pts: &[[f32; 2]], color: Color32, width: f32| { + let cp: Vec = + pts.iter().map(|q| photocraft_doc::adjust::CurvePoint { input: q[0] / 255.0, output: q[1] / 255.0 }).collect(); + let lut = photocraft_compose::adjust::curve_lut(&cp); + let n = lut.len().max(2); + let line: Vec = + (0..n).step_by((n / 256).max(1)).map(|i| to_scr([i as f32 / (n - 1) as f32 * 255.0, lut.get(i).copied().unwrap_or(0.0) * 255.0])).collect(); + p.add(egui::Shape::line(line, Stroke::new(width, color))); + }; + let draw_map = |map: &[f32], color: Color32, width: f32| { + let last = map.len().saturating_sub(1).max(1) as f32; + let line: Vec = map.iter().enumerate().map(|(k, o)| to_scr([k as f32 / last * 255.0, *o])).collect(); + p.add(egui::Shape::line(line, Stroke::new(width, color))); + }; + if overlay_others && ch == 0 { + // Photoshop overlays the edited channel curves on the composite. + for c in chans.iter().skip(1) { + if pencil { + let m = read_map(v, c.key); + if m.iter().enumerate().any(|(k, o)| (o - k as f32).abs() > 0.5) { + draw_map(&m, bar_color(c, &t).gamma_multiply(0.8), 1.0); + } + continue; + } + let cp = read_curve(v, c.key); + if cp.len() > 2 || cp.first().is_some_and(|q| q[1] != 0.0) || cp.last().is_some_and(|q| q[1] != 255.0) { + draw_curve(&cp, bar_color(c, &t).gamma_multiply(0.8), 1.0); + } + } + } + let color = if tinted { bar_color(&chan, &t) } else { t.text }; + if pencil { + draw_map(&map, color, 1.5); + } else { + draw_curve(&pts, color, 1.5); + } + for (i, q) in pts.iter().enumerate().filter(|_| !pencil) { + let r = Rect::from_center_size(to_scr(*q), vec2(CURVE_HANDLE_SIZE, CURVE_HANDLE_SIZE)); + if Some(i) == st.gesture.selected { + p.rect_filled(r, 0.0, t.text); + p.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::BLACK), StrokeKind::Outside); + } else { + p.rect_filled(r, 0.0, t.field); + p.rect_stroke(r, 0.0, Stroke::new(1.0, t.text), StrokeKind::Inside); + } + } + + // Input / Output of the selected point. + ui.add_space(6.0); + ui.horizontal(|ui| { + let i = st.gesture.selected.filter(|i| *i < pts.len() && !pencil); + let (mut vi, mut vo) = i.map_or((0.0, 0.0), |i| (pts[i][0], pts[i][1])); + label(ui, tl!("Input:")); + let ri = ui.add_enabled_ui(i.is_some(), |ui| widgets::value_field(ui, &mut vi, 0.0..=255.0, "", 52.0).accessible_name(tl!("Input:"))).inner; + label(ui, tl!("Output:")); + let ro = ui.add_enabled_ui(i.is_some(), |ui| widgets::value_field(ui, &mut vo, 0.0..=255.0, "", 52.0).accessible_name(tl!("Output:"))).inner; + if let Some(i) = i + && (ri.changed() || ro.changed()) + && curve_edit::move_to(&mut pts, i, [vi, vo]) + { + changed = true; + e.commit |= !(ri.dragged() || ro.dragged()); + } + if ri.drag_stopped() || ro.drag_stopped() { + e.commit = true; + } + }); + let t2 = Tokens::get(ui.ctx()); + let hint = if pencil { + crate::i18n::fmt(tl!("Drag to draw the curve · {key}-click draws a straight line"), &[("key", &crate::shortcuts::pretty("Shift"))]) + } else { + crate::i18n::fmt(tl!("Click to add a point · drag off or {key}-click or Delete to remove"), &[("key", &crate::shortcuts::pretty("Cmd"))]) + }; + ui.label(RichText::new(hint).color(t2.text_faint).size(11.0)); + ui.data_mut(|d| d.insert_temp(state_id, st)); + if drawn { + write_map(v, key, &map); + if space == ToneSpace::Lab + && let Some(o) = v.as_object_mut() + { + o.remove("points"); + } + e.changed = true; + } + if changed && !pencil { + v[key] = json!(pts.iter().map(|q| [q[0].round(), q[1].round()]).collect::>()); + if space == ToneSpace::Lab { + // Lab has no composite: "points" would alias lightness. + if let Some(o) = v.as_object_mut() { + o.remove("points"); + } + } + e.changed = true; + } + e +} diff --git a/crates/ui-egui/src/adjust_editors/gradient_map.rs b/crates/ui-egui/src/adjust_editors/gradient_map.rs new file mode 100644 index 0000000000..1684d9bb47 --- /dev/null +++ b/crates/ui-egui/src/adjust_editors/gradient_map.rs @@ -0,0 +1,284 @@ +use super::hue_saturation::spectrum_bar; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Gradient Map + +type Stop = (f32, [f32; 3]); + +fn read_stops(v: &Value) -> Vec { + let mut s: Vec = v + .get("stops") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(|s| { + let p = s.as_array()?; + let t = p.first()?.as_f64()? as f32; + let c = rgb_of(&json!({"c": p.get(1)?.clone()}), "c", [0.0; 3]); + Some((t.clamp(0.0, 1.0), c)) + }) + .collect() + }) + .unwrap_or_default(); + if s.len() < 2 { + s = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]; + } + s +} + +fn write_stops(v: &mut Value, s: &[Stop]) { + let mut s = s.to_vec(); + s.sort_by(|a, b| a.0.total_cmp(&b.0)); + v["stops"] = json!(s.iter().map(|(t, c)| json!([round(*t, 0.001), adjust_params::hex(*c)])).collect::>()); +} + +fn sample_stops(s: &[Stop], t: f32) -> [f32; 3] { + let mut sorted = s.to_vec(); + sorted.sort_by(|a, b| a.0.total_cmp(&b.0)); + let Some(first) = sorted.first() else { return [t; 3] }; + if t <= first.0 { + return first.1; + } + for w in sorted.windows(2) { + if t <= w[1].0 { + let k = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 }; + return std::array::from_fn(|i| w[0].1[i] + (w[1].1[i] - w[0].1[i]) * k); + } + } + sorted.last().map_or([t; 3], |l| l.1) +} + +#[derive(Clone, Copy)] +struct MapStopDrag { + index: usize, + offset: f32, + changed: bool, +} + +/// Keep selection on the same stop when it crosses another stop (including coincident stops). +fn move_map_stop(stops: &mut [Stop], index: usize, location: f32) -> Option { + let stop = stops.get_mut(index)?; + stop.0 = round(location.clamp(0.0, 1.0), 0.001); + let location = stop.0; + let rank = stops.iter().enumerate().filter(|(i, s)| *i != index && (s.0 < location || (s.0 == location && *i < index))).count(); + stops.sort_by(|a, b| a.0.total_cmp(&b.0)); + Some(rank) +} + +fn gradient_map_strip(ui: &mut egui::Ui, stops: &mut Vec, cx: &EditorCx, selected: &mut usize) -> Edit { + let t = Tokens::get(ui.ctx()); + let key = cx.mem.with("gm-stop-drag"); + let mut edit = Edit::default(); + let w = ui.available_width().min(300.0); + let (outer, resp) = ui.allocate_exact_size(vec2(w, 44.0), Sense::click_and_drag()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), tl!("Gradient stops"))); + let bar = Rect::from_min_max(outer.min + vec2(8.0, 2.0), pos2(outer.right() - 8.0, outer.top() + 26.0)); + let x_of = |loc: f32| bar.left() + loc * bar.width(); + let loc_of = |x: f32| ((x - bar.left()) / bar.width().max(1.0)).clamp(0.0, 1.0); + let hit = + |pos: Pos2, stops: &[Stop]| stops.iter().enumerate().rev().find(|(_, s)| pos.y >= bar.bottom() && (x_of(s.0) - pos.x).abs() <= 6.0).map(|(i, _)| i); + if resp.drag_started() + && let Some(pos) = ui.input(|i| i.pointer.press_origin()) + && let Some(index) = hit(pos, stops) + { + *selected = index; + let offset = stops.get(index).map_or(0.0, |s| pos.x - x_of(s.0)); + ui.data_mut(|d| d.insert_temp(key, MapStopDrag { index, offset, changed: false })); + } + if let Some(mut drag) = ui.data(|d| d.get_temp::(key)) { + if (resp.dragged() || resp.drag_stopped()) + && let Some(pos) = resp.interact_pointer_pos() + { + let location = round(loc_of(pos.x - drag.offset), 0.001); + let changed = stops.get(drag.index).is_some_and(|s| s.0 != location); + if let Some(index) = move_map_stop(stops, drag.index, location) { + drag.index = index; + drag.changed |= changed; + *selected = index; + edit.changed |= changed; + } + } + if resp.drag_stopped() { + edit.commit = drag.changed; + ui.data_mut(|d| d.remove::(key)); + } else if ui.input(|i| i.pointer.primary_down()) { + ui.data_mut(|d| d.insert_temp(key, drag)); + } else { + ui.data_mut(|d| d.remove::(key)); + } + } + if resp.clicked() + && let Some(pos) = resp.interact_pointer_pos() + { + resp.request_focus(); + if let Some(index) = hit(pos, stops) { + *selected = index; + } else if stops.len() < 64 { + let at = round(loc_of(pos.x), 0.001); + let color = sample_stops(stops, at); + stops.push((at, color)); + let index = stops.len() - 1; + *selected = move_map_stop(stops, index, at).unwrap_or(0); + edit.add(Edit::discrete(true)); + } + } + if resp.hovered() && ui.input(|i| i.pointer.hover_pos()).is_some_and(|pos| hit(pos, stops).is_some()) || resp.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); + } + // Markers address un-reversed locations, as in the Gradient Tool; Reverse changes the image. + let cols: Vec = (0..=48).map(|i| color32(sample_stops(stops, i as f32 / 48.0))).collect(); + spectrum_bar(ui.painter(), bar, &cols); + ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside); + for (i, (at, color)) in stops.iter().enumerate() { + let x = x_of(*at); + let border = if i == *selected { t.accent } else { t.text_dim }; + let body = Rect::from_center_size(pos2(x, bar.bottom() + 10.0), vec2(10.0, 10.0)); + ui.painter().add(egui::Shape::convex_polygon( + vec![pos2(x, bar.bottom() + 1.0), pos2(x + 5.0, body.top()), pos2(x - 5.0, body.top())], + border, + Stroke::NONE, + )); + ui.painter().rect_filled(body, 1.0, color32(*color)); + ui.painter().rect_stroke(body, 1.0, Stroke::new(1.0, border), StrokeKind::Outside); + } + edit +} + +pub(super) fn gradient_map(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { + let t = Tokens::get(ui.ctx()); + let mut e = Edit::default(); + let mut stops = read_stops(v); + let selection = cx.mem.with("gm-stop-selection"); + let mut selected = ui.data(|d| d.get_temp::(selection)).unwrap_or(0).min(stops.len().saturating_sub(1)); + // Photoshop's gradient picker: the same library as the Gradient tool and Gradients panel + // (built-in groups and the user's own), Foreground/Background resolved to the current colours. + let [fg, bg] = cx.swatches.map(|c| [c[0], c[1], c[2], 1.0]); + ui.horizontal(|ui| { + label(ui, tl!("Preset:")); + let mut picked = None; + let (press, close) = crate::press_menu::PressCombo::before(ui, cx.mem.with("gm-preset")); + let combo = egui::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::>()); + } + }); + } + } + }); + press.after(&combo.response); + let _ = combo.response.accessible_name(tl!("Preset:")); + if let Some(p) = picked { + stops = p; + selected = 0; + ui.data_mut(|d| d.remove::(cx.mem.with("gm-stop-drag"))); + write_stops(v, &stops); + e.add(Edit::discrete(true)); + } + }); + let strip = gradient_map_strip(ui, &mut stops, cx, &mut selected); + let mut changed = strip.changed; + e.add(strip); + // The selected stop's colour and location, like the Gradient Tool's compact stop editor. + let mut location = None; + let mut remove = false; + let can_remove = stops.len() > 2; + if let Some(s) = stops.get_mut(selected) { + ui.horizontal(|ui| { + label(ui, tl!("Color:")); + let r = color_button(ui, &mut s.1); + changed |= r.changed; + e.add(r); + ui.add_enabled_ui(can_remove, |ui| { + remove = crate::icons::button(ui, "x", 20.0, false, tl!("Remove stop")).clicked(); + }); + }); + ui.horizontal(|ui| { + label(ui, tl!("Location:")); + let mut loc = s.0 * 100.0; + let rl = widgets::value_field(ui, &mut loc, 0.0..=100.0, "%", 70.0).accessible_name(tl!("Location:")); + if rl.changed() { + location = Some(loc / 100.0); + changed = true; + } + e.add(Edit::of(&rl)); + }); + } + if let Some(loc) = location { + selected = move_map_stop(&mut stops, selected, loc).unwrap_or(0); + } + if remove && can_remove { + stops.remove(selected); + selected = selected.min(stops.len() - 1); + changed = true; + e.add(Edit::discrete(true)); + } + if stops.len() < 64 && widgets::secondary_button(ui, tl!("Add Stop"), 0.0).clicked() { + // Halfway along the widest gap, in the gradient's colour there. + let mut sorted = stops.clone(); + sorted.sort_by(|a, b| a.0.total_cmp(&b.0)); + let at = sorted.windows(2).max_by(|a, b| (a[1].0 - a[0].0).total_cmp(&(b[1].0 - b[0].0))).map_or(0.5, |w| (w[0].0 + w[1].0) / 2.0); + stops.push((at, sample_stops(&stops, at))); + let index = stops.len() - 1; + selected = move_map_stop(&mut stops, index, at).unwrap_or(0); + changed = true; + e.add(Edit::discrete(true)); + } + if changed { + write_stops(v, &stops); + e.changed = true; + } + ui.data_mut(|d| d.insert_temp(selection, selected)); + ui.horizontal(|ui| { + for (key, text) in [("reverse", tl!("Reverse")), ("dither", tl!("Dither"))] { + let mut b = flag(v, key, false); + if widgets::checkbox(ui, &mut b, text).changed() { + v[key] = json!(b); + e.add(Edit::discrete(true)); + } + } + }); + e +} + +// --------------------------------------------------------------------------------------------- +// Hosts + +/// Whether a document of this mode edits Levels/Curves through a single Gray channel. +pub fn is_gray(mode: photocraft_doc::ColorMode) -> bool { + matches!(mode, photocraft_doc::ColorMode::Grayscale | photocraft_doc::ColorMode::Duotone | photocraft_doc::ColorMode::Bitmap) +} + +/// The gradient preset library for a `kind` editor's picker (Gradient Map only; empty otherwise). +pub fn gradient_presets(app: &PhotocraftApp, kind: &str) -> Vec> { + if kind == "gradientMap" { app.session.presets.gradients.clone() } else { Vec::new() } +} + +pub fn swatches(app: &PhotocraftApp) -> [[f32; 3]; 2] { + let c = |x: [f32; 4]| [x[0], x[1], x[2]]; + [c(app.session.tools.foreground), c(app.session.tools.background)] +} diff --git a/crates/ui-egui/src/adjust_editors/hue_saturation.rs b/crates/ui-egui/src/adjust_editors/hue_saturation.rs new file mode 100644 index 0000000000..042f398619 --- /dev/null +++ b/crates/ui-egui/src/adjust_editors/hue_saturation.rs @@ -0,0 +1,207 @@ +use super::basic::{sliders, track_stops}; +use super::curves::gradient_bar; +use super::levels::nearest; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Hue/Saturation + +pub(super) const RANGE_LABELS: [&str; 6] = ["Reds", "Yellows", "Greens", "Cyans", "Blues", "Magentas"]; + +/// The Saturation slider's track: grey to the hue at full saturation (UI-217-16). +pub(super) fn saturation_track(hue_deg: f32) -> [Color32; 2] { + [Color32::from_gray(128), hue_color(hue_deg)] +} + +/// The Lightness slider's track: black, mid grey, white, whatever the hue, as in Photoshop +/// (UI-217-16, #6539). +pub(super) fn lightness_track() -> [Color32; 3] { + [Color32::BLACK, Color32::from_gray(128), Color32::WHITE] +} + +pub(super) fn move_hue_range_handle(bounds: [f32; 4], k: usize, deg: f32) -> [f32; 4] { + let mut b = HueRange::canonical_bounds(bounds); + if k >= b.len() { + return b; + } + if k == 0 { + let delta = (deg - b[0] + 180.0).rem_euclid(360.0) - 180.0; + b[0] = (b[0] + delta).min(b[1]).max(b[1] - 180.0); + } else { + let rel = (deg - b[0]).rem_euclid(360.0); + let hi = if k == 3 { b[0] + 359.0 } else { b[k + 1] }; + b[k] = (b[0] + rel).clamp(b[k - 1], hi); + } + b +} + +/// 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); + let rect = photocraft_geom::Rect::new(0, 0, n as i32, 1); + let px = (0..n) + .map(|i| { + let c = photocraft_color::convert::hsb_to_rgb([i as f32 / (n - 1).max(1) as f32 * 360.0, 1.0, 1.0]); + [c[0], c[1], c[2], 1.0] + }) + .collect(); + let mut buf = photocraft_compose::Buffer { rect, px }; + photocraft_compose::adjust::apply(&adj, &mut buf); + buf.px.iter().map(|p| color32([p[0], p[1], p[2]])).collect() +} + +pub(super) fn spectrum_bar(p: &egui::Painter, r: Rect, colors: &[Color32]) { + let n = colors.len().saturating_sub(1).max(1); + for (i, w) in colors.windows(2).enumerate() { + let x0 = r.left() + r.width() * i as f32 / n as f32; + let x1 = r.left() + r.width() * (i + 1) as f32 / n as f32; + gradient_bar(p, Rect::from_min_max(pos2(x0, r.top()), pos2(x1, r.bottom())), w[0], w[1], false); + } +} + +pub(super) fn hue_saturation(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { + let t = Tokens::get(ui.ctx()); + let range_id = cx.mem.with("hs-range"); + let mut range: usize = ui.data(|d| d.get_temp(range_id)).unwrap_or(0); + let colorize = flag(v, "colorize", false); + if colorize { + range = 0; + } + ui.horizontal(|ui| { + let opts: Vec<(usize, &str)> = std::iter::once((0, tl!("Master"))).chain(RANGE_LABELS.iter().enumerate().map(|(i, l)| (i + 1, *l))).collect(); + ui.add_enabled_ui(!colorize, |ui| widgets::dropdown(ui, &format!("{range_id:?}"), tl!("Range"), &mut range, &opts, 120.0)); + }); + ui.data_mut(|d| d.insert_temp(range_id, range)); + let mut e = Edit::default(); + let hue_grad = widgets::hue_stops(); + if range == 0 { + let (hlo, hhi, slo) = if colorize { (0.0, 360.0, 0.0) } else { (-180.0, 180.0, -100.0) }; + let mut h = num(v, "hue", 0.0).clamp(hlo, hhi); + let r = widgets::slider_row(ui, tl!("Hue"), &mut h, hlo..=hhi, "°", track_stops(cx, &hue_grad)); + if r.changed() { + v["hue"] = json!(h.round()); + } + e.add(Edit::of(&r)); + // The Saturation track follows the current hue; the Lightness track is a fixed + // black-grey-white ramp, as in Photoshop (UI-217-16). + let sat_track = saturation_track(h); + let mut s = num(v, "saturation", 0.0).clamp(slo, 100.0); + let r = widgets::slider_row(ui, tl!("Saturation"), &mut s, slo..=100.0, "%", track_stops(cx, &sat_track)); + if r.changed() { + v["saturation"] = json!(s.round()); + } + e.add(Edit::of(&r)); + let light_track = lightness_track(); + let mut l = num(v, "lightness", 0.0).clamp(-100.0, 100.0); + let r = widgets::slider_row(ui, tl!("Lightness"), &mut l, -100.0..=100.0, "%", track_stops(cx, &light_track)); + if r.changed() { + v["lightness"] = json!(l.round()); + } + e.add(Edit::of(&r)); + } else { + let key = HUE_RANGES[range - 1]; + if !v.get(key).is_some_and(Value::is_object) { + v[key] = json!({}); + } + let mut o = v[key].clone(); + let mut sub = Edit::default(); + let mut h = num(&o, "hue", 0.0); + let r = widgets::slider_row(ui, tl!("Hue"), &mut h, -180.0..=180.0, "°", track_stops(cx, &hue_grad)); + if r.changed() { + o["hue"] = json!(h.round()); + } + sub.add(Edit::of(&r)); + sub.add(sliders( + ui, + &mut o, + &[("saturation", tl!("Saturation"), -100.0, 100.0, 0.0, "%", None), ("lightness", tl!("Lightness"), -100.0, 100.0, 0.0, "%", None)], + )); + if sub.changed { + v[key] = o; + } + e.add(sub); + } + let mut c = colorize; + if widgets::checkbox(ui, &mut c, tl!("Colorize")).changed() { + v["colorize"] = json!(c); + let h = num(v, "hue", 0.0); + v["hue"] = json!(if c { + h.rem_euclid(360.0) + } else if h > 180.0 { + h - 360.0 + } else { + h + }); + if c { + v["saturation"] = json!(num(v, "saturation", 25.0).max(0.0).max(25.0)); + } + e.add(Edit::discrete(true)); + } + // Spectrum bars: input hues above, adjusted below; the selected range's sliders between. + ui.add_space(6.0); + // As wide as the sliders above, whatever the panel's width (#9242). + let w = ui.available_width(); + let (bars, bresp) = ui.allocate_exact_size(vec2(w, 40.0), Sense::click_and_drag()); + ui.data_mut(|d| d.insert_temp(cx.mem.with("hs-bars"), bars)); + let top = Rect::from_min_size(bars.min, vec2(w, 10.0)); + let bottom = Rect::from_min_size(pos2(bars.left(), bars.bottom() - 10.0), vec2(w, 10.0)); + let p = ui.painter_at(bars.expand(4.0)); + let input: Vec = (0..=36).map(|i| hue_color(i as f32 * 10.0)).collect(); + spectrum_bar(&p, top, &input); + spectrum_bar(&p, bottom, &adjusted_spectrum(v, 37)); + if range > 0 { + let key = HUE_RANGES[range - 1]; + let neutral = photocraft_doc::adjust::HueRange::neutral(range - 1).bounds; + let mut b = HueRange::canonical_bounds(nums(&v[key], "range", neutral)); + let xof = |deg: f32| bars.left() + deg.rem_euclid(360.0) / 360.0 * w; + let deg_of = |x: f32| ((x - bars.left()) / w * 360.0).clamp(0.0, 360.0); + let mid = bars.center().y; + // Range band (fully affected) and fall-off. + let band = |a: f32, z: f32, color: Color32| { + let (xa, xz) = (xof(a), xof(z)); + if xa <= xz { + p.rect_filled(Rect::from_min_max(pos2(xa, mid - 3.0), pos2(xz, mid + 3.0)), 0.0, color); + } else { + p.rect_filled(Rect::from_min_max(pos2(xa, mid - 3.0), pos2(bars.right(), mid + 3.0)), 0.0, color); + p.rect_filled(Rect::from_min_max(pos2(bars.left(), mid - 3.0), pos2(xz, mid + 3.0)), 0.0, color); + } + }; + band(b[0], b[3], t.text_faint); + band(b[1], b[2], t.text_dim); + for (k, d) in b.iter().enumerate() { + let x = xof(*d); + let fill = if k == 1 || k == 2 { t.text } else { t.field }; + 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); + } + let drag_id = cx.mem.with("hs-range-drag"); + let mut which: Option = ui.data(|d| d.get_temp(drag_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); + } + if bresp.is_pointer_button_down_on() + && let (Some(k), Some(pos)) = (which, ui.input(|i| i.pointer.interact_pos())) + { + let k = k as usize; + let deg = deg_of(pos.x); + let before = b; + b = move_hue_range_handle(b, k, deg); + if b != before { + v[key]["range"] = json!(b.map(|x| x.round())); + e.changed = true; + } + } + if which.is_some() && !bresp.is_pointer_button_down_on() { + which = None; + e.commit = true; + } + ui.data_mut(|d| d.insert_temp(drag_id, which)); + let lab = + format!("{:.0}° / {:.0}° · {:.0}° \\ {:.0}°", b[0].rem_euclid(360.0), b[1].rem_euclid(360.0), b[2].rem_euclid(360.0), b[3].rem_euclid(360.0)); + ui.label(RichText::new(lab).font(crate::theme::mono(11.0)).color(t.text_faint)); + } + e +} diff --git a/crates/ui-egui/src/adjust_editors/levels.rs b/crates/ui-egui/src/adjust_editors/levels.rs new file mode 100644 index 0000000000..8963e438e2 --- /dev/null +++ b/crates/ui-egui/src/adjust_editors/levels.rs @@ -0,0 +1,208 @@ +use super::curves::{ToneChannel, bar_color, channel_picker, gradient_bar, hist_color, tone_channels}; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Levels + +type Lv = [f32; 5]; // in_black, gamma, in_white, out_black, out_white (0–255, gamma as is) + +fn read_levels(v: &Value, key: &str) -> Lv { + let o = if key.is_empty() { Some(v) } else { v.get(key) }; + let g = |k: &str, d: f32| o.and_then(|o| o.get(k)).and_then(Value::as_f64).map_or(d, |x| x as f32); + [g("inBlack", 0.0), g("gamma", 1.0), g("inWhite", 255.0), g("outBlack", 0.0), g("outWhite", 255.0)] +} + +fn write_levels(v: &mut Value, key: &str, l: &Lv) { + let obj = json!({"inBlack": l[0].round(), "gamma": round(l[1], 0.01), "inWhite": l[2].round(), "outBlack": l[3].round(), "outWhite": l[4].round()}); + if key.is_empty() { + if let (Some(dst), Value::Object(src)) = (v.as_object_mut(), obj) { + dst.extend(src); + } + } else { + v[key] = obj; + } +} + +/// A triangular slider handle below a bar. +fn handle(p: &egui::Painter, x: f32, y: f32, fill: Color32, stroke: Color32) { + p.add(egui::Shape::convex_polygon(vec![pos2(x, y), pos2(x + 5.5, y + 9.0), pos2(x - 5.5, y + 9.0)], fill, Stroke::new(1.0, stroke))); +} + +/// Input level (0–255) where the gamma slider sits: the input that maps to 50% grey. +pub fn gamma_pos(black: f32, white: f32, gamma: f32) -> f32 { + black + (white - black) * 0.5f32.powf(gamma) +} + +pub fn gamma_from_pos(black: f32, white: f32, x: f32) -> f32 { + let t = ((x - black) / (white - black).max(1.0)).clamp(0.01, 0.99); + (t.ln() / 0.5f32.ln()).clamp(0.01, 9.99) +} + +/// Black and white input levels clipping 0.1 % at each end of `h` (Photoshop's Auto). +pub fn auto_levels(h: &[u32; 256]) -> (f32, f32) { + let total: u64 = h.iter().map(|x| u64::from(*x)).sum(); + let clip = total / 1000; + let (mut acc, mut lo) = (0u64, 0usize); + while lo < 253 && acc + u64::from(h[lo]) <= clip { + acc += u64::from(h[lo]); + lo += 1; + } + let (mut acc, mut hi) = (0u64, 255usize); + while hi > lo + 2 && acc + u64::from(h[hi]) <= clip { + acc += u64::from(h[hi]); + hi -= 1; + } + (lo as f32, hi as f32) +} + +/// Which handle of a slider row a press at `x` grabs (nearest), among `xs`. +pub(super) fn nearest(xs: &[f32], x: f32) -> Option { + xs.iter().enumerate().min_by(|a, b| (a.1 - x).abs().total_cmp(&(b.1 - x).abs())).map(|(i, _)| i as u8) +} + +pub(super) fn levels(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { + let t = Tokens::get(ui.ctx()); + let chans = tone_channels(space_of(v), cx.gray); + let mut ch = 0; + let mut auto = false; + ui.horizontal(|ui| { + ch = channel_picker(ui, cx.mem.with("levels-ch"), chans, tl!("Channel:")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + auto = widgets::secondary_button(ui, tl!("Auto"), 0.0).clicked(); + }); + }); + let chan = chans.get(ch).copied().unwrap_or(ToneChannel { key: "", label: "" }); + let mut l = read_levels(v, chan.key); + let mut e = Edit::default(); + let mut changed = false; + if auto && let Some(h) = &cx.hist { + let (lo, hi) = auto_levels(&h[ch]); + l[0] = lo; + l[2] = hi; + l[1] = 1.0; + changed = true; + e.commit = true; + } + let w = ui.available_width().min(300.0); + // Histogram. + let (hr, _) = ui.allocate_exact_size(vec2(w, 110.0), Sense::hover()); + let hr = hr.shrink2(vec2(6.0, 0.0)); + let p = ui.painter_at(hr.expand(1.0)); + p.rect_filled(hr, 0.0, t.field); + if let Some(h) = &cx.hist { + tone::draw_histogram(&p, hr, &h[ch], hist_color(&chan, &t)); + } + p.rect_stroke(hr, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside); + // Input sliders: black, gamma, white. + let (sr, sresp) = ui.allocate_exact_size(vec2(w, 14.0), Sense::click_and_drag()); + let track = sr.shrink2(vec2(6.0, 0.0)); + let xpos = |val: f32| track.left() + val / 255.0 * track.width(); + let xval = |x: f32| ((x - track.left()) / track.width() * 255.0).clamp(0.0, 255.0); + let drag_id = cx.mem.with("levels-drag"); + let mut which: Option = ui.data(|d| d.get_temp(drag_id)).flatten(); + let ctx = ui.ctx().clone(); + let pressed = |r: &egui::Response| r.is_pointer_button_down_on() && ctx.input(|i| i.pointer.primary_pressed()); + if pressed(&sresp) + && let Some(pos) = ui.input(|i| i.pointer.press_origin()) + { + which = nearest(&[xpos(l[0]), xpos(gamma_pos(l[0], l[2], l[1])), xpos(l[2])], pos.x); + } + if sresp.is_pointer_button_down_on() + && let (Some(k), Some(pos)) = (which, ui.input(|i| i.pointer.interact_pos())) + { + let x = xval(pos.x); + let before = l; + match k { + 0 => l[0] = x.min(l[2] - 2.0).round(), + 2 => l[2] = x.max(l[0] + 2.0).round(), + _ => l[1] = round(gamma_from_pos(l[0], l[2], x), 0.01), + } + changed |= l != before; + } + if which.is_some() && !sresp.is_pointer_button_down_on() { + which = None; + e.commit = true; + } + ui.data_mut(|d| d.insert_temp(drag_id, which)); + let sp = ui.painter_at(sr.expand(6.0)); + handle(&sp, xpos(l[0]), sr.top() + 2.0, Color32::BLACK, t.text_dim); + handle(&sp, xpos(gamma_pos(l[0], l[2], l[1])), sr.top() + 2.0, Color32::from_gray(128), t.text_dim); + handle(&sp, xpos(l[2]), sr.top() + 2.0, Color32::WHITE, t.text_dim); + ui.horizontal(|ui| { + let fw = ((w - 16.0) / 3.0).min(70.0); + let (mut nb, mut ng, mut nw) = (l[0], l[1], l[2]); + let gap = ((w - 3.0 * fw) / 2.0 - 12.0).max(0.0); + let r0 = widgets::value_field(ui, &mut nb, 0.0..=253.0, "", fw).accessible_name(tl!("Black")); + ui.add_space(gap); + let r1 = widgets::value_field(ui, &mut ng, 0.01..=9.99, "", fw).accessible_name(tl!("Gamma")); + ui.add_space(gap); + let r2 = widgets::value_field(ui, &mut nw, 2.0..=255.0, "", fw).accessible_name(tl!("White")); + if r0.changed() { + l[0] = nb.round().min(l[2] - 2.0); + } + if r1.changed() { + l[1] = round(ng.clamp(0.01, 9.99), 0.01); + } + if r2.changed() { + l[2] = nw.round().max(l[0] + 2.0); + } + for r in [&r0, &r1, &r2] { + changed |= r.changed(); + e.add(Edit::of(r)); + } + }); + // Output levels. + ui.add_space(6.0); + label(ui, tl!("Output Levels:")); + let (ob_r, _) = ui.allocate_exact_size(vec2(w, 10.0), Sense::hover()); + gradient_bar(ui.painter(), ob_r.shrink2(vec2(6.0, 0.0)), Color32::BLACK, bar_color(&chan, &t), false); + let (or, oresp) = ui.allocate_exact_size(vec2(w, 14.0), Sense::click_and_drag()); + let otrack = or.shrink2(vec2(6.0, 0.0)); + let oxpos = |val: f32| otrack.left() + val / 255.0 * otrack.width(); + let oval = |x: f32| ((x - otrack.left()) / otrack.width() * 255.0).clamp(0.0, 255.0); + let odrag_id = cx.mem.with("levels-odrag"); + let mut owhich: Option = ui.data(|d| d.get_temp(odrag_id)).flatten(); + if pressed(&oresp) + && let Some(pos) = ui.input(|i| i.pointer.press_origin()) + { + owhich = nearest(&[oxpos(l[3]), oxpos(l[4])], pos.x); + } + if oresp.is_pointer_button_down_on() + && let (Some(k), Some(pos)) = (owhich, ui.input(|i| i.pointer.interact_pos())) + { + let slot = if k == 0 { 3 } else { 4 }; + let nv = oval(pos.x).round(); + changed |= l[slot] != nv; + l[slot] = nv; + } + if owhich.is_some() && !oresp.is_pointer_button_down_on() { + owhich = None; + e.commit = true; + } + ui.data_mut(|d| d.insert_temp(odrag_id, owhich)); + let op = ui.painter_at(or.expand(6.0)); + handle(&op, oxpos(l[3]), or.top() + 2.0, Color32::BLACK, t.text_dim); + handle(&op, oxpos(l[4]), or.top() + 2.0, Color32::WHITE, t.text_dim); + ui.horizontal(|ui| { + let fw = ((w - 16.0) / 3.0).min(70.0); + let (mut a, mut c) = (l[3], l[4]); + let ra = widgets::value_field(ui, &mut a, 0.0..=255.0, "", fw).accessible_name(tl!("Black")); + ui.add_space((w - 2.0 * fw - 16.0).max(0.0)); + let rc = widgets::value_field(ui, &mut c, 0.0..=255.0, "", fw).accessible_name(tl!("White")); + if ra.changed() { + l[3] = a.round(); + } + if rc.changed() { + l[4] = c.round(); + } + for r in [&ra, &rc] { + changed |= r.changed(); + e.add(Edit::of(r)); + } + }); + if changed { + write_levels(v, chan.key, &l); + e.changed = true; + } + e +} diff --git a/crates/ui-egui/src/adjust_editors/session.rs b/crates/ui-egui/src/adjust_editors/session.rs new file mode 100644 index 0000000000..bb3eeeebbc --- /dev/null +++ b/crates/ui-egui/src/adjust_editors/session.rs @@ -0,0 +1,148 @@ +use super::basic::reset_color_balance; +use super::gradient_map::{gradient_presets, is_gray, swatches}; +use super::*; + +/// Root of an adjustment layer's Properties editor view state in egui memory. +pub fn layer_mem(id: LayerId) -> egui::Id { + egui::Id::unique(("adjust-layer", id.0)) +} + +/// Kinds whose Properties edits follow Photoshop's history and Reset (measured for Color Balance, +/// Photoshop 25.4): consecutive edits of the layer make one history step, and Reset first returns +/// to the settings the layer had when the panel started showing it. +fn photoshop_session(kind: &str) -> bool { + kind == "colorBalance" +} + +/// The `coalesce` key of a layer's Properties edits (one history step while they follow each +/// other, like Photoshop's "Modify … Layer"). +pub fn properties_coalesce(id: LayerId) -> String { + format!("properties-adjustment:{}", id.0) +} + +/// A layer's Properties session: document, last pass drawn, the settings the panel found, and +/// whether the panel edited them since (or since the last Reset). +type Session = (u64, u64, Value, bool); + +fn session_key(id: LayerId) -> egui::Id { + layer_mem(id).with("session") +} + +/// Remember the settings `id` (in document `doc`) had when the panel started showing it: kept +/// while it is drawn pass after pass, taken anew after a pass without it (another layer, +/// document or panel state shown). +fn track_session(ctx: &egui::Context, doc: u64, id: LayerId, committed: &Value) { + let pass = ctx.cumulative_pass_nr(); + let kept: Option = ctx.data(|d| d.get_temp(session_key(id))); + let (start, edited) = match kept { + Some((d, last, v, e)) if d == doc && last.saturating_add(1) >= pass => (v, e), + _ => (committed.clone(), false), + }; + ctx.data_mut(|d| d.insert_temp(session_key(id), (doc, pass, start, edited))); +} + +fn set_edited(ctx: &egui::Context, id: LayerId, edited: bool) { + let kept: Option = ctx.data(|d| d.get_temp(session_key(id))); + if let Some((doc, pass, start, _)) = kept { + ctx.data_mut(|d| d.insert_temp(session_key(id), (doc, pass, start, edited))); + } +} + +/// The settings layer `id` of document `doc` had when the Properties panel started showing it, +/// if the panel has edited them since (or since the last Reset). +pub fn session_start(ctx: &egui::Context, doc: u64, id: LayerId) -> Option { + let kept: Option = ctx.data(|d| d.get_temp(session_key(id))); + kept.filter(|k| k.0 == doc && k.3).map(|k| k.2) +} + +/// The Properties panel's Reset for an adjustment layer whose kind follows Photoshop's session +/// ([`photoshop_session`]): the `layer.setAdjustment` params, or None for other kinds. Edited in +/// the panel since it started showing the layer (or since the last Reset): back to the settings it +/// found (Tone choice kept); otherwise the defaults (Color Balance: [`reset_color_balance`]). +/// Either way part of the layer's edit step. +pub fn properties_reset(ctx: &egui::Context, doc: u64, id: LayerId, adj: &Adjustment) -> Option { + let kind = photocraft_engine::commands::adjustment_kind(adj); + if !photoshop_session(kind) { + return None; + } + let mut v = match session_start(ctx, doc, id) { + Some(start) => start, + None => { + let mut v = adjust_params::to_params(adj); + reset_color_balance(ctx, layer_mem(id), &mut v); + v + } + }; + set_edited(ctx, id, false); + v["layer"] = json!(id.0); + v["coalesce"] = json!(properties_coalesce(id)); + Some(v) +} + +/// The Properties-panel editor of an adjustment layer: previews live (`app.live_adjust`) while a +/// control moves and commits one `layer.setAdjustment` per gesture. +pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj: &Adjustment) { + let t = Tokens::get(ui.ctx()); + let kind = photocraft_engine::commands::adjustment_kind(adj); + match adj { + Adjustment::SelectiveColor { .. } => return crate::adjust_ui::selective_color_editor(app, ui, id, adj), + Adjustment::ColorLookup { .. } => return crate::adjust_ui::color_lookup_editor(app, ui, id, adj), + Adjustment::Invert => { + ui.label(RichText::new(tl!("Invert has no settings.")).color(t.text_faint)); + return; + } + Adjustment::Unsupported { psd_key, .. } => { + let template = "This adjustment ({key}) is kept as imported and can't be edited yet."; + ui.label(RichText::new(crate::i18n::fmt(tl!(template), &[("key", psd_key)])).color(t.text_faint)); + return; + } + _ => {} + } + let committed = adjust_params::to_params(adj); + let session = photoshop_session(kind); + if session && let Some(doc) = app.session.active().map(|s| s.doc.id.0) { + track_session(ui.ctx(), doc, id, &committed); + } + let mut values = match &app.live_adjust { + Some((l, v)) if *l == id => v.clone(), + _ => committed.clone(), + }; + let gray = app.session.active().is_some_and(|s| is_gray(s.doc.mode)); + let hist = needs_histogram(kind).then(|| tone::histograms(app, HistSource::BelowLayer(id), space_of(&values))); + let cx = EditorCx { + mem: layer_mem(id), + hist, + gray, + swatches: swatches(app), + gradients: gradient_presets(app, kind), + dialog: false, + dynamic_color_sliders: app.session.prefs().interface.dynamic_color_sliders, + isolated_curve: None, + }; + if matches!(kind, "levels" | "curves") { + crate::layer_picker::controls(app, ui, id); + } + let e = editor(ui, kind, &mut values, &cx); + if e.import_gradients { + crate::preset_files_ui::import_gradients_dialog(app); + } + if e.changed { + app.live_adjust = Some((id, values.clone())); + } + if e.commit { + if values != committed { + let rev = app.session.active().map(|s| s.revision); + let mut p = values; + p["layer"] = json!(id.0); + if session { + p["coalesce"] = json!(properties_coalesce(id)); + set_edited(ui.ctx(), id, true); + } + if let Err(err) = app.run("layer.setAdjustment", p) { + app.ui.status = err; + } + tone::keep_after_commit(app, id, rev); + } + app.live_adjust = None; + } +} From d9f198e8b9f783d988b1088e08ad726e4a8e9c09 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:18:32 +0000 Subject: [PATCH 231/259] refactor(ui-egui): split caf_ui.rs into caf_ui/ --- crates/ui-egui/src/caf_ui.rs | 1232 +----------------------- crates/ui-egui/src/caf_ui/controls.rs | 196 ++++ crates/ui-egui/src/caf_ui/lifecycle.rs | 269 ++++++ crates/ui-egui/src/caf_ui/preview.rs | 315 ++++++ crates/ui-egui/src/caf_ui/view.rs | 448 +++++++++ 5 files changed, 1242 insertions(+), 1218 deletions(-) create mode 100644 crates/ui-egui/src/caf_ui/controls.rs create mode 100644 crates/ui-egui/src/caf_ui/lifecycle.rs create mode 100644 crates/ui-egui/src/caf_ui/preview.rs create mode 100644 crates/ui-egui/src/caf_ui/view.rs diff --git a/crates/ui-egui/src/caf_ui.rs b/crates/ui-egui/src/caf_ui.rs index f0f6f8cb1e..1b5e9a97eb 100644 --- a/crates/ui-egui/src/caf_ui.rs +++ b/crates/ui-egui/src/caf_ui.rs @@ -35,6 +35,20 @@ use crate::canvas::ToolEvent; use crate::theme::Tokens; use crate::widgets; +mod controls; +mod lifecycle; +mod preview; +mod view; + +pub use controls::{control, keys, pointer}; +pub use lifecycle::{apply, cancel, commit, open}; +#[cfg(test)] +use preview::plan_params; +use preview::{Base, Preview, outline, points_limit}; +pub use view::show; +#[cfg(test)] +use view::view_image; + /// Longest side of the document proxy shown in the view (px). const PROXY_SIDE: usize = 1600; const LEFT_W: f32 = 48.0; @@ -203,63 +217,6 @@ fn stroke_json(s: &SamplingStroke) -> Value { json!({"mode": if s.add { "add" } else { "subtract" }, "size": s.size, "points": s.points}) } -/// What the plan (without the brush strokes) says: the window, the fill area and the sampling -/// option's area, over `rect`. -struct Base { - window: Rect, - rect: Rect, - hole: Vec, - base: Vec, -} - -impl Base { - /// The index into `hole` and `base` of document point `(x, y)`, when it is inside `rect`. - fn index(&self, x: f64, y: f64) -> Option { - let (xi, yi) = (x.floor() as i32, y.floor() as i32); - self.rect.contains(xi, yi).then(|| (yi - self.rect.y0) as usize * self.rect.width() as usize + (xi - self.rect.x0) as usize) - } -} - -/// A computed preview: the filled rectangle as an image, or why it failed. -#[cfg(not(target_arch = "wasm32"))] -type PreviewResult = Result<(Rect, egui::ColorImage), String>; - -/// The preview being computed or shown. -#[derive(Default)] -struct Preview { - /// Bumped whenever the state changes; a result for an older generation is dropped. - want: u64, - #[cfg(not(target_arch = "wasm32"))] - running: Option<(u64, std::sync::mpsc::Receiver, photocraft_engine::jobs::JobCtx)>, - shown: u64, - /// A finished preview waiting to be uploaded (on the UI thread, which has the context). - pending_image: Option<(Rect, egui::ColorImage)>, - tex: Option<(TextureHandle, Rect)>, - /// Screen px per document px (0 = frame the window on the next frame) and the view centre. - zoom: f32, - center: [f64; 2], - error: Option, -} - -impl Preview { - /// Takes the result of the preview of state `generation`: an image to upload, or the error, - /// which stands for that state until it changes (the same preview is not started again). - fn finish(&mut self, generation: u64, r: Result<(Rect, egui::ColorImage), String>) { - self.shown = generation; - self.tex = None; - match r { - Ok(img) => { - self.pending_image = Some(img); - self.error = None; - } - Err(e) => { - self.pending_image = None; - self.error = Some(e); - } - } - } -} - pub struct CafWorkspace { pub layer: LayerId, layer_name: String, @@ -307,30 +264,6 @@ pub struct CafWorkspace { pub error: Option, } -/// The preview's error when the sampling area has no pixels outside the fill area (the engine's -/// fill refuses that case with the same words). -const NOTHING_TO_SAMPLE: &str = "nothing to sample from: the sampling area has no pixels outside the fill area"; - -/// The plan of the current state (without strokes when `strokes` is false). -fn plan_params(w: &CafWorkspace, strokes: bool) -> Value { - let o = &w.opts; - let mut p = json!({ - "sampling": o.sampling, - "sampleAllLayers": o.sample_all, - "colorAdaptation": o.color_adaptation, - "rotationAdaptation": o.rotation, - "scale": o.scale, - "mirror": o.mirror, - "output": o.output, - "layer": w.layer.0, - "fillEdits": w.fill_edits, - }); - if strokes && !w.strokes.is_empty() { - p["samplingStrokes"] = Value::Array(w.strokes.iter().map(stroke_json).collect()); - } - p -} - impl CafWorkspace { pub fn describe(&self) -> Value { let sampled = self.mask.iter().zip(&self.hole_px).filter(|(m, h)| **m && !**h).count(); @@ -470,1142 +403,5 @@ impl CafWorkspace { } } -fn points_limit() -> String { - format!("at most {MAX_CAF_POINTS} points in all sampling strokes and lasso edits: undo some, or reset") -} - -/// The plan without strokes: the window, fill area and the option's area. Custom starts empty -/// (the window and fill area are those of Rectangular). -fn compute_base(app: &PhotocraftApp, w: &CafWorkspace) -> Result { - let st = app.session.active().ok_or("no document")?; - let mut p = plan_params(w, false); - let custom = w.opts.sampling == "custom"; - if custom { - p["sampling"] = json!("rectangular"); - } - let plan = photocraft_engine::edit_menu_cmds::content_aware_plan(&st.doc, w.layer, &p, CMD).map_err(|e| e.to_string())?; - let base = if custom { vec![false; plan.base.len()] } else { plan.base }; - Ok(Base { window: plan.window, rect: plan.rect, hole: plan.hole, base }) -} - -/// Unit edges between the fill area and the rest, in document px. -fn outline(b: &Base) -> Option> { - let (w, h) = (b.rect.width() as usize, b.rect.height() as usize); - let (ox, oy) = (b.rect.x0 as f32, b.rect.y0 as f32); - let at = |x: i64, y: i64| x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h && b.hole.get(y as usize * w + x as usize).copied().unwrap_or(false); - let mut out = Vec::new(); - for y in 0..h as i64 { - for x in 0..w as i64 { - if !at(x, y) { - continue; - } - let (fx, fy) = (ox + x as f32, oy + y as f32); - if !at(x - 1, y) { - out.push([[fx, fy], [fx, fy + 1.0]]); - } - if !at(x + 1, y) { - out.push([[fx + 1.0, fy], [fx + 1.0, fy + 1.0]]); - } - if !at(x, y - 1) { - out.push([[fx, fy], [fx + 1.0, fy]]); - } - if !at(x, y + 1) { - out.push([[fx, fy + 1.0], [fx + 1.0, fy + 1.0]]); - } - if out.len() > MAX_OUTLINE_EDGES { - return None; - } - } - } - Some(out) -} - -/// Recompute the base after a change of the fill area, the sampling option or the document. -fn rebase(app: &mut PhotocraftApp) { - let Some(w) = app.distort.caf.as_ref() else { return }; - let r = compute_base(app, w); - let Some(w) = app.distort.caf.as_mut() else { return }; - match r { - Ok(b) => { - w.set_base(b); - w.error = None; - } - Err(e) => { - w.error = Some(e); - w.restate_all(); - } - } - w.stale(); -} - -/// Opens the workspace on the active layer and its selection. -pub fn open(app: &mut PhotocraftApp) -> Result<(), String> { - if !app.session.is_enabled(CMD) { - return Err("Content-Aware Fill needs a selection on a pixel layer".into()); - } - let st = app.session.active().ok_or("no document")?; - let layer = st.active_layer.ok_or("no active layer")?; - let canvas = st.doc.bounds(); - let revision = st.revision; - let name = st.doc.layer(layer).map(|l| l.name.clone()).unwrap_or_default(); - let k = (canvas.width().max(canvas.height()) as usize).div_ceil(PROXY_SIDE).max(1); - let (pw, ph) = ((canvas.width() as usize).div_ceil(k), (canvas.height() as usize).div_ceil(k)); - let mut opts = CafOpts::default(); - if let Some(saved) = app.session.prefs().dialogs.get(REMEMBERED) { - let _ = opts.apply(saved); - } - let mut w = CafWorkspace { - layer, - layer_name: name, - canvas, - revision, - opts, - tool: CafTool::Brush, - brush_add: false, - brush_size: 20.0, - lasso_op: 0, - expand_by: 3.0, - strokes: Vec::new(), - fill_edits: Vec::new(), - undo: Vec::new(), - redo: Vec::new(), - cur: None, - lasso: None, - base: Base { window: Rect::EMPTY, rect: Rect::EMPTY, hole: Vec::new(), base: Vec::new() }, - outline: None, - k, - pw, - ph, - base_px: vec![false; pw * ph], - hole_px: vec![false; pw * ph], - mask: vec![false; pw * ph], - pressed: false, - texture_limit: 2048, - image_tex: None, - overlay_tex: None, - overlay_dirty: true, - zoom: 0.0, - center: [f64::from(canvas.x0 + canvas.x1) / 2.0, f64::from(canvas.y0 + canvas.y1) / 2.0], - hover: None, - preview: Preview::default(), - error: None, - }; - w.brush_add = w.opts.sampling == "custom"; - let base = compute_base(app, &w)?; - w.brush_size = photocraft_algo::content_aware::default_brush_size(bounds(&base)); - w.set_base(base); - w.stale(); - app.distort.caf = Some(w); - Ok(()) -} - -/// Bounds of the fill area. -fn bounds(b: &Base) -> Rect { - let w = b.rect.width() as usize; - b.hole.iter().enumerate().filter(|(_, h)| **h).fold(Rect::EMPTY, |r, (i, _)| { - let (x, y) = (b.rect.x0 + (i % w) as i32, b.rect.y0 + (i / w) as i32); - r.union(&Rect::new(x, y, x + 1, y + 1)) - }) -} - -fn remember(app: &mut PhotocraftApp, opts: &CafOpts) { - let v = opts.to_json(); - app.session.prefs.edit(|p| p.dialogs.insert(REMEMBERED.into(), v)); -} - -/// Apply: fill with the current state (one history step); the workspace stays open. -pub fn apply(app: &mut PhotocraftApp) -> Result { - let Some(w) = app.distort.caf.as_mut() else { return Err("Content-Aware Fill is not open".into()) }; - w.end_stroke(); - let p = plan_params(w, true); - let opts = w.opts.clone(); - remember(app, &opts); - let r = app.run(CMD, p); - if r.is_ok() { - refresh(app); - } - r -} - -/// OK: fill and close. A fill that fails (nothing to sample from, a fill area too large, …) -/// leaves the workspace open with the error in its panel, so the areas can be fixed and OK -/// pressed again instead of the work being thrown away. -pub fn commit(app: &mut PhotocraftApp) { - match apply(app) { - Ok(_) => close(app), - Err(e) => report(app, e), - } -} - -/// An Apply or OK that failed: the error in the panel and the status bar. -fn report(app: &mut PhotocraftApp, e: String) { - if let Some(w) = app.distort.caf.as_mut() { - w.error = Some(e.clone()); - } - app.ui.status = e; - app.ui.status_error = true; -} - -/// Cancel (button, Esc): closes; what was applied stays. The settings are kept. -pub fn cancel(app: &mut PhotocraftApp) { - if let Some(w) = app.distort.caf.as_ref() { - let opts = w.opts.clone(); - remember(app, &opts); - } - close(app); -} - -fn close(app: &mut PhotocraftApp) { - if let Some(w) = app.distort.caf.take() { - cancel_preview(w); - } -} - -#[cfg(not(target_arch = "wasm32"))] -fn cancel_preview(w: CafWorkspace) { - if let Some((_, _, job)) = w.preview.running { - job.cancel(); - } -} - -#[cfg(target_arch = "wasm32")] -fn cancel_preview(_: CafWorkspace) {} - -/// The document changed under the workspace (an Apply): new textures, a new base. -fn refresh(app: &mut PhotocraftApp) { - let rev = app.session.active().map(|s| s.revision); - if let Some(w) = app.distort.caf.as_mut() { - w.image_tex = None; - w.revision = rev.unwrap_or(w.revision); - } - rebase(app); -} - -fn undo(app: &mut PhotocraftApp) { - let Some(w) = app.distort.caf.as_mut() else { return }; - w.end_stroke(); - let Some(step) = w.undo.pop() else { return }; - let rebuild = match &step { - Step::Stroke(_) => { - w.strokes.pop(); - w.redo.push(step); - w.restate_all(); - w.stale(); - // The sampling area changed, as with a new stroke: an error a failed OK or Apply left - // in the panel no longer applies (the other steps rebase, which clears it too). - w.error = None; - false - } - Step::Fill(_) => { - w.fill_edits.pop(); - w.redo.push(step); - true - } - Step::State { sampling, strokes, fill_edits } => { - let now = Step::State { sampling: w.opts.sampling.clone(), strokes: w.strokes.clone(), fill_edits: w.fill_edits.clone() }; - w.opts.sampling = sampling.clone(); - w.strokes = strokes.clone(); - w.fill_edits = fill_edits.clone(); - w.brush_add = w.opts.sampling == "custom"; - w.redo.push(now); - true - } - }; - if rebuild { - rebase(app); - } -} - -fn redo(app: &mut PhotocraftApp) { - let Some(w) = app.distort.caf.as_mut() else { return }; - w.end_stroke(); - let Some(step) = w.redo.pop() else { return }; - let rebuild = match &step { - Step::Stroke(s) => { - w.strokes.push(s.clone()); - w.undo.push(step); - w.restate_all(); - w.stale(); - w.error = None; - false - } - Step::Fill(e) => { - w.fill_edits.push(e.clone()); - w.undo.push(step); - true - } - Step::State { sampling, strokes, fill_edits } => { - let now = Step::State { sampling: w.opts.sampling.clone(), strokes: w.strokes.clone(), fill_edits: w.fill_edits.clone() }; - w.opts.sampling = sampling.clone(); - w.strokes = strokes.clone(); - w.fill_edits = fill_edits.clone(); - w.brush_add = w.opts.sampling == "custom"; - w.undo.push(now); - true - } - }; - if rebuild { - rebase(app); - } -} - -/// A lasso edit of the fill area (or Expand / Contract), undoable. -fn fill_edit(app: &mut PhotocraftApp, edit: Value) { - let Some(w) = app.distort.caf.as_mut() else { return }; - w.end_stroke(); - // The engine's limits, kept here (see `begin_stroke`). - if w.fill_edits.len() >= MAX_CAF_EDITS { - w.error = Some(format!("at most {MAX_CAF_EDITS} lasso edits: undo some, or reset the fill area")); - return; - } - if w.points_used() + edit.get("points").and_then(Value::as_array).map_or(0, Vec::len) > MAX_CAF_POINTS { - w.error = Some(points_limit()); - return; - } - w.fill_edits.push(edit.clone()); - w.push(Step::Fill(edit)); - rebase(app); - // An edit that empties the fill area is refused (the plan says so): undo it. - if app.distort.caf.as_ref().is_some_and(|w| w.error.is_some()) { - let msg = app.distort.caf.as_ref().and_then(|w| w.error.clone()); - undo(app); - if let Some(w) = app.distort.caf.as_mut() { - w.redo.clear(); - w.error = msg; - } - } -} - -/// A new sampling option (Auto, Rectangular, Custom): the brush strokes start over and the brush -/// takes the option's mode (Custom adds, the others subtract). -fn set_sampling(app: &mut PhotocraftApp, sampling: &str) { - let Some(w) = app.distort.caf.as_mut() else { return }; - if w.opts.sampling == sampling && w.strokes.is_empty() { - return; - } - w.end_stroke(); - let prev = Step::State { sampling: w.opts.sampling.clone(), strokes: std::mem::take(&mut w.strokes), fill_edits: w.fill_edits.clone() }; - w.push(prev); - w.opts.sampling = sampling.to_string(); - w.brush_add = sampling == "custom"; - rebase(app); -} - -/// Reset buttons: the sampling options, the fill settings, or everything. -fn reset(app: &mut PhotocraftApp, what: &str) { - let Some(w) = app.distort.caf.as_mut() else { return }; - let d = CafOpts::default(); - match what { - "fill" => { - w.opts.color_adaptation = d.color_adaptation; - w.opts.rotation = d.rotation; - w.opts.scale = d.scale; - w.opts.mirror = d.mirror; - w.stale(); - } - "sampling" => { - w.opts.sample_all = false; - set_sampling(app, "auto"); - } - "lasso" => { - if !w.fill_edits.is_empty() { - let prev = Step::State { sampling: w.opts.sampling.clone(), strokes: w.strokes.clone(), fill_edits: std::mem::take(&mut w.fill_edits) }; - w.push(prev); - rebase(app); - } - } - _ => { - let prev = - Step::State { sampling: w.opts.sampling.clone(), strokes: std::mem::take(&mut w.strokes), fill_edits: std::mem::take(&mut w.fill_edits) }; - w.push(prev); - w.opts = CafOpts::default(); - w.brush_add = false; - rebase(app); - } - } -} - -/// Control channel: `edit.contentAwareFill {"ui": {...}}` while the workspace is open. -pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result { - let flag = |k: &str| ui.get(k).and_then(Value::as_bool) == Some(true); - if flag("cancel") { - cancel(app); - return Ok(json!({"cancelled": true})); - } - let before = app.distort.caf.as_ref().ok_or("Content-Aware Fill is not open")?.opts.clone(); - { - let w = app.distort.caf.as_mut().ok_or("Content-Aware Fill is not open")?; - let mut o = w.opts.clone(); - o.apply(ui)?; - // The sampling option goes through `set_sampling` (it resets the strokes). - let sampling = std::mem::replace(&mut o.sampling, w.opts.sampling.clone()); - w.opts = o; - if let Some(t) = ui.get("tool").and_then(Value::as_str) { - w.tool = CafTool::from_name(t).ok_or(format!("bad tool `{t}` (brush|lasso|hand|zoom)"))?; - } - if let Some(n) = ui.get("brushSize").and_then(Value::as_f64).filter(|n| n.is_finite()) { - w.brush_size = n.clamp(1.0, 5000.0); - } - if let Some(m) = ui.get("brushMode").and_then(Value::as_str) { - w.brush_add = m == "add"; - } - if let Some(m) = ui.get("lassoMode").and_then(Value::as_str) { - w.lasso_op = LASSO_OPS.iter().position(|o| *o == m).ok_or(format!("bad lassoMode `{m}`"))?; - } - if let Some(n) = ui.get("expandBy").and_then(Value::as_f64).filter(|n| n.is_finite()) { - w.expand_by = (n as f32).clamp(1.0, 100.0); - } - if sampling != w.opts.sampling { - set_sampling(app, &sampling); - } - } - let after = app.distort.caf.as_ref().map(|w| w.opts.clone()); - if after.as_ref().is_some_and(|a| a.sample_all != before.sample_all) { - rebase(app); - } else if after.as_ref().is_some_and(|a| *a != before) - && let Some(w) = app.distort.caf.as_mut() - { - w.stale(); - w.restate_all(); - } - if let Some(s) = ui.get("stroke") { - let pts: Vec<[f64; 2]> = serde_json::from_value(s.get("points").cloned().unwrap_or(Value::Null)).map_err(|e| format!("bad stroke points: {e}"))?; - let w = app.distort.caf.as_mut().ok_or("Content-Aware Fill is not open")?; - if let Some(n) = s.get("size").and_then(Value::as_f64) { - w.brush_size = n.clamp(1.0, 5000.0); - } - let alt = s.get("alt").and_then(Value::as_bool).unwrap_or(false); - if let Some(first) = pts.first() { - w.begin_stroke(*first, alt); - for p in &pts[1..] { - w.extend_stroke(*p); - } - w.end_stroke(); - } - } - if let Some(l) = ui.get("lasso") { - let pts: Vec<[f64; 2]> = serde_json::from_value(l.get("points").cloned().unwrap_or(Value::Null)).map_err(|e| format!("bad lasso points: {e}"))?; - let op = match l.get("op").and_then(Value::as_str) { - Some(o) if LASSO_OPS.contains(&o) => o.to_string(), - Some(o) => return Err(format!("bad lasso op `{o}`")), - None => LASSO_OPS[app.distort.caf.as_ref().map_or(0, |w| w.lasso_op)].to_string(), - }; - fill_edit(app, json!({"op": op, "points": pts})); - } - for k in ["expand", "contract"] { - if let Some(n) = ui.get(k).and_then(Value::as_f64) { - fill_edit(app, json!({"op": k, "by": n.clamp(1.0, 100.0)})); - } - } - if let Some(r) = ui.get("reset").and_then(Value::as_str) { - reset(app, r); - } - if flag("undo") { - undo(app); - } - if flag("redo") { - redo(app); - } - if flag("apply") { - apply(app)?; - } - if flag("waitPreview") { - wait_preview(app)?; - } - // OK last, with the settings given alongside. A failed fill keeps the workspace open, as - // the OK button does. - if flag("commit") { - let r = apply(app); - match &r { - Ok(_) => close(app), - Err(e) => report(app, e.clone()), - } - return r.map(|v| json!({"committed": true, "result": v})); - } - Ok(app.distort.caf.as_ref().map(CafWorkspace::describe).unwrap_or(Value::Null)) -} - -/// Computes the preview now, on this thread (tests and the control channel). -fn wait_preview(app: &mut PhotocraftApp) -> Result<(), String> { - let (doc, layer, p, want, limit) = { - let w = app.distort.caf.as_ref().ok_or("Content-Aware Fill is not open")?; - let st = app.session.active().ok_or("no document")?; - (st.doc.clone(), w.layer, plan_params(w, true), w.preview.want, w.texture_limit) - }; - let r = compute_preview(&doc, layer, &p, &photocraft_raster::Interrupt::NONE, limit); - let w = app.distort.caf.as_mut().ok_or("Content-Aware Fill is not open")?; - let err = r.as_ref().err().cloned(); - w.preview.finish(want, r); - err.map_or(Ok(()), Err) -} - -/// The filled rectangle as an image (what Apply would write there), as a texture no wider than -/// `max_side`: past the device's limit it is box-averaged to fit (the rectangle it is drawn over -/// stays the plan's). -fn compute_preview( - doc: &photocraft_doc::Document, - layer: LayerId, - p: &Value, - ctl: &photocraft_raster::Interrupt, - max_side: usize, -) -> Result<(Rect, egui::ColorImage), String> { - let plan = photocraft_engine::edit_menu_cmds::content_aware_plan_with(doc, layer, p, CMD, ctl).map_err(|e| match e { - photocraft_engine::EngineError::Cancelled => "cancelled".to_string(), - e => e.to_string(), - })?; - // Patches come only from the sampling area outside the fill area. With none (the Sampling - // Brush erased it all, a Custom area not painted yet) the fill would come out black, so the - // preview says so instead of showing that. - if !plan.source.iter().any(|s| *s) { - return Err(NOTHING_TO_SAMPLE.into()); - } - let (w, h) = (plan.rect.width() as usize, plan.rect.height() as usize); - let n = plan.fmt.channels(); - let filled = - photocraft_algo::content_aware::fill_with(w, h, n, &plan.img, &plan.hole, &plan.source, &plan.opts, ctl).map_err(|_| "cancelled".to_string())?; - let own = plan.layer_pixels(); - // Pixel `i`: the fill over the fill area (a partly selected pixel by its coverage), the - // layer's own pixels elsewhere. - let pixel = |i: usize| -> [f32; 4] { - let src = if plan.hole[i] { &filled[i * n..(i + 1) * n] } else { &own[i * n..(i + 1) * n] }; - let mut c = photocraft_raster::to_rgba(&plan.fmt, src); - if plan.hole[i] { - let k = plan.cover[i]; - let under = photocraft_raster::to_rgba(&plan.fmt, &own[i * n..(i + 1) * n]); - for j in 0..4 { - c[j] = under[j] + (c[j] - under[j]) * k; - } - } - c - }; - let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - let color = |c: [f32; 4]| Color32::from_rgba_unmultiplied(b(c[0]), b(c[1]), b(c[2]), b(c[3])); - let f = crate::filter_preview_ui::texture_factor(w as u32, h as u32, max_side) as usize; - if f == 1 { - let px = (0..w * h).map(|i| color(pixel(i))).collect(); - return Ok((plan.rect, egui::ColorImage::new([w, h], px))); - } - let (tw, th) = (w.div_ceil(f), h.div_ceil(f)); - let mut px = Vec::with_capacity(tw * th); - for ty in 0..th { - for tx in 0..tw { - // The block's premultiplied average. - let (mut acc, mut count) = ([0.0f32; 4], 0.0f32); - for y in ty * f..((ty + 1) * f).min(h) { - for x in tx * f..((tx + 1) * f).min(w) { - let c = pixel(y * w + x); - for j in 0..3 { - acc[j] += c[j] * c[3]; - } - acc[3] += c[3]; - count += 1.0; - } - } - let c = if acc[3] > 0.0 { [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3] / count] } else { [0.0; 4] }; - px.push(color(c)); - } - } - Ok((plan.rect, egui::ColorImage::new([tw, th], px))) -} - -/// Starts a background preview when the shown one is out of date (and the pointer is up), and -/// collects a finished one. -#[cfg(not(target_arch = "wasm32"))] -fn drive_preview(app: &mut PhotocraftApp, ctx: &egui::Context, dragging: bool) { - let doc = app.session.active().map(|s| s.doc.clone()); - let Some(w) = app.distort.caf.as_mut() else { return }; - let pv = &mut w.preview; - if let Some((generation, rx, _)) = &pv.running { - match rx.try_recv() { - Ok(r) => { - let generation = *generation; - pv.running = None; - if generation == pv.want { - match r { - Err(e) if e == "cancelled" => {} - r => pv.finish(generation, r), - } - } - } - Err(std::sync::mpsc::TryRecvError::Empty) => { - // Superseded: stop it, a new one starts when it has gone. - if *generation != pv.want - && let Some((_, _, job)) = &pv.running - { - job.cancel(); - } - ctx.request_repaint_after(std::time::Duration::from_millis(50)); - return; - } - Err(std::sync::mpsc::TryRecvError::Disconnected) => pv.running = None, - } - } - if pv.running.is_some() || pv.shown == pv.want || dragging { - return; - } - let Some(doc) = doc else { return }; - let (layer, p, generation, limit) = (w.layer, plan_params(w, true), w.preview.want, w.texture_limit); - let (tx, rx) = std::sync::mpsc::sync_channel(1); - let job = photocraft_engine::jobs::JobCtx::new(); - let work = job.clone(); - let repaint = ctx.clone(); - let spawned = std::thread::Builder::new().name("caf-preview".into()).spawn(move || { - let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| work.stage(0.0, 1.0, "", |ctl| compute_preview(&doc, layer, &p, ctl, limit)))) - .unwrap_or_else(|_| Err("the preview failed".into())); - let _ = tx.send(r); - repaint.request_repaint(); - }); - match spawned { - Ok(_) => w.preview.running = Some((generation, rx, job)), - Err(e) => w.preview.error = Some(format!("could not start the preview: {e}")), - } -} - -/// The web build has no threads: the preview is computed when the pointer comes up. -#[cfg(target_arch = "wasm32")] -fn drive_preview(app: &mut PhotocraftApp, _ctx: &egui::Context, dragging: bool) { - let stale = app.distort.caf.as_ref().is_some_and(|w| w.preview.shown != w.preview.want); - if stale && !dragging { - let _ = wait_preview(app); - } -} - -/// Pointer in document coordinates (from the view or the control channel). -pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { - let Some(w) = app.distort.caf.as_mut() else { return }; - match (w.tool, ev) { - (CafTool::Brush, ToolEvent::Down { x, y, .. }) => w.begin_stroke([x, y], mods.alt), - (CafTool::Brush, ToolEvent::Move { x, y, .. }) => { - w.hover = Some([x, y]); - w.extend_stroke([x, y]); - } - (CafTool::Brush, ToolEvent::Up { x, y }) => { - w.extend_stroke([x, y]); - w.end_stroke(); - } - (CafTool::Lasso, ToolEvent::Down { x, y, .. }) => { - // Shift adds, Alt subtracts, both intersect (as Photoshop's selection tools). - let op = match (mods.shift, mods.alt) { - (true, true) => 3, - (true, false) => 1, - (false, true) => 2, - _ => w.lasso_op, - }; - w.lasso = Some((op, vec![[x, y]])); - } - (CafTool::Lasso, ToolEvent::Move { x, y, .. }) => { - if let Some((_, pts)) = &mut w.lasso - && pts.last().is_none_or(|l| l[0] != x || l[1] != y) - { - pts.push([x, y]); - } - } - (CafTool::Lasso, ToolEvent::Up { .. }) => { - if let Some((op, pts)) = w.lasso.take() - && pts.len() >= 3 - { - fill_edit(app, json!({"op": LASSO_OPS[op], "points": pts})); - } - } - (CafTool::Zoom, ToolEvent::Down { x, y, .. }) => { - let f = if mods.alt { 0.5 } else { 2.0 }; - w.zoom = (w.zoom * f).clamp(0.01, 32.0); - w.center = [x, y]; - } - _ => {} - } -} - -pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) { - let cmd_shift = egui::Modifiers::COMMAND | egui::Modifiers::SHIFT; - if ctx.input_mut(|i| i.consume_key(cmd_shift, egui::Key::Z)) { - redo(app); - return; - } - if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::Z)) { - undo(app); - return; - } - let Some(w) = app.distort.caf.as_mut() else { return }; - // Ctrl+H hides the overlay (Hide Extras). - if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::H)) { - w.opts.show_overlay = !w.opts.show_overlay; - w.overlay_dirty = true; - } - if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::OpenBracket)) { - w.brush_size = (w.brush_size * 0.9).max(1.0).round(); - } - if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::CloseBracket)) { - w.brush_size = (w.brush_size * 1.1).min(5000.0).round().max(w.brush_size + 1.0); - } - for (k, t) in [(egui::Key::B, CafTool::Brush), (egui::Key::L, CafTool::Lasso), (egui::Key::H, CafTool::Hand), (egui::Key::Z, CafTool::Zoom)] { - if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, k)) { - w.tool = t; - } - } -} - -fn tool_icon(t: CafTool) -> &'static str { - match t { - CafTool::Brush => "brush", - CafTool::Lasso => "lasso", - CafTool::Hand => "hand", - CafTool::Zoom => "zoom-in", - } -} - -fn tool_tip(t: CafTool) -> String { - match t { - CafTool::Brush => format!("{} (B)", tl!("Sampling Brush Tool")), - CafTool::Lasso => format!("{} (L)", tl!("Lasso Tool")), - CafTool::Hand => format!("{} (H)", tl!("Hand Tool")), - CafTool::Zoom => format!("{} (Z)", tl!("Zoom Tool")), - } -} - -/// A view: screen px per document px and the document point at the centre of `area`. -#[derive(Clone, Copy)] -struct View { - area: ERect, - zoom: f32, - center: [f64; 2], -} - -impl View { - fn to_screen(self, p: [f64; 2]) -> Pos2 { - let c = self.area.center(); - pos2(c.x + ((p[0] - self.center[0]) as f32) * self.zoom, c.y + ((p[1] - self.center[1]) as f32) * self.zoom) - } - fn to_doc(self, s: Pos2) -> [f64; 2] { - let c = self.area.center(); - [self.center[0] + f64::from((s.x - c.x) / self.zoom), self.center[1] + f64::from((s.y - c.y) / self.zoom)] - } - fn rect(self, r: Rect) -> ERect { - ERect::from_min_max(self.to_screen([f64::from(r.x0), f64::from(r.y0)]), self.to_screen([f64::from(r.x1), f64::from(r.y1)])) - } -} - -/// Upload what changed: the document proxy, the overlay, a finished preview. -fn upload(app: &mut PhotocraftApp, ctx: &egui::Context) { - let need_image = app.distort.caf.as_ref().is_some_and(|w| w.image_tex.is_none()); - if need_image { - let img = view_image(app); - if let (Some(w), Some(img)) = (app.distort.caf.as_mut(), img) { - w.image_tex = Some(ctx.load_texture("caf-image", img, egui::TextureOptions::LINEAR)); - } - } - let Some(w) = app.distort.caf.as_mut() else { return }; - if w.overlay_dirty || w.overlay_tex.is_none() { - w.overlay_dirty = false; - let [r, g, b] = w.opts.color; - let a = (w.opts.opacity / 100.0 * 255.0).round() as u8; - let tint = Color32::from_rgba_unmultiplied(r, g, b, a); - // The tint marks the sampling area (with Indicates: Excluded Area, what is left out); - // the fill area is never tinted. - let px: Vec = - w.mask.iter().zip(&w.hole_px).map(|(m, h)| if w.opts.show_overlay && !*h && *m != w.opts.excluded { tint } else { Color32::TRANSPARENT }).collect(); - let img = egui::ColorImage::new([w.pw, w.ph], px); - match &mut w.overlay_tex { - Some(t) => t.set(img, egui::TextureOptions::NEAREST), - None => w.overlay_tex = Some(ctx.load_texture("caf-overlay", img, egui::TextureOptions::NEAREST)), - } - } - if let Some((rect, img)) = w.preview.pending_image.take() { - w.preview.tex = Some((ctx.load_texture("caf-preview", img, egui::TextureOptions::LINEAR), rect)); - } -} - -/// The document as the view shows it: the visible layers composited, as on the canvas (so an -/// Apply to a new layer shows), reduced to the proxy. -fn view_image(app: &PhotocraftApp) -> Option { - let w = app.distort.caf.as_ref()?; - let st = app.session.active()?; - let buf = photocraft_compose::render_reduced(&st.doc, w.pw as u32, w.ph as u32); - let (display, _) = crate::canvas::canvas_display(app, &st.doc, None); - Some(crate::canvas::display_image(display.as_deref(), &buf)) -} - -/// Draws the workspace (a full-window layer over the app). -pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { - // An Apply (or anything else) changed the document: refresh. - let rev = app.session.active().map(|s| s.revision); - if app.distort.caf.as_ref().is_some_and(|w| Some(w.revision) != rev) { - refresh(app); - } - upload(app, ctx); - let t = Tokens::get(ctx); - let screen = ctx.content_rect(); - let mut action: Option<&str> = None; - let mut events: Vec = Vec::new(); - let mut mods = egui::Modifiers::NONE; - let mut new_sampling: Option<&str> = None; - let mut fill_btn: Option = None; - let mut reset_what: Option<&str> = None; - let mut rebase_needed = false; - let mut dragging = false; - egui::Area::new(egui::Id::unique("caf-workspace")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| { - let Some(w) = app.distort.caf.as_mut() else { return }; - let before = w.opts.clone(); - w.texture_limit = ctx.input(|i| i.max_texture_side); - let (full, _) = ui.allocate_exact_size(screen.size(), Sense::hover()); - let painter = ui.painter().clone(); - painter.rect_filled(full, 0.0, t.chrome); - // Title strip. - let title = ERect::from_min_size(full.min, vec2(full.width(), 30.0)); - painter.rect_filled(title, 0.0, t.dock); - painter.line_segment([title.left_bottom(), title.right_bottom()], Stroke::new(1.0, t.separator)); - let pct = if w.zoom > 0.0 { w.zoom * 100.0 } else { 100.0 }; - painter.text( - title.center(), - Align2::CENTER_CENTER, - format!("{} ({}, {:.0}%)", tl!("Content-Aware Fill…").trim_end_matches('…'), w.layer_name, pct), - FontId::proportional(13.0), - t.text, - ); - // Options bar. - let bar = ERect::from_min_size(pos2(full.left(), title.bottom()), vec2(full.width(), BAR_H)); - painter.rect_filled(bar, 0.0, t.dock); - painter.line_segment([bar.left_bottom(), bar.right_bottom()], Stroke::new(1.0, t.separator)); - let mut bui = - ui.new_child(egui::UiBuilder::new().max_rect(bar.shrink2(vec2(LEFT_W + 8.0, 4.0))).layout(egui::Layout::left_to_right(egui::Align::Center))); - match w.tool { - CafTool::Brush => { - if crate::icons::button(&mut bui, "plus", 26.0, w.brush_add, tl!("Add")).clicked() { - w.brush_add = true; - } - if crate::icons::button(&mut bui, "minus", 26.0, !w.brush_add, tl!("Subtract")).clicked() { - w.brush_add = false; - } - bui.add_space(8.0); - bui.label(tl!("Size:")); - let mut size = w.brush_size as f32; - if widgets::value_field(&mut bui, &mut size, 1.0..=5000.0, " px", 64.0).accessible_name(tl!("Size:")).changed() { - w.brush_size = f64::from(size); - } - } - CafTool::Lasso => { - // The selection tools' mode buttons (the lasso here edits the fill area). - let tips = [ - tl!("New selection").to_string(), - crate::i18n::fmt(tl!("Add to selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift"))]), - crate::i18n::fmt(tl!("Subtract from selection ({key})"), &[("key", &crate::shortcuts::pretty("Alt"))]), - crate::i18n::fmt(tl!("Intersect with selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift+Alt"))]), - ]; - for (i, (icon, tip)) in ["square", "plus", "minus", "squares-subtract"].into_iter().zip(tips.iter()).enumerate() { - if crate::icons::button(&mut bui, icon, 26.0, w.lasso_op == i, tip).clicked() { - w.lasso_op = i; - } - } - bui.add_space(8.0); - if widgets::secondary_button(&mut bui, tl!("Expand"), 70.0).clicked() { - fill_btn = Some(json!({"op": "expand", "by": w.expand_by})); - } - if widgets::secondary_button(&mut bui, tl!("Contract"), 70.0).clicked() { - fill_btn = Some(json!({"op": "contract", "by": w.expand_by})); - } - widgets::value_field(&mut bui, &mut w.expand_by, 1.0..=100.0, " px", 56.0).accessible_name(tl!("Expand")); - if crate::icons::button(&mut bui, "undo-2", 26.0, false, tl!("Reset")).clicked() { - reset_what = Some("lasso"); - } - } - _ => {} - } - let body = ERect::from_min_max(pos2(full.left(), bar.bottom()), full.max); - // Left tool strip. - let left = ERect::from_min_size(pos2(full.left(), title.bottom()), vec2(LEFT_W, full.height() - title.height())); - painter.rect_filled(left, 0.0, t.dock); - painter.line_segment([left.right_top(), left.right_bottom()], Stroke::new(1.0, t.separator)); - let mut strip = ui.new_child(egui::UiBuilder::new().max_rect(left.shrink2(vec2(6.0, 8.0)))); - strip.spacing_mut().item_spacing.y = 4.0; - for tool in [CafTool::Brush, CafTool::Lasso, CafTool::Hand, CafTool::Zoom] { - if crate::icons::button(&mut strip, tool_icon(tool), 34.0, w.tool == tool, &tool_tip(tool)).clicked() { - w.tool = tool; - } - } - // Right: the Content-Aware Fill panel. - let right = ERect::from_min_size(pos2(body.right() - PANEL_W, body.top()), vec2(PANEL_W, body.height())); - painter.rect_filled(right, 0.0, t.dock); - painter.line_segment([right.left_top(), right.left_bottom()], Stroke::new(1.0, t.separator)); - let mut props = - ui.new_child(egui::UiBuilder::new().max_rect(ERect::from_min_max(right.min + vec2(14.0, 12.0), pos2(right.right() - 14.0, right.bottom() - 60.0)))); - egui::ScrollArea::vertical().id_salt("caf-props").show(&mut props, |ui| { - ui.spacing_mut().item_spacing.y = 6.0; - egui::CollapsingHeader::new(tl!("Sampling Area Overlay")).id_salt("caf-overlay").default_open(false).show(ui, |ui| { - widgets::checkbox(ui, &mut w.opts.show_overlay, tl!("Show Sampling Area")); - widgets::slider_row(ui, tl!("Opacity"), &mut w.opts.opacity, 0.0..=100.0, "%", None); - ui.horizontal(|ui| { - ui.label(tl!("Color")); - widgets::color_edit_button_srgb(ui, &mut w.opts.color); - ui.add_space(8.0); - ui.label(tl!("Indicates")); - widgets::dropdown( - ui, - "caf-indicates", - tl!("Indicates"), - &mut w.opts.excluded, - &[(false, tl!("Sampling Area")), (true, tl!("Excluded Area"))], - 120.0, - ); - }); - }); - widgets::hairline(ui); - ui.horizontal(|ui| { - widgets::section_label(ui, tl!("Sampling Area Options")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::icons::button(ui, "undo-2", 22.0, false, tl!("Reset")).clicked() { - reset_what = Some("sampling"); - } - }); - }); - ui.horizontal(|ui| { - for (k, l) in [("auto", tl!("Auto")), ("rectangular", tl!("Rectangular")), ("custom", tl!("Custom"))] { - if ui.selectable_label(w.opts.sampling == k, l).clicked() && w.opts.sampling != k { - new_sampling = Some(k); - } - } - }); - if widgets::checkbox(ui, &mut w.opts.sample_all, tl!("Sample All Layers")).changed() { - rebase_needed = true; - } - widgets::hairline(ui); - ui.horizontal(|ui| { - widgets::section_label(ui, tl!("Fill Settings")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::icons::button(ui, "undo-2", 22.0, false, tl!("Reset")).clicked() { - reset_what = Some("fill"); - } - }); - }); - ui.horizontal(|ui| { - ui.label(tl!("Color Adaptation")); - let o = [ - ("none".to_string(), tl!("None")), - ("default".to_string(), tl!("Default")), - ("high".to_string(), tl!("High")), - ("veryHigh".to_string(), tl!("Very High")), - ]; - widgets::dropdown(ui, "caf-color", tl!("Color Adaptation"), &mut w.opts.color_adaptation, &o, 110.0); - }); - ui.horizontal(|ui| { - ui.label(tl!("Rotation Adaptation")); - let o = [ - ("none".to_string(), tl!("None")), - ("low".to_string(), tl!("Low")), - ("medium".to_string(), tl!("Medium")), - ("high".to_string(), tl!("High")), - ("full".to_string(), tl!("Full")), - ]; - widgets::dropdown(ui, "caf-rotation", tl!("Rotation Adaptation"), &mut w.opts.rotation, &o, 110.0); - }); - ui.horizontal(|ui| { - widgets::checkbox(ui, &mut w.opts.scale, tl!("Scale")); - widgets::checkbox(ui, &mut w.opts.mirror, tl!("Mirror")); - }); - widgets::hairline(ui); - widgets::section_label(ui, tl!("Output Settings")); - ui.horizontal(|ui| { - ui.label(tl!("Output To")); - let o = - [("current".to_string(), tl!("Current Layer")), ("new".to_string(), tl!("New Layer")), ("duplicate".to_string(), tl!("Duplicate Layer"))]; - widgets::dropdown(ui, "caf-output", tl!("Output To"), &mut w.opts.output, &o, 140.0); - }); - if let Some(e) = w.error.as_ref().or(w.preview.error.as_ref()) { - ui.label(egui::RichText::new(e.as_str()).color(t.danger).size(11.0)); - } - }); - // Footer, in Photoshop's order on every platform: reset all at the left, then OK, Apply, - // Cancel against the right edge. - let foot = ERect::from_min_size(pos2(right.left() + 10.0, right.bottom() - 48.0), vec2(PANEL_W - 20.0, 32.0)); - let mut fb = ui.new_child(egui::UiBuilder::new().max_rect(foot).layout(egui::Layout::right_to_left(egui::Align::Center))); - if widgets::secondary_button(&mut fb, tl!("Cancel"), 70.0).clicked() { - action = Some("cancel"); - } - if widgets::secondary_button(&mut fb, tl!("Apply"), 70.0).clicked() { - action = Some("apply"); - } - if widgets::primary_button(&mut fb, tl!("OK"), 64.0).clicked() { - action = Some("ok"); - } - if crate::icons::button(&mut fb, "undo-2", 24.0, false, tl!("Reset")).clicked() { - reset_what = Some("all"); - } - // The Preview panel. - let pv_rect = ERect::from_min_size(pos2(right.left() - PREVIEW_W, body.top()), vec2(PREVIEW_W, body.height())); - painter.rect_filled(pv_rect, 0.0, t.dock); - painter.line_segment([pv_rect.left_top(), pv_rect.left_bottom()], Stroke::new(1.0, t.separator)); - painter.text(pv_rect.left_top() + vec2(12.0, 10.0), Align2::LEFT_TOP, tl!("Preview"), FontId::proportional(12.0), t.text); - let pv_area = ERect::from_min_max(pv_rect.min + vec2(0.0, 30.0), pv_rect.max - vec2(0.0, 44.0)); - painter.rect_filled(pv_area, 0.0, t.canvas); - if w.preview.zoom <= 0.0 { - // Opens framed on the sampling window, as Photoshop's. - let win = w.base.window; - if !win.is_empty() { - w.preview.zoom = (pv_area.width() / win.width().max(win.height()) as f32).clamp(0.01, 32.0); - w.preview.center = [f64::from(win.x0 + win.x1) / 2.0, f64::from(win.y0 + win.y1) / 2.0]; - } - } - let pv = View { area: pv_area, zoom: w.preview.zoom.max(0.01), center: w.preview.center }; - let pclip = painter.with_clip_rect(pv_area); - let uv = ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); - let img_rect = pv.rect(w.canvas); - widgets::checker(&pclip, img_rect.intersect(pv_area), 8.0); - if let Some(tex) = &w.image_tex { - pclip.image(tex.id(), img_rect, uv, Color32::WHITE); - } - if let Some((tex, r)) = &w.preview.tex { - pclip.image(tex.id(), pv.rect(*r), uv, Color32::WHITE); - } - if w.preview.shown != w.preview.want { - // Being recomputed: a spinner in the corner. - let sp = ERect::from_min_size(pv_area.right_bottom() - vec2(26.0, 26.0), vec2(18.0, 18.0)); - ui.put(sp, egui::Spinner::new().size(16.0)); - } - let presp = ui.interact(pv_area, egui::Id::unique("caf-preview-view"), Sense::click_and_drag()); - if presp.dragged() { - let d = presp.drag_delta(); - w.preview.center = [w.preview.center[0] - f64::from(d.x / pv.zoom), w.preview.center[1] - f64::from(d.y / pv.zoom)]; - } - if presp.hovered() { - let scroll = ui.input(|i| i.smooth_scroll_delta.y); - if scroll != 0.0 { - w.preview.zoom = (w.preview.zoom * (scroll / 200.0).exp()).clamp(0.01, 32.0); - } - } - let zrow = ERect::from_min_size(pos2(pv_rect.left() + 10.0, pv_rect.bottom() - 38.0), vec2(PREVIEW_W - 20.0, 30.0)); - let mut zr = ui.new_child(egui::UiBuilder::new().max_rect(zrow).layout(egui::Layout::left_to_right(egui::Align::Center))); - let mut pct = (w.preview.zoom * 100.0).round(); - if widgets::value_field(&mut zr, &mut pct, 1.0..=3200.0, "%", 64.0).accessible_name(tl!("Zoom")).changed() { - w.preview.zoom = pct / 100.0; - } - let mut lz = pct.max(1.0).ln(); - if zr.add(egui::Slider::new(&mut lz, 0.0..=3200f32.ln()).show_value(false)).accessible_name(tl!("Zoom")).changed() { - w.preview.zoom = lz.exp() / 100.0; - } - // The document view. - let area = ERect::from_min_max(pos2(left.right(), body.top()), pos2(pv_rect.left(), body.bottom())); - painter.rect_filled(area, 0.0, t.canvas); - let (cw, chh) = (w.canvas.width() as f32, w.canvas.height() as f32); - if w.zoom <= 0.0 { - w.zoom = ((area.width() - 40.0) / cw).min((area.height() - 40.0) / chh).clamp(0.01, 4.0); - } - let resp = ui.interact(area, egui::Id::unique("caf-view"), Sense::click_and_drag()); - if resp.hovered() { - let scroll = ui.input(|i| i.smooth_scroll_delta.y); - if scroll != 0.0 - && let Some(hp) = resp.hover_pos() - { - let v = View { area, zoom: w.zoom, center: w.center }; - let before = v.to_doc(hp); - w.zoom = (w.zoom * (scroll / 200.0).exp()).clamp(0.01, 32.0); - let after = View { area, zoom: w.zoom, center: w.center }.to_doc(hp); - w.center = [w.center[0] + before[0] - after[0], w.center[1] + before[1] - after[1]]; - } - } - let v = View { area, zoom: w.zoom, center: w.center }; - let clip = painter.with_clip_rect(area); - let img = v.rect(w.canvas); - widgets::checker(&clip, img.intersect(area), 8.0); - if let Some(tex) = &w.image_tex { - clip.image(tex.id(), img, uv, Color32::WHITE); - } - if let Some(tex) = &w.overlay_tex { - // The proxy's blocks are `k` document px; its last row and column may reach past the - // canvas, so the overlay is clipped to it. - let pr = ERect::from_min_size(img.min, vec2((w.pw * w.k) as f32 * v.zoom, (w.ph * w.k) as f32 * v.zoom)); - clip.with_clip_rect(img.intersect(area)).image(tex.id(), pr, uv, Color32::WHITE); - } - // The fill area's outline (marching ants: black dashes on white). - let phase = (ui.input(|i| i.time) * 8.0) as usize; - match &w.outline { - Some(edges) => { - for e in edges { - let (a, b) = (v.to_screen([f64::from(e[0][0]), f64::from(e[0][1])]), v.to_screen([f64::from(e[1][0]), f64::from(e[1][1])])); - let dark = ((e[0][0] + e[0][1]) as usize / 4 + phase).is_multiple_of(2); - clip.line_segment([a, b], Stroke::new(1.0, if dark { Color32::BLACK } else { Color32::WHITE })); - } - } - None => { - let b = v.rect(bounds(&w.base)); - clip.rect_stroke(b, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Outside); - } - } - ctx.request_repaint_after(std::time::Duration::from_millis(120)); - if let Some((_, pts)) = &w.lasso - && pts.len() > 1 - { - let line: Vec = pts.iter().map(|p| v.to_screen(*p)).collect(); - clip.add(egui::Shape::line(line, Stroke::new(1.0, t.accent))); - } - if let Some(hp) = resp.hover_pos() { - if w.tool == CafTool::Brush { - let r = w.brush_size as f32 * 0.5 * v.zoom; - clip.circle_stroke(hp, r, Stroke::new(1.5, Color32::BLACK)); - clip.circle_stroke(hp, r, Stroke::new(0.75, Color32::WHITE)); - } - w.hover = Some(v.to_doc(hp)); - } - clip.rect_stroke(img, 0.0, Stroke::new(1.0, t.separator), egui::StrokeKind::Outside); - // Mouse → tools (Space, the middle button or the Hand pan). - let pan = ui.input(|i| i.key_down(egui::Key::Space) || i.pointer.middle_down()) || w.tool == CafTool::Hand; - if pan && resp.dragged() { - let dl = resp.drag_delta(); - w.center = [w.center[0] - f64::from(dl.x / w.zoom), w.center[1] - f64::from(dl.y / w.zoom)]; - } else if !pan - && resp.is_pointer_button_down_on() - && let Some(pp) = resp.interact_pointer_pos() - { - // The press is the first point; the frames before egui's drag threshold and the drag - // itself continue it (a second `Down` would start the stroke over, dropping them). - let q = v.to_doc(pp); - mods = ui.input(|i| i.modifiers); - if w.pressed { - events.push(ToolEvent::Move { x: q[0], y: q[1], pressure: 1.0 }); - ctx.request_repaint(); - } else { - w.pressed = true; - events.push(ToolEvent::Down { x: q[0], y: q[1], pressure: 1.0 }); - } - dragging = true; - } - if w.pressed && !resp.is_pointer_button_down_on() { - w.pressed = false; - let q = w.hover.unwrap_or(w.center); - events.push(ToolEvent::Up { x: q[0], y: q[1] }); - dragging = false; - } - // Settings changed in the panel: the overlay and the preview follow. - if w.opts != before { - w.overlay_dirty = true; - w.stale(); - } - }); - if let Some(s) = new_sampling { - set_sampling(app, s); - } - if let Some(r) = reset_what { - reset(app, r); - } - if let Some(e) = fill_btn { - fill_edit(app, e); - } - if rebase_needed { - rebase(app); - } - for ev in events { - pointer(app, ev, mods); - } - drive_preview(app, ctx, dragging); - match action { - Some("ok") => commit(app), - Some("cancel") => cancel(app), - Some("apply") => { - if let Err(e) = apply(app) { - report(app, e); - } - } - _ => {} - } -} - #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/caf_ui/controls.rs b/crates/ui-egui/src/caf_ui/controls.rs new file mode 100644 index 0000000000..f01d4d6852 --- /dev/null +++ b/crates/ui-egui/src/caf_ui/controls.rs @@ -0,0 +1,196 @@ +use super::lifecycle::{apply, cancel, close, fill_edit, redo, report, reset, set_sampling, undo}; +use super::preview::{rebase, wait_preview}; +use super::*; + +/// Control channel: `edit.contentAwareFill {"ui": {...}}` while the workspace is open. +pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result { + let flag = |k: &str| ui.get(k).and_then(Value::as_bool) == Some(true); + if flag("cancel") { + cancel(app); + return Ok(json!({"cancelled": true})); + } + let before = app.distort.caf.as_ref().ok_or("Content-Aware Fill is not open")?.opts.clone(); + { + let w = app.distort.caf.as_mut().ok_or("Content-Aware Fill is not open")?; + let mut o = w.opts.clone(); + o.apply(ui)?; + // The sampling option goes through `set_sampling` (it resets the strokes). + let sampling = std::mem::replace(&mut o.sampling, w.opts.sampling.clone()); + w.opts = o; + if let Some(t) = ui.get("tool").and_then(Value::as_str) { + w.tool = CafTool::from_name(t).ok_or(format!("bad tool `{t}` (brush|lasso|hand|zoom)"))?; + } + if let Some(n) = ui.get("brushSize").and_then(Value::as_f64).filter(|n| n.is_finite()) { + w.brush_size = n.clamp(1.0, 5000.0); + } + if let Some(m) = ui.get("brushMode").and_then(Value::as_str) { + w.brush_add = m == "add"; + } + if let Some(m) = ui.get("lassoMode").and_then(Value::as_str) { + w.lasso_op = LASSO_OPS.iter().position(|o| *o == m).ok_or(format!("bad lassoMode `{m}`"))?; + } + if let Some(n) = ui.get("expandBy").and_then(Value::as_f64).filter(|n| n.is_finite()) { + w.expand_by = (n as f32).clamp(1.0, 100.0); + } + if sampling != w.opts.sampling { + set_sampling(app, &sampling); + } + } + let after = app.distort.caf.as_ref().map(|w| w.opts.clone()); + if after.as_ref().is_some_and(|a| a.sample_all != before.sample_all) { + rebase(app); + } else if after.as_ref().is_some_and(|a| *a != before) + && let Some(w) = app.distort.caf.as_mut() + { + w.stale(); + w.restate_all(); + } + if let Some(s) = ui.get("stroke") { + let pts: Vec<[f64; 2]> = serde_json::from_value(s.get("points").cloned().unwrap_or(Value::Null)).map_err(|e| format!("bad stroke points: {e}"))?; + let w = app.distort.caf.as_mut().ok_or("Content-Aware Fill is not open")?; + if let Some(n) = s.get("size").and_then(Value::as_f64) { + w.brush_size = n.clamp(1.0, 5000.0); + } + let alt = s.get("alt").and_then(Value::as_bool).unwrap_or(false); + if let Some(first) = pts.first() { + w.begin_stroke(*first, alt); + for p in &pts[1..] { + w.extend_stroke(*p); + } + w.end_stroke(); + } + } + if let Some(l) = ui.get("lasso") { + let pts: Vec<[f64; 2]> = serde_json::from_value(l.get("points").cloned().unwrap_or(Value::Null)).map_err(|e| format!("bad lasso points: {e}"))?; + let op = match l.get("op").and_then(Value::as_str) { + Some(o) if LASSO_OPS.contains(&o) => o.to_string(), + Some(o) => return Err(format!("bad lasso op `{o}`")), + None => LASSO_OPS[app.distort.caf.as_ref().map_or(0, |w| w.lasso_op)].to_string(), + }; + fill_edit(app, json!({"op": op, "points": pts})); + } + for k in ["expand", "contract"] { + if let Some(n) = ui.get(k).and_then(Value::as_f64) { + fill_edit(app, json!({"op": k, "by": n.clamp(1.0, 100.0)})); + } + } + if let Some(r) = ui.get("reset").and_then(Value::as_str) { + reset(app, r); + } + if flag("undo") { + undo(app); + } + if flag("redo") { + redo(app); + } + if flag("apply") { + apply(app)?; + } + if flag("waitPreview") { + wait_preview(app)?; + } + // OK last, with the settings given alongside. A failed fill keeps the workspace open, as + // the OK button does. + if flag("commit") { + let r = apply(app); + match &r { + Ok(_) => close(app), + Err(e) => report(app, e.clone()), + } + return r.map(|v| json!({"committed": true, "result": v})); + } + Ok(app.distort.caf.as_ref().map(CafWorkspace::describe).unwrap_or(Value::Null)) +} + +/// Pointer in document coordinates (from the view or the control channel). +pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { + let Some(w) = app.distort.caf.as_mut() else { return }; + match (w.tool, ev) { + (CafTool::Brush, ToolEvent::Down { x, y, .. }) => w.begin_stroke([x, y], mods.alt), + (CafTool::Brush, ToolEvent::Move { x, y, .. }) => { + w.hover = Some([x, y]); + w.extend_stroke([x, y]); + } + (CafTool::Brush, ToolEvent::Up { x, y }) => { + w.extend_stroke([x, y]); + w.end_stroke(); + } + (CafTool::Lasso, ToolEvent::Down { x, y, .. }) => { + // Shift adds, Alt subtracts, both intersect (as Photoshop's selection tools). + let op = match (mods.shift, mods.alt) { + (true, true) => 3, + (true, false) => 1, + (false, true) => 2, + _ => w.lasso_op, + }; + w.lasso = Some((op, vec![[x, y]])); + } + (CafTool::Lasso, ToolEvent::Move { x, y, .. }) => { + if let Some((_, pts)) = &mut w.lasso + && pts.last().is_none_or(|l| l[0] != x || l[1] != y) + { + pts.push([x, y]); + } + } + (CafTool::Lasso, ToolEvent::Up { .. }) => { + if let Some((op, pts)) = w.lasso.take() + && pts.len() >= 3 + { + fill_edit(app, json!({"op": LASSO_OPS[op], "points": pts})); + } + } + (CafTool::Zoom, ToolEvent::Down { x, y, .. }) => { + let f = if mods.alt { 0.5 } else { 2.0 }; + w.zoom = (w.zoom * f).clamp(0.01, 32.0); + w.center = [x, y]; + } + _ => {} + } +} + +pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) { + let cmd_shift = egui::Modifiers::COMMAND | egui::Modifiers::SHIFT; + if ctx.input_mut(|i| i.consume_key(cmd_shift, egui::Key::Z)) { + redo(app); + return; + } + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::Z)) { + undo(app); + return; + } + let Some(w) = app.distort.caf.as_mut() else { return }; + // Ctrl+H hides the overlay (Hide Extras). + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::H)) { + w.opts.show_overlay = !w.opts.show_overlay; + w.overlay_dirty = true; + } + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::OpenBracket)) { + w.brush_size = (w.brush_size * 0.9).max(1.0).round(); + } + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::CloseBracket)) { + w.brush_size = (w.brush_size * 1.1).min(5000.0).round().max(w.brush_size + 1.0); + } + for (k, t) in [(egui::Key::B, CafTool::Brush), (egui::Key::L, CafTool::Lasso), (egui::Key::H, CafTool::Hand), (egui::Key::Z, CafTool::Zoom)] { + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, k)) { + w.tool = t; + } + } +} + +pub(super) fn tool_icon(t: CafTool) -> &'static str { + match t { + CafTool::Brush => "brush", + CafTool::Lasso => "lasso", + CafTool::Hand => "hand", + CafTool::Zoom => "zoom-in", + } +} + +pub(super) fn tool_tip(t: CafTool) -> String { + match t { + CafTool::Brush => format!("{} (B)", tl!("Sampling Brush Tool")), + CafTool::Lasso => format!("{} (L)", tl!("Lasso Tool")), + CafTool::Hand => format!("{} (H)", tl!("Hand Tool")), + CafTool::Zoom => format!("{} (Z)", tl!("Zoom Tool")), + } +} diff --git a/crates/ui-egui/src/caf_ui/lifecycle.rs b/crates/ui-egui/src/caf_ui/lifecycle.rs new file mode 100644 index 0000000000..5bc21da079 --- /dev/null +++ b/crates/ui-egui/src/caf_ui/lifecycle.rs @@ -0,0 +1,269 @@ +use super::preview::{Base, Preview, cancel_preview, compute_base, plan_params, points_limit, rebase, refresh}; +use super::*; + +/// Opens the workspace on the active layer and its selection. +pub fn open(app: &mut PhotocraftApp) -> Result<(), String> { + if !app.session.is_enabled(CMD) { + return Err("Content-Aware Fill needs a selection on a pixel layer".into()); + } + let st = app.session.active().ok_or("no document")?; + let layer = st.active_layer.ok_or("no active layer")?; + let canvas = st.doc.bounds(); + let revision = st.revision; + let name = st.doc.layer(layer).map(|l| l.name.clone()).unwrap_or_default(); + let k = (canvas.width().max(canvas.height()) as usize).div_ceil(PROXY_SIDE).max(1); + let (pw, ph) = ((canvas.width() as usize).div_ceil(k), (canvas.height() as usize).div_ceil(k)); + let mut opts = CafOpts::default(); + if let Some(saved) = app.session.prefs().dialogs.get(REMEMBERED) { + let _ = opts.apply(saved); + } + let mut w = CafWorkspace { + layer, + layer_name: name, + canvas, + revision, + opts, + tool: CafTool::Brush, + brush_add: false, + brush_size: 20.0, + lasso_op: 0, + expand_by: 3.0, + strokes: Vec::new(), + fill_edits: Vec::new(), + undo: Vec::new(), + redo: Vec::new(), + cur: None, + lasso: None, + base: Base { window: Rect::EMPTY, rect: Rect::EMPTY, hole: Vec::new(), base: Vec::new() }, + outline: None, + k, + pw, + ph, + base_px: vec![false; pw * ph], + hole_px: vec![false; pw * ph], + mask: vec![false; pw * ph], + pressed: false, + texture_limit: 2048, + image_tex: None, + overlay_tex: None, + overlay_dirty: true, + zoom: 0.0, + center: [f64::from(canvas.x0 + canvas.x1) / 2.0, f64::from(canvas.y0 + canvas.y1) / 2.0], + hover: None, + preview: Preview::default(), + error: None, + }; + w.brush_add = w.opts.sampling == "custom"; + let base = compute_base(app, &w)?; + w.brush_size = photocraft_algo::content_aware::default_brush_size(bounds(&base)); + w.set_base(base); + w.stale(); + app.distort.caf = Some(w); + Ok(()) +} + +/// Bounds of the fill area. +pub(super) fn bounds(b: &Base) -> Rect { + let w = b.rect.width() as usize; + b.hole.iter().enumerate().filter(|(_, h)| **h).fold(Rect::EMPTY, |r, (i, _)| { + let (x, y) = (b.rect.x0 + (i % w) as i32, b.rect.y0 + (i / w) as i32); + r.union(&Rect::new(x, y, x + 1, y + 1)) + }) +} + +fn remember(app: &mut PhotocraftApp, opts: &CafOpts) { + let v = opts.to_json(); + app.session.prefs.edit(|p| p.dialogs.insert(REMEMBERED.into(), v)); +} + +/// Apply: fill with the current state (one history step); the workspace stays open. +pub fn apply(app: &mut PhotocraftApp) -> Result { + let Some(w) = app.distort.caf.as_mut() else { return Err("Content-Aware Fill is not open".into()) }; + w.end_stroke(); + let p = plan_params(w, true); + let opts = w.opts.clone(); + remember(app, &opts); + let r = app.run(CMD, p); + if r.is_ok() { + refresh(app); + } + r +} + +/// OK: fill and close. A fill that fails (nothing to sample from, a fill area too large, …) +/// leaves the workspace open with the error in its panel, so the areas can be fixed and OK +/// pressed again instead of the work being thrown away. +pub fn commit(app: &mut PhotocraftApp) { + match apply(app) { + Ok(_) => close(app), + Err(e) => report(app, e), + } +} + +/// An Apply or OK that failed: the error in the panel and the status bar. +pub(super) fn report(app: &mut PhotocraftApp, e: String) { + if let Some(w) = app.distort.caf.as_mut() { + w.error = Some(e.clone()); + } + app.ui.status = e; + app.ui.status_error = true; +} + +/// Cancel (button, Esc): closes; what was applied stays. The settings are kept. +pub fn cancel(app: &mut PhotocraftApp) { + if let Some(w) = app.distort.caf.as_ref() { + let opts = w.opts.clone(); + remember(app, &opts); + } + close(app); +} + +pub(super) fn close(app: &mut PhotocraftApp) { + if let Some(w) = app.distort.caf.take() { + cancel_preview(w); + } +} + +pub(super) fn undo(app: &mut PhotocraftApp) { + let Some(w) = app.distort.caf.as_mut() else { return }; + w.end_stroke(); + let Some(step) = w.undo.pop() else { return }; + let rebuild = match &step { + Step::Stroke(_) => { + w.strokes.pop(); + w.redo.push(step); + w.restate_all(); + w.stale(); + // The sampling area changed, as with a new stroke: an error a failed OK or Apply left + // in the panel no longer applies (the other steps rebase, which clears it too). + w.error = None; + false + } + Step::Fill(_) => { + w.fill_edits.pop(); + w.redo.push(step); + true + } + Step::State { sampling, strokes, fill_edits } => { + let now = Step::State { sampling: w.opts.sampling.clone(), strokes: w.strokes.clone(), fill_edits: w.fill_edits.clone() }; + w.opts.sampling = sampling.clone(); + w.strokes = strokes.clone(); + w.fill_edits = fill_edits.clone(); + w.brush_add = w.opts.sampling == "custom"; + w.redo.push(now); + true + } + }; + if rebuild { + rebase(app); + } +} + +pub(super) fn redo(app: &mut PhotocraftApp) { + let Some(w) = app.distort.caf.as_mut() else { return }; + w.end_stroke(); + let Some(step) = w.redo.pop() else { return }; + let rebuild = match &step { + Step::Stroke(s) => { + w.strokes.push(s.clone()); + w.undo.push(step); + w.restate_all(); + w.stale(); + w.error = None; + false + } + Step::Fill(e) => { + w.fill_edits.push(e.clone()); + w.undo.push(step); + true + } + Step::State { sampling, strokes, fill_edits } => { + let now = Step::State { sampling: w.opts.sampling.clone(), strokes: w.strokes.clone(), fill_edits: w.fill_edits.clone() }; + w.opts.sampling = sampling.clone(); + w.strokes = strokes.clone(); + w.fill_edits = fill_edits.clone(); + w.brush_add = w.opts.sampling == "custom"; + w.undo.push(now); + true + } + }; + if rebuild { + rebase(app); + } +} + +/// A lasso edit of the fill area (or Expand / Contract), undoable. +pub(super) fn fill_edit(app: &mut PhotocraftApp, edit: Value) { + let Some(w) = app.distort.caf.as_mut() else { return }; + w.end_stroke(); + // The engine's limits, kept here (see `begin_stroke`). + if w.fill_edits.len() >= MAX_CAF_EDITS { + w.error = Some(format!("at most {MAX_CAF_EDITS} lasso edits: undo some, or reset the fill area")); + return; + } + if w.points_used() + edit.get("points").and_then(Value::as_array).map_or(0, Vec::len) > MAX_CAF_POINTS { + w.error = Some(points_limit()); + return; + } + w.fill_edits.push(edit.clone()); + w.push(Step::Fill(edit)); + rebase(app); + // An edit that empties the fill area is refused (the plan says so): undo it. + if app.distort.caf.as_ref().is_some_and(|w| w.error.is_some()) { + let msg = app.distort.caf.as_ref().and_then(|w| w.error.clone()); + undo(app); + if let Some(w) = app.distort.caf.as_mut() { + w.redo.clear(); + w.error = msg; + } + } +} + +/// A new sampling option (Auto, Rectangular, Custom): the brush strokes start over and the brush +/// takes the option's mode (Custom adds, the others subtract). +pub(super) fn set_sampling(app: &mut PhotocraftApp, sampling: &str) { + let Some(w) = app.distort.caf.as_mut() else { return }; + if w.opts.sampling == sampling && w.strokes.is_empty() { + return; + } + w.end_stroke(); + let prev = Step::State { sampling: w.opts.sampling.clone(), strokes: std::mem::take(&mut w.strokes), fill_edits: w.fill_edits.clone() }; + w.push(prev); + w.opts.sampling = sampling.to_string(); + w.brush_add = sampling == "custom"; + rebase(app); +} + +/// Reset buttons: the sampling options, the fill settings, or everything. +pub(super) fn reset(app: &mut PhotocraftApp, what: &str) { + let Some(w) = app.distort.caf.as_mut() else { return }; + let d = CafOpts::default(); + match what { + "fill" => { + w.opts.color_adaptation = d.color_adaptation; + w.opts.rotation = d.rotation; + w.opts.scale = d.scale; + w.opts.mirror = d.mirror; + w.stale(); + } + "sampling" => { + w.opts.sample_all = false; + set_sampling(app, "auto"); + } + "lasso" => { + if !w.fill_edits.is_empty() { + let prev = Step::State { sampling: w.opts.sampling.clone(), strokes: w.strokes.clone(), fill_edits: std::mem::take(&mut w.fill_edits) }; + w.push(prev); + rebase(app); + } + } + _ => { + let prev = + Step::State { sampling: w.opts.sampling.clone(), strokes: std::mem::take(&mut w.strokes), fill_edits: std::mem::take(&mut w.fill_edits) }; + w.push(prev); + w.opts = CafOpts::default(); + w.brush_add = false; + rebase(app); + } + } +} diff --git a/crates/ui-egui/src/caf_ui/preview.rs b/crates/ui-egui/src/caf_ui/preview.rs new file mode 100644 index 0000000000..628893bf1b --- /dev/null +++ b/crates/ui-egui/src/caf_ui/preview.rs @@ -0,0 +1,315 @@ +use super::*; + +/// What the plan (without the brush strokes) says: the window, the fill area and the sampling +/// option's area, over `rect`. +pub(super) struct Base { + pub(super) window: Rect, + pub(super) rect: Rect, + pub(super) hole: Vec, + pub(super) base: Vec, +} + +impl Base { + /// The index into `hole` and `base` of document point `(x, y)`, when it is inside `rect`. + pub(super) fn index(&self, x: f64, y: f64) -> Option { + let (xi, yi) = (x.floor() as i32, y.floor() as i32); + self.rect.contains(xi, yi).then(|| (yi - self.rect.y0) as usize * self.rect.width() as usize + (xi - self.rect.x0) as usize) + } +} + +/// A computed preview: the filled rectangle as an image, or why it failed. +#[cfg(not(target_arch = "wasm32"))] +type PreviewResult = Result<(Rect, egui::ColorImage), String>; + +/// The preview being computed or shown. +#[derive(Default)] +pub(super) struct Preview { + /// Bumped whenever the state changes; a result for an older generation is dropped. + pub(super) want: u64, + #[cfg(not(target_arch = "wasm32"))] + running: Option<(u64, std::sync::mpsc::Receiver, photocraft_engine::jobs::JobCtx)>, + pub(super) shown: u64, + /// A finished preview waiting to be uploaded (on the UI thread, which has the context). + pub(super) pending_image: Option<(Rect, egui::ColorImage)>, + pub(super) tex: Option<(TextureHandle, Rect)>, + /// Screen px per document px (0 = frame the window on the next frame) and the view centre. + pub(super) zoom: f32, + pub(super) center: [f64; 2], + pub(super) error: Option, +} + +impl Preview { + /// Takes the result of the preview of state `generation`: an image to upload, or the error, + /// which stands for that state until it changes (the same preview is not started again). + fn finish(&mut self, generation: u64, r: Result<(Rect, egui::ColorImage), String>) { + self.shown = generation; + self.tex = None; + match r { + Ok(img) => { + self.pending_image = Some(img); + self.error = None; + } + Err(e) => { + self.pending_image = None; + self.error = Some(e); + } + } + } +} + +/// The preview's error when the sampling area has no pixels outside the fill area (the engine's +/// fill refuses that case with the same words). +const NOTHING_TO_SAMPLE: &str = "nothing to sample from: the sampling area has no pixels outside the fill area"; + +/// The plan of the current state (without strokes when `strokes` is false). +pub(super) fn plan_params(w: &CafWorkspace, strokes: bool) -> Value { + let o = &w.opts; + let mut p = json!({ + "sampling": o.sampling, + "sampleAllLayers": o.sample_all, + "colorAdaptation": o.color_adaptation, + "rotationAdaptation": o.rotation, + "scale": o.scale, + "mirror": o.mirror, + "output": o.output, + "layer": w.layer.0, + "fillEdits": w.fill_edits, + }); + if strokes && !w.strokes.is_empty() { + p["samplingStrokes"] = Value::Array(w.strokes.iter().map(stroke_json).collect()); + } + p +} + +pub(super) fn points_limit() -> String { + format!("at most {MAX_CAF_POINTS} points in all sampling strokes and lasso edits: undo some, or reset") +} + +/// The plan without strokes: the window, fill area and the option's area. Custom starts empty +/// (the window and fill area are those of Rectangular). +pub(super) fn compute_base(app: &PhotocraftApp, w: &CafWorkspace) -> Result { + let st = app.session.active().ok_or("no document")?; + let mut p = plan_params(w, false); + let custom = w.opts.sampling == "custom"; + if custom { + p["sampling"] = json!("rectangular"); + } + let plan = photocraft_engine::edit_menu_cmds::content_aware_plan(&st.doc, w.layer, &p, CMD).map_err(|e| e.to_string())?; + let base = if custom { vec![false; plan.base.len()] } else { plan.base }; + Ok(Base { window: plan.window, rect: plan.rect, hole: plan.hole, base }) +} + +/// Unit edges between the fill area and the rest, in document px. +pub(super) fn outline(b: &Base) -> Option> { + let (w, h) = (b.rect.width() as usize, b.rect.height() as usize); + let (ox, oy) = (b.rect.x0 as f32, b.rect.y0 as f32); + let at = |x: i64, y: i64| x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h && b.hole.get(y as usize * w + x as usize).copied().unwrap_or(false); + let mut out = Vec::new(); + for y in 0..h as i64 { + for x in 0..w as i64 { + if !at(x, y) { + continue; + } + let (fx, fy) = (ox + x as f32, oy + y as f32); + if !at(x - 1, y) { + out.push([[fx, fy], [fx, fy + 1.0]]); + } + if !at(x + 1, y) { + out.push([[fx + 1.0, fy], [fx + 1.0, fy + 1.0]]); + } + if !at(x, y - 1) { + out.push([[fx, fy], [fx + 1.0, fy]]); + } + if !at(x, y + 1) { + out.push([[fx, fy + 1.0], [fx + 1.0, fy + 1.0]]); + } + if out.len() > MAX_OUTLINE_EDGES { + return None; + } + } + } + Some(out) +} + +/// Recompute the base after a change of the fill area, the sampling option or the document. +pub(super) fn rebase(app: &mut PhotocraftApp) { + let Some(w) = app.distort.caf.as_ref() else { return }; + let r = compute_base(app, w); + let Some(w) = app.distort.caf.as_mut() else { return }; + match r { + Ok(b) => { + w.set_base(b); + w.error = None; + } + Err(e) => { + w.error = Some(e); + w.restate_all(); + } + } + w.stale(); +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn cancel_preview(w: CafWorkspace) { + if let Some((_, _, job)) = w.preview.running { + job.cancel(); + } +} + +#[cfg(target_arch = "wasm32")] +pub(super) fn cancel_preview(_: CafWorkspace) {} + +/// The document changed under the workspace (an Apply): new textures, a new base. +pub(super) fn refresh(app: &mut PhotocraftApp) { + let rev = app.session.active().map(|s| s.revision); + if let Some(w) = app.distort.caf.as_mut() { + w.image_tex = None; + w.revision = rev.unwrap_or(w.revision); + } + rebase(app); +} + +/// Computes the preview now, on this thread (tests and the control channel). +pub(super) fn wait_preview(app: &mut PhotocraftApp) -> Result<(), String> { + let (doc, layer, p, want, limit) = { + let w = app.distort.caf.as_ref().ok_or("Content-Aware Fill is not open")?; + let st = app.session.active().ok_or("no document")?; + (st.doc.clone(), w.layer, plan_params(w, true), w.preview.want, w.texture_limit) + }; + let r = compute_preview(&doc, layer, &p, &photocraft_raster::Interrupt::NONE, limit); + let w = app.distort.caf.as_mut().ok_or("Content-Aware Fill is not open")?; + let err = r.as_ref().err().cloned(); + w.preview.finish(want, r); + err.map_or(Ok(()), Err) +} + +/// The filled rectangle as an image (what Apply would write there), as a texture no wider than +/// `max_side`: past the device's limit it is box-averaged to fit (the rectangle it is drawn over +/// stays the plan's). +fn compute_preview( + doc: &photocraft_doc::Document, + layer: LayerId, + p: &Value, + ctl: &photocraft_raster::Interrupt, + max_side: usize, +) -> Result<(Rect, egui::ColorImage), String> { + let plan = photocraft_engine::edit_menu_cmds::content_aware_plan_with(doc, layer, p, CMD, ctl).map_err(|e| match e { + photocraft_engine::EngineError::Cancelled => "cancelled".to_string(), + e => e.to_string(), + })?; + // Patches come only from the sampling area outside the fill area. With none (the Sampling + // Brush erased it all, a Custom area not painted yet) the fill would come out black, so the + // preview says so instead of showing that. + if !plan.source.iter().any(|s| *s) { + return Err(NOTHING_TO_SAMPLE.into()); + } + let (w, h) = (plan.rect.width() as usize, plan.rect.height() as usize); + let n = plan.fmt.channels(); + let filled = + photocraft_algo::content_aware::fill_with(w, h, n, &plan.img, &plan.hole, &plan.source, &plan.opts, ctl).map_err(|_| "cancelled".to_string())?; + let own = plan.layer_pixels(); + // Pixel `i`: the fill over the fill area (a partly selected pixel by its coverage), the + // layer's own pixels elsewhere. + let pixel = |i: usize| -> [f32; 4] { + let src = if plan.hole[i] { &filled[i * n..(i + 1) * n] } else { &own[i * n..(i + 1) * n] }; + let mut c = photocraft_raster::to_rgba(&plan.fmt, src); + if plan.hole[i] { + let k = plan.cover[i]; + let under = photocraft_raster::to_rgba(&plan.fmt, &own[i * n..(i + 1) * n]); + for j in 0..4 { + c[j] = under[j] + (c[j] - under[j]) * k; + } + } + c + }; + let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + let color = |c: [f32; 4]| Color32::from_rgba_unmultiplied(b(c[0]), b(c[1]), b(c[2]), b(c[3])); + let f = crate::filter_preview_ui::texture_factor(w as u32, h as u32, max_side) as usize; + if f == 1 { + let px = (0..w * h).map(|i| color(pixel(i))).collect(); + return Ok((plan.rect, egui::ColorImage::new([w, h], px))); + } + let (tw, th) = (w.div_ceil(f), h.div_ceil(f)); + let mut px = Vec::with_capacity(tw * th); + for ty in 0..th { + for tx in 0..tw { + // The block's premultiplied average. + let (mut acc, mut count) = ([0.0f32; 4], 0.0f32); + for y in ty * f..((ty + 1) * f).min(h) { + for x in tx * f..((tx + 1) * f).min(w) { + let c = pixel(y * w + x); + for j in 0..3 { + acc[j] += c[j] * c[3]; + } + acc[3] += c[3]; + count += 1.0; + } + } + let c = if acc[3] > 0.0 { [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3] / count] } else { [0.0; 4] }; + px.push(color(c)); + } + } + Ok((plan.rect, egui::ColorImage::new([tw, th], px))) +} + +/// Starts a background preview when the shown one is out of date (and the pointer is up), and +/// collects a finished one. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn drive_preview(app: &mut PhotocraftApp, ctx: &egui::Context, dragging: bool) { + let doc = app.session.active().map(|s| s.doc.clone()); + let Some(w) = app.distort.caf.as_mut() else { return }; + let pv = &mut w.preview; + if let Some((generation, rx, _)) = &pv.running { + match rx.try_recv() { + Ok(r) => { + let generation = *generation; + pv.running = None; + if generation == pv.want { + match r { + Err(e) if e == "cancelled" => {} + r => pv.finish(generation, r), + } + } + } + Err(std::sync::mpsc::TryRecvError::Empty) => { + // Superseded: stop it, a new one starts when it has gone. + if *generation != pv.want + && let Some((_, _, job)) = &pv.running + { + job.cancel(); + } + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + return; + } + Err(std::sync::mpsc::TryRecvError::Disconnected) => pv.running = None, + } + } + if pv.running.is_some() || pv.shown == pv.want || dragging { + return; + } + let Some(doc) = doc else { return }; + let (layer, p, generation, limit) = (w.layer, plan_params(w, true), w.preview.want, w.texture_limit); + let (tx, rx) = std::sync::mpsc::sync_channel(1); + let job = photocraft_engine::jobs::JobCtx::new(); + let work = job.clone(); + let repaint = ctx.clone(); + let spawned = std::thread::Builder::new().name("caf-preview".into()).spawn(move || { + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| work.stage(0.0, 1.0, "", |ctl| compute_preview(&doc, layer, &p, ctl, limit)))) + .unwrap_or_else(|_| Err("the preview failed".into())); + let _ = tx.send(r); + repaint.request_repaint(); + }); + match spawned { + Ok(_) => w.preview.running = Some((generation, rx, job)), + Err(e) => w.preview.error = Some(format!("could not start the preview: {e}")), + } +} + +/// The web build has no threads: the preview is computed when the pointer comes up. +#[cfg(target_arch = "wasm32")] +pub(super) fn drive_preview(app: &mut PhotocraftApp, _ctx: &egui::Context, dragging: bool) { + let stale = app.distort.caf.as_ref().is_some_and(|w| w.preview.shown != w.preview.want); + if stale && !dragging { + let _ = wait_preview(app); + } +} diff --git a/crates/ui-egui/src/caf_ui/view.rs b/crates/ui-egui/src/caf_ui/view.rs new file mode 100644 index 0000000000..f9987ff822 --- /dev/null +++ b/crates/ui-egui/src/caf_ui/view.rs @@ -0,0 +1,448 @@ +use super::controls::{pointer, tool_icon, tool_tip}; +use super::lifecycle::{apply, bounds, cancel, commit, fill_edit, report, reset, set_sampling}; +use super::preview::{drive_preview, rebase, refresh}; +use super::*; + +/// A view: screen px per document px and the document point at the centre of `area`. +#[derive(Clone, Copy)] +struct View { + area: ERect, + zoom: f32, + center: [f64; 2], +} + +impl View { + fn to_screen(self, p: [f64; 2]) -> Pos2 { + let c = self.area.center(); + pos2(c.x + ((p[0] - self.center[0]) as f32) * self.zoom, c.y + ((p[1] - self.center[1]) as f32) * self.zoom) + } + fn to_doc(self, s: Pos2) -> [f64; 2] { + let c = self.area.center(); + [self.center[0] + f64::from((s.x - c.x) / self.zoom), self.center[1] + f64::from((s.y - c.y) / self.zoom)] + } + fn rect(self, r: Rect) -> ERect { + ERect::from_min_max(self.to_screen([f64::from(r.x0), f64::from(r.y0)]), self.to_screen([f64::from(r.x1), f64::from(r.y1)])) + } +} + +/// Upload what changed: the document proxy, the overlay, a finished preview. +fn upload(app: &mut PhotocraftApp, ctx: &egui::Context) { + let need_image = app.distort.caf.as_ref().is_some_and(|w| w.image_tex.is_none()); + if need_image { + let img = view_image(app); + if let (Some(w), Some(img)) = (app.distort.caf.as_mut(), img) { + w.image_tex = Some(ctx.load_texture("caf-image", img, egui::TextureOptions::LINEAR)); + } + } + let Some(w) = app.distort.caf.as_mut() else { return }; + if w.overlay_dirty || w.overlay_tex.is_none() { + w.overlay_dirty = false; + let [r, g, b] = w.opts.color; + let a = (w.opts.opacity / 100.0 * 255.0).round() as u8; + let tint = Color32::from_rgba_unmultiplied(r, g, b, a); + // The tint marks the sampling area (with Indicates: Excluded Area, what is left out); + // the fill area is never tinted. + let px: Vec = + w.mask.iter().zip(&w.hole_px).map(|(m, h)| if w.opts.show_overlay && !*h && *m != w.opts.excluded { tint } else { Color32::TRANSPARENT }).collect(); + let img = egui::ColorImage::new([w.pw, w.ph], px); + match &mut w.overlay_tex { + Some(t) => t.set(img, egui::TextureOptions::NEAREST), + None => w.overlay_tex = Some(ctx.load_texture("caf-overlay", img, egui::TextureOptions::NEAREST)), + } + } + if let Some((rect, img)) = w.preview.pending_image.take() { + w.preview.tex = Some((ctx.load_texture("caf-preview", img, egui::TextureOptions::LINEAR), rect)); + } +} + +/// The document as the view shows it: the visible layers composited, as on the canvas (so an +/// Apply to a new layer shows), reduced to the proxy. +pub(super) fn view_image(app: &PhotocraftApp) -> Option { + let w = app.distort.caf.as_ref()?; + let st = app.session.active()?; + let buf = photocraft_compose::render_reduced(&st.doc, w.pw as u32, w.ph as u32); + let (display, _) = crate::canvas::canvas_display(app, &st.doc, None); + Some(crate::canvas::display_image(display.as_deref(), &buf)) +} + +/// Draws the workspace (a full-window layer over the app). +pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { + // An Apply (or anything else) changed the document: refresh. + let rev = app.session.active().map(|s| s.revision); + if app.distort.caf.as_ref().is_some_and(|w| Some(w.revision) != rev) { + refresh(app); + } + upload(app, ctx); + let t = Tokens::get(ctx); + let screen = ctx.content_rect(); + let mut action: Option<&str> = None; + let mut events: Vec = Vec::new(); + let mut mods = egui::Modifiers::NONE; + let mut new_sampling: Option<&str> = None; + let mut fill_btn: Option = None; + let mut reset_what: Option<&str> = None; + let mut rebase_needed = false; + let mut dragging = false; + egui::Area::new(egui::Id::unique("caf-workspace")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| { + let Some(w) = app.distort.caf.as_mut() else { return }; + let before = w.opts.clone(); + w.texture_limit = ctx.input(|i| i.max_texture_side); + let (full, _) = ui.allocate_exact_size(screen.size(), Sense::hover()); + let painter = ui.painter().clone(); + painter.rect_filled(full, 0.0, t.chrome); + // Title strip. + let title = ERect::from_min_size(full.min, vec2(full.width(), 30.0)); + painter.rect_filled(title, 0.0, t.dock); + painter.line_segment([title.left_bottom(), title.right_bottom()], Stroke::new(1.0, t.separator)); + let pct = if w.zoom > 0.0 { w.zoom * 100.0 } else { 100.0 }; + painter.text( + title.center(), + Align2::CENTER_CENTER, + format!("{} ({}, {:.0}%)", tl!("Content-Aware Fill…").trim_end_matches('…'), w.layer_name, pct), + FontId::proportional(13.0), + t.text, + ); + // Options bar. + let bar = ERect::from_min_size(pos2(full.left(), title.bottom()), vec2(full.width(), BAR_H)); + painter.rect_filled(bar, 0.0, t.dock); + painter.line_segment([bar.left_bottom(), bar.right_bottom()], Stroke::new(1.0, t.separator)); + let mut bui = + ui.new_child(egui::UiBuilder::new().max_rect(bar.shrink2(vec2(LEFT_W + 8.0, 4.0))).layout(egui::Layout::left_to_right(egui::Align::Center))); + match w.tool { + CafTool::Brush => { + if crate::icons::button(&mut bui, "plus", 26.0, w.brush_add, tl!("Add")).clicked() { + w.brush_add = true; + } + if crate::icons::button(&mut bui, "minus", 26.0, !w.brush_add, tl!("Subtract")).clicked() { + w.brush_add = false; + } + bui.add_space(8.0); + bui.label(tl!("Size:")); + let mut size = w.brush_size as f32; + if widgets::value_field(&mut bui, &mut size, 1.0..=5000.0, " px", 64.0).accessible_name(tl!("Size:")).changed() { + w.brush_size = f64::from(size); + } + } + CafTool::Lasso => { + // The selection tools' mode buttons (the lasso here edits the fill area). + let tips = [ + tl!("New selection").to_string(), + crate::i18n::fmt(tl!("Add to selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift"))]), + crate::i18n::fmt(tl!("Subtract from selection ({key})"), &[("key", &crate::shortcuts::pretty("Alt"))]), + crate::i18n::fmt(tl!("Intersect with selection ({key})"), &[("key", &crate::shortcuts::pretty("Shift+Alt"))]), + ]; + for (i, (icon, tip)) in ["square", "plus", "minus", "squares-subtract"].into_iter().zip(tips.iter()).enumerate() { + if crate::icons::button(&mut bui, icon, 26.0, w.lasso_op == i, tip).clicked() { + w.lasso_op = i; + } + } + bui.add_space(8.0); + if widgets::secondary_button(&mut bui, tl!("Expand"), 70.0).clicked() { + fill_btn = Some(json!({"op": "expand", "by": w.expand_by})); + } + if widgets::secondary_button(&mut bui, tl!("Contract"), 70.0).clicked() { + fill_btn = Some(json!({"op": "contract", "by": w.expand_by})); + } + widgets::value_field(&mut bui, &mut w.expand_by, 1.0..=100.0, " px", 56.0).accessible_name(tl!("Expand")); + if crate::icons::button(&mut bui, "undo-2", 26.0, false, tl!("Reset")).clicked() { + reset_what = Some("lasso"); + } + } + _ => {} + } + let body = ERect::from_min_max(pos2(full.left(), bar.bottom()), full.max); + // Left tool strip. + let left = ERect::from_min_size(pos2(full.left(), title.bottom()), vec2(LEFT_W, full.height() - title.height())); + painter.rect_filled(left, 0.0, t.dock); + painter.line_segment([left.right_top(), left.right_bottom()], Stroke::new(1.0, t.separator)); + let mut strip = ui.new_child(egui::UiBuilder::new().max_rect(left.shrink2(vec2(6.0, 8.0)))); + strip.spacing_mut().item_spacing.y = 4.0; + for tool in [CafTool::Brush, CafTool::Lasso, CafTool::Hand, CafTool::Zoom] { + if crate::icons::button(&mut strip, tool_icon(tool), 34.0, w.tool == tool, &tool_tip(tool)).clicked() { + w.tool = tool; + } + } + // Right: the Content-Aware Fill panel. + let right = ERect::from_min_size(pos2(body.right() - PANEL_W, body.top()), vec2(PANEL_W, body.height())); + painter.rect_filled(right, 0.0, t.dock); + painter.line_segment([right.left_top(), right.left_bottom()], Stroke::new(1.0, t.separator)); + let mut props = + ui.new_child(egui::UiBuilder::new().max_rect(ERect::from_min_max(right.min + vec2(14.0, 12.0), pos2(right.right() - 14.0, right.bottom() - 60.0)))); + egui::ScrollArea::vertical().id_salt("caf-props").show(&mut props, |ui| { + ui.spacing_mut().item_spacing.y = 6.0; + egui::CollapsingHeader::new(tl!("Sampling Area Overlay")).id_salt("caf-overlay").default_open(false).show(ui, |ui| { + widgets::checkbox(ui, &mut w.opts.show_overlay, tl!("Show Sampling Area")); + widgets::slider_row(ui, tl!("Opacity"), &mut w.opts.opacity, 0.0..=100.0, "%", None); + ui.horizontal(|ui| { + ui.label(tl!("Color")); + widgets::color_edit_button_srgb(ui, &mut w.opts.color); + ui.add_space(8.0); + ui.label(tl!("Indicates")); + widgets::dropdown( + ui, + "caf-indicates", + tl!("Indicates"), + &mut w.opts.excluded, + &[(false, tl!("Sampling Area")), (true, tl!("Excluded Area"))], + 120.0, + ); + }); + }); + widgets::hairline(ui); + ui.horizontal(|ui| { + widgets::section_label(ui, tl!("Sampling Area Options")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::icons::button(ui, "undo-2", 22.0, false, tl!("Reset")).clicked() { + reset_what = Some("sampling"); + } + }); + }); + ui.horizontal(|ui| { + for (k, l) in [("auto", tl!("Auto")), ("rectangular", tl!("Rectangular")), ("custom", tl!("Custom"))] { + if ui.selectable_label(w.opts.sampling == k, l).clicked() && w.opts.sampling != k { + new_sampling = Some(k); + } + } + }); + if widgets::checkbox(ui, &mut w.opts.sample_all, tl!("Sample All Layers")).changed() { + rebase_needed = true; + } + widgets::hairline(ui); + ui.horizontal(|ui| { + widgets::section_label(ui, tl!("Fill Settings")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::icons::button(ui, "undo-2", 22.0, false, tl!("Reset")).clicked() { + reset_what = Some("fill"); + } + }); + }); + ui.horizontal(|ui| { + ui.label(tl!("Color Adaptation")); + let o = [ + ("none".to_string(), tl!("None")), + ("default".to_string(), tl!("Default")), + ("high".to_string(), tl!("High")), + ("veryHigh".to_string(), tl!("Very High")), + ]; + widgets::dropdown(ui, "caf-color", tl!("Color Adaptation"), &mut w.opts.color_adaptation, &o, 110.0); + }); + ui.horizontal(|ui| { + ui.label(tl!("Rotation Adaptation")); + let o = [ + ("none".to_string(), tl!("None")), + ("low".to_string(), tl!("Low")), + ("medium".to_string(), tl!("Medium")), + ("high".to_string(), tl!("High")), + ("full".to_string(), tl!("Full")), + ]; + widgets::dropdown(ui, "caf-rotation", tl!("Rotation Adaptation"), &mut w.opts.rotation, &o, 110.0); + }); + ui.horizontal(|ui| { + widgets::checkbox(ui, &mut w.opts.scale, tl!("Scale")); + widgets::checkbox(ui, &mut w.opts.mirror, tl!("Mirror")); + }); + widgets::hairline(ui); + widgets::section_label(ui, tl!("Output Settings")); + ui.horizontal(|ui| { + ui.label(tl!("Output To")); + let o = + [("current".to_string(), tl!("Current Layer")), ("new".to_string(), tl!("New Layer")), ("duplicate".to_string(), tl!("Duplicate Layer"))]; + widgets::dropdown(ui, "caf-output", tl!("Output To"), &mut w.opts.output, &o, 140.0); + }); + if let Some(e) = w.error.as_ref().or(w.preview.error.as_ref()) { + ui.label(egui::RichText::new(e.as_str()).color(t.danger).size(11.0)); + } + }); + // Footer, in Photoshop's order on every platform: reset all at the left, then OK, Apply, + // Cancel against the right edge. + let foot = ERect::from_min_size(pos2(right.left() + 10.0, right.bottom() - 48.0), vec2(PANEL_W - 20.0, 32.0)); + let mut fb = ui.new_child(egui::UiBuilder::new().max_rect(foot).layout(egui::Layout::right_to_left(egui::Align::Center))); + if widgets::secondary_button(&mut fb, tl!("Cancel"), 70.0).clicked() { + action = Some("cancel"); + } + if widgets::secondary_button(&mut fb, tl!("Apply"), 70.0).clicked() { + action = Some("apply"); + } + if widgets::primary_button(&mut fb, tl!("OK"), 64.0).clicked() { + action = Some("ok"); + } + if crate::icons::button(&mut fb, "undo-2", 24.0, false, tl!("Reset")).clicked() { + reset_what = Some("all"); + } + // The Preview panel. + let pv_rect = ERect::from_min_size(pos2(right.left() - PREVIEW_W, body.top()), vec2(PREVIEW_W, body.height())); + painter.rect_filled(pv_rect, 0.0, t.dock); + painter.line_segment([pv_rect.left_top(), pv_rect.left_bottom()], Stroke::new(1.0, t.separator)); + painter.text(pv_rect.left_top() + vec2(12.0, 10.0), Align2::LEFT_TOP, tl!("Preview"), FontId::proportional(12.0), t.text); + let pv_area = ERect::from_min_max(pv_rect.min + vec2(0.0, 30.0), pv_rect.max - vec2(0.0, 44.0)); + painter.rect_filled(pv_area, 0.0, t.canvas); + if w.preview.zoom <= 0.0 { + // Opens framed on the sampling window, as Photoshop's. + let win = w.base.window; + if !win.is_empty() { + w.preview.zoom = (pv_area.width() / win.width().max(win.height()) as f32).clamp(0.01, 32.0); + w.preview.center = [f64::from(win.x0 + win.x1) / 2.0, f64::from(win.y0 + win.y1) / 2.0]; + } + } + let pv = View { area: pv_area, zoom: w.preview.zoom.max(0.01), center: w.preview.center }; + let pclip = painter.with_clip_rect(pv_area); + let uv = ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + let img_rect = pv.rect(w.canvas); + widgets::checker(&pclip, img_rect.intersect(pv_area), 8.0); + if let Some(tex) = &w.image_tex { + pclip.image(tex.id(), img_rect, uv, Color32::WHITE); + } + if let Some((tex, r)) = &w.preview.tex { + pclip.image(tex.id(), pv.rect(*r), uv, Color32::WHITE); + } + if w.preview.shown != w.preview.want { + // Being recomputed: a spinner in the corner. + let sp = ERect::from_min_size(pv_area.right_bottom() - vec2(26.0, 26.0), vec2(18.0, 18.0)); + ui.put(sp, egui::Spinner::new().size(16.0)); + } + let presp = ui.interact(pv_area, egui::Id::unique("caf-preview-view"), Sense::click_and_drag()); + if presp.dragged() { + let d = presp.drag_delta(); + w.preview.center = [w.preview.center[0] - f64::from(d.x / pv.zoom), w.preview.center[1] - f64::from(d.y / pv.zoom)]; + } + if presp.hovered() { + let scroll = ui.input(|i| i.smooth_scroll_delta.y); + if scroll != 0.0 { + w.preview.zoom = (w.preview.zoom * (scroll / 200.0).exp()).clamp(0.01, 32.0); + } + } + let zrow = ERect::from_min_size(pos2(pv_rect.left() + 10.0, pv_rect.bottom() - 38.0), vec2(PREVIEW_W - 20.0, 30.0)); + let mut zr = ui.new_child(egui::UiBuilder::new().max_rect(zrow).layout(egui::Layout::left_to_right(egui::Align::Center))); + let mut pct = (w.preview.zoom * 100.0).round(); + if widgets::value_field(&mut zr, &mut pct, 1.0..=3200.0, "%", 64.0).accessible_name(tl!("Zoom")).changed() { + w.preview.zoom = pct / 100.0; + } + let mut lz = pct.max(1.0).ln(); + if zr.add(egui::Slider::new(&mut lz, 0.0..=3200f32.ln()).show_value(false)).accessible_name(tl!("Zoom")).changed() { + w.preview.zoom = lz.exp() / 100.0; + } + // The document view. + let area = ERect::from_min_max(pos2(left.right(), body.top()), pos2(pv_rect.left(), body.bottom())); + painter.rect_filled(area, 0.0, t.canvas); + let (cw, chh) = (w.canvas.width() as f32, w.canvas.height() as f32); + if w.zoom <= 0.0 { + w.zoom = ((area.width() - 40.0) / cw).min((area.height() - 40.0) / chh).clamp(0.01, 4.0); + } + let resp = ui.interact(area, egui::Id::unique("caf-view"), Sense::click_and_drag()); + if resp.hovered() { + let scroll = ui.input(|i| i.smooth_scroll_delta.y); + if scroll != 0.0 + && let Some(hp) = resp.hover_pos() + { + let v = View { area, zoom: w.zoom, center: w.center }; + let before = v.to_doc(hp); + w.zoom = (w.zoom * (scroll / 200.0).exp()).clamp(0.01, 32.0); + let after = View { area, zoom: w.zoom, center: w.center }.to_doc(hp); + w.center = [w.center[0] + before[0] - after[0], w.center[1] + before[1] - after[1]]; + } + } + let v = View { area, zoom: w.zoom, center: w.center }; + let clip = painter.with_clip_rect(area); + let img = v.rect(w.canvas); + widgets::checker(&clip, img.intersect(area), 8.0); + if let Some(tex) = &w.image_tex { + clip.image(tex.id(), img, uv, Color32::WHITE); + } + if let Some(tex) = &w.overlay_tex { + // The proxy's blocks are `k` document px; its last row and column may reach past the + // canvas, so the overlay is clipped to it. + let pr = ERect::from_min_size(img.min, vec2((w.pw * w.k) as f32 * v.zoom, (w.ph * w.k) as f32 * v.zoom)); + clip.with_clip_rect(img.intersect(area)).image(tex.id(), pr, uv, Color32::WHITE); + } + // The fill area's outline (marching ants: black dashes on white). + let phase = (ui.input(|i| i.time) * 8.0) as usize; + match &w.outline { + Some(edges) => { + for e in edges { + let (a, b) = (v.to_screen([f64::from(e[0][0]), f64::from(e[0][1])]), v.to_screen([f64::from(e[1][0]), f64::from(e[1][1])])); + let dark = ((e[0][0] + e[0][1]) as usize / 4 + phase).is_multiple_of(2); + clip.line_segment([a, b], Stroke::new(1.0, if dark { Color32::BLACK } else { Color32::WHITE })); + } + } + None => { + let b = v.rect(bounds(&w.base)); + clip.rect_stroke(b, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Outside); + } + } + ctx.request_repaint_after(std::time::Duration::from_millis(120)); + if let Some((_, pts)) = &w.lasso + && pts.len() > 1 + { + let line: Vec = pts.iter().map(|p| v.to_screen(*p)).collect(); + clip.add(egui::Shape::line(line, Stroke::new(1.0, t.accent))); + } + if let Some(hp) = resp.hover_pos() { + if w.tool == CafTool::Brush { + let r = w.brush_size as f32 * 0.5 * v.zoom; + clip.circle_stroke(hp, r, Stroke::new(1.5, Color32::BLACK)); + clip.circle_stroke(hp, r, Stroke::new(0.75, Color32::WHITE)); + } + w.hover = Some(v.to_doc(hp)); + } + clip.rect_stroke(img, 0.0, Stroke::new(1.0, t.separator), egui::StrokeKind::Outside); + // Mouse → tools (Space, the middle button or the Hand pan). + let pan = ui.input(|i| i.key_down(egui::Key::Space) || i.pointer.middle_down()) || w.tool == CafTool::Hand; + if pan && resp.dragged() { + let dl = resp.drag_delta(); + w.center = [w.center[0] - f64::from(dl.x / w.zoom), w.center[1] - f64::from(dl.y / w.zoom)]; + } else if !pan + && resp.is_pointer_button_down_on() + && let Some(pp) = resp.interact_pointer_pos() + { + // The press is the first point; the frames before egui's drag threshold and the drag + // itself continue it (a second `Down` would start the stroke over, dropping them). + let q = v.to_doc(pp); + mods = ui.input(|i| i.modifiers); + if w.pressed { + events.push(ToolEvent::Move { x: q[0], y: q[1], pressure: 1.0 }); + ctx.request_repaint(); + } else { + w.pressed = true; + events.push(ToolEvent::Down { x: q[0], y: q[1], pressure: 1.0 }); + } + dragging = true; + } + if w.pressed && !resp.is_pointer_button_down_on() { + w.pressed = false; + let q = w.hover.unwrap_or(w.center); + events.push(ToolEvent::Up { x: q[0], y: q[1] }); + dragging = false; + } + // Settings changed in the panel: the overlay and the preview follow. + if w.opts != before { + w.overlay_dirty = true; + w.stale(); + } + }); + if let Some(s) = new_sampling { + set_sampling(app, s); + } + if let Some(r) = reset_what { + reset(app, r); + } + if let Some(e) = fill_btn { + fill_edit(app, e); + } + if rebase_needed { + rebase(app); + } + for ev in events { + pointer(app, ev, mods); + } + drive_preview(app, ctx, dragging); + match action { + Some("ok") => commit(app), + Some("cancel") => cancel(app), + Some("apply") => { + if let Err(e) = apply(app) { + report(app, e); + } + } + _ => {} + } +} From 07b6d0602d72310dc4731757c3ddfc686396b981 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:22:42 +0000 Subject: [PATCH 232/259] refactor(ui-egui): split camera_raw_ui.rs into camera_raw_ui/ --- crates/ui-egui/src/camera_raw_ui.rs | 1607 +----------------- crates/ui-egui/src/camera_raw_ui/controls.rs | 513 ++++++ crates/ui-egui/src/camera_raw_ui/convert.rs | 192 +++ crates/ui-egui/src/camera_raw_ui/menu.rs | 169 ++ crates/ui-egui/src/camera_raw_ui/open.rs | 496 ++++++ crates/ui-egui/src/camera_raw_ui/proxy.rs | 79 + crates/ui-egui/src/camera_raw_ui/sidecar.rs | 155 ++ 7 files changed, 1627 insertions(+), 1584 deletions(-) create mode 100644 crates/ui-egui/src/camera_raw_ui/controls.rs create mode 100644 crates/ui-egui/src/camera_raw_ui/convert.rs create mode 100644 crates/ui-egui/src/camera_raw_ui/menu.rs create mode 100644 crates/ui-egui/src/camera_raw_ui/open.rs create mode 100644 crates/ui-egui/src/camera_raw_ui/proxy.rs create mode 100644 crates/ui-egui/src/camera_raw_ui/sidecar.rs diff --git a/crates/ui-egui/src/camera_raw_ui.rs b/crates/ui-egui/src/camera_raw_ui.rs index 411d963c4f..85dc6d011c 100644 --- a/crates/ui-egui/src/camera_raw_ui.rs +++ b/crates/ui-egui/src/camera_raw_ui.rs @@ -27,6 +27,29 @@ use crate::PhotocraftApp; use crate::theme::Tokens; use crate::widgets; +mod controls; +mod convert; +mod menu; +mod open; +mod proxy; +mod sidecar; + +pub use controls::show; +#[cfg(test)] +use convert::open_pixels; +pub use menu::menu; +#[cfg(test)] +use open::{Coverage, commit_open_raw, document_index, finish_redevelop, open_raw, replace_raw_document}; +pub use open::{ + REDEVELOP_JOB, RawOpen, Redevelop, on_redevelop_event, open, open_smart_filter, opened_without_dialog, queue_open_dialog, wants_open_dialog, + without_develop_note, +}; +use open::{Target, non_defaults}; +use proxy::{ProxyFrame, ProxyJob}; +pub use sidecar::sidecar_path; +#[cfg(test)] +use sidecar::{existing_sidecar_is_ours, read_bounded}; + const PROXY_SIDE: usize = 900; /// Smallest run of proxy pixels one rayon task takes in the per-pixel passes: below it the /// split costs more than the work. @@ -273,1593 +296,9 @@ impl CameraRawDialog { } } -/// Everything one develop of the proxy reads, owned, so it can run off the UI thread. -struct ProxyJob { - proxy: std::sync::Arc>, - selection: Option>>, - raw_curve: Option>>, - params: CameraRaw, - float: bool, - size: (usize, usize), - full_w: usize, - display: std::sync::Arc, - gpu: Option, - source_key: u64, -} - -/// A developed proxy, ready to show. -struct ProxyFrame { - px: Vec<[f32; 4]>, - histogram: RgbHistogram, - histogram_ms: f64, - image: egui::ColorImage, - display: std::sync::Arc, - ms: f64, - develop_ms: f64, - backend: &'static str, -} - -impl ProxyJob { - fn run(self) -> ProxyFrame { - let t0 = crate::gpu_canvas::now_ms(); - let (pw, ph) = self.size; - let mut p = self.params; - p.pixel_scale = (pw as f32 / self.full_w.max(1) as f32).min(1.0); - // The open-time dialog re-tones the proxy for each job; otherwise the GPU reads the - // proxy as it is and uploads it once. - let retoned = self.raw_curve.as_ref().map(|curve| { - let mut px = self.proxy.to_vec(); - photocraft_io::raw::retone(&mut px, pw, ph, curve, raw_stage(&p)); - px - }); - if retoned.is_some() { - (p.shadows, p.highlights, p.clarity, p.texture, p.dehaze) = (0.0, 0.0, 0.0, 0.0, 0.0); - } - let develop_start = crate::gpu_canvas::now_ms(); - let key = retoned.is_none().then_some(self.source_key); - let input = retoned.as_deref().unwrap_or(&self.proxy); - let (mut px, backend) = match self.gpu.as_ref().and_then(|g| g.develop(input, key, pw, ph, &p, self.float)) { - Some(out) => (out, "gpu"), - None => { - let mut px = retoned.unwrap_or_else(|| self.proxy.to_vec()); - photocraft_algo::camera_raw::develop(&mut px, pw, ph, &p, self.float); - (px, "cpu") - } - }; - let develop_ms = crate::gpu_canvas::now_ms() - develop_start; - if let Some(mask) = &self.selection { - let blend = |(out, (original, coverage)): (&mut [f32; 4], (&[f32; 4], &f32))| { - for (out, original) in out.iter_mut().zip(original) { - *out = *original + (*out - *original) * coverage; - } - }; - // Each pixel is independent, so bands of the proxy blend in parallel (#211, P36). - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - px.par_iter_mut().zip(self.proxy.par_iter().zip(mask.par_iter())).with_min_len(PARALLEL_MIN_PIXELS).for_each(blend); - } - #[cfg(target_arch = "wasm32")] - px.iter_mut().zip(self.proxy.iter().zip(mask.iter())).for_each(blend); - } - let histogram_start = crate::gpu_canvas::now_ms(); - let histogram = RgbHistogram::from_rgba(&px); - let histogram_ms = crate::gpu_canvas::now_ms() - histogram_start; - let image = CameraRawDialog::image(&px, pw, ph, &self.display); - ProxyFrame { px, histogram, histogram_ms, image, display: self.display, ms: crate::gpu_canvas::now_ms() - t0, develop_ms, backend } - } -} - -/// Opens the dialog on the active layer. -/// Where OK writes: a new filter on the layer, or an existing smart filter (by index). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Target { - NewFilter, - SmartFilter(usize), - /// The open-time dialog of a raw file just opened (File › Open): OK is **Open**, Cancel - /// closes the document again. See [`RawOpen`]. - OpenRaw, -} - -/// 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. -#[derive(Clone, Debug)] -pub struct RawOpen { - pub document: photocraft_doc::DocId, - pub name: String, - pub path: Option, - /// The file, when it was opened from bytes (no path to read it again from). - pub bytes: Option>>, - /// The demosaic method the open developed it with. - 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, -} - -/// Should an interactive open of `name` show the open-time Camera Raw dialog? `warnings` are -/// the import's: only a raw developed from its sensor data qualifies (not a preview fallback). -pub fn wants_open_dialog(app: &PhotocraftApp, warnings: &[String]) -> bool { - app.session.prefs().raw_defaults.open_in_camera_raw && warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)) -} - -/// `warnings` without the "developed with default settings" note: the open-time dialog shows -/// how the raw is developed. -pub fn without_develop_note(warnings: &[String]) -> Vec { - warnings.iter().filter(|w| !w.contains(photocraft_io::raw::DEVELOPED_NOTE)).cloned().collect() -} - -/// Queues the open-time dialog for the document whose import completed, independent of the -/// active tab. A delayed completion for a closed document must not review another photograph. -/// `warnings` are the import's: its note says which demosaic method the open developed with. -pub fn queue_open_dialog( - app: &mut PhotocraftApp, - document: photocraft_doc::DocId, - name: &str, - path: Option<&str>, - bytes: Option<&[u8]>, - warnings: &[String], -) -> Result<(), String> { - if document_index(app, document).is_none() { - return Err("the imported raw document is missing".into()); - } - // The method the open actually used (`jobs::import_options` at the job's start), from its - // note: the preference may have changed while a background open ran. - let method = photocraft_io::raw::developed_demosaic(warnings).unwrap_or_else(|| app.session.prefs().raw_defaults.demosaic.method()); - app.pending_raw_open = Some(RawOpen { - document, - name: name.to_string(), - path: path.map(str::to_string), - bytes: bytes.map(|b| std::sync::Arc::new(b.to_vec())), - developed_with: method, - demosaic: method, - }); - Ok(()) -} - -/// Opens the queued open-time dialog on its document's (only) layer. -fn open_raw(app: &mut PhotocraftApp, ctx: &egui::Context, raw: RawOpen) -> 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)?; - // The file's sidecar (`IMG_0001.xmp` beside it) fills the dialog, as Camera Raw's does; the - // status bar names what it could not apply. - let mut params = CameraRaw::default(); - let mut from_sidecar = false; - if let Some((loaded, report, file)) = raw.path.as_deref().and_then(read_sidecar) { - params = loaded; - from_sidecar = true; - app.ui.status = if report.ignored.is_empty() { - crate::i18n::fmt(tl!("Settings from {name}"), &[("name", &file)]) - } else { - crate::i18n::fmt( - tl!("Settings from {name}; {count} not supported: {names}"), - &[("name", &file), ("count", &report.ignored.len().to_string()), ("names", &report.ignored.join(", "))], - ) - }; - app.ui.status_error = false; - } - open_pixels(app, ctx, layer, surf, params, Coverage::None, Target::OpenRaw)?; - // Camera Raw Defaults › Apply auto tone: a file without its own settings opens with Auto. - if !from_sidecar - && app.session.prefs().raw_defaults.apply_auto_tone - && let Some(d) = app.camera_raw.as_mut() - { - photocraft_algo::camera_raw::auto_tone(&d.proxy, &mut d.params); - d.dirty = true; - } - let curve = match (&raw.bytes, &raw.path) { - (Some(b), _) => Some(photocraft_io::raw::tone_curve(b)), - #[cfg(not(target_arch = "wasm32"))] - (None, Some(p)) => std::fs::read(p).ok().map(|b| photocraft_io::raw::tone_curve(&b)), - _ => None, - }; - if let Some(d) = app.camera_raw.as_mut() { - d.layer_name = raw.name.clone(); - // The full-size preview retones the whole frame with it, as Open will. - let curve = curve.map(std::sync::Arc::new); - d.detail.raw_curve = curve.clone(); - d.raw_curve = curve; - d.raw_open = Some(raw); - } - Ok(()) -} - -fn document_index(app: &PhotocraftApp, id: photocraft_doc::DocId) -> Option { - app.session.documents().iter().position(|st| st.doc.id == id) -} - -/// The non-default settings of `p` as engine params. -fn non_defaults(p: &CameraRaw) -> Value { - let full = serde_json::to_value(p).unwrap_or(json!({})); - let def = serde_json::to_value(CameraRaw::default()).unwrap_or(json!({})); - let mut out = serde_json::Map::new(); - if let (Value::Object(f), Value::Object(d)) = (full, def) { - for (k, v) in f { - if k != "pixelScale" && d.get(&k) != Some(&v) { - out.insert(k, v); - } - } - } - Value::Object(out) -} - -/// The job id of an open-time re-develop (not an engine command: the shell starts it). -pub const REDEVELOP_JOB: &str = "cameraRaw.redevelop"; - -/// An open-time re-develop running in the background: what to finish with when it lands. -#[derive(Clone, Debug)] -pub struct Redevelop { - pub job: photocraft_engine::jobs::JobId, - params: CameraRaw, - raw: RawOpen, - /// The job is the final Camera Raw step (`filter.cameraRaw`), not the re-develop: when it - /// lands the Camera Raw Defaults' conversions follow and the document is marked unmodified. - filter_step: bool, - /// The Camera Raw Defaults the open started with, for the conversions after the filter step. - defaults: photocraft_engine::prefs::RawDefaults, -} - -/// The sliders a raw open applies while developing, before the tone curve (as Camera Raw does). -fn raw_stage(p: &CameraRaw) -> photocraft_io::raw::Tone { - photocraft_io::raw::Tone { shadows: p.shadows, highlights: p.highlights, clarity: p.clarity, texture: p.texture, dehaze: p.dehaze } -} - -/// Open: re-develop for raw-stage settings, apply the rest, keep the document unmodified. -/// -/// Re-developing reads and decodes the whole raw again, so in the desktop app (background jobs -/// on) it runs as a job like the open itself: the reply is `{"job", "pending": true}`, the -/// document is locked meanwhile, and [`on_redevelop_event`] finishes when it lands. Elsewhere -/// (tests, the web) it runs inline. -fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen, loaded: Option<&CameraRaw>) -> Result { - let index = document_index(app, raw.document).ok_or("the raw document was closed")?; - write_sidecar(app, raw, params, loaded); - let tuning = photocraft_io::raw::RawTuning { - temperature: params.temperature, - tint: params.tint, - exposure: params.exposure, - demosaic: raw.demosaic, - shadows: params.shadows, - highlights: params.highlights, - clarity: params.clarity, - texture: params.texture, - dehaze: params.dehaze, - }; - // 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() }; - // Without the file the raw-stage settings stay RGB adjustments, like the filter's. - let source = match (&raw.bytes, &raw.path) { - (Some(b), _) => Some(photocraft_engine::jobs::OpenSource::Bytes(b.clone())), - #[cfg(not(target_arch = "wasm32"))] - (None, Some(p)) => Some(photocraft_engine::jobs::OpenSource::Path(p.clone())), - _ => None, - }; - let Some(source) = source.filter(|_| tuning != as_opened) else { - let defaults = app.session.prefs().raw_defaults.clone(); - return finish_open_raw(app, index, params.clone(), None, raw, &defaults); - }; - app.session.set_active(index); - let (name, doc_id) = (raw.name.clone(), raw.document); - let work = move |ctx: &photocraft_engine::jobs::JobCtx| -> photocraft_engine::Result<(photocraft_io::ImportResult, bool)> { - ctx.progress(0.0, "Reading"); - let bytes = match source { - photocraft_engine::jobs::OpenSource::Bytes(b) => b, - #[cfg(not(target_arch = "wasm32"))] - photocraft_engine::jobs::OpenSource::Path(p) => { - std::sync::Arc::new(std::fs::read(&p).map_err(|e| photocraft_engine::EngineError::Other(format!("{p}: {e}")))?) - } - #[cfg(target_arch = "wasm32")] - photocraft_engine::jobs::OpenSource::Path(p) => return Err(photocraft_engine::EngineError::Other(format!("{p}: cannot read files here"))), - }; - ctx.check()?; - ctx.progress(0.05, "Developing"); - photocraft_io::raw::import_raw_tuned(&name, &bytes, &tuning).map_err(|e| photocraft_engine::EngineError::Other(e.to_string())) - }; - let apply = move |s: &mut photocraft_engine::Session, (r, wb): (photocraft_io::ImportResult, bool)| replace_raw_document(s, doc_id, r, wb); - let label = crate::i18n::fmt(tl!("Developing {name}"), &[("name", &raw.name)]); - let started = if app.background_jobs { - app.session.start_job(REDEVELOP_JOB, json!({"name": raw.name}), &label, true, work, apply).map_err(|e| e.to_string())? - } else { - let v = work(&photocraft_engine::jobs::JobCtx::new()).and_then(|t| apply(&mut app.session, t)).map_err(|e| e.to_string())?; - photocraft_engine::jobs::Started::Done(v) - }; - match started { - photocraft_engine::jobs::Started::Done(v) => { - let defaults = app.session.prefs().raw_defaults.clone(); - finish_redevelop(app, params, raw, &v, &defaults) - } - photocraft_engine::jobs::Started::Job(job) => { - let defaults = app.session.prefs().raw_defaults.clone(); - app.raw_redevelop.push(Redevelop { job, params: params.clone(), raw: raw.clone(), filter_step: false, defaults }); - app.ui.status = label; - app.ui.status_error = false; - Ok(json!({"job": job.0, "pending": true})) - } - } -} - -/// Swap the default-developed document `doc_id` for the re-developed one, at the same tab -/// position and with the same path. Returns `{document, docId, previous, warnings, wb}`: -/// `document` is the tab index at apply time, `docId` is the replacement's stable identity. -fn replace_raw_document( - s: &mut photocraft_engine::Session, - doc_id: photocraft_doc::DocId, - mut r: photocraft_io::ImportResult, - wb: bool, -) -> photocraft_engine::Result { - let index = - s.documents().iter().position(|st| st.doc.id == doc_id).ok_or_else(|| photocraft_engine::EngineError::Other("the raw document was closed".into()))?; - let path = s.documents().get(index).and_then(|st| st.path.clone()); - // The resolution it opened with (Preferences › Raw Defaults), which re-developing keeps. - if let Some(st) = s.documents().get(index) { - r.document.resolution_dpi = st.doc.resolution_dpi; - } - s.close(index); - let (opened, _) = s.open_document(r.document, path); - let replacement = s.documents().get(opened).ok_or(photocraft_engine::EngineError::NoDocument)?.doc.id; - let index = match s.execute("document.move", json!({"document": opened, "to": index})) { - Ok(moved) => moved.get("document").and_then(Value::as_u64).map_or(opened, |i| i as usize), - Err(_) => opened, - }; - s.set_active(index); - Ok(json!({"document": index, "docId": replacement.0, "previous": doc_id.0, "warnings": r.warnings, "wb": wb})) -} - -/// After the re-develop: keep the old document's view (zoom, scroll) on the new one, report -/// the import's notes, then apply the remaining settings. -fn finish_redevelop( - app: &mut PhotocraftApp, - params: &CameraRaw, - raw: &RawOpen, - v: &Value, - defaults: &photocraft_engine::prefs::RawDefaults, -) -> Result { - // A preceding completion (for example Save and Close) may have shifted the tab indices. - // Validate identity before remapping views, filtering or marking any document unmodified. - let replacement = v.get("docId").and_then(Value::as_u64).map(photocraft_doc::DocId).ok_or("the re-develop returned no document identity")?; - let index = document_index(app, replacement).ok_or("the re-developed document was closed")?; - for id in app.view_docs.iter_mut().filter(|id| **id == raw.document) { - *id = replacement; - } - let warnings: Vec = - v.get("warnings").and_then(Value::as_array).map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default(); - crate::notices::io_warnings(app, &format!("Opened {}", raw.name), &without_develop_note(&warnings)); - let mut rest = params.clone(); - rest.exposure = 0.0; - rest.shadows = 0.0; - rest.highlights = 0.0; - rest.clarity = 0.0; - rest.texture = 0.0; - rest.dehaze = 0.0; - if v.get("wb").and_then(Value::as_bool) == Some(true) { - rest.temperature = 0.0; - rest.tint = 0.0; - } - finish_open_raw(app, index, rest, Some(true), raw, defaults) -} - -/// The other settings as one Camera Raw step on document `index`, then the Camera Raw Defaults' -/// conversions, then the document is marked unmodified (developing is part of opening). The -/// step runs like any filter (in the background in the desktop app); the conversions follow and -/// the document is marked unmodified when it lands. The step works on the developed ProPhoto -/// pixels the dialog previewed, and the conversion to the workflow space comes last, as in -/// Camera Raw. -fn finish_open_raw( - app: &mut PhotocraftApp, - index: usize, - mut rest: CameraRaw, - redeveloped: Option, - raw: &RawOpen, - d: &photocraft_engine::prefs::RawDefaults, -) -> Result { - app.session.set_active(index); - app.sync_views(); - let mut result = json!({"document": index, "redeveloped": redeveloped.unwrap_or(false)}); - let mut applied = output_sharpening(d, &mut rest); - applied.extend(raw_conversions(d)); - if !applied.is_empty() { - result["defaults"] = json!(applied); - } - if !rest.is_identity() { - let layer = app.session.active().and_then(|st| st.active_layer).ok_or("no layer to develop")?; - let mut p = non_defaults(&rest); - p["layer"] = json!(layer.0); - let r = app.run("filter.cameraRaw", p)?; - if r.get("pending").and_then(Value::as_bool) == Some(true) - && let Some(job) = r.get("job").and_then(Value::as_u64) - { - let job = photocraft_engine::jobs::JobId(job); - app.raw_redevelop.push(Redevelop { job, params: rest.clone(), raw: raw.clone(), filter_step: true, defaults: d.clone() }); - result["filter"] = r; - mark_unmodified(app, index); - return Ok(result); - } - result["filter"] = r; - } - // The Camera Raw step has landed: a failed conversion is reported, and the open still - // completes (a second Open would apply the step twice). - if let Err(e) = apply_raw_conversions(app, index, d) { - crate::notices::error(app, format!("{}: {e}", raw.name)); - } - mark_unmodified(app, index); - Ok(result) -} - -/// The sidecar beside a raw file: `IMG_0001.xmp` for `IMG_0001.CR2`, as Camera Raw names it. -pub fn sidecar_path(path: &str) -> String { - match path.rsplit_once('.') { - Some((stem, ext)) if !ext.contains(['/', '\\']) => format!("{stem}.xmp"), - _ => format!("{path}.xmp"), - } -} - -/// A DNG carries its settings inside the file in Camera Raw; a sidecar is read for one too, -/// but never written beside it. -fn is_dng(path: &str) -> bool { - path.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("dng")) -} - -/// The settings of the sidecar beside `path`, when there is one that parses: the settings, what -/// the loader skipped, and the sidecar's file name. A sidecar that doesn't parse is ignored (the -/// raw still opens) and reported in the log. -#[cfg(not(target_arch = "wasm32"))] -fn read_sidecar(path: &str) -> Option<(CameraRaw, photocraft_io::camera_raw_xmp::LoadReport, String)> { - let sidecar = sidecar_path(path); - let Some(bytes) = read_bounded(&sidecar) else { - log::warn!("{sidecar}: not a readable sidecar of at most {} bytes, ignored", photocraft_io::camera_raw_xmp::MAX_XMP_BYTES); - return None; - }; - let mut params = CameraRaw::default(); - match photocraft_io::camera_raw_xmp::load(&mut params, &bytes) { - Ok(report) => Some((params, report, crate::file_open::display_name(&sidecar))), - Err(e) => { - log::warn!("{sidecar}: sidecar ignored: {e}"); - None - } - } -} -#[cfg(target_arch = "wasm32")] -fn read_sidecar(_: &str) -> Option<(CameraRaw, photocraft_io::camera_raw_xmp::LoadReport, String)> { - None -} - -/// Keep the develop settings beside the raw file (Camera Raw Defaults › Write xmp sidecars): -/// written when the settings aren't the defaults or PhotoCraft's own sidecar is there, so a -/// file reopens as it was developed. `loaded` are the settings the open started from: nothing -/// is written when they didn't change. Not for DNGs, never over a sidecar another application -/// wrote (Lightroom's and Bridge's hold crops, masks, ratings and keywords PhotoCraft can't keep), -/// never for a control or MCP request (it has no authority to write beside the user's files), and -/// never fatal: a folder that can't be written to is reported in a notice. -fn write_sidecar(app: &mut PhotocraftApp, raw: &RawOpen, params: &CameraRaw, loaded: Option<&CameraRaw>) { - if !app.session.prefs().raw_defaults.write_xmp_sidecars || loaded == Some(params) { - return; - } - if app.automation_input || app.session.authorize.is_some() { - log::info!("{}: sidecar not written for an automation request", raw.name); - return; - } - let Some(path) = raw.path.as_deref().filter(|p| !is_dng(p)) else { return }; - let sidecar = sidecar_path(path); - let name = crate::file_open::display_name(&sidecar); - match existing_sidecar_is_ours(&sidecar) { - Some(false) => { - let kept = crate::i18n::fmt(tl!("Kept {name}: written by another application"), &[("name", &name)]); - crate::notices::post(app, kept, Vec::new(), false, None); - return; - } - None if params.is_identity() => return, - _ => {} - } - let bytes = photocraft_io::camera_raw_xmp::save(params).into_bytes(); - let Some(write) = app.services.write.as_mut() else { return }; - if let Err(e) = write(&sidecar, &bytes) { - crate::notices::error(app, crate::i18n::fmt(tl!("Could not write {name}: {error}"), &[("name", &name), ("error", &e)])); - } -} - -/// `None` when there is no sidecar at `sidecar`, else whether PhotoCraft wrote it. One that -/// can't be read or is too large to be ours counts as another application's. -#[cfg(not(target_arch = "wasm32"))] -fn existing_sidecar_is_ours(sidecar: &str) -> Option { - std::fs::symlink_metadata(sidecar).ok()?; - Some(read_bounded(sidecar).is_some_and(|b| photocraft_io::camera_raw_xmp::is_photocraft_xmp(&b))) -} - -/// The bytes of the regular file at `path` when it holds at most -/// [`photocraft_io::camera_raw_xmp::MAX_XMP_BYTES`]; `None` for anything else (missing, a folder, -/// a pipe or device that might never end, larger). Never reads more than the cap plus one byte. -#[cfg(not(target_arch = "wasm32"))] -fn read_bounded(path: &str) -> Option> { - use std::io::Read; - let cap = photocraft_io::camera_raw_xmp::MAX_XMP_BYTES; - // Checked before opening: opening a pipe for reading waits for a writer. - if !std::fs::metadata(path).ok()?.is_file() { - return None; - } - let file = std::fs::File::open(path).ok()?; - let mut bytes = Vec::new(); - file.take(cap as u64 + 1).read_to_end(&mut bytes).ok()?; - (bytes.len() <= cap).then_some(bytes) -} -#[cfg(target_arch = "wasm32")] -fn existing_sidecar_is_ours(_: &str) -> Option { - None -} - -/// Camera Raw Defaults › Sharpen For: output sharpening, folded into the Camera Raw step `rest` -/// as the workflow's Sharpen For is. Returns what it applied. -fn output_sharpening(d: &photocraft_engine::prefs::RawDefaults, rest: &mut CameraRaw) -> Vec<&'static str> { - match d.sharpen_for.preset() { - Some((amount, radius)) if rest.sharpen_amount == 0.0 => { - rest.sharpen_amount = amount; - rest.sharpen_radius = radius; - vec!["sharpenFor"] - } - _ => Vec::new(), - } -} - -/// The Camera Raw Defaults [`apply_raw_conversions`] applies. Resolution is not among them: the -/// open itself sets it (`file_cmds::raw_defaults`), and a re-develop keeps it. -fn raw_conversions(d: &photocraft_engine::prefs::RawDefaults) -> Vec<&'static str> { - use photocraft_engine::prefs::{RawColorSpace, RawDepth}; - let mut out = Vec::new(); - // Raws develop into ProPhoto-compatible RGB (`photocraft_io::raw`); the other spaces are a - // conversion. - if d.color_space != RawColorSpace::ProPhoto { - out.push("colorSpace"); - } - if d.bit_depth == RawDepth::Eight { - out.push("bitDepth"); - } - if d.open_as_smart_object { - out.push("openAsSmartObject"); - } - out -} - -/// Camera Raw Defaults (Preferences) after the Camera Raw step: the colour space and bit depth -/// the developed document opens in, and Open as Smart Object. -fn apply_raw_conversions(app: &mut PhotocraftApp, index: usize, d: &photocraft_engine::prefs::RawDefaults) -> Result<(), String> { - app.session.set_active(index); - for step in raw_conversions(d) { - let (id, params) = match step { - "colorSpace" => ("edit.convertToProfile", json!({"profile": d.color_space.profile_id(), "intent": "relative"})), - "bitDepth" => ("image.mode.bits8", json!({})), - _ => ("layer.smartObjects.convertToSmartObject", json!({})), - }; - app.session.execute(id, params).map_err(|e| e.to_string())?; - } - Ok(()) -} - -/// A raw that opened without the dialog (Camera Raw Defaults › Open in Camera Raw off): its -/// sidecar's settings develop it as the dialog's Open would, and the Camera Raw Defaults apply. -/// `warnings` are the import's; only a developed raw qualifies. -pub fn opened_without_dialog(app: &mut PhotocraftApp, index: usize, name: &str, path: Option<&str>, warnings: &[String]) { - if !warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)) { - return; - } - 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 params = CameraRaw::default(); - let sidecar = path.and_then(read_sidecar).map(|(loaded, _, _)| loaded); - if let Some(loaded) = &sidecar { - params = loaded.clone(); - } else if app.session.prefs().raw_defaults.apply_auto_tone - && let Some(px) = app.session.active().and_then(|st| st.doc.layer(st.active_layer?)).and_then(|l| l.surface()).map(|s| sample_pixels(s, 512)) - { - photocraft_algo::camera_raw::auto_tone(&px, &mut params); - } - let r = if params.is_identity() { - let defaults = app.session.prefs().raw_defaults.clone(); - finish_open_raw(app, index, params, None, &raw, &defaults) - } else { - commit_open_raw(app, ¶ms, &raw, sidecar.as_ref()) - }; - if let Err(e) = r { - app.ui.status = e; - app.ui.status_error = true; - } -} - -/// Every k-th pixel of a surface's content, k chosen so the longer side has about `max_side` -/// samples: enough for a histogram (Auto tone) without reading a whole raw. -fn sample_pixels(surf: &photocraft_raster::Surface, max_side: usize) -> Vec<[f32; 4]> { - let area = surf.content_bounds(); - let (w, h) = (area.x1.saturating_sub(area.x0).max(0) as usize, area.y1.saturating_sub(area.y0).max(0) as usize); - if w == 0 || h == 0 { - return Vec::new(); - } - let k = w.max(h).div_ceil(max_side.max(1)).max(1); - let mut out = Vec::with_capacity(w.div_ceil(k) * h.div_ceil(k)); - let mut row = vec![[0.0f32; 4]; w]; - for y in (0..h).step_by(k) { - let yy = area.y0.saturating_add(y as i32); - surf.read_rgba_into(Rect::new(area.x0, yy, area.x1, yy.saturating_add(1)), &mut row); - out.extend(row.iter().step_by(k).copied()); - } - out -} - -fn mark_unmodified(app: &mut PhotocraftApp, index: usize) { - let active = app.session.active_index(); - app.session.set_active(index); - if let Some(st) = app.session.active_mut() { - st.saved_revision = st.revision; - } - if let Some(i) = active { - app.session.set_active(i); - } - app.sync_views(); -} - -/// A finished background re-develop ([`REDEVELOP_JOB`]) or open-time Camera Raw step. `true` -/// when the event was one of those (handled here). -pub fn on_redevelop_event(app: &mut PhotocraftApp, e: &photocraft_engine::jobs::JobEvent) -> bool { - let Some(at) = app.raw_redevelop.iter().position(|r| r.job == e.id) else { return false }; - let pending = app.raw_redevelop.remove(at); - if pending.filter_step { - // The Camera Raw Defaults' conversions follow the Camera Raw step, whatever its outcome: - // the document still opens in the workflow's colour space and depth. - if let Some(index) = e.document.and_then(|id| document_index(app, id)) { - let active = app.session.active_index(); - if let Err(err) = apply_raw_conversions(app, index, &pending.defaults) { - crate::notices::error(app, format!("{}: {err}", pending.raw.name)); - } - if let Some(i) = active { - app.session.set_active(i); - } - if matches!(e.outcome, photocraft_engine::jobs::JobOutcome::Done(_)) { - mark_unmodified(app, index); - } - app.sync_views(); - } - // The usual filter reporting still applies. - return false; - } - match &e.outcome { - photocraft_engine::jobs::JobOutcome::Done(v) => match finish_redevelop(app, &pending.params, &pending.raw, v, &pending.defaults) { - Ok(_) => { - app.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", &pending.raw.name)]); - app.ui.status_error = false; - } - Err(err) => crate::notices::error(app, format!("{}: {err}", e.label)), - }, - photocraft_engine::jobs::JobOutcome::Failed(err) => { - // The document stays open, developed with the defaults. - app.sync_views(); - crate::notices::error(app, format!("{}: {err}", e.label)); - } - photocraft_engine::jobs::JobOutcome::Cancelled => { - app.ui.status = crate::i18n::fmt(tl!("Cancelled {label}"), &[("label", &e.label)]); - app.ui.status_error = false; - } - } - true -} - -/// Cancel: closes the dialog; for the open-time dialog also the document it was opening. -fn cancel(app: &mut PhotocraftApp) { - let Some(d) = app.camera_raw.take() else { return }; - if let (Target::OpenRaw, Some(raw)) = (d.target, &d.raw_open) - && let Some(index) = document_index(app, raw.document) - { - app.session.close(index); - app.sync_views(); - app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &raw.name)]); - app.ui.status_error = false; - } -} - -/// What limits the preview: the document selection (a new filter applies through it, as the -/// engine does), a smart object's filter mask, or nothing. -enum Coverage { - Selection, - Mask(photocraft_doc::LayerMask), - None, -} - -pub fn open(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { - 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)?; - open_pixels(app, ctx, layer, surf, CameraRaw::default(), Coverage::Selection, Target::NewFilter) -} - -/// Opens Camera Raw on smart filter `index` of smart layer `layer`, with its stored settings and -/// the pixels below it; OK updates that filter (`layer.smartFilter.setParams`), as double-clicking -/// a Camera Raw smart filter does in Photoshop. -pub fn open_smart_filter(app: &mut PhotocraftApp, ctx: &egui::Context, layer: LayerId, index: usize) -> Result<(), String> { - use photocraft_engine::lens_cmds::{RAW, raw_params}; - let st = app.session.active().ok_or("no document")?; - let Some(photocraft_doc::LayerContent::Smart(sm)) = st.doc.layer(layer).map(|l| &l.content) else { - return Err("the layer is not a smart object".into()); - }; - 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()); - } - 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) - .map_err(|e| e.to_string())? - .ok_or("the smart object's contents are unavailable (missing linked file?)")?; - let coverage = sm.filter_mask.clone().filter(|m| m.enabled).map_or(Coverage::None, Coverage::Mask); - open_pixels(app, ctx, layer, surf, params, coverage, Target::SmartFilter(index)) -} - -fn open_pixels( - app: &mut PhotocraftApp, - ctx: &egui::Context, - layer: LayerId, - surf: photocraft_raster::Surface, - params: CameraRaw, - coverage: Coverage, - target: Target, -) -> Result<(), String> { - let st = app.session.active().ok_or("no document")?; - let canvas = st.doc.bounds(); - let name = st.doc.layer(layer).map(|l| l.name.clone()).unwrap_or_default(); - let mut params = params; - if params.encoding_gamma == 0.0 { - params.encoding_gamma = photocraft_engine::lens_cmds::encoding_gamma(&st.doc); - } - // Use the engine filter domain, including pixels outside the canvas: spatial Camera Raw - // stages (vignette, grain, local contrast) must agree with the committed result. - let area = canvas.union(&surf.content_bounds()); - 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()); - }; - 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()); - } - let k = w.max(h).div_ceil(PROXY_SIDE).max(1); - let (pw, ph) = (w.div_ceil(k), h.div_ceil(k)); - let mut proxy = vec![[0.0f32; 4]; pw * ph]; - let mut row = vec![[0.0f32; 4]; w]; - for py in 0..ph { - // Box-average k×k blocks. - let mut acc = vec![[0.0f32; 5]; pw]; - for dy in 0..k { - let y = area.y0 + (py * k + dy).min(h - 1) as i32; - surf.read_rgba_into(Rect::new(area.x0, y, area.x1, y + 1), &mut row); - for (x, q) in row.iter().enumerate() { - let a = &mut acc[x / k]; - for c in 0..4 { - a[c] += q[c]; - } - a[4] += 1.0; - } - } - for (x, a) in acc.iter().enumerate() { - proxy[py * pw + x] = [a[0] / a[4], a[1] / a[4], a[2] / a[4], a[3] / a[4]]; - } - } - // Coverage at the centre of each proxy block. - let sample = |value: &dyn Fn(i32, i32) -> f32| { - (0..ph) - .flat_map(|y| (0..pw).map(move |x| (area.x0 + (x * k + k / 2).min(w - 1) as i32, area.y0 + (y * k + k / 2).min(h - 1) as i32))) - .map(|(x, y)| value(x, y).clamp(0.0, 1.0)) - .collect::>() - }; - let selection = match &coverage { - Coverage::Selection => st.doc.selection.as_ref().map(|mask| sample(&|x, y| mask.sample_channel(x, y, 0))), - Coverage::Mask(mask) => Some(sample(&|x, y| mask.value(x, y))), - Coverage::None => None, - }; - let source = photocraft_engine::color_cmds::composite_profile(&st.doc); - let display = app.session.color.canvas_display(&st.doc).map_err(|e| e.to_string())?; - let lab_transform = photocraft_cms::cached(&source, photocraft_cms::Builtin::LabD50.profile(), Default::default()).map_err(|e| e.to_string())?; - let scope_transform = photocraft_cms::cached(&source, photocraft_cms::Builtin::Srgb.profile(), Default::default()).map_err(|e| e.to_string())?; - if let Some(saved) = app.session.prefs().dialogs.get("filter.cameraRaw.scope") - && saved.get("samplers").and_then(Value::as_array).is_none_or(|a| a.len() <= MAX_SAMPLERS) - && let Ok(view) = serde_json::from_value(saved.clone()) - { - app.ui.camera_raw_scope = view; - } - app.ui.camera_raw_preview = Default::default(); - app.ui.camera_raw_scope.samplers.clear(); - // Keep Camera Raw compact on open; vectorscope is an opt-in context-menu view. - app.ui.camera_raw_scope.vectorscope = false; - if selection.is_none() { - app.ui.camera_raw_scope.selected_region = false; - } - let float = surf.format().sample == photocraft_color::SampleType::F32; - // Builds the GPU pass the first time any Camera Raw dialog opens. - let gpu = crate::camera_raw_gpu::for_app(app); - let mut d = CameraRawDialog { - layer, - layer_name: name, - original: params.clone(), - params, - target, - before_histogram: RgbHistogram::from_rgba(&proxy), - processed: Vec::new(), - lab_transform, - scope_transform, - scope: Default::default(), - after_histogram: RgbHistogram::default(), - preview_revision: 0, - histogram_ms: 0.0, - proxy: std::sync::Arc::new(proxy), - selection: selection.map(std::sync::Arc::new), - pw, - ph, - full_w: w, - full_h: h, - preview_ppp: ctx.pixels_per_point(), - detail: super::camera_raw_detail_ui::DetailPreview::new( - surf, - area, - match coverage { - Coverage::Selection => { - st.doc.selection.clone().map(super::camera_raw_detail_ui::Coverage::Selection).unwrap_or(super::camera_raw_detail_ui::Coverage::None) - } - Coverage::Mask(mask) => super::camera_raw_detail_ui::Coverage::Mask(mask), - Coverage::None => super::camera_raw_detail_ui::Coverage::None, - }, - ), - display, - viewport: None, - float, - tex: None, - before_tex: None, - before_display_key: None, - dirty: true, - show_before: false, - mixer_tab: 1, - curve_state: Default::default(), - curve_rect: None, - render_ms: 0.0, - raw_open: None, - raw_curve: None, - pending: None, - preview_error: None, - gpu, - source_key: crate::camera_raw_gpu::source_key(), - develop_ms: 0.0, - develop_backend: "cpu", - undo: Vec::new(), - redo: Vec::new(), - edit_origin: None, - }; - d.render(ctx); - app.camera_raw = Some(d); - Ok(()) -} - -/// Menu / control-channel entry point. `None` when the call isn't for this dialog. -pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { - if id != "filter.cameraRaw" { - return None; - } - let Some(fields) = params.as_object() else { - return Some(Err("Camera Raw params must be an object".into())); - }; - if fields.is_empty() { - return Some( - open(app, ctx).map(|_| app.camera_raw.as_ref().map(|d| d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)).unwrap_or(Value::Null)), - ); - } - if let Some(sf) = params.get("smartFilter") { - let opened = (|| { - if fields.len() > 1 { - return Err("smartFilter opens the dialog; send ui requests separately".to_string()); - } - let layer = sf.get("layer").and_then(Value::as_u64).ok_or("smartFilter.layer must be a layer id")?; - let index = sf.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).ok_or("smartFilter.index must be a filter index")?; - open_smart_filter(app, ctx, LayerId(layer), index)?; - Ok(app.camera_raw.as_ref().map(|d| d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)).unwrap_or(Value::Null)) - })(); - return Some(opened); - } - let ui = params.get("ui")?; - let Some(fields) = ui.as_object() else { - return Some(Err("Camera Raw ui must be an object".into())); - }; - for (key, value) in fields { - match key.as_str() { - "set" | "scope" | "view" | "demosaic" => {} - "before" | "commit" | "cancel" | "saveSettings" | "loadSettings" | "undo" | "redo" | "auto" if value.is_boolean() => {} - "before" | "commit" | "cancel" | "saveSettings" | "loadSettings" | "undo" | "redo" | "auto" => { - return Some(Err(format!("Camera Raw {key} must be a boolean"))); - } - _ => return Some(Err(format!("unknown Camera Raw ui property {key}"))), - } - } - if ui.get("commit").and_then(Value::as_bool) == Some(true) && ui.get("cancel").and_then(Value::as_bool) == Some(true) { - return Some(Err("Camera Raw cannot commit and cancel together".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(run(app)); - } - } - let was_closed = app.camera_raw.is_none(); - let previous_view = app.ui.camera_raw_scope.clone(); - let previous_navigation = app.ui.camera_raw_preview; - if was_closed && let Err(e) = open(app, ctx) { - return Some(Err(e)); - } - let result = menu_update(app, ctx, ui); - if was_closed && result.as_ref().is_some_and(Result::is_err) { - app.camera_raw = None; - app.ui.camera_raw_scope = previous_view; - app.ui.camera_raw_preview = previous_navigation; - } - result -} - -fn menu_update(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &Value) -> Option> { - // Stage both filter and presentation updates. No texture, preference or dialog mutation - // occurs until every part of the request has passed validation. - let d = app.camera_raw.as_ref()?; - let mut next_params = d.params.clone(); - // Auto (the Light panel's button): the tone sliders from the image's histogram. - if ui.get("auto").and_then(Value::as_bool) == Some(true) { - photocraft_algo::camera_raw::auto_tone(&d.proxy, &mut next_params); - } - if let Some(set) = ui.get("set") { - if !set.is_object() { - return Some(Err("bad Camera Raw 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}"))); - } - 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}"))), - }; - if let Err(e) = next_params.validate_changes(&d.original) { - return Some(Err(format!("bad Camera Raw settings: {e}"))); - } - } - let scope_update = match ui.get("scope") { - Some(scope) => match super::camera_raw_scope_ui::prepare_control(&next_params, d.selection.is_some(), &app.ui.camera_raw_scope, scope) { - Ok(update) => Some(update), - Err(e) => return Some(Err(e)), - }, - None => None, - }; - let navigation = match ui.get("view") { - Some(view) => match super::camera_raw_preview_ui::prepare(app.ui.camera_raw_preview, view) { - Ok(next) => Some(next), - Err(e) => return Some(Err(e)), - }, - None => None, - }; - let demosaic = match ui.get("demosaic") { - None => None, - Some(_) if d.raw_open.is_none() => return Some(Err("demosaic applies only while a raw file opens".into())), - Some(v) => match v.as_str().and_then(photocraft_io::raw::Demosaic::from_id) { - Some(m) => Some(m), - None => return Some(Err("demosaic must be ahd, mhc or bilinear".into())), - }, - }; - let d = app.camera_raw.as_mut()?; - if let (Some(m), Some(raw)) = (demosaic, d.raw_open.as_mut()) { - raw.demosaic = m; - } - if let Some(view) = navigation { - app.ui.camera_raw_preview = view; - } - if d.params.point_curve != next_params.point_curve { - d.curve_state = Default::default(); - } - if d.params != next_params { - remember_edit(d); - d.dirty = true; - d.params = next_params; - } - if let Some(b) = ui.get("before").and_then(Value::as_bool) { - d.show_before = b; - } - if let Some(update) = scope_update { - update.apply(d, &mut app.ui.camera_raw_scope); - } - if ui.get("undo").and_then(Value::as_bool) == Some(true) { - undo_edit(d); - } - if ui.get("redo").and_then(Value::as_bool) == Some(true) { - redo_edit(d); - } - if d.dirty { - d.render(ctx); - } - // The control channel can read the status before the next frame draws. - d.clear_recovered_error(&mut app.ui); - if app.ui.camera_raw_scope.vectorscope - && let Some(d) = app.camera_raw.as_mut() - { - d.ensure_scope(app.ui.camera_raw_scope.selected_region); - } - super::camera_raw_scope_ui::persist(app, ctx); - if ui.get("cancel").and_then(Value::as_bool) == Some(true) { - cancel(app); - return Some(Ok(json!({"cancelled": true}))); - } - if ui.get("commit").and_then(Value::as_bool) == Some(true) { - return Some(commit(app)); - } - Some(Ok(app.camera_raw.as_ref().map(|d| d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)).unwrap_or(Value::Null))) -} - -/// Save Settings…: the dialog's settings as a Camera Raw `.xmp` settings file. -fn save_settings(app: &mut PhotocraftApp) -> Result { - let d = app.camera_raw.as_ref().ok_or(tl!("Camera Raw 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| { - let write = app.services.write.as_mut().ok_or("no writer configured")?; - write(&path, &bytes)?; - Ok(json!({"path": path})) - }) -} - -/// 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. -fn load_settings(app: &mut PhotocraftApp) -> Result { - app.camera_raw.as_ref().ok_or(tl!("Camera Raw 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 mut next = d.params.clone(); - let report = photocraft_io::camera_raw_xmp::load(&mut next, &bytes).map_err(|e| format!("{file}: {e}"))?; - next.validate_changes(&d.original).map_err(|e| format!("{file}: {e}"))?; - if d.params.point_curve != next.point_curve { - d.curve_state = Default::default(); - } - if d.params != next { - remember_edit(d); - d.dirty = true; - d.params = next; - } - 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)]) - } else { - let template = "Loaded Camera Raw 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})) - }) -} - -fn report_file_error(app: &mut PhotocraftApp, r: Result) { - if let Err(e) = r - && e != crate::file_dialog::CANCELLED - { - app.ui.status_error = true; - app.ui.status = e; - } -} - -const RAW_UNDO_LIMIT: usize = 40; - -fn remember_edit(d: &mut CameraRawDialog) { - if d.undo.len() == RAW_UNDO_LIMIT { - d.undo.remove(0); - } - d.undo.push(d.params.clone()); - d.redo.clear(); -} - -fn undo_edit(d: &mut CameraRawDialog) -> bool { - let Some(prev) = d.undo.pop() else { return false }; - d.redo.push(d.params.clone()); - if d.params.point_curve != prev.point_curve { - d.curve_state = Default::default(); - } - d.params = prev; - d.dirty = true; - d.edit_origin = None; - true -} - -fn redo_edit(d: &mut CameraRawDialog) -> bool { - let Some(next) = d.redo.pop() else { return false }; - d.undo.push(d.params.clone()); - if d.params.point_curve != next.point_curve { - d.curve_state = Default::default(); - } - d.params = next; - d.dirty = true; - d.edit_origin = None; - true -} - -fn history_keys(d: &mut CameraRawDialog, ctx: &egui::Context) { - let cmd_shift = egui::Modifiers::COMMAND | egui::Modifiers::SHIFT; - if ctx.input_mut(|i| i.consume_key(cmd_shift, egui::Key::Z)) { - redo_edit(d); - } else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::Z)) { - undo_edit(d); - } -} - -fn commit(app: &mut PhotocraftApp) -> Result { - let d = app.camera_raw.as_ref().ok_or(tl!("Camera Raw isn't open"))?; - let result = match d.target { - Target::NewFilter => { - let mut p = d.command_params(); - p["layer"] = json!(d.layer.0); - app.run("filter.cameraRaw", p)? - } - Target::SmartFilter(index) => { - d.params.validate_changes(&d.original)?; - // Every setting, not just the non-defaults: setParams merges into the stored ones, - // so a control reset to its default must overwrite the old value. - let mut params = serde_json::to_value(&d.params).map_err(|e| e.to_string())?; - if let Value::Object(m) = &mut params { - m.remove("pixelScale"); - } - app.run("layer.smartFilter.setParams", json!({"layer": d.layer.0, "index": index, "params": params}))? - } - Target::OpenRaw => { - let raw = d.raw_open.clone().ok_or("no raw file is being opened")?; - let (params, original) = (d.params.clone(), d.original.clone()); - commit_open_raw(app, ¶ms, &raw, Some(&original))? - } - }; - app.camera_raw = None; - Ok(result) -} - -/// The open-time demosaic choice (at the top of Detail). Photoshop's Camera Raw picks one method -/// for every file; here it is the user's. Open re-develops with it; the preview keeps the method -/// the file was opened with (the differences are finer than the preview's pixels). -fn demosaic_row(ui: &mut egui::Ui, m: &mut photocraft_io::raw::Demosaic) { - use photocraft_io::raw::Demosaic; - ui.horizontal(|ui| { - ui.label(crate::i18n::tr_ctx(crate::i18n::current(), "cameraRaw", "Demosaic")).on_hover_text(tl!( - "How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with." - )); - let options = [ - (Demosaic::Ahd, "AHD (adaptive homogeneity)", "Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest."), - (Demosaic::Mhc, "Malvar–He–Cutler", "Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail."), - (Demosaic::Bilinear, "Bilinear", "The fastest and the softest, with colour fringing on fine detail."), - ]; - widgets::dropdown_with_tooltips(ui, "camera-raw-demosaic", tl!("Demosaic"), m, &options, 180.0); - }); - ui.add_space(4.0); -} - -fn temp_stops() -> Vec { - vec![Color32::from_rgb(70, 120, 230), Color32::from_rgb(200, 200, 200), Color32::from_rgb(235, 200, 60)] -} -fn tint_stops() -> Vec { - vec![Color32::from_rgb(70, 190, 80), Color32::from_rgb(200, 200, 200), Color32::from_rgb(210, 80, 200)] -} - -/// One labelled slider; marks the dialog dirty when it moves. -fn row(ui: &mut egui::Ui, dirty: &mut bool, label: &str, v: &mut f32, range: std::ops::RangeInclusive, grad: Option<&[Color32]>) { - let _ = slider(ui, dirty, label, v, range, grad); -} - -fn slider(ui: &mut egui::Ui, dirty: &mut bool, label: &str, v: &mut f32, range: std::ops::RangeInclusive, grad: Option<&[Color32]>) -> egui::Response { - let r = widgets::slider_row(ui, crate::i18n::tr_ctx(crate::i18n::current(), "cameraRaw", label), v, range, "", grad); - if r.changed() { - *dirty = true; - } - if r.double_clicked() { - *v = 0.0; - *dirty = true; - } - r -} - -/// A Light tone slider; Alt-dragging it shows that zone's channel clipping on the preview. -fn tone_row(ui: &mut egui::Ui, dirty: &mut bool, alt: &mut Option, zone: ToneZone, v: &mut f32) { - let r = slider(ui, dirty, zone.name(), v, -zone.limit()..=zone.limit(), None); - if r.dragged() && ui.input(|i| i.modifiers.alt) { - *alt = Some(zone); - } -} - -fn section(ui: &mut egui::Ui, title: &str, open: bool, body: impl FnOnce(&mut egui::Ui)) { - egui::CollapsingHeader::new(egui::RichText::new(crate::i18n::tr_ctx(crate::i18n::current(), "cameraRaw", title)).font(FontId::proportional(13.0))) - .id_salt(("camera-raw-section", title)) - .default_open(open) - .show(ui, body); -} - -fn wheel(ui: &mut egui::Ui, dirty: &mut bool, title: &str, w: &mut Wheel) { - widgets::section_label(ui, crate::i18n::tr_ctx(crate::i18n::current(), "cameraRaw", title)); - let hs = widgets::hue_stops(); - row(ui, dirty, "Hue", &mut w.hue, 0.0..=360.0, Some(&hs)); - row(ui, dirty, "Saturation", &mut w.sat, 0.0..=100.0, None); - row(ui, dirty, "Luminance", &mut w.lum, -100.0..=100.0, None); -} - // The shared Curve editor must never produce a curve `CameraRaw::validate` rejects. const _: () = assert!(crate::point_curve::MAX_POINTS == photocraft_algo::camera_raw::MAX_CURVE_POINTS && crate::point_curve::MIN_GAP >= 1.0); -/// Small point-curve editor (master channel): click to add, drag to move, right-click to delete. -fn curve_editor(ui: &mut egui::Ui, p: &mut CameraRaw, dirty: &mut bool, state: &mut crate::state::PointCurveState) -> ERect { - let t = Tokens::get(ui.ctx()); - let side = ui.available_width().min(260.0); - let (rect, resp) = ui.allocate_exact_size(vec2(side, side), Sense::click_and_drag()); - let painter = ui.painter_at(rect); - painter.rect_filled(rect, t.radius_sm, t.field); - for i in 1..4 { - let f = i as f32 / 4.0; - painter.line_segment([pos2(rect.left() + f * side, rect.top()), pos2(rect.left() + f * side, rect.bottom())], Stroke::new(1.0, t.separator)); - painter.line_segment([pos2(rect.left(), rect.top() + f * side), pos2(rect.right(), rect.top() + f * side)], Stroke::new(1.0, t.separator)); - } - let to_screen = |x: f32, y: f32| pos2(rect.left() + x / 255.0 * side, rect.bottom() - y / 255.0 * side); - // The identity handles are presentation until a gesture actually edits them. - let mut points = if p.point_curve.is_empty() { vec![[0.0, 0.0], [255.0, 255.0]] } else { p.point_curve.clone() }; - if crate::point_curve::interact(ui, &resp, rect, &mut points, state).changed { - p.point_curve = points.clone(); - *dirty = true; - } - // Curve (point curve after the parametric one). - let lut = curve_lut(&points, 256); - let pts: Vec = lut.iter().enumerate().map(|(i, value)| to_screen(i as f32, value * 255.0)).collect(); - painter.add(egui::Shape::line(pts, Stroke::new(1.5, t.text))); - for (i, c) in points.iter().enumerate() { - let center = to_screen(c[0], c[1]); - if state.selected == Some(i) { - painter.circle_filled(center, 3.0, t.accent); - } - painter.circle_stroke(center, 4.0, Stroke::new(1.5, t.accent)); - } - rect -} - -pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { - if app.camera_raw.is_none() - && let Some(raw) = app.pending_raw_open.take() - && let Err(e) = open_raw(app, ctx, raw) - { - // The document stays open, developed with the defaults. - app.ui.status = e; - app.ui.status_error = true; - } - let Some(d) = app.camera_raw.as_ref() else { return }; - // Where the platform has no extra windows (the web build), draw over the main window. - if ctx.embed_viewports() { - draw(app, ctx, false); - return; - } - let window_title = d.window_title(); - // Camera Raw is modal, as in Photoshop: the main window is dimmed and takes no input while it - // is open (in a separate window, or drawn over it where there are no extra windows). - let main = ctx.content_rect(); - egui::Area::new(egui::Id::unique("camera-raw-modal")).order(egui::Order::Foreground).fixed_pos(main.min).show(ctx, |ui| { - let (r, _) = ui.allocate_exact_size(main.size(), Sense::click_and_drag()); - ui.painter().rect_filled(r, 0.0, Tokens::get(ui.ctx()).scrim); - }); - // A window of its own (title bar, moved and resized like any window), like Adobe Camera Raw. - let builder = egui::ViewportBuilder::default().with_title(window_title).with_inner_size([1360.0, 900.0]).with_min_inner_size([900.0, 600.0]); - let mut close = false; - ctx.show_viewport_immediate(egui::ViewportId::from_hash_of("camera-raw-window"), builder, |ui, class| { - if ui.ctx().input(|i| i.viewport().close_requested()) { - close = true; - } - draw(app, ui.ctx(), class != egui::ViewportClass::EmbeddedWindow); - }); - if close && app.camera_raw.is_some() { - cancel(app); - } -} - -impl CameraRawDialog { - /// "Camera Raw (name)" for the open-time dialog, "Camera Raw Filter (layer)" otherwise. - fn window_title(&self) -> String { - if self.target == Target::OpenRaw { - crate::i18n::fmt(tl!("Camera Raw ({name})"), &[("name", &self.layer_name)]) - } else { - crate::i18n::fmt(tl!("Camera Raw Filter ({layer})"), &[("layer", &self.layer_name)]) - } - } -} - -/// The dialog's contents over the whole of `ctx`'s window. `own_window`: the OS window already -/// shows the title, so none is painted. -fn draw(app: &mut PhotocraftApp, ctx: &egui::Context, own_window: bool) { - let t = Tokens::get(ctx); - let screen = ctx.content_rect(); - let current_display = app.session.active().and_then(|st| app.session.color.canvas_display(&st.doc).ok()); - let mut action: Option<&str> = None; - egui::Area::new(egui::Id::unique("camera-raw-dialog")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| { - let Some(d) = app.camera_raw.as_mut() else { return }; - history_keys(d, ctx); - let pointer = ctx.input(|i| i.pointer.primary_down()); - if pointer && d.edit_origin.is_none() { - d.edit_origin = Some(d.params.clone()); - } - if let Some(display) = ¤t_display - && display.key != d.display.key - { - d.display = display.clone(); - d.dirty = true; - } - d.curve_rect = None; - d.scope.vectorscope_rect = None; - if let Err(e) = d.poll_render(ctx) { - d.preview_error = Some((e.clone(), d.preview_revision)); - app.ui.status = e; - app.ui.status_error = true; - } - d.request_render(ctx); - d.clear_recovered_error(&mut app.ui); - let (full, _) = ui.allocate_exact_size(screen.size(), Sense::click()); - let painter = ui.painter().clone(); - painter.rect_filled(full, 0.0, t.chrome); - let title = ERect::from_min_size(full.min, vec2(full.width(), if own_window { 0.0 } else { 30.0 })); - if !own_window { - painter.rect_filled(title, 0.0, t.dock); - painter.line_segment([title.left_bottom(), title.right_bottom()], Stroke::new(1.0, t.separator)); - painter.text(title.center(), Align2::CENTER_CENTER, d.window_title(), FontId::proportional(13.0), t.text); - } - let ok_label = if d.target == Target::OpenRaw { tl!("Open") } else { tl!("OK") }; - let footer_h = 48.0; - let body = ERect::from_min_max(pos2(full.left(), title.bottom()), pos2(full.right(), full.bottom() - footer_h)); - let animated_zoom = app.session.prefs().general.animated_zoom; - let scope = &mut app.ui.camera_raw_scope; - // Clip both pixels and scope overlays before painting the settings dock/footer. - let preview_body = ERect::from_min_max(body.min, pos2((body.right() - PANEL_W).max(body.left() + 1.0), body.bottom())); - let view = ERect::from_min_max( - preview_body.min + vec2(16.0, 16.0), - pos2((preview_body.right() - 16.0).max(preview_body.left() + 17.0), (preview_body.bottom() - 48.0).max(preview_body.top() + 17.0)), - ); - d.viewport = Some(view); - d.preview_ppp = ctx.pixels_per_point(); - let size = vec2(d.full_w as f32, d.full_h as f32) / ctx.pixels_per_point(); - let navigation = &mut app.ui.camera_raw_preview; - let mut preview = ui.new_child(egui::UiBuilder::new().max_rect(view)); - preview.set_clip_rect(view.intersect(ui.clip_rect())); - preview.painter().rect_filled(view, 0.0, t.canvas); - let (r, response, panning, zoom_box) = - super::camera_raw_preview_ui::interact(&mut preview, navigation, view, size, &mut scope.sampler_tool, animated_zoom); - let tex = if d.show_before { d.before_tex.as_ref() } else { d.tex.as_ref() }; - if let Some(tex) = tex { - // Never tile a checker across the offscreen extent of a highly zoomed image. - widgets::checker(preview.painter(), r.intersect(view), 8.0); - preview.painter().image(tex.id(), r, ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - let raw_tone = d.raw_curve.is_some() && !raw_stage(&d.params).is_neutral(); - let detail_needed = !raw_tone && (r.width() * ctx.pixels_per_point() > d.pw as f32 || r.height() * ctx.pixels_per_point() > d.ph as f32); - d.detail.paint(&preview, r, d.preview_revision, d.show_before, &d.params, detail_needed, &d.display); - if d.detail.pending() { - ctx.request_repaint_after(std::time::Duration::from_millis(50)); - } - d.scope.preview_rect = Some(r); - super::camera_raw_scope_ui::preview(&mut preview, d, scope, r, &response, panning); - } - if let Some(region) = zoom_box { - preview.painter().rect_stroke(region, 0.0, egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); - } - let toolbar = ERect::from_min_max(pos2(preview_body.left() + 16.0, view.bottom() + 8.0), preview_body.right_bottom() - vec2(16.0, 4.0)); - let mut nav_ui = ui.new_child(egui::UiBuilder::new().max_rect(toolbar).layout(egui::Layout::left_to_right(egui::Align::Center))); - nav_ui.set_clip_rect(preview_body.intersect(ui.clip_rect())); - super::camera_raw_preview_ui::toolbar(&mut nav_ui, navigation, view, size, &mut scope.sampler_tool); - if d.detail.pending() { - nav_ui.spinner(); - } - if let Some(error) = &d.detail.error { - nav_ui.label(egui::RichText::new(tl!("Full-resolution preview unavailable")).color(t.text_faint)).on_hover_text(error); - } - // Panels. - let right = ERect::from_min_max(pos2(body.right() - PANEL_W, body.top()), body.max); - painter.rect_filled(right, 0.0, t.dock); - painter.line_segment([right.left_top(), right.left_bottom()], Stroke::new(1.0, t.separator)); - let mut props = ui.new_child(egui::UiBuilder::new().max_rect(right.shrink2(vec2(14.0, 10.0)))); - // This header is outside the settings scroll area and follows the same Before/After - // selector as the texture. Both derive from the same completed preview revision. - super::camera_raw_scope_ui::header(&mut props, d, scope); - d.scope.alt_tone = None; - let mut dirty = false; - egui::ScrollArea::vertical().id_salt("camera-raw-props").show(&mut props, |ui| { - ui.spacing_mut().item_spacing.y = 4.0; - let p = &mut d.params; - let proxy = &d.proxy; - let alt = &mut d.scope.alt_tone; - let (ts, tn) = (temp_stops(), tint_stops()); - section(ui, "Light", true, |ui| { - // Auto: Camera Raw's one-click tone from the histogram; the sliders show what it - // chose, so each can be adjusted afterwards. - if ui.button(tl!("Auto")).on_hover_text(tl!("Set the tone sliders from the image")).clicked() { - photocraft_algo::camera_raw::auto_tone(proxy, p); - dirty = true; - } - tone_row(ui, &mut dirty, alt, ToneZone::Exposure, &mut p.exposure); - row(ui, &mut dirty, "Contrast", &mut p.contrast, -100.0..=100.0, None); - tone_row(ui, &mut dirty, alt, ToneZone::Highlights, &mut p.highlights); - tone_row(ui, &mut dirty, alt, ToneZone::Shadows, &mut p.shadows); - tone_row(ui, &mut dirty, alt, ToneZone::Whites, &mut p.whites); - tone_row(ui, &mut dirty, alt, ToneZone::Blacks, &mut p.blacks); - }); - section(ui, "Color", false, |ui| { - widgets::section_label(ui, tl!("White Balance: As Shot")); - row(ui, &mut dirty, "Temperature", &mut p.temperature, -100.0..=100.0, Some(&ts)); - row(ui, &mut dirty, "Tint", &mut p.tint, -100.0..=100.0, Some(&tn)); - row(ui, &mut dirty, "Vibrance", &mut p.vibrance, -100.0..=100.0, None); - row(ui, &mut dirty, "Saturation", &mut p.saturation, -100.0..=100.0, None); - }); - section(ui, "Effects", false, |ui| { - row(ui, &mut dirty, "Texture", &mut p.texture, -100.0..=100.0, None); - row(ui, &mut dirty, "Clarity", &mut p.clarity, -100.0..=100.0, None); - row(ui, &mut dirty, "Dehaze", &mut p.dehaze, -100.0..=100.0, None); - widgets::section_label(ui, tl!("Vignetting")); - let mut style = p.vignette_style.clone(); - if widgets::dropdown( - ui, - "cr-vig-style", - tl!("Vignetting"), - &mut style, - &[ - ("highlightPriority".to_string(), tl!("Highlight Priority")), - ("colorPriority".to_string(), tl!("Color Priority")), - ("paintOverlay".to_string(), tl!("Paint Overlay")), - ], - 200.0, - ) { - p.vignette_style = style; - dirty = true; - } - row(ui, &mut dirty, "Amount", &mut p.vignette_amount, -100.0..=100.0, None); - row(ui, &mut dirty, "Midpoint", &mut p.vignette_midpoint, 0.0..=100.0, None); - row(ui, &mut dirty, "Roundness", &mut p.vignette_roundness, -100.0..=100.0, None); - row(ui, &mut dirty, "Feather", &mut p.vignette_feather, 0.0..=100.0, None); - row(ui, &mut dirty, "Highlights", &mut p.vignette_highlights, 0.0..=100.0, None); - widgets::section_label(ui, tl!("Grain")); - row(ui, &mut dirty, "Amount", &mut p.grain_amount, 0.0..=100.0, None); - row(ui, &mut dirty, "Size", &mut p.grain_size, 0.0..=100.0, None); - row(ui, &mut dirty, "Roughness", &mut p.grain_roughness, 0.0..=100.0, None); - }); - section(ui, "Curve", false, |ui| { - d.curve_rect = Some(curve_editor(ui, p, &mut dirty, &mut d.curve_state)); - row(ui, &mut dirty, "Highlights", &mut p.curve_highlights, -100.0..=100.0, None); - row(ui, &mut dirty, "Lights", &mut p.curve_lights, -100.0..=100.0, None); - row(ui, &mut dirty, "Darks", &mut p.curve_darks, -100.0..=100.0, None); - row(ui, &mut dirty, "Shadows", &mut p.curve_shadows, -100.0..=100.0, None); - }); - section(ui, "Color Mixer", false, |ui| { - ui.horizontal_wrapped(|ui| { - for (i, source) in ["Hue", "Saturation", "Luminance"].iter().enumerate() { - let name = crate::i18n::tr_ctx(crate::i18n::current(), "cameraRaw", source); - let response = widgets::pill_tab(ui, name, d.mixer_tab == i); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), d.mixer_tab == i, name)); - if response.clicked() { - d.mixer_tab = i; - } - } - }); - let arr = match d.mixer_tab { - 0 => &mut p.hsl_hue, - 1 => &mut p.hsl_sat, - _ => &mut p.hsl_lum, - }; - for (k, name) in BANDS.iter().enumerate() { - let c = photocraft_algo::camera_raw::HSL_BANDS[k]; - let base = widgets::hue_color(c); - let grad = [Color32::from_gray(128), base]; - row(ui, &mut dirty, name, &mut arr[k], -100.0..=100.0, Some(&grad)); - } - }); - section(ui, "Color Grading", false, |ui| { - wheel(ui, &mut dirty, "Shadows", &mut p.grade_shadows); - wheel(ui, &mut dirty, "Midtones", &mut p.grade_midtones); - wheel(ui, &mut dirty, "Highlights", &mut p.grade_highlights); - wheel(ui, &mut dirty, "Global", &mut p.grade_global); - row(ui, &mut dirty, "Blending", &mut p.grade_blending, 0.0..=100.0, None); - row(ui, &mut dirty, "Balance", &mut p.grade_balance, -100.0..=100.0, None); - }); - section(ui, "Detail", false, |ui| { - if let Some(raw) = d.raw_open.as_mut() { - demosaic_row(ui, &mut raw.demosaic); - } - widgets::section_label(ui, tl!("Sharpening")); - row(ui, &mut dirty, "Amount", &mut p.sharpen_amount, 0.0..=150.0, None); - row(ui, &mut dirty, "Radius", &mut p.sharpen_radius, 0.5..=3.0, None); - row(ui, &mut dirty, "Detail", &mut p.sharpen_detail, 0.0..=100.0, None); - row(ui, &mut dirty, "Masking", &mut p.sharpen_masking, 0.0..=100.0, None); - widgets::section_label(ui, tl!("Noise Reduction")); - row(ui, &mut dirty, "Luminance", &mut p.noise_luminance, 0.0..=100.0, None); - row(ui, &mut dirty, "Luminance Detail", &mut p.noise_luminance_detail, 0.0..=100.0, None); - row(ui, &mut dirty, "Color", &mut p.noise_color, 0.0..=100.0, None); - row(ui, &mut dirty, "Color Detail", &mut p.noise_color_detail, 0.0..=100.0, None); - }); - // Camera Raw's Calibration panel: a tint for the shadows and each primary's hue and - // saturation (Process Version is implied: 2012 and later). - section(ui, "Calibration", false, |ui| { - widgets::section_label(ui, tl!("Shadows")); - row(ui, &mut dirty, "Tint", &mut p.shadow_tint, -100.0..=100.0, Some(&tn)); - for (i, name) in ["Red Primary", "Green Primary", "Blue Primary"].iter().enumerate() { - widgets::section_label(ui, crate::i18n::tr_ctx(crate::i18n::current(), "cameraRaw", name)); - ui.push_id(name, |ui| { - row(ui, &mut dirty, "Hue", &mut p.calibration_hue[i], -100.0..=100.0, None); - row(ui, &mut dirty, "Saturation", &mut p.calibration_sat[i], -100.0..=100.0, None); - }); - } - }); - }); - super::camera_raw_scope_ui::floating(ctx, d, scope, right); - super::camera_raw_scope_ui::shortcuts(ctx, scope); - d.dirty |= dirty; - if d.dirty { - ctx.request_repaint(); - } - if d.render_pending() { - // The worker asks for a repaint when it is done; this catches a missed wake-up. - ctx.request_repaint_after(std::time::Duration::from_millis(50)); - } - // Footer. - let foot = ERect::from_min_max(pos2(full.left(), full.bottom() - footer_h), full.max); - painter.rect_filled(foot, 0.0, t.dock); - painter.line_segment([foot.left_top(), foot.right_top()], Stroke::new(1.0, t.separator)); - let mut fu = ui.new_child(egui::UiBuilder::new().max_rect(foot.shrink2(vec2(16.0, 9.0))).layout(egui::Layout::right_to_left(egui::Align::Center))); - if let Some(role) = widgets::dialog_buttons( - &mut fu, - &[ - widgets::DialogButton::new(widgets::ButtonRole::Default, ok_label, 90.0), - widgets::DialogButton::new(widgets::ButtonRole::Cancel, tl!("Cancel"), 90.0), - ], - ) { - action = Some(if role == widgets::ButtonRole::Default { "ok" } else { "cancel" }); - } - fu.add_space(12.0); - widgets::checkbox(&mut fu, &mut d.show_before, tl!("Before (Y)")); - fu.label(egui::RichText::new(format!("{:.0} ms", d.render_ms)).color(t.text_faint)); - fu.add_space(12.0); - if fu.button(tl!("Save Settings…")).on_hover_text(tl!("Save these settings as a Camera Raw .xmp file")).clicked() { - action = Some("save"); - } - if fu.button(tl!("Load Settings…")).on_hover_text(tl!("Load settings from a Camera Raw .xmp file")).clicked() { - action = Some("load"); - } - if !ctx.input(|i| i.pointer.primary_down()) - && let Some(origin) = d.edit_origin.take() - && origin != d.params - { - let edited = std::mem::replace(&mut d.params, origin); - remember_edit(d); - d.params = edited; - } - }); - super::camera_raw_scope_ui::persist(app, ctx); - if ctx.input(|i| i.key_pressed(egui::Key::Y)) - && let Some(d) = app.camera_raw.as_mut() - { - d.show_before = !d.show_before; - } - if ctx.input(|i| i.key_pressed(egui::Key::Escape)) { - action = Some("cancel"); - } - match action { - Some("ok") => { - if let Err(e) = commit(app) { - app.ui.status = e; - } - } - Some("cancel") => cancel(app), - Some("save") => { - let r = save_settings(app); - report_file_error(app, r); - } - Some("load") => { - let r = load_settings(app); - report_file_error(app, r); - } - _ => {} - } -} - #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/camera_raw_ui/controls.rs b/crates/ui-egui/src/camera_raw_ui/controls.rs new file mode 100644 index 0000000000..3f9e8ba19b --- /dev/null +++ b/crates/ui-egui/src/camera_raw_ui/controls.rs @@ -0,0 +1,513 @@ +use super::open::{Target, cancel, commit_open_raw, open_raw, raw_stage}; +use super::sidecar::{load_settings, report_file_error, save_settings}; +use super::*; + +const RAW_UNDO_LIMIT: usize = 40; + +pub(super) fn remember_edit(d: &mut CameraRawDialog) { + if d.undo.len() == RAW_UNDO_LIMIT { + d.undo.remove(0); + } + d.undo.push(d.params.clone()); + d.redo.clear(); +} + +pub(super) fn undo_edit(d: &mut CameraRawDialog) -> bool { + let Some(prev) = d.undo.pop() else { return false }; + d.redo.push(d.params.clone()); + if d.params.point_curve != prev.point_curve { + d.curve_state = Default::default(); + } + d.params = prev; + d.dirty = true; + d.edit_origin = None; + true +} + +pub(super) fn redo_edit(d: &mut CameraRawDialog) -> bool { + let Some(next) = d.redo.pop() else { return false }; + d.undo.push(d.params.clone()); + if d.params.point_curve != next.point_curve { + d.curve_state = Default::default(); + } + d.params = next; + d.dirty = true; + d.edit_origin = None; + true +} + +fn history_keys(d: &mut CameraRawDialog, ctx: &egui::Context) { + let cmd_shift = egui::Modifiers::COMMAND | egui::Modifiers::SHIFT; + if ctx.input_mut(|i| i.consume_key(cmd_shift, egui::Key::Z)) { + redo_edit(d); + } else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::Z)) { + undo_edit(d); + } +} + +pub(super) fn commit(app: &mut PhotocraftApp) -> Result { + let d = app.camera_raw.as_ref().ok_or(tl!("Camera Raw isn't open"))?; + let result = match d.target { + Target::NewFilter => { + let mut p = d.command_params(); + p["layer"] = json!(d.layer.0); + app.run("filter.cameraRaw", p)? + } + Target::SmartFilter(index) => { + d.params.validate_changes(&d.original)?; + // Every setting, not just the non-defaults: setParams merges into the stored ones, + // so a control reset to its default must overwrite the old value. + let mut params = serde_json::to_value(&d.params).map_err(|e| e.to_string())?; + if let Value::Object(m) = &mut params { + m.remove("pixelScale"); + } + app.run("layer.smartFilter.setParams", json!({"layer": d.layer.0, "index": index, "params": params}))? + } + Target::OpenRaw => { + let raw = d.raw_open.clone().ok_or("no raw file is being opened")?; + let (params, original) = (d.params.clone(), d.original.clone()); + commit_open_raw(app, ¶ms, &raw, Some(&original))? + } + }; + app.camera_raw = None; + Ok(result) +} + +/// The open-time demosaic choice (at the top of Detail). Photoshop's Camera Raw picks one method +/// for every file; here it is the user's. Open re-develops with it; the preview keeps the method +/// the file was opened with (the differences are finer than the preview's pixels). +fn demosaic_row(ui: &mut egui::Ui, m: &mut photocraft_io::raw::Demosaic) { + use photocraft_io::raw::Demosaic; + ui.horizontal(|ui| { + ui.label(crate::i18n::tr_ctx(crate::i18n::current(), "cameraRaw", "Demosaic")).on_hover_text(tl!( + "How the camera's colour filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with." + )); + let options = [ + (Demosaic::Ahd, "AHD (adaptive homogeneity)", "Hirakawa–Parks: the cleanest edges and the least colour fringing, the slowest."), + (Demosaic::Mhc, "Malvar–He–Cutler", "Gradient-corrected interpolation: sharp and fast, with some colour fringing on fine detail."), + (Demosaic::Bilinear, "Bilinear", "The fastest and the softest, with colour fringing on fine detail."), + ]; + widgets::dropdown_with_tooltips(ui, "camera-raw-demosaic", tl!("Demosaic"), m, &options, 180.0); + }); + ui.add_space(4.0); +} + +fn temp_stops() -> Vec { + vec![Color32::from_rgb(70, 120, 230), Color32::from_rgb(200, 200, 200), Color32::from_rgb(235, 200, 60)] +} + +fn tint_stops() -> Vec { + vec![Color32::from_rgb(70, 190, 80), Color32::from_rgb(200, 200, 200), Color32::from_rgb(210, 80, 200)] +} + +/// One labelled slider; marks the dialog dirty when it moves. +fn row(ui: &mut egui::Ui, dirty: &mut bool, label: &str, v: &mut f32, range: std::ops::RangeInclusive, grad: Option<&[Color32]>) { + let _ = slider(ui, dirty, label, v, range, grad); +} + +fn slider(ui: &mut egui::Ui, dirty: &mut bool, label: &str, v: &mut f32, range: std::ops::RangeInclusive, grad: Option<&[Color32]>) -> egui::Response { + let r = widgets::slider_row(ui, crate::i18n::tr_ctx(crate::i18n::current(), "cameraRaw", label), v, range, "", grad); + if r.changed() { + *dirty = true; + } + if r.double_clicked() { + *v = 0.0; + *dirty = true; + } + r +} + +/// A Light tone slider; Alt-dragging it shows that zone's channel clipping on the preview. +fn tone_row(ui: &mut egui::Ui, dirty: &mut bool, alt: &mut Option, zone: ToneZone, v: &mut f32) { + let r = slider(ui, dirty, zone.name(), v, -zone.limit()..=zone.limit(), None); + if r.dragged() && ui.input(|i| i.modifiers.alt) { + *alt = Some(zone); + } +} + +fn section(ui: &mut egui::Ui, title: &str, open: bool, body: impl FnOnce(&mut egui::Ui)) { + egui::CollapsingHeader::new(egui::RichText::new(crate::i18n::tr_ctx(crate::i18n::current(), "cameraRaw", title)).font(FontId::proportional(13.0))) + .id_salt(("camera-raw-section", title)) + .default_open(open) + .show(ui, body); +} + +fn wheel(ui: &mut egui::Ui, dirty: &mut bool, title: &str, w: &mut Wheel) { + widgets::section_label(ui, crate::i18n::tr_ctx(crate::i18n::current(), "cameraRaw", title)); + let hs = widgets::hue_stops(); + row(ui, dirty, "Hue", &mut w.hue, 0.0..=360.0, Some(&hs)); + row(ui, dirty, "Saturation", &mut w.sat, 0.0..=100.0, None); + row(ui, dirty, "Luminance", &mut w.lum, -100.0..=100.0, None); +} + +/// Small point-curve editor (master channel): click to add, drag to move, right-click to delete. +fn curve_editor(ui: &mut egui::Ui, p: &mut CameraRaw, dirty: &mut bool, state: &mut crate::state::PointCurveState) -> ERect { + let t = Tokens::get(ui.ctx()); + let side = ui.available_width().min(260.0); + let (rect, resp) = ui.allocate_exact_size(vec2(side, side), Sense::click_and_drag()); + let painter = ui.painter_at(rect); + painter.rect_filled(rect, t.radius_sm, t.field); + for i in 1..4 { + let f = i as f32 / 4.0; + painter.line_segment([pos2(rect.left() + f * side, rect.top()), pos2(rect.left() + f * side, rect.bottom())], Stroke::new(1.0, t.separator)); + painter.line_segment([pos2(rect.left(), rect.top() + f * side), pos2(rect.right(), rect.top() + f * side)], Stroke::new(1.0, t.separator)); + } + let to_screen = |x: f32, y: f32| pos2(rect.left() + x / 255.0 * side, rect.bottom() - y / 255.0 * side); + // The identity handles are presentation until a gesture actually edits them. + let mut points = if p.point_curve.is_empty() { vec![[0.0, 0.0], [255.0, 255.0]] } else { p.point_curve.clone() }; + if crate::point_curve::interact(ui, &resp, rect, &mut points, state).changed { + p.point_curve = points.clone(); + *dirty = true; + } + // Curve (point curve after the parametric one). + let lut = curve_lut(&points, 256); + let pts: Vec = lut.iter().enumerate().map(|(i, value)| to_screen(i as f32, value * 255.0)).collect(); + painter.add(egui::Shape::line(pts, Stroke::new(1.5, t.text))); + for (i, c) in points.iter().enumerate() { + let center = to_screen(c[0], c[1]); + if state.selected == Some(i) { + painter.circle_filled(center, 3.0, t.accent); + } + painter.circle_stroke(center, 4.0, Stroke::new(1.5, t.accent)); + } + rect +} + +pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { + if app.camera_raw.is_none() + && let Some(raw) = app.pending_raw_open.take() + && let Err(e) = open_raw(app, ctx, raw) + { + // The document stays open, developed with the defaults. + app.ui.status = e; + app.ui.status_error = true; + } + let Some(d) = app.camera_raw.as_ref() else { return }; + // Where the platform has no extra windows (the web build), draw over the main window. + if ctx.embed_viewports() { + draw(app, ctx, false); + return; + } + let window_title = d.window_title(); + // Camera Raw is modal, as in Photoshop: the main window is dimmed and takes no input while it + // is open (in a separate window, or drawn over it where there are no extra windows). + let main = ctx.content_rect(); + egui::Area::new(egui::Id::unique("camera-raw-modal")).order(egui::Order::Foreground).fixed_pos(main.min).show(ctx, |ui| { + let (r, _) = ui.allocate_exact_size(main.size(), Sense::click_and_drag()); + ui.painter().rect_filled(r, 0.0, Tokens::get(ui.ctx()).scrim); + }); + // A window of its own (title bar, moved and resized like any window), like Adobe Camera Raw. + let builder = egui::ViewportBuilder::default().with_title(window_title).with_inner_size([1360.0, 900.0]).with_min_inner_size([900.0, 600.0]); + let mut close = false; + ctx.show_viewport_immediate(egui::ViewportId::from_hash_of("camera-raw-window"), builder, |ui, class| { + if ui.ctx().input(|i| i.viewport().close_requested()) { + close = true; + } + draw(app, ui.ctx(), class != egui::ViewportClass::EmbeddedWindow); + }); + if close && app.camera_raw.is_some() { + cancel(app); + } +} + +impl CameraRawDialog { + /// "Camera Raw (name)" for the open-time dialog, "Camera Raw Filter (layer)" otherwise. + fn window_title(&self) -> String { + if self.target == Target::OpenRaw { + crate::i18n::fmt(tl!("Camera Raw ({name})"), &[("name", &self.layer_name)]) + } else { + crate::i18n::fmt(tl!("Camera Raw Filter ({layer})"), &[("layer", &self.layer_name)]) + } + } +} + +/// The dialog's contents over the whole of `ctx`'s window. `own_window`: the OS window already +/// shows the title, so none is painted. +fn draw(app: &mut PhotocraftApp, ctx: &egui::Context, own_window: bool) { + let t = Tokens::get(ctx); + let screen = ctx.content_rect(); + let current_display = app.session.active().and_then(|st| app.session.color.canvas_display(&st.doc).ok()); + let mut action: Option<&str> = None; + egui::Area::new(egui::Id::unique("camera-raw-dialog")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| { + let Some(d) = app.camera_raw.as_mut() else { return }; + history_keys(d, ctx); + let pointer = ctx.input(|i| i.pointer.primary_down()); + if pointer && d.edit_origin.is_none() { + d.edit_origin = Some(d.params.clone()); + } + if let Some(display) = ¤t_display + && display.key != d.display.key + { + d.display = display.clone(); + d.dirty = true; + } + d.curve_rect = None; + d.scope.vectorscope_rect = None; + if let Err(e) = d.poll_render(ctx) { + d.preview_error = Some((e.clone(), d.preview_revision)); + app.ui.status = e; + app.ui.status_error = true; + } + d.request_render(ctx); + d.clear_recovered_error(&mut app.ui); + let (full, _) = ui.allocate_exact_size(screen.size(), Sense::click()); + let painter = ui.painter().clone(); + painter.rect_filled(full, 0.0, t.chrome); + let title = ERect::from_min_size(full.min, vec2(full.width(), if own_window { 0.0 } else { 30.0 })); + if !own_window { + painter.rect_filled(title, 0.0, t.dock); + painter.line_segment([title.left_bottom(), title.right_bottom()], Stroke::new(1.0, t.separator)); + painter.text(title.center(), Align2::CENTER_CENTER, d.window_title(), FontId::proportional(13.0), t.text); + } + let ok_label = if d.target == Target::OpenRaw { tl!("Open") } else { tl!("OK") }; + let footer_h = 48.0; + let body = ERect::from_min_max(pos2(full.left(), title.bottom()), pos2(full.right(), full.bottom() - footer_h)); + let animated_zoom = app.session.prefs().general.animated_zoom; + let scope = &mut app.ui.camera_raw_scope; + // Clip both pixels and scope overlays before painting the settings dock/footer. + let preview_body = ERect::from_min_max(body.min, pos2((body.right() - PANEL_W).max(body.left() + 1.0), body.bottom())); + let view = ERect::from_min_max( + preview_body.min + vec2(16.0, 16.0), + pos2((preview_body.right() - 16.0).max(preview_body.left() + 17.0), (preview_body.bottom() - 48.0).max(preview_body.top() + 17.0)), + ); + d.viewport = Some(view); + d.preview_ppp = ctx.pixels_per_point(); + let size = vec2(d.full_w as f32, d.full_h as f32) / ctx.pixels_per_point(); + let navigation = &mut app.ui.camera_raw_preview; + let mut preview = ui.new_child(egui::UiBuilder::new().max_rect(view)); + preview.set_clip_rect(view.intersect(ui.clip_rect())); + preview.painter().rect_filled(view, 0.0, t.canvas); + let (r, response, panning, zoom_box) = + crate::camera_raw_preview_ui::interact(&mut preview, navigation, view, size, &mut scope.sampler_tool, animated_zoom); + let tex = if d.show_before { d.before_tex.as_ref() } else { d.tex.as_ref() }; + if let Some(tex) = tex { + // Never tile a checker across the offscreen extent of a highly zoomed image. + widgets::checker(preview.painter(), r.intersect(view), 8.0); + preview.painter().image(tex.id(), r, ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + let raw_tone = d.raw_curve.is_some() && !raw_stage(&d.params).is_neutral(); + let detail_needed = !raw_tone && (r.width() * ctx.pixels_per_point() > d.pw as f32 || r.height() * ctx.pixels_per_point() > d.ph as f32); + d.detail.paint(&preview, r, d.preview_revision, d.show_before, &d.params, detail_needed, &d.display); + if d.detail.pending() { + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + } + d.scope.preview_rect = Some(r); + crate::camera_raw_scope_ui::preview(&mut preview, d, scope, r, &response, panning); + } + if let Some(region) = zoom_box { + preview.painter().rect_stroke(region, 0.0, egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + } + let toolbar = ERect::from_min_max(pos2(preview_body.left() + 16.0, view.bottom() + 8.0), preview_body.right_bottom() - vec2(16.0, 4.0)); + let mut nav_ui = ui.new_child(egui::UiBuilder::new().max_rect(toolbar).layout(egui::Layout::left_to_right(egui::Align::Center))); + nav_ui.set_clip_rect(preview_body.intersect(ui.clip_rect())); + crate::camera_raw_preview_ui::toolbar(&mut nav_ui, navigation, view, size, &mut scope.sampler_tool); + if d.detail.pending() { + nav_ui.spinner(); + } + if let Some(error) = &d.detail.error { + nav_ui.label(egui::RichText::new(tl!("Full-resolution preview unavailable")).color(t.text_faint)).on_hover_text(error); + } + // Panels. + let right = ERect::from_min_max(pos2(body.right() - PANEL_W, body.top()), body.max); + painter.rect_filled(right, 0.0, t.dock); + painter.line_segment([right.left_top(), right.left_bottom()], Stroke::new(1.0, t.separator)); + let mut props = ui.new_child(egui::UiBuilder::new().max_rect(right.shrink2(vec2(14.0, 10.0)))); + // This header is outside the settings scroll area and follows the same Before/After + // selector as the texture. Both derive from the same completed preview revision. + crate::camera_raw_scope_ui::header(&mut props, d, scope); + d.scope.alt_tone = None; + let mut dirty = false; + egui::ScrollArea::vertical().id_salt("camera-raw-props").show(&mut props, |ui| { + ui.spacing_mut().item_spacing.y = 4.0; + let p = &mut d.params; + let proxy = &d.proxy; + let alt = &mut d.scope.alt_tone; + let (ts, tn) = (temp_stops(), tint_stops()); + section(ui, "Light", true, |ui| { + // Auto: Camera Raw's one-click tone from the histogram; the sliders show what it + // chose, so each can be adjusted afterwards. + if ui.button(tl!("Auto")).on_hover_text(tl!("Set the tone sliders from the image")).clicked() { + photocraft_algo::camera_raw::auto_tone(proxy, p); + dirty = true; + } + tone_row(ui, &mut dirty, alt, ToneZone::Exposure, &mut p.exposure); + row(ui, &mut dirty, "Contrast", &mut p.contrast, -100.0..=100.0, None); + tone_row(ui, &mut dirty, alt, ToneZone::Highlights, &mut p.highlights); + tone_row(ui, &mut dirty, alt, ToneZone::Shadows, &mut p.shadows); + tone_row(ui, &mut dirty, alt, ToneZone::Whites, &mut p.whites); + tone_row(ui, &mut dirty, alt, ToneZone::Blacks, &mut p.blacks); + }); + section(ui, "Color", false, |ui| { + widgets::section_label(ui, tl!("White Balance: As Shot")); + row(ui, &mut dirty, "Temperature", &mut p.temperature, -100.0..=100.0, Some(&ts)); + row(ui, &mut dirty, "Tint", &mut p.tint, -100.0..=100.0, Some(&tn)); + row(ui, &mut dirty, "Vibrance", &mut p.vibrance, -100.0..=100.0, None); + row(ui, &mut dirty, "Saturation", &mut p.saturation, -100.0..=100.0, None); + }); + section(ui, "Effects", false, |ui| { + row(ui, &mut dirty, "Texture", &mut p.texture, -100.0..=100.0, None); + row(ui, &mut dirty, "Clarity", &mut p.clarity, -100.0..=100.0, None); + row(ui, &mut dirty, "Dehaze", &mut p.dehaze, -100.0..=100.0, None); + widgets::section_label(ui, tl!("Vignetting")); + let mut style = p.vignette_style.clone(); + if widgets::dropdown( + ui, + "cr-vig-style", + tl!("Vignetting"), + &mut style, + &[ + ("highlightPriority".to_string(), tl!("Highlight Priority")), + ("colorPriority".to_string(), tl!("Color Priority")), + ("paintOverlay".to_string(), tl!("Paint Overlay")), + ], + 200.0, + ) { + p.vignette_style = style; + dirty = true; + } + row(ui, &mut dirty, "Amount", &mut p.vignette_amount, -100.0..=100.0, None); + row(ui, &mut dirty, "Midpoint", &mut p.vignette_midpoint, 0.0..=100.0, None); + row(ui, &mut dirty, "Roundness", &mut p.vignette_roundness, -100.0..=100.0, None); + row(ui, &mut dirty, "Feather", &mut p.vignette_feather, 0.0..=100.0, None); + row(ui, &mut dirty, "Highlights", &mut p.vignette_highlights, 0.0..=100.0, None); + widgets::section_label(ui, tl!("Grain")); + row(ui, &mut dirty, "Amount", &mut p.grain_amount, 0.0..=100.0, None); + row(ui, &mut dirty, "Size", &mut p.grain_size, 0.0..=100.0, None); + row(ui, &mut dirty, "Roughness", &mut p.grain_roughness, 0.0..=100.0, None); + }); + section(ui, "Curve", false, |ui| { + d.curve_rect = Some(curve_editor(ui, p, &mut dirty, &mut d.curve_state)); + row(ui, &mut dirty, "Highlights", &mut p.curve_highlights, -100.0..=100.0, None); + row(ui, &mut dirty, "Lights", &mut p.curve_lights, -100.0..=100.0, None); + row(ui, &mut dirty, "Darks", &mut p.curve_darks, -100.0..=100.0, None); + row(ui, &mut dirty, "Shadows", &mut p.curve_shadows, -100.0..=100.0, None); + }); + section(ui, "Color Mixer", false, |ui| { + ui.horizontal_wrapped(|ui| { + for (i, source) in ["Hue", "Saturation", "Luminance"].iter().enumerate() { + let name = crate::i18n::tr_ctx(crate::i18n::current(), "cameraRaw", source); + let response = widgets::pill_tab(ui, name, d.mixer_tab == i); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), d.mixer_tab == i, name)); + if response.clicked() { + d.mixer_tab = i; + } + } + }); + let arr = match d.mixer_tab { + 0 => &mut p.hsl_hue, + 1 => &mut p.hsl_sat, + _ => &mut p.hsl_lum, + }; + for (k, name) in BANDS.iter().enumerate() { + let c = photocraft_algo::camera_raw::HSL_BANDS[k]; + let base = widgets::hue_color(c); + let grad = [Color32::from_gray(128), base]; + row(ui, &mut dirty, name, &mut arr[k], -100.0..=100.0, Some(&grad)); + } + }); + section(ui, "Color Grading", false, |ui| { + wheel(ui, &mut dirty, "Shadows", &mut p.grade_shadows); + wheel(ui, &mut dirty, "Midtones", &mut p.grade_midtones); + wheel(ui, &mut dirty, "Highlights", &mut p.grade_highlights); + wheel(ui, &mut dirty, "Global", &mut p.grade_global); + row(ui, &mut dirty, "Blending", &mut p.grade_blending, 0.0..=100.0, None); + row(ui, &mut dirty, "Balance", &mut p.grade_balance, -100.0..=100.0, None); + }); + section(ui, "Detail", false, |ui| { + if let Some(raw) = d.raw_open.as_mut() { + demosaic_row(ui, &mut raw.demosaic); + } + widgets::section_label(ui, tl!("Sharpening")); + row(ui, &mut dirty, "Amount", &mut p.sharpen_amount, 0.0..=150.0, None); + row(ui, &mut dirty, "Radius", &mut p.sharpen_radius, 0.5..=3.0, None); + row(ui, &mut dirty, "Detail", &mut p.sharpen_detail, 0.0..=100.0, None); + row(ui, &mut dirty, "Masking", &mut p.sharpen_masking, 0.0..=100.0, None); + widgets::section_label(ui, tl!("Noise Reduction")); + row(ui, &mut dirty, "Luminance", &mut p.noise_luminance, 0.0..=100.0, None); + row(ui, &mut dirty, "Luminance Detail", &mut p.noise_luminance_detail, 0.0..=100.0, None); + row(ui, &mut dirty, "Color", &mut p.noise_color, 0.0..=100.0, None); + row(ui, &mut dirty, "Color Detail", &mut p.noise_color_detail, 0.0..=100.0, None); + }); + // Camera Raw's Calibration panel: a tint for the shadows and each primary's hue and + // saturation (Process Version is implied: 2012 and later). + section(ui, "Calibration", false, |ui| { + widgets::section_label(ui, tl!("Shadows")); + row(ui, &mut dirty, "Tint", &mut p.shadow_tint, -100.0..=100.0, Some(&tn)); + for (i, name) in ["Red Primary", "Green Primary", "Blue Primary"].iter().enumerate() { + widgets::section_label(ui, crate::i18n::tr_ctx(crate::i18n::current(), "cameraRaw", name)); + ui.push_id(name, |ui| { + row(ui, &mut dirty, "Hue", &mut p.calibration_hue[i], -100.0..=100.0, None); + row(ui, &mut dirty, "Saturation", &mut p.calibration_sat[i], -100.0..=100.0, None); + }); + } + }); + }); + crate::camera_raw_scope_ui::floating(ctx, d, scope, right); + crate::camera_raw_scope_ui::shortcuts(ctx, scope); + d.dirty |= dirty; + if d.dirty { + ctx.request_repaint(); + } + if d.render_pending() { + // The worker asks for a repaint when it is done; this catches a missed wake-up. + ctx.request_repaint_after(std::time::Duration::from_millis(50)); + } + // Footer. + let foot = ERect::from_min_max(pos2(full.left(), full.bottom() - footer_h), full.max); + painter.rect_filled(foot, 0.0, t.dock); + painter.line_segment([foot.left_top(), foot.right_top()], Stroke::new(1.0, t.separator)); + let mut fu = ui.new_child(egui::UiBuilder::new().max_rect(foot.shrink2(vec2(16.0, 9.0))).layout(egui::Layout::right_to_left(egui::Align::Center))); + if let Some(role) = widgets::dialog_buttons( + &mut fu, + &[ + widgets::DialogButton::new(widgets::ButtonRole::Default, ok_label, 90.0), + widgets::DialogButton::new(widgets::ButtonRole::Cancel, tl!("Cancel"), 90.0), + ], + ) { + action = Some(if role == widgets::ButtonRole::Default { "ok" } else { "cancel" }); + } + fu.add_space(12.0); + widgets::checkbox(&mut fu, &mut d.show_before, tl!("Before (Y)")); + fu.label(egui::RichText::new(format!("{:.0} ms", d.render_ms)).color(t.text_faint)); + fu.add_space(12.0); + if fu.button(tl!("Save Settings…")).on_hover_text(tl!("Save these settings as a Camera Raw .xmp file")).clicked() { + action = Some("save"); + } + if fu.button(tl!("Load Settings…")).on_hover_text(tl!("Load settings from a Camera Raw .xmp file")).clicked() { + action = Some("load"); + } + if !ctx.input(|i| i.pointer.primary_down()) + && let Some(origin) = d.edit_origin.take() + && origin != d.params + { + let edited = std::mem::replace(&mut d.params, origin); + remember_edit(d); + d.params = edited; + } + }); + crate::camera_raw_scope_ui::persist(app, ctx); + if ctx.input(|i| i.key_pressed(egui::Key::Y)) + && let Some(d) = app.camera_raw.as_mut() + { + d.show_before = !d.show_before; + } + if ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + action = Some("cancel"); + } + match action { + Some("ok") => { + if let Err(e) = commit(app) { + app.ui.status = e; + } + } + Some("cancel") => cancel(app), + Some("save") => { + let r = save_settings(app); + report_file_error(app, r); + } + Some("load") => { + let r = load_settings(app); + report_file_error(app, r); + } + _ => {} + } +} diff --git a/crates/ui-egui/src/camera_raw_ui/convert.rs b/crates/ui-egui/src/camera_raw_ui/convert.rs new file mode 100644 index 0000000000..873db1a826 --- /dev/null +++ b/crates/ui-egui/src/camera_raw_ui/convert.rs @@ -0,0 +1,192 @@ +use super::open::{Coverage, Target}; +use super::*; + +/// Camera Raw Defaults › Sharpen For: output sharpening, folded into the Camera Raw step `rest` +/// as the workflow's Sharpen For is. Returns what it applied. +pub(super) fn output_sharpening(d: &photocraft_engine::prefs::RawDefaults, rest: &mut CameraRaw) -> Vec<&'static str> { + match d.sharpen_for.preset() { + Some((amount, radius)) if rest.sharpen_amount == 0.0 => { + rest.sharpen_amount = amount; + rest.sharpen_radius = radius; + vec!["sharpenFor"] + } + _ => Vec::new(), + } +} + +/// The Camera Raw Defaults [`apply_raw_conversions`] applies. Resolution is not among them: the +/// open itself sets it (`file_cmds::raw_defaults`), and a re-develop keeps it. +pub(super) fn raw_conversions(d: &photocraft_engine::prefs::RawDefaults) -> Vec<&'static str> { + use photocraft_engine::prefs::{RawColorSpace, RawDepth}; + let mut out = Vec::new(); + // Raws develop into ProPhoto-compatible RGB (`photocraft_io::raw`); the other spaces are a + // conversion. + if d.color_space != RawColorSpace::ProPhoto { + out.push("colorSpace"); + } + if d.bit_depth == RawDepth::Eight { + out.push("bitDepth"); + } + if d.open_as_smart_object { + out.push("openAsSmartObject"); + } + out +} + +/// Camera Raw Defaults (Preferences) after the Camera Raw step: the colour space and bit depth +/// the developed document opens in, and Open as Smart Object. +pub(super) fn apply_raw_conversions(app: &mut PhotocraftApp, index: usize, d: &photocraft_engine::prefs::RawDefaults) -> Result<(), String> { + app.session.set_active(index); + for step in raw_conversions(d) { + let (id, params) = match step { + "colorSpace" => ("edit.convertToProfile", json!({"profile": d.color_space.profile_id(), "intent": "relative"})), + "bitDepth" => ("image.mode.bits8", json!({})), + _ => ("layer.smartObjects.convertToSmartObject", json!({})), + }; + app.session.execute(id, params).map_err(|e| e.to_string())?; + } + Ok(()) +} + +pub(super) fn open_pixels( + app: &mut PhotocraftApp, + ctx: &egui::Context, + layer: LayerId, + surf: photocraft_raster::Surface, + params: CameraRaw, + coverage: Coverage, + target: Target, +) -> Result<(), String> { + let st = app.session.active().ok_or("no document")?; + let canvas = st.doc.bounds(); + let name = st.doc.layer(layer).map(|l| l.name.clone()).unwrap_or_default(); + let mut params = params; + if params.encoding_gamma == 0.0 { + params.encoding_gamma = photocraft_engine::lens_cmds::encoding_gamma(&st.doc); + } + // Use the engine filter domain, including pixels outside the canvas: spatial Camera Raw + // stages (vignette, grain, local contrast) must agree with the committed result. + let area = canvas.union(&surf.content_bounds()); + 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()); + }; + 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()); + } + let k = w.max(h).div_ceil(PROXY_SIDE).max(1); + let (pw, ph) = (w.div_ceil(k), h.div_ceil(k)); + let mut proxy = vec![[0.0f32; 4]; pw * ph]; + let mut row = vec![[0.0f32; 4]; w]; + for py in 0..ph { + // Box-average k×k blocks. + let mut acc = vec![[0.0f32; 5]; pw]; + for dy in 0..k { + let y = area.y0 + (py * k + dy).min(h - 1) as i32; + surf.read_rgba_into(Rect::new(area.x0, y, area.x1, y + 1), &mut row); + for (x, q) in row.iter().enumerate() { + let a = &mut acc[x / k]; + for c in 0..4 { + a[c] += q[c]; + } + a[4] += 1.0; + } + } + for (x, a) in acc.iter().enumerate() { + proxy[py * pw + x] = [a[0] / a[4], a[1] / a[4], a[2] / a[4], a[3] / a[4]]; + } + } + // Coverage at the centre of each proxy block. + let sample = |value: &dyn Fn(i32, i32) -> f32| { + (0..ph) + .flat_map(|y| (0..pw).map(move |x| (area.x0 + (x * k + k / 2).min(w - 1) as i32, area.y0 + (y * k + k / 2).min(h - 1) as i32))) + .map(|(x, y)| value(x, y).clamp(0.0, 1.0)) + .collect::>() + }; + let selection = match &coverage { + Coverage::Selection => st.doc.selection.as_ref().map(|mask| sample(&|x, y| mask.sample_channel(x, y, 0))), + Coverage::Mask(mask) => Some(sample(&|x, y| mask.value(x, y))), + Coverage::None => None, + }; + let source = photocraft_engine::color_cmds::composite_profile(&st.doc); + let display = app.session.color.canvas_display(&st.doc).map_err(|e| e.to_string())?; + let lab_transform = photocraft_cms::cached(&source, photocraft_cms::Builtin::LabD50.profile(), Default::default()).map_err(|e| e.to_string())?; + let scope_transform = photocraft_cms::cached(&source, photocraft_cms::Builtin::Srgb.profile(), Default::default()).map_err(|e| e.to_string())?; + if let Some(saved) = app.session.prefs().dialogs.get("filter.cameraRaw.scope") + && saved.get("samplers").and_then(Value::as_array).is_none_or(|a| a.len() <= MAX_SAMPLERS) + && let Ok(view) = serde_json::from_value(saved.clone()) + { + app.ui.camera_raw_scope = view; + } + app.ui.camera_raw_preview = Default::default(); + app.ui.camera_raw_scope.samplers.clear(); + // Keep Camera Raw compact on open; vectorscope is an opt-in context-menu view. + app.ui.camera_raw_scope.vectorscope = false; + if selection.is_none() { + app.ui.camera_raw_scope.selected_region = false; + } + let float = surf.format().sample == photocraft_color::SampleType::F32; + // Builds the GPU pass the first time any Camera Raw dialog opens. + let gpu = crate::camera_raw_gpu::for_app(app); + let mut d = CameraRawDialog { + layer, + layer_name: name, + original: params.clone(), + params, + target, + before_histogram: RgbHistogram::from_rgba(&proxy), + processed: Vec::new(), + lab_transform, + scope_transform, + scope: Default::default(), + after_histogram: RgbHistogram::default(), + preview_revision: 0, + histogram_ms: 0.0, + proxy: std::sync::Arc::new(proxy), + selection: selection.map(std::sync::Arc::new), + pw, + ph, + full_w: w, + full_h: h, + preview_ppp: ctx.pixels_per_point(), + detail: crate::camera_raw_detail_ui::DetailPreview::new( + surf, + area, + match coverage { + Coverage::Selection => { + st.doc.selection.clone().map(crate::camera_raw_detail_ui::Coverage::Selection).unwrap_or(crate::camera_raw_detail_ui::Coverage::None) + } + Coverage::Mask(mask) => crate::camera_raw_detail_ui::Coverage::Mask(mask), + Coverage::None => crate::camera_raw_detail_ui::Coverage::None, + }, + ), + display, + viewport: None, + float, + tex: None, + before_tex: None, + before_display_key: None, + dirty: true, + show_before: false, + mixer_tab: 1, + curve_state: Default::default(), + curve_rect: None, + render_ms: 0.0, + raw_open: None, + raw_curve: None, + pending: None, + preview_error: None, + gpu, + source_key: crate::camera_raw_gpu::source_key(), + develop_ms: 0.0, + develop_backend: "cpu", + undo: Vec::new(), + redo: Vec::new(), + edit_origin: None, + }; + d.render(ctx); + app.camera_raw = Some(d); + Ok(()) +} diff --git a/crates/ui-egui/src/camera_raw_ui/menu.rs b/crates/ui-egui/src/camera_raw_ui/menu.rs new file mode 100644 index 0000000000..91b938e14c --- /dev/null +++ b/crates/ui-egui/src/camera_raw_ui/menu.rs @@ -0,0 +1,169 @@ +use super::controls::{commit, redo_edit, remember_edit, undo_edit}; +use super::open::{cancel, open, open_smart_filter}; +use super::sidecar::{load_settings, save_settings}; +use super::*; + +/// Menu / control-channel entry point. `None` when the call isn't for this dialog. +pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { + if id != "filter.cameraRaw" { + return None; + } + let Some(fields) = params.as_object() else { + return Some(Err("Camera Raw params must be an object".into())); + }; + if fields.is_empty() { + return Some( + open(app, ctx).map(|_| app.camera_raw.as_ref().map(|d| d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)).unwrap_or(Value::Null)), + ); + } + if let Some(sf) = params.get("smartFilter") { + let opened = (|| { + if fields.len() > 1 { + return Err("smartFilter opens the dialog; send ui requests separately".to_string()); + } + let layer = sf.get("layer").and_then(Value::as_u64).ok_or("smartFilter.layer must be a layer id")?; + let index = sf.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).ok_or("smartFilter.index must be a filter index")?; + open_smart_filter(app, ctx, LayerId(layer), index)?; + Ok(app.camera_raw.as_ref().map(|d| d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)).unwrap_or(Value::Null)) + })(); + return Some(opened); + } + let ui = params.get("ui")?; + let Some(fields) = ui.as_object() else { + return Some(Err("Camera Raw ui must be an object".into())); + }; + for (key, value) in fields { + match key.as_str() { + "set" | "scope" | "view" | "demosaic" => {} + "before" | "commit" | "cancel" | "saveSettings" | "loadSettings" | "undo" | "redo" | "auto" if value.is_boolean() => {} + "before" | "commit" | "cancel" | "saveSettings" | "loadSettings" | "undo" | "redo" | "auto" => { + return Some(Err(format!("Camera Raw {key} must be a boolean"))); + } + _ => return Some(Err(format!("unknown Camera Raw ui property {key}"))), + } + } + if ui.get("commit").and_then(Value::as_bool) == Some(true) && ui.get("cancel").and_then(Value::as_bool) == Some(true) { + return Some(Err("Camera Raw cannot commit and cancel together".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(run(app)); + } + } + let was_closed = app.camera_raw.is_none(); + let previous_view = app.ui.camera_raw_scope.clone(); + let previous_navigation = app.ui.camera_raw_preview; + if was_closed && let Err(e) = open(app, ctx) { + return Some(Err(e)); + } + let result = menu_update(app, ctx, ui); + if was_closed && result.as_ref().is_some_and(Result::is_err) { + app.camera_raw = None; + app.ui.camera_raw_scope = previous_view; + app.ui.camera_raw_preview = previous_navigation; + } + result +} + +fn menu_update(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &Value) -> Option> { + // Stage both filter and presentation updates. No texture, preference or dialog mutation + // occurs until every part of the request has passed validation. + let d = app.camera_raw.as_ref()?; + let mut next_params = d.params.clone(); + // Auto (the Light panel's button): the tone sliders from the image's histogram. + if ui.get("auto").and_then(Value::as_bool) == Some(true) { + photocraft_algo::camera_raw::auto_tone(&d.proxy, &mut next_params); + } + if let Some(set) = ui.get("set") { + if !set.is_object() { + return Some(Err("bad Camera Raw 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}"))); + } + 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}"))), + }; + if let Err(e) = next_params.validate_changes(&d.original) { + return Some(Err(format!("bad Camera Raw settings: {e}"))); + } + } + let scope_update = match ui.get("scope") { + Some(scope) => match crate::camera_raw_scope_ui::prepare_control(&next_params, d.selection.is_some(), &app.ui.camera_raw_scope, scope) { + Ok(update) => Some(update), + Err(e) => return Some(Err(e)), + }, + None => None, + }; + let navigation = match ui.get("view") { + Some(view) => match crate::camera_raw_preview_ui::prepare(app.ui.camera_raw_preview, view) { + Ok(next) => Some(next), + Err(e) => return Some(Err(e)), + }, + None => None, + }; + let demosaic = match ui.get("demosaic") { + None => None, + Some(_) if d.raw_open.is_none() => return Some(Err("demosaic applies only while a raw file opens".into())), + Some(v) => match v.as_str().and_then(photocraft_io::raw::Demosaic::from_id) { + Some(m) => Some(m), + None => return Some(Err("demosaic must be ahd, mhc or bilinear".into())), + }, + }; + let d = app.camera_raw.as_mut()?; + if let (Some(m), Some(raw)) = (demosaic, d.raw_open.as_mut()) { + raw.demosaic = m; + } + if let Some(view) = navigation { + app.ui.camera_raw_preview = view; + } + if d.params.point_curve != next_params.point_curve { + d.curve_state = Default::default(); + } + if d.params != next_params { + remember_edit(d); + d.dirty = true; + d.params = next_params; + } + if let Some(b) = ui.get("before").and_then(Value::as_bool) { + d.show_before = b; + } + if let Some(update) = scope_update { + update.apply(d, &mut app.ui.camera_raw_scope); + } + if ui.get("undo").and_then(Value::as_bool) == Some(true) { + undo_edit(d); + } + if ui.get("redo").and_then(Value::as_bool) == Some(true) { + redo_edit(d); + } + if d.dirty { + d.render(ctx); + } + // The control channel can read the status before the next frame draws. + d.clear_recovered_error(&mut app.ui); + if app.ui.camera_raw_scope.vectorscope + && let Some(d) = app.camera_raw.as_mut() + { + d.ensure_scope(app.ui.camera_raw_scope.selected_region); + } + crate::camera_raw_scope_ui::persist(app, ctx); + if ui.get("cancel").and_then(Value::as_bool) == Some(true) { + cancel(app); + return Some(Ok(json!({"cancelled": true}))); + } + if ui.get("commit").and_then(Value::as_bool) == Some(true) { + return Some(commit(app)); + } + Some(Ok(app.camera_raw.as_ref().map(|d| d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)).unwrap_or(Value::Null))) +} diff --git a/crates/ui-egui/src/camera_raw_ui/open.rs b/crates/ui-egui/src/camera_raw_ui/open.rs new file mode 100644 index 0000000000..429e245eb0 --- /dev/null +++ b/crates/ui-egui/src/camera_raw_ui/open.rs @@ -0,0 +1,496 @@ +use super::convert::{apply_raw_conversions, open_pixels, output_sharpening, raw_conversions}; +use super::sidecar::{read_sidecar, write_sidecar}; +use super::*; + +/// Opens the dialog on the active layer. +/// Where OK writes: a new filter on the layer, or an existing smart filter (by index). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Target { + NewFilter, + SmartFilter(usize), + /// The open-time dialog of a raw file just opened (File › Open): OK is **Open**, Cancel + /// closes the document again. See [`RawOpen`]. + OpenRaw, +} + +/// 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. +#[derive(Clone, Debug)] +pub struct RawOpen { + pub document: photocraft_doc::DocId, + pub name: String, + pub path: Option, + /// The file, when it was opened from bytes (no path to read it again from). + pub bytes: Option>>, + /// The demosaic method the open developed it with. + 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, +} + +/// Should an interactive open of `name` show the open-time Camera Raw dialog? `warnings` are +/// the import's: only a raw developed from its sensor data qualifies (not a preview fallback). +pub fn wants_open_dialog(app: &PhotocraftApp, warnings: &[String]) -> bool { + app.session.prefs().raw_defaults.open_in_camera_raw && warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)) +} + +/// `warnings` without the "developed with default settings" note: the open-time dialog shows +/// how the raw is developed. +pub fn without_develop_note(warnings: &[String]) -> Vec { + warnings.iter().filter(|w| !w.contains(photocraft_io::raw::DEVELOPED_NOTE)).cloned().collect() +} + +/// Queues the open-time dialog for the document whose import completed, independent of the +/// active tab. A delayed completion for a closed document must not review another photograph. +/// `warnings` are the import's: its note says which demosaic method the open developed with. +pub fn queue_open_dialog( + app: &mut PhotocraftApp, + document: photocraft_doc::DocId, + name: &str, + path: Option<&str>, + bytes: Option<&[u8]>, + warnings: &[String], +) -> Result<(), String> { + if document_index(app, document).is_none() { + return Err("the imported raw document is missing".into()); + } + // The method the open actually used (`jobs::import_options` at the job's start), from its + // note: the preference may have changed while a background open ran. + let method = photocraft_io::raw::developed_demosaic(warnings).unwrap_or_else(|| app.session.prefs().raw_defaults.demosaic.method()); + app.pending_raw_open = Some(RawOpen { + document, + name: name.to_string(), + path: path.map(str::to_string), + bytes: bytes.map(|b| std::sync::Arc::new(b.to_vec())), + developed_with: method, + demosaic: method, + }); + Ok(()) +} + +/// Opens the queued open-time dialog on its document's (only) layer. +pub(super) fn open_raw(app: &mut PhotocraftApp, ctx: &egui::Context, raw: RawOpen) -> 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)?; + // The file's sidecar (`IMG_0001.xmp` beside it) fills the dialog, as Camera Raw's does; the + // status bar names what it could not apply. + let mut params = CameraRaw::default(); + let mut from_sidecar = false; + if let Some((loaded, report, file)) = raw.path.as_deref().and_then(read_sidecar) { + params = loaded; + from_sidecar = true; + app.ui.status = if report.ignored.is_empty() { + crate::i18n::fmt(tl!("Settings from {name}"), &[("name", &file)]) + } else { + crate::i18n::fmt( + tl!("Settings from {name}; {count} not supported: {names}"), + &[("name", &file), ("count", &report.ignored.len().to_string()), ("names", &report.ignored.join(", "))], + ) + }; + app.ui.status_error = false; + } + open_pixels(app, ctx, layer, surf, params, Coverage::None, Target::OpenRaw)?; + // Camera Raw Defaults › Apply auto tone: a file without its own settings opens with Auto. + if !from_sidecar + && app.session.prefs().raw_defaults.apply_auto_tone + && let Some(d) = app.camera_raw.as_mut() + { + photocraft_algo::camera_raw::auto_tone(&d.proxy, &mut d.params); + d.dirty = true; + } + let curve = match (&raw.bytes, &raw.path) { + (Some(b), _) => Some(photocraft_io::raw::tone_curve(b)), + #[cfg(not(target_arch = "wasm32"))] + (None, Some(p)) => std::fs::read(p).ok().map(|b| photocraft_io::raw::tone_curve(&b)), + _ => None, + }; + if let Some(d) = app.camera_raw.as_mut() { + d.layer_name = raw.name.clone(); + // The full-size preview retones the whole frame with it, as Open will. + let curve = curve.map(std::sync::Arc::new); + d.detail.raw_curve = curve.clone(); + d.raw_curve = curve; + d.raw_open = Some(raw); + } + Ok(()) +} + +pub(super) fn document_index(app: &PhotocraftApp, id: photocraft_doc::DocId) -> Option { + app.session.documents().iter().position(|st| st.doc.id == id) +} + +/// The non-default settings of `p` as engine params. +pub(super) fn non_defaults(p: &CameraRaw) -> Value { + let full = serde_json::to_value(p).unwrap_or(json!({})); + let def = serde_json::to_value(CameraRaw::default()).unwrap_or(json!({})); + let mut out = serde_json::Map::new(); + if let (Value::Object(f), Value::Object(d)) = (full, def) { + for (k, v) in f { + if k != "pixelScale" && d.get(&k) != Some(&v) { + out.insert(k, v); + } + } + } + Value::Object(out) +} + +/// The job id of an open-time re-develop (not an engine command: the shell starts it). +pub const REDEVELOP_JOB: &str = "cameraRaw.redevelop"; + +/// An open-time re-develop running in the background: what to finish with when it lands. +#[derive(Clone, Debug)] +pub struct Redevelop { + pub job: photocraft_engine::jobs::JobId, + params: CameraRaw, + raw: RawOpen, + /// The job is the final Camera Raw step (`filter.cameraRaw`), not the re-develop: when it + /// lands the Camera Raw Defaults' conversions follow and the document is marked unmodified. + filter_step: bool, + /// The Camera Raw Defaults the open started with, for the conversions after the filter step. + defaults: photocraft_engine::prefs::RawDefaults, +} + +/// The sliders a raw open applies while developing, before the tone curve (as Camera Raw does). +pub(super) fn raw_stage(p: &CameraRaw) -> photocraft_io::raw::Tone { + photocraft_io::raw::Tone { shadows: p.shadows, highlights: p.highlights, clarity: p.clarity, texture: p.texture, dehaze: p.dehaze } +} + +/// Open: re-develop for raw-stage settings, apply the rest, keep the document unmodified. +/// +/// Re-developing reads and decodes the whole raw again, so in the desktop app (background jobs +/// on) it runs as a job like the open itself: the reply is `{"job", "pending": true}`, the +/// document is locked meanwhile, and [`on_redevelop_event`] finishes when it lands. Elsewhere +/// (tests, the web) it runs inline. +pub(super) fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen, loaded: Option<&CameraRaw>) -> Result { + let index = document_index(app, raw.document).ok_or("the raw document was closed")?; + write_sidecar(app, raw, params, loaded); + let tuning = photocraft_io::raw::RawTuning { + temperature: params.temperature, + tint: params.tint, + exposure: params.exposure, + demosaic: raw.demosaic, + shadows: params.shadows, + highlights: params.highlights, + clarity: params.clarity, + texture: params.texture, + dehaze: params.dehaze, + }; + // 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() }; + // Without the file the raw-stage settings stay RGB adjustments, like the filter's. + let source = match (&raw.bytes, &raw.path) { + (Some(b), _) => Some(photocraft_engine::jobs::OpenSource::Bytes(b.clone())), + #[cfg(not(target_arch = "wasm32"))] + (None, Some(p)) => Some(photocraft_engine::jobs::OpenSource::Path(p.clone())), + _ => None, + }; + let Some(source) = source.filter(|_| tuning != as_opened) else { + let defaults = app.session.prefs().raw_defaults.clone(); + return finish_open_raw(app, index, params.clone(), None, raw, &defaults); + }; + app.session.set_active(index); + let (name, doc_id) = (raw.name.clone(), raw.document); + let work = move |ctx: &photocraft_engine::jobs::JobCtx| -> photocraft_engine::Result<(photocraft_io::ImportResult, bool)> { + ctx.progress(0.0, "Reading"); + let bytes = match source { + photocraft_engine::jobs::OpenSource::Bytes(b) => b, + #[cfg(not(target_arch = "wasm32"))] + photocraft_engine::jobs::OpenSource::Path(p) => { + std::sync::Arc::new(std::fs::read(&p).map_err(|e| photocraft_engine::EngineError::Other(format!("{p}: {e}")))?) + } + #[cfg(target_arch = "wasm32")] + photocraft_engine::jobs::OpenSource::Path(p) => return Err(photocraft_engine::EngineError::Other(format!("{p}: cannot read files here"))), + }; + ctx.check()?; + ctx.progress(0.05, "Developing"); + photocraft_io::raw::import_raw_tuned(&name, &bytes, &tuning).map_err(|e| photocraft_engine::EngineError::Other(e.to_string())) + }; + let apply = move |s: &mut photocraft_engine::Session, (r, wb): (photocraft_io::ImportResult, bool)| replace_raw_document(s, doc_id, r, wb); + let label = crate::i18n::fmt(tl!("Developing {name}"), &[("name", &raw.name)]); + let started = if app.background_jobs { + app.session.start_job(REDEVELOP_JOB, json!({"name": raw.name}), &label, true, work, apply).map_err(|e| e.to_string())? + } else { + let v = work(&photocraft_engine::jobs::JobCtx::new()).and_then(|t| apply(&mut app.session, t)).map_err(|e| e.to_string())?; + photocraft_engine::jobs::Started::Done(v) + }; + match started { + photocraft_engine::jobs::Started::Done(v) => { + let defaults = app.session.prefs().raw_defaults.clone(); + finish_redevelop(app, params, raw, &v, &defaults) + } + photocraft_engine::jobs::Started::Job(job) => { + let defaults = app.session.prefs().raw_defaults.clone(); + app.raw_redevelop.push(Redevelop { job, params: params.clone(), raw: raw.clone(), filter_step: false, defaults }); + app.ui.status = label; + app.ui.status_error = false; + Ok(json!({"job": job.0, "pending": true})) + } + } +} + +/// Swap the default-developed document `doc_id` for the re-developed one, at the same tab +/// position and with the same path. Returns `{document, docId, previous, warnings, wb}`: +/// `document` is the tab index at apply time, `docId` is the replacement's stable identity. +pub(super) fn replace_raw_document( + s: &mut photocraft_engine::Session, + doc_id: photocraft_doc::DocId, + mut r: photocraft_io::ImportResult, + wb: bool, +) -> photocraft_engine::Result { + let index = + s.documents().iter().position(|st| st.doc.id == doc_id).ok_or_else(|| photocraft_engine::EngineError::Other("the raw document was closed".into()))?; + let path = s.documents().get(index).and_then(|st| st.path.clone()); + // The resolution it opened with (Preferences › Raw Defaults), which re-developing keeps. + if let Some(st) = s.documents().get(index) { + r.document.resolution_dpi = st.doc.resolution_dpi; + } + s.close(index); + let (opened, _) = s.open_document(r.document, path); + let replacement = s.documents().get(opened).ok_or(photocraft_engine::EngineError::NoDocument)?.doc.id; + let index = match s.execute("document.move", json!({"document": opened, "to": index})) { + Ok(moved) => moved.get("document").and_then(Value::as_u64).map_or(opened, |i| i as usize), + Err(_) => opened, + }; + s.set_active(index); + Ok(json!({"document": index, "docId": replacement.0, "previous": doc_id.0, "warnings": r.warnings, "wb": wb})) +} + +/// After the re-develop: keep the old document's view (zoom, scroll) on the new one, report +/// the import's notes, then apply the remaining settings. +pub(super) fn finish_redevelop( + app: &mut PhotocraftApp, + params: &CameraRaw, + raw: &RawOpen, + v: &Value, + defaults: &photocraft_engine::prefs::RawDefaults, +) -> Result { + // A preceding completion (for example Save and Close) may have shifted the tab indices. + // Validate identity before remapping views, filtering or marking any document unmodified. + let replacement = v.get("docId").and_then(Value::as_u64).map(photocraft_doc::DocId).ok_or("the re-develop returned no document identity")?; + let index = document_index(app, replacement).ok_or("the re-developed document was closed")?; + for id in app.view_docs.iter_mut().filter(|id| **id == raw.document) { + *id = replacement; + } + let warnings: Vec = + v.get("warnings").and_then(Value::as_array).map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default(); + crate::notices::io_warnings(app, &format!("Opened {}", raw.name), &without_develop_note(&warnings)); + let mut rest = params.clone(); + rest.exposure = 0.0; + rest.shadows = 0.0; + rest.highlights = 0.0; + rest.clarity = 0.0; + rest.texture = 0.0; + rest.dehaze = 0.0; + if v.get("wb").and_then(Value::as_bool) == Some(true) { + rest.temperature = 0.0; + rest.tint = 0.0; + } + finish_open_raw(app, index, rest, Some(true), raw, defaults) +} + +/// The other settings as one Camera Raw step on document `index`, then the Camera Raw Defaults' +/// conversions, then the document is marked unmodified (developing is part of opening). The +/// step runs like any filter (in the background in the desktop app); the conversions follow and +/// the document is marked unmodified when it lands. The step works on the developed ProPhoto +/// pixels the dialog previewed, and the conversion to the workflow space comes last, as in +/// Camera Raw. +fn finish_open_raw( + app: &mut PhotocraftApp, + index: usize, + mut rest: CameraRaw, + redeveloped: Option, + raw: &RawOpen, + d: &photocraft_engine::prefs::RawDefaults, +) -> Result { + app.session.set_active(index); + app.sync_views(); + let mut result = json!({"document": index, "redeveloped": redeveloped.unwrap_or(false)}); + let mut applied = output_sharpening(d, &mut rest); + applied.extend(raw_conversions(d)); + if !applied.is_empty() { + result["defaults"] = json!(applied); + } + if !rest.is_identity() { + let layer = app.session.active().and_then(|st| st.active_layer).ok_or("no layer to develop")?; + let mut p = non_defaults(&rest); + p["layer"] = json!(layer.0); + let r = app.run("filter.cameraRaw", p)?; + if r.get("pending").and_then(Value::as_bool) == Some(true) + && let Some(job) = r.get("job").and_then(Value::as_u64) + { + let job = photocraft_engine::jobs::JobId(job); + app.raw_redevelop.push(Redevelop { job, params: rest.clone(), raw: raw.clone(), filter_step: true, defaults: d.clone() }); + result["filter"] = r; + mark_unmodified(app, index); + return Ok(result); + } + result["filter"] = r; + } + // The Camera Raw step has landed: a failed conversion is reported, and the open still + // completes (a second Open would apply the step twice). + if let Err(e) = apply_raw_conversions(app, index, d) { + crate::notices::error(app, format!("{}: {e}", raw.name)); + } + mark_unmodified(app, index); + Ok(result) +} + +/// A raw that opened without the dialog (Camera Raw Defaults › Open in Camera Raw off): its +/// sidecar's settings develop it as the dialog's Open would, and the Camera Raw Defaults apply. +/// `warnings` are the import's; only a developed raw qualifies. +pub fn opened_without_dialog(app: &mut PhotocraftApp, index: usize, name: &str, path: Option<&str>, warnings: &[String]) { + if !warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)) { + return; + } + 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 params = CameraRaw::default(); + let sidecar = path.and_then(read_sidecar).map(|(loaded, _, _)| loaded); + if let Some(loaded) = &sidecar { + params = loaded.clone(); + } else if app.session.prefs().raw_defaults.apply_auto_tone + && let Some(px) = app.session.active().and_then(|st| st.doc.layer(st.active_layer?)).and_then(|l| l.surface()).map(|s| sample_pixels(s, 512)) + { + photocraft_algo::camera_raw::auto_tone(&px, &mut params); + } + let r = if params.is_identity() { + let defaults = app.session.prefs().raw_defaults.clone(); + finish_open_raw(app, index, params, None, &raw, &defaults) + } else { + commit_open_raw(app, ¶ms, &raw, sidecar.as_ref()) + }; + if let Err(e) = r { + app.ui.status = e; + app.ui.status_error = true; + } +} + +/// Every k-th pixel of a surface's content, k chosen so the longer side has about `max_side` +/// samples: enough for a histogram (Auto tone) without reading a whole raw. +fn sample_pixels(surf: &photocraft_raster::Surface, max_side: usize) -> Vec<[f32; 4]> { + let area = surf.content_bounds(); + let (w, h) = (area.x1.saturating_sub(area.x0).max(0) as usize, area.y1.saturating_sub(area.y0).max(0) as usize); + if w == 0 || h == 0 { + return Vec::new(); + } + let k = w.max(h).div_ceil(max_side.max(1)).max(1); + let mut out = Vec::with_capacity(w.div_ceil(k) * h.div_ceil(k)); + let mut row = vec![[0.0f32; 4]; w]; + for y in (0..h).step_by(k) { + let yy = area.y0.saturating_add(y as i32); + surf.read_rgba_into(Rect::new(area.x0, yy, area.x1, yy.saturating_add(1)), &mut row); + out.extend(row.iter().step_by(k).copied()); + } + out +} + +fn mark_unmodified(app: &mut PhotocraftApp, index: usize) { + let active = app.session.active_index(); + app.session.set_active(index); + if let Some(st) = app.session.active_mut() { + st.saved_revision = st.revision; + } + if let Some(i) = active { + app.session.set_active(i); + } + app.sync_views(); +} + +/// A finished background re-develop ([`REDEVELOP_JOB`]) or open-time Camera Raw step. `true` +/// when the event was one of those (handled here). +pub fn on_redevelop_event(app: &mut PhotocraftApp, e: &photocraft_engine::jobs::JobEvent) -> bool { + let Some(at) = app.raw_redevelop.iter().position(|r| r.job == e.id) else { return false }; + let pending = app.raw_redevelop.remove(at); + if pending.filter_step { + // The Camera Raw Defaults' conversions follow the Camera Raw step, whatever its outcome: + // the document still opens in the workflow's colour space and depth. + if let Some(index) = e.document.and_then(|id| document_index(app, id)) { + let active = app.session.active_index(); + if let Err(err) = apply_raw_conversions(app, index, &pending.defaults) { + crate::notices::error(app, format!("{}: {err}", pending.raw.name)); + } + if let Some(i) = active { + app.session.set_active(i); + } + if matches!(e.outcome, photocraft_engine::jobs::JobOutcome::Done(_)) { + mark_unmodified(app, index); + } + app.sync_views(); + } + // The usual filter reporting still applies. + return false; + } + match &e.outcome { + photocraft_engine::jobs::JobOutcome::Done(v) => match finish_redevelop(app, &pending.params, &pending.raw, v, &pending.defaults) { + Ok(_) => { + app.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", &pending.raw.name)]); + app.ui.status_error = false; + } + Err(err) => crate::notices::error(app, format!("{}: {err}", e.label)), + }, + photocraft_engine::jobs::JobOutcome::Failed(err) => { + // The document stays open, developed with the defaults. + app.sync_views(); + crate::notices::error(app, format!("{}: {err}", e.label)); + } + photocraft_engine::jobs::JobOutcome::Cancelled => { + app.ui.status = crate::i18n::fmt(tl!("Cancelled {label}"), &[("label", &e.label)]); + app.ui.status_error = false; + } + } + true +} + +/// Cancel: closes the dialog; for the open-time dialog also the document it was opening. +pub(super) fn cancel(app: &mut PhotocraftApp) { + let Some(d) = app.camera_raw.take() else { return }; + if let (Target::OpenRaw, Some(raw)) = (d.target, &d.raw_open) + && let Some(index) = document_index(app, raw.document) + { + app.session.close(index); + app.sync_views(); + app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &raw.name)]); + app.ui.status_error = false; + } +} + +/// What limits the preview: the document selection (a new filter applies through it, as the +/// engine does), a smart object's filter mask, or nothing. +pub(super) enum Coverage { + Selection, + Mask(photocraft_doc::LayerMask), + None, +} + +pub fn open(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { + 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)?; + open_pixels(app, ctx, layer, surf, CameraRaw::default(), Coverage::Selection, Target::NewFilter) +} + +/// Opens Camera Raw on smart filter `index` of smart layer `layer`, with its stored settings and +/// the pixels below it; OK updates that filter (`layer.smartFilter.setParams`), as double-clicking +/// a Camera Raw smart filter does in Photoshop. +pub fn open_smart_filter(app: &mut PhotocraftApp, ctx: &egui::Context, layer: LayerId, index: usize) -> Result<(), String> { + use photocraft_engine::lens_cmds::{RAW, raw_params}; + let st = app.session.active().ok_or("no document")?; + let Some(photocraft_doc::LayerContent::Smart(sm)) = st.doc.layer(layer).map(|l| &l.content) else { + return Err("the layer is not a smart object".into()); + }; + 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()); + } + 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) + .map_err(|e| e.to_string())? + .ok_or("the smart object's contents are unavailable (missing linked file?)")?; + let coverage = sm.filter_mask.clone().filter(|m| m.enabled).map_or(Coverage::None, Coverage::Mask); + open_pixels(app, ctx, layer, surf, params, coverage, Target::SmartFilter(index)) +} diff --git a/crates/ui-egui/src/camera_raw_ui/proxy.rs b/crates/ui-egui/src/camera_raw_ui/proxy.rs new file mode 100644 index 0000000000..93e00960b0 --- /dev/null +++ b/crates/ui-egui/src/camera_raw_ui/proxy.rs @@ -0,0 +1,79 @@ +use super::open::raw_stage; +use super::*; + +/// Everything one develop of the proxy reads, owned, so it can run off the UI thread. +pub(super) struct ProxyJob { + pub(super) proxy: std::sync::Arc>, + pub(super) selection: Option>>, + pub(super) raw_curve: Option>>, + pub(super) params: CameraRaw, + pub(super) float: bool, + pub(super) size: (usize, usize), + pub(super) full_w: usize, + pub(super) display: std::sync::Arc, + pub(super) gpu: Option, + pub(super) source_key: u64, +} + +/// A developed proxy, ready to show. +pub(super) struct ProxyFrame { + pub(super) px: Vec<[f32; 4]>, + pub(super) histogram: RgbHistogram, + pub(super) histogram_ms: f64, + pub(super) image: egui::ColorImage, + pub(super) display: std::sync::Arc, + pub(super) ms: f64, + pub(super) develop_ms: f64, + pub(super) backend: &'static str, +} + +impl ProxyJob { + pub(super) fn run(self) -> ProxyFrame { + let t0 = crate::gpu_canvas::now_ms(); + let (pw, ph) = self.size; + let mut p = self.params; + p.pixel_scale = (pw as f32 / self.full_w.max(1) as f32).min(1.0); + // The open-time dialog re-tones the proxy for each job; otherwise the GPU reads the + // proxy as it is and uploads it once. + let retoned = self.raw_curve.as_ref().map(|curve| { + let mut px = self.proxy.to_vec(); + photocraft_io::raw::retone(&mut px, pw, ph, curve, raw_stage(&p)); + px + }); + if retoned.is_some() { + (p.shadows, p.highlights, p.clarity, p.texture, p.dehaze) = (0.0, 0.0, 0.0, 0.0, 0.0); + } + let develop_start = crate::gpu_canvas::now_ms(); + let key = retoned.is_none().then_some(self.source_key); + let input = retoned.as_deref().unwrap_or(&self.proxy); + let (mut px, backend) = match self.gpu.as_ref().and_then(|g| g.develop(input, key, pw, ph, &p, self.float)) { + Some(out) => (out, "gpu"), + None => { + let mut px = retoned.unwrap_or_else(|| self.proxy.to_vec()); + photocraft_algo::camera_raw::develop(&mut px, pw, ph, &p, self.float); + (px, "cpu") + } + }; + let develop_ms = crate::gpu_canvas::now_ms() - develop_start; + if let Some(mask) = &self.selection { + let blend = |(out, (original, coverage)): (&mut [f32; 4], (&[f32; 4], &f32))| { + for (out, original) in out.iter_mut().zip(original) { + *out = *original + (*out - *original) * coverage; + } + }; + // Each pixel is independent, so bands of the proxy blend in parallel (#211, P36). + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + px.par_iter_mut().zip(self.proxy.par_iter().zip(mask.par_iter())).with_min_len(PARALLEL_MIN_PIXELS).for_each(blend); + } + #[cfg(target_arch = "wasm32")] + px.iter_mut().zip(self.proxy.iter().zip(mask.iter())).for_each(blend); + } + let histogram_start = crate::gpu_canvas::now_ms(); + let histogram = RgbHistogram::from_rgba(&px); + let histogram_ms = crate::gpu_canvas::now_ms() - histogram_start; + let image = CameraRawDialog::image(&px, pw, ph, &self.display); + ProxyFrame { px, histogram, histogram_ms, image, display: self.display, ms: crate::gpu_canvas::now_ms() - t0, develop_ms, backend } + } +} diff --git a/crates/ui-egui/src/camera_raw_ui/sidecar.rs b/crates/ui-egui/src/camera_raw_ui/sidecar.rs new file mode 100644 index 0000000000..1b5b6c9a3d --- /dev/null +++ b/crates/ui-egui/src/camera_raw_ui/sidecar.rs @@ -0,0 +1,155 @@ +use super::controls::remember_edit; +use super::open::RawOpen; +use super::*; + +/// The sidecar beside a raw file: `IMG_0001.xmp` for `IMG_0001.CR2`, as Camera Raw names it. +pub fn sidecar_path(path: &str) -> String { + match path.rsplit_once('.') { + Some((stem, ext)) if !ext.contains(['/', '\\']) => format!("{stem}.xmp"), + _ => format!("{path}.xmp"), + } +} + +/// A DNG carries its settings inside the file in Camera Raw; a sidecar is read for one too, +/// but never written beside it. +fn is_dng(path: &str) -> bool { + path.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("dng")) +} + +/// The settings of the sidecar beside `path`, when there is one that parses: the settings, what +/// the loader skipped, and the sidecar's file name. A sidecar that doesn't parse is ignored (the +/// raw still opens) and reported in the log. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn read_sidecar(path: &str) -> Option<(CameraRaw, photocraft_io::camera_raw_xmp::LoadReport, String)> { + let sidecar = sidecar_path(path); + let Some(bytes) = read_bounded(&sidecar) else { + log::warn!("{sidecar}: not a readable sidecar of at most {} bytes, ignored", photocraft_io::camera_raw_xmp::MAX_XMP_BYTES); + return None; + }; + let mut params = CameraRaw::default(); + match photocraft_io::camera_raw_xmp::load(&mut params, &bytes) { + Ok(report) => Some((params, report, crate::file_open::display_name(&sidecar))), + Err(e) => { + log::warn!("{sidecar}: sidecar ignored: {e}"); + None + } + } +} + +#[cfg(target_arch = "wasm32")] +pub(super) fn read_sidecar(_: &str) -> Option<(CameraRaw, photocraft_io::camera_raw_xmp::LoadReport, String)> { + None +} + +/// Keep the develop settings beside the raw file (Camera Raw Defaults › Write xmp sidecars): +/// written when the settings aren't the defaults or PhotoCraft's own sidecar is there, so a +/// file reopens as it was developed. `loaded` are the settings the open started from: nothing +/// is written when they didn't change. Not for DNGs, never over a sidecar another application +/// wrote (Lightroom's and Bridge's hold crops, masks, ratings and keywords PhotoCraft can't keep), +/// never for a control or MCP request (it has no authority to write beside the user's files), and +/// never fatal: a folder that can't be written to is reported in a notice. +pub(super) fn write_sidecar(app: &mut PhotocraftApp, raw: &RawOpen, params: &CameraRaw, loaded: Option<&CameraRaw>) { + if !app.session.prefs().raw_defaults.write_xmp_sidecars || loaded == Some(params) { + return; + } + if app.automation_input || app.session.authorize.is_some() { + log::info!("{}: sidecar not written for an automation request", raw.name); + return; + } + let Some(path) = raw.path.as_deref().filter(|p| !is_dng(p)) else { return }; + let sidecar = sidecar_path(path); + let name = crate::file_open::display_name(&sidecar); + match existing_sidecar_is_ours(&sidecar) { + Some(false) => { + let kept = crate::i18n::fmt(tl!("Kept {name}: written by another application"), &[("name", &name)]); + crate::notices::post(app, kept, Vec::new(), false, None); + return; + } + None if params.is_identity() => return, + _ => {} + } + let bytes = photocraft_io::camera_raw_xmp::save(params).into_bytes(); + let Some(write) = app.services.write.as_mut() else { return }; + if let Err(e) = write(&sidecar, &bytes) { + crate::notices::error(app, crate::i18n::fmt(tl!("Could not write {name}: {error}"), &[("name", &name), ("error", &e)])); + } +} + +/// `None` when there is no sidecar at `sidecar`, else whether PhotoCraft wrote it. One that +/// can't be read or is too large to be ours counts as another application's. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn existing_sidecar_is_ours(sidecar: &str) -> Option { + std::fs::symlink_metadata(sidecar).ok()?; + Some(read_bounded(sidecar).is_some_and(|b| photocraft_io::camera_raw_xmp::is_photocraft_xmp(&b))) +} + +/// The bytes of the regular file at `path` when it holds at most +/// [`photocraft_io::camera_raw_xmp::MAX_XMP_BYTES`]; `None` for anything else (missing, a folder, +/// a pipe or device that might never end, larger). Never reads more than the cap plus one byte. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn read_bounded(path: &str) -> Option> { + use std::io::Read; + let cap = photocraft_io::camera_raw_xmp::MAX_XMP_BYTES; + // Checked before opening: opening a pipe for reading waits for a writer. + if !std::fs::metadata(path).ok()?.is_file() { + return None; + } + let file = std::fs::File::open(path).ok()?; + let mut bytes = Vec::new(); + file.take(cap as u64 + 1).read_to_end(&mut bytes).ok()?; + (bytes.len() <= cap).then_some(bytes) +} + +#[cfg(target_arch = "wasm32")] +fn existing_sidecar_is_ours(_: &str) -> Option { + None +} + +/// 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 bytes = photocraft_io::camera_raw_xmp::save(&d.params).into_bytes(); + app.pick_save("Camera Raw Settings.xmp", move |app, path| { + let write = app.services.write.as_mut().ok_or("no writer configured")?; + write(&path, &bytes)?; + Ok(json!({"path": path})) + }) +} + +/// 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.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 mut next = d.params.clone(); + let report = photocraft_io::camera_raw_xmp::load(&mut next, &bytes).map_err(|e| format!("{file}: {e}"))?; + next.validate_changes(&d.original).map_err(|e| format!("{file}: {e}"))?; + if d.params.point_curve != next.point_curve { + d.curve_state = Default::default(); + } + if d.params != next { + remember_edit(d); + d.dirty = true; + d.params = next; + } + 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)]) + } else { + let template = "Loaded Camera Raw 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})) + }) +} + +pub(super) fn report_file_error(app: &mut PhotocraftApp, r: Result) { + if let Err(e) = r + && e != crate::file_dialog::CANCELLED + { + app.ui.status_error = true; + app.ui.status = e; + } +} From 27d3634239237b5837bc111ba0a0b546391a872c Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 20:26:59 +0000 Subject: [PATCH 233/259] refactor(engine): move commands.rs to cmd.rs --- crates/engine/src/{commands.rs => cmd.rs} | 0 crates/engine/src/{commands => cmd}/adjust_params.rs | 0 crates/engine/src/{commands => cmd}/enabled.rs | 0 crates/engine/src/{commands => cmd}/layer_params.rs | 0 crates/engine/src/{commands => cmd}/ops.rs | 0 crates/engine/src/{commands => cmd}/params.rs | 0 crates/engine/src/lib.rs | 3 ++- 7 files changed, 2 insertions(+), 1 deletion(-) rename crates/engine/src/{commands.rs => cmd.rs} (100%) rename crates/engine/src/{commands => cmd}/adjust_params.rs (100%) rename crates/engine/src/{commands => cmd}/enabled.rs (100%) rename crates/engine/src/{commands => cmd}/layer_params.rs (100%) rename crates/engine/src/{commands => cmd}/ops.rs (100%) rename crates/engine/src/{commands => cmd}/params.rs (100%) diff --git a/crates/engine/src/commands.rs b/crates/engine/src/cmd.rs similarity index 100% rename from crates/engine/src/commands.rs rename to crates/engine/src/cmd.rs diff --git a/crates/engine/src/commands/adjust_params.rs b/crates/engine/src/cmd/adjust_params.rs similarity index 100% rename from crates/engine/src/commands/adjust_params.rs rename to crates/engine/src/cmd/adjust_params.rs diff --git a/crates/engine/src/commands/enabled.rs b/crates/engine/src/cmd/enabled.rs similarity index 100% rename from crates/engine/src/commands/enabled.rs rename to crates/engine/src/cmd/enabled.rs diff --git a/crates/engine/src/commands/layer_params.rs b/crates/engine/src/cmd/layer_params.rs similarity index 100% rename from crates/engine/src/commands/layer_params.rs rename to crates/engine/src/cmd/layer_params.rs diff --git a/crates/engine/src/commands/ops.rs b/crates/engine/src/cmd/ops.rs similarity index 100% rename from crates/engine/src/commands/ops.rs rename to crates/engine/src/cmd/ops.rs diff --git a/crates/engine/src/commands/params.rs b/crates/engine/src/cmd/params.rs similarity index 100% rename from crates/engine/src/commands/params.rs rename to crates/engine/src/cmd/params.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1633d59b6c..1143583ebf 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -28,7 +28,6 @@ pub mod channel_cmds; mod clip_group; pub mod color_cmds; pub mod color_to_alpha_cmds; -pub mod commands; pub mod comps_cmds; pub mod contour_lib_cmds; mod crop_fill; @@ -153,10 +152,12 @@ pub use photocraft_doc as doc; pub use photocraft_paint as paint; pub use photocraft_paint::BrushSettings; +pub mod cmd; mod doc_state; mod error; mod session; +pub use cmd as commands; pub use doc_state::{CopiedStyle, DocState, PRECHECKED, ToolState}; pub use error::{EngineError, Result}; pub(crate) use session::fix_selection; From 501b7f3459c2645cae7d5d8a06cdc92ac8a59d17 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 20:53:20 +0000 Subject: [PATCH 234/259] refactor(engine): move the *_cmds modules under cmd/ --- crates/engine/src/cmd.rs | 101 +++++++++ crates/engine/src/{ => cmd}/actions_cmds.rs | 0 .../src/{ => cmd}/actions_cmds/tests.rs | 0 .../engine/src/{ => cmd}/actions_edit_cmds.rs | 0 crates/engine/src/{ => cmd}/adjust_cmds.rs | 0 .../engine/src/{ => cmd}/adjust_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/align_cmds.rs | 0 .../engine/src/{ => cmd}/align_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/analysis_cmds.rs | 0 .../src/{ => cmd}/analysis_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/artboard_cmds.rs | 0 .../src/{ => cmd}/artboard_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/atn_cmds.rs | 0 .../src/{ => cmd}/atn_cmds/adjustments.rs | 0 .../engine/src/{ => cmd}/atn_cmds/convert.rs | 0 .../src/{ => cmd}/atn_cmds/descriptors.rs | 0 .../engine/src/{ => cmd}/atn_cmds/events.rs | 0 .../engine/src/{ => cmd}/atn_cmds/fields.rs | 0 crates/engine/src/{ => cmd}/atn_cmds/files.rs | 0 .../{ => cmd}/atn_cmds/layer_props_tests.rs | 0 .../src/{ => cmd}/atn_cmds/steps_doc.rs | 0 .../src/{ => cmd}/atn_cmds/steps_image.rs | 0 .../src/{ => cmd}/atn_cmds/steps_layer.rs | 0 .../src/{ => cmd}/atn_cmds/steps_make.rs | 0 .../engine/src/{ => cmd}/atn_cmds/tables.rs | 0 crates/engine/src/{ => cmd}/atn_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/automate_cmds.rs | 0 .../src/{ => cmd}/automate_cmds/tests.rs | 0 .../engine/src/{ => cmd}/background_cmds.rs | 0 crates/engine/src/{ => cmd}/brush_cmds.rs | 0 .../src/{ => cmd}/brush_cmds/mixer_live.rs | 0 .../{ => cmd}/brush_cmds/mixer_live_tests.rs | 0 .../engine/src/{ => cmd}/brush_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/brush_key_cmds.rs | 0 .../engine/src/{ => cmd}/brush_preset_cmds.rs | 0 .../src/{ => cmd}/brush_preset_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/channel_cmds.rs | 0 .../engine/src/{ => cmd}/channel_cmds/calc.rs | 0 .../src/{ => cmd}/channel_cmds/manage.rs | 0 .../src/{ => cmd}/channel_cmds/planes.rs | 0 .../engine/src/{ => cmd}/channel_cmds/refs.rs | 0 .../src/{ => cmd}/channel_cmds/selection.rs | 0 .../engine/src/{ => cmd}/channel_cmds/spot.rs | 0 .../src/{ => cmd}/channel_cmds/targeting.rs | 0 .../src/{ => cmd}/channel_cmds/tests.rs | 0 .../engine/src/{ => cmd}/channel_cmds/view.rs | 0 crates/engine/src/{ => cmd}/color_cmds.rs | 0 .../src/{ => cmd}/color_to_alpha_cmds.rs | 0 crates/engine/src/{ => cmd}/comps_cmds.rs | 0 .../engine/src/{ => cmd}/comps_cmds/tests.rs | 0 .../engine/src/{ => cmd}/contour_lib_cmds.rs | 0 crates/engine/src/{ => cmd}/cutout_cmds.rs | 0 crates/engine/src/{ => cmd}/distort_cmds.rs | 0 .../src/{ => cmd}/distort_cmds/tests.rs | 0 .../src/{ => cmd}/document_preset_cmds.rs | 0 crates/engine/src/{ => cmd}/edit_cmds.rs | 0 .../engine/src/{ => cmd}/edit_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/edit_menu_cmds.rs | 0 .../{ => cmd}/edit_menu_cmds/content_aware.rs | 0 .../edit_menu_cmds/content_aware_scale.rs | 0 .../src/{ => cmd}/edit_menu_cmds/fade.rs | 0 .../{ => cmd}/edit_menu_cmds/find_replace.rs | 0 .../src/{ => cmd}/edit_menu_cmds/presets.rs | 0 .../src/{ => cmd}/edit_menu_cmds/purge.rs | 0 .../src/{ => cmd}/edit_menu_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/eraser_cmds.rs | 0 .../engine/src/{ => cmd}/eraser_cmds/tests.rs | 0 .../src/{ => cmd}/export_preset_cmds.rs | 0 crates/engine/src/{ => cmd}/exr_cmds.rs | 0 crates/engine/src/{ => cmd}/extra_cmds.rs | 0 .../engine/src/{ => cmd}/extra_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/face_cmds.rs | 0 crates/engine/src/{ => cmd}/file_cmds.rs | 0 .../src/{ => cmd}/file_cmds/batch_naming.rs | 0 .../src/{ => cmd}/file_cmds/batch_run.rs | 0 .../engine/src/{ => cmd}/file_cmds/export.rs | 0 crates/engine/src/{ => cmd}/file_cmds/info.rs | 0 crates/engine/src/{ => cmd}/file_cmds/open.rs | 0 .../engine/src/{ => cmd}/file_cmds/paths.rs | 0 .../src/{ => cmd}/file_cmds/processing.rs | 0 crates/engine/src/{ => cmd}/file_cmds/save.rs | 0 .../engine/src/{ => cmd}/file_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/fill_cmds.rs | 0 .../engine/src/{ => cmd}/fill_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/fill_key_cmds.rs | 0 crates/engine/src/{ => cmd}/float_cmds.rs | 0 .../engine/src/{ => cmd}/float_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/frame_cmds.rs | 0 crates/engine/src/{ => cmd}/fx_view_cmds.rs | 0 .../src/{ => cmd}/fx_visibility_cmds.rs | 0 crates/engine/src/{ => cmd}/gallery_cmds.rs | 0 .../src/{ => cmd}/gallery_cmds/tests.rs | 0 .../src/{ => cmd}/gradient_fill_cmds.rs | 0 .../src/{ => cmd}/gradient_fill_cmds/tests.rs | 0 .../engine/src/{ => cmd}/group_view_cmds.rs | 0 crates/engine/src/{ => cmd}/history_cmds.rs | 0 .../engine/src/{ => cmd}/history_menu_cmds.rs | 0 .../src/{ => cmd}/history_select_cmds.rs | 0 .../src/{ => cmd}/history_source_cmds.rs | 0 crates/engine/src/{ => cmd}/image_cmds.rs | 0 .../engine/src/{ => cmd}/image_cmds/tests.rs | 0 .../engine/src/{ => cmd}/layer_copy_cmds.rs | 0 .../src/{ => cmd}/layer_copy_cmds/tests.rs | 0 .../engine/src/{ => cmd}/layer_label_cmds.rs | 0 .../src/{ => cmd}/layer_label_cmds/tests.rs | 0 .../engine/src/{ => cmd}/layer_list_cmds.rs | 0 .../src/{ => cmd}/layer_mask_props_cmds.rs | 0 .../{ => cmd}/layer_mask_props_cmds/tests.rs | 0 .../engine/src/{ => cmd}/layer_menu_cmds.rs | 0 .../src/{ => cmd}/layer_menu_cmds/tests.rs | 0 .../engine/src/{ => cmd}/layer_multi_cmds.rs | 0 .../src/{ => cmd}/layer_multi_cmds/align.rs | 0 .../src/{ => cmd}/layer_multi_cmds/damage.rs | 0 .../layers_panel_parity_tests.rs | 0 .../src/{ => cmd}/layer_multi_cmds/moves.rs | 0 .../{ => cmd}/layer_multi_cmds/selection.rs | 0 .../{ => cmd}/layer_multi_cmds/structure.rs | 0 .../src/{ => cmd}/layer_multi_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/layer_nav_cmds.rs | 0 crates/engine/src/{ => cmd}/layer_xmp_cmds.rs | 0 .../src/{ => cmd}/layer_xmp_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/lens_cmds.rs | 0 crates/engine/src/{ => cmd}/magnetic_cmds.rs | 0 .../src/{ => cmd}/magnetic_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/mask_view_cmds.rs | 0 .../src/{ => cmd}/mask_view_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/migrate_cmds.rs | 0 crates/engine/src/{ => cmd}/mode_cmds.rs | 0 .../engine/src/{ => cmd}/mode_cmds/tests.rs | 0 .../engine/src/{ => cmd}/multichannel_cmds.rs | 0 .../src/{ => cmd}/multichannel_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/notes_cmds.rs | 0 crates/engine/src/{ => cmd}/paint_cmds.rs | 0 .../engine/src/{ => cmd}/paint_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/path_edit_cmds.rs | 0 crates/engine/src/{ => cmd}/pattern_cmds.rs | 0 .../engine/src/{ => cmd}/pattern_fill_cmds.rs | 0 .../src/{ => cmd}/perspective_crop_cmds.rs | 0 crates/engine/src/{ => cmd}/photo_cmds.rs | 0 .../engine/src/{ => cmd}/photo_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/pick_cmds.rs | 0 crates/engine/src/{ => cmd}/plugin_cmds.rs | 0 .../engine/src/{ => cmd}/plugin_cmds/tests.rs | 2 +- .../src/{ => cmd}/preset_import_cmds.rs | 0 crates/engine/src/{ => cmd}/print_cmds.rs | 0 .../engine/src/{ => cmd}/print_cmds/tests.rs | 0 .../src/{ => cmd}/print_cmds/windows_marks.rs | 0 .../src/{ => cmd}/rasterize_style_cmds.rs | 0 .../{ => cmd}/rasterize_style_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/redeye_cmds.rs | 0 crates/engine/src/{ => cmd}/render_cmds.rs | 0 crates/engine/src/{ => cmd}/retouch_cmds.rs | 0 .../src/{ => cmd}/retouch_cmds/art_history.rs | 0 .../src/{ => cmd}/retouch_cmds/clone.rs | 0 .../retouch_cmds/content_aware_move.rs | 0 .../engine/src/{ => cmd}/retouch_cmds/dab.rs | 0 .../engine/src/{ => cmd}/retouch_cmds/heal.rs | 0 .../src/{ => cmd}/retouch_cmds/patch.rs | 0 .../{ => cmd}/retouch_cmds/pattern_stamp.rs | 0 .../src/{ => cmd}/retouch_cmds/periodic.rs | 0 .../src/{ => cmd}/retouch_cmds/remove.rs | 0 .../src/{ => cmd}/retouch_cmds/sampling.rs | 0 .../src/{ => cmd}/retouch_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/sample_cmds.rs | 0 crates/engine/src/{ => cmd}/sampler_cmds.rs | 0 .../src/{ => cmd}/sampler_cmds/tests.rs | 0 .../engine/src/{ => cmd}/select_extra_cmds.rs | 0 crates/engine/src/{ => cmd}/selection_cmds.rs | 0 .../src/{ => cmd}/selection_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/slice_cmds.rs | 0 .../engine/src/{ => cmd}/slice_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/smart_cmds.rs | 0 .../src/{ => cmd}/smart_cmds/contents.rs | 0 .../src/{ => cmd}/smart_cmds/filters.rs | 0 .../src/{ => cmd}/smart_cmds/placing.rs | 0 .../src/{ => cmd}/smart_cmds/rendering.rs | 0 .../engine/src/{ => cmd}/smart_cmds/source.rs | 0 .../src/{ => cmd}/smart_cmds/stack_cache.rs | 0 .../engine/src/{ => cmd}/smart_cmds/tests.rs | 0 .../smart_cmds/tests/filter_mask_paint.rs | 0 .../{ => cmd}/smart_cmds/tests/selection.rs | 0 .../{ => cmd}/smart_cmds/tests/stack_cache.rs | 0 .../engine/src/{ => cmd}/smart_cmds/unpack.rs | 0 .../engine/src/{ => cmd}/smartselect_cmds.rs | 0 .../src/{ => cmd}/smartselect_cmds/tests.rs | 0 .../engine/src/{ => cmd}/solid_fill_cmds.rs | 0 crates/engine/src/{ => cmd}/stamp_cmds.rs | 0 crates/engine/src/{ => cmd}/style_asl_cmds.rs | 0 crates/engine/src/{ => cmd}/swatch_cmds.rs | 0 .../engine/src/{ => cmd}/swatch_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/symmetry_cmds.rs | 0 .../{ => cmd}/symmetry_cmds/preset_tests.rs | 0 crates/engine/src/{ => cmd}/timeline_cmds.rs | 0 crates/engine/src/{ => cmd}/transform_cmds.rs | 0 .../src/{ => cmd}/transform_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/trap_cmds.rs | 0 crates/engine/src/{ => cmd}/type_area_cmds.rs | 0 .../src/{ => cmd}/type_area_cmds/tests.rs | 0 .../engine/src/{ => cmd}/type_caret_cmds.rs | 0 crates/engine/src/{ => cmd}/type_cmds.rs | 0 .../engine/src/{ => cmd}/type_cmds/tests.rs | 0 .../engine/src/{ => cmd}/type_extra_cmds.rs | 0 .../src/{ => cmd}/type_extra_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/type_mask_cmds.rs | 0 .../engine/src/{ => cmd}/type_spell_cmds.rs | 0 .../engine/src/{ => cmd}/type_styles_cmds.rs | 0 .../src/{ => cmd}/type_styles_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/updates_cmds.rs | 0 crates/engine/src/{ => cmd}/variables_cmds.rs | 0 .../src/{ => cmd}/variables_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/vector_cmds.rs | 0 .../src/{ => cmd}/vector_cmds/params.rs | 0 .../engine/src/{ => cmd}/vector_cmds/paths.rs | 0 .../engine/src/{ => cmd}/vector_cmds/shape.rs | 0 .../engine/src/{ => cmd}/vector_cmds/tests.rs | 0 .../src/{ => cmd}/vector_cmds/vector_mask.rs | 0 crates/engine/src/{ => cmd}/video_cmds.rs | 0 .../engine/src/{ => cmd}/video_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/vp_cmds.rs | 0 crates/engine/src/{ => cmd}/warp_cmds.rs | 0 .../engine/src/{ => cmd}/warp_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/web_cmds.rs | 0 .../engine/src/{ => cmd}/web_cmds/assets.rs | 0 .../{ => cmd}/web_cmds/color_table_tests.rs | 0 .../src/{ => cmd}/web_cmds/optimizer.rs | 0 crates/engine/src/{ => cmd}/web_cmds/quick.rs | 0 .../engine/src/{ => cmd}/web_cmds/save_web.rs | 0 .../engine/src/{ => cmd}/web_cmds/settings.rs | 0 crates/engine/src/{ => cmd}/web_cmds/tests.rs | 0 crates/engine/src/{ => cmd}/wia_cmds.rs | 0 crates/engine/src/lib.rs | 202 +++++++++--------- 231 files changed, 203 insertions(+), 102 deletions(-) rename crates/engine/src/{ => cmd}/actions_cmds.rs (100%) rename crates/engine/src/{ => cmd}/actions_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/actions_edit_cmds.rs (100%) rename crates/engine/src/{ => cmd}/adjust_cmds.rs (100%) rename crates/engine/src/{ => cmd}/adjust_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/align_cmds.rs (100%) rename crates/engine/src/{ => cmd}/align_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/analysis_cmds.rs (100%) rename crates/engine/src/{ => cmd}/analysis_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/artboard_cmds.rs (100%) rename crates/engine/src/{ => cmd}/artboard_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/atn_cmds.rs (100%) rename crates/engine/src/{ => cmd}/atn_cmds/adjustments.rs (100%) rename crates/engine/src/{ => cmd}/atn_cmds/convert.rs (100%) rename crates/engine/src/{ => cmd}/atn_cmds/descriptors.rs (100%) rename crates/engine/src/{ => cmd}/atn_cmds/events.rs (100%) rename crates/engine/src/{ => cmd}/atn_cmds/fields.rs (100%) rename crates/engine/src/{ => cmd}/atn_cmds/files.rs (100%) rename crates/engine/src/{ => cmd}/atn_cmds/layer_props_tests.rs (100%) rename crates/engine/src/{ => cmd}/atn_cmds/steps_doc.rs (100%) rename crates/engine/src/{ => cmd}/atn_cmds/steps_image.rs (100%) rename crates/engine/src/{ => cmd}/atn_cmds/steps_layer.rs (100%) rename crates/engine/src/{ => cmd}/atn_cmds/steps_make.rs (100%) rename crates/engine/src/{ => cmd}/atn_cmds/tables.rs (100%) rename crates/engine/src/{ => cmd}/atn_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/automate_cmds.rs (100%) rename crates/engine/src/{ => cmd}/automate_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/background_cmds.rs (100%) rename crates/engine/src/{ => cmd}/brush_cmds.rs (100%) rename crates/engine/src/{ => cmd}/brush_cmds/mixer_live.rs (100%) rename crates/engine/src/{ => cmd}/brush_cmds/mixer_live_tests.rs (100%) rename crates/engine/src/{ => cmd}/brush_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/brush_key_cmds.rs (100%) rename crates/engine/src/{ => cmd}/brush_preset_cmds.rs (100%) rename crates/engine/src/{ => cmd}/brush_preset_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/channel_cmds.rs (100%) rename crates/engine/src/{ => cmd}/channel_cmds/calc.rs (100%) rename crates/engine/src/{ => cmd}/channel_cmds/manage.rs (100%) rename crates/engine/src/{ => cmd}/channel_cmds/planes.rs (100%) rename crates/engine/src/{ => cmd}/channel_cmds/refs.rs (100%) rename crates/engine/src/{ => cmd}/channel_cmds/selection.rs (100%) rename crates/engine/src/{ => cmd}/channel_cmds/spot.rs (100%) rename crates/engine/src/{ => cmd}/channel_cmds/targeting.rs (100%) rename crates/engine/src/{ => cmd}/channel_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/channel_cmds/view.rs (100%) rename crates/engine/src/{ => cmd}/color_cmds.rs (100%) rename crates/engine/src/{ => cmd}/color_to_alpha_cmds.rs (100%) rename crates/engine/src/{ => cmd}/comps_cmds.rs (100%) rename crates/engine/src/{ => cmd}/comps_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/contour_lib_cmds.rs (100%) rename crates/engine/src/{ => cmd}/cutout_cmds.rs (100%) rename crates/engine/src/{ => cmd}/distort_cmds.rs (100%) rename crates/engine/src/{ => cmd}/distort_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/document_preset_cmds.rs (100%) rename crates/engine/src/{ => cmd}/edit_cmds.rs (100%) rename crates/engine/src/{ => cmd}/edit_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/edit_menu_cmds.rs (100%) rename crates/engine/src/{ => cmd}/edit_menu_cmds/content_aware.rs (100%) rename crates/engine/src/{ => cmd}/edit_menu_cmds/content_aware_scale.rs (100%) rename crates/engine/src/{ => cmd}/edit_menu_cmds/fade.rs (100%) rename crates/engine/src/{ => cmd}/edit_menu_cmds/find_replace.rs (100%) rename crates/engine/src/{ => cmd}/edit_menu_cmds/presets.rs (100%) rename crates/engine/src/{ => cmd}/edit_menu_cmds/purge.rs (100%) rename crates/engine/src/{ => cmd}/edit_menu_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/eraser_cmds.rs (100%) rename crates/engine/src/{ => cmd}/eraser_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/export_preset_cmds.rs (100%) rename crates/engine/src/{ => cmd}/exr_cmds.rs (100%) rename crates/engine/src/{ => cmd}/extra_cmds.rs (100%) rename crates/engine/src/{ => cmd}/extra_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/face_cmds.rs (100%) rename crates/engine/src/{ => cmd}/file_cmds.rs (100%) rename crates/engine/src/{ => cmd}/file_cmds/batch_naming.rs (100%) rename crates/engine/src/{ => cmd}/file_cmds/batch_run.rs (100%) rename crates/engine/src/{ => cmd}/file_cmds/export.rs (100%) rename crates/engine/src/{ => cmd}/file_cmds/info.rs (100%) rename crates/engine/src/{ => cmd}/file_cmds/open.rs (100%) rename crates/engine/src/{ => cmd}/file_cmds/paths.rs (100%) rename crates/engine/src/{ => cmd}/file_cmds/processing.rs (100%) rename crates/engine/src/{ => cmd}/file_cmds/save.rs (100%) rename crates/engine/src/{ => cmd}/file_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/fill_cmds.rs (100%) rename crates/engine/src/{ => cmd}/fill_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/fill_key_cmds.rs (100%) rename crates/engine/src/{ => cmd}/float_cmds.rs (100%) rename crates/engine/src/{ => cmd}/float_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/frame_cmds.rs (100%) rename crates/engine/src/{ => cmd}/fx_view_cmds.rs (100%) rename crates/engine/src/{ => cmd}/fx_visibility_cmds.rs (100%) rename crates/engine/src/{ => cmd}/gallery_cmds.rs (100%) rename crates/engine/src/{ => cmd}/gallery_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/gradient_fill_cmds.rs (100%) rename crates/engine/src/{ => cmd}/gradient_fill_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/group_view_cmds.rs (100%) rename crates/engine/src/{ => cmd}/history_cmds.rs (100%) rename crates/engine/src/{ => cmd}/history_menu_cmds.rs (100%) rename crates/engine/src/{ => cmd}/history_select_cmds.rs (100%) rename crates/engine/src/{ => cmd}/history_source_cmds.rs (100%) rename crates/engine/src/{ => cmd}/image_cmds.rs (100%) rename crates/engine/src/{ => cmd}/image_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/layer_copy_cmds.rs (100%) rename crates/engine/src/{ => cmd}/layer_copy_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/layer_label_cmds.rs (100%) rename crates/engine/src/{ => cmd}/layer_label_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/layer_list_cmds.rs (100%) rename crates/engine/src/{ => cmd}/layer_mask_props_cmds.rs (100%) rename crates/engine/src/{ => cmd}/layer_mask_props_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/layer_menu_cmds.rs (100%) rename crates/engine/src/{ => cmd}/layer_menu_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/layer_multi_cmds.rs (100%) rename crates/engine/src/{ => cmd}/layer_multi_cmds/align.rs (100%) rename crates/engine/src/{ => cmd}/layer_multi_cmds/damage.rs (100%) rename crates/engine/src/{ => cmd}/layer_multi_cmds/layers_panel_parity_tests.rs (100%) rename crates/engine/src/{ => cmd}/layer_multi_cmds/moves.rs (100%) rename crates/engine/src/{ => cmd}/layer_multi_cmds/selection.rs (100%) rename crates/engine/src/{ => cmd}/layer_multi_cmds/structure.rs (100%) rename crates/engine/src/{ => cmd}/layer_multi_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/layer_nav_cmds.rs (100%) rename crates/engine/src/{ => cmd}/layer_xmp_cmds.rs (100%) rename crates/engine/src/{ => cmd}/layer_xmp_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/lens_cmds.rs (100%) rename crates/engine/src/{ => cmd}/magnetic_cmds.rs (100%) rename crates/engine/src/{ => cmd}/magnetic_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/mask_view_cmds.rs (100%) rename crates/engine/src/{ => cmd}/mask_view_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/migrate_cmds.rs (100%) rename crates/engine/src/{ => cmd}/mode_cmds.rs (100%) rename crates/engine/src/{ => cmd}/mode_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/multichannel_cmds.rs (100%) rename crates/engine/src/{ => cmd}/multichannel_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/notes_cmds.rs (100%) rename crates/engine/src/{ => cmd}/paint_cmds.rs (100%) rename crates/engine/src/{ => cmd}/paint_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/path_edit_cmds.rs (100%) rename crates/engine/src/{ => cmd}/pattern_cmds.rs (100%) rename crates/engine/src/{ => cmd}/pattern_fill_cmds.rs (100%) rename crates/engine/src/{ => cmd}/perspective_crop_cmds.rs (100%) rename crates/engine/src/{ => cmd}/photo_cmds.rs (100%) rename crates/engine/src/{ => cmd}/photo_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/pick_cmds.rs (100%) rename crates/engine/src/{ => cmd}/plugin_cmds.rs (100%) rename crates/engine/src/{ => cmd}/plugin_cmds/tests.rs (99%) rename crates/engine/src/{ => cmd}/preset_import_cmds.rs (100%) rename crates/engine/src/{ => cmd}/print_cmds.rs (100%) rename crates/engine/src/{ => cmd}/print_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/print_cmds/windows_marks.rs (100%) rename crates/engine/src/{ => cmd}/rasterize_style_cmds.rs (100%) rename crates/engine/src/{ => cmd}/rasterize_style_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/redeye_cmds.rs (100%) rename crates/engine/src/{ => cmd}/render_cmds.rs (100%) rename crates/engine/src/{ => cmd}/retouch_cmds.rs (100%) rename crates/engine/src/{ => cmd}/retouch_cmds/art_history.rs (100%) rename crates/engine/src/{ => cmd}/retouch_cmds/clone.rs (100%) rename crates/engine/src/{ => cmd}/retouch_cmds/content_aware_move.rs (100%) rename crates/engine/src/{ => cmd}/retouch_cmds/dab.rs (100%) rename crates/engine/src/{ => cmd}/retouch_cmds/heal.rs (100%) rename crates/engine/src/{ => cmd}/retouch_cmds/patch.rs (100%) rename crates/engine/src/{ => cmd}/retouch_cmds/pattern_stamp.rs (100%) rename crates/engine/src/{ => cmd}/retouch_cmds/periodic.rs (100%) rename crates/engine/src/{ => cmd}/retouch_cmds/remove.rs (100%) rename crates/engine/src/{ => cmd}/retouch_cmds/sampling.rs (100%) rename crates/engine/src/{ => cmd}/retouch_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/sample_cmds.rs (100%) rename crates/engine/src/{ => cmd}/sampler_cmds.rs (100%) rename crates/engine/src/{ => cmd}/sampler_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/select_extra_cmds.rs (100%) rename crates/engine/src/{ => cmd}/selection_cmds.rs (100%) rename crates/engine/src/{ => cmd}/selection_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/slice_cmds.rs (100%) rename crates/engine/src/{ => cmd}/slice_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/smart_cmds.rs (100%) rename crates/engine/src/{ => cmd}/smart_cmds/contents.rs (100%) rename crates/engine/src/{ => cmd}/smart_cmds/filters.rs (100%) rename crates/engine/src/{ => cmd}/smart_cmds/placing.rs (100%) rename crates/engine/src/{ => cmd}/smart_cmds/rendering.rs (100%) rename crates/engine/src/{ => cmd}/smart_cmds/source.rs (100%) rename crates/engine/src/{ => cmd}/smart_cmds/stack_cache.rs (100%) rename crates/engine/src/{ => cmd}/smart_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/smart_cmds/tests/filter_mask_paint.rs (100%) rename crates/engine/src/{ => cmd}/smart_cmds/tests/selection.rs (100%) rename crates/engine/src/{ => cmd}/smart_cmds/tests/stack_cache.rs (100%) rename crates/engine/src/{ => cmd}/smart_cmds/unpack.rs (100%) rename crates/engine/src/{ => cmd}/smartselect_cmds.rs (100%) rename crates/engine/src/{ => cmd}/smartselect_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/solid_fill_cmds.rs (100%) rename crates/engine/src/{ => cmd}/stamp_cmds.rs (100%) rename crates/engine/src/{ => cmd}/style_asl_cmds.rs (100%) rename crates/engine/src/{ => cmd}/swatch_cmds.rs (100%) rename crates/engine/src/{ => cmd}/swatch_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/symmetry_cmds.rs (100%) rename crates/engine/src/{ => cmd}/symmetry_cmds/preset_tests.rs (100%) rename crates/engine/src/{ => cmd}/timeline_cmds.rs (100%) rename crates/engine/src/{ => cmd}/transform_cmds.rs (100%) rename crates/engine/src/{ => cmd}/transform_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/trap_cmds.rs (100%) rename crates/engine/src/{ => cmd}/type_area_cmds.rs (100%) rename crates/engine/src/{ => cmd}/type_area_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/type_caret_cmds.rs (100%) rename crates/engine/src/{ => cmd}/type_cmds.rs (100%) rename crates/engine/src/{ => cmd}/type_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/type_extra_cmds.rs (100%) rename crates/engine/src/{ => cmd}/type_extra_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/type_mask_cmds.rs (100%) rename crates/engine/src/{ => cmd}/type_spell_cmds.rs (100%) rename crates/engine/src/{ => cmd}/type_styles_cmds.rs (100%) rename crates/engine/src/{ => cmd}/type_styles_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/updates_cmds.rs (100%) rename crates/engine/src/{ => cmd}/variables_cmds.rs (100%) rename crates/engine/src/{ => cmd}/variables_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/vector_cmds.rs (100%) rename crates/engine/src/{ => cmd}/vector_cmds/params.rs (100%) rename crates/engine/src/{ => cmd}/vector_cmds/paths.rs (100%) rename crates/engine/src/{ => cmd}/vector_cmds/shape.rs (100%) rename crates/engine/src/{ => cmd}/vector_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/vector_cmds/vector_mask.rs (100%) rename crates/engine/src/{ => cmd}/video_cmds.rs (100%) rename crates/engine/src/{ => cmd}/video_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/vp_cmds.rs (100%) rename crates/engine/src/{ => cmd}/warp_cmds.rs (100%) rename crates/engine/src/{ => cmd}/warp_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/web_cmds.rs (100%) rename crates/engine/src/{ => cmd}/web_cmds/assets.rs (100%) rename crates/engine/src/{ => cmd}/web_cmds/color_table_tests.rs (100%) rename crates/engine/src/{ => cmd}/web_cmds/optimizer.rs (100%) rename crates/engine/src/{ => cmd}/web_cmds/quick.rs (100%) rename crates/engine/src/{ => cmd}/web_cmds/save_web.rs (100%) rename crates/engine/src/{ => cmd}/web_cmds/settings.rs (100%) rename crates/engine/src/{ => cmd}/web_cmds/tests.rs (100%) rename crates/engine/src/{ => cmd}/wia_cmds.rs (100%) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index bfef73b7b7..38ede534b1 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -49,11 +49,112 @@ macro_rules! cmd { }; } +pub mod actions_cmds; +pub mod actions_edit_cmds; +pub mod adjust_cmds; mod adjust_params; +pub mod align_cmds; +pub mod analysis_cmds; +pub mod artboard_cmds; +pub mod atn_cmds; +pub mod automate_cmds; +pub mod background_cmds; +pub mod brush_cmds; +pub mod brush_key_cmds; +pub mod brush_preset_cmds; +pub mod channel_cmds; +pub mod color_cmds; +pub mod color_to_alpha_cmds; +pub mod comps_cmds; +pub mod contour_lib_cmds; +pub mod cutout_cmds; +pub mod distort_cmds; +pub mod document_preset_cmds; +pub mod edit_cmds; +pub mod edit_menu_cmds; mod enabled; +pub mod eraser_cmds; +pub mod export_preset_cmds; +pub mod exr_cmds; +pub mod extra_cmds; +pub mod face_cmds; +pub mod file_cmds; +pub mod fill_cmds; +pub mod fill_key_cmds; +pub mod float_cmds; +pub(super) mod frame_cmds; +pub mod fx_view_cmds; +pub mod fx_visibility_cmds; +pub mod gallery_cmds; +pub mod gradient_fill_cmds; +pub mod group_view_cmds; +pub mod history_cmds; +pub mod history_menu_cmds; +pub mod history_select_cmds; +pub mod history_source_cmds; +pub mod image_cmds; +pub mod layer_copy_cmds; +pub mod layer_label_cmds; +pub mod layer_list_cmds; +pub mod layer_mask_props_cmds; +pub mod layer_menu_cmds; +pub mod layer_multi_cmds; +pub mod layer_nav_cmds; mod layer_params; +pub mod layer_xmp_cmds; +pub mod lens_cmds; +pub mod magnetic_cmds; +pub mod mask_view_cmds; +pub(super) mod migrate_cmds; +pub mod mode_cmds; +pub mod multichannel_cmds; +pub mod notes_cmds; mod ops; +pub mod paint_cmds; mod params; +pub(super) mod path_edit_cmds; +pub mod pattern_cmds; +pub mod pattern_fill_cmds; +pub mod perspective_crop_cmds; +pub mod photo_cmds; +pub mod pick_cmds; +pub mod plugin_cmds; +pub mod preset_import_cmds; +pub mod print_cmds; +pub mod rasterize_style_cmds; +pub mod redeye_cmds; +pub mod render_cmds; +pub mod retouch_cmds; +pub mod sample_cmds; +pub mod sampler_cmds; +pub mod select_extra_cmds; +pub mod selection_cmds; +pub mod slice_cmds; +pub mod smart_cmds; +pub mod smartselect_cmds; +pub mod solid_fill_cmds; +pub mod stamp_cmds; +pub mod style_asl_cmds; +pub mod swatch_cmds; +pub mod symmetry_cmds; +pub(super) mod timeline_cmds; +pub mod transform_cmds; +pub(super) mod trap_cmds; +pub mod type_area_cmds; +pub mod type_caret_cmds; +pub mod type_cmds; +pub mod type_extra_cmds; +pub mod type_mask_cmds; +pub mod type_spell_cmds; +pub mod type_styles_cmds; +pub mod updates_cmds; +pub(super) mod variables_cmds; +pub mod vector_cmds; +pub(super) mod video_cmds; +pub mod vp_cmds; +pub mod warp_cmds; +pub mod web_cmds; +pub(super) mod wia_cmds; pub(crate) use adjust_params::inject_kind; use adjust_params::{adjust_mode, destructive_adjust, doc_mode, gray_tone_params, new_adjustment}; diff --git a/crates/engine/src/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs similarity index 100% rename from crates/engine/src/actions_cmds.rs rename to crates/engine/src/cmd/actions_cmds.rs diff --git a/crates/engine/src/actions_cmds/tests.rs b/crates/engine/src/cmd/actions_cmds/tests.rs similarity index 100% rename from crates/engine/src/actions_cmds/tests.rs rename to crates/engine/src/cmd/actions_cmds/tests.rs diff --git a/crates/engine/src/actions_edit_cmds.rs b/crates/engine/src/cmd/actions_edit_cmds.rs similarity index 100% rename from crates/engine/src/actions_edit_cmds.rs rename to crates/engine/src/cmd/actions_edit_cmds.rs diff --git a/crates/engine/src/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs similarity index 100% rename from crates/engine/src/adjust_cmds.rs rename to crates/engine/src/cmd/adjust_cmds.rs diff --git a/crates/engine/src/adjust_cmds/tests.rs b/crates/engine/src/cmd/adjust_cmds/tests.rs similarity index 100% rename from crates/engine/src/adjust_cmds/tests.rs rename to crates/engine/src/cmd/adjust_cmds/tests.rs diff --git a/crates/engine/src/align_cmds.rs b/crates/engine/src/cmd/align_cmds.rs similarity index 100% rename from crates/engine/src/align_cmds.rs rename to crates/engine/src/cmd/align_cmds.rs diff --git a/crates/engine/src/align_cmds/tests.rs b/crates/engine/src/cmd/align_cmds/tests.rs similarity index 100% rename from crates/engine/src/align_cmds/tests.rs rename to crates/engine/src/cmd/align_cmds/tests.rs diff --git a/crates/engine/src/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs similarity index 100% rename from crates/engine/src/analysis_cmds.rs rename to crates/engine/src/cmd/analysis_cmds.rs diff --git a/crates/engine/src/analysis_cmds/tests.rs b/crates/engine/src/cmd/analysis_cmds/tests.rs similarity index 100% rename from crates/engine/src/analysis_cmds/tests.rs rename to crates/engine/src/cmd/analysis_cmds/tests.rs diff --git a/crates/engine/src/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs similarity index 100% rename from crates/engine/src/artboard_cmds.rs rename to crates/engine/src/cmd/artboard_cmds.rs diff --git a/crates/engine/src/artboard_cmds/tests.rs b/crates/engine/src/cmd/artboard_cmds/tests.rs similarity index 100% rename from crates/engine/src/artboard_cmds/tests.rs rename to crates/engine/src/cmd/artboard_cmds/tests.rs diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs similarity index 100% rename from crates/engine/src/atn_cmds.rs rename to crates/engine/src/cmd/atn_cmds.rs diff --git a/crates/engine/src/atn_cmds/adjustments.rs b/crates/engine/src/cmd/atn_cmds/adjustments.rs similarity index 100% rename from crates/engine/src/atn_cmds/adjustments.rs rename to crates/engine/src/cmd/atn_cmds/adjustments.rs diff --git a/crates/engine/src/atn_cmds/convert.rs b/crates/engine/src/cmd/atn_cmds/convert.rs similarity index 100% rename from crates/engine/src/atn_cmds/convert.rs rename to crates/engine/src/cmd/atn_cmds/convert.rs diff --git a/crates/engine/src/atn_cmds/descriptors.rs b/crates/engine/src/cmd/atn_cmds/descriptors.rs similarity index 100% rename from crates/engine/src/atn_cmds/descriptors.rs rename to crates/engine/src/cmd/atn_cmds/descriptors.rs diff --git a/crates/engine/src/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs similarity index 100% rename from crates/engine/src/atn_cmds/events.rs rename to crates/engine/src/cmd/atn_cmds/events.rs diff --git a/crates/engine/src/atn_cmds/fields.rs b/crates/engine/src/cmd/atn_cmds/fields.rs similarity index 100% rename from crates/engine/src/atn_cmds/fields.rs rename to crates/engine/src/cmd/atn_cmds/fields.rs diff --git a/crates/engine/src/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs similarity index 100% rename from crates/engine/src/atn_cmds/files.rs rename to crates/engine/src/cmd/atn_cmds/files.rs diff --git a/crates/engine/src/atn_cmds/layer_props_tests.rs b/crates/engine/src/cmd/atn_cmds/layer_props_tests.rs similarity index 100% rename from crates/engine/src/atn_cmds/layer_props_tests.rs rename to crates/engine/src/cmd/atn_cmds/layer_props_tests.rs diff --git a/crates/engine/src/atn_cmds/steps_doc.rs b/crates/engine/src/cmd/atn_cmds/steps_doc.rs similarity index 100% rename from crates/engine/src/atn_cmds/steps_doc.rs rename to crates/engine/src/cmd/atn_cmds/steps_doc.rs diff --git a/crates/engine/src/atn_cmds/steps_image.rs b/crates/engine/src/cmd/atn_cmds/steps_image.rs similarity index 100% rename from crates/engine/src/atn_cmds/steps_image.rs rename to crates/engine/src/cmd/atn_cmds/steps_image.rs diff --git a/crates/engine/src/atn_cmds/steps_layer.rs b/crates/engine/src/cmd/atn_cmds/steps_layer.rs similarity index 100% rename from crates/engine/src/atn_cmds/steps_layer.rs rename to crates/engine/src/cmd/atn_cmds/steps_layer.rs diff --git a/crates/engine/src/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs similarity index 100% rename from crates/engine/src/atn_cmds/steps_make.rs rename to crates/engine/src/cmd/atn_cmds/steps_make.rs diff --git a/crates/engine/src/atn_cmds/tables.rs b/crates/engine/src/cmd/atn_cmds/tables.rs similarity index 100% rename from crates/engine/src/atn_cmds/tables.rs rename to crates/engine/src/cmd/atn_cmds/tables.rs diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs similarity index 100% rename from crates/engine/src/atn_cmds/tests.rs rename to crates/engine/src/cmd/atn_cmds/tests.rs diff --git a/crates/engine/src/automate_cmds.rs b/crates/engine/src/cmd/automate_cmds.rs similarity index 100% rename from crates/engine/src/automate_cmds.rs rename to crates/engine/src/cmd/automate_cmds.rs diff --git a/crates/engine/src/automate_cmds/tests.rs b/crates/engine/src/cmd/automate_cmds/tests.rs similarity index 100% rename from crates/engine/src/automate_cmds/tests.rs rename to crates/engine/src/cmd/automate_cmds/tests.rs diff --git a/crates/engine/src/background_cmds.rs b/crates/engine/src/cmd/background_cmds.rs similarity index 100% rename from crates/engine/src/background_cmds.rs rename to crates/engine/src/cmd/background_cmds.rs diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs similarity index 100% rename from crates/engine/src/brush_cmds.rs rename to crates/engine/src/cmd/brush_cmds.rs diff --git a/crates/engine/src/brush_cmds/mixer_live.rs b/crates/engine/src/cmd/brush_cmds/mixer_live.rs similarity index 100% rename from crates/engine/src/brush_cmds/mixer_live.rs rename to crates/engine/src/cmd/brush_cmds/mixer_live.rs diff --git a/crates/engine/src/brush_cmds/mixer_live_tests.rs b/crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs similarity index 100% rename from crates/engine/src/brush_cmds/mixer_live_tests.rs rename to crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs diff --git a/crates/engine/src/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs similarity index 100% rename from crates/engine/src/brush_cmds/tests.rs rename to crates/engine/src/cmd/brush_cmds/tests.rs diff --git a/crates/engine/src/brush_key_cmds.rs b/crates/engine/src/cmd/brush_key_cmds.rs similarity index 100% rename from crates/engine/src/brush_key_cmds.rs rename to crates/engine/src/cmd/brush_key_cmds.rs diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/cmd/brush_preset_cmds.rs similarity index 100% rename from crates/engine/src/brush_preset_cmds.rs rename to crates/engine/src/cmd/brush_preset_cmds.rs diff --git a/crates/engine/src/brush_preset_cmds/tests.rs b/crates/engine/src/cmd/brush_preset_cmds/tests.rs similarity index 100% rename from crates/engine/src/brush_preset_cmds/tests.rs rename to crates/engine/src/cmd/brush_preset_cmds/tests.rs diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/cmd/channel_cmds.rs similarity index 100% rename from crates/engine/src/channel_cmds.rs rename to crates/engine/src/cmd/channel_cmds.rs diff --git a/crates/engine/src/channel_cmds/calc.rs b/crates/engine/src/cmd/channel_cmds/calc.rs similarity index 100% rename from crates/engine/src/channel_cmds/calc.rs rename to crates/engine/src/cmd/channel_cmds/calc.rs diff --git a/crates/engine/src/channel_cmds/manage.rs b/crates/engine/src/cmd/channel_cmds/manage.rs similarity index 100% rename from crates/engine/src/channel_cmds/manage.rs rename to crates/engine/src/cmd/channel_cmds/manage.rs diff --git a/crates/engine/src/channel_cmds/planes.rs b/crates/engine/src/cmd/channel_cmds/planes.rs similarity index 100% rename from crates/engine/src/channel_cmds/planes.rs rename to crates/engine/src/cmd/channel_cmds/planes.rs diff --git a/crates/engine/src/channel_cmds/refs.rs b/crates/engine/src/cmd/channel_cmds/refs.rs similarity index 100% rename from crates/engine/src/channel_cmds/refs.rs rename to crates/engine/src/cmd/channel_cmds/refs.rs diff --git a/crates/engine/src/channel_cmds/selection.rs b/crates/engine/src/cmd/channel_cmds/selection.rs similarity index 100% rename from crates/engine/src/channel_cmds/selection.rs rename to crates/engine/src/cmd/channel_cmds/selection.rs diff --git a/crates/engine/src/channel_cmds/spot.rs b/crates/engine/src/cmd/channel_cmds/spot.rs similarity index 100% rename from crates/engine/src/channel_cmds/spot.rs rename to crates/engine/src/cmd/channel_cmds/spot.rs diff --git a/crates/engine/src/channel_cmds/targeting.rs b/crates/engine/src/cmd/channel_cmds/targeting.rs similarity index 100% rename from crates/engine/src/channel_cmds/targeting.rs rename to crates/engine/src/cmd/channel_cmds/targeting.rs diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/cmd/channel_cmds/tests.rs similarity index 100% rename from crates/engine/src/channel_cmds/tests.rs rename to crates/engine/src/cmd/channel_cmds/tests.rs diff --git a/crates/engine/src/channel_cmds/view.rs b/crates/engine/src/cmd/channel_cmds/view.rs similarity index 100% rename from crates/engine/src/channel_cmds/view.rs rename to crates/engine/src/cmd/channel_cmds/view.rs diff --git a/crates/engine/src/color_cmds.rs b/crates/engine/src/cmd/color_cmds.rs similarity index 100% rename from crates/engine/src/color_cmds.rs rename to crates/engine/src/cmd/color_cmds.rs diff --git a/crates/engine/src/color_to_alpha_cmds.rs b/crates/engine/src/cmd/color_to_alpha_cmds.rs similarity index 100% rename from crates/engine/src/color_to_alpha_cmds.rs rename to crates/engine/src/cmd/color_to_alpha_cmds.rs diff --git a/crates/engine/src/comps_cmds.rs b/crates/engine/src/cmd/comps_cmds.rs similarity index 100% rename from crates/engine/src/comps_cmds.rs rename to crates/engine/src/cmd/comps_cmds.rs diff --git a/crates/engine/src/comps_cmds/tests.rs b/crates/engine/src/cmd/comps_cmds/tests.rs similarity index 100% rename from crates/engine/src/comps_cmds/tests.rs rename to crates/engine/src/cmd/comps_cmds/tests.rs diff --git a/crates/engine/src/contour_lib_cmds.rs b/crates/engine/src/cmd/contour_lib_cmds.rs similarity index 100% rename from crates/engine/src/contour_lib_cmds.rs rename to crates/engine/src/cmd/contour_lib_cmds.rs diff --git a/crates/engine/src/cutout_cmds.rs b/crates/engine/src/cmd/cutout_cmds.rs similarity index 100% rename from crates/engine/src/cutout_cmds.rs rename to crates/engine/src/cmd/cutout_cmds.rs diff --git a/crates/engine/src/distort_cmds.rs b/crates/engine/src/cmd/distort_cmds.rs similarity index 100% rename from crates/engine/src/distort_cmds.rs rename to crates/engine/src/cmd/distort_cmds.rs diff --git a/crates/engine/src/distort_cmds/tests.rs b/crates/engine/src/cmd/distort_cmds/tests.rs similarity index 100% rename from crates/engine/src/distort_cmds/tests.rs rename to crates/engine/src/cmd/distort_cmds/tests.rs diff --git a/crates/engine/src/document_preset_cmds.rs b/crates/engine/src/cmd/document_preset_cmds.rs similarity index 100% rename from crates/engine/src/document_preset_cmds.rs rename to crates/engine/src/cmd/document_preset_cmds.rs diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/cmd/edit_cmds.rs similarity index 100% rename from crates/engine/src/edit_cmds.rs rename to crates/engine/src/cmd/edit_cmds.rs diff --git a/crates/engine/src/edit_cmds/tests.rs b/crates/engine/src/cmd/edit_cmds/tests.rs similarity index 100% rename from crates/engine/src/edit_cmds/tests.rs rename to crates/engine/src/cmd/edit_cmds/tests.rs diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/cmd/edit_menu_cmds.rs similarity index 100% rename from crates/engine/src/edit_menu_cmds.rs rename to crates/engine/src/cmd/edit_menu_cmds.rs diff --git a/crates/engine/src/edit_menu_cmds/content_aware.rs b/crates/engine/src/cmd/edit_menu_cmds/content_aware.rs similarity index 100% rename from crates/engine/src/edit_menu_cmds/content_aware.rs rename to crates/engine/src/cmd/edit_menu_cmds/content_aware.rs diff --git a/crates/engine/src/edit_menu_cmds/content_aware_scale.rs b/crates/engine/src/cmd/edit_menu_cmds/content_aware_scale.rs similarity index 100% rename from crates/engine/src/edit_menu_cmds/content_aware_scale.rs rename to crates/engine/src/cmd/edit_menu_cmds/content_aware_scale.rs diff --git a/crates/engine/src/edit_menu_cmds/fade.rs b/crates/engine/src/cmd/edit_menu_cmds/fade.rs similarity index 100% rename from crates/engine/src/edit_menu_cmds/fade.rs rename to crates/engine/src/cmd/edit_menu_cmds/fade.rs diff --git a/crates/engine/src/edit_menu_cmds/find_replace.rs b/crates/engine/src/cmd/edit_menu_cmds/find_replace.rs similarity index 100% rename from crates/engine/src/edit_menu_cmds/find_replace.rs rename to crates/engine/src/cmd/edit_menu_cmds/find_replace.rs diff --git a/crates/engine/src/edit_menu_cmds/presets.rs b/crates/engine/src/cmd/edit_menu_cmds/presets.rs similarity index 100% rename from crates/engine/src/edit_menu_cmds/presets.rs rename to crates/engine/src/cmd/edit_menu_cmds/presets.rs diff --git a/crates/engine/src/edit_menu_cmds/purge.rs b/crates/engine/src/cmd/edit_menu_cmds/purge.rs similarity index 100% rename from crates/engine/src/edit_menu_cmds/purge.rs rename to crates/engine/src/cmd/edit_menu_cmds/purge.rs diff --git a/crates/engine/src/edit_menu_cmds/tests.rs b/crates/engine/src/cmd/edit_menu_cmds/tests.rs similarity index 100% rename from crates/engine/src/edit_menu_cmds/tests.rs rename to crates/engine/src/cmd/edit_menu_cmds/tests.rs diff --git a/crates/engine/src/eraser_cmds.rs b/crates/engine/src/cmd/eraser_cmds.rs similarity index 100% rename from crates/engine/src/eraser_cmds.rs rename to crates/engine/src/cmd/eraser_cmds.rs diff --git a/crates/engine/src/eraser_cmds/tests.rs b/crates/engine/src/cmd/eraser_cmds/tests.rs similarity index 100% rename from crates/engine/src/eraser_cmds/tests.rs rename to crates/engine/src/cmd/eraser_cmds/tests.rs diff --git a/crates/engine/src/export_preset_cmds.rs b/crates/engine/src/cmd/export_preset_cmds.rs similarity index 100% rename from crates/engine/src/export_preset_cmds.rs rename to crates/engine/src/cmd/export_preset_cmds.rs diff --git a/crates/engine/src/exr_cmds.rs b/crates/engine/src/cmd/exr_cmds.rs similarity index 100% rename from crates/engine/src/exr_cmds.rs rename to crates/engine/src/cmd/exr_cmds.rs diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/cmd/extra_cmds.rs similarity index 100% rename from crates/engine/src/extra_cmds.rs rename to crates/engine/src/cmd/extra_cmds.rs diff --git a/crates/engine/src/extra_cmds/tests.rs b/crates/engine/src/cmd/extra_cmds/tests.rs similarity index 100% rename from crates/engine/src/extra_cmds/tests.rs rename to crates/engine/src/cmd/extra_cmds/tests.rs diff --git a/crates/engine/src/face_cmds.rs b/crates/engine/src/cmd/face_cmds.rs similarity index 100% rename from crates/engine/src/face_cmds.rs rename to crates/engine/src/cmd/face_cmds.rs diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs similarity index 100% rename from crates/engine/src/file_cmds.rs rename to crates/engine/src/cmd/file_cmds.rs diff --git a/crates/engine/src/file_cmds/batch_naming.rs b/crates/engine/src/cmd/file_cmds/batch_naming.rs similarity index 100% rename from crates/engine/src/file_cmds/batch_naming.rs rename to crates/engine/src/cmd/file_cmds/batch_naming.rs diff --git a/crates/engine/src/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs similarity index 100% rename from crates/engine/src/file_cmds/batch_run.rs rename to crates/engine/src/cmd/file_cmds/batch_run.rs diff --git a/crates/engine/src/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs similarity index 100% rename from crates/engine/src/file_cmds/export.rs rename to crates/engine/src/cmd/file_cmds/export.rs diff --git a/crates/engine/src/file_cmds/info.rs b/crates/engine/src/cmd/file_cmds/info.rs similarity index 100% rename from crates/engine/src/file_cmds/info.rs rename to crates/engine/src/cmd/file_cmds/info.rs diff --git a/crates/engine/src/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs similarity index 100% rename from crates/engine/src/file_cmds/open.rs rename to crates/engine/src/cmd/file_cmds/open.rs diff --git a/crates/engine/src/file_cmds/paths.rs b/crates/engine/src/cmd/file_cmds/paths.rs similarity index 100% rename from crates/engine/src/file_cmds/paths.rs rename to crates/engine/src/cmd/file_cmds/paths.rs diff --git a/crates/engine/src/file_cmds/processing.rs b/crates/engine/src/cmd/file_cmds/processing.rs similarity index 100% rename from crates/engine/src/file_cmds/processing.rs rename to crates/engine/src/cmd/file_cmds/processing.rs diff --git a/crates/engine/src/file_cmds/save.rs b/crates/engine/src/cmd/file_cmds/save.rs similarity index 100% rename from crates/engine/src/file_cmds/save.rs rename to crates/engine/src/cmd/file_cmds/save.rs diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs similarity index 100% rename from crates/engine/src/file_cmds/tests.rs rename to crates/engine/src/cmd/file_cmds/tests.rs diff --git a/crates/engine/src/fill_cmds.rs b/crates/engine/src/cmd/fill_cmds.rs similarity index 100% rename from crates/engine/src/fill_cmds.rs rename to crates/engine/src/cmd/fill_cmds.rs diff --git a/crates/engine/src/fill_cmds/tests.rs b/crates/engine/src/cmd/fill_cmds/tests.rs similarity index 100% rename from crates/engine/src/fill_cmds/tests.rs rename to crates/engine/src/cmd/fill_cmds/tests.rs diff --git a/crates/engine/src/fill_key_cmds.rs b/crates/engine/src/cmd/fill_key_cmds.rs similarity index 100% rename from crates/engine/src/fill_key_cmds.rs rename to crates/engine/src/cmd/fill_key_cmds.rs diff --git a/crates/engine/src/float_cmds.rs b/crates/engine/src/cmd/float_cmds.rs similarity index 100% rename from crates/engine/src/float_cmds.rs rename to crates/engine/src/cmd/float_cmds.rs diff --git a/crates/engine/src/float_cmds/tests.rs b/crates/engine/src/cmd/float_cmds/tests.rs similarity index 100% rename from crates/engine/src/float_cmds/tests.rs rename to crates/engine/src/cmd/float_cmds/tests.rs diff --git a/crates/engine/src/frame_cmds.rs b/crates/engine/src/cmd/frame_cmds.rs similarity index 100% rename from crates/engine/src/frame_cmds.rs rename to crates/engine/src/cmd/frame_cmds.rs diff --git a/crates/engine/src/fx_view_cmds.rs b/crates/engine/src/cmd/fx_view_cmds.rs similarity index 100% rename from crates/engine/src/fx_view_cmds.rs rename to crates/engine/src/cmd/fx_view_cmds.rs diff --git a/crates/engine/src/fx_visibility_cmds.rs b/crates/engine/src/cmd/fx_visibility_cmds.rs similarity index 100% rename from crates/engine/src/fx_visibility_cmds.rs rename to crates/engine/src/cmd/fx_visibility_cmds.rs diff --git a/crates/engine/src/gallery_cmds.rs b/crates/engine/src/cmd/gallery_cmds.rs similarity index 100% rename from crates/engine/src/gallery_cmds.rs rename to crates/engine/src/cmd/gallery_cmds.rs diff --git a/crates/engine/src/gallery_cmds/tests.rs b/crates/engine/src/cmd/gallery_cmds/tests.rs similarity index 100% rename from crates/engine/src/gallery_cmds/tests.rs rename to crates/engine/src/cmd/gallery_cmds/tests.rs diff --git a/crates/engine/src/gradient_fill_cmds.rs b/crates/engine/src/cmd/gradient_fill_cmds.rs similarity index 100% rename from crates/engine/src/gradient_fill_cmds.rs rename to crates/engine/src/cmd/gradient_fill_cmds.rs diff --git a/crates/engine/src/gradient_fill_cmds/tests.rs b/crates/engine/src/cmd/gradient_fill_cmds/tests.rs similarity index 100% rename from crates/engine/src/gradient_fill_cmds/tests.rs rename to crates/engine/src/cmd/gradient_fill_cmds/tests.rs diff --git a/crates/engine/src/group_view_cmds.rs b/crates/engine/src/cmd/group_view_cmds.rs similarity index 100% rename from crates/engine/src/group_view_cmds.rs rename to crates/engine/src/cmd/group_view_cmds.rs diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/cmd/history_cmds.rs similarity index 100% rename from crates/engine/src/history_cmds.rs rename to crates/engine/src/cmd/history_cmds.rs diff --git a/crates/engine/src/history_menu_cmds.rs b/crates/engine/src/cmd/history_menu_cmds.rs similarity index 100% rename from crates/engine/src/history_menu_cmds.rs rename to crates/engine/src/cmd/history_menu_cmds.rs diff --git a/crates/engine/src/history_select_cmds.rs b/crates/engine/src/cmd/history_select_cmds.rs similarity index 100% rename from crates/engine/src/history_select_cmds.rs rename to crates/engine/src/cmd/history_select_cmds.rs diff --git a/crates/engine/src/history_source_cmds.rs b/crates/engine/src/cmd/history_source_cmds.rs similarity index 100% rename from crates/engine/src/history_source_cmds.rs rename to crates/engine/src/cmd/history_source_cmds.rs diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs similarity index 100% rename from crates/engine/src/image_cmds.rs rename to crates/engine/src/cmd/image_cmds.rs diff --git a/crates/engine/src/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs similarity index 100% rename from crates/engine/src/image_cmds/tests.rs rename to crates/engine/src/cmd/image_cmds/tests.rs diff --git a/crates/engine/src/layer_copy_cmds.rs b/crates/engine/src/cmd/layer_copy_cmds.rs similarity index 100% rename from crates/engine/src/layer_copy_cmds.rs rename to crates/engine/src/cmd/layer_copy_cmds.rs diff --git a/crates/engine/src/layer_copy_cmds/tests.rs b/crates/engine/src/cmd/layer_copy_cmds/tests.rs similarity index 100% rename from crates/engine/src/layer_copy_cmds/tests.rs rename to crates/engine/src/cmd/layer_copy_cmds/tests.rs diff --git a/crates/engine/src/layer_label_cmds.rs b/crates/engine/src/cmd/layer_label_cmds.rs similarity index 100% rename from crates/engine/src/layer_label_cmds.rs rename to crates/engine/src/cmd/layer_label_cmds.rs diff --git a/crates/engine/src/layer_label_cmds/tests.rs b/crates/engine/src/cmd/layer_label_cmds/tests.rs similarity index 100% rename from crates/engine/src/layer_label_cmds/tests.rs rename to crates/engine/src/cmd/layer_label_cmds/tests.rs diff --git a/crates/engine/src/layer_list_cmds.rs b/crates/engine/src/cmd/layer_list_cmds.rs similarity index 100% rename from crates/engine/src/layer_list_cmds.rs rename to crates/engine/src/cmd/layer_list_cmds.rs diff --git a/crates/engine/src/layer_mask_props_cmds.rs b/crates/engine/src/cmd/layer_mask_props_cmds.rs similarity index 100% rename from crates/engine/src/layer_mask_props_cmds.rs rename to crates/engine/src/cmd/layer_mask_props_cmds.rs diff --git a/crates/engine/src/layer_mask_props_cmds/tests.rs b/crates/engine/src/cmd/layer_mask_props_cmds/tests.rs similarity index 100% rename from crates/engine/src/layer_mask_props_cmds/tests.rs rename to crates/engine/src/cmd/layer_mask_props_cmds/tests.rs diff --git a/crates/engine/src/layer_menu_cmds.rs b/crates/engine/src/cmd/layer_menu_cmds.rs similarity index 100% rename from crates/engine/src/layer_menu_cmds.rs rename to crates/engine/src/cmd/layer_menu_cmds.rs diff --git a/crates/engine/src/layer_menu_cmds/tests.rs b/crates/engine/src/cmd/layer_menu_cmds/tests.rs similarity index 100% rename from crates/engine/src/layer_menu_cmds/tests.rs rename to crates/engine/src/cmd/layer_menu_cmds/tests.rs diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/cmd/layer_multi_cmds.rs similarity index 100% rename from crates/engine/src/layer_multi_cmds.rs rename to crates/engine/src/cmd/layer_multi_cmds.rs diff --git a/crates/engine/src/layer_multi_cmds/align.rs b/crates/engine/src/cmd/layer_multi_cmds/align.rs similarity index 100% rename from crates/engine/src/layer_multi_cmds/align.rs rename to crates/engine/src/cmd/layer_multi_cmds/align.rs diff --git a/crates/engine/src/layer_multi_cmds/damage.rs b/crates/engine/src/cmd/layer_multi_cmds/damage.rs similarity index 100% rename from crates/engine/src/layer_multi_cmds/damage.rs rename to crates/engine/src/cmd/layer_multi_cmds/damage.rs diff --git a/crates/engine/src/layer_multi_cmds/layers_panel_parity_tests.rs b/crates/engine/src/cmd/layer_multi_cmds/layers_panel_parity_tests.rs similarity index 100% rename from crates/engine/src/layer_multi_cmds/layers_panel_parity_tests.rs rename to crates/engine/src/cmd/layer_multi_cmds/layers_panel_parity_tests.rs diff --git a/crates/engine/src/layer_multi_cmds/moves.rs b/crates/engine/src/cmd/layer_multi_cmds/moves.rs similarity index 100% rename from crates/engine/src/layer_multi_cmds/moves.rs rename to crates/engine/src/cmd/layer_multi_cmds/moves.rs diff --git a/crates/engine/src/layer_multi_cmds/selection.rs b/crates/engine/src/cmd/layer_multi_cmds/selection.rs similarity index 100% rename from crates/engine/src/layer_multi_cmds/selection.rs rename to crates/engine/src/cmd/layer_multi_cmds/selection.rs diff --git a/crates/engine/src/layer_multi_cmds/structure.rs b/crates/engine/src/cmd/layer_multi_cmds/structure.rs similarity index 100% rename from crates/engine/src/layer_multi_cmds/structure.rs rename to crates/engine/src/cmd/layer_multi_cmds/structure.rs diff --git a/crates/engine/src/layer_multi_cmds/tests.rs b/crates/engine/src/cmd/layer_multi_cmds/tests.rs similarity index 100% rename from crates/engine/src/layer_multi_cmds/tests.rs rename to crates/engine/src/cmd/layer_multi_cmds/tests.rs diff --git a/crates/engine/src/layer_nav_cmds.rs b/crates/engine/src/cmd/layer_nav_cmds.rs similarity index 100% rename from crates/engine/src/layer_nav_cmds.rs rename to crates/engine/src/cmd/layer_nav_cmds.rs diff --git a/crates/engine/src/layer_xmp_cmds.rs b/crates/engine/src/cmd/layer_xmp_cmds.rs similarity index 100% rename from crates/engine/src/layer_xmp_cmds.rs rename to crates/engine/src/cmd/layer_xmp_cmds.rs diff --git a/crates/engine/src/layer_xmp_cmds/tests.rs b/crates/engine/src/cmd/layer_xmp_cmds/tests.rs similarity index 100% rename from crates/engine/src/layer_xmp_cmds/tests.rs rename to crates/engine/src/cmd/layer_xmp_cmds/tests.rs diff --git a/crates/engine/src/lens_cmds.rs b/crates/engine/src/cmd/lens_cmds.rs similarity index 100% rename from crates/engine/src/lens_cmds.rs rename to crates/engine/src/cmd/lens_cmds.rs diff --git a/crates/engine/src/magnetic_cmds.rs b/crates/engine/src/cmd/magnetic_cmds.rs similarity index 100% rename from crates/engine/src/magnetic_cmds.rs rename to crates/engine/src/cmd/magnetic_cmds.rs diff --git a/crates/engine/src/magnetic_cmds/tests.rs b/crates/engine/src/cmd/magnetic_cmds/tests.rs similarity index 100% rename from crates/engine/src/magnetic_cmds/tests.rs rename to crates/engine/src/cmd/magnetic_cmds/tests.rs diff --git a/crates/engine/src/mask_view_cmds.rs b/crates/engine/src/cmd/mask_view_cmds.rs similarity index 100% rename from crates/engine/src/mask_view_cmds.rs rename to crates/engine/src/cmd/mask_view_cmds.rs diff --git a/crates/engine/src/mask_view_cmds/tests.rs b/crates/engine/src/cmd/mask_view_cmds/tests.rs similarity index 100% rename from crates/engine/src/mask_view_cmds/tests.rs rename to crates/engine/src/cmd/mask_view_cmds/tests.rs diff --git a/crates/engine/src/migrate_cmds.rs b/crates/engine/src/cmd/migrate_cmds.rs similarity index 100% rename from crates/engine/src/migrate_cmds.rs rename to crates/engine/src/cmd/migrate_cmds.rs diff --git a/crates/engine/src/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs similarity index 100% rename from crates/engine/src/mode_cmds.rs rename to crates/engine/src/cmd/mode_cmds.rs diff --git a/crates/engine/src/mode_cmds/tests.rs b/crates/engine/src/cmd/mode_cmds/tests.rs similarity index 100% rename from crates/engine/src/mode_cmds/tests.rs rename to crates/engine/src/cmd/mode_cmds/tests.rs diff --git a/crates/engine/src/multichannel_cmds.rs b/crates/engine/src/cmd/multichannel_cmds.rs similarity index 100% rename from crates/engine/src/multichannel_cmds.rs rename to crates/engine/src/cmd/multichannel_cmds.rs diff --git a/crates/engine/src/multichannel_cmds/tests.rs b/crates/engine/src/cmd/multichannel_cmds/tests.rs similarity index 100% rename from crates/engine/src/multichannel_cmds/tests.rs rename to crates/engine/src/cmd/multichannel_cmds/tests.rs diff --git a/crates/engine/src/notes_cmds.rs b/crates/engine/src/cmd/notes_cmds.rs similarity index 100% rename from crates/engine/src/notes_cmds.rs rename to crates/engine/src/cmd/notes_cmds.rs diff --git a/crates/engine/src/paint_cmds.rs b/crates/engine/src/cmd/paint_cmds.rs similarity index 100% rename from crates/engine/src/paint_cmds.rs rename to crates/engine/src/cmd/paint_cmds.rs diff --git a/crates/engine/src/paint_cmds/tests.rs b/crates/engine/src/cmd/paint_cmds/tests.rs similarity index 100% rename from crates/engine/src/paint_cmds/tests.rs rename to crates/engine/src/cmd/paint_cmds/tests.rs diff --git a/crates/engine/src/path_edit_cmds.rs b/crates/engine/src/cmd/path_edit_cmds.rs similarity index 100% rename from crates/engine/src/path_edit_cmds.rs rename to crates/engine/src/cmd/path_edit_cmds.rs diff --git a/crates/engine/src/pattern_cmds.rs b/crates/engine/src/cmd/pattern_cmds.rs similarity index 100% rename from crates/engine/src/pattern_cmds.rs rename to crates/engine/src/cmd/pattern_cmds.rs diff --git a/crates/engine/src/pattern_fill_cmds.rs b/crates/engine/src/cmd/pattern_fill_cmds.rs similarity index 100% rename from crates/engine/src/pattern_fill_cmds.rs rename to crates/engine/src/cmd/pattern_fill_cmds.rs diff --git a/crates/engine/src/perspective_crop_cmds.rs b/crates/engine/src/cmd/perspective_crop_cmds.rs similarity index 100% rename from crates/engine/src/perspective_crop_cmds.rs rename to crates/engine/src/cmd/perspective_crop_cmds.rs diff --git a/crates/engine/src/photo_cmds.rs b/crates/engine/src/cmd/photo_cmds.rs similarity index 100% rename from crates/engine/src/photo_cmds.rs rename to crates/engine/src/cmd/photo_cmds.rs diff --git a/crates/engine/src/photo_cmds/tests.rs b/crates/engine/src/cmd/photo_cmds/tests.rs similarity index 100% rename from crates/engine/src/photo_cmds/tests.rs rename to crates/engine/src/cmd/photo_cmds/tests.rs diff --git a/crates/engine/src/pick_cmds.rs b/crates/engine/src/cmd/pick_cmds.rs similarity index 100% rename from crates/engine/src/pick_cmds.rs rename to crates/engine/src/cmd/pick_cmds.rs diff --git a/crates/engine/src/plugin_cmds.rs b/crates/engine/src/cmd/plugin_cmds.rs similarity index 100% rename from crates/engine/src/plugin_cmds.rs rename to crates/engine/src/cmd/plugin_cmds.rs diff --git a/crates/engine/src/plugin_cmds/tests.rs b/crates/engine/src/cmd/plugin_cmds/tests.rs similarity index 99% rename from crates/engine/src/plugin_cmds/tests.rs rename to crates/engine/src/cmd/plugin_cmds/tests.rs index 7c6ed635aa..5f93ce7909 100644 --- a/crates/engine/src/plugin_cmds/tests.rs +++ b/crates/engine/src/cmd/plugin_cmds/tests.rs @@ -2,7 +2,7 @@ use super::*; use photocraft_geom::Rect; /// The example Invert plug-in, built from `examples/plugins/invert-rs`. -const INVERT: &[u8] = include_bytes!("../../../plugins/tests/fixtures/invert.wasm"); +const INVERT: &[u8] = include_bytes!("../../../../plugins/tests/fixtures/invert.wasm"); const INVERT_ID: &str = "org.photocraft.example.invert"; fn b64(b: &[u8]) -> String { diff --git a/crates/engine/src/preset_import_cmds.rs b/crates/engine/src/cmd/preset_import_cmds.rs similarity index 100% rename from crates/engine/src/preset_import_cmds.rs rename to crates/engine/src/cmd/preset_import_cmds.rs diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/cmd/print_cmds.rs similarity index 100% rename from crates/engine/src/print_cmds.rs rename to crates/engine/src/cmd/print_cmds.rs diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/cmd/print_cmds/tests.rs similarity index 100% rename from crates/engine/src/print_cmds/tests.rs rename to crates/engine/src/cmd/print_cmds/tests.rs diff --git a/crates/engine/src/print_cmds/windows_marks.rs b/crates/engine/src/cmd/print_cmds/windows_marks.rs similarity index 100% rename from crates/engine/src/print_cmds/windows_marks.rs rename to crates/engine/src/cmd/print_cmds/windows_marks.rs diff --git a/crates/engine/src/rasterize_style_cmds.rs b/crates/engine/src/cmd/rasterize_style_cmds.rs similarity index 100% rename from crates/engine/src/rasterize_style_cmds.rs rename to crates/engine/src/cmd/rasterize_style_cmds.rs diff --git a/crates/engine/src/rasterize_style_cmds/tests.rs b/crates/engine/src/cmd/rasterize_style_cmds/tests.rs similarity index 100% rename from crates/engine/src/rasterize_style_cmds/tests.rs rename to crates/engine/src/cmd/rasterize_style_cmds/tests.rs diff --git a/crates/engine/src/redeye_cmds.rs b/crates/engine/src/cmd/redeye_cmds.rs similarity index 100% rename from crates/engine/src/redeye_cmds.rs rename to crates/engine/src/cmd/redeye_cmds.rs diff --git a/crates/engine/src/render_cmds.rs b/crates/engine/src/cmd/render_cmds.rs similarity index 100% rename from crates/engine/src/render_cmds.rs rename to crates/engine/src/cmd/render_cmds.rs diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs similarity index 100% rename from crates/engine/src/retouch_cmds.rs rename to crates/engine/src/cmd/retouch_cmds.rs diff --git a/crates/engine/src/retouch_cmds/art_history.rs b/crates/engine/src/cmd/retouch_cmds/art_history.rs similarity index 100% rename from crates/engine/src/retouch_cmds/art_history.rs rename to crates/engine/src/cmd/retouch_cmds/art_history.rs diff --git a/crates/engine/src/retouch_cmds/clone.rs b/crates/engine/src/cmd/retouch_cmds/clone.rs similarity index 100% rename from crates/engine/src/retouch_cmds/clone.rs rename to crates/engine/src/cmd/retouch_cmds/clone.rs diff --git a/crates/engine/src/retouch_cmds/content_aware_move.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs similarity index 100% rename from crates/engine/src/retouch_cmds/content_aware_move.rs rename to crates/engine/src/cmd/retouch_cmds/content_aware_move.rs diff --git a/crates/engine/src/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs similarity index 100% rename from crates/engine/src/retouch_cmds/dab.rs rename to crates/engine/src/cmd/retouch_cmds/dab.rs diff --git a/crates/engine/src/retouch_cmds/heal.rs b/crates/engine/src/cmd/retouch_cmds/heal.rs similarity index 100% rename from crates/engine/src/retouch_cmds/heal.rs rename to crates/engine/src/cmd/retouch_cmds/heal.rs diff --git a/crates/engine/src/retouch_cmds/patch.rs b/crates/engine/src/cmd/retouch_cmds/patch.rs similarity index 100% rename from crates/engine/src/retouch_cmds/patch.rs rename to crates/engine/src/cmd/retouch_cmds/patch.rs diff --git a/crates/engine/src/retouch_cmds/pattern_stamp.rs b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs similarity index 100% rename from crates/engine/src/retouch_cmds/pattern_stamp.rs rename to crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs diff --git a/crates/engine/src/retouch_cmds/periodic.rs b/crates/engine/src/cmd/retouch_cmds/periodic.rs similarity index 100% rename from crates/engine/src/retouch_cmds/periodic.rs rename to crates/engine/src/cmd/retouch_cmds/periodic.rs diff --git a/crates/engine/src/retouch_cmds/remove.rs b/crates/engine/src/cmd/retouch_cmds/remove.rs similarity index 100% rename from crates/engine/src/retouch_cmds/remove.rs rename to crates/engine/src/cmd/retouch_cmds/remove.rs diff --git a/crates/engine/src/retouch_cmds/sampling.rs b/crates/engine/src/cmd/retouch_cmds/sampling.rs similarity index 100% rename from crates/engine/src/retouch_cmds/sampling.rs rename to crates/engine/src/cmd/retouch_cmds/sampling.rs diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs similarity index 100% rename from crates/engine/src/retouch_cmds/tests.rs rename to crates/engine/src/cmd/retouch_cmds/tests.rs diff --git a/crates/engine/src/sample_cmds.rs b/crates/engine/src/cmd/sample_cmds.rs similarity index 100% rename from crates/engine/src/sample_cmds.rs rename to crates/engine/src/cmd/sample_cmds.rs diff --git a/crates/engine/src/sampler_cmds.rs b/crates/engine/src/cmd/sampler_cmds.rs similarity index 100% rename from crates/engine/src/sampler_cmds.rs rename to crates/engine/src/cmd/sampler_cmds.rs diff --git a/crates/engine/src/sampler_cmds/tests.rs b/crates/engine/src/cmd/sampler_cmds/tests.rs similarity index 100% rename from crates/engine/src/sampler_cmds/tests.rs rename to crates/engine/src/cmd/sampler_cmds/tests.rs diff --git a/crates/engine/src/select_extra_cmds.rs b/crates/engine/src/cmd/select_extra_cmds.rs similarity index 100% rename from crates/engine/src/select_extra_cmds.rs rename to crates/engine/src/cmd/select_extra_cmds.rs diff --git a/crates/engine/src/selection_cmds.rs b/crates/engine/src/cmd/selection_cmds.rs similarity index 100% rename from crates/engine/src/selection_cmds.rs rename to crates/engine/src/cmd/selection_cmds.rs diff --git a/crates/engine/src/selection_cmds/tests.rs b/crates/engine/src/cmd/selection_cmds/tests.rs similarity index 100% rename from crates/engine/src/selection_cmds/tests.rs rename to crates/engine/src/cmd/selection_cmds/tests.rs diff --git a/crates/engine/src/slice_cmds.rs b/crates/engine/src/cmd/slice_cmds.rs similarity index 100% rename from crates/engine/src/slice_cmds.rs rename to crates/engine/src/cmd/slice_cmds.rs diff --git a/crates/engine/src/slice_cmds/tests.rs b/crates/engine/src/cmd/slice_cmds/tests.rs similarity index 100% rename from crates/engine/src/slice_cmds/tests.rs rename to crates/engine/src/cmd/slice_cmds/tests.rs diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/cmd/smart_cmds.rs similarity index 100% rename from crates/engine/src/smart_cmds.rs rename to crates/engine/src/cmd/smart_cmds.rs diff --git a/crates/engine/src/smart_cmds/contents.rs b/crates/engine/src/cmd/smart_cmds/contents.rs similarity index 100% rename from crates/engine/src/smart_cmds/contents.rs rename to crates/engine/src/cmd/smart_cmds/contents.rs diff --git a/crates/engine/src/smart_cmds/filters.rs b/crates/engine/src/cmd/smart_cmds/filters.rs similarity index 100% rename from crates/engine/src/smart_cmds/filters.rs rename to crates/engine/src/cmd/smart_cmds/filters.rs diff --git a/crates/engine/src/smart_cmds/placing.rs b/crates/engine/src/cmd/smart_cmds/placing.rs similarity index 100% rename from crates/engine/src/smart_cmds/placing.rs rename to crates/engine/src/cmd/smart_cmds/placing.rs diff --git a/crates/engine/src/smart_cmds/rendering.rs b/crates/engine/src/cmd/smart_cmds/rendering.rs similarity index 100% rename from crates/engine/src/smart_cmds/rendering.rs rename to crates/engine/src/cmd/smart_cmds/rendering.rs diff --git a/crates/engine/src/smart_cmds/source.rs b/crates/engine/src/cmd/smart_cmds/source.rs similarity index 100% rename from crates/engine/src/smart_cmds/source.rs rename to crates/engine/src/cmd/smart_cmds/source.rs diff --git a/crates/engine/src/smart_cmds/stack_cache.rs b/crates/engine/src/cmd/smart_cmds/stack_cache.rs similarity index 100% rename from crates/engine/src/smart_cmds/stack_cache.rs rename to crates/engine/src/cmd/smart_cmds/stack_cache.rs diff --git a/crates/engine/src/smart_cmds/tests.rs b/crates/engine/src/cmd/smart_cmds/tests.rs similarity index 100% rename from crates/engine/src/smart_cmds/tests.rs rename to crates/engine/src/cmd/smart_cmds/tests.rs diff --git a/crates/engine/src/smart_cmds/tests/filter_mask_paint.rs b/crates/engine/src/cmd/smart_cmds/tests/filter_mask_paint.rs similarity index 100% rename from crates/engine/src/smart_cmds/tests/filter_mask_paint.rs rename to crates/engine/src/cmd/smart_cmds/tests/filter_mask_paint.rs diff --git a/crates/engine/src/smart_cmds/tests/selection.rs b/crates/engine/src/cmd/smart_cmds/tests/selection.rs similarity index 100% rename from crates/engine/src/smart_cmds/tests/selection.rs rename to crates/engine/src/cmd/smart_cmds/tests/selection.rs diff --git a/crates/engine/src/smart_cmds/tests/stack_cache.rs b/crates/engine/src/cmd/smart_cmds/tests/stack_cache.rs similarity index 100% rename from crates/engine/src/smart_cmds/tests/stack_cache.rs rename to crates/engine/src/cmd/smart_cmds/tests/stack_cache.rs diff --git a/crates/engine/src/smart_cmds/unpack.rs b/crates/engine/src/cmd/smart_cmds/unpack.rs similarity index 100% rename from crates/engine/src/smart_cmds/unpack.rs rename to crates/engine/src/cmd/smart_cmds/unpack.rs diff --git a/crates/engine/src/smartselect_cmds.rs b/crates/engine/src/cmd/smartselect_cmds.rs similarity index 100% rename from crates/engine/src/smartselect_cmds.rs rename to crates/engine/src/cmd/smartselect_cmds.rs diff --git a/crates/engine/src/smartselect_cmds/tests.rs b/crates/engine/src/cmd/smartselect_cmds/tests.rs similarity index 100% rename from crates/engine/src/smartselect_cmds/tests.rs rename to crates/engine/src/cmd/smartselect_cmds/tests.rs diff --git a/crates/engine/src/solid_fill_cmds.rs b/crates/engine/src/cmd/solid_fill_cmds.rs similarity index 100% rename from crates/engine/src/solid_fill_cmds.rs rename to crates/engine/src/cmd/solid_fill_cmds.rs diff --git a/crates/engine/src/stamp_cmds.rs b/crates/engine/src/cmd/stamp_cmds.rs similarity index 100% rename from crates/engine/src/stamp_cmds.rs rename to crates/engine/src/cmd/stamp_cmds.rs diff --git a/crates/engine/src/style_asl_cmds.rs b/crates/engine/src/cmd/style_asl_cmds.rs similarity index 100% rename from crates/engine/src/style_asl_cmds.rs rename to crates/engine/src/cmd/style_asl_cmds.rs diff --git a/crates/engine/src/swatch_cmds.rs b/crates/engine/src/cmd/swatch_cmds.rs similarity index 100% rename from crates/engine/src/swatch_cmds.rs rename to crates/engine/src/cmd/swatch_cmds.rs diff --git a/crates/engine/src/swatch_cmds/tests.rs b/crates/engine/src/cmd/swatch_cmds/tests.rs similarity index 100% rename from crates/engine/src/swatch_cmds/tests.rs rename to crates/engine/src/cmd/swatch_cmds/tests.rs diff --git a/crates/engine/src/symmetry_cmds.rs b/crates/engine/src/cmd/symmetry_cmds.rs similarity index 100% rename from crates/engine/src/symmetry_cmds.rs rename to crates/engine/src/cmd/symmetry_cmds.rs diff --git a/crates/engine/src/symmetry_cmds/preset_tests.rs b/crates/engine/src/cmd/symmetry_cmds/preset_tests.rs similarity index 100% rename from crates/engine/src/symmetry_cmds/preset_tests.rs rename to crates/engine/src/cmd/symmetry_cmds/preset_tests.rs diff --git a/crates/engine/src/timeline_cmds.rs b/crates/engine/src/cmd/timeline_cmds.rs similarity index 100% rename from crates/engine/src/timeline_cmds.rs rename to crates/engine/src/cmd/timeline_cmds.rs diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/cmd/transform_cmds.rs similarity index 100% rename from crates/engine/src/transform_cmds.rs rename to crates/engine/src/cmd/transform_cmds.rs diff --git a/crates/engine/src/transform_cmds/tests.rs b/crates/engine/src/cmd/transform_cmds/tests.rs similarity index 100% rename from crates/engine/src/transform_cmds/tests.rs rename to crates/engine/src/cmd/transform_cmds/tests.rs diff --git a/crates/engine/src/trap_cmds.rs b/crates/engine/src/cmd/trap_cmds.rs similarity index 100% rename from crates/engine/src/trap_cmds.rs rename to crates/engine/src/cmd/trap_cmds.rs diff --git a/crates/engine/src/type_area_cmds.rs b/crates/engine/src/cmd/type_area_cmds.rs similarity index 100% rename from crates/engine/src/type_area_cmds.rs rename to crates/engine/src/cmd/type_area_cmds.rs diff --git a/crates/engine/src/type_area_cmds/tests.rs b/crates/engine/src/cmd/type_area_cmds/tests.rs similarity index 100% rename from crates/engine/src/type_area_cmds/tests.rs rename to crates/engine/src/cmd/type_area_cmds/tests.rs diff --git a/crates/engine/src/type_caret_cmds.rs b/crates/engine/src/cmd/type_caret_cmds.rs similarity index 100% rename from crates/engine/src/type_caret_cmds.rs rename to crates/engine/src/cmd/type_caret_cmds.rs diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/cmd/type_cmds.rs similarity index 100% rename from crates/engine/src/type_cmds.rs rename to crates/engine/src/cmd/type_cmds.rs diff --git a/crates/engine/src/type_cmds/tests.rs b/crates/engine/src/cmd/type_cmds/tests.rs similarity index 100% rename from crates/engine/src/type_cmds/tests.rs rename to crates/engine/src/cmd/type_cmds/tests.rs diff --git a/crates/engine/src/type_extra_cmds.rs b/crates/engine/src/cmd/type_extra_cmds.rs similarity index 100% rename from crates/engine/src/type_extra_cmds.rs rename to crates/engine/src/cmd/type_extra_cmds.rs diff --git a/crates/engine/src/type_extra_cmds/tests.rs b/crates/engine/src/cmd/type_extra_cmds/tests.rs similarity index 100% rename from crates/engine/src/type_extra_cmds/tests.rs rename to crates/engine/src/cmd/type_extra_cmds/tests.rs diff --git a/crates/engine/src/type_mask_cmds.rs b/crates/engine/src/cmd/type_mask_cmds.rs similarity index 100% rename from crates/engine/src/type_mask_cmds.rs rename to crates/engine/src/cmd/type_mask_cmds.rs diff --git a/crates/engine/src/type_spell_cmds.rs b/crates/engine/src/cmd/type_spell_cmds.rs similarity index 100% rename from crates/engine/src/type_spell_cmds.rs rename to crates/engine/src/cmd/type_spell_cmds.rs diff --git a/crates/engine/src/type_styles_cmds.rs b/crates/engine/src/cmd/type_styles_cmds.rs similarity index 100% rename from crates/engine/src/type_styles_cmds.rs rename to crates/engine/src/cmd/type_styles_cmds.rs diff --git a/crates/engine/src/type_styles_cmds/tests.rs b/crates/engine/src/cmd/type_styles_cmds/tests.rs similarity index 100% rename from crates/engine/src/type_styles_cmds/tests.rs rename to crates/engine/src/cmd/type_styles_cmds/tests.rs diff --git a/crates/engine/src/updates_cmds.rs b/crates/engine/src/cmd/updates_cmds.rs similarity index 100% rename from crates/engine/src/updates_cmds.rs rename to crates/engine/src/cmd/updates_cmds.rs diff --git a/crates/engine/src/variables_cmds.rs b/crates/engine/src/cmd/variables_cmds.rs similarity index 100% rename from crates/engine/src/variables_cmds.rs rename to crates/engine/src/cmd/variables_cmds.rs diff --git a/crates/engine/src/variables_cmds/tests.rs b/crates/engine/src/cmd/variables_cmds/tests.rs similarity index 100% rename from crates/engine/src/variables_cmds/tests.rs rename to crates/engine/src/cmd/variables_cmds/tests.rs diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/cmd/vector_cmds.rs similarity index 100% rename from crates/engine/src/vector_cmds.rs rename to crates/engine/src/cmd/vector_cmds.rs diff --git a/crates/engine/src/vector_cmds/params.rs b/crates/engine/src/cmd/vector_cmds/params.rs similarity index 100% rename from crates/engine/src/vector_cmds/params.rs rename to crates/engine/src/cmd/vector_cmds/params.rs diff --git a/crates/engine/src/vector_cmds/paths.rs b/crates/engine/src/cmd/vector_cmds/paths.rs similarity index 100% rename from crates/engine/src/vector_cmds/paths.rs rename to crates/engine/src/cmd/vector_cmds/paths.rs diff --git a/crates/engine/src/vector_cmds/shape.rs b/crates/engine/src/cmd/vector_cmds/shape.rs similarity index 100% rename from crates/engine/src/vector_cmds/shape.rs rename to crates/engine/src/cmd/vector_cmds/shape.rs diff --git a/crates/engine/src/vector_cmds/tests.rs b/crates/engine/src/cmd/vector_cmds/tests.rs similarity index 100% rename from crates/engine/src/vector_cmds/tests.rs rename to crates/engine/src/cmd/vector_cmds/tests.rs diff --git a/crates/engine/src/vector_cmds/vector_mask.rs b/crates/engine/src/cmd/vector_cmds/vector_mask.rs similarity index 100% rename from crates/engine/src/vector_cmds/vector_mask.rs rename to crates/engine/src/cmd/vector_cmds/vector_mask.rs diff --git a/crates/engine/src/video_cmds.rs b/crates/engine/src/cmd/video_cmds.rs similarity index 100% rename from crates/engine/src/video_cmds.rs rename to crates/engine/src/cmd/video_cmds.rs diff --git a/crates/engine/src/video_cmds/tests.rs b/crates/engine/src/cmd/video_cmds/tests.rs similarity index 100% rename from crates/engine/src/video_cmds/tests.rs rename to crates/engine/src/cmd/video_cmds/tests.rs diff --git a/crates/engine/src/vp_cmds.rs b/crates/engine/src/cmd/vp_cmds.rs similarity index 100% rename from crates/engine/src/vp_cmds.rs rename to crates/engine/src/cmd/vp_cmds.rs diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/cmd/warp_cmds.rs similarity index 100% rename from crates/engine/src/warp_cmds.rs rename to crates/engine/src/cmd/warp_cmds.rs diff --git a/crates/engine/src/warp_cmds/tests.rs b/crates/engine/src/cmd/warp_cmds/tests.rs similarity index 100% rename from crates/engine/src/warp_cmds/tests.rs rename to crates/engine/src/cmd/warp_cmds/tests.rs diff --git a/crates/engine/src/web_cmds.rs b/crates/engine/src/cmd/web_cmds.rs similarity index 100% rename from crates/engine/src/web_cmds.rs rename to crates/engine/src/cmd/web_cmds.rs diff --git a/crates/engine/src/web_cmds/assets.rs b/crates/engine/src/cmd/web_cmds/assets.rs similarity index 100% rename from crates/engine/src/web_cmds/assets.rs rename to crates/engine/src/cmd/web_cmds/assets.rs diff --git a/crates/engine/src/web_cmds/color_table_tests.rs b/crates/engine/src/cmd/web_cmds/color_table_tests.rs similarity index 100% rename from crates/engine/src/web_cmds/color_table_tests.rs rename to crates/engine/src/cmd/web_cmds/color_table_tests.rs diff --git a/crates/engine/src/web_cmds/optimizer.rs b/crates/engine/src/cmd/web_cmds/optimizer.rs similarity index 100% rename from crates/engine/src/web_cmds/optimizer.rs rename to crates/engine/src/cmd/web_cmds/optimizer.rs diff --git a/crates/engine/src/web_cmds/quick.rs b/crates/engine/src/cmd/web_cmds/quick.rs similarity index 100% rename from crates/engine/src/web_cmds/quick.rs rename to crates/engine/src/cmd/web_cmds/quick.rs diff --git a/crates/engine/src/web_cmds/save_web.rs b/crates/engine/src/cmd/web_cmds/save_web.rs similarity index 100% rename from crates/engine/src/web_cmds/save_web.rs rename to crates/engine/src/cmd/web_cmds/save_web.rs diff --git a/crates/engine/src/web_cmds/settings.rs b/crates/engine/src/cmd/web_cmds/settings.rs similarity index 100% rename from crates/engine/src/web_cmds/settings.rs rename to crates/engine/src/cmd/web_cmds/settings.rs diff --git a/crates/engine/src/web_cmds/tests.rs b/crates/engine/src/cmd/web_cmds/tests.rs similarity index 100% rename from crates/engine/src/web_cmds/tests.rs rename to crates/engine/src/cmd/web_cmds/tests.rs diff --git a/crates/engine/src/wia_cmds.rs b/crates/engine/src/cmd/wia_cmds.rs similarity index 100% rename from crates/engine/src/wia_cmds.rs rename to crates/engine/src/cmd/wia_cmds.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1143583ebf..93e91922b6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -7,139 +7,38 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -pub mod actions_cmds; -pub mod actions_edit_cmds; -pub mod adjust_cmds; pub mod adjust_params; -pub mod align_cmds; mod allocation; -pub mod analysis_cmds; -pub mod artboard_cmds; -pub mod atn_cmds; -pub mod automate_cmds; -pub mod background_cmds; -pub mod brush_cmds; -pub mod brush_key_cmds; -pub mod brush_preset_cmds; pub mod build_info; mod canvas_geom; mod channel_clip; -pub mod channel_cmds; mod clip_group; -pub mod color_cmds; -pub mod color_to_alpha_cmds; -pub mod comps_cmds; -pub mod contour_lib_cmds; mod crop_fill; -pub mod cutout_cmds; pub mod display_color; -pub mod distort_cmds; pub mod doc_path; -pub mod document_preset_cmds; -pub mod edit_cmds; -pub mod edit_menu_cmds; -pub mod eraser_cmds; -pub mod export_preset_cmds; -pub mod exr_cmds; -pub mod extra_cmds; -pub mod face_cmds; -pub mod file_cmds; -pub mod fill_cmds; -pub mod fill_key_cmds; pub mod filters; pub mod filters_ext; -pub mod float_cmds; -mod frame_cmds; -pub mod fx_view_cmds; -pub mod fx_visibility_cmds; -pub mod gallery_cmds; -pub mod gradient_fill_cmds; -pub mod group_view_cmds; pub mod guide_layout; pub mod hidden_target; -pub mod history_cmds; -pub mod history_menu_cmds; -pub mod history_select_cmds; -pub mod history_source_cmds; -pub mod image_cmds; pub mod inspect; pub mod installed_profiles; pub mod jobs; pub mod kys; -pub mod layer_copy_cmds; -pub mod layer_label_cmds; -pub mod layer_list_cmds; -pub mod layer_mask_props_cmds; -pub mod layer_menu_cmds; -pub mod layer_multi_cmds; -pub mod layer_nav_cmds; pub mod layer_style; -pub mod layer_xmp_cmds; -pub mod lens_cmds; pub mod link_watch; -pub mod magnetic_cmds; -pub mod mask_view_cmds; -mod migrate_cmds; -pub mod mode_cmds; -pub mod multichannel_cmds; pub mod new_layer; -pub mod notes_cmds; -pub mod paint_cmds; mod param_check; -mod path_edit_cmds; -pub mod pattern_cmds; -pub mod pattern_fill_cmds; -pub mod perspective_crop_cmds; -pub mod photo_cmds; -pub mod pick_cmds; mod pixels; -pub mod plugin_cmds; pub mod prefs; -pub mod preset_import_cmds; pub mod preset_store; pub mod presets; -pub mod print_cmds; pub mod proof_sim; -pub mod rasterize_style_cmds; -pub mod redeye_cmds; -pub mod render_cmds; -pub mod retouch_cmds; -pub mod sample_cmds; -pub mod sampler_cmds; -pub mod select_extra_cmds; pub mod select_mask_edits; -pub mod selection_cmds; pub mod shell_commands; pub mod shortcut_sets; -pub mod slice_cmds; -pub mod smart_cmds; -pub mod smartselect_cmds; pub mod snap; -pub mod solid_fill_cmds; -pub mod stamp_cmds; -pub mod style_asl_cmds; -pub mod swatch_cmds; -pub mod symmetry_cmds; -mod timeline_cmds; -pub mod transform_cmds; -mod trap_cmds; -pub mod type_area_cmds; -pub mod type_caret_cmds; -pub mod type_cmds; -pub mod type_extra_cmds; -pub mod type_mask_cmds; -pub mod type_spell_cmds; -pub mod type_styles_cmds; -pub mod updates_cmds; -mod variables_cmds; pub use variables_cmds::{export_data_sets_with, import_data_sets_text}; -pub mod vector_cmds; -mod video_cmds; pub use video_cmds::render_video_with; -pub mod vp_cmds; -pub mod warp_cmds; -pub mod web_cmds; -mod wia_cmds; use std::sync::Arc; @@ -158,6 +57,107 @@ mod error; mod session; pub use cmd as commands; +pub use cmd::actions_cmds; +pub use cmd::actions_edit_cmds; +pub use cmd::adjust_cmds; +pub use cmd::align_cmds; +pub use cmd::analysis_cmds; +pub use cmd::artboard_cmds; +pub use cmd::atn_cmds; +pub use cmd::automate_cmds; +pub use cmd::background_cmds; +pub use cmd::brush_cmds; +pub use cmd::brush_key_cmds; +pub use cmd::brush_preset_cmds; +pub use cmd::channel_cmds; +pub use cmd::color_cmds; +pub use cmd::color_to_alpha_cmds; +pub use cmd::comps_cmds; +pub use cmd::contour_lib_cmds; +pub use cmd::cutout_cmds; +pub use cmd::distort_cmds; +pub use cmd::document_preset_cmds; +pub use cmd::edit_cmds; +pub use cmd::edit_menu_cmds; +pub use cmd::eraser_cmds; +pub use cmd::export_preset_cmds; +pub use cmd::exr_cmds; +pub use cmd::extra_cmds; +pub use cmd::face_cmds; +pub use cmd::file_cmds; +pub use cmd::fill_cmds; +pub use cmd::fill_key_cmds; +pub use cmd::float_cmds; +use cmd::frame_cmds; +pub use cmd::fx_view_cmds; +pub use cmd::fx_visibility_cmds; +pub use cmd::gallery_cmds; +pub use cmd::gradient_fill_cmds; +pub use cmd::group_view_cmds; +pub use cmd::history_cmds; +pub use cmd::history_menu_cmds; +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_label_cmds; +pub use cmd::layer_list_cmds; +pub use cmd::layer_mask_props_cmds; +pub use cmd::layer_menu_cmds; +pub use cmd::layer_multi_cmds; +pub use cmd::layer_nav_cmds; +pub use cmd::layer_xmp_cmds; +pub use cmd::lens_cmds; +pub use cmd::magnetic_cmds; +pub use cmd::mask_view_cmds; +use cmd::migrate_cmds; +pub use cmd::mode_cmds; +pub use cmd::multichannel_cmds; +pub use cmd::notes_cmds; +pub use cmd::paint_cmds; +use cmd::path_edit_cmds; +pub use cmd::pattern_cmds; +pub use cmd::pattern_fill_cmds; +pub use cmd::perspective_crop_cmds; +pub use cmd::photo_cmds; +pub use cmd::pick_cmds; +pub use cmd::plugin_cmds; +pub use cmd::preset_import_cmds; +pub use cmd::print_cmds; +pub use cmd::rasterize_style_cmds; +pub use cmd::redeye_cmds; +pub use cmd::render_cmds; +pub use cmd::retouch_cmds; +pub use cmd::sample_cmds; +pub use cmd::sampler_cmds; +pub use cmd::select_extra_cmds; +pub use cmd::selection_cmds; +pub use cmd::slice_cmds; +pub use cmd::smart_cmds; +pub use cmd::smartselect_cmds; +pub use cmd::solid_fill_cmds; +pub use cmd::stamp_cmds; +pub use cmd::style_asl_cmds; +pub use cmd::swatch_cmds; +pub use cmd::symmetry_cmds; +use cmd::timeline_cmds; +pub use cmd::transform_cmds; +use cmd::trap_cmds; +pub use cmd::type_area_cmds; +pub use cmd::type_caret_cmds; +pub use cmd::type_cmds; +pub use cmd::type_extra_cmds; +pub use cmd::type_mask_cmds; +pub use cmd::type_spell_cmds; +pub use cmd::type_styles_cmds; +pub use cmd::updates_cmds; +use cmd::variables_cmds; +pub use cmd::vector_cmds; +use cmd::video_cmds; +pub use cmd::vp_cmds; +pub use cmd::warp_cmds; +pub use cmd::web_cmds; +use cmd::wia_cmds; pub use doc_state::{CopiedStyle, DocState, PRECHECKED, ToolState}; pub use error::{EngineError, Result}; pub(crate) use session::fix_selection; From b32f4a0a55e3c7165a9d47ad5da2d18ba7412d2c Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 22:54:35 +0000 Subject: [PATCH 235/259] test(engine): name the print_cmds child tests by their cmd:: path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The spooling tests rerun themselves in a child process with an exact test-name filter. print_cmds moved under cmd/, so the filters name cmd::print_cmds::tests::…; with the old names the child ran no tests. --- crates/engine/src/cmd/print_cmds/tests.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/print_cmds/tests.rs b/crates/engine/src/cmd/print_cmds/tests.rs index c4c211d16e..ab2e104a48 100644 --- a/crates/engine/src/cmd/print_cmds/tests.rs +++ b/crates/engine/src/cmd/print_cmds/tests.rs @@ -646,7 +646,7 @@ fn spool_transport_streams_pdf_and_propagates_refusal() { ).unwrap(); std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap(); let result = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "print_cmds::tests::spool_transport_streams_pdf_and_propagates_refusal", "--nocapture"]) + .args(["--exact", "cmd::print_cmds::tests::spool_transport_streams_pdf_and_propagates_refusal", "--nocapture"]) .env(CHILD, dir.path()) .env("PATH", dir.path()) // The child spools into the fake `lp` above, so a shell that blocks real printing @@ -737,7 +737,7 @@ fn recording_spooler(preferred: bool, seen: &std::sync::Arc Date: Mon, 26 Oct 2026 21:03:35 +0000 Subject: [PATCH 236/259] refactor(ui-egui): move canvas modules under canvas/ --- crates/ui-egui/src/canvas.rs | 30 ++++++++ crates/ui-egui/src/{ => canvas}/ants.rs | 0 .../ui-egui/src/{ => canvas}/artboard_ui.rs | 0 .../src/{ => canvas}/background_redraw.rs | 0 .../{ => canvas}/background_redraw/tests.rs | 0 .../ui-egui/src/{ => canvas}/cam_preview.rs | 0 .../src/{ => canvas}/canvas_autoscroll.rs | 0 .../ui-egui/src/{ => canvas}/canvas_popup.rs | 0 .../src/{ => canvas}/canvas_tool_menu.rs | 0 .../{ => canvas}/canvas_tool_menu/tests.rs | 3 +- .../ui-egui/src/{ => canvas}/channel_view.rs | 0 .../src/{ => canvas}/channel_view/tests.rs | 5 +- crates/ui-egui/src/{ => canvas}/gpu_canvas.rs | 8 +-- .../src/{ => canvas}/gpu_canvas/budget.rs | 0 .../src/{ => canvas}/gpu_canvas/callback.rs | 0 .../{ => canvas}/gpu_canvas/doc_textures.rs | 0 .../src/{ => canvas}/gpu_canvas/mip_tests.rs | 0 .../src/{ => canvas}/gpu_canvas/perf.rs | 0 .../src/{ => canvas}/gpu_canvas/resources.rs | 0 .../src/{ => canvas}/gpu_canvas/setup.rs | 0 .../src/{ => canvas}/gpu_canvas/shaders.rs | 0 .../src/{ => canvas}/gpu_canvas/tests.rs | 0 .../src/{ => canvas}/gpu_canvas/texels.rs | 0 .../ui-egui/src/{ => canvas}/guide_select.rs | 0 .../src/{ => canvas}/guide_select/tests.rs | 0 .../ui-egui/src/{ => canvas}/layer_pick_ui.rs | 0 crates/ui-egui/src/{ => canvas}/move_ui.rs | 0 .../ui-egui/src/{ => canvas}/move_ui/tests.rs | 0 crates/ui-egui/src/{ => canvas}/outline.rs | 0 .../ui-egui/src/{ => canvas}/paint_mouse.rs | 0 .../src/{ => canvas}/paint_mouse/tests.rs | 0 .../ui-egui/src/{ => canvas}/patch_preview.rs | 0 .../src/{ => canvas}/pattern_preview.rs | 0 crates/ui-egui/src/{ => canvas}/pixel_grid.rs | 0 crates/ui-egui/src/{ => canvas}/quick_pick.rs | 0 .../ui-egui/src/{ => canvas}/rotate_view.rs | 0 .../src/{ => canvas}/rotate_view/tests.rs | 0 crates/ui-egui/src/{ => canvas}/rulers.rs | 0 .../ui-egui/src/{ => canvas}/rulers/tests.rs | 0 crates/ui-egui/src/{ => canvas}/scrollbars.rs | 0 .../src/{ => canvas}/select_mask_view.rs | 0 crates/ui-egui/src/{ => canvas}/snap_ui.rs | 0 .../ui-egui/src/{ => canvas}/snap_ui/tests.rs | 3 +- .../ui-egui/src/{ => canvas}/tile_overlay.rs | 0 .../ui-egui/src/{ => canvas}/tool_cursor.rs | 0 .../src/{ => canvas}/tool_cursor/hand.rs | 0 .../src/{ => canvas}/tool_cursor/tests.rs | 0 .../src/{ => canvas}/tool_cursor/zoom.rs | 0 .../ui-egui/src/{ => canvas}/tool_feedback.rs | 0 crates/ui-egui/src/{ => canvas}/wheel_nav.rs | 0 .../src/{ => canvas}/wheel_nav/tests.rs | 39 +++------- crates/ui-egui/src/{ => canvas}/zoom_hold.rs | 0 .../ui-egui/src/{ => canvas}/zoom_levels.rs | 0 .../src/{ => canvas}/zoom_window_fit.rs | 0 crates/ui-egui/src/lib.rs | 71 ++++++++++--------- 55 files changed, 86 insertions(+), 73 deletions(-) rename crates/ui-egui/src/{ => canvas}/ants.rs (100%) rename crates/ui-egui/src/{ => canvas}/artboard_ui.rs (100%) rename crates/ui-egui/src/{ => canvas}/background_redraw.rs (100%) rename crates/ui-egui/src/{ => canvas}/background_redraw/tests.rs (100%) rename crates/ui-egui/src/{ => canvas}/cam_preview.rs (100%) rename crates/ui-egui/src/{ => canvas}/canvas_autoscroll.rs (100%) rename crates/ui-egui/src/{ => canvas}/canvas_popup.rs (100%) rename crates/ui-egui/src/{ => canvas}/canvas_tool_menu.rs (100%) rename crates/ui-egui/src/{ => canvas}/canvas_tool_menu/tests.rs (99%) rename crates/ui-egui/src/{ => canvas}/channel_view.rs (100%) rename crates/ui-egui/src/{ => canvas}/channel_view/tests.rs (99%) rename crates/ui-egui/src/{ => canvas}/gpu_canvas.rs (100%) rename crates/ui-egui/src/{ => canvas}/gpu_canvas/budget.rs (100%) rename crates/ui-egui/src/{ => canvas}/gpu_canvas/callback.rs (100%) rename crates/ui-egui/src/{ => canvas}/gpu_canvas/doc_textures.rs (100%) rename crates/ui-egui/src/{ => canvas}/gpu_canvas/mip_tests.rs (100%) rename crates/ui-egui/src/{ => canvas}/gpu_canvas/perf.rs (100%) rename crates/ui-egui/src/{ => canvas}/gpu_canvas/resources.rs (100%) rename crates/ui-egui/src/{ => canvas}/gpu_canvas/setup.rs (100%) rename crates/ui-egui/src/{ => canvas}/gpu_canvas/shaders.rs (100%) rename crates/ui-egui/src/{ => canvas}/gpu_canvas/tests.rs (100%) rename crates/ui-egui/src/{ => canvas}/gpu_canvas/texels.rs (100%) rename crates/ui-egui/src/{ => canvas}/guide_select.rs (100%) rename crates/ui-egui/src/{ => canvas}/guide_select/tests.rs (100%) rename crates/ui-egui/src/{ => canvas}/layer_pick_ui.rs (100%) rename crates/ui-egui/src/{ => canvas}/move_ui.rs (100%) rename crates/ui-egui/src/{ => canvas}/move_ui/tests.rs (100%) rename crates/ui-egui/src/{ => canvas}/outline.rs (100%) rename crates/ui-egui/src/{ => canvas}/paint_mouse.rs (100%) rename crates/ui-egui/src/{ => canvas}/paint_mouse/tests.rs (100%) rename crates/ui-egui/src/{ => canvas}/patch_preview.rs (100%) rename crates/ui-egui/src/{ => canvas}/pattern_preview.rs (100%) rename crates/ui-egui/src/{ => canvas}/pixel_grid.rs (100%) rename crates/ui-egui/src/{ => canvas}/quick_pick.rs (100%) rename crates/ui-egui/src/{ => canvas}/rotate_view.rs (100%) rename crates/ui-egui/src/{ => canvas}/rotate_view/tests.rs (100%) rename crates/ui-egui/src/{ => canvas}/rulers.rs (100%) rename crates/ui-egui/src/{ => canvas}/rulers/tests.rs (100%) rename crates/ui-egui/src/{ => canvas}/scrollbars.rs (100%) rename crates/ui-egui/src/{ => canvas}/select_mask_view.rs (100%) rename crates/ui-egui/src/{ => canvas}/snap_ui.rs (100%) rename crates/ui-egui/src/{ => canvas}/snap_ui/tests.rs (99%) rename crates/ui-egui/src/{ => canvas}/tile_overlay.rs (100%) rename crates/ui-egui/src/{ => canvas}/tool_cursor.rs (100%) rename crates/ui-egui/src/{ => canvas}/tool_cursor/hand.rs (100%) rename crates/ui-egui/src/{ => canvas}/tool_cursor/tests.rs (100%) rename crates/ui-egui/src/{ => canvas}/tool_cursor/zoom.rs (100%) rename crates/ui-egui/src/{ => canvas}/tool_feedback.rs (100%) rename crates/ui-egui/src/{ => canvas}/wheel_nav.rs (100%) rename crates/ui-egui/src/{ => canvas}/wheel_nav/tests.rs (97%) rename crates/ui-egui/src/{ => canvas}/zoom_hold.rs (100%) rename crates/ui-egui/src/{ => canvas}/zoom_levels.rs (100%) rename crates/ui-egui/src/{ => canvas}/zoom_window_fit.rs (100%) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 1afc46a3b6..75ecf186f2 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -12,21 +12,51 @@ use serde_json::json; use crate::PhotocraftApp; use crate::state::{Tool, View}; +pub(super) mod ants; +pub mod artboard_ui; +pub(crate) mod background_redraw; +pub(crate) mod cam_preview; +pub mod canvas_autoscroll; +pub(super) mod canvas_popup; +pub mod canvas_tool_menu; +pub mod channel_view; mod cursors; mod display; mod drag; mod filter_preview; mod gesture; +pub mod gpu_canvas; +pub mod guide_select; +pub mod layer_pick_ui; +pub mod move_ui; mod navigator; +pub mod outline; mod paint; +pub mod paint_mouse; +pub mod patch_preview; +pub mod pattern_preview; +pub mod pixel_grid; +pub mod quick_pick; +pub mod rotate_view; +pub mod rulers; +pub mod scrollbars; +pub mod select_mask_view; mod selection; +pub mod snap_ui; mod start_screen; mod strokes; mod tabs; mod textures; +pub(super) mod tile_overlay; +pub(super) mod tool_cursor; +pub mod tool_feedback; mod tool_input; mod transform_controls; mod view_xform; +pub mod wheel_nav; +pub mod zoom_hold; +pub mod zoom_levels; +pub mod zoom_window_fit; #[cfg(test)] pub(crate) use cursors::eyedropper_ring_colors; diff --git a/crates/ui-egui/src/ants.rs b/crates/ui-egui/src/canvas/ants.rs similarity index 100% rename from crates/ui-egui/src/ants.rs rename to crates/ui-egui/src/canvas/ants.rs diff --git a/crates/ui-egui/src/artboard_ui.rs b/crates/ui-egui/src/canvas/artboard_ui.rs similarity index 100% rename from crates/ui-egui/src/artboard_ui.rs rename to crates/ui-egui/src/canvas/artboard_ui.rs diff --git a/crates/ui-egui/src/background_redraw.rs b/crates/ui-egui/src/canvas/background_redraw.rs similarity index 100% rename from crates/ui-egui/src/background_redraw.rs rename to crates/ui-egui/src/canvas/background_redraw.rs diff --git a/crates/ui-egui/src/background_redraw/tests.rs b/crates/ui-egui/src/canvas/background_redraw/tests.rs similarity index 100% rename from crates/ui-egui/src/background_redraw/tests.rs rename to crates/ui-egui/src/canvas/background_redraw/tests.rs diff --git a/crates/ui-egui/src/cam_preview.rs b/crates/ui-egui/src/canvas/cam_preview.rs similarity index 100% rename from crates/ui-egui/src/cam_preview.rs rename to crates/ui-egui/src/canvas/cam_preview.rs diff --git a/crates/ui-egui/src/canvas_autoscroll.rs b/crates/ui-egui/src/canvas/canvas_autoscroll.rs similarity index 100% rename from crates/ui-egui/src/canvas_autoscroll.rs rename to crates/ui-egui/src/canvas/canvas_autoscroll.rs diff --git a/crates/ui-egui/src/canvas_popup.rs b/crates/ui-egui/src/canvas/canvas_popup.rs similarity index 100% rename from crates/ui-egui/src/canvas_popup.rs rename to crates/ui-egui/src/canvas/canvas_popup.rs diff --git a/crates/ui-egui/src/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs similarity index 100% rename from crates/ui-egui/src/canvas_tool_menu.rs rename to crates/ui-egui/src/canvas/canvas_tool_menu.rs diff --git a/crates/ui-egui/src/canvas_tool_menu/tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs similarity index 99% rename from crates/ui-egui/src/canvas_tool_menu/tests.rs rename to crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs index 5980e4e28c..eb9147a7a5 100644 --- a/crates/ui-egui/src/canvas_tool_menu/tests.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs @@ -323,8 +323,7 @@ fn right_click_during_free_transform_switches_modes_rotates_and_flips_the_box() right_click(&mut h, center, Modifiers::NONE); let menu = h.state().ui.canvas_tool_menu.clone().expect("the transform menu"); assert!(menu.transform && rows(&menu) == TRANSFORM_MENU); - for (id, on) in - [("edit.contentAwareScale", false), ("edit.puppetWarp", false), ("edit.transform.rotate90Cw", true), ("edit.transform.flipVertical", true)] + for (id, on) in [("edit.contentAwareScale", false), ("edit.puppetWarp", false), ("edit.transform.rotate90Cw", true), ("edit.transform.flipVertical", true)] { assert_eq!(entry_enabled(h.state(), &menu, id), on, "{id}"); } diff --git a/crates/ui-egui/src/channel_view.rs b/crates/ui-egui/src/canvas/channel_view.rs similarity index 100% rename from crates/ui-egui/src/channel_view.rs rename to crates/ui-egui/src/canvas/channel_view.rs diff --git a/crates/ui-egui/src/channel_view/tests.rs b/crates/ui-egui/src/canvas/channel_view/tests.rs similarity index 99% rename from crates/ui-egui/src/channel_view/tests.rs rename to crates/ui-egui/src/canvas/channel_view/tests.rs index 99def559a2..d8581ebbbb 100644 --- a/crates/ui-egui/src/channel_view/tests.rs +++ b/crates/ui-egui/src/canvas/channel_view/tests.rs @@ -246,10 +246,7 @@ fn show_channels_in_color_tints_the_canvas() { let st = s.active().unwrap(); let b = st.doc.bounds(); assert_eq!(render(&st.doc, &st.channel_view, b, 1, Look::default(), st.active_layer).unwrap()[0], Color32::from_gray(128)); - assert_eq!( - render(&st.doc, &st.channel_view, b, 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0], - Color32::from_rgb(0, 128, 0) - ); + assert_eq!(render(&st.doc, &st.channel_view, b, 1, Look { in_color: true, ..Look::default() }, st.active_layer).unwrap()[0], Color32::from_rgb(0, 128, 0)); let mut s = Session::new(); s.execute("file.new", json!({"width": 4, "height": 4, "mode": "cmyk"})).unwrap(); diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/canvas/gpu_canvas.rs similarity index 100% rename from crates/ui-egui/src/gpu_canvas.rs rename to crates/ui-egui/src/canvas/gpu_canvas.rs index d96eae7dde..7f16afd5ce 100644 --- a/crates/ui-egui/src/gpu_canvas.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas.rs @@ -43,12 +43,12 @@ mod setup; mod shaders; mod texels; +#[cfg(test)] +use budget::drm_video_memory; pub use budget::{ DEFER_PX, MIN_GPU_BUDGET, OVER_BUDGET, OVER_CANVAS_BUDGET, REFRESH_DEFERRED, REFRESH_OVER_BUDGET, canvas_budget, canvas_texture_bytes, memory_budget, physical_memory, video_memory, vram_share, }; -#[cfg(test)] -use budget::drm_video_memory; #[cfg(all(test, windows))] use budget::{detect_physical_memory, detect_video_memory}; use callback::CanvasCallback; @@ -66,11 +66,11 @@ use setup::texture_buffer; pub use setup::{Refresh, device_descriptor, device_limits, display_texels, timing_features, use_adapter_limits, use_adapter_limits_with, wgpu_setup}; #[cfg(test)] use shaders::{CANVAS_WGSL, ENCODE_WGSL, MIP_WGSL}; +#[cfg(not(target_arch = "wasm32"))] +use texels::texel_to_f32; pub use texels::{LayerFit, premultiply_rgba8, premultiply_rgba16f}; #[cfg(test)] use texels::{f16_to_f32, f32_to_f16}; -#[cfg(not(target_arch = "wasm32"))] -use texels::texel_to_f32; use texels::{texel_bytes, texels, texels_into}; /// Default tile side; documents up to this size (and the device limit) use a single texture. diff --git a/crates/ui-egui/src/gpu_canvas/budget.rs b/crates/ui-egui/src/canvas/gpu_canvas/budget.rs similarity index 100% rename from crates/ui-egui/src/gpu_canvas/budget.rs rename to crates/ui-egui/src/canvas/gpu_canvas/budget.rs diff --git a/crates/ui-egui/src/gpu_canvas/callback.rs b/crates/ui-egui/src/canvas/gpu_canvas/callback.rs similarity index 100% rename from crates/ui-egui/src/gpu_canvas/callback.rs rename to crates/ui-egui/src/canvas/gpu_canvas/callback.rs diff --git a/crates/ui-egui/src/gpu_canvas/doc_textures.rs b/crates/ui-egui/src/canvas/gpu_canvas/doc_textures.rs similarity index 100% rename from crates/ui-egui/src/gpu_canvas/doc_textures.rs rename to crates/ui-egui/src/canvas/gpu_canvas/doc_textures.rs diff --git a/crates/ui-egui/src/gpu_canvas/mip_tests.rs b/crates/ui-egui/src/canvas/gpu_canvas/mip_tests.rs similarity index 100% rename from crates/ui-egui/src/gpu_canvas/mip_tests.rs rename to crates/ui-egui/src/canvas/gpu_canvas/mip_tests.rs diff --git a/crates/ui-egui/src/gpu_canvas/perf.rs b/crates/ui-egui/src/canvas/gpu_canvas/perf.rs similarity index 100% rename from crates/ui-egui/src/gpu_canvas/perf.rs rename to crates/ui-egui/src/canvas/gpu_canvas/perf.rs diff --git a/crates/ui-egui/src/gpu_canvas/resources.rs b/crates/ui-egui/src/canvas/gpu_canvas/resources.rs similarity index 100% rename from crates/ui-egui/src/gpu_canvas/resources.rs rename to crates/ui-egui/src/canvas/gpu_canvas/resources.rs diff --git a/crates/ui-egui/src/gpu_canvas/setup.rs b/crates/ui-egui/src/canvas/gpu_canvas/setup.rs similarity index 100% rename from crates/ui-egui/src/gpu_canvas/setup.rs rename to crates/ui-egui/src/canvas/gpu_canvas/setup.rs diff --git a/crates/ui-egui/src/gpu_canvas/shaders.rs b/crates/ui-egui/src/canvas/gpu_canvas/shaders.rs similarity index 100% rename from crates/ui-egui/src/gpu_canvas/shaders.rs rename to crates/ui-egui/src/canvas/gpu_canvas/shaders.rs diff --git a/crates/ui-egui/src/gpu_canvas/tests.rs b/crates/ui-egui/src/canvas/gpu_canvas/tests.rs similarity index 100% rename from crates/ui-egui/src/gpu_canvas/tests.rs rename to crates/ui-egui/src/canvas/gpu_canvas/tests.rs diff --git a/crates/ui-egui/src/gpu_canvas/texels.rs b/crates/ui-egui/src/canvas/gpu_canvas/texels.rs similarity index 100% rename from crates/ui-egui/src/gpu_canvas/texels.rs rename to crates/ui-egui/src/canvas/gpu_canvas/texels.rs diff --git a/crates/ui-egui/src/guide_select.rs b/crates/ui-egui/src/canvas/guide_select.rs similarity index 100% rename from crates/ui-egui/src/guide_select.rs rename to crates/ui-egui/src/canvas/guide_select.rs diff --git a/crates/ui-egui/src/guide_select/tests.rs b/crates/ui-egui/src/canvas/guide_select/tests.rs similarity index 100% rename from crates/ui-egui/src/guide_select/tests.rs rename to crates/ui-egui/src/canvas/guide_select/tests.rs diff --git a/crates/ui-egui/src/layer_pick_ui.rs b/crates/ui-egui/src/canvas/layer_pick_ui.rs similarity index 100% rename from crates/ui-egui/src/layer_pick_ui.rs rename to crates/ui-egui/src/canvas/layer_pick_ui.rs diff --git a/crates/ui-egui/src/move_ui.rs b/crates/ui-egui/src/canvas/move_ui.rs similarity index 100% rename from crates/ui-egui/src/move_ui.rs rename to crates/ui-egui/src/canvas/move_ui.rs diff --git a/crates/ui-egui/src/move_ui/tests.rs b/crates/ui-egui/src/canvas/move_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/move_ui/tests.rs rename to crates/ui-egui/src/canvas/move_ui/tests.rs diff --git a/crates/ui-egui/src/outline.rs b/crates/ui-egui/src/canvas/outline.rs similarity index 100% rename from crates/ui-egui/src/outline.rs rename to crates/ui-egui/src/canvas/outline.rs diff --git a/crates/ui-egui/src/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs similarity index 100% rename from crates/ui-egui/src/paint_mouse.rs rename to crates/ui-egui/src/canvas/paint_mouse.rs diff --git a/crates/ui-egui/src/paint_mouse/tests.rs b/crates/ui-egui/src/canvas/paint_mouse/tests.rs similarity index 100% rename from crates/ui-egui/src/paint_mouse/tests.rs rename to crates/ui-egui/src/canvas/paint_mouse/tests.rs diff --git a/crates/ui-egui/src/patch_preview.rs b/crates/ui-egui/src/canvas/patch_preview.rs similarity index 100% rename from crates/ui-egui/src/patch_preview.rs rename to crates/ui-egui/src/canvas/patch_preview.rs diff --git a/crates/ui-egui/src/pattern_preview.rs b/crates/ui-egui/src/canvas/pattern_preview.rs similarity index 100% rename from crates/ui-egui/src/pattern_preview.rs rename to crates/ui-egui/src/canvas/pattern_preview.rs diff --git a/crates/ui-egui/src/pixel_grid.rs b/crates/ui-egui/src/canvas/pixel_grid.rs similarity index 100% rename from crates/ui-egui/src/pixel_grid.rs rename to crates/ui-egui/src/canvas/pixel_grid.rs diff --git a/crates/ui-egui/src/quick_pick.rs b/crates/ui-egui/src/canvas/quick_pick.rs similarity index 100% rename from crates/ui-egui/src/quick_pick.rs rename to crates/ui-egui/src/canvas/quick_pick.rs diff --git a/crates/ui-egui/src/rotate_view.rs b/crates/ui-egui/src/canvas/rotate_view.rs similarity index 100% rename from crates/ui-egui/src/rotate_view.rs rename to crates/ui-egui/src/canvas/rotate_view.rs diff --git a/crates/ui-egui/src/rotate_view/tests.rs b/crates/ui-egui/src/canvas/rotate_view/tests.rs similarity index 100% rename from crates/ui-egui/src/rotate_view/tests.rs rename to crates/ui-egui/src/canvas/rotate_view/tests.rs diff --git a/crates/ui-egui/src/rulers.rs b/crates/ui-egui/src/canvas/rulers.rs similarity index 100% rename from crates/ui-egui/src/rulers.rs rename to crates/ui-egui/src/canvas/rulers.rs diff --git a/crates/ui-egui/src/rulers/tests.rs b/crates/ui-egui/src/canvas/rulers/tests.rs similarity index 100% rename from crates/ui-egui/src/rulers/tests.rs rename to crates/ui-egui/src/canvas/rulers/tests.rs diff --git a/crates/ui-egui/src/scrollbars.rs b/crates/ui-egui/src/canvas/scrollbars.rs similarity index 100% rename from crates/ui-egui/src/scrollbars.rs rename to crates/ui-egui/src/canvas/scrollbars.rs diff --git a/crates/ui-egui/src/select_mask_view.rs b/crates/ui-egui/src/canvas/select_mask_view.rs similarity index 100% rename from crates/ui-egui/src/select_mask_view.rs rename to crates/ui-egui/src/canvas/select_mask_view.rs diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/canvas/snap_ui.rs similarity index 100% rename from crates/ui-egui/src/snap_ui.rs rename to crates/ui-egui/src/canvas/snap_ui.rs diff --git a/crates/ui-egui/src/snap_ui/tests.rs b/crates/ui-egui/src/canvas/snap_ui/tests.rs similarity index 99% rename from crates/ui-egui/src/snap_ui/tests.rs rename to crates/ui-egui/src/canvas/snap_ui/tests.rs index 8f763efc12..56617d906e 100644 --- a/crates/ui-egui/src/snap_ui/tests.rs +++ b/crates/ui-egui/src/canvas/snap_ui/tests.rs @@ -63,8 +63,7 @@ fn mover_bounds(app: &PhotocraftApp) -> photocraft_geom::Rect { #[test] fn drawing_a_new_crop_snaps_its_corner_not_the_default_frame() { // In both crop modes: the default mode draws a new box inside the untouched frame too. - for (classic, snap, end) in [(true, false, [300.0, 220.0]), (true, true, [294.0, 217.0]), (false, false, [300.0, 220.0]), (false, true, [294.0, 217.0])] - { + for (classic, snap, end) in [(true, false, [300.0, 220.0]), (true, true, [294.0, 217.0]), (false, false, [300.0, 220.0]), (false, true, [294.0, 217.0])] { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 640, "height": 480, "background": "white"})).unwrap(); app.run("shape.create", json!({"kind": "rect", "rect": [100, 80, 200, 140], "fill": "#d59b40"})).unwrap(); diff --git a/crates/ui-egui/src/tile_overlay.rs b/crates/ui-egui/src/canvas/tile_overlay.rs similarity index 100% rename from crates/ui-egui/src/tile_overlay.rs rename to crates/ui-egui/src/canvas/tile_overlay.rs diff --git a/crates/ui-egui/src/tool_cursor.rs b/crates/ui-egui/src/canvas/tool_cursor.rs similarity index 100% rename from crates/ui-egui/src/tool_cursor.rs rename to crates/ui-egui/src/canvas/tool_cursor.rs diff --git a/crates/ui-egui/src/tool_cursor/hand.rs b/crates/ui-egui/src/canvas/tool_cursor/hand.rs similarity index 100% rename from crates/ui-egui/src/tool_cursor/hand.rs rename to crates/ui-egui/src/canvas/tool_cursor/hand.rs diff --git a/crates/ui-egui/src/tool_cursor/tests.rs b/crates/ui-egui/src/canvas/tool_cursor/tests.rs similarity index 100% rename from crates/ui-egui/src/tool_cursor/tests.rs rename to crates/ui-egui/src/canvas/tool_cursor/tests.rs diff --git a/crates/ui-egui/src/tool_cursor/zoom.rs b/crates/ui-egui/src/canvas/tool_cursor/zoom.rs similarity index 100% rename from crates/ui-egui/src/tool_cursor/zoom.rs rename to crates/ui-egui/src/canvas/tool_cursor/zoom.rs diff --git a/crates/ui-egui/src/tool_feedback.rs b/crates/ui-egui/src/canvas/tool_feedback.rs similarity index 100% rename from crates/ui-egui/src/tool_feedback.rs rename to crates/ui-egui/src/canvas/tool_feedback.rs diff --git a/crates/ui-egui/src/wheel_nav.rs b/crates/ui-egui/src/canvas/wheel_nav.rs similarity index 100% rename from crates/ui-egui/src/wheel_nav.rs rename to crates/ui-egui/src/canvas/wheel_nav.rs diff --git a/crates/ui-egui/src/wheel_nav/tests.rs b/crates/ui-egui/src/canvas/wheel_nav/tests.rs similarity index 97% rename from crates/ui-egui/src/wheel_nav/tests.rs rename to crates/ui-egui/src/canvas/wheel_nav/tests.rs index 2a727d2dcf..d2211a7daa 100644 --- a/crates/ui-egui/src/wheel_nav/tests.rs +++ b/crates/ui-egui/src/canvas/wheel_nav/tests.rs @@ -28,8 +28,7 @@ fn gesture_with(frames: Vec>, zoom_with_wheel: bool, legacy: bool, an let (mut pan, mut zoom, mut snaps) = (Vec2::ZERO, 1.0, 0i32); let mut frames = frames.into_iter(); for n in 0..60 { - let mut raw = - RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events: frames.next().unwrap_or_default(), ..Default::default() }; + let mut raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events: frames.next().unwrap_or_default(), ..Default::default() }; if legacy { fold_legacy_pinch(&ctx, &mut raw); } @@ -368,8 +367,7 @@ fn shift_snap_zoom_drops_the_unfinished_eased_notch() { /// frame zooms by its own events, at once. #[test] fn animated_zoom_does_not_ease_a_trackpad() { - let frames = - run_zoom(30, |n| if n == 0 { vec![wheel_point(Vec2::new(0.0, 4.0), Modifiers::ALT)] } else { Vec::new() }, |n| f64::from(n) / 60.0, |_| true); + let frames = run_zoom(30, |n| if n == 0 { vec![wheel_point(Vec2::new(0.0, 4.0), Modifiers::ALT)] } else { Vec::new() }, |n| f64::from(n) / 60.0, |_| true); assert!((frames[0] - NOTCH.powf(0.1)).abs() < 1e-6, "all of it in the frame it arrives: {:?}", &frames[..4]); assert!(frames[1..].iter().all(|f| *f == 1.0), "no tail after it: {frames:?}"); } @@ -403,8 +401,7 @@ fn animated_zoom_keeps_the_sideways_wheel_unsmoothed_with_animations_off() { /// is a 10-point step, which egui smooths, so Animated Zoom eases it. #[test] fn a_diagonal_alt_point_step_is_measured_like_egui() { - let frames = - run_zoom(60, |n| if n == 0 { vec![wheel_point(Vec2::new(5.0, 5.0), Modifiers::ALT)] } else { Vec::new() }, |n| f64::from(n) / 60.0, |_| true); + let frames = run_zoom(60, |n| if n == 0 { vec![wheel_point(Vec2::new(5.0, 5.0), Modifiers::ALT)] } else { Vec::new() }, |n| f64::from(n) / 60.0, |_| true); assert!(frames[0] < NOTCH.powf(0.25) - 1e-4 && frames[1] > 1.0, "eased: {:?}", &frames[..4]); } @@ -859,8 +856,7 @@ fn cross_viewport_does_not_leak_residual() { let mut snaps_a = 0i32; let mut snaps_b = 0i32; // Frame 0: 30 points over A (hovered), B not hovered. - let raw = - RawInput { time: Some(0.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 30.0), Modifiers::SHIFT)], ..Default::default() }; + let raw = RawInput { time: Some(0.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 30.0), Modifiers::SHIFT)], ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| { if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_a, true) { snaps_a += s; @@ -873,12 +869,8 @@ fn cross_viewport_does_not_leak_residual() { assert_eq!(snaps_a, 0, "A: 30 points, below 1 notch"); assert_eq!(snaps_b, 0, "B: not hovered, nothing"); // Frame 1: 10 points, pointer moved to B (B hovered, A not). - let raw = RawInput { - time: Some(1.0 / 60.0), - predicted_dt: 1.0 / 60.0, - events: vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], - ..Default::default() - }; + let raw = + RawInput { time: Some(1.0 / 60.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 10.0), Modifiers::SHIFT)], ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| { if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_a, false) { snaps_a += s; @@ -907,12 +899,8 @@ fn cross_viewport_does_not_leak_residual() { } assert_eq!(snaps_b, 1, "B: 10+10+10+10 = 40 → 1 step"); // Frame 5: switch back to A — A's residual was cleared on the viewport switch. - let raw = RawInput { - time: Some(5.0 / 60.0), - predicted_dt: 1.0 / 60.0, - events: vec![wheel_point(Vec2::new(0.0, 30.0), Modifiers::SHIFT)], - ..Default::default() - }; + let raw = + RawInput { time: Some(5.0 / 60.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 30.0), Modifiers::SHIFT)], ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| { if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner_a, true) { snaps_a += s; @@ -929,8 +917,7 @@ fn two_reads_same_owner_same_frame_do_not_double_count() { let ctx = Context::default(); configure(&ctx); let mut total_snaps = 0i32; - let raw = - RawInput { time: Some(0.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 20.0), Modifiers::SHIFT)], ..Default::default() }; + let raw = RawInput { time: Some(0.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 20.0), Modifiers::SHIFT)], ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| { if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner, true) { total_snaps += s; @@ -942,12 +929,8 @@ fn two_reads_same_owner_same_frame_do_not_double_count() { out.textures_delta.clear(); assert_eq!(total_snaps, 0, "20 points read twice must not become 40"); // Now add another 20 in the next frame — should snap since accumulated 20+20=40. - let raw = RawInput { - time: Some(1.0 / 60.0), - predicted_dt: 1.0 / 60.0, - events: vec![wheel_point(Vec2::new(0.0, 20.0), Modifiers::SHIFT)], - ..Default::default() - }; + let raw = + RawInput { time: Some(1.0 / 60.0), predicted_dt: 1.0 / 60.0, events: vec![wheel_point(Vec2::new(0.0, 20.0), Modifiers::SHIFT)], ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| { if let Some(Wheel::SnapZoom(s)) = read(ui.ctx(), true, true, true, owner, true) { total_snaps += s; diff --git a/crates/ui-egui/src/zoom_hold.rs b/crates/ui-egui/src/canvas/zoom_hold.rs similarity index 100% rename from crates/ui-egui/src/zoom_hold.rs rename to crates/ui-egui/src/canvas/zoom_hold.rs diff --git a/crates/ui-egui/src/zoom_levels.rs b/crates/ui-egui/src/canvas/zoom_levels.rs similarity index 100% rename from crates/ui-egui/src/zoom_levels.rs rename to crates/ui-egui/src/canvas/zoom_levels.rs diff --git a/crates/ui-egui/src/zoom_window_fit.rs b/crates/ui-egui/src/canvas/zoom_window_fit.rs similarity index 100% rename from crates/ui-egui/src/zoom_window_fit.rs rename to crates/ui-egui/src/canvas/zoom_window_fit.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bbfd0e8b75..a5bd4d057e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -23,11 +23,8 @@ mod align_bar; mod alt_grab; pub mod analysis_ui; pub mod anchor_tools; -mod ants; pub mod apply_color; pub mod artboard_tool; -pub mod artboard_ui; -pub(crate) mod background_redraw; pub mod bidi_text; pub(crate) mod bitmap_dialog; mod blend_keys; @@ -43,7 +40,6 @@ pub mod brush_resize; pub mod brush_sections; pub mod brushes_tab; pub mod caf_ui; -pub(crate) mod cam_preview; mod cam_transform; mod camera_raw_detail_ui; mod camera_raw_gpu; @@ -51,12 +47,8 @@ mod camera_raw_preview_ui; mod camera_raw_scope_ui; pub mod camera_raw_ui; pub mod canvas; -pub mod canvas_autoscroll; -mod canvas_popup; -pub mod canvas_tool_menu; pub mod cas_transform; pub mod channel_options_ui; -pub mod channel_view; pub mod channels_panel; pub mod chrome_ui; pub mod cjk_fonts; @@ -110,11 +102,9 @@ pub mod flick_pan; mod font_preview; pub mod frame_tool; pub mod gallery_ui; -pub mod gpu_canvas; pub mod gpu_status; pub mod gradient_ui; pub mod guide_layout_ui; -pub mod guide_select; pub mod histogram_panel; pub mod history_menu_ui; pub mod hold_keys; @@ -128,7 +118,6 @@ pub mod lasso_ui; pub(crate) mod last_brush; pub mod layer_filter_ui; pub mod layer_menu_ui; -pub mod layer_pick_ui; pub mod layer_picker; pub mod layer_props_ui; mod layer_reveal; @@ -154,7 +143,6 @@ pub mod move_distance; pub mod move_hover; pub mod move_lock; pub mod move_mods; -pub mod move_ui; pub mod native_menu; pub mod new_doc_ui; pub mod new_guide_ui; @@ -165,19 +153,14 @@ mod numeric_expression; pub mod object_finder; mod opacity_keys; pub mod open_prompt; -pub mod outline; mod page_keys; -pub mod paint_mouse; pub mod palette; mod panel_docking; pub mod panels; pub mod parity; -pub mod patch_preview; pub(crate) mod pattern_fill_ui; -pub mod pattern_preview; pub mod perspective_crop_ui; pub mod perspective_ui; -pub mod pixel_grid; pub mod plugin_ui; pub mod point_curve; pub mod prefs_ui; @@ -188,18 +171,13 @@ mod pressure_curve_ui; pub mod props_layout; pub mod proxy; pub mod puppet_ui; -pub mod quick_pick; pub mod rasterize_prompt; pub mod replace_prompt; pub mod retouch_ui; mod rgb_histogram; -pub mod rotate_view; -pub mod rulers; pub mod screen_picker; pub mod screenshot; -pub mod scrollbars; mod scrub_wrap; -pub mod select_mask_view; pub mod served_fonts; pub mod shape_dialog; pub(crate) mod shape_fill_ui; @@ -214,7 +192,6 @@ mod sizing; pub mod slice_ui; pub mod smart_filter_dialog; pub mod smart_ui; -pub mod snap_ui; pub mod snapshot_dialog; pub(crate) mod solid_fill_ui; pub mod spring_tools; @@ -234,13 +211,10 @@ pub mod texel_guard; pub mod text_field_menu; pub mod theme; pub mod tiff_options_ui; -mod tile_overlay; mod timeline_ui; mod titlebar; pub use titlebar::{Caption, CaptionFamily, CaptionIcon, CaptionIcons, CaptionStyle, RenderIconFn}; pub mod tone; -mod tool_cursor; -pub mod tool_feedback; pub(crate) mod tool_memory; mod tool_reset; mod tool_shortcuts; @@ -258,15 +232,11 @@ pub mod vector_ui; pub mod view_cmds; pub mod vp_ui; pub mod warp_preview; -pub mod wheel_nav; pub mod wide_angle_ui; pub mod widgets; pub mod work_area; pub mod workspace_ui; -pub mod zoom_hold; -pub mod zoom_levels; pub mod zoom_tool; -pub mod zoom_window_fit; use std::collections::HashMap; use std::sync::mpsc::{Receiver, Sender}; @@ -283,15 +253,50 @@ pub use state::{Tool, UiState}; mod app; mod services; -use app::read_dropped; #[cfg(test)] use app::layer_thumb_frame; +use app::read_dropped; pub use app::surface_fingerprint; pub(crate) use app::{adjustment_layer_active, remember_new_document}; +use canvas::ants; +pub use canvas::artboard_ui; +pub(crate) use canvas::background_redraw; +pub(crate) use canvas::cam_preview; +pub use canvas::canvas_autoscroll; +use canvas::canvas_popup; +pub use canvas::canvas_tool_menu; +pub use canvas::channel_view; +pub use canvas::gpu_canvas; +pub use canvas::guide_select; +pub use canvas::layer_pick_ui; +pub use canvas::move_ui; +pub use canvas::outline; +pub use canvas::paint_mouse; +pub use canvas::patch_preview; +pub use canvas::pattern_preview; +pub use canvas::pixel_grid; +pub use canvas::quick_pick; +pub use canvas::rotate_view; +pub use canvas::rulers; +pub use canvas::scrollbars; +pub use canvas::select_mask_view; +pub use canvas::snap_ui; +use canvas::tile_overlay; +use canvas::tool_cursor; +pub use canvas::tool_feedback; +pub use canvas::wheel_nav; +pub use canvas::zoom_hold; +pub use canvas::zoom_levels; +pub use canvas::zoom_window_fit; +pub(crate) use services::SAVE_OPTIONS_OPEN; #[cfg(test)] pub(crate) use services::saved_revision_after_write; -pub use services::{AdoptAutosaveFn, AppendTextFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, CaptionStyleFn, ClipboardGetFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn, ExportSettings, FileStamp, FileStampFn, FormatChoices, ImportFn, Inbox, LoadTextFn, OpenUrlFn, OsEventsFn, PhotoshopShortcutsFn, QuitFn, Recoverable, RecoverFn, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, WindowFrameFn, WriteFn}; -pub(crate) use services::SAVE_OPTIONS_OPEN; +pub use services::{ + AdoptAutosaveFn, AppendTextFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, + CaptionStyleFn, ClipboardGetFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn, ExportSettings, FileStamp, + FileStampFn, FormatChoices, ImportFn, Inbox, LoadTextFn, OpenUrlFn, OsEventsFn, PhotoshopShortcutsFn, QuitFn, RecoverFn, Recoverable, RightButtonDownFn, + SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, WindowFrameFn, WriteFn, +}; /// The Info panel's cached sample: pixel x, y, document revision and Eyedropper Sample Size. type InfoSampleKey = (i32, i32, u64, u32); From 0b2c35c02422522df017621cb4b4c59352f6ace9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 21:11:20 +0000 Subject: [PATCH 237/259] refactor(ui-egui): move panels modules under panels/ --- crates/ui-egui/src/lib.rs | 73 +++++++++---------- crates/ui-egui/src/panels.rs | 56 +++++++++++--- crates/ui-egui/src/{ => panels}/actions.rs | 0 .../ui-egui/src/{ => panels}/actions/tests.rs | 8 +- crates/ui-egui/src/{ => panels}/adjust_ui.rs | 0 .../ui-egui/src/{ => panels}/apply_color.rs | 0 .../src/{ => panels}/apply_color/tests.rs | 0 .../ui-egui/src/{ => panels}/blend_preview.rs | 0 .../src/{ => panels}/blend_preview/tests.rs | 0 crates/ui-egui/src/{ => panels}/brand.rs | 2 +- .../ui-egui/src/{ => panels}/brush_panel.rs | 0 .../src/{ => panels}/brush_panel/tests.rs | 0 .../ui-egui/src/{ => panels}/brush_preview.rs | 0 .../src/{ => panels}/brush_sections.rs | 0 .../src/{ => panels}/brush_sections/tests.rs | 0 .../ui-egui/src/{ => panels}/brushes_tab.rs | 0 .../src/{ => panels}/brushes_tab/tests.rs | 0 .../src/{ => panels}/channels_panel.rs | 0 .../src/{ => panels}/channels_panel/tests.rs | 0 crates/ui-egui/src/{ => panels}/chrome_ui.rs | 0 .../ui-egui/src/{ => panels}/clip_line_ui.rs | 0 .../src/{ => panels}/clip_line_ui/tests.rs | 0 .../src/{ => panels}/color_panel_ui.rs | 0 crates/ui-egui/src/{ => panels}/comps_ui.rs | 0 .../ui-egui/src/{ => panels}/doc_props_ui.rs | 0 .../src/{ => panels}/histogram_panel.rs | 0 .../src/{ => panels}/histogram_panel/tests.rs | 0 .../src/{ => panels}/history_menu_ui.rs | 0 .../src/{ => panels}/layer_filter_ui.rs | 0 .../src/{ => panels}/layer_filter_ui/tests.rs | 0 .../ui-egui/src/{ => panels}/layer_menu_ui.rs | 0 .../{ => panels}/layer_menu_ui/color_tests.rs | 0 .../src/{ => panels}/layer_menu_ui/tests.rs | 36 ++++----- .../src/{ => panels}/layer_props_ui.rs | 0 .../ui-egui/src/{ => panels}/layer_reveal.rs | 0 .../src/{ => panels}/layer_reveal/tests.rs | 0 .../ui-egui/src/{ => panels}/layer_row_ui.rs | 0 .../{ => panels}/layer_row_ui/edit_tests.rs | 0 .../{ => panels}/layer_row_ui/rename_tests.rs | 0 .../src/{ => panels}/layer_row_ui/tests.rs | 0 .../src/{ => panels}/layer_transfer.rs | 0 .../src/{ => panels}/layer_transfer/tests.rs | 0 .../ui-egui/src/{ => panels}/layer_tree_ui.rs | 0 .../src/{ => panels}/layer_tree_ui/tests.rs | 0 .../src/{ => panels}/layers_panel_ui.rs | 0 .../ui-egui/src/{ => panels}/mask_props_ui.rs | 0 .../src/{ => panels}/mask_thumbs_ui.rs | 0 .../src/{ => panels}/mask_thumbs_ui/tests.rs | 0 .../ui-egui/src/{ => panels}/panel_docking.rs | 0 .../panel_docking/native_tests.rs | 0 .../src/{ => panels}/panel_docking/tests.rs | 2 +- .../ui-egui/src/{ => panels}/preset_panels.rs | 5 +- .../src/{ => panels}/preset_panels/panels.rs | 0 .../ui-egui/src/{ => panels}/props_layout.rs | 0 .../src/{ => panels}/props_layout/tests.rs | 0 crates/ui-egui/src/{ => panels}/smart_ui.rs | 0 .../src/{ => panels}/smart_ui/editor_tests.rs | 0 .../ui-egui/src/{ => panels}/swatches_ui.rs | 0 .../ui-egui/src/{ => panels}/timeline_ui.rs | 0 crates/ui-egui/src/{ => panels}/titlebar.rs | 0 .../src/{ => panels}/titlebar/tests.rs | 0 .../src/{ => panels}/type_panels_ui.rs | 0 .../type_panels_ui/color_picker.rs | 0 .../type_panels_ui/color_picker/tests.rs | 0 .../ui-egui/src/{ => panels}/variables_ui.rs | 0 65 files changed, 104 insertions(+), 78 deletions(-) rename crates/ui-egui/src/{ => panels}/actions.rs (100%) rename crates/ui-egui/src/{ => panels}/actions/tests.rs (99%) rename crates/ui-egui/src/{ => panels}/adjust_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/apply_color.rs (100%) rename crates/ui-egui/src/{ => panels}/apply_color/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/blend_preview.rs (100%) rename crates/ui-egui/src/{ => panels}/blend_preview/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/brand.rs (96%) rename crates/ui-egui/src/{ => panels}/brush_panel.rs (100%) rename crates/ui-egui/src/{ => panels}/brush_panel/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/brush_preview.rs (100%) rename crates/ui-egui/src/{ => panels}/brush_sections.rs (100%) rename crates/ui-egui/src/{ => panels}/brush_sections/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/brushes_tab.rs (100%) rename crates/ui-egui/src/{ => panels}/brushes_tab/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/channels_panel.rs (100%) rename crates/ui-egui/src/{ => panels}/channels_panel/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/chrome_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/clip_line_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/clip_line_ui/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/color_panel_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/comps_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/doc_props_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/histogram_panel.rs (100%) rename crates/ui-egui/src/{ => panels}/histogram_panel/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/history_menu_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_filter_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_filter_ui/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_menu_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_menu_ui/color_tests.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_menu_ui/tests.rs (97%) rename crates/ui-egui/src/{ => panels}/layer_props_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_reveal.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_reveal/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_row_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_row_ui/edit_tests.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_row_ui/rename_tests.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_row_ui/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_transfer.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_transfer/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_tree_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/layer_tree_ui/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/layers_panel_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/mask_props_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/mask_thumbs_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/mask_thumbs_ui/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/panel_docking.rs (100%) rename crates/ui-egui/src/{ => panels}/panel_docking/native_tests.rs (100%) rename crates/ui-egui/src/{ => panels}/panel_docking/tests.rs (99%) rename crates/ui-egui/src/{ => panels}/preset_panels.rs (99%) rename crates/ui-egui/src/{ => panels}/preset_panels/panels.rs (100%) rename crates/ui-egui/src/{ => panels}/props_layout.rs (100%) rename crates/ui-egui/src/{ => panels}/props_layout/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/smart_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/smart_ui/editor_tests.rs (100%) rename crates/ui-egui/src/{ => panels}/swatches_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/timeline_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/titlebar.rs (100%) rename crates/ui-egui/src/{ => panels}/titlebar/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/type_panels_ui.rs (100%) rename crates/ui-egui/src/{ => panels}/type_panels_ui/color_picker.rs (100%) rename crates/ui-egui/src/{ => panels}/type_panels_ui/color_picker/tests.rs (100%) rename crates/ui-egui/src/{ => panels}/variables_ui.rs (100%) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a5bd4d057e..877211960a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -13,32 +13,22 @@ macro_rules! tl { $crate::i18n::t($s) }; } - -pub mod actions; pub mod adjust_dialog; pub mod adjust_editors; pub mod adjust_preview; -pub mod adjust_ui; mod align_bar; mod alt_grab; pub mod analysis_ui; pub mod anchor_tools; -pub mod apply_color; pub mod artboard_tool; pub mod bidi_text; pub(crate) mod bitmap_dialog; mod blend_keys; -pub(crate) mod blend_preview; pub mod blur_pins; -mod brand; pub(crate) mod brush_cursor; -pub mod brush_panel; pub mod brush_picker; pub mod brush_preset_dialog; -pub mod brush_preview; pub mod brush_resize; -pub mod brush_sections; -pub mod brushes_tab; pub mod caf_ui; mod cam_transform; mod camera_raw_detail_ui; @@ -49,15 +39,10 @@ pub mod camera_raw_ui; pub mod canvas; pub mod cas_transform; pub mod channel_options_ui; -pub mod channels_panel; -pub mod chrome_ui; pub mod cjk_fonts; -pub mod clip_line_ui; -pub mod color_panel_ui; pub mod color_picker_ui; pub mod color_range_ui; pub mod color_table_ui; -pub mod comps_ui; pub mod control; mod control_click; pub mod corner_radius; @@ -79,7 +64,6 @@ pub mod direction; pub mod discard_ui; pub mod disk_change_prompt; pub mod distort_ui; -pub mod doc_props_ui; pub mod dock; pub mod duplicate_layer_ui; pub mod edit_history; @@ -105,8 +89,6 @@ pub mod gallery_ui; pub mod gpu_status; pub mod gradient_ui; pub mod guide_layout_ui; -pub mod histogram_panel; -pub mod history_menu_ui; pub mod hold_keys; pub mod i18n; mod icon_data; @@ -116,22 +98,12 @@ pub mod jpeg_options_ui; pub mod kys_import; pub mod lasso_ui; pub(crate) mod last_brush; -pub mod layer_filter_ui; -pub mod layer_menu_ui; pub mod layer_picker; -pub mod layer_props_ui; -mod layer_reveal; -pub mod layer_row_ui; pub mod layer_style; -mod layer_transfer; -pub mod layer_tree_ui; -pub mod layers_panel_ui; mod layout_keys; pub mod links; pub mod liquify_ui; pub mod magnetic_lasso_ui; -mod mask_props_ui; -pub mod mask_thumbs_ui; pub mod mask_trash_prompt; pub mod menu_catalog; pub mod menu_keys; @@ -155,7 +127,6 @@ mod opacity_keys; pub mod open_prompt; mod page_keys; pub mod palette; -mod panel_docking; pub mod panels; pub mod parity; pub(crate) mod pattern_fill_ui; @@ -165,10 +136,8 @@ pub mod plugin_ui; pub mod point_curve; pub mod prefs_ui; pub mod preset_files_ui; -pub mod preset_panels; pub mod press_menu; mod pressure_curve_ui; -pub mod props_layout; pub mod proxy; pub mod puppet_ui; pub mod rasterize_prompt; @@ -191,7 +160,6 @@ mod single_line_drag; mod sizing; pub mod slice_ui; pub mod smart_filter_dialog; -pub mod smart_ui; pub mod snapshot_dialog; pub(crate) mod solid_fill_ui; pub mod spring_tools; @@ -203,7 +171,6 @@ pub mod stroke_trail; pub mod stroke_ui; pub mod stylus; pub mod swap_arrow; -pub mod swatches_ui; pub mod symmetry_ui; mod tab_strip; pub mod targa_options_ui; @@ -211,8 +178,6 @@ pub mod texel_guard; pub mod text_field_menu; pub mod theme; pub mod tiff_options_ui; -mod timeline_ui; -mod titlebar; pub use titlebar::{Caption, CaptionFamily, CaptionIcon, CaptionIcons, CaptionStyle, RenderIconFn}; pub mod tone; pub(crate) mod tool_memory; @@ -223,11 +188,9 @@ pub mod transform_fx; pub mod transform_tex; pub mod transform_tool; mod type_font_preview; -pub mod type_panels_ui; pub mod type_tool; mod type_transform; pub mod updates_ui; -mod variables_ui; pub mod vector_ui; pub mod view_cmds; pub mod vp_ui; @@ -288,6 +251,42 @@ pub use canvas::wheel_nav; pub use canvas::zoom_hold; pub use canvas::zoom_levels; pub use canvas::zoom_window_fit; +pub use panels::actions; +pub use panels::adjust_ui; +pub use panels::apply_color; +pub(crate) use panels::blend_preview; +use panels::brand; +pub use panels::brush_panel; +pub use panels::brush_preview; +pub use panels::brush_sections; +pub use panels::brushes_tab; +pub use panels::channels_panel; +pub use panels::chrome_ui; +pub use panels::clip_line_ui; +pub use panels::color_panel_ui; +pub use panels::comps_ui; +pub use panels::doc_props_ui; +pub use panels::histogram_panel; +pub use panels::history_menu_ui; +pub use panels::layer_filter_ui; +pub use panels::layer_menu_ui; +pub use panels::layer_props_ui; +use panels::layer_reveal; +pub use panels::layer_row_ui; +use panels::layer_transfer; +pub use panels::layer_tree_ui; +pub use panels::layers_panel_ui; +use panels::mask_props_ui; +pub use panels::mask_thumbs_ui; +use panels::panel_docking; +pub use panels::preset_panels; +pub use panels::props_layout; +pub use panels::smart_ui; +pub use panels::swatches_ui; +use panels::timeline_ui; +use panels::titlebar; +pub use panels::type_panels_ui; +use panels::variables_ui; pub(crate) use services::SAVE_OPTIONS_OPEN; #[cfg(test)] pub(crate) use services::saved_revision_after_write; diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index a4c556ce37..78812d8c0c 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -11,31 +11,67 @@ use crate::state::Tool; use crate::theme::{self, Tokens}; use crate::{PhotocraftApp, icons, widgets}; +pub mod actions; +pub mod adjust_ui; +pub mod apply_color; +pub(crate) mod blend_preview; +pub(super) mod brand; mod brush_controls; +pub mod brush_panel; +pub mod brush_preview; +pub mod brush_sections; +pub mod brushes_tab; +pub mod channels_panel; +pub mod chrome_ui; +pub mod clip_line_ui; mod color; +pub mod color_panel_ui; +pub mod comps_ui; +pub mod doc_props_ui; mod dock; +pub mod histogram_panel; mod history; +pub mod history_menu_ui; mod info; mod layer_drag; +pub mod layer_filter_ui; +pub mod layer_menu_ui; +pub mod layer_props_ui; +pub(super) mod layer_reveal; mod layer_row; +pub mod layer_row_ui; +pub(super) mod layer_transfer; +pub mod layer_tree_ui; mod layers; +pub mod layers_panel_ui; +pub(super) mod mask_props_ui; +pub mod mask_thumbs_ui; mod navigator; mod options_bar; +pub(super) mod panel_docking; mod panel_state; +pub mod preset_panels; mod properties; +pub mod props_layout; +pub mod smart_ui; mod status_bar; +pub mod swatches_ui; +pub(super) mod timeline_ui; mod title_bar; +pub(super) mod titlebar; mod toolbar; +pub mod type_panels_ui; +pub(super) mod variables_ui; #[cfg(test)] use color::color_field_height; -#[cfg(test)] -pub(crate) use color::{hsva_color32, hsva_srgb, srgb_bytes}; pub(crate) use color::{color_field, color_field_fill_id, field_chips, field_hsva, offer_color_field_fill, srgb_hsva}; #[cfg(test)] +pub(crate) use color::{hsva_color32, hsva_srgb, srgb_bytes}; +#[cfg(test)] pub(crate) use dock::DOCK_MIN_WIDTH; -pub use dock::{dock_area, request_dock_width}; pub(crate) use dock::{canvas_panel, dock_body, dock_width_id, dock_width_range}; +pub use dock::{dock_area, request_dock_width}; #[cfg(test)] use history::history; #[cfg(test)] @@ -43,36 +79,36 @@ pub(crate) use history::select_snapshot; pub(crate) use history::selected_snapshot; #[cfg(test)] use info::info_panel; -pub(crate) use info::{sampler_readouts, SamplerReadouts}; +pub(crate) use info::{SamplerReadouts, sampler_readouts}; #[cfg(test)] use layer_drag::{background_drop_refused, layer_drop_payload}; pub(crate) use layer_drag::{dropped_on, layer_drag_edge_scroll}; #[cfg(test)] -use layer_row::{layer_thumb_fit, paint_clipping_indicator}; -#[cfg(test)] pub(crate) use layer_row::thumb_load_badge; #[cfg(test)] +use layer_row::{layer_thumb_fit, paint_clipping_indicator}; +#[cfg(test)] use layers::{layers, opacity_row_layout, simple_lock_toggle}; #[cfg(test)] use navigator::{NAV_ROW_H, navigator, navigator_zoom_drag_id, navigator_zoom_to}; #[cfg(test)] pub(crate) use navigator::{last_navigator_controls, last_navigator_preview}; #[cfg(test)] -use options_bar::options_bar_height; -#[cfg(test)] use options_bar::LAYER_PCT_W; pub use options_bar::options_bar; +#[cfg(test)] +use options_bar::options_bar_height; pub(crate) use options_bar::{FIXED_SIZE_MAX_PX, opt_label}; pub use panel_state::{migrate_panel_state, panel_state_id, remember_panel_state}; +pub use properties::properties_window; #[cfg(test)] use properties::{adjustments_grid, properties_body}; -pub use properties::properties_window; pub use status_bar::{status_bar, status_bar_heights}; #[cfg(test)] use title_bar::title_x; pub use title_bar::{sync_window_title, system_title_bar, title_bar, window_title}; #[cfg(test)] -use toolbar::{chips_height, color_chips, STUDIO_CHIP, tool_flyout_drag_open, tool_flyout_release, TOOL_SECTIONS, toolbar_icon_size, visible_sections}; +use toolbar::{STUDIO_CHIP, TOOL_SECTIONS, chips_height, color_chips, tool_flyout_drag_open, tool_flyout_release, toolbar_icon_size, visible_sections}; pub use toolbar::{paint_toolbar_flyout_indicator, toolbar}; fn c32(c: [f32; 4]) -> Color32 { diff --git a/crates/ui-egui/src/actions.rs b/crates/ui-egui/src/panels/actions.rs similarity index 100% rename from crates/ui-egui/src/actions.rs rename to crates/ui-egui/src/panels/actions.rs diff --git a/crates/ui-egui/src/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs similarity index 99% rename from crates/ui-egui/src/actions/tests.rs rename to crates/ui-egui/src/panels/actions/tests.rs index 3286a65e09..551bcf7b21 100644 --- a/crates/ui-egui/src/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -439,9 +439,7 @@ fn recorded_save_as_and_save_replay_and_write_the_file() { let written = std::rc::Rc::new(std::cell::RefCell::new(Vec::::new())); let log = written.clone(); let services = crate::Services { - export: Some(Box::new(|doc, path, _| { - photocraft_io::export(doc, path, &Default::default()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()) - })), + export: Some(Box::new(|doc, path, _| photocraft_io::export(doc, path, &Default::default()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()))), write: Some(Box::new(move |path, _| { log.borrow_mut().push(path.to_string()); Ok(()) @@ -472,9 +470,7 @@ fn disk_app(answers: Vec>) -> Photo import: Some(Box::new(|name, bytes, opts| { photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()) })), - export: Some(Box::new(|doc, path, _| { - photocraft_io::export(doc, path, &Default::default()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()) - })), + export: Some(Box::new(|doc, path, _| photocraft_io::export(doc, path, &Default::default()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()))), write: Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))), file_dialog: Some(crate::file_dialog::fake(answers).0), ..Default::default() diff --git a/crates/ui-egui/src/adjust_ui.rs b/crates/ui-egui/src/panels/adjust_ui.rs similarity index 100% rename from crates/ui-egui/src/adjust_ui.rs rename to crates/ui-egui/src/panels/adjust_ui.rs diff --git a/crates/ui-egui/src/apply_color.rs b/crates/ui-egui/src/panels/apply_color.rs similarity index 100% rename from crates/ui-egui/src/apply_color.rs rename to crates/ui-egui/src/panels/apply_color.rs diff --git a/crates/ui-egui/src/apply_color/tests.rs b/crates/ui-egui/src/panels/apply_color/tests.rs similarity index 100% rename from crates/ui-egui/src/apply_color/tests.rs rename to crates/ui-egui/src/panels/apply_color/tests.rs diff --git a/crates/ui-egui/src/blend_preview.rs b/crates/ui-egui/src/panels/blend_preview.rs similarity index 100% rename from crates/ui-egui/src/blend_preview.rs rename to crates/ui-egui/src/panels/blend_preview.rs diff --git a/crates/ui-egui/src/blend_preview/tests.rs b/crates/ui-egui/src/panels/blend_preview/tests.rs similarity index 100% rename from crates/ui-egui/src/blend_preview/tests.rs rename to crates/ui-egui/src/panels/blend_preview/tests.rs diff --git a/crates/ui-egui/src/brand.rs b/crates/ui-egui/src/panels/brand.rs similarity index 96% rename from crates/ui-egui/src/brand.rs rename to crates/ui-egui/src/panels/brand.rs index 01cf827d35..1c3a35a2ba 100644 --- a/crates/ui-egui/src/brand.rs +++ b/crates/ui-egui/src/panels/brand.rs @@ -7,7 +7,7 @@ use egui::{Color32, Context, Id, Rect, TextureHandle, TextureOptions, Ui, pos2}; use photocraft_codecs::{ChannelLayout, SampleType}; /// 128 px: sharp at 20 pt on a 3× display, and the mipmaps keep it clean at 1×. -const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.photocraft.png"); +const ICON_PNG: &[u8] = include_bytes!("../../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.photocraft.png"); /// The icon's pixels (one transparent pixel if it couldn't be decoded, which a test rules out). fn decode() -> egui::ColorImage { diff --git a/crates/ui-egui/src/brush_panel.rs b/crates/ui-egui/src/panels/brush_panel.rs similarity index 100% rename from crates/ui-egui/src/brush_panel.rs rename to crates/ui-egui/src/panels/brush_panel.rs diff --git a/crates/ui-egui/src/brush_panel/tests.rs b/crates/ui-egui/src/panels/brush_panel/tests.rs similarity index 100% rename from crates/ui-egui/src/brush_panel/tests.rs rename to crates/ui-egui/src/panels/brush_panel/tests.rs diff --git a/crates/ui-egui/src/brush_preview.rs b/crates/ui-egui/src/panels/brush_preview.rs similarity index 100% rename from crates/ui-egui/src/brush_preview.rs rename to crates/ui-egui/src/panels/brush_preview.rs diff --git a/crates/ui-egui/src/brush_sections.rs b/crates/ui-egui/src/panels/brush_sections.rs similarity index 100% rename from crates/ui-egui/src/brush_sections.rs rename to crates/ui-egui/src/panels/brush_sections.rs diff --git a/crates/ui-egui/src/brush_sections/tests.rs b/crates/ui-egui/src/panels/brush_sections/tests.rs similarity index 100% rename from crates/ui-egui/src/brush_sections/tests.rs rename to crates/ui-egui/src/panels/brush_sections/tests.rs diff --git a/crates/ui-egui/src/brushes_tab.rs b/crates/ui-egui/src/panels/brushes_tab.rs similarity index 100% rename from crates/ui-egui/src/brushes_tab.rs rename to crates/ui-egui/src/panels/brushes_tab.rs diff --git a/crates/ui-egui/src/brushes_tab/tests.rs b/crates/ui-egui/src/panels/brushes_tab/tests.rs similarity index 100% rename from crates/ui-egui/src/brushes_tab/tests.rs rename to crates/ui-egui/src/panels/brushes_tab/tests.rs diff --git a/crates/ui-egui/src/channels_panel.rs b/crates/ui-egui/src/panels/channels_panel.rs similarity index 100% rename from crates/ui-egui/src/channels_panel.rs rename to crates/ui-egui/src/panels/channels_panel.rs diff --git a/crates/ui-egui/src/channels_panel/tests.rs b/crates/ui-egui/src/panels/channels_panel/tests.rs similarity index 100% rename from crates/ui-egui/src/channels_panel/tests.rs rename to crates/ui-egui/src/panels/channels_panel/tests.rs diff --git a/crates/ui-egui/src/chrome_ui.rs b/crates/ui-egui/src/panels/chrome_ui.rs similarity index 100% rename from crates/ui-egui/src/chrome_ui.rs rename to crates/ui-egui/src/panels/chrome_ui.rs diff --git a/crates/ui-egui/src/clip_line_ui.rs b/crates/ui-egui/src/panels/clip_line_ui.rs similarity index 100% rename from crates/ui-egui/src/clip_line_ui.rs rename to crates/ui-egui/src/panels/clip_line_ui.rs diff --git a/crates/ui-egui/src/clip_line_ui/tests.rs b/crates/ui-egui/src/panels/clip_line_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/clip_line_ui/tests.rs rename to crates/ui-egui/src/panels/clip_line_ui/tests.rs diff --git a/crates/ui-egui/src/color_panel_ui.rs b/crates/ui-egui/src/panels/color_panel_ui.rs similarity index 100% rename from crates/ui-egui/src/color_panel_ui.rs rename to crates/ui-egui/src/panels/color_panel_ui.rs diff --git a/crates/ui-egui/src/comps_ui.rs b/crates/ui-egui/src/panels/comps_ui.rs similarity index 100% rename from crates/ui-egui/src/comps_ui.rs rename to crates/ui-egui/src/panels/comps_ui.rs diff --git a/crates/ui-egui/src/doc_props_ui.rs b/crates/ui-egui/src/panels/doc_props_ui.rs similarity index 100% rename from crates/ui-egui/src/doc_props_ui.rs rename to crates/ui-egui/src/panels/doc_props_ui.rs diff --git a/crates/ui-egui/src/histogram_panel.rs b/crates/ui-egui/src/panels/histogram_panel.rs similarity index 100% rename from crates/ui-egui/src/histogram_panel.rs rename to crates/ui-egui/src/panels/histogram_panel.rs diff --git a/crates/ui-egui/src/histogram_panel/tests.rs b/crates/ui-egui/src/panels/histogram_panel/tests.rs similarity index 100% rename from crates/ui-egui/src/histogram_panel/tests.rs rename to crates/ui-egui/src/panels/histogram_panel/tests.rs diff --git a/crates/ui-egui/src/history_menu_ui.rs b/crates/ui-egui/src/panels/history_menu_ui.rs similarity index 100% rename from crates/ui-egui/src/history_menu_ui.rs rename to crates/ui-egui/src/panels/history_menu_ui.rs diff --git a/crates/ui-egui/src/layer_filter_ui.rs b/crates/ui-egui/src/panels/layer_filter_ui.rs similarity index 100% rename from crates/ui-egui/src/layer_filter_ui.rs rename to crates/ui-egui/src/panels/layer_filter_ui.rs diff --git a/crates/ui-egui/src/layer_filter_ui/tests.rs b/crates/ui-egui/src/panels/layer_filter_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/layer_filter_ui/tests.rs rename to crates/ui-egui/src/panels/layer_filter_ui/tests.rs diff --git a/crates/ui-egui/src/layer_menu_ui.rs b/crates/ui-egui/src/panels/layer_menu_ui.rs similarity index 100% rename from crates/ui-egui/src/layer_menu_ui.rs rename to crates/ui-egui/src/panels/layer_menu_ui.rs diff --git a/crates/ui-egui/src/layer_menu_ui/color_tests.rs b/crates/ui-egui/src/panels/layer_menu_ui/color_tests.rs similarity index 100% rename from crates/ui-egui/src/layer_menu_ui/color_tests.rs rename to crates/ui-egui/src/panels/layer_menu_ui/color_tests.rs diff --git a/crates/ui-egui/src/layer_menu_ui/tests.rs b/crates/ui-egui/src/panels/layer_menu_ui/tests.rs similarity index 97% rename from crates/ui-egui/src/layer_menu_ui/tests.rs rename to crates/ui-egui/src/panels/layer_menu_ui/tests.rs index 948a4a373f..f0b0b237e5 100644 --- a/crates/ui-egui/src/layer_menu_ui/tests.rs +++ b/crates/ui-egui/src/panels/layer_menu_ui/tests.rs @@ -133,12 +133,11 @@ fn smart_object_context_menu_edits_the_clicked_layer() { s.execute("paint.stroke", json!({"points": [[100, 100]], "size": 20})).unwrap(); let smart = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap(); s.execute("layer.new.layer", json!({"name": "Other active layer"})).unwrap(); - let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_pixels_per_point(ppp).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe( - move |cc| { + let mut h = + Harness::builder().with_size(vec2(1440.0, 900.0)).with_pixels_per_point(ppp).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); @@ -330,15 +329,13 @@ fn open_multi_selection_menu() -> (egui_kittest::Harness<'static, crate::Photocr let other = s.execute("shape.create", json!({"kind": "rect", "rect": [300, 100, 380, 160]})).unwrap()["layer"].as_u64().unwrap(); s.execute("layer.select", json!({"layer": text})).unwrap(); s.execute("layer.select", json!({"layer": shape, "mode": "add"})).unwrap(); - let mut h = egui_kittest::Harness::builder() - .with_size(vec2(1440.0, 900.0)) - .with_pixels_per_point(1.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 mut h = + egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).with_pixels_per_point(1.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); @@ -400,13 +397,9 @@ fn multi_selection_menu_greys_what_acts_on_one_layer() { /// [`single_layer_only`]; a new single-layer command added to the menu must be classified. #[test] fn single_layer_only_covers_the_per_layer_commands() { - for id in [ - "layer.layerStyle.blendingOptions", - "layer.layerStyle.copyLayerStyle", - "layer.layerMask.enabled", - "layer.layerMask.apply", - "layer.layerMask.delete", - ] { + for id in + ["layer.layerStyle.blendingOptions", "layer.layerStyle.copyLayerStyle", "layer.layerMask.enabled", "layer.layerMask.apply", "layer.layerMask.delete"] + { assert!(single_layer_only(id), "{id}"); } for id in [ @@ -549,8 +542,7 @@ fn every_entry_is_a_known_command() { let mut s = photocraft_engine::Session::new(); s.execute("file.new", json!({"width": 10, "height": 10})).unwrap(); let l = s.active().unwrap().doc.layers[0].clone(); - for (_, id) in entries(&l, false, true).into_iter().chain(entries(&l, false, false)).chain(entries(&l, true, false)).chain(effects_entries()).flatten() - { + for (_, id) in entries(&l, false, true).into_iter().chain(entries(&l, false, false)).chain(entries(&l, true, false)).chain(effects_entries()).flatten() { assert!(crate::menu_catalog::CATALOG.iter().any(|m| m.3 == id) || photocraft_engine::commands::find(id).is_some(), "{id}"); } } diff --git a/crates/ui-egui/src/layer_props_ui.rs b/crates/ui-egui/src/panels/layer_props_ui.rs similarity index 100% rename from crates/ui-egui/src/layer_props_ui.rs rename to crates/ui-egui/src/panels/layer_props_ui.rs diff --git a/crates/ui-egui/src/layer_reveal.rs b/crates/ui-egui/src/panels/layer_reveal.rs similarity index 100% rename from crates/ui-egui/src/layer_reveal.rs rename to crates/ui-egui/src/panels/layer_reveal.rs diff --git a/crates/ui-egui/src/layer_reveal/tests.rs b/crates/ui-egui/src/panels/layer_reveal/tests.rs similarity index 100% rename from crates/ui-egui/src/layer_reveal/tests.rs rename to crates/ui-egui/src/panels/layer_reveal/tests.rs diff --git a/crates/ui-egui/src/layer_row_ui.rs b/crates/ui-egui/src/panels/layer_row_ui.rs similarity index 100% rename from crates/ui-egui/src/layer_row_ui.rs rename to crates/ui-egui/src/panels/layer_row_ui.rs diff --git a/crates/ui-egui/src/layer_row_ui/edit_tests.rs b/crates/ui-egui/src/panels/layer_row_ui/edit_tests.rs similarity index 100% rename from crates/ui-egui/src/layer_row_ui/edit_tests.rs rename to crates/ui-egui/src/panels/layer_row_ui/edit_tests.rs diff --git a/crates/ui-egui/src/layer_row_ui/rename_tests.rs b/crates/ui-egui/src/panels/layer_row_ui/rename_tests.rs similarity index 100% rename from crates/ui-egui/src/layer_row_ui/rename_tests.rs rename to crates/ui-egui/src/panels/layer_row_ui/rename_tests.rs diff --git a/crates/ui-egui/src/layer_row_ui/tests.rs b/crates/ui-egui/src/panels/layer_row_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/layer_row_ui/tests.rs rename to crates/ui-egui/src/panels/layer_row_ui/tests.rs diff --git a/crates/ui-egui/src/layer_transfer.rs b/crates/ui-egui/src/panels/layer_transfer.rs similarity index 100% rename from crates/ui-egui/src/layer_transfer.rs rename to crates/ui-egui/src/panels/layer_transfer.rs diff --git a/crates/ui-egui/src/layer_transfer/tests.rs b/crates/ui-egui/src/panels/layer_transfer/tests.rs similarity index 100% rename from crates/ui-egui/src/layer_transfer/tests.rs rename to crates/ui-egui/src/panels/layer_transfer/tests.rs diff --git a/crates/ui-egui/src/layer_tree_ui.rs b/crates/ui-egui/src/panels/layer_tree_ui.rs similarity index 100% rename from crates/ui-egui/src/layer_tree_ui.rs rename to crates/ui-egui/src/panels/layer_tree_ui.rs diff --git a/crates/ui-egui/src/layer_tree_ui/tests.rs b/crates/ui-egui/src/panels/layer_tree_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/layer_tree_ui/tests.rs rename to crates/ui-egui/src/panels/layer_tree_ui/tests.rs diff --git a/crates/ui-egui/src/layers_panel_ui.rs b/crates/ui-egui/src/panels/layers_panel_ui.rs similarity index 100% rename from crates/ui-egui/src/layers_panel_ui.rs rename to crates/ui-egui/src/panels/layers_panel_ui.rs diff --git a/crates/ui-egui/src/mask_props_ui.rs b/crates/ui-egui/src/panels/mask_props_ui.rs similarity index 100% rename from crates/ui-egui/src/mask_props_ui.rs rename to crates/ui-egui/src/panels/mask_props_ui.rs diff --git a/crates/ui-egui/src/mask_thumbs_ui.rs b/crates/ui-egui/src/panels/mask_thumbs_ui.rs similarity index 100% rename from crates/ui-egui/src/mask_thumbs_ui.rs rename to crates/ui-egui/src/panels/mask_thumbs_ui.rs diff --git a/crates/ui-egui/src/mask_thumbs_ui/tests.rs b/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/mask_thumbs_ui/tests.rs rename to crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panels/panel_docking.rs similarity index 100% rename from crates/ui-egui/src/panel_docking.rs rename to crates/ui-egui/src/panels/panel_docking.rs diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panels/panel_docking/native_tests.rs similarity index 100% rename from crates/ui-egui/src/panel_docking/native_tests.rs rename to crates/ui-egui/src/panels/panel_docking/native_tests.rs diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panels/panel_docking/tests.rs similarity index 99% rename from crates/ui-egui/src/panel_docking/tests.rs rename to crates/ui-egui/src/panels/panel_docking/tests.rs index 2db737f917..fb2fb9bd79 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panels/panel_docking/tests.rs @@ -849,7 +849,7 @@ fn the_dock_can_be_as_wide_as_the_window_allows() { /// keys, and the first change saves a versioned workspace. #[test] fn main_workspace_file_loads_as_the_default_and_saves_as_a_workspace() { - let saved: Value = serde_json::from_str(include_str!("../../tests/fixtures/main-docking-workspace.json")).unwrap(); + let saved: Value = serde_json::from_str(include_str!("../../../tests/fixtures/main-docking-workspace.json")).unwrap(); let mut app = app(); app.ui.theme = crate::theme::ThemeKind::ProMedium; crate::dock::apply(&mut app, &saved); diff --git a/crates/ui-egui/src/preset_panels.rs b/crates/ui-egui/src/panels/preset_panels.rs similarity index 99% rename from crates/ui-egui/src/preset_panels.rs rename to crates/ui-egui/src/panels/preset_panels.rs index b624e53bdd..b06e3145f7 100644 --- a/crates/ui-egui/src/preset_panels.rs +++ b/crates/ui-egui/src/panels/preset_panels.rs @@ -20,9 +20,12 @@ use crate::theme::Tokens; mod panels; +pub use panels::{ + clone_sample_point, clone_source_panel, finish_custom_shape, gradients_panel, patterns_panel, select_tool_preset, shape_picker, shapes_panel, styles_panel, + tool_presets_panel, windows, +}; #[cfg(test)] use panels::{new_tool_preset_params, tool_id}; -pub use panels::{clone_sample_point, clone_source_panel, finish_custom_shape, gradients_panel, patterns_panel, select_tool_preset, shape_picker, shapes_panel, styles_panel, tool_presets_panel, windows}; /// Panel state (serde, so the control channel can read and drive it). #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] diff --git a/crates/ui-egui/src/preset_panels/panels.rs b/crates/ui-egui/src/panels/preset_panels/panels.rs similarity index 100% rename from crates/ui-egui/src/preset_panels/panels.rs rename to crates/ui-egui/src/panels/preset_panels/panels.rs diff --git a/crates/ui-egui/src/props_layout.rs b/crates/ui-egui/src/panels/props_layout.rs similarity index 100% rename from crates/ui-egui/src/props_layout.rs rename to crates/ui-egui/src/panels/props_layout.rs diff --git a/crates/ui-egui/src/props_layout/tests.rs b/crates/ui-egui/src/panels/props_layout/tests.rs similarity index 100% rename from crates/ui-egui/src/props_layout/tests.rs rename to crates/ui-egui/src/panels/props_layout/tests.rs diff --git a/crates/ui-egui/src/smart_ui.rs b/crates/ui-egui/src/panels/smart_ui.rs similarity index 100% rename from crates/ui-egui/src/smart_ui.rs rename to crates/ui-egui/src/panels/smart_ui.rs diff --git a/crates/ui-egui/src/smart_ui/editor_tests.rs b/crates/ui-egui/src/panels/smart_ui/editor_tests.rs similarity index 100% rename from crates/ui-egui/src/smart_ui/editor_tests.rs rename to crates/ui-egui/src/panels/smart_ui/editor_tests.rs diff --git a/crates/ui-egui/src/swatches_ui.rs b/crates/ui-egui/src/panels/swatches_ui.rs similarity index 100% rename from crates/ui-egui/src/swatches_ui.rs rename to crates/ui-egui/src/panels/swatches_ui.rs diff --git a/crates/ui-egui/src/timeline_ui.rs b/crates/ui-egui/src/panels/timeline_ui.rs similarity index 100% rename from crates/ui-egui/src/timeline_ui.rs rename to crates/ui-egui/src/panels/timeline_ui.rs diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/panels/titlebar.rs similarity index 100% rename from crates/ui-egui/src/titlebar.rs rename to crates/ui-egui/src/panels/titlebar.rs diff --git a/crates/ui-egui/src/titlebar/tests.rs b/crates/ui-egui/src/panels/titlebar/tests.rs similarity index 100% rename from crates/ui-egui/src/titlebar/tests.rs rename to crates/ui-egui/src/panels/titlebar/tests.rs diff --git a/crates/ui-egui/src/type_panels_ui.rs b/crates/ui-egui/src/panels/type_panels_ui.rs similarity index 100% rename from crates/ui-egui/src/type_panels_ui.rs rename to crates/ui-egui/src/panels/type_panels_ui.rs diff --git a/crates/ui-egui/src/type_panels_ui/color_picker.rs b/crates/ui-egui/src/panels/type_panels_ui/color_picker.rs similarity index 100% rename from crates/ui-egui/src/type_panels_ui/color_picker.rs rename to crates/ui-egui/src/panels/type_panels_ui/color_picker.rs diff --git a/crates/ui-egui/src/type_panels_ui/color_picker/tests.rs b/crates/ui-egui/src/panels/type_panels_ui/color_picker/tests.rs similarity index 100% rename from crates/ui-egui/src/type_panels_ui/color_picker/tests.rs rename to crates/ui-egui/src/panels/type_panels_ui/color_picker/tests.rs diff --git a/crates/ui-egui/src/variables_ui.rs b/crates/ui-egui/src/panels/variables_ui.rs similarity index 100% rename from crates/ui-egui/src/variables_ui.rs rename to crates/ui-egui/src/panels/variables_ui.rs From b6afd0953dbd3600deba8bec720a0c265c168846 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 21:21:37 +0000 Subject: [PATCH 238/259] refactor(ui-egui): move dialogs modules under dialogs/ --- crates/ui-egui/src/dialogs.rs | 62 +++++++++ .../src/{ => dialogs}/adjust_dialog.rs | 0 .../src/{ => dialogs}/adjust_dialog/tests.rs | 27 ++-- .../src/{ => dialogs}/adjust_editors.rs | 0 .../src/{ => dialogs}/adjust_editors/basic.rs | 0 .../{ => dialogs}/adjust_editors/curves.rs | 0 .../adjust_editors/gradient_map.rs | 0 .../adjust_editors/hue_saturation.rs | 0 .../{ => dialogs}/adjust_editors/levels.rs | 0 .../{ => dialogs}/adjust_editors/session.rs | 0 .../{ => dialogs}/adjust_editors/ui_tests.rs | 0 .../src/{ => dialogs}/adjust_preview.rs | 0 .../src/{ => dialogs}/adjust_preview/tests.rs | 0 .../src/{ => dialogs}/bitmap_dialog.rs | 0 .../src/{ => dialogs}/bitmap_dialog/tests.rs | 0 crates/ui-egui/src/{ => dialogs}/blur_pins.rs | 0 .../src/{ => dialogs}/brush_preset_dialog.rs | 0 .../brush_preset_dialog/tests.rs | 0 crates/ui-egui/src/{ => dialogs}/caf_ui.rs | 0 .../src/{ => dialogs}/caf_ui/controls.rs | 0 .../src/{ => dialogs}/caf_ui/lifecycle.rs | 0 .../src/{ => dialogs}/caf_ui/preview.rs | 0 .../ui-egui/src/{ => dialogs}/caf_ui/tests.rs | 0 .../ui-egui/src/{ => dialogs}/caf_ui/view.rs | 0 .../src/{ => dialogs}/camera_raw_detail_ui.rs | 0 .../src/{ => dialogs}/camera_raw_gpu.rs | 0 .../{ => dialogs}/camera_raw_preview_ui.rs | 0 .../src/{ => dialogs}/camera_raw_scope_ui.rs | 0 .../src/{ => dialogs}/camera_raw_ui.rs | 6 +- .../{ => dialogs}/camera_raw_ui/controls.rs | 0 .../{ => dialogs}/camera_raw_ui/convert.rs | 0 .../camera_raw_ui/identity_tests.rs | 0 .../src/{ => dialogs}/camera_raw_ui/menu.rs | 0 .../src/{ => dialogs}/camera_raw_ui/open.rs | 0 .../src/{ => dialogs}/camera_raw_ui/proxy.rs | 0 .../{ => dialogs}/camera_raw_ui/sidecar.rs | 0 .../src/{ => dialogs}/camera_raw_ui/tests.rs | 0 .../src/{ => dialogs}/channel_options_ui.rs | 0 .../{ => dialogs}/channel_options_ui/tests.rs | 0 .../src/{ => dialogs}/color_picker_ui.rs | 0 .../{ => dialogs}/color_picker_ui/tests.rs | 7 +- .../src/{ => dialogs}/color_range_ui.rs | 0 .../src/{ => dialogs}/color_range_ui/tests.rs | 0 .../src/{ => dialogs}/color_table_ui.rs | 0 crates/ui-egui/src/{ => dialogs}/credits.rs | 0 .../src/{ => dialogs}/credits/ui_tests.rs | 0 .../src/{ => dialogs}/dds_options_ui.rs | 0 .../src/{ => dialogs}/delete_layer_prompt.rs | 0 .../src/{ => dialogs}/dialog_alt_reset.rs | 0 .../src/{ => dialogs}/dialog_blend_ui.rs | 0 .../ui-egui/src/{ => dialogs}/discard_ui.rs | 0 .../src/{ => dialogs}/discard_ui/tests.rs | 0 .../discard_ui/tests/dds_tests.rs | 0 .../discard_ui/tests/jpeg_tests.rs | 0 .../discard_ui/tests/targa_tests.rs | 0 .../discard_ui/tests/tiff_tests.rs | 0 .../src/{ => dialogs}/disk_change_prompt.rs | 0 .../ui-egui/src/{ => dialogs}/distort_ui.rs | 0 .../src/{ => dialogs}/duplicate_layer_ui.rs | 0 .../ui-egui/src/{ => dialogs}/edit_history.rs | 0 .../src/{ => dialogs}/export_dialog.rs | 0 .../src/{ => dialogs}/export_dialog/tests.rs | 5 +- crates/ui-egui/src/{ => dialogs}/file_ui.rs | 10 +- .../src/{ => dialogs}/file_ui/print.rs | 0 .../src/{ => dialogs}/file_ui/tests.rs | 6 +- .../ui-egui/src/{ => dialogs}/file_ui/web.rs | 0 .../src/{ => dialogs}/file_ui/web_preview.rs | 0 crates/ui-egui/src/{ => dialogs}/fill_ui.rs | 0 .../src/{ => dialogs}/fill_ui/tests.rs | 0 .../src/{ => dialogs}/filter_dialog.rs | 0 .../src/{ => dialogs}/filter_dialog/tests.rs | 7 +- .../filter_dialog/zoom_center.rs | 0 .../src/{ => dialogs}/filter_preview_ui.rs | 0 .../{ => dialogs}/filter_preview_worker.rs | 0 .../ui-egui/src/{ => dialogs}/gallery_ui.rs | 0 .../src/{ => dialogs}/gallery_ui/tests.rs | 0 .../src/{ => dialogs}/guide_layout_ui.rs | 0 .../{ => dialogs}/guide_layout_ui/tests.rs | 0 .../src/{ => dialogs}/jpeg_options_ui.rs | 0 .../ui-egui/src/{ => dialogs}/layer_picker.rs | 0 .../ui-egui/src/{ => dialogs}/layer_style.rs | 0 .../layer_style/bevel_modes_tests.rs | 0 .../{ => dialogs}/layer_style/color_picker.rs | 0 .../layer_style/color_picker/tests.rs | 0 .../src/{ => dialogs}/layer_style/contour.rs | 0 .../layer_style/gradient_method_tests.rs | 0 .../src/{ => dialogs}/layer_style/tests.rs | 3 +- .../ui-egui/src/{ => dialogs}/liquify_ui.rs | 0 .../src/{ => dialogs}/liquify_ui/tests.rs | 12 +- .../src/{ => dialogs}/mask_trash_prompt.rs | 0 .../ui-egui/src/{ => dialogs}/new_doc_ui.rs | 0 .../src/{ => dialogs}/new_doc_ui/tests.rs | 11 +- .../ui-egui/src/{ => dialogs}/new_guide_ui.rs | 0 .../src/{ => dialogs}/new_guide_ui/tests.rs | 0 .../ui-egui/src/{ => dialogs}/new_layer_ui.rs | 0 .../ui-egui/src/{ => dialogs}/open_prompt.rs | 0 crates/ui-egui/src/{ => dialogs}/palette.rs | 0 .../src/{ => dialogs}/pattern_fill_ui.rs | 0 .../{ => dialogs}/pattern_fill_ui/tests.rs | 0 .../src/{ => dialogs}/rasterize_prompt.rs | 0 .../{ => dialogs}/rasterize_prompt/tests.rs | 0 .../src/{ => dialogs}/replace_prompt.rs | 0 .../src/{ => dialogs}/rgb_histogram.rs | 0 .../src/{ => dialogs}/screen_picker.rs | 0 .../ui-egui/src/{ => dialogs}/shape_dialog.rs | 0 .../src/{ => dialogs}/shape_dialog/tests.rs | 0 .../src/{ => dialogs}/shape_fill_ui.rs | 0 .../src/{ => dialogs}/shape_fill_ui/tests.rs | 0 crates/ui-egui/src/{ => dialogs}/sizing.rs | 0 .../ui-egui/src/{ => dialogs}/sizing/tests.rs | 0 .../src/{ => dialogs}/smart_filter_dialog.rs | 0 .../smart_filter_dialog/tests.rs | 0 .../src/{ => dialogs}/snapshot_dialog.rs | 0 .../src/{ => dialogs}/solid_fill_ui.rs | 0 .../src/{ => dialogs}/solid_fill_ui/tests.rs | 0 .../ui-egui/src/{ => dialogs}/stack_dialog.rs | 0 .../src/{ => dialogs}/stack_dialog/tests.rs | 0 crates/ui-egui/src/{ => dialogs}/stroke_ui.rs | 0 .../src/{ => dialogs}/stroke_ui/tests.rs | 0 .../src/{ => dialogs}/targa_options_ui.rs | 0 .../src/{ => dialogs}/tiff_options_ui.rs | 0 crates/ui-egui/src/{ => dialogs}/vp_ui.rs | 0 .../ui-egui/src/{ => dialogs}/vp_ui/tests.rs | 0 .../src/{ => dialogs}/wide_angle_ui.rs | 0 crates/ui-egui/src/lib.rs | 124 +++++++++--------- 125 files changed, 155 insertions(+), 125 deletions(-) rename crates/ui-egui/src/{ => dialogs}/adjust_dialog.rs (100%) rename crates/ui-egui/src/{ => dialogs}/adjust_dialog/tests.rs (97%) rename crates/ui-egui/src/{ => dialogs}/adjust_editors.rs (100%) rename crates/ui-egui/src/{ => dialogs}/adjust_editors/basic.rs (100%) rename crates/ui-egui/src/{ => dialogs}/adjust_editors/curves.rs (100%) rename crates/ui-egui/src/{ => dialogs}/adjust_editors/gradient_map.rs (100%) rename crates/ui-egui/src/{ => dialogs}/adjust_editors/hue_saturation.rs (100%) rename crates/ui-egui/src/{ => dialogs}/adjust_editors/levels.rs (100%) rename crates/ui-egui/src/{ => dialogs}/adjust_editors/session.rs (100%) rename crates/ui-egui/src/{ => dialogs}/adjust_editors/ui_tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/adjust_preview.rs (100%) rename crates/ui-egui/src/{ => dialogs}/adjust_preview/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/bitmap_dialog.rs (100%) rename crates/ui-egui/src/{ => dialogs}/bitmap_dialog/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/blur_pins.rs (100%) rename crates/ui-egui/src/{ => dialogs}/brush_preset_dialog.rs (100%) rename crates/ui-egui/src/{ => dialogs}/brush_preset_dialog/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/caf_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/caf_ui/controls.rs (100%) rename crates/ui-egui/src/{ => dialogs}/caf_ui/lifecycle.rs (100%) rename crates/ui-egui/src/{ => dialogs}/caf_ui/preview.rs (100%) rename crates/ui-egui/src/{ => dialogs}/caf_ui/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/caf_ui/view.rs (100%) rename crates/ui-egui/src/{ => dialogs}/camera_raw_detail_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/camera_raw_gpu.rs (100%) rename crates/ui-egui/src/{ => dialogs}/camera_raw_preview_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/camera_raw_scope_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/camera_raw_ui.rs (98%) rename crates/ui-egui/src/{ => dialogs}/camera_raw_ui/controls.rs (100%) rename crates/ui-egui/src/{ => dialogs}/camera_raw_ui/convert.rs (100%) rename crates/ui-egui/src/{ => dialogs}/camera_raw_ui/identity_tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/camera_raw_ui/menu.rs (100%) rename crates/ui-egui/src/{ => dialogs}/camera_raw_ui/open.rs (100%) rename crates/ui-egui/src/{ => dialogs}/camera_raw_ui/proxy.rs (100%) rename crates/ui-egui/src/{ => dialogs}/camera_raw_ui/sidecar.rs (100%) rename crates/ui-egui/src/{ => dialogs}/camera_raw_ui/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/channel_options_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/channel_options_ui/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/color_picker_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/color_picker_ui/tests.rs (99%) rename crates/ui-egui/src/{ => dialogs}/color_range_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/color_range_ui/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/color_table_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/credits.rs (100%) rename crates/ui-egui/src/{ => dialogs}/credits/ui_tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/dds_options_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/delete_layer_prompt.rs (100%) rename crates/ui-egui/src/{ => dialogs}/dialog_alt_reset.rs (100%) rename crates/ui-egui/src/{ => dialogs}/dialog_blend_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/discard_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/discard_ui/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/discard_ui/tests/dds_tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/discard_ui/tests/jpeg_tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/discard_ui/tests/targa_tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/discard_ui/tests/tiff_tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/disk_change_prompt.rs (100%) rename crates/ui-egui/src/{ => dialogs}/distort_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/duplicate_layer_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/edit_history.rs (100%) rename crates/ui-egui/src/{ => dialogs}/export_dialog.rs (100%) rename crates/ui-egui/src/{ => dialogs}/export_dialog/tests.rs (99%) rename crates/ui-egui/src/{ => dialogs}/file_ui.rs (99%) rename crates/ui-egui/src/{ => dialogs}/file_ui/print.rs (100%) rename crates/ui-egui/src/{ => dialogs}/file_ui/tests.rs (99%) rename crates/ui-egui/src/{ => dialogs}/file_ui/web.rs (100%) rename crates/ui-egui/src/{ => dialogs}/file_ui/web_preview.rs (100%) rename crates/ui-egui/src/{ => dialogs}/fill_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/fill_ui/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/filter_dialog.rs (100%) rename crates/ui-egui/src/{ => dialogs}/filter_dialog/tests.rs (99%) rename crates/ui-egui/src/{ => dialogs}/filter_dialog/zoom_center.rs (100%) rename crates/ui-egui/src/{ => dialogs}/filter_preview_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/filter_preview_worker.rs (100%) rename crates/ui-egui/src/{ => dialogs}/gallery_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/gallery_ui/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/guide_layout_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/guide_layout_ui/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/jpeg_options_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/layer_picker.rs (100%) rename crates/ui-egui/src/{ => dialogs}/layer_style.rs (100%) rename crates/ui-egui/src/{ => dialogs}/layer_style/bevel_modes_tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/layer_style/color_picker.rs (100%) rename crates/ui-egui/src/{ => dialogs}/layer_style/color_picker/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/layer_style/contour.rs (100%) rename crates/ui-egui/src/{ => dialogs}/layer_style/gradient_method_tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/layer_style/tests.rs (99%) rename crates/ui-egui/src/{ => dialogs}/liquify_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/liquify_ui/tests.rs (99%) rename crates/ui-egui/src/{ => dialogs}/mask_trash_prompt.rs (100%) rename crates/ui-egui/src/{ => dialogs}/new_doc_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/new_doc_ui/tests.rs (99%) rename crates/ui-egui/src/{ => dialogs}/new_guide_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/new_guide_ui/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/new_layer_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/open_prompt.rs (100%) rename crates/ui-egui/src/{ => dialogs}/palette.rs (100%) rename crates/ui-egui/src/{ => dialogs}/pattern_fill_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/pattern_fill_ui/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/rasterize_prompt.rs (100%) rename crates/ui-egui/src/{ => dialogs}/rasterize_prompt/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/replace_prompt.rs (100%) rename crates/ui-egui/src/{ => dialogs}/rgb_histogram.rs (100%) rename crates/ui-egui/src/{ => dialogs}/screen_picker.rs (100%) rename crates/ui-egui/src/{ => dialogs}/shape_dialog.rs (100%) rename crates/ui-egui/src/{ => dialogs}/shape_dialog/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/shape_fill_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/shape_fill_ui/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/sizing.rs (100%) rename crates/ui-egui/src/{ => dialogs}/sizing/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/smart_filter_dialog.rs (100%) rename crates/ui-egui/src/{ => dialogs}/smart_filter_dialog/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/snapshot_dialog.rs (100%) rename crates/ui-egui/src/{ => dialogs}/solid_fill_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/solid_fill_ui/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/stack_dialog.rs (100%) rename crates/ui-egui/src/{ => dialogs}/stack_dialog/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/stroke_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/stroke_ui/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/targa_options_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/tiff_options_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/vp_ui.rs (100%) rename crates/ui-egui/src/{ => dialogs}/vp_ui/tests.rs (100%) rename crates/ui-egui/src/{ => dialogs}/wide_angle_ui.rs (100%) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e99864ded8..c9d6f46d68 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -979,8 +979,70 @@ pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str) app.ui.open_dialog(DialogKind::Command, fields) } +pub mod adjust_dialog; +pub mod adjust_editors; +pub mod adjust_preview; +pub(crate) mod bitmap_dialog; +pub mod blur_pins; +pub mod brush_preset_dialog; +pub mod caf_ui; +pub(super) mod camera_raw_detail_ui; +pub(super) mod camera_raw_gpu; +pub(super) mod camera_raw_preview_ui; +pub(super) mod camera_raw_scope_ui; +pub mod camera_raw_ui; +pub mod channel_options_ui; +pub mod color_picker_ui; +pub mod color_range_ui; +pub mod color_table_ui; +pub mod credits; +pub mod dds_options_ui; +pub mod delete_layer_prompt; +pub mod dialog_alt_reset; +pub mod dialog_blend_ui; +pub mod discard_ui; +pub mod disk_change_prompt; +pub mod distort_ui; +pub mod duplicate_layer_ui; +pub mod edit_history; +pub mod export_dialog; +pub mod file_ui; +pub mod fill_ui; +pub mod filter_dialog; +pub(super) mod filter_preview_ui; +#[cfg(not(target_arch = "wasm32"))] +pub(super) mod filter_preview_worker; +pub mod gallery_ui; +pub mod guide_layout_ui; +pub mod jpeg_options_ui; +pub mod layer_picker; +pub mod layer_style; +pub mod liquify_ui; +pub mod mask_trash_prompt; +pub mod new_doc_ui; +pub mod new_guide_ui; +pub mod new_layer_ui; +pub mod open_prompt; +pub mod palette; +pub(crate) mod pattern_fill_ui; +pub mod rasterize_prompt; +pub mod replace_prompt; +pub(super) mod rgb_histogram; +pub mod screen_picker; +pub mod shape_dialog; +pub(crate) mod shape_fill_ui; +pub(super) mod sizing; +pub mod smart_filter_dialog; +pub mod snapshot_dialog; +pub(crate) mod solid_fill_ui; +pub mod stack_dialog; +pub mod stroke_ui; +pub mod targa_options_ui; #[cfg(test)] mod tests; +pub mod tiff_options_ui; +pub mod vp_ui; +pub mod wide_angle_ui; #[cfg(test)] mod preference_resize_tests { diff --git a/crates/ui-egui/src/adjust_dialog.rs b/crates/ui-egui/src/dialogs/adjust_dialog.rs similarity index 100% rename from crates/ui-egui/src/adjust_dialog.rs rename to crates/ui-egui/src/dialogs/adjust_dialog.rs diff --git a/crates/ui-egui/src/adjust_dialog/tests.rs b/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs similarity index 97% rename from crates/ui-egui/src/adjust_dialog/tests.rs rename to crates/ui-egui/src/dialogs/adjust_dialog/tests.rs index e8bee2b4c7..d3bcf2b688 100644 --- a/crates/ui-egui/src/adjust_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog/tests.rs @@ -101,8 +101,7 @@ fn color_balance_dialog() -> (Harness<'static, PhotocraftApp>, u64) { PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); let id = open(h.state_mut(), "image.adjustments.colorBalance").unwrap(); let d = h.state_mut().ui.dialog_mut(id).unwrap(); - for (k, v) in - [("shadows", json!([10, 0, 0])), ("midtones", json!([40, -30, 20])), ("highlights", json!([0, 0, -15])), ("preserveLuminosity", json!(false))] + for (k, v) in [("shadows", json!([10, 0, 0])), ("midtones", json!([40, -30, 20])), ("highlights", json!([0, 0, -15])), ("preserveLuminosity", json!(false))] { d.fields.insert(k.into(), v); } @@ -166,8 +165,7 @@ fn color_balance_dialog_gestures_match_photoshop() { h.run_steps(2); let reset = h.get_by_label("Reset").rect(); assert!(h.query_by_label("Cancel").is_none()); - let click = - |pressed| egui::Event::PointerButton { pos: reset.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; + let click = |pressed| egui::Event::PointerButton { pos: reset.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; input(&mut h, egui::Modifiers::ALT, &[egui::Event::PointerMoved(reset.center()), click(true), click(false)]); assert!(h.state().ui.dialogs.iter().any(|d| d.id == id), "Reset keeps the dialog open"); for k in ["shadows", "midtones", "highlights"] { @@ -177,8 +175,7 @@ fn color_balance_dialog_gestures_match_photoshop() { assert_eq!(h.ctx.data(|d| d.get_temp::(tone)), Some(1), "Reset shows Midtones"); // Without Alt it is Cancel again, and it closes. let cancel = h.get_by_label("Cancel").rect(); - let click = - |pressed| egui::Event::PointerButton { pos: cancel.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let click = |pressed| egui::Event::PointerButton { pos: cancel.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; input(&mut h, egui::Modifiers::NONE, &[egui::Event::PointerMoved(cancel.center()), click(true), click(false)]); assert!(h.state().ui.dialogs.is_empty(), "Cancel closes"); } @@ -198,8 +195,7 @@ fn levels_alt_reset_restores_defaults() { h.run_steps(2); let reset = h.get_by_label("Reset").rect(); assert!(h.query_by_label("Cancel").is_none()); - let click = - |pressed| egui::Event::PointerButton { pos: reset.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; + let click = |pressed| egui::Event::PointerButton { pos: reset.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; input(&mut h, egui::Modifiers::ALT, &[egui::Event::PointerMoved(reset.center()), click(true), click(false)]); assert!(h.state().ui.dialogs.iter().any(|d| d.id == id), "Reset keeps the dialog open"); let defaults = @@ -335,8 +331,7 @@ fn curves_graph_never_pushes_the_dialog_off_a_short_window() { #[test] fn cancel_leaves_the_document_untouched() { - let mut harness = - Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + let mut harness = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); let id = open(harness.state_mut(), "image.adjustments.curves").unwrap(); harness.run_steps(2); @@ -589,18 +584,13 @@ fn curves_picker_modes_and_depths_are_explicit() { assert!((neutral_anchor[1] - serialized_target_level).abs() < 1e-5, "depth={depth} anchor={neutral_anchor:?} sampled={sampled:?}"); assert!((neutral_anchor[0] - sample_level).abs() <= 0.0051, "depth={depth} anchor={neutral_anchor:?} sampled={}", sampled[0]); if depth == 16 || depth == 32 { - assert!( - (sampled[0] * 255.0 - (sampled[0] * 255.0).round()).abs() > 0.01, - "depth={depth} sample was quantized to an 8-bit level: {}", - sampled[0] - ); + assert!((sampled[0] * 255.0 - (sampled[0] * 255.0).round()).abs() > 0.01, "depth={depth} sample was quantized to an 8-bit level: {}", sampled[0]); } } } fn pointer_down(app: &mut PhotocraftApp, ctx: &egui::Context, x: f64, y: f64, modifiers: Value) { - let (request, _receiver) = - crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "down", "x": x, "y": y}], "modifiers": modifiers})); + let (request, _receiver) = crate::control::ControlRequest::new("ui.pointer", json!({"events": [{"kind": "down", "x": x, "y": y}], "modifiers": modifiers})); let _ = crate::control::handle(app, ctx, &request); } @@ -697,8 +687,7 @@ fn command_click_adds_nothing_without_the_modifier_on_a_full_curve_or_with_an_ey } // Sixteen points (the most a curve holds), none within reach of level 86. - let full: Vec<[f64; 2]> = - [0, 10, 20, 30, 40, 50, 60, 70, 80, 100, 120, 140, 160, 180, 200, 255].iter().map(|&i| [f64::from(i), f64::from(i)]).collect(); + let full: Vec<[f64; 2]> = [0, 10, 20, 30, 40, 50, 60, 70, 80, 100, 120, 140, 160, 180, 200, 255].iter().map(|&i| [f64::from(i), f64::from(i)]).collect(); app.ui.dialog_mut(id).unwrap().fields.insert("points".into(), json!(full)); pointer_down(&mut app, &ctx, 8.0, 8.0, json!({"command": true})); assert_eq!(channel_points(&app, "points"), full, "a full curve takes no more points and moves none"); diff --git a/crates/ui-egui/src/adjust_editors.rs b/crates/ui-egui/src/dialogs/adjust_editors.rs similarity index 100% rename from crates/ui-egui/src/adjust_editors.rs rename to crates/ui-egui/src/dialogs/adjust_editors.rs diff --git a/crates/ui-egui/src/adjust_editors/basic.rs b/crates/ui-egui/src/dialogs/adjust_editors/basic.rs similarity index 100% rename from crates/ui-egui/src/adjust_editors/basic.rs rename to crates/ui-egui/src/dialogs/adjust_editors/basic.rs diff --git a/crates/ui-egui/src/adjust_editors/curves.rs b/crates/ui-egui/src/dialogs/adjust_editors/curves.rs similarity index 100% rename from crates/ui-egui/src/adjust_editors/curves.rs rename to crates/ui-egui/src/dialogs/adjust_editors/curves.rs diff --git a/crates/ui-egui/src/adjust_editors/gradient_map.rs b/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs similarity index 100% rename from crates/ui-egui/src/adjust_editors/gradient_map.rs rename to crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs diff --git a/crates/ui-egui/src/adjust_editors/hue_saturation.rs b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs similarity index 100% rename from crates/ui-egui/src/adjust_editors/hue_saturation.rs rename to crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs diff --git a/crates/ui-egui/src/adjust_editors/levels.rs b/crates/ui-egui/src/dialogs/adjust_editors/levels.rs similarity index 100% rename from crates/ui-egui/src/adjust_editors/levels.rs rename to crates/ui-egui/src/dialogs/adjust_editors/levels.rs diff --git a/crates/ui-egui/src/adjust_editors/session.rs b/crates/ui-egui/src/dialogs/adjust_editors/session.rs similarity index 100% rename from crates/ui-egui/src/adjust_editors/session.rs rename to crates/ui-egui/src/dialogs/adjust_editors/session.rs diff --git a/crates/ui-egui/src/adjust_editors/ui_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs similarity index 100% rename from crates/ui-egui/src/adjust_editors/ui_tests.rs rename to crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs diff --git a/crates/ui-egui/src/adjust_preview.rs b/crates/ui-egui/src/dialogs/adjust_preview.rs similarity index 100% rename from crates/ui-egui/src/adjust_preview.rs rename to crates/ui-egui/src/dialogs/adjust_preview.rs diff --git a/crates/ui-egui/src/adjust_preview/tests.rs b/crates/ui-egui/src/dialogs/adjust_preview/tests.rs similarity index 100% rename from crates/ui-egui/src/adjust_preview/tests.rs rename to crates/ui-egui/src/dialogs/adjust_preview/tests.rs diff --git a/crates/ui-egui/src/bitmap_dialog.rs b/crates/ui-egui/src/dialogs/bitmap_dialog.rs similarity index 100% rename from crates/ui-egui/src/bitmap_dialog.rs rename to crates/ui-egui/src/dialogs/bitmap_dialog.rs diff --git a/crates/ui-egui/src/bitmap_dialog/tests.rs b/crates/ui-egui/src/dialogs/bitmap_dialog/tests.rs similarity index 100% rename from crates/ui-egui/src/bitmap_dialog/tests.rs rename to crates/ui-egui/src/dialogs/bitmap_dialog/tests.rs diff --git a/crates/ui-egui/src/blur_pins.rs b/crates/ui-egui/src/dialogs/blur_pins.rs similarity index 100% rename from crates/ui-egui/src/blur_pins.rs rename to crates/ui-egui/src/dialogs/blur_pins.rs diff --git a/crates/ui-egui/src/brush_preset_dialog.rs b/crates/ui-egui/src/dialogs/brush_preset_dialog.rs similarity index 100% rename from crates/ui-egui/src/brush_preset_dialog.rs rename to crates/ui-egui/src/dialogs/brush_preset_dialog.rs diff --git a/crates/ui-egui/src/brush_preset_dialog/tests.rs b/crates/ui-egui/src/dialogs/brush_preset_dialog/tests.rs similarity index 100% rename from crates/ui-egui/src/brush_preset_dialog/tests.rs rename to crates/ui-egui/src/dialogs/brush_preset_dialog/tests.rs diff --git a/crates/ui-egui/src/caf_ui.rs b/crates/ui-egui/src/dialogs/caf_ui.rs similarity index 100% rename from crates/ui-egui/src/caf_ui.rs rename to crates/ui-egui/src/dialogs/caf_ui.rs diff --git a/crates/ui-egui/src/caf_ui/controls.rs b/crates/ui-egui/src/dialogs/caf_ui/controls.rs similarity index 100% rename from crates/ui-egui/src/caf_ui/controls.rs rename to crates/ui-egui/src/dialogs/caf_ui/controls.rs diff --git a/crates/ui-egui/src/caf_ui/lifecycle.rs b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs similarity index 100% rename from crates/ui-egui/src/caf_ui/lifecycle.rs rename to crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs diff --git a/crates/ui-egui/src/caf_ui/preview.rs b/crates/ui-egui/src/dialogs/caf_ui/preview.rs similarity index 100% rename from crates/ui-egui/src/caf_ui/preview.rs rename to crates/ui-egui/src/dialogs/caf_ui/preview.rs diff --git a/crates/ui-egui/src/caf_ui/tests.rs b/crates/ui-egui/src/dialogs/caf_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/caf_ui/tests.rs rename to crates/ui-egui/src/dialogs/caf_ui/tests.rs diff --git a/crates/ui-egui/src/caf_ui/view.rs b/crates/ui-egui/src/dialogs/caf_ui/view.rs similarity index 100% rename from crates/ui-egui/src/caf_ui/view.rs rename to crates/ui-egui/src/dialogs/caf_ui/view.rs diff --git a/crates/ui-egui/src/camera_raw_detail_ui.rs b/crates/ui-egui/src/dialogs/camera_raw_detail_ui.rs similarity index 100% rename from crates/ui-egui/src/camera_raw_detail_ui.rs rename to crates/ui-egui/src/dialogs/camera_raw_detail_ui.rs diff --git a/crates/ui-egui/src/camera_raw_gpu.rs b/crates/ui-egui/src/dialogs/camera_raw_gpu.rs similarity index 100% rename from crates/ui-egui/src/camera_raw_gpu.rs rename to crates/ui-egui/src/dialogs/camera_raw_gpu.rs diff --git a/crates/ui-egui/src/camera_raw_preview_ui.rs b/crates/ui-egui/src/dialogs/camera_raw_preview_ui.rs similarity index 100% rename from crates/ui-egui/src/camera_raw_preview_ui.rs rename to crates/ui-egui/src/dialogs/camera_raw_preview_ui.rs diff --git a/crates/ui-egui/src/camera_raw_scope_ui.rs b/crates/ui-egui/src/dialogs/camera_raw_scope_ui.rs similarity index 100% rename from crates/ui-egui/src/camera_raw_scope_ui.rs rename to crates/ui-egui/src/dialogs/camera_raw_scope_ui.rs diff --git a/crates/ui-egui/src/camera_raw_ui.rs b/crates/ui-egui/src/dialogs/camera_raw_ui.rs similarity index 98% rename from crates/ui-egui/src/camera_raw_ui.rs rename to crates/ui-egui/src/dialogs/camera_raw_ui.rs index 85dc6d011c..e920b95da8 100644 --- a/crates/ui-egui/src/camera_raw_ui.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui.rs @@ -75,7 +75,7 @@ pub struct CameraRawDialog { pub(crate) full_w: usize, full_h: usize, preview_ppp: f32, - pub(crate) detail: super::camera_raw_detail_ui::DetailPreview, + pub(crate) detail: crate::camera_raw_detail_ui::DetailPreview, display: std::sync::Arc, pub(crate) viewport: Option, pub(crate) float: bool, @@ -86,7 +86,7 @@ pub struct CameraRawDialog { pub(crate) processed: Vec<[f32; 4]>, pub(crate) lab_transform: std::sync::Arc, pub(crate) scope_transform: std::sync::Arc, - pub(crate) scope: super::camera_raw_scope_ui::ScopeView, + pub(crate) scope: crate::camera_raw_scope_ui::ScopeView, pub(crate) after_histogram: RgbHistogram, pub(crate) preview_revision: u64, histogram_ms: f64, @@ -173,7 +173,7 @@ impl CameraRawDialog { fn image(px: &[[f32; 4]], w: usize, h: usize, display: &photocraft_engine::display_color::CanvasDisplay) -> egui::ColorImage { // Bands copied straight from `px`, converted in parallel (#4682), not a whole copy of the // proxy converted on one thread. - super::camera_raw_detail_ui::display_image(Rect::new(0, 0, w as i32, h as i32), display, |r, out| { + crate::camera_raw_detail_ui::display_image(Rect::new(0, 0, w as i32, h as i32), display, |r, out| { let start = (r.y0.max(0) as usize).saturating_mul(w); if let Some(src) = px.get(start..start.saturating_add(out.len())) { out.copy_from_slice(src); diff --git a/crates/ui-egui/src/camera_raw_ui/controls.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs similarity index 100% rename from crates/ui-egui/src/camera_raw_ui/controls.rs rename to crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs diff --git a/crates/ui-egui/src/camera_raw_ui/convert.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs similarity index 100% rename from crates/ui-egui/src/camera_raw_ui/convert.rs rename to crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs diff --git a/crates/ui-egui/src/camera_raw_ui/identity_tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/identity_tests.rs similarity index 100% rename from crates/ui-egui/src/camera_raw_ui/identity_tests.rs rename to crates/ui-egui/src/dialogs/camera_raw_ui/identity_tests.rs diff --git a/crates/ui-egui/src/camera_raw_ui/menu.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/menu.rs similarity index 100% rename from crates/ui-egui/src/camera_raw_ui/menu.rs rename to crates/ui-egui/src/dialogs/camera_raw_ui/menu.rs diff --git a/crates/ui-egui/src/camera_raw_ui/open.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs similarity index 100% rename from crates/ui-egui/src/camera_raw_ui/open.rs rename to crates/ui-egui/src/dialogs/camera_raw_ui/open.rs diff --git a/crates/ui-egui/src/camera_raw_ui/proxy.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/proxy.rs similarity index 100% rename from crates/ui-egui/src/camera_raw_ui/proxy.rs rename to crates/ui-egui/src/dialogs/camera_raw_ui/proxy.rs diff --git a/crates/ui-egui/src/camera_raw_ui/sidecar.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/sidecar.rs similarity index 100% rename from crates/ui-egui/src/camera_raw_ui/sidecar.rs rename to crates/ui-egui/src/dialogs/camera_raw_ui/sidecar.rs diff --git a/crates/ui-egui/src/camera_raw_ui/tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/camera_raw_ui/tests.rs rename to crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs diff --git a/crates/ui-egui/src/channel_options_ui.rs b/crates/ui-egui/src/dialogs/channel_options_ui.rs similarity index 100% rename from crates/ui-egui/src/channel_options_ui.rs rename to crates/ui-egui/src/dialogs/channel_options_ui.rs diff --git a/crates/ui-egui/src/channel_options_ui/tests.rs b/crates/ui-egui/src/dialogs/channel_options_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/channel_options_ui/tests.rs rename to crates/ui-egui/src/dialogs/channel_options_ui/tests.rs diff --git a/crates/ui-egui/src/color_picker_ui.rs b/crates/ui-egui/src/dialogs/color_picker_ui.rs similarity index 100% rename from crates/ui-egui/src/color_picker_ui.rs rename to crates/ui-egui/src/dialogs/color_picker_ui.rs diff --git a/crates/ui-egui/src/color_picker_ui/tests.rs b/crates/ui-egui/src/dialogs/color_picker_ui/tests.rs similarity index 99% rename from crates/ui-egui/src/color_picker_ui/tests.rs rename to crates/ui-egui/src/dialogs/color_picker_ui/tests.rs index 02f6b0af20..0ef4eb1ec0 100644 --- a/crates/ui-egui/src/color_picker_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker_ui/tests.rs @@ -93,12 +93,7 @@ fn field_and_slider_pick_on_press_and_follow_small_moves() { h.event(egui::Event::PointerMoved(at + vec2(3.0, 0.0))); h.run_steps(1); assert_ne!(color(&h), picked, "a small drag adjusts the pick"); - h.event(egui::Event::PointerButton { - pos: at + vec2(3.0, 0.0), - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }); + h.event(egui::Event::PointerButton { pos: at + vec2(3.0, 0.0), button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); h.run_steps(2); // Hue slider: a press near the bottom picks a hue near 0 at once. let before = color(&h); diff --git a/crates/ui-egui/src/color_range_ui.rs b/crates/ui-egui/src/dialogs/color_range_ui.rs similarity index 100% rename from crates/ui-egui/src/color_range_ui.rs rename to crates/ui-egui/src/dialogs/color_range_ui.rs diff --git a/crates/ui-egui/src/color_range_ui/tests.rs b/crates/ui-egui/src/dialogs/color_range_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/color_range_ui/tests.rs rename to crates/ui-egui/src/dialogs/color_range_ui/tests.rs diff --git a/crates/ui-egui/src/color_table_ui.rs b/crates/ui-egui/src/dialogs/color_table_ui.rs similarity index 100% rename from crates/ui-egui/src/color_table_ui.rs rename to crates/ui-egui/src/dialogs/color_table_ui.rs diff --git a/crates/ui-egui/src/credits.rs b/crates/ui-egui/src/dialogs/credits.rs similarity index 100% rename from crates/ui-egui/src/credits.rs rename to crates/ui-egui/src/dialogs/credits.rs diff --git a/crates/ui-egui/src/credits/ui_tests.rs b/crates/ui-egui/src/dialogs/credits/ui_tests.rs similarity index 100% rename from crates/ui-egui/src/credits/ui_tests.rs rename to crates/ui-egui/src/dialogs/credits/ui_tests.rs diff --git a/crates/ui-egui/src/dds_options_ui.rs b/crates/ui-egui/src/dialogs/dds_options_ui.rs similarity index 100% rename from crates/ui-egui/src/dds_options_ui.rs rename to crates/ui-egui/src/dialogs/dds_options_ui.rs diff --git a/crates/ui-egui/src/delete_layer_prompt.rs b/crates/ui-egui/src/dialogs/delete_layer_prompt.rs similarity index 100% rename from crates/ui-egui/src/delete_layer_prompt.rs rename to crates/ui-egui/src/dialogs/delete_layer_prompt.rs diff --git a/crates/ui-egui/src/dialog_alt_reset.rs b/crates/ui-egui/src/dialogs/dialog_alt_reset.rs similarity index 100% rename from crates/ui-egui/src/dialog_alt_reset.rs rename to crates/ui-egui/src/dialogs/dialog_alt_reset.rs diff --git a/crates/ui-egui/src/dialog_blend_ui.rs b/crates/ui-egui/src/dialogs/dialog_blend_ui.rs similarity index 100% rename from crates/ui-egui/src/dialog_blend_ui.rs rename to crates/ui-egui/src/dialogs/dialog_blend_ui.rs diff --git a/crates/ui-egui/src/discard_ui.rs b/crates/ui-egui/src/dialogs/discard_ui.rs similarity index 100% rename from crates/ui-egui/src/discard_ui.rs rename to crates/ui-egui/src/dialogs/discard_ui.rs diff --git a/crates/ui-egui/src/discard_ui/tests.rs b/crates/ui-egui/src/dialogs/discard_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/discard_ui/tests.rs rename to crates/ui-egui/src/dialogs/discard_ui/tests.rs diff --git a/crates/ui-egui/src/discard_ui/tests/dds_tests.rs b/crates/ui-egui/src/dialogs/discard_ui/tests/dds_tests.rs similarity index 100% rename from crates/ui-egui/src/discard_ui/tests/dds_tests.rs rename to crates/ui-egui/src/dialogs/discard_ui/tests/dds_tests.rs diff --git a/crates/ui-egui/src/discard_ui/tests/jpeg_tests.rs b/crates/ui-egui/src/dialogs/discard_ui/tests/jpeg_tests.rs similarity index 100% rename from crates/ui-egui/src/discard_ui/tests/jpeg_tests.rs rename to crates/ui-egui/src/dialogs/discard_ui/tests/jpeg_tests.rs diff --git a/crates/ui-egui/src/discard_ui/tests/targa_tests.rs b/crates/ui-egui/src/dialogs/discard_ui/tests/targa_tests.rs similarity index 100% rename from crates/ui-egui/src/discard_ui/tests/targa_tests.rs rename to crates/ui-egui/src/dialogs/discard_ui/tests/targa_tests.rs diff --git a/crates/ui-egui/src/discard_ui/tests/tiff_tests.rs b/crates/ui-egui/src/dialogs/discard_ui/tests/tiff_tests.rs similarity index 100% rename from crates/ui-egui/src/discard_ui/tests/tiff_tests.rs rename to crates/ui-egui/src/dialogs/discard_ui/tests/tiff_tests.rs diff --git a/crates/ui-egui/src/disk_change_prompt.rs b/crates/ui-egui/src/dialogs/disk_change_prompt.rs similarity index 100% rename from crates/ui-egui/src/disk_change_prompt.rs rename to crates/ui-egui/src/dialogs/disk_change_prompt.rs diff --git a/crates/ui-egui/src/distort_ui.rs b/crates/ui-egui/src/dialogs/distort_ui.rs similarity index 100% rename from crates/ui-egui/src/distort_ui.rs rename to crates/ui-egui/src/dialogs/distort_ui.rs diff --git a/crates/ui-egui/src/duplicate_layer_ui.rs b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs similarity index 100% rename from crates/ui-egui/src/duplicate_layer_ui.rs rename to crates/ui-egui/src/dialogs/duplicate_layer_ui.rs diff --git a/crates/ui-egui/src/edit_history.rs b/crates/ui-egui/src/dialogs/edit_history.rs similarity index 100% rename from crates/ui-egui/src/edit_history.rs rename to crates/ui-egui/src/dialogs/edit_history.rs diff --git a/crates/ui-egui/src/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs similarity index 100% rename from crates/ui-egui/src/export_dialog.rs rename to crates/ui-egui/src/dialogs/export_dialog.rs diff --git a/crates/ui-egui/src/export_dialog/tests.rs b/crates/ui-egui/src/dialogs/export_dialog/tests.rs similarity index 99% rename from crates/ui-egui/src/export_dialog/tests.rs rename to crates/ui-egui/src/dialogs/export_dialog/tests.rs index b5815fd700..b015c97f85 100644 --- a/crates/ui-egui/src/export_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/tests.rs @@ -357,9 +357,8 @@ fn export_as_downscales_stroke_only_shapes_and_preview() { for depth in [8, 16, 32] { let mut session = photocraft_engine::Session::new(); session.execute("file.new", json!({"width": 1024, "height": 1024, "depth": depth, "background": "transparent"})).unwrap(); - let id = session.execute("shape.create", json!({"rect": [256, 256, 512, 512], "fill": null, "stroke": {"width": 32}})).unwrap()["layer"] - .as_u64() - .unwrap(); + let id = + session.execute("shape.create", json!({"rect": [256, 256, 512, 512], "fill": null, "stroke": {"width": 32}})).unwrap()["layer"].as_u64().unwrap(); let doc = session.active().unwrap().doc.clone(); let fields = Map::from_iter([("format".into(), json!("png")), ("scale".into(), json!(25))]); for limit in [None, Some(128)] { diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/dialogs/file_ui.rs similarity index 99% rename from crates/ui-egui/src/file_ui.rs rename to crates/ui-egui/src/dialogs/file_ui.rs index 16f1e613bf..425d7eae44 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/dialogs/file_ui.rs @@ -17,15 +17,15 @@ use crate::theme::Tokens; mod print; mod web; -use print::{print_body, print_confirm}; -#[cfg(test)] -use print::{drag_print_position, driver_paper_is_wide, print_params, print_preview_image, printer_options, take_turned_page, turn_driver}; pub use print::open_print; pub(crate) use print::print_status; -use web::{web_body, web_confirm}; #[cfg(test)] -use web::{advance_preview, download_for_web, WEB_COMMAND, web_frame_document, WebCache, WebProxy}; +use print::{drag_print_position, driver_paper_is_wide, print_params, print_preview_image, printer_options, take_turned_page, turn_driver}; +use print::{print_body, print_confirm}; pub use web::open_web; +#[cfg(test)] +use web::{WEB_COMMAND, WebCache, WebProxy, advance_preview, download_for_web, web_frame_document}; +use web::{web_body, web_confirm}; fn no_params(p: &Value) -> bool { p.as_object().is_none_or(|o| o.is_empty()) diff --git a/crates/ui-egui/src/file_ui/print.rs b/crates/ui-egui/src/dialogs/file_ui/print.rs similarity index 100% rename from crates/ui-egui/src/file_ui/print.rs rename to crates/ui-egui/src/dialogs/file_ui/print.rs diff --git a/crates/ui-egui/src/file_ui/tests.rs b/crates/ui-egui/src/dialogs/file_ui/tests.rs similarity index 99% rename from crates/ui-egui/src/file_ui/tests.rs rename to crates/ui-egui/src/dialogs/file_ui/tests.rs index 1a6a882456..1bc5273cad 100644 --- a/crates/ui-egui/src/file_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/file_ui/tests.rs @@ -459,10 +459,8 @@ fn the_printable_area_goes_only_with_a_print_to_the_printer() { fn print_dialog_opens_with_the_settings_remembered_from_an_earlier_session() { let (mut app, _) = app(); app.session.prefs.edit(|p| { - p.dialogs.insert( - photocraft_engine::print_cmds::REMEMBERED.into(), - json!({"paper": "a5", "scale": 50, "orientation": "landscape", "intent": "perceptual"}), - ); + p.dialogs + .insert(photocraft_engine::print_cmds::REMEMBERED.into(), json!({"paper": "a5", "scale": 50, "orientation": "landscape", "intent": "perceptual"})); }); let id = open_print(&mut app); let f = &app.ui.dialog_mut(id).unwrap().fields; diff --git a/crates/ui-egui/src/file_ui/web.rs b/crates/ui-egui/src/dialogs/file_ui/web.rs similarity index 100% rename from crates/ui-egui/src/file_ui/web.rs rename to crates/ui-egui/src/dialogs/file_ui/web.rs diff --git a/crates/ui-egui/src/file_ui/web_preview.rs b/crates/ui-egui/src/dialogs/file_ui/web_preview.rs similarity index 100% rename from crates/ui-egui/src/file_ui/web_preview.rs rename to crates/ui-egui/src/dialogs/file_ui/web_preview.rs diff --git a/crates/ui-egui/src/fill_ui.rs b/crates/ui-egui/src/dialogs/fill_ui.rs similarity index 100% rename from crates/ui-egui/src/fill_ui.rs rename to crates/ui-egui/src/dialogs/fill_ui.rs diff --git a/crates/ui-egui/src/fill_ui/tests.rs b/crates/ui-egui/src/dialogs/fill_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/fill_ui/tests.rs rename to crates/ui-egui/src/dialogs/fill_ui/tests.rs diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs similarity index 100% rename from crates/ui-egui/src/filter_dialog.rs rename to crates/ui-egui/src/dialogs/filter_dialog.rs diff --git a/crates/ui-egui/src/filter_dialog/tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs similarity index 99% rename from crates/ui-egui/src/filter_dialog/tests.rs rename to crates/ui-egui/src/dialogs/filter_dialog/tests.rs index ce2f77025d..fdd6ad04e4 100644 --- a/crates/ui-egui/src/filter_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs @@ -1232,11 +1232,8 @@ fn sweep_params(app: &mut PhotocraftApp, command: &str) -> Vec<(String, Value)> /// Every previewed command with its parameter sets. fn previewed_cases() -> Vec<(&'static str, String, Value)> { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); - let ids: Vec<&'static str> = photocraft_engine::command_specs() - .iter() - .map(|c| c.id) - .filter(|id| has_dialog(id) && (id.starts_with("filter.") || PREVIEWED.contains(id))) - .collect(); + let ids: Vec<&'static str> = + photocraft_engine::command_specs().iter().map(|c| c.id).filter(|id| has_dialog(id) && (id.starts_with("filter.") || PREVIEWED.contains(id))).collect(); ids.into_iter().flat_map(|id| sweep_params(&mut app, id).into_iter().map(move |(label, p)| (id, label, p))).collect() } diff --git a/crates/ui-egui/src/filter_dialog/zoom_center.rs b/crates/ui-egui/src/dialogs/filter_dialog/zoom_center.rs similarity index 100% rename from crates/ui-egui/src/filter_dialog/zoom_center.rs rename to crates/ui-egui/src/dialogs/filter_dialog/zoom_center.rs diff --git a/crates/ui-egui/src/filter_preview_ui.rs b/crates/ui-egui/src/dialogs/filter_preview_ui.rs similarity index 100% rename from crates/ui-egui/src/filter_preview_ui.rs rename to crates/ui-egui/src/dialogs/filter_preview_ui.rs diff --git a/crates/ui-egui/src/filter_preview_worker.rs b/crates/ui-egui/src/dialogs/filter_preview_worker.rs similarity index 100% rename from crates/ui-egui/src/filter_preview_worker.rs rename to crates/ui-egui/src/dialogs/filter_preview_worker.rs diff --git a/crates/ui-egui/src/gallery_ui.rs b/crates/ui-egui/src/dialogs/gallery_ui.rs similarity index 100% rename from crates/ui-egui/src/gallery_ui.rs rename to crates/ui-egui/src/dialogs/gallery_ui.rs diff --git a/crates/ui-egui/src/gallery_ui/tests.rs b/crates/ui-egui/src/dialogs/gallery_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/gallery_ui/tests.rs rename to crates/ui-egui/src/dialogs/gallery_ui/tests.rs diff --git a/crates/ui-egui/src/guide_layout_ui.rs b/crates/ui-egui/src/dialogs/guide_layout_ui.rs similarity index 100% rename from crates/ui-egui/src/guide_layout_ui.rs rename to crates/ui-egui/src/dialogs/guide_layout_ui.rs diff --git a/crates/ui-egui/src/guide_layout_ui/tests.rs b/crates/ui-egui/src/dialogs/guide_layout_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/guide_layout_ui/tests.rs rename to crates/ui-egui/src/dialogs/guide_layout_ui/tests.rs diff --git a/crates/ui-egui/src/jpeg_options_ui.rs b/crates/ui-egui/src/dialogs/jpeg_options_ui.rs similarity index 100% rename from crates/ui-egui/src/jpeg_options_ui.rs rename to crates/ui-egui/src/dialogs/jpeg_options_ui.rs diff --git a/crates/ui-egui/src/layer_picker.rs b/crates/ui-egui/src/dialogs/layer_picker.rs similarity index 100% rename from crates/ui-egui/src/layer_picker.rs rename to crates/ui-egui/src/dialogs/layer_picker.rs diff --git a/crates/ui-egui/src/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs similarity index 100% rename from crates/ui-egui/src/layer_style.rs rename to crates/ui-egui/src/dialogs/layer_style.rs diff --git a/crates/ui-egui/src/layer_style/bevel_modes_tests.rs b/crates/ui-egui/src/dialogs/layer_style/bevel_modes_tests.rs similarity index 100% rename from crates/ui-egui/src/layer_style/bevel_modes_tests.rs rename to crates/ui-egui/src/dialogs/layer_style/bevel_modes_tests.rs diff --git a/crates/ui-egui/src/layer_style/color_picker.rs b/crates/ui-egui/src/dialogs/layer_style/color_picker.rs similarity index 100% rename from crates/ui-egui/src/layer_style/color_picker.rs rename to crates/ui-egui/src/dialogs/layer_style/color_picker.rs diff --git a/crates/ui-egui/src/layer_style/color_picker/tests.rs b/crates/ui-egui/src/dialogs/layer_style/color_picker/tests.rs similarity index 100% rename from crates/ui-egui/src/layer_style/color_picker/tests.rs rename to crates/ui-egui/src/dialogs/layer_style/color_picker/tests.rs diff --git a/crates/ui-egui/src/layer_style/contour.rs b/crates/ui-egui/src/dialogs/layer_style/contour.rs similarity index 100% rename from crates/ui-egui/src/layer_style/contour.rs rename to crates/ui-egui/src/dialogs/layer_style/contour.rs diff --git a/crates/ui-egui/src/layer_style/gradient_method_tests.rs b/crates/ui-egui/src/dialogs/layer_style/gradient_method_tests.rs similarity index 100% rename from crates/ui-egui/src/layer_style/gradient_method_tests.rs rename to crates/ui-egui/src/dialogs/layer_style/gradient_method_tests.rs diff --git a/crates/ui-egui/src/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs similarity index 99% rename from crates/ui-egui/src/layer_style/tests.rs rename to crates/ui-egui/src/dialogs/layer_style/tests.rs index ebfb894081..7fe1b40c49 100644 --- a/crates/ui-egui/src/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -431,8 +431,7 @@ fn blending_page_renders_for_every_mode_and_odd_fields() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); let mut layer = photocraft_doc::Layer::new("L", photocraft_doc::LayerContent::Adjustment(photocraft_doc::Adjustment::Invert)); layer.advanced.knockout = photocraft_doc::Knockout::Deep; - for mode in - [photocraft_color::ColorMode::Rgb, photocraft_color::ColorMode::Cmyk, photocraft_color::ColorMode::Lab, photocraft_color::ColorMode::Grayscale] + for mode in [photocraft_color::ColorMode::Rgb, photocraft_color::ColorMode::Cmyk, photocraft_color::ColorMode::Lab, photocraft_color::ColorMode::Grayscale] { let mut f = initial_fields(&layer, Some(BLENDING), 120.0); set_blending_fields(&mut f, &layer, mode); diff --git a/crates/ui-egui/src/liquify_ui.rs b/crates/ui-egui/src/dialogs/liquify_ui.rs similarity index 100% rename from crates/ui-egui/src/liquify_ui.rs rename to crates/ui-egui/src/dialogs/liquify_ui.rs diff --git a/crates/ui-egui/src/liquify_ui/tests.rs b/crates/ui-egui/src/dialogs/liquify_ui/tests.rs similarity index 99% rename from crates/ui-egui/src/liquify_ui/tests.rs rename to crates/ui-egui/src/dialogs/liquify_ui/tests.rs index 6a6796409e..9b50c50677 100644 --- a/crates/ui-egui/src/liquify_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui/tests.rs @@ -210,8 +210,7 @@ fn dialog_strokes_match_the_engine_and_commit_once() { pointer(&mut app, ev, egui::Modifiers::NONE); } control(&mut app, &json!({"tool": "bloat"})).unwrap(); - for ev in [ToolEvent::Down { x: 80.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 80.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 80.0, y: 40.0 }] - { + for ev in [ToolEvent::Down { x: 80.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 80.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 80.0, y: 40.0 }] { pointer(&mut app, ev, egui::Modifiers::NONE); } let d = app.distort.liquify.as_ref().unwrap(); @@ -269,8 +268,7 @@ fn undo_dirties_the_zoomed_preview() { let mut app = app_with_layer(); open(&mut app, &ctx).unwrap(); control(&mut app, &json!({"tool": "forwardWarp", "size": 40})).unwrap(); - for ev in [ToolEvent::Down { x: 35.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 55.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 55.0, y: 40.0 }] - { + for ev in [ToolEvent::Down { x: 35.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 55.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 55.0, y: 40.0 }] { pointer(&mut app, ev, egui::Modifiers::NONE); } { @@ -431,8 +429,7 @@ fn shortcut_handler_undoes_liquify_even_when_egui_owns_keyboard_focus() { let ctx = egui::Context::default(); let mut app = app_with_layer(); open(&mut app, &ctx).unwrap(); - for ev in [ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 52.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 52.0, y: 40.0 }] - { + for ev in [ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 52.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 52.0, y: 40.0 }] { pointer(&mut app, ev, egui::Modifiers::NONE); } assert_eq!(app.distort.liquify.as_ref().unwrap().strokes.len(), 1); @@ -472,8 +469,7 @@ fn liquify_undo_and_redo_work_while_a_numeric_field_is_focused() { let ctx = egui::Context::default(); let mut app = app_with_layer(); open(&mut app, &ctx).unwrap(); - for ev in [ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 52.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 52.0, y: 40.0 }] - { + for ev in [ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 52.0, y: 40.0, pressure: 1.0 }, ToolEvent::Up { x: 52.0, y: 40.0 }] { pointer(&mut app, ev, egui::Modifiers::NONE); } let strokes = |app: &PhotocraftApp| app.distort.liquify.as_ref().unwrap().strokes.len(); diff --git a/crates/ui-egui/src/mask_trash_prompt.rs b/crates/ui-egui/src/dialogs/mask_trash_prompt.rs similarity index 100% rename from crates/ui-egui/src/mask_trash_prompt.rs rename to crates/ui-egui/src/dialogs/mask_trash_prompt.rs diff --git a/crates/ui-egui/src/new_doc_ui.rs b/crates/ui-egui/src/dialogs/new_doc_ui.rs similarity index 100% rename from crates/ui-egui/src/new_doc_ui.rs rename to crates/ui-egui/src/dialogs/new_doc_ui.rs diff --git a/crates/ui-egui/src/new_doc_ui/tests.rs b/crates/ui-egui/src/dialogs/new_doc_ui/tests.rs similarity index 99% rename from crates/ui-egui/src/new_doc_ui/tests.rs rename to crates/ui-egui/src/dialogs/new_doc_ui/tests.rs index e4461f7d85..6dbe011439 100644 --- a/crates/ui-egui/src/new_doc_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/new_doc_ui/tests.rs @@ -10,10 +10,7 @@ fn color_profile_menu_lists_the_profiles_of_the_modes_space() { InstalledProfile { path: "panel.icc".into(), description: "Panel".into(), class: ProfileClass::Display, color_space: ColorSpace::Rgb }, ]; let values = |mode: &str| { - profile_options(color_mode_of(mode).map(photocraft_engine::color_cmds::mode_space), "sRGB", &installed) - .into_iter() - .map(|(v, _)| v) - .collect::>() + profile_options(color_mode_of(mode).map(photocraft_engine::color_cmds::mode_space), "sRGB", &installed).into_iter().map(|(v, _)| v).collect::>() }; let rgb = values("rgb"); assert_eq!(rgb[0], "working"); @@ -469,10 +466,8 @@ mod dialog { fn harness() -> Harness<'static, PhotocraftApp> { let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut h = Harness::builder() - .with_size(egui::vec2(1400.0, 900.0)) - .with_step_dt(1.0 / 60.0) - .build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + let mut h = + Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); h.state_mut().ui.open_dialog(DialogKind::NewDocument, UiState::new_document_fields()); h.run_steps(3); diff --git a/crates/ui-egui/src/new_guide_ui.rs b/crates/ui-egui/src/dialogs/new_guide_ui.rs similarity index 100% rename from crates/ui-egui/src/new_guide_ui.rs rename to crates/ui-egui/src/dialogs/new_guide_ui.rs diff --git a/crates/ui-egui/src/new_guide_ui/tests.rs b/crates/ui-egui/src/dialogs/new_guide_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/new_guide_ui/tests.rs rename to crates/ui-egui/src/dialogs/new_guide_ui/tests.rs diff --git a/crates/ui-egui/src/new_layer_ui.rs b/crates/ui-egui/src/dialogs/new_layer_ui.rs similarity index 100% rename from crates/ui-egui/src/new_layer_ui.rs rename to crates/ui-egui/src/dialogs/new_layer_ui.rs diff --git a/crates/ui-egui/src/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs similarity index 100% rename from crates/ui-egui/src/open_prompt.rs rename to crates/ui-egui/src/dialogs/open_prompt.rs diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/dialogs/palette.rs similarity index 100% rename from crates/ui-egui/src/palette.rs rename to crates/ui-egui/src/dialogs/palette.rs diff --git a/crates/ui-egui/src/pattern_fill_ui.rs b/crates/ui-egui/src/dialogs/pattern_fill_ui.rs similarity index 100% rename from crates/ui-egui/src/pattern_fill_ui.rs rename to crates/ui-egui/src/dialogs/pattern_fill_ui.rs diff --git a/crates/ui-egui/src/pattern_fill_ui/tests.rs b/crates/ui-egui/src/dialogs/pattern_fill_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/pattern_fill_ui/tests.rs rename to crates/ui-egui/src/dialogs/pattern_fill_ui/tests.rs diff --git a/crates/ui-egui/src/rasterize_prompt.rs b/crates/ui-egui/src/dialogs/rasterize_prompt.rs similarity index 100% rename from crates/ui-egui/src/rasterize_prompt.rs rename to crates/ui-egui/src/dialogs/rasterize_prompt.rs diff --git a/crates/ui-egui/src/rasterize_prompt/tests.rs b/crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs similarity index 100% rename from crates/ui-egui/src/rasterize_prompt/tests.rs rename to crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs diff --git a/crates/ui-egui/src/replace_prompt.rs b/crates/ui-egui/src/dialogs/replace_prompt.rs similarity index 100% rename from crates/ui-egui/src/replace_prompt.rs rename to crates/ui-egui/src/dialogs/replace_prompt.rs diff --git a/crates/ui-egui/src/rgb_histogram.rs b/crates/ui-egui/src/dialogs/rgb_histogram.rs similarity index 100% rename from crates/ui-egui/src/rgb_histogram.rs rename to crates/ui-egui/src/dialogs/rgb_histogram.rs diff --git a/crates/ui-egui/src/screen_picker.rs b/crates/ui-egui/src/dialogs/screen_picker.rs similarity index 100% rename from crates/ui-egui/src/screen_picker.rs rename to crates/ui-egui/src/dialogs/screen_picker.rs diff --git a/crates/ui-egui/src/shape_dialog.rs b/crates/ui-egui/src/dialogs/shape_dialog.rs similarity index 100% rename from crates/ui-egui/src/shape_dialog.rs rename to crates/ui-egui/src/dialogs/shape_dialog.rs diff --git a/crates/ui-egui/src/shape_dialog/tests.rs b/crates/ui-egui/src/dialogs/shape_dialog/tests.rs similarity index 100% rename from crates/ui-egui/src/shape_dialog/tests.rs rename to crates/ui-egui/src/dialogs/shape_dialog/tests.rs diff --git a/crates/ui-egui/src/shape_fill_ui.rs b/crates/ui-egui/src/dialogs/shape_fill_ui.rs similarity index 100% rename from crates/ui-egui/src/shape_fill_ui.rs rename to crates/ui-egui/src/dialogs/shape_fill_ui.rs diff --git a/crates/ui-egui/src/shape_fill_ui/tests.rs b/crates/ui-egui/src/dialogs/shape_fill_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/shape_fill_ui/tests.rs rename to crates/ui-egui/src/dialogs/shape_fill_ui/tests.rs diff --git a/crates/ui-egui/src/sizing.rs b/crates/ui-egui/src/dialogs/sizing.rs similarity index 100% rename from crates/ui-egui/src/sizing.rs rename to crates/ui-egui/src/dialogs/sizing.rs diff --git a/crates/ui-egui/src/sizing/tests.rs b/crates/ui-egui/src/dialogs/sizing/tests.rs similarity index 100% rename from crates/ui-egui/src/sizing/tests.rs rename to crates/ui-egui/src/dialogs/sizing/tests.rs diff --git a/crates/ui-egui/src/smart_filter_dialog.rs b/crates/ui-egui/src/dialogs/smart_filter_dialog.rs similarity index 100% rename from crates/ui-egui/src/smart_filter_dialog.rs rename to crates/ui-egui/src/dialogs/smart_filter_dialog.rs diff --git a/crates/ui-egui/src/smart_filter_dialog/tests.rs b/crates/ui-egui/src/dialogs/smart_filter_dialog/tests.rs similarity index 100% rename from crates/ui-egui/src/smart_filter_dialog/tests.rs rename to crates/ui-egui/src/dialogs/smart_filter_dialog/tests.rs diff --git a/crates/ui-egui/src/snapshot_dialog.rs b/crates/ui-egui/src/dialogs/snapshot_dialog.rs similarity index 100% rename from crates/ui-egui/src/snapshot_dialog.rs rename to crates/ui-egui/src/dialogs/snapshot_dialog.rs diff --git a/crates/ui-egui/src/solid_fill_ui.rs b/crates/ui-egui/src/dialogs/solid_fill_ui.rs similarity index 100% rename from crates/ui-egui/src/solid_fill_ui.rs rename to crates/ui-egui/src/dialogs/solid_fill_ui.rs diff --git a/crates/ui-egui/src/solid_fill_ui/tests.rs b/crates/ui-egui/src/dialogs/solid_fill_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/solid_fill_ui/tests.rs rename to crates/ui-egui/src/dialogs/solid_fill_ui/tests.rs diff --git a/crates/ui-egui/src/stack_dialog.rs b/crates/ui-egui/src/dialogs/stack_dialog.rs similarity index 100% rename from crates/ui-egui/src/stack_dialog.rs rename to crates/ui-egui/src/dialogs/stack_dialog.rs diff --git a/crates/ui-egui/src/stack_dialog/tests.rs b/crates/ui-egui/src/dialogs/stack_dialog/tests.rs similarity index 100% rename from crates/ui-egui/src/stack_dialog/tests.rs rename to crates/ui-egui/src/dialogs/stack_dialog/tests.rs diff --git a/crates/ui-egui/src/stroke_ui.rs b/crates/ui-egui/src/dialogs/stroke_ui.rs similarity index 100% rename from crates/ui-egui/src/stroke_ui.rs rename to crates/ui-egui/src/dialogs/stroke_ui.rs diff --git a/crates/ui-egui/src/stroke_ui/tests.rs b/crates/ui-egui/src/dialogs/stroke_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/stroke_ui/tests.rs rename to crates/ui-egui/src/dialogs/stroke_ui/tests.rs diff --git a/crates/ui-egui/src/targa_options_ui.rs b/crates/ui-egui/src/dialogs/targa_options_ui.rs similarity index 100% rename from crates/ui-egui/src/targa_options_ui.rs rename to crates/ui-egui/src/dialogs/targa_options_ui.rs diff --git a/crates/ui-egui/src/tiff_options_ui.rs b/crates/ui-egui/src/dialogs/tiff_options_ui.rs similarity index 100% rename from crates/ui-egui/src/tiff_options_ui.rs rename to crates/ui-egui/src/dialogs/tiff_options_ui.rs diff --git a/crates/ui-egui/src/vp_ui.rs b/crates/ui-egui/src/dialogs/vp_ui.rs similarity index 100% rename from crates/ui-egui/src/vp_ui.rs rename to crates/ui-egui/src/dialogs/vp_ui.rs diff --git a/crates/ui-egui/src/vp_ui/tests.rs b/crates/ui-egui/src/dialogs/vp_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/vp_ui/tests.rs rename to crates/ui-egui/src/dialogs/vp_ui/tests.rs diff --git a/crates/ui-egui/src/wide_angle_ui.rs b/crates/ui-egui/src/dialogs/wide_angle_ui.rs similarity index 100% rename from crates/ui-egui/src/wide_angle_ui.rs rename to crates/ui-egui/src/dialogs/wide_angle_ui.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 877211960a..209df28b21 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -13,40 +13,23 @@ macro_rules! tl { $crate::i18n::t($s) }; } -pub mod adjust_dialog; -pub mod adjust_editors; -pub mod adjust_preview; mod align_bar; mod alt_grab; pub mod analysis_ui; pub mod anchor_tools; pub mod artboard_tool; pub mod bidi_text; -pub(crate) mod bitmap_dialog; mod blend_keys; -pub mod blur_pins; pub(crate) mod brush_cursor; pub mod brush_picker; -pub mod brush_preset_dialog; pub mod brush_resize; -pub mod caf_ui; mod cam_transform; -mod camera_raw_detail_ui; -mod camera_raw_gpu; -mod camera_raw_preview_ui; -mod camera_raw_scope_ui; -pub mod camera_raw_ui; pub mod canvas; pub mod cas_transform; -pub mod channel_options_ui; pub mod cjk_fonts; -pub mod color_picker_ui; -pub mod color_range_ui; -pub mod color_table_ui; pub mod control; mod control_click; pub mod corner_radius; -pub mod credits; pub mod crop_mode; pub mod crop_overlay; pub mod crop_presets; @@ -54,57 +37,34 @@ pub mod crop_shield; pub mod crop_size; pub mod crop_straighten; pub mod crop_ui; -pub mod dds_options_ui; -pub mod delete_layer_prompt; -pub mod dialog_alt_reset; -pub mod dialog_blend_ui; pub mod dialogs; pub mod direct_select; pub mod direction; -pub mod discard_ui; -pub mod disk_change_prompt; -pub mod distort_ui; pub mod dock; -pub mod duplicate_layer_ui; -pub mod edit_history; pub mod egui_fonts; pub mod enable_rules; pub mod eraser_ui; -pub mod export_dialog; pub mod eyedropper_ui; pub mod field_tab; pub mod field_wheel; pub mod file_dialog; pub mod file_open; -pub mod file_ui; -pub mod fill_ui; -pub mod filter_dialog; -mod filter_preview_ui; -#[cfg(not(target_arch = "wasm32"))] -mod filter_preview_worker; pub mod flick_pan; mod font_preview; pub mod frame_tool; -pub mod gallery_ui; pub mod gpu_status; pub mod gradient_ui; -pub mod guide_layout_ui; pub mod hold_keys; pub mod i18n; mod icon_data; pub mod icons; pub mod jobs_ui; -pub mod jpeg_options_ui; pub mod kys_import; pub mod lasso_ui; pub(crate) mod last_brush; -pub mod layer_picker; -pub mod layer_style; mod layout_keys; pub mod links; -pub mod liquify_ui; pub mod magnetic_lasso_ui; -pub mod mask_trash_prompt; pub mod menu_catalog; pub mod menu_keys; pub mod menu_nav; @@ -116,20 +76,14 @@ pub mod move_hover; pub mod move_lock; pub mod move_mods; pub mod native_menu; -pub mod new_doc_ui; -pub mod new_guide_ui; -pub mod new_layer_ui; pub mod notices; pub mod nudge_bundle; mod numeric_expression; pub mod object_finder; mod opacity_keys; -pub mod open_prompt; mod page_keys; -pub mod palette; pub mod panels; pub mod parity; -pub(crate) mod pattern_fill_ui; pub mod perspective_crop_ui; pub mod perspective_ui; pub mod plugin_ui; @@ -140,16 +94,10 @@ pub mod press_menu; mod pressure_curve_ui; pub mod proxy; pub mod puppet_ui; -pub mod rasterize_prompt; -pub mod replace_prompt; pub mod retouch_ui; -mod rgb_histogram; -pub mod screen_picker; pub mod screenshot; mod scrub_wrap; pub mod served_fonts; -pub mod shape_dialog; -pub(crate) mod shape_fill_ui; mod shape_gradient_ui; mod shape_options; mod shape_paint_ui; @@ -157,27 +105,19 @@ pub mod shape_stroke_ui; pub mod shortcut_dispatch; pub mod shortcuts; mod single_line_drag; -mod sizing; pub mod slice_ui; -pub mod smart_filter_dialog; -pub mod snapshot_dialog; -pub(crate) mod solid_fill_ui; pub mod spring_tools; -pub mod stack_dialog; pub mod state; pub mod stroke_constraint; pub mod stroke_trace; pub mod stroke_trail; -pub mod stroke_ui; pub mod stylus; pub mod swap_arrow; pub mod symmetry_ui; mod tab_strip; -pub mod targa_options_ui; pub mod texel_guard; pub mod text_field_menu; pub mod theme; -pub mod tiff_options_ui; pub use titlebar::{Caption, CaptionFamily, CaptionIcon, CaptionIcons, CaptionStyle, RenderIconFn}; pub mod tone; pub(crate) mod tool_memory; @@ -193,9 +133,7 @@ mod type_transform; pub mod updates_ui; pub mod vector_ui; pub mod view_cmds; -pub mod vp_ui; pub mod warp_preview; -pub mod wide_angle_ui; pub mod widgets; pub mod work_area; pub mod workspace_ui; @@ -251,6 +189,68 @@ pub use canvas::wheel_nav; pub use canvas::zoom_hold; pub use canvas::zoom_levels; pub use canvas::zoom_window_fit; +pub use dialogs::adjust_dialog; +pub use dialogs::adjust_editors; +pub use dialogs::adjust_preview; +pub(crate) use dialogs::bitmap_dialog; +pub use dialogs::blur_pins; +pub use dialogs::brush_preset_dialog; +pub use dialogs::caf_ui; +use dialogs::camera_raw_detail_ui; +use dialogs::camera_raw_gpu; +use dialogs::camera_raw_preview_ui; +use dialogs::camera_raw_scope_ui; +pub use dialogs::camera_raw_ui; +pub use dialogs::channel_options_ui; +pub use dialogs::color_picker_ui; +pub use dialogs::color_range_ui; +pub use dialogs::color_table_ui; +pub use dialogs::credits; +pub use dialogs::dds_options_ui; +pub use dialogs::delete_layer_prompt; +pub use dialogs::dialog_alt_reset; +pub use dialogs::dialog_blend_ui; +pub use dialogs::discard_ui; +pub use dialogs::disk_change_prompt; +pub use dialogs::distort_ui; +pub use dialogs::duplicate_layer_ui; +pub use dialogs::edit_history; +pub use dialogs::export_dialog; +pub use dialogs::file_ui; +pub use dialogs::fill_ui; +pub use dialogs::filter_dialog; +use dialogs::filter_preview_ui; +#[cfg(not(target_arch = "wasm32"))] +use dialogs::filter_preview_worker; +pub use dialogs::gallery_ui; +pub use dialogs::guide_layout_ui; +pub use dialogs::jpeg_options_ui; +pub use dialogs::layer_picker; +pub use dialogs::layer_style; +pub use dialogs::liquify_ui; +pub use dialogs::mask_trash_prompt; +pub use dialogs::new_doc_ui; +pub use dialogs::new_guide_ui; +pub use dialogs::new_layer_ui; +pub use dialogs::open_prompt; +pub use dialogs::palette; +pub(crate) use dialogs::pattern_fill_ui; +pub use dialogs::rasterize_prompt; +pub use dialogs::replace_prompt; +use dialogs::rgb_histogram; +pub use dialogs::screen_picker; +pub use dialogs::shape_dialog; +pub(crate) use dialogs::shape_fill_ui; +use dialogs::sizing; +pub use dialogs::smart_filter_dialog; +pub use dialogs::snapshot_dialog; +pub(crate) use dialogs::solid_fill_ui; +pub use dialogs::stack_dialog; +pub use dialogs::stroke_ui; +pub use dialogs::targa_options_ui; +pub use dialogs::tiff_options_ui; +pub use dialogs::vp_ui; +pub use dialogs::wide_angle_ui; pub use panels::actions; pub use panels::adjust_ui; pub use panels::apply_color; From 086bdba30349279faf409c094c65a561ea95ff3a Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 21:26:46 +0000 Subject: [PATCH 239/259] refactor(ui-egui): move menus modules under menus/ --- crates/ui-egui/src/lib.rs | 16 +++++++-------- crates/ui-egui/src/menus.rs | 18 ++++++++++++----- .../ui-egui/src/{ => menus}/enable_rules.rs | 0 crates/ui-egui/src/{ => menus}/menu_keys.rs | 0 .../{ => menus}/menu_keys/harness_tests.rs | 0 crates/ui-egui/src/{ => menus}/menu_nav.rs | 0 .../ui-egui/src/{ => menus}/menu_nav/tests.rs | 0 crates/ui-egui/src/{ => menus}/native_menu.rs | 0 .../src/{ => menus}/native_menu/tests.rs | 20 ++----------------- crates/ui-egui/src/{ => menus}/parity.rs | 0 crates/ui-egui/src/{ => menus}/plugin_ui.rs | 0 crates/ui-egui/src/{ => menus}/view_cmds.rs | 2 +- .../src/{ => menus}/view_cmds/arrange.rs | 0 .../src/{ => menus}/view_cmds/dialogs.rs | 0 .../src/{ => menus}/view_cmds/dispatch.rs | 0 .../src/{ => menus}/view_cmds/options.rs | 0 .../src/{ => menus}/view_cmds/tests.rs | 0 .../ui-egui/src/{ => menus}/workspace_ui.rs | 0 18 files changed, 24 insertions(+), 32 deletions(-) rename crates/ui-egui/src/{ => menus}/enable_rules.rs (100%) rename crates/ui-egui/src/{ => menus}/menu_keys.rs (100%) rename crates/ui-egui/src/{ => menus}/menu_keys/harness_tests.rs (100%) rename crates/ui-egui/src/{ => menus}/menu_nav.rs (100%) rename crates/ui-egui/src/{ => menus}/menu_nav/tests.rs (100%) rename crates/ui-egui/src/{ => menus}/native_menu.rs (100%) rename crates/ui-egui/src/{ => menus}/native_menu/tests.rs (98%) rename crates/ui-egui/src/{ => menus}/parity.rs (100%) rename crates/ui-egui/src/{ => menus}/plugin_ui.rs (100%) rename crates/ui-egui/src/{ => menus}/view_cmds.rs (100%) rename crates/ui-egui/src/{ => menus}/view_cmds/arrange.rs (100%) rename crates/ui-egui/src/{ => menus}/view_cmds/dialogs.rs (100%) rename crates/ui-egui/src/{ => menus}/view_cmds/dispatch.rs (100%) rename crates/ui-egui/src/{ => menus}/view_cmds/options.rs (100%) rename crates/ui-egui/src/{ => menus}/view_cmds/tests.rs (100%) rename crates/ui-egui/src/{ => menus}/workspace_ui.rs (100%) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 209df28b21..be9c058080 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -42,7 +42,6 @@ pub mod direct_select; pub mod direction; pub mod dock; pub mod egui_fonts; -pub mod enable_rules; pub mod eraser_ui; pub mod eyedropper_ui; pub mod field_tab; @@ -66,8 +65,6 @@ mod layout_keys; pub mod links; pub mod magnetic_lasso_ui; pub mod menu_catalog; -pub mod menu_keys; -pub mod menu_nav; pub mod menus; pub mod monitor_status; pub mod move_box; @@ -75,7 +72,6 @@ pub mod move_distance; pub mod move_hover; pub mod move_lock; pub mod move_mods; -pub mod native_menu; pub mod notices; pub mod nudge_bundle; mod numeric_expression; @@ -83,10 +79,8 @@ pub mod object_finder; mod opacity_keys; mod page_keys; pub mod panels; -pub mod parity; pub mod perspective_crop_ui; pub mod perspective_ui; -pub mod plugin_ui; pub mod point_curve; pub mod prefs_ui; pub mod preset_files_ui; @@ -132,11 +126,9 @@ pub mod type_tool; mod type_transform; pub mod updates_ui; pub mod vector_ui; -pub mod view_cmds; pub mod warp_preview; pub mod widgets; pub mod work_area; -pub mod workspace_ui; pub mod zoom_tool; use std::collections::HashMap; @@ -251,6 +243,14 @@ pub use dialogs::targa_options_ui; pub use dialogs::tiff_options_ui; pub use dialogs::vp_ui; pub use dialogs::wide_angle_ui; +pub use menus::enable_rules; +pub use menus::menu_keys; +pub use menus::menu_nav; +pub use menus::native_menu; +pub use menus::parity; +pub use menus::plugin_ui; +pub use menus::view_cmds; +pub use menus::workspace_ui; pub use panels::actions; pub use panels::adjust_ui; pub use panels::apply_color; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 84d607aeff..cff7c22749 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -6,29 +6,37 @@ use crate::PhotocraftApp; use crate::state::DialogKind; mod bar; +pub mod enable_rules; mod invoke; mod items; +pub mod menu_keys; +pub mod menu_nav; +pub mod native_menu; +pub mod parity; +pub mod plugin_ui; mod render; mod search; mod state; +pub mod view_cmds; +pub mod workspace_ui; +pub use bar::menu_bar; #[cfg(test)] use bar::pointer_reaches_title; -pub use bar::menu_bar; pub use invoke::{apply_workspace, invoke}; pub(crate) use invoke::{invoke_unguarded, panel_alias}; -pub use items::{is_live, menu_items, MenuItem}; pub(crate) use items::ItemCache; +pub use items::{MenuItem, is_live, menu_items}; +pub use render::alt_click; #[cfg(test)] use render::submenu_enabled; -pub use render::alt_click; #[cfg(test)] use search::HELP_SEARCH_MAX; pub use search::{search_items, search_rank}; -#[cfg(test)] -use state::{checked, translated_menu_label}; pub use state::is_enabled; pub(crate) use state::reveal_label; +#[cfg(test)] +use state::{checked, translated_menu_label}; /// Shared gate for native menu clicks and control-channel `ui.menu.invoke`. /// Dialogs and unsaved-changes prompts block edits, but allow the four view-navigation diff --git a/crates/ui-egui/src/enable_rules.rs b/crates/ui-egui/src/menus/enable_rules.rs similarity index 100% rename from crates/ui-egui/src/enable_rules.rs rename to crates/ui-egui/src/menus/enable_rules.rs diff --git a/crates/ui-egui/src/menu_keys.rs b/crates/ui-egui/src/menus/menu_keys.rs similarity index 100% rename from crates/ui-egui/src/menu_keys.rs rename to crates/ui-egui/src/menus/menu_keys.rs diff --git a/crates/ui-egui/src/menu_keys/harness_tests.rs b/crates/ui-egui/src/menus/menu_keys/harness_tests.rs similarity index 100% rename from crates/ui-egui/src/menu_keys/harness_tests.rs rename to crates/ui-egui/src/menus/menu_keys/harness_tests.rs diff --git a/crates/ui-egui/src/menu_nav.rs b/crates/ui-egui/src/menus/menu_nav.rs similarity index 100% rename from crates/ui-egui/src/menu_nav.rs rename to crates/ui-egui/src/menus/menu_nav.rs diff --git a/crates/ui-egui/src/menu_nav/tests.rs b/crates/ui-egui/src/menus/menu_nav/tests.rs similarity index 100% rename from crates/ui-egui/src/menu_nav/tests.rs rename to crates/ui-egui/src/menus/menu_nav/tests.rs diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/menus/native_menu.rs similarity index 100% rename from crates/ui-egui/src/native_menu.rs rename to crates/ui-egui/src/menus/native_menu.rs diff --git a/crates/ui-egui/src/native_menu/tests.rs b/crates/ui-egui/src/menus/native_menu/tests.rs similarity index 98% rename from crates/ui-egui/src/native_menu/tests.rs rename to crates/ui-egui/src/menus/native_menu/tests.rs index 648fd04287..f01d1257f2 100644 --- a/crates/ui-egui/src/native_menu/tests.rs +++ b/crates/ui-egui/src/menus/native_menu/tests.rs @@ -33,21 +33,7 @@ fn photocraft_gets_a_mac_app_menu() { assert_eq!((app.title.as_str(), app.role), ("PhotoCraft", MenuRole::App)); assert_eq!( ids(&app.children), - [ - "help.about", - "---", - "[Settings]", - "[Language]", - "[Appearance]", - "---", - "", - "---", - HIDE, - "", - "", - "---", - "file.exit" - ] + ["help.about", "---", "[Settings]", "[Language]", "[Appearance]", "---", "", "---", HIDE, "", "", "---", "file.exit"] ); let quit = l.bar.find("file.exit").unwrap(); assert_eq!((quit.label.as_str(), quit.shortcut.as_deref()), ("Quit PhotoCraft", Some("Cmd+Q"))); @@ -379,9 +365,7 @@ fn cut_selected_type_from_native_menu_matches_keyboard_cut() { }); out.textures_delta.clear(); assert_eq!(out.platform_output.commands, [egui::OutputCommand::CopyText("Hello".into())]); - let photocraft_doc::LayerContent::Text(text) = &app.session.active().unwrap().doc.layer(id).unwrap().content else { - panic!("type layer changed kind") - }; + let photocraft_doc::LayerContent::Text(text) = &app.session.active().unwrap().doc.layer(id).unwrap().content else { panic!("type layer changed kind") }; assert!(text.text.is_empty()); let edit = app.ui.text_edit.as_ref().unwrap(); assert_eq!((edit.anchor, edit.caret), (0, 0)); diff --git a/crates/ui-egui/src/parity.rs b/crates/ui-egui/src/menus/parity.rs similarity index 100% rename from crates/ui-egui/src/parity.rs rename to crates/ui-egui/src/menus/parity.rs diff --git a/crates/ui-egui/src/plugin_ui.rs b/crates/ui-egui/src/menus/plugin_ui.rs similarity index 100% rename from crates/ui-egui/src/plugin_ui.rs rename to crates/ui-egui/src/menus/plugin_ui.rs diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/menus/view_cmds.rs similarity index 100% rename from crates/ui-egui/src/view_cmds.rs rename to crates/ui-egui/src/menus/view_cmds.rs index afe640cc3f..3bc850e12f 100644 --- a/crates/ui-egui/src/view_cmds.rs +++ b/crates/ui-egui/src/menus/view_cmds.rs @@ -20,10 +20,10 @@ mod options; pub use arrange::cells; pub(crate) use arrange::float_window; +pub(crate) use dialogs::write_copy; #[cfg(test)] use dialogs::{form, front, label_of}; pub use dialogs::{form_body, form_keys, reset_form}; -pub(crate) use dialogs::write_copy; #[cfg(test)] use dispatch::is_enabled_with_engine; pub use dispatch::{checked, handles, invoke, is_enabled}; diff --git a/crates/ui-egui/src/view_cmds/arrange.rs b/crates/ui-egui/src/menus/view_cmds/arrange.rs similarity index 100% rename from crates/ui-egui/src/view_cmds/arrange.rs rename to crates/ui-egui/src/menus/view_cmds/arrange.rs diff --git a/crates/ui-egui/src/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs similarity index 100% rename from crates/ui-egui/src/view_cmds/dialogs.rs rename to crates/ui-egui/src/menus/view_cmds/dialogs.rs diff --git a/crates/ui-egui/src/view_cmds/dispatch.rs b/crates/ui-egui/src/menus/view_cmds/dispatch.rs similarity index 100% rename from crates/ui-egui/src/view_cmds/dispatch.rs rename to crates/ui-egui/src/menus/view_cmds/dispatch.rs diff --git a/crates/ui-egui/src/view_cmds/options.rs b/crates/ui-egui/src/menus/view_cmds/options.rs similarity index 100% rename from crates/ui-egui/src/view_cmds/options.rs rename to crates/ui-egui/src/menus/view_cmds/options.rs diff --git a/crates/ui-egui/src/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs similarity index 100% rename from crates/ui-egui/src/view_cmds/tests.rs rename to crates/ui-egui/src/menus/view_cmds/tests.rs diff --git a/crates/ui-egui/src/workspace_ui.rs b/crates/ui-egui/src/menus/workspace_ui.rs similarity index 100% rename from crates/ui-egui/src/workspace_ui.rs rename to crates/ui-egui/src/menus/workspace_ui.rs From afd0b1c1081a63445da411d4d8a04d961c45b0cb Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 21:30:42 +0000 Subject: [PATCH 240/259] refactor(ui-egui): move widgets modules under widgets/ --- crates/ui-egui/src/lib.rs | 18 +++++++++--------- crates/ui-egui/src/widgets.rs | 9 +++++++++ crates/ui-egui/src/{ => widgets}/field_tab.rs | 0 .../ui-egui/src/{ => widgets}/field_wheel.rs | 0 .../src/{ => widgets}/numeric_expression.rs | 0 .../ui-egui/src/{ => widgets}/point_curve.rs | 0 crates/ui-egui/src/{ => widgets}/press_menu.rs | 0 crates/ui-egui/src/{ => widgets}/swap_arrow.rs | 0 crates/ui-egui/src/{ => widgets}/tab_strip.rs | 0 .../src/{ => widgets}/text_field_menu.rs | 0 crates/ui-egui/src/{ => widgets}/tone.rs | 0 11 files changed, 18 insertions(+), 9 deletions(-) rename crates/ui-egui/src/{ => widgets}/field_tab.rs (100%) rename crates/ui-egui/src/{ => widgets}/field_wheel.rs (100%) rename crates/ui-egui/src/{ => widgets}/numeric_expression.rs (100%) rename crates/ui-egui/src/{ => widgets}/point_curve.rs (100%) rename crates/ui-egui/src/{ => widgets}/press_menu.rs (100%) rename crates/ui-egui/src/{ => widgets}/swap_arrow.rs (100%) rename crates/ui-egui/src/{ => widgets}/tab_strip.rs (100%) rename crates/ui-egui/src/{ => widgets}/text_field_menu.rs (100%) rename crates/ui-egui/src/{ => widgets}/tone.rs (100%) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index be9c058080..7fd5a2559b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -44,8 +44,6 @@ pub mod dock; pub mod egui_fonts; pub mod eraser_ui; pub mod eyedropper_ui; -pub mod field_tab; -pub mod field_wheel; pub mod file_dialog; pub mod file_open; pub mod flick_pan; @@ -74,17 +72,14 @@ pub mod move_lock; pub mod move_mods; pub mod notices; pub mod nudge_bundle; -mod numeric_expression; pub mod object_finder; mod opacity_keys; mod page_keys; pub mod panels; pub mod perspective_crop_ui; pub mod perspective_ui; -pub mod point_curve; pub mod prefs_ui; pub mod preset_files_ui; -pub mod press_menu; mod pressure_curve_ui; pub mod proxy; pub mod puppet_ui; @@ -106,14 +101,10 @@ pub mod stroke_constraint; pub mod stroke_trace; pub mod stroke_trail; pub mod stylus; -pub mod swap_arrow; pub mod symmetry_ui; -mod tab_strip; pub mod texel_guard; -pub mod text_field_menu; pub mod theme; pub use titlebar::{Caption, CaptionFamily, CaptionIcon, CaptionIcons, CaptionStyle, RenderIconFn}; -pub mod tone; pub(crate) mod tool_memory; mod tool_reset; mod tool_shortcuts; @@ -296,6 +287,15 @@ pub use services::{ FileStampFn, FormatChoices, ImportFn, Inbox, LoadTextFn, OpenUrlFn, OsEventsFn, PhotoshopShortcutsFn, QuitFn, RecoverFn, Recoverable, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, WindowFrameFn, WriteFn, }; +pub use widgets::field_tab; +pub use widgets::field_wheel; +use widgets::numeric_expression; +pub use widgets::point_curve; +pub use widgets::press_menu; +pub use widgets::swap_arrow; +use widgets::tab_strip; +pub use widgets::text_field_menu; +pub use widgets::tone; /// The Info panel's cached sample: pixel x, y, document revision and Eyedropper Sample Size. type InfoSampleKey = (i32, i32, u64, u32); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 55463ddcf8..8be17ebf3d 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -15,11 +15,20 @@ pub use type_ahead::list_open as dropdown_list_open; mod buttons; mod color; mod dropdown; +pub mod field_tab; +pub mod field_wheel; mod fields; +pub(super) mod numeric_expression; mod panel; +pub mod point_curve; +pub mod press_menu; mod scrub; mod slider; +pub mod swap_arrow; +pub(super) mod tab_strip; mod text_field; +pub mod text_field_menu; +pub mod tone; mod units; pub use buttons::{ diff --git a/crates/ui-egui/src/field_tab.rs b/crates/ui-egui/src/widgets/field_tab.rs similarity index 100% rename from crates/ui-egui/src/field_tab.rs rename to crates/ui-egui/src/widgets/field_tab.rs diff --git a/crates/ui-egui/src/field_wheel.rs b/crates/ui-egui/src/widgets/field_wheel.rs similarity index 100% rename from crates/ui-egui/src/field_wheel.rs rename to crates/ui-egui/src/widgets/field_wheel.rs diff --git a/crates/ui-egui/src/numeric_expression.rs b/crates/ui-egui/src/widgets/numeric_expression.rs similarity index 100% rename from crates/ui-egui/src/numeric_expression.rs rename to crates/ui-egui/src/widgets/numeric_expression.rs diff --git a/crates/ui-egui/src/point_curve.rs b/crates/ui-egui/src/widgets/point_curve.rs similarity index 100% rename from crates/ui-egui/src/point_curve.rs rename to crates/ui-egui/src/widgets/point_curve.rs diff --git a/crates/ui-egui/src/press_menu.rs b/crates/ui-egui/src/widgets/press_menu.rs similarity index 100% rename from crates/ui-egui/src/press_menu.rs rename to crates/ui-egui/src/widgets/press_menu.rs diff --git a/crates/ui-egui/src/swap_arrow.rs b/crates/ui-egui/src/widgets/swap_arrow.rs similarity index 100% rename from crates/ui-egui/src/swap_arrow.rs rename to crates/ui-egui/src/widgets/swap_arrow.rs diff --git a/crates/ui-egui/src/tab_strip.rs b/crates/ui-egui/src/widgets/tab_strip.rs similarity index 100% rename from crates/ui-egui/src/tab_strip.rs rename to crates/ui-egui/src/widgets/tab_strip.rs diff --git a/crates/ui-egui/src/text_field_menu.rs b/crates/ui-egui/src/widgets/text_field_menu.rs similarity index 100% rename from crates/ui-egui/src/text_field_menu.rs rename to crates/ui-egui/src/widgets/text_field_menu.rs diff --git a/crates/ui-egui/src/tone.rs b/crates/ui-egui/src/widgets/tone.rs similarity index 100% rename from crates/ui-egui/src/tone.rs rename to crates/ui-egui/src/widgets/tone.rs From 36199e41c3c7045d1b7f2178d029ddc56749cb12 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 21:42:17 +0000 Subject: [PATCH 241/259] refactor(ui-egui): move tools modules under tools/ --- crates/ui-egui/src/lib.rs | 107 +++++++++--------- crates/ui-egui/src/tools.rs | 53 +++++++++ crates/ui-egui/src/{ => tools}/align_bar.rs | 0 crates/ui-egui/src/{ => tools}/analysis_ui.rs | 0 .../src/{ => tools}/analysis_ui/tests.rs | 0 .../ui-egui/src/{ => tools}/anchor_tools.rs | 0 .../src/{ => tools}/anchor_tools/tests.rs | 0 .../ui-egui/src/{ => tools}/artboard_tool.rs | 0 .../ui-egui/src/{ => tools}/brush_cursor.rs | 0 .../ui-egui/src/{ => tools}/brush_picker.rs | 0 .../ui-egui/src/{ => tools}/brush_resize.rs | 0 .../src/{ => tools}/brush_resize/tests.rs | 0 .../ui-egui/src/{ => tools}/cam_transform.rs | 0 .../ui-egui/src/{ => tools}/cas_transform.rs | 0 .../ui-egui/src/{ => tools}/corner_radius.rs | 0 .../src/{ => tools}/corner_radius/tests.rs | 0 crates/ui-egui/src/{ => tools}/crop_mode.rs | 0 .../src/{ => tools}/crop_mode/tests.rs | 7 +- .../ui-egui/src/{ => tools}/crop_overlay.rs | 0 .../ui-egui/src/{ => tools}/crop_presets.rs | 0 crates/ui-egui/src/{ => tools}/crop_shield.rs | 0 crates/ui-egui/src/{ => tools}/crop_size.rs | 0 .../src/{ => tools}/crop_straighten.rs | 0 crates/ui-egui/src/{ => tools}/crop_ui.rs | 0 .../ui-egui/src/{ => tools}/crop_ui/tests.rs | 0 .../ui-egui/src/{ => tools}/direct_select.rs | 0 .../src/{ => tools}/direct_select/tests.rs | 0 crates/ui-egui/src/{ => tools}/eraser_ui.rs | 0 .../ui-egui/src/{ => tools}/eyedropper_ui.rs | 0 crates/ui-egui/src/{ => tools}/frame_tool.rs | 0 crates/ui-egui/src/{ => tools}/gradient_ui.rs | 0 .../{ => tools}/gradient_ui/editor_tests.rs | 0 .../gradient_ui/properties_panel.rs | 0 .../src/{ => tools}/gradient_ui/tests.rs | 0 crates/ui-egui/src/{ => tools}/lasso_ui.rs | 0 .../ui-egui/src/{ => tools}/lasso_ui/tests.rs | 0 .../src/{ => tools}/magnetic_lasso_ui.rs | 0 .../{ => tools}/magnetic_lasso_ui/tests.rs | 0 crates/ui-egui/src/{ => tools}/move_box.rs | 0 .../ui-egui/src/{ => tools}/move_distance.rs | 0 crates/ui-egui/src/{ => tools}/move_hover.rs | 0 crates/ui-egui/src/{ => tools}/move_lock.rs | 0 crates/ui-egui/src/{ => tools}/move_mods.rs | 0 .../src/{ => tools}/move_mods/tests.rs | 0 .../ui-egui/src/{ => tools}/object_finder.rs | 0 .../src/{ => tools}/perspective_crop_ui.rs | 0 .../ui-egui/src/{ => tools}/perspective_ui.rs | 0 crates/ui-egui/src/{ => tools}/puppet_ui.rs | 0 .../src/{ => tools}/puppet_ui/tests.rs | 0 crates/ui-egui/src/{ => tools}/retouch_ui.rs | 0 .../src/{ => tools}/retouch_ui/tests.rs | 0 .../src/{ => tools}/shape_gradient_ui.rs | 0 .../ui-egui/src/{ => tools}/shape_options.rs | 0 .../ui-egui/src/{ => tools}/shape_paint_ui.rs | 0 .../src/{ => tools}/shape_stroke_ui.rs | 0 .../src/{ => tools}/shape_stroke_ui/editor.rs | 0 .../shape_stroke_ui/shortcut_tests.rs | 0 .../src/{ => tools}/shape_stroke_ui/tests.rs | 0 crates/ui-egui/src/{ => tools}/slice_ui.rs | 0 .../ui-egui/src/{ => tools}/slice_ui/tests.rs | 0 .../src/{ => tools}/stroke_constraint.rs | 0 .../ui-egui/src/{ => tools}/stroke_trace.rs | 0 .../ui-egui/src/{ => tools}/stroke_trail.rs | 0 crates/ui-egui/src/{ => tools}/symmetry_ui.rs | 0 .../src/{ => tools}/symmetry_ui/tests.rs | 0 crates/ui-egui/src/{ => tools}/tool_reset.rs | 0 .../ui-egui/src/{ => tools}/transform_fx.rs | 0 .../ui-egui/src/{ => tools}/transform_tex.rs | 0 .../ui-egui/src/{ => tools}/transform_tool.rs | 0 .../src/{ => tools}/transform_tool/begin.rs | 0 .../src/{ => tools}/transform_tool/commit.rs | 0 .../{ => tools}/transform_tool/drag_modes.rs | 0 .../src/{ => tools}/transform_tool/draw.rs | 0 .../{ => tools}/transform_tool/options_bar.rs | 0 .../src/{ => tools}/transform_tool/pointer.rs | 0 .../src/{ => tools}/transform_tool/preview.rs | 0 .../src/{ => tools}/transform_tool/tests.rs | 0 .../src/{ => tools}/transform_tool/warp.rs | 0 .../src/{ => tools}/type_font_preview.rs | 0 crates/ui-egui/src/{ => tools}/type_tool.rs | 16 +-- .../src/{ => tools}/type_tool/canvas_tests.rs | 0 .../src/{ => tools}/type_tool/commit_tests.rs | 0 .../src/{ => tools}/type_tool/defaults.rs | 0 .../src/{ => tools}/type_tool/editing.rs | 0 .../type_tool/font_picker_tests.rs | 0 .../src/{ => tools}/type_tool/fonts.rs | 0 .../ui-egui/src/{ => tools}/type_tool/ime.rs | 0 .../src/{ => tools}/type_tool/ime_edit.rs | 0 .../src/{ => tools}/type_tool/ime_tests.rs | 28 ++--- .../ui-egui/src/{ => tools}/type_tool/keys.rs | 0 .../src/{ => tools}/type_tool/layout.rs | 0 .../src/{ => tools}/type_tool/options_bar.rs | 0 .../src/{ => tools}/type_tool/overlay.rs | 0 .../src/{ => tools}/type_tool/panel.rs | 0 .../src/{ => tools}/type_tool/pointer.rs | 0 .../src/{ => tools}/type_tool/tests.rs | 0 .../ui-egui/src/{ => tools}/type_transform.rs | 0 crates/ui-egui/src/{ => tools}/vector_ui.rs | 0 .../src/{ => tools}/vector_ui/curvature.rs | 0 .../src/{ => tools}/vector_ui/options.rs | 0 .../src/{ => tools}/vector_ui/overlay.rs | 0 .../src/{ => tools}/vector_ui/paint_tests.rs | 0 .../src/{ => tools}/vector_ui/path_ops.rs | 0 .../vector_ui/path_selection_tests.rs | 0 .../src/{ => tools}/vector_ui/paths_panel.rs | 0 .../ui-egui/src/{ => tools}/vector_ui/pen.rs | 0 .../{ => tools}/vector_ui/pen_draw_tests.rs | 0 .../src/{ => tools}/vector_ui/shapes.rs | 0 .../src/{ => tools}/vector_ui/tests.rs | 0 .../ui-egui/src/{ => tools}/warp_preview.rs | 0 crates/ui-egui/src/{ => tools}/zoom_tool.rs | 0 .../src/{ => tools}/zoom_tool/tests.rs | 0 112 files changed, 127 insertions(+), 84 deletions(-) create mode 100644 crates/ui-egui/src/tools.rs rename crates/ui-egui/src/{ => tools}/align_bar.rs (100%) rename crates/ui-egui/src/{ => tools}/analysis_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/analysis_ui/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/anchor_tools.rs (100%) rename crates/ui-egui/src/{ => tools}/anchor_tools/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/artboard_tool.rs (100%) rename crates/ui-egui/src/{ => tools}/brush_cursor.rs (100%) rename crates/ui-egui/src/{ => tools}/brush_picker.rs (100%) rename crates/ui-egui/src/{ => tools}/brush_resize.rs (100%) rename crates/ui-egui/src/{ => tools}/brush_resize/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/cam_transform.rs (100%) rename crates/ui-egui/src/{ => tools}/cas_transform.rs (100%) rename crates/ui-egui/src/{ => tools}/corner_radius.rs (100%) rename crates/ui-egui/src/{ => tools}/corner_radius/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/crop_mode.rs (100%) rename crates/ui-egui/src/{ => tools}/crop_mode/tests.rs (99%) rename crates/ui-egui/src/{ => tools}/crop_overlay.rs (100%) rename crates/ui-egui/src/{ => tools}/crop_presets.rs (100%) rename crates/ui-egui/src/{ => tools}/crop_shield.rs (100%) rename crates/ui-egui/src/{ => tools}/crop_size.rs (100%) rename crates/ui-egui/src/{ => tools}/crop_straighten.rs (100%) rename crates/ui-egui/src/{ => tools}/crop_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/crop_ui/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/direct_select.rs (100%) rename crates/ui-egui/src/{ => tools}/direct_select/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/eraser_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/eyedropper_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/frame_tool.rs (100%) rename crates/ui-egui/src/{ => tools}/gradient_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/gradient_ui/editor_tests.rs (100%) rename crates/ui-egui/src/{ => tools}/gradient_ui/properties_panel.rs (100%) rename crates/ui-egui/src/{ => tools}/gradient_ui/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/lasso_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/lasso_ui/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/magnetic_lasso_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/magnetic_lasso_ui/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/move_box.rs (100%) rename crates/ui-egui/src/{ => tools}/move_distance.rs (100%) rename crates/ui-egui/src/{ => tools}/move_hover.rs (100%) rename crates/ui-egui/src/{ => tools}/move_lock.rs (100%) rename crates/ui-egui/src/{ => tools}/move_mods.rs (100%) rename crates/ui-egui/src/{ => tools}/move_mods/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/object_finder.rs (100%) rename crates/ui-egui/src/{ => tools}/perspective_crop_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/perspective_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/puppet_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/puppet_ui/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/retouch_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/retouch_ui/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/shape_gradient_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/shape_options.rs (100%) rename crates/ui-egui/src/{ => tools}/shape_paint_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/shape_stroke_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/shape_stroke_ui/editor.rs (100%) rename crates/ui-egui/src/{ => tools}/shape_stroke_ui/shortcut_tests.rs (100%) rename crates/ui-egui/src/{ => tools}/shape_stroke_ui/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/slice_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/slice_ui/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/stroke_constraint.rs (100%) rename crates/ui-egui/src/{ => tools}/stroke_trace.rs (100%) rename crates/ui-egui/src/{ => tools}/stroke_trail.rs (100%) rename crates/ui-egui/src/{ => tools}/symmetry_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/symmetry_ui/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/tool_reset.rs (100%) rename crates/ui-egui/src/{ => tools}/transform_fx.rs (100%) rename crates/ui-egui/src/{ => tools}/transform_tex.rs (100%) rename crates/ui-egui/src/{ => tools}/transform_tool.rs (100%) rename crates/ui-egui/src/{ => tools}/transform_tool/begin.rs (100%) rename crates/ui-egui/src/{ => tools}/transform_tool/commit.rs (100%) rename crates/ui-egui/src/{ => tools}/transform_tool/drag_modes.rs (100%) rename crates/ui-egui/src/{ => tools}/transform_tool/draw.rs (100%) rename crates/ui-egui/src/{ => tools}/transform_tool/options_bar.rs (100%) rename crates/ui-egui/src/{ => tools}/transform_tool/pointer.rs (100%) rename crates/ui-egui/src/{ => tools}/transform_tool/preview.rs (100%) rename crates/ui-egui/src/{ => tools}/transform_tool/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/transform_tool/warp.rs (100%) rename crates/ui-egui/src/{ => tools}/type_font_preview.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool.rs (93%) rename crates/ui-egui/src/{ => tools}/type_tool/canvas_tests.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool/commit_tests.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool/defaults.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool/editing.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool/font_picker_tests.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool/fonts.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool/ime.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool/ime_edit.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool/ime_tests.rs (97%) rename crates/ui-egui/src/{ => tools}/type_tool/keys.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool/layout.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool/options_bar.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool/overlay.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool/panel.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool/pointer.rs (100%) rename crates/ui-egui/src/{ => tools}/type_tool/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/type_transform.rs (100%) rename crates/ui-egui/src/{ => tools}/vector_ui.rs (100%) rename crates/ui-egui/src/{ => tools}/vector_ui/curvature.rs (100%) rename crates/ui-egui/src/{ => tools}/vector_ui/options.rs (100%) rename crates/ui-egui/src/{ => tools}/vector_ui/overlay.rs (100%) rename crates/ui-egui/src/{ => tools}/vector_ui/paint_tests.rs (100%) rename crates/ui-egui/src/{ => tools}/vector_ui/path_ops.rs (100%) rename crates/ui-egui/src/{ => tools}/vector_ui/path_selection_tests.rs (100%) rename crates/ui-egui/src/{ => tools}/vector_ui/paths_panel.rs (100%) rename crates/ui-egui/src/{ => tools}/vector_ui/pen.rs (100%) rename crates/ui-egui/src/{ => tools}/vector_ui/pen_draw_tests.rs (100%) rename crates/ui-egui/src/{ => tools}/vector_ui/shapes.rs (100%) rename crates/ui-egui/src/{ => tools}/vector_ui/tests.rs (100%) rename crates/ui-egui/src/{ => tools}/warp_preview.rs (100%) rename crates/ui-egui/src/{ => tools}/zoom_tool.rs (100%) rename crates/ui-egui/src/{ => tools}/zoom_tool/tests.rs (100%) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7fd5a2559b..79d631753f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -13,114 +13,61 @@ macro_rules! tl { $crate::i18n::t($s) }; } -mod align_bar; mod alt_grab; -pub mod analysis_ui; -pub mod anchor_tools; -pub mod artboard_tool; pub mod bidi_text; mod blend_keys; -pub(crate) mod brush_cursor; -pub mod brush_picker; -pub mod brush_resize; -mod cam_transform; pub mod canvas; -pub mod cas_transform; pub mod cjk_fonts; pub mod control; mod control_click; -pub mod corner_radius; -pub mod crop_mode; -pub mod crop_overlay; -pub mod crop_presets; -pub mod crop_shield; -pub mod crop_size; -pub mod crop_straighten; -pub mod crop_ui; pub mod dialogs; -pub mod direct_select; pub mod direction; pub mod dock; pub mod egui_fonts; -pub mod eraser_ui; -pub mod eyedropper_ui; pub mod file_dialog; pub mod file_open; pub mod flick_pan; mod font_preview; -pub mod frame_tool; pub mod gpu_status; -pub mod gradient_ui; pub mod hold_keys; pub mod i18n; mod icon_data; pub mod icons; pub mod jobs_ui; pub mod kys_import; -pub mod lasso_ui; pub(crate) mod last_brush; mod layout_keys; pub mod links; -pub mod magnetic_lasso_ui; pub mod menu_catalog; pub mod menus; pub mod monitor_status; -pub mod move_box; -pub mod move_distance; -pub mod move_hover; -pub mod move_lock; -pub mod move_mods; pub mod notices; pub mod nudge_bundle; -pub mod object_finder; mod opacity_keys; mod page_keys; pub mod panels; -pub mod perspective_crop_ui; -pub mod perspective_ui; pub mod prefs_ui; pub mod preset_files_ui; mod pressure_curve_ui; pub mod proxy; -pub mod puppet_ui; -pub mod retouch_ui; pub mod screenshot; mod scrub_wrap; pub mod served_fonts; -mod shape_gradient_ui; -mod shape_options; -mod shape_paint_ui; -pub mod shape_stroke_ui; pub mod shortcut_dispatch; pub mod shortcuts; mod single_line_drag; -pub mod slice_ui; pub mod spring_tools; pub mod state; -pub mod stroke_constraint; -pub mod stroke_trace; -pub mod stroke_trail; pub mod stylus; -pub mod symmetry_ui; pub mod texel_guard; pub mod theme; pub use titlebar::{Caption, CaptionFamily, CaptionIcon, CaptionIcons, CaptionStyle, RenderIconFn}; pub(crate) mod tool_memory; -mod tool_reset; mod tool_shortcuts; pub mod touch_twins; -pub mod transform_fx; -pub mod transform_tex; -pub mod transform_tool; -mod type_font_preview; -pub mod type_tool; -mod type_transform; pub mod updates_ui; -pub mod vector_ui; -pub mod warp_preview; pub mod widgets; pub mod work_area; -pub mod zoom_tool; use std::collections::HashMap; use std::sync::mpsc::{Receiver, Sender}; @@ -136,6 +83,7 @@ pub use state::{Tool, UiState}; mod app; mod services; +mod tools; #[cfg(test)] use app::layer_thumb_frame; @@ -287,6 +235,59 @@ pub use services::{ FileStampFn, FormatChoices, ImportFn, Inbox, LoadTextFn, OpenUrlFn, OsEventsFn, PhotoshopShortcutsFn, QuitFn, RecoverFn, Recoverable, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, WindowFrameFn, WriteFn, }; +use tools::align_bar; +pub use tools::analysis_ui; +pub use tools::anchor_tools; +pub use tools::artboard_tool; +pub(crate) use tools::brush_cursor; +pub use tools::brush_picker; +pub use tools::brush_resize; +use tools::cam_transform; +pub use tools::cas_transform; +pub use tools::corner_radius; +pub use tools::crop_mode; +pub use tools::crop_overlay; +pub use tools::crop_presets; +pub use tools::crop_shield; +pub use tools::crop_size; +pub use tools::crop_straighten; +pub use tools::crop_ui; +pub use tools::direct_select; +pub use tools::eraser_ui; +pub use tools::eyedropper_ui; +pub use tools::frame_tool; +pub use tools::gradient_ui; +pub use tools::lasso_ui; +pub use tools::magnetic_lasso_ui; +pub use tools::move_box; +pub use tools::move_distance; +pub use tools::move_hover; +pub use tools::move_lock; +pub use tools::move_mods; +pub use tools::object_finder; +pub use tools::perspective_crop_ui; +pub use tools::perspective_ui; +pub use tools::puppet_ui; +pub use tools::retouch_ui; +use tools::shape_gradient_ui; +use tools::shape_options; +use tools::shape_paint_ui; +pub use tools::shape_stroke_ui; +pub use tools::slice_ui; +pub use tools::stroke_constraint; +pub use tools::stroke_trace; +pub use tools::stroke_trail; +pub use tools::symmetry_ui; +use tools::tool_reset; +pub use tools::transform_fx; +pub use tools::transform_tex; +pub use tools::transform_tool; +use tools::type_font_preview; +pub use tools::type_tool; +use tools::type_transform; +pub use tools::vector_ui; +pub use tools::warp_preview; +pub use tools::zoom_tool; pub use widgets::field_tab; pub use widgets::field_wheel; use widgets::numeric_expression; diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs new file mode 100644 index 0000000000..27dfed9190 --- /dev/null +++ b/crates/ui-egui/src/tools.rs @@ -0,0 +1,53 @@ +pub(super) mod align_bar; +pub mod analysis_ui; +pub mod anchor_tools; +pub mod artboard_tool; +pub(crate) mod brush_cursor; +pub mod brush_picker; +pub mod brush_resize; +pub(super) mod cam_transform; +pub mod cas_transform; +pub mod corner_radius; +pub mod crop_mode; +pub mod crop_overlay; +pub mod crop_presets; +pub mod crop_shield; +pub mod crop_size; +pub mod crop_straighten; +pub mod crop_ui; +pub mod direct_select; +pub mod eraser_ui; +pub mod eyedropper_ui; +pub mod frame_tool; +pub mod gradient_ui; +pub mod lasso_ui; +pub mod magnetic_lasso_ui; +pub mod move_box; +pub mod move_distance; +pub mod move_hover; +pub mod move_lock; +pub mod move_mods; +pub mod object_finder; +pub mod perspective_crop_ui; +pub mod perspective_ui; +pub mod puppet_ui; +pub mod retouch_ui; +pub(super) mod shape_gradient_ui; +pub(super) mod shape_options; +pub(super) mod shape_paint_ui; +pub mod shape_stroke_ui; +pub mod slice_ui; +pub mod stroke_constraint; +pub mod stroke_trace; +pub mod stroke_trail; +pub mod symmetry_ui; +pub(super) mod tool_reset; +pub mod transform_fx; +pub mod transform_tex; +pub mod transform_tool; +pub(super) mod type_font_preview; +pub mod type_tool; +pub(super) mod type_transform; +pub mod vector_ui; +pub mod warp_preview; +pub mod zoom_tool; diff --git a/crates/ui-egui/src/align_bar.rs b/crates/ui-egui/src/tools/align_bar.rs similarity index 100% rename from crates/ui-egui/src/align_bar.rs rename to crates/ui-egui/src/tools/align_bar.rs diff --git a/crates/ui-egui/src/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs similarity index 100% rename from crates/ui-egui/src/analysis_ui.rs rename to crates/ui-egui/src/tools/analysis_ui.rs diff --git a/crates/ui-egui/src/analysis_ui/tests.rs b/crates/ui-egui/src/tools/analysis_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/analysis_ui/tests.rs rename to crates/ui-egui/src/tools/analysis_ui/tests.rs diff --git a/crates/ui-egui/src/anchor_tools.rs b/crates/ui-egui/src/tools/anchor_tools.rs similarity index 100% rename from crates/ui-egui/src/anchor_tools.rs rename to crates/ui-egui/src/tools/anchor_tools.rs diff --git a/crates/ui-egui/src/anchor_tools/tests.rs b/crates/ui-egui/src/tools/anchor_tools/tests.rs similarity index 100% rename from crates/ui-egui/src/anchor_tools/tests.rs rename to crates/ui-egui/src/tools/anchor_tools/tests.rs diff --git a/crates/ui-egui/src/artboard_tool.rs b/crates/ui-egui/src/tools/artboard_tool.rs similarity index 100% rename from crates/ui-egui/src/artboard_tool.rs rename to crates/ui-egui/src/tools/artboard_tool.rs diff --git a/crates/ui-egui/src/brush_cursor.rs b/crates/ui-egui/src/tools/brush_cursor.rs similarity index 100% rename from crates/ui-egui/src/brush_cursor.rs rename to crates/ui-egui/src/tools/brush_cursor.rs diff --git a/crates/ui-egui/src/brush_picker.rs b/crates/ui-egui/src/tools/brush_picker.rs similarity index 100% rename from crates/ui-egui/src/brush_picker.rs rename to crates/ui-egui/src/tools/brush_picker.rs diff --git a/crates/ui-egui/src/brush_resize.rs b/crates/ui-egui/src/tools/brush_resize.rs similarity index 100% rename from crates/ui-egui/src/brush_resize.rs rename to crates/ui-egui/src/tools/brush_resize.rs diff --git a/crates/ui-egui/src/brush_resize/tests.rs b/crates/ui-egui/src/tools/brush_resize/tests.rs similarity index 100% rename from crates/ui-egui/src/brush_resize/tests.rs rename to crates/ui-egui/src/tools/brush_resize/tests.rs diff --git a/crates/ui-egui/src/cam_transform.rs b/crates/ui-egui/src/tools/cam_transform.rs similarity index 100% rename from crates/ui-egui/src/cam_transform.rs rename to crates/ui-egui/src/tools/cam_transform.rs diff --git a/crates/ui-egui/src/cas_transform.rs b/crates/ui-egui/src/tools/cas_transform.rs similarity index 100% rename from crates/ui-egui/src/cas_transform.rs rename to crates/ui-egui/src/tools/cas_transform.rs diff --git a/crates/ui-egui/src/corner_radius.rs b/crates/ui-egui/src/tools/corner_radius.rs similarity index 100% rename from crates/ui-egui/src/corner_radius.rs rename to crates/ui-egui/src/tools/corner_radius.rs diff --git a/crates/ui-egui/src/corner_radius/tests.rs b/crates/ui-egui/src/tools/corner_radius/tests.rs similarity index 100% rename from crates/ui-egui/src/corner_radius/tests.rs rename to crates/ui-egui/src/tools/corner_radius/tests.rs diff --git a/crates/ui-egui/src/crop_mode.rs b/crates/ui-egui/src/tools/crop_mode.rs similarity index 100% rename from crates/ui-egui/src/crop_mode.rs rename to crates/ui-egui/src/tools/crop_mode.rs diff --git a/crates/ui-egui/src/crop_mode/tests.rs b/crates/ui-egui/src/tools/crop_mode/tests.rs similarity index 99% rename from crates/ui-egui/src/crop_mode/tests.rs rename to crates/ui-egui/src/tools/crop_mode/tests.rs index 0abd3c40f4..5f059917c9 100644 --- a/crates/ui-egui/src/crop_mode/tests.rs +++ b/crates/ui-egui/src/tools/crop_mode/tests.rs @@ -625,9 +625,7 @@ fn ui_pointer_drives_the_default_mode_in_press_coordinates() { #[test] fn degenerate_input_never_panics() { let mut app = app(); - for frame in - [[0.0, 0.0, 0.0, 0.0], [5.0, 5.0, 5.0, 5.0], [f64::NAN, 0.0, 10.0, 10.0], [f64::INFINITY, 0.0, 1e300, 1e300], [-1e300, -1e300, 1e300, 1e300]] - { + for frame in [[0.0, 0.0, 0.0, 0.0], [5.0, 5.0, 5.0, 5.0], [f64::NAN, 0.0, 10.0, 10.0], [f64::INFINITY, 0.0, 1e300, 1e300], [-1e300, -1e300, 1e300, 1e300]] { for angle in [0.0, f64::NAN, f64::INFINITY, 1e300, -720.5] { app.ui.crop_rect = Some(frame); app.ui.crop_angle = angle; @@ -739,8 +737,7 @@ fn a_recrop_handle_snaps_exactly_to_the_hidden_pixels_edge() { .iter() .any(|l| l.vertical == vertical && l.pos == pos && l.kind == photocraft_engine::snap::SnapKind::LayerEdge) }; - (hx == 0 || on(true, if hx < 0 { hidden[0] } else { hidden[2] })) - && (hy == 0 || on(false, if hy < 0 { hidden[1] } else { hidden[3] })) + (hx == 0 || on(true, if hx < 0 { hidden[0] } else { hidden[2] })) && (hy == 0 || on(false, if hy < 0 { hidden[1] } else { hidden[3] })) }; let mut end = None; for i in 1..=80 { diff --git a/crates/ui-egui/src/crop_overlay.rs b/crates/ui-egui/src/tools/crop_overlay.rs similarity index 100% rename from crates/ui-egui/src/crop_overlay.rs rename to crates/ui-egui/src/tools/crop_overlay.rs diff --git a/crates/ui-egui/src/crop_presets.rs b/crates/ui-egui/src/tools/crop_presets.rs similarity index 100% rename from crates/ui-egui/src/crop_presets.rs rename to crates/ui-egui/src/tools/crop_presets.rs diff --git a/crates/ui-egui/src/crop_shield.rs b/crates/ui-egui/src/tools/crop_shield.rs similarity index 100% rename from crates/ui-egui/src/crop_shield.rs rename to crates/ui-egui/src/tools/crop_shield.rs diff --git a/crates/ui-egui/src/crop_size.rs b/crates/ui-egui/src/tools/crop_size.rs similarity index 100% rename from crates/ui-egui/src/crop_size.rs rename to crates/ui-egui/src/tools/crop_size.rs diff --git a/crates/ui-egui/src/crop_straighten.rs b/crates/ui-egui/src/tools/crop_straighten.rs similarity index 100% rename from crates/ui-egui/src/crop_straighten.rs rename to crates/ui-egui/src/tools/crop_straighten.rs diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/tools/crop_ui.rs similarity index 100% rename from crates/ui-egui/src/crop_ui.rs rename to crates/ui-egui/src/tools/crop_ui.rs diff --git a/crates/ui-egui/src/crop_ui/tests.rs b/crates/ui-egui/src/tools/crop_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/crop_ui/tests.rs rename to crates/ui-egui/src/tools/crop_ui/tests.rs diff --git a/crates/ui-egui/src/direct_select.rs b/crates/ui-egui/src/tools/direct_select.rs similarity index 100% rename from crates/ui-egui/src/direct_select.rs rename to crates/ui-egui/src/tools/direct_select.rs diff --git a/crates/ui-egui/src/direct_select/tests.rs b/crates/ui-egui/src/tools/direct_select/tests.rs similarity index 100% rename from crates/ui-egui/src/direct_select/tests.rs rename to crates/ui-egui/src/tools/direct_select/tests.rs diff --git a/crates/ui-egui/src/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs similarity index 100% rename from crates/ui-egui/src/eraser_ui.rs rename to crates/ui-egui/src/tools/eraser_ui.rs diff --git a/crates/ui-egui/src/eyedropper_ui.rs b/crates/ui-egui/src/tools/eyedropper_ui.rs similarity index 100% rename from crates/ui-egui/src/eyedropper_ui.rs rename to crates/ui-egui/src/tools/eyedropper_ui.rs diff --git a/crates/ui-egui/src/frame_tool.rs b/crates/ui-egui/src/tools/frame_tool.rs similarity index 100% rename from crates/ui-egui/src/frame_tool.rs rename to crates/ui-egui/src/tools/frame_tool.rs diff --git a/crates/ui-egui/src/gradient_ui.rs b/crates/ui-egui/src/tools/gradient_ui.rs similarity index 100% rename from crates/ui-egui/src/gradient_ui.rs rename to crates/ui-egui/src/tools/gradient_ui.rs diff --git a/crates/ui-egui/src/gradient_ui/editor_tests.rs b/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs similarity index 100% rename from crates/ui-egui/src/gradient_ui/editor_tests.rs rename to crates/ui-egui/src/tools/gradient_ui/editor_tests.rs diff --git a/crates/ui-egui/src/gradient_ui/properties_panel.rs b/crates/ui-egui/src/tools/gradient_ui/properties_panel.rs similarity index 100% rename from crates/ui-egui/src/gradient_ui/properties_panel.rs rename to crates/ui-egui/src/tools/gradient_ui/properties_panel.rs diff --git a/crates/ui-egui/src/gradient_ui/tests.rs b/crates/ui-egui/src/tools/gradient_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/gradient_ui/tests.rs rename to crates/ui-egui/src/tools/gradient_ui/tests.rs diff --git a/crates/ui-egui/src/lasso_ui.rs b/crates/ui-egui/src/tools/lasso_ui.rs similarity index 100% rename from crates/ui-egui/src/lasso_ui.rs rename to crates/ui-egui/src/tools/lasso_ui.rs diff --git a/crates/ui-egui/src/lasso_ui/tests.rs b/crates/ui-egui/src/tools/lasso_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/lasso_ui/tests.rs rename to crates/ui-egui/src/tools/lasso_ui/tests.rs diff --git a/crates/ui-egui/src/magnetic_lasso_ui.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs similarity index 100% rename from crates/ui-egui/src/magnetic_lasso_ui.rs rename to crates/ui-egui/src/tools/magnetic_lasso_ui.rs diff --git a/crates/ui-egui/src/magnetic_lasso_ui/tests.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/magnetic_lasso_ui/tests.rs rename to crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs diff --git a/crates/ui-egui/src/move_box.rs b/crates/ui-egui/src/tools/move_box.rs similarity index 100% rename from crates/ui-egui/src/move_box.rs rename to crates/ui-egui/src/tools/move_box.rs diff --git a/crates/ui-egui/src/move_distance.rs b/crates/ui-egui/src/tools/move_distance.rs similarity index 100% rename from crates/ui-egui/src/move_distance.rs rename to crates/ui-egui/src/tools/move_distance.rs diff --git a/crates/ui-egui/src/move_hover.rs b/crates/ui-egui/src/tools/move_hover.rs similarity index 100% rename from crates/ui-egui/src/move_hover.rs rename to crates/ui-egui/src/tools/move_hover.rs diff --git a/crates/ui-egui/src/move_lock.rs b/crates/ui-egui/src/tools/move_lock.rs similarity index 100% rename from crates/ui-egui/src/move_lock.rs rename to crates/ui-egui/src/tools/move_lock.rs diff --git a/crates/ui-egui/src/move_mods.rs b/crates/ui-egui/src/tools/move_mods.rs similarity index 100% rename from crates/ui-egui/src/move_mods.rs rename to crates/ui-egui/src/tools/move_mods.rs diff --git a/crates/ui-egui/src/move_mods/tests.rs b/crates/ui-egui/src/tools/move_mods/tests.rs similarity index 100% rename from crates/ui-egui/src/move_mods/tests.rs rename to crates/ui-egui/src/tools/move_mods/tests.rs diff --git a/crates/ui-egui/src/object_finder.rs b/crates/ui-egui/src/tools/object_finder.rs similarity index 100% rename from crates/ui-egui/src/object_finder.rs rename to crates/ui-egui/src/tools/object_finder.rs diff --git a/crates/ui-egui/src/perspective_crop_ui.rs b/crates/ui-egui/src/tools/perspective_crop_ui.rs similarity index 100% rename from crates/ui-egui/src/perspective_crop_ui.rs rename to crates/ui-egui/src/tools/perspective_crop_ui.rs diff --git a/crates/ui-egui/src/perspective_ui.rs b/crates/ui-egui/src/tools/perspective_ui.rs similarity index 100% rename from crates/ui-egui/src/perspective_ui.rs rename to crates/ui-egui/src/tools/perspective_ui.rs diff --git a/crates/ui-egui/src/puppet_ui.rs b/crates/ui-egui/src/tools/puppet_ui.rs similarity index 100% rename from crates/ui-egui/src/puppet_ui.rs rename to crates/ui-egui/src/tools/puppet_ui.rs diff --git a/crates/ui-egui/src/puppet_ui/tests.rs b/crates/ui-egui/src/tools/puppet_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/puppet_ui/tests.rs rename to crates/ui-egui/src/tools/puppet_ui/tests.rs diff --git a/crates/ui-egui/src/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs similarity index 100% rename from crates/ui-egui/src/retouch_ui.rs rename to crates/ui-egui/src/tools/retouch_ui.rs diff --git a/crates/ui-egui/src/retouch_ui/tests.rs b/crates/ui-egui/src/tools/retouch_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/retouch_ui/tests.rs rename to crates/ui-egui/src/tools/retouch_ui/tests.rs diff --git a/crates/ui-egui/src/shape_gradient_ui.rs b/crates/ui-egui/src/tools/shape_gradient_ui.rs similarity index 100% rename from crates/ui-egui/src/shape_gradient_ui.rs rename to crates/ui-egui/src/tools/shape_gradient_ui.rs diff --git a/crates/ui-egui/src/shape_options.rs b/crates/ui-egui/src/tools/shape_options.rs similarity index 100% rename from crates/ui-egui/src/shape_options.rs rename to crates/ui-egui/src/tools/shape_options.rs diff --git a/crates/ui-egui/src/shape_paint_ui.rs b/crates/ui-egui/src/tools/shape_paint_ui.rs similarity index 100% rename from crates/ui-egui/src/shape_paint_ui.rs rename to crates/ui-egui/src/tools/shape_paint_ui.rs diff --git a/crates/ui-egui/src/shape_stroke_ui.rs b/crates/ui-egui/src/tools/shape_stroke_ui.rs similarity index 100% rename from crates/ui-egui/src/shape_stroke_ui.rs rename to crates/ui-egui/src/tools/shape_stroke_ui.rs diff --git a/crates/ui-egui/src/shape_stroke_ui/editor.rs b/crates/ui-egui/src/tools/shape_stroke_ui/editor.rs similarity index 100% rename from crates/ui-egui/src/shape_stroke_ui/editor.rs rename to crates/ui-egui/src/tools/shape_stroke_ui/editor.rs diff --git a/crates/ui-egui/src/shape_stroke_ui/shortcut_tests.rs b/crates/ui-egui/src/tools/shape_stroke_ui/shortcut_tests.rs similarity index 100% rename from crates/ui-egui/src/shape_stroke_ui/shortcut_tests.rs rename to crates/ui-egui/src/tools/shape_stroke_ui/shortcut_tests.rs diff --git a/crates/ui-egui/src/shape_stroke_ui/tests.rs b/crates/ui-egui/src/tools/shape_stroke_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/shape_stroke_ui/tests.rs rename to crates/ui-egui/src/tools/shape_stroke_ui/tests.rs diff --git a/crates/ui-egui/src/slice_ui.rs b/crates/ui-egui/src/tools/slice_ui.rs similarity index 100% rename from crates/ui-egui/src/slice_ui.rs rename to crates/ui-egui/src/tools/slice_ui.rs diff --git a/crates/ui-egui/src/slice_ui/tests.rs b/crates/ui-egui/src/tools/slice_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/slice_ui/tests.rs rename to crates/ui-egui/src/tools/slice_ui/tests.rs diff --git a/crates/ui-egui/src/stroke_constraint.rs b/crates/ui-egui/src/tools/stroke_constraint.rs similarity index 100% rename from crates/ui-egui/src/stroke_constraint.rs rename to crates/ui-egui/src/tools/stroke_constraint.rs diff --git a/crates/ui-egui/src/stroke_trace.rs b/crates/ui-egui/src/tools/stroke_trace.rs similarity index 100% rename from crates/ui-egui/src/stroke_trace.rs rename to crates/ui-egui/src/tools/stroke_trace.rs diff --git a/crates/ui-egui/src/stroke_trail.rs b/crates/ui-egui/src/tools/stroke_trail.rs similarity index 100% rename from crates/ui-egui/src/stroke_trail.rs rename to crates/ui-egui/src/tools/stroke_trail.rs diff --git a/crates/ui-egui/src/symmetry_ui.rs b/crates/ui-egui/src/tools/symmetry_ui.rs similarity index 100% rename from crates/ui-egui/src/symmetry_ui.rs rename to crates/ui-egui/src/tools/symmetry_ui.rs diff --git a/crates/ui-egui/src/symmetry_ui/tests.rs b/crates/ui-egui/src/tools/symmetry_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/symmetry_ui/tests.rs rename to crates/ui-egui/src/tools/symmetry_ui/tests.rs diff --git a/crates/ui-egui/src/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs similarity index 100% rename from crates/ui-egui/src/tool_reset.rs rename to crates/ui-egui/src/tools/tool_reset.rs diff --git a/crates/ui-egui/src/transform_fx.rs b/crates/ui-egui/src/tools/transform_fx.rs similarity index 100% rename from crates/ui-egui/src/transform_fx.rs rename to crates/ui-egui/src/tools/transform_fx.rs diff --git a/crates/ui-egui/src/transform_tex.rs b/crates/ui-egui/src/tools/transform_tex.rs similarity index 100% rename from crates/ui-egui/src/transform_tex.rs rename to crates/ui-egui/src/tools/transform_tex.rs diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/tools/transform_tool.rs similarity index 100% rename from crates/ui-egui/src/transform_tool.rs rename to crates/ui-egui/src/tools/transform_tool.rs diff --git a/crates/ui-egui/src/transform_tool/begin.rs b/crates/ui-egui/src/tools/transform_tool/begin.rs similarity index 100% rename from crates/ui-egui/src/transform_tool/begin.rs rename to crates/ui-egui/src/tools/transform_tool/begin.rs diff --git a/crates/ui-egui/src/transform_tool/commit.rs b/crates/ui-egui/src/tools/transform_tool/commit.rs similarity index 100% rename from crates/ui-egui/src/transform_tool/commit.rs rename to crates/ui-egui/src/tools/transform_tool/commit.rs diff --git a/crates/ui-egui/src/transform_tool/drag_modes.rs b/crates/ui-egui/src/tools/transform_tool/drag_modes.rs similarity index 100% rename from crates/ui-egui/src/transform_tool/drag_modes.rs rename to crates/ui-egui/src/tools/transform_tool/drag_modes.rs diff --git a/crates/ui-egui/src/transform_tool/draw.rs b/crates/ui-egui/src/tools/transform_tool/draw.rs similarity index 100% rename from crates/ui-egui/src/transform_tool/draw.rs rename to crates/ui-egui/src/tools/transform_tool/draw.rs diff --git a/crates/ui-egui/src/transform_tool/options_bar.rs b/crates/ui-egui/src/tools/transform_tool/options_bar.rs similarity index 100% rename from crates/ui-egui/src/transform_tool/options_bar.rs rename to crates/ui-egui/src/tools/transform_tool/options_bar.rs diff --git a/crates/ui-egui/src/transform_tool/pointer.rs b/crates/ui-egui/src/tools/transform_tool/pointer.rs similarity index 100% rename from crates/ui-egui/src/transform_tool/pointer.rs rename to crates/ui-egui/src/tools/transform_tool/pointer.rs diff --git a/crates/ui-egui/src/transform_tool/preview.rs b/crates/ui-egui/src/tools/transform_tool/preview.rs similarity index 100% rename from crates/ui-egui/src/transform_tool/preview.rs rename to crates/ui-egui/src/tools/transform_tool/preview.rs diff --git a/crates/ui-egui/src/transform_tool/tests.rs b/crates/ui-egui/src/tools/transform_tool/tests.rs similarity index 100% rename from crates/ui-egui/src/transform_tool/tests.rs rename to crates/ui-egui/src/tools/transform_tool/tests.rs diff --git a/crates/ui-egui/src/transform_tool/warp.rs b/crates/ui-egui/src/tools/transform_tool/warp.rs similarity index 100% rename from crates/ui-egui/src/transform_tool/warp.rs rename to crates/ui-egui/src/tools/transform_tool/warp.rs diff --git a/crates/ui-egui/src/type_font_preview.rs b/crates/ui-egui/src/tools/type_font_preview.rs similarity index 100% rename from crates/ui-egui/src/type_font_preview.rs rename to crates/ui-egui/src/tools/type_font_preview.rs diff --git a/crates/ui-egui/src/type_tool.rs b/crates/ui-egui/src/tools/type_tool.rs similarity index 93% rename from crates/ui-egui/src/type_tool.rs rename to crates/ui-egui/src/tools/type_tool.rs index 8d46c71c03..2789a2b48f 100644 --- a/crates/ui-egui/src/type_tool.rs +++ b/crates/ui-egui/src/tools/type_tool.rs @@ -36,20 +36,20 @@ use defaults::{apply, default_style_params, default_styles, shown_scale}; pub use defaults::{foreground_changed, open_color_picker}; pub(crate) use defaults::{formatting_params, target, target_text, type_unit, with_target}; #[cfg(test)] -use editing::{insert, insert_typed, smart_quotes}; -#[cfg(test)] pub(crate) use editing::{CharToggle, step_char_metric, toggle_char_style, toggle_hyphenate}; pub use editing::{cancel, commit, commit_with, edit_active, edit_at, end_if_left}; pub(crate) use editing::{copy_selection, cut_selection, request_paste, select_all}; #[cfg(test)] -use fonts::{font_labels_id, FONT_MENU_HEIGHT, font_menu_rows, font_picker_in, style_names, wheel_family_index}; +use editing::{insert, insert_typed, smart_quotes}; #[cfg(test)] pub(crate) use fonts::{Axis, axis_value, slider_axes}; +#[cfg(test)] +use fonts::{FONT_MENU_HEIGHT, font_labels_id, font_menu_rows, font_picker_in, style_names, wheel_family_index}; pub use fonts::{families, style_label, styles, sync_font_names, warm_fonts}; pub(crate) use fonts::{family_picker_in, fonts_ready, selected_style}; +pub(crate) use ime::{ImeState, controls_only, finish_reset_logic, finish_reset_pass, in_ui_pass, install_reset_hooks}; #[cfg(test)] use ime::{IncomingComposition, ResetPhase}; -pub(crate) use ime::{controls_only, finish_reset_logic, finish_reset_pass, ImeState, in_ui_pass, install_reset_hooks}; #[cfg(test)] use ime_edit::ime_update; pub(crate) use ime_edit::sync_ime; @@ -60,22 +60,22 @@ pub use layout::layout; pub(crate) use layout::{hit_layer, offset_at, shows_own_layout}; #[cfg(test)] use options_bar::num_field; -#[cfg(test)] -pub(crate) use options_bar::{kerning_label, parse_kerning}; pub use options_bar::options_bar; pub(crate) use options_bar::styles_at; #[cfg(test)] +pub(crate) use options_bar::{kerning_label, parse_kerning}; +#[cfg(test)] use overlay::CARET_STROKES; pub use overlay::draw_overlay; #[cfg(test)] pub(crate) use panel::{OPENTYPE_BUTTONS, toggle_opentype}; pub use panel::{character_panel, type_properties}; #[cfg(test)] -use pointer::{handle_sides, MIN_BOX, word_boundary}; +use pointer::{MIN_BOX, handle_sides, word_boundary}; +pub(crate) use pointer::{PathClick, box_handle_at, hover_path_target, inside_box}; #[cfg(test)] pub(crate) use pointer::{box_shape, click_selection, next_click_count, path_target}; pub use pointer::{multi_click, pointer_down, pointer_move, pointer_up}; -pub(crate) use pointer::{box_handle_at, hover_path_target, inside_box, PathClick}; pub const PLACEHOLDER: &str = "Lorem Ipsum"; diff --git a/crates/ui-egui/src/type_tool/canvas_tests.rs b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs similarity index 100% rename from crates/ui-egui/src/type_tool/canvas_tests.rs rename to crates/ui-egui/src/tools/type_tool/canvas_tests.rs diff --git a/crates/ui-egui/src/type_tool/commit_tests.rs b/crates/ui-egui/src/tools/type_tool/commit_tests.rs similarity index 100% rename from crates/ui-egui/src/type_tool/commit_tests.rs rename to crates/ui-egui/src/tools/type_tool/commit_tests.rs diff --git a/crates/ui-egui/src/type_tool/defaults.rs b/crates/ui-egui/src/tools/type_tool/defaults.rs similarity index 100% rename from crates/ui-egui/src/type_tool/defaults.rs rename to crates/ui-egui/src/tools/type_tool/defaults.rs diff --git a/crates/ui-egui/src/type_tool/editing.rs b/crates/ui-egui/src/tools/type_tool/editing.rs similarity index 100% rename from crates/ui-egui/src/type_tool/editing.rs rename to crates/ui-egui/src/tools/type_tool/editing.rs diff --git a/crates/ui-egui/src/type_tool/font_picker_tests.rs b/crates/ui-egui/src/tools/type_tool/font_picker_tests.rs similarity index 100% rename from crates/ui-egui/src/type_tool/font_picker_tests.rs rename to crates/ui-egui/src/tools/type_tool/font_picker_tests.rs diff --git a/crates/ui-egui/src/type_tool/fonts.rs b/crates/ui-egui/src/tools/type_tool/fonts.rs similarity index 100% rename from crates/ui-egui/src/type_tool/fonts.rs rename to crates/ui-egui/src/tools/type_tool/fonts.rs diff --git a/crates/ui-egui/src/type_tool/ime.rs b/crates/ui-egui/src/tools/type_tool/ime.rs similarity index 100% rename from crates/ui-egui/src/type_tool/ime.rs rename to crates/ui-egui/src/tools/type_tool/ime.rs diff --git a/crates/ui-egui/src/type_tool/ime_edit.rs b/crates/ui-egui/src/tools/type_tool/ime_edit.rs similarity index 100% rename from crates/ui-egui/src/type_tool/ime_edit.rs rename to crates/ui-egui/src/tools/type_tool/ime_edit.rs diff --git a/crates/ui-egui/src/type_tool/ime_tests.rs b/crates/ui-egui/src/tools/type_tool/ime_tests.rs similarity index 97% rename from crates/ui-egui/src/type_tool/ime_tests.rs rename to crates/ui-egui/src/tools/type_tool/ime_tests.rs index 48e08f533e..d76938c87a 100644 --- a/crates/ui-egui/src/type_tool/ime_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/ime_tests.rs @@ -158,8 +158,8 @@ fn delete_surrounding_bytes_with_preedit_excludes_the_composition() { // `c` is the byte immediately before the pre-edit; deleting it must not delete or // report the composing `x`. - let deleted = run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 })]) - .expect("deletion descriptor"); + let deleted = + run(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::DeleteSurroundingBytes { before_bytes: 1, after_bytes: 0 })]).expect("deletion descriptor"); assert_eq!(deleted.change_cause, ImeChangeCause::InputMethod); assert_eq!(payload(&deleted).text, "ab"); assert_eq!((payload(&deleted).cursor, payload(&deleted).anchor), (2, 2)); @@ -266,8 +266,8 @@ fn external_edit_invalidates_the_preedit_and_rejects_its_late_commit() { unchanged(&app); assert!(matches!(app.type_ime.incoming, Some(IncomingComposition::Stale)), "terminal input cannot acknowledge cancellation"); - let fresh = run(&mut app, &ctx, vec![completed(invalidated.reset_request.expect("reset request")), preedit("Q")]) - .expect("fresh preview descriptor"); + let fresh = + run(&mut app, &ctx, vec![completed(invalidated.reset_request.expect("reset request")), preedit("Q")]).expect("fresh preview descriptor"); assert_eq!(layer_text(&app), "bcにdQef"); assert_eq!(payload(&fresh).text, "bcにdef", "fresh preview is excluded from committed text"); assert!(!fresh.should_interrupt_composition); @@ -432,8 +432,7 @@ fn the_real_app_logic_and_ui_publish_the_descriptor() { // The first pass registers fonts; the next passes run the real logic → ui orchestration // (where `handle_keys` and the final `sync_ime` live). for _ in 0..3 { - let raw = - egui::RawInput { focused: true, screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, 800.0))), ..Default::default() }; + let raw = egui::RawInput { focused: true, screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, 800.0))), ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| { app.logic(ui.ctx(), &mut frame); app.ui(ui, &mut frame); @@ -536,10 +535,7 @@ fn raw_application_selection_changes_reject_old_terminal_input_and_allow_later_f let revision = app.session.active().unwrap().revision; let transition = run(&mut app, &ctx, vec![raw_key(key, command, shift)]).expect("selection reset"); let selected = app.ui.text_edit.as_ref().unwrap().clone(); - assert!( - (selected.anchor, selected.caret) != (before.chars().count(), before.chars().count()), - "actual raw selection key changed the caret" - ); + assert!((selected.anchor, selected.caret) != (before.chars().count(), before.chars().count()), "actual raw selection key changed the caret"); for _ in 0..3 { run(&mut app, &ctx, vec![]); } @@ -624,8 +620,7 @@ fn the_real_app_pointer_interruption_rejects_idle_delayed_terminal_then_accepts_ } let before = layer_text(&app); let button = |pressed| egui::Event::PointerButton { pos: point, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - let press = - actual_app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(point), button(true)]).platform_output.ime.expect("press descriptor"); + let press = actual_app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(point), button(true)]).platform_output.ime.expect("press descriptor"); let release = actual_app_frame(&mut app, &ctx, vec![button(false)]).platform_output.ime.expect("release descriptor"); let request = release.reset_request.or(press.reset_request).expect("pointer reset"); assert_eq!(app.ui.text_edit.as_ref().unwrap().caret, 1, "actual canvas pointer moved the caret"); @@ -763,10 +758,8 @@ fn foreign_viewport_and_context_completions_cannot_release_root() { let foreign_input = || { let rect = egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(400.0, 300.0)); let mut raw = egui::RawInput { viewport_id: viewport, screen_rect: Some(rect), focused: true, ..Default::default() }; - raw.viewports.insert( - viewport, - egui::ViewportInfo { inner_rect: Some(rect), native_pixels_per_point: Some(1.0), minimized: Some(false), ..Default::default() }, - ); + raw.viewports + .insert(viewport, egui::ViewportInfo { inner_rect: Some(rect), native_pixels_per_point: Some(1.0), minimized: Some(false), ..Default::default() }); raw }; let mut text = String::new(); @@ -963,8 +956,7 @@ fn pointer_press_without_a_guard_defers_the_same_batch_custom_suffix() { let before = layer_text(&app); let revision = app.session.active().unwrap().revision; let selection = app.ui.text_edit.as_ref().map(|ed| (ed.anchor, ed.caret)); - let press = - egui::Event::PointerButton { pos: Pos2::new(20.0, 20.0), button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }; + let press = egui::Event::PointerButton { pos: Pos2::new(20.0, 20.0), button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }; let output = run( &mut app, &ctx, diff --git a/crates/ui-egui/src/type_tool/keys.rs b/crates/ui-egui/src/tools/type_tool/keys.rs similarity index 100% rename from crates/ui-egui/src/type_tool/keys.rs rename to crates/ui-egui/src/tools/type_tool/keys.rs diff --git a/crates/ui-egui/src/type_tool/layout.rs b/crates/ui-egui/src/tools/type_tool/layout.rs similarity index 100% rename from crates/ui-egui/src/type_tool/layout.rs rename to crates/ui-egui/src/tools/type_tool/layout.rs diff --git a/crates/ui-egui/src/type_tool/options_bar.rs b/crates/ui-egui/src/tools/type_tool/options_bar.rs similarity index 100% rename from crates/ui-egui/src/type_tool/options_bar.rs rename to crates/ui-egui/src/tools/type_tool/options_bar.rs diff --git a/crates/ui-egui/src/type_tool/overlay.rs b/crates/ui-egui/src/tools/type_tool/overlay.rs similarity index 100% rename from crates/ui-egui/src/type_tool/overlay.rs rename to crates/ui-egui/src/tools/type_tool/overlay.rs diff --git a/crates/ui-egui/src/type_tool/panel.rs b/crates/ui-egui/src/tools/type_tool/panel.rs similarity index 100% rename from crates/ui-egui/src/type_tool/panel.rs rename to crates/ui-egui/src/tools/type_tool/panel.rs diff --git a/crates/ui-egui/src/type_tool/pointer.rs b/crates/ui-egui/src/tools/type_tool/pointer.rs similarity index 100% rename from crates/ui-egui/src/type_tool/pointer.rs rename to crates/ui-egui/src/tools/type_tool/pointer.rs diff --git a/crates/ui-egui/src/type_tool/tests.rs b/crates/ui-egui/src/tools/type_tool/tests.rs similarity index 100% rename from crates/ui-egui/src/type_tool/tests.rs rename to crates/ui-egui/src/tools/type_tool/tests.rs diff --git a/crates/ui-egui/src/type_transform.rs b/crates/ui-egui/src/tools/type_transform.rs similarity index 100% rename from crates/ui-egui/src/type_transform.rs rename to crates/ui-egui/src/tools/type_transform.rs diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs similarity index 100% rename from crates/ui-egui/src/vector_ui.rs rename to crates/ui-egui/src/tools/vector_ui.rs diff --git a/crates/ui-egui/src/vector_ui/curvature.rs b/crates/ui-egui/src/tools/vector_ui/curvature.rs similarity index 100% rename from crates/ui-egui/src/vector_ui/curvature.rs rename to crates/ui-egui/src/tools/vector_ui/curvature.rs diff --git a/crates/ui-egui/src/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs similarity index 100% rename from crates/ui-egui/src/vector_ui/options.rs rename to crates/ui-egui/src/tools/vector_ui/options.rs diff --git a/crates/ui-egui/src/vector_ui/overlay.rs b/crates/ui-egui/src/tools/vector_ui/overlay.rs similarity index 100% rename from crates/ui-egui/src/vector_ui/overlay.rs rename to crates/ui-egui/src/tools/vector_ui/overlay.rs diff --git a/crates/ui-egui/src/vector_ui/paint_tests.rs b/crates/ui-egui/src/tools/vector_ui/paint_tests.rs similarity index 100% rename from crates/ui-egui/src/vector_ui/paint_tests.rs rename to crates/ui-egui/src/tools/vector_ui/paint_tests.rs diff --git a/crates/ui-egui/src/vector_ui/path_ops.rs b/crates/ui-egui/src/tools/vector_ui/path_ops.rs similarity index 100% rename from crates/ui-egui/src/vector_ui/path_ops.rs rename to crates/ui-egui/src/tools/vector_ui/path_ops.rs diff --git a/crates/ui-egui/src/vector_ui/path_selection_tests.rs b/crates/ui-egui/src/tools/vector_ui/path_selection_tests.rs similarity index 100% rename from crates/ui-egui/src/vector_ui/path_selection_tests.rs rename to crates/ui-egui/src/tools/vector_ui/path_selection_tests.rs diff --git a/crates/ui-egui/src/vector_ui/paths_panel.rs b/crates/ui-egui/src/tools/vector_ui/paths_panel.rs similarity index 100% rename from crates/ui-egui/src/vector_ui/paths_panel.rs rename to crates/ui-egui/src/tools/vector_ui/paths_panel.rs diff --git a/crates/ui-egui/src/vector_ui/pen.rs b/crates/ui-egui/src/tools/vector_ui/pen.rs similarity index 100% rename from crates/ui-egui/src/vector_ui/pen.rs rename to crates/ui-egui/src/tools/vector_ui/pen.rs diff --git a/crates/ui-egui/src/vector_ui/pen_draw_tests.rs b/crates/ui-egui/src/tools/vector_ui/pen_draw_tests.rs similarity index 100% rename from crates/ui-egui/src/vector_ui/pen_draw_tests.rs rename to crates/ui-egui/src/tools/vector_ui/pen_draw_tests.rs diff --git a/crates/ui-egui/src/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs similarity index 100% rename from crates/ui-egui/src/vector_ui/shapes.rs rename to crates/ui-egui/src/tools/vector_ui/shapes.rs diff --git a/crates/ui-egui/src/vector_ui/tests.rs b/crates/ui-egui/src/tools/vector_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/vector_ui/tests.rs rename to crates/ui-egui/src/tools/vector_ui/tests.rs diff --git a/crates/ui-egui/src/warp_preview.rs b/crates/ui-egui/src/tools/warp_preview.rs similarity index 100% rename from crates/ui-egui/src/warp_preview.rs rename to crates/ui-egui/src/tools/warp_preview.rs diff --git a/crates/ui-egui/src/zoom_tool.rs b/crates/ui-egui/src/tools/zoom_tool.rs similarity index 100% rename from crates/ui-egui/src/zoom_tool.rs rename to crates/ui-egui/src/tools/zoom_tool.rs diff --git a/crates/ui-egui/src/zoom_tool/tests.rs b/crates/ui-egui/src/tools/zoom_tool/tests.rs similarity index 100% rename from crates/ui-egui/src/zoom_tool/tests.rs rename to crates/ui-egui/src/tools/zoom_tool/tests.rs From e47ee81e386722e8c8f72be7be8ab2907365afb2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 21:46:10 +0000 Subject: [PATCH 242/259] refactor(ui-egui): move input modules under input/ --- crates/ui-egui/src/input.rs | 16 +++++++++ crates/ui-egui/src/{ => input}/alt_grab.rs | 0 crates/ui-egui/src/{ => input}/blend_keys.rs | 0 .../src/{ => input}/blend_keys/tests.rs | 0 .../ui-egui/src/{ => input}/control_click.rs | 0 crates/ui-egui/src/{ => input}/hold_keys.rs | 0 .../src/{ => input}/hold_keys/tests.rs | 0 crates/ui-egui/src/{ => input}/layout_keys.rs | 0 .../ui-egui/src/{ => input}/nudge_bundle.rs | 0 .../ui-egui/src/{ => input}/opacity_keys.rs | 0 crates/ui-egui/src/{ => input}/page_keys.rs | 0 crates/ui-egui/src/{ => input}/scrub_wrap.rs | 0 .../src/{ => input}/shortcut_dispatch.rs | 0 .../{ => input}/shortcut_dispatch/tests.rs | 0 crates/ui-egui/src/{ => input}/shortcuts.rs | 0 .../src/{ => input}/shortcuts/tests.rs | 3 +- .../src/{ => input}/single_line_drag.rs | 0 .../ui-egui/src/{ => input}/spring_tools.rs | 0 .../src/{ => input}/spring_tools/tests.rs | 0 crates/ui-egui/src/{ => input}/stylus.rs | 0 .../ui-egui/src/{ => input}/stylus/tests.rs | 14 ++------ .../ui-egui/src/{ => input}/tool_shortcuts.rs | 0 crates/ui-egui/src/{ => input}/touch_twins.rs | 0 crates/ui-egui/src/lib.rs | 33 ++++++++++--------- 24 files changed, 37 insertions(+), 29 deletions(-) create mode 100644 crates/ui-egui/src/input.rs rename crates/ui-egui/src/{ => input}/alt_grab.rs (100%) rename crates/ui-egui/src/{ => input}/blend_keys.rs (100%) rename crates/ui-egui/src/{ => input}/blend_keys/tests.rs (100%) rename crates/ui-egui/src/{ => input}/control_click.rs (100%) rename crates/ui-egui/src/{ => input}/hold_keys.rs (100%) rename crates/ui-egui/src/{ => input}/hold_keys/tests.rs (100%) rename crates/ui-egui/src/{ => input}/layout_keys.rs (100%) rename crates/ui-egui/src/{ => input}/nudge_bundle.rs (100%) rename crates/ui-egui/src/{ => input}/opacity_keys.rs (100%) rename crates/ui-egui/src/{ => input}/page_keys.rs (100%) rename crates/ui-egui/src/{ => input}/scrub_wrap.rs (100%) rename crates/ui-egui/src/{ => input}/shortcut_dispatch.rs (100%) rename crates/ui-egui/src/{ => input}/shortcut_dispatch/tests.rs (100%) rename crates/ui-egui/src/{ => input}/shortcuts.rs (100%) rename crates/ui-egui/src/{ => input}/shortcuts/tests.rs (99%) rename crates/ui-egui/src/{ => input}/single_line_drag.rs (100%) rename crates/ui-egui/src/{ => input}/spring_tools.rs (100%) rename crates/ui-egui/src/{ => input}/spring_tools/tests.rs (100%) rename crates/ui-egui/src/{ => input}/stylus.rs (100%) rename crates/ui-egui/src/{ => input}/stylus/tests.rs (96%) rename crates/ui-egui/src/{ => input}/tool_shortcuts.rs (100%) rename crates/ui-egui/src/{ => input}/touch_twins.rs (100%) diff --git a/crates/ui-egui/src/input.rs b/crates/ui-egui/src/input.rs new file mode 100644 index 0000000000..b147c2182d --- /dev/null +++ b/crates/ui-egui/src/input.rs @@ -0,0 +1,16 @@ +pub(super) mod alt_grab; +pub(super) mod blend_keys; +pub(super) mod control_click; +pub mod hold_keys; +pub(super) mod layout_keys; +pub mod nudge_bundle; +pub(super) mod opacity_keys; +pub(super) mod page_keys; +pub(super) mod scrub_wrap; +pub mod shortcut_dispatch; +pub mod shortcuts; +pub(super) mod single_line_drag; +pub mod spring_tools; +pub mod stylus; +pub(super) mod tool_shortcuts; +pub mod touch_twins; diff --git a/crates/ui-egui/src/alt_grab.rs b/crates/ui-egui/src/input/alt_grab.rs similarity index 100% rename from crates/ui-egui/src/alt_grab.rs rename to crates/ui-egui/src/input/alt_grab.rs diff --git a/crates/ui-egui/src/blend_keys.rs b/crates/ui-egui/src/input/blend_keys.rs similarity index 100% rename from crates/ui-egui/src/blend_keys.rs rename to crates/ui-egui/src/input/blend_keys.rs diff --git a/crates/ui-egui/src/blend_keys/tests.rs b/crates/ui-egui/src/input/blend_keys/tests.rs similarity index 100% rename from crates/ui-egui/src/blend_keys/tests.rs rename to crates/ui-egui/src/input/blend_keys/tests.rs diff --git a/crates/ui-egui/src/control_click.rs b/crates/ui-egui/src/input/control_click.rs similarity index 100% rename from crates/ui-egui/src/control_click.rs rename to crates/ui-egui/src/input/control_click.rs diff --git a/crates/ui-egui/src/hold_keys.rs b/crates/ui-egui/src/input/hold_keys.rs similarity index 100% rename from crates/ui-egui/src/hold_keys.rs rename to crates/ui-egui/src/input/hold_keys.rs diff --git a/crates/ui-egui/src/hold_keys/tests.rs b/crates/ui-egui/src/input/hold_keys/tests.rs similarity index 100% rename from crates/ui-egui/src/hold_keys/tests.rs rename to crates/ui-egui/src/input/hold_keys/tests.rs diff --git a/crates/ui-egui/src/layout_keys.rs b/crates/ui-egui/src/input/layout_keys.rs similarity index 100% rename from crates/ui-egui/src/layout_keys.rs rename to crates/ui-egui/src/input/layout_keys.rs diff --git a/crates/ui-egui/src/nudge_bundle.rs b/crates/ui-egui/src/input/nudge_bundle.rs similarity index 100% rename from crates/ui-egui/src/nudge_bundle.rs rename to crates/ui-egui/src/input/nudge_bundle.rs diff --git a/crates/ui-egui/src/opacity_keys.rs b/crates/ui-egui/src/input/opacity_keys.rs similarity index 100% rename from crates/ui-egui/src/opacity_keys.rs rename to crates/ui-egui/src/input/opacity_keys.rs diff --git a/crates/ui-egui/src/page_keys.rs b/crates/ui-egui/src/input/page_keys.rs similarity index 100% rename from crates/ui-egui/src/page_keys.rs rename to crates/ui-egui/src/input/page_keys.rs diff --git a/crates/ui-egui/src/scrub_wrap.rs b/crates/ui-egui/src/input/scrub_wrap.rs similarity index 100% rename from crates/ui-egui/src/scrub_wrap.rs rename to crates/ui-egui/src/input/scrub_wrap.rs diff --git a/crates/ui-egui/src/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs similarity index 100% rename from crates/ui-egui/src/shortcut_dispatch.rs rename to crates/ui-egui/src/input/shortcut_dispatch.rs diff --git a/crates/ui-egui/src/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs similarity index 100% rename from crates/ui-egui/src/shortcut_dispatch/tests.rs rename to crates/ui-egui/src/input/shortcut_dispatch/tests.rs diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs similarity index 100% rename from crates/ui-egui/src/shortcuts.rs rename to crates/ui-egui/src/input/shortcuts.rs diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/input/shortcuts/tests.rs similarity index 99% rename from crates/ui-egui/src/shortcuts/tests.rs rename to crates/ui-egui/src/input/shortcuts/tests.rs index bb24e69fdc..c6b8694a6e 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/input/shortcuts/tests.rs @@ -373,8 +373,7 @@ fn an_image_paste_released_after_command_still_pastes() { fn web_paste_key_and_paste_event_are_one_press() { let ctx = egui::Context::default(); let key = |key, pressed| egui::Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: Modifiers::COMMAND }; - let mut r = - egui::RawInput { events: vec![key(Key::V, true), egui::Event::Paste("x".into()), key(Key::X, true), egui::Event::Cut], ..Default::default() }; + let mut r = egui::RawInput { events: vec![key(Key::V, true), egui::Event::Paste("x".into()), key(Key::X, true), egui::Event::Cut], ..Default::default() }; clipboard_keys(&ctx, false, &mut r); let presses = |k| r.events.iter().filter(|e| matches!(e, egui::Event::Key { key, pressed: true, .. } if *key == k)).count(); assert_eq!((presses(Key::V), presses(Key::X)), (1, 1)); diff --git a/crates/ui-egui/src/single_line_drag.rs b/crates/ui-egui/src/input/single_line_drag.rs similarity index 100% rename from crates/ui-egui/src/single_line_drag.rs rename to crates/ui-egui/src/input/single_line_drag.rs diff --git a/crates/ui-egui/src/spring_tools.rs b/crates/ui-egui/src/input/spring_tools.rs similarity index 100% rename from crates/ui-egui/src/spring_tools.rs rename to crates/ui-egui/src/input/spring_tools.rs diff --git a/crates/ui-egui/src/spring_tools/tests.rs b/crates/ui-egui/src/input/spring_tools/tests.rs similarity index 100% rename from crates/ui-egui/src/spring_tools/tests.rs rename to crates/ui-egui/src/input/spring_tools/tests.rs diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/input/stylus.rs similarity index 100% rename from crates/ui-egui/src/stylus.rs rename to crates/ui-egui/src/input/stylus.rs diff --git a/crates/ui-egui/src/stylus/tests.rs b/crates/ui-egui/src/input/stylus/tests.rs similarity index 96% rename from crates/ui-egui/src/stylus/tests.rs rename to crates/ui-egui/src/input/stylus/tests.rs index 4dcd15ee63..f5c872f4af 100644 --- a/crates/ui-egui/src/stylus/tests.rs +++ b/crates/ui-egui/src/input/stylus/tests.rs @@ -17,12 +17,7 @@ fn held_contact_right_clicks(hover_first: bool, force: Option) -> bool { vec![ ev(egui::TouchPhase::Start, force), egui::Event::PointerMoved(egui::pos2(50.0, 50.0)), - egui::Event::PointerButton { - pos: egui::pos2(50.0, 50.0), - button: egui::PointerButton::Primary, - pressed: true, - modifiers: egui::Modifiers::NONE, - }, + egui::Event::PointerButton { pos: egui::pos2(50.0, 50.0), button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }, ], )); for t in [0.4, 0.7, 1.0, 1.3] { @@ -30,11 +25,8 @@ fn held_contact_right_clicks(hover_first: bool, force: Option) -> bool { } for (time, mut events) in frames { // egui-winit emits the touch and its emulated pointer events together. - let mut raw = egui::RawInput { - time: Some(time), - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(200.0, 200.0))), - ..Default::default() - }; + let mut raw = + egui::RawInput { time: Some(time), screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(200.0, 200.0))), ..Default::default() }; raw.events.append(&mut events); let pen = contacts.observe(&raw.events); pen_hold_is_no_right_click(&ctx, pen); diff --git a/crates/ui-egui/src/tool_shortcuts.rs b/crates/ui-egui/src/input/tool_shortcuts.rs similarity index 100% rename from crates/ui-egui/src/tool_shortcuts.rs rename to crates/ui-egui/src/input/tool_shortcuts.rs diff --git a/crates/ui-egui/src/touch_twins.rs b/crates/ui-egui/src/input/touch_twins.rs similarity index 100% rename from crates/ui-egui/src/touch_twins.rs rename to crates/ui-egui/src/input/touch_twins.rs diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 79d631753f..2f566ff44b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -13,13 +13,10 @@ macro_rules! tl { $crate::i18n::t($s) }; } -mod alt_grab; pub mod bidi_text; -mod blend_keys; pub mod canvas; pub mod cjk_fonts; pub mod control; -mod control_click; pub mod dialogs; pub mod direction; pub mod dock; @@ -29,42 +26,29 @@ pub mod file_open; pub mod flick_pan; mod font_preview; pub mod gpu_status; -pub mod hold_keys; pub mod i18n; mod icon_data; pub mod icons; pub mod jobs_ui; pub mod kys_import; pub(crate) mod last_brush; -mod layout_keys; pub mod links; pub mod menu_catalog; pub mod menus; pub mod monitor_status; pub mod notices; -pub mod nudge_bundle; -mod opacity_keys; -mod page_keys; pub mod panels; pub mod prefs_ui; pub mod preset_files_ui; mod pressure_curve_ui; pub mod proxy; pub mod screenshot; -mod scrub_wrap; pub mod served_fonts; -pub mod shortcut_dispatch; -pub mod shortcuts; -mod single_line_drag; -pub mod spring_tools; pub mod state; -pub mod stylus; pub mod texel_guard; pub mod theme; pub use titlebar::{Caption, CaptionFamily, CaptionIcon, CaptionIcons, CaptionStyle, RenderIconFn}; pub(crate) mod tool_memory; -mod tool_shortcuts; -pub mod touch_twins; pub mod updates_ui; pub mod widgets; pub mod work_area; @@ -82,6 +66,7 @@ pub use file_open::OsEvent; pub use state::{Tool, UiState}; mod app; +mod input; mod services; mod tools; @@ -182,6 +167,22 @@ pub use dialogs::targa_options_ui; pub use dialogs::tiff_options_ui; pub use dialogs::vp_ui; pub use dialogs::wide_angle_ui; +use input::alt_grab; +use input::blend_keys; +use input::control_click; +pub use input::hold_keys; +use input::layout_keys; +pub use input::nudge_bundle; +use input::opacity_keys; +use input::page_keys; +use input::scrub_wrap; +pub use input::shortcut_dispatch; +pub use input::shortcuts; +use input::single_line_drag; +pub use input::spring_tools; +pub use input::stylus; +use input::tool_shortcuts; +pub use input::touch_twins; pub use menus::enable_rules; pub use menus::menu_keys; pub use menus::menu_nav; From b786bb01c1a4aed7b092d74daec41423cba203b4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 21:47:58 +0000 Subject: [PATCH 243/259] refactor(ui-egui): move prefs modules under prefs/ --- crates/ui-egui/src/lib.rs | 9 +++++---- crates/ui-egui/src/prefs.rs | 4 ++++ crates/ui-egui/src/{ => prefs}/flick_pan.rs | 0 crates/ui-egui/src/{ => prefs}/kys_import.rs | 0 crates/ui-egui/src/{ => prefs}/kys_import/tests.rs | 0 crates/ui-egui/src/{ => prefs}/prefs_ui.rs | 0 crates/ui-egui/src/{ => prefs}/prefs_ui/appearance.rs | 0 crates/ui-egui/src/{ => prefs}/prefs_ui/dialogs.rs | 0 crates/ui-egui/src/{ => prefs}/prefs_ui/fields.rs | 0 crates/ui-egui/src/{ => prefs}/prefs_ui/graphics.rs | 0 .../ui-egui/src/{ => prefs}/prefs_ui/recovery_tests.rs | 0 crates/ui-egui/src/{ => prefs}/prefs_ui/save.rs | 0 .../src/{ => prefs}/prefs_ui/shortcut_capture_tests.rs | 0 .../src/{ => prefs}/prefs_ui/shortcut_set_tests.rs | 0 crates/ui-egui/src/{ => prefs}/prefs_ui/shortcuts.rs | 0 crates/ui-egui/src/{ => prefs}/prefs_ui/startup.rs | 0 crates/ui-egui/src/{ => prefs}/prefs_ui/tests.rs | 0 crates/ui-egui/src/{ => prefs}/pressure_curve_ui.rs | 0 18 files changed, 9 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/src/prefs.rs rename crates/ui-egui/src/{ => prefs}/flick_pan.rs (100%) rename crates/ui-egui/src/{ => prefs}/kys_import.rs (100%) rename crates/ui-egui/src/{ => prefs}/kys_import/tests.rs (100%) rename crates/ui-egui/src/{ => prefs}/prefs_ui.rs (100%) rename crates/ui-egui/src/{ => prefs}/prefs_ui/appearance.rs (100%) rename crates/ui-egui/src/{ => prefs}/prefs_ui/dialogs.rs (100%) rename crates/ui-egui/src/{ => prefs}/prefs_ui/fields.rs (100%) rename crates/ui-egui/src/{ => prefs}/prefs_ui/graphics.rs (100%) rename crates/ui-egui/src/{ => prefs}/prefs_ui/recovery_tests.rs (100%) rename crates/ui-egui/src/{ => prefs}/prefs_ui/save.rs (100%) rename crates/ui-egui/src/{ => prefs}/prefs_ui/shortcut_capture_tests.rs (100%) rename crates/ui-egui/src/{ => prefs}/prefs_ui/shortcut_set_tests.rs (100%) rename crates/ui-egui/src/{ => prefs}/prefs_ui/shortcuts.rs (100%) rename crates/ui-egui/src/{ => prefs}/prefs_ui/startup.rs (100%) rename crates/ui-egui/src/{ => prefs}/prefs_ui/tests.rs (100%) rename crates/ui-egui/src/{ => prefs}/pressure_curve_ui.rs (100%) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2f566ff44b..ef57601504 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -23,14 +23,12 @@ pub mod dock; pub mod egui_fonts; pub mod file_dialog; pub mod file_open; -pub mod flick_pan; mod font_preview; pub mod gpu_status; pub mod i18n; mod icon_data; pub mod icons; pub mod jobs_ui; -pub mod kys_import; pub(crate) mod last_brush; pub mod links; pub mod menu_catalog; @@ -38,9 +36,7 @@ pub mod menus; pub mod monitor_status; pub mod notices; pub mod panels; -pub mod prefs_ui; pub mod preset_files_ui; -mod pressure_curve_ui; pub mod proxy; pub mod screenshot; pub mod served_fonts; @@ -67,6 +63,7 @@ pub use state::{Tool, UiState}; mod app; mod input; +mod prefs; mod services; mod tools; @@ -227,6 +224,10 @@ use panels::timeline_ui; use panels::titlebar; pub use panels::type_panels_ui; use panels::variables_ui; +pub use prefs::flick_pan; +pub use prefs::kys_import; +pub use prefs::prefs_ui; +use prefs::pressure_curve_ui; pub(crate) use services::SAVE_OPTIONS_OPEN; #[cfg(test)] pub(crate) use services::saved_revision_after_write; diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs new file mode 100644 index 0000000000..c7d4503302 --- /dev/null +++ b/crates/ui-egui/src/prefs.rs @@ -0,0 +1,4 @@ +pub mod flick_pan; +pub mod kys_import; +pub mod prefs_ui; +pub(super) mod pressure_curve_ui; diff --git a/crates/ui-egui/src/flick_pan.rs b/crates/ui-egui/src/prefs/flick_pan.rs similarity index 100% rename from crates/ui-egui/src/flick_pan.rs rename to crates/ui-egui/src/prefs/flick_pan.rs diff --git a/crates/ui-egui/src/kys_import.rs b/crates/ui-egui/src/prefs/kys_import.rs similarity index 100% rename from crates/ui-egui/src/kys_import.rs rename to crates/ui-egui/src/prefs/kys_import.rs diff --git a/crates/ui-egui/src/kys_import/tests.rs b/crates/ui-egui/src/prefs/kys_import/tests.rs similarity index 100% rename from crates/ui-egui/src/kys_import/tests.rs rename to crates/ui-egui/src/prefs/kys_import/tests.rs diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs/prefs_ui.rs similarity index 100% rename from crates/ui-egui/src/prefs_ui.rs rename to crates/ui-egui/src/prefs/prefs_ui.rs diff --git a/crates/ui-egui/src/prefs_ui/appearance.rs b/crates/ui-egui/src/prefs/prefs_ui/appearance.rs similarity index 100% rename from crates/ui-egui/src/prefs_ui/appearance.rs rename to crates/ui-egui/src/prefs/prefs_ui/appearance.rs diff --git a/crates/ui-egui/src/prefs_ui/dialogs.rs b/crates/ui-egui/src/prefs/prefs_ui/dialogs.rs similarity index 100% rename from crates/ui-egui/src/prefs_ui/dialogs.rs rename to crates/ui-egui/src/prefs/prefs_ui/dialogs.rs diff --git a/crates/ui-egui/src/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs similarity index 100% rename from crates/ui-egui/src/prefs_ui/fields.rs rename to crates/ui-egui/src/prefs/prefs_ui/fields.rs diff --git a/crates/ui-egui/src/prefs_ui/graphics.rs b/crates/ui-egui/src/prefs/prefs_ui/graphics.rs similarity index 100% rename from crates/ui-egui/src/prefs_ui/graphics.rs rename to crates/ui-egui/src/prefs/prefs_ui/graphics.rs diff --git a/crates/ui-egui/src/prefs_ui/recovery_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/recovery_tests.rs similarity index 100% rename from crates/ui-egui/src/prefs_ui/recovery_tests.rs rename to crates/ui-egui/src/prefs/prefs_ui/recovery_tests.rs diff --git a/crates/ui-egui/src/prefs_ui/save.rs b/crates/ui-egui/src/prefs/prefs_ui/save.rs similarity index 100% rename from crates/ui-egui/src/prefs_ui/save.rs rename to crates/ui-egui/src/prefs/prefs_ui/save.rs diff --git a/crates/ui-egui/src/prefs_ui/shortcut_capture_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_capture_tests.rs similarity index 100% rename from crates/ui-egui/src/prefs_ui/shortcut_capture_tests.rs rename to crates/ui-egui/src/prefs/prefs_ui/shortcut_capture_tests.rs diff --git a/crates/ui-egui/src/prefs_ui/shortcut_set_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_tests.rs similarity index 100% rename from crates/ui-egui/src/prefs_ui/shortcut_set_tests.rs rename to crates/ui-egui/src/prefs/prefs_ui/shortcut_set_tests.rs diff --git a/crates/ui-egui/src/prefs_ui/shortcuts.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs similarity index 100% rename from crates/ui-egui/src/prefs_ui/shortcuts.rs rename to crates/ui-egui/src/prefs/prefs_ui/shortcuts.rs diff --git a/crates/ui-egui/src/prefs_ui/startup.rs b/crates/ui-egui/src/prefs/prefs_ui/startup.rs similarity index 100% rename from crates/ui-egui/src/prefs_ui/startup.rs rename to crates/ui-egui/src/prefs/prefs_ui/startup.rs diff --git a/crates/ui-egui/src/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs similarity index 100% rename from crates/ui-egui/src/prefs_ui/tests.rs rename to crates/ui-egui/src/prefs/prefs_ui/tests.rs diff --git a/crates/ui-egui/src/pressure_curve_ui.rs b/crates/ui-egui/src/prefs/pressure_curve_ui.rs similarity index 100% rename from crates/ui-egui/src/pressure_curve_ui.rs rename to crates/ui-egui/src/prefs/pressure_curve_ui.rs From f44e18d6fe77e0087e14b3b9e030e941af884c9d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 21:50:27 +0000 Subject: [PATCH 244/259] refactor(ui-egui): move text modules under text/ --- crates/ui-egui/src/lib.rs | 13 +++++++------ crates/ui-egui/src/text.rs | 6 ++++++ crates/ui-egui/src/{ => text}/bidi_text.rs | 0 crates/ui-egui/src/{ => text}/cjk_fonts.rs | 0 .../ui-egui/src/{ => text}/cjk_fonts/tests.rs | 19 +++++++++++-------- crates/ui-egui/src/{ => text}/direction.rs | 0 .../ui-egui/src/{ => text}/direction/tests.rs | 0 crates/ui-egui/src/{ => text}/egui_fonts.rs | 0 crates/ui-egui/src/{ => text}/font_preview.rs | 0 crates/ui-egui/src/{ => text}/served_fonts.rs | 0 10 files changed, 24 insertions(+), 14 deletions(-) create mode 100644 crates/ui-egui/src/text.rs rename crates/ui-egui/src/{ => text}/bidi_text.rs (100%) rename crates/ui-egui/src/{ => text}/cjk_fonts.rs (100%) rename crates/ui-egui/src/{ => text}/cjk_fonts/tests.rs (99%) rename crates/ui-egui/src/{ => text}/direction.rs (100%) rename crates/ui-egui/src/{ => text}/direction/tests.rs (100%) rename crates/ui-egui/src/{ => text}/egui_fonts.rs (100%) rename crates/ui-egui/src/{ => text}/font_preview.rs (100%) rename crates/ui-egui/src/{ => text}/served_fonts.rs (100%) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ef57601504..5a64b551f4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -13,17 +13,12 @@ macro_rules! tl { $crate::i18n::t($s) }; } -pub mod bidi_text; pub mod canvas; -pub mod cjk_fonts; pub mod control; pub mod dialogs; -pub mod direction; pub mod dock; -pub mod egui_fonts; pub mod file_dialog; pub mod file_open; -mod font_preview; pub mod gpu_status; pub mod i18n; mod icon_data; @@ -39,7 +34,6 @@ pub mod panels; pub mod preset_files_ui; pub mod proxy; pub mod screenshot; -pub mod served_fonts; pub mod state; pub mod texel_guard; pub mod theme; @@ -65,6 +59,7 @@ mod app; mod input; mod prefs; mod services; +mod text; mod tools; #[cfg(test)] @@ -237,6 +232,12 @@ pub use services::{ FileStampFn, FormatChoices, ImportFn, Inbox, LoadTextFn, OpenUrlFn, OsEventsFn, PhotoshopShortcutsFn, QuitFn, RecoverFn, Recoverable, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, WindowFrameFn, WriteFn, }; +pub use text::bidi_text; +pub use text::cjk_fonts; +pub use text::direction; +pub use text::egui_fonts; +use text::font_preview; +pub use text::served_fonts; use tools::align_bar; pub use tools::analysis_ui; pub use tools::anchor_tools; diff --git a/crates/ui-egui/src/text.rs b/crates/ui-egui/src/text.rs new file mode 100644 index 0000000000..ddfc651ef9 --- /dev/null +++ b/crates/ui-egui/src/text.rs @@ -0,0 +1,6 @@ +pub mod bidi_text; +pub mod cjk_fonts; +pub mod direction; +pub mod egui_fonts; +pub(super) mod font_preview; +pub mod served_fonts; diff --git a/crates/ui-egui/src/bidi_text.rs b/crates/ui-egui/src/text/bidi_text.rs similarity index 100% rename from crates/ui-egui/src/bidi_text.rs rename to crates/ui-egui/src/text/bidi_text.rs diff --git a/crates/ui-egui/src/cjk_fonts.rs b/crates/ui-egui/src/text/cjk_fonts.rs similarity index 100% rename from crates/ui-egui/src/cjk_fonts.rs rename to crates/ui-egui/src/text/cjk_fonts.rs diff --git a/crates/ui-egui/src/cjk_fonts/tests.rs b/crates/ui-egui/src/text/cjk_fonts/tests.rs similarity index 99% rename from crates/ui-egui/src/cjk_fonts/tests.rs rename to crates/ui-egui/src/text/cjk_fonts/tests.rs index 863b465453..06e8ec4b14 100644 --- a/crates/ui-egui/src/cjk_fonts/tests.rs +++ b/crates/ui-egui/src/text/cjk_fonts/tests.rs @@ -211,7 +211,7 @@ fn fake_dir() -> PathBuf { g.get_or_insert_with(|| { let dir = std::env::temp_dir().join(format!("photocraft-cjk-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("font.ttf"), include_bytes!("../../../../assets/fonts/Inter-Regular.ttf")).unwrap(); + std::fs::write(dir.join("font.ttf"), include_bytes!("../../../../../assets/fonts/Inter-Regular.ttf")).unwrap(); std::fs::write(dir.join("empty.ttf"), b"").unwrap(); std::fs::write(dir.join("thai.ttf"), synthetic_font(&[(0x0E01, 0x0E5B)])).unwrap(); std::fs::write(dir.join("arabic.ttf"), synthetic_font(&[(0x0600, 0x06FF)])).unwrap(); @@ -222,7 +222,10 @@ fn fake_dir() -> PathBuf { std::fs::write(dir.join("hant.ttf"), synthetic_font(&[(0x9F8D, 0x9F8D)])).unwrap(); std::fs::write( dir.join("families.ttc"), - two_face_ttc(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"), include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf")), + two_face_ttc( + include_bytes!("../../../../../assets/fonts/Inter-Regular.ttf"), + include_bytes!("../../../../../assets/fonts/JetBrainsMono-Regular.ttf"), + ), ) .unwrap(); dir @@ -278,7 +281,7 @@ fn provider_skips_missing_and_corrupt_script_candidates_before_registering() { let malformed = fake_dir().join("provider-corrupt-thai.ttf"); let collection = fake_dir().join("provider-corrupt-selected-thai.ttc"); std::fs::write(&malformed, font_with_out_of_bounds_table()).expect("write the malformed test font"); - std::fs::write(&collection, two_face_ttc(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"), &font_with_out_of_bounds_table())) + std::fs::write(&collection, two_face_ttc(include_bytes!("../../../../../assets/fonts/Inter-Regular.ttf"), &font_with_out_of_bounds_table())) .expect("write the malformed selected-face collection"); let sources = Sources { @@ -626,7 +629,7 @@ fn system_fonts_cover_other_script_samples() { #[test] fn vertical_metrics_parse_and_reject_garbage() { - let (asc, desc, gap) = vertical_metrics(include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"), 0).unwrap(); + let (asc, desc, gap) = vertical_metrics(include_bytes!("../../../../../assets/fonts/Inter-Regular.ttf"), 0).unwrap(); assert!((asc - 1984.0 / 2048.0).abs() < 1e-4 && (desc + 494.0 / 2048.0).abs() < 1e-4 && gap == 0.0); for bad in [&b""[..], b"ttcf", b"ttcf\0\0\0\0\0\0\0\0\xff\xff\xff\xff", b"\0\x01\0\0\0\xff\0\0\0\0\0\0"] { assert!(vertical_metrics(bad, 0).is_none()); @@ -1302,7 +1305,7 @@ fn provider_negative_caches_invalid_fonts_separately_from_noncovering_faces() { let invalid = fake("not-a-font-cache.ttf").path; std::fs::write(&invalid, b"this is not a font").expect("write invalid bytes"); let truncated = fake("truncated-font-cache.ttf").path; - std::fs::write(&truncated, &include_bytes!("../../../../assets/fonts/Inter-Regular.ttf")[..20]).expect("write truncated font"); + std::fs::write(&truncated, &include_bytes!("../../../../../assets/fonts/Inter-Regular.ttf")[..20]).expect("write truncated font"); for path in [&invalid, &truncated] { for c in ['日', '本'] { let file = vec![FontFile { path: path.clone(), family: String::new() }]; @@ -1476,8 +1479,8 @@ fn font_with_out_of_bounds_table() -> Vec { /// stays readable, and face 1's `cmap`/`name` still work, so a file-level check plus coverage /// accepts it even though the face cannot be installed safely. fn collection_with_out_of_bounds_selected_face() -> Vec { - let inter = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"); - let mut jetbrains = include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec(); + let inter = include_bytes!("../../../../../assets/fonts/Inter-Regular.ttf"); + let mut jetbrains = include_bytes!("../../../../../assets/fonts/JetBrainsMono-Regular.ttf").to_vec(); let tables = u16::from_be_bytes([jetbrains[4], jetbrains[5]]) as usize; let glyf = (0..tables).map(|i| 12 + 16 * i).find(|&rec| jetbrains.get(rec..rec + 4) == Some(&b"glyf"[..])).expect("JetBrains Mono has a glyf table"); jetbrains[glyf + 12..glyf + 16].copy_from_slice(&u32::MAX.to_be_bytes()); @@ -1515,7 +1518,7 @@ fn lazy_loader_rejects_a_font_with_an_out_of_bounds_table_and_uses_the_next_cand // A readable collection with an unreadable covering face must also skip that face: the // coverage route selects face 1 by its valid cmap, not the readable face 0. let collection = fake_dir().join("out-of-bounds-thai.ttc"); - let inter = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf"); + let inter = include_bytes!("../../../../../assets/fonts/Inter-Regular.ttf"); let collection_bytes = two_face_ttc(inter, &font_with_out_of_bounds_table()); std::fs::write(&collection, &collection_bytes).unwrap(); assert!(cjk::font_file_is_readable(&collection_bytes), "face 0 keeps the collection readable"); diff --git a/crates/ui-egui/src/direction.rs b/crates/ui-egui/src/text/direction.rs similarity index 100% rename from crates/ui-egui/src/direction.rs rename to crates/ui-egui/src/text/direction.rs diff --git a/crates/ui-egui/src/direction/tests.rs b/crates/ui-egui/src/text/direction/tests.rs similarity index 100% rename from crates/ui-egui/src/direction/tests.rs rename to crates/ui-egui/src/text/direction/tests.rs diff --git a/crates/ui-egui/src/egui_fonts.rs b/crates/ui-egui/src/text/egui_fonts.rs similarity index 100% rename from crates/ui-egui/src/egui_fonts.rs rename to crates/ui-egui/src/text/egui_fonts.rs diff --git a/crates/ui-egui/src/font_preview.rs b/crates/ui-egui/src/text/font_preview.rs similarity index 100% rename from crates/ui-egui/src/font_preview.rs rename to crates/ui-egui/src/text/font_preview.rs diff --git a/crates/ui-egui/src/served_fonts.rs b/crates/ui-egui/src/text/served_fonts.rs similarity index 100% rename from crates/ui-egui/src/served_fonts.rs rename to crates/ui-egui/src/text/served_fonts.rs From 9bb24235335f61a7ce62696bae3448ad3180f097 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:47:00 +0000 Subject: [PATCH 245/259] refactor(compose): split lib.rs into composite, content, ctx, extents, fx_cache, reduced, render --- crates/compose/src/adjust/tone_tests.rs | 3 +- crates/compose/src/composite.rs | 685 ++++++ crates/compose/src/content.rs | 241 +++ crates/compose/src/ctx.rs | 225 ++ crates/compose/src/effects/tests.rs | 22 +- crates/compose/src/extents.rs | 428 ++++ crates/compose/src/fx_cache.rs | 281 +++ crates/compose/src/lib.rs | 2522 +---------------------- crates/compose/src/reduced.rs | 300 +++ crates/compose/src/render.rs | 360 ++++ 10 files changed, 2567 insertions(+), 2500 deletions(-) create mode 100644 crates/compose/src/composite.rs create mode 100644 crates/compose/src/content.rs create mode 100644 crates/compose/src/ctx.rs create mode 100644 crates/compose/src/extents.rs create mode 100644 crates/compose/src/fx_cache.rs create mode 100644 crates/compose/src/reduced.rs create mode 100644 crates/compose/src/render.rs diff --git a/crates/compose/src/adjust/tone_tests.rs b/crates/compose/src/adjust/tone_tests.rs index 99b20e9096..fbd91bf14b 100644 --- a/crates/compose/src/adjust/tone_tests.rs +++ b/crates/compose/src/adjust/tone_tests.rs @@ -860,8 +860,7 @@ fn lab_gradient_map_follows_l() { fn other_modes_and_adjustments_keep_the_screen_colour_path() { let c = [0.2, 0.5, 0.7, 1.0]; let lab_only = [Adjustment::Invert, Adjustment::Threshold { level: 0.47 }, Adjustment::Posterize { levels: 4 }]; - for adj in - lab_only.iter().chain([&Adjustment::HueSaturation { hue: 30.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }]) + for adj in lab_only.iter().chain([&Adjustment::HueSaturation { hue: 30.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges: HueRange::defaults() }]) { for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Grayscale, ColorMode::Lab] { let (mut a, mut b) = (Buffer::filled(crate::Rect::new(0, 0, 1, 1), c), Buffer::filled(crate::Rect::new(0, 0, 1, 1), c)); diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs new file mode 100644 index 0000000000..dccaed8c4b --- /dev/null +++ b/crates/compose/src/composite.rs @@ -0,0 +1,685 @@ +use super::content::{channel_weights, empty_in, recycle_buffer, render_content, restore_channels, scratch_buffer, surface_to_buffer}; +use super::ctx::Ctx; +use super::extents::{effects_frame, mask_k, mask_vals, shapeless_stroke_bounds}; +use super::fx_cache::effect_maps; +use super::*; + +/// Composite an isolated group's sibling list (bottom→top) onto `backdrop` (its own buffer). +pub(crate) fn composite_stack(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx) { + composite_stack_at(layers, backdrop, cx, advanced::Scope::ISOLATED); +} + +/// Composite a sibling list (bottom→top) onto `backdrop`; `scope` says where the stack sits (see +/// [`advanced::Scope`]: it decides what knockouts reveal). +pub(crate) fn composite_stack_at(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { + // Shallow knockouts stop at the bottom of this stack: the backdrop it starts from. + let floor = (!scope.root && advanced::needs_floor(layers)).then(|| backdrop.clone()); + let mut i = 0; + while i < layers.len() { + let base = &layers[i]; + // Collect the clipping group: following layers with `clipped = true`. + let mut j = i + 1; + while j < layers.len() && layers[j].clipped && !base.clipped { + j += 1; + } + let clipped = &layers[i + 1..j]; + if base.visible { + let ko = advanced::knockout_target(base, floor.as_ref(), backdrop.rect, cx, scope); + composite_layer(base, clipped, backdrop, cx, ko.as_deref(), scope); + if let (LayerContent::Adjustment(_), Some(q)) = (&base.content, adjustment_quantum(cx.depth)) { + quantize(backdrop, q); + } + } + i = j.max(i + 1); + } +} + +/// Steps per unit of an integer document's samples: Photoshop applies adjustment layers to +/// buffers of the document's depth (8-bit: 255 levels, 16-bit: 32768), so their result is +/// rounded there; a steep curve then amplifies the rounding of its input exactly as in +/// Photoshop (psd-tools adjustment_nested_composition_4: 9.6 → 5.1 % of pixels off; +/// exposure_grayscale passes). Blends stay in float (quantising them too made other files +/// worse). +pub fn adjustment_quantum(depth: photocraft_color::SampleType) -> Option { + match depth { + photocraft_color::SampleType::U8 => Some(255.0), + photocraft_color::SampleType::U16 => Some(32768.0), + photocraft_color::SampleType::F32 => None, + } +} + +pub(crate) fn quantize(b: &mut Buffer, q: f32) { + for p in &mut b.px { + for v in p.iter_mut() { + *v = branchless_floor(*v * q + 0.5) / q; + } + } +} + +/// `x.floor()`, bit for bit (signed zeros, infinities and NaNs included), without a call: baseline +/// x86-64 has no SSE4.1 `roundss`, so `floor` is a software routine there, called once per sample +/// of the backdrop under every adjustment layer ([`quantize`]). This form has no branch, so the +/// loop vectorizes. +#[inline] +pub(crate) fn branchless_floor(x: f32) -> f32 { + // From 2^23 on every f32 is whole. Below it, adding and taking away 2^23 rounds to the + // nearest whole number; where that went up, step down. + const WHOLE: f32 = 8_388_608.0; + let a = x.abs(); + let r = ((a + WHOLE) - WHOLE).copysign(x); + let r = if r > x { r - 1.0 } else { r }; + if a < WHOLE { r } else { x } +} + +/// Blend an adjustment layer's result (`adjusted`) back into the backdrop it was made from, each +/// pixel by its coverage `ks` (opacity × mask) in blend mode `mode`. +fn blend_back(backdrop: &mut [[f32; 4]], adjusted: &[[f32; 4]], ks: impl Iterator, mode: BlendMode) { + for ((b, a), k) in backdrop.iter_mut().zip(adjusted).zip(ks) { + if k <= 0.0 { + continue; + } + let s = [a[0], a[1], a[2]]; + // Normal is the source as it is (`blend_rgb` gives exactly that), and most adjustment + // layers are Normal: no per-pixel mode dispatch for them. + let blended = if mode == BlendMode::Normal { s } else { blend::blend_rgb(mode, [b[0], b[1], b[2]], s) }; + *b = [b[0] + (blended[0] - b[0]) * k, b[1] + (blended[1] - b[1]) * k, b[2] + (blended[2] - b[2]) * k, b[3]]; + } +} + +/// Deterministic hash for Dissolve (document-coordinate based, so it is stable under tiling). +#[inline] +pub(crate) fn dissolve_noise(x: i32, y: i32) -> f32 { + let mut h = (x as u32).wrapping_mul(0x8da6_b343) ^ (y as u32).wrapping_mul(0xd816_3841) ^ 0x9e37_79b9; + h ^= h >> 15; + h = h.wrapping_mul(0x2c1b_3c6d); + h ^= h >> 12; + (h & 0xffff) as f32 / 65536.0 +} + +/// Whether `layer` replaces everything beneath it in its stack: a visible, unclipped fill layer +/// in Normal mode at full opacity and fill, without masks, effects, channel restrictions or Blend +/// If, whose fill is opaque everywhere (a solid colour, or a gradient whose colour and opacity +/// stops are all opaque). Normal blending at alpha 1 returns the layer's colour exactly, so the +/// layers below can be skipped (the live Gradient tool's preview recomposites the whole canvas on +/// every pointer move). +pub fn occludes_below(layer: &Layer, mode: photocraft_color::ColorMode) -> bool { + let LayerContent::Fill(f) = &layer.content else { return false }; + let opaque = match f { + Fill::Solid(c) => c.alpha >= 1.0, + Fill::Gradient { stops, opacity_stops, .. } => { + !stops.is_empty() && stops.iter().all(|(_, c)| c.alpha >= 1.0) && opacity_stops.iter().all(|(_, o)| *o >= 1.0) + } + Fill::Pattern { .. } => false, + }; + // A cached render in use (a PSD's stored fill pixels) may not be opaque. + let cached = layer.fill_cache.as_ref().is_some_and(|c| c.fill == *f); + opaque + && !cached + && layer.visible + && !layer.clipped + && layer.blend == photocraft_color::BlendMode::Normal + && layer.opacity >= 1.0 + && layer.fill_opacity >= 1.0 + && !layer.mask.as_ref().is_some_and(|m| m.enabled) + && !layer.vector_mask.as_ref().is_some_and(|m| m.enabled) + && !effects::has_effects(layer) + && layer.excluded_channels == 0 + && !blend_if_active(layer, mode) +} + +/// Whether Blending Options › Blend If changes how `layer` composites in a `mode` document. +/// RGB documents test Gray and R, G, B; grayscale (and duotone) documents their one channel. +/// Other modes composite in display RGB, where ranges over their own channels have no exact +/// equivalent, so (like channel restrictions) the setting round-trips but isn't applied there. +pub fn blend_if_active(layer: &Layer, mode: photocraft_color::ColorMode) -> bool { + use photocraft_color::ColorMode as M; + matches!(mode, M::Rgb | M::Grayscale | M::Duotone) && !layer.blend_if.is_default() +} + +/// How much of a pixel shows through `layer`'s Blend If ranges, given the layer's own colour +/// (`this`, `None` where the layer has no content of its own there) and the colour beneath it +/// (`under`, `None` where nothing is beneath). Every range multiplies in. +fn blend_if_weight(layer: &Layer, mode: photocraft_color::ColorMode, this: Option<[f32; 4]>, under: Option<[f32; 4]>) -> f32 { + use photocraft_color::ColorMode as M; + let bi = &layer.blend_if; + let mut k = 1.0; + for (side, px) in [this, under].into_iter().enumerate() { + let Some(p) = px else { continue }; + let v = |c: usize| blend_if_level(p[c]); + match mode { + // Gray is the colour channels' luma (Rec. 601 weights), then R, G, B. + M::Rgb => { + let gray = 0.299 * v(0) + 0.587 * v(1) + 0.114 * v(2); + k *= bi.get(0)[side].weight(gray); + for c in 0..3 { + k *= bi.get(c + 1)[side].weight(v(c)); + } + } + // One channel: the PSD spec marks the composite-gray entry irrelevant here, so the + // channel's own entry carries the setting; both are honoured. + _ => k *= bi.get(0)[side].weight(v(0)) * bi.get(1)[side].weight(v(0)), + } + if k <= 0.0 { + return 0.0; + } + } + k +} + +/// A channel value on Blend If's 0..=255 scale. Compositing can leave an 8- or 16-bit level a few +/// millionths off (a level-20 backdrop composited at partial alpha reads 19.999998), which would +/// put it on the wrong side of a hard point at that level: a value that close to a level is that +/// level. Values of those depths that aren't on a level are at least 1/257 away from one. The GPU +/// compositor (`compose.wgsl` `blend_if_weight`) snaps alike. +fn blend_if_level(x: f32) -> f32 { + let v = x.clamp(0.0, 1.0) * 255.0; + let r = v.round(); + if (v - r).abs() < 1e-4 { r } else { v } +} + +/// Blend If groups inside one another whose own colour is still rendered separately. Each extra +/// level multiplies the work by the tree's depth, so the cost is polynomial, not exponential. +const MAX_BLEND_IF_GROUP_DEPTH: u32 = 2; + +thread_local! { + /// Blend If groups being rendered for their own colour on this thread. + static BLEND_IF_GROUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Apply `layer`'s Blend If to a finished composite: `out` (the backdrop with the layer drawn) +/// is mixed back towards `before` (the backdrop without it) where the ranges hide the layer. +/// Mixing premultiplied colour by `k` equals compositing the layer at `k` × its alpha, since +/// every blend mode's source-over result is linear in the source alpha. +fn apply_blend_if(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx) { + // "This Layer" is the layer's own colour; adjustment layers (no content of their own) are + // judged by their result. So are groups nested deeper than `MAX_BLEND_IF_GROUP_DEPTH` Blend + // Ifs: a group's own colour re-composites its children, which doubles the work at every + // level of Blend If groups inside one another. + let is_group = matches!(layer.content, LayerContent::Group(_)); + let nested = BLEND_IF_GROUPS.with(std::cell::Cell::get); + let own = if matches!(layer.content, LayerContent::Adjustment(_)) || (is_group && nested >= MAX_BLEND_IF_GROUP_DEPTH) { + None + } else { + BLEND_IF_GROUPS.with(|d| d.set(nested + u32::from(is_group))); + let own = render_content(layer, out.rect, cx); + BLEND_IF_GROUPS.with(|d| d.set(nested)); + own + }; + for (i, (p, b)) in out.px.iter_mut().zip(&before.px).enumerate() { + let this = match &own { + Some(o) => Some(o.px[i]).filter(|q| q[3] > 0.0), + None => Some(*p), + }; + let under = Some(*b).filter(|q| q[3] > 0.0); + let k = blend_if_weight(layer, cx.mode, this, under); + if k >= 1.0 { + continue; + } + let a = b[3] + (p[3] - b[3]) * k; + *p = if a > 0.0 { + let c = |c: usize| ((b[c] * b[3] + (p[c] * p[3] - b[c] * b[3]) * k) / a).clamp(0.0, 1.0); + [c(0), c(1), c(2), a] + } else { + [0.0; 4] + }; + } +} + +/// Composite `layer` (plus its clipping group) onto `backdrop`, honouring its channel restrictions +/// and Blend If, and knocking out to `ko` when it has a knockout (see [`advanced`]). +pub(crate) fn composite_layer(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, ko: Option<&Buffer>, scope: advanced::Scope) { + // Blend Clipped Layers as Group off: the base alone, then each clipped layer in its own mode. + if advanced::clips_individually(layer, clipped) { + advanced::composite_clipped_individually(layer, clipped, backdrop, cx, ko, scope); + return; + } + let w = channel_weights(layer, cx.mode); + let blend_if = blend_if_active(layer, cx.mode); + let before = (w.is_some() || blend_if).then(|| backdrop.clone()); + match ko { + Some(target) => advanced::knockout(layer, backdrop, target, false, cx, |b| composite_layer_any(layer, clipped, b, cx, scope)), + None => composite_layer_any(layer, clipped, backdrop, cx, scope), + } + if let Some(before) = &before { + if let Some(w) = w { + restore_channels(backdrop, before, w); + } + if blend_if { + apply_blend_if(layer, before, backdrop, cx); + } + } +} + +fn composite_layer_any(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { + if let LayerContent::Group(g) = &layer.content + && let Some(ab) = &g.artboard + { + composite_artboard(layer, ab, clipped, backdrop, cx, scope); + return; + } + composite_layer_plain(layer, clipped, backdrop, cx, scope); +} + +/// An artboard: its background and the group, composited only inside the board (contents and +/// effects outside it are clipped away; the backdrop there is untouched). +fn composite_artboard(layer: &Layer, ab: &photocraft_doc::Artboard, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { + let board = ab.rect.intersect(&backdrop.rect); + if board.is_empty() { + return; + } + let (bw, w) = (board.width() as usize, backdrop.rect.width() as usize); + let row0 = |y: i32| (y - backdrop.rect.y0) as usize * w + (board.x0 - backdrop.rect.x0) as usize; + let mut sub = Buffer::transparent(board); + for y in board.y0..board.y1 { + let o = row0(y); + let so = (y - board.y0) as usize * bw; + sub.px[so..so + bw].copy_from_slice(&backdrop.px[o..o + bw]); + } + if let Some(bg) = ab.background.rgba() { + blend_into(&mut sub, &Buffer::filled(board, bg), BlendMode::Normal, 1.0); + } + composite_layer_plain(layer, clipped, &mut sub, cx, scope); + for y in board.y0..board.y1 { + let o = row0(y); + let so = (y - board.y0) as usize * bw; + backdrop.px[o..o + bw].copy_from_slice(&sub.px[so..so + bw]); + } +} + +/// The surface `render_content` reads `layer`'s pixels from, when that is all it draws. +pub(crate) fn pixel_surface(layer: &Layer) -> Option<&Surface> { + if matches!(layer.content, LayerContent::Group(_) | LayerContent::Fill(_) | LayerContent::Adjustment(_)) { + return None; + } + layer.surface() +} + +/// A pixel layer (nothing clipped to it) onto `backdrop`, read from its tiles a row at a time: +/// the same arithmetic as `render_content` + `blend_into_fill`, without a tile-sized copy of the +/// layer (a megabyte per 256² render tile). +pub(crate) fn composite_pixel_layer(layer: &Layer, surf: &Surface, backdrop: &mut Buffer, cx: &Ctx) { + let rect = backdrop.rect; + let w = rect.width() as usize; + if w == 0 { + return; + } + let mv = mask_vals(layer, rect, cx); + let gamma = text_gamma(layer); + let mut row = vec![[0.0f32; 4]; w]; + for (ry, dst) in backdrop.px.chunks_exact_mut(w).enumerate() { + let y = rect.y0 + ry as i32; + surf.read_rgba_into(Rect::new(rect.x0, y, rect.x1, y + 1), &mut row); + if let Some(m) = mv.as_ref().and_then(|m| m.get(ry * w..(ry + 1) * w)) { + for (p, k) in row.iter_mut().zip(m) { + p[3] *= k; + } + } + blend_span_fill(dst, &row, rect.x0, y, layer.blend, layer.opacity, layer.fill_opacity, gamma); + } +} + +pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { + let rect = backdrop.rect; + // A TSL-off stroke base that is transparent here can still have visible clipped siblings; + // keep the full clipping path for it instead of the stroke-bounds shortcut. Other bases keep + // the usual skip (their clipped layers vanish with them). + if (clipped.is_empty() || shapeless_stroke_bounds(layer).is_none()) && empty_in(layer, rect) { + return; + } + let opacity = layer.opacity * layer.fill_opacity; + + // Pass-through groups composite their children straight into the backdrop. Below 100% fill + // Photoshop renders the group isolated, like Normal (psd-tools passthrough_fill_*: an + // adjustment inside no longer reaches the layers beneath), and so it does for a group that + // is the base of a clipping group and holds an adjustment layer (psd-tools + // passthrough_clipping_mask_adjustment: an Exposure inside leaves the layers beneath alone), + // while such a group's blend modes still reach the backdrop (passthrough_clipping_mask_blendmode). + let clip_base_adjusts = clipped.iter().any(|c| c.visible) + && matches!(&layer.content, LayerContent::Group(g) if g.children.iter().any(|c| c.visible && matches!(c.content, LayerContent::Adjustment(_)))); + if let LayerContent::Group(g) = &layer.content + && layer.blend == BlendMode::PassThrough + && layer.fill_opacity >= 1.0 + && !effects::has_effects(layer) + && !clip_base_adjusts + { + let needs_mix = opacity < 1.0 || layer.mask.is_some() || layer.vector_mask.is_some(); + let has_clipped = clipped.iter().any(|c| c.visible); + // Children can draw directly unless mixing or clipping needs the original backdrop. + let before = (needs_mix || has_clipped).then(|| backdrop.clone()); + composite_stack_at(&g.children, backdrop, cx, scope.pass_through()); + if needs_mix && let Some(before) = &before { + let mv = mask_vals(layer, rect, cx); + for (i, (p, a)) in backdrop.px.iter_mut().zip(&before.px).enumerate() { + let k = opacity * mask_k(&mv, i); + let b = *p; + // Coverage mixes premultiplied colour; the stored buffer remains straight alpha. + let wa = a[3] * (1.0 - k); + let wb = b[3] * k; + let alpha = wa + wb; + *p = if alpha > 0.0 { + let c = |c: usize| (a[c] * wa + b[c] * wb) / alpha; + [c(0), c(1), c(2), alpha] + } else { + [0.0; 4] + }; + } + } + // Layers clipped to a pass-through group sit atop the group's + // isolated rendering; their effect (isolated result with vs. without + // them, each placed over the original backdrop) is added to the + // pass-through result. Exact when the children blend Normal, close + // otherwise (matches psd-tools clipping-mask3/4/5). + if has_clipped && let (Some(before), Some(iso)) = (before, render_content(layer, rect, cx)) { + let mut clipped_iso = iso.clone(); + advanced::composite_clipped(clipped, &mut clipped_iso, cx); + let mut without = before.clone(); + blend_into(&mut without, &iso, BlendMode::Normal, opacity); + let mut with = before; + blend_into(&mut with, &clipped_iso, BlendMode::Normal, opacity); + for ((p, w), wo) in backdrop.px.iter_mut().zip(&with.px).zip(&without.px) { + // Work premultiplied so transparent areas stay consistent. + let pa = p[3]; + let mut pm = [p[0] * pa, p[1] * pa, p[2] * pa, pa]; + for c in 0..3 { + pm[c] += w[c] * w[3] - wo[c] * wo[3]; + } + pm[3] += w[3] - wo[3]; + let a = pm[3].clamp(0.0, 1.0); + *p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] }; + } + } + return; + } + + // Adjustment layers transform the backdrop, then blend the result back in. + if let LayerContent::Adjustment(adj) = &layer.content { + let mv = mask_vals(layer, rect, cx); + if mv.as_ref().is_some_and(|values| values.iter().all(|&value| opacity * value <= 0.0)) { + return; + } + let mut adjusted = scratch_buffer(rect); + adjusted.px.copy_from_slice(&backdrop.px); + cx.apply_adjustment(adj, &mut adjusted); + // Clipped layers onto an adjustment are uncommon; they composite atop the adjusted result. + advanced::composite_clipped(clipped, &mut adjusted, cx); + if layer.blend == BlendMode::Dissolve { + // An adjustment has no standalone source alpha. Its effective coverage comes from its + // own opacity and mask, not a continuous RGB mix (#3050). + for y in rect.y0..rect.y1 { + for x in rect.x0..rect.x1 { + let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize; + let k = opacity * mask_k(&mv, i); + if k > 0.0 && dissolve_noise(x, y) < k { + let a = adjusted.px[i]; + backdrop.px[i] = [a[0], a[1], a[2], backdrop.px[i][3]]; + } + } + } + } else { + match &mv { + Some(m) => blend_back(&mut backdrop.px, &adjusted.px, m.iter().map(|v| opacity * v), layer.blend), + None => blend_back(&mut backdrop.px, &adjusted.px, std::iter::repeat(opacity), layer.blend), + } + } + recycle_buffer(adjusted); + return; + } + + if effects::has_effects(layer) { + // Layer / Vector Mask Hides Effects: the effects are built without that mask, which then + // hides the finished layer and effects. + let src = advanced::effects_source(layer); + let hide = advanced::hiding_mask(layer, rect, cx); + let before = hide.as_ref().map(|_| backdrop.clone()); + composite_layer_effects(&src, clipped, backdrop, cx); + if let (Some(m), Some(b)) = (&hide, &before) { + advanced::apply_hiding_mask(backdrop, b, m); + } + return; + } + if let Some((mut content, stroke, mask)) = shape_parts(layer, clipped, rect, cx) { + advanced::composite_clipped(clipped, &mut content, cx); + for (i, (p, s)) in content.px.iter_mut().zip(&stroke.px).enumerate() { + *p = psblend::composite(BlendMode::Normal, *p, *s, 1.0); + p[3] *= mask_k(&mask, i); + } + blend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, 1.0); + return; + } + if !matches!(layer.content, LayerContent::Group(_) | LayerContent::Fill(_) | LayerContent::Adjustment(_)) + && let Some(s) = layer.surface() + && layer.blend == BlendMode::Normal + && opacity >= 1.0 + && !clipped.iter().any(|c| c.visible) + && layer.mask.is_none() + && layer.vector_mask.is_none() + && text_gamma(layer) == 1.0 + && !psblend::LAB_MIX.with(|l| l.get()) + && backdrop.px.iter().all(|p| p[3] <= 0.0) + { + s.read_rgba_into(rect, &mut backdrop.px); + for p in &mut backdrop.px { + if p[3] <= 0.0 { + *p = [0.0; 4]; + } else if p[3] < 1.0 { + *p = psblend::composite_normal_rgb([0.0; 4], *p, 1.0); + } + } + return; + } + if clipped.is_empty() + && let Some(surf) = pixel_surface(layer) + { + return composite_pixel_layer(layer, surf, backdrop, cx); + } + let Some(mut content) = render_content(layer, rect, cx) else { return }; + advanced::composite_clipped(clipped, &mut content, cx); + blend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, text_gamma(layer)); + recycle_buffer(content); +} + +/// A layer with effects (and its clipping group) onto `backdrop`. +fn composite_layer_effects(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx) { + let rect = backdrop.rect; + // Neighbourhoods are already captured by the full-region effect maps; + // content and effect application only need the output rectangle. + // A stroked shape's vector stroke stays above its clipped layers and interior effects. + let (mut content, vstroke) = match split_parts(layer, rect, cx) { + Some((fill, stroke, mask)) => (fill, Some((stroke, mask))), + None => { + let Some(content) = render_content(layer, rect, cx) else { return }; + (content, None) + } + }; + advanced::composite_clipped(clipped, &mut content, cx); + let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); + let maps = effect_maps(layer, rect, cx); + effects::composite_with_effects_prepared(layer, &content, backdrop, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke); +} + +/// The coverage-mixing gamma of a layer: the text blending gamma +/// ([`psblend::set_text_gamma`], Photoshop's default 1.45) for type layers, else 1. +pub fn text_gamma(layer: &Layer) -> f32 { + if matches!(layer.content, LayerContent::Text(_)) { psblend::text_gamma() } else { 1.0 } +} + +/// A stroked shape layer with visible clipped layers: Photoshop draws the shape's vector stroke +/// above the clipped layers, so the base content is the fill alone and the stroke is laid on top +/// after clipping. See [`split_parts`]. +fn shape_parts(layer: &Layer, clipped: &[Layer], rect: Rect, cx: &Ctx) -> Option<(Buffer, Buffer, Option>)> { + if !clipped.iter().any(|c| c.visible) { + return None; + } + split_parts(layer, rect, cx) +} + +/// A stroked shape layer's (fill, vector stroke, mask values) over `rect`; `None` for other +/// layers. Fill and stroke are unmasked: the mask applies to them together. Layer effects paint +/// the fill's interior effects beneath the vector stroke (psd-tools stroke-composite: a colour +/// overlay leaves the stroke, the stroke effect covers it). +fn split_parts(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<(Buffer, Buffer, Option>)> { + let LayerContent::Shape(sh) = &layer.content else { return None }; + sh.stroke.as_ref()?; + let (fs, ss) = shape_split::split(sh, cx.canvas, cx.depth)?; + Some((surface_to_buffer(&fs, rect), surface_to_buffer(&ss, rect), mask_vals(layer, rect, cx))) +} + +pub(crate) fn texture_ctx<'a>(layer: &Layer, region: Rect, cx: &Ctx<'a>) -> effects::TextureCtx<'a> { + let sb = effects_frame(layer, cx.canvas); + effects::TextureCtx { rect: region, patterns: cx.patterns.source(), anchor: layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))) } +} + +/// Composite `layer` onto `base` restricted to the base's alpha (clipping mask semantics), +/// honouring its channel restrictions and Blend If. +pub(crate) fn composite_atop(layer: &Layer, base: &mut Buffer, cx: &Ctx) { + let w = channel_weights(layer, cx.mode); + let blend_if = blend_if_active(layer, cx.mode); + let before = (w.is_some() || blend_if).then(|| base.clone()); + composite_atop_any(layer, base, cx); + if let Some(before) = &before { + if let Some(w) = w { + restore_channels(base, before, w); + } + if blend_if { + apply_blend_if(layer, before, base, cx); + } + } +} + +fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) { + let rect = base.rect; + if let LayerContent::Adjustment(adj) = &layer.content { + let mut adjusted = base.clone(); + cx.apply_adjustment(adj, &mut adjusted); + let mv = mask_vals(layer, rect, cx); + for (i, p) in base.px.iter_mut().enumerate() { + let k = layer.opacity * layer.fill_opacity * mask_k(&mv, i); + let a = adjusted.px[i]; + if layer.blend == BlendMode::Dissolve { + let x = rect.x0 + (i % rect.width() as usize) as i32; + let y = rect.y0 + (i / rect.width() as usize) as i32; + if dissolve_noise(x, y) < k { + *p = [a[0], a[1], a[2], p[3]]; + } + continue; + } + let bl = blend::blend_rgb(layer.blend, [p[0], p[1], p[2]], [a[0], a[1], a[2]]); + for c in 0..3 { + p[c] += (bl[c] - p[c]) * k; + } + } + return; + } + if effects::has_effects(layer) { + // Effects of a clipped layer are clipped to the base too: render + // them over the base (treated as opaque) and keep the base's alpha. + // The full-region effect maps already capture their neighbourhoods. + // A mask that hides the effects applies to the finished result instead. + let hide = advanced::hiding_mask(layer, rect, cx); + let src = advanced::effects_source(layer); + let layer = src.as_ref(); + let (content, vstroke) = match split_parts(layer, rect, cx) { + Some((fill, stroke, mask)) => (fill, Some((stroke, mask))), + None => { + let Some(content) = render_content(layer, rect, cx) else { return }; + (content, None) + } + }; + let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); + let mut opaque = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() }; + let maps = effect_maps(layer, rect, cx); + effects::composite_with_effects_prepared(layer, &content, &mut opaque, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke); + if let Some(m) = &hide { + let plain = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() }; + advanced::apply_hiding_mask(&mut opaque, &plain, m); + } + for (p, o) in base.px.iter_mut().zip(&opaque.px) { + if p[3] > 0.0 { + *p = [o[0], o[1], o[2], p[3]]; + } + } + return; + } + let Some(content) = render_content(layer, rect, cx) else { return }; + let opacity = layer.opacity * layer.fill_opacity; + let gamma = text_gamma(layer); + for (i, p) in base.px.iter_mut().enumerate() { + let alpha = p[3]; + if alpha <= 0.0 { + continue; + } + let s = content.px[i]; + if layer.blend == BlendMode::Dissolve { + // Clipping preserves the opaque base's alpha. Dissolve still selects source + // pixels by spatial coverage instead of continuously mixing the colours (#3052). + let x = rect.x0 + (i as i32 % rect.width() as i32); + let y = rect.y0 + (i as i32 / rect.width() as i32); + if dissolve_noise(x, y) < s[3] * opacity { + *p = [s[0], s[1], s[2], alpha]; + } + continue; + } + // Blend as if the base were opaque, then keep the base's alpha. + let r = blend::composite_gamma(layer.blend, [p[0], p[1], p[2], 1.0], s, opacity, gamma); + *p = [r[0], r[1], r[2], alpha]; + } +} + +/// Blend an isolated layer buffer into the backdrop. +fn blend_into(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32) { + blend_into_g(backdrop, src, mode, opacity, 1.0); +} + +/// [`blend_into_g`] for a layer's own `opacity` and `fill`: Fill is part of the blend for +/// Photoshop's special eight ([`psblend::composite_fill`]), plain coverage otherwise. +pub(crate) fn blend_into_fill(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, fill: f32, gamma: f32) { + for_rows(backdrop, src, |dst, s, x0, y| blend_span_fill(dst, s, x0, y, mode, opacity, fill, gamma)); +} + +/// [`blend_into`] mixing coverage in a `gamma` space (type layers). +pub(crate) fn blend_into_g(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, gamma: f32) { + for_rows(backdrop, src, |dst, s, x0, y| blend_span_g(dst, s, x0, y, mode, opacity, gamma)); +} + +/// Runs `f(backdrop row, src row, x0, y)` over the rows of two buffers covering the same rect. +fn for_rows(backdrop: &mut Buffer, src: &Buffer, mut f: impl FnMut(&mut [[f32; 4]], &[[f32; 4]], i32, i32)) { + let rect = backdrop.rect; + let w = (rect.width() as usize).max(1); + for (ry, (dst, s)) in backdrop.px.chunks_mut(w).zip(src.px.chunks(w)).enumerate() { + f(dst, s, rect.x0, rect.y0 + ry as i32); + } +} + +/// [`blend_into_fill`] of one row: `dst` and `src` start at pixel (`x0`, `y`). +#[allow(clippy::too_many_arguments)] +fn blend_span_fill(dst: &mut [[f32; 4]], src: &[[f32; 4]], x0: i32, y: i32, mode: BlendMode, opacity: f32, fill: f32, gamma: f32) { + if fill >= 1.0 || !psblend::fill_is_special(mode) { + return blend_span_g(dst, src, x0, y, mode, opacity * fill, gamma); + } + for (b, s) in dst.iter_mut().zip(src) { + if s[3] > 0.0 { + *b = psblend::composite_fill(mode, *b, *s, opacity, fill, gamma); + } + } +} + +/// [`blend_into_g`] of one row: `dst` and `src` start at pixel (`x0`, `y`). +fn blend_span_g(dst: &mut [[f32; 4]], src: &[[f32; 4]], x0: i32, y: i32, mode: BlendMode, opacity: f32, gamma: f32) { + // The blend space is constant in this loop. Some TLS implementations synchronise even a + // boolean read, so select the common Normal kernel once instead of once per pixel. + if mode == BlendMode::Normal && gamma == 1.0 && !psblend::LAB_MIX.with(|l| l.get()) { + return psblend::composite_normal_rgb_span(dst, src, opacity); + } + for (x, (b, s)) in (x0..).zip(dst.iter_mut().zip(src)) { + let mut s = *s; + if s[3] <= 0.0 { + continue; + } + if mode == BlendMode::Dissolve { + s[3] = if dissolve_noise(x, y) < s[3] * opacity { 1.0 } else { 0.0 }; + *b = blend::composite(BlendMode::Normal, *b, s, 1.0); + continue; + } + *b = blend::composite_gamma(mode, *b, s, opacity, gamma); + } +} diff --git a/crates/compose/src/content.rs b/crates/compose/src/content.rs new file mode 100644 index 0000000000..88ec2751a9 --- /dev/null +++ b/crates/compose/src/content.rs @@ -0,0 +1,241 @@ +use super::composite::{adjustment_quantum, composite_stack}; +use super::ctx::Ctx; +use super::extents::{effect_shape, effect_source_bounds, mask_vals, shapeless_stroke_bounds, transparent_outside}; +use super::fx_cache::effect_maps; +use super::*; + +/// Tile size for parallel rendering (tile results are independent). +pub const RENDER_TILE: i32 = 256; + +// One tile of scratch per worker; nested rendering takes its own buffer. +thread_local! { + static SCRATCH: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +pub(crate) fn scratch_buffer(rect: Rect) -> Buffer { + if rect.width() as usize * rect.height() as usize > (RENDER_TILE * RENDER_TILE) as usize { + return Buffer::transparent(rect); + } + let mut px = SCRATCH.with(|slot| std::mem::take(&mut *slot.borrow_mut())); + px.resize(rect.width() as usize * rect.height() as usize, [0.0; 4]); + Buffer { rect, px } +} + +pub(crate) fn recycle_buffer(buf: Buffer) { + if buf.px.capacity() <= (RENDER_TILE * RENDER_TILE) as usize { + SCRATCH.with(|slot| { + let mut slot = slot.borrow_mut(); + if slot.capacity() < buf.px.capacity() { + *slot = buf.px; + } + }); + } +} + +#[cfg(test)] +#[test] +fn scratch_reuse_preserves_pixels_and_bounds_retention() { + SCRATCH.with(|slot| slot.borrow_mut().clear()); + let rect = Rect::new(-2, -3, 18, 11); + for fmt in [photocraft_color::PixelFormat::RGBA8, photocraft_color::PixelFormat::RGBA16, photocraft_color::PixelFormat::RGBA32F] { + let s = Surface::with_default(fmt, &[0.2, 0.4, 0.6, 0.8]); + let buf = surface_to_scratch(&s, rect); + assert_eq!(buf, surface_to_buffer(&s, rect)); + let ptr = buf.px.as_ptr(); + recycle_buffer(buf); + let reused = surface_to_scratch(&Surface::new(fmt), rect); + assert_eq!(reused.px.as_ptr(), ptr); + assert!(reused.px.iter().all(|p| p == &[0.0; 4])); + let nested = scratch_buffer(rect); + assert_ne!(nested.px.as_ptr(), reused.px.as_ptr()); + recycle_buffer(nested); + recycle_buffer(reused); + } + let cached = SCRATCH.with(|slot| slot.borrow().as_ptr()); + let huge = scratch_buffer(Rect::new(0, 0, RENDER_TILE + 1, RENDER_TILE)); + recycle_buffer(huge); + SCRATCH.with(|slot| { + assert_eq!(slot.borrow().as_ptr(), cached); + assert!(slot.borrow().capacity() <= (RENDER_TILE * RENDER_TILE) as usize); + }); +} + +/// Render a layer's own content (no blending into the backdrop yet) into an isolated buffer. +/// Returns None for layers that operate on the backdrop (adjustments, pass-through groups). +pub(crate) fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option { + let mut buf = match &layer.content { + LayerContent::Group(g) => { + let mut b = Buffer::transparent(rect); + composite_stack(&g.children, &mut b, cx); + b + } + LayerContent::Fill(f) => match &layer.fill_cache { + // Photoshop's own rendering, valid while the fill is unchanged. + Some(c) if c.fill == *f => surface_to_scratch(&c.surface, rect), + _ if cx.mode == photocraft_color::ColorMode::Cmyk => { + let frame = fill_frame(layer, cx.canvas); + let native_rect = if matches!(f, Fill::Solid(_)) { Rect::new(0, 0, 1, 1) } else { rect }; + match gradient_fill::render_cmyk_fill(f, native_rect, frame, cx.depth) { + Some(s) if matches!(f, Fill::Solid(_)) => Buffer::filled(rect, s.rgba(0, 0)), + Some(s) => surface_to_buffer(&s, rect), + None => render_fill(f, rect, frame, cx.patterns, adjustment_quantum(cx.depth)), + } + } + _ => render_fill(f, rect, fill_frame(layer, cx.canvas), cx.patterns, adjustment_quantum(cx.depth)), + }, + LayerContent::Adjustment(_) => return None, + _ => match layer.surface() { + Some(s) => surface_to_scratch(s, rect), + None => Buffer::transparent(rect), + }, + }; + if let Some(m) = mask_vals(layer, rect, cx) { + for (p, k) in buf.px.iter_mut().zip(&m) { + p[3] *= k; + } + } + Some(buf) +} + +/// The shape `layer`'s effect maps are built from over `rect` (row-major; for the GPU +/// compositor): its content's alpha (masks applied), joined with the [`effect_outline`] of a +/// filled shape. Zero for adjustment layers. +/// +/// See also [`stroke_frame`]. +pub fn layer_shape(doc: &Document, layer: &Layer, rect: Rect) -> Vec { + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let cx = Ctx::for_doc(doc, &patterns); + effect_shape(layer, rect, &cx) +} + +/// The frame a gradient stroke `st` of `layer` is laid out in (`effects::FxMaps::stroke_frame`), +/// from the layer's cached effect maps; `None` when `st` isn't a gradient stroke of the layer. +/// For the GPU compositor. +pub fn stroke_frame(doc: &Document, layer: &Layer, st: &photocraft_doc::StrokeFx) -> Option { + if !matches!(st.paint, photocraft_doc::FxPaint::Gradient(_)) || !effects::has_effects(layer) { + return None; + } + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let cx = Ctx::for_doc(doc, &patterns); + effect_maps(layer, doc.bounds(), &cx).stroke_frame(st) +} + +pub fn surface_to_buffer(s: &Surface, rect: Rect) -> Buffer { + let mut px = vec![[0.0f32; 4]; rect.width() as usize * rect.height() as usize]; + s.read_rgba_into(rect, &mut px); + Buffer { rect, px } +} + +fn surface_to_scratch(s: &Surface, rect: Rect) -> Buffer { + let mut buf = scratch_buffer(rect); + s.read_rgba_into(rect, &mut buf.px); + buf +} + +/// The frame a fill layer's gradient is laid out in ("Align with layer", Photoshop's default): +/// the layer's bounds, i.e. the area its masks reveal: a hide-all pixel mask's painted area, or +/// the vector mask's path; otherwise the canvas. +pub fn fill_frame(layer: &Layer, canvas: Rect) -> Rect { + let mut frame = canvas; + // "Align with layer" off: the canvas (the Gradient tool's live gradients). + if let LayerContent::Fill(Fill::Gradient { align: false, .. }) = &layer.content { + return frame; + } + if let Some(m) = &layer.mask + && m.enabled + && m.surface.default_pixel().first().is_some_and(|v| *v <= 0.0) + { + let b = bounds::content_bounds(&m.surface).intersect(&canvas); + if !b.is_empty() { + frame = b; + } + } + if let Some(vm) = &layer.vector_mask + && vm.enabled + && !vm.path.inverted + && let Some((x0, y0, x1, y1)) = vm.path.control_bounds() + { + let b = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32).intersect(&frame); + if !b.is_empty() { + frame = b; + } + } + frame +} + +/// A fill layer's content over `canvas`, laid out in the frame its masks give it (as the +/// compositor does) but without applying the masks: the pixels a PSD fill layer stores. +pub fn render_fill_content(layer: &Layer, f: &Fill, canvas: Rect, patterns: &[Pattern]) -> Buffer { + let prepared = pattern::PreparedPatterns::new(patterns, pattern::PREPARED_PATTERN_BYTES); + render_fill(f, canvas, fill_frame(layer, canvas), &prepared, None) +} + +/// `quantum`: the document depth's levels, which a dithered gradient is rounded to +/// ([`gradient_fill::render_quantized`]); `None` keeps it in float. +pub(crate) fn render_fill(f: &Fill, rect: Rect, canvas: Rect, patterns: &pattern::PreparedPatterns<'_>, quantum: Option) -> Buffer { + match f { + Fill::Solid(c) => { + let rgb = c.to_rgb(); + Buffer::filled(rect, [rgb[0], rgb[1], rgb[2], c.alpha]) + } + // Gradient geometry relative to the layer's frame, independent of the render rect. + Fill::Gradient { .. } => Buffer { rect, px: gradient_fill::render_quantized(f, rect, canvas, quantum) }, + // Laid out from the layer's frame when linked; transparent if the pattern is missing. + Fill::Pattern { name, scale, id, angle, link, phase } => match patterns.get(id, name) { + Some(tile) => Buffer { rect, px: pattern::render(&tile, &pattern::Placement::new(canvas, *link, *phase, *scale, *angle), rect) }, + None => Buffer::transparent(rect), + }, + } +} + +/// `true` when a pixel-backed layer has nothing to contribute in `rect`: +/// no allocated tiles there, a transparent default, and no effects (which +/// could reach in from outside). Clipped layers depend on the base, so they +/// vanish with it. +pub(crate) fn empty_in(layer: &Layer, rect: Rect) -> bool { + if effects::has_effects(layer) { + // Effects reach at most `margin` beyond the layer's pixels (when it is transparent + // outside them; a group's from its children with their effects): render tiles away from a + // small text layer skip it entirely. + let canvas = Rect::new(i32::MIN / 4, i32::MIN / 4, i32::MAX / 4, i32::MAX / 4); + let bounds = shapeless_stroke_bounds(layer).unwrap_or_else(|| effect_source_bounds(layer, canvas)); + return transparent_outside(layer) && bounds.inflate(effects::margin(layer)).intersect(&rect).is_empty(); + } + match &layer.content { + LayerContent::Raster(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_) => match layer.surface() { + Some(s) => !s.has_tiles_in(rect) && s.default_pixel().last().is_some_and(|a| *a <= 0.0) && s.format().alpha, + None => true, + }, + _ => false, + } +} + +/// Blending Options › Channels as per-channel weights over display RGB (1 = the layer's result, +/// 0 = the backdrop's value kept), or `None` when every channel blends. RGB documents map R, G, B +/// directly and a grayscale document's single channel covers all three; other modes composite in +/// display RGB, where a restriction to their own channels has no exact equivalent, so it is +/// ignored there. +pub fn channel_weights(layer: &Layer, mode: photocraft_color::ColorMode) -> Option<[f32; 3]> { + use photocraft_color::ColorMode as M; + let x = layer.excluded_channels; + if x == 0 { + return None; + } + let keep = |bit: u32| if x & (1 << bit) != 0 { 0.0 } else { 1.0 }; + match mode { + M::Rgb => Some([keep(0), keep(1), keep(2)]), + M::Grayscale | M::Duotone => Some([keep(0); 3]), + _ => None, + } + .filter(|w| w != &[1.0; 3]) +} + +/// Put back the backdrop's values in the channels a layer leaves out (`w` from +/// [`channel_weights`]); alpha stays the layer's result. +pub(crate) fn restore_channels(out: &mut Buffer, before: &Buffer, w: [f32; 3]) { + for (p, b) in out.px.iter_mut().zip(&before.px) { + for c in 0..3 { + p[c] = b[c] + (p[c] - b[c]) * w[c]; + } + } +} diff --git a/crates/compose/src/ctx.rs b/crates/compose/src/ctx.rs new file mode 100644 index 0000000000..38c150db55 --- /dev/null +++ b/crates/compose/src/ctx.rs @@ -0,0 +1,225 @@ +use super::content::empty_in; +use super::fx_cache::{effect_maps, fx_over_budget, layer_identity}; +use super::*; + +type VectorMaskSlot = std::sync::Arc>; + +#[derive(Default)] +pub(crate) struct RenderVectorMasks { + /// Compiled masks by content. Callers pass temporary clones (see `advanced.rs`), so an + /// address cannot identify a mask: a dropped clone's address is reused by the next one. + masks: std::sync::Mutex>, +} + +impl RenderVectorMasks { + pub(crate) fn values(&self, mask: &photocraft_doc::VectorMask, rect: Rect) -> Vec { + let slot = { + let mut masks = self.masks.lock().unwrap_or_else(|e| e.into_inner()); + match masks.iter().find(|(m, _)| m == mask) { + Some((_, slot)) => slot.clone(), + None => { + let slot = VectorMaskSlot::default(); + masks.push((mask.clone(), slot.clone())); + slot + } + } + }; + // Compilation is sequential. Rendering can enter Rayon and must happen after + // initialization, so waiting tiles cannot re-enter a slot still being built. + let compiled = slot.get_or_init(|| photocraft_vector::CompiledVectorMask::new(mask)); + compiled.render(rect) + } +} + +/// Rendering context shared down the tree. +pub(crate) struct Ctx<'a> { + /// Document canvas: fill layers and gradients are laid out relative to it, never to the render rect. + pub(crate) canvas: Rect, + /// Tone transfer used by adjustments that work in linear light. + pub(crate) transfer: adjust::Transfer, + /// Global light for layer effects. + pub(crate) light: photocraft_doc::GlobalLight, + /// Prepared document patterns, shared across all tiles and bands of this render call. + pub(crate) patterns: &'a pattern::PreparedPatterns<'a>, + /// The document's colour mode (channel restrictions name its channels). + pub(crate) mode: photocraft_color::ColorMode, + pub(crate) depth: photocraft_color::SampleType, + /// At most 1 MiB of tone tables, initialized once and shared by this render's tiles and bands. + pub(crate) tone_luts: Vec<(&'a photocraft_doc::Adjustment, std::sync::OnceLock<[Vec; 4]>)>, + pub(crate) vector_masks: RenderVectorMasks, + /// Effect maps used by this render, by cache key: built before the parallel tiles (see + /// [`prepare_effects`]) and held for the whole render (or band, for maps clipped to it: the + /// `bool`), so eviction can't force a rebuild. + pub(crate) fx_maps: std::sync::Mutex, bool)>>, + /// The rectangle being rendered (a band of [`render_bands`]); see [`effect_region`]. + pub(crate) fx_clip: std::sync::Mutex>, + /// The whole-region effect maps of this render's layers wouldn't fit in the effect cache + /// together ([`fx_over_budget`]), so local ones are clipped to the render rect (#8330). + pub(crate) fx_over_budget: bool, + /// The document being rendered (deep knockouts reveal its Background); `None` for a lone layer. + pub(crate) doc: Option<&'a Document>, + /// Effect-map identities of this render's document layers (see [`LayerKeys`]). + pub(crate) layer_keys: LayerKeys, +} + +/// Memo of [`layer_identity`] for the layers of the document being rendered. The identity depends +/// on the layer alone, not on the tile, so it is computed once per layer per render instead of +/// once per tile. Only layers that sit in the document tree are memoised by address: the document +/// is borrowed for the whole render, so no other object can live at such an address. Temporary +/// copies (`advanced::effects_source`) are never in the tree and always take the full path. +#[derive(Default)] +pub(crate) struct LayerKeys { + /// Addresses of every layer in the document tree, collected on first use. + in_doc: std::sync::OnceLock>, + ids: std::sync::Mutex>, + /// Identities computed (tests count them). + #[cfg(test)] + pub(crate) built: std::sync::atomic::AtomicUsize, +} + +impl LayerKeys { + pub(crate) fn identity(&self, layer: &Layer, doc: Option<&Document>) -> u64 { + let addr = std::ptr::from_ref(layer) as usize; + let in_doc = doc.is_some_and(|d| self.in_doc.get_or_init(|| doc_layer_addresses(d)).contains(&addr)); + if in_doc { + let mut ids = self.ids.lock().unwrap_or_else(|e| e.into_inner()); + // Computing an identity only hashes immutable layer data; it does not run Rayon + // work or re-enter this memo. Keep the miss and insertion atomic across callers. + *ids.entry(addr).or_insert_with(|| self.compute(layer)) + } else { + self.compute(layer) + } + } + + fn compute(&self, layer: &Layer) -> u64 { + use std::hash::Hasher; + #[cfg(test)] + self.built.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let mut h = std::collections::hash_map::DefaultHasher::new(); + layer_identity(layer, &mut h, &mut |_| {}); + h.finish() + } +} + +/// Addresses of all layers of `doc` (groups' children included). +fn doc_layer_addresses(doc: &Document) -> std::collections::HashSet { + let mut out = std::collections::HashSet::new(); + let mut todo: Vec<&Layer> = doc.layers.iter().collect(); + while let Some(l) = todo.pop() { + out.insert(std::ptr::from_ref(l) as usize); + if let LayerContent::Group(g) = &l.content { + todo.extend(g.children.iter()); + } + } + out +} + +impl<'a> Ctx<'a> { + pub(crate) fn for_doc(doc: &'a Document, patterns: &'a pattern::PreparedPatterns<'a>) -> Self { + Self { + doc: Some(doc), + canvas: doc.bounds(), + transfer: adjust::Transfer::for_document(doc.mode, doc.depth), + light: doc.global_light, + patterns, + mode: doc.mode, + depth: doc.depth, + vector_masks: RenderVectorMasks::default(), + fx_maps: Default::default(), + fx_clip: Default::default(), + fx_over_budget: fx_over_budget(&doc.layers, doc.bounds()), + layer_keys: Default::default(), + tone_luts: prepare_tones(&doc.layers, 0), + } + } + + /// Start rendering `rect`: effect maps clipped to the previous rectangle are let go. + pub(crate) fn set_fx_clip(&self, rect: Rect) { + let mut clip = self.fx_clip.lock().unwrap_or_else(|e| e.into_inner()); + if *clip != Some(rect) { + *clip = Some(rect); + self.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, (_, clipped)| !*clipped); + } + } + + pub(crate) fn apply_adjustment(&self, adj: &photocraft_doc::Adjustment, buf: &mut Buffer) { + if let photocraft_doc::Adjustment::Levels { space, .. } | photocraft_doc::Adjustment::Curves { space, .. } = adj + && !matches!(adj, photocraft_doc::Adjustment::Levels { space: photocraft_doc::adjust::ToneSpace::Rgb, .. } if self.depth == photocraft_color::SampleType::F32) + && let Some((_, luts)) = self.tone_luts.iter().find(|(a, _)| std::ptr::eq(*a, adj)) + { + let identity = adjust::float_tone_identity(adj, Some(self.depth)); + if identity == [true; 3] { + return; + } + let extrapolate = adjust::float_tone_extrapolates(adj, Some(self.depth), self.mode); + adjust::apply_tone(buf, *space, luts.get_or_init(|| adjust::tone_luts_depth(adj, Some(self.depth))), identity, extrapolate); + } else { + adjust::apply_in(adj, buf, self.transfer, Some(self.depth), self.mode); + } + } +} + +pub(crate) fn prepare_tones(layers: &[Layer], depth: u32) -> Vec<(&photocraft_doc::Adjustment, std::sync::OnceLock<[Vec; 4]>)> { + let mut out = Vec::new(); + for layer in layers.iter().filter(|l| l.visible) { + if out.len() == 16 { + break; + } + match &layer.content { + LayerContent::Adjustment(a @ (photocraft_doc::Adjustment::Levels { .. } | photocraft_doc::Adjustment::Curves { .. })) => { + out.push((a, Default::default())) + } + LayerContent::Group(g) if depth < PREPARE_DEPTH => out.extend(prepare_tones(&g.children, depth + 1).into_iter().take(16 - out.len())), + _ => {} + } + } + out +} + +/// Deepest group nesting preparation walks (deeper layers prepare on demand). +pub(crate) const PREPARE_DEPTH: u32 = 64; + +/// Build the effect maps of every visible layer in `layers` (groups included) that can reach +/// `rect` before tiles render in parallel, layers concurrently on native targets, each build +/// inside `setting` (the tiles' thread-local colour setting). Tiles then only read finished maps: +/// none builds one while others need it (#276), and none duplicates another's build. Builds never +/// wait on each other (`cached_effect_maps`), so building them in parallel can't deadlock. +pub(crate) fn prepare_effects(layers: &[Layer], rect: Rect, cx: &Ctx, setting: impl Fn(&mut dyn FnMut()) + Sync) { + let mut todo = Vec::new(); + effect_layers(layers, rect, 0, &mut todo); + let build = |l: &std::borrow::Cow| { + setting(&mut || { + let _ = effect_maps(l, rect, cx); + }); + }; + #[cfg(not(target_arch = "wasm32"))] + if todo.len() > 1 { + use rayon::prelude::*; + todo.par_iter().for_each(build); + return; + } + todo.iter().for_each(build); +} + +/// The visible layers of `layers` (groups included) with effects that can reach `rect`. +pub(crate) fn effect_layers<'l>(layers: &'l [Layer], rect: Rect, depth: u32, out: &mut Vec>) { + let mut base_visible = true; + for l in layers { + if !l.clipped { + base_visible = l.visible; + } + // A clipping group is drawn only when its base is. + if !l.visible || !base_visible { + continue; + } + if effects::has_effects(l) && !empty_in(l, rect) { + // A mask that hides the effects is left out of the shape they are built from. + out.push(advanced::effects_source(l)); + } + if let LayerContent::Group(g) = &l.content + && depth < PREPARE_DEPTH + { + effect_layers(&g.children, rect, depth + 1, out); + } + } +} diff --git a/crates/compose/src/effects/tests.rs b/crates/compose/src/effects/tests.rs index c811b89e13..4aea00004f 100644 --- a/crates/compose/src/effects/tests.rs +++ b/crates/compose/src/effects/tests.rs @@ -690,9 +690,7 @@ fn bevel_maps_do_not_depend_on_the_threads() { /// The four fields that use the distance transform, of `m`. fn distance_field_of(m: &Map, reach: f32) -> Vec> { - [FieldKind::Inside, FieldKind::Outside, FieldKind::BevelInside, FieldKind::BevelOutside] - .map(|k| distance_field(k, m.v.clone(), m.w, m.h, reach)) - .to_vec() + [FieldKind::Inside, FieldKind::Outside, FieldKind::BevelInside, FieldKind::BevelOutside].map(|k| distance_field(k, m.v.clone(), m.w, m.h, reach)).to_vec() } fn aa_disc(w: usize, h: usize, r: f32) -> Map { @@ -774,11 +772,8 @@ fn bevel_contour_and_texture_shape_the_height() { photocraft_doc::adjust::CurvePoint { input: 0.5, output: 1.0 }, photocraft_doc::adjust::CurvePoint { input: 1.0, output: 0.0 }, ]; - c.contour = Some(photocraft_doc::BevelContour { - contour: Contour::Custom { name: "fold".into(), points: fold, corners: vec![] }, - range: 1.0, - anti_alias: false, - }); + c.contour = + Some(photocraft_doc::BevelContour { contour: Contour::Custom { name: "fold".into(), points: fold, corners: vec![] }, range: 1.0, anti_alias: false }); let (b, _) = bevel_maps(&shape, &c, &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)); let diff: f32 = a[1].v.iter().zip(&b[1].v).map(|(x, y)| (x - y).abs()).sum(); assert!(diff > 5.0, "{diff}"); @@ -788,15 +783,8 @@ fn bevel_contour_and_texture_shape_the_height() { sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]); let pats = [Pattern::new("stripes", sf, 4, 4)]; let mut t = plain.clone(); - t.texture = Some(photocraft_doc::BevelTexture { - name: "stripes".into(), - id: String::new(), - scale: 1.0, - depth: 1.0, - invert: false, - link: true, - phase: (0.0, 0.0), - }); + t.texture = + Some(photocraft_doc::BevelTexture { name: "stripes".into(), id: String::new(), scale: 1.0, depth: 1.0, invert: false, link: true, phase: (0.0, 0.0) }); let tex = TextureCtx { rect: Rect::new(0, 0, 40, 40), patterns: &pats, anchor: (0.0, 0.0) }; let (m, _) = bevel_maps(&shape, &t, &l, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)); let mid: f32 = (16..24).map(|y| m[0].v[y * 40 + 20] + m[1].v[y * 40 + 20]).sum(); diff --git a/crates/compose/src/extents.rs b/crates/compose/src/extents.rs new file mode 100644 index 0000000000..77b99bed85 --- /dev/null +++ b/crates/compose/src/extents.rs @@ -0,0 +1,428 @@ +use super::content::{render_content, surface_to_buffer}; +use super::ctx::Ctx; +use super::*; + +/// Bounds of a layer's own pixels (union over group children; the canvas +/// for fill layers; an artboard's board). +pub fn layer_bounds(layer: &Layer, canvas: Rect) -> Rect { + // Transparency Shapes Layer off: effects and knockout cover the whole layer (the canvas). + if advanced::shapeless(layer) { + return canvas; + } + match &layer.content { + LayerContent::Group(g) if g.artboard.is_some() => g.artboard.as_ref().map_or(Rect::EMPTY, |a| a.rect), + LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).fold(Rect::EMPTY, |acc, c| { + let b = layer_bounds(c, canvas); + if b.is_empty() { + acc + } else if acc.is_empty() { + b + } else { + acc.union(&b) + } + }), + LayerContent::Fill(_) => canvas, + _ => { + let b = layer.surface().map_or(Rect::EMPTY, bounds::content_bounds); + let b = match &layer.content { + LayerContent::Shape(sh) => { + let p = shape_bounds(sh).map(|r| r.intersect(&canvas)).unwrap_or(Rect::EMPTY); + if !b.is_empty() && !p.is_empty() { + b.union(&p) + } else if !p.is_empty() { + p + } else { + b + } + } + _ => b, + }; + // Effects follow a filled shape's outline, also where its fill is transparent. + match effect_outline(layer).and_then(|_| paint_bounds(layer)).filter(|_| effects::has_effects(layer)) { + Some(p) if !b.is_empty() => b.union(&p), + Some(p) => p, + None => b, + } + } + } +} + +/// Where a layer's effects take their shape from: [`layer_bounds`], except that a group's +/// children count with their own effects (a child's outside stroke shapes the group's drop +/// shadow and must not be cut off at the child's pixels, #3274). +pub fn effect_source_bounds(layer: &Layer, canvas: Rect) -> Rect { + match &layer.content { + LayerContent::Group(g) if g.artboard.is_none() && !advanced::shapeless(layer) => g.children.iter().filter(|c| c.visible).fold(Rect::EMPTY, |acc, c| { + let m = if effects::has_effects(c) { effects::margin(c) } else { 0 }; + let b = effect_source_bounds(c, canvas); + let b = if b.is_empty() { b } else { b.inflate(m) }; + if b.is_empty() { + acc + } else if acc.is_empty() { + b + } else { + acc.union(&b) + } + }), + _ => layer_bounds(layer, canvas), + } +} + +/// The path a shape layer's effects are shaped by: its fill path. Photoshop builds a filled +/// shape's layer effects from its vector outline, not from its pixels: a stroke runs along the +/// whole path even where a gradient fill fades out (psd-tools stroke-effects). `None` for other +/// layers, shapes without fill, empty and inverted paths, and shapes whose vector stroke reaches +/// past the path (their pixels give the outline: psd-tools double-stroke-effects), and shapes +/// with a density or feather. +pub fn effect_outline(layer: &Layer) -> Option<&photocraft_doc::vector::Path> { + let LayerContent::Shape(sh) = &layer.content else { return None }; + let stroke_inside = sh.stroke.as_ref().is_none_or(|s| s.width <= 0.0 || s.align == photocraft_doc::vector::StrokeAlign::Inside); + // A soft (feathered or less dense) fill's own alpha is its outline. + (sh.fill.is_some() && stroke_inside && !sh.path.is_empty() && !sh.path.inverted && !sh.has_soft_mask()).then_some(&sh.path) +} + +/// The shape a layer's effects are built from over `rect` (row-major): its content's alpha +/// (masks applied), completed for shapes with an [`effect_outline`] by the outline's coverage +/// where the fill is see-through. With `l` the alpha and `f` the fill's own opacity (the largest +/// alpha around), the shape is `l + (1 - f) × coverage`: Photoshop's own rasterization where the +/// fill is opaque (it can differ from ours by a fraction of a pixel: psd-tools shape-fx2), the +/// path where the fill fades out (psd-tools stroke-effects). +pub(crate) fn effect_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec { + let n = rect.width() as usize * rect.height() as usize; + // Transparency Shapes Layer off: the effects take the whole layer as their shape (its masks + // still apply). + if !layer.advanced.transparency_shapes { + return mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n]); + } + let Some(path) = effect_outline(layer).filter(|_| n > 0) else { + return render_content(layer, rect, cx).map(|b| b.px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; n]); + }; + // Unmasked: the masks scale the shape, they aren't the fill's transparency. + let a: Vec = layer.surface().map(|s| surface_to_buffer(s, rect).px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; n]); + let cov = photocraft_vector::path_coverage(path, rect); + let mv = mask_vals(layer, rect, cx); + let (w, h) = (rect.width() as usize, rect.height() as usize); + let mut out = vec![0.0; n]; + for y in 0..h { + for x in 0..w { + let i = y * w + x; + // A pixel the outline covers is inside, whatever the fill's opacity. + let v = if cov[i] >= 1.0 - 1e-3 { + 1.0 + } else { + let mut f = 0.0f32; + for yy in y.saturating_sub(1)..(y + 2).min(h) { + for xx in x.saturating_sub(1)..(x + 2).min(w) { + f = f.max(a[yy * w + xx]); + } + } + (a[i] + (1.0 - f.min(1.0)) * cov[i]).clamp(0.0, 1.0) + }; + out[i] = v * mask_k(&mv, i); + } + } + out +} + +/// The frame layer-effect gradients and linked patterns are laid out in, when it isn't the +/// layer's pixel bounds: a shape layer's path bounds, truncated to whole pixels. Its rendered +/// pixels can extend past the path (transparent anti-aliasing margin), which Photoshop ignores: +/// psd-tools shape-fx2's 45° overlay spans the 0.92–29.61 path as 0–29 (29 px, centred at 14.5), +/// not the 32 px of pixels. +pub fn paint_bounds(layer: &Layer) -> Option { + let LayerContent::Shape(sh) = &layer.content else { return None }; + let (x0, y0, x1, y1) = sh.path.control_bounds()?; + let r = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.floor() as i32, y1.floor() as i32); + (!r.is_empty()).then_some(r) +} + +/// The frame a layer's effects are laid out in: [`paint_bounds`] for a shape, else the layer's +/// bounds ([`layer_bounds`]). A Gradient Overlay spans it, linked patterns tile from its corner. +pub fn effects_frame(layer: &Layer, canvas: Rect) -> Rect { + paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, canvas)) +} + +/// The pixels a change from `a` to `b` repaints beyond those it changed: where a layer whose +/// effects span its frame ([`effects::spans_frame`]) moved that frame, the layer's whole composite +/// before and after. Painting on a layer with a Gradient Overlay lays the one gradient out again +/// over the grown layer, as Photoshop does after each stroke; damage that covers only the stroke +/// leaves the old gradient around earlier strokes (#4053). Empty when no such frame moved. +pub fn relayout_damage(a: &Document, b: &Document) -> Rect { + let mut out = Rect::EMPTY; + let mut add = |r: Rect| { + if !r.is_empty() { + out = if out.is_empty() { r } else { out.union(&r) }; + } + }; + for (_, _, y) in b.walk() { + if !y.visible || !effects::spans_frame(y) { + continue; + } + let Some(x) = a.layer(y.id) else { continue }; + if effects_frame(x, a.bounds()) == effects_frame(y, b.bounds()) { + continue; + } + add(change_bounds(x, a.bounds()).unwrap_or_else(|| a.bounds())); + add(change_bounds(y, b.bounds()).unwrap_or_else(|| b.bounds())); + } + out +} + +/// The bounding box of a shape layer's path and stroke, ignoring its Density and Feather: its +/// path control bounds plus stroke width (a conservative reach for any alignment, cap and join). +pub fn hard_shape_bounds(sh: &photocraft_doc::ShapeLayer) -> Option { + if sh.fill.is_none() && sh.stroke.as_ref().is_none_or(|s| s.width <= 0.0 || s.opacity <= 0.0) { + return None; + } + let (x0, y0, x1, y1) = sh.path.control_bounds()?; + let stroke_margin = sh.stroke.as_ref().filter(|s| s.opacity > 0.0).map_or(0.0, |s| s.width.ceil()) as i32; + let r = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32).inflate(stroke_margin); + (!r.is_empty()).then_some(r) +} + +/// The frame Free Transform, the Move tool's transform controls, snapping and Properties show for +/// a soft shape (Density below 100 % or a Feather), whose rendering reaches past its path: the +/// pixels the same shape renders in `format` over `canvas` at full Density without Feather, so +/// the frame is exactly the hard shape's whatever the stroke's alignment, cap and join (in +/// Photoshop a shape's transform frame follows its path and stroke whatever its mask Density and +/// Feather, #5846). An inverted path's frame is its own outline, not the whole canvas. Renders +/// only the strips along the edges of the rasterizers' (1 px conservative) bounds. +pub fn soft_shape_frame(sh: &photocraft_doc::ShapeLayer, format: photocraft_color::PixelFormat, canvas: Rect) -> Option { + let mut path = sh.path.clone(); + path.inverted = false; + let hard = photocraft_doc::ShapeLayer { density: 1.0, feather: 0.0, path, fill: sh.fill.clone(), stroke: sh.stroke.clone(), ..Default::default() }; + let shape = photocraft_vector::CompiledShape::new(&hard, photocraft_vector::DEFAULT_TOLERANCE, canvas); + let r = shape.bounds()?.intersect(&canvas); + trim_to_painted(r, |strip| shape.render(format, strip).content_bounds()) +} + +/// `r` shrunk to the pixels `painted` reports (the painted bounds within a strip of `r`, empty if +/// none), looking in from each edge through strips that double in thickness: a few renders per +/// edge however wide the empty margin (a subtracted or intersected subpath can leave most of the +/// rasterizers' bounds empty), and none of `r`'s inside rendered at once. +pub(crate) fn trim_to_painted(mut r: Rect, mut painted: impl FnMut(Rect) -> Rect) -> Option { + // Top: the first strip holding paint gives the first painted row. + let mut t = 1; + while !r.is_empty() { + let strip = Rect::new(r.x0, r.y0, r.x1, r.y0.saturating_add(t).min(r.y1)); + let p = painted(strip).intersect(&strip); + if !p.is_empty() { + r.y0 = p.y0; + break; + } + r.y0 = strip.y1; + t = t.saturating_mul(2); + } + let mut t = 1; + while !r.is_empty() { + let strip = Rect::new(r.x0, r.y1.saturating_sub(t).max(r.y0), r.x1, r.y1); + let p = painted(strip).intersect(&strip); + if !p.is_empty() { + r.y1 = p.y1; + break; + } + r.y1 = strip.y0; + t = t.saturating_mul(2); + } + let mut t = 1; + while !r.is_empty() { + let strip = Rect::new(r.x0, r.y0, r.x0.saturating_add(t).min(r.x1), r.y1); + let p = painted(strip).intersect(&strip); + if !p.is_empty() { + r.x0 = p.x0; + break; + } + r.x0 = strip.x1; + t = t.saturating_mul(2); + } + let mut t = 1; + while !r.is_empty() { + let strip = Rect::new(r.x1.saturating_sub(t).max(r.x0), r.y0, r.x1, r.y1); + let p = painted(strip).intersect(&strip); + if !p.is_empty() { + r.x1 = p.x1; + break; + } + r.x1 = strip.x0; + t = t.saturating_mul(2); + } + (!r.is_empty()).then_some(r) +} + +/// The bounding box of a shape layer's vector content: its path control bounds plus stroke width +/// (and the reach of a soft fill). +pub fn shape_bounds(sh: &photocraft_doc::ShapeLayer) -> Option { + let r = hard_shape_bounds(sh)?; + // A soft fill reaches past the path: by its feather, or everywhere below 100 % density. + if sh.fill.is_some() && sh.has_soft_mask() { + if sh.density.is_finite() && sh.density < 1.0 { + return Some(Rect::new(i32::MIN / 4, i32::MIN / 4, i32::MAX / 4, i32::MAX / 4)); + } + return Some(r.union(&photocraft_vector::feather::path_area(&sh.path, masks::feather_sigma(sh.feather)))); + } + Some(r) +} + +/// The layer's effective mask over `rect` (row-major), read once per tile: the pixel mask +/// times the rasterized vector mask. +pub(crate) fn mask_vals(layer: &Layer, rect: Rect, cx: &Ctx) -> Option> { + // Feathers blur across tiles: read the cached, canvas-wide combined mask. + if masks::has_feather(layer) + && let Some(s) = masks::combined_mask(layer, cx.canvas) + { + let mut v = Vec::new(); + s.read_region_into(rect, &mut v); + return Some(v); + } + let vector = layer.vector_mask.as_ref().map(|vm| cx.vector_masks.values(vm, rect)); + let Some(m) = layer.mask.as_ref() else { return vector }; + let mut v = Vec::new(); + m.values_into(rect, &mut v); + if let Some(vm) = vector { + for (a, b) in v.iter_mut().zip(vm) { + *a *= b; + } + } + Some(v) +} + +#[inline] +pub(crate) fn mask_k(m: &Option>, i: usize) -> f32 { + m.as_ref().map_or(1.0, |v| v[i]) +} + +/// For the narrow `tsly=0` case where only local stroke effects are enabled, the effects cannot +/// contribute outside the stroke reach from the layer's pixels. Other `tsly=0` effects can cover +/// the full layer, and advanced blending can change the backdrop independently of those pixels. +pub(crate) fn shapeless_stroke_bounds(layer: &Layer) -> Option { + use photocraft_doc::Knockout; + + if layer.advanced.transparency_shapes + || layer.advanced.knockout != Knockout::None + || layer.advanced.blend_interior + || layer.clipped + || !layer.blend_if.is_default() + || layer.mask.as_ref().is_some_and(|m| m.enabled) + || layer.vector_mask.as_ref().is_some_and(|m| m.enabled) + || !transparent_outside(layer) + || !effects::maps_are_local(layer) + { + return None; + } + + if !layer.effects.enabled + || !layer.effects.items.iter().any(|e| e.enabled()) + || layer.effects.items.iter().any(|e| e.enabled() && !matches!(e, photocraft_doc::Effect::Stroke(_))) + { + return None; + } + + match &layer.content { + LayerContent::Raster(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_) => { + let b = layer.surface().map_or(Rect::EMPTY, bounds::content_bounds); + // A filled shape's effects follow its outline, also where its fill is transparent (as + // in `layer_bounds`). + Some(match effect_outline(layer).and_then(|_| paint_bounds(layer)) { + Some(p) if !b.is_empty() => b.union(&p), + Some(p) => p, + None => b, + }) + } + _ => None, + } +} + +/// Where `layer`'s composite (its pixels and effects; a group's visible children with theirs) can +/// be non-transparent, or `None` when it may draw anywhere (a surface with an opaque default +/// pixel). Outside it, compositing the layer leaves the backdrop unchanged in every blend mode. +/// Adjustment layers count as empty: they only change pixels already there (which is what an +/// isolated group needs; see [`change_bounds`] for the document-level question). +pub fn composite_bounds(layer: &Layer, canvas: Rect) -> Option { + if !transparent_outside(layer) { + return None; + } + let own = match &layer.content { + LayerContent::Group(g) if g.artboard.is_none() => { + let mut acc = Rect::EMPTY; + for c in g.children.iter().filter(|c| c.visible) { + let b = composite_bounds(c, canvas)?; + if !b.is_empty() { + acc = if acc.is_empty() { b } else { acc.union(&b) }; + } + } + acc + } + LayerContent::Adjustment(_) => Rect::EMPTY, + _ => layer_bounds(layer, canvas), + }; + 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)) +} + +/// The document pixels that showing, hiding, moving or restyling `layer` can change, or `None` +/// for anywhere: an adjustment layer (and a pass-through group holding one) reaches everything +/// beneath it. Clipped layers above stay within their base's bounds, so they are covered too; +/// effects of groups around the layer can reach further (callers grow the rect by that reach). +pub fn change_bounds(layer: &Layer, canvas: Rect) -> Option { + fn reaches_below(l: &Layer) -> bool { + match &l.content { + LayerContent::Adjustment(_) => !l.clipped, + // Clipped to a base, an adjustment changes only the base's pixels; one with no base + // beneath it in its list composites as an ordinary adjustment (#6535). + LayerContent::Group(g) if l.blend == BlendMode::PassThrough => g.children.iter().enumerate().any(|(k, c)| { + let orphan = + c.clipped && matches!(c.content, LayerContent::Adjustment(_)) && g.children.get(..k).is_none_or(|below| below.iter().all(|b| b.clipped)); + orphan || reaches_below(c) + }), + _ => false, + } + } + if matches!(layer.content, LayerContent::Adjustment(_)) || reaches_below(layer) { + return None; + } + 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 { + 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) + && group.blend == BlendMode::PassThrough + && !group.clipped + && outer.get(g + 1).is_some_and(|above| above.clipped) + { + // The group bounds its base too. + return change_bounds(group, canvas); + } + return change_bounds(base, canvas); + } + change_bounds(layer, canvas) +} + +/// Whether the layer's content is transparent outside its bounds (every surface it draws from +/// has a transparent default pixel), so its effects can't change pixels beyond its bounds grown +/// by their reach. +pub fn transparent_outside(layer: &Layer) -> bool { + match &layer.content { + LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).all(transparent_outside), + // Fill layers cover the canvas (their bounds); adjustments draw nothing of their own. + LayerContent::Fill(_) | LayerContent::Adjustment(_) => true, + _ => layer.surface().is_none_or(|s| s.format().alpha && s.default_pixel().last().is_some_and(|a| *a <= 0.0)), + } +} diff --git a/crates/compose/src/fx_cache.rs b/crates/compose/src/fx_cache.rs new file mode 100644 index 0000000000..cd08eaff7c --- /dev/null +++ b/crates/compose/src/fx_cache.rs @@ -0,0 +1,281 @@ +use super::composite::texture_ctx; +use super::ctx::{Ctx, PREPARE_DEPTH}; +use super::extents::{effect_shape, effect_source_bounds}; +use super::*; + +// --------------------------------------------------------------------------------------------- +// Layer-effect map cache + +/// Order-independent identity of a layer's pixels, masks, effects, Advanced Blending and Blend If +/// and (for groups) children. +/// Pixels are identified by their copy-on-write tile pointers. `pin` sees every tile hashed: a +/// cache entry keeps a [`std::sync::Weak`] to each, which reserves the tile's address (so no +/// other tile can reuse it and match the key) without keeping its pixels alive (#4530). +pub(crate) fn layer_identity(layer: &Layer, h: &mut std::collections::hash_map::DefaultHasher, pin: &mut dyn FnMut(&std::sync::Arc)) { + use std::hash::{Hash, Hasher}; + fn surface_fp(s: &Surface, pin: &mut dyn FnMut(&std::sync::Arc)) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + s.format().hash(&mut h); + // Missing tiles read the default pixel, so tile identity alone is not pixel identity. + for sample in s.default_pixel() { + sample.to_bits().hash(&mut h); + } + let tiles = s.tiles().fold(s.tile_count() as u64, |acc, (c, t)| { + pin(t); + let mut x = (std::sync::Arc::as_ptr(t) as usize as u64) ^ ((c.tx as u64) << 40) ^ ((c.ty as u32 as u64) << 8); + x = x.wrapping_mul(0x9e37_79b9_7f4a_7c15); + acc.wrapping_add(x ^ (x >> 29)) + }); + tiles.hash(&mut h); + h.finish() + } + layer.id.0.hash(h); + // What the maps depend on: `fill_opacity` shades them; layer `opacity` is applied when the + // maps are composited and `visible` only skips the lookup entirely, so neither belongs in + // the key (an opacity drag must not rebuild shadows over the whole layer; the GPU's + // `fx::shape_key` keeps them out for the same reason). + layer.fill_opacity.to_bits().hash(h); + match &layer.content { + LayerContent::Group(g) => { + for c in &g.children { + // A styled group's maps come from its children's composite, so how each child + // composites (unlike the group's own visibility and opacity) shapes them. + (c.visible, c.opacity.to_bits(), c.clipped).hash(h); + format!("{:?}", c.blend).hash(h); + layer_identity(c, h, pin); + } + format!("{:?}", g.artboard).hash(h); + } + LayerContent::Fill(f) => { + format!("{f:?}").hash(h); + // The cached pixels are what shapes the maps while they match the fill: a + // pixel-only rewrite of the cache (Image › Transform, crop) leaves `f` alone, and + // the stale maps would keep shadowing the pre-rewrite shape. + if let Some(c) = &layer.fill_cache + && c.fill == *f + { + surface_fp(&c.surface, pin).hash(h); + } + } + LayerContent::Adjustment(a) => format!("{a:?}").hash(h), + _ => layer.surface().map_or(0, |s| surface_fp(s, pin)).hash(h), + } + if let Some(m) = &layer.mask { + (surface_fp(&m.surface, pin), m.enabled, m.density.to_bits(), m.feather.to_bits()).hash(h); + } + if let Some(vm) = &layer.vector_mask { + format!("{vm:?}").hash(h); + } + format!("{:?}", layer.effects).hash(h); + // Transparency Shapes Layer picks the shape (content or the whole layer); a group child's + // Blend If and knockout change the composite a styled group's shape comes from. + layer.advanced.hash(h); + layer.blend_if.hash(h); + h.write_u8(0xfe); +} + +struct FxEntry { + maps: std::sync::Arc, + /// The tiles the key identifies (see [`layer_identity`]): their addresses, not their pixels. + _pin: Vec>, + bytes: usize, +} + +/// Global cache of effect maps (bounded by bytes), one slot per layer state. Slots are filled +/// with `set`, never `get_or_init`: nothing may block on a build (see `cached_effect_maps`). +type FxSlot = std::sync::Arc>; + +struct FxCache { + map: std::collections::HashMap, + order: std::collections::VecDeque, + bytes: usize, +} + +/// Default effect-cache budget (Preferences › Performance can change it). +pub const DEFAULT_FX_CACHE_BUDGET: usize = 768 << 20; + +static FX_CACHE_BUDGET: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(DEFAULT_FX_CACHE_BUDGET); + +/// Set the memory budget (bytes) of the layer-effect map cache; entries over it are evicted +/// oldest-first on the next build. +pub fn set_effect_cache_budget(bytes: usize) { + FX_CACHE_BUDGET.store(bytes.max(1 << 20), std::sync::atomic::Ordering::Relaxed); +} + +/// The current effect-cache budget in bytes. +pub fn effect_cache_budget() -> usize { + FX_CACHE_BUDGET.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Bytes currently held by the effect-map cache. +pub fn effect_cache_bytes() -> usize { + fx_cache().lock().unwrap_or_else(|e| e.into_inner()).bytes +} + +/// Drop every cached effect map (Edit › Purge › All). Returns the bytes released. +pub fn purge_effect_cache() -> usize { + let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); + let freed = c.bytes; + c.map.clear(); + c.order.clear(); + c.bytes = 0; + freed +} + +fn fx_cache() -> &'static std::sync::Mutex { + static C: std::sync::OnceLock> = std::sync::OnceLock::new(); + C.get_or_init(|| std::sync::Mutex::new(FxCache { map: Default::default(), order: Default::default(), bytes: 0 })) +} + +/// Where `layer`'s effect maps are built (see [`effect_maps`]) and whether that is clipped to the +/// rectangle being rendered rather than the whole region. +/// +/// Transparency Shapes Layer off makes the region the whole canvas whatever the layer holds: on a +/// 1920 × 103675 webtoon page each such layer's maps took about 2.4 GB, and a render held them for +/// every layer at once (60 GB with 25 stroked type layers, #1909). When its effects are local +/// ([`effects::maps_are_local`]), such a layer's maps are built over the render rectangle padded +/// by twice the effect reach instead, which gives the same pixels there. So are any layer's local +/// maps when the render's whole-region maps wouldn't fit in the effect cache ([`fx_over_budget`]). +/// Only when `rect`, what +/// the caller composites the layer over, lies within the render rectangle: a group's effect shape +/// (or anything else rendering children over a wider area) gets the whole region. +pub(crate) fn effect_region(layer: &Layer, rect: Rect, cx: &Ctx) -> (Rect, bool) { + let m = effects::margin(layer); + let region = effect_source_bounds(layer, cx.canvas).inflate(m).intersect(&cx.canvas.inflate(m)); + let clip = *cx.fx_clip.lock().unwrap_or_else(|e| e.into_inner()); + match clip { + Some(c) if c.contains_rect(&rect) && (advanced::shapeless(layer) || cx.fx_over_budget) && effects::maps_are_local(layer) => { + let part = region.intersect(&c.inflate(m.saturating_mul(2))); + (part, part != region) + } + _ => (region, false), + } +} + +/// Whether the effect maps of the visible layers of `layers` (groups included), each over its +/// whole region, would take more than the effect cache budget together. A render needs all of +/// them, so when they don't fit, building one evicts the next one needed and every render builds +/// them all again, seconds even for a small rect (#8330). Counted as [`effects::FxMaps::bytes`] +/// counts the built maps ([`effects::map_count`] arrays over each region). +pub(crate) fn fx_over_budget(layers: &[Layer], canvas: Rect) -> bool { + fx_region_bytes(layers, canvas) > effect_cache_budget() as u64 +} + +/// The bytes [`fx_over_budget`] compares with the budget. +pub(crate) fn fx_region_bytes(layers: &[Layer], canvas: Rect) -> u64 { + fn bytes(layers: &[Layer], canvas: Rect, depth: u32) -> u64 { + let mut total = 0u64; + for l in layers.iter().filter(|l| l.visible) { + if effects::has_effects(l) { + let m = effects::margin(l); + let region = effect_source_bounds(l, canvas).inflate(m).intersect(&canvas.inflate(m)); + let maps = effects::map_count(l) as u64; + let px = u64::from(region.width()) * u64::from(region.height()); + total = total.saturating_add(maps.saturating_mul(px).saturating_mul(4)); + } + if let LayerContent::Group(g) = &l.content + && depth < PREPARE_DEPTH + { + total = total.saturating_add(bytes(&g.children, canvas, depth + 1)); + } + } + total + } + bytes(layers, canvas, 0) +} + +/// Most bytes one layer's effect maps and source may take to build, whatever the cache budget. +const MAX_FX_BUILD_BYTES: u64 = if cfg!(target_pointer_width = "64") { 4 << 30 } else { 512 << 20 }; + +/// The layer's effect maps over its region (layer bounds grown by the effect reach, within the +/// canvas grown likewise; see [`effect_region`]), built once per layer state and shared by every +/// tile. `rect` is what the caller composites the layer over (see [`effect_region`]). +pub(crate) fn effect_maps(layer: &Layer, rect: Rect, cx: &Ctx) -> std::sync::Arc { + use std::hash::{Hash, Hasher}; + let (mut region, clipped) = effect_region(layer, rect, cx); + // Non-local effects keep their whole source region, which a few distant pixels stretch over + // the canvas: past the cap the effects are left out instead of allocating it. + let region_px = u64::from(region.width()) * u64::from(region.height()); + if (effects::map_count(layer) as u64 + 1).saturating_mul(region_px).saturating_mul(4) > MAX_FX_BUILD_BYTES { + region = Rect::EMPTY; + } + static NO_CACHE: std::sync::OnceLock = std::sync::OnceLock::new(); + if *NO_CACHE.get_or_init(|| std::env::var_os("PHOTOCRAFT_FX_NOCACHE").is_some()) { + let shape = if region.is_empty() { Vec::new() } else { effect_shape(layer, region, cx) }; + return std::sync::Arc::new(effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns)); + } + let mut h = std::collections::hash_map::DefaultHasher::new(); + cx.layer_keys.identity(layer, cx.doc).hash(&mut h); + (region.x0, region.y0, region.x1, region.y1).hash(&mut h); + (cx.light.angle.to_bits(), cx.light.altitude.to_bits()).hash(&mut h); + let key = h.finish(); + // Prepared for this render (see `prepare_effects`): no global lookup, no build. + if let Some((m, _)) = cx.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { + return m.clone(); + } + let maps = cached_effect_maps(layer, region, key, cx); + cx.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).entry(key).or_insert((maps, clipped)).0.clone() +} + +fn build_fx_slot_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx, slot: &FxSlot) -> std::sync::Arc { + let shape: Vec = if region.is_empty() { Vec::new() } else { effect_shape(layer, region, cx) }; + let maps = effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns); + let mut pin = Vec::new(); + layer_identity(layer, &mut std::collections::hash_map::DefaultHasher::new(), &mut |t| pin.push(std::sync::Arc::downgrade(t))); + // The maps, plus what each reserved tile address keeps allocated. + let bytes = maps.bytes().saturating_add(pin.len().saturating_mul(std::mem::size_of::() + 2 * std::mem::size_of::())); + let maps = std::sync::Arc::new(maps); + if slot.set(FxEntry { maps: maps.clone(), _pin: pin, bytes }).is_ok() { + // Counted exactly once, by the build that filled the slot, and only while the + // slot is still cached (eviction may have dropped it meanwhile). + let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); + if c.map.get(&key).is_some_and(|s| std::sync::Arc::ptr_eq(s, slot)) { + c.bytes += bytes; + } + } + // A concurrent build that finished first wins, so every tile shares one map. + slot.get().map_or(maps, |e| e.maps.clone()) +} + +fn evict_fx_cache_over_budget(key: u64) { + let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); + let budget = effect_cache_budget(); + while c.bytes > budget && c.order.len() > 1 { + let Some(old) = c.order.pop_front() else { break }; + if old == key { + c.order.push_back(old); + continue; + } + if let Some(s) = c.map.remove(&old) { + c.bytes = c.bytes.saturating_sub(s.get().map_or(0, |e| e.bytes)); + } + } +} + +/// The layer's effect maps from the global cache, built on a miss. +/// +/// Never waits for another thread's build (#276): this can run on a Rayon worker inside a tile, +/// and the build itself runs Rayon work. A worker waiting on that work may steal another tile of +/// the same layer; had it blocked on a once-init held further up its own stack, it would deadlock. +/// Instead a miss builds the maps here and the first finished build is kept. Renders build every +/// layer's maps before their parallel tiles (`prepare_effects`), so tiles rarely miss. +fn cached_effect_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx) -> std::sync::Arc { + let slot = { + let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); + if let Some(s) = c.map.get(&key) { + s.clone() + } else { + let s: FxSlot = Default::default(); + c.map.insert(key, s.clone()); + c.order.push_back(key); + s + } + }; + let maps = match slot.get() { + Some(e) => e.maps.clone(), + None => build_fx_slot_maps(layer, region, key, cx, &slot), + }; + // Evict the oldest entries over budget (never the one just used). + evict_fx_cache_over_budget(key); + maps +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 0a3f5c4802..e593290571 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -42,6 +42,47 @@ use psblend as blend; pub use advanced::advanced_active; +mod composite; +mod content; +mod ctx; +mod extents; +mod fx_cache; +mod reduced; +mod render; + +pub use composite::{adjustment_quantum, blend_if_active, occludes_below, text_gamma}; +#[cfg(test)] +use composite::{blend_into_fill, blend_into_g, branchless_floor, composite_layer_plain, composite_pixel_layer, pixel_surface, quantize}; +use composite::{composite_atop, composite_layer, composite_stack_at, dissolve_noise}; +#[cfg(test)] +use content::render_fill; +pub use content::{RENDER_TILE, channel_weights, fill_frame, layer_shape, render_fill_content, stroke_frame, surface_to_buffer}; +use content::{empty_in, render_content}; +use ctx::{Ctx, prepare_effects}; +#[cfg(test)] +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, +}; +#[cfg(test)] +use extents::{mask_k, shapeless_stroke_bounds, trim_to_painted}; +pub use fx_cache::{DEFAULT_FX_CACHE_BUDGET, effect_cache_budget, effect_cache_bytes, purge_effect_cache, set_effect_cache_budget}; +#[cfg(test)] +use fx_cache::{effect_maps, effect_region, fx_region_bytes}; +pub use reduced::{PROXY_THUMBNAIL_PIXELS, render_reduced, render_reduced_damage, render_reduced_rect, thumbnail, thumbnail_buffer, thumbnail_size}; +#[cfg(test)] +use reduced::{ReducedStats, render_reduced_in_bands, render_reduced_with}; +use render::in_blend_space; +#[cfg(test)] +use render::render_tiled_with; +pub(crate) use render::visible_layers; +pub use render::{ + BAND_PIXELS, MAX_RENDER_PIXELS, band_rows_for, cmyk_space, composite_to_surface, flatten, flatten_to_surface, render, render_bands, render_layer, + render_layer_in, render_tiled, +}; + /// Straight-alpha RGBA float buffer covering a rectangle. #[derive(Clone, Debug, PartialEq)] pub struct Buffer { @@ -95,2487 +136,6 @@ impl Buffer { } } -/// Tile size for parallel rendering (tile results are independent). -pub const RENDER_TILE: i32 = 256; - -// One tile of scratch per worker; nested rendering takes its own buffer. -thread_local! { - static SCRATCH: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; -} - -fn scratch_buffer(rect: Rect) -> Buffer { - if rect.width() as usize * rect.height() as usize > (RENDER_TILE * RENDER_TILE) as usize { - return Buffer::transparent(rect); - } - let mut px = SCRATCH.with(|slot| std::mem::take(&mut *slot.borrow_mut())); - px.resize(rect.width() as usize * rect.height() as usize, [0.0; 4]); - Buffer { rect, px } -} - -fn recycle_buffer(buf: Buffer) { - if buf.px.capacity() <= (RENDER_TILE * RENDER_TILE) as usize { - SCRATCH.with(|slot| { - let mut slot = slot.borrow_mut(); - if slot.capacity() < buf.px.capacity() { - *slot = buf.px; - } - }); - } -} - -#[cfg(test)] -#[test] -fn scratch_reuse_preserves_pixels_and_bounds_retention() { - SCRATCH.with(|slot| slot.borrow_mut().clear()); - let rect = Rect::new(-2, -3, 18, 11); - for fmt in [photocraft_color::PixelFormat::RGBA8, photocraft_color::PixelFormat::RGBA16, photocraft_color::PixelFormat::RGBA32F] { - let s = Surface::with_default(fmt, &[0.2, 0.4, 0.6, 0.8]); - let buf = surface_to_scratch(&s, rect); - assert_eq!(buf, surface_to_buffer(&s, rect)); - let ptr = buf.px.as_ptr(); - recycle_buffer(buf); - let reused = surface_to_scratch(&Surface::new(fmt), rect); - assert_eq!(reused.px.as_ptr(), ptr); - assert!(reused.px.iter().all(|p| p == &[0.0; 4])); - let nested = scratch_buffer(rect); - assert_ne!(nested.px.as_ptr(), reused.px.as_ptr()); - recycle_buffer(nested); - recycle_buffer(reused); - } - let cached = SCRATCH.with(|slot| slot.borrow().as_ptr()); - let huge = scratch_buffer(Rect::new(0, 0, RENDER_TILE + 1, RENDER_TILE)); - recycle_buffer(huge); - SCRATCH.with(|slot| { - assert_eq!(slot.borrow().as_ptr(), cached); - assert!(slot.borrow().capacity() <= (RENDER_TILE * RENDER_TILE) as usize); - }); -} - -/// Every layer the compositor draws, groups before their children: hidden layers and everything -/// inside hidden groups are left out. -pub(crate) fn visible_layers(layers: &[Layer]) -> Vec<&Layer> { - fn rec<'a>(layers: &'a [Layer], out: &mut Vec<&'a Layer>) { - for l in layers.iter().filter(|l| l.visible) { - out.push(l); - if let Some(children) = l.children() { - rec(children, out); - } - } - } - let mut out = Vec::new(); - rec(layers, &mut out); - out -} - -/// Composite the whole document over `rect`, in parallel 256² tiles on -/// native targets (single-threaded on wasm). -pub fn render(doc: &Document, rect: Rect) -> Buffer { - render_tiled(doc, rect, RENDER_TILE) -} - -/// Most pixels one [`render`] call will produce (2^30, a 16 GiB buffer; 32768² px). Larger rects -/// (a hostile canvas size is up to 300000 px a side) return an empty buffer instead of aborting -/// on allocation; callers wanting more render in pieces. -pub const MAX_RENDER_PIXELS: u64 = 1 << 30; - -/// [`render`] with an explicit tile size (tests check tile independence). -pub fn render_tiled(doc: &Document, rect: Rect, tile: i32) -> Buffer { - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - let cx = Ctx::for_doc(doc, &patterns); - render_tiled_with(doc, rect, tile, &cx) -} - -fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> Buffer { - let tile = tile.max(1); - // Lab documents mix Normal blending in CIELAB, as Photoshop does (psblend::LAB_MIX); 32-bit - // documents don't clip Add / Divide or Hue / Saturation / Color / Luminosity at 1 (psblend::HDR). - let lab = doc.mode == photocraft_color::ColorMode::Lab; - let hdr = doc.depth == photocraft_color::SampleType::F32; - // CMYK layers are read through the document's own CMYK profile (thread-local scope). - let cmyk = cmyk_space(doc); - let cmyk = cmyk.as_ref(); - if rect.is_empty() { - return Buffer::transparent(rect); - } - // Refuse rects too large to hold: an empty buffer, not an allocation failure. - if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS { - return Buffer::transparent(Rect::EMPTY); - } - // A CMYK stack with adjustment layers the inks carry exactly composites on its inks. - if let Some(buf) = native::render_cmyk(doc, rect, tile) { - return buf; - } - // A Lab stack with adjustment layers that work on L, a and b composites on its stored values. - if let Some(buf) = native_lab::render_lab(doc, rect, tile) { - return buf; - } - cx.set_fx_clip(rect); - if i64::from(rect.width()) <= i64::from(tile) && i64::from(rect.height()) <= i64::from(tile) { - return photocraft_color::convert::with_cmyk_space(cmyk, || { - let mut buf = multichannel::backdrop(doc, rect); - in_blend_space(lab, hdr, || composite_stack_at(&doc.layers, &mut buf, cx, advanced::Scope::ROOT)); - buf - }); - } - // Effect maps are built once, here, before any tile needs them (#276). - prepare_effects(&doc.layers, rect, cx, |f| { - photocraft_color::convert::with_cmyk_space(cmyk, || in_blend_space(lab, hdr, f)); - }); - let run = |t: Rect| { - photocraft_color::convert::with_cmyk_space(cmyk, || { - let mut b = multichannel::backdrop(doc, t); - in_blend_space(lab, hdr, || composite_stack_at(&doc.layers, &mut b, cx, advanced::Scope::ROOT)); - b - }) - }; - // Tiles are written straight into the output, one row of tiles (a band) at a time, so the - // peak is the output plus the tiles in flight, not a second full-size copy. - let w = rect.width() as usize; - let mut out = Buffer::transparent(rect); - let band_tiles = |y0: i32| { - let y1 = y0.saturating_add(tile).min(rect.y1); - let mut v = Vec::new(); - let mut x = rect.x0; - while x < rect.x1 { - let x1 = x.saturating_add(tile).min(rect.x1); - v.push(Rect::new(x, y0, x1, y1)); - x = x1; - } - v - }; - let put = |band: &mut [[f32; 4]], y0: i32, part: &Buffer| { - let pw = part.rect.width() as usize; - for (row, src) in part.px.chunks_exact(pw).enumerate() { - let o = ((part.rect.y0 - y0) as usize + row) * w + (part.rect.x0 - rect.x0) as usize; - band[o..o + pw].copy_from_slice(src); - } - }; - let band_len = w * tile as usize; - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - let bands = rect.height().div_ceil(tile as u32) as usize; - if bands >= 2 * rayon::current_num_threads() { - // Enough bands to keep every core busy: one band per task, its tiles in turn. - out.px.par_chunks_mut(band_len).enumerate().for_each(|(i, band)| { - let y0 = rect.y0 + i as i32 * tile; - for t in band_tiles(y0) { - put(band, y0, &run(t)); - } - }); - } else { - // Few, wide bands: the tiles of each band in parallel, and the bands too, so a band's - // slowest tile doesn't leave the other cores idle until the next band starts. Each - // tile is written as soon as it is done, so only the tiles in flight are held. - out.px.par_chunks_mut(band_len).enumerate().for_each(|(i, band)| { - let y0 = rect.y0 + i as i32 * tile; - let band = std::sync::Mutex::new(band); - band_tiles(y0).into_par_iter().for_each(|t| { - let part = run(t); - let mut band = band.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - put(&mut band, y0, &part); - }); - }); - } - } - #[cfg(target_arch = "wasm32")] - for (i, band) in out.px.chunks_mut(band_len).enumerate() { - let y0 = rect.y0 + i as i32 * tile; - for t in band_tiles(y0) { - put(band, y0, &run(t)); - } - } - out -} - -/// Runs `f` with this thread's document blend flags set ([`psblend::LAB_MIX`], [`psblend::HDR`]), -/// then restores the values they had (also on unwind): a nested rayon job can run another tile -/// on this thread mid-composite, and clearing the flags there broke the outer tile (#1112). -fn in_blend_space(lab: bool, hdr: bool, f: impl FnOnce() -> R) -> R { - psblend::with_lab_mix(lab, || psblend::with_hdr(hdr, f)) -} - -/// The document's own CMYK profile for reading its CMYK pixels (`None`: not a CMYK document, -/// untagged, or the built-in coated CMYK). Enter it with `photocraft_color::convert::with_cmyk_space` -/// around code that converts the document's CMYK pixels or colours to RGB. -pub fn cmyk_space(doc: &Document) -> Option> { - if doc.mode != photocraft_color::ColorMode::Cmyk { - return None; - } - photocraft_color::convert::CmykSpace::for_profile(doc.icc_profile.as_ref()) -} - -/// Pixels per band of [`render_bands`] (a 14000 px wide band is ~600 rows, ~130 MB of f32). -pub const BAND_PIXELS: u64 = 8 << 20; - -/// Composite `rect` in horizontal bands, top to bottom, handing each band to `sink` (tiles inside -/// a band render in parallel). Peak memory is one band instead of the whole composite, so huge -/// documents can be exported or displayed without a full-size float copy. `band_rows` of 0 picks -/// about [`BAND_PIXELS`] per band; bands are whole multiples of [`RENDER_TILE`] rows. -pub fn render_bands(doc: &Document, rect: Rect, band_rows: i32, mut sink: impl FnMut(Buffer) -> Result<(), E>) -> Result<(), E> { - if rect.is_empty() { - return Ok(()); - } - // Keep prepared pixels and compiled vector masks across bands without retaining any rendered band. - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - let cx = Ctx::for_doc(doc, &patterns); - let rows = band_rows_for(rect.width(), band_rows); - let mut y = rect.y0; - while y < rect.y1 { - let y1 = y.saturating_add(rows).min(rect.y1); - sink(render_tiled_with(doc, Rect::new(rect.x0, y, rect.x1, y1), RENDER_TILE, &cx))?; - y = y1; - } - Ok(()) -} - -/// Band height for [`render_bands`]: `requested` rounded up to whole tiles, or ~[`BAND_PIXELS`]. -pub fn band_rows_for(width: u32, requested: i32) -> i32 { - let want = if requested > 0 { i64::from(requested) } else { (BAND_PIXELS / u64::from(width.max(1))) as i64 }; - let tiles = (want + i64::from(RENDER_TILE) - 1) / i64::from(RENDER_TILE); - (tiles.clamp(1, 1 << 16) * i64::from(RENDER_TILE)) as i32 -} - -/// The document's composite as a pixel surface in `fmt` (straight RGBA converted to its model -/// and depth), optionally flattened over an opaque `background`; rendered and written in bands, -/// so no full-size float composite is held. Tiles equal to the default pixel are pruned. -/// -/// Fully transparent pixels are written as the default pixel. Converting transparent black -/// leaves colour behind in CMYK (K = 100%) and Lab (neutral a/b = 0.5), and those pixels would -/// otherwise count as content: the result would span the whole canvas. -/// -/// A CMYK document flattened to CMYK is composited in its ink values instead, so flattening -/// doesn't round-trip its pixels through RGB: plain Normal layers by [`native::flatten_cmyk`] -/// (#3778), and masks, groups, clipping, other blend modes and the other layer kinds by [`cmyk`] -/// where its layers mix on their inks (#2220). Otherwise the composite goes back to CMYK through -/// the document's own profile, the one its layers were read through. A Lab document of plain -/// layers is composited in its L, a and b ([`native_lab::flatten_lab`]). -pub fn flatten_to_surface(doc: &Document, fmt: photocraft_color::PixelFormat, background: Option<[f32; 3]>) -> Surface { - composite_to_surface(doc, doc.bounds(), fmt, background) -} - -/// [`flatten_to_surface`] over `rect` only (the rest of the surface stays empty). -pub fn composite_to_surface(doc: &Document, rect: Rect, fmt: photocraft_color::PixelFormat, background: Option<[f32; 3]>) -> Surface { - let paper = background.is_some_and(|bg| bg == [1.0; 3]); - if (background.is_none() || paper) - && let Some(s) = native::flatten_cmyk(doc, rect, fmt, paper) - { - return s; - } - if (background.is_none() || paper) - && let Some(s) = native_lab::flatten_lab(doc, rect, fmt, paper) - { - return s; - } - let space = cmyk_space(doc); - let to_cmyk = fmt.mode == photocraft_color::ColorMode::Cmyk && doc.mode == photocraft_color::ColorMode::Cmyk; - if to_cmyk && cmyk::renders_inks(doc) { - return composite_inks_to_surface(doc, rect, fmt, background, space.as_ref()); - } - // The composite separates back to CMYK through the document's own profile, the one its - // pixels were read through. - let mut s = Surface::new(fmt); - let n = fmt.channels(); - let empty = s.default_pixel(); - let mut data = Vec::new(); - let _ = render_bands(doc, rect, 0, |band| -> Result<(), ()> { - let band = match background { - Some(bg) => band.over_background(bg), - None => band, - }; - data.clear(); - data.resize(band.px.len() * n, 0.0); - photocraft_color::convert::with_cmyk_space(space.as_ref(), || { - for (p, out) in band.px.iter().zip(data.chunks_exact_mut(n)) { - if fmt.alpha && (p[3] <= 0.0 || p[3].is_nan()) && empty.len() == n { - out.copy_from_slice(&empty); - } else { - photocraft_raster::from_rgba_into(&fmt, *p, out); - } - } - }); - s.write_region(band.rect, &data); - Ok(()) - }); - s.prune(); - s -} - -/// One CMYK pixel's output channels into `data`: its inks (over `paper` when given) and alpha. -fn push_ink_pixel(data: &mut Vec, p: &[f32; 5], paper: Option<[f32; 4]>, fmt: photocraft_color::PixelFormat, empty: &[f32]) { - if paper.is_none() && fmt.alpha && (p[4] <= 0.0 || p[4].is_nan()) && empty.len() == fmt.channels() { - data.extend_from_slice(empty); - return; - } - // Over the paper (fully covered pixels keep their inks exactly), or straight. - let ink = |c: usize| match paper { - Some(bg) if p[4] < 1.0 => p[c] * p[4] + bg[c] * (1.0 - p[4]), - _ => p[c], - }; - data.extend((0..4).map(ink)); - if fmt.alpha { - data.push(if paper.is_some() { 1.0 } else { p[4] }); - } -} - -/// [`composite_to_surface`] for a CMYK document flattened to CMYK, composited in its inks. -fn composite_inks_to_surface( - doc: &Document, - rect: Rect, - fmt: photocraft_color::PixelFormat, - background: Option<[f32; 3]>, - space: Option<&std::sync::Arc>, -) -> Surface { - let mut s = Surface::new(fmt); - let n = fmt.channels(); - let empty = s.default_pixel(); - let mut data = Vec::new(); - // White paper is no ink; another background colour goes through the profile. - let paper = background - .map(|bg| if bg == [1.0; 3] { [0.0; 4] } else { photocraft_color::convert::with_cmyk_space(space, || photocraft_color::convert::rgb_to_cmyk(bg)) }); - let _ = cmyk::render_cmyk_bands(doc, rect, 0, |band| -> Result<(), ()> { - data.clear(); - data.reserve(band.px.len() * n); - for p in &band.px { - push_ink_pixel(&mut data, p, paper, fmt, &empty); - } - s.write_region(band.rect, &data); - Ok(()) - }); - s.prune(); - s -} - -/// Composite the full canvas. -pub fn flatten(doc: &Document) -> Buffer { - render(doc, doc.bounds()) -} - -/// Render an arbitrary subset: a single layer (e.g. for thumbnails), isolated. -/// Rects past [`MAX_RENDER_PIXELS`] give an empty buffer. -pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer { - if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS { - return Buffer::transparent(Rect::EMPTY); - } - let mut buf = Buffer::transparent(rect); - let patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES); - composite_stack_at( - std::slice::from_ref(layer), - &mut buf, - &Ctx { - canvas: rect, - transfer: adjust::Transfer::Srgb, - light: photocraft_doc::GlobalLight::default(), - patterns: &patterns, - mode: photocraft_color::ColorMode::Rgb, - depth: photocraft_color::SampleType::F32, - vector_masks: RenderVectorMasks::default(), - fx_maps: Default::default(), - fx_clip: Default::default(), - fx_over_budget: false, - tone_luts: prepare_tones(std::slice::from_ref(layer), 0), - doc: None, - layer_keys: Default::default(), - }, - advanced::Scope::ROOT, - ); - buf -} - -/// [`render_layer`] in `doc`'s context: the layer alone over `rect`, with the document's patterns, -/// Global Light, colour mode, depth and canvas (fill layers and gradients are laid out on it), as -/// the canvas composites it. Bakes (Scripts › Flatten All Layer Effects) render through this so -/// the pixels match what was on screen (#5719). Rects past [`MAX_RENDER_PIXELS`] give an empty -/// buffer. -pub fn render_layer_in(doc: &Document, layer: &Layer, rect: Rect) -> Buffer { - if rect.is_empty() { - return Buffer::transparent(rect); - } - if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS { - return Buffer::transparent(Rect::EMPTY); - } - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - // A lone layer: a deep knockout reveals transparency, not the document's Background. - let cx = Ctx { doc: None, ..Ctx::for_doc(doc, &patterns) }; - let lab = doc.mode == photocraft_color::ColorMode::Lab; - let hdr = doc.depth == photocraft_color::SampleType::F32; - let cmyk = cmyk_space(doc); - photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || { - let mut buf = Buffer::transparent(rect); - in_blend_space(lab, hdr, || composite_stack_at(std::slice::from_ref(layer), &mut buf, &cx, advanced::Scope::ROOT)); - buf - }) -} - -/// Documents above this many pixels get thumbnails from a proxy (see [`proxy`]) when that is -/// faithful; smaller ones are reduced from the exact composite. -pub const PROXY_THUMBNAIL_PIXELS: u64 = 16 << 20; - -/// Downscaled RGBA8 render of the document (area-averaged) for thumbnails, navigators and -/// histograms, at most `max_side` pixels on its longer side. Large documents are reduced from a -/// downsampled proxy (about twice the thumbnail's size), so a thumbnail of a 200 MP document -/// costs milliseconds and no full-size composite; the rest stream the exact composite in bands. -pub fn thumbnail(doc: &Document, max_side: u32) -> Rgba8Image { - thumbnail_buffer(doc, max_side).to_rgba8() -} - -/// Width and height of [`thumbnail`]`(doc, max_side)`. -pub fn thumbnail_size(doc: &Document, max_side: u32) -> (u32, u32) { - let b = doc.bounds(); - let longest = b.width().max(b.height()).max(1); - let scale = (max_side as f32 / longest as f32).min(1.0); - (((b.width() as f32 * scale).round() as u32).max(1), ((b.height() as f32 * scale).round() as u32).max(1)) -} - -/// [`thumbnail`] as straight-alpha floats (for callers that colour-convert it first). -pub fn thumbnail_buffer(doc: &Document, max_side: u32) -> Buffer { - let b = doc.bounds(); - let longest = b.width().max(b.height()).max(1); - let (w, h) = thumbnail_size(doc, max_side); - let k = longest / max_side.max(1).saturating_mul(2); - if k >= 2 && doc.size.area() > PROXY_THUMBNAIL_PIXELS && proxy::proxy_faithful(doc) { - render_reduced(&proxy::proxy_document(doc, k), w, h) - } else { - render_reduced(doc, w, h) - } -} - -/// The document's composite area-averaged (premultiplied) down to `w`×`h` (clamped to the -/// document size), rendered in bands so no full-size composite is held. -pub fn render_reduced(doc: &Document, w: u32, h: u32) -> Buffer { - render_reduced_in_bands(doc, doc.bounds(), w, h, None, 0) -} - -/// [`render_reduced`] of any area of the document plane, `rect`, which may lie past the canvas -/// (layer pixels there are kept until a crop deletes them). The buffer's rect is in output pixels -/// from (0, 0). -pub fn render_reduced_rect(doc: &Document, rect: Rect, w: u32, h: u32) -> Buffer { - render_reduced_in_bands(doc, rect, w, h, None, 0) -} - -/// The part of [`render_reduced`]`(doc, w, h)` that a change to `damage` (document pixels) can -/// affect: the output pixels whose source areas meet it, rendered from just those areas, with the -/// same values the whole reduction gives them. The buffer's rect is in output pixels (empty when -/// `damage` misses the document), so a reduced canvas texture can update only what a stroke touched. -pub fn render_reduced_damage(doc: &Document, w: u32, h: u32, damage: Rect) -> Buffer { - render_reduced_in_bands(doc, doc.bounds(), w, h, Some(damage), 0) -} - -/// [`render_reduced_rect`] (or, with `damage`, [`render_reduced_damage`]) of area `b` with an -/// explicit band height (see [`render_bands`]). -fn render_reduced_in_bands(doc: &Document, b: Rect, w: u32, h: u32, damage: Option, band_rows: i32) -> Buffer { - render_reduced_with(doc, b, w, h, damage, band_rows, true, &mut ReducedStats::default()) -} - -/// What a reduced render composited (tests check that one-colour areas are not composited). -#[derive(Debug, Default)] -struct ReducedStats { - /// Whether one-colour areas were looked for ([`uniform::UniformAreas`]). - uniform: bool, - /// Document pixels composited one by one. - composited: u64, -} - -/// A tile of a reduced render: one colour (premultiplied), or its composited pixels. -enum Part { - Solid([f32; 4]), - Px(Buffer), -} - -/// A column of document tiles in a reduced render (`b`-relative source columns). -struct TileColumn { - /// The columns rendered: the tile's, within the source area. - x0: usize, - x1: usize, - /// The whole tile's columns within `b`, whose values decide whether it is one colour. - whole: (i64, i64), - /// Runs of (output column, how many of the rendered columns it averages). - runs: Vec<(usize, f32)>, -} - -/// [`render_reduced_in_bands`]; `uniform` off composites every pixel (the reference in tests). -#[allow(clippy::too_many_arguments)] -fn render_reduced_with(doc: &Document, b: Rect, w: u32, h: u32, damage: Option, band_rows: i32, uniform: bool, stats: &mut ReducedStats) -> Buffer { - let (fw, fh) = (b.width() as usize, b.height() as usize); - let (w, h) = (w.clamp(1, b.width().max(1)) as usize, h.clamp(1, b.height().max(1)) as usize); - let full = Rect::from_xywh(0, 0, w as u32, h as u32); - if fw == 0 || fh == 0 { - return Buffer::transparent(if damage.is_some() { Rect::EMPTY } else { full }); - } - // Output column / row of each document column / row: output pixel t covers [t·f/n, (t+1)·f/n). - let span = |t: usize, f: usize, n: usize| (t * f / n, ((t + 1) * f / n).max(t * f / n + 1).min(f)); - // The output pixel whose span holds document column / row `x` (spans are contiguous: n <= f). - let cell = |x: usize, f: usize, n: usize| ((x + 1) * n).saturating_sub(1) / f; - // Output pixels to produce and the document area they cover. - let out = match damage { - None => full, - Some(d) => { - let d = d.intersect(&b); - if d.is_empty() { - return Buffer::transparent(Rect::EMPTY); - } - let (x0, x1) = ((d.x0 - b.x0) as usize, (d.x1 - b.x0) as usize); - let (y0, y1) = ((d.y0 - b.y0) as usize, (d.y1 - b.y0) as usize); - Rect::new(cell(x0, fw, w) as i32, cell(y0, fh, h) as i32, cell(x1 - 1, fw, w) as i32 + 1, cell(y1 - 1, fh, h) as i32 + 1) - } - }; - let (ox0, oy0, ow, oh) = (out.x0 as usize, out.y0 as usize, out.width() as usize, out.height() as usize); - let (sx0, sx1) = (span(ox0, fw, w).0, span(ox0 + ow - 1, fw, w).1); - let (sy0, sy1) = (span(oy0, fh, h).0, span(oy0 + oh - 1, fh, h).1); - let src = Rect::new(b.x0 + sx0 as i32, b.y0 + sy0 as i32, b.x0 + sx1 as i32, b.y0 + sy1 as i32); - if (w, h) == (fw, fh) { - let mut px = render(doc, src); - px.rect = out; - return px; - } - let map = |f: usize, n: usize| { - let mut m = vec![0u32; f]; - for t in 0..n { - let (a, z) = span(t, f, n); - m[a..z].fill(t as u32); - } - m - }; - let (cols, rows) = (map(fw, w), map(fh, h)); - let cols = &cols[sx0..sx1]; - let mut acc = vec![[0.0f32; 4]; ow * oh]; - // Each output row sums its source rows in a band (in order, top to bottom), each row's pixels - // left to right: `row(y, out)` adds source row `y` (band-relative) to output row `out`. - let sum_band = |acc: &mut [[f32; 4]], by0: usize, by1: usize, row: &(dyn Fn(usize, &mut [[f32; 4]]) + Sync)| { - let (t0, t1) = (rows[by0] as usize, rows[by1 - 1] as usize + 1); - let sum_row = |t: usize, out: &mut [[f32; 4]]| { - let (a, z) = span(t, fh, h); - for y in a.max(by0)..z.min(by1) { - row(y - by0, out); - } - }; - let part = &mut acc[(t0 - oy0) * ow..(t1 - oy0) * ow]; - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - part.par_chunks_mut(ow).enumerate().for_each(|(i, out)| sum_row(t0 + i, out)); - } - #[cfg(target_arch = "wasm32")] - for (i, out) in part.chunks_mut(ow).enumerate() { - sum_row(t0 + i, out); - } - }; - let add = |o: &mut [f32; 4], p: &[f32; 4]| { - for i in 0..3 { - o[i] += p[i] * p[3]; - } - o[3] += p[3]; - }; - if let Some(uniform) = uniform.then(|| uniform::UniformAreas::new(doc)).flatten() { - stats.uniform = true; - // One-colour tiles (a new document's background, the empty parts of a sparse one) are - // composited once per colour and summed per run of source columns, not per pixel - // (#4017). Tiles lie on the document's tile grid whatever `damage` is, so a damage - // render sums exactly what the whole reduction does. - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - let cx = Ctx::for_doc(doc, &patterns); - let t = RENDER_TILE as usize; - // The document tile grid (the surfaces' own), in `b`-relative coordinates: the start of - // the tile holding `v` (negative when `b` starts inside a tile). - let grid = |v: usize, o: i32| (i64::from(o) + v as i64).div_euclid(t as i64) * t as i64 - i64::from(o); - let tile_cols: Vec = (grid(sx0, b.x0)..sx1 as i64) - .step_by(t) - .map(|gx| { - let (x0, x1) = ((gx.max(0) as usize).max(sx0), ((gx + t as i64) as usize).min(sx1)); - let mut runs: Vec<(usize, f32)> = Vec::new(); - for &c in &cols[x0 - sx0..x1 - sx0] { - match runs.last_mut() { - Some((last, n)) if *last == c as usize - ox0 => *n += 1.0, - _ => runs.push((c as usize - ox0, 1.0)), - } - } - TileColumn { x0, x1, whole: (gx.max(0), (gx + t as i64).min(fw as i64)), runs } - }) - .collect(); - let band_h = band_rows_for(src.width(), band_rows).max(RENDER_TILE) as usize; - let mut y = grid(sy0, b.y0); - while y < sy1 as i64 { - let y1 = (y + band_h as i64).min(sy1 as i64); - let tiles: Vec<(Rect, Rect)> = (y..y1) - .step_by(t) - .flat_map(|gy| { - tile_cols.iter().map(move |&TileColumn { x0, x1, whole: (gx0, gx1), .. }| { - let at = |x0: i64, y0: i64, x1: i64, y1: i64| Rect::new(b.x0 + x0 as i32, b.y0 + y0 as i32, b.x0 + x1 as i32, b.y0 + y1 as i32); - let (gy0, gy1) = (gy.max(0), (gy + t as i64).min(fh as i64)); - (at(gx0, gy0, gx1, gy1), at(x0 as i64, gy0.max(sy0 as i64), x1 as i64, gy1.min(sy1 as i64))) - }) - }) - .collect(); - let one = |(whole, part): &(Rect, Rect)| -> Part { - let render = |r: Rect| render_tiled_with(doc, r, RENDER_TILE, &cx); - match uniform.color(*whole, |r| render(r).px.first().copied()) { - Some(p) => Part::Solid([p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]]), - None => Part::Px(render(*part)), - } - }; - #[cfg(not(target_arch = "wasm32"))] - let parts: Vec = { - use rayon::prelude::*; - tiles.par_iter().map(one).collect() - }; - #[cfg(target_arch = "wasm32")] - let parts: Vec = tiles.iter().map(one).collect(); - stats.composited += parts.iter().map(|p| if let Part::Px(b) = p { b.px.len() as u64 } else { 0 }).sum::(); - let (by0, by1) = (y.max(sy0 as i64) as usize, y1 as usize); - let n = tile_cols.len(); - let band_y = y; - sum_band(&mut acc, by0, by1, &|row: usize, out: &mut [[f32; 4]]| { - let y = (by0 + row) as i64; - let j = (y - band_y) as usize / t; - let ty = (y - (band_y + (j * t) as i64).max(sy0 as i64)) as usize; - for (TileColumn { x0, x1, runs, .. }, part) in tile_cols.iter().zip(parts.iter().skip(j * n).take(n)) { - match part { - Part::Solid(pa) => { - for &(c, k) in runs { - let o = &mut out[c]; - for i in 0..4 { - o[i] += pa[i] * k; - } - } - } - Part::Px(buf) => { - let tw = x1 - x0; - for (p, &c) in buf.px.iter().skip(ty * tw).take(tw).zip(&cols[x0 - sx0..x1 - sx0]) { - add(&mut out[c as usize - ox0], p); - } - } - } - } - }); - y = y1; - } - } else { - let ok: Result<(), ()> = render_bands(doc, src, band_rows, |band| { - stats.composited += band.px.len() as u64; - let (by0, by1) = ((band.rect.y0 - b.y0) as usize, (band.rect.y1 - b.y0) as usize); - let sw = sx1 - sx0; - sum_band(&mut acc, by0, by1, &|y: usize, out: &mut [[f32; 4]]| { - for (p, &c) in band.px[y * sw..(y + 1) * sw].iter().zip(cols) { - add(&mut out[c as usize - ox0], p); - } - }); - Ok(()) - }); - debug_assert!(ok.is_ok()); - } - let col_w: Vec = (0..ow) - .map(|x| { - let (x0, x1) = span(ox0 + x, fw, w); - (x1 - x0).max(1) - }) - .collect(); - let norm_row = |row: usize, out: &mut [[f32; 4]]| { - let (y0, y1) = span(oy0 + row, fh, h); - let rh = (y1 - y0).max(1); - for (p, &cw) in out.iter_mut().zip(&col_w) { - let a = p[3]; - if a > 0.0 { - let n = (rh * cw) as f32; - *p = [p[0] / a, p[1] / a, p[2] / a, a / n]; - } else { - *p = [0.0; 4]; - } - } - }; - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - acc.par_chunks_mut(ow).enumerate().for_each(|(row, out)| norm_row(row, out)); - } - #[cfg(target_arch = "wasm32")] - for (row, out) in acc.chunks_mut(ow).enumerate() { - norm_row(row, out); - } - Buffer { rect: out, px: acc } -} - -type VectorMaskSlot = std::sync::Arc>; - -#[derive(Default)] -struct RenderVectorMasks { - /// Compiled masks by content. Callers pass temporary clones (see `advanced.rs`), so an - /// address cannot identify a mask: a dropped clone's address is reused by the next one. - masks: std::sync::Mutex>, -} - -impl RenderVectorMasks { - fn values(&self, mask: &photocraft_doc::VectorMask, rect: Rect) -> Vec { - let slot = { - let mut masks = self.masks.lock().unwrap_or_else(|e| e.into_inner()); - match masks.iter().find(|(m, _)| m == mask) { - Some((_, slot)) => slot.clone(), - None => { - let slot = VectorMaskSlot::default(); - masks.push((mask.clone(), slot.clone())); - slot - } - } - }; - // Compilation is sequential. Rendering can enter Rayon and must happen after - // initialization, so waiting tiles cannot re-enter a slot still being built. - let compiled = slot.get_or_init(|| photocraft_vector::CompiledVectorMask::new(mask)); - compiled.render(rect) - } -} - -/// Rendering context shared down the tree. -struct Ctx<'a> { - /// Document canvas: fill layers and gradients are laid out relative to it, never to the render rect. - canvas: Rect, - /// Tone transfer used by adjustments that work in linear light. - transfer: adjust::Transfer, - /// Global light for layer effects. - light: photocraft_doc::GlobalLight, - /// Prepared document patterns, shared across all tiles and bands of this render call. - patterns: &'a pattern::PreparedPatterns<'a>, - /// The document's colour mode (channel restrictions name its channels). - mode: photocraft_color::ColorMode, - depth: photocraft_color::SampleType, - /// At most 1 MiB of tone tables, initialized once and shared by this render's tiles and bands. - tone_luts: Vec<(&'a photocraft_doc::Adjustment, std::sync::OnceLock<[Vec; 4]>)>, - vector_masks: RenderVectorMasks, - /// Effect maps used by this render, by cache key: built before the parallel tiles (see - /// [`prepare_effects`]) and held for the whole render (or band, for maps clipped to it: the - /// `bool`), so eviction can't force a rebuild. - fx_maps: std::sync::Mutex, bool)>>, - /// The rectangle being rendered (a band of [`render_bands`]); see [`effect_region`]. - fx_clip: std::sync::Mutex>, - /// The whole-region effect maps of this render's layers wouldn't fit in the effect cache - /// together ([`fx_over_budget`]), so local ones are clipped to the render rect (#8330). - fx_over_budget: bool, - /// The document being rendered (deep knockouts reveal its Background); `None` for a lone layer. - doc: Option<&'a Document>, - /// Effect-map identities of this render's document layers (see [`LayerKeys`]). - layer_keys: LayerKeys, -} - -/// Memo of [`layer_identity`] for the layers of the document being rendered. The identity depends -/// on the layer alone, not on the tile, so it is computed once per layer per render instead of -/// once per tile. Only layers that sit in the document tree are memoised by address: the document -/// is borrowed for the whole render, so no other object can live at such an address. Temporary -/// copies (`advanced::effects_source`) are never in the tree and always take the full path. -#[derive(Default)] -struct LayerKeys { - /// Addresses of every layer in the document tree, collected on first use. - in_doc: std::sync::OnceLock>, - ids: std::sync::Mutex>, - /// Identities computed (tests count them). - #[cfg(test)] - built: std::sync::atomic::AtomicUsize, -} - -impl LayerKeys { - fn identity(&self, layer: &Layer, doc: Option<&Document>) -> u64 { - let addr = std::ptr::from_ref(layer) as usize; - let in_doc = doc.is_some_and(|d| self.in_doc.get_or_init(|| doc_layer_addresses(d)).contains(&addr)); - if in_doc { - let mut ids = self.ids.lock().unwrap_or_else(|e| e.into_inner()); - // Computing an identity only hashes immutable layer data; it does not run Rayon - // work or re-enter this memo. Keep the miss and insertion atomic across callers. - *ids.entry(addr).or_insert_with(|| self.compute(layer)) - } else { - self.compute(layer) - } - } - - fn compute(&self, layer: &Layer) -> u64 { - use std::hash::Hasher; - #[cfg(test)] - self.built.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let mut h = std::collections::hash_map::DefaultHasher::new(); - layer_identity(layer, &mut h, &mut |_| {}); - h.finish() - } -} - -/// Addresses of all layers of `doc` (groups' children included). -fn doc_layer_addresses(doc: &Document) -> std::collections::HashSet { - let mut out = std::collections::HashSet::new(); - let mut todo: Vec<&Layer> = doc.layers.iter().collect(); - while let Some(l) = todo.pop() { - out.insert(std::ptr::from_ref(l) as usize); - if let LayerContent::Group(g) = &l.content { - todo.extend(g.children.iter()); - } - } - out -} - -impl<'a> Ctx<'a> { - fn for_doc(doc: &'a Document, patterns: &'a pattern::PreparedPatterns<'a>) -> Self { - Self { - doc: Some(doc), - canvas: doc.bounds(), - transfer: adjust::Transfer::for_document(doc.mode, doc.depth), - light: doc.global_light, - patterns, - mode: doc.mode, - depth: doc.depth, - vector_masks: RenderVectorMasks::default(), - fx_maps: Default::default(), - fx_clip: Default::default(), - fx_over_budget: fx_over_budget(&doc.layers, doc.bounds()), - layer_keys: Default::default(), - tone_luts: prepare_tones(&doc.layers, 0), - } - } - - /// Start rendering `rect`: effect maps clipped to the previous rectangle are let go. - fn set_fx_clip(&self, rect: Rect) { - let mut clip = self.fx_clip.lock().unwrap_or_else(|e| e.into_inner()); - if *clip != Some(rect) { - *clip = Some(rect); - self.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, (_, clipped)| !*clipped); - } - } - - fn apply_adjustment(&self, adj: &photocraft_doc::Adjustment, buf: &mut Buffer) { - if let photocraft_doc::Adjustment::Levels { space, .. } | photocraft_doc::Adjustment::Curves { space, .. } = adj - && !matches!(adj, photocraft_doc::Adjustment::Levels { space: photocraft_doc::adjust::ToneSpace::Rgb, .. } if self.depth == photocraft_color::SampleType::F32) - && let Some((_, luts)) = self.tone_luts.iter().find(|(a, _)| std::ptr::eq(*a, adj)) - { - let identity = adjust::float_tone_identity(adj, Some(self.depth)); - if identity == [true; 3] { - return; - } - let extrapolate = adjust::float_tone_extrapolates(adj, Some(self.depth), self.mode); - adjust::apply_tone(buf, *space, luts.get_or_init(|| adjust::tone_luts_depth(adj, Some(self.depth))), identity, extrapolate); - } else { - adjust::apply_in(adj, buf, self.transfer, Some(self.depth), self.mode); - } - } -} - -fn prepare_tones(layers: &[Layer], depth: u32) -> Vec<(&photocraft_doc::Adjustment, std::sync::OnceLock<[Vec; 4]>)> { - let mut out = Vec::new(); - for layer in layers.iter().filter(|l| l.visible) { - if out.len() == 16 { - break; - } - match &layer.content { - LayerContent::Adjustment(a @ (photocraft_doc::Adjustment::Levels { .. } | photocraft_doc::Adjustment::Curves { .. })) => { - out.push((a, Default::default())) - } - LayerContent::Group(g) if depth < PREPARE_DEPTH => out.extend(prepare_tones(&g.children, depth + 1).into_iter().take(16 - out.len())), - _ => {} - } - } - out -} - -/// Deepest group nesting preparation walks (deeper layers prepare on demand). -const PREPARE_DEPTH: u32 = 64; - -/// Build the effect maps of every visible layer in `layers` (groups included) that can reach -/// `rect` before tiles render in parallel, layers concurrently on native targets, each build -/// inside `setting` (the tiles' thread-local colour setting). Tiles then only read finished maps: -/// none builds one while others need it (#276), and none duplicates another's build. Builds never -/// wait on each other (`cached_effect_maps`), so building them in parallel can't deadlock. -fn prepare_effects(layers: &[Layer], rect: Rect, cx: &Ctx, setting: impl Fn(&mut dyn FnMut()) + Sync) { - let mut todo = Vec::new(); - effect_layers(layers, rect, 0, &mut todo); - let build = |l: &std::borrow::Cow| { - setting(&mut || { - let _ = effect_maps(l, rect, cx); - }); - }; - #[cfg(not(target_arch = "wasm32"))] - if todo.len() > 1 { - use rayon::prelude::*; - todo.par_iter().for_each(build); - return; - } - todo.iter().for_each(build); -} - -/// The visible layers of `layers` (groups included) with effects that can reach `rect`. -fn effect_layers<'l>(layers: &'l [Layer], rect: Rect, depth: u32, out: &mut Vec>) { - let mut base_visible = true; - for l in layers { - if !l.clipped { - base_visible = l.visible; - } - // A clipping group is drawn only when its base is. - if !l.visible || !base_visible { - continue; - } - if effects::has_effects(l) && !empty_in(l, rect) { - // A mask that hides the effects is left out of the shape they are built from. - out.push(advanced::effects_source(l)); - } - if let LayerContent::Group(g) = &l.content - && depth < PREPARE_DEPTH - { - effect_layers(&g.children, rect, depth + 1, out); - } - } -} - -/// Composite an isolated group's sibling list (bottom→top) onto `backdrop` (its own buffer). -fn composite_stack(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx) { - composite_stack_at(layers, backdrop, cx, advanced::Scope::ISOLATED); -} - -/// Composite a sibling list (bottom→top) onto `backdrop`; `scope` says where the stack sits (see -/// [`advanced::Scope`]: it decides what knockouts reveal). -fn composite_stack_at(layers: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { - // Shallow knockouts stop at the bottom of this stack: the backdrop it starts from. - let floor = (!scope.root && advanced::needs_floor(layers)).then(|| backdrop.clone()); - let mut i = 0; - while i < layers.len() { - let base = &layers[i]; - // Collect the clipping group: following layers with `clipped = true`. - let mut j = i + 1; - while j < layers.len() && layers[j].clipped && !base.clipped { - j += 1; - } - let clipped = &layers[i + 1..j]; - if base.visible { - let ko = advanced::knockout_target(base, floor.as_ref(), backdrop.rect, cx, scope); - composite_layer(base, clipped, backdrop, cx, ko.as_deref(), scope); - if let (LayerContent::Adjustment(_), Some(q)) = (&base.content, adjustment_quantum(cx.depth)) { - quantize(backdrop, q); - } - } - i = j.max(i + 1); - } -} - -/// Steps per unit of an integer document's samples: Photoshop applies adjustment layers to -/// buffers of the document's depth (8-bit: 255 levels, 16-bit: 32768), so their result is -/// rounded there; a steep curve then amplifies the rounding of its input exactly as in -/// Photoshop (psd-tools adjustment_nested_composition_4: 9.6 → 5.1 % of pixels off; -/// exposure_grayscale passes). Blends stay in float (quantising them too made other files -/// worse). -pub fn adjustment_quantum(depth: photocraft_color::SampleType) -> Option { - match depth { - photocraft_color::SampleType::U8 => Some(255.0), - photocraft_color::SampleType::U16 => Some(32768.0), - photocraft_color::SampleType::F32 => None, - } -} - -fn quantize(b: &mut Buffer, q: f32) { - for p in &mut b.px { - for v in p.iter_mut() { - *v = branchless_floor(*v * q + 0.5) / q; - } - } -} - -/// `x.floor()`, bit for bit (signed zeros, infinities and NaNs included), without a call: baseline -/// x86-64 has no SSE4.1 `roundss`, so `floor` is a software routine there, called once per sample -/// of the backdrop under every adjustment layer ([`quantize`]). This form has no branch, so the -/// loop vectorizes. -#[inline] -fn branchless_floor(x: f32) -> f32 { - // From 2^23 on every f32 is whole. Below it, adding and taking away 2^23 rounds to the - // nearest whole number; where that went up, step down. - const WHOLE: f32 = 8_388_608.0; - let a = x.abs(); - let r = ((a + WHOLE) - WHOLE).copysign(x); - let r = if r > x { r - 1.0 } else { r }; - if a < WHOLE { r } else { x } -} - -/// Blend an adjustment layer's result (`adjusted`) back into the backdrop it was made from, each -/// pixel by its coverage `ks` (opacity × mask) in blend mode `mode`. -fn blend_back(backdrop: &mut [[f32; 4]], adjusted: &[[f32; 4]], ks: impl Iterator, mode: BlendMode) { - for ((b, a), k) in backdrop.iter_mut().zip(adjusted).zip(ks) { - if k <= 0.0 { - continue; - } - let s = [a[0], a[1], a[2]]; - // Normal is the source as it is (`blend_rgb` gives exactly that), and most adjustment - // layers are Normal: no per-pixel mode dispatch for them. - let blended = if mode == BlendMode::Normal { s } else { blend::blend_rgb(mode, [b[0], b[1], b[2]], s) }; - *b = [b[0] + (blended[0] - b[0]) * k, b[1] + (blended[1] - b[1]) * k, b[2] + (blended[2] - b[2]) * k, b[3]]; - } -} - -/// Deterministic hash for Dissolve (document-coordinate based, so it is stable under tiling). -#[inline] -fn dissolve_noise(x: i32, y: i32) -> f32 { - let mut h = (x as u32).wrapping_mul(0x8da6_b343) ^ (y as u32).wrapping_mul(0xd816_3841) ^ 0x9e37_79b9; - h ^= h >> 15; - h = h.wrapping_mul(0x2c1b_3c6d); - h ^= h >> 12; - (h & 0xffff) as f32 / 65536.0 -} - -/// Bounds of a layer's own pixels (union over group children; the canvas -/// for fill layers; an artboard's board). -pub fn layer_bounds(layer: &Layer, canvas: Rect) -> Rect { - // Transparency Shapes Layer off: effects and knockout cover the whole layer (the canvas). - if advanced::shapeless(layer) { - return canvas; - } - match &layer.content { - LayerContent::Group(g) if g.artboard.is_some() => g.artboard.as_ref().map_or(Rect::EMPTY, |a| a.rect), - LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).fold(Rect::EMPTY, |acc, c| { - let b = layer_bounds(c, canvas); - if b.is_empty() { - acc - } else if acc.is_empty() { - b - } else { - acc.union(&b) - } - }), - LayerContent::Fill(_) => canvas, - _ => { - let b = layer.surface().map_or(Rect::EMPTY, bounds::content_bounds); - let b = match &layer.content { - LayerContent::Shape(sh) => { - let p = shape_bounds(sh).map(|r| r.intersect(&canvas)).unwrap_or(Rect::EMPTY); - if !b.is_empty() && !p.is_empty() { - b.union(&p) - } else if !p.is_empty() { - p - } else { - b - } - } - _ => b, - }; - // Effects follow a filled shape's outline, also where its fill is transparent. - match effect_outline(layer).and_then(|_| paint_bounds(layer)).filter(|_| effects::has_effects(layer)) { - Some(p) if !b.is_empty() => b.union(&p), - Some(p) => p, - None => b, - } - } - } -} - -/// Where a layer's effects take their shape from: [`layer_bounds`], except that a group's -/// children count with their own effects (a child's outside stroke shapes the group's drop -/// shadow and must not be cut off at the child's pixels, #3274). -pub fn effect_source_bounds(layer: &Layer, canvas: Rect) -> Rect { - match &layer.content { - LayerContent::Group(g) if g.artboard.is_none() && !advanced::shapeless(layer) => g.children.iter().filter(|c| c.visible).fold(Rect::EMPTY, |acc, c| { - let m = if effects::has_effects(c) { effects::margin(c) } else { 0 }; - let b = effect_source_bounds(c, canvas); - let b = if b.is_empty() { b } else { b.inflate(m) }; - if b.is_empty() { - acc - } else if acc.is_empty() { - b - } else { - acc.union(&b) - } - }), - _ => layer_bounds(layer, canvas), - } -} - -/// The path a shape layer's effects are shaped by: its fill path. Photoshop builds a filled -/// shape's layer effects from its vector outline, not from its pixels: a stroke runs along the -/// whole path even where a gradient fill fades out (psd-tools stroke-effects). `None` for other -/// layers, shapes without fill, empty and inverted paths, and shapes whose vector stroke reaches -/// past the path (their pixels give the outline: psd-tools double-stroke-effects), and shapes -/// with a density or feather. -pub fn effect_outline(layer: &Layer) -> Option<&photocraft_doc::vector::Path> { - let LayerContent::Shape(sh) = &layer.content else { return None }; - let stroke_inside = sh.stroke.as_ref().is_none_or(|s| s.width <= 0.0 || s.align == photocraft_doc::vector::StrokeAlign::Inside); - // A soft (feathered or less dense) fill's own alpha is its outline. - (sh.fill.is_some() && stroke_inside && !sh.path.is_empty() && !sh.path.inverted && !sh.has_soft_mask()).then_some(&sh.path) -} - -/// The shape a layer's effects are built from over `rect` (row-major): its content's alpha -/// (masks applied), completed for shapes with an [`effect_outline`] by the outline's coverage -/// where the fill is see-through. With `l` the alpha and `f` the fill's own opacity (the largest -/// alpha around), the shape is `l + (1 - f) × coverage`: Photoshop's own rasterization where the -/// fill is opaque (it can differ from ours by a fraction of a pixel: psd-tools shape-fx2), the -/// path where the fill fades out (psd-tools stroke-effects). -fn effect_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec { - let n = rect.width() as usize * rect.height() as usize; - // Transparency Shapes Layer off: the effects take the whole layer as their shape (its masks - // still apply). - if !layer.advanced.transparency_shapes { - return mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n]); - } - let Some(path) = effect_outline(layer).filter(|_| n > 0) else { - return render_content(layer, rect, cx).map(|b| b.px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; n]); - }; - // Unmasked: the masks scale the shape, they aren't the fill's transparency. - let a: Vec = layer.surface().map(|s| surface_to_buffer(s, rect).px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; n]); - let cov = photocraft_vector::path_coverage(path, rect); - let mv = mask_vals(layer, rect, cx); - let (w, h) = (rect.width() as usize, rect.height() as usize); - let mut out = vec![0.0; n]; - for y in 0..h { - for x in 0..w { - let i = y * w + x; - // A pixel the outline covers is inside, whatever the fill's opacity. - let v = if cov[i] >= 1.0 - 1e-3 { - 1.0 - } else { - let mut f = 0.0f32; - for yy in y.saturating_sub(1)..(y + 2).min(h) { - for xx in x.saturating_sub(1)..(x + 2).min(w) { - f = f.max(a[yy * w + xx]); - } - } - (a[i] + (1.0 - f.min(1.0)) * cov[i]).clamp(0.0, 1.0) - }; - out[i] = v * mask_k(&mv, i); - } - } - out -} - -/// The frame layer-effect gradients and linked patterns are laid out in, when it isn't the -/// layer's pixel bounds: a shape layer's path bounds, truncated to whole pixels. Its rendered -/// pixels can extend past the path (transparent anti-aliasing margin), which Photoshop ignores: -/// psd-tools shape-fx2's 45° overlay spans the 0.92–29.61 path as 0–29 (29 px, centred at 14.5), -/// not the 32 px of pixels. -pub fn paint_bounds(layer: &Layer) -> Option { - let LayerContent::Shape(sh) = &layer.content else { return None }; - let (x0, y0, x1, y1) = sh.path.control_bounds()?; - let r = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.floor() as i32, y1.floor() as i32); - (!r.is_empty()).then_some(r) -} - -/// The frame a layer's effects are laid out in: [`paint_bounds`] for a shape, else the layer's -/// bounds ([`layer_bounds`]). A Gradient Overlay spans it, linked patterns tile from its corner. -pub fn effects_frame(layer: &Layer, canvas: Rect) -> Rect { - paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, canvas)) -} - -/// The pixels a change from `a` to `b` repaints beyond those it changed: where a layer whose -/// effects span its frame ([`effects::spans_frame`]) moved that frame, the layer's whole composite -/// before and after. Painting on a layer with a Gradient Overlay lays the one gradient out again -/// over the grown layer, as Photoshop does after each stroke; damage that covers only the stroke -/// leaves the old gradient around earlier strokes (#4053). Empty when no such frame moved. -pub fn relayout_damage(a: &Document, b: &Document) -> Rect { - let mut out = Rect::EMPTY; - let mut add = |r: Rect| { - if !r.is_empty() { - out = if out.is_empty() { r } else { out.union(&r) }; - } - }; - for (_, _, y) in b.walk() { - if !y.visible || !effects::spans_frame(y) { - continue; - } - let Some(x) = a.layer(y.id) else { continue }; - if effects_frame(x, a.bounds()) == effects_frame(y, b.bounds()) { - continue; - } - add(change_bounds(x, a.bounds()).unwrap_or_else(|| a.bounds())); - add(change_bounds(y, b.bounds()).unwrap_or_else(|| b.bounds())); - } - out -} - -/// The bounding box of a shape layer's path and stroke, ignoring its Density and Feather: its -/// path control bounds plus stroke width (a conservative reach for any alignment, cap and join). -pub fn hard_shape_bounds(sh: &photocraft_doc::ShapeLayer) -> Option { - if sh.fill.is_none() && sh.stroke.as_ref().is_none_or(|s| s.width <= 0.0 || s.opacity <= 0.0) { - return None; - } - let (x0, y0, x1, y1) = sh.path.control_bounds()?; - let stroke_margin = sh.stroke.as_ref().filter(|s| s.opacity > 0.0).map_or(0.0, |s| s.width.ceil()) as i32; - let r = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32).inflate(stroke_margin); - (!r.is_empty()).then_some(r) -} - -/// The frame Free Transform, the Move tool's transform controls, snapping and Properties show for -/// a soft shape (Density below 100 % or a Feather), whose rendering reaches past its path: the -/// pixels the same shape renders in `format` over `canvas` at full Density without Feather, so -/// the frame is exactly the hard shape's whatever the stroke's alignment, cap and join (in -/// Photoshop a shape's transform frame follows its path and stroke whatever its mask Density and -/// Feather, #5846). An inverted path's frame is its own outline, not the whole canvas. Renders -/// only the strips along the edges of the rasterizers' (1 px conservative) bounds. -pub fn soft_shape_frame(sh: &photocraft_doc::ShapeLayer, format: photocraft_color::PixelFormat, canvas: Rect) -> Option { - let mut path = sh.path.clone(); - path.inverted = false; - let hard = photocraft_doc::ShapeLayer { density: 1.0, feather: 0.0, path, fill: sh.fill.clone(), stroke: sh.stroke.clone(), ..Default::default() }; - let shape = photocraft_vector::CompiledShape::new(&hard, photocraft_vector::DEFAULT_TOLERANCE, canvas); - let r = shape.bounds()?.intersect(&canvas); - trim_to_painted(r, |strip| shape.render(format, strip).content_bounds()) -} - -/// `r` shrunk to the pixels `painted` reports (the painted bounds within a strip of `r`, empty if -/// none), looking in from each edge through strips that double in thickness: a few renders per -/// edge however wide the empty margin (a subtracted or intersected subpath can leave most of the -/// rasterizers' bounds empty), and none of `r`'s inside rendered at once. -fn trim_to_painted(mut r: Rect, mut painted: impl FnMut(Rect) -> Rect) -> Option { - // Top: the first strip holding paint gives the first painted row. - let mut t = 1; - while !r.is_empty() { - let strip = Rect::new(r.x0, r.y0, r.x1, r.y0.saturating_add(t).min(r.y1)); - let p = painted(strip).intersect(&strip); - if !p.is_empty() { - r.y0 = p.y0; - break; - } - r.y0 = strip.y1; - t = t.saturating_mul(2); - } - let mut t = 1; - while !r.is_empty() { - let strip = Rect::new(r.x0, r.y1.saturating_sub(t).max(r.y0), r.x1, r.y1); - let p = painted(strip).intersect(&strip); - if !p.is_empty() { - r.y1 = p.y1; - break; - } - r.y1 = strip.y0; - t = t.saturating_mul(2); - } - let mut t = 1; - while !r.is_empty() { - let strip = Rect::new(r.x0, r.y0, r.x0.saturating_add(t).min(r.x1), r.y1); - let p = painted(strip).intersect(&strip); - if !p.is_empty() { - r.x0 = p.x0; - break; - } - r.x0 = strip.x1; - t = t.saturating_mul(2); - } - let mut t = 1; - while !r.is_empty() { - let strip = Rect::new(r.x1.saturating_sub(t).max(r.x0), r.y0, r.x1, r.y1); - let p = painted(strip).intersect(&strip); - if !p.is_empty() { - r.x1 = p.x1; - break; - } - r.x1 = strip.x0; - t = t.saturating_mul(2); - } - (!r.is_empty()).then_some(r) -} - -/// The bounding box of a shape layer's vector content: its path control bounds plus stroke width -/// (and the reach of a soft fill). -pub fn shape_bounds(sh: &photocraft_doc::ShapeLayer) -> Option { - let r = hard_shape_bounds(sh)?; - // A soft fill reaches past the path: by its feather, or everywhere below 100 % density. - if sh.fill.is_some() && sh.has_soft_mask() { - if sh.density.is_finite() && sh.density < 1.0 { - return Some(Rect::new(i32::MIN / 4, i32::MIN / 4, i32::MAX / 4, i32::MAX / 4)); - } - return Some(r.union(&photocraft_vector::feather::path_area(&sh.path, masks::feather_sigma(sh.feather)))); - } - Some(r) -} - -/// The layer's effective mask over `rect` (row-major), read once per tile: the pixel mask -/// times the rasterized vector mask. -fn mask_vals(layer: &Layer, rect: Rect, cx: &Ctx) -> Option> { - // Feathers blur across tiles: read the cached, canvas-wide combined mask. - if masks::has_feather(layer) - && let Some(s) = masks::combined_mask(layer, cx.canvas) - { - let mut v = Vec::new(); - s.read_region_into(rect, &mut v); - return Some(v); - } - let vector = layer.vector_mask.as_ref().map(|vm| cx.vector_masks.values(vm, rect)); - let Some(m) = layer.mask.as_ref() else { return vector }; - let mut v = Vec::new(); - m.values_into(rect, &mut v); - if let Some(vm) = vector { - for (a, b) in v.iter_mut().zip(vm) { - *a *= b; - } - } - Some(v) -} - -#[inline] -fn mask_k(m: &Option>, i: usize) -> f32 { - m.as_ref().map_or(1.0, |v| v[i]) -} - -/// Render a layer's own content (no blending into the backdrop yet) into an isolated buffer. -/// Returns None for layers that operate on the backdrop (adjustments, pass-through groups). -fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option { - let mut buf = match &layer.content { - LayerContent::Group(g) => { - let mut b = Buffer::transparent(rect); - composite_stack(&g.children, &mut b, cx); - b - } - LayerContent::Fill(f) => match &layer.fill_cache { - // Photoshop's own rendering, valid while the fill is unchanged. - Some(c) if c.fill == *f => surface_to_scratch(&c.surface, rect), - _ if cx.mode == photocraft_color::ColorMode::Cmyk => { - let frame = fill_frame(layer, cx.canvas); - let native_rect = if matches!(f, Fill::Solid(_)) { Rect::new(0, 0, 1, 1) } else { rect }; - match gradient_fill::render_cmyk_fill(f, native_rect, frame, cx.depth) { - Some(s) if matches!(f, Fill::Solid(_)) => Buffer::filled(rect, s.rgba(0, 0)), - Some(s) => surface_to_buffer(&s, rect), - None => render_fill(f, rect, frame, cx.patterns, adjustment_quantum(cx.depth)), - } - } - _ => render_fill(f, rect, fill_frame(layer, cx.canvas), cx.patterns, adjustment_quantum(cx.depth)), - }, - LayerContent::Adjustment(_) => return None, - _ => match layer.surface() { - Some(s) => surface_to_scratch(s, rect), - None => Buffer::transparent(rect), - }, - }; - if let Some(m) = mask_vals(layer, rect, cx) { - for (p, k) in buf.px.iter_mut().zip(&m) { - p[3] *= k; - } - } - Some(buf) -} - -/// The shape `layer`'s effect maps are built from over `rect` (row-major; for the GPU -/// compositor): its content's alpha (masks applied), joined with the [`effect_outline`] of a -/// filled shape. Zero for adjustment layers. -/// -/// See also [`stroke_frame`]. -pub fn layer_shape(doc: &Document, layer: &Layer, rect: Rect) -> Vec { - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - let cx = Ctx::for_doc(doc, &patterns); - effect_shape(layer, rect, &cx) -} - -/// The frame a gradient stroke `st` of `layer` is laid out in (`effects::FxMaps::stroke_frame`), -/// from the layer's cached effect maps; `None` when `st` isn't a gradient stroke of the layer. -/// For the GPU compositor. -pub fn stroke_frame(doc: &Document, layer: &Layer, st: &photocraft_doc::StrokeFx) -> Option { - if !matches!(st.paint, photocraft_doc::FxPaint::Gradient(_)) || !effects::has_effects(layer) { - return None; - } - let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); - let cx = Ctx::for_doc(doc, &patterns); - effect_maps(layer, doc.bounds(), &cx).stroke_frame(st) -} - -pub fn surface_to_buffer(s: &Surface, rect: Rect) -> Buffer { - let mut px = vec![[0.0f32; 4]; rect.width() as usize * rect.height() as usize]; - s.read_rgba_into(rect, &mut px); - Buffer { rect, px } -} - -fn surface_to_scratch(s: &Surface, rect: Rect) -> Buffer { - let mut buf = scratch_buffer(rect); - s.read_rgba_into(rect, &mut buf.px); - buf -} - -/// The frame a fill layer's gradient is laid out in ("Align with layer", Photoshop's default): -/// the layer's bounds, i.e. the area its masks reveal: a hide-all pixel mask's painted area, or -/// the vector mask's path; otherwise the canvas. -pub fn fill_frame(layer: &Layer, canvas: Rect) -> Rect { - let mut frame = canvas; - // "Align with layer" off: the canvas (the Gradient tool's live gradients). - if let LayerContent::Fill(Fill::Gradient { align: false, .. }) = &layer.content { - return frame; - } - if let Some(m) = &layer.mask - && m.enabled - && m.surface.default_pixel().first().is_some_and(|v| *v <= 0.0) - { - let b = bounds::content_bounds(&m.surface).intersect(&canvas); - if !b.is_empty() { - frame = b; - } - } - if let Some(vm) = &layer.vector_mask - && vm.enabled - && !vm.path.inverted - && let Some((x0, y0, x1, y1)) = vm.path.control_bounds() - { - let b = Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32).intersect(&frame); - if !b.is_empty() { - frame = b; - } - } - frame -} - -/// A fill layer's content over `canvas`, laid out in the frame its masks give it (as the -/// compositor does) but without applying the masks: the pixels a PSD fill layer stores. -pub fn render_fill_content(layer: &Layer, f: &Fill, canvas: Rect, patterns: &[Pattern]) -> Buffer { - let prepared = pattern::PreparedPatterns::new(patterns, pattern::PREPARED_PATTERN_BYTES); - render_fill(f, canvas, fill_frame(layer, canvas), &prepared, None) -} - -/// `quantum`: the document depth's levels, which a dithered gradient is rounded to -/// ([`gradient_fill::render_quantized`]); `None` keeps it in float. -fn render_fill(f: &Fill, rect: Rect, canvas: Rect, patterns: &pattern::PreparedPatterns<'_>, quantum: Option) -> Buffer { - match f { - Fill::Solid(c) => { - let rgb = c.to_rgb(); - Buffer::filled(rect, [rgb[0], rgb[1], rgb[2], c.alpha]) - } - // Gradient geometry relative to the layer's frame, independent of the render rect. - Fill::Gradient { .. } => Buffer { rect, px: gradient_fill::render_quantized(f, rect, canvas, quantum) }, - // Laid out from the layer's frame when linked; transparent if the pattern is missing. - Fill::Pattern { name, scale, id, angle, link, phase } => match patterns.get(id, name) { - Some(tile) => Buffer { rect, px: pattern::render(&tile, &pattern::Placement::new(canvas, *link, *phase, *scale, *angle), rect) }, - None => Buffer::transparent(rect), - }, - } -} - -/// `true` when a pixel-backed layer has nothing to contribute in `rect`: -/// no allocated tiles there, a transparent default, and no effects (which -/// could reach in from outside). Clipped layers depend on the base, so they -/// vanish with it. -fn empty_in(layer: &Layer, rect: Rect) -> bool { - if effects::has_effects(layer) { - // Effects reach at most `margin` beyond the layer's pixels (when it is transparent - // outside them; a group's from its children with their effects): render tiles away from a - // small text layer skip it entirely. - let canvas = Rect::new(i32::MIN / 4, i32::MIN / 4, i32::MAX / 4, i32::MAX / 4); - let bounds = shapeless_stroke_bounds(layer).unwrap_or_else(|| effect_source_bounds(layer, canvas)); - return transparent_outside(layer) && bounds.inflate(effects::margin(layer)).intersect(&rect).is_empty(); - } - match &layer.content { - LayerContent::Raster(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_) => match layer.surface() { - Some(s) => !s.has_tiles_in(rect) && s.default_pixel().last().is_some_and(|a| *a <= 0.0) && s.format().alpha, - None => true, - }, - _ => false, - } -} - -/// For the narrow `tsly=0` case where only local stroke effects are enabled, the effects cannot -/// contribute outside the stroke reach from the layer's pixels. Other `tsly=0` effects can cover -/// the full layer, and advanced blending can change the backdrop independently of those pixels. -fn shapeless_stroke_bounds(layer: &Layer) -> Option { - use photocraft_doc::Knockout; - - if layer.advanced.transparency_shapes - || layer.advanced.knockout != Knockout::None - || layer.advanced.blend_interior - || layer.clipped - || !layer.blend_if.is_default() - || layer.mask.as_ref().is_some_and(|m| m.enabled) - || layer.vector_mask.as_ref().is_some_and(|m| m.enabled) - || !transparent_outside(layer) - || !effects::maps_are_local(layer) - { - return None; - } - - if !layer.effects.enabled - || !layer.effects.items.iter().any(|e| e.enabled()) - || layer.effects.items.iter().any(|e| e.enabled() && !matches!(e, photocraft_doc::Effect::Stroke(_))) - { - return None; - } - - match &layer.content { - LayerContent::Raster(_) | LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Smart(_) => { - let b = layer.surface().map_or(Rect::EMPTY, bounds::content_bounds); - // A filled shape's effects follow its outline, also where its fill is transparent (as - // in `layer_bounds`). - Some(match effect_outline(layer).and_then(|_| paint_bounds(layer)) { - Some(p) if !b.is_empty() => b.union(&p), - Some(p) => p, - None => b, - }) - } - _ => None, - } -} - -/// Blending Options › Channels as per-channel weights over display RGB (1 = the layer's result, -/// 0 = the backdrop's value kept), or `None` when every channel blends. RGB documents map R, G, B -/// directly and a grayscale document's single channel covers all three; other modes composite in -/// display RGB, where a restriction to their own channels has no exact equivalent, so it is -/// ignored there. -pub fn channel_weights(layer: &Layer, mode: photocraft_color::ColorMode) -> Option<[f32; 3]> { - use photocraft_color::ColorMode as M; - let x = layer.excluded_channels; - if x == 0 { - return None; - } - let keep = |bit: u32| if x & (1 << bit) != 0 { 0.0 } else { 1.0 }; - match mode { - M::Rgb => Some([keep(0), keep(1), keep(2)]), - M::Grayscale | M::Duotone => Some([keep(0); 3]), - _ => None, - } - .filter(|w| w != &[1.0; 3]) -} - -/// Put back the backdrop's values in the channels a layer leaves out (`w` from -/// [`channel_weights`]); alpha stays the layer's result. -fn restore_channels(out: &mut Buffer, before: &Buffer, w: [f32; 3]) { - for (p, b) in out.px.iter_mut().zip(&before.px) { - for c in 0..3 { - p[c] = b[c] + (p[c] - b[c]) * w[c]; - } - } -} - -/// Where `layer`'s composite (its pixels and effects; a group's visible children with theirs) can -/// be non-transparent, or `None` when it may draw anywhere (a surface with an opaque default -/// pixel). Outside it, compositing the layer leaves the backdrop unchanged in every blend mode. -/// Adjustment layers count as empty: they only change pixels already there (which is what an -/// isolated group needs; see [`change_bounds`] for the document-level question). -pub fn composite_bounds(layer: &Layer, canvas: Rect) -> Option { - if !transparent_outside(layer) { - return None; - } - let own = match &layer.content { - LayerContent::Group(g) if g.artboard.is_none() => { - let mut acc = Rect::EMPTY; - for c in g.children.iter().filter(|c| c.visible) { - let b = composite_bounds(c, canvas)?; - if !b.is_empty() { - acc = if acc.is_empty() { b } else { acc.union(&b) }; - } - } - acc - } - LayerContent::Adjustment(_) => Rect::EMPTY, - _ => layer_bounds(layer, canvas), - }; - 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)) -} - -/// The document pixels that showing, hiding, moving or restyling `layer` can change, or `None` -/// for anywhere: an adjustment layer (and a pass-through group holding one) reaches everything -/// beneath it. Clipped layers above stay within their base's bounds, so they are covered too; -/// effects of groups around the layer can reach further (callers grow the rect by that reach). -pub fn change_bounds(layer: &Layer, canvas: Rect) -> Option { - fn reaches_below(l: &Layer) -> bool { - match &l.content { - LayerContent::Adjustment(_) => !l.clipped, - // Clipped to a base, an adjustment changes only the base's pixels; one with no base - // beneath it in its list composites as an ordinary adjustment (#6535). - LayerContent::Group(g) if l.blend == BlendMode::PassThrough => g.children.iter().enumerate().any(|(k, c)| { - let orphan = - c.clipped && matches!(c.content, LayerContent::Adjustment(_)) && g.children.get(..k).is_none_or(|below| below.iter().all(|b| b.clipped)); - orphan || reaches_below(c) - }), - _ => false, - } - } - if matches!(layer.content, LayerContent::Adjustment(_)) || reaches_below(layer) { - return None; - } - 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 { - 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) - && group.blend == BlendMode::PassThrough - && !group.clipped - && outer.get(g + 1).is_some_and(|above| above.clipped) - { - // The group bounds its base too. - return change_bounds(group, canvas); - } - return change_bounds(base, canvas); - } - change_bounds(layer, canvas) -} - -/// Whether the layer's content is transparent outside its bounds (every surface it draws from -/// has a transparent default pixel), so its effects can't change pixels beyond its bounds grown -/// by their reach. -pub fn transparent_outside(layer: &Layer) -> bool { - match &layer.content { - LayerContent::Group(g) => g.children.iter().filter(|c| c.visible).all(transparent_outside), - // Fill layers cover the canvas (their bounds); adjustments draw nothing of their own. - LayerContent::Fill(_) | LayerContent::Adjustment(_) => true, - _ => layer.surface().is_none_or(|s| s.format().alpha && s.default_pixel().last().is_some_and(|a| *a <= 0.0)), - } -} - -/// Whether `layer` replaces everything beneath it in its stack: a visible, unclipped fill layer -/// in Normal mode at full opacity and fill, without masks, effects, channel restrictions or Blend -/// If, whose fill is opaque everywhere (a solid colour, or a gradient whose colour and opacity -/// stops are all opaque). Normal blending at alpha 1 returns the layer's colour exactly, so the -/// layers below can be skipped (the live Gradient tool's preview recomposites the whole canvas on -/// every pointer move). -pub fn occludes_below(layer: &Layer, mode: photocraft_color::ColorMode) -> bool { - let LayerContent::Fill(f) = &layer.content else { return false }; - let opaque = match f { - Fill::Solid(c) => c.alpha >= 1.0, - Fill::Gradient { stops, opacity_stops, .. } => { - !stops.is_empty() && stops.iter().all(|(_, c)| c.alpha >= 1.0) && opacity_stops.iter().all(|(_, o)| *o >= 1.0) - } - Fill::Pattern { .. } => false, - }; - // A cached render in use (a PSD's stored fill pixels) may not be opaque. - let cached = layer.fill_cache.as_ref().is_some_and(|c| c.fill == *f); - opaque - && !cached - && layer.visible - && !layer.clipped - && layer.blend == photocraft_color::BlendMode::Normal - && layer.opacity >= 1.0 - && layer.fill_opacity >= 1.0 - && !layer.mask.as_ref().is_some_and(|m| m.enabled) - && !layer.vector_mask.as_ref().is_some_and(|m| m.enabled) - && !effects::has_effects(layer) - && layer.excluded_channels == 0 - && !blend_if_active(layer, mode) -} - -/// Whether Blending Options › Blend If changes how `layer` composites in a `mode` document. -/// RGB documents test Gray and R, G, B; grayscale (and duotone) documents their one channel. -/// Other modes composite in display RGB, where ranges over their own channels have no exact -/// equivalent, so (like channel restrictions) the setting round-trips but isn't applied there. -pub fn blend_if_active(layer: &Layer, mode: photocraft_color::ColorMode) -> bool { - use photocraft_color::ColorMode as M; - matches!(mode, M::Rgb | M::Grayscale | M::Duotone) && !layer.blend_if.is_default() -} - -/// How much of a pixel shows through `layer`'s Blend If ranges, given the layer's own colour -/// (`this`, `None` where the layer has no content of its own there) and the colour beneath it -/// (`under`, `None` where nothing is beneath). Every range multiplies in. -fn blend_if_weight(layer: &Layer, mode: photocraft_color::ColorMode, this: Option<[f32; 4]>, under: Option<[f32; 4]>) -> f32 { - use photocraft_color::ColorMode as M; - let bi = &layer.blend_if; - let mut k = 1.0; - for (side, px) in [this, under].into_iter().enumerate() { - let Some(p) = px else { continue }; - let v = |c: usize| blend_if_level(p[c]); - match mode { - // Gray is the colour channels' luma (Rec. 601 weights), then R, G, B. - M::Rgb => { - let gray = 0.299 * v(0) + 0.587 * v(1) + 0.114 * v(2); - k *= bi.get(0)[side].weight(gray); - for c in 0..3 { - k *= bi.get(c + 1)[side].weight(v(c)); - } - } - // One channel: the PSD spec marks the composite-gray entry irrelevant here, so the - // channel's own entry carries the setting; both are honoured. - _ => k *= bi.get(0)[side].weight(v(0)) * bi.get(1)[side].weight(v(0)), - } - if k <= 0.0 { - return 0.0; - } - } - k -} - -/// A channel value on Blend If's 0..=255 scale. Compositing can leave an 8- or 16-bit level a few -/// millionths off (a level-20 backdrop composited at partial alpha reads 19.999998), which would -/// put it on the wrong side of a hard point at that level: a value that close to a level is that -/// level. Values of those depths that aren't on a level are at least 1/257 away from one. The GPU -/// compositor (`compose.wgsl` `blend_if_weight`) snaps alike. -fn blend_if_level(x: f32) -> f32 { - let v = x.clamp(0.0, 1.0) * 255.0; - let r = v.round(); - if (v - r).abs() < 1e-4 { r } else { v } -} - -/// Blend If groups inside one another whose own colour is still rendered separately. Each extra -/// level multiplies the work by the tree's depth, so the cost is polynomial, not exponential. -const MAX_BLEND_IF_GROUP_DEPTH: u32 = 2; - -thread_local! { - /// Blend If groups being rendered for their own colour on this thread. - static BLEND_IF_GROUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Apply `layer`'s Blend If to a finished composite: `out` (the backdrop with the layer drawn) -/// is mixed back towards `before` (the backdrop without it) where the ranges hide the layer. -/// Mixing premultiplied colour by `k` equals compositing the layer at `k` × its alpha, since -/// every blend mode's source-over result is linear in the source alpha. -fn apply_blend_if(layer: &Layer, before: &Buffer, out: &mut Buffer, cx: &Ctx) { - // "This Layer" is the layer's own colour; adjustment layers (no content of their own) are - // judged by their result. So are groups nested deeper than `MAX_BLEND_IF_GROUP_DEPTH` Blend - // Ifs: a group's own colour re-composites its children, which doubles the work at every - // level of Blend If groups inside one another. - let is_group = matches!(layer.content, LayerContent::Group(_)); - let nested = BLEND_IF_GROUPS.with(std::cell::Cell::get); - let own = if matches!(layer.content, LayerContent::Adjustment(_)) || (is_group && nested >= MAX_BLEND_IF_GROUP_DEPTH) { - None - } else { - BLEND_IF_GROUPS.with(|d| d.set(nested + u32::from(is_group))); - let own = render_content(layer, out.rect, cx); - BLEND_IF_GROUPS.with(|d| d.set(nested)); - own - }; - for (i, (p, b)) in out.px.iter_mut().zip(&before.px).enumerate() { - let this = match &own { - Some(o) => Some(o.px[i]).filter(|q| q[3] > 0.0), - None => Some(*p), - }; - let under = Some(*b).filter(|q| q[3] > 0.0); - let k = blend_if_weight(layer, cx.mode, this, under); - if k >= 1.0 { - continue; - } - let a = b[3] + (p[3] - b[3]) * k; - *p = if a > 0.0 { - let c = |c: usize| ((b[c] * b[3] + (p[c] * p[3] - b[c] * b[3]) * k) / a).clamp(0.0, 1.0); - [c(0), c(1), c(2), a] - } else { - [0.0; 4] - }; - } -} - -/// Composite `layer` (plus its clipping group) onto `backdrop`, honouring its channel restrictions -/// and Blend If, and knocking out to `ko` when it has a knockout (see [`advanced`]). -fn composite_layer(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, ko: Option<&Buffer>, scope: advanced::Scope) { - // Blend Clipped Layers as Group off: the base alone, then each clipped layer in its own mode. - if advanced::clips_individually(layer, clipped) { - advanced::composite_clipped_individually(layer, clipped, backdrop, cx, ko, scope); - return; - } - let w = channel_weights(layer, cx.mode); - let blend_if = blend_if_active(layer, cx.mode); - let before = (w.is_some() || blend_if).then(|| backdrop.clone()); - match ko { - Some(target) => advanced::knockout(layer, backdrop, target, false, cx, |b| composite_layer_any(layer, clipped, b, cx, scope)), - None => composite_layer_any(layer, clipped, backdrop, cx, scope), - } - if let Some(before) = &before { - if let Some(w) = w { - restore_channels(backdrop, before, w); - } - if blend_if { - apply_blend_if(layer, before, backdrop, cx); - } - } -} - -fn composite_layer_any(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { - if let LayerContent::Group(g) = &layer.content - && let Some(ab) = &g.artboard - { - composite_artboard(layer, ab, clipped, backdrop, cx, scope); - return; - } - composite_layer_plain(layer, clipped, backdrop, cx, scope); -} - -/// An artboard: its background and the group, composited only inside the board (contents and -/// effects outside it are clipped away; the backdrop there is untouched). -fn composite_artboard(layer: &Layer, ab: &photocraft_doc::Artboard, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { - let board = ab.rect.intersect(&backdrop.rect); - if board.is_empty() { - return; - } - let (bw, w) = (board.width() as usize, backdrop.rect.width() as usize); - let row0 = |y: i32| (y - backdrop.rect.y0) as usize * w + (board.x0 - backdrop.rect.x0) as usize; - let mut sub = Buffer::transparent(board); - for y in board.y0..board.y1 { - let o = row0(y); - let so = (y - board.y0) as usize * bw; - sub.px[so..so + bw].copy_from_slice(&backdrop.px[o..o + bw]); - } - if let Some(bg) = ab.background.rgba() { - blend_into(&mut sub, &Buffer::filled(board, bg), BlendMode::Normal, 1.0); - } - composite_layer_plain(layer, clipped, &mut sub, cx, scope); - for y in board.y0..board.y1 { - let o = row0(y); - let so = (y - board.y0) as usize * bw; - backdrop.px[o..o + bw].copy_from_slice(&sub.px[so..so + bw]); - } -} - -/// The surface `render_content` reads `layer`'s pixels from, when that is all it draws. -fn pixel_surface(layer: &Layer) -> Option<&Surface> { - if matches!(layer.content, LayerContent::Group(_) | LayerContent::Fill(_) | LayerContent::Adjustment(_)) { - return None; - } - layer.surface() -} - -/// A pixel layer (nothing clipped to it) onto `backdrop`, read from its tiles a row at a time: -/// the same arithmetic as `render_content` + `blend_into_fill`, without a tile-sized copy of the -/// layer (a megabyte per 256² render tile). -fn composite_pixel_layer(layer: &Layer, surf: &Surface, backdrop: &mut Buffer, cx: &Ctx) { - let rect = backdrop.rect; - let w = rect.width() as usize; - if w == 0 { - return; - } - let mv = mask_vals(layer, rect, cx); - let gamma = text_gamma(layer); - let mut row = vec![[0.0f32; 4]; w]; - for (ry, dst) in backdrop.px.chunks_exact_mut(w).enumerate() { - let y = rect.y0 + ry as i32; - surf.read_rgba_into(Rect::new(rect.x0, y, rect.x1, y + 1), &mut row); - if let Some(m) = mv.as_ref().and_then(|m| m.get(ry * w..(ry + 1) * w)) { - for (p, k) in row.iter_mut().zip(m) { - p[3] *= k; - } - } - blend_span_fill(dst, &row, rect.x0, y, layer.blend, layer.opacity, layer.fill_opacity, gamma); - } -} - -fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { - let rect = backdrop.rect; - // A TSL-off stroke base that is transparent here can still have visible clipped siblings; - // keep the full clipping path for it instead of the stroke-bounds shortcut. Other bases keep - // the usual skip (their clipped layers vanish with them). - if (clipped.is_empty() || shapeless_stroke_bounds(layer).is_none()) && empty_in(layer, rect) { - return; - } - let opacity = layer.opacity * layer.fill_opacity; - - // Pass-through groups composite their children straight into the backdrop. Below 100% fill - // Photoshop renders the group isolated, like Normal (psd-tools passthrough_fill_*: an - // adjustment inside no longer reaches the layers beneath), and so it does for a group that - // is the base of a clipping group and holds an adjustment layer (psd-tools - // passthrough_clipping_mask_adjustment: an Exposure inside leaves the layers beneath alone), - // while such a group's blend modes still reach the backdrop (passthrough_clipping_mask_blendmode). - let clip_base_adjusts = clipped.iter().any(|c| c.visible) - && matches!(&layer.content, LayerContent::Group(g) if g.children.iter().any(|c| c.visible && matches!(c.content, LayerContent::Adjustment(_)))); - if let LayerContent::Group(g) = &layer.content - && layer.blend == BlendMode::PassThrough - && layer.fill_opacity >= 1.0 - && !effects::has_effects(layer) - && !clip_base_adjusts - { - let needs_mix = opacity < 1.0 || layer.mask.is_some() || layer.vector_mask.is_some(); - let has_clipped = clipped.iter().any(|c| c.visible); - // Children can draw directly unless mixing or clipping needs the original backdrop. - let before = (needs_mix || has_clipped).then(|| backdrop.clone()); - composite_stack_at(&g.children, backdrop, cx, scope.pass_through()); - if needs_mix && let Some(before) = &before { - let mv = mask_vals(layer, rect, cx); - for (i, (p, a)) in backdrop.px.iter_mut().zip(&before.px).enumerate() { - let k = opacity * mask_k(&mv, i); - let b = *p; - // Coverage mixes premultiplied colour; the stored buffer remains straight alpha. - let wa = a[3] * (1.0 - k); - let wb = b[3] * k; - let alpha = wa + wb; - *p = if alpha > 0.0 { - let c = |c: usize| (a[c] * wa + b[c] * wb) / alpha; - [c(0), c(1), c(2), alpha] - } else { - [0.0; 4] - }; - } - } - // Layers clipped to a pass-through group sit atop the group's - // isolated rendering; their effect (isolated result with vs. without - // them, each placed over the original backdrop) is added to the - // pass-through result. Exact when the children blend Normal, close - // otherwise (matches psd-tools clipping-mask3/4/5). - if has_clipped && let (Some(before), Some(iso)) = (before, render_content(layer, rect, cx)) { - let mut clipped_iso = iso.clone(); - advanced::composite_clipped(clipped, &mut clipped_iso, cx); - let mut without = before.clone(); - blend_into(&mut without, &iso, BlendMode::Normal, opacity); - let mut with = before; - blend_into(&mut with, &clipped_iso, BlendMode::Normal, opacity); - for ((p, w), wo) in backdrop.px.iter_mut().zip(&with.px).zip(&without.px) { - // Work premultiplied so transparent areas stay consistent. - let pa = p[3]; - let mut pm = [p[0] * pa, p[1] * pa, p[2] * pa, pa]; - for c in 0..3 { - pm[c] += w[c] * w[3] - wo[c] * wo[3]; - } - pm[3] += w[3] - wo[3]; - let a = pm[3].clamp(0.0, 1.0); - *p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] }; - } - } - return; - } - - // Adjustment layers transform the backdrop, then blend the result back in. - if let LayerContent::Adjustment(adj) = &layer.content { - let mv = mask_vals(layer, rect, cx); - if mv.as_ref().is_some_and(|values| values.iter().all(|&value| opacity * value <= 0.0)) { - return; - } - let mut adjusted = scratch_buffer(rect); - adjusted.px.copy_from_slice(&backdrop.px); - cx.apply_adjustment(adj, &mut adjusted); - // Clipped layers onto an adjustment are uncommon; they composite atop the adjusted result. - advanced::composite_clipped(clipped, &mut adjusted, cx); - if layer.blend == BlendMode::Dissolve { - // An adjustment has no standalone source alpha. Its effective coverage comes from its - // own opacity and mask, not a continuous RGB mix (#3050). - for y in rect.y0..rect.y1 { - for x in rect.x0..rect.x1 { - let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize; - let k = opacity * mask_k(&mv, i); - if k > 0.0 && dissolve_noise(x, y) < k { - let a = adjusted.px[i]; - backdrop.px[i] = [a[0], a[1], a[2], backdrop.px[i][3]]; - } - } - } - } else { - match &mv { - Some(m) => blend_back(&mut backdrop.px, &adjusted.px, m.iter().map(|v| opacity * v), layer.blend), - None => blend_back(&mut backdrop.px, &adjusted.px, std::iter::repeat(opacity), layer.blend), - } - } - recycle_buffer(adjusted); - return; - } - - if effects::has_effects(layer) { - // Layer / Vector Mask Hides Effects: the effects are built without that mask, which then - // hides the finished layer and effects. - let src = advanced::effects_source(layer); - let hide = advanced::hiding_mask(layer, rect, cx); - let before = hide.as_ref().map(|_| backdrop.clone()); - composite_layer_effects(&src, clipped, backdrop, cx); - if let (Some(m), Some(b)) = (&hide, &before) { - advanced::apply_hiding_mask(backdrop, b, m); - } - return; - } - if let Some((mut content, stroke, mask)) = shape_parts(layer, clipped, rect, cx) { - advanced::composite_clipped(clipped, &mut content, cx); - for (i, (p, s)) in content.px.iter_mut().zip(&stroke.px).enumerate() { - *p = psblend::composite(BlendMode::Normal, *p, *s, 1.0); - p[3] *= mask_k(&mask, i); - } - blend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, 1.0); - return; - } - if !matches!(layer.content, LayerContent::Group(_) | LayerContent::Fill(_) | LayerContent::Adjustment(_)) - && let Some(s) = layer.surface() - && layer.blend == BlendMode::Normal - && opacity >= 1.0 - && !clipped.iter().any(|c| c.visible) - && layer.mask.is_none() - && layer.vector_mask.is_none() - && text_gamma(layer) == 1.0 - && !psblend::LAB_MIX.with(|l| l.get()) - && backdrop.px.iter().all(|p| p[3] <= 0.0) - { - s.read_rgba_into(rect, &mut backdrop.px); - for p in &mut backdrop.px { - if p[3] <= 0.0 { - *p = [0.0; 4]; - } else if p[3] < 1.0 { - *p = psblend::composite_normal_rgb([0.0; 4], *p, 1.0); - } - } - return; - } - if clipped.is_empty() - && let Some(surf) = pixel_surface(layer) - { - return composite_pixel_layer(layer, surf, backdrop, cx); - } - let Some(mut content) = render_content(layer, rect, cx) else { return }; - advanced::composite_clipped(clipped, &mut content, cx); - blend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, text_gamma(layer)); - recycle_buffer(content); -} - -/// A layer with effects (and its clipping group) onto `backdrop`. -fn composite_layer_effects(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx) { - let rect = backdrop.rect; - // Neighbourhoods are already captured by the full-region effect maps; - // content and effect application only need the output rectangle. - // A stroked shape's vector stroke stays above its clipped layers and interior effects. - let (mut content, vstroke) = match split_parts(layer, rect, cx) { - Some((fill, stroke, mask)) => (fill, Some((stroke, mask))), - None => { - let Some(content) = render_content(layer, rect, cx) else { return }; - (content, None) - } - }; - advanced::composite_clipped(clipped, &mut content, cx); - let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); - let maps = effect_maps(layer, rect, cx); - effects::composite_with_effects_prepared(layer, &content, backdrop, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke); -} - -/// The coverage-mixing gamma of a layer: the text blending gamma -/// ([`psblend::set_text_gamma`], Photoshop's default 1.45) for type layers, else 1. -pub fn text_gamma(layer: &Layer) -> f32 { - if matches!(layer.content, LayerContent::Text(_)) { psblend::text_gamma() } else { 1.0 } -} - -/// A stroked shape layer with visible clipped layers: Photoshop draws the shape's vector stroke -/// above the clipped layers, so the base content is the fill alone and the stroke is laid on top -/// after clipping. See [`split_parts`]. -fn shape_parts(layer: &Layer, clipped: &[Layer], rect: Rect, cx: &Ctx) -> Option<(Buffer, Buffer, Option>)> { - if !clipped.iter().any(|c| c.visible) { - return None; - } - split_parts(layer, rect, cx) -} - -/// A stroked shape layer's (fill, vector stroke, mask values) over `rect`; `None` for other -/// layers. Fill and stroke are unmasked: the mask applies to them together. Layer effects paint -/// the fill's interior effects beneath the vector stroke (psd-tools stroke-composite: a colour -/// overlay leaves the stroke, the stroke effect covers it). -fn split_parts(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<(Buffer, Buffer, Option>)> { - let LayerContent::Shape(sh) = &layer.content else { return None }; - sh.stroke.as_ref()?; - let (fs, ss) = shape_split::split(sh, cx.canvas, cx.depth)?; - Some((surface_to_buffer(&fs, rect), surface_to_buffer(&ss, rect), mask_vals(layer, rect, cx))) -} - -// --------------------------------------------------------------------------------------------- -// Layer-effect map cache - -/// Order-independent identity of a layer's pixels, masks, effects, Advanced Blending and Blend If -/// and (for groups) children. -/// Pixels are identified by their copy-on-write tile pointers. `pin` sees every tile hashed: a -/// cache entry keeps a [`std::sync::Weak`] to each, which reserves the tile's address (so no -/// other tile can reuse it and match the key) without keeping its pixels alive (#4530). -fn layer_identity(layer: &Layer, h: &mut std::collections::hash_map::DefaultHasher, pin: &mut dyn FnMut(&std::sync::Arc)) { - use std::hash::{Hash, Hasher}; - fn surface_fp(s: &Surface, pin: &mut dyn FnMut(&std::sync::Arc)) -> u64 { - let mut h = std::collections::hash_map::DefaultHasher::new(); - s.format().hash(&mut h); - // Missing tiles read the default pixel, so tile identity alone is not pixel identity. - for sample in s.default_pixel() { - sample.to_bits().hash(&mut h); - } - let tiles = s.tiles().fold(s.tile_count() as u64, |acc, (c, t)| { - pin(t); - let mut x = (std::sync::Arc::as_ptr(t) as usize as u64) ^ ((c.tx as u64) << 40) ^ ((c.ty as u32 as u64) << 8); - x = x.wrapping_mul(0x9e37_79b9_7f4a_7c15); - acc.wrapping_add(x ^ (x >> 29)) - }); - tiles.hash(&mut h); - h.finish() - } - layer.id.0.hash(h); - // What the maps depend on: `fill_opacity` shades them; layer `opacity` is applied when the - // maps are composited and `visible` only skips the lookup entirely, so neither belongs in - // the key (an opacity drag must not rebuild shadows over the whole layer; the GPU's - // `fx::shape_key` keeps them out for the same reason). - layer.fill_opacity.to_bits().hash(h); - match &layer.content { - LayerContent::Group(g) => { - for c in &g.children { - // A styled group's maps come from its children's composite, so how each child - // composites (unlike the group's own visibility and opacity) shapes them. - (c.visible, c.opacity.to_bits(), c.clipped).hash(h); - format!("{:?}", c.blend).hash(h); - layer_identity(c, h, pin); - } - format!("{:?}", g.artboard).hash(h); - } - LayerContent::Fill(f) => { - format!("{f:?}").hash(h); - // The cached pixels are what shapes the maps while they match the fill: a - // pixel-only rewrite of the cache (Image › Transform, crop) leaves `f` alone, and - // the stale maps would keep shadowing the pre-rewrite shape. - if let Some(c) = &layer.fill_cache - && c.fill == *f - { - surface_fp(&c.surface, pin).hash(h); - } - } - LayerContent::Adjustment(a) => format!("{a:?}").hash(h), - _ => layer.surface().map_or(0, |s| surface_fp(s, pin)).hash(h), - } - if let Some(m) = &layer.mask { - (surface_fp(&m.surface, pin), m.enabled, m.density.to_bits(), m.feather.to_bits()).hash(h); - } - if let Some(vm) = &layer.vector_mask { - format!("{vm:?}").hash(h); - } - format!("{:?}", layer.effects).hash(h); - // Transparency Shapes Layer picks the shape (content or the whole layer); a group child's - // Blend If and knockout change the composite a styled group's shape comes from. - layer.advanced.hash(h); - layer.blend_if.hash(h); - h.write_u8(0xfe); -} - -struct FxEntry { - maps: std::sync::Arc, - /// The tiles the key identifies (see [`layer_identity`]): their addresses, not their pixels. - _pin: Vec>, - bytes: usize, -} - -/// Global cache of effect maps (bounded by bytes), one slot per layer state. Slots are filled -/// with `set`, never `get_or_init`: nothing may block on a build (see `cached_effect_maps`). -type FxSlot = std::sync::Arc>; -struct FxCache { - map: std::collections::HashMap, - order: std::collections::VecDeque, - bytes: usize, -} - -/// Default effect-cache budget (Preferences › Performance can change it). -pub const DEFAULT_FX_CACHE_BUDGET: usize = 768 << 20; -static FX_CACHE_BUDGET: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(DEFAULT_FX_CACHE_BUDGET); - -/// Set the memory budget (bytes) of the layer-effect map cache; entries over it are evicted -/// oldest-first on the next build. -pub fn set_effect_cache_budget(bytes: usize) { - FX_CACHE_BUDGET.store(bytes.max(1 << 20), std::sync::atomic::Ordering::Relaxed); -} - -/// The current effect-cache budget in bytes. -pub fn effect_cache_budget() -> usize { - FX_CACHE_BUDGET.load(std::sync::atomic::Ordering::Relaxed) -} - -/// Bytes currently held by the effect-map cache. -pub fn effect_cache_bytes() -> usize { - fx_cache().lock().unwrap_or_else(|e| e.into_inner()).bytes -} - -/// Drop every cached effect map (Edit › Purge › All). Returns the bytes released. -pub fn purge_effect_cache() -> usize { - let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); - let freed = c.bytes; - c.map.clear(); - c.order.clear(); - c.bytes = 0; - freed -} - -fn fx_cache() -> &'static std::sync::Mutex { - static C: std::sync::OnceLock> = std::sync::OnceLock::new(); - C.get_or_init(|| std::sync::Mutex::new(FxCache { map: Default::default(), order: Default::default(), bytes: 0 })) -} - -/// Where `layer`'s effect maps are built (see [`effect_maps`]) and whether that is clipped to the -/// rectangle being rendered rather than the whole region. -/// -/// Transparency Shapes Layer off makes the region the whole canvas whatever the layer holds: on a -/// 1920 × 103675 webtoon page each such layer's maps took about 2.4 GB, and a render held them for -/// every layer at once (60 GB with 25 stroked type layers, #1909). When its effects are local -/// ([`effects::maps_are_local`]), such a layer's maps are built over the render rectangle padded -/// by twice the effect reach instead, which gives the same pixels there. So are any layer's local -/// maps when the render's whole-region maps wouldn't fit in the effect cache ([`fx_over_budget`]). -/// Only when `rect`, what -/// the caller composites the layer over, lies within the render rectangle: a group's effect shape -/// (or anything else rendering children over a wider area) gets the whole region. -fn effect_region(layer: &Layer, rect: Rect, cx: &Ctx) -> (Rect, bool) { - let m = effects::margin(layer); - let region = effect_source_bounds(layer, cx.canvas).inflate(m).intersect(&cx.canvas.inflate(m)); - let clip = *cx.fx_clip.lock().unwrap_or_else(|e| e.into_inner()); - match clip { - Some(c) if c.contains_rect(&rect) && (advanced::shapeless(layer) || cx.fx_over_budget) && effects::maps_are_local(layer) => { - let part = region.intersect(&c.inflate(m.saturating_mul(2))); - (part, part != region) - } - _ => (region, false), - } -} - -/// Whether the effect maps of the visible layers of `layers` (groups included), each over its -/// whole region, would take more than the effect cache budget together. A render needs all of -/// them, so when they don't fit, building one evicts the next one needed and every render builds -/// them all again, seconds even for a small rect (#8330). Counted as [`effects::FxMaps::bytes`] -/// counts the built maps ([`effects::map_count`] arrays over each region). -fn fx_over_budget(layers: &[Layer], canvas: Rect) -> bool { - fx_region_bytes(layers, canvas) > effect_cache_budget() as u64 -} - -/// The bytes [`fx_over_budget`] compares with the budget. -fn fx_region_bytes(layers: &[Layer], canvas: Rect) -> u64 { - fn bytes(layers: &[Layer], canvas: Rect, depth: u32) -> u64 { - let mut total = 0u64; - for l in layers.iter().filter(|l| l.visible) { - if effects::has_effects(l) { - let m = effects::margin(l); - let region = effect_source_bounds(l, canvas).inflate(m).intersect(&canvas.inflate(m)); - let maps = effects::map_count(l) as u64; - let px = u64::from(region.width()) * u64::from(region.height()); - total = total.saturating_add(maps.saturating_mul(px).saturating_mul(4)); - } - if let LayerContent::Group(g) = &l.content - && depth < PREPARE_DEPTH - { - total = total.saturating_add(bytes(&g.children, canvas, depth + 1)); - } - } - total - } - bytes(layers, canvas, 0) -} - -/// Most bytes one layer's effect maps and source may take to build, whatever the cache budget. -const MAX_FX_BUILD_BYTES: u64 = if cfg!(target_pointer_width = "64") { 4 << 30 } else { 512 << 20 }; - -/// The layer's effect maps over its region (layer bounds grown by the effect reach, within the -/// canvas grown likewise; see [`effect_region`]), built once per layer state and shared by every -/// tile. `rect` is what the caller composites the layer over (see [`effect_region`]). -fn effect_maps(layer: &Layer, rect: Rect, cx: &Ctx) -> std::sync::Arc { - use std::hash::{Hash, Hasher}; - let (mut region, clipped) = effect_region(layer, rect, cx); - // Non-local effects keep their whole source region, which a few distant pixels stretch over - // the canvas: past the cap the effects are left out instead of allocating it. - let region_px = u64::from(region.width()) * u64::from(region.height()); - if (effects::map_count(layer) as u64 + 1).saturating_mul(region_px).saturating_mul(4) > MAX_FX_BUILD_BYTES { - region = Rect::EMPTY; - } - static NO_CACHE: std::sync::OnceLock = std::sync::OnceLock::new(); - if *NO_CACHE.get_or_init(|| std::env::var_os("PHOTOCRAFT_FX_NOCACHE").is_some()) { - let shape = if region.is_empty() { Vec::new() } else { effect_shape(layer, region, cx) }; - return std::sync::Arc::new(effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns)); - } - let mut h = std::collections::hash_map::DefaultHasher::new(); - cx.layer_keys.identity(layer, cx.doc).hash(&mut h); - (region.x0, region.y0, region.x1, region.y1).hash(&mut h); - (cx.light.angle.to_bits(), cx.light.altitude.to_bits()).hash(&mut h); - let key = h.finish(); - // Prepared for this render (see `prepare_effects`): no global lookup, no build. - if let Some((m, _)) = cx.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { - return m.clone(); - } - let maps = cached_effect_maps(layer, region, key, cx); - cx.fx_maps.lock().unwrap_or_else(|e| e.into_inner()).entry(key).or_insert((maps, clipped)).0.clone() -} - -fn build_fx_slot_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx, slot: &FxSlot) -> std::sync::Arc { - let shape: Vec = if region.is_empty() { Vec::new() } else { effect_shape(layer, region, cx) }; - let maps = effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns); - let mut pin = Vec::new(); - layer_identity(layer, &mut std::collections::hash_map::DefaultHasher::new(), &mut |t| pin.push(std::sync::Arc::downgrade(t))); - // The maps, plus what each reserved tile address keeps allocated. - let bytes = maps.bytes().saturating_add(pin.len().saturating_mul(std::mem::size_of::() + 2 * std::mem::size_of::())); - let maps = std::sync::Arc::new(maps); - if slot.set(FxEntry { maps: maps.clone(), _pin: pin, bytes }).is_ok() { - // Counted exactly once, by the build that filled the slot, and only while the - // slot is still cached (eviction may have dropped it meanwhile). - let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); - if c.map.get(&key).is_some_and(|s| std::sync::Arc::ptr_eq(s, slot)) { - c.bytes += bytes; - } - } - // A concurrent build that finished first wins, so every tile shares one map. - slot.get().map_or(maps, |e| e.maps.clone()) -} - -fn evict_fx_cache_over_budget(key: u64) { - let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); - let budget = effect_cache_budget(); - while c.bytes > budget && c.order.len() > 1 { - let Some(old) = c.order.pop_front() else { break }; - if old == key { - c.order.push_back(old); - continue; - } - if let Some(s) = c.map.remove(&old) { - c.bytes = c.bytes.saturating_sub(s.get().map_or(0, |e| e.bytes)); - } - } -} - -/// The layer's effect maps from the global cache, built on a miss. -/// -/// Never waits for another thread's build (#276): this can run on a Rayon worker inside a tile, -/// and the build itself runs Rayon work. A worker waiting on that work may steal another tile of -/// the same layer; had it blocked on a once-init held further up its own stack, it would deadlock. -/// Instead a miss builds the maps here and the first finished build is kept. Renders build every -/// layer's maps before their parallel tiles (`prepare_effects`), so tiles rarely miss. -fn cached_effect_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx) -> std::sync::Arc { - let slot = { - let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); - if let Some(s) = c.map.get(&key) { - s.clone() - } else { - let s: FxSlot = Default::default(); - c.map.insert(key, s.clone()); - c.order.push_back(key); - s - } - }; - let maps = match slot.get() { - Some(e) => e.maps.clone(), - None => build_fx_slot_maps(layer, region, key, cx, &slot), - }; - // Evict the oldest entries over budget (never the one just used). - evict_fx_cache_over_budget(key); - maps -} - -fn texture_ctx<'a>(layer: &Layer, region: Rect, cx: &Ctx<'a>) -> effects::TextureCtx<'a> { - let sb = effects_frame(layer, cx.canvas); - effects::TextureCtx { rect: region, patterns: cx.patterns.source(), anchor: layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))) } -} - -/// Composite `layer` onto `base` restricted to the base's alpha (clipping mask semantics), -/// honouring its channel restrictions and Blend If. -fn composite_atop(layer: &Layer, base: &mut Buffer, cx: &Ctx) { - let w = channel_weights(layer, cx.mode); - let blend_if = blend_if_active(layer, cx.mode); - let before = (w.is_some() || blend_if).then(|| base.clone()); - composite_atop_any(layer, base, cx); - if let Some(before) = &before { - if let Some(w) = w { - restore_channels(base, before, w); - } - if blend_if { - apply_blend_if(layer, before, base, cx); - } - } -} - -fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) { - let rect = base.rect; - if let LayerContent::Adjustment(adj) = &layer.content { - let mut adjusted = base.clone(); - cx.apply_adjustment(adj, &mut adjusted); - let mv = mask_vals(layer, rect, cx); - for (i, p) in base.px.iter_mut().enumerate() { - let k = layer.opacity * layer.fill_opacity * mask_k(&mv, i); - let a = adjusted.px[i]; - if layer.blend == BlendMode::Dissolve { - let x = rect.x0 + (i % rect.width() as usize) as i32; - let y = rect.y0 + (i / rect.width() as usize) as i32; - if dissolve_noise(x, y) < k { - *p = [a[0], a[1], a[2], p[3]]; - } - continue; - } - let bl = blend::blend_rgb(layer.blend, [p[0], p[1], p[2]], [a[0], a[1], a[2]]); - for c in 0..3 { - p[c] += (bl[c] - p[c]) * k; - } - } - return; - } - if effects::has_effects(layer) { - // Effects of a clipped layer are clipped to the base too: render - // them over the base (treated as opaque) and keep the base's alpha. - // The full-region effect maps already capture their neighbourhoods. - // A mask that hides the effects applies to the finished result instead. - let hide = advanced::hiding_mask(layer, rect, cx); - let src = advanced::effects_source(layer); - let layer = src.as_ref(); - let (content, vstroke) = match split_parts(layer, rect, cx) { - Some((fill, stroke, mask)) => (fill, Some((stroke, mask))), - None => { - let Some(content) = render_content(layer, rect, cx) else { return }; - (content, None) - } - }; - let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); - let mut opaque = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() }; - let maps = effect_maps(layer, rect, cx); - effects::composite_with_effects_prepared(layer, &content, &mut opaque, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke); - if let Some(m) = &hide { - let plain = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() }; - advanced::apply_hiding_mask(&mut opaque, &plain, m); - } - for (p, o) in base.px.iter_mut().zip(&opaque.px) { - if p[3] > 0.0 { - *p = [o[0], o[1], o[2], p[3]]; - } - } - return; - } - let Some(content) = render_content(layer, rect, cx) else { return }; - let opacity = layer.opacity * layer.fill_opacity; - let gamma = text_gamma(layer); - for (i, p) in base.px.iter_mut().enumerate() { - let alpha = p[3]; - if alpha <= 0.0 { - continue; - } - let s = content.px[i]; - if layer.blend == BlendMode::Dissolve { - // Clipping preserves the opaque base's alpha. Dissolve still selects source - // pixels by spatial coverage instead of continuously mixing the colours (#3052). - let x = rect.x0 + (i as i32 % rect.width() as i32); - let y = rect.y0 + (i as i32 / rect.width() as i32); - if dissolve_noise(x, y) < s[3] * opacity { - *p = [s[0], s[1], s[2], alpha]; - } - continue; - } - // Blend as if the base were opaque, then keep the base's alpha. - let r = blend::composite_gamma(layer.blend, [p[0], p[1], p[2], 1.0], s, opacity, gamma); - *p = [r[0], r[1], r[2], alpha]; - } -} - -/// Blend an isolated layer buffer into the backdrop. -fn blend_into(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32) { - blend_into_g(backdrop, src, mode, opacity, 1.0); -} - -/// [`blend_into_g`] for a layer's own `opacity` and `fill`: Fill is part of the blend for -/// Photoshop's special eight ([`psblend::composite_fill`]), plain coverage otherwise. -fn blend_into_fill(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, fill: f32, gamma: f32) { - for_rows(backdrop, src, |dst, s, x0, y| blend_span_fill(dst, s, x0, y, mode, opacity, fill, gamma)); -} - -/// [`blend_into`] mixing coverage in a `gamma` space (type layers). -fn blend_into_g(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, gamma: f32) { - for_rows(backdrop, src, |dst, s, x0, y| blend_span_g(dst, s, x0, y, mode, opacity, gamma)); -} - -/// Runs `f(backdrop row, src row, x0, y)` over the rows of two buffers covering the same rect. -fn for_rows(backdrop: &mut Buffer, src: &Buffer, mut f: impl FnMut(&mut [[f32; 4]], &[[f32; 4]], i32, i32)) { - let rect = backdrop.rect; - let w = (rect.width() as usize).max(1); - for (ry, (dst, s)) in backdrop.px.chunks_mut(w).zip(src.px.chunks(w)).enumerate() { - f(dst, s, rect.x0, rect.y0 + ry as i32); - } -} - -/// [`blend_into_fill`] of one row: `dst` and `src` start at pixel (`x0`, `y`). -#[allow(clippy::too_many_arguments)] -fn blend_span_fill(dst: &mut [[f32; 4]], src: &[[f32; 4]], x0: i32, y: i32, mode: BlendMode, opacity: f32, fill: f32, gamma: f32) { - if fill >= 1.0 || !psblend::fill_is_special(mode) { - return blend_span_g(dst, src, x0, y, mode, opacity * fill, gamma); - } - for (b, s) in dst.iter_mut().zip(src) { - if s[3] > 0.0 { - *b = psblend::composite_fill(mode, *b, *s, opacity, fill, gamma); - } - } -} - -/// [`blend_into_g`] of one row: `dst` and `src` start at pixel (`x0`, `y`). -fn blend_span_g(dst: &mut [[f32; 4]], src: &[[f32; 4]], x0: i32, y: i32, mode: BlendMode, opacity: f32, gamma: f32) { - // The blend space is constant in this loop. Some TLS implementations synchronise even a - // boolean read, so select the common Normal kernel once instead of once per pixel. - if mode == BlendMode::Normal && gamma == 1.0 && !psblend::LAB_MIX.with(|l| l.get()) { - return psblend::composite_normal_rgb_span(dst, src, opacity); - } - for (x, (b, s)) in (x0..).zip(dst.iter_mut().zip(src)) { - let mut s = *s; - if s[3] <= 0.0 { - continue; - } - if mode == BlendMode::Dissolve { - s[3] = if dissolve_noise(x, y) < s[3] * opacity { 1.0 } else { 0.0 }; - *b = blend::composite(BlendMode::Normal, *b, s, 1.0); - continue; - } - *b = blend::composite_gamma(mode, *b, s, opacity, gamma); - } -} - #[cfg(test)] mod soft_shape_tests; #[cfg(test)] diff --git a/crates/compose/src/reduced.rs b/crates/compose/src/reduced.rs new file mode 100644 index 0000000000..479bf1655f --- /dev/null +++ b/crates/compose/src/reduced.rs @@ -0,0 +1,300 @@ +use super::content::RENDER_TILE; +use super::ctx::Ctx; +use super::render::{band_rows_for, render, render_bands, render_tiled_with}; +use super::*; + +/// Documents above this many pixels get thumbnails from a proxy (see [`proxy`]) when that is +/// faithful; smaller ones are reduced from the exact composite. +pub const PROXY_THUMBNAIL_PIXELS: u64 = 16 << 20; + +/// Downscaled RGBA8 render of the document (area-averaged) for thumbnails, navigators and +/// histograms, at most `max_side` pixels on its longer side. Large documents are reduced from a +/// downsampled proxy (about twice the thumbnail's size), so a thumbnail of a 200 MP document +/// costs milliseconds and no full-size composite; the rest stream the exact composite in bands. +pub fn thumbnail(doc: &Document, max_side: u32) -> Rgba8Image { + thumbnail_buffer(doc, max_side).to_rgba8() +} + +/// Width and height of [`thumbnail`]`(doc, max_side)`. +pub fn thumbnail_size(doc: &Document, max_side: u32) -> (u32, u32) { + let b = doc.bounds(); + let longest = b.width().max(b.height()).max(1); + let scale = (max_side as f32 / longest as f32).min(1.0); + (((b.width() as f32 * scale).round() as u32).max(1), ((b.height() as f32 * scale).round() as u32).max(1)) +} + +/// [`thumbnail`] as straight-alpha floats (for callers that colour-convert it first). +pub fn thumbnail_buffer(doc: &Document, max_side: u32) -> Buffer { + let b = doc.bounds(); + let longest = b.width().max(b.height()).max(1); + let (w, h) = thumbnail_size(doc, max_side); + let k = longest / max_side.max(1).saturating_mul(2); + if k >= 2 && doc.size.area() > PROXY_THUMBNAIL_PIXELS && proxy::proxy_faithful(doc) { + render_reduced(&proxy::proxy_document(doc, k), w, h) + } else { + render_reduced(doc, w, h) + } +} + +/// The document's composite area-averaged (premultiplied) down to `w`×`h` (clamped to the +/// document size), rendered in bands so no full-size composite is held. +pub fn render_reduced(doc: &Document, w: u32, h: u32) -> Buffer { + render_reduced_in_bands(doc, doc.bounds(), w, h, None, 0) +} + +/// [`render_reduced`] of any area of the document plane, `rect`, which may lie past the canvas +/// (layer pixels there are kept until a crop deletes them). The buffer's rect is in output pixels +/// from (0, 0). +pub fn render_reduced_rect(doc: &Document, rect: Rect, w: u32, h: u32) -> Buffer { + render_reduced_in_bands(doc, rect, w, h, None, 0) +} + +/// The part of [`render_reduced`]`(doc, w, h)` that a change to `damage` (document pixels) can +/// affect: the output pixels whose source areas meet it, rendered from just those areas, with the +/// same values the whole reduction gives them. The buffer's rect is in output pixels (empty when +/// `damage` misses the document), so a reduced canvas texture can update only what a stroke touched. +pub fn render_reduced_damage(doc: &Document, w: u32, h: u32, damage: Rect) -> Buffer { + render_reduced_in_bands(doc, doc.bounds(), w, h, Some(damage), 0) +} + +/// [`render_reduced_rect`] (or, with `damage`, [`render_reduced_damage`]) of area `b` with an +/// explicit band height (see [`render_bands`]). +pub(crate) fn render_reduced_in_bands(doc: &Document, b: Rect, w: u32, h: u32, damage: Option, band_rows: i32) -> Buffer { + render_reduced_with(doc, b, w, h, damage, band_rows, true, &mut ReducedStats::default()) +} + +/// What a reduced render composited (tests check that one-colour areas are not composited). +#[derive(Debug, Default)] +pub(crate) struct ReducedStats { + /// Whether one-colour areas were looked for ([`uniform::UniformAreas`]). + pub(crate) uniform: bool, + /// Document pixels composited one by one. + pub(crate) composited: u64, +} + +/// A tile of a reduced render: one colour (premultiplied), or its composited pixels. +enum Part { + Solid([f32; 4]), + Px(Buffer), +} + +/// A column of document tiles in a reduced render (`b`-relative source columns). +struct TileColumn { + /// The columns rendered: the tile's, within the source area. + x0: usize, + x1: usize, + /// The whole tile's columns within `b`, whose values decide whether it is one colour. + whole: (i64, i64), + /// Runs of (output column, how many of the rendered columns it averages). + runs: Vec<(usize, f32)>, +} + +/// [`render_reduced_in_bands`]; `uniform` off composites every pixel (the reference in tests). +#[allow(clippy::too_many_arguments)] +pub(crate) fn render_reduced_with( + doc: &Document, + b: Rect, + w: u32, + h: u32, + damage: Option, + band_rows: i32, + uniform: bool, + stats: &mut ReducedStats, +) -> Buffer { + let (fw, fh) = (b.width() as usize, b.height() as usize); + let (w, h) = (w.clamp(1, b.width().max(1)) as usize, h.clamp(1, b.height().max(1)) as usize); + let full = Rect::from_xywh(0, 0, w as u32, h as u32); + if fw == 0 || fh == 0 { + return Buffer::transparent(if damage.is_some() { Rect::EMPTY } else { full }); + } + // Output column / row of each document column / row: output pixel t covers [t·f/n, (t+1)·f/n). + let span = |t: usize, f: usize, n: usize| (t * f / n, ((t + 1) * f / n).max(t * f / n + 1).min(f)); + // The output pixel whose span holds document column / row `x` (spans are contiguous: n <= f). + let cell = |x: usize, f: usize, n: usize| ((x + 1) * n).saturating_sub(1) / f; + // Output pixels to produce and the document area they cover. + let out = match damage { + None => full, + Some(d) => { + let d = d.intersect(&b); + if d.is_empty() { + return Buffer::transparent(Rect::EMPTY); + } + let (x0, x1) = ((d.x0 - b.x0) as usize, (d.x1 - b.x0) as usize); + let (y0, y1) = ((d.y0 - b.y0) as usize, (d.y1 - b.y0) as usize); + Rect::new(cell(x0, fw, w) as i32, cell(y0, fh, h) as i32, cell(x1 - 1, fw, w) as i32 + 1, cell(y1 - 1, fh, h) as i32 + 1) + } + }; + let (ox0, oy0, ow, oh) = (out.x0 as usize, out.y0 as usize, out.width() as usize, out.height() as usize); + let (sx0, sx1) = (span(ox0, fw, w).0, span(ox0 + ow - 1, fw, w).1); + let (sy0, sy1) = (span(oy0, fh, h).0, span(oy0 + oh - 1, fh, h).1); + let src = Rect::new(b.x0 + sx0 as i32, b.y0 + sy0 as i32, b.x0 + sx1 as i32, b.y0 + sy1 as i32); + if (w, h) == (fw, fh) { + let mut px = render(doc, src); + px.rect = out; + return px; + } + let map = |f: usize, n: usize| { + let mut m = vec![0u32; f]; + for t in 0..n { + let (a, z) = span(t, f, n); + m[a..z].fill(t as u32); + } + m + }; + let (cols, rows) = (map(fw, w), map(fh, h)); + let cols = &cols[sx0..sx1]; + let mut acc = vec![[0.0f32; 4]; ow * oh]; + // Each output row sums its source rows in a band (in order, top to bottom), each row's pixels + // left to right: `row(y, out)` adds source row `y` (band-relative) to output row `out`. + let sum_band = |acc: &mut [[f32; 4]], by0: usize, by1: usize, row: &(dyn Fn(usize, &mut [[f32; 4]]) + Sync)| { + let (t0, t1) = (rows[by0] as usize, rows[by1 - 1] as usize + 1); + let sum_row = |t: usize, out: &mut [[f32; 4]]| { + let (a, z) = span(t, fh, h); + for y in a.max(by0)..z.min(by1) { + row(y - by0, out); + } + }; + let part = &mut acc[(t0 - oy0) * ow..(t1 - oy0) * ow]; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + part.par_chunks_mut(ow).enumerate().for_each(|(i, out)| sum_row(t0 + i, out)); + } + #[cfg(target_arch = "wasm32")] + for (i, out) in part.chunks_mut(ow).enumerate() { + sum_row(t0 + i, out); + } + }; + let add = |o: &mut [f32; 4], p: &[f32; 4]| { + for i in 0..3 { + o[i] += p[i] * p[3]; + } + o[3] += p[3]; + }; + if let Some(uniform) = uniform.then(|| uniform::UniformAreas::new(doc)).flatten() { + stats.uniform = true; + // One-colour tiles (a new document's background, the empty parts of a sparse one) are + // composited once per colour and summed per run of source columns, not per pixel + // (#4017). Tiles lie on the document's tile grid whatever `damage` is, so a damage + // render sums exactly what the whole reduction does. + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let cx = Ctx::for_doc(doc, &patterns); + let t = RENDER_TILE as usize; + // The document tile grid (the surfaces' own), in `b`-relative coordinates: the start of + // the tile holding `v` (negative when `b` starts inside a tile). + let grid = |v: usize, o: i32| (i64::from(o) + v as i64).div_euclid(t as i64) * t as i64 - i64::from(o); + let tile_cols: Vec = (grid(sx0, b.x0)..sx1 as i64) + .step_by(t) + .map(|gx| { + let (x0, x1) = ((gx.max(0) as usize).max(sx0), ((gx + t as i64) as usize).min(sx1)); + let mut runs: Vec<(usize, f32)> = Vec::new(); + for &c in &cols[x0 - sx0..x1 - sx0] { + match runs.last_mut() { + Some((last, n)) if *last == c as usize - ox0 => *n += 1.0, + _ => runs.push((c as usize - ox0, 1.0)), + } + } + TileColumn { x0, x1, whole: (gx.max(0), (gx + t as i64).min(fw as i64)), runs } + }) + .collect(); + let band_h = band_rows_for(src.width(), band_rows).max(RENDER_TILE) as usize; + let mut y = grid(sy0, b.y0); + while y < sy1 as i64 { + let y1 = (y + band_h as i64).min(sy1 as i64); + let tiles: Vec<(Rect, Rect)> = (y..y1) + .step_by(t) + .flat_map(|gy| { + tile_cols.iter().map(move |&TileColumn { x0, x1, whole: (gx0, gx1), .. }| { + let at = |x0: i64, y0: i64, x1: i64, y1: i64| Rect::new(b.x0 + x0 as i32, b.y0 + y0 as i32, b.x0 + x1 as i32, b.y0 + y1 as i32); + let (gy0, gy1) = (gy.max(0), (gy + t as i64).min(fh as i64)); + (at(gx0, gy0, gx1, gy1), at(x0 as i64, gy0.max(sy0 as i64), x1 as i64, gy1.min(sy1 as i64))) + }) + }) + .collect(); + let one = |(whole, part): &(Rect, Rect)| -> Part { + let render = |r: Rect| render_tiled_with(doc, r, RENDER_TILE, &cx); + match uniform.color(*whole, |r| render(r).px.first().copied()) { + Some(p) => Part::Solid([p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]]), + None => Part::Px(render(*part)), + } + }; + #[cfg(not(target_arch = "wasm32"))] + let parts: Vec = { + use rayon::prelude::*; + tiles.par_iter().map(one).collect() + }; + #[cfg(target_arch = "wasm32")] + let parts: Vec = tiles.iter().map(one).collect(); + stats.composited += parts.iter().map(|p| if let Part::Px(b) = p { b.px.len() as u64 } else { 0 }).sum::(); + let (by0, by1) = (y.max(sy0 as i64) as usize, y1 as usize); + let n = tile_cols.len(); + let band_y = y; + sum_band(&mut acc, by0, by1, &|row: usize, out: &mut [[f32; 4]]| { + let y = (by0 + row) as i64; + let j = (y - band_y) as usize / t; + let ty = (y - (band_y + (j * t) as i64).max(sy0 as i64)) as usize; + for (TileColumn { x0, x1, runs, .. }, part) in tile_cols.iter().zip(parts.iter().skip(j * n).take(n)) { + match part { + Part::Solid(pa) => { + for &(c, k) in runs { + let o = &mut out[c]; + for i in 0..4 { + o[i] += pa[i] * k; + } + } + } + Part::Px(buf) => { + let tw = x1 - x0; + for (p, &c) in buf.px.iter().skip(ty * tw).take(tw).zip(&cols[x0 - sx0..x1 - sx0]) { + add(&mut out[c as usize - ox0], p); + } + } + } + } + }); + y = y1; + } + } else { + let ok: Result<(), ()> = render_bands(doc, src, band_rows, |band| { + stats.composited += band.px.len() as u64; + let (by0, by1) = ((band.rect.y0 - b.y0) as usize, (band.rect.y1 - b.y0) as usize); + let sw = sx1 - sx0; + sum_band(&mut acc, by0, by1, &|y: usize, out: &mut [[f32; 4]]| { + for (p, &c) in band.px[y * sw..(y + 1) * sw].iter().zip(cols) { + add(&mut out[c as usize - ox0], p); + } + }); + Ok(()) + }); + debug_assert!(ok.is_ok()); + } + let col_w: Vec = (0..ow) + .map(|x| { + let (x0, x1) = span(ox0 + x, fw, w); + (x1 - x0).max(1) + }) + .collect(); + let norm_row = |row: usize, out: &mut [[f32; 4]]| { + let (y0, y1) = span(oy0 + row, fh, h); + let rh = (y1 - y0).max(1); + for (p, &cw) in out.iter_mut().zip(&col_w) { + let a = p[3]; + if a > 0.0 { + let n = (rh * cw) as f32; + *p = [p[0] / a, p[1] / a, p[2] / a, a / n]; + } else { + *p = [0.0; 4]; + } + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + acc.par_chunks_mut(ow).enumerate().for_each(|(row, out)| norm_row(row, out)); + } + #[cfg(target_arch = "wasm32")] + for (row, out) in acc.chunks_mut(ow).enumerate() { + norm_row(row, out); + } + Buffer { rect: out, px: acc } +} diff --git a/crates/compose/src/render.rs b/crates/compose/src/render.rs new file mode 100644 index 0000000000..33b17d25b8 --- /dev/null +++ b/crates/compose/src/render.rs @@ -0,0 +1,360 @@ +use super::composite::composite_stack_at; +use super::content::RENDER_TILE; +use super::ctx::{Ctx, RenderVectorMasks, prepare_effects, prepare_tones}; +use super::*; + +/// Every layer the compositor draws, groups before their children: hidden layers and everything +/// inside hidden groups are left out. +pub(crate) fn visible_layers(layers: &[Layer]) -> Vec<&Layer> { + fn rec<'a>(layers: &'a [Layer], out: &mut Vec<&'a Layer>) { + for l in layers.iter().filter(|l| l.visible) { + out.push(l); + if let Some(children) = l.children() { + rec(children, out); + } + } + } + let mut out = Vec::new(); + rec(layers, &mut out); + out +} + +/// Composite the whole document over `rect`, in parallel 256² tiles on +/// native targets (single-threaded on wasm). +pub fn render(doc: &Document, rect: Rect) -> Buffer { + render_tiled(doc, rect, RENDER_TILE) +} + +/// Most pixels one [`render`] call will produce (2^30, a 16 GiB buffer; 32768² px). Larger rects +/// (a hostile canvas size is up to 300000 px a side) return an empty buffer instead of aborting +/// on allocation; callers wanting more render in pieces. +pub const MAX_RENDER_PIXELS: u64 = 1 << 30; + +/// [`render`] with an explicit tile size (tests check tile independence). +pub fn render_tiled(doc: &Document, rect: Rect, tile: i32) -> Buffer { + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let cx = Ctx::for_doc(doc, &patterns); + render_tiled_with(doc, rect, tile, &cx) +} + +pub(crate) fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> Buffer { + let tile = tile.max(1); + // Lab documents mix Normal blending in CIELAB, as Photoshop does (psblend::LAB_MIX); 32-bit + // documents don't clip Add / Divide or Hue / Saturation / Color / Luminosity at 1 (psblend::HDR). + let lab = doc.mode == photocraft_color::ColorMode::Lab; + let hdr = doc.depth == photocraft_color::SampleType::F32; + // CMYK layers are read through the document's own CMYK profile (thread-local scope). + let cmyk = cmyk_space(doc); + let cmyk = cmyk.as_ref(); + if rect.is_empty() { + return Buffer::transparent(rect); + } + // Refuse rects too large to hold: an empty buffer, not an allocation failure. + if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS { + return Buffer::transparent(Rect::EMPTY); + } + // A CMYK stack with adjustment layers the inks carry exactly composites on its inks. + if let Some(buf) = native::render_cmyk(doc, rect, tile) { + return buf; + } + // A Lab stack with adjustment layers that work on L, a and b composites on its stored values. + if let Some(buf) = native_lab::render_lab(doc, rect, tile) { + return buf; + } + cx.set_fx_clip(rect); + if i64::from(rect.width()) <= i64::from(tile) && i64::from(rect.height()) <= i64::from(tile) { + return photocraft_color::convert::with_cmyk_space(cmyk, || { + let mut buf = multichannel::backdrop(doc, rect); + in_blend_space(lab, hdr, || composite_stack_at(&doc.layers, &mut buf, cx, advanced::Scope::ROOT)); + buf + }); + } + // Effect maps are built once, here, before any tile needs them (#276). + prepare_effects(&doc.layers, rect, cx, |f| { + photocraft_color::convert::with_cmyk_space(cmyk, || in_blend_space(lab, hdr, f)); + }); + let run = |t: Rect| { + photocraft_color::convert::with_cmyk_space(cmyk, || { + let mut b = multichannel::backdrop(doc, t); + in_blend_space(lab, hdr, || composite_stack_at(&doc.layers, &mut b, cx, advanced::Scope::ROOT)); + b + }) + }; + // Tiles are written straight into the output, one row of tiles (a band) at a time, so the + // peak is the output plus the tiles in flight, not a second full-size copy. + let w = rect.width() as usize; + let mut out = Buffer::transparent(rect); + let band_tiles = |y0: i32| { + let y1 = y0.saturating_add(tile).min(rect.y1); + let mut v = Vec::new(); + let mut x = rect.x0; + while x < rect.x1 { + let x1 = x.saturating_add(tile).min(rect.x1); + v.push(Rect::new(x, y0, x1, y1)); + x = x1; + } + v + }; + let put = |band: &mut [[f32; 4]], y0: i32, part: &Buffer| { + let pw = part.rect.width() as usize; + for (row, src) in part.px.chunks_exact(pw).enumerate() { + let o = ((part.rect.y0 - y0) as usize + row) * w + (part.rect.x0 - rect.x0) as usize; + band[o..o + pw].copy_from_slice(src); + } + }; + let band_len = w * tile as usize; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + let bands = rect.height().div_ceil(tile as u32) as usize; + if bands >= 2 * rayon::current_num_threads() { + // Enough bands to keep every core busy: one band per task, its tiles in turn. + out.px.par_chunks_mut(band_len).enumerate().for_each(|(i, band)| { + let y0 = rect.y0 + i as i32 * tile; + for t in band_tiles(y0) { + put(band, y0, &run(t)); + } + }); + } else { + // Few, wide bands: the tiles of each band in parallel, and the bands too, so a band's + // slowest tile doesn't leave the other cores idle until the next band starts. Each + // tile is written as soon as it is done, so only the tiles in flight are held. + out.px.par_chunks_mut(band_len).enumerate().for_each(|(i, band)| { + let y0 = rect.y0 + i as i32 * tile; + let band = std::sync::Mutex::new(band); + band_tiles(y0).into_par_iter().for_each(|t| { + let part = run(t); + let mut band = band.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + put(&mut band, y0, &part); + }); + }); + } + } + #[cfg(target_arch = "wasm32")] + for (i, band) in out.px.chunks_mut(band_len).enumerate() { + let y0 = rect.y0 + i as i32 * tile; + for t in band_tiles(y0) { + put(band, y0, &run(t)); + } + } + out +} + +/// Runs `f` with this thread's document blend flags set ([`psblend::LAB_MIX`], [`psblend::HDR`]), +/// then restores the values they had (also on unwind): a nested rayon job can run another tile +/// on this thread mid-composite, and clearing the flags there broke the outer tile (#1112). +pub(crate) fn in_blend_space(lab: bool, hdr: bool, f: impl FnOnce() -> R) -> R { + psblend::with_lab_mix(lab, || psblend::with_hdr(hdr, f)) +} + +/// The document's own CMYK profile for reading its CMYK pixels (`None`: not a CMYK document, +/// untagged, or the built-in coated CMYK). Enter it with `photocraft_color::convert::with_cmyk_space` +/// around code that converts the document's CMYK pixels or colours to RGB. +pub fn cmyk_space(doc: &Document) -> Option> { + if doc.mode != photocraft_color::ColorMode::Cmyk { + return None; + } + photocraft_color::convert::CmykSpace::for_profile(doc.icc_profile.as_ref()) +} + +/// Pixels per band of [`render_bands`] (a 14000 px wide band is ~600 rows, ~130 MB of f32). +pub const BAND_PIXELS: u64 = 8 << 20; + +/// Composite `rect` in horizontal bands, top to bottom, handing each band to `sink` (tiles inside +/// a band render in parallel). Peak memory is one band instead of the whole composite, so huge +/// documents can be exported or displayed without a full-size float copy. `band_rows` of 0 picks +/// about [`BAND_PIXELS`] per band; bands are whole multiples of [`RENDER_TILE`] rows. +pub fn render_bands(doc: &Document, rect: Rect, band_rows: i32, mut sink: impl FnMut(Buffer) -> Result<(), E>) -> Result<(), E> { + if rect.is_empty() { + return Ok(()); + } + // Keep prepared pixels and compiled vector masks across bands without retaining any rendered band. + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + let cx = Ctx::for_doc(doc, &patterns); + let rows = band_rows_for(rect.width(), band_rows); + let mut y = rect.y0; + while y < rect.y1 { + let y1 = y.saturating_add(rows).min(rect.y1); + sink(render_tiled_with(doc, Rect::new(rect.x0, y, rect.x1, y1), RENDER_TILE, &cx))?; + y = y1; + } + Ok(()) +} + +/// Band height for [`render_bands`]: `requested` rounded up to whole tiles, or ~[`BAND_PIXELS`]. +pub fn band_rows_for(width: u32, requested: i32) -> i32 { + let want = if requested > 0 { i64::from(requested) } else { (BAND_PIXELS / u64::from(width.max(1))) as i64 }; + let tiles = (want + i64::from(RENDER_TILE) - 1) / i64::from(RENDER_TILE); + (tiles.clamp(1, 1 << 16) * i64::from(RENDER_TILE)) as i32 +} + +/// The document's composite as a pixel surface in `fmt` (straight RGBA converted to its model +/// and depth), optionally flattened over an opaque `background`; rendered and written in bands, +/// so no full-size float composite is held. Tiles equal to the default pixel are pruned. +/// +/// Fully transparent pixels are written as the default pixel. Converting transparent black +/// leaves colour behind in CMYK (K = 100%) and Lab (neutral a/b = 0.5), and those pixels would +/// otherwise count as content: the result would span the whole canvas. +/// +/// A CMYK document flattened to CMYK is composited in its ink values instead, so flattening +/// doesn't round-trip its pixels through RGB: plain Normal layers by [`native::flatten_cmyk`] +/// (#3778), and masks, groups, clipping, other blend modes and the other layer kinds by [`cmyk`] +/// where its layers mix on their inks (#2220). Otherwise the composite goes back to CMYK through +/// the document's own profile, the one its layers were read through. A Lab document of plain +/// layers is composited in its L, a and b ([`native_lab::flatten_lab`]). +pub fn flatten_to_surface(doc: &Document, fmt: photocraft_color::PixelFormat, background: Option<[f32; 3]>) -> Surface { + composite_to_surface(doc, doc.bounds(), fmt, background) +} + +/// [`flatten_to_surface`] over `rect` only (the rest of the surface stays empty). +pub fn composite_to_surface(doc: &Document, rect: Rect, fmt: photocraft_color::PixelFormat, background: Option<[f32; 3]>) -> Surface { + let paper = background.is_some_and(|bg| bg == [1.0; 3]); + if (background.is_none() || paper) + && let Some(s) = native::flatten_cmyk(doc, rect, fmt, paper) + { + return s; + } + if (background.is_none() || paper) + && let Some(s) = native_lab::flatten_lab(doc, rect, fmt, paper) + { + return s; + } + let space = cmyk_space(doc); + let to_cmyk = fmt.mode == photocraft_color::ColorMode::Cmyk && doc.mode == photocraft_color::ColorMode::Cmyk; + if to_cmyk && cmyk::renders_inks(doc) { + return composite_inks_to_surface(doc, rect, fmt, background, space.as_ref()); + } + // The composite separates back to CMYK through the document's own profile, the one its + // pixels were read through. + let mut s = Surface::new(fmt); + let n = fmt.channels(); + let empty = s.default_pixel(); + let mut data = Vec::new(); + let _ = render_bands(doc, rect, 0, |band| -> Result<(), ()> { + let band = match background { + Some(bg) => band.over_background(bg), + None => band, + }; + data.clear(); + data.resize(band.px.len() * n, 0.0); + photocraft_color::convert::with_cmyk_space(space.as_ref(), || { + for (p, out) in band.px.iter().zip(data.chunks_exact_mut(n)) { + if fmt.alpha && (p[3] <= 0.0 || p[3].is_nan()) && empty.len() == n { + out.copy_from_slice(&empty); + } else { + photocraft_raster::from_rgba_into(&fmt, *p, out); + } + } + }); + s.write_region(band.rect, &data); + Ok(()) + }); + s.prune(); + s +} + +/// One CMYK pixel's output channels into `data`: its inks (over `paper` when given) and alpha. +fn push_ink_pixel(data: &mut Vec, p: &[f32; 5], paper: Option<[f32; 4]>, fmt: photocraft_color::PixelFormat, empty: &[f32]) { + if paper.is_none() && fmt.alpha && (p[4] <= 0.0 || p[4].is_nan()) && empty.len() == fmt.channels() { + data.extend_from_slice(empty); + return; + } + // Over the paper (fully covered pixels keep their inks exactly), or straight. + let ink = |c: usize| match paper { + Some(bg) if p[4] < 1.0 => p[c] * p[4] + bg[c] * (1.0 - p[4]), + _ => p[c], + }; + data.extend((0..4).map(ink)); + if fmt.alpha { + data.push(if paper.is_some() { 1.0 } else { p[4] }); + } +} + +/// [`composite_to_surface`] for a CMYK document flattened to CMYK, composited in its inks. +fn composite_inks_to_surface( + doc: &Document, + rect: Rect, + fmt: photocraft_color::PixelFormat, + background: Option<[f32; 3]>, + space: Option<&std::sync::Arc>, +) -> Surface { + let mut s = Surface::new(fmt); + let n = fmt.channels(); + let empty = s.default_pixel(); + let mut data = Vec::new(); + // White paper is no ink; another background colour goes through the profile. + let paper = background + .map(|bg| if bg == [1.0; 3] { [0.0; 4] } else { photocraft_color::convert::with_cmyk_space(space, || photocraft_color::convert::rgb_to_cmyk(bg)) }); + let _ = cmyk::render_cmyk_bands(doc, rect, 0, |band| -> Result<(), ()> { + data.clear(); + data.reserve(band.px.len() * n); + for p in &band.px { + push_ink_pixel(&mut data, p, paper, fmt, &empty); + } + s.write_region(band.rect, &data); + Ok(()) + }); + s.prune(); + s +} + +/// Composite the full canvas. +pub fn flatten(doc: &Document) -> Buffer { + render(doc, doc.bounds()) +} + +/// Render an arbitrary subset: a single layer (e.g. for thumbnails), isolated. +/// Rects past [`MAX_RENDER_PIXELS`] give an empty buffer. +pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer { + if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS { + return Buffer::transparent(Rect::EMPTY); + } + let mut buf = Buffer::transparent(rect); + let patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES); + composite_stack_at( + std::slice::from_ref(layer), + &mut buf, + &Ctx { + canvas: rect, + transfer: adjust::Transfer::Srgb, + light: photocraft_doc::GlobalLight::default(), + patterns: &patterns, + mode: photocraft_color::ColorMode::Rgb, + depth: photocraft_color::SampleType::F32, + vector_masks: RenderVectorMasks::default(), + fx_maps: Default::default(), + fx_clip: Default::default(), + fx_over_budget: false, + tone_luts: prepare_tones(std::slice::from_ref(layer), 0), + doc: None, + layer_keys: Default::default(), + }, + advanced::Scope::ROOT, + ); + buf +} + +/// [`render_layer`] in `doc`'s context: the layer alone over `rect`, with the document's patterns, +/// Global Light, colour mode, depth and canvas (fill layers and gradients are laid out on it), as +/// the canvas composites it. Bakes (Scripts › Flatten All Layer Effects) render through this so +/// the pixels match what was on screen (#5719). Rects past [`MAX_RENDER_PIXELS`] give an empty +/// buffer. +pub fn render_layer_in(doc: &Document, layer: &Layer, rect: Rect) -> Buffer { + if rect.is_empty() { + return Buffer::transparent(rect); + } + if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS { + return Buffer::transparent(Rect::EMPTY); + } + let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode); + // A lone layer: a deep knockout reveals transparency, not the document's Background. + let cx = Ctx { doc: None, ..Ctx::for_doc(doc, &patterns) }; + let lab = doc.mode == photocraft_color::ColorMode::Lab; + let hdr = doc.depth == photocraft_color::SampleType::F32; + let cmyk = cmyk_space(doc); + photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || { + let mut buf = Buffer::transparent(rect); + in_blend_space(lab, hdr, || composite_stack_at(std::slice::from_ref(layer), &mut buf, &cx, advanced::Scope::ROOT)); + buf + }) +} From 32588fb0acf3a141b3cbaf4250494da5a3c10e44 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 18:49:39 +0000 Subject: [PATCH 246/259] refactor(compose): split effects.rs into effects/ --- crates/compose/src/effects.rs | 2253 +---------------------- crates/compose/src/effects/bevel.rs | 284 +++ crates/compose/src/effects/blur.rs | 212 +++ crates/compose/src/effects/composite.rs | 533 ++++++ crates/compose/src/effects/distance.rs | 810 ++++++++ crates/compose/src/effects/paint.rs | 402 ++++ 6 files changed, 2268 insertions(+), 2226 deletions(-) create mode 100644 crates/compose/src/effects/bevel.rs create mode 100644 crates/compose/src/effects/blur.rs create mode 100644 crates/compose/src/effects/composite.rs create mode 100644 crates/compose/src/effects/distance.rs create mode 100644 crates/compose/src/effects/paint.rs diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index 8bd761fd09..adf0b7a7b0 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -32,6 +32,33 @@ use photocraft_geom::Rect; use crate::pattern::{PREPARED_PATTERN_BYTES, Placement, PreparedPatterns}; use crate::{Buffer, psblend}; +mod bevel; +mod blur; +mod composite; +mod distance; +mod paint; + +pub use bevel::{BEVEL_H_EPS, BevelGeom, BevelPaint, TextureCtx, bevel_chisel_h, bevel_geom, satin_distance}; +#[cfg(test)] +use bevel::{bevel_maps, satin_map}; +pub use blur::tent_kernel; +#[cfg(test)] +use blur::{blur, box_line, dilate, tent, tent_direct}; +pub(crate) use composite::{VectorStroke, build_maps_prepared, composite_with_effects_prepared, map_count}; +pub use composite::{build_maps, composite_with_effects, outline_share, premerges_layer, shadow_see_through, stroke_widths}; +pub use distance::{FieldKind, STROKE_CHAMFER_MAX, bevel_distance_fields, distance_field, stroke_outside_exact}; +#[cfg(test)] +use distance::{ + SharpEdges, THREADS, bevel_dist_inside, bevel_dist_outside, chamfer_nearest, dist_inside, dist_outside, edge_offset, edt, edt_nearest, par_units, + sharp_edges, +}; +use paint::dissolves; +pub use paint::{ + bevel_contour_lut, glow_gradient_gain, glow_lut, gradient_t, gradient_units, hash_noise, ranged_lut, sample_gradient, satin_lut, spread_split, +}; +#[cfg(test)] +use paint::{glow_map, lut_at, noise, offset, shadow_map}; + /// `true` if the layer has at least one enabled effect and the master switch is on. pub fn has_effects(layer: &Layer) -> bool { layer.effects.enabled && layer.effects.items.iter().any(Effect::enabled) @@ -149,1617 +176,6 @@ impl Map { } } -/// 1D squared distance transform (Felzenszwalb & Huttenlocher). -fn dt1(f: &[f32], out: &mut [f32], v: &mut [usize], z: &mut [f32], near: &mut [usize]) { - let n = f.len(); - let mut k = 0usize; - v[0] = 0; - z[0] = f32::NEG_INFINITY; - z[1] = f32::INFINITY; - for q in 1..n { - loop { - let p = v[k]; - let s = ((f[q] + (q * q) as f32) - (f[p] + (p * p) as f32)) / (2.0 * q as f32 - 2.0 * p as f32); - if s <= z[k] && k > 0 { - k -= 1; - continue; - } - if s <= z[k] { - // k == 0 and parabola dominates: replace. - v[0] = q; - z[0] = f32::NEG_INFINITY; - z[1] = f32::INFINITY; - break; - } - k += 1; - v[k] = q; - z[k] = s; - z[k + 1] = f32::INFINITY; - break; - } - } - k = 0; - for (q, o) in out.iter_mut().enumerate() { - while z[k + 1] < q as f32 { - k += 1; - } - let p = v[k]; - let d = q as f32 - p as f32; - *o = d * d + f[p]; - near[q] = p; - } -} - -/// Exact Euclidean distance from every pixel to the nearest pixel where -/// `inside` is true (0 on those pixels). -#[cfg(test)] -fn edt(inside: &[bool], w: usize, h: usize) -> Vec { - edt_nearest(inside, w, h).0 -} - -/// Maps with fewer pixels (or other units of work) than this are not worth spawning threads for. -const PAR_MIN: usize = 1 << 16; - -/// Most threads one pass uses (as for the blurs, [`rows_par`]). -const PAR_THREADS: usize = 16; - -#[cfg(test)] -thread_local! { - /// Test hook: the thread count [`par_threads`] gives on this thread, whatever the work. - static THREADS: std::cell::Cell> = const { std::cell::Cell::new(None) }; -} - -/// How many threads a pass over `work` pixels (or similar units) uses. -fn par_threads(work: usize) -> usize { - #[cfg(test)] - if let Some(n) = THREADS.with(std::cell::Cell::get) { - return n; - } - if cfg!(target_arch = "wasm32") || work < PAR_MIN { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, PAR_THREADS) } -} - -/// Runs `f(scratch, u, a_u, b_u)` for every unit `u` of two slices: unit `u` of `a` is -/// `a[u * unit_a..][..unit_a]` (the last may be shorter), the same of `b` with `unit_b`, which is 0 -/// when there is no second slice. `work` says how big the whole pass is ([`par_threads`]). Groups of -/// units go to scoped OS threads, each with a scratch value from `init`; not to rayon, as for -/// [`rows_par`]: maps are built from inside rayon tiles, where a waiting worker steals other tiles. -/// A unit is computed from its own arguments alone, so the result does not depend on the threads. -fn par_units( - work: usize, - a: &mut [A], - unit_a: usize, - b: &mut [B], - unit_b: usize, - init: impl Fn() -> S + Sync, - f: impl Fn(&mut S, usize, &mut [A], &mut [B]) + Sync, -) { - if unit_a == 0 { - return; - } - let units = a.len().div_ceil(unit_a); - let threads = par_threads(work).min(units); - if threads <= 1 { - run_units(&mut init(), 0, a, unit_a, b, unit_b, &f); - return; - } - // Many more groups than threads, so that a heavy one (an edge-rich stretch) does not hold the rest up. - let group = units.div_ceil(threads * 8).max(1); - let mut groups = Vec::new(); - let (mut rest_a, mut rest_b, mut first) = (a, b, 0usize); - while !rest_a.is_empty() { - let (ga, na) = rest_a.split_at_mut((group * unit_a).min(rest_a.len())); - let (gb, nb) = rest_b.split_at_mut((group * unit_b).min(rest_b.len())); - groups.push((first, ga, gb)); - (rest_a, rest_b, first) = (na, nb, first + group); - } - let queue = std::sync::Mutex::new(groups.into_iter()); - let worker = || { - let mut scratch = init(); - loop { - let next = queue.lock().unwrap_or_else(std::sync::PoisonError::into_inner).next(); - let Some((first, ga, gb)) = next else { break }; - run_units(&mut scratch, first, ga, unit_a, gb, unit_b, &f); - } - }; - std::thread::scope(|sc| { - // A thread that cannot be spawned leaves its share to the others. - for _ in 1..threads { - let _ = std::thread::Builder::new().spawn_scoped(sc, worker); - } - worker(); - }); -} - -fn run_units(scratch: &mut S, first: usize, a: &mut [A], unit_a: usize, b: &mut [B], unit_b: usize, f: &impl Fn(&mut S, usize, &mut [A], &mut [B])) { - for (k, ua) in a.chunks_mut(unit_a).enumerate() { - let ub = b.get_mut(k * unit_b..((k + 1) * unit_b).min(b.len())).unwrap_or(&mut []); - f(scratch, first + k, ua, ub); - } -} - -/// A `w × h` buffer of `fill`, then filled row by row through `f(y, row)`. -fn par_fill(w: usize, h: usize, fill: T, f: impl Fn(usize, &mut [T]) + Sync) -> Vec { - let mut out = vec![fill; w.saturating_mul(h)]; - par_units(out.len(), &mut out, w.max(1), &mut [] as &mut [()], 0, || (), |_, y, row, _| f(y, row)); - out -} - -/// Working buffers of the 1D distance transform, for lines of up to `n` pixels. -struct Dt1Scratch { - f: Vec, - o: Vec, - v: Vec, - z: Vec, - near: Vec, -} - -impl Dt1Scratch { - fn new(n: usize) -> Self { - Dt1Scratch { f: vec![0.0; n], o: vec![0.0; n], v: vec![0; n], z: vec![0.0; n + 1], near: vec![0; n] } - } -} - -/// [`edt`] plus the index of the nearest `inside` pixel (as `u32`: a map past 2³² pixels has no -/// nearest pixel to give, and every distance is then "far"). -/// -/// Both passes run line by line in parallel: the columns, then the rows. The columns' results are -/// kept column by column (`gc[x * h + y]`) so that each thread writes its own stretch of them. -fn edt_nearest(inside: &[bool], w: usize, h: usize) -> (Vec, Vec) { - const INF: f32 = 1e20; - let total = w.saturating_mul(h); - if total != inside.len() || total > u32::MAX as usize { - return (vec![INF; inside.len()], vec![0; inside.len()]); - } - let n = w.max(h); - let mut gc = vec![0.0f32; total]; - let mut nc = vec![0u32; total]; - par_units( - total, - &mut gc, - h.max(1), - &mut nc, - h.max(1), - || Dt1Scratch::new(n), - |t, x, g, near| { - for (y, f) in t.f[..h].iter_mut().enumerate() { - *f = if inside[y * w + x] { 0.0 } else { INF }; - } - dt1(&t.f[..h], &mut t.o[..h], &mut t.v, &mut t.z, &mut t.near[..h]); - g.copy_from_slice(&t.o[..h]); - for (d, &p) in near.iter_mut().zip(&t.near[..h]) { - *d = p as u32; - } - }, - ); - let mut g = vec![0.0f32; total]; - let mut nearest = vec![0u32; total]; - par_units( - total, - &mut g, - w.max(1), - &mut nearest, - w.max(1), - || Dt1Scratch::new(n), - |t, y, out, near| { - for (x, f) in t.f[..w].iter_mut().enumerate() { - *f = gc[x * h + y]; - } - dt1(&t.f[..w], &mut t.o[..w], &mut t.v, &mut t.z, &mut t.near[..w]); - for (x, (d, ne)) in out.iter_mut().zip(near.iter_mut()).enumerate() { - *d = t.o[x].sqrt(); - let px = t.near[x]; - *ne = (nc[px * h + y] as usize * w + px) as u32; - } - }, - ); - (g, nearest) -} - -/// Chamfer distance transform with a 5 × 5 mask of exact Euclidean step lengths (1, √2, √5), -/// plus the index of the nearest `inside` pixel (0 on inside pixels). Photoshop's effect -/// distances follow this metric: its stroke corners measure 3.236 = √5 + 1 at offset (1, 3) -/// and 3.650 = √5 + √2 at (2, 3), where the exact distances are 3.162 and 3.606. -#[cfg(test)] -fn chamfer_nearest(inside: &[bool], w: usize, h: usize) -> (Vec, Vec) { - chamfer_from(inside.iter().map(|&b| if b { 0.0 } else { CHAMFER_INF }).collect(), w, h) -} - -const CHAMFER_INF: f32 = 1e20; - -/// [`chamfer_nearest`] from per-pixel start values (`CHAMFER_INF` = not a seed): the result is -/// the minimum over seeds of start value + path length, so partly covered seeds can start at -/// their sub-pixel edge offset. -fn chamfer_from(mut d: Vec, w: usize, h: usize) -> (Vec, Vec) { - const S2: f32 = std::f32::consts::SQRT_2; - const S5: f32 = 2.236_068; - // Forward-pass neighbours (already visited in raster order); the backward pass mirrors them. - const FWD: [(i64, i64, f32); 8] = [(-1, 0, 1.0), (-1, -1, S2), (0, -1, 1.0), (1, -1, S2), (-1, -2, S5), (1, -2, S5), (-2, -1, S5), (2, -1, S5)]; - let mut near: Vec = (0..w * h).collect(); - let (wi, hi) = (w as i64, h as i64); - let relax = |x: i64, y: i64, sign: i64, d: &mut Vec, near: &mut Vec| { - let i = (y * wi + x) as usize; - let mut best = d[i]; - let mut bn = near[i]; - for &(ox, oy, wt) in &FWD { - let (nx, ny) = (x + ox * sign, y + oy * sign); - if nx < 0 || ny < 0 || nx >= wi || ny >= hi { - continue; - } - let j = (ny * wi + nx) as usize; - let c = d[j] + wt; - if c < best { - best = c; - bn = near[j]; - } - } - d[i] = best; - near[i] = bn; - }; - for y in 0..hi { - for x in 0..wi { - relax(x, y, 1, &mut d, &mut near); - } - } - for y in (0..hi).rev() { - for x in (0..wi).rev() { - relax(x, y, -1, &mut d, &mut near); - } - } - (d, near) -} - -/// Distance from each pixel centre outside the shape to the shape's edge. -/// Pixels with non-zero alpha are inside; the edge inside the nearest such -/// pixel is placed by its alpha (coverage), as Photoshop does. Inside pixels -/// get ≤ 0. -fn dist_outside(s: &Map) -> Vec { - dist_outside_by(s, Metric::Euclidean) -} - -/// Distance metric for effect distance fields. -#[derive(Clone, Copy, PartialEq)] -enum Metric { - /// Exact Euclidean (effect edges). - Euclidean, - /// 5 × 5 chamfer (inside strokes, spread / choke; see [`chamfer_nearest`]). - Chamfer, -} - -/// Outside width from which a stroke's outer edge uses the exact Euclidean transform instead of -/// the fitted 5 × 5 chamfer. -/// -/// The chamfer's level sets are octagons: measured against a point source, its distance exceeds -/// the Euclidean radius by up to `0.027 · r` px — 0.48 px at r = 18 (the widest outside stroke any -/// Photoshop oracle matches with the chamfer) and 1.6 px at r = 60, where a wide stroke's boundary -/// visibly facets (#3646). Half a pixel of deviation is reached at r ≈ 19, so strokes narrower -/// than 20 px keep the chamfer, whose sub-pixel edge seeding Photoshop matches at small offsets, -/// and wider ones stay round. -pub const STROKE_CHAMFER_MAX: f32 = 20.0; - -/// Whether a stroke whose outside edge is `out_w` px wide uses the exact Euclidean transform (round) -/// rather than the 5 × 5 chamfer's octagon ([`STROKE_CHAMFER_MAX`]). The CPU compositor and the GPU -/// compositor's `program_with` both call this, so a stroke picks the same field in each. -pub fn stroke_outside_exact(out_w: f32) -> bool { - out_w >= STROKE_CHAMFER_MAX -} - -fn dist_outside_by(s: &Map, m: Metric) -> Vec { - if m == Metric::Chamfer { - // Seeds start at their sub-pixel edge offset (1 − coverage). - let start = s.v.iter().map(|&a| if a > INSIDE_EPS { 1.0 - a.min(1.0) } else { CHAMFER_INF }).collect(); - let (d, _) = chamfer_from(start, s.w, s.h); - return d.iter().zip(&s.v).map(|(d, &a)| if a > INSIDE_EPS { -0.5 } else { d - 0.5 }).collect(); - } - let inside = covered(s, |a| a > INSIDE_EPS); - let (d, near) = edt_nearest(&inside, s.w, s.h); - par_fill(s.w, s.h, 0.0f32, |y, row| { - for (x, out) in row.iter_mut().enumerate() { - let i = y * s.w + x; - *out = if inside[i] { -0.5 } else { d[i] - 0.5 + (1.0 - s.v[near[i] as usize].min(1.0)) }; - } - }) -} - -/// Which pixels of `s` satisfy `test`, row by row in parallel. -fn covered(s: &Map, test: impl Fn(f32) -> bool + Sync) -> Vec { - par_fill(s.w, s.h, false, |y, row| { - for (e, &a) in row.iter_mut().zip(s.v.get(y * s.w..).unwrap_or_default()) { - *e = test(a); - } - }) -} - -/// Distance from each pixel centre inside the shape to the shape's edge -/// (≤ 0 outside). -fn dist_inside(s: &Map) -> Vec { - dist_inside_by(s, Metric::Euclidean) -} - -fn dist_inside_by(s: &Map, m: Metric) -> Vec { - if m == Metric::Chamfer { - // Partly covered edge pixels (alpha below their neighbourhood's) are seeds starting at - // their coverage, mirroring `dist_outside`: a 25 % edge column puts the edge 0.25 px in. - let cov = local_coverage(s); - let start = - s.v.iter() - .zip(&cov.v) - .map(|(&a, &c)| { - if a <= INSIDE_EPS { - 0.0 - } else if c < 1.0 - INSIDE_EPS { - c - } else { - CHAMFER_INF - } - }) - .collect(); - let (d, _) = chamfer_from(start, s.w, s.h); - return d.iter().zip(&s.v).map(|(d, &a)| if a <= INSIDE_EPS { -0.5 } else { d - 0.5 }).collect(); - } - let outside = covered(s, |a| a <= INSIDE_EPS); - let (d, _) = edt_nearest(&outside, s.w, s.h); - par_fill(s.w, s.h, 0.0f32, |y, row| { - for (x, out) in row.iter_mut().enumerate() { - let i = y * s.w + x; - *out = if outside[i] { -0.5 } else { d[i] - 0.5 }; - } - }) -} - -/// Alpha relative to the 3×3 neighbourhood maximum: separates edge coverage -/// from the fill's own opacity on shape layers. -fn local_coverage(s: &Map) -> Map { - let mut out = s.clone(); - for y in 0..s.h as i64 { - for x in 0..s.w as i64 { - let a = s.get(x, y); - if a <= INSIDE_EPS { - continue; - } - let mut mx = a; - for dy in -1..=1 { - for dx in -1..=1 { - mx = mx.max(s.get(x + dx, y + dy)); - } - } - out.v[y as usize * s.w + x as usize] = (a / mx).min(1.0); - } - } - out -} - -/// Signed distance from the centre of a pixel of coverage `a` to the straight edge crossing it, -/// positive when the centre is inside the shape. `n` is the edge's unit normal (its signs don't -/// matter). -/// -/// A unit pixel cut by a straight edge at distance `r` from its centre (on the side that holds at -/// most half of the pixel) is covered `1/2 - r/u` while the edge crosses two opposite sides, and -/// `((u + v)/2 - r)² / (2uv)` once it only cuts off a corner, with `u ≥ v` the larger and smaller -/// component of the normal. Inverting that places the edge by its coverage at any angle. For an -/// axis-aligned edge (`v = 0`) it is the `a - 1/2` that [`dist_outside`] assumes. -fn edge_offset(n: [f32; 2], a: f32) -> f32 { - if !a.is_finite() { - return 0.0; - } - let (u, v) = (n[0].abs().max(n[1].abs()), n[0].abs().min(n[1].abs())); - let (c, inside) = if a > 0.5 { (1.0 - a, true) } else { (a, false) }; - let c = c.clamp(0.0, 0.5); - // The coverage below which the edge only cuts off a corner. - let corner = if u > 0.0 { v / (2.0 * u) } else { 0.0 }; - let r = if c >= corner { (0.5 - c) * u } else { 0.5 * (u + v) - (2.0 * u * v * c).sqrt() }; - if inside { r } else { -r } -} - -/// A sharp, anti-aliased edge pixel: where it puts the straight edge crossing it. -#[derive(Clone, Copy)] -struct SharpEdge { - /// Signed distance from the pixel's centre to the edge, positive inside ([`edge_offset`]). - offset: f32, - /// The edge's unit normal pointing into the shape (`[0, 0]` when the coverage gives no direction). - normal: [f32; 2], -} - -/// Half the spacing of the edge pixels along an edge (at most √2 / 2, along a diagonal): a pixel -/// within it of the foot of the perpendicular sees the edge as a line, one further out as its end. -const EDGE_REACH: f32 = 0.75; - -impl SharpEdge { - /// Distance to the edge from the pixel `(dx, dy)` away from this one, positive on the shape's - /// side (`inside`) or on the empty side. It is the distance to the edge's line where the - /// perpendicular lands within [`EDGE_REACH`] of this pixel, and to the end of that stretch - /// beyond, so the distance to a straight edge is exact and does not follow the pixel staircase. - /// `None` when the edge has no direction or `(dx, dy)` is on the wrong side of it. - fn distance(&self, dx: f32, dy: f32, inside: bool) -> Option { - let [nx, ny] = self.normal; - if nx == 0.0 && ny == 0.0 { - return None; - } - let signed = self.offset + dx * nx + dy * ny; - let across = if inside { signed } else { -signed }; - let along = (dx * -ny + dy * nx).abs(); - (across > 0.0).then(|| across.hypot((along - EDGE_REACH).max(0.0))) - } -} - -/// A sharp edge pixel and where it sits. -#[derive(Clone, Copy)] -struct EdgePixel { - /// Index of the pixel in the map. - at: u32, - /// The pixel's coverage ([`local_coverage`] of it). - cov: f32, - edge: SharpEdge, -} - -/// The sharp edge pixels of a map: a short list, and for every pixel a 4 byte slot (0 = no edge, k = -/// the k-th of the list). Maps are big and edge pixels few, so a per-pixel `Option` (16 -/// bytes) made every pass over it, and the copies the refinement needs, memory-bound. -struct SharpEdges { - w: usize, - h: usize, - slot: Vec, - pixels: Vec, -} - -impl SharpEdges { - fn empty(w: usize, h: usize) -> Self { - SharpEdges { w, h, slot: Vec::new(), pixels: Vec::new() } - } - - /// The edge of pixel `i`, if it is a sharp edge pixel. - fn get(&self, i: usize) -> Option { - let k = (*self.slot.get(i)? as usize).checked_sub(1)?; - self.pixels.get(k).map(|p| p.edge) - } - - /// The edge of pixel `(x, y)`, if it is a sharp edge pixel (`None` off the map). - fn at(&self, x: usize, y: usize) -> Option { - if x >= self.w || y >= self.h { None } else { self.get(y * self.w + x) } - } - - fn has(&self, x: usize, y: usize) -> bool { - self.at(x, y).is_some() - } - - fn is_empty(&self) -> bool { - self.pixels.is_empty() - } - - /// Every sharp edge pixel, as (index in the map, its edge), in pixel order. - #[cfg(test)] - fn iter(&self) -> impl Iterator + '_ { - self.pixels.iter().map(|p| (p.at as usize, p.edge)) - } -} - -/// Where the sharp, anti-aliased edge pixels of `s` put the edge ([`edge_offset`], along the normal -/// the coverage gradient gives). Sharp pixels are partly covered and touch both an empty and a full -/// pixel; hard edges and soft ramps have none and keep the `alpha - 1/2` of [`dist_outside`]. -/// -/// An edge pixel is covered and has an empty neighbour, so a pass over which pixels are covered finds -/// the few candidates without computing [`local_coverage`] of the whole map; the coverage is then -/// worked out where it is needed, by the same formula. Rows are independent and go in parallel. -fn sharp_edges(s: &Map) -> SharpEdges { - let (w, h) = (s.w, s.h); - if w == 0 || h == 0 || s.v.len() != w * h || s.v.len() >= u32::MAX as usize { - return SharpEdges::empty(w, h); - } - let (wi, hi) = (w as i64, h as i64); - // `local_coverage` of the pixel at (x, y), on the map. - let cov_at = |x: i64, y: i64| -> f32 { - let a = s.v[y as usize * w + x as usize]; - if a <= INSIDE_EPS { - return a; - } - let mut mx = a; - for dy in -1..=1 { - for dx in -1..=1 { - mx = mx.max(s.get(x + dx, y + dy)); - } - } - (a / mx).min(1.0) - }; - // The coverage with the map's border repeated, for the gradient. - let cov_clamped = |x: i64, y: i64| cov_at(x.max(0).min(wi - 1), y.max(0).min(hi - 1)); - // Whether a pixel is not empty. Off the map counts as covered: only a neighbour on the map can be empty. - let solid = |x: i64, y: i64| -> bool { - if x < 0 || y < 0 || x >= wi || y >= hi { - return true; - } - let a = s.v[y as usize * w + x as usize]; - a.is_nan() || a > INSIDE_EPS - }; - let mut rows: Vec> = vec![Vec::new(); h]; - par_units( - w * h, - &mut rows, - 1, - &mut [] as &mut [()], - 0, - || (), - |_, y, row, _| { - let Some(row) = row.first_mut() else { return }; - let y = y as i64; - for x in 0..wi { - if !solid(x, y) || (-1..=1).all(|dy| (-1..=1).all(|dx| solid(x + dx, y + dy))) { - continue; - } - let i = (y * wi + x) as usize; - let c = cov_at(x, y); - if s.v[i] <= INSIDE_EPS || c >= 1.0 - INSIDE_EPS { - continue; - } - let (mut empty, mut full) = (false, false); - for (dx, dy) in (-1..=1).flat_map(|dy| (-1..=1).map(move |dx| (dx, dy))) { - let (nx, ny) = (x + dx, y + dy); - if (dx, dy) == (0, 0) || nx < 0 || ny < 0 || nx >= wi || ny >= hi { - continue; - } - empty |= s.get(nx, ny) <= INSIDE_EPS; - full |= cov_at(nx, ny) >= 1.0 - INSIDE_EPS; - } - if !(empty && full) { - continue; - } - let at = &cov_clamped; - let gx = (at(x + 1, y - 1) + 2.0 * at(x + 1, y) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2.0 * at(x - 1, y) + at(x - 1, y + 1)); - let gy = (at(x - 1, y + 1) + 2.0 * at(x, y + 1) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2.0 * at(x, y - 1) + at(x + 1, y - 1)); - let len = gx.hypot(gy); - let (normal, n) = if len.is_finite() && len > 1e-6 { ([gx / len, gy / len], [gx / len, gy / len]) } else { ([0.0, 0.0], [1.0, 0.0]) }; - row.push(EdgePixel { at: i as u32, cov: c, edge: SharpEdge { offset: edge_offset(n, c), normal } }); - } - }, - ); - let mut pixels: Vec = Vec::with_capacity(rows.iter().map(Vec::len).sum()); - for row in rows { - pixels.extend(row); - } - let mut slot = vec![0u32; w * h]; - for (k, p) in pixels.iter().enumerate() { - if let Some(s) = slot.get_mut(p.at as usize) { - *s = k as u32 + 1; - } - } - refine_edge_normals(&mut pixels, &slot, w, h); - SharpEdges { w, h, slot, pixels } -} - -/// How far (in pixels) around an edge pixel [`refine_edge_normals`] looks for its neighbours. -const NORMAL_RADIUS: i64 = 3; - -/// The 3×3 gradient of the coverage gives an edge's direction to 1-2 degrees, and its error is -/// systematic, so it tilts the distance of every pixel the same way and shows as a faint ripple. -/// The edge points of a straight edge's pixels (each pixel's centre moved to its edge) lie on one -/// line, and the line through the points of the pixels around one gives the direction to a fraction -/// of a degree. Where those points are not on a line (corners, tight curves) the gradient's normal -/// stays. -fn refine_edge_normals(pixels: &mut [EdgePixel], slot: &[u32], w: usize, h: usize) { - let (wi, hi) = (w as i64, h as i64); - let points: Vec<[f32; 2]> = pixels - .iter() - .map(|p| [(p.at as i64 % wi) as f32 - p.edge.offset * p.edge.normal[0], (p.at as i64 / wi) as f32 - p.edge.offset * p.edge.normal[1]]) - .collect(); - let before: Vec = pixels.iter().map(|p| p.edge).collect(); - // Every pixel reads the unrefined edges around it and writes its own, so they go in parallel. - let work = pixels.len().saturating_mul(32); - par_units(work, pixels, 1, &mut [] as &mut [()], 0, Vec::<[f32; 2]>::new, |near, k, pixel, _| { - let (Some(pixel), Some(&e)) = (pixel.first_mut(), before.get(k)) else { return }; - let (x, y) = (pixel.at as i64 % wi, pixel.at as i64 / wi); - let (mut n, mut sum) = (0.0f32, [0.0f32; 2]); - near.clear(); - for (dx, dy) in (-NORMAL_RADIUS..=NORMAL_RADIUS).flat_map(|dy| (-NORMAL_RADIUS..=NORMAL_RADIUS).map(move |dx| (dx, dy))) { - let (nx, ny) = (x + dx, y + dy); - if dx * dx + dy * dy > NORMAL_RADIUS * NORMAL_RADIUS || nx < 0 || ny < 0 || nx >= wi || ny >= hi { - continue; - } - let Some(j) = slot.get((ny * wi + nx) as usize).and_then(|&s| (s as usize).checked_sub(1)) else { continue }; - let (Some(o), Some(&p)) = (before.get(j), points.get(j)) else { continue }; - if o.normal[0] * e.normal[0] + o.normal[1] * e.normal[1] > 0.9 { - near.push(p); - sum = [sum[0] + p[0], sum[1] + p[1]]; - n += 1.0; - } - } - if near.len() < 3 { - return; - } - let mean = [sum[0] / n, sum[1] / n]; - let (mut sxx, mut sxy, mut syy) = (0.0f32, 0.0f32, 0.0f32); - for p in near.iter() { - let (dx, dy) = (p[0] - mean[0], p[1] - mean[1]); - sxx += dx * dx; - sxy += dx * dy; - syy += dy * dy; - } - // Spread along and across the best line through the points. - let half = 0.5 * (sxx + syy); - let root = (0.25 * (sxx - syy) * (sxx - syy) + sxy * sxy).sqrt(); - let (along, across) = (((half + root) / n).max(0.0).sqrt(), ((half - root) / n).max(0.0).sqrt()); - if !(along > EDGE_LINE_MIN_SPREAD && across < EDGE_LINE_MAX_OFF) { - return; - } - let angle = 0.5 * (2.0 * sxy).atan2(sxx - syy); - let mut normal = [-angle.sin(), angle.cos()]; - if normal[0] * e.normal[0] + normal[1] * e.normal[1] < 0.0 { - normal = [-normal[0], -normal[1]]; - } - pixel.edge.normal = normal; - pixel.edge.offset = edge_offset(normal, pixel.cov); - }); -} - -/// The edge points around a pixel must spread at least this far (px, standard deviation) along -/// their line to give it a direction, and stay within [`EDGE_LINE_MAX_OFF`] of it. -const EDGE_LINE_MIN_SPREAD: f32 = 0.7; -const EDGE_LINE_MAX_OFF: f32 = 0.1; - -/// How far from the foot of the perpendicular (in pixels) [`edge_distance`] looks for edge pixels. -const FOOT_RADIUS: i64 = 2; - -/// The distance from pixel `p` to the sharp edge whose pixel `q` is nearest to it, or `None` when -/// `q` gives no usable distance. The nearest pixel by its centre is not the best one: it can sit a -/// few pixels along the edge from the foot of the perpendicular and deeper than the edge, and the -/// further `p` is from the edge the further, so its distance ripples along the edge. So this takes -/// the smallest distance of the edge pixels around that foot, which is exact for a straight edge. -fn edge_distance(sharp: &SharpEdges, p: [usize; 2], q: [usize; 2], inside: bool) -> Option { - let (px, py) = (p[0] as f32, p[1] as f32); - let e = sharp.at(q[0], q[1])?; - let mut best = e.distance(px - q[0] as f32, py - q[1] as f32, inside)?; - // Where p's perpendicular meets q's line. - let signed = e.offset + (px - q[0] as f32) * e.normal[0] + (py - q[1] as f32) * e.normal[1]; - let (fx, fy) = ((px - signed * e.normal[0]).round() as i64, (py - signed * e.normal[1]).round() as i64); - for sy in (fy - FOOT_RADIUS).max(0)..=(fy + FOOT_RADIUS).min(sharp.h as i64 - 1) { - for sx in (fx - FOOT_RADIUS).max(0)..=(fx + FOOT_RADIUS).min(sharp.w as i64 - 1) { - if let Some(near) = sharp.at(sx as usize, sy as usize) - && let Some(d) = near.distance(px - sx as f32, py - sy as f32, inside) - { - best = best.min(d); - } - } - } - Some(best) -} - -/// [`dist_inside`] for chiselled bevels. A sharp edge pixel puts the edge where its coverage says, -/// at any angle, and the pixels near it measure to that edge ([`edge_distance`]), so the distance -/// ramps stay planar along an oblique edge instead of following the pixel staircase. The plain -/// distance (to the nearest empty pixel, less half a pixel) never falls short of the true one, so -/// it caps the result where an edge lies exactly on a pixel boundary and has no sharp pixel; a mask -/// without sharp pixels gives exactly [`dist_inside`]. Values past `reach` pixels are not refined. -fn bevel_dist_inside(s: &Map, sharp: &SharpEdges, reach: f32) -> Vec { - let empty = covered(s, |a| a <= INSIDE_EPS); - let (d, near) = edt_nearest(&empty, s.w, s.h); - let at = |x: usize, y: usize| -> f32 { - let i = y * s.w + x; - if empty[i] { - return -0.5; - } - if let Some(e) = sharp.get(i) { - return e.offset; - } - let plain = d[i] - 0.5; - if d[i] > reach + EDGE_MARGIN || sharp.is_empty() { - return plain; - } - // The sharp pixel next to the nearest empty one that is nearest to this pixel. - let (px, py) = (x as i64, y as i64); - let (ox, oy) = ((near[i] as usize % s.w) as i64, (near[i] as usize / s.w) as i64); - let q = (-1..=1) - .flat_map(|dy| (-1..=1).map(move |dx| (ox + dx, oy + dy))) - .filter(|&(x, y)| x >= 0 && y >= 0 && sharp.has(x as usize, y as usize)) - .min_by_key(|&(x, y)| (x - px) * (x - px) + (y - py) * (y - py)); - match q.and_then(|(x, y)| edge_distance(sharp, [px as usize, py as usize], [x as usize, y as usize], true)) { - Some(refined) => refined.min(plain), - None => plain, - } - }; - par_fill(s.w, s.h, 0.0f32, |y, row| { - for (x, out) in row.iter_mut().enumerate() { - *out = at(x, y); - } - }) -} - -/// [`dist_outside`] for chiselled bevels, with sharp edge pixels placed as in [`bevel_dist_inside`]. -fn bevel_dist_outside(s: &Map, sharp: &SharpEdges, reach: f32) -> Vec { - let inside = covered(s, |a| a > INSIDE_EPS); - let (d, near) = edt_nearest(&inside, s.w, s.h); - let at = |x: usize, y: usize| -> f32 { - let i = y * s.w + x; - if let Some(e) = sharp.get(i) { - return -e.offset; - } - if inside[i] { - return -0.5; - } - let q = near[i] as usize; - let Some(e) = sharp.get(q) else { return d[i] - (s.v[q].min(1.0) - 0.5) }; - let (p, qp) = ([x, y], [q % s.w, q / s.w]); - let measured = if d[i] <= reach + EDGE_MARGIN { - edge_distance(sharp, p, qp, false) - } else { - e.distance(p[0] as f32 - qp[0] as f32, p[1] as f32 - qp[1] as f32, false) - }; - measured.unwrap_or(d[i] - e.offset) - }; - par_fill(s.w, s.h, 0.0f32, |y, row| { - for (x, out) in row.iter_mut().enumerate() { - *out = at(x, y); - } - }) -} - -/// Pixels past the reach that are still refined, so the value is right where the ramp ends. -const EDGE_MARGIN: f32 = 2.0; - -/// Alpha above which a pixel belongs to the layer's shape (half an 8-bit step). -const INSIDE_EPS: f32 = 0.5 / 255.0; - -/// The soft falloff of an effect of `size` pixels: two box passes of width `size` (a tent), -/// as Photoshop does. Fitted on psd-tools layer_effects.psd against the earlier Gaussian -/// (sigma = 0.4 × size): drop shadow coverage error 0.0064 → 0.0038, satin 0.014 → 0.002. -fn blur(m: &mut Map, size: f32) { - if size.is_finite() { - tent(m, size); - } -} - -/// Grows the shape by `r` pixels (anti-aliased), keeping the original soft edge. Distances use -/// the 5 × 5 chamfer metric, as for strokes: Photoshop's spread of a group drop shadow around an -/// ellipse (ag-psd group-drop-shadows) is round at 0° and 45° and falls short in between, peaking -/// near 15° where the chamfer metric overestimates most (5/255 lighter with an exact Euclidean -/// dilation, within 2/255 with the chamfer). -fn dilate(s: &Map, r: f32) -> Map { - if r <= 0.0 { - return s.clone(); - } - let d = dist_outside_by(s, Metric::Chamfer); - let mut out = s.clone(); - for (o, d) in out.v.iter_mut().zip(d) { - // Partly covered pixels (distance sentinel < 0) grow by `r` from their own coverage, so a - // 2 % spread doesn't make every anti-aliased edge pixel opaque (ag-psd drop shadow). - *o = if d < 0.0 { (*o + r).min(1.0) } else { o.max((r + 0.5 - d).clamp(0.0, 1.0)) }; - } - out -} - -fn contour_lut(c: &Contour) -> Option> { - match c { - Contour::Linear => None, - Contour::Custom { points, corners, .. } => Some(crate::adjust::contour_curve_lut(points, corners)), - } -} - -/// Satin's coverage transfer: the contour read from its far end, `|c(1 − v) − c(1)|`. Measured in -/// Photoshop 27.11: Cone and Cone − Inverted Satins are identical, and a Gaussian Satin runs under -/// the diagonal (0.36 at 0.5) while the same Gaussian on a glow or gloss runs over it (0.65). -/// `None` = identity. -pub fn satin_lut(c: &Contour) -> Option> { - let lut = contour_lut(c)?; - let end = lut.last().copied().unwrap_or(1.0); - Some(lut.iter().rev().map(|v| (v - end).abs()).collect()) -} - -/// Interpolated lookup in a 0..=1 table (as the GPU's `lut()`). -fn lut_at(l: &[f32], v: f32) -> f32 { - let x = v.clamp(0.0, 1.0) * (l.len() - 1) as f32; - let i = x.floor() as usize; - let j = (i + 1).min(l.len() - 1); - l[i] + (l[j] - l[i]) * (x - i as f32) -} - -/// A glow's coverage transfer: its contour applied over the Range (Photoshop maps the glow's -/// coverage `v` through `contour(min(v / range, 1))`, so the default 50 % doubles a blurred -/// edge's 0.5 to full strength). `None` = identity. -pub fn glow_lut(g: &Glow) -> Option> { - ranged_lut(&g.contour, g.range) -} - -/// A contour applied over a Range (`contour(min(v / range, 1))`); `None` = identity. -pub fn ranged_lut(contour: &Contour, range: f32) -> Option> { - let base = contour_lut(contour); - let range = if range.is_finite() { range.clamp(0.01, 1.0) } else { 1.0 }; - if range >= 0.999 { - return base; - } - let n = 4096; - Some( - (0..n) - .map(|k| { - let v = (k as f32 / (n - 1) as f32 / range).min(1.0); - base.as_ref().map_or(v, |l| lut_at(l, v)) - }) - .collect(), - ) -} - -/// The bevel Contour element's height transfer: the contour alone. Unlike a glow's, its Range is -/// not a `v / range` stretch: that flattened a Linear contour at the default 50 % to a bevel half -/// as wide as Photoshop's (a real 18 px smooth inner bevel at 136 % depth: top-edge highlight gone -/// 15 px in, Photoshop's still 0.19 at 16 px), and dropping it lowers the bad pixels of every -/// contour oracle (bevel-inner-contour-ramp-peak 25.9 → 21.8 %, -double-ring-aa-r70 25.2 → 21.0 %, -/// bevel-pillow-chisel-hard-gloss-and-contour 11.4 → 7.2 %). What Range does instead is still open. -pub fn bevel_contour_lut(c: &photocraft_doc::BevelContour) -> Vec { - contour_lut(&c.contour).unwrap_or_else(|| (0..4096).map(|k| k as f32 / 4095.0).collect()) -} - -fn apply_lut(m: Map, l: Option>) -> Map { - match l { - None => m, - Some(l) => m.map(|v| lut_at(&l, v)), - } -} - -/// Deterministic per-pixel value in 0..=1, hashed from document coordinates -/// (the same hash as the GPU's `dissolve_noise`), so the speckle is stable -/// across renders, frames and tiles. -pub fn hash_noise(x: i64, y: i64) -> f32 { - let mut h = (x as i32 as u32).wrapping_mul(0x8da6_b343) ^ (y as i32 as u32).wrapping_mul(0xd816_3841) ^ 0x9e37_79b9; - h ^= h >> 15; - h = h.wrapping_mul(0x2c1b_3c6d); - h ^= h >> 12; - (h & 0xffff) as f32 / 65536.0 -} - -/// Effect noise (Photoshop's Noise slider): monochrome speckle in the coverage, -/// applied after the contour. `amount` is 0..=1; 0 leaves the map untouched. The speckle is -/// scaled by the coverage, so it fades out with the effect instead of lighting up the blur's -/// near-zero tail out to the edge of its rectangular reach (#7833). -fn noise(m: &mut Map, amount: f32, x0: i32, y0: i32) { - if !amount.is_finite() || amount <= 0.0 { - return; - } - for y in 0..m.h { - for x in 0..m.w { - let v = &mut m.v[y * m.w + x]; - if *v <= 0.0 { - continue; - } - let n = hash_noise(i64::from(x0 + x as i32), i64::from(y0 + y as i32)); - *v = (*v * (1.0 + (n - 0.5) * 2.0 * amount)).clamp(0.0, 1.0); - } - } -} - -fn apply_contour(m: Map, c: &Contour) -> Map { - match contour_lut(c) { - None => m, - Some(l) => m.map(|v| lut_at(&l, v)), - } -} - -fn rgb(c: &photocraft_color::Color) -> [f32; 3] { - c.to_rgb() -} - -/// Offset of an effect lit from `angle` at `distance` (shadow falls away from -/// the light), rounded to whole pixels as Photoshop does. -fn offset(angle: f32, distance: f32) -> (f32, f32) { - let a = angle.to_radians(); - ((-a.cos() * distance).round(), (a.sin() * distance).round()) -} - -/// The lengths a 100 % gradient at `angle` spans in a `w` × `h` frame: the chord (Linear and -/// Reflected) and the ellipse-norm length (Radial, Angle, Diamond; its half is the radius). -pub fn gradient_units(angle: f32, w: f32, h: f32) -> (f32, f32) { - let (s, c) = angle.to_radians().sin_cos(); - // Gradient length: the bounds' extent along the angle as an ellipse - // norm (a unit gradient scaled to the bounds); fitted on psd-tools - // gradient-styles.psd (cached Photoshop renderings of every style). - let len = ((c * w).powi(2) + (s * h).powi(2)).sqrt().max(1.0); - // Linear / Reflected span the chord of the bounds through their centre along the angle: - // min(w / |cos|, h / |sin|). A 45° gradient on a 29 px square runs 41 px (psd-tools - // shape-fx2), an 87° one on a 600 × 60 text line 60 px (layer_effects); axis-aligned angles - // span the width / height. - let chord = (w / c.abs().max(1e-6)).min(h / s.abs().max(1e-6)).max(1.0); - (chord, len) -} - -/// Gradient parameter `t` in `0..=1` for pixel centre `(x, y)` inside `bounds`. -#[allow(clippy::too_many_arguments)] -pub fn gradient_t(style: GradientStyle, angle: f32, scale: f32, reverse: bool, offset: (f32, f32), bounds: Rect, x: f32, y: f32) -> f32 { - let w = bounds.width().max(1) as f32; - let h = bounds.height().max(1) as f32; - let cx = bounds.x0 as f32 + w / 2.0 + offset.0 * w; - let cy = bounds.y0 as f32 + h / 2.0 + offset.1 * h; - let (s, c) = angle.to_radians().sin_cos(); - let (dx, dy) = (x - cx, y - cy); - // Distance along the gradient direction (y axis points down). - let along = dx * c - dy * s; - let across = dx * s + dy * c; - let (chord, len) = gradient_units(angle, w, h); - let (chord, len) = (chord * scale.max(1e-3), len * scale.max(1e-3)); - // Linear / Reflected sample the pixel's top-left corner, half a pixel before its centre - // (with the whole-pixel end points of `fill_layout`: layer_effects' overlay 5.8 → 1.8/255, - // shape-fx2 2.8 → 1.1/255, gradient-fill.psd 1.9 → 0.5/255). - let corner = 0.5 * (c - s); - let mut t = match style { - GradientStyle::Linear => (along - corner) / chord + 0.5, - GradientStyle::Reflected => ((along - corner) / (chord / 2.0)).abs(), - GradientStyle::Radial => (dx * dx + dy * dy).sqrt() / (len / 2.0), - GradientStyle::Diamond => (along.abs() + across.abs()) / (len / 2.0), - // Clockwise sweep starting at the gradient angle. - GradientStyle::Angle => ((angle.to_radians() - (-dy).atan2(dx)) / std::f32::consts::TAU).rem_euclid(1.0), - }; - t = t.clamp(0.0, 1.0); - if reverse { 1.0 - t } else { t } -} - -/// Samples colour and opacity stops at `t`. -pub fn sample_gradient(g: &Gradient, t: f32) -> [f32; 4] { - PreparedGradient::new(g).sample(t) -} - -// Prepared only for one paint call: CMYK conversions must use that call's active profile. -struct PreparedGradient { - color: Vec<(f32, [f32; 3])>, - opacity: Vec<(f32, [f32; 3])>, -} - -impl PreparedGradient { - fn new(g: &Gradient) -> Self { - Self { color: g.stops.iter().map(|(p, c)| (*p, rgb(c))).collect(), opacity: g.opacity_stops.iter().map(|(p, a)| (*p, [*a; 3])).collect() } - } - - fn sample(&self, t: f32) -> [f32; 4] { - let color = sample_stops(&self.color, t); - let alpha = if self.opacity.is_empty() { 1.0 } else { sample_stops(&self.opacity, t)[0] }; - [color[0], color[1], color[2], alpha] - } -} - -fn sample_stops(stops: &[(f32, [f32; 3])], t: f32) -> [f32; 3] { - match stops { - [] => [t; 3], - [s] => s.1, - _ => { - if t <= stops[0].0 { - return stops[0].1; - } - for w in stops.windows(2) { - if t <= w[1].0 { - let k = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 }; - return std::array::from_fn(|i| w[0].1[i] + (w[1].1[i] - w[0].1[i]) * k); - } - } - stops[stops.len() - 1].1 - } - } -} - -/// Composite `color × coverage` into `dst` (both over the same rectangle). -fn paint(dst: &mut Buffer, m: &Map, color: impl Fn(usize) -> [f32; 4], blend: BlendMode, opacity: f32) { - let (x0, y0, w) = (i64::from(dst.rect.x0), i64::from(dst.rect.y0), (dst.rect.width().max(1)) as usize); - for (i, p) in dst.px.iter_mut().enumerate() { - let a = m.v[i] * opacity; - if a <= 0.0 { - continue; - } - let c = color(i); - if blend == BlendMode::Dissolve { - if dissolves_in(x0 + (i % w) as i64, y0 + (i / w) as i64, c[3] * a) { - *p = psblend::composite(BlendMode::Normal, *p, [c[0], c[1], c[2], 1.0], 1.0); - } - continue; - } - *p = psblend::composite(blend, *p, [c[0], c[1], c[2], c[3] * a], 1.0); - } -} - -/// Whether `e` paints anything in Dissolve mode. -fn dissolves(e: &Effect) -> bool { - let d = |m: BlendMode| m == BlendMode::Dissolve; - match e { - Effect::DropShadow(s) | Effect::InnerShadow(s) => d(s.common.blend), - Effect::OuterGlow(g) | Effect::InnerGlow(g) => d(g.common.blend), - Effect::Stroke(s) => d(s.common.blend), - Effect::ColorOverlay { common, .. } | Effect::GradientOverlay { common, .. } | Effect::PatternOverlay { common, .. } => d(common.blend), - Effect::Satin(s) => d(s.common.blend), - Effect::BevelEmboss(b) => d(b.highlight.blend) || d(b.shadow.blend), - } -} - -/// Dissolve on an effect (#6995): a pixel takes the effect fully or not at all, with probability -/// `coverage`, picked by the same document-coordinate noise as a Dissolve layer. A soft glow or -/// shadow turns into scattered speckle instead of a smooth falloff. -fn dissolves_in(x: i64, y: i64, coverage: f32) -> bool { - hash_noise(x, y) < coverage -} - -fn paint_color(dst: &mut Buffer, m: &Map, c: [f32; 3], blend: BlendMode, opacity: f32) { - paint(dst, m, |_| [c[0], c[1], c[2], 1.0], blend, opacity); -} - -/// Spread / choke of a soft effect: (dilation radius, blur width). The dilation is whole pixels -/// (`size × spread` rounded: a 2 % spread of a 5 px shadow doesn't grow it at all), the blur -/// keeps `size × (1 − spread)` (ag-psd effects 10.6 → 3.8 % of pixels off). -pub fn spread_split(size: f32, spread: f32) -> (f32, f32) { - ((size * spread).round(), size * (1.0 - spread)) -} - -fn shadow_map(shape: &Map, s: &Shadow, light: &GlobalLight, inner: bool, origin: (i32, i32)) -> Map { - let angle = if s.use_global_light { light.angle } else { s.angle }; - let (dx, dy) = offset(angle, s.distance); - let src = if inner { shape.clone().map(|a| 1.0 - a) } else { shape.clone() }; - let mut m = src.shifted(dx, dy, if inner { 1.0 } else { 0.0 }); - let (r, bw) = spread_split(s.size, s.spread); - m = dilate(&m, r); - blur(&mut m, bw); - let mut m = apply_contour(m, &s.contour); - noise(&mut m, s.noise, origin.0, origin.1); - if inner { - for (v, a) in m.v.iter_mut().zip(&shape.v) { - *v *= a; - } - } - m -} - -fn glow_map(shape: &Map, g: &Glow, inner: bool, origin: (i32, i32)) -> Map { - // An inner glow is built from the edge inwards; a centre-source glow is its inverse, taken - // after the contour and Range (Photoshop 27.11, measured: the centre glow is exactly - // 1 − the edge glow, for both techniques). - let src = if inner { shape.clone().map(|a| 1.0 - a) } else { shape.clone() }; - let mut m = match g.technique { - GlowTechnique::Precise => { - // Coverage falls linearly from 0.5 at the edge to 0 at `size + 1` px (centre to - // centre), solid within the spread / choke: after the default 50 % Range that is - // Photoshop's 1 − D / (size + 1) beyond the solid part (measured: outer and inner, - // sizes 10 and 20, spread 0 and 40 %, choke 0 and 30 %: within 1 level; other Range - // values are unmeasured). The distances here are 0.5 px short of centre to centre. - let d = if inner { dist_inside(shape) } else { dist_outside(&src) }; - let solid = g.size * g.spread; - let soft = (g.size + 1.0 - solid).max(1e-3); - let mut m = Map::new(shape.w, shape.h, 0.0); - for (o, d) in m.v.iter_mut().zip(d) { - let d = d + 0.5; - *o = if d <= solid { 1.0 } else { 0.5 * (1.0 - (d - solid) / soft).clamp(0.0, 1.0) }; - } - m - } - GlowTechnique::Softer => { - let (r, bw) = spread_split(g.size, g.spread); - let mut m = dilate(&src, r); - blur(&mut m, bw); - m - } - }; - m = apply_lut(m, glow_lut(g)); - if inner && g.source == GlowSource::Center { - m = m.map(|v| 1.0 - v); - } - noise(&mut m, g.noise, origin.0, origin.1); - if inner { - for (v, a) in m.v.iter_mut().zip(&shape.v) { - *v *= a; - } - } - m -} - -/// Paints a pattern (looked up in `patterns`) through coverage `m`; missing patterns paint nothing. -#[allow(clippy::too_many_arguments)] -fn paint_pattern( - dst: &mut Buffer, - m: &Map, - patterns: &PreparedPatterns<'_>, - name: &str, - id: &str, - place: Placement, - big: Rect, - blend: BlendMode, - opacity: f32, -) { - let Some(tile) = patterns.get(id, name) else { return }; - let w = big.width() as usize; - paint( - dst, - m, - |i| { - let (x, y) = (f64::from(big.x0 + (i % w) as i32) + 0.5, f64::from(big.y0 + (i / w) as i32) + 0.5); - let (u, v) = place.map(x, y); - tile.sample(u, v) - }, - blend, - opacity, - ); -} - -#[allow(clippy::too_many_arguments)] -fn paint_fx( - dst: &mut Buffer, - m: &Map, - p: &FxPaint, - shape_bounds: Rect, - anchor: (f64, f64), - big: Rect, - blend: BlendMode, - opacity: f32, - patterns: &PreparedPatterns<'_>, -) { - match p { - FxPaint::Color(c) => paint_color(dst, m, rgb(c), blend, opacity), - FxPaint::Gradient(g) => { - let prepared = PreparedGradient::new(g); - let (angle, scale, offset) = crate::fill_layout::gradient_layout(g.style, g.angle, g.scale, g.offset, shape_bounds); - let w = big.width() as usize; - paint( - dst, - m, - |i| { - let (x, y) = ((big.x0 + (i % w) as i32) as f32 + 0.5, (big.y0 + (i / w) as i32) as f32 + 0.5); - prepared.sample(gradient_t(g.style, angle, scale, g.reverse, offset, shape_bounds, x, y)) - }, - blend, - opacity, - ) - } - FxPaint::Pattern { name, id, scale } => { - paint_pattern(dst, m, patterns, name, id, Placement::anchored(anchor, true, (0.0, 0.0), *scale, 0.0), big, blend, opacity) - } - } -} - -/// The opacity gain of a gradient glow: it is opaque from strength `range²` on (see [`paint_glow`]). -pub fn glow_gradient_gain(range: f32) -> f32 { - let r = if range.is_finite() { range.clamp(0.01, 1.0) } else { 1.0 }; - 1.0 / (r * r) -} - -/// A glow's paint over its map `m`. A gradient runs along the glow rather than across the -/// canvas: Photoshop colours the glow where its (ranged, contoured) strength is `v` with the -/// gradient at `1 - v`, so the first stop hugs the edge, and the glow is opaque from `v = range²` -/// on (photoshop corpus outer-glow-gradient.psd: 1.4/255 mean, against bands across the canvas; -/// psd-tools layer_params.psd). Glows have no gradient angle, style or Reverse. -#[allow(clippy::too_many_arguments)] -fn paint_glow(dst: &mut Buffer, m: &Map, g: &Glow, shape_bounds: Rect, anchor: (f64, f64), big: Rect, patterns: &PreparedPatterns<'_>) { - let FxPaint::Gradient(gradient) = &g.paint else { - return paint_fx(dst, m, &g.paint, shape_bounds, anchor, big, g.common.blend, g.common.opacity, patterns); - }; - let prepared = PreparedGradient::new(gradient); - let gain = glow_gradient_gain(g.range); - let strength = Map { w: m.w, h: m.h, v: m.v.iter().map(|v| (v * gain).min(1.0)).collect() }; - paint(dst, &strength, |i| prepared.sample(1.0 - m.v.get(i).copied().unwrap_or(0.0).clamp(0.0, 1.0)), g.common.blend, g.common.opacity); -} - -/// A box width as the blurs use it: at least 1, at most [`MAX_REACH`] (an effect never reaches -/// further, see [`margin`]), and 1 for NaN. A size or softness from a command or a file can be -/// anything, and an unbounded width sizes the kernel and its buffers (#1543). -fn box_width(w: f32) -> f32 { - if w.is_nan() { 1.0 } else { w.clamp(1.0, MAX_REACH) } -} - -/// Normalised weights of a centred box of (fractional) width `w`: tap `i` gets the overlap of -/// `[i - 0.5, i + 0.5]` with `[-w/2, w/2]`. -fn box_weights(w: f32) -> Vec { - let w = box_width(w); - let half = w / 2.0; - let r = (half - 0.5).ceil().max(0.0) as i64; - let v: Vec = (-r..=r).map(|i| ((i as f32 + 0.5).min(half) - (i as f32 - 0.5).max(-half)).max(0.0)).collect(); - let sum: f32 = v.iter().sum(); - v.iter().map(|x| x / sum).collect() -} - -/// The 1D kernel of two box passes of width `w` (a tent of half-width ≈ `w`): `(radius, weights)`. -/// Photoshop's bevel height maps are this blur of the shape (fitted on the corpus: a smooth -/// inner bevel of size 5 matches within 0.7 % mean, size 41 within 2.6 %). -pub fn tent_kernel(w: f32) -> (i32, Vec) { - let b = box_weights(w); - let n = b.len() * 2 - 1; - let mut t = vec![0.0f32; n]; - for (i, x) in b.iter().enumerate() { - for (j, y) in b.iter().enumerate() { - t[i + j] += x * y; - } - } - ((n as i32 - 1) / 2, t) -} - -/// Box geometry for a (fractional) width: (`r`, end-tap weight `f`, 1 / width) — the -/// [`box_weights`] taps are `r - 1` full ones each side of the centre plus the two end taps at `f`. -fn box_geom(bw: f32) -> (i64, f64, f64) { - let bw = box_width(bw); - let half = bw / 2.0; - let r = (half - 0.5).ceil().max(0.0) as i64; - let f = f64::from((half - (r as f32 - 0.5)).clamp(0.0, 1.0)); - (r, f, 1.0 / f64::from(bw)) -} - -/// One box pass over `src` (zero outside it) evaluated at `x0 .. x0 + dst.len()`, as a running -/// sum (O(1) per sample whatever the width). -fn box_line(src: &[f64], x0: i64, dst: &mut [f64], bw: f32) { - let n = src.len() as i64; - let (r, f, norm) = box_geom(bw); - let at = |i: i64| if i >= 0 && i < n { src[i as usize] } else { 0.0 }; - if r == 0 { - for (k, d) in dst.iter_mut().enumerate() { - *d = at(x0 + k as i64); - } - return; - } - let window = x0 - (r - 1)..=x0 + (r - 1); - let mut inner: f64 = window.clone().map(at).sum(); - let mut last_covered = window.rev().find(|&x| at(x) != 0.0).unwrap_or(i64::MIN); - for (k, d) in dst.iter_mut().enumerate() { - let x = x0 + k as i64; - *d = (inner + f * (at(x - r) + at(x + r))) * norm; - let entering = at(x + r); - inner += entering - at(x - r + 1); - if entering != 0.0 { - last_covered = x + r; - } - // Cancellation can leave positive residue after the last covered pixel leaves. - // Noise amplifies even that residue into visible speckles (#5638). Reset only - // truly empty windows, preserving arbitrarily faint real coverage. - if last_covered < x - r + 2 { - inner = 0.0; - } - } -} - -/// Two box passes along a line, exactly the convolution with [`tent_kernel`] (zero outside): the -/// first pass is evaluated `r` samples beyond each end so the second sees what lies there. -fn tent_line(src: &[f32], dst: &mut [f32], bw: f32) { - let (r, _, _) = box_geom(bw); - let s: Vec = src.iter().map(|v| f64::from(*v)).collect(); - let mut mid = vec![0.0f64; src.len() + 2 * r as usize]; - box_line(&s, -r, &mut mid, bw); - let mut out = vec![0.0f64; src.len()]; - // `mid[k]` holds position k - r: output position p reads index p + r. - box_line(&mid, r, &mut out, bw); - for (d, v) in dst.iter_mut().zip(out) { - *d = v as f32; - } -} - -/// Rows of a `w`-wide row-major buffer, each through `f(src_row, dst_row)`, in parallel on -/// scoped OS threads. Not rayon: maps can be built from inside a rayon tile, where a waiting -/// worker steals other tiles. Map builds no longer block on each other (#276), but the blur -/// keeps out of the tile pool. -fn rows_par(src: &[f32], dst: &mut [f32], w: usize, f: impl Fn(&[f32], &mut [f32]) + Sync) { - if w == 0 { - return; - } - let threads = - if cfg!(target_arch = "wasm32") || src.len() < 1 << 16 { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 16) }; - if threads == 1 { - dst.chunks_mut(w).zip(src.chunks(w)).for_each(|(d, s)| f(s, d)); - return; - } - let rows = (src.len() / w).div_ceil(threads); - std::thread::scope(|sc| { - for (d, s) in dst.chunks_mut(rows * w).zip(src.chunks(rows * w)) { - let f = &f; - sc.spawn(move || d.chunks_mut(w).zip(s.chunks(w)).for_each(|(d, s)| f(s, d))); - } - }); -} - -fn transpose_map(v: &[f32], w: usize, h: usize) -> Vec { - let mut out = vec![0.0f32; v.len()]; - const B: usize = 32; - for by in (0..h).step_by(B) { - for bx in (0..w).step_by(B) { - for y in by..(by + B).min(h) { - for x in bx..(bx + B).min(w) { - out[x * h + y] = v[y * w + x]; - } - } - } - } - out -} - -/// Two box passes of width `w` along each axis (the tent [`tent_kernel`] describes, which the GPU -/// convolves directly). -fn tent(m: &mut Map, w: f32) { - if tent_kernel(w).0 == 0 || m.v.is_empty() { - return; - } - tent_fast(m, w); -} - -/// [`tent`] as a direct convolution with [`tent_kernel`] (the GPU's way; tests compare). -#[cfg(test)] -fn tent_direct(m: &mut Map, w: f32) { - { - let (r, k) = tent_kernel(w); - let (mw, mh) = (m.w as i64, m.h as i64); - let mut tmp = vec![0.0f32; m.v.len()]; - for y in 0..mh { - for x in 0..mw { - let mut acc = 0.0; - for (i, kv) in k.iter().enumerate() { - let xx = x + i as i64 - r as i64; - if xx >= 0 && xx < mw { - acc += m.v[(y * mw + xx) as usize] * kv; - } - } - tmp[(y * mw + x) as usize] = acc; - } - } - for y in 0..mh { - for x in 0..mw { - let mut acc = 0.0; - for (i, kv) in k.iter().enumerate() { - let yy = y + i as i64 - r as i64; - if yy >= 0 && yy < mh { - acc += tmp[(yy * mw + x) as usize] * kv; - } - } - m.v[(y * mw + x) as usize] = acc; - } - } - } -} - -fn tent_fast(m: &mut Map, w: f32) { - let (mw, mh) = (m.w, m.h); - let twice = |s: &[f32], d: &mut [f32]| tent_line(s, d, w); - let mut a = vec![0.0f32; m.v.len()]; - rows_par(&m.v, &mut a, mw, twice); - let t = transpose_map(&a, mw, mh); - let mut b = vec![0.0f32; t.len()]; - rows_par(&t, &mut b, mh, twice); - m.v = transpose_map(&b, mh, mw); -} - -/// Where a bevel's maps paint: inside the shape (with the layer), outside it (onto the -/// backdrop), or both (emboss styles: maps 0–1 inside, 2–3 outside). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BevelPaint { - Inner, - Outer, - Both, -} - -/// Height below which an outer bevel pixel counts as off the bevel (beyond the blur's reach): -/// above float noise of the running-sum blur (~3e-7), far below anything that shades. -pub const BEVEL_H_EPS: f32 = 1e-5; - -/// Bevel geometry shared by the CPU maps and the GPU programs. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct BevelGeom { - pub paint: BevelPaint, - /// Box width of the smooth height blur (size; half the size, rounded up, for emboss styles). - pub width: f32, - /// Height-map gradient scale: depth × width (smooth) or depth × size (chisel), signed by - /// direction. - pub depth: f32, - /// Pillow emboss: the outside slopes face the other way. - pub pillow: bool, - /// Chisel Soft: extra tent width over the chiselled height map. - pub chisel_soft: f32, -} - -pub fn bevel_geom(b: &Bevel) -> BevelGeom { - let size = b.size.max(1.0); - let emboss = matches!(b.style, BevelStyle::Emboss | BevelStyle::PillowEmboss); - let paint = match b.style { - BevelStyle::OuterBevel => BevelPaint::Outer, - BevelStyle::Emboss | BevelStyle::PillowEmboss => BevelPaint::Both, - BevelStyle::InnerBevel | BevelStyle::StrokeEmboss => BevelPaint::Inner, - }; - // Emboss styles straddle the edge with half the size, rounded up to whole pixels: a 41 px - // emboss blurs over 21 (psd-tools layer_effects: 20.5 left narrow letter parts up to - // 5.7/255 dark, 21 is within 2.2). - let width = if emboss { (size / 2.0).ceil() } else { size }; - let smooth = b.technique == BevelTechnique::Smooth; - let sign = if b.up { 1.0 } else { -1.0 }; - BevelGeom { - paint, - width, - // A bevel rises `depth × width / 2` px: Smooth with a slope falling from `depth` at the - // edge (the tent), a chisel with the constant slope of its ramp (see `bevel_chisel_h`). - depth: b.depth * if smooth { width } else { size / 2.0 } * sign, - pillow: b.style == BevelStyle::PillowEmboss, - chisel_soft: if b.technique == BevelTechnique::ChiselSoft { (size / 4.0).max(1.0) } else { 0.0 }, - } -} - -/// Bevel height map in `0..=1`. Smooth: the shape blurred by two box passes of the bevel -/// width. Chisel: linear ramps of the distance to the edge (size wide; emboss styles straddle the -/// edge), slightly blurred for Chisel Soft. The distance puts the edge by the anti-aliased -/// coverage of its pixels ([`bevel_dist_inside`]), so a facet is planar at any angle. Soften blurs -/// the result. -fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, patterns: &PreparedPatterns<'_>) -> Map { - let size = b.size.max(1.0); - let mut h = if b.technique == BevelTechnique::Smooth { - let mut h = shape.clone(); - tent(&mut h, g.width); - h - } else { - let [din, dout] = bevel_dists(shape, size); - let soft = g.chisel_soft > 0.0; - let w = shape.w; - let v = par_fill(w, shape.h, 0.0, |y, row| { - for (x, o) in row.iter_mut().enumerate() { - let i = y * w + x; - *o = bevel_chisel_h(g.paint, size, din[i], dout[i], soft); - } - }); - let mut h = Map { w, h: shape.h, v }; - // Inner and outer Chisel Soft are not blurred in Photoshop (their facets equal Chisel - // Hard's across a straight edge); emboss styles keep the blur until measured. - if soft && g.paint == BevelPaint::Both { - tent(&mut h, g.chisel_soft); - } - h - }; - // Contour element: the height profile through the contour. - if let Some(c) = &b.contour { - h = apply_lut(h, Some(bevel_contour_lut(c))); - } - // Texture element: the pattern's luminance as extra height, scaled so a full-contrast step - // at 100 % depth slopes like the bevel at its depth. - if let Some(t) = &b.texture - && let Some(tile) = patterns.get(&t.id, &t.name) - { - let unit = if b.depth.abs() > 1e-6 { (g.depth / b.depth).abs().max(1e-3) } else { g.width.max(1.0) }; - let place = Placement::anchored(tex.anchor, t.link, t.phase, t.scale, 0.0); - let k = t.depth / unit; - let (x0, y0) = (tex.rect.x0, tex.rect.y0); - let w = h.w; - par_units( - h.v.len(), - &mut h.v, - w, - &mut [] as &mut [()], - 0, - || (), - |_, y, row, _| { - for (x, o) in row.iter_mut().enumerate() { - let (u, v) = place.map(f64::from(x0 + x as i32) + 0.5, f64::from(y0 + y as i32) + 0.5); - let p = tile.sample(u, v); - let l = (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) * p[3]; - *o += k * if t.invert { 1.0 - l } else { l }; - } - }, - ); - } - if b.soften >= 1.0 { - tent(&mut h, b.soften); - } - h -} - -/// Where a bevel texture tiles: the maps' rectangle, the document's patterns and the linked -/// origin (the effects reference point, else the layer's top-left). -pub struct TextureCtx<'a> { - pub rect: Rect, - pub patterns: &'a [Pattern], - pub anchor: (f64, f64), -} - -/// Chiselled height from the inside / outside distances (keep in sync with `fs_mbevelh`). -/// -/// Photoshop 27.11, measured across straight edges (sizes 10 and 20, depth 100 and 300): a chisel -/// facet has the constant slope `depth × size / (2 (size + 1))`, i.e. one height step of -/// `1 / (size + 1)` per pixel at the `depth × size / 2` scale of [`bevel_geom`]. Inner Hard's ramp -/// runs from half a pixel beyond the edge to `size + ½` (the facet is flat right up to the edge -/// pixel); Inner Soft starts a pixel further out, so its edge pixel is steeper; Outer Hard ends a -/// pixel further out. All within 1 level of Photoshop on those profiles. -pub fn bevel_chisel_h(paint: BevelPaint, size: f32, din: f32, dout: f32, soft: bool) -> f32 { - let ramp = size + 1.0; - match paint { - BevelPaint::Outer if !soft => { - let top = (size + 2.0) / ramp; - if dout > 0.0 { ((size + 1.5 - dout) / ramp).clamp(0.0, top) } else { top } - } - // Outer Soft: Outer Hard's ramp a pixel shorter, with a steeper edge pixel. - BevelPaint::Outer => { - if dout > 0.0 { - 1.0 - ((dout + 0.5) / ramp).clamp(0.0, 1.0) - } else { - (size + 2.0) / ramp - } - } - BevelPaint::Both => { - let half = size / 2.0 + 0.5; - if din > 0.0 { 0.5 + 0.5 * (din / half).clamp(0.0, 1.0) } else { 0.5 - 0.5 * (dout / half).clamp(0.0, 1.0) } - } - BevelPaint::Inner if soft => { - if din > 0.0 { - ((din + 1.5) / ramp).clamp(0.0, (size + 2.0) / ramp) - } else { - 0.0 - } - } - BevelPaint::Inner => { - if din > 0.0 { - ((din + 0.5) / ramp).clamp(0.0, 1.0) - } else { - 0.0 - } - } - } -} - -/// Bevel highlight and shadow maps: `[hi, sh]` (inner or outer) or `[hi, sh, hi_out, sh_out]` -/// (emboss styles). -fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &TextureCtx, patterns: &PreparedPatterns<'_>) -> (Vec, BevelPaint) { - let g = bevel_geom(b); - let hmap = bevel_height(shape, b, &g, tex, patterns); - let (angle, altitude) = if b.use_global_light { (light.angle, light.altitude) } else { (b.angle, b.altitude) }; - let (sa, ca) = angle.to_radians().sin_cos(); - let (se, ce) = altitude.to_radians().sin_cos(); - let light_v = [ca * ce, -sa * ce, se]; - // Region: 0 = inside (× the shape's alpha), 1 = under the layer's edge and outside. - // A pixel is on the bevel where its height is raised. Emboss styles also shade the last pixel - // past the blur's reach (a raised 4-neighbour: it still slopes; psd-tools layer_effects' - // emboss shadow runs one row past it), outer bevels don't (Photoshop oracle - // bevel-outer-smooth). - // Outer chisel bevels too: the pixel where their ramp reaches zero still slopes (Photoshop - // 27.11 shades it, half strength, at `size + 1½` px out). - let reach_past = g.paint == BevelPaint::Both || (g.paint == BevelPaint::Outer && b.technique != BevelTechnique::Smooth); - let on_bevel = |x: i64, y: i64| { - hmap.get(x, y) > BEVEL_H_EPS || (reach_past && [(1, 0), (-1, 0), (0, 1), (0, -1)].iter().any(|(dx, dy)| hmap.get(x + dx, y + dy) > BEVEL_H_EPS)) - }; - // The gloss contour remaps the shading `n · light` before it splits into highlight (above - // what it maps a flat face's `sin(altitude)` to) and shadow. Applied to the highlight and shadow amounts - // instead, a contour that starts high (Rolling Slope - Descending) lit every pixel the light - // missed, so a bevelled glyph's flat face took the full highlight (#7360) where Photoshop - // leaves it at the layer's colour. The Linear contour changes nothing either way. - let gloss = contour_lut(&b.gloss_contour); - let shade_into = |depth: f32, region_kind: u8| -> (Map, Map) { - let (mut hi, mut sh) = (Map::new(shape.w, shape.h, 0.0), Map::new(shape.w, shape.h, 0.0)); - // Rows on threads: every pixel reads only `hmap` and `shape`. - par_units( - hi.v.len(), - &mut hi.v, - shape.w, - &mut sh.v, - shape.w, - || (), - |_, y, hi_row, sh_row| { - let y = y as i64; - for x in 0..shape.w as i64 { - let i = y as usize * shape.w + x as usize; - let gx = (hmap.get(x + 1, y) - hmap.get(x - 1, y)) * 0.5 * depth; - let gy = (hmap.get(x, y + 1) - hmap.get(x, y - 1)) * 0.5 * depth; - let n = [-gx, -gy, 1.0]; - let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt(); - let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len; - let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) }; - let k = gloss.as_ref().map_or(shade - se, |l| lut_at(l, shade) - lut_at(l, se)); - if k > 0.0 { - hi_row[x as usize] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region; - } else { - sh_row[x as usize] = (-k / se.max(1e-3)).clamp(0.0, 1.0) * region; - } - } - }, - ); - (hi, sh) - }; - let maps = match g.paint { - BevelPaint::Inner | BevelPaint::Outer => { - let (hi, sh) = shade_into(g.depth, u8::from(g.paint == BevelPaint::Outer)); - vec![hi, sh] - } - BevelPaint::Both => { - // One map per colour over the whole bevel: the inside half where the shape is (× its - // alpha), the outside half (pillow: facing the other way) for the rest of each pixel. - // A 1 % edge pixel of a pillow emboss takes the outside shading (Photoshop oracle - // bevel-pillow-smooth), a 75 % one of an emboss mostly the inside (layer_effects). - let (hi, sh) = shade_into(g.depth, 0); - let (ho, so) = shade_into(if g.pillow { -g.depth } else { g.depth }, 1); - let mix = |a: Map, b: Map| -> Map { - let v = par_fill(a.w, a.h, 0.0, |y, row| { - for (x, o) in row.iter_mut().enumerate() { - let i = y * a.w + x; - let (x, y, s) = (a.v[i], b.v[i], shape.v[i]); - *o = if s > INSIDE_EPS { x } else { 0.0 } + y * (1.0 - s.min(1.0)); - } - }); - Map { w: a.w, h: a.h, v } - }; - vec![mix(hi, ho), mix(sh, so)] - } - }; - (maps, g.paint) -} - /// Effect maps derived from a layer's shape (its alpha), computed once over the layer's whole /// region and cropped per render tile. They depend only on the shape, the effect settings and the /// global light, never on the backdrop, so they can be cached across tiles and edits. @@ -1829,620 +245,5 @@ impl FxMaps { } } -/// The distance the two satin copies are offset by. Photoshop draws Distance 0 as 1 px (an -/// edge band of 2/size, measured in Photoshop 27.11), not as two copies cancelling out. -pub fn satin_distance(s: &photocraft_doc::effects::Satin) -> f32 { - s.distance.max(1.0) -} - -fn satin_map(shape: &Map, s: &photocraft_doc::effects::Satin) -> Map { - let (dx, dy) = offset(s.angle, satin_distance(s)); - let mut a = shape.shifted(dx, dy, 0.0); - let mut b = shape.shifted(-dx, -dy, 0.0); - // Two box passes of the satin size (fitted: 0.2 % mean error on psd-tools layer_effects). - tent(&mut a, s.size); - tent(&mut b, s.size); - let mut m = Map { w: shape.w, h: shape.h, v: a.v.iter().zip(&b.v).map(|(x, y)| (x - y).abs()).collect() }; - if s.invert { - m = m.map(|v| 1.0 - v); - } - let mut m = apply_lut(m, satin_lut(&s.contour)); - for (v, a) in m.v.iter_mut().zip(&shape.v) { - *v *= a; - } - m -} - -/// Build every effect map for `layer` from its alpha `shape` over `rect`. -pub fn build_maps(layer: &Layer, shape: Vec, rect: Rect, light: &GlobalLight, tex: &TextureCtx) -> FxMaps { - let prepared = PreparedPatterns::new(tex.patterns, PREPARED_PATTERN_BYTES); - build_maps_prepared(layer, shape, rect, light, tex, &prepared) -} - -/// How many region-sized arrays [`build_maps_prepared`] builds for `layer` (what -/// [`FxMaps::bytes`] counts): the shape, each effect's maps, and a stroke's distance fields. Kept -/// next to the builder so the effect cache's estimate (#8330) follows it. -pub(crate) fn map_count(layer: &Layer) -> usize { - let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); - let per: usize = items - .iter() - .map(|e| match e { - Effect::DropShadow(_) | Effect::InnerShadow(_) | Effect::OuterGlow(_) | Effect::InnerGlow(_) | Effect::Satin(_) => 1, - Effect::BevelEmboss(_) => 2, - _ => 0, - }) - .sum(); - let out_widths: Vec = - items.iter().filter_map(|e| if let Effect::Stroke(st) = e { Some(stroke_widths(st).1) } else { None }).filter(|w| *w > 0.0).collect(); - let has_stroke = items.iter().any(|e| matches!(e, Effect::Stroke(_))); - let outside = usize::from(out_widths.iter().any(|&w| !stroke_outside_exact(w))) + usize::from(out_widths.iter().any(|&w| stroke_outside_exact(w))); - let stroke = if has_stroke { 1 + outside } else { 0 }; - let vector_outline = - if has_stroke && matches!(layer.content, photocraft_doc::LayerContent::Shape(_)) && crate::effect_outline(layer).is_none() { outside } else { 0 }; - 1 + per + stroke + vector_outline -} - -pub(crate) fn build_maps_prepared( - layer: &Layer, - shape: Vec, - rect: Rect, - light: &GlobalLight, - tex: &TextureCtx, - patterns: &PreparedPatterns<'_>, -) -> FxMaps { - let (w, h) = (rect.width() as usize, rect.height() as usize); - let shape = Map { w, h, v: shape }; - let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); - let mut bevel_paint = vec![BevelPaint::Inner; items.len()]; - let per: Vec> = items - .iter() - .enumerate() - .map(|(i, e)| match e { - Effect::DropShadow(s) => vec![shadow_map(&shape, s, light, false, (rect.x0, rect.y0))], - Effect::InnerShadow(s) => vec![shadow_map(&shape, s, light, true, (rect.x0, rect.y0))], - Effect::OuterGlow(g) => vec![glow_map(&shape, g, false, (rect.x0, rect.y0))], - Effect::InnerGlow(g) => vec![glow_map(&shape, g, true, (rect.x0, rect.y0))], - Effect::Satin(s) => vec![satin_map(&shape, s)], - Effect::BevelEmboss(b) => { - let (maps, paint) = bevel_maps(&shape, b, light, tex, patterns); - bevel_paint[i] = paint; - maps - } - _ => Vec::new(), - }) - .collect(); - let has_stroke = items.iter().any(|e| matches!(e, Effect::Stroke(_))); - let vector_shape = matches!(layer.content, photocraft_doc::LayerContent::Shape(_)); - // A stroke's outer edge keeps the 5 × 5 chamfer while its outside width is under - // `STROKE_CHAMFER_MAX` — Photoshop matches the chamfer's sub-pixel edge seeding at small - // offsets — and uses the exact Euclidean transform at or above it, where the chamfer's octagon - // facets a wide stroke (#3646). Inside stroke distances always keep the chamfer. Each outer - // field is built only when a stroke of that width is present; the compositor picks per stroke, - // so one layer may hold both a narrow and a wide stroke. - let out_widths: Vec = - items.iter().filter_map(|e| if let Effect::Stroke(st) = e { Some(stroke_widths(st).1) } else { None }).filter(|w| *w > 0.0).collect(); - let chamfer_out = out_widths.iter().any(|&w| !stroke_outside_exact(w)); - let exact_out = out_widths.iter().any(|&w| stroke_outside_exact(w)); - let (din, dout, dout_exact) = if has_stroke { - ( - Some(dist_inside_by(&shape, Metric::Chamfer)), - chamfer_out.then(|| dist_outside_by(&shape, Metric::Chamfer)), - exact_out.then(|| dist_outside_by(&shape, Metric::Euclidean)), - ) - } else { - (None, None, None) - }; - // Without an outline (unfilled shapes), estimate the vector outline from local coverage; it - // picks the chamfer or the exact transform the same way. - let outline = crate::effect_outline(layer).is_some(); - let (vdout, vdout_exact) = if has_stroke && vector_shape && !outline { - let lc = local_coverage(&shape); - (chamfer_out.then(|| dist_outside_by(&lc, Metric::Chamfer)), exact_out.then(|| dist_outside_by(&lc, Metric::Euclidean))) - } else { - (None, None) - }; - let mut frames: Vec<(u32, Rect)> = Vec::new(); - for e in &items { - if let Effect::Stroke(st) = e - && matches!(st.paint, FxPaint::Gradient(_)) - { - let out_w = stroke_widths(st).1; - if !frames.iter().any(|f| f.0 == out_w.to_bits()) { - frames.push((out_w.to_bits(), stroke_frame(&shape, out_w, rect))); - } - } - } - FxMaps { rect, shape, per, bevel_paint, din, dout, dout_exact, vdout, vdout_exact, outline, frames } -} - -/// Far outside any shape (distance fill for cropped distance fields). -const FAR: f32 = 1.0e9; - -/// Keep an exterior effect behind the layer's shape when Fill is partly or wholly -/// transparent. The visible part beneath a fully opaque fill is already covered by the -/// layer, so avoid attenuating anti-aliased edges twice in that case. -fn knock_out_exterior(map: &mut Map, shape: &Map, fill_opacity: f32) { - let see_through = 1.0 - fill_opacity.clamp(0.0, 1.0); - for (coverage, alpha) in map.v.iter_mut().zip(&shape.v) { - *coverage *= 1.0 - alpha * see_through; - } -} - -/// How far the layer lets a knocked-out drop shadow show beneath its own shape (Layer Knocks Out -/// Drop Shadow), 0 = covered, 1 = knocked out wholly. In a normal mode an opaque layer covers the -/// shadow anyway, so only see-through fill knocks it out (and anti-aliased edges are not -/// attenuated twice). In any other mode the layer blends with what's beneath it, shadow and all: -/// an Exclusion or Difference layer would invert it, Multiply darken by it, Screen show it as -/// grey. Photoshop keeps it out from under the shape, so here it's knocked out wholly. -pub fn shadow_see_through(layer: &Layer) -> f32 { - if matches!(layer.blend, BlendMode::Normal | BlendMode::Dissolve | BlendMode::PassThrough) { 1.0 - layer.fill_opacity.clamp(0.0, 1.0) } else { 1.0 } -} - -/// Blend Interior Effects as Group off (Photoshop's default): the layer's mode applies to its -/// own pixels only, and the interior effects paint over the blended result. The layer is merged -/// into the backdrop before they paint, so an Overlay colour overlay on a black Color-mode layer -/// tints the grey beneath it (#3996). A Normal layer merges only when an interior effect blends -/// in another mode: below 100 % fill that effect sees the backdrop through the layer, so a Soft -/// Light overlay on a Fill 0 % layer soft-lights the backdrop instead of showing its own colour -/// (#6232). Normal effects give the same result either way, and the merge would count a -/// half-transparent backdrop twice, so those layers keep the plain composite. -pub fn premerges_layer(layer: &Layer) -> bool { - !layer.advanced.blend_interior - && match layer.blend { - BlendMode::PassThrough | BlendMode::Dissolve => false, - BlendMode::Normal => blends_inside(layer), - _ => true, - } -} - -/// `true` if an enabled effect painted inside the layer (with its content) blends in a mode -/// other than Normal. -fn blends_inside(layer: &Layer) -> bool { - let blends = |m: BlendMode| m != BlendMode::Normal; - layer.effects.items.iter().filter(|e| e.enabled()).any(|e| match e { - Effect::ColorOverlay { common, .. } | Effect::GradientOverlay { common, .. } | Effect::PatternOverlay { common, .. } => blends(common.blend), - Effect::Satin(s) => blends(s.common.blend), - Effect::InnerGlow(g) => blends(g.common.blend), - Effect::InnerShadow(s) => blends(s.common.blend), - Effect::Stroke(s) => stroke_widths(s).0 > 0.0 && blends(s.common.blend), - Effect::BevelEmboss(b) => bevel_geom(b).paint == BevelPaint::Inner && (blends(b.highlight.blend) || blends(b.shadow.blend)), - Effect::DropShadow(_) | Effect::OuterGlow(_) => false, - }) -} - -/// Composites `content` (the layer's own pixels over `big`, alpha already -/// masked, clipped layers applied) plus its effects into `backdrop`. -pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Buffer, maps: &FxMaps, layer_bounds: Rect, patterns: &[Pattern]) { - let prepared = PreparedPatterns::new(patterns, PREPARED_PATTERN_BYTES); - composite_with_effects_prepared(layer, content, backdrop, maps, layer_bounds, &prepared, None); -} - -pub(crate) fn composite_with_effects_prepared( - layer: &Layer, - content: &Buffer, - backdrop: &mut Buffer, - maps: &FxMaps, - layer_bounds: Rect, - patterns: &PreparedPatterns<'_>, - vstroke: Option>, -) { - let big = content.rect; - let (w, h) = (big.width() as usize, big.height() as usize); - // The effect shape: the content's alpha (with a split-off vector stroke, `content` is the - // unmasked fill and the mask applies to fill ∪ stroke), joined with a filled shape's outline. - let kmask = |i: usize| vstroke.as_ref().and_then(|v| v.mask).and_then(|m| m.get(i)).copied().unwrap_or(1.0); - let union = |i: usize, a: f32| vstroke.as_ref().and_then(|v| v.stroke.px.get(i)).map_or(a, |s| kmask(i) * (a + s[3] * (1.0 - a))); - // Transparency Shapes Layer off: the shape is the whole layer (its masks, as the maps were - // built), and the content's own transparency acts like fill opacity within it. - let shapeless = !layer.advanced.transparency_shapes; - let shape = if shapeless { - maps.crop(&maps.shape, big, 0.0) - } else if maps.outline { - let o = maps.crop(&maps.shape, big, 0.0); - Map { w, h, v: o.v.iter().zip(&content.px).enumerate().map(|(i, (o, p))| o.max(union(i, p[3]))).collect() } - } else { - Map { w, h, v: content.px.iter().enumerate().map(|(i, p)| union(i, p[3])).collect() } - }; - let relative = shapeless || maps.outline || vstroke.is_some(); - let fx = |i: usize, k: usize| maps.crop(&maps.per[i][k], big, 0.0); - // Layer bounds (gradients aligned with the layer use the whole layer, - // independent of the render rect). - let sb = layer_bounds; - // Linked patterns tile from the effects reference point (else the layer's top-left). - let anchor = layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))); - let rect = backdrop.rect; - let before = backdrop.clone(); - // Exterior effects are painted on a backdrop copy extended to `big`. - let mut work = Buffer::transparent(big); - for y in rect.y0.max(big.y0)..rect.y1.min(big.y1) { - for x in rect.x0.max(big.x0)..rect.x1.min(big.x1) { - work.px[((y - big.y0) as usize) * w + (x - big.x0) as usize] = before.get(x, y); - } - } - let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); - let vector_shape = matches!(layer.content, photocraft_doc::LayerContent::Shape(_)); - // Multiple instances: the first listed is on top, so paint in reverse. - let rev = || items.iter().copied().enumerate().rev(); - - for (i, e) in rev() { - if let Effect::DropShadow(s) = e { - let mut m = fx(i, 0); - if s.knocks_out { - // The layer hides the shadow beneath it where its fill is see-through (at 100 % - // fill in a normal mode it covers it anyway; at 0 % the shape shows the bare - // backdrop), and wholly in a mode that blends with it ([`shadow_see_through`]). - knock_out_exterior(&mut m, &shape, 1.0 - shadow_see_through(layer)); - } - paint_color(&mut work, &m, rgb(&s.color), s.common.blend, s.common.opacity); - } - } - for (i, e) in rev() { - if let Effect::OuterGlow(g) = e { - let mut m = fx(i, 0); - // The glow is behind the shape, not painted across its interior when Fill is 0 %. - // Preserve the existing anti-aliased edge when the fill is fully opaque. - knock_out_exterior(&mut m, &shape, layer.fill_opacity); - paint_glow(&mut work, &m, g, sb, anchor, big, patterns); - } - } - - // The layer: content at fill opacity, then interior effects. Interior effects are painted - // relative to the layer's shape (alpha = coverage within the shape), then the shape's alpha - // applies: a colour overlay at 100 % replaces the colour of a half-transparent edge pixel and - // keeps its alpha, as in Photoshop. - let fill = layer.fill_opacity; - // Blend Interior Effects as Group: the interior effects (overlays, satin, inner glow) are - // combined with the content first, and fill opacity applies to the combination. - let interior_group = layer.advanced.blend_interior && fill < 1.0; - let content_fill = if interior_group { 1.0 } else { fill }; - let inside = |a: f32| a > INSIDE_EPS; - // Within an outline (or a split-off vector stroke) the content's own transparency (a fading - // gradient fill) acts like fill opacity: the effects still cover the whole shape. - let lay_alpha = |i: usize, p: &[f32; 4], a: f32| { - if !inside(a) { - 0.0 - } else if relative { - content_fill * (kmask(i) * p[3] / a).min(1.0) - } else { - content_fill - } - }; - let mut lay = Buffer { rect: big, px: content.px.iter().zip(&shape.v).enumerate().map(|(i, (p, a))| [p[0], p[1], p[2], lay_alpha(i, p, *a)]).collect() }; - let gamma = crate::text_gamma(layer); - let premerge = premerges_layer(layer); - if premerge { - for (lp, wp) in lay.px.iter_mut().zip(&work.px) { - *lp = psblend::composite_gamma(layer.blend, *wp, *lp, 1.0, gamma); - } - } - let rel = |m: Map| -> Map { - let v = m.v.iter().zip(&shape.v).map(|(m, a)| if inside(*a) { (m / a).min(1.0) } else { 0.0 }).collect(); - Map { w: m.w, h: m.h, v } - }; - let full = Map { w, h, v: shape.v.iter().map(|a| if inside(*a) { 1.0 } else { 0.0 }).collect() }; - for (_, e) in rev() { - if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e { - paint_pattern(&mut lay, &full, patterns, name, id, Placement::anchored(anchor, *link, *phase, *scale, *angle), big, common.blend, common.opacity); - } - } - for (_, e) in rev() { - if let Effect::GradientOverlay { common, gradient, .. } = e { - paint_fx(&mut lay, &full, &FxPaint::Gradient(gradient.clone()), sb, anchor, big, common.blend, common.opacity, patterns) - } - } - for (_, e) in rev() { - if let Effect::ColorOverlay { common, color } = e { - paint_color(&mut lay, &full, rgb(color), common.blend, common.opacity); - } - } - for (i, e) in rev() { - if let Effect::Satin(s) = e { - let m = rel(fx(i, 0)); - paint_color(&mut lay, &m, rgb(&s.color), s.common.blend, s.common.opacity); - } - } - for (i, e) in rev() { - if let Effect::InnerGlow(g) = e { - paint_glow(&mut lay, &rel(fx(i, 0)), g, sb, anchor, big, patterns); - } - } - if interior_group { - for p in &mut lay.px { - p[3] *= fill.max(0.0); - } - } - for (i, e) in rev() { - if let Effect::InnerShadow(s) = e { - let m = rel(fx(i, 0)); - paint_color(&mut lay, &m, rgb(&s.color), s.common.blend, s.common.opacity); - } - } - // A stroked shape's vector stroke: Photoshop draws it above the fill's clipped layers and - // interior effects, below the stroke effect (psd-tools stroke-composite). - if let Some(vs) = &vstroke { - for (i, ((p, s), a)) in lay.px.iter_mut().zip(&vs.stroke.px).zip(&shape.v).enumerate() { - if s[3] > 0.0 && inside(*a) { - *p = psblend::composite(BlendMode::Normal, *p, [s[0], s[1], s[2], fill * (kmask(i) * s[3] / a).min(1.0)], 1.0); - } - } - } - // Strokes. Inside parts are painted over the layer (bottom instance first); outside parts - // are slid beneath it, so the first listed (top) instance is processed first. - let strokes: Vec<&photocraft_doc::StrokeFx> = items.iter().filter_map(|e| if let Effect::Stroke(s) = e { Some(s) } else { None }).collect(); - let ready = !strokes.is_empty(); - let din = if ready { maps.din.as_ref().map(|a| maps.crop_vec(a, big, 0.0)).unwrap_or_default() } else { Vec::new() }; - // A stroke's outer edge picks the chamfer or the exact field by its width - // ([`stroke_outside_exact`]); both are cropped here, and only the ones a stroke needs exist. - let crop_out = |v: &Option>| v.as_ref().map(|b| maps.crop_vec(b, big, FAR)); - let (dout, dout_exact, vdout, vdout_exact) = - if ready { (crop_out(&maps.dout), crop_out(&maps.dout_exact), crop_out(&maps.vdout), crop_out(&maps.vdout_exact)) } else { (None, None, None, None) }; - let widths = stroke_widths; - // A gradient stroke aligned with the layer spans the stroke's own extent. - let frame = |st: &photocraft_doc::StrokeFx| maps.stroke_frame(st).unwrap_or(sb); - for st in strokes.iter().rev().copied() { - let (in_w, _) = widths(st); - if in_w <= 0.0 { - continue; - } - let mut m = Map::new(w, h, 0.0); - for ((mv, a), dv) in m.v.iter_mut().zip(&shape.v).zip(&din) { - *mv = if inside(*a) { (in_w + 0.5 - dv).clamp(0.0, 1.0) } else { 0.0 }; - } - paint_fx(&mut lay, &m, &st.paint, frame(st), anchor, big, st.common.blend, st.common.opacity, patterns); - } - for (i, e) in rev() { - if let Effect::BevelEmboss(b) = e - && maps.bevel_paint[i] == BevelPaint::Inner - { - let (hi, sh) = (rel(fx(i, 0)), rel(fx(i, 1))); - paint_color(&mut lay, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); - paint_color(&mut lay, &sh, rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); - } - } - // The shape's own alpha. - for (p, a) in lay.px.iter_mut().zip(&shape.v) { - p[3] *= a.min(1.0); - } - // Shape layers without a filled outline stroke their vector outline, estimated from local - // coverage; every other layer strokes its shape. The width then picks the field. - let vector_outline = vector_shape && !maps.outline; - // Outside parts lie beneath the layer and blend onto the backdrop with their own mode. A - // higher stroke covers the ones below it (Photoshop: a Multiply stroke listed above a wider - // Normal stroke multiplies the backdrop, not the lower stroke). Each stroke's share is its - // coverage × opacity not yet taken by strokes above; for Normal strokes this equals stacking - // them top over bottom. - if strokes.iter().any(|st| widths(st).1 > 0.0) { - let base = work.clone(); - let mut acc = vec![[0.0f32; 4]; w * h]; // premultiplied Σ share·blended - let mut cover = vec![0.0f32; w * h]; - for st in strokes.iter().copied() { - let (_, out_w) = widths(st); - if out_w <= 0.0 { - continue; - } - // Shape layers: Photoshop strokes the vector outline (estimated from local coverage - // for unfilled shapes); the stroke never shows through the shape's pixels. Along a - // filled shape's outline it covers the part of each edge pixel outside the path. - let exact = stroke_outside_exact(out_w); - let d: &[f32] = if vector_outline { - (if exact { vdout_exact.as_deref() } else { vdout.as_deref() }).unwrap_or_default() - } else if exact { - dout_exact.as_deref().unwrap_or_default() - } else { - dout.as_deref().unwrap_or_default() - }; - let mut share = vec![0.0f32; w * h]; - for (i, sh) in share.iter_mut().enumerate() { - let band = (out_w + 0.5 - d[i]).clamp(0.0, 1.0); - let k = - if inside(shape.v[i]) { if vector_shape && !maps.outline { 0.0 } else { band * outline_share(shape.v[i], lay.px[i][3]) } } else { band }; - let mut k = k * st.common.opacity; - if st.common.blend == BlendMode::Dissolve { - let (x, y) = (i64::from(big.x0) + (i % w) as i64, i64::from(big.y0) + (i / w) as i64); - k = if k > 0.0 && dissolves_in(x, y, k) { 1.0 } else { 0.0 }; - } - *sh = k * (1.0 - cover[i]); - cover[i] += *sh; - } - // The stroke blended over the backdrop at full coverage. - let mut blended = base.clone(); - let ones = Map { w, h, v: share.iter().map(|&s| if s > 0.0 { 1.0 } else { 0.0 }).collect() }; - // The share already carries the Dissolve choice, so the paint itself composites as Normal. - let paint_blend = if st.common.blend == BlendMode::Dissolve { BlendMode::Normal } else { st.common.blend }; - paint_fx(&mut blended, &ones, &st.paint, frame(st), anchor, big, paint_blend, 1.0, patterns); - for ((a, b), s) in acc.iter_mut().zip(&blended.px).zip(&share) { - if *s > 0.0 { - for c in 0..3 { - a[c] += s * b[c] * b[3]; - } - a[3] += s * b[3]; - } - } - } - for ((p, a), c) in work.px.iter_mut().zip(&acc).zip(&cover) { - if *c <= 0.0 { - continue; - } - let k = 1.0 - c.min(1.0); - let alpha = p[3] * k + a[3]; - if alpha > 0.0 { - *p = [(p[0] * p[3] * k + a[0]) / alpha, (p[1] * p[3] * k + a[1]) / alpha, (p[2] * p[3] * k + a[2]) / alpha, alpha.min(1.0)]; - } - } - } - for (i, e) in rev() { - if let Effect::BevelEmboss(b) = e - && maps.bevel_paint[i] == BevelPaint::Outer - { - let (hi, sh) = (fx(i, 0), fx(i, 1)); - paint_color(&mut work, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); - paint_color(&mut work, &sh, rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); - } - } - - // Layer (with interior effects) onto the exterior result, in the layer's mode. - let mode = if premerge || layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; - for (wp, lp) in work.px.iter_mut().zip(&lay.px) { - if lp[3] > 0.0 { - *wp = psblend::composite_gamma(mode, *wp, *lp, 1.0, gamma); - } - } - // Emboss styles shade the composited layer (their maps cover inside and outside). Painting - // them into the layer before its (text-gamma) composite left a type layer's lit top edges up - // to 6/255 dark (psd-tools layer_effects Emboss: 7.8 → 5.7/255). - for (i, e) in rev() { - if let Effect::BevelEmboss(b) = e - && maps.bevel_paint[i] == BevelPaint::Both - { - paint_color(&mut work, &fx(i, 0), rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); - paint_color(&mut work, &fx(i, 1), rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); - } - } - // Layer opacity applies to the whole stack. - let op = layer.opacity; - for y in rect.y0..rect.y1 { - for x in rect.x0..rect.x1 { - let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize; - let a = before.px[i]; - let b = if x >= big.x0 && x < big.x1 && y >= big.y0 && y < big.y1 { work.px[((y - big.y0) as usize) * w + (x - big.x0) as usize] } else { a }; - backdrop.px[i] = if layer.blend == BlendMode::Dissolve { - // Dissolve applies layer opacity to the completed interior/exterior effect - // stack as pixel coverage, not continuous gray interpolation (#3051). - if crate::dissolve_noise(x, y) < op { b } else { a } - } else { - mix_premul(a, b, op) - }; - } - } -} - -/// Coverage of an outside stroke beneath a filled shape's edge pixel, for a pixel the outline -/// covers `cov` of and the layer (with its interior effects) ends at alpha `l`. Photoshop treats -/// the stroke and the shape as disjoint areas: the stroke fills the part outside the path and -/// the layer adds its own alpha (psd-tools stroke-effects: a 58 % covered edge pixel of an -/// opaque fill ends opaque, one of a faded fill at 42 % + its alpha). Composited beneath the -/// layer, `share + l (1 - share) = (1 - cov) + l`. -pub fn outline_share(cov: f32, l: f32) -> f32 { - let outside = (1.0 - cov.clamp(0.0, 1.0)).max(0.0); - if outside <= 1e-6 { - return 0.0; - } - let rest = 1.0 - l.clamp(0.0, 1.0); - if rest <= 1e-6 { 1.0 } else { (outside / rest).min(1.0) } -} - -/// (inside width, outside width) of a stroke. -pub fn stroke_widths(st: &photocraft_doc::StrokeFx) -> (f32, f32) { - match st.position { - StrokePosition::Outside => (0.0, st.size), - StrokePosition::Inside => (st.size, 0.0), - StrokePosition::Center => (st.size / 2.0, st.size / 2.0), - } -} - -/// The frame a gradient stroke aligned with the layer is laid out in: the pixel bounds of the -/// effect shape (over `rect`) grown by the stroke's outside width less one pixel. Photoshop -/// spans the gradient over the stroke's extent, not the layer's: a 4 px outside stroke around a -/// 22 px square runs its 90° gradient over 28 px (psd-tools stroke-effects), a 3 px one around -/// 36 px of type over 40 px (psd-tools effect-stroke-gradient). -fn stroke_frame(shape: &Map, out_w: f32, rect: Rect) -> Rect { - let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize); - for y in 0..shape.h { - for x in 0..shape.w { - if shape.v[y * shape.w + x] > INSIDE_EPS { - (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)); - } - } - } - if x0 == usize::MAX { - return rect; - } - let grow = if out_w.is_finite() { (out_w.min(MAX_REACH).ceil() as i32 - 1).max(0) } else { 0 }; - Rect::new(rect.x0 + x0 as i32, rect.y0 + y0 as i32, rect.x0 + x1 as i32, rect.y0 + y1 as i32).inflate(grow) -} - -/// A stroked shape's vector stroke, composited apart from its fill (which the compositor then -/// passes unmasked): the stroke's pixels over the render rect and the layer's mask values. -pub(crate) struct VectorStroke<'a> { - pub stroke: &'a Buffer, - pub mask: Option<&'a [f32]>, -} - -/// Premultiplied linear interpolation between two straight-alpha pixels. -fn mix_premul(a: [f32; 4], b: [f32; 4], k: f32) -> [f32; 4] { - let alpha = a[3] + (b[3] - a[3]) * k; - if alpha <= 0.0 { - return [0.0; 4]; - } - let mut out = [0.0; 4]; - for c in 0..3 { - out[c] = (a[c] * a[3] + (b[c] * b[3] - a[c] * a[3]) * k) / alpha; - } - out[3] = alpha; - out -} - -/// A distance field of an effect shape, as the map builders above compute it (for the GPU -/// compositor, which builds the rest of the maps itself; keep in sync with `shadow_map`, -/// `glow_map`, `bevel_maps` and `build_maps`). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum FieldKind { - /// `dist_outside` of the shape: precise outer glows. - Outside, - /// `dist_inside` of the shape: precise inner glows. - Inside, - /// `bevel_dist_outside` of the shape: the outside distance of chiselled bevels. - BevelOutside, - /// `bevel_dist_inside` of the shape: the inside distance of chiselled bevels. - BevelInside, - /// Chamfer distance outside the shape: a narrow raster stroke's outer edge (see - /// [`stroke_outside_exact`]), and the spread of drop shadows and softer outer glows - /// ([`dilate`]); their metric is fitted to Photoshop (#224) and keeps the sub-pixel seeding. - StrokeOutside, - /// Chamfer distance outside `1 - alpha`: the choke of inner shadows and softer inner glows. - ChokeInside, - /// Stroke distance inside the shape. - StrokeInside, - /// Exact Euclidean distance outside the shape: a wide raster stroke's outer edge (see - /// [`stroke_outside_exact`]). The chamfer's level sets are polygons (an ~8-fold octagon), so a - /// wide stroke's outer boundary facets; the shadow / glow spread above keeps the chamfer (#3646). - StrokeOutsideExact, - /// Stroke distance outside a shape layer's outline (from its local coverage), exact Euclidean. - StrokeOutsideVector, - /// Chamfer distance outside a shape layer's outline (from its local coverage): a narrow vector - /// stroke's outer edge, where the chamfer matches Photoshop (see [`STROKE_CHAMFER_MAX`]). - StrokeOutsideVectorChamfer, -} - -/// The `kind` distance field of the shape `alpha` (row-major `w × h`). Values past `reach` pixels -/// from the shape's edge are only meant to be large (the bevel fields skip refining them). -pub fn distance_field(kind: FieldKind, alpha: Vec, w: usize, h: usize, reach: f32) -> Vec { - let s = Map { w, h, v: alpha }; - match kind { - FieldKind::Outside => dist_outside(&s), - FieldKind::Inside => dist_inside(&s), - FieldKind::BevelOutside => bevel_dist_outside(&s, &sharp_edges(&s), reach), - FieldKind::BevelInside => bevel_dist_inside(&s, &sharp_edges(&s), reach), - FieldKind::StrokeOutside => dist_outside_by(&s, Metric::Chamfer), - FieldKind::ChokeInside => dist_outside_by(&s.map(|a| 1.0 - a), Metric::Chamfer), - FieldKind::StrokeInside => dist_inside_by(&s, Metric::Chamfer), - FieldKind::StrokeOutsideExact => dist_outside_by(&s, Metric::Euclidean), - FieldKind::StrokeOutsideVector => dist_outside_by(&local_coverage(&s), Metric::Euclidean), - FieldKind::StrokeOutsideVectorChamfer => dist_outside_by(&local_coverage(&s), Metric::Chamfer), - } -} - -/// Both chiselled bevel fields of `alpha`, `[BevelInside, BevelOutside]`: each is its -/// [`distance_field`], with the sharp edges they both start from found once. -pub fn bevel_distance_fields(alpha: Vec, w: usize, h: usize, reach: f32) -> [Vec; 2] { - bevel_dists(&Map { w, h, v: alpha }, reach) -} - -/// The inside and outside bevel distances of `s`, from one set of sharp edges. -fn bevel_dists(s: &Map, reach: f32) -> [Vec; 2] { - let sharp = sharp_edges(s); - [bevel_dist_inside(s, &sharp, reach), bevel_dist_outside(s, &sharp, reach)] -} - #[cfg(test)] mod tests; diff --git a/crates/compose/src/effects/bevel.rs b/crates/compose/src/effects/bevel.rs new file mode 100644 index 0000000000..ec038d842f --- /dev/null +++ b/crates/compose/src/effects/bevel.rs @@ -0,0 +1,284 @@ +use super::blur::tent; +use super::distance::{INSIDE_EPS, bevel_dists, par_fill, par_units}; +use super::paint::{apply_lut, bevel_contour_lut, contour_lut, lut_at, offset, satin_lut}; +use super::*; + +/// Where a bevel's maps paint: inside the shape (with the layer), outside it (onto the +/// backdrop), or both (emboss styles: maps 0–1 inside, 2–3 outside). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BevelPaint { + Inner, + Outer, + Both, +} + +/// Height below which an outer bevel pixel counts as off the bevel (beyond the blur's reach): +/// above float noise of the running-sum blur (~3e-7), far below anything that shades. +pub const BEVEL_H_EPS: f32 = 1e-5; + +/// Bevel geometry shared by the CPU maps and the GPU programs. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BevelGeom { + pub paint: BevelPaint, + /// Box width of the smooth height blur (size; half the size, rounded up, for emboss styles). + pub width: f32, + /// Height-map gradient scale: depth × width (smooth) or depth × size (chisel), signed by + /// direction. + pub depth: f32, + /// Pillow emboss: the outside slopes face the other way. + pub pillow: bool, + /// Chisel Soft: extra tent width over the chiselled height map. + pub chisel_soft: f32, +} + +pub fn bevel_geom(b: &Bevel) -> BevelGeom { + let size = b.size.max(1.0); + let emboss = matches!(b.style, BevelStyle::Emboss | BevelStyle::PillowEmboss); + let paint = match b.style { + BevelStyle::OuterBevel => BevelPaint::Outer, + BevelStyle::Emboss | BevelStyle::PillowEmboss => BevelPaint::Both, + BevelStyle::InnerBevel | BevelStyle::StrokeEmboss => BevelPaint::Inner, + }; + // Emboss styles straddle the edge with half the size, rounded up to whole pixels: a 41 px + // emboss blurs over 21 (psd-tools layer_effects: 20.5 left narrow letter parts up to + // 5.7/255 dark, 21 is within 2.2). + let width = if emboss { (size / 2.0).ceil() } else { size }; + let smooth = b.technique == BevelTechnique::Smooth; + let sign = if b.up { 1.0 } else { -1.0 }; + BevelGeom { + paint, + width, + // A bevel rises `depth × width / 2` px: Smooth with a slope falling from `depth` at the + // edge (the tent), a chisel with the constant slope of its ramp (see `bevel_chisel_h`). + depth: b.depth * if smooth { width } else { size / 2.0 } * sign, + pillow: b.style == BevelStyle::PillowEmboss, + chisel_soft: if b.technique == BevelTechnique::ChiselSoft { (size / 4.0).max(1.0) } else { 0.0 }, + } +} + +/// Bevel height map in `0..=1`. Smooth: the shape blurred by two box passes of the bevel +/// width. Chisel: linear ramps of the distance to the edge (size wide; emboss styles straddle the +/// edge), slightly blurred for Chisel Soft. The distance puts the edge by the anti-aliased +/// coverage of its pixels ([`bevel_dist_inside`]), so a facet is planar at any angle. Soften blurs +/// the result. +fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, patterns: &PreparedPatterns<'_>) -> Map { + let size = b.size.max(1.0); + let mut h = if b.technique == BevelTechnique::Smooth { + let mut h = shape.clone(); + tent(&mut h, g.width); + h + } else { + let [din, dout] = bevel_dists(shape, size); + let soft = g.chisel_soft > 0.0; + let w = shape.w; + let v = par_fill(w, shape.h, 0.0, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + let i = y * w + x; + *o = bevel_chisel_h(g.paint, size, din[i], dout[i], soft); + } + }); + let mut h = Map { w, h: shape.h, v }; + // Inner and outer Chisel Soft are not blurred in Photoshop (their facets equal Chisel + // Hard's across a straight edge); emboss styles keep the blur until measured. + if soft && g.paint == BevelPaint::Both { + tent(&mut h, g.chisel_soft); + } + h + }; + // Contour element: the height profile through the contour. + if let Some(c) = &b.contour { + h = apply_lut(h, Some(bevel_contour_lut(c))); + } + // Texture element: the pattern's luminance as extra height, scaled so a full-contrast step + // at 100 % depth slopes like the bevel at its depth. + if let Some(t) = &b.texture + && let Some(tile) = patterns.get(&t.id, &t.name) + { + let unit = if b.depth.abs() > 1e-6 { (g.depth / b.depth).abs().max(1e-3) } else { g.width.max(1.0) }; + let place = Placement::anchored(tex.anchor, t.link, t.phase, t.scale, 0.0); + let k = t.depth / unit; + let (x0, y0) = (tex.rect.x0, tex.rect.y0); + let w = h.w; + par_units( + h.v.len(), + &mut h.v, + w, + &mut [] as &mut [()], + 0, + || (), + |_, y, row, _| { + for (x, o) in row.iter_mut().enumerate() { + let (u, v) = place.map(f64::from(x0 + x as i32) + 0.5, f64::from(y0 + y as i32) + 0.5); + let p = tile.sample(u, v); + let l = (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) * p[3]; + *o += k * if t.invert { 1.0 - l } else { l }; + } + }, + ); + } + if b.soften >= 1.0 { + tent(&mut h, b.soften); + } + h +} + +/// Where a bevel texture tiles: the maps' rectangle, the document's patterns and the linked +/// origin (the effects reference point, else the layer's top-left). +pub struct TextureCtx<'a> { + pub rect: Rect, + pub patterns: &'a [Pattern], + pub anchor: (f64, f64), +} + +/// Chiselled height from the inside / outside distances (keep in sync with `fs_mbevelh`). +/// +/// Photoshop 27.11, measured across straight edges (sizes 10 and 20, depth 100 and 300): a chisel +/// facet has the constant slope `depth × size / (2 (size + 1))`, i.e. one height step of +/// `1 / (size + 1)` per pixel at the `depth × size / 2` scale of [`bevel_geom`]. Inner Hard's ramp +/// runs from half a pixel beyond the edge to `size + ½` (the facet is flat right up to the edge +/// pixel); Inner Soft starts a pixel further out, so its edge pixel is steeper; Outer Hard ends a +/// pixel further out. All within 1 level of Photoshop on those profiles. +pub fn bevel_chisel_h(paint: BevelPaint, size: f32, din: f32, dout: f32, soft: bool) -> f32 { + let ramp = size + 1.0; + match paint { + BevelPaint::Outer if !soft => { + let top = (size + 2.0) / ramp; + if dout > 0.0 { ((size + 1.5 - dout) / ramp).clamp(0.0, top) } else { top } + } + // Outer Soft: Outer Hard's ramp a pixel shorter, with a steeper edge pixel. + BevelPaint::Outer => { + if dout > 0.0 { + 1.0 - ((dout + 0.5) / ramp).clamp(0.0, 1.0) + } else { + (size + 2.0) / ramp + } + } + BevelPaint::Both => { + let half = size / 2.0 + 0.5; + if din > 0.0 { 0.5 + 0.5 * (din / half).clamp(0.0, 1.0) } else { 0.5 - 0.5 * (dout / half).clamp(0.0, 1.0) } + } + BevelPaint::Inner if soft => { + if din > 0.0 { + ((din + 1.5) / ramp).clamp(0.0, (size + 2.0) / ramp) + } else { + 0.0 + } + } + BevelPaint::Inner => { + if din > 0.0 { + ((din + 0.5) / ramp).clamp(0.0, 1.0) + } else { + 0.0 + } + } + } +} + +/// Bevel highlight and shadow maps: `[hi, sh]` (inner or outer) or `[hi, sh, hi_out, sh_out]` +/// (emboss styles). +pub(super) fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &TextureCtx, patterns: &PreparedPatterns<'_>) -> (Vec, BevelPaint) { + let g = bevel_geom(b); + let hmap = bevel_height(shape, b, &g, tex, patterns); + let (angle, altitude) = if b.use_global_light { (light.angle, light.altitude) } else { (b.angle, b.altitude) }; + let (sa, ca) = angle.to_radians().sin_cos(); + let (se, ce) = altitude.to_radians().sin_cos(); + let light_v = [ca * ce, -sa * ce, se]; + // Region: 0 = inside (× the shape's alpha), 1 = under the layer's edge and outside. + // A pixel is on the bevel where its height is raised. Emboss styles also shade the last pixel + // past the blur's reach (a raised 4-neighbour: it still slopes; psd-tools layer_effects' + // emboss shadow runs one row past it), outer bevels don't (Photoshop oracle + // bevel-outer-smooth). + // Outer chisel bevels too: the pixel where their ramp reaches zero still slopes (Photoshop + // 27.11 shades it, half strength, at `size + 1½` px out). + let reach_past = g.paint == BevelPaint::Both || (g.paint == BevelPaint::Outer && b.technique != BevelTechnique::Smooth); + let on_bevel = |x: i64, y: i64| { + hmap.get(x, y) > BEVEL_H_EPS || (reach_past && [(1, 0), (-1, 0), (0, 1), (0, -1)].iter().any(|(dx, dy)| hmap.get(x + dx, y + dy) > BEVEL_H_EPS)) + }; + // The gloss contour remaps the shading `n · light` before it splits into highlight (above + // what it maps a flat face's `sin(altitude)` to) and shadow. Applied to the highlight and shadow amounts + // instead, a contour that starts high (Rolling Slope - Descending) lit every pixel the light + // missed, so a bevelled glyph's flat face took the full highlight (#7360) where Photoshop + // leaves it at the layer's colour. The Linear contour changes nothing either way. + let gloss = contour_lut(&b.gloss_contour); + let shade_into = |depth: f32, region_kind: u8| -> (Map, Map) { + let (mut hi, mut sh) = (Map::new(shape.w, shape.h, 0.0), Map::new(shape.w, shape.h, 0.0)); + // Rows on threads: every pixel reads only `hmap` and `shape`. + par_units( + hi.v.len(), + &mut hi.v, + shape.w, + &mut sh.v, + shape.w, + || (), + |_, y, hi_row, sh_row| { + let y = y as i64; + for x in 0..shape.w as i64 { + let i = y as usize * shape.w + x as usize; + let gx = (hmap.get(x + 1, y) - hmap.get(x - 1, y)) * 0.5 * depth; + let gy = (hmap.get(x, y + 1) - hmap.get(x, y - 1)) * 0.5 * depth; + let n = [-gx, -gy, 1.0]; + let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt(); + let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len; + let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) }; + let k = gloss.as_ref().map_or(shade - se, |l| lut_at(l, shade) - lut_at(l, se)); + if k > 0.0 { + hi_row[x as usize] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region; + } else { + sh_row[x as usize] = (-k / se.max(1e-3)).clamp(0.0, 1.0) * region; + } + } + }, + ); + (hi, sh) + }; + let maps = match g.paint { + BevelPaint::Inner | BevelPaint::Outer => { + let (hi, sh) = shade_into(g.depth, u8::from(g.paint == BevelPaint::Outer)); + vec![hi, sh] + } + BevelPaint::Both => { + // One map per colour over the whole bevel: the inside half where the shape is (× its + // alpha), the outside half (pillow: facing the other way) for the rest of each pixel. + // A 1 % edge pixel of a pillow emboss takes the outside shading (Photoshop oracle + // bevel-pillow-smooth), a 75 % one of an emboss mostly the inside (layer_effects). + let (hi, sh) = shade_into(g.depth, 0); + let (ho, so) = shade_into(if g.pillow { -g.depth } else { g.depth }, 1); + let mix = |a: Map, b: Map| -> Map { + let v = par_fill(a.w, a.h, 0.0, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + let i = y * a.w + x; + let (x, y, s) = (a.v[i], b.v[i], shape.v[i]); + *o = if s > INSIDE_EPS { x } else { 0.0 } + y * (1.0 - s.min(1.0)); + } + }); + Map { w: a.w, h: a.h, v } + }; + vec![mix(hi, ho), mix(sh, so)] + } + }; + (maps, g.paint) +} + +/// The distance the two satin copies are offset by. Photoshop draws Distance 0 as 1 px (an +/// edge band of 2/size, measured in Photoshop 27.11), not as two copies cancelling out. +pub fn satin_distance(s: &photocraft_doc::effects::Satin) -> f32 { + s.distance.max(1.0) +} + +pub(super) fn satin_map(shape: &Map, s: &photocraft_doc::effects::Satin) -> Map { + let (dx, dy) = offset(s.angle, satin_distance(s)); + let mut a = shape.shifted(dx, dy, 0.0); + let mut b = shape.shifted(-dx, -dy, 0.0); + // Two box passes of the satin size (fitted: 0.2 % mean error on psd-tools layer_effects). + tent(&mut a, s.size); + tent(&mut b, s.size); + let mut m = Map { w: shape.w, h: shape.h, v: a.v.iter().zip(&b.v).map(|(x, y)| (x - y).abs()).collect() }; + if s.invert { + m = m.map(|v| 1.0 - v); + } + let mut m = apply_lut(m, satin_lut(&s.contour)); + for (v, a) in m.v.iter_mut().zip(&shape.v) { + *v *= a; + } + m +} diff --git a/crates/compose/src/effects/blur.rs b/crates/compose/src/effects/blur.rs new file mode 100644 index 0000000000..686870523d --- /dev/null +++ b/crates/compose/src/effects/blur.rs @@ -0,0 +1,212 @@ +use super::distance::{Metric, dist_outside_by}; +use super::*; + +/// The soft falloff of an effect of `size` pixels: two box passes of width `size` (a tent), +/// as Photoshop does. Fitted on psd-tools layer_effects.psd against the earlier Gaussian +/// (sigma = 0.4 × size): drop shadow coverage error 0.0064 → 0.0038, satin 0.014 → 0.002. +pub(super) fn blur(m: &mut Map, size: f32) { + if size.is_finite() { + tent(m, size); + } +} + +/// Grows the shape by `r` pixels (anti-aliased), keeping the original soft edge. Distances use +/// the 5 × 5 chamfer metric, as for strokes: Photoshop's spread of a group drop shadow around an +/// ellipse (ag-psd group-drop-shadows) is round at 0° and 45° and falls short in between, peaking +/// near 15° where the chamfer metric overestimates most (5/255 lighter with an exact Euclidean +/// dilation, within 2/255 with the chamfer). +pub(super) fn dilate(s: &Map, r: f32) -> Map { + if r <= 0.0 { + return s.clone(); + } + let d = dist_outside_by(s, Metric::Chamfer); + let mut out = s.clone(); + for (o, d) in out.v.iter_mut().zip(d) { + // Partly covered pixels (distance sentinel < 0) grow by `r` from their own coverage, so a + // 2 % spread doesn't make every anti-aliased edge pixel opaque (ag-psd drop shadow). + *o = if d < 0.0 { (*o + r).min(1.0) } else { o.max((r + 0.5 - d).clamp(0.0, 1.0)) }; + } + out +} + +/// A box width as the blurs use it: at least 1, at most [`MAX_REACH`] (an effect never reaches +/// further, see [`margin`]), and 1 for NaN. A size or softness from a command or a file can be +/// anything, and an unbounded width sizes the kernel and its buffers (#1543). +fn box_width(w: f32) -> f32 { + if w.is_nan() { 1.0 } else { w.clamp(1.0, MAX_REACH) } +} + +/// Normalised weights of a centred box of (fractional) width `w`: tap `i` gets the overlap of +/// `[i - 0.5, i + 0.5]` with `[-w/2, w/2]`. +fn box_weights(w: f32) -> Vec { + let w = box_width(w); + let half = w / 2.0; + let r = (half - 0.5).ceil().max(0.0) as i64; + let v: Vec = (-r..=r).map(|i| ((i as f32 + 0.5).min(half) - (i as f32 - 0.5).max(-half)).max(0.0)).collect(); + let sum: f32 = v.iter().sum(); + v.iter().map(|x| x / sum).collect() +} + +/// The 1D kernel of two box passes of width `w` (a tent of half-width ≈ `w`): `(radius, weights)`. +/// Photoshop's bevel height maps are this blur of the shape (fitted on the corpus: a smooth +/// inner bevel of size 5 matches within 0.7 % mean, size 41 within 2.6 %). +pub fn tent_kernel(w: f32) -> (i32, Vec) { + let b = box_weights(w); + let n = b.len() * 2 - 1; + let mut t = vec![0.0f32; n]; + for (i, x) in b.iter().enumerate() { + for (j, y) in b.iter().enumerate() { + t[i + j] += x * y; + } + } + ((n as i32 - 1) / 2, t) +} + +/// Box geometry for a (fractional) width: (`r`, end-tap weight `f`, 1 / width) — the +/// [`box_weights`] taps are `r - 1` full ones each side of the centre plus the two end taps at `f`. +fn box_geom(bw: f32) -> (i64, f64, f64) { + let bw = box_width(bw); + let half = bw / 2.0; + let r = (half - 0.5).ceil().max(0.0) as i64; + let f = f64::from((half - (r as f32 - 0.5)).clamp(0.0, 1.0)); + (r, f, 1.0 / f64::from(bw)) +} + +/// One box pass over `src` (zero outside it) evaluated at `x0 .. x0 + dst.len()`, as a running +/// sum (O(1) per sample whatever the width). +pub(super) fn box_line(src: &[f64], x0: i64, dst: &mut [f64], bw: f32) { + let n = src.len() as i64; + let (r, f, norm) = box_geom(bw); + let at = |i: i64| if i >= 0 && i < n { src[i as usize] } else { 0.0 }; + if r == 0 { + for (k, d) in dst.iter_mut().enumerate() { + *d = at(x0 + k as i64); + } + return; + } + let window = x0 - (r - 1)..=x0 + (r - 1); + let mut inner: f64 = window.clone().map(at).sum(); + let mut last_covered = window.rev().find(|&x| at(x) != 0.0).unwrap_or(i64::MIN); + for (k, d) in dst.iter_mut().enumerate() { + let x = x0 + k as i64; + *d = (inner + f * (at(x - r) + at(x + r))) * norm; + let entering = at(x + r); + inner += entering - at(x - r + 1); + if entering != 0.0 { + last_covered = x + r; + } + // Cancellation can leave positive residue after the last covered pixel leaves. + // Noise amplifies even that residue into visible speckles (#5638). Reset only + // truly empty windows, preserving arbitrarily faint real coverage. + if last_covered < x - r + 2 { + inner = 0.0; + } + } +} + +/// Two box passes along a line, exactly the convolution with [`tent_kernel`] (zero outside): the +/// first pass is evaluated `r` samples beyond each end so the second sees what lies there. +fn tent_line(src: &[f32], dst: &mut [f32], bw: f32) { + let (r, _, _) = box_geom(bw); + let s: Vec = src.iter().map(|v| f64::from(*v)).collect(); + let mut mid = vec![0.0f64; src.len() + 2 * r as usize]; + box_line(&s, -r, &mut mid, bw); + let mut out = vec![0.0f64; src.len()]; + // `mid[k]` holds position k - r: output position p reads index p + r. + box_line(&mid, r, &mut out, bw); + for (d, v) in dst.iter_mut().zip(out) { + *d = v as f32; + } +} + +/// Rows of a `w`-wide row-major buffer, each through `f(src_row, dst_row)`, in parallel on +/// scoped OS threads. Not rayon: maps can be built from inside a rayon tile, where a waiting +/// worker steals other tiles. Map builds no longer block on each other (#276), but the blur +/// keeps out of the tile pool. +fn rows_par(src: &[f32], dst: &mut [f32], w: usize, f: impl Fn(&[f32], &mut [f32]) + Sync) { + if w == 0 { + return; + } + let threads = + if cfg!(target_arch = "wasm32") || src.len() < 1 << 16 { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 16) }; + if threads == 1 { + dst.chunks_mut(w).zip(src.chunks(w)).for_each(|(d, s)| f(s, d)); + return; + } + let rows = (src.len() / w).div_ceil(threads); + std::thread::scope(|sc| { + for (d, s) in dst.chunks_mut(rows * w).zip(src.chunks(rows * w)) { + let f = &f; + sc.spawn(move || d.chunks_mut(w).zip(s.chunks(w)).for_each(|(d, s)| f(s, d))); + } + }); +} + +fn transpose_map(v: &[f32], w: usize, h: usize) -> Vec { + let mut out = vec![0.0f32; v.len()]; + const B: usize = 32; + for by in (0..h).step_by(B) { + for bx in (0..w).step_by(B) { + for y in by..(by + B).min(h) { + for x in bx..(bx + B).min(w) { + out[x * h + y] = v[y * w + x]; + } + } + } + } + out +} + +/// Two box passes of width `w` along each axis (the tent [`tent_kernel`] describes, which the GPU +/// convolves directly). +pub(super) fn tent(m: &mut Map, w: f32) { + if tent_kernel(w).0 == 0 || m.v.is_empty() { + return; + } + tent_fast(m, w); +} + +/// [`tent`] as a direct convolution with [`tent_kernel`] (the GPU's way; tests compare). +#[cfg(test)] +pub(super) fn tent_direct(m: &mut Map, w: f32) { + { + let (r, k) = tent_kernel(w); + let (mw, mh) = (m.w as i64, m.h as i64); + let mut tmp = vec![0.0f32; m.v.len()]; + for y in 0..mh { + for x in 0..mw { + let mut acc = 0.0; + for (i, kv) in k.iter().enumerate() { + let xx = x + i as i64 - r as i64; + if xx >= 0 && xx < mw { + acc += m.v[(y * mw + xx) as usize] * kv; + } + } + tmp[(y * mw + x) as usize] = acc; + } + } + for y in 0..mh { + for x in 0..mw { + let mut acc = 0.0; + for (i, kv) in k.iter().enumerate() { + let yy = y + i as i64 - r as i64; + if yy >= 0 && yy < mh { + acc += tmp[(yy * mw + x) as usize] * kv; + } + } + m.v[(y * mw + x) as usize] = acc; + } + } + } +} + +fn tent_fast(m: &mut Map, w: f32) { + let (mw, mh) = (m.w, m.h); + let twice = |s: &[f32], d: &mut [f32]| tent_line(s, d, w); + let mut a = vec![0.0f32; m.v.len()]; + rows_par(&m.v, &mut a, mw, twice); + let t = transpose_map(&a, mw, mh); + let mut b = vec![0.0f32; t.len()]; + rows_par(&t, &mut b, mh, twice); + m.v = transpose_map(&b, mh, mw); +} diff --git a/crates/compose/src/effects/composite.rs b/crates/compose/src/effects/composite.rs new file mode 100644 index 0000000000..cf6402f1ca --- /dev/null +++ b/crates/compose/src/effects/composite.rs @@ -0,0 +1,533 @@ +use super::bevel::{BevelPaint, TextureCtx, bevel_geom, bevel_maps, satin_map}; +use super::distance::{INSIDE_EPS, Metric, dist_inside_by, dist_outside_by, local_coverage, stroke_outside_exact}; +use super::paint::{dissolves_in, glow_map, paint_color, paint_fx, paint_glow, paint_pattern, rgb, shadow_map}; +use super::*; + +/// Build every effect map for `layer` from its alpha `shape` over `rect`. +pub fn build_maps(layer: &Layer, shape: Vec, rect: Rect, light: &GlobalLight, tex: &TextureCtx) -> FxMaps { + let prepared = PreparedPatterns::new(tex.patterns, PREPARED_PATTERN_BYTES); + build_maps_prepared(layer, shape, rect, light, tex, &prepared) +} + +/// How many region-sized arrays [`build_maps_prepared`] builds for `layer` (what +/// [`FxMaps::bytes`] counts): the shape, each effect's maps, and a stroke's distance fields. Kept +/// next to the builder so the effect cache's estimate (#8330) follows it. +pub(crate) fn map_count(layer: &Layer) -> usize { + let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); + let per: usize = items + .iter() + .map(|e| match e { + Effect::DropShadow(_) | Effect::InnerShadow(_) | Effect::OuterGlow(_) | Effect::InnerGlow(_) | Effect::Satin(_) => 1, + Effect::BevelEmboss(_) => 2, + _ => 0, + }) + .sum(); + let out_widths: Vec = + items.iter().filter_map(|e| if let Effect::Stroke(st) = e { Some(stroke_widths(st).1) } else { None }).filter(|w| *w > 0.0).collect(); + let has_stroke = items.iter().any(|e| matches!(e, Effect::Stroke(_))); + let outside = usize::from(out_widths.iter().any(|&w| !stroke_outside_exact(w))) + usize::from(out_widths.iter().any(|&w| stroke_outside_exact(w))); + let stroke = if has_stroke { 1 + outside } else { 0 }; + let vector_outline = + if has_stroke && matches!(layer.content, photocraft_doc::LayerContent::Shape(_)) && crate::effect_outline(layer).is_none() { outside } else { 0 }; + 1 + per + stroke + vector_outline +} + +pub(crate) fn build_maps_prepared( + layer: &Layer, + shape: Vec, + rect: Rect, + light: &GlobalLight, + tex: &TextureCtx, + patterns: &PreparedPatterns<'_>, +) -> FxMaps { + let (w, h) = (rect.width() as usize, rect.height() as usize); + let shape = Map { w, h, v: shape }; + let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); + let mut bevel_paint = vec![BevelPaint::Inner; items.len()]; + let per: Vec> = items + .iter() + .enumerate() + .map(|(i, e)| match e { + Effect::DropShadow(s) => vec![shadow_map(&shape, s, light, false, (rect.x0, rect.y0))], + Effect::InnerShadow(s) => vec![shadow_map(&shape, s, light, true, (rect.x0, rect.y0))], + Effect::OuterGlow(g) => vec![glow_map(&shape, g, false, (rect.x0, rect.y0))], + Effect::InnerGlow(g) => vec![glow_map(&shape, g, true, (rect.x0, rect.y0))], + Effect::Satin(s) => vec![satin_map(&shape, s)], + Effect::BevelEmboss(b) => { + let (maps, paint) = bevel_maps(&shape, b, light, tex, patterns); + bevel_paint[i] = paint; + maps + } + _ => Vec::new(), + }) + .collect(); + let has_stroke = items.iter().any(|e| matches!(e, Effect::Stroke(_))); + let vector_shape = matches!(layer.content, photocraft_doc::LayerContent::Shape(_)); + // A stroke's outer edge keeps the 5 × 5 chamfer while its outside width is under + // `STROKE_CHAMFER_MAX` — Photoshop matches the chamfer's sub-pixel edge seeding at small + // offsets — and uses the exact Euclidean transform at or above it, where the chamfer's octagon + // facets a wide stroke (#3646). Inside stroke distances always keep the chamfer. Each outer + // field is built only when a stroke of that width is present; the compositor picks per stroke, + // so one layer may hold both a narrow and a wide stroke. + let out_widths: Vec = + items.iter().filter_map(|e| if let Effect::Stroke(st) = e { Some(stroke_widths(st).1) } else { None }).filter(|w| *w > 0.0).collect(); + let chamfer_out = out_widths.iter().any(|&w| !stroke_outside_exact(w)); + let exact_out = out_widths.iter().any(|&w| stroke_outside_exact(w)); + let (din, dout, dout_exact) = if has_stroke { + ( + Some(dist_inside_by(&shape, Metric::Chamfer)), + chamfer_out.then(|| dist_outside_by(&shape, Metric::Chamfer)), + exact_out.then(|| dist_outside_by(&shape, Metric::Euclidean)), + ) + } else { + (None, None, None) + }; + // Without an outline (unfilled shapes), estimate the vector outline from local coverage; it + // picks the chamfer or the exact transform the same way. + let outline = crate::effect_outline(layer).is_some(); + let (vdout, vdout_exact) = if has_stroke && vector_shape && !outline { + let lc = local_coverage(&shape); + (chamfer_out.then(|| dist_outside_by(&lc, Metric::Chamfer)), exact_out.then(|| dist_outside_by(&lc, Metric::Euclidean))) + } else { + (None, None) + }; + let mut frames: Vec<(u32, Rect)> = Vec::new(); + for e in &items { + if let Effect::Stroke(st) = e + && matches!(st.paint, FxPaint::Gradient(_)) + { + let out_w = stroke_widths(st).1; + if !frames.iter().any(|f| f.0 == out_w.to_bits()) { + frames.push((out_w.to_bits(), stroke_frame(&shape, out_w, rect))); + } + } + } + FxMaps { rect, shape, per, bevel_paint, din, dout, dout_exact, vdout, vdout_exact, outline, frames } +} + +/// Far outside any shape (distance fill for cropped distance fields). +const FAR: f32 = 1.0e9; + +/// Keep an exterior effect behind the layer's shape when Fill is partly or wholly +/// transparent. The visible part beneath a fully opaque fill is already covered by the +/// layer, so avoid attenuating anti-aliased edges twice in that case. +fn knock_out_exterior(map: &mut Map, shape: &Map, fill_opacity: f32) { + let see_through = 1.0 - fill_opacity.clamp(0.0, 1.0); + for (coverage, alpha) in map.v.iter_mut().zip(&shape.v) { + *coverage *= 1.0 - alpha * see_through; + } +} + +/// How far the layer lets a knocked-out drop shadow show beneath its own shape (Layer Knocks Out +/// Drop Shadow), 0 = covered, 1 = knocked out wholly. In a normal mode an opaque layer covers the +/// shadow anyway, so only see-through fill knocks it out (and anti-aliased edges are not +/// attenuated twice). In any other mode the layer blends with what's beneath it, shadow and all: +/// an Exclusion or Difference layer would invert it, Multiply darken by it, Screen show it as +/// grey. Photoshop keeps it out from under the shape, so here it's knocked out wholly. +pub fn shadow_see_through(layer: &Layer) -> f32 { + if matches!(layer.blend, BlendMode::Normal | BlendMode::Dissolve | BlendMode::PassThrough) { 1.0 - layer.fill_opacity.clamp(0.0, 1.0) } else { 1.0 } +} + +/// Blend Interior Effects as Group off (Photoshop's default): the layer's mode applies to its +/// own pixels only, and the interior effects paint over the blended result. The layer is merged +/// into the backdrop before they paint, so an Overlay colour overlay on a black Color-mode layer +/// tints the grey beneath it (#3996). A Normal layer merges only when an interior effect blends +/// in another mode: below 100 % fill that effect sees the backdrop through the layer, so a Soft +/// Light overlay on a Fill 0 % layer soft-lights the backdrop instead of showing its own colour +/// (#6232). Normal effects give the same result either way, and the merge would count a +/// half-transparent backdrop twice, so those layers keep the plain composite. +pub fn premerges_layer(layer: &Layer) -> bool { + !layer.advanced.blend_interior + && match layer.blend { + BlendMode::PassThrough | BlendMode::Dissolve => false, + BlendMode::Normal => blends_inside(layer), + _ => true, + } +} + +/// `true` if an enabled effect painted inside the layer (with its content) blends in a mode +/// other than Normal. +fn blends_inside(layer: &Layer) -> bool { + let blends = |m: BlendMode| m != BlendMode::Normal; + layer.effects.items.iter().filter(|e| e.enabled()).any(|e| match e { + Effect::ColorOverlay { common, .. } | Effect::GradientOverlay { common, .. } | Effect::PatternOverlay { common, .. } => blends(common.blend), + Effect::Satin(s) => blends(s.common.blend), + Effect::InnerGlow(g) => blends(g.common.blend), + Effect::InnerShadow(s) => blends(s.common.blend), + Effect::Stroke(s) => stroke_widths(s).0 > 0.0 && blends(s.common.blend), + Effect::BevelEmboss(b) => bevel_geom(b).paint == BevelPaint::Inner && (blends(b.highlight.blend) || blends(b.shadow.blend)), + Effect::DropShadow(_) | Effect::OuterGlow(_) => false, + }) +} + +/// Composites `content` (the layer's own pixels over `big`, alpha already +/// masked, clipped layers applied) plus its effects into `backdrop`. +pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Buffer, maps: &FxMaps, layer_bounds: Rect, patterns: &[Pattern]) { + let prepared = PreparedPatterns::new(patterns, PREPARED_PATTERN_BYTES); + composite_with_effects_prepared(layer, content, backdrop, maps, layer_bounds, &prepared, None); +} + +pub(crate) fn composite_with_effects_prepared( + layer: &Layer, + content: &Buffer, + backdrop: &mut Buffer, + maps: &FxMaps, + layer_bounds: Rect, + patterns: &PreparedPatterns<'_>, + vstroke: Option>, +) { + let big = content.rect; + let (w, h) = (big.width() as usize, big.height() as usize); + // The effect shape: the content's alpha (with a split-off vector stroke, `content` is the + // unmasked fill and the mask applies to fill ∪ stroke), joined with a filled shape's outline. + let kmask = |i: usize| vstroke.as_ref().and_then(|v| v.mask).and_then(|m| m.get(i)).copied().unwrap_or(1.0); + let union = |i: usize, a: f32| vstroke.as_ref().and_then(|v| v.stroke.px.get(i)).map_or(a, |s| kmask(i) * (a + s[3] * (1.0 - a))); + // Transparency Shapes Layer off: the shape is the whole layer (its masks, as the maps were + // built), and the content's own transparency acts like fill opacity within it. + let shapeless = !layer.advanced.transparency_shapes; + let shape = if shapeless { + maps.crop(&maps.shape, big, 0.0) + } else if maps.outline { + let o = maps.crop(&maps.shape, big, 0.0); + Map { w, h, v: o.v.iter().zip(&content.px).enumerate().map(|(i, (o, p))| o.max(union(i, p[3]))).collect() } + } else { + Map { w, h, v: content.px.iter().enumerate().map(|(i, p)| union(i, p[3])).collect() } + }; + let relative = shapeless || maps.outline || vstroke.is_some(); + let fx = |i: usize, k: usize| maps.crop(&maps.per[i][k], big, 0.0); + // Layer bounds (gradients aligned with the layer use the whole layer, + // independent of the render rect). + let sb = layer_bounds; + // Linked patterns tile from the effects reference point (else the layer's top-left). + let anchor = layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))); + let rect = backdrop.rect; + let before = backdrop.clone(); + // Exterior effects are painted on a backdrop copy extended to `big`. + let mut work = Buffer::transparent(big); + for y in rect.y0.max(big.y0)..rect.y1.min(big.y1) { + for x in rect.x0.max(big.x0)..rect.x1.min(big.x1) { + work.px[((y - big.y0) as usize) * w + (x - big.x0) as usize] = before.get(x, y); + } + } + let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); + let vector_shape = matches!(layer.content, photocraft_doc::LayerContent::Shape(_)); + // Multiple instances: the first listed is on top, so paint in reverse. + let rev = || items.iter().copied().enumerate().rev(); + + for (i, e) in rev() { + if let Effect::DropShadow(s) = e { + let mut m = fx(i, 0); + if s.knocks_out { + // The layer hides the shadow beneath it where its fill is see-through (at 100 % + // fill in a normal mode it covers it anyway; at 0 % the shape shows the bare + // backdrop), and wholly in a mode that blends with it ([`shadow_see_through`]). + knock_out_exterior(&mut m, &shape, 1.0 - shadow_see_through(layer)); + } + paint_color(&mut work, &m, rgb(&s.color), s.common.blend, s.common.opacity); + } + } + for (i, e) in rev() { + if let Effect::OuterGlow(g) = e { + let mut m = fx(i, 0); + // The glow is behind the shape, not painted across its interior when Fill is 0 %. + // Preserve the existing anti-aliased edge when the fill is fully opaque. + knock_out_exterior(&mut m, &shape, layer.fill_opacity); + paint_glow(&mut work, &m, g, sb, anchor, big, patterns); + } + } + + // The layer: content at fill opacity, then interior effects. Interior effects are painted + // relative to the layer's shape (alpha = coverage within the shape), then the shape's alpha + // applies: a colour overlay at 100 % replaces the colour of a half-transparent edge pixel and + // keeps its alpha, as in Photoshop. + let fill = layer.fill_opacity; + // Blend Interior Effects as Group: the interior effects (overlays, satin, inner glow) are + // combined with the content first, and fill opacity applies to the combination. + let interior_group = layer.advanced.blend_interior && fill < 1.0; + let content_fill = if interior_group { 1.0 } else { fill }; + let inside = |a: f32| a > INSIDE_EPS; + // Within an outline (or a split-off vector stroke) the content's own transparency (a fading + // gradient fill) acts like fill opacity: the effects still cover the whole shape. + let lay_alpha = |i: usize, p: &[f32; 4], a: f32| { + if !inside(a) { + 0.0 + } else if relative { + content_fill * (kmask(i) * p[3] / a).min(1.0) + } else { + content_fill + } + }; + let mut lay = Buffer { rect: big, px: content.px.iter().zip(&shape.v).enumerate().map(|(i, (p, a))| [p[0], p[1], p[2], lay_alpha(i, p, *a)]).collect() }; + let gamma = crate::text_gamma(layer); + let premerge = premerges_layer(layer); + if premerge { + for (lp, wp) in lay.px.iter_mut().zip(&work.px) { + *lp = psblend::composite_gamma(layer.blend, *wp, *lp, 1.0, gamma); + } + } + let rel = |m: Map| -> Map { + let v = m.v.iter().zip(&shape.v).map(|(m, a)| if inside(*a) { (m / a).min(1.0) } else { 0.0 }).collect(); + Map { w: m.w, h: m.h, v } + }; + let full = Map { w, h, v: shape.v.iter().map(|a| if inside(*a) { 1.0 } else { 0.0 }).collect() }; + for (_, e) in rev() { + if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e { + paint_pattern(&mut lay, &full, patterns, name, id, Placement::anchored(anchor, *link, *phase, *scale, *angle), big, common.blend, common.opacity); + } + } + for (_, e) in rev() { + if let Effect::GradientOverlay { common, gradient, .. } = e { + paint_fx(&mut lay, &full, &FxPaint::Gradient(gradient.clone()), sb, anchor, big, common.blend, common.opacity, patterns) + } + } + for (_, e) in rev() { + if let Effect::ColorOverlay { common, color } = e { + paint_color(&mut lay, &full, rgb(color), common.blend, common.opacity); + } + } + for (i, e) in rev() { + if let Effect::Satin(s) = e { + let m = rel(fx(i, 0)); + paint_color(&mut lay, &m, rgb(&s.color), s.common.blend, s.common.opacity); + } + } + for (i, e) in rev() { + if let Effect::InnerGlow(g) = e { + paint_glow(&mut lay, &rel(fx(i, 0)), g, sb, anchor, big, patterns); + } + } + if interior_group { + for p in &mut lay.px { + p[3] *= fill.max(0.0); + } + } + for (i, e) in rev() { + if let Effect::InnerShadow(s) = e { + let m = rel(fx(i, 0)); + paint_color(&mut lay, &m, rgb(&s.color), s.common.blend, s.common.opacity); + } + } + // A stroked shape's vector stroke: Photoshop draws it above the fill's clipped layers and + // interior effects, below the stroke effect (psd-tools stroke-composite). + if let Some(vs) = &vstroke { + for (i, ((p, s), a)) in lay.px.iter_mut().zip(&vs.stroke.px).zip(&shape.v).enumerate() { + if s[3] > 0.0 && inside(*a) { + *p = psblend::composite(BlendMode::Normal, *p, [s[0], s[1], s[2], fill * (kmask(i) * s[3] / a).min(1.0)], 1.0); + } + } + } + // Strokes. Inside parts are painted over the layer (bottom instance first); outside parts + // are slid beneath it, so the first listed (top) instance is processed first. + let strokes: Vec<&photocraft_doc::StrokeFx> = items.iter().filter_map(|e| if let Effect::Stroke(s) = e { Some(s) } else { None }).collect(); + let ready = !strokes.is_empty(); + let din = if ready { maps.din.as_ref().map(|a| maps.crop_vec(a, big, 0.0)).unwrap_or_default() } else { Vec::new() }; + // A stroke's outer edge picks the chamfer or the exact field by its width + // ([`stroke_outside_exact`]); both are cropped here, and only the ones a stroke needs exist. + let crop_out = |v: &Option>| v.as_ref().map(|b| maps.crop_vec(b, big, FAR)); + let (dout, dout_exact, vdout, vdout_exact) = + if ready { (crop_out(&maps.dout), crop_out(&maps.dout_exact), crop_out(&maps.vdout), crop_out(&maps.vdout_exact)) } else { (None, None, None, None) }; + let widths = stroke_widths; + // A gradient stroke aligned with the layer spans the stroke's own extent. + let frame = |st: &photocraft_doc::StrokeFx| maps.stroke_frame(st).unwrap_or(sb); + for st in strokes.iter().rev().copied() { + let (in_w, _) = widths(st); + if in_w <= 0.0 { + continue; + } + let mut m = Map::new(w, h, 0.0); + for ((mv, a), dv) in m.v.iter_mut().zip(&shape.v).zip(&din) { + *mv = if inside(*a) { (in_w + 0.5 - dv).clamp(0.0, 1.0) } else { 0.0 }; + } + paint_fx(&mut lay, &m, &st.paint, frame(st), anchor, big, st.common.blend, st.common.opacity, patterns); + } + for (i, e) in rev() { + if let Effect::BevelEmboss(b) = e + && maps.bevel_paint[i] == BevelPaint::Inner + { + let (hi, sh) = (rel(fx(i, 0)), rel(fx(i, 1))); + paint_color(&mut lay, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); + paint_color(&mut lay, &sh, rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); + } + } + // The shape's own alpha. + for (p, a) in lay.px.iter_mut().zip(&shape.v) { + p[3] *= a.min(1.0); + } + // Shape layers without a filled outline stroke their vector outline, estimated from local + // coverage; every other layer strokes its shape. The width then picks the field. + let vector_outline = vector_shape && !maps.outline; + // Outside parts lie beneath the layer and blend onto the backdrop with their own mode. A + // higher stroke covers the ones below it (Photoshop: a Multiply stroke listed above a wider + // Normal stroke multiplies the backdrop, not the lower stroke). Each stroke's share is its + // coverage × opacity not yet taken by strokes above; for Normal strokes this equals stacking + // them top over bottom. + if strokes.iter().any(|st| widths(st).1 > 0.0) { + let base = work.clone(); + let mut acc = vec![[0.0f32; 4]; w * h]; // premultiplied Σ share·blended + let mut cover = vec![0.0f32; w * h]; + for st in strokes.iter().copied() { + let (_, out_w) = widths(st); + if out_w <= 0.0 { + continue; + } + // Shape layers: Photoshop strokes the vector outline (estimated from local coverage + // for unfilled shapes); the stroke never shows through the shape's pixels. Along a + // filled shape's outline it covers the part of each edge pixel outside the path. + let exact = stroke_outside_exact(out_w); + let d: &[f32] = if vector_outline { + (if exact { vdout_exact.as_deref() } else { vdout.as_deref() }).unwrap_or_default() + } else if exact { + dout_exact.as_deref().unwrap_or_default() + } else { + dout.as_deref().unwrap_or_default() + }; + let mut share = vec![0.0f32; w * h]; + for (i, sh) in share.iter_mut().enumerate() { + let band = (out_w + 0.5 - d[i]).clamp(0.0, 1.0); + let k = + if inside(shape.v[i]) { if vector_shape && !maps.outline { 0.0 } else { band * outline_share(shape.v[i], lay.px[i][3]) } } else { band }; + let mut k = k * st.common.opacity; + if st.common.blend == BlendMode::Dissolve { + let (x, y) = (i64::from(big.x0) + (i % w) as i64, i64::from(big.y0) + (i / w) as i64); + k = if k > 0.0 && dissolves_in(x, y, k) { 1.0 } else { 0.0 }; + } + *sh = k * (1.0 - cover[i]); + cover[i] += *sh; + } + // The stroke blended over the backdrop at full coverage. + let mut blended = base.clone(); + let ones = Map { w, h, v: share.iter().map(|&s| if s > 0.0 { 1.0 } else { 0.0 }).collect() }; + // The share already carries the Dissolve choice, so the paint itself composites as Normal. + let paint_blend = if st.common.blend == BlendMode::Dissolve { BlendMode::Normal } else { st.common.blend }; + paint_fx(&mut blended, &ones, &st.paint, frame(st), anchor, big, paint_blend, 1.0, patterns); + for ((a, b), s) in acc.iter_mut().zip(&blended.px).zip(&share) { + if *s > 0.0 { + for c in 0..3 { + a[c] += s * b[c] * b[3]; + } + a[3] += s * b[3]; + } + } + } + for ((p, a), c) in work.px.iter_mut().zip(&acc).zip(&cover) { + if *c <= 0.0 { + continue; + } + let k = 1.0 - c.min(1.0); + let alpha = p[3] * k + a[3]; + if alpha > 0.0 { + *p = [(p[0] * p[3] * k + a[0]) / alpha, (p[1] * p[3] * k + a[1]) / alpha, (p[2] * p[3] * k + a[2]) / alpha, alpha.min(1.0)]; + } + } + } + for (i, e) in rev() { + if let Effect::BevelEmboss(b) = e + && maps.bevel_paint[i] == BevelPaint::Outer + { + let (hi, sh) = (fx(i, 0), fx(i, 1)); + paint_color(&mut work, &hi, rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); + paint_color(&mut work, &sh, rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); + } + } + + // Layer (with interior effects) onto the exterior result, in the layer's mode. + let mode = if premerge || layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; + for (wp, lp) in work.px.iter_mut().zip(&lay.px) { + if lp[3] > 0.0 { + *wp = psblend::composite_gamma(mode, *wp, *lp, 1.0, gamma); + } + } + // Emboss styles shade the composited layer (their maps cover inside and outside). Painting + // them into the layer before its (text-gamma) composite left a type layer's lit top edges up + // to 6/255 dark (psd-tools layer_effects Emboss: 7.8 → 5.7/255). + for (i, e) in rev() { + if let Effect::BevelEmboss(b) = e + && maps.bevel_paint[i] == BevelPaint::Both + { + paint_color(&mut work, &fx(i, 0), rgb(&b.highlight_color), b.highlight.blend, b.highlight.opacity); + paint_color(&mut work, &fx(i, 1), rgb(&b.shadow_color), b.shadow.blend, b.shadow.opacity); + } + } + // Layer opacity applies to the whole stack. + let op = layer.opacity; + for y in rect.y0..rect.y1 { + for x in rect.x0..rect.x1 { + let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize; + let a = before.px[i]; + let b = if x >= big.x0 && x < big.x1 && y >= big.y0 && y < big.y1 { work.px[((y - big.y0) as usize) * w + (x - big.x0) as usize] } else { a }; + backdrop.px[i] = if layer.blend == BlendMode::Dissolve { + // Dissolve applies layer opacity to the completed interior/exterior effect + // stack as pixel coverage, not continuous gray interpolation (#3051). + if crate::dissolve_noise(x, y) < op { b } else { a } + } else { + mix_premul(a, b, op) + }; + } + } +} + +/// Coverage of an outside stroke beneath a filled shape's edge pixel, for a pixel the outline +/// covers `cov` of and the layer (with its interior effects) ends at alpha `l`. Photoshop treats +/// the stroke and the shape as disjoint areas: the stroke fills the part outside the path and +/// the layer adds its own alpha (psd-tools stroke-effects: a 58 % covered edge pixel of an +/// opaque fill ends opaque, one of a faded fill at 42 % + its alpha). Composited beneath the +/// layer, `share + l (1 - share) = (1 - cov) + l`. +pub fn outline_share(cov: f32, l: f32) -> f32 { + let outside = (1.0 - cov.clamp(0.0, 1.0)).max(0.0); + if outside <= 1e-6 { + return 0.0; + } + let rest = 1.0 - l.clamp(0.0, 1.0); + if rest <= 1e-6 { 1.0 } else { (outside / rest).min(1.0) } +} + +/// (inside width, outside width) of a stroke. +pub fn stroke_widths(st: &photocraft_doc::StrokeFx) -> (f32, f32) { + match st.position { + StrokePosition::Outside => (0.0, st.size), + StrokePosition::Inside => (st.size, 0.0), + StrokePosition::Center => (st.size / 2.0, st.size / 2.0), + } +} + +/// The frame a gradient stroke aligned with the layer is laid out in: the pixel bounds of the +/// effect shape (over `rect`) grown by the stroke's outside width less one pixel. Photoshop +/// spans the gradient over the stroke's extent, not the layer's: a 4 px outside stroke around a +/// 22 px square runs its 90° gradient over 28 px (psd-tools stroke-effects), a 3 px one around +/// 36 px of type over 40 px (psd-tools effect-stroke-gradient). +fn stroke_frame(shape: &Map, out_w: f32, rect: Rect) -> Rect { + let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize); + for y in 0..shape.h { + for x in 0..shape.w { + if shape.v[y * shape.w + x] > INSIDE_EPS { + (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)); + } + } + } + if x0 == usize::MAX { + return rect; + } + let grow = if out_w.is_finite() { (out_w.min(MAX_REACH).ceil() as i32 - 1).max(0) } else { 0 }; + Rect::new(rect.x0 + x0 as i32, rect.y0 + y0 as i32, rect.x0 + x1 as i32, rect.y0 + y1 as i32).inflate(grow) +} + +/// A stroked shape's vector stroke, composited apart from its fill (which the compositor then +/// passes unmasked): the stroke's pixels over the render rect and the layer's mask values. +pub(crate) struct VectorStroke<'a> { + pub stroke: &'a Buffer, + pub mask: Option<&'a [f32]>, +} + +/// Premultiplied linear interpolation between two straight-alpha pixels. +fn mix_premul(a: [f32; 4], b: [f32; 4], k: f32) -> [f32; 4] { + let alpha = a[3] + (b[3] - a[3]) * k; + if alpha <= 0.0 { + return [0.0; 4]; + } + let mut out = [0.0; 4]; + for c in 0..3 { + out[c] = (a[c] * a[3] + (b[c] * b[3] - a[c] * a[3]) * k) / alpha; + } + out[3] = alpha; + out +} diff --git a/crates/compose/src/effects/distance.rs b/crates/compose/src/effects/distance.rs new file mode 100644 index 0000000000..8581e1c821 --- /dev/null +++ b/crates/compose/src/effects/distance.rs @@ -0,0 +1,810 @@ +use super::*; + +/// 1D squared distance transform (Felzenszwalb & Huttenlocher). +fn dt1(f: &[f32], out: &mut [f32], v: &mut [usize], z: &mut [f32], near: &mut [usize]) { + let n = f.len(); + let mut k = 0usize; + v[0] = 0; + z[0] = f32::NEG_INFINITY; + z[1] = f32::INFINITY; + for q in 1..n { + loop { + let p = v[k]; + let s = ((f[q] + (q * q) as f32) - (f[p] + (p * p) as f32)) / (2.0 * q as f32 - 2.0 * p as f32); + if s <= z[k] && k > 0 { + k -= 1; + continue; + } + if s <= z[k] { + // k == 0 and parabola dominates: replace. + v[0] = q; + z[0] = f32::NEG_INFINITY; + z[1] = f32::INFINITY; + break; + } + k += 1; + v[k] = q; + z[k] = s; + z[k + 1] = f32::INFINITY; + break; + } + } + k = 0; + for (q, o) in out.iter_mut().enumerate() { + while z[k + 1] < q as f32 { + k += 1; + } + let p = v[k]; + let d = q as f32 - p as f32; + *o = d * d + f[p]; + near[q] = p; + } +} + +/// Exact Euclidean distance from every pixel to the nearest pixel where +/// `inside` is true (0 on those pixels). +#[cfg(test)] +pub(super) fn edt(inside: &[bool], w: usize, h: usize) -> Vec { + edt_nearest(inside, w, h).0 +} + +/// Maps with fewer pixels (or other units of work) than this are not worth spawning threads for. +const PAR_MIN: usize = 1 << 16; + +/// Most threads one pass uses (as for the blurs, [`rows_par`]). +const PAR_THREADS: usize = 16; + +#[cfg(test)] +thread_local! { + /// Test hook: the thread count [`par_threads`] gives on this thread, whatever the work. + pub(super) static THREADS: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// How many threads a pass over `work` pixels (or similar units) uses. +fn par_threads(work: usize) -> usize { + #[cfg(test)] + if let Some(n) = THREADS.with(std::cell::Cell::get) { + return n; + } + if cfg!(target_arch = "wasm32") || work < PAR_MIN { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, PAR_THREADS) } +} + +/// Runs `f(scratch, u, a_u, b_u)` for every unit `u` of two slices: unit `u` of `a` is +/// `a[u * unit_a..][..unit_a]` (the last may be shorter), the same of `b` with `unit_b`, which is 0 +/// when there is no second slice. `work` says how big the whole pass is ([`par_threads`]). Groups of +/// units go to scoped OS threads, each with a scratch value from `init`; not to rayon, as for +/// [`rows_par`]: maps are built from inside rayon tiles, where a waiting worker steals other tiles. +/// A unit is computed from its own arguments alone, so the result does not depend on the threads. +pub(super) fn par_units( + work: usize, + a: &mut [A], + unit_a: usize, + b: &mut [B], + unit_b: usize, + init: impl Fn() -> S + Sync, + f: impl Fn(&mut S, usize, &mut [A], &mut [B]) + Sync, +) { + if unit_a == 0 { + return; + } + let units = a.len().div_ceil(unit_a); + let threads = par_threads(work).min(units); + if threads <= 1 { + run_units(&mut init(), 0, a, unit_a, b, unit_b, &f); + return; + } + // Many more groups than threads, so that a heavy one (an edge-rich stretch) does not hold the rest up. + let group = units.div_ceil(threads * 8).max(1); + let mut groups = Vec::new(); + let (mut rest_a, mut rest_b, mut first) = (a, b, 0usize); + while !rest_a.is_empty() { + let (ga, na) = rest_a.split_at_mut((group * unit_a).min(rest_a.len())); + let (gb, nb) = rest_b.split_at_mut((group * unit_b).min(rest_b.len())); + groups.push((first, ga, gb)); + (rest_a, rest_b, first) = (na, nb, first + group); + } + let queue = std::sync::Mutex::new(groups.into_iter()); + let worker = || { + let mut scratch = init(); + loop { + let next = queue.lock().unwrap_or_else(std::sync::PoisonError::into_inner).next(); + let Some((first, ga, gb)) = next else { break }; + run_units(&mut scratch, first, ga, unit_a, gb, unit_b, &f); + } + }; + std::thread::scope(|sc| { + // A thread that cannot be spawned leaves its share to the others. + for _ in 1..threads { + let _ = std::thread::Builder::new().spawn_scoped(sc, worker); + } + worker(); + }); +} + +fn run_units(scratch: &mut S, first: usize, a: &mut [A], unit_a: usize, b: &mut [B], unit_b: usize, f: &impl Fn(&mut S, usize, &mut [A], &mut [B])) { + for (k, ua) in a.chunks_mut(unit_a).enumerate() { + let ub = b.get_mut(k * unit_b..((k + 1) * unit_b).min(b.len())).unwrap_or(&mut []); + f(scratch, first + k, ua, ub); + } +} + +/// A `w × h` buffer of `fill`, then filled row by row through `f(y, row)`. +pub(super) fn par_fill(w: usize, h: usize, fill: T, f: impl Fn(usize, &mut [T]) + Sync) -> Vec { + let mut out = vec![fill; w.saturating_mul(h)]; + par_units(out.len(), &mut out, w.max(1), &mut [] as &mut [()], 0, || (), |_, y, row, _| f(y, row)); + out +} + +/// Working buffers of the 1D distance transform, for lines of up to `n` pixels. +struct Dt1Scratch { + f: Vec, + o: Vec, + v: Vec, + z: Vec, + near: Vec, +} + +impl Dt1Scratch { + fn new(n: usize) -> Self { + Dt1Scratch { f: vec![0.0; n], o: vec![0.0; n], v: vec![0; n], z: vec![0.0; n + 1], near: vec![0; n] } + } +} + +/// [`edt`] plus the index of the nearest `inside` pixel (as `u32`: a map past 2³² pixels has no +/// nearest pixel to give, and every distance is then "far"). +/// +/// Both passes run line by line in parallel: the columns, then the rows. The columns' results are +/// kept column by column (`gc[x * h + y]`) so that each thread writes its own stretch of them. +pub(super) fn edt_nearest(inside: &[bool], w: usize, h: usize) -> (Vec, Vec) { + const INF: f32 = 1e20; + let total = w.saturating_mul(h); + if total != inside.len() || total > u32::MAX as usize { + return (vec![INF; inside.len()], vec![0; inside.len()]); + } + let n = w.max(h); + let mut gc = vec![0.0f32; total]; + let mut nc = vec![0u32; total]; + par_units( + total, + &mut gc, + h.max(1), + &mut nc, + h.max(1), + || Dt1Scratch::new(n), + |t, x, g, near| { + for (y, f) in t.f[..h].iter_mut().enumerate() { + *f = if inside[y * w + x] { 0.0 } else { INF }; + } + dt1(&t.f[..h], &mut t.o[..h], &mut t.v, &mut t.z, &mut t.near[..h]); + g.copy_from_slice(&t.o[..h]); + for (d, &p) in near.iter_mut().zip(&t.near[..h]) { + *d = p as u32; + } + }, + ); + let mut g = vec![0.0f32; total]; + let mut nearest = vec![0u32; total]; + par_units( + total, + &mut g, + w.max(1), + &mut nearest, + w.max(1), + || Dt1Scratch::new(n), + |t, y, out, near| { + for (x, f) in t.f[..w].iter_mut().enumerate() { + *f = gc[x * h + y]; + } + dt1(&t.f[..w], &mut t.o[..w], &mut t.v, &mut t.z, &mut t.near[..w]); + for (x, (d, ne)) in out.iter_mut().zip(near.iter_mut()).enumerate() { + *d = t.o[x].sqrt(); + let px = t.near[x]; + *ne = (nc[px * h + y] as usize * w + px) as u32; + } + }, + ); + (g, nearest) +} + +/// Chamfer distance transform with a 5 × 5 mask of exact Euclidean step lengths (1, √2, √5), +/// plus the index of the nearest `inside` pixel (0 on inside pixels). Photoshop's effect +/// distances follow this metric: its stroke corners measure 3.236 = √5 + 1 at offset (1, 3) +/// and 3.650 = √5 + √2 at (2, 3), where the exact distances are 3.162 and 3.606. +#[cfg(test)] +pub(super) fn chamfer_nearest(inside: &[bool], w: usize, h: usize) -> (Vec, Vec) { + chamfer_from(inside.iter().map(|&b| if b { 0.0 } else { CHAMFER_INF }).collect(), w, h) +} + +const CHAMFER_INF: f32 = 1e20; + +/// [`chamfer_nearest`] from per-pixel start values (`CHAMFER_INF` = not a seed): the result is +/// the minimum over seeds of start value + path length, so partly covered seeds can start at +/// their sub-pixel edge offset. +fn chamfer_from(mut d: Vec, w: usize, h: usize) -> (Vec, Vec) { + const S2: f32 = std::f32::consts::SQRT_2; + const S5: f32 = 2.236_068; + // Forward-pass neighbours (already visited in raster order); the backward pass mirrors them. + const FWD: [(i64, i64, f32); 8] = [(-1, 0, 1.0), (-1, -1, S2), (0, -1, 1.0), (1, -1, S2), (-1, -2, S5), (1, -2, S5), (-2, -1, S5), (2, -1, S5)]; + let mut near: Vec = (0..w * h).collect(); + let (wi, hi) = (w as i64, h as i64); + let relax = |x: i64, y: i64, sign: i64, d: &mut Vec, near: &mut Vec| { + let i = (y * wi + x) as usize; + let mut best = d[i]; + let mut bn = near[i]; + for &(ox, oy, wt) in &FWD { + let (nx, ny) = (x + ox * sign, y + oy * sign); + if nx < 0 || ny < 0 || nx >= wi || ny >= hi { + continue; + } + let j = (ny * wi + nx) as usize; + let c = d[j] + wt; + if c < best { + best = c; + bn = near[j]; + } + } + d[i] = best; + near[i] = bn; + }; + for y in 0..hi { + for x in 0..wi { + relax(x, y, 1, &mut d, &mut near); + } + } + for y in (0..hi).rev() { + for x in (0..wi).rev() { + relax(x, y, -1, &mut d, &mut near); + } + } + (d, near) +} + +/// Distance from each pixel centre outside the shape to the shape's edge. +/// Pixels with non-zero alpha are inside; the edge inside the nearest such +/// pixel is placed by its alpha (coverage), as Photoshop does. Inside pixels +/// get ≤ 0. +pub(super) fn dist_outside(s: &Map) -> Vec { + dist_outside_by(s, Metric::Euclidean) +} + +/// Distance metric for effect distance fields. +#[derive(Clone, Copy, PartialEq)] +pub(super) enum Metric { + /// Exact Euclidean (effect edges). + Euclidean, + /// 5 × 5 chamfer (inside strokes, spread / choke; see [`chamfer_nearest`]). + Chamfer, +} + +/// Outside width from which a stroke's outer edge uses the exact Euclidean transform instead of +/// the fitted 5 × 5 chamfer. +/// +/// The chamfer's level sets are octagons: measured against a point source, its distance exceeds +/// the Euclidean radius by up to `0.027 · r` px — 0.48 px at r = 18 (the widest outside stroke any +/// Photoshop oracle matches with the chamfer) and 1.6 px at r = 60, where a wide stroke's boundary +/// visibly facets (#3646). Half a pixel of deviation is reached at r ≈ 19, so strokes narrower +/// than 20 px keep the chamfer, whose sub-pixel edge seeding Photoshop matches at small offsets, +/// and wider ones stay round. +pub const STROKE_CHAMFER_MAX: f32 = 20.0; + +/// Whether a stroke whose outside edge is `out_w` px wide uses the exact Euclidean transform (round) +/// rather than the 5 × 5 chamfer's octagon ([`STROKE_CHAMFER_MAX`]). The CPU compositor and the GPU +/// compositor's `program_with` both call this, so a stroke picks the same field in each. +pub fn stroke_outside_exact(out_w: f32) -> bool { + out_w >= STROKE_CHAMFER_MAX +} + +pub(super) fn dist_outside_by(s: &Map, m: Metric) -> Vec { + if m == Metric::Chamfer { + // Seeds start at their sub-pixel edge offset (1 − coverage). + let start = s.v.iter().map(|&a| if a > INSIDE_EPS { 1.0 - a.min(1.0) } else { CHAMFER_INF }).collect(); + let (d, _) = chamfer_from(start, s.w, s.h); + return d.iter().zip(&s.v).map(|(d, &a)| if a > INSIDE_EPS { -0.5 } else { d - 0.5 }).collect(); + } + let inside = covered(s, |a| a > INSIDE_EPS); + let (d, near) = edt_nearest(&inside, s.w, s.h); + par_fill(s.w, s.h, 0.0f32, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + let i = y * s.w + x; + *out = if inside[i] { -0.5 } else { d[i] - 0.5 + (1.0 - s.v[near[i] as usize].min(1.0)) }; + } + }) +} + +/// Which pixels of `s` satisfy `test`, row by row in parallel. +fn covered(s: &Map, test: impl Fn(f32) -> bool + Sync) -> Vec { + par_fill(s.w, s.h, false, |y, row| { + for (e, &a) in row.iter_mut().zip(s.v.get(y * s.w..).unwrap_or_default()) { + *e = test(a); + } + }) +} + +/// Distance from each pixel centre inside the shape to the shape's edge +/// (≤ 0 outside). +pub(super) fn dist_inside(s: &Map) -> Vec { + dist_inside_by(s, Metric::Euclidean) +} + +pub(super) fn dist_inside_by(s: &Map, m: Metric) -> Vec { + if m == Metric::Chamfer { + // Partly covered edge pixels (alpha below their neighbourhood's) are seeds starting at + // their coverage, mirroring `dist_outside`: a 25 % edge column puts the edge 0.25 px in. + let cov = local_coverage(s); + let start = + s.v.iter() + .zip(&cov.v) + .map(|(&a, &c)| { + if a <= INSIDE_EPS { + 0.0 + } else if c < 1.0 - INSIDE_EPS { + c + } else { + CHAMFER_INF + } + }) + .collect(); + let (d, _) = chamfer_from(start, s.w, s.h); + return d.iter().zip(&s.v).map(|(d, &a)| if a <= INSIDE_EPS { -0.5 } else { d - 0.5 }).collect(); + } + let outside = covered(s, |a| a <= INSIDE_EPS); + let (d, _) = edt_nearest(&outside, s.w, s.h); + par_fill(s.w, s.h, 0.0f32, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + let i = y * s.w + x; + *out = if outside[i] { -0.5 } else { d[i] - 0.5 }; + } + }) +} + +/// Alpha relative to the 3×3 neighbourhood maximum: separates edge coverage +/// from the fill's own opacity on shape layers. +pub(super) fn local_coverage(s: &Map) -> Map { + let mut out = s.clone(); + for y in 0..s.h as i64 { + for x in 0..s.w as i64 { + let a = s.get(x, y); + if a <= INSIDE_EPS { + continue; + } + let mut mx = a; + for dy in -1..=1 { + for dx in -1..=1 { + mx = mx.max(s.get(x + dx, y + dy)); + } + } + out.v[y as usize * s.w + x as usize] = (a / mx).min(1.0); + } + } + out +} + +/// Signed distance from the centre of a pixel of coverage `a` to the straight edge crossing it, +/// positive when the centre is inside the shape. `n` is the edge's unit normal (its signs don't +/// matter). +/// +/// A unit pixel cut by a straight edge at distance `r` from its centre (on the side that holds at +/// most half of the pixel) is covered `1/2 - r/u` while the edge crosses two opposite sides, and +/// `((u + v)/2 - r)² / (2uv)` once it only cuts off a corner, with `u ≥ v` the larger and smaller +/// component of the normal. Inverting that places the edge by its coverage at any angle. For an +/// axis-aligned edge (`v = 0`) it is the `a - 1/2` that [`dist_outside`] assumes. +pub(super) fn edge_offset(n: [f32; 2], a: f32) -> f32 { + if !a.is_finite() { + return 0.0; + } + let (u, v) = (n[0].abs().max(n[1].abs()), n[0].abs().min(n[1].abs())); + let (c, inside) = if a > 0.5 { (1.0 - a, true) } else { (a, false) }; + let c = c.clamp(0.0, 0.5); + // The coverage below which the edge only cuts off a corner. + let corner = if u > 0.0 { v / (2.0 * u) } else { 0.0 }; + let r = if c >= corner { (0.5 - c) * u } else { 0.5 * (u + v) - (2.0 * u * v * c).sqrt() }; + if inside { r } else { -r } +} + +/// A sharp, anti-aliased edge pixel: where it puts the straight edge crossing it. +#[derive(Clone, Copy)] +pub(super) struct SharpEdge { + /// Signed distance from the pixel's centre to the edge, positive inside ([`edge_offset`]). + pub(super) offset: f32, + /// The edge's unit normal pointing into the shape (`[0, 0]` when the coverage gives no direction). + pub(super) normal: [f32; 2], +} + +/// Half the spacing of the edge pixels along an edge (at most √2 / 2, along a diagonal): a pixel +/// within it of the foot of the perpendicular sees the edge as a line, one further out as its end. +const EDGE_REACH: f32 = 0.75; + +impl SharpEdge { + /// Distance to the edge from the pixel `(dx, dy)` away from this one, positive on the shape's + /// side (`inside`) or on the empty side. It is the distance to the edge's line where the + /// perpendicular lands within [`EDGE_REACH`] of this pixel, and to the end of that stretch + /// beyond, so the distance to a straight edge is exact and does not follow the pixel staircase. + /// `None` when the edge has no direction or `(dx, dy)` is on the wrong side of it. + fn distance(&self, dx: f32, dy: f32, inside: bool) -> Option { + let [nx, ny] = self.normal; + if nx == 0.0 && ny == 0.0 { + return None; + } + let signed = self.offset + dx * nx + dy * ny; + let across = if inside { signed } else { -signed }; + let along = (dx * -ny + dy * nx).abs(); + (across > 0.0).then(|| across.hypot((along - EDGE_REACH).max(0.0))) + } +} + +/// A sharp edge pixel and where it sits. +#[derive(Clone, Copy)] +pub(super) struct EdgePixel { + /// Index of the pixel in the map. + pub(super) at: u32, + /// The pixel's coverage ([`local_coverage`] of it). + pub(super) cov: f32, + pub(super) edge: SharpEdge, +} + +/// The sharp edge pixels of a map: a short list, and for every pixel a 4 byte slot (0 = no edge, k = +/// the k-th of the list). Maps are big and edge pixels few, so a per-pixel `Option` (16 +/// bytes) made every pass over it, and the copies the refinement needs, memory-bound. +pub(super) struct SharpEdges { + w: usize, + h: usize, + pub(super) slot: Vec, + pub(super) pixels: Vec, +} + +impl SharpEdges { + fn empty(w: usize, h: usize) -> Self { + SharpEdges { w, h, slot: Vec::new(), pixels: Vec::new() } + } + + /// The edge of pixel `i`, if it is a sharp edge pixel. + fn get(&self, i: usize) -> Option { + let k = (*self.slot.get(i)? as usize).checked_sub(1)?; + self.pixels.get(k).map(|p| p.edge) + } + + /// The edge of pixel `(x, y)`, if it is a sharp edge pixel (`None` off the map). + fn at(&self, x: usize, y: usize) -> Option { + if x >= self.w || y >= self.h { None } else { self.get(y * self.w + x) } + } + + fn has(&self, x: usize, y: usize) -> bool { + self.at(x, y).is_some() + } + + pub(super) fn is_empty(&self) -> bool { + self.pixels.is_empty() + } + + /// Every sharp edge pixel, as (index in the map, its edge), in pixel order. + #[cfg(test)] + pub(super) fn iter(&self) -> impl Iterator + '_ { + self.pixels.iter().map(|p| (p.at as usize, p.edge)) + } +} + +/// Where the sharp, anti-aliased edge pixels of `s` put the edge ([`edge_offset`], along the normal +/// the coverage gradient gives). Sharp pixels are partly covered and touch both an empty and a full +/// pixel; hard edges and soft ramps have none and keep the `alpha - 1/2` of [`dist_outside`]. +/// +/// An edge pixel is covered and has an empty neighbour, so a pass over which pixels are covered finds +/// the few candidates without computing [`local_coverage`] of the whole map; the coverage is then +/// worked out where it is needed, by the same formula. Rows are independent and go in parallel. +pub(super) fn sharp_edges(s: &Map) -> SharpEdges { + let (w, h) = (s.w, s.h); + if w == 0 || h == 0 || s.v.len() != w * h || s.v.len() >= u32::MAX as usize { + return SharpEdges::empty(w, h); + } + let (wi, hi) = (w as i64, h as i64); + // `local_coverage` of the pixel at (x, y), on the map. + let cov_at = |x: i64, y: i64| -> f32 { + let a = s.v[y as usize * w + x as usize]; + if a <= INSIDE_EPS { + return a; + } + let mut mx = a; + for dy in -1..=1 { + for dx in -1..=1 { + mx = mx.max(s.get(x + dx, y + dy)); + } + } + (a / mx).min(1.0) + }; + // The coverage with the map's border repeated, for the gradient. + let cov_clamped = |x: i64, y: i64| cov_at(x.max(0).min(wi - 1), y.max(0).min(hi - 1)); + // Whether a pixel is not empty. Off the map counts as covered: only a neighbour on the map can be empty. + let solid = |x: i64, y: i64| -> bool { + if x < 0 || y < 0 || x >= wi || y >= hi { + return true; + } + let a = s.v[y as usize * w + x as usize]; + a.is_nan() || a > INSIDE_EPS + }; + let mut rows: Vec> = vec![Vec::new(); h]; + par_units( + w * h, + &mut rows, + 1, + &mut [] as &mut [()], + 0, + || (), + |_, y, row, _| { + let Some(row) = row.first_mut() else { return }; + let y = y as i64; + for x in 0..wi { + if !solid(x, y) || (-1..=1).all(|dy| (-1..=1).all(|dx| solid(x + dx, y + dy))) { + continue; + } + let i = (y * wi + x) as usize; + let c = cov_at(x, y); + if s.v[i] <= INSIDE_EPS || c >= 1.0 - INSIDE_EPS { + continue; + } + let (mut empty, mut full) = (false, false); + for (dx, dy) in (-1..=1).flat_map(|dy| (-1..=1).map(move |dx| (dx, dy))) { + let (nx, ny) = (x + dx, y + dy); + if (dx, dy) == (0, 0) || nx < 0 || ny < 0 || nx >= wi || ny >= hi { + continue; + } + empty |= s.get(nx, ny) <= INSIDE_EPS; + full |= cov_at(nx, ny) >= 1.0 - INSIDE_EPS; + } + if !(empty && full) { + continue; + } + let at = &cov_clamped; + let gx = (at(x + 1, y - 1) + 2.0 * at(x + 1, y) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2.0 * at(x - 1, y) + at(x - 1, y + 1)); + let gy = (at(x - 1, y + 1) + 2.0 * at(x, y + 1) + at(x + 1, y + 1)) - (at(x - 1, y - 1) + 2.0 * at(x, y - 1) + at(x + 1, y - 1)); + let len = gx.hypot(gy); + let (normal, n) = if len.is_finite() && len > 1e-6 { ([gx / len, gy / len], [gx / len, gy / len]) } else { ([0.0, 0.0], [1.0, 0.0]) }; + row.push(EdgePixel { at: i as u32, cov: c, edge: SharpEdge { offset: edge_offset(n, c), normal } }); + } + }, + ); + let mut pixels: Vec = Vec::with_capacity(rows.iter().map(Vec::len).sum()); + for row in rows { + pixels.extend(row); + } + let mut slot = vec![0u32; w * h]; + for (k, p) in pixels.iter().enumerate() { + if let Some(s) = slot.get_mut(p.at as usize) { + *s = k as u32 + 1; + } + } + refine_edge_normals(&mut pixels, &slot, w, h); + SharpEdges { w, h, slot, pixels } +} + +/// How far (in pixels) around an edge pixel [`refine_edge_normals`] looks for its neighbours. +const NORMAL_RADIUS: i64 = 3; + +/// The 3×3 gradient of the coverage gives an edge's direction to 1-2 degrees, and its error is +/// systematic, so it tilts the distance of every pixel the same way and shows as a faint ripple. +/// The edge points of a straight edge's pixels (each pixel's centre moved to its edge) lie on one +/// line, and the line through the points of the pixels around one gives the direction to a fraction +/// of a degree. Where those points are not on a line (corners, tight curves) the gradient's normal +/// stays. +fn refine_edge_normals(pixels: &mut [EdgePixel], slot: &[u32], w: usize, h: usize) { + let (wi, hi) = (w as i64, h as i64); + let points: Vec<[f32; 2]> = pixels + .iter() + .map(|p| [(p.at as i64 % wi) as f32 - p.edge.offset * p.edge.normal[0], (p.at as i64 / wi) as f32 - p.edge.offset * p.edge.normal[1]]) + .collect(); + let before: Vec = pixels.iter().map(|p| p.edge).collect(); + // Every pixel reads the unrefined edges around it and writes its own, so they go in parallel. + let work = pixels.len().saturating_mul(32); + par_units(work, pixels, 1, &mut [] as &mut [()], 0, Vec::<[f32; 2]>::new, |near, k, pixel, _| { + let (Some(pixel), Some(&e)) = (pixel.first_mut(), before.get(k)) else { return }; + let (x, y) = (pixel.at as i64 % wi, pixel.at as i64 / wi); + let (mut n, mut sum) = (0.0f32, [0.0f32; 2]); + near.clear(); + for (dx, dy) in (-NORMAL_RADIUS..=NORMAL_RADIUS).flat_map(|dy| (-NORMAL_RADIUS..=NORMAL_RADIUS).map(move |dx| (dx, dy))) { + let (nx, ny) = (x + dx, y + dy); + if dx * dx + dy * dy > NORMAL_RADIUS * NORMAL_RADIUS || nx < 0 || ny < 0 || nx >= wi || ny >= hi { + continue; + } + let Some(j) = slot.get((ny * wi + nx) as usize).and_then(|&s| (s as usize).checked_sub(1)) else { continue }; + let (Some(o), Some(&p)) = (before.get(j), points.get(j)) else { continue }; + if o.normal[0] * e.normal[0] + o.normal[1] * e.normal[1] > 0.9 { + near.push(p); + sum = [sum[0] + p[0], sum[1] + p[1]]; + n += 1.0; + } + } + if near.len() < 3 { + return; + } + let mean = [sum[0] / n, sum[1] / n]; + let (mut sxx, mut sxy, mut syy) = (0.0f32, 0.0f32, 0.0f32); + for p in near.iter() { + let (dx, dy) = (p[0] - mean[0], p[1] - mean[1]); + sxx += dx * dx; + sxy += dx * dy; + syy += dy * dy; + } + // Spread along and across the best line through the points. + let half = 0.5 * (sxx + syy); + let root = (0.25 * (sxx - syy) * (sxx - syy) + sxy * sxy).sqrt(); + let (along, across) = (((half + root) / n).max(0.0).sqrt(), ((half - root) / n).max(0.0).sqrt()); + if !(along > EDGE_LINE_MIN_SPREAD && across < EDGE_LINE_MAX_OFF) { + return; + } + let angle = 0.5 * (2.0 * sxy).atan2(sxx - syy); + let mut normal = [-angle.sin(), angle.cos()]; + if normal[0] * e.normal[0] + normal[1] * e.normal[1] < 0.0 { + normal = [-normal[0], -normal[1]]; + } + pixel.edge.normal = normal; + pixel.edge.offset = edge_offset(normal, pixel.cov); + }); +} + +/// The edge points around a pixel must spread at least this far (px, standard deviation) along +/// their line to give it a direction, and stay within [`EDGE_LINE_MAX_OFF`] of it. +const EDGE_LINE_MIN_SPREAD: f32 = 0.7; + +const EDGE_LINE_MAX_OFF: f32 = 0.1; + +/// How far from the foot of the perpendicular (in pixels) [`edge_distance`] looks for edge pixels. +const FOOT_RADIUS: i64 = 2; + +/// The distance from pixel `p` to the sharp edge whose pixel `q` is nearest to it, or `None` when +/// `q` gives no usable distance. The nearest pixel by its centre is not the best one: it can sit a +/// few pixels along the edge from the foot of the perpendicular and deeper than the edge, and the +/// further `p` is from the edge the further, so its distance ripples along the edge. So this takes +/// the smallest distance of the edge pixels around that foot, which is exact for a straight edge. +fn edge_distance(sharp: &SharpEdges, p: [usize; 2], q: [usize; 2], inside: bool) -> Option { + let (px, py) = (p[0] as f32, p[1] as f32); + let e = sharp.at(q[0], q[1])?; + let mut best = e.distance(px - q[0] as f32, py - q[1] as f32, inside)?; + // Where p's perpendicular meets q's line. + let signed = e.offset + (px - q[0] as f32) * e.normal[0] + (py - q[1] as f32) * e.normal[1]; + let (fx, fy) = ((px - signed * e.normal[0]).round() as i64, (py - signed * e.normal[1]).round() as i64); + for sy in (fy - FOOT_RADIUS).max(0)..=(fy + FOOT_RADIUS).min(sharp.h as i64 - 1) { + for sx in (fx - FOOT_RADIUS).max(0)..=(fx + FOOT_RADIUS).min(sharp.w as i64 - 1) { + if let Some(near) = sharp.at(sx as usize, sy as usize) + && let Some(d) = near.distance(px - sx as f32, py - sy as f32, inside) + { + best = best.min(d); + } + } + } + Some(best) +} + +/// [`dist_inside`] for chiselled bevels. A sharp edge pixel puts the edge where its coverage says, +/// at any angle, and the pixels near it measure to that edge ([`edge_distance`]), so the distance +/// ramps stay planar along an oblique edge instead of following the pixel staircase. The plain +/// distance (to the nearest empty pixel, less half a pixel) never falls short of the true one, so +/// it caps the result where an edge lies exactly on a pixel boundary and has no sharp pixel; a mask +/// without sharp pixels gives exactly [`dist_inside`]. Values past `reach` pixels are not refined. +pub(super) fn bevel_dist_inside(s: &Map, sharp: &SharpEdges, reach: f32) -> Vec { + let empty = covered(s, |a| a <= INSIDE_EPS); + let (d, near) = edt_nearest(&empty, s.w, s.h); + let at = |x: usize, y: usize| -> f32 { + let i = y * s.w + x; + if empty[i] { + return -0.5; + } + if let Some(e) = sharp.get(i) { + return e.offset; + } + let plain = d[i] - 0.5; + if d[i] > reach + EDGE_MARGIN || sharp.is_empty() { + return plain; + } + // The sharp pixel next to the nearest empty one that is nearest to this pixel. + let (px, py) = (x as i64, y as i64); + let (ox, oy) = ((near[i] as usize % s.w) as i64, (near[i] as usize / s.w) as i64); + let q = (-1..=1) + .flat_map(|dy| (-1..=1).map(move |dx| (ox + dx, oy + dy))) + .filter(|&(x, y)| x >= 0 && y >= 0 && sharp.has(x as usize, y as usize)) + .min_by_key(|&(x, y)| (x - px) * (x - px) + (y - py) * (y - py)); + match q.and_then(|(x, y)| edge_distance(sharp, [px as usize, py as usize], [x as usize, y as usize], true)) { + Some(refined) => refined.min(plain), + None => plain, + } + }; + par_fill(s.w, s.h, 0.0f32, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + *out = at(x, y); + } + }) +} + +/// [`dist_outside`] for chiselled bevels, with sharp edge pixels placed as in [`bevel_dist_inside`]. +pub(super) fn bevel_dist_outside(s: &Map, sharp: &SharpEdges, reach: f32) -> Vec { + let inside = covered(s, |a| a > INSIDE_EPS); + let (d, near) = edt_nearest(&inside, s.w, s.h); + let at = |x: usize, y: usize| -> f32 { + let i = y * s.w + x; + if let Some(e) = sharp.get(i) { + return -e.offset; + } + if inside[i] { + return -0.5; + } + let q = near[i] as usize; + let Some(e) = sharp.get(q) else { return d[i] - (s.v[q].min(1.0) - 0.5) }; + let (p, qp) = ([x, y], [q % s.w, q / s.w]); + let measured = if d[i] <= reach + EDGE_MARGIN { + edge_distance(sharp, p, qp, false) + } else { + e.distance(p[0] as f32 - qp[0] as f32, p[1] as f32 - qp[1] as f32, false) + }; + measured.unwrap_or(d[i] - e.offset) + }; + par_fill(s.w, s.h, 0.0f32, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + *out = at(x, y); + } + }) +} + +/// Pixels past the reach that are still refined, so the value is right where the ramp ends. +const EDGE_MARGIN: f32 = 2.0; + +/// Alpha above which a pixel belongs to the layer's shape (half an 8-bit step). +pub(super) const INSIDE_EPS: f32 = 0.5 / 255.0; + +/// A distance field of an effect shape, as the map builders above compute it (for the GPU +/// compositor, which builds the rest of the maps itself; keep in sync with `shadow_map`, +/// `glow_map`, `bevel_maps` and `build_maps`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum FieldKind { + /// `dist_outside` of the shape: precise outer glows. + Outside, + /// `dist_inside` of the shape: precise inner glows. + Inside, + /// `bevel_dist_outside` of the shape: the outside distance of chiselled bevels. + BevelOutside, + /// `bevel_dist_inside` of the shape: the inside distance of chiselled bevels. + BevelInside, + /// Chamfer distance outside the shape: a narrow raster stroke's outer edge (see + /// [`stroke_outside_exact`]), and the spread of drop shadows and softer outer glows + /// ([`dilate`]); their metric is fitted to Photoshop (#224) and keeps the sub-pixel seeding. + StrokeOutside, + /// Chamfer distance outside `1 - alpha`: the choke of inner shadows and softer inner glows. + ChokeInside, + /// Stroke distance inside the shape. + StrokeInside, + /// Exact Euclidean distance outside the shape: a wide raster stroke's outer edge (see + /// [`stroke_outside_exact`]). The chamfer's level sets are polygons (an ~8-fold octagon), so a + /// wide stroke's outer boundary facets; the shadow / glow spread above keeps the chamfer (#3646). + StrokeOutsideExact, + /// Stroke distance outside a shape layer's outline (from its local coverage), exact Euclidean. + StrokeOutsideVector, + /// Chamfer distance outside a shape layer's outline (from its local coverage): a narrow vector + /// stroke's outer edge, where the chamfer matches Photoshop (see [`STROKE_CHAMFER_MAX`]). + StrokeOutsideVectorChamfer, +} + +/// The `kind` distance field of the shape `alpha` (row-major `w × h`). Values past `reach` pixels +/// from the shape's edge are only meant to be large (the bevel fields skip refining them). +pub fn distance_field(kind: FieldKind, alpha: Vec, w: usize, h: usize, reach: f32) -> Vec { + let s = Map { w, h, v: alpha }; + match kind { + FieldKind::Outside => dist_outside(&s), + FieldKind::Inside => dist_inside(&s), + FieldKind::BevelOutside => bevel_dist_outside(&s, &sharp_edges(&s), reach), + FieldKind::BevelInside => bevel_dist_inside(&s, &sharp_edges(&s), reach), + FieldKind::StrokeOutside => dist_outside_by(&s, Metric::Chamfer), + FieldKind::ChokeInside => dist_outside_by(&s.map(|a| 1.0 - a), Metric::Chamfer), + FieldKind::StrokeInside => dist_inside_by(&s, Metric::Chamfer), + FieldKind::StrokeOutsideExact => dist_outside_by(&s, Metric::Euclidean), + FieldKind::StrokeOutsideVector => dist_outside_by(&local_coverage(&s), Metric::Euclidean), + FieldKind::StrokeOutsideVectorChamfer => dist_outside_by(&local_coverage(&s), Metric::Chamfer), + } +} + +/// Both chiselled bevel fields of `alpha`, `[BevelInside, BevelOutside]`: each is its +/// [`distance_field`], with the sharp edges they both start from found once. +pub fn bevel_distance_fields(alpha: Vec, w: usize, h: usize, reach: f32) -> [Vec; 2] { + bevel_dists(&Map { w, h, v: alpha }, reach) +} + +/// The inside and outside bevel distances of `s`, from one set of sharp edges. +pub(super) fn bevel_dists(s: &Map, reach: f32) -> [Vec; 2] { + let sharp = sharp_edges(s); + [bevel_dist_inside(s, &sharp, reach), bevel_dist_outside(s, &sharp, reach)] +} diff --git a/crates/compose/src/effects/paint.rs b/crates/compose/src/effects/paint.rs new file mode 100644 index 0000000000..9b17749049 --- /dev/null +++ b/crates/compose/src/effects/paint.rs @@ -0,0 +1,402 @@ +use super::blur::{blur, dilate}; +use super::distance::{dist_inside, dist_outside}; +use super::*; + +pub(super) fn contour_lut(c: &Contour) -> Option> { + match c { + Contour::Linear => None, + Contour::Custom { points, corners, .. } => Some(crate::adjust::contour_curve_lut(points, corners)), + } +} + +/// Satin's coverage transfer: the contour read from its far end, `|c(1 − v) − c(1)|`. Measured in +/// Photoshop 27.11: Cone and Cone − Inverted Satins are identical, and a Gaussian Satin runs under +/// the diagonal (0.36 at 0.5) while the same Gaussian on a glow or gloss runs over it (0.65). +/// `None` = identity. +pub fn satin_lut(c: &Contour) -> Option> { + let lut = contour_lut(c)?; + let end = lut.last().copied().unwrap_or(1.0); + Some(lut.iter().rev().map(|v| (v - end).abs()).collect()) +} + +/// Interpolated lookup in a 0..=1 table (as the GPU's `lut()`). +pub(super) fn lut_at(l: &[f32], v: f32) -> f32 { + let x = v.clamp(0.0, 1.0) * (l.len() - 1) as f32; + let i = x.floor() as usize; + let j = (i + 1).min(l.len() - 1); + l[i] + (l[j] - l[i]) * (x - i as f32) +} + +/// A glow's coverage transfer: its contour applied over the Range (Photoshop maps the glow's +/// coverage `v` through `contour(min(v / range, 1))`, so the default 50 % doubles a blurred +/// edge's 0.5 to full strength). `None` = identity. +pub fn glow_lut(g: &Glow) -> Option> { + ranged_lut(&g.contour, g.range) +} + +/// A contour applied over a Range (`contour(min(v / range, 1))`); `None` = identity. +pub fn ranged_lut(contour: &Contour, range: f32) -> Option> { + let base = contour_lut(contour); + let range = if range.is_finite() { range.clamp(0.01, 1.0) } else { 1.0 }; + if range >= 0.999 { + return base; + } + let n = 4096; + Some( + (0..n) + .map(|k| { + let v = (k as f32 / (n - 1) as f32 / range).min(1.0); + base.as_ref().map_or(v, |l| lut_at(l, v)) + }) + .collect(), + ) +} + +/// The bevel Contour element's height transfer: the contour alone. Unlike a glow's, its Range is +/// not a `v / range` stretch: that flattened a Linear contour at the default 50 % to a bevel half +/// as wide as Photoshop's (a real 18 px smooth inner bevel at 136 % depth: top-edge highlight gone +/// 15 px in, Photoshop's still 0.19 at 16 px), and dropping it lowers the bad pixels of every +/// contour oracle (bevel-inner-contour-ramp-peak 25.9 → 21.8 %, -double-ring-aa-r70 25.2 → 21.0 %, +/// bevel-pillow-chisel-hard-gloss-and-contour 11.4 → 7.2 %). What Range does instead is still open. +pub fn bevel_contour_lut(c: &photocraft_doc::BevelContour) -> Vec { + contour_lut(&c.contour).unwrap_or_else(|| (0..4096).map(|k| k as f32 / 4095.0).collect()) +} + +pub(super) fn apply_lut(m: Map, l: Option>) -> Map { + match l { + None => m, + Some(l) => m.map(|v| lut_at(&l, v)), + } +} + +/// Deterministic per-pixel value in 0..=1, hashed from document coordinates +/// (the same hash as the GPU's `dissolve_noise`), so the speckle is stable +/// across renders, frames and tiles. +pub fn hash_noise(x: i64, y: i64) -> f32 { + let mut h = (x as i32 as u32).wrapping_mul(0x8da6_b343) ^ (y as i32 as u32).wrapping_mul(0xd816_3841) ^ 0x9e37_79b9; + h ^= h >> 15; + h = h.wrapping_mul(0x2c1b_3c6d); + h ^= h >> 12; + (h & 0xffff) as f32 / 65536.0 +} + +/// Effect noise (Photoshop's Noise slider): monochrome speckle in the coverage, +/// applied after the contour. `amount` is 0..=1; 0 leaves the map untouched. The speckle is +/// scaled by the coverage, so it fades out with the effect instead of lighting up the blur's +/// near-zero tail out to the edge of its rectangular reach (#7833). +pub(super) fn noise(m: &mut Map, amount: f32, x0: i32, y0: i32) { + if !amount.is_finite() || amount <= 0.0 { + return; + } + for y in 0..m.h { + for x in 0..m.w { + let v = &mut m.v[y * m.w + x]; + if *v <= 0.0 { + continue; + } + let n = hash_noise(i64::from(x0 + x as i32), i64::from(y0 + y as i32)); + *v = (*v * (1.0 + (n - 0.5) * 2.0 * amount)).clamp(0.0, 1.0); + } + } +} + +fn apply_contour(m: Map, c: &Contour) -> Map { + match contour_lut(c) { + None => m, + Some(l) => m.map(|v| lut_at(&l, v)), + } +} + +pub(super) fn rgb(c: &photocraft_color::Color) -> [f32; 3] { + c.to_rgb() +} + +/// Offset of an effect lit from `angle` at `distance` (shadow falls away from +/// the light), rounded to whole pixels as Photoshop does. +pub(super) fn offset(angle: f32, distance: f32) -> (f32, f32) { + let a = angle.to_radians(); + ((-a.cos() * distance).round(), (a.sin() * distance).round()) +} + +/// The lengths a 100 % gradient at `angle` spans in a `w` × `h` frame: the chord (Linear and +/// Reflected) and the ellipse-norm length (Radial, Angle, Diamond; its half is the radius). +pub fn gradient_units(angle: f32, w: f32, h: f32) -> (f32, f32) { + let (s, c) = angle.to_radians().sin_cos(); + // Gradient length: the bounds' extent along the angle as an ellipse + // norm (a unit gradient scaled to the bounds); fitted on psd-tools + // gradient-styles.psd (cached Photoshop renderings of every style). + let len = ((c * w).powi(2) + (s * h).powi(2)).sqrt().max(1.0); + // Linear / Reflected span the chord of the bounds through their centre along the angle: + // min(w / |cos|, h / |sin|). A 45° gradient on a 29 px square runs 41 px (psd-tools + // shape-fx2), an 87° one on a 600 × 60 text line 60 px (layer_effects); axis-aligned angles + // span the width / height. + let chord = (w / c.abs().max(1e-6)).min(h / s.abs().max(1e-6)).max(1.0); + (chord, len) +} + +/// Gradient parameter `t` in `0..=1` for pixel centre `(x, y)` inside `bounds`. +#[allow(clippy::too_many_arguments)] +pub fn gradient_t(style: GradientStyle, angle: f32, scale: f32, reverse: bool, offset: (f32, f32), bounds: Rect, x: f32, y: f32) -> f32 { + let w = bounds.width().max(1) as f32; + let h = bounds.height().max(1) as f32; + let cx = bounds.x0 as f32 + w / 2.0 + offset.0 * w; + let cy = bounds.y0 as f32 + h / 2.0 + offset.1 * h; + let (s, c) = angle.to_radians().sin_cos(); + let (dx, dy) = (x - cx, y - cy); + // Distance along the gradient direction (y axis points down). + let along = dx * c - dy * s; + let across = dx * s + dy * c; + let (chord, len) = gradient_units(angle, w, h); + let (chord, len) = (chord * scale.max(1e-3), len * scale.max(1e-3)); + // Linear / Reflected sample the pixel's top-left corner, half a pixel before its centre + // (with the whole-pixel end points of `fill_layout`: layer_effects' overlay 5.8 → 1.8/255, + // shape-fx2 2.8 → 1.1/255, gradient-fill.psd 1.9 → 0.5/255). + let corner = 0.5 * (c - s); + let mut t = match style { + GradientStyle::Linear => (along - corner) / chord + 0.5, + GradientStyle::Reflected => ((along - corner) / (chord / 2.0)).abs(), + GradientStyle::Radial => (dx * dx + dy * dy).sqrt() / (len / 2.0), + GradientStyle::Diamond => (along.abs() + across.abs()) / (len / 2.0), + // Clockwise sweep starting at the gradient angle. + GradientStyle::Angle => ((angle.to_radians() - (-dy).atan2(dx)) / std::f32::consts::TAU).rem_euclid(1.0), + }; + t = t.clamp(0.0, 1.0); + if reverse { 1.0 - t } else { t } +} + +/// Samples colour and opacity stops at `t`. +pub fn sample_gradient(g: &Gradient, t: f32) -> [f32; 4] { + PreparedGradient::new(g).sample(t) +} + +// Prepared only for one paint call: CMYK conversions must use that call's active profile. +struct PreparedGradient { + color: Vec<(f32, [f32; 3])>, + opacity: Vec<(f32, [f32; 3])>, +} + +impl PreparedGradient { + fn new(g: &Gradient) -> Self { + Self { color: g.stops.iter().map(|(p, c)| (*p, rgb(c))).collect(), opacity: g.opacity_stops.iter().map(|(p, a)| (*p, [*a; 3])).collect() } + } + + fn sample(&self, t: f32) -> [f32; 4] { + let color = sample_stops(&self.color, t); + let alpha = if self.opacity.is_empty() { 1.0 } else { sample_stops(&self.opacity, t)[0] }; + [color[0], color[1], color[2], alpha] + } +} + +fn sample_stops(stops: &[(f32, [f32; 3])], t: f32) -> [f32; 3] { + match stops { + [] => [t; 3], + [s] => s.1, + _ => { + if t <= stops[0].0 { + return stops[0].1; + } + for w in stops.windows(2) { + if t <= w[1].0 { + let k = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 }; + return std::array::from_fn(|i| w[0].1[i] + (w[1].1[i] - w[0].1[i]) * k); + } + } + stops[stops.len() - 1].1 + } + } +} + +/// Composite `color × coverage` into `dst` (both over the same rectangle). +fn paint(dst: &mut Buffer, m: &Map, color: impl Fn(usize) -> [f32; 4], blend: BlendMode, opacity: f32) { + let (x0, y0, w) = (i64::from(dst.rect.x0), i64::from(dst.rect.y0), (dst.rect.width().max(1)) as usize); + for (i, p) in dst.px.iter_mut().enumerate() { + let a = m.v[i] * opacity; + if a <= 0.0 { + continue; + } + let c = color(i); + if blend == BlendMode::Dissolve { + if dissolves_in(x0 + (i % w) as i64, y0 + (i / w) as i64, c[3] * a) { + *p = psblend::composite(BlendMode::Normal, *p, [c[0], c[1], c[2], 1.0], 1.0); + } + continue; + } + *p = psblend::composite(blend, *p, [c[0], c[1], c[2], c[3] * a], 1.0); + } +} + +/// Whether `e` paints anything in Dissolve mode. +pub(super) fn dissolves(e: &Effect) -> bool { + let d = |m: BlendMode| m == BlendMode::Dissolve; + match e { + Effect::DropShadow(s) | Effect::InnerShadow(s) => d(s.common.blend), + Effect::OuterGlow(g) | Effect::InnerGlow(g) => d(g.common.blend), + Effect::Stroke(s) => d(s.common.blend), + Effect::ColorOverlay { common, .. } | Effect::GradientOverlay { common, .. } | Effect::PatternOverlay { common, .. } => d(common.blend), + Effect::Satin(s) => d(s.common.blend), + Effect::BevelEmboss(b) => d(b.highlight.blend) || d(b.shadow.blend), + } +} + +/// Dissolve on an effect (#6995): a pixel takes the effect fully or not at all, with probability +/// `coverage`, picked by the same document-coordinate noise as a Dissolve layer. A soft glow or +/// shadow turns into scattered speckle instead of a smooth falloff. +pub(super) fn dissolves_in(x: i64, y: i64, coverage: f32) -> bool { + hash_noise(x, y) < coverage +} + +pub(super) fn paint_color(dst: &mut Buffer, m: &Map, c: [f32; 3], blend: BlendMode, opacity: f32) { + paint(dst, m, |_| [c[0], c[1], c[2], 1.0], blend, opacity); +} + +/// Spread / choke of a soft effect: (dilation radius, blur width). The dilation is whole pixels +/// (`size × spread` rounded: a 2 % spread of a 5 px shadow doesn't grow it at all), the blur +/// keeps `size × (1 − spread)` (ag-psd effects 10.6 → 3.8 % of pixels off). +pub fn spread_split(size: f32, spread: f32) -> (f32, f32) { + ((size * spread).round(), size * (1.0 - spread)) +} + +pub(super) fn shadow_map(shape: &Map, s: &Shadow, light: &GlobalLight, inner: bool, origin: (i32, i32)) -> Map { + let angle = if s.use_global_light { light.angle } else { s.angle }; + let (dx, dy) = offset(angle, s.distance); + let src = if inner { shape.clone().map(|a| 1.0 - a) } else { shape.clone() }; + let mut m = src.shifted(dx, dy, if inner { 1.0 } else { 0.0 }); + let (r, bw) = spread_split(s.size, s.spread); + m = dilate(&m, r); + blur(&mut m, bw); + let mut m = apply_contour(m, &s.contour); + noise(&mut m, s.noise, origin.0, origin.1); + if inner { + for (v, a) in m.v.iter_mut().zip(&shape.v) { + *v *= a; + } + } + m +} + +pub(super) fn glow_map(shape: &Map, g: &Glow, inner: bool, origin: (i32, i32)) -> Map { + // An inner glow is built from the edge inwards; a centre-source glow is its inverse, taken + // after the contour and Range (Photoshop 27.11, measured: the centre glow is exactly + // 1 − the edge glow, for both techniques). + let src = if inner { shape.clone().map(|a| 1.0 - a) } else { shape.clone() }; + let mut m = match g.technique { + GlowTechnique::Precise => { + // Coverage falls linearly from 0.5 at the edge to 0 at `size + 1` px (centre to + // centre), solid within the spread / choke: after the default 50 % Range that is + // Photoshop's 1 − D / (size + 1) beyond the solid part (measured: outer and inner, + // sizes 10 and 20, spread 0 and 40 %, choke 0 and 30 %: within 1 level; other Range + // values are unmeasured). The distances here are 0.5 px short of centre to centre. + let d = if inner { dist_inside(shape) } else { dist_outside(&src) }; + let solid = g.size * g.spread; + let soft = (g.size + 1.0 - solid).max(1e-3); + let mut m = Map::new(shape.w, shape.h, 0.0); + for (o, d) in m.v.iter_mut().zip(d) { + let d = d + 0.5; + *o = if d <= solid { 1.0 } else { 0.5 * (1.0 - (d - solid) / soft).clamp(0.0, 1.0) }; + } + m + } + GlowTechnique::Softer => { + let (r, bw) = spread_split(g.size, g.spread); + let mut m = dilate(&src, r); + blur(&mut m, bw); + m + } + }; + m = apply_lut(m, glow_lut(g)); + if inner && g.source == GlowSource::Center { + m = m.map(|v| 1.0 - v); + } + noise(&mut m, g.noise, origin.0, origin.1); + if inner { + for (v, a) in m.v.iter_mut().zip(&shape.v) { + *v *= a; + } + } + m +} + +/// Paints a pattern (looked up in `patterns`) through coverage `m`; missing patterns paint nothing. +#[allow(clippy::too_many_arguments)] +pub(super) fn paint_pattern( + dst: &mut Buffer, + m: &Map, + patterns: &PreparedPatterns<'_>, + name: &str, + id: &str, + place: Placement, + big: Rect, + blend: BlendMode, + opacity: f32, +) { + let Some(tile) = patterns.get(id, name) else { return }; + let w = big.width() as usize; + paint( + dst, + m, + |i| { + let (x, y) = (f64::from(big.x0 + (i % w) as i32) + 0.5, f64::from(big.y0 + (i / w) as i32) + 0.5); + let (u, v) = place.map(x, y); + tile.sample(u, v) + }, + blend, + opacity, + ); +} + +#[allow(clippy::too_many_arguments)] +pub(super) fn paint_fx( + dst: &mut Buffer, + m: &Map, + p: &FxPaint, + shape_bounds: Rect, + anchor: (f64, f64), + big: Rect, + blend: BlendMode, + opacity: f32, + patterns: &PreparedPatterns<'_>, +) { + match p { + FxPaint::Color(c) => paint_color(dst, m, rgb(c), blend, opacity), + FxPaint::Gradient(g) => { + let prepared = PreparedGradient::new(g); + let (angle, scale, offset) = crate::fill_layout::gradient_layout(g.style, g.angle, g.scale, g.offset, shape_bounds); + let w = big.width() as usize; + paint( + dst, + m, + |i| { + let (x, y) = ((big.x0 + (i % w) as i32) as f32 + 0.5, (big.y0 + (i / w) as i32) as f32 + 0.5); + prepared.sample(gradient_t(g.style, angle, scale, g.reverse, offset, shape_bounds, x, y)) + }, + blend, + opacity, + ) + } + FxPaint::Pattern { name, id, scale } => { + paint_pattern(dst, m, patterns, name, id, Placement::anchored(anchor, true, (0.0, 0.0), *scale, 0.0), big, blend, opacity) + } + } +} + +/// The opacity gain of a gradient glow: it is opaque from strength `range²` on (see [`paint_glow`]). +pub fn glow_gradient_gain(range: f32) -> f32 { + let r = if range.is_finite() { range.clamp(0.01, 1.0) } else { 1.0 }; + 1.0 / (r * r) +} + +/// A glow's paint over its map `m`. A gradient runs along the glow rather than across the +/// canvas: Photoshop colours the glow where its (ranged, contoured) strength is `v` with the +/// gradient at `1 - v`, so the first stop hugs the edge, and the glow is opaque from `v = range²` +/// on (photoshop corpus outer-glow-gradient.psd: 1.4/255 mean, against bands across the canvas; +/// psd-tools layer_params.psd). Glows have no gradient angle, style or Reverse. +#[allow(clippy::too_many_arguments)] +pub(super) fn paint_glow(dst: &mut Buffer, m: &Map, g: &Glow, shape_bounds: Rect, anchor: (f64, f64), big: Rect, patterns: &PreparedPatterns<'_>) { + let FxPaint::Gradient(gradient) = &g.paint else { + return paint_fx(dst, m, &g.paint, shape_bounds, anchor, big, g.common.blend, g.common.opacity, patterns); + }; + let prepared = PreparedGradient::new(gradient); + let gain = glow_gradient_gain(g.range); + let strength = Map { w: m.w, h: m.h, v: m.v.iter().map(|v| (v * gain).min(1.0)).collect() }; + paint(dst, &strength, |i| prepared.sample(1.0 - m.v.get(i).copied().unwrap_or(0.0).clamp(0.0, 1.0)), g.common.blend, g.common.opacity); +} From 273de6ace0af5f099511c66d6350f6da1da96e39 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:00:08 +0000 Subject: [PATCH 247/259] refactor(compose): split adjust.rs into adjust/ --- crates/compose/src/adjust.rs | 1268 +------------------------ crates/compose/src/adjust/channels.rs | 278 ++++++ crates/compose/src/adjust/color.rs | 482 ++++++++++ crates/compose/src/adjust/tone.rs | 488 ++++++++++ 4 files changed, 1274 insertions(+), 1242 deletions(-) create mode 100644 crates/compose/src/adjust/channels.rs create mode 100644 crates/compose/src/adjust/color.rs create mode 100644 crates/compose/src/adjust/tone.rs diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs index 5eb3314bbf..c25867c938 100644 --- a/crates/compose/src/adjust.rs +++ b/crates/compose/src/adjust.rs @@ -10,6 +10,32 @@ use photocraft_doc::adjust::{CurvePoint, HueRange, LevelsChannel, ToneSpace, lut use crate::Buffer; +mod channels; +mod color; +mod tone; + +#[cfg(test)] +use channels::lab_denorm; +pub use channels::{ + LAB_NEUTRAL, LabOp, apply_cmy, cmy_adjustment, cmyk_channel_adjustment, ink_brightness_contrast_lut, ink_luma, ink_through, lab_channel_adjustment, + lab_stored_op, stored_channel_adjustment, stored_channels, threshold_white, +}; +use channels::{apply_lab, legacy_brightness_contrast, legacy_brightness_contrast_hdr}; +use color::gradient; +pub use color::{ + BalanceCurve, VIBRANCE_BOOST, VIBRANCE_GREY, bayer4, black_white_gray, color_balance_channel, colorize_saturation, hdr_saturation_factor, hsl_to_rgb, + hue_range_tables, hue_saturation, hue_saturation_in, lut3d_sample, photo_filter_matrix, range_lightness, rgb_to_hsl, selective_color, + selective_color_weights, vibrance_lin, vibrance_px, +}; +#[cfg(test)] +use tone::LUT_SIZE; +pub(crate) use tone::apply_tone; +pub use tone::{ + TONE_SLOPE_SPAN, contour_curve_lut, curve_lut, curve_lut_mode, curve_map_lut, float_tone_extrapolates, float_tone_identity, levels, levels_float, + levels_gamma, levels_q, modern_brightness, modern_contrast, modern_lut, posterize, posterize_in, tone_luts, tone_luts_depth, tone_luts_q, +}; +use tone::{lut, map_rgb}; + /// The document tone curve used to linearize values for adjustments that /// work in linear light (Exposure). Until ICC profiles are wired in (M8) this /// approximates the Photoshop defaults: sRGB for colour documents and the @@ -265,57 +291,6 @@ fn apply_depth_mode(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, dept } } -/// Legacy Brightness/Contrast on a 32-bit document's samples: unclipped, with contrast pivoting at -/// 127 of 255 (photoshop corpus rgb32 and gray32 brightness-contrast-legacy.psd: every pixel -/// exact, negative and over-white values included; the 8/16-bit pivot, 128, is 0.43 of a level -/// off there). -fn legacy_brightness_contrast_hdr(brightness: f32, contrast: f32) -> impl Fn(f32) -> f32 { - const PIVOT: f32 = 127.0 / 255.0; - let b = brightness / 255.0; - let c = contrast.clamp(-100.0, 99.0); - let k = if c >= 0.0 { 1.0 / (1.0 - c / 100.0) } else { 1.0 + c / 100.0 }; - let (pre, post) = if c >= 0.0 { (b, 0.0) } else { (0.0, b) }; - move |v: f32| (v + pre - PIVOT) * k + PIVOT + post -} - -/// Legacy Brightness/Contrast as one channel's tone curve (see [`apply_depth`]). -fn legacy_brightness_contrast(brightness: f32, contrast: f32) -> impl Fn(f32) -> f32 { - legacy_brightness_contrast_at(brightness, contrast, LEGACY_PIVOT) -} - -/// [`legacy_brightness_contrast`] with contrast pivoting at `pivot`. -fn legacy_brightness_contrast_at(brightness: f32, contrast: f32, pivot: f32) -> impl Fn(f32) -> f32 { - let b = brightness / 255.0; - let c = contrast.clamp(-100.0, 99.0); - let k = if c >= 0.0 { 1.0 / (1.0 - c / 100.0) } else { 1.0 + c / 100.0 }; - let (pre, post) = if c >= 0.0 { (b, 0.0) } else { (0.0, b) }; - move |v: f32| ((v + pre - pivot) * k + pivot + post).clamp(0.0, 1.0) -} - -/// Whether Threshold at `level` turns colour `c` white in a document of `depth` (`None`: unknown, -/// treated as 8-bit). Photoshop splits on the luminosity 0.30 R + 0.59 G + 0.11 B (the blend -/// modes' `lum`), not the Rec. 601 grey, of the document's whole sample values: -/// - 8 bits: white when that luminosity, rounded to a level with halves down, reaches the level; -/// - 16 bits: white when it reaches the level converted to 16 bits (128 → 16448); -/// - 32 bits: white when it reaches the level. -/// -/// Exact on every pixel of psd-tools threshold_rgb.psd, threshold_16bits_rgb.psd and -/// threshold_16bits_grayscale.psd and of the photoshop corpus's rgb16 threshold-128.psd, where the -/// Rec. 601 grey split 28 and 100 pixels of the first two the other way. The sums of -/// `30 R + 59 G + 11 B` over whole samples are exact in f32 (at most 3 276 800). -pub fn threshold_white(c: [f32; 3], level: f32, depth: Option) -> bool { - let t = (level * 255.0).round(); - let sum = |q: f32| { - let [r, g, b] = c.map(|v| (v.clamp(0.0, 1.0) * q).round()); - 30.0 * r + 59.0 * g + 11.0 * b - }; - match depth { - None | Some(SampleType::U8) => sum(255.0) > 100.0 * t - 50.0, - Some(SampleType::U16) => sum(32768.0) >= 100.0 * (t * 32768.0 / 255.0).round(), - Some(SampleType::F32) => (0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]) * 255.0 >= t, - } -} - /// Applies an adjustment in a document of colour `mode`: [`apply_depth`], except that in Lab /// and CMYK documents the adjustments Photoshop evaluates on the document's own channels do so /// (see [`lab_channel_adjustment`] and [`cmyk_channel_adjustment`]). @@ -348,1197 +323,6 @@ pub fn apply_in(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth: O } } -/// Whether a Lab document evaluates `adj` on its L, a and b channels rather than on the screen -/// colour: Invert and Posterize (L, a and b alike), Brightness/Contrast (L only), Threshold -/// (split on L, neutral result) and Gradient Map (driven by L). Levels and Curves carry their own -/// Lab records ([`ToneSpace::Lab`]); everything else stays on the screen colour. -pub fn lab_channel_adjustment(adj: &Adjustment) -> bool { - matches!( - adj, - Adjustment::Invert - | Adjustment::Posterize { .. } - | Adjustment::Threshold { .. } - | Adjustment::BrightnessContrast { .. } - | Adjustment::GradientMap { .. } - ) -} - -/// Whether a CMYK document evaluates `adj` on its inks rather than on the screen colour: Invert -/// and Posterize (each ink, black included, so paper inverts to 400% ink), Threshold (paper or -/// 100% black ink alone) and Brightness/Contrast (each ink's stored value, 1 - ink, through the -/// tone curve; see [`ink_through`]). Photoshop corpus cmyk8 and cmyk16 invert, posterize-4, -/// threshold-128 and brightness-contrast(-legacy) follow these rules on the files' own inks on -/// every pixel; here the inks are the screen colour separated through the document's CMYK -/// profile, so neutrals carry the black that profile generates rather than the file's. -pub fn cmyk_channel_adjustment(adj: &Adjustment) -> bool { - stored_channel_adjustment(adj) || cmy_adjustment(adj) || matches!(adj, Adjustment::BrightnessContrast { .. }) -} - -/// Whether a CMYK document evaluates `adj` on C, M and Y as the complement of an RGB colour, -/// black kept ([`apply_cmy`]): Hue/Saturation (not Colorize, which Photoshop separates again, -/// black and all) and Color Balance (photoshop corpus cmyk16 hue-saturation.psd follows this on -/// every pixel within half a level, cmyk8 within two; color-balance within our RGB Color -/// Balance's own error). -pub fn cmy_adjustment(adj: &Adjustment) -> bool { - matches!(adj, Adjustment::HueSaturation { colorize: false, .. } | Adjustment::ColorBalance { .. }) -} - -/// A [`cmy_adjustment`] on straight inks (C, M, Y, K; 0 none): the RGB adjustment on -/// `(1 - c, 1 - m, 1 - y)`, black left alone. -pub fn apply_cmy(adj: &Adjustment, inks: &mut [[f32; 4]]) { - let width = i32::try_from(inks.len()).unwrap_or(i32::MAX); - let mut buf = Buffer { rect: crate::Rect::new(0, 0, width, 1), px: inks.iter().map(|i| [1.0 - i[0], 1.0 - i[1], 1.0 - i[2], 1.0]).collect() }; - apply_depth(adj, &mut buf, Transfer::Srgb, None); - for (ink, p) in inks.iter_mut().zip(&buf.px) { - for c in 0..3 { - ink[c] = (1.0 - p[c]).clamp(0.0, 1.0); - } - } -} - -/// Brightness/Contrast as the lookup table (4096 samples over 0..1) a CMYK ink's stored value, -/// `1 - ink`, goes through ([`ink_through`]): [`modern_lut`], or the legacy linear curve with its -/// contrast pivoting at 128 in ink, which is 127 of 255 stored (photoshop corpus cmyk16 -/// brightness-contrast-legacy.psd sits 0.43 of a level off around 128 stored, as a one-level -/// pivot shift times contrast +30's slope predicts). -pub fn ink_brightness_contrast_lut(brightness: f32, contrast: f32, legacy: bool) -> Vec { - if !legacy { - return modern_lut(brightness, contrast); - } - let curve = legacy_brightness_contrast_at(brightness, contrast, 1.0 - LEGACY_PIVOT); - (0..LUT_SIZE).map(|k| curve(k as f32 / (LUT_SIZE - 1) as f32)).collect() -} - -/// One CMYK ink (0: none) through a channel tone curve the way Photoshop applies one in CMYK: to -/// the stored value, `1 - ink`, so raising brightness takes ink away. -pub fn ink_through(table: &[f32], ink: f32) -> f32 { - 1.0 - lut(table, 1.0 - ink) -} - -/// Whether [`stored_channels`] evaluates `adj`: Invert, Posterize and Threshold. -pub fn stored_channel_adjustment(adj: &Adjustment) -> bool { - matches!(adj, Adjustment::Invert | Adjustment::Posterize { .. } | Adjustment::Threshold { .. }) -} - -/// Invert, Posterize or Threshold on one pixel's own channels in a Lab or CMYK document of -/// `depth` (`None`: unknown, treated as 8-bit): `ch` holds L, a, b normalised as [`lab_norm`] -/// gives them, or the C, M, Y, K inks (0: none). Lab Invert turns 8-bit bytes `v` into `255 - v` -/// (a becomes -1 - a) and mirrors a and b around neutral at 16 bits (photoshop corpus lab16 -/// invert.psd: neutral stays neutral). CMYK Threshold compares [`ink_luma`]. -pub fn stored_channels(adj: &Adjustment, mode: ColorMode, depth: Option, ch: &mut [f32]) { - let lab = mode == ColorMode::Lab; - match adj { - Adjustment::Invert => { - let mirror = if lab && depth.is_some_and(|d| d != SampleType::U8) { 256.0 / 255.0 } else { 1.0 }; - for (i, v) in ch.iter_mut().enumerate() { - *v = if i > 0 { mirror } else { 1.0 } - v.clamp(0.0, 1.0); - } - } - // CMYK posterizes the stored values (1 - ink), which its uneven levels make differ from - // posterizing the ink: psd-tools posterize_cmyk.psd (3 to 21 levels) is exact so. - Adjustment::Posterize { levels } if mode == ColorMode::Cmyk => ch.iter_mut().for_each(|v| *v = 1.0 - posterize_in(1.0 - *v, *levels, depth)), - Adjustment::Posterize { levels } => ch.iter_mut().for_each(|v| *v = posterize_in(*v, *levels, depth)), - Adjustment::Threshold { level } => { - // On the 8-bit grid, like the RGB threshold. - let t = (level * 255.0).round(); - let out = if lab { - let white = ch.first().is_some_and(|l| (l.clamp(0.0, 1.0) * 255.0).round() >= t); - [if white { 1.0 } else { 0.0 }, 128.0 / 255.0, 128.0 / 255.0, 0.0] - } else { - let ink = |i: usize| ch.get(i).copied().unwrap_or(0.0); - let black = (ink_luma([ink(0), ink(1), ink(2), ink(3)]) * 255.0).round() < t; - [0.0, 0.0, 0.0, if black { 1.0 } else { 0.0 }] - }; - ch.iter_mut().zip(out).for_each(|(v, o)| *v = o); - } - _ => {} - } -} - -/// The luma Photoshop's CMYK Threshold compares: Rec. 601 weights on the inks' plain complement, -/// `(1 - c)(1 - k)` and so on, whatever the document's profile (photoshop corpus cmyk8 and cmyk16 -/// threshold-128.psd: every pixel on the right side of level 128). -pub fn ink_luma(ink: [f32; 4]) -> f32 { - let paper = 1.0 - ink[3].clamp(0.0, 1.0); - rgb_to_gray([0, 1, 2].map(|i| (1.0 - ink[i].clamp(0.0, 1.0)) * paper)) -} - -/// Encoded sRGB → Lab normalised the way Photoshop's channels hold it: L/100, (a+128)/255, -/// (b+128)/255. -fn lab_norm(c: [f32; 3]) -> [f32; 3] { - let l = srgb_to_lab(c); - [l[0] / 100.0, (l[1] + 128.0) / 255.0, (l[2] + 128.0) / 255.0] -} - -/// The inverse of [`lab_norm`]. -fn lab_denorm(n: [f32; 3]) -> [f32; 3] { - lab_to_srgb([n[0] * 100.0, n[1] * 255.0 - 128.0, n[2] * 255.0 - 128.0]) -} - -/// Neutral a or b as Lab surfaces store it ((0 + 128) / 255). -pub const LAB_NEUTRAL: f32 = 128.0 / 255.0; - -/// An adjustment Photoshop evaluates on a Lab document's own channels, as an operation on one -/// pixel's stored L, a, b (normalised as Lab surfaces store them: L / 100, (a + 128) / 255, -/// (b + 128) / 255) in a document of `depth`: Invert and Posterize (each channel), Threshold -/// (split on L, neutral result), Brightness/Contrast (L) and Levels or Curves with Lab records. -/// `None` for any other adjustment. On the stored values colours outside the display gamut keep -/// theirs, where [`apply_in`] can only round-trip them through clipped display RGB. -pub fn lab_stored_op(adj: &Adjustment, depth: Option) -> Option> { - let op: LabOp<'_> = match adj { - Adjustment::Invert | Adjustment::Posterize { .. } => Box::new(move |ch: &mut [f32; 3]| stored_channels(adj, ColorMode::Lab, depth, ch)), - Adjustment::Threshold { level } => { - // Split on L on the 8-bit grid, like the display path (`apply_lab`). - let t = (level * 255.0).round(); - Box::new(move |ch: &mut [f32; 3]| { - let white = (ch[0].clamp(0.0, 1.0) * 255.0).round() >= t; - *ch = [if white { 1.0 } else { 0.0 }, LAB_NEUTRAL, LAB_NEUTRAL]; - }) - } - Adjustment::BrightnessContrast { brightness, contrast, legacy } => { - let (b, c, legacy) = (*brightness, *contrast, *legacy); - let legacy_curve = legacy_brightness_contrast(b, c); - Box::new(move |ch: &mut [f32; 3]| { - ch[0] = if legacy { legacy_curve(ch[0]) } else { modern_contrast(modern_brightness(ch[0], b), c).clamp(0.0, 1.0) }; - }) - } - Adjustment::Levels { space: ToneSpace::Lab, .. } | Adjustment::Curves { space: ToneSpace::Lab, .. } => { - let luts = tone_luts_depth(adj, depth); - Box::new(move |ch: &mut [f32; 3]| { - for (v, t) in ch.iter_mut().zip(&luts) { - *v = lut(t, *v); - } - }) - } - _ => return None, - }; - Some(op) -} - -/// One pixel's stored L, a, b through an adjustment ([`lab_stored_op`]). -pub type LabOp<'a> = Box; - -/// The Lab evaluation of a [`lab_channel_adjustment`] in a document of `depth` (no-op for any -/// other adjustment). -fn apply_lab(adj: &Adjustment, buf: &mut Buffer, depth: Option) { - match adj { - // L → 100 - L and a, b mirrored about neutral; each channel posterized (see `stored_channels`). - Adjustment::Invert | Adjustment::Posterize { .. } => map_rgb(buf, |c| { - let mut n = lab_norm(c); - stored_channels(adj, ColorMode::Lab, depth, &mut n); - lab_denorm(n) - }), - Adjustment::Threshold { level } => { - // Split on L alone (on the 8-bit grid); the result is neutral black or white. - let t = (level * 255.0).round(); - map_rgb(buf, |c| [if (lab_norm(c)[0].clamp(0.0, 1.0) * 255.0).round() >= t { 1.0 } else { 0.0 }; 3]) - } - Adjustment::BrightnessContrast { brightness, contrast, legacy } => { - let legacy_curve = legacy_brightness_contrast(*brightness, *contrast); - let modern = (!*legacy).then(|| modern_lut(*brightness, *contrast)); - let curve = |v: f32| match &modern { - Some(table) => lut(table, v), - None => legacy_curve(v), - }; - // The tone curve on L only. Added as the difference of two round trips (like - // `tone_in_space`) so a and b, and colours a round trip moves, stay put. - map_rgb(buf, |c| { - let n = lab_norm(c); - let l = curve(n[0]); - if l == n[0] { - return c; - } - let (before, after) = (lab_denorm(n), lab_denorm([l, n[1], n[2]])); - std::array::from_fn(|i| (c[i] + after[i] - before[i]).clamp(0.0, 1.0)) - }) - } - Adjustment::GradientMap { stops, reverse, dither } => { - let (w, x0, y0) = (buf.rect.width().max(1) as usize, buf.rect.x0, buf.rect.y0); - for (i, p) in buf.px.iter_mut().enumerate() { - if p[3] <= 0.0 { - continue; - } - // Driven by L: equal lightness maps to the same stop colour whatever the chroma. - let l = lab_norm([p[0], p[1], p[2]])[0].clamp(0.0, 1.0); - let mut o = gradient(stops, if *reverse { 1.0 - l } else { l }); - if *dither { - let d = bayer4(x0 + (i % w) as i32, y0 + (i / w) as i32) / 255.0; - o = o.map(|v| (v + d).clamp(0.0, 1.0)); - } - p[..3].copy_from_slice(&o); - } - } - _ => {} - } -} - -/// Float RGB curve channels with no edit must preserve samples outside the LUT domain; edited -/// ones extend past it (see [`float_tone_extrapolates`]). -pub fn float_tone_identity(adj: &Adjustment, depth: Option) -> [bool; 3] { - match adj { - Adjustment::Curves { master, per_channel, space: ToneSpace::Rgb, .. } if depth == Some(SampleType::F32) => { - std::array::from_fn(|i| photocraft_doc::adjust::is_identity_curve(master) && photocraft_doc::adjust::is_identity_curve(&per_channel[i])) - } - _ => [false; 3], - } -} - -/// Whether an edited Curves adjustment continues past 0..1 instead of clipping: in a 32-bit RGB -/// document Photoshop extends each curve beyond its end points along the slope of its end -/// segments (#7157: `[[0,0],[255,128]]` maps -0.5 to -0.250980407 and 2 to 1.003921628). Only -/// in RGB documents: the curve's space is not the document's, and other modes keep the table. -pub fn float_tone_extrapolates(adj: &Adjustment, depth: Option, mode: ColorMode) -> bool { - matches!(adj, Adjustment::Curves { space: ToneSpace::Rgb, .. }) && depth == Some(SampleType::F32) && mode == ColorMode::Rgb -} - -pub(crate) fn apply_tone(buf: &mut Buffer, space: ToneSpace, luts: &[Vec; 4], identity: [bool; 3], extrapolate: bool) { - let sample = if extrapolate { lut_extended } else { lut }; - match space { - ToneSpace::Rgb => map_rgb(buf, |c| std::array::from_fn(|i| if identity[i] { c[i] } else { sample(&luts[i], c[i]) })), - ToneSpace::Cmyk | ToneSpace::Lab => map_rgb(buf, |c| tone_in_space(space, luts, c)), - } -} - -/// Per-channel LUTs of a Levels or Curves adjustment: each channel's record first, then the -/// master (composite) record, as Photoshop does (psd-tools levels_rgb.psd and curves_rgb.psd, -/// #975). Four rows: the three `per_channel` channels then black -/// (identity unless the space is CMYK). In Lab there is no composite record, so the master is ignored. -pub fn tone_luts(adj: &Adjustment) -> [Vec; 4] { - tone_luts_q(adj, None) -} - -/// [`tone_luts`] for samples with `quantum` steps per unit (Levels works on whole levels; see -/// [`levels_q`]). -pub fn tone_luts_q(adj: &Adjustment, quantum: Option) -> [Vec; 4] { - let x = |k: usize| k as f32 / (LUT_SIZE - 1) as f32; - match adj { - Adjustment::Levels { master, per_channel, space, black } => { - let ident = LevelsChannel::default(); - let m = if *space == ToneSpace::Lab { &ident } else { master }; - let row = |c: &LevelsChannel| (0..LUT_SIZE).map(|k| levels_q(m, levels_q(c, x(k), quantum), quantum)).collect(); - [row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), row(if *space == ToneSpace::Cmyk { black } else { &ident })] - } - Adjustment::Curves { master, per_channel, space, black, pencil } => { - let m = if *space == ToneSpace::Lab { curve_lut(&[]) } else { curve_lut_mode(master, *pencil) }; - let row = |c: &[CurvePoint]| curve_lut_mode(c, *pencil).iter().map(|&v| lut(&m, v)).collect(); - [row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), row(if *space == ToneSpace::Cmyk { black } else { &[] })] - } - _ => std::array::from_fn(|_| (0..LUT_SIZE).map(x).collect()), - } -} - -/// [`tone_luts_q`] in a document of `depth` (`None`: unrounded). 32-bit Levels use -/// [`levels_float`], sampled on 0..1 and kept in 0..1 for LUT consumers. Float RGB rendering -/// evaluates the formula directly instead, so samples and results outside that domain survive. -pub fn tone_luts_depth(adj: &Adjustment, depth: Option) -> [Vec; 4] { - match (adj, depth) { - (Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, .. }, Some(SampleType::F32)) => { - let x = |k: usize| k as f32 / (LUT_SIZE - 1) as f32; - let row = |c: &LevelsChannel| (0..LUT_SIZE).map(|k| levels_float(master, levels_float(c, x(k))).clamp(0.0, 1.0)).collect(); - [row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), (0..LUT_SIZE).map(x).collect()] - } - _ => tone_luts_q(adj, depth.and_then(crate::adjustment_quantum)), - } -} - -/// Applies channel LUTs to a display-RGB colour in CMYK (ink brightness, 1 - ink) or Lab space, -/// through the conversions the document's surfaces use. The change is added as a difference of -/// two round trips, so channels a curve leaves alone (and out-of-gamut colours) stay exact. -fn tone_in_space(space: ToneSpace, luts: &[Vec; 4], c: [f32; 3]) -> [f32; 3] { - use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk}; - let (before, after) = match space { - ToneSpace::Cmyk => { - let ink = rgb_to_cmyk(c); - let out: [f32; 4] = std::array::from_fn(|i| 1.0 - lut(&luts[i], 1.0 - ink[i])); - if out == ink { - return c; - } - (cmyk_to_rgb(ink), cmyk_to_rgb(out)) - } - ToneSpace::Lab => { - let l = srgb_to_lab(c); - let n = [l[0] / 100.0, (l[1] + 128.0) / 255.0, (l[2] + 128.0) / 255.0]; - let o: [f32; 3] = std::array::from_fn(|i| lut(&luts[i], n[i])); - if o == n { - return c; - } - let back = |v: [f32; 3]| lab_to_srgb([v[0] * 100.0, v[1] * 255.0 - 128.0, v[2] * 255.0 - 128.0]); - (back(n), back(o)) - } - ToneSpace::Rgb => return std::array::from_fn(|i| lut(&luts[i], c[i])), - }; - std::array::from_fn(|i| (c[i] + after[i] - before[i]).clamp(0.0, 1.0)) -} - -/// Hue/Saturation's range edits as three hue-indexed tables (hue shift in degrees, saturation and -/// lightness as fractions), sampled at hue `k / (len - 1)` turns. Ranges add up where they overlap. -pub fn hue_range_tables(ranges: &[HueRange; 6]) -> [Vec; 3] { - let at = |k: usize| { - let deg = k as f32 / (LUT_SIZE - 1) as f32 * 360.0; - ranges.iter().filter(|r| !r.is_neutral()).fold([0.0f32; 3], |acc, r| { - let w = r.weight(deg); - [acc[0] + w * r.hue, acc[1] + w * r.saturation / 100.0, acc[2] + w * r.lightness / 100.0] - }) - }; - let rows: Vec<[f32; 3]> = (0..LUT_SIZE).map(at).collect(); - std::array::from_fn(|i| rows.iter().map(|r| r[i]).collect()) -} - -/// Hue/Saturation's saturation `s` (-1..1) as [`hue_saturation`] takes it in a document of -/// `depth`. A 32-bit Colorize builds its colour with the saturation times `1 - |lightness|`: -/// the photoshop corpus's rgb32 hue-saturation-colorize.psd (Saturation 40, Lightness +5) has 0.95 -/// of the chroma at every lightness, and is exact so, where 8 and 16 bits keep the full saturation -/// (their oracles are exact without it). Only a raised Lightness is measured; a lowered one is -/// taken to scale the same way. -pub fn colorize_saturation(s: f32, lightness: f32, colorize: bool, depth: Option) -> f32 { - // Clamped here too: a PSD can store a saturation beyond ±100, and the GPU scales it unclamped. - if colorize && depth == Some(SampleType::F32) { s.clamp(-1.0, 1.0) * (1.0 - lightness.abs().min(1.0)) } else { s } -} - -/// One Hue/Saturation evaluation: hue shift in degrees, saturation and lightness in -1..=1. -/// Colorize sets the hue and saturation instead of shifting them; at 0% it leaves only the -/// lightness, as in Photoshop (#2326). Ticking Colorize in the dialog starts saturation at 25%. -pub fn hue_saturation(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool) -> [f32; 3] { - hue_saturation_in(c, hue, s, l, colorize, None) -} - -/// [`hue_saturation`] in a document of `depth`. At 32 bits Photoshop doesn't clip the raised -/// saturation, so saturated colours leave 0..1 (red with Hue +40, Saturation +25, Lightness -10 -/// becomes (1.0477, 0.649, -0.1477)), and it scales each colour's chroma around its lightness by -/// [`hdr_saturation_factor`], so colours at or above lightness 1 keep their hue too: the photoshop -/// corpus's rgb32 hue-saturation.psd is exact so. -pub fn hue_saturation_in(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool, depth: Option) -> [f32; 3] { - let hdr = depth == Some(SampleType::F32); - let lighten = |v: f32| if l > 0.0 { v + (1.0 - v) * l } else { v * (1.0 + l) }; - if colorize { - // Colorize builds the colour at the lightened (or darkened) lightness, so black with - // Lightness +30 becomes a 30 % lightness colour, not grey (measured in Photoshop 27.11). - let (_, _, ll) = rgb_to_hsl(c); - return hsl_to_rgb(hue.rem_euclid(360.0) / 360.0, s.abs().min(1.0), lighten(ll)); - } - // Photoshop applies Lightness first, then rotates the hue and scales the saturation of the - // result: Hue +40, Saturation +25, Lightness -10 turns (240, 160, 30) into (173, 243, 0), not - // (168, 230, 14) (Photoshop 27.11 corpus file adjustments/rgb8/hue-saturation). - let lc = c.map(lighten); - let (hh, ss, ll) = rgb_to_hsl(lc); - let hh = (hh + hue / 360.0).rem_euclid(1.0); - if hdr { - // The chroma, not the HSL saturation, whose `2 - max - min` divisor is 0 at lightness 1 - // and negative above it: (2, 0, 0) with Hue +40 becomes (2, 1.333, 0) in Photoshop. - let d = (lc[0].max(lc[1]).max(lc[2]) - lc[0].min(lc[1]).min(lc[2])) * hdr_saturation_factor(s); - return hue_rgb(hh, ll - d / 2.0, ll + d / 2.0); - } - // Raising saturation divides by 1 - s, lowering it multiplies by 1 + s: +50 % doubles it - // (measured in Photoshop 27.11); +100 % saturates any colour that has some. - let ss = if s > 0.0 { ss / (1.0 - s).max(1.0 / 512.0) } else { ss * (1.0 + s) }.clamp(0.0, 1.0); - hsl_to_rgb(hh, ss, ll) -} - -/// The factor 32-bit Hue/Saturation scales chroma by for saturation `s` (-1..1), as Photoshop -/// computes it (measured at every whole percent from -100 to +100 on a 32-bit document): lowering -/// cuts `s` to 1/256 steps, raising cuts it to 254 steps out of 255, takes 255 / (255 - steps) to -/// 1/256 and stops at 32767/256, so +25 % gives 340/256, +99 % 63.75 and +100 % 127.996. -/// compose.wgsl's Hue/Saturation does the same in whole numbers. -pub fn hdr_saturation_factor(s: f32) -> f32 { - // The 1e-4 keeps a master plus range sum on its step: -0.46 + 0.96 is 0.49999997 in f32. - let s = s.clamp(-1.0, 1.0); - if s <= 0.0 { - return 1.0 - (-s * 256.0 + 1e-4).floor() / 256.0; - } - let steps = (s * 254.0 + 1e-4).floor() as u32; - (65280 / 255u32.saturating_sub(steps).max(1)).min(32767) as f32 / 256.0 -} - -/// A colour range's Lightness, applied after the master edits. It moves each channel towards the -/// pixel's brightest channel when raised and towards its darkest when lowered, not towards white -/// or black: Blues +50 turns (0, 29, 115) into (57, 71, 115), Blues -50 turns (102, 128, 204) into -/// (102, 115, 153) (measured in Photoshop 27.11). -pub fn range_lightness(c: [f32; 3], l: f32) -> [f32; 3] { - let l = l.clamp(-1.0, 1.0); - let target = if l > 0.0 { c[0].max(c[1]).max(c[2]) } else { c[0].min(c[1]).min(c[2]) }; - c.map(|v| v + (target - v) * l.abs()) -} - -/// Black & White grey value. Each colour is the sum of a grey part (its smallest channel), a -/// secondary-colour part (yellow, cyan or magenta: middle − smallest) and a primary part (red, -/// green or blue: largest − middle); the sliders (percent, Photoshop defaults 40 60 40 60 20 80 for -/// reds, yellows, greens, cyans, blues, magentas) weight the two colour parts. Unclipped: the -/// document's depth decides the range. -pub fn black_white_gray(c: [f32; 3], weights: &[f32; 6]) -> f32 { - let (r, g, b) = (c[0], c[1], c[2]); - let (max, min) = (r.max(g).max(b), r.min(g).min(b)); - let mid = r + g + b - max - min; - // Primary: the largest channel; secondary: the two largest channels together. - let primary = if r >= g && r >= b { - 0 - } else if g >= b { - 2 - } else { - 4 - }; - let secondary = if b <= r && b <= g { - 1 // red + green = yellow - } else if r <= g { - 3 // green + blue = cyan - } else { - 5 // red + blue = magenta - }; - min + (mid - min) * weights[secondary] / 100.0 + (max - mid) * weights[primary] / 100.0 -} - -/// Ordered-dither offset in -0.5..0.5 (4×4 Bayer matrix) for document pixel (x, y). -pub fn bayer4(x: i32, y: i32) -> f32 { - const M: [f32; 16] = [0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0]; - (M[((y & 3) * 4 + (x & 3)) as usize] + 0.5) / 16.0 - 0.5 -} - -/// Samples a 3D LUT (`n`³ RGB triplets, red fastest) at `c`, trilinear or tetrahedral. -pub fn lut3d_sample(lut: &[f32], n: usize, c: [f32; 3], tetrahedral: bool) -> [f32; 3] { - // A degenerate or short table can't be sampled: leave the colour alone. - if n < 2 || n.checked_pow(3).and_then(|c| c.checked_mul(3)).is_none_or(|len| lut.len() < len) { - return c; - } - let m = (n - 1) as f32; - let pos = c.map(|v| v.clamp(0.0, 1.0) * m); - let i0 = pos.map(|p| (p.floor() as usize).min(n - 2)); - let f: [f32; 3] = std::array::from_fn(|k| pos[k] - i0[k] as f32); - let at = |dr: usize, dg: usize, db: usize| -> [f32; 3] { - let idx = (((i0[2] + db) * n + i0[1] + dg) * n + i0[0] + dr) * 3; - [lut[idx], lut[idx + 1], lut[idx + 2]] - }; - let mix = |w: &[(f32, [f32; 3])]| -> [f32; 3] { std::array::from_fn(|k| w.iter().map(|(a, v)| a * v[k]).sum()) }; - let (fr, fg, fb) = (f[0], f[1], f[2]); - if tetrahedral { - let (c000, c111) = (at(0, 0, 0), at(1, 1, 1)); - if fr > fg { - if fg > fb { - mix(&[(1.0 - fr, c000), (fr - fg, at(1, 0, 0)), (fg - fb, at(1, 1, 0)), (fb, c111)]) - } else if fr > fb { - mix(&[(1.0 - fr, c000), (fr - fb, at(1, 0, 0)), (fb - fg, at(1, 0, 1)), (fg, c111)]) - } else { - mix(&[(1.0 - fb, c000), (fb - fr, at(0, 0, 1)), (fr - fg, at(1, 0, 1)), (fg, c111)]) - } - } else if fb > fg { - mix(&[(1.0 - fb, c000), (fb - fg, at(0, 0, 1)), (fg - fr, at(0, 1, 1)), (fr, c111)]) - } else if fb > fr { - mix(&[(1.0 - fg, c000), (fg - fb, at(0, 1, 0)), (fb - fr, at(0, 1, 1)), (fr, c111)]) - } else { - mix(&[(1.0 - fg, c000), (fg - fr, at(0, 1, 0)), (fr - fb, at(1, 1, 0)), (fb, c111)]) - } - } else { - let lerp = |a: [f32; 3], b: [f32; 3], t: f32| -> [f32; 3] { std::array::from_fn(|k| a[k] + (b[k] - a[k]) * t) }; - let c00 = lerp(at(0, 0, 0), at(1, 0, 0), fr); - let c10 = lerp(at(0, 1, 0), at(1, 1, 0), fr); - let c01 = lerp(at(0, 0, 1), at(1, 0, 1), fr); - let c11 = lerp(at(0, 1, 1), at(1, 1, 1), fr); - lerp(lerp(c00, c10, fg), lerp(c01, c11, fg), fb) - } -} - -/// Color Balance on channel `ch` (0 red, 1 green, 2 blue) of `v` (0..1); `tones` are the -/// shadows, midtones and highlights slider triples (cyan–red, magenta–green, yellow–blue, -/// −100..100). -/// -/// Reverse-engineered from Photoshop (a 16-bit gray ramp through every tone at ±10..±100, pairs of -/// tones, and random settings of all nine sliders, Preserve Luminosity on and off): the three -/// tones fold into one Levels per channel (input black point, input white point, midtone gamma), -/// within 0.8 of 255 everywhere. Folding matters: a lowered shadows and a raised highlights -/// slider cancel each other's gamma, which applying the tones one after another doesn't (#3423). -/// - Preserve Luminosity off: a slider only moves its own channel. Lowered shadows set the black -/// point to |shadows| levels, raised highlights set the white point to 255 − highlights levels, -/// and the gamma is 2^(m / 100) with m = midtones + (shadows + highlights) / 2. -/// - Preserve Luminosity on: each channel's black point is (max − own) shadows levels, its white -/// point 255 − (own − min) highlights levels, and m = own − (max + min) / 2 midtones. -/// -/// A gamma > 1 starts with slope 2^gamma at black (up to 18 of 255 brighter -/// near black without it). When the black point reaches the white point, input -/// at or above the white point is white and the rest black. -pub fn color_balance_channel(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize, v: f32) -> f32 { - BalanceCurve::new(tones, preserve_luminosity, ch).eval(v) -} - -/// One channel's Color Balance curve (see [`color_balance_channel`]), with the terms that don't -/// depend on the sample worked out once rather than per pixel. -pub struct BalanceCurve { - /// Input black and white points. - b: f32, - w: f32, - /// The power curve's exponent, 1 / gamma. - e: f32, - /// The Hermite join of a gamma > 1. - knee: Option, -} - -/// Where a gamma > 1 curve's Hermite join ends (`u0`), its starting slope 2^gamma (`s0`), and the -/// power curve's value (`p`) and slope (`d`) at `u0`. -#[derive(Clone, Copy)] -struct Knee { - u0: f32, - s0: f32, - p: f32, - d: f32, -} - -impl BalanceCurve { - /// The red, green and blue curves. - pub fn rgb(tones: [[f32; 3]; 3], preserve_luminosity: bool) -> [Self; 3] { - std::array::from_fn(|ch| Self::new(tones, preserve_luminosity, ch)) - } - - /// The curve of channel `ch` (0 red, 1 green, 2 blue) for the shadows, midtones and - /// highlights slider triples `tones`. - pub fn new(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize) -> Self { - let [shadows, midtones, highlights] = tones.map(|t| t.map(|s| if s.is_finite() { s.clamp(-100.0, 100.0) } else { 0.0 })); - let own = |t: [f32; 3]| t.get(ch).copied().unwrap_or(0.0); - let max = |t: [f32; 3]| t[0].max(t[1]).max(t[2]); - let min = |t: [f32; 3]| t[0].min(t[1]).min(t[2]); - let (black, white, m) = if preserve_luminosity { - (max(shadows) - own(shadows), own(highlights) - min(highlights), own(midtones) - (max(midtones) + min(midtones)) / 2.0) - } else { - ((-own(shadows)).max(0.0), own(highlights).max(0.0), own(midtones) + (own(shadows) + own(highlights)) / 2.0) - }; - // The midtone gamma of the channel's Levels: `u^(1/gamma)`, except that a gamma > 1 - // (which would start with infinite slope) starts at slope 2^gamma and joins the power - // curve in a cubic Hermite at twice the input where that line meets it (Photoshop, - // measured on a 16-bit ramp at gamma 1.07..2: within 0.02 of 255). - let gamma = 2f32.powf(m / 100.0); - let e = 1.0 / gamma.max(0.01); - let knee = if gamma > 1.0 { - let s0 = 2f32.powf(gamma); - let u0 = (2.0 * s0.powf(1.0 / (e - 1.0))).min(1.0); - (!u0.is_nan() && u0 > 0.0).then(|| Knee { u0, s0, p: u0.powf(e), d: e * u0.powf(e - 1.0) }) - } else { - None - }; - Self { b: black / 255.0, w: 1.0 - white / 255.0, e, knee } - } - - /// The curve at `v` (0..1). - pub fn eval(&self, v: f32) -> f32 { - let (b, w) = (self.b, self.w); - let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; - if v >= w { - return 1.0; - } - if v <= b { - return 0.0; - } - let u = (v - b) / (w - b); - match self.knee { - Some(Knee { u0, s0, p, d }) if u < u0 => { - let t = u / u0; - let (t2, t3) = (t * t, t * t * t); - ((t3 - 2.0 * t2 + t) * u0 * s0 + (3.0 * t2 - 2.0 * t3) * p + (t3 - t2) * u0 * d).clamp(0.0, 1.0) - } - _ => u.powf(self.e), - } - } -} - -/// How much a colour belongs to each Selective Color range: reds, yellows, greens, cyans, -/// blues, magentas (by chroma within the hue sector), whites, neutrals and blacks (by lightness). -pub fn selective_color_weights(c: [f32; 3]) -> [f32; 9] { - let max = c[0].max(c[1]).max(c[2]); - let min = c[0].min(c[1]).min(c[2]); - let mid = c[0] + c[1] + c[2] - max - min; - let top = |i: usize| if c[i] >= max { max - mid } else { 0.0 }; - let bottom = |i: usize| if c[i] <= min { mid - min } else { 0.0 }; - [ - top(0), - bottom(2), - top(1), - bottom(0), - top(2), - bottom(1), - ((min - 0.5) * 2.0).max(0.0), - (1.0 - (max - 0.5).abs() - (min - 0.5).abs()).clamp(0.0, 1.0), - ((0.5 - max) * 2.0).max(0.0), - ] -} - -/// Photoshop Selective Color: each range shifts the cyan, magenta and yellow ink (1 − R, G, B) by -/// its percentage, plus its black percentage on every ink, weighted by how much the colour belongs -/// to the range. Relative mode scales the shift by the ink already present (so it can't tint pure -/// white). Absolute mode scales it by the room the ink has: adding ink by min(1, 2 × (1 − ink)), -/// removing it by min(1, 2 × ink), so Neutrals Cyan +50 darkens red 64 by 32, not 64 (all 72 -/// absolute range × ink cases within 1 level of Photoshop 27.11). -pub fn selective_color(c: [f32; 3], relative: bool, adj: &[[f32; 4]; 9]) -> [f32; 3] { - let w = selective_color_weights(c); - let mut delta = [0.0f32; 3]; - for (r, wr) in w.iter().enumerate() { - if *wr <= 0.0 { - continue; - } - let a = adj[r].map(|v| v / 100.0); - for i in 0..3 { - let ink = 1.0 - c[i]; - let d = a[i] + a[3]; - let d = if relative { - d * ink - } else if d > 0.0 { - d * (2.0 * (1.0 - ink)).min(1.0) - } else { - d * (2.0 * ink).min(1.0) - }; - delta[i] += d * wr; - } - } - std::array::from_fn(|i| (c[i] - delta[i]).clamp(0.0, 1.0)) -} - -const LUT_SIZE: usize = 4096; - -fn map_rgb(buf: &mut Buffer, f: impl Fn([f32; 3]) -> [f32; 3]) { - for p in &mut buf.px { - if p[3] <= 0.0 { - continue; - } - let r = f([p[0], p[1], p[2]]); - p[0] = r[0]; - p[1] = r[1]; - p[2] = r[2]; - } -} - -#[inline] -fn lut(table: &[f32], v: f32) -> f32 { - let x = v.clamp(0.0, 1.0) * (table.len() - 1) as f32; - // Never negative (NaN casts to 0, as its floor did), so truncating is `floor`, without the - // libm call baseline x86-64 (no SSE4.1) makes for it. - let i = x as usize; - let j = (i + 1).min(table.len() - 1); - let f = x - i as f32; - table[i] * (1.0 - f) + table[j] * f -} - -/// Table steps the end slopes of [`lut_extended`] are measured over: one step's difference near -/// 0.5 carries f32 rounding (2e-4 of the slope), while 16 steps are still only 0.4 % of the domain. -pub const TONE_SLOPE_SPAN: usize = 16; - -/// [`lut`] continued past 0..1 along the slope of the table's end segments, as Photoshop applies -/// a curve to float samples ([`float_tone_extrapolates`]). Inside the domain it is [`lut`]; -/// non-finite samples stay with it too, so an infinite one can't become NaN on a flat end. -#[inline] -fn lut_extended(table: &[f32], v: f32) -> f32 { - let n = table.len(); - if !v.is_finite() || (0.0..=1.0).contains(&v) || n < 2 { - return lut(table, v); - } - let k = TONE_SLOPE_SPAN.min(n - 1); - let per_unit = (n - 1) as f32 / k as f32; - if v < 0.0 { table[0] + v * (table[k] - table[0]) * per_unit } else { table[n - 1] + (v - 1.0) * (table[n - 1] - table[n - 1 - k]) * per_unit } -} - -/// Photo Filter's linear-light RGB matrix. Photoshop multiplies the pixel's D50 XYZ, relative to -/// white, by the filter colour's (mixed in by `density`): a fixed linear map, so it is folded into -/// one matrix. With `normalize_y` the map keeps luminance Y (32-bit Preserve Luminosity; 8/16-bit -/// documents instead restore the encoded luminosity like the Luminosity blend mode). Fitted on the -/// photoshop corpus `photo-filter.psd`: rgb16 within 0.6/255 everywhere. -pub fn photo_filter_matrix(color: [f32; 3], density: f32, normalize_y: bool) -> [[f32; 3]; 3] { - let d = if density.is_finite() { density.clamp(0.0, 1.0) } else { 0.0 }; - let xyz = mat3_mul(&SRGB_TO_XYZ_D50, color.map(|v| srgb_to_linear(v.clamp(0.0, 1.0)))); - let mut s: [f32; 3] = std::array::from_fn(|i| 1.0 - d + d * xyz[i] / D50[i]); - if normalize_y && s[1] > 1e-6 { - let y = s[1]; - s = s.map(|v| v / y); - } - // XYZ_D50_TO_SRGB · diag(s) · SRGB_TO_XYZ_D50 - std::array::from_fn(|r| std::array::from_fn(|c| (0..3).map(|k| XYZ_D50_TO_SRGB[r][k] * s[k] * SRGB_TO_XYZ_D50[k][c]).sum())) -} - -/// Photoshop's Vibrance on one pixel (`v`, `s`: the sliders / 100; `hi`: the sample ceiling). -/// -/// Measured black-box against Photoshop 25.4 on 7,400-colour charts (8- and 16-bit; sRGB, Adobe RGB -/// and ProPhoto documents). Both sliders work in linear light through the document's tone curve, -/// Vibrance first, then Saturation: -/// - Saturation moves each colour away from (or towards) the grey `0.288 R + 0.712 G` (blue has no -/// weight, in every profile) by `1 + s`, clipping each channel: within 0.07/255 at every `s`. -/// - Vibrance is an HSV change in linear light that keeps the hue: see [`vibrance_lin`]. -pub fn vibrance_px(c: [f32; 3], v: f32, s: f32, transfer: Transfer, hi: f32) -> [f32; 3] { - let mut l = c.map(|x| transfer.decode(x)); - if v != 0.0 { - l = vibrance_lin(l, v); - } - if s != 0.0 { - let g = VIBRANCE_GREY[0] * l[0] + VIBRANCE_GREY[1] * l[1]; - l = l.map(|x| (g + (1.0 + s) * (x - g)).clamp(0.0, hi)); - } - l.map(|x| transfer.encode(x.clamp(0.0, hi))) -} - -/// Weights of the grey Photoshop's Vibrance › Saturation desaturates to (R, G; blue has none). -pub const VIBRANCE_GREY: [f32; 2] = [0.288, 0.712]; - -/// Positive Vibrance's saturation boost, fitted to the measurements (see [`vibrance_lin`]). -pub const VIBRANCE_BOOST: [f32; 7] = [0.5001, 0.0887, 0.4374, 0.7573, -0.8113, 0.5154, 2.8026]; - -/// The Vibrance slider (`v` in [-1, 1]) on a linear-light pixel. With `t = 1 - min/max` (HSV -/// saturation) and `V = max`: -/// - below 0 (`a = -v`): `t' = t (1 - a/4) (1 - a + a t (1 + t) / 2)` and -/// `V' = V - a t (1 - t) (2 - t + t²) V (1 - V)`; exact (0.2/255 mean) except in the deepest -/// shadows (`V` under 0.05), which Photoshop desaturates less. -/// - above 0: `V' = V + v/4 t (1 - t) (2 - t + t²) V (1 - V)` (exact) and a saturation boost that -/// grows as `t` and `V` fall, damped on reds and skin (HSV hue 0–30°, fading out by 45° and in -/// from 300°): a fit, 0.4 (+10) to 5 (+100) /255 off on average. -pub fn vibrance_lin(c: [f32; 3], v: f32) -> [f32; 3] { - let mx = c[0].max(c[1]).max(c[2]); - let mn = c[0].min(c[1]).min(c[2]); - if mx <= 0.0 || mx - mn <= 1e-9 { - return c; - } - let t = 1.0 - mn / mx; - let shape = t * (1.0 - t) * (2.0 - t + t * t) * mx * (1.0 - mx).max(0.0); - let (t2, v2) = if v < 0.0 { - let a = -v; - (t * (1.0 - a / 4.0) * (1.0 - a + a * t * (1.0 + t) / 2.0), mx - a * shape) - } else { - let [c0, c1, p, q, r0, ra, rt] = VIBRANCE_BOOST; - let w = vibrance_skin(hsv_hue(c, mx, mn)); - let a = v * (1.0 - w) + 0.64 * v.powf(1.6) * w; - let boost = (c0 * a + c1 * a * a) * t.powf(p) * (1.0 - t).powf(q) * ((r0 + ra * a + rt * (1.0 - t)) * (1.0 - mx).max(0.0)).exp(); - ((t * (1.0 + boost)).min(1.0), mx + v / 4.0 * shape) - }; - let m2 = v2 * (1.0 - t2); - let k = (v2 - m2) / (mx - mn); - c.map(|x| m2 + (x - mn) * k) -} - -/// How much positive Vibrance treats a hue (degrees) as skin: 1 on 0–30°, fading to 0 by 45° and -/// in again from 300°. -fn vibrance_skin(h: f32) -> f32 { - if h <= 30.0 { - 1.0 - } else if h < 45.0 { - (45.0 - h) / 15.0 - } else if h < 300.0 { - 0.0 - } else { - (h - 300.0) / 60.0 - } -} - -/// HSV hue in degrees of `c` (its max `mx` and min `mn` given, `mx > mn`). -fn hsv_hue(c: [f32; 3], mx: f32, mn: f32) -> f32 { - let d = mx - mn; - let h = if mx == c[0] { - ((c[1] - c[2]) / d).rem_euclid(6.0) - } else if mx == c[1] { - (c[2] - c[0]) / d + 2.0 - } else { - (c[0] - c[1]) / d + 4.0 - }; - h * 60.0 -} - -/// Modern Brightness curve (one channel, `brightness` in [-150, 150]); pins pure black and white, -/// and `b = 0` is the identity. Raised, it is a line of slope `s = 1.375^(b/50)` from the origin -/// up to a knee at output 126/255, then a cubic Hermite to (1, 1) whose end slope is -/// `1 / (1 + 0.084 b)`; past about +110, where no such cubic stays below white, the roll-off is -/// `1 - (1 - y0)(1 - u)^α` instead (continuous slope `α` at the knee, flat at white). Lowered, it -/// is the inverse of the curve raised by as much. -/// -/// Fit to every Photoshop measurement we have, all within about a level and a half: its ±50 -/// samples (`modern_brightness_matches_photoshop`), the photoshop corpus's brightness-contrast.psd -/// (+25 with contrast +30) and psd-tools' brightnesscontrast_rgb.psd, whose masked layers give -/// +23, -31 and -95 (+150 within 6 levels there, where every curve family tried bottoms out). -pub fn modern_brightness(v: f32, brightness: f32) -> f32 { - if brightness == 0.0 || !brightness.is_finite() { - return v; - } - Brightness::new(brightness).eval(v) -} - -/// [`modern_brightness`] for one slider value, its curve's constants worked out once. -struct Brightness { - raise: bool, - s: f32, - e: f32, - x0: f32, - /// The knee's slope over the roll-off's secant (`α` of Fritsch–Carlson); a power roll-off - /// replaces the Hermite when α² + β² > 9. - alpha: f32, - hermite: bool, -} - -/// Output level of the Brightness curve's knee. -const BRIGHTNESS_KNEE: f32 = 126.0 / 255.0; - -impl Brightness { - fn new(brightness: f32) -> Self { - let b = brightness.abs(); - let s = 1.375f32.powf(b / 50.0); - let e = 1.0 / (1.0 + 0.084 * b); - let x0 = (BRIGHTNESS_KNEE / s).min(1.0); - let secant = (1.0 - BRIGHTNESS_KNEE) / (1.0 - x0).max(1e-6); - let (alpha, beta) = (s / secant, e / secant); - Brightness { raise: brightness > 0.0, s, e, x0, alpha, hermite: alpha * alpha + beta * beta <= 9.0 } - } - - fn eval(&self, v: f32) -> f32 { - let v = v.clamp(0.0, 1.0); - if self.raise { - return self.raised(v); - } - if v <= 0.0 || v >= 1.0 { - return v; - } - // The inverse of the raised curve (monotone on [0, 1]), by bisection. - let (mut lo, mut hi) = (0.0f32, 1.0f32); - for _ in 0..32 { - let mid = 0.5 * (lo + hi); - if self.raised(mid) < v { - lo = mid; - } else { - hi = mid; - } - } - 0.5 * (lo + hi) - } - - /// The curve raised: the line, then a monotone roll-off to (1, 1). - fn raised(&self, x: f32) -> f32 { - let Brightness { s, e, x0, alpha, hermite, .. } = *self; - let y0 = BRIGHTNESS_KNEE; - if x <= x0 { - return y0.min(s * x); - } - let h = (1.0 - x0).max(1e-6); - let t = ((x - x0) / h).clamp(0.0, 1.0); - let y = if hermite { - let (t2, t3) = (t * t, t * t * t); - (2.0 * t3 - 3.0 * t2 + 1.0) * y0 + (t3 - 2.0 * t2 + t) * h * s + (-2.0 * t3 + 3.0 * t2) + (t3 - t2) * h * e - } else { - 1.0 - (1.0 - y0) * (1.0 - t).powf(alpha) - }; - y.clamp(0.0, 1.0) - } -} - -/// Modern Brightness/Contrast as one channel's lookup table (4096 samples over 0..1): -/// [`modern_brightness`] then [`modern_contrast`], as Photoshop applies them. -pub fn modern_lut(brightness: f32, contrast: f32) -> Vec { - let step = |k: usize, n: usize| k as f32 / (n - 1) as f32; - let bright: Vec = if brightness == 0.0 || !brightness.is_finite() { - (0..LUT_SIZE).map(|k| step(k, LUT_SIZE)).collect() - } else if brightness > 0.0 { - let curve = Brightness::new(brightness); - (0..LUT_SIZE).map(|k| curve.raised(step(k, LUT_SIZE))).collect() - } else { - // Lowered: invert the raised curve, sampled four times finer, in one monotone pass. - let curve = Brightness::new(-brightness); - let fine = 4 * LUT_SIZE; - let ys: Vec = (0..fine).map(|j| curve.raised(step(j, fine))).collect(); - let mut j = 0; - (0..LUT_SIZE) - .map(|k| { - let y = step(k, LUT_SIZE); - while j + 2 < fine && ys.get(j + 1).is_some_and(|&n| n < y) { - j += 1; - } - let (y0, y1) = (ys.get(j).copied().unwrap_or(0.0), ys.get(j + 1).copied().unwrap_or(1.0)); - let f = if y1 > y0 { ((y - y0) / (y1 - y0)).clamp(0.0, 1.0) } else { 0.0 }; - (step(j, fine) + f / (fine - 1) as f32).clamp(0.0, 1.0) - }) - .collect() - }; - bright.into_iter().map(|b| modern_contrast(b, contrast).clamp(0.0, 1.0)).collect() -} - -/// Modern Contrast curve (one channel, `contrast` in [-50, 100]). A symmetric cubic-Hermite S-curve -/// pivoting at 0.5: endpoint slope `1 - c/128`, centre slope `1 + c/128`. Near-exact vs Photoshop -/// (≤0.5/255). `c = 0` is the identity; pins 0, 0.5 and 1. -pub fn modern_contrast(v: f32, contrast: f32) -> f32 { - if contrast == 0.0 { - return v; - } - let k = contrast / 128.0; - let (end, mid) = (1.0 - k, 1.0 + k); - // Cubic Hermite on [0, 0.5]: pinned (0,0) slope `end`, (0.5,0.5) slope `mid`. `t` in [0,1]. - let half = |t: f32| end * 0.5 * (t * t * t - 2.0 * t * t + t) + (-2.0 * t * t * t + 3.0 * t * t) * 0.5 + mid * 0.5 * (t * t * t - t * t); - let v = v.clamp(0.0, 1.0); - if v <= 0.5 { half(v / 0.5) } else { 1.0 - half((1.0 - v) / 0.5) } -} - -/// Photoshop posterize: `n` equal input bins over 0..=255, output levels -/// `floor(k * 255 / (n - 1))` (exact on the corpus for 3, 7, 13 and 21 levels). -pub fn posterize(v: f32, levels: u32) -> f32 { - let n = levels.clamp(2, 255) as f32; - let x = (v.clamp(0.0, 1.0) * 255.0).round(); - let bin = (x * n / 256.0).floor().min(n - 1.0); - (bin * 255.0 / (n - 1.0)).floor() / 255.0 -} - -/// [`posterize`] in a document of `depth` (`None`: unknown, treated as 8-bit). At 16 bits -/// Photoshop bins the 16-bit sample (`⌊v · n / 32768⌋`) and lands on 8-bit levels through a -/// 16-bit step: `⌊b · 32768 / (n - 1)⌋`, converted with `⌊(o · 255 + 16384) / 32768⌋`, so -/// 127.5 comes out as 128 but 42.5 as 42 (8 bits floor them all). Exact on every sample of -/// psd-tools posterize_16bits_rgb.psd and posterize_16bits_grayscale.psd (levels 2 to 21), -/// which the 8-bit rule missed by up to half the range. -pub fn posterize_in(v: f32, levels: u32, depth: Option) -> f32 { - if depth != Some(SampleType::U16) { - return posterize(v, levels); - } - let n = f64::from(levels.clamp(2, 255)); - let x = (f64::from(v.clamp(0.0, 1.0)) * 32768.0).round(); - let bin = (x * n / 32768.0).floor().min(n - 1.0); - let step = (bin * 32768.0 / (n - 1.0)).floor(); - (((step * 255.0 + 16384.0) / 32768.0).floor() / 255.0) as f32 -} - -pub fn levels(ch: &LevelsChannel, v: f32) -> f32 { - levels_q(ch, v, None) -} - -/// [`levels`] on samples with `quantum` steps per unit (8-bit: 255). Photoshop works on whole -/// levels in three steps, each rounded half up to a whole level: the input-range stretch, the -/// midtone gamma ([`levels_gamma`]) and the output range. So a 44..214 range maps 45, 46, 47, 48 -/// → 1.5, 3, 4.5, 6 → 2, 3, 5, 6 (psd-tools levels_grayscale, where the gamma toe magnifies the -/// steps), and an output range narrower than 0..255 maps neighbouring gamma levels to one level -/// (psd-tools levels_rgb: 43..48 → 58 through a 0.47 channel gamma and the master's 48..255). -/// In a LUT the result is a staircase that is exact at every level. -pub fn levels_q(ch: &LevelsChannel, v: f32, quantum: Option) -> f32 { - let range = (ch.in_white - ch.in_black).max(1e-6); - let quantum = quantum.filter(|q| q.is_finite() && *q >= 1.0); - let whole = |x: f32| match quantum { - Some(q) => (x * q + 0.5).floor() / q, - None => x, - }; - let u = match quantum { - Some(q) => { - let v = (v * q).round() / q; - (((v - ch.in_black) / range).clamp(0.0, 1.0) * q + 0.5 + 1e-3).floor() / q - } - None => ((v - ch.in_black) / range).clamp(0.0, 1.0), - }; - let t = whole(levels_gamma(u, ch.gamma.max(0.01))); - whole(ch.out_black + t * (ch.out_white - ch.out_black)) -} - -/// Exponent of the shadow toe in [`levels_gamma`] (fitted; see there). -const LEVELS_TOE_POWER: f32 = 2.2; - -/// Levels' midtone gamma `g` on `u` in 0..1: `u^(1/g)`, except that above 1, where that power -/// curve is infinitely steep at black, Photoshop starts along a toe `a·u − b·u^q` of slope -/// `a = 2^g` that joins the curve with the same value and slope. `q` = [`LEVELS_TOE_POWER`] is -/// fitted on whole-level oracles at gamma 1.16, 1.22, 1.3, 1.78 and 2.0 (psd-tools levels_rgb -/// and levels_grayscale, the photoshop corpus's rgb8 and gray8 levels.psd, a measured 0..255 -/// ramp): all but 2 of their 1118 levels exact, the others within one. Below 1 the power curve is -/// exact (gamma 0.67 and 0.7: every level). -pub fn levels_gamma(u: f32, g: f32) -> f32 { - let c = 1.0 / g; - if g <= 1.0 { - return u.powf(c); - } - let (a, q) = (2f32.powf(g), LEVELS_TOE_POWER); - // Where the toe meets the curve: a·u1 − b·u1^q = u1^c and a − q·b·u1^(q−1) = c·u1^(c−1). - let u1 = ((1.0 - c / q) / (a * (1.0 - 1.0 / q))).powf(1.0 / (1.0 - c)); - if u >= u1 || u1 <= 0.0 { - return u.powf(c); - } - let b = (a * u1 - u1.powf(c)) / u1.powf(q); - // Just above gamma 1 the toe shrinks to nothing: u1^q underflows to 0 while u1 doesn't, and - // the power curve is the toe's limit there (otherwise b = inf and black turns NaN). - if !b.is_finite() { - return u.powf(c); - } - a * u - b * u.powf(q) -} - -/// [`levels`] in a 32-bit document. Neither the input is clipped to the input range nor the result -/// to the output range there, and the midtone gamma is a plain power curve, mirrored below the -/// black point (the oracle corpus' rgb32 and gray32 levels.psd: within 0.5/255, 10/255 off with -/// the clipped curve). -pub fn levels_float(ch: &LevelsChannel, v: f32) -> f32 { - let t = (v - ch.in_black) / (ch.in_white - ch.in_black).max(1e-6); - let t = if ch.gamma == 1.0 { t } else { t.signum() * t.abs().powf(1.0 / ch.gamma.max(0.01)) }; - ch.out_black + t * (ch.out_white - ch.out_black) -} - -/// The LUT of one Curves curve: [`curve_map_lut`] for a pencil-drawn map, else [`curve_lut`]. -pub fn curve_lut_mode(points: &[CurvePoint], pencil: bool) -> Vec { - if pencil { curve_map_lut(points) } else { curve_lut(points) } -} - -/// A pencil-drawn Curves map (see [`photocraft_doc::adjust::curve_map`]): straight segments -/// between its entries, constant outside the first/last, clamped to 0..=1, sampled into a LUT. -pub fn curve_map_lut(points: &[CurvePoint]) -> Vec { - let mut pts: Vec<(f32, f32)> = points.iter().filter(|p| p.input.is_finite() && p.output.is_finite()).map(|p| (p.input, p.output)).collect(); - pts.sort_by(|a, b| a.0.total_cmp(&b.0)); - pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6); - let ident = |k: usize| k as f32 / (LUT_SIZE - 1) as f32; - let (Some(&first), Some(&last)) = (pts.first(), pts.last()) else { return (0..LUT_SIZE).map(ident).collect() }; - let mut seg = 0; - (0..LUT_SIZE) - .map(|k| { - let xv = ident(k); - if xv <= first.0 { - return first.1.clamp(0.0, 1.0); - } - if xv >= last.0 { - return last.1.clamp(0.0, 1.0); - } - while pts.get(seg + 1).is_some_and(|p| p.0 < xv) { - seg += 1; - } - let (Some(&(x0, y0)), Some(&(x1, y1))) = (pts.get(seg), pts.get(seg + 1)) else { return last.1.clamp(0.0, 1.0) }; - let t = if x1 > x0 { (xv - x0) / (x1 - x0) } else { 0.0 }; - (y0 + (y1 - y0) * t).clamp(0.0, 1.0) - }) - .collect() -} - -/// Photoshop curve: a natural cubic spline through the points (it may -/// overshoot between points, as Photoshop's does), constant outside the -/// first/last point, clamped to 0..=1, sampled into a LUT. -pub fn curve_lut(points: &[CurvePoint]) -> Vec { - let mut pts: Vec<(f32, f32)> = points.iter().map(|p| (p.input, p.output)).collect(); - pts.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); - pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6); - if pts.len() < 2 { - return (0..LUT_SIZE).map(|i| i as f32 / (LUT_SIZE - 1) as f32).collect(); - } - let n = pts.len(); - // Second derivatives of the natural spline (tridiagonal solve). - let mut m2 = vec![0.0f64; n]; - if n > 2 { - let x: Vec = pts.iter().map(|p| f64::from(p.0)).collect(); - let y: Vec = pts.iter().map(|p| f64::from(p.1)).collect(); - let mut c = vec![0.0f64; n]; - let mut d = vec![0.0f64; n]; - for i in 1..n - 1 { - let (h0, h1) = (x[i] - x[i - 1], x[i + 1] - x[i]); - let a = h0 / 6.0; - let b = (h0 + h1) / 3.0; - let cc = h1 / 6.0; - let r = (y[i + 1] - y[i]) / h1 - (y[i] - y[i - 1]) / h0; - let denom = b - a * c[i - 1]; - c[i] = cc / denom; - d[i] = (r - a * d[i - 1]) / denom; - } - for i in (1..n - 1).rev() { - m2[i] = d[i] - c[i] * m2[i + 1]; - } - } - (0..LUT_SIZE) - .map(|k| { - let xv = k as f32 / (LUT_SIZE - 1) as f32; - if xv <= pts[0].0 { - return pts[0].1.clamp(0.0, 1.0); - } - if xv >= pts[n - 1].0 { - return pts[n - 1].1.clamp(0.0, 1.0); - } - let i = pts.windows(2).position(|w| xv <= w[1].0).unwrap_or(n - 2); - let (x0, y0) = (f64::from(pts[i].0), f64::from(pts[i].1)); - let (x1, y1) = (f64::from(pts[i + 1].0), f64::from(pts[i + 1].1)); - let h = x1 - x0; - let t = f64::from(xv); - let a = (x1 - t) / h; - let b = (t - x0) / h; - let y = a * y0 + b * y1 + ((a * a * a - a) * m2[i] + (b * b * b - b) * m2[i + 1]) * h * h / 6.0; - (y as f32).clamp(0.0, 1.0) - }) - .collect() -} - -/// A layer-style contour curve: [`curve_lut`], except that the curve bends sharply at corner -/// points (`corners[i]` true; Photoshop's Contour Editor "Corner"): each run between corners is -/// its own natural spline, so all-corner points make a polyline. Missing flags are smooth. -pub fn contour_curve_lut(points: &[CurvePoint], corners: &[bool]) -> Vec { - let mut pts: Vec<(CurvePoint, bool)> = points.iter().enumerate().map(|(i, p)| (p.clone(), corners.get(i).copied().unwrap_or(false))).collect(); - if !pts.iter().any(|p| p.1) { - return curve_lut(points); - } - pts.sort_by(|a, b| a.0.input.partial_cmp(&b.0.input).unwrap_or(std::cmp::Ordering::Equal)); - pts.dedup_by(|a, b| (a.0.input - b.0.input).abs() < 1e-6); - let mut out: Vec = Vec::new(); - let mut start = 0usize; - let last = pts.len().saturating_sub(1); - for i in 1..=last { - let corner = pts.get(i).is_some_and(|p| p.1); - if !(corner || i == last) { - continue; - } - let Some(seg) = pts.get(start..=i) else { break }; - let from = seg.first().map_or(0.0, |p| p.0.input); - let lut = curve_lut(&seg.iter().map(|p| p.0.clone()).collect::>()); - if out.is_empty() { - out = lut; - } else { - for (k, (o, v)) in out.iter_mut().zip(lut).enumerate() { - if k as f32 / (LUT_SIZE - 1) as f32 >= from { - *o = v; - } - } - } - start = i; - } - if out.is_empty() { curve_lut(points) } else { out } -} - -fn gradient(stops: &[(f32, [f32; 3])], t: f32) -> [f32; 3] { - match stops { - [] => [t; 3], - [s] => s.1, - _ => { - if t <= stops[0].0 { - return stops[0].1; - } - for w in stops.windows(2) { - if t <= w[1].0 { - let k = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 }; - return std::array::from_fn(|i| w[0].1[i] + (w[1].1[i] - w[0].1[i]) * k); - } - } - stops[stops.len() - 1].1 - } - } -} - -pub fn rgb_to_hsl(c: [f32; 3]) -> (f32, f32, f32) { - let max = c[0].max(c[1]).max(c[2]); - let min = c[0].min(c[1]).min(c[2]); - let l = (max + min) / 2.0; - if (max - min).abs() < 1e-7 { - return (0.0, 0.0, l); - } - let d = max - min; - let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) }; - let h = if max == c[0] { - ((c[1] - c[2]) / d).rem_euclid(6.0) - } else if max == c[1] { - (c[2] - c[0]) / d + 2.0 - } else { - (c[0] - c[1]) / d + 4.0 - }; - (h / 6.0, s, l) -} - -pub fn hsl_to_rgb(h: f32, s: f32, l: f32) -> [f32; 3] { - if s <= 0.0 { - return [l; 3]; - } - let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s }; - hue_rgb(h, 2.0 * l - q, q) -} - -/// The colour of hue `h` (0..1) with its smallest channel at `p` and its largest at `q`. -fn hue_rgb(h: f32, p: f32, q: f32) -> [f32; 3] { - let f = |mut t: f32| { - t = t.rem_euclid(1.0); - if t < 1.0 / 6.0 { - p + (q - p) * 6.0 * t - } else if t < 0.5 { - q - } else if t < 2.0 / 3.0 { - p + (q - p) * (2.0 / 3.0 - t) * 6.0 - } else { - p - } - }; - [f(h + 1.0 / 3.0), f(h), f(h - 1.0 / 3.0)] -} - #[cfg(test)] mod lookup_tests { use super::*; diff --git a/crates/compose/src/adjust/channels.rs b/crates/compose/src/adjust/channels.rs new file mode 100644 index 0000000000..4b7d42b92a --- /dev/null +++ b/crates/compose/src/adjust/channels.rs @@ -0,0 +1,278 @@ +use super::color::{bayer4, gradient}; +use super::tone::{LUT_SIZE, lut, map_rgb, modern_brightness, modern_contrast, modern_lut, posterize_in, tone_luts_depth}; +use super::*; + +/// Legacy Brightness/Contrast on a 32-bit document's samples: unclipped, with contrast pivoting at +/// 127 of 255 (photoshop corpus rgb32 and gray32 brightness-contrast-legacy.psd: every pixel +/// exact, negative and over-white values included; the 8/16-bit pivot, 128, is 0.43 of a level +/// off there). +pub(super) fn legacy_brightness_contrast_hdr(brightness: f32, contrast: f32) -> impl Fn(f32) -> f32 { + const PIVOT: f32 = 127.0 / 255.0; + let b = brightness / 255.0; + let c = contrast.clamp(-100.0, 99.0); + let k = if c >= 0.0 { 1.0 / (1.0 - c / 100.0) } else { 1.0 + c / 100.0 }; + let (pre, post) = if c >= 0.0 { (b, 0.0) } else { (0.0, b) }; + move |v: f32| (v + pre - PIVOT) * k + PIVOT + post +} + +/// Legacy Brightness/Contrast as one channel's tone curve (see [`apply_depth`]). +pub(super) fn legacy_brightness_contrast(brightness: f32, contrast: f32) -> impl Fn(f32) -> f32 { + legacy_brightness_contrast_at(brightness, contrast, LEGACY_PIVOT) +} + +/// [`legacy_brightness_contrast`] with contrast pivoting at `pivot`. +fn legacy_brightness_contrast_at(brightness: f32, contrast: f32, pivot: f32) -> impl Fn(f32) -> f32 { + let b = brightness / 255.0; + let c = contrast.clamp(-100.0, 99.0); + let k = if c >= 0.0 { 1.0 / (1.0 - c / 100.0) } else { 1.0 + c / 100.0 }; + let (pre, post) = if c >= 0.0 { (b, 0.0) } else { (0.0, b) }; + move |v: f32| ((v + pre - pivot) * k + pivot + post).clamp(0.0, 1.0) +} + +/// Whether Threshold at `level` turns colour `c` white in a document of `depth` (`None`: unknown, +/// treated as 8-bit). Photoshop splits on the luminosity 0.30 R + 0.59 G + 0.11 B (the blend +/// modes' `lum`), not the Rec. 601 grey, of the document's whole sample values: +/// - 8 bits: white when that luminosity, rounded to a level with halves down, reaches the level; +/// - 16 bits: white when it reaches the level converted to 16 bits (128 → 16448); +/// - 32 bits: white when it reaches the level. +/// +/// Exact on every pixel of psd-tools threshold_rgb.psd, threshold_16bits_rgb.psd and +/// threshold_16bits_grayscale.psd and of the photoshop corpus's rgb16 threshold-128.psd, where the +/// Rec. 601 grey split 28 and 100 pixels of the first two the other way. The sums of +/// `30 R + 59 G + 11 B` over whole samples are exact in f32 (at most 3 276 800). +pub fn threshold_white(c: [f32; 3], level: f32, depth: Option) -> bool { + let t = (level * 255.0).round(); + let sum = |q: f32| { + let [r, g, b] = c.map(|v| (v.clamp(0.0, 1.0) * q).round()); + 30.0 * r + 59.0 * g + 11.0 * b + }; + match depth { + None | Some(SampleType::U8) => sum(255.0) > 100.0 * t - 50.0, + Some(SampleType::U16) => sum(32768.0) >= 100.0 * (t * 32768.0 / 255.0).round(), + Some(SampleType::F32) => (0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]) * 255.0 >= t, + } +} + +/// Whether a Lab document evaluates `adj` on its L, a and b channels rather than on the screen +/// colour: Invert and Posterize (L, a and b alike), Brightness/Contrast (L only), Threshold +/// (split on L, neutral result) and Gradient Map (driven by L). Levels and Curves carry their own +/// Lab records ([`ToneSpace::Lab`]); everything else stays on the screen colour. +pub fn lab_channel_adjustment(adj: &Adjustment) -> bool { + matches!( + adj, + Adjustment::Invert + | Adjustment::Posterize { .. } + | Adjustment::Threshold { .. } + | Adjustment::BrightnessContrast { .. } + | Adjustment::GradientMap { .. } + ) +} + +/// Whether a CMYK document evaluates `adj` on its inks rather than on the screen colour: Invert +/// and Posterize (each ink, black included, so paper inverts to 400% ink), Threshold (paper or +/// 100% black ink alone) and Brightness/Contrast (each ink's stored value, 1 - ink, through the +/// tone curve; see [`ink_through`]). Photoshop corpus cmyk8 and cmyk16 invert, posterize-4, +/// threshold-128 and brightness-contrast(-legacy) follow these rules on the files' own inks on +/// every pixel; here the inks are the screen colour separated through the document's CMYK +/// profile, so neutrals carry the black that profile generates rather than the file's. +pub fn cmyk_channel_adjustment(adj: &Adjustment) -> bool { + stored_channel_adjustment(adj) || cmy_adjustment(adj) || matches!(adj, Adjustment::BrightnessContrast { .. }) +} + +/// Whether a CMYK document evaluates `adj` on C, M and Y as the complement of an RGB colour, +/// black kept ([`apply_cmy`]): Hue/Saturation (not Colorize, which Photoshop separates again, +/// black and all) and Color Balance (photoshop corpus cmyk16 hue-saturation.psd follows this on +/// every pixel within half a level, cmyk8 within two; color-balance within our RGB Color +/// Balance's own error). +pub fn cmy_adjustment(adj: &Adjustment) -> bool { + matches!(adj, Adjustment::HueSaturation { colorize: false, .. } | Adjustment::ColorBalance { .. }) +} + +/// A [`cmy_adjustment`] on straight inks (C, M, Y, K; 0 none): the RGB adjustment on +/// `(1 - c, 1 - m, 1 - y)`, black left alone. +pub fn apply_cmy(adj: &Adjustment, inks: &mut [[f32; 4]]) { + let width = i32::try_from(inks.len()).unwrap_or(i32::MAX); + let mut buf = Buffer { rect: crate::Rect::new(0, 0, width, 1), px: inks.iter().map(|i| [1.0 - i[0], 1.0 - i[1], 1.0 - i[2], 1.0]).collect() }; + apply_depth(adj, &mut buf, Transfer::Srgb, None); + for (ink, p) in inks.iter_mut().zip(&buf.px) { + for c in 0..3 { + ink[c] = (1.0 - p[c]).clamp(0.0, 1.0); + } + } +} + +/// Brightness/Contrast as the lookup table (4096 samples over 0..1) a CMYK ink's stored value, +/// `1 - ink`, goes through ([`ink_through`]): [`modern_lut`], or the legacy linear curve with its +/// contrast pivoting at 128 in ink, which is 127 of 255 stored (photoshop corpus cmyk16 +/// brightness-contrast-legacy.psd sits 0.43 of a level off around 128 stored, as a one-level +/// pivot shift times contrast +30's slope predicts). +pub fn ink_brightness_contrast_lut(brightness: f32, contrast: f32, legacy: bool) -> Vec { + if !legacy { + return modern_lut(brightness, contrast); + } + let curve = legacy_brightness_contrast_at(brightness, contrast, 1.0 - LEGACY_PIVOT); + (0..LUT_SIZE).map(|k| curve(k as f32 / (LUT_SIZE - 1) as f32)).collect() +} + +/// One CMYK ink (0: none) through a channel tone curve the way Photoshop applies one in CMYK: to +/// the stored value, `1 - ink`, so raising brightness takes ink away. +pub fn ink_through(table: &[f32], ink: f32) -> f32 { + 1.0 - lut(table, 1.0 - ink) +} + +/// Whether [`stored_channels`] evaluates `adj`: Invert, Posterize and Threshold. +pub fn stored_channel_adjustment(adj: &Adjustment) -> bool { + matches!(adj, Adjustment::Invert | Adjustment::Posterize { .. } | Adjustment::Threshold { .. }) +} + +/// Invert, Posterize or Threshold on one pixel's own channels in a Lab or CMYK document of +/// `depth` (`None`: unknown, treated as 8-bit): `ch` holds L, a, b normalised as [`lab_norm`] +/// gives them, or the C, M, Y, K inks (0: none). Lab Invert turns 8-bit bytes `v` into `255 - v` +/// (a becomes -1 - a) and mirrors a and b around neutral at 16 bits (photoshop corpus lab16 +/// invert.psd: neutral stays neutral). CMYK Threshold compares [`ink_luma`]. +pub fn stored_channels(adj: &Adjustment, mode: ColorMode, depth: Option, ch: &mut [f32]) { + let lab = mode == ColorMode::Lab; + match adj { + Adjustment::Invert => { + let mirror = if lab && depth.is_some_and(|d| d != SampleType::U8) { 256.0 / 255.0 } else { 1.0 }; + for (i, v) in ch.iter_mut().enumerate() { + *v = if i > 0 { mirror } else { 1.0 } - v.clamp(0.0, 1.0); + } + } + // CMYK posterizes the stored values (1 - ink), which its uneven levels make differ from + // posterizing the ink: psd-tools posterize_cmyk.psd (3 to 21 levels) is exact so. + Adjustment::Posterize { levels } if mode == ColorMode::Cmyk => ch.iter_mut().for_each(|v| *v = 1.0 - posterize_in(1.0 - *v, *levels, depth)), + Adjustment::Posterize { levels } => ch.iter_mut().for_each(|v| *v = posterize_in(*v, *levels, depth)), + Adjustment::Threshold { level } => { + // On the 8-bit grid, like the RGB threshold. + let t = (level * 255.0).round(); + let out = if lab { + let white = ch.first().is_some_and(|l| (l.clamp(0.0, 1.0) * 255.0).round() >= t); + [if white { 1.0 } else { 0.0 }, 128.0 / 255.0, 128.0 / 255.0, 0.0] + } else { + let ink = |i: usize| ch.get(i).copied().unwrap_or(0.0); + let black = (ink_luma([ink(0), ink(1), ink(2), ink(3)]) * 255.0).round() < t; + [0.0, 0.0, 0.0, if black { 1.0 } else { 0.0 }] + }; + ch.iter_mut().zip(out).for_each(|(v, o)| *v = o); + } + _ => {} + } +} + +/// The luma Photoshop's CMYK Threshold compares: Rec. 601 weights on the inks' plain complement, +/// `(1 - c)(1 - k)` and so on, whatever the document's profile (photoshop corpus cmyk8 and cmyk16 +/// threshold-128.psd: every pixel on the right side of level 128). +pub fn ink_luma(ink: [f32; 4]) -> f32 { + let paper = 1.0 - ink[3].clamp(0.0, 1.0); + rgb_to_gray([0, 1, 2].map(|i| (1.0 - ink[i].clamp(0.0, 1.0)) * paper)) +} + +/// Encoded sRGB → Lab normalised the way Photoshop's channels hold it: L/100, (a+128)/255, +/// (b+128)/255. +fn lab_norm(c: [f32; 3]) -> [f32; 3] { + let l = srgb_to_lab(c); + [l[0] / 100.0, (l[1] + 128.0) / 255.0, (l[2] + 128.0) / 255.0] +} + +/// The inverse of [`lab_norm`]. +pub(super) fn lab_denorm(n: [f32; 3]) -> [f32; 3] { + lab_to_srgb([n[0] * 100.0, n[1] * 255.0 - 128.0, n[2] * 255.0 - 128.0]) +} + +/// Neutral a or b as Lab surfaces store it ((0 + 128) / 255). +pub const LAB_NEUTRAL: f32 = 128.0 / 255.0; + +/// An adjustment Photoshop evaluates on a Lab document's own channels, as an operation on one +/// pixel's stored L, a, b (normalised as Lab surfaces store them: L / 100, (a + 128) / 255, +/// (b + 128) / 255) in a document of `depth`: Invert and Posterize (each channel), Threshold +/// (split on L, neutral result), Brightness/Contrast (L) and Levels or Curves with Lab records. +/// `None` for any other adjustment. On the stored values colours outside the display gamut keep +/// theirs, where [`apply_in`] can only round-trip them through clipped display RGB. +pub fn lab_stored_op(adj: &Adjustment, depth: Option) -> Option> { + let op: LabOp<'_> = match adj { + Adjustment::Invert | Adjustment::Posterize { .. } => Box::new(move |ch: &mut [f32; 3]| stored_channels(adj, ColorMode::Lab, depth, ch)), + Adjustment::Threshold { level } => { + // Split on L on the 8-bit grid, like the display path (`apply_lab`). + let t = (level * 255.0).round(); + Box::new(move |ch: &mut [f32; 3]| { + let white = (ch[0].clamp(0.0, 1.0) * 255.0).round() >= t; + *ch = [if white { 1.0 } else { 0.0 }, LAB_NEUTRAL, LAB_NEUTRAL]; + }) + } + Adjustment::BrightnessContrast { brightness, contrast, legacy } => { + let (b, c, legacy) = (*brightness, *contrast, *legacy); + let legacy_curve = legacy_brightness_contrast(b, c); + Box::new(move |ch: &mut [f32; 3]| { + ch[0] = if legacy { legacy_curve(ch[0]) } else { modern_contrast(modern_brightness(ch[0], b), c).clamp(0.0, 1.0) }; + }) + } + Adjustment::Levels { space: ToneSpace::Lab, .. } | Adjustment::Curves { space: ToneSpace::Lab, .. } => { + let luts = tone_luts_depth(adj, depth); + Box::new(move |ch: &mut [f32; 3]| { + for (v, t) in ch.iter_mut().zip(&luts) { + *v = lut(t, *v); + } + }) + } + _ => return None, + }; + Some(op) +} + +/// One pixel's stored L, a, b through an adjustment ([`lab_stored_op`]). +pub type LabOp<'a> = Box; + +/// The Lab evaluation of a [`lab_channel_adjustment`] in a document of `depth` (no-op for any +/// other adjustment). +pub(super) fn apply_lab(adj: &Adjustment, buf: &mut Buffer, depth: Option) { + match adj { + // L → 100 - L and a, b mirrored about neutral; each channel posterized (see `stored_channels`). + Adjustment::Invert | Adjustment::Posterize { .. } => map_rgb(buf, |c| { + let mut n = lab_norm(c); + stored_channels(adj, ColorMode::Lab, depth, &mut n); + lab_denorm(n) + }), + Adjustment::Threshold { level } => { + // Split on L alone (on the 8-bit grid); the result is neutral black or white. + let t = (level * 255.0).round(); + map_rgb(buf, |c| [if (lab_norm(c)[0].clamp(0.0, 1.0) * 255.0).round() >= t { 1.0 } else { 0.0 }; 3]) + } + Adjustment::BrightnessContrast { brightness, contrast, legacy } => { + let legacy_curve = legacy_brightness_contrast(*brightness, *contrast); + let modern = (!*legacy).then(|| modern_lut(*brightness, *contrast)); + let curve = |v: f32| match &modern { + Some(table) => lut(table, v), + None => legacy_curve(v), + }; + // The tone curve on L only. Added as the difference of two round trips (like + // `tone_in_space`) so a and b, and colours a round trip moves, stay put. + map_rgb(buf, |c| { + let n = lab_norm(c); + let l = curve(n[0]); + if l == n[0] { + return c; + } + let (before, after) = (lab_denorm(n), lab_denorm([l, n[1], n[2]])); + std::array::from_fn(|i| (c[i] + after[i] - before[i]).clamp(0.0, 1.0)) + }) + } + Adjustment::GradientMap { stops, reverse, dither } => { + let (w, x0, y0) = (buf.rect.width().max(1) as usize, buf.rect.x0, buf.rect.y0); + for (i, p) in buf.px.iter_mut().enumerate() { + if p[3] <= 0.0 { + continue; + } + // Driven by L: equal lightness maps to the same stop colour whatever the chroma. + let l = lab_norm([p[0], p[1], p[2]])[0].clamp(0.0, 1.0); + let mut o = gradient(stops, if *reverse { 1.0 - l } else { l }); + if *dither { + let d = bayer4(x0 + (i % w) as i32, y0 + (i / w) as i32) / 255.0; + o = o.map(|v| (v + d).clamp(0.0, 1.0)); + } + p[..3].copy_from_slice(&o); + } + } + _ => {} + } +} diff --git a/crates/compose/src/adjust/color.rs b/crates/compose/src/adjust/color.rs new file mode 100644 index 0000000000..f47d1154f0 --- /dev/null +++ b/crates/compose/src/adjust/color.rs @@ -0,0 +1,482 @@ +use super::tone::LUT_SIZE; +use super::*; + +/// Hue/Saturation's range edits as three hue-indexed tables (hue shift in degrees, saturation and +/// lightness as fractions), sampled at hue `k / (len - 1)` turns. Ranges add up where they overlap. +pub fn hue_range_tables(ranges: &[HueRange; 6]) -> [Vec; 3] { + let at = |k: usize| { + let deg = k as f32 / (LUT_SIZE - 1) as f32 * 360.0; + ranges.iter().filter(|r| !r.is_neutral()).fold([0.0f32; 3], |acc, r| { + let w = r.weight(deg); + [acc[0] + w * r.hue, acc[1] + w * r.saturation / 100.0, acc[2] + w * r.lightness / 100.0] + }) + }; + let rows: Vec<[f32; 3]> = (0..LUT_SIZE).map(at).collect(); + std::array::from_fn(|i| rows.iter().map(|r| r[i]).collect()) +} + +/// Hue/Saturation's saturation `s` (-1..1) as [`hue_saturation`] takes it in a document of +/// `depth`. A 32-bit Colorize builds its colour with the saturation times `1 - |lightness|`: +/// the photoshop corpus's rgb32 hue-saturation-colorize.psd (Saturation 40, Lightness +5) has 0.95 +/// of the chroma at every lightness, and is exact so, where 8 and 16 bits keep the full saturation +/// (their oracles are exact without it). Only a raised Lightness is measured; a lowered one is +/// taken to scale the same way. +pub fn colorize_saturation(s: f32, lightness: f32, colorize: bool, depth: Option) -> f32 { + // Clamped here too: a PSD can store a saturation beyond ±100, and the GPU scales it unclamped. + if colorize && depth == Some(SampleType::F32) { s.clamp(-1.0, 1.0) * (1.0 - lightness.abs().min(1.0)) } else { s } +} + +/// One Hue/Saturation evaluation: hue shift in degrees, saturation and lightness in -1..=1. +/// Colorize sets the hue and saturation instead of shifting them; at 0% it leaves only the +/// lightness, as in Photoshop (#2326). Ticking Colorize in the dialog starts saturation at 25%. +pub fn hue_saturation(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool) -> [f32; 3] { + hue_saturation_in(c, hue, s, l, colorize, None) +} + +/// [`hue_saturation`] in a document of `depth`. At 32 bits Photoshop doesn't clip the raised +/// saturation, so saturated colours leave 0..1 (red with Hue +40, Saturation +25, Lightness -10 +/// becomes (1.0477, 0.649, -0.1477)), and it scales each colour's chroma around its lightness by +/// [`hdr_saturation_factor`], so colours at or above lightness 1 keep their hue too: the photoshop +/// corpus's rgb32 hue-saturation.psd is exact so. +pub fn hue_saturation_in(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool, depth: Option) -> [f32; 3] { + let hdr = depth == Some(SampleType::F32); + let lighten = |v: f32| if l > 0.0 { v + (1.0 - v) * l } else { v * (1.0 + l) }; + if colorize { + // Colorize builds the colour at the lightened (or darkened) lightness, so black with + // Lightness +30 becomes a 30 % lightness colour, not grey (measured in Photoshop 27.11). + let (_, _, ll) = rgb_to_hsl(c); + return hsl_to_rgb(hue.rem_euclid(360.0) / 360.0, s.abs().min(1.0), lighten(ll)); + } + // Photoshop applies Lightness first, then rotates the hue and scales the saturation of the + // result: Hue +40, Saturation +25, Lightness -10 turns (240, 160, 30) into (173, 243, 0), not + // (168, 230, 14) (Photoshop 27.11 corpus file adjustments/rgb8/hue-saturation). + let lc = c.map(lighten); + let (hh, ss, ll) = rgb_to_hsl(lc); + let hh = (hh + hue / 360.0).rem_euclid(1.0); + if hdr { + // The chroma, not the HSL saturation, whose `2 - max - min` divisor is 0 at lightness 1 + // and negative above it: (2, 0, 0) with Hue +40 becomes (2, 1.333, 0) in Photoshop. + let d = (lc[0].max(lc[1]).max(lc[2]) - lc[0].min(lc[1]).min(lc[2])) * hdr_saturation_factor(s); + return hue_rgb(hh, ll - d / 2.0, ll + d / 2.0); + } + // Raising saturation divides by 1 - s, lowering it multiplies by 1 + s: +50 % doubles it + // (measured in Photoshop 27.11); +100 % saturates any colour that has some. + let ss = if s > 0.0 { ss / (1.0 - s).max(1.0 / 512.0) } else { ss * (1.0 + s) }.clamp(0.0, 1.0); + hsl_to_rgb(hh, ss, ll) +} + +/// The factor 32-bit Hue/Saturation scales chroma by for saturation `s` (-1..1), as Photoshop +/// computes it (measured at every whole percent from -100 to +100 on a 32-bit document): lowering +/// cuts `s` to 1/256 steps, raising cuts it to 254 steps out of 255, takes 255 / (255 - steps) to +/// 1/256 and stops at 32767/256, so +25 % gives 340/256, +99 % 63.75 and +100 % 127.996. +/// compose.wgsl's Hue/Saturation does the same in whole numbers. +pub fn hdr_saturation_factor(s: f32) -> f32 { + // The 1e-4 keeps a master plus range sum on its step: -0.46 + 0.96 is 0.49999997 in f32. + let s = s.clamp(-1.0, 1.0); + if s <= 0.0 { + return 1.0 - (-s * 256.0 + 1e-4).floor() / 256.0; + } + let steps = (s * 254.0 + 1e-4).floor() as u32; + (65280 / 255u32.saturating_sub(steps).max(1)).min(32767) as f32 / 256.0 +} + +/// A colour range's Lightness, applied after the master edits. It moves each channel towards the +/// pixel's brightest channel when raised and towards its darkest when lowered, not towards white +/// or black: Blues +50 turns (0, 29, 115) into (57, 71, 115), Blues -50 turns (102, 128, 204) into +/// (102, 115, 153) (measured in Photoshop 27.11). +pub fn range_lightness(c: [f32; 3], l: f32) -> [f32; 3] { + let l = l.clamp(-1.0, 1.0); + let target = if l > 0.0 { c[0].max(c[1]).max(c[2]) } else { c[0].min(c[1]).min(c[2]) }; + c.map(|v| v + (target - v) * l.abs()) +} + +/// Black & White grey value. Each colour is the sum of a grey part (its smallest channel), a +/// secondary-colour part (yellow, cyan or magenta: middle − smallest) and a primary part (red, +/// green or blue: largest − middle); the sliders (percent, Photoshop defaults 40 60 40 60 20 80 for +/// reds, yellows, greens, cyans, blues, magentas) weight the two colour parts. Unclipped: the +/// document's depth decides the range. +pub fn black_white_gray(c: [f32; 3], weights: &[f32; 6]) -> f32 { + let (r, g, b) = (c[0], c[1], c[2]); + let (max, min) = (r.max(g).max(b), r.min(g).min(b)); + let mid = r + g + b - max - min; + // Primary: the largest channel; secondary: the two largest channels together. + let primary = if r >= g && r >= b { + 0 + } else if g >= b { + 2 + } else { + 4 + }; + let secondary = if b <= r && b <= g { + 1 // red + green = yellow + } else if r <= g { + 3 // green + blue = cyan + } else { + 5 // red + blue = magenta + }; + min + (mid - min) * weights[secondary] / 100.0 + (max - mid) * weights[primary] / 100.0 +} + +/// Ordered-dither offset in -0.5..0.5 (4×4 Bayer matrix) for document pixel (x, y). +pub fn bayer4(x: i32, y: i32) -> f32 { + const M: [f32; 16] = [0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0]; + (M[((y & 3) * 4 + (x & 3)) as usize] + 0.5) / 16.0 - 0.5 +} + +/// Samples a 3D LUT (`n`³ RGB triplets, red fastest) at `c`, trilinear or tetrahedral. +pub fn lut3d_sample(lut: &[f32], n: usize, c: [f32; 3], tetrahedral: bool) -> [f32; 3] { + // A degenerate or short table can't be sampled: leave the colour alone. + if n < 2 || n.checked_pow(3).and_then(|c| c.checked_mul(3)).is_none_or(|len| lut.len() < len) { + return c; + } + let m = (n - 1) as f32; + let pos = c.map(|v| v.clamp(0.0, 1.0) * m); + let i0 = pos.map(|p| (p.floor() as usize).min(n - 2)); + let f: [f32; 3] = std::array::from_fn(|k| pos[k] - i0[k] as f32); + let at = |dr: usize, dg: usize, db: usize| -> [f32; 3] { + let idx = (((i0[2] + db) * n + i0[1] + dg) * n + i0[0] + dr) * 3; + [lut[idx], lut[idx + 1], lut[idx + 2]] + }; + let mix = |w: &[(f32, [f32; 3])]| -> [f32; 3] { std::array::from_fn(|k| w.iter().map(|(a, v)| a * v[k]).sum()) }; + let (fr, fg, fb) = (f[0], f[1], f[2]); + if tetrahedral { + let (c000, c111) = (at(0, 0, 0), at(1, 1, 1)); + if fr > fg { + if fg > fb { + mix(&[(1.0 - fr, c000), (fr - fg, at(1, 0, 0)), (fg - fb, at(1, 1, 0)), (fb, c111)]) + } else if fr > fb { + mix(&[(1.0 - fr, c000), (fr - fb, at(1, 0, 0)), (fb - fg, at(1, 0, 1)), (fg, c111)]) + } else { + mix(&[(1.0 - fb, c000), (fb - fr, at(0, 0, 1)), (fr - fg, at(1, 0, 1)), (fg, c111)]) + } + } else if fb > fg { + mix(&[(1.0 - fb, c000), (fb - fg, at(0, 0, 1)), (fg - fr, at(0, 1, 1)), (fr, c111)]) + } else if fb > fr { + mix(&[(1.0 - fg, c000), (fg - fb, at(0, 1, 0)), (fb - fr, at(0, 1, 1)), (fr, c111)]) + } else { + mix(&[(1.0 - fg, c000), (fg - fr, at(0, 1, 0)), (fr - fb, at(1, 1, 0)), (fb, c111)]) + } + } else { + let lerp = |a: [f32; 3], b: [f32; 3], t: f32| -> [f32; 3] { std::array::from_fn(|k| a[k] + (b[k] - a[k]) * t) }; + let c00 = lerp(at(0, 0, 0), at(1, 0, 0), fr); + let c10 = lerp(at(0, 1, 0), at(1, 1, 0), fr); + let c01 = lerp(at(0, 0, 1), at(1, 0, 1), fr); + let c11 = lerp(at(0, 1, 1), at(1, 1, 1), fr); + lerp(lerp(c00, c10, fg), lerp(c01, c11, fg), fb) + } +} + +/// Color Balance on channel `ch` (0 red, 1 green, 2 blue) of `v` (0..1); `tones` are the +/// shadows, midtones and highlights slider triples (cyan–red, magenta–green, yellow–blue, +/// −100..100). +/// +/// Reverse-engineered from Photoshop (a 16-bit gray ramp through every tone at ±10..±100, pairs of +/// tones, and random settings of all nine sliders, Preserve Luminosity on and off): the three +/// tones fold into one Levels per channel (input black point, input white point, midtone gamma), +/// within 0.8 of 255 everywhere. Folding matters: a lowered shadows and a raised highlights +/// slider cancel each other's gamma, which applying the tones one after another doesn't (#3423). +/// - Preserve Luminosity off: a slider only moves its own channel. Lowered shadows set the black +/// point to |shadows| levels, raised highlights set the white point to 255 − highlights levels, +/// and the gamma is 2^(m / 100) with m = midtones + (shadows + highlights) / 2. +/// - Preserve Luminosity on: each channel's black point is (max − own) shadows levels, its white +/// point 255 − (own − min) highlights levels, and m = own − (max + min) / 2 midtones. +/// +/// A gamma > 1 starts with slope 2^gamma at black (up to 18 of 255 brighter +/// near black without it). When the black point reaches the white point, input +/// at or above the white point is white and the rest black. +pub fn color_balance_channel(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize, v: f32) -> f32 { + BalanceCurve::new(tones, preserve_luminosity, ch).eval(v) +} + +/// One channel's Color Balance curve (see [`color_balance_channel`]), with the terms that don't +/// depend on the sample worked out once rather than per pixel. +pub struct BalanceCurve { + /// Input black and white points. + b: f32, + w: f32, + /// The power curve's exponent, 1 / gamma. + e: f32, + /// The Hermite join of a gamma > 1. + knee: Option, +} + +/// Where a gamma > 1 curve's Hermite join ends (`u0`), its starting slope 2^gamma (`s0`), and the +/// power curve's value (`p`) and slope (`d`) at `u0`. +#[derive(Clone, Copy)] +struct Knee { + u0: f32, + s0: f32, + p: f32, + d: f32, +} + +impl BalanceCurve { + /// The red, green and blue curves. + pub fn rgb(tones: [[f32; 3]; 3], preserve_luminosity: bool) -> [Self; 3] { + std::array::from_fn(|ch| Self::new(tones, preserve_luminosity, ch)) + } + + /// The curve of channel `ch` (0 red, 1 green, 2 blue) for the shadows, midtones and + /// highlights slider triples `tones`. + pub fn new(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch: usize) -> Self { + let [shadows, midtones, highlights] = tones.map(|t| t.map(|s| if s.is_finite() { s.clamp(-100.0, 100.0) } else { 0.0 })); + let own = |t: [f32; 3]| t.get(ch).copied().unwrap_or(0.0); + let max = |t: [f32; 3]| t[0].max(t[1]).max(t[2]); + let min = |t: [f32; 3]| t[0].min(t[1]).min(t[2]); + let (black, white, m) = if preserve_luminosity { + (max(shadows) - own(shadows), own(highlights) - min(highlights), own(midtones) - (max(midtones) + min(midtones)) / 2.0) + } else { + ((-own(shadows)).max(0.0), own(highlights).max(0.0), own(midtones) + (own(shadows) + own(highlights)) / 2.0) + }; + // The midtone gamma of the channel's Levels: `u^(1/gamma)`, except that a gamma > 1 + // (which would start with infinite slope) starts at slope 2^gamma and joins the power + // curve in a cubic Hermite at twice the input where that line meets it (Photoshop, + // measured on a 16-bit ramp at gamma 1.07..2: within 0.02 of 255). + let gamma = 2f32.powf(m / 100.0); + let e = 1.0 / gamma.max(0.01); + let knee = if gamma > 1.0 { + let s0 = 2f32.powf(gamma); + let u0 = (2.0 * s0.powf(1.0 / (e - 1.0))).min(1.0); + (!u0.is_nan() && u0 > 0.0).then(|| Knee { u0, s0, p: u0.powf(e), d: e * u0.powf(e - 1.0) }) + } else { + None + }; + Self { b: black / 255.0, w: 1.0 - white / 255.0, e, knee } + } + + /// The curve at `v` (0..1). + pub fn eval(&self, v: f32) -> f32 { + let (b, w) = (self.b, self.w); + let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + if v >= w { + return 1.0; + } + if v <= b { + return 0.0; + } + let u = (v - b) / (w - b); + match self.knee { + Some(Knee { u0, s0, p, d }) if u < u0 => { + let t = u / u0; + let (t2, t3) = (t * t, t * t * t); + ((t3 - 2.0 * t2 + t) * u0 * s0 + (3.0 * t2 - 2.0 * t3) * p + (t3 - t2) * u0 * d).clamp(0.0, 1.0) + } + _ => u.powf(self.e), + } + } +} + +/// How much a colour belongs to each Selective Color range: reds, yellows, greens, cyans, +/// blues, magentas (by chroma within the hue sector), whites, neutrals and blacks (by lightness). +pub fn selective_color_weights(c: [f32; 3]) -> [f32; 9] { + let max = c[0].max(c[1]).max(c[2]); + let min = c[0].min(c[1]).min(c[2]); + let mid = c[0] + c[1] + c[2] - max - min; + let top = |i: usize| if c[i] >= max { max - mid } else { 0.0 }; + let bottom = |i: usize| if c[i] <= min { mid - min } else { 0.0 }; + [ + top(0), + bottom(2), + top(1), + bottom(0), + top(2), + bottom(1), + ((min - 0.5) * 2.0).max(0.0), + (1.0 - (max - 0.5).abs() - (min - 0.5).abs()).clamp(0.0, 1.0), + ((0.5 - max) * 2.0).max(0.0), + ] +} + +/// Photoshop Selective Color: each range shifts the cyan, magenta and yellow ink (1 − R, G, B) by +/// its percentage, plus its black percentage on every ink, weighted by how much the colour belongs +/// to the range. Relative mode scales the shift by the ink already present (so it can't tint pure +/// white). Absolute mode scales it by the room the ink has: adding ink by min(1, 2 × (1 − ink)), +/// removing it by min(1, 2 × ink), so Neutrals Cyan +50 darkens red 64 by 32, not 64 (all 72 +/// absolute range × ink cases within 1 level of Photoshop 27.11). +pub fn selective_color(c: [f32; 3], relative: bool, adj: &[[f32; 4]; 9]) -> [f32; 3] { + let w = selective_color_weights(c); + let mut delta = [0.0f32; 3]; + for (r, wr) in w.iter().enumerate() { + if *wr <= 0.0 { + continue; + } + let a = adj[r].map(|v| v / 100.0); + for i in 0..3 { + let ink = 1.0 - c[i]; + let d = a[i] + a[3]; + let d = if relative { + d * ink + } else if d > 0.0 { + d * (2.0 * (1.0 - ink)).min(1.0) + } else { + d * (2.0 * ink).min(1.0) + }; + delta[i] += d * wr; + } + } + std::array::from_fn(|i| (c[i] - delta[i]).clamp(0.0, 1.0)) +} + +/// Photo Filter's linear-light RGB matrix. Photoshop multiplies the pixel's D50 XYZ, relative to +/// white, by the filter colour's (mixed in by `density`): a fixed linear map, so it is folded into +/// one matrix. With `normalize_y` the map keeps luminance Y (32-bit Preserve Luminosity; 8/16-bit +/// documents instead restore the encoded luminosity like the Luminosity blend mode). Fitted on the +/// photoshop corpus `photo-filter.psd`: rgb16 within 0.6/255 everywhere. +pub fn photo_filter_matrix(color: [f32; 3], density: f32, normalize_y: bool) -> [[f32; 3]; 3] { + let d = if density.is_finite() { density.clamp(0.0, 1.0) } else { 0.0 }; + let xyz = mat3_mul(&SRGB_TO_XYZ_D50, color.map(|v| srgb_to_linear(v.clamp(0.0, 1.0)))); + let mut s: [f32; 3] = std::array::from_fn(|i| 1.0 - d + d * xyz[i] / D50[i]); + if normalize_y && s[1] > 1e-6 { + let y = s[1]; + s = s.map(|v| v / y); + } + // XYZ_D50_TO_SRGB · diag(s) · SRGB_TO_XYZ_D50 + std::array::from_fn(|r| std::array::from_fn(|c| (0..3).map(|k| XYZ_D50_TO_SRGB[r][k] * s[k] * SRGB_TO_XYZ_D50[k][c]).sum())) +} + +/// Photoshop's Vibrance on one pixel (`v`, `s`: the sliders / 100; `hi`: the sample ceiling). +/// +/// Measured black-box against Photoshop 25.4 on 7,400-colour charts (8- and 16-bit; sRGB, Adobe RGB +/// and ProPhoto documents). Both sliders work in linear light through the document's tone curve, +/// Vibrance first, then Saturation: +/// - Saturation moves each colour away from (or towards) the grey `0.288 R + 0.712 G` (blue has no +/// weight, in every profile) by `1 + s`, clipping each channel: within 0.07/255 at every `s`. +/// - Vibrance is an HSV change in linear light that keeps the hue: see [`vibrance_lin`]. +pub fn vibrance_px(c: [f32; 3], v: f32, s: f32, transfer: Transfer, hi: f32) -> [f32; 3] { + let mut l = c.map(|x| transfer.decode(x)); + if v != 0.0 { + l = vibrance_lin(l, v); + } + if s != 0.0 { + let g = VIBRANCE_GREY[0] * l[0] + VIBRANCE_GREY[1] * l[1]; + l = l.map(|x| (g + (1.0 + s) * (x - g)).clamp(0.0, hi)); + } + l.map(|x| transfer.encode(x.clamp(0.0, hi))) +} + +/// Weights of the grey Photoshop's Vibrance › Saturation desaturates to (R, G; blue has none). +pub const VIBRANCE_GREY: [f32; 2] = [0.288, 0.712]; + +/// Positive Vibrance's saturation boost, fitted to the measurements (see [`vibrance_lin`]). +pub const VIBRANCE_BOOST: [f32; 7] = [0.5001, 0.0887, 0.4374, 0.7573, -0.8113, 0.5154, 2.8026]; + +/// The Vibrance slider (`v` in [-1, 1]) on a linear-light pixel. With `t = 1 - min/max` (HSV +/// saturation) and `V = max`: +/// - below 0 (`a = -v`): `t' = t (1 - a/4) (1 - a + a t (1 + t) / 2)` and +/// `V' = V - a t (1 - t) (2 - t + t²) V (1 - V)`; exact (0.2/255 mean) except in the deepest +/// shadows (`V` under 0.05), which Photoshop desaturates less. +/// - above 0: `V' = V + v/4 t (1 - t) (2 - t + t²) V (1 - V)` (exact) and a saturation boost that +/// grows as `t` and `V` fall, damped on reds and skin (HSV hue 0–30°, fading out by 45° and in +/// from 300°): a fit, 0.4 (+10) to 5 (+100) /255 off on average. +pub fn vibrance_lin(c: [f32; 3], v: f32) -> [f32; 3] { + let mx = c[0].max(c[1]).max(c[2]); + let mn = c[0].min(c[1]).min(c[2]); + if mx <= 0.0 || mx - mn <= 1e-9 { + return c; + } + let t = 1.0 - mn / mx; + let shape = t * (1.0 - t) * (2.0 - t + t * t) * mx * (1.0 - mx).max(0.0); + let (t2, v2) = if v < 0.0 { + let a = -v; + (t * (1.0 - a / 4.0) * (1.0 - a + a * t * (1.0 + t) / 2.0), mx - a * shape) + } else { + let [c0, c1, p, q, r0, ra, rt] = VIBRANCE_BOOST; + let w = vibrance_skin(hsv_hue(c, mx, mn)); + let a = v * (1.0 - w) + 0.64 * v.powf(1.6) * w; + let boost = (c0 * a + c1 * a * a) * t.powf(p) * (1.0 - t).powf(q) * ((r0 + ra * a + rt * (1.0 - t)) * (1.0 - mx).max(0.0)).exp(); + ((t * (1.0 + boost)).min(1.0), mx + v / 4.0 * shape) + }; + let m2 = v2 * (1.0 - t2); + let k = (v2 - m2) / (mx - mn); + c.map(|x| m2 + (x - mn) * k) +} + +/// How much positive Vibrance treats a hue (degrees) as skin: 1 on 0–30°, fading to 0 by 45° and +/// in again from 300°. +fn vibrance_skin(h: f32) -> f32 { + if h <= 30.0 { + 1.0 + } else if h < 45.0 { + (45.0 - h) / 15.0 + } else if h < 300.0 { + 0.0 + } else { + (h - 300.0) / 60.0 + } +} + +/// HSV hue in degrees of `c` (its max `mx` and min `mn` given, `mx > mn`). +fn hsv_hue(c: [f32; 3], mx: f32, mn: f32) -> f32 { + let d = mx - mn; + let h = if mx == c[0] { + ((c[1] - c[2]) / d).rem_euclid(6.0) + } else if mx == c[1] { + (c[2] - c[0]) / d + 2.0 + } else { + (c[0] - c[1]) / d + 4.0 + }; + h * 60.0 +} + +pub(super) fn gradient(stops: &[(f32, [f32; 3])], t: f32) -> [f32; 3] { + match stops { + [] => [t; 3], + [s] => s.1, + _ => { + if t <= stops[0].0 { + return stops[0].1; + } + for w in stops.windows(2) { + if t <= w[1].0 { + let k = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 }; + return std::array::from_fn(|i| w[0].1[i] + (w[1].1[i] - w[0].1[i]) * k); + } + } + stops[stops.len() - 1].1 + } + } +} + +pub fn rgb_to_hsl(c: [f32; 3]) -> (f32, f32, f32) { + let max = c[0].max(c[1]).max(c[2]); + let min = c[0].min(c[1]).min(c[2]); + let l = (max + min) / 2.0; + if (max - min).abs() < 1e-7 { + return (0.0, 0.0, l); + } + let d = max - min; + let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) }; + let h = if max == c[0] { + ((c[1] - c[2]) / d).rem_euclid(6.0) + } else if max == c[1] { + (c[2] - c[0]) / d + 2.0 + } else { + (c[0] - c[1]) / d + 4.0 + }; + (h / 6.0, s, l) +} + +pub fn hsl_to_rgb(h: f32, s: f32, l: f32) -> [f32; 3] { + if s <= 0.0 { + return [l; 3]; + } + let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s }; + hue_rgb(h, 2.0 * l - q, q) +} + +/// The colour of hue `h` (0..1) with its smallest channel at `p` and its largest at `q`. +fn hue_rgb(h: f32, p: f32, q: f32) -> [f32; 3] { + let f = |mut t: f32| { + t = t.rem_euclid(1.0); + if t < 1.0 / 6.0 { + p + (q - p) * 6.0 * t + } else if t < 0.5 { + q + } else if t < 2.0 / 3.0 { + p + (q - p) * (2.0 / 3.0 - t) * 6.0 + } else { + p + } + }; + [f(h + 1.0 / 3.0), f(h), f(h - 1.0 / 3.0)] +} diff --git a/crates/compose/src/adjust/tone.rs b/crates/compose/src/adjust/tone.rs new file mode 100644 index 0000000000..3659748392 --- /dev/null +++ b/crates/compose/src/adjust/tone.rs @@ -0,0 +1,488 @@ +use super::*; + +/// Float RGB curve channels with no edit must preserve samples outside the LUT domain; edited +/// ones extend past it (see [`float_tone_extrapolates`]). +pub fn float_tone_identity(adj: &Adjustment, depth: Option) -> [bool; 3] { + match adj { + Adjustment::Curves { master, per_channel, space: ToneSpace::Rgb, .. } if depth == Some(SampleType::F32) => { + std::array::from_fn(|i| photocraft_doc::adjust::is_identity_curve(master) && photocraft_doc::adjust::is_identity_curve(&per_channel[i])) + } + _ => [false; 3], + } +} + +/// Whether an edited Curves adjustment continues past 0..1 instead of clipping: in a 32-bit RGB +/// document Photoshop extends each curve beyond its end points along the slope of its end +/// segments (#7157: `[[0,0],[255,128]]` maps -0.5 to -0.250980407 and 2 to 1.003921628). Only +/// in RGB documents: the curve's space is not the document's, and other modes keep the table. +pub fn float_tone_extrapolates(adj: &Adjustment, depth: Option, mode: ColorMode) -> bool { + matches!(adj, Adjustment::Curves { space: ToneSpace::Rgb, .. }) && depth == Some(SampleType::F32) && mode == ColorMode::Rgb +} + +pub(crate) fn apply_tone(buf: &mut Buffer, space: ToneSpace, luts: &[Vec; 4], identity: [bool; 3], extrapolate: bool) { + let sample = if extrapolate { lut_extended } else { lut }; + match space { + ToneSpace::Rgb => map_rgb(buf, |c| std::array::from_fn(|i| if identity[i] { c[i] } else { sample(&luts[i], c[i]) })), + ToneSpace::Cmyk | ToneSpace::Lab => map_rgb(buf, |c| tone_in_space(space, luts, c)), + } +} + +/// Per-channel LUTs of a Levels or Curves adjustment: each channel's record first, then the +/// master (composite) record, as Photoshop does (psd-tools levels_rgb.psd and curves_rgb.psd, +/// #975). Four rows: the three `per_channel` channels then black +/// (identity unless the space is CMYK). In Lab there is no composite record, so the master is ignored. +pub fn tone_luts(adj: &Adjustment) -> [Vec; 4] { + tone_luts_q(adj, None) +} + +/// [`tone_luts`] for samples with `quantum` steps per unit (Levels works on whole levels; see +/// [`levels_q`]). +pub fn tone_luts_q(adj: &Adjustment, quantum: Option) -> [Vec; 4] { + let x = |k: usize| k as f32 / (LUT_SIZE - 1) as f32; + match adj { + Adjustment::Levels { master, per_channel, space, black } => { + let ident = LevelsChannel::default(); + let m = if *space == ToneSpace::Lab { &ident } else { master }; + let row = |c: &LevelsChannel| (0..LUT_SIZE).map(|k| levels_q(m, levels_q(c, x(k), quantum), quantum)).collect(); + [row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), row(if *space == ToneSpace::Cmyk { black } else { &ident })] + } + Adjustment::Curves { master, per_channel, space, black, pencil } => { + let m = if *space == ToneSpace::Lab { curve_lut(&[]) } else { curve_lut_mode(master, *pencil) }; + let row = |c: &[CurvePoint]| curve_lut_mode(c, *pencil).iter().map(|&v| lut(&m, v)).collect(); + [row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), row(if *space == ToneSpace::Cmyk { black } else { &[] })] + } + _ => std::array::from_fn(|_| (0..LUT_SIZE).map(x).collect()), + } +} + +/// [`tone_luts_q`] in a document of `depth` (`None`: unrounded). 32-bit Levels use +/// [`levels_float`], sampled on 0..1 and kept in 0..1 for LUT consumers. Float RGB rendering +/// evaluates the formula directly instead, so samples and results outside that domain survive. +pub fn tone_luts_depth(adj: &Adjustment, depth: Option) -> [Vec; 4] { + match (adj, depth) { + (Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, .. }, Some(SampleType::F32)) => { + let x = |k: usize| k as f32 / (LUT_SIZE - 1) as f32; + let row = |c: &LevelsChannel| (0..LUT_SIZE).map(|k| levels_float(master, levels_float(c, x(k))).clamp(0.0, 1.0)).collect(); + [row(&per_channel[0]), row(&per_channel[1]), row(&per_channel[2]), (0..LUT_SIZE).map(x).collect()] + } + _ => tone_luts_q(adj, depth.and_then(crate::adjustment_quantum)), + } +} + +/// Applies channel LUTs to a display-RGB colour in CMYK (ink brightness, 1 - ink) or Lab space, +/// through the conversions the document's surfaces use. The change is added as a difference of +/// two round trips, so channels a curve leaves alone (and out-of-gamut colours) stay exact. +fn tone_in_space(space: ToneSpace, luts: &[Vec; 4], c: [f32; 3]) -> [f32; 3] { + use photocraft_color::convert::{cmyk_to_rgb, rgb_to_cmyk}; + let (before, after) = match space { + ToneSpace::Cmyk => { + let ink = rgb_to_cmyk(c); + let out: [f32; 4] = std::array::from_fn(|i| 1.0 - lut(&luts[i], 1.0 - ink[i])); + if out == ink { + return c; + } + (cmyk_to_rgb(ink), cmyk_to_rgb(out)) + } + ToneSpace::Lab => { + let l = srgb_to_lab(c); + let n = [l[0] / 100.0, (l[1] + 128.0) / 255.0, (l[2] + 128.0) / 255.0]; + let o: [f32; 3] = std::array::from_fn(|i| lut(&luts[i], n[i])); + if o == n { + return c; + } + let back = |v: [f32; 3]| lab_to_srgb([v[0] * 100.0, v[1] * 255.0 - 128.0, v[2] * 255.0 - 128.0]); + (back(n), back(o)) + } + ToneSpace::Rgb => return std::array::from_fn(|i| lut(&luts[i], c[i])), + }; + std::array::from_fn(|i| (c[i] + after[i] - before[i]).clamp(0.0, 1.0)) +} + +pub(super) const LUT_SIZE: usize = 4096; + +pub(super) fn map_rgb(buf: &mut Buffer, f: impl Fn([f32; 3]) -> [f32; 3]) { + for p in &mut buf.px { + if p[3] <= 0.0 { + continue; + } + let r = f([p[0], p[1], p[2]]); + p[0] = r[0]; + p[1] = r[1]; + p[2] = r[2]; + } +} + +#[inline] +pub(super) fn lut(table: &[f32], v: f32) -> f32 { + let x = v.clamp(0.0, 1.0) * (table.len() - 1) as f32; + // Never negative (NaN casts to 0, as its floor did), so truncating is `floor`, without the + // libm call baseline x86-64 (no SSE4.1) makes for it. + let i = x as usize; + let j = (i + 1).min(table.len() - 1); + let f = x - i as f32; + table[i] * (1.0 - f) + table[j] * f +} + +/// Table steps the end slopes of [`lut_extended`] are measured over: one step's difference near +/// 0.5 carries f32 rounding (2e-4 of the slope), while 16 steps are still only 0.4 % of the domain. +pub const TONE_SLOPE_SPAN: usize = 16; + +/// [`lut`] continued past 0..1 along the slope of the table's end segments, as Photoshop applies +/// a curve to float samples ([`float_tone_extrapolates`]). Inside the domain it is [`lut`]; +/// non-finite samples stay with it too, so an infinite one can't become NaN on a flat end. +#[inline] +fn lut_extended(table: &[f32], v: f32) -> f32 { + let n = table.len(); + if !v.is_finite() || (0.0..=1.0).contains(&v) || n < 2 { + return lut(table, v); + } + let k = TONE_SLOPE_SPAN.min(n - 1); + let per_unit = (n - 1) as f32 / k as f32; + if v < 0.0 { table[0] + v * (table[k] - table[0]) * per_unit } else { table[n - 1] + (v - 1.0) * (table[n - 1] - table[n - 1 - k]) * per_unit } +} + +/// Modern Brightness curve (one channel, `brightness` in [-150, 150]); pins pure black and white, +/// and `b = 0` is the identity. Raised, it is a line of slope `s = 1.375^(b/50)` from the origin +/// up to a knee at output 126/255, then a cubic Hermite to (1, 1) whose end slope is +/// `1 / (1 + 0.084 b)`; past about +110, where no such cubic stays below white, the roll-off is +/// `1 - (1 - y0)(1 - u)^α` instead (continuous slope `α` at the knee, flat at white). Lowered, it +/// is the inverse of the curve raised by as much. +/// +/// Fit to every Photoshop measurement we have, all within about a level and a half: its ±50 +/// samples (`modern_brightness_matches_photoshop`), the photoshop corpus's brightness-contrast.psd +/// (+25 with contrast +30) and psd-tools' brightnesscontrast_rgb.psd, whose masked layers give +/// +23, -31 and -95 (+150 within 6 levels there, where every curve family tried bottoms out). +pub fn modern_brightness(v: f32, brightness: f32) -> f32 { + if brightness == 0.0 || !brightness.is_finite() { + return v; + } + Brightness::new(brightness).eval(v) +} + +/// [`modern_brightness`] for one slider value, its curve's constants worked out once. +struct Brightness { + raise: bool, + s: f32, + e: f32, + x0: f32, + /// The knee's slope over the roll-off's secant (`α` of Fritsch–Carlson); a power roll-off + /// replaces the Hermite when α² + β² > 9. + alpha: f32, + hermite: bool, +} + +/// Output level of the Brightness curve's knee. +const BRIGHTNESS_KNEE: f32 = 126.0 / 255.0; + +impl Brightness { + fn new(brightness: f32) -> Self { + let b = brightness.abs(); + let s = 1.375f32.powf(b / 50.0); + let e = 1.0 / (1.0 + 0.084 * b); + let x0 = (BRIGHTNESS_KNEE / s).min(1.0); + let secant = (1.0 - BRIGHTNESS_KNEE) / (1.0 - x0).max(1e-6); + let (alpha, beta) = (s / secant, e / secant); + Brightness { raise: brightness > 0.0, s, e, x0, alpha, hermite: alpha * alpha + beta * beta <= 9.0 } + } + + fn eval(&self, v: f32) -> f32 { + let v = v.clamp(0.0, 1.0); + if self.raise { + return self.raised(v); + } + if v <= 0.0 || v >= 1.0 { + return v; + } + // The inverse of the raised curve (monotone on [0, 1]), by bisection. + let (mut lo, mut hi) = (0.0f32, 1.0f32); + for _ in 0..32 { + let mid = 0.5 * (lo + hi); + if self.raised(mid) < v { + lo = mid; + } else { + hi = mid; + } + } + 0.5 * (lo + hi) + } + + /// The curve raised: the line, then a monotone roll-off to (1, 1). + fn raised(&self, x: f32) -> f32 { + let Brightness { s, e, x0, alpha, hermite, .. } = *self; + let y0 = BRIGHTNESS_KNEE; + if x <= x0 { + return y0.min(s * x); + } + let h = (1.0 - x0).max(1e-6); + let t = ((x - x0) / h).clamp(0.0, 1.0); + let y = if hermite { + let (t2, t3) = (t * t, t * t * t); + (2.0 * t3 - 3.0 * t2 + 1.0) * y0 + (t3 - 2.0 * t2 + t) * h * s + (-2.0 * t3 + 3.0 * t2) + (t3 - t2) * h * e + } else { + 1.0 - (1.0 - y0) * (1.0 - t).powf(alpha) + }; + y.clamp(0.0, 1.0) + } +} + +/// Modern Brightness/Contrast as one channel's lookup table (4096 samples over 0..1): +/// [`modern_brightness`] then [`modern_contrast`], as Photoshop applies them. +pub fn modern_lut(brightness: f32, contrast: f32) -> Vec { + let step = |k: usize, n: usize| k as f32 / (n - 1) as f32; + let bright: Vec = if brightness == 0.0 || !brightness.is_finite() { + (0..LUT_SIZE).map(|k| step(k, LUT_SIZE)).collect() + } else if brightness > 0.0 { + let curve = Brightness::new(brightness); + (0..LUT_SIZE).map(|k| curve.raised(step(k, LUT_SIZE))).collect() + } else { + // Lowered: invert the raised curve, sampled four times finer, in one monotone pass. + let curve = Brightness::new(-brightness); + let fine = 4 * LUT_SIZE; + let ys: Vec = (0..fine).map(|j| curve.raised(step(j, fine))).collect(); + let mut j = 0; + (0..LUT_SIZE) + .map(|k| { + let y = step(k, LUT_SIZE); + while j + 2 < fine && ys.get(j + 1).is_some_and(|&n| n < y) { + j += 1; + } + let (y0, y1) = (ys.get(j).copied().unwrap_or(0.0), ys.get(j + 1).copied().unwrap_or(1.0)); + let f = if y1 > y0 { ((y - y0) / (y1 - y0)).clamp(0.0, 1.0) } else { 0.0 }; + (step(j, fine) + f / (fine - 1) as f32).clamp(0.0, 1.0) + }) + .collect() + }; + bright.into_iter().map(|b| modern_contrast(b, contrast).clamp(0.0, 1.0)).collect() +} + +/// Modern Contrast curve (one channel, `contrast` in [-50, 100]). A symmetric cubic-Hermite S-curve +/// pivoting at 0.5: endpoint slope `1 - c/128`, centre slope `1 + c/128`. Near-exact vs Photoshop +/// (≤0.5/255). `c = 0` is the identity; pins 0, 0.5 and 1. +pub fn modern_contrast(v: f32, contrast: f32) -> f32 { + if contrast == 0.0 { + return v; + } + let k = contrast / 128.0; + let (end, mid) = (1.0 - k, 1.0 + k); + // Cubic Hermite on [0, 0.5]: pinned (0,0) slope `end`, (0.5,0.5) slope `mid`. `t` in [0,1]. + let half = |t: f32| end * 0.5 * (t * t * t - 2.0 * t * t + t) + (-2.0 * t * t * t + 3.0 * t * t) * 0.5 + mid * 0.5 * (t * t * t - t * t); + let v = v.clamp(0.0, 1.0); + if v <= 0.5 { half(v / 0.5) } else { 1.0 - half((1.0 - v) / 0.5) } +} + +/// Photoshop posterize: `n` equal input bins over 0..=255, output levels +/// `floor(k * 255 / (n - 1))` (exact on the corpus for 3, 7, 13 and 21 levels). +pub fn posterize(v: f32, levels: u32) -> f32 { + let n = levels.clamp(2, 255) as f32; + let x = (v.clamp(0.0, 1.0) * 255.0).round(); + let bin = (x * n / 256.0).floor().min(n - 1.0); + (bin * 255.0 / (n - 1.0)).floor() / 255.0 +} + +/// [`posterize`] in a document of `depth` (`None`: unknown, treated as 8-bit). At 16 bits +/// Photoshop bins the 16-bit sample (`⌊v · n / 32768⌋`) and lands on 8-bit levels through a +/// 16-bit step: `⌊b · 32768 / (n - 1)⌋`, converted with `⌊(o · 255 + 16384) / 32768⌋`, so +/// 127.5 comes out as 128 but 42.5 as 42 (8 bits floor them all). Exact on every sample of +/// psd-tools posterize_16bits_rgb.psd and posterize_16bits_grayscale.psd (levels 2 to 21), +/// which the 8-bit rule missed by up to half the range. +pub fn posterize_in(v: f32, levels: u32, depth: Option) -> f32 { + if depth != Some(SampleType::U16) { + return posterize(v, levels); + } + let n = f64::from(levels.clamp(2, 255)); + let x = (f64::from(v.clamp(0.0, 1.0)) * 32768.0).round(); + let bin = (x * n / 32768.0).floor().min(n - 1.0); + let step = (bin * 32768.0 / (n - 1.0)).floor(); + (((step * 255.0 + 16384.0) / 32768.0).floor() / 255.0) as f32 +} + +pub fn levels(ch: &LevelsChannel, v: f32) -> f32 { + levels_q(ch, v, None) +} + +/// [`levels`] on samples with `quantum` steps per unit (8-bit: 255). Photoshop works on whole +/// levels in three steps, each rounded half up to a whole level: the input-range stretch, the +/// midtone gamma ([`levels_gamma`]) and the output range. So a 44..214 range maps 45, 46, 47, 48 +/// → 1.5, 3, 4.5, 6 → 2, 3, 5, 6 (psd-tools levels_grayscale, where the gamma toe magnifies the +/// steps), and an output range narrower than 0..255 maps neighbouring gamma levels to one level +/// (psd-tools levels_rgb: 43..48 → 58 through a 0.47 channel gamma and the master's 48..255). +/// In a LUT the result is a staircase that is exact at every level. +pub fn levels_q(ch: &LevelsChannel, v: f32, quantum: Option) -> f32 { + let range = (ch.in_white - ch.in_black).max(1e-6); + let quantum = quantum.filter(|q| q.is_finite() && *q >= 1.0); + let whole = |x: f32| match quantum { + Some(q) => (x * q + 0.5).floor() / q, + None => x, + }; + let u = match quantum { + Some(q) => { + let v = (v * q).round() / q; + (((v - ch.in_black) / range).clamp(0.0, 1.0) * q + 0.5 + 1e-3).floor() / q + } + None => ((v - ch.in_black) / range).clamp(0.0, 1.0), + }; + let t = whole(levels_gamma(u, ch.gamma.max(0.01))); + whole(ch.out_black + t * (ch.out_white - ch.out_black)) +} + +/// Exponent of the shadow toe in [`levels_gamma`] (fitted; see there). +const LEVELS_TOE_POWER: f32 = 2.2; + +/// Levels' midtone gamma `g` on `u` in 0..1: `u^(1/g)`, except that above 1, where that power +/// curve is infinitely steep at black, Photoshop starts along a toe `a·u − b·u^q` of slope +/// `a = 2^g` that joins the curve with the same value and slope. `q` = [`LEVELS_TOE_POWER`] is +/// fitted on whole-level oracles at gamma 1.16, 1.22, 1.3, 1.78 and 2.0 (psd-tools levels_rgb +/// and levels_grayscale, the photoshop corpus's rgb8 and gray8 levels.psd, a measured 0..255 +/// ramp): all but 2 of their 1118 levels exact, the others within one. Below 1 the power curve is +/// exact (gamma 0.67 and 0.7: every level). +pub fn levels_gamma(u: f32, g: f32) -> f32 { + let c = 1.0 / g; + if g <= 1.0 { + return u.powf(c); + } + let (a, q) = (2f32.powf(g), LEVELS_TOE_POWER); + // Where the toe meets the curve: a·u1 − b·u1^q = u1^c and a − q·b·u1^(q−1) = c·u1^(c−1). + let u1 = ((1.0 - c / q) / (a * (1.0 - 1.0 / q))).powf(1.0 / (1.0 - c)); + if u >= u1 || u1 <= 0.0 { + return u.powf(c); + } + let b = (a * u1 - u1.powf(c)) / u1.powf(q); + // Just above gamma 1 the toe shrinks to nothing: u1^q underflows to 0 while u1 doesn't, and + // the power curve is the toe's limit there (otherwise b = inf and black turns NaN). + if !b.is_finite() { + return u.powf(c); + } + a * u - b * u.powf(q) +} + +/// [`levels`] in a 32-bit document. Neither the input is clipped to the input range nor the result +/// to the output range there, and the midtone gamma is a plain power curve, mirrored below the +/// black point (the oracle corpus' rgb32 and gray32 levels.psd: within 0.5/255, 10/255 off with +/// the clipped curve). +pub fn levels_float(ch: &LevelsChannel, v: f32) -> f32 { + let t = (v - ch.in_black) / (ch.in_white - ch.in_black).max(1e-6); + let t = if ch.gamma == 1.0 { t } else { t.signum() * t.abs().powf(1.0 / ch.gamma.max(0.01)) }; + ch.out_black + t * (ch.out_white - ch.out_black) +} + +/// The LUT of one Curves curve: [`curve_map_lut`] for a pencil-drawn map, else [`curve_lut`]. +pub fn curve_lut_mode(points: &[CurvePoint], pencil: bool) -> Vec { + if pencil { curve_map_lut(points) } else { curve_lut(points) } +} + +/// A pencil-drawn Curves map (see [`photocraft_doc::adjust::curve_map`]): straight segments +/// between its entries, constant outside the first/last, clamped to 0..=1, sampled into a LUT. +pub fn curve_map_lut(points: &[CurvePoint]) -> Vec { + let mut pts: Vec<(f32, f32)> = points.iter().filter(|p| p.input.is_finite() && p.output.is_finite()).map(|p| (p.input, p.output)).collect(); + pts.sort_by(|a, b| a.0.total_cmp(&b.0)); + pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6); + let ident = |k: usize| k as f32 / (LUT_SIZE - 1) as f32; + let (Some(&first), Some(&last)) = (pts.first(), pts.last()) else { return (0..LUT_SIZE).map(ident).collect() }; + let mut seg = 0; + (0..LUT_SIZE) + .map(|k| { + let xv = ident(k); + if xv <= first.0 { + return first.1.clamp(0.0, 1.0); + } + if xv >= last.0 { + return last.1.clamp(0.0, 1.0); + } + while pts.get(seg + 1).is_some_and(|p| p.0 < xv) { + seg += 1; + } + let (Some(&(x0, y0)), Some(&(x1, y1))) = (pts.get(seg), pts.get(seg + 1)) else { return last.1.clamp(0.0, 1.0) }; + let t = if x1 > x0 { (xv - x0) / (x1 - x0) } else { 0.0 }; + (y0 + (y1 - y0) * t).clamp(0.0, 1.0) + }) + .collect() +} + +/// Photoshop curve: a natural cubic spline through the points (it may +/// overshoot between points, as Photoshop's does), constant outside the +/// first/last point, clamped to 0..=1, sampled into a LUT. +pub fn curve_lut(points: &[CurvePoint]) -> Vec { + let mut pts: Vec<(f32, f32)> = points.iter().map(|p| (p.input, p.output)).collect(); + pts.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); + pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6); + if pts.len() < 2 { + return (0..LUT_SIZE).map(|i| i as f32 / (LUT_SIZE - 1) as f32).collect(); + } + let n = pts.len(); + // Second derivatives of the natural spline (tridiagonal solve). + let mut m2 = vec![0.0f64; n]; + if n > 2 { + let x: Vec = pts.iter().map(|p| f64::from(p.0)).collect(); + let y: Vec = pts.iter().map(|p| f64::from(p.1)).collect(); + let mut c = vec![0.0f64; n]; + let mut d = vec![0.0f64; n]; + for i in 1..n - 1 { + let (h0, h1) = (x[i] - x[i - 1], x[i + 1] - x[i]); + let a = h0 / 6.0; + let b = (h0 + h1) / 3.0; + let cc = h1 / 6.0; + let r = (y[i + 1] - y[i]) / h1 - (y[i] - y[i - 1]) / h0; + let denom = b - a * c[i - 1]; + c[i] = cc / denom; + d[i] = (r - a * d[i - 1]) / denom; + } + for i in (1..n - 1).rev() { + m2[i] = d[i] - c[i] * m2[i + 1]; + } + } + (0..LUT_SIZE) + .map(|k| { + let xv = k as f32 / (LUT_SIZE - 1) as f32; + if xv <= pts[0].0 { + return pts[0].1.clamp(0.0, 1.0); + } + if xv >= pts[n - 1].0 { + return pts[n - 1].1.clamp(0.0, 1.0); + } + let i = pts.windows(2).position(|w| xv <= w[1].0).unwrap_or(n - 2); + let (x0, y0) = (f64::from(pts[i].0), f64::from(pts[i].1)); + let (x1, y1) = (f64::from(pts[i + 1].0), f64::from(pts[i + 1].1)); + let h = x1 - x0; + let t = f64::from(xv); + let a = (x1 - t) / h; + let b = (t - x0) / h; + let y = a * y0 + b * y1 + ((a * a * a - a) * m2[i] + (b * b * b - b) * m2[i + 1]) * h * h / 6.0; + (y as f32).clamp(0.0, 1.0) + }) + .collect() +} + +/// A layer-style contour curve: [`curve_lut`], except that the curve bends sharply at corner +/// points (`corners[i]` true; Photoshop's Contour Editor "Corner"): each run between corners is +/// its own natural spline, so all-corner points make a polyline. Missing flags are smooth. +pub fn contour_curve_lut(points: &[CurvePoint], corners: &[bool]) -> Vec { + let mut pts: Vec<(CurvePoint, bool)> = points.iter().enumerate().map(|(i, p)| (p.clone(), corners.get(i).copied().unwrap_or(false))).collect(); + if !pts.iter().any(|p| p.1) { + return curve_lut(points); + } + pts.sort_by(|a, b| a.0.input.partial_cmp(&b.0.input).unwrap_or(std::cmp::Ordering::Equal)); + pts.dedup_by(|a, b| (a.0.input - b.0.input).abs() < 1e-6); + let mut out: Vec = Vec::new(); + let mut start = 0usize; + let last = pts.len().saturating_sub(1); + for i in 1..=last { + let corner = pts.get(i).is_some_and(|p| p.1); + if !(corner || i == last) { + continue; + } + let Some(seg) = pts.get(start..=i) else { break }; + let from = seg.first().map_or(0.0, |p| p.0.input); + let lut = curve_lut(&seg.iter().map(|p| p.0.clone()).collect::>()); + if out.is_empty() { + out = lut; + } else { + for (k, (o, v)) in out.iter_mut().zip(lut).enumerate() { + if k as f32 / (LUT_SIZE - 1) as f32 >= from { + *o = v; + } + } + } + start = i; + } + if out.is_empty() { curve_lut(points) } else { out } +} From 81c83b124f0ab9ae9967889f8398c63faee4c82d Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:01:40 +0000 Subject: [PATCH 248/259] refactor(gpu): split lib.rs into batch, cells, consts, convert, encode, fx_passes, kit, paging, readback, setup, textures --- crates/gpu/src/batch.rs | 215 +++ crates/gpu/src/cells.rs | 523 ++++++ crates/gpu/src/consts.rs | 54 + crates/gpu/src/convert.rs | 371 +++++ crates/gpu/src/encode.rs | 423 +++++ crates/gpu/src/fx/tests.rs | 5 +- crates/gpu/src/fx_passes.rs | 268 ++++ crates/gpu/src/kit.rs | 144 ++ crates/gpu/src/lib.rs | 2878 +--------------------------------- crates/gpu/src/paging.rs | 126 ++ crates/gpu/src/plan/tests.rs | 9 +- crates/gpu/src/readback.rs | 70 + crates/gpu/src/setup.rs | 480 ++++++ crates/gpu/src/tests.rs | 9 +- crates/gpu/src/textures.rs | 247 +++ 15 files changed, 2958 insertions(+), 2864 deletions(-) create mode 100644 crates/gpu/src/batch.rs create mode 100644 crates/gpu/src/cells.rs create mode 100644 crates/gpu/src/consts.rs create mode 100644 crates/gpu/src/convert.rs create mode 100644 crates/gpu/src/encode.rs create mode 100644 crates/gpu/src/fx_passes.rs create mode 100644 crates/gpu/src/kit.rs create mode 100644 crates/gpu/src/paging.rs create mode 100644 crates/gpu/src/readback.rs create mode 100644 crates/gpu/src/setup.rs create mode 100644 crates/gpu/src/textures.rs diff --git a/crates/gpu/src/batch.rs b/crates/gpu/src/batch.rs new file mode 100644 index 0000000000..988a580cc4 --- /dev/null +++ b/crates/gpu/src/batch.rs @@ -0,0 +1,215 @@ +use super::convert::{W, words}; +use super::textures::Resident; +use super::*; + +/// The uniform record of a pass. +pub(crate) fn op_words(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, map: Option) -> Vec { + words(&op_values(p, tex, mask, map)) +} + +/// The uniform record of the `fs_layerbatch` pass that draws `p` (whose texture and mask cover +/// `tex` and `mask`) and then `extras`, each an unmasked plain layer's `LayerBlend` pass with the +/// area its texture covers. Layout: see `batch_layer` in compose.wgsl. +pub(crate) fn batch_op_words(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, extras: &[(&plan::Pass<'_>, Option<[i32; 4]>)]) -> Vec { + let mut v = op_values(p, tex, mask, None); + // Word offsets of the record's vec4s holding the extra layers, three each: p0, p1, p2 | p3, + // q0, q1 | q2, q3, q4. + const AT: [usize; 9] = [20, 24, 28, 32, 44, 48, 52, 56, 60]; + if let Some(kind) = v.get_mut(1) { + *kind = I(extras.len().min(AT.len() / 3) as i32); + } + for (e, (x, area)) in extras.iter().take(AT.len() / 3).enumerate() { + let r = area.unwrap_or([0; 4]); + let geo = [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]; + let prm = [x.opacity, x.fill, plan::mode_index(x.mode) as f32, if area.is_some() { 1.0 } else { 0.0 }]; + for (k, vals) in [geo, x.color, prm].into_iter().enumerate() { + let at = AT[e * 3 + k]; + for (c, f) in vals.into_iter().enumerate() { + if let Some(w) = v.get_mut(at + c) { + *w = F(f); + } + } + } + } + words(&v) +} + +/// The words of a pass's uniform record (`Op` in compose.wgsl). +fn op_values(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, map: Option) -> Vec { + let mut flags = p.flags; + let (mut to, mut ts, mut mo, mut ms) = ([0; 2], [0; 2], [0; 2], [0; 2]); + if let Some(r) = tex { + flags |= 4; + to = [r[0], r[1]]; + ts = [r[2], r[3]]; + } + let (mut density, mut mdefault) = (0.0, 1.0); + if let Some(m) = &p.mask { + flags |= 1; + density = m.density; + mdefault = m.default; + if let Some(r) = mask { + flags |= 2; + mo = [r[0], r[1]]; + ms = [r[2], r[3]]; + } + } + if p.gradient { + flags |= 8; + } + let (mpo, mps) = map.map_or(([0, 0], [0, 0]), |r| ([r.x0, r.y0], [r.width() as i32, r.height() as i32])); + let mut v = vec![ + I(plan::mode_index(p.mode)), + I(p.adjust_kind), + U(flags), + U(0), + F(p.opacity), + F(density), + F(mdefault), + F(p.fill), + I(to[0]), + I(to[1]), + I(ts[0]), + I(ts[1]), + I(mo[0]), + I(mo[1]), + I(ms[0]), + I(ms[1]), + ]; + v.extend(p.color.iter().map(|f| F(*f))); + for row in &p.params { + v.extend(row.iter().map(|f| F(*f))); + } + v.extend([I(mpo[0]), I(mpo[1]), I(mps[0]), I(mps[1])]); + v.extend(p.extra.iter().map(|f| F(*f))); + // q0..q4: only `fs_layerbatch` reads them (`batch_op_words`). + v.extend((0..20).map(|_| F(0.0))); + v +} + +/// Most layers one `fs_layerbatch` pass blends: its own and the three more its record holds. +pub(crate) const BATCH: usize = 4; + +/// For each pass, how many passes from it on the executor draws as one `fs_layerbatch` pass +/// (1: the pass alone). A run starts at a `LayerBlend` pass over the whole chunk (no clip) that +/// isn't a gradient (whose parameters use the words the extra layers go in), and continues while +/// the next pass is a `LayerBlend` of an unmasked plain layer (no text gamma, no Dissolve) onto +/// exactly what the previous pass wrote, a slot nothing else reads before it is written again. +/// A run never ends in the slot it reads from. +/// +/// The runs depend on the plan alone, never on the prefix cache: a compiler may give a layer +/// other bits batched than drawn alone (FXC on D3D12 does), and reusing a prefix must stay exact +/// (#5286). The cache captures and resumes only at `run_starts` instead. +pub(crate) fn batch_runs(plan: &Plan<'_>) -> Vec { + let passes = &plan.passes; + let n = passes.len(); + let reads = |p: &plan::Pass<'_>, s: plan::Slot| [p.a, p.b, p.c, p.d].contains(&Some(s)); + // feeds_next[i]: what pass i writes is read by pass i + 1 alone. + let feeds_next: Vec = (0..n) + .map(|i| { + let (Some(this), Some(next)) = (passes.get(i), passes.get(i + 1)) else { return false }; + let dst = this.dst; + if next.a != Some(dst) || [next.b, next.c, next.d].contains(&Some(dst)) { + return false; + } + for later in passes.iter().skip(i + 2) { + // A copy into a slot keeps what lies outside its rect: that is a read too. + if reads(later, dst) || (later.dst == dst && later.kernel == Kernel::CopyRect) { + return false; + } + if later.dst == dst { + return true; + } + } + dst != plan.root + }) + .collect(); + let lead = |p: &plan::Pass<'_>| p.kernel == Kernel::LayerBlend && p.clip.is_none() && !p.gradient; + let extra = |p: &plan::Pass<'_>| lead(p) && p.mask.is_none() && p.flags & plan::F_TEXT_GAMMA == 0 && p.mode != photocraft_color::BlendMode::Dissolve; + (0..n) + .map(|i| { + let Some(first) = passes.get(i).filter(|p| lead(p)) else { return 1 }; + let (mut k, mut best) = (1, 1); + while k < BATCH && feeds_next.get(i + k - 1).copied().unwrap_or(false) && passes.get(i + k).is_some_and(extra) { + k += 1; + if passes.get(i + k - 1).is_some_and(|p| Some(p.dst) != first.a) { + best = k; + } + } + best + }) + .collect() +} + +/// For each pass and the end of the plan, whether the executor draws `runs` (`batch_runs`) so +/// that a pass starts there rather than inside a run. +pub(crate) fn run_starts(runs: &[usize]) -> Vec { + let mut starts = vec![false; runs.len() + 1]; + let mut i = 0; + while let Some(s) = starts.get_mut(i) { + *s = true; + i += runs.get(i).copied().unwrap_or(1).max(1); + } + starts +} + +/// The pipeline that draws `run` (passes `batch_runs` joined): `fs_layerbatch_normal` when every +/// layer blends Normal without text gamma outside Lab documents, else `fs_layerbatch`. +pub(crate) fn batch_kernel(run: &[plan::Pass<'_>]) -> Kernel { + let normal = |p: &plan::Pass<'_>| p.mode == photocraft_color::BlendMode::Normal && p.flags & (plan::F_TEXT_GAMMA | plan::F_LAB) == 0; + if run.iter().all(normal) { Kernel::LayerBatchNormal } else { Kernel::LayerBatch } +} + +/// Canvas rounded out to whole tiles. +pub(crate) fn tile_grid(canvas: Rect) -> Rect { + let t = TILE_SIZE; + Rect::new(canvas.x0.div_euclid(t) * t, canvas.y0.div_euclid(t) * t, (canvas.x1 + t - 1).div_euclid(t) * t, (canvas.y1 + t - 1).div_euclid(t) * t) +} + +pub(crate) fn write_tile(queue: &wgpu::Queue, r: &Resident, c: TileCoord, bytes: &[u8]) { + let tr = c.rect(); + let bpp = r.kind.bytes_per_pixel() as u32; + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &r.texture, + mip_level: 0, + origin: wgpu::Origin3d { x: (tr.x0 - r.region.x0) as u32, y: (tr.y0 - r.region.y0) as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(TILE_SIZE as u32 * bpp), rows_per_image: Some(TILE_SIZE as u32) }, + wgpu::Extent3d { width: TILE_SIZE as u32, height: TILE_SIZE as u32, depth_or_array_layers: 1 }, + ); +} + +/// Submit what `encoder` recorded and continue in a fresh one, then wait for the previous +/// intermediate submit (`last`), so at most two batches of uploads and evicted pages are in +/// flight. The web has no blocking wait and relies on the browser's own scheduling. +pub(crate) fn submit_batch( + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + health: Option<&DeviceHealth>, + timer: Option<&mut timing::GpuTimer>, + last: &mut Option, +) { + let mut done = std::mem::replace(encoder, device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") })); + if let Some(t) = timer { + // One refresh, several command buffers: the measurement spans all of them. + t.split(&mut done, encoder); + } + let prev = last.replace(queue.submit([done.finish()])); + #[cfg(not(target_arch = "wasm32"))] + if let Some(prev) = prev { + match health { + Some(h) => { + h.wait(device, Some(prev)); + } + None => { + let _ = device.poll(wgpu::PollType::Wait { submission_index: Some(prev), timeout: None }); + } + } + } + #[cfg(target_arch = "wasm32")] + let _ = (prev, health); +} diff --git a/crates/gpu/src/cells.rs b/crates/gpu/src/cells.rs new file mode 100644 index 0000000000..8d8a44ec97 --- /dev/null +++ b/crates/gpu/src/cells.rs @@ -0,0 +1,523 @@ +use super::batch::{batch_kernel, batch_op_words, op_words, submit_batch}; +use super::consts::{FLUSH_OPS, MAP32, STRIDE}; +use super::convert::{convert_tile, convert_tiles, keep_overlap, put_tiles, words}; +use super::kit::{Bound, FrameRes, texture_group, uniform_group}; +use super::paging::cell_rect; +use super::textures::{CachedPattern, Cell, ChunkOut, ResKey, Resident, ResidentRef, Stats, Tex, TexKind}; +use super::*; + +impl Compositor { + /// Bring the pages of `cell` that `plan` samples up to date and resolve its effect maps. + #[allow(clippy::too_many_arguments)] + fn bind_cell( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + doc: DocId, + plan: &Plan<'_>, + paged: &[bool], + cell: Cell, + fr: &FrameRes, + first_pass: usize, + stats: &mut Stats, + ) -> Bound { + let cr = cell_rect(cell, self.page); + let mut views: Vec<(Option, Option)> = Vec::with_capacity(plan.passes.len()); + let mut keys: Vec = Vec::new(); + let mut maps = Vec::with_capacity(plan.passes.len()); + for (i, p) in plan.passes.iter().enumerate() { + if i < first_pass { + views.push((None, None)); + maps.push(None); + continue; + } + let (ta, ma) = fr.areas.get(i).copied().unwrap_or((Rect::EMPTY, Rect::EMPTY)); + let tex = + p.tex.as_ref().and_then(|t| self.sync(device, queue, encoder, doc, (t.layer, t.role, cell), t.surface.get(), ta.intersect(&cr), stats)).map( + |(k, r)| { + keys.push(k); + (keys.len() - 1, r) + }, + ); + let mask = p + .mask + .as_ref() + .and_then(|m| self.sync(device, queue, encoder, doc, (m.layer, Role::Mask, cell), m.surface.get(), ma.intersect(&cr), stats)) + .map(|(k, r)| { + keys.push(k); + (keys.len() - 1, r) + }); + views.push((tex, mask)); + maps.push(p.map.and_then(|m| { + let f = plan.fx.get(m.fx)?; + let key = (f.layer.id, paged.get(m.fx).copied().unwrap_or(false).then_some(cell)); + let e = self.fx.get(&key)?; + if m.item == plan::SHAPE_MAP { + return Some((e.shape.view.clone(), e.region)); + } + let t = e.progs.get(m.item)?.maps.get(m.map)?.as_ref()?; + Some((t.view.clone(), e.region)) + })); + } + Bound { views, keys, maps } + } + + /// Run `plan` (drawn as `runs`, its `batch_runs`) over the `chunks` of one page cell + /// (document rects, at most a chunk square), handing each finished chunk to `sink`. + #[allow(clippy::too_many_arguments)] + pub(crate) fn run_cell( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + doc: DocId, + plan: &Plan<'_>, + runs: &[usize], + paged: &[bool], + cell: Cell, + fr: &FrameRes, + chunks: &[Rect], + checkpoint: Option, + stats: &mut Stats, + sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), + // The previous intermediate submit, when this refresh may submit in between. + batch: &mut Option<&mut Option>, + ) { + if chunks.is_empty() { + return; + } + // Chunks may hold different checkpoints: bind from the lowest one any of them resumes at. + let first_pass = checkpoint + .and_then(|_| chunks.iter().map(|c| self.prefix.restore_point(*c).map(|r| r.pass_end)).try_fold(usize::MAX, |m, p| Some(m.min(p?)))) + .unwrap_or(0); + let bound = self.bind_cell(device, queue, encoder, doc, plan, paged, cell, fr, first_pass, stats); + // A page couldn't be created: draw nothing with the pages missing (the caller ends the refresh). + if self.layer_alloc.is_some() { + return; + } + + // Chunk pool. + while self.pool.len() < plan.slots as usize { + let t = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_compose_chunk"), + size: wgpu::Extent3d { width: self.chunk, height: self.chunk, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: self.acc_format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_SRC + | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let v = t.create_view(&Default::default()); + self.pool.push((t, v)); + } + + // Uniforms: chunk records, then one record per pass. encode_scoped preflight checked + // the length, device capacity and dynamic offsets before any GPU work for this frame. + let op_base = chunks.len() as u64 * STRIDE; + let mut data = vec![0u8; (op_base + plan.passes.len() as u64 * STRIDE) as usize]; + for (i, c) in chunks.iter().enumerate() { + let w = words(&[I(c.x0), I(c.y0), I(c.width() as i32), I(c.height() as i32)]); + data[i * STRIDE as usize..][..w.len()].copy_from_slice(&w); + } + for (i, p) in plan.passes.iter().enumerate() { + if i < first_pass { + continue; + } + let (tex, mask) = bound.views[i]; + let map = bound.maps[i].as_ref().map(|(_, r)| *r); + let run = runs.get(i).copied().unwrap_or(1); + let w = if run > 1 { + let extras: Vec<_> = (i + 1..i + run).filter_map(|j| Some((plan.passes.get(j)?, bound.views.get(j).and_then(|v| v.0).map(|t| t.1)))).collect(); + batch_op_words(p, tex.map(|t| t.1), mask.map(|m| m.1), &extras) + } else { + op_words(p, tex.map(|t| t.1), mask.map(|m| m.1), map) + }; + let off = (op_base + i as u64 * STRIDE) as usize; + data[off..][..w.len()].copy_from_slice(&w); + } + let ubuf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("pc_compose_uniforms"), + size: data.len() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&ubuf, 0, &data); + let bg0 = uniform_group(device, &self.kit.bgl0, &ubuf); + + // Per-pass texture bind groups (chunk-independent: pool slots are reused per chunk). + let dummy = &self.kit.dummy; + let resident_views: Vec<&wgpu::TextureView> = bound.keys.iter().map(|k| self.residents.get(k).map_or(dummy, |r| &r.view)).collect(); + let mut bg1 = Vec::with_capacity(plan.passes.len()); + for (i, p) in plan.passes.iter().enumerate() { + if i < first_pass || p.kernel.entry().is_none() { + bg1.push(None); + continue; + } + let slot = |s: Option| s.map_or(dummy, |s| &self.pool[s as usize].1); + let (tex, mask) = &bound.views[i]; + let tv = tex.map_or(slot(p.d), |(k, _)| resident_views[k]); + let mv = mask.map_or(dummy, |(k, _)| resident_views[k]); + let lv = fr.luts.get(i).and_then(Option::as_ref).map_or(dummy, |(_, v)| v); + let map = bound.maps[i].as_ref().map_or(dummy, |(v, _)| v); + let pat = fr.patterns.get(i).and_then(Option::as_ref).unwrap_or(dummy); + let run = runs.get(i).copied().unwrap_or(1); + if run > 1 { + // The extra layers' pixels in tex_b, tex_c and map_tex (`batch_layer`). + let extra = |e: usize| bound.views.get(i + e).and_then(|v| v.0).map_or(dummy, |(k, _)| resident_views[k]); + bg1.push(Some(texture_group(device, &self.kit.bgl1, &[slot(p.a), extra(1), tv, mv, lv, extra(2), extra(3), pat]))); + continue; + } + bg1.push(Some(texture_group(device, &self.kit.bgl1, &[slot(p.a), slot(p.b), tv, mv, lv, slot(p.c), map, pat]))); + } + + for (ci, c) in chunks.iter().enumerate() { + let mut resume = 0; + if let Some(cp) = checkpoint.and_then(|_| self.prefix.restore_point(*c)) + && let Some((dst, _)) = self.pool.get(cp.slot as usize) + && self.prefix.copy_out(encoder, *c, dst) + { + resume = cp.pass_end; + stats.prefix_hits = stats.prefix_hits.saturating_add(1); + stats.prefix_passes_skipped = stats.prefix_passes_skipped.saturating_add(resume); + } + // Passes drawn inside the previous `fs_layerbatch` pass. + let mut batched_to = 0; + for (i, p) in plan.passes.iter().enumerate() { + if i < resume || i < batched_to { + continue; + } + // Chunk textures, uniforms and bind groups outlive the submit, and the queue + // keeps the order, so a chunk may continue in the next command buffer. + if self.recorded >= FLUSH_OPS + && let Some(last) = batch.as_deref_mut() + { + submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), last); + self.staged = 0; + self.recorded = 0; + stats.flushes += 1; + if self.fault().is_some() { + return; + } + } + // Also after resuming from a lower checkpoint: the chunk moves up to this one. + if resume < i + && let Some(cp) = checkpoint.filter(|cp| cp.pass_end == i) + && let Some((src, _)) = self.pool.get(cp.slot as usize) + { + self.prefix.capture(device, encoder, *c, src, cp); + } + let scissor = match p.clip { + Some(clip) => { + let r = clip.intersect(c); + if r.is_empty() { + continue; + } + Rect::new(r.x0 - c.x0, r.y0 - c.y0, r.x1 - c.x0, r.y1 - c.y0) + } + None => Rect::new(0, 0, c.width() as i32, c.height() as i32), + }; + match p.kernel { + Kernel::CopyRect | Kernel::CopyFull => { + // The planner always gives copies a source. + let Some(a) = p.a else { continue }; + let src = &self.pool[a as usize].0; + let dst = &self.pool[p.dst as usize].0; + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { + texture: src, + mip_level: 0, + origin: wgpu::Origin3d { x: scissor.x0 as u32, y: scissor.y0 as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyTextureInfo { + texture: dst, + mip_level: 0, + origin: wgpu::Origin3d { x: scissor.x0 as u32, y: scissor.y0 as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::Extent3d { width: scissor.width(), height: scissor.height(), depth_or_array_layers: 1 }, + ); + self.recorded += 1; + continue; + } + _ => {} + } + self.recorded += 1; + // A run draws as one pass into the slot its last layer writes. + let run = runs.get(i).copied().unwrap_or(1); + let (kernel, dst) = match plan.passes.get(i + run - 1) { + Some(last) if run > 1 => { + batched_to = i + run; + stats.layers_batched = stats.layers_batched.saturating_add(run - 1); + let kernel = plan.passes.get(i..i + run).map_or(Kernel::LayerBatch, batch_kernel); + if kernel == Kernel::LayerBatchNormal { + stats.normal_batches = stats.normal_batches.saturating_add(1); + } + (kernel, last.dst) + } + _ => (p.kernel, p.dst), + }; + let target = &self.pool[dst as usize].1; + let clear = p.kernel == Kernel::Clear; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("pc_compose_pass"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: target, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: if clear { wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT) } else { wgpu::LoadOp::Load }, + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + if clear { + continue; + } + pass.set_pipeline(&self.kit.pipelines[&(kernel, self.acc_format)]); + pass.set_scissor_rect(scissor.x0 as u32, scissor.y0 as u32, scissor.width(), scissor.height()); + pass.set_bind_group(0, &bg0, &[(ci as u64 * STRIDE) as u32, (op_base + i as u64 * STRIDE) as u32]); + pass.set_bind_group(1, bg1[i].as_ref(), &[]); + pass.draw(0..3, 0..1); + } + if resume < plan.passes.len() + && let Some(cp) = checkpoint.filter(|cp| cp.pass_end == plan.passes.len()) + && let Some((src, _)) = self.pool.get(cp.slot as usize) + { + self.prefix.capture(device, encoder, *c, src, cp); + } + let (t, v) = &self.pool[plan.root as usize]; + sink(encoder, ChunkOut { rect: *c, texture: t, view: v }); + } + } + + /// Upload changed tiles of `surface` within `region` (its tile area inside one page cell); + /// returns the resident key and its region (x, y, w, h). + #[allow(clippy::too_many_arguments)] + fn sync( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + doc: DocId, + key: ResKey, + surface: &Surface, + region: Rect, + stats: &mut Stats, + ) -> Option<(ResKey, [i32; 4])> { + // An earlier page of this cell didn't fit: the refresh ends after the cell anyway. + if region.is_empty() || self.layer_alloc.is_some() { + return None; + } + let format = surface.format(); + let kind = TexKind::for_surface(key.1, format); + let cmyk = if format.mode == photocraft_color::ColorMode::Cmyk { self.cmyk } else { 0 }; + let default_pixel = surface.default_pixel(); + let default_bits: Vec = default_pixel.iter().map(|v| v.to_bits()).collect(); + let stale = self + .residents + .get(&key) + .is_none_or(|r| r.region != region || r.kind != kind || r.format != format || r.cmyk != cmyk || r.default_bits != default_bits); + if stale { + let desc = wgpu::TextureDescriptor { + label: Some("pc_compose_layer"), + size: wgpu::Extent3d { width: region.width(), height: region.height(), depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: kind.format(), + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }; + let bytes = region.width() as u64 * region.height() as u64 * kind.bytes_per_pixel() as u64; + let texture = self.create_layer_texture(device, &desc, key, bytes, stats)?; + let view = texture.create_view(&Default::default()); + let default_nonzero = default_pixel.iter().any(|v| *v != 0.0); + let mut r = Resident { + texture, + view, + region, + kind, + format, + tiles: HashMap::new(), + default_nonzero, + default_bits: default_bits.clone(), + doc, + last_used: 0, + stamp: 0, + cmyk, + ordered: false, + }; + // Only the region moved (painting past a layer's tiles grows it): keep the texels the + // old texture already holds instead of converting and uploading every tile again. + let kept = self.residents.remove(&key).map_or(Rect::EMPTY, |old| keep_overlap(device, queue, &old, &mut r)); + // A new layer whose tiles another resident already holds (a duplicate shares its + // source's tiles) starts as a GPU copy of that texture. Duplicating a 20 MP photo + // converted and uploaded every tile again. + let shares = + |o: &Resident| region.tiles().filter(|c| surface.tile(*c).is_some_and(|t| o.tiles.get(c).is_some_and(|ot| Arc::ptr_eq(ot, t)))).count(); + let donor = self + .residents + .iter() + .filter(|(k, o)| k.1 == key.1 && o.region == region && o.kind == kind && o.format == format && o.cmyk == cmyk && o.default_bits == default_bits) + .map(|(k, o)| (shares(o), *k)) + .filter(|(n, _)| *n > 0) + .max_by_key(|(n, _)| *n); + if kept.is_empty() + && let Some((n, o)) = donor.and_then(|(n, k)| Some((n, self.residents.get_mut(&k)?))) + { + // Recorded in the frame's encoder, after the writes and copies that brought the + // donor up to date ([`keep_overlap`]'s own submission would run before those). + o.ordered = true; + encoder.copy_texture_to_texture( + o.texture.as_image_copy(), + r.texture.as_image_copy(), + wgpu::Extent3d { width: region.width(), height: region.height(), depth_or_array_layers: 1 }, + ); + r.tiles = o.tiles.clone(); + r.ordered = true; + stats.tiles_shared += n; + } else { + // A new texture starts zeroed: write the tiles that are present, and the default + // pixel where they are missing if it isn't zero. Coordinates sharing a tile (a + // solid fill, the default) take one upload and GPU copies (#1774). Kept tiles are + // brought up to date below, like those of a resident that didn't move. + let mut present = Vec::new(); + let mut missing = Vec::new(); + for c in region.tiles().filter(|c| !kept.contains_rect(&c.rect())) { + match surface.tile(c) { + Some(t) => present.push((c, t.clone())), + None if default_nonzero => missing.push(c), + None => {} + } + } + if !missing.is_empty() { + let bytes = convert_tile(surface, None, kind, TileCoord::new(0, 0)); + self.staged += put_tiles(device, queue, encoder, &r, &missing, &bytes); + } + let staged = &mut self.staged; + convert_tiles(surface, present, kind, |t, cs, bytes| { + *staged += put_tiles(device, queue, encoder, &r, cs, bytes); + for &c in cs { + stats.tiles_uploaded += 1; + stats.bytes_uploaded += bytes.len(); + r.tiles.insert(c, t.clone()); + } + }); + } + // Tiles the donor held that this surface doesn't, or holds differently, are fixed up + // by the pass over the region below. + self.residents.insert(key, r); + } + // Present: inserted above when it was missing or stale. + let r = self.residents.get_mut(&key)?; + r.last_used = self.frame; + r.stamp = self.stamp; + r.doc = doc; + let mut changed = Vec::new(); + let mut gone = Vec::new(); + for c in region.tiles() { + match surface.tile(c) { + Some(t) => { + if !r.tiles.get(&c).is_some_and(|old| Arc::ptr_eq(old, t)) { + changed.push((c, t.clone())); + } + } + None => { + if r.tiles.remove(&c).is_some() { + gone.push(c); + } + } + } + } + if !gone.is_empty() { + // A tile that went away reads as the default pixel again. + let bytes = if r.default_nonzero { + convert_tile(surface, None, kind, TileCoord::new(0, 0)) + } else { + vec![0u8; (TILE_SIZE * TILE_SIZE) as usize * kind.bytes_per_pixel()] + }; + self.staged += put_tiles(device, queue, encoder, r, &gone, &bytes); + } + let staged = &mut self.staged; + convert_tiles(surface, changed, kind, |t, cs, bytes| { + *staged += put_tiles(device, queue, encoder, r, cs, bytes); + for &c in cs { + stats.tiles_uploaded += 1; + stats.bytes_uploaded += bytes.len(); + r.tiles.insert(c, t.clone()); + } + }); + Some((key, [region.x0, region.y0, region.width() as i32, region.height() as i32])) + } + + /// Premultiplied RGBA32F texture of a pattern as it paints in the document's mode (cached by + /// pixel identity and mode). + pub(crate) fn pattern_view(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, pat: &Pattern) -> wgpu::TextureView { + let fp = pat.surface.tiles().fold((pat.width as u64) << 32 | pat.height as u64, |acc, (c, t)| { + acc.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ (Arc::as_ptr(t) as usize as u64) ^ ((c.tx as u64) << 20) ^ c.ty as u64 + }); + let mode = self.pattern_mode; + let key = format!("{}\u{0}{}\u{0}{mode:?}", pat.id, pat.name); + let format = pat.surface.format(); + // Unstored tiles read the default pixel, interpreted in the source format. + let default_bits: Vec = pat.surface.default_pixel().iter().map(|v| v.to_bits()).collect(); + let (doc, last_used) = (self.pattern_doc, self.frame); + if let Some(cached) = self.patterns.get_mut(&key) + && cached.fingerprint == fp + && cached.format == format + && cached.default_bits == default_bits + { + cached.doc = doc; + cached.last_used = last_used; + return cached.texture.view.clone(); + } + let (w, h) = (pat.width, pat.height); + let px = photocraft_compose::pattern::pattern_rgba(pat, mode); + let bytes: Vec = px.iter().flat_map(|q| [q[0] * q[3], q[1] * q[3], q[2] * q[3], q[3]]).flat_map(f32::to_le_bytes).collect(); + let t = Tex::new(device, "pc_pattern", w, h, wgpu::TextureFormat::Rgba32Float, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + &bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 16), rows_per_image: Some(h) }, + wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + ); + let v = t.view.clone(); + let bytes = u64::from(w.max(1)) * u64::from(h.max(1)) * 16; + self.patterns.insert(key, CachedPattern { fingerprint: fp, format, default_bits, texture: t, doc, last_used, bytes }); + v + } + + /// An R32F temporary at least `region`-sized (the smallest that fits) not in `taken`. + /// Stages only read what they wrote, inside the region, so a larger one is as good; page + /// windows of different sizes share them. + pub(crate) fn temp(&mut self, device: &wgpu::Device, region: Rect, taken: &[wgpu::TextureView]) -> wgpu::TextureView { + let (w, h) = (region.width(), region.height()); + let frame = self.frame; + let fit = self + .temps + .iter_mut() + .filter(|(t, _)| { + let s = t.texture.size(); + s.width >= w && s.height >= h && !taken.contains(&t.view) + }) + .min_by_key(|(t, _)| t.texture.size().width as u64 * t.texture.size().height as u64); + if let Some((t, used)) = fit { + *used = frame; + return t.view.clone(); + } + let t = Tex::map(device, "pc_fx_temp", region, MAP32); + let v = t.view.clone(); + self.temps.push((t, frame)); + v + } +} diff --git a/crates/gpu/src/consts.rs b/crates/gpu/src/consts.rs new file mode 100644 index 0000000000..40081a55c8 --- /dev/null +++ b/crates/gpu/src/consts.rs @@ -0,0 +1,54 @@ +/// Accumulator format for intermediate buffers. Full float: discontinuous operations +/// (Posterize, Threshold, Hard Mix, Dissolve) must land on the same side of their thresholds as +/// the CPU reference, and Color Burn/Dodge amplify input error. +pub const ACC_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float; + +// default accumulation format; `preferred_acc_format` downgrades to Rgba16Float where 32-bit float isn't renderable +/// Effect intermediates (distances, blurs) and layer shapes. +pub(crate) const MAP32: wgpu::TextureFormat = wgpu::TextureFormat::R32Float; + +/// Final effect coverage maps (0..1; half precision is ~1/4000). +pub(crate) const MAP16: wgpu::TextureFormat = wgpu::TextureFormat::R16Float; + +/// Side of the square chunks the canvas is processed in. +pub const CHUNK: u32 = 1024; + +pub(crate) const STRIDE: u64 = 256; + +pub(crate) const CHUNK_UNIFORM: u64 = 16; + +pub(crate) const OP_UNIFORM: u64 = 256; + +/// GPU memory the effect-map cache may hold before evicting layers not drawn this frame. +pub const FX_BUDGET: usize = 1536 << 20; + +/// Largest side of the square pages layer surfaces are stored in on the GPU (smaller when the +/// device's texture limit is). A chunk only binds the pages of the cell it lies in, so layers of +/// any size composite on the GPU. +pub const PAGE: u32 = 2048; + +/// GPU memory resident layer pages may hold before the least recently used are evicted. +pub const RESIDENT_BUDGET: u64 = 4 << 30; + +/// GPU memory pattern textures may hold before the least recently painted are dropped (those the +/// current frame paints with always stay). +pub const PATTERN_BUDGET: u64 = 256 << 20; + +/// A pattern texture no frame has painted with for this many frames is dropped. +pub const PATTERN_IDLE_FRAMES: u64 = 240; + +/// Uploads (bytes) [`Compositor::render`] stages before submitting the work recorded so far, so +/// a refresh of a huge document never holds all its uploads in staging memory at once. +pub(crate) const FLUSH_BYTES: u64 = 512 << 20; + +/// Pass pixels (chunk pixels × passes) [`Compositor::render`] records before submitting: one +/// command buffer holding a whole huge refresh can run for seconds, long enough for the OS to +/// reset the GPU. +pub(crate) const FLUSH_WORK: u64 = 1 << 30; + +/// Copies and render passes [`Compositor::render`] records before submitting. wgpu opens up to +/// two backend command buffers for each (a render pass and its barrier pre-pass), and Metal +/// treats more than 4096 outstanding ones as a lost device: a refresh of a document with a few +/// hundred layers reached that inside a single page cell (P12, "pc_compose_uniforms is +/// invalid"), where the work and byte limits above never trigger. +pub(crate) const FLUSH_OPS: u32 = 1000; diff --git a/crates/gpu/src/convert.rs b/crates/gpu/src/convert.rs new file mode 100644 index 0000000000..6b0a7e6f98 --- /dev/null +++ b/crates/gpu/src/convert.rs @@ -0,0 +1,371 @@ +use super::batch::write_tile; +use super::textures::{Resident, TexKind}; +use super::*; + +/// Distinct tiles converted per parallel batch: bounds the converted bytes held at once (64 tiles +/// of a 16-bit page are 32 MiB). +pub(crate) const CONVERT_BATCH: usize = 64; + +/// Write the same tile `bytes` at every coordinate in `cs` of resident `r`; returns the bytes +/// staged. Several coordinates (a solid fill or a cleared area shares one tile) get one upload to +/// a scratch tile and GPU copies from it: writing each one from the CPU sent 387 MB per refresh +/// of a filled 50 MP 16-bit page (#1774). +pub(crate) fn put_tiles(device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, r: &Resident, cs: &[TileCoord], bytes: &[u8]) -> u64 { + if let [c] = cs + && !r.ordered + { + write_tile(queue, r, *c, bytes); + return bytes.len() as u64; + } + if cs.is_empty() { + return 0; + } + let extent = wgpu::Extent3d { width: TILE_SIZE as u32, height: TILE_SIZE as u32, depth_or_array_layers: 1 }; + // Its own texture per call: queued writes land before the encoder runs, so a shared scratch + // would hold only the last tile by then. + let scratch = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_tile_scratch"), + size: extent, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: r.kind.format(), + usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &scratch, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + bytes, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(TILE_SIZE as u32 * r.kind.bytes_per_pixel() as u32), + rows_per_image: Some(TILE_SIZE as u32), + }, + extent, + ); + for c in cs { + let tr = c.rect(); + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { texture: &scratch, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyTextureInfo { + texture: &r.texture, + mip_level: 0, + origin: wgpu::Origin3d { x: (tr.x0 - r.region.x0) as u32, y: (tr.y0 - r.region.y0) as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + extent, + ); + } + bytes.len() as u64 +} + +/// Copy the texels `old` holds inside the region of its replacement `new` (same texel kind, +/// format and default pixel; only the region moved) and carry over the tiles they show, so only +/// tiles outside the overlap or changed since need uploading. Returns the kept (tile-aligned) +/// rect; empty when nothing can be kept. +pub(crate) fn keep_overlap(device: &wgpu::Device, queue: &wgpu::Queue, old: &Resident, new: &mut Resident) -> Rect { + let same = old.kind == new.kind && old.format == new.format && old.cmyk == new.cmyk && old.default_bits == new.default_bits; + let k = old.region.intersect(&new.region); + if !same || k.is_empty() { + return Rect::EMPTY; + } + // Its own submission: tile writes go through the queue and land at the start of the next + // submit, before anything in the frame's encoder, so a copy recorded there would overwrite + // the tiles written after it with the old texels. + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose_keep") }); + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { + texture: &old.texture, + mip_level: 0, + origin: wgpu::Origin3d { x: (k.x0 - old.region.x0) as u32, y: (k.y0 - old.region.y0) as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyTextureInfo { + texture: &new.texture, + mip_level: 0, + origin: wgpu::Origin3d { x: (k.x0 - new.region.x0) as u32, y: (k.y0 - new.region.y0) as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::Extent3d { width: k.width(), height: k.height(), depth_or_array_layers: 1 }, + ); + queue.submit([encoder.finish()]); + new.tiles = old.tiles.iter().filter(|(c, _)| k.contains_rect(&c.rect())).map(|(c, t)| (*c, t.clone())).collect(); + k +} + +/// Convert `tiles` of `surface` to `kind` texels and hand each distinct tile, the coordinates +/// sharing it and its bytes to `put`. Each distinct tile is converted once (a solid fill shares +/// one `Arc` across every coordinate it covers), in parallel batches. Converting every tile one +/// after another on the UI thread froze a 50 MP 16-bit document for about 1.4 s after a +/// full-canvas fill (#1774). Returns how many tiles were converted. +pub(crate) fn convert_tiles( + surface: &Surface, + tiles: Vec<(TileCoord, Arc)>, + kind: TexKind, + mut put: impl FnMut(&Arc, &[TileCoord], &[u8]), +) -> usize { + let mut groups: Vec<(Arc, Vec)> = Vec::new(); + let mut index: HashMap<*const Tile, usize> = HashMap::new(); + for (c, t) in tiles { + match index.get(&Arc::as_ptr(&t)).and_then(|&i| groups.get_mut(i)) { + Some(g) => g.1.push(c), + None => { + index.insert(Arc::as_ptr(&t), groups.len()); + groups.push((t, vec![c])); + } + } + } + // CMYK and Lab tiles convert pixel by pixel through a colour transform (a CMYK tile took + // ~5 ms on one thread, the whole of a brush dab's refresh on an A4 CMYK page, #5108): those + // go in bands of rows, so even the one tile a dab touches spreads over the threads. Workers + // don't inherit this thread's CMYK profile scope, so each band enters it. + let bands = if colour_managed(&surface.format(), kind) { TILE_SIZE / MANAGED_BAND_ROWS } else { 1 }; + let space = photocraft_color::convert::active_cmyk_space(); + for batch in groups.chunks(CONVERT_BATCH) { + // A tile's content is the same at every coordinate sharing it: convert it at the first. + let jobs: Vec<_> = batch.iter().filter_map(|(t, cs)| cs.first().map(|c| (t, *c))).flat_map(|(t, c)| (0..bands).map(move |b| (t, c, b))).collect(); + let parts = fx::par_map(jobs, |(t, c, b)| { + photocraft_color::convert::with_cmyk_space(space.as_ref(), || { + if bands == 1 { + return convert_tile(surface, Some(t), kind, c); + } + let r = c.rect(); + let y0 = r.y0 + b * MANAGED_BAND_ROWS; + convert_rows(surface, Some(t), kind, Rect::new(r.x0, y0, r.x1, y0 + MANAGED_BAND_ROWS)) + }) + }); + for ((t, cs), bytes) in batch.iter().zip(parts.chunks(bands as usize)) { + // One part (every format but CMYK and Lab) goes through as is: no copy per tile. + match bytes { + [one] => put(t, cs, one), + _ => put(t, cs, &bytes.concat()), + } + } + } + groups.len() +} + +/// Rows per parallel band of a colour-managed (CMYK, Lab) tile conversion. +const MANAGED_BAND_ROWS: i32 = 16; + +/// Whether `fmt` pixels reach `kind` texels through a per-pixel colour transform (CMYK, Lab). +pub(crate) fn colour_managed(fmt: &PixelFormat, kind: TexKind) -> bool { + use photocraft_color::ColorMode; + matches!(kind, TexKind::Rgba8 | TexKind::Rgba16F) && matches!(fmt.mode, ColorMode::Cmyk | ColorMode::Lab) +} + +/// Tile pixels in the texture's format. `tile = None` gives the default pixel everywhere. +pub(crate) fn convert_tile(surface: &Surface, tile: Option<&Arc>, kind: TexKind, c: TileCoord) -> Vec { + if let (Some(t), TexKind::Rgba8Direct | TexKind::R8Direct) = (tile, kind) { + return t.bytes().to_vec(); + } + let fmt = surface.format(); + if let (Some(t), TexKind::Rgba16F) = (tile, kind) + && let Some(out) = rgb_gray16_to_f16(&fmt, t.bytes()).or_else(|| rgb_gray32_to_f16(&fmt, t.bytes())) + { + return out; + } + convert_rows(surface, tile, kind, c.rect()) +} + +/// [`convert_tile`]'s general path for `rect` (rows of one tile): each pixel through +/// `photocraft_raster::to_rgba`. A run of identical pixels (the transparent or flat areas around a +/// brush dab) is converted once: the same samples give the same texels. +fn convert_rows(surface: &Surface, tile: Option<&Arc>, kind: TexKind, rect: Rect) -> Vec { + let n = rect.width() as usize * rect.height() as usize; + let fmt = surface.format(); + let ch = fmt.channels(); + let raw: Vec = match tile { + Some(_) => surface.read_region(rect), + None => surface.default_pixel().repeat(n), + }; + let mut out = Vec::with_capacity(n * kind.bytes_per_pixel()); + // The previous pixel and its colour. + let mut last: Option<(usize, [f32; 4])> = None; + for (i, px) in raw.chunks_exact(ch).enumerate() { + let mut rgba = || -> [f32; 4] { + if let Some((j, v)) = last + && raw.get(j * ch..j * ch + ch).is_some_and(|p| p.iter().zip(px).all(|(a, b)| a.to_bits() == b.to_bits())) + { + return v; + } + let v = photocraft_raster::to_rgba(&fmt, px); + last = Some((i, v)); + v + }; + match kind { + TexKind::Rgba8Direct | TexKind::Rgba8 => { + let v = rgba(); + out.extend(v.map(|x| (x.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)); + } + TexKind::Rgba16F => { + let v = rgba(); + for x in v { + out.extend(f32_to_f16(x).to_le_bytes()); + } + } + TexKind::R8Direct => out.push((px[0].clamp(0.0, 1.0) * 255.0 + 0.5) as u8), + TexKind::R16F => out.extend(f32_to_f16(px[0]).to_le_bytes()), + TexKind::R32F => out.extend(px[0].to_le_bytes()), + } + } + out +} + +/// RGBA16F texels of a 16-bit RGB or grayscale tile, through a table of every 16-bit sample's +/// half: the same bytes as the general path at a fraction of its cost (a 50 MP 16-bit refresh +/// converts dozens of tiles). `None` for other formats. +pub(crate) fn rgb_gray16_to_f16(fmt: &PixelFormat, bytes: &[u8]) -> Option> { + use photocraft_color::ColorMode; + static HALF: std::sync::OnceLock> = std::sync::OnceLock::new(); + if fmt.sample != SampleType::U16 { + return None; + } + let gray = match fmt.mode { + ColorMode::Rgb => false, + ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => true, + _ => return None, + }; + let half = HALF.get_or_init(|| (0..=u16::MAX).map(|v| f32_to_f16(v as f32 / 65535.0)).collect()); + let one = f32_to_f16(1.0).to_le_bytes(); + let ch = fmt.channels(); + let mut out = Vec::with_capacity((TILE_SIZE * TILE_SIZE) as usize * 8); + for px in bytes.chunks_exact(ch * 2) { + let h = |i: usize| -> [u8; 2] { + let v = px.get(i * 2..i * 2 + 2).map_or(0, |b| u16::from_ne_bytes([b[0], b[1]])); + half.get(v as usize).copied().unwrap_or(0).to_le_bytes() + }; + let (r, g, b) = if gray { (h(0), h(0), h(0)) } else { (h(0), h(1), h(2)) }; + let a = if fmt.alpha { h(ch - 1) } else { one }; + out.extend_from_slice(&r); + out.extend_from_slice(&g); + out.extend_from_slice(&b); + out.extend_from_slice(&a); + } + Some(out) +} + +/// RGBA16F texels of a 32-bit float RGB or grayscale tile, straight from its samples: the same +/// bytes as the general path without decoding the tile into a float buffer and converting it +/// pixel by pixel (a brush dab on a 32-bit layer re-uploads the tiles it touched). `None` for +/// other formats. +pub(crate) fn rgb_gray32_to_f16(fmt: &PixelFormat, bytes: &[u8]) -> Option> { + use photocraft_color::ColorMode; + if fmt.sample != SampleType::F32 { + return None; + } + let gray = match fmt.mode { + ColorMode::Rgb => false, + ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => true, + _ => return None, + }; + let one = f32_to_f16(1.0).to_le_bytes(); + let ch = fmt.channels(); + let mut out = Vec::with_capacity((TILE_SIZE * TILE_SIZE) as usize * 8); + for px in bytes.chunks_exact(ch * 4) { + let h = |i: usize| -> [u8; 2] { + let v = px.get(i * 4..i * 4 + 4).map_or(0.0, |b| f32::from_ne_bytes([b[0], b[1], b[2], b[3]])); + f32_to_f16(v).to_le_bytes() + }; + let (r, g, b) = if gray { + let v = h(0); + (v, v, v) + } else { + (h(0), h(1), h(2)) + }; + let a = if fmt.alpha { h(ch - 1) } else { one }; + out.extend_from_slice(&r); + out.extend_from_slice(&g); + out.extend_from_slice(&b); + out.extend_from_slice(&a); + } + Some(out) +} + +pub(crate) fn lut_texture(device: &wgpu::Device, queue: &wgpu::Queue, rows: &[[f32; 4096]]) -> (wgpu::Texture, wgpu::TextureView) { + let t = device.create_texture(&wgpu::TextureDescriptor { + label: Some("pc_compose_lut"), + size: wgpu::Extent3d { width: 4096, height: rows.len() as u32, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R32Float, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let bytes: Vec = rows.iter().flat_map(|r| r.iter().flat_map(|v| v.to_le_bytes())).collect(); + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &t, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + &bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(4096 * 4), rows_per_image: Some(rows.len() as u32) }, + wgpu::Extent3d { width: 4096, height: rows.len() as u32, depth_or_array_layers: 1 }, + ); + let v = t.create_view(&Default::default()); + (t, v) +} + +#[derive(Clone, Copy)] +pub(crate) enum W { + I(i32), + U(u32), + F(f32), +} + +pub(crate) fn words(v: &[W]) -> Vec { + v.iter() + .flat_map(|w| match w { + I(i) => i.to_le_bytes(), + U(u) => u.to_le_bytes(), + F(f) => f.to_le_bytes(), + }) + .collect() +} + +/// IEEE half from f32 (round to nearest even; overflow → inf). +pub fn f32_to_f16(x: f32) -> u16 { + let b = x.to_bits(); + let sign = ((b >> 16) & 0x8000) as u16; + let exp = ((b >> 23) & 0xff) as i32; + let man = b & 0x7f_ffff; + if exp == 0xff { + return sign | 0x7c00 | if man != 0 { 0x200 } else { 0 }; + } + let e = exp - 127 + 15; + if e >= 0x1f { + return sign | 0x7c00; + } + if e <= 0 { + if e < -10 { + return sign; + } + let m = man | 0x80_0000; + let shift = (14 - e) as u32; + let half = 1u32 << (shift - 1); + let rounded = (m + half - 1 + ((m >> shift) & 1)) >> shift; + return sign | rounded as u16; + } + let mut h = ((e as u32) << 10) | (man >> 13); + let rest = man & 0x1fff; + if rest > 0x1000 || (rest == 0x1000 && (h & 1) == 1) { + h += 1; + } + sign | h as u16 +} + +/// f32 from IEEE half. +pub fn f16_to_f32(h: u16) -> f32 { + let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; + let exp = ((h >> 10) & 0x1f) as i32; + let man = (h & 0x3ff) as f32; + match exp { + 0 => sign * man * 2f32.powi(-24), + 0x1f => { + if man == 0.0 { + sign * f32::INFINITY + } else { + f32::NAN + } + } + e => sign * (1.0 + man / 1024.0) * 2f32.powi(e - 15), + } +} diff --git a/crates/gpu/src/encode.rs b/crates/gpu/src/encode.rs new file mode 100644 index 0000000000..037a4cc80d --- /dev/null +++ b/crates/gpu/src/encode.rs @@ -0,0 +1,423 @@ +use super::batch::{batch_runs, run_starts, submit_batch, tile_grid}; +use super::consts::{FLUSH_BYTES, FLUSH_OPS, FLUSH_WORK, PATTERN_IDLE_FRAMES}; +use super::convert::lut_texture; +use super::kit::FrameRes; +use super::paging::{OVER_BUDGET, cell_rect, first_error, grid_rect_count, grid_rects, lru_victims, scoped_work, uniform_buffer_len}; +use super::textures::{ChunkOut, FxKey, ResKey, Resident, Stats}; +use super::*; + +impl Compositor { + /// Composite `region` of `doc`. Each finished chunk is passed to `sink` while its encoder is + /// still open; the chunk texture is reused afterwards, so the sink must record any copies + /// or passes that read it into the given encoder. Submits the work before returning; a + /// refresh of a huge document also submits in between (the sink may be handed a new + /// encoder), so its uploads and evicted pages never pile up in memory. + pub fn render( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + doc: &Document, + region: Rect, + mut sink: impl FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), + ) -> Result { + let result = scoped_work(device, self.health.clone(), || { + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") }); + if self.timer.as_ref().is_some_and(timing::GpuTimer::busy) { + // The readback map completes on a poll. The app polls every frame, but a + // non-blocking poll here keeps the measurements coming whatever the caller does. + match &self.health { + Some(h) => h.poll(device), + None => { + let _ = device.poll(wgpu::PollType::Poll); + } + } + } + // Whatever came back since the last render travels out with this one's stats, so + // nothing has to reach back into the compositor for it afterwards. + let landed = self.timer.as_mut().and_then(timing::GpuTimer::take); + if let Some(t) = &mut self.timer { + let r = region.intersect(&doc.bounds()); + t.start(&mut encoder, r.width() as u64 * r.height() as u64); + } + let mut stats = self.encode_inner(device, queue, &mut encoder, doc, region, &mut sink, true); + if let Ok(s) = &mut stats { + s.gpu_time = landed; + } + if let Some(t) = &mut self.timer { + // A refresh that failed part way measures nothing: its spans describe work the + // caller is about to redo on the CPU. + match stats { + Ok(_) => t.finish(&mut encoder), + Err(_) => { + t.cancel(); + // The refresh is lost, but a measurement that came back with it is not: + // hand it to the next render rather than drop it on the fallback path. + if let Some(landed) = landed { + t.restore(landed); + } + } + } + } + let stats = stats?; + queue.submit([encoder.finish()]); + if let Some(t) = &mut self.timer { + t.submitted(); + } + Ok(stats) + }); + if result.is_err() { + self.discard_failed_work(); + } + result + } + + /// Like [`Self::render`] but records into `encoder` without submitting. + pub fn encode( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + doc: &Document, + region: Rect, + sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), + ) -> Result { + let result = scoped_work(device, self.health.clone(), || self.encode_inner(device, queue, encoder, doc, region, sink, false)); + if result.is_err() { + self.discard_failed_work(); + } + result + } + + fn discard_failed_work(&mut self) { + // Cache metadata advances while recording. A failed encoder may never execute its + // texture uploads or effect maps, so none of those cached pixels can be trusted. + self.prefix.clear(); + self.residents.clear(); + self.fx.clear(); + self.patterns.clear(); + self.temps.clear(); + self.pool.clear(); + } + + #[allow(clippy::too_many_arguments)] + fn encode_inner( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + doc: &Document, + region: Rect, + sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), + flush: bool, + ) -> Result { + if let Some(f) = self.fault() { + return Err(Unsupported(f.to_string())); + } + // CMYK layers convert through the document's own CMYK profile (uploads and plan colours). + let space = photocraft_compose::cmyk_space(doc); + self.cmyk = space.as_ref().map_or(0, |s| s.id); + photocraft_color::convert::with_cmyk_space(space.as_ref(), || self.encode_scoped(device, queue, encoder, doc, region, sink, flush)) + } + + #[allow(clippy::too_many_arguments)] + fn encode_scoped( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + doc: &Document, + region: Rect, + sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), + flush: bool, + ) -> Result { + let canvas = doc.bounds(); + let region = region.intersect(&canvas); + let plan = plan(doc)?; + self.check_fx(doc, &plan)?; + self.pattern_mode = doc.pixel_format().mode; + self.pattern_doc = doc.id; + let mut stats = Stats { passes: plan.passes.len(), slots: plan.slots, ..Default::default() }; + if region.is_empty() { + return Ok(stats); + } + let page = self.page; + let mut cells = grid_rects(region, page); + // Check every actual page cell before uploads, submissions or sink output. A later + // cell can need more chunk records than the first; a failure must leave the device healthy. + let buffer_limit = device.limits().max_buffer_size; + for part in &cells { + uniform_buffer_len(grid_rect_count(*part, self.chunk)?, plan.passes.len(), buffer_limit)?; + } + if self.frame == 0 { + // The first submission after device creation is dropped on some drivers (RADV), + // which would render the first frame black; land it on an empty buffer instead. + queue.submit(std::iter::empty::()); + } + self.frame += 1; + self.stamp += 1; + self.staged = 0; + self.recorded = 0; + self.layer_alloc = None; + self.admit_freed = 0; + + // Only render owns submission. A caller may discard encode's command buffer, so it + // cannot establish (or consume) a checkpoint whose GPU copy might never execute. + // Runs of plain layers drawn as one pass each (`fs_layerbatch`). The grouping is the same + // for every render of this plan, so a layer's bits don't depend on the cache: renders + // capture and resume only where a run starts. + let runs = batch_runs(&plan); + let checkpoint = if flush { + let starts = run_starts(&runs); + let resumable: Vec<_> = plan.checkpoints.iter().filter(|c| starts.get(c.pass_end).copied().unwrap_or(false)).copied().collect(); + self.prefix.prepare(doc, &resumable) + } else { + None + }; + + // Effect maps of whole regions first (they may render group shapes through sub-plans); + // regions larger than the limit are built per cell below. + let paged: Vec = plan.fx.iter().map(|f| self.fx_paged(f.region)).collect(); + let aprons: Vec = plan.fx.iter().zip(&paged).map(|(f, &pg)| if pg { Self::fx_apron(doc, f) } else { 0 }).collect(); + for (f, &pg) in plan.fx.iter().zip(&paged) { + if !pg { + self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, None), f.region, &mut stats)?; + } + } + let fr = self.frame_res(device, queue, canvas, &plan); + + // Page cells; every other frame in reverse, so a repeated full refresh of a document + // larger than the budget starts with the pages still resident. + if self.frame.is_multiple_of(2) { + cells.reverse(); + } + if let Some(f) = self.focus { + let p = page as i32; + let focused = |r: &Rect| !cell_rect((r.x0.div_euclid(p), r.y0.div_euclid(p)), page).intersect(&f).is_empty(); + cells.sort_by_key(focused); + } + let flush_bytes = FLUSH_BYTES.min(self.memory_budget() / 8).max(16 << 20); + stats.cells = cells.len(); + // The previous intermediate submit (see `submit_batch`). + let mut last_submit: Option = None; + // Work recorded and bytes evicted since the last submit. + let (mut work, mut freed) = (0u64, 0u64); + for part in cells { + self.stamp += 1; + let cell = (part.x0.div_euclid(page as i32), part.y0.div_euclid(page as i32)); + let cr = cell_rect(cell, page); + for (i, f) in plan.fx.iter().enumerate() { + let pf = cr.intersect(&f.region); + if !paged.get(i).copied().unwrap_or(false) || pf.is_empty() { + continue; + } + let window = pf.inflate(aprons.get(i).copied().unwrap_or(0)).intersect(&f.region); + self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, Some(cell)), window, &mut stats)?; + } + let chunks = grid_rects(part, self.chunk); + stats.chunks += chunks.len(); + work += part.width() as u64 * part.height() as u64 * plan.passes.len() as u64; + let mut batch = flush.then_some(&mut last_submit); + self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch); + // The device was lost in a submit inside the cell: issue no more work. + if let Some(f) = self.fault() { + return Err(Unsupported(f.to_string())); + } + // Out of memory although every page this cell doesn't use was dropped: the work recorded + // since the last submit can still hold those pages. Submit it, wait until the GPU is done + // with it so their memory is released, and run the cell once more. `encode` can't + // submit, so there the refresh goes to the CPU straight away. + if flush && self.layer_alloc.as_deref() == Some(OVER_BUDGET) { + self.layer_alloc = None; + submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), &mut last_submit); + #[cfg(not(target_arch = "wasm32"))] + { + let idle = match self.health.as_ref() { + Some(h) => h.wait_idle(device, last_submit.clone()), + None => device.poll(wgpu::PollType::Wait { submission_index: last_submit.clone(), timeout: None }).is_ok(), + }; + // The GPU has run every timestamp submitted so far, so a retry that fails too + // can drop this measurement without switching timing off for good. + if idle && let Some(t) = self.timer.as_mut() { + t.drained(); + } + } + self.staged = 0; + self.recorded = 0; + work = 0; + freed = 0; + self.admit_freed = 0; + stats.flushes += 1; + if let Some(f) = self.fault() { + return Err(Unsupported(f.to_string())); + } + let mut batch = Some(&mut last_submit); + self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch); + if let Some(f) = self.fault() { + return Err(Unsupported(f.to_string())); + } + } + // A page didn't fit even after evicting: this refresh goes to the CPU, the next one + // tries the GPU again (#6563). + if let Some(e) = self.layer_alloc.take() { + return Err(Unsupported(e)); + } + let (evicted, bytes) = self.evict(); + stats.evicted += evicted; + freed = freed.saturating_add(bytes.saturating_add(std::mem::take(&mut self.admit_freed))); + if flush && (self.staged >= flush_bytes || work >= FLUSH_WORK || freed >= flush_bytes || self.recorded >= FLUSH_OPS) { + submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), &mut last_submit); + self.staged = 0; + self.recorded = 0; + work = 0; + freed = 0; + stats.flushes += 1; + // The device was lost mid-refresh: issue no more work. + if let Some(f) = self.fault() { + return Err(Unsupported(f.to_string())); + } + } + } + + // Evict this document's textures whose layers are gone (hidden layers stay resident so + // toggling visibility costs no upload). + let frame = self.frame; + let live: std::collections::HashSet = doc.walk().into_iter().map(|(_, _, l)| l.id).collect(); + self.residents.retain(|(id, _, _), r| r.doc != doc.id || r.last_used == frame || live.contains(id)); + self.fx.retain(|(id, _), e| e.doc != doc.id || e.last_used == frame || live.contains(id)); + stats.evicted += self.evict().0; + self.temps.retain(|(_, used)| frame.saturating_sub(*used) < 240); + self.evict_patterns(); + Ok(stats) + } + + /// Drop the pattern textures no frame has painted with for [`PATTERN_IDLE_FRAMES`] frames, + /// then the least recently painted ones over the pattern budget. Never one this frame painted + /// with: it would only be uploaded again on the next frame. + fn evict_patterns(&mut self) { + let frame = self.frame; + self.patterns.retain(|_, p| frame.saturating_sub(p.last_used) < PATTERN_IDLE_FRAMES); + let mut total = self.pattern_cache_bytes(); + if total > self.pattern_budget { + let mut lru: Vec<(u64, String, u64)> = + self.patterns.iter().filter(|(_, p)| p.last_used != frame).map(|(k, p)| (p.last_used, k.clone(), p.bytes)).collect(); + lru.sort_unstable(); + for (_, key, bytes) in lru { + if total <= self.pattern_budget { + break; + } + self.patterns.remove(&key); + total = total.saturating_sub(bytes); + } + } + } + + /// Keep resident pages within the resident budget and the effect cache within + /// its budget, least recently used first. Never drops what the current cell uses, nor + /// whole-region effect maps drawn this frame. Returns how many textures were dropped and + /// their bytes. + fn evict(&mut self) -> (usize, u64) { + let (mut n, mut freed) = self.evict_residents(self.resident_budget, 0, None); + let mut total = self.fx_cache_bytes(); + let fx_budget = usize::try_from(self.fx_budget).unwrap_or(usize::MAX); + if total > fx_budget { + let (frame, stamp) = (self.frame, self.stamp); + let mut lru: Vec<((u64, u64), FxKey)> = self + .fx + .iter() + .filter(|(k, e)| e.last_used != frame || (k.1.is_some() && e.stamp != stamp)) + .map(|(k, e)| ((e.last_used, e.stamp), *k)) + .collect(); + lru.sort_unstable_by_key(|c| c.0); + for (_, k) in lru { + if total <= fx_budget { + break; + } + if let Some(e) = self.fx.remove(&k) { + total = total.saturating_sub(e.bytes()); + n += 1; + freed += e.bytes() as u64; + } + } + } + (n, freed) + } + + /// Drop least recently used resident pages until `incoming` more bytes fit in `budget`. + /// Never drops what the current cell uses, nor `keep`. Returns how many pages were dropped + /// and their bytes. + fn evict_residents(&mut self, budget: u64, incoming: u64, keep: Option) -> (usize, u64) { + let stamp = self.stamp; + let pages: Vec<(u64, ResKey, u64)> = + self.residents.iter().filter(|(k, r)| r.stamp != stamp && Some(**k) != keep).map(|(k, r)| (r.stamp, *k, r.bytes())).collect(); + let (mut n, mut freed) = (0, 0u64); + for k in lru_victims(pages, self.resident_bytes(), incoming, budget) { + if let Some(r) = self.residents.remove(&k) { + n += 1; + freed += r.bytes(); + } + } + (n, freed) + } + + /// Create the page texture for `key`, `bytes` large. Least recently used pages make room in + /// the budget first; when the device is still out of memory, every page the current cell + /// doesn't use is dropped and creation is tried once more (#6563). `None` (with + /// `layer_alloc` set) when it still fails: `render` submits the recorded work, which can still + /// hold the dropped pages, and runs the cell once more; after that the CPU draws the refresh. + pub(crate) fn create_layer_texture( + &mut self, + device: &wgpu::Device, + desc: &wgpu::TextureDescriptor<'_>, + key: ResKey, + bytes: u64, + stats: &mut Stats, + ) -> Option { + let replaced = self.residents.get(&key).map_or(0, Resident::bytes); + let (n, dropped) = self.evict_residents(self.resident_budget, bytes.saturating_sub(replaced), Some(key)); + stats.evicted += n; + self.admit_freed = self.admit_freed.saturating_add(dropped); + // WebGPU reports errors asynchronously: its failures reach the health callbacks. + if cfg!(target_arch = "wasm32") { + return Some(device.create_texture(desc)); + } + for retry in [false, true] { + let (texture, mut error) = first_error(device, || device.create_texture(desc)); + if error.is_none() && self.fail_allocs > 0 { + self.fail_allocs -= 1; + error = Some(wgpu::Error::OutOfMemory { source: "out of memory (test hook)".into() }); + } + match error { + None => return Some(texture), + Some(wgpu::Error::OutOfMemory { .. }) if !retry => { + let (n, dropped) = self.evict_residents(0, 0, Some(key)); + stats.evicted += n; + self.admit_freed = self.admit_freed.saturating_add(dropped); + } + Some(wgpu::Error::OutOfMemory { .. }) => { + self.layer_alloc = Some(OVER_BUDGET.into()); + return None; + } + Some(e) => { + self.layer_alloc = Some(format!("GPU layer texture failed: {e}")); + return None; + } + } + } + self.layer_alloc = Some(OVER_BUDGET.into()); + None + } + + /// Per-frame resources of `plan`: the tile area of each pass's surfaces, its LUT and pattern. + fn frame_res(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, canvas: Rect, plan: &Plan<'_>) -> FrameRes { + let grid = tile_grid(canvas); + let area = |s: &Surface| s.tile_bounds().intersect(&grid); + let areas = plan + .passes + .iter() + .map(|p| (p.tex.as_ref().map_or(Rect::EMPTY, |t| area(t.surface.get())), p.mask.as_ref().map_or(Rect::EMPTY, |m| area(m.surface.get())))) + .collect(); + let luts = plan.passes.iter().map(|p| p.lut.as_ref().map(|rows| lut_texture(device, queue, rows))).collect(); + let patterns = plan.passes.iter().map(|p| p.pattern.map(|pat| self.pattern_view(device, queue, pat))).collect(); + FrameRes { areas, luts, patterns } + } +} diff --git a/crates/gpu/src/fx/tests.rs b/crates/gpu/src/fx/tests.rs index 807d86be80..1622da28e2 100644 --- a/crates/gpu/src/fx/tests.rs +++ b/crates/gpu/src/fx/tests.rs @@ -227,9 +227,8 @@ fn paired_bevel_fields_equal_the_fields_one_at_a_time() { let banded = fields_in_windows(false, &shape, region, out, halo, |s, w, h| photocraft_compose::effects::bevel_distance_fields(s, w, h, reach as f32)); for (k, kind) in [FieldKind::BevelInside, FieldKind::BevelOutside].into_iter().enumerate() { - let [one] = fields_in_windows(false, &shape, region, out, halo, |s, w, h| { - [photocraft_compose::effects::distance_field(kind, s, w, h, reach as f32)] - }); + let [one] = + fields_in_windows(false, &shape, region, out, halo, |s, w, h| [photocraft_compose::effects::distance_field(kind, s, w, h, reach as f32)]); assert_eq!(bits(&banded[k]), bits(&one), "banded {kind:?}, reach {reach}, {out:?}"); } } diff --git a/crates/gpu/src/fx_passes.rs b/crates/gpu/src/fx_passes.rs new file mode 100644 index 0000000000..a549979f63 --- /dev/null +++ b/crates/gpu/src/fx_passes.rs @@ -0,0 +1,268 @@ +use super::batch::op_words; +use super::consts::{MAP16, MAP32}; +use super::kit::MapDraw; +use super::paging::field_reaches; +use super::textures::{FxEntry, FxKey, ProgState, Stats, Tex}; +use super::*; + +impl Compositor { + /// Build or update the effect maps of one layer over `region`: its whole effect region, or + /// the window of one page cell (`key.1`) grown by the effects' reach. + #[allow(clippy::too_many_arguments)] + pub(crate) fn sync_fx( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + doc: &Document, + f: &plan::FxLayer<'_>, + key: FxKey, + region: Rect, + stats: &mut Stats, + ) -> Result<(), Unsupported> { + let layer = f.layer; + let canvas = doc.bounds(); + let is_group = matches!(layer.content, LayerContent::Group(_)); + let shape_key = if is_group { fx::group_key(layer, &doc.global_light, &mut |_| {}) } else { fx::shape_key(layer, canvas) }; + let (content_src, mask_src) = if is_group { (None, None) } else { fx::shape_sources(layer) }; + let frame = self.frame; + let (rw, rh) = (region.width(), region.height()); + + // What changed: everything (new settings / size), the position only, some tiles, or + // nothing. + let mut damage = Rect::EMPTY; + let prev = self.fx.get(&key).filter(|e| e.shape_key == shape_key).map(|e| e.region); + let mut rebuild = true; + if prev == Some(region) + && let Some(e) = self.fx.get(&key) + { + rebuild = false; + for (old, cur) in e.tiles.iter().zip([content_src, mask_src]) { + let d = match (old, cur) { + (Some(o), Some(s)) => fx::damage(o, s), + (None, None) => Rect::EMPTY, + // A source appeared or vanished (the key changes with it too). + _ => region, + }; + damage = if damage.is_empty() { d } else { damage.union(&d) }; + } + damage = damage.intersect(®ion); + } else if let Some(old) = prev + && (old.width(), old.height()) == (rw, rh) + && !region.is_empty() + { + // Moved by whole pixels: maps are computed relative to the region, so if the shape + // moved unchanged with it, every map is still exact. + let v = fx::shape(doc, layer, region); + if let Some(e) = self.fx.get_mut(&key) + && v == e.shape_cpu + { + e.region = region; + rebuild = false; + } + } + if rebuild { + let shape = Tex::map(device, "pc_fx_shape", region, MAP32); + let n = rw as usize * rh as usize; + self.fx.insert( + key, + FxEntry { + doc: doc.id, + region, + shape_key, + tiles: [None, None], + _pin: if is_group { + let mut pin = Vec::new(); + fx::group_key(layer, &doc.global_light, &mut |t| pin.push(Arc::downgrade(t))); + pin + } else { + Vec::new() + }, + shape_cpu: vec![0.0; n], + shape, + fields: HashMap::new(), + progs: Vec::new(), + last_used: frame, + stamp: 0, + }, + ); + damage = region; + } + // Present: kept or (re)inserted above. + let stamp = self.stamp; + let Some(e) = self.fx.get_mut(&key) else { return Ok(()) }; + e.last_used = frame; + e.stamp = stamp; + e.doc = doc.id; + e.tiles = [content_src.map(fx::snapshot), mask_src.map(fx::snapshot)]; + if region.is_empty() { + return Ok(()); + } + + let t_trace = web_time_now(); + let mut staged = 0u64; + // Shape over the damage (compose's own alpha). + if !damage.is_empty() { + stats.fx_shapes += 1; + let v = fx::shape(doc, layer, damage); + fx::paste(&mut e.shape_cpu, region, damage, &v); + e.shape.write_r32(queue, region, damage, &v); + staged += v.len() as u64 * 4; + } + + // Programs, and the distance fields they read (max reach per field). + // Filled shapes stroke their outline (the effect shape); others estimate it. + let vector_shape = matches!(layer.content, LayerContent::Shape(_)) && photocraft_compose::effect_outline(layer).is_none(); + let anchor = layer.effects.reference.unwrap_or((f64::from(f.bounds.x0), f64::from(f.bounds.y0))); + let progs: Vec = + layer.effects.items.iter().filter(|e| e.enabled()).map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, anchor)).collect(); + let want = field_reaches(&progs); + e.fields.retain(|k, _| want.contains_key(k)); + // Each field to recompute: over which rectangle, exact up to which reach. + let jobs: Vec<(FieldKind, Rect, i32)> = want + .iter() + .filter_map(|(&kind, &reach)| match e.fields.get(&kind).map(|(r, _)| *r) { + Some(r) if r >= reach => (!damage.is_empty()).then(|| (kind, damage.inflate(fx::field_radius(kind, r)).intersect(®ion), r)), + _ => Some((kind, region, reach)), + }) + .collect(); + // A chiselled bevel's two fields are asked for and kept together (`fx::bevel_fields`), so they + // are recomputed together, over one rectangle at one reach. + let job = |k: FieldKind| jobs.iter().find(|j| j.0 == k).map(|j| (j.1, j.2)); + let (bevel_in, bevel_out) = (job(FieldKind::BevelInside), job(FieldKind::BevelOutside)); + if bevel_in != bevel_out { + return Err(Unsupported(format!("bevel fields of `{}` out of step: inside {bevel_in:?}, outside {bevel_out:?}", layer.name))); + } + for (kind, out, reach) in jobs { + let fields = match kind { + FieldKind::BevelInside => { + let [inside, outside] = fx::bevel_fields(reach, &e.shape_cpu, region, out); + vec![(FieldKind::BevelInside, inside), (FieldKind::BevelOutside, outside)] + } + // Computed with BevelInside, over the same rectangle at the same reach (checked above). + FieldKind::BevelOutside => continue, + _ => vec![(kind, fx::field(kind, reach, &e.shape_cpu, region, out))], + }; + for (kind, v) in fields { + if e.fields.get(&kind).is_none_or(|(r, _)| *r < reach) { + e.fields.insert(kind, (reach, Tex::map(device, "pc_fx_field", region, MAP32))); + } + if let Some((_, t)) = e.fields.get(&kind) { + t.write_r32(queue, region, out, &v); + } + staged += v.len() as u64 * 4; + stats.fx_pixels += out.width() as u64 * out.height() as u64; + } + } + + if let Some(t) = t_trace.filter(|_| !damage.is_empty()) { + eprintln!("effect maps of `{}`: shape + distance fields over {damage:?} in {:.2} ms (CPU)", layer.name, t.elapsed().as_secs_f64() * 1000.0); + } + e.progs.truncate(progs.len()); + while e.progs.len() < progs.len() { + e.progs.push(ProgState { key: 0, maps: Vec::new() }); + } + self.staged += staged; + for (i, prog) in progs.iter().enumerate() { + if prog.maps == 0 { + continue; + } + let Some(e) = self.fx.get_mut(&key) else { return Ok(()) }; + let same = e.progs[i].key == prog.key && e.progs[i].maps.len() == prog.maps; + let d = if same { damage } else { region }; + if d.is_empty() { + continue; + } + if !same { + e.progs[i] = ProgState { + key: prog.key, + maps: (0..prog.maps).map(|k| prog.stages.iter().any(|s| s.out == Some(k)).then(|| Tex::map(device, "pc_fx_map", region, MAP16))).collect(), + }; + } + stats.fx_programs += 1; + self.run_program(device, queue, encoder, key, i, prog, d, stats); + } + Ok(()) + } + + /// Record the passes of `prog` (maps of item `item` of `layer`) recomputing damage `d`. + #[allow(clippy::too_many_arguments)] + fn run_program( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + key: FxKey, + item: usize, + prog: &fx::MapProgram, + d: Rect, + stats: &mut Stats, + ) { + let pattern_views: Vec> = + prog.stages.iter().map(|s| s.pattern.as_ref().map(|p| self.pattern_view(device, queue, p))).collect(); + let Some(e) = self.fx.get(&key) else { return }; + let region = e.region; + let shape = e.shape.view.clone(); + let finals: Vec> = e.progs[item].maps.iter().map(|m| m.as_ref().map(|t| t.view.clone())).collect(); + let fields: HashMap = e.fields.iter().map(|(k, (r, t))| (*k, (*r, t.view.clone()))).collect(); + let windows = prog.windows(d, region, &|k| fields.get(&k).map_or(0, |f| f.0)); + let (assign, count) = prog.temps(); + let mut temps: Vec = Vec::with_capacity(count); + for _ in 0..count { + let v = self.temp(device, region, &temps); + temps.push(v); + } + // `None` only if a program's map or temporary wasn't allocated, which `sync_fx` and + // `MapProgram::temps` rule out. + let target_of = |i: usize| -> Option<(wgpu::TextureView, wgpu::TextureFormat)> { + match prog.stages[i].out { + Some(k) => Some((finals.get(k)?.clone()?, MAP16)), + None => Some((temps.get((*assign.get(i)?)?)?.clone(), MAP32)), + } + }; + let view_of = |inp: Option| -> Option { + match inp? { + fx::In::Shape => Some(shape.clone()), + fx::In::Field(k) => fields.get(&k).map(|f| f.1.clone()), + fx::In::Val(k) => target_of(k).map(|t| t.0), + } + }; + let mut draws = Vec::with_capacity(prog.stages.len()); + for (i, s) in prog.stages.iter().enumerate() { + let w = windows[i]; + if w.is_empty() { + continue; + } + stats.fx_pixels += w.width() as u64 * w.height() as u64; + let Some((target, format)) = target_of(i) else { continue }; + let mut p = plan::Pass::new(s.kernel, 0); + p.params[0] = s.p0; + p.params[1] = s.p1; + p.params[3] = s.p3; + p.extra = s.p4; + draws.push(MapDraw { + kernel: s.kernel, + format, + target, + scissor: [(w.x0 - region.x0) as u32, (w.y0 - region.y0) as u32, w.width(), w.height()], + space: [region.x0, region.y0, region.width() as i32, region.height() as i32], + op: op_words(&p, None, None, None), + views: [view_of(s.a), view_of(s.b), view_of(s.s), None, None, None, None, pattern_views[i].clone()], + lut: s.lut.clone(), + }); + } + self.kit.run(device, queue, encoder, &draws); + } +} + +/// A start time when `PHOTOCRAFT_FX_TRACE=1` (it prints the CPU time of effect shapes and +/// distance fields); never on wasm. +fn web_time_now() -> Option { + #[cfg(not(target_arch = "wasm32"))] + { + static T: std::sync::OnceLock = std::sync::OnceLock::new(); + T.get_or_init(|| std::env::var_os("PHOTOCRAFT_FX_TRACE").is_some()).then(std::time::Instant::now) + } + #[cfg(target_arch = "wasm32")] + None +} diff --git a/crates/gpu/src/kit.rs b/crates/gpu/src/kit.rs new file mode 100644 index 0000000000..2de048a2e2 --- /dev/null +++ b/crates/gpu/src/kit.rs @@ -0,0 +1,144 @@ +use super::consts::{CHUNK_UNIFORM, OP_UNIFORM, STRIDE}; +use super::convert::{lut_texture, words}; +use super::textures::{ResKey, ResidentRef}; +use super::*; + +/// Pipelines and layouts, shared by cheap clones (wgpu handles are reference counted). +#[derive(Clone)] +pub(crate) struct Kit { + pub(crate) pipelines: HashMap<(Kernel, wgpu::TextureFormat), wgpu::RenderPipeline>, + pub(crate) bgl0: wgpu::BindGroupLayout, + pub(crate) bgl1: wgpu::BindGroupLayout, + pub(crate) dummy: wgpu::TextureView, +} + +/// One draw of an effect-map kernel (outside the chunk loop). +pub(crate) struct MapDraw { + pub(crate) kernel: Kernel, + pub(crate) format: wgpu::TextureFormat, + pub(crate) target: wgpu::TextureView, + /// Target-local scissor (x, y, w, h). + pub(crate) scissor: [u32; 4], + /// Chunk record: origin and size of the target's space. + pub(crate) space: [i32; 4], + pub(crate) op: Vec, + pub(crate) views: [Option; 8], + pub(crate) lut: Option>>, +} + +impl Kit { + /// Record `draws` (each its own render pass) into `encoder`. + pub(crate) fn run(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, draws: &[MapDraw]) { + if draws.is_empty() { + return; + } + let mut data = vec![0u8; draws.len() * 2 * STRIDE as usize]; + for (i, d) in draws.iter().enumerate() { + let w = words(&[I(d.space[0]), I(d.space[1]), I(d.space[2]), I(d.space[3])]); + data[2 * i * STRIDE as usize..][..w.len()].copy_from_slice(&w); + data[(2 * i + 1) * STRIDE as usize..][..d.op.len()].copy_from_slice(&d.op); + } + let ubuf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("pc_fx_uniforms"), + size: data.len() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&ubuf, 0, &data); + let bg0 = uniform_group(device, &self.bgl0, &ubuf); + for (i, d) in draws.iter().enumerate() { + let lut = d.lut.as_ref().map(|l| { + let mut row = [0.0f32; 4096]; + row[..l.len().min(4096)].copy_from_slice(&l[..l.len().min(4096)]); + lut_texture(device, queue, &[row]) + }); + let mut views: Vec<&wgpu::TextureView> = d.views.iter().map(|v| v.as_ref().unwrap_or(&self.dummy)).collect(); + if let Some((_, lv)) = &lut { + views[4] = lv; + } + let bg1 = texture_group(device, &self.bgl1, &views); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("pc_fx_map"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &d.target, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&self.pipelines[&(d.kernel, d.format)]); + pass.set_scissor_rect(d.scissor[0], d.scissor[1], d.scissor[2], d.scissor[3]); + pass.set_bind_group(0, &bg0, &[(2 * i as u64 * STRIDE) as u32, ((2 * i + 1) as u64 * STRIDE) as u32]); + pass.set_bind_group(1, &bg1, &[]); + pass.draw(0..3, 0..1); + } + } +} + +pub(crate) fn uniform_group(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, ubuf: &wgpu::Buffer) -> wgpu::BindGroup { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("pc_compose_uniforms"), + layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: ubuf, offset: 0, size: NonZeroU64::new(CHUNK_UNIFORM) }), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: ubuf, offset: 0, size: NonZeroU64::new(OP_UNIFORM) }), + }, + ], + }) +} + +pub(crate) fn texture_group(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, views: &[&wgpu::TextureView]) -> wgpu::BindGroup { + let e: Vec = + views.iter().enumerate().map(|(b, v)| wgpu::BindGroupEntry { binding: b as u32, resource: wgpu::BindingResource::TextureView(v) }).collect(); + device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("pc_compose_pass"), layout, entries: &e }) +} + +pub(crate) fn tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + multisampled: false, + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + } +} + +pub(crate) fn uniform_entry(binding: u32, size: u64) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: true, min_binding_size: NonZeroU64::new(size) }, + count: None, + } +} + +/// The compositor's WGSL source (exposed for validation in tests). +pub const SHADER: &str = include_str!("compose.wgsl"); + +/// Pass-level resources resolved for one page cell: resident pages (texture, mask) and effect +/// maps (view and region) per pass. +pub(crate) struct Bound { + pub(crate) views: Vec<(Option, Option)>, + pub(crate) keys: Vec, + pub(crate) maps: Vec>, +} + +/// Pass-level resources shared by every cell of a frame. +pub(crate) struct FrameRes { + /// Tile area of each pass's (texture, mask) surface within the canvas tile grid. + pub(crate) areas: Vec<(Rect, Rect)>, + pub(crate) luts: Vec>, + pub(crate) patterns: Vec>, +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index c139a1860e..6fd8c13439 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -63,388 +63,6 @@ pub use health::{DeviceHealth, Fault}; pub use plan::{Kernel, Plan, Role, Unsupported, plan}; pub use timing::{GpuTimer, GpuTiming}; -/// Accumulator format for intermediate buffers. Full float: discontinuous operations -/// (Posterize, Threshold, Hard Mix, Dissolve) must land on the same side of their thresholds as -/// the CPU reference, and Color Burn/Dodge amplify input error. -pub const ACC_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float; // default accumulation format; `preferred_acc_format` downgrades to Rgba16Float where 32-bit float isn't renderable -/// Effect intermediates (distances, blurs) and layer shapes. -const MAP32: wgpu::TextureFormat = wgpu::TextureFormat::R32Float; -/// Final effect coverage maps (0..1; half precision is ~1/4000). -const MAP16: wgpu::TextureFormat = wgpu::TextureFormat::R16Float; -/// Side of the square chunks the canvas is processed in. -pub const CHUNK: u32 = 1024; -const STRIDE: u64 = 256; -const CHUNK_UNIFORM: u64 = 16; -const OP_UNIFORM: u64 = 256; -/// GPU memory the effect-map cache may hold before evicting layers not drawn this frame. -pub const FX_BUDGET: usize = 1536 << 20; -/// Largest side of the square pages layer surfaces are stored in on the GPU (smaller when the -/// device's texture limit is). A chunk only binds the pages of the cell it lies in, so layers of -/// any size composite on the GPU. -pub const PAGE: u32 = 2048; -/// GPU memory resident layer pages may hold before the least recently used are evicted. -pub const RESIDENT_BUDGET: u64 = 4 << 30; -/// GPU memory pattern textures may hold before the least recently painted are dropped (those the -/// current frame paints with always stay). -pub const PATTERN_BUDGET: u64 = 256 << 20; -/// A pattern texture no frame has painted with for this many frames is dropped. -pub const PATTERN_IDLE_FRAMES: u64 = 240; -/// Uploads (bytes) [`Compositor::render`] stages before submitting the work recorded so far, so -/// a refresh of a huge document never holds all its uploads in staging memory at once. -const FLUSH_BYTES: u64 = 512 << 20; -/// Pass pixels (chunk pixels × passes) [`Compositor::render`] records before submitting: one -/// command buffer holding a whole huge refresh can run for seconds, long enough for the OS to -/// reset the GPU. -const FLUSH_WORK: u64 = 1 << 30; -/// Copies and render passes [`Compositor::render`] records before submitting. wgpu opens up to -/// two backend command buffers for each (a render pass and its barrier pre-pass), and Metal -/// treats more than 4096 outstanding ones as a lost device: a refresh of a document with a few -/// hundred layers reached that inside a single page cell (P12, "pc_compose_uniforms is -/// invalid"), where the work and byte limits above never trigger. -const FLUSH_OPS: u32 = 1000; - -/// A finished chunk: straight-alpha RGBA32F pixels of `rect` (document coordinates) at the -/// texture's origin. -pub struct ChunkOut<'a> { - pub rect: Rect, - pub texture: &'a wgpu::Texture, - pub view: &'a wgpu::TextureView, -} - -/// What a render did (for profiling and tests). -#[derive(Clone, Copy, Debug, Default)] -pub struct Stats { - /// How long the GPU spent executing a composite, once its timestamps came back. Because the - /// readback is asynchronous this belongs to an *earlier* render than the one returning it - /// (it carries that render's own pixel count, so the two are never confused), and it is - /// `None` unless [`Compositor::measure_gpu_time`] is on and a measurement has landed. - /// Always `None` from [`Compositor::encode`], which submits nothing of its own. - pub gpu_time: Option, - pub passes: usize, - pub chunks: usize, - pub slots: u32, - pub tiles_uploaded: usize, - pub bytes_uploaded: usize, - /// Tiles a new layer texture took from another layer's texture by a GPU copy (a duplicate - /// shares its source's tiles) instead of uploading them. - pub tiles_shared: usize, - /// Effect layers whose shape was (re)rendered, fully or partially. - pub fx_shapes: usize, - /// Effect map programs run (one per effect whose maps were rebuilt). - pub fx_programs: usize, - /// Effect-map pixels written (all stages). - pub fx_pixels: u64, - /// Page cells the region spans (each binds only the layer pages it overlaps). - pub cells: usize, - /// Layer pages and paged effect maps evicted to stay within the memory budgets. - pub evicted: usize, - /// Intermediate submits of a huge refresh (to bound staging and evicted memory). - pub flushes: usize, - /// Chunks restored from an unchanged lower-stack composite. - pub prefix_hits: usize, - /// Planned prefix passes skipped, summed over the reused chunks. - pub prefix_passes_skipped: usize, - /// Plain layers blended inside another layer's pass (`fs_layerbatch`), summed over chunks. - pub layers_batched: usize, - /// Batched passes drawn with Normal's code alone (`fs_layerbatch_normal`), summed over chunks. - pub normal_batches: usize, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum TexKind { - /// RGBA8 tiles copied verbatim. - Rgba8Direct, - /// Other 8-bit formats converted to RGBA8. - Rgba8, - /// 16/32-bit formats converted to RGBA16F. - Rgba16F, - /// GRAY8 masks copied verbatim. - R8Direct, - /// 16-bit masks as R16F (the precision 16-bit pixels get as RGBA16F). - R16F, - /// 32-bit masks as R32F. - R32F, -} - -impl TexKind { - fn for_surface(role: Role, f: PixelFormat) -> Self { - match role { - Role::Content | Role::Stroke if f == PixelFormat::RGBA8 => TexKind::Rgba8Direct, - Role::Content | Role::Stroke if f.sample == SampleType::U8 => TexKind::Rgba8, - Role::Content | Role::Stroke => TexKind::Rgba16F, - Role::Mask if f == PixelFormat::GRAY8 => TexKind::R8Direct, - Role::Mask if f.sample == SampleType::F32 => TexKind::R32F, - Role::Mask => TexKind::R16F, - } - } - fn format(self) -> wgpu::TextureFormat { - match self { - TexKind::Rgba8Direct | TexKind::Rgba8 => wgpu::TextureFormat::Rgba8Unorm, - TexKind::Rgba16F => wgpu::TextureFormat::Rgba16Float, - TexKind::R8Direct => wgpu::TextureFormat::R8Unorm, - TexKind::R16F => wgpu::TextureFormat::R16Float, - TexKind::R32F => wgpu::TextureFormat::R32Float, - } - } - fn bytes_per_pixel(self) -> usize { - match self { - TexKind::Rgba8Direct | TexKind::Rgba8 => 4, - TexKind::Rgba16F => 8, - TexKind::R8Direct => 1, - TexKind::R16F => 2, - TexKind::R32F => 4, - } - } -} - -/// Index into the render's resident key list, and the texture's region (x, y, w, h). -type ResidentRef = (usize, [i32; 4]); -/// A page cell: the square `[x·page, (x+1)·page) × [y·page, (y+1)·page)` of document pixels. -type Cell = (i32, i32); -/// A resident layer page. -type ResKey = (LayerId, Role, Cell); -/// Effect maps of a layer: over its whole effect region (`None`), or one page cell of a region -/// larger than the texture limit. -type FxKey = (LayerId, Option); - -struct CachedPattern { - fingerprint: u64, - format: PixelFormat, - default_bits: Vec, - texture: Tex, - /// The document that last painted with it: closing that document frees the texture (#4971). - doc: DocId, - /// [`Compositor::frame`] when it last painted. - last_used: u64, - /// GPU bytes of the texture (RGBA32F). - bytes: u64, -} - -struct Resident { - texture: wgpu::Texture, - view: wgpu::TextureView, - /// Document-pixel rect covered (tile aligned, inside one page cell). - region: Rect, - kind: TexKind, - format: PixelFormat, - tiles: HashMap>, - default_nonzero: bool, - /// Bit pattern of the surface's default pixel when the texture was filled. Tiles the surface - /// doesn't store hold it, so a changed default (Invert, Fill) makes the texture stale. - default_bits: Vec, - doc: DocId, - last_used: u64, - /// Cell visit that last used it (least recently used pages are evicted first). - stamp: u64, - /// CMYK profile the texels were converted with (`CmykSpace::id`, 0 = built-in / not CMYK). - cmyk: u64, - /// Its texels were copied to or from another layer texture by the encoder, so every write - /// to it goes through the encoder too: a queued write lands before the encoder runs, and - /// would be overwritten by the copy, or leak into it. - ordered: bool, -} - -impl Resident { - fn bytes(&self) -> u64 { - self.region.width() as u64 * self.region.height() as u64 * self.kind.bytes_per_pixel() as u64 - } -} - -/// A texture and its default view. -#[derive(Clone)] -struct Tex { - texture: wgpu::Texture, - view: wgpu::TextureView, -} - -impl Tex { - fn new(device: &wgpu::Device, label: &str, w: u32, h: u32, format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> Self { - let texture = device.create_texture(&wgpu::TextureDescriptor { - label: Some(label), - size: wgpu::Extent3d { width: w.max(1), height: h.max(1), depth_or_array_layers: 1 }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format, - usage, - view_formats: &[], - }); - let view = texture.create_view(&Default::default()); - Tex { texture, view } - } - fn map(device: &wgpu::Device, label: &str, r: Rect, format: wgpu::TextureFormat) -> Self { - Tex::new( - device, - label, - r.width(), - r.height(), - format, - wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - ) - } - /// Upload R32F values (row-major over `r`) into this region-space texture at `r`. - fn write_r32(&self, queue: &wgpu::Queue, region: Rect, r: Rect, v: &[f32]) { - if r.is_empty() { - return; - } - let bytes: Vec = v.iter().flat_map(|x| x.to_le_bytes()).collect(); - queue.write_texture( - wgpu::TexelCopyTextureInfo { - texture: &self.texture, - mip_level: 0, - origin: wgpu::Origin3d { x: (r.x0 - region.x0) as u32, y: (r.y0 - region.y0) as u32, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - &bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(r.width() * 4), rows_per_image: Some(r.height()) }, - wgpu::Extent3d { width: r.width(), height: r.height(), depth_or_array_layers: 1 }, - ); - } - fn bytes(&self) -> usize { - let s = self.texture.size(); - let bpp = match self.texture.format() { - wgpu::TextureFormat::R16Float => 2, - wgpu::TextureFormat::Rgba32Float => 16, - wgpu::TextureFormat::Rgba16Float => 8, - _ => 4, - }; - s.width as usize * s.height as usize * bpp - } -} - -/// Cached maps of one effect (one enabled item of a layer). -struct ProgState { - key: u64, - maps: Vec>, -} - -/// Cached effect state of one layer. -struct FxEntry { - doc: DocId, - region: Rect, - shape_key: u64, - /// Tiles the shape was rendered from (content, mask): damage is their difference. - tiles: [Option; 2], - /// Groups: the tiles `shape_key` hashes, by address only (see [`fx::Tiles`]). - _pin: Vec>, - /// The shape on the CPU (distance fields are computed from it) and on the GPU. - shape_cpu: Vec, - shape: Tex, - /// Distance fields: the reach each is exact to, and its texture. - fields: HashMap, - progs: Vec, - last_used: u64, - stamp: u64, -} - -impl FxEntry { - fn bytes(&self) -> usize { - self.shape.bytes() - + self.shape_cpu.len() * 4 - + self.fields.values().map(|(_, t)| t.bytes()).sum::() - + self.progs.iter().flat_map(|p| p.maps.iter().flatten()).map(Tex::bytes).sum::() - } -} - -/// Pipelines and layouts, shared by cheap clones (wgpu handles are reference counted). -#[derive(Clone)] -struct Kit { - pipelines: HashMap<(Kernel, wgpu::TextureFormat), wgpu::RenderPipeline>, - bgl0: wgpu::BindGroupLayout, - bgl1: wgpu::BindGroupLayout, - dummy: wgpu::TextureView, -} - -/// One draw of an effect-map kernel (outside the chunk loop). -struct MapDraw { - kernel: Kernel, - format: wgpu::TextureFormat, - target: wgpu::TextureView, - /// Target-local scissor (x, y, w, h). - scissor: [u32; 4], - /// Chunk record: origin and size of the target's space. - space: [i32; 4], - op: Vec, - views: [Option; 8], - lut: Option>>, -} - -impl Kit { - /// Record `draws` (each its own render pass) into `encoder`. - fn run(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, draws: &[MapDraw]) { - if draws.is_empty() { - return; - } - let mut data = vec![0u8; draws.len() * 2 * STRIDE as usize]; - for (i, d) in draws.iter().enumerate() { - let w = words(&[I(d.space[0]), I(d.space[1]), I(d.space[2]), I(d.space[3])]); - data[2 * i * STRIDE as usize..][..w.len()].copy_from_slice(&w); - data[(2 * i + 1) * STRIDE as usize..][..d.op.len()].copy_from_slice(&d.op); - } - let ubuf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("pc_fx_uniforms"), - size: data.len() as u64, - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - queue.write_buffer(&ubuf, 0, &data); - let bg0 = uniform_group(device, &self.bgl0, &ubuf); - for (i, d) in draws.iter().enumerate() { - let lut = d.lut.as_ref().map(|l| { - let mut row = [0.0f32; 4096]; - row[..l.len().min(4096)].copy_from_slice(&l[..l.len().min(4096)]); - lut_texture(device, queue, &[row]) - }); - let mut views: Vec<&wgpu::TextureView> = d.views.iter().map(|v| v.as_ref().unwrap_or(&self.dummy)).collect(); - if let Some((_, lv)) = &lut { - views[4] = lv; - } - let bg1 = texture_group(device, &self.bgl1, &views); - let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("pc_fx_map"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &d.target, - resolve_target: None, - depth_slice: None, - ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store }, - })], - depth_stencil_attachment: None, - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); - pass.set_pipeline(&self.pipelines[&(d.kernel, d.format)]); - pass.set_scissor_rect(d.scissor[0], d.scissor[1], d.scissor[2], d.scissor[3]); - pass.set_bind_group(0, &bg0, &[(2 * i as u64 * STRIDE) as u32, ((2 * i + 1) as u64 * STRIDE) as u32]); - pass.set_bind_group(1, &bg1, &[]); - pass.draw(0..3, 0..1); - } - } -} - -fn uniform_group(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, ubuf: &wgpu::Buffer) -> wgpu::BindGroup { - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("pc_compose_uniforms"), - layout, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: ubuf, offset: 0, size: NonZeroU64::new(CHUNK_UNIFORM) }), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: ubuf, offset: 0, size: NonZeroU64::new(OP_UNIFORM) }), - }, - ], - }) -} - -fn texture_group(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, views: &[&wgpu::TextureView]) -> wgpu::BindGroup { - let e: Vec = - views.iter().enumerate().map(|(b, v)| wgpu::BindGroupEntry { binding: b as u32, resource: wgpu::BindingResource::TextureView(v) }).collect(); - device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("pc_compose_pass"), layout, entries: &e }) -} - /// GPU compositor. Create once per device; call [`Compositor::render`] per refresh. pub struct Compositor { kit: Kit, @@ -508,2476 +126,42 @@ pub struct Compositor { /// [`Compositor::measure_gpu_time`]); `None` = not measured. timer: Option, } - -fn tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { - wgpu::BindGroupLayoutEntry { - binding, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { - multisampled: false, - sample_type: wgpu::TextureSampleType::Float { filterable: false }, - view_dimension: wgpu::TextureViewDimension::D2, - }, - count: None, - } -} - -fn uniform_entry(binding: u32, size: u64) -> wgpu::BindGroupLayoutEntry { - wgpu::BindGroupLayoutEntry { - binding, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: true, min_binding_size: NonZeroU64::new(size) }, - count: None, - } -} - -/// The compositor's WGSL source (exposed for validation in tests). -pub const SHADER: &str = include_str!("compose.wgsl"); - -/// Pass-level resources resolved for one page cell: resident pages (texture, mask) and effect -/// maps (view and region) per pass. -struct Bound { - views: Vec<(Option, Option)>, - keys: Vec, - maps: Vec>, -} - -/// Pass-level resources shared by every cell of a frame. -struct FrameRes { - /// Tile area of each pass's (texture, mask) surface within the canvas tile grid. - areas: Vec<(Rect, Rect)>, - luts: Vec>, - patterns: Vec>, -} - -/// Document pixels of page cell `c`. -fn cell_rect(c: Cell, page: u32) -> Rect { - let p = page as i32; - Rect::new(c.0.saturating_mul(p), c.1.saturating_mul(p), c.0.saturating_add(1).saturating_mul(p), c.1.saturating_add(1).saturating_mul(p)) -} - -/// `r` cut along the grid of `step`-sized squares (row-major). -fn grid_rects(r: Rect, step: u32) -> Vec { - let s = step.max(1) as i32; - let mut out = Vec::new(); - let mut y = r.y0.div_euclid(s) * s; - while y < r.y1 { - let mut x = r.x0.div_euclid(s) * s; - while x < r.x1 { - out.push(Rect::new(x, y, x.saturating_add(s), y.saturating_add(s)).intersect(&r)); - x = x.saturating_add(s); - } - y = y.saturating_add(s); - } - out -} - -/// Number of rectangles `grid_rects` would produce, without allocating them during preflight. -fn grid_rect_count(r: Rect, step: u32) -> Result { - if r.is_empty() { - return Ok(0); - } - let s = i64::from(step.max(1)); - let axis = |lo: i32, hi: i32| usize::try_from((i64::from(hi) - 1).div_euclid(s) - i64::from(lo).div_euclid(s) + 1).ok(); - axis(r.x0, r.x1).and_then(|x| axis(r.y0, r.y1).and_then(|y| x.checked_mul(y))).ok_or_else(|| Unsupported("GPU compositor chunk count is too large".into())) -} - -/// Host length and GPU capacity for the chunk/pass uniform records, including their u32 -/// dynamic binding offsets. Decline unsupported stacks before an invalid buffer faults the device. -fn uniform_buffer_len(chunks: usize, passes: usize, limit: u64) -> Result { - let too_large = || Unsupported("GPU compositor uniform buffer is too large".into()); - let records = chunks.checked_add(passes).and_then(|n| u64::try_from(n).ok()).ok_or_else(too_large)?; - let bytes = records.checked_mul(STRIDE).ok_or_else(too_large)?; - if bytes > limit { - return Err(Unsupported(format!("GPU compositor uniform buffer requires {bytes} bytes; device limit is {limit}"))); - } - if bytes.saturating_sub(STRIDE) > u64::from(u32::MAX) { - return Err(Unsupported("GPU compositor uniform offsets exceed u32".into())); - } - usize::try_from(bytes).map_err(|_| too_large()) -} - -/// The reach up to which each distance field must be exact (the largest any program asks for). -fn field_reaches(progs: &[fx::MapProgram]) -> HashMap { - let mut want: HashMap = HashMap::new(); - for (k, r) in progs.iter().flat_map(|p| p.fields.iter()) { - let w = want.entry(*k).or_insert(0); - *w = (*w).max(*r); - } - want -} - -/// Why a refresh whose layer pages don't fit GPU memory is drawn on the CPU. -pub const OVER_BUDGET: &str = "layers exceed the GPU memory budget; full refresh on the CPU"; - -/// Which of `pages` (LRU clock, key, bytes) to drop, least recently used first, so `incoming` -/// more bytes fit `budget` on top of the `total` held now. Callers leave out pages that must stay. -fn lru_victims(mut pages: Vec<(u64, K, u64)>, total: u64, incoming: u64, budget: u64) -> Vec { - pages.sort_unstable_by_key(|p| p.0); - let mut total = total; - let mut out = Vec::new(); - for (_, k, bytes) in pages { - if total.saturating_add(incoming) <= budget { - break; - } - total = total.saturating_sub(bytes); - out.push(k); - } - out -} - -/// Runs `f` inside GPU error scopes and returns the first error raised. -/// Native wgpu reports validation/internal/OOM errors synchronously; where they only arrive -/// asynchronously (WebGPU) none is reported. -fn first_error(device: &wgpu::Device, f: impl FnOnce() -> T) -> (T, Option) { - let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); - let internal = device.push_error_scope(wgpu::ErrorFilter::Internal); - let memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); - let out = f(); - let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); - let mut error = None; - // Scopes pop in reverse order. - for pop in [memory.pop(), internal.pop(), validation.pop()] { - if let std::task::Poll::Ready(Some(e)) = std::pin::pin!(pop).poll(&mut cx) { - error.get_or_insert(e); - } - } - (out, error) -} - -/// Runs `f` inside the error scopes of [`first_error`], turning a reported error into -/// [`Unsupported`] instead of letting it escape to wgpu's panic handler. -/// -/// Every native caller needs this, watched or not: a validation error (writing into a destroyed -/// or too-small buffer, say) is raised synchronously and never reaches the health callbacks, so a -/// watched compositor still panicked on it. WebGPU reports its errors asynchronously, long after -/// the scope has popped, so wasm relies on the health callbacks alone. -/// -/// A scope also swallows the error that [`DeviceHealth`]'s uncaptured-error handler would have -/// recorded, so a reported error is handed back to `health`: a watched device must stop being -/// used and let the caller fall back to the CPU compositor. -fn scoped_work(device: &wgpu::Device, health: Option, f: impl FnOnce() -> Result) -> Result { - // WebGPU errors arrive asynchronously; its callers still use the health callbacks. - if cfg!(target_arch = "wasm32") { - return f(); - } - let (result, error) = first_error(device, f); - match error { - Some(error) => { - if let Some(health) = health.as_ref() { - health.caught(device, &error); - } - Err(Unsupported(format!("GPU work failed: {error}"))) - } - None => result, - } -} - -impl Compositor { - /// Create a compositor with the default accumulation format ([`ACC_FORMAT`]). - pub fn new(device: &wgpu::Device) -> Self { - Self::new_with_format(device, ACC_FORMAT) - } - - /// The accumulation format to use on `adapter`: `Rgba32Float` when it can be a render target, - /// else `Rgba16Float`. Some drivers (e.g. Intel Vulkan) don't support rendering to `Rgba32Float` - /// and would otherwise panic at render-pipeline creation. - pub fn preferred_acc_format(adapter: &wgpu::Adapter) -> wgpu::TextureFormat { - let feats = adapter.get_texture_format_features(wgpu::TextureFormat::Rgba32Float); - if feats.allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) { wgpu::TextureFormat::Rgba32Float } else { wgpu::TextureFormat::Rgba16Float } - } - - /// [`Compositor::new_with_format`], but a shader or pipeline the driver can't build (e.g. a - /// D3D12 shader-compiler failure) is an `Err` instead of a panic, so the caller can fall back - /// to the CPU compositor. Where errors only arrive asynchronously (WebGPU), creation is assumed - /// to have worked. - pub fn try_new_with_format(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Result { - match first_error(device, || Self::build(device, acc_format)) { - ((comp, None), None) => Ok(comp), - ((_, Some(e)), _) | (_, Some(e)) => Err(Unsupported(format!("couldn't build the compositor's pipelines: {e}"))), - } - } - - /// Create a compositor whose accumulation/render-target format is `acc_format`. Pass - /// `Rgba16Float` on adapters that can't render to `Rgba32Float` (e.g. some Intel Vulkan drivers), - /// which otherwise panics at render-pipeline creation. See `Compositor::preferred_acc_format`. - pub fn new_with_format(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Self { - let (comp, error) = Self::build(device, acc_format); - if let Some(e) = error { - log::error!("GPU compositor: couldn't build its pipelines: {e}"); - } - comp - } - - /// The compositor and the first error raised building its (non-map) pipelines. They are - /// built in parallel, each inside its own error scope on the thread that builds it (wgpu's - /// scopes are per thread): on DX12, FXC compiles one shader at a time and the ~30 pipelines - /// took about 8 s on one core (#6419). - fn build(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> (Self, Option) { - let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_compose"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); - let bgl0 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("pc_compose_uniforms"), - entries: &[uniform_entry(0, CHUNK_UNIFORM), uniform_entry(1, OP_UNIFORM)], - }); - let bgl1 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("pc_compose_textures"), - entries: &(0..8).map(tex_entry).collect::>(), - }); - let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("pc_compose"), - bind_group_layouts: &[Some(&bgl0), Some(&bgl1)], - immediate_size: 0, - }); - // `None` only for kernels without a fragment entry point, which are never drawn. - let pipeline = |k: Kernel, format: wgpu::TextureFormat| { - let entry = k.entry()?; - Some(device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some(entry), - layout: Some(&layout), - vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, - primitive: wgpu::PrimitiveState::default(), - depth_stencil: None, - multisample: wgpu::MultisampleState::default(), - fragment: Some(wgpu::FragmentState { - module: &module, - entry_point: Some(entry), - targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })], - compilation_options: Default::default(), - }), - multiview_mask: None, - cache: None, - })) - }; - // Effect maps render to R32Float / R16Float, which some adapters (e.g. GL without float - // render targets) can't: then layer effects use the CPU compositor and the rest stays here. - let keys = Kernel::DRAWN.iter().filter(|k| !k.is_map()).map(|&k| (k, acc_format)); - let keys: Vec<_> = keys.chain(Kernel::DRAWN.iter().filter(|k| k.is_map()).flat_map(|&k| [(k, MAP32), (k, MAP16)])).collect(); - let built = fx::par_map(keys, |key| { - let (built, error) = first_error(device, || pipeline(key.0, key.1)); - (key, built, error) - }); - let (mut pipelines, mut maps) = (HashMap::new(), Vec::new()); - let (mut error, mut map_error) = (None, None); - for (key, built, e) in built { - let map = key.0.is_map(); - // A failed map pipeline turns all effect maps off below. A failed non-map pipeline - // keeps its (invalid) handle: draws look pipelines up by key, so dropping it would - // turn a validation error into a missing-key panic on the first draw. - if let Some(e) = e { - if map { - map_error.get_or_insert(e); - continue; - } - error.get_or_insert(e); - } - let Some(p) = built else { continue }; - if map { - maps.push((key, p)); - } else { - pipelines.insert(key, p); - } - } - if let Some(e) = &map_error { - log::info!("GPU compositor: no effect-map pipelines ({e}); layer effects use the CPU"); - } else { - pipelines.extend(maps); - } - let dummy = Tex::new(device, "pc_compose_dummy", 1, 1, wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureUsages::TEXTURE_BINDING).view; - let comp = Self { - kit: Kit { pipelines, bgl0, bgl1, dummy }, - pool: Vec::new(), - residents: HashMap::new(), - fx: HashMap::new(), - prefix: prefix::Prefix::default(), - temps: Vec::new(), - patterns: HashMap::new(), - pattern_mode: photocraft_color::ColorMode::Rgb, - pattern_doc: DocId(0), - pattern_budget: PATTERN_BUDGET, - max_dim: 0, - device_max: device.limits().max_texture_dimension_2d, - page: PAGE, - chunk: CHUNK, - resident_budget: RESIDENT_BUDGET, - fx_budget: (FX_BUDGET as u64).saturating_sub(prefix::MAX_BYTES), - layer_need: 0, - lent: 0, - exact_resident: false, - focus: None, - frame: 0, - stamp: 0, - staged: 0, - recorded: 0, - layer_alloc: None, - admit_freed: 0, - fail_allocs: 0, - acc_format, - effect_maps: map_error.is_none(), - cmyk: 0, - health: None, - timer: None, - } - .with_texture_limit(device.limits().max_texture_dimension_2d); - (comp, error) - } - - fn with_texture_limit(mut self, max: u32) -> Self { - self.set_texture_limit(max); - self - } - - /// Plan paging for a texture side limit of `max` (clamped to the device's own limit and at - /// least one tile). Tests use a small limit to exercise documents larger than it on any - /// adapter. Drops every cached texture. - pub fn set_texture_limit(&mut self, max: u32) { - let tile = TILE_SIZE as u32; - self.max_dim = max.min(self.device_max).max(tile); - let mut page = tile; - while page * 2 <= self.max_dim.min(PAGE) { - page *= 2; - } - self.page = page; - self.chunk = CHUNK.min(page); - self.prefix.set_step(self.chunk); - self.pool.clear(); - self.residents.clear(); - self.fx.clear(); - self.temps.clear(); - self.prefix.clear(); - } - - /// The page side layer surfaces are stored in. - pub fn page_size(&self) -> u32 { - self.page - } - - /// Test hook: the next `n` layer page textures fail as if the device were out of memory - /// (a real one can't be forced), so the fallback paths of #6563 can be tested. - #[doc(hidden)] - pub fn fail_layer_allocs(&mut self, n: u32) { - self.fail_allocs = n; - } - - /// Set the GPU memory resident layer pages may hold (default [`RESIDENT_BUDGET`]), exactly: - /// nothing is lent to it ([`Self::fit_layers`]) until the next [`Self::set_memory_budget`]. - pub fn set_resident_budget(&mut self, bytes: u64) { - // The loan goes back to the effect maps, so the total budget stays what it was. - self.fx_budget = self.fx_budget.saturating_add(self.lent); - self.lent = 0; - self.resident_budget = bytes; - self.exact_resident = true; - } - - /// Set the GPU memory the compositor may hold for layer pages and caches together - /// (a quarter of it, at most [`FX_BUDGET`], for effect maps and lower-stack chunks). Uploads and evicted pages in - /// flight during a refresh stay within about a quarter more. - pub fn set_memory_budget(&mut self, bytes: u64) { - let caches = (FX_BUDGET as u64).min(bytes / 4); - self.prefix.set_budget((caches / 2).min(prefix::MAX_BYTES)); - self.fx_budget = caches.saturating_sub(self.prefix.budget()); - self.resident_budget = bytes.saturating_sub(caches); - self.lent = 0; - self.exact_resident = false; - self.lend(); - } - - /// Record that a render needs `needed` bytes of layer pages and return the resident budget - /// they now have. A render of the `whole` document sets the need; a part of it only raises - /// it, so a large partial refresh never shrinks what the next full one keeps resident. - /// - /// Pages that miss their share by less than the effect-map share borrow from it: an evicted - /// effect map is rebuilt by the next refresh that draws it, but one page too many sends the - /// whole refresh to the CPU compositor, 10× slower (#5973, P60: 150 layers of 6 MP on an - /// integrated GPU missed by 5 % and took 680 ms instead of 62). - /// The lower-stack share is never lent: it is what keeps a mid-stack edit at half the work. - /// The loan holds across [`Self::set_memory_budget`] until a later call needs less or more. - pub fn fit_layers(&mut self, needed: u64, whole: bool) -> u64 { - self.layer_need = if whole { needed } else { self.layer_need.max(needed) }; - self.lend(); - self.resident_budget - } - - /// Return the loan to the effect maps, then lend what [`Self::layer_need`] still lacks, if - /// the effect-map share covers it (lending part of it would fit nothing and only evict maps). - fn lend(&mut self) { - self.fx_budget = self.fx_budget.saturating_add(self.lent); - self.resident_budget = self.resident_budget.saturating_sub(self.lent); - let short = self.layer_need.saturating_sub(self.resident_budget); - self.lent = if short <= self.fx_budget && !self.exact_resident { short } else { 0 }; - self.fx_budget = self.fx_budget.saturating_sub(self.lent); - self.resident_budget = self.resident_budget.saturating_add(self.lent); - } - - /// The budget of layer pages, effect maps and lower-stack chunks (bytes). - pub fn memory_budget(&self) -> u64 { - self.resident_budget.saturating_add(self.fx_budget).saturating_add(self.prefix.budget()) - } - - /// Bytes held by reusable lower-stack chunks, within the overall cache allowance. - pub fn composite_cache_bytes(&self) -> u64 { - self.prefix.bytes() - } - - /// Cap lower-stack reuse (default at most 512 MiB); zero disables it. The released allowance - /// goes back to effect maps, preserving the total budget and layer-page allowance. - pub fn set_composite_cache_budget(&mut self, bytes: u64) { - let caches = self.fx_budget.saturating_add(self.prefix.budget()); - self.prefix.set_budget(bytes.min(caches)); - self.fx_budget = caches.saturating_sub(self.prefix.budget()); - } - - /// Bytes of the layer pages a render of `region` needs resident (each layer and mask - /// surface's tiles within the region's page cells, in their texture format). - pub fn working_set(&self, doc: &Document, region: Rect) -> u64 { - let Ok(plan) = plan(doc) else { return 0 }; - let grid = tile_grid(doc.bounds()); - let cells = grid_rects(region.intersect(&doc.bounds()), self.page) - .into_iter() - .map(|r| cell_rect((r.x0.div_euclid(self.page as i32), r.y0.div_euclid(self.page as i32)), self.page)) - .fold(Rect::EMPTY, |a, c| if a.is_empty() { c } else { a.union(&c) }); - let mut seen = std::collections::HashSet::new(); - let mut total = 0u64; - for p in &plan.passes { - let sources = [p.tex.as_ref().map(|t| (t.layer, t.role, t.surface.get())), p.mask.as_ref().map(|m| (m.layer, Role::Mask, m.surface.get()))]; - for (layer, role, s) in sources.into_iter().flatten() { - if seen.insert((layer, role)) { - let a = s.tile_bounds().intersect(&grid).intersect(&cells); - total += a.width() as u64 * a.height() as u64 * TexKind::for_surface(role, s.format()).bytes_per_pixel() as u64; - } - } - } - total - } - - /// The GPU memory resident layer pages may hold (bytes; see [`Compositor::set_memory_budget`]). - pub fn resident_budget(&self) -> u64 { - self.resident_budget - } - - /// Whether a render of `region` keeps every layer page it needs within the budget; when it - /// doesn't, each render re-uploads what was evicted. - pub fn fits_budget(&self, doc: &Document, region: Rect) -> bool { - self.working_set(doc, region) <= self.resident_budget - } - - /// The document area the view shows (`None`: unknown). Full refreshes draw its cells last. - pub fn set_focus(&mut self, focus: Option) { - self.focus = focus; - } - - /// GPU memory held by resident layer pages (bytes). - pub fn resident_bytes(&self) -> u64 { - self.residents.values().map(Resident::bytes).sum() - } - - /// GPU memory held by cached pattern textures (bytes). - pub fn pattern_cache_bytes(&self) -> u64 { - self.patterns.values().map(|p| p.bytes).sum() - } - - /// Set the GPU memory pattern textures may hold (default [`PATTERN_BUDGET`]). It takes effect - /// at the end of the next refresh. - pub fn set_pattern_budget(&mut self, bytes: u64) { - self.pattern_budget = bytes; - } - - /// Whether `doc` can be composited on the GPU. Documents and layers larger than the texture - /// limit are fine: surfaces are stored in page-sized textures and effect maps of regions - /// larger than the limit are built per page cell. - pub fn supports(&self, doc: &Document) -> Result<(), Unsupported> { - let p = plan(doc)?; - self.check_fx(doc, &p) - } - - /// Whether the maps of an effect region are built per page cell (it exceeds the limit). - fn fx_paged(&self, region: Rect) -> bool { - region.width() > self.max_dim || region.height() > self.max_dim - } - - /// How far beyond a page cell the effect maps of `f` must be computed to be exact in it. - fn fx_apron(doc: &Document, f: &plan::FxLayer<'_>) -> i32 { - let vector_shape = matches!(f.layer.content, LayerContent::Shape(_)) && photocraft_compose::effect_outline(f.layer).is_none(); - let progs: Vec = f - .layer - .effects - .items - .iter() - .filter(|e| e.enabled()) - .map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, (0.0, 0.0))) - .collect(); - let want = field_reaches(&progs); - // Distance fields are exact one pixel inside the window they are computed from. - progs.iter().map(|p| p.reach(&|k| want.get(&k).copied().unwrap_or(0))).max().unwrap_or(0).saturating_add(2) - } - - /// Effect maps must fit in textures (per page cell when the region exceeds the limit), and - /// patterns in one texture. - fn check_fx(&self, doc: &Document, p: &Plan<'_>) -> Result<(), Unsupported> { - if !self.effect_maps && !p.fx.is_empty() { - return Err(Unsupported("layer effects need float effect-map render targets, which this GPU lacks".into())); - } - for f in &p.fx { - if self.fx_paged(f.region) { - let side = i64::from(self.page) + 2 * i64::from(Self::fx_apron(doc, f)); - if side > i64::from(self.device_max) { - return Err(Unsupported(format!("effects of `{}` reach too far to build per page", f.layer.name))); - } - } - for e in f.layer.effects.items.iter().filter(|e| e.enabled()) { - // Effect noise is speckled in the CPU maps; keep CPU and GPU identical by - // rendering noise-carrying effects on the CPU path. - let noisy = match e { - photocraft_doc::Effect::DropShadow(s) | photocraft_doc::Effect::InnerShadow(s) => s.noise > 0.0, - photocraft_doc::Effect::OuterGlow(g) | photocraft_doc::Effect::InnerGlow(g) => g.noise > 0.0, - _ => false, - }; - if noisy { - return Err(Unsupported(format!("effect noise on `{}` uses the CPU path", f.layer.name))); - } - for s in fx::program_with(e, &doc.global_light, false, &doc.patterns, (0.0, 0.0)).stages { - if s.lut.as_ref().is_some_and(|l| l.len() > 4096) { - return Err(Unsupported(format!("effect blur on `{}` too wide for the GPU path", f.layer.name))); - } - } - } - } - for pass in &p.passes { - if let Some(pat) = pass.pattern - && (pat.width > self.device_max || pat.height > self.device_max) - { - return Err(Unsupported(format!("pattern `{}` larger than the GPU texture limit", pat.name))); - } - } - Ok(()) - } - - /// Drop GPU textures of a closed document. - pub fn forget_doc(&mut self, doc: DocId) { - self.residents.retain(|_, r| r.doc != doc); - self.fx.retain(|_, e| e.doc != doc); - self.patterns.retain(|_, p| p.doc != doc); - self.prefix.forget(doc); - } - - /// [`Self::forget_doc`] for every document `keep` rejects: what the compositor holds for - /// documents that were closed, however their canvas entry went (#4529). - pub fn retain_docs(&mut self, keep: impl Fn(DocId) -> bool) { - let mut gone: Vec = self - .residents - .values() - .map(|r| r.doc) - .chain(self.fx.values().map(|e| e.doc)) - .chain(self.patterns.values().map(|p| p.doc)) - .chain(self.prefix.doc()) - .filter(|d| !keep(*d)) - .collect(); - gone.sort_by_key(|d| d.0); - gone.dedup(); - for d in gone { - self.forget_doc(d); - } - } - - /// Documents the compositor holds pages, effect maps, pattern textures or a lower-stack - /// composite for. - pub fn held_docs(&self) -> Vec { - let mut docs: Vec = self - .residents - .values() - .map(|r| r.doc) - .chain(self.fx.values().map(|e| e.doc)) - .chain(self.patterns.values().map(|p| p.doc)) - .chain(self.prefix.doc()) - .collect(); - docs.sort_by_key(|d| d.0); - docs.dedup(); - docs - } - - /// GPU memory held by cached effect maps (bytes). - pub fn fx_cache_bytes(&self) -> usize { - self.fx.values().map(FxEntry::bytes).sum() - } - - /// Watch `health` (see [`DeviceHealth::watch`]): once the device is lost or reported an - /// error, every render returns [`Unsupported`] without touching the GPU, so callers use the - /// CPU compositor instead. - pub fn set_health(&mut self, health: DeviceHealth) { - self.health = Some(health); - } - - /// Why the device can't be used (`None` while healthy or unwatched). - pub fn fault(&self) -> Option { - self.health.as_ref().and_then(DeviceHealth::fault) - } - - /// Measure how long the GPU spends executing each [`Compositor::render`], with timestamp - /// queries read back asynchronously (nothing waits for the GPU). Returns whether the device - /// supports it: without [`timing::FEATURES`] there is no measurement at all, and callers - /// report no GPU time rather than the encode-and-submit cost `composite_ms` already is. - /// - /// A measurement arrives a frame or two after the refresh it belongs to, so it carries that - /// refresh's own pixel count; take it with [`Compositor::take_gpu_timing`]. - pub fn measure_gpu_time(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> bool { - // `PHOTOCRAFT_NO_GPU_TIMING` turns it off: a kill switch for a driver whose timestamp - // queries misbehave, and the control arm for measuring what the queries themselves - // cost — the device is identical either way, so only the instrumentation varies. - if std::env::var_os("PHOTOCRAFT_NO_GPU_TIMING").is_some() { - return false; - } - if self.timer.is_none() { - self.timer = timing::GpuTimer::new(device, queue); - } - self.timer.is_some() - } - - /// Whether [`Compositor::measure_gpu_time`] is on for this compositor. - pub fn measures_gpu_time(&self) -> bool { - self.timer.is_some() - } - - /// The most recent finished GPU measurement, leaving none behind (a stale number is never - /// reported twice as new). `None` while unmeasured, unsupported, or still in flight. - /// - /// [`Compositor::render`] already drains this into [`Stats::gpu_time`], so the app never - /// calls it; it is how a bench or a test collects a measurement without issuing another - /// render to carry it. - pub fn take_gpu_timing(&mut self) -> Option { - self.timer.as_mut().and_then(timing::GpuTimer::take) - } - - /// Composite `region` of `doc`. Each finished chunk is passed to `sink` while its encoder is - /// still open; the chunk texture is reused afterwards, so the sink must record any copies - /// or passes that read it into the given encoder. Submits the work before returning; a - /// refresh of a huge document also submits in between (the sink may be handed a new - /// encoder), so its uploads and evicted pages never pile up in memory. - pub fn render( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - doc: &Document, - region: Rect, - mut sink: impl FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), - ) -> Result { - let result = scoped_work(device, self.health.clone(), || { - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") }); - if self.timer.as_ref().is_some_and(timing::GpuTimer::busy) { - // The readback map completes on a poll. The app polls every frame, but a - // non-blocking poll here keeps the measurements coming whatever the caller does. - match &self.health { - Some(h) => h.poll(device), - None => { - let _ = device.poll(wgpu::PollType::Poll); - } - } - } - // Whatever came back since the last render travels out with this one's stats, so - // nothing has to reach back into the compositor for it afterwards. - let landed = self.timer.as_mut().and_then(timing::GpuTimer::take); - if let Some(t) = &mut self.timer { - let r = region.intersect(&doc.bounds()); - t.start(&mut encoder, r.width() as u64 * r.height() as u64); - } - let mut stats = self.encode_inner(device, queue, &mut encoder, doc, region, &mut sink, true); - if let Ok(s) = &mut stats { - s.gpu_time = landed; - } - if let Some(t) = &mut self.timer { - // A refresh that failed part way measures nothing: its spans describe work the - // caller is about to redo on the CPU. - match stats { - Ok(_) => t.finish(&mut encoder), - Err(_) => { - t.cancel(); - // The refresh is lost, but a measurement that came back with it is not: - // hand it to the next render rather than drop it on the fallback path. - if let Some(landed) = landed { - t.restore(landed); - } - } - } - } - let stats = stats?; - queue.submit([encoder.finish()]); - if let Some(t) = &mut self.timer { - t.submitted(); - } - Ok(stats) - }); - if result.is_err() { - self.discard_failed_work(); - } - result - } - - /// Like [`Self::render`] but records into `encoder` without submitting. - pub fn encode( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - doc: &Document, - region: Rect, - sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), - ) -> Result { - let result = scoped_work(device, self.health.clone(), || self.encode_inner(device, queue, encoder, doc, region, sink, false)); - if result.is_err() { - self.discard_failed_work(); - } - result - } - - fn discard_failed_work(&mut self) { - // Cache metadata advances while recording. A failed encoder may never execute its - // texture uploads or effect maps, so none of those cached pixels can be trusted. - self.prefix.clear(); - self.residents.clear(); - self.fx.clear(); - self.patterns.clear(); - self.temps.clear(); - self.pool.clear(); - } - - #[allow(clippy::too_many_arguments)] - fn encode_inner( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - doc: &Document, - region: Rect, - sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), - flush: bool, - ) -> Result { - if let Some(f) = self.fault() { - return Err(Unsupported(f.to_string())); - } - // CMYK layers convert through the document's own CMYK profile (uploads and plan colours). - let space = photocraft_compose::cmyk_space(doc); - self.cmyk = space.as_ref().map_or(0, |s| s.id); - photocraft_color::convert::with_cmyk_space(space.as_ref(), || self.encode_scoped(device, queue, encoder, doc, region, sink, flush)) - } - - #[allow(clippy::too_many_arguments)] - fn encode_scoped( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - doc: &Document, - region: Rect, - sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), - flush: bool, - ) -> Result { - let canvas = doc.bounds(); - let region = region.intersect(&canvas); - let plan = plan(doc)?; - self.check_fx(doc, &plan)?; - self.pattern_mode = doc.pixel_format().mode; - self.pattern_doc = doc.id; - let mut stats = Stats { passes: plan.passes.len(), slots: plan.slots, ..Default::default() }; - if region.is_empty() { - return Ok(stats); - } - let page = self.page; - let mut cells = grid_rects(region, page); - // Check every actual page cell before uploads, submissions or sink output. A later - // cell can need more chunk records than the first; a failure must leave the device healthy. - let buffer_limit = device.limits().max_buffer_size; - for part in &cells { - uniform_buffer_len(grid_rect_count(*part, self.chunk)?, plan.passes.len(), buffer_limit)?; - } - if self.frame == 0 { - // The first submission after device creation is dropped on some drivers (RADV), - // which would render the first frame black; land it on an empty buffer instead. - queue.submit(std::iter::empty::()); - } - self.frame += 1; - self.stamp += 1; - self.staged = 0; - self.recorded = 0; - self.layer_alloc = None; - self.admit_freed = 0; - - // Only render owns submission. A caller may discard encode's command buffer, so it - // cannot establish (or consume) a checkpoint whose GPU copy might never execute. - // Runs of plain layers drawn as one pass each (`fs_layerbatch`). The grouping is the same - // for every render of this plan, so a layer's bits don't depend on the cache: renders - // capture and resume only where a run starts. - let runs = batch_runs(&plan); - let checkpoint = if flush { - let starts = run_starts(&runs); - let resumable: Vec<_> = plan.checkpoints.iter().filter(|c| starts.get(c.pass_end).copied().unwrap_or(false)).copied().collect(); - self.prefix.prepare(doc, &resumable) - } else { - None - }; - - // Effect maps of whole regions first (they may render group shapes through sub-plans); - // regions larger than the limit are built per cell below. - let paged: Vec = plan.fx.iter().map(|f| self.fx_paged(f.region)).collect(); - let aprons: Vec = plan.fx.iter().zip(&paged).map(|(f, &pg)| if pg { Self::fx_apron(doc, f) } else { 0 }).collect(); - for (f, &pg) in plan.fx.iter().zip(&paged) { - if !pg { - self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, None), f.region, &mut stats)?; - } - } - let fr = self.frame_res(device, queue, canvas, &plan); - - // Page cells; every other frame in reverse, so a repeated full refresh of a document - // larger than the budget starts with the pages still resident. - if self.frame.is_multiple_of(2) { - cells.reverse(); - } - if let Some(f) = self.focus { - let p = page as i32; - let focused = |r: &Rect| !cell_rect((r.x0.div_euclid(p), r.y0.div_euclid(p)), page).intersect(&f).is_empty(); - cells.sort_by_key(focused); - } - let flush_bytes = FLUSH_BYTES.min(self.memory_budget() / 8).max(16 << 20); - stats.cells = cells.len(); - // The previous intermediate submit (see `submit_batch`). - let mut last_submit: Option = None; - // Work recorded and bytes evicted since the last submit. - let (mut work, mut freed) = (0u64, 0u64); - for part in cells { - self.stamp += 1; - let cell = (part.x0.div_euclid(page as i32), part.y0.div_euclid(page as i32)); - let cr = cell_rect(cell, page); - for (i, f) in plan.fx.iter().enumerate() { - let pf = cr.intersect(&f.region); - if !paged.get(i).copied().unwrap_or(false) || pf.is_empty() { - continue; - } - let window = pf.inflate(aprons.get(i).copied().unwrap_or(0)).intersect(&f.region); - self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, Some(cell)), window, &mut stats)?; - } - let chunks = grid_rects(part, self.chunk); - stats.chunks += chunks.len(); - work += part.width() as u64 * part.height() as u64 * plan.passes.len() as u64; - let mut batch = flush.then_some(&mut last_submit); - self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch); - // The device was lost in a submit inside the cell: issue no more work. - if let Some(f) = self.fault() { - return Err(Unsupported(f.to_string())); - } - // Out of memory although every page this cell doesn't use was dropped: the work recorded - // since the last submit can still hold those pages. Submit it, wait until the GPU is done - // with it so their memory is released, and run the cell once more. `encode` can't - // submit, so there the refresh goes to the CPU straight away. - if flush && self.layer_alloc.as_deref() == Some(OVER_BUDGET) { - self.layer_alloc = None; - submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), &mut last_submit); - #[cfg(not(target_arch = "wasm32"))] - { - let idle = match self.health.as_ref() { - Some(h) => h.wait_idle(device, last_submit.clone()), - None => device.poll(wgpu::PollType::Wait { submission_index: last_submit.clone(), timeout: None }).is_ok(), - }; - // The GPU has run every timestamp submitted so far, so a retry that fails too - // can drop this measurement without switching timing off for good. - if idle && let Some(t) = self.timer.as_mut() { - t.drained(); - } - } - self.staged = 0; - self.recorded = 0; - work = 0; - freed = 0; - self.admit_freed = 0; - stats.flushes += 1; - if let Some(f) = self.fault() { - return Err(Unsupported(f.to_string())); - } - let mut batch = Some(&mut last_submit); - self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch); - if let Some(f) = self.fault() { - return Err(Unsupported(f.to_string())); - } - } - // A page didn't fit even after evicting: this refresh goes to the CPU, the next one - // tries the GPU again (#6563). - if let Some(e) = self.layer_alloc.take() { - return Err(Unsupported(e)); - } - let (evicted, bytes) = self.evict(); - stats.evicted += evicted; - freed = freed.saturating_add(bytes.saturating_add(std::mem::take(&mut self.admit_freed))); - if flush && (self.staged >= flush_bytes || work >= FLUSH_WORK || freed >= flush_bytes || self.recorded >= FLUSH_OPS) { - submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), &mut last_submit); - self.staged = 0; - self.recorded = 0; - work = 0; - freed = 0; - stats.flushes += 1; - // The device was lost mid-refresh: issue no more work. - if let Some(f) = self.fault() { - return Err(Unsupported(f.to_string())); - } - } - } - - // Evict this document's textures whose layers are gone (hidden layers stay resident so - // toggling visibility costs no upload). - let frame = self.frame; - let live: std::collections::HashSet = doc.walk().into_iter().map(|(_, _, l)| l.id).collect(); - self.residents.retain(|(id, _, _), r| r.doc != doc.id || r.last_used == frame || live.contains(id)); - self.fx.retain(|(id, _), e| e.doc != doc.id || e.last_used == frame || live.contains(id)); - stats.evicted += self.evict().0; - self.temps.retain(|(_, used)| frame.saturating_sub(*used) < 240); - self.evict_patterns(); - Ok(stats) - } - - /// Drop the pattern textures no frame has painted with for [`PATTERN_IDLE_FRAMES`] frames, - /// then the least recently painted ones over the pattern budget. Never one this frame painted - /// with: it would only be uploaded again on the next frame. - fn evict_patterns(&mut self) { - let frame = self.frame; - self.patterns.retain(|_, p| frame.saturating_sub(p.last_used) < PATTERN_IDLE_FRAMES); - let mut total = self.pattern_cache_bytes(); - if total > self.pattern_budget { - let mut lru: Vec<(u64, String, u64)> = - self.patterns.iter().filter(|(_, p)| p.last_used != frame).map(|(k, p)| (p.last_used, k.clone(), p.bytes)).collect(); - lru.sort_unstable(); - for (_, key, bytes) in lru { - if total <= self.pattern_budget { - break; - } - self.patterns.remove(&key); - total = total.saturating_sub(bytes); - } - } - } - - /// Keep resident pages within the resident budget and the effect cache within - /// its budget, least recently used first. Never drops what the current cell uses, nor - /// whole-region effect maps drawn this frame. Returns how many textures were dropped and - /// their bytes. - fn evict(&mut self) -> (usize, u64) { - let (mut n, mut freed) = self.evict_residents(self.resident_budget, 0, None); - let mut total = self.fx_cache_bytes(); - let fx_budget = usize::try_from(self.fx_budget).unwrap_or(usize::MAX); - if total > fx_budget { - let (frame, stamp) = (self.frame, self.stamp); - let mut lru: Vec<((u64, u64), FxKey)> = self - .fx - .iter() - .filter(|(k, e)| e.last_used != frame || (k.1.is_some() && e.stamp != stamp)) - .map(|(k, e)| ((e.last_used, e.stamp), *k)) - .collect(); - lru.sort_unstable_by_key(|c| c.0); - for (_, k) in lru { - if total <= fx_budget { - break; - } - if let Some(e) = self.fx.remove(&k) { - total = total.saturating_sub(e.bytes()); - n += 1; - freed += e.bytes() as u64; - } - } - } - (n, freed) - } - - /// Drop least recently used resident pages until `incoming` more bytes fit in `budget`. - /// Never drops what the current cell uses, nor `keep`. Returns how many pages were dropped - /// and their bytes. - fn evict_residents(&mut self, budget: u64, incoming: u64, keep: Option) -> (usize, u64) { - let stamp = self.stamp; - let pages: Vec<(u64, ResKey, u64)> = - self.residents.iter().filter(|(k, r)| r.stamp != stamp && Some(**k) != keep).map(|(k, r)| (r.stamp, *k, r.bytes())).collect(); - let (mut n, mut freed) = (0, 0u64); - for k in lru_victims(pages, self.resident_bytes(), incoming, budget) { - if let Some(r) = self.residents.remove(&k) { - n += 1; - freed += r.bytes(); - } - } - (n, freed) - } - - /// Create the page texture for `key`, `bytes` large. Least recently used pages make room in - /// the budget first; when the device is still out of memory, every page the current cell - /// doesn't use is dropped and creation is tried once more (#6563). `None` (with - /// `layer_alloc` set) when it still fails: `render` submits the recorded work, which can still - /// hold the dropped pages, and runs the cell once more; after that the CPU draws the refresh. - fn create_layer_texture( - &mut self, - device: &wgpu::Device, - desc: &wgpu::TextureDescriptor<'_>, - key: ResKey, - bytes: u64, - stats: &mut Stats, - ) -> Option { - let replaced = self.residents.get(&key).map_or(0, Resident::bytes); - let (n, dropped) = self.evict_residents(self.resident_budget, bytes.saturating_sub(replaced), Some(key)); - stats.evicted += n; - self.admit_freed = self.admit_freed.saturating_add(dropped); - // WebGPU reports errors asynchronously: its failures reach the health callbacks. - if cfg!(target_arch = "wasm32") { - return Some(device.create_texture(desc)); - } - for retry in [false, true] { - let (texture, mut error) = first_error(device, || device.create_texture(desc)); - if error.is_none() && self.fail_allocs > 0 { - self.fail_allocs -= 1; - error = Some(wgpu::Error::OutOfMemory { source: "out of memory (test hook)".into() }); - } - match error { - None => return Some(texture), - Some(wgpu::Error::OutOfMemory { .. }) if !retry => { - let (n, dropped) = self.evict_residents(0, 0, Some(key)); - stats.evicted += n; - self.admit_freed = self.admit_freed.saturating_add(dropped); - } - Some(wgpu::Error::OutOfMemory { .. }) => { - self.layer_alloc = Some(OVER_BUDGET.into()); - return None; - } - Some(e) => { - self.layer_alloc = Some(format!("GPU layer texture failed: {e}")); - return None; - } - } - } - self.layer_alloc = Some(OVER_BUDGET.into()); - None - } - - /// Per-frame resources of `plan`: the tile area of each pass's surfaces, its LUT and pattern. - fn frame_res(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, canvas: Rect, plan: &Plan<'_>) -> FrameRes { - let grid = tile_grid(canvas); - let area = |s: &Surface| s.tile_bounds().intersect(&grid); - let areas = plan - .passes - .iter() - .map(|p| (p.tex.as_ref().map_or(Rect::EMPTY, |t| area(t.surface.get())), p.mask.as_ref().map_or(Rect::EMPTY, |m| area(m.surface.get())))) - .collect(); - let luts = plan.passes.iter().map(|p| p.lut.as_ref().map(|rows| lut_texture(device, queue, rows))).collect(); - let patterns = plan.passes.iter().map(|p| p.pattern.map(|pat| self.pattern_view(device, queue, pat))).collect(); - FrameRes { areas, luts, patterns } - } - - /// Bring the pages of `cell` that `plan` samples up to date and resolve its effect maps. - #[allow(clippy::too_many_arguments)] - fn bind_cell( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - doc: DocId, - plan: &Plan<'_>, - paged: &[bool], - cell: Cell, - fr: &FrameRes, - first_pass: usize, - stats: &mut Stats, - ) -> Bound { - let cr = cell_rect(cell, self.page); - let mut views: Vec<(Option, Option)> = Vec::with_capacity(plan.passes.len()); - let mut keys: Vec = Vec::new(); - let mut maps = Vec::with_capacity(plan.passes.len()); - for (i, p) in plan.passes.iter().enumerate() { - if i < first_pass { - views.push((None, None)); - maps.push(None); - continue; - } - let (ta, ma) = fr.areas.get(i).copied().unwrap_or((Rect::EMPTY, Rect::EMPTY)); - let tex = - p.tex.as_ref().and_then(|t| self.sync(device, queue, encoder, doc, (t.layer, t.role, cell), t.surface.get(), ta.intersect(&cr), stats)).map( - |(k, r)| { - keys.push(k); - (keys.len() - 1, r) - }, - ); - let mask = p - .mask - .as_ref() - .and_then(|m| self.sync(device, queue, encoder, doc, (m.layer, Role::Mask, cell), m.surface.get(), ma.intersect(&cr), stats)) - .map(|(k, r)| { - keys.push(k); - (keys.len() - 1, r) - }); - views.push((tex, mask)); - maps.push(p.map.and_then(|m| { - let f = plan.fx.get(m.fx)?; - let key = (f.layer.id, paged.get(m.fx).copied().unwrap_or(false).then_some(cell)); - let e = self.fx.get(&key)?; - if m.item == plan::SHAPE_MAP { - return Some((e.shape.view.clone(), e.region)); - } - let t = e.progs.get(m.item)?.maps.get(m.map)?.as_ref()?; - Some((t.view.clone(), e.region)) - })); - } - Bound { views, keys, maps } - } - - /// Run `plan` (drawn as `runs`, its `batch_runs`) over the `chunks` of one page cell - /// (document rects, at most a chunk square), handing each finished chunk to `sink`. - #[allow(clippy::too_many_arguments)] - fn run_cell( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - doc: DocId, - plan: &Plan<'_>, - runs: &[usize], - paged: &[bool], - cell: Cell, - fr: &FrameRes, - chunks: &[Rect], - checkpoint: Option, - stats: &mut Stats, - sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>), - // The previous intermediate submit, when this refresh may submit in between. - batch: &mut Option<&mut Option>, - ) { - if chunks.is_empty() { - return; - } - // Chunks may hold different checkpoints: bind from the lowest one any of them resumes at. - let first_pass = checkpoint - .and_then(|_| chunks.iter().map(|c| self.prefix.restore_point(*c).map(|r| r.pass_end)).try_fold(usize::MAX, |m, p| Some(m.min(p?)))) - .unwrap_or(0); - let bound = self.bind_cell(device, queue, encoder, doc, plan, paged, cell, fr, first_pass, stats); - // A page couldn't be created: draw nothing with the pages missing (the caller ends the refresh). - if self.layer_alloc.is_some() { - return; - } - - // Chunk pool. - while self.pool.len() < plan.slots as usize { - let t = device.create_texture(&wgpu::TextureDescriptor { - label: Some("pc_compose_chunk"), - size: wgpu::Extent3d { width: self.chunk, height: self.chunk, depth_or_array_layers: 1 }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: self.acc_format, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT - | wgpu::TextureUsages::TEXTURE_BINDING - | wgpu::TextureUsages::COPY_SRC - | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - let v = t.create_view(&Default::default()); - self.pool.push((t, v)); - } - - // Uniforms: chunk records, then one record per pass. encode_scoped preflight checked - // the length, device capacity and dynamic offsets before any GPU work for this frame. - let op_base = chunks.len() as u64 * STRIDE; - let mut data = vec![0u8; (op_base + plan.passes.len() as u64 * STRIDE) as usize]; - for (i, c) in chunks.iter().enumerate() { - let w = words(&[I(c.x0), I(c.y0), I(c.width() as i32), I(c.height() as i32)]); - data[i * STRIDE as usize..][..w.len()].copy_from_slice(&w); - } - for (i, p) in plan.passes.iter().enumerate() { - if i < first_pass { - continue; - } - let (tex, mask) = bound.views[i]; - let map = bound.maps[i].as_ref().map(|(_, r)| *r); - let run = runs.get(i).copied().unwrap_or(1); - let w = if run > 1 { - let extras: Vec<_> = (i + 1..i + run).filter_map(|j| Some((plan.passes.get(j)?, bound.views.get(j).and_then(|v| v.0).map(|t| t.1)))).collect(); - batch_op_words(p, tex.map(|t| t.1), mask.map(|m| m.1), &extras) - } else { - op_words(p, tex.map(|t| t.1), mask.map(|m| m.1), map) - }; - let off = (op_base + i as u64 * STRIDE) as usize; - data[off..][..w.len()].copy_from_slice(&w); - } - let ubuf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("pc_compose_uniforms"), - size: data.len() as u64, - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - queue.write_buffer(&ubuf, 0, &data); - let bg0 = uniform_group(device, &self.kit.bgl0, &ubuf); - - // Per-pass texture bind groups (chunk-independent: pool slots are reused per chunk). - let dummy = &self.kit.dummy; - let resident_views: Vec<&wgpu::TextureView> = bound.keys.iter().map(|k| self.residents.get(k).map_or(dummy, |r| &r.view)).collect(); - let mut bg1 = Vec::with_capacity(plan.passes.len()); - for (i, p) in plan.passes.iter().enumerate() { - if i < first_pass || p.kernel.entry().is_none() { - bg1.push(None); - continue; - } - let slot = |s: Option| s.map_or(dummy, |s| &self.pool[s as usize].1); - let (tex, mask) = &bound.views[i]; - let tv = tex.map_or(slot(p.d), |(k, _)| resident_views[k]); - let mv = mask.map_or(dummy, |(k, _)| resident_views[k]); - let lv = fr.luts.get(i).and_then(Option::as_ref).map_or(dummy, |(_, v)| v); - let map = bound.maps[i].as_ref().map_or(dummy, |(v, _)| v); - let pat = fr.patterns.get(i).and_then(Option::as_ref).unwrap_or(dummy); - let run = runs.get(i).copied().unwrap_or(1); - if run > 1 { - // The extra layers' pixels in tex_b, tex_c and map_tex (`batch_layer`). - let extra = |e: usize| bound.views.get(i + e).and_then(|v| v.0).map_or(dummy, |(k, _)| resident_views[k]); - bg1.push(Some(texture_group(device, &self.kit.bgl1, &[slot(p.a), extra(1), tv, mv, lv, extra(2), extra(3), pat]))); - continue; - } - bg1.push(Some(texture_group(device, &self.kit.bgl1, &[slot(p.a), slot(p.b), tv, mv, lv, slot(p.c), map, pat]))); - } - - for (ci, c) in chunks.iter().enumerate() { - let mut resume = 0; - if let Some(cp) = checkpoint.and_then(|_| self.prefix.restore_point(*c)) - && let Some((dst, _)) = self.pool.get(cp.slot as usize) - && self.prefix.copy_out(encoder, *c, dst) - { - resume = cp.pass_end; - stats.prefix_hits = stats.prefix_hits.saturating_add(1); - stats.prefix_passes_skipped = stats.prefix_passes_skipped.saturating_add(resume); - } - // Passes drawn inside the previous `fs_layerbatch` pass. - let mut batched_to = 0; - for (i, p) in plan.passes.iter().enumerate() { - if i < resume || i < batched_to { - continue; - } - // Chunk textures, uniforms and bind groups outlive the submit, and the queue - // keeps the order, so a chunk may continue in the next command buffer. - if self.recorded >= FLUSH_OPS - && let Some(last) = batch.as_deref_mut() - { - submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), last); - self.staged = 0; - self.recorded = 0; - stats.flushes += 1; - if self.fault().is_some() { - return; - } - } - // Also after resuming from a lower checkpoint: the chunk moves up to this one. - if resume < i - && let Some(cp) = checkpoint.filter(|cp| cp.pass_end == i) - && let Some((src, _)) = self.pool.get(cp.slot as usize) - { - self.prefix.capture(device, encoder, *c, src, cp); - } - let scissor = match p.clip { - Some(clip) => { - let r = clip.intersect(c); - if r.is_empty() { - continue; - } - Rect::new(r.x0 - c.x0, r.y0 - c.y0, r.x1 - c.x0, r.y1 - c.y0) - } - None => Rect::new(0, 0, c.width() as i32, c.height() as i32), - }; - match p.kernel { - Kernel::CopyRect | Kernel::CopyFull => { - // The planner always gives copies a source. - let Some(a) = p.a else { continue }; - let src = &self.pool[a as usize].0; - let dst = &self.pool[p.dst as usize].0; - encoder.copy_texture_to_texture( - wgpu::TexelCopyTextureInfo { - texture: src, - mip_level: 0, - origin: wgpu::Origin3d { x: scissor.x0 as u32, y: scissor.y0 as u32, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - wgpu::TexelCopyTextureInfo { - texture: dst, - mip_level: 0, - origin: wgpu::Origin3d { x: scissor.x0 as u32, y: scissor.y0 as u32, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - wgpu::Extent3d { width: scissor.width(), height: scissor.height(), depth_or_array_layers: 1 }, - ); - self.recorded += 1; - continue; - } - _ => {} - } - self.recorded += 1; - // A run draws as one pass into the slot its last layer writes. - let run = runs.get(i).copied().unwrap_or(1); - let (kernel, dst) = match plan.passes.get(i + run - 1) { - Some(last) if run > 1 => { - batched_to = i + run; - stats.layers_batched = stats.layers_batched.saturating_add(run - 1); - let kernel = plan.passes.get(i..i + run).map_or(Kernel::LayerBatch, batch_kernel); - if kernel == Kernel::LayerBatchNormal { - stats.normal_batches = stats.normal_batches.saturating_add(1); - } - (kernel, last.dst) - } - _ => (p.kernel, p.dst), - }; - let target = &self.pool[dst as usize].1; - let clear = p.kernel == Kernel::Clear; - let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("pc_compose_pass"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: target, - resolve_target: None, - depth_slice: None, - ops: wgpu::Operations { - load: if clear { wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT) } else { wgpu::LoadOp::Load }, - store: wgpu::StoreOp::Store, - }, - })], - depth_stencil_attachment: None, - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); - if clear { - continue; - } - pass.set_pipeline(&self.kit.pipelines[&(kernel, self.acc_format)]); - pass.set_scissor_rect(scissor.x0 as u32, scissor.y0 as u32, scissor.width(), scissor.height()); - pass.set_bind_group(0, &bg0, &[(ci as u64 * STRIDE) as u32, (op_base + i as u64 * STRIDE) as u32]); - pass.set_bind_group(1, bg1[i].as_ref(), &[]); - pass.draw(0..3, 0..1); - } - if resume < plan.passes.len() - && let Some(cp) = checkpoint.filter(|cp| cp.pass_end == plan.passes.len()) - && let Some((src, _)) = self.pool.get(cp.slot as usize) - { - self.prefix.capture(device, encoder, *c, src, cp); - } - let (t, v) = &self.pool[plan.root as usize]; - sink(encoder, ChunkOut { rect: *c, texture: t, view: v }); - } - } - - /// Upload changed tiles of `surface` within `region` (its tile area inside one page cell); - /// returns the resident key and its region (x, y, w, h). - #[allow(clippy::too_many_arguments)] - fn sync( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - doc: DocId, - key: ResKey, - surface: &Surface, - region: Rect, - stats: &mut Stats, - ) -> Option<(ResKey, [i32; 4])> { - // An earlier page of this cell didn't fit: the refresh ends after the cell anyway. - if region.is_empty() || self.layer_alloc.is_some() { - return None; - } - let format = surface.format(); - let kind = TexKind::for_surface(key.1, format); - let cmyk = if format.mode == photocraft_color::ColorMode::Cmyk { self.cmyk } else { 0 }; - let default_pixel = surface.default_pixel(); - let default_bits: Vec = default_pixel.iter().map(|v| v.to_bits()).collect(); - let stale = self - .residents - .get(&key) - .is_none_or(|r| r.region != region || r.kind != kind || r.format != format || r.cmyk != cmyk || r.default_bits != default_bits); - if stale { - let desc = wgpu::TextureDescriptor { - label: Some("pc_compose_layer"), - size: wgpu::Extent3d { width: region.width(), height: region.height(), depth_or_array_layers: 1 }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: kind.format(), - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC, - view_formats: &[], - }; - let bytes = region.width() as u64 * region.height() as u64 * kind.bytes_per_pixel() as u64; - let texture = self.create_layer_texture(device, &desc, key, bytes, stats)?; - let view = texture.create_view(&Default::default()); - let default_nonzero = default_pixel.iter().any(|v| *v != 0.0); - let mut r = Resident { - texture, - view, - region, - kind, - format, - tiles: HashMap::new(), - default_nonzero, - default_bits: default_bits.clone(), - doc, - last_used: 0, - stamp: 0, - cmyk, - ordered: false, - }; - // Only the region moved (painting past a layer's tiles grows it): keep the texels the - // old texture already holds instead of converting and uploading every tile again. - let kept = self.residents.remove(&key).map_or(Rect::EMPTY, |old| keep_overlap(device, queue, &old, &mut r)); - // A new layer whose tiles another resident already holds (a duplicate shares its - // source's tiles) starts as a GPU copy of that texture. Duplicating a 20 MP photo - // converted and uploaded every tile again. - let shares = - |o: &Resident| region.tiles().filter(|c| surface.tile(*c).is_some_and(|t| o.tiles.get(c).is_some_and(|ot| Arc::ptr_eq(ot, t)))).count(); - let donor = self - .residents - .iter() - .filter(|(k, o)| k.1 == key.1 && o.region == region && o.kind == kind && o.format == format && o.cmyk == cmyk && o.default_bits == default_bits) - .map(|(k, o)| (shares(o), *k)) - .filter(|(n, _)| *n > 0) - .max_by_key(|(n, _)| *n); - if kept.is_empty() - && let Some((n, o)) = donor.and_then(|(n, k)| Some((n, self.residents.get_mut(&k)?))) - { - // Recorded in the frame's encoder, after the writes and copies that brought the - // donor up to date ([`keep_overlap`]'s own submission would run before those). - o.ordered = true; - encoder.copy_texture_to_texture( - o.texture.as_image_copy(), - r.texture.as_image_copy(), - wgpu::Extent3d { width: region.width(), height: region.height(), depth_or_array_layers: 1 }, - ); - r.tiles = o.tiles.clone(); - r.ordered = true; - stats.tiles_shared += n; - } else { - // A new texture starts zeroed: write the tiles that are present, and the default - // pixel where they are missing if it isn't zero. Coordinates sharing a tile (a - // solid fill, the default) take one upload and GPU copies (#1774). Kept tiles are - // brought up to date below, like those of a resident that didn't move. - let mut present = Vec::new(); - let mut missing = Vec::new(); - for c in region.tiles().filter(|c| !kept.contains_rect(&c.rect())) { - match surface.tile(c) { - Some(t) => present.push((c, t.clone())), - None if default_nonzero => missing.push(c), - None => {} - } - } - if !missing.is_empty() { - let bytes = convert_tile(surface, None, kind, TileCoord::new(0, 0)); - self.staged += put_tiles(device, queue, encoder, &r, &missing, &bytes); - } - let staged = &mut self.staged; - convert_tiles(surface, present, kind, |t, cs, bytes| { - *staged += put_tiles(device, queue, encoder, &r, cs, bytes); - for &c in cs { - stats.tiles_uploaded += 1; - stats.bytes_uploaded += bytes.len(); - r.tiles.insert(c, t.clone()); - } - }); - } - // Tiles the donor held that this surface doesn't, or holds differently, are fixed up - // by the pass over the region below. - self.residents.insert(key, r); - } - // Present: inserted above when it was missing or stale. - let r = self.residents.get_mut(&key)?; - r.last_used = self.frame; - r.stamp = self.stamp; - r.doc = doc; - let mut changed = Vec::new(); - let mut gone = Vec::new(); - for c in region.tiles() { - match surface.tile(c) { - Some(t) => { - if !r.tiles.get(&c).is_some_and(|old| Arc::ptr_eq(old, t)) { - changed.push((c, t.clone())); - } - } - None => { - if r.tiles.remove(&c).is_some() { - gone.push(c); - } - } - } - } - if !gone.is_empty() { - // A tile that went away reads as the default pixel again. - let bytes = if r.default_nonzero { - convert_tile(surface, None, kind, TileCoord::new(0, 0)) - } else { - vec![0u8; (TILE_SIZE * TILE_SIZE) as usize * kind.bytes_per_pixel()] - }; - self.staged += put_tiles(device, queue, encoder, r, &gone, &bytes); - } - let staged = &mut self.staged; - convert_tiles(surface, changed, kind, |t, cs, bytes| { - *staged += put_tiles(device, queue, encoder, r, cs, bytes); - for &c in cs { - stats.tiles_uploaded += 1; - stats.bytes_uploaded += bytes.len(); - r.tiles.insert(c, t.clone()); - } - }); - Some((key, [region.x0, region.y0, region.width() as i32, region.height() as i32])) - } - - /// Premultiplied RGBA32F texture of a pattern as it paints in the document's mode (cached by - /// pixel identity and mode). - fn pattern_view(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, pat: &Pattern) -> wgpu::TextureView { - let fp = pat.surface.tiles().fold((pat.width as u64) << 32 | pat.height as u64, |acc, (c, t)| { - acc.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ (Arc::as_ptr(t) as usize as u64) ^ ((c.tx as u64) << 20) ^ c.ty as u64 - }); - let mode = self.pattern_mode; - let key = format!("{}\u{0}{}\u{0}{mode:?}", pat.id, pat.name); - let format = pat.surface.format(); - // Unstored tiles read the default pixel, interpreted in the source format. - let default_bits: Vec = pat.surface.default_pixel().iter().map(|v| v.to_bits()).collect(); - let (doc, last_used) = (self.pattern_doc, self.frame); - if let Some(cached) = self.patterns.get_mut(&key) - && cached.fingerprint == fp - && cached.format == format - && cached.default_bits == default_bits - { - cached.doc = doc; - cached.last_used = last_used; - return cached.texture.view.clone(); - } - let (w, h) = (pat.width, pat.height); - let px = photocraft_compose::pattern::pattern_rgba(pat, mode); - let bytes: Vec = px.iter().flat_map(|q| [q[0] * q[3], q[1] * q[3], q[2] * q[3], q[3]]).flat_map(f32::to_le_bytes).collect(); - let t = Tex::new(device, "pc_pattern", w, h, wgpu::TextureFormat::Rgba32Float, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST); - queue.write_texture( - wgpu::TexelCopyTextureInfo { texture: &t.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - &bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 16), rows_per_image: Some(h) }, - wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, - ); - let v = t.view.clone(); - let bytes = u64::from(w.max(1)) * u64::from(h.max(1)) * 16; - self.patterns.insert(key, CachedPattern { fingerprint: fp, format, default_bits, texture: t, doc, last_used, bytes }); - v - } - - /// An R32F temporary at least `region`-sized (the smallest that fits) not in `taken`. - /// Stages only read what they wrote, inside the region, so a larger one is as good; page - /// windows of different sizes share them. - fn temp(&mut self, device: &wgpu::Device, region: Rect, taken: &[wgpu::TextureView]) -> wgpu::TextureView { - let (w, h) = (region.width(), region.height()); - let frame = self.frame; - let fit = self - .temps - .iter_mut() - .filter(|(t, _)| { - let s = t.texture.size(); - s.width >= w && s.height >= h && !taken.contains(&t.view) - }) - .min_by_key(|(t, _)| t.texture.size().width as u64 * t.texture.size().height as u64); - if let Some((t, used)) = fit { - *used = frame; - return t.view.clone(); - } - let t = Tex::map(device, "pc_fx_temp", region, MAP32); - let v = t.view.clone(); - self.temps.push((t, frame)); - v - } - - /// Build or update the effect maps of one layer over `region`: its whole effect region, or - /// the window of one page cell (`key.1`) grown by the effects' reach. - #[allow(clippy::too_many_arguments)] - fn sync_fx( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - doc: &Document, - f: &plan::FxLayer<'_>, - key: FxKey, - region: Rect, - stats: &mut Stats, - ) -> Result<(), Unsupported> { - let layer = f.layer; - let canvas = doc.bounds(); - let is_group = matches!(layer.content, LayerContent::Group(_)); - let shape_key = if is_group { fx::group_key(layer, &doc.global_light, &mut |_| {}) } else { fx::shape_key(layer, canvas) }; - let (content_src, mask_src) = if is_group { (None, None) } else { fx::shape_sources(layer) }; - let frame = self.frame; - let (rw, rh) = (region.width(), region.height()); - - // What changed: everything (new settings / size), the position only, some tiles, or - // nothing. - let mut damage = Rect::EMPTY; - let prev = self.fx.get(&key).filter(|e| e.shape_key == shape_key).map(|e| e.region); - let mut rebuild = true; - if prev == Some(region) - && let Some(e) = self.fx.get(&key) - { - rebuild = false; - for (old, cur) in e.tiles.iter().zip([content_src, mask_src]) { - let d = match (old, cur) { - (Some(o), Some(s)) => fx::damage(o, s), - (None, None) => Rect::EMPTY, - // A source appeared or vanished (the key changes with it too). - _ => region, - }; - damage = if damage.is_empty() { d } else { damage.union(&d) }; - } - damage = damage.intersect(®ion); - } else if let Some(old) = prev - && (old.width(), old.height()) == (rw, rh) - && !region.is_empty() - { - // Moved by whole pixels: maps are computed relative to the region, so if the shape - // moved unchanged with it, every map is still exact. - let v = fx::shape(doc, layer, region); - if let Some(e) = self.fx.get_mut(&key) - && v == e.shape_cpu - { - e.region = region; - rebuild = false; - } - } - if rebuild { - let shape = Tex::map(device, "pc_fx_shape", region, MAP32); - let n = rw as usize * rh as usize; - self.fx.insert( - key, - FxEntry { - doc: doc.id, - region, - shape_key, - tiles: [None, None], - _pin: if is_group { - let mut pin = Vec::new(); - fx::group_key(layer, &doc.global_light, &mut |t| pin.push(Arc::downgrade(t))); - pin - } else { - Vec::new() - }, - shape_cpu: vec![0.0; n], - shape, - fields: HashMap::new(), - progs: Vec::new(), - last_used: frame, - stamp: 0, - }, - ); - damage = region; - } - // Present: kept or (re)inserted above. - let stamp = self.stamp; - let Some(e) = self.fx.get_mut(&key) else { return Ok(()) }; - e.last_used = frame; - e.stamp = stamp; - e.doc = doc.id; - e.tiles = [content_src.map(fx::snapshot), mask_src.map(fx::snapshot)]; - if region.is_empty() { - return Ok(()); - } - - let t_trace = web_time_now(); - let mut staged = 0u64; - // Shape over the damage (compose's own alpha). - if !damage.is_empty() { - stats.fx_shapes += 1; - let v = fx::shape(doc, layer, damage); - fx::paste(&mut e.shape_cpu, region, damage, &v); - e.shape.write_r32(queue, region, damage, &v); - staged += v.len() as u64 * 4; - } - - // Programs, and the distance fields they read (max reach per field). - // Filled shapes stroke their outline (the effect shape); others estimate it. - let vector_shape = matches!(layer.content, LayerContent::Shape(_)) && photocraft_compose::effect_outline(layer).is_none(); - let anchor = layer.effects.reference.unwrap_or((f64::from(f.bounds.x0), f64::from(f.bounds.y0))); - let progs: Vec = - layer.effects.items.iter().filter(|e| e.enabled()).map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, anchor)).collect(); - let want = field_reaches(&progs); - e.fields.retain(|k, _| want.contains_key(k)); - // Each field to recompute: over which rectangle, exact up to which reach. - let jobs: Vec<(FieldKind, Rect, i32)> = want - .iter() - .filter_map(|(&kind, &reach)| match e.fields.get(&kind).map(|(r, _)| *r) { - Some(r) if r >= reach => (!damage.is_empty()).then(|| (kind, damage.inflate(fx::field_radius(kind, r)).intersect(®ion), r)), - _ => Some((kind, region, reach)), - }) - .collect(); - // A chiselled bevel's two fields are asked for and kept together (`fx::bevel_fields`), so they - // are recomputed together, over one rectangle at one reach. - let job = |k: FieldKind| jobs.iter().find(|j| j.0 == k).map(|j| (j.1, j.2)); - let (bevel_in, bevel_out) = (job(FieldKind::BevelInside), job(FieldKind::BevelOutside)); - if bevel_in != bevel_out { - return Err(Unsupported(format!("bevel fields of `{}` out of step: inside {bevel_in:?}, outside {bevel_out:?}", layer.name))); - } - for (kind, out, reach) in jobs { - let fields = match kind { - FieldKind::BevelInside => { - let [inside, outside] = fx::bevel_fields(reach, &e.shape_cpu, region, out); - vec![(FieldKind::BevelInside, inside), (FieldKind::BevelOutside, outside)] - } - // Computed with BevelInside, over the same rectangle at the same reach (checked above). - FieldKind::BevelOutside => continue, - _ => vec![(kind, fx::field(kind, reach, &e.shape_cpu, region, out))], - }; - for (kind, v) in fields { - if e.fields.get(&kind).is_none_or(|(r, _)| *r < reach) { - e.fields.insert(kind, (reach, Tex::map(device, "pc_fx_field", region, MAP32))); - } - if let Some((_, t)) = e.fields.get(&kind) { - t.write_r32(queue, region, out, &v); - } - staged += v.len() as u64 * 4; - stats.fx_pixels += out.width() as u64 * out.height() as u64; - } - } - - if let Some(t) = t_trace.filter(|_| !damage.is_empty()) { - eprintln!("effect maps of `{}`: shape + distance fields over {damage:?} in {:.2} ms (CPU)", layer.name, t.elapsed().as_secs_f64() * 1000.0); - } - e.progs.truncate(progs.len()); - while e.progs.len() < progs.len() { - e.progs.push(ProgState { key: 0, maps: Vec::new() }); - } - self.staged += staged; - for (i, prog) in progs.iter().enumerate() { - if prog.maps == 0 { - continue; - } - let Some(e) = self.fx.get_mut(&key) else { return Ok(()) }; - let same = e.progs[i].key == prog.key && e.progs[i].maps.len() == prog.maps; - let d = if same { damage } else { region }; - if d.is_empty() { - continue; - } - if !same { - e.progs[i] = ProgState { - key: prog.key, - maps: (0..prog.maps).map(|k| prog.stages.iter().any(|s| s.out == Some(k)).then(|| Tex::map(device, "pc_fx_map", region, MAP16))).collect(), - }; - } - stats.fx_programs += 1; - self.run_program(device, queue, encoder, key, i, prog, d, stats); - } - Ok(()) - } - - /// Record the passes of `prog` (maps of item `item` of `layer`) recomputing damage `d`. - #[allow(clippy::too_many_arguments)] - fn run_program( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - key: FxKey, - item: usize, - prog: &fx::MapProgram, - d: Rect, - stats: &mut Stats, - ) { - let pattern_views: Vec> = - prog.stages.iter().map(|s| s.pattern.as_ref().map(|p| self.pattern_view(device, queue, p))).collect(); - let Some(e) = self.fx.get(&key) else { return }; - let region = e.region; - let shape = e.shape.view.clone(); - let finals: Vec> = e.progs[item].maps.iter().map(|m| m.as_ref().map(|t| t.view.clone())).collect(); - let fields: HashMap = e.fields.iter().map(|(k, (r, t))| (*k, (*r, t.view.clone()))).collect(); - let windows = prog.windows(d, region, &|k| fields.get(&k).map_or(0, |f| f.0)); - let (assign, count) = prog.temps(); - let mut temps: Vec = Vec::with_capacity(count); - for _ in 0..count { - let v = self.temp(device, region, &temps); - temps.push(v); - } - // `None` only if a program's map or temporary wasn't allocated, which `sync_fx` and - // `MapProgram::temps` rule out. - let target_of = |i: usize| -> Option<(wgpu::TextureView, wgpu::TextureFormat)> { - match prog.stages[i].out { - Some(k) => Some((finals.get(k)?.clone()?, MAP16)), - None => Some((temps.get((*assign.get(i)?)?)?.clone(), MAP32)), - } - }; - let view_of = |inp: Option| -> Option { - match inp? { - fx::In::Shape => Some(shape.clone()), - fx::In::Field(k) => fields.get(&k).map(|f| f.1.clone()), - fx::In::Val(k) => target_of(k).map(|t| t.0), - } - }; - let mut draws = Vec::with_capacity(prog.stages.len()); - for (i, s) in prog.stages.iter().enumerate() { - let w = windows[i]; - if w.is_empty() { - continue; - } - stats.fx_pixels += w.width() as u64 * w.height() as u64; - let Some((target, format)) = target_of(i) else { continue }; - let mut p = plan::Pass::new(s.kernel, 0); - p.params[0] = s.p0; - p.params[1] = s.p1; - p.params[3] = s.p3; - p.extra = s.p4; - draws.push(MapDraw { - kernel: s.kernel, - format, - target, - scissor: [(w.x0 - region.x0) as u32, (w.y0 - region.y0) as u32, w.width(), w.height()], - space: [region.x0, region.y0, region.width() as i32, region.height() as i32], - op: op_words(&p, None, None, None), - views: [view_of(s.a), view_of(s.b), view_of(s.s), None, None, None, None, pattern_views[i].clone()], - lut: s.lut.clone(), - }); - } - self.kit.run(device, queue, encoder, &draws); - } -} - -/// A start time when `PHOTOCRAFT_FX_TRACE=1` (it prints the CPU time of effect shapes and -/// distance fields); never on wasm. -fn web_time_now() -> Option { - #[cfg(not(target_arch = "wasm32"))] - { - static T: std::sync::OnceLock = std::sync::OnceLock::new(); - T.get_or_init(|| std::env::var_os("PHOTOCRAFT_FX_TRACE").is_some()).then(std::time::Instant::now) - } - #[cfg(target_arch = "wasm32")] - None -} - -/// The uniform record of a pass. -fn op_words(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, map: Option) -> Vec { - words(&op_values(p, tex, mask, map)) -} - -/// The uniform record of the `fs_layerbatch` pass that draws `p` (whose texture and mask cover -/// `tex` and `mask`) and then `extras`, each an unmasked plain layer's `LayerBlend` pass with the -/// area its texture covers. Layout: see `batch_layer` in compose.wgsl. -fn batch_op_words(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, extras: &[(&plan::Pass<'_>, Option<[i32; 4]>)]) -> Vec { - let mut v = op_values(p, tex, mask, None); - // Word offsets of the record's vec4s holding the extra layers, three each: p0, p1, p2 | p3, - // q0, q1 | q2, q3, q4. - const AT: [usize; 9] = [20, 24, 28, 32, 44, 48, 52, 56, 60]; - if let Some(kind) = v.get_mut(1) { - *kind = I(extras.len().min(AT.len() / 3) as i32); - } - for (e, (x, area)) in extras.iter().take(AT.len() / 3).enumerate() { - let r = area.unwrap_or([0; 4]); - let geo = [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]; - let prm = [x.opacity, x.fill, plan::mode_index(x.mode) as f32, if area.is_some() { 1.0 } else { 0.0 }]; - for (k, vals) in [geo, x.color, prm].into_iter().enumerate() { - let at = AT[e * 3 + k]; - for (c, f) in vals.into_iter().enumerate() { - if let Some(w) = v.get_mut(at + c) { - *w = F(f); - } - } - } - } - words(&v) -} - -/// The words of a pass's uniform record (`Op` in compose.wgsl). -fn op_values(p: &plan::Pass<'_>, tex: Option<[i32; 4]>, mask: Option<[i32; 4]>, map: Option) -> Vec { - let mut flags = p.flags; - let (mut to, mut ts, mut mo, mut ms) = ([0; 2], [0; 2], [0; 2], [0; 2]); - if let Some(r) = tex { - flags |= 4; - to = [r[0], r[1]]; - ts = [r[2], r[3]]; - } - let (mut density, mut mdefault) = (0.0, 1.0); - if let Some(m) = &p.mask { - flags |= 1; - density = m.density; - mdefault = m.default; - if let Some(r) = mask { - flags |= 2; - mo = [r[0], r[1]]; - ms = [r[2], r[3]]; - } - } - if p.gradient { - flags |= 8; - } - let (mpo, mps) = map.map_or(([0, 0], [0, 0]), |r| ([r.x0, r.y0], [r.width() as i32, r.height() as i32])); - let mut v = vec![ - I(plan::mode_index(p.mode)), - I(p.adjust_kind), - U(flags), - U(0), - F(p.opacity), - F(density), - F(mdefault), - F(p.fill), - I(to[0]), - I(to[1]), - I(ts[0]), - I(ts[1]), - I(mo[0]), - I(mo[1]), - I(ms[0]), - I(ms[1]), - ]; - v.extend(p.color.iter().map(|f| F(*f))); - for row in &p.params { - v.extend(row.iter().map(|f| F(*f))); - } - v.extend([I(mpo[0]), I(mpo[1]), I(mps[0]), I(mps[1])]); - v.extend(p.extra.iter().map(|f| F(*f))); - // q0..q4: only `fs_layerbatch` reads them (`batch_op_words`). - v.extend((0..20).map(|_| F(0.0))); - v -} - -/// Most layers one `fs_layerbatch` pass blends: its own and the three more its record holds. -const BATCH: usize = 4; - -/// For each pass, how many passes from it on the executor draws as one `fs_layerbatch` pass -/// (1: the pass alone). A run starts at a `LayerBlend` pass over the whole chunk (no clip) that -/// isn't a gradient (whose parameters use the words the extra layers go in), and continues while -/// the next pass is a `LayerBlend` of an unmasked plain layer (no text gamma, no Dissolve) onto -/// exactly what the previous pass wrote, a slot nothing else reads before it is written again. -/// A run never ends in the slot it reads from. -/// -/// The runs depend on the plan alone, never on the prefix cache: a compiler may give a layer -/// other bits batched than drawn alone (FXC on D3D12 does), and reusing a prefix must stay exact -/// (#5286). The cache captures and resumes only at `run_starts` instead. -fn batch_runs(plan: &Plan<'_>) -> Vec { - let passes = &plan.passes; - let n = passes.len(); - let reads = |p: &plan::Pass<'_>, s: plan::Slot| [p.a, p.b, p.c, p.d].contains(&Some(s)); - // feeds_next[i]: what pass i writes is read by pass i + 1 alone. - let feeds_next: Vec = (0..n) - .map(|i| { - let (Some(this), Some(next)) = (passes.get(i), passes.get(i + 1)) else { return false }; - let dst = this.dst; - if next.a != Some(dst) || [next.b, next.c, next.d].contains(&Some(dst)) { - return false; - } - for later in passes.iter().skip(i + 2) { - // A copy into a slot keeps what lies outside its rect: that is a read too. - if reads(later, dst) || (later.dst == dst && later.kernel == Kernel::CopyRect) { - return false; - } - if later.dst == dst { - return true; - } - } - dst != plan.root - }) - .collect(); - let lead = |p: &plan::Pass<'_>| p.kernel == Kernel::LayerBlend && p.clip.is_none() && !p.gradient; - let extra = |p: &plan::Pass<'_>| lead(p) && p.mask.is_none() && p.flags & plan::F_TEXT_GAMMA == 0 && p.mode != photocraft_color::BlendMode::Dissolve; - (0..n) - .map(|i| { - let Some(first) = passes.get(i).filter(|p| lead(p)) else { return 1 }; - let (mut k, mut best) = (1, 1); - while k < BATCH && feeds_next.get(i + k - 1).copied().unwrap_or(false) && passes.get(i + k).is_some_and(extra) { - k += 1; - if passes.get(i + k - 1).is_some_and(|p| Some(p.dst) != first.a) { - best = k; - } - } - best - }) - .collect() -} - -/// For each pass and the end of the plan, whether the executor draws `runs` (`batch_runs`) so -/// that a pass starts there rather than inside a run. -fn run_starts(runs: &[usize]) -> Vec { - let mut starts = vec![false; runs.len() + 1]; - let mut i = 0; - while let Some(s) = starts.get_mut(i) { - *s = true; - i += runs.get(i).copied().unwrap_or(1).max(1); - } - starts -} - -/// The pipeline that draws `run` (passes `batch_runs` joined): `fs_layerbatch_normal` when every -/// layer blends Normal without text gamma outside Lab documents, else `fs_layerbatch`. -fn batch_kernel(run: &[plan::Pass<'_>]) -> Kernel { - let normal = |p: &plan::Pass<'_>| p.mode == photocraft_color::BlendMode::Normal && p.flags & (plan::F_TEXT_GAMMA | plan::F_LAB) == 0; - if run.iter().all(normal) { Kernel::LayerBatchNormal } else { Kernel::LayerBatch } -} - -/// Canvas rounded out to whole tiles. -fn tile_grid(canvas: Rect) -> Rect { - let t = TILE_SIZE; - Rect::new(canvas.x0.div_euclid(t) * t, canvas.y0.div_euclid(t) * t, (canvas.x1 + t - 1).div_euclid(t) * t, (canvas.y1 + t - 1).div_euclid(t) * t) -} - -fn write_tile(queue: &wgpu::Queue, r: &Resident, c: TileCoord, bytes: &[u8]) { - let tr = c.rect(); - let bpp = r.kind.bytes_per_pixel() as u32; - queue.write_texture( - wgpu::TexelCopyTextureInfo { - texture: &r.texture, - mip_level: 0, - origin: wgpu::Origin3d { x: (tr.x0 - r.region.x0) as u32, y: (tr.y0 - r.region.y0) as u32, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(TILE_SIZE as u32 * bpp), rows_per_image: Some(TILE_SIZE as u32) }, - wgpu::Extent3d { width: TILE_SIZE as u32, height: TILE_SIZE as u32, depth_or_array_layers: 1 }, - ); -} - -/// Submit what `encoder` recorded and continue in a fresh one, then wait for the previous -/// intermediate submit (`last`), so at most two batches of uploads and evicted pages are in -/// flight. The web has no blocking wait and relies on the browser's own scheduling. -fn submit_batch( - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - health: Option<&DeviceHealth>, - timer: Option<&mut timing::GpuTimer>, - last: &mut Option, -) { - let mut done = std::mem::replace(encoder, device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") })); - if let Some(t) = timer { - // One refresh, several command buffers: the measurement spans all of them. - t.split(&mut done, encoder); - } - let prev = last.replace(queue.submit([done.finish()])); - #[cfg(not(target_arch = "wasm32"))] - if let Some(prev) = prev { - match health { - Some(h) => { - h.wait(device, Some(prev)); - } - None => { - let _ = device.poll(wgpu::PollType::Wait { submission_index: Some(prev), timeout: None }); - } - } - } - #[cfg(target_arch = "wasm32")] - let _ = (prev, health); -} - -/// Distinct tiles converted per parallel batch: bounds the converted bytes held at once (64 tiles -/// of a 16-bit page are 32 MiB). -const CONVERT_BATCH: usize = 64; - -/// Write the same tile `bytes` at every coordinate in `cs` of resident `r`; returns the bytes -/// staged. Several coordinates (a solid fill or a cleared area shares one tile) get one upload to -/// a scratch tile and GPU copies from it: writing each one from the CPU sent 387 MB per refresh -/// of a filled 50 MP 16-bit page (#1774). -fn put_tiles(device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, r: &Resident, cs: &[TileCoord], bytes: &[u8]) -> u64 { - if let [c] = cs - && !r.ordered - { - write_tile(queue, r, *c, bytes); - return bytes.len() as u64; - } - if cs.is_empty() { - return 0; - } - let extent = wgpu::Extent3d { width: TILE_SIZE as u32, height: TILE_SIZE as u32, depth_or_array_layers: 1 }; - // Its own texture per call: queued writes land before the encoder runs, so a shared scratch - // would hold only the last tile by then. - let scratch = device.create_texture(&wgpu::TextureDescriptor { - label: Some("pc_tile_scratch"), - size: extent, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: r.kind.format(), - usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - queue.write_texture( - wgpu::TexelCopyTextureInfo { texture: &scratch, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - bytes, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(TILE_SIZE as u32 * r.kind.bytes_per_pixel() as u32), - rows_per_image: Some(TILE_SIZE as u32), - }, - extent, - ); - for c in cs { - let tr = c.rect(); - encoder.copy_texture_to_texture( - wgpu::TexelCopyTextureInfo { texture: &scratch, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - wgpu::TexelCopyTextureInfo { - texture: &r.texture, - mip_level: 0, - origin: wgpu::Origin3d { x: (tr.x0 - r.region.x0) as u32, y: (tr.y0 - r.region.y0) as u32, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - extent, - ); - } - bytes.len() as u64 -} - -/// Copy the texels `old` holds inside the region of its replacement `new` (same texel kind, -/// format and default pixel; only the region moved) and carry over the tiles they show, so only -/// tiles outside the overlap or changed since need uploading. Returns the kept (tile-aligned) -/// rect; empty when nothing can be kept. -fn keep_overlap(device: &wgpu::Device, queue: &wgpu::Queue, old: &Resident, new: &mut Resident) -> Rect { - let same = old.kind == new.kind && old.format == new.format && old.cmyk == new.cmyk && old.default_bits == new.default_bits; - let k = old.region.intersect(&new.region); - if !same || k.is_empty() { - return Rect::EMPTY; - } - // Its own submission: tile writes go through the queue and land at the start of the next - // submit, before anything in the frame's encoder, so a copy recorded there would overwrite - // the tiles written after it with the old texels. - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose_keep") }); - encoder.copy_texture_to_texture( - wgpu::TexelCopyTextureInfo { - texture: &old.texture, - mip_level: 0, - origin: wgpu::Origin3d { x: (k.x0 - old.region.x0) as u32, y: (k.y0 - old.region.y0) as u32, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - wgpu::TexelCopyTextureInfo { - texture: &new.texture, - mip_level: 0, - origin: wgpu::Origin3d { x: (k.x0 - new.region.x0) as u32, y: (k.y0 - new.region.y0) as u32, z: 0 }, - aspect: wgpu::TextureAspect::All, - }, - wgpu::Extent3d { width: k.width(), height: k.height(), depth_or_array_layers: 1 }, - ); - queue.submit([encoder.finish()]); - new.tiles = old.tiles.iter().filter(|(c, _)| k.contains_rect(&c.rect())).map(|(c, t)| (*c, t.clone())).collect(); - k -} - -/// Convert `tiles` of `surface` to `kind` texels and hand each distinct tile, the coordinates -/// sharing it and its bytes to `put`. Each distinct tile is converted once (a solid fill shares -/// one `Arc` across every coordinate it covers), in parallel batches. Converting every tile one -/// after another on the UI thread froze a 50 MP 16-bit document for about 1.4 s after a -/// full-canvas fill (#1774). Returns how many tiles were converted. -fn convert_tiles(surface: &Surface, tiles: Vec<(TileCoord, Arc)>, kind: TexKind, mut put: impl FnMut(&Arc, &[TileCoord], &[u8])) -> usize { - let mut groups: Vec<(Arc, Vec)> = Vec::new(); - let mut index: HashMap<*const Tile, usize> = HashMap::new(); - for (c, t) in tiles { - match index.get(&Arc::as_ptr(&t)).and_then(|&i| groups.get_mut(i)) { - Some(g) => g.1.push(c), - None => { - index.insert(Arc::as_ptr(&t), groups.len()); - groups.push((t, vec![c])); - } - } - } - // CMYK and Lab tiles convert pixel by pixel through a colour transform (a CMYK tile took - // ~5 ms on one thread, the whole of a brush dab's refresh on an A4 CMYK page, #5108): those - // go in bands of rows, so even the one tile a dab touches spreads over the threads. Workers - // don't inherit this thread's CMYK profile scope, so each band enters it. - let bands = if colour_managed(&surface.format(), kind) { TILE_SIZE / MANAGED_BAND_ROWS } else { 1 }; - let space = photocraft_color::convert::active_cmyk_space(); - for batch in groups.chunks(CONVERT_BATCH) { - // A tile's content is the same at every coordinate sharing it: convert it at the first. - let jobs: Vec<_> = batch.iter().filter_map(|(t, cs)| cs.first().map(|c| (t, *c))).flat_map(|(t, c)| (0..bands).map(move |b| (t, c, b))).collect(); - let parts = fx::par_map(jobs, |(t, c, b)| { - photocraft_color::convert::with_cmyk_space(space.as_ref(), || { - if bands == 1 { - return convert_tile(surface, Some(t), kind, c); - } - let r = c.rect(); - let y0 = r.y0 + b * MANAGED_BAND_ROWS; - convert_rows(surface, Some(t), kind, Rect::new(r.x0, y0, r.x1, y0 + MANAGED_BAND_ROWS)) - }) - }); - for ((t, cs), bytes) in batch.iter().zip(parts.chunks(bands as usize)) { - // One part (every format but CMYK and Lab) goes through as is: no copy per tile. - match bytes { - [one] => put(t, cs, one), - _ => put(t, cs, &bytes.concat()), - } - } - } - groups.len() -} - -/// Rows per parallel band of a colour-managed (CMYK, Lab) tile conversion. -const MANAGED_BAND_ROWS: i32 = 16; - -/// Whether `fmt` pixels reach `kind` texels through a per-pixel colour transform (CMYK, Lab). -fn colour_managed(fmt: &PixelFormat, kind: TexKind) -> bool { - use photocraft_color::ColorMode; - matches!(kind, TexKind::Rgba8 | TexKind::Rgba16F) && matches!(fmt.mode, ColorMode::Cmyk | ColorMode::Lab) -} - -/// Tile pixels in the texture's format. `tile = None` gives the default pixel everywhere. -fn convert_tile(surface: &Surface, tile: Option<&Arc>, kind: TexKind, c: TileCoord) -> Vec { - if let (Some(t), TexKind::Rgba8Direct | TexKind::R8Direct) = (tile, kind) { - return t.bytes().to_vec(); - } - let fmt = surface.format(); - if let (Some(t), TexKind::Rgba16F) = (tile, kind) - && let Some(out) = rgb_gray16_to_f16(&fmt, t.bytes()).or_else(|| rgb_gray32_to_f16(&fmt, t.bytes())) - { - return out; - } - convert_rows(surface, tile, kind, c.rect()) -} - -/// [`convert_tile`]'s general path for `rect` (rows of one tile): each pixel through -/// `photocraft_raster::to_rgba`. A run of identical pixels (the transparent or flat areas around a -/// brush dab) is converted once: the same samples give the same texels. -fn convert_rows(surface: &Surface, tile: Option<&Arc>, kind: TexKind, rect: Rect) -> Vec { - let n = rect.width() as usize * rect.height() as usize; - let fmt = surface.format(); - let ch = fmt.channels(); - let raw: Vec = match tile { - Some(_) => surface.read_region(rect), - None => surface.default_pixel().repeat(n), - }; - let mut out = Vec::with_capacity(n * kind.bytes_per_pixel()); - // The previous pixel and its colour. - let mut last: Option<(usize, [f32; 4])> = None; - for (i, px) in raw.chunks_exact(ch).enumerate() { - let mut rgba = || -> [f32; 4] { - if let Some((j, v)) = last - && raw.get(j * ch..j * ch + ch).is_some_and(|p| p.iter().zip(px).all(|(a, b)| a.to_bits() == b.to_bits())) - { - return v; - } - let v = photocraft_raster::to_rgba(&fmt, px); - last = Some((i, v)); - v - }; - match kind { - TexKind::Rgba8Direct | TexKind::Rgba8 => { - let v = rgba(); - out.extend(v.map(|x| (x.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)); - } - TexKind::Rgba16F => { - let v = rgba(); - for x in v { - out.extend(f32_to_f16(x).to_le_bytes()); - } - } - TexKind::R8Direct => out.push((px[0].clamp(0.0, 1.0) * 255.0 + 0.5) as u8), - TexKind::R16F => out.extend(f32_to_f16(px[0]).to_le_bytes()), - TexKind::R32F => out.extend(px[0].to_le_bytes()), - } - } - out -} - -/// RGBA16F texels of a 16-bit RGB or grayscale tile, through a table of every 16-bit sample's -/// half: the same bytes as the general path at a fraction of its cost (a 50 MP 16-bit refresh -/// converts dozens of tiles). `None` for other formats. -fn rgb_gray16_to_f16(fmt: &PixelFormat, bytes: &[u8]) -> Option> { - use photocraft_color::ColorMode; - static HALF: std::sync::OnceLock> = std::sync::OnceLock::new(); - if fmt.sample != SampleType::U16 { - return None; - } - let gray = match fmt.mode { - ColorMode::Rgb => false, - ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => true, - _ => return None, - }; - let half = HALF.get_or_init(|| (0..=u16::MAX).map(|v| f32_to_f16(v as f32 / 65535.0)).collect()); - let one = f32_to_f16(1.0).to_le_bytes(); - let ch = fmt.channels(); - let mut out = Vec::with_capacity((TILE_SIZE * TILE_SIZE) as usize * 8); - for px in bytes.chunks_exact(ch * 2) { - let h = |i: usize| -> [u8; 2] { - let v = px.get(i * 2..i * 2 + 2).map_or(0, |b| u16::from_ne_bytes([b[0], b[1]])); - half.get(v as usize).copied().unwrap_or(0).to_le_bytes() - }; - let (r, g, b) = if gray { (h(0), h(0), h(0)) } else { (h(0), h(1), h(2)) }; - let a = if fmt.alpha { h(ch - 1) } else { one }; - out.extend_from_slice(&r); - out.extend_from_slice(&g); - out.extend_from_slice(&b); - out.extend_from_slice(&a); - } - Some(out) -} - -/// RGBA16F texels of a 32-bit float RGB or grayscale tile, straight from its samples: the same -/// bytes as the general path without decoding the tile into a float buffer and converting it -/// pixel by pixel (a brush dab on a 32-bit layer re-uploads the tiles it touched). `None` for -/// other formats. -fn rgb_gray32_to_f16(fmt: &PixelFormat, bytes: &[u8]) -> Option> { - use photocraft_color::ColorMode; - if fmt.sample != SampleType::F32 { - return None; - } - let gray = match fmt.mode { - ColorMode::Rgb => false, - ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => true, - _ => return None, - }; - let one = f32_to_f16(1.0).to_le_bytes(); - let ch = fmt.channels(); - let mut out = Vec::with_capacity((TILE_SIZE * TILE_SIZE) as usize * 8); - for px in bytes.chunks_exact(ch * 4) { - let h = |i: usize| -> [u8; 2] { - let v = px.get(i * 4..i * 4 + 4).map_or(0.0, |b| f32::from_ne_bytes([b[0], b[1], b[2], b[3]])); - f32_to_f16(v).to_le_bytes() - }; - let (r, g, b) = if gray { - let v = h(0); - (v, v, v) - } else { - (h(0), h(1), h(2)) - }; - let a = if fmt.alpha { h(ch - 1) } else { one }; - out.extend_from_slice(&r); - out.extend_from_slice(&g); - out.extend_from_slice(&b); - out.extend_from_slice(&a); - } - Some(out) -} - -fn lut_texture(device: &wgpu::Device, queue: &wgpu::Queue, rows: &[[f32; 4096]]) -> (wgpu::Texture, wgpu::TextureView) { - let t = device.create_texture(&wgpu::TextureDescriptor { - label: Some("pc_compose_lut"), - size: wgpu::Extent3d { width: 4096, height: rows.len() as u32, depth_or_array_layers: 1 }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::R32Float, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - let bytes: Vec = rows.iter().flat_map(|r| r.iter().flat_map(|v| v.to_le_bytes())).collect(); - queue.write_texture( - wgpu::TexelCopyTextureInfo { texture: &t, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - &bytes, - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(4096 * 4), rows_per_image: Some(rows.len() as u32) }, - wgpu::Extent3d { width: 4096, height: rows.len() as u32, depth_or_array_layers: 1 }, - ); - let v = t.create_view(&Default::default()); - (t, v) -} - -#[derive(Clone, Copy)] -enum W { - I(i32), - U(u32), - F(f32), -} use W::{F, I, U}; -fn words(v: &[W]) -> Vec { - v.iter() - .flat_map(|w| match w { - I(i) => i.to_le_bytes(), - U(u) => u.to_le_bytes(), - F(f) => f.to_le_bytes(), - }) - .collect() -} - -/// IEEE half from f32 (round to nearest even; overflow → inf). -pub fn f32_to_f16(x: f32) -> u16 { - let b = x.to_bits(); - let sign = ((b >> 16) & 0x8000) as u16; - let exp = ((b >> 23) & 0xff) as i32; - let man = b & 0x7f_ffff; - if exp == 0xff { - return sign | 0x7c00 | if man != 0 { 0x200 } else { 0 }; - } - let e = exp - 127 + 15; - if e >= 0x1f { - return sign | 0x7c00; - } - if e <= 0 { - if e < -10 { - return sign; - } - let m = man | 0x80_0000; - let shift = (14 - e) as u32; - let half = 1u32 << (shift - 1); - let rounded = (m + half - 1 + ((m >> shift) & 1)) >> shift; - return sign | rounded as u16; - } - let mut h = ((e as u32) << 10) | (man >> 13); - let rest = man & 0x1fff; - if rest > 0x1000 || (rest == 0x1000 && (h & 1) == 1) { - h += 1; - } - sign | h as u16 -} - -/// f32 from IEEE half. -pub fn f16_to_f32(h: u16) -> f32 { - let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; - let exp = ((h >> 10) & 0x1f) as i32; - let man = (h & 0x3ff) as f32; - match exp { - 0 => sign * man * 2f32.powi(-24), - 0x1f => { - if man == 0.0 { - sign * f32::INFINITY - } else { - f32::NAN - } - } - e => sign * (1.0 + man / 1024.0) * 2f32.powi(e - 15), - } -} - -/// Blocking readback of a composite (native tests and tools). +mod batch; +mod cells; +mod consts; +mod convert; +mod encode; +mod fx_passes; +mod kit; +mod paging; #[cfg(not(target_arch = "wasm32"))] -pub fn render_to_vec(comp: &mut Compositor, device: &wgpu::Device, queue: &wgpu::Queue, doc: &Document, rect: Rect) -> Result, Unsupported> { - render_to_vec_stats(comp, device, queue, doc, rect).map(|(v, _)| v) -} +mod readback; +mod setup; +mod textures; -/// [`render_to_vec`] plus the render's [`Stats`]. +#[cfg(test)] +use batch::{BATCH, batch_kernel, batch_op_words, batch_runs, op_words, run_starts, tile_grid}; +#[cfg(test)] +use consts::OP_UNIFORM; +pub use consts::{ACC_FORMAT, CHUNK, FX_BUDGET, PAGE, PATTERN_BUDGET, PATTERN_IDLE_FRAMES, RESIDENT_BUDGET}; +use convert::W; +#[cfg(test)] +use convert::{CONVERT_BATCH, colour_managed, convert_tile, convert_tiles, rgb_gray16_to_f16, rgb_gray32_to_f16}; +pub use convert::{f16_to_f32, f32_to_f16}; +pub use kit::SHADER; +use kit::{Kit, tex_entry}; +pub use paging::OVER_BUDGET; +use paging::first_error; +#[cfg(test)] +use paging::{lru_victims, uniform_buffer_len}; #[cfg(not(target_arch = "wasm32"))] -pub fn render_to_vec_stats( - comp: &mut Compositor, - device: &wgpu::Device, - queue: &wgpu::Queue, - doc: &Document, - rect: Rect, -) -> Result<(Vec<[f32; 4]>, Stats), Unsupported> { - let rect = rect.intersect(&doc.bounds()); - let mut staging: Vec<(Rect, wgpu::Buffer, u32)> = Vec::new(); - let mut bpp = 16u32; - let stats = comp.render(device, queue, doc, rect, |enc, out| { - // Bytes per pixel of the accumulation format (Rgba32Float = 16, Rgba16Float = 8). - bpp = if out.texture.format() == wgpu::TextureFormat::Rgba32Float { 16 } else { 8 }; - let row = (out.rect.width() * bpp).div_ceil(256) * 256; - let buf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("pc_readback"), - size: (row * out.rect.height()) as u64, - usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, - mapped_at_creation: false, - }); - enc.copy_texture_to_buffer( - wgpu::TexelCopyTextureInfo { texture: out.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, - wgpu::TexelCopyBufferInfo { - buffer: &buf, - layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: Some(out.rect.height()) }, - }, - wgpu::Extent3d { width: out.rect.width(), height: out.rect.height(), depth_or_array_layers: 1 }, - ); - staging.push((out.rect, buf, row)); - })?; - for (_, b, _) in &staging { - b.slice(..).map_async(wgpu::MapMode::Read, |_| {}); - } - match &comp.health { - Some(h) if !h.wait(device, None) => return Err(Unsupported(h.fault().map_or_else(|| "GPU device lost".into(), |f| f.to_string()))), - Some(_) => {} - None => { - let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }); - } - } - let w = rect.width() as usize; - let mut out = vec![[0.0f32; 4]; w * rect.height() as usize]; - for (r, b, row) in &staging { - let data = b.slice(..).get_mapped_range().map_err(|e| Unsupported(format!("GPU readback failed: {e:?}")))?; - for y in 0..r.height() as usize { - for x in 0..r.width() as usize { - let o = y * *row as usize + x * bpp as usize; - let px: [f32; 4] = if bpp == 16 { - std::array::from_fn(|i| f32::from_le_bytes([data[o + i * 4], data[o + i * 4 + 1], data[o + i * 4 + 2], data[o + i * 4 + 3]])) - } else { - std::array::from_fn(|i| half::f16::from_le_bytes([data[o + i * 2], data[o + i * 2 + 1]]).to_f32()) - }; - let (dx, dy) = ((r.x0 - rect.x0) as usize + x, (r.y0 - rect.y0) as usize + y); - out[dy * w + dx] = px; - } - } - } - Ok((out, stats)) -} +pub use readback::{render_to_vec, render_to_vec_stats}; +#[cfg(test)] +use textures::TexKind; +use textures::{CachedPattern, FxEntry, FxKey, ResKey, Resident, Tex}; +pub use textures::{ChunkOut, Stats}; #[cfg(test)] mod tests; diff --git a/crates/gpu/src/paging.rs b/crates/gpu/src/paging.rs new file mode 100644 index 0000000000..c6d4b61563 --- /dev/null +++ b/crates/gpu/src/paging.rs @@ -0,0 +1,126 @@ +use super::consts::STRIDE; +use super::textures::Cell; +use super::*; + +/// Document pixels of page cell `c`. +pub(crate) fn cell_rect(c: Cell, page: u32) -> Rect { + let p = page as i32; + Rect::new(c.0.saturating_mul(p), c.1.saturating_mul(p), c.0.saturating_add(1).saturating_mul(p), c.1.saturating_add(1).saturating_mul(p)) +} + +/// `r` cut along the grid of `step`-sized squares (row-major). +pub(crate) fn grid_rects(r: Rect, step: u32) -> Vec { + let s = step.max(1) as i32; + let mut out = Vec::new(); + let mut y = r.y0.div_euclid(s) * s; + while y < r.y1 { + let mut x = r.x0.div_euclid(s) * s; + while x < r.x1 { + out.push(Rect::new(x, y, x.saturating_add(s), y.saturating_add(s)).intersect(&r)); + x = x.saturating_add(s); + } + y = y.saturating_add(s); + } + out +} + +/// Number of rectangles `grid_rects` would produce, without allocating them during preflight. +pub(crate) fn grid_rect_count(r: Rect, step: u32) -> Result { + if r.is_empty() { + return Ok(0); + } + let s = i64::from(step.max(1)); + let axis = |lo: i32, hi: i32| usize::try_from((i64::from(hi) - 1).div_euclid(s) - i64::from(lo).div_euclid(s) + 1).ok(); + axis(r.x0, r.x1).and_then(|x| axis(r.y0, r.y1).and_then(|y| x.checked_mul(y))).ok_or_else(|| Unsupported("GPU compositor chunk count is too large".into())) +} + +/// Host length and GPU capacity for the chunk/pass uniform records, including their u32 +/// dynamic binding offsets. Decline unsupported stacks before an invalid buffer faults the device. +pub(crate) fn uniform_buffer_len(chunks: usize, passes: usize, limit: u64) -> Result { + let too_large = || Unsupported("GPU compositor uniform buffer is too large".into()); + let records = chunks.checked_add(passes).and_then(|n| u64::try_from(n).ok()).ok_or_else(too_large)?; + let bytes = records.checked_mul(STRIDE).ok_or_else(too_large)?; + if bytes > limit { + return Err(Unsupported(format!("GPU compositor uniform buffer requires {bytes} bytes; device limit is {limit}"))); + } + if bytes.saturating_sub(STRIDE) > u64::from(u32::MAX) { + return Err(Unsupported("GPU compositor uniform offsets exceed u32".into())); + } + usize::try_from(bytes).map_err(|_| too_large()) +} + +/// The reach up to which each distance field must be exact (the largest any program asks for). +pub(crate) fn field_reaches(progs: &[fx::MapProgram]) -> HashMap { + let mut want: HashMap = HashMap::new(); + for (k, r) in progs.iter().flat_map(|p| p.fields.iter()) { + let w = want.entry(*k).or_insert(0); + *w = (*w).max(*r); + } + want +} + +/// Why a refresh whose layer pages don't fit GPU memory is drawn on the CPU. +pub const OVER_BUDGET: &str = "layers exceed the GPU memory budget; full refresh on the CPU"; + +/// Which of `pages` (LRU clock, key, bytes) to drop, least recently used first, so `incoming` +/// more bytes fit `budget` on top of the `total` held now. Callers leave out pages that must stay. +pub(crate) fn lru_victims(mut pages: Vec<(u64, K, u64)>, total: u64, incoming: u64, budget: u64) -> Vec { + pages.sort_unstable_by_key(|p| p.0); + let mut total = total; + let mut out = Vec::new(); + for (_, k, bytes) in pages { + if total.saturating_add(incoming) <= budget { + break; + } + total = total.saturating_sub(bytes); + out.push(k); + } + out +} + +/// Runs `f` inside GPU error scopes and returns the first error raised. +/// Native wgpu reports validation/internal/OOM errors synchronously; where they only arrive +/// asynchronously (WebGPU) none is reported. +pub(crate) fn first_error(device: &wgpu::Device, f: impl FnOnce() -> T) -> (T, Option) { + let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); + let internal = device.push_error_scope(wgpu::ErrorFilter::Internal); + let memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let out = f(); + let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); + let mut error = None; + // Scopes pop in reverse order. + for pop in [memory.pop(), internal.pop(), validation.pop()] { + if let std::task::Poll::Ready(Some(e)) = std::pin::pin!(pop).poll(&mut cx) { + error.get_or_insert(e); + } + } + (out, error) +} + +/// Runs `f` inside the error scopes of [`first_error`], turning a reported error into +/// [`Unsupported`] instead of letting it escape to wgpu's panic handler. +/// +/// Every native caller needs this, watched or not: a validation error (writing into a destroyed +/// or too-small buffer, say) is raised synchronously and never reaches the health callbacks, so a +/// watched compositor still panicked on it. WebGPU reports its errors asynchronously, long after +/// the scope has popped, so wasm relies on the health callbacks alone. +/// +/// A scope also swallows the error that [`DeviceHealth`]'s uncaptured-error handler would have +/// recorded, so a reported error is handed back to `health`: a watched device must stop being +/// used and let the caller fall back to the CPU compositor. +pub(crate) fn scoped_work(device: &wgpu::Device, health: Option, f: impl FnOnce() -> Result) -> Result { + // WebGPU errors arrive asynchronously; its callers still use the health callbacks. + if cfg!(target_arch = "wasm32") { + return f(); + } + let (result, error) = first_error(device, f); + match error { + Some(error) => { + if let Some(health) = health.as_ref() { + health.caught(device, &error); + } + Err(Unsupported(format!("GPU work failed: {error}"))) + } + None => result, + } +} diff --git a/crates/gpu/src/plan/tests.rs b/crates/gpu/src/plan/tests.rs index 9807732927..283fe034de 100644 --- a/crates/gpu/src/plan/tests.rs +++ b/crates/gpu/src/plan/tests.rs @@ -99,9 +99,7 @@ fn outer_glow_plan_knocks_out_see_through_fill() { let glow = planned .passes .iter() - .find(|pass| { - pass.kernel == Kernel::FxPaint && pass.flags & F_KNOCKOUT != 0 && pass.color[0] > 0.9 && pass.color[1] > 0.9 && pass.color[2] < 0.1 - }) + .find(|pass| pass.kernel == Kernel::FxPaint && pass.flags & F_KNOCKOUT != 0 && pass.color[0] > 0.9 && pass.color[1] > 0.9 && pass.color[2] < 0.1) .expect("outer glow paint pass"); assert!((glow.extra[3] - (1.0 - fill)).abs() < 1e-6, "fill {fill}"); } @@ -227,10 +225,7 @@ fn exterior_effects_merge_from_the_shape() { let merge = p.passes.last().unwrap(); assert!(merge.flags & F_LAYER_SHAPE != 0); assert_eq!(merge.params[0][0], 0.7); - d.layers[1] - .effects - .items - .push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::WHITE }); + d.layers[1].effects.items.push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::WHITE }); let p = plan(&d).unwrap(); assert!(p.passes.iter().all(|p| p.flags & F_LAYER_SHAPE == 0)); assert!(p.passes.iter().any(|p| p.kernel == Kernel::FxInit)); diff --git a/crates/gpu/src/readback.rs b/crates/gpu/src/readback.rs new file mode 100644 index 0000000000..14dd73a831 --- /dev/null +++ b/crates/gpu/src/readback.rs @@ -0,0 +1,70 @@ +use super::textures::Stats; +use super::*; + +/// Blocking readback of a composite (native tests and tools). +#[cfg(not(target_arch = "wasm32"))] +pub fn render_to_vec(comp: &mut Compositor, device: &wgpu::Device, queue: &wgpu::Queue, doc: &Document, rect: Rect) -> Result, Unsupported> { + render_to_vec_stats(comp, device, queue, doc, rect).map(|(v, _)| v) +} + +/// [`render_to_vec`] plus the render's [`Stats`]. +#[cfg(not(target_arch = "wasm32"))] +pub fn render_to_vec_stats( + comp: &mut Compositor, + device: &wgpu::Device, + queue: &wgpu::Queue, + doc: &Document, + rect: Rect, +) -> Result<(Vec<[f32; 4]>, Stats), Unsupported> { + let rect = rect.intersect(&doc.bounds()); + let mut staging: Vec<(Rect, wgpu::Buffer, u32)> = Vec::new(); + let mut bpp = 16u32; + let stats = comp.render(device, queue, doc, rect, |enc, out| { + // Bytes per pixel of the accumulation format (Rgba32Float = 16, Rgba16Float = 8). + bpp = if out.texture.format() == wgpu::TextureFormat::Rgba32Float { 16 } else { 8 }; + let row = (out.rect.width() * bpp).div_ceil(256) * 256; + let buf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("pc_readback"), + size: (row * out.rect.height()) as u64, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + enc.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { texture: out.texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyBufferInfo { + buffer: &buf, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: Some(out.rect.height()) }, + }, + wgpu::Extent3d { width: out.rect.width(), height: out.rect.height(), depth_or_array_layers: 1 }, + ); + staging.push((out.rect, buf, row)); + })?; + for (_, b, _) in &staging { + b.slice(..).map_async(wgpu::MapMode::Read, |_| {}); + } + match &comp.health { + Some(h) if !h.wait(device, None) => return Err(Unsupported(h.fault().map_or_else(|| "GPU device lost".into(), |f| f.to_string()))), + Some(_) => {} + None => { + let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }); + } + } + let w = rect.width() as usize; + let mut out = vec![[0.0f32; 4]; w * rect.height() as usize]; + for (r, b, row) in &staging { + let data = b.slice(..).get_mapped_range().map_err(|e| Unsupported(format!("GPU readback failed: {e:?}")))?; + for y in 0..r.height() as usize { + for x in 0..r.width() as usize { + let o = y * *row as usize + x * bpp as usize; + let px: [f32; 4] = if bpp == 16 { + std::array::from_fn(|i| f32::from_le_bytes([data[o + i * 4], data[o + i * 4 + 1], data[o + i * 4 + 2], data[o + i * 4 + 3]])) + } else { + std::array::from_fn(|i| half::f16::from_le_bytes([data[o + i * 2], data[o + i * 2 + 1]]).to_f32()) + }; + let (dx, dy) = ((r.x0 - rect.x0) as usize + x, (r.y0 - rect.y0) as usize + y); + out[dy * w + dx] = px; + } + } + } + Ok((out, stats)) +} diff --git a/crates/gpu/src/setup.rs b/crates/gpu/src/setup.rs new file mode 100644 index 0000000000..30d04d872e --- /dev/null +++ b/crates/gpu/src/setup.rs @@ -0,0 +1,480 @@ +use super::batch::tile_grid; +use super::consts::{ACC_FORMAT, CHUNK, CHUNK_UNIFORM, FX_BUDGET, MAP16, MAP32, OP_UNIFORM, PAGE, PATTERN_BUDGET, RESIDENT_BUDGET}; +use super::kit::{Kit, SHADER, tex_entry, uniform_entry}; +use super::paging::{cell_rect, field_reaches, first_error, grid_rects}; +use super::textures::{FxEntry, Resident, Tex, TexKind}; +use super::*; + +impl Compositor { + /// Create a compositor with the default accumulation format ([`ACC_FORMAT`]). + pub fn new(device: &wgpu::Device) -> Self { + Self::new_with_format(device, ACC_FORMAT) + } + + /// The accumulation format to use on `adapter`: `Rgba32Float` when it can be a render target, + /// else `Rgba16Float`. Some drivers (e.g. Intel Vulkan) don't support rendering to `Rgba32Float` + /// and would otherwise panic at render-pipeline creation. + pub fn preferred_acc_format(adapter: &wgpu::Adapter) -> wgpu::TextureFormat { + let feats = adapter.get_texture_format_features(wgpu::TextureFormat::Rgba32Float); + if feats.allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) { wgpu::TextureFormat::Rgba32Float } else { wgpu::TextureFormat::Rgba16Float } + } + + /// [`Compositor::new_with_format`], but a shader or pipeline the driver can't build (e.g. a + /// D3D12 shader-compiler failure) is an `Err` instead of a panic, so the caller can fall back + /// to the CPU compositor. Where errors only arrive asynchronously (WebGPU), creation is assumed + /// to have worked. + pub fn try_new_with_format(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Result { + match first_error(device, || Self::build(device, acc_format)) { + ((comp, None), None) => Ok(comp), + ((_, Some(e)), _) | (_, Some(e)) => Err(Unsupported(format!("couldn't build the compositor's pipelines: {e}"))), + } + } + + /// Create a compositor whose accumulation/render-target format is `acc_format`. Pass + /// `Rgba16Float` on adapters that can't render to `Rgba32Float` (e.g. some Intel Vulkan drivers), + /// which otherwise panics at render-pipeline creation. See `Compositor::preferred_acc_format`. + pub fn new_with_format(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> Self { + let (comp, error) = Self::build(device, acc_format); + if let Some(e) = error { + log::error!("GPU compositor: couldn't build its pipelines: {e}"); + } + comp + } + + /// The compositor and the first error raised building its (non-map) pipelines. They are + /// built in parallel, each inside its own error scope on the thread that builds it (wgpu's + /// scopes are per thread): on DX12, FXC compiles one shader at a time and the ~30 pipelines + /// took about 8 s on one core (#6419). + fn build(device: &wgpu::Device, acc_format: wgpu::TextureFormat) -> (Self, Option) { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("pc_compose"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) }); + let bgl0 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("pc_compose_uniforms"), + entries: &[uniform_entry(0, CHUNK_UNIFORM), uniform_entry(1, OP_UNIFORM)], + }); + let bgl1 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("pc_compose_textures"), + entries: &(0..8).map(tex_entry).collect::>(), + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("pc_compose"), + bind_group_layouts: &[Some(&bgl0), Some(&bgl1)], + immediate_size: 0, + }); + // `None` only for kernels without a fragment entry point, which are never drawn. + let pipeline = |k: Kernel, format: wgpu::TextureFormat| { + let entry = k.entry()?; + Some(device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(entry), + layout: Some(&layout), + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), buffers: &[], compilation_options: Default::default() }, + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(entry), + targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })], + compilation_options: Default::default(), + }), + multiview_mask: None, + cache: None, + })) + }; + // Effect maps render to R32Float / R16Float, which some adapters (e.g. GL without float + // render targets) can't: then layer effects use the CPU compositor and the rest stays here. + let keys = Kernel::DRAWN.iter().filter(|k| !k.is_map()).map(|&k| (k, acc_format)); + let keys: Vec<_> = keys.chain(Kernel::DRAWN.iter().filter(|k| k.is_map()).flat_map(|&k| [(k, MAP32), (k, MAP16)])).collect(); + let built = fx::par_map(keys, |key| { + let (built, error) = first_error(device, || pipeline(key.0, key.1)); + (key, built, error) + }); + let (mut pipelines, mut maps) = (HashMap::new(), Vec::new()); + let (mut error, mut map_error) = (None, None); + for (key, built, e) in built { + let map = key.0.is_map(); + // A failed map pipeline turns all effect maps off below. A failed non-map pipeline + // keeps its (invalid) handle: draws look pipelines up by key, so dropping it would + // turn a validation error into a missing-key panic on the first draw. + if let Some(e) = e { + if map { + map_error.get_or_insert(e); + continue; + } + error.get_or_insert(e); + } + let Some(p) = built else { continue }; + if map { + maps.push((key, p)); + } else { + pipelines.insert(key, p); + } + } + if let Some(e) = &map_error { + log::info!("GPU compositor: no effect-map pipelines ({e}); layer effects use the CPU"); + } else { + pipelines.extend(maps); + } + let dummy = Tex::new(device, "pc_compose_dummy", 1, 1, wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureUsages::TEXTURE_BINDING).view; + let comp = Self { + kit: Kit { pipelines, bgl0, bgl1, dummy }, + pool: Vec::new(), + residents: HashMap::new(), + fx: HashMap::new(), + prefix: prefix::Prefix::default(), + temps: Vec::new(), + patterns: HashMap::new(), + pattern_mode: photocraft_color::ColorMode::Rgb, + pattern_doc: DocId(0), + pattern_budget: PATTERN_BUDGET, + max_dim: 0, + device_max: device.limits().max_texture_dimension_2d, + page: PAGE, + chunk: CHUNK, + resident_budget: RESIDENT_BUDGET, + fx_budget: (FX_BUDGET as u64).saturating_sub(prefix::MAX_BYTES), + layer_need: 0, + lent: 0, + exact_resident: false, + focus: None, + frame: 0, + stamp: 0, + staged: 0, + recorded: 0, + layer_alloc: None, + admit_freed: 0, + fail_allocs: 0, + acc_format, + effect_maps: map_error.is_none(), + cmyk: 0, + health: None, + timer: None, + } + .with_texture_limit(device.limits().max_texture_dimension_2d); + (comp, error) + } + + fn with_texture_limit(mut self, max: u32) -> Self { + self.set_texture_limit(max); + self + } + + /// Plan paging for a texture side limit of `max` (clamped to the device's own limit and at + /// least one tile). Tests use a small limit to exercise documents larger than it on any + /// adapter. Drops every cached texture. + pub fn set_texture_limit(&mut self, max: u32) { + let tile = TILE_SIZE as u32; + self.max_dim = max.min(self.device_max).max(tile); + let mut page = tile; + while page * 2 <= self.max_dim.min(PAGE) { + page *= 2; + } + self.page = page; + self.chunk = CHUNK.min(page); + self.prefix.set_step(self.chunk); + self.pool.clear(); + self.residents.clear(); + self.fx.clear(); + self.temps.clear(); + self.prefix.clear(); + } + + /// The page side layer surfaces are stored in. + pub fn page_size(&self) -> u32 { + self.page + } + + /// Test hook: the next `n` layer page textures fail as if the device were out of memory + /// (a real one can't be forced), so the fallback paths of #6563 can be tested. + #[doc(hidden)] + pub fn fail_layer_allocs(&mut self, n: u32) { + self.fail_allocs = n; + } + + /// Set the GPU memory resident layer pages may hold (default [`RESIDENT_BUDGET`]), exactly: + /// nothing is lent to it ([`Self::fit_layers`]) until the next [`Self::set_memory_budget`]. + pub fn set_resident_budget(&mut self, bytes: u64) { + // The loan goes back to the effect maps, so the total budget stays what it was. + self.fx_budget = self.fx_budget.saturating_add(self.lent); + self.lent = 0; + self.resident_budget = bytes; + self.exact_resident = true; + } + + /// Set the GPU memory the compositor may hold for layer pages and caches together + /// (a quarter of it, at most [`FX_BUDGET`], for effect maps and lower-stack chunks). Uploads and evicted pages in + /// flight during a refresh stay within about a quarter more. + pub fn set_memory_budget(&mut self, bytes: u64) { + let caches = (FX_BUDGET as u64).min(bytes / 4); + self.prefix.set_budget((caches / 2).min(prefix::MAX_BYTES)); + self.fx_budget = caches.saturating_sub(self.prefix.budget()); + self.resident_budget = bytes.saturating_sub(caches); + self.lent = 0; + self.exact_resident = false; + self.lend(); + } + + /// Record that a render needs `needed` bytes of layer pages and return the resident budget + /// they now have. A render of the `whole` document sets the need; a part of it only raises + /// it, so a large partial refresh never shrinks what the next full one keeps resident. + /// + /// Pages that miss their share by less than the effect-map share borrow from it: an evicted + /// effect map is rebuilt by the next refresh that draws it, but one page too many sends the + /// whole refresh to the CPU compositor, 10× slower (#5973, P60: 150 layers of 6 MP on an + /// integrated GPU missed by 5 % and took 680 ms instead of 62). + /// The lower-stack share is never lent: it is what keeps a mid-stack edit at half the work. + /// The loan holds across [`Self::set_memory_budget`] until a later call needs less or more. + pub fn fit_layers(&mut self, needed: u64, whole: bool) -> u64 { + self.layer_need = if whole { needed } else { self.layer_need.max(needed) }; + self.lend(); + self.resident_budget + } + + /// Return the loan to the effect maps, then lend what [`Self::layer_need`] still lacks, if + /// the effect-map share covers it (lending part of it would fit nothing and only evict maps). + fn lend(&mut self) { + self.fx_budget = self.fx_budget.saturating_add(self.lent); + self.resident_budget = self.resident_budget.saturating_sub(self.lent); + let short = self.layer_need.saturating_sub(self.resident_budget); + self.lent = if short <= self.fx_budget && !self.exact_resident { short } else { 0 }; + self.fx_budget = self.fx_budget.saturating_sub(self.lent); + self.resident_budget = self.resident_budget.saturating_add(self.lent); + } + + /// The budget of layer pages, effect maps and lower-stack chunks (bytes). + pub fn memory_budget(&self) -> u64 { + self.resident_budget.saturating_add(self.fx_budget).saturating_add(self.prefix.budget()) + } + + /// Bytes held by reusable lower-stack chunks, within the overall cache allowance. + pub fn composite_cache_bytes(&self) -> u64 { + self.prefix.bytes() + } + + /// Cap lower-stack reuse (default at most 512 MiB); zero disables it. The released allowance + /// goes back to effect maps, preserving the total budget and layer-page allowance. + pub fn set_composite_cache_budget(&mut self, bytes: u64) { + let caches = self.fx_budget.saturating_add(self.prefix.budget()); + self.prefix.set_budget(bytes.min(caches)); + self.fx_budget = caches.saturating_sub(self.prefix.budget()); + } + + /// Bytes of the layer pages a render of `region` needs resident (each layer and mask + /// surface's tiles within the region's page cells, in their texture format). + pub fn working_set(&self, doc: &Document, region: Rect) -> u64 { + let Ok(plan) = plan(doc) else { return 0 }; + let grid = tile_grid(doc.bounds()); + let cells = grid_rects(region.intersect(&doc.bounds()), self.page) + .into_iter() + .map(|r| cell_rect((r.x0.div_euclid(self.page as i32), r.y0.div_euclid(self.page as i32)), self.page)) + .fold(Rect::EMPTY, |a, c| if a.is_empty() { c } else { a.union(&c) }); + let mut seen = std::collections::HashSet::new(); + let mut total = 0u64; + for p in &plan.passes { + let sources = [p.tex.as_ref().map(|t| (t.layer, t.role, t.surface.get())), p.mask.as_ref().map(|m| (m.layer, Role::Mask, m.surface.get()))]; + for (layer, role, s) in sources.into_iter().flatten() { + if seen.insert((layer, role)) { + let a = s.tile_bounds().intersect(&grid).intersect(&cells); + total += a.width() as u64 * a.height() as u64 * TexKind::for_surface(role, s.format()).bytes_per_pixel() as u64; + } + } + } + total + } + + /// The GPU memory resident layer pages may hold (bytes; see [`Compositor::set_memory_budget`]). + pub fn resident_budget(&self) -> u64 { + self.resident_budget + } + + /// Whether a render of `region` keeps every layer page it needs within the budget; when it + /// doesn't, each render re-uploads what was evicted. + pub fn fits_budget(&self, doc: &Document, region: Rect) -> bool { + self.working_set(doc, region) <= self.resident_budget + } + + /// The document area the view shows (`None`: unknown). Full refreshes draw its cells last. + pub fn set_focus(&mut self, focus: Option) { + self.focus = focus; + } + + /// GPU memory held by resident layer pages (bytes). + pub fn resident_bytes(&self) -> u64 { + self.residents.values().map(Resident::bytes).sum() + } + + /// GPU memory held by cached pattern textures (bytes). + pub fn pattern_cache_bytes(&self) -> u64 { + self.patterns.values().map(|p| p.bytes).sum() + } + + /// Set the GPU memory pattern textures may hold (default [`PATTERN_BUDGET`]). It takes effect + /// at the end of the next refresh. + pub fn set_pattern_budget(&mut self, bytes: u64) { + self.pattern_budget = bytes; + } + + /// Whether `doc` can be composited on the GPU. Documents and layers larger than the texture + /// limit are fine: surfaces are stored in page-sized textures and effect maps of regions + /// larger than the limit are built per page cell. + pub fn supports(&self, doc: &Document) -> Result<(), Unsupported> { + let p = plan(doc)?; + self.check_fx(doc, &p) + } + + /// Whether the maps of an effect region are built per page cell (it exceeds the limit). + pub(crate) fn fx_paged(&self, region: Rect) -> bool { + region.width() > self.max_dim || region.height() > self.max_dim + } + + /// How far beyond a page cell the effect maps of `f` must be computed to be exact in it. + pub(crate) fn fx_apron(doc: &Document, f: &plan::FxLayer<'_>) -> i32 { + let vector_shape = matches!(f.layer.content, LayerContent::Shape(_)) && photocraft_compose::effect_outline(f.layer).is_none(); + let progs: Vec = f + .layer + .effects + .items + .iter() + .filter(|e| e.enabled()) + .map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, (0.0, 0.0))) + .collect(); + let want = field_reaches(&progs); + // Distance fields are exact one pixel inside the window they are computed from. + progs.iter().map(|p| p.reach(&|k| want.get(&k).copied().unwrap_or(0))).max().unwrap_or(0).saturating_add(2) + } + + /// Effect maps must fit in textures (per page cell when the region exceeds the limit), and + /// patterns in one texture. + pub(crate) fn check_fx(&self, doc: &Document, p: &Plan<'_>) -> Result<(), Unsupported> { + if !self.effect_maps && !p.fx.is_empty() { + return Err(Unsupported("layer effects need float effect-map render targets, which this GPU lacks".into())); + } + for f in &p.fx { + if self.fx_paged(f.region) { + let side = i64::from(self.page) + 2 * i64::from(Self::fx_apron(doc, f)); + if side > i64::from(self.device_max) { + return Err(Unsupported(format!("effects of `{}` reach too far to build per page", f.layer.name))); + } + } + for e in f.layer.effects.items.iter().filter(|e| e.enabled()) { + // Effect noise is speckled in the CPU maps; keep CPU and GPU identical by + // rendering noise-carrying effects on the CPU path. + let noisy = match e { + photocraft_doc::Effect::DropShadow(s) | photocraft_doc::Effect::InnerShadow(s) => s.noise > 0.0, + photocraft_doc::Effect::OuterGlow(g) | photocraft_doc::Effect::InnerGlow(g) => g.noise > 0.0, + _ => false, + }; + if noisy { + return Err(Unsupported(format!("effect noise on `{}` uses the CPU path", f.layer.name))); + } + for s in fx::program_with(e, &doc.global_light, false, &doc.patterns, (0.0, 0.0)).stages { + if s.lut.as_ref().is_some_and(|l| l.len() > 4096) { + return Err(Unsupported(format!("effect blur on `{}` too wide for the GPU path", f.layer.name))); + } + } + } + } + for pass in &p.passes { + if let Some(pat) = pass.pattern + && (pat.width > self.device_max || pat.height > self.device_max) + { + return Err(Unsupported(format!("pattern `{}` larger than the GPU texture limit", pat.name))); + } + } + Ok(()) + } + + /// Drop GPU textures of a closed document. + pub fn forget_doc(&mut self, doc: DocId) { + self.residents.retain(|_, r| r.doc != doc); + self.fx.retain(|_, e| e.doc != doc); + self.patterns.retain(|_, p| p.doc != doc); + self.prefix.forget(doc); + } + + /// [`Self::forget_doc`] for every document `keep` rejects: what the compositor holds for + /// documents that were closed, however their canvas entry went (#4529). + pub fn retain_docs(&mut self, keep: impl Fn(DocId) -> bool) { + let mut gone: Vec = self + .residents + .values() + .map(|r| r.doc) + .chain(self.fx.values().map(|e| e.doc)) + .chain(self.patterns.values().map(|p| p.doc)) + .chain(self.prefix.doc()) + .filter(|d| !keep(*d)) + .collect(); + gone.sort_by_key(|d| d.0); + gone.dedup(); + for d in gone { + self.forget_doc(d); + } + } + + /// Documents the compositor holds pages, effect maps, pattern textures or a lower-stack + /// composite for. + pub fn held_docs(&self) -> Vec { + let mut docs: Vec = self + .residents + .values() + .map(|r| r.doc) + .chain(self.fx.values().map(|e| e.doc)) + .chain(self.patterns.values().map(|p| p.doc)) + .chain(self.prefix.doc()) + .collect(); + docs.sort_by_key(|d| d.0); + docs.dedup(); + docs + } + + /// GPU memory held by cached effect maps (bytes). + pub fn fx_cache_bytes(&self) -> usize { + self.fx.values().map(FxEntry::bytes).sum() + } + + /// Watch `health` (see [`DeviceHealth::watch`]): once the device is lost or reported an + /// error, every render returns [`Unsupported`] without touching the GPU, so callers use the + /// CPU compositor instead. + pub fn set_health(&mut self, health: DeviceHealth) { + self.health = Some(health); + } + + /// Why the device can't be used (`None` while healthy or unwatched). + pub fn fault(&self) -> Option { + self.health.as_ref().and_then(DeviceHealth::fault) + } + + /// Measure how long the GPU spends executing each [`Compositor::render`], with timestamp + /// queries read back asynchronously (nothing waits for the GPU). Returns whether the device + /// supports it: without [`timing::FEATURES`] there is no measurement at all, and callers + /// report no GPU time rather than the encode-and-submit cost `composite_ms` already is. + /// + /// A measurement arrives a frame or two after the refresh it belongs to, so it carries that + /// refresh's own pixel count; take it with [`Compositor::take_gpu_timing`]. + pub fn measure_gpu_time(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> bool { + // `PHOTOCRAFT_NO_GPU_TIMING` turns it off: a kill switch for a driver whose timestamp + // queries misbehave, and the control arm for measuring what the queries themselves + // cost — the device is identical either way, so only the instrumentation varies. + if std::env::var_os("PHOTOCRAFT_NO_GPU_TIMING").is_some() { + return false; + } + if self.timer.is_none() { + self.timer = timing::GpuTimer::new(device, queue); + } + self.timer.is_some() + } + + /// Whether [`Compositor::measure_gpu_time`] is on for this compositor. + pub fn measures_gpu_time(&self) -> bool { + self.timer.is_some() + } + + /// The most recent finished GPU measurement, leaving none behind (a stale number is never + /// reported twice as new). `None` while unmeasured, unsupported, or still in flight. + /// + /// [`Compositor::render`] already drains this into [`Stats::gpu_time`], so the app never + /// calls it; it is how a bench or a test collects a measurement without issuing another + /// render to carry it. + pub fn take_gpu_timing(&mut self) -> Option { + self.timer.as_mut().and_then(timing::GpuTimer::take) + } +} diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index f2a6847dd0..281c67421e 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -91,8 +91,7 @@ fn runs_of_normal_layers_draw_with_normal_code_alone() { let normal = pass(BlendMode::Normal, plan::F_HDR); assert_eq!(batch_kernel(&[normal.clone(), pass(BlendMode::Normal, 0)]), Kernel::LayerBatchNormal); // Any other mode, text gamma or a Lab document anywhere in the run takes the full shader. - for other in - [pass(BlendMode::Multiply, 0), pass(BlendMode::Dissolve, 0), pass(BlendMode::Normal, plan::F_TEXT_GAMMA), pass(BlendMode::Normal, plan::F_LAB)] + for other in [pass(BlendMode::Multiply, 0), pass(BlendMode::Dissolve, 0), pass(BlendMode::Normal, plan::F_TEXT_GAMMA), pass(BlendMode::Normal, plan::F_LAB)] { assert_eq!(batch_kernel(&[normal.clone(), other.clone()]), Kernel::LayerBatch); assert_eq!(batch_kernel(&[other, normal.clone()]), Kernel::LayerBatch); @@ -375,11 +374,7 @@ fn colour_managed_tiles_match_the_per_pixel_conversion() { } }) .collect(); - assert!( - bytes == want.as_slice(), - "{fmt:?} {c:?} with {}", - if space.is_some() { "the document's profile" } else { "the built-in profile" } - ); + assert!(bytes == want.as_slice(), "{fmt:?} {c:?} with {}", if space.is_some() { "the document's profile" } else { "the built-in profile" }); assert_eq!(convert_tile(&s, s.tile(c), kind, c), want, "{fmt:?} {c:?}"); seen += 1; } diff --git a/crates/gpu/src/textures.rs b/crates/gpu/src/textures.rs new file mode 100644 index 0000000000..1b28f61150 --- /dev/null +++ b/crates/gpu/src/textures.rs @@ -0,0 +1,247 @@ +use super::*; + +/// A finished chunk: straight-alpha RGBA32F pixels of `rect` (document coordinates) at the +/// texture's origin. +pub struct ChunkOut<'a> { + pub rect: Rect, + pub texture: &'a wgpu::Texture, + pub view: &'a wgpu::TextureView, +} + +/// What a render did (for profiling and tests). +#[derive(Clone, Copy, Debug, Default)] +pub struct Stats { + /// How long the GPU spent executing a composite, once its timestamps came back. Because the + /// readback is asynchronous this belongs to an *earlier* render than the one returning it + /// (it carries that render's own pixel count, so the two are never confused), and it is + /// `None` unless [`Compositor::measure_gpu_time`] is on and a measurement has landed. + /// Always `None` from [`Compositor::encode`], which submits nothing of its own. + pub gpu_time: Option, + pub passes: usize, + pub chunks: usize, + pub slots: u32, + pub tiles_uploaded: usize, + pub bytes_uploaded: usize, + /// Tiles a new layer texture took from another layer's texture by a GPU copy (a duplicate + /// shares its source's tiles) instead of uploading them. + pub tiles_shared: usize, + /// Effect layers whose shape was (re)rendered, fully or partially. + pub fx_shapes: usize, + /// Effect map programs run (one per effect whose maps were rebuilt). + pub fx_programs: usize, + /// Effect-map pixels written (all stages). + pub fx_pixels: u64, + /// Page cells the region spans (each binds only the layer pages it overlaps). + pub cells: usize, + /// Layer pages and paged effect maps evicted to stay within the memory budgets. + pub evicted: usize, + /// Intermediate submits of a huge refresh (to bound staging and evicted memory). + pub flushes: usize, + /// Chunks restored from an unchanged lower-stack composite. + pub prefix_hits: usize, + /// Planned prefix passes skipped, summed over the reused chunks. + pub prefix_passes_skipped: usize, + /// Plain layers blended inside another layer's pass (`fs_layerbatch`), summed over chunks. + pub layers_batched: usize, + /// Batched passes drawn with Normal's code alone (`fs_layerbatch_normal`), summed over chunks. + pub normal_batches: usize, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum TexKind { + /// RGBA8 tiles copied verbatim. + Rgba8Direct, + /// Other 8-bit formats converted to RGBA8. + Rgba8, + /// 16/32-bit formats converted to RGBA16F. + Rgba16F, + /// GRAY8 masks copied verbatim. + R8Direct, + /// 16-bit masks as R16F (the precision 16-bit pixels get as RGBA16F). + R16F, + /// 32-bit masks as R32F. + R32F, +} + +impl TexKind { + pub(crate) fn for_surface(role: Role, f: PixelFormat) -> Self { + match role { + Role::Content | Role::Stroke if f == PixelFormat::RGBA8 => TexKind::Rgba8Direct, + Role::Content | Role::Stroke if f.sample == SampleType::U8 => TexKind::Rgba8, + Role::Content | Role::Stroke => TexKind::Rgba16F, + Role::Mask if f == PixelFormat::GRAY8 => TexKind::R8Direct, + Role::Mask if f.sample == SampleType::F32 => TexKind::R32F, + Role::Mask => TexKind::R16F, + } + } + pub(crate) fn format(self) -> wgpu::TextureFormat { + match self { + TexKind::Rgba8Direct | TexKind::Rgba8 => wgpu::TextureFormat::Rgba8Unorm, + TexKind::Rgba16F => wgpu::TextureFormat::Rgba16Float, + TexKind::R8Direct => wgpu::TextureFormat::R8Unorm, + TexKind::R16F => wgpu::TextureFormat::R16Float, + TexKind::R32F => wgpu::TextureFormat::R32Float, + } + } + pub(crate) fn bytes_per_pixel(self) -> usize { + match self { + TexKind::Rgba8Direct | TexKind::Rgba8 => 4, + TexKind::Rgba16F => 8, + TexKind::R8Direct => 1, + TexKind::R16F => 2, + TexKind::R32F => 4, + } + } +} + +/// Index into the render's resident key list, and the texture's region (x, y, w, h). +pub(crate) type ResidentRef = (usize, [i32; 4]); + +/// A page cell: the square `[x·page, (x+1)·page) × [y·page, (y+1)·page)` of document pixels. +pub(crate) type Cell = (i32, i32); + +/// A resident layer page. +pub(crate) type ResKey = (LayerId, Role, Cell); + +/// Effect maps of a layer: over its whole effect region (`None`), or one page cell of a region +/// larger than the texture limit. +pub(crate) type FxKey = (LayerId, Option); + +pub(crate) struct CachedPattern { + pub(crate) fingerprint: u64, + pub(crate) format: PixelFormat, + pub(crate) default_bits: Vec, + pub(crate) texture: Tex, + /// The document that last painted with it: closing that document frees the texture (#4971). + pub(crate) doc: DocId, + /// [`Compositor::frame`] when it last painted. + pub(crate) last_used: u64, + /// GPU bytes of the texture (RGBA32F). + pub(crate) bytes: u64, +} + +pub(crate) struct Resident { + pub(crate) texture: wgpu::Texture, + pub(crate) view: wgpu::TextureView, + /// Document-pixel rect covered (tile aligned, inside one page cell). + pub(crate) region: Rect, + pub(crate) kind: TexKind, + pub(crate) format: PixelFormat, + pub(crate) tiles: HashMap>, + pub(crate) default_nonzero: bool, + /// Bit pattern of the surface's default pixel when the texture was filled. Tiles the surface + /// doesn't store hold it, so a changed default (Invert, Fill) makes the texture stale. + pub(crate) default_bits: Vec, + pub(crate) doc: DocId, + pub(crate) last_used: u64, + /// Cell visit that last used it (least recently used pages are evicted first). + pub(crate) stamp: u64, + /// CMYK profile the texels were converted with (`CmykSpace::id`, 0 = built-in / not CMYK). + pub(crate) cmyk: u64, + /// Its texels were copied to or from another layer texture by the encoder, so every write + /// to it goes through the encoder too: a queued write lands before the encoder runs, and + /// would be overwritten by the copy, or leak into it. + pub(crate) ordered: bool, +} + +impl Resident { + pub(crate) fn bytes(&self) -> u64 { + self.region.width() as u64 * self.region.height() as u64 * self.kind.bytes_per_pixel() as u64 + } +} + +/// A texture and its default view. +#[derive(Clone)] +pub(crate) struct Tex { + pub(crate) texture: wgpu::Texture, + pub(crate) view: wgpu::TextureView, +} + +impl Tex { + pub(crate) fn new(device: &wgpu::Device, label: &str, w: u32, h: u32, format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> Self { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { width: w.max(1), height: h.max(1), depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + Tex { texture, view } + } + pub(crate) fn map(device: &wgpu::Device, label: &str, r: Rect, format: wgpu::TextureFormat) -> Self { + Tex::new( + device, + label, + r.width(), + r.height(), + format, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + ) + } + /// Upload R32F values (row-major over `r`) into this region-space texture at `r`. + pub(crate) fn write_r32(&self, queue: &wgpu::Queue, region: Rect, r: Rect, v: &[f32]) { + if r.is_empty() { + return; + } + let bytes: Vec = v.iter().flat_map(|x| x.to_le_bytes()).collect(); + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &self.texture, + mip_level: 0, + origin: wgpu::Origin3d { x: (r.x0 - region.x0) as u32, y: (r.y0 - region.y0) as u32, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + &bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(r.width() * 4), rows_per_image: Some(r.height()) }, + wgpu::Extent3d { width: r.width(), height: r.height(), depth_or_array_layers: 1 }, + ); + } + fn bytes(&self) -> usize { + let s = self.texture.size(); + let bpp = match self.texture.format() { + wgpu::TextureFormat::R16Float => 2, + wgpu::TextureFormat::Rgba32Float => 16, + wgpu::TextureFormat::Rgba16Float => 8, + _ => 4, + }; + s.width as usize * s.height as usize * bpp + } +} + +/// Cached maps of one effect (one enabled item of a layer). +pub(crate) struct ProgState { + pub(crate) key: u64, + pub(crate) maps: Vec>, +} + +/// Cached effect state of one layer. +pub(crate) struct FxEntry { + pub(crate) doc: DocId, + pub(crate) region: Rect, + pub(crate) shape_key: u64, + /// Tiles the shape was rendered from (content, mask): damage is their difference. + pub(crate) tiles: [Option; 2], + /// Groups: the tiles `shape_key` hashes, by address only (see [`fx::Tiles`]). + pub(crate) _pin: Vec>, + /// The shape on the CPU (distance fields are computed from it) and on the GPU. + pub(crate) shape_cpu: Vec, + pub(crate) shape: Tex, + /// Distance fields: the reach each is exact to, and its texture. + pub(crate) fields: HashMap, + pub(crate) progs: Vec, + pub(crate) last_used: u64, + pub(crate) stamp: u64, +} + +impl FxEntry { + pub(crate) fn bytes(&self) -> usize { + self.shape.bytes() + + self.shape_cpu.len() * 4 + + self.fields.values().map(|(_, t)| t.bytes()).sum::() + + self.progs.iter().flat_map(|p| p.maps.iter().flatten()).map(Tex::bytes).sum::() + } +} From 7ba8fdc79fb13fb8e73c4ed165c5729d15cdf608 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:04:45 +0000 Subject: [PATCH 249/259] refactor(gpu): split plan.rs into plan/ --- crates/gpu/src/plan.rs | 1848 +------------------------------- crates/gpu/src/plan/lower.rs | 344 ++++++ crates/gpu/src/plan/planner.rs | 1215 +++++++++++++++++++++ crates/gpu/src/plan/types.rs | 304 ++++++ 4 files changed, 1879 insertions(+), 1832 deletions(-) create mode 100644 crates/gpu/src/plan/lower.rs create mode 100644 crates/gpu/src/plan/planner.rs create mode 100644 crates/gpu/src/plan/types.rs diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs index a9a266e97a..166e977800 100644 --- a/crates/gpu/src/plan.rs +++ b/crates/gpu/src/plan.rs @@ -23,272 +23,25 @@ use photocraft_raster::Surface; use crate::bounds; +mod lower; +mod planner; +mod types; + +#[cfg(test)] +use lower::check_gradient_stops; +pub use lower::{adjustment_on_gpu, adjustment_program, mode_index, stroke_widths}; +use planner::Planner; +#[cfg(test)] +use planner::blend_if_params; +pub use planner::{ + F_ADD_DIFF, F_ATOP, F_BLEND_IF, F_CHANNELS, F_FIRST, F_GATE, F_HDR, F_KNOCKOUT, F_LAB, F_LAYER_SHAPE, F_NO_LAYER, F_OUTLINE, F_QUANT, F_REL, F_STROKE_OUT, + F_TEXT_GAMMA, F_VECTOR, INIT_ALPHA, INIT_COVER, INIT_INSIDE, INIT_OPAQUE, INIT_OUTLINE, INIT_RELATIVE, INIT_SCALE, INIT_VSTROKE, SHAPE_MAP, +}; +pub use types::{Checkpoint, DocCtx, FxLayer, Kernel, MapRef, MaskUse, Pass, Role, SurfaceRef, TexUse, Unsupported}; + /// Index of a chunk-sized accumulator texture. pub type Slot = u32; -/// Pipeline (fragment entry point) of a pass. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Kernel { - /// Transparent fill (no draw). - Clear, - Content, - Mask, - Blend, - /// `Content` then `Blend` in one pass: a plain layer's pixels blended straight onto A. - LayerBlend, - /// A run of consecutive `LayerBlend` passes drawn as one (never planned: the executor draws - /// it in their place, see `batch_runs`). - LayerBatch, - /// `LayerBatch` of a run whose layers all blend Normal without text gamma, outside Lab - /// documents (never planned: the executor picks it, see `batch_kernel`). - LayerBatchNormal, - Atop, - Adjust, - AdjMix, - Lerp, - /// Effect chain start: the layer at fill opacity, or an opaque copy of a clipping base. - FxInit, - /// Paint an effect through a coverage map (or the layer's alpha) into A. - FxPaint, - /// Layer + interior effects over the exterior result, then layer opacity against the backdrop. - FxMerge, - /// Outside strokes: accumulate one stroke's share (`kind` 0, premultiplied colour) or its - /// coverage (`kind` 1). - FxStroke, - /// Outside strokes: resolve the accumulated strokes over the exterior result. - FxStrokeEnd, - /// Copy slot A into `dst` (an existing slot) over the pass clip (no draw). - CopyRect, - /// Copy all of slot A into the fresh slot `dst` (no draw). - CopyFull, - // Effect-map kernels (single-channel targets over an effect region, see `fx`). - MShift, - MDilate, - MBlur, - MGlow, - MFinish, - MBevelH, - MBevelShade, - MStroke, - MBevelTex, -} - -impl Kernel { - /// Fragment entry point in `compose.wgsl` (`None` for copies and clears). - pub fn entry(self) -> Option<&'static str> { - Some(match self { - Kernel::Clear | Kernel::CopyRect | Kernel::CopyFull => return None, - Kernel::Content => "fs_content", - Kernel::Mask => "fs_mask", - Kernel::Blend => "fs_blend", - Kernel::LayerBlend => "fs_layerblend", - Kernel::LayerBatch => "fs_layerbatch", - Kernel::LayerBatchNormal => "fs_layerbatch_normal", - Kernel::Atop => "fs_atop", - Kernel::Adjust => "fs_adjust", - Kernel::AdjMix => "fs_adjmix", - Kernel::Lerp => "fs_lerp", - Kernel::FxInit => "fs_fxinit", - Kernel::FxPaint => "fs_fxpaint", - Kernel::FxMerge => "fs_fxmerge", - Kernel::FxStroke => "fs_fxstroke", - Kernel::FxStrokeEnd => "fs_fxstrokeend", - Kernel::MShift => "fs_mshift", - Kernel::MDilate => "fs_mdilate", - Kernel::MBlur => "fs_mblur", - Kernel::MGlow => "fs_mglow", - Kernel::MFinish => "fs_mfinish", - Kernel::MBevelH => "fs_mbevelh", - Kernel::MBevelShade => "fs_mbevelshade", - Kernel::MStroke => "fs_mstroke", - Kernel::MBevelTex => "fs_mbeveltex", - }) - } - - /// Kernels that write effect maps (R32F / R16F targets) rather than RGBA accumulators. - pub fn is_map(self) -> bool { - matches!( - self, - Kernel::MShift - | Kernel::MDilate - | Kernel::MBlur - | Kernel::MGlow - | Kernel::MFinish - | Kernel::MBevelH - | Kernel::MBevelShade - | Kernel::MStroke - | Kernel::MBevelTex - ) - } - - /// Every kernel with a pipeline. - pub const DRAWN: [Kernel; 24] = [ - Kernel::Content, - Kernel::Mask, - Kernel::Blend, - Kernel::LayerBlend, - Kernel::LayerBatch, - Kernel::LayerBatchNormal, - Kernel::Atop, - Kernel::Adjust, - Kernel::AdjMix, - Kernel::Lerp, - Kernel::FxInit, - Kernel::FxPaint, - Kernel::FxMerge, - Kernel::FxStroke, - Kernel::FxStrokeEnd, - Kernel::MShift, - Kernel::MDilate, - Kernel::MBlur, - Kernel::MGlow, - Kernel::MFinish, - Kernel::MBevelH, - Kernel::MBevelShade, - Kernel::MStroke, - Kernel::MBevelTex, - ]; -} - -/// Which resident texture a pass samples. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Role { - Content, - Mask, - /// A stroked shape's stroke alone (its fill uses `Content`). - Stroke, -} - -/// A surface the pass needs on the GPU. -#[derive(Clone, Debug)] -pub struct TexUse<'a> { - pub layer: LayerId, - pub role: Role, - pub surface: SurfaceRef<'a>, -} - -/// An effect map sampled by a pass: map `map` of enabled effect `item` of `plan.fx[fx]`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct MapRef { - pub fx: usize, - pub item: usize, - pub map: usize, -} - -#[derive(Clone, Debug)] -pub struct Pass<'a> { - pub kernel: Kernel, - pub dst: Slot, - pub a: Option, - pub b: Option, - pub c: Option, - /// A fourth slot, bound in place of `tex` (passes without layer pixels). - pub d: Option, - pub mode: BlendMode, - pub opacity: f32, - /// The layer's Fill where it isn't folded into `opacity`: the final blend of a plain layer - /// (`Kernel::Blend`), so the special eight can apply it inside the blend. 1 elsewhere. - pub fill: f32, - /// Layer pixels (raster / text / shape / smart cache / fill cache). - pub tex: Option>, - /// Colour outside `tex` (the surface's default pixel), the solid fill colour, or the effect - /// colour. - pub color: [f32; 4], - pub mask: Option>, - /// Adjustment kind (see `adjust` in compose.wgsl) and parameters; the coverage kind of an - /// effect paint. - pub adjust_kind: i32, - pub params: [[f32; 4]; 4], - pub extra: [f32; 4], - /// Extra shader flags (`F_KNOCKOUT`, …). - pub flags: u32, - /// 4096-entry LUT rows (Levels / Curves / Gradient map / gradient stops). - pub lut: Option>, - pub gradient: bool, - /// Effect map sampled by `FxPaint`. - pub map: Option, - /// Pattern painted by `FxPaint`. - pub pattern: Option<&'a Pattern>, - /// Only pixels inside this rect (document coordinates) are computed; the pass is skipped for - /// chunks it misses. Consumers of the slot must be clipped alike. - pub clip: Option, -} - -/// Pixels a pass samples: a surface of the document, or one derived from it on the CPU (a -/// combined pixel × vector mask, a shape's fill or stroke alone). -#[derive(Clone, Debug)] -pub enum SurfaceRef<'a> { - Doc(&'a Surface), - Derived(std::sync::Arc), -} - -impl SurfaceRef<'_> { - pub fn get(&self) -> &Surface { - match self { - SurfaceRef::Doc(s) => s, - SurfaceRef::Derived(s) => s, - } - } -} - -#[derive(Clone, Debug)] -pub struct MaskUse<'a> { - pub layer: LayerId, - pub surface: SurfaceRef<'a>, - pub density: f32, - pub default: f32, -} - -impl<'a> Pass<'a> { - pub(crate) fn new(kernel: Kernel, dst: Slot) -> Self { - Pass { - kernel, - dst, - a: None, - b: None, - c: None, - d: None, - mode: BlendMode::Normal, - opacity: 1.0, - fill: 1.0, - tex: None, - color: [0.0; 4], - mask: None, - adjust_kind: 0, - params: [[0.0; 4]; 4], - extra: [0.0; 4], - flags: 0, - lut: None, - gradient: false, - map: None, - pattern: None, - clip: None, - } - } -} - -/// Why a document can't be composited on the GPU (the caller falls back to the CPU compositor). -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Unsupported(pub String); - -impl std::fmt::Display for Unsupported { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "GPU compositor: {}", self.0) - } -} - -impl std::error::Error for Unsupported {} - -/// A layer whose effects the plan renders: its maps are built (or reused) before the chunks run. -#[derive(Clone, Copy, Debug)] -pub struct FxLayer<'a> { - pub layer: &'a Layer, - /// Region the maps cover (`compose::effect_maps`). - pub region: Rect, - /// Layer bounds (gradients and linked patterns are laid out in them). - pub bounds: Rect, -} - #[derive(Debug)] pub struct Plan<'a> { pub passes: Vec>, @@ -300,46 +53,6 @@ pub struct Plan<'a> { pub checkpoints: Vec, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Checkpoint { - /// First root layer included after occlusion pruning. - pub layer_start: usize, - /// Root layers below this boundary (including the complete clipping unit). - pub layer_end: usize, - /// Resume at this pass with `slot` restored. - pub pass_end: usize, - pub slot: Slot, -} - -/// Document-level inputs of a plan. -#[derive(Clone, Copy)] -pub struct DocCtx<'a> { - pub canvas: Rect, - pub transfer: Transfer, - pub light: GlobalLight, - pub patterns: &'a [Pattern], - /// Colour mode (channel restrictions name its channels). - pub mode: photocraft_color::ColorMode, - /// Sample depth (adjustment results are rounded to it). - pub depth: photocraft_color::SampleType, - /// The document (effect geometry the CPU computes, e.g. gradient stroke frames). - pub doc: &'a Document, -} - -impl<'a> DocCtx<'a> { - pub fn of(doc: &'a Document) -> Self { - DocCtx { - canvas: doc.bounds(), - transfer: Transfer::for_document(doc.mode, doc.depth), - light: doc.global_light, - patterns: &doc.patterns, - mode: doc.mode, - depth: doc.depth, - doc, - } - } -} - /// Build the pass list for `doc`. pub fn plan(doc: &Document) -> Result, Unsupported> { if doc.mode == photocraft_color::ColorMode::Multichannel { @@ -354,1534 +67,5 @@ pub fn plan(doc: &Document) -> Result, Unsupported> { Ok(p.finish(root)) } -struct Planner<'a> { - passes: Vec>, - free: Vec, - refs: Vec, - cx: DocCtx<'a>, - fx: Vec>, - checkpoints: Vec, - /// Layers planned so far, counting a layer each time it is planned (a clipped pass-through - /// group is planned twice). - visits: usize, -} - -/// Most layer plannings one document may take: a pass-through group with clipped layers is -/// planned twice, so groups nested in one another double the work at every level. -const MAX_PLAN_VISITS: usize = 100_000; - -/// Coverage source of an effect paint (`kind` in `fs_fxpaint`); flags refine it. -#[derive(Clone, Copy)] -enum Cov { - /// An effect map; `outside` beyond its region. - Map(MapRef, f32), - /// Full coverage. - One, -} - -/// Shader flags for effect passes (keep in sync with compose.wgsl). Coverage `m` of a paint, with -/// `a` the layer's alpha and `inside` = `a > 0.5/255`: -/// knockout `m × (1 − a × k)` (k in `p4.w`); gate `inside ? m : 0`; rel `inside ? min(m / a, 1) : 0`; -/// stroke-out `inside ? (vector ? 0 : (1 − a) / (1 − layer alpha), 1 at an opaque layer) : m`. -pub const F_KNOCKOUT: u32 = 16; -/// Effect merge: A already holds the layer; only mix with the backdrop by the layer's opacity. -pub const F_NO_LAYER: u32 = 32; -/// Outside strokes along a filled shape's outline (`effects::outline_share`; the coverage slot -/// carries the layer's alpha in `.g`). -pub const F_OUTLINE: u32 = 131072; -/// Shape layer (outside strokes never show inside it). -pub const F_VECTOR: u32 = 64; -/// Merge onto an opaque clipping base, keeping its alpha. -pub const F_ATOP: u32 = 128; -pub const F_GATE: u32 = 256; -pub const F_REL: u32 = 512; -pub const F_STROKE_OUT: u32 = 1024; -/// First outside stroke (no accumulated share yet). -pub const F_FIRST: u32 = 2048; -/// `Lerp` per channel: weights in `p0` (channel restrictions), no opacity or mask. -pub const F_CHANNELS: u32 = 4096; -/// Lab document: Normal blending mixes in CIELAB (`psblend::LAB_MIX`). -pub const F_LAB: u32 = 65536; -/// 32-bit float document: Add, Divide and Exposure retain values above 1; the non-separable -/// blend modes clip only below 0 (`psblend::HDR`). -pub const F_HDR: u32 = 262144; -/// `Lerp`: A rounded to `p0.x` steps per unit (adjustment results on integer documents). -pub const F_QUANT: u32 = 32768; -/// `Lerp` as A + (B − C) premultiplied (layers clipped to pass-through groups). -pub const F_ADD_DIFF: u32 = 16384; -/// `Lerp`: B mixed back towards A (the backdrop) by the layer's Blend If weight -/// (`compose::apply_blend_if`), from C ("This Layer", or B itself for an adjustment layer, `p4.y`) -/// and A ("Underlying Layer"). The ranges are packed in `p0..p3` (`blend_if_params`); `p4.x` marks -/// a one-channel document. -pub const F_BLEND_IF: u32 = 524288; -/// Blend / Atop / FxMerge of a type layer: coverage mixed at `psblend::TEXT_GAMMA`. -pub const F_TEXT_GAMMA: u32 = 8192; -/// `FxMerge`: B is the layer's shape (its content); the layer is its colour at fill opacity -/// (`p0.x`) inside the shape, times the shape's alpha: `FxInit` `INIT_INSIDE` then -/// `INIT_ALPHA` in the merge, for a layer with no interior effects between them. -pub const F_LAYER_SHAPE: u32 = 1_048_576; - -/// A layer's Blend If ranges for `F_BLEND_IF`: Gray, then the colour channels, each as -/// [this layer, underlying layer]; every range as two floats, `black low × 256 + black high` and -/// `white low × 256 + white high` (exact in f32), so entry `e`, side `s` starts at float -/// `(e × 2 + s) × 2`. Entries past the fourth never apply (RGB has four, one-channel modes two). -fn blend_if_params(bi: &photocraft_doc::BlendIf) -> [[f32; 4]; 4] { - let mut f = [0.0f32; 16]; - for e in 0..4 { - for (s, r) in bi.get(e).iter().enumerate() { - let i = (e * 2 + s) * 2; - f[i] = f32::from(r.black[0]) * 256.0 + f32::from(r.black[1]); - f[i + 1] = f32::from(r.white[0]) * 256.0 + f32::from(r.white[1]); - } - } - [[f[0], f[1], f[2], f[3]], [f[4], f[5], f[6], f[7]], [f[8], f[9], f[10], f[11]], [f[12], f[13], f[14], f[15]]] -} - -/// `F_TEXT_GAMMA` for type layers while text gamma blending is on; the gamma goes in `p4.w`. -fn gamma_flag(layer: &Layer) -> u32 { - if photocraft_compose::text_gamma(layer) != 1.0 { F_TEXT_GAMMA } else { 0 } -} - -/// `FxInit` kinds: A at `opacity` × alpha; an opaque copy of A; A's colour with alpha `opacity` -/// inside B's shape; A with alpha × B's alpha. -pub const INIT_SCALE: i32 = 0; -pub const INIT_OPAQUE: i32 = 1; -pub const INIT_INSIDE: i32 = 2; -pub const INIT_ALPHA: i32 = 3; -/// The vector stroke C over A relative to the shape B, at `opacity`. -pub const INIT_VSTROKE: i32 = 4; -/// A's colour with alpha `opacity` × A's alpha relative to B's. -pub const INIT_RELATIVE: i32 = 5; -/// Outside-stroke coverage seed: (0, A's alpha). -pub const INIT_COVER: i32 = 6; -/// A with its alpha joined with the effect shape (the map). -pub const INIT_OUTLINE: i32 = 7; - -/// `MapRef::item` of the layer's effect shape (`compose::layer_shape`) instead of an effect map. -pub const SHAPE_MAP: usize = usize::MAX; - -impl<'a> Planner<'a> { - fn new(cx: DocCtx<'a>) -> Self { - Planner { passes: Vec::new(), free: Vec::new(), refs: Vec::new(), cx, fx: Vec::new(), checkpoints: Vec::new(), visits: 0 } - } - - fn finish(self, root: Slot) -> Plan<'a> { - Plan { passes: self.passes, slots: self.refs.len() as u32, root, fx: self.fx, checkpoints: self.checkpoints } - } - - fn alloc(&mut self) -> Slot { - if let Some(s) = self.free.pop() { - self.refs[s as usize] = 1; - return s; - } - self.refs.push(1); - (self.refs.len() - 1) as Slot - } - fn retain(&mut self, s: Slot) -> Slot { - self.refs[s as usize] += 1; - s - } - fn release(&mut self, s: Slot) { - let r = &mut self.refs[s as usize]; - *r -= 1; - if *r == 0 { - self.free.push(s); - } - } - /// Emit `pass` into a fresh slot, releasing its inputs. - fn emit(&mut self, mut pass: Pass<'a>) -> Slot { - let dst = self.alloc(); - pass.dst = dst; - if self.cx.mode == photocraft_color::ColorMode::Lab { - pass.flags |= F_LAB; - } - if self.cx.depth == photocraft_color::SampleType::F32 { - pass.flags |= F_HDR; - } - let (a, b, c, d) = (pass.a, pass.b, pass.c, pass.d); - self.passes.push(pass); - for s in [a, b, c, d].into_iter().flatten() { - self.release(s); - } - dst - } - fn clear(&mut self) -> Slot { - self.emit(Pass::new(Kernel::Clear, 0)) - } - - /// composite_stack: returns the new backdrop (consumes `backdrop`). - fn stack(&mut self, layers: &'a [Layer], backdrop: Slot) -> Result { - self.stack_inner(layers, backdrop, None) - } - - fn stack_inner(&mut self, layers: &'a [Layer], mut backdrop: Slot, root_start: Option) -> Result { - let mut i = 0; - while i < layers.len() { - let base = &layers[i]; - let mut j = i + 1; - while j < layers.len() && layers[j].clipped && !base.clipped { - j += 1; - } - let clipped = &layers[i + 1..j]; - if base.visible { - backdrop = self.layer(base, clipped, backdrop)?; - if let (LayerContent::Adjustment(_), Some(q)) = (&base.content, photocraft_compose::adjustment_quantum(self.cx.depth)) { - // compose: adjustment results are rounded to the document's depth. - let mut p = Pass::new(Kernel::Lerp, 0); - p.a = Some(backdrop); - p.flags = F_QUANT; - p.params[0] = [q, 0.0, 0.0, 0.0]; - backdrop = self.emit(p); - } - } - i = j.max(i + 1); - if let Some(start) = root_start - && self.refs.iter().enumerate().all(|(slot, &refs)| refs == u32::from(slot == backdrop as usize)) - { - self.checkpoints.push(Checkpoint { layer_start: start, layer_end: start.saturating_add(i), pass_end: self.passes.len(), slot: backdrop }); - } - } - Ok(backdrop) - } - - fn mask_use(&self, layer: &'a Layer) -> Option> { - if let Some(c) = photocraft_compose::masks::combined_mask(layer, self.cx.canvas) { - let default = c.default_pixel().first().copied().unwrap_or(1.0); - return Some(MaskUse { layer: layer.id, surface: SurfaceRef::Derived(std::sync::Arc::new(c)), density: 1.0, default }); - } - let m = layer.mask.as_ref()?; - if !m.enabled { - return None; - } - Some(MaskUse { - layer: layer.id, - surface: SurfaceRef::Doc(&m.surface), - density: m.density, - default: m.surface.default_pixel().first().copied().unwrap_or(1.0), - }) - } - - /// `compose::apply_blend_if`: `after` (the backdrop with `layer` drawn) mixed back towards - /// `before` (the backdrop without it) where the layer's Blend If ranges hide it. "This Layer" - /// is the layer's own content with its masks; an adjustment layer is judged by its result. - /// Consumes both slots. - fn blend_if(&mut self, layer: &'a Layer, before: Slot, after: Slot) -> Result { - let own = match layer.content { - LayerContent::Adjustment(_) => None, - _ => Some(self.content(layer)?), - }; - let mut p = Pass::new(Kernel::Lerp, 0); - p.a = Some(before); - p.b = Some(after); - p.c = own; - p.flags = F_BLEND_IF; - p.params = blend_if_params(&layer.blend_if); - let one_channel = self.cx.mode != photocraft_color::ColorMode::Rgb; - p.extra = [f32::from(u8::from(one_channel)), f32::from(u8::from(own.is_none())), 0.0, 0.0]; - Ok(self.emit(p)) - } - - /// Channel restrictions and Blend If around `draw`, which composites `layer` onto `backdrop` - /// (`compose::composite_layer` / `composite_atop`: both are relative to the same backdrop). - fn restricted(&mut self, layer: &'a Layer, backdrop: Slot, draw: impl FnOnce(&mut Self, Slot) -> Result) -> Result { - let w = photocraft_compose::channel_weights(layer, self.cx.mode); - let blend_if = photocraft_compose::blend_if_active(layer, self.cx.mode); - if w.is_none() && !blend_if { - return draw(self, backdrop); - } - let before = self.retain(backdrop); - let mut after = draw(self, backdrop)?; - if let Some(w) = w { - let b = if blend_if { self.retain(before) } else { before }; - after = self.restore_channels(b, after, w); - } - if blend_if { - after = self.blend_if(layer, before, after)?; - } - Ok(after) - } - - /// Blending Options › Advanced Blending (knockout, clipped layers blended individually, blend - /// interior effects as group, transparency shapes off, masks hiding effects) has no GPU pass: - /// documents using it are composited on the CPU (`photocraft_compose::advanced`). Layers at - /// Photoshop's defaults pass this check for free. - fn check_advanced(&self, layer: &Layer, clipped: &[Layer]) -> Result<(), Unsupported> { - if photocraft_compose::advanced_active(layer, clipped) { - return Err(Unsupported(format!("Advanced Blending on `{}` (composited on the CPU)", layer.name))); - } - Ok(()) - } - - /// composite_layer, honouring the layer's channel restrictions. - fn layer(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result { - self.visits += 1; - if self.visits > MAX_PLAN_VISITS { - return Err(Unsupported("too many nested layers to plan for the GPU (composited on the CPU)".into())); - } - self.check_advanced(layer, clipped)?; - self.restricted(layer, backdrop, |s, b| s.layer_any(layer, clipped, b)) - } - - /// `compose::restore_channels`: `after` with the channels a layer leaves out taken from - /// `before` (consumes both). - fn restore_channels(&mut self, before: Slot, after: Slot, w: [f32; 3]) -> Slot { - let mut p = Pass::new(Kernel::Lerp, 0); - p.a = Some(before); - p.b = Some(after); - p.flags = F_CHANNELS; - p.params[0] = [w[0], w[1], w[2], 1.0]; - self.emit(p) - } - - fn layer_any(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result { - match layer.artboard() { - Some(ab) => self.artboard(layer, ab, clipped, backdrop), - None => self.layer_plain(layer, clipped, backdrop), - } - } - - /// compose::composite_artboard: the board's background and the group composited over the - /// backdrop, kept only inside the board (contents and effects outside it are clipped away). - fn artboard(&mut self, layer: &'a Layer, ab: &photocraft_doc::Artboard, clipped: &'a [Layer], backdrop: Slot) -> Result { - let board = ab.rect.intersect(&self.cx.canvas); - if board.is_empty() { - return Ok(backdrop); - } - let before = self.retain(backdrop); - let mut sub = backdrop; - if let Some(bg) = ab.background.rgba() { - let mut c = Pass::new(Kernel::Content, 0); - c.color = bg; - let c = self.emit(c); - let mut p = Pass::new(Kernel::Blend, 0); - p.a = Some(sub); - p.b = Some(c); - sub = self.emit(p); - } - let sub = self.layer_plain(layer, clipped, sub)?; - let dst = if self.refs[before as usize] == 1 { - before - } else { - let n = self.alloc(); - let mut p = Pass::new(Kernel::CopyFull, n); - p.a = Some(before); - self.passes.push(p); - self.release(before); - n - }; - let mut p = Pass::new(Kernel::CopyRect, dst); - p.a = Some(sub); - p.clip = Some(board); - self.passes.push(p); - self.release(sub); - Ok(dst) - } - - fn layer_plain(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result { - let opacity = layer.opacity * layer.fill_opacity; - let visible_clipped: Vec<&'a Layer> = clipped.iter().filter(|c| c.visible).collect(); - - // Below 100% fill a pass-through group renders isolated (as the CPU compositor does), and - // so does one that is the base of a clipping group and holds an adjustment layer. - let clip_base_adjusts = !visible_clipped.is_empty() - && matches!(&layer.content, LayerContent::Group(g) if g.children.iter().any(|c| c.visible && matches!(c.content, LayerContent::Adjustment(_)))); - if let LayerContent::Group(g) = &layer.content - && layer.blend == BlendMode::PassThrough - && layer.fill_opacity >= 1.0 - && !has_effects(layer) - && !clip_base_adjusts - { - let before = self.retain(backdrop); - let mut after = self.stack(&g.children, backdrop)?; - if opacity < 1.0 || layer.mask.is_some() || layer.vector_mask.is_some() { - let mut p = Pass::new(Kernel::Lerp, 0); - p.a = Some(self.retain(before)); - p.b = Some(after); - p.opacity = opacity; - p.mask = self.mask_use(layer); - after = self.emit(p); - } - if visible_clipped.is_empty() { - self.release(before); - return Ok(after); - } - // Layers clipped to a pass-through group (compose: their effect on the group's - // isolated rendering, each placed over the original backdrop, is added to the - // pass-through result, premultiplied). - let iso = self.content(layer)?; - let iso_keep = self.retain(iso); - let mut clipped_iso = iso; - for c in visible_clipped { - clipped_iso = self.atop(c, clipped_iso)?; - } - let over = |s: &mut Self, src: Slot, before: Slot| { - let mut p = Pass::new(Kernel::Blend, 0); - p.a = Some(before); - p.b = Some(src); - p.opacity = opacity; - s.emit(p) - }; - let b2 = self.retain(before); - let without = over(self, iso_keep, b2); - let with = over(self, clipped_iso, before); - let mut p = Pass::new(Kernel::Lerp, 0); - p.a = Some(after); - p.b = Some(with); - p.c = Some(without); - p.flags = F_ADD_DIFF; - return Ok(self.emit(p)); - } - - if let LayerContent::Adjustment(adj) = &layer.content { - let before = self.retain(backdrop); - let mut adjusted = self.adjust(adj, backdrop)?; - for c in visible_clipped { - adjusted = self.atop(c, adjusted)?; - } - let mut p = Pass::new(Kernel::AdjMix, 0); - p.a = Some(before); - p.b = Some(adjusted); - p.mode = layer.blend; - p.opacity = opacity; - p.mask = self.mask_use(layer); - return Ok(self.emit(p)); - } - - if has_effects(layer) { - return self.effects(layer, &visible_clipped, backdrop, false); - } - - if let LayerContent::Shape(sh) = &layer.content - && !visible_clipped.is_empty() - && let Some((fill, stroke)) = photocraft_compose::shape_split::split(sh, self.cx.canvas, self.cx.depth) - { - // The vector stroke goes above the clipped layers: the fill is the clipping base, - // the stroke is laid over the clipped result, then the masks apply to both - // (compose::shape_parts). - let mut content = self.shape_part(layer, Role::Content, fill); - for c in visible_clipped { - content = self.atop(c, content)?; - } - let stroke = self.shape_part(layer, Role::Stroke, stroke); - let mut p = Pass::new(Kernel::Blend, 0); - p.a = Some(content); - p.b = Some(stroke); - let mut content = self.emit(p); - if let Some(m) = self.mask_use(layer) { - let mut p = Pass::new(Kernel::Mask, 0); - p.a = Some(content); - p.mask = Some(m); - content = self.emit(p); - } - let mut p = Pass::new(Kernel::Blend, 0); - p.a = Some(backdrop); - p.b = Some(content); - p.mode = layer.blend; - p.opacity = layer.opacity; - p.fill = layer.fill_opacity; - return Ok(self.emit(p)); - } - - // A layer that covers little of the canvas composites only over its bounds and is - // copied back into the backdrop (#125): a layout with hundreds of small text and shape - // layers otherwise shades every layer over every chunk. - let clip = self.local_clip(layer); - if clip.is_some_and(|c| c.is_empty()) { - // Nothing to draw (an empty layer, or a group of them). - for c in &visible_clipped { - self.check_advanced(c, &[])?; - } - return Ok(backdrop); - } - // A layer with nothing clipped to it whose content is one Content pass is blended - // straight from its pixels (`Kernel::LayerBlend`): one pass instead of two, and no - // scratch chunk written and read back. - let mut p = if visible_clipped.is_empty() && single_content_pass(layer) { - let mut p = self.content_pass(layer)?; - p.kernel = Kernel::LayerBlend; - p - } else { - let start = self.passes.len(); - let mut content = self.content(layer)?; - for c in visible_clipped { - content = self.atop(c, content)?; - } - if let Some(clip) = clip { - // Everything that built the layer's content only matters inside its bounds. - for p in &mut self.passes[start..] { - if p.clip.is_none() && !matches!(p.kernel, Kernel::Clear | Kernel::CopyFull) { - p.clip = Some(clip); - } - } - } - let mut p = Pass::new(Kernel::Blend, 0); - p.b = Some(content); - p - }; - p.a = Some(if clip.is_some() { self.retain(backdrop) } else { backdrop }); - p.mode = layer.blend; - p.opacity = layer.opacity; - p.fill = layer.fill_opacity; - p.flags |= gamma_flag(layer); - p.extra[3] = photocraft_compose::text_gamma(layer); - p.clip = clip; - let merged = self.emit(p); - match clip { - Some(clip) => Ok(self.write_back(backdrop, merged, clip)), - None => Ok(merged), - } - } - - /// The rect a plain layer composites over: its composite bounds when they cover at most half - /// the canvas (beyond that, compositing everywhere costs less than the copy back). - fn local_clip(&self, layer: &Layer) -> Option { - let canvas = self.cx.canvas; - let b = bounds::composite_bounds(layer, canvas)?; - (b.width() as u64 * b.height() as u64 * 2 <= canvas.width() as u64 * canvas.height() as u64).then_some(b) - } - - /// Copy `merged` into `backdrop` over `clip` (in place when nothing else holds the backdrop); - /// returns the new backdrop. Consumes both. - fn write_back(&mut self, backdrop: Slot, merged: Slot, clip: Rect) -> Slot { - // A clip over the whole canvas left no pixel of `merged` uncomputed: it is the backdrop. - if clip.contains_rect(&self.cx.canvas) { - self.release(backdrop); - return merged; - } - let dst = if self.refs[backdrop as usize] == 1 { - backdrop - } else { - let n = self.alloc(); - let mut p = Pass::new(Kernel::CopyFull, n); - p.a = Some(backdrop); - self.passes.push(p); - self.release(backdrop); - n - }; - let mut p = Pass::new(Kernel::CopyRect, dst); - p.a = Some(merged); - p.clip = Some(clip); - self.passes.push(p); - self.release(merged); - dst - } - - /// A stroked shape's fill or vector stroke alone (`compose::shape_split`), unmasked. - fn shape_part(&mut self, layer: &'a Layer, role: Role, surface: Surface) -> Slot { - let mut p = Pass::new(Kernel::Content, 0); - p.color = photocraft_raster::to_rgba(&surface.format(), &surface.default_pixel()); - if surface.tile_count() > 0 { - p.tex = Some(TexUse { layer: layer.id, role, surface: SurfaceRef::Derived(std::sync::Arc::new(surface)) }); - } - self.emit(p) - } - - /// render_content for non-adjustment layers. - fn content(&mut self, layer: &'a Layer) -> Result { - match &layer.content { - LayerContent::Group(g) => { - let empty = self.clear(); - let s = self.stack(&g.children, empty)?; - if layer.mask.is_some() || layer.vector_mask.is_some() { - let mut p = Pass::new(Kernel::Mask, 0); - p.a = Some(s); - p.mask = self.mask_use(layer); - return Ok(self.emit(p)); - } - Ok(s) - } - // Adjustments are handled by the caller and never get here. - LayerContent::Adjustment(_) => Err(Unsupported("adjustment layer reached the content planner".into())), - LayerContent::Fill(f @ Fill::Pattern { name, scale, id, angle, link, phase }) if layer.fill_cache.as_ref().is_none_or(|c| c.fill != *f) => { - // compose::render_fill: the pattern tiled from the layer's frame (transparent - // when missing), then the layer's masks. - let empty = self.clear(); - let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) else { return Ok(empty) }; - let frame = photocraft_compose::fill_frame(layer, self.cx.canvas); - let anchor = if frame.is_empty() { (0.0, 0.0) } else { (f64::from(frame.x0), f64::from(frame.y0)) }; - let paint = Paint::Pattern(pat, placement(anchor, *link, *phase, *scale, *angle)); - let canvas = self.cx.canvas; - let s = self.paint(empty, empty, Cov::One, &paint, BlendMode::Normal, 1.0, 0, canvas, canvas); - if layer.mask.is_some() || layer.vector_mask.is_some() { - let mut p = Pass::new(Kernel::Mask, 0); - p.a = Some(s); - p.mask = self.mask_use(layer); - return Ok(self.emit(p)); - } - Ok(s) - } - _ => { - let p = self.content_pass(layer)?; - Ok(self.emit(p)) - } - } - } - - /// The Content pass of a raster / text / shape / smart / fill layer. - fn content_pass(&self, layer: &'a Layer) -> Result, Unsupported> { - let mut p = Pass::new(Kernel::Content, 0); - p.mask = self.mask_use(layer); - match &layer.content { - LayerContent::Fill(f) => match &layer.fill_cache { - Some(c) if c.fill == *f => self.surface_tex(&mut p, layer.id, &c.surface), - _ => self.fill(&mut p, f, photocraft_compose::fill_frame(layer, self.cx.canvas))?, - }, - _ => { - if let Some(s) = layer.surface() { - self.surface_tex(&mut p, layer.id, s); - } - } - } - Ok(p) - } - - fn surface_tex(&self, p: &mut Pass<'a>, id: LayerId, s: &'a Surface) { - let dp = s.default_pixel(); - p.color = photocraft_raster::to_rgba(&s.format(), &dp); - if s.tile_count() > 0 { - p.tex = Some(TexUse { layer: id, role: Role::Content, surface: SurfaceRef::Doc(s) }); - } - } - - fn fill(&self, p: &mut Pass<'a>, f: &Fill, frame: photocraft_geom::Rect) -> Result<(), Unsupported> { - // The RGB shader cannot interpolate or dither native ink channels. - if self.cx.mode == photocraft_color::ColorMode::Cmyk && !matches!(f, Fill::Pattern { .. }) { - return Err(Unsupported("native CMYK fill (composited on the CPU)".into())); - } - match f { - Fill::Solid(c) => { - let rgb = c.to_rgb(); - p.color = [rgb[0], rgb[1], rgb[2], c.alpha]; - } - Fill::Gradient { stops, opacity_stops, angle, scale, style, reverse, offset, dither, .. } => { - check_gradient_stops(stops)?; - check_gradient_stops(opacity_stops)?; - p.gradient = true; - // compose::render_fill: whole-pixel end points (fill_layout). - let (angle, scale, offset) = photocraft_compose::fill_layout::gradient_layout(*style, *angle, *scale, *offset, frame); - p.params[0] = [angle, scale, if *reverse { 1.0 } else { 0.0 }, style_index(*style)]; - let c = frame; - p.params[1] = [c.x0 as f32, c.y0 as f32, c.width() as f32, c.height() as f32]; - // p2.xy: centre offset; p2.z: the depth's levels a dithered pixel is rounded to - // (0: float, compose::gradient_fill::render_quantized); p2.w: dither (the shared - // position hash, see the shader). - let quantum = photocraft_compose::adjustment_quantum(self.cx.depth).unwrap_or(0.0); - p.params[2] = [offset.0, offset.1, quantum, if *dither { 1.0 } else { 0.0 }]; - let ramp = photocraft_compose::gradient_fill::Ramp::new(f); - let mut rows = vec![[0.0f32; 4096]; 4]; - for k in 0..4096 { - let v = ramp.as_ref().map_or([0.0; 4], |r| r.sample(k as f32 / 4095.0)); - for (ch, row) in rows.iter_mut().enumerate() { - row[k] = v[ch]; - } - } - p.lut = Some(rows); - } - // Pattern fills fall back to the CPU compositor (see `check`). - Fill::Pattern { .. } => {} - } - Ok(()) - } - - /// composite_atop: `layer` onto `base`, restricted to the base's alpha, honouring the - /// layer's channel restrictions. - fn atop(&mut self, layer: &'a Layer, base: Slot) -> Result { - self.check_advanced(layer, &[])?; - self.restricted(layer, base, |s, b| s.atop_any(layer, b)) - } - - fn atop_any(&mut self, layer: &'a Layer, base: Slot) -> Result { - let opacity = layer.opacity * layer.fill_opacity; - if let LayerContent::Adjustment(adj) = &layer.content { - let before = self.retain(base); - let adjusted = self.adjust(adj, base)?; - let mut p = Pass::new(Kernel::AdjMix, 0); - p.a = Some(before); - p.b = Some(adjusted); - p.mode = layer.blend; - p.opacity = opacity; - p.mask = self.mask_use(layer); - return Ok(self.emit(p)); - } - if has_effects(layer) { - return self.effects(layer, &[], base, true); - } - let content = self.content(layer)?; - let mut p = Pass::new(Kernel::Atop, 0); - p.a = Some(base); - p.b = Some(content); - p.mode = layer.blend; - p.opacity = opacity; - p.flags = gamma_flag(layer); - p.extra[3] = photocraft_compose::text_gamma(layer); - Ok(self.emit(p)) - } - - /// adjust::apply_with on a slot (consumes it). - fn adjust(&mut self, adj: &Adjustment, src: Slot) -> Result { - if !adjustment_on_gpu(adj, self.cx.mode) { - return Err(Unsupported(format!("{} on CMYK/Lab channels (evaluated on the CPU)", adj.label()))); - } - if let Adjustment::GradientMap { stops, .. } = adj { - check_gradient_stops(stops)?; - } - let mut p = Pass::new(Kernel::Adjust, 0); - p.a = Some(src); - let (kind, params, lut) = adjustment_program(adj, self.cx.transfer, self.cx.depth, self.cx.mode); - p.adjust_kind = kind; - p.params = params; - p.lut = lut; - Ok(self.emit(p)) - } - - /// `composite_with_effects` (atop = false) or the clipped-layer variant of `composite_atop` - /// (atop = true: effects over the base treated as opaque, keeping the base's alpha). - /// Consumes `backdrop`. - fn effects(&mut self, layer: &'a Layer, clipped: &[&'a Layer], backdrop: Slot, atop: bool) -> Result { - let canvas = self.cx.canvas; - let region = bounds::effect_region(layer, canvas); - let sb = photocraft_compose::paint_bounds(layer).unwrap_or_else(|| bounds::layer_bounds(layer, canvas)); - let clip = if bounds::transparent_outside(layer) { region } else { canvas }; - // A stroked shape's vector stroke goes above its clipped layers and interior effects - // (compose::split_parts): the fill and the stroke unmasked, the masks applied after. - let split = match &layer.content { - LayerContent::Shape(sh) if sh.stroke.is_some() => photocraft_compose::shape_split::split(sh, canvas, self.cx.depth), - _ => None, - }; - let (mut content, vstroke) = match split { - Some((fill, stroke)) => { - let f = self.shape_part(layer, Role::Content, fill); - let s = self.shape_part(layer, Role::Stroke, stroke); - (f, Some(s)) - } - None => (self.content(layer)?, None), - }; - for p in self.passes.iter_mut().rev().take(if vstroke.is_some() { 2 } else { 1 }) { - if !matches!(layer.content, LayerContent::Group(_)) { - p.clip = Some(clip); - } - } - for c in clipped { - content = self.atop(c, content)?; - } - let fx = self.fx.len(); - self.fx.push(FxLayer { layer, region, bounds: sb }); - let outline = photocraft_compose::effect_outline(layer).is_some(); - let relative = outline || vstroke.is_some(); - // `content` becomes the effect shape (B of every effect pass); `lay_src` the layer's colour. - let (lay_src, vstroke) = match vstroke { - Some(s) => { - let mut p = Pass::new(Kernel::Blend, 0); - p.a = Some(self.retain(content)); - p.b = Some(self.retain(s)); - p.clip = Some(clip); - let union = self.emit(p); - let m = self.mask_use(layer); - let masked = |me: &mut Self, slot: Slot| match &m { - Some(m) => { - let mut p = Pass::new(Kernel::Mask, 0); - p.a = Some(slot); - p.mask = Some(m.clone()); - p.clip = Some(clip); - me.emit(p) - } - None => slot, - }; - let fill = masked(self, content); - content = masked(self, union); - (fill, Some(masked(self, s))) - } - None => (self.retain(content), None), - }; - if outline { - let mut p = Pass::new(Kernel::FxInit, 0); - p.a = Some(content); - p.adjust_kind = INIT_OUTLINE; - p.map = Some(MapRef { fx, item: SHAPE_MAP, map: 0 }); - p.clip = Some(clip); - content = self.emit(p); - } - - let items: Vec<&'a Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); - for e in &items { - let gradient = match e { - Effect::GradientOverlay { gradient, .. } => Some(gradient), - Effect::Stroke(s) => match &s.paint { - FxPaint::Gradient(g) => Some(g), - _ => None, - }, - Effect::OuterGlow(g) | Effect::InnerGlow(g) => match &g.paint { - FxPaint::Gradient(g) => Some(g), - _ => None, - }, - _ => None, - }; - if let Some(g) = gradient { - check_gradient_stops(&g.stops)?; - check_gradient_stops(&g.opacity_stops)?; - } - } - // Linked patterns tile from the effects reference point (else the layer's top-left). - let anchor = layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))); - let vector_shape = matches!(layer.content, LayerContent::Shape(_)) && !outline; - let map = |item: usize, map: usize| MapRef { fx, item, map }; - let rev: Vec<(usize, &'a Effect)> = items.iter().copied().enumerate().rev().collect(); - let init = |s: &mut Self, src: Slot, b: Option, kind: i32, opacity: f32| { - let mut p = Pass::new(Kernel::FxInit, 0); - p.a = Some(src); - p.b = b; - p.adjust_kind = kind; - p.opacity = opacity; - p.clip = Some(clip); - s.emit(p) - }; - - // Exterior effects over the backdrop (an opaque copy of it for clipped layers). - let mut w = if atop { - let b = self.retain(backdrop); - init(self, b, None, INIT_OPAQUE, 1.0) - } else { - self.retain(backdrop) - }; - for &(i, e) in &rev { - if let Effect::DropShadow(s) = e { - // The layer hides the shadow beneath it where its fill is see-through, and wholly - // in a mode that blends with it (as the CPU renderer: `shadow_see_through`). - let flags = if s.knocks_out { F_KNOCKOUT } else { 0 }; - let see_through = photocraft_compose::effects::shadow_see_through(layer); - w = self.paint_k( - w, - content, - Cov::Map(map(i, 0), 0.0), - &Paint::Color(s.color.to_rgb()), - s.common.blend, - s.common.opacity, - flags, - clip, - sb, - see_through, - ); - } - } - for &(i, e) in &rev { - if let Effect::OuterGlow(g) = e { - let paint = self.glow_paint(g, anchor); - // Match CPU exterior knockout: a see-through fill must not reveal the - // glow through its own shape. The shader applies m × (1 − alpha × k). - let see_through = 1.0 - layer.fill_opacity.clamp(0.0, 1.0); - w = self.paint_k(w, content, Cov::Map(map(i, 0), 0.0), &paint, g.common.blend, g.common.opacity, F_KNOCKOUT, clip, sb, see_through); - } - } - - // Only exterior effects (drop shadows, outer glows): nothing is painted between the - // layer's colour inside its shape and the shape's alpha, so the merge derives both from - // the shape (`F_LAYER_SHAPE`) instead of two passes building the layer. - let premerge = photocraft_compose::effects::premerges_layer(layer); - if !relative && !premerge && items.iter().all(|e| matches!(e, Effect::DropShadow(_) | Effect::OuterGlow(_))) { - let mut p = Pass::new(Kernel::FxMerge, 0); - p.a = Some(w); - p.b = Some(lay_src); - p.c = Some(self.retain(backdrop)); - p.mode = if layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; - p.opacity = layer.opacity; - p.flags = if atop { F_ATOP } else { 0 } | gamma_flag(layer) | F_LAYER_SHAPE; - p.params[0][0] = layer.fill_opacity; - p.extra[3] = photocraft_compose::text_gamma(layer); - p.clip = Some(clip); - let merged = self.emit(p); - self.release(content); - return Ok(self.write_back(backdrop, merged, clip)); - } - // The layer: its colour at fill opacity inside its shape; interior effects are painted - // relative to the shape (coverage within it), then the shape's alpha applies. - let mut l = if relative { - let c = self.retain(content); - init(self, lay_src, Some(c), INIT_RELATIVE, layer.fill_opacity) - } else { - init(self, lay_src, None, INIT_INSIDE, layer.fill_opacity) - }; - // Blend Interior Effects as Group off: the layer merges in its mode first and the - // interior effects paint over the result (`effects::premerges_layer`). - if premerge { - let mut p = Pass::new(Kernel::Blend, 0); - p.a = Some(self.retain(w)); - p.b = Some(l); - p.mode = layer.blend; - p.flags = gamma_flag(layer); - p.extra[3] = photocraft_compose::text_gamma(layer); - p.clip = Some(clip); - l = self.emit(p); - } - for &(_, e) in &rev { - if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e - && let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) - { - let paint = Paint::Pattern(pat, placement(anchor, *link, *phase, *scale, *angle)); - l = self.paint(l, content, Cov::One, &paint, common.blend, common.opacity, F_GATE, clip, sb); - } - } - for &(_, e) in &rev { - if let Effect::GradientOverlay { common, gradient, .. } = e { - l = self.paint(l, content, Cov::One, &Paint::Gradient(gradient), common.blend, common.opacity, F_GATE, clip, sb); - } - } - for &(_, e) in &rev { - if let Effect::ColorOverlay { common, color } = e { - l = self.paint(l, content, Cov::One, &Paint::Color(color.to_rgb()), common.blend, common.opacity, F_GATE, clip, sb); - } - } - for &(i, e) in &rev { - if let Effect::Satin(s) = e { - l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(s.color.to_rgb()), s.common.blend, s.common.opacity, F_REL, clip, sb); - } - } - for &(i, e) in &rev { - if let Effect::InnerGlow(g) = e { - let paint = self.glow_paint(g, anchor); - l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &paint, g.common.blend, g.common.opacity, F_REL, clip, sb); - } - } - for &(i, e) in &rev { - if let Effect::InnerShadow(s) = e { - l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(s.color.to_rgb()), s.common.blend, s.common.opacity, F_REL, clip, sb); - } - } - if let Some(s) = vstroke { - let mut p = Pass::new(Kernel::FxInit, 0); - p.a = Some(l); - p.b = Some(self.retain(content)); - p.c = Some(s); - p.adjust_kind = INIT_VSTROKE; - p.opacity = layer.fill_opacity; - p.clip = Some(clip); - l = self.emit(p); - } - // Inside stroke parts are painted over the layer (bottom instance first). - for &(i, e) in &rev { - if let Effect::Stroke(st) = e { - let (in_w, _) = stroke_widths(st); - if in_w > 0.0 { - let paint = self.fx_paint(&st.paint, anchor); - l = self.paint( - l, - content, - Cov::Map(map(i, 1), (in_w + 0.5).clamp(0.0, 1.0)), - &paint, - st.common.blend, - st.common.opacity, - F_GATE, - clip, - photocraft_compose::stroke_frame(self.cx.doc, layer, st).unwrap_or(sb), - ); - } - } - } - let bevel_paint = |b: &photocraft_doc::Bevel| photocraft_compose::effects::bevel_geom(b).paint; - for &(i, e) in &rev { - if let Effect::BevelEmboss(b) = e - && bevel_paint(b) == photocraft_compose::effects::BevelPaint::Inner - { - l = self.paint( - l, - content, - Cov::Map(map(i, 0), 0.0), - &Paint::Color(b.highlight_color.to_rgb()), - b.highlight.blend, - b.highlight.opacity, - F_REL, - clip, - sb, - ); - l = self.paint(l, content, Cov::Map(map(i, 1), 0.0), &Paint::Color(b.shadow_color.to_rgb()), b.shadow.blend, b.shadow.opacity, F_REL, clip, sb); - } - } - // The shape's own alpha. - let c = self.retain(content); - l = init(self, l, Some(c), INIT_ALPHA, 1.0); - // Outside stroke parts lie beneath the layer and blend onto the exterior result with their - // own mode; a higher stroke covers the ones below it (each takes its coverage × opacity - // not yet taken above it, blended over the result as it was before the strokes). - let outs: Vec<(usize, &photocraft_doc::StrokeFx)> = items - .iter() - .copied() - .enumerate() - .filter_map(|(i, e)| if let Effect::Stroke(st) = e { Some((i, st)) } else { None }) - .filter(|(_, st)| stroke_widths(st).1 > 0.0) - .collect(); - if !outs.is_empty() { - let (mut acc, mut cover): (Option, Option) = (None, None); - if outline || !vector_shape { - // The layer's alpha rides along the coverage: `effects::outline_share`, and for - // pixel layers the stroke's share beneath a partly covering layer (fill < 100 %). - let ll = self.retain(l); - cover = Some(init(self, ll, None, INIT_COVER, 1.0)); - } - for (n, &(i, st)) in outs.iter().enumerate() { - let paint = self.fx_paint(&st.paint, anchor); - let flags = F_STROKE_OUT | if vector_shape { F_VECTOR } else { 0 } | if outline { F_OUTLINE } else { 0 } | if n == 0 { F_FIRST } else { 0 }; - // Share × blended colour, then coverage (both read the coverage so far). - let mut p = self.fx_pass_kernel( - Kernel::FxStroke, - w, - content, - &paint, - st.common.blend, - st.common.opacity, - flags, - clip, - photocraft_compose::stroke_frame(self.cx.doc, layer, st).unwrap_or(sb), - ); - if matches!(paint, Paint::None) { - // A missing pattern paints nothing: the stroke's share keeps the result as is. - p.params[2][2] = 3.0; - } - p.adjust_kind = 0; - p.map = Some(map(i, 0)); - p.c = cover.map(|c| self.retain(c)); - p.d = acc; - let a = self.emit(p); - // The stroke's mode rides along only for Dissolve, whose coverage is all or - // nothing in this pass as in the colour pass (#6995). - let mut p = self.fx_pass_kernel(Kernel::FxStroke, w, content, &Paint::Color([0.0; 3]), st.common.blend, st.common.opacity, flags, clip, sb); - p.adjust_kind = 1; - p.map = Some(map(i, 0)); - p.c = cover; - cover = Some(self.emit(p)); - acc = Some(a); - } - let mut p = Pass::new(Kernel::FxStrokeEnd, 0); - p.a = Some(w); - p.b = acc; - p.c = cover; - p.clip = Some(clip); - w = self.emit(p); - } - for &(i, e) in &rev { - if let Effect::BevelEmboss(b) = e - && bevel_paint(b) == photocraft_compose::effects::BevelPaint::Outer - { - let k = 0; - w = self.paint( - w, - content, - Cov::Map(map(i, k), 0.0), - &Paint::Color(b.highlight_color.to_rgb()), - b.highlight.blend, - b.highlight.opacity, - 0, - clip, - sb, - ); - w = self.paint(w, content, Cov::Map(map(i, k + 1), 0.0), &Paint::Color(b.shadow_color.to_rgb()), b.shadow.blend, b.shadow.opacity, 0, clip, sb); - } - } - - let mode = if premerge || layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; - let late: Vec<(usize, &'a photocraft_doc::Bevel)> = rev - .iter() - .filter_map(|&(i, e)| if let Effect::BevelEmboss(b) = e { Some((i, b)) } else { None }) - .filter(|(_, b)| bevel_paint(b) == photocraft_compose::effects::BevelPaint::Both) - .collect(); - let merged = if late.is_empty() { - let mut p = Pass::new(Kernel::FxMerge, 0); - p.a = Some(w); - p.b = Some(l); - p.c = Some(self.retain(backdrop)); - p.mode = mode; - p.opacity = layer.opacity; - p.flags = if atop { F_ATOP } else { 0 } | gamma_flag(layer); - p.extra[3] = photocraft_compose::text_gamma(layer); - p.clip = Some(clip); - self.emit(p) - } else { - // Emboss styles shade the composited layer (`composite_with_effects`): merge at full - // opacity, paint their maps (inside and outside halves), then mix. - let mut p = Pass::new(Kernel::FxMerge, 0); - p.a = Some(w); - p.b = Some(l); - p.c = Some(self.retain(w)); - p.mode = mode; - p.opacity = 1.0; - p.flags = gamma_flag(layer); - p.extra[3] = photocraft_compose::text_gamma(layer); - p.clip = Some(clip); - let mut m = self.emit(p); - for (i, b) in late { - for (k, color, fxc) in [(0, &b.highlight_color, &b.highlight), (1, &b.shadow_color, &b.shadow)] { - m = self.paint(m, content, Cov::Map(map(i, k), 0.0), &Paint::Color(color.to_rgb()), fxc.blend, fxc.opacity, 0, clip, sb); - } - } - let mut p = Pass::new(Kernel::FxMerge, 0); - p.b = Some(self.retain(m)); - p.a = Some(m); - p.c = Some(self.retain(backdrop)); - p.mode = mode; - p.opacity = layer.opacity; - p.flags = if atop { F_ATOP } else { 0 } | F_NO_LAYER; - p.clip = Some(clip); - self.emit(p) - }; - self.release(content); - - // Write the clipped result back into the backdrop (in place when nothing else holds it). - Ok(self.write_back(backdrop, merged, clip)) - } - - fn fx_paint(&self, p: &'a FxPaint, anchor: (f64, f64)) -> Paint<'a> { - match p { - FxPaint::Color(c) => Paint::Color(c.to_rgb()), - FxPaint::Gradient(g) => Paint::Gradient(g), - FxPaint::Pattern { name, id, scale } => match photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) { - Some(pat) => Paint::Pattern(pat, placement(anchor, true, (0.0, 0.0), *scale, 0.0)), - None => Paint::None, - }, - } - } - - fn glow_paint(&self, g: &'a Glow, anchor: (f64, f64)) -> Paint<'a> { - match &g.paint { - FxPaint::Gradient(gradient) => Paint::GlowGradient(gradient, photocraft_compose::effects::glow_gradient_gain(g.range)), - p => self.fx_paint(p, anchor), - } - } - - /// An effect pass reading `dst` (A, retained) and the layer `content` (B, retained) with its - /// paint set up. - #[allow(clippy::too_many_arguments)] - fn fx_pass(&mut self, dst: Slot, content: Slot, paint: &Paint<'a>, blend: BlendMode, opacity: f32, flags: u32, clip: Rect, sb: Rect) -> Pass<'a> { - self.fx_pass_kernel(Kernel::FxPaint, dst, content, paint, blend, opacity, flags, clip, sb) - } - - #[allow(clippy::too_many_arguments)] - fn fx_pass_kernel( - &mut self, - kernel: Kernel, - dst: Slot, - content: Slot, - paint: &Paint<'a>, - blend: BlendMode, - opacity: f32, - flags: u32, - clip: Rect, - sb: Rect, - ) -> Pass<'a> { - let mut p = Pass::new(kernel, 0); - p.a = Some(self.retain(dst)); - p.b = Some(self.retain(content)); - p.mode = blend; - p.opacity = opacity; - p.flags = flags; - p.clip = Some(clip); - match paint { - Paint::None => {} - Paint::Color(c) => p.color = [c[0], c[1], c[2], 1.0], - Paint::Gradient(g) => { - // effects::paint_fx: whole-pixel end points (fill_layout::gradient_layout). - let (angle, scale, offset) = photocraft_compose::fill_layout::gradient_layout(g.style, g.angle, g.scale, g.offset, sb); - p.params[0] = [angle, scale, if g.reverse { 1.0 } else { 0.0 }, style_index(g.style)]; - p.params[1] = [sb.x0 as f32, sb.y0 as f32, sb.width() as f32, sb.height() as f32]; - p.params[2][0] = offset.0; - p.params[2][1] = offset.1; - p.params[2][2] = 1.0; - p.lut = Some(gradient_rows(g)); - } - Paint::GlowGradient(g, gain) => { - // effects::paint_glow: the gradient at 1 - strength, opaque from 1 / gain. - p.params[0][0] = *gain; - p.params[2][2] = 4.0; - p.lut = Some(gradient_rows(g)); - } - Paint::Pattern(pat, pl) => { - p.params[2][2] = 2.0; - p.params[3] = [pl.origin.0 as f32, pl.origin.1 as f32, pl.cs.0 as f32, pl.cs.1 as f32]; - p.extra = [pl.inv_scale as f32, pat.width as f32, pat.height as f32, 0.0]; - p.pattern = Some(pat); - } - } - p - } - - /// One effect paint into `dst` (consumed); reads the layer's alpha from `content` (kept). - #[allow(clippy::too_many_arguments)] - fn paint(&mut self, dst: Slot, content: Slot, cov: Cov, paint: &Paint<'a>, blend: BlendMode, opacity: f32, flags: u32, clip: Rect, sb: Rect) -> Slot { - self.paint_k(dst, content, cov, paint, blend, opacity, flags, clip, sb, 1.0) - } - - /// [`Self::paint`] with the knockout strength (`F_KNOCKOUT`: coverage × (1 − alpha × k)). - #[allow(clippy::too_many_arguments)] - fn paint_k( - &mut self, - dst: Slot, - content: Slot, - cov: Cov, - paint: &Paint<'a>, - blend: BlendMode, - opacity: f32, - flags: u32, - clip: Rect, - sb: Rect, - knockout: f32, - ) -> Slot { - if matches!(paint, Paint::None) { - // Missing pattern: compose paints nothing. - return dst; - } - let mut p = self.fx_pass(dst, content, paint, blend, opacity, flags, clip, sb); - self.release(dst); - match cov { - Cov::Map(m, outside) => { - p.adjust_kind = 0; - p.map = Some(m); - p.params[2][3] = outside; - } - Cov::One => p.adjust_kind = 1, - } - p.extra[3] = knockout; - self.emit(p) - } -} - -/// Paint source of an effect. -enum Paint<'a> { - None, - Color([f32; 3]), - Gradient(&'a Gradient), - /// A glow's gradient with its opacity gain (`effects::paint_glow`). - GlowGradient(&'a Gradient, f32), - Pattern(&'a Pattern, Placement), -} - -/// `compose::pattern::Placement` (origin, inverse rotation, inverse scale). -#[derive(Clone, Copy, Debug)] -struct Placement { - origin: (f64, f64), - cs: (f64, f64), - inv_scale: f64, -} - -/// `Placement::anchored`: linked patterns tile from `anchor` (the effects reference point). -fn placement(anchor: (f64, f64), link: bool, phase: (f32, f32), scale: f32, angle: f32) -> Placement { - let base = if link { anchor } else { (0.0, 0.0) }; - let origin = (base.0 + f64::from(phase.0), base.1 + f64::from(phase.1)); - let s = f64::from(scale); - let inv_scale = if s.is_finite() && s > 1e-3 { 1.0 / s } else { 1.0 }; - let a = f64::from(angle).to_radians(); - Placement { origin, cs: (a.cos(), a.sin()), inv_scale } -} - -/// (inside width, outside width) of a stroke. -pub fn stroke_widths(st: &photocraft_doc::StrokeFx) -> (f32, f32) { - match st.position { - StrokePosition::Outside => (0.0, st.size), - StrokePosition::Inside => (st.size, 0.0), - StrokePosition::Center => (st.size / 2.0, st.size / 2.0), - } -} - -fn style_index(s: photocraft_doc::GradientStyle) -> f32 { - match s { - photocraft_doc::GradientStyle::Linear => 0.0, - photocraft_doc::GradientStyle::Radial => 1.0, - photocraft_doc::GradientStyle::Angle => 2.0, - photocraft_doc::GradientStyle::Reflected => 3.0, - photocraft_doc::GradientStyle::Diamond => 4.0, - } -} - -fn sample_stops4(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] { - match stops { - [] => [0.0; 4], - [only] => only.1, - _ => { - if t <= stops[0].0 { - return stops[0].1; - } - for w in stops.windows(2) { - let (a, b) = (&w[0], &w[1]); - if t <= b.0 { - let k = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 }; - return std::array::from_fn(|i| a.1[i] + (b.1[i] - a.1[i]) * k); - } - } - stops[stops.len() - 1].1 - } - } -} - -fn lut_rows(f: impl Fn(usize, f32) -> f32, rows: usize) -> Vec<[f32; 4096]> { - (0..rows) - .map(|r| { - let mut row = [0.0f32; 4096]; - for (k, v) in row.iter_mut().enumerate() { - *v = f(r, k as f32 / 4095.0); - } - row - }) - .collect() -} - -type Program = (i32, [[f32; 4]; 4], Option>); - -/// A CPU LUT (4096 entries) as one texture row. -fn to_row(t: &[f32]) -> [f32; 4096] { - let mut row = [0.0f32; 4096]; - for (o, v) in row.iter_mut().zip(t) { - *o = *v; - } - row -} - -/// Whether the adjustment kernel can evaluate `adj` in a document of colour `mode`: Levels and -/// Curves on CMYK ink or Lab channels convert through ICC profiles per pixel, and so do the -/// adjustments a Lab document evaluates on L, a and b (`photocraft_compose::adjust::lab_channel_adjustment`) -/// and a CMYK document on its inks (`cmyk_channel_adjustment`), which only the CPU does. -pub fn adjustment_on_gpu(adj: &Adjustment, mode: photocraft_color::ColorMode) -> bool { - use photocraft_compose::adjust::{cmyk_channel_adjustment, lab_channel_adjustment}; - let tone_in_space = - matches!(adj, Adjustment::Levels { space: ToneSpace::Cmyk | ToneSpace::Lab, .. } | Adjustment::Curves { space: ToneSpace::Cmyk | ToneSpace::Lab, .. }); - let own_channels = match mode { - photocraft_color::ColorMode::Lab => lab_channel_adjustment(adj), - photocraft_color::ColorMode::Cmyk => cmyk_channel_adjustment(adj), - _ => false, - }; - !tone_in_space && !own_channels -} - -/// A tone transfer as the shader's `t_decode`/`t_encode` exponent (0: the sRGB curve). -fn transfer_exponent(t: Transfer) -> f32 { - match t { - Transfer::Srgb => 0.0, - Transfer::Gamma(g) => g, - } -} - -/// Adjustment → (kernel kind, parameters, LUT rows). Kinds are the `switch` in `adjust()`. -pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraft_color::SampleType, mode: photocraft_color::ColorMode) -> Program { - let mut p = [[0.0f32; 4]; 4]; - match adj { - Adjustment::Invert => (1, p, None), - Adjustment::Threshold { level } => { - // The level, the depth's split (compose::adjust::threshold_white) and the level in 16 bits. - let t = (level * 255.0).round(); - p[0] = match depth { - photocraft_color::SampleType::U8 => [t, 1.0, 0.0, 0.0], - photocraft_color::SampleType::U16 => [t, 2.0, (t * 32768.0 / 255.0).round(), 0.0], - photocraft_color::SampleType::F32 => [t, 0.0, 0.0, 0.0], - }; - (2, p, None) - } - Adjustment::Posterize { levels } => { - // The levels, and the 16-bit rule (compose::adjust::posterize_in). - p[0][0] = (*levels).clamp(2, 255) as f32; - p[0][1] = if depth == photocraft_color::SampleType::U16 { 1.0 } else { 0.0 }; - (3, p, None) - } - Adjustment::BrightnessContrast { brightness, contrast, legacy: true } => { - let c = contrast.clamp(-100.0, 99.0); - let k = if c >= 0.0 { 1.0 / (1.0 - c / 100.0) } else { 1.0 + c / 100.0 }; - // Brightness before contrast when it is raised, after it when lowered (compose::adjust). - let (pre, post) = if c >= 0.0 { (brightness / 255.0, 0.0) } else { (0.0, brightness / 255.0) }; - // 32-bit documents pivot at 127 of 255 and don't clip (the shader checks F_HDR). - let pivot = if depth == photocraft_color::SampleType::F32 { 127.0 / 255.0 } else { photocraft_compose::adjust::LEGACY_PIVOT }; - p[0] = [pre, k, pivot, post]; - (4, p, None) - } - Adjustment::BrightnessContrast { brightness, contrast, .. } => { - // Modern B/C: the CPU's lookup table (compose::adjust::modern_lut) on every channel, - // through the Levels / Curves kernel. - let row = to_row(&adjust::modern_lut(*brightness, *contrast)); - (7, p, Some(vec![row; 3])) - } - Adjustment::Exposure { exposure, offset, gamma } => { - p[0] = [2f32.powf(*exposure), *offset, gamma.max(0.01), transfer_exponent(transfer.for_exposure())]; - (6, p, None) - } - Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, .. } if depth == photocraft_color::SampleType::F32 => { - // Twenty coefficients exceed the sixteen uniform parameters. Store four records - // in LUT row 0, read texel-exact by the analytic float Levels kernel. - let mut row = [0.0f32; 4096]; - for (i, ch) in std::iter::once(master).chain(per_channel).enumerate() { - let coefficients = [ch.in_black, ch.in_white, ch.gamma.max(0.01), ch.out_black, ch.out_white]; - row[i * 5..i * 5 + 5].copy_from_slice(&coefficients); - } - (17, p, Some(vec![row])) - } - // RGB space only (see `adjustment_on_gpu`); the rows are the CPU's channel∘master LUTs. - Adjustment::Levels { .. } | Adjustment::Curves { .. } => { - for (v, identity) in p[0].iter_mut().zip(adjust::float_tone_identity(adj, Some(depth))) { - *v = if identity { 1.0 } else { 0.0 }; - } - // p0.w: continue the curve past 0..1 (32-bit RGB Curves, #7157). - p[0][3] = if adjust::float_tone_extrapolates(adj, Some(depth), mode) { 1.0 } else { 0.0 }; - (7, p, Some(adjust::tone_luts_depth(adj, Some(depth)).iter().take(3).map(|t| to_row(t)).collect())) - } - Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges } => { - let sat = adjust::colorize_saturation(saturation / 100.0, lightness / 100.0, *colorize, Some(depth)); - p[0] = [*hue, sat, lightness / 100.0, if *colorize { 1.0 } else { 0.0 }]; - if !*colorize && ranges.iter().any(|r| !r.is_neutral()) { - // Range edits: hue-indexed rows (shift, saturation, lightness), as on the CPU. - p[1][0] = 1.0; - (8, p, Some(adjust::hue_range_tables(ranges).iter().map(|t| to_row(t)).collect())) - } else { - (8, p, None) - } - } - Adjustment::Vibrance { vibrance, saturation } => { - // compose::adjust::vibrance_px; 32-bit samples aren't clipped at 1. - let hi = if depth == photocraft_color::SampleType::F32 { f32::MAX } else { 1.0 }; - p[0] = [vibrance / 100.0, saturation / 100.0, transfer_exponent(transfer), hi]; - let b = adjust::VIBRANCE_BOOST; - p[1] = [b[0], b[1], b[2], b[3]]; - p[2] = [b[4], b[5], b[6], 0.0]; - (9, p, None) - } - Adjustment::ChannelMixer { matrix, monochrome } => { - // compose::adjust: 32-bit documents cut each percentage to 1/1024, count 255/512 of - // the constant and don't clip (the shader checks F_HDR). - let hdr = depth == photocraft_color::SampleType::F32; - let cut = |v: f32| if hdr { (v * 1024.0).trunc() / 1024.0 } else { v }; - let rows = matrix.map(|r| [cut(r[0]), cut(r[1]), cut(r[2]), if hdr { r[3] * 255.0 / 512.0 } else { r[3] }]); - p[0] = rows[0]; - p[1] = rows[1]; - p[2] = rows[2]; - p[3][0] = if *monochrome { 1.0 } else { 0.0 }; - (10, p, None) - } - Adjustment::PhotoFilter { color, density, preserve_luminosity } => { - // compose::adjust: the linear-light matrix, then SetLum on the encoded values (8/16-bit). - let linear_doc = depth == photocraft_color::SampleType::F32; - let m = adjust::photo_filter_matrix(*color, *density, *preserve_luminosity && linear_doc); - for (row, m) in p.iter_mut().zip(m) { - *row = [m[0], m[1], m[2], 0.0]; - } - p[3] = [if *preserve_luminosity && !linear_doc { 1.0 } else { 0.0 }, transfer_exponent(transfer), 0.0, 0.0]; - (11, p, None) - } - Adjustment::BlackWhite { weights, tint } => { - p[0] = [weights[0], weights[1], weights[2], weights[3]]; - p[1] = [weights[4], weights[5], if tint.is_some() { 1.0 } else { 0.0 }, 0.0]; - if let Some(t) = tint { - p[2] = [t[0], t[1], t[2], 0.0]; - } - (12, p, None) - } - Adjustment::GradientMap { stops, reverse, dither } => { - p[0][0] = if *reverse { 1.0 } else { 0.0 }; - p[0][1] = if *dither { 1.0 } else { 0.0 }; - let s4: Vec<(f32, [f32; 4])> = stops.iter().map(|(t, c)| (*t, [c[0], c[1], c[2], 1.0])).collect(); - let rows = lut_rows(|r, t| if s4.is_empty() { t } else { sample_stops4(&s4, t)[r] }, 3); - (13, p, Some(rows)) - } - Adjustment::ColorBalance { shadows, midtones, highlights, preserve_luminosity } => { - // Per-channel curves (compose::adjust::BalanceCurve), through the Levels kernel. - let curves = adjust::BalanceCurve::rgb([*shadows, *midtones, *highlights], *preserve_luminosity); - (7, p, Some(lut_rows(|ch, v| curves[ch].eval(v), 3))) - } - Adjustment::SelectiveColor { relative, adjustments } => { - // 9 ranges × CMYK don't fit the 16 params: they go in LUT row 0 (read texel-exact). - p[0][0] = if *relative { 1.0 } else { 0.0 }; - let mut row = [0.0f32; 4096]; - for (i, v) in adjustments.iter().flatten().enumerate() { - row[i] = *v; - } - (15, p, Some(vec![row])) - } - Adjustment::ColorLookup { lut: Some(table), size, tetrahedral, dither, .. } if lut3d_len(*size).is_some_and(|len| table.len() >= len) => { - // The flattened table (n³ RGB triplets) spans as many 4096-wide rows as it needs. - let n = *size as usize; - let rows = lut3d_len(*size) - .and_then(|len| table.get(..len)) - .unwrap_or_default() - .chunks(4096) - .map(|c| { - let mut row = [0.0f32; 4096]; - row[..c.len()].copy_from_slice(c); - row - }) - .collect(); - p[0] = [n as f32, if *tetrahedral { 1.0 } else { 0.0 }, if *dither { 1.0 } else { 0.0 }, 0.0]; - (16, p, Some(rows)) - } - // Identity on the CPU too (not evaluated there). - Adjustment::ColorLookup { .. } | Adjustment::Unsupported { .. } => (0, p, None), - } -} - -/// A gradient's colour and alpha as four 4096-entry LUT rows (`lut_tex`). -fn gradient_rows(g: &Gradient) -> Vec<[f32; 4096]> { - let mut rows = vec![[0.0f32; 4096]; 4]; - for k in 0..4096 { - let v = photocraft_compose::effects::sample_gradient(g, k as f32 / 4095.0); - for (ch, row) in rows.iter_mut().enumerate() { - row[k] = v[ch]; - } - } - rows -} - -/// Linear interpolation between LUT entries cannot preserve a discontinuity. Let the canvas -/// use the CPU oracle for coincident stops, including opacity stops and unsorted fill ramps -/// (which `gradient_fill::Ramp` sorts). Check only ramps we will sample: cached fills and -/// disabled effects can still use the GPU. -fn check_gradient_stops(stops: &[(f32, T)]) -> Result<(), Unsupported> { - let mut positions: Vec = stops.iter().map(|s| s.0).collect(); - positions.sort_by(f32::total_cmp); - // A 4096-entry LUT cannot keep two stops that fall in the same entry apart (#3053). - if positions.windows(2).any(|w| (w[1] - w[0]).abs() < 1.0 / 4095.0) { - return Err(Unsupported("coincident gradient stops (composited on the CPU)".into())); - } - Ok(()) -} - -/// Mode index used by the shader (declaration order of [`BlendMode`]). -pub fn mode_index(m: BlendMode) -> i32 { - match m { - BlendMode::PassThrough => 0, - BlendMode::Normal => 1, - BlendMode::Dissolve => 2, - BlendMode::Darken => 3, - BlendMode::Multiply => 4, - BlendMode::ColorBurn => 5, - BlendMode::LinearBurn => 6, - BlendMode::DarkerColor => 7, - BlendMode::Lighten => 8, - BlendMode::Screen => 9, - BlendMode::ColorDodge => 10, - BlendMode::LinearDodge => 11, - BlendMode::LighterColor => 12, - BlendMode::Overlay => 13, - BlendMode::SoftLight => 14, - BlendMode::HardLight => 15, - BlendMode::VividLight => 16, - BlendMode::LinearLight => 17, - BlendMode::PinLight => 18, - BlendMode::HardMix => 19, - BlendMode::Difference => 20, - BlendMode::Exclusion => 21, - BlendMode::Subtract => 22, - BlendMode::Divide => 23, - BlendMode::Hue => 24, - BlendMode::Saturation => 25, - BlendMode::Color => 26, - BlendMode::Luminosity => 27, - BlendMode::Reflect => 28, - BlendMode::Glow => 29, - BlendMode::Negation => 30, - BlendMode::Xor => 31, - BlendMode::PaintNetColorBurn => 32, - BlendMode::PaintNetColorDodge => 33, - } -} - -/// Whether `Planner::content` draws `layer` as one `Planner::content_pass`: not a group's stack, -/// an adjustment, or a pattern fill painted in passes. -fn single_content_pass(layer: &Layer) -> bool { - match &layer.content { - LayerContent::Group(_) | LayerContent::Adjustment(_) => false, - LayerContent::Fill(f @ Fill::Pattern { .. }) => layer.fill_cache.as_ref().is_some_and(|c| c.fill == *f), - _ => true, - } -} - #[cfg(test)] mod tests; diff --git a/crates/gpu/src/plan/lower.rs b/crates/gpu/src/plan/lower.rs new file mode 100644 index 0000000000..42dd17e099 --- /dev/null +++ b/crates/gpu/src/plan/lower.rs @@ -0,0 +1,344 @@ +use super::types::Unsupported; +use super::*; + +/// Paint source of an effect. +pub(super) enum Paint<'a> { + None, + Color([f32; 3]), + Gradient(&'a Gradient), + /// A glow's gradient with its opacity gain (`effects::paint_glow`). + GlowGradient(&'a Gradient, f32), + Pattern(&'a Pattern, Placement), +} + +/// `compose::pattern::Placement` (origin, inverse rotation, inverse scale). +#[derive(Clone, Copy, Debug)] +pub(super) struct Placement { + pub(super) origin: (f64, f64), + pub(super) cs: (f64, f64), + pub(super) inv_scale: f64, +} + +/// `Placement::anchored`: linked patterns tile from `anchor` (the effects reference point). +pub(super) fn placement(anchor: (f64, f64), link: bool, phase: (f32, f32), scale: f32, angle: f32) -> Placement { + let base = if link { anchor } else { (0.0, 0.0) }; + let origin = (base.0 + f64::from(phase.0), base.1 + f64::from(phase.1)); + let s = f64::from(scale); + let inv_scale = if s.is_finite() && s > 1e-3 { 1.0 / s } else { 1.0 }; + let a = f64::from(angle).to_radians(); + Placement { origin, cs: (a.cos(), a.sin()), inv_scale } +} + +/// (inside width, outside width) of a stroke. +pub fn stroke_widths(st: &photocraft_doc::StrokeFx) -> (f32, f32) { + match st.position { + StrokePosition::Outside => (0.0, st.size), + StrokePosition::Inside => (st.size, 0.0), + StrokePosition::Center => (st.size / 2.0, st.size / 2.0), + } +} + +pub(super) fn style_index(s: photocraft_doc::GradientStyle) -> f32 { + match s { + photocraft_doc::GradientStyle::Linear => 0.0, + photocraft_doc::GradientStyle::Radial => 1.0, + photocraft_doc::GradientStyle::Angle => 2.0, + photocraft_doc::GradientStyle::Reflected => 3.0, + photocraft_doc::GradientStyle::Diamond => 4.0, + } +} + +fn sample_stops4(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] { + match stops { + [] => [0.0; 4], + [only] => only.1, + _ => { + if t <= stops[0].0 { + return stops[0].1; + } + for w in stops.windows(2) { + let (a, b) = (&w[0], &w[1]); + if t <= b.0 { + let k = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 }; + return std::array::from_fn(|i| a.1[i] + (b.1[i] - a.1[i]) * k); + } + } + stops[stops.len() - 1].1 + } + } +} + +fn lut_rows(f: impl Fn(usize, f32) -> f32, rows: usize) -> Vec<[f32; 4096]> { + (0..rows) + .map(|r| { + let mut row = [0.0f32; 4096]; + for (k, v) in row.iter_mut().enumerate() { + *v = f(r, k as f32 / 4095.0); + } + row + }) + .collect() +} + +type Program = (i32, [[f32; 4]; 4], Option>); + +/// A CPU LUT (4096 entries) as one texture row. +fn to_row(t: &[f32]) -> [f32; 4096] { + let mut row = [0.0f32; 4096]; + for (o, v) in row.iter_mut().zip(t) { + *o = *v; + } + row +} + +/// Whether the adjustment kernel can evaluate `adj` in a document of colour `mode`: Levels and +/// Curves on CMYK ink or Lab channels convert through ICC profiles per pixel, and so do the +/// adjustments a Lab document evaluates on L, a and b (`photocraft_compose::adjust::lab_channel_adjustment`) +/// and a CMYK document on its inks (`cmyk_channel_adjustment`), which only the CPU does. +pub fn adjustment_on_gpu(adj: &Adjustment, mode: photocraft_color::ColorMode) -> bool { + use photocraft_compose::adjust::{cmyk_channel_adjustment, lab_channel_adjustment}; + let tone_in_space = + matches!(adj, Adjustment::Levels { space: ToneSpace::Cmyk | ToneSpace::Lab, .. } | Adjustment::Curves { space: ToneSpace::Cmyk | ToneSpace::Lab, .. }); + let own_channels = match mode { + photocraft_color::ColorMode::Lab => lab_channel_adjustment(adj), + photocraft_color::ColorMode::Cmyk => cmyk_channel_adjustment(adj), + _ => false, + }; + !tone_in_space && !own_channels +} + +/// A tone transfer as the shader's `t_decode`/`t_encode` exponent (0: the sRGB curve). +fn transfer_exponent(t: Transfer) -> f32 { + match t { + Transfer::Srgb => 0.0, + Transfer::Gamma(g) => g, + } +} + +/// Adjustment → (kernel kind, parameters, LUT rows). Kinds are the `switch` in `adjust()`. +pub fn adjustment_program(adj: &Adjustment, transfer: Transfer, depth: photocraft_color::SampleType, mode: photocraft_color::ColorMode) -> Program { + let mut p = [[0.0f32; 4]; 4]; + match adj { + Adjustment::Invert => (1, p, None), + Adjustment::Threshold { level } => { + // The level, the depth's split (compose::adjust::threshold_white) and the level in 16 bits. + let t = (level * 255.0).round(); + p[0] = match depth { + photocraft_color::SampleType::U8 => [t, 1.0, 0.0, 0.0], + photocraft_color::SampleType::U16 => [t, 2.0, (t * 32768.0 / 255.0).round(), 0.0], + photocraft_color::SampleType::F32 => [t, 0.0, 0.0, 0.0], + }; + (2, p, None) + } + Adjustment::Posterize { levels } => { + // The levels, and the 16-bit rule (compose::adjust::posterize_in). + p[0][0] = (*levels).clamp(2, 255) as f32; + p[0][1] = if depth == photocraft_color::SampleType::U16 { 1.0 } else { 0.0 }; + (3, p, None) + } + Adjustment::BrightnessContrast { brightness, contrast, legacy: true } => { + let c = contrast.clamp(-100.0, 99.0); + let k = if c >= 0.0 { 1.0 / (1.0 - c / 100.0) } else { 1.0 + c / 100.0 }; + // Brightness before contrast when it is raised, after it when lowered (compose::adjust). + let (pre, post) = if c >= 0.0 { (brightness / 255.0, 0.0) } else { (0.0, brightness / 255.0) }; + // 32-bit documents pivot at 127 of 255 and don't clip (the shader checks F_HDR). + let pivot = if depth == photocraft_color::SampleType::F32 { 127.0 / 255.0 } else { photocraft_compose::adjust::LEGACY_PIVOT }; + p[0] = [pre, k, pivot, post]; + (4, p, None) + } + Adjustment::BrightnessContrast { brightness, contrast, .. } => { + // Modern B/C: the CPU's lookup table (compose::adjust::modern_lut) on every channel, + // through the Levels / Curves kernel. + let row = to_row(&adjust::modern_lut(*brightness, *contrast)); + (7, p, Some(vec![row; 3])) + } + Adjustment::Exposure { exposure, offset, gamma } => { + p[0] = [2f32.powf(*exposure), *offset, gamma.max(0.01), transfer_exponent(transfer.for_exposure())]; + (6, p, None) + } + Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, .. } if depth == photocraft_color::SampleType::F32 => { + // Twenty coefficients exceed the sixteen uniform parameters. Store four records + // in LUT row 0, read texel-exact by the analytic float Levels kernel. + let mut row = [0.0f32; 4096]; + for (i, ch) in std::iter::once(master).chain(per_channel).enumerate() { + let coefficients = [ch.in_black, ch.in_white, ch.gamma.max(0.01), ch.out_black, ch.out_white]; + row[i * 5..i * 5 + 5].copy_from_slice(&coefficients); + } + (17, p, Some(vec![row])) + } + // RGB space only (see `adjustment_on_gpu`); the rows are the CPU's channel∘master LUTs. + Adjustment::Levels { .. } | Adjustment::Curves { .. } => { + for (v, identity) in p[0].iter_mut().zip(adjust::float_tone_identity(adj, Some(depth))) { + *v = if identity { 1.0 } else { 0.0 }; + } + // p0.w: continue the curve past 0..1 (32-bit RGB Curves, #7157). + p[0][3] = if adjust::float_tone_extrapolates(adj, Some(depth), mode) { 1.0 } else { 0.0 }; + (7, p, Some(adjust::tone_luts_depth(adj, Some(depth)).iter().take(3).map(|t| to_row(t)).collect())) + } + Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges } => { + let sat = adjust::colorize_saturation(saturation / 100.0, lightness / 100.0, *colorize, Some(depth)); + p[0] = [*hue, sat, lightness / 100.0, if *colorize { 1.0 } else { 0.0 }]; + if !*colorize && ranges.iter().any(|r| !r.is_neutral()) { + // Range edits: hue-indexed rows (shift, saturation, lightness), as on the CPU. + p[1][0] = 1.0; + (8, p, Some(adjust::hue_range_tables(ranges).iter().map(|t| to_row(t)).collect())) + } else { + (8, p, None) + } + } + Adjustment::Vibrance { vibrance, saturation } => { + // compose::adjust::vibrance_px; 32-bit samples aren't clipped at 1. + let hi = if depth == photocraft_color::SampleType::F32 { f32::MAX } else { 1.0 }; + p[0] = [vibrance / 100.0, saturation / 100.0, transfer_exponent(transfer), hi]; + let b = adjust::VIBRANCE_BOOST; + p[1] = [b[0], b[1], b[2], b[3]]; + p[2] = [b[4], b[5], b[6], 0.0]; + (9, p, None) + } + Adjustment::ChannelMixer { matrix, monochrome } => { + // compose::adjust: 32-bit documents cut each percentage to 1/1024, count 255/512 of + // the constant and don't clip (the shader checks F_HDR). + let hdr = depth == photocraft_color::SampleType::F32; + let cut = |v: f32| if hdr { (v * 1024.0).trunc() / 1024.0 } else { v }; + let rows = matrix.map(|r| [cut(r[0]), cut(r[1]), cut(r[2]), if hdr { r[3] * 255.0 / 512.0 } else { r[3] }]); + p[0] = rows[0]; + p[1] = rows[1]; + p[2] = rows[2]; + p[3][0] = if *monochrome { 1.0 } else { 0.0 }; + (10, p, None) + } + Adjustment::PhotoFilter { color, density, preserve_luminosity } => { + // compose::adjust: the linear-light matrix, then SetLum on the encoded values (8/16-bit). + let linear_doc = depth == photocraft_color::SampleType::F32; + let m = adjust::photo_filter_matrix(*color, *density, *preserve_luminosity && linear_doc); + for (row, m) in p.iter_mut().zip(m) { + *row = [m[0], m[1], m[2], 0.0]; + } + p[3] = [if *preserve_luminosity && !linear_doc { 1.0 } else { 0.0 }, transfer_exponent(transfer), 0.0, 0.0]; + (11, p, None) + } + Adjustment::BlackWhite { weights, tint } => { + p[0] = [weights[0], weights[1], weights[2], weights[3]]; + p[1] = [weights[4], weights[5], if tint.is_some() { 1.0 } else { 0.0 }, 0.0]; + if let Some(t) = tint { + p[2] = [t[0], t[1], t[2], 0.0]; + } + (12, p, None) + } + Adjustment::GradientMap { stops, reverse, dither } => { + p[0][0] = if *reverse { 1.0 } else { 0.0 }; + p[0][1] = if *dither { 1.0 } else { 0.0 }; + let s4: Vec<(f32, [f32; 4])> = stops.iter().map(|(t, c)| (*t, [c[0], c[1], c[2], 1.0])).collect(); + let rows = lut_rows(|r, t| if s4.is_empty() { t } else { sample_stops4(&s4, t)[r] }, 3); + (13, p, Some(rows)) + } + Adjustment::ColorBalance { shadows, midtones, highlights, preserve_luminosity } => { + // Per-channel curves (compose::adjust::BalanceCurve), through the Levels kernel. + let curves = adjust::BalanceCurve::rgb([*shadows, *midtones, *highlights], *preserve_luminosity); + (7, p, Some(lut_rows(|ch, v| curves[ch].eval(v), 3))) + } + Adjustment::SelectiveColor { relative, adjustments } => { + // 9 ranges × CMYK don't fit the 16 params: they go in LUT row 0 (read texel-exact). + p[0][0] = if *relative { 1.0 } else { 0.0 }; + let mut row = [0.0f32; 4096]; + for (i, v) in adjustments.iter().flatten().enumerate() { + row[i] = *v; + } + (15, p, Some(vec![row])) + } + Adjustment::ColorLookup { lut: Some(table), size, tetrahedral, dither, .. } if lut3d_len(*size).is_some_and(|len| table.len() >= len) => { + // The flattened table (n³ RGB triplets) spans as many 4096-wide rows as it needs. + let n = *size as usize; + let rows = lut3d_len(*size) + .and_then(|len| table.get(..len)) + .unwrap_or_default() + .chunks(4096) + .map(|c| { + let mut row = [0.0f32; 4096]; + row[..c.len()].copy_from_slice(c); + row + }) + .collect(); + p[0] = [n as f32, if *tetrahedral { 1.0 } else { 0.0 }, if *dither { 1.0 } else { 0.0 }, 0.0]; + (16, p, Some(rows)) + } + // Identity on the CPU too (not evaluated there). + Adjustment::ColorLookup { .. } | Adjustment::Unsupported { .. } => (0, p, None), + } +} + +/// A gradient's colour and alpha as four 4096-entry LUT rows (`lut_tex`). +pub(super) fn gradient_rows(g: &Gradient) -> Vec<[f32; 4096]> { + let mut rows = vec![[0.0f32; 4096]; 4]; + for k in 0..4096 { + let v = photocraft_compose::effects::sample_gradient(g, k as f32 / 4095.0); + for (ch, row) in rows.iter_mut().enumerate() { + row[k] = v[ch]; + } + } + rows +} + +/// Linear interpolation between LUT entries cannot preserve a discontinuity. Let the canvas +/// use the CPU oracle for coincident stops, including opacity stops and unsorted fill ramps +/// (which `gradient_fill::Ramp` sorts). Check only ramps we will sample: cached fills and +/// disabled effects can still use the GPU. +pub(super) fn check_gradient_stops(stops: &[(f32, T)]) -> Result<(), Unsupported> { + let mut positions: Vec = stops.iter().map(|s| s.0).collect(); + positions.sort_by(f32::total_cmp); + // A 4096-entry LUT cannot keep two stops that fall in the same entry apart (#3053). + if positions.windows(2).any(|w| (w[1] - w[0]).abs() < 1.0 / 4095.0) { + return Err(Unsupported("coincident gradient stops (composited on the CPU)".into())); + } + Ok(()) +} + +/// Mode index used by the shader (declaration order of [`BlendMode`]). +pub fn mode_index(m: BlendMode) -> i32 { + match m { + BlendMode::PassThrough => 0, + BlendMode::Normal => 1, + BlendMode::Dissolve => 2, + BlendMode::Darken => 3, + BlendMode::Multiply => 4, + BlendMode::ColorBurn => 5, + BlendMode::LinearBurn => 6, + BlendMode::DarkerColor => 7, + BlendMode::Lighten => 8, + BlendMode::Screen => 9, + BlendMode::ColorDodge => 10, + BlendMode::LinearDodge => 11, + BlendMode::LighterColor => 12, + BlendMode::Overlay => 13, + BlendMode::SoftLight => 14, + BlendMode::HardLight => 15, + BlendMode::VividLight => 16, + BlendMode::LinearLight => 17, + BlendMode::PinLight => 18, + BlendMode::HardMix => 19, + BlendMode::Difference => 20, + BlendMode::Exclusion => 21, + BlendMode::Subtract => 22, + BlendMode::Divide => 23, + BlendMode::Hue => 24, + BlendMode::Saturation => 25, + BlendMode::Color => 26, + BlendMode::Luminosity => 27, + BlendMode::Reflect => 28, + BlendMode::Glow => 29, + BlendMode::Negation => 30, + BlendMode::Xor => 31, + BlendMode::PaintNetColorBurn => 32, + BlendMode::PaintNetColorDodge => 33, + } +} + +/// Whether `Planner::content` draws `layer` as one `Planner::content_pass`: not a group's stack, +/// an adjustment, or a pattern fill painted in passes. +pub(super) fn single_content_pass(layer: &Layer) -> bool { + match &layer.content { + LayerContent::Group(_) | LayerContent::Adjustment(_) => false, + LayerContent::Fill(f @ Fill::Pattern { .. }) => layer.fill_cache.as_ref().is_some_and(|c| c.fill == *f), + _ => true, + } +} diff --git a/crates/gpu/src/plan/planner.rs b/crates/gpu/src/plan/planner.rs new file mode 100644 index 0000000000..577237e975 --- /dev/null +++ b/crates/gpu/src/plan/planner.rs @@ -0,0 +1,1215 @@ +use super::lower::{ + Paint, adjustment_on_gpu, adjustment_program, check_gradient_stops, gradient_rows, placement, single_content_pass, stroke_widths, style_index, +}; +use super::types::{Checkpoint, DocCtx, FxLayer, Kernel, MapRef, MaskUse, Pass, Role, SurfaceRef, TexUse, Unsupported}; +use super::*; + +pub(super) struct Planner<'a> { + passes: Vec>, + free: Vec, + refs: Vec, + cx: DocCtx<'a>, + fx: Vec>, + checkpoints: Vec, + /// Layers planned so far, counting a layer each time it is planned (a clipped pass-through + /// group is planned twice). + visits: usize, +} + +/// Most layer plannings one document may take: a pass-through group with clipped layers is +/// planned twice, so groups nested in one another double the work at every level. +const MAX_PLAN_VISITS: usize = 100_000; + +/// Coverage source of an effect paint (`kind` in `fs_fxpaint`); flags refine it. +#[derive(Clone, Copy)] +enum Cov { + /// An effect map; `outside` beyond its region. + Map(MapRef, f32), + /// Full coverage. + One, +} + +/// Shader flags for effect passes (keep in sync with compose.wgsl). Coverage `m` of a paint, with +/// `a` the layer's alpha and `inside` = `a > 0.5/255`: +/// knockout `m × (1 − a × k)` (k in `p4.w`); gate `inside ? m : 0`; rel `inside ? min(m / a, 1) : 0`; +/// stroke-out `inside ? (vector ? 0 : (1 − a) / (1 − layer alpha), 1 at an opaque layer) : m`. +pub const F_KNOCKOUT: u32 = 16; + +/// Effect merge: A already holds the layer; only mix with the backdrop by the layer's opacity. +pub const F_NO_LAYER: u32 = 32; + +/// Outside strokes along a filled shape's outline (`effects::outline_share`; the coverage slot +/// carries the layer's alpha in `.g`). +pub const F_OUTLINE: u32 = 131072; + +/// Shape layer (outside strokes never show inside it). +pub const F_VECTOR: u32 = 64; + +/// Merge onto an opaque clipping base, keeping its alpha. +pub const F_ATOP: u32 = 128; + +pub const F_GATE: u32 = 256; + +pub const F_REL: u32 = 512; + +pub const F_STROKE_OUT: u32 = 1024; + +/// First outside stroke (no accumulated share yet). +pub const F_FIRST: u32 = 2048; + +/// `Lerp` per channel: weights in `p0` (channel restrictions), no opacity or mask. +pub const F_CHANNELS: u32 = 4096; + +/// Lab document: Normal blending mixes in CIELAB (`psblend::LAB_MIX`). +pub const F_LAB: u32 = 65536; + +/// 32-bit float document: Add, Divide and Exposure retain values above 1; the non-separable +/// blend modes clip only below 0 (`psblend::HDR`). +pub const F_HDR: u32 = 262144; + +/// `Lerp`: A rounded to `p0.x` steps per unit (adjustment results on integer documents). +pub const F_QUANT: u32 = 32768; + +/// `Lerp` as A + (B − C) premultiplied (layers clipped to pass-through groups). +pub const F_ADD_DIFF: u32 = 16384; + +/// `Lerp`: B mixed back towards A (the backdrop) by the layer's Blend If weight +/// (`compose::apply_blend_if`), from C ("This Layer", or B itself for an adjustment layer, `p4.y`) +/// and A ("Underlying Layer"). The ranges are packed in `p0..p3` (`blend_if_params`); `p4.x` marks +/// a one-channel document. +pub const F_BLEND_IF: u32 = 524288; + +/// Blend / Atop / FxMerge of a type layer: coverage mixed at `psblend::TEXT_GAMMA`. +pub const F_TEXT_GAMMA: u32 = 8192; + +/// `FxMerge`: B is the layer's shape (its content); the layer is its colour at fill opacity +/// (`p0.x`) inside the shape, times the shape's alpha: `FxInit` `INIT_INSIDE` then +/// `INIT_ALPHA` in the merge, for a layer with no interior effects between them. +pub const F_LAYER_SHAPE: u32 = 1_048_576; + +/// A layer's Blend If ranges for `F_BLEND_IF`: Gray, then the colour channels, each as +/// [this layer, underlying layer]; every range as two floats, `black low × 256 + black high` and +/// `white low × 256 + white high` (exact in f32), so entry `e`, side `s` starts at float +/// `(e × 2 + s) × 2`. Entries past the fourth never apply (RGB has four, one-channel modes two). +pub(super) fn blend_if_params(bi: &photocraft_doc::BlendIf) -> [[f32; 4]; 4] { + let mut f = [0.0f32; 16]; + for e in 0..4 { + for (s, r) in bi.get(e).iter().enumerate() { + let i = (e * 2 + s) * 2; + f[i] = f32::from(r.black[0]) * 256.0 + f32::from(r.black[1]); + f[i + 1] = f32::from(r.white[0]) * 256.0 + f32::from(r.white[1]); + } + } + [[f[0], f[1], f[2], f[3]], [f[4], f[5], f[6], f[7]], [f[8], f[9], f[10], f[11]], [f[12], f[13], f[14], f[15]]] +} + +/// `F_TEXT_GAMMA` for type layers while text gamma blending is on; the gamma goes in `p4.w`. +fn gamma_flag(layer: &Layer) -> u32 { + if photocraft_compose::text_gamma(layer) != 1.0 { F_TEXT_GAMMA } else { 0 } +} + +/// `FxInit` kinds: A at `opacity` × alpha; an opaque copy of A; A's colour with alpha `opacity` +/// inside B's shape; A with alpha × B's alpha. +pub const INIT_SCALE: i32 = 0; + +pub const INIT_OPAQUE: i32 = 1; + +pub const INIT_INSIDE: i32 = 2; + +pub const INIT_ALPHA: i32 = 3; + +/// The vector stroke C over A relative to the shape B, at `opacity`. +pub const INIT_VSTROKE: i32 = 4; + +/// A's colour with alpha `opacity` × A's alpha relative to B's. +pub const INIT_RELATIVE: i32 = 5; + +/// Outside-stroke coverage seed: (0, A's alpha). +pub const INIT_COVER: i32 = 6; + +/// A with its alpha joined with the effect shape (the map). +pub const INIT_OUTLINE: i32 = 7; + +/// `MapRef::item` of the layer's effect shape (`compose::layer_shape`) instead of an effect map. +pub const SHAPE_MAP: usize = usize::MAX; + +impl<'a> Planner<'a> { + pub(super) fn new(cx: DocCtx<'a>) -> Self { + Planner { passes: Vec::new(), free: Vec::new(), refs: Vec::new(), cx, fx: Vec::new(), checkpoints: Vec::new(), visits: 0 } + } + + pub(super) fn finish(self, root: Slot) -> Plan<'a> { + Plan { passes: self.passes, slots: self.refs.len() as u32, root, fx: self.fx, checkpoints: self.checkpoints } + } + + fn alloc(&mut self) -> Slot { + if let Some(s) = self.free.pop() { + self.refs[s as usize] = 1; + return s; + } + self.refs.push(1); + (self.refs.len() - 1) as Slot + } + fn retain(&mut self, s: Slot) -> Slot { + self.refs[s as usize] += 1; + s + } + fn release(&mut self, s: Slot) { + let r = &mut self.refs[s as usize]; + *r -= 1; + if *r == 0 { + self.free.push(s); + } + } + /// Emit `pass` into a fresh slot, releasing its inputs. + fn emit(&mut self, mut pass: Pass<'a>) -> Slot { + let dst = self.alloc(); + pass.dst = dst; + if self.cx.mode == photocraft_color::ColorMode::Lab { + pass.flags |= F_LAB; + } + if self.cx.depth == photocraft_color::SampleType::F32 { + pass.flags |= F_HDR; + } + let (a, b, c, d) = (pass.a, pass.b, pass.c, pass.d); + self.passes.push(pass); + for s in [a, b, c, d].into_iter().flatten() { + self.release(s); + } + dst + } + pub(super) fn clear(&mut self) -> Slot { + self.emit(Pass::new(Kernel::Clear, 0)) + } + + /// composite_stack: returns the new backdrop (consumes `backdrop`). + fn stack(&mut self, layers: &'a [Layer], backdrop: Slot) -> Result { + self.stack_inner(layers, backdrop, None) + } + + pub(super) fn stack_inner(&mut self, layers: &'a [Layer], mut backdrop: Slot, root_start: Option) -> Result { + let mut i = 0; + while i < layers.len() { + let base = &layers[i]; + let mut j = i + 1; + while j < layers.len() && layers[j].clipped && !base.clipped { + j += 1; + } + let clipped = &layers[i + 1..j]; + if base.visible { + backdrop = self.layer(base, clipped, backdrop)?; + if let (LayerContent::Adjustment(_), Some(q)) = (&base.content, photocraft_compose::adjustment_quantum(self.cx.depth)) { + // compose: adjustment results are rounded to the document's depth. + let mut p = Pass::new(Kernel::Lerp, 0); + p.a = Some(backdrop); + p.flags = F_QUANT; + p.params[0] = [q, 0.0, 0.0, 0.0]; + backdrop = self.emit(p); + } + } + i = j.max(i + 1); + if let Some(start) = root_start + && self.refs.iter().enumerate().all(|(slot, &refs)| refs == u32::from(slot == backdrop as usize)) + { + self.checkpoints.push(Checkpoint { layer_start: start, layer_end: start.saturating_add(i), pass_end: self.passes.len(), slot: backdrop }); + } + } + Ok(backdrop) + } + + fn mask_use(&self, layer: &'a Layer) -> Option> { + if let Some(c) = photocraft_compose::masks::combined_mask(layer, self.cx.canvas) { + let default = c.default_pixel().first().copied().unwrap_or(1.0); + return Some(MaskUse { layer: layer.id, surface: SurfaceRef::Derived(std::sync::Arc::new(c)), density: 1.0, default }); + } + let m = layer.mask.as_ref()?; + if !m.enabled { + return None; + } + Some(MaskUse { + layer: layer.id, + surface: SurfaceRef::Doc(&m.surface), + density: m.density, + default: m.surface.default_pixel().first().copied().unwrap_or(1.0), + }) + } + + /// `compose::apply_blend_if`: `after` (the backdrop with `layer` drawn) mixed back towards + /// `before` (the backdrop without it) where the layer's Blend If ranges hide it. "This Layer" + /// is the layer's own content with its masks; an adjustment layer is judged by its result. + /// Consumes both slots. + fn blend_if(&mut self, layer: &'a Layer, before: Slot, after: Slot) -> Result { + let own = match layer.content { + LayerContent::Adjustment(_) => None, + _ => Some(self.content(layer)?), + }; + let mut p = Pass::new(Kernel::Lerp, 0); + p.a = Some(before); + p.b = Some(after); + p.c = own; + p.flags = F_BLEND_IF; + p.params = blend_if_params(&layer.blend_if); + let one_channel = self.cx.mode != photocraft_color::ColorMode::Rgb; + p.extra = [f32::from(u8::from(one_channel)), f32::from(u8::from(own.is_none())), 0.0, 0.0]; + Ok(self.emit(p)) + } + + /// Channel restrictions and Blend If around `draw`, which composites `layer` onto `backdrop` + /// (`compose::composite_layer` / `composite_atop`: both are relative to the same backdrop). + fn restricted(&mut self, layer: &'a Layer, backdrop: Slot, draw: impl FnOnce(&mut Self, Slot) -> Result) -> Result { + let w = photocraft_compose::channel_weights(layer, self.cx.mode); + let blend_if = photocraft_compose::blend_if_active(layer, self.cx.mode); + if w.is_none() && !blend_if { + return draw(self, backdrop); + } + let before = self.retain(backdrop); + let mut after = draw(self, backdrop)?; + if let Some(w) = w { + let b = if blend_if { self.retain(before) } else { before }; + after = self.restore_channels(b, after, w); + } + if blend_if { + after = self.blend_if(layer, before, after)?; + } + Ok(after) + } + + /// Blending Options › Advanced Blending (knockout, clipped layers blended individually, blend + /// interior effects as group, transparency shapes off, masks hiding effects) has no GPU pass: + /// documents using it are composited on the CPU (`photocraft_compose::advanced`). Layers at + /// Photoshop's defaults pass this check for free. + fn check_advanced(&self, layer: &Layer, clipped: &[Layer]) -> Result<(), Unsupported> { + if photocraft_compose::advanced_active(layer, clipped) { + return Err(Unsupported(format!("Advanced Blending on `{}` (composited on the CPU)", layer.name))); + } + Ok(()) + } + + /// composite_layer, honouring the layer's channel restrictions. + fn layer(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result { + self.visits += 1; + if self.visits > MAX_PLAN_VISITS { + return Err(Unsupported("too many nested layers to plan for the GPU (composited on the CPU)".into())); + } + self.check_advanced(layer, clipped)?; + self.restricted(layer, backdrop, |s, b| s.layer_any(layer, clipped, b)) + } + + /// `compose::restore_channels`: `after` with the channels a layer leaves out taken from + /// `before` (consumes both). + fn restore_channels(&mut self, before: Slot, after: Slot, w: [f32; 3]) -> Slot { + let mut p = Pass::new(Kernel::Lerp, 0); + p.a = Some(before); + p.b = Some(after); + p.flags = F_CHANNELS; + p.params[0] = [w[0], w[1], w[2], 1.0]; + self.emit(p) + } + + fn layer_any(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result { + match layer.artboard() { + Some(ab) => self.artboard(layer, ab, clipped, backdrop), + None => self.layer_plain(layer, clipped, backdrop), + } + } + + /// compose::composite_artboard: the board's background and the group composited over the + /// backdrop, kept only inside the board (contents and effects outside it are clipped away). + fn artboard(&mut self, layer: &'a Layer, ab: &photocraft_doc::Artboard, clipped: &'a [Layer], backdrop: Slot) -> Result { + let board = ab.rect.intersect(&self.cx.canvas); + if board.is_empty() { + return Ok(backdrop); + } + let before = self.retain(backdrop); + let mut sub = backdrop; + if let Some(bg) = ab.background.rgba() { + let mut c = Pass::new(Kernel::Content, 0); + c.color = bg; + let c = self.emit(c); + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(sub); + p.b = Some(c); + sub = self.emit(p); + } + let sub = self.layer_plain(layer, clipped, sub)?; + let dst = if self.refs[before as usize] == 1 { + before + } else { + let n = self.alloc(); + let mut p = Pass::new(Kernel::CopyFull, n); + p.a = Some(before); + self.passes.push(p); + self.release(before); + n + }; + let mut p = Pass::new(Kernel::CopyRect, dst); + p.a = Some(sub); + p.clip = Some(board); + self.passes.push(p); + self.release(sub); + Ok(dst) + } + + fn layer_plain(&mut self, layer: &'a Layer, clipped: &'a [Layer], backdrop: Slot) -> Result { + let opacity = layer.opacity * layer.fill_opacity; + let visible_clipped: Vec<&'a Layer> = clipped.iter().filter(|c| c.visible).collect(); + + // Below 100% fill a pass-through group renders isolated (as the CPU compositor does), and + // so does one that is the base of a clipping group and holds an adjustment layer. + let clip_base_adjusts = !visible_clipped.is_empty() + && matches!(&layer.content, LayerContent::Group(g) if g.children.iter().any(|c| c.visible && matches!(c.content, LayerContent::Adjustment(_)))); + if let LayerContent::Group(g) = &layer.content + && layer.blend == BlendMode::PassThrough + && layer.fill_opacity >= 1.0 + && !has_effects(layer) + && !clip_base_adjusts + { + let before = self.retain(backdrop); + let mut after = self.stack(&g.children, backdrop)?; + if opacity < 1.0 || layer.mask.is_some() || layer.vector_mask.is_some() { + let mut p = Pass::new(Kernel::Lerp, 0); + p.a = Some(self.retain(before)); + p.b = Some(after); + p.opacity = opacity; + p.mask = self.mask_use(layer); + after = self.emit(p); + } + if visible_clipped.is_empty() { + self.release(before); + return Ok(after); + } + // Layers clipped to a pass-through group (compose: their effect on the group's + // isolated rendering, each placed over the original backdrop, is added to the + // pass-through result, premultiplied). + let iso = self.content(layer)?; + let iso_keep = self.retain(iso); + let mut clipped_iso = iso; + for c in visible_clipped { + clipped_iso = self.atop(c, clipped_iso)?; + } + let over = |s: &mut Self, src: Slot, before: Slot| { + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(before); + p.b = Some(src); + p.opacity = opacity; + s.emit(p) + }; + let b2 = self.retain(before); + let without = over(self, iso_keep, b2); + let with = over(self, clipped_iso, before); + let mut p = Pass::new(Kernel::Lerp, 0); + p.a = Some(after); + p.b = Some(with); + p.c = Some(without); + p.flags = F_ADD_DIFF; + return Ok(self.emit(p)); + } + + if let LayerContent::Adjustment(adj) = &layer.content { + let before = self.retain(backdrop); + let mut adjusted = self.adjust(adj, backdrop)?; + for c in visible_clipped { + adjusted = self.atop(c, adjusted)?; + } + let mut p = Pass::new(Kernel::AdjMix, 0); + p.a = Some(before); + p.b = Some(adjusted); + p.mode = layer.blend; + p.opacity = opacity; + p.mask = self.mask_use(layer); + return Ok(self.emit(p)); + } + + if has_effects(layer) { + return self.effects(layer, &visible_clipped, backdrop, false); + } + + if let LayerContent::Shape(sh) = &layer.content + && !visible_clipped.is_empty() + && let Some((fill, stroke)) = photocraft_compose::shape_split::split(sh, self.cx.canvas, self.cx.depth) + { + // The vector stroke goes above the clipped layers: the fill is the clipping base, + // the stroke is laid over the clipped result, then the masks apply to both + // (compose::shape_parts). + let mut content = self.shape_part(layer, Role::Content, fill); + for c in visible_clipped { + content = self.atop(c, content)?; + } + let stroke = self.shape_part(layer, Role::Stroke, stroke); + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(content); + p.b = Some(stroke); + let mut content = self.emit(p); + if let Some(m) = self.mask_use(layer) { + let mut p = Pass::new(Kernel::Mask, 0); + p.a = Some(content); + p.mask = Some(m); + content = self.emit(p); + } + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(backdrop); + p.b = Some(content); + p.mode = layer.blend; + p.opacity = layer.opacity; + p.fill = layer.fill_opacity; + return Ok(self.emit(p)); + } + + // A layer that covers little of the canvas composites only over its bounds and is + // copied back into the backdrop (#125): a layout with hundreds of small text and shape + // layers otherwise shades every layer over every chunk. + let clip = self.local_clip(layer); + if clip.is_some_and(|c| c.is_empty()) { + // Nothing to draw (an empty layer, or a group of them). + for c in &visible_clipped { + self.check_advanced(c, &[])?; + } + return Ok(backdrop); + } + // A layer with nothing clipped to it whose content is one Content pass is blended + // straight from its pixels (`Kernel::LayerBlend`): one pass instead of two, and no + // scratch chunk written and read back. + let mut p = if visible_clipped.is_empty() && single_content_pass(layer) { + let mut p = self.content_pass(layer)?; + p.kernel = Kernel::LayerBlend; + p + } else { + let start = self.passes.len(); + let mut content = self.content(layer)?; + for c in visible_clipped { + content = self.atop(c, content)?; + } + if let Some(clip) = clip { + // Everything that built the layer's content only matters inside its bounds. + for p in &mut self.passes[start..] { + if p.clip.is_none() && !matches!(p.kernel, Kernel::Clear | Kernel::CopyFull) { + p.clip = Some(clip); + } + } + } + let mut p = Pass::new(Kernel::Blend, 0); + p.b = Some(content); + p + }; + p.a = Some(if clip.is_some() { self.retain(backdrop) } else { backdrop }); + p.mode = layer.blend; + p.opacity = layer.opacity; + p.fill = layer.fill_opacity; + p.flags |= gamma_flag(layer); + p.extra[3] = photocraft_compose::text_gamma(layer); + p.clip = clip; + let merged = self.emit(p); + match clip { + Some(clip) => Ok(self.write_back(backdrop, merged, clip)), + None => Ok(merged), + } + } + + /// The rect a plain layer composites over: its composite bounds when they cover at most half + /// the canvas (beyond that, compositing everywhere costs less than the copy back). + fn local_clip(&self, layer: &Layer) -> Option { + let canvas = self.cx.canvas; + let b = bounds::composite_bounds(layer, canvas)?; + (b.width() as u64 * b.height() as u64 * 2 <= canvas.width() as u64 * canvas.height() as u64).then_some(b) + } + + /// Copy `merged` into `backdrop` over `clip` (in place when nothing else holds the backdrop); + /// returns the new backdrop. Consumes both. + fn write_back(&mut self, backdrop: Slot, merged: Slot, clip: Rect) -> Slot { + // A clip over the whole canvas left no pixel of `merged` uncomputed: it is the backdrop. + if clip.contains_rect(&self.cx.canvas) { + self.release(backdrop); + return merged; + } + let dst = if self.refs[backdrop as usize] == 1 { + backdrop + } else { + let n = self.alloc(); + let mut p = Pass::new(Kernel::CopyFull, n); + p.a = Some(backdrop); + self.passes.push(p); + self.release(backdrop); + n + }; + let mut p = Pass::new(Kernel::CopyRect, dst); + p.a = Some(merged); + p.clip = Some(clip); + self.passes.push(p); + self.release(merged); + dst + } + + /// A stroked shape's fill or vector stroke alone (`compose::shape_split`), unmasked. + fn shape_part(&mut self, layer: &'a Layer, role: Role, surface: Surface) -> Slot { + let mut p = Pass::new(Kernel::Content, 0); + p.color = photocraft_raster::to_rgba(&surface.format(), &surface.default_pixel()); + if surface.tile_count() > 0 { + p.tex = Some(TexUse { layer: layer.id, role, surface: SurfaceRef::Derived(std::sync::Arc::new(surface)) }); + } + self.emit(p) + } + + /// render_content for non-adjustment layers. + fn content(&mut self, layer: &'a Layer) -> Result { + match &layer.content { + LayerContent::Group(g) => { + let empty = self.clear(); + let s = self.stack(&g.children, empty)?; + if layer.mask.is_some() || layer.vector_mask.is_some() { + let mut p = Pass::new(Kernel::Mask, 0); + p.a = Some(s); + p.mask = self.mask_use(layer); + return Ok(self.emit(p)); + } + Ok(s) + } + // Adjustments are handled by the caller and never get here. + LayerContent::Adjustment(_) => Err(Unsupported("adjustment layer reached the content planner".into())), + LayerContent::Fill(f @ Fill::Pattern { name, scale, id, angle, link, phase }) if layer.fill_cache.as_ref().is_none_or(|c| c.fill != *f) => { + // compose::render_fill: the pattern tiled from the layer's frame (transparent + // when missing), then the layer's masks. + let empty = self.clear(); + let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) else { return Ok(empty) }; + let frame = photocraft_compose::fill_frame(layer, self.cx.canvas); + let anchor = if frame.is_empty() { (0.0, 0.0) } else { (f64::from(frame.x0), f64::from(frame.y0)) }; + let paint = Paint::Pattern(pat, placement(anchor, *link, *phase, *scale, *angle)); + let canvas = self.cx.canvas; + let s = self.paint(empty, empty, Cov::One, &paint, BlendMode::Normal, 1.0, 0, canvas, canvas); + if layer.mask.is_some() || layer.vector_mask.is_some() { + let mut p = Pass::new(Kernel::Mask, 0); + p.a = Some(s); + p.mask = self.mask_use(layer); + return Ok(self.emit(p)); + } + Ok(s) + } + _ => { + let p = self.content_pass(layer)?; + Ok(self.emit(p)) + } + } + } + + /// The Content pass of a raster / text / shape / smart / fill layer. + fn content_pass(&self, layer: &'a Layer) -> Result, Unsupported> { + let mut p = Pass::new(Kernel::Content, 0); + p.mask = self.mask_use(layer); + match &layer.content { + LayerContent::Fill(f) => match &layer.fill_cache { + Some(c) if c.fill == *f => self.surface_tex(&mut p, layer.id, &c.surface), + _ => self.fill(&mut p, f, photocraft_compose::fill_frame(layer, self.cx.canvas))?, + }, + _ => { + if let Some(s) = layer.surface() { + self.surface_tex(&mut p, layer.id, s); + } + } + } + Ok(p) + } + + fn surface_tex(&self, p: &mut Pass<'a>, id: LayerId, s: &'a Surface) { + let dp = s.default_pixel(); + p.color = photocraft_raster::to_rgba(&s.format(), &dp); + if s.tile_count() > 0 { + p.tex = Some(TexUse { layer: id, role: Role::Content, surface: SurfaceRef::Doc(s) }); + } + } + + fn fill(&self, p: &mut Pass<'a>, f: &Fill, frame: photocraft_geom::Rect) -> Result<(), Unsupported> { + // The RGB shader cannot interpolate or dither native ink channels. + if self.cx.mode == photocraft_color::ColorMode::Cmyk && !matches!(f, Fill::Pattern { .. }) { + return Err(Unsupported("native CMYK fill (composited on the CPU)".into())); + } + match f { + Fill::Solid(c) => { + let rgb = c.to_rgb(); + p.color = [rgb[0], rgb[1], rgb[2], c.alpha]; + } + Fill::Gradient { stops, opacity_stops, angle, scale, style, reverse, offset, dither, .. } => { + check_gradient_stops(stops)?; + check_gradient_stops(opacity_stops)?; + p.gradient = true; + // compose::render_fill: whole-pixel end points (fill_layout). + let (angle, scale, offset) = photocraft_compose::fill_layout::gradient_layout(*style, *angle, *scale, *offset, frame); + p.params[0] = [angle, scale, if *reverse { 1.0 } else { 0.0 }, style_index(*style)]; + let c = frame; + p.params[1] = [c.x0 as f32, c.y0 as f32, c.width() as f32, c.height() as f32]; + // p2.xy: centre offset; p2.z: the depth's levels a dithered pixel is rounded to + // (0: float, compose::gradient_fill::render_quantized); p2.w: dither (the shared + // position hash, see the shader). + let quantum = photocraft_compose::adjustment_quantum(self.cx.depth).unwrap_or(0.0); + p.params[2] = [offset.0, offset.1, quantum, if *dither { 1.0 } else { 0.0 }]; + let ramp = photocraft_compose::gradient_fill::Ramp::new(f); + let mut rows = vec![[0.0f32; 4096]; 4]; + for k in 0..4096 { + let v = ramp.as_ref().map_or([0.0; 4], |r| r.sample(k as f32 / 4095.0)); + for (ch, row) in rows.iter_mut().enumerate() { + row[k] = v[ch]; + } + } + p.lut = Some(rows); + } + // Pattern fills fall back to the CPU compositor (see `check`). + Fill::Pattern { .. } => {} + } + Ok(()) + } + + /// composite_atop: `layer` onto `base`, restricted to the base's alpha, honouring the + /// layer's channel restrictions. + fn atop(&mut self, layer: &'a Layer, base: Slot) -> Result { + self.check_advanced(layer, &[])?; + self.restricted(layer, base, |s, b| s.atop_any(layer, b)) + } + + fn atop_any(&mut self, layer: &'a Layer, base: Slot) -> Result { + let opacity = layer.opacity * layer.fill_opacity; + if let LayerContent::Adjustment(adj) = &layer.content { + let before = self.retain(base); + let adjusted = self.adjust(adj, base)?; + let mut p = Pass::new(Kernel::AdjMix, 0); + p.a = Some(before); + p.b = Some(adjusted); + p.mode = layer.blend; + p.opacity = opacity; + p.mask = self.mask_use(layer); + return Ok(self.emit(p)); + } + if has_effects(layer) { + return self.effects(layer, &[], base, true); + } + let content = self.content(layer)?; + let mut p = Pass::new(Kernel::Atop, 0); + p.a = Some(base); + p.b = Some(content); + p.mode = layer.blend; + p.opacity = opacity; + p.flags = gamma_flag(layer); + p.extra[3] = photocraft_compose::text_gamma(layer); + Ok(self.emit(p)) + } + + /// adjust::apply_with on a slot (consumes it). + fn adjust(&mut self, adj: &Adjustment, src: Slot) -> Result { + if !adjustment_on_gpu(adj, self.cx.mode) { + return Err(Unsupported(format!("{} on CMYK/Lab channels (evaluated on the CPU)", adj.label()))); + } + if let Adjustment::GradientMap { stops, .. } = adj { + check_gradient_stops(stops)?; + } + let mut p = Pass::new(Kernel::Adjust, 0); + p.a = Some(src); + let (kind, params, lut) = adjustment_program(adj, self.cx.transfer, self.cx.depth, self.cx.mode); + p.adjust_kind = kind; + p.params = params; + p.lut = lut; + Ok(self.emit(p)) + } + + /// `composite_with_effects` (atop = false) or the clipped-layer variant of `composite_atop` + /// (atop = true: effects over the base treated as opaque, keeping the base's alpha). + /// Consumes `backdrop`. + fn effects(&mut self, layer: &'a Layer, clipped: &[&'a Layer], backdrop: Slot, atop: bool) -> Result { + let canvas = self.cx.canvas; + let region = bounds::effect_region(layer, canvas); + let sb = photocraft_compose::paint_bounds(layer).unwrap_or_else(|| bounds::layer_bounds(layer, canvas)); + let clip = if bounds::transparent_outside(layer) { region } else { canvas }; + // A stroked shape's vector stroke goes above its clipped layers and interior effects + // (compose::split_parts): the fill and the stroke unmasked, the masks applied after. + let split = match &layer.content { + LayerContent::Shape(sh) if sh.stroke.is_some() => photocraft_compose::shape_split::split(sh, canvas, self.cx.depth), + _ => None, + }; + let (mut content, vstroke) = match split { + Some((fill, stroke)) => { + let f = self.shape_part(layer, Role::Content, fill); + let s = self.shape_part(layer, Role::Stroke, stroke); + (f, Some(s)) + } + None => (self.content(layer)?, None), + }; + for p in self.passes.iter_mut().rev().take(if vstroke.is_some() { 2 } else { 1 }) { + if !matches!(layer.content, LayerContent::Group(_)) { + p.clip = Some(clip); + } + } + for c in clipped { + content = self.atop(c, content)?; + } + let fx = self.fx.len(); + self.fx.push(FxLayer { layer, region, bounds: sb }); + let outline = photocraft_compose::effect_outline(layer).is_some(); + let relative = outline || vstroke.is_some(); + // `content` becomes the effect shape (B of every effect pass); `lay_src` the layer's colour. + let (lay_src, vstroke) = match vstroke { + Some(s) => { + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(self.retain(content)); + p.b = Some(self.retain(s)); + p.clip = Some(clip); + let union = self.emit(p); + let m = self.mask_use(layer); + let masked = |me: &mut Self, slot: Slot| match &m { + Some(m) => { + let mut p = Pass::new(Kernel::Mask, 0); + p.a = Some(slot); + p.mask = Some(m.clone()); + p.clip = Some(clip); + me.emit(p) + } + None => slot, + }; + let fill = masked(self, content); + content = masked(self, union); + (fill, Some(masked(self, s))) + } + None => (self.retain(content), None), + }; + if outline { + let mut p = Pass::new(Kernel::FxInit, 0); + p.a = Some(content); + p.adjust_kind = INIT_OUTLINE; + p.map = Some(MapRef { fx, item: SHAPE_MAP, map: 0 }); + p.clip = Some(clip); + content = self.emit(p); + } + + let items: Vec<&'a Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect(); + for e in &items { + let gradient = match e { + Effect::GradientOverlay { gradient, .. } => Some(gradient), + Effect::Stroke(s) => match &s.paint { + FxPaint::Gradient(g) => Some(g), + _ => None, + }, + Effect::OuterGlow(g) | Effect::InnerGlow(g) => match &g.paint { + FxPaint::Gradient(g) => Some(g), + _ => None, + }, + _ => None, + }; + if let Some(g) = gradient { + check_gradient_stops(&g.stops)?; + check_gradient_stops(&g.opacity_stops)?; + } + } + // Linked patterns tile from the effects reference point (else the layer's top-left). + let anchor = layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))); + let vector_shape = matches!(layer.content, LayerContent::Shape(_)) && !outline; + let map = |item: usize, map: usize| MapRef { fx, item, map }; + let rev: Vec<(usize, &'a Effect)> = items.iter().copied().enumerate().rev().collect(); + let init = |s: &mut Self, src: Slot, b: Option, kind: i32, opacity: f32| { + let mut p = Pass::new(Kernel::FxInit, 0); + p.a = Some(src); + p.b = b; + p.adjust_kind = kind; + p.opacity = opacity; + p.clip = Some(clip); + s.emit(p) + }; + + // Exterior effects over the backdrop (an opaque copy of it for clipped layers). + let mut w = if atop { + let b = self.retain(backdrop); + init(self, b, None, INIT_OPAQUE, 1.0) + } else { + self.retain(backdrop) + }; + for &(i, e) in &rev { + if let Effect::DropShadow(s) = e { + // The layer hides the shadow beneath it where its fill is see-through, and wholly + // in a mode that blends with it (as the CPU renderer: `shadow_see_through`). + let flags = if s.knocks_out { F_KNOCKOUT } else { 0 }; + let see_through = photocraft_compose::effects::shadow_see_through(layer); + w = self.paint_k( + w, + content, + Cov::Map(map(i, 0), 0.0), + &Paint::Color(s.color.to_rgb()), + s.common.blend, + s.common.opacity, + flags, + clip, + sb, + see_through, + ); + } + } + for &(i, e) in &rev { + if let Effect::OuterGlow(g) = e { + let paint = self.glow_paint(g, anchor); + // Match CPU exterior knockout: a see-through fill must not reveal the + // glow through its own shape. The shader applies m × (1 − alpha × k). + let see_through = 1.0 - layer.fill_opacity.clamp(0.0, 1.0); + w = self.paint_k(w, content, Cov::Map(map(i, 0), 0.0), &paint, g.common.blend, g.common.opacity, F_KNOCKOUT, clip, sb, see_through); + } + } + + // Only exterior effects (drop shadows, outer glows): nothing is painted between the + // layer's colour inside its shape and the shape's alpha, so the merge derives both from + // the shape (`F_LAYER_SHAPE`) instead of two passes building the layer. + let premerge = photocraft_compose::effects::premerges_layer(layer); + if !relative && !premerge && items.iter().all(|e| matches!(e, Effect::DropShadow(_) | Effect::OuterGlow(_))) { + let mut p = Pass::new(Kernel::FxMerge, 0); + p.a = Some(w); + p.b = Some(lay_src); + p.c = Some(self.retain(backdrop)); + p.mode = if layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; + p.opacity = layer.opacity; + p.flags = if atop { F_ATOP } else { 0 } | gamma_flag(layer) | F_LAYER_SHAPE; + p.params[0][0] = layer.fill_opacity; + p.extra[3] = photocraft_compose::text_gamma(layer); + p.clip = Some(clip); + let merged = self.emit(p); + self.release(content); + return Ok(self.write_back(backdrop, merged, clip)); + } + // The layer: its colour at fill opacity inside its shape; interior effects are painted + // relative to the shape (coverage within it), then the shape's alpha applies. + let mut l = if relative { + let c = self.retain(content); + init(self, lay_src, Some(c), INIT_RELATIVE, layer.fill_opacity) + } else { + init(self, lay_src, None, INIT_INSIDE, layer.fill_opacity) + }; + // Blend Interior Effects as Group off: the layer merges in its mode first and the + // interior effects paint over the result (`effects::premerges_layer`). + if premerge { + let mut p = Pass::new(Kernel::Blend, 0); + p.a = Some(self.retain(w)); + p.b = Some(l); + p.mode = layer.blend; + p.flags = gamma_flag(layer); + p.extra[3] = photocraft_compose::text_gamma(layer); + p.clip = Some(clip); + l = self.emit(p); + } + for &(_, e) in &rev { + if let Effect::PatternOverlay { common, name, id, scale, angle, link, phase } = e + && let Some(pat) = photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) + { + let paint = Paint::Pattern(pat, placement(anchor, *link, *phase, *scale, *angle)); + l = self.paint(l, content, Cov::One, &paint, common.blend, common.opacity, F_GATE, clip, sb); + } + } + for &(_, e) in &rev { + if let Effect::GradientOverlay { common, gradient, .. } = e { + l = self.paint(l, content, Cov::One, &Paint::Gradient(gradient), common.blend, common.opacity, F_GATE, clip, sb); + } + } + for &(_, e) in &rev { + if let Effect::ColorOverlay { common, color } = e { + l = self.paint(l, content, Cov::One, &Paint::Color(color.to_rgb()), common.blend, common.opacity, F_GATE, clip, sb); + } + } + for &(i, e) in &rev { + if let Effect::Satin(s) = e { + l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(s.color.to_rgb()), s.common.blend, s.common.opacity, F_REL, clip, sb); + } + } + for &(i, e) in &rev { + if let Effect::InnerGlow(g) = e { + let paint = self.glow_paint(g, anchor); + l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &paint, g.common.blend, g.common.opacity, F_REL, clip, sb); + } + } + for &(i, e) in &rev { + if let Effect::InnerShadow(s) = e { + l = self.paint(l, content, Cov::Map(map(i, 0), 0.0), &Paint::Color(s.color.to_rgb()), s.common.blend, s.common.opacity, F_REL, clip, sb); + } + } + if let Some(s) = vstroke { + let mut p = Pass::new(Kernel::FxInit, 0); + p.a = Some(l); + p.b = Some(self.retain(content)); + p.c = Some(s); + p.adjust_kind = INIT_VSTROKE; + p.opacity = layer.fill_opacity; + p.clip = Some(clip); + l = self.emit(p); + } + // Inside stroke parts are painted over the layer (bottom instance first). + for &(i, e) in &rev { + if let Effect::Stroke(st) = e { + let (in_w, _) = stroke_widths(st); + if in_w > 0.0 { + let paint = self.fx_paint(&st.paint, anchor); + l = self.paint( + l, + content, + Cov::Map(map(i, 1), (in_w + 0.5).clamp(0.0, 1.0)), + &paint, + st.common.blend, + st.common.opacity, + F_GATE, + clip, + photocraft_compose::stroke_frame(self.cx.doc, layer, st).unwrap_or(sb), + ); + } + } + } + let bevel_paint = |b: &photocraft_doc::Bevel| photocraft_compose::effects::bevel_geom(b).paint; + for &(i, e) in &rev { + if let Effect::BevelEmboss(b) = e + && bevel_paint(b) == photocraft_compose::effects::BevelPaint::Inner + { + l = self.paint( + l, + content, + Cov::Map(map(i, 0), 0.0), + &Paint::Color(b.highlight_color.to_rgb()), + b.highlight.blend, + b.highlight.opacity, + F_REL, + clip, + sb, + ); + l = self.paint(l, content, Cov::Map(map(i, 1), 0.0), &Paint::Color(b.shadow_color.to_rgb()), b.shadow.blend, b.shadow.opacity, F_REL, clip, sb); + } + } + // The shape's own alpha. + let c = self.retain(content); + l = init(self, l, Some(c), INIT_ALPHA, 1.0); + // Outside stroke parts lie beneath the layer and blend onto the exterior result with their + // own mode; a higher stroke covers the ones below it (each takes its coverage × opacity + // not yet taken above it, blended over the result as it was before the strokes). + let outs: Vec<(usize, &photocraft_doc::StrokeFx)> = items + .iter() + .copied() + .enumerate() + .filter_map(|(i, e)| if let Effect::Stroke(st) = e { Some((i, st)) } else { None }) + .filter(|(_, st)| stroke_widths(st).1 > 0.0) + .collect(); + if !outs.is_empty() { + let (mut acc, mut cover): (Option, Option) = (None, None); + if outline || !vector_shape { + // The layer's alpha rides along the coverage: `effects::outline_share`, and for + // pixel layers the stroke's share beneath a partly covering layer (fill < 100 %). + let ll = self.retain(l); + cover = Some(init(self, ll, None, INIT_COVER, 1.0)); + } + for (n, &(i, st)) in outs.iter().enumerate() { + let paint = self.fx_paint(&st.paint, anchor); + let flags = F_STROKE_OUT | if vector_shape { F_VECTOR } else { 0 } | if outline { F_OUTLINE } else { 0 } | if n == 0 { F_FIRST } else { 0 }; + // Share × blended colour, then coverage (both read the coverage so far). + let mut p = self.fx_pass_kernel( + Kernel::FxStroke, + w, + content, + &paint, + st.common.blend, + st.common.opacity, + flags, + clip, + photocraft_compose::stroke_frame(self.cx.doc, layer, st).unwrap_or(sb), + ); + if matches!(paint, Paint::None) { + // A missing pattern paints nothing: the stroke's share keeps the result as is. + p.params[2][2] = 3.0; + } + p.adjust_kind = 0; + p.map = Some(map(i, 0)); + p.c = cover.map(|c| self.retain(c)); + p.d = acc; + let a = self.emit(p); + // The stroke's mode rides along only for Dissolve, whose coverage is all or + // nothing in this pass as in the colour pass (#6995). + let mut p = self.fx_pass_kernel(Kernel::FxStroke, w, content, &Paint::Color([0.0; 3]), st.common.blend, st.common.opacity, flags, clip, sb); + p.adjust_kind = 1; + p.map = Some(map(i, 0)); + p.c = cover; + cover = Some(self.emit(p)); + acc = Some(a); + } + let mut p = Pass::new(Kernel::FxStrokeEnd, 0); + p.a = Some(w); + p.b = acc; + p.c = cover; + p.clip = Some(clip); + w = self.emit(p); + } + for &(i, e) in &rev { + if let Effect::BevelEmboss(b) = e + && bevel_paint(b) == photocraft_compose::effects::BevelPaint::Outer + { + let k = 0; + w = self.paint( + w, + content, + Cov::Map(map(i, k), 0.0), + &Paint::Color(b.highlight_color.to_rgb()), + b.highlight.blend, + b.highlight.opacity, + 0, + clip, + sb, + ); + w = self.paint(w, content, Cov::Map(map(i, k + 1), 0.0), &Paint::Color(b.shadow_color.to_rgb()), b.shadow.blend, b.shadow.opacity, 0, clip, sb); + } + } + + let mode = if premerge || layer.blend == BlendMode::PassThrough { BlendMode::Normal } else { layer.blend }; + let late: Vec<(usize, &'a photocraft_doc::Bevel)> = rev + .iter() + .filter_map(|&(i, e)| if let Effect::BevelEmboss(b) = e { Some((i, b)) } else { None }) + .filter(|(_, b)| bevel_paint(b) == photocraft_compose::effects::BevelPaint::Both) + .collect(); + let merged = if late.is_empty() { + let mut p = Pass::new(Kernel::FxMerge, 0); + p.a = Some(w); + p.b = Some(l); + p.c = Some(self.retain(backdrop)); + p.mode = mode; + p.opacity = layer.opacity; + p.flags = if atop { F_ATOP } else { 0 } | gamma_flag(layer); + p.extra[3] = photocraft_compose::text_gamma(layer); + p.clip = Some(clip); + self.emit(p) + } else { + // Emboss styles shade the composited layer (`composite_with_effects`): merge at full + // opacity, paint their maps (inside and outside halves), then mix. + let mut p = Pass::new(Kernel::FxMerge, 0); + p.a = Some(w); + p.b = Some(l); + p.c = Some(self.retain(w)); + p.mode = mode; + p.opacity = 1.0; + p.flags = gamma_flag(layer); + p.extra[3] = photocraft_compose::text_gamma(layer); + p.clip = Some(clip); + let mut m = self.emit(p); + for (i, b) in late { + for (k, color, fxc) in [(0, &b.highlight_color, &b.highlight), (1, &b.shadow_color, &b.shadow)] { + m = self.paint(m, content, Cov::Map(map(i, k), 0.0), &Paint::Color(color.to_rgb()), fxc.blend, fxc.opacity, 0, clip, sb); + } + } + let mut p = Pass::new(Kernel::FxMerge, 0); + p.b = Some(self.retain(m)); + p.a = Some(m); + p.c = Some(self.retain(backdrop)); + p.mode = mode; + p.opacity = layer.opacity; + p.flags = if atop { F_ATOP } else { 0 } | F_NO_LAYER; + p.clip = Some(clip); + self.emit(p) + }; + self.release(content); + + // Write the clipped result back into the backdrop (in place when nothing else holds it). + Ok(self.write_back(backdrop, merged, clip)) + } + + fn fx_paint(&self, p: &'a FxPaint, anchor: (f64, f64)) -> Paint<'a> { + match p { + FxPaint::Color(c) => Paint::Color(c.to_rgb()), + FxPaint::Gradient(g) => Paint::Gradient(g), + FxPaint::Pattern { name, id, scale } => match photocraft_doc::pattern::find(self.cx.patterns, id, name).filter(|p| p.is_paintable()) { + Some(pat) => Paint::Pattern(pat, placement(anchor, true, (0.0, 0.0), *scale, 0.0)), + None => Paint::None, + }, + } + } + + fn glow_paint(&self, g: &'a Glow, anchor: (f64, f64)) -> Paint<'a> { + match &g.paint { + FxPaint::Gradient(gradient) => Paint::GlowGradient(gradient, photocraft_compose::effects::glow_gradient_gain(g.range)), + p => self.fx_paint(p, anchor), + } + } + + /// An effect pass reading `dst` (A, retained) and the layer `content` (B, retained) with its + /// paint set up. + #[allow(clippy::too_many_arguments)] + fn fx_pass(&mut self, dst: Slot, content: Slot, paint: &Paint<'a>, blend: BlendMode, opacity: f32, flags: u32, clip: Rect, sb: Rect) -> Pass<'a> { + self.fx_pass_kernel(Kernel::FxPaint, dst, content, paint, blend, opacity, flags, clip, sb) + } + + #[allow(clippy::too_many_arguments)] + fn fx_pass_kernel( + &mut self, + kernel: Kernel, + dst: Slot, + content: Slot, + paint: &Paint<'a>, + blend: BlendMode, + opacity: f32, + flags: u32, + clip: Rect, + sb: Rect, + ) -> Pass<'a> { + let mut p = Pass::new(kernel, 0); + p.a = Some(self.retain(dst)); + p.b = Some(self.retain(content)); + p.mode = blend; + p.opacity = opacity; + p.flags = flags; + p.clip = Some(clip); + match paint { + Paint::None => {} + Paint::Color(c) => p.color = [c[0], c[1], c[2], 1.0], + Paint::Gradient(g) => { + // effects::paint_fx: whole-pixel end points (fill_layout::gradient_layout). + let (angle, scale, offset) = photocraft_compose::fill_layout::gradient_layout(g.style, g.angle, g.scale, g.offset, sb); + p.params[0] = [angle, scale, if g.reverse { 1.0 } else { 0.0 }, style_index(g.style)]; + p.params[1] = [sb.x0 as f32, sb.y0 as f32, sb.width() as f32, sb.height() as f32]; + p.params[2][0] = offset.0; + p.params[2][1] = offset.1; + p.params[2][2] = 1.0; + p.lut = Some(gradient_rows(g)); + } + Paint::GlowGradient(g, gain) => { + // effects::paint_glow: the gradient at 1 - strength, opaque from 1 / gain. + p.params[0][0] = *gain; + p.params[2][2] = 4.0; + p.lut = Some(gradient_rows(g)); + } + Paint::Pattern(pat, pl) => { + p.params[2][2] = 2.0; + p.params[3] = [pl.origin.0 as f32, pl.origin.1 as f32, pl.cs.0 as f32, pl.cs.1 as f32]; + p.extra = [pl.inv_scale as f32, pat.width as f32, pat.height as f32, 0.0]; + p.pattern = Some(pat); + } + } + p + } + + /// One effect paint into `dst` (consumed); reads the layer's alpha from `content` (kept). + #[allow(clippy::too_many_arguments)] + fn paint(&mut self, dst: Slot, content: Slot, cov: Cov, paint: &Paint<'a>, blend: BlendMode, opacity: f32, flags: u32, clip: Rect, sb: Rect) -> Slot { + self.paint_k(dst, content, cov, paint, blend, opacity, flags, clip, sb, 1.0) + } + + /// [`Self::paint`] with the knockout strength (`F_KNOCKOUT`: coverage × (1 − alpha × k)). + #[allow(clippy::too_many_arguments)] + fn paint_k( + &mut self, + dst: Slot, + content: Slot, + cov: Cov, + paint: &Paint<'a>, + blend: BlendMode, + opacity: f32, + flags: u32, + clip: Rect, + sb: Rect, + knockout: f32, + ) -> Slot { + if matches!(paint, Paint::None) { + // Missing pattern: compose paints nothing. + return dst; + } + let mut p = self.fx_pass(dst, content, paint, blend, opacity, flags, clip, sb); + self.release(dst); + match cov { + Cov::Map(m, outside) => { + p.adjust_kind = 0; + p.map = Some(m); + p.params[2][3] = outside; + } + Cov::One => p.adjust_kind = 1, + } + p.extra[3] = knockout; + self.emit(p) + } +} diff --git a/crates/gpu/src/plan/types.rs b/crates/gpu/src/plan/types.rs new file mode 100644 index 0000000000..e83fac8c8c --- /dev/null +++ b/crates/gpu/src/plan/types.rs @@ -0,0 +1,304 @@ +use super::*; + +/// Pipeline (fragment entry point) of a pass. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kernel { + /// Transparent fill (no draw). + Clear, + Content, + Mask, + Blend, + /// `Content` then `Blend` in one pass: a plain layer's pixels blended straight onto A. + LayerBlend, + /// A run of consecutive `LayerBlend` passes drawn as one (never planned: the executor draws + /// it in their place, see `batch_runs`). + LayerBatch, + /// `LayerBatch` of a run whose layers all blend Normal without text gamma, outside Lab + /// documents (never planned: the executor picks it, see `batch_kernel`). + LayerBatchNormal, + Atop, + Adjust, + AdjMix, + Lerp, + /// Effect chain start: the layer at fill opacity, or an opaque copy of a clipping base. + FxInit, + /// Paint an effect through a coverage map (or the layer's alpha) into A. + FxPaint, + /// Layer + interior effects over the exterior result, then layer opacity against the backdrop. + FxMerge, + /// Outside strokes: accumulate one stroke's share (`kind` 0, premultiplied colour) or its + /// coverage (`kind` 1). + FxStroke, + /// Outside strokes: resolve the accumulated strokes over the exterior result. + FxStrokeEnd, + /// Copy slot A into `dst` (an existing slot) over the pass clip (no draw). + CopyRect, + /// Copy all of slot A into the fresh slot `dst` (no draw). + CopyFull, + // Effect-map kernels (single-channel targets over an effect region, see `fx`). + MShift, + MDilate, + MBlur, + MGlow, + MFinish, + MBevelH, + MBevelShade, + MStroke, + MBevelTex, +} + +impl Kernel { + /// Fragment entry point in `compose.wgsl` (`None` for copies and clears). + pub fn entry(self) -> Option<&'static str> { + Some(match self { + Kernel::Clear | Kernel::CopyRect | Kernel::CopyFull => return None, + Kernel::Content => "fs_content", + Kernel::Mask => "fs_mask", + Kernel::Blend => "fs_blend", + Kernel::LayerBlend => "fs_layerblend", + Kernel::LayerBatch => "fs_layerbatch", + Kernel::LayerBatchNormal => "fs_layerbatch_normal", + Kernel::Atop => "fs_atop", + Kernel::Adjust => "fs_adjust", + Kernel::AdjMix => "fs_adjmix", + Kernel::Lerp => "fs_lerp", + Kernel::FxInit => "fs_fxinit", + Kernel::FxPaint => "fs_fxpaint", + Kernel::FxMerge => "fs_fxmerge", + Kernel::FxStroke => "fs_fxstroke", + Kernel::FxStrokeEnd => "fs_fxstrokeend", + Kernel::MShift => "fs_mshift", + Kernel::MDilate => "fs_mdilate", + Kernel::MBlur => "fs_mblur", + Kernel::MGlow => "fs_mglow", + Kernel::MFinish => "fs_mfinish", + Kernel::MBevelH => "fs_mbevelh", + Kernel::MBevelShade => "fs_mbevelshade", + Kernel::MStroke => "fs_mstroke", + Kernel::MBevelTex => "fs_mbeveltex", + }) + } + + /// Kernels that write effect maps (R32F / R16F targets) rather than RGBA accumulators. + pub fn is_map(self) -> bool { + matches!( + self, + Kernel::MShift + | Kernel::MDilate + | Kernel::MBlur + | Kernel::MGlow + | Kernel::MFinish + | Kernel::MBevelH + | Kernel::MBevelShade + | Kernel::MStroke + | Kernel::MBevelTex + ) + } + + /// Every kernel with a pipeline. + pub const DRAWN: [Kernel; 24] = [ + Kernel::Content, + Kernel::Mask, + Kernel::Blend, + Kernel::LayerBlend, + Kernel::LayerBatch, + Kernel::LayerBatchNormal, + Kernel::Atop, + Kernel::Adjust, + Kernel::AdjMix, + Kernel::Lerp, + Kernel::FxInit, + Kernel::FxPaint, + Kernel::FxMerge, + Kernel::FxStroke, + Kernel::FxStrokeEnd, + Kernel::MShift, + Kernel::MDilate, + Kernel::MBlur, + Kernel::MGlow, + Kernel::MFinish, + Kernel::MBevelH, + Kernel::MBevelShade, + Kernel::MStroke, + Kernel::MBevelTex, + ]; +} + +/// Which resident texture a pass samples. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Role { + Content, + Mask, + /// A stroked shape's stroke alone (its fill uses `Content`). + Stroke, +} + +/// A surface the pass needs on the GPU. +#[derive(Clone, Debug)] +pub struct TexUse<'a> { + pub layer: LayerId, + pub role: Role, + pub surface: SurfaceRef<'a>, +} + +/// An effect map sampled by a pass: map `map` of enabled effect `item` of `plan.fx[fx]`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MapRef { + pub fx: usize, + pub item: usize, + pub map: usize, +} + +#[derive(Clone, Debug)] +pub struct Pass<'a> { + pub kernel: Kernel, + pub dst: Slot, + pub a: Option, + pub b: Option, + pub c: Option, + /// A fourth slot, bound in place of `tex` (passes without layer pixels). + pub d: Option, + pub mode: BlendMode, + pub opacity: f32, + /// The layer's Fill where it isn't folded into `opacity`: the final blend of a plain layer + /// (`Kernel::Blend`), so the special eight can apply it inside the blend. 1 elsewhere. + pub fill: f32, + /// Layer pixels (raster / text / shape / smart cache / fill cache). + pub tex: Option>, + /// Colour outside `tex` (the surface's default pixel), the solid fill colour, or the effect + /// colour. + pub color: [f32; 4], + pub mask: Option>, + /// Adjustment kind (see `adjust` in compose.wgsl) and parameters; the coverage kind of an + /// effect paint. + pub adjust_kind: i32, + pub params: [[f32; 4]; 4], + pub extra: [f32; 4], + /// Extra shader flags (`F_KNOCKOUT`, …). + pub flags: u32, + /// 4096-entry LUT rows (Levels / Curves / Gradient map / gradient stops). + pub lut: Option>, + pub gradient: bool, + /// Effect map sampled by `FxPaint`. + pub map: Option, + /// Pattern painted by `FxPaint`. + pub pattern: Option<&'a Pattern>, + /// Only pixels inside this rect (document coordinates) are computed; the pass is skipped for + /// chunks it misses. Consumers of the slot must be clipped alike. + pub clip: Option, +} + +/// Pixels a pass samples: a surface of the document, or one derived from it on the CPU (a +/// combined pixel × vector mask, a shape's fill or stroke alone). +#[derive(Clone, Debug)] +pub enum SurfaceRef<'a> { + Doc(&'a Surface), + Derived(std::sync::Arc), +} + +impl SurfaceRef<'_> { + pub fn get(&self) -> &Surface { + match self { + SurfaceRef::Doc(s) => s, + SurfaceRef::Derived(s) => s, + } + } +} + +#[derive(Clone, Debug)] +pub struct MaskUse<'a> { + pub layer: LayerId, + pub surface: SurfaceRef<'a>, + pub density: f32, + pub default: f32, +} + +impl<'a> Pass<'a> { + pub(crate) fn new(kernel: Kernel, dst: Slot) -> Self { + Pass { + kernel, + dst, + a: None, + b: None, + c: None, + d: None, + mode: BlendMode::Normal, + opacity: 1.0, + fill: 1.0, + tex: None, + color: [0.0; 4], + mask: None, + adjust_kind: 0, + params: [[0.0; 4]; 4], + extra: [0.0; 4], + flags: 0, + lut: None, + gradient: false, + map: None, + pattern: None, + clip: None, + } + } +} + +/// Why a document can't be composited on the GPU (the caller falls back to the CPU compositor). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Unsupported(pub String); + +impl std::fmt::Display for Unsupported { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "GPU compositor: {}", self.0) + } +} + +impl std::error::Error for Unsupported {} + +/// A layer whose effects the plan renders: its maps are built (or reused) before the chunks run. +#[derive(Clone, Copy, Debug)] +pub struct FxLayer<'a> { + pub layer: &'a Layer, + /// Region the maps cover (`compose::effect_maps`). + pub region: Rect, + /// Layer bounds (gradients and linked patterns are laid out in them). + pub bounds: Rect, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Checkpoint { + /// First root layer included after occlusion pruning. + pub layer_start: usize, + /// Root layers below this boundary (including the complete clipping unit). + pub layer_end: usize, + /// Resume at this pass with `slot` restored. + pub pass_end: usize, + pub slot: Slot, +} + +/// Document-level inputs of a plan. +#[derive(Clone, Copy)] +pub struct DocCtx<'a> { + pub canvas: Rect, + pub transfer: Transfer, + pub light: GlobalLight, + pub patterns: &'a [Pattern], + /// Colour mode (channel restrictions name its channels). + pub mode: photocraft_color::ColorMode, + /// Sample depth (adjustment results are rounded to it). + pub depth: photocraft_color::SampleType, + /// The document (effect geometry the CPU computes, e.g. gradient stroke frames). + pub doc: &'a Document, +} + +impl<'a> DocCtx<'a> { + pub fn of(doc: &'a Document) -> Self { + DocCtx { + canvas: doc.bounds(), + transfer: Transfer::for_document(doc.mode, doc.depth), + light: doc.global_light, + patterns: &doc.patterns, + mode: doc.mode, + depth: doc.depth, + doc, + } + } +} From ff2a29a364b5ae0d243c947f1a99c06e7d626c70 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:18:13 +0000 Subject: [PATCH 250/259] refactor(algo): split inpaint.rs into inpaint/ --- crates/algo/src/inpaint.rs | 1698 +------------------------- crates/algo/src/inpaint/common.rs | 119 ++ crates/algo/src/inpaint/solver.rs | 866 +++++++++++++ crates/algo/src/inpaint/sources.rs | 326 +++++ crates/algo/src/inpaint/synthesis.rs | 381 ++++++ crates/algo/src/inpaint/tests.rs | 3 +- 6 files changed, 1711 insertions(+), 1682 deletions(-) create mode 100644 crates/algo/src/inpaint/common.rs create mode 100644 crates/algo/src/inpaint/solver.rs create mode 100644 crates/algo/src/inpaint/sources.rs create mode 100644 crates/algo/src/inpaint/synthesis.rs diff --git a/crates/algo/src/inpaint.rs b/crates/algo/src/inpaint.rs index e05aa3daac..87b8407a95 100644 --- a/crates/algo/src/inpaint.rs +++ b/crates/algo/src/inpaint.rs @@ -51,64 +51,25 @@ use crate::poisson::membrane_fill; mod proximity_integral; use proximity_integral::HoleIntegral; -/// Below this many cells a pass runs on the calling thread (thread hand-off costs more than it -/// saves). Every pass gives the same result either way. -const PAR_MIN: usize = 64 * 64; +mod common; +mod solver; +mod sources; +mod synthesis; -/// [`PAR_MIN`] for the passes that match or vote a patch per cell. -const PAR_MIN_PATCHES: usize = 16 * 16; - -/// Largest level (in cells) whose source patches' moments [`Solver::prepare`] keeps. -const SOURCE_MOMENTS_MAX: usize = 1 << 20; - -/// SplitMix64: tiny deterministic RNG. -#[derive(Clone)] -pub(crate) struct Rng(u64); -impl Rng { - /// A generator whose sequence is fixed by `seed`. - pub(crate) fn new(seed: u64) -> Self { - Rng(seed ^ 0x9E37_79B9_7F4A_7C15) - } - /// The next value of the SplitMix64 sequence. - pub(crate) fn next(&mut self) -> u64 { - crate::photo_util::splitmix64(&mut self.0) - } - /// Skip `n` numbers (the same state as after `n` calls of [`Rng::next`]). - pub(crate) fn skip(&mut self, n: u64) { - self.0 = self.0.wrapping_add(n.wrapping_mul(0x9E37_79B9_7F4A_7C15)); - } - /// Uniform integer in `lo..=hi`. - pub(crate) fn range(&mut self, lo: i32, hi: i32) -> i32 { - if hi <= lo { - return lo; - } - lo + (self.next() % (hi - lo + 1) as u64) as i32 - } -} - -/// How far a copied patch may be adjusted to its target, per channel: `gain · source + bias`, the -/// gain within `gain` and the bias within `±bias` (Image Melding's photometric transform). The -/// gain is the ratio of the patches' standard deviations, the bias what then matches their means. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Adapt { - pub gain: (f32, f32), - pub bias: f32, -} - -impl Adapt { - /// Copies are taken as they are. - pub const NONE: Adapt = Adapt { gain: (1.0, 1.0), bias: 0.0 }; - - pub fn is_none(&self) -> bool { - self.gain == (1.0, 1.0) && self.bias == 0.0 - } -} - -impl Default for Adapt { - fn default() -> Self { - Self::NONE - } -} +#[cfg(test)] +use common::Bounds; +pub(crate) use common::Rng; +pub use common::{Adapt, Px}; +use common::{Level, SOURCE_MOMENTS_MAX}; +use solver::Solver; +pub(crate) use solver::fit; +#[cfg(test)] +use solver::least_sum; +use sources::{Coarser, Sources, THIN_RATIO, downsample, hole_bounds, hole_thickness, peel_affordable, targets_around, valid_sources, window_count}; +#[cfg(test)] +use sources::{hole_bbox, integral}; +use synthesis::onion_peel; +pub use synthesis::{best_offset, synthesize}; /// Parameters for [`complete`]. #[derive(Clone, Debug, PartialEq)] @@ -135,1417 +96,6 @@ impl Default for CompleteParams { } } -/// What a pixel is to [`complete_masked`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Px { - /// Not part of the image (a gap, or outside a transformed copy): ignored. - Void, - /// Known, part of the context the fill must agree with, but not copied from. - Known, - /// Known and may be copied from. - Source, - /// To be filled. - Hole, -} - -/// One pyramid level. Level 0 borrows the caller's buffers until it is solved. -struct Level<'a> { - w: usize, - h: usize, - img: Cow<'a, [f32]>, - px: Cow<'a, [Px]>, -} - -impl Level<'_> { - const EMPTY: Level<'static> = Level { w: 0, h: 0, img: Cow::Borrowed(&[]), px: Cow::Borrowed(&[]) }; -} - -/// The half-open box `[x0, x1) × [y0, y1)` of a level's grid. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct Bounds { - x0: usize, - y0: usize, - x1: usize, - y1: usize, -} - -impl Bounds { - /// Grown by `r` on every side, within a `w × h` grid. - fn grow(self, r: usize, w: usize, h: usize) -> Bounds { - Bounds { x0: self.x0.saturating_sub(r), y0: self.y0.saturating_sub(r), x1: self.x1.saturating_add(r).min(w), y1: self.y1.saturating_add(r).min(h) } - } - - /// The same box on the next coarser level (whose cells are 2 × 2 of these). - fn half(self) -> Bounds { - Bounds { x0: self.x0 / 2, y0: self.y0 / 2, x1: self.x1.div_ceil(2), y1: self.y1.div_ceil(2) } - } - - fn width(&self) -> usize { - self.x1.saturating_sub(self.x0) - } - - fn height(&self) -> usize { - self.y1.saturating_sub(self.y0) - } - - fn area(&self) -> usize { - self.width() * self.height() - } -} - -/// Half-size level: a cell is a hole if any of its pixels is; else it averages its non-void -/// pixels, and may be copied from only if all of them may. -fn downsample(l: &Level, ch: usize) -> Level<'static> { - let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2)); - let mut img = vec![0.0f32; w * h * ch]; - let mut px = vec![Px::Void; w * h]; - let (lw, lh, limg, lpx) = (l.w, l.h, &*l.img, &*l.px); - let row = |y: usize, irow: &mut [f32], prow: &mut [Px]| { - for (x, p) in prow.iter_mut().enumerate() { - let mut n = 0.0f32; - let o = x * ch; - let (mut hole, mut all_source, mut any) = (false, true, false); - for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { - let (sx, sy) = (x * 2 + dx, y * 2 + dy); - if sx >= lw || sy >= lh { - continue; - } - let si = sy * lw + sx; - match lpx[si] { - Px::Hole => hole = true, - Px::Void => all_source = false, - k => { - any = true; - all_source &= k == Px::Source; - for c in 0..ch { - irow[o + c] += limg[si * ch + c]; - } - n += 1.0; - } - } - } - if n > 0.0 { - for c in 0..ch { - irow[o + c] /= n; - } - } - *p = if hole { - Px::Hole - } else if !any { - Px::Void - } else if all_source { - Px::Source - } else { - Px::Known - }; - } - }; - par::chunks2_mut(&mut img, w * ch, &mut px, w, w * h >= PAR_MIN, row); - Level { w, h, img: Cow::Owned(img), px: Cow::Owned(px) } -} - -/// Summed-area table of a boolean grid (`(w+1) × (h+1)`). Not inlined: in [`synthesize`] it made -/// Create Texture's candidate loop slower (measured). -#[inline(never)] -fn integral(w: usize, h: usize, m: &[bool]) -> Vec { - let mut s = vec![0u32; (w + 1) * (h + 1)]; - for y in 0..h { - let mut row = 0u32; - for x in 0..w { - row += u32::from(m[y * w + x]); - s[(y + 1) * (w + 1) + x + 1] = s[y * (w + 1) + x + 1] + row; - } - } - s -} - -/// Count of set cells in the clipped window `[x0, x1) × [y0, y1)`. -fn window_count(s: &[u32], gw: usize, gh: usize, x0: i32, y0: i32, x1: i32, y1: i32) -> u32 { - let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize); - let (x1, y1) = ((x1.max(0) as usize).min(gw), (y1.max(0) as usize).min(gh)); - if x1 <= x0 || y1 <= y0 { - return 0; - } - let w1 = gw + 1; - s[y1 * w1 + x1] + s[y0 * w1 + x0] - s[y0 * w1 + x1] - s[y1 * w1 + x0] -} - -fn hole_bbox(w: usize, h: usize, hole: &[bool]) -> Option<(usize, usize, usize, usize)> { - let mut b: Option<(usize, usize, usize, usize)> = None; - for y in 0..h { - for x in 0..w { - if hole[y * w + x] { - b = Some(match b { - None => (x, y, x + 1, y + 1), - Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)), - }); - } - } - } - b -} - -/// A hole at most `1 / THIN_RATIO` as thick as its bounds are long counts as thin (a wire, a -/// string, a hair, a long brush stroke): see the module docs. -const THIN_RATIO: usize = 4; - -/// How thick the hole within bounds `hb` of a `w`-wide role grid is: twice the largest distance -/// from a hole pixel to the nearest pixel that is not one (a long, thin hole is thin however long -/// its bounds). -fn hole_thickness(w: usize, hb: Bounds, px: &[Px]) -> usize { - // The bounds and a ring of non-hole cells around them (also past the grid's edge). - let (gw, gh) = (hb.width() + 2, hb.height() + 2); - let outside: Vec = par::map(gw * gh, gw * gh >= PAR_MIN, |i| { - let (gx, gy) = (i % gw, i / gw); - if gx == 0 || gy == 0 || gx > hb.width() || gy > hb.height() { - return true; - } - px.get((hb.y0 + gy - 1) * w + hb.x0 + gx - 1) != Some(&Px::Hole) - }); - let deepest = crate::selection::edt(&outside, gw, gh).into_iter().fold(0.0f32, f32::max); - (2.0 * deepest).ceil() as usize -} - -/// Most target pixels × sources the onion peel of a thin hole may compare (its search is -/// exhaustive, though most comparisons stop early: about a second at this many). -const PEEL_BUDGET: usize = 1 << 28; - -/// Whether the onion peel of the hole cells within `hb` of a `w`-wide role grid from `sources` -/// source centres stays within [`PEEL_BUDGET`]. -fn peel_affordable(w: usize, px: &[Px], hb: Bounds, sources: usize) -> bool { - let holes: usize = (hb.y0..hb.y1).map(|y| px.get(y * w + hb.x0..y * w + hb.x1).map_or(0, |row| row.iter().filter(|k| **k == Px::Hole).count())).sum(); - holes.saturating_mul(sources) <= PEEL_BUDGET -} - -/// Bounds of the hole pixels of a role grid. -fn hole_bounds(w: usize, h: usize, px: &[Px]) -> Option { - // A zero-width grid holds no pixels whatever its height; don't size a row table by it. - if w == 0 || h == 0 { - return None; - } - // Per row the first and last hole column; the union of the rows' spans. - let rows: Vec> = par::map(h, w * h >= PAR_MIN, |y| { - let row = px.get(y * w..(y + 1) * w)?; - let x0 = row.iter().position(|k| *k == Px::Hole)?; - let x1 = row.iter().rposition(|k| *k == Px::Hole).unwrap_or(x0) + 1; - Some((x0, x1)) - }); - let mut b: Option = None; - for (y, span) in rows.into_iter().enumerate() { - if let Some((x0, x1)) = span { - b = Some(match b { - None => Bounds { x0, y0: y, x1, y1: y + 1 }, - Some(b) => Bounds { x0: b.x0.min(x0), y0: b.y0, x1: b.x1.max(x1), y1: y + 1 }, - }); - } - } - b -} - -/// Valid source centres: the whole `2r+1` patch inside the grid and copyable. Found per row -/// (each pixel's horizontal run), then per column of runs. `None` when cancelled. -fn valid_sources(w: usize, h: usize, r: usize, px: &[Px], ctl: &photocraft_raster::Interrupt) -> Option> { - const BAND: usize = 64; - let side = 2 * r + 1; - let par = w * h >= PAR_MIN; - let mut run = vec![false; w * h]; - if w < side || h < side { - return Some(run); - } - // Per row: is the run of `side` pixels centred on each one all copyable (a sliding count)? - par::chunks_mut(&mut run, w, par, |y, out| { - if y % BAND == 0 && ctl.cancelled() { - return; - } - let row = &px[y * w..(y + 1) * w]; - let copyable = |x: usize| usize::from(row[x] == Px::Source); - let mut count: usize = (0..side).map(copyable).sum(); - out[r] = count == side; - for (x, o) in out.iter_mut().enumerate().take(w - r).skip(r + 1) { - count = count + copyable(x + r) - copyable(x - r - 1); - *o = count == side; - } - }); - if ctl.cancelled() { - return None; - } - // Per column, in bands of rows: how many such runs end each row in a row; a centre is valid - // where `side` of them stack up to `r` rows below it. - let mut valid = vec![false; w * h]; - par::chunks_mut(&mut valid, BAND * w, par, |band, out| { - if ctl.cancelled() { - return; - } - let (y0, rows) = (band * BAND, out.len() / w); - let mut stack = vec![0usize; w]; - for yy in y0.saturating_sub(r)..(y0 + rows + r).min(h) { - for (x, n) in stack.iter_mut().enumerate() { - *n = if run[yy * w + x] { *n + 1 } else { 0 }; - } - // `yy` is the bottom row of centre `y`'s patch. - if yy < y0 + r || yy < 2 * r { - continue; - } - let y = yy - r; - for (v, n) in out[(y - y0) * w..(y - y0 + 1) * w].iter_mut().zip(&stack).take(w - r).skip(r) { - *v = *n >= side; - } - } - }); - if ctl.cancelled() { - return None; - } - Some(valid) -} - -/// Columns per block of [`Sources`]' index. -const SOURCE_BLOCK: usize = 64; - -/// The valid source centres in row-major order, indexed by counts per row and per block of -/// [`SOURCE_BLOCK`] columns (so the `k`-th is found without listing them all). -struct Sources { - /// Valid centres before each row (`h + 1` entries). - row_start: Vec, - /// Per row, the valid centres in it before each block. - block_start: Vec, - blocks: usize, -} - -impl Sources { - fn new(valid: &[bool], w: usize) -> Sources { - let h = valid.len().checked_div(w).unwrap_or(0); - let blocks = w.div_ceil(SOURCE_BLOCK); - let mut block_start = vec![0u32; h * blocks]; - // Per row: the block prefix, and the row's count. - let counts: Vec = par::map(h, valid.len() >= PAR_MIN, |y| valid[y * w..(y + 1) * w].iter().filter(|v| **v).count()); - par::chunks_mut(&mut block_start, blocks, valid.len() >= PAR_MIN, |y, out| { - let mut n = 0u32; - for (b, o) in out.iter_mut().enumerate() { - *o = n; - n += valid[y * w + b * SOURCE_BLOCK..y * w + ((b + 1) * SOURCE_BLOCK).min(w)].iter().filter(|v| **v).count() as u32; - } - }); - let mut row_start = Vec::with_capacity(counts.len() + 1); - let mut total = 0usize; - row_start.push(0); - for c in counts { - total += c; - row_start.push(total); - } - Sources { row_start, block_start, blocks } - } - - fn len(&self) -> usize { - self.row_start.last().copied().unwrap_or(0) - } - - /// The `k`-th valid centre in row-major order (`k < len`). - fn nth(&self, k: usize, valid: &[bool], w: usize) -> (i32, i32) { - let y = self.row_start.partition_point(|&s| s <= k).saturating_sub(1); - let left = k.saturating_sub(self.row_start.get(y).copied().unwrap_or(0)); - let row_blocks = self.block_start.get(y * self.blocks..(y + 1) * self.blocks).unwrap_or(&[]); - let b = row_blocks.partition_point(|&s| s as usize <= left).saturating_sub(1); - let mut left = left.saturating_sub(row_blocks.get(b).copied().unwrap_or(0) as usize); - let x0 = b * SOURCE_BLOCK; - for (x, v) in valid.iter().skip(y * w + x0).take(w.saturating_sub(x0)).enumerate() { - if *v { - if left == 0 { - return ((x0 + x) as i32, y as i32); - } - left -= 1; - } - } - (0, 0) - } - - /// All of them, in row-major order. - fn all(&self, valid: &[bool], w: usize) -> Vec<(i32, i32)> { - let mut out = Vec::with_capacity(self.len()); - for (i, v) in valid.iter().enumerate() { - if *v { - out.push(((i % w) as i32, (i / w) as i32)); - } - } - out - } -} - -/// Per cell of `tb` (the hole's bounds `hb` grown by the patch radius, where all of them lie): is -/// it a target centre (its patch overlaps the hole)? -fn targets_around(w: usize, r: usize, px: &[Px], hb: Bounds, tb: Bounds) -> Vec { - // Hole counts summed over the hole's bounds: every hole pixel lies inside them. - let (bw, bh) = (hb.width(), hb.height()); - let mut s = vec![0u32; (bw + 1) * (bh + 1)]; - for y in 0..bh { - let mut row = 0u32; - for x in 0..bw { - row += u32::from(px[(hb.y0 + y) * w + hb.x0 + x] == Px::Hole); - s[(y + 1) * (bw + 1) + x + 1] = s[y * (bw + 1) + x + 1] + row; - } - } - let mut targets = vec![false; tb.area()]; - let ri = r as i32; - let (ox, oy) = (hb.x0 as i32, hb.y0 as i32); - for y in tb.y0..tb.y1 { - for x in tb.x0..tb.x1 { - let k = (y - tb.y0) * tb.width() + (x - tb.x0); - let (x, y) = (x as i32, y as i32); - targets[k] = window_count(&s, bw, bh, x - ri - ox, y - ri - oy, x + ri + 1 - ox, y + ri + 1 - oy) > 0; - } - } - targets -} - -/// A finished coarser level: its size, pixels and match field (the source centre per cell of -/// its target box, `i32::MIN` where there is none; empty when it had nothing to copy). -struct Coarser { - w: usize, - h: usize, - img: Vec, - field: Vec<(i32, i32)>, - tbox: Bounds, -} - -impl Coarser { - /// The match of cell `(x, y)` (`i32::MIN` outside the target box). - fn field_at(&self, x: usize, y: usize) -> (i32, i32) { - let t = self.tbox; - if x < t.x0 || x >= t.x1 || y < t.y0 || y >= t.y1 { - return (i32::MIN, i32::MIN); - } - self.field.get((y - t.y0) * t.width() + (x - t.x0)).copied().unwrap_or((i32::MIN, i32::MIN)) - } -} - -/// Most channels whose moments the colour adaptation fits (the rest are copied as they are). -const MOM_CH: usize = 8; - -/// Per-level PatchMatch/EM state. -struct Solver<'a> { - w: usize, - h: usize, - ch: usize, - r: i32, - img: &'a mut Vec, - px: &'a [Px], - /// Valid source centres: the whole patch is inside the grid and may be copied from. - valid: Vec, - /// The hole's bounds and the targets' (the hole's grown by the patch radius): nothing outside - /// them changes or is matched. The match field, its costs and these per-target tables are - /// kept over `tbox`, row-major. - hole_box: Bounds, - tbox: Bounds, - /// Target centres (the patch overlaps the hole). - targets: Vec, - /// Per cell of `tbox`: the whole patch is inside the grid and not void (so its distances - /// need no bounds checks and its own moments can be kept). - full: Vec, - /// With colour adaptation, per cell of `tbox` and channel (at most [`MOM_CH`]): `Σt, Σt²` of - /// the patch, for full patches, as of the last [`Solver::costs`]. - tmom: Vec<[f32; 2]>, - /// With colour adaptation where it pays: per source centre and channel, `Σs, Σs²` of its - /// patch (source pixels never change within a level). Empty otherwise. - smom: Vec<[f32; 2]>, - adapt: Adapt, - /// Cancellation: checked per row band; a cancelled solve's output is discarded. - ctl: photocraft_raster::Interrupt<'a>, -} - -/// A channel deviation under which a patch counts as flat for [`fit`] (about 5 levels of 255). -const FLAT: f32 = 0.02; - -/// Gain and bias of one channel for target moments `(Σt, Σt²)` and source moments `(Σs, Σs²)` -/// over `n` samples, within the limits. -#[inline] -pub(crate) fn fit(a: Adapt, n: f32, st: f32, stt: f32, ss: f32, sss: f32) -> (f32, f32) { - let (mt, ms) = (st / n, ss / n); - let vt = (stt / n - mt * mt).max(0.0); - let vs = (sss / n - ms * ms).max(0.0); - let g = if vs > 1e-10 { (vt / vs).sqrt() } else { 1.0 }; - let (mut lo, mut hi) = a.gain; - // Nearly flat patches of about the same colour (their means within the bias of each other): - // the ratio of their deviations is noise, so match the mean first, keeping the gain where the - // bias can still bring the source's mean to the target's. Gained about zero, a gain at its - // limit moved bright means further than the bias could bring back, and each channel by a - // different amount: a tinted blotch in a smooth gradient. Textured patches, and flat ones - // whose colours differ more (Content-Aware Move's Color), are fitted as before. - if vt.max(vs) < FLAT * FLAT && (mt - ms).abs() <= a.bias && ms > 1e-6 { - let (glo, ghi) = ((mt - a.bias) / ms, (mt + a.bias) / ms); - if glo.max(lo) <= ghi.min(hi) { - (lo, hi) = (glo.max(lo), ghi.min(hi)); - } - } - let g = g.clamp(lo, hi); - let b = (mt - g * ms).clamp(-a.bias, a.bias); - (g, b) -} - -impl Solver<'_> { - #[inline] - fn is_valid(&self, x: i32, y: i32) -> bool { - x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h && self.valid[y as usize * self.w + x as usize] - } - - /// Mark the full target patches (`full`), and keep the source moments where they pay off. - fn prepare(&mut self, keep_source_moments: bool) { - let (w, h, r, tb) = (self.w, self.h, self.r as usize, self.tbox); - let side = 2 * r + 1; - let mut full = vec![false; tb.area()]; - let px = self.px; - par::chunks_mut(&mut full, tb.width(), tb.area() >= PAR_MIN_PATCHES, |ty, out| { - let y = tb.y0 + ty; - if y < r || y + r >= h { - return; - } - for (tx, f) in out.iter_mut().enumerate() { - let x = tb.x0 + tx; - if x < r || x + r >= w { - continue; - } - *f = (y - r..=y + r).all(|yy| px[yy * w + x - r..yy * w + x - r + side].iter().all(|k| *k != Px::Void)); - } - }); - self.full = full; - if self.adapt.is_none() { - return; - } - let c8 = self.ch.min(MOM_CH); - self.tmom = vec![[0.0; 2]; tb.area() * c8]; - if !keep_source_moments { - return; - } - let (ch, img, valid, ctl) = (self.ch, &*self.img, &self.valid, &self.ctl); - let mut smom = vec![[0.0f32; 2]; w * h * c8]; - par::chunks_mut(&mut smom, w * c8, w * h >= PAR_MIN_PATCHES, |y, out| { - if ctl.cancelled() { - return; - } - for x in 0..w { - if valid[y * w + x] { - patch_moments(img, w, ch, c8, side, x - r, y - r, &mut out[x * c8..(x + 1) * c8]); - } - } - }); - self.smom = smom; - } - - /// Distance between the target patch at `t` (its pixels inside the grid and not void; `k` its - /// index in the `tbox` tables) and the source patch at `s`, per sample; with colour adaptation - /// the source is fitted first. - #[inline] - fn dist(&self, t: (i32, i32), k: usize, s: (i32, i32), cutoff: f32) -> f32 { - let full = self.full[k]; - if !self.adapt.is_none() { - return if full { self.dist_adapted_full(k, t, s) } else { self.dist_adapted(t, s) }; - } - if full { self.dist_full(t, s, cutoff) } else { self.dist_clipped(t, s, cutoff) } - } - - /// [`Solver::dist`] without adaptation, of a patch that may be clipped. - fn dist_clipped(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 { - let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r); - let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32; - let mut sum = 0.0f32; - let mut n = 0usize; - for dy in -r..=r { - let ty = t.1 + dy; - if ty < 0 || ty >= h { - continue; - } - let sy = s.1 + dy; - for dx in -r..=r { - let tx = t.0 + dx; - if tx < 0 || tx >= w || self.px[ty as usize * self.w + tx as usize] == Px::Void { - continue; - } - let ti = (ty as usize * self.w + tx as usize) * ch; - let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch; - for c in 0..ch { - let d = self.img[ti + c] - self.img[si + c]; - sum += d * d; - } - n += ch; - } - // Early out: the mean can only be ≥ sum / (full patch size). - if sum > cutoff * full { - return f32::INFINITY; - } - } - if n == 0 { f32::INFINITY } else { sum / n as f32 } - } - - /// [`Solver::dist_clipped`] of a full patch: the same sums, in the same order. It gives up - /// (infinity) as soon as the sum shows the patch is worse than `cutoff`, which the sum, only - /// growing, can show after any pixel: the caller only asks whether it is better. - fn dist_full(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 { - let (w, ch, r) = (self.w, self.ch, self.r); - let side = (2 * r + 1) as usize; - let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32; - let (span, limit) = (side * ch, cutoff * full); - let mut sum = 0.0f32; - for dy in -r..=r { - let ti = ((t.1 + dy) as usize * w + (t.0 - r) as usize) * ch; - let si = ((s.1 + dy) as usize * w + (s.0 - r) as usize) * ch; - for (tp, sp) in self.img[ti..ti + span].chunks_exact(ch).zip(self.img[si..si + span].chunks_exact(ch)) { - for (a, b) in tp.iter().zip(sp) { - let d = a - b; - sum += d * d; - } - if sum > limit { - return f32::INFINITY; - } - } - } - sum / (side * side * ch) as f32 - } - - /// Moments of the target patch at `t` and the source patch at `s` per channel: - /// `[Σt, Σt², Σs, Σs², Σts]`, and the sample count. - fn moments(&self, t: (i32, i32), s: (i32, i32), m: &mut [[f32; 5]]) -> usize { - let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r); - m.iter_mut().for_each(|v| *v = [0.0; 5]); - let mut n = 0usize; - for dy in -r..=r { - let ty = t.1 + dy; - if ty < 0 || ty >= h { - continue; - } - let sy = s.1 + dy; - for dx in -r..=r { - let tx = t.0 + dx; - if tx < 0 || tx >= w || self.px[ty as usize * self.w + tx as usize] == Px::Void { - continue; - } - let ti = (ty as usize * self.w + tx as usize) * ch; - let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch; - for (c, mc) in m.iter_mut().enumerate().take(ch) { - let (a, b) = (self.img[ti + c], self.img[si + c]); - mc[0] += a; - mc[1] += a * a; - mc[2] += b; - mc[3] += b * b; - mc[4] += a * b; - } - n += 1; - } - } - n - } - - /// [`Solver::moments`] of a full target patch (`k` in the `tbox` tables): the target's own - /// sums kept from [`Solver::costs`], the source's from [`Solver::prepare`] when kept, each - /// summed in the same order as there. - fn moments_full(&self, k: usize, t: (i32, i32), s: (i32, i32), m: &mut [[f32; 5]]) { - let (w, ch, r) = (self.w, self.ch, self.r); - let c8 = m.len(); - let side = (2 * r + 1) as usize; - let tm = &self.tmom[k * c8..(k + 1) * c8]; - let sm = self.smom.get((s.1 as usize * w + s.0 as usize) * c8..(s.1 as usize * w + s.0 as usize + 1) * c8); - let mut acc = [[0.0f32; 3]; MOM_CH]; - for dy in -r..=r { - let ti = ((t.1 + dy) as usize * w + (t.0 - r) as usize) * ch; - let si = ((s.1 + dy) as usize * w + (s.0 - r) as usize) * ch; - let (trow, srow) = (&self.img[ti..ti + side * ch], &self.img[si..si + side * ch]); - if sm.is_some() { - for (tp, sp) in trow.chunks_exact(ch).zip(srow.chunks_exact(ch)) { - for c in 0..c8 { - acc[c][2] += tp[c] * sp[c]; - } - } - } else { - for (tp, sp) in trow.chunks_exact(ch).zip(srow.chunks_exact(ch)) { - for c in 0..c8 { - let (a, b) = (tp[c], sp[c]); - acc[c][0] += b; - acc[c][1] += b * b; - acc[c][2] += a * b; - } - } - } - } - for (c, mc) in m.iter_mut().enumerate() { - let [ss, sss] = match sm { - Some(sm) => sm[c], - None => [acc[c][0], acc[c][1]], - }; - *mc = [tm[c][0], tm[c][1], ss, sss, acc[c][2]]; - } - } - - fn dist_adapted(&self, t: (i32, i32), s: (i32, i32)) -> f32 { - let mut m = [[0.0f32; 5]; MOM_CH]; - let ch = self.ch.min(MOM_CH); - let n = self.moments(t, s, &mut m[..ch]); - if n == 0 { - return f32::INFINITY; - } - adapted_cost(self.adapt, n as f32, &m[..ch]) - } - - fn dist_adapted_full(&self, k: usize, t: (i32, i32), s: (i32, i32)) -> f32 { - let mut m = [[0.0f32; 5]; MOM_CH]; - let ch = self.ch.min(MOM_CH); - self.moments_full(k, t, s, &mut m[..ch]); - let side = (2 * self.r + 1) as usize; - adapted_cost(self.adapt, (side * side) as f32, &m[..ch]) - } - - /// Gain and bias per channel for the match `t → s` (identity without adaptation). - fn transform(&self, t: (i32, i32), k: usize, s: (i32, i32), out: &mut [(f32, f32)]) { - if self.adapt.is_none() { - out.iter_mut().for_each(|v| *v = (1.0, 0.0)); - return; - } - let mut m = [[0.0f32; 5]; MOM_CH]; - let ch = self.ch.min(MOM_CH); - let n = if self.full[k] { - self.moments_full(k, t, s, &mut m[..ch]); - let side = (2 * self.r + 1) as usize; - side * side - } else { - self.moments(t, s, &mut m[..ch]) - }; - for (c, o) in out.iter_mut().enumerate() { - *o = if n == 0 || c >= ch { (1.0, 0.0) } else { fit(self.adapt, n as f32, m[c][0], m[c][1], m[c][2], m[c][3]) }; - } - } - - /// One PatchMatch step at target `t` (`k` in the target box) whose match is `cur`: propagation - /// from the matches of the neighbours visited just before it (`left` in its row, `up` in its - /// column, in this pass's direction `step`), then random search in exponentially shrinking - /// windows around the best (two numbers from `rng` per window). - #[allow(clippy::too_many_arguments)] - #[inline] - fn pm_step( - &self, - t: (i32, i32), - k: usize, - cur: ((i32, i32), f32), - left: Option<(i32, i32)>, - up: Option<(i32, i32)>, - step: i32, - rng: &mut Rng, - search_radius: i32, - ) -> ((i32, i32), f32) { - let (mut best, mut bc) = cur; - if let Some(c) = left { - let cand = (c.0 + step, c.1); - if self.is_valid(cand.0, cand.1) && cand != best { - let d = self.dist(t, k, cand, bc); - if d < bc { - (best, bc) = (cand, d); - } - } - } - if let Some(c) = up { - let cand = (c.0, c.1 + step); - if self.is_valid(cand.0, cand.1) && cand != best { - let d = self.dist(t, k, cand, bc); - if d < bc { - (best, bc) = (cand, d); - } - } - } - let mut rad = search_radius; - while rad >= 1 { - let cand = (best.0 + rng.range(-rad, rad), best.1 + rng.range(-rad, rad)); - if self.is_valid(cand.0, cand.1) && cand != best { - let d = self.dist(t, k, cand, bc); - if d < bc { - (best, bc) = (cand, d); - } - } - rad /= 2; - } - (best, bc) - } - - /// One PatchMatch pass over all target rows, in bands of the grid's rows: each band is - /// visited in raster order (backwards on odd passes), propagating within itself, its random - /// numbers seeded by its index. `nnf` and `cost` are over the target box. The bands run in - /// parallel; when there are fewer of them than threads, each is also swept in wavefronts of - /// blocks (a cell depends only on its neighbours before it in its row and its column), which - /// visits every cell with the same neighbours and random numbers as the raster order. - fn patchmatch(&self, nnf: &mut [(i32, i32)], cost: &mut [f32], pass: usize, seed: u64, search_radius: i32) { - const BAND: usize = 16; - let tb = self.tbox; - let tw = tb.width(); - if tw == 0 || tb.height() == 0 || nnf.len() < tb.area() || cost.len() < tb.area() { - return; - } - let reverse = pass % 2 == 1; - let step: i32 = if reverse { -1 } else { 1 }; - let band_seed = |bi: usize| seed ^ (bi as u64).wrapping_mul(0x2545_F491_4F6C_DD1D) ^ ((pass as u64) << 40); - // The bands crossing the target box: index, first row, rows in the box. - let mut bands = Vec::new(); - let mut y = tb.y0; - while y < tb.y1 { - let bi = y / BAND; - let end = ((bi + 1) * BAND).min(tb.y1); - bands.push((bi, y, end - y)); - y = end; - } - let threads = par::threads(); - if tb.area() >= PAR_MIN_PATCHES * 8 && !bands.is_empty() && bands.len() < threads { - self.patchmatch_wavefront(nnf, cost, &bands, reverse, &band_seed, search_radius); - return; - } - let band_fn = |bi: usize, ys: usize, nn: &mut [(i32, i32)], co: &mut [f32]| { - if self.ctl.cancelled() { - return; - } - let rows = nn.len() / tw; - let mut rng = Rng::new(band_seed(bi)); - for ry in 0..rows { - if self.ctl.cancelled() { - return; - } - let ly = if reverse { rows - 1 - ry } else { ry }; - let y = ys + ly; - for rx in 0..tw { - let lx = if reverse { tw - 1 - rx } else { rx }; - let li = ly * tw + lx; - let k = (y - tb.y0) * tw + lx; - if !self.targets[k] { - continue; - } - // Neighbours outside the target box hold no match: nothing to try. - let nx = lx as i32 - step; - let left = (nx >= 0 && (nx as usize) < tw).then(|| nn[ly * tw + nx as usize]); - let nly = ly as i32 - step; - let up = (nly >= 0 && (nly as usize) < rows).then(|| nn[nly as usize * tw + lx]); - let t = ((tb.x0 + lx) as i32, y as i32); - (nn[li], co[li]) = self.pm_step(t, k, (nn[li], co[li]), left, up, step, &mut rng, search_radius); - } - } - }; - // The target box's rows, band by band. - let mut parts = Vec::with_capacity(bands.len()); - let (mut nn_rest, mut co_rest) = (&mut nnf[..tb.area()], &mut cost[..tb.area()]); - for &(bi, ys, rows) in &bands { - let (nn, nr) = std::mem::take(&mut nn_rest).split_at_mut(rows * tw); - let (co, cr) = std::mem::take(&mut co_rest).split_at_mut(rows * tw); - parts.push((bi, ys, nn, co)); - (nn_rest, co_rest) = (nr, cr); - } - let par = tb.area() >= PAR_MIN_PATCHES && parts.len() > 1; - par::each(parts, par, |(bi, ys, nn, co)| band_fn(bi, ys, nn, co)); - } - - /// [`Solver::patchmatch`] swept in wavefronts: the cells of each band in blocks of a row, a - /// block once the block before it in its row and the one above it (in the pass's direction) - /// are done. A target's random numbers are those it would draw in raster order (each target - /// draws the same count). - fn patchmatch_wavefront( - &self, - nnf: &mut [(i32, i32)], - cost: &mut [f32], - bands: &[(usize, usize, usize)], - reverse: bool, - band_seed: &(dyn Fn(usize) -> u64 + Sync), - search_radius: i32, - ) { - use std::sync::atomic::{AtomicU32, AtomicU64, Ordering::Relaxed}; - - let tb = self.tbox; - let tw = tb.width(); - let step: i32 = if reverse { -1 } else { 1 }; - let pack = |(x, y): (i32, i32)| (u64::from(x as u32) << 32) | u64::from(y as u32); - let unpack = |v: u64| ((v >> 32) as u32 as i32, v as u32 as i32); - // Random numbers each target draws. - let mut draws = 0u64; - let mut rad = search_radius; - while rad >= 1 { - draws += 2; - rad /= 2; - } - // Targets before each column of each row of the box. - let mut before = vec![0u32; tb.height() * (tw + 1)]; - for (ry, row) in before.chunks_mut(tw + 1).enumerate() { - for lx in 0..tw { - row[lx + 1] = row[lx] + u32::from(self.targets[ry * tw + lx]); - } - } - // Targets visited before each of a band's rows (in the pass's order). - let row_base: Vec> = bands - .iter() - .map(|&(_, ys, rows)| { - let mut base = Vec::with_capacity(rows); - let mut n = 0u64; - for pr in 0..rows { - base.push(n); - let ly = if reverse { rows - 1 - pr } else { pr }; - n += u64::from(before[(ys + ly - tb.y0) * (tw + 1) + tw]); - } - base - }) - .collect(); - let block = (tw / 8).clamp(4, 32); - let blocks = tw.div_ceil(block); - let nn: Vec = nnf[..tb.area()].iter().map(|m| AtomicU64::new(pack(*m))).collect(); - let co: Vec = cost[..tb.area()].iter().map(|c| AtomicU32::new(c.to_bits())).collect(); - let sweep = |(j, pr, b): (usize, usize, usize)| { - let (bi, ys, rows) = bands[j]; - let ly = if reverse { rows - 1 - pr } else { pr }; - let y = ys + ly; - let ry = y - tb.y0; - let (pc0, pc1) = (b * block, ((b + 1) * block).min(tw)); - // The targets visited before this block, in raster order. - let first = if reverse { tw - 1 - pc0 } else { pc0 }; - let row = &before[ry * (tw + 1)..(ry + 1) * (tw + 1)]; - let in_row = if reverse { row[tw] - row[first + 1] } else { row[first] }; - let mut rng = Rng::new(band_seed(bi)); - rng.skip((row_base[j][pr] + u64::from(in_row)) * draws); - for pc in pc0..pc1 { - let lx = if reverse { tw - 1 - pc } else { pc }; - let k = ry * tw + lx; - if !self.targets[k] { - continue; - } - let nx = lx as i32 - step; - let left = (nx >= 0 && (nx as usize) < tw).then(|| unpack(nn[ry * tw + nx as usize].load(Relaxed))); - let nly = ly as i32 - step; - let up = (nly >= 0 && (nly as usize) < rows).then(|| unpack(nn[(ys + nly as usize - tb.y0) * tw + lx].load(Relaxed))); - let cur = (unpack(nn[k].load(Relaxed)), f32::from_bits(co[k].load(Relaxed))); - let t = ((tb.x0 + lx) as i32, y as i32); - let (m, c) = self.pm_step(t, k, cur, left, up, step, &mut rng, search_radius); - nn[k].store(pack(m), Relaxed); - co[k].store(c.to_bits(), Relaxed); - } - }; - // Wavefront `d`: block `b` of (visited) row `pr` with `pr + b = d`, in every band. Each - // wave ends before the next starts. - let longest = bands.iter().map(|b| b.2).max().unwrap_or(0); - for d in 0..longest + blocks - 1 { - if self.ctl.cancelled() { - return; - } - let wave: Vec<(usize, usize, usize)> = bands - .iter() - .enumerate() - .flat_map(|(j, &(_, _, rows))| (0..rows).filter(move |&pr| pr <= d && d - pr < blocks).map(move |pr| (j, pr, d - pr))) - .collect(); - par::each(wave, true, sweep); - } - for (m, a) in nnf.iter_mut().zip(&nn) { - *m = unpack(a.load(Relaxed)); - } - for (c, a) in cost.iter_mut().zip(&co) { - *c = f32::from_bits(a.load(Relaxed)); - } - } - - /// Recompute every target's match cost (hole pixels change between iterations), and with - /// colour adaptation the full target patches' own moments. - fn costs(&mut self, nnf: &[(i32, i32)], cost: &mut [f32]) -> Result<(), photocraft_raster::Cancelled> { - let (w, ch, r, tb) = (self.w, self.ch, self.r as usize, self.tbox); - let par = tb.area() >= PAR_MIN_PATCHES; - self.ctl.check()?; - if !self.adapt.is_none() { - let c8 = ch.min(MOM_CH); - let side = 2 * r + 1; - let mut tmom = std::mem::take(&mut self.tmom); - let (img, full, ctl) = (&*self.img, &self.full, &self.ctl); - par::chunks_mut(&mut tmom, tb.width() * c8, par, |ty, out| { - if ctl.cancelled() { - return; - } - for tx in 0..tb.width() { - if full[ty * tb.width() + tx] { - patch_moments(img, w, ch, c8, side, tb.x0 + tx - r, tb.y0 + ty - r, &mut out[tx * c8..(tx + 1) * c8]); - } - } - }); - self.tmom = tmom; - } - let this = &*self; - par::chunks_mut(cost, tb.width(), par, |ty, co| { - if this.ctl.cancelled() { - return; - } - let y = tb.y0 + ty; - for (tx, c) in co.iter_mut().enumerate() { - let k = ty * tb.width() + tx; - if this.targets[k] { - *c = this.dist(((tb.x0 + tx) as i32, y as i32), k, nnf[k], f32::INFINITY); - } - } - }); - self.ctl.check() - } - - /// Re-estimate hole pixels by a similarity-weighted vote of all overlapping patch matches - /// (each copy adjusted by its gain and bias). - fn vote(&mut self, nnf: &[(i32, i32)], cost: &[f32]) { - let (w, h, ch, r) = (self.w, self.h, self.ch, self.r); - let (tb, hb) = (self.tbox, self.hole_box); - // A cancelled solve is thrown away. - if self.ctl.cancelled() { - return; - } - let used = |k: usize| self.targets[k] && cost[k].is_finite(); - // σ² from the 75th percentile of match costs (Wexler et al. use a robust scale like this). - let cs: Vec = (0..tb.area()).filter(|&k| used(k)).map(|k| cost[k]).collect(); - let mut cs = cs; - let sigma2 = if cs.is_empty() { - 1.0 - } else { - let k = (cs.len() * 3 / 4).min(cs.len() - 1); - let (_, v, _) = cs.select_nth_unstable_by(k, |a, b| a.total_cmp(b)); - v.max(1e-6) - }; - drop(cs); - // Each target's weight and photometric transform (computed once, used by every pixel it - // covers). - let adapted = !self.adapt.is_none(); - let par = tb.area() >= PAR_MIN_PATCHES; - // A weight (zero for a target that doesn't vote) and its match's centre (as a pixel - // index) per target. - let mut wt = vec![0.0f32; tb.area()]; - let mut src = vec![0isize; tb.area()]; - par::chunks2_mut(&mut wt, tb.width(), &mut src, tb.width(), par, |ty, wrow, srow| { - for (tx, (o, sc)) in wrow.iter_mut().zip(srow.iter_mut()).enumerate() { - let k = ty * tb.width() + tx; - if used(k) { - *o = (-cost[k] / (2.0 * sigma2)).exp().max(1e-8); - *sc = nnf[k].1 as isize * w as isize + nnf[k].0 as isize; - } - } - }); - let mut gb: Vec<(f32, f32)> = Vec::new(); - if adapted { - gb = vec![(1.0f32, 0.0f32); tb.area() * ch]; - let this = &*self; - par::chunks_mut(&mut gb, tb.width() * ch, par, |ty, out| { - if this.ctl.cancelled() { - return; - } - let y = tb.y0 + ty; - for tx in 0..tb.width() { - let k = ty * tb.width() + tx; - if used(k) { - this.transform(((tb.x0 + tx) as i32, y as i32), k, nnf[k], &mut out[tx * ch..(tx + 1) * ch]); - } - } - }); - } - // The vote, into a buffer over the hole's bounds (every pixel reads the old pixels). - let votes = Votes { w, h, ch, r: r as usize, tbox: tb, img: &*self.img, wt: &wt, src: &src, gb: &gb }; - let (px, ctl) = (self.px, &self.ctl); - let mut out = vec![0.0f32; hb.area() * ch]; - let mut got = vec![false; hb.area()]; - let row = |yy: usize, orow: &mut [f32], grow: &mut [bool]| { - if ctl.cancelled() { - return; - } - let y = hb.y0 + yy; - for x in hb.x0..hb.x1 { - if px[y * w + x] != Px::Hole { - continue; - } - let o = (x - hb.x0) * ch; - let dst = &mut orow[o..o + ch]; - grow[x - hb.x0] = match (ch, adapted) { - (1, false) => votes.pixel::<1, false>(x, y, dst), - (3, false) => votes.pixel::<3, false>(x, y, dst), - (4, false) => votes.pixel::<4, false>(x, y, dst), - (1, true) => votes.pixel::<1, true>(x, y, dst), - (3, true) => votes.pixel::<3, true>(x, y, dst), - (4, true) => votes.pixel::<4, true>(x, y, dst), - _ => votes.pixel_any(x, y, adapted, dst), - }; - } - }; - par::chunks2_mut(&mut out, hb.width() * ch, &mut got, hb.width(), hb.area() >= PAR_MIN_PATCHES, row); - for yy in 0..hb.height() { - for xx in 0..hb.width() { - if got[yy * hb.width() + xx] { - let (d, s) = (((hb.y0 + yy) * w + hb.x0 + xx) * ch, (yy * hb.width() + xx) * ch); - self.img[d..d + ch].copy_from_slice(&out[s..s + ch]); - } - } - } - } -} - -/// What [`Solver::vote`] votes with: per target (over the target box) its weight (zero when it -/// doesn't vote), its match's centre as a pixel index, and with colour adaptation its gain and -/// bias per channel. -struct Votes<'a> { - w: usize, - h: usize, - ch: usize, - r: usize, - tbox: Bounds, - img: &'a [f32], - wt: &'a [f32], - src: &'a [isize], - gb: &'a [(f32, f32)], -} - -impl Votes<'_> { - /// Hole pixel `(x, y)`'s vote into `out` (`CH` channels): the weighted mean of what the - /// matches of the patches covering it put there, summed patch by patch in raster order of - /// their centres. False when no patch votes. - #[inline(always)] - fn pixel(&self, x: usize, y: usize, out: &mut [f32]) -> bool { - let (w, r, tb) = (self.w, self.r, self.tbox); - let mut acc = [0.0f32; CH]; - let mut wsum = 0.0f32; - for ty in y.saturating_sub(r)..=(y + r).min(self.h - 1) { - let dy = ty as isize - y as isize; - let krow = (ty - tb.y0) * tb.width(); - for tx in x.saturating_sub(r)..=(x + r).min(w - 1) { - let k = krow + tx - tb.x0; - let wt = self.wt[k]; - if wt == 0.0 { - continue; - } - // The pixel of the match's patch that lands here. - let si = (self.src[k] - dy * w as isize - (tx as isize - x as isize)) as usize * CH; - let s = &self.img[si..si + CH]; - for c in 0..CH { - let v = if ADAPT { - let (g, b) = self.gb[k * CH + c]; - g * s[c] + b - } else { - s[c] - }; - acc[c] += v * wt; - } - wsum += wt; - } - } - if wsum > 0.0 { - for (d, a) in out.iter_mut().zip(&acc) { - *d = a / wsum; - } - return true; - } - false - } - - /// [`Votes::pixel`] for any number of channels. - fn pixel_any(&self, x: usize, y: usize, adapted: bool, out: &mut [f32]) -> bool { - let (w, r, tb, ch) = (self.w, self.r, self.tbox, self.ch); - let mut acc = vec![0.0f32; ch]; - let mut wsum = 0.0f32; - for ty in y.saturating_sub(r)..=(y + r).min(self.h - 1) { - let dy = ty as isize - y as isize; - let krow = (ty - tb.y0) * tb.width(); - for tx in x.saturating_sub(r)..=(x + r).min(w - 1) { - let k = krow + tx - tb.x0; - let wt = self.wt[k]; - if wt == 0.0 { - continue; - } - let si = (self.src[k] - dy * w as isize - (tx as isize - x as isize)) as usize * ch; - for (c, a) in acc.iter_mut().enumerate() { - let v = if adapted { - let (g, b) = self.gb[k * ch + c]; - g * self.img[si + c] + b - } else { - self.img[si + c] - }; - *a += v * wt; - } - wsum += wt; - } - } - if wsum > 0.0 { - for (d, a) in out.iter_mut().zip(&acc) { - *d = a / wsum; - } - return true; - } - false - } -} - -/// `Σv, Σv²` per channel (the first `out.len()`) of the `side × side` patch with top-left -/// `(x0, y0)`, summed row by row, pixel by pixel, as [`Solver::moments`] does. -#[allow(clippy::too_many_arguments)] -fn patch_moments(img: &[f32], w: usize, ch: usize, c8: usize, side: usize, x0: usize, y0: usize, out: &mut [[f32; 2]]) { - out.iter_mut().for_each(|v| *v = [0.0; 2]); - for y in y0..y0 + side { - let row = &img[(y * w + x0) * ch..(y * w + x0 + side) * ch]; - for p in row.chunks_exact(ch) { - for (c, o) in out.iter_mut().enumerate().take(c8) { - let a = p[c]; - o[0] += a; - o[1] += a * a; - } - } - } -} - -/// The adapted distance from the moments `[Σt, Σt², Σs, Σs², Σts]` of each channel over `n` -/// samples: what is left of the target after the source is fitted to it, per sample. -#[inline] -fn adapted_cost(a: Adapt, nf: f32, m: &[[f32; 5]]) -> f32 { - let mut sum = 0.0f32; - for mc in m { - let (g, b) = fit(a, nf, mc[0], mc[1], mc[2], mc[3]); - // Σ (t − g s − b)², expanded. - sum += mc[1] + g * g * mc[3] + nf * b * b - 2.0 * g * mc[4] - 2.0 * b * mc[0] + 2.0 * g * b * mc[2]; - } - sum.max(0.0) / (nf * m.len() as f32) -} - -/// `Σ (t − s)²` over a target patch's known pixels (offsets `offs` from its centre, samples -/// `tv`, `CH` per pixel) against the source patch centred at pixel `base`, summed in that order; -/// `None` once the sum reaches `limit` (it only grows). -#[inline(always)] -fn known_sse(image: &[f32], offs: &[isize], tv: &[f32], base: isize, limit: f32) -> Option { - let mut e = 0.0f32; - for (o, t) in offs.iter().zip(tv.as_chunks::().0) { - let si = (base + o) as usize * CH; - let s = &image[si..si + CH]; - for c in 0..CH { - let d = t[c] - s[c]; - e += d * d; - } - if e >= limit { - return None; - } - } - Some(e) -} - -/// [`known_sse`] of [`LANES`] sources at once, each against its own limit (summed in step: the -/// sums are independent, so the processor overlaps them). -#[inline(always)] -fn known_sse_lanes(image: &[f32], offs: &[isize], tv: &[f32], bases: [isize; LANES], limits: [f32; LANES]) -> [Option; LANES] { - let mut e = [0.0f32; LANES]; - for (o, t) in offs.iter().zip(tv.as_chunks::().0) { - for l in 0..LANES { - let si = (bases[l] + o) as usize * CH; - let s = &image[si..si + CH]; - for c in 0..CH { - let d = t[c] - s[c]; - e[l] += d * d; - } - } - // Sums only grow: once all of them reached their limits, none can win. - if (0..LANES).all(|l| e[l] >= limits[l]) { - break; - } - } - std::array::from_fn(|l| (e[l] < limits[l]).then_some(e[l])) -} - -/// Sources [`known_sse_lanes`] sums at once. -const LANES: usize = 4; - -/// [`known_sse`] for any number of channels. -fn known_sse_any(image: &[f32], ch: usize, offs: &[isize], tv: &[f32], base: isize, limit: f32) -> Option { - let mut e = 0.0f32; - for (o, t) in offs.iter().zip(tv.chunks_exact(ch.max(1))) { - let si = (base + o) as usize * ch; - for (tc, sc) in t.iter().zip(&image[si..si + ch]) { - let d = tc - sc; - e += d * d; - } - if e >= limit { - return None; - } - } - Some(e) -} - -/// The best source so far of [`onion_peel`]'s search. -#[derive(Clone, Copy)] -struct Best { - /// Error per sample, and the place in the sources. - v: f32, - j: usize, - /// Sums of squared errors from which `sum / n` is above `v`, and at least `v`. - worse: f32, - equal: f32, -} - -/// The least sum `e ≥ 0` with `e / n > v` (`strict`) or `e / n ≥ v` in float arithmetic (the -/// quotient only grows with `e`); infinity for an infinite `v`. -fn least_sum(v: f32, n: f32, strict: bool) -> f32 { - let holds = |e: f32| if strict { e / n > v } else { e / n >= v }; - if !v.is_finite() || !n.is_finite() || n <= 0.0 { - return f32::INFINITY; - } - let mut e = (v * n).max(0.0); - while e > 0.0 && holds(e.next_down()) { - e = e.next_down(); - } - while !holds(e) && e < f32::INFINITY { - e = e.next_up(); - } - e -} - -/// Fill the hole from its edge inwards, one ring at a time: each pixel takes the centre of the -/// source patch that best matches what is already known around it (the first in `sources` of -/// those that match best). `hb` bounds the hole. -/// -/// The search is exhaustive, but most sources are given up early (#2771, #2805): the target's -/// known pixels are gathered once, the search starts from where the pixel's filled neighbours -/// took their sources (or every 16th source at the hole's edge), and a source's error stops being -/// added up once it can only lose (it only grows). So it finds the same source as a plain scan in -/// order, sooner. -#[allow(clippy::too_many_arguments)] -fn onion_peel( - w: usize, - h: usize, - ch: usize, - r: i32, - img: &mut [f32], - px: &[Px], - hb: Bounds, - sources: &[(i32, i32)], - ctl: &photocraft_raster::Interrupt, -) -> Result<(), photocraft_raster::Cancelled> { - const NONE: u32 = u32::MAX; - let mut known: Vec = px.iter().map(|k| matches!(k, Px::Known | Px::Source)).collect(); - // Each source centre's place in `sources`, and the source each filled pixel took. - let mut index = vec![NONE; w * h]; - for (j, &(x, y)) in sources.iter().enumerate() { - index[y as usize * w + x as usize] = j as u32; - } - let mut took = vec![NONE; w * h]; - let neighbours = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]; - loop { - ctl.check()?; - let mut front: Vec = Vec::new(); - for y in hb.y0..hb.y1 { - for x in hb.x0..hb.x1 { - let i = y * w + x; - if known[i] || px[i] != Px::Hole { - continue; - } - let (x, y) = (x as i32, y as i32); - let edge = (-1..=1).any(|dy: i32| { - (-1..=1).any(|dx: i32| { - let (nx, ny) = (x + dx, y + dy); - nx >= 0 && ny >= 0 && (nx as usize) < w && (ny as usize) < h && known[ny as usize * w + nx as usize] - }) - }); - if edge { - front.push(i); - } - } - } - if front.is_empty() { - break; - } - let (known_now, took_now) = (&known, &took); - let image = &*img; - let best = |&i: &usize| -> (Vec, u32) { - let (x, y) = ((i % w) as i32, (i / w) as i32); - // The known pixels of the target patch, in the plain scan's order: each one's offset - // from the patch centre (in pixels) and its samples (gathered once, #2805). - let side = (2 * r + 1) as usize; - let mut offs: Vec = Vec::with_capacity(side * side); - let mut tv: Vec = Vec::with_capacity(side * side * ch); - for dy in -r..=r { - for dx in -r..=r { - let (tx, ty) = (x + dx, y + dy); - if tx >= 0 && ty >= 0 && (tx as usize) < w && (ty as usize) < h && known_now[ty as usize * w + tx as usize] { - let ti = (ty as usize * w + tx as usize) * ch; - offs.push(dy as isize * w as isize + dx as isize); - tv.extend_from_slice(&image[ti..ti + ch]); - } - } - } - // The best so far: its error per sample, its place in `sources` (the first of equals - // wins, as in a scan in order), and the sums of squares at which a source surely loses - // to it (`e / n` above the best) or ties it (at least the best). - let mut best = Best { v: f32::INFINITY, j: usize::MAX, worse: f32::INFINITY, equal: f32::INFINITY }; - if !offs.is_empty() { - let nf = offs.len() as f32; - let base_of = |j: usize| sources.get(j).map_or(0, |&(sx, sy)| sy as isize * w as isize + sx as isize); - // The sum at which source `j` can't win: a tie loses to an earlier source. - let limit_of = |j: usize, best: &Best| if j > best.j { best.equal } else { best.worse }; - // Source `j`'s whole sum `e` (it did not reach its limit): does it win? - let adopt = |j: usize, e: f32, best: &mut Best| { - let v = e / nf; - if v < f32::INFINITY && (v < best.v || (v == best.v && j < best.j)) { - *best = Best { v, j, worse: least_sum(v, nf, true), equal: least_sum(v, nf, false) }; - } - }; - let consider = |j: usize, best: &mut Best| { - if j >= sources.len() { - return; - } - let (base, limit) = (base_of(j), limit_of(j, best)); - let e = match ch { - 1 => known_sse::<1>(image, &offs, &tv, base, limit), - 3 => known_sse::<3>(image, &offs, &tv, base, limit), - 4 => known_sse::<4>(image, &offs, &tv, base, limit), - _ => known_sse_any(image, ch, &offs, &tv, base, limit), - }; - if let Some(e) = e { - adopt(j, e, best); - } - }; - // A close bound early: where the filled neighbours' sources point (shifted as in - // PatchMatch's propagation), or at the hole's edge, where none is filled yet, - // every 16th source. - for (dx, dy) in neighbours { - let (qx, qy) = (x + dx, y + dy); - if qx < 0 || qy < 0 || qx as usize >= w || qy as usize >= h { - continue; - } - let Some(&(sx, sy)) = sources.get(took_now[qy as usize * w + qx as usize] as usize) else { continue }; - let (cx, cy) = (sx - dx, sy - dy); - if cx >= 0 && cy >= 0 && (cx as usize) < w && (cy as usize) < h && index[cy as usize * w + cx as usize] != NONE { - consider(index[cy as usize * w + cx as usize] as usize, &mut best); - } - } - if best.j == usize::MAX { - for j in (0..sources.len()).step_by(16) { - consider(j, &mut best); - } - } - // The scan in order, `LANES` sources at a time (their sums are independent, so they - // overlap), each against its limit from the best before them: the best only gets - // better, so a source given up would have lost to it anyway. - let mut j = 0; - while j + LANES <= sources.len() { - if j.is_multiple_of(4096) && j > 0 && ctl.cancelled() { - break; - } - let bases: [isize; LANES] = std::array::from_fn(|l| base_of(j + l)); - let limits: [f32; LANES] = std::array::from_fn(|l| limit_of(j + l, &best)); - let sums = match ch { - 1 => known_sse_lanes::<1>(image, &offs, &tv, bases, limits), - 3 => known_sse_lanes::<3>(image, &offs, &tv, bases, limits), - 4 => known_sse_lanes::<4>(image, &offs, &tv, bases, limits), - _ => std::array::from_fn(|l| known_sse_any(image, ch, &offs, &tv, bases[l], limits[l])), - }; - for (l, e) in sums.into_iter().enumerate() { - if let Some(e) = e { - adopt(j + l, e, &mut best); - } - } - j += LANES; - } - for j in j..sources.len() { - consider(j, &mut best); - } - } - let (sx, sy) = sources.get(best.j).copied().unwrap_or((0, 0)); - let si = (sy as usize * w + sx as usize) * ch; - (image[si..si + ch].to_vec(), if best.j == usize::MAX { NONE } else { best.j as u32 }) - }; - let vals: Vec<(Vec, u32)> = par::map(front.len(), front.len() * sources.len() >= 4096, |k| best(&front[k])); - ctl.check()?; - for (&i, (v, j)) in front.iter().zip(vals) { - img[i * ch..(i + 1) * ch].copy_from_slice(&v); - known[i] = true; - took[i] = j; - } - } - Ok(()) -} - /// Content-aware completion of `hole` (see module docs), copying from any pixel outside it. Returns /// `None` when there is no fully-known patch to copy from (the caller can fall back to /// [`membrane_fill`]). @@ -1820,217 +370,5 @@ fn complete_cow<'a>( Ok(prev.map(|c| c.img).ok_or(Cow::Owned(Vec::new()))) } -/// Proximity match: the displacement `(dx, dy)` (within `max_radius`) whose surroundings best match the -/// ring of `ring` pixels around the hole, with the displaced hole fully inside the grid and outside the -/// hole. `None` if no displacement fits. -pub fn best_offset(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], ring: usize, max_radius: i32) -> Option<(i32, i32)> { - let (bx0, by0, bx1, by1) = hole_bbox(w, h, hole)?; - // No valid translation can move farther than the source image's extent. - // Bound arbitrary public API inputs before constructing i32 search ranges: - // usize -> i32 truncation and signed increments otherwise overflow or hang. - let extent = w.max(h).min((i32::MAX / 4) as usize) as i32; - let max_radius = max_radius.max(0).min(extent); - if max_radius == 0 { - return None; - } - let ring = ring.max(1).min(extent as usize) as i32; - // Every set cell lies in the hole bounds. Counts outside that rectangle are zero, - // so source rejection needs a table for the hole, not for the whole photo. - let hs = HoleIntegral::new(w, hole, (bx0, by0, bx1, by1))?; - // Sample points: the hole's ring (dilated minus hole), subsampled for speed. - let mut pts = Vec::new(); - let (x0, y0) = (bx0 as i32 - ring, by0 as i32 - ring); - let (x1, y1) = (bx1 as i32 + ring, by1 as i32 + ring); - for y in y0.max(0)..y1.min(h as i32) { - for x in x0.max(0)..x1.min(w as i32) { - if hole[y as usize * w + x as usize] { - continue; - } - if hs.count(x - ring, y - ring, x + ring + 1, y + ring + 1) > 0 { - pts.push((x, y)); - } - } - } - let stride = (pts.len() / 2000).max(1); - let pts: Vec<(i32, i32)> = pts.into_iter().step_by(stride).collect(); - let eval = |dx: i32, dy: i32, cutoff: f32| -> Option { - let (hx0, hy0, hx1, hy1) = (x0 + dx, y0 + dy, x1 + dx, y1 + dy); - let inside = hx0 >= 0 && hy0 >= 0 && hx1 <= w as i32 && hy1 <= h as i32; - if (dx, dy) == (0, 0) || !inside || hs.count(hx0, hy0, hx1, hy1) != 0 { - return None; - } - let mut e = 0.0f32; - let n = pts.len().max(1) as f32; - let penalty = 1.0 + 1e-3 * ((dx as f32).hypot(dy as f32) / max_radius as f32); - for (i, &(x, y)) in pts.iter().enumerate() { - let (a, b) = ((y as usize * w + x as usize) * ch, ((y + dy) as usize * w + (x + dx) as usize) * ch); - for c in 0..ch { - let d = img[a + c] - img[b + c]; - e += d * d; - } - // SSD terms are nonnegative. The partial score is a lower bound on the - // final score; use the same division and penalty to keep float rounding - // and strict tie ordering unchanged. Check in batches to keep this cheap. - if i % 32 == 31 && cutoff.is_finite() && e / n * penalty >= cutoff { - return None; - } - } - // Mild preference for nearer sources on ties. - Some(e / n * penalty) - }; - // Coarse grid over the search window, then a full-resolution refinement around the winner. - let step = (max_radius / 24).max(1); - let mut best: Option<((i32, i32), f32)> = None; - let consider = |dx: i32, dy: i32, best: &mut Option<((i32, i32), f32)>| { - if let Some(e) = eval(dx, dy, best.map_or(f32::INFINITY, |(_, error)| error)) - && best.is_none_or(|(_, be)| e < be) - { - *best = Some(((dx, dy), e)); - } - }; - let mut dy = -max_radius; - while dy <= max_radius { - let mut dx = -max_radius; - while dx <= max_radius { - consider(dx, dy, &mut best); - dx += step; - } - dy += step; - } - if step > 1 - && let Some(((bx, by), _)) = best - { - for dy in (by - step)..=(by + step) { - for dx in (bx - step)..=(bx + step) { - consider(dx, dy, &mut best); - } - } - } - best.map(|b| b.0) -} - -/// Create texture: fill the hole with blocks of surrounding texture (see module docs). -pub fn synthesize(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], block: usize, seed: u64) -> Vec { - let mut out = img.to_vec(); - let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return out }; - let b = block.max(4) as i32; - let ov = (b / 3).max(1); - let hs = integral(w, h, hole); - // Candidate block origins: whole block (with overlap) inside the grid and outside the hole. - let mut cands = Vec::new(); - for y in ov..(h as i32 - b - ov) { - for x in ov..(w as i32 - b - ov) { - if window_count(&hs, w, h, x - ov, y - ov, x + b + ov, y + b + ov) == 0 { - cands.push((x, y)); - } - } - } - if cands.is_empty() { - return membrane_fill(w, h, ch, img, hole); - } - let mut filled: Vec = hole.iter().map(|x| !x).collect(); - let mut rng = Rng::new(seed); - let mut by = by0 as i32; - while by < by1 as i32 { - let mut bx = bx0 as i32; - while bx < bx1 as i32 { - if window_count(&hs, w, h, bx, by, bx + b, by + b) > 0 { - // Pick the candidate whose block best agrees with already-known pixels around/inside. - let mut best = (cands[0], f32::INFINITY); - for _ in 0..48 { - let c = cands[(rng.next() % cands.len() as u64) as usize]; - let (mut e, mut n) = (0.0f32, 0u32); - for y in (by - ov)..(by + b + ov) { - for x in (bx - ov)..(bx + b + ov) { - if x < 0 || y < 0 || x >= w as i32 || y >= h as i32 || !filled[y as usize * w + x as usize] { - continue; - } - let (a, s) = ((y as usize * w + x as usize) * ch, ((y - by + c.1) as usize * w + (x - bx + c.0) as usize) * ch); - for k in 0..ch { - let d = out[a + k] - img[s + k]; - e += d * d; - } - n += 1; - } - } - let e = if n == 0 { 0.0 } else { e / n as f32 }; - if e < best.1 { - best = (c, e); - } - } - let c = best.0; - let (x0, y0) = ((bx - ov).max(0), (by - ov).max(0)); - let (x1, y1) = ((bx + b + ov).min(w as i32), (by + b + ov).min(h as i32)); - let src = |x: i32, y: i32| ((y - by + c.1) as usize * w + (x - bx + c.0) as usize) * ch; - // Squared difference between what is there and the block, where both exist. - let err = |x: i32, y: i32| { - let i = y as usize * w + x as usize; - if !(hole[i] && filled[i]) { - return 0.0; - } - let (a, s) = (i * ch, src(x, y)); - (0..ch).map(|q| (out[a + q] - img[s + q]).powi(2)).sum::() - }; - // Minimum-error boundary cuts through the overlaps with the blocks to the left and - // above: the block is copied right of and below them, untouched pixels are kept - // on the other side. Copying (rather than averaging) keeps the texture's grain. - let left = min_cut((x0..(bx + ov).min(x1)).len(), (y0..y1).len(), |u, v| err(x0 + u as i32, y0 + v as i32)); - let top = min_cut((y0..(by + ov).min(y1)).len(), (x0..x1).len(), |u, v| err(x0 + v as i32, y0 + u as i32)); - for y in y0..y1 { - for x in x0..x1 { - let i = y as usize * w + x as usize; - if !hole[i] { - continue; - } - let (u, v) = ((x - x0) as usize, (y - y0) as usize); - let keep = filled[i] && (left.get(v).is_some_and(|s| u < *s) || top.get(u).is_some_and(|s| v < *s)); - if !keep { - let (a, s) = (i * ch, src(x, y)); - out[a..a + ch].copy_from_slice(&img[s..s + ch]); - } - filled[i] = true; - } - } - } - bx += b; - } - by += b; - } - out -} - -/// The minimum-error cut through a band `across` wide and `along` long (Efros & Freeman's -/// boundary cut, by dynamic programming): for each step along the band, the offset across it -/// where the cut runs (`err(across, along)` is the cost of a pixel). Pixels before the cut keep -/// what is there. Empty when there is no cost anywhere (nothing to cut through). -fn min_cut(across: usize, along: usize, err: impl Fn(usize, usize) -> f32) -> Vec { - if across == 0 || along == 0 { - return Vec::new(); - } - // Cumulative cost, step by step along the band; the cut may move by one pixel per step. - let mut acc: Vec = (0..along).flat_map(|v| (0..across).map(move |u| (u, v))).map(|(u, v)| err(u, v)).collect(); - if acc.iter().all(|x| *x == 0.0) { - return Vec::new(); - } - for v in 1..along { - for u in 0..across { - let lo = u.saturating_sub(1); - let hi = (u + 1).min(across - 1); - let m = (lo..=hi).map(|k| acc[(v - 1) * across + k]).fold(f32::INFINITY, f32::min); - acc[v * across + u] += m; - } - } - let argmin = |v: usize, lo: usize, hi: usize| (lo..=hi).min_by(|a, b| acc[v * across + a].total_cmp(&acc[v * across + b])).unwrap_or(lo); - let mut cut = vec![0; along]; - let mut u = argmin(along - 1, 0, across - 1); - for v in (0..along).rev() { - if v + 1 < along { - u = argmin(v, u.saturating_sub(1), (u + 1).min(across - 1)); - } - cut[v] = u; - } - cut -} - #[cfg(test)] mod tests; diff --git a/crates/algo/src/inpaint/common.rs b/crates/algo/src/inpaint/common.rs new file mode 100644 index 0000000000..bbbcc8df26 --- /dev/null +++ b/crates/algo/src/inpaint/common.rs @@ -0,0 +1,119 @@ +use super::*; + +/// Below this many cells a pass runs on the calling thread (thread hand-off costs more than it +/// saves). Every pass gives the same result either way. +pub(super) const PAR_MIN: usize = 64 * 64; + +/// [`PAR_MIN`] for the passes that match or vote a patch per cell. +pub(super) const PAR_MIN_PATCHES: usize = 16 * 16; + +/// Largest level (in cells) whose source patches' moments [`Solver::prepare`] keeps. +pub(super) const SOURCE_MOMENTS_MAX: usize = 1 << 20; + +/// SplitMix64: tiny deterministic RNG. +#[derive(Clone)] +pub(crate) struct Rng(pub(crate) u64); + +impl Rng { + /// A generator whose sequence is fixed by `seed`. + pub(crate) fn new(seed: u64) -> Self { + Rng(seed ^ 0x9E37_79B9_7F4A_7C15) + } + /// The next value of the SplitMix64 sequence. + pub(crate) fn next(&mut self) -> u64 { + crate::photo_util::splitmix64(&mut self.0) + } + /// Skip `n` numbers (the same state as after `n` calls of [`Rng::next`]). + pub(crate) fn skip(&mut self, n: u64) { + self.0 = self.0.wrapping_add(n.wrapping_mul(0x9E37_79B9_7F4A_7C15)); + } + /// Uniform integer in `lo..=hi`. + pub(crate) fn range(&mut self, lo: i32, hi: i32) -> i32 { + if hi <= lo { + return lo; + } + lo + (self.next() % (hi - lo + 1) as u64) as i32 + } +} + +/// How far a copied patch may be adjusted to its target, per channel: `gain · source + bias`, the +/// gain within `gain` and the bias within `±bias` (Image Melding's photometric transform). The +/// gain is the ratio of the patches' standard deviations, the bias what then matches their means. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Adapt { + pub gain: (f32, f32), + pub bias: f32, +} + +impl Adapt { + /// Copies are taken as they are. + pub const NONE: Adapt = Adapt { gain: (1.0, 1.0), bias: 0.0 }; + + pub fn is_none(&self) -> bool { + self.gain == (1.0, 1.0) && self.bias == 0.0 + } +} + +impl Default for Adapt { + fn default() -> Self { + Self::NONE + } +} + +/// What a pixel is to [`complete_masked`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Px { + /// Not part of the image (a gap, or outside a transformed copy): ignored. + Void, + /// Known, part of the context the fill must agree with, but not copied from. + Known, + /// Known and may be copied from. + Source, + /// To be filled. + Hole, +} + +/// One pyramid level. Level 0 borrows the caller's buffers until it is solved. +pub(super) struct Level<'a> { + pub(super) w: usize, + pub(super) h: usize, + pub(super) img: Cow<'a, [f32]>, + pub(super) px: Cow<'a, [Px]>, +} + +impl Level<'_> { + pub(super) const EMPTY: Level<'static> = Level { w: 0, h: 0, img: Cow::Borrowed(&[]), px: Cow::Borrowed(&[]) }; +} + +/// The half-open box `[x0, x1) × [y0, y1)` of a level's grid. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Bounds { + pub(super) x0: usize, + pub(super) y0: usize, + pub(super) x1: usize, + pub(super) y1: usize, +} + +impl Bounds { + /// Grown by `r` on every side, within a `w × h` grid. + pub(super) fn grow(self, r: usize, w: usize, h: usize) -> Bounds { + Bounds { x0: self.x0.saturating_sub(r), y0: self.y0.saturating_sub(r), x1: self.x1.saturating_add(r).min(w), y1: self.y1.saturating_add(r).min(h) } + } + + /// The same box on the next coarser level (whose cells are 2 × 2 of these). + pub(super) fn half(self) -> Bounds { + Bounds { x0: self.x0 / 2, y0: self.y0 / 2, x1: self.x1.div_ceil(2), y1: self.y1.div_ceil(2) } + } + + pub(super) fn width(&self) -> usize { + self.x1.saturating_sub(self.x0) + } + + pub(super) fn height(&self) -> usize { + self.y1.saturating_sub(self.y0) + } + + pub(super) fn area(&self) -> usize { + self.width() * self.height() + } +} diff --git a/crates/algo/src/inpaint/solver.rs b/crates/algo/src/inpaint/solver.rs new file mode 100644 index 0000000000..b5cc82915d --- /dev/null +++ b/crates/algo/src/inpaint/solver.rs @@ -0,0 +1,866 @@ +use super::common::{Adapt, Bounds, PAR_MIN_PATCHES, Px, Rng}; +use super::*; + +/// Most channels whose moments the colour adaptation fits (the rest are copied as they are). +const MOM_CH: usize = 8; + +/// Per-level PatchMatch/EM state. +pub(super) struct Solver<'a> { + pub(super) w: usize, + pub(super) h: usize, + pub(super) ch: usize, + pub(super) r: i32, + pub(super) img: &'a mut Vec, + pub(super) px: &'a [Px], + /// Valid source centres: the whole patch is inside the grid and may be copied from. + pub(super) valid: Vec, + /// The hole's bounds and the targets' (the hole's grown by the patch radius): nothing outside + /// them changes or is matched. The match field, its costs and these per-target tables are + /// kept over `tbox`, row-major. + pub(super) hole_box: Bounds, + pub(super) tbox: Bounds, + /// Target centres (the patch overlaps the hole). + pub(super) targets: Vec, + /// Per cell of `tbox`: the whole patch is inside the grid and not void (so its distances + /// need no bounds checks and its own moments can be kept). + pub(super) full: Vec, + /// With colour adaptation, per cell of `tbox` and channel (at most [`MOM_CH`]): `Σt, Σt²` of + /// the patch, for full patches, as of the last [`Solver::costs`]. + pub(super) tmom: Vec<[f32; 2]>, + /// With colour adaptation where it pays: per source centre and channel, `Σs, Σs²` of its + /// patch (source pixels never change within a level). Empty otherwise. + pub(super) smom: Vec<[f32; 2]>, + pub(super) adapt: Adapt, + /// Cancellation: checked per row band; a cancelled solve's output is discarded. + pub(super) ctl: photocraft_raster::Interrupt<'a>, +} + +/// A channel deviation under which a patch counts as flat for [`fit`] (about 5 levels of 255). +const FLAT: f32 = 0.02; + +/// Gain and bias of one channel for target moments `(Σt, Σt²)` and source moments `(Σs, Σs²)` +/// over `n` samples, within the limits. +#[inline] +pub(crate) fn fit(a: Adapt, n: f32, st: f32, stt: f32, ss: f32, sss: f32) -> (f32, f32) { + let (mt, ms) = (st / n, ss / n); + let vt = (stt / n - mt * mt).max(0.0); + let vs = (sss / n - ms * ms).max(0.0); + let g = if vs > 1e-10 { (vt / vs).sqrt() } else { 1.0 }; + let (mut lo, mut hi) = a.gain; + // Nearly flat patches of about the same colour (their means within the bias of each other): + // the ratio of their deviations is noise, so match the mean first, keeping the gain where the + // bias can still bring the source's mean to the target's. Gained about zero, a gain at its + // limit moved bright means further than the bias could bring back, and each channel by a + // different amount: a tinted blotch in a smooth gradient. Textured patches, and flat ones + // whose colours differ more (Content-Aware Move's Color), are fitted as before. + if vt.max(vs) < FLAT * FLAT && (mt - ms).abs() <= a.bias && ms > 1e-6 { + let (glo, ghi) = ((mt - a.bias) / ms, (mt + a.bias) / ms); + if glo.max(lo) <= ghi.min(hi) { + (lo, hi) = (glo.max(lo), ghi.min(hi)); + } + } + let g = g.clamp(lo, hi); + let b = (mt - g * ms).clamp(-a.bias, a.bias); + (g, b) +} + +impl Solver<'_> { + #[inline] + pub(super) fn is_valid(&self, x: i32, y: i32) -> bool { + x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h && self.valid[y as usize * self.w + x as usize] + } + + /// Mark the full target patches (`full`), and keep the source moments where they pay off. + pub(super) fn prepare(&mut self, keep_source_moments: bool) { + let (w, h, r, tb) = (self.w, self.h, self.r as usize, self.tbox); + let side = 2 * r + 1; + let mut full = vec![false; tb.area()]; + let px = self.px; + par::chunks_mut(&mut full, tb.width(), tb.area() >= PAR_MIN_PATCHES, |ty, out| { + let y = tb.y0 + ty; + if y < r || y + r >= h { + return; + } + for (tx, f) in out.iter_mut().enumerate() { + let x = tb.x0 + tx; + if x < r || x + r >= w { + continue; + } + *f = (y - r..=y + r).all(|yy| px[yy * w + x - r..yy * w + x - r + side].iter().all(|k| *k != Px::Void)); + } + }); + self.full = full; + if self.adapt.is_none() { + return; + } + let c8 = self.ch.min(MOM_CH); + self.tmom = vec![[0.0; 2]; tb.area() * c8]; + if !keep_source_moments { + return; + } + let (ch, img, valid, ctl) = (self.ch, &*self.img, &self.valid, &self.ctl); + let mut smom = vec![[0.0f32; 2]; w * h * c8]; + par::chunks_mut(&mut smom, w * c8, w * h >= PAR_MIN_PATCHES, |y, out| { + if ctl.cancelled() { + return; + } + for x in 0..w { + if valid[y * w + x] { + patch_moments(img, w, ch, c8, side, x - r, y - r, &mut out[x * c8..(x + 1) * c8]); + } + } + }); + self.smom = smom; + } + + /// Distance between the target patch at `t` (its pixels inside the grid and not void; `k` its + /// index in the `tbox` tables) and the source patch at `s`, per sample; with colour adaptation + /// the source is fitted first. + #[inline] + fn dist(&self, t: (i32, i32), k: usize, s: (i32, i32), cutoff: f32) -> f32 { + let full = self.full[k]; + if !self.adapt.is_none() { + return if full { self.dist_adapted_full(k, t, s) } else { self.dist_adapted(t, s) }; + } + if full { self.dist_full(t, s, cutoff) } else { self.dist_clipped(t, s, cutoff) } + } + + /// [`Solver::dist`] without adaptation, of a patch that may be clipped. + pub(super) fn dist_clipped(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 { + let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r); + let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32; + let mut sum = 0.0f32; + let mut n = 0usize; + for dy in -r..=r { + let ty = t.1 + dy; + if ty < 0 || ty >= h { + continue; + } + let sy = s.1 + dy; + for dx in -r..=r { + let tx = t.0 + dx; + if tx < 0 || tx >= w || self.px[ty as usize * self.w + tx as usize] == Px::Void { + continue; + } + let ti = (ty as usize * self.w + tx as usize) * ch; + let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch; + for c in 0..ch { + let d = self.img[ti + c] - self.img[si + c]; + sum += d * d; + } + n += ch; + } + // Early out: the mean can only be ≥ sum / (full patch size). + if sum > cutoff * full { + return f32::INFINITY; + } + } + if n == 0 { f32::INFINITY } else { sum / n as f32 } + } + + /// [`Solver::dist_clipped`] of a full patch: the same sums, in the same order. It gives up + /// (infinity) as soon as the sum shows the patch is worse than `cutoff`, which the sum, only + /// growing, can show after any pixel: the caller only asks whether it is better. + pub(super) fn dist_full(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 { + let (w, ch, r) = (self.w, self.ch, self.r); + let side = (2 * r + 1) as usize; + let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32; + let (span, limit) = (side * ch, cutoff * full); + let mut sum = 0.0f32; + for dy in -r..=r { + let ti = ((t.1 + dy) as usize * w + (t.0 - r) as usize) * ch; + let si = ((s.1 + dy) as usize * w + (s.0 - r) as usize) * ch; + for (tp, sp) in self.img[ti..ti + span].chunks_exact(ch).zip(self.img[si..si + span].chunks_exact(ch)) { + for (a, b) in tp.iter().zip(sp) { + let d = a - b; + sum += d * d; + } + if sum > limit { + return f32::INFINITY; + } + } + } + sum / (side * side * ch) as f32 + } + + /// Moments of the target patch at `t` and the source patch at `s` per channel: + /// `[Σt, Σt², Σs, Σs², Σts]`, and the sample count. + pub(super) fn moments(&self, t: (i32, i32), s: (i32, i32), m: &mut [[f32; 5]]) -> usize { + let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r); + m.iter_mut().for_each(|v| *v = [0.0; 5]); + let mut n = 0usize; + for dy in -r..=r { + let ty = t.1 + dy; + if ty < 0 || ty >= h { + continue; + } + let sy = s.1 + dy; + for dx in -r..=r { + let tx = t.0 + dx; + if tx < 0 || tx >= w || self.px[ty as usize * self.w + tx as usize] == Px::Void { + continue; + } + let ti = (ty as usize * self.w + tx as usize) * ch; + let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch; + for (c, mc) in m.iter_mut().enumerate().take(ch) { + let (a, b) = (self.img[ti + c], self.img[si + c]); + mc[0] += a; + mc[1] += a * a; + mc[2] += b; + mc[3] += b * b; + mc[4] += a * b; + } + n += 1; + } + } + n + } + + /// [`Solver::moments`] of a full target patch (`k` in the `tbox` tables): the target's own + /// sums kept from [`Solver::costs`], the source's from [`Solver::prepare`] when kept, each + /// summed in the same order as there. + pub(super) fn moments_full(&self, k: usize, t: (i32, i32), s: (i32, i32), m: &mut [[f32; 5]]) { + let (w, ch, r) = (self.w, self.ch, self.r); + let c8 = m.len(); + let side = (2 * r + 1) as usize; + let tm = &self.tmom[k * c8..(k + 1) * c8]; + let sm = self.smom.get((s.1 as usize * w + s.0 as usize) * c8..(s.1 as usize * w + s.0 as usize + 1) * c8); + let mut acc = [[0.0f32; 3]; MOM_CH]; + for dy in -r..=r { + let ti = ((t.1 + dy) as usize * w + (t.0 - r) as usize) * ch; + let si = ((s.1 + dy) as usize * w + (s.0 - r) as usize) * ch; + let (trow, srow) = (&self.img[ti..ti + side * ch], &self.img[si..si + side * ch]); + if sm.is_some() { + for (tp, sp) in trow.chunks_exact(ch).zip(srow.chunks_exact(ch)) { + for c in 0..c8 { + acc[c][2] += tp[c] * sp[c]; + } + } + } else { + for (tp, sp) in trow.chunks_exact(ch).zip(srow.chunks_exact(ch)) { + for c in 0..c8 { + let (a, b) = (tp[c], sp[c]); + acc[c][0] += b; + acc[c][1] += b * b; + acc[c][2] += a * b; + } + } + } + } + for (c, mc) in m.iter_mut().enumerate() { + let [ss, sss] = match sm { + Some(sm) => sm[c], + None => [acc[c][0], acc[c][1]], + }; + *mc = [tm[c][0], tm[c][1], ss, sss, acc[c][2]]; + } + } + + pub(super) fn dist_adapted(&self, t: (i32, i32), s: (i32, i32)) -> f32 { + let mut m = [[0.0f32; 5]; MOM_CH]; + let ch = self.ch.min(MOM_CH); + let n = self.moments(t, s, &mut m[..ch]); + if n == 0 { + return f32::INFINITY; + } + adapted_cost(self.adapt, n as f32, &m[..ch]) + } + + pub(super) fn dist_adapted_full(&self, k: usize, t: (i32, i32), s: (i32, i32)) -> f32 { + let mut m = [[0.0f32; 5]; MOM_CH]; + let ch = self.ch.min(MOM_CH); + self.moments_full(k, t, s, &mut m[..ch]); + let side = (2 * self.r + 1) as usize; + adapted_cost(self.adapt, (side * side) as f32, &m[..ch]) + } + + /// Gain and bias per channel for the match `t → s` (identity without adaptation). + fn transform(&self, t: (i32, i32), k: usize, s: (i32, i32), out: &mut [(f32, f32)]) { + if self.adapt.is_none() { + out.iter_mut().for_each(|v| *v = (1.0, 0.0)); + return; + } + let mut m = [[0.0f32; 5]; MOM_CH]; + let ch = self.ch.min(MOM_CH); + let n = if self.full[k] { + self.moments_full(k, t, s, &mut m[..ch]); + let side = (2 * self.r + 1) as usize; + side * side + } else { + self.moments(t, s, &mut m[..ch]) + }; + for (c, o) in out.iter_mut().enumerate() { + *o = if n == 0 || c >= ch { (1.0, 0.0) } else { fit(self.adapt, n as f32, m[c][0], m[c][1], m[c][2], m[c][3]) }; + } + } + + /// One PatchMatch step at target `t` (`k` in the target box) whose match is `cur`: propagation + /// from the matches of the neighbours visited just before it (`left` in its row, `up` in its + /// column, in this pass's direction `step`), then random search in exponentially shrinking + /// windows around the best (two numbers from `rng` per window). + #[allow(clippy::too_many_arguments)] + #[inline] + fn pm_step( + &self, + t: (i32, i32), + k: usize, + cur: ((i32, i32), f32), + left: Option<(i32, i32)>, + up: Option<(i32, i32)>, + step: i32, + rng: &mut Rng, + search_radius: i32, + ) -> ((i32, i32), f32) { + let (mut best, mut bc) = cur; + if let Some(c) = left { + let cand = (c.0 + step, c.1); + if self.is_valid(cand.0, cand.1) && cand != best { + let d = self.dist(t, k, cand, bc); + if d < bc { + (best, bc) = (cand, d); + } + } + } + if let Some(c) = up { + let cand = (c.0, c.1 + step); + if self.is_valid(cand.0, cand.1) && cand != best { + let d = self.dist(t, k, cand, bc); + if d < bc { + (best, bc) = (cand, d); + } + } + } + let mut rad = search_radius; + while rad >= 1 { + let cand = (best.0 + rng.range(-rad, rad), best.1 + rng.range(-rad, rad)); + if self.is_valid(cand.0, cand.1) && cand != best { + let d = self.dist(t, k, cand, bc); + if d < bc { + (best, bc) = (cand, d); + } + } + rad /= 2; + } + (best, bc) + } + + /// One PatchMatch pass over all target rows, in bands of the grid's rows: each band is + /// visited in raster order (backwards on odd passes), propagating within itself, its random + /// numbers seeded by its index. `nnf` and `cost` are over the target box. The bands run in + /// parallel; when there are fewer of them than threads, each is also swept in wavefronts of + /// blocks (a cell depends only on its neighbours before it in its row and its column), which + /// visits every cell with the same neighbours and random numbers as the raster order. + pub(super) fn patchmatch(&self, nnf: &mut [(i32, i32)], cost: &mut [f32], pass: usize, seed: u64, search_radius: i32) { + const BAND: usize = 16; + let tb = self.tbox; + let tw = tb.width(); + if tw == 0 || tb.height() == 0 || nnf.len() < tb.area() || cost.len() < tb.area() { + return; + } + let reverse = pass % 2 == 1; + let step: i32 = if reverse { -1 } else { 1 }; + let band_seed = |bi: usize| seed ^ (bi as u64).wrapping_mul(0x2545_F491_4F6C_DD1D) ^ ((pass as u64) << 40); + // The bands crossing the target box: index, first row, rows in the box. + let mut bands = Vec::new(); + let mut y = tb.y0; + while y < tb.y1 { + let bi = y / BAND; + let end = ((bi + 1) * BAND).min(tb.y1); + bands.push((bi, y, end - y)); + y = end; + } + let threads = par::threads(); + if tb.area() >= PAR_MIN_PATCHES * 8 && !bands.is_empty() && bands.len() < threads { + self.patchmatch_wavefront(nnf, cost, &bands, reverse, &band_seed, search_radius); + return; + } + let band_fn = |bi: usize, ys: usize, nn: &mut [(i32, i32)], co: &mut [f32]| { + if self.ctl.cancelled() { + return; + } + let rows = nn.len() / tw; + let mut rng = Rng::new(band_seed(bi)); + for ry in 0..rows { + if self.ctl.cancelled() { + return; + } + let ly = if reverse { rows - 1 - ry } else { ry }; + let y = ys + ly; + for rx in 0..tw { + let lx = if reverse { tw - 1 - rx } else { rx }; + let li = ly * tw + lx; + let k = (y - tb.y0) * tw + lx; + if !self.targets[k] { + continue; + } + // Neighbours outside the target box hold no match: nothing to try. + let nx = lx as i32 - step; + let left = (nx >= 0 && (nx as usize) < tw).then(|| nn[ly * tw + nx as usize]); + let nly = ly as i32 - step; + let up = (nly >= 0 && (nly as usize) < rows).then(|| nn[nly as usize * tw + lx]); + let t = ((tb.x0 + lx) as i32, y as i32); + (nn[li], co[li]) = self.pm_step(t, k, (nn[li], co[li]), left, up, step, &mut rng, search_radius); + } + } + }; + // The target box's rows, band by band. + let mut parts = Vec::with_capacity(bands.len()); + let (mut nn_rest, mut co_rest) = (&mut nnf[..tb.area()], &mut cost[..tb.area()]); + for &(bi, ys, rows) in &bands { + let (nn, nr) = std::mem::take(&mut nn_rest).split_at_mut(rows * tw); + let (co, cr) = std::mem::take(&mut co_rest).split_at_mut(rows * tw); + parts.push((bi, ys, nn, co)); + (nn_rest, co_rest) = (nr, cr); + } + let par = tb.area() >= PAR_MIN_PATCHES && parts.len() > 1; + par::each(parts, par, |(bi, ys, nn, co)| band_fn(bi, ys, nn, co)); + } + + /// [`Solver::patchmatch`] swept in wavefronts: the cells of each band in blocks of a row, a + /// block once the block before it in its row and the one above it (in the pass's direction) + /// are done. A target's random numbers are those it would draw in raster order (each target + /// draws the same count). + fn patchmatch_wavefront( + &self, + nnf: &mut [(i32, i32)], + cost: &mut [f32], + bands: &[(usize, usize, usize)], + reverse: bool, + band_seed: &(dyn Fn(usize) -> u64 + Sync), + search_radius: i32, + ) { + use std::sync::atomic::{AtomicU32, AtomicU64, Ordering::Relaxed}; + + let tb = self.tbox; + let tw = tb.width(); + let step: i32 = if reverse { -1 } else { 1 }; + let pack = |(x, y): (i32, i32)| (u64::from(x as u32) << 32) | u64::from(y as u32); + let unpack = |v: u64| ((v >> 32) as u32 as i32, v as u32 as i32); + // Random numbers each target draws. + let mut draws = 0u64; + let mut rad = search_radius; + while rad >= 1 { + draws += 2; + rad /= 2; + } + // Targets before each column of each row of the box. + let mut before = vec![0u32; tb.height() * (tw + 1)]; + for (ry, row) in before.chunks_mut(tw + 1).enumerate() { + for lx in 0..tw { + row[lx + 1] = row[lx] + u32::from(self.targets[ry * tw + lx]); + } + } + // Targets visited before each of a band's rows (in the pass's order). + let row_base: Vec> = bands + .iter() + .map(|&(_, ys, rows)| { + let mut base = Vec::with_capacity(rows); + let mut n = 0u64; + for pr in 0..rows { + base.push(n); + let ly = if reverse { rows - 1 - pr } else { pr }; + n += u64::from(before[(ys + ly - tb.y0) * (tw + 1) + tw]); + } + base + }) + .collect(); + let block = (tw / 8).clamp(4, 32); + let blocks = tw.div_ceil(block); + let nn: Vec = nnf[..tb.area()].iter().map(|m| AtomicU64::new(pack(*m))).collect(); + let co: Vec = cost[..tb.area()].iter().map(|c| AtomicU32::new(c.to_bits())).collect(); + let sweep = |(j, pr, b): (usize, usize, usize)| { + let (bi, ys, rows) = bands[j]; + let ly = if reverse { rows - 1 - pr } else { pr }; + let y = ys + ly; + let ry = y - tb.y0; + let (pc0, pc1) = (b * block, ((b + 1) * block).min(tw)); + // The targets visited before this block, in raster order. + let first = if reverse { tw - 1 - pc0 } else { pc0 }; + let row = &before[ry * (tw + 1)..(ry + 1) * (tw + 1)]; + let in_row = if reverse { row[tw] - row[first + 1] } else { row[first] }; + let mut rng = Rng::new(band_seed(bi)); + rng.skip((row_base[j][pr] + u64::from(in_row)) * draws); + for pc in pc0..pc1 { + let lx = if reverse { tw - 1 - pc } else { pc }; + let k = ry * tw + lx; + if !self.targets[k] { + continue; + } + let nx = lx as i32 - step; + let left = (nx >= 0 && (nx as usize) < tw).then(|| unpack(nn[ry * tw + nx as usize].load(Relaxed))); + let nly = ly as i32 - step; + let up = (nly >= 0 && (nly as usize) < rows).then(|| unpack(nn[(ys + nly as usize - tb.y0) * tw + lx].load(Relaxed))); + let cur = (unpack(nn[k].load(Relaxed)), f32::from_bits(co[k].load(Relaxed))); + let t = ((tb.x0 + lx) as i32, y as i32); + let (m, c) = self.pm_step(t, k, cur, left, up, step, &mut rng, search_radius); + nn[k].store(pack(m), Relaxed); + co[k].store(c.to_bits(), Relaxed); + } + }; + // Wavefront `d`: block `b` of (visited) row `pr` with `pr + b = d`, in every band. Each + // wave ends before the next starts. + let longest = bands.iter().map(|b| b.2).max().unwrap_or(0); + for d in 0..longest + blocks - 1 { + if self.ctl.cancelled() { + return; + } + let wave: Vec<(usize, usize, usize)> = bands + .iter() + .enumerate() + .flat_map(|(j, &(_, _, rows))| (0..rows).filter(move |&pr| pr <= d && d - pr < blocks).map(move |pr| (j, pr, d - pr))) + .collect(); + par::each(wave, true, sweep); + } + for (m, a) in nnf.iter_mut().zip(&nn) { + *m = unpack(a.load(Relaxed)); + } + for (c, a) in cost.iter_mut().zip(&co) { + *c = f32::from_bits(a.load(Relaxed)); + } + } + + /// Recompute every target's match cost (hole pixels change between iterations), and with + /// colour adaptation the full target patches' own moments. + pub(super) fn costs(&mut self, nnf: &[(i32, i32)], cost: &mut [f32]) -> Result<(), photocraft_raster::Cancelled> { + let (w, ch, r, tb) = (self.w, self.ch, self.r as usize, self.tbox); + let par = tb.area() >= PAR_MIN_PATCHES; + self.ctl.check()?; + if !self.adapt.is_none() { + let c8 = ch.min(MOM_CH); + let side = 2 * r + 1; + let mut tmom = std::mem::take(&mut self.tmom); + let (img, full, ctl) = (&*self.img, &self.full, &self.ctl); + par::chunks_mut(&mut tmom, tb.width() * c8, par, |ty, out| { + if ctl.cancelled() { + return; + } + for tx in 0..tb.width() { + if full[ty * tb.width() + tx] { + patch_moments(img, w, ch, c8, side, tb.x0 + tx - r, tb.y0 + ty - r, &mut out[tx * c8..(tx + 1) * c8]); + } + } + }); + self.tmom = tmom; + } + let this = &*self; + par::chunks_mut(cost, tb.width(), par, |ty, co| { + if this.ctl.cancelled() { + return; + } + let y = tb.y0 + ty; + for (tx, c) in co.iter_mut().enumerate() { + let k = ty * tb.width() + tx; + if this.targets[k] { + *c = this.dist(((tb.x0 + tx) as i32, y as i32), k, nnf[k], f32::INFINITY); + } + } + }); + self.ctl.check() + } + + /// Re-estimate hole pixels by a similarity-weighted vote of all overlapping patch matches + /// (each copy adjusted by its gain and bias). + pub(super) fn vote(&mut self, nnf: &[(i32, i32)], cost: &[f32]) { + let (w, h, ch, r) = (self.w, self.h, self.ch, self.r); + let (tb, hb) = (self.tbox, self.hole_box); + // A cancelled solve is thrown away. + if self.ctl.cancelled() { + return; + } + let used = |k: usize| self.targets[k] && cost[k].is_finite(); + // σ² from the 75th percentile of match costs (Wexler et al. use a robust scale like this). + let cs: Vec = (0..tb.area()).filter(|&k| used(k)).map(|k| cost[k]).collect(); + let mut cs = cs; + let sigma2 = if cs.is_empty() { + 1.0 + } else { + let k = (cs.len() * 3 / 4).min(cs.len() - 1); + let (_, v, _) = cs.select_nth_unstable_by(k, |a, b| a.total_cmp(b)); + v.max(1e-6) + }; + drop(cs); + // Each target's weight and photometric transform (computed once, used by every pixel it + // covers). + let adapted = !self.adapt.is_none(); + let par = tb.area() >= PAR_MIN_PATCHES; + // A weight (zero for a target that doesn't vote) and its match's centre (as a pixel + // index) per target. + let mut wt = vec![0.0f32; tb.area()]; + let mut src = vec![0isize; tb.area()]; + par::chunks2_mut(&mut wt, tb.width(), &mut src, tb.width(), par, |ty, wrow, srow| { + for (tx, (o, sc)) in wrow.iter_mut().zip(srow.iter_mut()).enumerate() { + let k = ty * tb.width() + tx; + if used(k) { + *o = (-cost[k] / (2.0 * sigma2)).exp().max(1e-8); + *sc = nnf[k].1 as isize * w as isize + nnf[k].0 as isize; + } + } + }); + let mut gb: Vec<(f32, f32)> = Vec::new(); + if adapted { + gb = vec![(1.0f32, 0.0f32); tb.area() * ch]; + let this = &*self; + par::chunks_mut(&mut gb, tb.width() * ch, par, |ty, out| { + if this.ctl.cancelled() { + return; + } + let y = tb.y0 + ty; + for tx in 0..tb.width() { + let k = ty * tb.width() + tx; + if used(k) { + this.transform(((tb.x0 + tx) as i32, y as i32), k, nnf[k], &mut out[tx * ch..(tx + 1) * ch]); + } + } + }); + } + // The vote, into a buffer over the hole's bounds (every pixel reads the old pixels). + let votes = Votes { w, h, ch, r: r as usize, tbox: tb, img: &*self.img, wt: &wt, src: &src, gb: &gb }; + let (px, ctl) = (self.px, &self.ctl); + let mut out = vec![0.0f32; hb.area() * ch]; + let mut got = vec![false; hb.area()]; + let row = |yy: usize, orow: &mut [f32], grow: &mut [bool]| { + if ctl.cancelled() { + return; + } + let y = hb.y0 + yy; + for x in hb.x0..hb.x1 { + if px[y * w + x] != Px::Hole { + continue; + } + let o = (x - hb.x0) * ch; + let dst = &mut orow[o..o + ch]; + grow[x - hb.x0] = match (ch, adapted) { + (1, false) => votes.pixel::<1, false>(x, y, dst), + (3, false) => votes.pixel::<3, false>(x, y, dst), + (4, false) => votes.pixel::<4, false>(x, y, dst), + (1, true) => votes.pixel::<1, true>(x, y, dst), + (3, true) => votes.pixel::<3, true>(x, y, dst), + (4, true) => votes.pixel::<4, true>(x, y, dst), + _ => votes.pixel_any(x, y, adapted, dst), + }; + } + }; + par::chunks2_mut(&mut out, hb.width() * ch, &mut got, hb.width(), hb.area() >= PAR_MIN_PATCHES, row); + for yy in 0..hb.height() { + for xx in 0..hb.width() { + if got[yy * hb.width() + xx] { + let (d, s) = (((hb.y0 + yy) * w + hb.x0 + xx) * ch, (yy * hb.width() + xx) * ch); + self.img[d..d + ch].copy_from_slice(&out[s..s + ch]); + } + } + } + } +} + +/// What [`Solver::vote`] votes with: per target (over the target box) its weight (zero when it +/// doesn't vote), its match's centre as a pixel index, and with colour adaptation its gain and +/// bias per channel. +struct Votes<'a> { + w: usize, + h: usize, + ch: usize, + r: usize, + tbox: Bounds, + img: &'a [f32], + wt: &'a [f32], + src: &'a [isize], + gb: &'a [(f32, f32)], +} + +impl Votes<'_> { + /// Hole pixel `(x, y)`'s vote into `out` (`CH` channels): the weighted mean of what the + /// matches of the patches covering it put there, summed patch by patch in raster order of + /// their centres. False when no patch votes. + #[inline(always)] + fn pixel(&self, x: usize, y: usize, out: &mut [f32]) -> bool { + let (w, r, tb) = (self.w, self.r, self.tbox); + let mut acc = [0.0f32; CH]; + let mut wsum = 0.0f32; + for ty in y.saturating_sub(r)..=(y + r).min(self.h - 1) { + let dy = ty as isize - y as isize; + let krow = (ty - tb.y0) * tb.width(); + for tx in x.saturating_sub(r)..=(x + r).min(w - 1) { + let k = krow + tx - tb.x0; + let wt = self.wt[k]; + if wt == 0.0 { + continue; + } + // The pixel of the match's patch that lands here. + let si = (self.src[k] - dy * w as isize - (tx as isize - x as isize)) as usize * CH; + let s = &self.img[si..si + CH]; + for c in 0..CH { + let v = if ADAPT { + let (g, b) = self.gb[k * CH + c]; + g * s[c] + b + } else { + s[c] + }; + acc[c] += v * wt; + } + wsum += wt; + } + } + if wsum > 0.0 { + for (d, a) in out.iter_mut().zip(&acc) { + *d = a / wsum; + } + return true; + } + false + } + + /// [`Votes::pixel`] for any number of channels. + fn pixel_any(&self, x: usize, y: usize, adapted: bool, out: &mut [f32]) -> bool { + let (w, r, tb, ch) = (self.w, self.r, self.tbox, self.ch); + let mut acc = vec![0.0f32; ch]; + let mut wsum = 0.0f32; + for ty in y.saturating_sub(r)..=(y + r).min(self.h - 1) { + let dy = ty as isize - y as isize; + let krow = (ty - tb.y0) * tb.width(); + for tx in x.saturating_sub(r)..=(x + r).min(w - 1) { + let k = krow + tx - tb.x0; + let wt = self.wt[k]; + if wt == 0.0 { + continue; + } + let si = (self.src[k] - dy * w as isize - (tx as isize - x as isize)) as usize * ch; + for (c, a) in acc.iter_mut().enumerate() { + let v = if adapted { + let (g, b) = self.gb[k * ch + c]; + g * self.img[si + c] + b + } else { + self.img[si + c] + }; + *a += v * wt; + } + wsum += wt; + } + } + if wsum > 0.0 { + for (d, a) in out.iter_mut().zip(&acc) { + *d = a / wsum; + } + return true; + } + false + } +} + +/// `Σv, Σv²` per channel (the first `out.len()`) of the `side × side` patch with top-left +/// `(x0, y0)`, summed row by row, pixel by pixel, as [`Solver::moments`] does. +#[allow(clippy::too_many_arguments)] +fn patch_moments(img: &[f32], w: usize, ch: usize, c8: usize, side: usize, x0: usize, y0: usize, out: &mut [[f32; 2]]) { + out.iter_mut().for_each(|v| *v = [0.0; 2]); + for y in y0..y0 + side { + let row = &img[(y * w + x0) * ch..(y * w + x0 + side) * ch]; + for p in row.chunks_exact(ch) { + for (c, o) in out.iter_mut().enumerate().take(c8) { + let a = p[c]; + o[0] += a; + o[1] += a * a; + } + } + } +} + +/// The adapted distance from the moments `[Σt, Σt², Σs, Σs², Σts]` of each channel over `n` +/// samples: what is left of the target after the source is fitted to it, per sample. +#[inline] +fn adapted_cost(a: Adapt, nf: f32, m: &[[f32; 5]]) -> f32 { + let mut sum = 0.0f32; + for mc in m { + let (g, b) = fit(a, nf, mc[0], mc[1], mc[2], mc[3]); + // Σ (t − g s − b)², expanded. + sum += mc[1] + g * g * mc[3] + nf * b * b - 2.0 * g * mc[4] - 2.0 * b * mc[0] + 2.0 * g * b * mc[2]; + } + sum.max(0.0) / (nf * m.len() as f32) +} + +/// `Σ (t − s)²` over a target patch's known pixels (offsets `offs` from its centre, samples +/// `tv`, `CH` per pixel) against the source patch centred at pixel `base`, summed in that order; +/// `None` once the sum reaches `limit` (it only grows). +#[inline(always)] +pub(super) fn known_sse(image: &[f32], offs: &[isize], tv: &[f32], base: isize, limit: f32) -> Option { + let mut e = 0.0f32; + for (o, t) in offs.iter().zip(tv.as_chunks::().0) { + let si = (base + o) as usize * CH; + let s = &image[si..si + CH]; + for c in 0..CH { + let d = t[c] - s[c]; + e += d * d; + } + if e >= limit { + return None; + } + } + Some(e) +} + +/// [`known_sse`] of [`LANES`] sources at once, each against its own limit (summed in step: the +/// sums are independent, so the processor overlaps them). +#[inline(always)] +pub(super) fn known_sse_lanes(image: &[f32], offs: &[isize], tv: &[f32], bases: [isize; LANES], limits: [f32; LANES]) -> [Option; LANES] { + let mut e = [0.0f32; LANES]; + for (o, t) in offs.iter().zip(tv.as_chunks::().0) { + for l in 0..LANES { + let si = (bases[l] + o) as usize * CH; + let s = &image[si..si + CH]; + for c in 0..CH { + let d = t[c] - s[c]; + e[l] += d * d; + } + } + // Sums only grow: once all of them reached their limits, none can win. + if (0..LANES).all(|l| e[l] >= limits[l]) { + break; + } + } + std::array::from_fn(|l| (e[l] < limits[l]).then_some(e[l])) +} + +/// Sources [`known_sse_lanes`] sums at once. +pub(super) const LANES: usize = 4; + +/// [`known_sse`] for any number of channels. +pub(super) fn known_sse_any(image: &[f32], ch: usize, offs: &[isize], tv: &[f32], base: isize, limit: f32) -> Option { + let mut e = 0.0f32; + for (o, t) in offs.iter().zip(tv.chunks_exact(ch.max(1))) { + let si = (base + o) as usize * ch; + for (tc, sc) in t.iter().zip(&image[si..si + ch]) { + let d = tc - sc; + e += d * d; + } + if e >= limit { + return None; + } + } + Some(e) +} + +/// The best source so far of [`onion_peel`]'s search. +#[derive(Clone, Copy)] +pub(super) struct Best { + /// Error per sample, and the place in the sources. + pub(super) v: f32, + pub(super) j: usize, + /// Sums of squared errors from which `sum / n` is above `v`, and at least `v`. + pub(super) worse: f32, + pub(super) equal: f32, +} + +/// The least sum `e ≥ 0` with `e / n > v` (`strict`) or `e / n ≥ v` in float arithmetic (the +/// quotient only grows with `e`); infinity for an infinite `v`. +pub(super) fn least_sum(v: f32, n: f32, strict: bool) -> f32 { + let holds = |e: f32| if strict { e / n > v } else { e / n >= v }; + if !v.is_finite() || !n.is_finite() || n <= 0.0 { + return f32::INFINITY; + } + let mut e = (v * n).max(0.0); + while e > 0.0 && holds(e.next_down()) { + e = e.next_down(); + } + while !holds(e) && e < f32::INFINITY { + e = e.next_up(); + } + e +} diff --git a/crates/algo/src/inpaint/sources.rs b/crates/algo/src/inpaint/sources.rs new file mode 100644 index 0000000000..a3f390cfc3 --- /dev/null +++ b/crates/algo/src/inpaint/sources.rs @@ -0,0 +1,326 @@ +use super::common::{Bounds, Level, PAR_MIN, Px}; +use super::*; + +/// Half-size level: a cell is a hole if any of its pixels is; else it averages its non-void +/// pixels, and may be copied from only if all of them may. +pub(super) fn downsample(l: &Level, ch: usize) -> Level<'static> { + let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2)); + let mut img = vec![0.0f32; w * h * ch]; + let mut px = vec![Px::Void; w * h]; + let (lw, lh, limg, lpx) = (l.w, l.h, &*l.img, &*l.px); + let row = |y: usize, irow: &mut [f32], prow: &mut [Px]| { + for (x, p) in prow.iter_mut().enumerate() { + let mut n = 0.0f32; + let o = x * ch; + let (mut hole, mut all_source, mut any) = (false, true, false); + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let (sx, sy) = (x * 2 + dx, y * 2 + dy); + if sx >= lw || sy >= lh { + continue; + } + let si = sy * lw + sx; + match lpx[si] { + Px::Hole => hole = true, + Px::Void => all_source = false, + k => { + any = true; + all_source &= k == Px::Source; + for c in 0..ch { + irow[o + c] += limg[si * ch + c]; + } + n += 1.0; + } + } + } + if n > 0.0 { + for c in 0..ch { + irow[o + c] /= n; + } + } + *p = if hole { + Px::Hole + } else if !any { + Px::Void + } else if all_source { + Px::Source + } else { + Px::Known + }; + } + }; + par::chunks2_mut(&mut img, w * ch, &mut px, w, w * h >= PAR_MIN, row); + Level { w, h, img: Cow::Owned(img), px: Cow::Owned(px) } +} + +/// Summed-area table of a boolean grid (`(w+1) × (h+1)`). Not inlined: in [`synthesize`] it made +/// Create Texture's candidate loop slower (measured). +#[inline(never)] +pub(super) fn integral(w: usize, h: usize, m: &[bool]) -> Vec { + let mut s = vec![0u32; (w + 1) * (h + 1)]; + for y in 0..h { + let mut row = 0u32; + for x in 0..w { + row += u32::from(m[y * w + x]); + s[(y + 1) * (w + 1) + x + 1] = s[y * (w + 1) + x + 1] + row; + } + } + s +} + +/// Count of set cells in the clipped window `[x0, x1) × [y0, y1)`. +pub(super) fn window_count(s: &[u32], gw: usize, gh: usize, x0: i32, y0: i32, x1: i32, y1: i32) -> u32 { + let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize); + let (x1, y1) = ((x1.max(0) as usize).min(gw), (y1.max(0) as usize).min(gh)); + if x1 <= x0 || y1 <= y0 { + return 0; + } + let w1 = gw + 1; + s[y1 * w1 + x1] + s[y0 * w1 + x0] - s[y0 * w1 + x1] - s[y1 * w1 + x0] +} + +pub(super) fn hole_bbox(w: usize, h: usize, hole: &[bool]) -> Option<(usize, usize, usize, usize)> { + let mut b: Option<(usize, usize, usize, usize)> = None; + for y in 0..h { + for x in 0..w { + if hole[y * w + x] { + b = Some(match b { + None => (x, y, x + 1, y + 1), + Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)), + }); + } + } + } + b +} + +/// A hole at most `1 / THIN_RATIO` as thick as its bounds are long counts as thin (a wire, a +/// string, a hair, a long brush stroke): see the module docs. +pub(super) const THIN_RATIO: usize = 4; + +/// How thick the hole within bounds `hb` of a `w`-wide role grid is: twice the largest distance +/// from a hole pixel to the nearest pixel that is not one (a long, thin hole is thin however long +/// its bounds). +pub(super) fn hole_thickness(w: usize, hb: Bounds, px: &[Px]) -> usize { + // The bounds and a ring of non-hole cells around them (also past the grid's edge). + let (gw, gh) = (hb.width() + 2, hb.height() + 2); + let outside: Vec = par::map(gw * gh, gw * gh >= PAR_MIN, |i| { + let (gx, gy) = (i % gw, i / gw); + if gx == 0 || gy == 0 || gx > hb.width() || gy > hb.height() { + return true; + } + px.get((hb.y0 + gy - 1) * w + hb.x0 + gx - 1) != Some(&Px::Hole) + }); + let deepest = crate::selection::edt(&outside, gw, gh).into_iter().fold(0.0f32, f32::max); + (2.0 * deepest).ceil() as usize +} + +/// Most target pixels × sources the onion peel of a thin hole may compare (its search is +/// exhaustive, though most comparisons stop early: about a second at this many). +const PEEL_BUDGET: usize = 1 << 28; + +/// Whether the onion peel of the hole cells within `hb` of a `w`-wide role grid from `sources` +/// source centres stays within [`PEEL_BUDGET`]. +pub(super) fn peel_affordable(w: usize, px: &[Px], hb: Bounds, sources: usize) -> bool { + let holes: usize = (hb.y0..hb.y1).map(|y| px.get(y * w + hb.x0..y * w + hb.x1).map_or(0, |row| row.iter().filter(|k| **k == Px::Hole).count())).sum(); + holes.saturating_mul(sources) <= PEEL_BUDGET +} + +/// Bounds of the hole pixels of a role grid. +pub(super) fn hole_bounds(w: usize, h: usize, px: &[Px]) -> Option { + // A zero-width grid holds no pixels whatever its height; don't size a row table by it. + if w == 0 || h == 0 { + return None; + } + // Per row the first and last hole column; the union of the rows' spans. + let rows: Vec> = par::map(h, w * h >= PAR_MIN, |y| { + let row = px.get(y * w..(y + 1) * w)?; + let x0 = row.iter().position(|k| *k == Px::Hole)?; + let x1 = row.iter().rposition(|k| *k == Px::Hole).unwrap_or(x0) + 1; + Some((x0, x1)) + }); + let mut b: Option = None; + for (y, span) in rows.into_iter().enumerate() { + if let Some((x0, x1)) = span { + b = Some(match b { + None => Bounds { x0, y0: y, x1, y1: y + 1 }, + Some(b) => Bounds { x0: b.x0.min(x0), y0: b.y0, x1: b.x1.max(x1), y1: y + 1 }, + }); + } + } + b +} + +/// Valid source centres: the whole `2r+1` patch inside the grid and copyable. Found per row +/// (each pixel's horizontal run), then per column of runs. `None` when cancelled. +pub(super) fn valid_sources(w: usize, h: usize, r: usize, px: &[Px], ctl: &photocraft_raster::Interrupt) -> Option> { + const BAND: usize = 64; + let side = 2 * r + 1; + let par = w * h >= PAR_MIN; + let mut run = vec![false; w * h]; + if w < side || h < side { + return Some(run); + } + // Per row: is the run of `side` pixels centred on each one all copyable (a sliding count)? + par::chunks_mut(&mut run, w, par, |y, out| { + if y % BAND == 0 && ctl.cancelled() { + return; + } + let row = &px[y * w..(y + 1) * w]; + let copyable = |x: usize| usize::from(row[x] == Px::Source); + let mut count: usize = (0..side).map(copyable).sum(); + out[r] = count == side; + for (x, o) in out.iter_mut().enumerate().take(w - r).skip(r + 1) { + count = count + copyable(x + r) - copyable(x - r - 1); + *o = count == side; + } + }); + if ctl.cancelled() { + return None; + } + // Per column, in bands of rows: how many such runs end each row in a row; a centre is valid + // where `side` of them stack up to `r` rows below it. + let mut valid = vec![false; w * h]; + par::chunks_mut(&mut valid, BAND * w, par, |band, out| { + if ctl.cancelled() { + return; + } + let (y0, rows) = (band * BAND, out.len() / w); + let mut stack = vec![0usize; w]; + for yy in y0.saturating_sub(r)..(y0 + rows + r).min(h) { + for (x, n) in stack.iter_mut().enumerate() { + *n = if run[yy * w + x] { *n + 1 } else { 0 }; + } + // `yy` is the bottom row of centre `y`'s patch. + if yy < y0 + r || yy < 2 * r { + continue; + } + let y = yy - r; + for (v, n) in out[(y - y0) * w..(y - y0 + 1) * w].iter_mut().zip(&stack).take(w - r).skip(r) { + *v = *n >= side; + } + } + }); + if ctl.cancelled() { + return None; + } + Some(valid) +} + +/// Columns per block of [`Sources`]' index. +const SOURCE_BLOCK: usize = 64; + +/// The valid source centres in row-major order, indexed by counts per row and per block of +/// [`SOURCE_BLOCK`] columns (so the `k`-th is found without listing them all). +pub(super) struct Sources { + /// Valid centres before each row (`h + 1` entries). + row_start: Vec, + /// Per row, the valid centres in it before each block. + block_start: Vec, + blocks: usize, +} + +impl Sources { + pub(super) fn new(valid: &[bool], w: usize) -> Sources { + let h = valid.len().checked_div(w).unwrap_or(0); + let blocks = w.div_ceil(SOURCE_BLOCK); + let mut block_start = vec![0u32; h * blocks]; + // Per row: the block prefix, and the row's count. + let counts: Vec = par::map(h, valid.len() >= PAR_MIN, |y| valid[y * w..(y + 1) * w].iter().filter(|v| **v).count()); + par::chunks_mut(&mut block_start, blocks, valid.len() >= PAR_MIN, |y, out| { + let mut n = 0u32; + for (b, o) in out.iter_mut().enumerate() { + *o = n; + n += valid[y * w + b * SOURCE_BLOCK..y * w + ((b + 1) * SOURCE_BLOCK).min(w)].iter().filter(|v| **v).count() as u32; + } + }); + let mut row_start = Vec::with_capacity(counts.len() + 1); + let mut total = 0usize; + row_start.push(0); + for c in counts { + total += c; + row_start.push(total); + } + Sources { row_start, block_start, blocks } + } + + pub(super) fn len(&self) -> usize { + self.row_start.last().copied().unwrap_or(0) + } + + /// The `k`-th valid centre in row-major order (`k < len`). + pub(super) fn nth(&self, k: usize, valid: &[bool], w: usize) -> (i32, i32) { + let y = self.row_start.partition_point(|&s| s <= k).saturating_sub(1); + let left = k.saturating_sub(self.row_start.get(y).copied().unwrap_or(0)); + let row_blocks = self.block_start.get(y * self.blocks..(y + 1) * self.blocks).unwrap_or(&[]); + let b = row_blocks.partition_point(|&s| s as usize <= left).saturating_sub(1); + let mut left = left.saturating_sub(row_blocks.get(b).copied().unwrap_or(0) as usize); + let x0 = b * SOURCE_BLOCK; + for (x, v) in valid.iter().skip(y * w + x0).take(w.saturating_sub(x0)).enumerate() { + if *v { + if left == 0 { + return ((x0 + x) as i32, y as i32); + } + left -= 1; + } + } + (0, 0) + } + + /// All of them, in row-major order. + pub(super) fn all(&self, valid: &[bool], w: usize) -> Vec<(i32, i32)> { + let mut out = Vec::with_capacity(self.len()); + for (i, v) in valid.iter().enumerate() { + if *v { + out.push(((i % w) as i32, (i / w) as i32)); + } + } + out + } +} + +/// Per cell of `tb` (the hole's bounds `hb` grown by the patch radius, where all of them lie): is +/// it a target centre (its patch overlaps the hole)? +pub(super) fn targets_around(w: usize, r: usize, px: &[Px], hb: Bounds, tb: Bounds) -> Vec { + // Hole counts summed over the hole's bounds: every hole pixel lies inside them. + let (bw, bh) = (hb.width(), hb.height()); + let mut s = vec![0u32; (bw + 1) * (bh + 1)]; + for y in 0..bh { + let mut row = 0u32; + for x in 0..bw { + row += u32::from(px[(hb.y0 + y) * w + hb.x0 + x] == Px::Hole); + s[(y + 1) * (bw + 1) + x + 1] = s[y * (bw + 1) + x + 1] + row; + } + } + let mut targets = vec![false; tb.area()]; + let ri = r as i32; + let (ox, oy) = (hb.x0 as i32, hb.y0 as i32); + for y in tb.y0..tb.y1 { + for x in tb.x0..tb.x1 { + let k = (y - tb.y0) * tb.width() + (x - tb.x0); + let (x, y) = (x as i32, y as i32); + targets[k] = window_count(&s, bw, bh, x - ri - ox, y - ri - oy, x + ri + 1 - ox, y + ri + 1 - oy) > 0; + } + } + targets +} + +/// A finished coarser level: its size, pixels and match field (the source centre per cell of +/// its target box, `i32::MIN` where there is none; empty when it had nothing to copy). +pub(super) struct Coarser { + pub(super) w: usize, + pub(super) h: usize, + pub(super) img: Vec, + pub(super) field: Vec<(i32, i32)>, + pub(super) tbox: Bounds, +} + +impl Coarser { + /// The match of cell `(x, y)` (`i32::MIN` outside the target box). + pub(super) fn field_at(&self, x: usize, y: usize) -> (i32, i32) { + let t = self.tbox; + if x < t.x0 || x >= t.x1 || y < t.y0 || y >= t.y1 { + return (i32::MIN, i32::MIN); + } + self.field.get((y - t.y0) * t.width() + (x - t.x0)).copied().unwrap_or((i32::MIN, i32::MIN)) + } +} diff --git a/crates/algo/src/inpaint/synthesis.rs b/crates/algo/src/inpaint/synthesis.rs new file mode 100644 index 0000000000..0c3bf9c375 --- /dev/null +++ b/crates/algo/src/inpaint/synthesis.rs @@ -0,0 +1,381 @@ +use super::common::{Bounds, Px, Rng}; +use super::solver::{Best, LANES, known_sse, known_sse_any, known_sse_lanes, least_sum}; +use super::sources::{hole_bbox, integral, window_count}; +use super::*; + +/// Fill the hole from its edge inwards, one ring at a time: each pixel takes the centre of the +/// source patch that best matches what is already known around it (the first in `sources` of +/// those that match best). `hb` bounds the hole. +/// +/// The search is exhaustive, but most sources are given up early (#2771, #2805): the target's +/// known pixels are gathered once, the search starts from where the pixel's filled neighbours +/// took their sources (or every 16th source at the hole's edge), and a source's error stops being +/// added up once it can only lose (it only grows). So it finds the same source as a plain scan in +/// order, sooner. +#[allow(clippy::too_many_arguments)] +pub(super) fn onion_peel( + w: usize, + h: usize, + ch: usize, + r: i32, + img: &mut [f32], + px: &[Px], + hb: Bounds, + sources: &[(i32, i32)], + ctl: &photocraft_raster::Interrupt, +) -> Result<(), photocraft_raster::Cancelled> { + const NONE: u32 = u32::MAX; + let mut known: Vec = px.iter().map(|k| matches!(k, Px::Known | Px::Source)).collect(); + // Each source centre's place in `sources`, and the source each filled pixel took. + let mut index = vec![NONE; w * h]; + for (j, &(x, y)) in sources.iter().enumerate() { + index[y as usize * w + x as usize] = j as u32; + } + let mut took = vec![NONE; w * h]; + let neighbours = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]; + loop { + ctl.check()?; + let mut front: Vec = Vec::new(); + for y in hb.y0..hb.y1 { + for x in hb.x0..hb.x1 { + let i = y * w + x; + if known[i] || px[i] != Px::Hole { + continue; + } + let (x, y) = (x as i32, y as i32); + let edge = (-1..=1).any(|dy: i32| { + (-1..=1).any(|dx: i32| { + let (nx, ny) = (x + dx, y + dy); + nx >= 0 && ny >= 0 && (nx as usize) < w && (ny as usize) < h && known[ny as usize * w + nx as usize] + }) + }); + if edge { + front.push(i); + } + } + } + if front.is_empty() { + break; + } + let (known_now, took_now) = (&known, &took); + let image = &*img; + let best = |&i: &usize| -> (Vec, u32) { + let (x, y) = ((i % w) as i32, (i / w) as i32); + // The known pixels of the target patch, in the plain scan's order: each one's offset + // from the patch centre (in pixels) and its samples (gathered once, #2805). + let side = (2 * r + 1) as usize; + let mut offs: Vec = Vec::with_capacity(side * side); + let mut tv: Vec = Vec::with_capacity(side * side * ch); + for dy in -r..=r { + for dx in -r..=r { + let (tx, ty) = (x + dx, y + dy); + if tx >= 0 && ty >= 0 && (tx as usize) < w && (ty as usize) < h && known_now[ty as usize * w + tx as usize] { + let ti = (ty as usize * w + tx as usize) * ch; + offs.push(dy as isize * w as isize + dx as isize); + tv.extend_from_slice(&image[ti..ti + ch]); + } + } + } + // The best so far: its error per sample, its place in `sources` (the first of equals + // wins, as in a scan in order), and the sums of squares at which a source surely loses + // to it (`e / n` above the best) or ties it (at least the best). + let mut best = Best { v: f32::INFINITY, j: usize::MAX, worse: f32::INFINITY, equal: f32::INFINITY }; + if !offs.is_empty() { + let nf = offs.len() as f32; + let base_of = |j: usize| sources.get(j).map_or(0, |&(sx, sy)| sy as isize * w as isize + sx as isize); + // The sum at which source `j` can't win: a tie loses to an earlier source. + let limit_of = |j: usize, best: &Best| if j > best.j { best.equal } else { best.worse }; + // Source `j`'s whole sum `e` (it did not reach its limit): does it win? + let adopt = |j: usize, e: f32, best: &mut Best| { + let v = e / nf; + if v < f32::INFINITY && (v < best.v || (v == best.v && j < best.j)) { + *best = Best { v, j, worse: least_sum(v, nf, true), equal: least_sum(v, nf, false) }; + } + }; + let consider = |j: usize, best: &mut Best| { + if j >= sources.len() { + return; + } + let (base, limit) = (base_of(j), limit_of(j, best)); + let e = match ch { + 1 => known_sse::<1>(image, &offs, &tv, base, limit), + 3 => known_sse::<3>(image, &offs, &tv, base, limit), + 4 => known_sse::<4>(image, &offs, &tv, base, limit), + _ => known_sse_any(image, ch, &offs, &tv, base, limit), + }; + if let Some(e) = e { + adopt(j, e, best); + } + }; + // A close bound early: where the filled neighbours' sources point (shifted as in + // PatchMatch's propagation), or at the hole's edge, where none is filled yet, + // every 16th source. + for (dx, dy) in neighbours { + let (qx, qy) = (x + dx, y + dy); + if qx < 0 || qy < 0 || qx as usize >= w || qy as usize >= h { + continue; + } + let Some(&(sx, sy)) = sources.get(took_now[qy as usize * w + qx as usize] as usize) else { continue }; + let (cx, cy) = (sx - dx, sy - dy); + if cx >= 0 && cy >= 0 && (cx as usize) < w && (cy as usize) < h && index[cy as usize * w + cx as usize] != NONE { + consider(index[cy as usize * w + cx as usize] as usize, &mut best); + } + } + if best.j == usize::MAX { + for j in (0..sources.len()).step_by(16) { + consider(j, &mut best); + } + } + // The scan in order, `LANES` sources at a time (their sums are independent, so they + // overlap), each against its limit from the best before them: the best only gets + // better, so a source given up would have lost to it anyway. + let mut j = 0; + while j + LANES <= sources.len() { + if j.is_multiple_of(4096) && j > 0 && ctl.cancelled() { + break; + } + let bases: [isize; LANES] = std::array::from_fn(|l| base_of(j + l)); + let limits: [f32; LANES] = std::array::from_fn(|l| limit_of(j + l, &best)); + let sums = match ch { + 1 => known_sse_lanes::<1>(image, &offs, &tv, bases, limits), + 3 => known_sse_lanes::<3>(image, &offs, &tv, bases, limits), + 4 => known_sse_lanes::<4>(image, &offs, &tv, bases, limits), + _ => std::array::from_fn(|l| known_sse_any(image, ch, &offs, &tv, bases[l], limits[l])), + }; + for (l, e) in sums.into_iter().enumerate() { + if let Some(e) = e { + adopt(j + l, e, &mut best); + } + } + j += LANES; + } + for j in j..sources.len() { + consider(j, &mut best); + } + } + let (sx, sy) = sources.get(best.j).copied().unwrap_or((0, 0)); + let si = (sy as usize * w + sx as usize) * ch; + (image[si..si + ch].to_vec(), if best.j == usize::MAX { NONE } else { best.j as u32 }) + }; + let vals: Vec<(Vec, u32)> = par::map(front.len(), front.len() * sources.len() >= 4096, |k| best(&front[k])); + ctl.check()?; + for (&i, (v, j)) in front.iter().zip(vals) { + img[i * ch..(i + 1) * ch].copy_from_slice(&v); + known[i] = true; + took[i] = j; + } + } + Ok(()) +} + +/// Proximity match: the displacement `(dx, dy)` (within `max_radius`) whose surroundings best match the +/// ring of `ring` pixels around the hole, with the displaced hole fully inside the grid and outside the +/// hole. `None` if no displacement fits. +pub fn best_offset(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], ring: usize, max_radius: i32) -> Option<(i32, i32)> { + let (bx0, by0, bx1, by1) = hole_bbox(w, h, hole)?; + // No valid translation can move farther than the source image's extent. + // Bound arbitrary public API inputs before constructing i32 search ranges: + // usize -> i32 truncation and signed increments otherwise overflow or hang. + let extent = w.max(h).min((i32::MAX / 4) as usize) as i32; + let max_radius = max_radius.max(0).min(extent); + if max_radius == 0 { + return None; + } + let ring = ring.max(1).min(extent as usize) as i32; + // Every set cell lies in the hole bounds. Counts outside that rectangle are zero, + // so source rejection needs a table for the hole, not for the whole photo. + let hs = HoleIntegral::new(w, hole, (bx0, by0, bx1, by1))?; + // Sample points: the hole's ring (dilated minus hole), subsampled for speed. + let mut pts = Vec::new(); + let (x0, y0) = (bx0 as i32 - ring, by0 as i32 - ring); + let (x1, y1) = (bx1 as i32 + ring, by1 as i32 + ring); + for y in y0.max(0)..y1.min(h as i32) { + for x in x0.max(0)..x1.min(w as i32) { + if hole[y as usize * w + x as usize] { + continue; + } + if hs.count(x - ring, y - ring, x + ring + 1, y + ring + 1) > 0 { + pts.push((x, y)); + } + } + } + let stride = (pts.len() / 2000).max(1); + let pts: Vec<(i32, i32)> = pts.into_iter().step_by(stride).collect(); + let eval = |dx: i32, dy: i32, cutoff: f32| -> Option { + let (hx0, hy0, hx1, hy1) = (x0 + dx, y0 + dy, x1 + dx, y1 + dy); + let inside = hx0 >= 0 && hy0 >= 0 && hx1 <= w as i32 && hy1 <= h as i32; + if (dx, dy) == (0, 0) || !inside || hs.count(hx0, hy0, hx1, hy1) != 0 { + return None; + } + let mut e = 0.0f32; + let n = pts.len().max(1) as f32; + let penalty = 1.0 + 1e-3 * ((dx as f32).hypot(dy as f32) / max_radius as f32); + for (i, &(x, y)) in pts.iter().enumerate() { + let (a, b) = ((y as usize * w + x as usize) * ch, ((y + dy) as usize * w + (x + dx) as usize) * ch); + for c in 0..ch { + let d = img[a + c] - img[b + c]; + e += d * d; + } + // SSD terms are nonnegative. The partial score is a lower bound on the + // final score; use the same division and penalty to keep float rounding + // and strict tie ordering unchanged. Check in batches to keep this cheap. + if i % 32 == 31 && cutoff.is_finite() && e / n * penalty >= cutoff { + return None; + } + } + // Mild preference for nearer sources on ties. + Some(e / n * penalty) + }; + // Coarse grid over the search window, then a full-resolution refinement around the winner. + let step = (max_radius / 24).max(1); + let mut best: Option<((i32, i32), f32)> = None; + let consider = |dx: i32, dy: i32, best: &mut Option<((i32, i32), f32)>| { + if let Some(e) = eval(dx, dy, best.map_or(f32::INFINITY, |(_, error)| error)) + && best.is_none_or(|(_, be)| e < be) + { + *best = Some(((dx, dy), e)); + } + }; + let mut dy = -max_radius; + while dy <= max_radius { + let mut dx = -max_radius; + while dx <= max_radius { + consider(dx, dy, &mut best); + dx += step; + } + dy += step; + } + if step > 1 + && let Some(((bx, by), _)) = best + { + for dy in (by - step)..=(by + step) { + for dx in (bx - step)..=(bx + step) { + consider(dx, dy, &mut best); + } + } + } + best.map(|b| b.0) +} + +/// Create texture: fill the hole with blocks of surrounding texture (see module docs). +pub fn synthesize(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], block: usize, seed: u64) -> Vec { + let mut out = img.to_vec(); + let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return out }; + let b = block.max(4) as i32; + let ov = (b / 3).max(1); + let hs = integral(w, h, hole); + // Candidate block origins: whole block (with overlap) inside the grid and outside the hole. + let mut cands = Vec::new(); + for y in ov..(h as i32 - b - ov) { + for x in ov..(w as i32 - b - ov) { + if window_count(&hs, w, h, x - ov, y - ov, x + b + ov, y + b + ov) == 0 { + cands.push((x, y)); + } + } + } + if cands.is_empty() { + return membrane_fill(w, h, ch, img, hole); + } + let mut filled: Vec = hole.iter().map(|x| !x).collect(); + let mut rng = Rng::new(seed); + let mut by = by0 as i32; + while by < by1 as i32 { + let mut bx = bx0 as i32; + while bx < bx1 as i32 { + if window_count(&hs, w, h, bx, by, bx + b, by + b) > 0 { + // Pick the candidate whose block best agrees with already-known pixels around/inside. + let mut best = (cands[0], f32::INFINITY); + for _ in 0..48 { + let c = cands[(rng.next() % cands.len() as u64) as usize]; + let (mut e, mut n) = (0.0f32, 0u32); + for y in (by - ov)..(by + b + ov) { + for x in (bx - ov)..(bx + b + ov) { + if x < 0 || y < 0 || x >= w as i32 || y >= h as i32 || !filled[y as usize * w + x as usize] { + continue; + } + let (a, s) = ((y as usize * w + x as usize) * ch, ((y - by + c.1) as usize * w + (x - bx + c.0) as usize) * ch); + for k in 0..ch { + let d = out[a + k] - img[s + k]; + e += d * d; + } + n += 1; + } + } + let e = if n == 0 { 0.0 } else { e / n as f32 }; + if e < best.1 { + best = (c, e); + } + } + let c = best.0; + let (x0, y0) = ((bx - ov).max(0), (by - ov).max(0)); + let (x1, y1) = ((bx + b + ov).min(w as i32), (by + b + ov).min(h as i32)); + let src = |x: i32, y: i32| ((y - by + c.1) as usize * w + (x - bx + c.0) as usize) * ch; + // Squared difference between what is there and the block, where both exist. + let err = |x: i32, y: i32| { + let i = y as usize * w + x as usize; + if !(hole[i] && filled[i]) { + return 0.0; + } + let (a, s) = (i * ch, src(x, y)); + (0..ch).map(|q| (out[a + q] - img[s + q]).powi(2)).sum::() + }; + // Minimum-error boundary cuts through the overlaps with the blocks to the left and + // above: the block is copied right of and below them, untouched pixels are kept + // on the other side. Copying (rather than averaging) keeps the texture's grain. + let left = min_cut((x0..(bx + ov).min(x1)).len(), (y0..y1).len(), |u, v| err(x0 + u as i32, y0 + v as i32)); + let top = min_cut((y0..(by + ov).min(y1)).len(), (x0..x1).len(), |u, v| err(x0 + v as i32, y0 + u as i32)); + for y in y0..y1 { + for x in x0..x1 { + let i = y as usize * w + x as usize; + if !hole[i] { + continue; + } + let (u, v) = ((x - x0) as usize, (y - y0) as usize); + let keep = filled[i] && (left.get(v).is_some_and(|s| u < *s) || top.get(u).is_some_and(|s| v < *s)); + if !keep { + let (a, s) = (i * ch, src(x, y)); + out[a..a + ch].copy_from_slice(&img[s..s + ch]); + } + filled[i] = true; + } + } + } + bx += b; + } + by += b; + } + out +} + +/// The minimum-error cut through a band `across` wide and `along` long (Efros & Freeman's +/// boundary cut, by dynamic programming): for each step along the band, the offset across it +/// where the cut runs (`err(across, along)` is the cost of a pixel). Pixels before the cut keep +/// what is there. Empty when there is no cost anywhere (nothing to cut through). +fn min_cut(across: usize, along: usize, err: impl Fn(usize, usize) -> f32) -> Vec { + if across == 0 || along == 0 { + return Vec::new(); + } + // Cumulative cost, step by step along the band; the cut may move by one pixel per step. + let mut acc: Vec = (0..along).flat_map(|v| (0..across).map(move |u| (u, v))).map(|(u, v)| err(u, v)).collect(); + if acc.iter().all(|x| *x == 0.0) { + return Vec::new(); + } + for v in 1..along { + for u in 0..across { + let lo = u.saturating_sub(1); + let hi = (u + 1).min(across - 1); + let m = (lo..=hi).map(|k| acc[(v - 1) * across + k]).fold(f32::INFINITY, f32::min); + acc[v * across + u] += m; + } + } + let argmin = |v: usize, lo: usize, hi: usize| (lo..=hi).min_by(|a, b| acc[v * across + a].total_cmp(&acc[v * across + b])).unwrap_or(lo); + let mut cut = vec![0; along]; + let mut u = argmin(along - 1, 0, across - 1); + for v in (0..along).rev() { + if v + 1 < along { + u = argmin(v, u.saturating_sub(1), (u + 1).min(across - 1)); + } + cut[v] = u; + } + cut +} diff --git a/crates/algo/src/inpaint/tests.rs b/crates/algo/src/inpaint/tests.rs index 28cb470cd8..45690fac01 100644 --- a/crates/algo/src/inpaint/tests.rs +++ b/crates/algo/src/inpaint/tests.rs @@ -119,8 +119,7 @@ fn busy(w: usize, h: usize, ch: usize, seed: u64) -> Vec { let (x, y) = (i % w, i / w); let flat = (x / 9 + y / 7) % 5 == 0; let n = (rng.next() % 1000) as f32 / 1000.0; - (0..ch) - .map(move |c| if flat { 0.25 + 0.1 * c as f32 } else { (0.2 + 0.004 * x as f32 + 0.1 * ((x + 2 * y + c) % 6) as f32 + 0.05 * n).min(1.0) }) + (0..ch).map(move |c| if flat { 0.25 + 0.1 * c as f32 } else { (0.2 + 0.004 * x as f32 + 0.1 * ((x + 2 * y + c) % 6) as f32 + 0.05 * n).min(1.0) }) }) .collect() } From 4d07ccded0f16ac948bed0d5b77a8c1965173737 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:18:49 +0000 Subject: [PATCH 251/259] refactor(algo): split panorama.rs into panorama/ --- crates/algo/src/panorama.rs | 696 +----------------------------- crates/algo/src/panorama/blend.rs | 692 +++++++++++++++++++++++++++++ 2 files changed, 698 insertions(+), 690 deletions(-) create mode 100644 crates/algo/src/panorama/blend.rs diff --git a/crates/algo/src/panorama.rs b/crates/algo/src/panorama.rs index 2be876d89c..dc44f06c1f 100644 --- a/crates/algo/src/panorama.rs +++ b/crates/algo/src/panorama.rs @@ -38,6 +38,12 @@ use crate::features::{self, Descriptor, Model}; use crate::photo_util::{Normal, Rng, par_map, par_rows, solve_dense}; use crate::transform::Homography; +mod blend; + +pub use blend::{Geometry, Photometric, RoiImage, blend_levels, multiband, photometric, seam_labels}; +#[cfg(test)] +use blend::{expand, multiband_batched, push_pull, reduce}; + /// Photomerge layouts. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Layout { @@ -720,696 +726,6 @@ fn align_layout(feats: &[ImageFeatures], matches: &[PairMatch], opts: &AlignOpti Some(Alignment { layout, reference, placements, focal, k1, pairs: edges.iter().map(|e| (e.0, e.1, e.2)).collect(), rms }) } -// ---------- photometric ---------- - -/// One image warped into the panorama: an axis-aligned region with colour channels and coverage. -#[derive(Clone, Debug)] -pub struct RoiImage { - pub x0: i32, - pub y0: i32, - pub w: usize, - pub h: usize, - /// Colour channels per pixel (no alpha). - pub ch: usize, - pub px: Vec, - /// Coverage `0..=1`. - pub alpha: Vec, -} - -impl RoiImage { - fn at(&self, x: i32, y: i32) -> Option { - let (lx, ly) = (x - self.x0, y - self.y0); - (lx >= 0 && ly >= 0 && (lx as usize) < self.w && (ly as usize) < self.h).then(|| ly as usize * self.w + lx as usize) - } -} - -/// Placements and source sizes (for the vignetting radius). -pub type Geometry<'a> = (&'a [Placement], &'a [(usize, usize)]); - -/// Gains (per image, per channel) and the vignetting model found by [`photometric`]. -#[derive(Clone, Debug, PartialEq)] -pub struct Photometric { - pub gains: Vec>, - /// `log V(r) = a·r² + b·r⁴`, `r` = distance from the image centre over the half diagonal. - pub vignette: [f64; 2], -} - -impl Photometric { - /// Multiplier that corrects a pixel of image `i` at normalised squared radius `r2`. - pub fn factor(&self, i: usize, c: usize, r2: f64) -> f32 { - let v = (self.vignette[0] * r2 + self.vignette[1] * r2 * r2).exp(); - (1.0 / (self.gains[i][c] as f64 * v)) as f32 - } -} - -/// Estimates exposure gains (`gain`) and a shared vignetting falloff (`vignette`) from the -/// overlaps of `imgs` (`placements`/`sizes` give each panorama pixel's source radius). -/// Without `geometry` (placements and source sizes) the vignetting model is not estimated. -pub fn photometric(imgs: &[RoiImage], geometry: Option, gain: bool, vignette: bool) -> Photometric { - let vignette = vignette && geometry.is_some(); - let n = imgs.len(); - let ch = imgs.first().map_or(1, |i| i.ch); - let identity = Photometric { gains: vec![vec![1.0; ch]; n], vignette: [0.0, 0.0] }; - if n == 0 || (!gain && !vignette) { - return identity; - } - // Overlap samples on a grid: (a, b, colours, radii²). - let (mut x0, mut y0, mut x1, mut y1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN); - for im in imgs { - x0 = x0.min(im.x0); - y0 = y0.min(im.y0); - x1 = x1.max(im.x0 + im.w as i32); - y1 = y1.max(im.y0 + im.h as i32); - } - let step = (((x1 - x0) as i64 * (y1 - y0) as i64 / 40_000).max(1) as f64).sqrt().ceil() as i32; - let r2_of = |i: usize, u: i32, v: i32| -> Option { - let Some((placements, sizes)) = geometry else { return Some(0.0) }; - let (sx, sy) = placements[i].inverse(u as f64 + 0.5, v as f64 + 0.5)?; - let (w, h) = (sizes[i].0 as f64, sizes[i].1 as f64); - let (dx, dy) = (sx - w / 2.0, sy - h / 2.0); - Some((dx * dx + dy * dy) / (w * w / 4.0 + h * h / 4.0)) - }; - type Sample = (usize, usize, Vec, Vec, f64, f64); - let mut samples: Vec = Vec::new(); - let mut y = y0; - while y < y1 { - let mut x = x0; - while x < x1 { - let cover: Vec<(usize, usize)> = (0..n).filter_map(|i| imgs[i].at(x, y).filter(|&k| imgs[i].alpha[k] > 0.999).map(|k| (i, k))).collect(); - for p in 0..cover.len() { - for q in p + 1..cover.len() { - let ((a, ka), (b, kb)) = (cover[p], cover[q]); - let ca = imgs[a].px[ka * ch..(ka + 1) * ch].to_vec(); - let cb = imgs[b].px[kb * ch..(kb + 1) * ch].to_vec(); - if ca.iter().chain(&cb).any(|v| !(0.02..=0.98).contains(v)) { - continue; - } - // Disagreeing content (parallax, moving objects) says nothing about exposure. - if ca.iter().zip(&cb).any(|(x, y)| (x / y).ln().abs() > 1.0) { - continue; - } - let (Some(ra), Some(rb)) = (r2_of(a, x, y), r2_of(b, x, y)) else { continue }; - samples.push((a, b, ca, cb, ra, rb)); - } - } - x += step; - } - y += step; - } - if samples.len() < 20 { - return identity; - } - // Unknowns: log gain per image (per channel), then a, b (shared, from mean log intensity). - let sigma_n = 0.05; - let sigma_g = if gain { 0.15 } else { 1e-4 }; - let mut out = identity.clone(); - let nv = if vignette { 2 } else { 0 }; - // Vignetting is solved on the channel mean, then gains per channel with it fixed. - let mut ne = Normal::new(n + nv); - for (a, b, ca, cb, ra, rb) in &samples { - let la = ca.iter().map(|v| (*v as f64).ln()).sum::() / ch as f64; - let lb = cb.iter().map(|v| (*v as f64).ln()).sum::() / ch as f64; - let mut row = vec![(*a, 1.0), (*b, -1.0)]; - if vignette { - row.push((n, ra - rb)); - row.push((n + 1, ra * ra - rb * rb)); - } - ne.add(&row, la - lb, 1.0 / sigma_n); - } - for i in 0..n { - ne.add(&[(i, 1.0)], 0.0, 1.0 / sigma_g); - } - if vignette { - ne.add(&[(n, 1.0)], 0.0, 0.5); - ne.add(&[(n + 1, 1.0)], 0.0, 0.5); - } - let Some(sol) = ne.solve() else { return out }; - if vignette { - // Vignetting only darkens; clamp a runaway brightening fit. - out.vignette = [sol[n].clamp(-2.0, 0.5), sol[n + 1].clamp(-2.0, 2.0)]; - } - if gain { - for c in 0..ch { - let mut ne = Normal::new(n); - for (a, b, ca, cb, ra, rb) in &samples { - let va = out.vignette[0] * ra + out.vignette[1] * ra * ra; - let vb = out.vignette[0] * rb + out.vignette[1] * rb * rb; - ne.add(&[(*a, 1.0), (*b, -1.0)], ((ca[c] as f64).ln() - va) - ((cb[c] as f64).ln() - vb), 1.0 / sigma_n); - } - for i in 0..n { - ne.add(&[(i, 1.0)], 0.0, 1.0 / sigma_g); - } - if let Some(g) = ne.solve() { - for i in 0..n { - out.gains[i][c] = g[i].exp().clamp(0.2, 5.0) as f32; - } - } - } - } - out -} - -// ---------- seams ---------- - -/// Seam labels on a `w × h` grid (`-1` = no image): images are added in `order`; each new image -/// takes the part of its overlap with the composite that lies on its side of the cheapest path -/// through the overlap (cost = colour difference). -pub fn seam_labels(w: usize, h: usize, luma: &[Vec], cover: &[Vec], order: &[usize]) -> Vec { - let mut label = vec![-1i32; w * h]; - for &img in order { - let cov = &cover[img]; - let mut overlap = vec![false; w * h]; - let (mut sx, mut sy, mut no) = (0.0f64, 0.0f64, 0usize); - let (mut nx, mut ny, mut nn) = (0.0f64, 0.0f64, 0usize); - for i in 0..w * h { - if !cov[i] { - continue; - } - nx += (i % w) as f64; - ny += (i / w) as f64; - nn += 1; - if label[i] >= 0 { - overlap[i] = true; - sx += (i % w) as f64; - sy += (i / w) as f64; - no += 1; - } else { - label[i] = img as i32; - } - } - if no == 0 { - continue; - } - let (cx, cy) = (nx / nn as f64, ny / nn as f64); - let contained = nn == no; - let (ox, oy) = if contained { - // Wholly inside the composite (#5745: two photos in one document, the second moved - // by Auto-Align so the canvas crops it to the part over the first). Its side of the - // seam is the one it lies towards from the composite's centre; an image centred on - // the composite has no side, and the earlier images keep it. - let (mut px, mut py, mut pn) = (0.0f64, 0.0f64, 0usize); - for (i, l) in label.iter().enumerate() { - if *l >= 0 { - px += (i % w) as f64; - py += (i / w) as f64; - pn += 1; - } - } - let (px, py) = (px / pn.max(1) as f64, py / pn.max(1) as f64); - if (cx - px).abs() < 0.5 && (cy - py).abs() < 0.5 { - continue; - } - (px, py) - } else { - (sx / no as f64, sy / no as f64) - }; - let vertical = (cx - ox).abs() >= (cy - oy).abs(); - // Image on the increasing side along the seam's cross axis? - let positive = if vertical { cx > ox } else { cy > oy }; - // A contained image has no pixels of its own, so a seam on its outer edge would leave it - // nothing: break cost ties away from its side (towards larger k when it lies on the - // decreasing side) so it keeps its side of the overlap. - let prefer_high = contained && !positive; - let cost = |i: usize| -> f32 { 0.002 + (luma[img][i] - luma[label[i] as usize][i]).abs() }; - let (lines, len) = if vertical { (h, w) } else { (w, h) }; - let idx = |line: usize, k: usize| if vertical { line * w + k } else { k * w + line }; - // DP over lines (rows for a vertical seam), within the overlap. - let mut acc = vec![f32::INFINITY; w * h]; - let mut from = vec![usize::MAX; w * h]; - let mut prev_line: Option = None; - for line in 0..lines { - let any = (0..len).any(|k| overlap[idx(line, k)]); - if !any { - continue; - } - for k in 0..len { - let i = idx(line, k); - if !overlap[i] { - continue; - } - let mut best = (0.0f32, usize::MAX); - if let Some(pl) = prev_line.filter(|pl| *pl + 1 == line) { - best = (f32::INFINITY, usize::MAX); - let dks = if prefer_high { [1i64, 0, -1] } else { [-1i64, 0, 1] }; - for dk in dks { - let kk = k as i64 + dk; - if kk < 0 || kk >= len as i64 { - continue; - } - let j = idx(pl, kk as usize); - if acc[j] < best.0 { - best = (acc[j], kk as usize); - } - } - if best.1 == usize::MAX { - best = (0.0, usize::MAX); - } - } - acc[i] = best.0 + cost(i); - from[i] = best.1; - } - prev_line = Some(line); - } - // Backtrack from the cheapest end; lines not reached keep their own best cell. - let mut seam = vec![usize::MAX; lines]; - let mut line = lines; - while line > 0 { - line -= 1; - if seam[line] != usize::MAX { - continue; - } - let Some(k) = (0..len) - .filter(|&k| overlap[idx(line, k)]) - .min_by(|&a, &b| acc[idx(line, a)].total_cmp(&acc[idx(line, b)]).then(if prefer_high { b.cmp(&a) } else { a.cmp(&b) })) - else { - continue; - }; - let (mut l, mut k) = (line, k); - loop { - seam[l] = k; - let f = from[idx(l, k)]; - if f == usize::MAX || l == 0 { - break; - } - l -= 1; - if seam[l] != usize::MAX { - break; - } - k = f; - } - } - for line in 0..lines { - let s = seam[line]; - if s == usize::MAX { - continue; - } - let on_side = |k: usize| if positive { k > s } else { k < s }; - // A contained image has no other cells, so where the overlap has nothing on its side - // of the seam (a line one cell wide) it takes the seam cell rather than nothing. - let take_seam = contained && !(0..len).any(|k| overlap[idx(line, k)] && on_side(k)); - for k in 0..len { - let i = idx(line, k); - if overlap[i] && (on_side(k) || (take_seam && k == s)) { - label[i] = img as i32; - } - } - } - } - label -} - -// ---------- multi-band blending ---------- - -/// Number of pyramid levels used by [`multiband`] for a seam mask of this size. -pub fn blend_levels(w: usize, h: usize) -> usize { - let mut s = w.min(h); - let mut n = 1; - while s > 16 && n < 7 { - s /= 2; - n += 1; - } - n -} - -/// `a[i] ⊕ b[i]` for every `i` (the shorter length wins, like `zip`), in parallel on native -/// targets. Purely elementwise, so the result is the serial result bit for bit. -fn par_zip(a: &[f32], b: &[f32], f: impl Fn(f32, f32) -> f32 + Sync + Send) -> Vec { - const CHUNK: usize = 1 << 14; - let mut out = vec![0.0f32; a.len().min(b.len())]; - let fill = |o: &mut [f32], a: &[f32], b: &[f32]| { - for ((o, &a), &b) in o.iter_mut().zip(a).zip(b) { - *o = f(a, b); - } - }; - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - out.par_chunks_mut(CHUNK).zip(a.par_chunks(CHUNK)).zip(b.par_chunks(CHUNK)).for_each(|((o, a), b)| fill(o, a, b)); - } - #[cfg(target_arch = "wasm32")] - out.chunks_mut(CHUNK).zip(a.chunks(CHUNK)).zip(b.chunks(CHUNK)).for_each(|((o, a), b)| fill(o, a, b)); - out -} - -/// `f(a[i])` for every `i`, in parallel on native targets (elementwise, so bit for bit serial). -fn par_map1(a: &[f32], f: impl Fn(f32) -> f32 + Sync + Send) -> Vec { - par_zip(a, a, |x, _| f(x)) -} - -// `reduce`, `expand` and `push_pull` run one pyramid level for one image at a time, and the -// images themselves only fill part of a many-core machine, so each of them also runs its rows -// in parallel. Every output element is computed by the same expression, in the same order, as -// the one-thread loops they replace (rows never read each other's output), so the result is -// bit for bit unchanged. - -fn reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usize, Vec) { - let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); - let k = [1.0f32, 4.0, 6.0, 4.0, 1.0]; - // Separable 5-tap binomial, then decimate. - let mut tmp = vec![0.0f32; nw * h * ch]; - par_rows(&mut tmp, nw, ch, |y, row| { - let line = &src[y * w * ch..(y + 1) * w * ch]; - for x in 0..nw { - // The clamped source column of each tap is the same for every channel. - let xs: [usize; 5] = std::array::from_fn(|t| (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize * ch); - for c in 0..ch { - let mut s = 0.0; - for (kv, xx) in k.iter().zip(xs) { - s += kv * line[xx + c]; - } - row[x * ch + c] = s / 16.0; - } - } - }); - let mut out = vec![0.0f32; nw * nh * ch]; - par_rows(&mut out, nw, ch, |y, row| { - // Each output row is five source rows added in tap order: the same sum per element as - // before (`0 + k0·a + k1·b + …`), but over whole rows so it vectorises. - for (t, kv) in k.iter().enumerate() { - let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize; - for (o, &v) in row.iter_mut().zip(&tmp[yy * nw * ch..(yy + 1) * nw * ch]) { - *o += kv * v; - } - } - for o in row.iter_mut() { - *o /= 16.0; - } - }); - (nw, nh, out) -} - -fn expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Vec { - // Bilinear upsampling at half-pixel-aligned positions. - let mut out = vec![0.0f32; w * h * ch]; - // Source columns and weights depend on x only: worked out once instead of for every row. - // The clamped position is never negative, so truncating is `floor` (and spares the libm call). - let cols: Vec<(usize, usize, f32)> = (0..w) - .map(|x| { - let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32); - let x0 = fx as usize; - (x0 * ch, (x0 + 1).min(sw - 1) * ch, fx - x0 as f32) - }) - .collect(); - par_rows(&mut out, w, ch, |y, row| { - let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32); - let y0 = fy as usize; - let ty = fy - y0 as f32; - let y1 = (y0 + 1).min(sh - 1); - let (r0, r1) = (&src[y0 * sw * ch..(y0 + 1) * sw * ch], &src[y1 * sw * ch..(y1 + 1) * sw * ch]); - for (px, &(x0, x1, tx)) in row.chunks_exact_mut(ch.max(1)).zip(&cols) { - for (c, o) in px.iter_mut().enumerate() { - let top = r0[x0 + c] + (r0[x1 + c] - r0[x0 + c]) * tx; - let bot = r1[x0 + c] + (r1[x1 + c] - r1[x0 + c]) * tx; - *o = top + (bot - top) * ty; - } - } - }); - out -} - -/// Fills pixels with zero `wt` from their surroundings (push-pull), so pyramid levels don't -/// pull in black from outside an image. -fn push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) { - if w <= 1 && h <= 1 { - return; - } - let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); - // Coarse sums. A coarse row is fed by two fine rows; walking them in raster order adds each - // coarse cell's (up to) four fine pixels in the order the serial scatter-add did, from zero. - let mut cpx = vec![0.0f32; nw * nh * ch]; - let mut cw = vec![0.0f32; nw * nh]; - par_rows(&mut cw, nw, 1, |cy, row| { - for y in 2 * cy..(2 * cy + 2).min(h) { - for (x, &a) in wt[y * w..(y + 1) * w].iter().enumerate() { - row[x / 2] += a; - } - } - }); - let px_in: &[f32] = px; - par_rows(&mut cpx, nw, ch, |cy, row| { - for y in 2 * cy..(2 * cy + 2).min(h) { - for x in 0..w { - let (i, j) = (y * w + x, x / 2); - let a = wt[i]; - for c in 0..ch { - row[j * ch + c] += a * px_in[i * ch + c]; - } - } - } - }); - // Normalise by the weight (this reads `cw` before it is reset to 0 / 1 below). - par_rows(&mut cpx, nw, ch, |cy, row| { - for cx in 0..nw { - let wj = cw[cy * nw + cx]; - if wj > 0.0 { - for c in 0..ch { - row[cx * ch + c] /= wj; - } - } - } - }); - for v in cw.iter_mut() { - if *v > 0.0 { - *v = 1.0; - } - } - if cw.contains(&0.0) && cw.iter().any(|v| *v > 0.0) { - push_pull(nw, nh, ch, &mut cpx, &cw); - } - par_rows(px, w, ch, |y, row| { - for x in 0..w { - let i = y * w + x; - if wt[i] < 1.0 { - let j = (y / 2) * nw + x / 2; - let a = wt[i]; - for c in 0..ch { - row[x * ch + c] = a * row[x * ch + c] + (1.0 - a) * cpx[j * ch + c]; - } - } - } - }); -} - -/// One image's pyramid in [`multiband`]: the grid origin `(gx0, gy0)` at level 0, the Laplacian -/// levels `(w, h, colours)` and the Gaussian weight levels. -type PyramidBand = (i32, i32, Vec<(usize, usize, Vec)>, Vec>); - -/// The part of `band` on panorama row `py` of level `l`: the panorama column its first pixel -/// lands on, its width, its weight row and its colour row. `None` when it misses the row. -fn band_row(band: &PyramidBand, l: usize, ch: usize, py: usize) -> Option<(usize, usize, &[f32], &[f32])> { - let (ox, oy) = ((band.0 >> l) as usize, (band.1 >> l) as usize); - let (lw, lh, colours) = &band.2[l]; - (py >= oy && py - oy < *lh).then(|| { - let y = py - oy; - (ox, *lw, &band.3[l][y * lw..(y + 1) * lw], &colours[y * lw * ch..(y + 1) * lw * ch]) - }) -} - -/// Estimated bytes of band construction [`multiband`] keeps in flight at once. Images are built -/// and accumulated in batches under it, so its peak memory doesn't grow with the image count -/// (#7758). Four 24 MP RGB sources (~1.2 GB each) fit in one batch: building bands side by side -/// uses a many-core machine better than one band's row-parallel work, and one at a time made the -/// usual 2–4 image Photomerge 12–36% slower on a 32-thread desktop. -#[cfg(not(target_arch = "wasm32"))] -const BAND_BUDGET: usize = 5 << 30; -/// Without threads the bands of a batch are built one after another anyway, so each is added as -/// soon as it is built (the browser's address space is 4 GB). -#[cfg(target_arch = "wasm32")] -const BAND_BUDGET: usize = 0; - -/// Multi-band blend of `imgs` into a `w × h` panorama (origin 0,0) with one weight map per image -/// over the same grid as its ROI (`weights[i]` has `w_i × h_i` entries). Returns the colour -/// channels (`ch` per pixel) and the total coverage. -pub fn multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize) -> (Vec, Vec) { - multiband_batched(w, h, imgs, weights, levels, BAND_BUDGET) -} - -/// [`multiband`], building at most `budget` estimated bytes of bands at a time (at least one -/// image). Each pixel still adds the bands in image order, so the result doesn't depend on it. -fn multiband_batched(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize, budget: usize) -> (Vec, Vec) { - let ch = imgs.first().map_or(1, |i| i.ch); - let levels = levels.max(1); - let align = 1i32 << (levels - 1); - // Level sizes of the panorama. - let mut sizes = vec![(w, h)]; - for _ in 1..levels { - let Some(&(pw, ph)) = sizes.last() else { break }; - sizes.push((pw.div_ceil(2), ph.div_ceil(2))); - } - let mut acc: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh * ch]).collect(); - let mut wsum: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh]).collect(); - let margin = align * 4; - // Each image on its ROI grown by a margin and aligned to the coarsest level's grid. - let grid = |im: &RoiImage| { - let gx0 = ((im.x0 - margin).max(0) / align) * align; - let gy0 = ((im.y0 - margin).max(0) / align) * align; - let gx1 = (im.x0 + im.w as i32 + margin).min(w as i32); - let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32); - (gx0, gy0, (gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize) - }; - // Building one band holds its grid's colour and weight planes about three times over: the - // pyramids are 4/3 of a plane, and the grid copy, coverage and `expand` scratch come on top. - let cost = |im: &RoiImage| { - let (_, _, gw, gh) = grid(im); - gw.saturating_mul(gh).saturating_mul(ch + 1).saturating_mul(4 * 3) - }; - let band = |k: usize| -> PyramidBand { - let im = &imgs[k]; - let (gx0, gy0, gw, gh) = grid(im); - // Each grid pixel takes the image pixel that lands on it (every image pixel lands on at - // most one), so rows of the grid are independent and fill in parallel. - let src_of = |gx: usize, gy: usize| -> Option { - let (x, y) = (gx as i64 + gx0 as i64 - im.x0 as i64, gy as i64 + gy0 as i64 - im.y0 as i64); - (x >= 0 && y >= 0 && (x as usize) < im.w && (y as usize) < im.h).then(|| y as usize * im.w + x as usize) - }; - let mut px = vec![0.0f32; gw * gh * ch]; - par_rows(&mut px, gw, ch, |gy, row| { - for gx in 0..gw { - if let Some(i) = src_of(gx, gy) { - row[gx * ch..(gx + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]); - } - } - }); - let mut cov = vec![0.0f32; gw * gh]; - par_rows(&mut cov, gw, 1, |gy, row| { - for (gx, o) in row.iter_mut().enumerate() { - if let Some(i) = src_of(gx, gy) { - *o = im.alpha[i]; - } - } - }); - let mut wt = vec![0.0f32; gw * gh]; - par_rows(&mut wt, gw, 1, |gy, row| { - for (gx, o) in row.iter_mut().enumerate() { - if let Some(i) = src_of(gx, gy) { - *o = weights[k][i] * im.alpha[i].min(1.0); - } - } - }); - let bin: Vec = par_map1(&cov, |a| if a > 0.5 { 1.0 } else { 0.0 }); - drop(cov); - push_pull(gw, gh, ch, &mut px, &bin); - drop(bin); - // Laplacian of the colours, Gaussian of the weights. Planes move into the pyramids rather - // than being copied: with one image built at a time, a copy is a serial pass over it. - let mut lap: Vec<(usize, usize, Vec)> = Vec::new(); - let mut gau: Vec> = Vec::new(); - let (mut cw, mut chh, mut cur, mut cwt) = (gw, gh, px, wt); - for l in 0..levels { - if l + 1 == levels { - lap.push((cw, chh, cur)); - gau.push(cwt); - break; - } - let (nw, nh, down) = reduce(cw, chh, ch, &cur); - let up = expand(nw, nh, ch, &down, cw, chh); - lap.push((cw, chh, par_zip(&cur, &up, |a, b| a - b))); - let (_, _, wdown) = reduce(cw, chh, 1, &cwt); - gau.push(cwt); - cw = nw; - chh = nh; - cur = down; - cwt = wdown; - } - (gx0, gy0, lap, gau) - }; - // Build the bands a batch at a time and add each batch before building the next. Each pixel - // adds the bands in the same order as the serial loop (per level, bands one after another; - // batches follow each other in image order), but rows of a level are independent, so they - // run in parallel: every row walks the batch's bands itself. - let mut start = 0; - while start < imgs.len() { - let mut end = start + 1; - let mut bytes = cost(&imgs[start]); - while let Some(im) = imgs.get(end) - && bytes.saturating_add(cost(im)) <= budget - { - bytes = bytes.saturating_add(cost(im)); - end += 1; - } - let bands = par_map(end - start, |j| band(start + j)); - for l in 0..levels { - let pw = sizes[l].0; - par_rows(&mut wsum[l], pw, 1, |py, row| { - for b in &bands { - let Some((ox, lw, g, _)) = band_row(b, l, ch, py) else { continue }; - for x in 0..lw { - let px = ox + x; - if px >= pw { - break; - } - let k = g[x]; - if k <= 0.0 { - continue; - } - row[px] += k; - } - } - }); - par_rows(&mut acc[l], pw, ch, |py, row| { - for b in &bands { - let Some((ox, lw, g, band)) = band_row(b, l, ch, py) else { continue }; - for x in 0..lw { - let px = ox + x; - if px >= pw { - break; - } - let k = g[x]; - if k <= 0.0 { - continue; - } - for c in 0..ch { - row[px * ch + c] += k * band[x * ch + c]; - } - } - } - }); - } - start = end; - } - for l in 0..levels { - let pw = sizes[l].0; - let ws = &wsum[l]; - par_rows(&mut acc[l], pw, ch, |py, row| { - for x in 0..pw { - let k = ws[py * pw + x]; - for c in 0..ch { - row[x * ch + c] = if k > 1e-8 { row[x * ch + c] / k } else { 0.0 }; - } - } - }); - } - // Collapse. - // `levels ≥ 1`, so there is always a coarsest level. - let Some(mut cur) = acc.pop() else { return (vec![0.0; w * h * ch], vec![0.0; w * h]) }; - for l in (0..levels - 1).rev() { - let (pw, ph) = sizes[l]; - let (sw, sh) = sizes[l + 1]; - let up = expand(sw, sh, ch, &cur, pw, ph); - cur = par_zip(&acc[l], &up, |a, b| a + b); - } - // Coverage: union of the images. Rows are independent; each walks the images in order, so a - // pixel sees the same sequence of `max` calls as in the serial loop. - let mut cov = vec![0.0f32; w * h]; - par_rows(&mut cov, w, 1, |py, row| { - for im in imgs { - let y = py as i64 - im.y0 as i64; - if y < 0 || y as usize >= im.h { - continue; - } - for x in 0..im.w { - let px = im.x0 + x as i32; - if px < 0 || px as usize >= w { - continue; - } - let p = px as usize; - row[p] = row[p].max(im.alpha[y as usize * im.w + x]); - } - } - }); - (cur, cov) -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/algo/src/panorama/blend.rs b/crates/algo/src/panorama/blend.rs new file mode 100644 index 0000000000..1aaa821c14 --- /dev/null +++ b/crates/algo/src/panorama/blend.rs @@ -0,0 +1,692 @@ +use super::*; + +// ---------- photometric ---------- + +/// One image warped into the panorama: an axis-aligned region with colour channels and coverage. +#[derive(Clone, Debug)] +pub struct RoiImage { + pub x0: i32, + pub y0: i32, + pub w: usize, + pub h: usize, + /// Colour channels per pixel (no alpha). + pub ch: usize, + pub px: Vec, + /// Coverage `0..=1`. + pub alpha: Vec, +} + +impl RoiImage { + fn at(&self, x: i32, y: i32) -> Option { + let (lx, ly) = (x - self.x0, y - self.y0); + (lx >= 0 && ly >= 0 && (lx as usize) < self.w && (ly as usize) < self.h).then(|| ly as usize * self.w + lx as usize) + } +} + +/// Placements and source sizes (for the vignetting radius). +pub type Geometry<'a> = (&'a [Placement], &'a [(usize, usize)]); + +/// Gains (per image, per channel) and the vignetting model found by [`photometric`]. +#[derive(Clone, Debug, PartialEq)] +pub struct Photometric { + pub gains: Vec>, + /// `log V(r) = a·r² + b·r⁴`, `r` = distance from the image centre over the half diagonal. + pub vignette: [f64; 2], +} + +impl Photometric { + /// Multiplier that corrects a pixel of image `i` at normalised squared radius `r2`. + pub fn factor(&self, i: usize, c: usize, r2: f64) -> f32 { + let v = (self.vignette[0] * r2 + self.vignette[1] * r2 * r2).exp(); + (1.0 / (self.gains[i][c] as f64 * v)) as f32 + } +} + +/// Estimates exposure gains (`gain`) and a shared vignetting falloff (`vignette`) from the +/// overlaps of `imgs` (`placements`/`sizes` give each panorama pixel's source radius). +/// Without `geometry` (placements and source sizes) the vignetting model is not estimated. +pub fn photometric(imgs: &[RoiImage], geometry: Option, gain: bool, vignette: bool) -> Photometric { + let vignette = vignette && geometry.is_some(); + let n = imgs.len(); + let ch = imgs.first().map_or(1, |i| i.ch); + let identity = Photometric { gains: vec![vec![1.0; ch]; n], vignette: [0.0, 0.0] }; + if n == 0 || (!gain && !vignette) { + return identity; + } + // Overlap samples on a grid: (a, b, colours, radii²). + let (mut x0, mut y0, mut x1, mut y1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN); + for im in imgs { + x0 = x0.min(im.x0); + y0 = y0.min(im.y0); + x1 = x1.max(im.x0 + im.w as i32); + y1 = y1.max(im.y0 + im.h as i32); + } + let step = (((x1 - x0) as i64 * (y1 - y0) as i64 / 40_000).max(1) as f64).sqrt().ceil() as i32; + let r2_of = |i: usize, u: i32, v: i32| -> Option { + let Some((placements, sizes)) = geometry else { return Some(0.0) }; + let (sx, sy) = placements[i].inverse(u as f64 + 0.5, v as f64 + 0.5)?; + let (w, h) = (sizes[i].0 as f64, sizes[i].1 as f64); + let (dx, dy) = (sx - w / 2.0, sy - h / 2.0); + Some((dx * dx + dy * dy) / (w * w / 4.0 + h * h / 4.0)) + }; + type Sample = (usize, usize, Vec, Vec, f64, f64); + let mut samples: Vec = Vec::new(); + let mut y = y0; + while y < y1 { + let mut x = x0; + while x < x1 { + let cover: Vec<(usize, usize)> = (0..n).filter_map(|i| imgs[i].at(x, y).filter(|&k| imgs[i].alpha[k] > 0.999).map(|k| (i, k))).collect(); + for p in 0..cover.len() { + for q in p + 1..cover.len() { + let ((a, ka), (b, kb)) = (cover[p], cover[q]); + let ca = imgs[a].px[ka * ch..(ka + 1) * ch].to_vec(); + let cb = imgs[b].px[kb * ch..(kb + 1) * ch].to_vec(); + if ca.iter().chain(&cb).any(|v| !(0.02..=0.98).contains(v)) { + continue; + } + // Disagreeing content (parallax, moving objects) says nothing about exposure. + if ca.iter().zip(&cb).any(|(x, y)| (x / y).ln().abs() > 1.0) { + continue; + } + let (Some(ra), Some(rb)) = (r2_of(a, x, y), r2_of(b, x, y)) else { continue }; + samples.push((a, b, ca, cb, ra, rb)); + } + } + x += step; + } + y += step; + } + if samples.len() < 20 { + return identity; + } + // Unknowns: log gain per image (per channel), then a, b (shared, from mean log intensity). + let sigma_n = 0.05; + let sigma_g = if gain { 0.15 } else { 1e-4 }; + let mut out = identity.clone(); + let nv = if vignette { 2 } else { 0 }; + // Vignetting is solved on the channel mean, then gains per channel with it fixed. + let mut ne = Normal::new(n + nv); + for (a, b, ca, cb, ra, rb) in &samples { + let la = ca.iter().map(|v| (*v as f64).ln()).sum::() / ch as f64; + let lb = cb.iter().map(|v| (*v as f64).ln()).sum::() / ch as f64; + let mut row = vec![(*a, 1.0), (*b, -1.0)]; + if vignette { + row.push((n, ra - rb)); + row.push((n + 1, ra * ra - rb * rb)); + } + ne.add(&row, la - lb, 1.0 / sigma_n); + } + for i in 0..n { + ne.add(&[(i, 1.0)], 0.0, 1.0 / sigma_g); + } + if vignette { + ne.add(&[(n, 1.0)], 0.0, 0.5); + ne.add(&[(n + 1, 1.0)], 0.0, 0.5); + } + let Some(sol) = ne.solve() else { return out }; + if vignette { + // Vignetting only darkens; clamp a runaway brightening fit. + out.vignette = [sol[n].clamp(-2.0, 0.5), sol[n + 1].clamp(-2.0, 2.0)]; + } + if gain { + for c in 0..ch { + let mut ne = Normal::new(n); + for (a, b, ca, cb, ra, rb) in &samples { + let va = out.vignette[0] * ra + out.vignette[1] * ra * ra; + let vb = out.vignette[0] * rb + out.vignette[1] * rb * rb; + ne.add(&[(*a, 1.0), (*b, -1.0)], ((ca[c] as f64).ln() - va) - ((cb[c] as f64).ln() - vb), 1.0 / sigma_n); + } + for i in 0..n { + ne.add(&[(i, 1.0)], 0.0, 1.0 / sigma_g); + } + if let Some(g) = ne.solve() { + for i in 0..n { + out.gains[i][c] = g[i].exp().clamp(0.2, 5.0) as f32; + } + } + } + } + out +} + +// ---------- seams ---------- + +/// Seam labels on a `w × h` grid (`-1` = no image): images are added in `order`; each new image +/// takes the part of its overlap with the composite that lies on its side of the cheapest path +/// through the overlap (cost = colour difference). +pub fn seam_labels(w: usize, h: usize, luma: &[Vec], cover: &[Vec], order: &[usize]) -> Vec { + let mut label = vec![-1i32; w * h]; + for &img in order { + let cov = &cover[img]; + let mut overlap = vec![false; w * h]; + let (mut sx, mut sy, mut no) = (0.0f64, 0.0f64, 0usize); + let (mut nx, mut ny, mut nn) = (0.0f64, 0.0f64, 0usize); + for i in 0..w * h { + if !cov[i] { + continue; + } + nx += (i % w) as f64; + ny += (i / w) as f64; + nn += 1; + if label[i] >= 0 { + overlap[i] = true; + sx += (i % w) as f64; + sy += (i / w) as f64; + no += 1; + } else { + label[i] = img as i32; + } + } + if no == 0 { + continue; + } + let (cx, cy) = (nx / nn as f64, ny / nn as f64); + let contained = nn == no; + let (ox, oy) = if contained { + // Wholly inside the composite (#5745: two photos in one document, the second moved + // by Auto-Align so the canvas crops it to the part over the first). Its side of the + // seam is the one it lies towards from the composite's centre; an image centred on + // the composite has no side, and the earlier images keep it. + let (mut px, mut py, mut pn) = (0.0f64, 0.0f64, 0usize); + for (i, l) in label.iter().enumerate() { + if *l >= 0 { + px += (i % w) as f64; + py += (i / w) as f64; + pn += 1; + } + } + let (px, py) = (px / pn.max(1) as f64, py / pn.max(1) as f64); + if (cx - px).abs() < 0.5 && (cy - py).abs() < 0.5 { + continue; + } + (px, py) + } else { + (sx / no as f64, sy / no as f64) + }; + let vertical = (cx - ox).abs() >= (cy - oy).abs(); + // Image on the increasing side along the seam's cross axis? + let positive = if vertical { cx > ox } else { cy > oy }; + // A contained image has no pixels of its own, so a seam on its outer edge would leave it + // nothing: break cost ties away from its side (towards larger k when it lies on the + // decreasing side) so it keeps its side of the overlap. + let prefer_high = contained && !positive; + let cost = |i: usize| -> f32 { 0.002 + (luma[img][i] - luma[label[i] as usize][i]).abs() }; + let (lines, len) = if vertical { (h, w) } else { (w, h) }; + let idx = |line: usize, k: usize| if vertical { line * w + k } else { k * w + line }; + // DP over lines (rows for a vertical seam), within the overlap. + let mut acc = vec![f32::INFINITY; w * h]; + let mut from = vec![usize::MAX; w * h]; + let mut prev_line: Option = None; + for line in 0..lines { + let any = (0..len).any(|k| overlap[idx(line, k)]); + if !any { + continue; + } + for k in 0..len { + let i = idx(line, k); + if !overlap[i] { + continue; + } + let mut best = (0.0f32, usize::MAX); + if let Some(pl) = prev_line.filter(|pl| *pl + 1 == line) { + best = (f32::INFINITY, usize::MAX); + let dks = if prefer_high { [1i64, 0, -1] } else { [-1i64, 0, 1] }; + for dk in dks { + let kk = k as i64 + dk; + if kk < 0 || kk >= len as i64 { + continue; + } + let j = idx(pl, kk as usize); + if acc[j] < best.0 { + best = (acc[j], kk as usize); + } + } + if best.1 == usize::MAX { + best = (0.0, usize::MAX); + } + } + acc[i] = best.0 + cost(i); + from[i] = best.1; + } + prev_line = Some(line); + } + // Backtrack from the cheapest end; lines not reached keep their own best cell. + let mut seam = vec![usize::MAX; lines]; + let mut line = lines; + while line > 0 { + line -= 1; + if seam[line] != usize::MAX { + continue; + } + let Some(k) = (0..len) + .filter(|&k| overlap[idx(line, k)]) + .min_by(|&a, &b| acc[idx(line, a)].total_cmp(&acc[idx(line, b)]).then(if prefer_high { b.cmp(&a) } else { a.cmp(&b) })) + else { + continue; + }; + let (mut l, mut k) = (line, k); + loop { + seam[l] = k; + let f = from[idx(l, k)]; + if f == usize::MAX || l == 0 { + break; + } + l -= 1; + if seam[l] != usize::MAX { + break; + } + k = f; + } + } + for line in 0..lines { + let s = seam[line]; + if s == usize::MAX { + continue; + } + let on_side = |k: usize| if positive { k > s } else { k < s }; + // A contained image has no other cells, so where the overlap has nothing on its side + // of the seam (a line one cell wide) it takes the seam cell rather than nothing. + let take_seam = contained && !(0..len).any(|k| overlap[idx(line, k)] && on_side(k)); + for k in 0..len { + let i = idx(line, k); + if overlap[i] && (on_side(k) || (take_seam && k == s)) { + label[i] = img as i32; + } + } + } + } + label +} + +// ---------- multi-band blending ---------- + +/// Number of pyramid levels used by [`multiband`] for a seam mask of this size. +pub fn blend_levels(w: usize, h: usize) -> usize { + let mut s = w.min(h); + let mut n = 1; + while s > 16 && n < 7 { + s /= 2; + n += 1; + } + n +} + +/// `a[i] ⊕ b[i]` for every `i` (the shorter length wins, like `zip`), in parallel on native +/// targets. Purely elementwise, so the result is the serial result bit for bit. +fn par_zip(a: &[f32], b: &[f32], f: impl Fn(f32, f32) -> f32 + Sync + Send) -> Vec { + const CHUNK: usize = 1 << 14; + let mut out = vec![0.0f32; a.len().min(b.len())]; + let fill = |o: &mut [f32], a: &[f32], b: &[f32]| { + for ((o, &a), &b) in o.iter_mut().zip(a).zip(b) { + *o = f(a, b); + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + out.par_chunks_mut(CHUNK).zip(a.par_chunks(CHUNK)).zip(b.par_chunks(CHUNK)).for_each(|((o, a), b)| fill(o, a, b)); + } + #[cfg(target_arch = "wasm32")] + out.chunks_mut(CHUNK).zip(a.chunks(CHUNK)).zip(b.chunks(CHUNK)).for_each(|((o, a), b)| fill(o, a, b)); + out +} + +/// `f(a[i])` for every `i`, in parallel on native targets (elementwise, so bit for bit serial). +fn par_map1(a: &[f32], f: impl Fn(f32) -> f32 + Sync + Send) -> Vec { + par_zip(a, a, |x, _| f(x)) +} + +// `reduce`, `expand` and `push_pull` run one pyramid level for one image at a time, and the +// images themselves only fill part of a many-core machine, so each of them also runs its rows +// in parallel. Every output element is computed by the same expression, in the same order, as +// the one-thread loops they replace (rows never read each other's output), so the result is +// bit for bit unchanged. + +pub(super) fn reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usize, Vec) { + let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); + let k = [1.0f32, 4.0, 6.0, 4.0, 1.0]; + // Separable 5-tap binomial, then decimate. + let mut tmp = vec![0.0f32; nw * h * ch]; + par_rows(&mut tmp, nw, ch, |y, row| { + let line = &src[y * w * ch..(y + 1) * w * ch]; + for x in 0..nw { + // The clamped source column of each tap is the same for every channel. + let xs: [usize; 5] = std::array::from_fn(|t| (2 * x as i64 + t as i64 - 2).clamp(0, w as i64 - 1) as usize * ch); + for c in 0..ch { + let mut s = 0.0; + for (kv, xx) in k.iter().zip(xs) { + s += kv * line[xx + c]; + } + row[x * ch + c] = s / 16.0; + } + } + }); + let mut out = vec![0.0f32; nw * nh * ch]; + par_rows(&mut out, nw, ch, |y, row| { + // Each output row is five source rows added in tap order: the same sum per element as + // before (`0 + k0·a + k1·b + …`), but over whole rows so it vectorises. + for (t, kv) in k.iter().enumerate() { + let yy = (2 * y as i64 + t as i64 - 2).clamp(0, h as i64 - 1) as usize; + for (o, &v) in row.iter_mut().zip(&tmp[yy * nw * ch..(yy + 1) * nw * ch]) { + *o += kv * v; + } + } + for o in row.iter_mut() { + *o /= 16.0; + } + }); + (nw, nh, out) +} + +pub(super) fn expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Vec { + // Bilinear upsampling at half-pixel-aligned positions. + let mut out = vec![0.0f32; w * h * ch]; + // Source columns and weights depend on x only: worked out once instead of for every row. + // The clamped position is never negative, so truncating is `floor` (and spares the libm call). + let cols: Vec<(usize, usize, f32)> = (0..w) + .map(|x| { + let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32); + let x0 = fx as usize; + (x0 * ch, (x0 + 1).min(sw - 1) * ch, fx - x0 as f32) + }) + .collect(); + par_rows(&mut out, w, ch, |y, row| { + let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32); + let y0 = fy as usize; + let ty = fy - y0 as f32; + let y1 = (y0 + 1).min(sh - 1); + let (r0, r1) = (&src[y0 * sw * ch..(y0 + 1) * sw * ch], &src[y1 * sw * ch..(y1 + 1) * sw * ch]); + for (px, &(x0, x1, tx)) in row.chunks_exact_mut(ch.max(1)).zip(&cols) { + for (c, o) in px.iter_mut().enumerate() { + let top = r0[x0 + c] + (r0[x1 + c] - r0[x0 + c]) * tx; + let bot = r1[x0 + c] + (r1[x1 + c] - r1[x0 + c]) * tx; + *o = top + (bot - top) * ty; + } + } + }); + out +} + +/// Fills pixels with zero `wt` from their surroundings (push-pull), so pyramid levels don't +/// pull in black from outside an image. +pub(super) fn push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) { + if w <= 1 && h <= 1 { + return; + } + let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); + // Coarse sums. A coarse row is fed by two fine rows; walking them in raster order adds each + // coarse cell's (up to) four fine pixels in the order the serial scatter-add did, from zero. + let mut cpx = vec![0.0f32; nw * nh * ch]; + let mut cw = vec![0.0f32; nw * nh]; + par_rows(&mut cw, nw, 1, |cy, row| { + for y in 2 * cy..(2 * cy + 2).min(h) { + for (x, &a) in wt[y * w..(y + 1) * w].iter().enumerate() { + row[x / 2] += a; + } + } + }); + let px_in: &[f32] = px; + par_rows(&mut cpx, nw, ch, |cy, row| { + for y in 2 * cy..(2 * cy + 2).min(h) { + for x in 0..w { + let (i, j) = (y * w + x, x / 2); + let a = wt[i]; + for c in 0..ch { + row[j * ch + c] += a * px_in[i * ch + c]; + } + } + } + }); + // Normalise by the weight (this reads `cw` before it is reset to 0 / 1 below). + par_rows(&mut cpx, nw, ch, |cy, row| { + for cx in 0..nw { + let wj = cw[cy * nw + cx]; + if wj > 0.0 { + for c in 0..ch { + row[cx * ch + c] /= wj; + } + } + } + }); + for v in cw.iter_mut() { + if *v > 0.0 { + *v = 1.0; + } + } + if cw.contains(&0.0) && cw.iter().any(|v| *v > 0.0) { + push_pull(nw, nh, ch, &mut cpx, &cw); + } + par_rows(px, w, ch, |y, row| { + for x in 0..w { + let i = y * w + x; + if wt[i] < 1.0 { + let j = (y / 2) * nw + x / 2; + let a = wt[i]; + for c in 0..ch { + row[x * ch + c] = a * row[x * ch + c] + (1.0 - a) * cpx[j * ch + c]; + } + } + } + }); +} + +/// One image's pyramid in [`multiband`]: the grid origin `(gx0, gy0)` at level 0, the Laplacian +/// levels `(w, h, colours)` and the Gaussian weight levels. +type PyramidBand = (i32, i32, Vec<(usize, usize, Vec)>, Vec>); + +/// The part of `band` on panorama row `py` of level `l`: the panorama column its first pixel +/// lands on, its width, its weight row and its colour row. `None` when it misses the row. +fn band_row(band: &PyramidBand, l: usize, ch: usize, py: usize) -> Option<(usize, usize, &[f32], &[f32])> { + let (ox, oy) = ((band.0 >> l) as usize, (band.1 >> l) as usize); + let (lw, lh, colours) = &band.2[l]; + (py >= oy && py - oy < *lh).then(|| { + let y = py - oy; + (ox, *lw, &band.3[l][y * lw..(y + 1) * lw], &colours[y * lw * ch..(y + 1) * lw * ch]) + }) +} + +/// Estimated bytes of band construction [`multiband`] keeps in flight at once. Images are built +/// and accumulated in batches under it, so its peak memory doesn't grow with the image count +/// (#7758). Four 24 MP RGB sources (~1.2 GB each) fit in one batch: building bands side by side +/// uses a many-core machine better than one band's row-parallel work, and one at a time made the +/// usual 2–4 image Photomerge 12–36% slower on a 32-thread desktop. +#[cfg(not(target_arch = "wasm32"))] +const BAND_BUDGET: usize = 5 << 30; + +/// Without threads the bands of a batch are built one after another anyway, so each is added as +/// soon as it is built (the browser's address space is 4 GB). +#[cfg(target_arch = "wasm32")] +const BAND_BUDGET: usize = 0; + +/// Multi-band blend of `imgs` into a `w × h` panorama (origin 0,0) with one weight map per image +/// over the same grid as its ROI (`weights[i]` has `w_i × h_i` entries). Returns the colour +/// channels (`ch` per pixel) and the total coverage. +pub fn multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize) -> (Vec, Vec) { + multiband_batched(w, h, imgs, weights, levels, BAND_BUDGET) +} + +/// [`multiband`], building at most `budget` estimated bytes of bands at a time (at least one +/// image). Each pixel still adds the bands in image order, so the result doesn't depend on it. +pub(super) fn multiband_batched(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize, budget: usize) -> (Vec, Vec) { + let ch = imgs.first().map_or(1, |i| i.ch); + let levels = levels.max(1); + let align = 1i32 << (levels - 1); + // Level sizes of the panorama. + let mut sizes = vec![(w, h)]; + for _ in 1..levels { + let Some(&(pw, ph)) = sizes.last() else { break }; + sizes.push((pw.div_ceil(2), ph.div_ceil(2))); + } + let mut acc: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh * ch]).collect(); + let mut wsum: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh]).collect(); + let margin = align * 4; + // Each image on its ROI grown by a margin and aligned to the coarsest level's grid. + let grid = |im: &RoiImage| { + let gx0 = ((im.x0 - margin).max(0) / align) * align; + let gy0 = ((im.y0 - margin).max(0) / align) * align; + let gx1 = (im.x0 + im.w as i32 + margin).min(w as i32); + let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32); + (gx0, gy0, (gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize) + }; + // Building one band holds its grid's colour and weight planes about three times over: the + // pyramids are 4/3 of a plane, and the grid copy, coverage and `expand` scratch come on top. + let cost = |im: &RoiImage| { + let (_, _, gw, gh) = grid(im); + gw.saturating_mul(gh).saturating_mul(ch + 1).saturating_mul(4 * 3) + }; + let band = |k: usize| -> PyramidBand { + let im = &imgs[k]; + let (gx0, gy0, gw, gh) = grid(im); + // Each grid pixel takes the image pixel that lands on it (every image pixel lands on at + // most one), so rows of the grid are independent and fill in parallel. + let src_of = |gx: usize, gy: usize| -> Option { + let (x, y) = (gx as i64 + gx0 as i64 - im.x0 as i64, gy as i64 + gy0 as i64 - im.y0 as i64); + (x >= 0 && y >= 0 && (x as usize) < im.w && (y as usize) < im.h).then(|| y as usize * im.w + x as usize) + }; + let mut px = vec![0.0f32; gw * gh * ch]; + par_rows(&mut px, gw, ch, |gy, row| { + for gx in 0..gw { + if let Some(i) = src_of(gx, gy) { + row[gx * ch..(gx + 1) * ch].copy_from_slice(&im.px[i * ch..(i + 1) * ch]); + } + } + }); + let mut cov = vec![0.0f32; gw * gh]; + par_rows(&mut cov, gw, 1, |gy, row| { + for (gx, o) in row.iter_mut().enumerate() { + if let Some(i) = src_of(gx, gy) { + *o = im.alpha[i]; + } + } + }); + let mut wt = vec![0.0f32; gw * gh]; + par_rows(&mut wt, gw, 1, |gy, row| { + for (gx, o) in row.iter_mut().enumerate() { + if let Some(i) = src_of(gx, gy) { + *o = weights[k][i] * im.alpha[i].min(1.0); + } + } + }); + let bin: Vec = par_map1(&cov, |a| if a > 0.5 { 1.0 } else { 0.0 }); + drop(cov); + push_pull(gw, gh, ch, &mut px, &bin); + drop(bin); + // Laplacian of the colours, Gaussian of the weights. Planes move into the pyramids rather + // than being copied: with one image built at a time, a copy is a serial pass over it. + let mut lap: Vec<(usize, usize, Vec)> = Vec::new(); + let mut gau: Vec> = Vec::new(); + let (mut cw, mut chh, mut cur, mut cwt) = (gw, gh, px, wt); + for l in 0..levels { + if l + 1 == levels { + lap.push((cw, chh, cur)); + gau.push(cwt); + break; + } + let (nw, nh, down) = reduce(cw, chh, ch, &cur); + let up = expand(nw, nh, ch, &down, cw, chh); + lap.push((cw, chh, par_zip(&cur, &up, |a, b| a - b))); + let (_, _, wdown) = reduce(cw, chh, 1, &cwt); + gau.push(cwt); + cw = nw; + chh = nh; + cur = down; + cwt = wdown; + } + (gx0, gy0, lap, gau) + }; + // Build the bands a batch at a time and add each batch before building the next. Each pixel + // adds the bands in the same order as the serial loop (per level, bands one after another; + // batches follow each other in image order), but rows of a level are independent, so they + // run in parallel: every row walks the batch's bands itself. + let mut start = 0; + while start < imgs.len() { + let mut end = start + 1; + let mut bytes = cost(&imgs[start]); + while let Some(im) = imgs.get(end) + && bytes.saturating_add(cost(im)) <= budget + { + bytes = bytes.saturating_add(cost(im)); + end += 1; + } + let bands = par_map(end - start, |j| band(start + j)); + for l in 0..levels { + let pw = sizes[l].0; + par_rows(&mut wsum[l], pw, 1, |py, row| { + for b in &bands { + let Some((ox, lw, g, _)) = band_row(b, l, ch, py) else { continue }; + for x in 0..lw { + let px = ox + x; + if px >= pw { + break; + } + let k = g[x]; + if k <= 0.0 { + continue; + } + row[px] += k; + } + } + }); + par_rows(&mut acc[l], pw, ch, |py, row| { + for b in &bands { + let Some((ox, lw, g, band)) = band_row(b, l, ch, py) else { continue }; + for x in 0..lw { + let px = ox + x; + if px >= pw { + break; + } + let k = g[x]; + if k <= 0.0 { + continue; + } + for c in 0..ch { + row[px * ch + c] += k * band[x * ch + c]; + } + } + } + }); + } + start = end; + } + for l in 0..levels { + let pw = sizes[l].0; + let ws = &wsum[l]; + par_rows(&mut acc[l], pw, ch, |py, row| { + for x in 0..pw { + let k = ws[py * pw + x]; + for c in 0..ch { + row[x * ch + c] = if k > 1e-8 { row[x * ch + c] / k } else { 0.0 }; + } + } + }); + } + // Collapse. + // `levels ≥ 1`, so there is always a coarsest level. + let Some(mut cur) = acc.pop() else { return (vec![0.0; w * h * ch], vec![0.0; w * h]) }; + for l in (0..levels - 1).rev() { + let (pw, ph) = sizes[l]; + let (sw, sh) = sizes[l + 1]; + let up = expand(sw, sh, ch, &cur, pw, ph); + cur = par_zip(&acc[l], &up, |a, b| a + b); + } + // Coverage: union of the images. Rows are independent; each walks the images in order, so a + // pixel sees the same sequence of `max` calls as in the serial loop. + let mut cov = vec![0.0f32; w * h]; + par_rows(&mut cov, w, 1, |py, row| { + for im in imgs { + let y = py as i64 - im.y0 as i64; + if y < 0 || y as usize >= im.h { + continue; + } + for x in 0..im.w { + let px = im.x0 + x as i32; + if px < 0 || px as usize >= w { + continue; + } + let p = px as usize; + row[p] = row[p].max(im.alpha[y as usize * im.w + x]); + } + } + }); + (cur, cov) +} From 2aa88b0956f47048a08813f3bdcb99b06b748e62 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:19:10 +0000 Subject: [PATCH 252/259] refactor(io): split psd_export.rs into psd_export/ --- crates/io/src/psd_export.rs | 1044 +------------------------ crates/io/src/psd_export/document.rs | 391 +++++++++ crates/io/src/psd_export/estimate.rs | 135 ++++ crates/io/src/psd_export/merged.rs | 143 ++++ crates/io/src/psd_export/resources.rs | 116 +++ crates/io/src/psd_export/smart.rs | 253 ++++++ crates/io/src/psd_export/tests.rs | 12 +- 7 files changed, 1059 insertions(+), 1035 deletions(-) create mode 100644 crates/io/src/psd_export/document.rs create mode 100644 crates/io/src/psd_export/estimate.rs create mode 100644 crates/io/src/psd_export/merged.rs create mode 100644 crates/io/src/psd_export/resources.rs create mode 100644 crates/io/src/psd_export/smart.rs diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index af4739b661..0c809273a9 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -15,6 +15,23 @@ use crate::blocks; use crate::pixels::{deinterleave, encode_be, psd_depth}; use crate::psd_import::REGENERATED; +mod document; +mod estimate; +mod merged; +mod resources; +mod smart; + +pub(crate) use document::document_to_psd_interruptible; +pub use document::{document_to_psd, document_to_psd_with}; +use document::{document_to_psd_nested, mask_parameters}; +#[cfg(test)] +pub(crate) use estimate::estimate_psd_size; +pub(crate) use estimate::{block_signature, psd_size_exceeds_limit, psd_version}; +#[cfg(test)] +use estimate::{estimate_encoded_size, exceeds_psd_size_limit}; +pub(crate) use resources::{global_block, guides_resource, keep_imported_resource, legacy_name, pascal_names_resource, path_resources, unicode_names_resource}; +use smart::{LINK_KEYS, SmartOut, Source, contents_uuid, effects_unchanged, masked, size_from_layer, smart_keys, upsert}; + /// Blocks that define a layer's content as something other than pixels: fill (`SoCo`, `GdFl`, /// `PtFl`), placed / smart object (`SoLd`, `PlLd`, `SoLE`), type (`TySh`) and shape fill (`vscg`). /// A raster layer never writes them, nor adjustment blocks. @@ -138,202 +155,6 @@ fn psd_background(doc: &Document) -> Option { /// as pixels instead. const MAX_NESTING: u32 = 8; -/// An embedded smart-object source as written to `lnk2`. -#[derive(Clone, Debug)] -struct Source { - uuid: String, - /// Pixel size of the source document. - size: (f64, f64), - dpi: f64, -} - -fn contents_uuid(contents_id: SmartContentsId, bytes: &[u8]) -> String { - let mut identity = blake3::Hasher::new(); - identity.update(&contents_id.0.to_le_bytes()); - identity.update(bytes); - crate::smart_map::uuid_from(identity.finalize().as_bytes()) -} - -/// Smart-object state collected while emitting layers, written into the global blocks at the end. -#[derive(Default)] -struct SmartOut { - /// Nesting depth of this export (embedded documents are exported recursively). - depth: u32, - /// The document's preserved global blocks (embedded files and filter caches from PSD import). - globals: Vec, - /// uuids of the files in the preserved linked-layer blocks. - known: std::collections::HashSet, - /// uuids the layers reference. - used: std::collections::HashSet, - /// Unreferenced preserved files may be dropped (every smart layer's file id is known). - prune_ok: bool, - /// Files to embed. - add: Vec, - /// Sources converted so far, by contents identity, bytes and whether they were read from a - /// link (`Err` = can't be embedded). - converted: std::collections::HashMap<(SmartContentsId, [u8; 32], bool), Result>, - /// Each placed layer has its own id, even when it duplicates an imported layer. - placed_used: std::collections::HashSet, - /// Original instances reserve their imported placement regardless of layer order. - placed_owners: std::collections::HashMap, - /// Legacy records without a placed id stay unchanged for the original instance. - unplaced_owners: std::collections::HashMap, - /// The imported identity that keeps each original linked UUID. - linked_contents: std::collections::HashMap, - /// Independent copies of preserved linked items, including unavailable external sources. - linked_copies: std::collections::BTreeMap<(String, SmartContentsId), photocraft_doc::PsdGlobalBlock>, - /// Embedded documents decoded while converting them, by uuid (for the filter caches). - docs: std::collections::HashMap, - /// Source composites (document pixel format, source space) by uuid; `None` = unreadable. - composites: std::collections::HashMap, photocraft_geom::Rect)>>, - /// Preserved `FEid` items (by placed id). - old_fx: Vec, - /// Placed ids whose preserved `FEid` item stays. - keep_fx: std::collections::HashSet, - /// Regenerated `FEid` items. - new_fx: Vec, - /// The unfiltered pixels of each smart object whose filter mask shows: its layer record holds - /// the filtered pixels without the mask, as Photoshop's do (`compose::filter_mask`). - unfiltered: std::collections::HashMap, -} - -/// Whether a smart object's filter mask shows: enabled over at least one visible, enabled filter. -fn masked(sm: &photocraft_doc::SmartObject) -> bool { - sm.filter_mask.as_ref().is_some_and(|m| m.enabled) && sm.filters_enabled && sm.smart_filters.iter().any(|f| f.visible) -} - -/// `FEid` data padded to 4 bytes inside the block length: Photoshop counts the padding in the -/// length and can't open a file whose `FEid` is padded outside it. -fn padded_fx(fx: &photocraft_psd::filter_effects::FilterEffects) -> Vec { - let mut d = fx.to_bytes(); - d.resize(d.len().next_multiple_of(4), 0); - d -} - -const LINK_KEYS: [&[u8; 4]; 4] = [b"lnk2", b"lnk3", b"lnkD", b"lnkE"]; -const FX_KEYS: [&[u8; 4]; 2] = [b"FEid", b"FXid"]; - -impl SmartOut { - fn new(doc: &Document, depth: u32) -> Self { - let globals = doc.metadata.psd_global_blocks.clone(); - let known = globals.iter().filter(|(_, k, _)| LINK_KEYS.contains(&k)).flat_map(|(_, _, d)| crate::linked::block_uuids(d)).collect(); - let old_fx = globals - .iter() - .filter(|(_, k, _)| FX_KEYS.contains(&k)) - .filter_map(|(_, _, d)| photocraft_psd::filter_effects::FilterEffects::parse(d).ok()) - .flat_map(|fx| fx.items) - .collect(); - let mut linked_contents = std::collections::HashMap::new(); - let mut placed_owners = std::collections::HashMap::new(); - let mut unplaced_owners = std::collections::HashMap::new(); - let mut layers = doc.walk(); - // Duplicating a layer clears psd_id and gives it a newer runtime id. - layers.sort_by_key(|(_, _, layer)| (layer.psd_id.is_none(), layer.id)); - for (_, _, layer) in layers { - if let LayerContent::Smart(sm) = &layer.content - && let photocraft_doc::SmartSource::Linked { path } = &sm.source - && let Some(placed) = sm.psd_raw.as_ref().and_then(|d| crate::smart_map::parse_sold(d)) - && placed.idnt == *path - { - linked_contents.entry(path.clone()).or_insert(sm.contents_id); - if placed.placed.is_empty() { - unplaced_owners.entry(sm.contents_id).or_insert(layer.id); - } else { - placed_owners.entry(placed.placed).or_insert(layer.id); - } - } - } - SmartOut { depth, globals, known, prune_ok: true, old_fx, linked_contents, placed_owners, unplaced_owners, ..Default::default() } - } - - /// The document's global blocks with the linked-layer files and filter caches brought up to - /// date: unreferenced files dropped (when every reference is known), new files appended, - /// filter caches kept or regenerated per smart object. Unchanged blocks stay byte-identical. - fn finish(&self, blocks: Vec) -> Vec { - use std::sync::Arc; - let keep = |u: &str| !self.prune_ok || self.used.contains(u); - let mut out = Vec::with_capacity(blocks.len() + 2); - let mut added = false; - let mut fx_placed = false; - for (sig, key, data) in blocks { - if LINK_KEYS.contains(&&key) { - let add: &[crate::linked::LinkedFile] = if !added && &key == b"lnk2" { &self.add } else { &[] }; - added |= &key == b"lnk2"; - match crate::linked::rebuild_block(&data, &keep, add) { - None => out.push((sig, key, data)), - Some(d) if d.is_empty() => {} - Some(d) => out.push((sig, key, Arc::new(d))), - } - } else if FX_KEYS.contains(&&key) { - let Ok(mut fx) = photocraft_psd::filter_effects::FilterEffects::parse(&data) else { - out.push((sig, key, data)); - continue; - }; - let before = fx.items.len(); - fx.items.retain(|i| self.keep_fx.contains(&i.id)); - let fresh = !fx_placed && !self.new_fx.is_empty(); - if fresh { - fx.items.extend(self.new_fx.iter().cloned()); - fx_placed = true; - } - if fx.items.len() == before && !fresh { - out.push((sig, key, data)); - } else if !fx.items.is_empty() { - out.push((sig, key, Arc::new(padded_fx(&fx)))); - } - } else { - out.push((sig, key, data)); - } - } - if !added && !self.add.is_empty() { - let data: Vec = self.add.iter().flat_map(crate::linked::encode_linked_file).collect(); - out.push((*b"8BIM", *b"lnk2", Arc::new(data))); - } - for (sig, key, data) in self.linked_copies.values() { - if let Some((_, _, block)) = out.iter_mut().find(|(s, k, _)| s == sig && k == key) { - Arc::make_mut(block).extend_from_slice(data); - } else { - out.push((*sig, *key, data.clone())); - } - } - if !fx_placed && !self.new_fx.is_empty() { - let fx = photocraft_psd::filter_effects::FilterEffects { version: 3, items: self.new_fx.clone() }; - out.push((*b"8BIM", *b"FEid", Arc::new(padded_fx(&fx)))); - if !out.iter().any(|(_, k, _)| k == b"FMsk") { - // Filter mask overlay: RGB red at 50 %, Photoshop's default. - out.push((*b"8BIM", *b"FMsk", Arc::new(vec![0, 0, 255, 255, 0, 0, 0, 0, 0, 0, 0, 50]))); - } - } - out - } -} - -/// The source size of a smart object whose file we can't decode: its rendered bounds taken back -/// through the inverse transform (the source's top-left is the origin). -fn size_from_layer(sm: &photocraft_doc::SmartObject) -> (f64, f64) { - let r = sm.cache.as_ref().map(Surface::content_bounds).filter(|r| !r.is_empty()); - let (Some(r), Some(inv)) = (r, sm.transform.inverse()) else { return (1.0, 1.0) }; - let [a, b, c, d, e, f] = inv.m; - let (mut w, mut h) = (1.0f64, 1.0f64); - for (x, y) in [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)] { - let (x, y) = (f64::from(x), f64::from(y)); - w = w.max((a * x + c * y + e).round()); - h = h.max((b * x + d * y + f).round()); - } - (w, h) -} - -fn upsert(raw: &mut Vec<([u8; 4], Vec)>, key: &[u8; 4], data: Vec, before: Option<&[u8; 4]>) { - if let Some(e) = raw.iter_mut().find(|(k, _)| k == key) { - e.1 = data; - return; - } - match before.and_then(|b| raw.iter().position(|(k, _)| k == b)) { - Some(i) => raw.insert(i, (*key, data)), - None => raw.push((*key, data)), - } -} - fn h_of(r: photocraft_geom::Rect) -> usize { r.height() as usize } @@ -1195,836 +1016,5 @@ impl Ex { } } -/// Resource 1026 (Layer › Link Layers): one u16 group id per layer record, in the order -/// [`Ex::emit`] writes records (a group's bounding divider, its children, then the group). -/// Imported ids that fit in a u16 are kept, so unchanged files write the same bytes; otherwise -/// groups are renumbered by first appearance. `None` when no layer is linked. -fn link_group_resource(layers: &[Layer]) -> Option> { - fn walk(layers: &[Layer], out: &mut Vec>) { - for l in layers { - if let LayerContent::Group(g) = &l.content { - out.push(None); - walk(&g.children, out); - } - out.push(l.link_group); - } - } - let mut per = Vec::new(); - walk(layers, &mut per); - if per.iter().all(Option::is_none) { - return None; - } - let fits = per.iter().flatten().all(|&g| (1..=u64::from(u16::MAX)).contains(&g)); - let mut seen: Vec = Vec::new(); - let ids = per.iter().map(|g| match *g { - None => 0u16, - Some(g) if fits => g as u16, - Some(g) => { - let i = seen.iter().position(|&s| s == g).unwrap_or_else(|| { - seen.push(g); - seen.len() - 1 - }); - u16::try_from(i + 1).unwrap_or(u16::MAX) - } - }); - Some(ids.flat_map(u16::to_be_bytes).collect()) -} - -/// Whether the layer's effects still equal what its preserved `lmfx`/`lfx2` -/// decodes to. `None` when there is nothing preserved or it can't be decoded. -/// Block keys a smart object's `psd_raw` may be written under, in priority order. The data says -/// which it is: `PlLd` holds a `plcL` structure, `SoLd`/`SoLE` a `soLD` one (Adobe PSD spec, -/// "Placed Layer" and "Placed Layer Data"). Writing one under the other's key makes the block -/// unreadable. -fn smart_keys(data: Option<&[u8]>) -> &'static [&'static [u8; 4]] { - match data.and_then(|d| d.get(..4)) { - Some(b"plcL") => &[b"PlLd"], - Some(b"soLD") => &[b"SoLd", b"SoLE"], - _ => &[b"SoLd", b"PlLd", b"SoLE"], - } -} - -fn effects_unchanged(l: &Layer) -> Option { - let src = l.psd_blocks.iter().find(|(k, _)| k == b"lmfx").map(|(_, d)| d.clone()).or_else(|| l.effects.psd_raw.clone())?; - let (m, items) = crate::effects_map::parse_lfx2(&src)?; - Some(m == l.effects.enabled && items == l.effects.items) -} - -pub(crate) fn legacy_name(s: &str) -> Vec { - s.chars().map(|c| if c.is_ascii() && !c.is_ascii_control() { c as u8 } else { b'?' }).take(255).collect() -} - -pub(crate) fn unicode_names_resource(names: &[&str]) -> Vec { - let mut v = Vec::new(); - for n in names { - let units: Vec = n.encode_utf16().chain(std::iter::once(0)).collect(); - v.extend_from_slice(&(units.len() as u32).to_be_bytes()); - for u in units { - v.extend_from_slice(&u.to_be_bytes()); - } - } - v -} - -pub(crate) fn pascal_names_resource(names: &[&str]) -> Vec { - let mut v = Vec::new(); - for n in names { - let b = legacy_name(n); - let n = b.len().min(255); - v.push(n as u8); - v.extend_from_slice(&b[..n]); - } - // No per-string pad: Photoshop's resource 1006 for "Spot Color 1" is 13 bytes - // (length byte + 12 characters). The 8BIM container pads an odd resource separately. - v -} - -pub(crate) fn guides_resource(doc: &Document) -> Vec { - let mut v = Vec::new(); - v.extend_from_slice(&1u32.to_be_bytes()); - v.extend_from_slice(&576u32.to_be_bytes()); - v.extend_from_slice(&576u32.to_be_bytes()); - let n = doc.guides.horizontal.len() + doc.guides.vertical.len(); - v.extend_from_slice(&(n as u32).to_be_bytes()); - for (list, dir) in [(&doc.guides.vertical, 0u8), (&doc.guides.horizontal, 1u8)] { - for p in list { - v.extend_from_slice(&((p * 32.0).round() as i32).to_be_bytes()); - v.push(dir); - } - } - v -} - -/// Path resources: saved paths (2000+), the work path (1025) and the clipping path name (2999), -/// the last only when the imported one doesn't already name the document's clipping path. -pub(crate) fn path_resources(doc: &Document, warnings: &mut Vec) -> Vec { - use crate::vector_map::{CLIPPING_PATH, WORK_PATH, path_from_resource, path_to_records}; - let mut out = Vec::new(); - let (w, h) = (doc.size.width, doc.size.height); - let max = (*crate::vector_map::SAVED_PATHS.end() - *crate::vector_map::SAVED_PATHS.start() + 1) as usize; - if doc.paths.len() > max { - warnings.push(format!("only {max} saved paths fit in PSD; the rest were dropped")); - } - for (i, p) in doc.paths.iter().take(max).enumerate() { - let data = match &p.psd_raw { - Some(r) if path_from_resource(r, w, h).as_ref() == Some(&p.path) => r.to_vec(), - _ => path_to_records(&p.path, w, h).to_bytes(), - }; - let mut r = ImageResource::new(crate::vector_map::SAVED_PATHS.start() + i as u16, data); - r.name = legacy_name(&p.name); - out.push(r); - } - if let Some(wp) = &doc.work_path { - out.push(ImageResource::new(WORK_PATH, path_to_records(wp, w, h).to_bytes())); - } - let raw_clip = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == CLIPPING_PATH); - let raw_name = raw_clip.map(|(_, _, d)| { - let n = usize::from(d.first().copied().unwrap_or(0)); - d.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default() - }); - if let Some(c) = &doc.clipping_path - && raw_name.as_deref() != Some(c.name.as_str()) - { - // Pascal name, then flatness as 16.16 fixed (best effort; see vector_map docs). - let mut data = vec![0u8]; - let name = legacy_name(&c.name); - data[0] = name.len() as u8; - data.extend_from_slice(&name); - data.extend_from_slice(&((c.flatness.max(0.0) * 65536.0) as u32).to_be_bytes()); - out.push(ImageResource::new(CLIPPING_PATH, data)); - } - out -} - -/// Whether an imported (unmodelled) resource still describes the document and is written back. -pub(crate) fn keep_imported_resource(doc: &Document, id: u16, data: &[u8]) -> bool { - // Measurement scale / count resources: only while they still describe the document. - if !crate::annotations_map::keep_resource(doc, id) { - return false; - } - // Guides v2 and guide GUIDs: only while they still describe the document's guides. - if !crate::guides_map::keep_resource(doc, id, data) { - return false; - } - // A preserved clipping-path resource is only valid while it names the current one. - if id == crate::vector_map::CLIPPING_PATH { - let n = usize::from(data.first().copied().unwrap_or(0)); - let raw_name = data.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default(); - return doc.clipping_path.as_ref().is_some_and(|c| c.name == raw_name); - } - true -} - -/// A document-level (global) tagged block. Photoshop pads these to a multiple of 4, and readers -/// such as psd-tools step to the next block that way: an even pad after `CAI ` (77 bytes) -/// misaligned every block after it (#200). -pub(crate) fn global_block(signature: [u8; 4], key: [u8; 4], data: &[u8]) -> TaggedBlock { - let mut tb = TaggedBlock::new(key, data.to_vec()); - tb.signature = signature; - tb.padding = Some(vec![0; (4 - data.len() % 4) % 4]); - tb -} - -fn cmyk_of(fmt: &PixelFormat) -> bool { - fmt.mode == ColorMode::Cmyk -} - -/// The merged image's planes (colour channels, then alpha), big-endian, matted against white -/// when `matte`; with whether any pixel needs the alpha channel and whether any is below 1. -/// `ctl` gets the fraction of rows done after each band; once it is cancelled the rest of the -/// image is left blank (the caller discards it). -fn merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool, ctl: &Interrupt) -> (Vec, bool, bool) { - if cmyk && let Some(planes) = merged_ink_planes(doc, fmt.sample, matte, ctl) { - return planes; - } - let sample = fmt.sample; - let cc = fmt.mode.color_channels(); - let bps = sample.bytes(); - let n = doc.size.area() as usize; - let plane = n * bps; - let mut planes = vec![0u8; plane * (cc + 1)]; - let (mut has_alpha, mut translucent) = (false, false); - let white = photocraft_raster::from_rgba(fmt, [1.0, 1.0, 1.0, 1.0]); - let canvas = doc.bounds(); - let w = canvas.width() as usize; - let space = photocraft_compose::cmyk_space(doc); - let lab16 = fmt.mode == ColorMode::Lab && sample == SampleType::U16; - let rows = canvas.height().max(1) as f32; - let _ = photocraft_compose::render_bands(doc, canvas, 0, |band| -> Result<(), ()> { - if ctl.cancelled() { - return Err(()); - } - // Retain alpha whenever it differs from opaque at the stored precision. - has_alpha |= band.px.iter().any(|p| match sample { - SampleType::U8 => q255(p[3]) < 255, - SampleType::U16 => (p[3].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16 != u16::MAX, - SampleType::F32 => p[3] != 1.0, - }); - translucent |= band.px.iter().any(|p| p[3] < 1.0); - let start = (band.rect.y0 - canvas.y0) as usize * w; - // Converted and encoded on all cores, then copied into each plane. - let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| { - // The composite came through the document's CMYK profile: convert back through it too. - photocraft_color::convert::with_cmyk_space(space.as_ref(), || { - let mut out: Vec> = vec![Vec::with_capacity(range.len() * bps); cc + 1]; - let mut v = [0.0f32; 5]; - for p in &band.px[range.clone()] { - photocraft_raster::from_rgba_into(fmt, *p, &mut v); - for c in 0..=cc { - // Matte against white like Photoshop (see `pixels::matte`). - let m = if c < cc && matte { crate::pixels::matte(v[c], v[cc], white[c]) } else { v[c] }; - let x = if cmyk && c < cc { 1.0 - m } else { m }; - // 16-bit Lab a*/b* use Photoshop's 0..65280 scale (`pixels::lab16_chroma`). - let x = if lab16 && (c == 1 || c == 2) { x * (crate::pixels::LAB16_CHROMA_MAX / 65535.0) } else { x }; - encode_be(x, sample, &mut out[c]); - } - } - (range.start, out) - }) - }); - for (at, part) in parts { - for (c, src) in part.iter().enumerate() { - let o = c * plane + (start + at) * bps; - planes[o..o + src.len()].copy_from_slice(src); - } - } - ctl.progress((band.rect.y1 - canvas.y0) as f32 / rows); - Ok(()) - }); - (planes, has_alpha, translucent) -} - -/// [`merged_planes`] of a CMYK document whose layers are mixed on their ink values -/// (`photocraft_compose::cmyk`), so opaque pixels keep their exact inks; `None` for documents -/// that composite in RGB. Reports progress and stops on cancel like [`merged_planes`]. -fn merged_ink_planes(doc: &Document, sample: SampleType, matte: bool, ctl: &Interrupt) -> Option<(Vec, bool, bool)> { - let bps = sample.bytes(); - let n = doc.size.area() as usize; - let plane = n * bps; - let mut planes = vec![0u8; plane * 5]; - let (mut has_alpha, mut translucent) = (false, false); - let canvas = doc.bounds(); - let w = canvas.width() as usize; - let rows = canvas.height().max(1) as f32; - // A cancelled export leaves the rest blank (the caller discards it), so the result stands either way. - let _ = photocraft_compose::cmyk::render_cmyk_bands(doc, canvas, 0, |band| -> Result<(), ()> { - if ctl.cancelled() { - return Err(()); - } - // Retain alpha whenever it differs from opaque at the stored precision. - has_alpha |= band.px.iter().any(|p| match sample { - SampleType::U8 => q255(p[4]) < 255, - SampleType::U16 => (p[4].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16 != u16::MAX, - SampleType::F32 => p[4] != 1.0, - }); - translucent |= band.px.iter().any(|p| p[4] < 1.0); - let start = (band.rect.y0 - canvas.y0) as usize * w; - let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| { - let mut out: Vec> = (0..5).map(|_| Vec::with_capacity(range.len() * bps)).collect(); - for p in band.px.get(range.clone()).unwrap_or(&[]) { - for (c, o) in out.iter_mut().enumerate() { - // Inks matted against white paper (no ink) like Photoshop (see - // `pixels::matte`), and stored inverted as PSD's CMYK is. - let v = if c < 4 { 1.0 - if matte { crate::pixels::matte(p[c], p[4], 0.0) } else { p[c] } } else { p[4] }; - encode_be(v, sample, o); - } - } - (range.start, out) - }); - for (at, part) in parts { - for (c, src) in part.iter().enumerate() { - let o = c * plane + (start + at) * bps; - if let Some(dst) = planes.get_mut(o..o + src.len()) { - dst.copy_from_slice(src); - } - } - } - ctl.progress((band.rect.y1 - canvas.y0) as f32 / rows); - Ok(()) - })?; - Some((planes, has_alpha, translucent)) -} - -/// The merged image of a file saved without Maximize Compatibility: Photoshop's white placeholder -/// in the document's colour channels, with no alpha. Encoded like [`merged_planes`], so CMYK white -/// is no ink and Lab white is L 100 with neutral a*/b*. -fn placeholder_planes(doc: &Document, fmt: &PixelFormat) -> Vec { - let cc = fmt.mode.color_channels(); - let cmyk = cmyk_of(fmt); - let lab16 = fmt.mode == ColorMode::Lab && fmt.sample == SampleType::U16; - let space = photocraft_compose::cmyk_space(doc); - let white = photocraft_color::convert::with_cmyk_space(space.as_ref(), || photocraft_raster::from_rgba(fmt, [1.0, 1.0, 1.0, 1.0])); - let n = doc.size.area() as usize; - let mut planes = Vec::with_capacity(n * fmt.sample.bytes() * cc); - for c in 0..cc { - let v = white.get(c).copied().unwrap_or(1.0); - let x = if cmyk { 1.0 - v } else { v }; - let x = if lab16 && (c == 1 || c == 2) { x * (crate::pixels::LAB16_CHROMA_MAX / 65535.0) } else { x }; - let mut sample = Vec::with_capacity(4); - encode_be(x, fmt.sample, &mut sample); - planes.extend(sample.iter().copied().cycle().take(n * sample.len())); - } - planes -} - -/// Converts a document to a PSD file model (see [`document_to_psd_with`]). -pub fn document_to_psd(doc: &Document) -> PsdFile { - document_to_psd_with(doc, &PsdExportOptions::default()).0 -} - -/// Converts a document to a PSD/PSB file model, returning warnings about -/// anything that could not be represented. The merged composite is rendered -/// with `photocraft_compose::flatten`. -pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile, Vec) { - document_to_psd_nested(doc, opts, 0, &Interrupt::NONE) -} - -/// [`document_to_psd_with`] for a background save (#3389): reports progress through `ctl` after -/// each layer record and each band of the merged composite. Once `ctl` is cancelled it stops -/// early and returns an **incomplete** model: callers check `ctl` and discard it. -pub(crate) fn document_to_psd_interruptible(doc: &Document, opts: &PsdExportOptions, ctl: &Interrupt) -> (PsdFile, Vec) { - document_to_psd_nested(doc, opts, 0, ctl) -} - -/// How much of a PSD conversion the merged composite weighs, in layer records: rendering it -/// (all layers composited) and encoding its planes cost about two full-canvas layers. -const MERGED_WEIGHT: f32 = 2.0; -/// The part of the merged composite's share filled once its bands are rendered and converted; the -/// rest is compressing its planes. -const MERGED_RENDERED: f32 = 0.8; - -/// Adds headroom for compressed channel streams and their per-row length tables. -fn estimate_encoded_size(raw_bytes: u64, rows: u64, structural_bytes: u64) -> Option { - raw_bytes.checked_add(raw_bytes.checked_add(63)?.checked_div(64)?)?.checked_add(rows.checked_mul(8)?)?.checked_add(structural_bytes) -} - -fn add_plane_estimate(raw_bytes: &mut u64, rows: &mut u64, width: u64, height: u64, channels: u64, bytes_per_sample: u64) -> Option<()> { - let plane_bytes = width.checked_mul(height)?.checked_mul(channels)?.checked_mul(bytes_per_sample)?; - let plane_rows = height.checked_mul(channels)?; - *raw_bytes = raw_bytes.checked_add(plane_bytes)?; - *rows = rows.checked_add(plane_rows)?; - Some(()) -} - -fn exceeds_psd_size_limit(estimated_size: Option) -> bool { - estimated_size.is_none_or(|size| size > PSD_MAX_FILE_SIZE) -} - -fn surface_dimensions(surface: &Surface) -> Option<(u64, u64)> { - let bounds = surface.content_bounds(); - Some((u64::from(bounds.width()), u64::from(bounds.height()))) -} - -pub(crate) fn estimate_psd_size(doc: &Document) -> Option { - let mut raw_bytes = 0; - let mut rows = 0; - let mut structural_bytes = PSD_ESTIMATE_FIXED_OVERHEAD; - - let width = u64::from(doc.size.width); - let height = u64::from(doc.size.height); - - if doc.mode == ColorMode::Multichannel { - let channels = u64::try_from(doc.channels.len().clamp(1, 56)).ok()?; - let sample_bytes = u64::try_from(if doc.depth == SampleType::F32 { SampleType::U16.bytes() } else { doc.depth.bytes() }).ok()?; - add_plane_estimate(&mut raw_bytes, &mut rows, width, height, channels, sample_bytes)?; - } else { - let format = doc.pixel_format(); - let color_channels = u64::try_from(format.mode.color_channels()).ok()?; - let bytes_per_sample = u64::try_from(format.sample.bytes()).ok()?; - let layer_channels = color_channels.checked_add(1)?; - - for (_, _, layer) in doc.walk() { - structural_bytes = structural_bytes.checked_add(PSD_ESTIMATE_LAYER_OVERHEAD)?.checked_add(u64::try_from(layer.name.len()).ok()?)?; - for (_, data) in &layer.psd_blocks { - structural_bytes = structural_bytes.checked_add(u64::try_from(data.len()).ok()?)?; - } - - let surface = match &layer.content { - LayerContent::Fill(fill) => { - let mut fill_width = width; - let mut fill_height = height; - if let Some(cache) = &layer.fill_cache - && cache.fill == *fill - { - let (cache_width, cache_height) = surface_dimensions(&cache.surface)?; - fill_width = fill_width.max(cache_width); - fill_height = fill_height.max(cache_height); - } - add_plane_estimate(&mut raw_bytes, &mut rows, fill_width, fill_height, layer_channels, bytes_per_sample)?; - None - } - _ => layer.surface(), - }; - if let Some(surface) = surface { - let (surface_width, surface_height) = surface_dimensions(surface)?; - add_plane_estimate(&mut raw_bytes, &mut rows, surface_width, surface_height, layer_channels, bytes_per_sample)?; - } - if let Some(mask) = &layer.mask { - let (mask_width, mask_height) = surface_dimensions(&mask.surface)?; - add_plane_estimate(&mut raw_bytes, &mut rows, mask_width, mask_height, 1, bytes_per_sample)?; - } - if let LayerContent::Smart(smart) = &layer.content - && let photocraft_doc::SmartSource::Embedded { bytes, .. } = &smart.source - { - structural_bytes = structural_bytes.checked_add(u64::try_from(bytes.len()).ok()?)?; - } - } - - let max_extra_channels = 56usize.saturating_sub(format.mode.color_channels() + 1); - let mut extra_channels = doc.channels.len().min(max_extra_channels); - if doc.quick_mask.is_some() && extra_channels < max_extra_channels { - extra_channels += 1; - } - let merged_channels = color_channels.checked_add(1)?.checked_add(u64::try_from(extra_channels).ok()?)?; - add_plane_estimate(&mut raw_bytes, &mut rows, width, height, merged_channels, bytes_per_sample)?; - for channel in doc.channels.iter().take(extra_channels) { - structural_bytes = structural_bytes.checked_add(u64::try_from(channel.name.len()).ok()?)?; - } - } - - structural_bytes = structural_bytes - .checked_add(u64::try_from(doc.icc_profile.as_ref().map_or(0, |profile| profile.len())).ok()?)? - .checked_add(u64::try_from(doc.metadata.xmp.as_deref().map_or(0, str::len)).ok()?)? - .checked_add(u64::try_from(doc.metadata.exif.as_ref().map_or(0, |data| data.len())).ok()?)?; - for (_, name, data) in &doc.metadata.psd_resources { - structural_bytes = structural_bytes.checked_add(u64::try_from(name.len()).ok()?)?.checked_add(u64::try_from(data.len()).ok()?)?; - } - for (_, _, data) in &doc.metadata.psd_global_blocks { - structural_bytes = structural_bytes.checked_add(u64::try_from(data.len()).ok()?)?; - } - - estimate_encoded_size(raw_bytes, rows, structural_bytes) -} - -/// The signature a kept tagged block is written with. `8B64` exists only in PSB files: a PSD -/// with an `8B64` block (kept from a PSB source, e.g. its global `FMsk` or `cinf`) is refused by -/// Photoshop as "not compatible with this version" (measured in Photoshop 27.11). The other way -/// round, a PSB block with an 8-byte length is `8B64`, as Photoshop writes it: an `8BIM` `lnk2`, -/// `pths` or `cinf` (kept from a PSD source, whose lengths the PSB widens) makes Photoshop read -/// the length as 4 bytes and refuse the whole file (#7937). -pub(crate) fn block_signature(sig: [u8; 4], key: [u8; 4], version: Version) -> [u8; 4] { - match version { - Version::Psd if sig == *b"8B64" => *b"8BIM", - Version::Psb if sig == *b"8BIM" && photocraft_psd::tagged::uses_long_length(version, &key) => *b"8B64", - _ => sig, - } -} - -pub(crate) fn psd_version(doc: &Document, force_psb: bool, size_exceeds_limit: bool) -> Version { - let exceeds_dimensions = doc.size.width > 30_000 || doc.size.height > 30_000; - if force_psb || exceeds_dimensions || size_exceeds_limit { Version::Psb } else { Version::Psd } -} - -pub(crate) fn psd_size_exceeds_limit(doc: &Document) -> bool { - exceeds_psd_size_limit(estimate_psd_size(doc)) -} - -/// [`document_to_psd_with`] for a document embedded `depth` smart objects deep. -fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, ctl: &Interrupt) -> (PsdFile, Vec) { - if doc.mode == ColorMode::Multichannel { - return crate::multichannel_map::document_to_psd(doc, opts.force_psb); - } - if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb) { - return file; - } - let fmt = doc.pixel_format(); - // A Duotone is written over its grey plate with its inks: the block it was imported with, - // verbatim, while the inks are unedited, else one made from them (`duotone_map`). Photoshop - // has only 8-bit Duotone: it refuses to open a 16-bit one. - let duotone_inks: Option> = doc - .duotone - .as_ref() - .filter(|d| !d.inks.is_empty() && doc.mode == ColorMode::Duotone && fmt.mode == ColorMode::Grayscale && fmt.sample == SampleType::U8) - .map(|d| d.psd_raw.as_deref().map_or_else(|| crate::duotone_map::write(d), <[u8]>::to_vec)); - let sample = fmt.sample; - let cc = fmt.mode.color_channels(); - let big = doc.size.width > 30_000 || doc.size.height > 30_000; - let size_exceeds_limit = opts.size_limit_psb && !opts.force_psb && !big && psd_size_exceeds_limit(doc); - let version = psd_version(doc, opts.force_psb, size_exceeds_limit); - let mut ex = Ex { - fmt, - dpi: doc.resolution_dpi, - document: opts.document_path.clone(), - read_linked_files: opts.read_linked_files, - text_styles: doc.text_styles.clone(), - text_index: Default::default(), - mask_fmt: PixelFormat::new(ColorMode::Grayscale, sample, false), - cc, - cmyk: fmt.mode == ColorMode::Cmyk, - version, - next_id: 0, - used_ids: Default::default(), - layer_ids: Default::default(), - canvas: doc.bounds(), - records: Vec::new(), - warnings: Vec::new(), - guides: doc.guides.clone(), - comps: (!crate::comps_map::comps_unchanged(doc)).then(|| (doc.layer_comps.clone(), doc.last_document_state.clone())), - smart: SmartOut::new(doc, depth), - patterns: doc.patterns.clone(), - background: psd_background(doc), - }; - if big && !opts.force_psb { - ex.warnings.push("document exceeds 30000 px; written as PSB".into()); - } else if size_exceeds_limit && !opts.force_psb { - ex.warnings.push("estimated encoded size exceeds 2 GB; written as PSB".into()); - } - if fmt.mode != doc.mode && duotone_inks.is_none() { - ex.warnings.push(format!("{:?} document written as {:?}", doc.mode, fmt.mode)); - } - // Assign layer ids up front (stable across round trips): keep unique - // `psd_id`s, number the rest after them; dividers come after all. - { - let walk = doc.walk(); - let mut used = std::collections::HashSet::new(); - for (_, _, l) in &walk { - if let Some(id) = l.psd_id - && used.insert(id) - { - ex.layer_ids.insert(l.id, id); - } - } - let mut next = 1u32; - for (_, _, l) in &walk { - if let std::collections::hash_map::Entry::Vacant(e) = ex.layer_ids.entry(l.id) { - while used.contains(&next) { - next += 1; - } - used.insert(next); - e.insert(next); - } - } - ex.next_id = used.iter().copied().max().unwrap_or(0); - ex.used_ids = used; - // Text objects' number in the generated `Txt2` (#1348): a preserved `TySh` keeps the - // number it already names — its `Txt2` object must sit at that slot for `apply_txt2` — - // and new layers get numbers past every kept one and every object in the file's `Txt2`. - // Kept numbers are claimed first: a layer added below others must not take a number a - // layer above it keeps, or each of those would be renumbered onto its neighbour's object - // and take its style (#7773); nor may it land on a deleted layer's object. - let mut used_txt = std::collections::HashSet::new(); - ex.text_index = Default::default(); - let mut fresh = Vec::new(); - for (_, _, l) in &walk { - let LayerContent::Text(t) = &l.content else { - continue; - }; - match t.psd_raw.as_deref().and_then(|d| photocraft_text::psd::text_index(d)) { - Some(i) if used_txt.insert(i) => { - ex.text_index.insert(l.id, i); - } - _ => fresh.push(l.id), - } - } - let objects = - doc.metadata.psd_global_blocks.iter().find(|(_, key, _)| key == b"Txt2").map_or(0, |(_, _, d)| photocraft_text::psd::txt2_object_count(d)); - let mut next_txt = used_txt.iter().max().map_or(0, |m| m + 1).max(i32::try_from(objects).unwrap_or(i32::MAX)); - if next_txt.saturating_add(fresh.len() as i32) > photocraft_text::psd::MAX_TEXT_INDEX + 1 { - next_txt = 0; - } - for id in fresh { - while used_txt.contains(&next_txt) { - next_txt += 1; - } - used_txt.insert(next_txt); - ex.text_index.insert(id, next_txt); - } - } - // Progress: one unit per layer record, then the merged composite (#3389). - let records = doc.walk().len() as f32; - let units = records + MERGED_WEIGHT; - let layers_share = records / units; - let mut done = 0.0f32; - let mut tick = || { - done += 1.0; - ctl.progress(done / units); - !ctl.cancelled() - }; - let space = photocraft_compose::cmyk_space(doc); - photocraft_color::convert::with_cmyk_space(space.as_ref(), || ex.emit(&doc.layers, &mut tick)); - - // Without Maximize Compatibility the merged image is a white placeholder and the composite - // isn't rendered at all. A document without layer records keeps the real image: its pixels - // live nowhere else. So does a Duotone: it opens flattened from that image (its layer records - // are not read back). - let real_merged = opts.maximize_compatibility || ex.records.is_empty() || duotone_inks.is_some(); - let (mut planes, has_alpha) = if real_merged { - // Merged composite, rendered and encoded in bands (no full-size float composite). Matting - // against white only changes pixels with alpha < 1; if some are slightly translucent but - // all round to opaque (so no alpha channel is written), encode once more without the matte. - let merged_end = layers_share + (1.0 - layers_share) * MERGED_RENDERED; - let (mut planes, has_alpha, translucent) = - crate::with_span(ctl, layers_share, merged_end, |ctl| merged_planes(doc, &fmt, cmyk_of(&fmt), opts.merged_matte, ctl)); - if !has_alpha && translucent && opts.merged_matte { - planes = merged_planes(doc, &fmt, cmyk_of(&fmt), false, &Interrupt::cancel_only(&|| ctl.cancelled())).0; - } - (planes, has_alpha) - } else { - (placeholder_planes(doc, &fmt), false) - }; - let n = doc.size.area() as usize; - if !has_alpha { - planes.truncate(cc * n * sample.bytes()); - } - let canvas = doc.bounds(); - let max_extra = 56 - cc - usize::from(has_alpha); - if doc.channels.len() > max_extra { - ex.warnings.push(format!("only {max_extra} alpha channels fit in PSD; the rest were dropped")); - } - let mut extra: Vec<_> = doc.channels.iter().take(max_extra).collect(); - // Saved in Quick Mask mode: the mask is written as the last extra channel and flagged by - // resource 1022 (quick mask info: channel id, initially-empty flag), as Photoshop does. - let quick_mask_id = match &doc.quick_mask { - Some(q) if extra.len() < max_extra => { - extra.push(q); - Some((cc + usize::from(has_alpha) + extra.len() - 1) as u16) - } - Some(_) => { - ex.warnings.push("Quick Mask was dropped because the PSD channel limit was reached".into()); - None - } - None => None, - }; - for a in &extra { - let s = if a.surface.format() != ex.mask_fmt { a.surface.convert(ex.mask_fmt) } else { a.surface.clone() }; - let mut bytes = s.to_interleaved(canvas); - // Spot ink as Photoshop stores it (0 = solid); an alpha channel stays straight. - if a.spot.is_some() { - crate::channel_map::photoshop_spot_plane(&mut bytes, sample); - } - planes.extend(deinterleave(&bytes, 1, sample, &[false]).remove(0)); - } - let channels = (cc + usize::from(has_alpha) + extra.len()) as u16; - let mode = if duotone_inks.is_some() { PsdMode::Duotone } else { psd_mode(fmt.mode) }; - let header = Header::new(version, doc.size.width, doc.size.height, channels, psd_depth(sample), mode); - let mcomp = if sample == SampleType::F32 { Compression::Raw } else { opts.merged_compression }; - let image_data = ImageData::encode(mcomp, &planes, &header) - .or_else(|_| ImageData::encode(Compression::Raw, &planes, &header)) - .unwrap_or(ImageData { compression: Compression::Raw, data: planes }); - ctl.progress(1.0); - - // Resources. - let mut resources = vec![ - // hRes/vRes are always pixels per inch. The display unit written here is inches. - ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()), - ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()), - ImageResource::new(ids::GLOBAL_ALTITUDE, (doc.global_light.altitude.round() as i32).to_be_bytes().to_vec()), - ]; - if let Some(icc) = &doc.icc_profile { - resources.push(ImageResource::new(ids::ICC_PROFILE, icc.to_vec())); - } - if !doc.guides.horizontal.is_empty() || !doc.guides.vertical.is_empty() { - resources.push(ImageResource::new(1032, guides_resource(doc))); - } - if !extra.is_empty() { - // One entry per extra channel, the merged transparency included (as in every file - // Photoshop opens; one short, Photoshop refuses the file with "unexpected end-of-file"). - let names: Vec<&str> = has_alpha.then_some("Transparency").into_iter().chain(extra.iter().map(|a| a.name.as_str())).collect(); - resources.push(ImageResource::new(1006, pascal_names_resource(&names))); - resources.push(ImageResource::new(1045, unicode_names_resource(&names))); - resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(&extra, has_alpha))); - // Photoshop writes 1053 in every file with an extra channel. Its absence is how a file from - // an earlier PhotoCraft is told apart (`psd_import::earlier_photocraft_spot_planes`). - resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, crate::channel_map::alpha_identifiers(has_alpha, extra.len()))); - } - if let Some(id) = quick_mask_id { - let mut data = id.to_be_bytes().to_vec(); - data.push(0); - resources.push(ImageResource::new(crate::channel_map::QUICK_MASK_INFO, data)); - } - resources.extend(path_resources(doc, &mut ex.warnings)); - if let Some(groups) = link_group_resource(&doc.layers) { - resources.push(ImageResource::new(ids::LAYER_GROUP_INFO, groups)); - } - // The pixels are saved as they are shown: never let a reader rotate them again. The XMP and - // EXIF resolution follow the ResolutionInfo resource, so no copy contradicts it (#1691). - let ppi = Some((doc.resolution_dpi, doc.resolution_dpi)).filter(|d| d.0 > 0.0); - if let Some(x) = &doc.metadata.xmp { - resources.push(ImageResource::new(ids::XMP, photocraft_codecs::export_xmp(x, ppi).as_bytes().to_vec())); - } - if let Some(e) = &doc.metadata.exif { - resources.push(ImageResource::new(ids::EXIF, photocraft_codecs::export_exif(e, ppi).into_owned())); - } - let mut global_blocks = Vec::new(); - let preserved = ex.smart.finish(crate::annotations_map::export_blocks(doc, crate::pattern_map::export_global_blocks(doc))); - // The type layers' `Txt2` is regenerated (the auto-kern modes live there, and a preserved - // block goes stale as text is edited): one object per `TextIndex`, at the slot each layer's - // `TySh` names (unused slots stay empty; see `photocraft_text::psd::build_txt2`). The block - // it replaces is handed over so a kept object keeps everything the file held beyond its text - // and style runs (Photoshop's `/21 /1` glyph pen positions, …). - let text_layers: Vec<(i32, &photocraft_doc::TextLayer)> = doc - .walk() - .into_iter() - .filter_map(|(_, _, l)| match &l.content { - LayerContent::Text(t) => Some((ex.text_index.get(&l.id).copied().unwrap_or(0), t)), - _ => None, - }) - .collect(); - let previous = (!text_layers.is_empty()).then(|| preserved.iter().find(|(_, key, _)| key == b"Txt2").map(|(_, _, data)| data.to_vec())).flatten(); - // A fresh document of ordinary (Metrics) text has nothing to put in `Txt2`, and Photoshop never - // writes its empty `<< /0 << >> >>` stub — readers such as Photopea reject it (#3514). Keep the - // block when the file had one (round-trip its pen positions/extras) or a layer is Optical (the - // one mode EngineData can't carry; #1348). - let txt2 = (previous.is_some() || photocraft_text::psd::needs_txt2(&text_layers)) - .then(|| photocraft_text::psd::build_txt2_at(&text_layers, previous.as_deref(), ex.dpi)); - for (sig, key, data) in preserved { - if txt2.is_some() && key == *b"Txt2" { - continue; - } - // A kept layer block (one the import could not read, #2700) describes layers the - // document doesn't have. The document's own layers are written below, and a file holds - // one layer list: a second `Lr16`/`Lr32` would contradict it. - if !ex.records.is_empty() && matches!(&key, b"Lr16" | b"Lr32" | b"Layr") { - continue; - } - let block = global_block(block_signature(sig, key, version), key, &data); - // A kept merged-transparency marker describes the opened file's composite. Over an opaque - // one it would make the first alpha channel read back as the transparency, and vanish. - if !has_alpha && block.is_merged_transparency_marker() { - continue; - } - global_blocks.push(block); - } - if let Some(txt2) = txt2 { - let mut tb = TaggedBlock::new(*b"Txt2", txt2.clone()); - tb.signature = *b"8BIM"; - tb.padding = Some(vec![0; (4 - txt2.len() % 4) % 4]); - global_blocks.push(tb); - } - let comps_resource = ex.comps.is_some().then(|| crate::comps_map::write_comps_resource(doc)); - let (slices_resource, slices_warning) = crate::slices_map::export_resource(doc, &ex.layer_ids); - if let Some(warning) = slices_warning { - ex.warnings.push(warning); - } - for (id, name, data) in &doc.metadata.psd_resources { - // Layer comps: the preserved list while unchanged, else regenerated (or dropped) below. - if *id == crate::comps_map::LAYER_COMPS && comps_resource.is_some() { - continue; - } - // Slices: the preserved resource while unchanged, else regenerated (or dropped) below. - if *id == crate::slices_map::SLICES && slices_resource.is_some() { - continue; - } - if !keep_imported_resource(doc, *id, data) { - continue; - } - // 1053 is written afresh with the extra channels. A kept copy (from a Multichannel file, or - // a document saved by an earlier version) would be a second one, or list channels that - // are gone. - if *id == crate::channel_map::ALPHA_IDENTIFIERS { - continue; - } - let mut r = ImageResource::new(*id, data.to_vec()); - r.name = legacy_name(name); - resources.push(r); - } - if let Some(data) = crate::annotations_map::fresh_scale_resource(doc) { - resources.push(ImageResource::new(crate::annotations_map::MEASUREMENT_SCALE, data)); - } - if let Some(Some(data)) = comps_resource { - resources.push(ImageResource::new(crate::comps_map::LAYER_COMPS, data)); - } - if let Some(Some(data)) = slices_resource { - resources.push(ImageResource::new(crate::slices_map::SLICES, data)); - } - resources.push(version_info_resource(real_merged)); - - let has_layers = !ex.records.is_empty(); - // Photoshop writes a merged-transparency marker (`Mtrn`, `Mt16`, `Mt32`; `MTrn` in a TIFF) - // before the layer block, and won't open a file whose `Lr32` comes first (#5068): the layer - // block goes right after the last kept marker, else first. - let index = global_blocks.iter().rposition(TaggedBlock::is_merged_transparency_marker).map_or(0, |i| i + 1); - let placement = match (has_layers, sample) { - (true, SampleType::U16) => LayerInfoPlacement::GlobalBlock { index, signature: *b"8BIM", key: *b"Lr16", padding: None }, - (true, SampleType::F32) => LayerInfoPlacement::GlobalBlock { index, signature: *b"8BIM", key: *b"Lr32", padding: None }, - _ => LayerInfoPlacement::Section, - }; - let records = std::mem::take(&mut ex.records); - let mut layer_info = has_layers.then_some(LayerInfo { merged_alpha: has_alpha, layers: records, padding: None }); - if let Some(info) = &mut layer_info { - // Photoshop pads the layer info to 4 bytes (an even pad misaligns readers after a global - // `Lr16`/`Lr32` block, #200). A length that cannot be computed keeps the even default. - // A global block's length is the exact data length and its padding to 4 follows the block: - // readers that check that length exactly (Unity's PSD Importer) reject it otherwise (#4654). - if matches!(placement, LayerInfoPlacement::GlobalBlock { .. }) { - info.padding = Some(Vec::new()); - } else if info.pad_to(version, 4).is_err() { - info.padding = None; - } - } - // 32-bit files carry Photoshop's HDR toning records as Color Mode Data; Photoshop will not - // open a 32-bit file without them (#291). - let color_mode_data = match duotone_inks { - Some(raw) => raw, - None => photocraft_psd::hdr::color_mode_data_for_depth(header.depth), - }; - let file = PsdFile { - header, - color_mode_data, - resources, - layer_info, - layer_info_placement: placement, - global_layer_mask: (has_layers || !global_blocks.is_empty()).then(GlobalLayerMask::default), - global_blocks, - layer_mask_trailing: Vec::new(), - image_data, - }; - (file, ex.warnings) -} - -/// PSD mask parameters for a user mask's and a vector mask's (density, feather); `None` when -/// every value is the default (density 1, feather 0). -fn mask_parameters(user: Option<(f32, f32)>, vector: Option<(f32, f32)>) -> Option { - let density = |v: Option<(f32, f32)>| v.and_then(|(d, _)| (d < 1.0).then(|| q255(d))); - let feather = |v: Option<(f32, f32)>| v.and_then(|(_, f)| (f.is_finite() && f > 0.0).then_some(f64::from(f))); - let p = - MaskParameters { flags: 0, user_density: density(user), user_feather: feather(user), vector_density: density(vector), vector_feather: feather(vector) }; - let flags = u8::from(p.user_density.is_some()) - | u8::from(p.user_feather.is_some()) << 1 - | u8::from(p.vector_density.is_some()) << 2 - | u8::from(p.vector_feather.is_some()) << 3; - (flags != 0).then_some(MaskParameters { flags, ..p }) -} - #[cfg(test)] mod tests; diff --git a/crates/io/src/psd_export/document.rs b/crates/io/src/psd_export/document.rs new file mode 100644 index 0000000000..0ad7188a58 --- /dev/null +++ b/crates/io/src/psd_export/document.rs @@ -0,0 +1,391 @@ +use super::estimate::{MERGED_RENDERED, MERGED_WEIGHT, block_signature, psd_size_exceeds_limit, psd_version}; +use super::merged::{cmyk_of, merged_planes, placeholder_planes}; +use super::resources::{global_block, guides_resource, keep_imported_resource, legacy_name, pascal_names_resource, path_resources, unicode_names_resource}; +use super::smart::{SmartOut, link_group_resource}; +use super::*; + +/// Converts a document to a PSD file model (see [`document_to_psd_with`]). +pub fn document_to_psd(doc: &Document) -> PsdFile { + document_to_psd_with(doc, &PsdExportOptions::default()).0 +} + +/// Converts a document to a PSD/PSB file model, returning warnings about +/// anything that could not be represented. The merged composite is rendered +/// with `photocraft_compose::flatten`. +pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile, Vec) { + document_to_psd_nested(doc, opts, 0, &Interrupt::NONE) +} + +/// [`document_to_psd_with`] for a background save (#3389): reports progress through `ctl` after +/// each layer record and each band of the merged composite. Once `ctl` is cancelled it stops +/// early and returns an **incomplete** model: callers check `ctl` and discard it. +pub(crate) fn document_to_psd_interruptible(doc: &Document, opts: &PsdExportOptions, ctl: &Interrupt) -> (PsdFile, Vec) { + document_to_psd_nested(doc, opts, 0, ctl) +} + +/// [`document_to_psd_with`] for a document embedded `depth` smart objects deep. +pub(super) fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, ctl: &Interrupt) -> (PsdFile, Vec) { + if doc.mode == ColorMode::Multichannel { + return crate::multichannel_map::document_to_psd(doc, opts.force_psb); + } + if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb) { + return file; + } + let fmt = doc.pixel_format(); + // A Duotone is written over its grey plate with its inks: the block it was imported with, + // verbatim, while the inks are unedited, else one made from them (`duotone_map`). Photoshop + // has only 8-bit Duotone: it refuses to open a 16-bit one. + let duotone_inks: Option> = doc + .duotone + .as_ref() + .filter(|d| !d.inks.is_empty() && doc.mode == ColorMode::Duotone && fmt.mode == ColorMode::Grayscale && fmt.sample == SampleType::U8) + .map(|d| d.psd_raw.as_deref().map_or_else(|| crate::duotone_map::write(d), <[u8]>::to_vec)); + let sample = fmt.sample; + let cc = fmt.mode.color_channels(); + let big = doc.size.width > 30_000 || doc.size.height > 30_000; + let size_exceeds_limit = opts.size_limit_psb && !opts.force_psb && !big && psd_size_exceeds_limit(doc); + let version = psd_version(doc, opts.force_psb, size_exceeds_limit); + let mut ex = Ex { + fmt, + dpi: doc.resolution_dpi, + document: opts.document_path.clone(), + read_linked_files: opts.read_linked_files, + text_styles: doc.text_styles.clone(), + text_index: Default::default(), + mask_fmt: PixelFormat::new(ColorMode::Grayscale, sample, false), + cc, + cmyk: fmt.mode == ColorMode::Cmyk, + version, + next_id: 0, + used_ids: Default::default(), + layer_ids: Default::default(), + canvas: doc.bounds(), + records: Vec::new(), + warnings: Vec::new(), + guides: doc.guides.clone(), + comps: (!crate::comps_map::comps_unchanged(doc)).then(|| (doc.layer_comps.clone(), doc.last_document_state.clone())), + smart: SmartOut::new(doc, depth), + patterns: doc.patterns.clone(), + background: psd_background(doc), + }; + if big && !opts.force_psb { + ex.warnings.push("document exceeds 30000 px; written as PSB".into()); + } else if size_exceeds_limit && !opts.force_psb { + ex.warnings.push("estimated encoded size exceeds 2 GB; written as PSB".into()); + } + if fmt.mode != doc.mode && duotone_inks.is_none() { + ex.warnings.push(format!("{:?} document written as {:?}", doc.mode, fmt.mode)); + } + // Assign layer ids up front (stable across round trips): keep unique + // `psd_id`s, number the rest after them; dividers come after all. + { + let walk = doc.walk(); + let mut used = std::collections::HashSet::new(); + for (_, _, l) in &walk { + if let Some(id) = l.psd_id + && used.insert(id) + { + ex.layer_ids.insert(l.id, id); + } + } + let mut next = 1u32; + for (_, _, l) in &walk { + if let std::collections::hash_map::Entry::Vacant(e) = ex.layer_ids.entry(l.id) { + while used.contains(&next) { + next += 1; + } + used.insert(next); + e.insert(next); + } + } + ex.next_id = used.iter().copied().max().unwrap_or(0); + ex.used_ids = used; + // Text objects' number in the generated `Txt2` (#1348): a preserved `TySh` keeps the + // number it already names — its `Txt2` object must sit at that slot for `apply_txt2` — + // and new layers get numbers past every kept one and every object in the file's `Txt2`. + // Kept numbers are claimed first: a layer added below others must not take a number a + // layer above it keeps, or each of those would be renumbered onto its neighbour's object + // and take its style (#7773); nor may it land on a deleted layer's object. + let mut used_txt = std::collections::HashSet::new(); + ex.text_index = Default::default(); + let mut fresh = Vec::new(); + for (_, _, l) in &walk { + let LayerContent::Text(t) = &l.content else { + continue; + }; + match t.psd_raw.as_deref().and_then(|d| photocraft_text::psd::text_index(d)) { + Some(i) if used_txt.insert(i) => { + ex.text_index.insert(l.id, i); + } + _ => fresh.push(l.id), + } + } + let objects = + doc.metadata.psd_global_blocks.iter().find(|(_, key, _)| key == b"Txt2").map_or(0, |(_, _, d)| photocraft_text::psd::txt2_object_count(d)); + let mut next_txt = used_txt.iter().max().map_or(0, |m| m + 1).max(i32::try_from(objects).unwrap_or(i32::MAX)); + if next_txt.saturating_add(fresh.len() as i32) > photocraft_text::psd::MAX_TEXT_INDEX + 1 { + next_txt = 0; + } + for id in fresh { + while used_txt.contains(&next_txt) { + next_txt += 1; + } + used_txt.insert(next_txt); + ex.text_index.insert(id, next_txt); + } + } + // Progress: one unit per layer record, then the merged composite (#3389). + let records = doc.walk().len() as f32; + let units = records + MERGED_WEIGHT; + let layers_share = records / units; + let mut done = 0.0f32; + let mut tick = || { + done += 1.0; + ctl.progress(done / units); + !ctl.cancelled() + }; + let space = photocraft_compose::cmyk_space(doc); + photocraft_color::convert::with_cmyk_space(space.as_ref(), || ex.emit(&doc.layers, &mut tick)); + + // Without Maximize Compatibility the merged image is a white placeholder and the composite + // isn't rendered at all. A document without layer records keeps the real image: its pixels + // live nowhere else. So does a Duotone: it opens flattened from that image (its layer records + // are not read back). + let real_merged = opts.maximize_compatibility || ex.records.is_empty() || duotone_inks.is_some(); + let (mut planes, has_alpha) = if real_merged { + // Merged composite, rendered and encoded in bands (no full-size float composite). Matting + // against white only changes pixels with alpha < 1; if some are slightly translucent but + // all round to opaque (so no alpha channel is written), encode once more without the matte. + let merged_end = layers_share + (1.0 - layers_share) * MERGED_RENDERED; + let (mut planes, has_alpha, translucent) = + crate::with_span(ctl, layers_share, merged_end, |ctl| merged_planes(doc, &fmt, cmyk_of(&fmt), opts.merged_matte, ctl)); + if !has_alpha && translucent && opts.merged_matte { + planes = merged_planes(doc, &fmt, cmyk_of(&fmt), false, &Interrupt::cancel_only(&|| ctl.cancelled())).0; + } + (planes, has_alpha) + } else { + (placeholder_planes(doc, &fmt), false) + }; + let n = doc.size.area() as usize; + if !has_alpha { + planes.truncate(cc * n * sample.bytes()); + } + let canvas = doc.bounds(); + let max_extra = 56 - cc - usize::from(has_alpha); + if doc.channels.len() > max_extra { + ex.warnings.push(format!("only {max_extra} alpha channels fit in PSD; the rest were dropped")); + } + let mut extra: Vec<_> = doc.channels.iter().take(max_extra).collect(); + // Saved in Quick Mask mode: the mask is written as the last extra channel and flagged by + // resource 1022 (quick mask info: channel id, initially-empty flag), as Photoshop does. + let quick_mask_id = match &doc.quick_mask { + Some(q) if extra.len() < max_extra => { + extra.push(q); + Some((cc + usize::from(has_alpha) + extra.len() - 1) as u16) + } + Some(_) => { + ex.warnings.push("Quick Mask was dropped because the PSD channel limit was reached".into()); + None + } + None => None, + }; + for a in &extra { + let s = if a.surface.format() != ex.mask_fmt { a.surface.convert(ex.mask_fmt) } else { a.surface.clone() }; + let mut bytes = s.to_interleaved(canvas); + // Spot ink as Photoshop stores it (0 = solid); an alpha channel stays straight. + if a.spot.is_some() { + crate::channel_map::photoshop_spot_plane(&mut bytes, sample); + } + planes.extend(deinterleave(&bytes, 1, sample, &[false]).remove(0)); + } + let channels = (cc + usize::from(has_alpha) + extra.len()) as u16; + let mode = if duotone_inks.is_some() { PsdMode::Duotone } else { psd_mode(fmt.mode) }; + let header = Header::new(version, doc.size.width, doc.size.height, channels, psd_depth(sample), mode); + let mcomp = if sample == SampleType::F32 { Compression::Raw } else { opts.merged_compression }; + let image_data = ImageData::encode(mcomp, &planes, &header) + .or_else(|_| ImageData::encode(Compression::Raw, &planes, &header)) + .unwrap_or(ImageData { compression: Compression::Raw, data: planes }); + ctl.progress(1.0); + + // Resources. + let mut resources = vec![ + // hRes/vRes are always pixels per inch. The display unit written here is inches. + ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()), + ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()), + ImageResource::new(ids::GLOBAL_ALTITUDE, (doc.global_light.altitude.round() as i32).to_be_bytes().to_vec()), + ]; + if let Some(icc) = &doc.icc_profile { + resources.push(ImageResource::new(ids::ICC_PROFILE, icc.to_vec())); + } + if !doc.guides.horizontal.is_empty() || !doc.guides.vertical.is_empty() { + resources.push(ImageResource::new(1032, guides_resource(doc))); + } + if !extra.is_empty() { + // One entry per extra channel, the merged transparency included (as in every file + // Photoshop opens; one short, Photoshop refuses the file with "unexpected end-of-file"). + let names: Vec<&str> = has_alpha.then_some("Transparency").into_iter().chain(extra.iter().map(|a| a.name.as_str())).collect(); + resources.push(ImageResource::new(1006, pascal_names_resource(&names))); + resources.push(ImageResource::new(1045, unicode_names_resource(&names))); + resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(&extra, has_alpha))); + // Photoshop writes 1053 in every file with an extra channel. Its absence is how a file from + // an earlier PhotoCraft is told apart (`psd_import::earlier_photocraft_spot_planes`). + resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, crate::channel_map::alpha_identifiers(has_alpha, extra.len()))); + } + if let Some(id) = quick_mask_id { + let mut data = id.to_be_bytes().to_vec(); + data.push(0); + resources.push(ImageResource::new(crate::channel_map::QUICK_MASK_INFO, data)); + } + resources.extend(path_resources(doc, &mut ex.warnings)); + if let Some(groups) = link_group_resource(&doc.layers) { + resources.push(ImageResource::new(ids::LAYER_GROUP_INFO, groups)); + } + // The pixels are saved as they are shown: never let a reader rotate them again. The XMP and + // EXIF resolution follow the ResolutionInfo resource, so no copy contradicts it (#1691). + let ppi = Some((doc.resolution_dpi, doc.resolution_dpi)).filter(|d| d.0 > 0.0); + if let Some(x) = &doc.metadata.xmp { + resources.push(ImageResource::new(ids::XMP, photocraft_codecs::export_xmp(x, ppi).as_bytes().to_vec())); + } + if let Some(e) = &doc.metadata.exif { + resources.push(ImageResource::new(ids::EXIF, photocraft_codecs::export_exif(e, ppi).into_owned())); + } + let mut global_blocks = Vec::new(); + let preserved = ex.smart.finish(crate::annotations_map::export_blocks(doc, crate::pattern_map::export_global_blocks(doc))); + // The type layers' `Txt2` is regenerated (the auto-kern modes live there, and a preserved + // block goes stale as text is edited): one object per `TextIndex`, at the slot each layer's + // `TySh` names (unused slots stay empty; see `photocraft_text::psd::build_txt2`). The block + // it replaces is handed over so a kept object keeps everything the file held beyond its text + // and style runs (Photoshop's `/21 /1` glyph pen positions, …). + let text_layers: Vec<(i32, &photocraft_doc::TextLayer)> = doc + .walk() + .into_iter() + .filter_map(|(_, _, l)| match &l.content { + LayerContent::Text(t) => Some((ex.text_index.get(&l.id).copied().unwrap_or(0), t)), + _ => None, + }) + .collect(); + let previous = (!text_layers.is_empty()).then(|| preserved.iter().find(|(_, key, _)| key == b"Txt2").map(|(_, _, data)| data.to_vec())).flatten(); + // A fresh document of ordinary (Metrics) text has nothing to put in `Txt2`, and Photoshop never + // writes its empty `<< /0 << >> >>` stub — readers such as Photopea reject it (#3514). Keep the + // block when the file had one (round-trip its pen positions/extras) or a layer is Optical (the + // one mode EngineData can't carry; #1348). + let txt2 = (previous.is_some() || photocraft_text::psd::needs_txt2(&text_layers)) + .then(|| photocraft_text::psd::build_txt2_at(&text_layers, previous.as_deref(), ex.dpi)); + for (sig, key, data) in preserved { + if txt2.is_some() && key == *b"Txt2" { + continue; + } + // A kept layer block (one the import could not read, #2700) describes layers the + // document doesn't have. The document's own layers are written below, and a file holds + // one layer list: a second `Lr16`/`Lr32` would contradict it. + if !ex.records.is_empty() && matches!(&key, b"Lr16" | b"Lr32" | b"Layr") { + continue; + } + let block = global_block(block_signature(sig, key, version), key, &data); + // A kept merged-transparency marker describes the opened file's composite. Over an opaque + // one it would make the first alpha channel read back as the transparency, and vanish. + if !has_alpha && block.is_merged_transparency_marker() { + continue; + } + global_blocks.push(block); + } + if let Some(txt2) = txt2 { + let mut tb = TaggedBlock::new(*b"Txt2", txt2.clone()); + tb.signature = *b"8BIM"; + tb.padding = Some(vec![0; (4 - txt2.len() % 4) % 4]); + global_blocks.push(tb); + } + let comps_resource = ex.comps.is_some().then(|| crate::comps_map::write_comps_resource(doc)); + let (slices_resource, slices_warning) = crate::slices_map::export_resource(doc, &ex.layer_ids); + if let Some(warning) = slices_warning { + ex.warnings.push(warning); + } + for (id, name, data) in &doc.metadata.psd_resources { + // Layer comps: the preserved list while unchanged, else regenerated (or dropped) below. + if *id == crate::comps_map::LAYER_COMPS && comps_resource.is_some() { + continue; + } + // Slices: the preserved resource while unchanged, else regenerated (or dropped) below. + if *id == crate::slices_map::SLICES && slices_resource.is_some() { + continue; + } + if !keep_imported_resource(doc, *id, data) { + continue; + } + // 1053 is written afresh with the extra channels. A kept copy (from a Multichannel file, or + // a document saved by an earlier version) would be a second one, or list channels that + // are gone. + if *id == crate::channel_map::ALPHA_IDENTIFIERS { + continue; + } + let mut r = ImageResource::new(*id, data.to_vec()); + r.name = legacy_name(name); + resources.push(r); + } + if let Some(data) = crate::annotations_map::fresh_scale_resource(doc) { + resources.push(ImageResource::new(crate::annotations_map::MEASUREMENT_SCALE, data)); + } + if let Some(Some(data)) = comps_resource { + resources.push(ImageResource::new(crate::comps_map::LAYER_COMPS, data)); + } + if let Some(Some(data)) = slices_resource { + resources.push(ImageResource::new(crate::slices_map::SLICES, data)); + } + resources.push(version_info_resource(real_merged)); + + let has_layers = !ex.records.is_empty(); + // Photoshop writes a merged-transparency marker (`Mtrn`, `Mt16`, `Mt32`; `MTrn` in a TIFF) + // before the layer block, and won't open a file whose `Lr32` comes first (#5068): the layer + // block goes right after the last kept marker, else first. + let index = global_blocks.iter().rposition(TaggedBlock::is_merged_transparency_marker).map_or(0, |i| i + 1); + let placement = match (has_layers, sample) { + (true, SampleType::U16) => LayerInfoPlacement::GlobalBlock { index, signature: *b"8BIM", key: *b"Lr16", padding: None }, + (true, SampleType::F32) => LayerInfoPlacement::GlobalBlock { index, signature: *b"8BIM", key: *b"Lr32", padding: None }, + _ => LayerInfoPlacement::Section, + }; + let records = std::mem::take(&mut ex.records); + let mut layer_info = has_layers.then_some(LayerInfo { merged_alpha: has_alpha, layers: records, padding: None }); + if let Some(info) = &mut layer_info { + // Photoshop pads the layer info to 4 bytes (an even pad misaligns readers after a global + // `Lr16`/`Lr32` block, #200). A length that cannot be computed keeps the even default. + // A global block's length is the exact data length and its padding to 4 follows the block: + // readers that check that length exactly (Unity's PSD Importer) reject it otherwise (#4654). + if matches!(placement, LayerInfoPlacement::GlobalBlock { .. }) { + info.padding = Some(Vec::new()); + } else if info.pad_to(version, 4).is_err() { + info.padding = None; + } + } + // 32-bit files carry Photoshop's HDR toning records as Color Mode Data; Photoshop will not + // open a 32-bit file without them (#291). + let color_mode_data = match duotone_inks { + Some(raw) => raw, + None => photocraft_psd::hdr::color_mode_data_for_depth(header.depth), + }; + let file = PsdFile { + header, + color_mode_data, + resources, + layer_info, + layer_info_placement: placement, + global_layer_mask: (has_layers || !global_blocks.is_empty()).then(GlobalLayerMask::default), + global_blocks, + layer_mask_trailing: Vec::new(), + image_data, + }; + (file, ex.warnings) +} + +/// PSD mask parameters for a user mask's and a vector mask's (density, feather); `None` when +/// every value is the default (density 1, feather 0). +pub(super) fn mask_parameters(user: Option<(f32, f32)>, vector: Option<(f32, f32)>) -> Option { + let density = |v: Option<(f32, f32)>| v.and_then(|(d, _)| (d < 1.0).then(|| q255(d))); + let feather = |v: Option<(f32, f32)>| v.and_then(|(_, f)| (f.is_finite() && f > 0.0).then_some(f64::from(f))); + let p = + MaskParameters { flags: 0, user_density: density(user), user_feather: feather(user), vector_density: density(vector), vector_feather: feather(vector) }; + let flags = u8::from(p.user_density.is_some()) + | u8::from(p.user_feather.is_some()) << 1 + | u8::from(p.vector_density.is_some()) << 2 + | u8::from(p.vector_feather.is_some()) << 3; + (flags != 0).then_some(MaskParameters { flags, ..p }) +} diff --git a/crates/io/src/psd_export/estimate.rs b/crates/io/src/psd_export/estimate.rs new file mode 100644 index 0000000000..83c2388a1e --- /dev/null +++ b/crates/io/src/psd_export/estimate.rs @@ -0,0 +1,135 @@ +use super::*; + +/// How much of a PSD conversion the merged composite weighs, in layer records: rendering it +/// (all layers composited) and encoding its planes cost about two full-canvas layers. +pub(super) const MERGED_WEIGHT: f32 = 2.0; + +/// The part of the merged composite's share filled once its bands are rendered and converted; the +/// rest is compressing its planes. +pub(super) const MERGED_RENDERED: f32 = 0.8; + +/// Adds headroom for compressed channel streams and their per-row length tables. +pub(super) fn estimate_encoded_size(raw_bytes: u64, rows: u64, structural_bytes: u64) -> Option { + raw_bytes.checked_add(raw_bytes.checked_add(63)?.checked_div(64)?)?.checked_add(rows.checked_mul(8)?)?.checked_add(structural_bytes) +} + +fn add_plane_estimate(raw_bytes: &mut u64, rows: &mut u64, width: u64, height: u64, channels: u64, bytes_per_sample: u64) -> Option<()> { + let plane_bytes = width.checked_mul(height)?.checked_mul(channels)?.checked_mul(bytes_per_sample)?; + let plane_rows = height.checked_mul(channels)?; + *raw_bytes = raw_bytes.checked_add(plane_bytes)?; + *rows = rows.checked_add(plane_rows)?; + Some(()) +} + +pub(super) fn exceeds_psd_size_limit(estimated_size: Option) -> bool { + estimated_size.is_none_or(|size| size > PSD_MAX_FILE_SIZE) +} + +fn surface_dimensions(surface: &Surface) -> Option<(u64, u64)> { + let bounds = surface.content_bounds(); + Some((u64::from(bounds.width()), u64::from(bounds.height()))) +} + +pub(crate) fn estimate_psd_size(doc: &Document) -> Option { + let mut raw_bytes = 0; + let mut rows = 0; + let mut structural_bytes = PSD_ESTIMATE_FIXED_OVERHEAD; + + let width = u64::from(doc.size.width); + let height = u64::from(doc.size.height); + + if doc.mode == ColorMode::Multichannel { + let channels = u64::try_from(doc.channels.len().clamp(1, 56)).ok()?; + let sample_bytes = u64::try_from(if doc.depth == SampleType::F32 { SampleType::U16.bytes() } else { doc.depth.bytes() }).ok()?; + add_plane_estimate(&mut raw_bytes, &mut rows, width, height, channels, sample_bytes)?; + } else { + let format = doc.pixel_format(); + let color_channels = u64::try_from(format.mode.color_channels()).ok()?; + let bytes_per_sample = u64::try_from(format.sample.bytes()).ok()?; + let layer_channels = color_channels.checked_add(1)?; + + for (_, _, layer) in doc.walk() { + structural_bytes = structural_bytes.checked_add(PSD_ESTIMATE_LAYER_OVERHEAD)?.checked_add(u64::try_from(layer.name.len()).ok()?)?; + for (_, data) in &layer.psd_blocks { + structural_bytes = structural_bytes.checked_add(u64::try_from(data.len()).ok()?)?; + } + + let surface = match &layer.content { + LayerContent::Fill(fill) => { + let mut fill_width = width; + let mut fill_height = height; + if let Some(cache) = &layer.fill_cache + && cache.fill == *fill + { + let (cache_width, cache_height) = surface_dimensions(&cache.surface)?; + fill_width = fill_width.max(cache_width); + fill_height = fill_height.max(cache_height); + } + add_plane_estimate(&mut raw_bytes, &mut rows, fill_width, fill_height, layer_channels, bytes_per_sample)?; + None + } + _ => layer.surface(), + }; + if let Some(surface) = surface { + let (surface_width, surface_height) = surface_dimensions(surface)?; + add_plane_estimate(&mut raw_bytes, &mut rows, surface_width, surface_height, layer_channels, bytes_per_sample)?; + } + if let Some(mask) = &layer.mask { + let (mask_width, mask_height) = surface_dimensions(&mask.surface)?; + add_plane_estimate(&mut raw_bytes, &mut rows, mask_width, mask_height, 1, bytes_per_sample)?; + } + if let LayerContent::Smart(smart) = &layer.content + && let photocraft_doc::SmartSource::Embedded { bytes, .. } = &smart.source + { + structural_bytes = structural_bytes.checked_add(u64::try_from(bytes.len()).ok()?)?; + } + } + + let max_extra_channels = 56usize.saturating_sub(format.mode.color_channels() + 1); + let mut extra_channels = doc.channels.len().min(max_extra_channels); + if doc.quick_mask.is_some() && extra_channels < max_extra_channels { + extra_channels += 1; + } + let merged_channels = color_channels.checked_add(1)?.checked_add(u64::try_from(extra_channels).ok()?)?; + add_plane_estimate(&mut raw_bytes, &mut rows, width, height, merged_channels, bytes_per_sample)?; + for channel in doc.channels.iter().take(extra_channels) { + structural_bytes = structural_bytes.checked_add(u64::try_from(channel.name.len()).ok()?)?; + } + } + + structural_bytes = structural_bytes + .checked_add(u64::try_from(doc.icc_profile.as_ref().map_or(0, |profile| profile.len())).ok()?)? + .checked_add(u64::try_from(doc.metadata.xmp.as_deref().map_or(0, str::len)).ok()?)? + .checked_add(u64::try_from(doc.metadata.exif.as_ref().map_or(0, |data| data.len())).ok()?)?; + for (_, name, data) in &doc.metadata.psd_resources { + structural_bytes = structural_bytes.checked_add(u64::try_from(name.len()).ok()?)?.checked_add(u64::try_from(data.len()).ok()?)?; + } + for (_, _, data) in &doc.metadata.psd_global_blocks { + structural_bytes = structural_bytes.checked_add(u64::try_from(data.len()).ok()?)?; + } + + estimate_encoded_size(raw_bytes, rows, structural_bytes) +} + +/// The signature a kept tagged block is written with. `8B64` exists only in PSB files: a PSD +/// with an `8B64` block (kept from a PSB source, e.g. its global `FMsk` or `cinf`) is refused by +/// Photoshop as "not compatible with this version" (measured in Photoshop 27.11). The other way +/// round, a PSB block with an 8-byte length is `8B64`, as Photoshop writes it: an `8BIM` `lnk2`, +/// `pths` or `cinf` (kept from a PSD source, whose lengths the PSB widens) makes Photoshop read +/// the length as 4 bytes and refuse the whole file (#7937). +pub(crate) fn block_signature(sig: [u8; 4], key: [u8; 4], version: Version) -> [u8; 4] { + match version { + Version::Psd if sig == *b"8B64" => *b"8BIM", + Version::Psb if sig == *b"8BIM" && photocraft_psd::tagged::uses_long_length(version, &key) => *b"8B64", + _ => sig, + } +} + +pub(crate) fn psd_version(doc: &Document, force_psb: bool, size_exceeds_limit: bool) -> Version { + let exceeds_dimensions = doc.size.width > 30_000 || doc.size.height > 30_000; + if force_psb || exceeds_dimensions || size_exceeds_limit { Version::Psb } else { Version::Psd } +} + +pub(crate) fn psd_size_exceeds_limit(doc: &Document) -> bool { + exceeds_psd_size_limit(estimate_psd_size(doc)) +} diff --git a/crates/io/src/psd_export/merged.rs b/crates/io/src/psd_export/merged.rs new file mode 100644 index 0000000000..da3afe0597 --- /dev/null +++ b/crates/io/src/psd_export/merged.rs @@ -0,0 +1,143 @@ +use super::*; + +pub(super) fn cmyk_of(fmt: &PixelFormat) -> bool { + fmt.mode == ColorMode::Cmyk +} + +/// The merged image's planes (colour channels, then alpha), big-endian, matted against white +/// when `matte`; with whether any pixel needs the alpha channel and whether any is below 1. +/// `ctl` gets the fraction of rows done after each band; once it is cancelled the rest of the +/// image is left blank (the caller discards it). +pub(super) fn merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool, ctl: &Interrupt) -> (Vec, bool, bool) { + if cmyk && let Some(planes) = merged_ink_planes(doc, fmt.sample, matte, ctl) { + return planes; + } + let sample = fmt.sample; + let cc = fmt.mode.color_channels(); + let bps = sample.bytes(); + let n = doc.size.area() as usize; + let plane = n * bps; + let mut planes = vec![0u8; plane * (cc + 1)]; + let (mut has_alpha, mut translucent) = (false, false); + let white = photocraft_raster::from_rgba(fmt, [1.0, 1.0, 1.0, 1.0]); + let canvas = doc.bounds(); + let w = canvas.width() as usize; + let space = photocraft_compose::cmyk_space(doc); + let lab16 = fmt.mode == ColorMode::Lab && sample == SampleType::U16; + let rows = canvas.height().max(1) as f32; + let _ = photocraft_compose::render_bands(doc, canvas, 0, |band| -> Result<(), ()> { + if ctl.cancelled() { + return Err(()); + } + // Retain alpha whenever it differs from opaque at the stored precision. + has_alpha |= band.px.iter().any(|p| match sample { + SampleType::U8 => q255(p[3]) < 255, + SampleType::U16 => (p[3].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16 != u16::MAX, + SampleType::F32 => p[3] != 1.0, + }); + translucent |= band.px.iter().any(|p| p[3] < 1.0); + let start = (band.rect.y0 - canvas.y0) as usize * w; + // Converted and encoded on all cores, then copied into each plane. + let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| { + // The composite came through the document's CMYK profile: convert back through it too. + photocraft_color::convert::with_cmyk_space(space.as_ref(), || { + let mut out: Vec> = vec![Vec::with_capacity(range.len() * bps); cc + 1]; + let mut v = [0.0f32; 5]; + for p in &band.px[range.clone()] { + photocraft_raster::from_rgba_into(fmt, *p, &mut v); + for c in 0..=cc { + // Matte against white like Photoshop (see `pixels::matte`). + let m = if c < cc && matte { crate::pixels::matte(v[c], v[cc], white[c]) } else { v[c] }; + let x = if cmyk && c < cc { 1.0 - m } else { m }; + // 16-bit Lab a*/b* use Photoshop's 0..65280 scale (`pixels::lab16_chroma`). + let x = if lab16 && (c == 1 || c == 2) { x * (crate::pixels::LAB16_CHROMA_MAX / 65535.0) } else { x }; + encode_be(x, sample, &mut out[c]); + } + } + (range.start, out) + }) + }); + for (at, part) in parts { + for (c, src) in part.iter().enumerate() { + let o = c * plane + (start + at) * bps; + planes[o..o + src.len()].copy_from_slice(src); + } + } + ctl.progress((band.rect.y1 - canvas.y0) as f32 / rows); + Ok(()) + }); + (planes, has_alpha, translucent) +} + +/// [`merged_planes`] of a CMYK document whose layers are mixed on their ink values +/// (`photocraft_compose::cmyk`), so opaque pixels keep their exact inks; `None` for documents +/// that composite in RGB. Reports progress and stops on cancel like [`merged_planes`]. +fn merged_ink_planes(doc: &Document, sample: SampleType, matte: bool, ctl: &Interrupt) -> Option<(Vec, bool, bool)> { + let bps = sample.bytes(); + let n = doc.size.area() as usize; + let plane = n * bps; + let mut planes = vec![0u8; plane * 5]; + let (mut has_alpha, mut translucent) = (false, false); + let canvas = doc.bounds(); + let w = canvas.width() as usize; + let rows = canvas.height().max(1) as f32; + // A cancelled export leaves the rest blank (the caller discards it), so the result stands either way. + let _ = photocraft_compose::cmyk::render_cmyk_bands(doc, canvas, 0, |band| -> Result<(), ()> { + if ctl.cancelled() { + return Err(()); + } + // Retain alpha whenever it differs from opaque at the stored precision. + has_alpha |= band.px.iter().any(|p| match sample { + SampleType::U8 => q255(p[4]) < 255, + SampleType::U16 => (p[4].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16 != u16::MAX, + SampleType::F32 => p[4] != 1.0, + }); + translucent |= band.px.iter().any(|p| p[4] < 1.0); + let start = (band.rect.y0 - canvas.y0) as usize * w; + let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| { + let mut out: Vec> = (0..5).map(|_| Vec::with_capacity(range.len() * bps)).collect(); + for p in band.px.get(range.clone()).unwrap_or(&[]) { + for (c, o) in out.iter_mut().enumerate() { + // Inks matted against white paper (no ink) like Photoshop (see + // `pixels::matte`), and stored inverted as PSD's CMYK is. + let v = if c < 4 { 1.0 - if matte { crate::pixels::matte(p[c], p[4], 0.0) } else { p[c] } } else { p[4] }; + encode_be(v, sample, o); + } + } + (range.start, out) + }); + for (at, part) in parts { + for (c, src) in part.iter().enumerate() { + let o = c * plane + (start + at) * bps; + if let Some(dst) = planes.get_mut(o..o + src.len()) { + dst.copy_from_slice(src); + } + } + } + ctl.progress((band.rect.y1 - canvas.y0) as f32 / rows); + Ok(()) + })?; + Some((planes, has_alpha, translucent)) +} + +/// The merged image of a file saved without Maximize Compatibility: Photoshop's white placeholder +/// in the document's colour channels, with no alpha. Encoded like [`merged_planes`], so CMYK white +/// is no ink and Lab white is L 100 with neutral a*/b*. +pub(super) fn placeholder_planes(doc: &Document, fmt: &PixelFormat) -> Vec { + let cc = fmt.mode.color_channels(); + let cmyk = cmyk_of(fmt); + let lab16 = fmt.mode == ColorMode::Lab && fmt.sample == SampleType::U16; + let space = photocraft_compose::cmyk_space(doc); + let white = photocraft_color::convert::with_cmyk_space(space.as_ref(), || photocraft_raster::from_rgba(fmt, [1.0, 1.0, 1.0, 1.0])); + let n = doc.size.area() as usize; + let mut planes = Vec::with_capacity(n * fmt.sample.bytes() * cc); + for c in 0..cc { + let v = white.get(c).copied().unwrap_or(1.0); + let x = if cmyk { 1.0 - v } else { v }; + let x = if lab16 && (c == 1 || c == 2) { x * (crate::pixels::LAB16_CHROMA_MAX / 65535.0) } else { x }; + let mut sample = Vec::with_capacity(4); + encode_be(x, fmt.sample, &mut sample); + planes.extend(sample.iter().copied().cycle().take(n * sample.len())); + } + planes +} diff --git a/crates/io/src/psd_export/resources.rs b/crates/io/src/psd_export/resources.rs new file mode 100644 index 0000000000..4ab5210e94 --- /dev/null +++ b/crates/io/src/psd_export/resources.rs @@ -0,0 +1,116 @@ +use super::*; + +pub(crate) fn legacy_name(s: &str) -> Vec { + s.chars().map(|c| if c.is_ascii() && !c.is_ascii_control() { c as u8 } else { b'?' }).take(255).collect() +} + +pub(crate) fn unicode_names_resource(names: &[&str]) -> Vec { + let mut v = Vec::new(); + for n in names { + let units: Vec = n.encode_utf16().chain(std::iter::once(0)).collect(); + v.extend_from_slice(&(units.len() as u32).to_be_bytes()); + for u in units { + v.extend_from_slice(&u.to_be_bytes()); + } + } + v +} + +pub(crate) fn pascal_names_resource(names: &[&str]) -> Vec { + let mut v = Vec::new(); + for n in names { + let b = legacy_name(n); + let n = b.len().min(255); + v.push(n as u8); + v.extend_from_slice(&b[..n]); + } + // No per-string pad: Photoshop's resource 1006 for "Spot Color 1" is 13 bytes + // (length byte + 12 characters). The 8BIM container pads an odd resource separately. + v +} + +pub(crate) fn guides_resource(doc: &Document) -> Vec { + let mut v = Vec::new(); + v.extend_from_slice(&1u32.to_be_bytes()); + v.extend_from_slice(&576u32.to_be_bytes()); + v.extend_from_slice(&576u32.to_be_bytes()); + let n = doc.guides.horizontal.len() + doc.guides.vertical.len(); + v.extend_from_slice(&(n as u32).to_be_bytes()); + for (list, dir) in [(&doc.guides.vertical, 0u8), (&doc.guides.horizontal, 1u8)] { + for p in list { + v.extend_from_slice(&((p * 32.0).round() as i32).to_be_bytes()); + v.push(dir); + } + } + v +} + +/// Path resources: saved paths (2000+), the work path (1025) and the clipping path name (2999), +/// the last only when the imported one doesn't already name the document's clipping path. +pub(crate) fn path_resources(doc: &Document, warnings: &mut Vec) -> Vec { + use crate::vector_map::{CLIPPING_PATH, WORK_PATH, path_from_resource, path_to_records}; + let mut out = Vec::new(); + let (w, h) = (doc.size.width, doc.size.height); + let max = (*crate::vector_map::SAVED_PATHS.end() - *crate::vector_map::SAVED_PATHS.start() + 1) as usize; + if doc.paths.len() > max { + warnings.push(format!("only {max} saved paths fit in PSD; the rest were dropped")); + } + for (i, p) in doc.paths.iter().take(max).enumerate() { + let data = match &p.psd_raw { + Some(r) if path_from_resource(r, w, h).as_ref() == Some(&p.path) => r.to_vec(), + _ => path_to_records(&p.path, w, h).to_bytes(), + }; + let mut r = ImageResource::new(crate::vector_map::SAVED_PATHS.start() + i as u16, data); + r.name = legacy_name(&p.name); + out.push(r); + } + if let Some(wp) = &doc.work_path { + out.push(ImageResource::new(WORK_PATH, path_to_records(wp, w, h).to_bytes())); + } + let raw_clip = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == CLIPPING_PATH); + let raw_name = raw_clip.map(|(_, _, d)| { + let n = usize::from(d.first().copied().unwrap_or(0)); + d.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default() + }); + if let Some(c) = &doc.clipping_path + && raw_name.as_deref() != Some(c.name.as_str()) + { + // Pascal name, then flatness as 16.16 fixed (best effort; see vector_map docs). + let mut data = vec![0u8]; + let name = legacy_name(&c.name); + data[0] = name.len() as u8; + data.extend_from_slice(&name); + data.extend_from_slice(&((c.flatness.max(0.0) * 65536.0) as u32).to_be_bytes()); + out.push(ImageResource::new(CLIPPING_PATH, data)); + } + out +} + +/// Whether an imported (unmodelled) resource still describes the document and is written back. +pub(crate) fn keep_imported_resource(doc: &Document, id: u16, data: &[u8]) -> bool { + // Measurement scale / count resources: only while they still describe the document. + if !crate::annotations_map::keep_resource(doc, id) { + return false; + } + // Guides v2 and guide GUIDs: only while they still describe the document's guides. + if !crate::guides_map::keep_resource(doc, id, data) { + return false; + } + // A preserved clipping-path resource is only valid while it names the current one. + if id == crate::vector_map::CLIPPING_PATH { + let n = usize::from(data.first().copied().unwrap_or(0)); + let raw_name = data.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default(); + return doc.clipping_path.as_ref().is_some_and(|c| c.name == raw_name); + } + true +} + +/// A document-level (global) tagged block. Photoshop pads these to a multiple of 4, and readers +/// such as psd-tools step to the next block that way: an even pad after `CAI ` (77 bytes) +/// misaligned every block after it (#200). +pub(crate) fn global_block(signature: [u8; 4], key: [u8; 4], data: &[u8]) -> TaggedBlock { + let mut tb = TaggedBlock::new(key, data.to_vec()); + tb.signature = signature; + tb.padding = Some(vec![0; (4 - data.len() % 4) % 4]); + tb +} diff --git a/crates/io/src/psd_export/smart.rs b/crates/io/src/psd_export/smart.rs new file mode 100644 index 0000000000..264a2ab8ab --- /dev/null +++ b/crates/io/src/psd_export/smart.rs @@ -0,0 +1,253 @@ +use super::*; + +/// An embedded smart-object source as written to `lnk2`. +#[derive(Clone, Debug)] +pub(super) struct Source { + pub(super) uuid: String, + /// Pixel size of the source document. + pub(super) size: (f64, f64), + pub(super) dpi: f64, +} + +pub(super) fn contents_uuid(contents_id: SmartContentsId, bytes: &[u8]) -> String { + let mut identity = blake3::Hasher::new(); + identity.update(&contents_id.0.to_le_bytes()); + identity.update(bytes); + crate::smart_map::uuid_from(identity.finalize().as_bytes()) +} + +/// Smart-object state collected while emitting layers, written into the global blocks at the end. +#[derive(Default)] +pub(super) struct SmartOut { + /// Nesting depth of this export (embedded documents are exported recursively). + pub(super) depth: u32, + /// The document's preserved global blocks (embedded files and filter caches from PSD import). + pub(super) globals: Vec, + /// uuids of the files in the preserved linked-layer blocks. + pub(super) known: std::collections::HashSet, + /// uuids the layers reference. + pub(super) used: std::collections::HashSet, + /// Unreferenced preserved files may be dropped (every smart layer's file id is known). + pub(super) prune_ok: bool, + /// Files to embed. + pub(super) add: Vec, + /// Sources converted so far, by contents identity, bytes and whether they were read from a + /// link (`Err` = can't be embedded). + pub(super) converted: std::collections::HashMap<(SmartContentsId, [u8; 32], bool), Result>, + /// Each placed layer has its own id, even when it duplicates an imported layer. + pub(super) placed_used: std::collections::HashSet, + /// Original instances reserve their imported placement regardless of layer order. + pub(super) placed_owners: std::collections::HashMap, + /// Legacy records without a placed id stay unchanged for the original instance. + pub(super) unplaced_owners: std::collections::HashMap, + /// The imported identity that keeps each original linked UUID. + pub(super) linked_contents: std::collections::HashMap, + /// Independent copies of preserved linked items, including unavailable external sources. + pub(super) linked_copies: std::collections::BTreeMap<(String, SmartContentsId), photocraft_doc::PsdGlobalBlock>, + /// Embedded documents decoded while converting them, by uuid (for the filter caches). + pub(super) docs: std::collections::HashMap, + /// Source composites (document pixel format, source space) by uuid; `None` = unreadable. + pub(super) composites: std::collections::HashMap, photocraft_geom::Rect)>>, + /// Preserved `FEid` items (by placed id). + pub(super) old_fx: Vec, + /// Placed ids whose preserved `FEid` item stays. + pub(super) keep_fx: std::collections::HashSet, + /// Regenerated `FEid` items. + pub(super) new_fx: Vec, + /// The unfiltered pixels of each smart object whose filter mask shows: its layer record holds + /// the filtered pixels without the mask, as Photoshop's do (`compose::filter_mask`). + pub(super) unfiltered: std::collections::HashMap, +} + +/// Whether a smart object's filter mask shows: enabled over at least one visible, enabled filter. +pub(super) fn masked(sm: &photocraft_doc::SmartObject) -> bool { + sm.filter_mask.as_ref().is_some_and(|m| m.enabled) && sm.filters_enabled && sm.smart_filters.iter().any(|f| f.visible) +} + +/// `FEid` data padded to 4 bytes inside the block length: Photoshop counts the padding in the +/// length and can't open a file whose `FEid` is padded outside it. +fn padded_fx(fx: &photocraft_psd::filter_effects::FilterEffects) -> Vec { + let mut d = fx.to_bytes(); + d.resize(d.len().next_multiple_of(4), 0); + d +} + +pub(super) const LINK_KEYS: [&[u8; 4]; 4] = [b"lnk2", b"lnk3", b"lnkD", b"lnkE"]; + +const FX_KEYS: [&[u8; 4]; 2] = [b"FEid", b"FXid"]; + +impl SmartOut { + pub(super) fn new(doc: &Document, depth: u32) -> Self { + let globals = doc.metadata.psd_global_blocks.clone(); + let known = globals.iter().filter(|(_, k, _)| LINK_KEYS.contains(&k)).flat_map(|(_, _, d)| crate::linked::block_uuids(d)).collect(); + let old_fx = globals + .iter() + .filter(|(_, k, _)| FX_KEYS.contains(&k)) + .filter_map(|(_, _, d)| photocraft_psd::filter_effects::FilterEffects::parse(d).ok()) + .flat_map(|fx| fx.items) + .collect(); + let mut linked_contents = std::collections::HashMap::new(); + let mut placed_owners = std::collections::HashMap::new(); + let mut unplaced_owners = std::collections::HashMap::new(); + let mut layers = doc.walk(); + // Duplicating a layer clears psd_id and gives it a newer runtime id. + layers.sort_by_key(|(_, _, layer)| (layer.psd_id.is_none(), layer.id)); + for (_, _, layer) in layers { + if let LayerContent::Smart(sm) = &layer.content + && let photocraft_doc::SmartSource::Linked { path } = &sm.source + && let Some(placed) = sm.psd_raw.as_ref().and_then(|d| crate::smart_map::parse_sold(d)) + && placed.idnt == *path + { + linked_contents.entry(path.clone()).or_insert(sm.contents_id); + if placed.placed.is_empty() { + unplaced_owners.entry(sm.contents_id).or_insert(layer.id); + } else { + placed_owners.entry(placed.placed).or_insert(layer.id); + } + } + } + SmartOut { depth, globals, known, prune_ok: true, old_fx, linked_contents, placed_owners, unplaced_owners, ..Default::default() } + } + + /// The document's global blocks with the linked-layer files and filter caches brought up to + /// date: unreferenced files dropped (when every reference is known), new files appended, + /// filter caches kept or regenerated per smart object. Unchanged blocks stay byte-identical. + pub(super) fn finish(&self, blocks: Vec) -> Vec { + use std::sync::Arc; + let keep = |u: &str| !self.prune_ok || self.used.contains(u); + let mut out = Vec::with_capacity(blocks.len() + 2); + let mut added = false; + let mut fx_placed = false; + for (sig, key, data) in blocks { + if LINK_KEYS.contains(&&key) { + let add: &[crate::linked::LinkedFile] = if !added && &key == b"lnk2" { &self.add } else { &[] }; + added |= &key == b"lnk2"; + match crate::linked::rebuild_block(&data, &keep, add) { + None => out.push((sig, key, data)), + Some(d) if d.is_empty() => {} + Some(d) => out.push((sig, key, Arc::new(d))), + } + } else if FX_KEYS.contains(&&key) { + let Ok(mut fx) = photocraft_psd::filter_effects::FilterEffects::parse(&data) else { + out.push((sig, key, data)); + continue; + }; + let before = fx.items.len(); + fx.items.retain(|i| self.keep_fx.contains(&i.id)); + let fresh = !fx_placed && !self.new_fx.is_empty(); + if fresh { + fx.items.extend(self.new_fx.iter().cloned()); + fx_placed = true; + } + if fx.items.len() == before && !fresh { + out.push((sig, key, data)); + } else if !fx.items.is_empty() { + out.push((sig, key, Arc::new(padded_fx(&fx)))); + } + } else { + out.push((sig, key, data)); + } + } + if !added && !self.add.is_empty() { + let data: Vec = self.add.iter().flat_map(crate::linked::encode_linked_file).collect(); + out.push((*b"8BIM", *b"lnk2", Arc::new(data))); + } + for (sig, key, data) in self.linked_copies.values() { + if let Some((_, _, block)) = out.iter_mut().find(|(s, k, _)| s == sig && k == key) { + Arc::make_mut(block).extend_from_slice(data); + } else { + out.push((*sig, *key, data.clone())); + } + } + if !fx_placed && !self.new_fx.is_empty() { + let fx = photocraft_psd::filter_effects::FilterEffects { version: 3, items: self.new_fx.clone() }; + out.push((*b"8BIM", *b"FEid", Arc::new(padded_fx(&fx)))); + if !out.iter().any(|(_, k, _)| k == b"FMsk") { + // Filter mask overlay: RGB red at 50 %, Photoshop's default. + out.push((*b"8BIM", *b"FMsk", Arc::new(vec![0, 0, 255, 255, 0, 0, 0, 0, 0, 0, 0, 50]))); + } + } + out + } +} + +/// The source size of a smart object whose file we can't decode: its rendered bounds taken back +/// through the inverse transform (the source's top-left is the origin). +pub(super) fn size_from_layer(sm: &photocraft_doc::SmartObject) -> (f64, f64) { + let r = sm.cache.as_ref().map(Surface::content_bounds).filter(|r| !r.is_empty()); + let (Some(r), Some(inv)) = (r, sm.transform.inverse()) else { return (1.0, 1.0) }; + let [a, b, c, d, e, f] = inv.m; + let (mut w, mut h) = (1.0f64, 1.0f64); + for (x, y) in [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)] { + let (x, y) = (f64::from(x), f64::from(y)); + w = w.max((a * x + c * y + e).round()); + h = h.max((b * x + d * y + f).round()); + } + (w, h) +} + +pub(super) fn upsert(raw: &mut Vec<([u8; 4], Vec)>, key: &[u8; 4], data: Vec, before: Option<&[u8; 4]>) { + if let Some(e) = raw.iter_mut().find(|(k, _)| k == key) { + e.1 = data; + return; + } + match before.and_then(|b| raw.iter().position(|(k, _)| k == b)) { + Some(i) => raw.insert(i, (*key, data)), + None => raw.push((*key, data)), + } +} + +/// Resource 1026 (Layer › Link Layers): one u16 group id per layer record, in the order +/// [`Ex::emit`] writes records (a group's bounding divider, its children, then the group). +/// Imported ids that fit in a u16 are kept, so unchanged files write the same bytes; otherwise +/// groups are renumbered by first appearance. `None` when no layer is linked. +pub(super) fn link_group_resource(layers: &[Layer]) -> Option> { + fn walk(layers: &[Layer], out: &mut Vec>) { + for l in layers { + if let LayerContent::Group(g) = &l.content { + out.push(None); + walk(&g.children, out); + } + out.push(l.link_group); + } + } + let mut per = Vec::new(); + walk(layers, &mut per); + if per.iter().all(Option::is_none) { + return None; + } + let fits = per.iter().flatten().all(|&g| (1..=u64::from(u16::MAX)).contains(&g)); + let mut seen: Vec = Vec::new(); + let ids = per.iter().map(|g| match *g { + None => 0u16, + Some(g) if fits => g as u16, + Some(g) => { + let i = seen.iter().position(|&s| s == g).unwrap_or_else(|| { + seen.push(g); + seen.len() - 1 + }); + u16::try_from(i + 1).unwrap_or(u16::MAX) + } + }); + Some(ids.flat_map(u16::to_be_bytes).collect()) +} + +/// Whether the layer's effects still equal what its preserved `lmfx`/`lfx2` +/// decodes to. `None` when there is nothing preserved or it can't be decoded. +/// Block keys a smart object's `psd_raw` may be written under, in priority order. The data says +/// which it is: `PlLd` holds a `plcL` structure, `SoLd`/`SoLE` a `soLD` one (Adobe PSD spec, +/// "Placed Layer" and "Placed Layer Data"). Writing one under the other's key makes the block +/// unreadable. +pub(super) fn smart_keys(data: Option<&[u8]>) -> &'static [&'static [u8; 4]] { + match data.and_then(|d| d.get(..4)) { + Some(b"plcL") => &[b"PlLd"], + Some(b"soLD") => &[b"SoLd", b"SoLE"], + _ => &[b"SoLd", b"PlLd", b"SoLE"], + } +} + +pub(super) fn effects_unchanged(l: &Layer) -> Option { + let src = l.psd_blocks.iter().find(|(k, _)| k == b"lmfx").map(|(_, d)| d.clone()).or_else(|| l.effects.psd_raw.clone())?; + let (m, items) = crate::effects_map::parse_lfx2(&src)?; + Some(m == l.effects.enabled && items == l.effects.items) +} diff --git a/crates/io/src/psd_export/tests.rs b/crates/io/src/psd_export/tests.rs index 5633e30764..9688dfeac2 100644 --- a/crates/io/src/psd_export/tests.rs +++ b/crates/io/src/psd_export/tests.rs @@ -245,8 +245,7 @@ fn photo_filter_psd_is_four_byte_aligned_and_round_trips() { let assert_phfl = |file: &PsdFile| { let records = &file.layer_info.as_ref().unwrap().layers; - let data = - records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *b"phfl").map(|b| b.data.as_slice()).expect("Photo Filter adjustment data"); + let data = records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *b"phfl").map(|b| b.data.as_slice()).expect("Photo Filter adjustment data"); assert_eq!(data.len(), 20, "PSD layer block length includes four-byte padding"); assert_eq!(&data[0..2], &[0, 2], "version 2 RGB Photo Filter"); assert_eq!(&data[17..], &[0, 0, 0], "three padding bytes after the 17-byte payload"); @@ -279,8 +278,7 @@ fn photo_filter_version_3_is_kept_until_edited() { let v3 = vec![0, 3, 0, 0, 0x5e, 0x7f, 0, 0, 0x61, 0xaa, 0, 0, 0x0e, 0xf3, 0, 0, 0, 0x3f, 1, 0]; let adjustment = crate::adjust_map::parse(b"phfl", &v3, None, crate::adjust_map::Channels::Rgb); let photocraft_doc::Adjustment::PhotoFilter { color, .. } = adjustment else { panic!("{adjustment:?}") }; - let mut doc = - Document::with_background("Photo Filter v3", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); + let mut doc = Document::with_background("Photo Filter v3", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); let mut layer = Layer::new("Photo Filter 1", LayerContent::Adjustment(adjustment.clone())); layer.psd_blocks = vec![(*b"phfl", std::sync::Arc::new(v3.clone()))]; doc.layers.push(layer); @@ -371,10 +369,8 @@ fn kept_psb_blocks_are_written_as_8bim_in_a_psd() { // Photoshop 27.11 refuses a PSD holding `8B64` blocks ("not compatible with this // version"); they came from re-saving a PSB as PSD with its global FMsk and cinf kept. let mut doc = document(4, 4); - doc.metadata.psd_global_blocks = vec![ - (*b"8B64", *b"FMsk", std::sync::Arc::new(vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50])), - (*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new())), - ]; + doc.metadata.psd_global_blocks = + vec![(*b"8B64", *b"FMsk", std::sync::Arc::new(vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50])), (*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new()))]; let signatures = |force_psb| { let opts = PsdExportOptions { force_psb, ..PsdExportOptions::default() }; let bytes = document_to_psd_with(&doc, &opts).0.to_bytes().unwrap(); From 9cfb3cc5b0ccb6bd760b97f4ee367125f521f74c Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:19:41 +0000 Subject: [PATCH 253/259] refactor(io): split smart_map.rs into smart_map/ --- crates/io/src/smart_map.rs | 1468 +---------------------------- crates/io/src/smart_map/export.rs | 387 ++++++++ crates/io/src/smart_map/import.rs | 826 ++++++++++++++++ crates/io/src/smart_map/placed.rs | 274 ++++++ crates/io/src/smart_map/tests.rs | 35 +- 5 files changed, 1512 insertions(+), 1478 deletions(-) create mode 100644 crates/io/src/smart_map/export.rs create mode 100644 crates/io/src/smart_map/import.rs create mode 100644 crates/io/src/smart_map/placed.rs diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs index 5d56c55ae8..2cf5342980 100644 --- a/crates/io/src/smart_map.rs +++ b/crates/io/src/smart_map.rs @@ -48,6 +48,21 @@ mod perspective_warp; pub use displace::{embed_map as displace_embed_map, embedded_map as displace_embedded_map, without_map as displace_without_map}; +mod export; +mod import; +mod placed; + +use export::{blend_options, is_meta, rgbc, set, unit}; +pub use export::{filter_fx, item_for_filter}; +pub use import::filter_from_item; +#[cfg(test)] +use import::{GALLERY_EFFECTS, LENSES, MEZZOTINT_TYPES, adjustment_list, known_params}; +use import::{code, from_hex, int, to_hex}; +use placed::enumv; +pub use placed::{PlacedSpec, plld_bytes, sold_bytes, stored_size}; +#[cfg(test)] +use placed::{quad_moved, warp_desc}; + /// Command id of a Photoshop smart filter PhotoCraft does not implement. Its params hold the /// filter's name, Photoshop filter id and descriptor (`psd`, hex); it renders as a pass-through. pub const UNSUPPORTED_FILTER: &str = "psd.unsupportedFilter"; @@ -135,1459 +150,6 @@ pub fn filter_stack(fx: &Descriptor) -> FilterStack { } } -// ---------- the filters we model ---------- - -/// Photoshop filter → PhotoCraft command, keyed by the `Fltr` class (and `filterID`). -struct Known { - class: &'static str, - filter_id: i32, - /// `Nm ` as Photoshop writes it (the menu item, with its ellipsis and mnemonic). - name: &'static str, - command: &'static str, -} - -/// A four-character PSD code as the big-endian integer Photoshop stores it as. -const fn code(c: &[u8; 4]) -> i32 { - i32::from_be_bytes(*c) -} - -const KNOWN: [Known; 53] = [ - Known { class: "GsnB", filter_id: code(b"GsnB"), name: "Gaussian Blur...", command: "filter.blur.gaussianBlur" }, - Known { class: "boxblur", filter_id: 840, name: "Box Blur...", command: "filter.blur.boxBlur" }, - Known { class: "MtnB", filter_id: code(b"MtnB"), name: "Motion Blur...", command: "filter.blur.motionBlur" }, - // Surface Blur, Smart Blur and Radial Blur: keys, value types and enums measured in Photoshop. - Known { class: "surfaceBlur", filter_id: 1135, name: "Surface Blur...", command: "filter.blur.surfaceBlur" }, - Known { class: "SmrB", filter_id: code(b"SmrB"), name: "Smart Blur...", command: "filter.blur.smartBlur" }, - // Radial Blur at its defaults stores no `Fltr` (`hasoptions` false); that entry is kept verbatim. - Known { class: "RdlB", filter_id: code(b"RdlB"), name: "Radial Blur...", command: "filter.blur.radialBlur" }, - Known { class: "UnsM", filter_id: code(b"UnsM"), name: "Unsharp Mask...", command: "filter.sharpen.unsharpMask" }, - Known { class: "AdNs", filter_id: code(b"AdNs"), name: "Add Noise...", command: "filter.noise.addNoise" }, - Known { class: "Mdn ", filter_id: code(b"Mdn "), name: "Median...", command: "filter.noise.median" }, - Known { class: "HghP", filter_id: code(b"HghP"), name: "High Pass...", command: "filter.other.highPass" }, - Known { class: "Mxm ", filter_id: code(b"Mxm "), name: "Maximum...", command: "filter.other.maximum" }, - Known { class: "Mnm ", filter_id: code(b"Mnm "), name: "Minimum...", command: "filter.other.minimum" }, - Known { class: "Ofst", filter_id: code(b"Ofst"), name: "Offset...", command: "filter.other.offset" }, - Known { class: "Cstm", filter_id: code(b"Cstm"), name: "Custom...", command: "filter.other.custom" }, - Known { class: "Msc ", filter_id: code(b"Msc "), name: "Mosaic...", command: "filter.pixelate.mosaic" }, - Known { class: "Mztn", filter_id: code(b"Mztn"), name: "Mezzotint...", command: "filter.pixelate.mezzotint" }, - Known { class: "ClrH", filter_id: code(b"ClrH"), name: "Color Halftone...", command: "filter.pixelate.colorHalftone" }, - Known { class: "Embs", filter_id: code(b"Embs"), name: "Emboss...", command: "filter.stylize.emboss" }, - Known { class: "Dfs ", filter_id: code(b"Dfs "), name: "Diffuse...", command: "filter.stylize.diffuse" }, - Known { class: "TrcC", filter_id: code(b"TrcC"), name: "Trace Contour...", command: "filter.stylize.traceContour" }, - Known { class: "Crst", filter_id: code(b"Crst"), name: "Crystallize...", command: "filter.pixelate.crystallize" }, - Known { class: "Pntl", filter_id: code(b"Pntl"), name: "Pointillize...", command: "filter.pixelate.pointillize" }, - Known { class: "Wnd ", filter_id: code(b"Wnd "), name: "Wind...", command: "filter.stylize.wind" }, - Known { class: "Extr", filter_id: code(b"Extr"), name: "Extrude...", command: "filter.stylize.extrude" }, - Known { class: "Tls ", filter_id: code(b"Tls "), name: "Tiles...", command: "filter.stylize.tiles" }, - Known { class: "Lvls", filter_id: code(b"Lvls"), name: "Levels...", command: "image.adjustments.levels" }, - Known { class: "Crvs", filter_id: code(b"Crvs"), name: "Curves...", command: "image.adjustments.curves" }, - // Shadows/Highlights at its defaults stores no `Fltr` (`hasoptions` false). - Known { class: "adaptCorrect", filter_id: 781, name: "Shado&ws/Highlights...", command: "image.adjustments.shadowsHighlights" }, - // Filters without options (measured in Photoshop): `hasoptions` false, no `Fltr`, only the - // four-char `filterID`. The class is that code; see `NO_OPTIONS`. - Known { class: "Blr ", filter_id: code(b"Blr "), name: "Blur", command: "filter.blur.blur" }, - Known { class: "BlrM", filter_id: code(b"BlrM"), name: "Blur More", command: "filter.blur.blurMore" }, - Known { class: "Avrg", filter_id: code(b"Avrg"), name: "Average", command: "filter.blur.average" }, - Known { class: "Dspc", filter_id: code(b"Dspc"), name: "Despeckle", command: "filter.noise.despeckle" }, - Known { class: "FndE", filter_id: code(b"FndE"), name: "Find Edges", command: "filter.stylize.findEdges" }, - Known { class: "Fct ", filter_id: code(b"Fct "), name: "Facet", command: "filter.pixelate.facet" }, - Known { class: "Frgm", filter_id: code(b"Frgm"), name: "Fragment", command: "filter.pixelate.fragment" }, - Known { class: "Shrp", filter_id: code(b"Shrp"), name: "Sharpen", command: "filter.sharpen.sharpen" }, - Known { class: "ShrM", filter_id: code(b"ShrM"), name: "Sharpen More", command: "filter.sharpen.sharpenMore" }, - Known { class: "ShrE", filter_id: code(b"ShrE"), name: "Sharpen Edges", command: "filter.sharpen.sharpenEdges" }, - Known { class: "Slrz", filter_id: code(b"Slrz"), name: "Solarize", command: "filter.stylize.solarize" }, - // Smart Sharpen has a numeric filterID and a stringID class, like Box Blur. - Known { class: SMART_SHARPEN, filter_id: 1131, name: "Smart Sharpen...", command: "filter.sharpen.smartSharpen" }, - Known { class: "DstS", filter_id: code(b"DstS"), name: "Dust & Scratches...", command: "filter.noise.dustAndScratches" }, - // Distort (Photoshop 27, `corpus`-style check: one smart object per filter saved from Photoshop - // and read back). Shear isn't mapped yet: its curve lives on Photoshop's own grid. - Known { class: "Pnch", filter_id: code(b"Pnch"), name: "Pinch...", command: "filter.distort.pinch" }, - Known { class: "Plr ", filter_id: code(b"Plr "), name: "Polar Coordinates...", command: "filter.distort.polarCoordinates" }, - Known { class: "Rple", filter_id: code(b"Rple"), name: "Ripple...", command: "filter.distort.ripple" }, - Known { class: "Sphr", filter_id: code(b"Sphr"), name: "Spherize...", command: "filter.distort.spherize" }, - Known { class: "Twrl", filter_id: code(b"Twrl"), name: "Twirl...", command: "filter.distort.twirl" }, - Known { class: "Wave", filter_id: code(b"Wave"), name: "Wave...", command: "filter.distort.wave" }, - Known { class: "ZgZg", filter_id: code(b"ZgZg"), name: "ZigZag...", command: "filter.distort.zigZag" }, - // Image › Adjustments › Invert on a smart object: no settings, so no `Fltr` (`hasoptions` false). - Known { class: "Invr", filter_id: code(b"Invr"), name: "Invert", command: "image.adjustments.invert" }, - Known { class: "LnsF", filter_id: code(b"LnsF"), name: "Lens Flare...", command: "filter.render.lensFlare" }, - // These three also read the item's foreground and background colours (`coloured_params`). - Known { class: "Fbrs", filter_id: code(b"Fbrs"), name: "Fibers...", command: "filter.render.fibers" }, - Known { class: "Clds", filter_id: code(b"Clds"), name: "Clouds", command: "filter.render.clouds" }, - Known { class: "DfrC", filter_id: code(b"DfrC"), name: "Difference Clouds", command: "filter.render.differenceClouds" }, -]; - -/// Lens Flare's `Lns ` enum and our `lens` values. Photoshop's codes keep the old lens names: -/// Nikon 35 mm and 105 mm primes, a Panavision movie prime. -const LENSES: [(&[u8; 4], &str); 4] = [(b"Zm ", "zoom"), (b"Nkn ", "prime35"), (b"Nkn1", "prime105"), (b"PnVs", "moviePrime")]; - -/// Classes of the filters that have no options: Photoshop stores them without a `Fltr`. -const NO_OPTIONS: [&str; 11] = ["Blr ", "BlrM", "Avrg", "Dspc", "FndE", "Fct ", "Frgm", "Shrp", "ShrM", "ShrE", "Slrz"]; - -// ---------- Smart Sharpen and Dust & Scratches ---------- -// -// Measured in Photoshop (applied through Action Manager to a smart object, saved, `filterFX` read -// back): -// -// ```text -// Smart Sharpen (filterID 1131): smartSharpen { presetKind = presetKindType enum (only on the -// default entry), useLegacy bool, Amnt UntF #Prc, Rds UntF #Pxl, noiseReduction UntF #Prc, -// blur = blurType enum (GsnB | lensBlur | MtnB), Angl long (Motion Blur only) } -// Dust & Scratches (filterID DstS): DstS { Rds long, Thsh long } -// ``` -// -// PhotoCraft's Smart Sharpen removes a Gaussian blur, non-legacy: Lens Blur, Motion Blur, legacy -// mode, Shadow/Highlight settings or any other key keep the whole entry verbatim. `presetKind` -// only names the dialog's preset: it is accepted on open but not kept (the engine takes no such -// parameter) and not written (Photoshop leaves it out of entries with explicit values). - -const SMART_SHARPEN: &str = "smartSharpen"; -const SMART_SHARPEN_KEYS: [&str; 6] = ["presetKind", "useLegacy", "Amnt", "Rds ", "noiseReduction", "blur"]; - -/// A `UntF` value in `unit`, finite and within `lo..=hi`. -fn unit_in(d: &Descriptor, key: &str, u: &[u8; 4], lo: f64, hi: f64) -> Option { - match d.get(key)? { - Value::UnitFloat { unit, value } if unit == u && value.is_finite() && (lo..=hi).contains(value) => Some(*value), - _ => None, - } -} - -/// `filter.sharpen.smartSharpen` params; `None` for a setting PhotoCraft doesn't render. -fn smart_sharpen_params(f: &Descriptor) -> Option { - if f.items.iter().any(|(k, _)| !SMART_SHARPEN_KEYS.iter().any(|x| k.is(x))) { - return None; - } - let Some(Value::Boolean(false)) = f.get("useLegacy") else { return None }; - let Some(Value::Enumerated { type_id, value }) = f.get("blur") else { return None }; - if !type_id.is("blurType") || !value.is("GsnB") { - return None; - } - let mut out = Map::new(); - out.insert("amount".into(), json!(unit_in(f, "Amnt", b"#Prc", 1.0, 500.0)?)); - out.insert("radius".into(), json!(unit_in(f, "Rds ", b"#Pxl", 0.1, 64.0)?)); - out.insert("reduceNoise".into(), json!(unit_in(f, "noiseReduction", b"#Prc", 0.0, 100.0)?)); - match f.get("presetKind") { - None => {} - Some(Value::Enumerated { type_id, .. }) if type_id.is("presetKindType") => {} - Some(_) => return None, - } - Some(J::Object(out)) -} - -/// Photoshop enum codes ↔ PhotoCraft parameter values, per filter setting. -const RIPPLE_SIZE: [(&[u8; 4], &str); 3] = [(b"Sml ", "small"), (b"Mdm ", "medium"), (b"Lrg ", "large")]; -const SPHERIZE_MODE: [(&[u8; 4], &str); 3] = [(b"Nrml", "normal"), (b"HrzO", "horizontalOnly"), (b"VrtO", "verticalOnly")]; -const POLAR_MODE: [(&[u8; 4], &str); 2] = [(b"RctP", "rectangularToPolar"), (b"PlrR", "polarToRectangular")]; -const ZIGZAG_STYLE: [(&[u8; 4], &str); 3] = [(b"PndR", "pondRipples"), (b"OtFr", "outFromCenter"), (b"ArnC", "aroundCenter")]; -const WAVE_TYPE: [(&[u8; 4], &str); 3] = [(b"WvSn", "sine"), (b"WvTr", "triangle"), (b"WvSq", "square")]; -const UNDEFINED_AREAS: [(&[u8; 4], &str); 2] = [(b"WrpA", "wrap"), (b"RptE", "repeat")]; - -/// The PSD filter record that PhotoCraft's `command` is written as, if it has one. -fn known_by_command(command: &str) -> Option<&'static Known> { - KNOWN.iter().find(|k| k.command == command) -} - -/// RGB channel references in Levels/Curves (`Chnl` enum) and their parameter keys ("" = the -/// composite: top-level keys). -const CHANNELS: [(&[u8; 4], &str); 4] = [(b"Cmps", ""), (b"Rd ", "red"), (b"Grn ", "green"), (b"Bl ", "blue")]; - -/// Mezzotint's `MztT` enum codes and our `type` values (measured in Photoshop by rendering each). -const MEZZOTINT_TYPES: [(&[u8; 4], &str); 10] = [ - (b"FnDt", "fineDots"), - (b"MdmD", "mediumDots"), - (b"GrnD", "grainyDots"), - (b"CrsD", "coarseDots"), - (b"ShrL", "shortLines"), - (b"MdmL", "mediumLines"), - (b"LngL", "longLines"), - (b"ShSt", "shortStrokes"), - (b"MdmS", "mediumStrokes"), - (b"LngS", "longStrokes"), -]; - -/// Color Halftone's `Rds ` (max radius) and `Ang1`..`Ang4` (screen angles) longs, read within -/// the dialog's ranges; anything else is kept verbatim. -fn color_halftone_params(f: &Descriptor) -> Option { - if !only_keys(f, &["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"]) { - return None; - } - let radius = int(f, "Rds ").filter(|r| (4..=127).contains(r))?; - let angle = |k: &str| int(f, k).filter(|a| (-360..=360).contains(a)); - Some(json!({"maxRadius": radius, "channel1": angle("Ang1")?, "channel2": angle("Ang2")?, "channel3": angle("Ang3")?, "channel4": angle("Ang4")?})) -} - -/// A numeric descriptor item as a finite number; `None` when it is absent, not a number, or not finite. -fn px(d: &Descriptor, key: &str) -> Option { - num(d.get(key)).filter(|v| v.is_finite()) -} - -/// An integer descriptor item; `None` when it is absent or of another type. -fn int(d: &Descriptor, key: &str) -> Option { - match d.get(key)? { - Value::Integer(i) => Some(*i), - _ => None, - } -} - -/// `v` when it lies in `lo..=hi` (the filter dialog's range); out-of-range settings are not -/// opened as editable filters, so a re-save keeps Photoshop's value instead of a clamped one. -fn in_range(v: f64, lo: f64, hi: f64) -> Option { - (lo..=hi).contains(&v).then_some(v) -} - -/// Integer `key` of `f` when it lies in `lo..=hi`. -fn int_in(f: &Descriptor, key: &str, lo: i32, hi: i32) -> Option { - int(f, key).filter(|v| (lo..=hi).contains(v)) -} - -/// True when `f` holds only the given keys, each at most once. A filter with a setting we don't -/// know about (Radial Blur's off-centre centre, for one) or a repeated one is kept verbatim rather -/// than losing that setting. -fn only_keys(f: &Descriptor, keys: &[&str]) -> bool { - f.items.iter().all(|(k, _)| keys.iter().any(|x| k.is(x))) && keys.iter().all(|key| f.items.iter().filter(|(k, _)| k.is(key)).count() <= 1) -} - -/// Our name for enum `key`'s value in `f` (of enum type `type_id`), from `(PSD value, our name)` -/// pairs. An enum of another type is not one we know, so the filter stays verbatim. -fn enum_name(f: &Descriptor, key: &str, type_id: &str, table: &[(&[u8; 4], &'static str)]) -> Option<&'static str> { - let Some(Value::Enumerated { type_id: t, value }) = f.get(key) else { return None }; - if t.as_bytes() != type_id.as_bytes() { - return None; - } - table.iter().find(|(c, _)| value.as_bytes() == &c[..]).map(|(_, n)| *n) -} - -/// True when `f` holds each of the given keys once and nothing else. -fn exact_keys(f: &Descriptor, keys: &[&str]) -> bool { - only_keys(f, keys) && keys.iter().all(|x| f.items.iter().any(|(k, _)| k.is(x))) -} - -/// Finite `key` of `f` stored as a plain double (the type Photoshop writes and we write back). -fn double(f: &Descriptor, key: &str) -> Option { - match f.get(key)? { - Value::Double(v) if v.is_finite() => Some(*v), - _ => None, - } -} - -/// `p[key]` (`default` when absent) when it is a number in `lo..=hi`, the range the filter opens -/// with; anything else is an error, so a saved filter always opens as the same editable filter. -fn pf_range(p: &J, key: &str, default: f64, lo: f64, hi: f64) -> Result { - match p.get(key) { - None | Some(J::Null) => Ok(default), - Some(v) => v.as_f64().filter(|x| (lo..=hi).contains(x)).ok_or_else(|| format!("setting `{key}` ({v}) is not a number in {lo}..={hi}")), - } -} - -/// Integer `p[key]` (rounded; `default` when absent) in `lo..=hi`, as a PSD long. -fn pi_range(p: &J, key: &str, default: f64, lo: i32, hi: i32) -> Result { - let v = pf_range(p, key, default, f64::from(i32::MIN), f64::from(i32::MAX))?.round(); - let range = f64::from(lo)..=f64::from(hi); - if !range.contains(&v) { - return Err(format!("setting `{key}` ({v}) is not a number in {lo}..={hi}")); - } - Ok(Value::Integer(v as i32)) -} - -/// Enum `type_id` holding the PSD value of our name `p[key]` (`default` when absent). -fn enum_param(p: &J, key: &str, default: &str, type_id: &str, table: &[(&[u8; 4], &'static str)]) -> Result { - let name = match p.get(key) { - None | Some(J::Null) => default, - Some(v) => v.as_str().ok_or_else(|| format!("setting `{key}` is not text"))?, - }; - let code = table.iter().find(|(_, n)| *n == name).map(|(c, _)| **c).ok_or_else(|| format!("{key} `{name}` has no PSD equivalent"))?; - Ok(Value::Enumerated { type_id: Id::new(type_id), value: Id::Code(code) }) -} - -/// Smart Blur `SmBQ` / `SmBM` and Radial Blur `BlrM` / `BlrQ` values (measured in Photoshop). -const SMART_BLUR_QUALITY: [(&[u8; 4], &str); 3] = [(b"SBQL", "low"), (b"SBQM", "medium"), (b"SBQH", "high")]; -const SMART_BLUR_MODE: [(&[u8; 4], &str); 3] = [(b"SBMN", "normal"), (b"SBME", "edgeOnly"), (b"SBMO", "overlayEdge")]; -const RADIAL_METHOD: [(&[u8; 4], &str); 2] = [(b"Spn ", "spin"), (b"Zm ", "zoom")]; -const RADIAL_QUALITY: [(&[u8; 4], &str); 3] = [(b"Drft", "draft"), (b"Gd ", "good"), (b"Bst ", "best")]; - -fn channel_key(d: &Descriptor) -> Option<&'static str> { - let Some(Value::Reference(items)) = d.get("Chnl") else { return None }; - let Some(ReferenceItem::Enumerated { value, .. }) = items.first() else { return None }; - CHANNELS.iter().find(|(c, _)| value.as_bytes() == &c[..]).map(|(_, k)| *k) -} - -fn adjustment_list(d: &Descriptor) -> Option> { - let Some(Value::List(items)) = d.get("Adjs") else { return None }; - items - .iter() - .map(|v| match v { - Value::Descriptor(x) => Some(x), - _ => None, - }) - .collect() -} - -fn levels_params(f: &Descriptor) -> Option { - let mut out = Map::new(); - for a in adjustment_list(f)? { - let key = channel_key(a)?; - let mut o = Map::new(); - let pair = |k: &str| match a.get(k) { - Some(Value::List(v)) if v.len() == 2 => Some((int_value(&v[0])?, int_value(&v[1])?)), - _ => None, - }; - if let Some((lo, hi)) = pair("Inpt") { - o.insert("inBlack".into(), json!(lo)); - o.insert("inWhite".into(), json!(hi)); - } - if let Some(g) = px(a, "Gmm ") { - o.insert("gamma".into(), json!(g)); - } - if let Some((lo, hi)) = pair("Otpt") { - o.insert("outBlack".into(), json!(lo)); - o.insert("outWhite".into(), json!(hi)); - } - if key.is_empty() { - out.extend(o); - } else { - out.insert(key.into(), J::Object(o)); - } - } - Some(J::Object(out)) -} - -fn int_value(v: &Value) -> Option { - match v { - Value::Integer(i) => Some(*i), - _ => None, - } -} - -fn curves_params(f: &Descriptor) -> Option { - let mut out = Map::new(); - for a in adjustment_list(f)? { - let key = channel_key(a)?; - // A pencil-drawn curve is a mapping of 256 output levels (`Mpng`) instead of points. - if let Some(Value::List(map)) = a.get("Mpng") { - let map: Option> = map.iter().map(|v| int_value(v).map(|o| json!(o.clamp(0, 255)))).collect(); - out.insert(if key.is_empty() { "points".into() } else { key.into() }, J::Array(map.filter(|m| m.len() == 256)?)); - out.insert("pencil".into(), J::Bool(true)); - continue; - } - let Some(Value::List(pts)) = a.get("Crv ") else { return None }; - let pts: Option> = pts - .iter() - .map(|p| match p { - Value::Descriptor(p) => Some(json!([px(p, "Hrzn")?, px(p, "Vrtc")?])), - _ => None, - }) - .collect(); - out.insert(if key.is_empty() { "points".into() } else { key.into() }, J::Array(pts?)); - } - Some(J::Object(out)) -} - -/// Diffuse's `Md ` (`DfsM` enum, measured in Photoshop) ↔ our `mode`. -const DIFFUSE_MODES: [(&str, &str); 4] = [("Nrml", "normal"), ("DrkO", "darkenOnly"), ("LghO", "lightenOnly"), ("anisotropic", "anisotropic")]; - -/// Trace Contour's `Edg ` (`CntE` enum, measured in Photoshop) ↔ our `edge`. -const TRACE_EDGES: [(&str, &str); 2] = [("Upr ", "upper"), ("Lwr ", "lower")]; - -/// Our name for the enum value of `key` (of type `type_id`) through `table` (Photoshop's value, ours). -fn enum_from(d: &Descriptor, key: &str, type_id: &str, table: &[(&str, &'static str)]) -> Option<&'static str> { - let Some(Value::Enumerated { type_id: t, value }) = d.get(key) else { return None }; - if t.as_bytes() != type_id.as_bytes() { - return None; - } - table.iter().find(|(psd, _)| value.as_bytes() == psd.as_bytes()).map(|(_, ours)| *ours) -} - -// Wind, Extrude and Tiles, measured in Photoshop (each code changes the rendered result). - -/// Wind's `WndM` (enum `WndM`) ↔ our `method`. -const WIND_METHODS: [(&str, &str); 3] = [("Wnd ", "wind"), ("Blst", "blast"), ("Stgr", "stagger")]; -/// Wind's `Drct` (enum `Drct`) ↔ our `direction`. Photoshop's `Left` streaks extend to the left -/// of an edge, which is our wind from the right. -const WIND_DIRECTIONS: [(&str, &str); 2] = [("Left", "fromRight"), ("Rght", "fromLeft")]; -/// Extrude's `ExtT` (enum `ExtT`) ↔ our `type`. -const EXTRUDE_TYPES: [(&str, &str); 2] = [("Blks", "blocks"), ("Pyrm", "pyramids")]; -/// Extrude's `ExtR` (enum `ExtR`) ↔ our `depthMode`. -const EXTRUDE_DEPTHS: [(&str, &str); 2] = [("Rndm", "random"), ("LvlB", "levelBased")]; -/// Tiles' `FlCl` (enum `FlCl`) ↔ our `fill`. -const TILE_FILLS: [(&str, &str); 4] = [("FlBc", "background"), ("FlFr", "foreground"), ("FlIn", "inverse"), ("FlSm", "unaltered")]; -/// Extrude's size and depth (`ExtS`, `ExtD`) and Tiles' count and offset (`TlNm`, `TlOf`), all -/// `long`s, in the engine's (and Photoshop's dialog) ranges. -const EXTRUDE_SIZE: (i32, i32) = (2, 255); -const EXTRUDE_DEPTH: (i32, i32) = (1, 255); -const TILE_COUNT: (i32, i32) = (1, 99); -const TILE_OFFSET: (i32, i32) = (1, 99); - -/// The `bool` at `key`. -fn bool_at(d: &Descriptor, key: &str) -> Option { - match d.get(key)? { - Value::Boolean(b) => Some(*b), - _ => None, - } -} - -/// Tiles' params; background and foreground fills use the colours the entry carries (`FrgC`, -/// `BckC`). `None` when a setting or a colour that is there can't be read. -fn tiles_params(f: &Descriptor, item: &Descriptor) -> Option { - let mut out = Map::new(); - out.insert("count".into(), json!(int_in(f, "TlNm", TILE_COUNT.0, TILE_COUNT.1)?)); - out.insert("maxOffset".into(), json!(int_in(f, "TlOf", TILE_OFFSET.0, TILE_OFFSET.1)?)); - out.insert("fill".into(), json!(enum_from(f, "FlCl", "FlCl", &TILE_FILLS)?)); - for (psd, ours) in [("FrgC", "foreground"), ("BckC", "background")] { - if item.get(psd).is_some() { - out.insert(ours.into(), get_desc(item, psd).and_then(rgbc_colour)?); - } - } - Some(J::Object(out)) -} - -/// Offset › Undefined Areas: the `FlMd` enum (`Fl `) and our `undefinedAreas`. On a layer -/// Photoshop labels `Bckg` "Set to Transparent"; a smart object is always a layer. -const OFFSET_FILL: [(&str, &str); 3] = [("Wrp ", "wrap"), ("Rpt ", "repeat"), ("Bckg", "transparent")]; - -/// Custom's ranges in Photoshop's dialog: matrix cells, Scale, Offset. -const CUSTOM_CELL: (i32, i32) = (-999, 999); -const CUSTOM_SCALE: (i32, i32) = (1, 9999); -const CUSTOM_OFFSET: (i32, i32) = (-9999, 9999); - -/// `v` when it lies in `lo..=hi`. -fn long_in_range(v: Option, (lo, hi): (i32, i32)) -> Option { - v.filter(|v| (lo..=hi).contains(v)) -} - -/// `filter.other.custom` params for a `Cstm` filter: `Mtrx` is 25 longs, row-major 5 × 5. Values -/// outside Photoshop's ranges are not modelled (the filter stays verbatim). -fn custom_params(f: &Descriptor) -> Option { - if !only_keys(f, &["Mtrx", "Scl ", "Ofst"]) { - return None; - } - let Some(Value::List(m)) = f.get("Mtrx") else { return None }; - if m.len() != 25 { - return None; - } - let kernel: Option> = m.iter().map(|v| long_in_range(int_value(v), CUSTOM_CELL).map(|v| json!(v))).collect(); - let scale = long_in_range(int(f, "Scl "), CUSTOM_SCALE)?; - let offset = long_in_range(int(f, "Ofst"), CUSTOM_OFFSET)?; - Some(json!({"kernel": kernel?, "scale": scale, "offset": offset})) -} - -/// The settings of Photoshop's Wave, as it writes them (and we write them back). -const WAVE_KEYS: [&str; 10] = ["Wvtp", "NmbG", "WLMn", "WLMx", "AmMn", "AmMx", "SclH", "SclV", "UndA", "RndS"]; - -/// Our command and parameters for a known Photoshop filter; `None` when the filter (or one of its -/// settings) is not modelled. `item` is the whole `filterFX` entry (Pointillize reads its `BckC`, -/// Tiles its colours). -fn known_params(class: &str, f: Option<&Descriptor>, item: &Descriptor) -> Option<(&'static str, J)> { - let k = KNOWN.iter().find(|k| k.class == class)?; - let params = match (class, f) { - ("adaptCorrect" | "Invr", None) => json!({}), - (c, None) if NO_OPTIONS.contains(&c) => json!({}), - (_, None) => return None, - // Exactly the settings Photoshop writes (and we write back); an extra or repeated one keeps - // the filter verbatim rather than lose it on save. - ("Pnch", Some(f)) if exact_keys(f, &["Amnt"]) => json!({"amount": int(f, "Amnt")?}), - ("Twrl", Some(f)) if exact_keys(f, &["Angl"]) => json!({"angle": int(f, "Angl")?}), - ("Rple", Some(f)) if exact_keys(f, &["Amnt", "RplS"]) => json!({"amount": int(f, "Amnt")?, "size": enum_name(f, "RplS", "RplS", &RIPPLE_SIZE)?}), - ("Sphr", Some(f)) if exact_keys(f, &["Amnt", "SphM"]) => json!({"amount": int(f, "Amnt")?, "mode": enum_name(f, "SphM", "SphM", &SPHERIZE_MODE)?}), - ("Plr ", Some(f)) if exact_keys(f, &["Cnvr"]) => json!({"mode": enum_name(f, "Cnvr", "Cnvr", &POLAR_MODE)?}), - ("ZgZg", Some(f)) if exact_keys(f, &["Amnt", "NmbR", "ZZTy"]) => { - json!({"amount": int(f, "Amnt")?, "ridges": int(f, "NmbR")?, "style": enum_name(f, "ZZTy", "ZZTy", &ZIGZAG_STYLE)?}) - } - ("Wave", Some(f)) if exact_keys(f, &WAVE_KEYS) => { - // PhotoCraft's Wave has no Scale: a scaled wave stays verbatim rather than lose it. The - // same for more generators than the renderer models, which would draw fewer than - // Photoshop did (and than the file asks for, once its cached pixels are re-rendered). - let generators = int(f, "NmbG")?; - let modelled = u32::try_from(generators).is_ok_and(|g| (1..=photocraft_algo::MAX_WAVE_GENERATORS).contains(&g)); - if int(f, "SclH")? != 100 || int(f, "SclV")? != 100 || !modelled { - return None; - } - json!({ - "type": enum_name(f, "Wvtp", "Wvtp", &WAVE_TYPE)?, - "generators": generators, - "wavelengthMin": int(f, "WLMn")?, - "wavelengthMax": int(f, "WLMx")?, - "amplitudeMin": int(f, "AmMn")?, - "amplitudeMax": int(f, "AmMx")?, - "undefinedAreas": enum_name(f, "UndA", "UndA", &UNDEFINED_AREAS)?, - // `RndS` is a signed long; the seed is its bit pattern. - "seed": (int(f, "RndS")? as u32), - }) - } - ("GsnB" | "boxblur" | "Mdn " | "HghP" | "Mxm " | "Mnm ", Some(f)) => json!({"radius": px(f, "Rds ")?}), - ("MtnB", Some(f)) => json!({"angle": int(f, "Angl")?, "distance": px(f, "Dstn")?}), - ("UnsM", Some(f)) => json!({"amount": px(f, "Amnt")?, "radius": px(f, "Rds ")?, "threshold": int(f, "Thsh")?}), - ("AdNs", Some(f)) => { - let dist = match enum_of(f, "Dstr")? { - b"Unfr" => "uniform", - b"Gsn " => "gaussian", - _ => return None, - }; - let mono = match f.get("Mnch") { - Some(Value::Boolean(b)) => *b, - _ => return None, - }; - json!({"amount": px(f, "Nose")?, "distribution": dist, "monochromatic": mono, "seed": int(f, "FlRs").unwrap_or(0)}) - } - ("surfaceBlur", Some(f)) if only_keys(f, &["Rds ", "Thsh"]) => json!({ - "radius": unit_in(f, "Rds ", b"#Pxl", 1.0, 100.0)?, - "threshold": int_in(f, "Thsh", 2, 255)?, - }), - ("SmrB", Some(f)) if only_keys(f, &["Rds ", "Thsh", "SmBQ", "SmBM"]) => json!({ - "radius": in_range(double(f, "Rds ")?, 0.1, 100.0)?, - "threshold": in_range(double(f, "Thsh")?, 0.1, 100.0)?, - "quality": enum_name(f, "SmBQ", "SmBQ", &SMART_BLUR_QUALITY)?, - "mode": enum_name(f, "SmBM", "SmBM", &SMART_BLUR_MODE)?, - }), - ("RdlB", Some(f)) if only_keys(f, &["Amnt", "BlrM", "BlrQ"]) => json!({ - "amount": int_in(f, "Amnt", 1, 100)?, - "method": enum_name(f, "BlrM", "BlrM", &RADIAL_METHOD)?, - "quality": enum_name(f, "BlrQ", "BlrQ", &RADIAL_QUALITY)?, - }), - ("Msc ", Some(f)) => json!({"cellSize": px(f, "ClSz")?}), - ("Mztn", Some(f)) if only_keys(f, &["MztT"]) => json!({"type": enum_name(f, "MztT", "MztT", &MEZZOTINT_TYPES)?}), - ("ClrH", Some(f)) => color_halftone_params(f)?, - ("Embs", Some(f)) => json!({"angle": int(f, "Angl")?, "height": int(f, "Hght")?, "amount": int(f, "Amnt")?}), - (SMART_SHARPEN, Some(f)) => smart_sharpen_params(f)?, - ("DstS", Some(f)) => { - if f.items.iter().any(|(k, _)| !k.is("Rds ") && !k.is("Thsh")) { - return None; - } - json!({"radius": int_in(f, "Rds ", 1, 500)?, "threshold": int_in(f, "Thsh", 0, 255)?}) - } - ("Dfs ", Some(f)) => json!({"mode": enum_from(f, "Md ", "DfsM", &DIFFUSE_MODES)?}), - ("TrcC", Some(f)) => json!({"level": int_in(f, "Lvl ", 0, 255)?, "edge": enum_from(f, "Edg ", "CntE", &TRACE_EDGES)?}), - ("Crst", Some(f)) => json!({"cellSize": int_in(f, "ClSz", CELL_SIZE.0, CELL_SIZE.1)?}), - ("Pntl", Some(f)) => { - let mut p = json!({"cellSize": int_in(f, "ClSz", CELL_SIZE.0, CELL_SIZE.1)?}); - // Pointillize paints the gaps in the background colour the entry carries. - if item.get("BckC").is_some() { - p["background"] = get_desc(item, "BckC").and_then(rgbc_colour)?; - } - p - } - ("Wnd ", Some(f)) => json!({ - "method": enum_from(f, "WndM", "WndM", &WIND_METHODS)?, - "direction": enum_from(f, "Drct", "Drct", &WIND_DIRECTIONS)?, - }), - ("Extr", Some(f)) => json!({ - "type": enum_from(f, "ExtT", "ExtT", &EXTRUDE_TYPES)?, - "size": int_in(f, "ExtS", EXTRUDE_SIZE.0, EXTRUDE_SIZE.1)?, - "depth": int_in(f, "ExtD", EXTRUDE_DEPTH.0, EXTRUDE_DEPTH.1)?, - "depthMode": enum_from(f, "ExtR", "ExtR", &EXTRUDE_DEPTHS)?, - "solidFrontFaces": bool_at(f, "ExtF")?, - "maskIncompleteBlocks": bool_at(f, "ExtM")?, - }), - ("Tls ", Some(f)) => tiles_params(f, item)?, - ("Ofst", Some(f)) if only_keys(f, &["Hrzn", "Vrtc", "Fl "]) => { - json!({"horizontal": int(f, "Hrzn")?, "vertical": int(f, "Vrtc")?, "undefinedAreas": enum_from(f, "Fl ", "FlMd", &OFFSET_FILL)?}) - } - ("Cstm", Some(f)) => custom_params(f)?, - // Only the settings and value types Photoshop writes (and we write back); anything else - // keeps the filter verbatim. - ("LnsF", Some(f)) if exact_keys(f, &["Brgh", "FlrC", "Lns "]) => { - let centre = get_desc(f, "FlrC").filter(|c| c.class_id.is("Pnt ") && exact_keys(c, &["Hrzn", "Vrtc"]))?; - let lens = enum_name(f, "Lns ", "Lns ", &LENSES)?; - json!({"brightness": int(f, "Brgh")?, "centerX": double(centre, "Hrzn")?, "centerY": double(centre, "Vrtc")?, "lens": lens}) - } - ("Lvls", Some(f)) => levels_params(f)?, - ("Crvs", Some(f)) => curves_params(f)?, - _ => return None, - }; - Some((k.command, params)) -} - -// ---------- Filter Gallery ---------- -// -// Filter › Filter Gallery stores its effect stack in a `GEfc` filter (filterID `GEfc`). Photoshop -// writes a single effect inline; Photopea writes a list (also for one effect): -// -// ```text -// Fltr = GEfc { GEfk = GEft enum (the effect), } (Photoshop) -// Fltr = GEfc { GEfs = [ GEfc { , GEfk = GEft enum, GELv = visible } ] } (Photopea) -// ``` -// -// The list is in application order, like `filter.filterGallery`'s `effects`. The item's -// `FrgC`/`BckC` are the colours the Sketch effects read. Only effects whose settings we know are -// mapped; a stack with any other effect (or setting) stays an [`UNSUPPORTED_FILTER`]. - -const GALLERY_CLASS: &str = "GEfc"; -const GALLERY_COMMAND: &str = "filter.filterGallery"; -const GALLERY_NAME: &str = "Filter Gallery..."; - -/// One gallery effect: our filter key, Photoshop's `GEft` code and its settings (PSD key, our key). -struct GalleryCode { - key: &'static str, - code: &'static str, - settings: &'static [(&'static str, &'static str)], -} - -const GALLERY_EFFECTS: [GalleryCode; 1] = [GalleryCode { key: "chrome", code: "Chrm", settings: &[("Dtl ", "detail"), ("Smth", "smoothness")] }]; - -/// An `RGBC` descriptor (0–255 channels) as straight `[r, g, b, a]`, 0–1. -fn rgbc_colour(d: &Descriptor) -> Option { - let c = |k: &str| px(d, k).map(|v| (v / 255.0).clamp(0.0, 1.0)); - Some(json!([c("Rd ")?, c("Grn ")?, c("Bl ")?, 1.0])) -} - -/// Fibers, Clouds and Difference Clouds draw with the item's foreground and background colours: -/// their params are the `Fltr` settings plus those colours. -fn coloured_params(class: &str, item: &Descriptor, f: &Descriptor) -> Option<(&'static str, J)> { - let k = KNOWN.iter().find(|k| k.class == class)?; - // An `RGBC` of three `doub`s in 0–255, as Photoshop writes it (and we write it back); any - // other colour keeps the filter verbatim. - let colour = |key: &str| { - get_desc(item, key) - .filter(|c| c.class_id.is("RGBC") && exact_keys(c, &["Rd ", "Grn ", "Bl "])) - .filter(|c| ["Rd ", "Grn ", "Bl "].iter().all(|k| double(c, k).is_some_and(|v| (0.0..=255.0).contains(&v)))) - .and_then(rgbc_colour) - }; - // Only the settings Photoshop writes; an extra or repeated one keeps the filter verbatim. - let keys: &[&str] = if class == "Fbrs" { &["Vrnc", "Strg", "RndS"] } else { &["FlRs"] }; - if !exact_keys(f, keys) { - return None; - } - // The seeds (`RndS`, `FlRs`) are signed longs; ours is their bit pattern. - let mut p = match class { - "Fbrs" => json!({"variance": int(f, "Vrnc")?, "strength": int(f, "Strg")?, "seed": int(f, "RndS")? as u32}), - _ => json!({"seed": int(f, "FlRs")? as u32}), - }; - let o = p.as_object_mut()?; - o.insert("foreground".into(), colour("FrgC")?); - o.insert("background".into(), colour("BckC")?); - Some((k.command, p)) -} - -fn seed_param(p: &J) -> Value { - Value::Integer(p.get("seed").and_then(J::as_u64).and_then(|n| u32::try_from(n).ok()).unwrap_or(0) as i32) -} - -/// `filter.filterGallery` params for a `GEfc` filter item; `None` when an effect or setting is -/// not modelled. -fn gallery_params(item: &Descriptor, f: &Descriptor) -> Option { - let list: Vec<&Descriptor> = match f.get("GEfs") { - Some(Value::List(list)) => list - .iter() - .map(|v| match v { - Value::Descriptor(e) => Some(e), - _ => None, - }) - .collect::>()?, - Some(_) => return None, - None if f.get("GEfk").is_some() => vec![f], - None => return None, - }; - let mut effects = Vec::with_capacity(list.len()); - for e in list { - let code = enum_of(e, "GEfk")?; - let g = GALLERY_EFFECTS.iter().find(|g| g.code.as_bytes() == code)?; - let mut params = Map::new(); - for (k, v) in &e.items { - if k.is("GEfk") || k.is("GELv") { - continue; - } - let (_, ours) = g.settings.iter().find(|(psd, _)| k.is(psd))?; - params.insert((*ours).into(), json!(int_value(v)?)); - } - effects.push(json!({"filter": g.key, "params": params, "visible": bool_or(e, "GELv", true)})); - } - if effects.is_empty() { - return None; - } - let mut out = Map::new(); - out.insert("effects".into(), J::Array(effects)); - for (psd, ours) in [("FrgC", "foreground"), ("BckC", "background")] { - if let Some(c) = get_desc(item, psd).and_then(rgbc_colour) { - out.insert(ours.into(), c); - } - } - Some(J::Object(out)) -} - -fn colour_rgb(v: &J) -> Option<[f64; 3]> { - match v { - J::Array(a) => Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?]), - J::String(h) if h.len() == 7 && h.starts_with('#') => { - let ch = |j: usize| h.get(j..j + 2).and_then(|s| u8::from_str_radix(s, 16).ok()).map(|v| f64::from(v) / 255.0); - Some([ch(1)?, ch(3)?, ch(5)?]) - } - _ => None, - } -} - -/// A `[r, g, b(, a)]` (0–1) or `#rrggbb` colour param as an `RGBC` descriptor (0–255). -fn colour_rgbc(v: Option<&J>, default: f64) -> Result { - let Some(v) = v else { return Ok(rgbc(default)) }; - let rgb = colour_rgb(v).filter(|c| c.iter().all(|v| v.is_finite())).ok_or("a colour is not [r, g, b] or #rrggbb")?; - let c = |v: f64| Value::Double(v.clamp(0.0, 1.0) * 255.0); - Ok(Value::Descriptor(Descriptor::new("RGBC").with("Rd ", c(rgb[0])).with("Grn ", c(rgb[1])).with("Bl ", c(rgb[2])))) -} - -/// The `filterFXList` item for a `filter.filterGallery` smart filter. -fn gallery_item(f: &SmartFilter) -> Result { - let p = &f.params; - if let Some(k) = p.as_object().and_then(|o| o.keys().find(|k| !is_meta(k) && !["effects", "foreground", "background"].contains(&k.as_str()))) { - return Err(format!("setting `{k}` has no PSD equivalent")); - } - let list = p.get("effects").and_then(J::as_array).ok_or("it has no effects")?; - let mut out = Vec::with_capacity(list.len()); - for e in list { - let key = e.get("filter").and_then(J::as_str).ok_or("an effect has no `filter`")?; - let g = GALLERY_EFFECTS.iter().find(|g| g.key == key).ok_or_else(|| format!("gallery effect `{key}` has no PSD equivalent"))?; - let params = e.get("params").filter(|v| v.is_object()).unwrap_or(e); - if let Some(k) = params.as_object().and_then(|o| { - o.keys().find(|k| !is_meta(k) && !["filter", "params", "visible"].contains(&k.as_str()) && !g.settings.iter().any(|(_, ours)| ours == k)) - }) { - return Err(format!("gallery setting `{key}.{k}` has no PSD equivalent")); - } - let defaults = photocraft_algo::GalleryFilter::from_key(key).map(photocraft_algo::GalleryEffect::new); - let settings: Vec<(&str, Value)> = - g.settings.iter().map(|(psd, ours)| (*psd, pi(params, ours, defaults.as_ref().map_or(0.0, |x| f64::from(x.get(ours)))))).collect(); - out.push((g.code, settings, e.get("visible").and_then(J::as_bool).unwrap_or(true))); - } - let gallery = || { - let mut d = Descriptor::new(GALLERY_CLASS); - d.name = UnicodeString::new_nul("Filter Gallery"); - d - }; - // One visible effect: inline, as Photoshop writes it. Otherwise the effect list. - let fltr = match out.as_slice() { - [] => return Err("it has no effects".into()), - [(code, settings, true)] => settings.iter().fold(gallery().with("GEfk", enumv("GEft", code)), |d, (k, v)| d.with(k, v.clone())), - _ => { - let list = out - .into_iter() - .map(|(code, settings, visible)| { - let d = settings.into_iter().fold(gallery(), |d, (k, v)| d.with(k, v)); - Value::Descriptor(d.with("GEfk", enumv("GEft", code)).with("GELv", Value::Boolean(visible))) - }) - .collect(); - gallery().with("GEfs", Value::List(list)) - } - }; - Ok(Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul(GALLERY_NAME))) - .with("blendOptions", blend_options(f)) - .with("enab", Value::Boolean(f.visible)) - .with("hasoptions", Value::Boolean(true)) - .with("FrgC", colour_rgbc(p.get("foreground"), 0.0)?) - .with("BckC", colour_rgbc(p.get("background"), 255.0)?) - .with("Fltr", Value::Descriptor(fltr)) - .with("filterID", Value::Integer(code(b"GEfc")))) -} - -/// Lowercase hex of `bytes`. -fn to_hex(bytes: &[u8]) -> String { - const H: &[u8; 16] = b"0123456789abcdef"; - let mut s = String::with_capacity(bytes.len() * 2); - for b in bytes { - s.push(char::from(H[usize::from(b >> 4)])); - s.push(char::from(H[usize::from(b & 15)])); - } - s -} - -fn from_hex(s: &str) -> Option> { - let d = |c: u8| (c as char).to_digit(16).map(|v| v as u8); - let b = s.as_bytes(); - if !b.len().is_multiple_of(2) { - return None; - } - b.as_chunks::<2>().0.iter().map(|c| Some(d(c[0])? << 4 | d(c[1])?)).collect() -} - -/// One `filterFXList` item → [`SmartFilter`] (an [`UNSUPPORTED_FILTER`] when not modelled). -pub fn filter_from_item(item: &Descriptor) -> SmartFilter { - let opts = get_desc(item, "blendOptions"); - let opacity = opts.and_then(|o| px(o, "Opct")).map_or(1.0, |v| (v / 100.0).clamp(0.0, 1.0) as f32); - let blend = opts.and_then(|o| enum_of(o, "Md ")).and_then(crate::effects_map::blend_from_id).unwrap_or(BlendMode::Normal); - let visible = bool_or(item, "enab", true); - let fltr = get_desc(item, "Fltr"); - let class = fltr.map(|f| String::from_utf8_lossy(f.class_id.as_bytes()).into_owned()); - let filter_id = int(item, "filterID").unwrap_or(0); - let class = class.or_else(|| KNOWN.iter().find(|k| k.filter_id == filter_id).map(|k| k.class.to_string())); - let known = match class.as_deref() { - Some(camera_raw::CLASS) => camera_raw::import_params(item).map(|p| (camera_raw::COMMAND, p)), - Some(displace::CLASS) => displace::import_params(item).map(|p| (displace::COMMAND, p)), - Some(hue_sat::CLASS) => fltr.and_then(hue_sat::import_params).map(|p| (hue_sat::COMMAND, p)), - Some(perspective_warp::CLASS) => perspective_warp::import_params(item).map(|p| (perspective_warp::COMMAND, p)), - Some(GALLERY_CLASS) => fltr.and_then(|f| gallery_params(item, f)).map(|p| (GALLERY_COMMAND, p)), - Some(c @ ("Fbrs" | "Clds" | "DfrC")) => fltr.and_then(|f| coloured_params(c, item, f)), - // A `Fltr` that is there but not a descriptor is settings we can't read: kept verbatim - // rather than taken for a filter stored without options (which would drop it on save). - _ if fltr.is_none() && item.get("Fltr").is_some() => None, - c => c.and_then(|c| known_params(c, fltr, item)), - }; - let (command, params) = match known { - Some((c, p)) => (c.to_string(), p), - None => { - let name = text_of(item, "Nm ").unwrap_or_default(); - // The stored descriptor carries neutral blending (the model's own fields replace - // them on export), so hiding or re-blending the filter leaves its params alone. - let mut neutral = item.clone(); - for (k, v) in &mut neutral.items { - if k.is("blendOptions") { - *v = blend_options(&SmartFilter { command: String::new(), params: J::Null, blend: BlendMode::Normal, opacity: 1.0, visible: true }); - } else if k.is("enab") { - *v = Value::Boolean(true); - } - } - (UNSUPPORTED_FILTER.to_string(), json!({"name": name.replace('&', ""), "filterID": filter_id, "psd": to_hex(&neutral.to_bytes())})) - } - }; - SmartFilter { command, params, blend, opacity, visible } -} - -// ---------- writing ---------- - -fn unit(u: &[u8; 4], v: f64) -> Value { - Value::UnitFloat { unit: *u, value: v } -} - -fn rgbc(v: f64) -> Value { - Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))) -} - -fn blend_options(f: &SmartFilter) -> Value { - let opacity = if f.opacity.is_finite() { f64::from(f.opacity.clamp(0.0, 1.0)) * 100.0 } else { 100.0 }; - Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", opacity)).with("Md ", crate::effects_map::blend_long_value(f.blend))) -} - -/// Parameter keys that are bookkeeping, not filter settings. -fn is_meta(k: &str) -> bool { - k == "layer" || k.starts_with("__") -} - -fn pf(p: &J, key: &str, default: f64) -> f64 { - p.get(key).and_then(J::as_f64).filter(|v| v.is_finite()).unwrap_or(default) -} - -fn pi(p: &J, key: &str, default: f64) -> Value { - Value::Integer(pf(p, key, default).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32) -} - -/// A whole-number setting as a long, clamped to `range` like the engine clamps it; a fraction -/// has no PSD equivalent (Photoshop stores these as integers). -fn whole(v: f64, (lo, hi): (i32, i32), what: &str) -> Result { - if v.fract() != 0.0 { - return Err(format!("{what} ({v}) is not a whole number")); - } - Ok(Value::Integer(v.clamp(f64::from(lo), f64::from(hi)) as i32)) -} - -fn channel_ref(code: &[u8; 4]) -> Value { - Value::Reference(vec![ReferenceItem::Enumerated { - class: Class { name: UnicodeString::new_nul(""), class_id: Id::new("Chnl") }, - type_id: Id::new("Chnl"), - value: Id::Code(*code), - }]) -} - -/// The `Adjs` entries of a Levels or Curves filter: the composite first, then red, green, blue. -fn adjustments(p: &J, curves: bool) -> Result { - let obj = p.as_object().ok_or("parameters are not an object")?; - let allowed: &[&str] = - if curves { &["points", "red", "green", "blue", "pencil"] } else { &["inBlack", "inWhite", "gamma", "outBlack", "outWhite", "red", "green", "blue"] }; - if let Some(k) = obj.keys().find(|k| !is_meta(k) && !allowed.contains(&k.as_str())) { - return Err(format!("setting `{k}` has no PSD equivalent")); - } - let mut list = Vec::new(); - for (code, key) in CHANNELS { - let o = if key.is_empty() { Some(p) } else { p.get(key) }; - let Some(o) = o else { continue }; - let mut a = Descriptor::new(if curves { "CrvA" } else { "LvlA" }).with("Chnl", channel_ref(code)); - if curves { - let src = if key.is_empty() { p.get("points") } else { Some(o) }; - let Some(pts) = src.and_then(J::as_array) else { continue }; - if p.get("pencil").and_then(J::as_bool) == Some(true) { - let map: Option> = - pts.iter().map(|o| o.as_f64().filter(|o| o.is_finite()).map(|o| Value::Integer(o.round().clamp(0.0, 255.0) as i32))).collect(); - a = a.with("Mpng", Value::List(map.filter(|m| m.len() == 256).ok_or("a pencil-drawn curve is not 256 output levels")?)); - list.push(Value::Descriptor(a)); - continue; - } - let pts: Option> = pts - .iter() - .map(|q| { - let x = q.get(0)?.as_f64().filter(|v| v.is_finite())?; - let y = q.get(1)?.as_f64().filter(|v| v.is_finite())?; - Some(Value::Descriptor(Descriptor::new("Pnt ").with("Hrzn", Value::Double(x)).with("Vrtc", Value::Double(y)))) - }) - .collect(); - a = a.with("Crv ", Value::List(pts.ok_or("a curve point is not [input, output]")?)); - } else { - if key.is_empty() && !["inBlack", "inWhite", "gamma", "outBlack", "outWhite"].iter().any(|k| o.get(k).is_some()) { - continue; - } - a = a.with("Inpt", Value::List(vec![pi(o, "inBlack", 0.0), pi(o, "inWhite", 255.0)])).with("Gmm ", Value::Double(pf(o, "gamma", 1.0))); - if o.get("outBlack").is_some() || o.get("outWhite").is_some() { - a = a.with("Otpt", Value::List(vec![pi(o, "outBlack", 0.0), pi(o, "outWhite", 255.0)])); - } - } - list.push(Value::Descriptor(a)); - } - Ok(Value::List(list)) -} - -/// Crystallize's and Pointillize's cell size range (`ClSz`, a `long`). -const CELL_SIZE: (i32, i32) = (3, 300); - -/// Our `key` (a string) as Photoshop's enum value through `table` (Photoshop's value, ours). -fn enum_out(p: &J, key: &str, default: &str, type_id: &str, table: &[(&str, &str)]) -> Result { - let ours = match p.get(key) { - None => default, - Some(v) => v.as_str().ok_or_else(|| format!("`{key}` is not a string"))?, - }; - let (psd, _) = table.iter().find(|(_, o)| *o == ours).ok_or_else(|| format!("{key} `{ours}` has no PSD equivalent"))?; - Ok(enumv(type_id, psd)) -} - -/// `key` rounded to a `long` in `lo..=hi`. -fn pi_in(p: &J, key: &str, default: f64, lo: i32, hi: i32) -> Value { - Value::Integer(pf(p, key, default).round().clamp(f64::from(lo), f64::from(hi)) as i32) -} - -/// Param `key` as a `bool` (false when absent or not a bool, as the engine reads it). -fn bool_param(p: &J, key: &str) -> Value { - Value::Boolean(p.get(key).and_then(J::as_bool).unwrap_or(false)) -} - -/// The `Fltr` descriptor of a modelled filter (`None` = written without options). -fn fltr_for(k: &Known, p: &J) -> Result, String> { - let d = Descriptor::new(k.class); - Ok(Some(match k.class { - "GsnB" | "boxblur" | "Mdn " | "HghP" | "Mxm " | "Mnm " => { - if p.get("preserve").and_then(J::as_str).is_some_and(|s| s == "roundness") { - return Err("“preserve roundness” has no PSD equivalent".into()); - } - d.with("Rds ", unit(b"#Pxl", pf(p, "radius", 1.0))) - } - "MtnB" => d.with("Angl", pi(p, "angle", 0.0)).with("Dstn", unit(b"#Pxl", pf(p, "distance", 10.0))), - "UnsM" => d.with("Amnt", unit(b"#Prc", pf(p, "amount", 50.0))).with("Rds ", unit(b"#Pxl", pf(p, "radius", 1.0))).with("Thsh", pi(p, "threshold", 0.0)), - "AdNs" => { - let gauss = p.get("distribution").and_then(J::as_str) == Some("gaussian"); - d.with("Dstr", Value::Enumerated { type_id: Id::new("Dstr"), value: Id::new(if gauss { "Gsn " } else { "Unfr" }) }) - .with("Nose", unit(b"#Prc", pf(p, "amount", 12.5))) - .with("Mnch", Value::Boolean(p.get("monochromatic").and_then(J::as_bool).unwrap_or(false))) - .with("FlRs", pi(p, "seed", 0.0)) - } - "surfaceBlur" => d.with("Rds ", unit(b"#Pxl", pf_range(p, "radius", 5.0, 1.0, 100.0)?)).with("Thsh", pi_range(p, "threshold", 15.0, 2, 255)?), - "SmrB" => d - .with("Rds ", Value::Double(pf_range(p, "radius", 3.0, 0.1, 100.0)?)) - .with("Thsh", Value::Double(pf_range(p, "threshold", 25.0, 0.1, 100.0)?)) - .with("SmBQ", enum_param(p, "quality", "high", "SmBQ", &SMART_BLUR_QUALITY)?) - .with("SmBM", enum_param(p, "mode", "normal", "SmBM", &SMART_BLUR_MODE)?), - "RdlB" => { - // Photoshop wrote no centre key for a centred blur; an off-centre one is unmeasured. - for k in ["centerX", "centerY"] { - if (pf_range(p, k, 0.5, 0.0, 1.0)? - 0.5).abs() > 1e-9 { - return Err("an off-centre Radial Blur centre is not written to PSD".into()); - } - } - d.with("Amnt", pi_range(p, "amount", 10.0, 1, 100)?) - .with("BlrM", enum_param(p, "method", "spin", "BlrM", &RADIAL_METHOD)?) - .with("BlrQ", enum_param(p, "quality", "good", "BlrQ", &RADIAL_QUALITY)?) - } - "Msc " => d.with("ClSz", unit(b"#Pxl", pf(p, "cellSize", 10.0))), - // Photoshop's Mezzotint has no seed (it is random on every render), so `seed` is not saved. - "Mztn" => { - let t = p.get("type").and_then(J::as_str).unwrap_or("fineDots"); - let code = MEZZOTINT_TYPES.iter().find(|(_, k)| *k == t).map_or(b"FnDt", |(c, _)| *c); - d.with("MztT", Value::Enumerated { type_id: Id::new("MztT"), value: Id::Code(*code) }) - } - "ClrH" => { - // Longs within the dialog's ranges (what the engine accepts: radius 4..127, angles ±360). - let long = |key: &str, default: f64, lo: f64, hi: f64| Value::Integer(pf(p, key, default).round().clamp(lo, hi) as i32); - d.with("Rds ", long("maxRadius", 8.0, 4.0, 127.0)) - .with("Ang1", long("channel1", 108.0, -360.0, 360.0)) - .with("Ang2", long("channel2", 162.0, -360.0, 360.0)) - .with("Ang3", long("channel3", 90.0, -360.0, 360.0)) - .with("Ang4", long("channel4", 45.0, -360.0, 360.0)) - } - "Embs" => d.with("Angl", pi(p, "angle", 135.0)).with("Hght", pi(p, "height", 3.0)).with("Amnt", pi(p, "amount", 100.0)), - SMART_SHARPEN => { - // The engine's defaults and ranges (it clamps the same way when rendering). - d.with("useLegacy", Value::Boolean(false)) - .with("Amnt", unit(b"#Prc", pf(p, "amount", 100.0).clamp(1.0, 500.0))) - .with("Rds ", unit(b"#Pxl", pf(p, "radius", 1.0).clamp(0.1, 64.0))) - .with("noiseReduction", unit(b"#Prc", pf(p, "reduceNoise", 10.0).clamp(0.0, 100.0))) - .with("blur", enumv("blurType", "GsnB")) - } - // Photoshop stores whole pixels and levels. - "DstS" => { - let whole = |key: &str, default: f64, lo: f64, hi: f64| Value::Integer(pf(p, key, default).round().clamp(lo, hi) as i32); - d.with("Rds ", whole("radius", 1.0, 1.0, 500.0)).with("Thsh", whole("threshold", 0.0, 0.0, 255.0)) - } - // Photoshop stores no random seed for these: `seed` is ours only and is not written. - "Dfs " => d.with("Md ", enum_out(p, "mode", "normal", "DfsM", &DIFFUSE_MODES)?), - "TrcC" => d.with("Lvl ", pi_in(p, "level", 128.0, 0, 255)).with("Edg ", enum_out(p, "edge", "lower", "CntE", &TRACE_EDGES)?), - "Crst" => d.with("ClSz", pi_in(p, "cellSize", 10.0, CELL_SIZE.0, CELL_SIZE.1)), - "Pntl" => d.with("ClSz", pi_in(p, "cellSize", 5.0, CELL_SIZE.0, CELL_SIZE.1)), - // Photoshop stores no random seed for these: our `seed` is not written. - "Wnd " => { - d.with("WndM", enum_out(p, "method", "wind", "WndM", &WIND_METHODS)?).with("Drct", enum_out(p, "direction", "fromRight", "Drct", &WIND_DIRECTIONS)?) - } - "Extr" => d - .with("ExtT", enum_out(p, "type", "blocks", "ExtT", &EXTRUDE_TYPES)?) - .with("ExtS", pi_in(p, "size", 30.0, EXTRUDE_SIZE.0, EXTRUDE_SIZE.1)) - .with("ExtD", pi_in(p, "depth", 30.0, EXTRUDE_DEPTH.0, EXTRUDE_DEPTH.1)) - .with("ExtR", enum_out(p, "depthMode", "random", "ExtR", &EXTRUDE_DEPTHS)?) - .with("ExtF", bool_param(p, "solidFrontFaces")) - .with("ExtM", bool_param(p, "maskIncompleteBlocks")), - "Tls " => d - .with("TlNm", pi_in(p, "count", 10.0, TILE_COUNT.0, TILE_COUNT.1)) - .with("TlOf", pi_in(p, "maxOffset", 10.0, TILE_OFFSET.0, TILE_OFFSET.1)) - .with("FlCl", enum_out(p, "fill", "background", "FlCl", &TILE_FILLS)?), - "Ofst" => { - // As the engine reads it: anything but repeat / transparent wraps. - let ours = p.get("undefinedAreas").and_then(J::as_str).unwrap_or("wrap"); - let fill = OFFSET_FILL.iter().find(|(_, o)| *o == ours).map_or("Wrp ", |(psd, _)| *psd); - d.with("Hrzn", pi(p, "horizontal", 0.0)).with("Vrtc", pi(p, "vertical", 0.0)).with("Fl ", enumv("FlMd", fill)) - } - "Cstm" => { - // The engine's identity kernel when none is given; missing cells are 0. - let kernel = p.get("kernel").and_then(J::as_array); - let cell = |i: usize| match kernel { - Some(a) => a.get(i).and_then(J::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0), - None => f64::from(u8::from(i == 12)), - }; - let m = (0..25).map(|i| whole(cell(i), CUSTOM_CELL, "a kernel value")).collect::, _>>()?; - d.with("Scl ", whole(pf(p, "scale", 1.0), CUSTOM_SCALE, "Scale")?) - .with("Ofst", whole(pf(p, "offset", 0.0), CUSTOM_OFFSET, "Offset")?) - .with("Mtrx", Value::List(m)) - } - "LnsF" => { - let lens = p.get("lens").and_then(J::as_str).unwrap_or("zoom"); - let code = LENSES.iter().find(|(_, l)| *l == lens).ok_or_else(|| format!("lens `{lens}` has no PSD equivalent"))?.0; - let mut centre = Descriptor::new("Pnt ").with("Hrzn", Value::Double(pf(p, "centerX", 0.5))).with("Vrtc", Value::Double(pf(p, "centerY", 0.5))); - centre.name = UnicodeString::new_nul(""); - d.with("Brgh", pi(p, "brightness", 100.0)) - .with("FlrC", Value::Descriptor(centre)) - .with("Lns ", Value::Enumerated { type_id: Id::new("Lns "), value: Id::Code(*code) }) - } - "Fbrs" => d.with("Vrnc", pi(p, "variance", 16.0)).with("Strg", pi(p, "strength", 4.0)).with("RndS", seed_param(p)), - "Clds" | "DfrC" => d.with("FlRs", seed_param(p)), - "Lvls" => d.with("Adjs", adjustments(p, false)?), - "Crvs" => d.with("Adjs", adjustments(p, true)?), - "adaptCorrect" => { - if p.as_object().is_some_and(|o| o.keys().any(|k| !is_meta(k))) { - return Err("only default Shadows/Highlights settings are written to PSD".into()); - } - return Ok(None); - } - // No settings to write; any parameter keys an old record carries have no effect on the - // filter either, so nothing is lost. - c if NO_OPTIONS.contains(&c) => return Ok(None), - // Keys and order as Photoshop writes them. - "Pnch" => d.with("Amnt", pi(p, "amount", 50.0)), - "Twrl" => d.with("Angl", pi(p, "angle", 50.0)), - "Rple" => d.with("Amnt", pi(p, "amount", 100.0)).with("RplS", enum_param(p, "size", "medium", "RplS", &RIPPLE_SIZE)?), - "Sphr" => d.with("Amnt", pi(p, "amount", 100.0)).with("SphM", enum_param(p, "mode", "normal", "SphM", &SPHERIZE_MODE)?), - "Plr " => d.with("Cnvr", enum_param(p, "mode", "rectangularToPolar", "Cnvr", &POLAR_MODE)?), - "ZgZg" => { - d.with("Amnt", pi(p, "amount", 10.0)).with("NmbR", pi(p, "ridges", 5.0)).with("ZZTy", enum_param(p, "style", "pondRipples", "ZZTy", &ZIGZAG_STYLE)?) - } - "Wave" => { - // The seed the renderer draws with (engine `filters::seed`): a u32, else a legacy signed - // or fractional seed, rounded and saturated, as its bit pattern. - let seed = match p.get("seed").and_then(J::as_u64).and_then(|s| u32::try_from(s).ok()) { - Some(s) => Value::Integer(s as i32), - None => pi(p, "seed", 0.0), - }; - // The renderer draws at most MAX_WAVE_GENERATORS: write what PhotoCraft rendered, so - // Photoshop doesn't draw more generators than the user saw. - let generators = pf(p, "generators", 5.0).round().clamp(1.0, f64::from(photocraft_algo::MAX_WAVE_GENERATORS)) as i32; - d.with("Wvtp", enum_param(p, "type", "sine", "Wvtp", &WAVE_TYPE)?) - .with("NmbG", Value::Integer(generators)) - .with("WLMn", pi(p, "wavelengthMin", 10.0)) - .with("WLMx", pi(p, "wavelengthMax", 120.0)) - .with("AmMn", pi(p, "amplitudeMin", 5.0)) - .with("AmMx", pi(p, "amplitudeMax", 35.0)) - .with("SclH", Value::Integer(100)) - .with("SclV", Value::Integer(100)) - .with("UndA", enum_param(p, "undefinedAreas", "wrap", "UndA", &UNDEFINED_AREAS)?) - .with("RndS", seed) - } - "Invr" => return Ok(None), - _ => return Err("not a recognized filter".into()), - })) -} - -/// The `filterFXList` item for one smart filter, or why it can't be written. -pub fn item_for_filter(f: &SmartFilter) -> Result { - if f.command == camera_raw::COMMAND { - let mut d = camera_raw::export_item(&f.params)?; - set(&mut d, "blendOptions", blend_options(f)); - set(&mut d, "enab", Value::Boolean(f.visible)); - return Ok(d); - } - if f.command == displace::COMMAND { - let mut d = displace::export_item(&f.params)?; - set(&mut d, "blendOptions", blend_options(f)); - set(&mut d, "enab", Value::Boolean(f.visible)); - return Ok(d); - } - if f.command == GALLERY_COMMAND { - return gallery_item(f); - } - if f.command == hue_sat::COMMAND { - return hue_sat::export_item(f); - } - if perspective_warp::handles(&f.command) { - return perspective_warp::export_item(f); - } - if f.command == UNSUPPORTED_FILTER { - let raw = f.params.get("psd").and_then(J::as_str).and_then(from_hex).ok_or("its filter data is missing")?; - let mut d = Descriptor::from_bytes(&raw).map_err(|e| format!("its filter data is unreadable ({e})"))?; - set(&mut d, "blendOptions", blend_options(f)); - set(&mut d, "enab", Value::Boolean(f.visible)); - return Ok(d); - } - let k = known_by_command(&f.command).ok_or("this filter has no PSD equivalent")?; - let fltr = fltr_for(k, &f.params)?; - // Pointillize's background, Tiles' colours and the render filters' colours are the entry's; - // the others store Photoshop's defaults. - let (fg, bg) = match k.class { - "Pntl" => (rgbc(0.0), colour_rgbc(f.params.get("background"), 255.0)?), - "Tls " | "Fbrs" | "Clds" | "DfrC" => (colour_rgbc(f.params.get("foreground"), 0.0)?, colour_rgbc(f.params.get("background"), 255.0)?), - _ => (rgbc(0.0), rgbc(255.0)), - }; - // The render filters are written with the descriptor names Photoshop gives them: the filter's - // own name on `Fltr` and empty ones on the colours. - let render = matches!(k.class, "Fbrs" | "Clds" | "DfrC" | "LnsF"); - let (fltr, fg, bg) = if render { (fltr.map(|f| named(f, k.name.trim_end_matches("..."))), named_value(fg), named_value(bg)) } else { (fltr, fg, bg) }; - let mut d = Descriptor::new("filterFX") - .with("Nm ", Value::Text(UnicodeString::new_nul(k.name))) - .with("blendOptions", blend_options(f)) - .with("enab", Value::Boolean(f.visible)) - .with("hasoptions", Value::Boolean(fltr.is_some())) - .with("FrgC", fg) - .with("BckC", bg); - if let Some(x) = fltr { - d = d.with("Fltr", Value::Descriptor(x)); - } - Ok(d.with("filterID", Value::Integer(k.filter_id))) -} - -fn named(mut d: Descriptor, name: &str) -> Descriptor { - d.name = UnicodeString::new_nul(name); - d -} - -fn named_value(v: Value) -> Value { - match v { - Value::Descriptor(d) => Value::Descriptor(named(d, "")), - other => other, - } -} - -/// Builds a `filterFX` object; filters that can't be written are left out, with a message each. -pub fn filter_fx(stack: &FilterStack, layer: &str, warnings: &mut Vec) -> Descriptor { - let mut list = Vec::new(); - for f in &stack.filters { - match item_for_filter(f) { - Ok(d) => list.push(Value::Descriptor(d)), - Err(e) => warnings.push(format!("layer \"{layer}\": smart filter {} was not written to PSD: {e}", f.command)), - } - } - Descriptor::new("filterFXStyle") - .with("enab", Value::Boolean(stack.enabled)) - .with("validAtPosition", Value::Boolean(true)) - .with("filterMaskEnable", Value::Boolean(stack.mask_enabled)) - .with("filterMaskLinked", Value::Boolean(stack.mask_linked)) - .with("filterMaskExtendWithWhite", Value::Boolean(true)) - .with("filterFXList", Value::List(list)) -} - -/// Replaces item `key` in place, or appends it. -fn set(d: &mut Descriptor, key: &str, v: Value) { - match d.items.iter_mut().find(|(k, _)| k.is(key)) { - Some(e) => e.1 = v, - None => d.items.push((Id::new(key), v)), - } -} - -/// Replaces item `key` in place, or inserts it before item `before` (appends it without one). -fn set_before(d: &mut Descriptor, key: &str, v: Value, before: &str) { - if let Some(e) = d.items.iter_mut().find(|(k, _)| k.is(key)) { - e.1 = v; - return; - } - let at = d.items.iter().position(|(k, _)| k.is(before)).unwrap_or(d.items.len()); - d.items.insert(at, (Id::new(key), v)); -} - -/// Everything needed to write the placed-layer blocks of a smart object. -#[derive(Clone, Debug)] -pub struct PlacedSpec<'a> { - pub idnt: &'a str, - pub placed: &'a str, - /// Source pixels → document pixels. - pub transform: Affine, - /// Distort / Perspective: the full projective map (row-major 3×3), overriding `transform`. - pub perspective: Option<[f64; 9]>, - /// Source size in pixels. - pub size: (f64, f64), - /// Source resolution. - pub dpi: f64, - pub warp: Option<&'a Warp>, - /// `filterFX`, when the smart object has filters. - pub filter_fx: Option, -} - -/// Where the frame corners land (top-left, top-right, bottom-right, bottom-left), as x, y pairs. -/// The frame is [`crate::blocks::placed_frame`] of `warp`, the warp the block stores, for an -/// affine placement (the inverse of `parse_smart`), [`crate::blocks::perspective_frame`] of it -/// for a projective one (as `parse_smart_perspective` reads it). -fn quad_points(s: &PlacedSpec<'_>, warp: Option<&Warp>) -> [f64; 8] { - let (w, h) = s.size; - let [a, b, c, d, e, f] = s.transform.m; - let map = |x: f64, y: f64| match &s.perspective { - Some(p) => photocraft_algo::transform::Homography(*p).apply(x, y), - None => (a * x + c * y + e, b * x + d * y + f), - }; - let [x0, y0, x1, y1] = if s.perspective.is_some() { crate::blocks::perspective_frame(warp, w, h) } else { crate::blocks::placed_frame(warp, w, h) }; - let mut out = [0.0; 8]; - for (i, (x, y)) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].into_iter().enumerate() { - (out[2 * i], out[2 * i + 1]) = map(x, y); - } - out -} - -/// The transform quad: the source corners (top-left, top-right, bottom-right, bottom-left). -fn quad(s: &PlacedSpec<'_>, warp: Option<&Warp>) -> Value { - Value::List(quad_points(s, warp).into_iter().map(Value::Double).collect()) -} - -/// Has the placement moved from the quad a template descriptor stores (`Trnf`)? -fn quad_moved(template: &Descriptor, s: &PlacedSpec<'_>, warp: Option<&Warp>) -> bool { - let Some(Value::List(pts)) = template.get("Trnf") else { return true }; - let old: Vec = pts.iter().filter_map(|v| crate::blocks::num(Some(v))).collect(); - let new = quad_points(s, warp); - old.len() != 8 || old.iter().zip(new).any(|(a, b)| (a - b).abs() > 1e-6 * (1.0 + a.abs())) -} - -fn enumv(t: &str, v: &str) -> Value { - Value::Enumerated { type_id: Id::new(t), value: Id::new(v) } -} - -/// The mesh of a split warp: a custom warp of more than one patch, which `SoLd` stores as -/// `quiltWarp` and `PlLd` can't store. -fn split_mesh(w: Option<&Warp>) -> Option<&BezierMesh> { - w.filter(|w| w.style == WarpStyle::Custom).and_then(|w| w.mesh.as_ref()).filter(|m| m.points.len() != 16 && m.is_valid()) -} - -/// The warp `SoLd` stores: none, with a message, for a split warp of more patches along a side -/// than a `quiltWarp` is read with, so its corners are framed by the source rect as on reopen. -fn sold_warp<'a>(w: Option<&'a Warp>, warnings: &mut Vec) -> Option<&'a Warp> { - let too_big = split_mesh(w).is_some_and(|m| m.us.len().max(m.vs.len()) > crate::blocks::QUILT_MAX_PATCHES + 1); - if too_big { - warnings.push(format!("a split warp of more than {} patches along a side was written to PSD without its warp", crate::blocks::QUILT_MAX_PATCHES)); - return None; - } - w -} - -/// Style, bend, distortions, axis, bounds and order: the keys a `warp` and a `quiltWarp` -/// descriptor share, in Photoshop's order. -fn warp_head(class: &str, w: &Warp) -> Descriptor { - let [x0, y0, x1, y1] = w.bounds; - let bounds = Descriptor::new("classFloatRect") - .with("Top ", Value::Double(y0)) - .with("Left", Value::Double(x0)) - .with("Btom", Value::Double(y1)) - .with("Rght", Value::Double(x1)); - let d = Descriptor::new(class).with("warpStyle", enumv("warpStyle", w.style.psd_name())).with("warpValue", Value::Double(w.bend)); - // A cylinder is stored as its seven `warpValues` (#4112). - let d = if w.style == WarpStyle::Cylinder { d.with("warpValues", Value::List(w.values.iter().copied().map(Value::Double).collect())) } else { d }; - d.with("warpPerspective", Value::Double(w.h_distort)) - .with("warpPerspectiveOther", Value::Double(w.v_distort)) - .with("warpRotate", enumv("Ornt", if w.vertical { "Vrtc" } else { "Hrzn" })) - .with("bounds", Value::Descriptor(bounds)) - .with("uOrder", Value::Integer(4)) - .with("vOrder", Value::Integer(4)) -} - -/// The control points of a custom warp: an object array of their x and y. -fn mesh_points(m: &BezierMesh) -> Value { - let body = Descriptor::new("rationalPoint") - .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: m.points.iter().map(|p| p[0]).collect() }) - .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: m.points.iter().map(|p| p[1]).collect() }); - Value::ObjectArray(ObjectArray { prefix: m.points.len() as u32, body }) -} - -/// The `warp` descriptor (also the `PlLd` warp). A split warp is written as no warp: `SoLd` -/// keeps it in `quiltWarp` ([`quilt_desc`]), next to this `warpNone`, as Photoshop does. A -/// custom warp without a usable mesh is written as no warp, with a message. A cylinder is -/// written as its seven `warpValues`. -fn warp_desc(w: Option<&Warp>, size: (f64, f64), warnings: &mut Vec) -> Value { - let none = Warp::none([0.0, 0.0, size.0, size.1]); - let mut w = w.unwrap_or(&none).clone(); - let mesh = match (&w.style, &w.mesh) { - (WarpStyle::Custom, Some(m)) if m.points.len() == 16 => Some(m.clone()), - (WarpStyle::Custom, Some(m)) if m.is_valid() => { - w = none.clone(); - None - } - (WarpStyle::Custom, _) => { - warnings.push("a custom warp without a valid mesh was written to PSD without its warp".into()); - w = none.clone(); - None - } - _ => None, - }; - let mut d = warp_head("warp", &w); - if let Some(m) = mesh { - d = d.with("customEnvelopeWarp", Value::Descriptor(Descriptor::new("customEnvelopeWarp").with("meshPoints", mesh_points(&m)))); - } - Value::Descriptor(d) -} - -/// The `quiltWarp` descriptor of a split warp, in Photoshop's layout: `deformNumCols` × -/// `deformNumRows` control points, and the patch boundaries (`quiltSliceX` / `quiltSliceY`) at -/// the knots across the warp's box. The imported `quiltWarp` (`old`) gives its own slices where -/// they still bound the mesh's patches, so their units and padding stay Photoshop's. -fn quilt_desc(w: &Warp, mesh: &BezierMesh, old: Option<&Descriptor>) -> Value { - let old_env = old.and_then(|q| get_desc(q, "customEnvelopeWarp")); - let [x0, y0, x1, y1] = w.bounds; - let slices = |key: &str, knots: &[f64], lo: f64, hi: f64| { - if let Some(env) = old_env - && crate::blocks::quilt_knots(env, key, knots.len() - 1).as_deref() == Some(knots) - && let Some(v) = env.get(key) - { - return v.clone(); - } - let (lo, hi) = if (hi - lo).is_finite() && hi > lo { (lo, hi) } else { (0.0, 1.0) }; - let values: Vec = knots.iter().map(|u| lo + u * (hi - lo)).collect(); - let prefix = values.len() as u32; - Value::ObjectArray(ObjectArray { prefix, body: Descriptor::new("UntF").with(key, Value::UnitFloats { unit: *b"#Pxl", values }) }) - }; - let envelope = Descriptor::new("customEnvelopeWarp") - .with("quiltSliceX", slices("quiltSliceX", &mesh.us, x0, x1)) - .with("quiltSliceY", slices("quiltSliceY", &mesh.vs, y0, y1)) - .with("meshPoints", mesh_points(mesh)); - Value::Descriptor( - warp_head("quiltWarp", w) - .with("deformNumRows", Value::Integer(mesh.ny() as i32)) - .with("deformNumCols", Value::Integer(mesh.nx() as i32)) - .with("customEnvelopeWarp", Value::Descriptor(envelope)), - ) -} - -fn ratio(n: i32, d: i32) -> Value { - Value::Descriptor(Descriptor::new("null").with("numerator", Value::Integer(n)).with("denominator", Value::Integer(d))) -} - -fn pad4(mut v: Vec) -> Vec { - while !v.len().is_multiple_of(4) { - v.push(0); - } - v -} - -/// `SoLd` block data. With `template` (the imported descriptor) every key it has is kept and only -/// the placed id (for a duplicate), transform (when it moved), warp and filter stack are rewritten; -/// otherwise a fresh descriptor in Photoshop's key order. A split warp goes in `quiltWarp`. -pub fn sold_bytes(template: Option<&Descriptor>, s: &PlacedSpec<'_>, warnings: &mut Vec) -> Vec { - let stored = sold_warp(s.warp, warnings); - let warp = warp_desc(stored, s.size, warnings); - let split = stored.zip(split_mesh(stored)); - let d = match template { - Some(t) => { - let mut d = t.clone(); - if text_of(t, "placed").as_deref() != Some(s.placed) { - set(&mut d, "placed", Value::Text(UnicodeString::new_nul(s.placed))); - } - if quad_moved(t, s, stored) { - set(&mut d, "Trnf", quad(s, stored)); - set(&mut d, "nonAffineTransform", quad(s, stored)); - } - set(&mut d, "warp", warp); - // `quiltWarp` is read before `warp`, so the imported one stays only while it still - // says what the layer's warp is (unchanged, or unreadable while the layer has none); - // otherwise it is rewritten, or dropped for a warp that isn't split. - let old = get_desc(t, "quiltWarp"); - let kept = old.is_some_and(|q| match crate::blocks::warp_of(q) { - Some(w) => w.as_ref() == stored, - None => s.warp.is_none(), - }); - if !kept { - match split { - Some((w, m)) => set_before(&mut d, "quiltWarp", quilt_desc(w, m, old), "warp"), - None => d.items.retain(|(k, _)| !k.is("quiltWarp")), - } - } - match &s.filter_fx { - Some(fx) => set(&mut d, "filterFX", Value::Descriptor(fx.clone())), - None => d.items.retain(|(k, _)| !k.is("filterFX")), - } - d - } - None => { - let mut d = Descriptor::new("null") - .with("Idnt", Value::Text(UnicodeString::new_nul(s.idnt))) - .with("placed", Value::Text(UnicodeString::new_nul(s.placed))) - .with("PgNm", Value::Integer(1)) - .with("totalPages", Value::Integer(1)) - .with("Crop", Value::Integer(1)) - .with("frameStep", ratio(0, 600)) - .with("duration", ratio(0, 600)) - .with("frameCount", Value::Integer(1)) - .with("Annt", Value::Integer(16)) - .with("Type", Value::Integer(2)) - .with("Trnf", quad(s, stored)) - .with("nonAffineTransform", quad(s, stored)); - if let Some((w, m)) = split { - d = d.with("quiltWarp", quilt_desc(w, m, None)); - } - let mut d = d - .with("warp", warp) - .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(s.size.0)).with("Hght", Value::Double(s.size.1)))) - .with("Rslt", unit(b"#Rsl", s.dpi)); - if let Some(fx) = &s.filter_fx { - d = d.with("filterFX", Value::Descriptor(fx.clone())); - } - d.with("comp", Value::Integer(-1)) - .with("compInfo", Value::Descriptor(Descriptor::new("null").with("compID", Value::Integer(-1)).with("originalCompID", Value::Integer(-1)))) - } - }; - let mut out = b"soLD".to_vec(); - out.extend_from_slice(&4u32.to_be_bytes()); - out.extend(VersionedDescriptor::new(d).to_bytes()); - pad4(out) -} - -/// `PlLd` block data (`plcL` version 3): the legacy placed-layer record Photoshop writes next to -/// `SoLd`. It has no split warp: it stores none, its corners framed by the source rect. -pub fn plld_bytes(s: &PlacedSpec<'_>, warnings: &mut Vec) -> Vec { - let warp = s.warp.filter(|_| split_mesh(s.warp).is_none()); - let mut out = b"plcL".to_vec(); - out.extend_from_slice(&3u32.to_be_bytes()); - let id = s.idnt.as_bytes(); - let n = id.len().min(255); - out.push(n as u8); - out.extend_from_slice(&id[..n]); - for v in [1i32, 1, 16, 2] { - out.extend_from_slice(&v.to_be_bytes()); - } - if let Value::List(q) = quad(s, warp) { - for v in q { - if let Value::Double(x) = v { - out.extend_from_slice(&x.to_be_bytes()); - } - } - } - out.extend_from_slice(&0u32.to_be_bytes()); - let Value::Descriptor(w) = warp_desc(warp, s.size, warnings) else { return pad4(out) }; - out.extend(VersionedDescriptor::new(w).to_bytes()); - pad4(out) -} - -/// The source size a `soLD` descriptor stores (`Sz `). -pub fn stored_size(d: &Descriptor) -> Option<(f64, f64)> { - let sz = get_desc(d, "Sz ")?; - Some((num(sz.get("Wdth"))?, num(sz.get("Hght"))?)).filter(|(w, h)| *w > 0.0 && *h > 0.0) -} - // ---------- the filter mask (`FEid`) ---------- /// The filter mask stored in an `FEid` item, in document coordinates and white beyond its bounds diff --git a/crates/io/src/smart_map/export.rs b/crates/io/src/smart_map/export.rs new file mode 100644 index 0000000000..c8159201e4 --- /dev/null +++ b/crates/io/src/smart_map/export.rs @@ -0,0 +1,387 @@ +use super::import::{ + CHANNELS, CUSTOM_CELL, CUSTOM_OFFSET, CUSTOM_SCALE, DIFFUSE_MODES, EXTRUDE_DEPTH, EXTRUDE_DEPTHS, EXTRUDE_SIZE, EXTRUDE_TYPES, GALLERY_COMMAND, Known, + LENSES, MEZZOTINT_TYPES, NO_OPTIONS, OFFSET_FILL, POLAR_MODE, RADIAL_METHOD, RADIAL_QUALITY, RIPPLE_SIZE, SMART_BLUR_MODE, SMART_BLUR_QUALITY, + SMART_SHARPEN, SPHERIZE_MODE, TILE_COUNT, TILE_FILLS, TILE_OFFSET, TRACE_EDGES, UNDEFINED_AREAS, WAVE_TYPE, WIND_DIRECTIONS, WIND_METHODS, ZIGZAG_STYLE, + colour_rgbc, enum_param, from_hex, gallery_item, known_by_command, pf_range, pi_range, seed_param, +}; +use super::placed::enumv; +use super::*; + +// ---------- writing ---------- + +pub(crate) fn unit(u: &[u8; 4], v: f64) -> Value { + Value::UnitFloat { unit: *u, value: v } +} + +pub(crate) fn rgbc(v: f64) -> Value { + Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))) +} + +pub(crate) fn blend_options(f: &SmartFilter) -> Value { + let opacity = if f.opacity.is_finite() { f64::from(f.opacity.clamp(0.0, 1.0)) * 100.0 } else { 100.0 }; + Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", opacity)).with("Md ", crate::effects_map::blend_long_value(f.blend))) +} + +/// Parameter keys that are bookkeeping, not filter settings. +pub(crate) fn is_meta(k: &str) -> bool { + k == "layer" || k.starts_with("__") +} + +fn pf(p: &J, key: &str, default: f64) -> f64 { + p.get(key).and_then(J::as_f64).filter(|v| v.is_finite()).unwrap_or(default) +} + +pub(super) fn pi(p: &J, key: &str, default: f64) -> Value { + Value::Integer(pf(p, key, default).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32) +} + +/// A whole-number setting as a long, clamped to `range` like the engine clamps it; a fraction +/// has no PSD equivalent (Photoshop stores these as integers). +fn whole(v: f64, (lo, hi): (i32, i32), what: &str) -> Result { + if v.fract() != 0.0 { + return Err(format!("{what} ({v}) is not a whole number")); + } + Ok(Value::Integer(v.clamp(f64::from(lo), f64::from(hi)) as i32)) +} + +fn channel_ref(code: &[u8; 4]) -> Value { + Value::Reference(vec![ReferenceItem::Enumerated { + class: Class { name: UnicodeString::new_nul(""), class_id: Id::new("Chnl") }, + type_id: Id::new("Chnl"), + value: Id::Code(*code), + }]) +} + +/// The `Adjs` entries of a Levels or Curves filter: the composite first, then red, green, blue. +fn adjustments(p: &J, curves: bool) -> Result { + let obj = p.as_object().ok_or("parameters are not an object")?; + let allowed: &[&str] = + if curves { &["points", "red", "green", "blue", "pencil"] } else { &["inBlack", "inWhite", "gamma", "outBlack", "outWhite", "red", "green", "blue"] }; + if let Some(k) = obj.keys().find(|k| !is_meta(k) && !allowed.contains(&k.as_str())) { + return Err(format!("setting `{k}` has no PSD equivalent")); + } + let mut list = Vec::new(); + for (code, key) in CHANNELS { + let o = if key.is_empty() { Some(p) } else { p.get(key) }; + let Some(o) = o else { continue }; + let mut a = Descriptor::new(if curves { "CrvA" } else { "LvlA" }).with("Chnl", channel_ref(code)); + if curves { + let src = if key.is_empty() { p.get("points") } else { Some(o) }; + let Some(pts) = src.and_then(J::as_array) else { continue }; + if p.get("pencil").and_then(J::as_bool) == Some(true) { + let map: Option> = + pts.iter().map(|o| o.as_f64().filter(|o| o.is_finite()).map(|o| Value::Integer(o.round().clamp(0.0, 255.0) as i32))).collect(); + a = a.with("Mpng", Value::List(map.filter(|m| m.len() == 256).ok_or("a pencil-drawn curve is not 256 output levels")?)); + list.push(Value::Descriptor(a)); + continue; + } + let pts: Option> = pts + .iter() + .map(|q| { + let x = q.get(0)?.as_f64().filter(|v| v.is_finite())?; + let y = q.get(1)?.as_f64().filter(|v| v.is_finite())?; + Some(Value::Descriptor(Descriptor::new("Pnt ").with("Hrzn", Value::Double(x)).with("Vrtc", Value::Double(y)))) + }) + .collect(); + a = a.with("Crv ", Value::List(pts.ok_or("a curve point is not [input, output]")?)); + } else { + if key.is_empty() && !["inBlack", "inWhite", "gamma", "outBlack", "outWhite"].iter().any(|k| o.get(k).is_some()) { + continue; + } + a = a.with("Inpt", Value::List(vec![pi(o, "inBlack", 0.0), pi(o, "inWhite", 255.0)])).with("Gmm ", Value::Double(pf(o, "gamma", 1.0))); + if o.get("outBlack").is_some() || o.get("outWhite").is_some() { + a = a.with("Otpt", Value::List(vec![pi(o, "outBlack", 0.0), pi(o, "outWhite", 255.0)])); + } + } + list.push(Value::Descriptor(a)); + } + Ok(Value::List(list)) +} + +/// Crystallize's and Pointillize's cell size range (`ClSz`, a `long`). +pub(super) const CELL_SIZE: (i32, i32) = (3, 300); + +/// Our `key` (a string) as Photoshop's enum value through `table` (Photoshop's value, ours). +fn enum_out(p: &J, key: &str, default: &str, type_id: &str, table: &[(&str, &str)]) -> Result { + let ours = match p.get(key) { + None => default, + Some(v) => v.as_str().ok_or_else(|| format!("`{key}` is not a string"))?, + }; + let (psd, _) = table.iter().find(|(_, o)| *o == ours).ok_or_else(|| format!("{key} `{ours}` has no PSD equivalent"))?; + Ok(enumv(type_id, psd)) +} + +/// `key` rounded to a `long` in `lo..=hi`. +fn pi_in(p: &J, key: &str, default: f64, lo: i32, hi: i32) -> Value { + Value::Integer(pf(p, key, default).round().clamp(f64::from(lo), f64::from(hi)) as i32) +} + +/// Param `key` as a `bool` (false when absent or not a bool, as the engine reads it). +fn bool_param(p: &J, key: &str) -> Value { + Value::Boolean(p.get(key).and_then(J::as_bool).unwrap_or(false)) +} + +/// The `Fltr` descriptor of a modelled filter (`None` = written without options). +fn fltr_for(k: &Known, p: &J) -> Result, String> { + let d = Descriptor::new(k.class); + Ok(Some(match k.class { + "GsnB" | "boxblur" | "Mdn " | "HghP" | "Mxm " | "Mnm " => { + if p.get("preserve").and_then(J::as_str).is_some_and(|s| s == "roundness") { + return Err("“preserve roundness” has no PSD equivalent".into()); + } + d.with("Rds ", unit(b"#Pxl", pf(p, "radius", 1.0))) + } + "MtnB" => d.with("Angl", pi(p, "angle", 0.0)).with("Dstn", unit(b"#Pxl", pf(p, "distance", 10.0))), + "UnsM" => d.with("Amnt", unit(b"#Prc", pf(p, "amount", 50.0))).with("Rds ", unit(b"#Pxl", pf(p, "radius", 1.0))).with("Thsh", pi(p, "threshold", 0.0)), + "AdNs" => { + let gauss = p.get("distribution").and_then(J::as_str) == Some("gaussian"); + d.with("Dstr", Value::Enumerated { type_id: Id::new("Dstr"), value: Id::new(if gauss { "Gsn " } else { "Unfr" }) }) + .with("Nose", unit(b"#Prc", pf(p, "amount", 12.5))) + .with("Mnch", Value::Boolean(p.get("monochromatic").and_then(J::as_bool).unwrap_or(false))) + .with("FlRs", pi(p, "seed", 0.0)) + } + "surfaceBlur" => d.with("Rds ", unit(b"#Pxl", pf_range(p, "radius", 5.0, 1.0, 100.0)?)).with("Thsh", pi_range(p, "threshold", 15.0, 2, 255)?), + "SmrB" => d + .with("Rds ", Value::Double(pf_range(p, "radius", 3.0, 0.1, 100.0)?)) + .with("Thsh", Value::Double(pf_range(p, "threshold", 25.0, 0.1, 100.0)?)) + .with("SmBQ", enum_param(p, "quality", "high", "SmBQ", &SMART_BLUR_QUALITY)?) + .with("SmBM", enum_param(p, "mode", "normal", "SmBM", &SMART_BLUR_MODE)?), + "RdlB" => { + // Photoshop wrote no centre key for a centred blur; an off-centre one is unmeasured. + for k in ["centerX", "centerY"] { + if (pf_range(p, k, 0.5, 0.0, 1.0)? - 0.5).abs() > 1e-9 { + return Err("an off-centre Radial Blur centre is not written to PSD".into()); + } + } + d.with("Amnt", pi_range(p, "amount", 10.0, 1, 100)?) + .with("BlrM", enum_param(p, "method", "spin", "BlrM", &RADIAL_METHOD)?) + .with("BlrQ", enum_param(p, "quality", "good", "BlrQ", &RADIAL_QUALITY)?) + } + "Msc " => d.with("ClSz", unit(b"#Pxl", pf(p, "cellSize", 10.0))), + // Photoshop's Mezzotint has no seed (it is random on every render), so `seed` is not saved. + "Mztn" => { + let t = p.get("type").and_then(J::as_str).unwrap_or("fineDots"); + let code = MEZZOTINT_TYPES.iter().find(|(_, k)| *k == t).map_or(b"FnDt", |(c, _)| *c); + d.with("MztT", Value::Enumerated { type_id: Id::new("MztT"), value: Id::Code(*code) }) + } + "ClrH" => { + // Longs within the dialog's ranges (what the engine accepts: radius 4..127, angles ±360). + let long = |key: &str, default: f64, lo: f64, hi: f64| Value::Integer(pf(p, key, default).round().clamp(lo, hi) as i32); + d.with("Rds ", long("maxRadius", 8.0, 4.0, 127.0)) + .with("Ang1", long("channel1", 108.0, -360.0, 360.0)) + .with("Ang2", long("channel2", 162.0, -360.0, 360.0)) + .with("Ang3", long("channel3", 90.0, -360.0, 360.0)) + .with("Ang4", long("channel4", 45.0, -360.0, 360.0)) + } + "Embs" => d.with("Angl", pi(p, "angle", 135.0)).with("Hght", pi(p, "height", 3.0)).with("Amnt", pi(p, "amount", 100.0)), + SMART_SHARPEN => { + // The engine's defaults and ranges (it clamps the same way when rendering). + d.with("useLegacy", Value::Boolean(false)) + .with("Amnt", unit(b"#Prc", pf(p, "amount", 100.0).clamp(1.0, 500.0))) + .with("Rds ", unit(b"#Pxl", pf(p, "radius", 1.0).clamp(0.1, 64.0))) + .with("noiseReduction", unit(b"#Prc", pf(p, "reduceNoise", 10.0).clamp(0.0, 100.0))) + .with("blur", enumv("blurType", "GsnB")) + } + // Photoshop stores whole pixels and levels. + "DstS" => { + let whole = |key: &str, default: f64, lo: f64, hi: f64| Value::Integer(pf(p, key, default).round().clamp(lo, hi) as i32); + d.with("Rds ", whole("radius", 1.0, 1.0, 500.0)).with("Thsh", whole("threshold", 0.0, 0.0, 255.0)) + } + // Photoshop stores no random seed for these: `seed` is ours only and is not written. + "Dfs " => d.with("Md ", enum_out(p, "mode", "normal", "DfsM", &DIFFUSE_MODES)?), + "TrcC" => d.with("Lvl ", pi_in(p, "level", 128.0, 0, 255)).with("Edg ", enum_out(p, "edge", "lower", "CntE", &TRACE_EDGES)?), + "Crst" => d.with("ClSz", pi_in(p, "cellSize", 10.0, CELL_SIZE.0, CELL_SIZE.1)), + "Pntl" => d.with("ClSz", pi_in(p, "cellSize", 5.0, CELL_SIZE.0, CELL_SIZE.1)), + // Photoshop stores no random seed for these: our `seed` is not written. + "Wnd " => { + d.with("WndM", enum_out(p, "method", "wind", "WndM", &WIND_METHODS)?).with("Drct", enum_out(p, "direction", "fromRight", "Drct", &WIND_DIRECTIONS)?) + } + "Extr" => d + .with("ExtT", enum_out(p, "type", "blocks", "ExtT", &EXTRUDE_TYPES)?) + .with("ExtS", pi_in(p, "size", 30.0, EXTRUDE_SIZE.0, EXTRUDE_SIZE.1)) + .with("ExtD", pi_in(p, "depth", 30.0, EXTRUDE_DEPTH.0, EXTRUDE_DEPTH.1)) + .with("ExtR", enum_out(p, "depthMode", "random", "ExtR", &EXTRUDE_DEPTHS)?) + .with("ExtF", bool_param(p, "solidFrontFaces")) + .with("ExtM", bool_param(p, "maskIncompleteBlocks")), + "Tls " => d + .with("TlNm", pi_in(p, "count", 10.0, TILE_COUNT.0, TILE_COUNT.1)) + .with("TlOf", pi_in(p, "maxOffset", 10.0, TILE_OFFSET.0, TILE_OFFSET.1)) + .with("FlCl", enum_out(p, "fill", "background", "FlCl", &TILE_FILLS)?), + "Ofst" => { + // As the engine reads it: anything but repeat / transparent wraps. + let ours = p.get("undefinedAreas").and_then(J::as_str).unwrap_or("wrap"); + let fill = OFFSET_FILL.iter().find(|(_, o)| *o == ours).map_or("Wrp ", |(psd, _)| *psd); + d.with("Hrzn", pi(p, "horizontal", 0.0)).with("Vrtc", pi(p, "vertical", 0.0)).with("Fl ", enumv("FlMd", fill)) + } + "Cstm" => { + // The engine's identity kernel when none is given; missing cells are 0. + let kernel = p.get("kernel").and_then(J::as_array); + let cell = |i: usize| match kernel { + Some(a) => a.get(i).and_then(J::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0), + None => f64::from(u8::from(i == 12)), + }; + let m = (0..25).map(|i| whole(cell(i), CUSTOM_CELL, "a kernel value")).collect::, _>>()?; + d.with("Scl ", whole(pf(p, "scale", 1.0), CUSTOM_SCALE, "Scale")?) + .with("Ofst", whole(pf(p, "offset", 0.0), CUSTOM_OFFSET, "Offset")?) + .with("Mtrx", Value::List(m)) + } + "LnsF" => { + let lens = p.get("lens").and_then(J::as_str).unwrap_or("zoom"); + let code = LENSES.iter().find(|(_, l)| *l == lens).ok_or_else(|| format!("lens `{lens}` has no PSD equivalent"))?.0; + let mut centre = Descriptor::new("Pnt ").with("Hrzn", Value::Double(pf(p, "centerX", 0.5))).with("Vrtc", Value::Double(pf(p, "centerY", 0.5))); + centre.name = UnicodeString::new_nul(""); + d.with("Brgh", pi(p, "brightness", 100.0)) + .with("FlrC", Value::Descriptor(centre)) + .with("Lns ", Value::Enumerated { type_id: Id::new("Lns "), value: Id::Code(*code) }) + } + "Fbrs" => d.with("Vrnc", pi(p, "variance", 16.0)).with("Strg", pi(p, "strength", 4.0)).with("RndS", seed_param(p)), + "Clds" | "DfrC" => d.with("FlRs", seed_param(p)), + "Lvls" => d.with("Adjs", adjustments(p, false)?), + "Crvs" => d.with("Adjs", adjustments(p, true)?), + "adaptCorrect" => { + if p.as_object().is_some_and(|o| o.keys().any(|k| !is_meta(k))) { + return Err("only default Shadows/Highlights settings are written to PSD".into()); + } + return Ok(None); + } + // No settings to write; any parameter keys an old record carries have no effect on the + // filter either, so nothing is lost. + c if NO_OPTIONS.contains(&c) => return Ok(None), + // Keys and order as Photoshop writes them. + "Pnch" => d.with("Amnt", pi(p, "amount", 50.0)), + "Twrl" => d.with("Angl", pi(p, "angle", 50.0)), + "Rple" => d.with("Amnt", pi(p, "amount", 100.0)).with("RplS", enum_param(p, "size", "medium", "RplS", &RIPPLE_SIZE)?), + "Sphr" => d.with("Amnt", pi(p, "amount", 100.0)).with("SphM", enum_param(p, "mode", "normal", "SphM", &SPHERIZE_MODE)?), + "Plr " => d.with("Cnvr", enum_param(p, "mode", "rectangularToPolar", "Cnvr", &POLAR_MODE)?), + "ZgZg" => { + d.with("Amnt", pi(p, "amount", 10.0)).with("NmbR", pi(p, "ridges", 5.0)).with("ZZTy", enum_param(p, "style", "pondRipples", "ZZTy", &ZIGZAG_STYLE)?) + } + "Wave" => { + // The seed the renderer draws with (engine `filters::seed`): a u32, else a legacy signed + // or fractional seed, rounded and saturated, as its bit pattern. + let seed = match p.get("seed").and_then(J::as_u64).and_then(|s| u32::try_from(s).ok()) { + Some(s) => Value::Integer(s as i32), + None => pi(p, "seed", 0.0), + }; + // The renderer draws at most MAX_WAVE_GENERATORS: write what PhotoCraft rendered, so + // Photoshop doesn't draw more generators than the user saw. + let generators = pf(p, "generators", 5.0).round().clamp(1.0, f64::from(photocraft_algo::MAX_WAVE_GENERATORS)) as i32; + d.with("Wvtp", enum_param(p, "type", "sine", "Wvtp", &WAVE_TYPE)?) + .with("NmbG", Value::Integer(generators)) + .with("WLMn", pi(p, "wavelengthMin", 10.0)) + .with("WLMx", pi(p, "wavelengthMax", 120.0)) + .with("AmMn", pi(p, "amplitudeMin", 5.0)) + .with("AmMx", pi(p, "amplitudeMax", 35.0)) + .with("SclH", Value::Integer(100)) + .with("SclV", Value::Integer(100)) + .with("UndA", enum_param(p, "undefinedAreas", "wrap", "UndA", &UNDEFINED_AREAS)?) + .with("RndS", seed) + } + "Invr" => return Ok(None), + _ => return Err("not a recognized filter".into()), + })) +} + +/// The `filterFXList` item for one smart filter, or why it can't be written. +pub fn item_for_filter(f: &SmartFilter) -> Result { + if f.command == camera_raw::COMMAND { + let mut d = camera_raw::export_item(&f.params)?; + set(&mut d, "blendOptions", blend_options(f)); + set(&mut d, "enab", Value::Boolean(f.visible)); + return Ok(d); + } + if f.command == displace::COMMAND { + let mut d = displace::export_item(&f.params)?; + set(&mut d, "blendOptions", blend_options(f)); + set(&mut d, "enab", Value::Boolean(f.visible)); + return Ok(d); + } + if f.command == GALLERY_COMMAND { + return gallery_item(f); + } + if f.command == hue_sat::COMMAND { + return hue_sat::export_item(f); + } + if perspective_warp::handles(&f.command) { + return perspective_warp::export_item(f); + } + if f.command == UNSUPPORTED_FILTER { + let raw = f.params.get("psd").and_then(J::as_str).and_then(from_hex).ok_or("its filter data is missing")?; + let mut d = Descriptor::from_bytes(&raw).map_err(|e| format!("its filter data is unreadable ({e})"))?; + set(&mut d, "blendOptions", blend_options(f)); + set(&mut d, "enab", Value::Boolean(f.visible)); + return Ok(d); + } + let k = known_by_command(&f.command).ok_or("this filter has no PSD equivalent")?; + let fltr = fltr_for(k, &f.params)?; + // Pointillize's background, Tiles' colours and the render filters' colours are the entry's; + // the others store Photoshop's defaults. + let (fg, bg) = match k.class { + "Pntl" => (rgbc(0.0), colour_rgbc(f.params.get("background"), 255.0)?), + "Tls " | "Fbrs" | "Clds" | "DfrC" => (colour_rgbc(f.params.get("foreground"), 0.0)?, colour_rgbc(f.params.get("background"), 255.0)?), + _ => (rgbc(0.0), rgbc(255.0)), + }; + // The render filters are written with the descriptor names Photoshop gives them: the filter's + // own name on `Fltr` and empty ones on the colours. + let render = matches!(k.class, "Fbrs" | "Clds" | "DfrC" | "LnsF"); + let (fltr, fg, bg) = if render { (fltr.map(|f| named(f, k.name.trim_end_matches("..."))), named_value(fg), named_value(bg)) } else { (fltr, fg, bg) }; + let mut d = Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul(k.name))) + .with("blendOptions", blend_options(f)) + .with("enab", Value::Boolean(f.visible)) + .with("hasoptions", Value::Boolean(fltr.is_some())) + .with("FrgC", fg) + .with("BckC", bg); + if let Some(x) = fltr { + d = d.with("Fltr", Value::Descriptor(x)); + } + Ok(d.with("filterID", Value::Integer(k.filter_id))) +} + +fn named(mut d: Descriptor, name: &str) -> Descriptor { + d.name = UnicodeString::new_nul(name); + d +} + +fn named_value(v: Value) -> Value { + match v { + Value::Descriptor(d) => Value::Descriptor(named(d, "")), + other => other, + } +} + +/// Builds a `filterFX` object; filters that can't be written are left out, with a message each. +pub fn filter_fx(stack: &FilterStack, layer: &str, warnings: &mut Vec) -> Descriptor { + let mut list = Vec::new(); + for f in &stack.filters { + match item_for_filter(f) { + Ok(d) => list.push(Value::Descriptor(d)), + Err(e) => warnings.push(format!("layer \"{layer}\": smart filter {} was not written to PSD: {e}", f.command)), + } + } + Descriptor::new("filterFXStyle") + .with("enab", Value::Boolean(stack.enabled)) + .with("validAtPosition", Value::Boolean(true)) + .with("filterMaskEnable", Value::Boolean(stack.mask_enabled)) + .with("filterMaskLinked", Value::Boolean(stack.mask_linked)) + .with("filterMaskExtendWithWhite", Value::Boolean(true)) + .with("filterFXList", Value::List(list)) +} + +/// Replaces item `key` in place, or appends it. +pub(crate) fn set(d: &mut Descriptor, key: &str, v: Value) { + match d.items.iter_mut().find(|(k, _)| k.is(key)) { + Some(e) => e.1 = v, + None => d.items.push((Id::new(key), v)), + } +} + +/// Replaces item `key` in place, or inserts it before item `before` (appends it without one). +pub(super) fn set_before(d: &mut Descriptor, key: &str, v: Value, before: &str) { + if let Some(e) = d.items.iter_mut().find(|(k, _)| k.is(key)) { + e.1 = v; + return; + } + let at = d.items.iter().position(|(k, _)| k.is(before)).unwrap_or(d.items.len()); + d.items.insert(at, (Id::new(key), v)); +} diff --git a/crates/io/src/smart_map/import.rs b/crates/io/src/smart_map/import.rs new file mode 100644 index 0000000000..341d1d533e --- /dev/null +++ b/crates/io/src/smart_map/import.rs @@ -0,0 +1,826 @@ +use super::export::{CELL_SIZE, blend_options, is_meta, pi, rgbc}; +use super::placed::enumv; +use super::*; + +// ---------- the filters we model ---------- + +/// Photoshop filter → PhotoCraft command, keyed by the `Fltr` class (and `filterID`). +pub(super) struct Known { + pub(super) class: &'static str, + pub(super) filter_id: i32, + /// `Nm ` as Photoshop writes it (the menu item, with its ellipsis and mnemonic). + pub(super) name: &'static str, + command: &'static str, +} + +/// A four-character PSD code as the big-endian integer Photoshop stores it as. +pub(crate) const fn code(c: &[u8; 4]) -> i32 { + i32::from_be_bytes(*c) +} + +const KNOWN: [Known; 53] = [ + Known { class: "GsnB", filter_id: code(b"GsnB"), name: "Gaussian Blur...", command: "filter.blur.gaussianBlur" }, + Known { class: "boxblur", filter_id: 840, name: "Box Blur...", command: "filter.blur.boxBlur" }, + Known { class: "MtnB", filter_id: code(b"MtnB"), name: "Motion Blur...", command: "filter.blur.motionBlur" }, + // Surface Blur, Smart Blur and Radial Blur: keys, value types and enums measured in Photoshop. + Known { class: "surfaceBlur", filter_id: 1135, name: "Surface Blur...", command: "filter.blur.surfaceBlur" }, + Known { class: "SmrB", filter_id: code(b"SmrB"), name: "Smart Blur...", command: "filter.blur.smartBlur" }, + // Radial Blur at its defaults stores no `Fltr` (`hasoptions` false); that entry is kept verbatim. + Known { class: "RdlB", filter_id: code(b"RdlB"), name: "Radial Blur...", command: "filter.blur.radialBlur" }, + Known { class: "UnsM", filter_id: code(b"UnsM"), name: "Unsharp Mask...", command: "filter.sharpen.unsharpMask" }, + Known { class: "AdNs", filter_id: code(b"AdNs"), name: "Add Noise...", command: "filter.noise.addNoise" }, + Known { class: "Mdn ", filter_id: code(b"Mdn "), name: "Median...", command: "filter.noise.median" }, + Known { class: "HghP", filter_id: code(b"HghP"), name: "High Pass...", command: "filter.other.highPass" }, + Known { class: "Mxm ", filter_id: code(b"Mxm "), name: "Maximum...", command: "filter.other.maximum" }, + Known { class: "Mnm ", filter_id: code(b"Mnm "), name: "Minimum...", command: "filter.other.minimum" }, + Known { class: "Ofst", filter_id: code(b"Ofst"), name: "Offset...", command: "filter.other.offset" }, + Known { class: "Cstm", filter_id: code(b"Cstm"), name: "Custom...", command: "filter.other.custom" }, + Known { class: "Msc ", filter_id: code(b"Msc "), name: "Mosaic...", command: "filter.pixelate.mosaic" }, + Known { class: "Mztn", filter_id: code(b"Mztn"), name: "Mezzotint...", command: "filter.pixelate.mezzotint" }, + Known { class: "ClrH", filter_id: code(b"ClrH"), name: "Color Halftone...", command: "filter.pixelate.colorHalftone" }, + Known { class: "Embs", filter_id: code(b"Embs"), name: "Emboss...", command: "filter.stylize.emboss" }, + Known { class: "Dfs ", filter_id: code(b"Dfs "), name: "Diffuse...", command: "filter.stylize.diffuse" }, + Known { class: "TrcC", filter_id: code(b"TrcC"), name: "Trace Contour...", command: "filter.stylize.traceContour" }, + Known { class: "Crst", filter_id: code(b"Crst"), name: "Crystallize...", command: "filter.pixelate.crystallize" }, + Known { class: "Pntl", filter_id: code(b"Pntl"), name: "Pointillize...", command: "filter.pixelate.pointillize" }, + Known { class: "Wnd ", filter_id: code(b"Wnd "), name: "Wind...", command: "filter.stylize.wind" }, + Known { class: "Extr", filter_id: code(b"Extr"), name: "Extrude...", command: "filter.stylize.extrude" }, + Known { class: "Tls ", filter_id: code(b"Tls "), name: "Tiles...", command: "filter.stylize.tiles" }, + Known { class: "Lvls", filter_id: code(b"Lvls"), name: "Levels...", command: "image.adjustments.levels" }, + Known { class: "Crvs", filter_id: code(b"Crvs"), name: "Curves...", command: "image.adjustments.curves" }, + // Shadows/Highlights at its defaults stores no `Fltr` (`hasoptions` false). + Known { class: "adaptCorrect", filter_id: 781, name: "Shado&ws/Highlights...", command: "image.adjustments.shadowsHighlights" }, + // Filters without options (measured in Photoshop): `hasoptions` false, no `Fltr`, only the + // four-char `filterID`. The class is that code; see `NO_OPTIONS`. + Known { class: "Blr ", filter_id: code(b"Blr "), name: "Blur", command: "filter.blur.blur" }, + Known { class: "BlrM", filter_id: code(b"BlrM"), name: "Blur More", command: "filter.blur.blurMore" }, + Known { class: "Avrg", filter_id: code(b"Avrg"), name: "Average", command: "filter.blur.average" }, + Known { class: "Dspc", filter_id: code(b"Dspc"), name: "Despeckle", command: "filter.noise.despeckle" }, + Known { class: "FndE", filter_id: code(b"FndE"), name: "Find Edges", command: "filter.stylize.findEdges" }, + Known { class: "Fct ", filter_id: code(b"Fct "), name: "Facet", command: "filter.pixelate.facet" }, + Known { class: "Frgm", filter_id: code(b"Frgm"), name: "Fragment", command: "filter.pixelate.fragment" }, + Known { class: "Shrp", filter_id: code(b"Shrp"), name: "Sharpen", command: "filter.sharpen.sharpen" }, + Known { class: "ShrM", filter_id: code(b"ShrM"), name: "Sharpen More", command: "filter.sharpen.sharpenMore" }, + Known { class: "ShrE", filter_id: code(b"ShrE"), name: "Sharpen Edges", command: "filter.sharpen.sharpenEdges" }, + Known { class: "Slrz", filter_id: code(b"Slrz"), name: "Solarize", command: "filter.stylize.solarize" }, + // Smart Sharpen has a numeric filterID and a stringID class, like Box Blur. + Known { class: SMART_SHARPEN, filter_id: 1131, name: "Smart Sharpen...", command: "filter.sharpen.smartSharpen" }, + Known { class: "DstS", filter_id: code(b"DstS"), name: "Dust & Scratches...", command: "filter.noise.dustAndScratches" }, + // Distort (Photoshop 27, `corpus`-style check: one smart object per filter saved from Photoshop + // and read back). Shear isn't mapped yet: its curve lives on Photoshop's own grid. + Known { class: "Pnch", filter_id: code(b"Pnch"), name: "Pinch...", command: "filter.distort.pinch" }, + Known { class: "Plr ", filter_id: code(b"Plr "), name: "Polar Coordinates...", command: "filter.distort.polarCoordinates" }, + Known { class: "Rple", filter_id: code(b"Rple"), name: "Ripple...", command: "filter.distort.ripple" }, + Known { class: "Sphr", filter_id: code(b"Sphr"), name: "Spherize...", command: "filter.distort.spherize" }, + Known { class: "Twrl", filter_id: code(b"Twrl"), name: "Twirl...", command: "filter.distort.twirl" }, + Known { class: "Wave", filter_id: code(b"Wave"), name: "Wave...", command: "filter.distort.wave" }, + Known { class: "ZgZg", filter_id: code(b"ZgZg"), name: "ZigZag...", command: "filter.distort.zigZag" }, + // Image › Adjustments › Invert on a smart object: no settings, so no `Fltr` (`hasoptions` false). + Known { class: "Invr", filter_id: code(b"Invr"), name: "Invert", command: "image.adjustments.invert" }, + Known { class: "LnsF", filter_id: code(b"LnsF"), name: "Lens Flare...", command: "filter.render.lensFlare" }, + // These three also read the item's foreground and background colours (`coloured_params`). + Known { class: "Fbrs", filter_id: code(b"Fbrs"), name: "Fibers...", command: "filter.render.fibers" }, + Known { class: "Clds", filter_id: code(b"Clds"), name: "Clouds", command: "filter.render.clouds" }, + Known { class: "DfrC", filter_id: code(b"DfrC"), name: "Difference Clouds", command: "filter.render.differenceClouds" }, +]; + +/// Lens Flare's `Lns ` enum and our `lens` values. Photoshop's codes keep the old lens names: +/// Nikon 35 mm and 105 mm primes, a Panavision movie prime. +pub(super) const LENSES: [(&[u8; 4], &str); 4] = [(b"Zm ", "zoom"), (b"Nkn ", "prime35"), (b"Nkn1", "prime105"), (b"PnVs", "moviePrime")]; + +/// Classes of the filters that have no options: Photoshop stores them without a `Fltr`. +pub(super) const NO_OPTIONS: [&str; 11] = ["Blr ", "BlrM", "Avrg", "Dspc", "FndE", "Fct ", "Frgm", "Shrp", "ShrM", "ShrE", "Slrz"]; + +// ---------- Smart Sharpen and Dust & Scratches ---------- +// +// Measured in Photoshop (applied through Action Manager to a smart object, saved, `filterFX` read +// back): +// +// ```text +// Smart Sharpen (filterID 1131): smartSharpen { presetKind = presetKindType enum (only on the +// default entry), useLegacy bool, Amnt UntF #Prc, Rds UntF #Pxl, noiseReduction UntF #Prc, +// blur = blurType enum (GsnB | lensBlur | MtnB), Angl long (Motion Blur only) } +// Dust & Scratches (filterID DstS): DstS { Rds long, Thsh long } +// ``` +// +// PhotoCraft's Smart Sharpen removes a Gaussian blur, non-legacy: Lens Blur, Motion Blur, legacy +// mode, Shadow/Highlight settings or any other key keep the whole entry verbatim. `presetKind` +// only names the dialog's preset: it is accepted on open but not kept (the engine takes no such +// parameter) and not written (Photoshop leaves it out of entries with explicit values). + +pub(super) const SMART_SHARPEN: &str = "smartSharpen"; + +const SMART_SHARPEN_KEYS: [&str; 6] = ["presetKind", "useLegacy", "Amnt", "Rds ", "noiseReduction", "blur"]; + +/// A `UntF` value in `unit`, finite and within `lo..=hi`. +fn unit_in(d: &Descriptor, key: &str, u: &[u8; 4], lo: f64, hi: f64) -> Option { + match d.get(key)? { + Value::UnitFloat { unit, value } if unit == u && value.is_finite() && (lo..=hi).contains(value) => Some(*value), + _ => None, + } +} + +/// `filter.sharpen.smartSharpen` params; `None` for a setting PhotoCraft doesn't render. +fn smart_sharpen_params(f: &Descriptor) -> Option { + if f.items.iter().any(|(k, _)| !SMART_SHARPEN_KEYS.iter().any(|x| k.is(x))) { + return None; + } + let Some(Value::Boolean(false)) = f.get("useLegacy") else { return None }; + let Some(Value::Enumerated { type_id, value }) = f.get("blur") else { return None }; + if !type_id.is("blurType") || !value.is("GsnB") { + return None; + } + let mut out = Map::new(); + out.insert("amount".into(), json!(unit_in(f, "Amnt", b"#Prc", 1.0, 500.0)?)); + out.insert("radius".into(), json!(unit_in(f, "Rds ", b"#Pxl", 0.1, 64.0)?)); + out.insert("reduceNoise".into(), json!(unit_in(f, "noiseReduction", b"#Prc", 0.0, 100.0)?)); + match f.get("presetKind") { + None => {} + Some(Value::Enumerated { type_id, .. }) if type_id.is("presetKindType") => {} + Some(_) => return None, + } + Some(J::Object(out)) +} + +/// Photoshop enum codes ↔ PhotoCraft parameter values, per filter setting. +pub(super) const RIPPLE_SIZE: [(&[u8; 4], &str); 3] = [(b"Sml ", "small"), (b"Mdm ", "medium"), (b"Lrg ", "large")]; + +pub(super) const SPHERIZE_MODE: [(&[u8; 4], &str); 3] = [(b"Nrml", "normal"), (b"HrzO", "horizontalOnly"), (b"VrtO", "verticalOnly")]; + +pub(super) const POLAR_MODE: [(&[u8; 4], &str); 2] = [(b"RctP", "rectangularToPolar"), (b"PlrR", "polarToRectangular")]; + +pub(super) const ZIGZAG_STYLE: [(&[u8; 4], &str); 3] = [(b"PndR", "pondRipples"), (b"OtFr", "outFromCenter"), (b"ArnC", "aroundCenter")]; + +pub(super) const WAVE_TYPE: [(&[u8; 4], &str); 3] = [(b"WvSn", "sine"), (b"WvTr", "triangle"), (b"WvSq", "square")]; + +pub(super) const UNDEFINED_AREAS: [(&[u8; 4], &str); 2] = [(b"WrpA", "wrap"), (b"RptE", "repeat")]; + +/// The PSD filter record that PhotoCraft's `command` is written as, if it has one. +pub(super) fn known_by_command(command: &str) -> Option<&'static Known> { + KNOWN.iter().find(|k| k.command == command) +} + +/// RGB channel references in Levels/Curves (`Chnl` enum) and their parameter keys ("" = the +/// composite: top-level keys). +pub(super) const CHANNELS: [(&[u8; 4], &str); 4] = [(b"Cmps", ""), (b"Rd ", "red"), (b"Grn ", "green"), (b"Bl ", "blue")]; + +/// Mezzotint's `MztT` enum codes and our `type` values (measured in Photoshop by rendering each). +pub(super) const MEZZOTINT_TYPES: [(&[u8; 4], &str); 10] = [ + (b"FnDt", "fineDots"), + (b"MdmD", "mediumDots"), + (b"GrnD", "grainyDots"), + (b"CrsD", "coarseDots"), + (b"ShrL", "shortLines"), + (b"MdmL", "mediumLines"), + (b"LngL", "longLines"), + (b"ShSt", "shortStrokes"), + (b"MdmS", "mediumStrokes"), + (b"LngS", "longStrokes"), +]; + +/// Color Halftone's `Rds ` (max radius) and `Ang1`..`Ang4` (screen angles) longs, read within +/// the dialog's ranges; anything else is kept verbatim. +fn color_halftone_params(f: &Descriptor) -> Option { + if !only_keys(f, &["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"]) { + return None; + } + let radius = int(f, "Rds ").filter(|r| (4..=127).contains(r))?; + let angle = |k: &str| int(f, k).filter(|a| (-360..=360).contains(a)); + Some(json!({"maxRadius": radius, "channel1": angle("Ang1")?, "channel2": angle("Ang2")?, "channel3": angle("Ang3")?, "channel4": angle("Ang4")?})) +} + +/// A numeric descriptor item as a finite number; `None` when it is absent, not a number, or not finite. +fn px(d: &Descriptor, key: &str) -> Option { + num(d.get(key)).filter(|v| v.is_finite()) +} + +/// An integer descriptor item; `None` when it is absent or of another type. +pub(crate) fn int(d: &Descriptor, key: &str) -> Option { + match d.get(key)? { + Value::Integer(i) => Some(*i), + _ => None, + } +} + +/// `v` when it lies in `lo..=hi` (the filter dialog's range); out-of-range settings are not +/// opened as editable filters, so a re-save keeps Photoshop's value instead of a clamped one. +fn in_range(v: f64, lo: f64, hi: f64) -> Option { + (lo..=hi).contains(&v).then_some(v) +} + +/// Integer `key` of `f` when it lies in `lo..=hi`. +fn int_in(f: &Descriptor, key: &str, lo: i32, hi: i32) -> Option { + int(f, key).filter(|v| (lo..=hi).contains(v)) +} + +/// True when `f` holds only the given keys, each at most once. A filter with a setting we don't +/// know about (Radial Blur's off-centre centre, for one) or a repeated one is kept verbatim rather +/// than losing that setting. +fn only_keys(f: &Descriptor, keys: &[&str]) -> bool { + f.items.iter().all(|(k, _)| keys.iter().any(|x| k.is(x))) && keys.iter().all(|key| f.items.iter().filter(|(k, _)| k.is(key)).count() <= 1) +} + +/// Our name for enum `key`'s value in `f` (of enum type `type_id`), from `(PSD value, our name)` +/// pairs. An enum of another type is not one we know, so the filter stays verbatim. +fn enum_name(f: &Descriptor, key: &str, type_id: &str, table: &[(&[u8; 4], &'static str)]) -> Option<&'static str> { + let Some(Value::Enumerated { type_id: t, value }) = f.get(key) else { return None }; + if t.as_bytes() != type_id.as_bytes() { + return None; + } + table.iter().find(|(c, _)| value.as_bytes() == &c[..]).map(|(_, n)| *n) +} + +/// True when `f` holds each of the given keys once and nothing else. +fn exact_keys(f: &Descriptor, keys: &[&str]) -> bool { + only_keys(f, keys) && keys.iter().all(|x| f.items.iter().any(|(k, _)| k.is(x))) +} + +/// Finite `key` of `f` stored as a plain double (the type Photoshop writes and we write back). +fn double(f: &Descriptor, key: &str) -> Option { + match f.get(key)? { + Value::Double(v) if v.is_finite() => Some(*v), + _ => None, + } +} + +/// `p[key]` (`default` when absent) when it is a number in `lo..=hi`, the range the filter opens +/// with; anything else is an error, so a saved filter always opens as the same editable filter. +pub(super) fn pf_range(p: &J, key: &str, default: f64, lo: f64, hi: f64) -> Result { + match p.get(key) { + None | Some(J::Null) => Ok(default), + Some(v) => v.as_f64().filter(|x| (lo..=hi).contains(x)).ok_or_else(|| format!("setting `{key}` ({v}) is not a number in {lo}..={hi}")), + } +} + +/// Integer `p[key]` (rounded; `default` when absent) in `lo..=hi`, as a PSD long. +pub(super) fn pi_range(p: &J, key: &str, default: f64, lo: i32, hi: i32) -> Result { + let v = pf_range(p, key, default, f64::from(i32::MIN), f64::from(i32::MAX))?.round(); + let range = f64::from(lo)..=f64::from(hi); + if !range.contains(&v) { + return Err(format!("setting `{key}` ({v}) is not a number in {lo}..={hi}")); + } + Ok(Value::Integer(v as i32)) +} + +/// Enum `type_id` holding the PSD value of our name `p[key]` (`default` when absent). +pub(super) fn enum_param(p: &J, key: &str, default: &str, type_id: &str, table: &[(&[u8; 4], &'static str)]) -> Result { + let name = match p.get(key) { + None | Some(J::Null) => default, + Some(v) => v.as_str().ok_or_else(|| format!("setting `{key}` is not text"))?, + }; + let code = table.iter().find(|(_, n)| *n == name).map(|(c, _)| **c).ok_or_else(|| format!("{key} `{name}` has no PSD equivalent"))?; + Ok(Value::Enumerated { type_id: Id::new(type_id), value: Id::Code(code) }) +} + +/// Smart Blur `SmBQ` / `SmBM` and Radial Blur `BlrM` / `BlrQ` values (measured in Photoshop). +pub(super) const SMART_BLUR_QUALITY: [(&[u8; 4], &str); 3] = [(b"SBQL", "low"), (b"SBQM", "medium"), (b"SBQH", "high")]; + +pub(super) const SMART_BLUR_MODE: [(&[u8; 4], &str); 3] = [(b"SBMN", "normal"), (b"SBME", "edgeOnly"), (b"SBMO", "overlayEdge")]; + +pub(super) const RADIAL_METHOD: [(&[u8; 4], &str); 2] = [(b"Spn ", "spin"), (b"Zm ", "zoom")]; + +pub(super) const RADIAL_QUALITY: [(&[u8; 4], &str); 3] = [(b"Drft", "draft"), (b"Gd ", "good"), (b"Bst ", "best")]; + +fn channel_key(d: &Descriptor) -> Option<&'static str> { + let Some(Value::Reference(items)) = d.get("Chnl") else { return None }; + let Some(ReferenceItem::Enumerated { value, .. }) = items.first() else { return None }; + CHANNELS.iter().find(|(c, _)| value.as_bytes() == &c[..]).map(|(_, k)| *k) +} + +pub(super) fn adjustment_list(d: &Descriptor) -> Option> { + let Some(Value::List(items)) = d.get("Adjs") else { return None }; + items + .iter() + .map(|v| match v { + Value::Descriptor(x) => Some(x), + _ => None, + }) + .collect() +} + +fn levels_params(f: &Descriptor) -> Option { + let mut out = Map::new(); + for a in adjustment_list(f)? { + let key = channel_key(a)?; + let mut o = Map::new(); + let pair = |k: &str| match a.get(k) { + Some(Value::List(v)) if v.len() == 2 => Some((int_value(&v[0])?, int_value(&v[1])?)), + _ => None, + }; + if let Some((lo, hi)) = pair("Inpt") { + o.insert("inBlack".into(), json!(lo)); + o.insert("inWhite".into(), json!(hi)); + } + if let Some(g) = px(a, "Gmm ") { + o.insert("gamma".into(), json!(g)); + } + if let Some((lo, hi)) = pair("Otpt") { + o.insert("outBlack".into(), json!(lo)); + o.insert("outWhite".into(), json!(hi)); + } + if key.is_empty() { + out.extend(o); + } else { + out.insert(key.into(), J::Object(o)); + } + } + Some(J::Object(out)) +} + +fn int_value(v: &Value) -> Option { + match v { + Value::Integer(i) => Some(*i), + _ => None, + } +} + +fn curves_params(f: &Descriptor) -> Option { + let mut out = Map::new(); + for a in adjustment_list(f)? { + let key = channel_key(a)?; + // A pencil-drawn curve is a mapping of 256 output levels (`Mpng`) instead of points. + if let Some(Value::List(map)) = a.get("Mpng") { + let map: Option> = map.iter().map(|v| int_value(v).map(|o| json!(o.clamp(0, 255)))).collect(); + out.insert(if key.is_empty() { "points".into() } else { key.into() }, J::Array(map.filter(|m| m.len() == 256)?)); + out.insert("pencil".into(), J::Bool(true)); + continue; + } + let Some(Value::List(pts)) = a.get("Crv ") else { return None }; + let pts: Option> = pts + .iter() + .map(|p| match p { + Value::Descriptor(p) => Some(json!([px(p, "Hrzn")?, px(p, "Vrtc")?])), + _ => None, + }) + .collect(); + out.insert(if key.is_empty() { "points".into() } else { key.into() }, J::Array(pts?)); + } + Some(J::Object(out)) +} + +/// Diffuse's `Md ` (`DfsM` enum, measured in Photoshop) ↔ our `mode`. +pub(super) const DIFFUSE_MODES: [(&str, &str); 4] = [("Nrml", "normal"), ("DrkO", "darkenOnly"), ("LghO", "lightenOnly"), ("anisotropic", "anisotropic")]; + +/// Trace Contour's `Edg ` (`CntE` enum, measured in Photoshop) ↔ our `edge`. +pub(super) const TRACE_EDGES: [(&str, &str); 2] = [("Upr ", "upper"), ("Lwr ", "lower")]; + +/// Our name for the enum value of `key` (of type `type_id`) through `table` (Photoshop's value, ours). +fn enum_from(d: &Descriptor, key: &str, type_id: &str, table: &[(&str, &'static str)]) -> Option<&'static str> { + let Some(Value::Enumerated { type_id: t, value }) = d.get(key) else { return None }; + if t.as_bytes() != type_id.as_bytes() { + return None; + } + table.iter().find(|(psd, _)| value.as_bytes() == psd.as_bytes()).map(|(_, ours)| *ours) +} + +// Wind, Extrude and Tiles, measured in Photoshop (each code changes the rendered result). + +/// Wind's `WndM` (enum `WndM`) ↔ our `method`. +pub(super) const WIND_METHODS: [(&str, &str); 3] = [("Wnd ", "wind"), ("Blst", "blast"), ("Stgr", "stagger")]; + +/// Wind's `Drct` (enum `Drct`) ↔ our `direction`. Photoshop's `Left` streaks extend to the left +/// of an edge, which is our wind from the right. +pub(super) const WIND_DIRECTIONS: [(&str, &str); 2] = [("Left", "fromRight"), ("Rght", "fromLeft")]; + +/// Extrude's `ExtT` (enum `ExtT`) ↔ our `type`. +pub(super) const EXTRUDE_TYPES: [(&str, &str); 2] = [("Blks", "blocks"), ("Pyrm", "pyramids")]; + +/// Extrude's `ExtR` (enum `ExtR`) ↔ our `depthMode`. +pub(super) const EXTRUDE_DEPTHS: [(&str, &str); 2] = [("Rndm", "random"), ("LvlB", "levelBased")]; + +/// Tiles' `FlCl` (enum `FlCl`) ↔ our `fill`. +pub(super) const TILE_FILLS: [(&str, &str); 4] = [("FlBc", "background"), ("FlFr", "foreground"), ("FlIn", "inverse"), ("FlSm", "unaltered")]; + +/// Extrude's size and depth (`ExtS`, `ExtD`) and Tiles' count and offset (`TlNm`, `TlOf`), all +/// `long`s, in the engine's (and Photoshop's dialog) ranges. +pub(super) const EXTRUDE_SIZE: (i32, i32) = (2, 255); + +pub(super) const EXTRUDE_DEPTH: (i32, i32) = (1, 255); + +pub(super) const TILE_COUNT: (i32, i32) = (1, 99); + +pub(super) const TILE_OFFSET: (i32, i32) = (1, 99); + +/// The `bool` at `key`. +fn bool_at(d: &Descriptor, key: &str) -> Option { + match d.get(key)? { + Value::Boolean(b) => Some(*b), + _ => None, + } +} + +/// Tiles' params; background and foreground fills use the colours the entry carries (`FrgC`, +/// `BckC`). `None` when a setting or a colour that is there can't be read. +fn tiles_params(f: &Descriptor, item: &Descriptor) -> Option { + let mut out = Map::new(); + out.insert("count".into(), json!(int_in(f, "TlNm", TILE_COUNT.0, TILE_COUNT.1)?)); + out.insert("maxOffset".into(), json!(int_in(f, "TlOf", TILE_OFFSET.0, TILE_OFFSET.1)?)); + out.insert("fill".into(), json!(enum_from(f, "FlCl", "FlCl", &TILE_FILLS)?)); + for (psd, ours) in [("FrgC", "foreground"), ("BckC", "background")] { + if item.get(psd).is_some() { + out.insert(ours.into(), get_desc(item, psd).and_then(rgbc_colour)?); + } + } + Some(J::Object(out)) +} + +/// Offset › Undefined Areas: the `FlMd` enum (`Fl `) and our `undefinedAreas`. On a layer +/// Photoshop labels `Bckg` "Set to Transparent"; a smart object is always a layer. +pub(super) const OFFSET_FILL: [(&str, &str); 3] = [("Wrp ", "wrap"), ("Rpt ", "repeat"), ("Bckg", "transparent")]; + +/// Custom's ranges in Photoshop's dialog: matrix cells, Scale, Offset. +pub(super) const CUSTOM_CELL: (i32, i32) = (-999, 999); + +pub(super) const CUSTOM_SCALE: (i32, i32) = (1, 9999); + +pub(super) const CUSTOM_OFFSET: (i32, i32) = (-9999, 9999); + +/// `v` when it lies in `lo..=hi`. +fn long_in_range(v: Option, (lo, hi): (i32, i32)) -> Option { + v.filter(|v| (lo..=hi).contains(v)) +} + +/// `filter.other.custom` params for a `Cstm` filter: `Mtrx` is 25 longs, row-major 5 × 5. Values +/// outside Photoshop's ranges are not modelled (the filter stays verbatim). +fn custom_params(f: &Descriptor) -> Option { + if !only_keys(f, &["Mtrx", "Scl ", "Ofst"]) { + return None; + } + let Some(Value::List(m)) = f.get("Mtrx") else { return None }; + if m.len() != 25 { + return None; + } + let kernel: Option> = m.iter().map(|v| long_in_range(int_value(v), CUSTOM_CELL).map(|v| json!(v))).collect(); + let scale = long_in_range(int(f, "Scl "), CUSTOM_SCALE)?; + let offset = long_in_range(int(f, "Ofst"), CUSTOM_OFFSET)?; + Some(json!({"kernel": kernel?, "scale": scale, "offset": offset})) +} + +/// The settings of Photoshop's Wave, as it writes them (and we write them back). +const WAVE_KEYS: [&str; 10] = ["Wvtp", "NmbG", "WLMn", "WLMx", "AmMn", "AmMx", "SclH", "SclV", "UndA", "RndS"]; + +/// Our command and parameters for a known Photoshop filter; `None` when the filter (or one of its +/// settings) is not modelled. `item` is the whole `filterFX` entry (Pointillize reads its `BckC`, +/// Tiles its colours). +pub(super) fn known_params(class: &str, f: Option<&Descriptor>, item: &Descriptor) -> Option<(&'static str, J)> { + let k = KNOWN.iter().find(|k| k.class == class)?; + let params = match (class, f) { + ("adaptCorrect" | "Invr", None) => json!({}), + (c, None) if NO_OPTIONS.contains(&c) => json!({}), + (_, None) => return None, + // Exactly the settings Photoshop writes (and we write back); an extra or repeated one keeps + // the filter verbatim rather than lose it on save. + ("Pnch", Some(f)) if exact_keys(f, &["Amnt"]) => json!({"amount": int(f, "Amnt")?}), + ("Twrl", Some(f)) if exact_keys(f, &["Angl"]) => json!({"angle": int(f, "Angl")?}), + ("Rple", Some(f)) if exact_keys(f, &["Amnt", "RplS"]) => json!({"amount": int(f, "Amnt")?, "size": enum_name(f, "RplS", "RplS", &RIPPLE_SIZE)?}), + ("Sphr", Some(f)) if exact_keys(f, &["Amnt", "SphM"]) => json!({"amount": int(f, "Amnt")?, "mode": enum_name(f, "SphM", "SphM", &SPHERIZE_MODE)?}), + ("Plr ", Some(f)) if exact_keys(f, &["Cnvr"]) => json!({"mode": enum_name(f, "Cnvr", "Cnvr", &POLAR_MODE)?}), + ("ZgZg", Some(f)) if exact_keys(f, &["Amnt", "NmbR", "ZZTy"]) => { + json!({"amount": int(f, "Amnt")?, "ridges": int(f, "NmbR")?, "style": enum_name(f, "ZZTy", "ZZTy", &ZIGZAG_STYLE)?}) + } + ("Wave", Some(f)) if exact_keys(f, &WAVE_KEYS) => { + // PhotoCraft's Wave has no Scale: a scaled wave stays verbatim rather than lose it. The + // same for more generators than the renderer models, which would draw fewer than + // Photoshop did (and than the file asks for, once its cached pixels are re-rendered). + let generators = int(f, "NmbG")?; + let modelled = u32::try_from(generators).is_ok_and(|g| (1..=photocraft_algo::MAX_WAVE_GENERATORS).contains(&g)); + if int(f, "SclH")? != 100 || int(f, "SclV")? != 100 || !modelled { + return None; + } + json!({ + "type": enum_name(f, "Wvtp", "Wvtp", &WAVE_TYPE)?, + "generators": generators, + "wavelengthMin": int(f, "WLMn")?, + "wavelengthMax": int(f, "WLMx")?, + "amplitudeMin": int(f, "AmMn")?, + "amplitudeMax": int(f, "AmMx")?, + "undefinedAreas": enum_name(f, "UndA", "UndA", &UNDEFINED_AREAS)?, + // `RndS` is a signed long; the seed is its bit pattern. + "seed": (int(f, "RndS")? as u32), + }) + } + ("GsnB" | "boxblur" | "Mdn " | "HghP" | "Mxm " | "Mnm ", Some(f)) => json!({"radius": px(f, "Rds ")?}), + ("MtnB", Some(f)) => json!({"angle": int(f, "Angl")?, "distance": px(f, "Dstn")?}), + ("UnsM", Some(f)) => json!({"amount": px(f, "Amnt")?, "radius": px(f, "Rds ")?, "threshold": int(f, "Thsh")?}), + ("AdNs", Some(f)) => { + let dist = match enum_of(f, "Dstr")? { + b"Unfr" => "uniform", + b"Gsn " => "gaussian", + _ => return None, + }; + let mono = match f.get("Mnch") { + Some(Value::Boolean(b)) => *b, + _ => return None, + }; + json!({"amount": px(f, "Nose")?, "distribution": dist, "monochromatic": mono, "seed": int(f, "FlRs").unwrap_or(0)}) + } + ("surfaceBlur", Some(f)) if only_keys(f, &["Rds ", "Thsh"]) => json!({ + "radius": unit_in(f, "Rds ", b"#Pxl", 1.0, 100.0)?, + "threshold": int_in(f, "Thsh", 2, 255)?, + }), + ("SmrB", Some(f)) if only_keys(f, &["Rds ", "Thsh", "SmBQ", "SmBM"]) => json!({ + "radius": in_range(double(f, "Rds ")?, 0.1, 100.0)?, + "threshold": in_range(double(f, "Thsh")?, 0.1, 100.0)?, + "quality": enum_name(f, "SmBQ", "SmBQ", &SMART_BLUR_QUALITY)?, + "mode": enum_name(f, "SmBM", "SmBM", &SMART_BLUR_MODE)?, + }), + ("RdlB", Some(f)) if only_keys(f, &["Amnt", "BlrM", "BlrQ"]) => json!({ + "amount": int_in(f, "Amnt", 1, 100)?, + "method": enum_name(f, "BlrM", "BlrM", &RADIAL_METHOD)?, + "quality": enum_name(f, "BlrQ", "BlrQ", &RADIAL_QUALITY)?, + }), + ("Msc ", Some(f)) => json!({"cellSize": px(f, "ClSz")?}), + ("Mztn", Some(f)) if only_keys(f, &["MztT"]) => json!({"type": enum_name(f, "MztT", "MztT", &MEZZOTINT_TYPES)?}), + ("ClrH", Some(f)) => color_halftone_params(f)?, + ("Embs", Some(f)) => json!({"angle": int(f, "Angl")?, "height": int(f, "Hght")?, "amount": int(f, "Amnt")?}), + (SMART_SHARPEN, Some(f)) => smart_sharpen_params(f)?, + ("DstS", Some(f)) => { + if f.items.iter().any(|(k, _)| !k.is("Rds ") && !k.is("Thsh")) { + return None; + } + json!({"radius": int_in(f, "Rds ", 1, 500)?, "threshold": int_in(f, "Thsh", 0, 255)?}) + } + ("Dfs ", Some(f)) => json!({"mode": enum_from(f, "Md ", "DfsM", &DIFFUSE_MODES)?}), + ("TrcC", Some(f)) => json!({"level": int_in(f, "Lvl ", 0, 255)?, "edge": enum_from(f, "Edg ", "CntE", &TRACE_EDGES)?}), + ("Crst", Some(f)) => json!({"cellSize": int_in(f, "ClSz", CELL_SIZE.0, CELL_SIZE.1)?}), + ("Pntl", Some(f)) => { + let mut p = json!({"cellSize": int_in(f, "ClSz", CELL_SIZE.0, CELL_SIZE.1)?}); + // Pointillize paints the gaps in the background colour the entry carries. + if item.get("BckC").is_some() { + p["background"] = get_desc(item, "BckC").and_then(rgbc_colour)?; + } + p + } + ("Wnd ", Some(f)) => json!({ + "method": enum_from(f, "WndM", "WndM", &WIND_METHODS)?, + "direction": enum_from(f, "Drct", "Drct", &WIND_DIRECTIONS)?, + }), + ("Extr", Some(f)) => json!({ + "type": enum_from(f, "ExtT", "ExtT", &EXTRUDE_TYPES)?, + "size": int_in(f, "ExtS", EXTRUDE_SIZE.0, EXTRUDE_SIZE.1)?, + "depth": int_in(f, "ExtD", EXTRUDE_DEPTH.0, EXTRUDE_DEPTH.1)?, + "depthMode": enum_from(f, "ExtR", "ExtR", &EXTRUDE_DEPTHS)?, + "solidFrontFaces": bool_at(f, "ExtF")?, + "maskIncompleteBlocks": bool_at(f, "ExtM")?, + }), + ("Tls ", Some(f)) => tiles_params(f, item)?, + ("Ofst", Some(f)) if only_keys(f, &["Hrzn", "Vrtc", "Fl "]) => { + json!({"horizontal": int(f, "Hrzn")?, "vertical": int(f, "Vrtc")?, "undefinedAreas": enum_from(f, "Fl ", "FlMd", &OFFSET_FILL)?}) + } + ("Cstm", Some(f)) => custom_params(f)?, + // Only the settings and value types Photoshop writes (and we write back); anything else + // keeps the filter verbatim. + ("LnsF", Some(f)) if exact_keys(f, &["Brgh", "FlrC", "Lns "]) => { + let centre = get_desc(f, "FlrC").filter(|c| c.class_id.is("Pnt ") && exact_keys(c, &["Hrzn", "Vrtc"]))?; + let lens = enum_name(f, "Lns ", "Lns ", &LENSES)?; + json!({"brightness": int(f, "Brgh")?, "centerX": double(centre, "Hrzn")?, "centerY": double(centre, "Vrtc")?, "lens": lens}) + } + ("Lvls", Some(f)) => levels_params(f)?, + ("Crvs", Some(f)) => curves_params(f)?, + _ => return None, + }; + Some((k.command, params)) +} + +// ---------- Filter Gallery ---------- +// +// Filter › Filter Gallery stores its effect stack in a `GEfc` filter (filterID `GEfc`). Photoshop +// writes a single effect inline; Photopea writes a list (also for one effect): +// +// ```text +// Fltr = GEfc { GEfk = GEft enum (the effect), } (Photoshop) +// Fltr = GEfc { GEfs = [ GEfc { , GEfk = GEft enum, GELv = visible } ] } (Photopea) +// ``` +// +// The list is in application order, like `filter.filterGallery`'s `effects`. The item's +// `FrgC`/`BckC` are the colours the Sketch effects read. Only effects whose settings we know are +// mapped; a stack with any other effect (or setting) stays an [`UNSUPPORTED_FILTER`]. + +const GALLERY_CLASS: &str = "GEfc"; + +pub(super) const GALLERY_COMMAND: &str = "filter.filterGallery"; + +const GALLERY_NAME: &str = "Filter Gallery..."; + +/// One gallery effect: our filter key, Photoshop's `GEft` code and its settings (PSD key, our key). +pub(super) struct GalleryCode { + pub(super) key: &'static str, + code: &'static str, + pub(super) settings: &'static [(&'static str, &'static str)], +} + +pub(super) const GALLERY_EFFECTS: [GalleryCode; 1] = [GalleryCode { key: "chrome", code: "Chrm", settings: &[("Dtl ", "detail"), ("Smth", "smoothness")] }]; + +/// An `RGBC` descriptor (0–255 channels) as straight `[r, g, b, a]`, 0–1. +fn rgbc_colour(d: &Descriptor) -> Option { + let c = |k: &str| px(d, k).map(|v| (v / 255.0).clamp(0.0, 1.0)); + Some(json!([c("Rd ")?, c("Grn ")?, c("Bl ")?, 1.0])) +} + +/// Fibers, Clouds and Difference Clouds draw with the item's foreground and background colours: +/// their params are the `Fltr` settings plus those colours. +fn coloured_params(class: &str, item: &Descriptor, f: &Descriptor) -> Option<(&'static str, J)> { + let k = KNOWN.iter().find(|k| k.class == class)?; + // An `RGBC` of three `doub`s in 0–255, as Photoshop writes it (and we write it back); any + // other colour keeps the filter verbatim. + let colour = |key: &str| { + get_desc(item, key) + .filter(|c| c.class_id.is("RGBC") && exact_keys(c, &["Rd ", "Grn ", "Bl "])) + .filter(|c| ["Rd ", "Grn ", "Bl "].iter().all(|k| double(c, k).is_some_and(|v| (0.0..=255.0).contains(&v)))) + .and_then(rgbc_colour) + }; + // Only the settings Photoshop writes; an extra or repeated one keeps the filter verbatim. + let keys: &[&str] = if class == "Fbrs" { &["Vrnc", "Strg", "RndS"] } else { &["FlRs"] }; + if !exact_keys(f, keys) { + return None; + } + // The seeds (`RndS`, `FlRs`) are signed longs; ours is their bit pattern. + let mut p = match class { + "Fbrs" => json!({"variance": int(f, "Vrnc")?, "strength": int(f, "Strg")?, "seed": int(f, "RndS")? as u32}), + _ => json!({"seed": int(f, "FlRs")? as u32}), + }; + let o = p.as_object_mut()?; + o.insert("foreground".into(), colour("FrgC")?); + o.insert("background".into(), colour("BckC")?); + Some((k.command, p)) +} + +pub(super) fn seed_param(p: &J) -> Value { + Value::Integer(p.get("seed").and_then(J::as_u64).and_then(|n| u32::try_from(n).ok()).unwrap_or(0) as i32) +} + +/// `filter.filterGallery` params for a `GEfc` filter item; `None` when an effect or setting is +/// not modelled. +fn gallery_params(item: &Descriptor, f: &Descriptor) -> Option { + let list: Vec<&Descriptor> = match f.get("GEfs") { + Some(Value::List(list)) => list + .iter() + .map(|v| match v { + Value::Descriptor(e) => Some(e), + _ => None, + }) + .collect::>()?, + Some(_) => return None, + None if f.get("GEfk").is_some() => vec![f], + None => return None, + }; + let mut effects = Vec::with_capacity(list.len()); + for e in list { + let code = enum_of(e, "GEfk")?; + let g = GALLERY_EFFECTS.iter().find(|g| g.code.as_bytes() == code)?; + let mut params = Map::new(); + for (k, v) in &e.items { + if k.is("GEfk") || k.is("GELv") { + continue; + } + let (_, ours) = g.settings.iter().find(|(psd, _)| k.is(psd))?; + params.insert((*ours).into(), json!(int_value(v)?)); + } + effects.push(json!({"filter": g.key, "params": params, "visible": bool_or(e, "GELv", true)})); + } + if effects.is_empty() { + return None; + } + let mut out = Map::new(); + out.insert("effects".into(), J::Array(effects)); + for (psd, ours) in [("FrgC", "foreground"), ("BckC", "background")] { + if let Some(c) = get_desc(item, psd).and_then(rgbc_colour) { + out.insert(ours.into(), c); + } + } + Some(J::Object(out)) +} + +fn colour_rgb(v: &J) -> Option<[f64; 3]> { + match v { + J::Array(a) => Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?]), + J::String(h) if h.len() == 7 && h.starts_with('#') => { + let ch = |j: usize| h.get(j..j + 2).and_then(|s| u8::from_str_radix(s, 16).ok()).map(|v| f64::from(v) / 255.0); + Some([ch(1)?, ch(3)?, ch(5)?]) + } + _ => None, + } +} + +/// A `[r, g, b(, a)]` (0–1) or `#rrggbb` colour param as an `RGBC` descriptor (0–255). +pub(super) fn colour_rgbc(v: Option<&J>, default: f64) -> Result { + let Some(v) = v else { return Ok(rgbc(default)) }; + let rgb = colour_rgb(v).filter(|c| c.iter().all(|v| v.is_finite())).ok_or("a colour is not [r, g, b] or #rrggbb")?; + let c = |v: f64| Value::Double(v.clamp(0.0, 1.0) * 255.0); + Ok(Value::Descriptor(Descriptor::new("RGBC").with("Rd ", c(rgb[0])).with("Grn ", c(rgb[1])).with("Bl ", c(rgb[2])))) +} + +/// The `filterFXList` item for a `filter.filterGallery` smart filter. +pub(super) fn gallery_item(f: &SmartFilter) -> Result { + let p = &f.params; + if let Some(k) = p.as_object().and_then(|o| o.keys().find(|k| !is_meta(k) && !["effects", "foreground", "background"].contains(&k.as_str()))) { + return Err(format!("setting `{k}` has no PSD equivalent")); + } + let list = p.get("effects").and_then(J::as_array).ok_or("it has no effects")?; + let mut out = Vec::with_capacity(list.len()); + for e in list { + let key = e.get("filter").and_then(J::as_str).ok_or("an effect has no `filter`")?; + let g = GALLERY_EFFECTS.iter().find(|g| g.key == key).ok_or_else(|| format!("gallery effect `{key}` has no PSD equivalent"))?; + let params = e.get("params").filter(|v| v.is_object()).unwrap_or(e); + if let Some(k) = params.as_object().and_then(|o| { + o.keys().find(|k| !is_meta(k) && !["filter", "params", "visible"].contains(&k.as_str()) && !g.settings.iter().any(|(_, ours)| ours == k)) + }) { + return Err(format!("gallery setting `{key}.{k}` has no PSD equivalent")); + } + let defaults = photocraft_algo::GalleryFilter::from_key(key).map(photocraft_algo::GalleryEffect::new); + let settings: Vec<(&str, Value)> = + g.settings.iter().map(|(psd, ours)| (*psd, pi(params, ours, defaults.as_ref().map_or(0.0, |x| f64::from(x.get(ours)))))).collect(); + out.push((g.code, settings, e.get("visible").and_then(J::as_bool).unwrap_or(true))); + } + let gallery = || { + let mut d = Descriptor::new(GALLERY_CLASS); + d.name = UnicodeString::new_nul("Filter Gallery"); + d + }; + // One visible effect: inline, as Photoshop writes it. Otherwise the effect list. + let fltr = match out.as_slice() { + [] => return Err("it has no effects".into()), + [(code, settings, true)] => settings.iter().fold(gallery().with("GEfk", enumv("GEft", code)), |d, (k, v)| d.with(k, v.clone())), + _ => { + let list = out + .into_iter() + .map(|(code, settings, visible)| { + let d = settings.into_iter().fold(gallery(), |d, (k, v)| d.with(k, v)); + Value::Descriptor(d.with("GEfk", enumv("GEft", code)).with("GELv", Value::Boolean(visible))) + }) + .collect(); + gallery().with("GEfs", Value::List(list)) + } + }; + Ok(Descriptor::new("filterFX") + .with("Nm ", Value::Text(UnicodeString::new_nul(GALLERY_NAME))) + .with("blendOptions", blend_options(f)) + .with("enab", Value::Boolean(f.visible)) + .with("hasoptions", Value::Boolean(true)) + .with("FrgC", colour_rgbc(p.get("foreground"), 0.0)?) + .with("BckC", colour_rgbc(p.get("background"), 255.0)?) + .with("Fltr", Value::Descriptor(fltr)) + .with("filterID", Value::Integer(code(b"GEfc")))) +} + +/// Lowercase hex of `bytes`. +pub(crate) fn to_hex(bytes: &[u8]) -> String { + const H: &[u8; 16] = b"0123456789abcdef"; + let mut s = String::with_capacity(bytes.len() * 2); + for b in bytes { + s.push(char::from(H[usize::from(b >> 4)])); + s.push(char::from(H[usize::from(b & 15)])); + } + s +} + +pub(crate) fn from_hex(s: &str) -> Option> { + let d = |c: u8| (c as char).to_digit(16).map(|v| v as u8); + let b = s.as_bytes(); + if !b.len().is_multiple_of(2) { + return None; + } + b.as_chunks::<2>().0.iter().map(|c| Some(d(c[0])? << 4 | d(c[1])?)).collect() +} + +/// One `filterFXList` item → [`SmartFilter`] (an [`UNSUPPORTED_FILTER`] when not modelled). +pub fn filter_from_item(item: &Descriptor) -> SmartFilter { + let opts = get_desc(item, "blendOptions"); + let opacity = opts.and_then(|o| px(o, "Opct")).map_or(1.0, |v| (v / 100.0).clamp(0.0, 1.0) as f32); + let blend = opts.and_then(|o| enum_of(o, "Md ")).and_then(crate::effects_map::blend_from_id).unwrap_or(BlendMode::Normal); + let visible = bool_or(item, "enab", true); + let fltr = get_desc(item, "Fltr"); + let class = fltr.map(|f| String::from_utf8_lossy(f.class_id.as_bytes()).into_owned()); + let filter_id = int(item, "filterID").unwrap_or(0); + let class = class.or_else(|| KNOWN.iter().find(|k| k.filter_id == filter_id).map(|k| k.class.to_string())); + let known = match class.as_deref() { + Some(camera_raw::CLASS) => camera_raw::import_params(item).map(|p| (camera_raw::COMMAND, p)), + Some(displace::CLASS) => displace::import_params(item).map(|p| (displace::COMMAND, p)), + Some(hue_sat::CLASS) => fltr.and_then(hue_sat::import_params).map(|p| (hue_sat::COMMAND, p)), + Some(perspective_warp::CLASS) => perspective_warp::import_params(item).map(|p| (perspective_warp::COMMAND, p)), + Some(GALLERY_CLASS) => fltr.and_then(|f| gallery_params(item, f)).map(|p| (GALLERY_COMMAND, p)), + Some(c @ ("Fbrs" | "Clds" | "DfrC")) => fltr.and_then(|f| coloured_params(c, item, f)), + // A `Fltr` that is there but not a descriptor is settings we can't read: kept verbatim + // rather than taken for a filter stored without options (which would drop it on save). + _ if fltr.is_none() && item.get("Fltr").is_some() => None, + c => c.and_then(|c| known_params(c, fltr, item)), + }; + let (command, params) = match known { + Some((c, p)) => (c.to_string(), p), + None => { + let name = text_of(item, "Nm ").unwrap_or_default(); + // The stored descriptor carries neutral blending (the model's own fields replace + // them on export), so hiding or re-blending the filter leaves its params alone. + let mut neutral = item.clone(); + for (k, v) in &mut neutral.items { + if k.is("blendOptions") { + *v = blend_options(&SmartFilter { command: String::new(), params: J::Null, blend: BlendMode::Normal, opacity: 1.0, visible: true }); + } else if k.is("enab") { + *v = Value::Boolean(true); + } + } + (UNSUPPORTED_FILTER.to_string(), json!({"name": name.replace('&', ""), "filterID": filter_id, "psd": to_hex(&neutral.to_bytes())})) + } + }; + SmartFilter { command, params, blend, opacity, visible } +} diff --git a/crates/io/src/smart_map/placed.rs b/crates/io/src/smart_map/placed.rs new file mode 100644 index 0000000000..9bdb52bc1c --- /dev/null +++ b/crates/io/src/smart_map/placed.rs @@ -0,0 +1,274 @@ +use super::export::{set, set_before, unit}; +use super::*; + +/// Everything needed to write the placed-layer blocks of a smart object. +#[derive(Clone, Debug)] +pub struct PlacedSpec<'a> { + pub idnt: &'a str, + pub placed: &'a str, + /// Source pixels → document pixels. + pub transform: Affine, + /// Distort / Perspective: the full projective map (row-major 3×3), overriding `transform`. + pub perspective: Option<[f64; 9]>, + /// Source size in pixels. + pub size: (f64, f64), + /// Source resolution. + pub dpi: f64, + pub warp: Option<&'a Warp>, + /// `filterFX`, when the smart object has filters. + pub filter_fx: Option, +} + +/// Where the frame corners land (top-left, top-right, bottom-right, bottom-left), as x, y pairs. +/// The frame is [`crate::blocks::placed_frame`] of `warp`, the warp the block stores, for an +/// affine placement (the inverse of `parse_smart`), [`crate::blocks::perspective_frame`] of it +/// for a projective one (as `parse_smart_perspective` reads it). +fn quad_points(s: &PlacedSpec<'_>, warp: Option<&Warp>) -> [f64; 8] { + let (w, h) = s.size; + let [a, b, c, d, e, f] = s.transform.m; + let map = |x: f64, y: f64| match &s.perspective { + Some(p) => photocraft_algo::transform::Homography(*p).apply(x, y), + None => (a * x + c * y + e, b * x + d * y + f), + }; + let [x0, y0, x1, y1] = if s.perspective.is_some() { crate::blocks::perspective_frame(warp, w, h) } else { crate::blocks::placed_frame(warp, w, h) }; + let mut out = [0.0; 8]; + for (i, (x, y)) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].into_iter().enumerate() { + (out[2 * i], out[2 * i + 1]) = map(x, y); + } + out +} + +/// The transform quad: the source corners (top-left, top-right, bottom-right, bottom-left). +fn quad(s: &PlacedSpec<'_>, warp: Option<&Warp>) -> Value { + Value::List(quad_points(s, warp).into_iter().map(Value::Double).collect()) +} + +/// Has the placement moved from the quad a template descriptor stores (`Trnf`)? +pub(super) fn quad_moved(template: &Descriptor, s: &PlacedSpec<'_>, warp: Option<&Warp>) -> bool { + let Some(Value::List(pts)) = template.get("Trnf") else { return true }; + let old: Vec = pts.iter().filter_map(|v| crate::blocks::num(Some(v))).collect(); + let new = quad_points(s, warp); + old.len() != 8 || old.iter().zip(new).any(|(a, b)| (a - b).abs() > 1e-6 * (1.0 + a.abs())) +} + +pub(crate) fn enumv(t: &str, v: &str) -> Value { + Value::Enumerated { type_id: Id::new(t), value: Id::new(v) } +} + +/// The mesh of a split warp: a custom warp of more than one patch, which `SoLd` stores as +/// `quiltWarp` and `PlLd` can't store. +fn split_mesh(w: Option<&Warp>) -> Option<&BezierMesh> { + w.filter(|w| w.style == WarpStyle::Custom).and_then(|w| w.mesh.as_ref()).filter(|m| m.points.len() != 16 && m.is_valid()) +} + +/// The warp `SoLd` stores: none, with a message, for a split warp of more patches along a side +/// than a `quiltWarp` is read with, so its corners are framed by the source rect as on reopen. +fn sold_warp<'a>(w: Option<&'a Warp>, warnings: &mut Vec) -> Option<&'a Warp> { + let too_big = split_mesh(w).is_some_and(|m| m.us.len().max(m.vs.len()) > crate::blocks::QUILT_MAX_PATCHES + 1); + if too_big { + warnings.push(format!("a split warp of more than {} patches along a side was written to PSD without its warp", crate::blocks::QUILT_MAX_PATCHES)); + return None; + } + w +} + +/// Style, bend, distortions, axis, bounds and order: the keys a `warp` and a `quiltWarp` +/// descriptor share, in Photoshop's order. +fn warp_head(class: &str, w: &Warp) -> Descriptor { + let [x0, y0, x1, y1] = w.bounds; + let bounds = Descriptor::new("classFloatRect") + .with("Top ", Value::Double(y0)) + .with("Left", Value::Double(x0)) + .with("Btom", Value::Double(y1)) + .with("Rght", Value::Double(x1)); + let d = Descriptor::new(class).with("warpStyle", enumv("warpStyle", w.style.psd_name())).with("warpValue", Value::Double(w.bend)); + // A cylinder is stored as its seven `warpValues` (#4112). + let d = if w.style == WarpStyle::Cylinder { d.with("warpValues", Value::List(w.values.iter().copied().map(Value::Double).collect())) } else { d }; + d.with("warpPerspective", Value::Double(w.h_distort)) + .with("warpPerspectiveOther", Value::Double(w.v_distort)) + .with("warpRotate", enumv("Ornt", if w.vertical { "Vrtc" } else { "Hrzn" })) + .with("bounds", Value::Descriptor(bounds)) + .with("uOrder", Value::Integer(4)) + .with("vOrder", Value::Integer(4)) +} + +/// The control points of a custom warp: an object array of their x and y. +fn mesh_points(m: &BezierMesh) -> Value { + let body = Descriptor::new("rationalPoint") + .with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: m.points.iter().map(|p| p[0]).collect() }) + .with("Vrtc", Value::UnitFloats { unit: *b"#Pxl", values: m.points.iter().map(|p| p[1]).collect() }); + Value::ObjectArray(ObjectArray { prefix: m.points.len() as u32, body }) +} + +/// The `warp` descriptor (also the `PlLd` warp). A split warp is written as no warp: `SoLd` +/// keeps it in `quiltWarp` ([`quilt_desc`]), next to this `warpNone`, as Photoshop does. A +/// custom warp without a usable mesh is written as no warp, with a message. A cylinder is +/// written as its seven `warpValues`. +pub(super) fn warp_desc(w: Option<&Warp>, size: (f64, f64), warnings: &mut Vec) -> Value { + let none = Warp::none([0.0, 0.0, size.0, size.1]); + let mut w = w.unwrap_or(&none).clone(); + let mesh = match (&w.style, &w.mesh) { + (WarpStyle::Custom, Some(m)) if m.points.len() == 16 => Some(m.clone()), + (WarpStyle::Custom, Some(m)) if m.is_valid() => { + w = none.clone(); + None + } + (WarpStyle::Custom, _) => { + warnings.push("a custom warp without a valid mesh was written to PSD without its warp".into()); + w = none.clone(); + None + } + _ => None, + }; + let mut d = warp_head("warp", &w); + if let Some(m) = mesh { + d = d.with("customEnvelopeWarp", Value::Descriptor(Descriptor::new("customEnvelopeWarp").with("meshPoints", mesh_points(&m)))); + } + Value::Descriptor(d) +} + +/// The `quiltWarp` descriptor of a split warp, in Photoshop's layout: `deformNumCols` × +/// `deformNumRows` control points, and the patch boundaries (`quiltSliceX` / `quiltSliceY`) at +/// the knots across the warp's box. The imported `quiltWarp` (`old`) gives its own slices where +/// they still bound the mesh's patches, so their units and padding stay Photoshop's. +fn quilt_desc(w: &Warp, mesh: &BezierMesh, old: Option<&Descriptor>) -> Value { + let old_env = old.and_then(|q| get_desc(q, "customEnvelopeWarp")); + let [x0, y0, x1, y1] = w.bounds; + let slices = |key: &str, knots: &[f64], lo: f64, hi: f64| { + if let Some(env) = old_env + && crate::blocks::quilt_knots(env, key, knots.len() - 1).as_deref() == Some(knots) + && let Some(v) = env.get(key) + { + return v.clone(); + } + let (lo, hi) = if (hi - lo).is_finite() && hi > lo { (lo, hi) } else { (0.0, 1.0) }; + let values: Vec = knots.iter().map(|u| lo + u * (hi - lo)).collect(); + let prefix = values.len() as u32; + Value::ObjectArray(ObjectArray { prefix, body: Descriptor::new("UntF").with(key, Value::UnitFloats { unit: *b"#Pxl", values }) }) + }; + let envelope = Descriptor::new("customEnvelopeWarp") + .with("quiltSliceX", slices("quiltSliceX", &mesh.us, x0, x1)) + .with("quiltSliceY", slices("quiltSliceY", &mesh.vs, y0, y1)) + .with("meshPoints", mesh_points(mesh)); + Value::Descriptor( + warp_head("quiltWarp", w) + .with("deformNumRows", Value::Integer(mesh.ny() as i32)) + .with("deformNumCols", Value::Integer(mesh.nx() as i32)) + .with("customEnvelopeWarp", Value::Descriptor(envelope)), + ) +} + +fn ratio(n: i32, d: i32) -> Value { + Value::Descriptor(Descriptor::new("null").with("numerator", Value::Integer(n)).with("denominator", Value::Integer(d))) +} + +fn pad4(mut v: Vec) -> Vec { + while !v.len().is_multiple_of(4) { + v.push(0); + } + v +} + +/// `SoLd` block data. With `template` (the imported descriptor) every key it has is kept and only +/// the placed id (for a duplicate), transform (when it moved), warp and filter stack are rewritten; +/// otherwise a fresh descriptor in Photoshop's key order. A split warp goes in `quiltWarp`. +pub fn sold_bytes(template: Option<&Descriptor>, s: &PlacedSpec<'_>, warnings: &mut Vec) -> Vec { + let stored = sold_warp(s.warp, warnings); + let warp = warp_desc(stored, s.size, warnings); + let split = stored.zip(split_mesh(stored)); + let d = match template { + Some(t) => { + let mut d = t.clone(); + if text_of(t, "placed").as_deref() != Some(s.placed) { + set(&mut d, "placed", Value::Text(UnicodeString::new_nul(s.placed))); + } + if quad_moved(t, s, stored) { + set(&mut d, "Trnf", quad(s, stored)); + set(&mut d, "nonAffineTransform", quad(s, stored)); + } + set(&mut d, "warp", warp); + // `quiltWarp` is read before `warp`, so the imported one stays only while it still + // says what the layer's warp is (unchanged, or unreadable while the layer has none); + // otherwise it is rewritten, or dropped for a warp that isn't split. + let old = get_desc(t, "quiltWarp"); + let kept = old.is_some_and(|q| match crate::blocks::warp_of(q) { + Some(w) => w.as_ref() == stored, + None => s.warp.is_none(), + }); + if !kept { + match split { + Some((w, m)) => set_before(&mut d, "quiltWarp", quilt_desc(w, m, old), "warp"), + None => d.items.retain(|(k, _)| !k.is("quiltWarp")), + } + } + match &s.filter_fx { + Some(fx) => set(&mut d, "filterFX", Value::Descriptor(fx.clone())), + None => d.items.retain(|(k, _)| !k.is("filterFX")), + } + d + } + None => { + let mut d = Descriptor::new("null") + .with("Idnt", Value::Text(UnicodeString::new_nul(s.idnt))) + .with("placed", Value::Text(UnicodeString::new_nul(s.placed))) + .with("PgNm", Value::Integer(1)) + .with("totalPages", Value::Integer(1)) + .with("Crop", Value::Integer(1)) + .with("frameStep", ratio(0, 600)) + .with("duration", ratio(0, 600)) + .with("frameCount", Value::Integer(1)) + .with("Annt", Value::Integer(16)) + .with("Type", Value::Integer(2)) + .with("Trnf", quad(s, stored)) + .with("nonAffineTransform", quad(s, stored)); + if let Some((w, m)) = split { + d = d.with("quiltWarp", quilt_desc(w, m, None)); + } + let mut d = d + .with("warp", warp) + .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(s.size.0)).with("Hght", Value::Double(s.size.1)))) + .with("Rslt", unit(b"#Rsl", s.dpi)); + if let Some(fx) = &s.filter_fx { + d = d.with("filterFX", Value::Descriptor(fx.clone())); + } + d.with("comp", Value::Integer(-1)) + .with("compInfo", Value::Descriptor(Descriptor::new("null").with("compID", Value::Integer(-1)).with("originalCompID", Value::Integer(-1)))) + } + }; + let mut out = b"soLD".to_vec(); + out.extend_from_slice(&4u32.to_be_bytes()); + out.extend(VersionedDescriptor::new(d).to_bytes()); + pad4(out) +} + +/// `PlLd` block data (`plcL` version 3): the legacy placed-layer record Photoshop writes next to +/// `SoLd`. It has no split warp: it stores none, its corners framed by the source rect. +pub fn plld_bytes(s: &PlacedSpec<'_>, warnings: &mut Vec) -> Vec { + let warp = s.warp.filter(|_| split_mesh(s.warp).is_none()); + let mut out = b"plcL".to_vec(); + out.extend_from_slice(&3u32.to_be_bytes()); + let id = s.idnt.as_bytes(); + let n = id.len().min(255); + out.push(n as u8); + out.extend_from_slice(&id[..n]); + for v in [1i32, 1, 16, 2] { + out.extend_from_slice(&v.to_be_bytes()); + } + if let Value::List(q) = quad(s, warp) { + for v in q { + if let Value::Double(x) = v { + out.extend_from_slice(&x.to_be_bytes()); + } + } + } + out.extend_from_slice(&0u32.to_be_bytes()); + let Value::Descriptor(w) = warp_desc(warp, s.size, warnings) else { return pad4(out) }; + out.extend(VersionedDescriptor::new(w).to_bytes()); + pad4(out) +} + +/// The source size a `soLD` descriptor stores (`Sz `). +pub fn stored_size(d: &Descriptor) -> Option<(f64, f64)> { + let sz = get_desc(d, "Sz ")?; + Some((num(sz.get("Wdth"))?, num(sz.get("Hght"))?)).filter(|(w, h)| *w > 0.0 && *h > 0.0) +} diff --git a/crates/io/src/smart_map/tests.rs b/crates/io/src/smart_map/tests.rs index eea8c0538e..1bbd5bd094 100644 --- a/crates/io/src/smart_map/tests.rs +++ b/crates/io/src/smart_map/tests.rs @@ -663,9 +663,7 @@ fn malformed_wind_extrude_tiles_are_kept_verbatim() { ("BckC", Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)))), ( "BckC", - Value::Descriptor( - Descriptor::new("RGBC").with("Rd ", Value::Double(f64::NAN)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0)), - ), + Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(f64::NAN)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0))), ), ] { let mut item = measured_item(tiles(long(6), long(20), "FlFr"), 0.0, 255.0); @@ -929,8 +927,8 @@ fn color_halftone_round_trips_and_reads_photoshops_shape() { assert_eq!(f.params, json!({"maxRadius": 6, "channel1": 10, "channel2": 20, "channel3": 30, "channel4": 40})); assert_eq!(get_desc(&item_for_filter(&f).unwrap(), "Fltr"), Some(&measured)); // Defaults and hostile values write longs within the dialog's ranges. - let d = item_for_filter(&sf("filter.pixelate.colorHalftone", json!({"maxRadius": f64::NAN, "channel1": 1e12, "channel2": -1e12, "channel3": "x"}))) - .unwrap(); + let d = + item_for_filter(&sf("filter.pixelate.colorHalftone", json!({"maxRadius": f64::NAN, "channel1": 1e12, "channel2": -1e12, "channel3": "x"}))).unwrap(); let fltr = get_desc(&d, "Fltr").unwrap(); let got: Vec<_> = ["Rds ", "Ang1", "Ang2", "Ang3", "Ang4"].iter().map(|k| int(fltr, k)).collect(); assert_eq!(got, [Some(8), Some(360), Some(-360), Some(90), Some(45)]); @@ -1182,10 +1180,7 @@ fn hue_saturation_ranges_are_not_lost() { let fltr = Descriptor::new("HStr").with("Clrz", Value::Boolean(false)).with("Adjs", Value::List(adjs)); let item = Descriptor::new("filterFX") .with("Nm ", Value::Text(UnicodeString::new_nul("Hue/Saturation..."))) - .with( - "blendOptions", - Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal"))), - ) + .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) .with("enab", Value::Boolean(true)) .with("Fltr", Value::Descriptor(fltr)) .with("filterID", Value::Integer(code(b"HStr"))); @@ -1254,12 +1249,7 @@ fn blur_family_matches_photoshop_shapes() { let cases = [ (surface_blur(5.0, 15), 1135, "filter.blur.surfaceBlur", json!({"radius": 5.0, "threshold": 15})), (surface_blur(12.0, 40), 1135, "filter.blur.surfaceBlur", json!({"radius": 12.0, "threshold": 40})), - ( - smart_blur(5.0, 25.0, "SBQH", "SBMN"), - smart, - "filter.blur.smartBlur", - json!({"radius": 5.0, "threshold": 25.0, "quality": "high", "mode": "normal"}), - ), + (smart_blur(5.0, 25.0, "SBQH", "SBMN"), smart, "filter.blur.smartBlur", json!({"radius": 5.0, "threshold": 25.0, "quality": "high", "mode": "normal"})), ( smart_blur(3.0, 30.0, "SBQL", "SBME"), smart, @@ -1555,8 +1545,7 @@ fn malformed_stylize_and_pixelate_filters_are_kept_verbatim() { /// A Filter Gallery item as Photopea writes it (Chrome, Detail 12, Smoothness 4). fn gallery_item_with(effects: Vec) -> Descriptor { - let rgb = - |v: f64| Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))); + let rgb = |v: f64| Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))); Descriptor::new("filterFX") .with("Nm ", Value::Text(UnicodeString::new_nul("Filtergalerie"))) .with("blendOptions", Value::Descriptor(Descriptor::new("blendOptions").with("Opct", unit(b"#Prc", 100.0)).with("Md ", enumv("BlnM", "normal")))) @@ -1605,10 +1594,8 @@ fn filter_gallery_chrome_imports_as_editable_gallery() { /// A single effect as Photoshop 27 writes it: inline in `Fltr`, no `GEfs` list or `GELv`. fn photoshop_chrome(detail: i32, smoothness: i32) -> Descriptor { - let rgb = - |v: f64| Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))); - let mut fltr = - Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Chrm")).with("Dtl ", Value::Integer(detail)).with("Smth", Value::Integer(smoothness)); + let rgb = |v: f64| Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(v)).with("Grn ", Value::Double(v)).with("Bl ", Value::Double(v))); + let mut fltr = Descriptor::new("GEfc").with("GEfk", enumv("GEft", "Chrm")).with("Dtl ", Value::Integer(detail)).with("Smth", Value::Integer(smoothness)); fltr.name = UnicodeString::new_nul("Filter Gallery"); Descriptor::new("filterFX") .with("Nm ", Value::Text(UnicodeString::new_nul("Filter Gallery..."))) @@ -1732,8 +1719,7 @@ fn unwritable_filters_are_reported_not_fatal() { #[test] fn placed_blocks_parse_back() { let t = Affine { m: [0.5, 0.1, -0.1, 0.5, 10.0, 20.0] }; - let stack = - FilterStack { enabled: false, filters: vec![sf("filter.blur.gaussianBlur", json!({"radius": 3.0}))], mask_enabled: false, mask_linked: true }; + let stack = FilterStack { enabled: false, filters: vec![sf("filter.blur.gaussianBlur", json!({"radius": 3.0}))], mask_enabled: false, mask_linked: true }; let mut w = Vec::new(); let spec = PlacedSpec { idnt: "id-1", @@ -2131,8 +2117,7 @@ fn cylinder_warp_round_trips_through_sold() { let v = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5]; let warp = Warp::cylinder(&v, [0.0, 0.0, 1000.0, 1000.0]).unwrap(); let transform = Affine { m: [0.5, 0.0, 0.0, 0.5, 40.0, 30.0] }; - let mut spec = - PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (1000.0, 1000.0), dpi: 72.0, warp: Some(&warp), filter_fx: None }; + let mut spec = PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (1000.0, 1000.0), dpi: 72.0, warp: Some(&warp), filter_fx: None }; let mut warnings = Vec::new(); let sold = sold_bytes(None, &spec, &mut warnings); assert!(warnings.is_empty(), "{warnings:?}"); From 57bfd18bd7a136662b771288bdf2456b39872879 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:20:08 +0000 Subject: [PATCH 254/259] refactor(text): split psd.rs into psd/ --- crates/text/src/psd.rs | 1824 +-------------------------------- crates/text/src/psd/build.rs | 714 +++++++++++++ crates/text/src/psd/edit.rs | 320 ++++++ crates/text/src/psd/import.rs | 782 ++++++++++++++ 4 files changed, 1833 insertions(+), 1807 deletions(-) create mode 100644 crates/text/src/psd/build.rs create mode 100644 crates/text/src/psd/edit.rs create mode 100644 crates/text/src/psd/import.rs diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 4f3f54c367..7c51759482 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -20,6 +20,23 @@ use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D, Vers use crate::engine_data::{self as ed, Value as E}; use crate::fonts::guess_from_postscript; +mod build; +mod edit; +mod import; + +#[cfg(test)] +pub(crate) use build::font_entry; +pub use build::{MAX_TEXT_INDEX, build_engine_data, build_txt2, build_txt2_at, build_tysh, needs_txt2}; +pub(crate) use build::{font_set, paragraph_properties, style_sheet_data}; +pub use edit::{set_text_index, text_index, txt2_object_count}; +#[cfg(test)] +use import::MAX_ENGINE_RUNS; +pub use import::{ + OPENTYPE_KEYS, TXT2_FEATURES, TXT2_STYLISTIC_SETS, apply_txt2, apply_txt2_frame, apply_txt2_path, parse_txt2, refine_legacy_point_origin, + text_layer_from_tysh, +}; +pub(crate) use import::{arr_f, char_style, para_style, postscript_for, utf16_to_byte_lengths}; + /// Parsed `TySh` contents. #[derive(Clone, Debug, PartialEq)] pub struct TySh { @@ -141,1813 +158,6 @@ pub fn engine_text_is_blank(tysh: &[u8]) -> bool { .unwrap_or(false) } -/// Parses the document's `Txt2` block (Photoshop's text engine data for all type layers). -pub fn parse_txt2(data: &[u8]) -> Option { - // Txt2 is a bare sequence of `/key value` pairs (no enclosing `<< >>`). - let mut wrapped = Vec::with_capacity(data.len() + 4); - wrapped.extend_from_slice(b"<<"); - wrapped.extend_from_slice(data); - wrapped.extend_from_slice(b">>"); - ed::parse(&wrapped).ok().filter(|v| matches!(v, E::Dict(_))) -} - -/// Applies what Photoshop keeps only in `Txt2` to `layer`, read from `tysh`: the automatic -/// kerning modes (EngineData writes Optical and "0" alike as `AutoKerning true`) and the -/// OpenType settings besides (discretionary) ligatures: stylistic sets, contextual alternates, -/// swashes and the rest ([`TXT2_FEATURES`]), which Photoshop leaves out of EngineData. Only when -/// the layer's `TextIndex` entry still holds the layer's text (an edit elsewhere leaves `Txt2` -/// stale). -/// -/// Observed layout: `Txt2 /1` is the list of text objects; an object's `/0` is its text model -/// with `/0` the text (`\r` breaks, trailing `\r`) and `/6 /0` its style runs, each -/// `<< /0 << /0 << … /6 <